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.

279786 lines
7.5MB

  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. #define JUCE_IOS 1
  51. #else
  52. #define JUCE_MAC 1
  53. #endif
  54. #else
  55. #error "Unknown platform!"
  56. #endif
  57. #if JUCE_WINDOWS
  58. #ifdef _MSC_VER
  59. #ifdef _WIN64
  60. #define JUCE_64BIT 1
  61. #else
  62. #define JUCE_32BIT 1
  63. #endif
  64. #endif
  65. #ifdef _DEBUG
  66. #define JUCE_DEBUG 1
  67. #endif
  68. #ifdef __MINGW32__
  69. #define JUCE_MINGW 1
  70. #endif
  71. /** If defined, this indicates that the processor is little-endian. */
  72. #define JUCE_LITTLE_ENDIAN 1
  73. #define JUCE_INTEL 1
  74. #endif
  75. #if JUCE_MAC
  76. #ifndef NDEBUG
  77. #define JUCE_DEBUG 1
  78. #endif
  79. #ifdef __LITTLE_ENDIAN__
  80. #define JUCE_LITTLE_ENDIAN 1
  81. #else
  82. #define JUCE_BIG_ENDIAN 1
  83. #endif
  84. #if defined (__ppc__) || defined (__ppc64__)
  85. #define JUCE_PPC 1
  86. #else
  87. #define JUCE_INTEL 1
  88. #endif
  89. #ifdef __LP64__
  90. #define JUCE_64BIT 1
  91. #else
  92. #define JUCE_32BIT 1
  93. #endif
  94. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_4
  95. #error "Building for OSX 10.3 is no longer supported!"
  96. #endif
  97. #ifndef MAC_OS_X_VERSION_10_5
  98. #error "To build with 10.4 compatibility, use a 10.5 or 10.6 SDK and set the deployment target to 10.4"
  99. #endif
  100. #endif
  101. #if JUCE_IOS
  102. #ifndef NDEBUG
  103. #define JUCE_DEBUG 1
  104. #endif
  105. #ifdef __LITTLE_ENDIAN__
  106. #define JUCE_LITTLE_ENDIAN 1
  107. #else
  108. #define JUCE_BIG_ENDIAN 1
  109. #endif
  110. #endif
  111. #if JUCE_LINUX
  112. #ifdef _DEBUG
  113. #define JUCE_DEBUG 1
  114. #endif
  115. // Allow override for big-endian Linux platforms
  116. #ifndef JUCE_BIG_ENDIAN
  117. #define JUCE_LITTLE_ENDIAN 1
  118. #endif
  119. #if defined (__LP64__) || defined (_LP64)
  120. #define JUCE_64BIT 1
  121. #else
  122. #define JUCE_32BIT 1
  123. #endif
  124. #define JUCE_INTEL 1
  125. #endif
  126. // Compiler type macros.
  127. #ifdef __GNUC__
  128. #define JUCE_GCC 1
  129. #elif defined (_MSC_VER)
  130. #define JUCE_MSVC 1
  131. #if _MSC_VER >= 1400
  132. #define JUCE_USE_INTRINSICS 1
  133. #endif
  134. #else
  135. #error unknown compiler
  136. #endif
  137. #endif // __JUCE_TARGETPLATFORM_JUCEHEADER__
  138. /*** End of inlined file: juce_TargetPlatform.h ***/
  139. // FORCE_AMALGAMATOR_INCLUDE
  140. /*** Start of inlined file: juce_Config.h ***/
  141. #ifndef __JUCE_CONFIG_JUCEHEADER__
  142. #define __JUCE_CONFIG_JUCEHEADER__
  143. /*
  144. This file contains macros that enable/disable various JUCE features.
  145. */
  146. /** The name of the namespace that all Juce classes and functions will be
  147. put inside. If this is not defined, no namespace will be used.
  148. */
  149. #ifndef JUCE_NAMESPACE
  150. #define JUCE_NAMESPACE juce
  151. #endif
  152. /** JUCE_FORCE_DEBUG: Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and
  153. project settings, but if you define this value, you can override this to force
  154. it to be true or false.
  155. */
  156. #ifndef JUCE_FORCE_DEBUG
  157. //#define JUCE_FORCE_DEBUG 0
  158. #endif
  159. /** JUCE_LOG_ASSERTIONS: If this flag is enabled, the the jassert and jassertfalse
  160. macros will always use Logger::writeToLog() to write a message when an assertion happens.
  161. Enabling it will also leave this turned on in release builds. When it's disabled,
  162. however, the jassert and jassertfalse macros will not be compiled in a
  163. release build.
  164. @see jassert, jassertfalse, Logger
  165. */
  166. #ifndef JUCE_LOG_ASSERTIONS
  167. #define JUCE_LOG_ASSERTIONS 0
  168. #endif
  169. /** JUCE_ASIO: Enables ASIO audio devices (MS Windows only).
  170. Turning this on means that you'll need to have the Steinberg ASIO SDK installed
  171. on your Windows build machine.
  172. See the comments in the ASIOAudioIODevice class's header file for more
  173. info about this.
  174. */
  175. #ifndef JUCE_ASIO
  176. #define JUCE_ASIO 0
  177. #endif
  178. /** JUCE_WASAPI: Enables WASAPI audio devices (Windows Vista and above).
  179. */
  180. #ifndef JUCE_WASAPI
  181. #define JUCE_WASAPI 0
  182. #endif
  183. /** JUCE_DIRECTSOUND: Enables DirectSound audio (MS Windows only).
  184. */
  185. #ifndef JUCE_DIRECTSOUND
  186. #define JUCE_DIRECTSOUND 1
  187. #endif
  188. /** JUCE_ALSA: Enables ALSA audio devices (Linux only). */
  189. #ifndef JUCE_ALSA
  190. #define JUCE_ALSA 1
  191. #endif
  192. /** JUCE_JACK: Enables JACK audio devices (Linux only). */
  193. #ifndef JUCE_JACK
  194. #define JUCE_JACK 0
  195. #endif
  196. /** JUCE_QUICKTIME: Enables the QuickTimeMovieComponent class (Mac and Windows).
  197. If you're building on Windows, you'll need to have the Apple QuickTime SDK
  198. installed, and its header files will need to be on your include path.
  199. */
  200. #if ! (defined (JUCE_QUICKTIME) || JUCE_LINUX || JUCE_IOS || (JUCE_WINDOWS && ! JUCE_MSVC))
  201. #define JUCE_QUICKTIME 0
  202. #endif
  203. #if (JUCE_IOS || JUCE_LINUX) && JUCE_QUICKTIME
  204. #undef JUCE_QUICKTIME
  205. #endif
  206. /** JUCE_OPENGL: Enables the OpenGLComponent class (available on all platforms).
  207. If you're not using OpenGL, you might want to turn this off to reduce your binary's size.
  208. */
  209. #ifndef JUCE_OPENGL
  210. #define JUCE_OPENGL 1
  211. #endif
  212. /** JUCE_DIRECT2D: Enables the Windows 7 Direct2D renderer.
  213. If you're building on a platform older than Vista, you won't be able to compile with this feature.
  214. */
  215. #ifndef JUCE_DIRECT2D
  216. #define JUCE_DIRECT2D 0
  217. #endif
  218. /** JUCE_USE_FLAC: Enables the FLAC audio codec classes (available on all platforms).
  219. If your app doesn't need to read FLAC files, you might want to disable this to
  220. reduce the size of your codebase and build time.
  221. */
  222. #ifndef JUCE_USE_FLAC
  223. #define JUCE_USE_FLAC 1
  224. #endif
  225. /** JUCE_USE_OGGVORBIS: Enables the Ogg-Vorbis audio codec classes (available on all platforms).
  226. If your app doesn't need to read Ogg-Vorbis files, you might want to disable this to
  227. reduce the size of your codebase and build time.
  228. */
  229. #ifndef JUCE_USE_OGGVORBIS
  230. #define JUCE_USE_OGGVORBIS 1
  231. #endif
  232. /** JUCE_USE_CDBURNER: Enables the audio CD reader code (Mac and Windows only).
  233. Unless you're using CD-burning, you should probably turn this flag off to
  234. reduce code size.
  235. */
  236. #if (! defined (JUCE_USE_CDBURNER)) && ! (JUCE_WINDOWS && ! JUCE_MSVC)
  237. #define JUCE_USE_CDBURNER 1
  238. #endif
  239. /** JUCE_USE_CDREADER: Enables the audio CD reader code (Mac and Windows only).
  240. Unless you're using CD-reading, you should probably turn this flag off to
  241. reduce code size.
  242. */
  243. #ifndef JUCE_USE_CDREADER
  244. #define JUCE_USE_CDREADER 1
  245. #endif
  246. /** JUCE_USE_CAMERA: Enables web-cam support using the CameraDevice class (Mac and Windows).
  247. */
  248. #if (JUCE_QUICKTIME || JUCE_WINDOWS) && ! defined (JUCE_USE_CAMERA)
  249. #define JUCE_USE_CAMERA 0
  250. #endif
  251. /** JUCE_ENABLE_REPAINT_DEBUGGING: If this option is turned on, each area of the screen that
  252. gets repainted will flash in a random colour, so that you can check exactly how much and how
  253. often your components are being drawn.
  254. */
  255. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  256. #define JUCE_ENABLE_REPAINT_DEBUGGING 0
  257. #endif
  258. /** JUCE_USE_XINERAMA: Enables Xinerama multi-monitor support (Linux only).
  259. Unless you specifically want to disable this, it's best to leave this option turned on.
  260. */
  261. #ifndef JUCE_USE_XINERAMA
  262. #define JUCE_USE_XINERAMA 1
  263. #endif
  264. /** JUCE_USE_XSHM: Enables X shared memory for faster rendering on Linux. This is best left
  265. turned on unless you have a good reason to disable it.
  266. */
  267. #ifndef JUCE_USE_XSHM
  268. #define JUCE_USE_XSHM 1
  269. #endif
  270. /** JUCE_USE_XRENDER: Uses XRender to allow semi-transparent windowing on Linux.
  271. */
  272. #ifndef JUCE_USE_XRENDER
  273. #define JUCE_USE_XRENDER 0
  274. #endif
  275. /** JUCE_USE_XCURSOR: Uses XCursor to allow ARGB cursor on Linux. This is best left turned on
  276. unless you have a good reason to disable it.
  277. */
  278. #ifndef JUCE_USE_XCURSOR
  279. #define JUCE_USE_XCURSOR 1
  280. #endif
  281. /** JUCE_PLUGINHOST_VST: Enables the VST audio plugin hosting classes. This requires the
  282. Steinberg VST SDK to be installed on your machine, and should be left turned off unless
  283. you're building a plugin hosting app.
  284. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  285. */
  286. #ifndef JUCE_PLUGINHOST_VST
  287. #define JUCE_PLUGINHOST_VST 0
  288. #endif
  289. /** JUCE_PLUGINHOST_AU: Enables the AudioUnit plugin hosting classes. This is Mac-only,
  290. of course, and should only be enabled if you're building a plugin hosting app.
  291. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  292. */
  293. #ifndef JUCE_PLUGINHOST_AU
  294. #define JUCE_PLUGINHOST_AU 0
  295. #endif
  296. /** JUCE_ONLY_BUILD_CORE_LIBRARY: Enabling this will avoid including any UI classes in the build.
  297. This should be enabled if you're writing a console application.
  298. */
  299. #ifndef JUCE_ONLY_BUILD_CORE_LIBRARY
  300. #define JUCE_ONLY_BUILD_CORE_LIBRARY 0
  301. #endif
  302. /** JUCE_WEB_BROWSER: This lets you disable the WebBrowserComponent class (Mac and Windows).
  303. If you're not using any embedded web-pages, turning this off may reduce your code size.
  304. */
  305. #ifndef JUCE_WEB_BROWSER
  306. #define JUCE_WEB_BROWSER 1
  307. #endif
  308. /** JUCE_SUPPORT_CARBON: Enabling this allows the Mac code to use old Carbon library functions.
  309. Carbon isn't required for a normal app, but may be needed by specialised classes like
  310. plugin-hosts, which support older APIs.
  311. */
  312. #if ! (defined (JUCE_SUPPORT_CARBON) || defined (__LP64__))
  313. #define JUCE_SUPPORT_CARBON 1
  314. #endif
  315. /* JUCE_INCLUDE_ZLIB_CODE: Can be used to disable Juce's embedded 3rd-party zlib code.
  316. You might need to tweak this if you're linking to an external zlib library in your app,
  317. but for normal apps, this option should be left alone.
  318. */
  319. #ifndef JUCE_INCLUDE_ZLIB_CODE
  320. #define JUCE_INCLUDE_ZLIB_CODE 1
  321. #endif
  322. #ifndef JUCE_INCLUDE_FLAC_CODE
  323. #define JUCE_INCLUDE_FLAC_CODE 1
  324. #endif
  325. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  326. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  327. #endif
  328. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  329. #define JUCE_INCLUDE_PNGLIB_CODE 1
  330. #endif
  331. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  332. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  333. #endif
  334. /** JUCE_CHECK_MEMORY_LEAKS: Enables a memory-leak check when an app terminates.
  335. (Currently, this only affects Windows builds in debug mode).
  336. */
  337. #ifndef JUCE_CHECK_MEMORY_LEAKS
  338. #define JUCE_CHECK_MEMORY_LEAKS 1
  339. #endif
  340. /** JUCE_CATCH_UNHANDLED_EXCEPTIONS: Turn on juce's internal catching of exceptions
  341. that are thrown by the message dispatch loop. With it enabled, any unhandled exceptions
  342. are passed to the JUCEApplication::unhandledException() callback for logging.
  343. */
  344. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  345. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  346. #endif
  347. // If only building the core classes, we can explicitly turn off some features to avoid including them:
  348. #if JUCE_ONLY_BUILD_CORE_LIBRARY
  349. #undef JUCE_QUICKTIME
  350. #define JUCE_QUICKTIME 0
  351. #undef JUCE_OPENGL
  352. #define JUCE_OPENGL 0
  353. #undef JUCE_USE_CDBURNER
  354. #define JUCE_USE_CDBURNER 0
  355. #undef JUCE_USE_CDREADER
  356. #define JUCE_USE_CDREADER 0
  357. #undef JUCE_WEB_BROWSER
  358. #define JUCE_WEB_BROWSER 0
  359. #undef JUCE_PLUGINHOST_AU
  360. #define JUCE_PLUGINHOST_AU 0
  361. #undef JUCE_PLUGINHOST_VST
  362. #define JUCE_PLUGINHOST_VST 0
  363. #endif
  364. #endif
  365. /*** End of inlined file: juce_Config.h ***/
  366. // FORCE_AMALGAMATOR_INCLUDE
  367. #ifndef JUCE_BUILD_CORE
  368. #define JUCE_BUILD_CORE 1
  369. #endif
  370. #ifndef JUCE_BUILD_MISC
  371. #define JUCE_BUILD_MISC 1
  372. #endif
  373. #ifndef JUCE_BUILD_GUI
  374. #define JUCE_BUILD_GUI 1
  375. #endif
  376. #ifndef JUCE_BUILD_NATIVE
  377. #define JUCE_BUILD_NATIVE 1
  378. #endif
  379. #if JUCE_ONLY_BUILD_CORE_LIBRARY
  380. #undef JUCE_BUILD_MISC
  381. #undef JUCE_BUILD_GUI
  382. #endif
  383. //==============================================================================
  384. #if JUCE_BUILD_NATIVE || JUCE_BUILD_CORE || (JUCE_BUILD_MISC && (JUCE_PLUGINHOST_VST || JUCE_PLUGINHOST_AU))
  385. #if JUCE_WINDOWS
  386. /*** Start of inlined file: juce_win32_NativeIncludes.h ***/
  387. #ifndef __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  388. #define __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  389. #ifndef STRICT
  390. #define STRICT 1
  391. #endif
  392. #undef WIN32_LEAN_AND_MEAN
  393. #define WIN32_LEAN_AND_MEAN 1
  394. #if JUCE_MSVC
  395. #pragma warning (push)
  396. #pragma warning (disable : 4100 4201 4514 4312 4995)
  397. #endif
  398. #define _WIN32_WINNT 0x0500
  399. #define _UNICODE 1
  400. #define UNICODE 1
  401. #ifndef _WIN32_IE
  402. #define _WIN32_IE 0x0400
  403. #endif
  404. #include <windows.h>
  405. #include <windowsx.h>
  406. #include <commdlg.h>
  407. #include <shellapi.h>
  408. #include <mmsystem.h>
  409. #include <vfw.h>
  410. #include <tchar.h>
  411. #include <stddef.h>
  412. #include <ctime>
  413. #include <wininet.h>
  414. #include <nb30.h>
  415. #include <iphlpapi.h>
  416. #include <mapi.h>
  417. #include <float.h>
  418. #include <process.h>
  419. #include <Exdisp.h>
  420. #include <exdispid.h>
  421. #include <shlobj.h>
  422. #if ! JUCE_MINGW
  423. #include <crtdbg.h>
  424. #include <comutil.h>
  425. #endif
  426. #if JUCE_OPENGL
  427. #include <gl/gl.h>
  428. #endif
  429. #undef PACKED
  430. #if JUCE_ASIO
  431. /*
  432. This is very frustrating - we only need to use a handful of definitions from
  433. a couple of the header files in Steinberg's ASIO SDK, and it'd be easy to copy
  434. about 30 lines of code into this cpp file to create a fully stand-alone ASIO
  435. implementation...
  436. ..unfortunately that would break Steinberg's license agreement for use of
  437. their SDK, so I'm not allowed to do this.
  438. This means that anyone who wants to use JUCE's ASIO abilities will have to:
  439. 1) Agree to Steinberg's licensing terms and download the ASIO SDK
  440. (see www.steinberg.net/Steinberg/Developers.asp).
  441. 2) Rebuild the whole of JUCE, setting the global definition JUCE_ASIO (you
  442. can un-comment the "#define JUCE_ASIO" line in juce_Config.h
  443. if you prefer). Make sure that your header search path will find the
  444. iasiodrv.h file that comes with the SDK. (Only about 2-3 of the SDK header
  445. files are actually needed - so to simplify things, you could just copy
  446. these into your JUCE directory).
  447. If you're compiling and you get an error here because you don't have the
  448. ASIO SDK installed, you can disable ASIO support by commenting-out the
  449. "#define JUCE_ASIO" line in juce_Config.h, and rebuild your Juce library.
  450. */
  451. #include "iasiodrv.h"
  452. #endif
  453. #if JUCE_USE_CDBURNER
  454. /* You'll need the Platform SDK for these headers - if you don't have it and don't
  455. need to use CD-burning, then you might just want to disable the JUCE_USE_CDBURNER
  456. flag in juce_Config.h to avoid these includes.
  457. */
  458. #include <imapi.h>
  459. #include <imapierror.h>
  460. #endif
  461. #if JUCE_USE_CAMERA
  462. /* If you're using the camera classes, you'll need access to a few DirectShow headers.
  463. These files are provided in the normal Windows SDK, but some Microsoft plonker
  464. didn't realise that qedit.h doesn't actually compile without the rest of the DirectShow SDK..
  465. Microsoft's suggested fix for this is to hack their qedit.h file! See:
  466. http://social.msdn.microsoft.com/Forums/en-US/windowssdk/thread/ed097d2c-3d68-4f48-8448-277eaaf68252
  467. .. which is a bit of a bodge, but a lot less hassle than installing the full DShow SDK.
  468. An alternative workaround is to create a dummy dxtrans.h file and put it in your include path.
  469. The dummy file just needs to contain the following content:
  470. #define __IDxtCompositor_INTERFACE_DEFINED__
  471. #define __IDxtAlphaSetter_INTERFACE_DEFINED__
  472. #define __IDxtJpeg_INTERFACE_DEFINED__
  473. #define __IDxtKey_INTERFACE_DEFINED__
  474. ..and that should be enough to convince qedit.h that you have the SDK!
  475. */
  476. #include <dshow.h>
  477. #include <qedit.h>
  478. #include <dshowasf.h>
  479. #endif
  480. #if JUCE_WASAPI
  481. #include <MMReg.h>
  482. #include <mmdeviceapi.h>
  483. #include <Audioclient.h>
  484. #include <Avrt.h>
  485. #include <functiondiscoverykeys.h>
  486. #endif
  487. #if JUCE_QUICKTIME
  488. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  489. add its header directory to your include path.
  490. Alternatively, if you don't need any QuickTime services, just turn off the JUCE_QUICKTIME
  491. flag in juce_Config.h
  492. */
  493. #include <Movies.h>
  494. #include <QTML.h>
  495. #include <QuickTimeComponents.h>
  496. #include <MediaHandlers.h>
  497. #include <ImageCodec.h>
  498. /* If you've got QuickTime 7 installed, then these COM objects should be found in
  499. the "\Program Files\Quicktime" directory. You'll need to add this directory to
  500. your include search path to make these import statements work.
  501. */
  502. #import <QTOLibrary.dll>
  503. #import <QTOControl.dll>
  504. #endif
  505. #if JUCE_MSVC
  506. #pragma warning (pop)
  507. #endif
  508. #if JUCE_DIRECT2D
  509. #include <d2d1.h>
  510. #include <dwrite.h>
  511. #endif
  512. /** A simple COM smart pointer.
  513. Avoids having to include ATL just to get one of these.
  514. */
  515. template <class ComClass>
  516. class ComSmartPtr
  517. {
  518. public:
  519. ComSmartPtr() throw() : p (0) {}
  520. ComSmartPtr (ComClass* const p_) : p (p_) { if (p_ != 0) p_->AddRef(); }
  521. ComSmartPtr (const ComSmartPtr<ComClass>& p_) : p (p_.p) { if (p != 0) p->AddRef(); }
  522. ~ComSmartPtr() { release(); }
  523. operator ComClass*() const throw() { return p; }
  524. ComClass& operator*() const throw() { return *p; }
  525. ComClass* operator->() const throw() { return p; }
  526. ComSmartPtr& operator= (ComClass* const newP)
  527. {
  528. if (newP != 0) newP->AddRef();
  529. release();
  530. p = newP;
  531. return *this;
  532. }
  533. ComSmartPtr& operator= (const ComSmartPtr<ComClass>& newP) { return operator= (newP.p); }
  534. // Releases and nullifies this pointer and returns its address
  535. ComClass** resetAndGetPointerAddress()
  536. {
  537. release();
  538. p = 0;
  539. return &p;
  540. }
  541. HRESULT CoCreateInstance (REFCLSID classUUID, DWORD dwClsContext = CLSCTX_INPROC_SERVER)
  542. {
  543. #ifndef __MINGW32__
  544. return ::CoCreateInstance (classUUID, 0, dwClsContext, __uuidof (ComClass), (void**) resetAndGetPointerAddress());
  545. #else
  546. return E_NOTIMPL;
  547. #endif
  548. }
  549. template <class OtherComClass>
  550. HRESULT QueryInterface (REFCLSID classUUID, ComSmartPtr<OtherComClass>& destObject) const
  551. {
  552. if (p == 0)
  553. return E_POINTER;
  554. return p->QueryInterface (classUUID, (void**) destObject.resetAndGetPointerAddress());
  555. }
  556. private:
  557. ComClass* p;
  558. void release() { if (p != 0) p->Release(); }
  559. ComClass** operator&() throw(); // private to avoid it being used accidentally
  560. };
  561. /** Handy base class for writing COM objects, providing ref-counting and a basic QueryInterface method.
  562. */
  563. template <class ComClass>
  564. class ComBaseClassHelper : public ComClass
  565. {
  566. public:
  567. ComBaseClassHelper() : refCount (1) {}
  568. virtual ~ComBaseClassHelper() {}
  569. HRESULT __stdcall QueryInterface (REFIID refId, void** result)
  570. {
  571. #ifndef __MINGW32__
  572. if (refId == __uuidof (ComClass)) { AddRef(); *result = dynamic_cast <ComClass*> (this); return S_OK; }
  573. #endif
  574. if (refId == IID_IUnknown) { AddRef(); *result = dynamic_cast <IUnknown*> (this); return S_OK; }
  575. *result = 0;
  576. return E_NOINTERFACE;
  577. }
  578. ULONG __stdcall AddRef() { return ++refCount; }
  579. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  580. protected:
  581. int refCount;
  582. };
  583. #endif // __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  584. /*** End of inlined file: juce_win32_NativeIncludes.h ***/
  585. #elif JUCE_LINUX
  586. /*** Start of inlined file: juce_linux_NativeIncludes.h ***/
  587. #ifndef __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  588. #define __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  589. /*
  590. This file wraps together all the linux-specific headers, so
  591. that we can include them all just once, and compile all our
  592. platform-specific stuff in one big lump, keeping it out of the
  593. way of the rest of the codebase.
  594. */
  595. #include <sched.h>
  596. #include <pthread.h>
  597. #include <sys/time.h>
  598. #include <errno.h>
  599. #include <sys/stat.h>
  600. #include <sys/dir.h>
  601. #include <sys/ptrace.h>
  602. #include <sys/vfs.h>
  603. #include <sys/wait.h>
  604. #include <fnmatch.h>
  605. #include <utime.h>
  606. #include <pwd.h>
  607. #include <fcntl.h>
  608. #include <dlfcn.h>
  609. #include <netdb.h>
  610. #include <arpa/inet.h>
  611. #include <netinet/in.h>
  612. #include <sys/types.h>
  613. #include <sys/ioctl.h>
  614. #include <sys/socket.h>
  615. #include <net/if.h>
  616. #include <sys/sysinfo.h>
  617. #include <sys/file.h>
  618. #include <signal.h>
  619. /* Got a build error here? You'll need to install the freetype library...
  620. The name of the package to install is "libfreetype6-dev".
  621. */
  622. #include <ft2build.h>
  623. #include FT_FREETYPE_H
  624. #include <X11/Xlib.h>
  625. #include <X11/Xatom.h>
  626. #include <X11/Xresource.h>
  627. #include <X11/Xutil.h>
  628. #include <X11/Xmd.h>
  629. #include <X11/keysym.h>
  630. #include <X11/cursorfont.h>
  631. #if JUCE_USE_XINERAMA
  632. /* If you're trying to use Xinerama, you'll need to install the "libxinerama-dev" package.. */
  633. #include <X11/extensions/Xinerama.h>
  634. #endif
  635. #if JUCE_USE_XSHM
  636. #include <X11/extensions/XShm.h>
  637. #include <sys/shm.h>
  638. #include <sys/ipc.h>
  639. #endif
  640. #if JUCE_USE_XRENDER
  641. // If you're missing these headers, try installing the libxrender-dev and libxcomposite-dev
  642. #include <X11/extensions/Xrender.h>
  643. #include <X11/extensions/Xcomposite.h>
  644. #endif
  645. #if JUCE_USE_XCURSOR
  646. // If you're missing this header, try installing the libxcursor-dev package
  647. #include <X11/Xcursor/Xcursor.h>
  648. #endif
  649. #if JUCE_OPENGL
  650. /* Got an include error here?
  651. If you want to install OpenGL support, the packages to get are "mesa-common-dev"
  652. and "freeglut3-dev".
  653. Alternatively, you can turn off the JUCE_OPENGL flag in juce_Config.h if you
  654. want to disable it.
  655. */
  656. #include <GL/glx.h>
  657. #endif
  658. #undef KeyPress
  659. #if JUCE_ALSA
  660. /* Got an include error here? If so, you've either not got ALSA installed, or you've
  661. not got your paths set up correctly to find its header files.
  662. The package you need to install to get ASLA support is "libasound2-dev".
  663. If you don't have the ALSA library and don't want to build Juce with audio support,
  664. just disable the JUCE_ALSA flag in juce_Config.h
  665. */
  666. #include <alsa/asoundlib.h>
  667. #endif
  668. #if JUCE_JACK
  669. /* Got an include error here? If so, you've either not got jack-audio-connection-kit
  670. installed, or you've not got your paths set up correctly to find its header files.
  671. The package you need to install to get JACK support is "libjack-dev".
  672. If you don't have the jack-audio-connection-kit library and don't want to build
  673. Juce with low latency audio support, just disable the JUCE_JACK flag in juce_Config.h
  674. */
  675. #include <jack/jack.h>
  676. //#include <jack/transport.h>
  677. #endif
  678. #undef SIZEOF
  679. #endif // __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  680. /*** End of inlined file: juce_linux_NativeIncludes.h ***/
  681. #elif JUCE_MAC || JUCE_IPHONE
  682. /*** Start of inlined file: juce_mac_NativeIncludes.h ***/
  683. #ifndef __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  684. #define __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  685. /*
  686. This file wraps together all the mac-specific code, so that
  687. we can include all the native headers just once, and compile all our
  688. platform-specific stuff in one big lump, keeping it out of the way of
  689. the rest of the codebase.
  690. */
  691. #define USE_COREGRAPHICS_RENDERING 1
  692. #if JUCE_IOS
  693. #import <Foundation/Foundation.h>
  694. #import <UIKit/UIKit.h>
  695. #import <AudioToolbox/AudioToolbox.h>
  696. #import <AVFoundation/AVFoundation.h>
  697. #import <CoreData/CoreData.h>
  698. #import <MobileCoreServices/MobileCoreServices.h>
  699. #import <QuartzCore/QuartzCore.h>
  700. #include <sys/fcntl.h>
  701. #if JUCE_OPENGL
  702. #include <OpenGLES/ES1/gl.h>
  703. #include <OpenGLES/ES1/glext.h>
  704. #endif
  705. #else
  706. #import <Cocoa/Cocoa.h>
  707. #import <CoreAudio/HostTime.h>
  708. #import <CoreAudio/AudioHardware.h>
  709. #import <CoreMIDI/MIDIServices.h>
  710. #import <QTKit/QTKit.h>
  711. #import <WebKit/WebKit.h>
  712. #import <DiscRecording/DiscRecording.h>
  713. #import <IOKit/IOKitLib.h>
  714. #import <IOKit/IOCFPlugIn.h>
  715. #import <IOKit/hid/IOHIDLib.h>
  716. #import <IOKit/hid/IOHIDKeys.h>
  717. #import <IOKit/pwr_mgt/IOPMLib.h>
  718. #include <Carbon/Carbon.h>
  719. #include <sys/dir.h>
  720. #endif
  721. #include <sys/socket.h>
  722. #include <sys/sysctl.h>
  723. #include <sys/stat.h>
  724. #include <sys/param.h>
  725. #include <sys/mount.h>
  726. #include <fnmatch.h>
  727. #include <utime.h>
  728. #include <dlfcn.h>
  729. #include <ifaddrs.h>
  730. #include <net/if_dl.h>
  731. #include <mach/mach_time.h>
  732. #include <mach-o/dyld.h>
  733. #if MACOS_10_4_OR_EARLIER
  734. #include <GLUT/glut.h>
  735. #endif
  736. #if ! CGFLOAT_DEFINED
  737. #define CGFloat float
  738. #endif
  739. #endif // __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  740. /*** End of inlined file: juce_mac_NativeIncludes.h ***/
  741. #else
  742. #error "Unknown platform!"
  743. #endif
  744. #endif
  745. //==============================================================================
  746. #define DONT_SET_USING_JUCE_NAMESPACE 1
  747. #undef max
  748. #undef min
  749. #define NO_DUMMY_DECL
  750. #if JUCE_BUILD_NATIVE
  751. #include "juce_amalgamated.h" // FORCE_AMALGAMATOR_INCLUDE
  752. #endif
  753. #if (defined(_MSC_VER) && (_MSC_VER <= 1200))
  754. #pragma warning (disable: 4309 4305)
  755. #endif
  756. #if JUCE_MAC && JUCE_32BIT && JUCE_SUPPORT_CARBON && JUCE_BUILD_NATIVE && ! JUCE_ONLY_BUILD_CORE_LIBRARY
  757. BEGIN_JUCE_NAMESPACE
  758. /*** Start of inlined file: juce_mac_CarbonViewWrapperComponent.h ***/
  759. #ifndef __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  760. #define __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  761. /**
  762. Creates a floating carbon window that can be used to hold a carbon UI.
  763. This is a handy class that's designed to be inlined where needed, e.g.
  764. in the audio plugin hosting code.
  765. */
  766. class CarbonViewWrapperComponent : public Component,
  767. public ComponentMovementWatcher,
  768. public Timer
  769. {
  770. public:
  771. CarbonViewWrapperComponent()
  772. : ComponentMovementWatcher (this),
  773. wrapperWindow (0),
  774. carbonWindow (0),
  775. embeddedView (0),
  776. recursiveResize (false)
  777. {
  778. }
  779. virtual ~CarbonViewWrapperComponent()
  780. {
  781. jassert (embeddedView == 0); // must call deleteWindow() in the subclass's destructor!
  782. }
  783. virtual HIViewRef attachView (WindowRef windowRef, HIViewRef rootView) = 0;
  784. virtual void removeView (HIViewRef embeddedView) = 0;
  785. virtual void mouseDown (int, int) {}
  786. virtual void paint() {}
  787. virtual bool getEmbeddedViewSize (int& w, int& h)
  788. {
  789. if (embeddedView == 0)
  790. return false;
  791. HIRect bounds;
  792. HIViewGetBounds (embeddedView, &bounds);
  793. w = jmax (1, roundToInt (bounds.size.width));
  794. h = jmax (1, roundToInt (bounds.size.height));
  795. return true;
  796. }
  797. void createWindow()
  798. {
  799. if (wrapperWindow == 0)
  800. {
  801. Rect r;
  802. r.left = getScreenX();
  803. r.top = getScreenY();
  804. r.right = r.left + getWidth();
  805. r.bottom = r.top + getHeight();
  806. CreateNewWindow (kDocumentWindowClass,
  807. (WindowAttributes) (kWindowStandardHandlerAttribute | kWindowCompositingAttribute
  808. | kWindowNoShadowAttribute | kWindowNoTitleBarAttribute),
  809. &r, &wrapperWindow);
  810. jassert (wrapperWindow != 0);
  811. if (wrapperWindow == 0)
  812. return;
  813. carbonWindow = [[NSWindow alloc] initWithWindowRef: wrapperWindow];
  814. NSWindow* ownerWindow = [((NSView*) getWindowHandle()) window];
  815. [ownerWindow addChildWindow: carbonWindow
  816. ordered: NSWindowAbove];
  817. embeddedView = attachView (wrapperWindow, HIViewGetRoot (wrapperWindow));
  818. EventTypeSpec windowEventTypes[] =
  819. {
  820. { kEventClassWindow, kEventWindowGetClickActivation },
  821. { kEventClassWindow, kEventWindowHandleDeactivate },
  822. { kEventClassWindow, kEventWindowBoundsChanging },
  823. { kEventClassMouse, kEventMouseDown },
  824. { kEventClassMouse, kEventMouseMoved },
  825. { kEventClassMouse, kEventMouseDragged },
  826. { kEventClassMouse, kEventMouseUp},
  827. { kEventClassWindow, kEventWindowDrawContent },
  828. { kEventClassWindow, kEventWindowShown },
  829. { kEventClassWindow, kEventWindowHidden }
  830. };
  831. EventHandlerUPP upp = NewEventHandlerUPP (carbonEventCallback);
  832. InstallWindowEventHandler (wrapperWindow, upp,
  833. sizeof (windowEventTypes) / sizeof (EventTypeSpec),
  834. windowEventTypes, this, &eventHandlerRef);
  835. setOurSizeToEmbeddedViewSize();
  836. setEmbeddedWindowToOurSize();
  837. creationTime = Time::getCurrentTime();
  838. }
  839. }
  840. void deleteWindow()
  841. {
  842. removeView (embeddedView);
  843. embeddedView = 0;
  844. if (wrapperWindow != 0)
  845. {
  846. RemoveEventHandler (eventHandlerRef);
  847. DisposeWindow (wrapperWindow);
  848. wrapperWindow = 0;
  849. }
  850. }
  851. void setOurSizeToEmbeddedViewSize()
  852. {
  853. int w, h;
  854. if (getEmbeddedViewSize (w, h))
  855. {
  856. if (w != getWidth() || h != getHeight())
  857. {
  858. startTimer (50);
  859. setSize (w, h);
  860. if (getParentComponent() != 0)
  861. getParentComponent()->setSize (w, h);
  862. }
  863. else
  864. {
  865. startTimer (jlimit (50, 500, getTimerInterval() + 20));
  866. }
  867. }
  868. else
  869. {
  870. stopTimer();
  871. }
  872. }
  873. void setEmbeddedWindowToOurSize()
  874. {
  875. if (! recursiveResize)
  876. {
  877. recursiveResize = true;
  878. if (embeddedView != 0)
  879. {
  880. HIRect r;
  881. r.origin.x = 0;
  882. r.origin.y = 0;
  883. r.size.width = (float) getWidth();
  884. r.size.height = (float) getHeight();
  885. HIViewSetFrame (embeddedView, &r);
  886. }
  887. if (wrapperWindow != 0)
  888. {
  889. Rect wr;
  890. wr.left = getScreenX();
  891. wr.top = getScreenY();
  892. wr.right = wr.left + getWidth();
  893. wr.bottom = wr.top + getHeight();
  894. SetWindowBounds (wrapperWindow, kWindowContentRgn, &wr);
  895. ShowWindow (wrapperWindow);
  896. }
  897. recursiveResize = false;
  898. }
  899. }
  900. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  901. {
  902. setEmbeddedWindowToOurSize();
  903. }
  904. void componentPeerChanged()
  905. {
  906. deleteWindow();
  907. createWindow();
  908. }
  909. void componentVisibilityChanged (Component&)
  910. {
  911. if (isShowing())
  912. createWindow();
  913. else
  914. deleteWindow();
  915. setEmbeddedWindowToOurSize();
  916. }
  917. static void recursiveHIViewRepaint (HIViewRef view)
  918. {
  919. HIViewSetNeedsDisplay (view, true);
  920. HIViewRef child = HIViewGetFirstSubview (view);
  921. while (child != 0)
  922. {
  923. recursiveHIViewRepaint (child);
  924. child = HIViewGetNextView (child);
  925. }
  926. }
  927. void timerCallback()
  928. {
  929. setOurSizeToEmbeddedViewSize();
  930. // To avoid strange overpainting problems when the UI is first opened, we'll
  931. // repaint it a few times during the first second that it's on-screen..
  932. if ((Time::getCurrentTime() - creationTime).inMilliseconds() < 1000)
  933. recursiveHIViewRepaint (HIViewGetRoot (wrapperWindow));
  934. }
  935. OSStatus carbonEventHandler (EventHandlerCallRef /*nextHandlerRef*/, EventRef event)
  936. {
  937. switch (GetEventKind (event))
  938. {
  939. case kEventWindowHandleDeactivate:
  940. ActivateWindow (wrapperWindow, TRUE);
  941. return noErr;
  942. case kEventWindowGetClickActivation:
  943. {
  944. getTopLevelComponent()->toFront (false);
  945. [carbonWindow makeKeyAndOrderFront: nil];
  946. ClickActivationResult howToHandleClick = kActivateAndHandleClick;
  947. SetEventParameter (event, kEventParamClickActivation, typeClickActivationResult,
  948. sizeof (ClickActivationResult), &howToHandleClick);
  949. HIViewSetNeedsDisplay (embeddedView, true);
  950. return noErr;
  951. }
  952. }
  953. return eventNotHandledErr;
  954. }
  955. static pascal OSStatus carbonEventCallback (EventHandlerCallRef nextHandlerRef, EventRef event, void* userData)
  956. {
  957. return ((CarbonViewWrapperComponent*) userData)->carbonEventHandler (nextHandlerRef, event);
  958. }
  959. protected:
  960. WindowRef wrapperWindow;
  961. NSWindow* carbonWindow;
  962. HIViewRef embeddedView;
  963. bool recursiveResize;
  964. Time creationTime;
  965. EventHandlerRef eventHandlerRef;
  966. };
  967. #endif // __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  968. /*** End of inlined file: juce_mac_CarbonViewWrapperComponent.h ***/
  969. END_JUCE_NAMESPACE
  970. #endif
  971. #define JUCE_AMALGAMATED_TEMPLATE 1
  972. //==============================================================================
  973. #if JUCE_BUILD_CORE
  974. /*** Start of inlined file: juce_FileLogger.cpp ***/
  975. BEGIN_JUCE_NAMESPACE
  976. FileLogger::FileLogger (const File& logFile_,
  977. const String& welcomeMessage,
  978. const int maxInitialFileSizeBytes)
  979. : logFile (logFile_)
  980. {
  981. if (maxInitialFileSizeBytes >= 0)
  982. trimFileSize (maxInitialFileSizeBytes);
  983. if (! logFile_.exists())
  984. {
  985. // do this so that the parent directories get created..
  986. logFile_.create();
  987. }
  988. String welcome;
  989. welcome << "\r\n**********************************************************\r\n"
  990. << welcomeMessage
  991. << "\r\nLog started: " << Time::getCurrentTime().toString (true, true)
  992. << "\r\n";
  993. logMessage (welcome);
  994. }
  995. FileLogger::~FileLogger()
  996. {
  997. }
  998. void FileLogger::logMessage (const String& message)
  999. {
  1000. DBG (message);
  1001. const ScopedLock sl (logLock);
  1002. FileOutputStream out (logFile, 256);
  1003. out << message << "\r\n";
  1004. }
  1005. void FileLogger::trimFileSize (int maxFileSizeBytes) const
  1006. {
  1007. if (maxFileSizeBytes <= 0)
  1008. {
  1009. logFile.deleteFile();
  1010. }
  1011. else
  1012. {
  1013. const int64 fileSize = logFile.getSize();
  1014. if (fileSize > maxFileSizeBytes)
  1015. {
  1016. ScopedPointer <FileInputStream> in (logFile.createInputStream());
  1017. jassert (in != 0);
  1018. if (in != 0)
  1019. {
  1020. in->setPosition (fileSize - maxFileSizeBytes);
  1021. String content;
  1022. {
  1023. MemoryBlock contentToSave;
  1024. contentToSave.setSize (maxFileSizeBytes + 4);
  1025. contentToSave.fillWith (0);
  1026. in->read (contentToSave.getData(), maxFileSizeBytes);
  1027. in = 0;
  1028. content = contentToSave.toString();
  1029. }
  1030. int newStart = 0;
  1031. while (newStart < fileSize
  1032. && content[newStart] != '\n'
  1033. && content[newStart] != '\r')
  1034. ++newStart;
  1035. logFile.deleteFile();
  1036. logFile.appendText (content.substring (newStart), false, false);
  1037. }
  1038. }
  1039. }
  1040. }
  1041. FileLogger* FileLogger::createDefaultAppLogger (const String& logFileSubDirectoryName,
  1042. const String& logFileName,
  1043. const String& welcomeMessage,
  1044. const int maxInitialFileSizeBytes)
  1045. {
  1046. #if JUCE_MAC
  1047. File logFile ("~/Library/Logs");
  1048. logFile = logFile.getChildFile (logFileSubDirectoryName)
  1049. .getChildFile (logFileName);
  1050. #else
  1051. File logFile (File::getSpecialLocation (File::userApplicationDataDirectory));
  1052. if (logFile.isDirectory())
  1053. {
  1054. logFile = logFile.getChildFile (logFileSubDirectoryName)
  1055. .getChildFile (logFileName);
  1056. }
  1057. #endif
  1058. return new FileLogger (logFile, welcomeMessage, maxInitialFileSizeBytes);
  1059. }
  1060. END_JUCE_NAMESPACE
  1061. /*** End of inlined file: juce_FileLogger.cpp ***/
  1062. /*** Start of inlined file: juce_Logger.cpp ***/
  1063. BEGIN_JUCE_NAMESPACE
  1064. Logger::Logger()
  1065. {
  1066. }
  1067. Logger::~Logger()
  1068. {
  1069. }
  1070. Logger* Logger::currentLogger = 0;
  1071. void Logger::setCurrentLogger (Logger* const newLogger,
  1072. const bool deleteOldLogger)
  1073. {
  1074. Logger* const oldLogger = currentLogger;
  1075. currentLogger = newLogger;
  1076. if (deleteOldLogger)
  1077. delete oldLogger;
  1078. }
  1079. void Logger::writeToLog (const String& message)
  1080. {
  1081. if (currentLogger != 0)
  1082. currentLogger->logMessage (message);
  1083. else
  1084. outputDebugString (message);
  1085. }
  1086. #if JUCE_LOG_ASSERTIONS
  1087. void JUCE_API juce_LogAssertion (const char* filename, const int lineNum) throw()
  1088. {
  1089. String m ("JUCE Assertion failure in ");
  1090. m << filename << ", line " << lineNum;
  1091. Logger::writeToLog (m);
  1092. }
  1093. #endif
  1094. END_JUCE_NAMESPACE
  1095. /*** End of inlined file: juce_Logger.cpp ***/
  1096. /*** Start of inlined file: juce_Random.cpp ***/
  1097. BEGIN_JUCE_NAMESPACE
  1098. Random::Random (const int64 seedValue) throw()
  1099. : seed (seedValue)
  1100. {
  1101. }
  1102. Random::~Random() throw()
  1103. {
  1104. }
  1105. void Random::setSeed (const int64 newSeed) throw()
  1106. {
  1107. seed = newSeed;
  1108. }
  1109. void Random::combineSeed (const int64 seedValue) throw()
  1110. {
  1111. seed ^= nextInt64() ^ seedValue;
  1112. }
  1113. void Random::setSeedRandomly()
  1114. {
  1115. combineSeed ((int64) (pointer_sized_int) this);
  1116. combineSeed (Time::getMillisecondCounter());
  1117. combineSeed (Time::getHighResolutionTicks());
  1118. combineSeed (Time::getHighResolutionTicksPerSecond());
  1119. combineSeed (Time::currentTimeMillis());
  1120. }
  1121. int Random::nextInt() throw()
  1122. {
  1123. seed = (seed * literal64bit (0x5deece66d) + 11) & literal64bit (0xffffffffffff);
  1124. return (int) (seed >> 16);
  1125. }
  1126. int Random::nextInt (const int maxValue) throw()
  1127. {
  1128. jassert (maxValue > 0);
  1129. return (nextInt() & 0x7fffffff) % maxValue;
  1130. }
  1131. int64 Random::nextInt64() throw()
  1132. {
  1133. return (((int64) nextInt()) << 32) | (int64) (uint64) (uint32) nextInt();
  1134. }
  1135. bool Random::nextBool() throw()
  1136. {
  1137. return (nextInt() & 0x80000000) != 0;
  1138. }
  1139. float Random::nextFloat() throw()
  1140. {
  1141. return static_cast <uint32> (nextInt()) / (float) 0xffffffff;
  1142. }
  1143. double Random::nextDouble() throw()
  1144. {
  1145. return static_cast <uint32> (nextInt()) / (double) 0xffffffff;
  1146. }
  1147. const BigInteger Random::nextLargeNumber (const BigInteger& maximumValue)
  1148. {
  1149. BigInteger n;
  1150. do
  1151. {
  1152. fillBitsRandomly (n, 0, maximumValue.getHighestBit() + 1);
  1153. }
  1154. while (n >= maximumValue);
  1155. return n;
  1156. }
  1157. void Random::fillBitsRandomly (BigInteger& arrayToChange, int startBit, int numBits)
  1158. {
  1159. arrayToChange.setBit (startBit + numBits - 1, true); // to force the array to pre-allocate space
  1160. while ((startBit & 31) != 0 && numBits > 0)
  1161. {
  1162. arrayToChange.setBit (startBit++, nextBool());
  1163. --numBits;
  1164. }
  1165. while (numBits >= 32)
  1166. {
  1167. arrayToChange.setBitRangeAsInt (startBit, 32, (unsigned int) nextInt());
  1168. startBit += 32;
  1169. numBits -= 32;
  1170. }
  1171. while (--numBits >= 0)
  1172. arrayToChange.setBit (startBit + numBits, nextBool());
  1173. }
  1174. Random& Random::getSystemRandom() throw()
  1175. {
  1176. static Random sysRand (1);
  1177. return sysRand;
  1178. }
  1179. END_JUCE_NAMESPACE
  1180. /*** End of inlined file: juce_Random.cpp ***/
  1181. /*** Start of inlined file: juce_RelativeTime.cpp ***/
  1182. BEGIN_JUCE_NAMESPACE
  1183. RelativeTime::RelativeTime (const double seconds_) throw()
  1184. : seconds (seconds_)
  1185. {
  1186. }
  1187. RelativeTime::RelativeTime (const RelativeTime& other) throw()
  1188. : seconds (other.seconds)
  1189. {
  1190. }
  1191. RelativeTime::~RelativeTime() throw()
  1192. {
  1193. }
  1194. const RelativeTime RelativeTime::milliseconds (const int milliseconds) throw()
  1195. {
  1196. return RelativeTime (milliseconds * 0.001);
  1197. }
  1198. const RelativeTime RelativeTime::milliseconds (const int64 milliseconds) throw()
  1199. {
  1200. return RelativeTime (milliseconds * 0.001);
  1201. }
  1202. const RelativeTime RelativeTime::minutes (const double numberOfMinutes) throw()
  1203. {
  1204. return RelativeTime (numberOfMinutes * 60.0);
  1205. }
  1206. const RelativeTime RelativeTime::hours (const double numberOfHours) throw()
  1207. {
  1208. return RelativeTime (numberOfHours * (60.0 * 60.0));
  1209. }
  1210. const RelativeTime RelativeTime::days (const double numberOfDays) throw()
  1211. {
  1212. return RelativeTime (numberOfDays * (60.0 * 60.0 * 24.0));
  1213. }
  1214. const RelativeTime RelativeTime::weeks (const double numberOfWeeks) throw()
  1215. {
  1216. return RelativeTime (numberOfWeeks * (60.0 * 60.0 * 24.0 * 7.0));
  1217. }
  1218. int64 RelativeTime::inMilliseconds() const throw()
  1219. {
  1220. return (int64) (seconds * 1000.0);
  1221. }
  1222. double RelativeTime::inMinutes() const throw()
  1223. {
  1224. return seconds / 60.0;
  1225. }
  1226. double RelativeTime::inHours() const throw()
  1227. {
  1228. return seconds / (60.0 * 60.0);
  1229. }
  1230. double RelativeTime::inDays() const throw()
  1231. {
  1232. return seconds / (60.0 * 60.0 * 24.0);
  1233. }
  1234. double RelativeTime::inWeeks() const throw()
  1235. {
  1236. return seconds / (60.0 * 60.0 * 24.0 * 7.0);
  1237. }
  1238. const String RelativeTime::getDescription (const String& returnValueForZeroTime) const
  1239. {
  1240. if (seconds < 0.001 && seconds > -0.001)
  1241. return returnValueForZeroTime;
  1242. String result;
  1243. if (seconds < 0)
  1244. result = "-";
  1245. int fieldsShown = 0;
  1246. int n = abs ((int) inWeeks());
  1247. if (n > 0)
  1248. {
  1249. result << n << ((n == 1) ? TRANS(" week ")
  1250. : TRANS(" weeks "));
  1251. ++fieldsShown;
  1252. }
  1253. n = abs ((int) inDays()) % 7;
  1254. if (n > 0)
  1255. {
  1256. result << n << ((n == 1) ? TRANS(" day ")
  1257. : TRANS(" days "));
  1258. ++fieldsShown;
  1259. }
  1260. if (fieldsShown < 2)
  1261. {
  1262. n = abs ((int) inHours()) % 24;
  1263. if (n > 0)
  1264. {
  1265. result << n << ((n == 1) ? TRANS(" hr ")
  1266. : TRANS(" hrs "));
  1267. ++fieldsShown;
  1268. }
  1269. if (fieldsShown < 2)
  1270. {
  1271. n = abs ((int) inMinutes()) % 60;
  1272. if (n > 0)
  1273. {
  1274. result << n << ((n == 1) ? TRANS(" min ")
  1275. : TRANS(" mins "));
  1276. ++fieldsShown;
  1277. }
  1278. if (fieldsShown < 2)
  1279. {
  1280. n = abs ((int) inSeconds()) % 60;
  1281. if (n > 0)
  1282. {
  1283. result << n << ((n == 1) ? TRANS(" sec ")
  1284. : TRANS(" secs "));
  1285. ++fieldsShown;
  1286. }
  1287. if (fieldsShown < 1)
  1288. {
  1289. n = abs ((int) inMilliseconds()) % 1000;
  1290. if (n > 0)
  1291. {
  1292. result << n << TRANS(" ms");
  1293. ++fieldsShown;
  1294. }
  1295. }
  1296. }
  1297. }
  1298. }
  1299. return result.trimEnd();
  1300. }
  1301. RelativeTime& RelativeTime::operator= (const RelativeTime& other) throw()
  1302. {
  1303. seconds = other.seconds;
  1304. return *this;
  1305. }
  1306. bool RelativeTime::operator== (const RelativeTime& other) const throw() { return seconds == other.seconds; }
  1307. bool RelativeTime::operator!= (const RelativeTime& other) const throw() { return seconds != other.seconds; }
  1308. bool RelativeTime::operator> (const RelativeTime& other) const throw() { return seconds > other.seconds; }
  1309. bool RelativeTime::operator< (const RelativeTime& other) const throw() { return seconds < other.seconds; }
  1310. bool RelativeTime::operator>= (const RelativeTime& other) const throw() { return seconds >= other.seconds; }
  1311. bool RelativeTime::operator<= (const RelativeTime& other) const throw() { return seconds <= other.seconds; }
  1312. const RelativeTime RelativeTime::operator+ (const RelativeTime& timeToAdd) const throw()
  1313. {
  1314. return RelativeTime (seconds + timeToAdd.seconds);
  1315. }
  1316. const RelativeTime RelativeTime::operator- (const RelativeTime& timeToSubtract) const throw()
  1317. {
  1318. return RelativeTime (seconds - timeToSubtract.seconds);
  1319. }
  1320. const RelativeTime RelativeTime::operator+ (const double secondsToAdd) const throw()
  1321. {
  1322. return RelativeTime (seconds + secondsToAdd);
  1323. }
  1324. const RelativeTime RelativeTime::operator- (const double secondsToSubtract) const throw()
  1325. {
  1326. return RelativeTime (seconds - secondsToSubtract);
  1327. }
  1328. const RelativeTime& RelativeTime::operator+= (const RelativeTime& timeToAdd) throw()
  1329. {
  1330. seconds += timeToAdd.seconds;
  1331. return *this;
  1332. }
  1333. const RelativeTime& RelativeTime::operator-= (const RelativeTime& timeToSubtract) throw()
  1334. {
  1335. seconds -= timeToSubtract.seconds;
  1336. return *this;
  1337. }
  1338. const RelativeTime& RelativeTime::operator+= (const double secondsToAdd) throw()
  1339. {
  1340. seconds += secondsToAdd;
  1341. return *this;
  1342. }
  1343. const RelativeTime& RelativeTime::operator-= (const double secondsToSubtract) throw()
  1344. {
  1345. seconds -= secondsToSubtract;
  1346. return *this;
  1347. }
  1348. END_JUCE_NAMESPACE
  1349. /*** End of inlined file: juce_RelativeTime.cpp ***/
  1350. /*** Start of inlined file: juce_SystemStats.cpp ***/
  1351. BEGIN_JUCE_NAMESPACE
  1352. SystemStats::CPUFlags SystemStats::cpuFlags;
  1353. const String SystemStats::getJUCEVersion()
  1354. {
  1355. return "JUCE v" + String (JUCE_MAJOR_VERSION)
  1356. + "." + String (JUCE_MINOR_VERSION)
  1357. + "." + String (JUCE_BUILDNUMBER);
  1358. }
  1359. #ifdef JUCE_DLL
  1360. void* juce_Malloc (const int size)
  1361. {
  1362. return malloc (size);
  1363. }
  1364. void* juce_Calloc (const int size)
  1365. {
  1366. return calloc (1, size);
  1367. }
  1368. void* juce_Realloc (void* const block, const int size)
  1369. {
  1370. return realloc (block, size);
  1371. }
  1372. void juce_Free (void* const block)
  1373. {
  1374. free (block);
  1375. }
  1376. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  1377. void* juce_DebugMalloc (const int size, const char* file, const int line)
  1378. {
  1379. return _malloc_dbg (size, _NORMAL_BLOCK, file, line);
  1380. }
  1381. void* juce_DebugCalloc (const int size, const char* file, const int line)
  1382. {
  1383. return _calloc_dbg (1, size, _NORMAL_BLOCK, file, line);
  1384. }
  1385. void* juce_DebugRealloc (void* const block, const int size, const char* file, const int line)
  1386. {
  1387. return _realloc_dbg (block, size, _NORMAL_BLOCK, file, line);
  1388. }
  1389. void juce_DebugFree (void* const block)
  1390. {
  1391. _free_dbg (block, _NORMAL_BLOCK);
  1392. }
  1393. #endif
  1394. #endif
  1395. END_JUCE_NAMESPACE
  1396. /*** End of inlined file: juce_SystemStats.cpp ***/
  1397. /*** Start of inlined file: juce_Time.cpp ***/
  1398. #if JUCE_MSVC
  1399. #pragma warning (push)
  1400. #pragma warning (disable: 4514)
  1401. #endif
  1402. #ifndef JUCE_WINDOWS
  1403. #include <sys/time.h>
  1404. #else
  1405. #include <ctime>
  1406. #endif
  1407. #include <sys/timeb.h>
  1408. #if JUCE_MSVC
  1409. #pragma warning (pop)
  1410. #ifdef _INC_TIME_INL
  1411. #define USE_NEW_SECURE_TIME_FNS
  1412. #endif
  1413. #endif
  1414. BEGIN_JUCE_NAMESPACE
  1415. namespace TimeHelpers
  1416. {
  1417. static struct tm millisToLocal (const int64 millis) throw()
  1418. {
  1419. struct tm result;
  1420. const int64 seconds = millis / 1000;
  1421. if (seconds < literal64bit (86400) || seconds >= literal64bit (2145916800))
  1422. {
  1423. // use extended maths for dates beyond 1970 to 2037..
  1424. const int timeZoneAdjustment = 31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000);
  1425. const int64 jdm = seconds + timeZoneAdjustment + literal64bit (210866803200);
  1426. const int days = (int) (jdm / literal64bit (86400));
  1427. const int a = 32044 + days;
  1428. const int b = (4 * a + 3) / 146097;
  1429. const int c = a - (b * 146097) / 4;
  1430. const int d = (4 * c + 3) / 1461;
  1431. const int e = c - (d * 1461) / 4;
  1432. const int m = (5 * e + 2) / 153;
  1433. result.tm_mday = e - (153 * m + 2) / 5 + 1;
  1434. result.tm_mon = m + 2 - 12 * (m / 10);
  1435. result.tm_year = b * 100 + d - 6700 + (m / 10);
  1436. result.tm_wday = (days + 1) % 7;
  1437. result.tm_yday = -1;
  1438. int t = (int) (jdm % literal64bit (86400));
  1439. result.tm_hour = t / 3600;
  1440. t %= 3600;
  1441. result.tm_min = t / 60;
  1442. result.tm_sec = t % 60;
  1443. result.tm_isdst = -1;
  1444. }
  1445. else
  1446. {
  1447. time_t now = static_cast <time_t> (seconds);
  1448. #if JUCE_WINDOWS
  1449. #ifdef USE_NEW_SECURE_TIME_FNS
  1450. if (now >= 0 && now <= 0x793406fff)
  1451. localtime_s (&result, &now);
  1452. else
  1453. zeromem (&result, sizeof (result));
  1454. #else
  1455. result = *localtime (&now);
  1456. #endif
  1457. #else
  1458. // more thread-safe
  1459. localtime_r (&now, &result);
  1460. #endif
  1461. }
  1462. return result;
  1463. }
  1464. static int extendedModulo (const int64 value, const int modulo) throw()
  1465. {
  1466. return (int) (value >= 0 ? (value % modulo)
  1467. : (value - ((value / modulo) + 1) * modulo));
  1468. }
  1469. static uint32 lastMSCounterValue = 0;
  1470. }
  1471. Time::Time() throw()
  1472. : millisSinceEpoch (0)
  1473. {
  1474. }
  1475. Time::Time (const Time& other) throw()
  1476. : millisSinceEpoch (other.millisSinceEpoch)
  1477. {
  1478. }
  1479. Time::Time (const int64 ms) throw()
  1480. : millisSinceEpoch (ms)
  1481. {
  1482. }
  1483. Time::Time (const int year,
  1484. const int month,
  1485. const int day,
  1486. const int hours,
  1487. const int minutes,
  1488. const int seconds,
  1489. const int milliseconds,
  1490. const bool useLocalTime) throw()
  1491. {
  1492. jassert (year > 100); // year must be a 4-digit version
  1493. if (year < 1971 || year >= 2038 || ! useLocalTime)
  1494. {
  1495. // use extended maths for dates beyond 1970 to 2037..
  1496. const int timeZoneAdjustment = useLocalTime ? (31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000))
  1497. : 0;
  1498. const int a = (13 - month) / 12;
  1499. const int y = year + 4800 - a;
  1500. const int jd = day + (153 * (month + 12 * a - 2) + 2) / 5
  1501. + (y * 365) + (y / 4) - (y / 100) + (y / 400)
  1502. - 32045;
  1503. const int64 s = ((int64) jd) * literal64bit (86400) - literal64bit (210866803200);
  1504. millisSinceEpoch = 1000 * (s + (hours * 3600 + minutes * 60 + seconds - timeZoneAdjustment))
  1505. + milliseconds;
  1506. }
  1507. else
  1508. {
  1509. struct tm t;
  1510. t.tm_year = year - 1900;
  1511. t.tm_mon = month;
  1512. t.tm_mday = day;
  1513. t.tm_hour = hours;
  1514. t.tm_min = minutes;
  1515. t.tm_sec = seconds;
  1516. t.tm_isdst = -1;
  1517. millisSinceEpoch = 1000 * (int64) mktime (&t);
  1518. if (millisSinceEpoch < 0)
  1519. millisSinceEpoch = 0;
  1520. else
  1521. millisSinceEpoch += milliseconds;
  1522. }
  1523. }
  1524. Time::~Time() throw()
  1525. {
  1526. }
  1527. Time& Time::operator= (const Time& other) throw()
  1528. {
  1529. millisSinceEpoch = other.millisSinceEpoch;
  1530. return *this;
  1531. }
  1532. int64 Time::currentTimeMillis() throw()
  1533. {
  1534. static uint32 lastCounterResult = 0xffffffff;
  1535. static int64 correction = 0;
  1536. const uint32 now = getMillisecondCounter();
  1537. // check the counter hasn't wrapped (also triggered the first time this function is called)
  1538. if (now < lastCounterResult)
  1539. {
  1540. // double-check it's actually wrapped, in case multi-cpu machines have timers that drift a bit.
  1541. if (lastCounterResult == 0xffffffff || now < lastCounterResult - 10)
  1542. {
  1543. // get the time once using normal library calls, and store the difference needed to
  1544. // turn the millisecond counter into a real time.
  1545. #if JUCE_WINDOWS
  1546. struct _timeb t;
  1547. #ifdef USE_NEW_SECURE_TIME_FNS
  1548. _ftime_s (&t);
  1549. #else
  1550. _ftime (&t);
  1551. #endif
  1552. correction = (((int64) t.time) * 1000 + t.millitm) - now;
  1553. #else
  1554. struct timeval tv;
  1555. struct timezone tz;
  1556. gettimeofday (&tv, &tz);
  1557. correction = (((int64) tv.tv_sec) * 1000 + tv.tv_usec / 1000) - now;
  1558. #endif
  1559. }
  1560. }
  1561. lastCounterResult = now;
  1562. return correction + now;
  1563. }
  1564. uint32 juce_millisecondsSinceStartup() throw();
  1565. uint32 Time::getMillisecondCounter() throw()
  1566. {
  1567. const uint32 now = juce_millisecondsSinceStartup();
  1568. if (now < TimeHelpers::lastMSCounterValue)
  1569. {
  1570. // in multi-threaded apps this might be called concurrently, so
  1571. // make sure that our last counter value only increases and doesn't
  1572. // go backwards..
  1573. if (now < TimeHelpers::lastMSCounterValue - 1000)
  1574. TimeHelpers::lastMSCounterValue = now;
  1575. }
  1576. else
  1577. {
  1578. TimeHelpers::lastMSCounterValue = now;
  1579. }
  1580. return now;
  1581. }
  1582. uint32 Time::getApproximateMillisecondCounter() throw()
  1583. {
  1584. jassert (TimeHelpers::lastMSCounterValue != 0);
  1585. return TimeHelpers::lastMSCounterValue;
  1586. }
  1587. void Time::waitForMillisecondCounter (const uint32 targetTime) throw()
  1588. {
  1589. for (;;)
  1590. {
  1591. const uint32 now = getMillisecondCounter();
  1592. if (now >= targetTime)
  1593. break;
  1594. const int toWait = targetTime - now;
  1595. if (toWait > 2)
  1596. {
  1597. Thread::sleep (jmin (20, toWait >> 1));
  1598. }
  1599. else
  1600. {
  1601. // xxx should consider using mutex_pause on the mac as it apparently
  1602. // makes it seem less like a spinlock and avoids lowering the thread pri.
  1603. for (int i = 10; --i >= 0;)
  1604. Thread::yield();
  1605. }
  1606. }
  1607. }
  1608. double Time::highResolutionTicksToSeconds (const int64 ticks) throw()
  1609. {
  1610. return ticks / (double) getHighResolutionTicksPerSecond();
  1611. }
  1612. int64 Time::secondsToHighResolutionTicks (const double seconds) throw()
  1613. {
  1614. return (int64) (seconds * (double) getHighResolutionTicksPerSecond());
  1615. }
  1616. const Time JUCE_CALLTYPE Time::getCurrentTime() throw()
  1617. {
  1618. return Time (currentTimeMillis());
  1619. }
  1620. const String Time::toString (const bool includeDate,
  1621. const bool includeTime,
  1622. const bool includeSeconds,
  1623. const bool use24HourClock) const throw()
  1624. {
  1625. String result;
  1626. if (includeDate)
  1627. {
  1628. result << getDayOfMonth() << ' '
  1629. << getMonthName (true) << ' '
  1630. << getYear();
  1631. if (includeTime)
  1632. result << ' ';
  1633. }
  1634. if (includeTime)
  1635. {
  1636. const int mins = getMinutes();
  1637. result << (use24HourClock ? getHours() : getHoursInAmPmFormat())
  1638. << (mins < 10 ? ":0" : ":") << mins;
  1639. if (includeSeconds)
  1640. {
  1641. const int secs = getSeconds();
  1642. result << (secs < 10 ? ":0" : ":") << secs;
  1643. }
  1644. if (! use24HourClock)
  1645. result << (isAfternoon() ? "pm" : "am");
  1646. }
  1647. return result.trimEnd();
  1648. }
  1649. const String Time::formatted (const String& format) const
  1650. {
  1651. String buffer;
  1652. int bufferSize = 128;
  1653. buffer.preallocateStorage (bufferSize);
  1654. struct tm t (TimeHelpers::millisToLocal (millisSinceEpoch));
  1655. while (CharacterFunctions::ftime (static_cast <juce_wchar*> (buffer), bufferSize, format, &t) <= 0)
  1656. {
  1657. bufferSize += 128;
  1658. buffer.preallocateStorage (bufferSize);
  1659. }
  1660. return buffer;
  1661. }
  1662. int Time::getYear() const throw()
  1663. {
  1664. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_year + 1900;
  1665. }
  1666. int Time::getMonth() const throw()
  1667. {
  1668. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_mon;
  1669. }
  1670. int Time::getDayOfMonth() const throw()
  1671. {
  1672. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_mday;
  1673. }
  1674. int Time::getDayOfWeek() const throw()
  1675. {
  1676. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_wday;
  1677. }
  1678. int Time::getHours() const throw()
  1679. {
  1680. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_hour;
  1681. }
  1682. int Time::getHoursInAmPmFormat() const throw()
  1683. {
  1684. const int hours = getHours();
  1685. if (hours == 0)
  1686. return 12;
  1687. else if (hours <= 12)
  1688. return hours;
  1689. else
  1690. return hours - 12;
  1691. }
  1692. bool Time::isAfternoon() const throw()
  1693. {
  1694. return getHours() >= 12;
  1695. }
  1696. int Time::getMinutes() const throw()
  1697. {
  1698. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_min;
  1699. }
  1700. int Time::getSeconds() const throw()
  1701. {
  1702. return TimeHelpers::extendedModulo (millisSinceEpoch / 1000, 60);
  1703. }
  1704. int Time::getMilliseconds() const throw()
  1705. {
  1706. return TimeHelpers::extendedModulo (millisSinceEpoch, 1000);
  1707. }
  1708. bool Time::isDaylightSavingTime() const throw()
  1709. {
  1710. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_isdst != 0;
  1711. }
  1712. const String Time::getTimeZone() const throw()
  1713. {
  1714. String zone[2];
  1715. #if JUCE_WINDOWS
  1716. _tzset();
  1717. #ifdef USE_NEW_SECURE_TIME_FNS
  1718. {
  1719. char name [128];
  1720. size_t length;
  1721. for (int i = 0; i < 2; ++i)
  1722. {
  1723. zeromem (name, sizeof (name));
  1724. _get_tzname (&length, name, 127, i);
  1725. zone[i] = name;
  1726. }
  1727. }
  1728. #else
  1729. const char** const zonePtr = (const char**) _tzname;
  1730. zone[0] = zonePtr[0];
  1731. zone[1] = zonePtr[1];
  1732. #endif
  1733. #else
  1734. tzset();
  1735. const char** const zonePtr = (const char**) tzname;
  1736. zone[0] = zonePtr[0];
  1737. zone[1] = zonePtr[1];
  1738. #endif
  1739. if (isDaylightSavingTime())
  1740. {
  1741. zone[0] = zone[1];
  1742. if (zone[0].length() > 3
  1743. && zone[0].containsIgnoreCase ("daylight")
  1744. && zone[0].contains ("GMT"))
  1745. zone[0] = "BST";
  1746. }
  1747. return zone[0].substring (0, 3);
  1748. }
  1749. const String Time::getMonthName (const bool threeLetterVersion) const
  1750. {
  1751. return getMonthName (getMonth(), threeLetterVersion);
  1752. }
  1753. const String Time::getWeekdayName (const bool threeLetterVersion) const
  1754. {
  1755. return getWeekdayName (getDayOfWeek(), threeLetterVersion);
  1756. }
  1757. const String Time::getMonthName (int monthNumber, const bool threeLetterVersion)
  1758. {
  1759. const char* const shortMonthNames[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  1760. const char* const longMonthNames[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
  1761. monthNumber %= 12;
  1762. return TRANS (threeLetterVersion ? shortMonthNames [monthNumber]
  1763. : longMonthNames [monthNumber]);
  1764. }
  1765. const String Time::getWeekdayName (int day, const bool threeLetterVersion)
  1766. {
  1767. const char* const shortDayNames[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
  1768. const char* const longDayNames[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
  1769. day %= 7;
  1770. return TRANS (threeLetterVersion ? shortDayNames [day]
  1771. : longDayNames [day]);
  1772. }
  1773. END_JUCE_NAMESPACE
  1774. /*** End of inlined file: juce_Time.cpp ***/
  1775. /*** Start of inlined file: juce_Initialisation.cpp ***/
  1776. BEGIN_JUCE_NAMESPACE
  1777. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  1778. #endif
  1779. #if JUCE_WINDOWS
  1780. extern void juce_shutdownWin32Sockets(); // (defined in the sockets code)
  1781. #endif
  1782. #if JUCE_DEBUG
  1783. extern void juce_CheckForDanglingStreams(); // (in juce_OutputStream.cpp)
  1784. #endif
  1785. static bool juceInitialisedNonGUI = false;
  1786. JUCE_API void JUCE_CALLTYPE initialiseJuce_NonGUI()
  1787. {
  1788. if (! juceInitialisedNonGUI)
  1789. {
  1790. juceInitialisedNonGUI = true;
  1791. JUCE_AUTORELEASEPOOL
  1792. DBG (SystemStats::getJUCEVersion());
  1793. SystemStats::initialiseStats();
  1794. Random::getSystemRandom().setSeedRandomly(); // (mustn't call this before initialiseStats() because it relies on the time being set up)
  1795. }
  1796. // Some basic tests, to keep an eye on things and make sure these types work ok
  1797. // on all platforms. Let me know if any of these assertions fail on your system!
  1798. static_jassert (sizeof (pointer_sized_int) == sizeof (void*));
  1799. static_jassert (sizeof (int8) == 1);
  1800. static_jassert (sizeof (uint8) == 1);
  1801. static_jassert (sizeof (int16) == 2);
  1802. static_jassert (sizeof (uint16) == 2);
  1803. static_jassert (sizeof (int32) == 4);
  1804. static_jassert (sizeof (uint32) == 4);
  1805. static_jassert (sizeof (int64) == 8);
  1806. static_jassert (sizeof (uint64) == 8);
  1807. }
  1808. JUCE_API void JUCE_CALLTYPE shutdownJuce_NonGUI()
  1809. {
  1810. if (juceInitialisedNonGUI)
  1811. {
  1812. juceInitialisedNonGUI = false;
  1813. JUCE_AUTORELEASEPOOL
  1814. LocalisedStrings::setCurrentMappings (0);
  1815. Thread::stopAllThreads (3000);
  1816. #if JUCE_WINDOWS
  1817. juce_shutdownWin32Sockets();
  1818. #endif
  1819. #if JUCE_DEBUG
  1820. juce_CheckForDanglingStreams();
  1821. #endif
  1822. }
  1823. }
  1824. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  1825. void juce_setCurrentThreadName (const String& name);
  1826. static bool juceInitialisedGUI = false;
  1827. JUCE_API void JUCE_CALLTYPE initialiseJuce_GUI()
  1828. {
  1829. if (! juceInitialisedGUI)
  1830. {
  1831. juceInitialisedGUI = true;
  1832. JUCE_AUTORELEASEPOOL
  1833. initialiseJuce_NonGUI();
  1834. MessageManager::getInstance();
  1835. LookAndFeel::setDefaultLookAndFeel (0);
  1836. juce_setCurrentThreadName ("Juce Message Thread");
  1837. #if JUCE_DEBUG
  1838. // This section is just for catching people who mess up their project settings and
  1839. // turn RTTI off..
  1840. try
  1841. {
  1842. MemoryOutputStream mo;
  1843. OutputStream* o = &mo;
  1844. // Got an exception here? Then TURN ON RTTI in your compiler settings!!
  1845. o = dynamic_cast <MemoryOutputStream*> (o);
  1846. jassert (o != 0);
  1847. }
  1848. catch (...)
  1849. {
  1850. // Ended up here? If so, TURN ON RTTI in your compiler settings!!
  1851. jassertfalse;
  1852. }
  1853. #endif
  1854. }
  1855. }
  1856. JUCE_API void JUCE_CALLTYPE shutdownJuce_GUI()
  1857. {
  1858. if (juceInitialisedGUI)
  1859. {
  1860. juceInitialisedGUI = false;
  1861. JUCE_AUTORELEASEPOOL
  1862. DeletedAtShutdown::deleteAll();
  1863. LookAndFeel::clearDefaultLookAndFeel();
  1864. delete MessageManager::getInstance();
  1865. shutdownJuce_NonGUI();
  1866. }
  1867. }
  1868. #endif
  1869. #if JUCE_UNIT_TESTS
  1870. class AtomicTests : public UnitTest
  1871. {
  1872. public:
  1873. AtomicTests() : UnitTest ("Atomics") {}
  1874. void runTest()
  1875. {
  1876. beginTest ("Misc");
  1877. char a1[7];
  1878. expect (numElementsInArray(a1) == 7);
  1879. int a2[3];
  1880. expect (numElementsInArray(a2) == 3);
  1881. expect (ByteOrder::swap ((uint16) 0x1122) == 0x2211);
  1882. expect (ByteOrder::swap ((uint32) 0x11223344) == 0x44332211);
  1883. expect (ByteOrder::swap ((uint64) literal64bit (0x1122334455667788)) == literal64bit (0x8877665544332211));
  1884. beginTest ("Atomic types");
  1885. AtomicTester <int>::testInteger (*this);
  1886. AtomicTester <unsigned int>::testInteger (*this);
  1887. AtomicTester <int32>::testInteger (*this);
  1888. AtomicTester <uint32>::testInteger (*this);
  1889. AtomicTester <long>::testInteger (*this);
  1890. AtomicTester <void*>::testInteger (*this);
  1891. AtomicTester <int*>::testInteger (*this);
  1892. AtomicTester <float>::testFloat (*this);
  1893. #if ! JUCE_64BIT_ATOMICS_UNAVAILABLE // 64-bit intrinsics aren't available on some old platforms
  1894. AtomicTester <int64>::testInteger (*this);
  1895. AtomicTester <uint64>::testInteger (*this);
  1896. AtomicTester <double>::testFloat (*this);
  1897. #endif
  1898. }
  1899. template <typename Type>
  1900. class AtomicTester
  1901. {
  1902. public:
  1903. AtomicTester() {}
  1904. static void testInteger (UnitTest& test)
  1905. {
  1906. Atomic<Type> a, b;
  1907. a.set ((Type) 10);
  1908. a += (Type) 15;
  1909. a.memoryBarrier();
  1910. a -= (Type) 5;
  1911. ++a; ++a; --a;
  1912. a.memoryBarrier();
  1913. testFloat (test);
  1914. }
  1915. static void testFloat (UnitTest& test)
  1916. {
  1917. Atomic<Type> a, b;
  1918. a = (Type) 21;
  1919. a.memoryBarrier();
  1920. /* These are some simple test cases to check the atomics - let me know
  1921. if any of these assertions fail on your system!
  1922. */
  1923. test.expect (a.get() == (Type) 21);
  1924. test.expect (a.compareAndSetValue ((Type) 100, (Type) 50) == (Type) 21);
  1925. test.expect (a.get() == (Type) 21);
  1926. test.expect (a.compareAndSetValue ((Type) 101, a.get()) == (Type) 21);
  1927. test.expect (a.get() == (Type) 101);
  1928. test.expect (! a.compareAndSetBool ((Type) 300, (Type) 200));
  1929. test.expect (a.get() == (Type) 101);
  1930. test.expect (a.compareAndSetBool ((Type) 200, a.get()));
  1931. test.expect (a.get() == (Type) 200);
  1932. test.expect (a.exchange ((Type) 300) == (Type) 200);
  1933. test.expect (a.get() == (Type) 300);
  1934. b = a;
  1935. test.expect (b.get() == a.get());
  1936. }
  1937. };
  1938. };
  1939. static AtomicTests atomicUnitTests;
  1940. #endif
  1941. END_JUCE_NAMESPACE
  1942. /*** End of inlined file: juce_Initialisation.cpp ***/
  1943. /*** Start of inlined file: juce_AbstractFifo.cpp ***/
  1944. BEGIN_JUCE_NAMESPACE
  1945. AbstractFifo::AbstractFifo (const int capacity) throw()
  1946. : bufferSize (capacity)
  1947. {
  1948. jassert (bufferSize > 0);
  1949. }
  1950. AbstractFifo::~AbstractFifo() {}
  1951. int AbstractFifo::getTotalSize() const throw() { return bufferSize; }
  1952. int AbstractFifo::getFreeSpace() const throw() { return bufferSize - getNumReady(); }
  1953. int AbstractFifo::getNumReady() const throw() { return validEnd.get() - validStart.get(); }
  1954. void AbstractFifo::reset() throw()
  1955. {
  1956. validEnd = 0;
  1957. validStart = 0;
  1958. }
  1959. void AbstractFifo::setTotalSize (int newSize) throw()
  1960. {
  1961. jassert (newSize > 0);
  1962. reset();
  1963. bufferSize = newSize;
  1964. }
  1965. void AbstractFifo::prepareToWrite (int numToWrite, int& startIndex1, int& blockSize1, int& startIndex2, int& blockSize2) const throw()
  1966. {
  1967. const int vs = validStart.get();
  1968. const int ve = validEnd.get();
  1969. const int freeSpace = bufferSize - (ve - vs);
  1970. numToWrite = jmin (numToWrite, freeSpace);
  1971. if (numToWrite <= 0)
  1972. {
  1973. startIndex1 = 0;
  1974. startIndex2 = 0;
  1975. blockSize1 = 0;
  1976. blockSize2 = 0;
  1977. }
  1978. else
  1979. {
  1980. startIndex1 = (int) (ve % bufferSize);
  1981. startIndex2 = 0;
  1982. blockSize1 = jmin (bufferSize - startIndex1, numToWrite);
  1983. numToWrite -= blockSize1;
  1984. blockSize2 = numToWrite <= 0 ? 0 : jmin (numToWrite, (int) (vs % bufferSize));
  1985. }
  1986. }
  1987. void AbstractFifo::finishedWrite (int numWritten) throw()
  1988. {
  1989. jassert (numWritten >= 0 && numWritten < bufferSize);
  1990. validEnd += numWritten;
  1991. }
  1992. void AbstractFifo::prepareToRead (int numWanted, int& startIndex1, int& blockSize1, int& startIndex2, int& blockSize2) const throw()
  1993. {
  1994. const int vs = validStart.get();
  1995. const int ve = validEnd.get();
  1996. const int numReady = ve - vs;
  1997. numWanted = jmin (numWanted, numReady);
  1998. if (numWanted <= 0)
  1999. {
  2000. startIndex1 = 0;
  2001. startIndex2 = 0;
  2002. blockSize1 = 0;
  2003. blockSize2 = 0;
  2004. }
  2005. else
  2006. {
  2007. startIndex1 = (int) (vs % bufferSize);
  2008. startIndex2 = 0;
  2009. blockSize1 = jmin (bufferSize - startIndex1, numWanted);
  2010. numWanted -= blockSize1;
  2011. blockSize2 = numWanted <= 0 ? 0 : jmin (numWanted, (int) (ve % bufferSize));
  2012. }
  2013. }
  2014. void AbstractFifo::finishedRead (int numRead) throw()
  2015. {
  2016. jassert (numRead >= 0 && numRead < bufferSize);
  2017. validStart += numRead;
  2018. }
  2019. END_JUCE_NAMESPACE
  2020. /*** End of inlined file: juce_AbstractFifo.cpp ***/
  2021. /*** Start of inlined file: juce_BigInteger.cpp ***/
  2022. BEGIN_JUCE_NAMESPACE
  2023. BigInteger::BigInteger()
  2024. : numValues (4),
  2025. highestBit (-1),
  2026. negative (false)
  2027. {
  2028. values.calloc (numValues + 1);
  2029. }
  2030. BigInteger::BigInteger (const int32 value)
  2031. : numValues (4),
  2032. highestBit (31),
  2033. negative (value < 0)
  2034. {
  2035. values.calloc (numValues + 1);
  2036. values[0] = abs (value);
  2037. highestBit = getHighestBit();
  2038. }
  2039. BigInteger::BigInteger (const uint32 value)
  2040. : numValues (4),
  2041. highestBit (31),
  2042. negative (false)
  2043. {
  2044. values.calloc (numValues + 1);
  2045. values[0] = value;
  2046. highestBit = getHighestBit();
  2047. }
  2048. BigInteger::BigInteger (int64 value)
  2049. : numValues (4),
  2050. highestBit (63),
  2051. negative (value < 0)
  2052. {
  2053. values.calloc (numValues + 1);
  2054. if (value < 0)
  2055. value = -value;
  2056. values[0] = (uint32) value;
  2057. values[1] = (uint32) (value >> 32);
  2058. highestBit = getHighestBit();
  2059. }
  2060. BigInteger::BigInteger (const BigInteger& other)
  2061. : numValues (jmax (4, bitToIndex (other.highestBit) + 1)),
  2062. highestBit (other.getHighestBit()),
  2063. negative (other.negative)
  2064. {
  2065. values.malloc (numValues + 1);
  2066. memcpy (values, other.values, sizeof (uint32) * (numValues + 1));
  2067. }
  2068. BigInteger::~BigInteger()
  2069. {
  2070. }
  2071. void BigInteger::swapWith (BigInteger& other) throw()
  2072. {
  2073. values.swapWith (other.values);
  2074. swapVariables (numValues, other.numValues);
  2075. swapVariables (highestBit, other.highestBit);
  2076. swapVariables (negative, other.negative);
  2077. }
  2078. BigInteger& BigInteger::operator= (const BigInteger& other)
  2079. {
  2080. if (this != &other)
  2081. {
  2082. highestBit = other.getHighestBit();
  2083. numValues = jmax (4, bitToIndex (highestBit) + 1);
  2084. negative = other.negative;
  2085. values.malloc (numValues + 1);
  2086. memcpy (values, other.values, sizeof (uint32) * (numValues + 1));
  2087. }
  2088. return *this;
  2089. }
  2090. void BigInteger::ensureSize (const int numVals)
  2091. {
  2092. if (numVals + 2 >= numValues)
  2093. {
  2094. int oldSize = numValues;
  2095. numValues = ((numVals + 2) * 3) / 2;
  2096. values.realloc (numValues + 1);
  2097. while (oldSize < numValues)
  2098. values [oldSize++] = 0;
  2099. }
  2100. }
  2101. bool BigInteger::operator[] (const int bit) const throw()
  2102. {
  2103. return bit <= highestBit && bit >= 0
  2104. && ((values [bitToIndex (bit)] & bitToMask (bit)) != 0);
  2105. }
  2106. int BigInteger::toInteger() const throw()
  2107. {
  2108. const int n = (int) (values[0] & 0x7fffffff);
  2109. return negative ? -n : n;
  2110. }
  2111. const BigInteger BigInteger::getBitRange (int startBit, int numBits) const
  2112. {
  2113. BigInteger r;
  2114. numBits = jmin (numBits, getHighestBit() + 1 - startBit);
  2115. r.ensureSize (bitToIndex (numBits));
  2116. r.highestBit = numBits;
  2117. int i = 0;
  2118. while (numBits > 0)
  2119. {
  2120. r.values[i++] = getBitRangeAsInt (startBit, jmin (32, numBits));
  2121. numBits -= 32;
  2122. startBit += 32;
  2123. }
  2124. r.highestBit = r.getHighestBit();
  2125. return r;
  2126. }
  2127. int BigInteger::getBitRangeAsInt (const int startBit, int numBits) const throw()
  2128. {
  2129. if (numBits > 32)
  2130. {
  2131. jassertfalse; // use getBitRange() if you need more than 32 bits..
  2132. numBits = 32;
  2133. }
  2134. numBits = jmin (numBits, highestBit + 1 - startBit);
  2135. if (numBits <= 0)
  2136. return 0;
  2137. const int pos = bitToIndex (startBit);
  2138. const int offset = startBit & 31;
  2139. const int endSpace = 32 - numBits;
  2140. uint32 n = ((uint32) values [pos]) >> offset;
  2141. if (offset > endSpace)
  2142. n |= ((uint32) values [pos + 1]) << (32 - offset);
  2143. return (int) (n & (((uint32) 0xffffffff) >> endSpace));
  2144. }
  2145. void BigInteger::setBitRangeAsInt (const int startBit, int numBits, uint32 valueToSet)
  2146. {
  2147. if (numBits > 32)
  2148. {
  2149. jassertfalse;
  2150. numBits = 32;
  2151. }
  2152. for (int i = 0; i < numBits; ++i)
  2153. {
  2154. setBit (startBit + i, (valueToSet & 1) != 0);
  2155. valueToSet >>= 1;
  2156. }
  2157. }
  2158. void BigInteger::clear()
  2159. {
  2160. if (numValues > 16)
  2161. {
  2162. numValues = 4;
  2163. values.calloc (numValues + 1);
  2164. }
  2165. else
  2166. {
  2167. zeromem (values, sizeof (uint32) * (numValues + 1));
  2168. }
  2169. highestBit = -1;
  2170. negative = false;
  2171. }
  2172. void BigInteger::setBit (const int bit)
  2173. {
  2174. if (bit >= 0)
  2175. {
  2176. if (bit > highestBit)
  2177. {
  2178. ensureSize (bitToIndex (bit));
  2179. highestBit = bit;
  2180. }
  2181. values [bitToIndex (bit)] |= bitToMask (bit);
  2182. }
  2183. }
  2184. void BigInteger::setBit (const int bit, const bool shouldBeSet)
  2185. {
  2186. if (shouldBeSet)
  2187. setBit (bit);
  2188. else
  2189. clearBit (bit);
  2190. }
  2191. void BigInteger::clearBit (const int bit) throw()
  2192. {
  2193. if (bit >= 0 && bit <= highestBit)
  2194. values [bitToIndex (bit)] &= ~bitToMask (bit);
  2195. }
  2196. void BigInteger::setRange (int startBit, int numBits, const bool shouldBeSet)
  2197. {
  2198. while (--numBits >= 0)
  2199. setBit (startBit++, shouldBeSet);
  2200. }
  2201. void BigInteger::insertBit (const int bit, const bool shouldBeSet)
  2202. {
  2203. if (bit >= 0)
  2204. shiftBits (1, bit);
  2205. setBit (bit, shouldBeSet);
  2206. }
  2207. bool BigInteger::isZero() const throw()
  2208. {
  2209. return getHighestBit() < 0;
  2210. }
  2211. bool BigInteger::isOne() const throw()
  2212. {
  2213. return getHighestBit() == 0 && ! negative;
  2214. }
  2215. bool BigInteger::isNegative() const throw()
  2216. {
  2217. return negative && ! isZero();
  2218. }
  2219. void BigInteger::setNegative (const bool neg) throw()
  2220. {
  2221. negative = neg;
  2222. }
  2223. void BigInteger::negate() throw()
  2224. {
  2225. negative = (! negative) && ! isZero();
  2226. }
  2227. int BigInteger::countNumberOfSetBits() const throw()
  2228. {
  2229. int total = 0;
  2230. for (int i = bitToIndex (highestBit) + 1; --i >= 0;)
  2231. {
  2232. uint32 n = values[i];
  2233. if (n == 0xffffffff)
  2234. {
  2235. total += 32;
  2236. }
  2237. else
  2238. {
  2239. while (n != 0)
  2240. {
  2241. total += (n & 1);
  2242. n >>= 1;
  2243. }
  2244. }
  2245. }
  2246. return total;
  2247. }
  2248. int BigInteger::getHighestBit() const throw()
  2249. {
  2250. for (int i = highestBit + 1; --i >= 0;)
  2251. if ((values [bitToIndex (i)] & bitToMask (i)) != 0)
  2252. return i;
  2253. return -1;
  2254. }
  2255. int BigInteger::findNextSetBit (int i) const throw()
  2256. {
  2257. for (; i <= highestBit; ++i)
  2258. if ((values [bitToIndex (i)] & bitToMask (i)) != 0)
  2259. return i;
  2260. return -1;
  2261. }
  2262. int BigInteger::findNextClearBit (int i) const throw()
  2263. {
  2264. for (; i <= highestBit; ++i)
  2265. if ((values [bitToIndex (i)] & bitToMask (i)) == 0)
  2266. break;
  2267. return i;
  2268. }
  2269. BigInteger& BigInteger::operator+= (const BigInteger& other)
  2270. {
  2271. if (other.isNegative())
  2272. return operator-= (-other);
  2273. if (isNegative())
  2274. {
  2275. if (compareAbsolute (other) < 0)
  2276. {
  2277. BigInteger temp (*this);
  2278. temp.negate();
  2279. *this = other;
  2280. operator-= (temp);
  2281. }
  2282. else
  2283. {
  2284. negate();
  2285. operator-= (other);
  2286. negate();
  2287. }
  2288. }
  2289. else
  2290. {
  2291. if (other.highestBit > highestBit)
  2292. highestBit = other.highestBit;
  2293. ++highestBit;
  2294. const int numInts = bitToIndex (highestBit) + 1;
  2295. ensureSize (numInts);
  2296. int64 remainder = 0;
  2297. for (int i = 0; i <= numInts; ++i)
  2298. {
  2299. if (i < numValues)
  2300. remainder += values[i];
  2301. if (i < other.numValues)
  2302. remainder += other.values[i];
  2303. values[i] = (uint32) remainder;
  2304. remainder >>= 32;
  2305. }
  2306. jassert (remainder == 0);
  2307. highestBit = getHighestBit();
  2308. }
  2309. return *this;
  2310. }
  2311. BigInteger& BigInteger::operator-= (const BigInteger& other)
  2312. {
  2313. if (other.isNegative())
  2314. return operator+= (-other);
  2315. if (! isNegative())
  2316. {
  2317. if (compareAbsolute (other) < 0)
  2318. {
  2319. BigInteger temp (other);
  2320. swapWith (temp);
  2321. operator-= (temp);
  2322. negate();
  2323. return *this;
  2324. }
  2325. }
  2326. else
  2327. {
  2328. negate();
  2329. operator+= (other);
  2330. negate();
  2331. return *this;
  2332. }
  2333. const int numInts = bitToIndex (highestBit) + 1;
  2334. const int maxOtherInts = bitToIndex (other.highestBit) + 1;
  2335. int64 amountToSubtract = 0;
  2336. for (int i = 0; i <= numInts; ++i)
  2337. {
  2338. if (i <= maxOtherInts)
  2339. amountToSubtract += (int64) other.values[i];
  2340. if (values[i] >= amountToSubtract)
  2341. {
  2342. values[i] = (uint32) (values[i] - amountToSubtract);
  2343. amountToSubtract = 0;
  2344. }
  2345. else
  2346. {
  2347. const int64 n = ((int64) values[i] + (((int64) 1) << 32)) - amountToSubtract;
  2348. values[i] = (uint32) n;
  2349. amountToSubtract = 1;
  2350. }
  2351. }
  2352. return *this;
  2353. }
  2354. BigInteger& BigInteger::operator*= (const BigInteger& other)
  2355. {
  2356. BigInteger total;
  2357. highestBit = getHighestBit();
  2358. const bool wasNegative = isNegative();
  2359. setNegative (false);
  2360. for (int i = 0; i <= highestBit; ++i)
  2361. {
  2362. if (operator[](i))
  2363. {
  2364. BigInteger n (other);
  2365. n.setNegative (false);
  2366. n <<= i;
  2367. total += n;
  2368. }
  2369. }
  2370. total.setNegative (wasNegative ^ other.isNegative());
  2371. swapWith (total);
  2372. return *this;
  2373. }
  2374. void BigInteger::divideBy (const BigInteger& divisor, BigInteger& remainder)
  2375. {
  2376. jassert (this != &remainder); // (can't handle passing itself in to get the remainder)
  2377. const int divHB = divisor.getHighestBit();
  2378. const int ourHB = getHighestBit();
  2379. if (divHB < 0 || ourHB < 0)
  2380. {
  2381. // division by zero
  2382. remainder.clear();
  2383. clear();
  2384. }
  2385. else
  2386. {
  2387. const bool wasNegative = isNegative();
  2388. swapWith (remainder);
  2389. remainder.setNegative (false);
  2390. clear();
  2391. BigInteger temp (divisor);
  2392. temp.setNegative (false);
  2393. int leftShift = ourHB - divHB;
  2394. temp <<= leftShift;
  2395. while (leftShift >= 0)
  2396. {
  2397. if (remainder.compareAbsolute (temp) >= 0)
  2398. {
  2399. remainder -= temp;
  2400. setBit (leftShift);
  2401. }
  2402. if (--leftShift >= 0)
  2403. temp >>= 1;
  2404. }
  2405. negative = wasNegative ^ divisor.isNegative();
  2406. remainder.setNegative (wasNegative);
  2407. }
  2408. }
  2409. BigInteger& BigInteger::operator/= (const BigInteger& other)
  2410. {
  2411. BigInteger remainder;
  2412. divideBy (other, remainder);
  2413. return *this;
  2414. }
  2415. BigInteger& BigInteger::operator|= (const BigInteger& other)
  2416. {
  2417. // this operation doesn't take into account negative values..
  2418. jassert (isNegative() == other.isNegative());
  2419. if (other.highestBit >= 0)
  2420. {
  2421. ensureSize (bitToIndex (other.highestBit));
  2422. int n = bitToIndex (other.highestBit) + 1;
  2423. while (--n >= 0)
  2424. values[n] |= other.values[n];
  2425. if (other.highestBit > highestBit)
  2426. highestBit = other.highestBit;
  2427. highestBit = getHighestBit();
  2428. }
  2429. return *this;
  2430. }
  2431. BigInteger& BigInteger::operator&= (const BigInteger& other)
  2432. {
  2433. // this operation doesn't take into account negative values..
  2434. jassert (isNegative() == other.isNegative());
  2435. int n = numValues;
  2436. while (n > other.numValues)
  2437. values[--n] = 0;
  2438. while (--n >= 0)
  2439. values[n] &= other.values[n];
  2440. if (other.highestBit < highestBit)
  2441. highestBit = other.highestBit;
  2442. highestBit = getHighestBit();
  2443. return *this;
  2444. }
  2445. BigInteger& BigInteger::operator^= (const BigInteger& other)
  2446. {
  2447. // this operation will only work with the absolute values
  2448. jassert (isNegative() == other.isNegative());
  2449. if (other.highestBit >= 0)
  2450. {
  2451. ensureSize (bitToIndex (other.highestBit));
  2452. int n = bitToIndex (other.highestBit) + 1;
  2453. while (--n >= 0)
  2454. values[n] ^= other.values[n];
  2455. if (other.highestBit > highestBit)
  2456. highestBit = other.highestBit;
  2457. highestBit = getHighestBit();
  2458. }
  2459. return *this;
  2460. }
  2461. BigInteger& BigInteger::operator%= (const BigInteger& divisor)
  2462. {
  2463. BigInteger remainder;
  2464. divideBy (divisor, remainder);
  2465. swapWith (remainder);
  2466. return *this;
  2467. }
  2468. BigInteger& BigInteger::operator<<= (int numBitsToShift)
  2469. {
  2470. shiftBits (numBitsToShift, 0);
  2471. return *this;
  2472. }
  2473. BigInteger& BigInteger::operator>>= (int numBitsToShift)
  2474. {
  2475. return operator<<= (-numBitsToShift);
  2476. }
  2477. BigInteger& BigInteger::operator++() { return operator+= (1); }
  2478. BigInteger& BigInteger::operator--() { return operator-= (1); }
  2479. const BigInteger BigInteger::operator++ (int) { const BigInteger old (*this); operator+= (1); return old; }
  2480. const BigInteger BigInteger::operator-- (int) { const BigInteger old (*this); operator-= (1); return old; }
  2481. const BigInteger BigInteger::operator+ (const BigInteger& other) const { BigInteger b (*this); return b += other; }
  2482. const BigInteger BigInteger::operator- (const BigInteger& other) const { BigInteger b (*this); return b -= other; }
  2483. const BigInteger BigInteger::operator* (const BigInteger& other) const { BigInteger b (*this); return b *= other; }
  2484. const BigInteger BigInteger::operator/ (const BigInteger& other) const { BigInteger b (*this); return b /= other; }
  2485. const BigInteger BigInteger::operator| (const BigInteger& other) const { BigInteger b (*this); return b |= other; }
  2486. const BigInteger BigInteger::operator& (const BigInteger& other) const { BigInteger b (*this); return b &= other; }
  2487. const BigInteger BigInteger::operator^ (const BigInteger& other) const { BigInteger b (*this); return b ^= other; }
  2488. const BigInteger BigInteger::operator% (const BigInteger& other) const { BigInteger b (*this); return b %= other; }
  2489. const BigInteger BigInteger::operator<< (const int numBits) const { BigInteger b (*this); return b <<= numBits; }
  2490. const BigInteger BigInteger::operator>> (const int numBits) const { BigInteger b (*this); return b >>= numBits; }
  2491. const BigInteger BigInteger::operator-() const { BigInteger b (*this); b.negate(); return b; }
  2492. int BigInteger::compare (const BigInteger& other) const throw()
  2493. {
  2494. if (isNegative() == other.isNegative())
  2495. {
  2496. const int absComp = compareAbsolute (other);
  2497. return isNegative() ? -absComp : absComp;
  2498. }
  2499. else
  2500. {
  2501. return isNegative() ? -1 : 1;
  2502. }
  2503. }
  2504. int BigInteger::compareAbsolute (const BigInteger& other) const throw()
  2505. {
  2506. const int h1 = getHighestBit();
  2507. const int h2 = other.getHighestBit();
  2508. if (h1 > h2)
  2509. return 1;
  2510. else if (h1 < h2)
  2511. return -1;
  2512. for (int i = bitToIndex (h1) + 1; --i >= 0;)
  2513. if (values[i] != other.values[i])
  2514. return (values[i] > other.values[i]) ? 1 : -1;
  2515. return 0;
  2516. }
  2517. bool BigInteger::operator== (const BigInteger& other) const throw() { return compare (other) == 0; }
  2518. bool BigInteger::operator!= (const BigInteger& other) const throw() { return compare (other) != 0; }
  2519. bool BigInteger::operator< (const BigInteger& other) const throw() { return compare (other) < 0; }
  2520. bool BigInteger::operator<= (const BigInteger& other) const throw() { return compare (other) <= 0; }
  2521. bool BigInteger::operator> (const BigInteger& other) const throw() { return compare (other) > 0; }
  2522. bool BigInteger::operator>= (const BigInteger& other) const throw() { return compare (other) >= 0; }
  2523. void BigInteger::shiftBits (int bits, const int startBit)
  2524. {
  2525. if (highestBit < 0)
  2526. return;
  2527. if (startBit > 0)
  2528. {
  2529. if (bits < 0)
  2530. {
  2531. // right shift
  2532. for (int i = startBit; i <= highestBit; ++i)
  2533. setBit (i, operator[] (i - bits));
  2534. highestBit = getHighestBit();
  2535. }
  2536. else if (bits > 0)
  2537. {
  2538. // left shift
  2539. for (int i = highestBit + 1; --i >= startBit;)
  2540. setBit (i + bits, operator[] (i));
  2541. while (--bits >= 0)
  2542. clearBit (bits + startBit);
  2543. }
  2544. }
  2545. else
  2546. {
  2547. if (bits < 0)
  2548. {
  2549. // right shift
  2550. bits = -bits;
  2551. if (bits > highestBit)
  2552. {
  2553. clear();
  2554. }
  2555. else
  2556. {
  2557. const int wordsToMove = bitToIndex (bits);
  2558. int top = 1 + bitToIndex (highestBit) - wordsToMove;
  2559. highestBit -= bits;
  2560. if (wordsToMove > 0)
  2561. {
  2562. int i;
  2563. for (i = 0; i < top; ++i)
  2564. values [i] = values [i + wordsToMove];
  2565. for (i = 0; i < wordsToMove; ++i)
  2566. values [top + i] = 0;
  2567. bits &= 31;
  2568. }
  2569. if (bits != 0)
  2570. {
  2571. const int invBits = 32 - bits;
  2572. --top;
  2573. for (int i = 0; i < top; ++i)
  2574. values[i] = (values[i] >> bits) | (values [i + 1] << invBits);
  2575. values[top] = (values[top] >> bits);
  2576. }
  2577. highestBit = getHighestBit();
  2578. }
  2579. }
  2580. else if (bits > 0)
  2581. {
  2582. // left shift
  2583. ensureSize (bitToIndex (highestBit + bits) + 1);
  2584. const int wordsToMove = bitToIndex (bits);
  2585. int top = 1 + bitToIndex (highestBit);
  2586. highestBit += bits;
  2587. if (wordsToMove > 0)
  2588. {
  2589. int i;
  2590. for (i = top; --i >= 0;)
  2591. values [i + wordsToMove] = values [i];
  2592. for (i = 0; i < wordsToMove; ++i)
  2593. values [i] = 0;
  2594. bits &= 31;
  2595. }
  2596. if (bits != 0)
  2597. {
  2598. const int invBits = 32 - bits;
  2599. for (int i = top + 1 + wordsToMove; --i > wordsToMove;)
  2600. values[i] = (values[i] << bits) | (values [i - 1] >> invBits);
  2601. values [wordsToMove] = values [wordsToMove] << bits;
  2602. }
  2603. highestBit = getHighestBit();
  2604. }
  2605. }
  2606. }
  2607. const BigInteger BigInteger::simpleGCD (BigInteger* m, BigInteger* n)
  2608. {
  2609. while (! m->isZero())
  2610. {
  2611. if (n->compareAbsolute (*m) > 0)
  2612. swapVariables (m, n);
  2613. *m -= *n;
  2614. }
  2615. return *n;
  2616. }
  2617. const BigInteger BigInteger::findGreatestCommonDivisor (BigInteger n) const
  2618. {
  2619. BigInteger m (*this);
  2620. while (! n.isZero())
  2621. {
  2622. if (abs (m.getHighestBit() - n.getHighestBit()) <= 16)
  2623. return simpleGCD (&m, &n);
  2624. BigInteger temp1 (m), temp2;
  2625. temp1.divideBy (n, temp2);
  2626. m = n;
  2627. n = temp2;
  2628. }
  2629. return m;
  2630. }
  2631. void BigInteger::exponentModulo (const BigInteger& exponent, const BigInteger& modulus)
  2632. {
  2633. BigInteger exp (exponent);
  2634. exp %= modulus;
  2635. BigInteger value (1);
  2636. swapWith (value);
  2637. value %= modulus;
  2638. while (! exp.isZero())
  2639. {
  2640. if (exp [0])
  2641. {
  2642. operator*= (value);
  2643. operator%= (modulus);
  2644. }
  2645. value *= value;
  2646. value %= modulus;
  2647. exp >>= 1;
  2648. }
  2649. }
  2650. void BigInteger::inverseModulo (const BigInteger& modulus)
  2651. {
  2652. if (modulus.isOne() || modulus.isNegative())
  2653. {
  2654. clear();
  2655. return;
  2656. }
  2657. if (isNegative() || compareAbsolute (modulus) >= 0)
  2658. operator%= (modulus);
  2659. if (isOne())
  2660. return;
  2661. if (! (*this)[0])
  2662. {
  2663. // not invertible
  2664. clear();
  2665. return;
  2666. }
  2667. BigInteger a1 (modulus);
  2668. BigInteger a2 (*this);
  2669. BigInteger b1 (modulus);
  2670. BigInteger b2 (1);
  2671. while (! a2.isOne())
  2672. {
  2673. BigInteger temp1, temp2, multiplier (a1);
  2674. multiplier.divideBy (a2, temp1);
  2675. temp1 = a2;
  2676. temp1 *= multiplier;
  2677. temp2 = a1;
  2678. temp2 -= temp1;
  2679. a1 = a2;
  2680. a2 = temp2;
  2681. temp1 = b2;
  2682. temp1 *= multiplier;
  2683. temp2 = b1;
  2684. temp2 -= temp1;
  2685. b1 = b2;
  2686. b2 = temp2;
  2687. }
  2688. while (b2.isNegative())
  2689. b2 += modulus;
  2690. b2 %= modulus;
  2691. swapWith (b2);
  2692. }
  2693. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const BigInteger& value)
  2694. {
  2695. return stream << value.toString (10);
  2696. }
  2697. const String BigInteger::toString (const int base, const int minimumNumCharacters) const
  2698. {
  2699. String s;
  2700. BigInteger v (*this);
  2701. if (base == 2 || base == 8 || base == 16)
  2702. {
  2703. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2704. static const char* const hexDigits = "0123456789abcdef";
  2705. for (;;)
  2706. {
  2707. const int remainder = v.getBitRangeAsInt (0, bits);
  2708. v >>= bits;
  2709. if (remainder == 0 && v.isZero())
  2710. break;
  2711. s = String::charToString (hexDigits [remainder]) + s;
  2712. }
  2713. }
  2714. else if (base == 10)
  2715. {
  2716. const BigInteger ten (10);
  2717. BigInteger remainder;
  2718. for (;;)
  2719. {
  2720. v.divideBy (ten, remainder);
  2721. if (remainder.isZero() && v.isZero())
  2722. break;
  2723. s = String (remainder.getBitRangeAsInt (0, 8)) + s;
  2724. }
  2725. }
  2726. else
  2727. {
  2728. jassertfalse; // can't do the specified base!
  2729. return String::empty;
  2730. }
  2731. s = s.paddedLeft ('0', minimumNumCharacters);
  2732. return isNegative() ? "-" + s : s;
  2733. }
  2734. void BigInteger::parseString (const String& text, const int base)
  2735. {
  2736. clear();
  2737. const juce_wchar* t = text;
  2738. if (base == 2 || base == 8 || base == 16)
  2739. {
  2740. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2741. for (;;)
  2742. {
  2743. const juce_wchar c = *t++;
  2744. const int digit = CharacterFunctions::getHexDigitValue (c);
  2745. if (((uint32) digit) < (uint32) base)
  2746. {
  2747. operator<<= (bits);
  2748. operator+= (digit);
  2749. }
  2750. else if (c == 0)
  2751. {
  2752. break;
  2753. }
  2754. }
  2755. }
  2756. else if (base == 10)
  2757. {
  2758. const BigInteger ten ((uint32) 10);
  2759. for (;;)
  2760. {
  2761. const juce_wchar c = *t++;
  2762. if (c >= '0' && c <= '9')
  2763. {
  2764. operator*= (ten);
  2765. operator+= ((int) (c - '0'));
  2766. }
  2767. else if (c == 0)
  2768. {
  2769. break;
  2770. }
  2771. }
  2772. }
  2773. setNegative (text.trimStart().startsWithChar ('-'));
  2774. }
  2775. const MemoryBlock BigInteger::toMemoryBlock() const
  2776. {
  2777. const int numBytes = (getHighestBit() + 8) >> 3;
  2778. MemoryBlock mb ((size_t) numBytes);
  2779. for (int i = 0; i < numBytes; ++i)
  2780. mb[i] = (uint8) getBitRangeAsInt (i << 3, 8);
  2781. return mb;
  2782. }
  2783. void BigInteger::loadFromMemoryBlock (const MemoryBlock& data)
  2784. {
  2785. clear();
  2786. for (int i = (int) data.getSize(); --i >= 0;)
  2787. this->setBitRangeAsInt ((int) (i << 3), 8, data [i]);
  2788. }
  2789. END_JUCE_NAMESPACE
  2790. /*** End of inlined file: juce_BigInteger.cpp ***/
  2791. /*** Start of inlined file: juce_MemoryBlock.cpp ***/
  2792. BEGIN_JUCE_NAMESPACE
  2793. MemoryBlock::MemoryBlock() throw()
  2794. : size (0)
  2795. {
  2796. }
  2797. MemoryBlock::MemoryBlock (const size_t initialSize, const bool initialiseToZero)
  2798. {
  2799. if (initialSize > 0)
  2800. {
  2801. size = initialSize;
  2802. data.allocate (initialSize, initialiseToZero);
  2803. }
  2804. else
  2805. {
  2806. size = 0;
  2807. }
  2808. }
  2809. MemoryBlock::MemoryBlock (const MemoryBlock& other)
  2810. : size (other.size)
  2811. {
  2812. if (size > 0)
  2813. {
  2814. jassert (other.data != 0);
  2815. data.malloc (size);
  2816. memcpy (data, other.data, size);
  2817. }
  2818. }
  2819. MemoryBlock::MemoryBlock (const void* const dataToInitialiseFrom, const size_t sizeInBytes)
  2820. : size (jmax ((size_t) 0, sizeInBytes))
  2821. {
  2822. jassert (sizeInBytes >= 0);
  2823. if (size > 0)
  2824. {
  2825. jassert (dataToInitialiseFrom != 0); // non-zero size, but a zero pointer passed-in?
  2826. data.malloc (size);
  2827. if (dataToInitialiseFrom != 0)
  2828. memcpy (data, dataToInitialiseFrom, size);
  2829. }
  2830. }
  2831. MemoryBlock::~MemoryBlock() throw()
  2832. {
  2833. jassert (size >= 0); // should never happen
  2834. jassert (size == 0 || data != 0); // non-zero size but no data allocated?
  2835. }
  2836. MemoryBlock& MemoryBlock::operator= (const MemoryBlock& other)
  2837. {
  2838. if (this != &other)
  2839. {
  2840. setSize (other.size, false);
  2841. memcpy (data, other.data, size);
  2842. }
  2843. return *this;
  2844. }
  2845. bool MemoryBlock::operator== (const MemoryBlock& other) const throw()
  2846. {
  2847. return matches (other.data, other.size);
  2848. }
  2849. bool MemoryBlock::operator!= (const MemoryBlock& other) const throw()
  2850. {
  2851. return ! operator== (other);
  2852. }
  2853. bool MemoryBlock::matches (const void* dataToCompare, size_t dataSize) const throw()
  2854. {
  2855. return size == dataSize
  2856. && memcmp (data, dataToCompare, size) == 0;
  2857. }
  2858. // this will resize the block to this size
  2859. void MemoryBlock::setSize (const size_t newSize, const bool initialiseToZero)
  2860. {
  2861. if (size != newSize)
  2862. {
  2863. if (newSize <= 0)
  2864. {
  2865. data.free();
  2866. size = 0;
  2867. }
  2868. else
  2869. {
  2870. if (data != 0)
  2871. {
  2872. data.realloc (newSize);
  2873. if (initialiseToZero && (newSize > size))
  2874. zeromem (data + size, newSize - size);
  2875. }
  2876. else
  2877. {
  2878. data.allocate (newSize, initialiseToZero);
  2879. }
  2880. size = newSize;
  2881. }
  2882. }
  2883. }
  2884. void MemoryBlock::ensureSize (const size_t minimumSize, const bool initialiseToZero)
  2885. {
  2886. if (size < minimumSize)
  2887. setSize (minimumSize, initialiseToZero);
  2888. }
  2889. void MemoryBlock::swapWith (MemoryBlock& other) throw()
  2890. {
  2891. swapVariables (size, other.size);
  2892. data.swapWith (other.data);
  2893. }
  2894. void MemoryBlock::fillWith (const uint8 value) throw()
  2895. {
  2896. memset (data, (int) value, size);
  2897. }
  2898. void MemoryBlock::append (const void* const srcData, const size_t numBytes)
  2899. {
  2900. if (numBytes > 0)
  2901. {
  2902. const size_t oldSize = size;
  2903. setSize (size + numBytes);
  2904. memcpy (data + oldSize, srcData, numBytes);
  2905. }
  2906. }
  2907. void MemoryBlock::copyFrom (const void* const src, int offset, size_t num) throw()
  2908. {
  2909. const char* d = static_cast<const char*> (src);
  2910. if (offset < 0)
  2911. {
  2912. d -= offset;
  2913. num -= offset;
  2914. offset = 0;
  2915. }
  2916. if (offset + num > size)
  2917. num = size - offset;
  2918. if (num > 0)
  2919. memcpy (data + offset, d, num);
  2920. }
  2921. void MemoryBlock::copyTo (void* const dst, int offset, size_t num) const throw()
  2922. {
  2923. char* d = static_cast<char*> (dst);
  2924. if (offset < 0)
  2925. {
  2926. zeromem (d, -offset);
  2927. d -= offset;
  2928. num += offset;
  2929. offset = 0;
  2930. }
  2931. if (offset + num > size)
  2932. {
  2933. const size_t newNum = size - offset;
  2934. zeromem (d + newNum, num - newNum);
  2935. num = newNum;
  2936. }
  2937. if (num > 0)
  2938. memcpy (d, data + offset, num);
  2939. }
  2940. void MemoryBlock::removeSection (size_t startByte, size_t numBytesToRemove)
  2941. {
  2942. if (startByte < 0)
  2943. {
  2944. numBytesToRemove += startByte;
  2945. startByte = 0;
  2946. }
  2947. if (startByte + numBytesToRemove >= size)
  2948. {
  2949. setSize (startByte);
  2950. }
  2951. else if (numBytesToRemove > 0)
  2952. {
  2953. memmove (data + startByte,
  2954. data + startByte + numBytesToRemove,
  2955. size - (startByte + numBytesToRemove));
  2956. setSize (size - numBytesToRemove);
  2957. }
  2958. }
  2959. const String MemoryBlock::toString() const
  2960. {
  2961. return String (static_cast <const char*> (getData()), size);
  2962. }
  2963. int MemoryBlock::getBitRange (const size_t bitRangeStart, size_t numBits) const throw()
  2964. {
  2965. int res = 0;
  2966. size_t byte = bitRangeStart >> 3;
  2967. int offsetInByte = (int) bitRangeStart & 7;
  2968. size_t bitsSoFar = 0;
  2969. while (numBits > 0 && (size_t) byte < size)
  2970. {
  2971. const int bitsThisTime = jmin ((int) numBits, 8 - offsetInByte);
  2972. const int mask = (0xff >> (8 - bitsThisTime)) << offsetInByte;
  2973. res |= (((data[byte] & mask) >> offsetInByte) << bitsSoFar);
  2974. bitsSoFar += bitsThisTime;
  2975. numBits -= bitsThisTime;
  2976. ++byte;
  2977. offsetInByte = 0;
  2978. }
  2979. return res;
  2980. }
  2981. void MemoryBlock::setBitRange (const size_t bitRangeStart, size_t numBits, int bitsToSet) throw()
  2982. {
  2983. size_t byte = bitRangeStart >> 3;
  2984. int offsetInByte = (int) bitRangeStart & 7;
  2985. unsigned int mask = ~((((unsigned int) 0xffffffff) << (32 - numBits)) >> (32 - numBits));
  2986. while (numBits > 0 && (size_t) byte < size)
  2987. {
  2988. const int bitsThisTime = jmin ((int) numBits, 8 - offsetInByte);
  2989. const unsigned int tempMask = (mask << offsetInByte) | ~((((unsigned int) 0xffffffff) >> offsetInByte) << offsetInByte);
  2990. const unsigned int tempBits = bitsToSet << offsetInByte;
  2991. data[byte] = (char) ((data[byte] & tempMask) | tempBits);
  2992. ++byte;
  2993. numBits -= bitsThisTime;
  2994. bitsToSet >>= bitsThisTime;
  2995. mask >>= bitsThisTime;
  2996. offsetInByte = 0;
  2997. }
  2998. }
  2999. void MemoryBlock::loadFromHexString (const String& hex)
  3000. {
  3001. ensureSize (hex.length() >> 1);
  3002. char* dest = data;
  3003. int i = 0;
  3004. for (;;)
  3005. {
  3006. int byte = 0;
  3007. for (int loop = 2; --loop >= 0;)
  3008. {
  3009. byte <<= 4;
  3010. for (;;)
  3011. {
  3012. const juce_wchar c = hex [i++];
  3013. if (c >= '0' && c <= '9')
  3014. {
  3015. byte |= c - '0';
  3016. break;
  3017. }
  3018. else if (c >= 'a' && c <= 'z')
  3019. {
  3020. byte |= c - ('a' - 10);
  3021. break;
  3022. }
  3023. else if (c >= 'A' && c <= 'Z')
  3024. {
  3025. byte |= c - ('A' - 10);
  3026. break;
  3027. }
  3028. else if (c == 0)
  3029. {
  3030. setSize (static_cast <size_t> (dest - data));
  3031. return;
  3032. }
  3033. }
  3034. }
  3035. *dest++ = (char) byte;
  3036. }
  3037. }
  3038. const char* const MemoryBlock::encodingTable = ".ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+";
  3039. const String MemoryBlock::toBase64Encoding() const
  3040. {
  3041. const size_t numChars = ((size << 3) + 5) / 6;
  3042. String destString ((unsigned int) size); // store the length, followed by a '.', and then the data.
  3043. const int initialLen = destString.length();
  3044. destString.preallocateStorage (initialLen + 2 + numChars);
  3045. juce_wchar* d = destString;
  3046. d += initialLen;
  3047. *d++ = '.';
  3048. for (size_t i = 0; i < numChars; ++i)
  3049. *d++ = encodingTable [getBitRange (i * 6, 6)];
  3050. *d++ = 0;
  3051. return destString;
  3052. }
  3053. bool MemoryBlock::fromBase64Encoding (const String& s)
  3054. {
  3055. const int startPos = s.indexOfChar ('.') + 1;
  3056. if (startPos <= 0)
  3057. return false;
  3058. const int numBytesNeeded = s.substring (0, startPos - 1).getIntValue();
  3059. setSize (numBytesNeeded, true);
  3060. const int numChars = s.length() - startPos;
  3061. const juce_wchar* srcChars = s;
  3062. srcChars += startPos;
  3063. int pos = 0;
  3064. for (int i = 0; i < numChars; ++i)
  3065. {
  3066. const char c = (char) srcChars[i];
  3067. for (int j = 0; j < 64; ++j)
  3068. {
  3069. if (encodingTable[j] == c)
  3070. {
  3071. setBitRange (pos, 6, j);
  3072. pos += 6;
  3073. break;
  3074. }
  3075. }
  3076. }
  3077. return true;
  3078. }
  3079. END_JUCE_NAMESPACE
  3080. /*** End of inlined file: juce_MemoryBlock.cpp ***/
  3081. /*** Start of inlined file: juce_PropertySet.cpp ***/
  3082. BEGIN_JUCE_NAMESPACE
  3083. PropertySet::PropertySet (const bool ignoreCaseOfKeyNames)
  3084. : properties (ignoreCaseOfKeyNames),
  3085. fallbackProperties (0),
  3086. ignoreCaseOfKeys (ignoreCaseOfKeyNames)
  3087. {
  3088. }
  3089. PropertySet::PropertySet (const PropertySet& other)
  3090. : properties (other.properties),
  3091. fallbackProperties (other.fallbackProperties),
  3092. ignoreCaseOfKeys (other.ignoreCaseOfKeys)
  3093. {
  3094. }
  3095. PropertySet& PropertySet::operator= (const PropertySet& other)
  3096. {
  3097. properties = other.properties;
  3098. fallbackProperties = other.fallbackProperties;
  3099. ignoreCaseOfKeys = other.ignoreCaseOfKeys;
  3100. propertyChanged();
  3101. return *this;
  3102. }
  3103. PropertySet::~PropertySet()
  3104. {
  3105. }
  3106. void PropertySet::clear()
  3107. {
  3108. const ScopedLock sl (lock);
  3109. if (properties.size() > 0)
  3110. {
  3111. properties.clear();
  3112. propertyChanged();
  3113. }
  3114. }
  3115. const String PropertySet::getValue (const String& keyName,
  3116. const String& defaultValue) const throw()
  3117. {
  3118. const ScopedLock sl (lock);
  3119. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3120. if (index >= 0)
  3121. return properties.getAllValues() [index];
  3122. return fallbackProperties != 0 ? fallbackProperties->getValue (keyName, defaultValue)
  3123. : defaultValue;
  3124. }
  3125. int PropertySet::getIntValue (const String& keyName,
  3126. const int defaultValue) const throw()
  3127. {
  3128. const ScopedLock sl (lock);
  3129. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3130. if (index >= 0)
  3131. return properties.getAllValues() [index].getIntValue();
  3132. return fallbackProperties != 0 ? fallbackProperties->getIntValue (keyName, defaultValue)
  3133. : defaultValue;
  3134. }
  3135. double PropertySet::getDoubleValue (const String& keyName,
  3136. const double defaultValue) const throw()
  3137. {
  3138. const ScopedLock sl (lock);
  3139. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3140. if (index >= 0)
  3141. return properties.getAllValues()[index].getDoubleValue();
  3142. return fallbackProperties != 0 ? fallbackProperties->getDoubleValue (keyName, defaultValue)
  3143. : defaultValue;
  3144. }
  3145. bool PropertySet::getBoolValue (const String& keyName,
  3146. const bool defaultValue) const throw()
  3147. {
  3148. const ScopedLock sl (lock);
  3149. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3150. if (index >= 0)
  3151. return properties.getAllValues() [index].getIntValue() != 0;
  3152. return fallbackProperties != 0 ? fallbackProperties->getBoolValue (keyName, defaultValue)
  3153. : defaultValue;
  3154. }
  3155. XmlElement* PropertySet::getXmlValue (const String& keyName) const
  3156. {
  3157. XmlDocument doc (getValue (keyName));
  3158. return doc.getDocumentElement();
  3159. }
  3160. void PropertySet::setValue (const String& keyName, const var& v)
  3161. {
  3162. jassert (keyName.isNotEmpty()); // shouldn't use an empty key name!
  3163. if (keyName.isNotEmpty())
  3164. {
  3165. const String value (v.toString());
  3166. const ScopedLock sl (lock);
  3167. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3168. if (index < 0 || properties.getAllValues() [index] != value)
  3169. {
  3170. properties.set (keyName, value);
  3171. propertyChanged();
  3172. }
  3173. }
  3174. }
  3175. void PropertySet::removeValue (const String& keyName)
  3176. {
  3177. if (keyName.isNotEmpty())
  3178. {
  3179. const ScopedLock sl (lock);
  3180. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3181. if (index >= 0)
  3182. {
  3183. properties.remove (keyName);
  3184. propertyChanged();
  3185. }
  3186. }
  3187. }
  3188. void PropertySet::setValue (const String& keyName, const XmlElement* const xml)
  3189. {
  3190. setValue (keyName, xml == 0 ? var::null
  3191. : var (xml->createDocument (String::empty, true)));
  3192. }
  3193. bool PropertySet::containsKey (const String& keyName) const throw()
  3194. {
  3195. const ScopedLock sl (lock);
  3196. return properties.getAllKeys().contains (keyName, ignoreCaseOfKeys);
  3197. }
  3198. void PropertySet::setFallbackPropertySet (PropertySet* fallbackProperties_) throw()
  3199. {
  3200. const ScopedLock sl (lock);
  3201. fallbackProperties = fallbackProperties_;
  3202. }
  3203. XmlElement* PropertySet::createXml (const String& nodeName) const
  3204. {
  3205. const ScopedLock sl (lock);
  3206. XmlElement* const xml = new XmlElement (nodeName);
  3207. for (int i = 0; i < properties.getAllKeys().size(); ++i)
  3208. {
  3209. XmlElement* const e = xml->createNewChildElement ("VALUE");
  3210. e->setAttribute ("name", properties.getAllKeys()[i]);
  3211. e->setAttribute ("val", properties.getAllValues()[i]);
  3212. }
  3213. return xml;
  3214. }
  3215. void PropertySet::restoreFromXml (const XmlElement& xml)
  3216. {
  3217. const ScopedLock sl (lock);
  3218. clear();
  3219. forEachXmlChildElementWithTagName (xml, e, "VALUE")
  3220. {
  3221. if (e->hasAttribute ("name")
  3222. && e->hasAttribute ("val"))
  3223. {
  3224. properties.set (e->getStringAttribute ("name"),
  3225. e->getStringAttribute ("val"));
  3226. }
  3227. }
  3228. if (properties.size() > 0)
  3229. propertyChanged();
  3230. }
  3231. void PropertySet::propertyChanged()
  3232. {
  3233. }
  3234. END_JUCE_NAMESPACE
  3235. /*** End of inlined file: juce_PropertySet.cpp ***/
  3236. /*** Start of inlined file: juce_Identifier.cpp ***/
  3237. BEGIN_JUCE_NAMESPACE
  3238. StringPool& Identifier::getPool()
  3239. {
  3240. static StringPool pool;
  3241. return pool;
  3242. }
  3243. Identifier::Identifier() throw()
  3244. : name (0)
  3245. {
  3246. }
  3247. Identifier::Identifier (const Identifier& other) throw()
  3248. : name (other.name)
  3249. {
  3250. }
  3251. Identifier& Identifier::operator= (const Identifier& other) throw()
  3252. {
  3253. name = other.name;
  3254. return *this;
  3255. }
  3256. Identifier::Identifier (const String& name_)
  3257. : name (Identifier::getPool().getPooledString (name_))
  3258. {
  3259. /* An Identifier string must be suitable for use as a script variable or XML
  3260. attribute, so it can only contain this limited set of characters.. */
  3261. jassert (name_.containsOnly ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") && name_.isNotEmpty());
  3262. }
  3263. Identifier::Identifier (const char* const name_)
  3264. : name (Identifier::getPool().getPooledString (name_))
  3265. {
  3266. /* An Identifier string must be suitable for use as a script variable or XML
  3267. attribute, so it can only contain this limited set of characters.. */
  3268. jassert (toString().containsOnly ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") && toString().isNotEmpty());
  3269. }
  3270. Identifier::~Identifier()
  3271. {
  3272. }
  3273. END_JUCE_NAMESPACE
  3274. /*** End of inlined file: juce_Identifier.cpp ***/
  3275. /*** Start of inlined file: juce_Variant.cpp ***/
  3276. BEGIN_JUCE_NAMESPACE
  3277. class var::VariantType
  3278. {
  3279. public:
  3280. VariantType() {}
  3281. virtual ~VariantType() {}
  3282. virtual int toInt (const ValueUnion&) const { return 0; }
  3283. virtual double toDouble (const ValueUnion&) const { return 0; }
  3284. virtual const String toString (const ValueUnion&) const { return String::empty; }
  3285. virtual bool toBool (const ValueUnion&) const { return false; }
  3286. virtual DynamicObject* toObject (const ValueUnion&) const { return 0; }
  3287. virtual bool isVoid() const throw() { return false; }
  3288. virtual bool isInt() const throw() { return false; }
  3289. virtual bool isBool() const throw() { return false; }
  3290. virtual bool isDouble() const throw() { return false; }
  3291. virtual bool isString() const throw() { return false; }
  3292. virtual bool isObject() const throw() { return false; }
  3293. virtual bool isMethod() const throw() { return false; }
  3294. virtual void cleanUp (ValueUnion&) const throw() {}
  3295. virtual void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest = source; }
  3296. virtual bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw() = 0;
  3297. virtual void writeToStream (const ValueUnion& data, OutputStream& output) const = 0;
  3298. };
  3299. class var::VariantType_Void : public var::VariantType
  3300. {
  3301. public:
  3302. VariantType_Void() {}
  3303. static const VariantType_Void* getInstance() { static const VariantType_Void i; return &i; }
  3304. bool isVoid() const throw() { return true; }
  3305. bool equals (const ValueUnion&, const ValueUnion&, const VariantType& otherType) const throw() { return otherType.isVoid(); }
  3306. void writeToStream (const ValueUnion&, OutputStream& output) const { output.writeCompressedInt (0); }
  3307. };
  3308. class var::VariantType_Int : public var::VariantType
  3309. {
  3310. public:
  3311. VariantType_Int() {}
  3312. static const VariantType_Int* getInstance() { static const VariantType_Int i; return &i; }
  3313. int toInt (const ValueUnion& data) const { return data.intValue; };
  3314. double toDouble (const ValueUnion& data) const { return (double) data.intValue; }
  3315. const String toString (const ValueUnion& data) const { return String (data.intValue); }
  3316. bool toBool (const ValueUnion& data) const { return data.intValue != 0; }
  3317. bool isInt() const throw() { return true; }
  3318. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3319. {
  3320. return otherType.toInt (otherData) == data.intValue;
  3321. }
  3322. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3323. {
  3324. output.writeCompressedInt (5);
  3325. output.writeByte (1);
  3326. output.writeInt (data.intValue);
  3327. }
  3328. };
  3329. class var::VariantType_Double : public var::VariantType
  3330. {
  3331. public:
  3332. VariantType_Double() {}
  3333. static const VariantType_Double* getInstance() { static const VariantType_Double i; return &i; }
  3334. int toInt (const ValueUnion& data) const { return (int) data.doubleValue; };
  3335. double toDouble (const ValueUnion& data) const { return data.doubleValue; }
  3336. const String toString (const ValueUnion& data) const { return String (data.doubleValue); }
  3337. bool toBool (const ValueUnion& data) const { return data.doubleValue != 0; }
  3338. bool isDouble() const throw() { return true; }
  3339. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3340. {
  3341. return otherType.toDouble (otherData) == data.doubleValue;
  3342. }
  3343. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3344. {
  3345. output.writeCompressedInt (9);
  3346. output.writeByte (4);
  3347. output.writeDouble (data.doubleValue);
  3348. }
  3349. };
  3350. class var::VariantType_Bool : public var::VariantType
  3351. {
  3352. public:
  3353. VariantType_Bool() {}
  3354. static const VariantType_Bool* getInstance() { static const VariantType_Bool i; return &i; }
  3355. int toInt (const ValueUnion& data) const { return data.boolValue ? 1 : 0; };
  3356. double toDouble (const ValueUnion& data) const { return data.boolValue ? 1.0 : 0.0; }
  3357. const String toString (const ValueUnion& data) const { return String::charToString (data.boolValue ? '1' : '0'); }
  3358. bool toBool (const ValueUnion& data) const { return data.boolValue; }
  3359. bool isBool() const throw() { return true; }
  3360. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3361. {
  3362. return otherType.toBool (otherData) == data.boolValue;
  3363. }
  3364. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3365. {
  3366. output.writeCompressedInt (1);
  3367. output.writeByte (data.boolValue ? 2 : 3);
  3368. }
  3369. };
  3370. class var::VariantType_String : public var::VariantType
  3371. {
  3372. public:
  3373. VariantType_String() {}
  3374. static const VariantType_String* getInstance() { static const VariantType_String i; return &i; }
  3375. void cleanUp (ValueUnion& data) const throw() { delete data.stringValue; }
  3376. void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest.stringValue = new String (*source.stringValue); }
  3377. int toInt (const ValueUnion& data) const { return data.stringValue->getIntValue(); };
  3378. double toDouble (const ValueUnion& data) const { return data.stringValue->getDoubleValue(); }
  3379. const String toString (const ValueUnion& data) const { return *data.stringValue; }
  3380. bool toBool (const ValueUnion& data) const { return data.stringValue->getIntValue() != 0
  3381. || data.stringValue->trim().equalsIgnoreCase ("true")
  3382. || data.stringValue->trim().equalsIgnoreCase ("yes"); }
  3383. bool isString() const throw() { return true; }
  3384. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3385. {
  3386. return otherType.toString (otherData) == *data.stringValue;
  3387. }
  3388. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3389. {
  3390. const int len = data.stringValue->getNumBytesAsUTF8() + 1;
  3391. output.writeCompressedInt (len + 1);
  3392. output.writeByte (5);
  3393. HeapBlock<char> temp (len);
  3394. data.stringValue->copyToUTF8 (temp, len);
  3395. output.write (temp, len);
  3396. }
  3397. };
  3398. class var::VariantType_Object : public var::VariantType
  3399. {
  3400. public:
  3401. VariantType_Object() {}
  3402. static const VariantType_Object* getInstance() { static const VariantType_Object i; return &i; }
  3403. void cleanUp (ValueUnion& data) const throw() { if (data.objectValue != 0) data.objectValue->decReferenceCount(); }
  3404. void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest.objectValue = source.objectValue; if (dest.objectValue != 0) dest.objectValue->incReferenceCount(); }
  3405. const String toString (const ValueUnion& data) const { return "Object 0x" + String::toHexString ((int) (pointer_sized_int) data.objectValue); }
  3406. bool toBool (const ValueUnion& data) const { return data.objectValue != 0; }
  3407. DynamicObject* toObject (const ValueUnion& data) const { return data.objectValue; }
  3408. bool isObject() const throw() { return true; }
  3409. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3410. {
  3411. return otherType.toObject (otherData) == data.objectValue;
  3412. }
  3413. void writeToStream (const ValueUnion&, OutputStream& output) const
  3414. {
  3415. jassertfalse; // Can't write an object to a stream!
  3416. output.writeCompressedInt (0);
  3417. }
  3418. };
  3419. class var::VariantType_Method : public var::VariantType
  3420. {
  3421. public:
  3422. VariantType_Method() {}
  3423. static const VariantType_Method* getInstance() { static const VariantType_Method i; return &i; }
  3424. const String toString (const ValueUnion&) const { return "Method"; }
  3425. bool toBool (const ValueUnion& data) const { return data.methodValue != 0; }
  3426. bool isMethod() const throw() { return true; }
  3427. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3428. {
  3429. return otherType.isMethod() && otherData.methodValue == data.methodValue;
  3430. }
  3431. void writeToStream (const ValueUnion&, OutputStream& output) const
  3432. {
  3433. jassertfalse; // Can't write a method to a stream!
  3434. output.writeCompressedInt (0);
  3435. }
  3436. };
  3437. var::var() throw()
  3438. : type (VariantType_Void::getInstance())
  3439. {
  3440. }
  3441. var::~var() throw()
  3442. {
  3443. type->cleanUp (value);
  3444. }
  3445. const var var::null;
  3446. var::var (const var& valueToCopy) : type (valueToCopy.type)
  3447. {
  3448. type->createCopy (value, valueToCopy.value);
  3449. }
  3450. var::var (const int value_) throw() : type (VariantType_Int::getInstance())
  3451. {
  3452. value.intValue = value_;
  3453. }
  3454. var::var (const bool value_) throw() : type (VariantType_Bool::getInstance())
  3455. {
  3456. value.boolValue = value_;
  3457. }
  3458. var::var (const double value_) throw() : type (VariantType_Double::getInstance())
  3459. {
  3460. value.doubleValue = value_;
  3461. }
  3462. var::var (const String& value_) : type (VariantType_String::getInstance())
  3463. {
  3464. value.stringValue = new String (value_);
  3465. }
  3466. var::var (const char* const value_) : type (VariantType_String::getInstance())
  3467. {
  3468. value.stringValue = new String (value_);
  3469. }
  3470. var::var (const juce_wchar* const value_) : type (VariantType_String::getInstance())
  3471. {
  3472. value.stringValue = new String (value_);
  3473. }
  3474. var::var (DynamicObject* const object) : type (VariantType_Object::getInstance())
  3475. {
  3476. value.objectValue = object;
  3477. if (object != 0)
  3478. object->incReferenceCount();
  3479. }
  3480. var::var (MethodFunction method_) throw() : type (VariantType_Method::getInstance())
  3481. {
  3482. value.methodValue = method_;
  3483. }
  3484. bool var::isVoid() const throw() { return type->isVoid(); }
  3485. bool var::isInt() const throw() { return type->isInt(); }
  3486. bool var::isBool() const throw() { return type->isBool(); }
  3487. bool var::isDouble() const throw() { return type->isDouble(); }
  3488. bool var::isString() const throw() { return type->isString(); }
  3489. bool var::isObject() const throw() { return type->isObject(); }
  3490. bool var::isMethod() const throw() { return type->isMethod(); }
  3491. var::operator int() const { return type->toInt (value); }
  3492. var::operator bool() const { return type->toBool (value); }
  3493. var::operator float() const { return (float) type->toDouble (value); }
  3494. var::operator double() const { return type->toDouble (value); }
  3495. const String var::toString() const { return type->toString (value); }
  3496. var::operator const String() const { return type->toString (value); }
  3497. DynamicObject* var::getObject() const { return type->toObject (value); }
  3498. void var::swapWith (var& other) throw()
  3499. {
  3500. swapVariables (type, other.type);
  3501. swapVariables (value, other.value);
  3502. }
  3503. var& var::operator= (const var& newValue) { type->cleanUp (value); type = newValue.type; type->createCopy (value, newValue.value); return *this; }
  3504. var& var::operator= (int newValue) { var v (newValue); swapWith (v); return *this; }
  3505. var& var::operator= (bool newValue) { var v (newValue); swapWith (v); return *this; }
  3506. var& var::operator= (double newValue) { var v (newValue); swapWith (v); return *this; }
  3507. var& var::operator= (const char* newValue) { var v (newValue); swapWith (v); return *this; }
  3508. var& var::operator= (const juce_wchar* newValue) { var v (newValue); swapWith (v); return *this; }
  3509. var& var::operator= (const String& newValue) { var v (newValue); swapWith (v); return *this; }
  3510. var& var::operator= (DynamicObject* newValue) { var v (newValue); swapWith (v); return *this; }
  3511. var& var::operator= (MethodFunction newValue) { var v (newValue); swapWith (v); return *this; }
  3512. bool var::equals (const var& other) const throw()
  3513. {
  3514. return type->equals (value, other.value, *other.type);
  3515. }
  3516. bool operator== (const var& v1, const var& v2) throw() { return v1.equals (v2); }
  3517. bool operator!= (const var& v1, const var& v2) throw() { return ! v1.equals (v2); }
  3518. bool operator== (const var& v1, const String& v2) throw() { return v1.toString() == v2; }
  3519. bool operator!= (const var& v1, const String& v2) throw() { return v1.toString() != v2; }
  3520. void var::writeToStream (OutputStream& output) const
  3521. {
  3522. type->writeToStream (value, output);
  3523. }
  3524. const var var::readFromStream (InputStream& input)
  3525. {
  3526. const int numBytes = input.readCompressedInt();
  3527. if (numBytes > 0)
  3528. {
  3529. switch (input.readByte())
  3530. {
  3531. case 1: return var (input.readInt());
  3532. case 2: return var (true);
  3533. case 3: return var (false);
  3534. case 4: return var (input.readDouble());
  3535. case 5:
  3536. {
  3537. MemoryOutputStream mo;
  3538. mo.writeFromInputStream (input, numBytes - 1);
  3539. return var (mo.toUTF8());
  3540. }
  3541. default: input.skipNextBytes (numBytes - 1); break;
  3542. }
  3543. }
  3544. return var::null;
  3545. }
  3546. const var var::operator[] (const Identifier& propertyName) const
  3547. {
  3548. DynamicObject* const o = getObject();
  3549. return o != 0 ? o->getProperty (propertyName) : var::null;
  3550. }
  3551. const var var::invoke (const Identifier& method, const var* arguments, int numArguments) const
  3552. {
  3553. DynamicObject* const o = getObject();
  3554. return o != 0 ? o->invokeMethod (method, arguments, numArguments) : var::null;
  3555. }
  3556. const var var::invoke (const var& targetObject, const var* arguments, int numArguments) const
  3557. {
  3558. if (isMethod())
  3559. {
  3560. DynamicObject* const target = targetObject.getObject();
  3561. if (target != 0)
  3562. return (target->*(value.methodValue)) (arguments, numArguments);
  3563. }
  3564. return var::null;
  3565. }
  3566. const var var::call (const Identifier& method) const
  3567. {
  3568. return invoke (method, 0, 0);
  3569. }
  3570. const var var::call (const Identifier& method, const var& arg1) const
  3571. {
  3572. return invoke (method, &arg1, 1);
  3573. }
  3574. const var var::call (const Identifier& method, const var& arg1, const var& arg2) const
  3575. {
  3576. var args[] = { arg1, arg2 };
  3577. return invoke (method, args, 2);
  3578. }
  3579. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3)
  3580. {
  3581. var args[] = { arg1, arg2, arg3 };
  3582. return invoke (method, args, 3);
  3583. }
  3584. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4) const
  3585. {
  3586. var args[] = { arg1, arg2, arg3, arg4 };
  3587. return invoke (method, args, 4);
  3588. }
  3589. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4, const var& arg5) const
  3590. {
  3591. var args[] = { arg1, arg2, arg3, arg4, arg5 };
  3592. return invoke (method, args, 5);
  3593. }
  3594. END_JUCE_NAMESPACE
  3595. /*** End of inlined file: juce_Variant.cpp ***/
  3596. /*** Start of inlined file: juce_NamedValueSet.cpp ***/
  3597. BEGIN_JUCE_NAMESPACE
  3598. NamedValueSet::NamedValue::NamedValue() throw()
  3599. {
  3600. }
  3601. inline NamedValueSet::NamedValue::NamedValue (const Identifier& name_, const var& value_)
  3602. : name (name_), value (value_)
  3603. {
  3604. }
  3605. bool NamedValueSet::NamedValue::operator== (const NamedValueSet::NamedValue& other) const throw()
  3606. {
  3607. return name == other.name && value == other.value;
  3608. }
  3609. NamedValueSet::NamedValueSet() throw()
  3610. {
  3611. }
  3612. NamedValueSet::NamedValueSet (const NamedValueSet& other)
  3613. : values (other.values)
  3614. {
  3615. }
  3616. NamedValueSet& NamedValueSet::operator= (const NamedValueSet& other)
  3617. {
  3618. values = other.values;
  3619. return *this;
  3620. }
  3621. NamedValueSet::~NamedValueSet()
  3622. {
  3623. }
  3624. bool NamedValueSet::operator== (const NamedValueSet& other) const
  3625. {
  3626. return values == other.values;
  3627. }
  3628. bool NamedValueSet::operator!= (const NamedValueSet& other) const
  3629. {
  3630. return ! operator== (other);
  3631. }
  3632. int NamedValueSet::size() const throw()
  3633. {
  3634. return values.size();
  3635. }
  3636. const var& NamedValueSet::operator[] (const Identifier& name) const
  3637. {
  3638. for (int i = values.size(); --i >= 0;)
  3639. {
  3640. const NamedValue& v = values.getReference(i);
  3641. if (v.name == name)
  3642. return v.value;
  3643. }
  3644. return var::null;
  3645. }
  3646. const var NamedValueSet::getWithDefault (const Identifier& name, const var& defaultReturnValue) const
  3647. {
  3648. const var* v = getVarPointer (name);
  3649. return v != 0 ? *v : defaultReturnValue;
  3650. }
  3651. var* NamedValueSet::getVarPointer (const Identifier& name) const
  3652. {
  3653. for (int i = values.size(); --i >= 0;)
  3654. {
  3655. NamedValue& v = values.getReference(i);
  3656. if (v.name == name)
  3657. return &(v.value);
  3658. }
  3659. return 0;
  3660. }
  3661. bool NamedValueSet::set (const Identifier& name, const var& newValue)
  3662. {
  3663. for (int i = values.size(); --i >= 0;)
  3664. {
  3665. NamedValue& v = values.getReference(i);
  3666. if (v.name == name)
  3667. {
  3668. if (v.value == newValue)
  3669. return false;
  3670. v.value = newValue;
  3671. return true;
  3672. }
  3673. }
  3674. values.add (NamedValue (name, newValue));
  3675. return true;
  3676. }
  3677. bool NamedValueSet::contains (const Identifier& name) const
  3678. {
  3679. return getVarPointer (name) != 0;
  3680. }
  3681. bool NamedValueSet::remove (const Identifier& name)
  3682. {
  3683. for (int i = values.size(); --i >= 0;)
  3684. {
  3685. if (values.getReference(i).name == name)
  3686. {
  3687. values.remove (i);
  3688. return true;
  3689. }
  3690. }
  3691. return false;
  3692. }
  3693. const Identifier NamedValueSet::getName (const int index) const
  3694. {
  3695. jassert (((unsigned int) index) < (unsigned int) values.size());
  3696. return values [index].name;
  3697. }
  3698. const var NamedValueSet::getValueAt (const int index) const
  3699. {
  3700. jassert (((unsigned int) index) < (unsigned int) values.size());
  3701. return values [index].value;
  3702. }
  3703. void NamedValueSet::clear()
  3704. {
  3705. values.clear();
  3706. }
  3707. END_JUCE_NAMESPACE
  3708. /*** End of inlined file: juce_NamedValueSet.cpp ***/
  3709. /*** Start of inlined file: juce_DynamicObject.cpp ***/
  3710. BEGIN_JUCE_NAMESPACE
  3711. DynamicObject::DynamicObject()
  3712. {
  3713. }
  3714. DynamicObject::~DynamicObject()
  3715. {
  3716. }
  3717. bool DynamicObject::hasProperty (const Identifier& propertyName) const
  3718. {
  3719. var* const v = properties.getVarPointer (propertyName);
  3720. return v != 0 && ! v->isMethod();
  3721. }
  3722. const var DynamicObject::getProperty (const Identifier& propertyName) const
  3723. {
  3724. return properties [propertyName];
  3725. }
  3726. void DynamicObject::setProperty (const Identifier& propertyName, const var& newValue)
  3727. {
  3728. properties.set (propertyName, newValue);
  3729. }
  3730. void DynamicObject::removeProperty (const Identifier& propertyName)
  3731. {
  3732. properties.remove (propertyName);
  3733. }
  3734. bool DynamicObject::hasMethod (const Identifier& methodName) const
  3735. {
  3736. return getProperty (methodName).isMethod();
  3737. }
  3738. const var DynamicObject::invokeMethod (const Identifier& methodName,
  3739. const var* parameters,
  3740. int numParameters)
  3741. {
  3742. return properties [methodName].invoke (var (this), parameters, numParameters);
  3743. }
  3744. void DynamicObject::setMethod (const Identifier& name,
  3745. var::MethodFunction methodFunction)
  3746. {
  3747. properties.set (name, var (methodFunction));
  3748. }
  3749. void DynamicObject::clear()
  3750. {
  3751. properties.clear();
  3752. }
  3753. END_JUCE_NAMESPACE
  3754. /*** End of inlined file: juce_DynamicObject.cpp ***/
  3755. /*** Start of inlined file: juce_Expression.cpp ***/
  3756. BEGIN_JUCE_NAMESPACE
  3757. class Expression::Helpers
  3758. {
  3759. public:
  3760. typedef ReferenceCountedObjectPtr<Term> TermPtr;
  3761. class Constant : public Term
  3762. {
  3763. public:
  3764. Constant (const double value_, bool isResolutionTarget_)
  3765. : value (value_), isResolutionTarget (isResolutionTarget_) {}
  3766. Type getType() const throw() { return constantType; }
  3767. Term* clone() const { return new Constant (value, isResolutionTarget); }
  3768. double evaluate (const EvaluationContext&, int) const { return value; }
  3769. int getNumInputs() const { return 0; }
  3770. Term* getInput (int) const { return 0; }
  3771. const TermPtr negated()
  3772. {
  3773. return new Constant (-value, isResolutionTarget);
  3774. }
  3775. const String toString() const
  3776. {
  3777. if (isResolutionTarget)
  3778. return "@" + String (value);
  3779. return String (value);
  3780. }
  3781. double value;
  3782. bool isResolutionTarget;
  3783. };
  3784. class Symbol : public Term
  3785. {
  3786. public:
  3787. explicit Symbol (const String& symbol_)
  3788. : mainSymbol (symbol_.upToFirstOccurrenceOf (".", false, false).trim()),
  3789. member (symbol_.fromFirstOccurrenceOf (".", false, false).trim())
  3790. {}
  3791. Symbol (const String& symbol_, const String& member_)
  3792. : mainSymbol (symbol_),
  3793. member (member_)
  3794. {}
  3795. double evaluate (const EvaluationContext& c, int recursionDepth) const
  3796. {
  3797. if (++recursionDepth > 256)
  3798. throw EvaluationError ("Recursive symbol references");
  3799. try
  3800. {
  3801. return c.getSymbolValue (mainSymbol, member).term->evaluate (c, recursionDepth);
  3802. }
  3803. catch (...)
  3804. {}
  3805. return 0;
  3806. }
  3807. Type getType() const throw() { return symbolType; }
  3808. Term* clone() const { return new Symbol (mainSymbol, member); }
  3809. int getNumInputs() const { return 0; }
  3810. Term* getInput (int) const { return 0; }
  3811. const String getSymbolName() const { return toString(); }
  3812. const String toString() const
  3813. {
  3814. return member.isEmpty() ? mainSymbol
  3815. : mainSymbol + "." + member;
  3816. }
  3817. bool referencesSymbol (const String& s, const EvaluationContext* c, int recursionDepth) const
  3818. {
  3819. if (s == mainSymbol)
  3820. return true;
  3821. if (++recursionDepth > 256)
  3822. throw EvaluationError ("Recursive symbol references");
  3823. try
  3824. {
  3825. return c != 0 && c->getSymbolValue (mainSymbol, member).term->referencesSymbol (s, c, recursionDepth);
  3826. }
  3827. catch (EvaluationError&)
  3828. {
  3829. return false;
  3830. }
  3831. }
  3832. String mainSymbol, member;
  3833. };
  3834. class Function : public Term
  3835. {
  3836. public:
  3837. Function (const String& functionName_, const ReferenceCountedArray<Term>& parameters_)
  3838. : functionName (functionName_), parameters (parameters_)
  3839. {}
  3840. Term* clone() const { return new Function (functionName, parameters); }
  3841. double evaluate (const EvaluationContext& c, int recursionDepth) const
  3842. {
  3843. HeapBlock <double> params (parameters.size());
  3844. for (int i = 0; i < parameters.size(); ++i)
  3845. params[i] = parameters.getUnchecked(i)->evaluate (c, recursionDepth);
  3846. return c.evaluateFunction (functionName, params, parameters.size());
  3847. }
  3848. Type getType() const throw() { return functionType; }
  3849. int getInputIndexFor (const Term* possibleInput) const { return parameters.indexOf (possibleInput); }
  3850. int getNumInputs() const { return parameters.size(); }
  3851. Term* getInput (int i) const { return parameters [i]; }
  3852. const String getFunctionName() const { return functionName; }
  3853. bool referencesSymbol (const String& s, const EvaluationContext* c, int recursionDepth) const
  3854. {
  3855. for (int i = 0; i < parameters.size(); ++i)
  3856. if (parameters.getUnchecked(i)->referencesSymbol (s, c, recursionDepth))
  3857. return true;
  3858. return false;
  3859. }
  3860. const String toString() const
  3861. {
  3862. if (parameters.size() == 0)
  3863. return functionName + "()";
  3864. String s (functionName + " (");
  3865. for (int i = 0; i < parameters.size(); ++i)
  3866. {
  3867. s << parameters.getUnchecked(i)->toString();
  3868. if (i < parameters.size() - 1)
  3869. s << ", ";
  3870. }
  3871. s << ')';
  3872. return s;
  3873. }
  3874. const String functionName;
  3875. ReferenceCountedArray<Term> parameters;
  3876. };
  3877. class Negate : public Term
  3878. {
  3879. public:
  3880. Negate (const TermPtr& input_) : input (input_)
  3881. {
  3882. jassert (input_ != 0);
  3883. }
  3884. Type getType() const throw() { return operatorType; }
  3885. int getInputIndexFor (const Term* possibleInput) const { return possibleInput == input ? 0 : -1; }
  3886. int getNumInputs() const { return 1; }
  3887. Term* getInput (int index) const { return index == 0 ? static_cast<Term*> (input) : 0; }
  3888. Term* clone() const { return new Negate (input->clone()); }
  3889. double evaluate (const EvaluationContext& c, int recursionDepth) const { return -input->evaluate (c, recursionDepth); }
  3890. const String getFunctionName() const { return "-"; }
  3891. const TermPtr negated()
  3892. {
  3893. return input;
  3894. }
  3895. const TermPtr createTermToEvaluateInput (const EvaluationContext& context, const Term* input_, double overallTarget, Term* topLevelTerm) const
  3896. {
  3897. (void) input_;
  3898. jassert (input_ == input);
  3899. const Term* const dest = findDestinationFor (topLevelTerm, this);
  3900. return new Negate (dest == 0 ? new Constant (overallTarget, false)
  3901. : dest->createTermToEvaluateInput (context, this, overallTarget, topLevelTerm));
  3902. }
  3903. const String toString() const
  3904. {
  3905. if (input->getOperatorPrecedence() > 0)
  3906. return "-(" + input->toString() + ")";
  3907. else
  3908. return "-" + input->toString();
  3909. }
  3910. bool referencesSymbol (const String& s, const EvaluationContext* c, int recursionDepth) const
  3911. {
  3912. return input->referencesSymbol (s, c, recursionDepth);
  3913. }
  3914. private:
  3915. const TermPtr input;
  3916. };
  3917. class BinaryTerm : public Term
  3918. {
  3919. public:
  3920. BinaryTerm (Term* const left_, Term* const right_) : left (left_), right (right_)
  3921. {
  3922. jassert (left_ != 0 && right_ != 0);
  3923. }
  3924. int getInputIndexFor (const Term* possibleInput) const
  3925. {
  3926. return possibleInput == left ? 0 : (possibleInput == right ? 1 : -1);
  3927. }
  3928. Type getType() const throw() { return operatorType; }
  3929. int getNumInputs() const { return 2; }
  3930. Term* getInput (int index) const { return index == 0 ? static_cast<Term*> (left) : (index == 1 ? static_cast<Term*> (right) : 0); }
  3931. bool referencesSymbol (const String& s, const EvaluationContext* c, int recursionDepth) const
  3932. {
  3933. return left->referencesSymbol (s, c, recursionDepth)
  3934. || right->referencesSymbol (s, c, recursionDepth);
  3935. }
  3936. const String toString() const
  3937. {
  3938. String s;
  3939. const int ourPrecendence = getOperatorPrecedence();
  3940. if (left->getOperatorPrecedence() > ourPrecendence)
  3941. s << '(' << left->toString() << ')';
  3942. else
  3943. s = left->toString();
  3944. s << ' ' << getFunctionName() << ' ';
  3945. if (right->getOperatorPrecedence() >= ourPrecendence)
  3946. s << '(' << right->toString() << ')';
  3947. else
  3948. s << right->toString();
  3949. return s;
  3950. }
  3951. protected:
  3952. const TermPtr left, right;
  3953. const TermPtr createDestinationTerm (const EvaluationContext& context, const Term* input, double overallTarget, Term* topLevelTerm) const
  3954. {
  3955. jassert (input == left || input == right);
  3956. if (input != left && input != right)
  3957. return 0;
  3958. const Term* const dest = findDestinationFor (topLevelTerm, this);
  3959. if (dest == 0)
  3960. return new Constant (overallTarget, false);
  3961. return dest->createTermToEvaluateInput (context, this, overallTarget, topLevelTerm);
  3962. }
  3963. };
  3964. class Add : public BinaryTerm
  3965. {
  3966. public:
  3967. Add (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  3968. Term* clone() const { return new Add (left->clone(), right->clone()); }
  3969. double evaluate (const EvaluationContext& c, int recursionDepth) const { return left->evaluate (c, recursionDepth) + right->evaluate (c, recursionDepth); }
  3970. int getOperatorPrecedence() const { return 2; }
  3971. const String getFunctionName() const { return "+"; }
  3972. const TermPtr createTermToEvaluateInput (const EvaluationContext& c, const Term* input, double overallTarget, Term* topLevelTerm) const
  3973. {
  3974. const TermPtr newDest (createDestinationTerm (c, input, overallTarget, topLevelTerm));
  3975. if (newDest == 0)
  3976. return 0;
  3977. return new Subtract (newDest, (input == left ? right : left)->clone());
  3978. }
  3979. private:
  3980. Add (const Add&);
  3981. Add& operator= (const Add&);
  3982. };
  3983. class Subtract : public BinaryTerm
  3984. {
  3985. public:
  3986. Subtract (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  3987. Term* clone() const { return new Subtract (left->clone(), right->clone()); }
  3988. double evaluate (const EvaluationContext& c, int recursionDepth) const { return left->evaluate (c, recursionDepth) - right->evaluate (c, recursionDepth); }
  3989. int getOperatorPrecedence() const { return 2; }
  3990. const String getFunctionName() const { return "-"; }
  3991. const TermPtr createTermToEvaluateInput (const EvaluationContext& c, const Term* input, double overallTarget, Term* topLevelTerm) const
  3992. {
  3993. const TermPtr newDest (createDestinationTerm (c, input, overallTarget, topLevelTerm));
  3994. if (newDest == 0)
  3995. return 0;
  3996. if (input == left)
  3997. return new Add (newDest, right->clone());
  3998. else
  3999. return new Subtract (left->clone(), newDest);
  4000. }
  4001. private:
  4002. Subtract (const Subtract&);
  4003. Subtract& operator= (const Subtract&);
  4004. };
  4005. class Multiply : public BinaryTerm
  4006. {
  4007. public:
  4008. Multiply (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  4009. Term* clone() const { return new Multiply (left->clone(), right->clone()); }
  4010. double evaluate (const EvaluationContext& c, int recursionDepth) const { return left->evaluate (c, recursionDepth) * right->evaluate (c, recursionDepth); }
  4011. const String getFunctionName() const { return "*"; }
  4012. int getOperatorPrecedence() const { return 1; }
  4013. const TermPtr createTermToEvaluateInput (const EvaluationContext& c, const Term* input, double overallTarget, Term* topLevelTerm) const
  4014. {
  4015. const TermPtr newDest (createDestinationTerm (c, input, overallTarget, topLevelTerm));
  4016. if (newDest == 0)
  4017. return 0;
  4018. return new Divide (newDest, (input == left ? right : left)->clone());
  4019. }
  4020. private:
  4021. Multiply (const Multiply&);
  4022. Multiply& operator= (const Multiply&);
  4023. };
  4024. class Divide : public BinaryTerm
  4025. {
  4026. public:
  4027. Divide (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  4028. Term* clone() const { return new Divide (left->clone(), right->clone()); }
  4029. double evaluate (const EvaluationContext& c, int recursionDepth) const { return left->evaluate (c, recursionDepth) / right->evaluate (c, recursionDepth); }
  4030. const String getFunctionName() const { return "/"; }
  4031. int getOperatorPrecedence() const { return 1; }
  4032. const TermPtr createTermToEvaluateInput (const EvaluationContext& c, const Term* input, double overallTarget, Term* topLevelTerm) const
  4033. {
  4034. const TermPtr newDest (createDestinationTerm (c, input, overallTarget, topLevelTerm));
  4035. if (newDest == 0)
  4036. return 0;
  4037. if (input == left)
  4038. return new Multiply (newDest, right->clone());
  4039. else
  4040. return new Divide (left->clone(), newDest);
  4041. }
  4042. private:
  4043. Divide (const Divide&);
  4044. Divide& operator= (const Divide&);
  4045. };
  4046. static Term* findDestinationFor (Term* const topLevel, const Term* const inputTerm)
  4047. {
  4048. const int inputIndex = topLevel->getInputIndexFor (inputTerm);
  4049. if (inputIndex >= 0)
  4050. return topLevel;
  4051. for (int i = topLevel->getNumInputs(); --i >= 0;)
  4052. {
  4053. Term* t = findDestinationFor (topLevel->getInput (i), inputTerm);
  4054. if (t != 0)
  4055. return t;
  4056. }
  4057. return 0;
  4058. }
  4059. static Constant* findTermToAdjust (Term* const term, const bool mustBeFlagged)
  4060. {
  4061. Constant* c = dynamic_cast<Constant*> (term);
  4062. if (c != 0 && (c->isResolutionTarget || ! mustBeFlagged))
  4063. return c;
  4064. if (dynamic_cast<Function*> (term) != 0)
  4065. return 0;
  4066. int i;
  4067. const int numIns = term->getNumInputs();
  4068. for (i = 0; i < numIns; ++i)
  4069. {
  4070. Constant* c = dynamic_cast<Constant*> (term->getInput (i));
  4071. if (c != 0 && (c->isResolutionTarget || ! mustBeFlagged))
  4072. return c;
  4073. }
  4074. for (i = 0; i < numIns; ++i)
  4075. {
  4076. Constant* c = findTermToAdjust (term->getInput (i), mustBeFlagged);
  4077. if (c != 0)
  4078. return c;
  4079. }
  4080. return 0;
  4081. }
  4082. static bool containsAnySymbols (const Term* const t)
  4083. {
  4084. if (dynamic_cast <const Symbol*> (t) != 0)
  4085. return true;
  4086. for (int i = t->getNumInputs(); --i >= 0;)
  4087. if (containsAnySymbols (t->getInput (i)))
  4088. return true;
  4089. return false;
  4090. }
  4091. static bool renameSymbol (Term* const t, const String& oldName, const String& newName)
  4092. {
  4093. Symbol* const sym = dynamic_cast <Symbol*> (t);
  4094. if (sym != 0 && sym->mainSymbol == oldName)
  4095. {
  4096. sym->mainSymbol = newName;
  4097. return true;
  4098. }
  4099. bool anyChanged = false;
  4100. for (int i = t->getNumInputs(); --i >= 0;)
  4101. if (renameSymbol (t->getInput (i), oldName, newName))
  4102. anyChanged = true;
  4103. return anyChanged;
  4104. }
  4105. class Parser
  4106. {
  4107. public:
  4108. Parser (const String& stringToParse, int& textIndex_)
  4109. : textString (stringToParse), textIndex (textIndex_)
  4110. {
  4111. text = textString;
  4112. }
  4113. const TermPtr readExpression()
  4114. {
  4115. TermPtr lhs (readMultiplyOrDivideExpression());
  4116. char opType;
  4117. while (lhs != 0 && readOperator ("+-", &opType))
  4118. {
  4119. TermPtr rhs (readMultiplyOrDivideExpression());
  4120. if (rhs == 0)
  4121. throw ParseError ("Expected expression after \"" + String::charToString (opType) + "\"");
  4122. if (opType == '+')
  4123. lhs = new Add (lhs, rhs);
  4124. else
  4125. lhs = new Subtract (lhs, rhs);
  4126. }
  4127. return lhs;
  4128. }
  4129. private:
  4130. const String textString;
  4131. const juce_wchar* text;
  4132. int& textIndex;
  4133. static inline bool isDecimalDigit (const juce_wchar c) throw()
  4134. {
  4135. return c >= '0' && c <= '9';
  4136. }
  4137. void skipWhitespace (int& i)
  4138. {
  4139. while (CharacterFunctions::isWhitespace (text [i]))
  4140. ++i;
  4141. }
  4142. bool readChar (const juce_wchar required)
  4143. {
  4144. if (text[textIndex] == required)
  4145. {
  4146. ++textIndex;
  4147. return true;
  4148. }
  4149. return false;
  4150. }
  4151. bool readOperator (const char* ops, char* const opType = 0)
  4152. {
  4153. skipWhitespace (textIndex);
  4154. while (*ops != 0)
  4155. {
  4156. if (readChar (*ops))
  4157. {
  4158. if (opType != 0)
  4159. *opType = *ops;
  4160. return true;
  4161. }
  4162. ++ops;
  4163. }
  4164. return false;
  4165. }
  4166. bool readIdentifier (String& identifier)
  4167. {
  4168. skipWhitespace (textIndex);
  4169. int i = textIndex;
  4170. if (CharacterFunctions::isLetter (text[i]) || text[i] == '_')
  4171. {
  4172. ++i;
  4173. while (CharacterFunctions::isLetterOrDigit (text[i]) || text[i] == '_' || text[i] == '.')
  4174. ++i;
  4175. }
  4176. if (i > textIndex)
  4177. {
  4178. identifier = String (text + textIndex, i - textIndex);
  4179. textIndex = i;
  4180. return true;
  4181. }
  4182. return false;
  4183. }
  4184. Term* readNumber()
  4185. {
  4186. skipWhitespace (textIndex);
  4187. int i = textIndex;
  4188. const bool isResolutionTarget = (text[i] == '@');
  4189. if (isResolutionTarget)
  4190. {
  4191. ++i;
  4192. skipWhitespace (i);
  4193. textIndex = i;
  4194. }
  4195. if (text[i] == '-')
  4196. {
  4197. ++i;
  4198. skipWhitespace (i);
  4199. }
  4200. int numDigits = 0;
  4201. while (isDecimalDigit (text[i]))
  4202. {
  4203. ++i;
  4204. ++numDigits;
  4205. }
  4206. const bool hasPoint = (text[i] == '.');
  4207. if (hasPoint)
  4208. {
  4209. ++i;
  4210. while (isDecimalDigit (text[i]))
  4211. {
  4212. ++i;
  4213. ++numDigits;
  4214. }
  4215. }
  4216. if (numDigits == 0)
  4217. return 0;
  4218. juce_wchar c = text[i];
  4219. const bool hasExponent = (c == 'e' || c == 'E');
  4220. if (hasExponent)
  4221. {
  4222. ++i;
  4223. c = text[i];
  4224. if (c == '+' || c == '-')
  4225. ++i;
  4226. int numExpDigits = 0;
  4227. while (isDecimalDigit (text[i]))
  4228. {
  4229. ++i;
  4230. ++numExpDigits;
  4231. }
  4232. if (numExpDigits == 0)
  4233. return 0;
  4234. }
  4235. const int start = textIndex;
  4236. textIndex = i;
  4237. return new Constant (String (text + start, i - start).getDoubleValue(), isResolutionTarget);
  4238. }
  4239. const TermPtr readMultiplyOrDivideExpression()
  4240. {
  4241. TermPtr lhs (readUnaryExpression());
  4242. char opType;
  4243. while (lhs != 0 && readOperator ("*/", &opType))
  4244. {
  4245. TermPtr rhs (readUnaryExpression());
  4246. if (rhs == 0)
  4247. throw ParseError ("Expected expression after \"" + String::charToString (opType) + "\"");
  4248. if (opType == '*')
  4249. lhs = new Multiply (lhs, rhs);
  4250. else
  4251. lhs = new Divide (lhs, rhs);
  4252. }
  4253. return lhs;
  4254. }
  4255. const TermPtr readUnaryExpression()
  4256. {
  4257. char opType;
  4258. if (readOperator ("+-", &opType))
  4259. {
  4260. TermPtr term (readUnaryExpression());
  4261. if (term == 0)
  4262. throw ParseError ("Expected expression after \"" + String::charToString (opType) + "\"");
  4263. if (opType == '-')
  4264. term = term->negated();
  4265. return term;
  4266. }
  4267. return readPrimaryExpression();
  4268. }
  4269. const TermPtr readPrimaryExpression()
  4270. {
  4271. TermPtr e (readParenthesisedExpression());
  4272. if (e != 0)
  4273. return e;
  4274. e = readNumber();
  4275. if (e != 0)
  4276. return e;
  4277. String identifier;
  4278. if (readIdentifier (identifier))
  4279. {
  4280. if (readOperator ("(")) // method call...
  4281. {
  4282. Function* f = new Function (identifier, ReferenceCountedArray<Term>());
  4283. ScopedPointer<Term> func (f); // (can't use ScopedPointer<Function> in MSVC)
  4284. TermPtr param (readExpression());
  4285. if (param == 0)
  4286. {
  4287. if (readOperator (")"))
  4288. return func.release();
  4289. throw ParseError ("Expected parameters after \"" + identifier + " (\"");
  4290. }
  4291. f->parameters.add (param);
  4292. while (readOperator (","))
  4293. {
  4294. param = readExpression();
  4295. if (param == 0)
  4296. throw ParseError ("Expected expression after \",\"");
  4297. f->parameters.add (param);
  4298. }
  4299. if (readOperator (")"))
  4300. return func.release();
  4301. throw ParseError ("Expected \")\"");
  4302. }
  4303. else // just a symbol..
  4304. {
  4305. return new Symbol (identifier);
  4306. }
  4307. }
  4308. return 0;
  4309. }
  4310. const TermPtr readParenthesisedExpression()
  4311. {
  4312. if (! readOperator ("("))
  4313. return 0;
  4314. const TermPtr e (readExpression());
  4315. if (e == 0 || ! readOperator (")"))
  4316. return 0;
  4317. return e;
  4318. }
  4319. Parser (const Parser&);
  4320. Parser& operator= (const Parser&);
  4321. };
  4322. };
  4323. Expression::Expression()
  4324. : term (new Expression::Helpers::Constant (0, false))
  4325. {
  4326. }
  4327. Expression::~Expression()
  4328. {
  4329. }
  4330. Expression::Expression (Term* const term_)
  4331. : term (term_)
  4332. {
  4333. jassert (term != 0);
  4334. }
  4335. Expression::Expression (const double constant)
  4336. : term (new Expression::Helpers::Constant (constant, false))
  4337. {
  4338. }
  4339. Expression::Expression (const Expression& other)
  4340. : term (other.term)
  4341. {
  4342. }
  4343. Expression& Expression::operator= (const Expression& other)
  4344. {
  4345. term = other.term;
  4346. return *this;
  4347. }
  4348. Expression::Expression (const String& stringToParse)
  4349. {
  4350. int i = 0;
  4351. Helpers::Parser parser (stringToParse, i);
  4352. term = parser.readExpression();
  4353. if (term == 0)
  4354. term = new Helpers::Constant (0, false);
  4355. }
  4356. const Expression Expression::parse (const String& stringToParse, int& textIndexToStartFrom)
  4357. {
  4358. Helpers::Parser parser (stringToParse, textIndexToStartFrom);
  4359. const Helpers::TermPtr term (parser.readExpression());
  4360. if (term != 0)
  4361. return Expression (term);
  4362. return Expression();
  4363. }
  4364. double Expression::evaluate() const
  4365. {
  4366. return evaluate (Expression::EvaluationContext());
  4367. }
  4368. double Expression::evaluate (const Expression::EvaluationContext& context) const
  4369. {
  4370. return term->evaluate (context, 0);
  4371. }
  4372. const Expression Expression::operator+ (const Expression& other) const { return Expression (new Helpers::Add (term, other.term)); }
  4373. const Expression Expression::operator- (const Expression& other) const { return Expression (new Helpers::Subtract (term, other.term)); }
  4374. const Expression Expression::operator* (const Expression& other) const { return Expression (new Helpers::Multiply (term, other.term)); }
  4375. const Expression Expression::operator/ (const Expression& other) const { return Expression (new Helpers::Divide (term, other.term)); }
  4376. const Expression Expression::operator-() const { return Expression (term->negated()); }
  4377. const String Expression::toString() const
  4378. {
  4379. return term->toString();
  4380. }
  4381. const Expression Expression::symbol (const String& symbol)
  4382. {
  4383. return Expression (new Helpers::Symbol (symbol));
  4384. }
  4385. const Expression Expression::function (const String& functionName, const Array<Expression>& parameters)
  4386. {
  4387. ReferenceCountedArray<Term> params;
  4388. for (int i = 0; i < parameters.size(); ++i)
  4389. params.add (parameters.getReference(i).term);
  4390. return Expression (new Helpers::Function (functionName, params));
  4391. }
  4392. const Expression Expression::adjustedToGiveNewResult (const double targetValue,
  4393. const Expression::EvaluationContext& context) const
  4394. {
  4395. ScopedPointer<Term> newTerm (term->clone());
  4396. Helpers::Constant* termToAdjust = Helpers::findTermToAdjust (newTerm, true);
  4397. if (termToAdjust == 0)
  4398. termToAdjust = Helpers::findTermToAdjust (newTerm, false);
  4399. if (termToAdjust == 0)
  4400. {
  4401. newTerm = new Helpers::Add (newTerm.release(), new Helpers::Constant (0, false));
  4402. termToAdjust = Helpers::findTermToAdjust (newTerm, false);
  4403. }
  4404. jassert (termToAdjust != 0);
  4405. const Term* parent = Helpers::findDestinationFor (newTerm, termToAdjust);
  4406. if (parent == 0)
  4407. {
  4408. termToAdjust->value = targetValue;
  4409. }
  4410. else
  4411. {
  4412. const Helpers::TermPtr reverseTerm (parent->createTermToEvaluateInput (context, termToAdjust, targetValue, newTerm));
  4413. if (reverseTerm == 0)
  4414. return Expression (targetValue);
  4415. termToAdjust->value = reverseTerm->evaluate (context, 0);
  4416. }
  4417. return Expression (newTerm.release());
  4418. }
  4419. const Expression Expression::withRenamedSymbol (const String& oldSymbol, const String& newSymbol) const
  4420. {
  4421. jassert (newSymbol.toLowerCase().containsOnly ("abcdefghijklmnopqrstuvwxyz0123456789_"));
  4422. Expression newExpression (term->clone());
  4423. Helpers::renameSymbol (newExpression.term, oldSymbol, newSymbol);
  4424. return newExpression;
  4425. }
  4426. bool Expression::referencesSymbol (const String& symbol, const EvaluationContext* context) const
  4427. {
  4428. return term->referencesSymbol (symbol, context, 0);
  4429. }
  4430. bool Expression::usesAnySymbols() const
  4431. {
  4432. return Helpers::containsAnySymbols (term);
  4433. }
  4434. Expression::Type Expression::getType() const throw()
  4435. {
  4436. return term->getType();
  4437. }
  4438. const String Expression::getSymbol() const
  4439. {
  4440. return term->getSymbolName();
  4441. }
  4442. const String Expression::getFunction() const
  4443. {
  4444. return term->getFunctionName();
  4445. }
  4446. const String Expression::getOperator() const
  4447. {
  4448. return term->getFunctionName();
  4449. }
  4450. int Expression::getNumInputs() const
  4451. {
  4452. return term->getNumInputs();
  4453. }
  4454. const Expression Expression::getInput (int index) const
  4455. {
  4456. return Expression (term->getInput (index));
  4457. }
  4458. int Expression::Term::getOperatorPrecedence() const
  4459. {
  4460. return 0;
  4461. }
  4462. bool Expression::Term::referencesSymbol (const String&, const EvaluationContext*, int) const
  4463. {
  4464. return false;
  4465. }
  4466. int Expression::Term::getInputIndexFor (const Term*) const
  4467. {
  4468. return -1;
  4469. }
  4470. const ReferenceCountedObjectPtr<Expression::Term> Expression::Term::createTermToEvaluateInput (const EvaluationContext&, const Term*, double, Term*) const
  4471. {
  4472. jassertfalse;
  4473. return 0;
  4474. }
  4475. const ReferenceCountedObjectPtr<Expression::Term> Expression::Term::negated()
  4476. {
  4477. return new Helpers::Negate (this);
  4478. }
  4479. const String Expression::Term::getSymbolName() const
  4480. {
  4481. jassertfalse; // You should only call getSymbol() on an expression that's actually a symbol!
  4482. return String::empty;
  4483. }
  4484. const String Expression::Term::getFunctionName() const
  4485. {
  4486. jassertfalse; // You shouldn't call this for an expression that's not actually a function!
  4487. return String::empty;
  4488. }
  4489. Expression::ParseError::ParseError (const String& message)
  4490. : description (message)
  4491. {
  4492. DBG ("Expression::ParseError: " + message);
  4493. }
  4494. Expression::EvaluationError::EvaluationError (const String& message)
  4495. : description (message)
  4496. {
  4497. DBG ("Expression::EvaluationError: " + description);
  4498. }
  4499. Expression::EvaluationError::EvaluationError (const String& symbol, const String& member)
  4500. : description ("Unknown symbol: \"" + symbol + (member.isEmpty() ? "\"" : ("." + member + "\"")))
  4501. {
  4502. DBG ("Expression::EvaluationError: " + description);
  4503. }
  4504. Expression::EvaluationContext::EvaluationContext() {}
  4505. Expression::EvaluationContext::~EvaluationContext() {}
  4506. const Expression Expression::EvaluationContext::getSymbolValue (const String& symbol, const String& member) const
  4507. {
  4508. throw EvaluationError (symbol, member);
  4509. }
  4510. double Expression::EvaluationContext::evaluateFunction (const String& functionName, const double* parameters, int numParams) const
  4511. {
  4512. if (numParams > 0)
  4513. {
  4514. if (functionName == "min")
  4515. {
  4516. double v = parameters[0];
  4517. for (int i = 1; i < numParams; ++i)
  4518. v = jmin (v, parameters[i]);
  4519. return v;
  4520. }
  4521. else if (functionName == "max")
  4522. {
  4523. double v = parameters[0];
  4524. for (int i = 1; i < numParams; ++i)
  4525. v = jmax (v, parameters[i]);
  4526. return v;
  4527. }
  4528. else if (numParams == 1)
  4529. {
  4530. if (functionName == "sin") return sin (parameters[0]);
  4531. else if (functionName == "cos") return cos (parameters[0]);
  4532. else if (functionName == "tan") return tan (parameters[0]);
  4533. else if (functionName == "abs") return std::abs (parameters[0]);
  4534. }
  4535. }
  4536. throw EvaluationError ("Unknown function: \"" + functionName + "\"");
  4537. }
  4538. END_JUCE_NAMESPACE
  4539. /*** End of inlined file: juce_Expression.cpp ***/
  4540. /*** Start of inlined file: juce_BlowFish.cpp ***/
  4541. BEGIN_JUCE_NAMESPACE
  4542. BlowFish::BlowFish (const void* const keyData, const int keyBytes)
  4543. {
  4544. jassert (keyData != 0);
  4545. jassert (keyBytes > 0);
  4546. static const uint32 initialPValues [18] =
  4547. {
  4548. 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89,
  4549. 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917,
  4550. 0x9216d5d9, 0x8979fb1b
  4551. };
  4552. static const uint32 initialSValues [4 * 256] =
  4553. {
  4554. 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99,
  4555. 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,
  4556. 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
  4557. 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e,
  4558. 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,
  4559. 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
  4560. 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677,
  4561. 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032,
  4562. 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
  4563. 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0,
  4564. 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98,
  4565. 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
  4566. 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d,
  4567. 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7,
  4568. 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
  4569. 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09,
  4570. 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb,
  4571. 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
  4572. 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82,
  4573. 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573,
  4574. 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
  4575. 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8,
  4576. 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0,
  4577. 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
  4578. 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1,
  4579. 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9,
  4580. 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
  4581. 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af,
  4582. 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5,
  4583. 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
  4584. 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915,
  4585. 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a,
  4586. 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266,
  4587. 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e,
  4588. 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
  4589. 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1,
  4590. 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8,
  4591. 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
  4592. 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7,
  4593. 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331,
  4594. 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
  4595. 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87,
  4596. 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2,
  4597. 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
  4598. 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509,
  4599. 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3,
  4600. 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
  4601. 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960,
  4602. 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28,
  4603. 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
  4604. 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf,
  4605. 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e,
  4606. 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
  4607. 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281,
  4608. 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696,
  4609. 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
  4610. 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0,
  4611. 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250,
  4612. 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
  4613. 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061,
  4614. 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e,
  4615. 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
  4616. 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340,
  4617. 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7,
  4618. 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068,
  4619. 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840,
  4620. 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
  4621. 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb,
  4622. 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6,
  4623. 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
  4624. 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb,
  4625. 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b,
  4626. 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
  4627. 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc,
  4628. 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564,
  4629. 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
  4630. 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728,
  4631. 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e,
  4632. 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
  4633. 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b,
  4634. 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb,
  4635. 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
  4636. 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9,
  4637. 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe,
  4638. 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
  4639. 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61,
  4640. 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9,
  4641. 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
  4642. 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633,
  4643. 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169,
  4644. 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
  4645. 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62,
  4646. 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76,
  4647. 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
  4648. 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c,
  4649. 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0,
  4650. 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe,
  4651. 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4,
  4652. 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
  4653. 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22,
  4654. 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6,
  4655. 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
  4656. 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51,
  4657. 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c,
  4658. 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
  4659. 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd,
  4660. 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319,
  4661. 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
  4662. 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32,
  4663. 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,
  4664. 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
  4665. 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47,
  4666. 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d,
  4667. 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
  4668. 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd,
  4669. 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7,
  4670. 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
  4671. 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525,
  4672. 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442,
  4673. 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
  4674. 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d,
  4675. 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299,
  4676. 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
  4677. 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a,
  4678. 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b,
  4679. 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
  4680. 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9,
  4681. 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6
  4682. };
  4683. memcpy (p, initialPValues, sizeof (p));
  4684. int i, j = 0;
  4685. for (i = 4; --i >= 0;)
  4686. {
  4687. s[i].malloc (256);
  4688. memcpy (s[i], initialSValues + i * 256, 256 * sizeof (uint32));
  4689. }
  4690. for (i = 0; i < 18; ++i)
  4691. {
  4692. uint32 d = 0;
  4693. for (int k = 0; k < 4; ++k)
  4694. {
  4695. d = (d << 8) | static_cast <const uint8*> (keyData)[j];
  4696. if (++j >= keyBytes)
  4697. j = 0;
  4698. }
  4699. p[i] = initialPValues[i] ^ d;
  4700. }
  4701. uint32 l = 0, r = 0;
  4702. for (i = 0; i < 18; i += 2)
  4703. {
  4704. encrypt (l, r);
  4705. p[i] = l;
  4706. p[i + 1] = r;
  4707. }
  4708. for (i = 0; i < 4; ++i)
  4709. {
  4710. for (j = 0; j < 256; j += 2)
  4711. {
  4712. encrypt (l, r);
  4713. s[i][j] = l;
  4714. s[i][j + 1] = r;
  4715. }
  4716. }
  4717. }
  4718. BlowFish::BlowFish (const BlowFish& other)
  4719. {
  4720. for (int i = 4; --i >= 0;)
  4721. s[i].malloc (256);
  4722. operator= (other);
  4723. }
  4724. BlowFish& BlowFish::operator= (const BlowFish& other)
  4725. {
  4726. memcpy (p, other.p, sizeof (p));
  4727. for (int i = 4; --i >= 0;)
  4728. memcpy (s[i], other.s[i], 256 * sizeof (uint32));
  4729. return *this;
  4730. }
  4731. BlowFish::~BlowFish()
  4732. {
  4733. }
  4734. uint32 BlowFish::F (const uint32 x) const throw()
  4735. {
  4736. return ((s[0][(x >> 24) & 0xff] + s[1][(x >> 16) & 0xff])
  4737. ^ s[2][(x >> 8) & 0xff]) + s[3][x & 0xff];
  4738. }
  4739. void BlowFish::encrypt (uint32& data1, uint32& data2) const throw()
  4740. {
  4741. uint32 l = data1;
  4742. uint32 r = data2;
  4743. for (int i = 0; i < 16; ++i)
  4744. {
  4745. l ^= p[i];
  4746. r ^= F(l);
  4747. swapVariables (l, r);
  4748. }
  4749. data1 = r ^ p[17];
  4750. data2 = l ^ p[16];
  4751. }
  4752. void BlowFish::decrypt (uint32& data1, uint32& data2) const throw()
  4753. {
  4754. uint32 l = data1;
  4755. uint32 r = data2;
  4756. for (int i = 17; i > 1; --i)
  4757. {
  4758. l ^= p[i];
  4759. r ^= F(l);
  4760. swapVariables (l, r);
  4761. }
  4762. data1 = r ^ p[0];
  4763. data2 = l ^ p[1];
  4764. }
  4765. END_JUCE_NAMESPACE
  4766. /*** End of inlined file: juce_BlowFish.cpp ***/
  4767. /*** Start of inlined file: juce_MD5.cpp ***/
  4768. BEGIN_JUCE_NAMESPACE
  4769. MD5::MD5()
  4770. {
  4771. zerostruct (result);
  4772. }
  4773. MD5::MD5 (const MD5& other)
  4774. {
  4775. memcpy (result, other.result, sizeof (result));
  4776. }
  4777. MD5& MD5::operator= (const MD5& other)
  4778. {
  4779. memcpy (result, other.result, sizeof (result));
  4780. return *this;
  4781. }
  4782. MD5::MD5 (const MemoryBlock& data)
  4783. {
  4784. ProcessContext context;
  4785. context.processBlock (data.getData(), data.getSize());
  4786. context.finish (result);
  4787. }
  4788. MD5::MD5 (const void* data, const size_t numBytes)
  4789. {
  4790. ProcessContext context;
  4791. context.processBlock (data, numBytes);
  4792. context.finish (result);
  4793. }
  4794. MD5::MD5 (const String& text)
  4795. {
  4796. ProcessContext context;
  4797. const int len = text.length();
  4798. const juce_wchar* const t = text;
  4799. for (int i = 0; i < len; ++i)
  4800. {
  4801. // force the string into integer-sized unicode characters, to try to make it
  4802. // get the same results on all platforms + compilers.
  4803. uint32 unicodeChar = ByteOrder::swapIfBigEndian ((uint32) t[i]);
  4804. context.processBlock (&unicodeChar, sizeof (unicodeChar));
  4805. }
  4806. context.finish (result);
  4807. }
  4808. void MD5::processStream (InputStream& input, int64 numBytesToRead)
  4809. {
  4810. ProcessContext context;
  4811. if (numBytesToRead < 0)
  4812. numBytesToRead = std::numeric_limits<int64>::max();
  4813. while (numBytesToRead > 0)
  4814. {
  4815. uint8 tempBuffer [512];
  4816. const int bytesRead = input.read (tempBuffer, (int) jmin (numBytesToRead, (int64) sizeof (tempBuffer)));
  4817. if (bytesRead <= 0)
  4818. break;
  4819. numBytesToRead -= bytesRead;
  4820. context.processBlock (tempBuffer, bytesRead);
  4821. }
  4822. context.finish (result);
  4823. }
  4824. MD5::MD5 (InputStream& input, int64 numBytesToRead)
  4825. {
  4826. processStream (input, numBytesToRead);
  4827. }
  4828. MD5::MD5 (const File& file)
  4829. {
  4830. const ScopedPointer <FileInputStream> fin (file.createInputStream());
  4831. if (fin != 0)
  4832. processStream (*fin, -1);
  4833. else
  4834. zerostruct (result);
  4835. }
  4836. MD5::~MD5()
  4837. {
  4838. }
  4839. namespace MD5Functions
  4840. {
  4841. static void encode (void* const output, const void* const input, const int numBytes) throw()
  4842. {
  4843. for (int i = 0; i < (numBytes >> 2); ++i)
  4844. static_cast<uint32*> (output)[i] = ByteOrder::swapIfBigEndian (static_cast<const uint32*> (input) [i]);
  4845. }
  4846. static inline uint32 F (const uint32 x, const uint32 y, const uint32 z) throw() { return (x & y) | (~x & z); }
  4847. static inline uint32 G (const uint32 x, const uint32 y, const uint32 z) throw() { return (x & z) | (y & ~z); }
  4848. static inline uint32 H (const uint32 x, const uint32 y, const uint32 z) throw() { return x ^ y ^ z; }
  4849. static inline uint32 I (const uint32 x, const uint32 y, const uint32 z) throw() { return y ^ (x | ~z); }
  4850. static inline uint32 rotateLeft (const uint32 x, const uint32 n) throw() { return (x << n) | (x >> (32 - n)); }
  4851. static void FF (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4852. {
  4853. a += F (b, c, d) + x + ac;
  4854. a = rotateLeft (a, s) + b;
  4855. }
  4856. static void GG (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4857. {
  4858. a += G (b, c, d) + x + ac;
  4859. a = rotateLeft (a, s) + b;
  4860. }
  4861. static void HH (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4862. {
  4863. a += H (b, c, d) + x + ac;
  4864. a = rotateLeft (a, s) + b;
  4865. }
  4866. static void II (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4867. {
  4868. a += I (b, c, d) + x + ac;
  4869. a = rotateLeft (a, s) + b;
  4870. }
  4871. }
  4872. MD5::ProcessContext::ProcessContext()
  4873. {
  4874. state[0] = 0x67452301;
  4875. state[1] = 0xefcdab89;
  4876. state[2] = 0x98badcfe;
  4877. state[3] = 0x10325476;
  4878. count[0] = 0;
  4879. count[1] = 0;
  4880. }
  4881. void MD5::ProcessContext::processBlock (const void* const data, const size_t dataSize)
  4882. {
  4883. int bufferPos = ((count[0] >> 3) & 0x3F);
  4884. count[0] += (uint32) (dataSize << 3);
  4885. if (count[0] < ((uint32) dataSize << 3))
  4886. count[1]++;
  4887. count[1] += (uint32) (dataSize >> 29);
  4888. const size_t spaceLeft = 64 - bufferPos;
  4889. size_t i = 0;
  4890. if (dataSize >= spaceLeft)
  4891. {
  4892. memcpy (buffer + bufferPos, data, spaceLeft);
  4893. transform (buffer);
  4894. for (i = spaceLeft; i + 64 <= dataSize; i += 64)
  4895. transform (static_cast <const char*> (data) + i);
  4896. bufferPos = 0;
  4897. }
  4898. memcpy (buffer + bufferPos, static_cast <const char*> (data) + i, dataSize - i);
  4899. }
  4900. void MD5::ProcessContext::finish (void* const result)
  4901. {
  4902. unsigned char encodedLength[8];
  4903. MD5Functions::encode (encodedLength, count, 8);
  4904. // Pad out to 56 mod 64.
  4905. const int index = (uint32) ((count[0] >> 3) & 0x3f);
  4906. const int paddingLength = (index < 56) ? (56 - index)
  4907. : (120 - index);
  4908. uint8 paddingBuffer [64];
  4909. zeromem (paddingBuffer, paddingLength);
  4910. paddingBuffer [0] = 0x80;
  4911. processBlock (paddingBuffer, paddingLength);
  4912. processBlock (encodedLength, 8);
  4913. MD5Functions::encode (result, state, 16);
  4914. zerostruct (buffer);
  4915. }
  4916. void MD5::ProcessContext::transform (const void* const bufferToTransform)
  4917. {
  4918. using namespace MD5Functions;
  4919. uint32 a = state[0];
  4920. uint32 b = state[1];
  4921. uint32 c = state[2];
  4922. uint32 d = state[3];
  4923. uint32 x[16];
  4924. encode (x, bufferToTransform, 64);
  4925. enum Constants
  4926. {
  4927. S11 = 7, S12 = 12, S13 = 17, S14 = 22, S21 = 5, S22 = 9, S23 = 14, S24 = 20,
  4928. S31 = 4, S32 = 11, S33 = 16, S34 = 23, S41 = 6, S42 = 10, S43 = 15, S44 = 21
  4929. };
  4930. FF (a, b, c, d, x[ 0], S11, 0xd76aa478); FF (d, a, b, c, x[ 1], S12, 0xe8c7b756);
  4931. FF (c, d, a, b, x[ 2], S13, 0x242070db); FF (b, c, d, a, x[ 3], S14, 0xc1bdceee);
  4932. FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); FF (d, a, b, c, x[ 5], S12, 0x4787c62a);
  4933. FF (c, d, a, b, x[ 6], S13, 0xa8304613); FF (b, c, d, a, x[ 7], S14, 0xfd469501);
  4934. FF (a, b, c, d, x[ 8], S11, 0x698098d8); FF (d, a, b, c, x[ 9], S12, 0x8b44f7af);
  4935. FF (c, d, a, b, x[10], S13, 0xffff5bb1); FF (b, c, d, a, x[11], S14, 0x895cd7be);
  4936. FF (a, b, c, d, x[12], S11, 0x6b901122); FF (d, a, b, c, x[13], S12, 0xfd987193);
  4937. FF (c, d, a, b, x[14], S13, 0xa679438e); FF (b, c, d, a, x[15], S14, 0x49b40821);
  4938. GG (a, b, c, d, x[ 1], S21, 0xf61e2562); GG (d, a, b, c, x[ 6], S22, 0xc040b340);
  4939. GG (c, d, a, b, x[11], S23, 0x265e5a51); GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa);
  4940. GG (a, b, c, d, x[ 5], S21, 0xd62f105d); GG (d, a, b, c, x[10], S22, 0x02441453);
  4941. GG (c, d, a, b, x[15], S23, 0xd8a1e681); GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8);
  4942. GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); GG (d, a, b, c, x[14], S22, 0xc33707d6);
  4943. GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); GG (b, c, d, a, x[ 8], S24, 0x455a14ed);
  4944. GG (a, b, c, d, x[13], S21, 0xa9e3e905); GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8);
  4945. GG (c, d, a, b, x[ 7], S23, 0x676f02d9); GG (b, c, d, a, x[12], S24, 0x8d2a4c8a);
  4946. HH (a, b, c, d, x[ 5], S31, 0xfffa3942); HH (d, a, b, c, x[ 8], S32, 0x8771f681);
  4947. HH (c, d, a, b, x[11], S33, 0x6d9d6122); HH (b, c, d, a, x[14], S34, 0xfde5380c);
  4948. HH (a, b, c, d, x[ 1], S31, 0xa4beea44); HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9);
  4949. HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); HH (b, c, d, a, x[10], S34, 0xbebfbc70);
  4950. HH (a, b, c, d, x[13], S31, 0x289b7ec6); HH (d, a, b, c, x[ 0], S32, 0xeaa127fa);
  4951. HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); HH (b, c, d, a, x[ 6], S34, 0x04881d05);
  4952. HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); HH (d, a, b, c, x[12], S32, 0xe6db99e5);
  4953. HH (c, d, a, b, x[15], S33, 0x1fa27cf8); HH (b, c, d, a, x[ 2], S34, 0xc4ac5665);
  4954. II (a, b, c, d, x[ 0], S41, 0xf4292244); II (d, a, b, c, x[ 7], S42, 0x432aff97);
  4955. II (c, d, a, b, x[14], S43, 0xab9423a7); II (b, c, d, a, x[ 5], S44, 0xfc93a039);
  4956. II (a, b, c, d, x[12], S41, 0x655b59c3); II (d, a, b, c, x[ 3], S42, 0x8f0ccc92);
  4957. II (c, d, a, b, x[10], S43, 0xffeff47d); II (b, c, d, a, x[ 1], S44, 0x85845dd1);
  4958. II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); II (d, a, b, c, x[15], S42, 0xfe2ce6e0);
  4959. II (c, d, a, b, x[ 6], S43, 0xa3014314); II (b, c, d, a, x[13], S44, 0x4e0811a1);
  4960. II (a, b, c, d, x[ 4], S41, 0xf7537e82); II (d, a, b, c, x[11], S42, 0xbd3af235);
  4961. II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); II (b, c, d, a, x[ 9], S44, 0xeb86d391);
  4962. state[0] += a;
  4963. state[1] += b;
  4964. state[2] += c;
  4965. state[3] += d;
  4966. zerostruct (x);
  4967. }
  4968. const MemoryBlock MD5::getRawChecksumData() const
  4969. {
  4970. return MemoryBlock (result, sizeof (result));
  4971. }
  4972. const String MD5::toHexString() const
  4973. {
  4974. return String::toHexString (result, sizeof (result), 0);
  4975. }
  4976. bool MD5::operator== (const MD5& other) const
  4977. {
  4978. return memcmp (result, other.result, sizeof (result)) == 0;
  4979. }
  4980. bool MD5::operator!= (const MD5& other) const
  4981. {
  4982. return ! operator== (other);
  4983. }
  4984. END_JUCE_NAMESPACE
  4985. /*** End of inlined file: juce_MD5.cpp ***/
  4986. /*** Start of inlined file: juce_Primes.cpp ***/
  4987. BEGIN_JUCE_NAMESPACE
  4988. namespace PrimesHelpers
  4989. {
  4990. static void createSmallSieve (const int numBits, BigInteger& result)
  4991. {
  4992. result.setBit (numBits);
  4993. result.clearBit (numBits); // to enlarge the array
  4994. result.setBit (0);
  4995. int n = 2;
  4996. do
  4997. {
  4998. for (int i = n + n; i < numBits; i += n)
  4999. result.setBit (i);
  5000. n = result.findNextClearBit (n + 1);
  5001. }
  5002. while (n <= (numBits >> 1));
  5003. }
  5004. static void bigSieve (const BigInteger& base, const int numBits, BigInteger& result,
  5005. const BigInteger& smallSieve, const int smallSieveSize)
  5006. {
  5007. jassert (! base[0]); // must be even!
  5008. result.setBit (numBits);
  5009. result.clearBit (numBits); // to enlarge the array
  5010. int index = smallSieve.findNextClearBit (0);
  5011. do
  5012. {
  5013. const int prime = (index << 1) + 1;
  5014. BigInteger r (base), remainder;
  5015. r.divideBy (prime, remainder);
  5016. int i = prime - remainder.getBitRangeAsInt (0, 32);
  5017. if (r.isZero())
  5018. i += prime;
  5019. if ((i & 1) == 0)
  5020. i += prime;
  5021. i = (i - 1) >> 1;
  5022. while (i < numBits)
  5023. {
  5024. result.setBit (i);
  5025. i += prime;
  5026. }
  5027. index = smallSieve.findNextClearBit (index + 1);
  5028. }
  5029. while (index < smallSieveSize);
  5030. }
  5031. static bool findCandidate (const BigInteger& base, const BigInteger& sieve,
  5032. const int numBits, BigInteger& result, const int certainty)
  5033. {
  5034. for (int i = 0; i < numBits; ++i)
  5035. {
  5036. if (! sieve[i])
  5037. {
  5038. result = base + (unsigned int) ((i << 1) + 1);
  5039. if (Primes::isProbablyPrime (result, certainty))
  5040. return true;
  5041. }
  5042. }
  5043. return false;
  5044. }
  5045. static bool passesMillerRabin (const BigInteger& n, int iterations)
  5046. {
  5047. const BigInteger one (1), two (2);
  5048. const BigInteger nMinusOne (n - one);
  5049. BigInteger d (nMinusOne);
  5050. const int s = d.findNextSetBit (0);
  5051. d >>= s;
  5052. BigInteger smallPrimes;
  5053. int numBitsInSmallPrimes = 0;
  5054. for (;;)
  5055. {
  5056. numBitsInSmallPrimes += 256;
  5057. createSmallSieve (numBitsInSmallPrimes, smallPrimes);
  5058. const int numPrimesFound = numBitsInSmallPrimes - smallPrimes.countNumberOfSetBits();
  5059. if (numPrimesFound > iterations + 1)
  5060. break;
  5061. }
  5062. int smallPrime = 2;
  5063. while (--iterations >= 0)
  5064. {
  5065. smallPrime = smallPrimes.findNextClearBit (smallPrime + 1);
  5066. BigInteger r (smallPrime);
  5067. r.exponentModulo (d, n);
  5068. if (r != one && r != nMinusOne)
  5069. {
  5070. for (int j = 0; j < s; ++j)
  5071. {
  5072. r.exponentModulo (two, n);
  5073. if (r == nMinusOne)
  5074. break;
  5075. }
  5076. if (r != nMinusOne)
  5077. return false;
  5078. }
  5079. }
  5080. return true;
  5081. }
  5082. }
  5083. const BigInteger Primes::createProbablePrime (const int bitLength,
  5084. const int certainty,
  5085. const int* randomSeeds,
  5086. int numRandomSeeds)
  5087. {
  5088. using namespace PrimesHelpers;
  5089. int defaultSeeds [16];
  5090. if (numRandomSeeds <= 0)
  5091. {
  5092. randomSeeds = defaultSeeds;
  5093. numRandomSeeds = numElementsInArray (defaultSeeds);
  5094. Random r (0);
  5095. for (int j = 10; --j >= 0;)
  5096. {
  5097. r.setSeedRandomly();
  5098. for (int i = numRandomSeeds; --i >= 0;)
  5099. defaultSeeds[i] ^= r.nextInt() ^ Random::getSystemRandom().nextInt();
  5100. }
  5101. }
  5102. BigInteger smallSieve;
  5103. const int smallSieveSize = 15000;
  5104. createSmallSieve (smallSieveSize, smallSieve);
  5105. BigInteger p;
  5106. for (int i = numRandomSeeds; --i >= 0;)
  5107. {
  5108. BigInteger p2;
  5109. Random r (randomSeeds[i]);
  5110. r.fillBitsRandomly (p2, 0, bitLength);
  5111. p ^= p2;
  5112. }
  5113. p.setBit (bitLength - 1);
  5114. p.clearBit (0);
  5115. const int searchLen = jmax (1024, (bitLength / 20) * 64);
  5116. while (p.getHighestBit() < bitLength)
  5117. {
  5118. p += 2 * searchLen;
  5119. BigInteger sieve;
  5120. bigSieve (p, searchLen, sieve,
  5121. smallSieve, smallSieveSize);
  5122. BigInteger candidate;
  5123. if (findCandidate (p, sieve, searchLen, candidate, certainty))
  5124. return candidate;
  5125. }
  5126. jassertfalse;
  5127. return BigInteger();
  5128. }
  5129. bool Primes::isProbablyPrime (const BigInteger& number, const int certainty)
  5130. {
  5131. using namespace PrimesHelpers;
  5132. if (! number[0])
  5133. return false;
  5134. if (number.getHighestBit() <= 10)
  5135. {
  5136. const int num = number.getBitRangeAsInt (0, 10);
  5137. for (int i = num / 2; --i > 1;)
  5138. if (num % i == 0)
  5139. return false;
  5140. return true;
  5141. }
  5142. else
  5143. {
  5144. if (number.findGreatestCommonDivisor (2 * 3 * 5 * 7 * 11 * 13 * 17 * 19 * 23) != 1)
  5145. return false;
  5146. return passesMillerRabin (number, certainty);
  5147. }
  5148. }
  5149. END_JUCE_NAMESPACE
  5150. /*** End of inlined file: juce_Primes.cpp ***/
  5151. /*** Start of inlined file: juce_RSAKey.cpp ***/
  5152. BEGIN_JUCE_NAMESPACE
  5153. RSAKey::RSAKey()
  5154. {
  5155. }
  5156. RSAKey::RSAKey (const String& s)
  5157. {
  5158. if (s.containsChar (','))
  5159. {
  5160. part1.parseString (s.upToFirstOccurrenceOf (",", false, false), 16);
  5161. part2.parseString (s.fromFirstOccurrenceOf (",", false, false), 16);
  5162. }
  5163. else
  5164. {
  5165. // the string needs to be two hex numbers, comma-separated..
  5166. jassertfalse;
  5167. }
  5168. }
  5169. RSAKey::~RSAKey()
  5170. {
  5171. }
  5172. bool RSAKey::operator== (const RSAKey& other) const throw()
  5173. {
  5174. return part1 == other.part1 && part2 == other.part2;
  5175. }
  5176. bool RSAKey::operator!= (const RSAKey& other) const throw()
  5177. {
  5178. return ! operator== (other);
  5179. }
  5180. const String RSAKey::toString() const
  5181. {
  5182. return part1.toString (16) + "," + part2.toString (16);
  5183. }
  5184. bool RSAKey::applyToValue (BigInteger& value) const
  5185. {
  5186. if (part1.isZero() || part2.isZero() || value <= 0)
  5187. {
  5188. jassertfalse; // using an uninitialised key
  5189. value.clear();
  5190. return false;
  5191. }
  5192. BigInteger result;
  5193. while (! value.isZero())
  5194. {
  5195. result *= part2;
  5196. BigInteger remainder;
  5197. value.divideBy (part2, remainder);
  5198. remainder.exponentModulo (part1, part2);
  5199. result += remainder;
  5200. }
  5201. value.swapWith (result);
  5202. return true;
  5203. }
  5204. const BigInteger RSAKey::findBestCommonDivisor (const BigInteger& p, const BigInteger& q)
  5205. {
  5206. // try 3, 5, 9, 17, etc first because these only contain 2 bits and so
  5207. // are fast to divide + multiply
  5208. for (int i = 2; i <= 65536; i *= 2)
  5209. {
  5210. const BigInteger e (1 + i);
  5211. if (e.findGreatestCommonDivisor (p).isOne() && e.findGreatestCommonDivisor (q).isOne())
  5212. return e;
  5213. }
  5214. BigInteger e (4);
  5215. while (! (e.findGreatestCommonDivisor (p).isOne() && e.findGreatestCommonDivisor (q).isOne()))
  5216. ++e;
  5217. return e;
  5218. }
  5219. void RSAKey::createKeyPair (RSAKey& publicKey, RSAKey& privateKey,
  5220. const int numBits, const int* randomSeeds, const int numRandomSeeds)
  5221. {
  5222. jassert (numBits > 16); // not much point using less than this..
  5223. jassert (numRandomSeeds == 0 || numRandomSeeds >= 2); // you need to provide plenty of seeds here!
  5224. BigInteger p (Primes::createProbablePrime (numBits / 2, 30, randomSeeds, numRandomSeeds / 2));
  5225. BigInteger q (Primes::createProbablePrime (numBits - numBits / 2, 30, randomSeeds == 0 ? 0 : (randomSeeds + numRandomSeeds / 2), numRandomSeeds - numRandomSeeds / 2));
  5226. const BigInteger n (p * q);
  5227. const BigInteger m (--p * --q);
  5228. const BigInteger e (findBestCommonDivisor (p, q));
  5229. BigInteger d (e);
  5230. d.inverseModulo (m);
  5231. publicKey.part1 = e;
  5232. publicKey.part2 = n;
  5233. privateKey.part1 = d;
  5234. privateKey.part2 = n;
  5235. }
  5236. END_JUCE_NAMESPACE
  5237. /*** End of inlined file: juce_RSAKey.cpp ***/
  5238. /*** Start of inlined file: juce_InputStream.cpp ***/
  5239. BEGIN_JUCE_NAMESPACE
  5240. char InputStream::readByte()
  5241. {
  5242. char temp = 0;
  5243. read (&temp, 1);
  5244. return temp;
  5245. }
  5246. bool InputStream::readBool()
  5247. {
  5248. return readByte() != 0;
  5249. }
  5250. short InputStream::readShort()
  5251. {
  5252. char temp[2];
  5253. if (read (temp, 2) == 2)
  5254. return (short) ByteOrder::littleEndianShort (temp);
  5255. return 0;
  5256. }
  5257. short InputStream::readShortBigEndian()
  5258. {
  5259. char temp[2];
  5260. if (read (temp, 2) == 2)
  5261. return (short) ByteOrder::bigEndianShort (temp);
  5262. return 0;
  5263. }
  5264. int InputStream::readInt()
  5265. {
  5266. char temp[4];
  5267. if (read (temp, 4) == 4)
  5268. return (int) ByteOrder::littleEndianInt (temp);
  5269. return 0;
  5270. }
  5271. int InputStream::readIntBigEndian()
  5272. {
  5273. char temp[4];
  5274. if (read (temp, 4) == 4)
  5275. return (int) ByteOrder::bigEndianInt (temp);
  5276. return 0;
  5277. }
  5278. int InputStream::readCompressedInt()
  5279. {
  5280. const unsigned char sizeByte = readByte();
  5281. if (sizeByte == 0)
  5282. return 0;
  5283. const int numBytes = (sizeByte & 0x7f);
  5284. if (numBytes > 4)
  5285. {
  5286. jassertfalse; // trying to read corrupt data - this method must only be used
  5287. // to read data that was written by OutputStream::writeCompressedInt()
  5288. return 0;
  5289. }
  5290. char bytes[4] = { 0, 0, 0, 0 };
  5291. if (read (bytes, numBytes) != numBytes)
  5292. return 0;
  5293. const int num = (int) ByteOrder::littleEndianInt (bytes);
  5294. return (sizeByte >> 7) ? -num : num;
  5295. }
  5296. int64 InputStream::readInt64()
  5297. {
  5298. union { uint8 asBytes[8]; uint64 asInt64; } n;
  5299. if (read (n.asBytes, 8) == 8)
  5300. return (int64) ByteOrder::swapIfBigEndian (n.asInt64);
  5301. return 0;
  5302. }
  5303. int64 InputStream::readInt64BigEndian()
  5304. {
  5305. union { uint8 asBytes[8]; uint64 asInt64; } n;
  5306. if (read (n.asBytes, 8) == 8)
  5307. return (int64) ByteOrder::swapIfLittleEndian (n.asInt64);
  5308. return 0;
  5309. }
  5310. float InputStream::readFloat()
  5311. {
  5312. // the union below relies on these types being the same size...
  5313. static_jassert (sizeof (int32) == sizeof (float));
  5314. union { int32 asInt; float asFloat; } n;
  5315. n.asInt = (int32) readInt();
  5316. return n.asFloat;
  5317. }
  5318. float InputStream::readFloatBigEndian()
  5319. {
  5320. union { int32 asInt; float asFloat; } n;
  5321. n.asInt = (int32) readIntBigEndian();
  5322. return n.asFloat;
  5323. }
  5324. double InputStream::readDouble()
  5325. {
  5326. union { int64 asInt; double asDouble; } n;
  5327. n.asInt = readInt64();
  5328. return n.asDouble;
  5329. }
  5330. double InputStream::readDoubleBigEndian()
  5331. {
  5332. union { int64 asInt; double asDouble; } n;
  5333. n.asInt = readInt64BigEndian();
  5334. return n.asDouble;
  5335. }
  5336. const String InputStream::readString()
  5337. {
  5338. MemoryBlock buffer (256);
  5339. char* data = static_cast<char*> (buffer.getData());
  5340. size_t i = 0;
  5341. while ((data[i] = readByte()) != 0)
  5342. {
  5343. if (++i >= buffer.getSize())
  5344. {
  5345. buffer.setSize (buffer.getSize() + 512);
  5346. data = static_cast<char*> (buffer.getData());
  5347. }
  5348. }
  5349. return String::fromUTF8 (data, (int) i);
  5350. }
  5351. const String InputStream::readNextLine()
  5352. {
  5353. MemoryBlock buffer (256);
  5354. char* data = static_cast<char*> (buffer.getData());
  5355. size_t i = 0;
  5356. while ((data[i] = readByte()) != 0)
  5357. {
  5358. if (data[i] == '\n')
  5359. break;
  5360. if (data[i] == '\r')
  5361. {
  5362. const int64 lastPos = getPosition();
  5363. if (readByte() != '\n')
  5364. setPosition (lastPos);
  5365. break;
  5366. }
  5367. if (++i >= buffer.getSize())
  5368. {
  5369. buffer.setSize (buffer.getSize() + 512);
  5370. data = static_cast<char*> (buffer.getData());
  5371. }
  5372. }
  5373. return String::fromUTF8 (data, (int) i);
  5374. }
  5375. int InputStream::readIntoMemoryBlock (MemoryBlock& block, int numBytes)
  5376. {
  5377. MemoryOutputStream mo (block, true);
  5378. return mo.writeFromInputStream (*this, numBytes);
  5379. }
  5380. const String InputStream::readEntireStreamAsString()
  5381. {
  5382. MemoryOutputStream mo;
  5383. mo.writeFromInputStream (*this, -1);
  5384. return mo.toString();
  5385. }
  5386. void InputStream::skipNextBytes (int64 numBytesToSkip)
  5387. {
  5388. if (numBytesToSkip > 0)
  5389. {
  5390. const int skipBufferSize = (int) jmin (numBytesToSkip, (int64) 16384);
  5391. HeapBlock<char> temp (skipBufferSize);
  5392. while (numBytesToSkip > 0 && ! isExhausted())
  5393. numBytesToSkip -= read (temp, (int) jmin (numBytesToSkip, (int64) skipBufferSize));
  5394. }
  5395. }
  5396. END_JUCE_NAMESPACE
  5397. /*** End of inlined file: juce_InputStream.cpp ***/
  5398. /*** Start of inlined file: juce_OutputStream.cpp ***/
  5399. BEGIN_JUCE_NAMESPACE
  5400. #if JUCE_DEBUG
  5401. static Array<void*, CriticalSection> activeStreams;
  5402. void juce_CheckForDanglingStreams()
  5403. {
  5404. /*
  5405. It's always a bad idea to leak any object, but if you're leaking output
  5406. streams, then there's a good chance that you're failing to flush a file
  5407. to disk properly, which could result in corrupted data and other similar
  5408. nastiness..
  5409. */
  5410. jassert (activeStreams.size() == 0);
  5411. };
  5412. #endif
  5413. OutputStream::OutputStream()
  5414. {
  5415. #if JUCE_DEBUG
  5416. activeStreams.add (this);
  5417. #endif
  5418. }
  5419. OutputStream::~OutputStream()
  5420. {
  5421. #if JUCE_DEBUG
  5422. activeStreams.removeValue (this);
  5423. #endif
  5424. }
  5425. void OutputStream::writeBool (const bool b)
  5426. {
  5427. writeByte (b ? (char) 1
  5428. : (char) 0);
  5429. }
  5430. void OutputStream::writeByte (char byte)
  5431. {
  5432. write (&byte, 1);
  5433. }
  5434. void OutputStream::writeShort (short value)
  5435. {
  5436. const unsigned short v = ByteOrder::swapIfBigEndian ((unsigned short) value);
  5437. write (&v, 2);
  5438. }
  5439. void OutputStream::writeShortBigEndian (short value)
  5440. {
  5441. const unsigned short v = ByteOrder::swapIfLittleEndian ((unsigned short) value);
  5442. write (&v, 2);
  5443. }
  5444. void OutputStream::writeInt (int value)
  5445. {
  5446. const unsigned int v = ByteOrder::swapIfBigEndian ((unsigned int) value);
  5447. write (&v, 4);
  5448. }
  5449. void OutputStream::writeIntBigEndian (int value)
  5450. {
  5451. const unsigned int v = ByteOrder::swapIfLittleEndian ((unsigned int) value);
  5452. write (&v, 4);
  5453. }
  5454. void OutputStream::writeCompressedInt (int value)
  5455. {
  5456. unsigned int un = (value < 0) ? (unsigned int) -value
  5457. : (unsigned int) value;
  5458. uint8 data[5];
  5459. int num = 0;
  5460. while (un > 0)
  5461. {
  5462. data[++num] = (uint8) un;
  5463. un >>= 8;
  5464. }
  5465. data[0] = (uint8) num;
  5466. if (value < 0)
  5467. data[0] |= 0x80;
  5468. write (data, num + 1);
  5469. }
  5470. void OutputStream::writeInt64 (int64 value)
  5471. {
  5472. const uint64 v = ByteOrder::swapIfBigEndian ((uint64) value);
  5473. write (&v, 8);
  5474. }
  5475. void OutputStream::writeInt64BigEndian (int64 value)
  5476. {
  5477. const uint64 v = ByteOrder::swapIfLittleEndian ((uint64) value);
  5478. write (&v, 8);
  5479. }
  5480. void OutputStream::writeFloat (float value)
  5481. {
  5482. union { int asInt; float asFloat; } n;
  5483. n.asFloat = value;
  5484. writeInt (n.asInt);
  5485. }
  5486. void OutputStream::writeFloatBigEndian (float value)
  5487. {
  5488. union { int asInt; float asFloat; } n;
  5489. n.asFloat = value;
  5490. writeIntBigEndian (n.asInt);
  5491. }
  5492. void OutputStream::writeDouble (double value)
  5493. {
  5494. union { int64 asInt; double asDouble; } n;
  5495. n.asDouble = value;
  5496. writeInt64 (n.asInt);
  5497. }
  5498. void OutputStream::writeDoubleBigEndian (double value)
  5499. {
  5500. union { int64 asInt; double asDouble; } n;
  5501. n.asDouble = value;
  5502. writeInt64BigEndian (n.asInt);
  5503. }
  5504. void OutputStream::writeString (const String& text)
  5505. {
  5506. // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind
  5507. // if lots of large, persistent strings were to be written to streams).
  5508. const int numBytes = text.getNumBytesAsUTF8() + 1;
  5509. HeapBlock<char> temp (numBytes);
  5510. text.copyToUTF8 (temp, numBytes);
  5511. write (temp, numBytes);
  5512. }
  5513. void OutputStream::writeText (const String& text, const bool asUnicode,
  5514. const bool writeUnicodeHeaderBytes)
  5515. {
  5516. if (asUnicode)
  5517. {
  5518. if (writeUnicodeHeaderBytes)
  5519. write ("\x0ff\x0fe", 2);
  5520. const juce_wchar* src = text;
  5521. bool lastCharWasReturn = false;
  5522. while (*src != 0)
  5523. {
  5524. if (*src == L'\n' && ! lastCharWasReturn)
  5525. writeShort ((short) L'\r');
  5526. lastCharWasReturn = (*src == L'\r');
  5527. writeShort ((short) *src++);
  5528. }
  5529. }
  5530. else
  5531. {
  5532. const char* src = text.toUTF8();
  5533. const char* t = src;
  5534. for (;;)
  5535. {
  5536. if (*t == '\n')
  5537. {
  5538. if (t > src)
  5539. write (src, (int) (t - src));
  5540. write ("\r\n", 2);
  5541. src = t + 1;
  5542. }
  5543. else if (*t == '\r')
  5544. {
  5545. if (t[1] == '\n')
  5546. ++t;
  5547. }
  5548. else if (*t == 0)
  5549. {
  5550. if (t > src)
  5551. write (src, (int) (t - src));
  5552. break;
  5553. }
  5554. ++t;
  5555. }
  5556. }
  5557. }
  5558. int OutputStream::writeFromInputStream (InputStream& source, int64 numBytesToWrite)
  5559. {
  5560. if (numBytesToWrite < 0)
  5561. numBytesToWrite = std::numeric_limits<int64>::max();
  5562. int numWritten = 0;
  5563. while (numBytesToWrite > 0 && ! source.isExhausted())
  5564. {
  5565. char buffer [8192];
  5566. const int num = source.read (buffer, (int) jmin (numBytesToWrite, (int64) sizeof (buffer)));
  5567. if (num <= 0)
  5568. break;
  5569. write (buffer, num);
  5570. numBytesToWrite -= num;
  5571. numWritten += num;
  5572. }
  5573. return numWritten;
  5574. }
  5575. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const int number)
  5576. {
  5577. return stream << String (number);
  5578. }
  5579. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const double number)
  5580. {
  5581. return stream << String (number);
  5582. }
  5583. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char character)
  5584. {
  5585. stream.writeByte (character);
  5586. return stream;
  5587. }
  5588. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char* const text)
  5589. {
  5590. stream.write (text, (int) strlen (text));
  5591. return stream;
  5592. }
  5593. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryBlock& data)
  5594. {
  5595. stream.write (data.getData(), (int) data.getSize());
  5596. return stream;
  5597. }
  5598. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const File& fileToRead)
  5599. {
  5600. const ScopedPointer<FileInputStream> in (fileToRead.createInputStream());
  5601. if (in != 0)
  5602. stream.writeFromInputStream (*in, -1);
  5603. return stream;
  5604. }
  5605. END_JUCE_NAMESPACE
  5606. /*** End of inlined file: juce_OutputStream.cpp ***/
  5607. /*** Start of inlined file: juce_DirectoryIterator.cpp ***/
  5608. BEGIN_JUCE_NAMESPACE
  5609. DirectoryIterator::DirectoryIterator (const File& directory,
  5610. bool isRecursive_,
  5611. const String& wildCard_,
  5612. const int whatToLookFor_)
  5613. : fileFinder (directory, isRecursive_ ? "*" : wildCard_),
  5614. wildCard (wildCard_),
  5615. path (File::addTrailingSeparator (directory.getFullPathName())),
  5616. index (-1),
  5617. totalNumFiles (-1),
  5618. whatToLookFor (whatToLookFor_),
  5619. isRecursive (isRecursive_),
  5620. hasBeenAdvanced (false)
  5621. {
  5622. // you have to specify the type of files you're looking for!
  5623. jassert ((whatToLookFor_ & (File::findFiles | File::findDirectories)) != 0);
  5624. jassert (whatToLookFor_ > 0 && whatToLookFor_ <= 7);
  5625. }
  5626. DirectoryIterator::~DirectoryIterator()
  5627. {
  5628. }
  5629. bool DirectoryIterator::next()
  5630. {
  5631. return next (0, 0, 0, 0, 0, 0);
  5632. }
  5633. bool DirectoryIterator::next (bool* const isDirResult, bool* const isHiddenResult, int64* const fileSize,
  5634. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  5635. {
  5636. hasBeenAdvanced = true;
  5637. if (subIterator != 0)
  5638. {
  5639. if (subIterator->next (isDirResult, isHiddenResult, fileSize, modTime, creationTime, isReadOnly))
  5640. return true;
  5641. subIterator = 0;
  5642. }
  5643. String filename;
  5644. bool isDirectory, isHidden;
  5645. while (fileFinder.next (filename, &isDirectory, &isHidden, fileSize, modTime, creationTime, isReadOnly))
  5646. {
  5647. ++index;
  5648. if (! filename.containsOnly ("."))
  5649. {
  5650. const File fileFound (path + filename, 0);
  5651. bool matches = false;
  5652. if (isDirectory)
  5653. {
  5654. if (isRecursive && ((whatToLookFor & File::ignoreHiddenFiles) == 0 || ! isHidden))
  5655. subIterator = new DirectoryIterator (fileFound, true, wildCard, whatToLookFor);
  5656. matches = (whatToLookFor & File::findDirectories) != 0;
  5657. }
  5658. else
  5659. {
  5660. matches = (whatToLookFor & File::findFiles) != 0;
  5661. }
  5662. // if recursive, we're not relying on the OS iterator to do the wildcard match, so do it now..
  5663. if (matches && isRecursive)
  5664. matches = filename.matchesWildcard (wildCard, ! File::areFileNamesCaseSensitive());
  5665. if (matches && (whatToLookFor & File::ignoreHiddenFiles) != 0)
  5666. matches = ! isHidden;
  5667. if (matches)
  5668. {
  5669. currentFile = fileFound;
  5670. if (isHiddenResult != 0) *isHiddenResult = isHidden;
  5671. if (isDirResult != 0) *isDirResult = isDirectory;
  5672. return true;
  5673. }
  5674. else if (subIterator != 0)
  5675. {
  5676. return next();
  5677. }
  5678. }
  5679. }
  5680. return false;
  5681. }
  5682. const File DirectoryIterator::getFile() const
  5683. {
  5684. if (subIterator != 0 && subIterator->hasBeenAdvanced)
  5685. return subIterator->getFile();
  5686. // You need to call DirectoryIterator::next() before asking it for the file that it found!
  5687. jassert (hasBeenAdvanced);
  5688. return currentFile;
  5689. }
  5690. float DirectoryIterator::getEstimatedProgress() const
  5691. {
  5692. if (totalNumFiles < 0)
  5693. totalNumFiles = File (path).getNumberOfChildFiles (File::findFilesAndDirectories);
  5694. if (totalNumFiles <= 0)
  5695. return 0.0f;
  5696. const float detailedIndex = (subIterator != 0) ? index + subIterator->getEstimatedProgress()
  5697. : (float) index;
  5698. return detailedIndex / totalNumFiles;
  5699. }
  5700. END_JUCE_NAMESPACE
  5701. /*** End of inlined file: juce_DirectoryIterator.cpp ***/
  5702. /*** Start of inlined file: juce_File.cpp ***/
  5703. #if ! JUCE_WINDOWS
  5704. #include <pwd.h>
  5705. #endif
  5706. BEGIN_JUCE_NAMESPACE
  5707. File::File (const String& fullPathName)
  5708. : fullPath (parseAbsolutePath (fullPathName))
  5709. {
  5710. }
  5711. File::File (const String& path, int)
  5712. : fullPath (path)
  5713. {
  5714. }
  5715. const File File::createFileWithoutCheckingPath (const String& path)
  5716. {
  5717. return File (path, 0);
  5718. }
  5719. File::File (const File& other)
  5720. : fullPath (other.fullPath)
  5721. {
  5722. }
  5723. File& File::operator= (const String& newPath)
  5724. {
  5725. fullPath = parseAbsolutePath (newPath);
  5726. return *this;
  5727. }
  5728. File& File::operator= (const File& other)
  5729. {
  5730. fullPath = other.fullPath;
  5731. return *this;
  5732. }
  5733. const File File::nonexistent;
  5734. const String File::parseAbsolutePath (const String& p)
  5735. {
  5736. if (p.isEmpty())
  5737. return String::empty;
  5738. #if JUCE_WINDOWS
  5739. // Windows..
  5740. String path (p.replaceCharacter ('/', '\\'));
  5741. if (path.startsWithChar (File::separator))
  5742. {
  5743. if (path[1] != File::separator)
  5744. {
  5745. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  5746. If you're trying to parse a string that may be either a relative path or an absolute path,
  5747. you MUST provide a context against which the partial path can be evaluated - you can do
  5748. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  5749. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  5750. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  5751. */
  5752. jassertfalse;
  5753. path = File::getCurrentWorkingDirectory().getFullPathName().substring (0, 2) + path;
  5754. }
  5755. }
  5756. else if (! path.containsChar (':'))
  5757. {
  5758. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  5759. If you're trying to parse a string that may be either a relative path or an absolute path,
  5760. you MUST provide a context against which the partial path can be evaluated - you can do
  5761. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  5762. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  5763. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  5764. */
  5765. jassertfalse;
  5766. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  5767. }
  5768. #else
  5769. // Mac or Linux..
  5770. String path (p.replaceCharacter ('\\', '/'));
  5771. if (path.startsWithChar ('~'))
  5772. {
  5773. if (path[1] == File::separator || path[1] == 0)
  5774. {
  5775. // expand a name of the form "~/abc"
  5776. path = File::getSpecialLocation (File::userHomeDirectory).getFullPathName()
  5777. + path.substring (1);
  5778. }
  5779. else
  5780. {
  5781. // expand a name of type "~dave/abc"
  5782. const String userName (path.substring (1).upToFirstOccurrenceOf ("/", false, false));
  5783. struct passwd* const pw = getpwnam (userName.toUTF8());
  5784. if (pw != 0)
  5785. path = addTrailingSeparator (pw->pw_dir) + path.fromFirstOccurrenceOf ("/", false, false);
  5786. }
  5787. }
  5788. else if (! path.startsWithChar (File::separator))
  5789. {
  5790. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  5791. If you're trying to parse a string that may be either a relative path or an absolute path,
  5792. you MUST provide a context against which the partial path can be evaluated - you can do
  5793. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  5794. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  5795. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  5796. */
  5797. jassert (path.startsWith ("./") || path.startsWith ("../")); // (assume that a path "./xyz" is deliberately intended to be relative to the CWD)
  5798. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  5799. }
  5800. #endif
  5801. while (path.endsWithChar (separator) && path != separatorString) // careful not to turn a single "/" into an empty string.
  5802. path = path.dropLastCharacters (1);
  5803. return path;
  5804. }
  5805. const String File::addTrailingSeparator (const String& path)
  5806. {
  5807. return path.endsWithChar (File::separator) ? path
  5808. : path + File::separator;
  5809. }
  5810. #if JUCE_LINUX
  5811. #define NAMES_ARE_CASE_SENSITIVE 1
  5812. #endif
  5813. bool File::areFileNamesCaseSensitive()
  5814. {
  5815. #if NAMES_ARE_CASE_SENSITIVE
  5816. return true;
  5817. #else
  5818. return false;
  5819. #endif
  5820. }
  5821. bool File::operator== (const File& other) const
  5822. {
  5823. #if NAMES_ARE_CASE_SENSITIVE
  5824. return fullPath == other.fullPath;
  5825. #else
  5826. return fullPath.equalsIgnoreCase (other.fullPath);
  5827. #endif
  5828. }
  5829. bool File::operator!= (const File& other) const
  5830. {
  5831. return ! operator== (other);
  5832. }
  5833. bool File::operator< (const File& other) const
  5834. {
  5835. #if NAMES_ARE_CASE_SENSITIVE
  5836. return fullPath < other.fullPath;
  5837. #else
  5838. return fullPath.compareIgnoreCase (other.fullPath) < 0;
  5839. #endif
  5840. }
  5841. bool File::operator> (const File& other) const
  5842. {
  5843. #if NAMES_ARE_CASE_SENSITIVE
  5844. return fullPath > other.fullPath;
  5845. #else
  5846. return fullPath.compareIgnoreCase (other.fullPath) > 0;
  5847. #endif
  5848. }
  5849. bool File::setReadOnly (const bool shouldBeReadOnly,
  5850. const bool applyRecursively) const
  5851. {
  5852. bool worked = true;
  5853. if (applyRecursively && isDirectory())
  5854. {
  5855. Array <File> subFiles;
  5856. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  5857. for (int i = subFiles.size(); --i >= 0;)
  5858. worked = subFiles.getReference(i).setReadOnly (shouldBeReadOnly, true) && worked;
  5859. }
  5860. return setFileReadOnlyInternal (shouldBeReadOnly) && worked;
  5861. }
  5862. bool File::deleteRecursively() const
  5863. {
  5864. bool worked = true;
  5865. if (isDirectory())
  5866. {
  5867. Array<File> subFiles;
  5868. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  5869. for (int i = subFiles.size(); --i >= 0;)
  5870. worked = subFiles.getReference(i).deleteRecursively() && worked;
  5871. }
  5872. return deleteFile() && worked;
  5873. }
  5874. bool File::moveFileTo (const File& newFile) const
  5875. {
  5876. if (newFile.fullPath == fullPath)
  5877. return true;
  5878. #if ! NAMES_ARE_CASE_SENSITIVE
  5879. if (*this != newFile)
  5880. #endif
  5881. if (! newFile.deleteFile())
  5882. return false;
  5883. return moveInternal (newFile);
  5884. }
  5885. bool File::copyFileTo (const File& newFile) const
  5886. {
  5887. return (*this == newFile)
  5888. || (exists() && newFile.deleteFile() && copyInternal (newFile));
  5889. }
  5890. bool File::copyDirectoryTo (const File& newDirectory) const
  5891. {
  5892. if (isDirectory() && newDirectory.createDirectory())
  5893. {
  5894. Array<File> subFiles;
  5895. findChildFiles (subFiles, File::findFiles, false);
  5896. int i;
  5897. for (i = 0; i < subFiles.size(); ++i)
  5898. if (! subFiles.getReference(i).copyFileTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  5899. return false;
  5900. subFiles.clear();
  5901. findChildFiles (subFiles, File::findDirectories, false);
  5902. for (i = 0; i < subFiles.size(); ++i)
  5903. if (! subFiles.getReference(i).copyDirectoryTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  5904. return false;
  5905. return true;
  5906. }
  5907. return false;
  5908. }
  5909. const String File::getPathUpToLastSlash() const
  5910. {
  5911. const int lastSlash = fullPath.lastIndexOfChar (separator);
  5912. if (lastSlash > 0)
  5913. return fullPath.substring (0, lastSlash);
  5914. else if (lastSlash == 0)
  5915. return separatorString;
  5916. else
  5917. return fullPath;
  5918. }
  5919. const File File::getParentDirectory() const
  5920. {
  5921. return File (getPathUpToLastSlash(), (int) 0);
  5922. }
  5923. const String File::getFileName() const
  5924. {
  5925. return fullPath.substring (fullPath.lastIndexOfChar (separator) + 1);
  5926. }
  5927. int File::hashCode() const
  5928. {
  5929. return fullPath.hashCode();
  5930. }
  5931. int64 File::hashCode64() const
  5932. {
  5933. return fullPath.hashCode64();
  5934. }
  5935. const String File::getFileNameWithoutExtension() const
  5936. {
  5937. const int lastSlash = fullPath.lastIndexOfChar (separator) + 1;
  5938. const int lastDot = fullPath.lastIndexOfChar ('.');
  5939. if (lastDot > lastSlash)
  5940. return fullPath.substring (lastSlash, lastDot);
  5941. else
  5942. return fullPath.substring (lastSlash);
  5943. }
  5944. bool File::isAChildOf (const File& potentialParent) const
  5945. {
  5946. if (potentialParent == File::nonexistent)
  5947. return false;
  5948. const String ourPath (getPathUpToLastSlash());
  5949. #if NAMES_ARE_CASE_SENSITIVE
  5950. if (potentialParent.fullPath == ourPath)
  5951. #else
  5952. if (potentialParent.fullPath.equalsIgnoreCase (ourPath))
  5953. #endif
  5954. {
  5955. return true;
  5956. }
  5957. else if (potentialParent.fullPath.length() >= ourPath.length())
  5958. {
  5959. return false;
  5960. }
  5961. else
  5962. {
  5963. return getParentDirectory().isAChildOf (potentialParent);
  5964. }
  5965. }
  5966. bool File::isAbsolutePath (const String& path)
  5967. {
  5968. return path.startsWithChar ('/') || path.startsWithChar ('\\')
  5969. #if JUCE_WINDOWS
  5970. || (path.isNotEmpty() && path[1] == ':');
  5971. #else
  5972. || path.startsWithChar ('~');
  5973. #endif
  5974. }
  5975. const File File::getChildFile (String relativePath) const
  5976. {
  5977. if (isAbsolutePath (relativePath))
  5978. {
  5979. // the path is really absolute..
  5980. return File (relativePath);
  5981. }
  5982. else
  5983. {
  5984. // it's relative, so remove any ../ or ./ bits at the start.
  5985. String path (fullPath);
  5986. if (relativePath[0] == '.')
  5987. {
  5988. #if JUCE_WINDOWS
  5989. relativePath = relativePath.replaceCharacter ('/', '\\').trimStart();
  5990. #else
  5991. relativePath = relativePath.replaceCharacter ('\\', '/').trimStart();
  5992. #endif
  5993. while (relativePath[0] == '.')
  5994. {
  5995. if (relativePath[1] == '.')
  5996. {
  5997. if (relativePath [2] == 0 || relativePath[2] == separator)
  5998. {
  5999. const int lastSlash = path.lastIndexOfChar (separator);
  6000. if (lastSlash >= 0)
  6001. path = path.substring (0, lastSlash);
  6002. relativePath = relativePath.substring (3);
  6003. }
  6004. else
  6005. {
  6006. break;
  6007. }
  6008. }
  6009. else if (relativePath[1] == separator)
  6010. {
  6011. relativePath = relativePath.substring (2);
  6012. }
  6013. else
  6014. {
  6015. break;
  6016. }
  6017. }
  6018. }
  6019. return File (addTrailingSeparator (path) + relativePath);
  6020. }
  6021. }
  6022. const File File::getSiblingFile (const String& fileName) const
  6023. {
  6024. return getParentDirectory().getChildFile (fileName);
  6025. }
  6026. const String File::descriptionOfSizeInBytes (const int64 bytes)
  6027. {
  6028. if (bytes == 1)
  6029. {
  6030. return "1 byte";
  6031. }
  6032. else if (bytes < 1024)
  6033. {
  6034. return String ((int) bytes) + " bytes";
  6035. }
  6036. else if (bytes < 1024 * 1024)
  6037. {
  6038. return String (bytes / 1024.0, 1) + " KB";
  6039. }
  6040. else if (bytes < 1024 * 1024 * 1024)
  6041. {
  6042. return String (bytes / (1024.0 * 1024.0), 1) + " MB";
  6043. }
  6044. else
  6045. {
  6046. return String (bytes / (1024.0 * 1024.0 * 1024.0), 1) + " GB";
  6047. }
  6048. }
  6049. bool File::create() const
  6050. {
  6051. if (exists())
  6052. return true;
  6053. {
  6054. const File parentDir (getParentDirectory());
  6055. if (parentDir == *this || ! parentDir.createDirectory())
  6056. return false;
  6057. FileOutputStream fo (*this, 8);
  6058. }
  6059. return exists();
  6060. }
  6061. bool File::createDirectory() const
  6062. {
  6063. if (! isDirectory())
  6064. {
  6065. const File parentDir (getParentDirectory());
  6066. if (parentDir == *this || ! parentDir.createDirectory())
  6067. return false;
  6068. createDirectoryInternal (fullPath.trimCharactersAtEnd (separatorString));
  6069. return isDirectory();
  6070. }
  6071. return true;
  6072. }
  6073. const Time File::getCreationTime() const
  6074. {
  6075. int64 m, a, c;
  6076. getFileTimesInternal (m, a, c);
  6077. return Time (c);
  6078. }
  6079. const Time File::getLastModificationTime() const
  6080. {
  6081. int64 m, a, c;
  6082. getFileTimesInternal (m, a, c);
  6083. return Time (m);
  6084. }
  6085. const Time File::getLastAccessTime() const
  6086. {
  6087. int64 m, a, c;
  6088. getFileTimesInternal (m, a, c);
  6089. return Time (a);
  6090. }
  6091. bool File::setLastModificationTime (const Time& t) const { return setFileTimesInternal (t.toMilliseconds(), 0, 0); }
  6092. bool File::setLastAccessTime (const Time& t) const { return setFileTimesInternal (0, t.toMilliseconds(), 0); }
  6093. bool File::setCreationTime (const Time& t) const { return setFileTimesInternal (0, 0, t.toMilliseconds()); }
  6094. bool File::loadFileAsData (MemoryBlock& destBlock) const
  6095. {
  6096. if (! existsAsFile())
  6097. return false;
  6098. FileInputStream in (*this);
  6099. return getSize() == in.readIntoMemoryBlock (destBlock);
  6100. }
  6101. const String File::loadFileAsString() const
  6102. {
  6103. if (! existsAsFile())
  6104. return String::empty;
  6105. FileInputStream in (*this);
  6106. return in.readEntireStreamAsString();
  6107. }
  6108. int File::findChildFiles (Array<File>& results,
  6109. const int whatToLookFor,
  6110. const bool searchRecursively,
  6111. const String& wildCardPattern) const
  6112. {
  6113. DirectoryIterator di (*this, searchRecursively, wildCardPattern, whatToLookFor);
  6114. int total = 0;
  6115. while (di.next())
  6116. {
  6117. results.add (di.getFile());
  6118. ++total;
  6119. }
  6120. return total;
  6121. }
  6122. int File::getNumberOfChildFiles (const int whatToLookFor, const String& wildCardPattern) const
  6123. {
  6124. DirectoryIterator di (*this, false, wildCardPattern, whatToLookFor);
  6125. int total = 0;
  6126. while (di.next())
  6127. ++total;
  6128. return total;
  6129. }
  6130. bool File::containsSubDirectories() const
  6131. {
  6132. if (isDirectory())
  6133. {
  6134. DirectoryIterator di (*this, false, "*", findDirectories);
  6135. return di.next();
  6136. }
  6137. return false;
  6138. }
  6139. const File File::getNonexistentChildFile (const String& prefix_,
  6140. const String& suffix,
  6141. bool putNumbersInBrackets) const
  6142. {
  6143. File f (getChildFile (prefix_ + suffix));
  6144. if (f.exists())
  6145. {
  6146. int num = 2;
  6147. String prefix (prefix_);
  6148. // remove any bracketed numbers that may already be on the end..
  6149. if (prefix.trim().endsWithChar (')'))
  6150. {
  6151. putNumbersInBrackets = true;
  6152. const int openBracks = prefix.lastIndexOfChar ('(');
  6153. const int closeBracks = prefix.lastIndexOfChar (')');
  6154. if (openBracks > 0
  6155. && closeBracks > openBracks
  6156. && prefix.substring (openBracks + 1, closeBracks).containsOnly ("0123456789"))
  6157. {
  6158. num = prefix.substring (openBracks + 1, closeBracks).getIntValue() + 1;
  6159. prefix = prefix.substring (0, openBracks);
  6160. }
  6161. }
  6162. // also use brackets if it ends in a digit.
  6163. putNumbersInBrackets = putNumbersInBrackets
  6164. || CharacterFunctions::isDigit (prefix.getLastCharacter());
  6165. do
  6166. {
  6167. if (putNumbersInBrackets)
  6168. f = getChildFile (prefix + '(' + String (num++) + ')' + suffix);
  6169. else
  6170. f = getChildFile (prefix + String (num++) + suffix);
  6171. } while (f.exists());
  6172. }
  6173. return f;
  6174. }
  6175. const File File::getNonexistentSibling (const bool putNumbersInBrackets) const
  6176. {
  6177. if (exists())
  6178. {
  6179. return getParentDirectory()
  6180. .getNonexistentChildFile (getFileNameWithoutExtension(),
  6181. getFileExtension(),
  6182. putNumbersInBrackets);
  6183. }
  6184. else
  6185. {
  6186. return *this;
  6187. }
  6188. }
  6189. const String File::getFileExtension() const
  6190. {
  6191. String ext;
  6192. if (! isDirectory())
  6193. {
  6194. const int indexOfDot = fullPath.lastIndexOfChar ('.');
  6195. if (indexOfDot > fullPath.lastIndexOfChar (separator))
  6196. ext = fullPath.substring (indexOfDot);
  6197. }
  6198. return ext;
  6199. }
  6200. bool File::hasFileExtension (const String& possibleSuffix) const
  6201. {
  6202. if (possibleSuffix.isEmpty())
  6203. return fullPath.lastIndexOfChar ('.') <= fullPath.lastIndexOfChar (separator);
  6204. const int semicolon = possibleSuffix.indexOfChar (0, ';');
  6205. if (semicolon >= 0)
  6206. {
  6207. return hasFileExtension (possibleSuffix.substring (0, semicolon).trimEnd())
  6208. || hasFileExtension (possibleSuffix.substring (semicolon + 1).trimStart());
  6209. }
  6210. else
  6211. {
  6212. if (fullPath.endsWithIgnoreCase (possibleSuffix))
  6213. {
  6214. if (possibleSuffix.startsWithChar ('.'))
  6215. return true;
  6216. const int dotPos = fullPath.length() - possibleSuffix.length() - 1;
  6217. if (dotPos >= 0)
  6218. return fullPath [dotPos] == '.';
  6219. }
  6220. }
  6221. return false;
  6222. }
  6223. const File File::withFileExtension (const String& newExtension) const
  6224. {
  6225. if (fullPath.isEmpty())
  6226. return File::nonexistent;
  6227. String filePart (getFileName());
  6228. int i = filePart.lastIndexOfChar ('.');
  6229. if (i >= 0)
  6230. filePart = filePart.substring (0, i);
  6231. if (newExtension.isNotEmpty() && ! newExtension.startsWithChar ('.'))
  6232. filePart << '.';
  6233. return getSiblingFile (filePart + newExtension);
  6234. }
  6235. bool File::startAsProcess (const String& parameters) const
  6236. {
  6237. return exists() && PlatformUtilities::openDocument (fullPath, parameters);
  6238. }
  6239. FileInputStream* File::createInputStream() const
  6240. {
  6241. if (existsAsFile())
  6242. return new FileInputStream (*this);
  6243. return 0;
  6244. }
  6245. FileOutputStream* File::createOutputStream (const int bufferSize) const
  6246. {
  6247. ScopedPointer <FileOutputStream> out (new FileOutputStream (*this, bufferSize));
  6248. if (out->failedToOpen())
  6249. return 0;
  6250. return out.release();
  6251. }
  6252. bool File::appendData (const void* const dataToAppend,
  6253. const int numberOfBytes) const
  6254. {
  6255. if (numberOfBytes > 0)
  6256. {
  6257. const ScopedPointer <FileOutputStream> out (createOutputStream());
  6258. if (out == 0)
  6259. return false;
  6260. out->write (dataToAppend, numberOfBytes);
  6261. }
  6262. return true;
  6263. }
  6264. bool File::replaceWithData (const void* const dataToWrite,
  6265. const int numberOfBytes) const
  6266. {
  6267. jassert (numberOfBytes >= 0); // a negative number of bytes??
  6268. if (numberOfBytes <= 0)
  6269. return deleteFile();
  6270. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  6271. tempFile.getFile().appendData (dataToWrite, numberOfBytes);
  6272. return tempFile.overwriteTargetFileWithTemporary();
  6273. }
  6274. bool File::appendText (const String& text,
  6275. const bool asUnicode,
  6276. const bool writeUnicodeHeaderBytes) const
  6277. {
  6278. const ScopedPointer <FileOutputStream> out (createOutputStream());
  6279. if (out != 0)
  6280. {
  6281. out->writeText (text, asUnicode, writeUnicodeHeaderBytes);
  6282. return true;
  6283. }
  6284. return false;
  6285. }
  6286. bool File::replaceWithText (const String& textToWrite,
  6287. const bool asUnicode,
  6288. const bool writeUnicodeHeaderBytes) const
  6289. {
  6290. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  6291. tempFile.getFile().appendText (textToWrite, asUnicode, writeUnicodeHeaderBytes);
  6292. return tempFile.overwriteTargetFileWithTemporary();
  6293. }
  6294. bool File::hasIdenticalContentTo (const File& other) const
  6295. {
  6296. if (other == *this)
  6297. return true;
  6298. if (getSize() == other.getSize() && existsAsFile() && other.existsAsFile())
  6299. {
  6300. FileInputStream in1 (*this), in2 (other);
  6301. const int bufferSize = 4096;
  6302. HeapBlock <char> buffer1, buffer2;
  6303. buffer1.malloc (bufferSize);
  6304. buffer2.malloc (bufferSize);
  6305. for (;;)
  6306. {
  6307. const int num1 = in1.read (buffer1, bufferSize);
  6308. const int num2 = in2.read (buffer2, bufferSize);
  6309. if (num1 != num2)
  6310. break;
  6311. if (num1 <= 0)
  6312. return true;
  6313. if (memcmp (buffer1, buffer2, num1) != 0)
  6314. break;
  6315. }
  6316. }
  6317. return false;
  6318. }
  6319. const String File::createLegalPathName (const String& original)
  6320. {
  6321. String s (original);
  6322. String start;
  6323. if (s[1] == ':')
  6324. {
  6325. start = s.substring (0, 2);
  6326. s = s.substring (2);
  6327. }
  6328. return start + s.removeCharacters ("\"#@,;:<>*^|?")
  6329. .substring (0, 1024);
  6330. }
  6331. const String File::createLegalFileName (const String& original)
  6332. {
  6333. String s (original.removeCharacters ("\"#@,;:<>*^|?\\/"));
  6334. const int maxLength = 128; // only the length of the filename, not the whole path
  6335. const int len = s.length();
  6336. if (len > maxLength)
  6337. {
  6338. const int lastDot = s.lastIndexOfChar ('.');
  6339. if (lastDot > jmax (0, len - 12))
  6340. {
  6341. s = s.substring (0, maxLength - (len - lastDot))
  6342. + s.substring (lastDot);
  6343. }
  6344. else
  6345. {
  6346. s = s.substring (0, maxLength);
  6347. }
  6348. }
  6349. return s;
  6350. }
  6351. const String File::getRelativePathFrom (const File& dir) const
  6352. {
  6353. String thisPath (fullPath);
  6354. {
  6355. int len = thisPath.length();
  6356. while (--len >= 0 && thisPath [len] == File::separator)
  6357. thisPath [len] = 0;
  6358. }
  6359. String dirPath (addTrailingSeparator (dir.existsAsFile() ? dir.getParentDirectory().getFullPathName()
  6360. : dir.fullPath));
  6361. const int len = jmin (thisPath.length(), dirPath.length());
  6362. int commonBitLength = 0;
  6363. for (int i = 0; i < len; ++i)
  6364. {
  6365. #if NAMES_ARE_CASE_SENSITIVE
  6366. if (thisPath[i] != dirPath[i])
  6367. #else
  6368. if (CharacterFunctions::toLowerCase (thisPath[i])
  6369. != CharacterFunctions::toLowerCase (dirPath[i]))
  6370. #endif
  6371. {
  6372. break;
  6373. }
  6374. ++commonBitLength;
  6375. }
  6376. while (commonBitLength > 0 && thisPath [commonBitLength - 1] != File::separator)
  6377. --commonBitLength;
  6378. // if the only common bit is the root, then just return the full path..
  6379. if (commonBitLength <= 0
  6380. || (commonBitLength == 1 && thisPath [1] == File::separator))
  6381. return fullPath;
  6382. thisPath = thisPath.substring (commonBitLength);
  6383. dirPath = dirPath.substring (commonBitLength);
  6384. while (dirPath.isNotEmpty())
  6385. {
  6386. #if JUCE_WINDOWS
  6387. thisPath = "..\\" + thisPath;
  6388. #else
  6389. thisPath = "../" + thisPath;
  6390. #endif
  6391. const int sep = dirPath.indexOfChar (separator);
  6392. if (sep >= 0)
  6393. dirPath = dirPath.substring (sep + 1);
  6394. else
  6395. dirPath = String::empty;
  6396. }
  6397. return thisPath;
  6398. }
  6399. const File File::createTempFile (const String& fileNameEnding)
  6400. {
  6401. const File tempFile (getSpecialLocation (tempDirectory)
  6402. .getChildFile ("temp_" + String (Random::getSystemRandom().nextInt()))
  6403. .withFileExtension (fileNameEnding));
  6404. if (tempFile.exists())
  6405. return createTempFile (fileNameEnding);
  6406. else
  6407. return tempFile;
  6408. }
  6409. #if JUCE_UNIT_TESTS
  6410. class FileTests : public UnitTest
  6411. {
  6412. public:
  6413. FileTests() : UnitTest ("Files") {}
  6414. void runTest()
  6415. {
  6416. beginTest ("Reading");
  6417. const File home (File::getSpecialLocation (File::userHomeDirectory));
  6418. const File temp (File::getSpecialLocation (File::tempDirectory));
  6419. expect (! File::nonexistent.exists());
  6420. expect (home.isDirectory());
  6421. expect (home.exists());
  6422. expect (! home.existsAsFile());
  6423. expect (File::getSpecialLocation (File::userDocumentsDirectory).isDirectory());
  6424. expect (File::getSpecialLocation (File::userApplicationDataDirectory).isDirectory());
  6425. expect (File::getSpecialLocation (File::currentExecutableFile).exists());
  6426. expect (File::getSpecialLocation (File::currentApplicationFile).exists());
  6427. expect (File::getSpecialLocation (File::invokedExecutableFile).exists());
  6428. expect (home.getVolumeTotalSize() > 1024 * 1024);
  6429. expect (home.getBytesFreeOnVolume() > 0);
  6430. expect (! home.isHidden());
  6431. expect (home.isOnHardDisk());
  6432. expect (! home.isOnCDRomDrive());
  6433. expect (File::getCurrentWorkingDirectory().exists());
  6434. expect (home.setAsCurrentWorkingDirectory());
  6435. expect (File::getCurrentWorkingDirectory() == home);
  6436. {
  6437. Array<File> roots;
  6438. File::findFileSystemRoots (roots);
  6439. expect (roots.size() > 0);
  6440. int numRootsExisting = 0;
  6441. for (int i = 0; i < roots.size(); ++i)
  6442. if (roots[i].exists())
  6443. ++numRootsExisting;
  6444. // (on windows, some of the drives may not contain media, so as long as at least one is ok..)
  6445. expect (numRootsExisting > 0);
  6446. }
  6447. beginTest ("Writing");
  6448. File demoFolder (temp.getChildFile ("Juce UnitTests Temp Folder.folder"));
  6449. expect (demoFolder.deleteRecursively());
  6450. expect (demoFolder.createDirectory());
  6451. expect (demoFolder.isDirectory());
  6452. expect (demoFolder.getParentDirectory() == temp);
  6453. expect (temp.isDirectory());
  6454. {
  6455. Array<File> files;
  6456. temp.findChildFiles (files, File::findFilesAndDirectories, false, "*");
  6457. expect (files.contains (demoFolder));
  6458. }
  6459. {
  6460. Array<File> files;
  6461. temp.findChildFiles (files, File::findDirectories, true, "*.folder");
  6462. expect (files.contains (demoFolder));
  6463. }
  6464. File tempFile (demoFolder.getNonexistentChildFile ("test", ".txt", false));
  6465. expect (tempFile.getFileExtension() == ".txt");
  6466. expect (tempFile.hasFileExtension (".txt"));
  6467. expect (tempFile.hasFileExtension ("txt"));
  6468. expect (tempFile.withFileExtension ("xyz").hasFileExtension (".xyz"));
  6469. expect (tempFile.getSiblingFile ("foo").isAChildOf (temp));
  6470. expect (tempFile.hasWriteAccess());
  6471. {
  6472. FileOutputStream fo (tempFile);
  6473. fo.write ("0123456789", 10);
  6474. }
  6475. expect (tempFile.exists());
  6476. expect (tempFile.getSize() == 10);
  6477. expect (std::abs ((int) (tempFile.getLastModificationTime().toMilliseconds() - Time::getCurrentTime().toMilliseconds())) < 3000);
  6478. expect (tempFile.loadFileAsString() == "0123456789");
  6479. expect (! demoFolder.containsSubDirectories());
  6480. expect (demoFolder.getNumberOfChildFiles (File::findFiles) == 1);
  6481. expect (demoFolder.getNumberOfChildFiles (File::findFilesAndDirectories) == 1);
  6482. expect (demoFolder.getNumberOfChildFiles (File::findDirectories) == 0);
  6483. demoFolder.getNonexistentChildFile ("tempFolder", "", false).createDirectory();
  6484. expect (demoFolder.getNumberOfChildFiles (File::findDirectories) == 1);
  6485. expect (demoFolder.getNumberOfChildFiles (File::findFilesAndDirectories) == 2);
  6486. expect (demoFolder.containsSubDirectories());
  6487. expect (tempFile.hasWriteAccess());
  6488. tempFile.setReadOnly (true);
  6489. expect (! tempFile.hasWriteAccess());
  6490. tempFile.setReadOnly (false);
  6491. expect (tempFile.hasWriteAccess());
  6492. Time t (Time::getCurrentTime());
  6493. tempFile.setLastModificationTime (t);
  6494. Time t2 = tempFile.getLastModificationTime();
  6495. expect (std::abs ((int) (t2.toMilliseconds() - t.toMilliseconds())) <= 1000);
  6496. {
  6497. MemoryBlock mb;
  6498. tempFile.loadFileAsData (mb);
  6499. expect (mb.getSize() == 10);
  6500. expect (mb[0] == '0');
  6501. }
  6502. expect (tempFile.appendData ("abcdefghij", 10));
  6503. expect (tempFile.getSize() == 20);
  6504. expect (tempFile.replaceWithData ("abcdefghij", 10));
  6505. expect (tempFile.getSize() == 10);
  6506. File tempFile2 (tempFile.getNonexistentSibling (false));
  6507. expect (tempFile.copyFileTo (tempFile2));
  6508. expect (tempFile2.exists());
  6509. expect (tempFile2.hasIdenticalContentTo (tempFile));
  6510. expect (tempFile.deleteFile());
  6511. expect (! tempFile.exists());
  6512. expect (tempFile2.moveFileTo (tempFile));
  6513. expect (tempFile.exists());
  6514. expect (! tempFile2.exists());
  6515. expect (demoFolder.deleteRecursively());
  6516. expect (! demoFolder.exists());
  6517. }
  6518. };
  6519. static FileTests fileUnitTests;
  6520. #endif
  6521. END_JUCE_NAMESPACE
  6522. /*** End of inlined file: juce_File.cpp ***/
  6523. /*** Start of inlined file: juce_FileInputStream.cpp ***/
  6524. BEGIN_JUCE_NAMESPACE
  6525. int64 juce_fileSetPosition (void* handle, int64 pos);
  6526. FileInputStream::FileInputStream (const File& f)
  6527. : file (f),
  6528. fileHandle (0),
  6529. currentPosition (0),
  6530. totalSize (0),
  6531. needToSeek (true)
  6532. {
  6533. openHandle();
  6534. }
  6535. FileInputStream::~FileInputStream()
  6536. {
  6537. closeHandle();
  6538. }
  6539. int64 FileInputStream::getTotalLength()
  6540. {
  6541. return totalSize;
  6542. }
  6543. int FileInputStream::read (void* buffer, int bytesToRead)
  6544. {
  6545. int num = 0;
  6546. if (needToSeek)
  6547. {
  6548. if (juce_fileSetPosition (fileHandle, currentPosition) < 0)
  6549. return 0;
  6550. needToSeek = false;
  6551. }
  6552. num = readInternal (buffer, bytesToRead);
  6553. currentPosition += num;
  6554. return num;
  6555. }
  6556. bool FileInputStream::isExhausted()
  6557. {
  6558. return currentPosition >= totalSize;
  6559. }
  6560. int64 FileInputStream::getPosition()
  6561. {
  6562. return currentPosition;
  6563. }
  6564. bool FileInputStream::setPosition (int64 pos)
  6565. {
  6566. pos = jlimit ((int64) 0, totalSize, pos);
  6567. needToSeek |= (currentPosition != pos);
  6568. currentPosition = pos;
  6569. return true;
  6570. }
  6571. END_JUCE_NAMESPACE
  6572. /*** End of inlined file: juce_FileInputStream.cpp ***/
  6573. /*** Start of inlined file: juce_FileOutputStream.cpp ***/
  6574. BEGIN_JUCE_NAMESPACE
  6575. int64 juce_fileSetPosition (void* handle, int64 pos);
  6576. FileOutputStream::FileOutputStream (const File& f, const int bufferSize_)
  6577. : file (f),
  6578. fileHandle (0),
  6579. currentPosition (0),
  6580. bufferSize (bufferSize_),
  6581. bytesInBuffer (0),
  6582. buffer (jmax (bufferSize_, 16))
  6583. {
  6584. openHandle();
  6585. }
  6586. FileOutputStream::~FileOutputStream()
  6587. {
  6588. flush();
  6589. closeHandle();
  6590. }
  6591. int64 FileOutputStream::getPosition()
  6592. {
  6593. return currentPosition;
  6594. }
  6595. bool FileOutputStream::setPosition (int64 newPosition)
  6596. {
  6597. if (newPosition != currentPosition)
  6598. {
  6599. flush();
  6600. currentPosition = juce_fileSetPosition (fileHandle, newPosition);
  6601. }
  6602. return newPosition == currentPosition;
  6603. }
  6604. void FileOutputStream::flush()
  6605. {
  6606. if (bytesInBuffer > 0)
  6607. {
  6608. writeInternal (buffer, bytesInBuffer);
  6609. bytesInBuffer = 0;
  6610. }
  6611. flushInternal();
  6612. }
  6613. bool FileOutputStream::write (const void* const src, const int numBytes)
  6614. {
  6615. if (bytesInBuffer + numBytes < bufferSize)
  6616. {
  6617. memcpy (buffer + bytesInBuffer, src, numBytes);
  6618. bytesInBuffer += numBytes;
  6619. currentPosition += numBytes;
  6620. }
  6621. else
  6622. {
  6623. if (bytesInBuffer > 0)
  6624. {
  6625. // flush the reservoir
  6626. const bool wroteOk = (writeInternal (buffer, bytesInBuffer) == bytesInBuffer);
  6627. bytesInBuffer = 0;
  6628. if (! wroteOk)
  6629. return false;
  6630. }
  6631. if (numBytes < bufferSize)
  6632. {
  6633. memcpy (buffer + bytesInBuffer, src, numBytes);
  6634. bytesInBuffer += numBytes;
  6635. currentPosition += numBytes;
  6636. }
  6637. else
  6638. {
  6639. const int bytesWritten = writeInternal (src, numBytes);
  6640. if (bytesWritten < 0)
  6641. return false;
  6642. currentPosition += bytesWritten;
  6643. return bytesWritten == numBytes;
  6644. }
  6645. }
  6646. return true;
  6647. }
  6648. END_JUCE_NAMESPACE
  6649. /*** End of inlined file: juce_FileOutputStream.cpp ***/
  6650. /*** Start of inlined file: juce_FileSearchPath.cpp ***/
  6651. BEGIN_JUCE_NAMESPACE
  6652. FileSearchPath::FileSearchPath()
  6653. {
  6654. }
  6655. FileSearchPath::FileSearchPath (const String& path)
  6656. {
  6657. init (path);
  6658. }
  6659. FileSearchPath::FileSearchPath (const FileSearchPath& other)
  6660. : directories (other.directories)
  6661. {
  6662. }
  6663. FileSearchPath::~FileSearchPath()
  6664. {
  6665. }
  6666. FileSearchPath& FileSearchPath::operator= (const String& path)
  6667. {
  6668. init (path);
  6669. return *this;
  6670. }
  6671. void FileSearchPath::init (const String& path)
  6672. {
  6673. directories.clear();
  6674. directories.addTokens (path, ";", "\"");
  6675. directories.trim();
  6676. directories.removeEmptyStrings();
  6677. for (int i = directories.size(); --i >= 0;)
  6678. directories.set (i, directories[i].unquoted());
  6679. }
  6680. int FileSearchPath::getNumPaths() const
  6681. {
  6682. return directories.size();
  6683. }
  6684. const File FileSearchPath::operator[] (const int index) const
  6685. {
  6686. return File (directories [index]);
  6687. }
  6688. const String FileSearchPath::toString() const
  6689. {
  6690. StringArray directories2 (directories);
  6691. for (int i = directories2.size(); --i >= 0;)
  6692. if (directories2[i].containsChar (';'))
  6693. directories2.set (i, directories2[i].quoted());
  6694. return directories2.joinIntoString (";");
  6695. }
  6696. void FileSearchPath::add (const File& dir, const int insertIndex)
  6697. {
  6698. directories.insert (insertIndex, dir.getFullPathName());
  6699. }
  6700. void FileSearchPath::addIfNotAlreadyThere (const File& dir)
  6701. {
  6702. for (int i = 0; i < directories.size(); ++i)
  6703. if (File (directories[i]) == dir)
  6704. return;
  6705. add (dir);
  6706. }
  6707. void FileSearchPath::remove (const int index)
  6708. {
  6709. directories.remove (index);
  6710. }
  6711. void FileSearchPath::addPath (const FileSearchPath& other)
  6712. {
  6713. for (int i = 0; i < other.getNumPaths(); ++i)
  6714. addIfNotAlreadyThere (other[i]);
  6715. }
  6716. void FileSearchPath::removeRedundantPaths()
  6717. {
  6718. for (int i = directories.size(); --i >= 0;)
  6719. {
  6720. const File d1 (directories[i]);
  6721. for (int j = directories.size(); --j >= 0;)
  6722. {
  6723. const File d2 (directories[j]);
  6724. if ((i != j) && (d1.isAChildOf (d2) || d1 == d2))
  6725. {
  6726. directories.remove (i);
  6727. break;
  6728. }
  6729. }
  6730. }
  6731. }
  6732. void FileSearchPath::removeNonExistentPaths()
  6733. {
  6734. for (int i = directories.size(); --i >= 0;)
  6735. if (! File (directories[i]).isDirectory())
  6736. directories.remove (i);
  6737. }
  6738. int FileSearchPath::findChildFiles (Array<File>& results,
  6739. const int whatToLookFor,
  6740. const bool searchRecursively,
  6741. const String& wildCardPattern) const
  6742. {
  6743. int total = 0;
  6744. for (int i = 0; i < directories.size(); ++i)
  6745. total += operator[] (i).findChildFiles (results,
  6746. whatToLookFor,
  6747. searchRecursively,
  6748. wildCardPattern);
  6749. return total;
  6750. }
  6751. bool FileSearchPath::isFileInPath (const File& fileToCheck,
  6752. const bool checkRecursively) const
  6753. {
  6754. for (int i = directories.size(); --i >= 0;)
  6755. {
  6756. const File d (directories[i]);
  6757. if (checkRecursively)
  6758. {
  6759. if (fileToCheck.isAChildOf (d))
  6760. return true;
  6761. }
  6762. else
  6763. {
  6764. if (fileToCheck.getParentDirectory() == d)
  6765. return true;
  6766. }
  6767. }
  6768. return false;
  6769. }
  6770. END_JUCE_NAMESPACE
  6771. /*** End of inlined file: juce_FileSearchPath.cpp ***/
  6772. /*** Start of inlined file: juce_NamedPipe.cpp ***/
  6773. BEGIN_JUCE_NAMESPACE
  6774. NamedPipe::NamedPipe()
  6775. : internal (0)
  6776. {
  6777. }
  6778. NamedPipe::~NamedPipe()
  6779. {
  6780. close();
  6781. }
  6782. bool NamedPipe::openExisting (const String& pipeName)
  6783. {
  6784. currentPipeName = pipeName;
  6785. return openInternal (pipeName, false);
  6786. }
  6787. bool NamedPipe::createNewPipe (const String& pipeName)
  6788. {
  6789. currentPipeName = pipeName;
  6790. return openInternal (pipeName, true);
  6791. }
  6792. bool NamedPipe::isOpen() const
  6793. {
  6794. return internal != 0;
  6795. }
  6796. const String NamedPipe::getName() const
  6797. {
  6798. return currentPipeName;
  6799. }
  6800. // other methods for this class are implemented in the platform-specific files
  6801. END_JUCE_NAMESPACE
  6802. /*** End of inlined file: juce_NamedPipe.cpp ***/
  6803. /*** Start of inlined file: juce_TemporaryFile.cpp ***/
  6804. BEGIN_JUCE_NAMESPACE
  6805. TemporaryFile::TemporaryFile (const String& suffix, const int optionFlags)
  6806. {
  6807. createTempFile (File::getSpecialLocation (File::tempDirectory),
  6808. "temp_" + String (Random::getSystemRandom().nextInt()),
  6809. suffix,
  6810. optionFlags);
  6811. }
  6812. TemporaryFile::TemporaryFile (const File& targetFile_, const int optionFlags)
  6813. : targetFile (targetFile_)
  6814. {
  6815. // If you use this constructor, you need to give it a valid target file!
  6816. jassert (targetFile != File::nonexistent);
  6817. createTempFile (targetFile.getParentDirectory(),
  6818. targetFile.getFileNameWithoutExtension() + "_temp" + String (Random::getSystemRandom().nextInt()),
  6819. targetFile.getFileExtension(),
  6820. optionFlags);
  6821. }
  6822. void TemporaryFile::createTempFile (const File& parentDirectory, String name,
  6823. const String& suffix, const int optionFlags)
  6824. {
  6825. if ((optionFlags & useHiddenFile) != 0)
  6826. name = "." + name;
  6827. temporaryFile = parentDirectory.getNonexistentChildFile (name, suffix, (optionFlags & putNumbersInBrackets) != 0);
  6828. }
  6829. TemporaryFile::~TemporaryFile()
  6830. {
  6831. if (! deleteTemporaryFile())
  6832. {
  6833. /* Failed to delete our temporary file! The most likely reason for this would be
  6834. that you've not closed an output stream that was being used to write to file.
  6835. If you find that something beyond your control is changing permissions on
  6836. your temporary files and preventing them from being deleted, you may want to
  6837. call TemporaryFile::deleteTemporaryFile() to detect those error cases and
  6838. handle them appropriately.
  6839. */
  6840. jassertfalse;
  6841. }
  6842. }
  6843. bool TemporaryFile::overwriteTargetFileWithTemporary() const
  6844. {
  6845. // This method only works if you created this object with the constructor
  6846. // that takes a target file!
  6847. jassert (targetFile != File::nonexistent);
  6848. if (temporaryFile.exists())
  6849. {
  6850. // Have a few attempts at overwriting the file before giving up..
  6851. for (int i = 5; --i >= 0;)
  6852. {
  6853. if (temporaryFile.moveFileTo (targetFile))
  6854. return true;
  6855. Thread::sleep (100);
  6856. }
  6857. }
  6858. else
  6859. {
  6860. // There's no temporary file to use. If your write failed, you should
  6861. // probably check, and not bother calling this method.
  6862. jassertfalse;
  6863. }
  6864. return false;
  6865. }
  6866. bool TemporaryFile::deleteTemporaryFile() const
  6867. {
  6868. // Have a few attempts at deleting the file before giving up..
  6869. for (int i = 5; --i >= 0;)
  6870. {
  6871. if (temporaryFile.deleteFile())
  6872. return true;
  6873. Thread::sleep (50);
  6874. }
  6875. return false;
  6876. }
  6877. END_JUCE_NAMESPACE
  6878. /*** End of inlined file: juce_TemporaryFile.cpp ***/
  6879. /*** Start of inlined file: juce_Socket.cpp ***/
  6880. #if JUCE_WINDOWS
  6881. #include <winsock2.h>
  6882. #if JUCE_MSVC
  6883. #pragma warning (push)
  6884. #pragma warning (disable : 4127 4389 4018)
  6885. #endif
  6886. #else
  6887. #if JUCE_LINUX
  6888. #include <sys/types.h>
  6889. #include <sys/socket.h>
  6890. #include <sys/errno.h>
  6891. #include <unistd.h>
  6892. #include <netinet/in.h>
  6893. #elif (MACOSX_DEPLOYMENT_TARGET <= MAC_OS_X_VERSION_10_4) && ! JUCE_IOS
  6894. #include <CoreServices/CoreServices.h>
  6895. #endif
  6896. #include <fcntl.h>
  6897. #include <netdb.h>
  6898. #include <arpa/inet.h>
  6899. #include <netinet/tcp.h>
  6900. #endif
  6901. BEGIN_JUCE_NAMESPACE
  6902. #if defined (JUCE_LINUX) || defined (JUCE_MAC) || defined (JUCE_IOS)
  6903. typedef socklen_t juce_socklen_t;
  6904. #else
  6905. typedef int juce_socklen_t;
  6906. #endif
  6907. #if JUCE_WINDOWS
  6908. namespace SocketHelpers
  6909. {
  6910. typedef int (__stdcall juce_CloseWin32SocketLibCall) (void);
  6911. static juce_CloseWin32SocketLibCall* juce_CloseWin32SocketLib = 0;
  6912. void initWin32Sockets()
  6913. {
  6914. static CriticalSection lock;
  6915. const ScopedLock sl (lock);
  6916. if (SocketHelpers::juce_CloseWin32SocketLib == 0)
  6917. {
  6918. WSADATA wsaData;
  6919. const WORD wVersionRequested = MAKEWORD (1, 1);
  6920. WSAStartup (wVersionRequested, &wsaData);
  6921. SocketHelpers::juce_CloseWin32SocketLib = &WSACleanup;
  6922. }
  6923. }
  6924. }
  6925. void juce_shutdownWin32Sockets()
  6926. {
  6927. if (SocketHelpers::juce_CloseWin32SocketLib != 0)
  6928. (*SocketHelpers::juce_CloseWin32SocketLib)();
  6929. }
  6930. #endif
  6931. namespace SocketHelpers
  6932. {
  6933. static bool resetSocketOptions (const int handle, const bool isDatagram, const bool allowBroadcast) throw()
  6934. {
  6935. const int sndBufSize = 65536;
  6936. const int rcvBufSize = 65536;
  6937. const int one = 1;
  6938. return handle > 0
  6939. && setsockopt (handle, SOL_SOCKET, SO_RCVBUF, (const char*) &rcvBufSize, sizeof (rcvBufSize)) == 0
  6940. && setsockopt (handle, SOL_SOCKET, SO_SNDBUF, (const char*) &sndBufSize, sizeof (sndBufSize)) == 0
  6941. && (isDatagram ? ((! allowBroadcast) || setsockopt (handle, SOL_SOCKET, SO_BROADCAST, (const char*) &one, sizeof (one)) == 0)
  6942. : (setsockopt (handle, IPPROTO_TCP, TCP_NODELAY, (const char*) &one, sizeof (one)) == 0));
  6943. }
  6944. static bool bindSocketToPort (const int handle, const int port) throw()
  6945. {
  6946. if (handle <= 0 || port <= 0)
  6947. return false;
  6948. struct sockaddr_in servTmpAddr;
  6949. zerostruct (servTmpAddr);
  6950. servTmpAddr.sin_family = PF_INET;
  6951. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  6952. servTmpAddr.sin_port = htons ((uint16) port);
  6953. return bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) >= 0;
  6954. }
  6955. static int readSocket (const int handle,
  6956. void* const destBuffer, const int maxBytesToRead,
  6957. bool volatile& connected,
  6958. const bool blockUntilSpecifiedAmountHasArrived) throw()
  6959. {
  6960. int bytesRead = 0;
  6961. while (bytesRead < maxBytesToRead)
  6962. {
  6963. int bytesThisTime;
  6964. #if JUCE_WINDOWS
  6965. bytesThisTime = recv (handle, static_cast<char*> (destBuffer) + bytesRead, maxBytesToRead - bytesRead, 0);
  6966. #else
  6967. while ((bytesThisTime = (int) ::read (handle, addBytesToPointer (destBuffer, bytesRead), maxBytesToRead - bytesRead)) < 0
  6968. && errno == EINTR
  6969. && connected)
  6970. {
  6971. }
  6972. #endif
  6973. if (bytesThisTime <= 0 || ! connected)
  6974. {
  6975. if (bytesRead == 0)
  6976. bytesRead = -1;
  6977. break;
  6978. }
  6979. bytesRead += bytesThisTime;
  6980. if (! blockUntilSpecifiedAmountHasArrived)
  6981. break;
  6982. }
  6983. return bytesRead;
  6984. }
  6985. static int waitForReadiness (const int handle, const bool forReading,
  6986. const int timeoutMsecs) throw()
  6987. {
  6988. struct timeval timeout;
  6989. struct timeval* timeoutp;
  6990. if (timeoutMsecs >= 0)
  6991. {
  6992. timeout.tv_sec = timeoutMsecs / 1000;
  6993. timeout.tv_usec = (timeoutMsecs % 1000) * 1000;
  6994. timeoutp = &timeout;
  6995. }
  6996. else
  6997. {
  6998. timeoutp = 0;
  6999. }
  7000. fd_set rset, wset;
  7001. FD_ZERO (&rset);
  7002. FD_SET (handle, &rset);
  7003. FD_ZERO (&wset);
  7004. FD_SET (handle, &wset);
  7005. fd_set* const prset = forReading ? &rset : 0;
  7006. fd_set* const pwset = forReading ? 0 : &wset;
  7007. #if JUCE_WINDOWS
  7008. if (select (handle + 1, prset, pwset, 0, timeoutp) < 0)
  7009. return -1;
  7010. #else
  7011. {
  7012. int result;
  7013. while ((result = select (handle + 1, prset, pwset, 0, timeoutp)) < 0
  7014. && errno == EINTR)
  7015. {
  7016. }
  7017. if (result < 0)
  7018. return -1;
  7019. }
  7020. #endif
  7021. {
  7022. int opt;
  7023. juce_socklen_t len = sizeof (opt);
  7024. if (getsockopt (handle, SOL_SOCKET, SO_ERROR, (char*) &opt, &len) < 0
  7025. || opt != 0)
  7026. return -1;
  7027. }
  7028. if ((forReading && FD_ISSET (handle, &rset))
  7029. || ((! forReading) && FD_ISSET (handle, &wset)))
  7030. return 1;
  7031. return 0;
  7032. }
  7033. static bool setSocketBlockingState (const int handle, const bool shouldBlock) throw()
  7034. {
  7035. #if JUCE_WINDOWS
  7036. u_long nonBlocking = shouldBlock ? 0 : 1;
  7037. if (ioctlsocket (handle, FIONBIO, &nonBlocking) != 0)
  7038. return false;
  7039. #else
  7040. int socketFlags = fcntl (handle, F_GETFL, 0);
  7041. if (socketFlags == -1)
  7042. return false;
  7043. if (shouldBlock)
  7044. socketFlags &= ~O_NONBLOCK;
  7045. else
  7046. socketFlags |= O_NONBLOCK;
  7047. if (fcntl (handle, F_SETFL, socketFlags) != 0)
  7048. return false;
  7049. #endif
  7050. return true;
  7051. }
  7052. static bool connectSocket (int volatile& handle,
  7053. const bool isDatagram,
  7054. void** serverAddress,
  7055. const String& hostName,
  7056. const int portNumber,
  7057. const int timeOutMillisecs) throw()
  7058. {
  7059. struct hostent* const hostEnt = gethostbyname (hostName.toUTF8());
  7060. if (hostEnt == 0)
  7061. return false;
  7062. struct in_addr targetAddress;
  7063. memcpy (&targetAddress.s_addr,
  7064. *(hostEnt->h_addr_list),
  7065. sizeof (targetAddress.s_addr));
  7066. struct sockaddr_in servTmpAddr;
  7067. zerostruct (servTmpAddr);
  7068. servTmpAddr.sin_family = PF_INET;
  7069. servTmpAddr.sin_addr = targetAddress;
  7070. servTmpAddr.sin_port = htons ((uint16) portNumber);
  7071. if (handle < 0)
  7072. handle = (int) socket (AF_INET, isDatagram ? SOCK_DGRAM : SOCK_STREAM, 0);
  7073. if (handle < 0)
  7074. return false;
  7075. if (isDatagram)
  7076. {
  7077. *serverAddress = new struct sockaddr_in();
  7078. *((struct sockaddr_in*) *serverAddress) = servTmpAddr;
  7079. return true;
  7080. }
  7081. setSocketBlockingState (handle, false);
  7082. const int result = ::connect (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in));
  7083. if (result < 0)
  7084. {
  7085. #if JUCE_WINDOWS
  7086. if (result == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK)
  7087. #else
  7088. if (errno == EINPROGRESS)
  7089. #endif
  7090. {
  7091. if (waitForReadiness (handle, false, timeOutMillisecs) != 1)
  7092. {
  7093. setSocketBlockingState (handle, true);
  7094. return false;
  7095. }
  7096. }
  7097. }
  7098. setSocketBlockingState (handle, true);
  7099. resetSocketOptions (handle, false, false);
  7100. return true;
  7101. }
  7102. }
  7103. StreamingSocket::StreamingSocket()
  7104. : portNumber (0),
  7105. handle (-1),
  7106. connected (false),
  7107. isListener (false)
  7108. {
  7109. #if JUCE_WINDOWS
  7110. SocketHelpers::initWin32Sockets();
  7111. #endif
  7112. }
  7113. StreamingSocket::StreamingSocket (const String& hostName_,
  7114. const int portNumber_,
  7115. const int handle_)
  7116. : hostName (hostName_),
  7117. portNumber (portNumber_),
  7118. handle (handle_),
  7119. connected (true),
  7120. isListener (false)
  7121. {
  7122. #if JUCE_WINDOWS
  7123. SocketHelpers::initWin32Sockets();
  7124. #endif
  7125. SocketHelpers::resetSocketOptions (handle_, false, false);
  7126. }
  7127. StreamingSocket::~StreamingSocket()
  7128. {
  7129. close();
  7130. }
  7131. int StreamingSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  7132. {
  7133. return (connected && ! isListener) ? SocketHelpers::readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  7134. : -1;
  7135. }
  7136. int StreamingSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  7137. {
  7138. if (isListener || ! connected)
  7139. return -1;
  7140. #if JUCE_WINDOWS
  7141. return send (handle, (const char*) sourceBuffer, numBytesToWrite, 0);
  7142. #else
  7143. int result;
  7144. while ((result = (int) ::write (handle, sourceBuffer, numBytesToWrite)) < 0
  7145. && errno == EINTR)
  7146. {
  7147. }
  7148. return result;
  7149. #endif
  7150. }
  7151. int StreamingSocket::waitUntilReady (const bool readyForReading,
  7152. const int timeoutMsecs) const
  7153. {
  7154. return connected ? SocketHelpers::waitForReadiness (handle, readyForReading, timeoutMsecs)
  7155. : -1;
  7156. }
  7157. bool StreamingSocket::bindToPort (const int port)
  7158. {
  7159. return SocketHelpers::bindSocketToPort (handle, port);
  7160. }
  7161. bool StreamingSocket::connect (const String& remoteHostName,
  7162. const int remotePortNumber,
  7163. const int timeOutMillisecs)
  7164. {
  7165. if (isListener)
  7166. {
  7167. jassertfalse; // a listener socket can't connect to another one!
  7168. return false;
  7169. }
  7170. if (connected)
  7171. close();
  7172. hostName = remoteHostName;
  7173. portNumber = remotePortNumber;
  7174. isListener = false;
  7175. connected = SocketHelpers::connectSocket (handle, false, 0, remoteHostName,
  7176. remotePortNumber, timeOutMillisecs);
  7177. if (! (connected && SocketHelpers::resetSocketOptions (handle, false, false)))
  7178. {
  7179. close();
  7180. return false;
  7181. }
  7182. return true;
  7183. }
  7184. void StreamingSocket::close()
  7185. {
  7186. #if JUCE_WINDOWS
  7187. if (handle != SOCKET_ERROR || connected)
  7188. closesocket (handle);
  7189. connected = false;
  7190. #else
  7191. if (connected)
  7192. {
  7193. connected = false;
  7194. if (isListener)
  7195. {
  7196. // need to do this to interrupt the accept() function..
  7197. StreamingSocket temp;
  7198. temp.connect ("localhost", portNumber, 1000);
  7199. }
  7200. }
  7201. if (handle != -1)
  7202. ::close (handle);
  7203. #endif
  7204. hostName = String::empty;
  7205. portNumber = 0;
  7206. handle = -1;
  7207. isListener = false;
  7208. }
  7209. bool StreamingSocket::createListener (const int newPortNumber, const String& localHostName)
  7210. {
  7211. if (connected)
  7212. close();
  7213. hostName = "listener";
  7214. portNumber = newPortNumber;
  7215. isListener = true;
  7216. struct sockaddr_in servTmpAddr;
  7217. zerostruct (servTmpAddr);
  7218. servTmpAddr.sin_family = PF_INET;
  7219. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  7220. if (localHostName.isNotEmpty())
  7221. servTmpAddr.sin_addr.s_addr = ::inet_addr (localHostName.toUTF8());
  7222. servTmpAddr.sin_port = htons ((uint16) portNumber);
  7223. handle = (int) socket (AF_INET, SOCK_STREAM, 0);
  7224. if (handle < 0)
  7225. return false;
  7226. const int reuse = 1;
  7227. setsockopt (handle, SOL_SOCKET, SO_REUSEADDR, (const char*) &reuse, sizeof (reuse));
  7228. if (bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) < 0
  7229. || listen (handle, SOMAXCONN) < 0)
  7230. {
  7231. close();
  7232. return false;
  7233. }
  7234. connected = true;
  7235. return true;
  7236. }
  7237. StreamingSocket* StreamingSocket::waitForNextConnection() const
  7238. {
  7239. jassert (isListener || ! connected); // to call this method, you first have to use createListener() to
  7240. // prepare this socket as a listener.
  7241. if (connected && isListener)
  7242. {
  7243. struct sockaddr address;
  7244. juce_socklen_t len = sizeof (sockaddr);
  7245. const int newSocket = (int) accept (handle, &address, &len);
  7246. if (newSocket >= 0 && connected)
  7247. return new StreamingSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  7248. portNumber, newSocket);
  7249. }
  7250. return 0;
  7251. }
  7252. bool StreamingSocket::isLocal() const throw()
  7253. {
  7254. return hostName == "127.0.0.1";
  7255. }
  7256. DatagramSocket::DatagramSocket (const int localPortNumber, const bool allowBroadcast_)
  7257. : portNumber (0),
  7258. handle (-1),
  7259. connected (true),
  7260. allowBroadcast (allowBroadcast_),
  7261. serverAddress (0)
  7262. {
  7263. #if JUCE_WINDOWS
  7264. SocketHelpers::initWin32Sockets();
  7265. #endif
  7266. handle = (int) socket (AF_INET, SOCK_DGRAM, 0);
  7267. bindToPort (localPortNumber);
  7268. }
  7269. DatagramSocket::DatagramSocket (const String& hostName_, const int portNumber_,
  7270. const int handle_, const int localPortNumber)
  7271. : hostName (hostName_),
  7272. portNumber (portNumber_),
  7273. handle (handle_),
  7274. connected (true),
  7275. allowBroadcast (false),
  7276. serverAddress (0)
  7277. {
  7278. #if JUCE_WINDOWS
  7279. SocketHelpers::initWin32Sockets();
  7280. #endif
  7281. SocketHelpers::resetSocketOptions (handle_, true, allowBroadcast);
  7282. bindToPort (localPortNumber);
  7283. }
  7284. DatagramSocket::~DatagramSocket()
  7285. {
  7286. close();
  7287. delete static_cast <struct sockaddr_in*> (serverAddress);
  7288. serverAddress = 0;
  7289. }
  7290. void DatagramSocket::close()
  7291. {
  7292. #if JUCE_WINDOWS
  7293. closesocket (handle);
  7294. connected = false;
  7295. #else
  7296. connected = false;
  7297. ::close (handle);
  7298. #endif
  7299. hostName = String::empty;
  7300. portNumber = 0;
  7301. handle = -1;
  7302. }
  7303. bool DatagramSocket::bindToPort (const int port)
  7304. {
  7305. return SocketHelpers::bindSocketToPort (handle, port);
  7306. }
  7307. bool DatagramSocket::connect (const String& remoteHostName,
  7308. const int remotePortNumber,
  7309. const int timeOutMillisecs)
  7310. {
  7311. if (connected)
  7312. close();
  7313. hostName = remoteHostName;
  7314. portNumber = remotePortNumber;
  7315. connected = SocketHelpers::connectSocket (handle, true, &serverAddress,
  7316. remoteHostName, remotePortNumber,
  7317. timeOutMillisecs);
  7318. if (! (connected && SocketHelpers::resetSocketOptions (handle, true, allowBroadcast)))
  7319. {
  7320. close();
  7321. return false;
  7322. }
  7323. return true;
  7324. }
  7325. DatagramSocket* DatagramSocket::waitForNextConnection() const
  7326. {
  7327. struct sockaddr address;
  7328. juce_socklen_t len = sizeof (sockaddr);
  7329. while (waitUntilReady (true, -1) == 1)
  7330. {
  7331. char buf[1];
  7332. if (recvfrom (handle, buf, 0, 0, &address, &len) > 0)
  7333. {
  7334. return new DatagramSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  7335. ntohs (((struct sockaddr_in*) &address)->sin_port),
  7336. -1, -1);
  7337. }
  7338. }
  7339. return 0;
  7340. }
  7341. int DatagramSocket::waitUntilReady (const bool readyForReading,
  7342. const int timeoutMsecs) const
  7343. {
  7344. return connected ? SocketHelpers::waitForReadiness (handle, readyForReading, timeoutMsecs)
  7345. : -1;
  7346. }
  7347. int DatagramSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  7348. {
  7349. return connected ? SocketHelpers::readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  7350. : -1;
  7351. }
  7352. int DatagramSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  7353. {
  7354. // You need to call connect() first to set the server address..
  7355. jassert (serverAddress != 0 && connected);
  7356. return connected ? (int) sendto (handle, (const char*) sourceBuffer,
  7357. numBytesToWrite, 0,
  7358. (const struct sockaddr*) serverAddress,
  7359. sizeof (struct sockaddr_in))
  7360. : -1;
  7361. }
  7362. bool DatagramSocket::isLocal() const throw()
  7363. {
  7364. return hostName == "127.0.0.1";
  7365. }
  7366. #if JUCE_MSVC
  7367. #pragma warning (pop)
  7368. #endif
  7369. END_JUCE_NAMESPACE
  7370. /*** End of inlined file: juce_Socket.cpp ***/
  7371. /*** Start of inlined file: juce_URL.cpp ***/
  7372. BEGIN_JUCE_NAMESPACE
  7373. URL::URL()
  7374. {
  7375. }
  7376. URL::URL (const String& url_)
  7377. : url (url_)
  7378. {
  7379. int i = url.indexOfChar ('?');
  7380. if (i >= 0)
  7381. {
  7382. do
  7383. {
  7384. const int nextAmp = url.indexOfChar (i + 1, '&');
  7385. const int equalsPos = url.indexOfChar (i + 1, '=');
  7386. if (equalsPos > i + 1)
  7387. {
  7388. if (nextAmp < 0)
  7389. {
  7390. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  7391. removeEscapeChars (url.substring (equalsPos + 1)));
  7392. }
  7393. else if (nextAmp > 0 && equalsPos < nextAmp)
  7394. {
  7395. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  7396. removeEscapeChars (url.substring (equalsPos + 1, nextAmp)));
  7397. }
  7398. }
  7399. i = nextAmp;
  7400. }
  7401. while (i >= 0);
  7402. url = url.upToFirstOccurrenceOf ("?", false, false);
  7403. }
  7404. }
  7405. URL::URL (const URL& other)
  7406. : url (other.url),
  7407. postData (other.postData),
  7408. parameters (other.parameters),
  7409. filesToUpload (other.filesToUpload),
  7410. mimeTypes (other.mimeTypes)
  7411. {
  7412. }
  7413. URL& URL::operator= (const URL& other)
  7414. {
  7415. url = other.url;
  7416. postData = other.postData;
  7417. parameters = other.parameters;
  7418. filesToUpload = other.filesToUpload;
  7419. mimeTypes = other.mimeTypes;
  7420. return *this;
  7421. }
  7422. URL::~URL()
  7423. {
  7424. }
  7425. namespace URLHelpers
  7426. {
  7427. const String getMangledParameters (const StringPairArray& parameters)
  7428. {
  7429. String p;
  7430. for (int i = 0; i < parameters.size(); ++i)
  7431. {
  7432. if (i > 0)
  7433. p << '&';
  7434. p << URL::addEscapeChars (parameters.getAllKeys() [i], true)
  7435. << '='
  7436. << URL::addEscapeChars (parameters.getAllValues() [i], true);
  7437. }
  7438. return p;
  7439. }
  7440. int findStartOfDomain (const String& url)
  7441. {
  7442. int i = 0;
  7443. while (CharacterFunctions::isLetterOrDigit (url[i])
  7444. || CharacterFunctions::indexOfChar (L"+-.", url[i], false) >= 0)
  7445. ++i;
  7446. return url[i] == ':' ? i + 1 : 0;
  7447. }
  7448. }
  7449. const String URL::toString (const bool includeGetParameters) const
  7450. {
  7451. if (includeGetParameters && parameters.size() > 0)
  7452. return url + "?" + URLHelpers::getMangledParameters (parameters);
  7453. else
  7454. return url;
  7455. }
  7456. bool URL::isWellFormed() const
  7457. {
  7458. //xxx TODO
  7459. return url.isNotEmpty();
  7460. }
  7461. const String URL::getDomain() const
  7462. {
  7463. int start = URLHelpers::findStartOfDomain (url);
  7464. while (url[start] == '/')
  7465. ++start;
  7466. const int end1 = url.indexOfChar (start, '/');
  7467. const int end2 = url.indexOfChar (start, ':');
  7468. const int end = (end1 < 0 || end2 < 0) ? jmax (end1, end2)
  7469. : jmin (end1, end2);
  7470. return url.substring (start, end);
  7471. }
  7472. const String URL::getSubPath() const
  7473. {
  7474. int start = URLHelpers::findStartOfDomain (url);
  7475. while (url[start] == '/')
  7476. ++start;
  7477. const int startOfPath = url.indexOfChar (start, '/') + 1;
  7478. return startOfPath <= 0 ? String::empty
  7479. : url.substring (startOfPath);
  7480. }
  7481. const String URL::getScheme() const
  7482. {
  7483. return url.substring (0, URLHelpers::findStartOfDomain (url) - 1);
  7484. }
  7485. const URL URL::withNewSubPath (const String& newPath) const
  7486. {
  7487. int start = URLHelpers::findStartOfDomain (url);
  7488. while (url[start] == '/')
  7489. ++start;
  7490. const int startOfPath = url.indexOfChar (start, '/') + 1;
  7491. URL u (*this);
  7492. if (startOfPath > 0)
  7493. u.url = url.substring (0, startOfPath);
  7494. if (! u.url.endsWithChar ('/'))
  7495. u.url << '/';
  7496. if (newPath.startsWithChar ('/'))
  7497. u.url << newPath.substring (1);
  7498. else
  7499. u.url << newPath;
  7500. return u;
  7501. }
  7502. bool URL::isProbablyAWebsiteURL (const String& possibleURL)
  7503. {
  7504. if (possibleURL.startsWithIgnoreCase ("http:")
  7505. || possibleURL.startsWithIgnoreCase ("ftp:"))
  7506. return true;
  7507. if (possibleURL.startsWithIgnoreCase ("file:")
  7508. || possibleURL.containsChar ('@')
  7509. || possibleURL.endsWithChar ('.')
  7510. || (! possibleURL.containsChar ('.')))
  7511. return false;
  7512. if (possibleURL.startsWithIgnoreCase ("www.")
  7513. && possibleURL.substring (5).containsChar ('.'))
  7514. return true;
  7515. const char* commonTLDs[] = { "com", "net", "org", "uk", "de", "fr", "jp" };
  7516. for (int i = 0; i < numElementsInArray (commonTLDs); ++i)
  7517. if ((possibleURL + "/").containsIgnoreCase ("." + String (commonTLDs[i]) + "/"))
  7518. return true;
  7519. return false;
  7520. }
  7521. bool URL::isProbablyAnEmailAddress (const String& possibleEmailAddress)
  7522. {
  7523. const int atSign = possibleEmailAddress.indexOfChar ('@');
  7524. return atSign > 0
  7525. && possibleEmailAddress.lastIndexOfChar ('.') > (atSign + 1)
  7526. && (! possibleEmailAddress.endsWithChar ('.'));
  7527. }
  7528. void* juce_openInternetFile (const String& url,
  7529. const String& headers,
  7530. const MemoryBlock& optionalPostData,
  7531. const bool isPost,
  7532. URL::OpenStreamProgressCallback* callback,
  7533. void* callbackContext,
  7534. int timeOutMs);
  7535. void juce_closeInternetFile (void* handle);
  7536. int juce_readFromInternetFile (void* handle, void* dest, int bytesToRead);
  7537. int juce_seekInInternetFile (void* handle, int newPosition);
  7538. int64 juce_getInternetFileContentLength (void* handle);
  7539. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers);
  7540. class WebInputStream : public InputStream
  7541. {
  7542. public:
  7543. WebInputStream (const URL& url,
  7544. const bool isPost_,
  7545. URL::OpenStreamProgressCallback* const progressCallback_,
  7546. void* const progressCallbackContext_,
  7547. const String& extraHeaders,
  7548. const int timeOutMs_,
  7549. StringPairArray* const responseHeaders)
  7550. : position (0),
  7551. finished (false),
  7552. isPost (isPost_),
  7553. progressCallback (progressCallback_),
  7554. progressCallbackContext (progressCallbackContext_),
  7555. timeOutMs (timeOutMs_)
  7556. {
  7557. server = url.toString (! isPost);
  7558. if (isPost_)
  7559. createHeadersAndPostData (url);
  7560. headers += extraHeaders;
  7561. if (! headers.endsWithChar ('\n'))
  7562. headers << "\r\n";
  7563. handle = juce_openInternetFile (server, headers, postData, isPost,
  7564. progressCallback_, progressCallbackContext_,
  7565. timeOutMs);
  7566. if (responseHeaders != 0)
  7567. juce_getInternetFileHeaders (handle, *responseHeaders);
  7568. }
  7569. ~WebInputStream()
  7570. {
  7571. juce_closeInternetFile (handle);
  7572. }
  7573. bool isError() const { return handle == 0; }
  7574. int64 getTotalLength() { return juce_getInternetFileContentLength (handle); }
  7575. bool isExhausted() { return finished; }
  7576. int64 getPosition() { return position; }
  7577. int read (void* dest, int bytes)
  7578. {
  7579. if (finished || isError())
  7580. {
  7581. return 0;
  7582. }
  7583. else
  7584. {
  7585. const int bytesRead = juce_readFromInternetFile (handle, dest, bytes);
  7586. position += bytesRead;
  7587. if (bytesRead == 0)
  7588. finished = true;
  7589. return bytesRead;
  7590. }
  7591. }
  7592. bool setPosition (int64 wantedPos)
  7593. {
  7594. if (wantedPos != position)
  7595. {
  7596. finished = false;
  7597. const int actualPos = juce_seekInInternetFile (handle, (int) wantedPos);
  7598. if (actualPos == wantedPos)
  7599. {
  7600. position = wantedPos;
  7601. }
  7602. else
  7603. {
  7604. if (wantedPos < position)
  7605. {
  7606. juce_closeInternetFile (handle);
  7607. position = 0;
  7608. finished = false;
  7609. handle = juce_openInternetFile (server, headers, postData, isPost,
  7610. progressCallback, progressCallbackContext,
  7611. timeOutMs);
  7612. }
  7613. skipNextBytes (wantedPos - position);
  7614. }
  7615. }
  7616. return true;
  7617. }
  7618. juce_UseDebuggingNewOperator
  7619. private:
  7620. String server, headers;
  7621. MemoryBlock postData;
  7622. int64 position;
  7623. bool finished;
  7624. const bool isPost;
  7625. void* handle;
  7626. URL::OpenStreamProgressCallback* const progressCallback;
  7627. void* const progressCallbackContext;
  7628. const int timeOutMs;
  7629. void createHeadersAndPostData (const URL& url)
  7630. {
  7631. MemoryOutputStream data (postData, false);
  7632. if (url.getFilesToUpload().size() > 0)
  7633. {
  7634. // need to upload some files, so do it as multi-part...
  7635. const String boundary (String::toHexString (Random::getSystemRandom().nextInt64()));
  7636. headers << "Content-Type: multipart/form-data; boundary=" << boundary << "\r\n";
  7637. data << "--" << boundary;
  7638. int i;
  7639. for (i = 0; i < url.getParameters().size(); ++i)
  7640. {
  7641. data << "\r\nContent-Disposition: form-data; name=\""
  7642. << url.getParameters().getAllKeys() [i]
  7643. << "\"\r\n\r\n"
  7644. << url.getParameters().getAllValues() [i]
  7645. << "\r\n--"
  7646. << boundary;
  7647. }
  7648. for (i = 0; i < url.getFilesToUpload().size(); ++i)
  7649. {
  7650. const File file (url.getFilesToUpload().getAllValues() [i]);
  7651. const String paramName (url.getFilesToUpload().getAllKeys() [i]);
  7652. data << "\r\nContent-Disposition: form-data; name=\"" << paramName
  7653. << "\"; filename=\"" << file.getFileName() << "\"\r\n";
  7654. const String mimeType (url.getMimeTypesOfUploadFiles()
  7655. .getValue (paramName, String::empty));
  7656. if (mimeType.isNotEmpty())
  7657. data << "Content-Type: " << mimeType << "\r\n";
  7658. data << "Content-Transfer-Encoding: binary\r\n\r\n"
  7659. << file << "\r\n--" << boundary;
  7660. }
  7661. data << "--\r\n";
  7662. data.flush();
  7663. }
  7664. else
  7665. {
  7666. data << URLHelpers::getMangledParameters (url.getParameters())
  7667. << url.getPostData();
  7668. data.flush();
  7669. // just a short text attachment, so use simple url encoding..
  7670. headers = "Content-Type: application/x-www-form-urlencoded\r\nContent-length: "
  7671. + String ((unsigned int) postData.getSize())
  7672. + "\r\n";
  7673. }
  7674. }
  7675. WebInputStream (const WebInputStream&);
  7676. WebInputStream& operator= (const WebInputStream&);
  7677. };
  7678. InputStream* URL::createInputStream (const bool usePostCommand,
  7679. OpenStreamProgressCallback* const progressCallback,
  7680. void* const progressCallbackContext,
  7681. const String& extraHeaders,
  7682. const int timeOutMs,
  7683. StringPairArray* const responseHeaders) const
  7684. {
  7685. ScopedPointer <WebInputStream> wi (new WebInputStream (*this, usePostCommand,
  7686. progressCallback, progressCallbackContext,
  7687. extraHeaders, timeOutMs, responseHeaders));
  7688. return wi->isError() ? 0 : wi.release();
  7689. }
  7690. bool URL::readEntireBinaryStream (MemoryBlock& destData,
  7691. const bool usePostCommand) const
  7692. {
  7693. const ScopedPointer <InputStream> in (createInputStream (usePostCommand));
  7694. if (in != 0)
  7695. {
  7696. in->readIntoMemoryBlock (destData);
  7697. return true;
  7698. }
  7699. return false;
  7700. }
  7701. const String URL::readEntireTextStream (const bool usePostCommand) const
  7702. {
  7703. const ScopedPointer <InputStream> in (createInputStream (usePostCommand));
  7704. if (in != 0)
  7705. return in->readEntireStreamAsString();
  7706. return String::empty;
  7707. }
  7708. XmlElement* URL::readEntireXmlStream (const bool usePostCommand) const
  7709. {
  7710. XmlDocument doc (readEntireTextStream (usePostCommand));
  7711. return doc.getDocumentElement();
  7712. }
  7713. const URL URL::withParameter (const String& parameterName,
  7714. const String& parameterValue) const
  7715. {
  7716. URL u (*this);
  7717. u.parameters.set (parameterName, parameterValue);
  7718. return u;
  7719. }
  7720. const URL URL::withFileToUpload (const String& parameterName,
  7721. const File& fileToUpload,
  7722. const String& mimeType) const
  7723. {
  7724. jassert (mimeType.isNotEmpty()); // You need to supply a mime type!
  7725. URL u (*this);
  7726. u.filesToUpload.set (parameterName, fileToUpload.getFullPathName());
  7727. u.mimeTypes.set (parameterName, mimeType);
  7728. return u;
  7729. }
  7730. const URL URL::withPOSTData (const String& postData_) const
  7731. {
  7732. URL u (*this);
  7733. u.postData = postData_;
  7734. return u;
  7735. }
  7736. const StringPairArray& URL::getParameters() const
  7737. {
  7738. return parameters;
  7739. }
  7740. const StringPairArray& URL::getFilesToUpload() const
  7741. {
  7742. return filesToUpload;
  7743. }
  7744. const StringPairArray& URL::getMimeTypesOfUploadFiles() const
  7745. {
  7746. return mimeTypes;
  7747. }
  7748. const String URL::removeEscapeChars (const String& s)
  7749. {
  7750. String result (s.replaceCharacter ('+', ' '));
  7751. if (! result.containsChar ('%'))
  7752. return result;
  7753. // We need to operate on the string as raw UTF8 chars, and then recombine them into unicode
  7754. // after all the replacements have been made, so that multi-byte chars are handled.
  7755. Array<char> utf8 (result.toUTF8(), result.getNumBytesAsUTF8());
  7756. for (int i = 0; i < utf8.size(); ++i)
  7757. {
  7758. if (utf8.getUnchecked(i) == '%')
  7759. {
  7760. const int hexDigit1 = CharacterFunctions::getHexDigitValue (utf8 [i + 1]);
  7761. const int hexDigit2 = CharacterFunctions::getHexDigitValue (utf8 [i + 2]);
  7762. if (hexDigit1 >= 0 && hexDigit2 >= 0)
  7763. {
  7764. utf8.set (i, (char) ((hexDigit1 << 4) + hexDigit2));
  7765. utf8.removeRange (i + 1, 2);
  7766. }
  7767. }
  7768. }
  7769. return String::fromUTF8 (utf8.getRawDataPointer(), utf8.size());
  7770. }
  7771. const String URL::addEscapeChars (const String& s, const bool isParameter)
  7772. {
  7773. const char* const legalChars = isParameter ? "_-.*!'()"
  7774. : ",$_-.*!'()";
  7775. Array<char> utf8 (s.toUTF8(), s.getNumBytesAsUTF8());
  7776. for (int i = 0; i < utf8.size(); ++i)
  7777. {
  7778. const char c = utf8.getUnchecked(i);
  7779. if (! (CharacterFunctions::isLetterOrDigit (c)
  7780. || CharacterFunctions::indexOfChar (legalChars, c, false) >= 0))
  7781. {
  7782. if (c == ' ')
  7783. {
  7784. utf8.set (i, '+');
  7785. }
  7786. else
  7787. {
  7788. static const char* const hexDigits = "0123456789abcdef";
  7789. utf8.set (i, '%');
  7790. utf8.insert (++i, hexDigits [((uint8) c) >> 4]);
  7791. utf8.insert (++i, hexDigits [c & 15]);
  7792. }
  7793. }
  7794. }
  7795. return String::fromUTF8 (utf8.getRawDataPointer(), utf8.size());
  7796. }
  7797. bool URL::launchInDefaultBrowser() const
  7798. {
  7799. String u (toString (true));
  7800. if (u.containsChar ('@') && ! u.containsChar (':'))
  7801. u = "mailto:" + u;
  7802. return PlatformUtilities::openDocument (u, String::empty);
  7803. }
  7804. END_JUCE_NAMESPACE
  7805. /*** End of inlined file: juce_URL.cpp ***/
  7806. /*** Start of inlined file: juce_MACAddress.cpp ***/
  7807. BEGIN_JUCE_NAMESPACE
  7808. MACAddress::MACAddress()
  7809. : asInt64 (0)
  7810. {
  7811. }
  7812. MACAddress::MACAddress (const MACAddress& other)
  7813. : asInt64 (other.asInt64)
  7814. {
  7815. }
  7816. MACAddress& MACAddress::operator= (const MACAddress& other)
  7817. {
  7818. asInt64 = other.asInt64;
  7819. return *this;
  7820. }
  7821. MACAddress::MACAddress (const uint8 bytes[6])
  7822. : asInt64 (0)
  7823. {
  7824. memcpy (asBytes, bytes, sizeof (asBytes));
  7825. }
  7826. const String MACAddress::toString() const
  7827. {
  7828. String s;
  7829. s.preallocateStorage (18);
  7830. for (int i = 0; i < numElementsInArray (asBytes); ++i)
  7831. {
  7832. s << String::toHexString ((int) asBytes[i]).paddedLeft ('0', 2);
  7833. if (i < numElementsInArray (asBytes) - 1)
  7834. s << '-';
  7835. }
  7836. return s;
  7837. }
  7838. int64 MACAddress::toInt64() const throw()
  7839. {
  7840. int64 n = 0;
  7841. for (int i = numElementsInArray (asBytes); --i >= 0;)
  7842. n = (n << 8) | asBytes[i];
  7843. return n;
  7844. }
  7845. bool MACAddress::isNull() const throw() { return asInt64 == 0; }
  7846. bool MACAddress::operator== (const MACAddress& other) const throw() { return asInt64 == other.asInt64; }
  7847. bool MACAddress::operator!= (const MACAddress& other) const throw() { return asInt64 != other.asInt64; }
  7848. END_JUCE_NAMESPACE
  7849. /*** End of inlined file: juce_MACAddress.cpp ***/
  7850. /*** Start of inlined file: juce_BufferedInputStream.cpp ***/
  7851. BEGIN_JUCE_NAMESPACE
  7852. namespace
  7853. {
  7854. int calcBufferStreamBufferSize (int requestedSize, InputStream* const source) throw()
  7855. {
  7856. // You need to supply a real stream when creating a BufferedInputStream
  7857. jassert (source != 0);
  7858. requestedSize = jmax (256, requestedSize);
  7859. const int64 sourceSize = source->getTotalLength();
  7860. if (sourceSize >= 0 && sourceSize < requestedSize)
  7861. requestedSize = jmax (32, (int) sourceSize);
  7862. return requestedSize;
  7863. }
  7864. }
  7865. BufferedInputStream::BufferedInputStream (InputStream* const sourceStream, const int bufferSize_,
  7866. const bool deleteSourceWhenDestroyed)
  7867. : source (sourceStream),
  7868. sourceToDelete (deleteSourceWhenDestroyed ? sourceStream : 0),
  7869. bufferSize (calcBufferStreamBufferSize (bufferSize_, sourceStream)),
  7870. position (sourceStream->getPosition()),
  7871. lastReadPos (0),
  7872. bufferStart (position),
  7873. bufferOverlap (128)
  7874. {
  7875. buffer.malloc (bufferSize);
  7876. }
  7877. BufferedInputStream::BufferedInputStream (InputStream& sourceStream, const int bufferSize_)
  7878. : source (&sourceStream),
  7879. bufferSize (calcBufferStreamBufferSize (bufferSize_, &sourceStream)),
  7880. position (sourceStream.getPosition()),
  7881. lastReadPos (0),
  7882. bufferStart (position),
  7883. bufferOverlap (128)
  7884. {
  7885. buffer.malloc (bufferSize);
  7886. }
  7887. BufferedInputStream::~BufferedInputStream()
  7888. {
  7889. }
  7890. int64 BufferedInputStream::getTotalLength()
  7891. {
  7892. return source->getTotalLength();
  7893. }
  7894. int64 BufferedInputStream::getPosition()
  7895. {
  7896. return position;
  7897. }
  7898. bool BufferedInputStream::setPosition (int64 newPosition)
  7899. {
  7900. position = jmax ((int64) 0, newPosition);
  7901. return true;
  7902. }
  7903. bool BufferedInputStream::isExhausted()
  7904. {
  7905. return (position >= lastReadPos)
  7906. && source->isExhausted();
  7907. }
  7908. void BufferedInputStream::ensureBuffered()
  7909. {
  7910. const int64 bufferEndOverlap = lastReadPos - bufferOverlap;
  7911. if (position < bufferStart || position >= bufferEndOverlap)
  7912. {
  7913. int bytesRead;
  7914. if (position < lastReadPos
  7915. && position >= bufferEndOverlap
  7916. && position >= bufferStart)
  7917. {
  7918. const int bytesToKeep = (int) (lastReadPos - position);
  7919. memmove (buffer, buffer + (int) (position - bufferStart), bytesToKeep);
  7920. bufferStart = position;
  7921. bytesRead = source->read (buffer + bytesToKeep,
  7922. bufferSize - bytesToKeep);
  7923. lastReadPos += bytesRead;
  7924. bytesRead += bytesToKeep;
  7925. }
  7926. else
  7927. {
  7928. bufferStart = position;
  7929. source->setPosition (bufferStart);
  7930. bytesRead = source->read (buffer, bufferSize);
  7931. lastReadPos = bufferStart + bytesRead;
  7932. }
  7933. while (bytesRead < bufferSize)
  7934. buffer [bytesRead++] = 0;
  7935. }
  7936. }
  7937. int BufferedInputStream::read (void* destBuffer, int maxBytesToRead)
  7938. {
  7939. if (position >= bufferStart
  7940. && position + maxBytesToRead <= lastReadPos)
  7941. {
  7942. memcpy (destBuffer, buffer + (int) (position - bufferStart), maxBytesToRead);
  7943. position += maxBytesToRead;
  7944. return maxBytesToRead;
  7945. }
  7946. else
  7947. {
  7948. if (position < bufferStart || position >= lastReadPos)
  7949. ensureBuffered();
  7950. int bytesRead = 0;
  7951. while (maxBytesToRead > 0)
  7952. {
  7953. const int bytesAvailable = jmin (maxBytesToRead, (int) (lastReadPos - position));
  7954. if (bytesAvailable > 0)
  7955. {
  7956. memcpy (destBuffer, buffer + (int) (position - bufferStart), bytesAvailable);
  7957. maxBytesToRead -= bytesAvailable;
  7958. bytesRead += bytesAvailable;
  7959. position += bytesAvailable;
  7960. destBuffer = static_cast <char*> (destBuffer) + bytesAvailable;
  7961. }
  7962. const int64 oldLastReadPos = lastReadPos;
  7963. ensureBuffered();
  7964. if (oldLastReadPos == lastReadPos)
  7965. break; // if ensureBuffered() failed to read any more data, bail out
  7966. if (isExhausted())
  7967. break;
  7968. }
  7969. return bytesRead;
  7970. }
  7971. }
  7972. const String BufferedInputStream::readString()
  7973. {
  7974. if (position >= bufferStart
  7975. && position < lastReadPos)
  7976. {
  7977. const int maxChars = (int) (lastReadPos - position);
  7978. const char* const src = buffer + (int) (position - bufferStart);
  7979. for (int i = 0; i < maxChars; ++i)
  7980. {
  7981. if (src[i] == 0)
  7982. {
  7983. position += i + 1;
  7984. return String::fromUTF8 (src, i);
  7985. }
  7986. }
  7987. }
  7988. return InputStream::readString();
  7989. }
  7990. END_JUCE_NAMESPACE
  7991. /*** End of inlined file: juce_BufferedInputStream.cpp ***/
  7992. /*** Start of inlined file: juce_FileInputSource.cpp ***/
  7993. BEGIN_JUCE_NAMESPACE
  7994. FileInputSource::FileInputSource (const File& file_)
  7995. : file (file_)
  7996. {
  7997. }
  7998. FileInputSource::~FileInputSource()
  7999. {
  8000. }
  8001. InputStream* FileInputSource::createInputStream()
  8002. {
  8003. return file.createInputStream();
  8004. }
  8005. InputStream* FileInputSource::createInputStreamFor (const String& relatedItemPath)
  8006. {
  8007. return file.getSiblingFile (relatedItemPath).createInputStream();
  8008. }
  8009. int64 FileInputSource::hashCode() const
  8010. {
  8011. return file.hashCode();
  8012. }
  8013. END_JUCE_NAMESPACE
  8014. /*** End of inlined file: juce_FileInputSource.cpp ***/
  8015. /*** Start of inlined file: juce_MemoryInputStream.cpp ***/
  8016. BEGIN_JUCE_NAMESPACE
  8017. MemoryInputStream::MemoryInputStream (const void* const sourceData,
  8018. const size_t sourceDataSize,
  8019. const bool keepInternalCopy)
  8020. : data (static_cast <const char*> (sourceData)),
  8021. dataSize (sourceDataSize),
  8022. position (0)
  8023. {
  8024. if (keepInternalCopy)
  8025. {
  8026. internalCopy.append (data, sourceDataSize);
  8027. data = static_cast <const char*> (internalCopy.getData());
  8028. }
  8029. }
  8030. MemoryInputStream::MemoryInputStream (const MemoryBlock& sourceData,
  8031. const bool keepInternalCopy)
  8032. : data (static_cast <const char*> (sourceData.getData())),
  8033. dataSize (sourceData.getSize()),
  8034. position (0)
  8035. {
  8036. if (keepInternalCopy)
  8037. {
  8038. internalCopy = sourceData;
  8039. data = static_cast <const char*> (internalCopy.getData());
  8040. }
  8041. }
  8042. MemoryInputStream::~MemoryInputStream()
  8043. {
  8044. }
  8045. int64 MemoryInputStream::getTotalLength()
  8046. {
  8047. return dataSize;
  8048. }
  8049. int MemoryInputStream::read (void* const buffer, const int howMany)
  8050. {
  8051. jassert (howMany >= 0);
  8052. const int num = jmin (howMany, (int) (dataSize - position));
  8053. memcpy (buffer, data + position, num);
  8054. position += num;
  8055. return (int) num;
  8056. }
  8057. bool MemoryInputStream::isExhausted()
  8058. {
  8059. return (position >= dataSize);
  8060. }
  8061. bool MemoryInputStream::setPosition (const int64 pos)
  8062. {
  8063. position = (int) jlimit ((int64) 0, (int64) dataSize, pos);
  8064. return true;
  8065. }
  8066. int64 MemoryInputStream::getPosition()
  8067. {
  8068. return position;
  8069. }
  8070. #if JUCE_UNIT_TESTS
  8071. class MemoryStreamTests : public UnitTest
  8072. {
  8073. public:
  8074. MemoryStreamTests() : UnitTest ("MemoryInputStream & MemoryOutputStream") {}
  8075. void runTest()
  8076. {
  8077. beginTest ("Basics");
  8078. int randomInt = Random::getSystemRandom().nextInt();
  8079. int64 randomInt64 = Random::getSystemRandom().nextInt64();
  8080. double randomDouble = Random::getSystemRandom().nextDouble();
  8081. String randomString;
  8082. for (int i = 50; --i >= 0;)
  8083. randomString << (juce_wchar) (Random::getSystemRandom().nextInt() & 0xffff);
  8084. MemoryOutputStream mo;
  8085. mo.writeInt (randomInt);
  8086. mo.writeIntBigEndian (randomInt);
  8087. mo.writeCompressedInt (randomInt);
  8088. mo.writeString (randomString);
  8089. mo.writeInt64 (randomInt64);
  8090. mo.writeInt64BigEndian (randomInt64);
  8091. mo.writeDouble (randomDouble);
  8092. mo.writeDoubleBigEndian (randomDouble);
  8093. MemoryInputStream mi (mo.getData(), mo.getDataSize(), false);
  8094. expect (mi.readInt() == randomInt);
  8095. expect (mi.readIntBigEndian() == randomInt);
  8096. expect (mi.readCompressedInt() == randomInt);
  8097. expect (mi.readString() == randomString);
  8098. expect (mi.readInt64() == randomInt64);
  8099. expect (mi.readInt64BigEndian() == randomInt64);
  8100. expect (mi.readDouble() == randomDouble);
  8101. expect (mi.readDoubleBigEndian() == randomDouble);
  8102. }
  8103. };
  8104. static MemoryStreamTests memoryInputStreamUnitTests;
  8105. #endif
  8106. END_JUCE_NAMESPACE
  8107. /*** End of inlined file: juce_MemoryInputStream.cpp ***/
  8108. /*** Start of inlined file: juce_MemoryOutputStream.cpp ***/
  8109. BEGIN_JUCE_NAMESPACE
  8110. MemoryOutputStream::MemoryOutputStream (const size_t initialSize)
  8111. : data (internalBlock),
  8112. position (0),
  8113. size (0)
  8114. {
  8115. internalBlock.setSize (initialSize, false);
  8116. }
  8117. MemoryOutputStream::MemoryOutputStream (MemoryBlock& memoryBlockToWriteTo,
  8118. const bool appendToExistingBlockContent)
  8119. : data (memoryBlockToWriteTo),
  8120. position (0),
  8121. size (0)
  8122. {
  8123. if (appendToExistingBlockContent)
  8124. position = size = memoryBlockToWriteTo.getSize();
  8125. }
  8126. MemoryOutputStream::~MemoryOutputStream()
  8127. {
  8128. flush();
  8129. }
  8130. void MemoryOutputStream::flush()
  8131. {
  8132. if (&data != &internalBlock)
  8133. data.setSize (size, false);
  8134. }
  8135. void MemoryOutputStream::preallocate (const size_t bytesToPreallocate)
  8136. {
  8137. data.ensureSize (bytesToPreallocate + 1);
  8138. }
  8139. void MemoryOutputStream::reset() throw()
  8140. {
  8141. position = 0;
  8142. size = 0;
  8143. }
  8144. bool MemoryOutputStream::write (const void* const buffer, int howMany)
  8145. {
  8146. if (howMany > 0)
  8147. {
  8148. const size_t storageNeeded = position + howMany;
  8149. if (storageNeeded >= data.getSize())
  8150. data.ensureSize ((storageNeeded + jmin (storageNeeded / 2, (size_t) (1024 * 1024)) + 32) & ~31);
  8151. memcpy (static_cast<char*> (data.getData()) + position, buffer, howMany);
  8152. position += howMany;
  8153. size = jmax (size, position);
  8154. }
  8155. return true;
  8156. }
  8157. const void* MemoryOutputStream::getData() const throw()
  8158. {
  8159. void* const d = data.getData();
  8160. if (data.getSize() > size)
  8161. static_cast <char*> (d) [size] = 0;
  8162. return d;
  8163. }
  8164. bool MemoryOutputStream::setPosition (int64 newPosition)
  8165. {
  8166. if (newPosition <= (int64) size)
  8167. {
  8168. // ok to seek backwards
  8169. position = jlimit ((size_t) 0, size, (size_t) newPosition);
  8170. return true;
  8171. }
  8172. else
  8173. {
  8174. // trying to make it bigger isn't a good thing to do..
  8175. return false;
  8176. }
  8177. }
  8178. int MemoryOutputStream::writeFromInputStream (InputStream& source, int64 maxNumBytesToWrite)
  8179. {
  8180. // before writing from an input, see if we can preallocate to make it more efficient..
  8181. int64 availableData = source.getTotalLength() - source.getPosition();
  8182. if (availableData > 0)
  8183. {
  8184. if (maxNumBytesToWrite > 0 && maxNumBytesToWrite < availableData)
  8185. availableData = maxNumBytesToWrite;
  8186. preallocate (data.getSize() + (size_t) maxNumBytesToWrite);
  8187. }
  8188. return OutputStream::writeFromInputStream (source, maxNumBytesToWrite);
  8189. }
  8190. const String MemoryOutputStream::toUTF8() const
  8191. {
  8192. return String (static_cast <const char*> (getData()), getDataSize());
  8193. }
  8194. const String MemoryOutputStream::toString() const
  8195. {
  8196. return String::createStringFromData (getData(), getDataSize());
  8197. }
  8198. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryOutputStream& streamToRead)
  8199. {
  8200. stream.write (streamToRead.getData(), streamToRead.getDataSize());
  8201. return stream;
  8202. }
  8203. END_JUCE_NAMESPACE
  8204. /*** End of inlined file: juce_MemoryOutputStream.cpp ***/
  8205. /*** Start of inlined file: juce_SubregionStream.cpp ***/
  8206. BEGIN_JUCE_NAMESPACE
  8207. SubregionStream::SubregionStream (InputStream* const sourceStream,
  8208. const int64 startPositionInSourceStream_,
  8209. const int64 lengthOfSourceStream_,
  8210. const bool deleteSourceWhenDestroyed)
  8211. : source (sourceStream),
  8212. startPositionInSourceStream (startPositionInSourceStream_),
  8213. lengthOfSourceStream (lengthOfSourceStream_)
  8214. {
  8215. if (deleteSourceWhenDestroyed)
  8216. sourceToDelete = source;
  8217. setPosition (0);
  8218. }
  8219. SubregionStream::~SubregionStream()
  8220. {
  8221. }
  8222. int64 SubregionStream::getTotalLength()
  8223. {
  8224. const int64 srcLen = source->getTotalLength() - startPositionInSourceStream;
  8225. return (lengthOfSourceStream >= 0) ? jmin (lengthOfSourceStream, srcLen)
  8226. : srcLen;
  8227. }
  8228. int64 SubregionStream::getPosition()
  8229. {
  8230. return source->getPosition() - startPositionInSourceStream;
  8231. }
  8232. bool SubregionStream::setPosition (int64 newPosition)
  8233. {
  8234. return source->setPosition (jmax ((int64) 0, newPosition + startPositionInSourceStream));
  8235. }
  8236. int SubregionStream::read (void* destBuffer, int maxBytesToRead)
  8237. {
  8238. if (lengthOfSourceStream < 0)
  8239. {
  8240. return source->read (destBuffer, maxBytesToRead);
  8241. }
  8242. else
  8243. {
  8244. maxBytesToRead = (int) jmin ((int64) maxBytesToRead, lengthOfSourceStream - getPosition());
  8245. if (maxBytesToRead <= 0)
  8246. return 0;
  8247. return source->read (destBuffer, maxBytesToRead);
  8248. }
  8249. }
  8250. bool SubregionStream::isExhausted()
  8251. {
  8252. if (lengthOfSourceStream >= 0)
  8253. return (getPosition() >= lengthOfSourceStream) || source->isExhausted();
  8254. else
  8255. return source->isExhausted();
  8256. }
  8257. END_JUCE_NAMESPACE
  8258. /*** End of inlined file: juce_SubregionStream.cpp ***/
  8259. /*** Start of inlined file: juce_PerformanceCounter.cpp ***/
  8260. BEGIN_JUCE_NAMESPACE
  8261. PerformanceCounter::PerformanceCounter (const String& name_,
  8262. int runsPerPrintout,
  8263. const File& loggingFile)
  8264. : name (name_),
  8265. numRuns (0),
  8266. runsPerPrint (runsPerPrintout),
  8267. totalTime (0),
  8268. outputFile (loggingFile)
  8269. {
  8270. if (outputFile != File::nonexistent)
  8271. {
  8272. String s ("**** Counter for \"");
  8273. s << name_ << "\" started at: "
  8274. << Time::getCurrentTime().toString (true, true)
  8275. << "\r\n";
  8276. outputFile.appendText (s, false, false);
  8277. }
  8278. }
  8279. PerformanceCounter::~PerformanceCounter()
  8280. {
  8281. printStatistics();
  8282. }
  8283. void PerformanceCounter::start()
  8284. {
  8285. started = Time::getHighResolutionTicks();
  8286. }
  8287. void PerformanceCounter::stop()
  8288. {
  8289. const int64 now = Time::getHighResolutionTicks();
  8290. totalTime += 1000.0 * Time::highResolutionTicksToSeconds (now - started);
  8291. if (++numRuns == runsPerPrint)
  8292. printStatistics();
  8293. }
  8294. void PerformanceCounter::printStatistics()
  8295. {
  8296. if (numRuns > 0)
  8297. {
  8298. String s ("Performance count for \"");
  8299. s << name << "\" - average over " << numRuns << " run(s) = ";
  8300. const int micros = (int) (totalTime * (1000.0 / numRuns));
  8301. if (micros > 10000)
  8302. s << (micros/1000) << " millisecs";
  8303. else
  8304. s << micros << " microsecs";
  8305. s << ", total = " << String (totalTime / 1000, 5) << " seconds";
  8306. Logger::outputDebugString (s);
  8307. s << "\r\n";
  8308. if (outputFile != File::nonexistent)
  8309. outputFile.appendText (s, false, false);
  8310. numRuns = 0;
  8311. totalTime = 0;
  8312. }
  8313. }
  8314. END_JUCE_NAMESPACE
  8315. /*** End of inlined file: juce_PerformanceCounter.cpp ***/
  8316. /*** Start of inlined file: juce_Uuid.cpp ***/
  8317. BEGIN_JUCE_NAMESPACE
  8318. Uuid::Uuid()
  8319. {
  8320. // Mix up any available MAC addresses with some time-based pseudo-random numbers
  8321. // to make it very very unlikely that two UUIDs will ever be the same..
  8322. static int64 macAddresses[2];
  8323. static bool hasCheckedMacAddresses = false;
  8324. if (! hasCheckedMacAddresses)
  8325. {
  8326. hasCheckedMacAddresses = true;
  8327. Array<MACAddress> result;
  8328. MACAddress::findAllAddresses (result);
  8329. for (int i = 0; i < numElementsInArray (macAddresses); ++i)
  8330. macAddresses[i] = result[i].toInt64();
  8331. }
  8332. value.asInt64[0] = macAddresses[0];
  8333. value.asInt64[1] = macAddresses[1];
  8334. // We'll use both a local RNG that is re-seeded, plus the shared RNG,
  8335. // whose seed will carry over between calls to this method.
  8336. Random r (macAddresses[0] ^ macAddresses[1]
  8337. ^ Random::getSystemRandom().nextInt64());
  8338. for (int i = 4; --i >= 0;)
  8339. {
  8340. r.setSeedRandomly(); // calling this repeatedly improves randomness
  8341. value.asInt[i] ^= r.nextInt();
  8342. value.asInt[i] ^= Random::getSystemRandom().nextInt();
  8343. }
  8344. }
  8345. Uuid::~Uuid() throw()
  8346. {
  8347. }
  8348. Uuid::Uuid (const Uuid& other)
  8349. : value (other.value)
  8350. {
  8351. }
  8352. Uuid& Uuid::operator= (const Uuid& other)
  8353. {
  8354. value = other.value;
  8355. return *this;
  8356. }
  8357. bool Uuid::operator== (const Uuid& other) const
  8358. {
  8359. return value.asInt64[0] == other.value.asInt64[0]
  8360. && value.asInt64[1] == other.value.asInt64[1];
  8361. }
  8362. bool Uuid::operator!= (const Uuid& other) const
  8363. {
  8364. return ! operator== (other);
  8365. }
  8366. bool Uuid::isNull() const throw()
  8367. {
  8368. return (value.asInt64 [0] == 0) && (value.asInt64 [1] == 0);
  8369. }
  8370. const String Uuid::toString() const
  8371. {
  8372. return String::toHexString (value.asBytes, sizeof (value.asBytes), 0);
  8373. }
  8374. Uuid::Uuid (const String& uuidString)
  8375. {
  8376. operator= (uuidString);
  8377. }
  8378. Uuid& Uuid::operator= (const String& uuidString)
  8379. {
  8380. MemoryBlock mb;
  8381. mb.loadFromHexString (uuidString);
  8382. mb.ensureSize (sizeof (value.asBytes), true);
  8383. mb.copyTo (value.asBytes, 0, sizeof (value.asBytes));
  8384. return *this;
  8385. }
  8386. Uuid::Uuid (const uint8* const rawData)
  8387. {
  8388. operator= (rawData);
  8389. }
  8390. Uuid& Uuid::operator= (const uint8* const rawData)
  8391. {
  8392. if (rawData != 0)
  8393. memcpy (value.asBytes, rawData, sizeof (value.asBytes));
  8394. else
  8395. zeromem (value.asBytes, sizeof (value.asBytes));
  8396. return *this;
  8397. }
  8398. END_JUCE_NAMESPACE
  8399. /*** End of inlined file: juce_Uuid.cpp ***/
  8400. /*** Start of inlined file: juce_ZipFile.cpp ***/
  8401. BEGIN_JUCE_NAMESPACE
  8402. class ZipFile::ZipEntryInfo
  8403. {
  8404. public:
  8405. ZipFile::ZipEntry entry;
  8406. int streamOffset;
  8407. int compressedSize;
  8408. bool compressed;
  8409. };
  8410. class ZipFile::ZipInputStream : public InputStream
  8411. {
  8412. public:
  8413. ZipInputStream (ZipFile& file_, ZipFile::ZipEntryInfo& zei)
  8414. : file (file_),
  8415. zipEntryInfo (zei),
  8416. pos (0),
  8417. headerSize (0),
  8418. inputStream (0)
  8419. {
  8420. inputStream = file_.inputStream;
  8421. if (file_.inputSource != 0)
  8422. {
  8423. inputStream = streamToDelete = file.inputSource->createInputStream();
  8424. }
  8425. else
  8426. {
  8427. #if JUCE_DEBUG
  8428. file_.numOpenStreams++;
  8429. #endif
  8430. }
  8431. char buffer [30];
  8432. if (inputStream != 0
  8433. && inputStream->setPosition (zei.streamOffset)
  8434. && inputStream->read (buffer, 30) == 30
  8435. && ByteOrder::littleEndianInt (buffer) == 0x04034b50)
  8436. {
  8437. headerSize = 30 + ByteOrder::littleEndianShort (buffer + 26)
  8438. + ByteOrder::littleEndianShort (buffer + 28);
  8439. }
  8440. }
  8441. ~ZipInputStream()
  8442. {
  8443. #if JUCE_DEBUG
  8444. if (inputStream != 0 && inputStream == file.inputStream)
  8445. file.numOpenStreams--;
  8446. #endif
  8447. }
  8448. int64 getTotalLength()
  8449. {
  8450. return zipEntryInfo.compressedSize;
  8451. }
  8452. int read (void* buffer, int howMany)
  8453. {
  8454. if (headerSize <= 0)
  8455. return 0;
  8456. howMany = (int) jmin ((int64) howMany, zipEntryInfo.compressedSize - pos);
  8457. if (inputStream == 0)
  8458. return 0;
  8459. int num;
  8460. if (inputStream == file.inputStream)
  8461. {
  8462. const ScopedLock sl (file.lock);
  8463. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  8464. num = inputStream->read (buffer, howMany);
  8465. }
  8466. else
  8467. {
  8468. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  8469. num = inputStream->read (buffer, howMany);
  8470. }
  8471. pos += num;
  8472. return num;
  8473. }
  8474. bool isExhausted()
  8475. {
  8476. return headerSize <= 0 || pos >= zipEntryInfo.compressedSize;
  8477. }
  8478. int64 getPosition()
  8479. {
  8480. return pos;
  8481. }
  8482. bool setPosition (int64 newPos)
  8483. {
  8484. pos = jlimit ((int64) 0, (int64) zipEntryInfo.compressedSize, newPos);
  8485. return true;
  8486. }
  8487. private:
  8488. ZipFile& file;
  8489. ZipEntryInfo zipEntryInfo;
  8490. int64 pos;
  8491. int headerSize;
  8492. InputStream* inputStream;
  8493. ScopedPointer<InputStream> streamToDelete;
  8494. ZipInputStream (const ZipInputStream&);
  8495. ZipInputStream& operator= (const ZipInputStream&);
  8496. };
  8497. ZipFile::ZipFile (InputStream* const source_, const bool deleteStreamWhenDestroyed)
  8498. : inputStream (source_)
  8499. #if JUCE_DEBUG
  8500. , numOpenStreams (0)
  8501. #endif
  8502. {
  8503. if (deleteStreamWhenDestroyed)
  8504. streamToDelete = inputStream;
  8505. init();
  8506. }
  8507. ZipFile::ZipFile (const File& file)
  8508. : inputStream (0)
  8509. #if JUCE_DEBUG
  8510. , numOpenStreams (0)
  8511. #endif
  8512. {
  8513. inputSource = new FileInputSource (file);
  8514. init();
  8515. }
  8516. ZipFile::ZipFile (InputSource* const inputSource_)
  8517. : inputStream (0),
  8518. inputSource (inputSource_)
  8519. #if JUCE_DEBUG
  8520. , numOpenStreams (0)
  8521. #endif
  8522. {
  8523. init();
  8524. }
  8525. ZipFile::~ZipFile()
  8526. {
  8527. #if JUCE_DEBUG
  8528. entries.clear();
  8529. /* If you hit this assertion, it means you've created a stream to read one of the items in the
  8530. zipfile, but you've forgotten to delete that stream object before deleting the file..
  8531. Streams can't be kept open after the file is deleted because they need to share the input
  8532. stream that the file uses to read itself.
  8533. */
  8534. jassert (numOpenStreams == 0);
  8535. #endif
  8536. }
  8537. int ZipFile::getNumEntries() const throw()
  8538. {
  8539. return entries.size();
  8540. }
  8541. const ZipFile::ZipEntry* ZipFile::getEntry (const int index) const throw()
  8542. {
  8543. ZipEntryInfo* const zei = entries [index];
  8544. return zei != 0 ? &(zei->entry) : 0;
  8545. }
  8546. int ZipFile::getIndexOfFileName (const String& fileName) const throw()
  8547. {
  8548. for (int i = 0; i < entries.size(); ++i)
  8549. if (entries.getUnchecked (i)->entry.filename == fileName)
  8550. return i;
  8551. return -1;
  8552. }
  8553. const ZipFile::ZipEntry* ZipFile::getEntry (const String& fileName) const throw()
  8554. {
  8555. return getEntry (getIndexOfFileName (fileName));
  8556. }
  8557. InputStream* ZipFile::createStreamForEntry (const int index)
  8558. {
  8559. ZipEntryInfo* const zei = entries[index];
  8560. InputStream* stream = 0;
  8561. if (zei != 0)
  8562. {
  8563. stream = new ZipInputStream (*this, *zei);
  8564. if (zei->compressed)
  8565. {
  8566. stream = new GZIPDecompressorInputStream (stream, true, true,
  8567. zei->entry.uncompressedSize);
  8568. // (much faster to unzip in big blocks using a buffer..)
  8569. stream = new BufferedInputStream (stream, 32768, true);
  8570. }
  8571. }
  8572. return stream;
  8573. }
  8574. class ZipFile::ZipFilenameComparator
  8575. {
  8576. public:
  8577. int compareElements (const ZipFile::ZipEntryInfo* first, const ZipFile::ZipEntryInfo* second)
  8578. {
  8579. return first->entry.filename.compare (second->entry.filename);
  8580. }
  8581. };
  8582. void ZipFile::sortEntriesByFilename()
  8583. {
  8584. ZipFilenameComparator sorter;
  8585. entries.sort (sorter);
  8586. }
  8587. void ZipFile::init()
  8588. {
  8589. ScopedPointer <InputStream> toDelete;
  8590. InputStream* in = inputStream;
  8591. if (inputSource != 0)
  8592. {
  8593. in = inputSource->createInputStream();
  8594. toDelete = in;
  8595. }
  8596. if (in != 0)
  8597. {
  8598. int numEntries = 0;
  8599. int pos = findEndOfZipEntryTable (*in, numEntries);
  8600. if (pos >= 0 && pos < in->getTotalLength())
  8601. {
  8602. const int size = (int) (in->getTotalLength() - pos);
  8603. in->setPosition (pos);
  8604. MemoryBlock headerData;
  8605. if (in->readIntoMemoryBlock (headerData, size) == size)
  8606. {
  8607. pos = 0;
  8608. for (int i = 0; i < numEntries; ++i)
  8609. {
  8610. if (pos + 46 > size)
  8611. break;
  8612. const char* const buffer = static_cast <const char*> (headerData.getData()) + pos;
  8613. const int fileNameLen = ByteOrder::littleEndianShort (buffer + 28);
  8614. if (pos + 46 + fileNameLen > size)
  8615. break;
  8616. ZipEntryInfo* const zei = new ZipEntryInfo();
  8617. zei->entry.filename = String::fromUTF8 (buffer + 46, fileNameLen);
  8618. const int time = ByteOrder::littleEndianShort (buffer + 12);
  8619. const int date = ByteOrder::littleEndianShort (buffer + 14);
  8620. const int year = 1980 + (date >> 9);
  8621. const int month = ((date >> 5) & 15) - 1;
  8622. const int day = date & 31;
  8623. const int hours = time >> 11;
  8624. const int minutes = (time >> 5) & 63;
  8625. const int seconds = (time & 31) << 1;
  8626. zei->entry.fileTime = Time (year, month, day, hours, minutes, seconds);
  8627. zei->compressed = ByteOrder::littleEndianShort (buffer + 10) != 0;
  8628. zei->compressedSize = ByteOrder::littleEndianInt (buffer + 20);
  8629. zei->entry.uncompressedSize = ByteOrder::littleEndianInt (buffer + 24);
  8630. zei->streamOffset = ByteOrder::littleEndianInt (buffer + 42);
  8631. entries.add (zei);
  8632. pos += 46 + fileNameLen
  8633. + ByteOrder::littleEndianShort (buffer + 30)
  8634. + ByteOrder::littleEndianShort (buffer + 32);
  8635. }
  8636. }
  8637. }
  8638. }
  8639. }
  8640. int ZipFile::findEndOfZipEntryTable (InputStream& input, int& numEntries)
  8641. {
  8642. BufferedInputStream in (input, 8192);
  8643. in.setPosition (in.getTotalLength());
  8644. int64 pos = in.getPosition();
  8645. const int64 lowestPos = jmax ((int64) 0, pos - 1024);
  8646. char buffer [32];
  8647. zeromem (buffer, sizeof (buffer));
  8648. while (pos > lowestPos)
  8649. {
  8650. in.setPosition (pos - 22);
  8651. pos = in.getPosition();
  8652. memcpy (buffer + 22, buffer, 4);
  8653. if (in.read (buffer, 22) != 22)
  8654. return 0;
  8655. for (int i = 0; i < 22; ++i)
  8656. {
  8657. if (ByteOrder::littleEndianInt (buffer + i) == 0x06054b50)
  8658. {
  8659. in.setPosition (pos + i);
  8660. in.read (buffer, 22);
  8661. numEntries = ByteOrder::littleEndianShort (buffer + 10);
  8662. return ByteOrder::littleEndianInt (buffer + 16);
  8663. }
  8664. }
  8665. }
  8666. return 0;
  8667. }
  8668. bool ZipFile::uncompressTo (const File& targetDirectory,
  8669. const bool shouldOverwriteFiles)
  8670. {
  8671. for (int i = 0; i < entries.size(); ++i)
  8672. if (! uncompressEntry (i, targetDirectory, shouldOverwriteFiles))
  8673. return false;
  8674. return true;
  8675. }
  8676. bool ZipFile::uncompressEntry (const int index,
  8677. const File& targetDirectory,
  8678. bool shouldOverwriteFiles)
  8679. {
  8680. const ZipEntryInfo* zei = entries [index];
  8681. if (zei != 0)
  8682. {
  8683. const File targetFile (targetDirectory.getChildFile (zei->entry.filename));
  8684. if (zei->entry.filename.endsWithChar ('/'))
  8685. {
  8686. return targetFile.createDirectory(); // (entry is a directory, not a file)
  8687. }
  8688. else
  8689. {
  8690. ScopedPointer<InputStream> in (createStreamForEntry (index));
  8691. if (in != 0)
  8692. {
  8693. if (shouldOverwriteFiles && ! targetFile.deleteFile())
  8694. return false;
  8695. if ((! targetFile.exists()) && targetFile.getParentDirectory().createDirectory())
  8696. {
  8697. ScopedPointer<FileOutputStream> out (targetFile.createOutputStream());
  8698. if (out != 0)
  8699. {
  8700. out->writeFromInputStream (*in, -1);
  8701. out = 0;
  8702. targetFile.setCreationTime (zei->entry.fileTime);
  8703. targetFile.setLastModificationTime (zei->entry.fileTime);
  8704. targetFile.setLastAccessTime (zei->entry.fileTime);
  8705. return true;
  8706. }
  8707. }
  8708. }
  8709. }
  8710. }
  8711. return false;
  8712. }
  8713. END_JUCE_NAMESPACE
  8714. /*** End of inlined file: juce_ZipFile.cpp ***/
  8715. /*** Start of inlined file: juce_CharacterFunctions.cpp ***/
  8716. #if JUCE_MSVC
  8717. #pragma warning (push)
  8718. #pragma warning (disable: 4514 4996)
  8719. #endif
  8720. #include <cwctype>
  8721. #include <cctype>
  8722. #include <ctime>
  8723. BEGIN_JUCE_NAMESPACE
  8724. int CharacterFunctions::length (const char* const s) throw()
  8725. {
  8726. return (int) strlen (s);
  8727. }
  8728. int CharacterFunctions::length (const juce_wchar* const s) throw()
  8729. {
  8730. return (int) wcslen (s);
  8731. }
  8732. void CharacterFunctions::copy (char* dest, const char* src, const int maxChars) throw()
  8733. {
  8734. strncpy (dest, src, maxChars);
  8735. }
  8736. void CharacterFunctions::copy (juce_wchar* dest, const juce_wchar* src, int maxChars) throw()
  8737. {
  8738. wcsncpy (dest, src, maxChars);
  8739. }
  8740. void CharacterFunctions::copy (juce_wchar* dest, const char* src, const int maxChars) throw()
  8741. {
  8742. mbstowcs (dest, src, maxChars);
  8743. }
  8744. void CharacterFunctions::copy (char* dest, const juce_wchar* src, const int maxChars) throw()
  8745. {
  8746. wcstombs (dest, src, maxChars);
  8747. }
  8748. int CharacterFunctions::bytesRequiredForCopy (const juce_wchar* src) throw()
  8749. {
  8750. return (int) wcstombs (0, src, 0);
  8751. }
  8752. void CharacterFunctions::append (char* dest, const char* src) throw()
  8753. {
  8754. strcat (dest, src);
  8755. }
  8756. void CharacterFunctions::append (juce_wchar* dest, const juce_wchar* src) throw()
  8757. {
  8758. wcscat (dest, src);
  8759. }
  8760. int CharacterFunctions::compare (const char* const s1, const char* const s2) throw()
  8761. {
  8762. return strcmp (s1, s2);
  8763. }
  8764. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2) throw()
  8765. {
  8766. jassert (s1 != 0 && s2 != 0);
  8767. return wcscmp (s1, s2);
  8768. }
  8769. int CharacterFunctions::compare (const char* const s1, const char* const s2, const int maxChars) throw()
  8770. {
  8771. jassert (s1 != 0 && s2 != 0);
  8772. return strncmp (s1, s2, maxChars);
  8773. }
  8774. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  8775. {
  8776. jassert (s1 != 0 && s2 != 0);
  8777. return wcsncmp (s1, s2, maxChars);
  8778. }
  8779. int CharacterFunctions::compare (const juce_wchar* s1, const char* s2) throw()
  8780. {
  8781. jassert (s1 != 0 && s2 != 0);
  8782. for (;;)
  8783. {
  8784. const int diff = (int) (*s1 - (juce_wchar) (unsigned char) *s2);
  8785. if (diff != 0)
  8786. return diff;
  8787. else if (*s1 == 0)
  8788. break;
  8789. ++s1;
  8790. ++s2;
  8791. }
  8792. return 0;
  8793. }
  8794. int CharacterFunctions::compare (const char* s1, const juce_wchar* s2) throw()
  8795. {
  8796. return -compare (s2, s1);
  8797. }
  8798. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2) throw()
  8799. {
  8800. jassert (s1 != 0 && s2 != 0);
  8801. #if JUCE_WINDOWS
  8802. return stricmp (s1, s2);
  8803. #else
  8804. return strcasecmp (s1, s2);
  8805. #endif
  8806. }
  8807. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2) throw()
  8808. {
  8809. jassert (s1 != 0 && s2 != 0);
  8810. #if JUCE_WINDOWS
  8811. return _wcsicmp (s1, s2);
  8812. #else
  8813. for (;;)
  8814. {
  8815. if (*s1 != *s2)
  8816. {
  8817. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  8818. if (diff != 0)
  8819. return diff < 0 ? -1 : 1;
  8820. }
  8821. else if (*s1 == 0)
  8822. break;
  8823. ++s1;
  8824. ++s2;
  8825. }
  8826. return 0;
  8827. #endif
  8828. }
  8829. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const char* s2) throw()
  8830. {
  8831. jassert (s1 != 0 && s2 != 0);
  8832. for (;;)
  8833. {
  8834. if (*s1 != *s2)
  8835. {
  8836. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  8837. if (diff != 0)
  8838. return diff < 0 ? -1 : 1;
  8839. }
  8840. else if (*s1 == 0)
  8841. break;
  8842. ++s1;
  8843. ++s2;
  8844. }
  8845. return 0;
  8846. }
  8847. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2, const int maxChars) throw()
  8848. {
  8849. jassert (s1 != 0 && s2 != 0);
  8850. #if JUCE_WINDOWS
  8851. return strnicmp (s1, s2, maxChars);
  8852. #else
  8853. return strncasecmp (s1, s2, maxChars);
  8854. #endif
  8855. }
  8856. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  8857. {
  8858. jassert (s1 != 0 && s2 != 0);
  8859. #if JUCE_WINDOWS
  8860. return _wcsnicmp (s1, s2, maxChars);
  8861. #else
  8862. while (--maxChars >= 0)
  8863. {
  8864. if (*s1 != *s2)
  8865. {
  8866. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  8867. if (diff != 0)
  8868. return diff < 0 ? -1 : 1;
  8869. }
  8870. else if (*s1 == 0)
  8871. break;
  8872. ++s1;
  8873. ++s2;
  8874. }
  8875. return 0;
  8876. #endif
  8877. }
  8878. const char* CharacterFunctions::find (const char* const haystack, const char* const needle) throw()
  8879. {
  8880. return strstr (haystack, needle);
  8881. }
  8882. const juce_wchar* CharacterFunctions::find (const juce_wchar* haystack, const juce_wchar* const needle) throw()
  8883. {
  8884. return wcsstr (haystack, needle);
  8885. }
  8886. int CharacterFunctions::indexOfChar (const char* const haystack, const char needle, const bool ignoreCase) throw()
  8887. {
  8888. if (haystack != 0)
  8889. {
  8890. int i = 0;
  8891. if (ignoreCase)
  8892. {
  8893. const char n1 = toLowerCase (needle);
  8894. const char n2 = toUpperCase (needle);
  8895. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  8896. {
  8897. while (haystack[i] != 0)
  8898. {
  8899. if (haystack[i] == n1 || haystack[i] == n2)
  8900. return i;
  8901. ++i;
  8902. }
  8903. return -1;
  8904. }
  8905. jassert (n1 == needle);
  8906. }
  8907. while (haystack[i] != 0)
  8908. {
  8909. if (haystack[i] == needle)
  8910. return i;
  8911. ++i;
  8912. }
  8913. }
  8914. return -1;
  8915. }
  8916. int CharacterFunctions::indexOfChar (const juce_wchar* const haystack, const juce_wchar needle, const bool ignoreCase) throw()
  8917. {
  8918. if (haystack != 0)
  8919. {
  8920. int i = 0;
  8921. if (ignoreCase)
  8922. {
  8923. const juce_wchar n1 = toLowerCase (needle);
  8924. const juce_wchar n2 = toUpperCase (needle);
  8925. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  8926. {
  8927. while (haystack[i] != 0)
  8928. {
  8929. if (haystack[i] == n1 || haystack[i] == n2)
  8930. return i;
  8931. ++i;
  8932. }
  8933. return -1;
  8934. }
  8935. jassert (n1 == needle);
  8936. }
  8937. while (haystack[i] != 0)
  8938. {
  8939. if (haystack[i] == needle)
  8940. return i;
  8941. ++i;
  8942. }
  8943. }
  8944. return -1;
  8945. }
  8946. int CharacterFunctions::indexOfCharFast (const char* const haystack, const char needle) throw()
  8947. {
  8948. jassert (haystack != 0);
  8949. int i = 0;
  8950. while (haystack[i] != 0)
  8951. {
  8952. if (haystack[i] == needle)
  8953. return i;
  8954. ++i;
  8955. }
  8956. return -1;
  8957. }
  8958. int CharacterFunctions::indexOfCharFast (const juce_wchar* const haystack, const juce_wchar needle) throw()
  8959. {
  8960. jassert (haystack != 0);
  8961. int i = 0;
  8962. while (haystack[i] != 0)
  8963. {
  8964. if (haystack[i] == needle)
  8965. return i;
  8966. ++i;
  8967. }
  8968. return -1;
  8969. }
  8970. int CharacterFunctions::getIntialSectionContainingOnly (const char* const text, const char* const allowedChars) throw()
  8971. {
  8972. return allowedChars == 0 ? 0 : (int) strspn (text, allowedChars);
  8973. }
  8974. int CharacterFunctions::getIntialSectionContainingOnly (const juce_wchar* const text, const juce_wchar* const allowedChars) throw()
  8975. {
  8976. if (allowedChars == 0)
  8977. return 0;
  8978. int i = 0;
  8979. for (;;)
  8980. {
  8981. if (indexOfCharFast (allowedChars, text[i]) < 0)
  8982. break;
  8983. ++i;
  8984. }
  8985. return i;
  8986. }
  8987. int CharacterFunctions::ftime (char* const dest, const int maxChars, const char* const format, const struct tm* const tm) throw()
  8988. {
  8989. return (int) strftime (dest, maxChars, format, tm);
  8990. }
  8991. int CharacterFunctions::ftime (juce_wchar* const dest, const int maxChars, const juce_wchar* const format, const struct tm* const tm) throw()
  8992. {
  8993. return (int) wcsftime (dest, maxChars, format, tm);
  8994. }
  8995. int CharacterFunctions::getIntValue (const char* const s) throw()
  8996. {
  8997. return atoi (s);
  8998. }
  8999. int CharacterFunctions::getIntValue (const juce_wchar* s) throw()
  9000. {
  9001. #if JUCE_WINDOWS
  9002. return _wtoi (s);
  9003. #else
  9004. int v = 0;
  9005. while (isWhitespace (*s))
  9006. ++s;
  9007. const bool isNeg = *s == '-';
  9008. if (isNeg)
  9009. ++s;
  9010. for (;;)
  9011. {
  9012. const wchar_t c = *s++;
  9013. if (c >= '0' && c <= '9')
  9014. v = v * 10 + (int) (c - '0');
  9015. else
  9016. break;
  9017. }
  9018. return isNeg ? -v : v;
  9019. #endif
  9020. }
  9021. int64 CharacterFunctions::getInt64Value (const char* s) throw()
  9022. {
  9023. #if JUCE_LINUX
  9024. return atoll (s);
  9025. #elif JUCE_WINDOWS
  9026. return _atoi64 (s);
  9027. #else
  9028. int64 v = 0;
  9029. while (isWhitespace (*s))
  9030. ++s;
  9031. const bool isNeg = *s == '-';
  9032. if (isNeg)
  9033. ++s;
  9034. for (;;)
  9035. {
  9036. const char c = *s++;
  9037. if (c >= '0' && c <= '9')
  9038. v = v * 10 + (int64) (c - '0');
  9039. else
  9040. break;
  9041. }
  9042. return isNeg ? -v : v;
  9043. #endif
  9044. }
  9045. int64 CharacterFunctions::getInt64Value (const juce_wchar* s) throw()
  9046. {
  9047. #if JUCE_WINDOWS
  9048. return _wtoi64 (s);
  9049. #else
  9050. int64 v = 0;
  9051. while (isWhitespace (*s))
  9052. ++s;
  9053. const bool isNeg = *s == '-';
  9054. if (isNeg)
  9055. ++s;
  9056. for (;;)
  9057. {
  9058. const juce_wchar c = *s++;
  9059. if (c >= '0' && c <= '9')
  9060. v = v * 10 + (int64) (c - '0');
  9061. else
  9062. break;
  9063. }
  9064. return isNeg ? -v : v;
  9065. #endif
  9066. }
  9067. namespace
  9068. {
  9069. double juce_mulexp10 (const double value, int exponent) throw()
  9070. {
  9071. if (exponent == 0)
  9072. return value;
  9073. if (value == 0)
  9074. return 0;
  9075. const bool negative = (exponent < 0);
  9076. if (negative)
  9077. exponent = -exponent;
  9078. double result = 1.0, power = 10.0;
  9079. for (int bit = 1; exponent != 0; bit <<= 1)
  9080. {
  9081. if ((exponent & bit) != 0)
  9082. {
  9083. exponent ^= bit;
  9084. result *= power;
  9085. if (exponent == 0)
  9086. break;
  9087. }
  9088. power *= power;
  9089. }
  9090. return negative ? (value / result) : (value * result);
  9091. }
  9092. template <class CharType>
  9093. double juce_atof (const CharType* const original) throw()
  9094. {
  9095. double result[3] = { 0, 0, 0 }, accumulator[2] = { 0, 0 };
  9096. int exponentAdjustment[2] = { 0, 0 }, exponentAccumulator[2] = { -1, -1 };
  9097. int exponent = 0, decPointIndex = 0, digit = 0;
  9098. int lastDigit = 0, numSignificantDigits = 0;
  9099. bool isNegative = false, digitsFound = false;
  9100. const int maxSignificantDigits = 15 + 2;
  9101. const CharType* s = original;
  9102. while (CharacterFunctions::isWhitespace (*s))
  9103. ++s;
  9104. switch (*s)
  9105. {
  9106. case '-': isNegative = true; // fall-through..
  9107. case '+': ++s;
  9108. }
  9109. if (*s == 'n' || *s == 'N' || *s == 'i' || *s == 'I')
  9110. return atof (String (original).toUTF8()); // Let the c library deal with NAN and INF
  9111. for (;;)
  9112. {
  9113. if (CharacterFunctions::isDigit (*s))
  9114. {
  9115. lastDigit = digit;
  9116. digit = *s++ - '0';
  9117. digitsFound = true;
  9118. if (decPointIndex != 0)
  9119. exponentAdjustment[1]++;
  9120. if (numSignificantDigits == 0 && digit == 0)
  9121. continue;
  9122. if (++numSignificantDigits > maxSignificantDigits)
  9123. {
  9124. if (digit > 5)
  9125. ++accumulator [decPointIndex];
  9126. else if (digit == 5 && (lastDigit & 1) != 0)
  9127. ++accumulator [decPointIndex];
  9128. if (decPointIndex > 0)
  9129. exponentAdjustment[1]--;
  9130. else
  9131. exponentAdjustment[0]++;
  9132. while (CharacterFunctions::isDigit (*s))
  9133. {
  9134. ++s;
  9135. if (decPointIndex == 0)
  9136. exponentAdjustment[0]++;
  9137. }
  9138. }
  9139. else
  9140. {
  9141. const double maxAccumulatorValue = (double) ((std::numeric_limits<unsigned int>::max() - 9) / 10);
  9142. if (accumulator [decPointIndex] > maxAccumulatorValue)
  9143. {
  9144. result [decPointIndex] = juce_mulexp10 (result [decPointIndex], exponentAccumulator [decPointIndex])
  9145. + accumulator [decPointIndex];
  9146. accumulator [decPointIndex] = 0;
  9147. exponentAccumulator [decPointIndex] = 0;
  9148. }
  9149. accumulator [decPointIndex] = accumulator[decPointIndex] * 10 + digit;
  9150. exponentAccumulator [decPointIndex]++;
  9151. }
  9152. }
  9153. else if (decPointIndex == 0 && *s == '.')
  9154. {
  9155. ++s;
  9156. decPointIndex = 1;
  9157. if (numSignificantDigits > maxSignificantDigits)
  9158. {
  9159. while (CharacterFunctions::isDigit (*s))
  9160. ++s;
  9161. break;
  9162. }
  9163. }
  9164. else
  9165. {
  9166. break;
  9167. }
  9168. }
  9169. result[0] = juce_mulexp10 (result[0], exponentAccumulator[0]) + accumulator[0];
  9170. if (decPointIndex != 0)
  9171. result[1] = juce_mulexp10 (result[1], exponentAccumulator[1]) + accumulator[1];
  9172. if ((*s == 'e' || *s == 'E') && digitsFound)
  9173. {
  9174. bool negativeExponent = false;
  9175. switch (*++s)
  9176. {
  9177. case '-': negativeExponent = true; // fall-through..
  9178. case '+': ++s;
  9179. }
  9180. while (CharacterFunctions::isDigit (*s))
  9181. exponent = (exponent * 10) + (*s++ - '0');
  9182. if (negativeExponent)
  9183. exponent = -exponent;
  9184. }
  9185. double r = juce_mulexp10 (result[0], exponent + exponentAdjustment[0]);
  9186. if (decPointIndex != 0)
  9187. r += juce_mulexp10 (result[1], exponent - exponentAdjustment[1]);
  9188. return isNegative ? -r : r;
  9189. }
  9190. }
  9191. double CharacterFunctions::getDoubleValue (const char* const s) throw()
  9192. {
  9193. return juce_atof <char> (s);
  9194. }
  9195. double CharacterFunctions::getDoubleValue (const juce_wchar* const s) throw()
  9196. {
  9197. return juce_atof <juce_wchar> (s);
  9198. }
  9199. char CharacterFunctions::toUpperCase (const char character) throw()
  9200. {
  9201. return (char) toupper (character);
  9202. }
  9203. juce_wchar CharacterFunctions::toUpperCase (const juce_wchar character) throw()
  9204. {
  9205. return towupper (character);
  9206. }
  9207. void CharacterFunctions::toUpperCase (char* s) throw()
  9208. {
  9209. #if JUCE_WINDOWS
  9210. strupr (s);
  9211. #else
  9212. while (*s != 0)
  9213. {
  9214. *s = toUpperCase (*s);
  9215. ++s;
  9216. }
  9217. #endif
  9218. }
  9219. void CharacterFunctions::toUpperCase (juce_wchar* s) throw()
  9220. {
  9221. #if JUCE_WINDOWS
  9222. _wcsupr (s);
  9223. #else
  9224. while (*s != 0)
  9225. {
  9226. *s = toUpperCase (*s);
  9227. ++s;
  9228. }
  9229. #endif
  9230. }
  9231. bool CharacterFunctions::isUpperCase (const char character) throw()
  9232. {
  9233. return isupper (character) != 0;
  9234. }
  9235. bool CharacterFunctions::isUpperCase (const juce_wchar character) throw()
  9236. {
  9237. #if JUCE_WINDOWS
  9238. return iswupper (character) != 0;
  9239. #else
  9240. return toLowerCase (character) != character;
  9241. #endif
  9242. }
  9243. char CharacterFunctions::toLowerCase (const char character) throw()
  9244. {
  9245. return (char) tolower (character);
  9246. }
  9247. juce_wchar CharacterFunctions::toLowerCase (const juce_wchar character) throw()
  9248. {
  9249. return towlower (character);
  9250. }
  9251. void CharacterFunctions::toLowerCase (char* s) throw()
  9252. {
  9253. #if JUCE_WINDOWS
  9254. strlwr (s);
  9255. #else
  9256. while (*s != 0)
  9257. {
  9258. *s = toLowerCase (*s);
  9259. ++s;
  9260. }
  9261. #endif
  9262. }
  9263. void CharacterFunctions::toLowerCase (juce_wchar* s) throw()
  9264. {
  9265. #if JUCE_WINDOWS
  9266. _wcslwr (s);
  9267. #else
  9268. while (*s != 0)
  9269. {
  9270. *s = toLowerCase (*s);
  9271. ++s;
  9272. }
  9273. #endif
  9274. }
  9275. bool CharacterFunctions::isLowerCase (const char character) throw()
  9276. {
  9277. return islower (character) != 0;
  9278. }
  9279. bool CharacterFunctions::isLowerCase (const juce_wchar character) throw()
  9280. {
  9281. #if JUCE_WINDOWS
  9282. return iswlower (character) != 0;
  9283. #else
  9284. return toUpperCase (character) != character;
  9285. #endif
  9286. }
  9287. bool CharacterFunctions::isWhitespace (const char character) throw()
  9288. {
  9289. return character == ' ' || (character <= 13 && character >= 9);
  9290. }
  9291. bool CharacterFunctions::isWhitespace (const juce_wchar character) throw()
  9292. {
  9293. return iswspace (character) != 0;
  9294. }
  9295. bool CharacterFunctions::isDigit (const char character) throw()
  9296. {
  9297. return (character >= '0' && character <= '9');
  9298. }
  9299. bool CharacterFunctions::isDigit (const juce_wchar character) throw()
  9300. {
  9301. return iswdigit (character) != 0;
  9302. }
  9303. bool CharacterFunctions::isLetter (const char character) throw()
  9304. {
  9305. return (character >= 'a' && character <= 'z')
  9306. || (character >= 'A' && character <= 'Z');
  9307. }
  9308. bool CharacterFunctions::isLetter (const juce_wchar character) throw()
  9309. {
  9310. return iswalpha (character) != 0;
  9311. }
  9312. bool CharacterFunctions::isLetterOrDigit (const char character) throw()
  9313. {
  9314. return (character >= 'a' && character <= 'z')
  9315. || (character >= 'A' && character <= 'Z')
  9316. || (character >= '0' && character <= '9');
  9317. }
  9318. bool CharacterFunctions::isLetterOrDigit (const juce_wchar character) throw()
  9319. {
  9320. return iswalnum (character) != 0;
  9321. }
  9322. int CharacterFunctions::getHexDigitValue (const juce_wchar digit) throw()
  9323. {
  9324. unsigned int d = digit - '0';
  9325. if (d < (unsigned int) 10)
  9326. return (int) d;
  9327. d += (unsigned int) ('0' - 'a');
  9328. if (d < (unsigned int) 6)
  9329. return (int) d + 10;
  9330. d += (unsigned int) ('a' - 'A');
  9331. if (d < (unsigned int) 6)
  9332. return (int) d + 10;
  9333. return -1;
  9334. }
  9335. #if JUCE_MSVC
  9336. #pragma warning (pop)
  9337. #endif
  9338. END_JUCE_NAMESPACE
  9339. /*** End of inlined file: juce_CharacterFunctions.cpp ***/
  9340. /*** Start of inlined file: juce_LocalisedStrings.cpp ***/
  9341. BEGIN_JUCE_NAMESPACE
  9342. LocalisedStrings::LocalisedStrings (const String& fileContents)
  9343. {
  9344. loadFromText (fileContents);
  9345. }
  9346. LocalisedStrings::LocalisedStrings (const File& fileToLoad)
  9347. {
  9348. loadFromText (fileToLoad.loadFileAsString());
  9349. }
  9350. LocalisedStrings::~LocalisedStrings()
  9351. {
  9352. }
  9353. const String LocalisedStrings::translate (const String& text) const
  9354. {
  9355. return translations.getValue (text, text);
  9356. }
  9357. namespace
  9358. {
  9359. CriticalSection currentMappingsLock;
  9360. LocalisedStrings* currentMappings = 0;
  9361. int findCloseQuote (const String& text, int startPos)
  9362. {
  9363. juce_wchar lastChar = 0;
  9364. for (;;)
  9365. {
  9366. const juce_wchar c = text [startPos];
  9367. if (c == 0 || (c == '"' && lastChar != '\\'))
  9368. break;
  9369. lastChar = c;
  9370. ++startPos;
  9371. }
  9372. return startPos;
  9373. }
  9374. const String unescapeString (const String& s)
  9375. {
  9376. return s.replace ("\\\"", "\"")
  9377. .replace ("\\\'", "\'")
  9378. .replace ("\\t", "\t")
  9379. .replace ("\\r", "\r")
  9380. .replace ("\\n", "\n");
  9381. }
  9382. }
  9383. void LocalisedStrings::loadFromText (const String& fileContents)
  9384. {
  9385. StringArray lines;
  9386. lines.addLines (fileContents);
  9387. for (int i = 0; i < lines.size(); ++i)
  9388. {
  9389. String line (lines[i].trim());
  9390. if (line.startsWithChar ('"'))
  9391. {
  9392. int closeQuote = findCloseQuote (line, 1);
  9393. const String originalText (unescapeString (line.substring (1, closeQuote)));
  9394. if (originalText.isNotEmpty())
  9395. {
  9396. const int openingQuote = findCloseQuote (line, closeQuote + 1);
  9397. closeQuote = findCloseQuote (line, openingQuote + 1);
  9398. const String newText (unescapeString (line.substring (openingQuote + 1, closeQuote)));
  9399. if (newText.isNotEmpty())
  9400. translations.set (originalText, newText);
  9401. }
  9402. }
  9403. else if (line.startsWithIgnoreCase ("language:"))
  9404. {
  9405. languageName = line.substring (9).trim();
  9406. }
  9407. else if (line.startsWithIgnoreCase ("countries:"))
  9408. {
  9409. countryCodes.addTokens (line.substring (10).trim(), true);
  9410. countryCodes.trim();
  9411. countryCodes.removeEmptyStrings();
  9412. }
  9413. }
  9414. }
  9415. void LocalisedStrings::setIgnoresCase (const bool shouldIgnoreCase)
  9416. {
  9417. translations.setIgnoresCase (shouldIgnoreCase);
  9418. }
  9419. void LocalisedStrings::setCurrentMappings (LocalisedStrings* newTranslations)
  9420. {
  9421. const ScopedLock sl (currentMappingsLock);
  9422. delete currentMappings;
  9423. currentMappings = newTranslations;
  9424. }
  9425. LocalisedStrings* LocalisedStrings::getCurrentMappings()
  9426. {
  9427. return currentMappings;
  9428. }
  9429. const String LocalisedStrings::translateWithCurrentMappings (const String& text)
  9430. {
  9431. const ScopedLock sl (currentMappingsLock);
  9432. if (currentMappings != 0)
  9433. return currentMappings->translate (text);
  9434. return text;
  9435. }
  9436. const String LocalisedStrings::translateWithCurrentMappings (const char* text)
  9437. {
  9438. return translateWithCurrentMappings (String (text));
  9439. }
  9440. END_JUCE_NAMESPACE
  9441. /*** End of inlined file: juce_LocalisedStrings.cpp ***/
  9442. /*** Start of inlined file: juce_String.cpp ***/
  9443. #if JUCE_MSVC
  9444. #pragma warning (push)
  9445. #pragma warning (disable: 4514)
  9446. #endif
  9447. #include <locale>
  9448. BEGIN_JUCE_NAMESPACE
  9449. #if JUCE_MSVC
  9450. #pragma warning (pop)
  9451. #endif
  9452. #if defined (JUCE_STRINGS_ARE_UNICODE) && ! JUCE_STRINGS_ARE_UNICODE
  9453. #error "JUCE_STRINGS_ARE_UNICODE is deprecated! All strings are now unicode by default."
  9454. #endif
  9455. class StringHolder
  9456. {
  9457. public:
  9458. StringHolder()
  9459. : refCount (0x3fffffff), allocatedNumChars (0)
  9460. {
  9461. text[0] = 0;
  9462. }
  9463. static juce_wchar* createUninitialised (const size_t numChars)
  9464. {
  9465. StringHolder* const s = reinterpret_cast <StringHolder*> (new char [sizeof (StringHolder) + numChars * sizeof (juce_wchar)]);
  9466. s->refCount.value = 0;
  9467. s->allocatedNumChars = numChars;
  9468. return &(s->text[0]);
  9469. }
  9470. static juce_wchar* createCopy (const juce_wchar* const src, const size_t numChars)
  9471. {
  9472. juce_wchar* const dest = createUninitialised (numChars);
  9473. copyChars (dest, src, numChars);
  9474. return dest;
  9475. }
  9476. static juce_wchar* createCopy (const char* const src, const size_t numChars)
  9477. {
  9478. juce_wchar* const dest = createUninitialised (numChars);
  9479. CharacterFunctions::copy (dest, src, (int) numChars);
  9480. dest [numChars] = 0;
  9481. return dest;
  9482. }
  9483. static inline juce_wchar* getEmpty() throw()
  9484. {
  9485. return &(empty.text[0]);
  9486. }
  9487. static void retain (juce_wchar* const text) throw()
  9488. {
  9489. ++(bufferFromText (text)->refCount);
  9490. }
  9491. static inline void release (StringHolder* const b) throw()
  9492. {
  9493. if (--(b->refCount) == -1 && b != &empty)
  9494. delete[] reinterpret_cast <char*> (b);
  9495. }
  9496. static void release (juce_wchar* const text) throw()
  9497. {
  9498. release (bufferFromText (text));
  9499. }
  9500. static juce_wchar* makeUnique (juce_wchar* const text)
  9501. {
  9502. StringHolder* const b = bufferFromText (text);
  9503. if (b->refCount.get() <= 0)
  9504. return text;
  9505. juce_wchar* const newText = createCopy (text, b->allocatedNumChars);
  9506. release (b);
  9507. return newText;
  9508. }
  9509. static juce_wchar* makeUniqueWithSize (juce_wchar* const text, size_t numChars)
  9510. {
  9511. StringHolder* const b = bufferFromText (text);
  9512. if (b->refCount.get() <= 0 && b->allocatedNumChars >= numChars)
  9513. return text;
  9514. juce_wchar* const newText = createUninitialised (jmax (b->allocatedNumChars, numChars));
  9515. copyChars (newText, text, b->allocatedNumChars);
  9516. release (b);
  9517. return newText;
  9518. }
  9519. static size_t getAllocatedNumChars (juce_wchar* const text) throw()
  9520. {
  9521. return bufferFromText (text)->allocatedNumChars;
  9522. }
  9523. static void copyChars (juce_wchar* const dest, const juce_wchar* const src, const size_t numChars) throw()
  9524. {
  9525. jassert (src != 0 && dest != 0);
  9526. memcpy (dest, src, numChars * sizeof (juce_wchar));
  9527. dest [numChars] = 0;
  9528. }
  9529. Atomic<int> refCount;
  9530. size_t allocatedNumChars;
  9531. juce_wchar text[1];
  9532. static StringHolder empty;
  9533. private:
  9534. static inline StringHolder* bufferFromText (void* const text) throw()
  9535. {
  9536. // (Can't use offsetof() here because of warnings about this not being a POD)
  9537. return reinterpret_cast <StringHolder*> (static_cast <char*> (text)
  9538. - (reinterpret_cast <size_t> (reinterpret_cast <StringHolder*> (1)->text) - 1));
  9539. }
  9540. };
  9541. StringHolder StringHolder::empty;
  9542. const String String::empty;
  9543. void String::createInternal (const juce_wchar* const t, const size_t numChars)
  9544. {
  9545. jassert (t[numChars] == 0); // must have a null terminator
  9546. text = StringHolder::createCopy (t, numChars);
  9547. }
  9548. void String::appendInternal (const juce_wchar* const newText, const int numExtraChars)
  9549. {
  9550. if (numExtraChars > 0)
  9551. {
  9552. const int oldLen = length();
  9553. const int newTotalLen = oldLen + numExtraChars;
  9554. text = StringHolder::makeUniqueWithSize (text, newTotalLen);
  9555. StringHolder::copyChars (text + oldLen, newText, numExtraChars);
  9556. }
  9557. }
  9558. void String::preallocateStorage (const size_t numChars)
  9559. {
  9560. text = StringHolder::makeUniqueWithSize (text, numChars);
  9561. }
  9562. String::String() throw()
  9563. : text (StringHolder::getEmpty())
  9564. {
  9565. }
  9566. String::~String() throw()
  9567. {
  9568. StringHolder::release (text);
  9569. }
  9570. String::String (const String& other) throw()
  9571. : text (other.text)
  9572. {
  9573. StringHolder::retain (text);
  9574. }
  9575. void String::swapWith (String& other) throw()
  9576. {
  9577. swapVariables (text, other.text);
  9578. }
  9579. String& String::operator= (const String& other) throw()
  9580. {
  9581. juce_wchar* const newText = other.text;
  9582. StringHolder::retain (newText);
  9583. StringHolder::release (reinterpret_cast <Atomic<juce_wchar*>*> (&text)->exchange (newText));
  9584. return *this;
  9585. }
  9586. String::String (const size_t numChars, const int /*dummyVariable*/)
  9587. : text (StringHolder::createUninitialised (numChars))
  9588. {
  9589. }
  9590. String::String (const String& stringToCopy, const size_t charsToAllocate)
  9591. {
  9592. const size_t otherSize = StringHolder::getAllocatedNumChars (stringToCopy.text);
  9593. text = StringHolder::createUninitialised (jmax (charsToAllocate, otherSize));
  9594. StringHolder::copyChars (text, stringToCopy.text, otherSize);
  9595. }
  9596. String::String (const char* const t)
  9597. {
  9598. if (t != 0 && *t != 0)
  9599. text = StringHolder::createCopy (t, CharacterFunctions::length (t));
  9600. else
  9601. text = StringHolder::getEmpty();
  9602. }
  9603. String::String (const juce_wchar* const t)
  9604. {
  9605. if (t != 0 && *t != 0)
  9606. text = StringHolder::createCopy (t, CharacterFunctions::length (t));
  9607. else
  9608. text = StringHolder::getEmpty();
  9609. }
  9610. String::String (const char* const t, const size_t maxChars)
  9611. {
  9612. int i;
  9613. for (i = 0; (size_t) i < maxChars; ++i)
  9614. if (t[i] == 0)
  9615. break;
  9616. if (i > 0)
  9617. text = StringHolder::createCopy (t, i);
  9618. else
  9619. text = StringHolder::getEmpty();
  9620. }
  9621. String::String (const juce_wchar* const t, const size_t maxChars)
  9622. {
  9623. int i;
  9624. for (i = 0; (size_t) i < maxChars; ++i)
  9625. if (t[i] == 0)
  9626. break;
  9627. if (i > 0)
  9628. text = StringHolder::createCopy (t, i);
  9629. else
  9630. text = StringHolder::getEmpty();
  9631. }
  9632. const String String::charToString (const juce_wchar character)
  9633. {
  9634. String result ((size_t) 1, (int) 0);
  9635. result.text[0] = character;
  9636. result.text[1] = 0;
  9637. return result;
  9638. }
  9639. namespace NumberToStringConverters
  9640. {
  9641. // pass in a pointer to the END of a buffer..
  9642. static juce_wchar* int64ToString (juce_wchar* t, const int64 n) throw()
  9643. {
  9644. *--t = 0;
  9645. int64 v = (n >= 0) ? n : -n;
  9646. do
  9647. {
  9648. *--t = (juce_wchar) ('0' + (int) (v % 10));
  9649. v /= 10;
  9650. } while (v > 0);
  9651. if (n < 0)
  9652. *--t = '-';
  9653. return t;
  9654. }
  9655. static juce_wchar* uint64ToString (juce_wchar* t, int64 v) throw()
  9656. {
  9657. *--t = 0;
  9658. do
  9659. {
  9660. *--t = (juce_wchar) ('0' + (int) (v % 10));
  9661. v /= 10;
  9662. } while (v > 0);
  9663. return t;
  9664. }
  9665. static juce_wchar* intToString (juce_wchar* t, const int n) throw()
  9666. {
  9667. if (n == (int) 0x80000000) // (would cause an overflow)
  9668. return int64ToString (t, n);
  9669. *--t = 0;
  9670. int v = abs (n);
  9671. do
  9672. {
  9673. *--t = (juce_wchar) ('0' + (v % 10));
  9674. v /= 10;
  9675. } while (v > 0);
  9676. if (n < 0)
  9677. *--t = '-';
  9678. return t;
  9679. }
  9680. static juce_wchar* uintToString (juce_wchar* t, unsigned int v) throw()
  9681. {
  9682. *--t = 0;
  9683. do
  9684. {
  9685. *--t = (juce_wchar) ('0' + (v % 10));
  9686. v /= 10;
  9687. } while (v > 0);
  9688. return t;
  9689. }
  9690. static juce_wchar getDecimalPoint()
  9691. {
  9692. #if JUCE_MSVC && _MSC_VER < 1400
  9693. static juce_wchar dp = std::_USE (std::locale(), std::numpunct <wchar_t>).decimal_point();
  9694. #else
  9695. static juce_wchar dp = std::use_facet <std::numpunct <wchar_t> > (std::locale()).decimal_point();
  9696. #endif
  9697. return dp;
  9698. }
  9699. static juce_wchar* doubleToString (juce_wchar* buffer, int numChars, double n, int numDecPlaces, size_t& len) throw()
  9700. {
  9701. if (numDecPlaces > 0 && n > -1.0e20 && n < 1.0e20)
  9702. {
  9703. juce_wchar* const end = buffer + numChars;
  9704. juce_wchar* t = end;
  9705. int64 v = (int64) (pow (10.0, numDecPlaces) * std::abs (n) + 0.5);
  9706. *--t = (juce_wchar) 0;
  9707. while (numDecPlaces >= 0 || v > 0)
  9708. {
  9709. if (numDecPlaces == 0)
  9710. *--t = getDecimalPoint();
  9711. *--t = (juce_wchar) ('0' + (v % 10));
  9712. v /= 10;
  9713. --numDecPlaces;
  9714. }
  9715. if (n < 0)
  9716. *--t = '-';
  9717. len = end - t - 1;
  9718. return t;
  9719. }
  9720. else
  9721. {
  9722. #if JUCE_WINDOWS
  9723. #if JUCE_MSVC && _MSC_VER <= 1400
  9724. len = _snwprintf (buffer, numChars, L"%.9g", n);
  9725. #else
  9726. len = _snwprintf_s (buffer, numChars, _TRUNCATE, L"%.9g", n);
  9727. #endif
  9728. #else
  9729. len = swprintf (buffer, numChars, L"%.9g", n);
  9730. #endif
  9731. return buffer;
  9732. }
  9733. }
  9734. }
  9735. String::String (const int number)
  9736. {
  9737. juce_wchar buffer [16];
  9738. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9739. juce_wchar* const start = NumberToStringConverters::intToString (end, number);
  9740. createInternal (start, end - start - 1);
  9741. }
  9742. String::String (const unsigned int number)
  9743. {
  9744. juce_wchar buffer [16];
  9745. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9746. juce_wchar* const start = NumberToStringConverters::uintToString (end, number);
  9747. createInternal (start, end - start - 1);
  9748. }
  9749. String::String (const short number)
  9750. {
  9751. juce_wchar buffer [16];
  9752. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9753. juce_wchar* const start = NumberToStringConverters::intToString (end, (int) number);
  9754. createInternal (start, end - start - 1);
  9755. }
  9756. String::String (const unsigned short number)
  9757. {
  9758. juce_wchar buffer [16];
  9759. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9760. juce_wchar* const start = NumberToStringConverters::uintToString (end, (unsigned int) number);
  9761. createInternal (start, end - start - 1);
  9762. }
  9763. String::String (const int64 number)
  9764. {
  9765. juce_wchar buffer [32];
  9766. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9767. juce_wchar* const start = NumberToStringConverters::int64ToString (end, number);
  9768. createInternal (start, end - start - 1);
  9769. }
  9770. String::String (const uint64 number)
  9771. {
  9772. juce_wchar buffer [32];
  9773. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9774. juce_wchar* const start = NumberToStringConverters::uint64ToString (end, number);
  9775. createInternal (start, end - start - 1);
  9776. }
  9777. String::String (const float number, const int numberOfDecimalPlaces)
  9778. {
  9779. juce_wchar buffer [48];
  9780. size_t len;
  9781. juce_wchar* start = NumberToStringConverters::doubleToString (buffer, numElementsInArray (buffer), (double) number, numberOfDecimalPlaces, len);
  9782. createInternal (start, len);
  9783. }
  9784. String::String (const double number, const int numberOfDecimalPlaces)
  9785. {
  9786. juce_wchar buffer [48];
  9787. size_t len;
  9788. juce_wchar* start = NumberToStringConverters::doubleToString (buffer, numElementsInArray (buffer), number, numberOfDecimalPlaces, len);
  9789. createInternal (start, len);
  9790. }
  9791. int String::length() const throw()
  9792. {
  9793. return CharacterFunctions::length (text);
  9794. }
  9795. int String::hashCode() const throw()
  9796. {
  9797. const juce_wchar* t = text;
  9798. int result = 0;
  9799. while (*t != (juce_wchar) 0)
  9800. result = 31 * result + *t++;
  9801. return result;
  9802. }
  9803. int64 String::hashCode64() const throw()
  9804. {
  9805. const juce_wchar* t = text;
  9806. int64 result = 0;
  9807. while (*t != (juce_wchar) 0)
  9808. result = 101 * result + *t++;
  9809. return result;
  9810. }
  9811. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const String& string2) throw()
  9812. {
  9813. return string1.compare (string2) == 0;
  9814. }
  9815. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const char* string2) throw()
  9816. {
  9817. return string1.compare (string2) == 0;
  9818. }
  9819. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const juce_wchar* string2) throw()
  9820. {
  9821. return string1.compare (string2) == 0;
  9822. }
  9823. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const String& string2) throw()
  9824. {
  9825. return string1.compare (string2) != 0;
  9826. }
  9827. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const char* string2) throw()
  9828. {
  9829. return string1.compare (string2) != 0;
  9830. }
  9831. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const juce_wchar* string2) throw()
  9832. {
  9833. return string1.compare (string2) != 0;
  9834. }
  9835. JUCE_API bool JUCE_CALLTYPE operator> (const String& string1, const String& string2) throw()
  9836. {
  9837. return string1.compare (string2) > 0;
  9838. }
  9839. JUCE_API bool JUCE_CALLTYPE operator< (const String& string1, const String& string2) throw()
  9840. {
  9841. return string1.compare (string2) < 0;
  9842. }
  9843. JUCE_API bool JUCE_CALLTYPE operator>= (const String& string1, const String& string2) throw()
  9844. {
  9845. return string1.compare (string2) >= 0;
  9846. }
  9847. JUCE_API bool JUCE_CALLTYPE operator<= (const String& string1, const String& string2) throw()
  9848. {
  9849. return string1.compare (string2) <= 0;
  9850. }
  9851. bool String::equalsIgnoreCase (const juce_wchar* t) const throw()
  9852. {
  9853. return t != 0 ? CharacterFunctions::compareIgnoreCase (text, t) == 0
  9854. : isEmpty();
  9855. }
  9856. bool String::equalsIgnoreCase (const char* t) const throw()
  9857. {
  9858. return t != 0 ? CharacterFunctions::compareIgnoreCase (text, t) == 0
  9859. : isEmpty();
  9860. }
  9861. bool String::equalsIgnoreCase (const String& other) const throw()
  9862. {
  9863. return text == other.text
  9864. || CharacterFunctions::compareIgnoreCase (text, other.text) == 0;
  9865. }
  9866. int String::compare (const String& other) const throw()
  9867. {
  9868. return (text == other.text) ? 0 : CharacterFunctions::compare (text, other.text);
  9869. }
  9870. int String::compare (const char* other) const throw()
  9871. {
  9872. return other == 0 ? isEmpty() : CharacterFunctions::compare (text, other);
  9873. }
  9874. int String::compare (const juce_wchar* other) const throw()
  9875. {
  9876. return other == 0 ? isEmpty() : CharacterFunctions::compare (text, other);
  9877. }
  9878. int String::compareIgnoreCase (const String& other) const throw()
  9879. {
  9880. return (text == other.text) ? 0 : CharacterFunctions::compareIgnoreCase (text, other.text);
  9881. }
  9882. int String::compareLexicographically (const String& other) const throw()
  9883. {
  9884. const juce_wchar* s1 = text;
  9885. while (*s1 != 0 && ! CharacterFunctions::isLetterOrDigit (*s1))
  9886. ++s1;
  9887. const juce_wchar* s2 = other.text;
  9888. while (*s2 != 0 && ! CharacterFunctions::isLetterOrDigit (*s2))
  9889. ++s2;
  9890. return CharacterFunctions::compareIgnoreCase (s1, s2);
  9891. }
  9892. String& String::operator+= (const juce_wchar* const t)
  9893. {
  9894. if (t != 0)
  9895. appendInternal (t, CharacterFunctions::length (t));
  9896. return *this;
  9897. }
  9898. String& String::operator+= (const String& other)
  9899. {
  9900. if (isEmpty())
  9901. operator= (other);
  9902. else
  9903. appendInternal (other.text, other.length());
  9904. return *this;
  9905. }
  9906. String& String::operator+= (const char ch)
  9907. {
  9908. const juce_wchar asString[] = { (juce_wchar) ch, 0 };
  9909. return operator+= (static_cast <const juce_wchar*> (asString));
  9910. }
  9911. String& String::operator+= (const juce_wchar ch)
  9912. {
  9913. const juce_wchar asString[] = { (juce_wchar) ch, 0 };
  9914. return operator+= (static_cast <const juce_wchar*> (asString));
  9915. }
  9916. String& String::operator+= (const int number)
  9917. {
  9918. juce_wchar buffer [16];
  9919. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9920. juce_wchar* const start = NumberToStringConverters::intToString (end, number);
  9921. appendInternal (start, (int) (end - start));
  9922. return *this;
  9923. }
  9924. String& String::operator+= (const unsigned int number)
  9925. {
  9926. juce_wchar buffer [16];
  9927. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9928. juce_wchar* const start = NumberToStringConverters::uintToString (end, number);
  9929. appendInternal (start, (int) (end - start));
  9930. return *this;
  9931. }
  9932. void String::append (const juce_wchar* const other, const int howMany)
  9933. {
  9934. if (howMany > 0)
  9935. {
  9936. int i;
  9937. for (i = 0; i < howMany; ++i)
  9938. if (other[i] == 0)
  9939. break;
  9940. appendInternal (other, i);
  9941. }
  9942. }
  9943. JUCE_API const String JUCE_CALLTYPE operator+ (const char* const string1, const String& string2)
  9944. {
  9945. String s (string1);
  9946. return s += string2;
  9947. }
  9948. JUCE_API const String JUCE_CALLTYPE operator+ (const juce_wchar* const string1, const String& string2)
  9949. {
  9950. String s (string1);
  9951. return s += string2;
  9952. }
  9953. JUCE_API const String JUCE_CALLTYPE operator+ (const char string1, const String& string2)
  9954. {
  9955. return String::charToString (string1) + string2;
  9956. }
  9957. JUCE_API const String JUCE_CALLTYPE operator+ (const juce_wchar string1, const String& string2)
  9958. {
  9959. return String::charToString (string1) + string2;
  9960. }
  9961. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const String& string2)
  9962. {
  9963. return string1 += string2;
  9964. }
  9965. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const char* const string2)
  9966. {
  9967. return string1 += string2;
  9968. }
  9969. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const juce_wchar* const string2)
  9970. {
  9971. return string1 += string2;
  9972. }
  9973. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const char string2)
  9974. {
  9975. return string1 += string2;
  9976. }
  9977. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const juce_wchar string2)
  9978. {
  9979. return string1 += string2;
  9980. }
  9981. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const char characterToAppend)
  9982. {
  9983. return string1 += characterToAppend;
  9984. }
  9985. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const juce_wchar characterToAppend)
  9986. {
  9987. return string1 += characterToAppend;
  9988. }
  9989. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const char* const string2)
  9990. {
  9991. return string1 += string2;
  9992. }
  9993. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const juce_wchar* const string2)
  9994. {
  9995. return string1 += string2;
  9996. }
  9997. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const String& string2)
  9998. {
  9999. return string1 += string2;
  10000. }
  10001. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const short number)
  10002. {
  10003. return string1 += (int) number;
  10004. }
  10005. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const int number)
  10006. {
  10007. return string1 += number;
  10008. }
  10009. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const unsigned int number)
  10010. {
  10011. return string1 += number;
  10012. }
  10013. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const long number)
  10014. {
  10015. return string1 += (int) number;
  10016. }
  10017. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const unsigned long number)
  10018. {
  10019. return string1 += (unsigned int) number;
  10020. }
  10021. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const float number)
  10022. {
  10023. return string1 += String (number);
  10024. }
  10025. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const double number)
  10026. {
  10027. return string1 += String (number);
  10028. }
  10029. JUCE_API OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const String& text)
  10030. {
  10031. // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind
  10032. // if lots of large, persistent strings were to be written to streams).
  10033. const int numBytes = text.getNumBytesAsUTF8();
  10034. HeapBlock<char> temp (numBytes + 1);
  10035. text.copyToUTF8 (temp, numBytes + 1);
  10036. stream.write (temp, numBytes);
  10037. return stream;
  10038. }
  10039. int String::indexOfChar (const juce_wchar character) const throw()
  10040. {
  10041. const juce_wchar* t = text;
  10042. for (;;)
  10043. {
  10044. if (*t == character)
  10045. return (int) (t - text);
  10046. if (*t++ == 0)
  10047. return -1;
  10048. }
  10049. }
  10050. int String::lastIndexOfChar (const juce_wchar character) const throw()
  10051. {
  10052. for (int i = length(); --i >= 0;)
  10053. if (text[i] == character)
  10054. return i;
  10055. return -1;
  10056. }
  10057. int String::indexOf (const String& t) const throw()
  10058. {
  10059. const juce_wchar* const r = CharacterFunctions::find (text, t.text);
  10060. return r == 0 ? -1 : (int) (r - text);
  10061. }
  10062. int String::indexOfChar (const int startIndex,
  10063. const juce_wchar character) const throw()
  10064. {
  10065. if (startIndex > 0 && startIndex >= length())
  10066. return -1;
  10067. const juce_wchar* t = text + jmax (0, startIndex);
  10068. for (;;)
  10069. {
  10070. if (*t == character)
  10071. return (int) (t - text);
  10072. if (*t == 0)
  10073. return -1;
  10074. ++t;
  10075. }
  10076. }
  10077. int String::indexOfAnyOf (const String& charactersToLookFor,
  10078. const int startIndex,
  10079. const bool ignoreCase) const throw()
  10080. {
  10081. if (startIndex > 0 && startIndex >= length())
  10082. return -1;
  10083. const juce_wchar* t = text + jmax (0, startIndex);
  10084. while (*t != 0)
  10085. {
  10086. if (CharacterFunctions::indexOfChar (charactersToLookFor.text, *t, ignoreCase) >= 0)
  10087. return (int) (t - text);
  10088. ++t;
  10089. }
  10090. return -1;
  10091. }
  10092. int String::indexOf (const int startIndex, const String& other) const throw()
  10093. {
  10094. if (startIndex > 0 && startIndex >= length())
  10095. return -1;
  10096. const juce_wchar* const found = CharacterFunctions::find (text + jmax (0, startIndex), other.text);
  10097. return found == 0 ? -1 : (int) (found - text);
  10098. }
  10099. int String::indexOfIgnoreCase (const String& other) const throw()
  10100. {
  10101. if (other.isNotEmpty())
  10102. {
  10103. const int len = other.length();
  10104. const int end = length() - len;
  10105. for (int i = 0; i <= end; ++i)
  10106. if (CharacterFunctions::compareIgnoreCase (text + i, other.text, len) == 0)
  10107. return i;
  10108. }
  10109. return -1;
  10110. }
  10111. int String::indexOfIgnoreCase (const int startIndex, const String& other) const throw()
  10112. {
  10113. if (other.isNotEmpty())
  10114. {
  10115. const int len = other.length();
  10116. const int end = length() - len;
  10117. for (int i = jmax (0, startIndex); i <= end; ++i)
  10118. if (CharacterFunctions::compareIgnoreCase (text + i, other.text, len) == 0)
  10119. return i;
  10120. }
  10121. return -1;
  10122. }
  10123. int String::lastIndexOf (const String& other) const throw()
  10124. {
  10125. if (other.isNotEmpty())
  10126. {
  10127. const int len = other.length();
  10128. int i = length() - len;
  10129. if (i >= 0)
  10130. {
  10131. const juce_wchar* n = text + i;
  10132. while (i >= 0)
  10133. {
  10134. if (CharacterFunctions::compare (n--, other.text, len) == 0)
  10135. return i;
  10136. --i;
  10137. }
  10138. }
  10139. }
  10140. return -1;
  10141. }
  10142. int String::lastIndexOfIgnoreCase (const String& other) const throw()
  10143. {
  10144. if (other.isNotEmpty())
  10145. {
  10146. const int len = other.length();
  10147. int i = length() - len;
  10148. if (i >= 0)
  10149. {
  10150. const juce_wchar* n = text + i;
  10151. while (i >= 0)
  10152. {
  10153. if (CharacterFunctions::compareIgnoreCase (n--, other.text, len) == 0)
  10154. return i;
  10155. --i;
  10156. }
  10157. }
  10158. }
  10159. return -1;
  10160. }
  10161. int String::lastIndexOfAnyOf (const String& charactersToLookFor, const bool ignoreCase) const throw()
  10162. {
  10163. for (int i = length(); --i >= 0;)
  10164. if (CharacterFunctions::indexOfChar (charactersToLookFor.text, text[i], ignoreCase) >= 0)
  10165. return i;
  10166. return -1;
  10167. }
  10168. bool String::contains (const String& other) const throw()
  10169. {
  10170. return indexOf (other) >= 0;
  10171. }
  10172. bool String::containsChar (const juce_wchar character) const throw()
  10173. {
  10174. const juce_wchar* t = text;
  10175. for (;;)
  10176. {
  10177. if (*t == 0)
  10178. return false;
  10179. if (*t == character)
  10180. return true;
  10181. ++t;
  10182. }
  10183. }
  10184. bool String::containsIgnoreCase (const String& t) const throw()
  10185. {
  10186. return indexOfIgnoreCase (t) >= 0;
  10187. }
  10188. int String::indexOfWholeWord (const String& word) const throw()
  10189. {
  10190. if (word.isNotEmpty())
  10191. {
  10192. const int wordLen = word.length();
  10193. const int end = length() - wordLen;
  10194. const juce_wchar* t = text;
  10195. for (int i = 0; i <= end; ++i)
  10196. {
  10197. if (CharacterFunctions::compare (t, word.text, wordLen) == 0
  10198. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  10199. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  10200. {
  10201. return i;
  10202. }
  10203. ++t;
  10204. }
  10205. }
  10206. return -1;
  10207. }
  10208. int String::indexOfWholeWordIgnoreCase (const String& word) const throw()
  10209. {
  10210. if (word.isNotEmpty())
  10211. {
  10212. const int wordLen = word.length();
  10213. const int end = length() - wordLen;
  10214. const juce_wchar* t = text;
  10215. for (int i = 0; i <= end; ++i)
  10216. {
  10217. if (CharacterFunctions::compareIgnoreCase (t, word.text, wordLen) == 0
  10218. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  10219. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  10220. {
  10221. return i;
  10222. }
  10223. ++t;
  10224. }
  10225. }
  10226. return -1;
  10227. }
  10228. bool String::containsWholeWord (const String& wordToLookFor) const throw()
  10229. {
  10230. return indexOfWholeWord (wordToLookFor) >= 0;
  10231. }
  10232. bool String::containsWholeWordIgnoreCase (const String& wordToLookFor) const throw()
  10233. {
  10234. return indexOfWholeWordIgnoreCase (wordToLookFor) >= 0;
  10235. }
  10236. namespace WildCardHelpers
  10237. {
  10238. int indexOfMatch (const juce_wchar* const wildcard,
  10239. const juce_wchar* const test,
  10240. const bool ignoreCase) throw()
  10241. {
  10242. int start = 0;
  10243. while (test [start] != 0)
  10244. {
  10245. int i = 0;
  10246. for (;;)
  10247. {
  10248. const juce_wchar wc = wildcard [i];
  10249. const juce_wchar c = test [i + start];
  10250. if (wc == c
  10251. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  10252. || (wc == '?' && c != 0))
  10253. {
  10254. if (wc == 0)
  10255. return start;
  10256. ++i;
  10257. }
  10258. else
  10259. {
  10260. if (wc == '*' && (wildcard [i + 1] == 0
  10261. || indexOfMatch (wildcard + i + 1, test + start + i, ignoreCase) >= 0))
  10262. {
  10263. return start;
  10264. }
  10265. break;
  10266. }
  10267. }
  10268. ++start;
  10269. }
  10270. return -1;
  10271. }
  10272. }
  10273. bool String::matchesWildcard (const String& wildcard, const bool ignoreCase) const throw()
  10274. {
  10275. int i = 0;
  10276. for (;;)
  10277. {
  10278. const juce_wchar wc = wildcard.text [i];
  10279. const juce_wchar c = text [i];
  10280. if (wc == c
  10281. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  10282. || (wc == '?' && c != 0))
  10283. {
  10284. if (wc == 0)
  10285. return true;
  10286. ++i;
  10287. }
  10288. else
  10289. {
  10290. return wc == '*' && (wildcard [i + 1] == 0
  10291. || WildCardHelpers::indexOfMatch (wildcard.text + i + 1, text + i, ignoreCase) >= 0);
  10292. }
  10293. }
  10294. }
  10295. const String String::repeatedString (const String& stringToRepeat, int numberOfTimesToRepeat)
  10296. {
  10297. const int len = stringToRepeat.length();
  10298. String result ((size_t) (len * numberOfTimesToRepeat + 1), (int) 0);
  10299. juce_wchar* n = result.text;
  10300. *n = 0;
  10301. while (--numberOfTimesToRepeat >= 0)
  10302. {
  10303. StringHolder::copyChars (n, stringToRepeat.text, len);
  10304. n += len;
  10305. }
  10306. return result;
  10307. }
  10308. const String String::paddedLeft (const juce_wchar padCharacter, int minimumLength) const
  10309. {
  10310. jassert (padCharacter != 0);
  10311. const int len = length();
  10312. if (len >= minimumLength || padCharacter == 0)
  10313. return *this;
  10314. String result ((size_t) minimumLength + 1, (int) 0);
  10315. juce_wchar* n = result.text;
  10316. minimumLength -= len;
  10317. while (--minimumLength >= 0)
  10318. *n++ = padCharacter;
  10319. StringHolder::copyChars (n, text, len);
  10320. return result;
  10321. }
  10322. const String String::paddedRight (const juce_wchar padCharacter, int minimumLength) const
  10323. {
  10324. jassert (padCharacter != 0);
  10325. const int len = length();
  10326. if (len >= minimumLength || padCharacter == 0)
  10327. return *this;
  10328. String result (*this, (size_t) minimumLength);
  10329. juce_wchar* n = result.text + len;
  10330. minimumLength -= len;
  10331. while (--minimumLength >= 0)
  10332. *n++ = padCharacter;
  10333. *n = 0;
  10334. return result;
  10335. }
  10336. const String String::replaceSection (int index, int numCharsToReplace, const String& stringToInsert) const
  10337. {
  10338. if (index < 0)
  10339. {
  10340. // a negative index to replace from?
  10341. jassertfalse;
  10342. index = 0;
  10343. }
  10344. if (numCharsToReplace < 0)
  10345. {
  10346. // replacing a negative number of characters?
  10347. numCharsToReplace = 0;
  10348. jassertfalse;
  10349. }
  10350. const int len = length();
  10351. if (index + numCharsToReplace > len)
  10352. {
  10353. if (index > len)
  10354. {
  10355. // replacing beyond the end of the string?
  10356. index = len;
  10357. jassertfalse;
  10358. }
  10359. numCharsToReplace = len - index;
  10360. }
  10361. const int newStringLen = stringToInsert.length();
  10362. const int newTotalLen = len + newStringLen - numCharsToReplace;
  10363. if (newTotalLen <= 0)
  10364. return String::empty;
  10365. String result ((size_t) newTotalLen, (int) 0);
  10366. StringHolder::copyChars (result.text, text, index);
  10367. if (newStringLen > 0)
  10368. StringHolder::copyChars (result.text + index, stringToInsert.text, newStringLen);
  10369. const int endStringLen = newTotalLen - (index + newStringLen);
  10370. if (endStringLen > 0)
  10371. StringHolder::copyChars (result.text + (index + newStringLen),
  10372. text + (index + numCharsToReplace),
  10373. endStringLen);
  10374. return result;
  10375. }
  10376. const String String::replace (const String& stringToReplace, const String& stringToInsert, const bool ignoreCase) const
  10377. {
  10378. const int stringToReplaceLen = stringToReplace.length();
  10379. const int stringToInsertLen = stringToInsert.length();
  10380. int i = 0;
  10381. String result (*this);
  10382. while ((i = (ignoreCase ? result.indexOfIgnoreCase (i, stringToReplace)
  10383. : result.indexOf (i, stringToReplace))) >= 0)
  10384. {
  10385. result = result.replaceSection (i, stringToReplaceLen, stringToInsert);
  10386. i += stringToInsertLen;
  10387. }
  10388. return result;
  10389. }
  10390. const String String::replaceCharacter (const juce_wchar charToReplace, const juce_wchar charToInsert) const
  10391. {
  10392. const int index = indexOfChar (charToReplace);
  10393. if (index < 0)
  10394. return *this;
  10395. String result (*this, size_t());
  10396. juce_wchar* t = result.text + index;
  10397. while (*t != 0)
  10398. {
  10399. if (*t == charToReplace)
  10400. *t = charToInsert;
  10401. ++t;
  10402. }
  10403. return result;
  10404. }
  10405. const String String::replaceCharacters (const String& charactersToReplace,
  10406. const String& charactersToInsertInstead) const
  10407. {
  10408. String result (*this, size_t());
  10409. juce_wchar* t = result.text;
  10410. const int len2 = charactersToInsertInstead.length();
  10411. // the two strings passed in are supposed to be the same length!
  10412. jassert (len2 == charactersToReplace.length());
  10413. while (*t != 0)
  10414. {
  10415. const int index = charactersToReplace.indexOfChar (*t);
  10416. if (((unsigned int) index) < (unsigned int) len2)
  10417. *t = charactersToInsertInstead [index];
  10418. ++t;
  10419. }
  10420. return result;
  10421. }
  10422. bool String::startsWith (const String& other) const throw()
  10423. {
  10424. return CharacterFunctions::compare (text, other.text, other.length()) == 0;
  10425. }
  10426. bool String::startsWithIgnoreCase (const String& other) const throw()
  10427. {
  10428. return CharacterFunctions::compareIgnoreCase (text, other.text, other.length()) == 0;
  10429. }
  10430. bool String::startsWithChar (const juce_wchar character) const throw()
  10431. {
  10432. jassert (character != 0); // strings can't contain a null character!
  10433. return text[0] == character;
  10434. }
  10435. bool String::endsWithChar (const juce_wchar character) const throw()
  10436. {
  10437. jassert (character != 0); // strings can't contain a null character!
  10438. return text[0] != 0
  10439. && text [length() - 1] == character;
  10440. }
  10441. bool String::endsWith (const String& other) const throw()
  10442. {
  10443. const int thisLen = length();
  10444. const int otherLen = other.length();
  10445. return thisLen >= otherLen
  10446. && CharacterFunctions::compare (text + thisLen - otherLen, other.text) == 0;
  10447. }
  10448. bool String::endsWithIgnoreCase (const String& other) const throw()
  10449. {
  10450. const int thisLen = length();
  10451. const int otherLen = other.length();
  10452. return thisLen >= otherLen
  10453. && CharacterFunctions::compareIgnoreCase (text + thisLen - otherLen, other.text) == 0;
  10454. }
  10455. const String String::toUpperCase() const
  10456. {
  10457. String result (*this, size_t());
  10458. CharacterFunctions::toUpperCase (result.text);
  10459. return result;
  10460. }
  10461. const String String::toLowerCase() const
  10462. {
  10463. String result (*this, size_t());
  10464. CharacterFunctions::toLowerCase (result.text);
  10465. return result;
  10466. }
  10467. juce_wchar& String::operator[] (const int index)
  10468. {
  10469. jassert (((unsigned int) index) <= (unsigned int) length());
  10470. text = StringHolder::makeUnique (text);
  10471. return text [index];
  10472. }
  10473. juce_wchar String::getLastCharacter() const throw()
  10474. {
  10475. return isEmpty() ? juce_wchar() : text [length() - 1];
  10476. }
  10477. const String String::substring (int start, int end) const
  10478. {
  10479. if (start < 0)
  10480. start = 0;
  10481. else if (end <= start)
  10482. return empty;
  10483. int len = 0;
  10484. while (len <= end && text [len] != 0)
  10485. ++len;
  10486. if (end >= len)
  10487. {
  10488. if (start == 0)
  10489. return *this;
  10490. end = len;
  10491. }
  10492. return String (text + start, end - start);
  10493. }
  10494. const String String::substring (const int start) const
  10495. {
  10496. if (start <= 0)
  10497. return *this;
  10498. const int len = length();
  10499. if (start >= len)
  10500. return empty;
  10501. return String (text + start, len - start);
  10502. }
  10503. const String String::dropLastCharacters (const int numberToDrop) const
  10504. {
  10505. return String (text, jmax (0, length() - numberToDrop));
  10506. }
  10507. const String String::getLastCharacters (const int numCharacters) const
  10508. {
  10509. return String (text + jmax (0, length() - jmax (0, numCharacters)));
  10510. }
  10511. const String String::fromFirstOccurrenceOf (const String& sub,
  10512. const bool includeSubString,
  10513. const bool ignoreCase) const
  10514. {
  10515. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  10516. : indexOf (sub);
  10517. if (i < 0)
  10518. return empty;
  10519. return substring (includeSubString ? i : i + sub.length());
  10520. }
  10521. const String String::fromLastOccurrenceOf (const String& sub,
  10522. const bool includeSubString,
  10523. const bool ignoreCase) const
  10524. {
  10525. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  10526. : lastIndexOf (sub);
  10527. if (i < 0)
  10528. return *this;
  10529. return substring (includeSubString ? i : i + sub.length());
  10530. }
  10531. const String String::upToFirstOccurrenceOf (const String& sub,
  10532. const bool includeSubString,
  10533. const bool ignoreCase) const
  10534. {
  10535. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  10536. : indexOf (sub);
  10537. if (i < 0)
  10538. return *this;
  10539. return substring (0, includeSubString ? i + sub.length() : i);
  10540. }
  10541. const String String::upToLastOccurrenceOf (const String& sub,
  10542. const bool includeSubString,
  10543. const bool ignoreCase) const
  10544. {
  10545. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  10546. : lastIndexOf (sub);
  10547. if (i < 0)
  10548. return *this;
  10549. return substring (0, includeSubString ? i + sub.length() : i);
  10550. }
  10551. bool String::isQuotedString() const
  10552. {
  10553. const String trimmed (trimStart());
  10554. return trimmed[0] == '"'
  10555. || trimmed[0] == '\'';
  10556. }
  10557. const String String::unquoted() const
  10558. {
  10559. String s (*this);
  10560. if (s.text[0] == '"' || s.text[0] == '\'')
  10561. s = s.substring (1);
  10562. const int lastCharIndex = s.length() - 1;
  10563. if (lastCharIndex >= 0
  10564. && (s [lastCharIndex] == '"' || s[lastCharIndex] == '\''))
  10565. s [lastCharIndex] = 0;
  10566. return s;
  10567. }
  10568. const String String::quoted (const juce_wchar quoteCharacter) const
  10569. {
  10570. if (isEmpty())
  10571. return charToString (quoteCharacter) + quoteCharacter;
  10572. String t (*this);
  10573. if (! t.startsWithChar (quoteCharacter))
  10574. t = charToString (quoteCharacter) + t;
  10575. if (! t.endsWithChar (quoteCharacter))
  10576. t += quoteCharacter;
  10577. return t;
  10578. }
  10579. const String String::trim() const
  10580. {
  10581. if (isEmpty())
  10582. return empty;
  10583. int start = 0;
  10584. while (CharacterFunctions::isWhitespace (text [start]))
  10585. ++start;
  10586. const int len = length();
  10587. int end = len - 1;
  10588. while ((end >= start) && CharacterFunctions::isWhitespace (text [end]))
  10589. --end;
  10590. ++end;
  10591. if (end <= start)
  10592. return empty;
  10593. else if (start > 0 || end < len)
  10594. return String (text + start, end - start);
  10595. return *this;
  10596. }
  10597. const String String::trimStart() const
  10598. {
  10599. if (isEmpty())
  10600. return empty;
  10601. const juce_wchar* t = text;
  10602. while (CharacterFunctions::isWhitespace (*t))
  10603. ++t;
  10604. if (t == text)
  10605. return *this;
  10606. return String (t);
  10607. }
  10608. const String String::trimEnd() const
  10609. {
  10610. if (isEmpty())
  10611. return empty;
  10612. const juce_wchar* endT = text + (length() - 1);
  10613. while ((endT >= text) && CharacterFunctions::isWhitespace (*endT))
  10614. --endT;
  10615. return String (text, (int) (++endT - text));
  10616. }
  10617. const String String::trimCharactersAtStart (const String& charactersToTrim) const
  10618. {
  10619. const juce_wchar* t = text;
  10620. while (charactersToTrim.containsChar (*t))
  10621. ++t;
  10622. return t == text ? *this : String (t);
  10623. }
  10624. const String String::trimCharactersAtEnd (const String& charactersToTrim) const
  10625. {
  10626. if (isEmpty())
  10627. return empty;
  10628. const int len = length();
  10629. const juce_wchar* endT = text + (len - 1);
  10630. int numToRemove = 0;
  10631. while (numToRemove < len && charactersToTrim.containsChar (*endT))
  10632. {
  10633. ++numToRemove;
  10634. --endT;
  10635. }
  10636. return numToRemove > 0 ? String (text, len - numToRemove) : *this;
  10637. }
  10638. const String String::retainCharacters (const String& charactersToRetain) const
  10639. {
  10640. if (isEmpty())
  10641. return empty;
  10642. String result (StringHolder::getAllocatedNumChars (text), (int) 0);
  10643. juce_wchar* dst = result.text;
  10644. const juce_wchar* src = text;
  10645. while (*src != 0)
  10646. {
  10647. if (charactersToRetain.containsChar (*src))
  10648. *dst++ = *src;
  10649. ++src;
  10650. }
  10651. *dst = 0;
  10652. return result;
  10653. }
  10654. const String String::removeCharacters (const String& charactersToRemove) const
  10655. {
  10656. if (isEmpty())
  10657. return empty;
  10658. String result (StringHolder::getAllocatedNumChars (text), (int) 0);
  10659. juce_wchar* dst = result.text;
  10660. const juce_wchar* src = text;
  10661. while (*src != 0)
  10662. {
  10663. if (! charactersToRemove.containsChar (*src))
  10664. *dst++ = *src;
  10665. ++src;
  10666. }
  10667. *dst = 0;
  10668. return result;
  10669. }
  10670. const String String::initialSectionContainingOnly (const String& permittedCharacters) const
  10671. {
  10672. int i = 0;
  10673. for (;;)
  10674. {
  10675. if (! permittedCharacters.containsChar (text[i]))
  10676. break;
  10677. ++i;
  10678. }
  10679. return substring (0, i);
  10680. }
  10681. const String String::initialSectionNotContaining (const String& charactersToStopAt) const
  10682. {
  10683. const juce_wchar* const t = text;
  10684. int i = 0;
  10685. while (t[i] != 0)
  10686. {
  10687. if (charactersToStopAt.containsChar (t[i]))
  10688. return String (text, i);
  10689. ++i;
  10690. }
  10691. return empty;
  10692. }
  10693. bool String::containsOnly (const String& chars) const throw()
  10694. {
  10695. const juce_wchar* t = text;
  10696. while (*t != 0)
  10697. if (! chars.containsChar (*t++))
  10698. return false;
  10699. return true;
  10700. }
  10701. bool String::containsAnyOf (const String& chars) const throw()
  10702. {
  10703. const juce_wchar* t = text;
  10704. while (*t != 0)
  10705. if (chars.containsChar (*t++))
  10706. return true;
  10707. return false;
  10708. }
  10709. bool String::containsNonWhitespaceChars() const throw()
  10710. {
  10711. const juce_wchar* t = text;
  10712. while (*t != 0)
  10713. if (! CharacterFunctions::isWhitespace (*t++))
  10714. return true;
  10715. return false;
  10716. }
  10717. const String String::formatted (const juce_wchar* const pf, ... )
  10718. {
  10719. jassert (pf != 0);
  10720. va_list args;
  10721. va_start (args, pf);
  10722. size_t bufferSize = 256;
  10723. String result (bufferSize, (int) 0);
  10724. result.text[0] = 0;
  10725. for (;;)
  10726. {
  10727. #if JUCE_LINUX && JUCE_64BIT
  10728. va_list tempArgs;
  10729. va_copy (tempArgs, args);
  10730. const int num = (int) vswprintf (result.text, bufferSize - 1, pf, tempArgs);
  10731. va_end (tempArgs);
  10732. #elif JUCE_WINDOWS
  10733. #if JUCE_MSVC
  10734. #pragma warning (push)
  10735. #pragma warning (disable: 4996)
  10736. #endif
  10737. const int num = (int) _vsnwprintf (result.text, bufferSize - 1, pf, args);
  10738. #if JUCE_MSVC
  10739. #pragma warning (pop)
  10740. #endif
  10741. #else
  10742. const int num = (int) vswprintf (result.text, bufferSize - 1, pf, args);
  10743. #endif
  10744. if (num > 0)
  10745. return result;
  10746. bufferSize += 256;
  10747. if (num == 0 || bufferSize > 65536) // the upper limit is a sanity check to avoid situations where vprintf repeatedly
  10748. break; // returns -1 because of an error rather than because it needs more space.
  10749. result.preallocateStorage (bufferSize);
  10750. }
  10751. return empty;
  10752. }
  10753. int String::getIntValue() const throw()
  10754. {
  10755. return CharacterFunctions::getIntValue (text);
  10756. }
  10757. int String::getTrailingIntValue() const throw()
  10758. {
  10759. int n = 0;
  10760. int mult = 1;
  10761. const juce_wchar* t = text + length();
  10762. while (--t >= text)
  10763. {
  10764. const juce_wchar c = *t;
  10765. if (! CharacterFunctions::isDigit (c))
  10766. {
  10767. if (c == '-')
  10768. n = -n;
  10769. break;
  10770. }
  10771. n += mult * (c - '0');
  10772. mult *= 10;
  10773. }
  10774. return n;
  10775. }
  10776. int64 String::getLargeIntValue() const throw()
  10777. {
  10778. return CharacterFunctions::getInt64Value (text);
  10779. }
  10780. float String::getFloatValue() const throw()
  10781. {
  10782. return (float) CharacterFunctions::getDoubleValue (text);
  10783. }
  10784. double String::getDoubleValue() const throw()
  10785. {
  10786. return CharacterFunctions::getDoubleValue (text);
  10787. }
  10788. static const juce_wchar* const hexDigits = JUCE_T("0123456789abcdef");
  10789. const String String::toHexString (const int number)
  10790. {
  10791. juce_wchar buffer[32];
  10792. juce_wchar* const end = buffer + 32;
  10793. juce_wchar* t = end;
  10794. *--t = 0;
  10795. unsigned int v = (unsigned int) number;
  10796. do
  10797. {
  10798. *--t = hexDigits [v & 15];
  10799. v >>= 4;
  10800. } while (v != 0);
  10801. return String (t, (int) (((char*) end) - (char*) t) - 1);
  10802. }
  10803. const String String::toHexString (const int64 number)
  10804. {
  10805. juce_wchar buffer[32];
  10806. juce_wchar* const end = buffer + 32;
  10807. juce_wchar* t = end;
  10808. *--t = 0;
  10809. uint64 v = (uint64) number;
  10810. do
  10811. {
  10812. *--t = hexDigits [(int) (v & 15)];
  10813. v >>= 4;
  10814. } while (v != 0);
  10815. return String (t, (int) (((char*) end) - (char*) t));
  10816. }
  10817. const String String::toHexString (const short number)
  10818. {
  10819. return toHexString ((int) (unsigned short) number);
  10820. }
  10821. const String String::toHexString (const unsigned char* data,
  10822. const int size,
  10823. const int groupSize)
  10824. {
  10825. if (size <= 0)
  10826. return empty;
  10827. int numChars = (size * 2) + 2;
  10828. if (groupSize > 0)
  10829. numChars += size / groupSize;
  10830. String s ((size_t) numChars, (int) 0);
  10831. juce_wchar* d = s.text;
  10832. for (int i = 0; i < size; ++i)
  10833. {
  10834. *d++ = hexDigits [(*data) >> 4];
  10835. *d++ = hexDigits [(*data) & 0xf];
  10836. ++data;
  10837. if (groupSize > 0 && (i % groupSize) == (groupSize - 1) && i < (size - 1))
  10838. *d++ = ' ';
  10839. }
  10840. *d = 0;
  10841. return s;
  10842. }
  10843. int String::getHexValue32() const throw()
  10844. {
  10845. int result = 0;
  10846. const juce_wchar* c = text;
  10847. for (;;)
  10848. {
  10849. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  10850. if (hexValue >= 0)
  10851. result = (result << 4) | hexValue;
  10852. else if (*c == 0)
  10853. break;
  10854. ++c;
  10855. }
  10856. return result;
  10857. }
  10858. int64 String::getHexValue64() const throw()
  10859. {
  10860. int64 result = 0;
  10861. const juce_wchar* c = text;
  10862. for (;;)
  10863. {
  10864. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  10865. if (hexValue >= 0)
  10866. result = (result << 4) | hexValue;
  10867. else if (*c == 0)
  10868. break;
  10869. ++c;
  10870. }
  10871. return result;
  10872. }
  10873. const String String::createStringFromData (const void* const data_, const int size)
  10874. {
  10875. const char* const data = static_cast <const char*> (data_);
  10876. if (size <= 0 || data == 0)
  10877. {
  10878. return empty;
  10879. }
  10880. else if (size < 2)
  10881. {
  10882. return charToString (data[0]);
  10883. }
  10884. else if ((data[0] == (char)-2 && data[1] == (char)-1)
  10885. || (data[0] == (char)-1 && data[1] == (char)-2))
  10886. {
  10887. // assume it's 16-bit unicode
  10888. const bool bigEndian = (data[0] == (char)-2);
  10889. const int numChars = size / 2 - 1;
  10890. String result;
  10891. result.preallocateStorage (numChars + 2);
  10892. const uint16* const src = (const uint16*) (data + 2);
  10893. juce_wchar* const dst = const_cast <juce_wchar*> (static_cast <const juce_wchar*> (result));
  10894. if (bigEndian)
  10895. {
  10896. for (int i = 0; i < numChars; ++i)
  10897. dst[i] = (juce_wchar) ByteOrder::swapIfLittleEndian (src[i]);
  10898. }
  10899. else
  10900. {
  10901. for (int i = 0; i < numChars; ++i)
  10902. dst[i] = (juce_wchar) ByteOrder::swapIfBigEndian (src[i]);
  10903. }
  10904. dst [numChars] = 0;
  10905. return result;
  10906. }
  10907. else
  10908. {
  10909. return String::fromUTF8 (data, size);
  10910. }
  10911. }
  10912. const char* String::toUTF8() const
  10913. {
  10914. if (isEmpty())
  10915. {
  10916. return reinterpret_cast <const char*> (text);
  10917. }
  10918. else
  10919. {
  10920. const int currentLen = length() + 1;
  10921. const int utf8BytesNeeded = getNumBytesAsUTF8();
  10922. String* const mutableThis = const_cast <String*> (this);
  10923. mutableThis->text = StringHolder::makeUniqueWithSize (mutableThis->text, currentLen + 1 + utf8BytesNeeded / sizeof (juce_wchar));
  10924. char* const otherCopy = reinterpret_cast <char*> (mutableThis->text + currentLen);
  10925. #if JUCE_DEBUG // (This just avoids spurious warnings from valgrind about the uninitialised bytes at the end of the buffer..)
  10926. *(juce_wchar*) (otherCopy + (utf8BytesNeeded & ~(sizeof (juce_wchar) - 1))) = 0;
  10927. #endif
  10928. copyToUTF8 (otherCopy, std::numeric_limits<int>::max());
  10929. return otherCopy;
  10930. }
  10931. }
  10932. int String::copyToUTF8 (char* const buffer, const int maxBufferSizeBytes) const throw()
  10933. {
  10934. jassert (maxBufferSizeBytes >= 0); // keep this value positive, or no characters will be copied!
  10935. int num = 0, index = 0;
  10936. for (;;)
  10937. {
  10938. const uint32 c = (uint32) text [index++];
  10939. if (c >= 0x80)
  10940. {
  10941. int numExtraBytes = 1;
  10942. if (c >= 0x800)
  10943. {
  10944. ++numExtraBytes;
  10945. if (c >= 0x10000)
  10946. {
  10947. ++numExtraBytes;
  10948. if (c >= 0x200000)
  10949. {
  10950. ++numExtraBytes;
  10951. if (c >= 0x4000000)
  10952. ++numExtraBytes;
  10953. }
  10954. }
  10955. }
  10956. if (buffer != 0)
  10957. {
  10958. if (num + numExtraBytes >= maxBufferSizeBytes)
  10959. {
  10960. buffer [num++] = 0;
  10961. break;
  10962. }
  10963. else
  10964. {
  10965. buffer [num++] = (uint8) ((0xff << (7 - numExtraBytes)) | (c >> (numExtraBytes * 6)));
  10966. while (--numExtraBytes >= 0)
  10967. buffer [num++] = (uint8) (0x80 | (0x3f & (c >> (numExtraBytes * 6))));
  10968. }
  10969. }
  10970. else
  10971. {
  10972. num += numExtraBytes + 1;
  10973. }
  10974. }
  10975. else
  10976. {
  10977. if (buffer != 0)
  10978. {
  10979. if (num + 1 >= maxBufferSizeBytes)
  10980. {
  10981. buffer [num++] = 0;
  10982. break;
  10983. }
  10984. buffer [num] = (uint8) c;
  10985. }
  10986. ++num;
  10987. }
  10988. if (c == 0)
  10989. break;
  10990. }
  10991. return num;
  10992. }
  10993. int String::getNumBytesAsUTF8() const throw()
  10994. {
  10995. int num = 0;
  10996. const juce_wchar* t = text;
  10997. for (;;)
  10998. {
  10999. const uint32 c = (uint32) *t;
  11000. if (c >= 0x80)
  11001. {
  11002. ++num;
  11003. if (c >= 0x800)
  11004. {
  11005. ++num;
  11006. if (c >= 0x10000)
  11007. {
  11008. ++num;
  11009. if (c >= 0x200000)
  11010. {
  11011. ++num;
  11012. if (c >= 0x4000000)
  11013. ++num;
  11014. }
  11015. }
  11016. }
  11017. }
  11018. else if (c == 0)
  11019. break;
  11020. ++num;
  11021. ++t;
  11022. }
  11023. return num;
  11024. }
  11025. const String String::fromUTF8 (const char* const buffer, int bufferSizeBytes)
  11026. {
  11027. if (buffer == 0)
  11028. return empty;
  11029. if (bufferSizeBytes < 0)
  11030. bufferSizeBytes = std::numeric_limits<int>::max();
  11031. size_t numBytes;
  11032. for (numBytes = 0; numBytes < (size_t) bufferSizeBytes; ++numBytes)
  11033. if (buffer [numBytes] == 0)
  11034. break;
  11035. String result ((size_t) numBytes + 1, (int) 0);
  11036. juce_wchar* dest = result.text;
  11037. size_t i = 0;
  11038. while (i < numBytes)
  11039. {
  11040. const char c = buffer [i++];
  11041. if (c < 0)
  11042. {
  11043. unsigned int mask = 0x7f;
  11044. int bit = 0x40;
  11045. int numExtraValues = 0;
  11046. while (bit != 0 && (c & bit) != 0)
  11047. {
  11048. bit >>= 1;
  11049. mask >>= 1;
  11050. ++numExtraValues;
  11051. }
  11052. int n = (mask & (unsigned char) c);
  11053. while (--numExtraValues >= 0 && i < (size_t) bufferSizeBytes)
  11054. {
  11055. const char nextByte = buffer[i];
  11056. if ((nextByte & 0xc0) != 0x80)
  11057. break;
  11058. n <<= 6;
  11059. n |= (nextByte & 0x3f);
  11060. ++i;
  11061. }
  11062. *dest++ = (juce_wchar) n;
  11063. }
  11064. else
  11065. {
  11066. *dest++ = (juce_wchar) c;
  11067. }
  11068. }
  11069. *dest = 0;
  11070. return result;
  11071. }
  11072. const char* String::toCString() const
  11073. {
  11074. if (isEmpty())
  11075. {
  11076. return reinterpret_cast <const char*> (text);
  11077. }
  11078. else
  11079. {
  11080. const int len = length();
  11081. String* const mutableThis = const_cast <String*> (this);
  11082. mutableThis->text = StringHolder::makeUniqueWithSize (mutableThis->text, (len + 1) * 2);
  11083. char* otherCopy = reinterpret_cast <char*> (mutableThis->text + len + 1);
  11084. CharacterFunctions::copy (otherCopy, text, len);
  11085. otherCopy [len] = 0;
  11086. return otherCopy;
  11087. }
  11088. }
  11089. #if JUCE_MSVC
  11090. #pragma warning (push)
  11091. #pragma warning (disable: 4514 4996)
  11092. #endif
  11093. int String::getNumBytesAsCString() const throw()
  11094. {
  11095. return (int) wcstombs (0, text, 0);
  11096. }
  11097. int String::copyToCString (char* destBuffer, const int maxBufferSizeBytes) const throw()
  11098. {
  11099. const int numBytes = (int) wcstombs (destBuffer, text, maxBufferSizeBytes);
  11100. if (destBuffer != 0 && numBytes >= 0)
  11101. destBuffer [numBytes] = 0;
  11102. return numBytes;
  11103. }
  11104. #if JUCE_MSVC
  11105. #pragma warning (pop)
  11106. #endif
  11107. void String::copyToUnicode (juce_wchar* const destBuffer, const int maxCharsToCopy) const throw()
  11108. {
  11109. jassert (destBuffer != 0 && maxCharsToCopy >= 0);
  11110. if (destBuffer != 0 && maxCharsToCopy >= 0)
  11111. StringHolder::copyChars (destBuffer, text, jmin (maxCharsToCopy, length()));
  11112. }
  11113. String::Concatenator::Concatenator (String& stringToAppendTo)
  11114. : result (stringToAppendTo),
  11115. nextIndex (stringToAppendTo.length())
  11116. {
  11117. }
  11118. String::Concatenator::~Concatenator()
  11119. {
  11120. }
  11121. void String::Concatenator::append (const String& s)
  11122. {
  11123. const int len = s.length();
  11124. if (len > 0)
  11125. {
  11126. result.preallocateStorage (nextIndex + len);
  11127. s.copyToUnicode (static_cast <juce_wchar*> (result) + nextIndex, len);
  11128. nextIndex += len;
  11129. }
  11130. }
  11131. #if JUCE_UNIT_TESTS
  11132. class StringTests : public UnitTest
  11133. {
  11134. public:
  11135. StringTests() : UnitTest ("String class") {}
  11136. void runTest()
  11137. {
  11138. {
  11139. beginTest ("Basics");
  11140. expect (String().length() == 0);
  11141. expect (String() == String::empty);
  11142. String s1, s2 ("abcd");
  11143. expect (s1.isEmpty() && ! s1.isNotEmpty());
  11144. expect (s2.isNotEmpty() && ! s2.isEmpty());
  11145. expect (s2.length() == 4);
  11146. s1 = "abcd";
  11147. expect (s2 == s1 && s1 == s2);
  11148. expect (s1 == "abcd" && s1 == L"abcd");
  11149. expect (String ("abcd") == String (L"abcd"));
  11150. expect (String ("abcdefg", 4) == L"abcd");
  11151. expect (String ("abcdefg", 4) == String (L"abcdefg", 4));
  11152. expect (String::charToString ('x') == "x");
  11153. expect (String::charToString (0) == String::empty);
  11154. expect (s2 + "e" == "abcde" && s2 + 'e' == "abcde");
  11155. expect (s2 + L'e' == "abcde" && s2 + L"e" == "abcde");
  11156. expect (s1.equalsIgnoreCase ("abcD") && s1 < "abce" && s1 > "abbb");
  11157. expect (s1.startsWith ("ab") && s1.startsWith ("abcd") && ! s1.startsWith ("abcde"));
  11158. expect (s1.startsWithIgnoreCase ("aB") && s1.endsWithIgnoreCase ("CD"));
  11159. expect (s1.endsWith ("bcd") && ! s1.endsWith ("aabcd"));
  11160. expect (s1.indexOf (String::empty) == 0);
  11161. expect (s1.startsWith (String::empty) && s1.endsWith (String::empty) && s1.contains (String::empty));
  11162. expect (s1.contains ("cd") && s1.contains ("ab") && s1.contains ("abcd"));
  11163. expect (s1.containsChar ('a') && ! s1.containsChar (0));
  11164. expect (String ("abc foo bar").containsWholeWord ("abc") && String ("abc foo bar").containsWholeWord ("abc"));
  11165. }
  11166. {
  11167. beginTest ("Operations");
  11168. String s ("012345678");
  11169. expect (s.hashCode() != 0);
  11170. expect (s.hashCode64() != 0);
  11171. expect (s.hashCode() != (s + s).hashCode());
  11172. expect (s.hashCode64() != (s + s).hashCode64());
  11173. expect (s.compare (String ("012345678")) == 0);
  11174. expect (s.compare (String ("012345679")) < 0);
  11175. expect (s.compare (String ("012345676")) > 0);
  11176. expect (s.substring (2, 3) == String::charToString (s[2]));
  11177. expect (s.substring (0, 1) == String::charToString (s[0]));
  11178. expect (s.getLastCharacter() == s [s.length() - 1]);
  11179. expect (String::charToString (s.getLastCharacter()) == s.getLastCharacters (1));
  11180. expect (s.substring (0, 3) == L"012");
  11181. expect (s.substring (0, 100) == s);
  11182. expect (s.substring (-1, 100) == s);
  11183. expect (s.substring (3) == "345678");
  11184. expect (s.indexOf (L"45") == 4);
  11185. expect (String ("444445").indexOf ("45") == 4);
  11186. expect (String ("444445").lastIndexOfChar ('4') == 4);
  11187. expect (String ("45454545x").lastIndexOf (L"45") == 6);
  11188. expect (String ("45454545x").lastIndexOfAnyOf ("456") == 7);
  11189. expect (String ("45454545x").lastIndexOfAnyOf (L"456x") == 8);
  11190. expect (String ("abABaBaBa").lastIndexOfIgnoreCase ("Ab") == 6);
  11191. expect (s.indexOfChar (L'4') == 4);
  11192. expect (s + s == "012345678012345678");
  11193. expect (s.startsWith (s));
  11194. expect (s.startsWith (s.substring (0, 4)));
  11195. expect (s.startsWith (s.dropLastCharacters (4)));
  11196. expect (s.endsWith (s.substring (5)));
  11197. expect (s.endsWith (s));
  11198. expect (s.contains (s.substring (3, 6)));
  11199. expect (s.contains (s.substring (3)));
  11200. expect (s.startsWithChar (s[0]));
  11201. expect (s.endsWithChar (s.getLastCharacter()));
  11202. expect (s [s.length()] == 0);
  11203. expect (String ("abcdEFGH").toLowerCase() == String ("abcdefgh"));
  11204. expect (String ("abcdEFGH").toUpperCase() == String ("ABCDEFGH"));
  11205. String s2 ("123");
  11206. s2 << ((int) 4) << ((short) 5) << "678" << L"9" << '0';
  11207. s2 += "xyz";
  11208. expect (s2 == "1234567890xyz");
  11209. beginTest ("Numeric conversions");
  11210. expect (String::empty.getIntValue() == 0);
  11211. expect (String::empty.getDoubleValue() == 0.0);
  11212. expect (String::empty.getFloatValue() == 0.0f);
  11213. expect (s.getIntValue() == 12345678);
  11214. expect (s.getLargeIntValue() == (int64) 12345678);
  11215. expect (s.getDoubleValue() == 12345678.0);
  11216. expect (s.getFloatValue() == 12345678.0f);
  11217. expect (String (-1234).getIntValue() == -1234);
  11218. expect (String ((int64) -1234).getLargeIntValue() == -1234);
  11219. expect (String (-1234.56).getDoubleValue() == -1234.56);
  11220. expect (String (-1234.56f).getFloatValue() == -1234.56f);
  11221. expect (("xyz" + s).getTrailingIntValue() == s.getIntValue());
  11222. expect (s.getHexValue32() == 0x12345678);
  11223. expect (s.getHexValue64() == (int64) 0x12345678);
  11224. expect (String::toHexString (0x1234abcd).equalsIgnoreCase ("1234abcd"));
  11225. expect (String::toHexString ((int64) 0x1234abcd).equalsIgnoreCase ("1234abcd"));
  11226. expect (String::toHexString ((short) 0x12ab).equalsIgnoreCase ("12ab"));
  11227. unsigned char data[] = { 1, 2, 3, 4, 0xa, 0xb, 0xc, 0xd };
  11228. expect (String::toHexString (data, 8, 0).equalsIgnoreCase ("010203040a0b0c0d"));
  11229. expect (String::toHexString (data, 8, 1).equalsIgnoreCase ("01 02 03 04 0a 0b 0c 0d"));
  11230. expect (String::toHexString (data, 8, 2).equalsIgnoreCase ("0102 0304 0a0b 0c0d"));
  11231. beginTest ("Subsections");
  11232. String s3;
  11233. s3 = "abcdeFGHIJ";
  11234. expect (s3.equalsIgnoreCase ("ABCdeFGhiJ"));
  11235. expect (s3.compareIgnoreCase (L"ABCdeFGhiJ") == 0);
  11236. expect (s3.containsIgnoreCase (s3.substring (3)));
  11237. expect (s3.indexOfAnyOf ("xyzf", 2, true) == 5);
  11238. expect (s3.indexOfAnyOf (L"xyzf", 2, false) == -1);
  11239. expect (s3.indexOfAnyOf ("xyzF", 2, false) == 5);
  11240. expect (s3.containsAnyOf (L"zzzFs"));
  11241. expect (s3.startsWith ("abcd"));
  11242. expect (s3.startsWithIgnoreCase (L"abCD"));
  11243. expect (s3.startsWith (String::empty));
  11244. expect (s3.startsWithChar ('a'));
  11245. expect (s3.endsWith (String ("HIJ")));
  11246. expect (s3.endsWithIgnoreCase (L"Hij"));
  11247. expect (s3.endsWith (String::empty));
  11248. expect (s3.endsWithChar (L'J'));
  11249. expect (s3.indexOf ("HIJ") == 7);
  11250. expect (s3.indexOf (L"HIJK") == -1);
  11251. expect (s3.indexOfIgnoreCase ("hij") == 7);
  11252. expect (s3.indexOfIgnoreCase (L"hijk") == -1);
  11253. String s4 (s3);
  11254. s4.append (String ("xyz123"), 3);
  11255. expect (s4 == s3 + "xyz");
  11256. expect (String (1234) < String (1235));
  11257. expect (String (1235) > String (1234));
  11258. expect (String (1234) >= String (1234));
  11259. expect (String (1234) <= String (1234));
  11260. expect (String (1235) >= String (1234));
  11261. expect (String (1234) <= String (1235));
  11262. String s5 ("word word2 word3");
  11263. expect (s5.containsWholeWord (String ("word2")));
  11264. expect (s5.indexOfWholeWord ("word2") == 5);
  11265. expect (s5.containsWholeWord (L"word"));
  11266. expect (s5.containsWholeWord ("word3"));
  11267. expect (s5.containsWholeWord (s5));
  11268. expect (s5.containsWholeWordIgnoreCase (L"Word2"));
  11269. expect (s5.indexOfWholeWordIgnoreCase ("Word2") == 5);
  11270. expect (s5.containsWholeWordIgnoreCase (L"Word"));
  11271. expect (s5.containsWholeWordIgnoreCase ("Word3"));
  11272. expect (! s5.containsWholeWordIgnoreCase (L"Wordx"));
  11273. expect (!s5.containsWholeWordIgnoreCase ("xWord2"));
  11274. expect (s5.containsNonWhitespaceChars());
  11275. expect (! String (" \n\r\t").containsNonWhitespaceChars());
  11276. expect (s5.matchesWildcard (L"wor*", false));
  11277. expect (s5.matchesWildcard ("wOr*", true));
  11278. expect (s5.matchesWildcard (L"*word3", true));
  11279. expect (s5.matchesWildcard ("*word?", true));
  11280. expect (s5.matchesWildcard (L"Word*3", true));
  11281. expect (s5.fromFirstOccurrenceOf (String::empty, true, false) == s5);
  11282. expect (s5.fromFirstOccurrenceOf ("xword2", true, false) == s5.substring (100));
  11283. expect (s5.fromFirstOccurrenceOf (L"word2", true, false) == s5.substring (5));
  11284. expect (s5.fromFirstOccurrenceOf ("Word2", true, true) == s5.substring (5));
  11285. expect (s5.fromFirstOccurrenceOf ("word2", false, false) == s5.getLastCharacters (6));
  11286. expect (s5.fromFirstOccurrenceOf (L"Word2", false, true) == s5.getLastCharacters (6));
  11287. expect (s5.fromLastOccurrenceOf (String::empty, true, false) == s5);
  11288. expect (s5.fromLastOccurrenceOf (L"wordx", true, false) == s5);
  11289. expect (s5.fromLastOccurrenceOf ("word", true, false) == s5.getLastCharacters (5));
  11290. expect (s5.fromLastOccurrenceOf (L"worD", true, true) == s5.getLastCharacters (5));
  11291. expect (s5.fromLastOccurrenceOf ("word", false, false) == s5.getLastCharacters (1));
  11292. expect (s5.fromLastOccurrenceOf (L"worD", false, true) == s5.getLastCharacters (1));
  11293. expect (s5.upToFirstOccurrenceOf (String::empty, true, false).isEmpty());
  11294. expect (s5.upToFirstOccurrenceOf ("word4", true, false) == s5);
  11295. expect (s5.upToFirstOccurrenceOf (L"word2", true, false) == s5.substring (0, 10));
  11296. expect (s5.upToFirstOccurrenceOf ("Word2", true, true) == s5.substring (0, 10));
  11297. expect (s5.upToFirstOccurrenceOf (L"word2", false, false) == s5.substring (0, 5));
  11298. expect (s5.upToFirstOccurrenceOf ("Word2", false, true) == s5.substring (0, 5));
  11299. expect (s5.upToLastOccurrenceOf (String::empty, true, false) == s5);
  11300. expect (s5.upToLastOccurrenceOf ("zword", true, false) == s5);
  11301. expect (s5.upToLastOccurrenceOf ("word", true, false) == s5.dropLastCharacters (1));
  11302. expect (s5.dropLastCharacters(1).upToLastOccurrenceOf ("word", true, false) == s5.dropLastCharacters (1));
  11303. expect (s5.upToLastOccurrenceOf ("Word", true, true) == s5.dropLastCharacters (1));
  11304. expect (s5.upToLastOccurrenceOf ("word", false, false) == s5.dropLastCharacters (5));
  11305. expect (s5.upToLastOccurrenceOf ("Word", false, true) == s5.dropLastCharacters (5));
  11306. expect (s5.replace ("word", L"xyz", false) == String ("xyz xyz2 xyz3"));
  11307. expect (s5.replace (L"Word", "xyz", true) == "xyz xyz2 xyz3");
  11308. expect (s5.dropLastCharacters (1).replace ("Word", String ("xyz"), true) == L"xyz xyz2 xyz");
  11309. expect (s5.replace ("Word", "", true) == " 2 3");
  11310. expect (s5.replace ("Word2", L"xyz", true) == String ("word xyz word3"));
  11311. expect (s5.replaceCharacter (L'w', 'x') != s5);
  11312. expect (s5.replaceCharacter ('w', L'x').replaceCharacter ('x', 'w') == s5);
  11313. expect (s5.replaceCharacters ("wo", "xy") != s5);
  11314. expect (s5.replaceCharacters ("wo", "xy").replaceCharacters ("xy", L"wo") == s5);
  11315. expect (s5.retainCharacters ("1wordxya") == String ("wordwordword"));
  11316. expect (s5.retainCharacters (String::empty).isEmpty());
  11317. expect (s5.removeCharacters ("1wordxya") == " 2 3");
  11318. expect (s5.removeCharacters (String::empty) == s5);
  11319. expect (s5.initialSectionContainingOnly ("word") == L"word");
  11320. expect (s5.initialSectionNotContaining (String ("xyz ")) == String ("word"));
  11321. expect (! s5.isQuotedString());
  11322. expect (s5.quoted().isQuotedString());
  11323. expect (! s5.quoted().unquoted().isQuotedString());
  11324. expect (! String ("x'").isQuotedString());
  11325. expect (String ("'x").isQuotedString());
  11326. String s6 (" \t xyz \t\r\n");
  11327. expect (s6.trim() == String ("xyz"));
  11328. expect (s6.trim().trim() == "xyz");
  11329. expect (s5.trim() == s5);
  11330. expect (s6.trimStart().trimEnd() == s6.trim());
  11331. expect (s6.trimStart().trimEnd() == s6.trimEnd().trimStart());
  11332. expect (s6.trimStart().trimStart().trimEnd().trimEnd() == s6.trimEnd().trimStart());
  11333. expect (s6.trimStart() != s6.trimEnd());
  11334. expect (("\t\r\n " + s6 + "\t\n \r").trim() == s6.trim());
  11335. expect (String::repeatedString ("xyz", 3) == L"xyzxyzxyz");
  11336. }
  11337. {
  11338. beginTest ("UTF8");
  11339. String s ("word word2 word3");
  11340. {
  11341. char buffer [100];
  11342. memset (buffer, 0xff, sizeof (buffer));
  11343. s.copyToUTF8 (buffer, 100);
  11344. expect (String::fromUTF8 (buffer, 100) == s);
  11345. juce_wchar bufferUnicode [100];
  11346. memset (bufferUnicode, 0xff, sizeof (bufferUnicode));
  11347. s.copyToUnicode (bufferUnicode, 100);
  11348. expect (String (bufferUnicode, 100) == s);
  11349. }
  11350. {
  11351. juce_wchar wideBuffer [50];
  11352. zerostruct (wideBuffer);
  11353. for (int i = 0; i < numElementsInArray (wideBuffer) - 1; ++i)
  11354. wideBuffer[i] = (juce_wchar) (1 + Random::getSystemRandom().nextInt (std::numeric_limits<juce_wchar>::max() - 1));
  11355. String wide (wideBuffer);
  11356. expect (wide == (const juce_wchar*) wideBuffer);
  11357. expect (wide.length() == numElementsInArray (wideBuffer) - 1);
  11358. expect (String::fromUTF8 (wide.toUTF8()) == wide);
  11359. expect (String::fromUTF8 (wide.toUTF8()) == wideBuffer);
  11360. }
  11361. }
  11362. }
  11363. };
  11364. static StringTests stringUnitTests;
  11365. #endif
  11366. END_JUCE_NAMESPACE
  11367. /*** End of inlined file: juce_String.cpp ***/
  11368. /*** Start of inlined file: juce_StringArray.cpp ***/
  11369. BEGIN_JUCE_NAMESPACE
  11370. StringArray::StringArray() throw()
  11371. {
  11372. }
  11373. StringArray::StringArray (const StringArray& other)
  11374. : strings (other.strings)
  11375. {
  11376. }
  11377. StringArray::StringArray (const String& firstValue)
  11378. {
  11379. strings.add (firstValue);
  11380. }
  11381. StringArray::StringArray (const juce_wchar* const* const initialStrings,
  11382. const int numberOfStrings)
  11383. {
  11384. for (int i = 0; i < numberOfStrings; ++i)
  11385. strings.add (initialStrings [i]);
  11386. }
  11387. StringArray::StringArray (const char* const* const initialStrings,
  11388. const int numberOfStrings)
  11389. {
  11390. for (int i = 0; i < numberOfStrings; ++i)
  11391. strings.add (initialStrings [i]);
  11392. }
  11393. StringArray::StringArray (const juce_wchar* const* const initialStrings)
  11394. {
  11395. int i = 0;
  11396. while (initialStrings[i] != 0)
  11397. strings.add (initialStrings [i++]);
  11398. }
  11399. StringArray::StringArray (const char* const* const initialStrings)
  11400. {
  11401. int i = 0;
  11402. while (initialStrings[i] != 0)
  11403. strings.add (initialStrings [i++]);
  11404. }
  11405. StringArray& StringArray::operator= (const StringArray& other)
  11406. {
  11407. strings = other.strings;
  11408. return *this;
  11409. }
  11410. StringArray::~StringArray()
  11411. {
  11412. }
  11413. bool StringArray::operator== (const StringArray& other) const throw()
  11414. {
  11415. if (other.size() != size())
  11416. return false;
  11417. for (int i = size(); --i >= 0;)
  11418. if (other.strings.getReference(i) != strings.getReference(i))
  11419. return false;
  11420. return true;
  11421. }
  11422. bool StringArray::operator!= (const StringArray& other) const throw()
  11423. {
  11424. return ! operator== (other);
  11425. }
  11426. void StringArray::clear()
  11427. {
  11428. strings.clear();
  11429. }
  11430. const String& StringArray::operator[] (const int index) const throw()
  11431. {
  11432. if (((unsigned int) index) < (unsigned int) strings.size())
  11433. return strings.getReference (index);
  11434. return String::empty;
  11435. }
  11436. String& StringArray::getReference (const int index) throw()
  11437. {
  11438. jassert (((unsigned int) index) < (unsigned int) strings.size());
  11439. return strings.getReference (index);
  11440. }
  11441. void StringArray::add (const String& newString)
  11442. {
  11443. strings.add (newString);
  11444. }
  11445. void StringArray::insert (const int index, const String& newString)
  11446. {
  11447. strings.insert (index, newString);
  11448. }
  11449. void StringArray::addIfNotAlreadyThere (const String& newString, const bool ignoreCase)
  11450. {
  11451. if (! contains (newString, ignoreCase))
  11452. add (newString);
  11453. }
  11454. void StringArray::addArray (const StringArray& otherArray, int startIndex, int numElementsToAdd)
  11455. {
  11456. if (startIndex < 0)
  11457. {
  11458. jassertfalse;
  11459. startIndex = 0;
  11460. }
  11461. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > otherArray.size())
  11462. numElementsToAdd = otherArray.size() - startIndex;
  11463. while (--numElementsToAdd >= 0)
  11464. strings.add (otherArray.strings.getReference (startIndex++));
  11465. }
  11466. void StringArray::set (const int index, const String& newString)
  11467. {
  11468. strings.set (index, newString);
  11469. }
  11470. bool StringArray::contains (const String& stringToLookFor, const bool ignoreCase) const
  11471. {
  11472. if (ignoreCase)
  11473. {
  11474. for (int i = size(); --i >= 0;)
  11475. if (strings.getReference(i).equalsIgnoreCase (stringToLookFor))
  11476. return true;
  11477. }
  11478. else
  11479. {
  11480. for (int i = size(); --i >= 0;)
  11481. if (stringToLookFor == strings.getReference(i))
  11482. return true;
  11483. }
  11484. return false;
  11485. }
  11486. int StringArray::indexOf (const String& stringToLookFor, const bool ignoreCase, int i) const
  11487. {
  11488. if (i < 0)
  11489. i = 0;
  11490. const int numElements = size();
  11491. if (ignoreCase)
  11492. {
  11493. while (i < numElements)
  11494. {
  11495. if (strings.getReference(i).equalsIgnoreCase (stringToLookFor))
  11496. return i;
  11497. ++i;
  11498. }
  11499. }
  11500. else
  11501. {
  11502. while (i < numElements)
  11503. {
  11504. if (stringToLookFor == strings.getReference (i))
  11505. return i;
  11506. ++i;
  11507. }
  11508. }
  11509. return -1;
  11510. }
  11511. void StringArray::remove (const int index)
  11512. {
  11513. strings.remove (index);
  11514. }
  11515. void StringArray::removeString (const String& stringToRemove,
  11516. const bool ignoreCase)
  11517. {
  11518. if (ignoreCase)
  11519. {
  11520. for (int i = size(); --i >= 0;)
  11521. if (strings.getReference(i).equalsIgnoreCase (stringToRemove))
  11522. strings.remove (i);
  11523. }
  11524. else
  11525. {
  11526. for (int i = size(); --i >= 0;)
  11527. if (stringToRemove == strings.getReference (i))
  11528. strings.remove (i);
  11529. }
  11530. }
  11531. void StringArray::removeRange (int startIndex, int numberToRemove)
  11532. {
  11533. strings.removeRange (startIndex, numberToRemove);
  11534. }
  11535. void StringArray::removeEmptyStrings (const bool removeWhitespaceStrings)
  11536. {
  11537. if (removeWhitespaceStrings)
  11538. {
  11539. for (int i = size(); --i >= 0;)
  11540. if (! strings.getReference(i).containsNonWhitespaceChars())
  11541. strings.remove (i);
  11542. }
  11543. else
  11544. {
  11545. for (int i = size(); --i >= 0;)
  11546. if (strings.getReference(i).isEmpty())
  11547. strings.remove (i);
  11548. }
  11549. }
  11550. void StringArray::trim()
  11551. {
  11552. for (int i = size(); --i >= 0;)
  11553. {
  11554. String& s = strings.getReference(i);
  11555. s = s.trim();
  11556. }
  11557. }
  11558. class InternalStringArrayComparator_CaseSensitive
  11559. {
  11560. public:
  11561. static int compareElements (String& first, String& second) { return first.compare (second); }
  11562. };
  11563. class InternalStringArrayComparator_CaseInsensitive
  11564. {
  11565. public:
  11566. static int compareElements (String& first, String& second) { return first.compareIgnoreCase (second); }
  11567. };
  11568. void StringArray::sort (const bool ignoreCase)
  11569. {
  11570. if (ignoreCase)
  11571. {
  11572. InternalStringArrayComparator_CaseInsensitive comp;
  11573. strings.sort (comp);
  11574. }
  11575. else
  11576. {
  11577. InternalStringArrayComparator_CaseSensitive comp;
  11578. strings.sort (comp);
  11579. }
  11580. }
  11581. void StringArray::move (const int currentIndex, int newIndex) throw()
  11582. {
  11583. strings.move (currentIndex, newIndex);
  11584. }
  11585. const String StringArray::joinIntoString (const String& separator, int start, int numberToJoin) const
  11586. {
  11587. const int last = (numberToJoin < 0) ? size()
  11588. : jmin (size(), start + numberToJoin);
  11589. if (start < 0)
  11590. start = 0;
  11591. if (start >= last)
  11592. return String::empty;
  11593. if (start == last - 1)
  11594. return strings.getReference (start);
  11595. const int separatorLen = separator.length();
  11596. int charsNeeded = separatorLen * (last - start - 1);
  11597. for (int i = start; i < last; ++i)
  11598. charsNeeded += strings.getReference(i).length();
  11599. String result;
  11600. result.preallocateStorage (charsNeeded);
  11601. juce_wchar* dest = result;
  11602. while (start < last)
  11603. {
  11604. const String& s = strings.getReference (start);
  11605. const int len = s.length();
  11606. if (len > 0)
  11607. {
  11608. s.copyToUnicode (dest, len);
  11609. dest += len;
  11610. }
  11611. if (++start < last && separatorLen > 0)
  11612. {
  11613. separator.copyToUnicode (dest, separatorLen);
  11614. dest += separatorLen;
  11615. }
  11616. }
  11617. *dest = 0;
  11618. return result;
  11619. }
  11620. int StringArray::addTokens (const String& text, const bool preserveQuotedStrings)
  11621. {
  11622. return addTokens (text, " \n\r\t", preserveQuotedStrings ? "\"" : "");
  11623. }
  11624. int StringArray::addTokens (const String& text, const String& breakCharacters, const String& quoteCharacters)
  11625. {
  11626. int num = 0;
  11627. if (text.isNotEmpty())
  11628. {
  11629. bool insideQuotes = false;
  11630. juce_wchar currentQuoteChar = 0;
  11631. int i = 0;
  11632. int tokenStart = 0;
  11633. for (;;)
  11634. {
  11635. const juce_wchar c = text[i];
  11636. const bool isBreak = (c == 0) || ((! insideQuotes) && breakCharacters.containsChar (c));
  11637. if (! isBreak)
  11638. {
  11639. if (quoteCharacters.containsChar (c))
  11640. {
  11641. if (insideQuotes)
  11642. {
  11643. // only break out of quotes-mode if we find a matching quote to the
  11644. // one that we opened with..
  11645. if (currentQuoteChar == c)
  11646. insideQuotes = false;
  11647. }
  11648. else
  11649. {
  11650. insideQuotes = true;
  11651. currentQuoteChar = c;
  11652. }
  11653. }
  11654. }
  11655. else
  11656. {
  11657. add (String (static_cast <const juce_wchar*> (text) + tokenStart, i - tokenStart));
  11658. ++num;
  11659. tokenStart = i + 1;
  11660. }
  11661. if (c == 0)
  11662. break;
  11663. ++i;
  11664. }
  11665. }
  11666. return num;
  11667. }
  11668. int StringArray::addLines (const String& sourceText)
  11669. {
  11670. int numLines = 0;
  11671. const juce_wchar* text = sourceText;
  11672. while (*text != 0)
  11673. {
  11674. const juce_wchar* const startOfLine = text;
  11675. while (*text != 0)
  11676. {
  11677. if (*text == '\r')
  11678. {
  11679. ++text;
  11680. if (*text == '\n')
  11681. ++text;
  11682. break;
  11683. }
  11684. if (*text == '\n')
  11685. {
  11686. ++text;
  11687. break;
  11688. }
  11689. ++text;
  11690. }
  11691. const juce_wchar* endOfLine = text;
  11692. if (endOfLine > startOfLine && (*(endOfLine - 1) == '\r' || *(endOfLine - 1) == '\n'))
  11693. --endOfLine;
  11694. if (endOfLine > startOfLine && (*(endOfLine - 1) == '\r' || *(endOfLine - 1) == '\n'))
  11695. --endOfLine;
  11696. add (String (startOfLine, jmax (0, (int) (endOfLine - startOfLine))));
  11697. ++numLines;
  11698. }
  11699. return numLines;
  11700. }
  11701. void StringArray::removeDuplicates (const bool ignoreCase)
  11702. {
  11703. for (int i = 0; i < size() - 1; ++i)
  11704. {
  11705. const String s (strings.getReference(i));
  11706. int nextIndex = i + 1;
  11707. for (;;)
  11708. {
  11709. nextIndex = indexOf (s, ignoreCase, nextIndex);
  11710. if (nextIndex < 0)
  11711. break;
  11712. strings.remove (nextIndex);
  11713. }
  11714. }
  11715. }
  11716. void StringArray::appendNumbersToDuplicates (const bool ignoreCase,
  11717. const bool appendNumberToFirstInstance,
  11718. const juce_wchar* preNumberString,
  11719. const juce_wchar* postNumberString)
  11720. {
  11721. if (preNumberString == 0)
  11722. preNumberString = L" (";
  11723. if (postNumberString == 0)
  11724. postNumberString = L")";
  11725. for (int i = 0; i < size() - 1; ++i)
  11726. {
  11727. String& s = strings.getReference(i);
  11728. int nextIndex = indexOf (s, ignoreCase, i + 1);
  11729. if (nextIndex >= 0)
  11730. {
  11731. const String original (s);
  11732. int number = 0;
  11733. if (appendNumberToFirstInstance)
  11734. s = original + preNumberString + String (++number) + postNumberString;
  11735. else
  11736. ++number;
  11737. while (nextIndex >= 0)
  11738. {
  11739. set (nextIndex, (*this)[nextIndex] + preNumberString + String (++number) + postNumberString);
  11740. nextIndex = indexOf (original, ignoreCase, nextIndex + 1);
  11741. }
  11742. }
  11743. }
  11744. }
  11745. void StringArray::minimiseStorageOverheads()
  11746. {
  11747. strings.minimiseStorageOverheads();
  11748. }
  11749. END_JUCE_NAMESPACE
  11750. /*** End of inlined file: juce_StringArray.cpp ***/
  11751. /*** Start of inlined file: juce_StringPairArray.cpp ***/
  11752. BEGIN_JUCE_NAMESPACE
  11753. StringPairArray::StringPairArray (const bool ignoreCase_)
  11754. : ignoreCase (ignoreCase_)
  11755. {
  11756. }
  11757. StringPairArray::StringPairArray (const StringPairArray& other)
  11758. : keys (other.keys),
  11759. values (other.values),
  11760. ignoreCase (other.ignoreCase)
  11761. {
  11762. }
  11763. StringPairArray::~StringPairArray()
  11764. {
  11765. }
  11766. StringPairArray& StringPairArray::operator= (const StringPairArray& other)
  11767. {
  11768. keys = other.keys;
  11769. values = other.values;
  11770. return *this;
  11771. }
  11772. bool StringPairArray::operator== (const StringPairArray& other) const
  11773. {
  11774. for (int i = keys.size(); --i >= 0;)
  11775. if (other [keys[i]] != values[i])
  11776. return false;
  11777. return true;
  11778. }
  11779. bool StringPairArray::operator!= (const StringPairArray& other) const
  11780. {
  11781. return ! operator== (other);
  11782. }
  11783. const String& StringPairArray::operator[] (const String& key) const
  11784. {
  11785. return values [keys.indexOf (key, ignoreCase)];
  11786. }
  11787. const String StringPairArray::getValue (const String& key, const String& defaultReturnValue) const
  11788. {
  11789. const int i = keys.indexOf (key, ignoreCase);
  11790. if (i >= 0)
  11791. return values[i];
  11792. return defaultReturnValue;
  11793. }
  11794. void StringPairArray::set (const String& key, const String& value)
  11795. {
  11796. const int i = keys.indexOf (key, ignoreCase);
  11797. if (i >= 0)
  11798. {
  11799. values.set (i, value);
  11800. }
  11801. else
  11802. {
  11803. keys.add (key);
  11804. values.add (value);
  11805. }
  11806. }
  11807. void StringPairArray::addArray (const StringPairArray& other)
  11808. {
  11809. for (int i = 0; i < other.size(); ++i)
  11810. set (other.keys[i], other.values[i]);
  11811. }
  11812. void StringPairArray::clear()
  11813. {
  11814. keys.clear();
  11815. values.clear();
  11816. }
  11817. void StringPairArray::remove (const String& key)
  11818. {
  11819. remove (keys.indexOf (key, ignoreCase));
  11820. }
  11821. void StringPairArray::remove (const int index)
  11822. {
  11823. keys.remove (index);
  11824. values.remove (index);
  11825. }
  11826. void StringPairArray::setIgnoresCase (const bool shouldIgnoreCase)
  11827. {
  11828. ignoreCase = shouldIgnoreCase;
  11829. }
  11830. const String StringPairArray::getDescription() const
  11831. {
  11832. String s;
  11833. for (int i = 0; i < keys.size(); ++i)
  11834. {
  11835. s << keys[i] << " = " << values[i];
  11836. if (i < keys.size())
  11837. s << ", ";
  11838. }
  11839. return s;
  11840. }
  11841. void StringPairArray::minimiseStorageOverheads()
  11842. {
  11843. keys.minimiseStorageOverheads();
  11844. values.minimiseStorageOverheads();
  11845. }
  11846. END_JUCE_NAMESPACE
  11847. /*** End of inlined file: juce_StringPairArray.cpp ***/
  11848. /*** Start of inlined file: juce_StringPool.cpp ***/
  11849. BEGIN_JUCE_NAMESPACE
  11850. StringPool::StringPool() throw() {}
  11851. StringPool::~StringPool() {}
  11852. namespace StringPoolHelpers
  11853. {
  11854. template <class StringType>
  11855. const juce_wchar* getPooledStringFromArray (Array<String>& strings, StringType newString)
  11856. {
  11857. int start = 0;
  11858. int end = strings.size();
  11859. for (;;)
  11860. {
  11861. if (start >= end)
  11862. {
  11863. jassert (start <= end);
  11864. strings.insert (start, newString);
  11865. return strings.getReference (start);
  11866. }
  11867. else
  11868. {
  11869. const String& startString = strings.getReference (start);
  11870. if (startString == newString)
  11871. return startString;
  11872. const int halfway = (start + end) >> 1;
  11873. if (halfway == start)
  11874. {
  11875. if (startString.compare (newString) < 0)
  11876. ++start;
  11877. strings.insert (start, newString);
  11878. return strings.getReference (start);
  11879. }
  11880. const int comp = strings.getReference (halfway).compare (newString);
  11881. if (comp == 0)
  11882. return strings.getReference (halfway);
  11883. else if (comp < 0)
  11884. start = halfway;
  11885. else
  11886. end = halfway;
  11887. }
  11888. }
  11889. }
  11890. }
  11891. const juce_wchar* StringPool::getPooledString (const String& s)
  11892. {
  11893. if (s.isEmpty())
  11894. return String::empty;
  11895. return StringPoolHelpers::getPooledStringFromArray (strings, s);
  11896. }
  11897. const juce_wchar* StringPool::getPooledString (const char* const s)
  11898. {
  11899. if (s == 0 || *s == 0)
  11900. return String::empty;
  11901. return StringPoolHelpers::getPooledStringFromArray (strings, s);
  11902. }
  11903. const juce_wchar* StringPool::getPooledString (const juce_wchar* const s)
  11904. {
  11905. if (s == 0 || *s == 0)
  11906. return String::empty;
  11907. return StringPoolHelpers::getPooledStringFromArray (strings, s);
  11908. }
  11909. int StringPool::size() const throw()
  11910. {
  11911. return strings.size();
  11912. }
  11913. const juce_wchar* StringPool::operator[] (const int index) const throw()
  11914. {
  11915. return strings [index];
  11916. }
  11917. END_JUCE_NAMESPACE
  11918. /*** End of inlined file: juce_StringPool.cpp ***/
  11919. /*** Start of inlined file: juce_XmlDocument.cpp ***/
  11920. BEGIN_JUCE_NAMESPACE
  11921. XmlDocument::XmlDocument (const String& documentText)
  11922. : originalText (documentText),
  11923. ignoreEmptyTextElements (true)
  11924. {
  11925. }
  11926. XmlDocument::XmlDocument (const File& file)
  11927. : ignoreEmptyTextElements (true)
  11928. {
  11929. inputSource = new FileInputSource (file);
  11930. }
  11931. XmlDocument::~XmlDocument()
  11932. {
  11933. }
  11934. void XmlDocument::setInputSource (InputSource* const newSource) throw()
  11935. {
  11936. inputSource = newSource;
  11937. }
  11938. void XmlDocument::setEmptyTextElementsIgnored (const bool shouldBeIgnored) throw()
  11939. {
  11940. ignoreEmptyTextElements = shouldBeIgnored;
  11941. }
  11942. bool XmlDocument::isXmlIdentifierCharSlow (const juce_wchar c) throw()
  11943. {
  11944. return CharacterFunctions::isLetterOrDigit (c)
  11945. || c == '_' || c == '-' || c == ':' || c == '.';
  11946. }
  11947. inline bool XmlDocument::isXmlIdentifierChar (const juce_wchar c) const throw()
  11948. {
  11949. return (c > 0 && c <= 127) ? identifierLookupTable [(int) c]
  11950. : isXmlIdentifierCharSlow (c);
  11951. }
  11952. XmlElement* XmlDocument::getDocumentElement (const bool onlyReadOuterDocumentElement)
  11953. {
  11954. String textToParse (originalText);
  11955. if (textToParse.isEmpty() && inputSource != 0)
  11956. {
  11957. ScopedPointer <InputStream> in (inputSource->createInputStream());
  11958. if (in != 0)
  11959. {
  11960. MemoryOutputStream data;
  11961. data.writeFromInputStream (*in, onlyReadOuterDocumentElement ? 8192 : -1);
  11962. textToParse = data.toString();
  11963. if (! onlyReadOuterDocumentElement)
  11964. originalText = textToParse;
  11965. }
  11966. }
  11967. input = textToParse;
  11968. lastError = String::empty;
  11969. errorOccurred = false;
  11970. outOfData = false;
  11971. needToLoadDTD = true;
  11972. for (int i = 0; i < 128; ++i)
  11973. identifierLookupTable[i] = isXmlIdentifierCharSlow ((juce_wchar) i);
  11974. if (textToParse.isEmpty())
  11975. {
  11976. lastError = "not enough input";
  11977. }
  11978. else
  11979. {
  11980. skipHeader();
  11981. if (input != 0)
  11982. {
  11983. ScopedPointer <XmlElement> result (readNextElement (! onlyReadOuterDocumentElement));
  11984. if (! errorOccurred)
  11985. return result.release();
  11986. }
  11987. else
  11988. {
  11989. lastError = "incorrect xml header";
  11990. }
  11991. }
  11992. return 0;
  11993. }
  11994. const String& XmlDocument::getLastParseError() const throw()
  11995. {
  11996. return lastError;
  11997. }
  11998. void XmlDocument::setLastError (const String& desc, const bool carryOn)
  11999. {
  12000. lastError = desc;
  12001. errorOccurred = ! carryOn;
  12002. }
  12003. const String XmlDocument::getFileContents (const String& filename) const
  12004. {
  12005. if (inputSource != 0)
  12006. {
  12007. const ScopedPointer <InputStream> in (inputSource->createInputStreamFor (filename.trim().unquoted()));
  12008. if (in != 0)
  12009. return in->readEntireStreamAsString();
  12010. }
  12011. return String::empty;
  12012. }
  12013. juce_wchar XmlDocument::readNextChar() throw()
  12014. {
  12015. if (*input != 0)
  12016. {
  12017. return *input++;
  12018. }
  12019. else
  12020. {
  12021. outOfData = true;
  12022. return 0;
  12023. }
  12024. }
  12025. int XmlDocument::findNextTokenLength() throw()
  12026. {
  12027. int len = 0;
  12028. juce_wchar c = *input;
  12029. while (isXmlIdentifierChar (c))
  12030. c = input [++len];
  12031. return len;
  12032. }
  12033. void XmlDocument::skipHeader()
  12034. {
  12035. const juce_wchar* const found = CharacterFunctions::find (input, JUCE_T("<?xml"));
  12036. if (found != 0)
  12037. {
  12038. input = found;
  12039. input = CharacterFunctions::find (input, JUCE_T("?>"));
  12040. if (input == 0)
  12041. return;
  12042. input += 2;
  12043. }
  12044. skipNextWhiteSpace();
  12045. const juce_wchar* docType = CharacterFunctions::find (input, JUCE_T("<!DOCTYPE"));
  12046. if (docType == 0)
  12047. return;
  12048. input = docType + 9;
  12049. int n = 1;
  12050. while (n > 0)
  12051. {
  12052. const juce_wchar c = readNextChar();
  12053. if (outOfData)
  12054. return;
  12055. if (c == '<')
  12056. ++n;
  12057. else if (c == '>')
  12058. --n;
  12059. }
  12060. docType += 9;
  12061. dtdText = String (docType, (int) (input - (docType + 1))).trim();
  12062. }
  12063. void XmlDocument::skipNextWhiteSpace()
  12064. {
  12065. for (;;)
  12066. {
  12067. juce_wchar c = *input;
  12068. while (CharacterFunctions::isWhitespace (c))
  12069. c = *++input;
  12070. if (c == 0)
  12071. {
  12072. outOfData = true;
  12073. break;
  12074. }
  12075. else if (c == '<')
  12076. {
  12077. if (input[1] == '!'
  12078. && input[2] == '-'
  12079. && input[3] == '-')
  12080. {
  12081. const juce_wchar* const closeComment = CharacterFunctions::find (input, JUCE_T("-->"));
  12082. if (closeComment == 0)
  12083. {
  12084. outOfData = true;
  12085. break;
  12086. }
  12087. input = closeComment + 3;
  12088. continue;
  12089. }
  12090. else if (input[1] == '?')
  12091. {
  12092. const juce_wchar* const closeBracket = CharacterFunctions::find (input, JUCE_T("?>"));
  12093. if (closeBracket == 0)
  12094. {
  12095. outOfData = true;
  12096. break;
  12097. }
  12098. input = closeBracket + 2;
  12099. continue;
  12100. }
  12101. }
  12102. break;
  12103. }
  12104. }
  12105. void XmlDocument::readQuotedString (String& result)
  12106. {
  12107. const juce_wchar quote = readNextChar();
  12108. while (! outOfData)
  12109. {
  12110. const juce_wchar c = readNextChar();
  12111. if (c == quote)
  12112. break;
  12113. if (c == '&')
  12114. {
  12115. --input;
  12116. readEntity (result);
  12117. }
  12118. else
  12119. {
  12120. --input;
  12121. const juce_wchar* const start = input;
  12122. for (;;)
  12123. {
  12124. const juce_wchar character = *input;
  12125. if (character == quote)
  12126. {
  12127. result.append (start, (int) (input - start));
  12128. ++input;
  12129. return;
  12130. }
  12131. else if (character == '&')
  12132. {
  12133. result.append (start, (int) (input - start));
  12134. break;
  12135. }
  12136. else if (character == 0)
  12137. {
  12138. outOfData = true;
  12139. setLastError ("unmatched quotes", false);
  12140. break;
  12141. }
  12142. ++input;
  12143. }
  12144. }
  12145. }
  12146. }
  12147. XmlElement* XmlDocument::readNextElement (const bool alsoParseSubElements)
  12148. {
  12149. XmlElement* node = 0;
  12150. skipNextWhiteSpace();
  12151. if (outOfData)
  12152. return 0;
  12153. input = CharacterFunctions::find (input, JUCE_T("<"));
  12154. if (input != 0)
  12155. {
  12156. ++input;
  12157. int tagLen = findNextTokenLength();
  12158. if (tagLen == 0)
  12159. {
  12160. // no tag name - but allow for a gap after the '<' before giving an error
  12161. skipNextWhiteSpace();
  12162. tagLen = findNextTokenLength();
  12163. if (tagLen == 0)
  12164. {
  12165. setLastError ("tag name missing", false);
  12166. return node;
  12167. }
  12168. }
  12169. node = new XmlElement (String (input, tagLen));
  12170. input += tagLen;
  12171. XmlElement::XmlAttributeNode* lastAttribute = 0;
  12172. // look for attributes
  12173. for (;;)
  12174. {
  12175. skipNextWhiteSpace();
  12176. const juce_wchar c = *input;
  12177. // empty tag..
  12178. if (c == '/' && input[1] == '>')
  12179. {
  12180. input += 2;
  12181. break;
  12182. }
  12183. // parse the guts of the element..
  12184. if (c == '>')
  12185. {
  12186. ++input;
  12187. if (alsoParseSubElements)
  12188. readChildElements (node);
  12189. break;
  12190. }
  12191. // get an attribute..
  12192. if (isXmlIdentifierChar (c))
  12193. {
  12194. const int attNameLen = findNextTokenLength();
  12195. if (attNameLen > 0)
  12196. {
  12197. const juce_wchar* attNameStart = input;
  12198. input += attNameLen;
  12199. skipNextWhiteSpace();
  12200. if (readNextChar() == '=')
  12201. {
  12202. skipNextWhiteSpace();
  12203. const juce_wchar nextChar = *input;
  12204. if (nextChar == '"' || nextChar == '\'')
  12205. {
  12206. XmlElement::XmlAttributeNode* const newAtt
  12207. = new XmlElement::XmlAttributeNode (String (attNameStart, attNameLen),
  12208. String::empty);
  12209. readQuotedString (newAtt->value);
  12210. if (lastAttribute == 0)
  12211. node->attributes = newAtt;
  12212. else
  12213. lastAttribute->next = newAtt;
  12214. lastAttribute = newAtt;
  12215. continue;
  12216. }
  12217. }
  12218. }
  12219. }
  12220. else
  12221. {
  12222. if (! outOfData)
  12223. setLastError ("illegal character found in " + node->getTagName() + ": '" + c + "'", false);
  12224. }
  12225. break;
  12226. }
  12227. }
  12228. return node;
  12229. }
  12230. void XmlDocument::readChildElements (XmlElement* parent)
  12231. {
  12232. XmlElement* lastChildNode = 0;
  12233. for (;;)
  12234. {
  12235. const juce_wchar* const preWhitespaceInput = input;
  12236. skipNextWhiteSpace();
  12237. if (outOfData)
  12238. {
  12239. setLastError ("unmatched tags", false);
  12240. break;
  12241. }
  12242. if (*input == '<')
  12243. {
  12244. if (input[1] == '/')
  12245. {
  12246. // our close tag..
  12247. input = CharacterFunctions::find (input, JUCE_T(">"));
  12248. ++input;
  12249. break;
  12250. }
  12251. else if (input[1] == '!'
  12252. && input[2] == '['
  12253. && input[3] == 'C'
  12254. && input[4] == 'D'
  12255. && input[5] == 'A'
  12256. && input[6] == 'T'
  12257. && input[7] == 'A'
  12258. && input[8] == '[')
  12259. {
  12260. input += 9;
  12261. const juce_wchar* const inputStart = input;
  12262. int len = 0;
  12263. for (;;)
  12264. {
  12265. if (*input == 0)
  12266. {
  12267. setLastError ("unterminated CDATA section", false);
  12268. outOfData = true;
  12269. break;
  12270. }
  12271. else if (input[0] == ']'
  12272. && input[1] == ']'
  12273. && input[2] == '>')
  12274. {
  12275. input += 3;
  12276. break;
  12277. }
  12278. ++input;
  12279. ++len;
  12280. }
  12281. XmlElement* const e = XmlElement::createTextElement (String (inputStart, len));
  12282. if (lastChildNode != 0)
  12283. lastChildNode->nextElement = e;
  12284. else
  12285. parent->addChildElement (e);
  12286. lastChildNode = e;
  12287. }
  12288. else
  12289. {
  12290. // this is some other element, so parse and add it..
  12291. XmlElement* const n = readNextElement (true);
  12292. if (n != 0)
  12293. {
  12294. if (lastChildNode == 0)
  12295. parent->addChildElement (n);
  12296. else
  12297. lastChildNode->nextElement = n;
  12298. lastChildNode = n;
  12299. }
  12300. else
  12301. {
  12302. return;
  12303. }
  12304. }
  12305. }
  12306. else // must be a character block
  12307. {
  12308. input = preWhitespaceInput; // roll back to include the leading whitespace
  12309. String textElementContent;
  12310. for (;;)
  12311. {
  12312. const juce_wchar c = *input;
  12313. if (c == '<')
  12314. break;
  12315. if (c == 0)
  12316. {
  12317. setLastError ("unmatched tags", false);
  12318. outOfData = true;
  12319. return;
  12320. }
  12321. if (c == '&')
  12322. {
  12323. String entity;
  12324. readEntity (entity);
  12325. if (entity.startsWithChar ('<') && entity [1] != 0)
  12326. {
  12327. const juce_wchar* const oldInput = input;
  12328. const bool oldOutOfData = outOfData;
  12329. input = entity;
  12330. outOfData = false;
  12331. for (;;)
  12332. {
  12333. XmlElement* const n = readNextElement (true);
  12334. if (n == 0)
  12335. break;
  12336. if (lastChildNode == 0)
  12337. parent->addChildElement (n);
  12338. else
  12339. lastChildNode->nextElement = n;
  12340. lastChildNode = n;
  12341. }
  12342. input = oldInput;
  12343. outOfData = oldOutOfData;
  12344. }
  12345. else
  12346. {
  12347. textElementContent += entity;
  12348. }
  12349. }
  12350. else
  12351. {
  12352. const juce_wchar* start = input;
  12353. int len = 0;
  12354. for (;;)
  12355. {
  12356. const juce_wchar nextChar = *input;
  12357. if (nextChar == '<' || nextChar == '&')
  12358. {
  12359. break;
  12360. }
  12361. else if (nextChar == 0)
  12362. {
  12363. setLastError ("unmatched tags", false);
  12364. outOfData = true;
  12365. return;
  12366. }
  12367. ++input;
  12368. ++len;
  12369. }
  12370. textElementContent.append (start, len);
  12371. }
  12372. }
  12373. if ((! ignoreEmptyTextElements) || textElementContent.containsNonWhitespaceChars())
  12374. {
  12375. XmlElement* const textElement = XmlElement::createTextElement (textElementContent);
  12376. if (lastChildNode != 0)
  12377. lastChildNode->nextElement = textElement;
  12378. else
  12379. parent->addChildElement (textElement);
  12380. lastChildNode = textElement;
  12381. }
  12382. }
  12383. }
  12384. }
  12385. void XmlDocument::readEntity (String& result)
  12386. {
  12387. // skip over the ampersand
  12388. ++input;
  12389. if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("amp;"), 4) == 0)
  12390. {
  12391. input += 4;
  12392. result += '&';
  12393. }
  12394. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("quot;"), 5) == 0)
  12395. {
  12396. input += 5;
  12397. result += '"';
  12398. }
  12399. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("apos;"), 5) == 0)
  12400. {
  12401. input += 5;
  12402. result += '\'';
  12403. }
  12404. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("lt;"), 3) == 0)
  12405. {
  12406. input += 3;
  12407. result += '<';
  12408. }
  12409. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("gt;"), 3) == 0)
  12410. {
  12411. input += 3;
  12412. result += '>';
  12413. }
  12414. else if (*input == '#')
  12415. {
  12416. int charCode = 0;
  12417. ++input;
  12418. if (*input == 'x' || *input == 'X')
  12419. {
  12420. ++input;
  12421. int numChars = 0;
  12422. while (input[0] != ';')
  12423. {
  12424. const int hexValue = CharacterFunctions::getHexDigitValue (input[0]);
  12425. if (hexValue < 0 || ++numChars > 8)
  12426. {
  12427. setLastError ("illegal escape sequence", true);
  12428. break;
  12429. }
  12430. charCode = (charCode << 4) | hexValue;
  12431. ++input;
  12432. }
  12433. ++input;
  12434. }
  12435. else if (input[0] >= '0' && input[0] <= '9')
  12436. {
  12437. int numChars = 0;
  12438. while (input[0] != ';')
  12439. {
  12440. if (++numChars > 12)
  12441. {
  12442. setLastError ("illegal escape sequence", true);
  12443. break;
  12444. }
  12445. charCode = charCode * 10 + (input[0] - '0');
  12446. ++input;
  12447. }
  12448. ++input;
  12449. }
  12450. else
  12451. {
  12452. setLastError ("illegal escape sequence", true);
  12453. result += '&';
  12454. return;
  12455. }
  12456. result << (juce_wchar) charCode;
  12457. }
  12458. else
  12459. {
  12460. const juce_wchar* const entityNameStart = input;
  12461. const juce_wchar* const closingSemiColon = CharacterFunctions::find (input, JUCE_T(";"));
  12462. if (closingSemiColon == 0)
  12463. {
  12464. outOfData = true;
  12465. result += '&';
  12466. }
  12467. else
  12468. {
  12469. input = closingSemiColon + 1;
  12470. result += expandExternalEntity (String (entityNameStart,
  12471. (int) (closingSemiColon - entityNameStart)));
  12472. }
  12473. }
  12474. }
  12475. const String XmlDocument::expandEntity (const String& ent)
  12476. {
  12477. if (ent.equalsIgnoreCase ("amp"))
  12478. return String::charToString ('&');
  12479. if (ent.equalsIgnoreCase ("quot"))
  12480. return String::charToString ('"');
  12481. if (ent.equalsIgnoreCase ("apos"))
  12482. return String::charToString ('\'');
  12483. if (ent.equalsIgnoreCase ("lt"))
  12484. return String::charToString ('<');
  12485. if (ent.equalsIgnoreCase ("gt"))
  12486. return String::charToString ('>');
  12487. if (ent[0] == '#')
  12488. {
  12489. if (ent[1] == 'x' || ent[1] == 'X')
  12490. return String::charToString (static_cast <juce_wchar> (ent.substring (2).getHexValue32()));
  12491. if (ent[1] >= '0' && ent[1] <= '9')
  12492. return String::charToString (static_cast <juce_wchar> (ent.substring (1).getIntValue()));
  12493. setLastError ("illegal escape sequence", false);
  12494. return String::charToString ('&');
  12495. }
  12496. return expandExternalEntity (ent);
  12497. }
  12498. const String XmlDocument::expandExternalEntity (const String& entity)
  12499. {
  12500. if (needToLoadDTD)
  12501. {
  12502. if (dtdText.isNotEmpty())
  12503. {
  12504. dtdText = dtdText.trimCharactersAtEnd (">");
  12505. tokenisedDTD.addTokens (dtdText, true);
  12506. if (tokenisedDTD [tokenisedDTD.size() - 2].equalsIgnoreCase ("system")
  12507. && tokenisedDTD [tokenisedDTD.size() - 1].isQuotedString())
  12508. {
  12509. const String fn (tokenisedDTD [tokenisedDTD.size() - 1]);
  12510. tokenisedDTD.clear();
  12511. tokenisedDTD.addTokens (getFileContents (fn), true);
  12512. }
  12513. else
  12514. {
  12515. tokenisedDTD.clear();
  12516. const int openBracket = dtdText.indexOfChar ('[');
  12517. if (openBracket > 0)
  12518. {
  12519. const int closeBracket = dtdText.lastIndexOfChar (']');
  12520. if (closeBracket > openBracket)
  12521. tokenisedDTD.addTokens (dtdText.substring (openBracket + 1,
  12522. closeBracket), true);
  12523. }
  12524. }
  12525. for (int i = tokenisedDTD.size(); --i >= 0;)
  12526. {
  12527. if (tokenisedDTD[i].startsWithChar ('%')
  12528. && tokenisedDTD[i].endsWithChar (';'))
  12529. {
  12530. const String parsed (getParameterEntity (tokenisedDTD[i].substring (1, tokenisedDTD[i].length() - 1)));
  12531. StringArray newToks;
  12532. newToks.addTokens (parsed, true);
  12533. tokenisedDTD.remove (i);
  12534. for (int j = newToks.size(); --j >= 0;)
  12535. tokenisedDTD.insert (i, newToks[j]);
  12536. }
  12537. }
  12538. }
  12539. needToLoadDTD = false;
  12540. }
  12541. for (int i = 0; i < tokenisedDTD.size(); ++i)
  12542. {
  12543. if (tokenisedDTD[i] == entity)
  12544. {
  12545. if (tokenisedDTD[i - 1].equalsIgnoreCase ("<!entity"))
  12546. {
  12547. String ent (tokenisedDTD [i + 1].trimCharactersAtEnd (">").trim().unquoted());
  12548. // check for sub-entities..
  12549. int ampersand = ent.indexOfChar ('&');
  12550. while (ampersand >= 0)
  12551. {
  12552. const int semiColon = ent.indexOf (i + 1, ";");
  12553. if (semiColon < 0)
  12554. {
  12555. setLastError ("entity without terminating semi-colon", false);
  12556. break;
  12557. }
  12558. const String resolved (expandEntity (ent.substring (i + 1, semiColon)));
  12559. ent = ent.substring (0, ampersand)
  12560. + resolved
  12561. + ent.substring (semiColon + 1);
  12562. ampersand = ent.indexOfChar (semiColon + 1, '&');
  12563. }
  12564. return ent;
  12565. }
  12566. }
  12567. }
  12568. setLastError ("unknown entity", true);
  12569. return entity;
  12570. }
  12571. const String XmlDocument::getParameterEntity (const String& entity)
  12572. {
  12573. for (int i = 0; i < tokenisedDTD.size(); ++i)
  12574. {
  12575. if (tokenisedDTD[i] == entity)
  12576. {
  12577. if (tokenisedDTD [i - 1] == "%"
  12578. && tokenisedDTD [i - 2].equalsIgnoreCase ("<!entity"))
  12579. {
  12580. const String ent (tokenisedDTD [i + 1].trimCharactersAtEnd (">"));
  12581. if (ent.equalsIgnoreCase ("system"))
  12582. return getFileContents (tokenisedDTD [i + 2].trimCharactersAtEnd (">"));
  12583. else
  12584. return ent.trim().unquoted();
  12585. }
  12586. }
  12587. }
  12588. return entity;
  12589. }
  12590. END_JUCE_NAMESPACE
  12591. /*** End of inlined file: juce_XmlDocument.cpp ***/
  12592. /*** Start of inlined file: juce_XmlElement.cpp ***/
  12593. BEGIN_JUCE_NAMESPACE
  12594. XmlElement::XmlAttributeNode::XmlAttributeNode (const XmlAttributeNode& other) throw()
  12595. : name (other.name),
  12596. value (other.value),
  12597. next (0)
  12598. {
  12599. }
  12600. XmlElement::XmlAttributeNode::XmlAttributeNode (const String& name_, const String& value_) throw()
  12601. : name (name_),
  12602. value (value_),
  12603. next (0)
  12604. {
  12605. }
  12606. XmlElement::XmlElement (const String& tagName_) throw()
  12607. : tagName (tagName_),
  12608. firstChildElement (0),
  12609. nextElement (0),
  12610. attributes (0)
  12611. {
  12612. // the tag name mustn't be empty, or it'll look like a text element!
  12613. jassert (tagName_.containsNonWhitespaceChars())
  12614. // The tag can't contain spaces or other characters that would create invalid XML!
  12615. jassert (! tagName_.containsAnyOf (" <>/&"));
  12616. }
  12617. XmlElement::XmlElement (int /*dummy*/) throw()
  12618. : firstChildElement (0),
  12619. nextElement (0),
  12620. attributes (0)
  12621. {
  12622. }
  12623. XmlElement::XmlElement (const XmlElement& other)
  12624. : tagName (other.tagName),
  12625. firstChildElement (0),
  12626. nextElement (0),
  12627. attributes (0)
  12628. {
  12629. copyChildrenAndAttributesFrom (other);
  12630. }
  12631. XmlElement& XmlElement::operator= (const XmlElement& other)
  12632. {
  12633. if (this != &other)
  12634. {
  12635. removeAllAttributes();
  12636. deleteAllChildElements();
  12637. tagName = other.tagName;
  12638. copyChildrenAndAttributesFrom (other);
  12639. }
  12640. return *this;
  12641. }
  12642. void XmlElement::copyChildrenAndAttributesFrom (const XmlElement& other)
  12643. {
  12644. XmlElement* child = other.firstChildElement;
  12645. XmlElement* lastChild = 0;
  12646. while (child != 0)
  12647. {
  12648. XmlElement* const copiedChild = new XmlElement (*child);
  12649. if (lastChild != 0)
  12650. lastChild->nextElement = copiedChild;
  12651. else
  12652. firstChildElement = copiedChild;
  12653. lastChild = copiedChild;
  12654. child = child->nextElement;
  12655. }
  12656. const XmlAttributeNode* att = other.attributes;
  12657. XmlAttributeNode* lastAtt = 0;
  12658. while (att != 0)
  12659. {
  12660. XmlAttributeNode* const newAtt = new XmlAttributeNode (*att);
  12661. if (lastAtt != 0)
  12662. lastAtt->next = newAtt;
  12663. else
  12664. attributes = newAtt;
  12665. lastAtt = newAtt;
  12666. att = att->next;
  12667. }
  12668. }
  12669. XmlElement::~XmlElement() throw()
  12670. {
  12671. XmlElement* child = firstChildElement;
  12672. while (child != 0)
  12673. {
  12674. XmlElement* const nextChild = child->nextElement;
  12675. delete child;
  12676. child = nextChild;
  12677. }
  12678. XmlAttributeNode* att = attributes;
  12679. while (att != 0)
  12680. {
  12681. XmlAttributeNode* const nextAtt = att->next;
  12682. delete att;
  12683. att = nextAtt;
  12684. }
  12685. }
  12686. namespace XmlOutputFunctions
  12687. {
  12688. /*static bool isLegalXmlCharSlow (const juce_wchar character) throw()
  12689. {
  12690. if ((character >= 'a' && character <= 'z')
  12691. || (character >= 'A' && character <= 'Z')
  12692. || (character >= '0' && character <= '9'))
  12693. return true;
  12694. const char* t = " .,;:-()_+=?!'#@[]/\\*%~{}$|";
  12695. do
  12696. {
  12697. if (((juce_wchar) (uint8) *t) == character)
  12698. return true;
  12699. }
  12700. while (*++t != 0);
  12701. return false;
  12702. }
  12703. static void generateLegalCharConstants()
  12704. {
  12705. uint8 n[32];
  12706. zerostruct (n);
  12707. for (int i = 0; i < 256; ++i)
  12708. if (isLegalXmlCharSlow (i))
  12709. n[i >> 3] |= (1 << (i & 7));
  12710. String s;
  12711. for (int i = 0; i < 32; ++i)
  12712. s << (int) n[i] << ", ";
  12713. DBG (s);
  12714. }*/
  12715. static bool isLegalXmlChar (const uint32 c) throw()
  12716. {
  12717. static const unsigned char legalChars[] = { 0, 0, 0, 0, 187, 255, 255, 175, 255, 255, 255, 191, 254, 255, 255, 127 };
  12718. return c < sizeof (legalChars) * 8
  12719. && (legalChars [c >> 3] & (1 << (c & 7))) != 0;
  12720. }
  12721. static void escapeIllegalXmlChars (OutputStream& outputStream, const String& text, const bool changeNewLines)
  12722. {
  12723. const juce_wchar* t = text;
  12724. for (;;)
  12725. {
  12726. const juce_wchar character = *t++;
  12727. if (character == 0)
  12728. break;
  12729. if (isLegalXmlChar ((uint32) character))
  12730. {
  12731. outputStream << (char) character;
  12732. }
  12733. else
  12734. {
  12735. switch (character)
  12736. {
  12737. case '&': outputStream << "&amp;"; break;
  12738. case '"': outputStream << "&quot;"; break;
  12739. case '>': outputStream << "&gt;"; break;
  12740. case '<': outputStream << "&lt;"; break;
  12741. case '\n':
  12742. if (changeNewLines)
  12743. outputStream << "&#10;";
  12744. else
  12745. outputStream << (char) character;
  12746. break;
  12747. case '\r':
  12748. if (changeNewLines)
  12749. outputStream << "&#13;";
  12750. else
  12751. outputStream << (char) character;
  12752. break;
  12753. default:
  12754. outputStream << "&#" << ((int) (unsigned int) character) << ';';
  12755. break;
  12756. }
  12757. }
  12758. }
  12759. }
  12760. static void writeSpaces (OutputStream& out, int numSpaces)
  12761. {
  12762. if (numSpaces > 0)
  12763. {
  12764. const char blanks[] = " ";
  12765. const int blankSize = (int) numElementsInArray (blanks) - 1;
  12766. while (numSpaces > blankSize)
  12767. {
  12768. out.write (blanks, blankSize);
  12769. numSpaces -= blankSize;
  12770. }
  12771. out.write (blanks, numSpaces);
  12772. }
  12773. }
  12774. static void writeNewLine (OutputStream& out)
  12775. {
  12776. out.write ("\r\n", 2);
  12777. }
  12778. }
  12779. void XmlElement::writeElementAsText (OutputStream& outputStream,
  12780. const int indentationLevel,
  12781. const int lineWrapLength) const
  12782. {
  12783. using namespace XmlOutputFunctions;
  12784. writeSpaces (outputStream, indentationLevel);
  12785. if (! isTextElement())
  12786. {
  12787. outputStream.writeByte ('<');
  12788. outputStream << tagName;
  12789. {
  12790. const int attIndent = indentationLevel + tagName.length() + 1;
  12791. int lineLen = 0;
  12792. const XmlAttributeNode* att = attributes;
  12793. while (att != 0)
  12794. {
  12795. if (lineLen > lineWrapLength && indentationLevel >= 0)
  12796. {
  12797. writeNewLine (outputStream);
  12798. writeSpaces (outputStream, attIndent);
  12799. lineLen = 0;
  12800. }
  12801. const int64 startPos = outputStream.getPosition();
  12802. outputStream.writeByte (' ');
  12803. outputStream << att->name;
  12804. outputStream.write ("=\"", 2);
  12805. escapeIllegalXmlChars (outputStream, att->value, true);
  12806. outputStream.writeByte ('"');
  12807. lineLen += (int) (outputStream.getPosition() - startPos);
  12808. att = att->next;
  12809. }
  12810. }
  12811. if (firstChildElement != 0)
  12812. {
  12813. outputStream.writeByte ('>');
  12814. XmlElement* child = firstChildElement;
  12815. bool lastWasTextNode = false;
  12816. while (child != 0)
  12817. {
  12818. if (child->isTextElement())
  12819. {
  12820. escapeIllegalXmlChars (outputStream, child->getText(), false);
  12821. lastWasTextNode = true;
  12822. }
  12823. else
  12824. {
  12825. if (indentationLevel >= 0 && ! lastWasTextNode)
  12826. writeNewLine (outputStream);
  12827. child->writeElementAsText (outputStream,
  12828. lastWasTextNode ? 0 : (indentationLevel + (indentationLevel >= 0 ? 2 : 0)), lineWrapLength);
  12829. lastWasTextNode = false;
  12830. }
  12831. child = child->nextElement;
  12832. }
  12833. if (indentationLevel >= 0 && ! lastWasTextNode)
  12834. {
  12835. writeNewLine (outputStream);
  12836. writeSpaces (outputStream, indentationLevel);
  12837. }
  12838. outputStream.write ("</", 2);
  12839. outputStream << tagName;
  12840. outputStream.writeByte ('>');
  12841. }
  12842. else
  12843. {
  12844. outputStream.write ("/>", 2);
  12845. }
  12846. }
  12847. else
  12848. {
  12849. escapeIllegalXmlChars (outputStream, getText(), false);
  12850. }
  12851. }
  12852. const String XmlElement::createDocument (const String& dtdToUse,
  12853. const bool allOnOneLine,
  12854. const bool includeXmlHeader,
  12855. const String& encodingType,
  12856. const int lineWrapLength) const
  12857. {
  12858. MemoryOutputStream mem (2048);
  12859. writeToStream (mem, dtdToUse, allOnOneLine, includeXmlHeader, encodingType, lineWrapLength);
  12860. return mem.toUTF8();
  12861. }
  12862. void XmlElement::writeToStream (OutputStream& output,
  12863. const String& dtdToUse,
  12864. const bool allOnOneLine,
  12865. const bool includeXmlHeader,
  12866. const String& encodingType,
  12867. const int lineWrapLength) const
  12868. {
  12869. using namespace XmlOutputFunctions;
  12870. if (includeXmlHeader)
  12871. {
  12872. output << "<?xml version=\"1.0\" encoding=\"" << encodingType << "\"?>";
  12873. if (allOnOneLine)
  12874. {
  12875. output.writeByte (' ');
  12876. }
  12877. else
  12878. {
  12879. writeNewLine (output);
  12880. writeNewLine (output);
  12881. }
  12882. }
  12883. if (dtdToUse.isNotEmpty())
  12884. {
  12885. output << dtdToUse;
  12886. if (allOnOneLine)
  12887. output.writeByte (' ');
  12888. else
  12889. writeNewLine (output);
  12890. }
  12891. writeElementAsText (output, allOnOneLine ? -1 : 0, lineWrapLength);
  12892. if (! allOnOneLine)
  12893. writeNewLine (output);
  12894. }
  12895. bool XmlElement::writeToFile (const File& file,
  12896. const String& dtdToUse,
  12897. const String& encodingType,
  12898. const int lineWrapLength) const
  12899. {
  12900. if (file.hasWriteAccess())
  12901. {
  12902. TemporaryFile tempFile (file);
  12903. ScopedPointer <FileOutputStream> out (tempFile.getFile().createOutputStream());
  12904. if (out != 0)
  12905. {
  12906. writeToStream (*out, dtdToUse, false, true, encodingType, lineWrapLength);
  12907. out = 0;
  12908. return tempFile.overwriteTargetFileWithTemporary();
  12909. }
  12910. }
  12911. return false;
  12912. }
  12913. bool XmlElement::hasTagName (const String& tagNameWanted) const throw()
  12914. {
  12915. #if JUCE_DEBUG
  12916. // if debugging, check that the case is actually the same, because
  12917. // valid xml is case-sensitive, and although this lets it pass, it's
  12918. // better not to..
  12919. if (tagName.equalsIgnoreCase (tagNameWanted))
  12920. {
  12921. jassert (tagName == tagNameWanted);
  12922. return true;
  12923. }
  12924. else
  12925. {
  12926. return false;
  12927. }
  12928. #else
  12929. return tagName.equalsIgnoreCase (tagNameWanted);
  12930. #endif
  12931. }
  12932. XmlElement* XmlElement::getNextElementWithTagName (const String& requiredTagName) const
  12933. {
  12934. XmlElement* e = nextElement;
  12935. while (e != 0 && ! e->hasTagName (requiredTagName))
  12936. e = e->nextElement;
  12937. return e;
  12938. }
  12939. int XmlElement::getNumAttributes() const throw()
  12940. {
  12941. const XmlAttributeNode* att = attributes;
  12942. int count = 0;
  12943. while (att != 0)
  12944. {
  12945. att = att->next;
  12946. ++count;
  12947. }
  12948. return count;
  12949. }
  12950. const String& XmlElement::getAttributeName (const int index) const throw()
  12951. {
  12952. const XmlAttributeNode* att = attributes;
  12953. int count = 0;
  12954. while (att != 0)
  12955. {
  12956. if (count == index)
  12957. return att->name;
  12958. att = att->next;
  12959. ++count;
  12960. }
  12961. return String::empty;
  12962. }
  12963. const String& XmlElement::getAttributeValue (const int index) const throw()
  12964. {
  12965. const XmlAttributeNode* att = attributes;
  12966. int count = 0;
  12967. while (att != 0)
  12968. {
  12969. if (count == index)
  12970. return att->value;
  12971. att = att->next;
  12972. ++count;
  12973. }
  12974. return String::empty;
  12975. }
  12976. bool XmlElement::hasAttribute (const String& attributeName) const throw()
  12977. {
  12978. const XmlAttributeNode* att = attributes;
  12979. while (att != 0)
  12980. {
  12981. if (att->name.equalsIgnoreCase (attributeName))
  12982. return true;
  12983. att = att->next;
  12984. }
  12985. return false;
  12986. }
  12987. const String& XmlElement::getStringAttribute (const String& attributeName) const throw()
  12988. {
  12989. const XmlAttributeNode* att = attributes;
  12990. while (att != 0)
  12991. {
  12992. if (att->name.equalsIgnoreCase (attributeName))
  12993. return att->value;
  12994. att = att->next;
  12995. }
  12996. return String::empty;
  12997. }
  12998. const String XmlElement::getStringAttribute (const String& attributeName, const String& defaultReturnValue) const
  12999. {
  13000. const XmlAttributeNode* att = attributes;
  13001. while (att != 0)
  13002. {
  13003. if (att->name.equalsIgnoreCase (attributeName))
  13004. return att->value;
  13005. att = att->next;
  13006. }
  13007. return defaultReturnValue;
  13008. }
  13009. int XmlElement::getIntAttribute (const String& attributeName, const int defaultReturnValue) const
  13010. {
  13011. const XmlAttributeNode* att = attributes;
  13012. while (att != 0)
  13013. {
  13014. if (att->name.equalsIgnoreCase (attributeName))
  13015. return att->value.getIntValue();
  13016. att = att->next;
  13017. }
  13018. return defaultReturnValue;
  13019. }
  13020. double XmlElement::getDoubleAttribute (const String& attributeName, const double defaultReturnValue) const
  13021. {
  13022. const XmlAttributeNode* att = attributes;
  13023. while (att != 0)
  13024. {
  13025. if (att->name.equalsIgnoreCase (attributeName))
  13026. return att->value.getDoubleValue();
  13027. att = att->next;
  13028. }
  13029. return defaultReturnValue;
  13030. }
  13031. bool XmlElement::getBoolAttribute (const String& attributeName, const bool defaultReturnValue) const
  13032. {
  13033. const XmlAttributeNode* att = attributes;
  13034. while (att != 0)
  13035. {
  13036. if (att->name.equalsIgnoreCase (attributeName))
  13037. {
  13038. juce_wchar firstChar = att->value[0];
  13039. if (CharacterFunctions::isWhitespace (firstChar))
  13040. firstChar = att->value.trimStart() [0];
  13041. return firstChar == '1'
  13042. || firstChar == 't'
  13043. || firstChar == 'y'
  13044. || firstChar == 'T'
  13045. || firstChar == 'Y';
  13046. }
  13047. att = att->next;
  13048. }
  13049. return defaultReturnValue;
  13050. }
  13051. bool XmlElement::compareAttribute (const String& attributeName,
  13052. const String& stringToCompareAgainst,
  13053. const bool ignoreCase) const throw()
  13054. {
  13055. const XmlAttributeNode* att = attributes;
  13056. while (att != 0)
  13057. {
  13058. if (att->name.equalsIgnoreCase (attributeName))
  13059. {
  13060. if (ignoreCase)
  13061. return att->value.equalsIgnoreCase (stringToCompareAgainst);
  13062. else
  13063. return att->value == stringToCompareAgainst;
  13064. }
  13065. att = att->next;
  13066. }
  13067. return false;
  13068. }
  13069. void XmlElement::setAttribute (const String& attributeName, const String& value)
  13070. {
  13071. #if JUCE_DEBUG
  13072. // check the identifier being passed in is legal..
  13073. const juce_wchar* t = attributeName;
  13074. while (*t != 0)
  13075. {
  13076. jassert (CharacterFunctions::isLetterOrDigit (*t)
  13077. || *t == '_'
  13078. || *t == '-'
  13079. || *t == ':');
  13080. ++t;
  13081. }
  13082. #endif
  13083. if (attributes == 0)
  13084. {
  13085. attributes = new XmlAttributeNode (attributeName, value);
  13086. }
  13087. else
  13088. {
  13089. XmlAttributeNode* att = attributes;
  13090. for (;;)
  13091. {
  13092. if (att->name.equalsIgnoreCase (attributeName))
  13093. {
  13094. att->value = value;
  13095. break;
  13096. }
  13097. else if (att->next == 0)
  13098. {
  13099. att->next = new XmlAttributeNode (attributeName, value);
  13100. break;
  13101. }
  13102. att = att->next;
  13103. }
  13104. }
  13105. }
  13106. void XmlElement::setAttribute (const String& attributeName, const int number)
  13107. {
  13108. setAttribute (attributeName, String (number));
  13109. }
  13110. void XmlElement::setAttribute (const String& attributeName, const double number)
  13111. {
  13112. setAttribute (attributeName, String (number));
  13113. }
  13114. void XmlElement::removeAttribute (const String& attributeName) throw()
  13115. {
  13116. XmlAttributeNode* att = attributes;
  13117. XmlAttributeNode* lastAtt = 0;
  13118. while (att != 0)
  13119. {
  13120. if (att->name.equalsIgnoreCase (attributeName))
  13121. {
  13122. if (lastAtt == 0)
  13123. attributes = att->next;
  13124. else
  13125. lastAtt->next = att->next;
  13126. delete att;
  13127. break;
  13128. }
  13129. lastAtt = att;
  13130. att = att->next;
  13131. }
  13132. }
  13133. void XmlElement::removeAllAttributes() throw()
  13134. {
  13135. while (attributes != 0)
  13136. {
  13137. XmlAttributeNode* const nextAtt = attributes->next;
  13138. delete attributes;
  13139. attributes = nextAtt;
  13140. }
  13141. }
  13142. int XmlElement::getNumChildElements() const throw()
  13143. {
  13144. int count = 0;
  13145. const XmlElement* child = firstChildElement;
  13146. while (child != 0)
  13147. {
  13148. ++count;
  13149. child = child->nextElement;
  13150. }
  13151. return count;
  13152. }
  13153. XmlElement* XmlElement::getChildElement (const int index) const throw()
  13154. {
  13155. int count = 0;
  13156. XmlElement* child = firstChildElement;
  13157. while (child != 0 && count < index)
  13158. {
  13159. child = child->nextElement;
  13160. ++count;
  13161. }
  13162. return child;
  13163. }
  13164. XmlElement* XmlElement::getChildByName (const String& childName) const throw()
  13165. {
  13166. XmlElement* child = firstChildElement;
  13167. while (child != 0)
  13168. {
  13169. if (child->hasTagName (childName))
  13170. break;
  13171. child = child->nextElement;
  13172. }
  13173. return child;
  13174. }
  13175. void XmlElement::addChildElement (XmlElement* const newNode) throw()
  13176. {
  13177. if (newNode != 0)
  13178. {
  13179. if (firstChildElement == 0)
  13180. {
  13181. firstChildElement = newNode;
  13182. }
  13183. else
  13184. {
  13185. XmlElement* child = firstChildElement;
  13186. while (child->nextElement != 0)
  13187. child = child->nextElement;
  13188. child->nextElement = newNode;
  13189. // if this is non-zero, then something's probably
  13190. // gone wrong..
  13191. jassert (newNode->nextElement == 0);
  13192. }
  13193. }
  13194. }
  13195. void XmlElement::insertChildElement (XmlElement* const newNode,
  13196. int indexToInsertAt) throw()
  13197. {
  13198. if (newNode != 0)
  13199. {
  13200. removeChildElement (newNode, false);
  13201. if (indexToInsertAt == 0)
  13202. {
  13203. newNode->nextElement = firstChildElement;
  13204. firstChildElement = newNode;
  13205. }
  13206. else
  13207. {
  13208. if (firstChildElement == 0)
  13209. {
  13210. firstChildElement = newNode;
  13211. }
  13212. else
  13213. {
  13214. if (indexToInsertAt < 0)
  13215. indexToInsertAt = std::numeric_limits<int>::max();
  13216. XmlElement* child = firstChildElement;
  13217. while (child->nextElement != 0 && --indexToInsertAt > 0)
  13218. child = child->nextElement;
  13219. newNode->nextElement = child->nextElement;
  13220. child->nextElement = newNode;
  13221. }
  13222. }
  13223. }
  13224. }
  13225. XmlElement* XmlElement::createNewChildElement (const String& childTagName)
  13226. {
  13227. XmlElement* const newElement = new XmlElement (childTagName);
  13228. addChildElement (newElement);
  13229. return newElement;
  13230. }
  13231. bool XmlElement::replaceChildElement (XmlElement* const currentChildElement,
  13232. XmlElement* const newNode) throw()
  13233. {
  13234. if (newNode != 0)
  13235. {
  13236. XmlElement* child = firstChildElement;
  13237. XmlElement* previousNode = 0;
  13238. while (child != 0)
  13239. {
  13240. if (child == currentChildElement)
  13241. {
  13242. if (child != newNode)
  13243. {
  13244. if (previousNode == 0)
  13245. firstChildElement = newNode;
  13246. else
  13247. previousNode->nextElement = newNode;
  13248. newNode->nextElement = child->nextElement;
  13249. delete child;
  13250. }
  13251. return true;
  13252. }
  13253. previousNode = child;
  13254. child = child->nextElement;
  13255. }
  13256. }
  13257. return false;
  13258. }
  13259. void XmlElement::removeChildElement (XmlElement* const childToRemove,
  13260. const bool shouldDeleteTheChild) throw()
  13261. {
  13262. if (childToRemove != 0)
  13263. {
  13264. if (firstChildElement == childToRemove)
  13265. {
  13266. firstChildElement = childToRemove->nextElement;
  13267. childToRemove->nextElement = 0;
  13268. }
  13269. else
  13270. {
  13271. XmlElement* child = firstChildElement;
  13272. XmlElement* last = 0;
  13273. while (child != 0)
  13274. {
  13275. if (child == childToRemove)
  13276. {
  13277. if (last == 0)
  13278. firstChildElement = child->nextElement;
  13279. else
  13280. last->nextElement = child->nextElement;
  13281. childToRemove->nextElement = 0;
  13282. break;
  13283. }
  13284. last = child;
  13285. child = child->nextElement;
  13286. }
  13287. }
  13288. if (shouldDeleteTheChild)
  13289. delete childToRemove;
  13290. }
  13291. }
  13292. bool XmlElement::isEquivalentTo (const XmlElement* const other,
  13293. const bool ignoreOrderOfAttributes) const throw()
  13294. {
  13295. if (this != other)
  13296. {
  13297. if (other == 0 || tagName != other->tagName)
  13298. return false;
  13299. if (ignoreOrderOfAttributes)
  13300. {
  13301. int totalAtts = 0;
  13302. const XmlAttributeNode* att = attributes;
  13303. while (att != 0)
  13304. {
  13305. if (! other->compareAttribute (att->name, att->value))
  13306. return false;
  13307. att = att->next;
  13308. ++totalAtts;
  13309. }
  13310. if (totalAtts != other->getNumAttributes())
  13311. return false;
  13312. }
  13313. else
  13314. {
  13315. const XmlAttributeNode* thisAtt = attributes;
  13316. const XmlAttributeNode* otherAtt = other->attributes;
  13317. for (;;)
  13318. {
  13319. if (thisAtt == 0 || otherAtt == 0)
  13320. {
  13321. if (thisAtt == otherAtt) // both 0, so it's a match
  13322. break;
  13323. return false;
  13324. }
  13325. if (thisAtt->name != otherAtt->name
  13326. || thisAtt->value != otherAtt->value)
  13327. {
  13328. return false;
  13329. }
  13330. thisAtt = thisAtt->next;
  13331. otherAtt = otherAtt->next;
  13332. }
  13333. }
  13334. const XmlElement* thisChild = firstChildElement;
  13335. const XmlElement* otherChild = other->firstChildElement;
  13336. for (;;)
  13337. {
  13338. if (thisChild == 0 || otherChild == 0)
  13339. {
  13340. if (thisChild == otherChild) // both 0, so it's a match
  13341. break;
  13342. return false;
  13343. }
  13344. if (! thisChild->isEquivalentTo (otherChild, ignoreOrderOfAttributes))
  13345. return false;
  13346. thisChild = thisChild->nextElement;
  13347. otherChild = otherChild->nextElement;
  13348. }
  13349. }
  13350. return true;
  13351. }
  13352. void XmlElement::deleteAllChildElements() throw()
  13353. {
  13354. while (firstChildElement != 0)
  13355. {
  13356. XmlElement* const nextChild = firstChildElement->nextElement;
  13357. delete firstChildElement;
  13358. firstChildElement = nextChild;
  13359. }
  13360. }
  13361. void XmlElement::deleteAllChildElementsWithTagName (const String& name) throw()
  13362. {
  13363. XmlElement* child = firstChildElement;
  13364. while (child != 0)
  13365. {
  13366. if (child->hasTagName (name))
  13367. {
  13368. XmlElement* const nextChild = child->nextElement;
  13369. removeChildElement (child, true);
  13370. child = nextChild;
  13371. }
  13372. else
  13373. {
  13374. child = child->nextElement;
  13375. }
  13376. }
  13377. }
  13378. bool XmlElement::containsChildElement (const XmlElement* const possibleChild) const throw()
  13379. {
  13380. const XmlElement* child = firstChildElement;
  13381. while (child != 0)
  13382. {
  13383. if (child == possibleChild)
  13384. return true;
  13385. child = child->nextElement;
  13386. }
  13387. return false;
  13388. }
  13389. XmlElement* XmlElement::findParentElementOf (const XmlElement* const elementToLookFor) throw()
  13390. {
  13391. if (this == elementToLookFor || elementToLookFor == 0)
  13392. return 0;
  13393. XmlElement* child = firstChildElement;
  13394. while (child != 0)
  13395. {
  13396. if (elementToLookFor == child)
  13397. return this;
  13398. XmlElement* const found = child->findParentElementOf (elementToLookFor);
  13399. if (found != 0)
  13400. return found;
  13401. child = child->nextElement;
  13402. }
  13403. return 0;
  13404. }
  13405. void XmlElement::getChildElementsAsArray (XmlElement** elems) const throw()
  13406. {
  13407. XmlElement* e = firstChildElement;
  13408. while (e != 0)
  13409. {
  13410. *elems++ = e;
  13411. e = e->nextElement;
  13412. }
  13413. }
  13414. void XmlElement::reorderChildElements (XmlElement** const elems, const int num) throw()
  13415. {
  13416. XmlElement* e = firstChildElement = elems[0];
  13417. for (int i = 1; i < num; ++i)
  13418. {
  13419. e->nextElement = elems[i];
  13420. e = e->nextElement;
  13421. }
  13422. e->nextElement = 0;
  13423. }
  13424. bool XmlElement::isTextElement() const throw()
  13425. {
  13426. return tagName.isEmpty();
  13427. }
  13428. static const juce_wchar* const juce_xmltextContentAttributeName = L"text";
  13429. const String& XmlElement::getText() const throw()
  13430. {
  13431. jassert (isTextElement()); // you're trying to get the text from an element that
  13432. // isn't actually a text element.. If this contains text sub-nodes, you
  13433. // probably want to use getAllSubText instead.
  13434. return getStringAttribute (juce_xmltextContentAttributeName);
  13435. }
  13436. void XmlElement::setText (const String& newText)
  13437. {
  13438. if (isTextElement())
  13439. setAttribute (juce_xmltextContentAttributeName, newText);
  13440. else
  13441. jassertfalse; // you can only change the text in a text element, not a normal one.
  13442. }
  13443. const String XmlElement::getAllSubText() const
  13444. {
  13445. if (isTextElement())
  13446. return getText();
  13447. String result;
  13448. String::Concatenator concatenator (result);
  13449. const XmlElement* child = firstChildElement;
  13450. while (child != 0)
  13451. {
  13452. concatenator.append (child->getAllSubText());
  13453. child = child->nextElement;
  13454. }
  13455. return result;
  13456. }
  13457. const String XmlElement::getChildElementAllSubText (const String& childTagName,
  13458. const String& defaultReturnValue) const
  13459. {
  13460. const XmlElement* const child = getChildByName (childTagName);
  13461. if (child != 0)
  13462. return child->getAllSubText();
  13463. return defaultReturnValue;
  13464. }
  13465. XmlElement* XmlElement::createTextElement (const String& text)
  13466. {
  13467. XmlElement* const e = new XmlElement ((int) 0);
  13468. e->setAttribute (juce_xmltextContentAttributeName, text);
  13469. return e;
  13470. }
  13471. void XmlElement::addTextElement (const String& text)
  13472. {
  13473. addChildElement (createTextElement (text));
  13474. }
  13475. void XmlElement::deleteAllTextElements() throw()
  13476. {
  13477. XmlElement* child = firstChildElement;
  13478. while (child != 0)
  13479. {
  13480. XmlElement* const next = child->nextElement;
  13481. if (child->isTextElement())
  13482. removeChildElement (child, true);
  13483. child = next;
  13484. }
  13485. }
  13486. END_JUCE_NAMESPACE
  13487. /*** End of inlined file: juce_XmlElement.cpp ***/
  13488. /*** Start of inlined file: juce_ReadWriteLock.cpp ***/
  13489. BEGIN_JUCE_NAMESPACE
  13490. ReadWriteLock::ReadWriteLock() throw()
  13491. : numWaitingWriters (0),
  13492. numWriters (0),
  13493. writerThreadId (0)
  13494. {
  13495. }
  13496. ReadWriteLock::~ReadWriteLock() throw()
  13497. {
  13498. jassert (readerThreads.size() == 0);
  13499. jassert (numWriters == 0);
  13500. }
  13501. void ReadWriteLock::enterRead() const throw()
  13502. {
  13503. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13504. const ScopedLock sl (accessLock);
  13505. for (;;)
  13506. {
  13507. jassert (readerThreads.size() % 2 == 0);
  13508. int i;
  13509. for (i = 0; i < readerThreads.size(); i += 2)
  13510. if (readerThreads.getUnchecked(i) == threadId)
  13511. break;
  13512. if (i < readerThreads.size()
  13513. || numWriters + numWaitingWriters == 0
  13514. || (threadId == writerThreadId && numWriters > 0))
  13515. {
  13516. if (i < readerThreads.size())
  13517. {
  13518. readerThreads.set (i + 1, (Thread::ThreadID) (1 + (pointer_sized_int) readerThreads.getUnchecked (i + 1)));
  13519. }
  13520. else
  13521. {
  13522. readerThreads.add (threadId);
  13523. readerThreads.add ((Thread::ThreadID) 1);
  13524. }
  13525. return;
  13526. }
  13527. const ScopedUnlock ul (accessLock);
  13528. waitEvent.wait (100);
  13529. }
  13530. }
  13531. void ReadWriteLock::exitRead() const throw()
  13532. {
  13533. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13534. const ScopedLock sl (accessLock);
  13535. for (int i = 0; i < readerThreads.size(); i += 2)
  13536. {
  13537. if (readerThreads.getUnchecked(i) == threadId)
  13538. {
  13539. const pointer_sized_int newCount = ((pointer_sized_int) readerThreads.getUnchecked (i + 1)) - 1;
  13540. if (newCount == 0)
  13541. {
  13542. readerThreads.removeRange (i, 2);
  13543. waitEvent.signal();
  13544. }
  13545. else
  13546. {
  13547. readerThreads.set (i + 1, (Thread::ThreadID) newCount);
  13548. }
  13549. return;
  13550. }
  13551. }
  13552. jassertfalse; // unlocking a lock that wasn't locked..
  13553. }
  13554. void ReadWriteLock::enterWrite() const throw()
  13555. {
  13556. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13557. const ScopedLock sl (accessLock);
  13558. for (;;)
  13559. {
  13560. if (readerThreads.size() + numWriters == 0
  13561. || threadId == writerThreadId
  13562. || (readerThreads.size() == 2
  13563. && readerThreads.getUnchecked(0) == threadId))
  13564. {
  13565. writerThreadId = threadId;
  13566. ++numWriters;
  13567. break;
  13568. }
  13569. ++numWaitingWriters;
  13570. accessLock.exit();
  13571. waitEvent.wait (100);
  13572. accessLock.enter();
  13573. --numWaitingWriters;
  13574. }
  13575. }
  13576. bool ReadWriteLock::tryEnterWrite() const throw()
  13577. {
  13578. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13579. const ScopedLock sl (accessLock);
  13580. if (readerThreads.size() + numWriters == 0
  13581. || threadId == writerThreadId
  13582. || (readerThreads.size() == 2
  13583. && readerThreads.getUnchecked(0) == threadId))
  13584. {
  13585. writerThreadId = threadId;
  13586. ++numWriters;
  13587. return true;
  13588. }
  13589. return false;
  13590. }
  13591. void ReadWriteLock::exitWrite() const throw()
  13592. {
  13593. const ScopedLock sl (accessLock);
  13594. // check this thread actually had the lock..
  13595. jassert (numWriters > 0 && writerThreadId == Thread::getCurrentThreadId());
  13596. if (--numWriters == 0)
  13597. {
  13598. writerThreadId = 0;
  13599. waitEvent.signal();
  13600. }
  13601. }
  13602. END_JUCE_NAMESPACE
  13603. /*** End of inlined file: juce_ReadWriteLock.cpp ***/
  13604. /*** Start of inlined file: juce_Thread.cpp ***/
  13605. BEGIN_JUCE_NAMESPACE
  13606. // these functions are implemented in the platform-specific code.
  13607. void* juce_createThread (void* userData);
  13608. void juce_killThread (void* handle);
  13609. bool juce_setThreadPriority (void* handle, int priority);
  13610. void juce_setCurrentThreadName (const String& name);
  13611. #if JUCE_WINDOWS
  13612. void juce_CloseThreadHandle (void* handle);
  13613. #endif
  13614. void Thread::threadEntryPoint (Thread* const thread)
  13615. {
  13616. {
  13617. const ScopedLock sl (runningThreadsLock);
  13618. runningThreads.add (thread);
  13619. }
  13620. JUCE_TRY
  13621. {
  13622. thread->threadId_ = Thread::getCurrentThreadId();
  13623. if (thread->threadName_.isNotEmpty())
  13624. juce_setCurrentThreadName (thread->threadName_);
  13625. if (thread->startSuspensionEvent_.wait (10000))
  13626. {
  13627. if (thread->affinityMask_ != 0)
  13628. setCurrentThreadAffinityMask (thread->affinityMask_);
  13629. thread->run();
  13630. }
  13631. }
  13632. JUCE_CATCH_ALL_ASSERT
  13633. {
  13634. const ScopedLock sl (runningThreadsLock);
  13635. jassert (runningThreads.contains (thread));
  13636. runningThreads.removeValue (thread);
  13637. }
  13638. #if JUCE_WINDOWS
  13639. juce_CloseThreadHandle (thread->threadHandle_);
  13640. #endif
  13641. thread->threadHandle_ = 0;
  13642. thread->threadId_ = 0;
  13643. }
  13644. // used to wrap the incoming call from the platform-specific code
  13645. void JUCE_API juce_threadEntryPoint (void* userData)
  13646. {
  13647. Thread::threadEntryPoint (static_cast <Thread*> (userData));
  13648. }
  13649. Thread::Thread (const String& threadName)
  13650. : threadName_ (threadName),
  13651. threadHandle_ (0),
  13652. threadPriority_ (5),
  13653. threadId_ (0),
  13654. affinityMask_ (0),
  13655. threadShouldExit_ (false)
  13656. {
  13657. }
  13658. Thread::~Thread()
  13659. {
  13660. stopThread (100);
  13661. }
  13662. void Thread::startThread()
  13663. {
  13664. const ScopedLock sl (startStopLock);
  13665. threadShouldExit_ = false;
  13666. if (threadHandle_ == 0)
  13667. {
  13668. threadHandle_ = juce_createThread (this);
  13669. juce_setThreadPriority (threadHandle_, threadPriority_);
  13670. startSuspensionEvent_.signal();
  13671. }
  13672. }
  13673. void Thread::startThread (const int priority)
  13674. {
  13675. const ScopedLock sl (startStopLock);
  13676. if (threadHandle_ == 0)
  13677. {
  13678. threadPriority_ = priority;
  13679. startThread();
  13680. }
  13681. else
  13682. {
  13683. setPriority (priority);
  13684. }
  13685. }
  13686. bool Thread::isThreadRunning() const
  13687. {
  13688. return threadHandle_ != 0;
  13689. }
  13690. void Thread::signalThreadShouldExit()
  13691. {
  13692. threadShouldExit_ = true;
  13693. }
  13694. bool Thread::waitForThreadToExit (const int timeOutMilliseconds) const
  13695. {
  13696. // Doh! So how exactly do you expect this thread to wait for itself to stop??
  13697. jassert (getThreadId() != getCurrentThreadId());
  13698. const int sleepMsPerIteration = 5;
  13699. int count = timeOutMilliseconds / sleepMsPerIteration;
  13700. while (isThreadRunning())
  13701. {
  13702. if (timeOutMilliseconds > 0 && --count < 0)
  13703. return false;
  13704. sleep (sleepMsPerIteration);
  13705. }
  13706. return true;
  13707. }
  13708. void Thread::stopThread (const int timeOutMilliseconds)
  13709. {
  13710. // agh! You can't stop the thread that's calling this method! How on earth
  13711. // would that work??
  13712. jassert (getCurrentThreadId() != getThreadId());
  13713. const ScopedLock sl (startStopLock);
  13714. if (isThreadRunning())
  13715. {
  13716. signalThreadShouldExit();
  13717. notify();
  13718. if (timeOutMilliseconds != 0)
  13719. waitForThreadToExit (timeOutMilliseconds);
  13720. if (isThreadRunning())
  13721. {
  13722. // very bad karma if this point is reached, as
  13723. // there are bound to be locks and events left in
  13724. // silly states when a thread is killed by force..
  13725. jassertfalse;
  13726. Logger::writeToLog ("!! killing thread by force !!");
  13727. juce_killThread (threadHandle_);
  13728. threadHandle_ = 0;
  13729. threadId_ = 0;
  13730. const ScopedLock sl2 (runningThreadsLock);
  13731. runningThreads.removeValue (this);
  13732. }
  13733. }
  13734. }
  13735. bool Thread::setPriority (const int priority)
  13736. {
  13737. const ScopedLock sl (startStopLock);
  13738. const bool worked = juce_setThreadPriority (threadHandle_, priority);
  13739. if (worked)
  13740. threadPriority_ = priority;
  13741. return worked;
  13742. }
  13743. bool Thread::setCurrentThreadPriority (const int priority)
  13744. {
  13745. return juce_setThreadPriority (0, priority);
  13746. }
  13747. void Thread::setAffinityMask (const uint32 affinityMask)
  13748. {
  13749. affinityMask_ = affinityMask;
  13750. }
  13751. bool Thread::wait (const int timeOutMilliseconds) const
  13752. {
  13753. return defaultEvent_.wait (timeOutMilliseconds);
  13754. }
  13755. void Thread::notify() const
  13756. {
  13757. defaultEvent_.signal();
  13758. }
  13759. int Thread::getNumRunningThreads()
  13760. {
  13761. return runningThreads.size();
  13762. }
  13763. Thread* Thread::getCurrentThread()
  13764. {
  13765. const ThreadID thisId = getCurrentThreadId();
  13766. const ScopedLock sl (runningThreadsLock);
  13767. for (int i = runningThreads.size(); --i >= 0;)
  13768. {
  13769. Thread* const t = runningThreads.getUnchecked(i);
  13770. if (t->threadId_ == thisId)
  13771. return t;
  13772. }
  13773. return 0;
  13774. }
  13775. void Thread::stopAllThreads (const int timeOutMilliseconds)
  13776. {
  13777. {
  13778. const ScopedLock sl (runningThreadsLock);
  13779. for (int i = runningThreads.size(); --i >= 0;)
  13780. runningThreads.getUnchecked(i)->signalThreadShouldExit();
  13781. }
  13782. for (;;)
  13783. {
  13784. Thread* firstThread;
  13785. {
  13786. const ScopedLock sl (runningThreadsLock);
  13787. firstThread = runningThreads.getFirst();
  13788. }
  13789. if (firstThread == 0)
  13790. break;
  13791. firstThread->stopThread (timeOutMilliseconds);
  13792. }
  13793. }
  13794. Array<Thread*> Thread::runningThreads;
  13795. CriticalSection Thread::runningThreadsLock;
  13796. END_JUCE_NAMESPACE
  13797. /*** End of inlined file: juce_Thread.cpp ***/
  13798. /*** Start of inlined file: juce_ThreadPool.cpp ***/
  13799. BEGIN_JUCE_NAMESPACE
  13800. ThreadPoolJob::ThreadPoolJob (const String& name)
  13801. : jobName (name),
  13802. pool (0),
  13803. shouldStop (false),
  13804. isActive (false),
  13805. shouldBeDeleted (false)
  13806. {
  13807. }
  13808. ThreadPoolJob::~ThreadPoolJob()
  13809. {
  13810. // you mustn't delete a job while it's still in a pool! Use ThreadPool::removeJob()
  13811. // to remove it first!
  13812. jassert (pool == 0 || ! pool->contains (this));
  13813. }
  13814. const String ThreadPoolJob::getJobName() const
  13815. {
  13816. return jobName;
  13817. }
  13818. void ThreadPoolJob::setJobName (const String& newName)
  13819. {
  13820. jobName = newName;
  13821. }
  13822. void ThreadPoolJob::signalJobShouldExit()
  13823. {
  13824. shouldStop = true;
  13825. }
  13826. class ThreadPool::ThreadPoolThread : public Thread
  13827. {
  13828. public:
  13829. ThreadPoolThread (ThreadPool& pool_)
  13830. : Thread ("Pool"),
  13831. pool (pool_),
  13832. busy (false)
  13833. {
  13834. }
  13835. ~ThreadPoolThread()
  13836. {
  13837. }
  13838. void run()
  13839. {
  13840. while (! threadShouldExit())
  13841. {
  13842. if (! pool.runNextJob())
  13843. wait (500);
  13844. }
  13845. }
  13846. private:
  13847. ThreadPool& pool;
  13848. bool volatile busy;
  13849. ThreadPoolThread (const ThreadPoolThread&);
  13850. ThreadPoolThread& operator= (const ThreadPoolThread&);
  13851. };
  13852. ThreadPool::ThreadPool (const int numThreads,
  13853. const bool startThreadsOnlyWhenNeeded,
  13854. const int stopThreadsWhenNotUsedTimeoutMs)
  13855. : threadStopTimeout (stopThreadsWhenNotUsedTimeoutMs),
  13856. priority (5)
  13857. {
  13858. jassert (numThreads > 0); // not much point having one of these with no threads in it.
  13859. for (int i = jmax (1, numThreads); --i >= 0;)
  13860. threads.add (new ThreadPoolThread (*this));
  13861. if (! startThreadsOnlyWhenNeeded)
  13862. for (int i = threads.size(); --i >= 0;)
  13863. threads.getUnchecked(i)->startThread (priority);
  13864. }
  13865. ThreadPool::~ThreadPool()
  13866. {
  13867. removeAllJobs (true, 4000);
  13868. int i;
  13869. for (i = threads.size(); --i >= 0;)
  13870. threads.getUnchecked(i)->signalThreadShouldExit();
  13871. for (i = threads.size(); --i >= 0;)
  13872. threads.getUnchecked(i)->stopThread (500);
  13873. }
  13874. void ThreadPool::addJob (ThreadPoolJob* const job)
  13875. {
  13876. jassert (job != 0);
  13877. jassert (job->pool == 0);
  13878. if (job->pool == 0)
  13879. {
  13880. job->pool = this;
  13881. job->shouldStop = false;
  13882. job->isActive = false;
  13883. {
  13884. const ScopedLock sl (lock);
  13885. jobs.add (job);
  13886. int numRunning = 0;
  13887. for (int i = threads.size(); --i >= 0;)
  13888. if (threads.getUnchecked(i)->isThreadRunning() && ! threads.getUnchecked(i)->threadShouldExit())
  13889. ++numRunning;
  13890. if (numRunning < threads.size())
  13891. {
  13892. bool startedOne = false;
  13893. int n = 1000;
  13894. while (--n >= 0 && ! startedOne)
  13895. {
  13896. for (int i = threads.size(); --i >= 0;)
  13897. {
  13898. if (! threads.getUnchecked(i)->isThreadRunning())
  13899. {
  13900. threads.getUnchecked(i)->startThread (priority);
  13901. startedOne = true;
  13902. break;
  13903. }
  13904. }
  13905. if (! startedOne)
  13906. Thread::sleep (2);
  13907. }
  13908. }
  13909. }
  13910. for (int i = threads.size(); --i >= 0;)
  13911. threads.getUnchecked(i)->notify();
  13912. }
  13913. }
  13914. int ThreadPool::getNumJobs() const
  13915. {
  13916. return jobs.size();
  13917. }
  13918. ThreadPoolJob* ThreadPool::getJob (const int index) const
  13919. {
  13920. const ScopedLock sl (lock);
  13921. return jobs [index];
  13922. }
  13923. bool ThreadPool::contains (const ThreadPoolJob* const job) const
  13924. {
  13925. const ScopedLock sl (lock);
  13926. return jobs.contains (const_cast <ThreadPoolJob*> (job));
  13927. }
  13928. bool ThreadPool::isJobRunning (const ThreadPoolJob* const job) const
  13929. {
  13930. const ScopedLock sl (lock);
  13931. return jobs.contains (const_cast <ThreadPoolJob*> (job)) && job->isActive;
  13932. }
  13933. bool ThreadPool::waitForJobToFinish (const ThreadPoolJob* const job,
  13934. const int timeOutMs) const
  13935. {
  13936. if (job != 0)
  13937. {
  13938. const uint32 start = Time::getMillisecondCounter();
  13939. while (contains (job))
  13940. {
  13941. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  13942. return false;
  13943. jobFinishedSignal.wait (2);
  13944. }
  13945. }
  13946. return true;
  13947. }
  13948. bool ThreadPool::removeJob (ThreadPoolJob* const job,
  13949. const bool interruptIfRunning,
  13950. const int timeOutMs)
  13951. {
  13952. bool dontWait = true;
  13953. if (job != 0)
  13954. {
  13955. const ScopedLock sl (lock);
  13956. if (jobs.contains (job))
  13957. {
  13958. if (job->isActive)
  13959. {
  13960. if (interruptIfRunning)
  13961. job->signalJobShouldExit();
  13962. dontWait = false;
  13963. }
  13964. else
  13965. {
  13966. jobs.removeValue (job);
  13967. job->pool = 0;
  13968. }
  13969. }
  13970. }
  13971. return dontWait || waitForJobToFinish (job, timeOutMs);
  13972. }
  13973. bool ThreadPool::removeAllJobs (const bool interruptRunningJobs,
  13974. const int timeOutMs,
  13975. const bool deleteInactiveJobs,
  13976. ThreadPool::JobSelector* selectedJobsToRemove)
  13977. {
  13978. Array <ThreadPoolJob*> jobsToWaitFor;
  13979. {
  13980. const ScopedLock sl (lock);
  13981. for (int i = jobs.size(); --i >= 0;)
  13982. {
  13983. ThreadPoolJob* const job = jobs.getUnchecked(i);
  13984. if (selectedJobsToRemove == 0 || selectedJobsToRemove->isJobSuitable (job))
  13985. {
  13986. if (job->isActive)
  13987. {
  13988. jobsToWaitFor.add (job);
  13989. if (interruptRunningJobs)
  13990. job->signalJobShouldExit();
  13991. }
  13992. else
  13993. {
  13994. jobs.remove (i);
  13995. if (deleteInactiveJobs)
  13996. delete job;
  13997. else
  13998. job->pool = 0;
  13999. }
  14000. }
  14001. }
  14002. }
  14003. const uint32 start = Time::getMillisecondCounter();
  14004. for (;;)
  14005. {
  14006. for (int i = jobsToWaitFor.size(); --i >= 0;)
  14007. if (! isJobRunning (jobsToWaitFor.getUnchecked (i)))
  14008. jobsToWaitFor.remove (i);
  14009. if (jobsToWaitFor.size() == 0)
  14010. break;
  14011. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  14012. return false;
  14013. jobFinishedSignal.wait (20);
  14014. }
  14015. return true;
  14016. }
  14017. const StringArray ThreadPool::getNamesOfAllJobs (const bool onlyReturnActiveJobs) const
  14018. {
  14019. StringArray s;
  14020. const ScopedLock sl (lock);
  14021. for (int i = 0; i < jobs.size(); ++i)
  14022. {
  14023. const ThreadPoolJob* const job = jobs.getUnchecked(i);
  14024. if (job->isActive || ! onlyReturnActiveJobs)
  14025. s.add (job->getJobName());
  14026. }
  14027. return s;
  14028. }
  14029. bool ThreadPool::setThreadPriorities (const int newPriority)
  14030. {
  14031. bool ok = true;
  14032. if (priority != newPriority)
  14033. {
  14034. priority = newPriority;
  14035. for (int i = threads.size(); --i >= 0;)
  14036. if (! threads.getUnchecked(i)->setPriority (newPriority))
  14037. ok = false;
  14038. }
  14039. return ok;
  14040. }
  14041. bool ThreadPool::runNextJob()
  14042. {
  14043. ThreadPoolJob* job = 0;
  14044. {
  14045. const ScopedLock sl (lock);
  14046. for (int i = 0; i < jobs.size(); ++i)
  14047. {
  14048. job = jobs[i];
  14049. if (job != 0 && ! (job->isActive || job->shouldStop))
  14050. break;
  14051. job = 0;
  14052. }
  14053. if (job != 0)
  14054. job->isActive = true;
  14055. }
  14056. if (job != 0)
  14057. {
  14058. JUCE_TRY
  14059. {
  14060. ThreadPoolJob::JobStatus result = job->runJob();
  14061. lastJobEndTime = Time::getApproximateMillisecondCounter();
  14062. const ScopedLock sl (lock);
  14063. if (jobs.contains (job))
  14064. {
  14065. job->isActive = false;
  14066. if (result != ThreadPoolJob::jobNeedsRunningAgain || job->shouldStop)
  14067. {
  14068. job->pool = 0;
  14069. job->shouldStop = true;
  14070. jobs.removeValue (job);
  14071. if (result == ThreadPoolJob::jobHasFinishedAndShouldBeDeleted)
  14072. delete job;
  14073. jobFinishedSignal.signal();
  14074. }
  14075. else
  14076. {
  14077. // move the job to the end of the queue if it wants another go
  14078. jobs.move (jobs.indexOf (job), -1);
  14079. }
  14080. }
  14081. }
  14082. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  14083. catch (...)
  14084. {
  14085. const ScopedLock sl (lock);
  14086. jobs.removeValue (job);
  14087. }
  14088. #endif
  14089. }
  14090. else
  14091. {
  14092. if (threadStopTimeout > 0
  14093. && Time::getApproximateMillisecondCounter() > lastJobEndTime + threadStopTimeout)
  14094. {
  14095. const ScopedLock sl (lock);
  14096. if (jobs.size() == 0)
  14097. for (int i = threads.size(); --i >= 0;)
  14098. threads.getUnchecked(i)->signalThreadShouldExit();
  14099. }
  14100. else
  14101. {
  14102. return false;
  14103. }
  14104. }
  14105. return true;
  14106. }
  14107. END_JUCE_NAMESPACE
  14108. /*** End of inlined file: juce_ThreadPool.cpp ***/
  14109. /*** Start of inlined file: juce_TimeSliceThread.cpp ***/
  14110. BEGIN_JUCE_NAMESPACE
  14111. TimeSliceThread::TimeSliceThread (const String& threadName)
  14112. : Thread (threadName),
  14113. index (0),
  14114. clientBeingCalled (0),
  14115. clientsChanged (false)
  14116. {
  14117. }
  14118. TimeSliceThread::~TimeSliceThread()
  14119. {
  14120. stopThread (2000);
  14121. }
  14122. void TimeSliceThread::addTimeSliceClient (TimeSliceClient* const client)
  14123. {
  14124. const ScopedLock sl (listLock);
  14125. clients.addIfNotAlreadyThere (client);
  14126. clientsChanged = true;
  14127. notify();
  14128. }
  14129. void TimeSliceThread::removeTimeSliceClient (TimeSliceClient* const client)
  14130. {
  14131. const ScopedLock sl1 (listLock);
  14132. clientsChanged = true;
  14133. // if there's a chance we're in the middle of calling this client, we need to
  14134. // also lock the outer lock..
  14135. if (clientBeingCalled == client)
  14136. {
  14137. const ScopedUnlock ul (listLock); // unlock first to get the order right..
  14138. const ScopedLock sl2 (callbackLock);
  14139. const ScopedLock sl3 (listLock);
  14140. clients.removeValue (client);
  14141. }
  14142. else
  14143. {
  14144. clients.removeValue (client);
  14145. }
  14146. }
  14147. int TimeSliceThread::getNumClients() const
  14148. {
  14149. return clients.size();
  14150. }
  14151. TimeSliceClient* TimeSliceThread::getClient (const int i) const
  14152. {
  14153. const ScopedLock sl (listLock);
  14154. return clients [i];
  14155. }
  14156. void TimeSliceThread::run()
  14157. {
  14158. int numCallsSinceBusy = 0;
  14159. while (! threadShouldExit())
  14160. {
  14161. int timeToWait = 500;
  14162. {
  14163. const ScopedLock sl (callbackLock);
  14164. {
  14165. const ScopedLock sl2 (listLock);
  14166. if (clients.size() > 0)
  14167. {
  14168. index = (index + 1) % clients.size();
  14169. clientBeingCalled = clients [index];
  14170. }
  14171. else
  14172. {
  14173. index = 0;
  14174. clientBeingCalled = 0;
  14175. }
  14176. if (clientsChanged)
  14177. {
  14178. clientsChanged = false;
  14179. numCallsSinceBusy = 0;
  14180. }
  14181. }
  14182. if (clientBeingCalled != 0)
  14183. {
  14184. if (clientBeingCalled->useTimeSlice())
  14185. numCallsSinceBusy = 0;
  14186. else
  14187. ++numCallsSinceBusy;
  14188. if (numCallsSinceBusy >= clients.size())
  14189. timeToWait = 500;
  14190. else if (index == 0)
  14191. timeToWait = 1; // throw in an occasional pause, to stop everything locking up
  14192. else
  14193. timeToWait = 0;
  14194. }
  14195. }
  14196. if (timeToWait > 0)
  14197. wait (timeToWait);
  14198. }
  14199. }
  14200. END_JUCE_NAMESPACE
  14201. /*** End of inlined file: juce_TimeSliceThread.cpp ***/
  14202. /*** Start of inlined file: juce_DeletedAtShutdown.cpp ***/
  14203. BEGIN_JUCE_NAMESPACE
  14204. DeletedAtShutdown::DeletedAtShutdown()
  14205. {
  14206. const ScopedLock sl (getLock());
  14207. getObjects().add (this);
  14208. }
  14209. DeletedAtShutdown::~DeletedAtShutdown()
  14210. {
  14211. const ScopedLock sl (getLock());
  14212. getObjects().removeValue (this);
  14213. }
  14214. void DeletedAtShutdown::deleteAll()
  14215. {
  14216. // make a local copy of the array, so it can't get into a loop if something
  14217. // creates another DeletedAtShutdown object during its destructor.
  14218. Array <DeletedAtShutdown*> localCopy;
  14219. {
  14220. const ScopedLock sl (getLock());
  14221. localCopy = getObjects();
  14222. }
  14223. for (int i = localCopy.size(); --i >= 0;)
  14224. {
  14225. JUCE_TRY
  14226. {
  14227. DeletedAtShutdown* deletee = localCopy.getUnchecked(i);
  14228. // double-check that it's not already been deleted during another object's destructor.
  14229. {
  14230. const ScopedLock sl (getLock());
  14231. if (! getObjects().contains (deletee))
  14232. deletee = 0;
  14233. }
  14234. delete deletee;
  14235. }
  14236. JUCE_CATCH_EXCEPTION
  14237. }
  14238. // if no objects got re-created during shutdown, this should have been emptied by their
  14239. // destructors
  14240. jassert (getObjects().size() == 0);
  14241. getObjects().clear(); // just to make sure the array doesn't have any memory still allocated
  14242. }
  14243. CriticalSection& DeletedAtShutdown::getLock()
  14244. {
  14245. static CriticalSection lock;
  14246. return lock;
  14247. }
  14248. Array <DeletedAtShutdown*>& DeletedAtShutdown::getObjects()
  14249. {
  14250. static Array <DeletedAtShutdown*> objects;
  14251. return objects;
  14252. }
  14253. END_JUCE_NAMESPACE
  14254. /*** End of inlined file: juce_DeletedAtShutdown.cpp ***/
  14255. /*** Start of inlined file: juce_UnitTest.cpp ***/
  14256. BEGIN_JUCE_NAMESPACE
  14257. UnitTest::UnitTest (const String& name_)
  14258. : name (name_), runner (0)
  14259. {
  14260. getAllTests().add (this);
  14261. }
  14262. UnitTest::~UnitTest()
  14263. {
  14264. getAllTests().removeValue (this);
  14265. }
  14266. Array<UnitTest*>& UnitTest::getAllTests()
  14267. {
  14268. static Array<UnitTest*> tests;
  14269. return tests;
  14270. }
  14271. void UnitTest::initialise() {}
  14272. void UnitTest::shutdown() {}
  14273. void UnitTest::performTest (UnitTestRunner* const runner_)
  14274. {
  14275. jassert (runner_ != 0);
  14276. runner = runner_;
  14277. initialise();
  14278. runTest();
  14279. shutdown();
  14280. }
  14281. void UnitTest::logMessage (const String& message)
  14282. {
  14283. runner->logMessage (message);
  14284. }
  14285. void UnitTest::beginTest (const String& testName)
  14286. {
  14287. runner->beginNewTest (this, testName);
  14288. }
  14289. void UnitTest::expect (const bool result, const String& failureMessage)
  14290. {
  14291. if (result)
  14292. runner->addPass();
  14293. else
  14294. runner->addFail (failureMessage);
  14295. }
  14296. UnitTestRunner::UnitTestRunner()
  14297. : currentTest (0), assertOnFailure (false)
  14298. {
  14299. }
  14300. UnitTestRunner::~UnitTestRunner()
  14301. {
  14302. }
  14303. int UnitTestRunner::getNumResults() const throw()
  14304. {
  14305. return results.size();
  14306. }
  14307. const UnitTestRunner::TestResult* UnitTestRunner::getResult (int index) const throw()
  14308. {
  14309. return results [index];
  14310. }
  14311. void UnitTestRunner::resultsUpdated()
  14312. {
  14313. }
  14314. void UnitTestRunner::runTests (const Array<UnitTest*>& tests, const bool assertOnFailure_)
  14315. {
  14316. results.clear();
  14317. assertOnFailure = assertOnFailure_;
  14318. resultsUpdated();
  14319. for (int i = 0; i < tests.size(); ++i)
  14320. {
  14321. try
  14322. {
  14323. tests.getUnchecked(i)->performTest (this);
  14324. }
  14325. catch (...)
  14326. {
  14327. addFail ("An unhandled exception was thrown!");
  14328. }
  14329. }
  14330. endTest();
  14331. }
  14332. void UnitTestRunner::runAllTests (const bool assertOnFailure_)
  14333. {
  14334. runTests (UnitTest::getAllTests(), assertOnFailure_);
  14335. }
  14336. void UnitTestRunner::logMessage (const String& message)
  14337. {
  14338. Logger::writeToLog (message);
  14339. }
  14340. void UnitTestRunner::beginNewTest (UnitTest* const test, const String& subCategory)
  14341. {
  14342. endTest();
  14343. currentTest = test;
  14344. TestResult* const r = new TestResult();
  14345. r->unitTestName = test->getName();
  14346. r->subcategoryName = subCategory;
  14347. r->passes = 0;
  14348. r->failures = 0;
  14349. results.add (r);
  14350. logMessage ("-----------------------------------------------------------------");
  14351. logMessage ("Starting test: " + r->unitTestName + " / " + subCategory + "...");
  14352. resultsUpdated();
  14353. }
  14354. void UnitTestRunner::endTest()
  14355. {
  14356. if (results.size() > 0)
  14357. {
  14358. TestResult* const r = results.getLast();
  14359. if (r->failures > 0)
  14360. {
  14361. String m ("FAILED!!");
  14362. m << r->failures << (r->failures == 1 ? "test" : "tests")
  14363. << " failed, out of a total of " << (r->passes + r->failures);
  14364. logMessage (String::empty);
  14365. logMessage (m);
  14366. logMessage (String::empty);
  14367. }
  14368. else
  14369. {
  14370. logMessage ("All tests completed successfully");
  14371. }
  14372. }
  14373. }
  14374. void UnitTestRunner::addPass()
  14375. {
  14376. {
  14377. const ScopedLock sl (results.getLock());
  14378. TestResult* const r = results.getLast();
  14379. jassert (r != 0); // You need to call UnitTest::beginTest() before performing any tests!
  14380. r->passes++;
  14381. String message ("Test ");
  14382. message << (r->failures + r->passes) << " passed";
  14383. logMessage (message);
  14384. }
  14385. resultsUpdated();
  14386. }
  14387. void UnitTestRunner::addFail (const String& failureMessage)
  14388. {
  14389. {
  14390. const ScopedLock sl (results.getLock());
  14391. TestResult* const r = results.getLast();
  14392. jassert (r != 0); // You need to call UnitTest::beginTest() before performing any tests!
  14393. r->failures++;
  14394. String message ("!!! Test ");
  14395. message << (r->failures + r->passes) << " failed";
  14396. if (failureMessage.isNotEmpty())
  14397. message << ": " << failureMessage;
  14398. r->messages.add (message);
  14399. logMessage (message);
  14400. }
  14401. resultsUpdated();
  14402. if (assertOnFailure) { jassertfalse }
  14403. }
  14404. END_JUCE_NAMESPACE
  14405. /*** End of inlined file: juce_UnitTest.cpp ***/
  14406. #endif
  14407. #if JUCE_BUILD_MISC
  14408. /*** Start of inlined file: juce_ValueTree.cpp ***/
  14409. BEGIN_JUCE_NAMESPACE
  14410. class ValueTree::SetPropertyAction : public UndoableAction
  14411. {
  14412. public:
  14413. SetPropertyAction (const SharedObjectPtr& target_, const Identifier& name_,
  14414. const var& newValue_, const var& oldValue_,
  14415. const bool isAddingNewProperty_, const bool isDeletingProperty_)
  14416. : target (target_), name (name_), newValue (newValue_), oldValue (oldValue_),
  14417. isAddingNewProperty (isAddingNewProperty_), isDeletingProperty (isDeletingProperty_)
  14418. {
  14419. }
  14420. ~SetPropertyAction() {}
  14421. bool perform()
  14422. {
  14423. jassert (! (isAddingNewProperty && target->hasProperty (name)));
  14424. if (isDeletingProperty)
  14425. target->removeProperty (name, 0);
  14426. else
  14427. target->setProperty (name, newValue, 0);
  14428. return true;
  14429. }
  14430. bool undo()
  14431. {
  14432. if (isAddingNewProperty)
  14433. target->removeProperty (name, 0);
  14434. else
  14435. target->setProperty (name, oldValue, 0);
  14436. return true;
  14437. }
  14438. int getSizeInUnits()
  14439. {
  14440. return (int) sizeof (*this); //xxx should be more accurate
  14441. }
  14442. UndoableAction* createCoalescedAction (UndoableAction* nextAction)
  14443. {
  14444. if (! (isAddingNewProperty || isDeletingProperty))
  14445. {
  14446. SetPropertyAction* next = dynamic_cast <SetPropertyAction*> (nextAction);
  14447. if (next != 0 && next->target == target && next->name == name
  14448. && ! (next->isAddingNewProperty || next->isDeletingProperty))
  14449. {
  14450. return new SetPropertyAction (target, name, next->newValue, oldValue, false, false);
  14451. }
  14452. }
  14453. return 0;
  14454. }
  14455. private:
  14456. const SharedObjectPtr target;
  14457. const Identifier name;
  14458. const var newValue;
  14459. var oldValue;
  14460. const bool isAddingNewProperty : 1, isDeletingProperty : 1;
  14461. SetPropertyAction (const SetPropertyAction&);
  14462. SetPropertyAction& operator= (const SetPropertyAction&);
  14463. };
  14464. class ValueTree::AddOrRemoveChildAction : public UndoableAction
  14465. {
  14466. public:
  14467. AddOrRemoveChildAction (const SharedObjectPtr& target_, const int childIndex_,
  14468. const SharedObjectPtr& newChild_)
  14469. : target (target_),
  14470. child (newChild_ != 0 ? newChild_ : target_->children [childIndex_]),
  14471. childIndex (childIndex_),
  14472. isDeleting (newChild_ == 0)
  14473. {
  14474. jassert (child != 0);
  14475. }
  14476. ~AddOrRemoveChildAction() {}
  14477. bool perform()
  14478. {
  14479. if (isDeleting)
  14480. target->removeChild (childIndex, 0);
  14481. else
  14482. target->addChild (child, childIndex, 0);
  14483. return true;
  14484. }
  14485. bool undo()
  14486. {
  14487. if (isDeleting)
  14488. {
  14489. target->addChild (child, childIndex, 0);
  14490. }
  14491. else
  14492. {
  14493. // If you hit this, it seems that your object's state is getting confused - probably
  14494. // because you've interleaved some undoable and non-undoable operations?
  14495. jassert (childIndex < target->children.size());
  14496. target->removeChild (childIndex, 0);
  14497. }
  14498. return true;
  14499. }
  14500. int getSizeInUnits()
  14501. {
  14502. return (int) sizeof (*this); //xxx should be more accurate
  14503. }
  14504. private:
  14505. const SharedObjectPtr target, child;
  14506. const int childIndex;
  14507. const bool isDeleting;
  14508. AddOrRemoveChildAction (const AddOrRemoveChildAction&);
  14509. AddOrRemoveChildAction& operator= (const AddOrRemoveChildAction&);
  14510. };
  14511. class ValueTree::MoveChildAction : public UndoableAction
  14512. {
  14513. public:
  14514. MoveChildAction (const SharedObjectPtr& parent_,
  14515. const int startIndex_, const int endIndex_)
  14516. : parent (parent_),
  14517. startIndex (startIndex_),
  14518. endIndex (endIndex_)
  14519. {
  14520. }
  14521. ~MoveChildAction() {}
  14522. bool perform()
  14523. {
  14524. parent->moveChild (startIndex, endIndex, 0);
  14525. return true;
  14526. }
  14527. bool undo()
  14528. {
  14529. parent->moveChild (endIndex, startIndex, 0);
  14530. return true;
  14531. }
  14532. int getSizeInUnits()
  14533. {
  14534. return (int) sizeof (*this); //xxx should be more accurate
  14535. }
  14536. UndoableAction* createCoalescedAction (UndoableAction* nextAction)
  14537. {
  14538. MoveChildAction* next = dynamic_cast <MoveChildAction*> (nextAction);
  14539. if (next != 0 && next->parent == parent && next->startIndex == endIndex)
  14540. return new MoveChildAction (parent, startIndex, next->endIndex);
  14541. return 0;
  14542. }
  14543. private:
  14544. const SharedObjectPtr parent;
  14545. const int startIndex, endIndex;
  14546. MoveChildAction (const MoveChildAction&);
  14547. MoveChildAction& operator= (const MoveChildAction&);
  14548. };
  14549. ValueTree::SharedObject::SharedObject (const Identifier& type_)
  14550. : type (type_), parent (0)
  14551. {
  14552. }
  14553. ValueTree::SharedObject::SharedObject (const SharedObject& other)
  14554. : type (other.type), properties (other.properties), parent (0)
  14555. {
  14556. for (int i = 0; i < other.children.size(); ++i)
  14557. {
  14558. SharedObject* const child = new SharedObject (*other.children.getUnchecked(i));
  14559. child->parent = this;
  14560. children.add (child);
  14561. }
  14562. }
  14563. ValueTree::SharedObject::~SharedObject()
  14564. {
  14565. jassert (parent == 0); // this should never happen unless something isn't obeying the ref-counting!
  14566. for (int i = children.size(); --i >= 0;)
  14567. {
  14568. const SharedObjectPtr c (children.getUnchecked(i));
  14569. c->parent = 0;
  14570. children.remove (i);
  14571. c->sendParentChangeMessage();
  14572. }
  14573. }
  14574. void ValueTree::SharedObject::sendPropertyChangeMessage (ValueTree& tree, const Identifier& property)
  14575. {
  14576. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  14577. {
  14578. ValueTree* const v = valueTreesWithListeners[i];
  14579. if (v != 0)
  14580. v->listeners.call (&ValueTree::Listener::valueTreePropertyChanged, tree, property);
  14581. }
  14582. }
  14583. void ValueTree::SharedObject::sendPropertyChangeMessage (const Identifier& property)
  14584. {
  14585. ValueTree tree (this);
  14586. ValueTree::SharedObject* t = this;
  14587. while (t != 0)
  14588. {
  14589. t->sendPropertyChangeMessage (tree, property);
  14590. t = t->parent;
  14591. }
  14592. }
  14593. void ValueTree::SharedObject::sendChildChangeMessage (ValueTree& tree)
  14594. {
  14595. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  14596. {
  14597. ValueTree* const v = valueTreesWithListeners[i];
  14598. if (v != 0)
  14599. v->listeners.call (&ValueTree::Listener::valueTreeChildrenChanged, tree);
  14600. }
  14601. }
  14602. void ValueTree::SharedObject::sendChildChangeMessage()
  14603. {
  14604. ValueTree tree (this);
  14605. ValueTree::SharedObject* t = this;
  14606. while (t != 0)
  14607. {
  14608. t->sendChildChangeMessage (tree);
  14609. t = t->parent;
  14610. }
  14611. }
  14612. void ValueTree::SharedObject::sendParentChangeMessage()
  14613. {
  14614. ValueTree tree (this);
  14615. int i;
  14616. for (i = children.size(); --i >= 0;)
  14617. {
  14618. SharedObject* const t = children[i];
  14619. if (t != 0)
  14620. t->sendParentChangeMessage();
  14621. }
  14622. for (i = valueTreesWithListeners.size(); --i >= 0;)
  14623. {
  14624. ValueTree* const v = valueTreesWithListeners[i];
  14625. if (v != 0)
  14626. v->listeners.call (&ValueTree::Listener::valueTreeParentChanged, tree);
  14627. }
  14628. }
  14629. const var& ValueTree::SharedObject::getProperty (const Identifier& name) const
  14630. {
  14631. return properties [name];
  14632. }
  14633. const var ValueTree::SharedObject::getProperty (const Identifier& name, const var& defaultReturnValue) const
  14634. {
  14635. return properties.getWithDefault (name, defaultReturnValue);
  14636. }
  14637. void ValueTree::SharedObject::setProperty (const Identifier& name, const var& newValue, UndoManager* const undoManager)
  14638. {
  14639. if (undoManager == 0)
  14640. {
  14641. if (properties.set (name, newValue))
  14642. sendPropertyChangeMessage (name);
  14643. }
  14644. else
  14645. {
  14646. var* const existingValue = properties.getVarPointer (name);
  14647. if (existingValue != 0)
  14648. {
  14649. if (*existingValue != newValue)
  14650. undoManager->perform (new SetPropertyAction (this, name, newValue, properties [name], false, false));
  14651. }
  14652. else
  14653. {
  14654. undoManager->perform (new SetPropertyAction (this, name, newValue, var::null, true, false));
  14655. }
  14656. }
  14657. }
  14658. bool ValueTree::SharedObject::hasProperty (const Identifier& name) const
  14659. {
  14660. return properties.contains (name);
  14661. }
  14662. void ValueTree::SharedObject::removeProperty (const Identifier& name, UndoManager* const undoManager)
  14663. {
  14664. if (undoManager == 0)
  14665. {
  14666. if (properties.remove (name))
  14667. sendPropertyChangeMessage (name);
  14668. }
  14669. else
  14670. {
  14671. if (properties.contains (name))
  14672. undoManager->perform (new SetPropertyAction (this, name, var::null, properties [name], false, true));
  14673. }
  14674. }
  14675. void ValueTree::SharedObject::removeAllProperties (UndoManager* const undoManager)
  14676. {
  14677. if (undoManager == 0)
  14678. {
  14679. while (properties.size() > 0)
  14680. {
  14681. const Identifier name (properties.getName (properties.size() - 1));
  14682. properties.remove (name);
  14683. sendPropertyChangeMessage (name);
  14684. }
  14685. }
  14686. else
  14687. {
  14688. for (int i = properties.size(); --i >= 0;)
  14689. undoManager->perform (new SetPropertyAction (this, properties.getName(i), var::null, properties.getValueAt(i), false, true));
  14690. }
  14691. }
  14692. ValueTree ValueTree::SharedObject::getChildWithName (const Identifier& typeToMatch) const
  14693. {
  14694. for (int i = 0; i < children.size(); ++i)
  14695. if (children.getUnchecked(i)->type == typeToMatch)
  14696. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  14697. return ValueTree::invalid;
  14698. }
  14699. ValueTree ValueTree::SharedObject::getOrCreateChildWithName (const Identifier& typeToMatch, UndoManager* undoManager)
  14700. {
  14701. for (int i = 0; i < children.size(); ++i)
  14702. if (children.getUnchecked(i)->type == typeToMatch)
  14703. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  14704. SharedObject* const newObject = new SharedObject (typeToMatch);
  14705. addChild (newObject, -1, undoManager);
  14706. return ValueTree (newObject);
  14707. }
  14708. ValueTree ValueTree::SharedObject::getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const
  14709. {
  14710. for (int i = 0; i < children.size(); ++i)
  14711. if (children.getUnchecked(i)->getProperty (propertyName) == propertyValue)
  14712. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  14713. return ValueTree::invalid;
  14714. }
  14715. bool ValueTree::SharedObject::isAChildOf (const SharedObject* const possibleParent) const
  14716. {
  14717. const SharedObject* p = parent;
  14718. while (p != 0)
  14719. {
  14720. if (p == possibleParent)
  14721. return true;
  14722. p = p->parent;
  14723. }
  14724. return false;
  14725. }
  14726. int ValueTree::SharedObject::indexOf (const ValueTree& child) const
  14727. {
  14728. return children.indexOf (child.object);
  14729. }
  14730. void ValueTree::SharedObject::addChild (SharedObject* child, int index, UndoManager* const undoManager)
  14731. {
  14732. if (child != 0 && child->parent != this)
  14733. {
  14734. if (child != this && ! isAChildOf (child))
  14735. {
  14736. // You should always make sure that a child is removed from its previous parent before
  14737. // adding it somewhere else - otherwise, it's ambiguous as to whether a different
  14738. // undomanager should be used when removing it from its current parent..
  14739. jassert (child->parent == 0);
  14740. if (child->parent != 0)
  14741. {
  14742. jassert (child->parent->children.indexOf (child) >= 0);
  14743. child->parent->removeChild (child->parent->children.indexOf (child), undoManager);
  14744. }
  14745. if (undoManager == 0)
  14746. {
  14747. children.insert (index, child);
  14748. child->parent = this;
  14749. sendChildChangeMessage();
  14750. child->sendParentChangeMessage();
  14751. }
  14752. else
  14753. {
  14754. if (index < 0)
  14755. index = children.size();
  14756. undoManager->perform (new AddOrRemoveChildAction (this, index, child));
  14757. }
  14758. }
  14759. else
  14760. {
  14761. // You're attempting to create a recursive loop! A node
  14762. // can't be a child of one of its own children!
  14763. jassertfalse;
  14764. }
  14765. }
  14766. }
  14767. void ValueTree::SharedObject::removeChild (const int childIndex, UndoManager* const undoManager)
  14768. {
  14769. const SharedObjectPtr child (children [childIndex]);
  14770. if (child != 0)
  14771. {
  14772. if (undoManager == 0)
  14773. {
  14774. children.remove (childIndex);
  14775. child->parent = 0;
  14776. sendChildChangeMessage();
  14777. child->sendParentChangeMessage();
  14778. }
  14779. else
  14780. {
  14781. undoManager->perform (new AddOrRemoveChildAction (this, childIndex, 0));
  14782. }
  14783. }
  14784. }
  14785. void ValueTree::SharedObject::removeAllChildren (UndoManager* const undoManager)
  14786. {
  14787. while (children.size() > 0)
  14788. removeChild (children.size() - 1, undoManager);
  14789. }
  14790. void ValueTree::SharedObject::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  14791. {
  14792. // The source index must be a valid index!
  14793. jassert (((unsigned int) currentIndex) < (unsigned int) children.size());
  14794. if (currentIndex != newIndex
  14795. && ((unsigned int) currentIndex) < (unsigned int) children.size())
  14796. {
  14797. if (undoManager == 0)
  14798. {
  14799. children.move (currentIndex, newIndex);
  14800. sendChildChangeMessage();
  14801. }
  14802. else
  14803. {
  14804. if (((unsigned int) newIndex) >= (unsigned int) children.size())
  14805. newIndex = children.size() - 1;
  14806. undoManager->perform (new MoveChildAction (this, currentIndex, newIndex));
  14807. }
  14808. }
  14809. }
  14810. void ValueTree::SharedObject::reorderChildren (const ReferenceCountedArray <SharedObject>& newOrder, UndoManager* undoManager)
  14811. {
  14812. jassert (newOrder.size() == children.size());
  14813. if (undoManager == 0)
  14814. {
  14815. children = newOrder;
  14816. sendChildChangeMessage();
  14817. }
  14818. else
  14819. {
  14820. for (int i = 0; i < children.size(); ++i)
  14821. {
  14822. if (children.getUnchecked(i) != newOrder.getUnchecked(i))
  14823. {
  14824. jassert (children.contains (newOrder.getUnchecked(i)));
  14825. moveChild (children.indexOf (newOrder.getUnchecked(i)), i, undoManager);
  14826. }
  14827. }
  14828. }
  14829. }
  14830. bool ValueTree::SharedObject::isEquivalentTo (const SharedObject& other) const
  14831. {
  14832. if (type != other.type
  14833. || properties.size() != other.properties.size()
  14834. || children.size() != other.children.size()
  14835. || properties != other.properties)
  14836. return false;
  14837. for (int i = 0; i < children.size(); ++i)
  14838. if (! children.getUnchecked(i)->isEquivalentTo (*other.children.getUnchecked(i)))
  14839. return false;
  14840. return true;
  14841. }
  14842. ValueTree::ValueTree() throw()
  14843. : object (0)
  14844. {
  14845. }
  14846. const ValueTree ValueTree::invalid;
  14847. ValueTree::ValueTree (const Identifier& type_)
  14848. : object (new ValueTree::SharedObject (type_))
  14849. {
  14850. jassert (type_.toString().isNotEmpty()); // All objects should be given a sensible type name!
  14851. }
  14852. ValueTree::ValueTree (SharedObject* const object_)
  14853. : object (object_)
  14854. {
  14855. }
  14856. ValueTree::ValueTree (const ValueTree& other)
  14857. : object (other.object)
  14858. {
  14859. }
  14860. ValueTree& ValueTree::operator= (const ValueTree& other)
  14861. {
  14862. if (listeners.size() > 0)
  14863. {
  14864. if (object != 0)
  14865. object->valueTreesWithListeners.removeValue (this);
  14866. if (other.object != 0)
  14867. other.object->valueTreesWithListeners.add (this);
  14868. }
  14869. object = other.object;
  14870. return *this;
  14871. }
  14872. ValueTree::~ValueTree()
  14873. {
  14874. if (listeners.size() > 0 && object != 0)
  14875. object->valueTreesWithListeners.removeValue (this);
  14876. }
  14877. bool ValueTree::operator== (const ValueTree& other) const throw()
  14878. {
  14879. return object == other.object;
  14880. }
  14881. bool ValueTree::operator!= (const ValueTree& other) const throw()
  14882. {
  14883. return object != other.object;
  14884. }
  14885. bool ValueTree::isEquivalentTo (const ValueTree& other) const
  14886. {
  14887. return object == other.object
  14888. || (object != 0 && other.object != 0 && object->isEquivalentTo (*other.object));
  14889. }
  14890. ValueTree ValueTree::createCopy() const
  14891. {
  14892. return ValueTree (object != 0 ? new SharedObject (*object) : 0);
  14893. }
  14894. bool ValueTree::hasType (const Identifier& typeName) const
  14895. {
  14896. return object != 0 && object->type == typeName;
  14897. }
  14898. const Identifier ValueTree::getType() const
  14899. {
  14900. return object != 0 ? object->type : Identifier();
  14901. }
  14902. ValueTree ValueTree::getParent() const
  14903. {
  14904. return ValueTree (object != 0 ? object->parent : (SharedObject*) 0);
  14905. }
  14906. ValueTree ValueTree::getSibling (const int delta) const
  14907. {
  14908. if (object == 0 || object->parent == 0)
  14909. return invalid;
  14910. const int index = object->parent->indexOf (*this) + delta;
  14911. return ValueTree (static_cast <SharedObject*> (object->parent->children [index]));
  14912. }
  14913. const var& ValueTree::operator[] (const Identifier& name) const
  14914. {
  14915. return object == 0 ? var::null : object->getProperty (name);
  14916. }
  14917. const var& ValueTree::getProperty (const Identifier& name) const
  14918. {
  14919. return object == 0 ? var::null : object->getProperty (name);
  14920. }
  14921. const var ValueTree::getProperty (const Identifier& name, const var& defaultReturnValue) const
  14922. {
  14923. return object == 0 ? defaultReturnValue : object->getProperty (name, defaultReturnValue);
  14924. }
  14925. void ValueTree::setProperty (const Identifier& name, const var& newValue, UndoManager* const undoManager)
  14926. {
  14927. jassert (name.toString().isNotEmpty());
  14928. if (object != 0 && name.toString().isNotEmpty())
  14929. object->setProperty (name, newValue, undoManager);
  14930. }
  14931. bool ValueTree::hasProperty (const Identifier& name) const
  14932. {
  14933. return object != 0 && object->hasProperty (name);
  14934. }
  14935. void ValueTree::removeProperty (const Identifier& name, UndoManager* const undoManager)
  14936. {
  14937. if (object != 0)
  14938. object->removeProperty (name, undoManager);
  14939. }
  14940. void ValueTree::removeAllProperties (UndoManager* const undoManager)
  14941. {
  14942. if (object != 0)
  14943. object->removeAllProperties (undoManager);
  14944. }
  14945. int ValueTree::getNumProperties() const
  14946. {
  14947. return object == 0 ? 0 : object->properties.size();
  14948. }
  14949. const Identifier ValueTree::getPropertyName (const int index) const
  14950. {
  14951. return object == 0 ? Identifier()
  14952. : object->properties.getName (index);
  14953. }
  14954. class ValueTreePropertyValueSource : public Value::ValueSource,
  14955. public ValueTree::Listener
  14956. {
  14957. public:
  14958. ValueTreePropertyValueSource (const ValueTree& tree_,
  14959. const Identifier& property_,
  14960. UndoManager* const undoManager_)
  14961. : tree (tree_),
  14962. property (property_),
  14963. undoManager (undoManager_)
  14964. {
  14965. tree.addListener (this);
  14966. }
  14967. ~ValueTreePropertyValueSource()
  14968. {
  14969. tree.removeListener (this);
  14970. }
  14971. const var getValue() const
  14972. {
  14973. return tree [property];
  14974. }
  14975. void setValue (const var& newValue)
  14976. {
  14977. tree.setProperty (property, newValue, undoManager);
  14978. }
  14979. void valueTreePropertyChanged (ValueTree& treeWhosePropertyHasChanged, const Identifier& changedProperty)
  14980. {
  14981. if (tree == treeWhosePropertyHasChanged && property == changedProperty)
  14982. sendChangeMessage (false);
  14983. }
  14984. void valueTreeChildrenChanged (ValueTree&) {}
  14985. void valueTreeParentChanged (ValueTree&) {}
  14986. private:
  14987. ValueTree tree;
  14988. const Identifier property;
  14989. UndoManager* const undoManager;
  14990. ValueTreePropertyValueSource& operator= (const ValueTreePropertyValueSource&);
  14991. };
  14992. Value ValueTree::getPropertyAsValue (const Identifier& name, UndoManager* const undoManager) const
  14993. {
  14994. return Value (new ValueTreePropertyValueSource (*this, name, undoManager));
  14995. }
  14996. int ValueTree::getNumChildren() const
  14997. {
  14998. return object == 0 ? 0 : object->children.size();
  14999. }
  15000. ValueTree ValueTree::getChild (int index) const
  15001. {
  15002. return ValueTree (object != 0 ? (SharedObject*) object->children [index] : (SharedObject*) 0);
  15003. }
  15004. ValueTree ValueTree::getChildWithName (const Identifier& type) const
  15005. {
  15006. return object != 0 ? object->getChildWithName (type) : ValueTree::invalid;
  15007. }
  15008. ValueTree ValueTree::getOrCreateChildWithName (const Identifier& type, UndoManager* undoManager)
  15009. {
  15010. return object != 0 ? object->getOrCreateChildWithName (type, undoManager) : ValueTree::invalid;
  15011. }
  15012. ValueTree ValueTree::getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const
  15013. {
  15014. return object != 0 ? object->getChildWithProperty (propertyName, propertyValue) : ValueTree::invalid;
  15015. }
  15016. bool ValueTree::isAChildOf (const ValueTree& possibleParent) const
  15017. {
  15018. return object != 0 && object->isAChildOf (possibleParent.object);
  15019. }
  15020. int ValueTree::indexOf (const ValueTree& child) const
  15021. {
  15022. return object != 0 ? object->indexOf (child) : -1;
  15023. }
  15024. void ValueTree::addChild (const ValueTree& child, int index, UndoManager* const undoManager)
  15025. {
  15026. if (object != 0)
  15027. object->addChild (child.object, index, undoManager);
  15028. }
  15029. void ValueTree::removeChild (const int childIndex, UndoManager* const undoManager)
  15030. {
  15031. if (object != 0)
  15032. object->removeChild (childIndex, undoManager);
  15033. }
  15034. void ValueTree::removeChild (const ValueTree& child, UndoManager* const undoManager)
  15035. {
  15036. if (object != 0)
  15037. object->removeChild (object->children.indexOf (child.object), undoManager);
  15038. }
  15039. void ValueTree::removeAllChildren (UndoManager* const undoManager)
  15040. {
  15041. if (object != 0)
  15042. object->removeAllChildren (undoManager);
  15043. }
  15044. void ValueTree::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  15045. {
  15046. if (object != 0)
  15047. object->moveChild (currentIndex, newIndex, undoManager);
  15048. }
  15049. void ValueTree::addListener (Listener* listener)
  15050. {
  15051. if (listener != 0)
  15052. {
  15053. if (listeners.size() == 0 && object != 0)
  15054. object->valueTreesWithListeners.add (this);
  15055. listeners.add (listener);
  15056. }
  15057. }
  15058. void ValueTree::removeListener (Listener* listener)
  15059. {
  15060. listeners.remove (listener);
  15061. if (listeners.size() == 0 && object != 0)
  15062. object->valueTreesWithListeners.removeValue (this);
  15063. }
  15064. XmlElement* ValueTree::SharedObject::createXml() const
  15065. {
  15066. XmlElement* xml = new XmlElement (type.toString());
  15067. int i;
  15068. for (i = 0; i < properties.size(); ++i)
  15069. {
  15070. Identifier name (properties.getName(i));
  15071. const var& v = properties [name];
  15072. jassert (! v.isObject()); // DynamicObjects can't be stored as XML!
  15073. xml->setAttribute (name.toString(), v.toString());
  15074. }
  15075. for (i = 0; i < children.size(); ++i)
  15076. xml->addChildElement (children.getUnchecked(i)->createXml());
  15077. return xml;
  15078. }
  15079. XmlElement* ValueTree::createXml() const
  15080. {
  15081. return object != 0 ? object->createXml() : 0;
  15082. }
  15083. ValueTree ValueTree::fromXml (const XmlElement& xml)
  15084. {
  15085. ValueTree v (xml.getTagName());
  15086. const int numAtts = xml.getNumAttributes(); // xxx inefficient - should write an att iterator..
  15087. for (int i = 0; i < numAtts; ++i)
  15088. v.setProperty (xml.getAttributeName (i), var (xml.getAttributeValue (i)), 0);
  15089. forEachXmlChildElement (xml, e)
  15090. {
  15091. v.addChild (fromXml (*e), -1, 0);
  15092. }
  15093. return v;
  15094. }
  15095. void ValueTree::writeToStream (OutputStream& output)
  15096. {
  15097. output.writeString (getType().toString());
  15098. const int numProps = getNumProperties();
  15099. output.writeCompressedInt (numProps);
  15100. int i;
  15101. for (i = 0; i < numProps; ++i)
  15102. {
  15103. const Identifier name (getPropertyName(i));
  15104. output.writeString (name.toString());
  15105. getProperty(name).writeToStream (output);
  15106. }
  15107. const int numChildren = getNumChildren();
  15108. output.writeCompressedInt (numChildren);
  15109. for (i = 0; i < numChildren; ++i)
  15110. getChild (i).writeToStream (output);
  15111. }
  15112. ValueTree ValueTree::readFromStream (InputStream& input)
  15113. {
  15114. const String type (input.readString());
  15115. if (type.isEmpty())
  15116. return ValueTree::invalid;
  15117. ValueTree v (type);
  15118. const int numProps = input.readCompressedInt();
  15119. if (numProps < 0)
  15120. {
  15121. jassertfalse; // trying to read corrupted data!
  15122. return v;
  15123. }
  15124. int i;
  15125. for (i = 0; i < numProps; ++i)
  15126. {
  15127. const String name (input.readString());
  15128. jassert (name.isNotEmpty());
  15129. const var value (var::readFromStream (input));
  15130. v.setProperty (name, value, 0);
  15131. }
  15132. const int numChildren = input.readCompressedInt();
  15133. for (i = 0; i < numChildren; ++i)
  15134. v.addChild (readFromStream (input), -1, 0);
  15135. return v;
  15136. }
  15137. ValueTree ValueTree::readFromData (const void* const data, const size_t numBytes)
  15138. {
  15139. MemoryInputStream in (data, numBytes, false);
  15140. return readFromStream (in);
  15141. }
  15142. END_JUCE_NAMESPACE
  15143. /*** End of inlined file: juce_ValueTree.cpp ***/
  15144. /*** Start of inlined file: juce_Value.cpp ***/
  15145. BEGIN_JUCE_NAMESPACE
  15146. Value::ValueSource::ValueSource()
  15147. {
  15148. }
  15149. Value::ValueSource::~ValueSource()
  15150. {
  15151. }
  15152. void Value::ValueSource::sendChangeMessage (const bool synchronous)
  15153. {
  15154. if (synchronous)
  15155. {
  15156. for (int i = valuesWithListeners.size(); --i >= 0;)
  15157. {
  15158. Value* const v = valuesWithListeners[i];
  15159. if (v != 0)
  15160. v->callListeners();
  15161. }
  15162. }
  15163. else
  15164. {
  15165. triggerAsyncUpdate();
  15166. }
  15167. }
  15168. void Value::ValueSource::handleAsyncUpdate()
  15169. {
  15170. sendChangeMessage (true);
  15171. }
  15172. class SimpleValueSource : public Value::ValueSource
  15173. {
  15174. public:
  15175. SimpleValueSource()
  15176. {
  15177. }
  15178. SimpleValueSource (const var& initialValue)
  15179. : value (initialValue)
  15180. {
  15181. }
  15182. ~SimpleValueSource()
  15183. {
  15184. }
  15185. const var getValue() const
  15186. {
  15187. return value;
  15188. }
  15189. void setValue (const var& newValue)
  15190. {
  15191. if (newValue != value)
  15192. {
  15193. value = newValue;
  15194. sendChangeMessage (false);
  15195. }
  15196. }
  15197. private:
  15198. var value;
  15199. SimpleValueSource (const SimpleValueSource&);
  15200. SimpleValueSource& operator= (const SimpleValueSource&);
  15201. };
  15202. Value::Value()
  15203. : value (new SimpleValueSource())
  15204. {
  15205. }
  15206. Value::Value (ValueSource* const value_)
  15207. : value (value_)
  15208. {
  15209. jassert (value_ != 0);
  15210. }
  15211. Value::Value (const var& initialValue)
  15212. : value (new SimpleValueSource (initialValue))
  15213. {
  15214. }
  15215. Value::Value (const Value& other)
  15216. : value (other.value)
  15217. {
  15218. }
  15219. Value& Value::operator= (const Value& other)
  15220. {
  15221. value = other.value;
  15222. return *this;
  15223. }
  15224. Value::~Value()
  15225. {
  15226. if (listeners.size() > 0)
  15227. value->valuesWithListeners.removeValue (this);
  15228. }
  15229. const var Value::getValue() const
  15230. {
  15231. return value->getValue();
  15232. }
  15233. Value::operator const var() const
  15234. {
  15235. return getValue();
  15236. }
  15237. void Value::setValue (const var& newValue)
  15238. {
  15239. value->setValue (newValue);
  15240. }
  15241. const String Value::toString() const
  15242. {
  15243. return value->getValue().toString();
  15244. }
  15245. Value& Value::operator= (const var& newValue)
  15246. {
  15247. value->setValue (newValue);
  15248. return *this;
  15249. }
  15250. void Value::referTo (const Value& valueToReferTo)
  15251. {
  15252. if (valueToReferTo.value != value)
  15253. {
  15254. if (listeners.size() > 0)
  15255. {
  15256. value->valuesWithListeners.removeValue (this);
  15257. valueToReferTo.value->valuesWithListeners.add (this);
  15258. }
  15259. value = valueToReferTo.value;
  15260. callListeners();
  15261. }
  15262. }
  15263. bool Value::refersToSameSourceAs (const Value& other) const
  15264. {
  15265. return value == other.value;
  15266. }
  15267. bool Value::operator== (const Value& other) const
  15268. {
  15269. return value == other.value || value->getValue() == other.getValue();
  15270. }
  15271. bool Value::operator!= (const Value& other) const
  15272. {
  15273. return value != other.value && value->getValue() != other.getValue();
  15274. }
  15275. void Value::addListener (Listener* const listener)
  15276. {
  15277. if (listener != 0)
  15278. {
  15279. if (listeners.size() == 0)
  15280. value->valuesWithListeners.add (this);
  15281. listeners.add (listener);
  15282. }
  15283. }
  15284. void Value::removeListener (Listener* const listener)
  15285. {
  15286. listeners.remove (listener);
  15287. if (listeners.size() == 0)
  15288. value->valuesWithListeners.removeValue (this);
  15289. }
  15290. void Value::callListeners()
  15291. {
  15292. Value v (*this); // (create a copy in case this gets deleted by a callback)
  15293. listeners.call (&Value::Listener::valueChanged, v);
  15294. }
  15295. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const Value& value)
  15296. {
  15297. return stream << value.toString();
  15298. }
  15299. END_JUCE_NAMESPACE
  15300. /*** End of inlined file: juce_Value.cpp ***/
  15301. /*** Start of inlined file: juce_Application.cpp ***/
  15302. BEGIN_JUCE_NAMESPACE
  15303. #if JUCE_MAC
  15304. extern void juce_initialiseMacMainMenu();
  15305. #endif
  15306. JUCEApplication::JUCEApplication()
  15307. : appReturnValue (0),
  15308. stillInitialising (true)
  15309. {
  15310. jassert (isStandaloneApp() && appInstance == 0);
  15311. appInstance = this;
  15312. }
  15313. JUCEApplication::~JUCEApplication()
  15314. {
  15315. if (appLock != 0)
  15316. {
  15317. appLock->exit();
  15318. appLock = 0;
  15319. }
  15320. jassert (appInstance == this);
  15321. appInstance = 0;
  15322. }
  15323. JUCEApplication::CreateInstanceFunction JUCEApplication::createInstance = 0;
  15324. JUCEApplication* JUCEApplication::appInstance = 0;
  15325. bool JUCEApplication::moreThanOneInstanceAllowed()
  15326. {
  15327. return true;
  15328. }
  15329. void JUCEApplication::anotherInstanceStarted (const String&)
  15330. {
  15331. }
  15332. void JUCEApplication::systemRequestedQuit()
  15333. {
  15334. quit();
  15335. }
  15336. void JUCEApplication::quit()
  15337. {
  15338. MessageManager::getInstance()->stopDispatchLoop();
  15339. }
  15340. void JUCEApplication::setApplicationReturnValue (const int newReturnValue) throw()
  15341. {
  15342. appReturnValue = newReturnValue;
  15343. }
  15344. void JUCEApplication::actionListenerCallback (const String& message)
  15345. {
  15346. if (message.startsWith (getApplicationName() + "/"))
  15347. anotherInstanceStarted (message.substring (getApplicationName().length() + 1));
  15348. }
  15349. void JUCEApplication::unhandledException (const std::exception*,
  15350. const String&,
  15351. const int)
  15352. {
  15353. jassertfalse;
  15354. }
  15355. void JUCEApplication::sendUnhandledException (const std::exception* const e,
  15356. const char* const sourceFile,
  15357. const int lineNumber)
  15358. {
  15359. if (appInstance != 0)
  15360. appInstance->unhandledException (e, sourceFile, lineNumber);
  15361. }
  15362. ApplicationCommandTarget* JUCEApplication::getNextCommandTarget()
  15363. {
  15364. return 0;
  15365. }
  15366. void JUCEApplication::getAllCommands (Array <CommandID>& commands)
  15367. {
  15368. commands.add (StandardApplicationCommandIDs::quit);
  15369. }
  15370. void JUCEApplication::getCommandInfo (const CommandID commandID, ApplicationCommandInfo& result)
  15371. {
  15372. if (commandID == StandardApplicationCommandIDs::quit)
  15373. {
  15374. result.setInfo (TRANS("Quit"),
  15375. TRANS("Quits the application"),
  15376. "Application",
  15377. 0);
  15378. result.defaultKeypresses.add (KeyPress ('q', ModifierKeys::commandModifier, 0));
  15379. }
  15380. }
  15381. bool JUCEApplication::perform (const InvocationInfo& info)
  15382. {
  15383. if (info.commandID == StandardApplicationCommandIDs::quit)
  15384. {
  15385. systemRequestedQuit();
  15386. return true;
  15387. }
  15388. return false;
  15389. }
  15390. bool JUCEApplication::initialiseApp (const String& commandLine)
  15391. {
  15392. commandLineParameters = commandLine.trim();
  15393. #if ! JUCE_IOS
  15394. jassert (appLock == 0); // initialiseApp must only be called once!
  15395. if (! moreThanOneInstanceAllowed())
  15396. {
  15397. appLock = new InterProcessLock ("juceAppLock_" + getApplicationName());
  15398. if (! appLock->enter(0))
  15399. {
  15400. appLock = 0;
  15401. MessageManager::broadcastMessage (getApplicationName() + "/" + commandLineParameters);
  15402. DBG ("Another instance is running - quitting...");
  15403. return false;
  15404. }
  15405. }
  15406. #endif
  15407. // let the app do its setting-up..
  15408. initialise (commandLineParameters);
  15409. #if JUCE_MAC
  15410. juce_initialiseMacMainMenu(); // needs to be called after the app object has created, to get its name
  15411. #endif
  15412. // register for broadcast new app messages
  15413. MessageManager::getInstance()->registerBroadcastListener (this);
  15414. stillInitialising = false;
  15415. return true;
  15416. }
  15417. int JUCEApplication::shutdownApp()
  15418. {
  15419. jassert (appInstance == this);
  15420. MessageManager::getInstance()->deregisterBroadcastListener (this);
  15421. JUCE_TRY
  15422. {
  15423. // give the app a chance to clean up..
  15424. shutdown();
  15425. }
  15426. JUCE_CATCH_EXCEPTION
  15427. return getApplicationReturnValue();
  15428. }
  15429. // This is called on the Mac and iOS where the OS doesn't allow the stack to unwind on shutdown..
  15430. void JUCEApplication::appWillTerminateByForce()
  15431. {
  15432. {
  15433. const ScopedPointer<JUCEApplication> app (JUCEApplication::getInstance());
  15434. if (app != 0)
  15435. app->shutdownApp();
  15436. }
  15437. shutdownJuce_GUI();
  15438. }
  15439. int JUCEApplication::main (const String& commandLine)
  15440. {
  15441. ScopedJuceInitialiser_GUI libraryInitialiser;
  15442. jassert (createInstance != 0);
  15443. int returnCode = 0;
  15444. {
  15445. const ScopedPointer<JUCEApplication> app (createInstance());
  15446. if (! app->initialiseApp (commandLine))
  15447. return 0;
  15448. JUCE_TRY
  15449. {
  15450. // loop until a quit message is received..
  15451. MessageManager::getInstance()->runDispatchLoop();
  15452. }
  15453. JUCE_CATCH_EXCEPTION
  15454. returnCode = app->shutdownApp();
  15455. }
  15456. return returnCode;
  15457. }
  15458. #if JUCE_IOS
  15459. extern int juce_iOSMain (int argc, const char* argv[]);
  15460. #endif
  15461. #if ! JUCE_WINDOWS
  15462. extern const char* juce_Argv0;
  15463. #endif
  15464. int JUCEApplication::main (int argc, const char* argv[])
  15465. {
  15466. JUCE_AUTORELEASEPOOL
  15467. #if ! JUCE_WINDOWS
  15468. jassert (createInstance != 0);
  15469. juce_Argv0 = argv[0];
  15470. #endif
  15471. #if JUCE_IOS
  15472. return juce_iOSMain (argc, argv);
  15473. #else
  15474. String cmd;
  15475. for (int i = 1; i < argc; ++i)
  15476. cmd << argv[i] << ' ';
  15477. return JUCEApplication::main (cmd);
  15478. #endif
  15479. }
  15480. END_JUCE_NAMESPACE
  15481. /*** End of inlined file: juce_Application.cpp ***/
  15482. /*** Start of inlined file: juce_ApplicationCommandInfo.cpp ***/
  15483. BEGIN_JUCE_NAMESPACE
  15484. ApplicationCommandInfo::ApplicationCommandInfo (const CommandID commandID_) throw()
  15485. : commandID (commandID_),
  15486. flags (0)
  15487. {
  15488. }
  15489. void ApplicationCommandInfo::setInfo (const String& shortName_,
  15490. const String& description_,
  15491. const String& categoryName_,
  15492. const int flags_) throw()
  15493. {
  15494. shortName = shortName_;
  15495. description = description_;
  15496. categoryName = categoryName_;
  15497. flags = flags_;
  15498. }
  15499. void ApplicationCommandInfo::setActive (const bool b) throw()
  15500. {
  15501. if (b)
  15502. flags &= ~isDisabled;
  15503. else
  15504. flags |= isDisabled;
  15505. }
  15506. void ApplicationCommandInfo::setTicked (const bool b) throw()
  15507. {
  15508. if (b)
  15509. flags |= isTicked;
  15510. else
  15511. flags &= ~isTicked;
  15512. }
  15513. void ApplicationCommandInfo::addDefaultKeypress (const int keyCode, const ModifierKeys& modifiers) throw()
  15514. {
  15515. defaultKeypresses.add (KeyPress (keyCode, modifiers, 0));
  15516. }
  15517. END_JUCE_NAMESPACE
  15518. /*** End of inlined file: juce_ApplicationCommandInfo.cpp ***/
  15519. /*** Start of inlined file: juce_ApplicationCommandManager.cpp ***/
  15520. BEGIN_JUCE_NAMESPACE
  15521. ApplicationCommandManager::ApplicationCommandManager()
  15522. : firstTarget (0)
  15523. {
  15524. keyMappings = new KeyPressMappingSet (this);
  15525. Desktop::getInstance().addFocusChangeListener (this);
  15526. }
  15527. ApplicationCommandManager::~ApplicationCommandManager()
  15528. {
  15529. Desktop::getInstance().removeFocusChangeListener (this);
  15530. keyMappings = 0;
  15531. }
  15532. void ApplicationCommandManager::clearCommands()
  15533. {
  15534. commands.clear();
  15535. keyMappings->clearAllKeyPresses();
  15536. triggerAsyncUpdate();
  15537. }
  15538. void ApplicationCommandManager::registerCommand (const ApplicationCommandInfo& newCommand)
  15539. {
  15540. // zero isn't a valid command ID!
  15541. jassert (newCommand.commandID != 0);
  15542. // the name isn't optional!
  15543. jassert (newCommand.shortName.isNotEmpty());
  15544. if (getCommandForID (newCommand.commandID) == 0)
  15545. {
  15546. ApplicationCommandInfo* const newInfo = new ApplicationCommandInfo (newCommand);
  15547. newInfo->flags &= ~ApplicationCommandInfo::isTicked;
  15548. commands.add (newInfo);
  15549. keyMappings->resetToDefaultMapping (newCommand.commandID);
  15550. triggerAsyncUpdate();
  15551. }
  15552. else
  15553. {
  15554. // trying to re-register the same command with different parameters?
  15555. jassert (newCommand.shortName == getCommandForID (newCommand.commandID)->shortName
  15556. && (newCommand.description == getCommandForID (newCommand.commandID)->description || newCommand.description.isEmpty())
  15557. && newCommand.categoryName == getCommandForID (newCommand.commandID)->categoryName
  15558. && newCommand.defaultKeypresses == getCommandForID (newCommand.commandID)->defaultKeypresses
  15559. && (newCommand.flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor))
  15560. == (getCommandForID (newCommand.commandID)->flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor)));
  15561. }
  15562. }
  15563. void ApplicationCommandManager::registerAllCommandsForTarget (ApplicationCommandTarget* target)
  15564. {
  15565. if (target != 0)
  15566. {
  15567. Array <CommandID> commandIDs;
  15568. target->getAllCommands (commandIDs);
  15569. for (int i = 0; i < commandIDs.size(); ++i)
  15570. {
  15571. ApplicationCommandInfo info (commandIDs.getUnchecked(i));
  15572. target->getCommandInfo (info.commandID, info);
  15573. registerCommand (info);
  15574. }
  15575. }
  15576. }
  15577. void ApplicationCommandManager::removeCommand (const CommandID commandID)
  15578. {
  15579. for (int i = commands.size(); --i >= 0;)
  15580. {
  15581. if (commands.getUnchecked (i)->commandID == commandID)
  15582. {
  15583. commands.remove (i);
  15584. triggerAsyncUpdate();
  15585. const Array <KeyPress> keys (keyMappings->getKeyPressesAssignedToCommand (commandID));
  15586. for (int j = keys.size(); --j >= 0;)
  15587. keyMappings->removeKeyPress (keys.getReference (j));
  15588. }
  15589. }
  15590. }
  15591. void ApplicationCommandManager::commandStatusChanged()
  15592. {
  15593. triggerAsyncUpdate();
  15594. }
  15595. const ApplicationCommandInfo* ApplicationCommandManager::getCommandForID (const CommandID commandID) const throw()
  15596. {
  15597. for (int i = commands.size(); --i >= 0;)
  15598. if (commands.getUnchecked(i)->commandID == commandID)
  15599. return commands.getUnchecked(i);
  15600. return 0;
  15601. }
  15602. const String ApplicationCommandManager::getNameOfCommand (const CommandID commandID) const throw()
  15603. {
  15604. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  15605. return (ci != 0) ? ci->shortName : String::empty;
  15606. }
  15607. const String ApplicationCommandManager::getDescriptionOfCommand (const CommandID commandID) const throw()
  15608. {
  15609. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  15610. return (ci != 0) ? (ci->description.isNotEmpty() ? ci->description : ci->shortName)
  15611. : String::empty;
  15612. }
  15613. const StringArray ApplicationCommandManager::getCommandCategories() const
  15614. {
  15615. StringArray s;
  15616. for (int i = 0; i < commands.size(); ++i)
  15617. s.addIfNotAlreadyThere (commands.getUnchecked(i)->categoryName, false);
  15618. return s;
  15619. }
  15620. const Array <CommandID> ApplicationCommandManager::getCommandsInCategory (const String& categoryName) const
  15621. {
  15622. Array <CommandID> results;
  15623. for (int i = 0; i < commands.size(); ++i)
  15624. if (commands.getUnchecked(i)->categoryName == categoryName)
  15625. results.add (commands.getUnchecked(i)->commandID);
  15626. return results;
  15627. }
  15628. bool ApplicationCommandManager::invokeDirectly (const CommandID commandID, const bool asynchronously)
  15629. {
  15630. ApplicationCommandTarget::InvocationInfo info (commandID);
  15631. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  15632. return invoke (info, asynchronously);
  15633. }
  15634. bool ApplicationCommandManager::invoke (const ApplicationCommandTarget::InvocationInfo& info_, const bool asynchronously)
  15635. {
  15636. // This call isn't thread-safe for use from a non-UI thread without locking the message
  15637. // manager first..
  15638. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  15639. ApplicationCommandInfo commandInfo (0);
  15640. ApplicationCommandTarget* const target = getTargetForCommand (info_.commandID, commandInfo);
  15641. if (target == 0)
  15642. return false;
  15643. ApplicationCommandTarget::InvocationInfo info (info_);
  15644. info.commandFlags = commandInfo.flags;
  15645. sendListenerInvokeCallback (info);
  15646. const bool ok = target->invoke (info, asynchronously);
  15647. commandStatusChanged();
  15648. return ok;
  15649. }
  15650. ApplicationCommandTarget* ApplicationCommandManager::getFirstCommandTarget (const CommandID)
  15651. {
  15652. return firstTarget != 0 ? firstTarget
  15653. : findDefaultComponentTarget();
  15654. }
  15655. void ApplicationCommandManager::setFirstCommandTarget (ApplicationCommandTarget* const newTarget) throw()
  15656. {
  15657. firstTarget = newTarget;
  15658. }
  15659. ApplicationCommandTarget* ApplicationCommandManager::getTargetForCommand (const CommandID commandID,
  15660. ApplicationCommandInfo& upToDateInfo)
  15661. {
  15662. ApplicationCommandTarget* target = getFirstCommandTarget (commandID);
  15663. if (target == 0)
  15664. target = JUCEApplication::getInstance();
  15665. if (target != 0)
  15666. target = target->getTargetForCommand (commandID);
  15667. if (target != 0)
  15668. target->getCommandInfo (commandID, upToDateInfo);
  15669. return target;
  15670. }
  15671. ApplicationCommandTarget* ApplicationCommandManager::findTargetForComponent (Component* c)
  15672. {
  15673. ApplicationCommandTarget* target = dynamic_cast <ApplicationCommandTarget*> (c);
  15674. if (target == 0 && c != 0)
  15675. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  15676. target = c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  15677. return target;
  15678. }
  15679. ApplicationCommandTarget* ApplicationCommandManager::findDefaultComponentTarget()
  15680. {
  15681. Component* c = Component::getCurrentlyFocusedComponent();
  15682. if (c == 0)
  15683. {
  15684. TopLevelWindow* const activeWindow = TopLevelWindow::getActiveTopLevelWindow();
  15685. if (activeWindow != 0)
  15686. {
  15687. c = activeWindow->getPeer()->getLastFocusedSubcomponent();
  15688. if (c == 0)
  15689. c = activeWindow;
  15690. }
  15691. }
  15692. if (c == 0 && Process::isForegroundProcess())
  15693. {
  15694. // getting a bit desperate now - try all desktop comps..
  15695. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  15696. {
  15697. ApplicationCommandTarget* const target
  15698. = findTargetForComponent (Desktop::getInstance().getComponent (i)
  15699. ->getPeer()->getLastFocusedSubcomponent());
  15700. if (target != 0)
  15701. return target;
  15702. }
  15703. }
  15704. if (c != 0)
  15705. {
  15706. ResizableWindow* const resizableWindow = dynamic_cast <ResizableWindow*> (c);
  15707. // if we're focused on a ResizableWindow, chances are that it's the content
  15708. // component that really should get the event. And if not, the event will
  15709. // still be passed up to the top level window anyway, so let's send it to the
  15710. // content comp.
  15711. if (resizableWindow != 0 && resizableWindow->getContentComponent() != 0)
  15712. c = resizableWindow->getContentComponent();
  15713. ApplicationCommandTarget* const target = findTargetForComponent (c);
  15714. if (target != 0)
  15715. return target;
  15716. }
  15717. return JUCEApplication::getInstance();
  15718. }
  15719. void ApplicationCommandManager::addListener (ApplicationCommandManagerListener* const listener)
  15720. {
  15721. listeners.add (listener);
  15722. }
  15723. void ApplicationCommandManager::removeListener (ApplicationCommandManagerListener* const listener)
  15724. {
  15725. listeners.remove (listener);
  15726. }
  15727. void ApplicationCommandManager::sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info)
  15728. {
  15729. listeners.call (&ApplicationCommandManagerListener::applicationCommandInvoked, info);
  15730. }
  15731. void ApplicationCommandManager::handleAsyncUpdate()
  15732. {
  15733. listeners.call (&ApplicationCommandManagerListener::applicationCommandListChanged);
  15734. }
  15735. void ApplicationCommandManager::globalFocusChanged (Component*)
  15736. {
  15737. commandStatusChanged();
  15738. }
  15739. END_JUCE_NAMESPACE
  15740. /*** End of inlined file: juce_ApplicationCommandManager.cpp ***/
  15741. /*** Start of inlined file: juce_ApplicationCommandTarget.cpp ***/
  15742. BEGIN_JUCE_NAMESPACE
  15743. ApplicationCommandTarget::ApplicationCommandTarget()
  15744. {
  15745. }
  15746. ApplicationCommandTarget::~ApplicationCommandTarget()
  15747. {
  15748. messageInvoker = 0;
  15749. }
  15750. bool ApplicationCommandTarget::tryToInvoke (const InvocationInfo& info, const bool async)
  15751. {
  15752. if (isCommandActive (info.commandID))
  15753. {
  15754. if (async)
  15755. {
  15756. if (messageInvoker == 0)
  15757. messageInvoker = new CommandTargetMessageInvoker (this);
  15758. messageInvoker->postMessage (new Message (0, 0, 0, new ApplicationCommandTarget::InvocationInfo (info)));
  15759. return true;
  15760. }
  15761. else
  15762. {
  15763. const bool success = perform (info);
  15764. jassert (success); // hmm - your target should have been able to perform this command. If it can't
  15765. // do it at the moment for some reason, it should clear the 'isActive' flag when it
  15766. // returns the command's info.
  15767. return success;
  15768. }
  15769. }
  15770. return false;
  15771. }
  15772. ApplicationCommandTarget* ApplicationCommandTarget::findFirstTargetParentComponent()
  15773. {
  15774. Component* c = dynamic_cast <Component*> (this);
  15775. if (c != 0)
  15776. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  15777. return c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  15778. return 0;
  15779. }
  15780. ApplicationCommandTarget* ApplicationCommandTarget::getTargetForCommand (const CommandID commandID)
  15781. {
  15782. ApplicationCommandTarget* target = this;
  15783. int depth = 0;
  15784. while (target != 0)
  15785. {
  15786. Array <CommandID> commandIDs;
  15787. target->getAllCommands (commandIDs);
  15788. if (commandIDs.contains (commandID))
  15789. return target;
  15790. target = target->getNextCommandTarget();
  15791. ++depth;
  15792. jassert (depth < 100); // could be a recursive command chain??
  15793. jassert (target != this); // definitely a recursive command chain!
  15794. if (depth > 100 || target == this)
  15795. break;
  15796. }
  15797. if (target == 0)
  15798. {
  15799. target = JUCEApplication::getInstance();
  15800. if (target != 0)
  15801. {
  15802. Array <CommandID> commandIDs;
  15803. target->getAllCommands (commandIDs);
  15804. if (commandIDs.contains (commandID))
  15805. return target;
  15806. }
  15807. }
  15808. return 0;
  15809. }
  15810. bool ApplicationCommandTarget::isCommandActive (const CommandID commandID)
  15811. {
  15812. ApplicationCommandInfo info (commandID);
  15813. info.flags = ApplicationCommandInfo::isDisabled;
  15814. getCommandInfo (commandID, info);
  15815. return (info.flags & ApplicationCommandInfo::isDisabled) == 0;
  15816. }
  15817. bool ApplicationCommandTarget::invoke (const InvocationInfo& info, const bool async)
  15818. {
  15819. ApplicationCommandTarget* target = this;
  15820. int depth = 0;
  15821. while (target != 0)
  15822. {
  15823. if (target->tryToInvoke (info, async))
  15824. return true;
  15825. target = target->getNextCommandTarget();
  15826. ++depth;
  15827. jassert (depth < 100); // could be a recursive command chain??
  15828. jassert (target != this); // definitely a recursive command chain!
  15829. if (depth > 100 || target == this)
  15830. break;
  15831. }
  15832. if (target == 0)
  15833. {
  15834. target = JUCEApplication::getInstance();
  15835. if (target != 0)
  15836. return target->tryToInvoke (info, async);
  15837. }
  15838. return false;
  15839. }
  15840. bool ApplicationCommandTarget::invokeDirectly (const CommandID commandID, const bool asynchronously)
  15841. {
  15842. ApplicationCommandTarget::InvocationInfo info (commandID);
  15843. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  15844. return invoke (info, asynchronously);
  15845. }
  15846. ApplicationCommandTarget::InvocationInfo::InvocationInfo (const CommandID commandID_)
  15847. : commandID (commandID_),
  15848. commandFlags (0),
  15849. invocationMethod (direct),
  15850. originatingComponent (0),
  15851. isKeyDown (false),
  15852. millisecsSinceKeyPressed (0)
  15853. {
  15854. }
  15855. ApplicationCommandTarget::CommandTargetMessageInvoker::CommandTargetMessageInvoker (ApplicationCommandTarget* const owner_)
  15856. : owner (owner_)
  15857. {
  15858. }
  15859. ApplicationCommandTarget::CommandTargetMessageInvoker::~CommandTargetMessageInvoker()
  15860. {
  15861. }
  15862. void ApplicationCommandTarget::CommandTargetMessageInvoker::handleMessage (const Message& message)
  15863. {
  15864. const ScopedPointer <InvocationInfo> info (static_cast <InvocationInfo*> (message.pointerParameter));
  15865. owner->tryToInvoke (*info, false);
  15866. }
  15867. END_JUCE_NAMESPACE
  15868. /*** End of inlined file: juce_ApplicationCommandTarget.cpp ***/
  15869. /*** Start of inlined file: juce_ApplicationProperties.cpp ***/
  15870. BEGIN_JUCE_NAMESPACE
  15871. juce_ImplementSingleton (ApplicationProperties)
  15872. ApplicationProperties::ApplicationProperties()
  15873. : msBeforeSaving (3000),
  15874. options (PropertiesFile::storeAsBinary),
  15875. commonSettingsAreReadOnly (0),
  15876. processLock (0)
  15877. {
  15878. }
  15879. ApplicationProperties::~ApplicationProperties()
  15880. {
  15881. closeFiles();
  15882. clearSingletonInstance();
  15883. }
  15884. void ApplicationProperties::setStorageParameters (const String& applicationName,
  15885. const String& fileNameSuffix,
  15886. const String& folderName_,
  15887. const int millisecondsBeforeSaving,
  15888. const int propertiesFileOptions,
  15889. InterProcessLock* processLock_)
  15890. {
  15891. appName = applicationName;
  15892. fileSuffix = fileNameSuffix;
  15893. folderName = folderName_;
  15894. msBeforeSaving = millisecondsBeforeSaving;
  15895. options = propertiesFileOptions;
  15896. processLock = processLock_;
  15897. }
  15898. bool ApplicationProperties::testWriteAccess (const bool testUserSettings,
  15899. const bool testCommonSettings,
  15900. const bool showWarningDialogOnFailure)
  15901. {
  15902. const bool userOk = (! testUserSettings) || getUserSettings()->save();
  15903. const bool commonOk = (! testCommonSettings) || getCommonSettings (false)->save();
  15904. if (! (userOk && commonOk))
  15905. {
  15906. if (showWarningDialogOnFailure)
  15907. {
  15908. String filenames;
  15909. if (userProps != 0 && ! userOk)
  15910. filenames << '\n' << userProps->getFile().getFullPathName();
  15911. if (commonProps != 0 && ! commonOk)
  15912. filenames << '\n' << commonProps->getFile().getFullPathName();
  15913. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  15914. appName + TRANS(" - Unable to save settings"),
  15915. TRANS("An error occurred when trying to save the application's settings file...\n\nIn order to save and restore its settings, ")
  15916. + appName + TRANS(" needs to be able to write to the following files:\n")
  15917. + filenames
  15918. + TRANS("\n\nMake sure that these files aren't read-only, and that the disk isn't full."));
  15919. }
  15920. return false;
  15921. }
  15922. return true;
  15923. }
  15924. void ApplicationProperties::openFiles()
  15925. {
  15926. // You need to call setStorageParameters() before trying to get hold of the
  15927. // properties!
  15928. jassert (appName.isNotEmpty());
  15929. if (appName.isNotEmpty())
  15930. {
  15931. if (userProps == 0)
  15932. userProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  15933. false, msBeforeSaving, options, processLock);
  15934. if (commonProps == 0)
  15935. commonProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  15936. true, msBeforeSaving, options, processLock);
  15937. userProps->setFallbackPropertySet (commonProps);
  15938. }
  15939. }
  15940. PropertiesFile* ApplicationProperties::getUserSettings()
  15941. {
  15942. if (userProps == 0)
  15943. openFiles();
  15944. return userProps;
  15945. }
  15946. PropertiesFile* ApplicationProperties::getCommonSettings (const bool returnUserPropsIfReadOnly)
  15947. {
  15948. if (commonProps == 0)
  15949. openFiles();
  15950. if (returnUserPropsIfReadOnly)
  15951. {
  15952. if (commonSettingsAreReadOnly == 0)
  15953. commonSettingsAreReadOnly = commonProps->save() ? -1 : 1;
  15954. if (commonSettingsAreReadOnly > 0)
  15955. return userProps;
  15956. }
  15957. return commonProps;
  15958. }
  15959. bool ApplicationProperties::saveIfNeeded()
  15960. {
  15961. return (userProps == 0 || userProps->saveIfNeeded())
  15962. && (commonProps == 0 || commonProps->saveIfNeeded());
  15963. }
  15964. void ApplicationProperties::closeFiles()
  15965. {
  15966. userProps = 0;
  15967. commonProps = 0;
  15968. }
  15969. END_JUCE_NAMESPACE
  15970. /*** End of inlined file: juce_ApplicationProperties.cpp ***/
  15971. /*** Start of inlined file: juce_PropertiesFile.cpp ***/
  15972. BEGIN_JUCE_NAMESPACE
  15973. namespace PropertyFileConstants
  15974. {
  15975. static const int magicNumber = (int) ByteOrder::littleEndianInt ("PROP");
  15976. static const int magicNumberCompressed = (int) ByteOrder::littleEndianInt ("CPRP");
  15977. static const char* const fileTag = "PROPERTIES";
  15978. static const char* const valueTag = "VALUE";
  15979. static const char* const nameAttribute = "name";
  15980. static const char* const valueAttribute = "val";
  15981. }
  15982. PropertiesFile::PropertiesFile (const File& f, const int millisecondsBeforeSaving,
  15983. const int options_, InterProcessLock* const processLock_)
  15984. : PropertySet (ignoreCaseOfKeyNames),
  15985. file (f),
  15986. timerInterval (millisecondsBeforeSaving),
  15987. options (options_),
  15988. loadedOk (false),
  15989. needsWriting (false),
  15990. processLock (processLock_)
  15991. {
  15992. // You need to correctly specify just one storage format for the file
  15993. jassert ((options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsBinary
  15994. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsCompressedBinary
  15995. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsXML);
  15996. ProcessScopedLock pl (createProcessLock());
  15997. if (pl != 0 && ! pl->isLocked())
  15998. return; // locking failure..
  15999. ScopedPointer<InputStream> fileStream (f.createInputStream());
  16000. if (fileStream != 0)
  16001. {
  16002. int magicNumber = fileStream->readInt();
  16003. if (magicNumber == PropertyFileConstants::magicNumberCompressed)
  16004. {
  16005. fileStream = new GZIPDecompressorInputStream (new SubregionStream (fileStream.release(), 4, -1, true), true);
  16006. magicNumber = PropertyFileConstants::magicNumber;
  16007. }
  16008. if (magicNumber == PropertyFileConstants::magicNumber)
  16009. {
  16010. loadedOk = true;
  16011. BufferedInputStream in (fileStream.release(), 2048, true);
  16012. int numValues = in.readInt();
  16013. while (--numValues >= 0 && ! in.isExhausted())
  16014. {
  16015. const String key (in.readString());
  16016. const String value (in.readString());
  16017. jassert (key.isNotEmpty());
  16018. if (key.isNotEmpty())
  16019. getAllProperties().set (key, value);
  16020. }
  16021. }
  16022. else
  16023. {
  16024. // Not a binary props file - let's see if it's XML..
  16025. fileStream = 0;
  16026. XmlDocument parser (f);
  16027. ScopedPointer<XmlElement> doc (parser.getDocumentElement (true));
  16028. if (doc != 0 && doc->hasTagName (PropertyFileConstants::fileTag))
  16029. {
  16030. doc = parser.getDocumentElement();
  16031. if (doc != 0)
  16032. {
  16033. loadedOk = true;
  16034. forEachXmlChildElementWithTagName (*doc, e, PropertyFileConstants::valueTag)
  16035. {
  16036. const String name (e->getStringAttribute (PropertyFileConstants::nameAttribute));
  16037. if (name.isNotEmpty())
  16038. {
  16039. getAllProperties().set (name,
  16040. e->getFirstChildElement() != 0
  16041. ? e->getFirstChildElement()->createDocument (String::empty, true)
  16042. : e->getStringAttribute (PropertyFileConstants::valueAttribute));
  16043. }
  16044. }
  16045. }
  16046. else
  16047. {
  16048. // must be a pretty broken XML file we're trying to parse here,
  16049. // or a sign that this object needs an InterProcessLock,
  16050. // or just a failure reading the file. This last reason is why
  16051. // we don't jassertfalse here.
  16052. }
  16053. }
  16054. }
  16055. }
  16056. else
  16057. {
  16058. loadedOk = ! f.exists();
  16059. }
  16060. }
  16061. PropertiesFile::~PropertiesFile()
  16062. {
  16063. if (! saveIfNeeded())
  16064. jassertfalse;
  16065. }
  16066. InterProcessLock::ScopedLockType* PropertiesFile::createProcessLock() const
  16067. {
  16068. return processLock != 0 ? new InterProcessLock::ScopedLockType (*processLock) : 0;
  16069. }
  16070. bool PropertiesFile::saveIfNeeded()
  16071. {
  16072. const ScopedLock sl (getLock());
  16073. return (! needsWriting) || save();
  16074. }
  16075. bool PropertiesFile::needsToBeSaved() const
  16076. {
  16077. const ScopedLock sl (getLock());
  16078. return needsWriting;
  16079. }
  16080. void PropertiesFile::setNeedsToBeSaved (const bool needsToBeSaved_)
  16081. {
  16082. const ScopedLock sl (getLock());
  16083. needsWriting = needsToBeSaved_;
  16084. }
  16085. bool PropertiesFile::save()
  16086. {
  16087. const ScopedLock sl (getLock());
  16088. stopTimer();
  16089. if (file == File::nonexistent
  16090. || file.isDirectory()
  16091. || ! file.getParentDirectory().createDirectory())
  16092. return false;
  16093. if ((options & storeAsXML) != 0)
  16094. {
  16095. XmlElement doc (PropertyFileConstants::fileTag);
  16096. for (int i = 0; i < getAllProperties().size(); ++i)
  16097. {
  16098. XmlElement* const e = doc.createNewChildElement (PropertyFileConstants::valueTag);
  16099. e->setAttribute (PropertyFileConstants::nameAttribute, getAllProperties().getAllKeys() [i]);
  16100. // if the value seems to contain xml, store it as such..
  16101. XmlDocument xmlContent (getAllProperties().getAllValues() [i]);
  16102. XmlElement* const childElement = xmlContent.getDocumentElement();
  16103. if (childElement != 0)
  16104. e->addChildElement (childElement);
  16105. else
  16106. e->setAttribute (PropertyFileConstants::valueAttribute,
  16107. getAllProperties().getAllValues() [i]);
  16108. }
  16109. ProcessScopedLock pl (createProcessLock());
  16110. if (pl != 0 && ! pl->isLocked())
  16111. return false; // locking failure..
  16112. if (doc.writeToFile (file, String::empty))
  16113. {
  16114. needsWriting = false;
  16115. return true;
  16116. }
  16117. }
  16118. else
  16119. {
  16120. ProcessScopedLock pl (createProcessLock());
  16121. if (pl != 0 && ! pl->isLocked())
  16122. return false; // locking failure..
  16123. TemporaryFile tempFile (file);
  16124. ScopedPointer <OutputStream> out (tempFile.getFile().createOutputStream());
  16125. if (out != 0)
  16126. {
  16127. if ((options & storeAsCompressedBinary) != 0)
  16128. {
  16129. out->writeInt (PropertyFileConstants::magicNumberCompressed);
  16130. out->flush();
  16131. out = new GZIPCompressorOutputStream (out.release(), 9, true);
  16132. }
  16133. else
  16134. {
  16135. // have you set up the storage option flags correctly?
  16136. jassert ((options & storeAsBinary) != 0);
  16137. out->writeInt (PropertyFileConstants::magicNumber);
  16138. }
  16139. const int numProperties = getAllProperties().size();
  16140. out->writeInt (numProperties);
  16141. for (int i = 0; i < numProperties; ++i)
  16142. {
  16143. out->writeString (getAllProperties().getAllKeys() [i]);
  16144. out->writeString (getAllProperties().getAllValues() [i]);
  16145. }
  16146. out = 0;
  16147. if (tempFile.overwriteTargetFileWithTemporary())
  16148. {
  16149. needsWriting = false;
  16150. return true;
  16151. }
  16152. }
  16153. }
  16154. return false;
  16155. }
  16156. void PropertiesFile::timerCallback()
  16157. {
  16158. saveIfNeeded();
  16159. }
  16160. void PropertiesFile::propertyChanged()
  16161. {
  16162. sendChangeMessage (this);
  16163. needsWriting = true;
  16164. if (timerInterval > 0)
  16165. startTimer (timerInterval);
  16166. else if (timerInterval == 0)
  16167. saveIfNeeded();
  16168. }
  16169. const File PropertiesFile::getDefaultAppSettingsFile (const String& applicationName,
  16170. const String& fileNameSuffix,
  16171. const String& folderName,
  16172. const bool commonToAllUsers)
  16173. {
  16174. // mustn't have illegal characters in this name..
  16175. jassert (applicationName == File::createLegalFileName (applicationName));
  16176. #if JUCE_MAC || JUCE_IOS
  16177. File dir (commonToAllUsers ? "/Library/Preferences"
  16178. : "~/Library/Preferences");
  16179. if (folderName.isNotEmpty())
  16180. dir = dir.getChildFile (folderName);
  16181. #endif
  16182. #ifdef JUCE_LINUX
  16183. const File dir ((commonToAllUsers ? "/var/" : "~/")
  16184. + (folderName.isNotEmpty() ? folderName
  16185. : ("." + applicationName)));
  16186. #endif
  16187. #if JUCE_WINDOWS
  16188. File dir (File::getSpecialLocation (commonToAllUsers ? File::commonApplicationDataDirectory
  16189. : File::userApplicationDataDirectory));
  16190. if (dir == File::nonexistent)
  16191. return File::nonexistent;
  16192. dir = dir.getChildFile (folderName.isNotEmpty() ? folderName
  16193. : applicationName);
  16194. #endif
  16195. return dir.getChildFile (applicationName)
  16196. .withFileExtension (fileNameSuffix);
  16197. }
  16198. PropertiesFile* PropertiesFile::createDefaultAppPropertiesFile (const String& applicationName,
  16199. const String& fileNameSuffix,
  16200. const String& folderName,
  16201. const bool commonToAllUsers,
  16202. const int millisecondsBeforeSaving,
  16203. const int propertiesFileOptions,
  16204. InterProcessLock* processLock_)
  16205. {
  16206. const File file (getDefaultAppSettingsFile (applicationName,
  16207. fileNameSuffix,
  16208. folderName,
  16209. commonToAllUsers));
  16210. jassert (file != File::nonexistent);
  16211. if (file == File::nonexistent)
  16212. return 0;
  16213. return new PropertiesFile (file, millisecondsBeforeSaving, propertiesFileOptions,processLock_);
  16214. }
  16215. END_JUCE_NAMESPACE
  16216. /*** End of inlined file: juce_PropertiesFile.cpp ***/
  16217. /*** Start of inlined file: juce_FileBasedDocument.cpp ***/
  16218. BEGIN_JUCE_NAMESPACE
  16219. FileBasedDocument::FileBasedDocument (const String& fileExtension_,
  16220. const String& fileWildcard_,
  16221. const String& openFileDialogTitle_,
  16222. const String& saveFileDialogTitle_)
  16223. : changedSinceSave (false),
  16224. fileExtension (fileExtension_),
  16225. fileWildcard (fileWildcard_),
  16226. openFileDialogTitle (openFileDialogTitle_),
  16227. saveFileDialogTitle (saveFileDialogTitle_)
  16228. {
  16229. }
  16230. FileBasedDocument::~FileBasedDocument()
  16231. {
  16232. }
  16233. void FileBasedDocument::setChangedFlag (const bool hasChanged)
  16234. {
  16235. if (changedSinceSave != hasChanged)
  16236. {
  16237. changedSinceSave = hasChanged;
  16238. sendChangeMessage (this);
  16239. }
  16240. }
  16241. void FileBasedDocument::changed()
  16242. {
  16243. changedSinceSave = true;
  16244. sendChangeMessage (this);
  16245. }
  16246. void FileBasedDocument::setFile (const File& newFile)
  16247. {
  16248. if (documentFile != newFile)
  16249. {
  16250. documentFile = newFile;
  16251. changed();
  16252. }
  16253. }
  16254. bool FileBasedDocument::loadFrom (const File& newFile,
  16255. const bool showMessageOnFailure)
  16256. {
  16257. MouseCursor::showWaitCursor();
  16258. const File oldFile (documentFile);
  16259. documentFile = newFile;
  16260. String error;
  16261. if (newFile.existsAsFile())
  16262. {
  16263. error = loadDocument (newFile);
  16264. if (error.isEmpty())
  16265. {
  16266. setChangedFlag (false);
  16267. MouseCursor::hideWaitCursor();
  16268. setLastDocumentOpened (newFile);
  16269. return true;
  16270. }
  16271. }
  16272. else
  16273. {
  16274. error = "The file doesn't exist";
  16275. }
  16276. documentFile = oldFile;
  16277. MouseCursor::hideWaitCursor();
  16278. if (showMessageOnFailure)
  16279. {
  16280. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  16281. TRANS("Failed to open file..."),
  16282. TRANS("There was an error while trying to load the file:\n\n")
  16283. + newFile.getFullPathName()
  16284. + "\n\n"
  16285. + error);
  16286. }
  16287. return false;
  16288. }
  16289. bool FileBasedDocument::loadFromUserSpecifiedFile (const bool showMessageOnFailure)
  16290. {
  16291. FileChooser fc (openFileDialogTitle,
  16292. getLastDocumentOpened(),
  16293. fileWildcard);
  16294. if (fc.browseForFileToOpen())
  16295. return loadFrom (fc.getResult(), showMessageOnFailure);
  16296. return false;
  16297. }
  16298. FileBasedDocument::SaveResult FileBasedDocument::save (const bool askUserForFileIfNotSpecified,
  16299. const bool showMessageOnFailure)
  16300. {
  16301. return saveAs (documentFile,
  16302. false,
  16303. askUserForFileIfNotSpecified,
  16304. showMessageOnFailure);
  16305. }
  16306. FileBasedDocument::SaveResult FileBasedDocument::saveAs (const File& newFile,
  16307. const bool warnAboutOverwritingExistingFiles,
  16308. const bool askUserForFileIfNotSpecified,
  16309. const bool showMessageOnFailure)
  16310. {
  16311. if (newFile == File::nonexistent)
  16312. {
  16313. if (askUserForFileIfNotSpecified)
  16314. {
  16315. return saveAsInteractive (true);
  16316. }
  16317. else
  16318. {
  16319. // can't save to an unspecified file
  16320. jassertfalse;
  16321. return failedToWriteToFile;
  16322. }
  16323. }
  16324. if (warnAboutOverwritingExistingFiles && newFile.exists())
  16325. {
  16326. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  16327. TRANS("File already exists"),
  16328. TRANS("There's already a file called:\n\n")
  16329. + newFile.getFullPathName()
  16330. + TRANS("\n\nAre you sure you want to overwrite it?"),
  16331. TRANS("overwrite"),
  16332. TRANS("cancel")))
  16333. {
  16334. return userCancelledSave;
  16335. }
  16336. }
  16337. MouseCursor::showWaitCursor();
  16338. const File oldFile (documentFile);
  16339. documentFile = newFile;
  16340. String error (saveDocument (newFile));
  16341. if (error.isEmpty())
  16342. {
  16343. setChangedFlag (false);
  16344. MouseCursor::hideWaitCursor();
  16345. return savedOk;
  16346. }
  16347. documentFile = oldFile;
  16348. MouseCursor::hideWaitCursor();
  16349. if (showMessageOnFailure)
  16350. {
  16351. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  16352. TRANS("Error writing to file..."),
  16353. TRANS("An error occurred while trying to save \"")
  16354. + getDocumentTitle()
  16355. + TRANS("\" to the file:\n\n")
  16356. + newFile.getFullPathName()
  16357. + "\n\n"
  16358. + error);
  16359. }
  16360. return failedToWriteToFile;
  16361. }
  16362. FileBasedDocument::SaveResult FileBasedDocument::saveIfNeededAndUserAgrees()
  16363. {
  16364. if (! hasChangedSinceSaved())
  16365. return savedOk;
  16366. const int r = AlertWindow::showYesNoCancelBox (AlertWindow::QuestionIcon,
  16367. TRANS("Closing document..."),
  16368. TRANS("Do you want to save the changes to \"")
  16369. + getDocumentTitle() + "\"?",
  16370. TRANS("save"),
  16371. TRANS("discard changes"),
  16372. TRANS("cancel"));
  16373. if (r == 1)
  16374. {
  16375. // save changes
  16376. return save (true, true);
  16377. }
  16378. else if (r == 2)
  16379. {
  16380. // discard changes
  16381. return savedOk;
  16382. }
  16383. return userCancelledSave;
  16384. }
  16385. FileBasedDocument::SaveResult FileBasedDocument::saveAsInteractive (const bool warnAboutOverwritingExistingFiles)
  16386. {
  16387. File f;
  16388. if (documentFile.existsAsFile())
  16389. f = documentFile;
  16390. else
  16391. f = getLastDocumentOpened();
  16392. String legalFilename (File::createLegalFileName (getDocumentTitle()));
  16393. if (legalFilename.isEmpty())
  16394. legalFilename = "unnamed";
  16395. if (f.existsAsFile() || f.getParentDirectory().isDirectory())
  16396. f = f.getSiblingFile (legalFilename);
  16397. else
  16398. f = File::getSpecialLocation (File::userDocumentsDirectory).getChildFile (legalFilename);
  16399. f = f.withFileExtension (fileExtension)
  16400. .getNonexistentSibling (true);
  16401. FileChooser fc (saveFileDialogTitle, f, fileWildcard);
  16402. if (fc.browseForFileToSave (warnAboutOverwritingExistingFiles))
  16403. {
  16404. File chosen (fc.getResult());
  16405. if (chosen.getFileExtension().isEmpty())
  16406. {
  16407. chosen = chosen.withFileExtension (fileExtension);
  16408. if (chosen.exists())
  16409. {
  16410. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  16411. TRANS("File already exists"),
  16412. TRANS("There's already a file called:")
  16413. + "\n\n" + chosen.getFullPathName()
  16414. + "\n\n" + TRANS("Are you sure you want to overwrite it?"),
  16415. TRANS("overwrite"),
  16416. TRANS("cancel")))
  16417. {
  16418. return userCancelledSave;
  16419. }
  16420. }
  16421. }
  16422. setLastDocumentOpened (chosen);
  16423. return saveAs (chosen, false, false, true);
  16424. }
  16425. return userCancelledSave;
  16426. }
  16427. END_JUCE_NAMESPACE
  16428. /*** End of inlined file: juce_FileBasedDocument.cpp ***/
  16429. /*** Start of inlined file: juce_RecentlyOpenedFilesList.cpp ***/
  16430. BEGIN_JUCE_NAMESPACE
  16431. RecentlyOpenedFilesList::RecentlyOpenedFilesList()
  16432. : maxNumberOfItems (10)
  16433. {
  16434. }
  16435. RecentlyOpenedFilesList::~RecentlyOpenedFilesList()
  16436. {
  16437. }
  16438. void RecentlyOpenedFilesList::setMaxNumberOfItems (const int newMaxNumber)
  16439. {
  16440. maxNumberOfItems = jmax (1, newMaxNumber);
  16441. while (getNumFiles() > maxNumberOfItems)
  16442. files.remove (getNumFiles() - 1);
  16443. }
  16444. int RecentlyOpenedFilesList::getNumFiles() const
  16445. {
  16446. return files.size();
  16447. }
  16448. const File RecentlyOpenedFilesList::getFile (const int index) const
  16449. {
  16450. return File (files [index]);
  16451. }
  16452. void RecentlyOpenedFilesList::clear()
  16453. {
  16454. files.clear();
  16455. }
  16456. void RecentlyOpenedFilesList::addFile (const File& file)
  16457. {
  16458. const String path (file.getFullPathName());
  16459. files.removeString (path, true);
  16460. files.insert (0, path);
  16461. setMaxNumberOfItems (maxNumberOfItems);
  16462. }
  16463. void RecentlyOpenedFilesList::removeNonExistentFiles()
  16464. {
  16465. for (int i = getNumFiles(); --i >= 0;)
  16466. if (! getFile(i).exists())
  16467. files.remove (i);
  16468. }
  16469. int RecentlyOpenedFilesList::createPopupMenuItems (PopupMenu& menuToAddTo,
  16470. const int baseItemId,
  16471. const bool showFullPaths,
  16472. const bool dontAddNonExistentFiles,
  16473. const File** filesToAvoid)
  16474. {
  16475. int num = 0;
  16476. for (int i = 0; i < getNumFiles(); ++i)
  16477. {
  16478. const File f (getFile(i));
  16479. if ((! dontAddNonExistentFiles) || f.exists())
  16480. {
  16481. bool needsAvoiding = false;
  16482. if (filesToAvoid != 0)
  16483. {
  16484. const File** avoid = filesToAvoid;
  16485. while (*avoid != 0)
  16486. {
  16487. if (f == **avoid)
  16488. {
  16489. needsAvoiding = true;
  16490. break;
  16491. }
  16492. ++avoid;
  16493. }
  16494. }
  16495. if (! needsAvoiding)
  16496. {
  16497. menuToAddTo.addItem (baseItemId + i,
  16498. showFullPaths ? f.getFullPathName()
  16499. : f.getFileName());
  16500. ++num;
  16501. }
  16502. }
  16503. }
  16504. return num;
  16505. }
  16506. const String RecentlyOpenedFilesList::toString() const
  16507. {
  16508. return files.joinIntoString ("\n");
  16509. }
  16510. void RecentlyOpenedFilesList::restoreFromString (const String& stringifiedVersion)
  16511. {
  16512. clear();
  16513. files.addLines (stringifiedVersion);
  16514. setMaxNumberOfItems (maxNumberOfItems);
  16515. }
  16516. END_JUCE_NAMESPACE
  16517. /*** End of inlined file: juce_RecentlyOpenedFilesList.cpp ***/
  16518. /*** Start of inlined file: juce_UndoManager.cpp ***/
  16519. BEGIN_JUCE_NAMESPACE
  16520. UndoManager::UndoManager (const int maxNumberOfUnitsToKeep,
  16521. const int minimumTransactions)
  16522. : totalUnitsStored (0),
  16523. nextIndex (0),
  16524. newTransaction (true),
  16525. reentrancyCheck (false)
  16526. {
  16527. setMaxNumberOfStoredUnits (maxNumberOfUnitsToKeep,
  16528. minimumTransactions);
  16529. }
  16530. UndoManager::~UndoManager()
  16531. {
  16532. clearUndoHistory();
  16533. }
  16534. void UndoManager::clearUndoHistory()
  16535. {
  16536. transactions.clear();
  16537. transactionNames.clear();
  16538. totalUnitsStored = 0;
  16539. nextIndex = 0;
  16540. sendChangeMessage (this);
  16541. }
  16542. int UndoManager::getNumberOfUnitsTakenUpByStoredCommands() const
  16543. {
  16544. return totalUnitsStored;
  16545. }
  16546. void UndoManager::setMaxNumberOfStoredUnits (const int maxNumberOfUnitsToKeep,
  16547. const int minimumTransactions)
  16548. {
  16549. maxNumUnitsToKeep = jmax (1, maxNumberOfUnitsToKeep);
  16550. minimumTransactionsToKeep = jmax (1, minimumTransactions);
  16551. }
  16552. bool UndoManager::perform (UndoableAction* const command_, const String& actionName)
  16553. {
  16554. if (command_ != 0)
  16555. {
  16556. ScopedPointer<UndoableAction> command (command_);
  16557. if (actionName.isNotEmpty())
  16558. currentTransactionName = actionName;
  16559. if (reentrancyCheck)
  16560. {
  16561. jassertfalse; // don't call perform() recursively from the UndoableAction::perform() or
  16562. // undo() methods, or else these actions won't actually get done.
  16563. return false;
  16564. }
  16565. else if (command->perform())
  16566. {
  16567. OwnedArray<UndoableAction>* commandSet = transactions [nextIndex - 1];
  16568. if (commandSet != 0 && ! newTransaction)
  16569. {
  16570. UndoableAction* lastAction = commandSet->getLast();
  16571. if (lastAction != 0)
  16572. {
  16573. UndoableAction* coalescedAction = lastAction->createCoalescedAction (command);
  16574. if (coalescedAction != 0)
  16575. {
  16576. command = coalescedAction;
  16577. totalUnitsStored -= lastAction->getSizeInUnits();
  16578. commandSet->removeLast();
  16579. }
  16580. }
  16581. }
  16582. else
  16583. {
  16584. commandSet = new OwnedArray<UndoableAction>();
  16585. transactions.insert (nextIndex, commandSet);
  16586. transactionNames.insert (nextIndex, currentTransactionName);
  16587. ++nextIndex;
  16588. }
  16589. totalUnitsStored += command->getSizeInUnits();
  16590. commandSet->add (command.release());
  16591. newTransaction = false;
  16592. while (nextIndex < transactions.size())
  16593. {
  16594. const OwnedArray <UndoableAction>* const lastSet = transactions.getLast();
  16595. for (int i = lastSet->size(); --i >= 0;)
  16596. totalUnitsStored -= lastSet->getUnchecked (i)->getSizeInUnits();
  16597. transactions.removeLast();
  16598. transactionNames.remove (transactionNames.size() - 1);
  16599. }
  16600. while (nextIndex > 0
  16601. && totalUnitsStored > maxNumUnitsToKeep
  16602. && transactions.size() > minimumTransactionsToKeep)
  16603. {
  16604. const OwnedArray <UndoableAction>* const firstSet = transactions.getFirst();
  16605. for (int i = firstSet->size(); --i >= 0;)
  16606. totalUnitsStored -= firstSet->getUnchecked (i)->getSizeInUnits();
  16607. jassert (totalUnitsStored >= 0); // something fishy going on if this fails!
  16608. transactions.remove (0);
  16609. transactionNames.remove (0);
  16610. --nextIndex;
  16611. }
  16612. sendChangeMessage (this);
  16613. return true;
  16614. }
  16615. }
  16616. return false;
  16617. }
  16618. void UndoManager::beginNewTransaction (const String& actionName)
  16619. {
  16620. newTransaction = true;
  16621. currentTransactionName = actionName;
  16622. }
  16623. void UndoManager::setCurrentTransactionName (const String& newName)
  16624. {
  16625. currentTransactionName = newName;
  16626. }
  16627. bool UndoManager::canUndo() const
  16628. {
  16629. return nextIndex > 0;
  16630. }
  16631. bool UndoManager::canRedo() const
  16632. {
  16633. return nextIndex < transactions.size();
  16634. }
  16635. const String UndoManager::getUndoDescription() const
  16636. {
  16637. return transactionNames [nextIndex - 1];
  16638. }
  16639. const String UndoManager::getRedoDescription() const
  16640. {
  16641. return transactionNames [nextIndex];
  16642. }
  16643. bool UndoManager::undo()
  16644. {
  16645. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex - 1];
  16646. if (commandSet == 0)
  16647. return false;
  16648. reentrancyCheck = true;
  16649. bool failed = false;
  16650. for (int i = commandSet->size(); --i >= 0;)
  16651. {
  16652. if (! commandSet->getUnchecked(i)->undo())
  16653. {
  16654. jassertfalse;
  16655. failed = true;
  16656. break;
  16657. }
  16658. }
  16659. reentrancyCheck = false;
  16660. if (failed)
  16661. clearUndoHistory();
  16662. else
  16663. --nextIndex;
  16664. beginNewTransaction();
  16665. sendChangeMessage (this);
  16666. return true;
  16667. }
  16668. bool UndoManager::redo()
  16669. {
  16670. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex];
  16671. if (commandSet == 0)
  16672. return false;
  16673. reentrancyCheck = true;
  16674. bool failed = false;
  16675. for (int i = 0; i < commandSet->size(); ++i)
  16676. {
  16677. if (! commandSet->getUnchecked(i)->perform())
  16678. {
  16679. jassertfalse;
  16680. failed = true;
  16681. break;
  16682. }
  16683. }
  16684. reentrancyCheck = false;
  16685. if (failed)
  16686. clearUndoHistory();
  16687. else
  16688. ++nextIndex;
  16689. beginNewTransaction();
  16690. sendChangeMessage (this);
  16691. return true;
  16692. }
  16693. bool UndoManager::undoCurrentTransactionOnly()
  16694. {
  16695. return newTransaction ? false : undo();
  16696. }
  16697. void UndoManager::getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const
  16698. {
  16699. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  16700. if (commandSet != 0 && ! newTransaction)
  16701. {
  16702. for (int i = 0; i < commandSet->size(); ++i)
  16703. actionsFound.add (commandSet->getUnchecked(i));
  16704. }
  16705. }
  16706. int UndoManager::getNumActionsInCurrentTransaction() const
  16707. {
  16708. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  16709. if (commandSet != 0 && ! newTransaction)
  16710. return commandSet->size();
  16711. return 0;
  16712. }
  16713. END_JUCE_NAMESPACE
  16714. /*** End of inlined file: juce_UndoManager.cpp ***/
  16715. /*** Start of inlined file: juce_AiffAudioFormat.cpp ***/
  16716. BEGIN_JUCE_NAMESPACE
  16717. static const char* const aiffFormatName = "AIFF file";
  16718. static const char* const aiffExtensions[] = { ".aiff", ".aif", 0 };
  16719. class AiffAudioFormatReader : public AudioFormatReader
  16720. {
  16721. public:
  16722. int bytesPerFrame;
  16723. int64 dataChunkStart;
  16724. bool littleEndian;
  16725. AiffAudioFormatReader (InputStream* in)
  16726. : AudioFormatReader (in, TRANS (aiffFormatName))
  16727. {
  16728. if (input->readInt() == chunkName ("FORM"))
  16729. {
  16730. const int len = input->readIntBigEndian();
  16731. const int64 end = input->getPosition() + len;
  16732. const int nextType = input->readInt();
  16733. if (nextType == chunkName ("AIFF") || nextType == chunkName ("AIFC"))
  16734. {
  16735. bool hasGotVer = false;
  16736. bool hasGotData = false;
  16737. bool hasGotType = false;
  16738. while (input->getPosition() < end)
  16739. {
  16740. const int type = input->readInt();
  16741. const uint32 length = (uint32) input->readIntBigEndian();
  16742. const int64 chunkEnd = input->getPosition() + length;
  16743. if (type == chunkName ("FVER"))
  16744. {
  16745. hasGotVer = true;
  16746. const int ver = input->readIntBigEndian();
  16747. if (ver != 0 && ver != (int) 0xa2805140)
  16748. break;
  16749. }
  16750. else if (type == chunkName ("COMM"))
  16751. {
  16752. hasGotType = true;
  16753. numChannels = (unsigned int) input->readShortBigEndian();
  16754. lengthInSamples = input->readIntBigEndian();
  16755. bitsPerSample = input->readShortBigEndian();
  16756. bytesPerFrame = (numChannels * bitsPerSample) >> 3;
  16757. unsigned char sampleRateBytes[10];
  16758. input->read (sampleRateBytes, 10);
  16759. const int byte0 = sampleRateBytes[0];
  16760. if ((byte0 & 0x80) != 0
  16761. || byte0 <= 0x3F || byte0 > 0x40
  16762. || (byte0 == 0x40 && sampleRateBytes[1] > 0x1C))
  16763. break;
  16764. unsigned int sampRate = ByteOrder::bigEndianInt (sampleRateBytes + 2);
  16765. sampRate >>= (16414 - ByteOrder::bigEndianShort (sampleRateBytes));
  16766. sampleRate = (int) sampRate;
  16767. if (length <= 18)
  16768. {
  16769. // some types don't have a chunk large enough to include a compression
  16770. // type, so assume it's just big-endian pcm
  16771. littleEndian = false;
  16772. }
  16773. else
  16774. {
  16775. const int compType = input->readInt();
  16776. if (compType == chunkName ("NONE") || compType == chunkName ("twos"))
  16777. {
  16778. littleEndian = false;
  16779. }
  16780. else if (compType == chunkName ("sowt"))
  16781. {
  16782. littleEndian = true;
  16783. }
  16784. else
  16785. {
  16786. sampleRate = 0;
  16787. break;
  16788. }
  16789. }
  16790. }
  16791. else if (type == chunkName ("SSND"))
  16792. {
  16793. hasGotData = true;
  16794. const int offset = input->readIntBigEndian();
  16795. dataChunkStart = input->getPosition() + 4 + offset;
  16796. lengthInSamples = (bytesPerFrame > 0) ? jmin (lengthInSamples, (int64) (length / bytesPerFrame)) : 0;
  16797. }
  16798. else if ((hasGotVer && hasGotData && hasGotType)
  16799. || chunkEnd < input->getPosition()
  16800. || input->isExhausted())
  16801. {
  16802. break;
  16803. }
  16804. input->setPosition (chunkEnd);
  16805. }
  16806. }
  16807. }
  16808. }
  16809. ~AiffAudioFormatReader()
  16810. {
  16811. }
  16812. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  16813. int64 startSampleInFile, int numSamples)
  16814. {
  16815. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  16816. if (samplesAvailable < numSamples)
  16817. {
  16818. for (int i = numDestChannels; --i >= 0;)
  16819. if (destSamples[i] != 0)
  16820. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  16821. numSamples = (int) samplesAvailable;
  16822. }
  16823. if (numSamples <= 0)
  16824. return true;
  16825. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  16826. while (numSamples > 0)
  16827. {
  16828. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  16829. char tempBuffer [tempBufSize];
  16830. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  16831. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  16832. if (bytesRead < numThisTime * bytesPerFrame)
  16833. {
  16834. jassert (bytesRead >= 0);
  16835. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  16836. }
  16837. jassert (! usesFloatingPointData); // (would need to add support for this if it's possible)
  16838. if (littleEndian)
  16839. {
  16840. switch (bitsPerSample)
  16841. {
  16842. case 8: ReadHelper<AudioData::Int32, AudioData::Int8, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16843. case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16844. case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16845. case 32: ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16846. default: jassertfalse; break;
  16847. }
  16848. }
  16849. else
  16850. {
  16851. switch (bitsPerSample)
  16852. {
  16853. case 8: ReadHelper<AudioData::Int32, AudioData::Int8, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16854. case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16855. case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16856. case 32: ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16857. default: jassertfalse; break;
  16858. }
  16859. }
  16860. startOffsetInDestBuffer += numThisTime;
  16861. numSamples -= numThisTime;
  16862. }
  16863. return true;
  16864. }
  16865. juce_UseDebuggingNewOperator
  16866. private:
  16867. AiffAudioFormatReader (const AiffAudioFormatReader&);
  16868. AiffAudioFormatReader& operator= (const AiffAudioFormatReader&);
  16869. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  16870. };
  16871. class AiffAudioFormatWriter : public AudioFormatWriter
  16872. {
  16873. public:
  16874. AiffAudioFormatWriter (OutputStream* out, double sampleRate_, unsigned int numChans, int bits)
  16875. : AudioFormatWriter (out, TRANS (aiffFormatName), sampleRate_, numChans, bits),
  16876. lengthInSamples (0),
  16877. bytesWritten (0),
  16878. writeFailed (false)
  16879. {
  16880. headerPosition = out->getPosition();
  16881. writeHeader();
  16882. }
  16883. ~AiffAudioFormatWriter()
  16884. {
  16885. if ((bytesWritten & 1) != 0)
  16886. output->writeByte (0);
  16887. writeHeader();
  16888. }
  16889. bool write (const int** data, int numSamples)
  16890. {
  16891. jassert (data != 0 && *data != 0); // the input must contain at least one channel!
  16892. if (writeFailed)
  16893. return false;
  16894. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  16895. tempBlock.ensureSize (bytes, false);
  16896. switch (bitsPerSample)
  16897. {
  16898. case 8: WriteHelper<AudioData::Int8, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16899. case 16: WriteHelper<AudioData::Int16, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16900. case 24: WriteHelper<AudioData::Int24, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16901. case 32: WriteHelper<AudioData::Int32, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16902. default: jassertfalse; break;
  16903. }
  16904. if (bytesWritten + bytes >= (uint32) 0xfff00000
  16905. || ! output->write (tempBlock.getData(), bytes))
  16906. {
  16907. // failed to write to disk, so let's try writing the header.
  16908. // If it's just run out of disk space, then if it does manage
  16909. // to write the header, we'll still have a useable file..
  16910. writeHeader();
  16911. writeFailed = true;
  16912. return false;
  16913. }
  16914. else
  16915. {
  16916. bytesWritten += bytes;
  16917. lengthInSamples += numSamples;
  16918. return true;
  16919. }
  16920. }
  16921. juce_UseDebuggingNewOperator
  16922. private:
  16923. MemoryBlock tempBlock;
  16924. uint32 lengthInSamples, bytesWritten;
  16925. int64 headerPosition;
  16926. bool writeFailed;
  16927. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  16928. AiffAudioFormatWriter (const AiffAudioFormatWriter&);
  16929. AiffAudioFormatWriter& operator= (const AiffAudioFormatWriter&);
  16930. void writeHeader()
  16931. {
  16932. const bool couldSeekOk = output->setPosition (headerPosition);
  16933. (void) couldSeekOk;
  16934. // if this fails, you've given it an output stream that can't seek! It needs
  16935. // to be able to seek back to write the header
  16936. jassert (couldSeekOk);
  16937. const int headerLen = 54;
  16938. int audioBytes = lengthInSamples * ((bitsPerSample * numChannels) / 8);
  16939. audioBytes += (audioBytes & 1);
  16940. output->writeInt (chunkName ("FORM"));
  16941. output->writeIntBigEndian (headerLen + audioBytes - 8);
  16942. output->writeInt (chunkName ("AIFF"));
  16943. output->writeInt (chunkName ("COMM"));
  16944. output->writeIntBigEndian (18);
  16945. output->writeShortBigEndian ((short) numChannels);
  16946. output->writeIntBigEndian (lengthInSamples);
  16947. output->writeShortBigEndian ((short) bitsPerSample);
  16948. uint8 sampleRateBytes[10];
  16949. zeromem (sampleRateBytes, 10);
  16950. if (sampleRate <= 1)
  16951. {
  16952. sampleRateBytes[0] = 0x3f;
  16953. sampleRateBytes[1] = 0xff;
  16954. sampleRateBytes[2] = 0x80;
  16955. }
  16956. else
  16957. {
  16958. int mask = 0x40000000;
  16959. sampleRateBytes[0] = 0x40;
  16960. if (sampleRate >= mask)
  16961. {
  16962. jassertfalse;
  16963. sampleRateBytes[1] = 0x1d;
  16964. }
  16965. else
  16966. {
  16967. int n = (int) sampleRate;
  16968. int i;
  16969. for (i = 0; i <= 32 ; ++i)
  16970. {
  16971. if ((n & mask) != 0)
  16972. break;
  16973. mask >>= 1;
  16974. }
  16975. n = n << (i + 1);
  16976. sampleRateBytes[1] = (uint8) (29 - i);
  16977. sampleRateBytes[2] = (uint8) ((n >> 24) & 0xff);
  16978. sampleRateBytes[3] = (uint8) ((n >> 16) & 0xff);
  16979. sampleRateBytes[4] = (uint8) ((n >> 8) & 0xff);
  16980. sampleRateBytes[5] = (uint8) (n & 0xff);
  16981. }
  16982. }
  16983. output->write (sampleRateBytes, 10);
  16984. output->writeInt (chunkName ("SSND"));
  16985. output->writeIntBigEndian (audioBytes + 8);
  16986. output->writeInt (0);
  16987. output->writeInt (0);
  16988. jassert (output->getPosition() == headerLen);
  16989. }
  16990. };
  16991. AiffAudioFormat::AiffAudioFormat()
  16992. : AudioFormat (TRANS (aiffFormatName), StringArray (aiffExtensions))
  16993. {
  16994. }
  16995. AiffAudioFormat::~AiffAudioFormat()
  16996. {
  16997. }
  16998. const Array <int> AiffAudioFormat::getPossibleSampleRates()
  16999. {
  17000. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  17001. return Array <int> (rates);
  17002. }
  17003. const Array <int> AiffAudioFormat::getPossibleBitDepths()
  17004. {
  17005. const int depths[] = { 8, 16, 24, 0 };
  17006. return Array <int> (depths);
  17007. }
  17008. bool AiffAudioFormat::canDoStereo() { return true; }
  17009. bool AiffAudioFormat::canDoMono() { return true; }
  17010. #if JUCE_MAC
  17011. bool AiffAudioFormat::canHandleFile (const File& f)
  17012. {
  17013. if (AudioFormat::canHandleFile (f))
  17014. return true;
  17015. const OSType type = PlatformUtilities::getTypeOfFile (f.getFullPathName());
  17016. return type == 'AIFF' || type == 'AIFC'
  17017. || type == 'aiff' || type == 'aifc';
  17018. }
  17019. #endif
  17020. AudioFormatReader* AiffAudioFormat::createReaderFor (InputStream* sourceStream, const bool deleteStreamIfOpeningFails)
  17021. {
  17022. ScopedPointer <AiffAudioFormatReader> w (new AiffAudioFormatReader (sourceStream));
  17023. if (w->sampleRate != 0)
  17024. return w.release();
  17025. if (! deleteStreamIfOpeningFails)
  17026. w->input = 0;
  17027. return 0;
  17028. }
  17029. AudioFormatWriter* AiffAudioFormat::createWriterFor (OutputStream* out,
  17030. double sampleRate,
  17031. unsigned int numberOfChannels,
  17032. int bitsPerSample,
  17033. const StringPairArray& /*metadataValues*/,
  17034. int /*qualityOptionIndex*/)
  17035. {
  17036. if (getPossibleBitDepths().contains (bitsPerSample))
  17037. return new AiffAudioFormatWriter (out, sampleRate, numberOfChannels, bitsPerSample);
  17038. return 0;
  17039. }
  17040. END_JUCE_NAMESPACE
  17041. /*** End of inlined file: juce_AiffAudioFormat.cpp ***/
  17042. /*** Start of inlined file: juce_AudioFormat.cpp ***/
  17043. BEGIN_JUCE_NAMESPACE
  17044. AudioFormat::AudioFormat (const String& name, const StringArray& extensions)
  17045. : formatName (name),
  17046. fileExtensions (extensions)
  17047. {
  17048. }
  17049. AudioFormat::~AudioFormat()
  17050. {
  17051. }
  17052. bool AudioFormat::canHandleFile (const File& f)
  17053. {
  17054. for (int i = 0; i < fileExtensions.size(); ++i)
  17055. if (f.hasFileExtension (fileExtensions[i]))
  17056. return true;
  17057. return false;
  17058. }
  17059. const String& AudioFormat::getFormatName() const { return formatName; }
  17060. const StringArray& AudioFormat::getFileExtensions() const { return fileExtensions; }
  17061. bool AudioFormat::isCompressed() { return false; }
  17062. const StringArray AudioFormat::getQualityOptions() { return StringArray(); }
  17063. END_JUCE_NAMESPACE
  17064. /*** End of inlined file: juce_AudioFormat.cpp ***/
  17065. /*** Start of inlined file: juce_AudioFormatReader.cpp ***/
  17066. BEGIN_JUCE_NAMESPACE
  17067. AudioFormatReader::AudioFormatReader (InputStream* const in,
  17068. const String& formatName_)
  17069. : sampleRate (0),
  17070. bitsPerSample (0),
  17071. lengthInSamples (0),
  17072. numChannels (0),
  17073. usesFloatingPointData (false),
  17074. input (in),
  17075. formatName (formatName_)
  17076. {
  17077. }
  17078. AudioFormatReader::~AudioFormatReader()
  17079. {
  17080. delete input;
  17081. }
  17082. bool AudioFormatReader::read (int* const* destSamples,
  17083. int numDestChannels,
  17084. int64 startSampleInSource,
  17085. int numSamplesToRead,
  17086. const bool fillLeftoverChannelsWithCopies)
  17087. {
  17088. jassert (numDestChannels > 0); // you have to actually give this some channels to work with!
  17089. int startOffsetInDestBuffer = 0;
  17090. if (startSampleInSource < 0)
  17091. {
  17092. const int silence = (int) jmin (-startSampleInSource, (int64) numSamplesToRead);
  17093. for (int i = numDestChannels; --i >= 0;)
  17094. if (destSamples[i] != 0)
  17095. zeromem (destSamples[i], sizeof (int) * silence);
  17096. startOffsetInDestBuffer += silence;
  17097. numSamplesToRead -= silence;
  17098. startSampleInSource = 0;
  17099. }
  17100. if (numSamplesToRead <= 0)
  17101. return true;
  17102. if (! readSamples (const_cast<int**> (destSamples),
  17103. jmin ((int) numChannels, numDestChannels), startOffsetInDestBuffer,
  17104. startSampleInSource, numSamplesToRead))
  17105. return false;
  17106. if (numDestChannels > (int) numChannels)
  17107. {
  17108. if (fillLeftoverChannelsWithCopies)
  17109. {
  17110. int* lastFullChannel = destSamples[0];
  17111. for (int i = (int) numChannels; --i > 0;)
  17112. {
  17113. if (destSamples[i] != 0)
  17114. {
  17115. lastFullChannel = destSamples[i];
  17116. break;
  17117. }
  17118. }
  17119. if (lastFullChannel != 0)
  17120. for (int i = numChannels; i < numDestChannels; ++i)
  17121. if (destSamples[i] != 0)
  17122. memcpy (destSamples[i], lastFullChannel, sizeof (int) * numSamplesToRead);
  17123. }
  17124. else
  17125. {
  17126. for (int i = numChannels; i < numDestChannels; ++i)
  17127. if (destSamples[i] != 0)
  17128. zeromem (destSamples[i], sizeof (int) * numSamplesToRead);
  17129. }
  17130. }
  17131. return true;
  17132. }
  17133. static void findAudioBufferMaxMin (const float* const buffer, const int num, float& maxVal, float& minVal) throw()
  17134. {
  17135. float mn = buffer[0];
  17136. float mx = mn;
  17137. for (int i = 1; i < num; ++i)
  17138. {
  17139. const float s = buffer[i];
  17140. if (s > mx) mx = s;
  17141. if (s < mn) mn = s;
  17142. }
  17143. maxVal = mx;
  17144. minVal = mn;
  17145. }
  17146. void AudioFormatReader::readMaxLevels (int64 startSampleInFile,
  17147. int64 numSamples,
  17148. float& lowestLeft, float& highestLeft,
  17149. float& lowestRight, float& highestRight)
  17150. {
  17151. if (numSamples <= 0)
  17152. {
  17153. lowestLeft = 0;
  17154. lowestRight = 0;
  17155. highestLeft = 0;
  17156. highestRight = 0;
  17157. return;
  17158. }
  17159. const int bufferSize = (int) jmin (numSamples, (int64) 4096);
  17160. HeapBlock<int> tempSpace (bufferSize * 2 + 64);
  17161. int* tempBuffer[3];
  17162. tempBuffer[0] = tempSpace.getData();
  17163. tempBuffer[1] = tempSpace.getData() + bufferSize;
  17164. tempBuffer[2] = 0;
  17165. if (usesFloatingPointData)
  17166. {
  17167. float lmin = 1.0e6f;
  17168. float lmax = -lmin;
  17169. float rmin = lmin;
  17170. float rmax = lmax;
  17171. while (numSamples > 0)
  17172. {
  17173. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  17174. read (tempBuffer, 2, startSampleInFile, numToDo, false);
  17175. numSamples -= numToDo;
  17176. startSampleInFile += numToDo;
  17177. float bufmin, bufmax;
  17178. findAudioBufferMaxMin (reinterpret_cast<float*> (tempBuffer[0]), numToDo, bufmax, bufmin);
  17179. lmin = jmin (lmin, bufmin);
  17180. lmax = jmax (lmax, bufmax);
  17181. if (numChannels > 1)
  17182. {
  17183. findAudioBufferMaxMin (reinterpret_cast<float*> (tempBuffer[1]), numToDo, bufmax, bufmin);
  17184. rmin = jmin (rmin, bufmin);
  17185. rmax = jmax (rmax, bufmax);
  17186. }
  17187. }
  17188. if (numChannels <= 1)
  17189. {
  17190. rmax = lmax;
  17191. rmin = lmin;
  17192. }
  17193. lowestLeft = lmin;
  17194. highestLeft = lmax;
  17195. lowestRight = rmin;
  17196. highestRight = rmax;
  17197. }
  17198. else
  17199. {
  17200. int lmax = std::numeric_limits<int>::min();
  17201. int lmin = std::numeric_limits<int>::max();
  17202. int rmax = std::numeric_limits<int>::min();
  17203. int rmin = std::numeric_limits<int>::max();
  17204. while (numSamples > 0)
  17205. {
  17206. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  17207. read (tempBuffer, 2, startSampleInFile, numToDo, false);
  17208. numSamples -= numToDo;
  17209. startSampleInFile += numToDo;
  17210. for (int j = numChannels; --j >= 0;)
  17211. {
  17212. int bufMax = std::numeric_limits<int>::min();
  17213. int bufMin = std::numeric_limits<int>::max();
  17214. const int* const b = tempBuffer[j];
  17215. for (int i = 0; i < numToDo; ++i)
  17216. {
  17217. const int samp = b[i];
  17218. if (samp < bufMin)
  17219. bufMin = samp;
  17220. if (samp > bufMax)
  17221. bufMax = samp;
  17222. }
  17223. if (j == 0)
  17224. {
  17225. lmax = jmax (lmax, bufMax);
  17226. lmin = jmin (lmin, bufMin);
  17227. }
  17228. else
  17229. {
  17230. rmax = jmax (rmax, bufMax);
  17231. rmin = jmin (rmin, bufMin);
  17232. }
  17233. }
  17234. }
  17235. if (numChannels <= 1)
  17236. {
  17237. rmax = lmax;
  17238. rmin = lmin;
  17239. }
  17240. lowestLeft = lmin / (float) std::numeric_limits<int>::max();
  17241. highestLeft = lmax / (float) std::numeric_limits<int>::max();
  17242. lowestRight = rmin / (float) std::numeric_limits<int>::max();
  17243. highestRight = rmax / (float) std::numeric_limits<int>::max();
  17244. }
  17245. }
  17246. int64 AudioFormatReader::searchForLevel (int64 startSample,
  17247. int64 numSamplesToSearch,
  17248. const double magnitudeRangeMinimum,
  17249. const double magnitudeRangeMaximum,
  17250. const int minimumConsecutiveSamples)
  17251. {
  17252. if (numSamplesToSearch == 0)
  17253. return -1;
  17254. const int bufferSize = 4096;
  17255. HeapBlock<int> tempSpace (bufferSize * 2 + 64);
  17256. int* tempBuffer[3];
  17257. tempBuffer[0] = tempSpace.getData();
  17258. tempBuffer[1] = tempSpace.getData() + bufferSize;
  17259. tempBuffer[2] = 0;
  17260. int consecutive = 0;
  17261. int64 firstMatchPos = -1;
  17262. jassert (magnitudeRangeMaximum > magnitudeRangeMinimum);
  17263. const double doubleMin = jlimit (0.0, (double) std::numeric_limits<int>::max(), magnitudeRangeMinimum * std::numeric_limits<int>::max());
  17264. const double doubleMax = jlimit (doubleMin, (double) std::numeric_limits<int>::max(), magnitudeRangeMaximum * std::numeric_limits<int>::max());
  17265. const int intMagnitudeRangeMinimum = roundToInt (doubleMin);
  17266. const int intMagnitudeRangeMaximum = roundToInt (doubleMax);
  17267. while (numSamplesToSearch != 0)
  17268. {
  17269. const int numThisTime = (int) jmin (abs64 (numSamplesToSearch), (int64) bufferSize);
  17270. int64 bufferStart = startSample;
  17271. if (numSamplesToSearch < 0)
  17272. bufferStart -= numThisTime;
  17273. if (bufferStart >= (int) lengthInSamples)
  17274. break;
  17275. read (tempBuffer, 2, bufferStart, numThisTime, false);
  17276. int num = numThisTime;
  17277. while (--num >= 0)
  17278. {
  17279. if (numSamplesToSearch < 0)
  17280. --startSample;
  17281. bool matches = false;
  17282. const int index = (int) (startSample - bufferStart);
  17283. if (usesFloatingPointData)
  17284. {
  17285. const float sample1 = std::abs (((float*) tempBuffer[0]) [index]);
  17286. if (sample1 >= magnitudeRangeMinimum
  17287. && sample1 <= magnitudeRangeMaximum)
  17288. {
  17289. matches = true;
  17290. }
  17291. else if (numChannels > 1)
  17292. {
  17293. const float sample2 = std::abs (((float*) tempBuffer[1]) [index]);
  17294. matches = (sample2 >= magnitudeRangeMinimum
  17295. && sample2 <= magnitudeRangeMaximum);
  17296. }
  17297. }
  17298. else
  17299. {
  17300. const int sample1 = abs (tempBuffer[0] [index]);
  17301. if (sample1 >= intMagnitudeRangeMinimum
  17302. && sample1 <= intMagnitudeRangeMaximum)
  17303. {
  17304. matches = true;
  17305. }
  17306. else if (numChannels > 1)
  17307. {
  17308. const int sample2 = abs (tempBuffer[1][index]);
  17309. matches = (sample2 >= intMagnitudeRangeMinimum
  17310. && sample2 <= intMagnitudeRangeMaximum);
  17311. }
  17312. }
  17313. if (matches)
  17314. {
  17315. if (firstMatchPos < 0)
  17316. firstMatchPos = startSample;
  17317. if (++consecutive >= minimumConsecutiveSamples)
  17318. {
  17319. if (firstMatchPos < 0 || firstMatchPos >= lengthInSamples)
  17320. return -1;
  17321. return firstMatchPos;
  17322. }
  17323. }
  17324. else
  17325. {
  17326. consecutive = 0;
  17327. firstMatchPos = -1;
  17328. }
  17329. if (numSamplesToSearch > 0)
  17330. ++startSample;
  17331. }
  17332. if (numSamplesToSearch > 0)
  17333. numSamplesToSearch -= numThisTime;
  17334. else
  17335. numSamplesToSearch += numThisTime;
  17336. }
  17337. return -1;
  17338. }
  17339. END_JUCE_NAMESPACE
  17340. /*** End of inlined file: juce_AudioFormatReader.cpp ***/
  17341. /*** Start of inlined file: juce_AudioFormatWriter.cpp ***/
  17342. BEGIN_JUCE_NAMESPACE
  17343. AudioFormatWriter::AudioFormatWriter (OutputStream* const out,
  17344. const String& formatName_,
  17345. const double rate,
  17346. const unsigned int numChannels_,
  17347. const unsigned int bitsPerSample_)
  17348. : sampleRate (rate),
  17349. numChannels (numChannels_),
  17350. bitsPerSample (bitsPerSample_),
  17351. usesFloatingPointData (false),
  17352. output (out),
  17353. formatName (formatName_)
  17354. {
  17355. }
  17356. AudioFormatWriter::~AudioFormatWriter()
  17357. {
  17358. delete output;
  17359. }
  17360. bool AudioFormatWriter::writeFromAudioReader (AudioFormatReader& reader,
  17361. int64 startSample,
  17362. int64 numSamplesToRead)
  17363. {
  17364. const int bufferSize = 16384;
  17365. AudioSampleBuffer tempBuffer (numChannels, bufferSize);
  17366. int* buffers [128];
  17367. zerostruct (buffers);
  17368. for (int i = tempBuffer.getNumChannels(); --i >= 0;)
  17369. buffers[i] = reinterpret_cast<int*> (tempBuffer.getSampleData (i, 0));
  17370. if (numSamplesToRead < 0)
  17371. numSamplesToRead = reader.lengthInSamples;
  17372. while (numSamplesToRead > 0)
  17373. {
  17374. const int numToDo = (int) jmin (numSamplesToRead, (int64) bufferSize);
  17375. if (! reader.read (buffers, numChannels, startSample, numToDo, false))
  17376. return false;
  17377. if (reader.usesFloatingPointData != isFloatingPoint())
  17378. {
  17379. int** bufferChan = buffers;
  17380. while (*bufferChan != 0)
  17381. {
  17382. int* b = *bufferChan++;
  17383. if (isFloatingPoint())
  17384. {
  17385. // int -> float
  17386. const double factor = 1.0 / std::numeric_limits<int>::max();
  17387. for (int i = 0; i < numToDo; ++i)
  17388. ((float*) b)[i] = (float) (factor * b[i]);
  17389. }
  17390. else
  17391. {
  17392. // float -> int
  17393. for (int i = 0; i < numToDo; ++i)
  17394. {
  17395. const double samp = *(const float*) b;
  17396. if (samp <= -1.0)
  17397. *b++ = std::numeric_limits<int>::min();
  17398. else if (samp >= 1.0)
  17399. *b++ = std::numeric_limits<int>::max();
  17400. else
  17401. *b++ = roundToInt (std::numeric_limits<int>::max() * samp);
  17402. }
  17403. }
  17404. }
  17405. }
  17406. if (! write (const_cast<const int**> (buffers), numToDo))
  17407. return false;
  17408. numSamplesToRead -= numToDo;
  17409. startSample += numToDo;
  17410. }
  17411. return true;
  17412. }
  17413. bool AudioFormatWriter::writeFromAudioSource (AudioSource& source, int numSamplesToRead, const int samplesPerBlock)
  17414. {
  17415. AudioSampleBuffer tempBuffer (getNumChannels(), samplesPerBlock);
  17416. while (numSamplesToRead > 0)
  17417. {
  17418. const int numToDo = jmin (numSamplesToRead, samplesPerBlock);
  17419. AudioSourceChannelInfo info;
  17420. info.buffer = &tempBuffer;
  17421. info.startSample = 0;
  17422. info.numSamples = numToDo;
  17423. info.clearActiveBufferRegion();
  17424. source.getNextAudioBlock (info);
  17425. if (! writeFromAudioSampleBuffer (tempBuffer, 0, numToDo))
  17426. return false;
  17427. numSamplesToRead -= numToDo;
  17428. }
  17429. return true;
  17430. }
  17431. bool AudioFormatWriter::writeFromAudioSampleBuffer (const AudioSampleBuffer& source, int startSample, int numSamples)
  17432. {
  17433. jassert (startSample >= 0 && startSample + numSamples <= source.getNumSamples() && source.getNumChannels() > 0);
  17434. if (numSamples <= 0)
  17435. return true;
  17436. HeapBlock<int> tempBuffer;
  17437. HeapBlock<int*> chans (numChannels + 1);
  17438. chans [numChannels] = 0;
  17439. if (isFloatingPoint())
  17440. {
  17441. for (int i = numChannels; --i >= 0;)
  17442. chans[i] = reinterpret_cast<int*> (source.getSampleData (i, startSample));
  17443. }
  17444. else
  17445. {
  17446. tempBuffer.malloc (numSamples * numChannels);
  17447. for (unsigned int i = 0; i < numChannels; ++i)
  17448. {
  17449. typedef AudioData::Pointer <AudioData::Int32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> DestSampleType;
  17450. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> SourceSampleType;
  17451. DestSampleType destData (chans[i] = tempBuffer + i * numSamples);
  17452. SourceSampleType sourceData (source.getSampleData (i, startSample));
  17453. destData.convertSamples (sourceData, numSamples);
  17454. }
  17455. }
  17456. return write ((const int**) chans.getData(), numSamples);
  17457. }
  17458. class AudioFormatWriter::ThreadedWriter::Buffer : public TimeSliceClient,
  17459. public AbstractFifo
  17460. {
  17461. public:
  17462. Buffer (TimeSliceThread& timeSliceThread_, AudioFormatWriter* writer_, int numChannels, int bufferSize)
  17463. : AbstractFifo (bufferSize),
  17464. buffer (numChannels, bufferSize),
  17465. timeSliceThread (timeSliceThread_),
  17466. writer (writer_), isRunning (true)
  17467. {
  17468. timeSliceThread.addTimeSliceClient (this);
  17469. }
  17470. ~Buffer()
  17471. {
  17472. isRunning = false;
  17473. timeSliceThread.removeTimeSliceClient (this);
  17474. while (useTimeSlice())
  17475. {}
  17476. }
  17477. bool write (const float** data, int numSamples)
  17478. {
  17479. if (numSamples <= 0 || ! isRunning)
  17480. return true;
  17481. jassert (timeSliceThread.isThreadRunning()); // you need to get your thread running before pumping data into this!
  17482. int start1, size1, start2, size2;
  17483. prepareToWrite (numSamples, start1, size1, start2, size2);
  17484. if (size1 + size2 < numSamples)
  17485. return false;
  17486. for (int i = buffer.getNumChannels(); --i >= 0;)
  17487. {
  17488. buffer.copyFrom (i, start1, data[i], size1);
  17489. buffer.copyFrom (i, start2, data[i] + size1, size2);
  17490. }
  17491. finishedWrite (size1 + size2);
  17492. timeSliceThread.notify();
  17493. return true;
  17494. }
  17495. bool useTimeSlice()
  17496. {
  17497. const int numToDo = getTotalSize() / 4;
  17498. int start1, size1, start2, size2;
  17499. prepareToRead (numToDo, start1, size1, start2, size2);
  17500. if (size1 <= 0)
  17501. return false;
  17502. writer->writeFromAudioSampleBuffer (buffer, start1, size1);
  17503. if (size2 > 0)
  17504. writer->writeFromAudioSampleBuffer (buffer, start2, size2);
  17505. finishedRead (size1 + size2);
  17506. return true;
  17507. }
  17508. private:
  17509. AudioSampleBuffer buffer;
  17510. TimeSliceThread& timeSliceThread;
  17511. ScopedPointer<AudioFormatWriter> writer;
  17512. volatile bool isRunning;
  17513. Buffer (const Buffer&);
  17514. Buffer& operator= (const Buffer&);
  17515. };
  17516. AudioFormatWriter::ThreadedWriter::ThreadedWriter (AudioFormatWriter* writer, TimeSliceThread& backgroundThread, int numSamplesToBuffer)
  17517. : buffer (new AudioFormatWriter::ThreadedWriter::Buffer (backgroundThread, writer, writer->numChannels, numSamplesToBuffer))
  17518. {
  17519. }
  17520. AudioFormatWriter::ThreadedWriter::~ThreadedWriter()
  17521. {
  17522. }
  17523. bool AudioFormatWriter::ThreadedWriter::write (const float** data, int numSamples)
  17524. {
  17525. return buffer->write (data, numSamples);
  17526. }
  17527. END_JUCE_NAMESPACE
  17528. /*** End of inlined file: juce_AudioFormatWriter.cpp ***/
  17529. /*** Start of inlined file: juce_AudioFormatManager.cpp ***/
  17530. BEGIN_JUCE_NAMESPACE
  17531. AudioFormatManager::AudioFormatManager()
  17532. : defaultFormatIndex (0)
  17533. {
  17534. }
  17535. AudioFormatManager::~AudioFormatManager()
  17536. {
  17537. clearFormats();
  17538. clearSingletonInstance();
  17539. }
  17540. juce_ImplementSingleton (AudioFormatManager);
  17541. void AudioFormatManager::registerFormat (AudioFormat* newFormat,
  17542. const bool makeThisTheDefaultFormat)
  17543. {
  17544. jassert (newFormat != 0);
  17545. if (newFormat != 0)
  17546. {
  17547. #if JUCE_DEBUG
  17548. for (int i = getNumKnownFormats(); --i >= 0;)
  17549. {
  17550. if (getKnownFormat (i)->getFormatName() == newFormat->getFormatName())
  17551. {
  17552. jassertfalse; // trying to add the same format twice!
  17553. }
  17554. }
  17555. #endif
  17556. if (makeThisTheDefaultFormat)
  17557. defaultFormatIndex = getNumKnownFormats();
  17558. knownFormats.add (newFormat);
  17559. }
  17560. }
  17561. void AudioFormatManager::registerBasicFormats()
  17562. {
  17563. #if JUCE_MAC
  17564. registerFormat (new AiffAudioFormat(), true);
  17565. registerFormat (new WavAudioFormat(), false);
  17566. #else
  17567. registerFormat (new WavAudioFormat(), true);
  17568. registerFormat (new AiffAudioFormat(), false);
  17569. #endif
  17570. #if JUCE_USE_FLAC
  17571. registerFormat (new FlacAudioFormat(), false);
  17572. #endif
  17573. #if JUCE_USE_OGGVORBIS
  17574. registerFormat (new OggVorbisAudioFormat(), false);
  17575. #endif
  17576. }
  17577. void AudioFormatManager::clearFormats()
  17578. {
  17579. knownFormats.clear();
  17580. defaultFormatIndex = 0;
  17581. }
  17582. int AudioFormatManager::getNumKnownFormats() const
  17583. {
  17584. return knownFormats.size();
  17585. }
  17586. AudioFormat* AudioFormatManager::getKnownFormat (const int index) const
  17587. {
  17588. return knownFormats [index];
  17589. }
  17590. AudioFormat* AudioFormatManager::getDefaultFormat() const
  17591. {
  17592. return getKnownFormat (defaultFormatIndex);
  17593. }
  17594. AudioFormat* AudioFormatManager::findFormatForFileExtension (const String& fileExtension) const
  17595. {
  17596. String e (fileExtension);
  17597. if (! e.startsWithChar ('.'))
  17598. e = "." + e;
  17599. for (int i = 0; i < getNumKnownFormats(); ++i)
  17600. if (getKnownFormat(i)->getFileExtensions().contains (e, true))
  17601. return getKnownFormat(i);
  17602. return 0;
  17603. }
  17604. const String AudioFormatManager::getWildcardForAllFormats() const
  17605. {
  17606. StringArray allExtensions;
  17607. int i;
  17608. for (i = 0; i < getNumKnownFormats(); ++i)
  17609. allExtensions.addArray (getKnownFormat (i)->getFileExtensions());
  17610. allExtensions.trim();
  17611. allExtensions.removeEmptyStrings();
  17612. String s;
  17613. for (i = 0; i < allExtensions.size(); ++i)
  17614. {
  17615. s << '*';
  17616. if (! allExtensions[i].startsWithChar ('.'))
  17617. s << '.';
  17618. s << allExtensions[i];
  17619. if (i < allExtensions.size() - 1)
  17620. s << ';';
  17621. }
  17622. return s;
  17623. }
  17624. AudioFormatReader* AudioFormatManager::createReaderFor (const File& file)
  17625. {
  17626. // you need to actually register some formats before the manager can
  17627. // use them to open a file!
  17628. jassert (getNumKnownFormats() > 0);
  17629. for (int i = 0; i < getNumKnownFormats(); ++i)
  17630. {
  17631. AudioFormat* const af = getKnownFormat(i);
  17632. if (af->canHandleFile (file))
  17633. {
  17634. InputStream* const in = file.createInputStream();
  17635. if (in != 0)
  17636. {
  17637. AudioFormatReader* const r = af->createReaderFor (in, true);
  17638. if (r != 0)
  17639. return r;
  17640. }
  17641. }
  17642. }
  17643. return 0;
  17644. }
  17645. AudioFormatReader* AudioFormatManager::createReaderFor (InputStream* audioFileStream)
  17646. {
  17647. // you need to actually register some formats before the manager can
  17648. // use them to open a file!
  17649. jassert (getNumKnownFormats() > 0);
  17650. ScopedPointer <InputStream> in (audioFileStream);
  17651. if (in != 0)
  17652. {
  17653. const int64 originalStreamPos = in->getPosition();
  17654. for (int i = 0; i < getNumKnownFormats(); ++i)
  17655. {
  17656. AudioFormatReader* const r = getKnownFormat(i)->createReaderFor (in, false);
  17657. if (r != 0)
  17658. {
  17659. in.release();
  17660. return r;
  17661. }
  17662. in->setPosition (originalStreamPos);
  17663. // the stream that is passed-in must be capable of being repositioned so
  17664. // that all the formats can have a go at opening it.
  17665. jassert (in->getPosition() == originalStreamPos);
  17666. }
  17667. }
  17668. return 0;
  17669. }
  17670. END_JUCE_NAMESPACE
  17671. /*** End of inlined file: juce_AudioFormatManager.cpp ***/
  17672. /*** Start of inlined file: juce_AudioSubsectionReader.cpp ***/
  17673. BEGIN_JUCE_NAMESPACE
  17674. AudioSubsectionReader::AudioSubsectionReader (AudioFormatReader* const source_,
  17675. const int64 startSample_,
  17676. const int64 length_,
  17677. const bool deleteSourceWhenDeleted_)
  17678. : AudioFormatReader (0, source_->getFormatName()),
  17679. source (source_),
  17680. startSample (startSample_),
  17681. deleteSourceWhenDeleted (deleteSourceWhenDeleted_)
  17682. {
  17683. length = jmin (jmax ((int64) 0, source->lengthInSamples - startSample), length_);
  17684. sampleRate = source->sampleRate;
  17685. bitsPerSample = source->bitsPerSample;
  17686. lengthInSamples = length;
  17687. numChannels = source->numChannels;
  17688. usesFloatingPointData = source->usesFloatingPointData;
  17689. }
  17690. AudioSubsectionReader::~AudioSubsectionReader()
  17691. {
  17692. if (deleteSourceWhenDeleted)
  17693. delete source;
  17694. }
  17695. bool AudioSubsectionReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  17696. int64 startSampleInFile, int numSamples)
  17697. {
  17698. if (startSampleInFile + numSamples > length)
  17699. {
  17700. for (int i = numDestChannels; --i >= 0;)
  17701. if (destSamples[i] != 0)
  17702. zeromem (destSamples[i], sizeof (int) * numSamples);
  17703. numSamples = jmin (numSamples, (int) (length - startSampleInFile));
  17704. if (numSamples <= 0)
  17705. return true;
  17706. }
  17707. return source->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer,
  17708. startSampleInFile + startSample, numSamples);
  17709. }
  17710. void AudioSubsectionReader::readMaxLevels (int64 startSampleInFile,
  17711. int64 numSamples,
  17712. float& lowestLeft,
  17713. float& highestLeft,
  17714. float& lowestRight,
  17715. float& highestRight)
  17716. {
  17717. startSampleInFile = jmax ((int64) 0, startSampleInFile);
  17718. numSamples = jmax ((int64) 0, jmin (numSamples, length - startSampleInFile));
  17719. source->readMaxLevels (startSampleInFile + startSample,
  17720. numSamples,
  17721. lowestLeft,
  17722. highestLeft,
  17723. lowestRight,
  17724. highestRight);
  17725. }
  17726. END_JUCE_NAMESPACE
  17727. /*** End of inlined file: juce_AudioSubsectionReader.cpp ***/
  17728. /*** Start of inlined file: juce_AudioThumbnail.cpp ***/
  17729. BEGIN_JUCE_NAMESPACE
  17730. AudioThumbnail::AudioThumbnail (const int orginalSamplesPerThumbnailSample_,
  17731. AudioFormatManager& formatManagerToUse_,
  17732. AudioThumbnailCache& cacheToUse)
  17733. : formatManagerToUse (formatManagerToUse_),
  17734. cache (cacheToUse),
  17735. orginalSamplesPerThumbnailSample (orginalSamplesPerThumbnailSample_),
  17736. timeBeforeDeletingReader (2000)
  17737. {
  17738. clear();
  17739. }
  17740. AudioThumbnail::~AudioThumbnail()
  17741. {
  17742. cache.removeThumbnail (this);
  17743. const ScopedLock sl (readerLock);
  17744. reader = 0;
  17745. }
  17746. AudioThumbnail::DataFormat* AudioThumbnail::getData() const throw()
  17747. {
  17748. jassert (data.getData() != 0);
  17749. return static_cast <DataFormat*> (data.getData());
  17750. }
  17751. void AudioThumbnail::setSource (InputSource* const newSource)
  17752. {
  17753. cache.removeThumbnail (this);
  17754. timerCallback(); // stops the timer and deletes the reader
  17755. source = newSource;
  17756. clear();
  17757. if (newSource != 0
  17758. && ! (cache.loadThumb (*this, newSource->hashCode())
  17759. && isFullyLoaded()))
  17760. {
  17761. {
  17762. const ScopedLock sl (readerLock);
  17763. reader = createReader();
  17764. }
  17765. if (reader != 0)
  17766. {
  17767. initialiseFromAudioFile (*reader);
  17768. cache.addThumbnail (this);
  17769. }
  17770. }
  17771. sendChangeMessage (this);
  17772. }
  17773. bool AudioThumbnail::useTimeSlice()
  17774. {
  17775. const ScopedLock sl (readerLock);
  17776. if (isFullyLoaded())
  17777. {
  17778. if (reader != 0)
  17779. startTimer (timeBeforeDeletingReader);
  17780. cache.removeThumbnail (this);
  17781. return false;
  17782. }
  17783. if (reader == 0)
  17784. reader = createReader();
  17785. if (reader != 0)
  17786. {
  17787. readNextBlockFromAudioFile (*reader);
  17788. stopTimer();
  17789. sendChangeMessage (this);
  17790. const bool justFinished = isFullyLoaded();
  17791. if (justFinished)
  17792. cache.storeThumb (*this, source->hashCode());
  17793. return ! justFinished;
  17794. }
  17795. return false;
  17796. }
  17797. AudioFormatReader* AudioThumbnail::createReader() const
  17798. {
  17799. if (source != 0)
  17800. {
  17801. InputStream* const audioFileStream = source->createInputStream();
  17802. if (audioFileStream != 0)
  17803. return formatManagerToUse.createReaderFor (audioFileStream);
  17804. }
  17805. return 0;
  17806. }
  17807. void AudioThumbnail::timerCallback()
  17808. {
  17809. stopTimer();
  17810. const ScopedLock sl (readerLock);
  17811. reader = 0;
  17812. }
  17813. void AudioThumbnail::clear()
  17814. {
  17815. data.setSize (sizeof (DataFormat) + 3);
  17816. DataFormat* const d = getData();
  17817. d->thumbnailMagic[0] = 'j';
  17818. d->thumbnailMagic[1] = 'a';
  17819. d->thumbnailMagic[2] = 't';
  17820. d->thumbnailMagic[3] = 'm';
  17821. d->samplesPerThumbSample = orginalSamplesPerThumbnailSample;
  17822. d->totalSamples = 0;
  17823. d->numFinishedSamples = 0;
  17824. d->numThumbnailSamples = 0;
  17825. d->numChannels = 0;
  17826. d->sampleRate = 0;
  17827. numSamplesCached = 0;
  17828. cacheNeedsRefilling = true;
  17829. }
  17830. void AudioThumbnail::loadFrom (InputStream& input)
  17831. {
  17832. const ScopedLock sl (readerLock);
  17833. data.setSize (0);
  17834. input.readIntoMemoryBlock (data);
  17835. DataFormat* const d = getData();
  17836. d->flipEndiannessIfBigEndian();
  17837. if (! (d->thumbnailMagic[0] == 'j'
  17838. && d->thumbnailMagic[1] == 'a'
  17839. && d->thumbnailMagic[2] == 't'
  17840. && d->thumbnailMagic[3] == 'm'))
  17841. {
  17842. clear();
  17843. }
  17844. numSamplesCached = 0;
  17845. cacheNeedsRefilling = true;
  17846. }
  17847. void AudioThumbnail::saveTo (OutputStream& output) const
  17848. {
  17849. const ScopedLock sl (readerLock);
  17850. DataFormat* const d = getData();
  17851. d->flipEndiannessIfBigEndian();
  17852. output.write (d, (int) data.getSize());
  17853. d->flipEndiannessIfBigEndian();
  17854. }
  17855. bool AudioThumbnail::initialiseFromAudioFile (AudioFormatReader& fileReader)
  17856. {
  17857. DataFormat* d = getData();
  17858. d->totalSamples = fileReader.lengthInSamples;
  17859. d->numChannels = jmin ((uint32) 2, fileReader.numChannels);
  17860. d->numFinishedSamples = 0;
  17861. d->sampleRate = roundToInt (fileReader.sampleRate);
  17862. d->numThumbnailSamples = (int) (d->totalSamples / d->samplesPerThumbSample) + 1;
  17863. data.setSize (sizeof (DataFormat) + 3 + d->numThumbnailSamples * d->numChannels * 2);
  17864. d = getData();
  17865. zeromem (d->data, d->numThumbnailSamples * d->numChannels * 2);
  17866. return d->totalSamples > 0;
  17867. }
  17868. bool AudioThumbnail::readNextBlockFromAudioFile (AudioFormatReader& fileReader)
  17869. {
  17870. DataFormat* const d = getData();
  17871. if (d->numFinishedSamples < d->totalSamples)
  17872. {
  17873. const int numToDo = (int) jmin ((int64) 65536, d->totalSamples - d->numFinishedSamples);
  17874. generateSection (fileReader,
  17875. d->numFinishedSamples,
  17876. numToDo);
  17877. d->numFinishedSamples += numToDo;
  17878. }
  17879. cacheNeedsRefilling = true;
  17880. return d->numFinishedSamples < d->totalSamples;
  17881. }
  17882. int AudioThumbnail::getNumChannels() const throw()
  17883. {
  17884. return getData()->numChannels;
  17885. }
  17886. double AudioThumbnail::getTotalLength() const throw()
  17887. {
  17888. const DataFormat* const d = getData();
  17889. if (d->sampleRate > 0)
  17890. return d->totalSamples / (double) d->sampleRate;
  17891. else
  17892. return 0.0;
  17893. }
  17894. void AudioThumbnail::generateSection (AudioFormatReader& fileReader,
  17895. int64 startSample,
  17896. int numSamples)
  17897. {
  17898. DataFormat* const d = getData();
  17899. const int firstDataPos = (int) (startSample / d->samplesPerThumbSample);
  17900. const int lastDataPos = (int) ((startSample + numSamples) / d->samplesPerThumbSample);
  17901. char* const l = getChannelData (0);
  17902. char* const r = getChannelData (1);
  17903. for (int i = firstDataPos; i < lastDataPos; ++i)
  17904. {
  17905. const int sourceStart = i * d->samplesPerThumbSample;
  17906. const int sourceEnd = sourceStart + d->samplesPerThumbSample;
  17907. float lowestLeft, highestLeft, lowestRight, highestRight;
  17908. fileReader.readMaxLevels (sourceStart,
  17909. sourceEnd - sourceStart,
  17910. lowestLeft,
  17911. highestLeft,
  17912. lowestRight,
  17913. highestRight);
  17914. int n = i * 2;
  17915. if (r != 0)
  17916. {
  17917. l [n] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  17918. r [n++] = (char) jlimit (-128.0f, 127.0f, lowestRight * 127.0f);
  17919. l [n] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  17920. r [n++] = (char) jlimit (-128.0f, 127.0f, highestRight * 127.0f);
  17921. }
  17922. else
  17923. {
  17924. l [n++] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  17925. l [n++] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  17926. }
  17927. }
  17928. }
  17929. char* AudioThumbnail::getChannelData (int channel) const
  17930. {
  17931. DataFormat* const d = getData();
  17932. if (channel >= 0 && channel < d->numChannels)
  17933. return d->data + (channel * 2 * d->numThumbnailSamples);
  17934. return 0;
  17935. }
  17936. bool AudioThumbnail::isFullyLoaded() const throw()
  17937. {
  17938. const DataFormat* const d = getData();
  17939. return d->numFinishedSamples >= d->totalSamples;
  17940. }
  17941. void AudioThumbnail::refillCache (const int numSamples,
  17942. double startTime,
  17943. const double timePerPixel)
  17944. {
  17945. const DataFormat* const d = getData();
  17946. if (numSamples <= 0
  17947. || timePerPixel <= 0.0
  17948. || d->sampleRate <= 0)
  17949. {
  17950. numSamplesCached = 0;
  17951. cacheNeedsRefilling = true;
  17952. return;
  17953. }
  17954. if (numSamples == numSamplesCached
  17955. && numChannelsCached == d->numChannels
  17956. && startTime == cachedStart
  17957. && timePerPixel == cachedTimePerPixel
  17958. && ! cacheNeedsRefilling)
  17959. {
  17960. return;
  17961. }
  17962. numSamplesCached = numSamples;
  17963. numChannelsCached = d->numChannels;
  17964. cachedStart = startTime;
  17965. cachedTimePerPixel = timePerPixel;
  17966. cachedLevels.ensureSize (2 * numChannelsCached * numSamples);
  17967. const bool needExtraDetail = (timePerPixel * d->sampleRate <= d->samplesPerThumbSample);
  17968. const ScopedLock sl (readerLock);
  17969. cacheNeedsRefilling = false;
  17970. if (needExtraDetail && reader == 0)
  17971. reader = createReader();
  17972. if (reader != 0 && timePerPixel * d->sampleRate <= d->samplesPerThumbSample)
  17973. {
  17974. startTimer (timeBeforeDeletingReader);
  17975. char* cacheData = static_cast <char*> (cachedLevels.getData());
  17976. int sample = roundToInt (startTime * d->sampleRate);
  17977. for (int i = numSamples; --i >= 0;)
  17978. {
  17979. const int nextSample = roundToInt ((startTime + timePerPixel) * d->sampleRate);
  17980. if (sample >= 0)
  17981. {
  17982. if (sample >= reader->lengthInSamples)
  17983. break;
  17984. float lmin, lmax, rmin, rmax;
  17985. reader->readMaxLevels (sample,
  17986. jmax (1, nextSample - sample),
  17987. lmin, lmax, rmin, rmax);
  17988. cacheData[0] = (char) jlimit (-128, 127, roundFloatToInt (lmin * 127.0f));
  17989. cacheData[1] = (char) jlimit (-128, 127, roundFloatToInt (lmax * 127.0f));
  17990. if (numChannelsCached > 1)
  17991. {
  17992. cacheData[2] = (char) jlimit (-128, 127, roundFloatToInt (rmin * 127.0f));
  17993. cacheData[3] = (char) jlimit (-128, 127, roundFloatToInt (rmax * 127.0f));
  17994. }
  17995. cacheData += 2 * numChannelsCached;
  17996. }
  17997. startTime += timePerPixel;
  17998. sample = nextSample;
  17999. }
  18000. }
  18001. else
  18002. {
  18003. for (int channelNum = 0; channelNum < numChannelsCached; ++channelNum)
  18004. {
  18005. char* const channelData = getChannelData (channelNum);
  18006. char* cacheData = static_cast <char*> (cachedLevels.getData()) + channelNum * 2;
  18007. const double timeToThumbSampleFactor = d->sampleRate / (double) d->samplesPerThumbSample;
  18008. startTime = cachedStart;
  18009. int sample = roundToInt (startTime * timeToThumbSampleFactor);
  18010. const int numFinished = (int) (d->numFinishedSamples / d->samplesPerThumbSample);
  18011. for (int i = numSamples; --i >= 0;)
  18012. {
  18013. const int nextSample = roundToInt ((startTime + timePerPixel) * timeToThumbSampleFactor);
  18014. if (sample >= 0 && channelData != 0)
  18015. {
  18016. char mx = -128;
  18017. char mn = 127;
  18018. while (sample <= nextSample)
  18019. {
  18020. if (sample >= numFinished)
  18021. break;
  18022. const int n = sample << 1;
  18023. const char sampMin = channelData [n];
  18024. const char sampMax = channelData [n + 1];
  18025. if (sampMin < mn)
  18026. mn = sampMin;
  18027. if (sampMax > mx)
  18028. mx = sampMax;
  18029. ++sample;
  18030. }
  18031. if (mn <= mx)
  18032. {
  18033. cacheData[0] = mn;
  18034. cacheData[1] = mx;
  18035. }
  18036. else
  18037. {
  18038. cacheData[0] = 1;
  18039. cacheData[1] = 0;
  18040. }
  18041. }
  18042. else
  18043. {
  18044. cacheData[0] = 1;
  18045. cacheData[1] = 0;
  18046. }
  18047. cacheData += numChannelsCached * 2;
  18048. startTime += timePerPixel;
  18049. sample = nextSample;
  18050. }
  18051. }
  18052. }
  18053. }
  18054. void AudioThumbnail::drawChannel (Graphics& g,
  18055. int x, int y, int w, int h,
  18056. double startTime,
  18057. double endTime,
  18058. int channelNum,
  18059. const float verticalZoomFactor)
  18060. {
  18061. refillCache (w, startTime, (endTime - startTime) / w);
  18062. if (numSamplesCached >= w
  18063. && channelNum >= 0
  18064. && channelNum < numChannelsCached)
  18065. {
  18066. const float topY = (float) y;
  18067. const float bottomY = topY + h;
  18068. const float midY = topY + h * 0.5f;
  18069. const float vscale = verticalZoomFactor * h / 256.0f;
  18070. const Rectangle<int> clip (g.getClipBounds());
  18071. const int skipLeft = jlimit (0, w, clip.getX() - x);
  18072. w -= skipLeft;
  18073. x += skipLeft;
  18074. const char* cacheData = static_cast <const char*> (cachedLevels.getData())
  18075. + (channelNum << 1)
  18076. + skipLeft * (numChannelsCached << 1);
  18077. while (--w >= 0)
  18078. {
  18079. const char mn = cacheData[0];
  18080. const char mx = cacheData[1];
  18081. cacheData += numChannelsCached << 1;
  18082. if (mn <= mx) // if the wrong way round, signifies that the sample's not yet known
  18083. g.drawVerticalLine (x, jmax (midY - mx * vscale - 0.3f, topY),
  18084. jmin (midY - mn * vscale + 0.3f, bottomY));
  18085. if (++x >= clip.getRight())
  18086. break;
  18087. }
  18088. }
  18089. }
  18090. void AudioThumbnail::DataFormat::flipEndiannessIfBigEndian() throw()
  18091. {
  18092. #if JUCE_BIG_ENDIAN
  18093. struct Flipper
  18094. {
  18095. static void flip (int32& n) { n = (int32) ByteOrder::swap ((uint32) n); }
  18096. static void flip (int64& n) { n = (int64) ByteOrder::swap ((uint64) n); }
  18097. };
  18098. Flipper::flip (samplesPerThumbSample);
  18099. Flipper::flip (totalSamples);
  18100. Flipper::flip (numFinishedSamples);
  18101. Flipper::flip (numThumbnailSamples);
  18102. Flipper::flip (numChannels);
  18103. Flipper::flip (sampleRate);
  18104. #endif
  18105. }
  18106. END_JUCE_NAMESPACE
  18107. /*** End of inlined file: juce_AudioThumbnail.cpp ***/
  18108. /*** Start of inlined file: juce_AudioThumbnailCache.cpp ***/
  18109. BEGIN_JUCE_NAMESPACE
  18110. struct ThumbnailCacheEntry
  18111. {
  18112. int64 hash;
  18113. uint32 lastUsed;
  18114. MemoryBlock data;
  18115. juce_UseDebuggingNewOperator
  18116. };
  18117. AudioThumbnailCache::AudioThumbnailCache (const int maxNumThumbsToStore_)
  18118. : TimeSliceThread ("thumb cache"),
  18119. maxNumThumbsToStore (maxNumThumbsToStore_)
  18120. {
  18121. startThread (2);
  18122. }
  18123. AudioThumbnailCache::~AudioThumbnailCache()
  18124. {
  18125. }
  18126. bool AudioThumbnailCache::loadThumb (AudioThumbnail& thumb, const int64 hashCode)
  18127. {
  18128. for (int i = thumbs.size(); --i >= 0;)
  18129. {
  18130. if (thumbs[i]->hash == hashCode)
  18131. {
  18132. MemoryInputStream in (thumbs[i]->data, false);
  18133. thumb.loadFrom (in);
  18134. thumbs[i]->lastUsed = Time::getMillisecondCounter();
  18135. return true;
  18136. }
  18137. }
  18138. return false;
  18139. }
  18140. void AudioThumbnailCache::storeThumb (const AudioThumbnail& thumb,
  18141. const int64 hashCode)
  18142. {
  18143. MemoryOutputStream out;
  18144. thumb.saveTo (out);
  18145. ThumbnailCacheEntry* te = 0;
  18146. for (int i = thumbs.size(); --i >= 0;)
  18147. {
  18148. if (thumbs[i]->hash == hashCode)
  18149. {
  18150. te = thumbs[i];
  18151. break;
  18152. }
  18153. }
  18154. if (te == 0)
  18155. {
  18156. te = new ThumbnailCacheEntry();
  18157. te->hash = hashCode;
  18158. if (thumbs.size() < maxNumThumbsToStore)
  18159. {
  18160. thumbs.add (te);
  18161. }
  18162. else
  18163. {
  18164. int oldest = 0;
  18165. unsigned int oldestTime = Time::getMillisecondCounter() + 1;
  18166. int i;
  18167. for (i = thumbs.size(); --i >= 0;)
  18168. if (thumbs[i]->lastUsed < oldestTime)
  18169. oldest = i;
  18170. thumbs.set (i, te);
  18171. }
  18172. }
  18173. te->lastUsed = Time::getMillisecondCounter();
  18174. te->data.setSize (0);
  18175. te->data.append (out.getData(), out.getDataSize());
  18176. }
  18177. void AudioThumbnailCache::clear()
  18178. {
  18179. thumbs.clear();
  18180. }
  18181. void AudioThumbnailCache::addThumbnail (AudioThumbnail* const thumb)
  18182. {
  18183. addTimeSliceClient (thumb);
  18184. }
  18185. void AudioThumbnailCache::removeThumbnail (AudioThumbnail* const thumb)
  18186. {
  18187. removeTimeSliceClient (thumb);
  18188. }
  18189. END_JUCE_NAMESPACE
  18190. /*** End of inlined file: juce_AudioThumbnailCache.cpp ***/
  18191. /*** Start of inlined file: juce_QuickTimeAudioFormat.cpp ***/
  18192. #if JUCE_QUICKTIME && ! (JUCE_64BIT || JUCE_IOS)
  18193. #if ! JUCE_WINDOWS
  18194. #include <QuickTime/Movies.h>
  18195. #include <QuickTime/QTML.h>
  18196. #include <QuickTime/QuickTimeComponents.h>
  18197. #include <QuickTime/MediaHandlers.h>
  18198. #include <QuickTime/ImageCodec.h>
  18199. #else
  18200. #if JUCE_MSVC
  18201. #pragma warning (push)
  18202. #pragma warning (disable : 4100)
  18203. #endif
  18204. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  18205. add its header directory to your include path.
  18206. Alternatively, if you don't need any QuickTime services, just turn off the JUCE_QUICKTIME
  18207. flag in juce_Config.h
  18208. */
  18209. #include <Movies.h>
  18210. #include <QTML.h>
  18211. #include <QuickTimeComponents.h>
  18212. #include <MediaHandlers.h>
  18213. #include <ImageCodec.h>
  18214. #if JUCE_MSVC
  18215. #pragma warning (pop)
  18216. #endif
  18217. #endif
  18218. BEGIN_JUCE_NAMESPACE
  18219. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  18220. static const char* const quickTimeFormatName = "QuickTime file";
  18221. static const char* const quickTimeExtensions[] = { ".mov", ".mp3", ".mp4", ".m4a", 0 };
  18222. class QTAudioReader : public AudioFormatReader
  18223. {
  18224. public:
  18225. QTAudioReader (InputStream* const input_, const int trackNum_)
  18226. : AudioFormatReader (input_, TRANS (quickTimeFormatName)),
  18227. ok (false),
  18228. movie (0),
  18229. trackNum (trackNum_),
  18230. lastSampleRead (0),
  18231. lastThreadId (0),
  18232. extractor (0),
  18233. dataHandle (0)
  18234. {
  18235. JUCE_AUTORELEASEPOOL
  18236. bufferList.calloc (256, 1);
  18237. #if JUCE_WINDOWS
  18238. if (InitializeQTML (0) != noErr)
  18239. return;
  18240. #endif
  18241. if (EnterMovies() != noErr)
  18242. return;
  18243. bool opened = juce_OpenQuickTimeMovieFromStream (input_, movie, dataHandle);
  18244. if (! opened)
  18245. return;
  18246. {
  18247. const int numTracks = GetMovieTrackCount (movie);
  18248. int trackCount = 0;
  18249. for (int i = 1; i <= numTracks; ++i)
  18250. {
  18251. track = GetMovieIndTrack (movie, i);
  18252. media = GetTrackMedia (track);
  18253. OSType mediaType;
  18254. GetMediaHandlerDescription (media, &mediaType, 0, 0);
  18255. if (mediaType == SoundMediaType
  18256. && trackCount++ == trackNum_)
  18257. {
  18258. ok = true;
  18259. break;
  18260. }
  18261. }
  18262. }
  18263. if (! ok)
  18264. return;
  18265. ok = false;
  18266. lengthInSamples = GetMediaDecodeDuration (media);
  18267. usesFloatingPointData = false;
  18268. samplesPerFrame = (int) (GetMediaDecodeDuration (media) / GetMediaSampleCount (media));
  18269. trackUnitsPerFrame = GetMovieTimeScale (movie) * samplesPerFrame
  18270. / GetMediaTimeScale (media);
  18271. OSStatus err = MovieAudioExtractionBegin (movie, 0, &extractor);
  18272. unsigned long output_layout_size;
  18273. err = MovieAudioExtractionGetPropertyInfo (extractor,
  18274. kQTPropertyClass_MovieAudioExtraction_Audio,
  18275. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  18276. 0, &output_layout_size, 0);
  18277. if (err != noErr)
  18278. return;
  18279. HeapBlock <AudioChannelLayout> qt_audio_channel_layout;
  18280. qt_audio_channel_layout.calloc (output_layout_size, 1);
  18281. err = MovieAudioExtractionGetProperty (extractor,
  18282. kQTPropertyClass_MovieAudioExtraction_Audio,
  18283. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  18284. output_layout_size, qt_audio_channel_layout, 0);
  18285. qt_audio_channel_layout[0].mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  18286. err = MovieAudioExtractionSetProperty (extractor,
  18287. kQTPropertyClass_MovieAudioExtraction_Audio,
  18288. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  18289. output_layout_size,
  18290. qt_audio_channel_layout);
  18291. err = MovieAudioExtractionGetProperty (extractor,
  18292. kQTPropertyClass_MovieAudioExtraction_Audio,
  18293. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  18294. sizeof (inputStreamDesc),
  18295. &inputStreamDesc, 0);
  18296. if (err != noErr)
  18297. return;
  18298. inputStreamDesc.mFormatFlags = kAudioFormatFlagIsSignedInteger
  18299. | kAudioFormatFlagIsPacked
  18300. | kAudioFormatFlagsNativeEndian;
  18301. inputStreamDesc.mBitsPerChannel = sizeof (SInt16) * 8;
  18302. inputStreamDesc.mChannelsPerFrame = jmin ((UInt32) 2, inputStreamDesc.mChannelsPerFrame);
  18303. inputStreamDesc.mBytesPerFrame = sizeof (SInt16) * inputStreamDesc.mChannelsPerFrame;
  18304. inputStreamDesc.mBytesPerPacket = inputStreamDesc.mBytesPerFrame;
  18305. err = MovieAudioExtractionSetProperty (extractor,
  18306. kQTPropertyClass_MovieAudioExtraction_Audio,
  18307. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  18308. sizeof (inputStreamDesc),
  18309. &inputStreamDesc);
  18310. if (err != noErr)
  18311. return;
  18312. Boolean allChannelsDiscrete = false;
  18313. err = MovieAudioExtractionSetProperty (extractor,
  18314. kQTPropertyClass_MovieAudioExtraction_Movie,
  18315. kQTMovieAudioExtractionMoviePropertyID_AllChannelsDiscrete,
  18316. sizeof (allChannelsDiscrete),
  18317. &allChannelsDiscrete);
  18318. if (err != noErr)
  18319. return;
  18320. bufferList->mNumberBuffers = 1;
  18321. bufferList->mBuffers[0].mNumberChannels = inputStreamDesc.mChannelsPerFrame;
  18322. bufferList->mBuffers[0].mDataByteSize = jmax ((UInt32) 4096, (UInt32) (samplesPerFrame * inputStreamDesc.mBytesPerFrame) + 16);
  18323. dataBuffer.malloc (bufferList->mBuffers[0].mDataByteSize);
  18324. bufferList->mBuffers[0].mData = dataBuffer;
  18325. sampleRate = inputStreamDesc.mSampleRate;
  18326. bitsPerSample = 16;
  18327. numChannels = inputStreamDesc.mChannelsPerFrame;
  18328. detachThread();
  18329. ok = true;
  18330. }
  18331. ~QTAudioReader()
  18332. {
  18333. JUCE_AUTORELEASEPOOL
  18334. checkThreadIsAttached();
  18335. if (dataHandle != 0)
  18336. DisposeHandle (dataHandle);
  18337. if (extractor != 0)
  18338. {
  18339. MovieAudioExtractionEnd (extractor);
  18340. extractor = 0;
  18341. }
  18342. DisposeMovie (movie);
  18343. #if JUCE_MAC
  18344. ExitMoviesOnThread ();
  18345. #endif
  18346. }
  18347. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  18348. int64 startSampleInFile, int numSamples)
  18349. {
  18350. JUCE_AUTORELEASEPOOL
  18351. checkThreadIsAttached();
  18352. bool ok = true;
  18353. while (numSamples > 0)
  18354. {
  18355. if (lastSampleRead != startSampleInFile)
  18356. {
  18357. TimeRecord time;
  18358. time.scale = (TimeScale) inputStreamDesc.mSampleRate;
  18359. time.base = 0;
  18360. time.value.hi = 0;
  18361. time.value.lo = (UInt32) startSampleInFile;
  18362. OSStatus err = MovieAudioExtractionSetProperty (extractor,
  18363. kQTPropertyClass_MovieAudioExtraction_Movie,
  18364. kQTMovieAudioExtractionMoviePropertyID_CurrentTime,
  18365. sizeof (time), &time);
  18366. if (err != noErr)
  18367. {
  18368. ok = false;
  18369. break;
  18370. }
  18371. }
  18372. int framesToDo = jmin (numSamples, (int) (bufferList->mBuffers[0].mDataByteSize / inputStreamDesc.mBytesPerFrame));
  18373. bufferList->mBuffers[0].mDataByteSize = inputStreamDesc.mBytesPerFrame * framesToDo;
  18374. UInt32 outFlags = 0;
  18375. UInt32 actualNumFrames = framesToDo;
  18376. OSStatus err = MovieAudioExtractionFillBuffer (extractor, &actualNumFrames, bufferList, &outFlags);
  18377. if (err != noErr)
  18378. {
  18379. ok = false;
  18380. break;
  18381. }
  18382. lastSampleRead = startSampleInFile + actualNumFrames;
  18383. const int samplesReceived = actualNumFrames;
  18384. for (int j = numDestChannels; --j >= 0;)
  18385. {
  18386. if (destSamples[j] != 0)
  18387. {
  18388. const short* const src = ((const short*) bufferList->mBuffers[0].mData) + j;
  18389. for (int i = 0; i < samplesReceived; ++i)
  18390. destSamples[j][startOffsetInDestBuffer + i] = src [i << 1] << 16;
  18391. }
  18392. }
  18393. startOffsetInDestBuffer += samplesReceived;
  18394. startSampleInFile += samplesReceived;
  18395. numSamples -= samplesReceived;
  18396. if ((outFlags & kQTMovieAudioExtractionComplete) != 0 && numSamples > 0)
  18397. {
  18398. for (int j = numDestChannels; --j >= 0;)
  18399. if (destSamples[j] != 0)
  18400. zeromem (destSamples[j] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  18401. break;
  18402. }
  18403. }
  18404. detachThread();
  18405. return ok;
  18406. }
  18407. juce_UseDebuggingNewOperator
  18408. bool ok;
  18409. private:
  18410. Movie movie;
  18411. Media media;
  18412. Track track;
  18413. const int trackNum;
  18414. double trackUnitsPerFrame;
  18415. int samplesPerFrame;
  18416. int64 lastSampleRead;
  18417. Thread::ThreadID lastThreadId;
  18418. MovieAudioExtractionRef extractor;
  18419. AudioStreamBasicDescription inputStreamDesc;
  18420. HeapBlock <AudioBufferList> bufferList;
  18421. HeapBlock <char> dataBuffer;
  18422. Handle dataHandle;
  18423. void checkThreadIsAttached()
  18424. {
  18425. #if JUCE_MAC
  18426. if (Thread::getCurrentThreadId() != lastThreadId)
  18427. EnterMoviesOnThread (0);
  18428. AttachMovieToCurrentThread (movie);
  18429. #endif
  18430. }
  18431. void detachThread()
  18432. {
  18433. #if JUCE_MAC
  18434. DetachMovieFromCurrentThread (movie);
  18435. #endif
  18436. }
  18437. QTAudioReader (const QTAudioReader&);
  18438. QTAudioReader& operator= (const QTAudioReader&);
  18439. };
  18440. QuickTimeAudioFormat::QuickTimeAudioFormat()
  18441. : AudioFormat (TRANS (quickTimeFormatName), StringArray (quickTimeExtensions))
  18442. {
  18443. }
  18444. QuickTimeAudioFormat::~QuickTimeAudioFormat()
  18445. {
  18446. }
  18447. const Array <int> QuickTimeAudioFormat::getPossibleSampleRates() { return Array<int>(); }
  18448. const Array <int> QuickTimeAudioFormat::getPossibleBitDepths() { return Array<int>(); }
  18449. bool QuickTimeAudioFormat::canDoStereo() { return true; }
  18450. bool QuickTimeAudioFormat::canDoMono() { return true; }
  18451. AudioFormatReader* QuickTimeAudioFormat::createReaderFor (InputStream* sourceStream,
  18452. const bool deleteStreamIfOpeningFails)
  18453. {
  18454. ScopedPointer <QTAudioReader> r (new QTAudioReader (sourceStream, 0));
  18455. if (r->ok)
  18456. return r.release();
  18457. if (! deleteStreamIfOpeningFails)
  18458. r->input = 0;
  18459. return 0;
  18460. }
  18461. AudioFormatWriter* QuickTimeAudioFormat::createWriterFor (OutputStream* /*streamToWriteTo*/,
  18462. double /*sampleRateToUse*/,
  18463. unsigned int /*numberOfChannels*/,
  18464. int /*bitsPerSample*/,
  18465. const StringPairArray& /*metadataValues*/,
  18466. int /*qualityOptionIndex*/)
  18467. {
  18468. jassertfalse; // not yet implemented!
  18469. return 0;
  18470. }
  18471. END_JUCE_NAMESPACE
  18472. #endif
  18473. /*** End of inlined file: juce_QuickTimeAudioFormat.cpp ***/
  18474. /*** Start of inlined file: juce_WavAudioFormat.cpp ***/
  18475. BEGIN_JUCE_NAMESPACE
  18476. static const char* const wavFormatName = "WAV file";
  18477. static const char* const wavExtensions[] = { ".wav", ".bwf", 0 };
  18478. const char* const WavAudioFormat::bwavDescription = "bwav description";
  18479. const char* const WavAudioFormat::bwavOriginator = "bwav originator";
  18480. const char* const WavAudioFormat::bwavOriginatorRef = "bwav originator ref";
  18481. const char* const WavAudioFormat::bwavOriginationDate = "bwav origination date";
  18482. const char* const WavAudioFormat::bwavOriginationTime = "bwav origination time";
  18483. const char* const WavAudioFormat::bwavTimeReference = "bwav time reference";
  18484. const char* const WavAudioFormat::bwavCodingHistory = "bwav coding history";
  18485. const StringPairArray WavAudioFormat::createBWAVMetadata (const String& description,
  18486. const String& originator,
  18487. const String& originatorRef,
  18488. const Time& date,
  18489. const int64 timeReferenceSamples,
  18490. const String& codingHistory)
  18491. {
  18492. StringPairArray m;
  18493. m.set (bwavDescription, description);
  18494. m.set (bwavOriginator, originator);
  18495. m.set (bwavOriginatorRef, originatorRef);
  18496. m.set (bwavOriginationDate, date.formatted ("%Y-%m-%d"));
  18497. m.set (bwavOriginationTime, date.formatted ("%H:%M:%S"));
  18498. m.set (bwavTimeReference, String (timeReferenceSamples));
  18499. m.set (bwavCodingHistory, codingHistory);
  18500. return m;
  18501. }
  18502. #if JUCE_MSVC
  18503. #pragma pack (push, 1)
  18504. #define PACKED
  18505. #elif JUCE_GCC
  18506. #define PACKED __attribute__((packed))
  18507. #else
  18508. #define PACKED
  18509. #endif
  18510. struct BWAVChunk
  18511. {
  18512. char description [256];
  18513. char originator [32];
  18514. char originatorRef [32];
  18515. char originationDate [10];
  18516. char originationTime [8];
  18517. uint32 timeRefLow;
  18518. uint32 timeRefHigh;
  18519. uint16 version;
  18520. uint8 umid[64];
  18521. uint8 reserved[190];
  18522. char codingHistory[1];
  18523. void copyTo (StringPairArray& values) const
  18524. {
  18525. values.set (WavAudioFormat::bwavDescription, String::fromUTF8 (description, 256));
  18526. values.set (WavAudioFormat::bwavOriginator, String::fromUTF8 (originator, 32));
  18527. values.set (WavAudioFormat::bwavOriginatorRef, String::fromUTF8 (originatorRef, 32));
  18528. values.set (WavAudioFormat::bwavOriginationDate, String::fromUTF8 (originationDate, 10));
  18529. values.set (WavAudioFormat::bwavOriginationTime, String::fromUTF8 (originationTime, 8));
  18530. const uint32 timeLow = ByteOrder::swapIfBigEndian (timeRefLow);
  18531. const uint32 timeHigh = ByteOrder::swapIfBigEndian (timeRefHigh);
  18532. const int64 time = (((int64)timeHigh) << 32) + timeLow;
  18533. values.set (WavAudioFormat::bwavTimeReference, String (time));
  18534. values.set (WavAudioFormat::bwavCodingHistory, String::fromUTF8 (codingHistory));
  18535. }
  18536. static MemoryBlock createFrom (const StringPairArray& values)
  18537. {
  18538. const size_t sizeNeeded = sizeof (BWAVChunk) + values [WavAudioFormat::bwavCodingHistory].getNumBytesAsUTF8();
  18539. MemoryBlock data ((sizeNeeded + 3) & ~3);
  18540. data.fillWith (0);
  18541. BWAVChunk* b = (BWAVChunk*) data.getData();
  18542. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  18543. // as they get called in the right order..
  18544. values [WavAudioFormat::bwavDescription].copyToUTF8 (b->description, 257);
  18545. values [WavAudioFormat::bwavOriginator].copyToUTF8 (b->originator, 33);
  18546. values [WavAudioFormat::bwavOriginatorRef].copyToUTF8 (b->originatorRef, 33);
  18547. values [WavAudioFormat::bwavOriginationDate].copyToUTF8 (b->originationDate, 11);
  18548. values [WavAudioFormat::bwavOriginationTime].copyToUTF8 (b->originationTime, 9);
  18549. const int64 time = values [WavAudioFormat::bwavTimeReference].getLargeIntValue();
  18550. b->timeRefLow = ByteOrder::swapIfBigEndian ((uint32) (time & 0xffffffff));
  18551. b->timeRefHigh = ByteOrder::swapIfBigEndian ((uint32) (time >> 32));
  18552. values [WavAudioFormat::bwavCodingHistory].copyToUTF8 (b->codingHistory, 0x7fffffff);
  18553. if (b->description[0] != 0
  18554. || b->originator[0] != 0
  18555. || b->originationDate[0] != 0
  18556. || b->originationTime[0] != 0
  18557. || b->codingHistory[0] != 0
  18558. || time != 0)
  18559. {
  18560. return data;
  18561. }
  18562. return MemoryBlock();
  18563. }
  18564. } PACKED;
  18565. struct SMPLChunk
  18566. {
  18567. struct SampleLoop
  18568. {
  18569. uint32 identifier;
  18570. uint32 type;
  18571. uint32 start;
  18572. uint32 end;
  18573. uint32 fraction;
  18574. uint32 playCount;
  18575. } PACKED;
  18576. uint32 manufacturer;
  18577. uint32 product;
  18578. uint32 samplePeriod;
  18579. uint32 midiUnityNote;
  18580. uint32 midiPitchFraction;
  18581. uint32 smpteFormat;
  18582. uint32 smpteOffset;
  18583. uint32 numSampleLoops;
  18584. uint32 samplerData;
  18585. SampleLoop loops[1];
  18586. void copyTo (StringPairArray& values, const int totalSize) const
  18587. {
  18588. values.set ("Manufacturer", String (ByteOrder::swapIfBigEndian (manufacturer)));
  18589. values.set ("Product", String (ByteOrder::swapIfBigEndian (product)));
  18590. values.set ("SamplePeriod", String (ByteOrder::swapIfBigEndian (samplePeriod)));
  18591. values.set ("MidiUnityNote", String (ByteOrder::swapIfBigEndian (midiUnityNote)));
  18592. values.set ("MidiPitchFraction", String (ByteOrder::swapIfBigEndian (midiPitchFraction)));
  18593. values.set ("SmpteFormat", String (ByteOrder::swapIfBigEndian (smpteFormat)));
  18594. values.set ("SmpteOffset", String (ByteOrder::swapIfBigEndian (smpteOffset)));
  18595. values.set ("NumSampleLoops", String (ByteOrder::swapIfBigEndian (numSampleLoops)));
  18596. values.set ("SamplerData", String (ByteOrder::swapIfBigEndian (samplerData)));
  18597. for (uint32 i = 0; i < numSampleLoops; ++i)
  18598. {
  18599. if ((uint8*) (loops + (i + 1)) > ((uint8*) this) + totalSize)
  18600. break;
  18601. const String prefix ("Loop" + String(i));
  18602. values.set (prefix + "Identifier", String (ByteOrder::swapIfBigEndian (loops[i].identifier)));
  18603. values.set (prefix + "Type", String (ByteOrder::swapIfBigEndian (loops[i].type)));
  18604. values.set (prefix + "Start", String (ByteOrder::swapIfBigEndian (loops[i].start)));
  18605. values.set (prefix + "End", String (ByteOrder::swapIfBigEndian (loops[i].end)));
  18606. values.set (prefix + "Fraction", String (ByteOrder::swapIfBigEndian (loops[i].fraction)));
  18607. values.set (prefix + "PlayCount", String (ByteOrder::swapIfBigEndian (loops[i].playCount)));
  18608. }
  18609. }
  18610. static MemoryBlock createFrom (const StringPairArray& values)
  18611. {
  18612. const int numLoops = jmin (64, values.getValue ("NumSampleLoops", "0").getIntValue());
  18613. if (numLoops <= 0)
  18614. return MemoryBlock();
  18615. const size_t sizeNeeded = sizeof (SMPLChunk) + (numLoops - 1) * sizeof (SampleLoop);
  18616. MemoryBlock data ((sizeNeeded + 3) & ~3);
  18617. data.fillWith (0);
  18618. SMPLChunk* s = (SMPLChunk*) data.getData();
  18619. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  18620. // as they get called in the right order..
  18621. s->manufacturer = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Manufacturer", "0").getIntValue());
  18622. s->product = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Product", "0").getIntValue());
  18623. s->samplePeriod = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplePeriod", "0").getIntValue());
  18624. s->midiUnityNote = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiUnityNote", "60").getIntValue());
  18625. s->midiPitchFraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiPitchFraction", "0").getIntValue());
  18626. s->smpteFormat = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteFormat", "0").getIntValue());
  18627. s->smpteOffset = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteOffset", "0").getIntValue());
  18628. s->numSampleLoops = ByteOrder::swapIfBigEndian ((uint32) numLoops);
  18629. s->samplerData = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplerData", "0").getIntValue());
  18630. for (int i = 0; i < numLoops; ++i)
  18631. {
  18632. const String prefix ("Loop" + String(i));
  18633. s->loops[i].identifier = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Identifier", "0").getIntValue());
  18634. s->loops[i].type = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Type", "0").getIntValue());
  18635. s->loops[i].start = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Start", "0").getIntValue());
  18636. s->loops[i].end = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "End", "0").getIntValue());
  18637. s->loops[i].fraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Fraction", "0").getIntValue());
  18638. s->loops[i].playCount = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "PlayCount", "0").getIntValue());
  18639. }
  18640. return data;
  18641. }
  18642. } PACKED;
  18643. struct ExtensibleWavSubFormat
  18644. {
  18645. uint32 data1;
  18646. uint16 data2;
  18647. uint16 data3;
  18648. uint8 data4[8];
  18649. } PACKED;
  18650. #if JUCE_MSVC
  18651. #pragma pack (pop)
  18652. #endif
  18653. #undef PACKED
  18654. class WavAudioFormatReader : public AudioFormatReader
  18655. {
  18656. public:
  18657. WavAudioFormatReader (InputStream* const in)
  18658. : AudioFormatReader (in, TRANS (wavFormatName)),
  18659. bwavChunkStart (0),
  18660. bwavSize (0),
  18661. dataLength (0)
  18662. {
  18663. if (input->readInt() == chunkName ("RIFF"))
  18664. {
  18665. const uint32 len = (uint32) input->readInt();
  18666. const int64 end = input->getPosition() + len;
  18667. bool hasGotType = false;
  18668. bool hasGotData = false;
  18669. if (input->readInt() == chunkName ("WAVE"))
  18670. {
  18671. while (input->getPosition() < end
  18672. && ! input->isExhausted())
  18673. {
  18674. const int chunkType = input->readInt();
  18675. uint32 length = (uint32) input->readInt();
  18676. const int64 chunkEnd = input->getPosition() + length + (length & 1);
  18677. if (chunkType == chunkName ("fmt "))
  18678. {
  18679. // read the format chunk
  18680. const unsigned short format = input->readShort();
  18681. const short numChans = input->readShort();
  18682. sampleRate = input->readInt();
  18683. const int bytesPerSec = input->readInt();
  18684. numChannels = numChans;
  18685. bytesPerFrame = bytesPerSec / (int)sampleRate;
  18686. bitsPerSample = 8 * bytesPerFrame / numChans;
  18687. if (format == 3)
  18688. {
  18689. usesFloatingPointData = true;
  18690. }
  18691. else if (format == 0xfffe /*WAVE_FORMAT_EXTENSIBLE*/)
  18692. {
  18693. if (length < 40) // too short
  18694. {
  18695. bytesPerFrame = 0;
  18696. }
  18697. else
  18698. {
  18699. input->skipNextBytes (12); // skip over blockAlign, bitsPerSample and speakerPosition mask
  18700. ExtensibleWavSubFormat subFormat;
  18701. subFormat.data1 = input->readInt();
  18702. subFormat.data2 = input->readShort();
  18703. subFormat.data3 = input->readShort();
  18704. input->read (subFormat.data4, sizeof (subFormat.data4));
  18705. const ExtensibleWavSubFormat pcmFormat
  18706. = { 0x00000001, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  18707. if (memcmp (&subFormat, &pcmFormat, sizeof (subFormat)) != 0)
  18708. {
  18709. const ExtensibleWavSubFormat ambisonicFormat
  18710. = { 0x00000001, 0x0721, 0x11d3, { 0x86, 0x44, 0xC8, 0xC1, 0xCA, 0x00, 0x00, 0x00 } };
  18711. if (memcmp (&subFormat, &ambisonicFormat, sizeof (subFormat)) != 0)
  18712. bytesPerFrame = 0;
  18713. }
  18714. }
  18715. }
  18716. else if (format != 1)
  18717. {
  18718. bytesPerFrame = 0;
  18719. }
  18720. hasGotType = true;
  18721. }
  18722. else if (chunkType == chunkName ("data"))
  18723. {
  18724. // get the data chunk's position
  18725. dataLength = length;
  18726. dataChunkStart = input->getPosition();
  18727. lengthInSamples = (bytesPerFrame > 0) ? (dataLength / bytesPerFrame) : 0;
  18728. hasGotData = true;
  18729. }
  18730. else if (chunkType == chunkName ("bext"))
  18731. {
  18732. bwavChunkStart = input->getPosition();
  18733. bwavSize = length;
  18734. // Broadcast-wav extension chunk..
  18735. HeapBlock <BWAVChunk> bwav;
  18736. bwav.calloc (jmax ((size_t) length + 1, sizeof (BWAVChunk)), 1);
  18737. input->read (bwav, length);
  18738. bwav->copyTo (metadataValues);
  18739. }
  18740. else if (chunkType == chunkName ("smpl"))
  18741. {
  18742. HeapBlock <SMPLChunk> smpl;
  18743. smpl.calloc (jmax ((size_t) length + 1, sizeof (SMPLChunk)), 1);
  18744. input->read (smpl, length);
  18745. smpl->copyTo (metadataValues, length);
  18746. }
  18747. else if (chunkEnd <= input->getPosition())
  18748. {
  18749. break;
  18750. }
  18751. input->setPosition (chunkEnd);
  18752. }
  18753. }
  18754. }
  18755. }
  18756. ~WavAudioFormatReader()
  18757. {
  18758. }
  18759. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  18760. int64 startSampleInFile, int numSamples)
  18761. {
  18762. jassert (destSamples != 0);
  18763. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  18764. if (samplesAvailable < numSamples)
  18765. {
  18766. for (int i = numDestChannels; --i >= 0;)
  18767. if (destSamples[i] != 0)
  18768. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  18769. numSamples = (int) samplesAvailable;
  18770. }
  18771. if (numSamples <= 0)
  18772. return true;
  18773. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  18774. while (numSamples > 0)
  18775. {
  18776. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  18777. char tempBuffer [tempBufSize];
  18778. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  18779. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  18780. if (bytesRead < numThisTime * bytesPerFrame)
  18781. {
  18782. jassert (bytesRead >= 0);
  18783. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  18784. }
  18785. switch (bitsPerSample)
  18786. {
  18787. case 8: ReadHelper<AudioData::Int32, AudioData::UInt8, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18788. case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18789. case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18790. case 32: if (usesFloatingPointData) ReadHelper<AudioData::Float32, AudioData::Float32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime);
  18791. else ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18792. default: jassertfalse; break;
  18793. }
  18794. startOffsetInDestBuffer += numThisTime;
  18795. numSamples -= numThisTime;
  18796. }
  18797. return true;
  18798. }
  18799. int64 bwavChunkStart, bwavSize;
  18800. juce_UseDebuggingNewOperator
  18801. private:
  18802. ScopedPointer<AudioData::Converter> converter;
  18803. int bytesPerFrame;
  18804. int64 dataChunkStart, dataLength;
  18805. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  18806. WavAudioFormatReader (const WavAudioFormatReader&);
  18807. WavAudioFormatReader& operator= (const WavAudioFormatReader&);
  18808. };
  18809. class WavAudioFormatWriter : public AudioFormatWriter
  18810. {
  18811. public:
  18812. WavAudioFormatWriter (OutputStream* const out,
  18813. const double sampleRate_,
  18814. const unsigned int numChannels_,
  18815. const int bits,
  18816. const StringPairArray& metadataValues)
  18817. : AudioFormatWriter (out,
  18818. TRANS (wavFormatName),
  18819. sampleRate_,
  18820. numChannels_,
  18821. bits),
  18822. lengthInSamples (0),
  18823. bytesWritten (0),
  18824. writeFailed (false)
  18825. {
  18826. if (metadataValues.size() > 0)
  18827. {
  18828. bwavChunk = BWAVChunk::createFrom (metadataValues);
  18829. smplChunk = SMPLChunk::createFrom (metadataValues);
  18830. }
  18831. headerPosition = out->getPosition();
  18832. writeHeader();
  18833. }
  18834. ~WavAudioFormatWriter()
  18835. {
  18836. writeHeader();
  18837. }
  18838. bool write (const int** data, int numSamples)
  18839. {
  18840. jassert (data != 0 && *data != 0); // the input must contain at least one channel!
  18841. if (writeFailed)
  18842. return false;
  18843. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  18844. tempBlock.ensureSize (bytes, false);
  18845. switch (bitsPerSample)
  18846. {
  18847. case 8: WriteHelper<AudioData::UInt8, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18848. case 16: WriteHelper<AudioData::Int16, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18849. case 24: WriteHelper<AudioData::Int24, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18850. case 32: WriteHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18851. default: jassertfalse; break;
  18852. }
  18853. if (bytesWritten + bytes >= (uint32) 0xfff00000
  18854. || ! output->write (tempBlock.getData(), bytes))
  18855. {
  18856. // failed to write to disk, so let's try writing the header.
  18857. // If it's just run out of disk space, then if it does manage
  18858. // to write the header, we'll still have a useable file..
  18859. writeHeader();
  18860. writeFailed = true;
  18861. return false;
  18862. }
  18863. else
  18864. {
  18865. bytesWritten += bytes;
  18866. lengthInSamples += numSamples;
  18867. return true;
  18868. }
  18869. }
  18870. juce_UseDebuggingNewOperator
  18871. private:
  18872. ScopedPointer<AudioData::Converter> converter;
  18873. MemoryBlock tempBlock, bwavChunk, smplChunk;
  18874. uint32 lengthInSamples, bytesWritten;
  18875. int64 headerPosition;
  18876. bool writeFailed;
  18877. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  18878. void writeHeader()
  18879. {
  18880. const bool seekedOk = output->setPosition (headerPosition);
  18881. (void) seekedOk;
  18882. // if this fails, you've given it an output stream that can't seek! It needs
  18883. // to be able to seek back to write the header
  18884. jassert (seekedOk);
  18885. const int bytesPerFrame = numChannels * bitsPerSample / 8;
  18886. output->writeInt (chunkName ("RIFF"));
  18887. output->writeInt ((int) (lengthInSamples * bytesPerFrame
  18888. + ((bwavChunk.getSize() > 0) ? (44 + bwavChunk.getSize()) : 36)));
  18889. output->writeInt (chunkName ("WAVE"));
  18890. output->writeInt (chunkName ("fmt "));
  18891. output->writeInt (16);
  18892. output->writeShort ((bitsPerSample < 32) ? (short) 1 /*WAVE_FORMAT_PCM*/
  18893. : (short) 3 /*WAVE_FORMAT_IEEE_FLOAT*/);
  18894. output->writeShort ((short) numChannels);
  18895. output->writeInt ((int) sampleRate);
  18896. output->writeInt (bytesPerFrame * (int) sampleRate);
  18897. output->writeShort ((short) bytesPerFrame);
  18898. output->writeShort ((short) bitsPerSample);
  18899. if (bwavChunk.getSize() > 0)
  18900. {
  18901. output->writeInt (chunkName ("bext"));
  18902. output->writeInt ((int) bwavChunk.getSize());
  18903. output->write (bwavChunk.getData(), (int) bwavChunk.getSize());
  18904. }
  18905. if (smplChunk.getSize() > 0)
  18906. {
  18907. output->writeInt (chunkName ("smpl"));
  18908. output->writeInt ((int) smplChunk.getSize());
  18909. output->write (smplChunk.getData(), (int) smplChunk.getSize());
  18910. }
  18911. output->writeInt (chunkName ("data"));
  18912. output->writeInt (lengthInSamples * bytesPerFrame);
  18913. usesFloatingPointData = (bitsPerSample == 32);
  18914. }
  18915. WavAudioFormatWriter (const WavAudioFormatWriter&);
  18916. WavAudioFormatWriter& operator= (const WavAudioFormatWriter&);
  18917. };
  18918. WavAudioFormat::WavAudioFormat()
  18919. : AudioFormat (TRANS (wavFormatName), StringArray (wavExtensions))
  18920. {
  18921. }
  18922. WavAudioFormat::~WavAudioFormat()
  18923. {
  18924. }
  18925. const Array <int> WavAudioFormat::getPossibleSampleRates()
  18926. {
  18927. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  18928. return Array <int> (rates);
  18929. }
  18930. const Array <int> WavAudioFormat::getPossibleBitDepths()
  18931. {
  18932. const int depths[] = { 8, 16, 24, 32, 0 };
  18933. return Array <int> (depths);
  18934. }
  18935. bool WavAudioFormat::canDoStereo() { return true; }
  18936. bool WavAudioFormat::canDoMono() { return true; }
  18937. AudioFormatReader* WavAudioFormat::createReaderFor (InputStream* sourceStream,
  18938. const bool deleteStreamIfOpeningFails)
  18939. {
  18940. ScopedPointer <WavAudioFormatReader> r (new WavAudioFormatReader (sourceStream));
  18941. if (r->sampleRate != 0)
  18942. return r.release();
  18943. if (! deleteStreamIfOpeningFails)
  18944. r->input = 0;
  18945. return 0;
  18946. }
  18947. AudioFormatWriter* WavAudioFormat::createWriterFor (OutputStream* out,
  18948. double sampleRate,
  18949. unsigned int numChannels,
  18950. int bitsPerSample,
  18951. const StringPairArray& metadataValues,
  18952. int /*qualityOptionIndex*/)
  18953. {
  18954. if (getPossibleBitDepths().contains (bitsPerSample))
  18955. {
  18956. return new WavAudioFormatWriter (out,
  18957. sampleRate,
  18958. numChannels,
  18959. bitsPerSample,
  18960. metadataValues);
  18961. }
  18962. return 0;
  18963. }
  18964. namespace
  18965. {
  18966. bool juce_slowCopyOfWavFileWithNewMetadata (const File& file, const StringPairArray& metadata)
  18967. {
  18968. TemporaryFile tempFile (file);
  18969. WavAudioFormat wav;
  18970. ScopedPointer <AudioFormatReader> reader (wav.createReaderFor (file.createInputStream(), true));
  18971. if (reader != 0)
  18972. {
  18973. ScopedPointer <OutputStream> outStream (tempFile.getFile().createOutputStream());
  18974. if (outStream != 0)
  18975. {
  18976. ScopedPointer <AudioFormatWriter> writer (wav.createWriterFor (outStream, reader->sampleRate,
  18977. reader->numChannels, reader->bitsPerSample,
  18978. metadata, 0));
  18979. if (writer != 0)
  18980. {
  18981. outStream.release();
  18982. bool ok = writer->writeFromAudioReader (*reader, 0, -1);
  18983. writer = 0;
  18984. reader = 0;
  18985. return ok && tempFile.overwriteTargetFileWithTemporary();
  18986. }
  18987. }
  18988. }
  18989. return false;
  18990. }
  18991. }
  18992. bool WavAudioFormat::replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata)
  18993. {
  18994. ScopedPointer <WavAudioFormatReader> reader ((WavAudioFormatReader*) createReaderFor (wavFile.createInputStream(), true));
  18995. if (reader != 0)
  18996. {
  18997. const int64 bwavPos = reader->bwavChunkStart;
  18998. const int64 bwavSize = reader->bwavSize;
  18999. reader = 0;
  19000. if (bwavSize > 0)
  19001. {
  19002. MemoryBlock chunk = BWAVChunk::createFrom (newMetadata);
  19003. if (chunk.getSize() <= (size_t) bwavSize)
  19004. {
  19005. // the new one will fit in the space available, so write it directly..
  19006. const int64 oldSize = wavFile.getSize();
  19007. {
  19008. ScopedPointer <FileOutputStream> out (wavFile.createOutputStream());
  19009. out->setPosition (bwavPos);
  19010. out->write (chunk.getData(), (int) chunk.getSize());
  19011. out->setPosition (oldSize);
  19012. }
  19013. jassert (wavFile.getSize() == oldSize);
  19014. return true;
  19015. }
  19016. }
  19017. }
  19018. return juce_slowCopyOfWavFileWithNewMetadata (wavFile, newMetadata);
  19019. }
  19020. END_JUCE_NAMESPACE
  19021. /*** End of inlined file: juce_WavAudioFormat.cpp ***/
  19022. /*** Start of inlined file: juce_AudioCDReader.cpp ***/
  19023. #if JUCE_USE_CDREADER
  19024. BEGIN_JUCE_NAMESPACE
  19025. int AudioCDReader::getNumTracks() const
  19026. {
  19027. return trackStartSamples.size() - 1;
  19028. }
  19029. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  19030. {
  19031. return trackStartSamples [trackNum];
  19032. }
  19033. const Array<int>& AudioCDReader::getTrackOffsets() const
  19034. {
  19035. return trackStartSamples;
  19036. }
  19037. int AudioCDReader::getCDDBId()
  19038. {
  19039. int checksum = 0;
  19040. const int numTracks = getNumTracks();
  19041. for (int i = 0; i < numTracks; ++i)
  19042. for (int offset = (trackStartSamples.getUnchecked(i) + 88200) / 44100; offset > 0; offset /= 10)
  19043. checksum += offset % 10;
  19044. const int length = (trackStartSamples.getLast() - trackStartSamples.getFirst()) / 44100;
  19045. // CCLLLLTT: checksum, length, tracks
  19046. return ((checksum & 0xff) << 24) | (length << 8) | numTracks;
  19047. }
  19048. END_JUCE_NAMESPACE
  19049. #endif
  19050. /*** End of inlined file: juce_AudioCDReader.cpp ***/
  19051. /*** Start of inlined file: juce_AudioFormatReaderSource.cpp ***/
  19052. BEGIN_JUCE_NAMESPACE
  19053. AudioFormatReaderSource::AudioFormatReaderSource (AudioFormatReader* const reader_,
  19054. const bool deleteReaderWhenThisIsDeleted)
  19055. : reader (reader_),
  19056. deleteReader (deleteReaderWhenThisIsDeleted),
  19057. nextPlayPos (0),
  19058. looping (false)
  19059. {
  19060. jassert (reader != 0);
  19061. }
  19062. AudioFormatReaderSource::~AudioFormatReaderSource()
  19063. {
  19064. releaseResources();
  19065. if (deleteReader)
  19066. delete reader;
  19067. }
  19068. void AudioFormatReaderSource::setNextReadPosition (int newPosition)
  19069. {
  19070. nextPlayPos = newPosition;
  19071. }
  19072. void AudioFormatReaderSource::setLooping (bool shouldLoop)
  19073. {
  19074. looping = shouldLoop;
  19075. }
  19076. int AudioFormatReaderSource::getNextReadPosition() const
  19077. {
  19078. return (looping) ? (nextPlayPos % (int) reader->lengthInSamples)
  19079. : nextPlayPos;
  19080. }
  19081. int AudioFormatReaderSource::getTotalLength() const
  19082. {
  19083. return (int) reader->lengthInSamples;
  19084. }
  19085. void AudioFormatReaderSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  19086. double /*sampleRate*/)
  19087. {
  19088. }
  19089. void AudioFormatReaderSource::releaseResources()
  19090. {
  19091. }
  19092. void AudioFormatReaderSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19093. {
  19094. if (info.numSamples > 0)
  19095. {
  19096. const int start = nextPlayPos;
  19097. if (looping)
  19098. {
  19099. const int newStart = start % (int) reader->lengthInSamples;
  19100. const int newEnd = (start + info.numSamples) % (int) reader->lengthInSamples;
  19101. if (newEnd > newStart)
  19102. {
  19103. info.buffer->readFromAudioReader (reader,
  19104. info.startSample,
  19105. newEnd - newStart,
  19106. newStart,
  19107. true, true);
  19108. }
  19109. else
  19110. {
  19111. const int endSamps = (int) reader->lengthInSamples - newStart;
  19112. info.buffer->readFromAudioReader (reader,
  19113. info.startSample,
  19114. endSamps,
  19115. newStart,
  19116. true, true);
  19117. info.buffer->readFromAudioReader (reader,
  19118. info.startSample + endSamps,
  19119. newEnd,
  19120. 0,
  19121. true, true);
  19122. }
  19123. nextPlayPos = newEnd;
  19124. }
  19125. else
  19126. {
  19127. info.buffer->readFromAudioReader (reader,
  19128. info.startSample,
  19129. info.numSamples,
  19130. start,
  19131. true, true);
  19132. nextPlayPos += info.numSamples;
  19133. }
  19134. }
  19135. }
  19136. END_JUCE_NAMESPACE
  19137. /*** End of inlined file: juce_AudioFormatReaderSource.cpp ***/
  19138. /*** Start of inlined file: juce_AudioSourcePlayer.cpp ***/
  19139. BEGIN_JUCE_NAMESPACE
  19140. AudioSourcePlayer::AudioSourcePlayer()
  19141. : source (0),
  19142. sampleRate (0),
  19143. bufferSize (0),
  19144. tempBuffer (2, 8),
  19145. lastGain (1.0f),
  19146. gain (1.0f)
  19147. {
  19148. }
  19149. AudioSourcePlayer::~AudioSourcePlayer()
  19150. {
  19151. setSource (0);
  19152. }
  19153. void AudioSourcePlayer::setSource (AudioSource* newSource)
  19154. {
  19155. if (source != newSource)
  19156. {
  19157. AudioSource* const oldSource = source;
  19158. if (newSource != 0 && bufferSize > 0 && sampleRate > 0)
  19159. newSource->prepareToPlay (bufferSize, sampleRate);
  19160. {
  19161. const ScopedLock sl (readLock);
  19162. source = newSource;
  19163. }
  19164. if (oldSource != 0)
  19165. oldSource->releaseResources();
  19166. }
  19167. }
  19168. void AudioSourcePlayer::setGain (const float newGain) throw()
  19169. {
  19170. gain = newGain;
  19171. }
  19172. void AudioSourcePlayer::audioDeviceIOCallback (const float** inputChannelData,
  19173. int totalNumInputChannels,
  19174. float** outputChannelData,
  19175. int totalNumOutputChannels,
  19176. int numSamples)
  19177. {
  19178. // these should have been prepared by audioDeviceAboutToStart()...
  19179. jassert (sampleRate > 0 && bufferSize > 0);
  19180. const ScopedLock sl (readLock);
  19181. if (source != 0)
  19182. {
  19183. AudioSourceChannelInfo info;
  19184. int i, numActiveChans = 0, numInputs = 0, numOutputs = 0;
  19185. // messy stuff needed to compact the channels down into an array
  19186. // of non-zero pointers..
  19187. for (i = 0; i < totalNumInputChannels; ++i)
  19188. {
  19189. if (inputChannelData[i] != 0)
  19190. {
  19191. inputChans [numInputs++] = inputChannelData[i];
  19192. if (numInputs >= numElementsInArray (inputChans))
  19193. break;
  19194. }
  19195. }
  19196. for (i = 0; i < totalNumOutputChannels; ++i)
  19197. {
  19198. if (outputChannelData[i] != 0)
  19199. {
  19200. outputChans [numOutputs++] = outputChannelData[i];
  19201. if (numOutputs >= numElementsInArray (outputChans))
  19202. break;
  19203. }
  19204. }
  19205. if (numInputs > numOutputs)
  19206. {
  19207. // if there aren't enough output channels for the number of
  19208. // inputs, we need to create some temporary extra ones (can't
  19209. // use the input data in case it gets written to)
  19210. tempBuffer.setSize (numInputs - numOutputs, numSamples,
  19211. false, false, true);
  19212. for (i = 0; i < numOutputs; ++i)
  19213. {
  19214. channels[numActiveChans] = outputChans[i];
  19215. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  19216. ++numActiveChans;
  19217. }
  19218. for (i = numOutputs; i < numInputs; ++i)
  19219. {
  19220. channels[numActiveChans] = tempBuffer.getSampleData (i - numOutputs, 0);
  19221. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  19222. ++numActiveChans;
  19223. }
  19224. }
  19225. else
  19226. {
  19227. for (i = 0; i < numInputs; ++i)
  19228. {
  19229. channels[numActiveChans] = outputChans[i];
  19230. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  19231. ++numActiveChans;
  19232. }
  19233. for (i = numInputs; i < numOutputs; ++i)
  19234. {
  19235. channels[numActiveChans] = outputChans[i];
  19236. zeromem (channels[numActiveChans], sizeof (float) * numSamples);
  19237. ++numActiveChans;
  19238. }
  19239. }
  19240. AudioSampleBuffer buffer (channels, numActiveChans, numSamples);
  19241. info.buffer = &buffer;
  19242. info.startSample = 0;
  19243. info.numSamples = numSamples;
  19244. source->getNextAudioBlock (info);
  19245. for (i = info.buffer->getNumChannels(); --i >= 0;)
  19246. info.buffer->applyGainRamp (i, info.startSample, info.numSamples, lastGain, gain);
  19247. lastGain = gain;
  19248. }
  19249. else
  19250. {
  19251. for (int i = 0; i < totalNumOutputChannels; ++i)
  19252. if (outputChannelData[i] != 0)
  19253. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  19254. }
  19255. }
  19256. void AudioSourcePlayer::audioDeviceAboutToStart (AudioIODevice* device)
  19257. {
  19258. sampleRate = device->getCurrentSampleRate();
  19259. bufferSize = device->getCurrentBufferSizeSamples();
  19260. zeromem (channels, sizeof (channels));
  19261. if (source != 0)
  19262. source->prepareToPlay (bufferSize, sampleRate);
  19263. }
  19264. void AudioSourcePlayer::audioDeviceStopped()
  19265. {
  19266. if (source != 0)
  19267. source->releaseResources();
  19268. sampleRate = 0.0;
  19269. bufferSize = 0;
  19270. tempBuffer.setSize (2, 8);
  19271. }
  19272. END_JUCE_NAMESPACE
  19273. /*** End of inlined file: juce_AudioSourcePlayer.cpp ***/
  19274. /*** Start of inlined file: juce_AudioTransportSource.cpp ***/
  19275. BEGIN_JUCE_NAMESPACE
  19276. AudioTransportSource::AudioTransportSource()
  19277. : source (0),
  19278. resamplerSource (0),
  19279. bufferingSource (0),
  19280. positionableSource (0),
  19281. masterSource (0),
  19282. gain (1.0f),
  19283. lastGain (1.0f),
  19284. playing (false),
  19285. stopped (true),
  19286. sampleRate (44100.0),
  19287. sourceSampleRate (0.0),
  19288. blockSize (128),
  19289. readAheadBufferSize (0),
  19290. isPrepared (false),
  19291. inputStreamEOF (false)
  19292. {
  19293. }
  19294. AudioTransportSource::~AudioTransportSource()
  19295. {
  19296. setSource (0);
  19297. releaseResources();
  19298. }
  19299. void AudioTransportSource::setSource (PositionableAudioSource* const newSource,
  19300. int readAheadBufferSize_,
  19301. double sourceSampleRateToCorrectFor)
  19302. {
  19303. if (source == newSource)
  19304. {
  19305. if (source == 0)
  19306. return;
  19307. setSource (0, 0, 0); // deselect and reselect to avoid releasing resources wrongly
  19308. }
  19309. readAheadBufferSize = readAheadBufferSize_;
  19310. sourceSampleRate = sourceSampleRateToCorrectFor;
  19311. ResamplingAudioSource* newResamplerSource = 0;
  19312. BufferingAudioSource* newBufferingSource = 0;
  19313. PositionableAudioSource* newPositionableSource = 0;
  19314. AudioSource* newMasterSource = 0;
  19315. ScopedPointer <ResamplingAudioSource> oldResamplerSource (resamplerSource);
  19316. ScopedPointer <BufferingAudioSource> oldBufferingSource (bufferingSource);
  19317. AudioSource* oldMasterSource = masterSource;
  19318. if (newSource != 0)
  19319. {
  19320. newPositionableSource = newSource;
  19321. if (readAheadBufferSize_ > 0)
  19322. newPositionableSource = newBufferingSource
  19323. = new BufferingAudioSource (newPositionableSource, false, readAheadBufferSize_);
  19324. newPositionableSource->setNextReadPosition (0);
  19325. if (sourceSampleRateToCorrectFor != 0)
  19326. newMasterSource = newResamplerSource
  19327. = new ResamplingAudioSource (newPositionableSource, false);
  19328. else
  19329. newMasterSource = newPositionableSource;
  19330. if (isPrepared)
  19331. {
  19332. if (newResamplerSource != 0 && sourceSampleRate > 0 && sampleRate > 0)
  19333. newResamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  19334. newMasterSource->prepareToPlay (blockSize, sampleRate);
  19335. }
  19336. }
  19337. {
  19338. const ScopedLock sl (callbackLock);
  19339. source = newSource;
  19340. resamplerSource = newResamplerSource;
  19341. bufferingSource = newBufferingSource;
  19342. masterSource = newMasterSource;
  19343. positionableSource = newPositionableSource;
  19344. playing = false;
  19345. }
  19346. if (oldMasterSource != 0)
  19347. oldMasterSource->releaseResources();
  19348. }
  19349. void AudioTransportSource::start()
  19350. {
  19351. if ((! playing) && masterSource != 0)
  19352. {
  19353. {
  19354. const ScopedLock sl (callbackLock);
  19355. playing = true;
  19356. stopped = false;
  19357. inputStreamEOF = false;
  19358. }
  19359. sendChangeMessage (this);
  19360. }
  19361. }
  19362. void AudioTransportSource::stop()
  19363. {
  19364. if (playing)
  19365. {
  19366. {
  19367. const ScopedLock sl (callbackLock);
  19368. playing = false;
  19369. }
  19370. int n = 500;
  19371. while (--n >= 0 && ! stopped)
  19372. Thread::sleep (2);
  19373. sendChangeMessage (this);
  19374. }
  19375. }
  19376. void AudioTransportSource::setPosition (double newPosition)
  19377. {
  19378. if (sampleRate > 0.0)
  19379. setNextReadPosition (roundToInt (newPosition * sampleRate));
  19380. }
  19381. double AudioTransportSource::getCurrentPosition() const
  19382. {
  19383. if (sampleRate > 0.0)
  19384. return getNextReadPosition() / sampleRate;
  19385. else
  19386. return 0.0;
  19387. }
  19388. void AudioTransportSource::setNextReadPosition (int newPosition)
  19389. {
  19390. if (positionableSource != 0)
  19391. {
  19392. if (sampleRate > 0 && sourceSampleRate > 0)
  19393. newPosition = roundToInt (newPosition * sourceSampleRate / sampleRate);
  19394. positionableSource->setNextReadPosition (newPosition);
  19395. }
  19396. }
  19397. int AudioTransportSource::getNextReadPosition() const
  19398. {
  19399. if (positionableSource != 0)
  19400. {
  19401. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  19402. return roundToInt (positionableSource->getNextReadPosition() * ratio);
  19403. }
  19404. return 0;
  19405. }
  19406. int AudioTransportSource::getTotalLength() const
  19407. {
  19408. const ScopedLock sl (callbackLock);
  19409. if (positionableSource != 0)
  19410. {
  19411. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  19412. return roundToInt (positionableSource->getTotalLength() * ratio);
  19413. }
  19414. return 0;
  19415. }
  19416. bool AudioTransportSource::isLooping() const
  19417. {
  19418. const ScopedLock sl (callbackLock);
  19419. return positionableSource != 0
  19420. && positionableSource->isLooping();
  19421. }
  19422. void AudioTransportSource::setGain (const float newGain) throw()
  19423. {
  19424. gain = newGain;
  19425. }
  19426. void AudioTransportSource::prepareToPlay (int samplesPerBlockExpected,
  19427. double sampleRate_)
  19428. {
  19429. const ScopedLock sl (callbackLock);
  19430. sampleRate = sampleRate_;
  19431. blockSize = samplesPerBlockExpected;
  19432. if (masterSource != 0)
  19433. masterSource->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19434. if (resamplerSource != 0 && sourceSampleRate != 0)
  19435. resamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  19436. isPrepared = true;
  19437. }
  19438. void AudioTransportSource::releaseResources()
  19439. {
  19440. const ScopedLock sl (callbackLock);
  19441. if (masterSource != 0)
  19442. masterSource->releaseResources();
  19443. isPrepared = false;
  19444. }
  19445. void AudioTransportSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19446. {
  19447. const ScopedLock sl (callbackLock);
  19448. inputStreamEOF = false;
  19449. if (masterSource != 0 && ! stopped)
  19450. {
  19451. masterSource->getNextAudioBlock (info);
  19452. if (! playing)
  19453. {
  19454. // just stopped playing, so fade out the last block..
  19455. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  19456. info.buffer->applyGainRamp (i, info.startSample, jmin (256, info.numSamples), 1.0f, 0.0f);
  19457. if (info.numSamples > 256)
  19458. info.buffer->clear (info.startSample + 256, info.numSamples - 256);
  19459. }
  19460. if (positionableSource->getNextReadPosition() > positionableSource->getTotalLength() + 1
  19461. && ! positionableSource->isLooping())
  19462. {
  19463. playing = false;
  19464. inputStreamEOF = true;
  19465. sendChangeMessage (this);
  19466. }
  19467. stopped = ! playing;
  19468. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  19469. {
  19470. info.buffer->applyGainRamp (i, info.startSample, info.numSamples,
  19471. lastGain, gain);
  19472. }
  19473. }
  19474. else
  19475. {
  19476. info.clearActiveBufferRegion();
  19477. stopped = true;
  19478. }
  19479. lastGain = gain;
  19480. }
  19481. END_JUCE_NAMESPACE
  19482. /*** End of inlined file: juce_AudioTransportSource.cpp ***/
  19483. /*** Start of inlined file: juce_BufferingAudioSource.cpp ***/
  19484. BEGIN_JUCE_NAMESPACE
  19485. class SharedBufferingAudioSourceThread : public DeletedAtShutdown,
  19486. public Thread,
  19487. private Timer
  19488. {
  19489. public:
  19490. SharedBufferingAudioSourceThread()
  19491. : Thread ("Audio Buffer")
  19492. {
  19493. }
  19494. ~SharedBufferingAudioSourceThread()
  19495. {
  19496. stopThread (10000);
  19497. clearSingletonInstance();
  19498. }
  19499. juce_DeclareSingleton (SharedBufferingAudioSourceThread, false)
  19500. void addSource (BufferingAudioSource* source)
  19501. {
  19502. const ScopedLock sl (lock);
  19503. if (! sources.contains (source))
  19504. {
  19505. sources.add (source);
  19506. startThread();
  19507. stopTimer();
  19508. }
  19509. notify();
  19510. }
  19511. void removeSource (BufferingAudioSource* source)
  19512. {
  19513. const ScopedLock sl (lock);
  19514. sources.removeValue (source);
  19515. if (sources.size() == 0)
  19516. startTimer (5000);
  19517. }
  19518. private:
  19519. Array <BufferingAudioSource*> sources;
  19520. CriticalSection lock;
  19521. void run()
  19522. {
  19523. while (! threadShouldExit())
  19524. {
  19525. bool busy = false;
  19526. for (int i = sources.size(); --i >= 0;)
  19527. {
  19528. if (threadShouldExit())
  19529. return;
  19530. const ScopedLock sl (lock);
  19531. BufferingAudioSource* const b = sources[i];
  19532. if (b != 0 && b->readNextBufferChunk())
  19533. busy = true;
  19534. }
  19535. if (! busy)
  19536. wait (500);
  19537. }
  19538. }
  19539. void timerCallback()
  19540. {
  19541. stopTimer();
  19542. if (sources.size() == 0)
  19543. deleteInstance();
  19544. }
  19545. SharedBufferingAudioSourceThread (const SharedBufferingAudioSourceThread&);
  19546. SharedBufferingAudioSourceThread& operator= (const SharedBufferingAudioSourceThread&);
  19547. };
  19548. juce_ImplementSingleton (SharedBufferingAudioSourceThread)
  19549. BufferingAudioSource::BufferingAudioSource (PositionableAudioSource* source_,
  19550. const bool deleteSourceWhenDeleted_,
  19551. int numberOfSamplesToBuffer_)
  19552. : source (source_),
  19553. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  19554. numberOfSamplesToBuffer (jmax (1024, numberOfSamplesToBuffer_)),
  19555. buffer (2, 0),
  19556. bufferValidStart (0),
  19557. bufferValidEnd (0),
  19558. nextPlayPos (0),
  19559. wasSourceLooping (false)
  19560. {
  19561. jassert (source_ != 0);
  19562. jassert (numberOfSamplesToBuffer_ > 1024); // not much point using this class if you're
  19563. // not using a larger buffer..
  19564. }
  19565. BufferingAudioSource::~BufferingAudioSource()
  19566. {
  19567. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19568. if (thread != 0)
  19569. thread->removeSource (this);
  19570. if (deleteSourceWhenDeleted)
  19571. delete source;
  19572. }
  19573. void BufferingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate_)
  19574. {
  19575. source->prepareToPlay (samplesPerBlockExpected, sampleRate_);
  19576. sampleRate = sampleRate_;
  19577. buffer.setSize (2, jmax (samplesPerBlockExpected * 2, numberOfSamplesToBuffer));
  19578. buffer.clear();
  19579. bufferValidStart = 0;
  19580. bufferValidEnd = 0;
  19581. SharedBufferingAudioSourceThread::getInstance()->addSource (this);
  19582. while (bufferValidEnd - bufferValidStart < jmin (((int) sampleRate_) / 4,
  19583. buffer.getNumSamples() / 2))
  19584. {
  19585. SharedBufferingAudioSourceThread::getInstance()->notify();
  19586. Thread::sleep (5);
  19587. }
  19588. }
  19589. void BufferingAudioSource::releaseResources()
  19590. {
  19591. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19592. if (thread != 0)
  19593. thread->removeSource (this);
  19594. buffer.setSize (2, 0);
  19595. source->releaseResources();
  19596. }
  19597. void BufferingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19598. {
  19599. const ScopedLock sl (bufferStartPosLock);
  19600. const int validStart = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos) - nextPlayPos;
  19601. const int validEnd = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos + info.numSamples) - nextPlayPos;
  19602. if (validStart == validEnd)
  19603. {
  19604. // total cache miss
  19605. info.clearActiveBufferRegion();
  19606. }
  19607. else
  19608. {
  19609. if (validStart > 0)
  19610. info.buffer->clear (info.startSample, validStart); // partial cache miss at start
  19611. if (validEnd < info.numSamples)
  19612. info.buffer->clear (info.startSample + validEnd,
  19613. info.numSamples - validEnd); // partial cache miss at end
  19614. if (validStart < validEnd)
  19615. {
  19616. for (int chan = jmin (2, info.buffer->getNumChannels()); --chan >= 0;)
  19617. {
  19618. const int startBufferIndex = (validStart + nextPlayPos) % buffer.getNumSamples();
  19619. const int endBufferIndex = (validEnd + nextPlayPos) % buffer.getNumSamples();
  19620. if (startBufferIndex < endBufferIndex)
  19621. {
  19622. info.buffer->copyFrom (chan, info.startSample + validStart,
  19623. buffer,
  19624. chan, startBufferIndex,
  19625. validEnd - validStart);
  19626. }
  19627. else
  19628. {
  19629. const int initialSize = buffer.getNumSamples() - startBufferIndex;
  19630. info.buffer->copyFrom (chan, info.startSample + validStart,
  19631. buffer,
  19632. chan, startBufferIndex,
  19633. initialSize);
  19634. info.buffer->copyFrom (chan, info.startSample + validStart + initialSize,
  19635. buffer,
  19636. chan, 0,
  19637. (validEnd - validStart) - initialSize);
  19638. }
  19639. }
  19640. }
  19641. nextPlayPos += info.numSamples;
  19642. if (source->isLooping() && nextPlayPos > 0)
  19643. nextPlayPos %= source->getTotalLength();
  19644. }
  19645. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19646. if (thread != 0)
  19647. thread->notify();
  19648. }
  19649. int BufferingAudioSource::getNextReadPosition() const
  19650. {
  19651. return (source->isLooping() && nextPlayPos > 0)
  19652. ? nextPlayPos % source->getTotalLength()
  19653. : nextPlayPos;
  19654. }
  19655. void BufferingAudioSource::setNextReadPosition (int newPosition)
  19656. {
  19657. const ScopedLock sl (bufferStartPosLock);
  19658. nextPlayPos = newPosition;
  19659. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19660. if (thread != 0)
  19661. thread->notify();
  19662. }
  19663. bool BufferingAudioSource::readNextBufferChunk()
  19664. {
  19665. int newBVS, newBVE, sectionToReadStart, sectionToReadEnd;
  19666. {
  19667. const ScopedLock sl (bufferStartPosLock);
  19668. if (wasSourceLooping != isLooping())
  19669. {
  19670. wasSourceLooping = isLooping();
  19671. bufferValidStart = 0;
  19672. bufferValidEnd = 0;
  19673. }
  19674. newBVS = jmax (0, nextPlayPos);
  19675. newBVE = newBVS + buffer.getNumSamples() - 4;
  19676. sectionToReadStart = 0;
  19677. sectionToReadEnd = 0;
  19678. const int maxChunkSize = 2048;
  19679. if (newBVS < bufferValidStart || newBVS >= bufferValidEnd)
  19680. {
  19681. newBVE = jmin (newBVE, newBVS + maxChunkSize);
  19682. sectionToReadStart = newBVS;
  19683. sectionToReadEnd = newBVE;
  19684. bufferValidStart = 0;
  19685. bufferValidEnd = 0;
  19686. }
  19687. else if (abs (newBVS - bufferValidStart) > 512
  19688. || abs (newBVE - bufferValidEnd) > 512)
  19689. {
  19690. newBVE = jmin (newBVE, bufferValidEnd + maxChunkSize);
  19691. sectionToReadStart = bufferValidEnd;
  19692. sectionToReadEnd = newBVE;
  19693. bufferValidStart = newBVS;
  19694. bufferValidEnd = jmin (bufferValidEnd, newBVE);
  19695. }
  19696. }
  19697. if (sectionToReadStart != sectionToReadEnd)
  19698. {
  19699. const int bufferIndexStart = sectionToReadStart % buffer.getNumSamples();
  19700. const int bufferIndexEnd = sectionToReadEnd % buffer.getNumSamples();
  19701. if (bufferIndexStart < bufferIndexEnd)
  19702. {
  19703. readBufferSection (sectionToReadStart,
  19704. sectionToReadEnd - sectionToReadStart,
  19705. bufferIndexStart);
  19706. }
  19707. else
  19708. {
  19709. const int initialSize = buffer.getNumSamples() - bufferIndexStart;
  19710. readBufferSection (sectionToReadStart,
  19711. initialSize,
  19712. bufferIndexStart);
  19713. readBufferSection (sectionToReadStart + initialSize,
  19714. (sectionToReadEnd - sectionToReadStart) - initialSize,
  19715. 0);
  19716. }
  19717. const ScopedLock sl2 (bufferStartPosLock);
  19718. bufferValidStart = newBVS;
  19719. bufferValidEnd = newBVE;
  19720. return true;
  19721. }
  19722. else
  19723. {
  19724. return false;
  19725. }
  19726. }
  19727. void BufferingAudioSource::readBufferSection (int start, int length, int bufferOffset)
  19728. {
  19729. if (source->getNextReadPosition() != start)
  19730. source->setNextReadPosition (start);
  19731. AudioSourceChannelInfo info;
  19732. info.buffer = &buffer;
  19733. info.startSample = bufferOffset;
  19734. info.numSamples = length;
  19735. source->getNextAudioBlock (info);
  19736. }
  19737. END_JUCE_NAMESPACE
  19738. /*** End of inlined file: juce_BufferingAudioSource.cpp ***/
  19739. /*** Start of inlined file: juce_ChannelRemappingAudioSource.cpp ***/
  19740. BEGIN_JUCE_NAMESPACE
  19741. ChannelRemappingAudioSource::ChannelRemappingAudioSource (AudioSource* const source_,
  19742. const bool deleteSourceWhenDeleted_)
  19743. : requiredNumberOfChannels (2),
  19744. source (source_),
  19745. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  19746. buffer (2, 16)
  19747. {
  19748. remappedInfo.buffer = &buffer;
  19749. remappedInfo.startSample = 0;
  19750. }
  19751. ChannelRemappingAudioSource::~ChannelRemappingAudioSource()
  19752. {
  19753. if (deleteSourceWhenDeleted)
  19754. delete source;
  19755. }
  19756. void ChannelRemappingAudioSource::setNumberOfChannelsToProduce (const int requiredNumberOfChannels_)
  19757. {
  19758. const ScopedLock sl (lock);
  19759. requiredNumberOfChannels = requiredNumberOfChannels_;
  19760. }
  19761. void ChannelRemappingAudioSource::clearAllMappings()
  19762. {
  19763. const ScopedLock sl (lock);
  19764. remappedInputs.clear();
  19765. remappedOutputs.clear();
  19766. }
  19767. void ChannelRemappingAudioSource::setInputChannelMapping (const int destIndex, const int sourceIndex)
  19768. {
  19769. const ScopedLock sl (lock);
  19770. while (remappedInputs.size() < destIndex)
  19771. remappedInputs.add (-1);
  19772. remappedInputs.set (destIndex, sourceIndex);
  19773. }
  19774. void ChannelRemappingAudioSource::setOutputChannelMapping (const int sourceIndex, const int destIndex)
  19775. {
  19776. const ScopedLock sl (lock);
  19777. while (remappedOutputs.size() < sourceIndex)
  19778. remappedOutputs.add (-1);
  19779. remappedOutputs.set (sourceIndex, destIndex);
  19780. }
  19781. int ChannelRemappingAudioSource::getRemappedInputChannel (const int inputChannelIndex) const
  19782. {
  19783. const ScopedLock sl (lock);
  19784. if (inputChannelIndex >= 0 && inputChannelIndex < remappedInputs.size())
  19785. return remappedInputs.getUnchecked (inputChannelIndex);
  19786. return -1;
  19787. }
  19788. int ChannelRemappingAudioSource::getRemappedOutputChannel (const int outputChannelIndex) const
  19789. {
  19790. const ScopedLock sl (lock);
  19791. if (outputChannelIndex >= 0 && outputChannelIndex < remappedOutputs.size())
  19792. return remappedOutputs .getUnchecked (outputChannelIndex);
  19793. return -1;
  19794. }
  19795. void ChannelRemappingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19796. {
  19797. source->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19798. }
  19799. void ChannelRemappingAudioSource::releaseResources()
  19800. {
  19801. source->releaseResources();
  19802. }
  19803. void ChannelRemappingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  19804. {
  19805. const ScopedLock sl (lock);
  19806. buffer.setSize (requiredNumberOfChannels, bufferToFill.numSamples, false, false, true);
  19807. const int numChans = bufferToFill.buffer->getNumChannels();
  19808. int i;
  19809. for (i = 0; i < buffer.getNumChannels(); ++i)
  19810. {
  19811. const int remappedChan = getRemappedInputChannel (i);
  19812. if (remappedChan >= 0 && remappedChan < numChans)
  19813. {
  19814. buffer.copyFrom (i, 0, *bufferToFill.buffer,
  19815. remappedChan,
  19816. bufferToFill.startSample,
  19817. bufferToFill.numSamples);
  19818. }
  19819. else
  19820. {
  19821. buffer.clear (i, 0, bufferToFill.numSamples);
  19822. }
  19823. }
  19824. remappedInfo.numSamples = bufferToFill.numSamples;
  19825. source->getNextAudioBlock (remappedInfo);
  19826. bufferToFill.clearActiveBufferRegion();
  19827. for (i = 0; i < requiredNumberOfChannels; ++i)
  19828. {
  19829. const int remappedChan = getRemappedOutputChannel (i);
  19830. if (remappedChan >= 0 && remappedChan < numChans)
  19831. {
  19832. bufferToFill.buffer->addFrom (remappedChan, bufferToFill.startSample,
  19833. buffer, i, 0, bufferToFill.numSamples);
  19834. }
  19835. }
  19836. }
  19837. XmlElement* ChannelRemappingAudioSource::createXml() const
  19838. {
  19839. XmlElement* e = new XmlElement ("MAPPINGS");
  19840. String ins, outs;
  19841. int i;
  19842. const ScopedLock sl (lock);
  19843. for (i = 0; i < remappedInputs.size(); ++i)
  19844. ins << remappedInputs.getUnchecked(i) << ' ';
  19845. for (i = 0; i < remappedOutputs.size(); ++i)
  19846. outs << remappedOutputs.getUnchecked(i) << ' ';
  19847. e->setAttribute ("inputs", ins.trimEnd());
  19848. e->setAttribute ("outputs", outs.trimEnd());
  19849. return e;
  19850. }
  19851. void ChannelRemappingAudioSource::restoreFromXml (const XmlElement& e)
  19852. {
  19853. if (e.hasTagName ("MAPPINGS"))
  19854. {
  19855. const ScopedLock sl (lock);
  19856. clearAllMappings();
  19857. StringArray ins, outs;
  19858. ins.addTokens (e.getStringAttribute ("inputs"), false);
  19859. outs.addTokens (e.getStringAttribute ("outputs"), false);
  19860. int i;
  19861. for (i = 0; i < ins.size(); ++i)
  19862. remappedInputs.add (ins[i].getIntValue());
  19863. for (i = 0; i < outs.size(); ++i)
  19864. remappedOutputs.add (outs[i].getIntValue());
  19865. }
  19866. }
  19867. END_JUCE_NAMESPACE
  19868. /*** End of inlined file: juce_ChannelRemappingAudioSource.cpp ***/
  19869. /*** Start of inlined file: juce_IIRFilterAudioSource.cpp ***/
  19870. BEGIN_JUCE_NAMESPACE
  19871. IIRFilterAudioSource::IIRFilterAudioSource (AudioSource* const inputSource,
  19872. const bool deleteInputWhenDeleted_)
  19873. : input (inputSource),
  19874. deleteInputWhenDeleted (deleteInputWhenDeleted_)
  19875. {
  19876. jassert (inputSource != 0);
  19877. for (int i = 2; --i >= 0;)
  19878. iirFilters.add (new IIRFilter());
  19879. }
  19880. IIRFilterAudioSource::~IIRFilterAudioSource()
  19881. {
  19882. if (deleteInputWhenDeleted)
  19883. delete input;
  19884. }
  19885. void IIRFilterAudioSource::setFilterParameters (const IIRFilter& newSettings)
  19886. {
  19887. for (int i = iirFilters.size(); --i >= 0;)
  19888. iirFilters.getUnchecked(i)->copyCoefficientsFrom (newSettings);
  19889. }
  19890. void IIRFilterAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19891. {
  19892. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19893. for (int i = iirFilters.size(); --i >= 0;)
  19894. iirFilters.getUnchecked(i)->reset();
  19895. }
  19896. void IIRFilterAudioSource::releaseResources()
  19897. {
  19898. input->releaseResources();
  19899. }
  19900. void IIRFilterAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  19901. {
  19902. input->getNextAudioBlock (bufferToFill);
  19903. const int numChannels = bufferToFill.buffer->getNumChannels();
  19904. while (numChannels > iirFilters.size())
  19905. iirFilters.add (new IIRFilter (*iirFilters.getUnchecked (0)));
  19906. for (int i = 0; i < numChannels; ++i)
  19907. iirFilters.getUnchecked(i)
  19908. ->processSamples (bufferToFill.buffer->getSampleData (i, bufferToFill.startSample),
  19909. bufferToFill.numSamples);
  19910. }
  19911. END_JUCE_NAMESPACE
  19912. /*** End of inlined file: juce_IIRFilterAudioSource.cpp ***/
  19913. /*** Start of inlined file: juce_MixerAudioSource.cpp ***/
  19914. BEGIN_JUCE_NAMESPACE
  19915. MixerAudioSource::MixerAudioSource()
  19916. : tempBuffer (2, 0),
  19917. currentSampleRate (0.0),
  19918. bufferSizeExpected (0)
  19919. {
  19920. }
  19921. MixerAudioSource::~MixerAudioSource()
  19922. {
  19923. removeAllInputs();
  19924. }
  19925. void MixerAudioSource::addInputSource (AudioSource* input, const bool deleteWhenRemoved)
  19926. {
  19927. if (input != 0 && ! inputs.contains (input))
  19928. {
  19929. double localRate;
  19930. int localBufferSize;
  19931. {
  19932. const ScopedLock sl (lock);
  19933. localRate = currentSampleRate;
  19934. localBufferSize = bufferSizeExpected;
  19935. }
  19936. if (localRate != 0.0)
  19937. input->prepareToPlay (localBufferSize, localRate);
  19938. const ScopedLock sl (lock);
  19939. inputsToDelete.setBit (inputs.size(), deleteWhenRemoved);
  19940. inputs.add (input);
  19941. }
  19942. }
  19943. void MixerAudioSource::removeInputSource (AudioSource* input, const bool deleteInput)
  19944. {
  19945. if (input != 0)
  19946. {
  19947. int index;
  19948. {
  19949. const ScopedLock sl (lock);
  19950. index = inputs.indexOf (input);
  19951. if (index >= 0)
  19952. {
  19953. inputsToDelete.shiftBits (index, 1);
  19954. inputs.remove (index);
  19955. }
  19956. }
  19957. if (index >= 0)
  19958. {
  19959. input->releaseResources();
  19960. if (deleteInput)
  19961. delete input;
  19962. }
  19963. }
  19964. }
  19965. void MixerAudioSource::removeAllInputs()
  19966. {
  19967. OwnedArray<AudioSource> toDelete;
  19968. {
  19969. const ScopedLock sl (lock);
  19970. for (int i = inputs.size(); --i >= 0;)
  19971. if (inputsToDelete[i])
  19972. toDelete.add (inputs.getUnchecked(i));
  19973. }
  19974. }
  19975. void MixerAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19976. {
  19977. tempBuffer.setSize (2, samplesPerBlockExpected);
  19978. const ScopedLock sl (lock);
  19979. currentSampleRate = sampleRate;
  19980. bufferSizeExpected = samplesPerBlockExpected;
  19981. for (int i = inputs.size(); --i >= 0;)
  19982. inputs.getUnchecked(i)->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19983. }
  19984. void MixerAudioSource::releaseResources()
  19985. {
  19986. const ScopedLock sl (lock);
  19987. for (int i = inputs.size(); --i >= 0;)
  19988. inputs.getUnchecked(i)->releaseResources();
  19989. tempBuffer.setSize (2, 0);
  19990. currentSampleRate = 0;
  19991. bufferSizeExpected = 0;
  19992. }
  19993. void MixerAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19994. {
  19995. const ScopedLock sl (lock);
  19996. if (inputs.size() > 0)
  19997. {
  19998. inputs.getUnchecked(0)->getNextAudioBlock (info);
  19999. if (inputs.size() > 1)
  20000. {
  20001. tempBuffer.setSize (jmax (1, info.buffer->getNumChannels()),
  20002. info.buffer->getNumSamples());
  20003. AudioSourceChannelInfo info2;
  20004. info2.buffer = &tempBuffer;
  20005. info2.numSamples = info.numSamples;
  20006. info2.startSample = 0;
  20007. for (int i = 1; i < inputs.size(); ++i)
  20008. {
  20009. inputs.getUnchecked(i)->getNextAudioBlock (info2);
  20010. for (int chan = 0; chan < info.buffer->getNumChannels(); ++chan)
  20011. info.buffer->addFrom (chan, info.startSample, tempBuffer, chan, 0, info.numSamples);
  20012. }
  20013. }
  20014. }
  20015. else
  20016. {
  20017. info.clearActiveBufferRegion();
  20018. }
  20019. }
  20020. END_JUCE_NAMESPACE
  20021. /*** End of inlined file: juce_MixerAudioSource.cpp ***/
  20022. /*** Start of inlined file: juce_ResamplingAudioSource.cpp ***/
  20023. BEGIN_JUCE_NAMESPACE
  20024. ResamplingAudioSource::ResamplingAudioSource (AudioSource* const inputSource,
  20025. const bool deleteInputWhenDeleted_,
  20026. const int numChannels_)
  20027. : input (inputSource),
  20028. deleteInputWhenDeleted (deleteInputWhenDeleted_),
  20029. ratio (1.0),
  20030. lastRatio (1.0),
  20031. buffer (numChannels_, 0),
  20032. sampsInBuffer (0),
  20033. numChannels (numChannels_)
  20034. {
  20035. jassert (input != 0);
  20036. }
  20037. ResamplingAudioSource::~ResamplingAudioSource()
  20038. {
  20039. if (deleteInputWhenDeleted)
  20040. delete input;
  20041. }
  20042. void ResamplingAudioSource::setResamplingRatio (const double samplesInPerOutputSample)
  20043. {
  20044. jassert (samplesInPerOutputSample > 0);
  20045. const ScopedLock sl (ratioLock);
  20046. ratio = jmax (0.0, samplesInPerOutputSample);
  20047. }
  20048. void ResamplingAudioSource::prepareToPlay (int samplesPerBlockExpected,
  20049. double sampleRate)
  20050. {
  20051. const ScopedLock sl (ratioLock);
  20052. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  20053. buffer.setSize (numChannels, roundToInt (samplesPerBlockExpected * ratio) + 32);
  20054. buffer.clear();
  20055. sampsInBuffer = 0;
  20056. bufferPos = 0;
  20057. subSampleOffset = 0.0;
  20058. filterStates.calloc (numChannels);
  20059. srcBuffers.calloc (numChannels);
  20060. destBuffers.calloc (numChannels);
  20061. createLowPass (ratio);
  20062. resetFilters();
  20063. }
  20064. void ResamplingAudioSource::releaseResources()
  20065. {
  20066. input->releaseResources();
  20067. buffer.setSize (numChannels, 0);
  20068. }
  20069. void ResamplingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  20070. {
  20071. const ScopedLock sl (ratioLock);
  20072. if (lastRatio != ratio)
  20073. {
  20074. createLowPass (ratio);
  20075. lastRatio = ratio;
  20076. }
  20077. const int sampsNeeded = roundToInt (info.numSamples * ratio) + 2;
  20078. int bufferSize = buffer.getNumSamples();
  20079. if (bufferSize < sampsNeeded + 8)
  20080. {
  20081. bufferPos %= bufferSize;
  20082. bufferSize = sampsNeeded + 32;
  20083. buffer.setSize (buffer.getNumChannels(), bufferSize, true, true);
  20084. }
  20085. bufferPos %= bufferSize;
  20086. int endOfBufferPos = bufferPos + sampsInBuffer;
  20087. const int channelsToProcess = jmin (numChannels, info.buffer->getNumChannels());
  20088. while (sampsNeeded > sampsInBuffer)
  20089. {
  20090. endOfBufferPos %= bufferSize;
  20091. int numToDo = jmin (sampsNeeded - sampsInBuffer,
  20092. bufferSize - endOfBufferPos);
  20093. AudioSourceChannelInfo readInfo;
  20094. readInfo.buffer = &buffer;
  20095. readInfo.numSamples = numToDo;
  20096. readInfo.startSample = endOfBufferPos;
  20097. input->getNextAudioBlock (readInfo);
  20098. if (ratio > 1.0001)
  20099. {
  20100. // for down-sampling, pre-apply the filter..
  20101. for (int i = channelsToProcess; --i >= 0;)
  20102. applyFilter (buffer.getSampleData (i, endOfBufferPos), numToDo, filterStates[i]);
  20103. }
  20104. sampsInBuffer += numToDo;
  20105. endOfBufferPos += numToDo;
  20106. }
  20107. for (int channel = 0; channel < channelsToProcess; ++channel)
  20108. {
  20109. destBuffers[channel] = info.buffer->getSampleData (channel, info.startSample);
  20110. srcBuffers[channel] = buffer.getSampleData (channel, 0);
  20111. }
  20112. int nextPos = (bufferPos + 1) % bufferSize;
  20113. for (int m = info.numSamples; --m >= 0;)
  20114. {
  20115. const float alpha = (float) subSampleOffset;
  20116. const float invAlpha = 1.0f - alpha;
  20117. for (int channel = 0; channel < channelsToProcess; ++channel)
  20118. *destBuffers[channel]++ = srcBuffers[channel][bufferPos] * invAlpha + srcBuffers[channel][nextPos] * alpha;
  20119. subSampleOffset += ratio;
  20120. jassert (sampsInBuffer > 0);
  20121. while (subSampleOffset >= 1.0)
  20122. {
  20123. if (++bufferPos >= bufferSize)
  20124. bufferPos = 0;
  20125. --sampsInBuffer;
  20126. nextPos = (bufferPos + 1) % bufferSize;
  20127. subSampleOffset -= 1.0;
  20128. }
  20129. }
  20130. if (ratio < 0.9999)
  20131. {
  20132. // for up-sampling, apply the filter after transposing..
  20133. for (int i = channelsToProcess; --i >= 0;)
  20134. applyFilter (info.buffer->getSampleData (i, info.startSample), info.numSamples, filterStates[i]);
  20135. }
  20136. else if (ratio <= 1.0001)
  20137. {
  20138. // if the filter's not currently being applied, keep it stoked with the last couple of samples to avoid discontinuities
  20139. for (int i = channelsToProcess; --i >= 0;)
  20140. {
  20141. const float* const endOfBuffer = info.buffer->getSampleData (i, info.startSample + info.numSamples - 1);
  20142. FilterState& fs = filterStates[i];
  20143. if (info.numSamples > 1)
  20144. {
  20145. fs.y2 = fs.x2 = *(endOfBuffer - 1);
  20146. }
  20147. else
  20148. {
  20149. fs.y2 = fs.y1;
  20150. fs.x2 = fs.x1;
  20151. }
  20152. fs.y1 = fs.x1 = *endOfBuffer;
  20153. }
  20154. }
  20155. jassert (sampsInBuffer >= 0);
  20156. }
  20157. void ResamplingAudioSource::createLowPass (const double frequencyRatio)
  20158. {
  20159. const double proportionalRate = (frequencyRatio > 1.0) ? 0.5 / frequencyRatio
  20160. : 0.5 * frequencyRatio;
  20161. const double n = 1.0 / tan (double_Pi * jmax (0.001, proportionalRate));
  20162. const double nSquared = n * n;
  20163. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  20164. setFilterCoefficients (c1,
  20165. c1 * 2.0f,
  20166. c1,
  20167. 1.0,
  20168. c1 * 2.0 * (1.0 - nSquared),
  20169. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  20170. }
  20171. void ResamplingAudioSource::setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6)
  20172. {
  20173. const double a = 1.0 / c4;
  20174. c1 *= a;
  20175. c2 *= a;
  20176. c3 *= a;
  20177. c5 *= a;
  20178. c6 *= a;
  20179. coefficients[0] = c1;
  20180. coefficients[1] = c2;
  20181. coefficients[2] = c3;
  20182. coefficients[3] = c4;
  20183. coefficients[4] = c5;
  20184. coefficients[5] = c6;
  20185. }
  20186. void ResamplingAudioSource::resetFilters()
  20187. {
  20188. zeromem (filterStates, sizeof (FilterState) * numChannels);
  20189. }
  20190. void ResamplingAudioSource::applyFilter (float* samples, int num, FilterState& fs)
  20191. {
  20192. while (--num >= 0)
  20193. {
  20194. const double in = *samples;
  20195. double out = coefficients[0] * in
  20196. + coefficients[1] * fs.x1
  20197. + coefficients[2] * fs.x2
  20198. - coefficients[4] * fs.y1
  20199. - coefficients[5] * fs.y2;
  20200. #if JUCE_INTEL
  20201. if (! (out < -1.0e-8 || out > 1.0e-8))
  20202. out = 0;
  20203. #endif
  20204. fs.x2 = fs.x1;
  20205. fs.x1 = in;
  20206. fs.y2 = fs.y1;
  20207. fs.y1 = out;
  20208. *samples++ = (float) out;
  20209. }
  20210. }
  20211. END_JUCE_NAMESPACE
  20212. /*** End of inlined file: juce_ResamplingAudioSource.cpp ***/
  20213. /*** Start of inlined file: juce_ToneGeneratorAudioSource.cpp ***/
  20214. BEGIN_JUCE_NAMESPACE
  20215. ToneGeneratorAudioSource::ToneGeneratorAudioSource()
  20216. : frequency (1000.0),
  20217. sampleRate (44100.0),
  20218. currentPhase (0.0),
  20219. phasePerSample (0.0),
  20220. amplitude (0.5f)
  20221. {
  20222. }
  20223. ToneGeneratorAudioSource::~ToneGeneratorAudioSource()
  20224. {
  20225. }
  20226. void ToneGeneratorAudioSource::setAmplitude (const float newAmplitude)
  20227. {
  20228. amplitude = newAmplitude;
  20229. }
  20230. void ToneGeneratorAudioSource::setFrequency (const double newFrequencyHz)
  20231. {
  20232. frequency = newFrequencyHz;
  20233. phasePerSample = 0.0;
  20234. }
  20235. void ToneGeneratorAudioSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  20236. double sampleRate_)
  20237. {
  20238. currentPhase = 0.0;
  20239. phasePerSample = 0.0;
  20240. sampleRate = sampleRate_;
  20241. }
  20242. void ToneGeneratorAudioSource::releaseResources()
  20243. {
  20244. }
  20245. void ToneGeneratorAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  20246. {
  20247. if (phasePerSample == 0.0)
  20248. phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  20249. for (int i = 0; i < info.numSamples; ++i)
  20250. {
  20251. const float sample = amplitude * (float) std::sin (currentPhase);
  20252. currentPhase += phasePerSample;
  20253. for (int j = info.buffer->getNumChannels(); --j >= 0;)
  20254. *info.buffer->getSampleData (j, info.startSample + i) = sample;
  20255. }
  20256. }
  20257. END_JUCE_NAMESPACE
  20258. /*** End of inlined file: juce_ToneGeneratorAudioSource.cpp ***/
  20259. /*** Start of inlined file: juce_AudioDeviceManager.cpp ***/
  20260. BEGIN_JUCE_NAMESPACE
  20261. AudioDeviceManager::AudioDeviceSetup::AudioDeviceSetup()
  20262. : sampleRate (0),
  20263. bufferSize (0),
  20264. useDefaultInputChannels (true),
  20265. useDefaultOutputChannels (true)
  20266. {
  20267. }
  20268. bool AudioDeviceManager::AudioDeviceSetup::operator== (const AudioDeviceManager::AudioDeviceSetup& other) const
  20269. {
  20270. return outputDeviceName == other.outputDeviceName
  20271. && inputDeviceName == other.inputDeviceName
  20272. && sampleRate == other.sampleRate
  20273. && bufferSize == other.bufferSize
  20274. && inputChannels == other.inputChannels
  20275. && useDefaultInputChannels == other.useDefaultInputChannels
  20276. && outputChannels == other.outputChannels
  20277. && useDefaultOutputChannels == other.useDefaultOutputChannels;
  20278. }
  20279. AudioDeviceManager::AudioDeviceManager()
  20280. : currentAudioDevice (0),
  20281. numInputChansNeeded (0),
  20282. numOutputChansNeeded (2),
  20283. listNeedsScanning (true),
  20284. useInputNames (false),
  20285. inputLevelMeasurementEnabledCount (0),
  20286. inputLevel (0),
  20287. tempBuffer (2, 2),
  20288. defaultMidiOutput (0),
  20289. cpuUsageMs (0),
  20290. timeToCpuScale (0)
  20291. {
  20292. callbackHandler.owner = this;
  20293. }
  20294. AudioDeviceManager::~AudioDeviceManager()
  20295. {
  20296. currentAudioDevice = 0;
  20297. defaultMidiOutput = 0;
  20298. }
  20299. void AudioDeviceManager::createDeviceTypesIfNeeded()
  20300. {
  20301. if (availableDeviceTypes.size() == 0)
  20302. {
  20303. createAudioDeviceTypes (availableDeviceTypes);
  20304. while (lastDeviceTypeConfigs.size() < availableDeviceTypes.size())
  20305. lastDeviceTypeConfigs.add (new AudioDeviceSetup());
  20306. if (availableDeviceTypes.size() > 0)
  20307. currentDeviceType = availableDeviceTypes.getUnchecked(0)->getTypeName();
  20308. }
  20309. }
  20310. const OwnedArray <AudioIODeviceType>& AudioDeviceManager::getAvailableDeviceTypes()
  20311. {
  20312. scanDevicesIfNeeded();
  20313. return availableDeviceTypes;
  20314. }
  20315. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio();
  20316. AudioIODeviceType* juce_createAudioIODeviceType_iPhoneAudio();
  20317. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI();
  20318. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound();
  20319. AudioIODeviceType* juce_createAudioIODeviceType_ASIO();
  20320. AudioIODeviceType* juce_createAudioIODeviceType_ALSA();
  20321. AudioIODeviceType* juce_createAudioIODeviceType_JACK();
  20322. void AudioDeviceManager::createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& list)
  20323. {
  20324. (void) list; // (to avoid 'unused param' warnings)
  20325. #if JUCE_WINDOWS
  20326. #if JUCE_WASAPI
  20327. if (SystemStats::getOperatingSystemType() >= SystemStats::WinVista)
  20328. list.add (juce_createAudioIODeviceType_WASAPI());
  20329. #endif
  20330. #if JUCE_DIRECTSOUND
  20331. list.add (juce_createAudioIODeviceType_DirectSound());
  20332. #endif
  20333. #if JUCE_ASIO
  20334. list.add (juce_createAudioIODeviceType_ASIO());
  20335. #endif
  20336. #endif
  20337. #if JUCE_MAC
  20338. list.add (juce_createAudioIODeviceType_CoreAudio());
  20339. #endif
  20340. #if JUCE_IOS
  20341. list.add (juce_createAudioIODeviceType_iPhoneAudio());
  20342. #endif
  20343. #if JUCE_LINUX && JUCE_ALSA
  20344. list.add (juce_createAudioIODeviceType_ALSA());
  20345. #endif
  20346. #if JUCE_LINUX && JUCE_JACK
  20347. list.add (juce_createAudioIODeviceType_JACK());
  20348. #endif
  20349. }
  20350. const String AudioDeviceManager::initialise (const int numInputChannelsNeeded,
  20351. const int numOutputChannelsNeeded,
  20352. const XmlElement* const e,
  20353. const bool selectDefaultDeviceOnFailure,
  20354. const String& preferredDefaultDeviceName,
  20355. const AudioDeviceSetup* preferredSetupOptions)
  20356. {
  20357. scanDevicesIfNeeded();
  20358. numInputChansNeeded = numInputChannelsNeeded;
  20359. numOutputChansNeeded = numOutputChannelsNeeded;
  20360. if (e != 0 && e->hasTagName ("DEVICESETUP"))
  20361. {
  20362. lastExplicitSettings = new XmlElement (*e);
  20363. String error;
  20364. AudioDeviceSetup setup;
  20365. if (preferredSetupOptions != 0)
  20366. setup = *preferredSetupOptions;
  20367. if (e->getStringAttribute ("audioDeviceName").isNotEmpty())
  20368. {
  20369. setup.inputDeviceName = setup.outputDeviceName
  20370. = e->getStringAttribute ("audioDeviceName");
  20371. }
  20372. else
  20373. {
  20374. setup.inputDeviceName = e->getStringAttribute ("audioInputDeviceName");
  20375. setup.outputDeviceName = e->getStringAttribute ("audioOutputDeviceName");
  20376. }
  20377. currentDeviceType = e->getStringAttribute ("deviceType");
  20378. if (currentDeviceType.isEmpty())
  20379. {
  20380. AudioIODeviceType* const type = findType (setup.inputDeviceName, setup.outputDeviceName);
  20381. if (type != 0)
  20382. currentDeviceType = type->getTypeName();
  20383. else if (availableDeviceTypes.size() > 0)
  20384. currentDeviceType = availableDeviceTypes[0]->getTypeName();
  20385. }
  20386. setup.bufferSize = e->getIntAttribute ("audioDeviceBufferSize");
  20387. setup.sampleRate = e->getDoubleAttribute ("audioDeviceRate");
  20388. setup.inputChannels.parseString (e->getStringAttribute ("audioDeviceInChans", "11"), 2);
  20389. setup.outputChannels.parseString (e->getStringAttribute ("audioDeviceOutChans", "11"), 2);
  20390. setup.useDefaultInputChannels = ! e->hasAttribute ("audioDeviceInChans");
  20391. setup.useDefaultOutputChannels = ! e->hasAttribute ("audioDeviceOutChans");
  20392. error = setAudioDeviceSetup (setup, true);
  20393. midiInsFromXml.clear();
  20394. forEachXmlChildElementWithTagName (*e, c, "MIDIINPUT")
  20395. midiInsFromXml.add (c->getStringAttribute ("name"));
  20396. const StringArray allMidiIns (MidiInput::getDevices());
  20397. for (int i = allMidiIns.size(); --i >= 0;)
  20398. setMidiInputEnabled (allMidiIns[i], midiInsFromXml.contains (allMidiIns[i]));
  20399. if (error.isNotEmpty() && selectDefaultDeviceOnFailure)
  20400. error = initialise (numInputChannelsNeeded, numOutputChannelsNeeded, 0,
  20401. false, preferredDefaultDeviceName);
  20402. setDefaultMidiOutput (e->getStringAttribute ("defaultMidiOutput"));
  20403. return error;
  20404. }
  20405. else
  20406. {
  20407. AudioDeviceSetup setup;
  20408. if (preferredSetupOptions != 0)
  20409. {
  20410. setup = *preferredSetupOptions;
  20411. }
  20412. else if (preferredDefaultDeviceName.isNotEmpty())
  20413. {
  20414. for (int j = availableDeviceTypes.size(); --j >= 0;)
  20415. {
  20416. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(j);
  20417. StringArray outs (type->getDeviceNames (false));
  20418. int i;
  20419. for (i = 0; i < outs.size(); ++i)
  20420. {
  20421. if (outs[i].matchesWildcard (preferredDefaultDeviceName, true))
  20422. {
  20423. setup.outputDeviceName = outs[i];
  20424. break;
  20425. }
  20426. }
  20427. StringArray ins (type->getDeviceNames (true));
  20428. for (i = 0; i < ins.size(); ++i)
  20429. {
  20430. if (ins[i].matchesWildcard (preferredDefaultDeviceName, true))
  20431. {
  20432. setup.inputDeviceName = ins[i];
  20433. break;
  20434. }
  20435. }
  20436. }
  20437. }
  20438. insertDefaultDeviceNames (setup);
  20439. return setAudioDeviceSetup (setup, false);
  20440. }
  20441. }
  20442. void AudioDeviceManager::insertDefaultDeviceNames (AudioDeviceSetup& setup) const
  20443. {
  20444. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  20445. if (type != 0)
  20446. {
  20447. if (setup.outputDeviceName.isEmpty())
  20448. setup.outputDeviceName = type->getDeviceNames (false) [type->getDefaultDeviceIndex (false)];
  20449. if (setup.inputDeviceName.isEmpty())
  20450. setup.inputDeviceName = type->getDeviceNames (true) [type->getDefaultDeviceIndex (true)];
  20451. }
  20452. }
  20453. XmlElement* AudioDeviceManager::createStateXml() const
  20454. {
  20455. return lastExplicitSettings != 0 ? new XmlElement (*lastExplicitSettings) : 0;
  20456. }
  20457. void AudioDeviceManager::scanDevicesIfNeeded()
  20458. {
  20459. if (listNeedsScanning)
  20460. {
  20461. listNeedsScanning = false;
  20462. createDeviceTypesIfNeeded();
  20463. for (int i = availableDeviceTypes.size(); --i >= 0;)
  20464. availableDeviceTypes.getUnchecked(i)->scanForDevices();
  20465. }
  20466. }
  20467. AudioIODeviceType* AudioDeviceManager::findType (const String& inputName, const String& outputName)
  20468. {
  20469. scanDevicesIfNeeded();
  20470. for (int i = availableDeviceTypes.size(); --i >= 0;)
  20471. {
  20472. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(i);
  20473. if ((inputName.isNotEmpty() && type->getDeviceNames (true).contains (inputName, true))
  20474. || (outputName.isNotEmpty() && type->getDeviceNames (false).contains (outputName, true)))
  20475. {
  20476. return type;
  20477. }
  20478. }
  20479. return 0;
  20480. }
  20481. void AudioDeviceManager::getAudioDeviceSetup (AudioDeviceSetup& setup)
  20482. {
  20483. setup = currentSetup;
  20484. }
  20485. void AudioDeviceManager::deleteCurrentDevice()
  20486. {
  20487. currentAudioDevice = 0;
  20488. currentSetup.inputDeviceName = String::empty;
  20489. currentSetup.outputDeviceName = String::empty;
  20490. }
  20491. void AudioDeviceManager::setCurrentAudioDeviceType (const String& type,
  20492. const bool treatAsChosenDevice)
  20493. {
  20494. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  20495. {
  20496. if (availableDeviceTypes.getUnchecked(i)->getTypeName() == type
  20497. && currentDeviceType != type)
  20498. {
  20499. currentDeviceType = type;
  20500. AudioDeviceSetup s (*lastDeviceTypeConfigs.getUnchecked(i));
  20501. insertDefaultDeviceNames (s);
  20502. setAudioDeviceSetup (s, treatAsChosenDevice);
  20503. sendChangeMessage (this);
  20504. break;
  20505. }
  20506. }
  20507. }
  20508. AudioIODeviceType* AudioDeviceManager::getCurrentDeviceTypeObject() const
  20509. {
  20510. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  20511. if (availableDeviceTypes[i]->getTypeName() == currentDeviceType)
  20512. return availableDeviceTypes[i];
  20513. return availableDeviceTypes[0];
  20514. }
  20515. const String AudioDeviceManager::setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  20516. const bool treatAsChosenDevice)
  20517. {
  20518. jassert (&newSetup != &currentSetup); // this will have no effect
  20519. if (newSetup == currentSetup && currentAudioDevice != 0)
  20520. return String::empty;
  20521. if (! (newSetup == currentSetup))
  20522. sendChangeMessage (this);
  20523. stopDevice();
  20524. const String newInputDeviceName (numInputChansNeeded == 0 ? String::empty : newSetup.inputDeviceName);
  20525. const String newOutputDeviceName (numOutputChansNeeded == 0 ? String::empty : newSetup.outputDeviceName);
  20526. String error;
  20527. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  20528. if (type == 0 || (newInputDeviceName.isEmpty() && newOutputDeviceName.isEmpty()))
  20529. {
  20530. deleteCurrentDevice();
  20531. if (treatAsChosenDevice)
  20532. updateXml();
  20533. return String::empty;
  20534. }
  20535. if (currentSetup.inputDeviceName != newInputDeviceName
  20536. || currentSetup.outputDeviceName != newOutputDeviceName
  20537. || currentAudioDevice == 0)
  20538. {
  20539. deleteCurrentDevice();
  20540. scanDevicesIfNeeded();
  20541. if (newOutputDeviceName.isNotEmpty()
  20542. && ! type->getDeviceNames (false).contains (newOutputDeviceName))
  20543. {
  20544. return "No such device: " + newOutputDeviceName;
  20545. }
  20546. if (newInputDeviceName.isNotEmpty()
  20547. && ! type->getDeviceNames (true).contains (newInputDeviceName))
  20548. {
  20549. return "No such device: " + newInputDeviceName;
  20550. }
  20551. currentAudioDevice = type->createDevice (newOutputDeviceName, newInputDeviceName);
  20552. if (currentAudioDevice == 0)
  20553. 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!";
  20554. else
  20555. error = currentAudioDevice->getLastError();
  20556. if (error.isNotEmpty())
  20557. {
  20558. deleteCurrentDevice();
  20559. return error;
  20560. }
  20561. if (newSetup.useDefaultInputChannels)
  20562. {
  20563. inputChannels.clear();
  20564. inputChannels.setRange (0, numInputChansNeeded, true);
  20565. }
  20566. if (newSetup.useDefaultOutputChannels)
  20567. {
  20568. outputChannels.clear();
  20569. outputChannels.setRange (0, numOutputChansNeeded, true);
  20570. }
  20571. if (newInputDeviceName.isEmpty())
  20572. inputChannels.clear();
  20573. if (newOutputDeviceName.isEmpty())
  20574. outputChannels.clear();
  20575. }
  20576. if (! newSetup.useDefaultInputChannels)
  20577. inputChannels = newSetup.inputChannels;
  20578. if (! newSetup.useDefaultOutputChannels)
  20579. outputChannels = newSetup.outputChannels;
  20580. currentSetup = newSetup;
  20581. currentSetup.sampleRate = chooseBestSampleRate (newSetup.sampleRate);
  20582. error = currentAudioDevice->open (inputChannels,
  20583. outputChannels,
  20584. currentSetup.sampleRate,
  20585. currentSetup.bufferSize);
  20586. if (error.isEmpty())
  20587. {
  20588. currentDeviceType = currentAudioDevice->getTypeName();
  20589. currentAudioDevice->start (&callbackHandler);
  20590. currentSetup.sampleRate = currentAudioDevice->getCurrentSampleRate();
  20591. currentSetup.bufferSize = currentAudioDevice->getCurrentBufferSizeSamples();
  20592. currentSetup.inputChannels = currentAudioDevice->getActiveInputChannels();
  20593. currentSetup.outputChannels = currentAudioDevice->getActiveOutputChannels();
  20594. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  20595. if (availableDeviceTypes.getUnchecked (i)->getTypeName() == currentDeviceType)
  20596. *(lastDeviceTypeConfigs.getUnchecked (i)) = currentSetup;
  20597. if (treatAsChosenDevice)
  20598. updateXml();
  20599. }
  20600. else
  20601. {
  20602. deleteCurrentDevice();
  20603. }
  20604. return error;
  20605. }
  20606. double AudioDeviceManager::chooseBestSampleRate (double rate) const
  20607. {
  20608. jassert (currentAudioDevice != 0);
  20609. if (rate > 0)
  20610. {
  20611. bool ok = false;
  20612. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  20613. {
  20614. const double sr = currentAudioDevice->getSampleRate (i);
  20615. if (sr == rate)
  20616. ok = true;
  20617. }
  20618. if (! ok)
  20619. rate = 0;
  20620. }
  20621. if (rate == 0)
  20622. {
  20623. double lowestAbove44 = 0.0;
  20624. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  20625. {
  20626. const double sr = currentAudioDevice->getSampleRate (i);
  20627. if (sr >= 44100.0 && (lowestAbove44 == 0 || sr < lowestAbove44))
  20628. lowestAbove44 = sr;
  20629. }
  20630. if (lowestAbove44 == 0.0)
  20631. rate = currentAudioDevice->getSampleRate (0);
  20632. else
  20633. rate = lowestAbove44;
  20634. }
  20635. return rate;
  20636. }
  20637. void AudioDeviceManager::stopDevice()
  20638. {
  20639. if (currentAudioDevice != 0)
  20640. currentAudioDevice->stop();
  20641. testSound = 0;
  20642. }
  20643. void AudioDeviceManager::closeAudioDevice()
  20644. {
  20645. stopDevice();
  20646. currentAudioDevice = 0;
  20647. }
  20648. void AudioDeviceManager::restartLastAudioDevice()
  20649. {
  20650. if (currentAudioDevice == 0)
  20651. {
  20652. if (currentSetup.inputDeviceName.isEmpty()
  20653. && currentSetup.outputDeviceName.isEmpty())
  20654. {
  20655. // This method will only reload the last device that was running
  20656. // before closeAudioDevice() was called - you need to actually open
  20657. // one first, with setAudioDevice().
  20658. jassertfalse;
  20659. return;
  20660. }
  20661. AudioDeviceSetup s (currentSetup);
  20662. setAudioDeviceSetup (s, false);
  20663. }
  20664. }
  20665. void AudioDeviceManager::updateXml()
  20666. {
  20667. lastExplicitSettings = new XmlElement ("DEVICESETUP");
  20668. lastExplicitSettings->setAttribute ("deviceType", currentDeviceType);
  20669. lastExplicitSettings->setAttribute ("audioOutputDeviceName", currentSetup.outputDeviceName);
  20670. lastExplicitSettings->setAttribute ("audioInputDeviceName", currentSetup.inputDeviceName);
  20671. if (currentAudioDevice != 0)
  20672. {
  20673. lastExplicitSettings->setAttribute ("audioDeviceRate", currentAudioDevice->getCurrentSampleRate());
  20674. if (currentAudioDevice->getDefaultBufferSize() != currentAudioDevice->getCurrentBufferSizeSamples())
  20675. lastExplicitSettings->setAttribute ("audioDeviceBufferSize", currentAudioDevice->getCurrentBufferSizeSamples());
  20676. if (! currentSetup.useDefaultInputChannels)
  20677. lastExplicitSettings->setAttribute ("audioDeviceInChans", currentSetup.inputChannels.toString (2));
  20678. if (! currentSetup.useDefaultOutputChannels)
  20679. lastExplicitSettings->setAttribute ("audioDeviceOutChans", currentSetup.outputChannels.toString (2));
  20680. }
  20681. for (int i = 0; i < enabledMidiInputs.size(); ++i)
  20682. {
  20683. XmlElement* const m = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  20684. m->setAttribute ("name", enabledMidiInputs[i]->getName());
  20685. }
  20686. if (midiInsFromXml.size() > 0)
  20687. {
  20688. // Add any midi devices that have been enabled before, but which aren't currently
  20689. // open because the device has been disconnected.
  20690. const StringArray availableMidiDevices (MidiInput::getDevices());
  20691. for (int i = 0; i < midiInsFromXml.size(); ++i)
  20692. {
  20693. if (! availableMidiDevices.contains (midiInsFromXml[i], true))
  20694. {
  20695. XmlElement* const m = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  20696. m->setAttribute ("name", midiInsFromXml[i]);
  20697. }
  20698. }
  20699. }
  20700. if (defaultMidiOutputName.isNotEmpty())
  20701. lastExplicitSettings->setAttribute ("defaultMidiOutput", defaultMidiOutputName);
  20702. }
  20703. void AudioDeviceManager::addAudioCallback (AudioIODeviceCallback* newCallback)
  20704. {
  20705. {
  20706. const ScopedLock sl (audioCallbackLock);
  20707. if (callbacks.contains (newCallback))
  20708. return;
  20709. }
  20710. if (currentAudioDevice != 0 && newCallback != 0)
  20711. newCallback->audioDeviceAboutToStart (currentAudioDevice);
  20712. const ScopedLock sl (audioCallbackLock);
  20713. callbacks.add (newCallback);
  20714. }
  20715. void AudioDeviceManager::removeAudioCallback (AudioIODeviceCallback* callback)
  20716. {
  20717. if (callback != 0)
  20718. {
  20719. bool needsDeinitialising = currentAudioDevice != 0;
  20720. {
  20721. const ScopedLock sl (audioCallbackLock);
  20722. needsDeinitialising = needsDeinitialising && callbacks.contains (callback);
  20723. callbacks.removeValue (callback);
  20724. }
  20725. if (needsDeinitialising)
  20726. callback->audioDeviceStopped();
  20727. }
  20728. }
  20729. void AudioDeviceManager::audioDeviceIOCallbackInt (const float** inputChannelData,
  20730. int numInputChannels,
  20731. float** outputChannelData,
  20732. int numOutputChannels,
  20733. int numSamples)
  20734. {
  20735. const ScopedLock sl (audioCallbackLock);
  20736. if (inputLevelMeasurementEnabledCount > 0)
  20737. {
  20738. for (int j = 0; j < numSamples; ++j)
  20739. {
  20740. float s = 0;
  20741. for (int i = 0; i < numInputChannels; ++i)
  20742. s += std::abs (inputChannelData[i][j]);
  20743. s /= numInputChannels;
  20744. const double decayFactor = 0.99992;
  20745. if (s > inputLevel)
  20746. inputLevel = s;
  20747. else if (inputLevel > 0.001f)
  20748. inputLevel *= decayFactor;
  20749. else
  20750. inputLevel = 0;
  20751. }
  20752. }
  20753. if (callbacks.size() > 0)
  20754. {
  20755. const double callbackStartTime = Time::getMillisecondCounterHiRes();
  20756. tempBuffer.setSize (jmax (1, numOutputChannels), jmax (1, numSamples), false, false, true);
  20757. callbacks.getUnchecked(0)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  20758. outputChannelData, numOutputChannels, numSamples);
  20759. float** const tempChans = tempBuffer.getArrayOfChannels();
  20760. for (int i = callbacks.size(); --i > 0;)
  20761. {
  20762. callbacks.getUnchecked(i)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  20763. tempChans, numOutputChannels, numSamples);
  20764. for (int chan = 0; chan < numOutputChannels; ++chan)
  20765. {
  20766. const float* const src = tempChans [chan];
  20767. float* const dst = outputChannelData [chan];
  20768. if (src != 0 && dst != 0)
  20769. for (int j = 0; j < numSamples; ++j)
  20770. dst[j] += src[j];
  20771. }
  20772. }
  20773. const double msTaken = Time::getMillisecondCounterHiRes() - callbackStartTime;
  20774. const double filterAmount = 0.2;
  20775. cpuUsageMs += filterAmount * (msTaken - cpuUsageMs);
  20776. }
  20777. else
  20778. {
  20779. for (int i = 0; i < numOutputChannels; ++i)
  20780. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  20781. }
  20782. if (testSound != 0)
  20783. {
  20784. const int numSamps = jmin (numSamples, testSound->getNumSamples() - testSoundPosition);
  20785. const float* const src = testSound->getSampleData (0, testSoundPosition);
  20786. for (int i = 0; i < numOutputChannels; ++i)
  20787. for (int j = 0; j < numSamps; ++j)
  20788. outputChannelData [i][j] += src[j];
  20789. testSoundPosition += numSamps;
  20790. if (testSoundPosition >= testSound->getNumSamples())
  20791. testSound = 0;
  20792. }
  20793. }
  20794. void AudioDeviceManager::audioDeviceAboutToStartInt (AudioIODevice* const device)
  20795. {
  20796. cpuUsageMs = 0;
  20797. const double sampleRate = device->getCurrentSampleRate();
  20798. const int blockSize = device->getCurrentBufferSizeSamples();
  20799. if (sampleRate > 0.0 && blockSize > 0)
  20800. {
  20801. const double msPerBlock = 1000.0 * blockSize / sampleRate;
  20802. timeToCpuScale = (msPerBlock > 0.0) ? (1.0 / msPerBlock) : 0.0;
  20803. }
  20804. {
  20805. const ScopedLock sl (audioCallbackLock);
  20806. for (int i = callbacks.size(); --i >= 0;)
  20807. callbacks.getUnchecked(i)->audioDeviceAboutToStart (device);
  20808. }
  20809. sendChangeMessage (this);
  20810. }
  20811. void AudioDeviceManager::audioDeviceStoppedInt()
  20812. {
  20813. cpuUsageMs = 0;
  20814. timeToCpuScale = 0;
  20815. sendChangeMessage (this);
  20816. const ScopedLock sl (audioCallbackLock);
  20817. for (int i = callbacks.size(); --i >= 0;)
  20818. callbacks.getUnchecked(i)->audioDeviceStopped();
  20819. }
  20820. double AudioDeviceManager::getCpuUsage() const
  20821. {
  20822. return jlimit (0.0, 1.0, timeToCpuScale * cpuUsageMs);
  20823. }
  20824. void AudioDeviceManager::setMidiInputEnabled (const String& name,
  20825. const bool enabled)
  20826. {
  20827. if (enabled != isMidiInputEnabled (name))
  20828. {
  20829. if (enabled)
  20830. {
  20831. const int index = MidiInput::getDevices().indexOf (name);
  20832. if (index >= 0)
  20833. {
  20834. MidiInput* const min = MidiInput::openDevice (index, &callbackHandler);
  20835. if (min != 0)
  20836. {
  20837. enabledMidiInputs.add (min);
  20838. min->start();
  20839. }
  20840. }
  20841. }
  20842. else
  20843. {
  20844. for (int i = enabledMidiInputs.size(); --i >= 0;)
  20845. if (enabledMidiInputs[i]->getName() == name)
  20846. enabledMidiInputs.remove (i);
  20847. }
  20848. updateXml();
  20849. sendChangeMessage (this);
  20850. }
  20851. }
  20852. bool AudioDeviceManager::isMidiInputEnabled (const String& name) const
  20853. {
  20854. for (int i = enabledMidiInputs.size(); --i >= 0;)
  20855. if (enabledMidiInputs[i]->getName() == name)
  20856. return true;
  20857. return false;
  20858. }
  20859. void AudioDeviceManager::addMidiInputCallback (const String& name,
  20860. MidiInputCallback* callback)
  20861. {
  20862. removeMidiInputCallback (name, callback);
  20863. if (name.isEmpty())
  20864. {
  20865. midiCallbacks.add (callback);
  20866. midiCallbackDevices.add (0);
  20867. }
  20868. else
  20869. {
  20870. for (int i = enabledMidiInputs.size(); --i >= 0;)
  20871. {
  20872. if (enabledMidiInputs[i]->getName() == name)
  20873. {
  20874. const ScopedLock sl (midiCallbackLock);
  20875. midiCallbacks.add (callback);
  20876. midiCallbackDevices.add (enabledMidiInputs[i]);
  20877. break;
  20878. }
  20879. }
  20880. }
  20881. }
  20882. void AudioDeviceManager::removeMidiInputCallback (const String& name,
  20883. MidiInputCallback* /*callback*/)
  20884. {
  20885. const ScopedLock sl (midiCallbackLock);
  20886. for (int i = midiCallbacks.size(); --i >= 0;)
  20887. {
  20888. String devName;
  20889. if (midiCallbackDevices.getUnchecked(i) != 0)
  20890. devName = midiCallbackDevices.getUnchecked(i)->getName();
  20891. if (devName == name)
  20892. {
  20893. midiCallbacks.remove (i);
  20894. midiCallbackDevices.remove (i);
  20895. }
  20896. }
  20897. }
  20898. void AudioDeviceManager::handleIncomingMidiMessageInt (MidiInput* source,
  20899. const MidiMessage& message)
  20900. {
  20901. if (! message.isActiveSense())
  20902. {
  20903. const bool isDefaultSource = (source == 0 || source == enabledMidiInputs.getFirst());
  20904. const ScopedLock sl (midiCallbackLock);
  20905. for (int i = midiCallbackDevices.size(); --i >= 0;)
  20906. {
  20907. MidiInput* const md = midiCallbackDevices.getUnchecked(i);
  20908. if (md == source || (md == 0 && isDefaultSource))
  20909. midiCallbacks.getUnchecked(i)->handleIncomingMidiMessage (source, message);
  20910. }
  20911. }
  20912. }
  20913. void AudioDeviceManager::setDefaultMidiOutput (const String& deviceName)
  20914. {
  20915. if (defaultMidiOutputName != deviceName)
  20916. {
  20917. SortedSet <AudioIODeviceCallback*> oldCallbacks;
  20918. {
  20919. const ScopedLock sl (audioCallbackLock);
  20920. oldCallbacks = callbacks;
  20921. callbacks.clear();
  20922. }
  20923. if (currentAudioDevice != 0)
  20924. for (int i = oldCallbacks.size(); --i >= 0;)
  20925. oldCallbacks.getUnchecked(i)->audioDeviceStopped();
  20926. defaultMidiOutput = 0;
  20927. defaultMidiOutputName = deviceName;
  20928. if (deviceName.isNotEmpty())
  20929. defaultMidiOutput = MidiOutput::openDevice (MidiOutput::getDevices().indexOf (deviceName));
  20930. if (currentAudioDevice != 0)
  20931. for (int i = oldCallbacks.size(); --i >= 0;)
  20932. oldCallbacks.getUnchecked(i)->audioDeviceAboutToStart (currentAudioDevice);
  20933. {
  20934. const ScopedLock sl (audioCallbackLock);
  20935. callbacks = oldCallbacks;
  20936. }
  20937. updateXml();
  20938. sendChangeMessage (this);
  20939. }
  20940. }
  20941. void AudioDeviceManager::CallbackHandler::audioDeviceIOCallback (const float** inputChannelData,
  20942. int numInputChannels,
  20943. float** outputChannelData,
  20944. int numOutputChannels,
  20945. int numSamples)
  20946. {
  20947. owner->audioDeviceIOCallbackInt (inputChannelData, numInputChannels, outputChannelData, numOutputChannels, numSamples);
  20948. }
  20949. void AudioDeviceManager::CallbackHandler::audioDeviceAboutToStart (AudioIODevice* device)
  20950. {
  20951. owner->audioDeviceAboutToStartInt (device);
  20952. }
  20953. void AudioDeviceManager::CallbackHandler::audioDeviceStopped()
  20954. {
  20955. owner->audioDeviceStoppedInt();
  20956. }
  20957. void AudioDeviceManager::CallbackHandler::handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message)
  20958. {
  20959. owner->handleIncomingMidiMessageInt (source, message);
  20960. }
  20961. void AudioDeviceManager::playTestSound()
  20962. {
  20963. { // cunningly nested to swap, unlock and delete in that order.
  20964. ScopedPointer <AudioSampleBuffer> oldSound;
  20965. {
  20966. const ScopedLock sl (audioCallbackLock);
  20967. oldSound = testSound;
  20968. }
  20969. }
  20970. testSoundPosition = 0;
  20971. if (currentAudioDevice != 0)
  20972. {
  20973. const double sampleRate = currentAudioDevice->getCurrentSampleRate();
  20974. const int soundLength = (int) sampleRate;
  20975. AudioSampleBuffer* const newSound = new AudioSampleBuffer (1, soundLength);
  20976. float* samples = newSound->getSampleData (0);
  20977. const double frequency = MidiMessage::getMidiNoteInHertz (80);
  20978. const float amplitude = 0.5f;
  20979. const double phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  20980. for (int i = 0; i < soundLength; ++i)
  20981. samples[i] = amplitude * (float) std::sin (i * phasePerSample);
  20982. newSound->applyGainRamp (0, 0, soundLength / 10, 0.0f, 1.0f);
  20983. newSound->applyGainRamp (0, soundLength - soundLength / 4, soundLength / 4, 1.0f, 0.0f);
  20984. const ScopedLock sl (audioCallbackLock);
  20985. testSound = newSound;
  20986. }
  20987. }
  20988. void AudioDeviceManager::enableInputLevelMeasurement (const bool enableMeasurement)
  20989. {
  20990. const ScopedLock sl (audioCallbackLock);
  20991. if (enableMeasurement)
  20992. ++inputLevelMeasurementEnabledCount;
  20993. else
  20994. --inputLevelMeasurementEnabledCount;
  20995. inputLevel = 0;
  20996. }
  20997. double AudioDeviceManager::getCurrentInputLevel() const
  20998. {
  20999. jassert (inputLevelMeasurementEnabledCount > 0); // you need to call enableInputLevelMeasurement() before using this!
  21000. return inputLevel;
  21001. }
  21002. END_JUCE_NAMESPACE
  21003. /*** End of inlined file: juce_AudioDeviceManager.cpp ***/
  21004. /*** Start of inlined file: juce_AudioIODevice.cpp ***/
  21005. BEGIN_JUCE_NAMESPACE
  21006. AudioIODevice::AudioIODevice (const String& deviceName, const String& typeName_)
  21007. : name (deviceName),
  21008. typeName (typeName_)
  21009. {
  21010. }
  21011. AudioIODevice::~AudioIODevice()
  21012. {
  21013. }
  21014. bool AudioIODevice::hasControlPanel() const
  21015. {
  21016. return false;
  21017. }
  21018. bool AudioIODevice::showControlPanel()
  21019. {
  21020. jassertfalse; // this should only be called for devices which return true from
  21021. // their hasControlPanel() method.
  21022. return false;
  21023. }
  21024. END_JUCE_NAMESPACE
  21025. /*** End of inlined file: juce_AudioIODevice.cpp ***/
  21026. /*** Start of inlined file: juce_AudioIODeviceType.cpp ***/
  21027. BEGIN_JUCE_NAMESPACE
  21028. AudioIODeviceType::AudioIODeviceType (const String& name)
  21029. : typeName (name)
  21030. {
  21031. }
  21032. AudioIODeviceType::~AudioIODeviceType()
  21033. {
  21034. }
  21035. END_JUCE_NAMESPACE
  21036. /*** End of inlined file: juce_AudioIODeviceType.cpp ***/
  21037. /*** Start of inlined file: juce_MidiOutput.cpp ***/
  21038. BEGIN_JUCE_NAMESPACE
  21039. MidiOutput::MidiOutput()
  21040. : Thread ("midi out"),
  21041. internal (0),
  21042. firstMessage (0)
  21043. {
  21044. }
  21045. MidiOutput::PendingMessage::PendingMessage (const uint8* const data, const int len,
  21046. const double sampleNumber)
  21047. : message (data, len, sampleNumber)
  21048. {
  21049. }
  21050. void MidiOutput::sendBlockOfMessages (const MidiBuffer& buffer,
  21051. const double millisecondCounterToStartAt,
  21052. double samplesPerSecondForBuffer)
  21053. {
  21054. // You've got to call startBackgroundThread() for this to actually work..
  21055. jassert (isThreadRunning());
  21056. // this needs to be a value in the future - RTFM for this method!
  21057. jassert (millisecondCounterToStartAt > 0);
  21058. const double timeScaleFactor = 1000.0 / samplesPerSecondForBuffer;
  21059. MidiBuffer::Iterator i (buffer);
  21060. const uint8* data;
  21061. int len, time;
  21062. while (i.getNextEvent (data, len, time))
  21063. {
  21064. const double eventTime = millisecondCounterToStartAt + timeScaleFactor * time;
  21065. PendingMessage* const m
  21066. = new PendingMessage (data, len, eventTime);
  21067. const ScopedLock sl (lock);
  21068. if (firstMessage == 0 || firstMessage->message.getTimeStamp() > eventTime)
  21069. {
  21070. m->next = firstMessage;
  21071. firstMessage = m;
  21072. }
  21073. else
  21074. {
  21075. PendingMessage* mm = firstMessage;
  21076. while (mm->next != 0 && mm->next->message.getTimeStamp() <= eventTime)
  21077. mm = mm->next;
  21078. m->next = mm->next;
  21079. mm->next = m;
  21080. }
  21081. }
  21082. notify();
  21083. }
  21084. void MidiOutput::clearAllPendingMessages()
  21085. {
  21086. const ScopedLock sl (lock);
  21087. while (firstMessage != 0)
  21088. {
  21089. PendingMessage* const m = firstMessage;
  21090. firstMessage = firstMessage->next;
  21091. delete m;
  21092. }
  21093. }
  21094. void MidiOutput::startBackgroundThread()
  21095. {
  21096. startThread (9);
  21097. }
  21098. void MidiOutput::stopBackgroundThread()
  21099. {
  21100. stopThread (5000);
  21101. }
  21102. void MidiOutput::run()
  21103. {
  21104. while (! threadShouldExit())
  21105. {
  21106. uint32 now = Time::getMillisecondCounter();
  21107. uint32 eventTime = 0;
  21108. uint32 timeToWait = 500;
  21109. PendingMessage* message;
  21110. {
  21111. const ScopedLock sl (lock);
  21112. message = firstMessage;
  21113. if (message != 0)
  21114. {
  21115. eventTime = roundToInt (message->message.getTimeStamp());
  21116. if (eventTime > now + 20)
  21117. {
  21118. timeToWait = eventTime - (now + 20);
  21119. message = 0;
  21120. }
  21121. else
  21122. {
  21123. firstMessage = message->next;
  21124. }
  21125. }
  21126. }
  21127. if (message != 0)
  21128. {
  21129. if (eventTime > now)
  21130. {
  21131. Time::waitForMillisecondCounter (eventTime);
  21132. if (threadShouldExit())
  21133. break;
  21134. }
  21135. if (eventTime > now - 200)
  21136. sendMessageNow (message->message);
  21137. delete message;
  21138. }
  21139. else
  21140. {
  21141. jassert (timeToWait < 1000 * 30);
  21142. wait (timeToWait);
  21143. }
  21144. }
  21145. clearAllPendingMessages();
  21146. }
  21147. END_JUCE_NAMESPACE
  21148. /*** End of inlined file: juce_MidiOutput.cpp ***/
  21149. /*** Start of inlined file: juce_AudioDataConverters.cpp ***/
  21150. BEGIN_JUCE_NAMESPACE
  21151. void AudioDataConverters::convertFloatToInt16LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21152. {
  21153. const double maxVal = (double) 0x7fff;
  21154. char* intData = static_cast <char*> (dest);
  21155. if (dest != (void*) source || destBytesPerSample <= 4)
  21156. {
  21157. for (int i = 0; i < numSamples; ++i)
  21158. {
  21159. *(uint16*) intData = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21160. intData += destBytesPerSample;
  21161. }
  21162. }
  21163. else
  21164. {
  21165. intData += destBytesPerSample * numSamples;
  21166. for (int i = numSamples; --i >= 0;)
  21167. {
  21168. intData -= destBytesPerSample;
  21169. *(uint16*) intData = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21170. }
  21171. }
  21172. }
  21173. void AudioDataConverters::convertFloatToInt16BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21174. {
  21175. const double maxVal = (double) 0x7fff;
  21176. char* intData = static_cast <char*> (dest);
  21177. if (dest != (void*) source || destBytesPerSample <= 4)
  21178. {
  21179. for (int i = 0; i < numSamples; ++i)
  21180. {
  21181. *(uint16*) intData = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21182. intData += destBytesPerSample;
  21183. }
  21184. }
  21185. else
  21186. {
  21187. intData += destBytesPerSample * numSamples;
  21188. for (int i = numSamples; --i >= 0;)
  21189. {
  21190. intData -= destBytesPerSample;
  21191. *(uint16*) intData = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21192. }
  21193. }
  21194. }
  21195. void AudioDataConverters::convertFloatToInt24LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21196. {
  21197. const double maxVal = (double) 0x7fffff;
  21198. char* intData = static_cast <char*> (dest);
  21199. if (dest != (void*) source || destBytesPerSample <= 4)
  21200. {
  21201. for (int i = 0; i < numSamples; ++i)
  21202. {
  21203. ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21204. intData += destBytesPerSample;
  21205. }
  21206. }
  21207. else
  21208. {
  21209. intData += destBytesPerSample * numSamples;
  21210. for (int i = numSamples; --i >= 0;)
  21211. {
  21212. intData -= destBytesPerSample;
  21213. ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21214. }
  21215. }
  21216. }
  21217. void AudioDataConverters::convertFloatToInt24BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21218. {
  21219. const double maxVal = (double) 0x7fffff;
  21220. char* intData = static_cast <char*> (dest);
  21221. if (dest != (void*) source || destBytesPerSample <= 4)
  21222. {
  21223. for (int i = 0; i < numSamples; ++i)
  21224. {
  21225. ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21226. intData += destBytesPerSample;
  21227. }
  21228. }
  21229. else
  21230. {
  21231. intData += destBytesPerSample * numSamples;
  21232. for (int i = numSamples; --i >= 0;)
  21233. {
  21234. intData -= destBytesPerSample;
  21235. ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21236. }
  21237. }
  21238. }
  21239. void AudioDataConverters::convertFloatToInt32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21240. {
  21241. const double maxVal = (double) 0x7fffffff;
  21242. char* intData = static_cast <char*> (dest);
  21243. if (dest != (void*) source || destBytesPerSample <= 4)
  21244. {
  21245. for (int i = 0; i < numSamples; ++i)
  21246. {
  21247. *(uint32*)intData = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21248. intData += destBytesPerSample;
  21249. }
  21250. }
  21251. else
  21252. {
  21253. intData += destBytesPerSample * numSamples;
  21254. for (int i = numSamples; --i >= 0;)
  21255. {
  21256. intData -= destBytesPerSample;
  21257. *(uint32*)intData = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21258. }
  21259. }
  21260. }
  21261. void AudioDataConverters::convertFloatToInt32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21262. {
  21263. const double maxVal = (double) 0x7fffffff;
  21264. char* intData = static_cast <char*> (dest);
  21265. if (dest != (void*) source || destBytesPerSample <= 4)
  21266. {
  21267. for (int i = 0; i < numSamples; ++i)
  21268. {
  21269. *(uint32*)intData = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21270. intData += destBytesPerSample;
  21271. }
  21272. }
  21273. else
  21274. {
  21275. intData += destBytesPerSample * numSamples;
  21276. for (int i = numSamples; --i >= 0;)
  21277. {
  21278. intData -= destBytesPerSample;
  21279. *(uint32*)intData = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21280. }
  21281. }
  21282. }
  21283. void AudioDataConverters::convertFloatToFloat32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21284. {
  21285. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  21286. char* d = static_cast <char*> (dest);
  21287. for (int i = 0; i < numSamples; ++i)
  21288. {
  21289. *(float*) d = source[i];
  21290. #if JUCE_BIG_ENDIAN
  21291. *(uint32*) d = ByteOrder::swap (*(uint32*) d);
  21292. #endif
  21293. d += destBytesPerSample;
  21294. }
  21295. }
  21296. void AudioDataConverters::convertFloatToFloat32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21297. {
  21298. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  21299. char* d = static_cast <char*> (dest);
  21300. for (int i = 0; i < numSamples; ++i)
  21301. {
  21302. *(float*) d = source[i];
  21303. #if JUCE_LITTLE_ENDIAN
  21304. *(uint32*) d = ByteOrder::swap (*(uint32*) d);
  21305. #endif
  21306. d += destBytesPerSample;
  21307. }
  21308. }
  21309. void AudioDataConverters::convertInt16LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21310. {
  21311. const float scale = 1.0f / 0x7fff;
  21312. const char* intData = static_cast <const char*> (source);
  21313. if (source != (void*) dest || srcBytesPerSample >= 4)
  21314. {
  21315. for (int i = 0; i < numSamples; ++i)
  21316. {
  21317. dest[i] = scale * (short) ByteOrder::swapIfBigEndian (*(uint16*)intData);
  21318. intData += srcBytesPerSample;
  21319. }
  21320. }
  21321. else
  21322. {
  21323. intData += srcBytesPerSample * numSamples;
  21324. for (int i = numSamples; --i >= 0;)
  21325. {
  21326. intData -= srcBytesPerSample;
  21327. dest[i] = scale * (short) ByteOrder::swapIfBigEndian (*(uint16*)intData);
  21328. }
  21329. }
  21330. }
  21331. void AudioDataConverters::convertInt16BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21332. {
  21333. const float scale = 1.0f / 0x7fff;
  21334. const char* intData = static_cast <const char*> (source);
  21335. if (source != (void*) dest || srcBytesPerSample >= 4)
  21336. {
  21337. for (int i = 0; i < numSamples; ++i)
  21338. {
  21339. dest[i] = scale * (short) ByteOrder::swapIfLittleEndian (*(uint16*)intData);
  21340. intData += srcBytesPerSample;
  21341. }
  21342. }
  21343. else
  21344. {
  21345. intData += srcBytesPerSample * numSamples;
  21346. for (int i = numSamples; --i >= 0;)
  21347. {
  21348. intData -= srcBytesPerSample;
  21349. dest[i] = scale * (short) ByteOrder::swapIfLittleEndian (*(uint16*)intData);
  21350. }
  21351. }
  21352. }
  21353. void AudioDataConverters::convertInt24LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21354. {
  21355. const float scale = 1.0f / 0x7fffff;
  21356. const char* intData = static_cast <const char*> (source);
  21357. if (source != (void*) dest || srcBytesPerSample >= 4)
  21358. {
  21359. for (int i = 0; i < numSamples; ++i)
  21360. {
  21361. dest[i] = scale * (short) ByteOrder::littleEndian24Bit (intData);
  21362. intData += srcBytesPerSample;
  21363. }
  21364. }
  21365. else
  21366. {
  21367. intData += srcBytesPerSample * numSamples;
  21368. for (int i = numSamples; --i >= 0;)
  21369. {
  21370. intData -= srcBytesPerSample;
  21371. dest[i] = scale * (short) ByteOrder::littleEndian24Bit (intData);
  21372. }
  21373. }
  21374. }
  21375. void AudioDataConverters::convertInt24BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21376. {
  21377. const float scale = 1.0f / 0x7fffff;
  21378. const char* intData = static_cast <const char*> (source);
  21379. if (source != (void*) dest || srcBytesPerSample >= 4)
  21380. {
  21381. for (int i = 0; i < numSamples; ++i)
  21382. {
  21383. dest[i] = scale * (short) ByteOrder::bigEndian24Bit (intData);
  21384. intData += srcBytesPerSample;
  21385. }
  21386. }
  21387. else
  21388. {
  21389. intData += srcBytesPerSample * numSamples;
  21390. for (int i = numSamples; --i >= 0;)
  21391. {
  21392. intData -= srcBytesPerSample;
  21393. dest[i] = scale * (short) ByteOrder::bigEndian24Bit (intData);
  21394. }
  21395. }
  21396. }
  21397. void AudioDataConverters::convertInt32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21398. {
  21399. const float scale = 1.0f / 0x7fffffff;
  21400. const char* intData = static_cast <const char*> (source);
  21401. if (source != (void*) dest || srcBytesPerSample >= 4)
  21402. {
  21403. for (int i = 0; i < numSamples; ++i)
  21404. {
  21405. dest[i] = scale * (int) ByteOrder::swapIfBigEndian (*(uint32*) intData);
  21406. intData += srcBytesPerSample;
  21407. }
  21408. }
  21409. else
  21410. {
  21411. intData += srcBytesPerSample * numSamples;
  21412. for (int i = numSamples; --i >= 0;)
  21413. {
  21414. intData -= srcBytesPerSample;
  21415. dest[i] = scale * (int) ByteOrder::swapIfBigEndian (*(uint32*) intData);
  21416. }
  21417. }
  21418. }
  21419. void AudioDataConverters::convertInt32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21420. {
  21421. const float scale = 1.0f / 0x7fffffff;
  21422. const char* intData = static_cast <const char*> (source);
  21423. if (source != (void*) dest || srcBytesPerSample >= 4)
  21424. {
  21425. for (int i = 0; i < numSamples; ++i)
  21426. {
  21427. dest[i] = scale * (int) ByteOrder::swapIfLittleEndian (*(uint32*) intData);
  21428. intData += srcBytesPerSample;
  21429. }
  21430. }
  21431. else
  21432. {
  21433. intData += srcBytesPerSample * numSamples;
  21434. for (int i = numSamples; --i >= 0;)
  21435. {
  21436. intData -= srcBytesPerSample;
  21437. dest[i] = scale * (int) ByteOrder::swapIfLittleEndian (*(uint32*) intData);
  21438. }
  21439. }
  21440. }
  21441. void AudioDataConverters::convertFloat32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21442. {
  21443. const char* s = static_cast <const char*> (source);
  21444. for (int i = 0; i < numSamples; ++i)
  21445. {
  21446. dest[i] = *(float*)s;
  21447. #if JUCE_BIG_ENDIAN
  21448. uint32* const d = (uint32*) (dest + i);
  21449. *d = ByteOrder::swap (*d);
  21450. #endif
  21451. s += srcBytesPerSample;
  21452. }
  21453. }
  21454. void AudioDataConverters::convertFloat32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21455. {
  21456. const char* s = static_cast <const char*> (source);
  21457. for (int i = 0; i < numSamples; ++i)
  21458. {
  21459. dest[i] = *(float*)s;
  21460. #if JUCE_LITTLE_ENDIAN
  21461. uint32* const d = (uint32*) (dest + i);
  21462. *d = ByteOrder::swap (*d);
  21463. #endif
  21464. s += srcBytesPerSample;
  21465. }
  21466. }
  21467. void AudioDataConverters::convertFloatToFormat (const DataFormat destFormat,
  21468. const float* const source,
  21469. void* const dest,
  21470. const int numSamples)
  21471. {
  21472. switch (destFormat)
  21473. {
  21474. case int16LE:
  21475. convertFloatToInt16LE (source, dest, numSamples);
  21476. break;
  21477. case int16BE:
  21478. convertFloatToInt16BE (source, dest, numSamples);
  21479. break;
  21480. case int24LE:
  21481. convertFloatToInt24LE (source, dest, numSamples);
  21482. break;
  21483. case int24BE:
  21484. convertFloatToInt24BE (source, dest, numSamples);
  21485. break;
  21486. case int32LE:
  21487. convertFloatToInt32LE (source, dest, numSamples);
  21488. break;
  21489. case int32BE:
  21490. convertFloatToInt32BE (source, dest, numSamples);
  21491. break;
  21492. case float32LE:
  21493. convertFloatToFloat32LE (source, dest, numSamples);
  21494. break;
  21495. case float32BE:
  21496. convertFloatToFloat32BE (source, dest, numSamples);
  21497. break;
  21498. default:
  21499. jassertfalse;
  21500. break;
  21501. }
  21502. }
  21503. void AudioDataConverters::convertFormatToFloat (const DataFormat sourceFormat,
  21504. const void* const source,
  21505. float* const dest,
  21506. const int numSamples)
  21507. {
  21508. switch (sourceFormat)
  21509. {
  21510. case int16LE:
  21511. convertInt16LEToFloat (source, dest, numSamples);
  21512. break;
  21513. case int16BE:
  21514. convertInt16BEToFloat (source, dest, numSamples);
  21515. break;
  21516. case int24LE:
  21517. convertInt24LEToFloat (source, dest, numSamples);
  21518. break;
  21519. case int24BE:
  21520. convertInt24BEToFloat (source, dest, numSamples);
  21521. break;
  21522. case int32LE:
  21523. convertInt32LEToFloat (source, dest, numSamples);
  21524. break;
  21525. case int32BE:
  21526. convertInt32BEToFloat (source, dest, numSamples);
  21527. break;
  21528. case float32LE:
  21529. convertFloat32LEToFloat (source, dest, numSamples);
  21530. break;
  21531. case float32BE:
  21532. convertFloat32BEToFloat (source, dest, numSamples);
  21533. break;
  21534. default:
  21535. jassertfalse;
  21536. break;
  21537. }
  21538. }
  21539. void AudioDataConverters::interleaveSamples (const float** const source,
  21540. float* const dest,
  21541. const int numSamples,
  21542. const int numChannels)
  21543. {
  21544. for (int chan = 0; chan < numChannels; ++chan)
  21545. {
  21546. int i = chan;
  21547. const float* src = source [chan];
  21548. for (int j = 0; j < numSamples; ++j)
  21549. {
  21550. dest [i] = src [j];
  21551. i += numChannels;
  21552. }
  21553. }
  21554. }
  21555. void AudioDataConverters::deinterleaveSamples (const float* const source,
  21556. float** const dest,
  21557. const int numSamples,
  21558. const int numChannels)
  21559. {
  21560. for (int chan = 0; chan < numChannels; ++chan)
  21561. {
  21562. int i = chan;
  21563. float* dst = dest [chan];
  21564. for (int j = 0; j < numSamples; ++j)
  21565. {
  21566. dst [j] = source [i];
  21567. i += numChannels;
  21568. }
  21569. }
  21570. }
  21571. #if JUCE_UNIT_TESTS
  21572. class AudioConversionTests : public UnitTest
  21573. {
  21574. public:
  21575. AudioConversionTests() : UnitTest ("Audio data conversion") {}
  21576. template <class F1, class E1, class F2, class E2>
  21577. struct Test5
  21578. {
  21579. static void test (UnitTest& unitTest)
  21580. {
  21581. test (unitTest, false);
  21582. test (unitTest, true);
  21583. }
  21584. static void test (UnitTest& unitTest, bool inPlace)
  21585. {
  21586. const int numSamples = 2048;
  21587. int32 original [numSamples], converted [numSamples], reversed [numSamples];
  21588. {
  21589. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::NonConst> d (original);
  21590. bool clippingFailed = false;
  21591. for (int i = 0; i < numSamples / 2; ++i)
  21592. {
  21593. d.setAsFloat (Random::getSystemRandom().nextFloat() * 2.2f - 1.1f);
  21594. if (! d.isFloatingPoint())
  21595. clippingFailed = d.getAsFloat() > 1.0f || d.getAsFloat() < -1.0f || clippingFailed;
  21596. ++d;
  21597. d.setAsInt32 (Random::getSystemRandom().nextInt());
  21598. ++d;
  21599. }
  21600. unitTest.expect (! clippingFailed);
  21601. }
  21602. // convert data from the source to dest format..
  21603. ScopedPointer<AudioData::Converter> conv (new AudioData::ConverterInstance <AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const>,
  21604. AudioData::Pointer<F2, E2, AudioData::NonInterleaved, AudioData::NonConst> >());
  21605. conv->convertSamples (inPlace ? reversed : converted, original, numSamples);
  21606. // ..and back again..
  21607. conv = new AudioData::ConverterInstance <AudioData::Pointer<F2, E2, AudioData::NonInterleaved, AudioData::Const>,
  21608. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::NonConst> >();
  21609. if (! inPlace)
  21610. zerostruct (reversed);
  21611. conv->convertSamples (reversed, inPlace ? reversed : converted, numSamples);
  21612. {
  21613. int biggestDiff = 0;
  21614. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const> d1 (original);
  21615. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const> d2 (reversed);
  21616. const int errorMargin = 2 * AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const>::get32BitResolution()
  21617. + AudioData::Pointer<F2, E2, AudioData::NonInterleaved, AudioData::Const>::get32BitResolution();
  21618. for (int i = 0; i < numSamples; ++i)
  21619. {
  21620. biggestDiff = jmax (biggestDiff, std::abs (d1.getAsInt32() - d2.getAsInt32()));
  21621. ++d1;
  21622. ++d2;
  21623. }
  21624. unitTest.expect (biggestDiff <= errorMargin);
  21625. }
  21626. }
  21627. };
  21628. template <class F1, class E1, class FormatType>
  21629. struct Test3
  21630. {
  21631. static void test (UnitTest& unitTest)
  21632. {
  21633. Test5 <F1, E1, FormatType, AudioData::BigEndian>::test (unitTest);
  21634. Test5 <F1, E1, FormatType, AudioData::LittleEndian>::test (unitTest);
  21635. }
  21636. };
  21637. template <class FormatType, class Endianness>
  21638. struct Test2
  21639. {
  21640. static void test (UnitTest& unitTest)
  21641. {
  21642. Test3 <FormatType, Endianness, AudioData::Int8>::test (unitTest);
  21643. Test3 <FormatType, Endianness, AudioData::UInt8>::test (unitTest);
  21644. Test3 <FormatType, Endianness, AudioData::Int16>::test (unitTest);
  21645. Test3 <FormatType, Endianness, AudioData::Int24>::test (unitTest);
  21646. Test3 <FormatType, Endianness, AudioData::Int32>::test (unitTest);
  21647. Test3 <FormatType, Endianness, AudioData::Float32>::test (unitTest);
  21648. }
  21649. };
  21650. template <class FormatType>
  21651. struct Test1
  21652. {
  21653. static void test (UnitTest& unitTest)
  21654. {
  21655. Test2 <FormatType, AudioData::BigEndian>::test (unitTest);
  21656. Test2 <FormatType, AudioData::LittleEndian>::test (unitTest);
  21657. }
  21658. };
  21659. void runTest()
  21660. {
  21661. beginTest ("Round-trip conversion");
  21662. Test1 <AudioData::Int8>::test (*this);
  21663. Test1 <AudioData::Int16>::test (*this);
  21664. Test1 <AudioData::Int24>::test (*this);
  21665. Test1 <AudioData::Int32>::test (*this);
  21666. Test1 <AudioData::Float32>::test (*this);
  21667. }
  21668. };
  21669. static AudioConversionTests audioConversionUnitTests;
  21670. #endif
  21671. END_JUCE_NAMESPACE
  21672. /*** End of inlined file: juce_AudioDataConverters.cpp ***/
  21673. /*** Start of inlined file: juce_AudioSampleBuffer.cpp ***/
  21674. BEGIN_JUCE_NAMESPACE
  21675. AudioSampleBuffer::AudioSampleBuffer (const int numChannels_,
  21676. const int numSamples) throw()
  21677. : numChannels (numChannels_),
  21678. size (numSamples)
  21679. {
  21680. jassert (numSamples >= 0);
  21681. jassert (numChannels_ > 0);
  21682. allocateData();
  21683. }
  21684. AudioSampleBuffer::AudioSampleBuffer (const AudioSampleBuffer& other) throw()
  21685. : numChannels (other.numChannels),
  21686. size (other.size)
  21687. {
  21688. allocateData();
  21689. const size_t numBytes = size * sizeof (float);
  21690. for (int i = 0; i < numChannels; ++i)
  21691. memcpy (channels[i], other.channels[i], numBytes);
  21692. }
  21693. void AudioSampleBuffer::allocateData()
  21694. {
  21695. const size_t channelListSize = (numChannels + 1) * sizeof (float*);
  21696. allocatedBytes = (int) (numChannels * size * sizeof (float) + channelListSize + 32);
  21697. allocatedData.malloc (allocatedBytes);
  21698. channels = reinterpret_cast <float**> (allocatedData.getData());
  21699. float* chan = (float*) (allocatedData + channelListSize);
  21700. for (int i = 0; i < numChannels; ++i)
  21701. {
  21702. channels[i] = chan;
  21703. chan += size;
  21704. }
  21705. channels [numChannels] = 0;
  21706. }
  21707. AudioSampleBuffer::AudioSampleBuffer (float** dataToReferTo,
  21708. const int numChannels_,
  21709. const int numSamples) throw()
  21710. : numChannels (numChannels_),
  21711. size (numSamples),
  21712. allocatedBytes (0)
  21713. {
  21714. jassert (numChannels_ > 0);
  21715. allocateChannels (dataToReferTo);
  21716. }
  21717. void AudioSampleBuffer::setDataToReferTo (float** dataToReferTo,
  21718. const int newNumChannels,
  21719. const int newNumSamples) throw()
  21720. {
  21721. jassert (newNumChannels > 0);
  21722. allocatedBytes = 0;
  21723. allocatedData.free();
  21724. numChannels = newNumChannels;
  21725. size = newNumSamples;
  21726. allocateChannels (dataToReferTo);
  21727. }
  21728. void AudioSampleBuffer::allocateChannels (float** const dataToReferTo)
  21729. {
  21730. // (try to avoid doing a malloc here, as that'll blow up things like Pro-Tools)
  21731. if (numChannels < numElementsInArray (preallocatedChannelSpace))
  21732. {
  21733. channels = static_cast <float**> (preallocatedChannelSpace);
  21734. }
  21735. else
  21736. {
  21737. allocatedData.malloc (numChannels + 1, sizeof (float*));
  21738. channels = reinterpret_cast <float**> (allocatedData.getData());
  21739. }
  21740. for (int i = 0; i < numChannels; ++i)
  21741. {
  21742. // you have to pass in the same number of valid pointers as numChannels
  21743. jassert (dataToReferTo[i] != 0);
  21744. channels[i] = dataToReferTo[i];
  21745. }
  21746. channels [numChannels] = 0;
  21747. }
  21748. AudioSampleBuffer& AudioSampleBuffer::operator= (const AudioSampleBuffer& other) throw()
  21749. {
  21750. if (this != &other)
  21751. {
  21752. setSize (other.getNumChannels(), other.getNumSamples(), false, false, false);
  21753. const size_t numBytes = size * sizeof (float);
  21754. for (int i = 0; i < numChannels; ++i)
  21755. memcpy (channels[i], other.channels[i], numBytes);
  21756. }
  21757. return *this;
  21758. }
  21759. AudioSampleBuffer::~AudioSampleBuffer() throw()
  21760. {
  21761. }
  21762. void AudioSampleBuffer::setSize (const int newNumChannels,
  21763. const int newNumSamples,
  21764. const bool keepExistingContent,
  21765. const bool clearExtraSpace,
  21766. const bool avoidReallocating) throw()
  21767. {
  21768. jassert (newNumChannels > 0);
  21769. if (newNumSamples != size || newNumChannels != numChannels)
  21770. {
  21771. const size_t channelListSize = (newNumChannels + 1) * sizeof (float*);
  21772. const size_t newTotalBytes = (newNumChannels * newNumSamples * sizeof (float)) + channelListSize + 32;
  21773. if (keepExistingContent)
  21774. {
  21775. HeapBlock <char> newData;
  21776. newData.allocate (newTotalBytes, clearExtraSpace);
  21777. const int numChansToCopy = jmin (numChannels, newNumChannels);
  21778. const size_t numBytesToCopy = sizeof (float) * jmin (newNumSamples, size);
  21779. float** const newChannels = reinterpret_cast <float**> (newData.getData());
  21780. float* newChan = reinterpret_cast <float*> (newData + channelListSize);
  21781. for (int i = 0; i < numChansToCopy; ++i)
  21782. {
  21783. memcpy (newChan, channels[i], numBytesToCopy);
  21784. newChannels[i] = newChan;
  21785. newChan += newNumSamples;
  21786. }
  21787. allocatedData.swapWith (newData);
  21788. allocatedBytes = (int) newTotalBytes;
  21789. channels = newChannels;
  21790. }
  21791. else
  21792. {
  21793. if (avoidReallocating && allocatedBytes >= newTotalBytes)
  21794. {
  21795. if (clearExtraSpace)
  21796. zeromem (allocatedData, newTotalBytes);
  21797. }
  21798. else
  21799. {
  21800. allocatedBytes = newTotalBytes;
  21801. allocatedData.allocate (newTotalBytes, clearExtraSpace);
  21802. channels = reinterpret_cast <float**> (allocatedData.getData());
  21803. }
  21804. float* chan = reinterpret_cast <float*> (allocatedData + channelListSize);
  21805. for (int i = 0; i < newNumChannels; ++i)
  21806. {
  21807. channels[i] = chan;
  21808. chan += newNumSamples;
  21809. }
  21810. }
  21811. channels [newNumChannels] = 0;
  21812. size = newNumSamples;
  21813. numChannels = newNumChannels;
  21814. }
  21815. }
  21816. void AudioSampleBuffer::clear() throw()
  21817. {
  21818. for (int i = 0; i < numChannels; ++i)
  21819. zeromem (channels[i], size * sizeof (float));
  21820. }
  21821. void AudioSampleBuffer::clear (const int startSample,
  21822. const int numSamples) throw()
  21823. {
  21824. jassert (startSample >= 0 && startSample + numSamples <= size);
  21825. for (int i = 0; i < numChannels; ++i)
  21826. zeromem (channels [i] + startSample, numSamples * sizeof (float));
  21827. }
  21828. void AudioSampleBuffer::clear (const int channel,
  21829. const int startSample,
  21830. const int numSamples) throw()
  21831. {
  21832. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21833. jassert (startSample >= 0 && startSample + numSamples <= size);
  21834. zeromem (channels [channel] + startSample, numSamples * sizeof (float));
  21835. }
  21836. void AudioSampleBuffer::applyGain (const int channel,
  21837. const int startSample,
  21838. int numSamples,
  21839. const float gain) throw()
  21840. {
  21841. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21842. jassert (startSample >= 0 && startSample + numSamples <= size);
  21843. if (gain != 1.0f)
  21844. {
  21845. float* d = channels [channel] + startSample;
  21846. if (gain == 0.0f)
  21847. {
  21848. zeromem (d, sizeof (float) * numSamples);
  21849. }
  21850. else
  21851. {
  21852. while (--numSamples >= 0)
  21853. *d++ *= gain;
  21854. }
  21855. }
  21856. }
  21857. void AudioSampleBuffer::applyGainRamp (const int channel,
  21858. const int startSample,
  21859. int numSamples,
  21860. float startGain,
  21861. float endGain) throw()
  21862. {
  21863. if (startGain == endGain)
  21864. {
  21865. applyGain (channel, startSample, numSamples, startGain);
  21866. }
  21867. else
  21868. {
  21869. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21870. jassert (startSample >= 0 && startSample + numSamples <= size);
  21871. const float increment = (endGain - startGain) / numSamples;
  21872. float* d = channels [channel] + startSample;
  21873. while (--numSamples >= 0)
  21874. {
  21875. *d++ *= startGain;
  21876. startGain += increment;
  21877. }
  21878. }
  21879. }
  21880. void AudioSampleBuffer::applyGain (const int startSample,
  21881. const int numSamples,
  21882. const float gain) throw()
  21883. {
  21884. for (int i = 0; i < numChannels; ++i)
  21885. applyGain (i, startSample, numSamples, gain);
  21886. }
  21887. void AudioSampleBuffer::addFrom (const int destChannel,
  21888. const int destStartSample,
  21889. const AudioSampleBuffer& source,
  21890. const int sourceChannel,
  21891. const int sourceStartSample,
  21892. int numSamples,
  21893. const float gain) throw()
  21894. {
  21895. jassert (&source != this || sourceChannel != destChannel);
  21896. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21897. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21898. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  21899. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  21900. if (gain != 0.0f && numSamples > 0)
  21901. {
  21902. float* d = channels [destChannel] + destStartSample;
  21903. const float* s = source.channels [sourceChannel] + sourceStartSample;
  21904. if (gain != 1.0f)
  21905. {
  21906. while (--numSamples >= 0)
  21907. *d++ += gain * *s++;
  21908. }
  21909. else
  21910. {
  21911. while (--numSamples >= 0)
  21912. *d++ += *s++;
  21913. }
  21914. }
  21915. }
  21916. void AudioSampleBuffer::addFrom (const int destChannel,
  21917. const int destStartSample,
  21918. const float* source,
  21919. int numSamples,
  21920. const float gain) throw()
  21921. {
  21922. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21923. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21924. jassert (source != 0);
  21925. if (gain != 0.0f && numSamples > 0)
  21926. {
  21927. float* d = channels [destChannel] + destStartSample;
  21928. if (gain != 1.0f)
  21929. {
  21930. while (--numSamples >= 0)
  21931. *d++ += gain * *source++;
  21932. }
  21933. else
  21934. {
  21935. while (--numSamples >= 0)
  21936. *d++ += *source++;
  21937. }
  21938. }
  21939. }
  21940. void AudioSampleBuffer::addFromWithRamp (const int destChannel,
  21941. const int destStartSample,
  21942. const float* source,
  21943. int numSamples,
  21944. float startGain,
  21945. const float endGain) throw()
  21946. {
  21947. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21948. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21949. jassert (source != 0);
  21950. if (startGain == endGain)
  21951. {
  21952. addFrom (destChannel,
  21953. destStartSample,
  21954. source,
  21955. numSamples,
  21956. startGain);
  21957. }
  21958. else
  21959. {
  21960. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  21961. {
  21962. const float increment = (endGain - startGain) / numSamples;
  21963. float* d = channels [destChannel] + destStartSample;
  21964. while (--numSamples >= 0)
  21965. {
  21966. *d++ += startGain * *source++;
  21967. startGain += increment;
  21968. }
  21969. }
  21970. }
  21971. }
  21972. void AudioSampleBuffer::copyFrom (const int destChannel,
  21973. const int destStartSample,
  21974. const AudioSampleBuffer& source,
  21975. const int sourceChannel,
  21976. const int sourceStartSample,
  21977. int numSamples) throw()
  21978. {
  21979. jassert (&source != this || sourceChannel != destChannel);
  21980. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21981. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21982. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  21983. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  21984. if (numSamples > 0)
  21985. {
  21986. memcpy (channels [destChannel] + destStartSample,
  21987. source.channels [sourceChannel] + sourceStartSample,
  21988. sizeof (float) * numSamples);
  21989. }
  21990. }
  21991. void AudioSampleBuffer::copyFrom (const int destChannel,
  21992. const int destStartSample,
  21993. const float* source,
  21994. int numSamples) throw()
  21995. {
  21996. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21997. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21998. jassert (source != 0);
  21999. if (numSamples > 0)
  22000. {
  22001. memcpy (channels [destChannel] + destStartSample,
  22002. source,
  22003. sizeof (float) * numSamples);
  22004. }
  22005. }
  22006. void AudioSampleBuffer::copyFrom (const int destChannel,
  22007. const int destStartSample,
  22008. const float* source,
  22009. int numSamples,
  22010. const float gain) throw()
  22011. {
  22012. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  22013. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  22014. jassert (source != 0);
  22015. if (numSamples > 0)
  22016. {
  22017. float* d = channels [destChannel] + destStartSample;
  22018. if (gain != 1.0f)
  22019. {
  22020. if (gain == 0)
  22021. {
  22022. zeromem (d, sizeof (float) * numSamples);
  22023. }
  22024. else
  22025. {
  22026. while (--numSamples >= 0)
  22027. *d++ = gain * *source++;
  22028. }
  22029. }
  22030. else
  22031. {
  22032. memcpy (d, source, sizeof (float) * numSamples);
  22033. }
  22034. }
  22035. }
  22036. void AudioSampleBuffer::copyFromWithRamp (const int destChannel,
  22037. const int destStartSample,
  22038. const float* source,
  22039. int numSamples,
  22040. float startGain,
  22041. float endGain) throw()
  22042. {
  22043. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  22044. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  22045. jassert (source != 0);
  22046. if (startGain == endGain)
  22047. {
  22048. copyFrom (destChannel,
  22049. destStartSample,
  22050. source,
  22051. numSamples,
  22052. startGain);
  22053. }
  22054. else
  22055. {
  22056. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  22057. {
  22058. const float increment = (endGain - startGain) / numSamples;
  22059. float* d = channels [destChannel] + destStartSample;
  22060. while (--numSamples >= 0)
  22061. {
  22062. *d++ = startGain * *source++;
  22063. startGain += increment;
  22064. }
  22065. }
  22066. }
  22067. }
  22068. void AudioSampleBuffer::findMinMax (const int channel,
  22069. const int startSample,
  22070. int numSamples,
  22071. float& minVal,
  22072. float& maxVal) const throw()
  22073. {
  22074. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  22075. jassert (startSample >= 0 && startSample + numSamples <= size);
  22076. if (numSamples <= 0)
  22077. {
  22078. minVal = 0.0f;
  22079. maxVal = 0.0f;
  22080. }
  22081. else
  22082. {
  22083. const float* d = channels [channel] + startSample;
  22084. float mn = *d++;
  22085. float mx = mn;
  22086. while (--numSamples > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  22087. {
  22088. const float samp = *d++;
  22089. if (samp > mx)
  22090. mx = samp;
  22091. if (samp < mn)
  22092. mn = samp;
  22093. }
  22094. maxVal = mx;
  22095. minVal = mn;
  22096. }
  22097. }
  22098. float AudioSampleBuffer::getMagnitude (const int channel,
  22099. const int startSample,
  22100. const int numSamples) const throw()
  22101. {
  22102. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  22103. jassert (startSample >= 0 && startSample + numSamples <= size);
  22104. float mn, mx;
  22105. findMinMax (channel, startSample, numSamples, mn, mx);
  22106. return jmax (mn, -mn, mx, -mx);
  22107. }
  22108. float AudioSampleBuffer::getMagnitude (const int startSample,
  22109. const int numSamples) const throw()
  22110. {
  22111. float mag = 0.0f;
  22112. for (int i = 0; i < numChannels; ++i)
  22113. mag = jmax (mag, getMagnitude (i, startSample, numSamples));
  22114. return mag;
  22115. }
  22116. float AudioSampleBuffer::getRMSLevel (const int channel,
  22117. const int startSample,
  22118. const int numSamples) const throw()
  22119. {
  22120. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  22121. jassert (startSample >= 0 && startSample + numSamples <= size);
  22122. if (numSamples <= 0 || channel < 0 || channel >= numChannels)
  22123. return 0.0f;
  22124. const float* const data = channels [channel] + startSample;
  22125. double sum = 0.0;
  22126. for (int i = 0; i < numSamples; ++i)
  22127. {
  22128. const float sample = data [i];
  22129. sum += sample * sample;
  22130. }
  22131. return (float) std::sqrt (sum / numSamples);
  22132. }
  22133. void AudioSampleBuffer::readFromAudioReader (AudioFormatReader* reader,
  22134. const int startSample,
  22135. const int numSamples,
  22136. const int readerStartSample,
  22137. const bool useLeftChan,
  22138. const bool useRightChan)
  22139. {
  22140. jassert (reader != 0);
  22141. jassert (startSample >= 0 && startSample + numSamples <= size);
  22142. if (numSamples > 0)
  22143. {
  22144. int* chans[3];
  22145. if (useLeftChan == useRightChan)
  22146. {
  22147. chans[0] = reinterpret_cast<int*> (getSampleData (0, startSample));
  22148. chans[1] = (reader->numChannels > 1 && getNumChannels() > 1) ? reinterpret_cast<int*> (getSampleData (1, startSample)) : 0;
  22149. }
  22150. else if (useLeftChan || (reader->numChannels == 1))
  22151. {
  22152. chans[0] = reinterpret_cast<int*> (getSampleData (0, startSample));
  22153. chans[1] = 0;
  22154. }
  22155. else if (useRightChan)
  22156. {
  22157. chans[0] = 0;
  22158. chans[1] = reinterpret_cast<int*> (getSampleData (0, startSample));
  22159. }
  22160. chans[2] = 0;
  22161. reader->read (chans, 2, readerStartSample, numSamples, true);
  22162. if (! reader->usesFloatingPointData)
  22163. {
  22164. for (int j = 0; j < 2; ++j)
  22165. {
  22166. float* const d = reinterpret_cast <float*> (chans[j]);
  22167. if (d != 0)
  22168. {
  22169. const float multiplier = 1.0f / 0x7fffffff;
  22170. for (int i = 0; i < numSamples; ++i)
  22171. d[i] = *reinterpret_cast<int*> (d + i) * multiplier;
  22172. }
  22173. }
  22174. }
  22175. if (numChannels > 1 && (chans[0] == 0 || chans[1] == 0))
  22176. {
  22177. // if this is a stereo buffer and the source was mono, dupe the first channel..
  22178. memcpy (getSampleData (1, startSample),
  22179. getSampleData (0, startSample),
  22180. sizeof (float) * numSamples);
  22181. }
  22182. }
  22183. }
  22184. void AudioSampleBuffer::writeToAudioWriter (AudioFormatWriter* writer,
  22185. const int startSample,
  22186. const int numSamples) const
  22187. {
  22188. jassert (writer != 0);
  22189. writer->writeFromAudioSampleBuffer (*this, startSample, numSamples);
  22190. }
  22191. END_JUCE_NAMESPACE
  22192. /*** End of inlined file: juce_AudioSampleBuffer.cpp ***/
  22193. /*** Start of inlined file: juce_IIRFilter.cpp ***/
  22194. BEGIN_JUCE_NAMESPACE
  22195. IIRFilter::IIRFilter()
  22196. : active (false)
  22197. {
  22198. reset();
  22199. }
  22200. IIRFilter::IIRFilter (const IIRFilter& other)
  22201. : active (other.active)
  22202. {
  22203. const ScopedLock sl (other.processLock);
  22204. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  22205. reset();
  22206. }
  22207. IIRFilter::~IIRFilter()
  22208. {
  22209. }
  22210. void IIRFilter::reset() throw()
  22211. {
  22212. const ScopedLock sl (processLock);
  22213. x1 = 0;
  22214. x2 = 0;
  22215. y1 = 0;
  22216. y2 = 0;
  22217. }
  22218. float IIRFilter::processSingleSampleRaw (const float in) throw()
  22219. {
  22220. float out = coefficients[0] * in
  22221. + coefficients[1] * x1
  22222. + coefficients[2] * x2
  22223. - coefficients[4] * y1
  22224. - coefficients[5] * y2;
  22225. #if JUCE_INTEL
  22226. if (! (out < -1.0e-8 || out > 1.0e-8))
  22227. out = 0;
  22228. #endif
  22229. x2 = x1;
  22230. x1 = in;
  22231. y2 = y1;
  22232. y1 = out;
  22233. return out;
  22234. }
  22235. void IIRFilter::processSamples (float* const samples,
  22236. const int numSamples) throw()
  22237. {
  22238. const ScopedLock sl (processLock);
  22239. if (active)
  22240. {
  22241. for (int i = 0; i < numSamples; ++i)
  22242. {
  22243. const float in = samples[i];
  22244. float out = coefficients[0] * in
  22245. + coefficients[1] * x1
  22246. + coefficients[2] * x2
  22247. - coefficients[4] * y1
  22248. - coefficients[5] * y2;
  22249. #if JUCE_INTEL
  22250. if (! (out < -1.0e-8 || out > 1.0e-8))
  22251. out = 0;
  22252. #endif
  22253. x2 = x1;
  22254. x1 = in;
  22255. y2 = y1;
  22256. y1 = out;
  22257. samples[i] = out;
  22258. }
  22259. }
  22260. }
  22261. void IIRFilter::makeLowPass (const double sampleRate,
  22262. const double frequency) throw()
  22263. {
  22264. jassert (sampleRate > 0);
  22265. const double n = 1.0 / tan (double_Pi * frequency / sampleRate);
  22266. const double nSquared = n * n;
  22267. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  22268. setCoefficients (c1,
  22269. c1 * 2.0f,
  22270. c1,
  22271. 1.0,
  22272. c1 * 2.0 * (1.0 - nSquared),
  22273. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  22274. }
  22275. void IIRFilter::makeHighPass (const double sampleRate,
  22276. const double frequency) throw()
  22277. {
  22278. const double n = tan (double_Pi * frequency / sampleRate);
  22279. const double nSquared = n * n;
  22280. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  22281. setCoefficients (c1,
  22282. c1 * -2.0f,
  22283. c1,
  22284. 1.0,
  22285. c1 * 2.0 * (nSquared - 1.0),
  22286. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  22287. }
  22288. void IIRFilter::makeLowShelf (const double sampleRate,
  22289. const double cutOffFrequency,
  22290. const double Q,
  22291. const float gainFactor) throw()
  22292. {
  22293. jassert (sampleRate > 0);
  22294. jassert (Q > 0);
  22295. const double A = jmax (0.0f, gainFactor);
  22296. const double aminus1 = A - 1.0;
  22297. const double aplus1 = A + 1.0;
  22298. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  22299. const double coso = std::cos (omega);
  22300. const double beta = std::sin (omega) * std::sqrt (A) / Q;
  22301. const double aminus1TimesCoso = aminus1 * coso;
  22302. setCoefficients (A * (aplus1 - aminus1TimesCoso + beta),
  22303. A * 2.0 * (aminus1 - aplus1 * coso),
  22304. A * (aplus1 - aminus1TimesCoso - beta),
  22305. aplus1 + aminus1TimesCoso + beta,
  22306. -2.0 * (aminus1 + aplus1 * coso),
  22307. aplus1 + aminus1TimesCoso - beta);
  22308. }
  22309. void IIRFilter::makeHighShelf (const double sampleRate,
  22310. const double cutOffFrequency,
  22311. const double Q,
  22312. const float gainFactor) throw()
  22313. {
  22314. jassert (sampleRate > 0);
  22315. jassert (Q > 0);
  22316. const double A = jmax (0.0f, gainFactor);
  22317. const double aminus1 = A - 1.0;
  22318. const double aplus1 = A + 1.0;
  22319. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  22320. const double coso = std::cos (omega);
  22321. const double beta = std::sin (omega) * std::sqrt (A) / Q;
  22322. const double aminus1TimesCoso = aminus1 * coso;
  22323. setCoefficients (A * (aplus1 + aminus1TimesCoso + beta),
  22324. A * -2.0 * (aminus1 + aplus1 * coso),
  22325. A * (aplus1 + aminus1TimesCoso - beta),
  22326. aplus1 - aminus1TimesCoso + beta,
  22327. 2.0 * (aminus1 - aplus1 * coso),
  22328. aplus1 - aminus1TimesCoso - beta);
  22329. }
  22330. void IIRFilter::makeBandPass (const double sampleRate,
  22331. const double centreFrequency,
  22332. const double Q,
  22333. const float gainFactor) throw()
  22334. {
  22335. jassert (sampleRate > 0);
  22336. jassert (Q > 0);
  22337. const double A = jmax (0.0f, gainFactor);
  22338. const double omega = (double_Pi * 2.0 * jmax (centreFrequency, 2.0)) / sampleRate;
  22339. const double alpha = 0.5 * std::sin (omega) / Q;
  22340. const double c2 = -2.0 * std::cos (omega);
  22341. const double alphaTimesA = alpha * A;
  22342. const double alphaOverA = alpha / A;
  22343. setCoefficients (1.0 + alphaTimesA,
  22344. c2,
  22345. 1.0 - alphaTimesA,
  22346. 1.0 + alphaOverA,
  22347. c2,
  22348. 1.0 - alphaOverA);
  22349. }
  22350. void IIRFilter::makeInactive() throw()
  22351. {
  22352. const ScopedLock sl (processLock);
  22353. active = false;
  22354. }
  22355. void IIRFilter::copyCoefficientsFrom (const IIRFilter& other) throw()
  22356. {
  22357. const ScopedLock sl (processLock);
  22358. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  22359. active = other.active;
  22360. }
  22361. void IIRFilter::setCoefficients (double c1,
  22362. double c2,
  22363. double c3,
  22364. double c4,
  22365. double c5,
  22366. double c6) throw()
  22367. {
  22368. const double a = 1.0 / c4;
  22369. c1 *= a;
  22370. c2 *= a;
  22371. c3 *= a;
  22372. c5 *= a;
  22373. c6 *= a;
  22374. const ScopedLock sl (processLock);
  22375. coefficients[0] = (float) c1;
  22376. coefficients[1] = (float) c2;
  22377. coefficients[2] = (float) c3;
  22378. coefficients[3] = (float) c4;
  22379. coefficients[4] = (float) c5;
  22380. coefficients[5] = (float) c6;
  22381. active = true;
  22382. }
  22383. END_JUCE_NAMESPACE
  22384. /*** End of inlined file: juce_IIRFilter.cpp ***/
  22385. /*** Start of inlined file: juce_MidiBuffer.cpp ***/
  22386. BEGIN_JUCE_NAMESPACE
  22387. MidiBuffer::MidiBuffer() throw()
  22388. : bytesUsed (0)
  22389. {
  22390. }
  22391. MidiBuffer::MidiBuffer (const MidiMessage& message) throw()
  22392. : bytesUsed (0)
  22393. {
  22394. addEvent (message, 0);
  22395. }
  22396. MidiBuffer::MidiBuffer (const MidiBuffer& other) throw()
  22397. : data (other.data),
  22398. bytesUsed (other.bytesUsed)
  22399. {
  22400. }
  22401. MidiBuffer& MidiBuffer::operator= (const MidiBuffer& other) throw()
  22402. {
  22403. bytesUsed = other.bytesUsed;
  22404. data = other.data;
  22405. return *this;
  22406. }
  22407. void MidiBuffer::swapWith (MidiBuffer& other) throw()
  22408. {
  22409. data.swapWith (other.data);
  22410. swapVariables <int> (bytesUsed, other.bytesUsed);
  22411. }
  22412. MidiBuffer::~MidiBuffer()
  22413. {
  22414. }
  22415. inline uint8* MidiBuffer::getData() const throw()
  22416. {
  22417. return static_cast <uint8*> (data.getData());
  22418. }
  22419. inline int MidiBuffer::getEventTime (const void* const d) throw()
  22420. {
  22421. return *static_cast <const int*> (d);
  22422. }
  22423. inline uint16 MidiBuffer::getEventDataSize (const void* const d) throw()
  22424. {
  22425. return *reinterpret_cast <const uint16*> (static_cast <const char*> (d) + sizeof (int));
  22426. }
  22427. inline uint16 MidiBuffer::getEventTotalSize (const void* const d) throw()
  22428. {
  22429. return getEventDataSize (d) + sizeof (int) + sizeof (uint16);
  22430. }
  22431. void MidiBuffer::clear() throw()
  22432. {
  22433. bytesUsed = 0;
  22434. }
  22435. void MidiBuffer::clear (const int startSample, const int numSamples)
  22436. {
  22437. uint8* const start = findEventAfter (getData(), startSample - 1);
  22438. uint8* const end = findEventAfter (start, startSample + numSamples - 1);
  22439. if (end > start)
  22440. {
  22441. const int bytesToMove = bytesUsed - (int) (end - getData());
  22442. if (bytesToMove > 0)
  22443. memmove (start, end, bytesToMove);
  22444. bytesUsed -= (int) (end - start);
  22445. }
  22446. }
  22447. void MidiBuffer::addEvent (const MidiMessage& m, const int sampleNumber)
  22448. {
  22449. addEvent (m.getRawData(), m.getRawDataSize(), sampleNumber);
  22450. }
  22451. namespace MidiBufferHelpers
  22452. {
  22453. int findActualEventLength (const uint8* const data, const int maxBytes) throw()
  22454. {
  22455. unsigned int byte = (unsigned int) *data;
  22456. int size = 0;
  22457. if (byte == 0xf0 || byte == 0xf7)
  22458. {
  22459. const uint8* d = data + 1;
  22460. while (d < data + maxBytes)
  22461. if (*d++ == 0xf7)
  22462. break;
  22463. size = (int) (d - data);
  22464. }
  22465. else if (byte == 0xff)
  22466. {
  22467. int n;
  22468. const int bytesLeft = MidiMessage::readVariableLengthVal (data + 1, n);
  22469. size = jmin (maxBytes, n + 2 + bytesLeft);
  22470. }
  22471. else if (byte >= 0x80)
  22472. {
  22473. size = jmin (maxBytes, MidiMessage::getMessageLengthFromFirstByte ((uint8) byte));
  22474. }
  22475. return size;
  22476. }
  22477. }
  22478. void MidiBuffer::addEvent (const void* const newData, const int maxBytes, const int sampleNumber)
  22479. {
  22480. const int numBytes = MidiBufferHelpers::findActualEventLength (static_cast <const uint8*> (newData), maxBytes);
  22481. if (numBytes > 0)
  22482. {
  22483. int spaceNeeded = bytesUsed + numBytes + sizeof (int) + sizeof (uint16);
  22484. data.ensureSize ((spaceNeeded + spaceNeeded / 2 + 8) & ~7);
  22485. uint8* d = findEventAfter (getData(), sampleNumber);
  22486. const int bytesToMove = bytesUsed - (int) (d - getData());
  22487. if (bytesToMove > 0)
  22488. memmove (d + numBytes + sizeof (int) + sizeof (uint16), d, bytesToMove);
  22489. *reinterpret_cast <int*> (d) = sampleNumber;
  22490. d += sizeof (int);
  22491. *reinterpret_cast <uint16*> (d) = (uint16) numBytes;
  22492. d += sizeof (uint16);
  22493. memcpy (d, newData, numBytes);
  22494. bytesUsed += numBytes + sizeof (int) + sizeof (uint16);
  22495. }
  22496. }
  22497. void MidiBuffer::addEvents (const MidiBuffer& otherBuffer,
  22498. const int startSample,
  22499. const int numSamples,
  22500. const int sampleDeltaToAdd)
  22501. {
  22502. Iterator i (otherBuffer);
  22503. i.setNextSamplePosition (startSample);
  22504. const uint8* eventData;
  22505. int eventSize, position;
  22506. while (i.getNextEvent (eventData, eventSize, position)
  22507. && (position < startSample + numSamples || numSamples < 0))
  22508. {
  22509. addEvent (eventData, eventSize, position + sampleDeltaToAdd);
  22510. }
  22511. }
  22512. void MidiBuffer::ensureSize (size_t minimumNumBytes)
  22513. {
  22514. data.ensureSize (minimumNumBytes);
  22515. }
  22516. bool MidiBuffer::isEmpty() const throw()
  22517. {
  22518. return bytesUsed == 0;
  22519. }
  22520. int MidiBuffer::getNumEvents() const throw()
  22521. {
  22522. int n = 0;
  22523. const uint8* d = getData();
  22524. const uint8* const end = d + bytesUsed;
  22525. while (d < end)
  22526. {
  22527. d += getEventTotalSize (d);
  22528. ++n;
  22529. }
  22530. return n;
  22531. }
  22532. int MidiBuffer::getFirstEventTime() const throw()
  22533. {
  22534. return bytesUsed > 0 ? getEventTime (data.getData()) : 0;
  22535. }
  22536. int MidiBuffer::getLastEventTime() const throw()
  22537. {
  22538. if (bytesUsed == 0)
  22539. return 0;
  22540. const uint8* d = getData();
  22541. const uint8* const endData = d + bytesUsed;
  22542. for (;;)
  22543. {
  22544. const uint8* const nextOne = d + getEventTotalSize (d);
  22545. if (nextOne >= endData)
  22546. return getEventTime (d);
  22547. d = nextOne;
  22548. }
  22549. }
  22550. uint8* MidiBuffer::findEventAfter (uint8* d, const int samplePosition) const throw()
  22551. {
  22552. const uint8* const endData = getData() + bytesUsed;
  22553. while (d < endData && getEventTime (d) <= samplePosition)
  22554. d += getEventTotalSize (d);
  22555. return d;
  22556. }
  22557. MidiBuffer::Iterator::Iterator (const MidiBuffer& buffer_) throw()
  22558. : buffer (buffer_),
  22559. data (buffer_.getData())
  22560. {
  22561. }
  22562. MidiBuffer::Iterator::~Iterator() throw()
  22563. {
  22564. }
  22565. void MidiBuffer::Iterator::setNextSamplePosition (const int samplePosition) throw()
  22566. {
  22567. data = buffer.getData();
  22568. const uint8* dataEnd = data + buffer.bytesUsed;
  22569. while (data < dataEnd && getEventTime (data) < samplePosition)
  22570. data += getEventTotalSize (data);
  22571. }
  22572. bool MidiBuffer::Iterator::getNextEvent (const uint8* &midiData, int& numBytes, int& samplePosition) throw()
  22573. {
  22574. if (data >= buffer.getData() + buffer.bytesUsed)
  22575. return false;
  22576. samplePosition = getEventTime (data);
  22577. numBytes = getEventDataSize (data);
  22578. data += sizeof (int) + sizeof (uint16);
  22579. midiData = data;
  22580. data += numBytes;
  22581. return true;
  22582. }
  22583. bool MidiBuffer::Iterator::getNextEvent (MidiMessage& result, int& samplePosition) throw()
  22584. {
  22585. if (data >= buffer.getData() + buffer.bytesUsed)
  22586. return false;
  22587. samplePosition = getEventTime (data);
  22588. const int numBytes = getEventDataSize (data);
  22589. data += sizeof (int) + sizeof (uint16);
  22590. result = MidiMessage (data, numBytes, samplePosition);
  22591. data += numBytes;
  22592. return true;
  22593. }
  22594. END_JUCE_NAMESPACE
  22595. /*** End of inlined file: juce_MidiBuffer.cpp ***/
  22596. /*** Start of inlined file: juce_MidiFile.cpp ***/
  22597. BEGIN_JUCE_NAMESPACE
  22598. namespace MidiFileHelpers
  22599. {
  22600. static void writeVariableLengthInt (OutputStream& out, unsigned int v)
  22601. {
  22602. unsigned int buffer = v & 0x7F;
  22603. while ((v >>= 7) != 0)
  22604. {
  22605. buffer <<= 8;
  22606. buffer |= ((v & 0x7F) | 0x80);
  22607. }
  22608. for (;;)
  22609. {
  22610. out.writeByte ((char) buffer);
  22611. if (buffer & 0x80)
  22612. buffer >>= 8;
  22613. else
  22614. break;
  22615. }
  22616. }
  22617. static bool parseMidiHeader (const uint8* &data, short& timeFormat, short& fileType, short& numberOfTracks) throw()
  22618. {
  22619. unsigned int ch = (int) ByteOrder::bigEndianInt (data);
  22620. data += 4;
  22621. if (ch != ByteOrder::bigEndianInt ("MThd"))
  22622. {
  22623. bool ok = false;
  22624. if (ch == ByteOrder::bigEndianInt ("RIFF"))
  22625. {
  22626. for (int i = 0; i < 8; ++i)
  22627. {
  22628. ch = ByteOrder::bigEndianInt (data);
  22629. data += 4;
  22630. if (ch == ByteOrder::bigEndianInt ("MThd"))
  22631. {
  22632. ok = true;
  22633. break;
  22634. }
  22635. }
  22636. }
  22637. if (! ok)
  22638. return false;
  22639. }
  22640. unsigned int bytesRemaining = ByteOrder::bigEndianInt (data);
  22641. data += 4;
  22642. fileType = (short) ByteOrder::bigEndianShort (data);
  22643. data += 2;
  22644. numberOfTracks = (short) ByteOrder::bigEndianShort (data);
  22645. data += 2;
  22646. timeFormat = (short) ByteOrder::bigEndianShort (data);
  22647. data += 2;
  22648. bytesRemaining -= 6;
  22649. data += bytesRemaining;
  22650. return true;
  22651. }
  22652. static double convertTicksToSeconds (const double time,
  22653. const MidiMessageSequence& tempoEvents,
  22654. const int timeFormat)
  22655. {
  22656. if (timeFormat > 0)
  22657. {
  22658. int numer = 4, denom = 4;
  22659. double tempoTime = 0.0, correctedTempoTime = 0.0;
  22660. const double tickLen = 1.0 / (timeFormat & 0x7fff);
  22661. double secsPerTick = 0.5 * tickLen;
  22662. const int numEvents = tempoEvents.getNumEvents();
  22663. for (int i = 0; i < numEvents; ++i)
  22664. {
  22665. const MidiMessage& m = tempoEvents.getEventPointer(i)->message;
  22666. if (time <= m.getTimeStamp())
  22667. break;
  22668. if (timeFormat > 0)
  22669. {
  22670. correctedTempoTime = correctedTempoTime
  22671. + (m.getTimeStamp() - tempoTime) * secsPerTick;
  22672. }
  22673. else
  22674. {
  22675. correctedTempoTime = tickLen * m.getTimeStamp() / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  22676. }
  22677. tempoTime = m.getTimeStamp();
  22678. if (m.isTempoMetaEvent())
  22679. secsPerTick = tickLen * m.getTempoSecondsPerQuarterNote();
  22680. else if (m.isTimeSignatureMetaEvent())
  22681. m.getTimeSignatureInfo (numer, denom);
  22682. while (i + 1 < numEvents)
  22683. {
  22684. const MidiMessage& m2 = tempoEvents.getEventPointer(i + 1)->message;
  22685. if (m2.getTimeStamp() == tempoTime)
  22686. {
  22687. ++i;
  22688. if (m2.isTempoMetaEvent())
  22689. secsPerTick = tickLen * m2.getTempoSecondsPerQuarterNote();
  22690. else if (m2.isTimeSignatureMetaEvent())
  22691. m2.getTimeSignatureInfo (numer, denom);
  22692. }
  22693. else
  22694. {
  22695. break;
  22696. }
  22697. }
  22698. }
  22699. return correctedTempoTime + (time - tempoTime) * secsPerTick;
  22700. }
  22701. else
  22702. {
  22703. return time / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  22704. }
  22705. }
  22706. // a comparator that puts all the note-offs before note-ons that have the same time
  22707. struct Sorter
  22708. {
  22709. static int compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  22710. const MidiMessageSequence::MidiEventHolder* const second) throw()
  22711. {
  22712. const double diff = (first->message.getTimeStamp() - second->message.getTimeStamp());
  22713. if (diff == 0)
  22714. {
  22715. if (first->message.isNoteOff() && second->message.isNoteOn())
  22716. return -1;
  22717. else if (first->message.isNoteOn() && second->message.isNoteOff())
  22718. return 1;
  22719. else
  22720. return 0;
  22721. }
  22722. else
  22723. {
  22724. return (diff > 0) ? 1 : -1;
  22725. }
  22726. }
  22727. };
  22728. }
  22729. MidiFile::MidiFile()
  22730. : timeFormat ((short) (unsigned short) 0xe728)
  22731. {
  22732. }
  22733. MidiFile::~MidiFile()
  22734. {
  22735. clear();
  22736. }
  22737. void MidiFile::clear()
  22738. {
  22739. tracks.clear();
  22740. }
  22741. int MidiFile::getNumTracks() const throw()
  22742. {
  22743. return tracks.size();
  22744. }
  22745. const MidiMessageSequence* MidiFile::getTrack (const int index) const throw()
  22746. {
  22747. return tracks [index];
  22748. }
  22749. void MidiFile::addTrack (const MidiMessageSequence& trackSequence)
  22750. {
  22751. tracks.add (new MidiMessageSequence (trackSequence));
  22752. }
  22753. short MidiFile::getTimeFormat() const throw()
  22754. {
  22755. return timeFormat;
  22756. }
  22757. void MidiFile::setTicksPerQuarterNote (const int ticks) throw()
  22758. {
  22759. timeFormat = (short) ticks;
  22760. }
  22761. void MidiFile::setSmpteTimeFormat (const int framesPerSecond,
  22762. const int subframeResolution) throw()
  22763. {
  22764. timeFormat = (short) (((-framesPerSecond) << 8) | subframeResolution);
  22765. }
  22766. void MidiFile::findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const
  22767. {
  22768. for (int i = tracks.size(); --i >= 0;)
  22769. {
  22770. const int numEvents = tracks.getUnchecked(i)->getNumEvents();
  22771. for (int j = 0; j < numEvents; ++j)
  22772. {
  22773. const MidiMessage& m = tracks.getUnchecked(i)->getEventPointer (j)->message;
  22774. if (m.isTempoMetaEvent())
  22775. tempoChangeEvents.addEvent (m);
  22776. }
  22777. }
  22778. }
  22779. void MidiFile::findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const
  22780. {
  22781. for (int i = tracks.size(); --i >= 0;)
  22782. {
  22783. const int numEvents = tracks.getUnchecked(i)->getNumEvents();
  22784. for (int j = 0; j < numEvents; ++j)
  22785. {
  22786. const MidiMessage& m = tracks.getUnchecked(i)->getEventPointer (j)->message;
  22787. if (m.isTimeSignatureMetaEvent())
  22788. timeSigEvents.addEvent (m);
  22789. }
  22790. }
  22791. }
  22792. double MidiFile::getLastTimestamp() const
  22793. {
  22794. double t = 0.0;
  22795. for (int i = tracks.size(); --i >= 0;)
  22796. t = jmax (t, tracks.getUnchecked(i)->getEndTime());
  22797. return t;
  22798. }
  22799. bool MidiFile::readFrom (InputStream& sourceStream)
  22800. {
  22801. clear();
  22802. MemoryBlock data;
  22803. const int maxSensibleMidiFileSize = 2 * 1024 * 1024;
  22804. // (put a sanity-check on the file size, as midi files are generally small)
  22805. if (sourceStream.readIntoMemoryBlock (data, maxSensibleMidiFileSize))
  22806. {
  22807. size_t size = data.getSize();
  22808. const uint8* d = static_cast <const uint8*> (data.getData());
  22809. short fileType, expectedTracks;
  22810. if (size > 16 && MidiFileHelpers::parseMidiHeader (d, timeFormat, fileType, expectedTracks))
  22811. {
  22812. size -= (int) (d - static_cast <const uint8*> (data.getData()));
  22813. int track = 0;
  22814. while (size > 0 && track < expectedTracks)
  22815. {
  22816. const int chunkType = (int) ByteOrder::bigEndianInt (d);
  22817. d += 4;
  22818. const int chunkSize = (int) ByteOrder::bigEndianInt (d);
  22819. d += 4;
  22820. if (chunkSize <= 0)
  22821. break;
  22822. if (size < 0)
  22823. return false;
  22824. if (chunkType == (int) ByteOrder::bigEndianInt ("MTrk"))
  22825. {
  22826. readNextTrack (d, chunkSize);
  22827. }
  22828. size -= chunkSize + 8;
  22829. d += chunkSize;
  22830. ++track;
  22831. }
  22832. return true;
  22833. }
  22834. }
  22835. return false;
  22836. }
  22837. void MidiFile::readNextTrack (const uint8* data, int size)
  22838. {
  22839. double time = 0;
  22840. char lastStatusByte = 0;
  22841. MidiMessageSequence result;
  22842. while (size > 0)
  22843. {
  22844. int bytesUsed;
  22845. const int delay = MidiMessage::readVariableLengthVal (data, bytesUsed);
  22846. data += bytesUsed;
  22847. size -= bytesUsed;
  22848. time += delay;
  22849. int messSize = 0;
  22850. const MidiMessage mm (data, size, messSize, lastStatusByte, time);
  22851. if (messSize <= 0)
  22852. break;
  22853. size -= messSize;
  22854. data += messSize;
  22855. result.addEvent (mm);
  22856. const char firstByte = *(mm.getRawData());
  22857. if ((firstByte & 0xf0) != 0xf0)
  22858. lastStatusByte = firstByte;
  22859. }
  22860. // use a sort that puts all the note-offs before note-ons that have the same time
  22861. MidiFileHelpers::Sorter sorter;
  22862. result.list.sort (sorter, true);
  22863. result.updateMatchedPairs();
  22864. addTrack (result);
  22865. }
  22866. void MidiFile::convertTimestampTicksToSeconds()
  22867. {
  22868. MidiMessageSequence tempoEvents;
  22869. findAllTempoEvents (tempoEvents);
  22870. findAllTimeSigEvents (tempoEvents);
  22871. for (int i = 0; i < tracks.size(); ++i)
  22872. {
  22873. MidiMessageSequence& ms = *tracks.getUnchecked(i);
  22874. for (int j = ms.getNumEvents(); --j >= 0;)
  22875. {
  22876. MidiMessage& m = ms.getEventPointer(j)->message;
  22877. m.setTimeStamp (MidiFileHelpers::convertTicksToSeconds (m.getTimeStamp(),
  22878. tempoEvents,
  22879. timeFormat));
  22880. }
  22881. }
  22882. }
  22883. bool MidiFile::writeTo (OutputStream& out)
  22884. {
  22885. out.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MThd"));
  22886. out.writeIntBigEndian (6);
  22887. out.writeShortBigEndian (1); // type
  22888. out.writeShortBigEndian ((short) tracks.size());
  22889. out.writeShortBigEndian (timeFormat);
  22890. for (int i = 0; i < tracks.size(); ++i)
  22891. writeTrack (out, i);
  22892. out.flush();
  22893. return true;
  22894. }
  22895. void MidiFile::writeTrack (OutputStream& mainOut,
  22896. const int trackNum)
  22897. {
  22898. MemoryOutputStream out;
  22899. const MidiMessageSequence& ms = *tracks[trackNum];
  22900. int lastTick = 0;
  22901. char lastStatusByte = 0;
  22902. for (int i = 0; i < ms.getNumEvents(); ++i)
  22903. {
  22904. const MidiMessage& mm = ms.getEventPointer(i)->message;
  22905. const int tick = roundToInt (mm.getTimeStamp());
  22906. const int delta = jmax (0, tick - lastTick);
  22907. MidiFileHelpers::writeVariableLengthInt (out, delta);
  22908. lastTick = tick;
  22909. const char statusByte = *(mm.getRawData());
  22910. if ((statusByte == lastStatusByte)
  22911. && ((statusByte & 0xf0) != 0xf0)
  22912. && i > 0
  22913. && mm.getRawDataSize() > 1)
  22914. {
  22915. out.write (mm.getRawData() + 1, mm.getRawDataSize() - 1);
  22916. }
  22917. else
  22918. {
  22919. out.write (mm.getRawData(), mm.getRawDataSize());
  22920. }
  22921. lastStatusByte = statusByte;
  22922. }
  22923. out.writeByte (0);
  22924. const MidiMessage m (MidiMessage::endOfTrack());
  22925. out.write (m.getRawData(),
  22926. m.getRawDataSize());
  22927. mainOut.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MTrk"));
  22928. mainOut.writeIntBigEndian ((int) out.getDataSize());
  22929. mainOut.write (out.getData(), (int) out.getDataSize());
  22930. }
  22931. END_JUCE_NAMESPACE
  22932. /*** End of inlined file: juce_MidiFile.cpp ***/
  22933. /*** Start of inlined file: juce_MidiKeyboardState.cpp ***/
  22934. BEGIN_JUCE_NAMESPACE
  22935. MidiKeyboardState::MidiKeyboardState()
  22936. {
  22937. zerostruct (noteStates);
  22938. }
  22939. MidiKeyboardState::~MidiKeyboardState()
  22940. {
  22941. }
  22942. void MidiKeyboardState::reset()
  22943. {
  22944. const ScopedLock sl (lock);
  22945. zerostruct (noteStates);
  22946. eventsToAdd.clear();
  22947. }
  22948. bool MidiKeyboardState::isNoteOn (const int midiChannel, const int n) const throw()
  22949. {
  22950. jassert (midiChannel >= 0 && midiChannel <= 16);
  22951. return ((unsigned int) n) < 128
  22952. && (noteStates[n] & (1 << (midiChannel - 1))) != 0;
  22953. }
  22954. bool MidiKeyboardState::isNoteOnForChannels (const int midiChannelMask, const int n) const throw()
  22955. {
  22956. return ((unsigned int) n) < 128
  22957. && (noteStates[n] & midiChannelMask) != 0;
  22958. }
  22959. void MidiKeyboardState::noteOn (const int midiChannel, const int midiNoteNumber, const float velocity)
  22960. {
  22961. jassert (midiChannel >= 0 && midiChannel <= 16);
  22962. jassert (((unsigned int) midiNoteNumber) < 128);
  22963. const ScopedLock sl (lock);
  22964. if (((unsigned int) midiNoteNumber) < 128)
  22965. {
  22966. const int timeNow = (int) Time::getMillisecondCounter();
  22967. eventsToAdd.addEvent (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity), timeNow);
  22968. eventsToAdd.clear (0, timeNow - 500);
  22969. noteOnInternal (midiChannel, midiNoteNumber, velocity);
  22970. }
  22971. }
  22972. void MidiKeyboardState::noteOnInternal (const int midiChannel, const int midiNoteNumber, const float velocity)
  22973. {
  22974. if (((unsigned int) midiNoteNumber) < 128)
  22975. {
  22976. noteStates [midiNoteNumber] |= (1 << (midiChannel - 1));
  22977. for (int i = listeners.size(); --i >= 0;)
  22978. listeners.getUnchecked(i)->handleNoteOn (this, midiChannel, midiNoteNumber, velocity);
  22979. }
  22980. }
  22981. void MidiKeyboardState::noteOff (const int midiChannel, const int midiNoteNumber)
  22982. {
  22983. const ScopedLock sl (lock);
  22984. if (isNoteOn (midiChannel, midiNoteNumber))
  22985. {
  22986. const int timeNow = (int) Time::getMillisecondCounter();
  22987. eventsToAdd.addEvent (MidiMessage::noteOff (midiChannel, midiNoteNumber), timeNow);
  22988. eventsToAdd.clear (0, timeNow - 500);
  22989. noteOffInternal (midiChannel, midiNoteNumber);
  22990. }
  22991. }
  22992. void MidiKeyboardState::noteOffInternal (const int midiChannel, const int midiNoteNumber)
  22993. {
  22994. if (isNoteOn (midiChannel, midiNoteNumber))
  22995. {
  22996. noteStates [midiNoteNumber] &= ~(1 << (midiChannel - 1));
  22997. for (int i = listeners.size(); --i >= 0;)
  22998. listeners.getUnchecked(i)->handleNoteOff (this, midiChannel, midiNoteNumber);
  22999. }
  23000. }
  23001. void MidiKeyboardState::allNotesOff (const int midiChannel)
  23002. {
  23003. const ScopedLock sl (lock);
  23004. if (midiChannel <= 0)
  23005. {
  23006. for (int i = 1; i <= 16; ++i)
  23007. allNotesOff (i);
  23008. }
  23009. else
  23010. {
  23011. for (int i = 0; i < 128; ++i)
  23012. noteOff (midiChannel, i);
  23013. }
  23014. }
  23015. void MidiKeyboardState::processNextMidiEvent (const MidiMessage& message)
  23016. {
  23017. if (message.isNoteOn())
  23018. {
  23019. noteOnInternal (message.getChannel(), message.getNoteNumber(), message.getFloatVelocity());
  23020. }
  23021. else if (message.isNoteOff())
  23022. {
  23023. noteOffInternal (message.getChannel(), message.getNoteNumber());
  23024. }
  23025. else if (message.isAllNotesOff())
  23026. {
  23027. for (int i = 0; i < 128; ++i)
  23028. noteOffInternal (message.getChannel(), i);
  23029. }
  23030. }
  23031. void MidiKeyboardState::processNextMidiBuffer (MidiBuffer& buffer,
  23032. const int startSample,
  23033. const int numSamples,
  23034. const bool injectIndirectEvents)
  23035. {
  23036. MidiBuffer::Iterator i (buffer);
  23037. MidiMessage message (0xf4, 0.0);
  23038. int time;
  23039. const ScopedLock sl (lock);
  23040. while (i.getNextEvent (message, time))
  23041. processNextMidiEvent (message);
  23042. if (injectIndirectEvents)
  23043. {
  23044. MidiBuffer::Iterator i2 (eventsToAdd);
  23045. const int firstEventToAdd = eventsToAdd.getFirstEventTime();
  23046. const double scaleFactor = numSamples / (double) (eventsToAdd.getLastEventTime() + 1 - firstEventToAdd);
  23047. while (i2.getNextEvent (message, time))
  23048. {
  23049. const int pos = jlimit (0, numSamples - 1, roundToInt ((time - firstEventToAdd) * scaleFactor));
  23050. buffer.addEvent (message, startSample + pos);
  23051. }
  23052. }
  23053. eventsToAdd.clear();
  23054. }
  23055. void MidiKeyboardState::addListener (MidiKeyboardStateListener* const listener)
  23056. {
  23057. const ScopedLock sl (lock);
  23058. listeners.addIfNotAlreadyThere (listener);
  23059. }
  23060. void MidiKeyboardState::removeListener (MidiKeyboardStateListener* const listener)
  23061. {
  23062. const ScopedLock sl (lock);
  23063. listeners.removeValue (listener);
  23064. }
  23065. END_JUCE_NAMESPACE
  23066. /*** End of inlined file: juce_MidiKeyboardState.cpp ***/
  23067. /*** Start of inlined file: juce_MidiMessage.cpp ***/
  23068. BEGIN_JUCE_NAMESPACE
  23069. int MidiMessage::readVariableLengthVal (const uint8* data, int& numBytesUsed) throw()
  23070. {
  23071. numBytesUsed = 0;
  23072. int v = 0;
  23073. int i;
  23074. do
  23075. {
  23076. i = (int) *data++;
  23077. if (++numBytesUsed > 6)
  23078. break;
  23079. v = (v << 7) + (i & 0x7f);
  23080. } while (i & 0x80);
  23081. return v;
  23082. }
  23083. int MidiMessage::getMessageLengthFromFirstByte (const uint8 firstByte) throw()
  23084. {
  23085. // this method only works for valid starting bytes of a short midi message
  23086. jassert (firstByte >= 0x80
  23087. && firstByte != 0xf0
  23088. && firstByte != 0xf7);
  23089. static const char messageLengths[] =
  23090. {
  23091. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  23092. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  23093. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  23094. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  23095. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  23096. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  23097. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  23098. 1, 2, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
  23099. };
  23100. return messageLengths [firstByte & 0x7f];
  23101. }
  23102. MidiMessage::MidiMessage (const void* const d, const int dataSize, const double t)
  23103. : timeStamp (t),
  23104. size (dataSize)
  23105. {
  23106. jassert (dataSize > 0);
  23107. if (dataSize <= 4)
  23108. data = static_cast<uint8*> (preallocatedData.asBytes);
  23109. else
  23110. data = new uint8 [dataSize];
  23111. memcpy (data, d, dataSize);
  23112. // check that the length matches the data..
  23113. jassert (size > 3 || data[0] >= 0xf0 || getMessageLengthFromFirstByte (data[0]) == size);
  23114. }
  23115. MidiMessage::MidiMessage (const int byte1, const double t) throw()
  23116. : timeStamp (t),
  23117. data (static_cast<uint8*> (preallocatedData.asBytes)),
  23118. size (1)
  23119. {
  23120. data[0] = (uint8) byte1;
  23121. // check that the length matches the data..
  23122. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 1);
  23123. }
  23124. MidiMessage::MidiMessage (const int byte1, const int byte2, const double t) throw()
  23125. : timeStamp (t),
  23126. data (static_cast<uint8*> (preallocatedData.asBytes)),
  23127. size (2)
  23128. {
  23129. data[0] = (uint8) byte1;
  23130. data[1] = (uint8) byte2;
  23131. // check that the length matches the data..
  23132. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 2);
  23133. }
  23134. MidiMessage::MidiMessage (const int byte1, const int byte2, const int byte3, const double t) throw()
  23135. : timeStamp (t),
  23136. data (static_cast<uint8*> (preallocatedData.asBytes)),
  23137. size (3)
  23138. {
  23139. data[0] = (uint8) byte1;
  23140. data[1] = (uint8) byte2;
  23141. data[2] = (uint8) byte3;
  23142. // check that the length matches the data..
  23143. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 3);
  23144. }
  23145. MidiMessage::MidiMessage (const MidiMessage& other)
  23146. : timeStamp (other.timeStamp),
  23147. size (other.size)
  23148. {
  23149. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  23150. {
  23151. data = new uint8 [size];
  23152. memcpy (data, other.data, size);
  23153. }
  23154. else
  23155. {
  23156. data = static_cast<uint8*> (preallocatedData.asBytes);
  23157. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  23158. }
  23159. }
  23160. MidiMessage::MidiMessage (const MidiMessage& other, const double newTimeStamp)
  23161. : timeStamp (newTimeStamp),
  23162. size (other.size)
  23163. {
  23164. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  23165. {
  23166. data = new uint8 [size];
  23167. memcpy (data, other.data, size);
  23168. }
  23169. else
  23170. {
  23171. data = static_cast<uint8*> (preallocatedData.asBytes);
  23172. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  23173. }
  23174. }
  23175. MidiMessage::MidiMessage (const void* src_, int sz, int& numBytesUsed, const uint8 lastStatusByte, double t)
  23176. : timeStamp (t),
  23177. data (static_cast<uint8*> (preallocatedData.asBytes))
  23178. {
  23179. const uint8* src = static_cast <const uint8*> (src_);
  23180. unsigned int byte = (unsigned int) *src;
  23181. if (byte < 0x80)
  23182. {
  23183. byte = (unsigned int) (uint8) lastStatusByte;
  23184. numBytesUsed = -1;
  23185. }
  23186. else
  23187. {
  23188. numBytesUsed = 0;
  23189. --sz;
  23190. ++src;
  23191. }
  23192. if (byte >= 0x80)
  23193. {
  23194. if (byte == 0xf0)
  23195. {
  23196. const uint8* d = src;
  23197. while (d < src + sz)
  23198. {
  23199. if (*d >= 0x80) // stop if we hit a status byte, and don't include it in this message
  23200. {
  23201. if (*d == 0xf7) // include an 0xf7 if we hit one
  23202. ++d;
  23203. break;
  23204. }
  23205. ++d;
  23206. }
  23207. size = 1 + (int) (d - src);
  23208. data = new uint8 [size];
  23209. *data = (uint8) byte;
  23210. memcpy (data + 1, src, size - 1);
  23211. }
  23212. else if (byte == 0xff)
  23213. {
  23214. int n;
  23215. const int bytesLeft = readVariableLengthVal (src + 1, n);
  23216. size = jmin (sz + 1, n + 2 + bytesLeft);
  23217. data = new uint8 [size];
  23218. *data = (uint8) byte;
  23219. memcpy (data + 1, src, size - 1);
  23220. }
  23221. else
  23222. {
  23223. preallocatedData.asInt32 = 0;
  23224. size = getMessageLengthFromFirstByte ((uint8) byte);
  23225. data[0] = (uint8) byte;
  23226. if (size > 1)
  23227. {
  23228. data[1] = src[0];
  23229. if (size > 2)
  23230. data[2] = src[1];
  23231. }
  23232. }
  23233. numBytesUsed += size;
  23234. }
  23235. else
  23236. {
  23237. preallocatedData.asInt32 = 0;
  23238. size = 0;
  23239. }
  23240. }
  23241. MidiMessage& MidiMessage::operator= (const MidiMessage& other)
  23242. {
  23243. if (this != &other)
  23244. {
  23245. timeStamp = other.timeStamp;
  23246. size = other.size;
  23247. if (data != static_cast <const uint8*> (preallocatedData.asBytes))
  23248. delete[] data;
  23249. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  23250. {
  23251. data = new uint8 [size];
  23252. memcpy (data, other.data, size);
  23253. }
  23254. else
  23255. {
  23256. data = static_cast<uint8*> (preallocatedData.asBytes);
  23257. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  23258. }
  23259. }
  23260. return *this;
  23261. }
  23262. MidiMessage::~MidiMessage()
  23263. {
  23264. if (data != static_cast <const uint8*> (preallocatedData.asBytes))
  23265. delete[] data;
  23266. }
  23267. int MidiMessage::getChannel() const throw()
  23268. {
  23269. if ((data[0] & 0xf0) != 0xf0)
  23270. return (data[0] & 0xf) + 1;
  23271. else
  23272. return 0;
  23273. }
  23274. bool MidiMessage::isForChannel (const int channel) const throw()
  23275. {
  23276. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23277. return ((data[0] & 0xf) == channel - 1)
  23278. && ((data[0] & 0xf0) != 0xf0);
  23279. }
  23280. void MidiMessage::setChannel (const int channel) throw()
  23281. {
  23282. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23283. if ((data[0] & 0xf0) != (uint8) 0xf0)
  23284. data[0] = (uint8) ((data[0] & (uint8)0xf0)
  23285. | (uint8)(channel - 1));
  23286. }
  23287. bool MidiMessage::isNoteOn (const bool returnTrueForVelocity0) const throw()
  23288. {
  23289. return ((data[0] & 0xf0) == 0x90)
  23290. && (returnTrueForVelocity0 || data[2] != 0);
  23291. }
  23292. bool MidiMessage::isNoteOff (const bool returnTrueForNoteOnVelocity0) const throw()
  23293. {
  23294. return ((data[0] & 0xf0) == 0x80)
  23295. || (returnTrueForNoteOnVelocity0 && (data[2] == 0) && ((data[0] & 0xf0) == 0x90));
  23296. }
  23297. bool MidiMessage::isNoteOnOrOff() const throw()
  23298. {
  23299. const int d = data[0] & 0xf0;
  23300. return (d == 0x90) || (d == 0x80);
  23301. }
  23302. int MidiMessage::getNoteNumber() const throw()
  23303. {
  23304. return data[1];
  23305. }
  23306. void MidiMessage::setNoteNumber (const int newNoteNumber) throw()
  23307. {
  23308. if (isNoteOnOrOff())
  23309. data[1] = (uint8) jlimit (0, 127, newNoteNumber);
  23310. }
  23311. uint8 MidiMessage::getVelocity() const throw()
  23312. {
  23313. if (isNoteOnOrOff())
  23314. return data[2];
  23315. else
  23316. return 0;
  23317. }
  23318. float MidiMessage::getFloatVelocity() const throw()
  23319. {
  23320. return getVelocity() * (1.0f / 127.0f);
  23321. }
  23322. void MidiMessage::setVelocity (const float newVelocity) throw()
  23323. {
  23324. if (isNoteOnOrOff())
  23325. data[2] = (uint8) jlimit (0, 0x7f, roundToInt (newVelocity * 127.0f));
  23326. }
  23327. void MidiMessage::multiplyVelocity (const float scaleFactor) throw()
  23328. {
  23329. if (isNoteOnOrOff())
  23330. data[2] = (uint8) jlimit (0, 0x7f, roundToInt (scaleFactor * data[2]));
  23331. }
  23332. bool MidiMessage::isAftertouch() const throw()
  23333. {
  23334. return (data[0] & 0xf0) == 0xa0;
  23335. }
  23336. int MidiMessage::getAfterTouchValue() const throw()
  23337. {
  23338. return data[2];
  23339. }
  23340. const MidiMessage MidiMessage::aftertouchChange (const int channel,
  23341. const int noteNum,
  23342. const int aftertouchValue) throw()
  23343. {
  23344. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23345. jassert (((unsigned int) noteNum) <= 127);
  23346. jassert (((unsigned int) aftertouchValue) <= 127);
  23347. return MidiMessage (0xa0 | jlimit (0, 15, channel - 1),
  23348. noteNum & 0x7f,
  23349. aftertouchValue & 0x7f);
  23350. }
  23351. bool MidiMessage::isChannelPressure() const throw()
  23352. {
  23353. return (data[0] & 0xf0) == 0xd0;
  23354. }
  23355. int MidiMessage::getChannelPressureValue() const throw()
  23356. {
  23357. jassert (isChannelPressure());
  23358. return data[1];
  23359. }
  23360. const MidiMessage MidiMessage::channelPressureChange (const int channel,
  23361. const int pressure) throw()
  23362. {
  23363. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23364. jassert (((unsigned int) pressure) <= 127);
  23365. return MidiMessage (0xd0 | jlimit (0, 15, channel - 1),
  23366. pressure & 0x7f);
  23367. }
  23368. bool MidiMessage::isProgramChange() const throw()
  23369. {
  23370. return (data[0] & 0xf0) == 0xc0;
  23371. }
  23372. int MidiMessage::getProgramChangeNumber() const throw()
  23373. {
  23374. return data[1];
  23375. }
  23376. const MidiMessage MidiMessage::programChange (const int channel,
  23377. const int programNumber) throw()
  23378. {
  23379. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23380. return MidiMessage (0xc0 | jlimit (0, 15, channel - 1),
  23381. programNumber & 0x7f);
  23382. }
  23383. bool MidiMessage::isPitchWheel() const throw()
  23384. {
  23385. return (data[0] & 0xf0) == 0xe0;
  23386. }
  23387. int MidiMessage::getPitchWheelValue() const throw()
  23388. {
  23389. return data[1] | (data[2] << 7);
  23390. }
  23391. const MidiMessage MidiMessage::pitchWheel (const int channel,
  23392. const int position) throw()
  23393. {
  23394. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23395. jassert (((unsigned int) position) <= 0x3fff);
  23396. return MidiMessage (0xe0 | jlimit (0, 15, channel - 1),
  23397. position & 127,
  23398. (position >> 7) & 127);
  23399. }
  23400. bool MidiMessage::isController() const throw()
  23401. {
  23402. return (data[0] & 0xf0) == 0xb0;
  23403. }
  23404. int MidiMessage::getControllerNumber() const throw()
  23405. {
  23406. jassert (isController());
  23407. return data[1];
  23408. }
  23409. int MidiMessage::getControllerValue() const throw()
  23410. {
  23411. jassert (isController());
  23412. return data[2];
  23413. }
  23414. const MidiMessage MidiMessage::controllerEvent (const int channel,
  23415. const int controllerType,
  23416. const int value) throw()
  23417. {
  23418. // the channel must be between 1 and 16 inclusive
  23419. jassert (channel > 0 && channel <= 16);
  23420. return MidiMessage (0xb0 | jlimit (0, 15, channel - 1),
  23421. controllerType & 127,
  23422. value & 127);
  23423. }
  23424. const MidiMessage MidiMessage::noteOn (const int channel,
  23425. const int noteNumber,
  23426. const float velocity) throw()
  23427. {
  23428. return noteOn (channel, noteNumber, (uint8)(velocity * 127.0f));
  23429. }
  23430. const MidiMessage MidiMessage::noteOn (const int channel,
  23431. const int noteNumber,
  23432. const uint8 velocity) throw()
  23433. {
  23434. jassert (channel > 0 && channel <= 16);
  23435. jassert (((unsigned int) noteNumber) <= 127);
  23436. return MidiMessage (0x90 | jlimit (0, 15, channel - 1),
  23437. noteNumber & 127,
  23438. jlimit (0, 127, roundToInt (velocity)));
  23439. }
  23440. const MidiMessage MidiMessage::noteOff (const int channel,
  23441. const int noteNumber) throw()
  23442. {
  23443. jassert (channel > 0 && channel <= 16);
  23444. jassert (((unsigned int) noteNumber) <= 127);
  23445. return MidiMessage (0x80 | jlimit (0, 15, channel - 1), noteNumber & 127, 0);
  23446. }
  23447. const MidiMessage MidiMessage::allNotesOff (const int channel) throw()
  23448. {
  23449. return controllerEvent (channel, 123, 0);
  23450. }
  23451. bool MidiMessage::isAllNotesOff() const throw()
  23452. {
  23453. return (data[0] & 0xf0) == 0xb0
  23454. && data[1] == 123;
  23455. }
  23456. const MidiMessage MidiMessage::allSoundOff (const int channel) throw()
  23457. {
  23458. return controllerEvent (channel, 120, 0);
  23459. }
  23460. bool MidiMessage::isAllSoundOff() const throw()
  23461. {
  23462. return (data[0] & 0xf0) == 0xb0
  23463. && data[1] == 120;
  23464. }
  23465. const MidiMessage MidiMessage::allControllersOff (const int channel) throw()
  23466. {
  23467. return controllerEvent (channel, 121, 0);
  23468. }
  23469. const MidiMessage MidiMessage::masterVolume (const float volume)
  23470. {
  23471. const int vol = jlimit (0, 0x3fff, roundToInt (volume * 0x4000));
  23472. uint8 buf[8];
  23473. buf[0] = 0xf0;
  23474. buf[1] = 0x7f;
  23475. buf[2] = 0x7f;
  23476. buf[3] = 0x04;
  23477. buf[4] = 0x01;
  23478. buf[5] = (uint8) (vol & 0x7f);
  23479. buf[6] = (uint8) (vol >> 7);
  23480. buf[7] = 0xf7;
  23481. return MidiMessage (buf, 8);
  23482. }
  23483. bool MidiMessage::isSysEx() const throw()
  23484. {
  23485. return *data == 0xf0;
  23486. }
  23487. const MidiMessage MidiMessage::createSysExMessage (const uint8* sysexData, const int dataSize)
  23488. {
  23489. MemoryBlock mm (dataSize + 2);
  23490. uint8* const m = static_cast <uint8*> (mm.getData());
  23491. m[0] = 0xf0;
  23492. memcpy (m + 1, sysexData, dataSize);
  23493. m[dataSize + 1] = 0xf7;
  23494. return MidiMessage (m, dataSize + 2);
  23495. }
  23496. const uint8* MidiMessage::getSysExData() const throw()
  23497. {
  23498. return (isSysEx()) ? getRawData() + 1 : 0;
  23499. }
  23500. int MidiMessage::getSysExDataSize() const throw()
  23501. {
  23502. return (isSysEx()) ? size - 2 : 0;
  23503. }
  23504. bool MidiMessage::isMetaEvent() const throw()
  23505. {
  23506. return *data == 0xff;
  23507. }
  23508. bool MidiMessage::isActiveSense() const throw()
  23509. {
  23510. return *data == 0xfe;
  23511. }
  23512. int MidiMessage::getMetaEventType() const throw()
  23513. {
  23514. if (*data != 0xff)
  23515. return -1;
  23516. else
  23517. return data[1];
  23518. }
  23519. int MidiMessage::getMetaEventLength() const throw()
  23520. {
  23521. if (*data == 0xff)
  23522. {
  23523. int n;
  23524. return jmin (size - 2, readVariableLengthVal (data + 2, n));
  23525. }
  23526. return 0;
  23527. }
  23528. const uint8* MidiMessage::getMetaEventData() const throw()
  23529. {
  23530. int n;
  23531. const uint8* d = data + 2;
  23532. readVariableLengthVal (d, n);
  23533. return d + n;
  23534. }
  23535. bool MidiMessage::isTrackMetaEvent() const throw()
  23536. {
  23537. return getMetaEventType() == 0;
  23538. }
  23539. bool MidiMessage::isEndOfTrackMetaEvent() const throw()
  23540. {
  23541. return getMetaEventType() == 47;
  23542. }
  23543. bool MidiMessage::isTextMetaEvent() const throw()
  23544. {
  23545. const int t = getMetaEventType();
  23546. return t > 0 && t < 16;
  23547. }
  23548. const String MidiMessage::getTextFromTextMetaEvent() const
  23549. {
  23550. return String (reinterpret_cast <const char*> (getMetaEventData()), getMetaEventLength());
  23551. }
  23552. bool MidiMessage::isTrackNameEvent() const throw()
  23553. {
  23554. return (data[1] == 3)
  23555. && (*data == 0xff);
  23556. }
  23557. bool MidiMessage::isTempoMetaEvent() const throw()
  23558. {
  23559. return (data[1] == 81)
  23560. && (*data == 0xff);
  23561. }
  23562. bool MidiMessage::isMidiChannelMetaEvent() const throw()
  23563. {
  23564. return (data[1] == 0x20)
  23565. && (*data == 0xff)
  23566. && (data[2] == 1);
  23567. }
  23568. int MidiMessage::getMidiChannelMetaEventChannel() const throw()
  23569. {
  23570. return data[3] + 1;
  23571. }
  23572. double MidiMessage::getTempoSecondsPerQuarterNote() const throw()
  23573. {
  23574. if (! isTempoMetaEvent())
  23575. return 0.0;
  23576. const uint8* const d = getMetaEventData();
  23577. return (((unsigned int) d[0] << 16)
  23578. | ((unsigned int) d[1] << 8)
  23579. | d[2])
  23580. / 1000000.0;
  23581. }
  23582. double MidiMessage::getTempoMetaEventTickLength (const short timeFormat) const throw()
  23583. {
  23584. if (timeFormat > 0)
  23585. {
  23586. if (! isTempoMetaEvent())
  23587. return 0.5 / timeFormat;
  23588. return getTempoSecondsPerQuarterNote() / timeFormat;
  23589. }
  23590. else
  23591. {
  23592. const int frameCode = (-timeFormat) >> 8;
  23593. double framesPerSecond;
  23594. switch (frameCode)
  23595. {
  23596. case 24: framesPerSecond = 24.0; break;
  23597. case 25: framesPerSecond = 25.0; break;
  23598. case 29: framesPerSecond = 29.97; break;
  23599. case 30: framesPerSecond = 30.0; break;
  23600. default: framesPerSecond = 30.0; break;
  23601. }
  23602. return (1.0 / framesPerSecond) / (timeFormat & 0xff);
  23603. }
  23604. }
  23605. const MidiMessage MidiMessage::tempoMetaEvent (int microsecondsPerQuarterNote) throw()
  23606. {
  23607. uint8 d[8];
  23608. d[0] = 0xff;
  23609. d[1] = 81;
  23610. d[2] = 3;
  23611. d[3] = (uint8) (microsecondsPerQuarterNote >> 16);
  23612. d[4] = (uint8) ((microsecondsPerQuarterNote >> 8) & 0xff);
  23613. d[5] = (uint8) (microsecondsPerQuarterNote & 0xff);
  23614. return MidiMessage (d, 6, 0.0);
  23615. }
  23616. bool MidiMessage::isTimeSignatureMetaEvent() const throw()
  23617. {
  23618. return (data[1] == 0x58)
  23619. && (*data == (uint8) 0xff);
  23620. }
  23621. void MidiMessage::getTimeSignatureInfo (int& numerator, int& denominator) const throw()
  23622. {
  23623. if (isTimeSignatureMetaEvent())
  23624. {
  23625. const uint8* const d = getMetaEventData();
  23626. numerator = d[0];
  23627. denominator = 1 << d[1];
  23628. }
  23629. else
  23630. {
  23631. numerator = 4;
  23632. denominator = 4;
  23633. }
  23634. }
  23635. const MidiMessage MidiMessage::timeSignatureMetaEvent (const int numerator, const int denominator)
  23636. {
  23637. uint8 d[8];
  23638. d[0] = 0xff;
  23639. d[1] = 0x58;
  23640. d[2] = 0x04;
  23641. d[3] = (uint8) numerator;
  23642. int n = 1;
  23643. int powerOfTwo = 0;
  23644. while (n < denominator)
  23645. {
  23646. n <<= 1;
  23647. ++powerOfTwo;
  23648. }
  23649. d[4] = (uint8) powerOfTwo;
  23650. d[5] = 0x01;
  23651. d[6] = 96;
  23652. return MidiMessage (d, 7, 0.0);
  23653. }
  23654. const MidiMessage MidiMessage::midiChannelMetaEvent (const int channel) throw()
  23655. {
  23656. uint8 d[8];
  23657. d[0] = 0xff;
  23658. d[1] = 0x20;
  23659. d[2] = 0x01;
  23660. d[3] = (uint8) jlimit (0, 0xff, channel - 1);
  23661. return MidiMessage (d, 4, 0.0);
  23662. }
  23663. bool MidiMessage::isKeySignatureMetaEvent() const throw()
  23664. {
  23665. return getMetaEventType() == 89;
  23666. }
  23667. int MidiMessage::getKeySignatureNumberOfSharpsOrFlats() const throw()
  23668. {
  23669. return (int) *getMetaEventData();
  23670. }
  23671. const MidiMessage MidiMessage::endOfTrack() throw()
  23672. {
  23673. return MidiMessage (0xff, 0x2f, 0, 0.0);
  23674. }
  23675. bool MidiMessage::isSongPositionPointer() const throw()
  23676. {
  23677. return *data == 0xf2;
  23678. }
  23679. int MidiMessage::getSongPositionPointerMidiBeat() const throw()
  23680. {
  23681. return data[1] | (data[2] << 7);
  23682. }
  23683. const MidiMessage MidiMessage::songPositionPointer (const int positionInMidiBeats) throw()
  23684. {
  23685. return MidiMessage (0xf2,
  23686. positionInMidiBeats & 127,
  23687. (positionInMidiBeats >> 7) & 127);
  23688. }
  23689. bool MidiMessage::isMidiStart() const throw()
  23690. {
  23691. return *data == 0xfa;
  23692. }
  23693. const MidiMessage MidiMessage::midiStart() throw()
  23694. {
  23695. return MidiMessage (0xfa);
  23696. }
  23697. bool MidiMessage::isMidiContinue() const throw()
  23698. {
  23699. return *data == 0xfb;
  23700. }
  23701. const MidiMessage MidiMessage::midiContinue() throw()
  23702. {
  23703. return MidiMessage (0xfb);
  23704. }
  23705. bool MidiMessage::isMidiStop() const throw()
  23706. {
  23707. return *data == 0xfc;
  23708. }
  23709. const MidiMessage MidiMessage::midiStop() throw()
  23710. {
  23711. return MidiMessage (0xfc);
  23712. }
  23713. bool MidiMessage::isMidiClock() const throw()
  23714. {
  23715. return *data == 0xf8;
  23716. }
  23717. const MidiMessage MidiMessage::midiClock() throw()
  23718. {
  23719. return MidiMessage (0xf8);
  23720. }
  23721. bool MidiMessage::isQuarterFrame() const throw()
  23722. {
  23723. return *data == 0xf1;
  23724. }
  23725. int MidiMessage::getQuarterFrameSequenceNumber() const throw()
  23726. {
  23727. return ((int) data[1]) >> 4;
  23728. }
  23729. int MidiMessage::getQuarterFrameValue() const throw()
  23730. {
  23731. return ((int) data[1]) & 0x0f;
  23732. }
  23733. const MidiMessage MidiMessage::quarterFrame (const int sequenceNumber,
  23734. const int value) throw()
  23735. {
  23736. return MidiMessage (0xf1, (sequenceNumber << 4) | value);
  23737. }
  23738. bool MidiMessage::isFullFrame() const throw()
  23739. {
  23740. return data[0] == 0xf0
  23741. && data[1] == 0x7f
  23742. && size >= 10
  23743. && data[3] == 0x01
  23744. && data[4] == 0x01;
  23745. }
  23746. void MidiMessage::getFullFrameParameters (int& hours,
  23747. int& minutes,
  23748. int& seconds,
  23749. int& frames,
  23750. MidiMessage::SmpteTimecodeType& timecodeType) const throw()
  23751. {
  23752. jassert (isFullFrame());
  23753. timecodeType = (SmpteTimecodeType) (data[5] >> 5);
  23754. hours = data[5] & 0x1f;
  23755. minutes = data[6];
  23756. seconds = data[7];
  23757. frames = data[8];
  23758. }
  23759. const MidiMessage MidiMessage::fullFrame (const int hours,
  23760. const int minutes,
  23761. const int seconds,
  23762. const int frames,
  23763. MidiMessage::SmpteTimecodeType timecodeType)
  23764. {
  23765. uint8 d[10];
  23766. d[0] = 0xf0;
  23767. d[1] = 0x7f;
  23768. d[2] = 0x7f;
  23769. d[3] = 0x01;
  23770. d[4] = 0x01;
  23771. d[5] = (uint8) ((hours & 0x01f) | (timecodeType << 5));
  23772. d[6] = (uint8) minutes;
  23773. d[7] = (uint8) seconds;
  23774. d[8] = (uint8) frames;
  23775. d[9] = 0xf7;
  23776. return MidiMessage (d, 10, 0.0);
  23777. }
  23778. bool MidiMessage::isMidiMachineControlMessage() const throw()
  23779. {
  23780. return data[0] == 0xf0
  23781. && data[1] == 0x7f
  23782. && data[3] == 0x06
  23783. && size > 5;
  23784. }
  23785. MidiMessage::MidiMachineControlCommand MidiMessage::getMidiMachineControlCommand() const throw()
  23786. {
  23787. jassert (isMidiMachineControlMessage());
  23788. return (MidiMachineControlCommand) data[4];
  23789. }
  23790. const MidiMessage MidiMessage::midiMachineControlCommand (MidiMessage::MidiMachineControlCommand command)
  23791. {
  23792. uint8 d[6];
  23793. d[0] = 0xf0;
  23794. d[1] = 0x7f;
  23795. d[2] = 0x00;
  23796. d[3] = 0x06;
  23797. d[4] = (uint8) command;
  23798. d[5] = 0xf7;
  23799. return MidiMessage (d, 6, 0.0);
  23800. }
  23801. bool MidiMessage::isMidiMachineControlGoto (int& hours,
  23802. int& minutes,
  23803. int& seconds,
  23804. int& frames) const throw()
  23805. {
  23806. if (size >= 12
  23807. && data[0] == 0xf0
  23808. && data[1] == 0x7f
  23809. && data[3] == 0x06
  23810. && data[4] == 0x44
  23811. && data[5] == 0x06
  23812. && data[6] == 0x01)
  23813. {
  23814. hours = data[7] % 24; // (that some machines send out hours > 24)
  23815. minutes = data[8];
  23816. seconds = data[9];
  23817. frames = data[10];
  23818. return true;
  23819. }
  23820. return false;
  23821. }
  23822. const MidiMessage MidiMessage::midiMachineControlGoto (int hours,
  23823. int minutes,
  23824. int seconds,
  23825. int frames)
  23826. {
  23827. uint8 d[12];
  23828. d[0] = 0xf0;
  23829. d[1] = 0x7f;
  23830. d[2] = 0x00;
  23831. d[3] = 0x06;
  23832. d[4] = 0x44;
  23833. d[5] = 0x06;
  23834. d[6] = 0x01;
  23835. d[7] = (uint8) hours;
  23836. d[8] = (uint8) minutes;
  23837. d[9] = (uint8) seconds;
  23838. d[10] = (uint8) frames;
  23839. d[11] = 0xf7;
  23840. return MidiMessage (d, 12, 0.0);
  23841. }
  23842. const String MidiMessage::getMidiNoteName (int note, bool useSharps, bool includeOctaveNumber, int octaveNumForMiddleC)
  23843. {
  23844. static const char* const sharpNoteNames[] = { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" };
  23845. static const char* const flatNoteNames[] = { "C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab", "A", "Bb", "B" };
  23846. if (((unsigned int) note) < 128)
  23847. {
  23848. String s (useSharps ? sharpNoteNames [note % 12]
  23849. : flatNoteNames [note % 12]);
  23850. if (includeOctaveNumber)
  23851. s << (note / 12 + (octaveNumForMiddleC - 5));
  23852. return s;
  23853. }
  23854. return String::empty;
  23855. }
  23856. const double MidiMessage::getMidiNoteInHertz (int noteNumber, const double frequencyOfA) throw()
  23857. {
  23858. noteNumber -= 12 * 6 + 9; // now 0 = A
  23859. return frequencyOfA * pow (2.0, noteNumber / 12.0);
  23860. }
  23861. const String MidiMessage::getGMInstrumentName (const int n)
  23862. {
  23863. const char* names[] =
  23864. {
  23865. "Acoustic Grand Piano", "Bright Acoustic Piano", "Electric Grand Piano", "Honky-tonk Piano",
  23866. "Electric Piano 1", "Electric Piano 2", "Harpsichord", "Clavinet", "Celesta", "Glockenspiel",
  23867. "Music Box", "Vibraphone", "Marimba", "Xylophone", "Tubular Bells", "Dulcimer", "Drawbar Organ",
  23868. "Percussive Organ", "Rock Organ", "Church Organ", "Reed Organ", "Accordion", "Harmonica",
  23869. "Tango Accordion", "Acoustic Guitar (nylon)", "Acoustic Guitar (steel)", "Electric Guitar (jazz)",
  23870. "Electric Guitar (clean)", "Electric Guitar (mute)", "Overdriven Guitar", "Distortion Guitar",
  23871. "Guitar Harmonics", "Acoustic Bass", "Electric Bass (finger)", "Electric Bass (pick)",
  23872. "Fretless Bass", "Slap Bass 1", "Slap Bass 2", "Synth Bass 1", "Synth Bass 2", "Violin",
  23873. "Viola", "Cello", "Contrabass", "Tremolo Strings", "Pizzicato Strings", "Orchestral Harp",
  23874. "Timpani", "String Ensemble 1", "String Ensemble 2", "SynthStrings 1", "SynthStrings 2",
  23875. "Choir Aahs", "Voice Oohs", "Synth Voice", "Orchestra Hit", "Trumpet", "Trombone", "Tuba",
  23876. "Muted Trumpet", "French Horn", "Brass Section", "SynthBrass 1", "SynthBrass 2", "Soprano Sax",
  23877. "Alto Sax", "Tenor Sax", "Baritone Sax", "Oboe", "English Horn", "Bassoon", "Clarinet",
  23878. "Piccolo", "Flute", "Recorder", "Pan Flute", "Blown Bottle", "Shakuhachi", "Whistle",
  23879. "Ocarina", "Lead 1 (square)", "Lead 2 (sawtooth)", "Lead 3 (calliope)", "Lead 4 (chiff)",
  23880. "Lead 5 (charang)", "Lead 6 (voice)", "Lead 7 (fifths)", "Lead 8 (bass+lead)", "Pad 1 (new age)",
  23881. "Pad 2 (warm)", "Pad 3 (polysynth)", "Pad 4 (choir)", "Pad 5 (bowed)", "Pad 6 (metallic)",
  23882. "Pad 7 (halo)", "Pad 8 (sweep)", "FX 1 (rain)", "FX 2 (soundtrack)", "FX 3 (crystal)",
  23883. "FX 4 (atmosphere)", "FX 5 (brightness)", "FX 6 (goblins)", "FX 7 (echoes)", "FX 8 (sci-fi)",
  23884. "Sitar", "Banjo", "Shamisen", "Koto", "Kalimba", "Bag pipe", "Fiddle", "Shanai", "Tinkle Bell",
  23885. "Agogo", "Steel Drums", "Woodblock", "Taiko Drum", "Melodic Tom", "Synth Drum", "Reverse Cymbal",
  23886. "Guitar Fret Noise", "Breath Noise", "Seashore", "Bird Tweet", "Telephone Ring", "Helicopter",
  23887. "Applause", "Gunshot"
  23888. };
  23889. return (((unsigned int) n) < 128) ? names[n] : (const char*) 0;
  23890. }
  23891. const String MidiMessage::getGMInstrumentBankName (const int n)
  23892. {
  23893. const char* names[] =
  23894. {
  23895. "Piano", "Chromatic Percussion", "Organ", "Guitar",
  23896. "Bass", "Strings", "Ensemble", "Brass",
  23897. "Reed", "Pipe", "Synth Lead", "Synth Pad",
  23898. "Synth Effects", "Ethnic", "Percussive", "Sound Effects"
  23899. };
  23900. return (((unsigned int) n) <= 15) ? names[n] : (const char*) 0;
  23901. }
  23902. const String MidiMessage::getRhythmInstrumentName (const int n)
  23903. {
  23904. const char* names[] =
  23905. {
  23906. "Acoustic Bass Drum", "Bass Drum 1", "Side Stick", "Acoustic Snare",
  23907. "Hand Clap", "Electric Snare", "Low Floor Tom", "Closed Hi-Hat", "High Floor Tom",
  23908. "Pedal Hi-Hat", "Low Tom", "Open Hi-Hat", "Low-Mid Tom", "Hi-Mid Tom", "Crash Cymbal 1",
  23909. "High Tom", "Ride Cymbal 1", "Chinese Cymbal", "Ride Bell", "Tambourine", "Splash Cymbal",
  23910. "Cowbell", "Crash Cymbal 2", "Vibraslap", "Ride Cymbal 2", "Hi Bongo", "Low Bongo",
  23911. "Mute Hi Conga", "Open Hi Conga", "Low Conga", "High Timbale", "Low Timbale", "High Agogo",
  23912. "Low Agogo", "Cabasa", "Maracas", "Short Whistle", "Long Whistle", "Short Guiro",
  23913. "Long Guiro", "Claves", "Hi Wood Block", "Low Wood Block", "Mute Cuica", "Open Cuica",
  23914. "Mute Triangle", "Open Triangle"
  23915. };
  23916. return (n >= 35 && n <= 81) ? names [n - 35] : (const char*) 0;
  23917. }
  23918. const String MidiMessage::getControllerName (const int n)
  23919. {
  23920. const char* names[] =
  23921. {
  23922. "Bank Select", "Modulation Wheel (coarse)", "Breath controller (coarse)",
  23923. 0, "Foot Pedal (coarse)", "Portamento Time (coarse)",
  23924. "Data Entry (coarse)", "Volume (coarse)", "Balance (coarse)",
  23925. 0, "Pan position (coarse)", "Expression (coarse)", "Effect Control 1 (coarse)",
  23926. "Effect Control 2 (coarse)", 0, 0, "General Purpose Slider 1", "General Purpose Slider 2",
  23927. "General Purpose Slider 3", "General Purpose Slider 4", 0, 0, 0, 0, 0, 0, 0, 0,
  23928. 0, 0, 0, 0, "Bank Select (fine)", "Modulation Wheel (fine)", "Breath controller (fine)",
  23929. 0, "Foot Pedal (fine)", "Portamento Time (fine)", "Data Entry (fine)", "Volume (fine)",
  23930. "Balance (fine)", 0, "Pan position (fine)", "Expression (fine)", "Effect Control 1 (fine)",
  23931. "Effect Control 2 (fine)", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  23932. "Hold Pedal (on/off)", "Portamento (on/off)", "Sustenuto Pedal (on/off)", "Soft Pedal (on/off)",
  23933. "Legato Pedal (on/off)", "Hold 2 Pedal (on/off)", "Sound Variation", "Sound Timbre",
  23934. "Sound Release Time", "Sound Attack Time", "Sound Brightness", "Sound Control 6",
  23935. "Sound Control 7", "Sound Control 8", "Sound Control 9", "Sound Control 10",
  23936. "General Purpose Button 1 (on/off)", "General Purpose Button 2 (on/off)",
  23937. "General Purpose Button 3 (on/off)", "General Purpose Button 4 (on/off)",
  23938. 0, 0, 0, 0, 0, 0, 0, "Reverb Level", "Tremolo Level", "Chorus Level", "Celeste Level",
  23939. "Phaser Level", "Data Button increment", "Data Button decrement", "Non-registered Parameter (fine)",
  23940. "Non-registered Parameter (coarse)", "Registered Parameter (fine)", "Registered Parameter (coarse)",
  23941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "All Sound Off", "All Controllers Off",
  23942. "Local Keyboard (on/off)", "All Notes Off", "Omni Mode Off", "Omni Mode On", "Mono Operation",
  23943. "Poly Operation"
  23944. };
  23945. return (((unsigned int) n) < 128) ? names[n] : (const char*) 0;
  23946. }
  23947. END_JUCE_NAMESPACE
  23948. /*** End of inlined file: juce_MidiMessage.cpp ***/
  23949. /*** Start of inlined file: juce_MidiMessageCollector.cpp ***/
  23950. BEGIN_JUCE_NAMESPACE
  23951. MidiMessageCollector::MidiMessageCollector()
  23952. : lastCallbackTime (0),
  23953. sampleRate (44100.0001)
  23954. {
  23955. }
  23956. MidiMessageCollector::~MidiMessageCollector()
  23957. {
  23958. }
  23959. void MidiMessageCollector::reset (const double sampleRate_)
  23960. {
  23961. jassert (sampleRate_ > 0);
  23962. const ScopedLock sl (midiCallbackLock);
  23963. sampleRate = sampleRate_;
  23964. incomingMessages.clear();
  23965. lastCallbackTime = Time::getMillisecondCounterHiRes();
  23966. }
  23967. void MidiMessageCollector::addMessageToQueue (const MidiMessage& message)
  23968. {
  23969. // you need to call reset() to set the correct sample rate before using this object
  23970. jassert (sampleRate != 44100.0001);
  23971. // the messages that come in here need to be time-stamped correctly - see MidiInput
  23972. // for details of what the number should be.
  23973. jassert (message.getTimeStamp() != 0);
  23974. const ScopedLock sl (midiCallbackLock);
  23975. const int sampleNumber
  23976. = (int) ((message.getTimeStamp() - 0.001 * lastCallbackTime) * sampleRate);
  23977. incomingMessages.addEvent (message, sampleNumber);
  23978. // if the messages don't get used for over a second, we'd better
  23979. // get rid of any old ones to avoid the queue getting too big
  23980. if (sampleNumber > sampleRate)
  23981. incomingMessages.clear (0, sampleNumber - (int) sampleRate);
  23982. }
  23983. void MidiMessageCollector::removeNextBlockOfMessages (MidiBuffer& destBuffer,
  23984. const int numSamples)
  23985. {
  23986. // you need to call reset() to set the correct sample rate before using this object
  23987. jassert (sampleRate != 44100.0001);
  23988. const double timeNow = Time::getMillisecondCounterHiRes();
  23989. const double msElapsed = timeNow - lastCallbackTime;
  23990. const ScopedLock sl (midiCallbackLock);
  23991. lastCallbackTime = timeNow;
  23992. if (! incomingMessages.isEmpty())
  23993. {
  23994. int numSourceSamples = jmax (1, roundToInt (msElapsed * 0.001 * sampleRate));
  23995. int startSample = 0;
  23996. int scale = 1 << 16;
  23997. const uint8* midiData;
  23998. int numBytes, samplePosition;
  23999. MidiBuffer::Iterator iter (incomingMessages);
  24000. if (numSourceSamples > numSamples)
  24001. {
  24002. // if our list of events is longer than the buffer we're being
  24003. // asked for, scale them down to squeeze them all in..
  24004. const int maxBlockLengthToUse = numSamples << 5;
  24005. if (numSourceSamples > maxBlockLengthToUse)
  24006. {
  24007. startSample = numSourceSamples - maxBlockLengthToUse;
  24008. numSourceSamples = maxBlockLengthToUse;
  24009. iter.setNextSamplePosition (startSample);
  24010. }
  24011. scale = (numSamples << 10) / numSourceSamples;
  24012. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  24013. {
  24014. samplePosition = ((samplePosition - startSample) * scale) >> 10;
  24015. destBuffer.addEvent (midiData, numBytes,
  24016. jlimit (0, numSamples - 1, samplePosition));
  24017. }
  24018. }
  24019. else
  24020. {
  24021. // if our event list is shorter than the number we need, put them
  24022. // towards the end of the buffer
  24023. startSample = numSamples - numSourceSamples;
  24024. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  24025. {
  24026. destBuffer.addEvent (midiData, numBytes,
  24027. jlimit (0, numSamples - 1, samplePosition + startSample));
  24028. }
  24029. }
  24030. incomingMessages.clear();
  24031. }
  24032. }
  24033. void MidiMessageCollector::handleNoteOn (MidiKeyboardState*, int midiChannel, int midiNoteNumber, float velocity)
  24034. {
  24035. MidiMessage m (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity));
  24036. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  24037. addMessageToQueue (m);
  24038. }
  24039. void MidiMessageCollector::handleNoteOff (MidiKeyboardState*, int midiChannel, int midiNoteNumber)
  24040. {
  24041. MidiMessage m (MidiMessage::noteOff (midiChannel, midiNoteNumber));
  24042. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  24043. addMessageToQueue (m);
  24044. }
  24045. void MidiMessageCollector::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  24046. {
  24047. addMessageToQueue (message);
  24048. }
  24049. END_JUCE_NAMESPACE
  24050. /*** End of inlined file: juce_MidiMessageCollector.cpp ***/
  24051. /*** Start of inlined file: juce_MidiMessageSequence.cpp ***/
  24052. BEGIN_JUCE_NAMESPACE
  24053. MidiMessageSequence::MidiMessageSequence()
  24054. {
  24055. }
  24056. MidiMessageSequence::MidiMessageSequence (const MidiMessageSequence& other)
  24057. {
  24058. list.ensureStorageAllocated (other.list.size());
  24059. for (int i = 0; i < other.list.size(); ++i)
  24060. list.add (new MidiEventHolder (other.list.getUnchecked(i)->message));
  24061. }
  24062. MidiMessageSequence& MidiMessageSequence::operator= (const MidiMessageSequence& other)
  24063. {
  24064. MidiMessageSequence otherCopy (other);
  24065. swapWith (otherCopy);
  24066. return *this;
  24067. }
  24068. void MidiMessageSequence::swapWith (MidiMessageSequence& other) throw()
  24069. {
  24070. list.swapWithArray (other.list);
  24071. }
  24072. MidiMessageSequence::~MidiMessageSequence()
  24073. {
  24074. }
  24075. void MidiMessageSequence::clear()
  24076. {
  24077. list.clear();
  24078. }
  24079. int MidiMessageSequence::getNumEvents() const
  24080. {
  24081. return list.size();
  24082. }
  24083. MidiMessageSequence::MidiEventHolder* MidiMessageSequence::getEventPointer (const int index) const
  24084. {
  24085. return list [index];
  24086. }
  24087. double MidiMessageSequence::getTimeOfMatchingKeyUp (const int index) const
  24088. {
  24089. const MidiEventHolder* const meh = list [index];
  24090. if (meh != 0 && meh->noteOffObject != 0)
  24091. return meh->noteOffObject->message.getTimeStamp();
  24092. else
  24093. return 0.0;
  24094. }
  24095. int MidiMessageSequence::getIndexOfMatchingKeyUp (const int index) const
  24096. {
  24097. const MidiEventHolder* const meh = list [index];
  24098. return (meh != 0) ? list.indexOf (meh->noteOffObject) : -1;
  24099. }
  24100. int MidiMessageSequence::getIndexOf (MidiEventHolder* const event) const
  24101. {
  24102. return list.indexOf (event);
  24103. }
  24104. int MidiMessageSequence::getNextIndexAtTime (const double timeStamp) const
  24105. {
  24106. const int numEvents = list.size();
  24107. int i;
  24108. for (i = 0; i < numEvents; ++i)
  24109. if (list.getUnchecked(i)->message.getTimeStamp() >= timeStamp)
  24110. break;
  24111. return i;
  24112. }
  24113. double MidiMessageSequence::getStartTime() const
  24114. {
  24115. if (list.size() > 0)
  24116. return list.getUnchecked(0)->message.getTimeStamp();
  24117. else
  24118. return 0;
  24119. }
  24120. double MidiMessageSequence::getEndTime() const
  24121. {
  24122. if (list.size() > 0)
  24123. return list.getLast()->message.getTimeStamp();
  24124. else
  24125. return 0;
  24126. }
  24127. double MidiMessageSequence::getEventTime (const int index) const
  24128. {
  24129. if (((unsigned int) index) < (unsigned int) list.size())
  24130. return list.getUnchecked (index)->message.getTimeStamp();
  24131. return 0.0;
  24132. }
  24133. void MidiMessageSequence::addEvent (const MidiMessage& newMessage,
  24134. double timeAdjustment)
  24135. {
  24136. MidiEventHolder* const newOne = new MidiEventHolder (newMessage);
  24137. timeAdjustment += newMessage.getTimeStamp();
  24138. newOne->message.setTimeStamp (timeAdjustment);
  24139. int i;
  24140. for (i = list.size(); --i >= 0;)
  24141. if (list.getUnchecked(i)->message.getTimeStamp() <= timeAdjustment)
  24142. break;
  24143. list.insert (i + 1, newOne);
  24144. }
  24145. void MidiMessageSequence::deleteEvent (const int index,
  24146. const bool deleteMatchingNoteUp)
  24147. {
  24148. if (((unsigned int) index) < (unsigned int) list.size())
  24149. {
  24150. if (deleteMatchingNoteUp)
  24151. deleteEvent (getIndexOfMatchingKeyUp (index), false);
  24152. list.remove (index);
  24153. }
  24154. }
  24155. void MidiMessageSequence::addSequence (const MidiMessageSequence& other,
  24156. double timeAdjustment,
  24157. double firstAllowableTime,
  24158. double endOfAllowableDestTimes)
  24159. {
  24160. firstAllowableTime -= timeAdjustment;
  24161. endOfAllowableDestTimes -= timeAdjustment;
  24162. for (int i = 0; i < other.list.size(); ++i)
  24163. {
  24164. const MidiMessage& m = other.list.getUnchecked(i)->message;
  24165. const double t = m.getTimeStamp();
  24166. if (t >= firstAllowableTime && t < endOfAllowableDestTimes)
  24167. {
  24168. MidiEventHolder* const newOne = new MidiEventHolder (m);
  24169. newOne->message.setTimeStamp (timeAdjustment + t);
  24170. list.add (newOne);
  24171. }
  24172. }
  24173. sort();
  24174. }
  24175. int MidiMessageSequence::compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  24176. const MidiMessageSequence::MidiEventHolder* const second) throw()
  24177. {
  24178. const double diff = first->message.getTimeStamp()
  24179. - second->message.getTimeStamp();
  24180. return (diff > 0) - (diff < 0);
  24181. }
  24182. void MidiMessageSequence::sort()
  24183. {
  24184. list.sort (*this, true);
  24185. }
  24186. void MidiMessageSequence::updateMatchedPairs()
  24187. {
  24188. for (int i = 0; i < list.size(); ++i)
  24189. {
  24190. const MidiMessage& m1 = list.getUnchecked(i)->message;
  24191. if (m1.isNoteOn())
  24192. {
  24193. list.getUnchecked(i)->noteOffObject = 0;
  24194. const int note = m1.getNoteNumber();
  24195. const int chan = m1.getChannel();
  24196. const int len = list.size();
  24197. for (int j = i + 1; j < len; ++j)
  24198. {
  24199. const MidiMessage& m = list.getUnchecked(j)->message;
  24200. if (m.getNoteNumber() == note && m.getChannel() == chan)
  24201. {
  24202. if (m.isNoteOff())
  24203. {
  24204. list.getUnchecked(i)->noteOffObject = list[j];
  24205. break;
  24206. }
  24207. else if (m.isNoteOn())
  24208. {
  24209. list.insert (j, new MidiEventHolder (MidiMessage::noteOff (chan, note)));
  24210. list.getUnchecked(j)->message.setTimeStamp (m.getTimeStamp());
  24211. list.getUnchecked(i)->noteOffObject = list[j];
  24212. break;
  24213. }
  24214. }
  24215. }
  24216. }
  24217. }
  24218. }
  24219. void MidiMessageSequence::addTimeToMessages (const double delta)
  24220. {
  24221. for (int i = list.size(); --i >= 0;)
  24222. list.getUnchecked (i)->message.setTimeStamp (list.getUnchecked (i)->message.getTimeStamp()
  24223. + delta);
  24224. }
  24225. void MidiMessageSequence::extractMidiChannelMessages (const int channelNumberToExtract,
  24226. MidiMessageSequence& destSequence,
  24227. const bool alsoIncludeMetaEvents) const
  24228. {
  24229. for (int i = 0; i < list.size(); ++i)
  24230. {
  24231. const MidiMessage& mm = list.getUnchecked(i)->message;
  24232. if (mm.isForChannel (channelNumberToExtract)
  24233. || (alsoIncludeMetaEvents && mm.isMetaEvent()))
  24234. {
  24235. destSequence.addEvent (mm);
  24236. }
  24237. }
  24238. }
  24239. void MidiMessageSequence::extractSysExMessages (MidiMessageSequence& destSequence) const
  24240. {
  24241. for (int i = 0; i < list.size(); ++i)
  24242. {
  24243. const MidiMessage& mm = list.getUnchecked(i)->message;
  24244. if (mm.isSysEx())
  24245. destSequence.addEvent (mm);
  24246. }
  24247. }
  24248. void MidiMessageSequence::deleteMidiChannelMessages (const int channelNumberToRemove)
  24249. {
  24250. for (int i = list.size(); --i >= 0;)
  24251. if (list.getUnchecked(i)->message.isForChannel (channelNumberToRemove))
  24252. list.remove(i);
  24253. }
  24254. void MidiMessageSequence::deleteSysExMessages()
  24255. {
  24256. for (int i = list.size(); --i >= 0;)
  24257. if (list.getUnchecked(i)->message.isSysEx())
  24258. list.remove(i);
  24259. }
  24260. void MidiMessageSequence::createControllerUpdatesForTime (const int channelNumber,
  24261. const double time,
  24262. OwnedArray<MidiMessage>& dest)
  24263. {
  24264. bool doneProg = false;
  24265. bool donePitchWheel = false;
  24266. Array <int> doneControllers;
  24267. doneControllers.ensureStorageAllocated (32);
  24268. for (int i = list.size(); --i >= 0;)
  24269. {
  24270. const MidiMessage& mm = list.getUnchecked(i)->message;
  24271. if (mm.isForChannel (channelNumber)
  24272. && mm.getTimeStamp() <= time)
  24273. {
  24274. if (mm.isProgramChange())
  24275. {
  24276. if (! doneProg)
  24277. {
  24278. dest.add (new MidiMessage (mm, 0.0));
  24279. doneProg = true;
  24280. }
  24281. }
  24282. else if (mm.isController())
  24283. {
  24284. if (! doneControllers.contains (mm.getControllerNumber()))
  24285. {
  24286. dest.add (new MidiMessage (mm, 0.0));
  24287. doneControllers.add (mm.getControllerNumber());
  24288. }
  24289. }
  24290. else if (mm.isPitchWheel())
  24291. {
  24292. if (! donePitchWheel)
  24293. {
  24294. dest.add (new MidiMessage (mm, 0.0));
  24295. donePitchWheel = true;
  24296. }
  24297. }
  24298. }
  24299. }
  24300. }
  24301. MidiMessageSequence::MidiEventHolder::MidiEventHolder (const MidiMessage& message_)
  24302. : message (message_),
  24303. noteOffObject (0)
  24304. {
  24305. }
  24306. MidiMessageSequence::MidiEventHolder::~MidiEventHolder()
  24307. {
  24308. }
  24309. END_JUCE_NAMESPACE
  24310. /*** End of inlined file: juce_MidiMessageSequence.cpp ***/
  24311. /*** Start of inlined file: juce_AudioPluginFormat.cpp ***/
  24312. BEGIN_JUCE_NAMESPACE
  24313. AudioPluginFormat::AudioPluginFormat() throw()
  24314. {
  24315. }
  24316. AudioPluginFormat::~AudioPluginFormat()
  24317. {
  24318. }
  24319. END_JUCE_NAMESPACE
  24320. /*** End of inlined file: juce_AudioPluginFormat.cpp ***/
  24321. /*** Start of inlined file: juce_AudioPluginFormatManager.cpp ***/
  24322. BEGIN_JUCE_NAMESPACE
  24323. AudioPluginFormatManager::AudioPluginFormatManager()
  24324. {
  24325. }
  24326. AudioPluginFormatManager::~AudioPluginFormatManager()
  24327. {
  24328. clearSingletonInstance();
  24329. }
  24330. juce_ImplementSingleton_SingleThreaded (AudioPluginFormatManager);
  24331. void AudioPluginFormatManager::addDefaultFormats()
  24332. {
  24333. #if JUCE_DEBUG
  24334. // you should only call this method once!
  24335. for (int i = formats.size(); --i >= 0;)
  24336. {
  24337. #if JUCE_PLUGINHOST_VST && ! (JUCE_MAC && JUCE_64BIT)
  24338. jassert (dynamic_cast <VSTPluginFormat*> (formats[i]) == 0);
  24339. #endif
  24340. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  24341. jassert (dynamic_cast <AudioUnitPluginFormat*> (formats[i]) == 0);
  24342. #endif
  24343. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  24344. jassert (dynamic_cast <DirectXPluginFormat*> (formats[i]) == 0);
  24345. #endif
  24346. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  24347. jassert (dynamic_cast <LADSPAPluginFormat*> (formats[i]) == 0);
  24348. #endif
  24349. }
  24350. #endif
  24351. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  24352. formats.add (new AudioUnitPluginFormat());
  24353. #endif
  24354. #if JUCE_PLUGINHOST_VST && ! (JUCE_MAC && JUCE_64BIT)
  24355. formats.add (new VSTPluginFormat());
  24356. #endif
  24357. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  24358. formats.add (new DirectXPluginFormat());
  24359. #endif
  24360. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  24361. formats.add (new LADSPAPluginFormat());
  24362. #endif
  24363. }
  24364. int AudioPluginFormatManager::getNumFormats()
  24365. {
  24366. return formats.size();
  24367. }
  24368. AudioPluginFormat* AudioPluginFormatManager::getFormat (const int index)
  24369. {
  24370. return formats [index];
  24371. }
  24372. void AudioPluginFormatManager::addFormat (AudioPluginFormat* const format)
  24373. {
  24374. formats.add (format);
  24375. }
  24376. AudioPluginInstance* AudioPluginFormatManager::createPluginInstance (const PluginDescription& description,
  24377. String& errorMessage) const
  24378. {
  24379. AudioPluginInstance* result = 0;
  24380. for (int i = 0; i < formats.size(); ++i)
  24381. {
  24382. result = formats.getUnchecked(i)->createInstanceFromDescription (description);
  24383. if (result != 0)
  24384. break;
  24385. }
  24386. if (result == 0)
  24387. {
  24388. if (! doesPluginStillExist (description))
  24389. errorMessage = TRANS ("This plug-in file no longer exists");
  24390. else
  24391. errorMessage = TRANS ("This plug-in failed to load correctly");
  24392. }
  24393. return result;
  24394. }
  24395. bool AudioPluginFormatManager::doesPluginStillExist (const PluginDescription& description) const
  24396. {
  24397. for (int i = 0; i < formats.size(); ++i)
  24398. if (formats.getUnchecked(i)->getName() == description.pluginFormatName)
  24399. return formats.getUnchecked(i)->doesPluginStillExist (description);
  24400. return false;
  24401. }
  24402. END_JUCE_NAMESPACE
  24403. /*** End of inlined file: juce_AudioPluginFormatManager.cpp ***/
  24404. /*** Start of inlined file: juce_AudioPluginInstance.cpp ***/
  24405. #define JUCE_PLUGIN_HOST 1
  24406. BEGIN_JUCE_NAMESPACE
  24407. AudioPluginInstance::AudioPluginInstance()
  24408. {
  24409. }
  24410. AudioPluginInstance::~AudioPluginInstance()
  24411. {
  24412. }
  24413. END_JUCE_NAMESPACE
  24414. /*** End of inlined file: juce_AudioPluginInstance.cpp ***/
  24415. /*** Start of inlined file: juce_KnownPluginList.cpp ***/
  24416. BEGIN_JUCE_NAMESPACE
  24417. KnownPluginList::KnownPluginList()
  24418. {
  24419. }
  24420. KnownPluginList::~KnownPluginList()
  24421. {
  24422. }
  24423. void KnownPluginList::clear()
  24424. {
  24425. if (types.size() > 0)
  24426. {
  24427. types.clear();
  24428. sendChangeMessage (this);
  24429. }
  24430. }
  24431. PluginDescription* KnownPluginList::getTypeForFile (const String& fileOrIdentifier) const
  24432. {
  24433. for (int i = 0; i < types.size(); ++i)
  24434. if (types.getUnchecked(i)->fileOrIdentifier == fileOrIdentifier)
  24435. return types.getUnchecked(i);
  24436. return 0;
  24437. }
  24438. PluginDescription* KnownPluginList::getTypeForIdentifierString (const String& identifierString) const
  24439. {
  24440. for (int i = 0; i < types.size(); ++i)
  24441. if (types.getUnchecked(i)->createIdentifierString() == identifierString)
  24442. return types.getUnchecked(i);
  24443. return 0;
  24444. }
  24445. bool KnownPluginList::addType (const PluginDescription& type)
  24446. {
  24447. for (int i = types.size(); --i >= 0;)
  24448. {
  24449. if (types.getUnchecked(i)->isDuplicateOf (type))
  24450. {
  24451. // strange - found a duplicate plugin with different info..
  24452. jassert (types.getUnchecked(i)->name == type.name);
  24453. jassert (types.getUnchecked(i)->isInstrument == type.isInstrument);
  24454. *types.getUnchecked(i) = type;
  24455. return false;
  24456. }
  24457. }
  24458. types.add (new PluginDescription (type));
  24459. sendChangeMessage (this);
  24460. return true;
  24461. }
  24462. void KnownPluginList::removeType (const int index)
  24463. {
  24464. types.remove (index);
  24465. sendChangeMessage (this);
  24466. }
  24467. namespace
  24468. {
  24469. const Time getPluginFileModTime (const String& fileOrIdentifier)
  24470. {
  24471. if (fileOrIdentifier.startsWithChar ('/') || fileOrIdentifier[1] == ':')
  24472. return File (fileOrIdentifier).getLastModificationTime();
  24473. return Time (0);
  24474. }
  24475. bool timesAreDifferent (const Time& t1, const Time& t2) throw()
  24476. {
  24477. return t1 != t2 || t1 == Time (0);
  24478. }
  24479. }
  24480. bool KnownPluginList::isListingUpToDate (const String& fileOrIdentifier) const
  24481. {
  24482. if (getTypeForFile (fileOrIdentifier) == 0)
  24483. return false;
  24484. for (int i = types.size(); --i >= 0;)
  24485. {
  24486. const PluginDescription* const d = types.getUnchecked(i);
  24487. if (d->fileOrIdentifier == fileOrIdentifier
  24488. && timesAreDifferent (d->lastFileModTime, getPluginFileModTime (fileOrIdentifier)))
  24489. {
  24490. return false;
  24491. }
  24492. }
  24493. return true;
  24494. }
  24495. bool KnownPluginList::scanAndAddFile (const String& fileOrIdentifier,
  24496. const bool dontRescanIfAlreadyInList,
  24497. OwnedArray <PluginDescription>& typesFound,
  24498. AudioPluginFormat& format)
  24499. {
  24500. bool addedOne = false;
  24501. if (dontRescanIfAlreadyInList
  24502. && getTypeForFile (fileOrIdentifier) != 0)
  24503. {
  24504. bool needsRescanning = false;
  24505. for (int i = types.size(); --i >= 0;)
  24506. {
  24507. const PluginDescription* const d = types.getUnchecked(i);
  24508. if (d->fileOrIdentifier == fileOrIdentifier)
  24509. {
  24510. if (timesAreDifferent (d->lastFileModTime, getPluginFileModTime (fileOrIdentifier)))
  24511. needsRescanning = true;
  24512. else
  24513. typesFound.add (new PluginDescription (*d));
  24514. }
  24515. }
  24516. if (! needsRescanning)
  24517. return false;
  24518. }
  24519. OwnedArray <PluginDescription> found;
  24520. format.findAllTypesForFile (found, fileOrIdentifier);
  24521. for (int i = 0; i < found.size(); ++i)
  24522. {
  24523. PluginDescription* const desc = found.getUnchecked(i);
  24524. jassert (desc != 0);
  24525. if (addType (*desc))
  24526. addedOne = true;
  24527. typesFound.add (new PluginDescription (*desc));
  24528. }
  24529. return addedOne;
  24530. }
  24531. void KnownPluginList::scanAndAddDragAndDroppedFiles (const StringArray& files,
  24532. OwnedArray <PluginDescription>& typesFound)
  24533. {
  24534. for (int i = 0; i < files.size(); ++i)
  24535. {
  24536. bool loaded = false;
  24537. for (int j = 0; j < AudioPluginFormatManager::getInstance()->getNumFormats(); ++j)
  24538. {
  24539. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (j);
  24540. if (scanAndAddFile (files[i], true, typesFound, *format))
  24541. loaded = true;
  24542. }
  24543. if (! loaded)
  24544. {
  24545. const File f (files[i]);
  24546. if (f.isDirectory())
  24547. {
  24548. StringArray s;
  24549. {
  24550. Array<File> subFiles;
  24551. f.findChildFiles (subFiles, File::findFilesAndDirectories, false);
  24552. for (int j = 0; j < subFiles.size(); ++j)
  24553. s.add (subFiles.getReference(j).getFullPathName());
  24554. }
  24555. scanAndAddDragAndDroppedFiles (s, typesFound);
  24556. }
  24557. }
  24558. }
  24559. }
  24560. class PluginSorter
  24561. {
  24562. public:
  24563. KnownPluginList::SortMethod method;
  24564. PluginSorter() throw() {}
  24565. int compareElements (const PluginDescription* const first,
  24566. const PluginDescription* const second) const
  24567. {
  24568. int diff = 0;
  24569. if (method == KnownPluginList::sortByCategory)
  24570. diff = first->category.compareLexicographically (second->category);
  24571. else if (method == KnownPluginList::sortByManufacturer)
  24572. diff = first->manufacturerName.compareLexicographically (second->manufacturerName);
  24573. else if (method == KnownPluginList::sortByFileSystemLocation)
  24574. diff = first->fileOrIdentifier.replaceCharacter ('\\', '/')
  24575. .upToLastOccurrenceOf ("/", false, false)
  24576. .compare (second->fileOrIdentifier.replaceCharacter ('\\', '/')
  24577. .upToLastOccurrenceOf ("/", false, false));
  24578. if (diff == 0)
  24579. diff = first->name.compareLexicographically (second->name);
  24580. return diff;
  24581. }
  24582. };
  24583. void KnownPluginList::sort (const SortMethod method)
  24584. {
  24585. if (method != defaultOrder)
  24586. {
  24587. PluginSorter sorter;
  24588. sorter.method = method;
  24589. types.sort (sorter, true);
  24590. sendChangeMessage (this);
  24591. }
  24592. }
  24593. XmlElement* KnownPluginList::createXml() const
  24594. {
  24595. XmlElement* const e = new XmlElement ("KNOWNPLUGINS");
  24596. for (int i = 0; i < types.size(); ++i)
  24597. e->addChildElement (types.getUnchecked(i)->createXml());
  24598. return e;
  24599. }
  24600. void KnownPluginList::recreateFromXml (const XmlElement& xml)
  24601. {
  24602. clear();
  24603. if (xml.hasTagName ("KNOWNPLUGINS"))
  24604. {
  24605. forEachXmlChildElement (xml, e)
  24606. {
  24607. PluginDescription info;
  24608. if (info.loadFromXml (*e))
  24609. addType (info);
  24610. }
  24611. }
  24612. }
  24613. const int menuIdBase = 0x324503f4;
  24614. // This is used to turn a bunch of paths into a nested menu structure.
  24615. struct PluginFilesystemTree
  24616. {
  24617. private:
  24618. String folder;
  24619. OwnedArray <PluginFilesystemTree> subFolders;
  24620. Array <PluginDescription*> plugins;
  24621. void addPlugin (PluginDescription* const pd, const String& path)
  24622. {
  24623. if (path.isEmpty())
  24624. {
  24625. plugins.add (pd);
  24626. }
  24627. else
  24628. {
  24629. const String firstSubFolder (path.upToFirstOccurrenceOf ("/", false, false));
  24630. const String remainingPath (path.fromFirstOccurrenceOf ("/", false, false));
  24631. for (int i = subFolders.size(); --i >= 0;)
  24632. {
  24633. if (subFolders.getUnchecked(i)->folder.equalsIgnoreCase (firstSubFolder))
  24634. {
  24635. subFolders.getUnchecked(i)->addPlugin (pd, remainingPath);
  24636. return;
  24637. }
  24638. }
  24639. PluginFilesystemTree* const newFolder = new PluginFilesystemTree();
  24640. newFolder->folder = firstSubFolder;
  24641. subFolders.add (newFolder);
  24642. newFolder->addPlugin (pd, remainingPath);
  24643. }
  24644. }
  24645. // removes any deeply nested folders that don't contain any actual plugins
  24646. void optimise()
  24647. {
  24648. for (int i = subFolders.size(); --i >= 0;)
  24649. {
  24650. PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  24651. sub->optimise();
  24652. if (sub->plugins.size() == 0)
  24653. {
  24654. for (int j = 0; j < sub->subFolders.size(); ++j)
  24655. subFolders.add (sub->subFolders.getUnchecked(j));
  24656. sub->subFolders.clear (false);
  24657. subFolders.remove (i);
  24658. }
  24659. }
  24660. }
  24661. public:
  24662. void buildTree (const Array <PluginDescription*>& allPlugins)
  24663. {
  24664. for (int i = 0; i < allPlugins.size(); ++i)
  24665. {
  24666. String path (allPlugins.getUnchecked(i)
  24667. ->fileOrIdentifier.replaceCharacter ('\\', '/')
  24668. .upToLastOccurrenceOf ("/", false, false));
  24669. if (path.substring (1, 2) == ":")
  24670. path = path.substring (2);
  24671. addPlugin (allPlugins.getUnchecked(i), path);
  24672. }
  24673. optimise();
  24674. }
  24675. void addToMenu (PopupMenu& m, const OwnedArray <PluginDescription>& allPlugins) const
  24676. {
  24677. int i;
  24678. for (i = 0; i < subFolders.size(); ++i)
  24679. {
  24680. const PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  24681. PopupMenu subMenu;
  24682. sub->addToMenu (subMenu, allPlugins);
  24683. #if JUCE_MAC
  24684. // avoid the special AU formatting nonsense on Mac..
  24685. m.addSubMenu (sub->folder.fromFirstOccurrenceOf (":", false, false), subMenu);
  24686. #else
  24687. m.addSubMenu (sub->folder, subMenu);
  24688. #endif
  24689. }
  24690. for (i = 0; i < plugins.size(); ++i)
  24691. {
  24692. PluginDescription* const plugin = plugins.getUnchecked(i);
  24693. m.addItem (allPlugins.indexOf (plugin) + menuIdBase,
  24694. plugin->name, true, false);
  24695. }
  24696. }
  24697. };
  24698. void KnownPluginList::addToMenu (PopupMenu& menu, const SortMethod sortMethod) const
  24699. {
  24700. Array <PluginDescription*> sorted;
  24701. {
  24702. PluginSorter sorter;
  24703. sorter.method = sortMethod;
  24704. for (int i = 0; i < types.size(); ++i)
  24705. sorted.addSorted (sorter, types.getUnchecked(i));
  24706. }
  24707. if (sortMethod == sortByCategory
  24708. || sortMethod == sortByManufacturer)
  24709. {
  24710. String lastSubMenuName;
  24711. PopupMenu sub;
  24712. for (int i = 0; i < sorted.size(); ++i)
  24713. {
  24714. const PluginDescription* const pd = sorted.getUnchecked(i);
  24715. String thisSubMenuName (sortMethod == sortByCategory ? pd->category
  24716. : pd->manufacturerName);
  24717. if (! thisSubMenuName.containsNonWhitespaceChars())
  24718. thisSubMenuName = "Other";
  24719. if (thisSubMenuName != lastSubMenuName)
  24720. {
  24721. if (sub.getNumItems() > 0)
  24722. {
  24723. menu.addSubMenu (lastSubMenuName, sub);
  24724. sub.clear();
  24725. }
  24726. lastSubMenuName = thisSubMenuName;
  24727. }
  24728. sub.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  24729. }
  24730. if (sub.getNumItems() > 0)
  24731. menu.addSubMenu (lastSubMenuName, sub);
  24732. }
  24733. else if (sortMethod == sortByFileSystemLocation)
  24734. {
  24735. PluginFilesystemTree root;
  24736. root.buildTree (sorted);
  24737. root.addToMenu (menu, types);
  24738. }
  24739. else
  24740. {
  24741. for (int i = 0; i < sorted.size(); ++i)
  24742. {
  24743. const PluginDescription* const pd = sorted.getUnchecked(i);
  24744. menu.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  24745. }
  24746. }
  24747. }
  24748. int KnownPluginList::getIndexChosenByMenu (const int menuResultCode) const
  24749. {
  24750. const int i = menuResultCode - menuIdBase;
  24751. return (((unsigned int) i) < (unsigned int) types.size()) ? i : -1;
  24752. }
  24753. END_JUCE_NAMESPACE
  24754. /*** End of inlined file: juce_KnownPluginList.cpp ***/
  24755. /*** Start of inlined file: juce_PluginDescription.cpp ***/
  24756. BEGIN_JUCE_NAMESPACE
  24757. PluginDescription::PluginDescription()
  24758. : uid (0),
  24759. isInstrument (false),
  24760. numInputChannels (0),
  24761. numOutputChannels (0)
  24762. {
  24763. }
  24764. PluginDescription::~PluginDescription()
  24765. {
  24766. }
  24767. PluginDescription::PluginDescription (const PluginDescription& other)
  24768. : name (other.name),
  24769. pluginFormatName (other.pluginFormatName),
  24770. category (other.category),
  24771. manufacturerName (other.manufacturerName),
  24772. version (other.version),
  24773. fileOrIdentifier (other.fileOrIdentifier),
  24774. lastFileModTime (other.lastFileModTime),
  24775. uid (other.uid),
  24776. isInstrument (other.isInstrument),
  24777. numInputChannels (other.numInputChannels),
  24778. numOutputChannels (other.numOutputChannels)
  24779. {
  24780. }
  24781. PluginDescription& PluginDescription::operator= (const PluginDescription& other)
  24782. {
  24783. name = other.name;
  24784. pluginFormatName = other.pluginFormatName;
  24785. category = other.category;
  24786. manufacturerName = other.manufacturerName;
  24787. version = other.version;
  24788. fileOrIdentifier = other.fileOrIdentifier;
  24789. uid = other.uid;
  24790. isInstrument = other.isInstrument;
  24791. lastFileModTime = other.lastFileModTime;
  24792. numInputChannels = other.numInputChannels;
  24793. numOutputChannels = other.numOutputChannels;
  24794. return *this;
  24795. }
  24796. bool PluginDescription::isDuplicateOf (const PluginDescription& other) const
  24797. {
  24798. return fileOrIdentifier == other.fileOrIdentifier
  24799. && uid == other.uid;
  24800. }
  24801. const String PluginDescription::createIdentifierString() const
  24802. {
  24803. return pluginFormatName
  24804. + "-" + name
  24805. + "-" + String::toHexString (fileOrIdentifier.hashCode())
  24806. + "-" + String::toHexString (uid);
  24807. }
  24808. XmlElement* PluginDescription::createXml() const
  24809. {
  24810. XmlElement* const e = new XmlElement ("PLUGIN");
  24811. e->setAttribute ("name", name);
  24812. e->setAttribute ("format", pluginFormatName);
  24813. e->setAttribute ("category", category);
  24814. e->setAttribute ("manufacturer", manufacturerName);
  24815. e->setAttribute ("version", version);
  24816. e->setAttribute ("file", fileOrIdentifier);
  24817. e->setAttribute ("uid", String::toHexString (uid));
  24818. e->setAttribute ("isInstrument", isInstrument);
  24819. e->setAttribute ("fileTime", String::toHexString (lastFileModTime.toMilliseconds()));
  24820. e->setAttribute ("numInputs", numInputChannels);
  24821. e->setAttribute ("numOutputs", numOutputChannels);
  24822. return e;
  24823. }
  24824. bool PluginDescription::loadFromXml (const XmlElement& xml)
  24825. {
  24826. if (xml.hasTagName ("PLUGIN"))
  24827. {
  24828. name = xml.getStringAttribute ("name");
  24829. pluginFormatName = xml.getStringAttribute ("format");
  24830. category = xml.getStringAttribute ("category");
  24831. manufacturerName = xml.getStringAttribute ("manufacturer");
  24832. version = xml.getStringAttribute ("version");
  24833. fileOrIdentifier = xml.getStringAttribute ("file");
  24834. uid = xml.getStringAttribute ("uid").getHexValue32();
  24835. isInstrument = xml.getBoolAttribute ("isInstrument", false);
  24836. lastFileModTime = Time (xml.getStringAttribute ("fileTime").getHexValue64());
  24837. numInputChannels = xml.getIntAttribute ("numInputs");
  24838. numOutputChannels = xml.getIntAttribute ("numOutputs");
  24839. return true;
  24840. }
  24841. return false;
  24842. }
  24843. END_JUCE_NAMESPACE
  24844. /*** End of inlined file: juce_PluginDescription.cpp ***/
  24845. /*** Start of inlined file: juce_PluginDirectoryScanner.cpp ***/
  24846. BEGIN_JUCE_NAMESPACE
  24847. PluginDirectoryScanner::PluginDirectoryScanner (KnownPluginList& listToAddTo,
  24848. AudioPluginFormat& formatToLookFor,
  24849. FileSearchPath directoriesToSearch,
  24850. const bool recursive,
  24851. const File& deadMansPedalFile_)
  24852. : list (listToAddTo),
  24853. format (formatToLookFor),
  24854. deadMansPedalFile (deadMansPedalFile_),
  24855. nextIndex (0),
  24856. progress (0)
  24857. {
  24858. directoriesToSearch.removeRedundantPaths();
  24859. filesOrIdentifiersToScan = format.searchPathsForPlugins (directoriesToSearch, recursive);
  24860. // If any plugins have crashed recently when being loaded, move them to the
  24861. // end of the list to give the others a chance to load correctly..
  24862. const StringArray crashedPlugins (getDeadMansPedalFile());
  24863. for (int i = 0; i < crashedPlugins.size(); ++i)
  24864. {
  24865. const String f = crashedPlugins[i];
  24866. for (int j = filesOrIdentifiersToScan.size(); --j >= 0;)
  24867. if (f == filesOrIdentifiersToScan[j])
  24868. filesOrIdentifiersToScan.move (j, -1);
  24869. }
  24870. }
  24871. PluginDirectoryScanner::~PluginDirectoryScanner()
  24872. {
  24873. }
  24874. const String PluginDirectoryScanner::getNextPluginFileThatWillBeScanned() const
  24875. {
  24876. return format.getNameOfPluginFromIdentifier (filesOrIdentifiersToScan [nextIndex]);
  24877. }
  24878. bool PluginDirectoryScanner::scanNextFile (const bool dontRescanIfAlreadyInList)
  24879. {
  24880. String file (filesOrIdentifiersToScan [nextIndex]);
  24881. if (file.isNotEmpty() && ! list.isListingUpToDate (file))
  24882. {
  24883. OwnedArray <PluginDescription> typesFound;
  24884. // Add this plugin to the end of the dead-man's pedal list in case it crashes...
  24885. StringArray crashedPlugins (getDeadMansPedalFile());
  24886. crashedPlugins.removeString (file);
  24887. crashedPlugins.add (file);
  24888. setDeadMansPedalFile (crashedPlugins);
  24889. list.scanAndAddFile (file,
  24890. dontRescanIfAlreadyInList,
  24891. typesFound,
  24892. format);
  24893. // Managed to load without crashing, so remove it from the dead-man's-pedal..
  24894. crashedPlugins.removeString (file);
  24895. setDeadMansPedalFile (crashedPlugins);
  24896. if (typesFound.size() == 0)
  24897. failedFiles.add (file);
  24898. }
  24899. return skipNextFile();
  24900. }
  24901. bool PluginDirectoryScanner::skipNextFile()
  24902. {
  24903. if (nextIndex >= filesOrIdentifiersToScan.size())
  24904. return false;
  24905. progress = ++nextIndex / (float) filesOrIdentifiersToScan.size();
  24906. return nextIndex < filesOrIdentifiersToScan.size();
  24907. }
  24908. const StringArray PluginDirectoryScanner::getDeadMansPedalFile()
  24909. {
  24910. StringArray lines;
  24911. if (deadMansPedalFile != File::nonexistent)
  24912. {
  24913. lines.addLines (deadMansPedalFile.loadFileAsString());
  24914. lines.removeEmptyStrings();
  24915. }
  24916. return lines;
  24917. }
  24918. void PluginDirectoryScanner::setDeadMansPedalFile (const StringArray& newContents)
  24919. {
  24920. if (deadMansPedalFile != File::nonexistent)
  24921. deadMansPedalFile.replaceWithText (newContents.joinIntoString ("\n"), true, true);
  24922. }
  24923. END_JUCE_NAMESPACE
  24924. /*** End of inlined file: juce_PluginDirectoryScanner.cpp ***/
  24925. /*** Start of inlined file: juce_PluginListComponent.cpp ***/
  24926. BEGIN_JUCE_NAMESPACE
  24927. PluginListComponent::PluginListComponent (KnownPluginList& listToEdit,
  24928. const File& deadMansPedalFile_,
  24929. PropertiesFile* const propertiesToUse_)
  24930. : list (listToEdit),
  24931. deadMansPedalFile (deadMansPedalFile_),
  24932. optionsButton ("Options..."),
  24933. propertiesToUse (propertiesToUse_)
  24934. {
  24935. listBox.setModel (this);
  24936. addAndMakeVisible (&listBox);
  24937. addAndMakeVisible (&optionsButton);
  24938. optionsButton.addButtonListener (this);
  24939. optionsButton.setTriggeredOnMouseDown (true);
  24940. setSize (400, 600);
  24941. list.addChangeListener (this);
  24942. changeListenerCallback (0);
  24943. }
  24944. PluginListComponent::~PluginListComponent()
  24945. {
  24946. list.removeChangeListener (this);
  24947. }
  24948. void PluginListComponent::resized()
  24949. {
  24950. listBox.setBounds (0, 0, getWidth(), getHeight() - 30);
  24951. optionsButton.changeWidthToFitText (24);
  24952. optionsButton.setTopLeftPosition (8, getHeight() - 28);
  24953. }
  24954. void PluginListComponent::changeListenerCallback (void*)
  24955. {
  24956. listBox.updateContent();
  24957. listBox.repaint();
  24958. }
  24959. int PluginListComponent::getNumRows()
  24960. {
  24961. return list.getNumTypes();
  24962. }
  24963. void PluginListComponent::paintListBoxItem (int row,
  24964. Graphics& g,
  24965. int width, int height,
  24966. bool rowIsSelected)
  24967. {
  24968. if (rowIsSelected)
  24969. g.fillAll (findColour (TextEditor::highlightColourId));
  24970. const PluginDescription* const pd = list.getType (row);
  24971. if (pd != 0)
  24972. {
  24973. GlyphArrangement ga;
  24974. ga.addCurtailedLineOfText (Font (height * 0.7f, Font::bold), pd->name, 8.0f, height * 0.8f, width - 10.0f, true);
  24975. g.setColour (Colours::black);
  24976. ga.draw (g);
  24977. const Rectangle<float> bb (ga.getBoundingBox (0, -1, false));
  24978. String desc;
  24979. desc << pd->pluginFormatName
  24980. << (pd->isInstrument ? " instrument" : " effect")
  24981. << " - "
  24982. << pd->numInputChannels << (pd->numInputChannels == 1 ? " in" : " ins")
  24983. << " / "
  24984. << pd->numOutputChannels << (pd->numOutputChannels == 1 ? " out" : " outs");
  24985. if (pd->manufacturerName.isNotEmpty())
  24986. desc << " - " << pd->manufacturerName;
  24987. if (pd->version.isNotEmpty())
  24988. desc << " - " << pd->version;
  24989. if (pd->category.isNotEmpty())
  24990. desc << " - category: '" << pd->category << '\'';
  24991. g.setColour (Colours::grey);
  24992. ga.clear();
  24993. ga.addCurtailedLineOfText (Font (height * 0.6f), desc, bb.getRight() + 10.0f, height * 0.8f, width - bb.getRight() - 12.0f, true);
  24994. ga.draw (g);
  24995. }
  24996. }
  24997. void PluginListComponent::deleteKeyPressed (int lastRowSelected)
  24998. {
  24999. list.removeType (lastRowSelected);
  25000. }
  25001. void PluginListComponent::buttonClicked (Button* button)
  25002. {
  25003. if (button == &optionsButton)
  25004. {
  25005. PopupMenu menu;
  25006. menu.addItem (1, TRANS("Clear list"));
  25007. menu.addItem (5, TRANS("Remove selected plugin from list"), listBox.getNumSelectedRows() > 0);
  25008. menu.addItem (6, TRANS("Show folder containing selected plugin"), listBox.getNumSelectedRows() > 0);
  25009. menu.addItem (7, TRANS("Remove any plugins whose files no longer exist"));
  25010. menu.addSeparator();
  25011. menu.addItem (2, TRANS("Sort alphabetically"));
  25012. menu.addItem (3, TRANS("Sort by category"));
  25013. menu.addItem (4, TRANS("Sort by manufacturer"));
  25014. menu.addSeparator();
  25015. for (int i = 0; i < AudioPluginFormatManager::getInstance()->getNumFormats(); ++i)
  25016. {
  25017. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (i);
  25018. if (format->getDefaultLocationsToSearch().getNumPaths() > 0)
  25019. menu.addItem (10 + i, "Scan for new or updated " + format->getName() + " plugins...");
  25020. }
  25021. const int r = menu.showAt (&optionsButton);
  25022. if (r == 1)
  25023. {
  25024. list.clear();
  25025. }
  25026. else if (r == 2)
  25027. {
  25028. list.sort (KnownPluginList::sortAlphabetically);
  25029. }
  25030. else if (r == 3)
  25031. {
  25032. list.sort (KnownPluginList::sortByCategory);
  25033. }
  25034. else if (r == 4)
  25035. {
  25036. list.sort (KnownPluginList::sortByManufacturer);
  25037. }
  25038. else if (r == 5)
  25039. {
  25040. const SparseSet <int> selected (listBox.getSelectedRows());
  25041. for (int i = list.getNumTypes(); --i >= 0;)
  25042. if (selected.contains (i))
  25043. list.removeType (i);
  25044. }
  25045. else if (r == 6)
  25046. {
  25047. const PluginDescription* const desc = list.getType (listBox.getSelectedRow());
  25048. if (desc != 0)
  25049. {
  25050. if (File (desc->fileOrIdentifier).existsAsFile())
  25051. File (desc->fileOrIdentifier).getParentDirectory().startAsProcess();
  25052. }
  25053. }
  25054. else if (r == 7)
  25055. {
  25056. for (int i = list.getNumTypes(); --i >= 0;)
  25057. {
  25058. if (! AudioPluginFormatManager::getInstance()->doesPluginStillExist (*list.getType (i)))
  25059. {
  25060. list.removeType (i);
  25061. }
  25062. }
  25063. }
  25064. else if (r != 0)
  25065. {
  25066. typeToScan = r - 10;
  25067. startTimer (1);
  25068. }
  25069. }
  25070. }
  25071. void PluginListComponent::timerCallback()
  25072. {
  25073. stopTimer();
  25074. scanFor (AudioPluginFormatManager::getInstance()->getFormat (typeToScan));
  25075. }
  25076. bool PluginListComponent::isInterestedInFileDrag (const StringArray& /*files*/)
  25077. {
  25078. return true;
  25079. }
  25080. void PluginListComponent::filesDropped (const StringArray& files, int, int)
  25081. {
  25082. OwnedArray <PluginDescription> typesFound;
  25083. list.scanAndAddDragAndDroppedFiles (files, typesFound);
  25084. }
  25085. void PluginListComponent::scanFor (AudioPluginFormat* format)
  25086. {
  25087. if (format == 0)
  25088. return;
  25089. FileSearchPath path (format->getDefaultLocationsToSearch());
  25090. if (propertiesToUse != 0)
  25091. path = propertiesToUse->getValue ("lastPluginScanPath_" + format->getName(), path.toString());
  25092. {
  25093. AlertWindow aw (TRANS("Select folders to scan..."), String::empty, AlertWindow::NoIcon);
  25094. FileSearchPathListComponent pathList;
  25095. pathList.setSize (500, 300);
  25096. pathList.setPath (path);
  25097. aw.addCustomComponent (&pathList);
  25098. aw.addButton (TRANS("Scan"), 1, KeyPress::returnKey);
  25099. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  25100. if (aw.runModalLoop() == 0)
  25101. return;
  25102. path = pathList.getPath();
  25103. }
  25104. if (propertiesToUse != 0)
  25105. {
  25106. propertiesToUse->setValue ("lastPluginScanPath_" + format->getName(), path.toString());
  25107. propertiesToUse->saveIfNeeded();
  25108. }
  25109. double progress = 0.0;
  25110. AlertWindow aw (TRANS("Scanning for plugins..."),
  25111. TRANS("Searching for all possible plugin files..."), AlertWindow::NoIcon);
  25112. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  25113. aw.addProgressBarComponent (progress);
  25114. aw.enterModalState();
  25115. MessageManager::getInstance()->runDispatchLoopUntil (300);
  25116. PluginDirectoryScanner scanner (list, *format, path, true, deadMansPedalFile);
  25117. for (;;)
  25118. {
  25119. aw.setMessage (TRANS("Testing:\n\n")
  25120. + scanner.getNextPluginFileThatWillBeScanned());
  25121. MessageManager::getInstance()->runDispatchLoopUntil (20);
  25122. if (! scanner.scanNextFile (true))
  25123. break;
  25124. if (! aw.isCurrentlyModal())
  25125. break;
  25126. progress = scanner.getProgress();
  25127. }
  25128. if (scanner.getFailedFiles().size() > 0)
  25129. {
  25130. StringArray shortNames;
  25131. for (int i = 0; i < scanner.getFailedFiles().size(); ++i)
  25132. shortNames.add (File (scanner.getFailedFiles()[i]).getFileName());
  25133. AlertWindow::showMessageBox (AlertWindow::InfoIcon,
  25134. TRANS("Scan complete"),
  25135. TRANS("Note that the following files appeared to be plugin files, but failed to load correctly:\n\n")
  25136. + shortNames.joinIntoString (", "));
  25137. }
  25138. }
  25139. END_JUCE_NAMESPACE
  25140. /*** End of inlined file: juce_PluginListComponent.cpp ***/
  25141. /*** Start of inlined file: juce_AudioUnitPluginFormat.mm ***/
  25142. #if JUCE_PLUGINHOST_AU && ! (JUCE_LINUX || JUCE_WINDOWS)
  25143. #include <AudioUnit/AudioUnit.h>
  25144. #include <AudioUnit/AUCocoaUIView.h>
  25145. #include <CoreAudioKit/AUGenericView.h>
  25146. #if JUCE_SUPPORT_CARBON
  25147. #include <AudioToolbox/AudioUnitUtilities.h>
  25148. #include <AudioUnit/AudioUnitCarbonView.h>
  25149. #endif
  25150. BEGIN_JUCE_NAMESPACE
  25151. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  25152. #endif
  25153. #if JUCE_MAC
  25154. // Change this to disable logging of various activities
  25155. #ifndef AU_LOGGING
  25156. #define AU_LOGGING 1
  25157. #endif
  25158. #if AU_LOGGING
  25159. #define log(a) Logger::writeToLog(a);
  25160. #else
  25161. #define log(a)
  25162. #endif
  25163. namespace AudioUnitFormatHelpers
  25164. {
  25165. static int insideCallback = 0;
  25166. static const String osTypeToString (OSType type)
  25167. {
  25168. char s[4];
  25169. s[0] = (char) (((uint32) type) >> 24);
  25170. s[1] = (char) (((uint32) type) >> 16);
  25171. s[2] = (char) (((uint32) type) >> 8);
  25172. s[3] = (char) ((uint32) type);
  25173. return String (s, 4);
  25174. }
  25175. static OSType stringToOSType (const String& s1)
  25176. {
  25177. const String s (s1 + " ");
  25178. return (((OSType) (unsigned char) s[0]) << 24)
  25179. | (((OSType) (unsigned char) s[1]) << 16)
  25180. | (((OSType) (unsigned char) s[2]) << 8)
  25181. | ((OSType) (unsigned char) s[3]);
  25182. }
  25183. static const char* auIdentifierPrefix = "AudioUnit:";
  25184. static const String createAUPluginIdentifier (const ComponentDescription& desc)
  25185. {
  25186. jassert (osTypeToString ('abcd') == "abcd"); // agh, must have got the endianness wrong..
  25187. jassert (stringToOSType ("abcd") == (OSType) 'abcd'); // ditto
  25188. String s (auIdentifierPrefix);
  25189. if (desc.componentType == kAudioUnitType_MusicDevice)
  25190. s << "Synths/";
  25191. else if (desc.componentType == kAudioUnitType_MusicEffect
  25192. || desc.componentType == kAudioUnitType_Effect)
  25193. s << "Effects/";
  25194. else if (desc.componentType == kAudioUnitType_Generator)
  25195. s << "Generators/";
  25196. else if (desc.componentType == kAudioUnitType_Panner)
  25197. s << "Panners/";
  25198. s << osTypeToString (desc.componentType) << ","
  25199. << osTypeToString (desc.componentSubType) << ","
  25200. << osTypeToString (desc.componentManufacturer);
  25201. return s;
  25202. }
  25203. static void getAUDetails (ComponentRecord* comp, String& name, String& manufacturer)
  25204. {
  25205. Handle componentNameHandle = NewHandle (sizeof (void*));
  25206. Handle componentInfoHandle = NewHandle (sizeof (void*));
  25207. if (componentNameHandle != 0 && componentInfoHandle != 0)
  25208. {
  25209. ComponentDescription desc;
  25210. if (GetComponentInfo (comp, &desc, componentNameHandle, componentInfoHandle, 0) == noErr)
  25211. {
  25212. ConstStr255Param nameString = (ConstStr255Param) (*componentNameHandle);
  25213. ConstStr255Param infoString = (ConstStr255Param) (*componentInfoHandle);
  25214. if (nameString != 0 && nameString[0] != 0)
  25215. {
  25216. const String all ((const char*) nameString + 1, nameString[0]);
  25217. DBG ("name: "+ all);
  25218. manufacturer = all.upToFirstOccurrenceOf (":", false, false).trim();
  25219. name = all.fromFirstOccurrenceOf (":", false, false).trim();
  25220. }
  25221. if (infoString != 0 && infoString[0] != 0)
  25222. {
  25223. DBG ("info: " + String ((const char*) infoString + 1, infoString[0]));
  25224. }
  25225. if (name.isEmpty())
  25226. name = "<Unknown>";
  25227. }
  25228. DisposeHandle (componentNameHandle);
  25229. DisposeHandle (componentInfoHandle);
  25230. }
  25231. }
  25232. static bool getComponentDescFromIdentifier (const String& fileOrIdentifier, ComponentDescription& desc,
  25233. String& name, String& version, String& manufacturer)
  25234. {
  25235. zerostruct (desc);
  25236. if (fileOrIdentifier.startsWithIgnoreCase (auIdentifierPrefix))
  25237. {
  25238. String s (fileOrIdentifier.substring (jmax (fileOrIdentifier.lastIndexOfChar (':'),
  25239. fileOrIdentifier.lastIndexOfChar ('/')) + 1));
  25240. StringArray tokens;
  25241. tokens.addTokens (s, ",", String::empty);
  25242. tokens.trim();
  25243. tokens.removeEmptyStrings();
  25244. if (tokens.size() == 3)
  25245. {
  25246. desc.componentType = stringToOSType (tokens[0]);
  25247. desc.componentSubType = stringToOSType (tokens[1]);
  25248. desc.componentManufacturer = stringToOSType (tokens[2]);
  25249. ComponentRecord* comp = FindNextComponent (0, &desc);
  25250. if (comp != 0)
  25251. {
  25252. getAUDetails (comp, name, manufacturer);
  25253. return true;
  25254. }
  25255. }
  25256. }
  25257. return false;
  25258. }
  25259. }
  25260. class AudioUnitPluginWindowCarbon;
  25261. class AudioUnitPluginWindowCocoa;
  25262. class AudioUnitPluginInstance : public AudioPluginInstance
  25263. {
  25264. public:
  25265. ~AudioUnitPluginInstance();
  25266. void initialise();
  25267. // AudioPluginInstance methods:
  25268. void fillInPluginDescription (PluginDescription& desc) const
  25269. {
  25270. desc.name = pluginName;
  25271. desc.fileOrIdentifier = AudioUnitFormatHelpers::createAUPluginIdentifier (componentDesc);
  25272. desc.uid = ((int) componentDesc.componentType)
  25273. ^ ((int) componentDesc.componentSubType)
  25274. ^ ((int) componentDesc.componentManufacturer);
  25275. desc.lastFileModTime = 0;
  25276. desc.pluginFormatName = "AudioUnit";
  25277. desc.category = getCategory();
  25278. desc.manufacturerName = manufacturer;
  25279. desc.version = version;
  25280. desc.numInputChannels = getNumInputChannels();
  25281. desc.numOutputChannels = getNumOutputChannels();
  25282. desc.isInstrument = (componentDesc.componentType == kAudioUnitType_MusicDevice);
  25283. }
  25284. const String getName() const { return pluginName; }
  25285. bool acceptsMidi() const { return wantsMidiMessages; }
  25286. bool producesMidi() const { return false; }
  25287. // AudioProcessor methods:
  25288. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  25289. void releaseResources();
  25290. void processBlock (AudioSampleBuffer& buffer,
  25291. MidiBuffer& midiMessages);
  25292. bool hasEditor() const;
  25293. AudioProcessorEditor* createEditor();
  25294. const String getInputChannelName (int index) const;
  25295. bool isInputChannelStereoPair (int index) const;
  25296. const String getOutputChannelName (int index) const;
  25297. bool isOutputChannelStereoPair (int index) const;
  25298. int getNumParameters();
  25299. float getParameter (int index);
  25300. void setParameter (int index, float newValue);
  25301. const String getParameterName (int index);
  25302. const String getParameterText (int index);
  25303. bool isParameterAutomatable (int index) const;
  25304. int getNumPrograms();
  25305. int getCurrentProgram();
  25306. void setCurrentProgram (int index);
  25307. const String getProgramName (int index);
  25308. void changeProgramName (int index, const String& newName);
  25309. void getStateInformation (MemoryBlock& destData);
  25310. void getCurrentProgramStateInformation (MemoryBlock& destData);
  25311. void setStateInformation (const void* data, int sizeInBytes);
  25312. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  25313. juce_UseDebuggingNewOperator
  25314. private:
  25315. friend class AudioUnitPluginWindowCarbon;
  25316. friend class AudioUnitPluginWindowCocoa;
  25317. friend class AudioUnitPluginFormat;
  25318. ComponentDescription componentDesc;
  25319. String pluginName, manufacturer, version;
  25320. String fileOrIdentifier;
  25321. CriticalSection lock;
  25322. bool wantsMidiMessages, wasPlaying, prepared;
  25323. HeapBlock <AudioBufferList> outputBufferList;
  25324. AudioTimeStamp timeStamp;
  25325. AudioSampleBuffer* currentBuffer;
  25326. AudioUnit audioUnit;
  25327. Array <int> parameterIds;
  25328. bool getComponentDescFromFile (const String& fileOrIdentifier);
  25329. void setPluginCallbacks();
  25330. void getParameterListFromPlugin();
  25331. OSStatus renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  25332. const AudioTimeStamp* inTimeStamp,
  25333. UInt32 inBusNumber,
  25334. UInt32 inNumberFrames,
  25335. AudioBufferList* ioData) const;
  25336. static OSStatus renderGetInputCallback (void* inRefCon,
  25337. AudioUnitRenderActionFlags* ioActionFlags,
  25338. const AudioTimeStamp* inTimeStamp,
  25339. UInt32 inBusNumber,
  25340. UInt32 inNumberFrames,
  25341. AudioBufferList* ioData)
  25342. {
  25343. return ((AudioUnitPluginInstance*) inRefCon)
  25344. ->renderGetInput (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  25345. }
  25346. OSStatus getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const;
  25347. OSStatus getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat, Float32* outTimeSig_Numerator,
  25348. UInt32* outTimeSig_Denominator, Float64* outCurrentMeasureDownBeat) const;
  25349. OSStatus getTransportState (Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  25350. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  25351. Float64* outCycleStartBeat, Float64* outCycleEndBeat);
  25352. static OSStatus getBeatAndTempoCallback (void* inHostUserData, Float64* outCurrentBeat, Float64* outCurrentTempo)
  25353. {
  25354. return ((AudioUnitPluginInstance*) inHostUserData)->getBeatAndTempo (outCurrentBeat, outCurrentTempo);
  25355. }
  25356. static OSStatus getMusicalTimeLocationCallback (void* inHostUserData, UInt32* outDeltaSampleOffsetToNextBeat,
  25357. Float32* outTimeSig_Numerator, UInt32* outTimeSig_Denominator,
  25358. Float64* outCurrentMeasureDownBeat)
  25359. {
  25360. return ((AudioUnitPluginInstance*) inHostUserData)
  25361. ->getMusicalTimeLocation (outDeltaSampleOffsetToNextBeat, outTimeSig_Numerator,
  25362. outTimeSig_Denominator, outCurrentMeasureDownBeat);
  25363. }
  25364. static OSStatus getTransportStateCallback (void* inHostUserData, Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  25365. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  25366. Float64* outCycleStartBeat, Float64* outCycleEndBeat)
  25367. {
  25368. return ((AudioUnitPluginInstance*) inHostUserData)
  25369. ->getTransportState (outIsPlaying, outTransportStateChanged,
  25370. outCurrentSampleInTimeLine, outIsCycling,
  25371. outCycleStartBeat, outCycleEndBeat);
  25372. }
  25373. void getNumChannels (int& numIns, int& numOuts)
  25374. {
  25375. numIns = 0;
  25376. numOuts = 0;
  25377. AUChannelInfo supportedChannels [128];
  25378. UInt32 supportedChannelsSize = sizeof (supportedChannels);
  25379. if (AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SupportedNumChannels, kAudioUnitScope_Global,
  25380. 0, supportedChannels, &supportedChannelsSize) == noErr
  25381. && supportedChannelsSize > 0)
  25382. {
  25383. int explicitNumIns = 0;
  25384. int explicitNumOuts = 0;
  25385. int maximumNumIns = 0;
  25386. int maximumNumOuts = 0;
  25387. for (int i = 0; i < supportedChannelsSize / sizeof (AUChannelInfo); ++i)
  25388. {
  25389. const int inChannels = (int) supportedChannels[i].inChannels;
  25390. const int outChannels = (int) supportedChannels[i].outChannels;
  25391. if (inChannels < 0)
  25392. maximumNumIns = jmin (maximumNumIns, inChannels);
  25393. else
  25394. explicitNumIns = jmax (explicitNumIns, inChannels);
  25395. if (outChannels < 0)
  25396. maximumNumOuts = jmin (maximumNumOuts, outChannels);
  25397. else
  25398. explicitNumOuts = jmax (explicitNumOuts, outChannels);
  25399. }
  25400. if ((maximumNumIns == -1 && maximumNumOuts == -1) // (special meaning: any number of ins/outs, as long as they match)
  25401. || (maximumNumIns == -2 && maximumNumOuts == -1) // (special meaning: any number of ins/outs, even if they don't match)
  25402. || (maximumNumIns == -1 && maximumNumOuts == -2))
  25403. {
  25404. numIns = numOuts = 2;
  25405. }
  25406. else
  25407. {
  25408. numIns = explicitNumIns;
  25409. numOuts = explicitNumOuts;
  25410. if (maximumNumIns == -1 || (maximumNumIns < 0 && explicitNumIns <= -maximumNumIns))
  25411. numIns = 2;
  25412. if (maximumNumOuts == -1 || (maximumNumOuts < 0 && explicitNumOuts <= -maximumNumOuts))
  25413. numOuts = 2;
  25414. }
  25415. }
  25416. else
  25417. {
  25418. // (this really means the plugin will take any number of ins/outs as long
  25419. // as they are the same)
  25420. numIns = numOuts = 2;
  25421. }
  25422. }
  25423. const String getCategory() const;
  25424. AudioUnitPluginInstance (const String& fileOrIdentifier);
  25425. };
  25426. AudioUnitPluginInstance::AudioUnitPluginInstance (const String& fileOrIdentifier)
  25427. : fileOrIdentifier (fileOrIdentifier),
  25428. wantsMidiMessages (false), wasPlaying (false), prepared (false),
  25429. audioUnit (0),
  25430. currentBuffer (0)
  25431. {
  25432. using namespace AudioUnitFormatHelpers;
  25433. try
  25434. {
  25435. ++insideCallback;
  25436. log ("Opening AU: " + fileOrIdentifier);
  25437. if (getComponentDescFromFile (fileOrIdentifier))
  25438. {
  25439. ComponentRecord* const comp = FindNextComponent (0, &componentDesc);
  25440. if (comp != 0)
  25441. {
  25442. audioUnit = (AudioUnit) OpenComponent (comp);
  25443. wantsMidiMessages = componentDesc.componentType == kAudioUnitType_MusicDevice
  25444. || componentDesc.componentType == kAudioUnitType_MusicEffect;
  25445. }
  25446. }
  25447. --insideCallback;
  25448. }
  25449. catch (...)
  25450. {
  25451. --insideCallback;
  25452. }
  25453. }
  25454. AudioUnitPluginInstance::~AudioUnitPluginInstance()
  25455. {
  25456. const ScopedLock sl (lock);
  25457. jassert (AudioUnitFormatHelpers::insideCallback == 0);
  25458. if (audioUnit != 0)
  25459. {
  25460. AudioUnitUninitialize (audioUnit);
  25461. CloseComponent (audioUnit);
  25462. audioUnit = 0;
  25463. }
  25464. }
  25465. bool AudioUnitPluginInstance::getComponentDescFromFile (const String& fileOrIdentifier)
  25466. {
  25467. zerostruct (componentDesc);
  25468. if (AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, componentDesc, pluginName, version, manufacturer))
  25469. return true;
  25470. const File file (fileOrIdentifier);
  25471. if (! file.hasFileExtension (".component"))
  25472. return false;
  25473. const char* const utf8 = fileOrIdentifier.toUTF8();
  25474. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  25475. strlen (utf8), file.isDirectory());
  25476. if (url != 0)
  25477. {
  25478. CFBundleRef bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  25479. CFRelease (url);
  25480. if (bundleRef != 0)
  25481. {
  25482. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  25483. if (name != 0 && CFGetTypeID (name) == CFStringGetTypeID())
  25484. pluginName = PlatformUtilities::cfStringToJuceString ((CFStringRef) name);
  25485. if (pluginName.isEmpty())
  25486. pluginName = file.getFileNameWithoutExtension();
  25487. CFTypeRef versionString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleVersion"));
  25488. if (versionString != 0 && CFGetTypeID (versionString) == CFStringGetTypeID())
  25489. version = PlatformUtilities::cfStringToJuceString ((CFStringRef) versionString);
  25490. CFTypeRef manuString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleGetInfoString"));
  25491. if (manuString != 0 && CFGetTypeID (manuString) == CFStringGetTypeID())
  25492. manufacturer = PlatformUtilities::cfStringToJuceString ((CFStringRef) manuString);
  25493. short resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  25494. UseResFile (resFileId);
  25495. for (int i = 1; i <= Count1Resources ('thng'); ++i)
  25496. {
  25497. Handle h = Get1IndResource ('thng', i);
  25498. if (h != 0)
  25499. {
  25500. HLock (h);
  25501. const uint32* const types = (const uint32*) *h;
  25502. if (types[0] == kAudioUnitType_MusicDevice
  25503. || types[0] == kAudioUnitType_MusicEffect
  25504. || types[0] == kAudioUnitType_Effect
  25505. || types[0] == kAudioUnitType_Generator
  25506. || types[0] == kAudioUnitType_Panner)
  25507. {
  25508. componentDesc.componentType = types[0];
  25509. componentDesc.componentSubType = types[1];
  25510. componentDesc.componentManufacturer = types[2];
  25511. break;
  25512. }
  25513. HUnlock (h);
  25514. ReleaseResource (h);
  25515. }
  25516. }
  25517. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  25518. CFRelease (bundleRef);
  25519. }
  25520. }
  25521. return componentDesc.componentType != 0 && componentDesc.componentSubType != 0;
  25522. }
  25523. void AudioUnitPluginInstance::initialise()
  25524. {
  25525. getParameterListFromPlugin();
  25526. setPluginCallbacks();
  25527. int numIns, numOuts;
  25528. getNumChannels (numIns, numOuts);
  25529. setPlayConfigDetails (numIns, numOuts, 0, 0);
  25530. setLatencySamples (0);
  25531. }
  25532. void AudioUnitPluginInstance::getParameterListFromPlugin()
  25533. {
  25534. parameterIds.clear();
  25535. if (audioUnit != 0)
  25536. {
  25537. UInt32 paramListSize = 0;
  25538. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  25539. 0, 0, &paramListSize);
  25540. if (paramListSize > 0)
  25541. {
  25542. parameterIds.insertMultiple (0, 0, paramListSize / sizeof (int));
  25543. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  25544. 0, &parameterIds.getReference(0), &paramListSize);
  25545. }
  25546. }
  25547. }
  25548. void AudioUnitPluginInstance::setPluginCallbacks()
  25549. {
  25550. if (audioUnit != 0)
  25551. {
  25552. {
  25553. AURenderCallbackStruct info;
  25554. zerostruct (info);
  25555. info.inputProcRefCon = this;
  25556. info.inputProc = renderGetInputCallback;
  25557. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
  25558. 0, &info, sizeof (info));
  25559. }
  25560. {
  25561. HostCallbackInfo info;
  25562. zerostruct (info);
  25563. info.hostUserData = this;
  25564. info.beatAndTempoProc = getBeatAndTempoCallback;
  25565. info.musicalTimeLocationProc = getMusicalTimeLocationCallback;
  25566. info.transportStateProc = getTransportStateCallback;
  25567. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_HostCallbacks, kAudioUnitScope_Global,
  25568. 0, &info, sizeof (info));
  25569. }
  25570. }
  25571. }
  25572. void AudioUnitPluginInstance::prepareToPlay (double sampleRate_,
  25573. int samplesPerBlockExpected)
  25574. {
  25575. if (audioUnit != 0)
  25576. {
  25577. releaseResources();
  25578. Float64 sampleRateIn = 0, sampleRateOut = 0;
  25579. UInt32 sampleRateSize = sizeof (sampleRateIn);
  25580. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Input, 0, &sampleRateIn, &sampleRateSize);
  25581. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Output, 0, &sampleRateOut, &sampleRateSize);
  25582. if (sampleRateIn != sampleRate_ || sampleRateOut != sampleRate_)
  25583. {
  25584. Float64 sr = sampleRate_;
  25585. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Input, 0, &sr, sizeof (Float64));
  25586. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Output, 0, &sr, sizeof (Float64));
  25587. }
  25588. int numIns, numOuts;
  25589. getNumChannels (numIns, numOuts);
  25590. setPlayConfigDetails (numIns, numOuts, sampleRate_, samplesPerBlockExpected);
  25591. Float64 latencySecs = 0.0;
  25592. UInt32 latencySize = sizeof (latencySecs);
  25593. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_Latency, kAudioUnitScope_Global,
  25594. 0, &latencySecs, &latencySize);
  25595. setLatencySamples (roundToInt (latencySecs * sampleRate_));
  25596. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  25597. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  25598. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  25599. {
  25600. AudioStreamBasicDescription stream;
  25601. zerostruct (stream);
  25602. stream.mSampleRate = sampleRate_;
  25603. stream.mFormatID = kAudioFormatLinearPCM;
  25604. stream.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kAudioFormatFlagIsNonInterleaved;
  25605. stream.mFramesPerPacket = 1;
  25606. stream.mBytesPerPacket = 4;
  25607. stream.mBytesPerFrame = 4;
  25608. stream.mBitsPerChannel = 32;
  25609. stream.mChannelsPerFrame = numIns;
  25610. OSStatus err = AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input,
  25611. 0, &stream, sizeof (stream));
  25612. stream.mChannelsPerFrame = numOuts;
  25613. err = AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output,
  25614. 0, &stream, sizeof (stream));
  25615. }
  25616. outputBufferList.calloc (sizeof (AudioBufferList) + sizeof (AudioBuffer) * (numOuts + 1), 1);
  25617. outputBufferList->mNumberBuffers = numOuts;
  25618. for (int i = numOuts; --i >= 0;)
  25619. outputBufferList->mBuffers[i].mNumberChannels = 1;
  25620. zerostruct (timeStamp);
  25621. timeStamp.mSampleTime = 0;
  25622. timeStamp.mHostTime = AudioGetCurrentHostTime();
  25623. timeStamp.mFlags = kAudioTimeStampSampleTimeValid | kAudioTimeStampHostTimeValid;
  25624. currentBuffer = 0;
  25625. wasPlaying = false;
  25626. prepared = (AudioUnitInitialize (audioUnit) == noErr);
  25627. }
  25628. }
  25629. void AudioUnitPluginInstance::releaseResources()
  25630. {
  25631. if (prepared)
  25632. {
  25633. AudioUnitUninitialize (audioUnit);
  25634. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  25635. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  25636. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  25637. outputBufferList.free();
  25638. currentBuffer = 0;
  25639. prepared = false;
  25640. }
  25641. }
  25642. OSStatus AudioUnitPluginInstance::renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  25643. const AudioTimeStamp* inTimeStamp,
  25644. UInt32 inBusNumber,
  25645. UInt32 inNumberFrames,
  25646. AudioBufferList* ioData) const
  25647. {
  25648. if (inBusNumber == 0
  25649. && currentBuffer != 0)
  25650. {
  25651. jassert (inNumberFrames == currentBuffer->getNumSamples()); // if this ever happens, might need to add extra handling
  25652. for (int i = 0; i < ioData->mNumberBuffers; ++i)
  25653. {
  25654. if (i < currentBuffer->getNumChannels())
  25655. {
  25656. memcpy (ioData->mBuffers[i].mData,
  25657. currentBuffer->getSampleData (i, 0),
  25658. sizeof (float) * inNumberFrames);
  25659. }
  25660. else
  25661. {
  25662. zeromem (ioData->mBuffers[i].mData, sizeof (float) * inNumberFrames);
  25663. }
  25664. }
  25665. }
  25666. return noErr;
  25667. }
  25668. void AudioUnitPluginInstance::processBlock (AudioSampleBuffer& buffer,
  25669. MidiBuffer& midiMessages)
  25670. {
  25671. const int numSamples = buffer.getNumSamples();
  25672. if (prepared)
  25673. {
  25674. AudioUnitRenderActionFlags flags = 0;
  25675. timeStamp.mHostTime = AudioGetCurrentHostTime();
  25676. for (int i = getNumOutputChannels(); --i >= 0;)
  25677. {
  25678. outputBufferList->mBuffers[i].mDataByteSize = sizeof (float) * numSamples;
  25679. outputBufferList->mBuffers[i].mData = buffer.getSampleData (i, 0);
  25680. }
  25681. currentBuffer = &buffer;
  25682. if (wantsMidiMessages)
  25683. {
  25684. const uint8* midiEventData;
  25685. int midiEventSize, midiEventPosition;
  25686. MidiBuffer::Iterator i (midiMessages);
  25687. while (i.getNextEvent (midiEventData, midiEventSize, midiEventPosition))
  25688. {
  25689. if (midiEventSize <= 3)
  25690. MusicDeviceMIDIEvent (audioUnit,
  25691. midiEventData[0], midiEventData[1], midiEventData[2],
  25692. midiEventPosition);
  25693. else
  25694. MusicDeviceSysEx (audioUnit, midiEventData, midiEventSize);
  25695. }
  25696. midiMessages.clear();
  25697. }
  25698. AudioUnitRender (audioUnit, &flags, &timeStamp,
  25699. 0, numSamples, outputBufferList);
  25700. timeStamp.mSampleTime += numSamples;
  25701. }
  25702. else
  25703. {
  25704. // Plugin not working correctly, so just bypass..
  25705. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  25706. buffer.clear (i, 0, buffer.getNumSamples());
  25707. }
  25708. }
  25709. OSStatus AudioUnitPluginInstance::getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const
  25710. {
  25711. AudioPlayHead* const ph = getPlayHead();
  25712. AudioPlayHead::CurrentPositionInfo result;
  25713. if (ph != 0 && ph->getCurrentPosition (result))
  25714. {
  25715. if (outCurrentBeat != 0)
  25716. *outCurrentBeat = result.ppqPosition;
  25717. if (outCurrentTempo != 0)
  25718. *outCurrentTempo = result.bpm;
  25719. }
  25720. else
  25721. {
  25722. if (outCurrentBeat != 0)
  25723. *outCurrentBeat = 0;
  25724. if (outCurrentTempo != 0)
  25725. *outCurrentTempo = 120.0;
  25726. }
  25727. return noErr;
  25728. }
  25729. OSStatus AudioUnitPluginInstance::getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat,
  25730. Float32* outTimeSig_Numerator,
  25731. UInt32* outTimeSig_Denominator,
  25732. Float64* outCurrentMeasureDownBeat) const
  25733. {
  25734. AudioPlayHead* const ph = getPlayHead();
  25735. AudioPlayHead::CurrentPositionInfo result;
  25736. if (ph != 0 && ph->getCurrentPosition (result))
  25737. {
  25738. if (outTimeSig_Numerator != 0)
  25739. *outTimeSig_Numerator = result.timeSigNumerator;
  25740. if (outTimeSig_Denominator != 0)
  25741. *outTimeSig_Denominator = result.timeSigDenominator;
  25742. if (outDeltaSampleOffsetToNextBeat != 0)
  25743. *outDeltaSampleOffsetToNextBeat = 0; //xxx
  25744. if (outCurrentMeasureDownBeat != 0)
  25745. *outCurrentMeasureDownBeat = result.ppqPositionOfLastBarStart; //xxx wrong
  25746. }
  25747. else
  25748. {
  25749. if (outDeltaSampleOffsetToNextBeat != 0)
  25750. *outDeltaSampleOffsetToNextBeat = 0;
  25751. if (outTimeSig_Numerator != 0)
  25752. *outTimeSig_Numerator = 4;
  25753. if (outTimeSig_Denominator != 0)
  25754. *outTimeSig_Denominator = 4;
  25755. if (outCurrentMeasureDownBeat != 0)
  25756. *outCurrentMeasureDownBeat = 0;
  25757. }
  25758. return noErr;
  25759. }
  25760. OSStatus AudioUnitPluginInstance::getTransportState (Boolean* outIsPlaying,
  25761. Boolean* outTransportStateChanged,
  25762. Float64* outCurrentSampleInTimeLine,
  25763. Boolean* outIsCycling,
  25764. Float64* outCycleStartBeat,
  25765. Float64* outCycleEndBeat)
  25766. {
  25767. AudioPlayHead* const ph = getPlayHead();
  25768. AudioPlayHead::CurrentPositionInfo result;
  25769. if (ph != 0 && ph->getCurrentPosition (result))
  25770. {
  25771. if (outIsPlaying != 0)
  25772. *outIsPlaying = result.isPlaying;
  25773. if (outTransportStateChanged != 0)
  25774. {
  25775. *outTransportStateChanged = result.isPlaying != wasPlaying;
  25776. wasPlaying = result.isPlaying;
  25777. }
  25778. if (outCurrentSampleInTimeLine != 0)
  25779. *outCurrentSampleInTimeLine = roundToInt (result.timeInSeconds * getSampleRate());
  25780. if (outIsCycling != 0)
  25781. *outIsCycling = false;
  25782. if (outCycleStartBeat != 0)
  25783. *outCycleStartBeat = 0;
  25784. if (outCycleEndBeat != 0)
  25785. *outCycleEndBeat = 0;
  25786. }
  25787. else
  25788. {
  25789. if (outIsPlaying != 0)
  25790. *outIsPlaying = false;
  25791. if (outTransportStateChanged != 0)
  25792. *outTransportStateChanged = false;
  25793. if (outCurrentSampleInTimeLine != 0)
  25794. *outCurrentSampleInTimeLine = 0;
  25795. if (outIsCycling != 0)
  25796. *outIsCycling = false;
  25797. if (outCycleStartBeat != 0)
  25798. *outCycleStartBeat = 0;
  25799. if (outCycleEndBeat != 0)
  25800. *outCycleEndBeat = 0;
  25801. }
  25802. return noErr;
  25803. }
  25804. class AudioUnitPluginWindowCocoa : public AudioProcessorEditor,
  25805. public Timer
  25806. {
  25807. public:
  25808. AudioUnitPluginWindowCocoa (AudioUnitPluginInstance& plugin_, const bool createGenericViewIfNeeded)
  25809. : AudioProcessorEditor (&plugin_),
  25810. plugin (plugin_)
  25811. {
  25812. addAndMakeVisible (&wrapper);
  25813. setOpaque (true);
  25814. setVisible (true);
  25815. setSize (100, 100);
  25816. createView (createGenericViewIfNeeded);
  25817. }
  25818. ~AudioUnitPluginWindowCocoa()
  25819. {
  25820. const bool wasValid = isValid();
  25821. wrapper.setView (0);
  25822. if (wasValid)
  25823. plugin.editorBeingDeleted (this);
  25824. }
  25825. bool isValid() const { return wrapper.getView() != 0; }
  25826. void paint (Graphics& g)
  25827. {
  25828. g.fillAll (Colours::white);
  25829. }
  25830. void resized()
  25831. {
  25832. wrapper.setSize (getWidth(), getHeight());
  25833. }
  25834. void timerCallback()
  25835. {
  25836. wrapper.resizeToFitView();
  25837. startTimer (jmin (713, getTimerInterval() + 51));
  25838. }
  25839. void childBoundsChanged (Component* child)
  25840. {
  25841. setSize (wrapper.getWidth(), wrapper.getHeight());
  25842. startTimer (70);
  25843. }
  25844. private:
  25845. AudioUnitPluginInstance& plugin;
  25846. NSViewComponent wrapper;
  25847. bool createView (const bool createGenericViewIfNeeded)
  25848. {
  25849. NSView* pluginView = 0;
  25850. UInt32 dataSize = 0;
  25851. Boolean isWritable = false;
  25852. AudioUnitInitialize (plugin.audioUnit);
  25853. if (AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  25854. 0, &dataSize, &isWritable) == noErr
  25855. && dataSize != 0
  25856. && AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  25857. 0, &dataSize, &isWritable) == noErr)
  25858. {
  25859. HeapBlock <AudioUnitCocoaViewInfo> info;
  25860. info.calloc (dataSize, 1);
  25861. if (AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  25862. 0, info, &dataSize) == noErr)
  25863. {
  25864. NSString* viewClassName = (NSString*) (info->mCocoaAUViewClass[0]);
  25865. NSString* path = (NSString*) CFURLCopyPath (info->mCocoaAUViewBundleLocation);
  25866. NSBundle* viewBundle = [NSBundle bundleWithPath: [path autorelease]];
  25867. Class viewClass = [viewBundle classNamed: viewClassName];
  25868. if ([viewClass conformsToProtocol: @protocol (AUCocoaUIBase)]
  25869. && [viewClass instancesRespondToSelector: @selector (interfaceVersion)]
  25870. && [viewClass instancesRespondToSelector: @selector (uiViewForAudioUnit: withSize:)])
  25871. {
  25872. id factory = [[[viewClass alloc] init] autorelease];
  25873. pluginView = [factory uiViewForAudioUnit: plugin.audioUnit
  25874. withSize: NSMakeSize (getWidth(), getHeight())];
  25875. }
  25876. for (int i = (dataSize - sizeof (CFURLRef)) / sizeof (CFStringRef); --i >= 0;)
  25877. CFRelease (info->mCocoaAUViewClass[i]);
  25878. CFRelease (info->mCocoaAUViewBundleLocation);
  25879. }
  25880. }
  25881. if (createGenericViewIfNeeded && (pluginView == 0))
  25882. pluginView = [[AUGenericView alloc] initWithAudioUnit: plugin.audioUnit];
  25883. wrapper.setView (pluginView);
  25884. if (pluginView != 0)
  25885. {
  25886. timerCallback();
  25887. startTimer (70);
  25888. }
  25889. return pluginView != 0;
  25890. }
  25891. };
  25892. #if JUCE_SUPPORT_CARBON
  25893. class AudioUnitPluginWindowCarbon : public AudioProcessorEditor
  25894. {
  25895. public:
  25896. AudioUnitPluginWindowCarbon (AudioUnitPluginInstance& plugin_)
  25897. : AudioProcessorEditor (&plugin_),
  25898. plugin (plugin_),
  25899. viewComponent (0)
  25900. {
  25901. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  25902. setOpaque (true);
  25903. setVisible (true);
  25904. setSize (400, 300);
  25905. ComponentDescription viewList [16];
  25906. UInt32 viewListSize = sizeof (viewList);
  25907. AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_GetUIComponentList, kAudioUnitScope_Global,
  25908. 0, &viewList, &viewListSize);
  25909. componentRecord = FindNextComponent (0, &viewList[0]);
  25910. }
  25911. ~AudioUnitPluginWindowCarbon()
  25912. {
  25913. innerWrapper = 0;
  25914. if (isValid())
  25915. plugin.editorBeingDeleted (this);
  25916. }
  25917. bool isValid() const throw() { return componentRecord != 0; }
  25918. void paint (Graphics& g)
  25919. {
  25920. g.fillAll (Colours::black);
  25921. }
  25922. void resized()
  25923. {
  25924. innerWrapper->setSize (getWidth(), getHeight());
  25925. }
  25926. bool keyStateChanged (bool)
  25927. {
  25928. return false;
  25929. }
  25930. bool keyPressed (const KeyPress&)
  25931. {
  25932. return false;
  25933. }
  25934. AudioUnit getAudioUnit() const { return plugin.audioUnit; }
  25935. AudioUnitCarbonView getViewComponent()
  25936. {
  25937. if (viewComponent == 0 && componentRecord != 0)
  25938. viewComponent = (AudioUnitCarbonView) OpenComponent (componentRecord);
  25939. return viewComponent;
  25940. }
  25941. void closeViewComponent()
  25942. {
  25943. if (viewComponent != 0)
  25944. {
  25945. log ("Closing AU GUI: " + plugin.getName());
  25946. CloseComponent (viewComponent);
  25947. viewComponent = 0;
  25948. }
  25949. }
  25950. juce_UseDebuggingNewOperator
  25951. private:
  25952. AudioUnitPluginInstance& plugin;
  25953. ComponentRecord* componentRecord;
  25954. AudioUnitCarbonView viewComponent;
  25955. class InnerWrapperComponent : public CarbonViewWrapperComponent
  25956. {
  25957. public:
  25958. InnerWrapperComponent (AudioUnitPluginWindowCarbon* const owner_)
  25959. : owner (owner_)
  25960. {
  25961. }
  25962. ~InnerWrapperComponent()
  25963. {
  25964. deleteWindow();
  25965. }
  25966. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  25967. {
  25968. log ("Opening AU GUI: " + owner->plugin.getName());
  25969. AudioUnitCarbonView viewComponent = owner->getViewComponent();
  25970. if (viewComponent == 0)
  25971. return 0;
  25972. Float32Point pos = { 0, 0 };
  25973. Float32Point size = { 250, 200 };
  25974. HIViewRef pluginView = 0;
  25975. AudioUnitCarbonViewCreate (viewComponent,
  25976. owner->getAudioUnit(),
  25977. windowRef,
  25978. rootView,
  25979. &pos,
  25980. &size,
  25981. (ControlRef*) &pluginView);
  25982. return pluginView;
  25983. }
  25984. void removeView (HIViewRef)
  25985. {
  25986. owner->closeViewComponent();
  25987. }
  25988. private:
  25989. AudioUnitPluginWindowCarbon* const owner;
  25990. };
  25991. friend class InnerWrapperComponent;
  25992. ScopedPointer<InnerWrapperComponent> innerWrapper;
  25993. };
  25994. #endif
  25995. bool AudioUnitPluginInstance::hasEditor() const
  25996. {
  25997. return true;
  25998. }
  25999. AudioProcessorEditor* AudioUnitPluginInstance::createEditor()
  26000. {
  26001. ScopedPointer<AudioProcessorEditor> w (new AudioUnitPluginWindowCocoa (*this, false));
  26002. if (! static_cast <AudioUnitPluginWindowCocoa*> (static_cast <AudioProcessorEditor*> (w))->isValid())
  26003. w = 0;
  26004. #if JUCE_SUPPORT_CARBON
  26005. if (w == 0)
  26006. {
  26007. w = new AudioUnitPluginWindowCarbon (*this);
  26008. if (! static_cast <AudioUnitPluginWindowCarbon*> (static_cast <AudioProcessorEditor*> (w))->isValid())
  26009. w = 0;
  26010. }
  26011. #endif
  26012. if (w == 0)
  26013. w = new AudioUnitPluginWindowCocoa (*this, true); // use AUGenericView as a fallback
  26014. return w.release();
  26015. }
  26016. const String AudioUnitPluginInstance::getCategory() const
  26017. {
  26018. const char* result = 0;
  26019. switch (componentDesc.componentType)
  26020. {
  26021. case kAudioUnitType_Effect:
  26022. case kAudioUnitType_MusicEffect:
  26023. result = "Effect";
  26024. break;
  26025. case kAudioUnitType_MusicDevice:
  26026. result = "Synth";
  26027. break;
  26028. case kAudioUnitType_Generator:
  26029. result = "Generator";
  26030. break;
  26031. case kAudioUnitType_Panner:
  26032. result = "Panner";
  26033. break;
  26034. default:
  26035. break;
  26036. }
  26037. return result;
  26038. }
  26039. int AudioUnitPluginInstance::getNumParameters()
  26040. {
  26041. return parameterIds.size();
  26042. }
  26043. float AudioUnitPluginInstance::getParameter (int index)
  26044. {
  26045. const ScopedLock sl (lock);
  26046. Float32 value = 0.0f;
  26047. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  26048. {
  26049. AudioUnitGetParameter (audioUnit,
  26050. (UInt32) parameterIds.getUnchecked (index),
  26051. kAudioUnitScope_Global, 0,
  26052. &value);
  26053. }
  26054. return value;
  26055. }
  26056. void AudioUnitPluginInstance::setParameter (int index, float newValue)
  26057. {
  26058. const ScopedLock sl (lock);
  26059. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  26060. {
  26061. AudioUnitSetParameter (audioUnit,
  26062. (UInt32) parameterIds.getUnchecked (index),
  26063. kAudioUnitScope_Global, 0,
  26064. newValue, 0);
  26065. }
  26066. }
  26067. const String AudioUnitPluginInstance::getParameterName (int index)
  26068. {
  26069. AudioUnitParameterInfo info;
  26070. zerostruct (info);
  26071. UInt32 sz = sizeof (info);
  26072. String name;
  26073. if (AudioUnitGetProperty (audioUnit,
  26074. kAudioUnitProperty_ParameterInfo,
  26075. kAudioUnitScope_Global,
  26076. parameterIds [index], &info, &sz) == noErr)
  26077. {
  26078. if ((info.flags & kAudioUnitParameterFlag_HasCFNameString) != 0)
  26079. name = PlatformUtilities::cfStringToJuceString (info.cfNameString);
  26080. else
  26081. name = String (info.name, sizeof (info.name));
  26082. }
  26083. return name;
  26084. }
  26085. const String AudioUnitPluginInstance::getParameterText (int index)
  26086. {
  26087. return String (getParameter (index));
  26088. }
  26089. bool AudioUnitPluginInstance::isParameterAutomatable (int index) const
  26090. {
  26091. AudioUnitParameterInfo info;
  26092. UInt32 sz = sizeof (info);
  26093. if (AudioUnitGetProperty (audioUnit,
  26094. kAudioUnitProperty_ParameterInfo,
  26095. kAudioUnitScope_Global,
  26096. parameterIds [index], &info, &sz) == noErr)
  26097. {
  26098. return (info.flags & kAudioUnitParameterFlag_NonRealTime) == 0;
  26099. }
  26100. return true;
  26101. }
  26102. int AudioUnitPluginInstance::getNumPrograms()
  26103. {
  26104. CFArrayRef presets;
  26105. UInt32 sz = sizeof (CFArrayRef);
  26106. int num = 0;
  26107. if (AudioUnitGetProperty (audioUnit,
  26108. kAudioUnitProperty_FactoryPresets,
  26109. kAudioUnitScope_Global,
  26110. 0, &presets, &sz) == noErr)
  26111. {
  26112. num = (int) CFArrayGetCount (presets);
  26113. CFRelease (presets);
  26114. }
  26115. return num;
  26116. }
  26117. int AudioUnitPluginInstance::getCurrentProgram()
  26118. {
  26119. AUPreset current;
  26120. current.presetNumber = 0;
  26121. UInt32 sz = sizeof (AUPreset);
  26122. AudioUnitGetProperty (audioUnit,
  26123. kAudioUnitProperty_FactoryPresets,
  26124. kAudioUnitScope_Global,
  26125. 0, &current, &sz);
  26126. return current.presetNumber;
  26127. }
  26128. void AudioUnitPluginInstance::setCurrentProgram (int newIndex)
  26129. {
  26130. AUPreset current;
  26131. current.presetNumber = newIndex;
  26132. current.presetName = 0;
  26133. AudioUnitSetProperty (audioUnit,
  26134. kAudioUnitProperty_FactoryPresets,
  26135. kAudioUnitScope_Global,
  26136. 0, &current, sizeof (AUPreset));
  26137. }
  26138. const String AudioUnitPluginInstance::getProgramName (int index)
  26139. {
  26140. String s;
  26141. CFArrayRef presets;
  26142. UInt32 sz = sizeof (CFArrayRef);
  26143. if (AudioUnitGetProperty (audioUnit,
  26144. kAudioUnitProperty_FactoryPresets,
  26145. kAudioUnitScope_Global,
  26146. 0, &presets, &sz) == noErr)
  26147. {
  26148. for (CFIndex i = 0; i < CFArrayGetCount (presets); ++i)
  26149. {
  26150. const AUPreset* p = (const AUPreset*) CFArrayGetValueAtIndex (presets, i);
  26151. if (p != 0 && p->presetNumber == index)
  26152. {
  26153. s = PlatformUtilities::cfStringToJuceString (p->presetName);
  26154. break;
  26155. }
  26156. }
  26157. CFRelease (presets);
  26158. }
  26159. return s;
  26160. }
  26161. void AudioUnitPluginInstance::changeProgramName (int index, const String& newName)
  26162. {
  26163. jassertfalse; // xxx not implemented!
  26164. }
  26165. const String AudioUnitPluginInstance::getInputChannelName (int index) const
  26166. {
  26167. if (((unsigned int) index) < (unsigned int) getNumInputChannels())
  26168. return "Input " + String (index + 1);
  26169. return String::empty;
  26170. }
  26171. bool AudioUnitPluginInstance::isInputChannelStereoPair (int index) const
  26172. {
  26173. if (((unsigned int) index) >= (unsigned int) getNumInputChannels())
  26174. return false;
  26175. return true;
  26176. }
  26177. const String AudioUnitPluginInstance::getOutputChannelName (int index) const
  26178. {
  26179. if (((unsigned int) index) < (unsigned int) getNumOutputChannels())
  26180. return "Output " + String (index + 1);
  26181. return String::empty;
  26182. }
  26183. bool AudioUnitPluginInstance::isOutputChannelStereoPair (int index) const
  26184. {
  26185. if (((unsigned int) index) >= (unsigned int) getNumOutputChannels())
  26186. return false;
  26187. return true;
  26188. }
  26189. void AudioUnitPluginInstance::getStateInformation (MemoryBlock& destData)
  26190. {
  26191. getCurrentProgramStateInformation (destData);
  26192. }
  26193. void AudioUnitPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  26194. {
  26195. CFPropertyListRef propertyList = 0;
  26196. UInt32 sz = sizeof (CFPropertyListRef);
  26197. if (AudioUnitGetProperty (audioUnit,
  26198. kAudioUnitProperty_ClassInfo,
  26199. kAudioUnitScope_Global,
  26200. 0, &propertyList, &sz) == noErr)
  26201. {
  26202. CFWriteStreamRef stream = CFWriteStreamCreateWithAllocatedBuffers (kCFAllocatorDefault, kCFAllocatorDefault);
  26203. CFWriteStreamOpen (stream);
  26204. CFIndex bytesWritten = CFPropertyListWriteToStream (propertyList, stream, kCFPropertyListBinaryFormat_v1_0, 0);
  26205. CFWriteStreamClose (stream);
  26206. CFDataRef data = (CFDataRef) CFWriteStreamCopyProperty (stream, kCFStreamPropertyDataWritten);
  26207. destData.setSize (bytesWritten);
  26208. destData.copyFrom (CFDataGetBytePtr (data), 0, destData.getSize());
  26209. CFRelease (data);
  26210. CFRelease (stream);
  26211. CFRelease (propertyList);
  26212. }
  26213. }
  26214. void AudioUnitPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  26215. {
  26216. setCurrentProgramStateInformation (data, sizeInBytes);
  26217. }
  26218. void AudioUnitPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  26219. {
  26220. CFReadStreamRef stream = CFReadStreamCreateWithBytesNoCopy (kCFAllocatorDefault,
  26221. (const UInt8*) data,
  26222. sizeInBytes,
  26223. kCFAllocatorNull);
  26224. CFReadStreamOpen (stream);
  26225. CFPropertyListFormat format = kCFPropertyListBinaryFormat_v1_0;
  26226. CFPropertyListRef propertyList = CFPropertyListCreateFromStream (kCFAllocatorDefault,
  26227. stream,
  26228. 0,
  26229. kCFPropertyListImmutable,
  26230. &format,
  26231. 0);
  26232. CFRelease (stream);
  26233. if (propertyList != 0)
  26234. AudioUnitSetProperty (audioUnit,
  26235. kAudioUnitProperty_ClassInfo,
  26236. kAudioUnitScope_Global,
  26237. 0, &propertyList, sizeof (propertyList));
  26238. }
  26239. AudioUnitPluginFormat::AudioUnitPluginFormat()
  26240. {
  26241. }
  26242. AudioUnitPluginFormat::~AudioUnitPluginFormat()
  26243. {
  26244. }
  26245. void AudioUnitPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  26246. const String& fileOrIdentifier)
  26247. {
  26248. if (! fileMightContainThisPluginType (fileOrIdentifier))
  26249. return;
  26250. PluginDescription desc;
  26251. desc.fileOrIdentifier = fileOrIdentifier;
  26252. desc.uid = 0;
  26253. try
  26254. {
  26255. ScopedPointer <AudioPluginInstance> createdInstance (createInstanceFromDescription (desc));
  26256. AudioUnitPluginInstance* const auInstance = dynamic_cast <AudioUnitPluginInstance*> ((AudioPluginInstance*) createdInstance);
  26257. if (auInstance != 0)
  26258. {
  26259. auInstance->fillInPluginDescription (desc);
  26260. results.add (new PluginDescription (desc));
  26261. }
  26262. }
  26263. catch (...)
  26264. {
  26265. // crashed while loading...
  26266. }
  26267. }
  26268. AudioPluginInstance* AudioUnitPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  26269. {
  26270. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  26271. {
  26272. ScopedPointer <AudioUnitPluginInstance> result (new AudioUnitPluginInstance (desc.fileOrIdentifier));
  26273. if (result->audioUnit != 0)
  26274. {
  26275. result->initialise();
  26276. return result.release();
  26277. }
  26278. }
  26279. return 0;
  26280. }
  26281. const StringArray AudioUnitPluginFormat::searchPathsForPlugins (const FileSearchPath& /*directoriesToSearch*/,
  26282. const bool /*recursive*/)
  26283. {
  26284. StringArray result;
  26285. ComponentRecord* comp = 0;
  26286. ComponentDescription desc;
  26287. zerostruct (desc);
  26288. for (;;)
  26289. {
  26290. zerostruct (desc);
  26291. comp = FindNextComponent (comp, &desc);
  26292. if (comp == 0)
  26293. break;
  26294. GetComponentInfo (comp, &desc, 0, 0, 0);
  26295. if (desc.componentType == kAudioUnitType_MusicDevice
  26296. || desc.componentType == kAudioUnitType_MusicEffect
  26297. || desc.componentType == kAudioUnitType_Effect
  26298. || desc.componentType == kAudioUnitType_Generator
  26299. || desc.componentType == kAudioUnitType_Panner)
  26300. {
  26301. const String s (AudioUnitFormatHelpers::createAUPluginIdentifier (desc));
  26302. DBG (s);
  26303. result.add (s);
  26304. }
  26305. }
  26306. return result;
  26307. }
  26308. bool AudioUnitPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  26309. {
  26310. ComponentDescription desc;
  26311. String name, version, manufacturer;
  26312. if (AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer))
  26313. return FindNextComponent (0, &desc) != 0;
  26314. const File f (fileOrIdentifier);
  26315. return f.hasFileExtension (".component")
  26316. && f.isDirectory();
  26317. }
  26318. const String AudioUnitPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  26319. {
  26320. ComponentDescription desc;
  26321. String name, version, manufacturer;
  26322. AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer);
  26323. if (name.isEmpty())
  26324. name = fileOrIdentifier;
  26325. return name;
  26326. }
  26327. bool AudioUnitPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  26328. {
  26329. if (desc.fileOrIdentifier.startsWithIgnoreCase (AudioUnitFormatHelpers::auIdentifierPrefix))
  26330. return fileMightContainThisPluginType (desc.fileOrIdentifier);
  26331. else
  26332. return File (desc.fileOrIdentifier).exists();
  26333. }
  26334. const FileSearchPath AudioUnitPluginFormat::getDefaultLocationsToSearch()
  26335. {
  26336. return FileSearchPath ("/(Default AudioUnit locations)");
  26337. }
  26338. #endif
  26339. END_JUCE_NAMESPACE
  26340. #undef log
  26341. #endif
  26342. /*** End of inlined file: juce_AudioUnitPluginFormat.mm ***/
  26343. /*** Start of inlined file: juce_VSTPluginFormat.mm ***/
  26344. // This file just wraps juce_VSTPluginFormat.cpp in an objective-C wrapper
  26345. #define JUCE_MAC_VST_INCLUDED 1
  26346. /*** Start of inlined file: juce_VSTPluginFormat.cpp ***/
  26347. #if JUCE_PLUGINHOST_VST && (JUCE_MAC_VST_INCLUDED || ! JUCE_MAC)
  26348. #if JUCE_WINDOWS
  26349. #undef _WIN32_WINNT
  26350. #define _WIN32_WINNT 0x500
  26351. #undef STRICT
  26352. #define STRICT
  26353. #include <windows.h>
  26354. #include <float.h>
  26355. #pragma warning (disable : 4312 4355)
  26356. #elif JUCE_LINUX
  26357. #include <float.h>
  26358. #include <sys/time.h>
  26359. #include <X11/Xlib.h>
  26360. #include <X11/Xutil.h>
  26361. #include <X11/Xatom.h>
  26362. #undef Font
  26363. #undef KeyPress
  26364. #undef Drawable
  26365. #undef Time
  26366. #else
  26367. #include <Cocoa/Cocoa.h>
  26368. #include <Carbon/Carbon.h>
  26369. #endif
  26370. #if ! (JUCE_MAC && JUCE_64BIT)
  26371. BEGIN_JUCE_NAMESPACE
  26372. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  26373. #endif
  26374. #undef PRAGMA_ALIGN_SUPPORTED
  26375. #define VST_FORCE_DEPRECATED 0
  26376. #if JUCE_MSVC
  26377. #pragma warning (push)
  26378. #pragma warning (disable: 4996)
  26379. #endif
  26380. /* Obviously you're going to need the Steinberg vstsdk2.4 folder in
  26381. your include path if you want to add VST support.
  26382. If you're not interested in VSTs, you can disable them by changing the
  26383. JUCE_PLUGINHOST_VST flag in juce_Config.h
  26384. */
  26385. #include "pluginterfaces/vst2.x/aeffectx.h"
  26386. #if JUCE_MSVC
  26387. #pragma warning (pop)
  26388. #endif
  26389. #if JUCE_LINUX
  26390. #define Font JUCE_NAMESPACE::Font
  26391. #define KeyPress JUCE_NAMESPACE::KeyPress
  26392. #define Drawable JUCE_NAMESPACE::Drawable
  26393. #define Time JUCE_NAMESPACE::Time
  26394. #endif
  26395. /*** Start of inlined file: juce_VSTMidiEventList.h ***/
  26396. #ifdef __aeffect__
  26397. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26398. #define __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26399. /** Holds a set of VSTMidiEvent objects and makes it easy to add
  26400. events to the list.
  26401. This is used by both the VST hosting code and the plugin wrapper.
  26402. */
  26403. class VSTMidiEventList
  26404. {
  26405. public:
  26406. VSTMidiEventList()
  26407. : numEventsUsed (0), numEventsAllocated (0)
  26408. {
  26409. }
  26410. ~VSTMidiEventList()
  26411. {
  26412. freeEvents();
  26413. }
  26414. void clear()
  26415. {
  26416. numEventsUsed = 0;
  26417. if (events != 0)
  26418. events->numEvents = 0;
  26419. }
  26420. void addEvent (const void* const midiData, const int numBytes, const int frameOffset)
  26421. {
  26422. ensureSize (numEventsUsed + 1);
  26423. VstMidiEvent* const e = (VstMidiEvent*) (events->events [numEventsUsed]);
  26424. events->numEvents = ++numEventsUsed;
  26425. if (numBytes <= 4)
  26426. {
  26427. if (e->type == kVstSysExType)
  26428. {
  26429. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  26430. e->type = kVstMidiType;
  26431. e->byteSize = sizeof (VstMidiEvent);
  26432. e->noteLength = 0;
  26433. e->noteOffset = 0;
  26434. e->detune = 0;
  26435. e->noteOffVelocity = 0;
  26436. }
  26437. e->deltaFrames = frameOffset;
  26438. memcpy (e->midiData, midiData, numBytes);
  26439. }
  26440. else
  26441. {
  26442. VstMidiSysexEvent* const se = (VstMidiSysexEvent*) e;
  26443. if (se->type == kVstSysExType)
  26444. se->sysexDump = (char*) juce_realloc (se->sysexDump, numBytes);
  26445. else
  26446. se->sysexDump = (char*) juce_malloc (numBytes);
  26447. memcpy (se->sysexDump, midiData, numBytes);
  26448. se->type = kVstSysExType;
  26449. se->byteSize = sizeof (VstMidiSysexEvent);
  26450. se->deltaFrames = frameOffset;
  26451. se->flags = 0;
  26452. se->dumpBytes = numBytes;
  26453. se->resvd1 = 0;
  26454. se->resvd2 = 0;
  26455. }
  26456. }
  26457. // Handy method to pull the events out of an event buffer supplied by the host
  26458. // or plugin.
  26459. static void addEventsToMidiBuffer (const VstEvents* events, MidiBuffer& dest)
  26460. {
  26461. for (int i = 0; i < events->numEvents; ++i)
  26462. {
  26463. const VstEvent* const e = events->events[i];
  26464. if (e != 0)
  26465. {
  26466. if (e->type == kVstMidiType)
  26467. {
  26468. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiEvent*) e)->midiData,
  26469. 4, e->deltaFrames);
  26470. }
  26471. else if (e->type == kVstSysExType)
  26472. {
  26473. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiSysexEvent*) e)->sysexDump,
  26474. (int) ((const VstMidiSysexEvent*) e)->dumpBytes,
  26475. e->deltaFrames);
  26476. }
  26477. }
  26478. }
  26479. }
  26480. void ensureSize (int numEventsNeeded)
  26481. {
  26482. if (numEventsNeeded > numEventsAllocated)
  26483. {
  26484. numEventsNeeded = (numEventsNeeded + 32) & ~31;
  26485. const int size = 20 + sizeof (VstEvent*) * numEventsNeeded;
  26486. if (events == 0)
  26487. events.calloc (size, 1);
  26488. else
  26489. events.realloc (size, 1);
  26490. for (int i = numEventsAllocated; i < numEventsNeeded; ++i)
  26491. {
  26492. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (jmax ((int) sizeof (VstMidiEvent),
  26493. (int) sizeof (VstMidiSysexEvent)));
  26494. e->type = kVstMidiType;
  26495. e->byteSize = sizeof (VstMidiEvent);
  26496. events->events[i] = (VstEvent*) e;
  26497. }
  26498. numEventsAllocated = numEventsNeeded;
  26499. }
  26500. }
  26501. void freeEvents()
  26502. {
  26503. if (events != 0)
  26504. {
  26505. for (int i = numEventsAllocated; --i >= 0;)
  26506. {
  26507. VstMidiEvent* const e = (VstMidiEvent*) (events->events[i]);
  26508. if (e->type == kVstSysExType)
  26509. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  26510. juce_free (e);
  26511. }
  26512. events.free();
  26513. numEventsUsed = 0;
  26514. numEventsAllocated = 0;
  26515. }
  26516. }
  26517. HeapBlock <VstEvents> events;
  26518. private:
  26519. int numEventsUsed, numEventsAllocated;
  26520. };
  26521. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26522. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26523. /*** End of inlined file: juce_VSTMidiEventList.h ***/
  26524. #if ! JUCE_WINDOWS
  26525. static void _fpreset() {}
  26526. static void _clearfp() {}
  26527. #endif
  26528. extern void juce_callAnyTimersSynchronously();
  26529. const int fxbVersionNum = 1;
  26530. struct fxProgram
  26531. {
  26532. long chunkMagic; // 'CcnK'
  26533. long byteSize; // of this chunk, excl. magic + byteSize
  26534. long fxMagic; // 'FxCk'
  26535. long version;
  26536. long fxID; // fx unique id
  26537. long fxVersion;
  26538. long numParams;
  26539. char prgName[28];
  26540. float params[1]; // variable no. of parameters
  26541. };
  26542. struct fxSet
  26543. {
  26544. long chunkMagic; // 'CcnK'
  26545. long byteSize; // of this chunk, excl. magic + byteSize
  26546. long fxMagic; // 'FxBk'
  26547. long version;
  26548. long fxID; // fx unique id
  26549. long fxVersion;
  26550. long numPrograms;
  26551. char future[128];
  26552. fxProgram programs[1]; // variable no. of programs
  26553. };
  26554. struct fxChunkSet
  26555. {
  26556. long chunkMagic; // 'CcnK'
  26557. long byteSize; // of this chunk, excl. magic + byteSize
  26558. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  26559. long version;
  26560. long fxID; // fx unique id
  26561. long fxVersion;
  26562. long numPrograms;
  26563. char future[128];
  26564. long chunkSize;
  26565. char chunk[8]; // variable
  26566. };
  26567. struct fxProgramSet
  26568. {
  26569. long chunkMagic; // 'CcnK'
  26570. long byteSize; // of this chunk, excl. magic + byteSize
  26571. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  26572. long version;
  26573. long fxID; // fx unique id
  26574. long fxVersion;
  26575. long numPrograms;
  26576. char name[28];
  26577. long chunkSize;
  26578. char chunk[8]; // variable
  26579. };
  26580. namespace
  26581. {
  26582. long vst_swap (const long x) throw()
  26583. {
  26584. #ifdef JUCE_LITTLE_ENDIAN
  26585. return (long) ByteOrder::swap ((uint32) x);
  26586. #else
  26587. return x;
  26588. #endif
  26589. }
  26590. float vst_swapFloat (const float x) throw()
  26591. {
  26592. #ifdef JUCE_LITTLE_ENDIAN
  26593. union { uint32 asInt; float asFloat; } n;
  26594. n.asFloat = x;
  26595. n.asInt = ByteOrder::swap (n.asInt);
  26596. return n.asFloat;
  26597. #else
  26598. return x;
  26599. #endif
  26600. }
  26601. double getVSTHostTimeNanoseconds()
  26602. {
  26603. #if JUCE_WINDOWS
  26604. return timeGetTime() * 1000000.0;
  26605. #elif JUCE_LINUX
  26606. timeval micro;
  26607. gettimeofday (&micro, 0);
  26608. return micro.tv_usec * 1000.0;
  26609. #elif JUCE_MAC
  26610. UnsignedWide micro;
  26611. Microseconds (&micro);
  26612. return micro.lo * 1000.0;
  26613. #endif
  26614. }
  26615. }
  26616. typedef AEffect* (*MainCall) (audioMasterCallback);
  26617. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt);
  26618. static int shellUIDToCreate = 0;
  26619. static int insideVSTCallback = 0;
  26620. class VSTPluginWindow;
  26621. // Change this to disable logging of various VST activities
  26622. #ifndef VST_LOGGING
  26623. #define VST_LOGGING 1
  26624. #endif
  26625. #if VST_LOGGING
  26626. #define log(a) Logger::writeToLog(a);
  26627. #else
  26628. #define log(a)
  26629. #endif
  26630. #if JUCE_MAC && JUCE_PPC
  26631. static void* NewCFMFromMachO (void* const machofp) throw()
  26632. {
  26633. void* result = juce_malloc (8);
  26634. ((void**) result)[0] = machofp;
  26635. ((void**) result)[1] = result;
  26636. return result;
  26637. }
  26638. #endif
  26639. #if JUCE_LINUX
  26640. extern Display* display;
  26641. extern XContext windowHandleXContext;
  26642. typedef void (*EventProcPtr) (XEvent* ev);
  26643. static bool xErrorTriggered;
  26644. namespace
  26645. {
  26646. int temporaryErrorHandler (Display*, XErrorEvent*)
  26647. {
  26648. xErrorTriggered = true;
  26649. return 0;
  26650. }
  26651. int getPropertyFromXWindow (Window handle, Atom atom)
  26652. {
  26653. XErrorHandler oldErrorHandler = XSetErrorHandler (temporaryErrorHandler);
  26654. xErrorTriggered = false;
  26655. int userSize;
  26656. unsigned long bytes, userCount;
  26657. unsigned char* data;
  26658. Atom userType;
  26659. XGetWindowProperty (display, handle, atom, 0, 1, false, AnyPropertyType,
  26660. &userType, &userSize, &userCount, &bytes, &data);
  26661. XSetErrorHandler (oldErrorHandler);
  26662. return (userCount == 1 && ! xErrorTriggered) ? *reinterpret_cast<int*> (data)
  26663. : 0;
  26664. }
  26665. Window getChildWindow (Window windowToCheck)
  26666. {
  26667. Window rootWindow, parentWindow;
  26668. Window* childWindows;
  26669. unsigned int numChildren;
  26670. XQueryTree (display,
  26671. windowToCheck,
  26672. &rootWindow,
  26673. &parentWindow,
  26674. &childWindows,
  26675. &numChildren);
  26676. if (numChildren > 0)
  26677. return childWindows [0];
  26678. return 0;
  26679. }
  26680. void translateJuceToXButtonModifiers (const MouseEvent& e, XEvent& ev) throw()
  26681. {
  26682. if (e.mods.isLeftButtonDown())
  26683. {
  26684. ev.xbutton.button = Button1;
  26685. ev.xbutton.state |= Button1Mask;
  26686. }
  26687. else if (e.mods.isRightButtonDown())
  26688. {
  26689. ev.xbutton.button = Button3;
  26690. ev.xbutton.state |= Button3Mask;
  26691. }
  26692. else if (e.mods.isMiddleButtonDown())
  26693. {
  26694. ev.xbutton.button = Button2;
  26695. ev.xbutton.state |= Button2Mask;
  26696. }
  26697. }
  26698. void translateJuceToXMotionModifiers (const MouseEvent& e, XEvent& ev) throw()
  26699. {
  26700. if (e.mods.isLeftButtonDown()) ev.xmotion.state |= Button1Mask;
  26701. else if (e.mods.isRightButtonDown()) ev.xmotion.state |= Button3Mask;
  26702. else if (e.mods.isMiddleButtonDown()) ev.xmotion.state |= Button2Mask;
  26703. }
  26704. void translateJuceToXCrossingModifiers (const MouseEvent& e, XEvent& ev) throw()
  26705. {
  26706. if (e.mods.isLeftButtonDown()) ev.xcrossing.state |= Button1Mask;
  26707. else if (e.mods.isRightButtonDown()) ev.xcrossing.state |= Button3Mask;
  26708. else if (e.mods.isMiddleButtonDown()) ev.xcrossing.state |= Button2Mask;
  26709. }
  26710. void translateJuceToXMouseWheelModifiers (const MouseEvent& e, const float increment, XEvent& ev) throw()
  26711. {
  26712. if (increment < 0)
  26713. {
  26714. ev.xbutton.button = Button5;
  26715. ev.xbutton.state |= Button5Mask;
  26716. }
  26717. else if (increment > 0)
  26718. {
  26719. ev.xbutton.button = Button4;
  26720. ev.xbutton.state |= Button4Mask;
  26721. }
  26722. }
  26723. }
  26724. #endif
  26725. class ModuleHandle : public ReferenceCountedObject
  26726. {
  26727. public:
  26728. File file;
  26729. MainCall moduleMain;
  26730. String pluginName;
  26731. static Array <ModuleHandle*>& getActiveModules()
  26732. {
  26733. static Array <ModuleHandle*> activeModules;
  26734. return activeModules;
  26735. }
  26736. static ModuleHandle* findOrCreateModule (const File& file)
  26737. {
  26738. for (int i = getActiveModules().size(); --i >= 0;)
  26739. {
  26740. ModuleHandle* const module = getActiveModules().getUnchecked(i);
  26741. if (module->file == file)
  26742. return module;
  26743. }
  26744. _fpreset(); // (doesn't do any harm)
  26745. ++insideVSTCallback;
  26746. shellUIDToCreate = 0;
  26747. log ("Attempting to load VST: " + file.getFullPathName());
  26748. ScopedPointer <ModuleHandle> m (new ModuleHandle (file));
  26749. if (! m->open())
  26750. m = 0;
  26751. --insideVSTCallback;
  26752. _fpreset(); // (doesn't do any harm)
  26753. return m.release();
  26754. }
  26755. ModuleHandle (const File& file_)
  26756. : file (file_),
  26757. moduleMain (0),
  26758. #if JUCE_WINDOWS || JUCE_LINUX
  26759. hModule (0)
  26760. #elif JUCE_MAC
  26761. fragId (0),
  26762. resHandle (0),
  26763. bundleRef (0),
  26764. resFileId (0)
  26765. #endif
  26766. {
  26767. getActiveModules().add (this);
  26768. #if JUCE_WINDOWS || JUCE_LINUX
  26769. fullParentDirectoryPathName = file_.getParentDirectory().getFullPathName();
  26770. #elif JUCE_MAC
  26771. FSRef ref;
  26772. PlatformUtilities::makeFSRefFromPath (&ref, file_.getParentDirectory().getFullPathName());
  26773. FSGetCatalogInfo (&ref, kFSCatInfoNone, 0, 0, &parentDirFSSpec, 0);
  26774. #endif
  26775. }
  26776. ~ModuleHandle()
  26777. {
  26778. getActiveModules().removeValue (this);
  26779. close();
  26780. }
  26781. juce_UseDebuggingNewOperator
  26782. #if JUCE_WINDOWS || JUCE_LINUX
  26783. void* hModule;
  26784. String fullParentDirectoryPathName;
  26785. bool open()
  26786. {
  26787. #if JUCE_WINDOWS
  26788. static bool timePeriodSet = false;
  26789. if (! timePeriodSet)
  26790. {
  26791. timePeriodSet = true;
  26792. timeBeginPeriod (2);
  26793. }
  26794. #endif
  26795. pluginName = file.getFileNameWithoutExtension();
  26796. hModule = PlatformUtilities::loadDynamicLibrary (file.getFullPathName());
  26797. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "VSTPluginMain");
  26798. if (moduleMain == 0)
  26799. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "main");
  26800. return moduleMain != 0;
  26801. }
  26802. void close()
  26803. {
  26804. _fpreset(); // (doesn't do any harm)
  26805. PlatformUtilities::freeDynamicLibrary (hModule);
  26806. }
  26807. void closeEffect (AEffect* eff)
  26808. {
  26809. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  26810. }
  26811. #else
  26812. CFragConnectionID fragId;
  26813. Handle resHandle;
  26814. CFBundleRef bundleRef;
  26815. FSSpec parentDirFSSpec;
  26816. short resFileId;
  26817. bool open()
  26818. {
  26819. bool ok = false;
  26820. const String filename (file.getFullPathName());
  26821. if (file.hasFileExtension (".vst"))
  26822. {
  26823. const char* const utf8 = filename.toUTF8();
  26824. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  26825. strlen (utf8), file.isDirectory());
  26826. if (url != 0)
  26827. {
  26828. bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  26829. CFRelease (url);
  26830. if (bundleRef != 0)
  26831. {
  26832. if (CFBundleLoadExecutable (bundleRef))
  26833. {
  26834. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("main_macho"));
  26835. if (moduleMain == 0)
  26836. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("VSTPluginMain"));
  26837. if (moduleMain != 0)
  26838. {
  26839. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  26840. if (name != 0)
  26841. {
  26842. if (CFGetTypeID (name) == CFStringGetTypeID())
  26843. {
  26844. char buffer[1024];
  26845. if (CFStringGetCString ((CFStringRef) name, buffer, sizeof (buffer), CFStringGetSystemEncoding()))
  26846. pluginName = buffer;
  26847. }
  26848. }
  26849. if (pluginName.isEmpty())
  26850. pluginName = file.getFileNameWithoutExtension();
  26851. resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  26852. ok = true;
  26853. }
  26854. }
  26855. if (! ok)
  26856. {
  26857. CFBundleUnloadExecutable (bundleRef);
  26858. CFRelease (bundleRef);
  26859. bundleRef = 0;
  26860. }
  26861. }
  26862. }
  26863. }
  26864. #if JUCE_PPC
  26865. else
  26866. {
  26867. FSRef fn;
  26868. if (FSPathMakeRef ((UInt8*) filename.toUTF8(), &fn, 0) == noErr)
  26869. {
  26870. resFileId = FSOpenResFile (&fn, fsRdPerm);
  26871. if (resFileId != -1)
  26872. {
  26873. const int numEffs = Count1Resources ('aEff');
  26874. for (int i = 0; i < numEffs; ++i)
  26875. {
  26876. resHandle = Get1IndResource ('aEff', i + 1);
  26877. if (resHandle != 0)
  26878. {
  26879. OSType type;
  26880. Str255 name;
  26881. SInt16 id;
  26882. GetResInfo (resHandle, &id, &type, name);
  26883. pluginName = String ((const char*) name + 1, name[0]);
  26884. DetachResource (resHandle);
  26885. HLock (resHandle);
  26886. Ptr ptr;
  26887. Str255 errorText;
  26888. OSErr err = GetMemFragment (*resHandle, GetHandleSize (resHandle),
  26889. name, kPrivateCFragCopy,
  26890. &fragId, &ptr, errorText);
  26891. if (err == noErr)
  26892. {
  26893. moduleMain = (MainCall) newMachOFromCFM (ptr);
  26894. ok = true;
  26895. }
  26896. else
  26897. {
  26898. HUnlock (resHandle);
  26899. }
  26900. break;
  26901. }
  26902. }
  26903. if (! ok)
  26904. CloseResFile (resFileId);
  26905. }
  26906. }
  26907. }
  26908. #endif
  26909. return ok;
  26910. }
  26911. void close()
  26912. {
  26913. #if JUCE_PPC
  26914. if (fragId != 0)
  26915. {
  26916. if (moduleMain != 0)
  26917. disposeMachOFromCFM ((void*) moduleMain);
  26918. CloseConnection (&fragId);
  26919. HUnlock (resHandle);
  26920. if (resFileId != 0)
  26921. CloseResFile (resFileId);
  26922. }
  26923. else
  26924. #endif
  26925. if (bundleRef != 0)
  26926. {
  26927. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  26928. if (CFGetRetainCount (bundleRef) == 1)
  26929. CFBundleUnloadExecutable (bundleRef);
  26930. if (CFGetRetainCount (bundleRef) > 0)
  26931. CFRelease (bundleRef);
  26932. }
  26933. }
  26934. void closeEffect (AEffect* eff)
  26935. {
  26936. #if JUCE_PPC
  26937. if (fragId != 0)
  26938. {
  26939. Array<void*> thingsToDelete;
  26940. thingsToDelete.add ((void*) eff->dispatcher);
  26941. thingsToDelete.add ((void*) eff->process);
  26942. thingsToDelete.add ((void*) eff->setParameter);
  26943. thingsToDelete.add ((void*) eff->getParameter);
  26944. thingsToDelete.add ((void*) eff->processReplacing);
  26945. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  26946. for (int i = thingsToDelete.size(); --i >= 0;)
  26947. disposeMachOFromCFM (thingsToDelete[i]);
  26948. }
  26949. else
  26950. #endif
  26951. {
  26952. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  26953. }
  26954. }
  26955. #if JUCE_PPC
  26956. static void* newMachOFromCFM (void* cfmfp)
  26957. {
  26958. if (cfmfp == 0)
  26959. return 0;
  26960. UInt32* const mfp = new UInt32[6];
  26961. mfp[0] = 0x3d800000 | ((UInt32) cfmfp >> 16);
  26962. mfp[1] = 0x618c0000 | ((UInt32) cfmfp & 0xffff);
  26963. mfp[2] = 0x800c0000;
  26964. mfp[3] = 0x804c0004;
  26965. mfp[4] = 0x7c0903a6;
  26966. mfp[5] = 0x4e800420;
  26967. MakeDataExecutable (mfp, sizeof (UInt32) * 6);
  26968. return mfp;
  26969. }
  26970. static void disposeMachOFromCFM (void* ptr)
  26971. {
  26972. delete[] static_cast <UInt32*> (ptr);
  26973. }
  26974. void coerceAEffectFunctionCalls (AEffect* eff)
  26975. {
  26976. if (fragId != 0)
  26977. {
  26978. eff->dispatcher = (AEffectDispatcherProc) newMachOFromCFM ((void*) eff->dispatcher);
  26979. eff->process = (AEffectProcessProc) newMachOFromCFM ((void*) eff->process);
  26980. eff->setParameter = (AEffectSetParameterProc) newMachOFromCFM ((void*) eff->setParameter);
  26981. eff->getParameter = (AEffectGetParameterProc) newMachOFromCFM ((void*) eff->getParameter);
  26982. eff->processReplacing = (AEffectProcessProc) newMachOFromCFM ((void*) eff->processReplacing);
  26983. }
  26984. }
  26985. #endif
  26986. #endif
  26987. };
  26988. /**
  26989. An instance of a plugin, created by a VSTPluginFormat.
  26990. */
  26991. class VSTPluginInstance : public AudioPluginInstance,
  26992. private Timer,
  26993. private AsyncUpdater
  26994. {
  26995. public:
  26996. ~VSTPluginInstance();
  26997. // AudioPluginInstance methods:
  26998. void fillInPluginDescription (PluginDescription& desc) const
  26999. {
  27000. desc.name = name;
  27001. desc.fileOrIdentifier = module->file.getFullPathName();
  27002. desc.uid = getUID();
  27003. desc.lastFileModTime = module->file.getLastModificationTime();
  27004. desc.pluginFormatName = "VST";
  27005. desc.category = getCategory();
  27006. {
  27007. char buffer [kVstMaxVendorStrLen + 8];
  27008. zerostruct (buffer);
  27009. dispatch (effGetVendorString, 0, 0, buffer, 0);
  27010. desc.manufacturerName = buffer;
  27011. }
  27012. desc.version = getVersion();
  27013. desc.numInputChannels = getNumInputChannels();
  27014. desc.numOutputChannels = getNumOutputChannels();
  27015. desc.isInstrument = (effect != 0 && (effect->flags & effFlagsIsSynth) != 0);
  27016. }
  27017. const String getName() const { return name; }
  27018. int getUID() const;
  27019. bool acceptsMidi() const { return wantsMidiMessages; }
  27020. bool producesMidi() const { return dispatch (effCanDo, 0, 0, (void*) "sendVstMidiEvent", 0) > 0; }
  27021. // AudioProcessor methods:
  27022. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  27023. void releaseResources();
  27024. void processBlock (AudioSampleBuffer& buffer,
  27025. MidiBuffer& midiMessages);
  27026. bool hasEditor() const { return effect != 0 && (effect->flags & effFlagsHasEditor) != 0; }
  27027. AudioProcessorEditor* createEditor();
  27028. const String getInputChannelName (int index) const;
  27029. bool isInputChannelStereoPair (int index) const;
  27030. const String getOutputChannelName (int index) const;
  27031. bool isOutputChannelStereoPair (int index) const;
  27032. int getNumParameters() { return effect != 0 ? effect->numParams : 0; }
  27033. float getParameter (int index);
  27034. void setParameter (int index, float newValue);
  27035. const String getParameterName (int index);
  27036. const String getParameterText (int index);
  27037. bool isParameterAutomatable (int index) const;
  27038. int getNumPrograms() { return effect != 0 ? effect->numPrograms : 0; }
  27039. int getCurrentProgram() { return dispatch (effGetProgram, 0, 0, 0, 0); }
  27040. void setCurrentProgram (int index);
  27041. const String getProgramName (int index);
  27042. void changeProgramName (int index, const String& newName);
  27043. void getStateInformation (MemoryBlock& destData);
  27044. void getCurrentProgramStateInformation (MemoryBlock& destData);
  27045. void setStateInformation (const void* data, int sizeInBytes);
  27046. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  27047. void timerCallback();
  27048. void handleAsyncUpdate();
  27049. VstIntPtr handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt);
  27050. juce_UseDebuggingNewOperator
  27051. private:
  27052. friend class VSTPluginWindow;
  27053. friend class VSTPluginFormat;
  27054. AEffect* effect;
  27055. String name;
  27056. CriticalSection lock;
  27057. bool wantsMidiMessages, initialised, isPowerOn;
  27058. mutable StringArray programNames;
  27059. AudioSampleBuffer tempBuffer;
  27060. CriticalSection midiInLock;
  27061. MidiBuffer incomingMidi;
  27062. VSTMidiEventList midiEventsToSend;
  27063. VstTimeInfo vstHostTime;
  27064. ReferenceCountedObjectPtr <ModuleHandle> module;
  27065. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const;
  27066. bool restoreProgramSettings (const fxProgram* const prog);
  27067. const String getCurrentProgramName();
  27068. void setParamsInProgramBlock (fxProgram* const prog);
  27069. void updateStoredProgramNames();
  27070. void initialise();
  27071. void handleMidiFromPlugin (const VstEvents* const events);
  27072. void createTempParameterStore (MemoryBlock& dest);
  27073. void restoreFromTempParameterStore (const MemoryBlock& mb);
  27074. const String getParameterLabel (int index) const;
  27075. bool usesChunks() const throw() { return effect != 0 && (effect->flags & effFlagsProgramChunks) != 0; }
  27076. void getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const;
  27077. void setChunkData (const char* data, int size, bool isPreset);
  27078. bool loadFromFXBFile (const void* data, int numBytes);
  27079. bool saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB);
  27080. int getVersionNumber() const throw() { return effect != 0 ? effect->version : 0; }
  27081. const String getVersion() const;
  27082. const String getCategory() const;
  27083. void setPower (const bool on);
  27084. VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module);
  27085. };
  27086. VSTPluginInstance::VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module_)
  27087. : effect (0),
  27088. wantsMidiMessages (false),
  27089. initialised (false),
  27090. isPowerOn (false),
  27091. tempBuffer (1, 1),
  27092. module (module_)
  27093. {
  27094. try
  27095. {
  27096. _fpreset();
  27097. ++insideVSTCallback;
  27098. name = module->pluginName;
  27099. log ("Creating VST instance: " + name);
  27100. #if JUCE_MAC
  27101. if (module->resFileId != 0)
  27102. UseResFile (module->resFileId);
  27103. #if JUCE_PPC
  27104. if (module->fragId != 0)
  27105. {
  27106. static void* audioMasterCoerced = 0;
  27107. if (audioMasterCoerced == 0)
  27108. audioMasterCoerced = NewCFMFromMachO ((void*) &audioMaster);
  27109. effect = module->moduleMain ((audioMasterCallback) audioMasterCoerced);
  27110. }
  27111. else
  27112. #endif
  27113. #endif
  27114. {
  27115. effect = module->moduleMain (&audioMaster);
  27116. }
  27117. --insideVSTCallback;
  27118. if (effect != 0 && effect->magic == kEffectMagic)
  27119. {
  27120. #if JUCE_PPC
  27121. module->coerceAEffectFunctionCalls (effect);
  27122. #endif
  27123. jassert (effect->resvd2 == 0);
  27124. jassert (effect->object != 0);
  27125. _fpreset(); // some dodgy plugs fuck around with this
  27126. }
  27127. else
  27128. {
  27129. effect = 0;
  27130. }
  27131. }
  27132. catch (...)
  27133. {
  27134. --insideVSTCallback;
  27135. }
  27136. }
  27137. VSTPluginInstance::~VSTPluginInstance()
  27138. {
  27139. const ScopedLock sl (lock);
  27140. jassert (insideVSTCallback == 0);
  27141. if (effect != 0 && effect->magic == kEffectMagic)
  27142. {
  27143. try
  27144. {
  27145. #if JUCE_MAC
  27146. if (module->resFileId != 0)
  27147. UseResFile (module->resFileId);
  27148. #endif
  27149. // Must delete any editors before deleting the plugin instance!
  27150. jassert (getActiveEditor() == 0);
  27151. _fpreset(); // some dodgy plugs fuck around with this
  27152. module->closeEffect (effect);
  27153. }
  27154. catch (...)
  27155. {}
  27156. }
  27157. module = 0;
  27158. effect = 0;
  27159. }
  27160. void VSTPluginInstance::initialise()
  27161. {
  27162. if (initialised || effect == 0)
  27163. return;
  27164. log ("Initialising VST: " + module->pluginName);
  27165. initialised = true;
  27166. dispatch (effIdentify, 0, 0, 0, 0);
  27167. // this code would ask the plugin for its name, but so few plugins
  27168. // actually bother implementing this correctly, that it's better to
  27169. // just ignore it and use the file name instead.
  27170. /* {
  27171. char buffer [256];
  27172. zerostruct (buffer);
  27173. dispatch (effGetEffectName, 0, 0, buffer, 0);
  27174. name = String (buffer).trim();
  27175. if (name.isEmpty())
  27176. name = module->pluginName;
  27177. }
  27178. */
  27179. if (getSampleRate() > 0)
  27180. dispatch (effSetSampleRate, 0, 0, 0, (float) getSampleRate());
  27181. if (getBlockSize() > 0)
  27182. dispatch (effSetBlockSize, 0, jmax (32, getBlockSize()), 0, 0);
  27183. dispatch (effOpen, 0, 0, 0, 0);
  27184. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  27185. getSampleRate(), getBlockSize());
  27186. if (getNumPrograms() > 1)
  27187. setCurrentProgram (0);
  27188. else
  27189. dispatch (effSetProgram, 0, 0, 0, 0);
  27190. int i;
  27191. for (i = effect->numInputs; --i >= 0;)
  27192. dispatch (effConnectInput, i, 1, 0, 0);
  27193. for (i = effect->numOutputs; --i >= 0;)
  27194. dispatch (effConnectOutput, i, 1, 0, 0);
  27195. updateStoredProgramNames();
  27196. wantsMidiMessages = dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0;
  27197. setLatencySamples (effect->initialDelay);
  27198. }
  27199. void VSTPluginInstance::prepareToPlay (double sampleRate_,
  27200. int samplesPerBlockExpected)
  27201. {
  27202. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  27203. sampleRate_, samplesPerBlockExpected);
  27204. setLatencySamples (effect->initialDelay);
  27205. vstHostTime.tempo = 120.0;
  27206. vstHostTime.timeSigNumerator = 4;
  27207. vstHostTime.timeSigDenominator = 4;
  27208. vstHostTime.sampleRate = sampleRate_;
  27209. vstHostTime.samplePos = 0;
  27210. vstHostTime.flags = kVstNanosValid; /*| kVstTransportPlaying | kVstTempoValid | kVstTimeSigValid*/;
  27211. initialise();
  27212. if (initialised)
  27213. {
  27214. wantsMidiMessages = wantsMidiMessages
  27215. || (dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0);
  27216. if (wantsMidiMessages)
  27217. midiEventsToSend.ensureSize (256);
  27218. else
  27219. midiEventsToSend.freeEvents();
  27220. incomingMidi.clear();
  27221. dispatch (effSetSampleRate, 0, 0, 0, (float) sampleRate_);
  27222. dispatch (effSetBlockSize, 0, jmax (16, samplesPerBlockExpected), 0, 0);
  27223. tempBuffer.setSize (jmax (1, effect->numOutputs), samplesPerBlockExpected);
  27224. if (! isPowerOn)
  27225. setPower (true);
  27226. // dodgy hack to force some plugins to initialise the sample rate..
  27227. if ((! hasEditor()) && getNumParameters() > 0)
  27228. {
  27229. const float old = getParameter (0);
  27230. setParameter (0, (old < 0.5f) ? 1.0f : 0.0f);
  27231. setParameter (0, old);
  27232. }
  27233. dispatch (effStartProcess, 0, 0, 0, 0);
  27234. }
  27235. }
  27236. void VSTPluginInstance::releaseResources()
  27237. {
  27238. if (initialised)
  27239. {
  27240. dispatch (effStopProcess, 0, 0, 0, 0);
  27241. setPower (false);
  27242. }
  27243. tempBuffer.setSize (1, 1);
  27244. incomingMidi.clear();
  27245. midiEventsToSend.freeEvents();
  27246. }
  27247. void VSTPluginInstance::processBlock (AudioSampleBuffer& buffer,
  27248. MidiBuffer& midiMessages)
  27249. {
  27250. const int numSamples = buffer.getNumSamples();
  27251. if (initialised)
  27252. {
  27253. AudioPlayHead* playHead = getPlayHead();
  27254. if (playHead != 0)
  27255. {
  27256. AudioPlayHead::CurrentPositionInfo position;
  27257. playHead->getCurrentPosition (position);
  27258. vstHostTime.tempo = position.bpm;
  27259. vstHostTime.timeSigNumerator = position.timeSigNumerator;
  27260. vstHostTime.timeSigDenominator = position.timeSigDenominator;
  27261. vstHostTime.ppqPos = position.ppqPosition;
  27262. vstHostTime.barStartPos = position.ppqPositionOfLastBarStart;
  27263. vstHostTime.flags |= kVstTempoValid | kVstTimeSigValid | kVstPpqPosValid | kVstBarsValid;
  27264. if (position.isPlaying)
  27265. vstHostTime.flags |= kVstTransportPlaying;
  27266. else
  27267. vstHostTime.flags &= ~kVstTransportPlaying;
  27268. }
  27269. vstHostTime.nanoSeconds = getVSTHostTimeNanoseconds();
  27270. if (wantsMidiMessages)
  27271. {
  27272. midiEventsToSend.clear();
  27273. midiEventsToSend.ensureSize (1);
  27274. MidiBuffer::Iterator iter (midiMessages);
  27275. const uint8* midiData;
  27276. int numBytesOfMidiData, samplePosition;
  27277. while (iter.getNextEvent (midiData, numBytesOfMidiData, samplePosition))
  27278. {
  27279. midiEventsToSend.addEvent (midiData, numBytesOfMidiData,
  27280. jlimit (0, numSamples - 1, samplePosition));
  27281. }
  27282. try
  27283. {
  27284. effect->dispatcher (effect, effProcessEvents, 0, 0, midiEventsToSend.events, 0);
  27285. }
  27286. catch (...)
  27287. {}
  27288. }
  27289. _clearfp();
  27290. if ((effect->flags & effFlagsCanReplacing) != 0)
  27291. {
  27292. try
  27293. {
  27294. effect->processReplacing (effect, buffer.getArrayOfChannels(), buffer.getArrayOfChannels(), numSamples);
  27295. }
  27296. catch (...)
  27297. {}
  27298. }
  27299. else
  27300. {
  27301. tempBuffer.setSize (effect->numOutputs, numSamples);
  27302. tempBuffer.clear();
  27303. try
  27304. {
  27305. effect->process (effect, buffer.getArrayOfChannels(), tempBuffer.getArrayOfChannels(), numSamples);
  27306. }
  27307. catch (...)
  27308. {}
  27309. for (int i = effect->numOutputs; --i >= 0;)
  27310. buffer.copyFrom (i, 0, tempBuffer.getSampleData (i), numSamples);
  27311. }
  27312. }
  27313. else
  27314. {
  27315. // Not initialised, so just bypass..
  27316. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  27317. buffer.clear (i, 0, buffer.getNumSamples());
  27318. }
  27319. {
  27320. // copy any incoming midi..
  27321. const ScopedLock sl (midiInLock);
  27322. midiMessages.swapWith (incomingMidi);
  27323. incomingMidi.clear();
  27324. }
  27325. }
  27326. void VSTPluginInstance::handleMidiFromPlugin (const VstEvents* const events)
  27327. {
  27328. if (events != 0)
  27329. {
  27330. const ScopedLock sl (midiInLock);
  27331. VSTMidiEventList::addEventsToMidiBuffer (events, incomingMidi);
  27332. }
  27333. }
  27334. static Array <VSTPluginWindow*> activeVSTWindows;
  27335. class VSTPluginWindow : public AudioProcessorEditor,
  27336. #if ! JUCE_MAC
  27337. public ComponentMovementWatcher,
  27338. #endif
  27339. public Timer
  27340. {
  27341. public:
  27342. VSTPluginWindow (VSTPluginInstance& plugin_)
  27343. : AudioProcessorEditor (&plugin_),
  27344. #if ! JUCE_MAC
  27345. ComponentMovementWatcher (this),
  27346. #endif
  27347. plugin (plugin_),
  27348. isOpen (false),
  27349. wasShowing (false),
  27350. pluginRefusesToResize (false),
  27351. pluginWantsKeys (false),
  27352. alreadyInside (false),
  27353. recursiveResize (false)
  27354. {
  27355. #if JUCE_WINDOWS
  27356. sizeCheckCount = 0;
  27357. pluginHWND = 0;
  27358. #elif JUCE_LINUX
  27359. pluginWindow = None;
  27360. pluginProc = None;
  27361. #else
  27362. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  27363. #endif
  27364. activeVSTWindows.add (this);
  27365. setSize (1, 1);
  27366. setOpaque (true);
  27367. setVisible (true);
  27368. }
  27369. ~VSTPluginWindow()
  27370. {
  27371. #if JUCE_MAC
  27372. innerWrapper = 0;
  27373. #else
  27374. closePluginWindow();
  27375. #endif
  27376. activeVSTWindows.removeValue (this);
  27377. plugin.editorBeingDeleted (this);
  27378. }
  27379. #if ! JUCE_MAC
  27380. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  27381. {
  27382. if (recursiveResize)
  27383. return;
  27384. Component* const topComp = getTopLevelComponent();
  27385. if (topComp->getPeer() != 0)
  27386. {
  27387. const Point<int> pos (relativePositionToOtherComponent (topComp, Point<int>()));
  27388. recursiveResize = true;
  27389. #if JUCE_WINDOWS
  27390. if (pluginHWND != 0)
  27391. MoveWindow (pluginHWND, pos.getX(), pos.getY(), getWidth(), getHeight(), TRUE);
  27392. #elif JUCE_LINUX
  27393. if (pluginWindow != 0)
  27394. {
  27395. XResizeWindow (display, pluginWindow, getWidth(), getHeight());
  27396. XMoveWindow (display, pluginWindow, pos.getX(), pos.getY());
  27397. XMapRaised (display, pluginWindow);
  27398. }
  27399. #endif
  27400. recursiveResize = false;
  27401. }
  27402. }
  27403. void componentVisibilityChanged (Component&)
  27404. {
  27405. const bool isShowingNow = isShowing();
  27406. if (wasShowing != isShowingNow)
  27407. {
  27408. wasShowing = isShowingNow;
  27409. if (isShowingNow)
  27410. openPluginWindow();
  27411. else
  27412. closePluginWindow();
  27413. }
  27414. componentMovedOrResized (true, true);
  27415. }
  27416. void componentPeerChanged()
  27417. {
  27418. closePluginWindow();
  27419. openPluginWindow();
  27420. }
  27421. #endif
  27422. bool keyStateChanged (bool)
  27423. {
  27424. return pluginWantsKeys;
  27425. }
  27426. bool keyPressed (const KeyPress&)
  27427. {
  27428. return pluginWantsKeys;
  27429. }
  27430. #if JUCE_MAC
  27431. void paint (Graphics& g)
  27432. {
  27433. g.fillAll (Colours::black);
  27434. }
  27435. #else
  27436. void paint (Graphics& g)
  27437. {
  27438. if (isOpen)
  27439. {
  27440. ComponentPeer* const peer = getPeer();
  27441. if (peer != 0)
  27442. {
  27443. const Point<int> pos (getScreenPosition() - peer->getScreenPosition());
  27444. peer->addMaskedRegion (pos.getX(), pos.getY(), getWidth(), getHeight());
  27445. #if JUCE_LINUX
  27446. if (pluginWindow != 0)
  27447. {
  27448. const Rectangle<int> clip (g.getClipBounds());
  27449. XEvent ev;
  27450. zerostruct (ev);
  27451. ev.xexpose.type = Expose;
  27452. ev.xexpose.display = display;
  27453. ev.xexpose.window = pluginWindow;
  27454. ev.xexpose.x = clip.getX();
  27455. ev.xexpose.y = clip.getY();
  27456. ev.xexpose.width = clip.getWidth();
  27457. ev.xexpose.height = clip.getHeight();
  27458. sendEventToChild (&ev);
  27459. }
  27460. #endif
  27461. }
  27462. }
  27463. else
  27464. {
  27465. g.fillAll (Colours::black);
  27466. }
  27467. }
  27468. #endif
  27469. void timerCallback()
  27470. {
  27471. #if JUCE_WINDOWS
  27472. if (--sizeCheckCount <= 0)
  27473. {
  27474. sizeCheckCount = 10;
  27475. checkPluginWindowSize();
  27476. }
  27477. #endif
  27478. try
  27479. {
  27480. static bool reentrant = false;
  27481. if (! reentrant)
  27482. {
  27483. reentrant = true;
  27484. plugin.dispatch (effEditIdle, 0, 0, 0, 0);
  27485. reentrant = false;
  27486. }
  27487. }
  27488. catch (...)
  27489. {}
  27490. }
  27491. void mouseDown (const MouseEvent& e)
  27492. {
  27493. #if JUCE_LINUX
  27494. if (pluginWindow == 0)
  27495. return;
  27496. toFront (true);
  27497. XEvent ev;
  27498. zerostruct (ev);
  27499. ev.xbutton.display = display;
  27500. ev.xbutton.type = ButtonPress;
  27501. ev.xbutton.window = pluginWindow;
  27502. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  27503. ev.xbutton.time = CurrentTime;
  27504. ev.xbutton.x = e.x;
  27505. ev.xbutton.y = e.y;
  27506. ev.xbutton.x_root = e.getScreenX();
  27507. ev.xbutton.y_root = e.getScreenY();
  27508. translateJuceToXButtonModifiers (e, ev);
  27509. sendEventToChild (&ev);
  27510. #elif JUCE_WINDOWS
  27511. (void) e;
  27512. toFront (true);
  27513. #endif
  27514. }
  27515. void broughtToFront()
  27516. {
  27517. activeVSTWindows.removeValue (this);
  27518. activeVSTWindows.add (this);
  27519. #if JUCE_MAC
  27520. dispatch (effEditTop, 0, 0, 0, 0);
  27521. #endif
  27522. }
  27523. juce_UseDebuggingNewOperator
  27524. private:
  27525. VSTPluginInstance& plugin;
  27526. bool isOpen, wasShowing, recursiveResize;
  27527. bool pluginWantsKeys, pluginRefusesToResize, alreadyInside;
  27528. #if JUCE_WINDOWS
  27529. HWND pluginHWND;
  27530. void* originalWndProc;
  27531. int sizeCheckCount;
  27532. #elif JUCE_LINUX
  27533. Window pluginWindow;
  27534. EventProcPtr pluginProc;
  27535. #endif
  27536. #if JUCE_MAC
  27537. void openPluginWindow (WindowRef parentWindow)
  27538. {
  27539. if (isOpen || parentWindow == 0)
  27540. return;
  27541. isOpen = true;
  27542. ERect* rect = 0;
  27543. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27544. dispatch (effEditOpen, 0, 0, parentWindow, 0);
  27545. // do this before and after like in the steinberg example
  27546. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27547. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  27548. // Install keyboard hooks
  27549. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  27550. // double-check it's not too tiny
  27551. int w = 250, h = 150;
  27552. if (rect != 0)
  27553. {
  27554. w = rect->right - rect->left;
  27555. h = rect->bottom - rect->top;
  27556. if (w == 0 || h == 0)
  27557. {
  27558. w = 250;
  27559. h = 150;
  27560. }
  27561. }
  27562. w = jmax (w, 32);
  27563. h = jmax (h, 32);
  27564. setSize (w, h);
  27565. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  27566. repaint();
  27567. }
  27568. #else
  27569. void openPluginWindow()
  27570. {
  27571. if (isOpen || getWindowHandle() == 0)
  27572. return;
  27573. log ("Opening VST UI: " + plugin.name);
  27574. isOpen = true;
  27575. ERect* rect = 0;
  27576. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27577. dispatch (effEditOpen, 0, 0, getWindowHandle(), 0);
  27578. // do this before and after like in the steinberg example
  27579. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27580. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  27581. // Install keyboard hooks
  27582. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  27583. #if JUCE_WINDOWS
  27584. originalWndProc = 0;
  27585. pluginHWND = GetWindow ((HWND) getWindowHandle(), GW_CHILD);
  27586. if (pluginHWND == 0)
  27587. {
  27588. isOpen = false;
  27589. setSize (300, 150);
  27590. return;
  27591. }
  27592. #pragma warning (push)
  27593. #pragma warning (disable: 4244)
  27594. originalWndProc = (void*) GetWindowLongPtr (pluginHWND, GWLP_WNDPROC);
  27595. if (! pluginWantsKeys)
  27596. SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) vstHookWndProc);
  27597. #pragma warning (pop)
  27598. int w, h;
  27599. RECT r;
  27600. GetWindowRect (pluginHWND, &r);
  27601. w = r.right - r.left;
  27602. h = r.bottom - r.top;
  27603. if (rect != 0)
  27604. {
  27605. const int rw = rect->right - rect->left;
  27606. const int rh = rect->bottom - rect->top;
  27607. if ((rw > 50 && rh > 50 && rw < 2000 && rh < 2000 && rw != w && rh != h)
  27608. || ((w == 0 && rw > 0) || (h == 0 && rh > 0)))
  27609. {
  27610. // very dodgy logic to decide which size is right.
  27611. if (abs (rw - w) > 350 || abs (rh - h) > 350)
  27612. {
  27613. SetWindowPos (pluginHWND, 0,
  27614. 0, 0, rw, rh,
  27615. SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  27616. GetWindowRect (pluginHWND, &r);
  27617. w = r.right - r.left;
  27618. h = r.bottom - r.top;
  27619. pluginRefusesToResize = (w != rw) || (h != rh);
  27620. w = rw;
  27621. h = rh;
  27622. }
  27623. }
  27624. }
  27625. #elif JUCE_LINUX
  27626. pluginWindow = getChildWindow ((Window) getWindowHandle());
  27627. if (pluginWindow != 0)
  27628. pluginProc = (EventProcPtr) getPropertyFromXWindow (pluginWindow,
  27629. XInternAtom (display, "_XEventProc", False));
  27630. int w = 250, h = 150;
  27631. if (rect != 0)
  27632. {
  27633. w = rect->right - rect->left;
  27634. h = rect->bottom - rect->top;
  27635. if (w == 0 || h == 0)
  27636. {
  27637. w = 250;
  27638. h = 150;
  27639. }
  27640. }
  27641. if (pluginWindow != 0)
  27642. XMapRaised (display, pluginWindow);
  27643. #endif
  27644. // double-check it's not too tiny
  27645. w = jmax (w, 32);
  27646. h = jmax (h, 32);
  27647. setSize (w, h);
  27648. #if JUCE_WINDOWS
  27649. checkPluginWindowSize();
  27650. #endif
  27651. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  27652. repaint();
  27653. }
  27654. #endif
  27655. #if ! JUCE_MAC
  27656. void closePluginWindow()
  27657. {
  27658. if (isOpen)
  27659. {
  27660. log ("Closing VST UI: " + plugin.getName());
  27661. isOpen = false;
  27662. dispatch (effEditClose, 0, 0, 0, 0);
  27663. #if JUCE_WINDOWS
  27664. #pragma warning (push)
  27665. #pragma warning (disable: 4244)
  27666. if (pluginHWND != 0 && IsWindow (pluginHWND))
  27667. SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) originalWndProc);
  27668. #pragma warning (pop)
  27669. stopTimer();
  27670. if (pluginHWND != 0 && IsWindow (pluginHWND))
  27671. DestroyWindow (pluginHWND);
  27672. pluginHWND = 0;
  27673. #elif JUCE_LINUX
  27674. stopTimer();
  27675. pluginWindow = 0;
  27676. pluginProc = 0;
  27677. #endif
  27678. }
  27679. }
  27680. #endif
  27681. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt)
  27682. {
  27683. return plugin.dispatch (opcode, index, value, ptr, opt);
  27684. }
  27685. #if JUCE_WINDOWS
  27686. void checkPluginWindowSize()
  27687. {
  27688. RECT r;
  27689. GetWindowRect (pluginHWND, &r);
  27690. const int w = r.right - r.left;
  27691. const int h = r.bottom - r.top;
  27692. if (isShowing() && w > 0 && h > 0
  27693. && (w != getWidth() || h != getHeight())
  27694. && ! pluginRefusesToResize)
  27695. {
  27696. setSize (w, h);
  27697. sizeCheckCount = 0;
  27698. }
  27699. }
  27700. // hooks to get keyboard events from VST windows..
  27701. static LRESULT CALLBACK vstHookWndProc (HWND hW, UINT message, WPARAM wParam, LPARAM lParam)
  27702. {
  27703. for (int i = activeVSTWindows.size(); --i >= 0;)
  27704. {
  27705. const VSTPluginWindow* const w = activeVSTWindows.getUnchecked (i);
  27706. if (w->pluginHWND == hW)
  27707. {
  27708. if (message == WM_CHAR
  27709. || message == WM_KEYDOWN
  27710. || message == WM_SYSKEYDOWN
  27711. || message == WM_KEYUP
  27712. || message == WM_SYSKEYUP
  27713. || message == WM_APPCOMMAND)
  27714. {
  27715. SendMessage ((HWND) w->getTopLevelComponent()->getWindowHandle(),
  27716. message, wParam, lParam);
  27717. }
  27718. return CallWindowProc ((WNDPROC) (w->originalWndProc),
  27719. (HWND) w->pluginHWND,
  27720. message,
  27721. wParam,
  27722. lParam);
  27723. }
  27724. }
  27725. return DefWindowProc (hW, message, wParam, lParam);
  27726. }
  27727. #endif
  27728. #if JUCE_LINUX
  27729. // overload mouse/keyboard events to forward them to the plugin's inner window..
  27730. void sendEventToChild (XEvent* event)
  27731. {
  27732. if (pluginProc != 0)
  27733. {
  27734. // if the plugin publishes an event procedure, pass the event directly..
  27735. pluginProc (event);
  27736. }
  27737. else if (pluginWindow != 0)
  27738. {
  27739. // if the plugin has a window, then send the event to the window so that
  27740. // its message thread will pick it up..
  27741. XSendEvent (display, pluginWindow, False, 0L, event);
  27742. XFlush (display);
  27743. }
  27744. }
  27745. void mouseEnter (const MouseEvent& e)
  27746. {
  27747. if (pluginWindow != 0)
  27748. {
  27749. XEvent ev;
  27750. zerostruct (ev);
  27751. ev.xcrossing.display = display;
  27752. ev.xcrossing.type = EnterNotify;
  27753. ev.xcrossing.window = pluginWindow;
  27754. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  27755. ev.xcrossing.time = CurrentTime;
  27756. ev.xcrossing.x = e.x;
  27757. ev.xcrossing.y = e.y;
  27758. ev.xcrossing.x_root = e.getScreenX();
  27759. ev.xcrossing.y_root = e.getScreenY();
  27760. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  27761. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  27762. translateJuceToXCrossingModifiers (e, ev);
  27763. sendEventToChild (&ev);
  27764. }
  27765. }
  27766. void mouseExit (const MouseEvent& e)
  27767. {
  27768. if (pluginWindow != 0)
  27769. {
  27770. XEvent ev;
  27771. zerostruct (ev);
  27772. ev.xcrossing.display = display;
  27773. ev.xcrossing.type = LeaveNotify;
  27774. ev.xcrossing.window = pluginWindow;
  27775. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  27776. ev.xcrossing.time = CurrentTime;
  27777. ev.xcrossing.x = e.x;
  27778. ev.xcrossing.y = e.y;
  27779. ev.xcrossing.x_root = e.getScreenX();
  27780. ev.xcrossing.y_root = e.getScreenY();
  27781. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  27782. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  27783. ev.xcrossing.focus = hasKeyboardFocus (true); // TODO - yes ?
  27784. translateJuceToXCrossingModifiers (e, ev);
  27785. sendEventToChild (&ev);
  27786. }
  27787. }
  27788. void mouseMove (const MouseEvent& e)
  27789. {
  27790. if (pluginWindow != 0)
  27791. {
  27792. XEvent ev;
  27793. zerostruct (ev);
  27794. ev.xmotion.display = display;
  27795. ev.xmotion.type = MotionNotify;
  27796. ev.xmotion.window = pluginWindow;
  27797. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  27798. ev.xmotion.time = CurrentTime;
  27799. ev.xmotion.is_hint = NotifyNormal;
  27800. ev.xmotion.x = e.x;
  27801. ev.xmotion.y = e.y;
  27802. ev.xmotion.x_root = e.getScreenX();
  27803. ev.xmotion.y_root = e.getScreenY();
  27804. sendEventToChild (&ev);
  27805. }
  27806. }
  27807. void mouseDrag (const MouseEvent& e)
  27808. {
  27809. if (pluginWindow != 0)
  27810. {
  27811. XEvent ev;
  27812. zerostruct (ev);
  27813. ev.xmotion.display = display;
  27814. ev.xmotion.type = MotionNotify;
  27815. ev.xmotion.window = pluginWindow;
  27816. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  27817. ev.xmotion.time = CurrentTime;
  27818. ev.xmotion.x = e.x ;
  27819. ev.xmotion.y = e.y;
  27820. ev.xmotion.x_root = e.getScreenX();
  27821. ev.xmotion.y_root = e.getScreenY();
  27822. ev.xmotion.is_hint = NotifyNormal;
  27823. translateJuceToXMotionModifiers (e, ev);
  27824. sendEventToChild (&ev);
  27825. }
  27826. }
  27827. void mouseUp (const MouseEvent& e)
  27828. {
  27829. if (pluginWindow != 0)
  27830. {
  27831. XEvent ev;
  27832. zerostruct (ev);
  27833. ev.xbutton.display = display;
  27834. ev.xbutton.type = ButtonRelease;
  27835. ev.xbutton.window = pluginWindow;
  27836. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  27837. ev.xbutton.time = CurrentTime;
  27838. ev.xbutton.x = e.x;
  27839. ev.xbutton.y = e.y;
  27840. ev.xbutton.x_root = e.getScreenX();
  27841. ev.xbutton.y_root = e.getScreenY();
  27842. translateJuceToXButtonModifiers (e, ev);
  27843. sendEventToChild (&ev);
  27844. }
  27845. }
  27846. void mouseWheelMove (const MouseEvent& e,
  27847. float incrementX,
  27848. float incrementY)
  27849. {
  27850. if (pluginWindow != 0)
  27851. {
  27852. XEvent ev;
  27853. zerostruct (ev);
  27854. ev.xbutton.display = display;
  27855. ev.xbutton.type = ButtonPress;
  27856. ev.xbutton.window = pluginWindow;
  27857. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  27858. ev.xbutton.time = CurrentTime;
  27859. ev.xbutton.x = e.x;
  27860. ev.xbutton.y = e.y;
  27861. ev.xbutton.x_root = e.getScreenX();
  27862. ev.xbutton.y_root = e.getScreenY();
  27863. translateJuceToXMouseWheelModifiers (e, incrementY, ev);
  27864. sendEventToChild (&ev);
  27865. // TODO - put a usleep here ?
  27866. ev.xbutton.type = ButtonRelease;
  27867. sendEventToChild (&ev);
  27868. }
  27869. }
  27870. #endif
  27871. #if JUCE_MAC
  27872. #if ! JUCE_SUPPORT_CARBON
  27873. #error "To build VSTs, you need to enable the JUCE_SUPPORT_CARBON flag in your config!"
  27874. #endif
  27875. class InnerWrapperComponent : public CarbonViewWrapperComponent
  27876. {
  27877. public:
  27878. InnerWrapperComponent (VSTPluginWindow* const owner_)
  27879. : owner (owner_),
  27880. alreadyInside (false)
  27881. {
  27882. }
  27883. ~InnerWrapperComponent()
  27884. {
  27885. deleteWindow();
  27886. }
  27887. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  27888. {
  27889. owner->openPluginWindow (windowRef);
  27890. return 0;
  27891. }
  27892. void removeView (HIViewRef)
  27893. {
  27894. owner->dispatch (effEditClose, 0, 0, 0, 0);
  27895. owner->dispatch (effEditSleep, 0, 0, 0, 0);
  27896. }
  27897. bool getEmbeddedViewSize (int& w, int& h)
  27898. {
  27899. ERect* rect = 0;
  27900. owner->dispatch (effEditGetRect, 0, 0, &rect, 0);
  27901. w = rect->right - rect->left;
  27902. h = rect->bottom - rect->top;
  27903. return true;
  27904. }
  27905. void mouseDown (int x, int y)
  27906. {
  27907. if (! alreadyInside)
  27908. {
  27909. alreadyInside = true;
  27910. getTopLevelComponent()->toFront (true);
  27911. owner->dispatch (effEditMouse, x, y, 0, 0);
  27912. alreadyInside = false;
  27913. }
  27914. else
  27915. {
  27916. PostEvent (::mouseDown, 0);
  27917. }
  27918. }
  27919. void paint()
  27920. {
  27921. ComponentPeer* const peer = getPeer();
  27922. if (peer != 0)
  27923. {
  27924. const Point<int> pos (getScreenPosition() - peer->getScreenPosition());
  27925. ERect r;
  27926. r.left = pos.getX();
  27927. r.right = r.left + getWidth();
  27928. r.top = pos.getY();
  27929. r.bottom = r.top + getHeight();
  27930. owner->dispatch (effEditDraw, 0, 0, &r, 0);
  27931. }
  27932. }
  27933. private:
  27934. VSTPluginWindow* const owner;
  27935. bool alreadyInside;
  27936. };
  27937. friend class InnerWrapperComponent;
  27938. ScopedPointer <InnerWrapperComponent> innerWrapper;
  27939. void resized()
  27940. {
  27941. innerWrapper->setSize (getWidth(), getHeight());
  27942. }
  27943. #endif
  27944. };
  27945. AudioProcessorEditor* VSTPluginInstance::createEditor()
  27946. {
  27947. if (hasEditor())
  27948. return new VSTPluginWindow (*this);
  27949. return 0;
  27950. }
  27951. void VSTPluginInstance::handleAsyncUpdate()
  27952. {
  27953. // indicates that something about the plugin has changed..
  27954. updateHostDisplay();
  27955. }
  27956. bool VSTPluginInstance::restoreProgramSettings (const fxProgram* const prog)
  27957. {
  27958. if (vst_swap (prog->chunkMagic) == 'CcnK' && vst_swap (prog->fxMagic) == 'FxCk')
  27959. {
  27960. changeProgramName (getCurrentProgram(), prog->prgName);
  27961. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  27962. setParameter (i, vst_swapFloat (prog->params[i]));
  27963. return true;
  27964. }
  27965. return false;
  27966. }
  27967. bool VSTPluginInstance::loadFromFXBFile (const void* const data,
  27968. const int dataSize)
  27969. {
  27970. if (dataSize < 28)
  27971. return false;
  27972. const fxSet* const set = (const fxSet*) data;
  27973. if ((vst_swap (set->chunkMagic) != 'CcnK' && vst_swap (set->chunkMagic) != 'KncC')
  27974. || vst_swap (set->version) > fxbVersionNum)
  27975. return false;
  27976. if (vst_swap (set->fxMagic) == 'FxBk')
  27977. {
  27978. // bank of programs
  27979. if (vst_swap (set->numPrograms) >= 0)
  27980. {
  27981. const int oldProg = getCurrentProgram();
  27982. const int numParams = vst_swap (((const fxProgram*) (set->programs))->numParams);
  27983. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  27984. for (int i = 0; i < vst_swap (set->numPrograms); ++i)
  27985. {
  27986. if (i != oldProg)
  27987. {
  27988. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + i * progLen);
  27989. if (((const char*) prog) - ((const char*) set) >= dataSize)
  27990. return false;
  27991. if (vst_swap (set->numPrograms) > 0)
  27992. setCurrentProgram (i);
  27993. if (! restoreProgramSettings (prog))
  27994. return false;
  27995. }
  27996. }
  27997. if (vst_swap (set->numPrograms) > 0)
  27998. setCurrentProgram (oldProg);
  27999. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + oldProg * progLen);
  28000. if (((const char*) prog) - ((const char*) set) >= dataSize)
  28001. return false;
  28002. if (! restoreProgramSettings (prog))
  28003. return false;
  28004. }
  28005. }
  28006. else if (vst_swap (set->fxMagic) == 'FxCk')
  28007. {
  28008. // single program
  28009. const fxProgram* const prog = (const fxProgram*) data;
  28010. if (vst_swap (prog->chunkMagic) != 'CcnK')
  28011. return false;
  28012. changeProgramName (getCurrentProgram(), prog->prgName);
  28013. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  28014. setParameter (i, vst_swapFloat (prog->params[i]));
  28015. }
  28016. else if (vst_swap (set->fxMagic) == 'FBCh' || vst_swap (set->fxMagic) == 'hCBF')
  28017. {
  28018. // non-preset chunk
  28019. const fxChunkSet* const cset = (const fxChunkSet*) data;
  28020. if (vst_swap (cset->chunkSize) + sizeof (fxChunkSet) - 8 > (unsigned int) dataSize)
  28021. return false;
  28022. setChunkData (cset->chunk, vst_swap (cset->chunkSize), false);
  28023. }
  28024. else if (vst_swap (set->fxMagic) == 'FPCh' || vst_swap (set->fxMagic) == 'hCPF')
  28025. {
  28026. // preset chunk
  28027. const fxProgramSet* const cset = (const fxProgramSet*) data;
  28028. if (vst_swap (cset->chunkSize) + sizeof (fxProgramSet) - 8 > (unsigned int) dataSize)
  28029. return false;
  28030. setChunkData (cset->chunk, vst_swap (cset->chunkSize), true);
  28031. changeProgramName (getCurrentProgram(), cset->name);
  28032. }
  28033. else
  28034. {
  28035. return false;
  28036. }
  28037. return true;
  28038. }
  28039. void VSTPluginInstance::setParamsInProgramBlock (fxProgram* const prog)
  28040. {
  28041. const int numParams = getNumParameters();
  28042. prog->chunkMagic = vst_swap ('CcnK');
  28043. prog->byteSize = 0;
  28044. prog->fxMagic = vst_swap ('FxCk');
  28045. prog->version = vst_swap (fxbVersionNum);
  28046. prog->fxID = vst_swap (getUID());
  28047. prog->fxVersion = vst_swap (getVersionNumber());
  28048. prog->numParams = vst_swap (numParams);
  28049. getCurrentProgramName().copyToCString (prog->prgName, sizeof (prog->prgName) - 1);
  28050. for (int i = 0; i < numParams; ++i)
  28051. prog->params[i] = vst_swapFloat (getParameter (i));
  28052. }
  28053. bool VSTPluginInstance::saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB)
  28054. {
  28055. const int numPrograms = getNumPrograms();
  28056. const int numParams = getNumParameters();
  28057. if (usesChunks())
  28058. {
  28059. if (isFXB)
  28060. {
  28061. MemoryBlock chunk;
  28062. getChunkData (chunk, false, maxSizeMB);
  28063. const size_t totalLen = sizeof (fxChunkSet) + chunk.getSize() - 8;
  28064. dest.setSize (totalLen, true);
  28065. fxChunkSet* const set = (fxChunkSet*) dest.getData();
  28066. set->chunkMagic = vst_swap ('CcnK');
  28067. set->byteSize = 0;
  28068. set->fxMagic = vst_swap ('FBCh');
  28069. set->version = vst_swap (fxbVersionNum);
  28070. set->fxID = vst_swap (getUID());
  28071. set->fxVersion = vst_swap (getVersionNumber());
  28072. set->numPrograms = vst_swap (numPrograms);
  28073. set->chunkSize = vst_swap ((long) chunk.getSize());
  28074. chunk.copyTo (set->chunk, 0, chunk.getSize());
  28075. }
  28076. else
  28077. {
  28078. MemoryBlock chunk;
  28079. getChunkData (chunk, true, maxSizeMB);
  28080. const size_t totalLen = sizeof (fxProgramSet) + chunk.getSize() - 8;
  28081. dest.setSize (totalLen, true);
  28082. fxProgramSet* const set = (fxProgramSet*) dest.getData();
  28083. set->chunkMagic = vst_swap ('CcnK');
  28084. set->byteSize = 0;
  28085. set->fxMagic = vst_swap ('FPCh');
  28086. set->version = vst_swap (fxbVersionNum);
  28087. set->fxID = vst_swap (getUID());
  28088. set->fxVersion = vst_swap (getVersionNumber());
  28089. set->numPrograms = vst_swap (numPrograms);
  28090. set->chunkSize = vst_swap ((long) chunk.getSize());
  28091. getCurrentProgramName().copyToCString (set->name, sizeof (set->name) - 1);
  28092. chunk.copyTo (set->chunk, 0, chunk.getSize());
  28093. }
  28094. }
  28095. else
  28096. {
  28097. if (isFXB)
  28098. {
  28099. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  28100. const int len = (sizeof (fxSet) - sizeof (fxProgram)) + progLen * jmax (1, numPrograms);
  28101. dest.setSize (len, true);
  28102. fxSet* const set = (fxSet*) dest.getData();
  28103. set->chunkMagic = vst_swap ('CcnK');
  28104. set->byteSize = 0;
  28105. set->fxMagic = vst_swap ('FxBk');
  28106. set->version = vst_swap (fxbVersionNum);
  28107. set->fxID = vst_swap (getUID());
  28108. set->fxVersion = vst_swap (getVersionNumber());
  28109. set->numPrograms = vst_swap (numPrograms);
  28110. const int oldProgram = getCurrentProgram();
  28111. MemoryBlock oldSettings;
  28112. createTempParameterStore (oldSettings);
  28113. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + oldProgram * progLen));
  28114. for (int i = 0; i < numPrograms; ++i)
  28115. {
  28116. if (i != oldProgram)
  28117. {
  28118. setCurrentProgram (i);
  28119. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + i * progLen));
  28120. }
  28121. }
  28122. setCurrentProgram (oldProgram);
  28123. restoreFromTempParameterStore (oldSettings);
  28124. }
  28125. else
  28126. {
  28127. const int totalLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  28128. dest.setSize (totalLen, true);
  28129. setParamsInProgramBlock ((fxProgram*) dest.getData());
  28130. }
  28131. }
  28132. return true;
  28133. }
  28134. void VSTPluginInstance::getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const
  28135. {
  28136. if (usesChunks())
  28137. {
  28138. void* data = 0;
  28139. const int bytes = dispatch (effGetChunk, isPreset ? 1 : 0, 0, &data, 0.0f);
  28140. if (data != 0 && bytes <= maxSizeMB * 1024 * 1024)
  28141. {
  28142. mb.setSize (bytes);
  28143. mb.copyFrom (data, 0, bytes);
  28144. }
  28145. }
  28146. }
  28147. void VSTPluginInstance::setChunkData (const char* data, int size, bool isPreset)
  28148. {
  28149. if (size > 0 && usesChunks())
  28150. {
  28151. dispatch (effSetChunk, isPreset ? 1 : 0, size, (void*) data, 0.0f);
  28152. if (! isPreset)
  28153. updateStoredProgramNames();
  28154. }
  28155. }
  28156. void VSTPluginInstance::timerCallback()
  28157. {
  28158. if (dispatch (effIdle, 0, 0, 0, 0) == 0)
  28159. stopTimer();
  28160. }
  28161. int VSTPluginInstance::dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const
  28162. {
  28163. const ScopedLock sl (lock);
  28164. ++insideVSTCallback;
  28165. int result = 0;
  28166. try
  28167. {
  28168. if (effect != 0)
  28169. {
  28170. #if JUCE_MAC
  28171. if (module->resFileId != 0)
  28172. UseResFile (module->resFileId);
  28173. #endif
  28174. result = effect->dispatcher (effect, opcode, index, value, ptr, opt);
  28175. #if JUCE_MAC
  28176. module->resFileId = CurResFile();
  28177. #endif
  28178. --insideVSTCallback;
  28179. return result;
  28180. }
  28181. }
  28182. catch (...)
  28183. {
  28184. }
  28185. --insideVSTCallback;
  28186. return result;
  28187. }
  28188. namespace
  28189. {
  28190. static const int defaultVSTSampleRateValue = 16384;
  28191. static const int defaultVSTBlockSizeValue = 512;
  28192. // handles non plugin-specific callbacks..
  28193. VstIntPtr handleGeneralCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  28194. {
  28195. (void) index;
  28196. (void) value;
  28197. (void) opt;
  28198. switch (opcode)
  28199. {
  28200. case audioMasterCanDo:
  28201. {
  28202. static const char* canDos[] = { "supplyIdle",
  28203. "sendVstEvents",
  28204. "sendVstMidiEvent",
  28205. "sendVstTimeInfo",
  28206. "receiveVstEvents",
  28207. "receiveVstMidiEvent",
  28208. "supportShell",
  28209. "shellCategory" };
  28210. for (int i = 0; i < numElementsInArray (canDos); ++i)
  28211. if (strcmp (canDos[i], (const char*) ptr) == 0)
  28212. return 1;
  28213. return 0;
  28214. }
  28215. case audioMasterVersion: return 0x2400;
  28216. case audioMasterCurrentId: return shellUIDToCreate;
  28217. case audioMasterGetNumAutomatableParameters: return 0;
  28218. case audioMasterGetAutomationState: return 1;
  28219. case audioMasterGetVendorVersion: return 0x0101;
  28220. case audioMasterGetVendorString:
  28221. case audioMasterGetProductString:
  28222. {
  28223. String hostName ("Juce VST Host");
  28224. if (JUCEApplication::getInstance() != 0)
  28225. hostName = JUCEApplication::getInstance()->getApplicationName();
  28226. hostName.copyToCString ((char*) ptr, jmin (kVstMaxVendorStrLen, kVstMaxProductStrLen) - 1);
  28227. break;
  28228. }
  28229. case audioMasterGetSampleRate: return (VstIntPtr) defaultVSTSampleRateValue;
  28230. case audioMasterGetBlockSize: return (VstIntPtr) defaultVSTBlockSizeValue;
  28231. case audioMasterSetOutputSampleRate: return 0;
  28232. default:
  28233. DBG ("*** Unhandled VST Callback: " + String ((int) opcode));
  28234. break;
  28235. }
  28236. return 0;
  28237. }
  28238. }
  28239. // handles callbacks for a specific plugin
  28240. VstIntPtr VSTPluginInstance::handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  28241. {
  28242. switch (opcode)
  28243. {
  28244. case audioMasterAutomate:
  28245. sendParamChangeMessageToListeners (index, opt);
  28246. break;
  28247. case audioMasterProcessEvents:
  28248. handleMidiFromPlugin ((const VstEvents*) ptr);
  28249. break;
  28250. case audioMasterGetTime:
  28251. #if JUCE_MSVC
  28252. #pragma warning (push)
  28253. #pragma warning (disable: 4311)
  28254. #endif
  28255. return (VstIntPtr) &vstHostTime;
  28256. #if JUCE_MSVC
  28257. #pragma warning (pop)
  28258. #endif
  28259. break;
  28260. case audioMasterIdle:
  28261. if (insideVSTCallback == 0 && MessageManager::getInstance()->isThisTheMessageThread())
  28262. {
  28263. ++insideVSTCallback;
  28264. #if JUCE_MAC
  28265. if (getActiveEditor() != 0)
  28266. dispatch (effEditIdle, 0, 0, 0, 0);
  28267. #endif
  28268. juce_callAnyTimersSynchronously();
  28269. handleUpdateNowIfNeeded();
  28270. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  28271. ComponentPeer::getPeer (i)->performAnyPendingRepaintsNow();
  28272. --insideVSTCallback;
  28273. }
  28274. break;
  28275. case audioMasterUpdateDisplay:
  28276. triggerAsyncUpdate();
  28277. break;
  28278. case audioMasterTempoAt:
  28279. // returns (10000 * bpm)
  28280. break;
  28281. case audioMasterNeedIdle:
  28282. startTimer (50);
  28283. break;
  28284. case audioMasterSizeWindow:
  28285. if (getActiveEditor() != 0)
  28286. getActiveEditor()->setSize (index, value);
  28287. return 1;
  28288. case audioMasterGetSampleRate:
  28289. return (VstIntPtr) (getSampleRate() > 0 ? getSampleRate() : defaultVSTSampleRateValue);
  28290. case audioMasterGetBlockSize:
  28291. return (VstIntPtr) (getBlockSize() > 0 ? getBlockSize() : defaultVSTBlockSizeValue);
  28292. case audioMasterWantMidi:
  28293. wantsMidiMessages = true;
  28294. break;
  28295. case audioMasterGetDirectory:
  28296. #if JUCE_MAC
  28297. return (VstIntPtr) (void*) &module->parentDirFSSpec;
  28298. #else
  28299. return (VstIntPtr) (pointer_sized_uint) module->fullParentDirectoryPathName.toUTF8();
  28300. #endif
  28301. case audioMasterGetAutomationState:
  28302. // returns 0: not supported, 1: off, 2:read, 3:write, 4:read/write
  28303. break;
  28304. // none of these are handled (yet)..
  28305. case audioMasterBeginEdit:
  28306. case audioMasterEndEdit:
  28307. case audioMasterSetTime:
  28308. case audioMasterPinConnected:
  28309. case audioMasterGetParameterQuantization:
  28310. case audioMasterIOChanged:
  28311. case audioMasterGetInputLatency:
  28312. case audioMasterGetOutputLatency:
  28313. case audioMasterGetPreviousPlug:
  28314. case audioMasterGetNextPlug:
  28315. case audioMasterWillReplaceOrAccumulate:
  28316. case audioMasterGetCurrentProcessLevel:
  28317. case audioMasterOfflineStart:
  28318. case audioMasterOfflineRead:
  28319. case audioMasterOfflineWrite:
  28320. case audioMasterOfflineGetCurrentPass:
  28321. case audioMasterOfflineGetCurrentMetaPass:
  28322. case audioMasterVendorSpecific:
  28323. case audioMasterSetIcon:
  28324. case audioMasterGetLanguage:
  28325. case audioMasterOpenWindow:
  28326. case audioMasterCloseWindow:
  28327. break;
  28328. default:
  28329. return handleGeneralCallback (opcode, index, value, ptr, opt);
  28330. }
  28331. return 0;
  28332. }
  28333. // entry point for all callbacks from the plugin
  28334. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt)
  28335. {
  28336. try
  28337. {
  28338. if (effect != 0 && effect->resvd2 != 0)
  28339. {
  28340. return ((VSTPluginInstance*)(effect->resvd2))
  28341. ->handleCallback (opcode, index, value, ptr, opt);
  28342. }
  28343. return handleGeneralCallback (opcode, index, value, ptr, opt);
  28344. }
  28345. catch (...)
  28346. {
  28347. return 0;
  28348. }
  28349. }
  28350. const String VSTPluginInstance::getVersion() const
  28351. {
  28352. unsigned int v = dispatch (effGetVendorVersion, 0, 0, 0, 0);
  28353. String s;
  28354. if (v == 0 || v == -1)
  28355. v = getVersionNumber();
  28356. if (v != 0)
  28357. {
  28358. int versionBits[4];
  28359. int n = 0;
  28360. while (v != 0)
  28361. {
  28362. versionBits [n++] = (v & 0xff);
  28363. v >>= 8;
  28364. }
  28365. s << 'V';
  28366. while (n > 0)
  28367. {
  28368. s << versionBits [--n];
  28369. if (n > 0)
  28370. s << '.';
  28371. }
  28372. }
  28373. return s;
  28374. }
  28375. int VSTPluginInstance::getUID() const
  28376. {
  28377. int uid = effect != 0 ? effect->uniqueID : 0;
  28378. if (uid == 0)
  28379. uid = module->file.hashCode();
  28380. return uid;
  28381. }
  28382. const String VSTPluginInstance::getCategory() const
  28383. {
  28384. const char* result = 0;
  28385. switch (dispatch (effGetPlugCategory, 0, 0, 0, 0))
  28386. {
  28387. case kPlugCategEffect: result = "Effect"; break;
  28388. case kPlugCategSynth: result = "Synth"; break;
  28389. case kPlugCategAnalysis: result = "Anaylsis"; break;
  28390. case kPlugCategMastering: result = "Mastering"; break;
  28391. case kPlugCategSpacializer: result = "Spacial"; break;
  28392. case kPlugCategRoomFx: result = "Reverb"; break;
  28393. case kPlugSurroundFx: result = "Surround"; break;
  28394. case kPlugCategRestoration: result = "Restoration"; break;
  28395. case kPlugCategGenerator: result = "Tone generation"; break;
  28396. default: break;
  28397. }
  28398. return result;
  28399. }
  28400. float VSTPluginInstance::getParameter (int index)
  28401. {
  28402. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  28403. {
  28404. try
  28405. {
  28406. const ScopedLock sl (lock);
  28407. return effect->getParameter (effect, index);
  28408. }
  28409. catch (...)
  28410. {
  28411. }
  28412. }
  28413. return 0.0f;
  28414. }
  28415. void VSTPluginInstance::setParameter (int index, float newValue)
  28416. {
  28417. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  28418. {
  28419. try
  28420. {
  28421. const ScopedLock sl (lock);
  28422. if (effect->getParameter (effect, index) != newValue)
  28423. effect->setParameter (effect, index, newValue);
  28424. }
  28425. catch (...)
  28426. {
  28427. }
  28428. }
  28429. }
  28430. const String VSTPluginInstance::getParameterName (int index)
  28431. {
  28432. if (effect != 0)
  28433. {
  28434. jassert (index >= 0 && index < effect->numParams);
  28435. char nm [256];
  28436. zerostruct (nm);
  28437. dispatch (effGetParamName, index, 0, nm, 0);
  28438. return String (nm).trim();
  28439. }
  28440. return String::empty;
  28441. }
  28442. const String VSTPluginInstance::getParameterLabel (int index) const
  28443. {
  28444. if (effect != 0)
  28445. {
  28446. jassert (index >= 0 && index < effect->numParams);
  28447. char nm [256];
  28448. zerostruct (nm);
  28449. dispatch (effGetParamLabel, index, 0, nm, 0);
  28450. return String (nm).trim();
  28451. }
  28452. return String::empty;
  28453. }
  28454. const String VSTPluginInstance::getParameterText (int index)
  28455. {
  28456. if (effect != 0)
  28457. {
  28458. jassert (index >= 0 && index < effect->numParams);
  28459. char nm [256];
  28460. zerostruct (nm);
  28461. dispatch (effGetParamDisplay, index, 0, nm, 0);
  28462. return String (nm).trim();
  28463. }
  28464. return String::empty;
  28465. }
  28466. bool VSTPluginInstance::isParameterAutomatable (int index) const
  28467. {
  28468. if (effect != 0)
  28469. {
  28470. jassert (index >= 0 && index < effect->numParams);
  28471. return dispatch (effCanBeAutomated, index, 0, 0, 0) != 0;
  28472. }
  28473. return false;
  28474. }
  28475. void VSTPluginInstance::createTempParameterStore (MemoryBlock& dest)
  28476. {
  28477. dest.setSize (64 + 4 * getNumParameters());
  28478. dest.fillWith (0);
  28479. getCurrentProgramName().copyToCString ((char*) dest.getData(), 63);
  28480. float* const p = (float*) (((char*) dest.getData()) + 64);
  28481. for (int i = 0; i < getNumParameters(); ++i)
  28482. p[i] = getParameter(i);
  28483. }
  28484. void VSTPluginInstance::restoreFromTempParameterStore (const MemoryBlock& m)
  28485. {
  28486. changeProgramName (getCurrentProgram(), (const char*) m.getData());
  28487. float* p = (float*) (((char*) m.getData()) + 64);
  28488. for (int i = 0; i < getNumParameters(); ++i)
  28489. setParameter (i, p[i]);
  28490. }
  28491. void VSTPluginInstance::setCurrentProgram (int newIndex)
  28492. {
  28493. if (getNumPrograms() > 0 && newIndex != getCurrentProgram())
  28494. dispatch (effSetProgram, 0, jlimit (0, getNumPrograms() - 1, newIndex), 0, 0);
  28495. }
  28496. const String VSTPluginInstance::getProgramName (int index)
  28497. {
  28498. if (index == getCurrentProgram())
  28499. {
  28500. return getCurrentProgramName();
  28501. }
  28502. else if (effect != 0)
  28503. {
  28504. char nm [256];
  28505. zerostruct (nm);
  28506. if (dispatch (effGetProgramNameIndexed,
  28507. jlimit (0, getNumPrograms(), index),
  28508. -1, nm, 0) != 0)
  28509. {
  28510. return String (nm).trim();
  28511. }
  28512. }
  28513. return programNames [index];
  28514. }
  28515. void VSTPluginInstance::changeProgramName (int index, const String& newName)
  28516. {
  28517. if (index == getCurrentProgram())
  28518. {
  28519. if (getNumPrograms() > 0 && newName != getCurrentProgramName())
  28520. dispatch (effSetProgramName, 0, 0, (void*) newName.substring (0, 24).toCString(), 0.0f);
  28521. }
  28522. else
  28523. {
  28524. jassertfalse; // xxx not implemented!
  28525. }
  28526. }
  28527. void VSTPluginInstance::updateStoredProgramNames()
  28528. {
  28529. if (effect != 0 && getNumPrograms() > 0)
  28530. {
  28531. char nm [256];
  28532. zerostruct (nm);
  28533. // only do this if the plugin can't use indexed names..
  28534. if (dispatch (effGetProgramNameIndexed, 0, -1, nm, 0) == 0)
  28535. {
  28536. const int oldProgram = getCurrentProgram();
  28537. MemoryBlock oldSettings;
  28538. createTempParameterStore (oldSettings);
  28539. for (int i = 0; i < getNumPrograms(); ++i)
  28540. {
  28541. setCurrentProgram (i);
  28542. getCurrentProgramName(); // (this updates the list)
  28543. }
  28544. setCurrentProgram (oldProgram);
  28545. restoreFromTempParameterStore (oldSettings);
  28546. }
  28547. }
  28548. }
  28549. const String VSTPluginInstance::getCurrentProgramName()
  28550. {
  28551. if (effect != 0)
  28552. {
  28553. char nm [256];
  28554. zerostruct (nm);
  28555. dispatch (effGetProgramName, 0, 0, nm, 0);
  28556. const int index = getCurrentProgram();
  28557. if (programNames[index].isEmpty())
  28558. {
  28559. while (programNames.size() < index)
  28560. programNames.add (String::empty);
  28561. programNames.set (index, String (nm).trim());
  28562. }
  28563. return String (nm).trim();
  28564. }
  28565. return String::empty;
  28566. }
  28567. const String VSTPluginInstance::getInputChannelName (int index) const
  28568. {
  28569. if (index >= 0 && index < getNumInputChannels())
  28570. {
  28571. VstPinProperties pinProps;
  28572. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  28573. return String (pinProps.label, sizeof (pinProps.label));
  28574. }
  28575. return String::empty;
  28576. }
  28577. bool VSTPluginInstance::isInputChannelStereoPair (int index) const
  28578. {
  28579. if (index < 0 || index >= getNumInputChannels())
  28580. return false;
  28581. VstPinProperties pinProps;
  28582. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  28583. return (pinProps.flags & kVstPinIsStereo) != 0;
  28584. return true;
  28585. }
  28586. const String VSTPluginInstance::getOutputChannelName (int index) const
  28587. {
  28588. if (index >= 0 && index < getNumOutputChannels())
  28589. {
  28590. VstPinProperties pinProps;
  28591. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  28592. return String (pinProps.label, sizeof (pinProps.label));
  28593. }
  28594. return String::empty;
  28595. }
  28596. bool VSTPluginInstance::isOutputChannelStereoPair (int index) const
  28597. {
  28598. if (index < 0 || index >= getNumOutputChannels())
  28599. return false;
  28600. VstPinProperties pinProps;
  28601. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  28602. return (pinProps.flags & kVstPinIsStereo) != 0;
  28603. return true;
  28604. }
  28605. void VSTPluginInstance::setPower (const bool on)
  28606. {
  28607. dispatch (effMainsChanged, 0, on ? 1 : 0, 0, 0);
  28608. isPowerOn = on;
  28609. }
  28610. const int defaultMaxSizeMB = 64;
  28611. void VSTPluginInstance::getStateInformation (MemoryBlock& destData)
  28612. {
  28613. saveToFXBFile (destData, true, defaultMaxSizeMB);
  28614. }
  28615. void VSTPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  28616. {
  28617. saveToFXBFile (destData, false, defaultMaxSizeMB);
  28618. }
  28619. void VSTPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  28620. {
  28621. loadFromFXBFile (data, sizeInBytes);
  28622. }
  28623. void VSTPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  28624. {
  28625. loadFromFXBFile (data, sizeInBytes);
  28626. }
  28627. VSTPluginFormat::VSTPluginFormat()
  28628. {
  28629. }
  28630. VSTPluginFormat::~VSTPluginFormat()
  28631. {
  28632. }
  28633. void VSTPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  28634. const String& fileOrIdentifier)
  28635. {
  28636. if (! fileMightContainThisPluginType (fileOrIdentifier))
  28637. return;
  28638. PluginDescription desc;
  28639. desc.fileOrIdentifier = fileOrIdentifier;
  28640. desc.uid = 0;
  28641. ScopedPointer <VSTPluginInstance> instance (dynamic_cast <VSTPluginInstance*> (createInstanceFromDescription (desc)));
  28642. if (instance == 0)
  28643. return;
  28644. try
  28645. {
  28646. #if JUCE_MAC
  28647. if (instance->module->resFileId != 0)
  28648. UseResFile (instance->module->resFileId);
  28649. #endif
  28650. instance->fillInPluginDescription (desc);
  28651. VstPlugCategory category = (VstPlugCategory) instance->dispatch (effGetPlugCategory, 0, 0, 0, 0);
  28652. if (category != kPlugCategShell)
  28653. {
  28654. // Normal plugin...
  28655. results.add (new PluginDescription (desc));
  28656. ++insideVSTCallback;
  28657. instance->dispatch (effOpen, 0, 0, 0, 0);
  28658. --insideVSTCallback;
  28659. }
  28660. else
  28661. {
  28662. // It's a shell plugin, so iterate all the subtypes...
  28663. char shellEffectName [64];
  28664. for (;;)
  28665. {
  28666. zerostruct (shellEffectName);
  28667. const int uid = instance->dispatch (effShellGetNextPlugin, 0, 0, shellEffectName, 0);
  28668. if (uid == 0)
  28669. {
  28670. break;
  28671. }
  28672. else
  28673. {
  28674. desc.uid = uid;
  28675. desc.name = shellEffectName;
  28676. bool alreadyThere = false;
  28677. for (int i = results.size(); --i >= 0;)
  28678. {
  28679. PluginDescription* const d = results.getUnchecked(i);
  28680. if (d->isDuplicateOf (desc))
  28681. {
  28682. alreadyThere = true;
  28683. break;
  28684. }
  28685. }
  28686. if (! alreadyThere)
  28687. results.add (new PluginDescription (desc));
  28688. }
  28689. }
  28690. }
  28691. }
  28692. catch (...)
  28693. {
  28694. // crashed while loading...
  28695. }
  28696. }
  28697. AudioPluginInstance* VSTPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  28698. {
  28699. ScopedPointer <VSTPluginInstance> result;
  28700. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  28701. {
  28702. File file (desc.fileOrIdentifier);
  28703. const File previousWorkingDirectory (File::getCurrentWorkingDirectory());
  28704. file.getParentDirectory().setAsCurrentWorkingDirectory();
  28705. const ReferenceCountedObjectPtr <ModuleHandle> module (ModuleHandle::findOrCreateModule (file));
  28706. if (module != 0)
  28707. {
  28708. shellUIDToCreate = desc.uid;
  28709. result = new VSTPluginInstance (module);
  28710. if (result->effect != 0)
  28711. {
  28712. result->effect->resvd2 = (VstIntPtr) (pointer_sized_int) (VSTPluginInstance*) result;
  28713. result->initialise();
  28714. }
  28715. else
  28716. {
  28717. result = 0;
  28718. }
  28719. }
  28720. previousWorkingDirectory.setAsCurrentWorkingDirectory();
  28721. }
  28722. return result.release();
  28723. }
  28724. bool VSTPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  28725. {
  28726. const File f (fileOrIdentifier);
  28727. #if JUCE_MAC
  28728. if (f.isDirectory() && f.hasFileExtension (".vst"))
  28729. return true;
  28730. #if JUCE_PPC
  28731. FSRef fileRef;
  28732. if (PlatformUtilities::makeFSRefFromPath (&fileRef, f.getFullPathName()))
  28733. {
  28734. const short resFileId = FSOpenResFile (&fileRef, fsRdPerm);
  28735. if (resFileId != -1)
  28736. {
  28737. const int numEffects = Count1Resources ('aEff');
  28738. CloseResFile (resFileId);
  28739. if (numEffects > 0)
  28740. return true;
  28741. }
  28742. }
  28743. #endif
  28744. return false;
  28745. #elif JUCE_WINDOWS
  28746. return f.existsAsFile() && f.hasFileExtension (".dll");
  28747. #elif JUCE_LINUX
  28748. return f.existsAsFile() && f.hasFileExtension (".so");
  28749. #endif
  28750. }
  28751. const String VSTPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  28752. {
  28753. return fileOrIdentifier;
  28754. }
  28755. bool VSTPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  28756. {
  28757. return File (desc.fileOrIdentifier).exists();
  28758. }
  28759. const StringArray VSTPluginFormat::searchPathsForPlugins (const FileSearchPath& directoriesToSearch, const bool recursive)
  28760. {
  28761. StringArray results;
  28762. for (int j = 0; j < directoriesToSearch.getNumPaths(); ++j)
  28763. recursiveFileSearch (results, directoriesToSearch [j], recursive);
  28764. return results;
  28765. }
  28766. void VSTPluginFormat::recursiveFileSearch (StringArray& results, const File& dir, const bool recursive)
  28767. {
  28768. // avoid allowing the dir iterator to be recursive, because we want to avoid letting it delve inside
  28769. // .component or .vst directories.
  28770. DirectoryIterator iter (dir, false, "*", File::findFilesAndDirectories);
  28771. while (iter.next())
  28772. {
  28773. const File f (iter.getFile());
  28774. bool isPlugin = false;
  28775. if (fileMightContainThisPluginType (f.getFullPathName()))
  28776. {
  28777. isPlugin = true;
  28778. results.add (f.getFullPathName());
  28779. }
  28780. if (recursive && (! isPlugin) && f.isDirectory())
  28781. recursiveFileSearch (results, f, true);
  28782. }
  28783. }
  28784. const FileSearchPath VSTPluginFormat::getDefaultLocationsToSearch()
  28785. {
  28786. #if JUCE_MAC
  28787. return FileSearchPath ("~/Library/Audio/Plug-Ins/VST;/Library/Audio/Plug-Ins/VST");
  28788. #elif JUCE_WINDOWS
  28789. const String programFiles (File::getSpecialLocation (File::globalApplicationsDirectory).getFullPathName());
  28790. return FileSearchPath (programFiles + "\\Steinberg\\VstPlugins");
  28791. #elif JUCE_LINUX
  28792. return FileSearchPath ("/usr/lib/vst");
  28793. #endif
  28794. }
  28795. END_JUCE_NAMESPACE
  28796. #endif
  28797. #undef log
  28798. #endif
  28799. /*** End of inlined file: juce_VSTPluginFormat.cpp ***/
  28800. /*** End of inlined file: juce_VSTPluginFormat.mm ***/
  28801. /*** Start of inlined file: juce_AudioProcessor.cpp ***/
  28802. BEGIN_JUCE_NAMESPACE
  28803. AudioProcessor::AudioProcessor()
  28804. : playHead (0),
  28805. activeEditor (0),
  28806. sampleRate (0),
  28807. blockSize (0),
  28808. numInputChannels (0),
  28809. numOutputChannels (0),
  28810. latencySamples (0),
  28811. suspended (false),
  28812. nonRealtime (false)
  28813. {
  28814. }
  28815. AudioProcessor::~AudioProcessor()
  28816. {
  28817. // ooh, nasty - the editor should have been deleted before the filter
  28818. // that it refers to is deleted..
  28819. jassert (activeEditor == 0);
  28820. #if JUCE_DEBUG
  28821. // This will fail if you've called beginParameterChangeGesture() for one
  28822. // or more parameters without having made a corresponding call to endParameterChangeGesture...
  28823. jassert (changingParams.countNumberOfSetBits() == 0);
  28824. #endif
  28825. }
  28826. void AudioProcessor::setPlayHead (AudioPlayHead* const newPlayHead) throw()
  28827. {
  28828. playHead = newPlayHead;
  28829. }
  28830. void AudioProcessor::addListener (AudioProcessorListener* const newListener)
  28831. {
  28832. const ScopedLock sl (listenerLock);
  28833. listeners.addIfNotAlreadyThere (newListener);
  28834. }
  28835. void AudioProcessor::removeListener (AudioProcessorListener* const listenerToRemove)
  28836. {
  28837. const ScopedLock sl (listenerLock);
  28838. listeners.removeValue (listenerToRemove);
  28839. }
  28840. void AudioProcessor::setPlayConfigDetails (const int numIns,
  28841. const int numOuts,
  28842. const double sampleRate_,
  28843. const int blockSize_) throw()
  28844. {
  28845. numInputChannels = numIns;
  28846. numOutputChannels = numOuts;
  28847. sampleRate = sampleRate_;
  28848. blockSize = blockSize_;
  28849. }
  28850. void AudioProcessor::setNonRealtime (const bool nonRealtime_) throw()
  28851. {
  28852. nonRealtime = nonRealtime_;
  28853. }
  28854. void AudioProcessor::setLatencySamples (const int newLatency)
  28855. {
  28856. if (latencySamples != newLatency)
  28857. {
  28858. latencySamples = newLatency;
  28859. updateHostDisplay();
  28860. }
  28861. }
  28862. void AudioProcessor::setParameterNotifyingHost (const int parameterIndex,
  28863. const float newValue)
  28864. {
  28865. setParameter (parameterIndex, newValue);
  28866. sendParamChangeMessageToListeners (parameterIndex, newValue);
  28867. }
  28868. void AudioProcessor::sendParamChangeMessageToListeners (const int parameterIndex, const float newValue)
  28869. {
  28870. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  28871. for (int i = listeners.size(); --i >= 0;)
  28872. {
  28873. AudioProcessorListener* l;
  28874. {
  28875. const ScopedLock sl (listenerLock);
  28876. l = listeners [i];
  28877. }
  28878. if (l != 0)
  28879. l->audioProcessorParameterChanged (this, parameterIndex, newValue);
  28880. }
  28881. }
  28882. void AudioProcessor::beginParameterChangeGesture (int parameterIndex)
  28883. {
  28884. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  28885. #if JUCE_DEBUG
  28886. // This means you've called beginParameterChangeGesture twice in succession without a matching
  28887. // call to endParameterChangeGesture. That might be fine in most hosts, but better to avoid doing it.
  28888. jassert (! changingParams [parameterIndex]);
  28889. changingParams.setBit (parameterIndex);
  28890. #endif
  28891. for (int i = listeners.size(); --i >= 0;)
  28892. {
  28893. AudioProcessorListener* l;
  28894. {
  28895. const ScopedLock sl (listenerLock);
  28896. l = listeners [i];
  28897. }
  28898. if (l != 0)
  28899. l->audioProcessorParameterChangeGestureBegin (this, parameterIndex);
  28900. }
  28901. }
  28902. void AudioProcessor::endParameterChangeGesture (int parameterIndex)
  28903. {
  28904. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  28905. #if JUCE_DEBUG
  28906. // This means you've called endParameterChangeGesture without having previously called
  28907. // endParameterChangeGesture. That might be fine in most hosts, but better to keep the
  28908. // calls matched correctly.
  28909. jassert (changingParams [parameterIndex]);
  28910. changingParams.clearBit (parameterIndex);
  28911. #endif
  28912. for (int i = listeners.size(); --i >= 0;)
  28913. {
  28914. AudioProcessorListener* l;
  28915. {
  28916. const ScopedLock sl (listenerLock);
  28917. l = listeners [i];
  28918. }
  28919. if (l != 0)
  28920. l->audioProcessorParameterChangeGestureEnd (this, parameterIndex);
  28921. }
  28922. }
  28923. void AudioProcessor::updateHostDisplay()
  28924. {
  28925. for (int i = listeners.size(); --i >= 0;)
  28926. {
  28927. AudioProcessorListener* l;
  28928. {
  28929. const ScopedLock sl (listenerLock);
  28930. l = listeners [i];
  28931. }
  28932. if (l != 0)
  28933. l->audioProcessorChanged (this);
  28934. }
  28935. }
  28936. bool AudioProcessor::isParameterAutomatable (int /*parameterIndex*/) const
  28937. {
  28938. return true;
  28939. }
  28940. bool AudioProcessor::isMetaParameter (int /*parameterIndex*/) const
  28941. {
  28942. return false;
  28943. }
  28944. void AudioProcessor::suspendProcessing (const bool shouldBeSuspended)
  28945. {
  28946. const ScopedLock sl (callbackLock);
  28947. suspended = shouldBeSuspended;
  28948. }
  28949. void AudioProcessor::reset()
  28950. {
  28951. }
  28952. void AudioProcessor::editorBeingDeleted (AudioProcessorEditor* const editor) throw()
  28953. {
  28954. const ScopedLock sl (callbackLock);
  28955. jassert (activeEditor == editor);
  28956. if (activeEditor == editor)
  28957. activeEditor = 0;
  28958. }
  28959. AudioProcessorEditor* AudioProcessor::createEditorIfNeeded()
  28960. {
  28961. if (activeEditor != 0)
  28962. return activeEditor;
  28963. AudioProcessorEditor* const ed = createEditor();
  28964. // You must make your hasEditor() method return a consistent result!
  28965. jassert (hasEditor() == (ed != 0));
  28966. if (ed != 0)
  28967. {
  28968. // you must give your editor comp a size before returning it..
  28969. jassert (ed->getWidth() > 0 && ed->getHeight() > 0);
  28970. const ScopedLock sl (callbackLock);
  28971. activeEditor = ed;
  28972. }
  28973. return ed;
  28974. }
  28975. void AudioProcessor::getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData)
  28976. {
  28977. getStateInformation (destData);
  28978. }
  28979. void AudioProcessor::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  28980. {
  28981. setStateInformation (data, sizeInBytes);
  28982. }
  28983. // magic number to identify memory blocks that we've stored as XML
  28984. const uint32 magicXmlNumber = 0x21324356;
  28985. void AudioProcessor::copyXmlToBinary (const XmlElement& xml,
  28986. JUCE_NAMESPACE::MemoryBlock& destData)
  28987. {
  28988. const String xmlString (xml.createDocument (String::empty, true, false));
  28989. const int stringLength = xmlString.getNumBytesAsUTF8();
  28990. destData.setSize (stringLength + 10);
  28991. char* const d = static_cast<char*> (destData.getData());
  28992. *(uint32*) d = ByteOrder::swapIfBigEndian ((const uint32) magicXmlNumber);
  28993. *(uint32*) (d + 4) = ByteOrder::swapIfBigEndian ((const uint32) stringLength);
  28994. xmlString.copyToUTF8 (d + 8, stringLength + 1);
  28995. }
  28996. XmlElement* AudioProcessor::getXmlFromBinary (const void* data,
  28997. const int sizeInBytes)
  28998. {
  28999. if (sizeInBytes > 8
  29000. && ByteOrder::littleEndianInt (data) == magicXmlNumber)
  29001. {
  29002. const int stringLength = (int) ByteOrder::littleEndianInt (addBytesToPointer (data, 4));
  29003. if (stringLength > 0)
  29004. {
  29005. XmlDocument doc (String::fromUTF8 (static_cast<const char*> (data) + 8,
  29006. jmin ((sizeInBytes - 8), stringLength)));
  29007. return doc.getDocumentElement();
  29008. }
  29009. }
  29010. return 0;
  29011. }
  29012. void AudioProcessorListener::audioProcessorParameterChangeGestureBegin (AudioProcessor*, int) {}
  29013. void AudioProcessorListener::audioProcessorParameterChangeGestureEnd (AudioProcessor*, int) {}
  29014. bool AudioPlayHead::CurrentPositionInfo::operator== (const CurrentPositionInfo& other) const throw()
  29015. {
  29016. return timeInSeconds == other.timeInSeconds
  29017. && ppqPosition == other.ppqPosition
  29018. && editOriginTime == other.editOriginTime
  29019. && ppqPositionOfLastBarStart == other.ppqPositionOfLastBarStart
  29020. && frameRate == other.frameRate
  29021. && isPlaying == other.isPlaying
  29022. && isRecording == other.isRecording
  29023. && bpm == other.bpm
  29024. && timeSigNumerator == other.timeSigNumerator
  29025. && timeSigDenominator == other.timeSigDenominator;
  29026. }
  29027. bool AudioPlayHead::CurrentPositionInfo::operator!= (const CurrentPositionInfo& other) const throw()
  29028. {
  29029. return ! operator== (other);
  29030. }
  29031. void AudioPlayHead::CurrentPositionInfo::resetToDefault()
  29032. {
  29033. zerostruct (*this);
  29034. timeSigNumerator = 4;
  29035. timeSigDenominator = 4;
  29036. bpm = 120;
  29037. }
  29038. END_JUCE_NAMESPACE
  29039. /*** End of inlined file: juce_AudioProcessor.cpp ***/
  29040. /*** Start of inlined file: juce_AudioProcessorEditor.cpp ***/
  29041. BEGIN_JUCE_NAMESPACE
  29042. AudioProcessorEditor::AudioProcessorEditor (AudioProcessor* const owner_)
  29043. : owner (owner_)
  29044. {
  29045. // the filter must be valid..
  29046. jassert (owner != 0);
  29047. }
  29048. AudioProcessorEditor::~AudioProcessorEditor()
  29049. {
  29050. // if this fails, then the wrapper hasn't called editorBeingDeleted() on the
  29051. // filter for some reason..
  29052. jassert (owner->getActiveEditor() != this);
  29053. }
  29054. END_JUCE_NAMESPACE
  29055. /*** End of inlined file: juce_AudioProcessorEditor.cpp ***/
  29056. /*** Start of inlined file: juce_AudioProcessorGraph.cpp ***/
  29057. BEGIN_JUCE_NAMESPACE
  29058. const int AudioProcessorGraph::midiChannelIndex = 0x1000;
  29059. AudioProcessorGraph::Node::Node (const uint32 id_, AudioProcessor* const processor_)
  29060. : id (id_),
  29061. processor (processor_),
  29062. isPrepared (false)
  29063. {
  29064. jassert (processor_ != 0);
  29065. }
  29066. AudioProcessorGraph::Node::~Node()
  29067. {
  29068. }
  29069. void AudioProcessorGraph::Node::prepare (const double sampleRate, const int blockSize,
  29070. AudioProcessorGraph* const graph)
  29071. {
  29072. if (! isPrepared)
  29073. {
  29074. isPrepared = true;
  29075. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  29076. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (static_cast<AudioProcessor*> (processor));
  29077. if (ioProc != 0)
  29078. ioProc->setParentGraph (graph);
  29079. processor->setPlayConfigDetails (processor->getNumInputChannels(),
  29080. processor->getNumOutputChannels(),
  29081. sampleRate, blockSize);
  29082. processor->prepareToPlay (sampleRate, blockSize);
  29083. }
  29084. }
  29085. void AudioProcessorGraph::Node::unprepare()
  29086. {
  29087. if (isPrepared)
  29088. {
  29089. isPrepared = false;
  29090. processor->releaseResources();
  29091. }
  29092. }
  29093. AudioProcessorGraph::AudioProcessorGraph()
  29094. : lastNodeId (0),
  29095. renderingBuffers (1, 1),
  29096. currentAudioOutputBuffer (1, 1)
  29097. {
  29098. }
  29099. AudioProcessorGraph::~AudioProcessorGraph()
  29100. {
  29101. clearRenderingSequence();
  29102. clear();
  29103. }
  29104. const String AudioProcessorGraph::getName() const
  29105. {
  29106. return "Audio Graph";
  29107. }
  29108. void AudioProcessorGraph::clear()
  29109. {
  29110. nodes.clear();
  29111. connections.clear();
  29112. triggerAsyncUpdate();
  29113. }
  29114. AudioProcessorGraph::Node* AudioProcessorGraph::getNodeForId (const uint32 nodeId) const
  29115. {
  29116. for (int i = nodes.size(); --i >= 0;)
  29117. if (nodes.getUnchecked(i)->id == nodeId)
  29118. return nodes.getUnchecked(i);
  29119. return 0;
  29120. }
  29121. AudioProcessorGraph::Node* AudioProcessorGraph::addNode (AudioProcessor* const newProcessor,
  29122. uint32 nodeId)
  29123. {
  29124. if (newProcessor == 0)
  29125. {
  29126. jassertfalse;
  29127. return 0;
  29128. }
  29129. if (nodeId == 0)
  29130. {
  29131. nodeId = ++lastNodeId;
  29132. }
  29133. else
  29134. {
  29135. // you can't add a node with an id that already exists in the graph..
  29136. jassert (getNodeForId (nodeId) == 0);
  29137. removeNode (nodeId);
  29138. }
  29139. lastNodeId = nodeId;
  29140. Node* const n = new Node (nodeId, newProcessor);
  29141. nodes.add (n);
  29142. triggerAsyncUpdate();
  29143. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  29144. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (static_cast<AudioProcessor*> (n->processor));
  29145. if (ioProc != 0)
  29146. ioProc->setParentGraph (this);
  29147. return n;
  29148. }
  29149. bool AudioProcessorGraph::removeNode (const uint32 nodeId)
  29150. {
  29151. disconnectNode (nodeId);
  29152. for (int i = nodes.size(); --i >= 0;)
  29153. {
  29154. if (nodes.getUnchecked(i)->id == nodeId)
  29155. {
  29156. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  29157. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (static_cast<AudioProcessor*> (nodes.getUnchecked(i)->processor));
  29158. if (ioProc != 0)
  29159. ioProc->setParentGraph (0);
  29160. nodes.remove (i);
  29161. triggerAsyncUpdate();
  29162. return true;
  29163. }
  29164. }
  29165. return false;
  29166. }
  29167. const AudioProcessorGraph::Connection* AudioProcessorGraph::getConnectionBetween (const uint32 sourceNodeId,
  29168. const int sourceChannelIndex,
  29169. const uint32 destNodeId,
  29170. const int destChannelIndex) const
  29171. {
  29172. for (int i = connections.size(); --i >= 0;)
  29173. {
  29174. const Connection* const c = connections.getUnchecked(i);
  29175. if (c->sourceNodeId == sourceNodeId
  29176. && c->destNodeId == destNodeId
  29177. && c->sourceChannelIndex == sourceChannelIndex
  29178. && c->destChannelIndex == destChannelIndex)
  29179. {
  29180. return c;
  29181. }
  29182. }
  29183. return 0;
  29184. }
  29185. bool AudioProcessorGraph::isConnected (const uint32 possibleSourceNodeId,
  29186. const uint32 possibleDestNodeId) const
  29187. {
  29188. for (int i = connections.size(); --i >= 0;)
  29189. {
  29190. const Connection* const c = connections.getUnchecked(i);
  29191. if (c->sourceNodeId == possibleSourceNodeId
  29192. && c->destNodeId == possibleDestNodeId)
  29193. {
  29194. return true;
  29195. }
  29196. }
  29197. return false;
  29198. }
  29199. bool AudioProcessorGraph::canConnect (const uint32 sourceNodeId,
  29200. const int sourceChannelIndex,
  29201. const uint32 destNodeId,
  29202. const int destChannelIndex) const
  29203. {
  29204. if (sourceChannelIndex < 0
  29205. || destChannelIndex < 0
  29206. || sourceNodeId == destNodeId
  29207. || (destChannelIndex == midiChannelIndex) != (sourceChannelIndex == midiChannelIndex))
  29208. return false;
  29209. const Node* const source = getNodeForId (sourceNodeId);
  29210. if (source == 0
  29211. || (sourceChannelIndex != midiChannelIndex && sourceChannelIndex >= source->processor->getNumOutputChannels())
  29212. || (sourceChannelIndex == midiChannelIndex && ! source->processor->producesMidi()))
  29213. return false;
  29214. const Node* const dest = getNodeForId (destNodeId);
  29215. if (dest == 0
  29216. || (destChannelIndex != midiChannelIndex && destChannelIndex >= dest->processor->getNumInputChannels())
  29217. || (destChannelIndex == midiChannelIndex && ! dest->processor->acceptsMidi()))
  29218. return false;
  29219. return getConnectionBetween (sourceNodeId, sourceChannelIndex,
  29220. destNodeId, destChannelIndex) == 0;
  29221. }
  29222. bool AudioProcessorGraph::addConnection (const uint32 sourceNodeId,
  29223. const int sourceChannelIndex,
  29224. const uint32 destNodeId,
  29225. const int destChannelIndex)
  29226. {
  29227. if (! canConnect (sourceNodeId, sourceChannelIndex, destNodeId, destChannelIndex))
  29228. return false;
  29229. Connection* const c = new Connection();
  29230. c->sourceNodeId = sourceNodeId;
  29231. c->sourceChannelIndex = sourceChannelIndex;
  29232. c->destNodeId = destNodeId;
  29233. c->destChannelIndex = destChannelIndex;
  29234. connections.add (c);
  29235. triggerAsyncUpdate();
  29236. return true;
  29237. }
  29238. void AudioProcessorGraph::removeConnection (const int index)
  29239. {
  29240. connections.remove (index);
  29241. triggerAsyncUpdate();
  29242. }
  29243. bool AudioProcessorGraph::removeConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  29244. const uint32 destNodeId, const int destChannelIndex)
  29245. {
  29246. bool doneAnything = false;
  29247. for (int i = connections.size(); --i >= 0;)
  29248. {
  29249. const Connection* const c = connections.getUnchecked(i);
  29250. if (c->sourceNodeId == sourceNodeId
  29251. && c->destNodeId == destNodeId
  29252. && c->sourceChannelIndex == sourceChannelIndex
  29253. && c->destChannelIndex == destChannelIndex)
  29254. {
  29255. removeConnection (i);
  29256. doneAnything = true;
  29257. triggerAsyncUpdate();
  29258. }
  29259. }
  29260. return doneAnything;
  29261. }
  29262. bool AudioProcessorGraph::disconnectNode (const uint32 nodeId)
  29263. {
  29264. bool doneAnything = false;
  29265. for (int i = connections.size(); --i >= 0;)
  29266. {
  29267. const Connection* const c = connections.getUnchecked(i);
  29268. if (c->sourceNodeId == nodeId || c->destNodeId == nodeId)
  29269. {
  29270. removeConnection (i);
  29271. doneAnything = true;
  29272. triggerAsyncUpdate();
  29273. }
  29274. }
  29275. return doneAnything;
  29276. }
  29277. bool AudioProcessorGraph::removeIllegalConnections()
  29278. {
  29279. bool doneAnything = false;
  29280. for (int i = connections.size(); --i >= 0;)
  29281. {
  29282. const Connection* const c = connections.getUnchecked(i);
  29283. const Node* const source = getNodeForId (c->sourceNodeId);
  29284. const Node* const dest = getNodeForId (c->destNodeId);
  29285. if (source == 0 || dest == 0
  29286. || (c->sourceChannelIndex != midiChannelIndex
  29287. && (((unsigned int) c->sourceChannelIndex) >= (unsigned int) source->processor->getNumOutputChannels()))
  29288. || (c->sourceChannelIndex == midiChannelIndex
  29289. && ! source->processor->producesMidi())
  29290. || (c->destChannelIndex != midiChannelIndex
  29291. && (((unsigned int) c->destChannelIndex) >= (unsigned int) dest->processor->getNumInputChannels()))
  29292. || (c->destChannelIndex == midiChannelIndex
  29293. && ! dest->processor->acceptsMidi()))
  29294. {
  29295. removeConnection (i);
  29296. doneAnything = true;
  29297. triggerAsyncUpdate();
  29298. }
  29299. }
  29300. return doneAnything;
  29301. }
  29302. namespace GraphRenderingOps
  29303. {
  29304. class AudioGraphRenderingOp
  29305. {
  29306. public:
  29307. AudioGraphRenderingOp() {}
  29308. virtual ~AudioGraphRenderingOp() {}
  29309. virtual void perform (AudioSampleBuffer& sharedBufferChans,
  29310. const OwnedArray <MidiBuffer>& sharedMidiBuffers,
  29311. const int numSamples) = 0;
  29312. juce_UseDebuggingNewOperator
  29313. };
  29314. class ClearChannelOp : public AudioGraphRenderingOp
  29315. {
  29316. public:
  29317. ClearChannelOp (const int channelNum_)
  29318. : channelNum (channelNum_)
  29319. {}
  29320. ~ClearChannelOp() {}
  29321. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  29322. {
  29323. sharedBufferChans.clear (channelNum, 0, numSamples);
  29324. }
  29325. private:
  29326. const int channelNum;
  29327. ClearChannelOp (const ClearChannelOp&);
  29328. ClearChannelOp& operator= (const ClearChannelOp&);
  29329. };
  29330. class CopyChannelOp : public AudioGraphRenderingOp
  29331. {
  29332. public:
  29333. CopyChannelOp (const int srcChannelNum_, const int dstChannelNum_)
  29334. : srcChannelNum (srcChannelNum_),
  29335. dstChannelNum (dstChannelNum_)
  29336. {}
  29337. ~CopyChannelOp() {}
  29338. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  29339. {
  29340. sharedBufferChans.copyFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  29341. }
  29342. private:
  29343. const int srcChannelNum, dstChannelNum;
  29344. CopyChannelOp (const CopyChannelOp&);
  29345. CopyChannelOp& operator= (const CopyChannelOp&);
  29346. };
  29347. class AddChannelOp : public AudioGraphRenderingOp
  29348. {
  29349. public:
  29350. AddChannelOp (const int srcChannelNum_, const int dstChannelNum_)
  29351. : srcChannelNum (srcChannelNum_),
  29352. dstChannelNum (dstChannelNum_)
  29353. {}
  29354. ~AddChannelOp() {}
  29355. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  29356. {
  29357. sharedBufferChans.addFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  29358. }
  29359. private:
  29360. const int srcChannelNum, dstChannelNum;
  29361. AddChannelOp (const AddChannelOp&);
  29362. AddChannelOp& operator= (const AddChannelOp&);
  29363. };
  29364. class ClearMidiBufferOp : public AudioGraphRenderingOp
  29365. {
  29366. public:
  29367. ClearMidiBufferOp (const int bufferNum_)
  29368. : bufferNum (bufferNum_)
  29369. {}
  29370. ~ClearMidiBufferOp() {}
  29371. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int)
  29372. {
  29373. sharedMidiBuffers.getUnchecked (bufferNum)->clear();
  29374. }
  29375. private:
  29376. const int bufferNum;
  29377. ClearMidiBufferOp (const ClearMidiBufferOp&);
  29378. ClearMidiBufferOp& operator= (const ClearMidiBufferOp&);
  29379. };
  29380. class CopyMidiBufferOp : public AudioGraphRenderingOp
  29381. {
  29382. public:
  29383. CopyMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_)
  29384. : srcBufferNum (srcBufferNum_),
  29385. dstBufferNum (dstBufferNum_)
  29386. {}
  29387. ~CopyMidiBufferOp() {}
  29388. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int)
  29389. {
  29390. *sharedMidiBuffers.getUnchecked (dstBufferNum) = *sharedMidiBuffers.getUnchecked (srcBufferNum);
  29391. }
  29392. private:
  29393. const int srcBufferNum, dstBufferNum;
  29394. CopyMidiBufferOp (const CopyMidiBufferOp&);
  29395. CopyMidiBufferOp& operator= (const CopyMidiBufferOp&);
  29396. };
  29397. class AddMidiBufferOp : public AudioGraphRenderingOp
  29398. {
  29399. public:
  29400. AddMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_)
  29401. : srcBufferNum (srcBufferNum_),
  29402. dstBufferNum (dstBufferNum_)
  29403. {}
  29404. ~AddMidiBufferOp() {}
  29405. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples)
  29406. {
  29407. sharedMidiBuffers.getUnchecked (dstBufferNum)
  29408. ->addEvents (*sharedMidiBuffers.getUnchecked (srcBufferNum), 0, numSamples, 0);
  29409. }
  29410. private:
  29411. const int srcBufferNum, dstBufferNum;
  29412. AddMidiBufferOp (const AddMidiBufferOp&);
  29413. AddMidiBufferOp& operator= (const AddMidiBufferOp&);
  29414. };
  29415. class ProcessBufferOp : public AudioGraphRenderingOp
  29416. {
  29417. public:
  29418. ProcessBufferOp (const AudioProcessorGraph::Node::Ptr& node_,
  29419. const Array <int>& audioChannelsToUse_,
  29420. const int totalChans_,
  29421. const int midiBufferToUse_)
  29422. : node (node_),
  29423. processor (node_->getProcessor()),
  29424. audioChannelsToUse (audioChannelsToUse_),
  29425. totalChans (jmax (1, totalChans_)),
  29426. midiBufferToUse (midiBufferToUse_)
  29427. {
  29428. channels.calloc (totalChans);
  29429. while (audioChannelsToUse.size() < totalChans)
  29430. audioChannelsToUse.add (0);
  29431. }
  29432. ~ProcessBufferOp()
  29433. {
  29434. }
  29435. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples)
  29436. {
  29437. for (int i = totalChans; --i >= 0;)
  29438. channels[i] = sharedBufferChans.getSampleData (audioChannelsToUse.getUnchecked (i), 0);
  29439. AudioSampleBuffer buffer (channels, totalChans, numSamples);
  29440. processor->processBlock (buffer, *sharedMidiBuffers.getUnchecked (midiBufferToUse));
  29441. }
  29442. const AudioProcessorGraph::Node::Ptr node;
  29443. AudioProcessor* const processor;
  29444. private:
  29445. Array <int> audioChannelsToUse;
  29446. HeapBlock <float*> channels;
  29447. int totalChans;
  29448. int midiBufferToUse;
  29449. ProcessBufferOp (const ProcessBufferOp&);
  29450. ProcessBufferOp& operator= (const ProcessBufferOp&);
  29451. };
  29452. /** Used to calculate the correct sequence of rendering ops needed, based on
  29453. the best re-use of shared buffers at each stage.
  29454. */
  29455. class RenderingOpSequenceCalculator
  29456. {
  29457. public:
  29458. RenderingOpSequenceCalculator (AudioProcessorGraph& graph_,
  29459. const Array<void*>& orderedNodes_,
  29460. Array<void*>& renderingOps)
  29461. : graph (graph_),
  29462. orderedNodes (orderedNodes_)
  29463. {
  29464. nodeIds.add (-2); // first buffer is read-only zeros
  29465. channels.add (0);
  29466. midiNodeIds.add (-2);
  29467. for (int i = 0; i < orderedNodes.size(); ++i)
  29468. {
  29469. createRenderingOpsForNode ((AudioProcessorGraph::Node*) orderedNodes.getUnchecked(i),
  29470. renderingOps, i);
  29471. markAnyUnusedBuffersAsFree (i);
  29472. }
  29473. }
  29474. int getNumBuffersNeeded() const { return nodeIds.size(); }
  29475. int getNumMidiBuffersNeeded() const { return midiNodeIds.size(); }
  29476. juce_UseDebuggingNewOperator
  29477. private:
  29478. AudioProcessorGraph& graph;
  29479. const Array<void*>& orderedNodes;
  29480. Array <int> nodeIds, channels, midiNodeIds;
  29481. void createRenderingOpsForNode (AudioProcessorGraph::Node* const node,
  29482. Array<void*>& renderingOps,
  29483. const int ourRenderingIndex)
  29484. {
  29485. const int numIns = node->getProcessor()->getNumInputChannels();
  29486. const int numOuts = node->getProcessor()->getNumOutputChannels();
  29487. const int totalChans = jmax (numIns, numOuts);
  29488. Array <int> audioChannelsToUse;
  29489. int midiBufferToUse = -1;
  29490. for (int inputChan = 0; inputChan < numIns; ++inputChan)
  29491. {
  29492. // get a list of all the inputs to this node
  29493. Array <int> sourceNodes, sourceOutputChans;
  29494. for (int i = graph.getNumConnections(); --i >= 0;)
  29495. {
  29496. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  29497. if (c->destNodeId == node->id && c->destChannelIndex == inputChan)
  29498. {
  29499. sourceNodes.add (c->sourceNodeId);
  29500. sourceOutputChans.add (c->sourceChannelIndex);
  29501. }
  29502. }
  29503. int bufIndex = -1;
  29504. if (sourceNodes.size() == 0)
  29505. {
  29506. // unconnected input channel
  29507. if (inputChan >= numOuts)
  29508. {
  29509. bufIndex = getReadOnlyEmptyBuffer();
  29510. jassert (bufIndex >= 0);
  29511. }
  29512. else
  29513. {
  29514. bufIndex = getFreeBuffer (false);
  29515. renderingOps.add (new ClearChannelOp (bufIndex));
  29516. }
  29517. }
  29518. else if (sourceNodes.size() == 1)
  29519. {
  29520. // channel with a straightforward single input..
  29521. const int srcNode = sourceNodes.getUnchecked(0);
  29522. const int srcChan = sourceOutputChans.getUnchecked(0);
  29523. bufIndex = getBufferContaining (srcNode, srcChan);
  29524. if (bufIndex < 0)
  29525. {
  29526. // if not found, this is probably a feedback loop
  29527. bufIndex = getReadOnlyEmptyBuffer();
  29528. jassert (bufIndex >= 0);
  29529. }
  29530. if (inputChan < numOuts
  29531. && isBufferNeededLater (ourRenderingIndex,
  29532. inputChan,
  29533. srcNode, srcChan))
  29534. {
  29535. // can't mess up this channel because it's needed later by another node, so we
  29536. // need to use a copy of it..
  29537. const int newFreeBuffer = getFreeBuffer (false);
  29538. renderingOps.add (new CopyChannelOp (bufIndex, newFreeBuffer));
  29539. bufIndex = newFreeBuffer;
  29540. }
  29541. }
  29542. else
  29543. {
  29544. // channel with a mix of several inputs..
  29545. // try to find a re-usable channel from our inputs..
  29546. int reusableInputIndex = -1;
  29547. for (int i = 0; i < sourceNodes.size(); ++i)
  29548. {
  29549. const int sourceBufIndex = getBufferContaining (sourceNodes.getUnchecked(i),
  29550. sourceOutputChans.getUnchecked(i));
  29551. if (sourceBufIndex >= 0
  29552. && ! isBufferNeededLater (ourRenderingIndex,
  29553. inputChan,
  29554. sourceNodes.getUnchecked(i),
  29555. sourceOutputChans.getUnchecked(i)))
  29556. {
  29557. // we've found one of our input chans that can be re-used..
  29558. reusableInputIndex = i;
  29559. bufIndex = sourceBufIndex;
  29560. break;
  29561. }
  29562. }
  29563. if (reusableInputIndex < 0)
  29564. {
  29565. // can't re-use any of our input chans, so get a new one and copy everything into it..
  29566. bufIndex = getFreeBuffer (false);
  29567. jassert (bufIndex != 0);
  29568. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked (0),
  29569. sourceOutputChans.getUnchecked (0));
  29570. if (srcIndex < 0)
  29571. {
  29572. // if not found, this is probably a feedback loop
  29573. renderingOps.add (new ClearChannelOp (bufIndex));
  29574. }
  29575. else
  29576. {
  29577. renderingOps.add (new CopyChannelOp (srcIndex, bufIndex));
  29578. }
  29579. reusableInputIndex = 0;
  29580. }
  29581. for (int j = 0; j < sourceNodes.size(); ++j)
  29582. {
  29583. if (j != reusableInputIndex)
  29584. {
  29585. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked(j),
  29586. sourceOutputChans.getUnchecked(j));
  29587. if (srcIndex >= 0)
  29588. renderingOps.add (new AddChannelOp (srcIndex, bufIndex));
  29589. }
  29590. }
  29591. }
  29592. jassert (bufIndex >= 0);
  29593. audioChannelsToUse.add (bufIndex);
  29594. if (inputChan < numOuts)
  29595. markBufferAsContaining (bufIndex, node->id, inputChan);
  29596. }
  29597. for (int outputChan = numIns; outputChan < numOuts; ++outputChan)
  29598. {
  29599. const int bufIndex = getFreeBuffer (false);
  29600. jassert (bufIndex != 0);
  29601. audioChannelsToUse.add (bufIndex);
  29602. markBufferAsContaining (bufIndex, node->id, outputChan);
  29603. }
  29604. // Now the same thing for midi..
  29605. Array <int> midiSourceNodes;
  29606. for (int i = graph.getNumConnections(); --i >= 0;)
  29607. {
  29608. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  29609. if (c->destNodeId == node->id && c->destChannelIndex == AudioProcessorGraph::midiChannelIndex)
  29610. midiSourceNodes.add (c->sourceNodeId);
  29611. }
  29612. if (midiSourceNodes.size() == 0)
  29613. {
  29614. // No midi inputs..
  29615. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  29616. if (node->getProcessor()->acceptsMidi() || node->getProcessor()->producesMidi())
  29617. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  29618. }
  29619. else if (midiSourceNodes.size() == 1)
  29620. {
  29621. // One midi input..
  29622. midiBufferToUse = getBufferContaining (midiSourceNodes.getUnchecked(0),
  29623. AudioProcessorGraph::midiChannelIndex);
  29624. if (midiBufferToUse >= 0)
  29625. {
  29626. if (isBufferNeededLater (ourRenderingIndex,
  29627. AudioProcessorGraph::midiChannelIndex,
  29628. midiSourceNodes.getUnchecked(0),
  29629. AudioProcessorGraph::midiChannelIndex))
  29630. {
  29631. // can't mess up this channel because it's needed later by another node, so we
  29632. // need to use a copy of it..
  29633. const int newFreeBuffer = getFreeBuffer (true);
  29634. renderingOps.add (new CopyMidiBufferOp (midiBufferToUse, newFreeBuffer));
  29635. midiBufferToUse = newFreeBuffer;
  29636. }
  29637. }
  29638. else
  29639. {
  29640. // probably a feedback loop, so just use an empty one..
  29641. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  29642. }
  29643. }
  29644. else
  29645. {
  29646. // More than one midi input being mixed..
  29647. int reusableInputIndex = -1;
  29648. for (int i = 0; i < midiSourceNodes.size(); ++i)
  29649. {
  29650. const int sourceBufIndex = getBufferContaining (midiSourceNodes.getUnchecked(i),
  29651. AudioProcessorGraph::midiChannelIndex);
  29652. if (sourceBufIndex >= 0
  29653. && ! isBufferNeededLater (ourRenderingIndex,
  29654. AudioProcessorGraph::midiChannelIndex,
  29655. midiSourceNodes.getUnchecked(i),
  29656. AudioProcessorGraph::midiChannelIndex))
  29657. {
  29658. // we've found one of our input buffers that can be re-used..
  29659. reusableInputIndex = i;
  29660. midiBufferToUse = sourceBufIndex;
  29661. break;
  29662. }
  29663. }
  29664. if (reusableInputIndex < 0)
  29665. {
  29666. // can't re-use any of our input buffers, so get a new one and copy everything into it..
  29667. midiBufferToUse = getFreeBuffer (true);
  29668. jassert (midiBufferToUse >= 0);
  29669. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(0),
  29670. AudioProcessorGraph::midiChannelIndex);
  29671. if (srcIndex >= 0)
  29672. renderingOps.add (new CopyMidiBufferOp (srcIndex, midiBufferToUse));
  29673. else
  29674. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  29675. reusableInputIndex = 0;
  29676. }
  29677. for (int j = 0; j < midiSourceNodes.size(); ++j)
  29678. {
  29679. if (j != reusableInputIndex)
  29680. {
  29681. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(j),
  29682. AudioProcessorGraph::midiChannelIndex);
  29683. if (srcIndex >= 0)
  29684. renderingOps.add (new AddMidiBufferOp (srcIndex, midiBufferToUse));
  29685. }
  29686. }
  29687. }
  29688. if (node->getProcessor()->producesMidi())
  29689. markBufferAsContaining (midiBufferToUse, node->id,
  29690. AudioProcessorGraph::midiChannelIndex);
  29691. renderingOps.add (new ProcessBufferOp (node, audioChannelsToUse,
  29692. totalChans, midiBufferToUse));
  29693. }
  29694. int getFreeBuffer (const bool forMidi)
  29695. {
  29696. if (forMidi)
  29697. {
  29698. for (int i = 1; i < midiNodeIds.size(); ++i)
  29699. if (midiNodeIds.getUnchecked(i) < 0)
  29700. return i;
  29701. midiNodeIds.add (-1);
  29702. return midiNodeIds.size() - 1;
  29703. }
  29704. else
  29705. {
  29706. for (int i = 1; i < nodeIds.size(); ++i)
  29707. if (nodeIds.getUnchecked(i) < 0)
  29708. return i;
  29709. nodeIds.add (-1);
  29710. channels.add (0);
  29711. return nodeIds.size() - 1;
  29712. }
  29713. }
  29714. int getReadOnlyEmptyBuffer() const
  29715. {
  29716. return 0;
  29717. }
  29718. int getBufferContaining (const int nodeId, const int outputChannel) const
  29719. {
  29720. if (outputChannel == AudioProcessorGraph::midiChannelIndex)
  29721. {
  29722. for (int i = midiNodeIds.size(); --i >= 0;)
  29723. if (midiNodeIds.getUnchecked(i) == nodeId)
  29724. return i;
  29725. }
  29726. else
  29727. {
  29728. for (int i = nodeIds.size(); --i >= 0;)
  29729. if (nodeIds.getUnchecked(i) == nodeId
  29730. && channels.getUnchecked(i) == outputChannel)
  29731. return i;
  29732. }
  29733. return -1;
  29734. }
  29735. void markAnyUnusedBuffersAsFree (const int stepIndex)
  29736. {
  29737. int i;
  29738. for (i = 0; i < nodeIds.size(); ++i)
  29739. {
  29740. if (nodeIds.getUnchecked(i) >= 0
  29741. && ! isBufferNeededLater (stepIndex, -1,
  29742. nodeIds.getUnchecked(i),
  29743. channels.getUnchecked(i)))
  29744. {
  29745. nodeIds.set (i, -1);
  29746. }
  29747. }
  29748. for (i = 0; i < midiNodeIds.size(); ++i)
  29749. {
  29750. if (midiNodeIds.getUnchecked(i) >= 0
  29751. && ! isBufferNeededLater (stepIndex, -1,
  29752. midiNodeIds.getUnchecked(i),
  29753. AudioProcessorGraph::midiChannelIndex))
  29754. {
  29755. midiNodeIds.set (i, -1);
  29756. }
  29757. }
  29758. }
  29759. bool isBufferNeededLater (int stepIndexToSearchFrom,
  29760. int inputChannelOfIndexToIgnore,
  29761. const int nodeId,
  29762. const int outputChanIndex) const
  29763. {
  29764. while (stepIndexToSearchFrom < orderedNodes.size())
  29765. {
  29766. const AudioProcessorGraph::Node* const node = (const AudioProcessorGraph::Node*) orderedNodes.getUnchecked (stepIndexToSearchFrom);
  29767. if (outputChanIndex == AudioProcessorGraph::midiChannelIndex)
  29768. {
  29769. if (inputChannelOfIndexToIgnore != AudioProcessorGraph::midiChannelIndex
  29770. && graph.getConnectionBetween (nodeId, AudioProcessorGraph::midiChannelIndex,
  29771. node->id, AudioProcessorGraph::midiChannelIndex) != 0)
  29772. return true;
  29773. }
  29774. else
  29775. {
  29776. for (int i = 0; i < node->getProcessor()->getNumInputChannels(); ++i)
  29777. if (i != inputChannelOfIndexToIgnore
  29778. && graph.getConnectionBetween (nodeId, outputChanIndex,
  29779. node->id, i) != 0)
  29780. return true;
  29781. }
  29782. inputChannelOfIndexToIgnore = -1;
  29783. ++stepIndexToSearchFrom;
  29784. }
  29785. return false;
  29786. }
  29787. void markBufferAsContaining (int bufferNum, int nodeId, int outputIndex)
  29788. {
  29789. if (outputIndex == AudioProcessorGraph::midiChannelIndex)
  29790. {
  29791. jassert (bufferNum > 0 && bufferNum < midiNodeIds.size());
  29792. midiNodeIds.set (bufferNum, nodeId);
  29793. }
  29794. else
  29795. {
  29796. jassert (bufferNum >= 0 && bufferNum < nodeIds.size());
  29797. nodeIds.set (bufferNum, nodeId);
  29798. channels.set (bufferNum, outputIndex);
  29799. }
  29800. }
  29801. RenderingOpSequenceCalculator (const RenderingOpSequenceCalculator&);
  29802. RenderingOpSequenceCalculator& operator= (const RenderingOpSequenceCalculator&);
  29803. };
  29804. }
  29805. void AudioProcessorGraph::clearRenderingSequence()
  29806. {
  29807. const ScopedLock sl (renderLock);
  29808. for (int i = renderingOps.size(); --i >= 0;)
  29809. {
  29810. GraphRenderingOps::AudioGraphRenderingOp* const r
  29811. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  29812. renderingOps.remove (i);
  29813. delete r;
  29814. }
  29815. }
  29816. bool AudioProcessorGraph::isAnInputTo (const uint32 possibleInputId,
  29817. const uint32 possibleDestinationId,
  29818. const int recursionCheck) const
  29819. {
  29820. if (recursionCheck > 0)
  29821. {
  29822. for (int i = connections.size(); --i >= 0;)
  29823. {
  29824. const AudioProcessorGraph::Connection* const c = connections.getUnchecked (i);
  29825. if (c->destNodeId == possibleDestinationId
  29826. && (c->sourceNodeId == possibleInputId
  29827. || isAnInputTo (possibleInputId, c->sourceNodeId, recursionCheck - 1)))
  29828. return true;
  29829. }
  29830. }
  29831. return false;
  29832. }
  29833. void AudioProcessorGraph::buildRenderingSequence()
  29834. {
  29835. Array<void*> newRenderingOps;
  29836. int numRenderingBuffersNeeded = 2;
  29837. int numMidiBuffersNeeded = 1;
  29838. {
  29839. MessageManagerLock mml;
  29840. Array<void*> orderedNodes;
  29841. int i;
  29842. for (i = 0; i < nodes.size(); ++i)
  29843. {
  29844. Node* const node = nodes.getUnchecked(i);
  29845. node->prepare (getSampleRate(), getBlockSize(), this);
  29846. int j = 0;
  29847. for (; j < orderedNodes.size(); ++j)
  29848. if (isAnInputTo (node->id,
  29849. ((Node*) orderedNodes.getUnchecked (j))->id,
  29850. nodes.size() + 1))
  29851. break;
  29852. orderedNodes.insert (j, node);
  29853. }
  29854. GraphRenderingOps::RenderingOpSequenceCalculator calculator (*this, orderedNodes, newRenderingOps);
  29855. numRenderingBuffersNeeded = calculator.getNumBuffersNeeded();
  29856. numMidiBuffersNeeded = calculator.getNumMidiBuffersNeeded();
  29857. }
  29858. Array<void*> oldRenderingOps (renderingOps);
  29859. {
  29860. // swap over to the new rendering sequence..
  29861. const ScopedLock sl (renderLock);
  29862. renderingBuffers.setSize (numRenderingBuffersNeeded, getBlockSize());
  29863. renderingBuffers.clear();
  29864. for (int i = midiBuffers.size(); --i >= 0;)
  29865. midiBuffers.getUnchecked(i)->clear();
  29866. while (midiBuffers.size() < numMidiBuffersNeeded)
  29867. midiBuffers.add (new MidiBuffer());
  29868. renderingOps = newRenderingOps;
  29869. }
  29870. for (int i = oldRenderingOps.size(); --i >= 0;)
  29871. delete (GraphRenderingOps::AudioGraphRenderingOp*) oldRenderingOps.getUnchecked(i);
  29872. }
  29873. void AudioProcessorGraph::handleAsyncUpdate()
  29874. {
  29875. buildRenderingSequence();
  29876. }
  29877. void AudioProcessorGraph::prepareToPlay (double /*sampleRate*/, int estimatedSamplesPerBlock)
  29878. {
  29879. currentAudioInputBuffer = 0;
  29880. currentAudioOutputBuffer.setSize (jmax (1, getNumOutputChannels()), estimatedSamplesPerBlock);
  29881. currentMidiInputBuffer = 0;
  29882. currentMidiOutputBuffer.clear();
  29883. clearRenderingSequence();
  29884. buildRenderingSequence();
  29885. }
  29886. void AudioProcessorGraph::releaseResources()
  29887. {
  29888. for (int i = 0; i < nodes.size(); ++i)
  29889. nodes.getUnchecked(i)->unprepare();
  29890. renderingBuffers.setSize (1, 1);
  29891. midiBuffers.clear();
  29892. currentAudioInputBuffer = 0;
  29893. currentAudioOutputBuffer.setSize (1, 1);
  29894. currentMidiInputBuffer = 0;
  29895. currentMidiOutputBuffer.clear();
  29896. }
  29897. void AudioProcessorGraph::processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages)
  29898. {
  29899. const int numSamples = buffer.getNumSamples();
  29900. const ScopedLock sl (renderLock);
  29901. currentAudioInputBuffer = &buffer;
  29902. currentAudioOutputBuffer.setSize (jmax (1, buffer.getNumChannels()), numSamples);
  29903. currentAudioOutputBuffer.clear();
  29904. currentMidiInputBuffer = &midiMessages;
  29905. currentMidiOutputBuffer.clear();
  29906. int i;
  29907. for (i = 0; i < renderingOps.size(); ++i)
  29908. {
  29909. GraphRenderingOps::AudioGraphRenderingOp* const op
  29910. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  29911. op->perform (renderingBuffers, midiBuffers, numSamples);
  29912. }
  29913. for (i = 0; i < buffer.getNumChannels(); ++i)
  29914. buffer.copyFrom (i, 0, currentAudioOutputBuffer, i, 0, numSamples);
  29915. midiMessages.clear();
  29916. midiMessages.addEvents (currentMidiOutputBuffer, 0, buffer.getNumSamples(), 0);
  29917. }
  29918. const String AudioProcessorGraph::getInputChannelName (int channelIndex) const
  29919. {
  29920. return "Input " + String (channelIndex + 1);
  29921. }
  29922. const String AudioProcessorGraph::getOutputChannelName (int channelIndex) const
  29923. {
  29924. return "Output " + String (channelIndex + 1);
  29925. }
  29926. bool AudioProcessorGraph::isInputChannelStereoPair (int /*index*/) const { return true; }
  29927. bool AudioProcessorGraph::isOutputChannelStereoPair (int /*index*/) const { return true; }
  29928. bool AudioProcessorGraph::acceptsMidi() const { return true; }
  29929. bool AudioProcessorGraph::producesMidi() const { return true; }
  29930. void AudioProcessorGraph::getStateInformation (JUCE_NAMESPACE::MemoryBlock& /*destData*/) {}
  29931. void AudioProcessorGraph::setStateInformation (const void* /*data*/, int /*sizeInBytes*/) {}
  29932. AudioProcessorGraph::AudioGraphIOProcessor::AudioGraphIOProcessor (const IODeviceType type_)
  29933. : type (type_),
  29934. graph (0)
  29935. {
  29936. }
  29937. AudioProcessorGraph::AudioGraphIOProcessor::~AudioGraphIOProcessor()
  29938. {
  29939. }
  29940. const String AudioProcessorGraph::AudioGraphIOProcessor::getName() const
  29941. {
  29942. switch (type)
  29943. {
  29944. case audioOutputNode: return "Audio Output";
  29945. case audioInputNode: return "Audio Input";
  29946. case midiOutputNode: return "Midi Output";
  29947. case midiInputNode: return "Midi Input";
  29948. default: break;
  29949. }
  29950. return String::empty;
  29951. }
  29952. void AudioProcessorGraph::AudioGraphIOProcessor::fillInPluginDescription (PluginDescription& d) const
  29953. {
  29954. d.name = getName();
  29955. d.uid = d.name.hashCode();
  29956. d.category = "I/O devices";
  29957. d.pluginFormatName = "Internal";
  29958. d.manufacturerName = "Raw Material Software";
  29959. d.version = "1.0";
  29960. d.isInstrument = false;
  29961. d.numInputChannels = getNumInputChannels();
  29962. if (type == audioOutputNode && graph != 0)
  29963. d.numInputChannels = graph->getNumInputChannels();
  29964. d.numOutputChannels = getNumOutputChannels();
  29965. if (type == audioInputNode && graph != 0)
  29966. d.numOutputChannels = graph->getNumOutputChannels();
  29967. }
  29968. void AudioProcessorGraph::AudioGraphIOProcessor::prepareToPlay (double, int)
  29969. {
  29970. jassert (graph != 0);
  29971. }
  29972. void AudioProcessorGraph::AudioGraphIOProcessor::releaseResources()
  29973. {
  29974. }
  29975. void AudioProcessorGraph::AudioGraphIOProcessor::processBlock (AudioSampleBuffer& buffer,
  29976. MidiBuffer& midiMessages)
  29977. {
  29978. jassert (graph != 0);
  29979. switch (type)
  29980. {
  29981. case audioOutputNode:
  29982. {
  29983. for (int i = jmin (graph->currentAudioOutputBuffer.getNumChannels(),
  29984. buffer.getNumChannels()); --i >= 0;)
  29985. {
  29986. graph->currentAudioOutputBuffer.addFrom (i, 0, buffer, i, 0, buffer.getNumSamples());
  29987. }
  29988. break;
  29989. }
  29990. case audioInputNode:
  29991. {
  29992. for (int i = jmin (graph->currentAudioInputBuffer->getNumChannels(),
  29993. buffer.getNumChannels()); --i >= 0;)
  29994. {
  29995. buffer.copyFrom (i, 0, *graph->currentAudioInputBuffer, i, 0, buffer.getNumSamples());
  29996. }
  29997. break;
  29998. }
  29999. case midiOutputNode:
  30000. graph->currentMidiOutputBuffer.addEvents (midiMessages, 0, buffer.getNumSamples(), 0);
  30001. break;
  30002. case midiInputNode:
  30003. midiMessages.addEvents (*graph->currentMidiInputBuffer, 0, buffer.getNumSamples(), 0);
  30004. break;
  30005. default:
  30006. break;
  30007. }
  30008. }
  30009. bool AudioProcessorGraph::AudioGraphIOProcessor::acceptsMidi() const
  30010. {
  30011. return type == midiOutputNode;
  30012. }
  30013. bool AudioProcessorGraph::AudioGraphIOProcessor::producesMidi() const
  30014. {
  30015. return type == midiInputNode;
  30016. }
  30017. const String AudioProcessorGraph::AudioGraphIOProcessor::getInputChannelName (int channelIndex) const
  30018. {
  30019. switch (type)
  30020. {
  30021. case audioOutputNode: return "Output " + String (channelIndex + 1);
  30022. case midiOutputNode: return "Midi Output";
  30023. default: break;
  30024. }
  30025. return String::empty;
  30026. }
  30027. const String AudioProcessorGraph::AudioGraphIOProcessor::getOutputChannelName (int channelIndex) const
  30028. {
  30029. switch (type)
  30030. {
  30031. case audioInputNode: return "Input " + String (channelIndex + 1);
  30032. case midiInputNode: return "Midi Input";
  30033. default: break;
  30034. }
  30035. return String::empty;
  30036. }
  30037. bool AudioProcessorGraph::AudioGraphIOProcessor::isInputChannelStereoPair (int /*index*/) const
  30038. {
  30039. return type == audioInputNode || type == audioOutputNode;
  30040. }
  30041. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutputChannelStereoPair (int index) const
  30042. {
  30043. return isInputChannelStereoPair (index);
  30044. }
  30045. bool AudioProcessorGraph::AudioGraphIOProcessor::isInput() const
  30046. {
  30047. return type == audioInputNode || type == midiInputNode;
  30048. }
  30049. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutput() const
  30050. {
  30051. return type == audioOutputNode || type == midiOutputNode;
  30052. }
  30053. bool AudioProcessorGraph::AudioGraphIOProcessor::hasEditor() const { return false; }
  30054. AudioProcessorEditor* AudioProcessorGraph::AudioGraphIOProcessor::createEditor() { return 0; }
  30055. int AudioProcessorGraph::AudioGraphIOProcessor::getNumParameters() { return 0; }
  30056. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterName (int) { return String::empty; }
  30057. float AudioProcessorGraph::AudioGraphIOProcessor::getParameter (int) { return 0.0f; }
  30058. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterText (int) { return String::empty; }
  30059. void AudioProcessorGraph::AudioGraphIOProcessor::setParameter (int, float) { }
  30060. int AudioProcessorGraph::AudioGraphIOProcessor::getNumPrograms() { return 0; }
  30061. int AudioProcessorGraph::AudioGraphIOProcessor::getCurrentProgram() { return 0; }
  30062. void AudioProcessorGraph::AudioGraphIOProcessor::setCurrentProgram (int) { }
  30063. const String AudioProcessorGraph::AudioGraphIOProcessor::getProgramName (int) { return String::empty; }
  30064. void AudioProcessorGraph::AudioGraphIOProcessor::changeProgramName (int, const String&) { }
  30065. void AudioProcessorGraph::AudioGraphIOProcessor::getStateInformation (JUCE_NAMESPACE::MemoryBlock&)
  30066. {
  30067. }
  30068. void AudioProcessorGraph::AudioGraphIOProcessor::setStateInformation (const void*, int)
  30069. {
  30070. }
  30071. void AudioProcessorGraph::AudioGraphIOProcessor::setParentGraph (AudioProcessorGraph* const newGraph)
  30072. {
  30073. graph = newGraph;
  30074. if (graph != 0)
  30075. {
  30076. setPlayConfigDetails (type == audioOutputNode ? graph->getNumOutputChannels() : 0,
  30077. type == audioInputNode ? graph->getNumInputChannels() : 0,
  30078. getSampleRate(),
  30079. getBlockSize());
  30080. updateHostDisplay();
  30081. }
  30082. }
  30083. END_JUCE_NAMESPACE
  30084. /*** End of inlined file: juce_AudioProcessorGraph.cpp ***/
  30085. /*** Start of inlined file: juce_AudioProcessorPlayer.cpp ***/
  30086. BEGIN_JUCE_NAMESPACE
  30087. AudioProcessorPlayer::AudioProcessorPlayer()
  30088. : processor (0),
  30089. sampleRate (0),
  30090. blockSize (0),
  30091. isPrepared (false),
  30092. numInputChans (0),
  30093. numOutputChans (0),
  30094. tempBuffer (1, 1)
  30095. {
  30096. }
  30097. AudioProcessorPlayer::~AudioProcessorPlayer()
  30098. {
  30099. setProcessor (0);
  30100. }
  30101. void AudioProcessorPlayer::setProcessor (AudioProcessor* const processorToPlay)
  30102. {
  30103. if (processor != processorToPlay)
  30104. {
  30105. if (processorToPlay != 0 && sampleRate > 0 && blockSize > 0)
  30106. {
  30107. processorToPlay->setPlayConfigDetails (numInputChans, numOutputChans,
  30108. sampleRate, blockSize);
  30109. processorToPlay->prepareToPlay (sampleRate, blockSize);
  30110. }
  30111. AudioProcessor* oldOne;
  30112. {
  30113. const ScopedLock sl (lock);
  30114. oldOne = isPrepared ? processor : 0;
  30115. processor = processorToPlay;
  30116. isPrepared = true;
  30117. }
  30118. if (oldOne != 0)
  30119. oldOne->releaseResources();
  30120. }
  30121. }
  30122. void AudioProcessorPlayer::audioDeviceIOCallback (const float** const inputChannelData,
  30123. const int numInputChannels,
  30124. float** const outputChannelData,
  30125. const int numOutputChannels,
  30126. const int numSamples)
  30127. {
  30128. // these should have been prepared by audioDeviceAboutToStart()...
  30129. jassert (sampleRate > 0 && blockSize > 0);
  30130. incomingMidi.clear();
  30131. messageCollector.removeNextBlockOfMessages (incomingMidi, numSamples);
  30132. int i, totalNumChans = 0;
  30133. if (numInputChannels > numOutputChannels)
  30134. {
  30135. // if there aren't enough output channels for the number of
  30136. // inputs, we need to create some temporary extra ones (can't
  30137. // use the input data in case it gets written to)
  30138. tempBuffer.setSize (numInputChannels - numOutputChannels, numSamples,
  30139. false, false, true);
  30140. for (i = 0; i < numOutputChannels; ++i)
  30141. {
  30142. channels[totalNumChans] = outputChannelData[i];
  30143. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  30144. ++totalNumChans;
  30145. }
  30146. for (i = numOutputChannels; i < numInputChannels; ++i)
  30147. {
  30148. channels[totalNumChans] = tempBuffer.getSampleData (i - numOutputChannels, 0);
  30149. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  30150. ++totalNumChans;
  30151. }
  30152. }
  30153. else
  30154. {
  30155. for (i = 0; i < numInputChannels; ++i)
  30156. {
  30157. channels[totalNumChans] = outputChannelData[i];
  30158. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  30159. ++totalNumChans;
  30160. }
  30161. for (i = numInputChannels; i < numOutputChannels; ++i)
  30162. {
  30163. channels[totalNumChans] = outputChannelData[i];
  30164. zeromem (channels[totalNumChans], sizeof (float) * numSamples);
  30165. ++totalNumChans;
  30166. }
  30167. }
  30168. AudioSampleBuffer buffer (channels, totalNumChans, numSamples);
  30169. const ScopedLock sl (lock);
  30170. if (processor != 0)
  30171. {
  30172. const ScopedLock sl (processor->getCallbackLock());
  30173. if (processor->isSuspended())
  30174. {
  30175. for (i = 0; i < numOutputChannels; ++i)
  30176. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  30177. }
  30178. else
  30179. {
  30180. processor->processBlock (buffer, incomingMidi);
  30181. }
  30182. }
  30183. }
  30184. void AudioProcessorPlayer::audioDeviceAboutToStart (AudioIODevice* device)
  30185. {
  30186. const ScopedLock sl (lock);
  30187. sampleRate = device->getCurrentSampleRate();
  30188. blockSize = device->getCurrentBufferSizeSamples();
  30189. numInputChans = device->getActiveInputChannels().countNumberOfSetBits();
  30190. numOutputChans = device->getActiveOutputChannels().countNumberOfSetBits();
  30191. messageCollector.reset (sampleRate);
  30192. zeromem (channels, sizeof (channels));
  30193. if (processor != 0)
  30194. {
  30195. if (isPrepared)
  30196. processor->releaseResources();
  30197. AudioProcessor* const oldProcessor = processor;
  30198. setProcessor (0);
  30199. setProcessor (oldProcessor);
  30200. }
  30201. }
  30202. void AudioProcessorPlayer::audioDeviceStopped()
  30203. {
  30204. const ScopedLock sl (lock);
  30205. if (processor != 0 && isPrepared)
  30206. processor->releaseResources();
  30207. sampleRate = 0.0;
  30208. blockSize = 0;
  30209. isPrepared = false;
  30210. tempBuffer.setSize (1, 1);
  30211. }
  30212. void AudioProcessorPlayer::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  30213. {
  30214. messageCollector.addMessageToQueue (message);
  30215. }
  30216. END_JUCE_NAMESPACE
  30217. /*** End of inlined file: juce_AudioProcessorPlayer.cpp ***/
  30218. /*** Start of inlined file: juce_GenericAudioProcessorEditor.cpp ***/
  30219. BEGIN_JUCE_NAMESPACE
  30220. class ProcessorParameterPropertyComp : public PropertyComponent,
  30221. public AudioProcessorListener,
  30222. public Timer
  30223. {
  30224. public:
  30225. ProcessorParameterPropertyComp (const String& name, AudioProcessor& owner_, const int index_)
  30226. : PropertyComponent (name),
  30227. owner (owner_),
  30228. index (index_),
  30229. paramHasChanged (false),
  30230. slider (owner_, index_)
  30231. {
  30232. startTimer (100);
  30233. addAndMakeVisible (&slider);
  30234. owner_.addListener (this);
  30235. }
  30236. ~ProcessorParameterPropertyComp()
  30237. {
  30238. owner.removeListener (this);
  30239. }
  30240. void refresh()
  30241. {
  30242. paramHasChanged = false;
  30243. slider.setValue (owner.getParameter (index), false);
  30244. }
  30245. void audioProcessorChanged (AudioProcessor*) {}
  30246. void audioProcessorParameterChanged (AudioProcessor*, int parameterIndex, float)
  30247. {
  30248. if (parameterIndex == index)
  30249. paramHasChanged = true;
  30250. }
  30251. void timerCallback()
  30252. {
  30253. if (paramHasChanged)
  30254. {
  30255. refresh();
  30256. startTimer (1000 / 50);
  30257. }
  30258. else
  30259. {
  30260. startTimer (jmin (1000 / 4, getTimerInterval() + 10));
  30261. }
  30262. }
  30263. juce_UseDebuggingNewOperator
  30264. private:
  30265. class ParamSlider : public Slider
  30266. {
  30267. public:
  30268. ParamSlider (AudioProcessor& owner_, const int index_)
  30269. : owner (owner_),
  30270. index (index_)
  30271. {
  30272. setRange (0.0, 1.0, 0.0);
  30273. setSliderStyle (Slider::LinearBar);
  30274. setTextBoxIsEditable (false);
  30275. setScrollWheelEnabled (false);
  30276. }
  30277. void valueChanged()
  30278. {
  30279. const float newVal = (float) getValue();
  30280. if (owner.getParameter (index) != newVal)
  30281. owner.setParameter (index, newVal);
  30282. }
  30283. const String getTextFromValue (double /*value*/)
  30284. {
  30285. return owner.getParameterText (index);
  30286. }
  30287. juce_UseDebuggingNewOperator
  30288. private:
  30289. AudioProcessor& owner;
  30290. const int index;
  30291. ParamSlider (const ParamSlider&);
  30292. ParamSlider& operator= (const ParamSlider&);
  30293. };
  30294. AudioProcessor& owner;
  30295. const int index;
  30296. bool volatile paramHasChanged;
  30297. ParamSlider slider;
  30298. ProcessorParameterPropertyComp (const ProcessorParameterPropertyComp&);
  30299. ProcessorParameterPropertyComp& operator= (const ProcessorParameterPropertyComp&);
  30300. };
  30301. GenericAudioProcessorEditor::GenericAudioProcessorEditor (AudioProcessor* const owner_)
  30302. : AudioProcessorEditor (owner_)
  30303. {
  30304. jassert (owner_ != 0);
  30305. setOpaque (true);
  30306. addAndMakeVisible (&panel);
  30307. Array <PropertyComponent*> params;
  30308. const int numParams = owner_->getNumParameters();
  30309. int totalHeight = 0;
  30310. for (int i = 0; i < numParams; ++i)
  30311. {
  30312. String name (owner_->getParameterName (i));
  30313. if (name.trim().isEmpty())
  30314. name = "Unnamed";
  30315. ProcessorParameterPropertyComp* const pc = new ProcessorParameterPropertyComp (name, *owner_, i);
  30316. params.add (pc);
  30317. totalHeight += pc->getPreferredHeight();
  30318. }
  30319. panel.addProperties (params);
  30320. setSize (400, jlimit (25, 400, totalHeight));
  30321. }
  30322. GenericAudioProcessorEditor::~GenericAudioProcessorEditor()
  30323. {
  30324. }
  30325. void GenericAudioProcessorEditor::paint (Graphics& g)
  30326. {
  30327. g.fillAll (Colours::white);
  30328. }
  30329. void GenericAudioProcessorEditor::resized()
  30330. {
  30331. panel.setBounds (getLocalBounds());
  30332. }
  30333. END_JUCE_NAMESPACE
  30334. /*** End of inlined file: juce_GenericAudioProcessorEditor.cpp ***/
  30335. /*** Start of inlined file: juce_Sampler.cpp ***/
  30336. BEGIN_JUCE_NAMESPACE
  30337. SamplerSound::SamplerSound (const String& name_,
  30338. AudioFormatReader& source,
  30339. const BigInteger& midiNotes_,
  30340. const int midiNoteForNormalPitch,
  30341. const double attackTimeSecs,
  30342. const double releaseTimeSecs,
  30343. const double maxSampleLengthSeconds)
  30344. : name (name_),
  30345. midiNotes (midiNotes_),
  30346. midiRootNote (midiNoteForNormalPitch)
  30347. {
  30348. sourceSampleRate = source.sampleRate;
  30349. if (sourceSampleRate <= 0 || source.lengthInSamples <= 0)
  30350. {
  30351. length = 0;
  30352. attackSamples = 0;
  30353. releaseSamples = 0;
  30354. }
  30355. else
  30356. {
  30357. length = jmin ((int) source.lengthInSamples,
  30358. (int) (maxSampleLengthSeconds * sourceSampleRate));
  30359. data = new AudioSampleBuffer (jmin (2, (int) source.numChannels), length + 4);
  30360. data->readFromAudioReader (&source, 0, length + 4, 0, true, true);
  30361. attackSamples = roundToInt (attackTimeSecs * sourceSampleRate);
  30362. releaseSamples = roundToInt (releaseTimeSecs * sourceSampleRate);
  30363. }
  30364. }
  30365. SamplerSound::~SamplerSound()
  30366. {
  30367. }
  30368. bool SamplerSound::appliesToNote (const int midiNoteNumber)
  30369. {
  30370. return midiNotes [midiNoteNumber];
  30371. }
  30372. bool SamplerSound::appliesToChannel (const int /*midiChannel*/)
  30373. {
  30374. return true;
  30375. }
  30376. SamplerVoice::SamplerVoice()
  30377. : pitchRatio (0.0),
  30378. sourceSamplePosition (0.0),
  30379. lgain (0.0f),
  30380. rgain (0.0f),
  30381. isInAttack (false),
  30382. isInRelease (false)
  30383. {
  30384. }
  30385. SamplerVoice::~SamplerVoice()
  30386. {
  30387. }
  30388. bool SamplerVoice::canPlaySound (SynthesiserSound* sound)
  30389. {
  30390. return dynamic_cast <const SamplerSound*> (sound) != 0;
  30391. }
  30392. void SamplerVoice::startNote (const int midiNoteNumber,
  30393. const float velocity,
  30394. SynthesiserSound* s,
  30395. const int /*currentPitchWheelPosition*/)
  30396. {
  30397. const SamplerSound* const sound = dynamic_cast <const SamplerSound*> (s);
  30398. jassert (sound != 0); // this object can only play SamplerSounds!
  30399. if (sound != 0)
  30400. {
  30401. const double targetFreq = MidiMessage::getMidiNoteInHertz (midiNoteNumber);
  30402. const double naturalFreq = MidiMessage::getMidiNoteInHertz (sound->midiRootNote);
  30403. pitchRatio = (targetFreq * sound->sourceSampleRate) / (naturalFreq * getSampleRate());
  30404. sourceSamplePosition = 0.0;
  30405. lgain = velocity;
  30406. rgain = velocity;
  30407. isInAttack = (sound->attackSamples > 0);
  30408. isInRelease = false;
  30409. if (isInAttack)
  30410. {
  30411. attackReleaseLevel = 0.0f;
  30412. attackDelta = (float) (pitchRatio / sound->attackSamples);
  30413. }
  30414. else
  30415. {
  30416. attackReleaseLevel = 1.0f;
  30417. attackDelta = 0.0f;
  30418. }
  30419. if (sound->releaseSamples > 0)
  30420. {
  30421. releaseDelta = (float) (-pitchRatio / sound->releaseSamples);
  30422. }
  30423. else
  30424. {
  30425. releaseDelta = 0.0f;
  30426. }
  30427. }
  30428. }
  30429. void SamplerVoice::stopNote (const bool allowTailOff)
  30430. {
  30431. if (allowTailOff)
  30432. {
  30433. isInAttack = false;
  30434. isInRelease = true;
  30435. }
  30436. else
  30437. {
  30438. clearCurrentNote();
  30439. }
  30440. }
  30441. void SamplerVoice::pitchWheelMoved (const int /*newValue*/)
  30442. {
  30443. }
  30444. void SamplerVoice::controllerMoved (const int /*controllerNumber*/,
  30445. const int /*newValue*/)
  30446. {
  30447. }
  30448. void SamplerVoice::renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples)
  30449. {
  30450. const SamplerSound* const playingSound = static_cast <SamplerSound*> (getCurrentlyPlayingSound().getObject());
  30451. if (playingSound != 0)
  30452. {
  30453. const float* const inL = playingSound->data->getSampleData (0, 0);
  30454. const float* const inR = playingSound->data->getNumChannels() > 1
  30455. ? playingSound->data->getSampleData (1, 0) : 0;
  30456. float* outL = outputBuffer.getSampleData (0, startSample);
  30457. float* outR = outputBuffer.getNumChannels() > 1 ? outputBuffer.getSampleData (1, startSample) : 0;
  30458. while (--numSamples >= 0)
  30459. {
  30460. const int pos = (int) sourceSamplePosition;
  30461. const float alpha = (float) (sourceSamplePosition - pos);
  30462. const float invAlpha = 1.0f - alpha;
  30463. // just using a very simple linear interpolation here..
  30464. float l = (inL [pos] * invAlpha + inL [pos + 1] * alpha);
  30465. float r = (inR != 0) ? (inR [pos] * invAlpha + inR [pos + 1] * alpha)
  30466. : l;
  30467. l *= lgain;
  30468. r *= rgain;
  30469. if (isInAttack)
  30470. {
  30471. l *= attackReleaseLevel;
  30472. r *= attackReleaseLevel;
  30473. attackReleaseLevel += attackDelta;
  30474. if (attackReleaseLevel >= 1.0f)
  30475. {
  30476. attackReleaseLevel = 1.0f;
  30477. isInAttack = false;
  30478. }
  30479. }
  30480. else if (isInRelease)
  30481. {
  30482. l *= attackReleaseLevel;
  30483. r *= attackReleaseLevel;
  30484. attackReleaseLevel += releaseDelta;
  30485. if (attackReleaseLevel <= 0.0f)
  30486. {
  30487. stopNote (false);
  30488. break;
  30489. }
  30490. }
  30491. if (outR != 0)
  30492. {
  30493. *outL++ += l;
  30494. *outR++ += r;
  30495. }
  30496. else
  30497. {
  30498. *outL++ += (l + r) * 0.5f;
  30499. }
  30500. sourceSamplePosition += pitchRatio;
  30501. if (sourceSamplePosition > playingSound->length)
  30502. {
  30503. stopNote (false);
  30504. break;
  30505. }
  30506. }
  30507. }
  30508. }
  30509. END_JUCE_NAMESPACE
  30510. /*** End of inlined file: juce_Sampler.cpp ***/
  30511. /*** Start of inlined file: juce_Synthesiser.cpp ***/
  30512. BEGIN_JUCE_NAMESPACE
  30513. SynthesiserSound::SynthesiserSound()
  30514. {
  30515. }
  30516. SynthesiserSound::~SynthesiserSound()
  30517. {
  30518. }
  30519. SynthesiserVoice::SynthesiserVoice()
  30520. : currentSampleRate (44100.0),
  30521. currentlyPlayingNote (-1),
  30522. noteOnTime (0),
  30523. currentlyPlayingSound (0)
  30524. {
  30525. }
  30526. SynthesiserVoice::~SynthesiserVoice()
  30527. {
  30528. }
  30529. bool SynthesiserVoice::isPlayingChannel (const int midiChannel) const
  30530. {
  30531. return currentlyPlayingSound != 0
  30532. && currentlyPlayingSound->appliesToChannel (midiChannel);
  30533. }
  30534. void SynthesiserVoice::setCurrentPlaybackSampleRate (const double newRate)
  30535. {
  30536. currentSampleRate = newRate;
  30537. }
  30538. void SynthesiserVoice::clearCurrentNote()
  30539. {
  30540. currentlyPlayingNote = -1;
  30541. currentlyPlayingSound = 0;
  30542. }
  30543. Synthesiser::Synthesiser()
  30544. : sampleRate (0),
  30545. lastNoteOnCounter (0),
  30546. shouldStealNotes (true)
  30547. {
  30548. for (int i = 0; i < numElementsInArray (lastPitchWheelValues); ++i)
  30549. lastPitchWheelValues[i] = 0x2000;
  30550. }
  30551. Synthesiser::~Synthesiser()
  30552. {
  30553. }
  30554. SynthesiserVoice* Synthesiser::getVoice (const int index) const
  30555. {
  30556. const ScopedLock sl (lock);
  30557. return voices [index];
  30558. }
  30559. void Synthesiser::clearVoices()
  30560. {
  30561. const ScopedLock sl (lock);
  30562. voices.clear();
  30563. }
  30564. void Synthesiser::addVoice (SynthesiserVoice* const newVoice)
  30565. {
  30566. const ScopedLock sl (lock);
  30567. voices.add (newVoice);
  30568. }
  30569. void Synthesiser::removeVoice (const int index)
  30570. {
  30571. const ScopedLock sl (lock);
  30572. voices.remove (index);
  30573. }
  30574. void Synthesiser::clearSounds()
  30575. {
  30576. const ScopedLock sl (lock);
  30577. sounds.clear();
  30578. }
  30579. void Synthesiser::addSound (const SynthesiserSound::Ptr& newSound)
  30580. {
  30581. const ScopedLock sl (lock);
  30582. sounds.add (newSound);
  30583. }
  30584. void Synthesiser::removeSound (const int index)
  30585. {
  30586. const ScopedLock sl (lock);
  30587. sounds.remove (index);
  30588. }
  30589. void Synthesiser::setNoteStealingEnabled (const bool shouldStealNotes_)
  30590. {
  30591. shouldStealNotes = shouldStealNotes_;
  30592. }
  30593. void Synthesiser::setCurrentPlaybackSampleRate (const double newRate)
  30594. {
  30595. if (sampleRate != newRate)
  30596. {
  30597. const ScopedLock sl (lock);
  30598. allNotesOff (0, false);
  30599. sampleRate = newRate;
  30600. for (int i = voices.size(); --i >= 0;)
  30601. voices.getUnchecked (i)->setCurrentPlaybackSampleRate (newRate);
  30602. }
  30603. }
  30604. void Synthesiser::renderNextBlock (AudioSampleBuffer& outputBuffer,
  30605. const MidiBuffer& midiData,
  30606. int startSample,
  30607. int numSamples)
  30608. {
  30609. // must set the sample rate before using this!
  30610. jassert (sampleRate != 0);
  30611. const ScopedLock sl (lock);
  30612. MidiBuffer::Iterator midiIterator (midiData);
  30613. midiIterator.setNextSamplePosition (startSample);
  30614. MidiMessage m (0xf4, 0.0);
  30615. while (numSamples > 0)
  30616. {
  30617. int midiEventPos;
  30618. const bool useEvent = midiIterator.getNextEvent (m, midiEventPos)
  30619. && midiEventPos < startSample + numSamples;
  30620. const int numThisTime = useEvent ? midiEventPos - startSample
  30621. : numSamples;
  30622. if (numThisTime > 0)
  30623. {
  30624. for (int i = voices.size(); --i >= 0;)
  30625. voices.getUnchecked (i)->renderNextBlock (outputBuffer, startSample, numThisTime);
  30626. }
  30627. if (useEvent)
  30628. {
  30629. if (m.isNoteOn())
  30630. {
  30631. const int channel = m.getChannel();
  30632. noteOn (channel,
  30633. m.getNoteNumber(),
  30634. m.getFloatVelocity());
  30635. }
  30636. else if (m.isNoteOff())
  30637. {
  30638. noteOff (m.getChannel(),
  30639. m.getNoteNumber(),
  30640. true);
  30641. }
  30642. else if (m.isAllNotesOff() || m.isAllSoundOff())
  30643. {
  30644. allNotesOff (m.getChannel(), true);
  30645. }
  30646. else if (m.isPitchWheel())
  30647. {
  30648. const int channel = m.getChannel();
  30649. const int wheelPos = m.getPitchWheelValue();
  30650. lastPitchWheelValues [channel - 1] = wheelPos;
  30651. handlePitchWheel (channel, wheelPos);
  30652. }
  30653. else if (m.isController())
  30654. {
  30655. handleController (m.getChannel(),
  30656. m.getControllerNumber(),
  30657. m.getControllerValue());
  30658. }
  30659. }
  30660. startSample += numThisTime;
  30661. numSamples -= numThisTime;
  30662. }
  30663. }
  30664. void Synthesiser::noteOn (const int midiChannel,
  30665. const int midiNoteNumber,
  30666. const float velocity)
  30667. {
  30668. const ScopedLock sl (lock);
  30669. for (int i = sounds.size(); --i >= 0;)
  30670. {
  30671. SynthesiserSound* const sound = sounds.getUnchecked(i);
  30672. if (sound->appliesToNote (midiNoteNumber)
  30673. && sound->appliesToChannel (midiChannel))
  30674. {
  30675. startVoice (findFreeVoice (sound, shouldStealNotes),
  30676. sound, midiChannel, midiNoteNumber, velocity);
  30677. }
  30678. }
  30679. }
  30680. void Synthesiser::startVoice (SynthesiserVoice* const voice,
  30681. SynthesiserSound* const sound,
  30682. const int midiChannel,
  30683. const int midiNoteNumber,
  30684. const float velocity)
  30685. {
  30686. if (voice != 0 && sound != 0)
  30687. {
  30688. if (voice->currentlyPlayingSound != 0)
  30689. voice->stopNote (false);
  30690. voice->startNote (midiNoteNumber,
  30691. velocity,
  30692. sound,
  30693. lastPitchWheelValues [midiChannel - 1]);
  30694. voice->currentlyPlayingNote = midiNoteNumber;
  30695. voice->noteOnTime = ++lastNoteOnCounter;
  30696. voice->currentlyPlayingSound = sound;
  30697. }
  30698. }
  30699. void Synthesiser::noteOff (const int midiChannel,
  30700. const int midiNoteNumber,
  30701. const bool allowTailOff)
  30702. {
  30703. const ScopedLock sl (lock);
  30704. for (int i = voices.size(); --i >= 0;)
  30705. {
  30706. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30707. if (voice->getCurrentlyPlayingNote() == midiNoteNumber)
  30708. {
  30709. SynthesiserSound* const sound = voice->getCurrentlyPlayingSound();
  30710. if (sound != 0
  30711. && sound->appliesToNote (midiNoteNumber)
  30712. && sound->appliesToChannel (midiChannel))
  30713. {
  30714. voice->stopNote (allowTailOff);
  30715. // the subclass MUST call clearCurrentNote() if it's not tailing off! RTFM for stopNote()!
  30716. jassert (allowTailOff || (voice->getCurrentlyPlayingNote() < 0 && voice->getCurrentlyPlayingSound() == 0));
  30717. }
  30718. }
  30719. }
  30720. }
  30721. void Synthesiser::allNotesOff (const int midiChannel,
  30722. const bool allowTailOff)
  30723. {
  30724. const ScopedLock sl (lock);
  30725. for (int i = voices.size(); --i >= 0;)
  30726. {
  30727. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30728. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  30729. voice->stopNote (allowTailOff);
  30730. }
  30731. }
  30732. void Synthesiser::handlePitchWheel (const int midiChannel,
  30733. const int wheelValue)
  30734. {
  30735. const ScopedLock sl (lock);
  30736. for (int i = voices.size(); --i >= 0;)
  30737. {
  30738. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30739. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  30740. {
  30741. voice->pitchWheelMoved (wheelValue);
  30742. }
  30743. }
  30744. }
  30745. void Synthesiser::handleController (const int midiChannel,
  30746. const int controllerNumber,
  30747. const int controllerValue)
  30748. {
  30749. const ScopedLock sl (lock);
  30750. for (int i = voices.size(); --i >= 0;)
  30751. {
  30752. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30753. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  30754. voice->controllerMoved (controllerNumber, controllerValue);
  30755. }
  30756. }
  30757. SynthesiserVoice* Synthesiser::findFreeVoice (SynthesiserSound* soundToPlay,
  30758. const bool stealIfNoneAvailable) const
  30759. {
  30760. const ScopedLock sl (lock);
  30761. for (int i = voices.size(); --i >= 0;)
  30762. if (voices.getUnchecked (i)->getCurrentlyPlayingNote() < 0
  30763. && voices.getUnchecked (i)->canPlaySound (soundToPlay))
  30764. return voices.getUnchecked (i);
  30765. if (stealIfNoneAvailable)
  30766. {
  30767. // currently this just steals the one that's been playing the longest, but could be made a bit smarter..
  30768. SynthesiserVoice* oldest = 0;
  30769. for (int i = voices.size(); --i >= 0;)
  30770. {
  30771. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30772. if (voice->canPlaySound (soundToPlay)
  30773. && (oldest == 0 || oldest->noteOnTime > voice->noteOnTime))
  30774. oldest = voice;
  30775. }
  30776. jassert (oldest != 0);
  30777. return oldest;
  30778. }
  30779. return 0;
  30780. }
  30781. END_JUCE_NAMESPACE
  30782. /*** End of inlined file: juce_Synthesiser.cpp ***/
  30783. /*** Start of inlined file: juce_ActionBroadcaster.cpp ***/
  30784. BEGIN_JUCE_NAMESPACE
  30785. ActionBroadcaster::ActionBroadcaster() throw()
  30786. {
  30787. // are you trying to create this object before or after juce has been intialised??
  30788. jassert (MessageManager::instance != 0);
  30789. }
  30790. ActionBroadcaster::~ActionBroadcaster()
  30791. {
  30792. // all event-based objects must be deleted BEFORE juce is shut down!
  30793. jassert (MessageManager::instance != 0);
  30794. }
  30795. void ActionBroadcaster::addActionListener (ActionListener* const listener)
  30796. {
  30797. actionListenerList.addActionListener (listener);
  30798. }
  30799. void ActionBroadcaster::removeActionListener (ActionListener* const listener)
  30800. {
  30801. jassert (actionListenerList.isValidMessageListener());
  30802. if (actionListenerList.isValidMessageListener())
  30803. actionListenerList.removeActionListener (listener);
  30804. }
  30805. void ActionBroadcaster::removeAllActionListeners()
  30806. {
  30807. actionListenerList.removeAllActionListeners();
  30808. }
  30809. void ActionBroadcaster::sendActionMessage (const String& message) const
  30810. {
  30811. actionListenerList.sendActionMessage (message);
  30812. }
  30813. END_JUCE_NAMESPACE
  30814. /*** End of inlined file: juce_ActionBroadcaster.cpp ***/
  30815. /*** Start of inlined file: juce_ActionListenerList.cpp ***/
  30816. BEGIN_JUCE_NAMESPACE
  30817. // special message of our own with a string in it
  30818. class ActionMessage : public Message
  30819. {
  30820. public:
  30821. const String message;
  30822. ActionMessage (const String& messageText, void* const listener_) throw()
  30823. : message (messageText)
  30824. {
  30825. pointerParameter = listener_;
  30826. }
  30827. ~ActionMessage() throw()
  30828. {
  30829. }
  30830. private:
  30831. ActionMessage (const ActionMessage&);
  30832. ActionMessage& operator= (const ActionMessage&);
  30833. };
  30834. ActionListenerList::ActionListenerList()
  30835. {
  30836. }
  30837. ActionListenerList::~ActionListenerList()
  30838. {
  30839. }
  30840. void ActionListenerList::addActionListener (ActionListener* const listener)
  30841. {
  30842. const ScopedLock sl (actionListenerLock_);
  30843. jassert (listener != 0);
  30844. jassert (! actionListeners_.contains (listener)); // trying to add a listener to the list twice!
  30845. if (listener != 0)
  30846. actionListeners_.add (listener);
  30847. }
  30848. void ActionListenerList::removeActionListener (ActionListener* const listener)
  30849. {
  30850. const ScopedLock sl (actionListenerLock_);
  30851. jassert (actionListeners_.contains (listener)); // trying to remove a listener that isn't on the list!
  30852. actionListeners_.removeValue (listener);
  30853. }
  30854. void ActionListenerList::removeAllActionListeners()
  30855. {
  30856. const ScopedLock sl (actionListenerLock_);
  30857. actionListeners_.clear();
  30858. }
  30859. void ActionListenerList::sendActionMessage (const String& message) const
  30860. {
  30861. const ScopedLock sl (actionListenerLock_);
  30862. for (int i = actionListeners_.size(); --i >= 0;)
  30863. postMessage (new ActionMessage (message, static_cast <ActionListener*> (actionListeners_.getUnchecked(i))));
  30864. }
  30865. void ActionListenerList::handleMessage (const Message& message)
  30866. {
  30867. const ActionMessage& am = (const ActionMessage&) message;
  30868. if (actionListeners_.contains (am.pointerParameter))
  30869. static_cast <ActionListener*> (am.pointerParameter)->actionListenerCallback (am.message);
  30870. }
  30871. END_JUCE_NAMESPACE
  30872. /*** End of inlined file: juce_ActionListenerList.cpp ***/
  30873. /*** Start of inlined file: juce_AsyncUpdater.cpp ***/
  30874. BEGIN_JUCE_NAMESPACE
  30875. AsyncUpdater::AsyncUpdater() throw()
  30876. : asyncMessagePending (false)
  30877. {
  30878. internalAsyncHandler.owner = this;
  30879. }
  30880. AsyncUpdater::~AsyncUpdater()
  30881. {
  30882. }
  30883. void AsyncUpdater::triggerAsyncUpdate()
  30884. {
  30885. if (! asyncMessagePending)
  30886. {
  30887. asyncMessagePending = true;
  30888. internalAsyncHandler.postMessage (new Message());
  30889. }
  30890. }
  30891. void AsyncUpdater::cancelPendingUpdate() throw()
  30892. {
  30893. asyncMessagePending = false;
  30894. }
  30895. void AsyncUpdater::handleUpdateNowIfNeeded()
  30896. {
  30897. if (asyncMessagePending)
  30898. {
  30899. asyncMessagePending = false;
  30900. handleAsyncUpdate();
  30901. }
  30902. }
  30903. void AsyncUpdater::AsyncUpdaterInternal::handleMessage (const Message&)
  30904. {
  30905. owner->handleUpdateNowIfNeeded();
  30906. }
  30907. END_JUCE_NAMESPACE
  30908. /*** End of inlined file: juce_AsyncUpdater.cpp ***/
  30909. /*** Start of inlined file: juce_ChangeBroadcaster.cpp ***/
  30910. BEGIN_JUCE_NAMESPACE
  30911. ChangeBroadcaster::ChangeBroadcaster() throw()
  30912. {
  30913. // are you trying to create this object before or after juce has been intialised??
  30914. jassert (MessageManager::instance != 0);
  30915. }
  30916. ChangeBroadcaster::~ChangeBroadcaster()
  30917. {
  30918. // all event-based objects must be deleted BEFORE juce is shut down!
  30919. jassert (MessageManager::instance != 0);
  30920. }
  30921. void ChangeBroadcaster::addChangeListener (ChangeListener* const listener)
  30922. {
  30923. changeListenerList.addChangeListener (listener);
  30924. }
  30925. void ChangeBroadcaster::removeChangeListener (ChangeListener* const listener)
  30926. {
  30927. jassert (changeListenerList.isValidMessageListener());
  30928. if (changeListenerList.isValidMessageListener())
  30929. changeListenerList.removeChangeListener (listener);
  30930. }
  30931. void ChangeBroadcaster::removeAllChangeListeners()
  30932. {
  30933. changeListenerList.removeAllChangeListeners();
  30934. }
  30935. void ChangeBroadcaster::sendChangeMessage (void* objectThatHasChanged)
  30936. {
  30937. changeListenerList.sendChangeMessage (objectThatHasChanged);
  30938. }
  30939. void ChangeBroadcaster::sendSynchronousChangeMessage (void* objectThatHasChanged)
  30940. {
  30941. changeListenerList.sendSynchronousChangeMessage (objectThatHasChanged);
  30942. }
  30943. void ChangeBroadcaster::dispatchPendingMessages()
  30944. {
  30945. changeListenerList.dispatchPendingMessages();
  30946. }
  30947. END_JUCE_NAMESPACE
  30948. /*** End of inlined file: juce_ChangeBroadcaster.cpp ***/
  30949. /*** Start of inlined file: juce_ChangeListenerList.cpp ***/
  30950. BEGIN_JUCE_NAMESPACE
  30951. ChangeListenerList::ChangeListenerList()
  30952. : lastChangedObject (0),
  30953. messagePending (false)
  30954. {
  30955. }
  30956. ChangeListenerList::~ChangeListenerList()
  30957. {
  30958. }
  30959. void ChangeListenerList::addChangeListener (ChangeListener* const listener)
  30960. {
  30961. const ScopedLock sl (lock);
  30962. jassert (listener != 0);
  30963. if (listener != 0)
  30964. listeners.add (listener);
  30965. }
  30966. void ChangeListenerList::removeChangeListener (ChangeListener* const listener)
  30967. {
  30968. const ScopedLock sl (lock);
  30969. listeners.removeValue (listener);
  30970. }
  30971. void ChangeListenerList::removeAllChangeListeners()
  30972. {
  30973. const ScopedLock sl (lock);
  30974. listeners.clear();
  30975. }
  30976. void ChangeListenerList::sendChangeMessage (void* const objectThatHasChanged)
  30977. {
  30978. const ScopedLock sl (lock);
  30979. if ((! messagePending) && (listeners.size() > 0))
  30980. {
  30981. lastChangedObject = objectThatHasChanged;
  30982. postMessage (new Message (0, 0, 0, objectThatHasChanged));
  30983. messagePending = true;
  30984. }
  30985. }
  30986. void ChangeListenerList::handleMessage (const Message& message)
  30987. {
  30988. sendSynchronousChangeMessage (message.pointerParameter);
  30989. }
  30990. void ChangeListenerList::sendSynchronousChangeMessage (void* const objectThatHasChanged)
  30991. {
  30992. const ScopedLock sl (lock);
  30993. messagePending = false;
  30994. for (int i = listeners.size(); --i >= 0;)
  30995. {
  30996. ChangeListener* const l = static_cast <ChangeListener*> (listeners.getUnchecked (i));
  30997. {
  30998. const ScopedUnlock tempUnlocker (lock);
  30999. l->changeListenerCallback (objectThatHasChanged);
  31000. }
  31001. i = jmin (i, listeners.size());
  31002. }
  31003. }
  31004. void ChangeListenerList::dispatchPendingMessages()
  31005. {
  31006. if (messagePending)
  31007. sendSynchronousChangeMessage (lastChangedObject);
  31008. }
  31009. END_JUCE_NAMESPACE
  31010. /*** End of inlined file: juce_ChangeListenerList.cpp ***/
  31011. /*** Start of inlined file: juce_InterprocessConnection.cpp ***/
  31012. BEGIN_JUCE_NAMESPACE
  31013. InterprocessConnection::InterprocessConnection (const bool callbacksOnMessageThread,
  31014. const uint32 magicMessageHeaderNumber)
  31015. : Thread ("Juce IPC connection"),
  31016. callbackConnectionState (false),
  31017. useMessageThread (callbacksOnMessageThread),
  31018. magicMessageHeader (magicMessageHeaderNumber),
  31019. pipeReceiveMessageTimeout (-1)
  31020. {
  31021. }
  31022. InterprocessConnection::~InterprocessConnection()
  31023. {
  31024. callbackConnectionState = false;
  31025. disconnect();
  31026. }
  31027. bool InterprocessConnection::connectToSocket (const String& hostName,
  31028. const int portNumber,
  31029. const int timeOutMillisecs)
  31030. {
  31031. disconnect();
  31032. const ScopedLock sl (pipeAndSocketLock);
  31033. socket = new StreamingSocket();
  31034. if (socket->connect (hostName, portNumber, timeOutMillisecs))
  31035. {
  31036. connectionMadeInt();
  31037. startThread();
  31038. return true;
  31039. }
  31040. else
  31041. {
  31042. socket = 0;
  31043. return false;
  31044. }
  31045. }
  31046. bool InterprocessConnection::connectToPipe (const String& pipeName,
  31047. const int pipeReceiveMessageTimeoutMs)
  31048. {
  31049. disconnect();
  31050. ScopedPointer <NamedPipe> newPipe (new NamedPipe());
  31051. if (newPipe->openExisting (pipeName))
  31052. {
  31053. const ScopedLock sl (pipeAndSocketLock);
  31054. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  31055. initialiseWithPipe (newPipe.release());
  31056. return true;
  31057. }
  31058. return false;
  31059. }
  31060. bool InterprocessConnection::createPipe (const String& pipeName,
  31061. const int pipeReceiveMessageTimeoutMs)
  31062. {
  31063. disconnect();
  31064. ScopedPointer <NamedPipe> newPipe (new NamedPipe());
  31065. if (newPipe->createNewPipe (pipeName))
  31066. {
  31067. const ScopedLock sl (pipeAndSocketLock);
  31068. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  31069. initialiseWithPipe (newPipe.release());
  31070. return true;
  31071. }
  31072. return false;
  31073. }
  31074. void InterprocessConnection::disconnect()
  31075. {
  31076. if (socket != 0)
  31077. socket->close();
  31078. if (pipe != 0)
  31079. {
  31080. pipe->cancelPendingReads();
  31081. pipe->close();
  31082. }
  31083. stopThread (4000);
  31084. {
  31085. const ScopedLock sl (pipeAndSocketLock);
  31086. socket = 0;
  31087. pipe = 0;
  31088. }
  31089. connectionLostInt();
  31090. }
  31091. bool InterprocessConnection::isConnected() const
  31092. {
  31093. const ScopedLock sl (pipeAndSocketLock);
  31094. return ((socket != 0 && socket->isConnected())
  31095. || (pipe != 0 && pipe->isOpen()))
  31096. && isThreadRunning();
  31097. }
  31098. const String InterprocessConnection::getConnectedHostName() const
  31099. {
  31100. if (pipe != 0)
  31101. {
  31102. return "localhost";
  31103. }
  31104. else if (socket != 0)
  31105. {
  31106. if (! socket->isLocal())
  31107. return socket->getHostName();
  31108. return "localhost";
  31109. }
  31110. return String::empty;
  31111. }
  31112. bool InterprocessConnection::sendMessage (const MemoryBlock& message)
  31113. {
  31114. uint32 messageHeader[2];
  31115. messageHeader [0] = ByteOrder::swapIfBigEndian (magicMessageHeader);
  31116. messageHeader [1] = ByteOrder::swapIfBigEndian ((uint32) message.getSize());
  31117. MemoryBlock messageData (sizeof (messageHeader) + message.getSize());
  31118. messageData.copyFrom (messageHeader, 0, sizeof (messageHeader));
  31119. messageData.copyFrom (message.getData(), sizeof (messageHeader), message.getSize());
  31120. size_t bytesWritten = 0;
  31121. const ScopedLock sl (pipeAndSocketLock);
  31122. if (socket != 0)
  31123. {
  31124. bytesWritten = socket->write (messageData.getData(), (int) messageData.getSize());
  31125. }
  31126. else if (pipe != 0)
  31127. {
  31128. bytesWritten = pipe->write (messageData.getData(), (int) messageData.getSize());
  31129. }
  31130. if (bytesWritten < 0)
  31131. {
  31132. // error..
  31133. return false;
  31134. }
  31135. return (bytesWritten == messageData.getSize());
  31136. }
  31137. void InterprocessConnection::initialiseWithSocket (StreamingSocket* const socket_)
  31138. {
  31139. jassert (socket == 0);
  31140. socket = socket_;
  31141. connectionMadeInt();
  31142. startThread();
  31143. }
  31144. void InterprocessConnection::initialiseWithPipe (NamedPipe* const pipe_)
  31145. {
  31146. jassert (pipe == 0);
  31147. pipe = pipe_;
  31148. connectionMadeInt();
  31149. startThread();
  31150. }
  31151. const int messageMagicNumber = 0xb734128b;
  31152. void InterprocessConnection::handleMessage (const Message& message)
  31153. {
  31154. if (message.intParameter1 == messageMagicNumber)
  31155. {
  31156. switch (message.intParameter2)
  31157. {
  31158. case 0:
  31159. {
  31160. ScopedPointer <MemoryBlock> data (static_cast <MemoryBlock*> (message.pointerParameter));
  31161. messageReceived (*data);
  31162. break;
  31163. }
  31164. case 1:
  31165. connectionMade();
  31166. break;
  31167. case 2:
  31168. connectionLost();
  31169. break;
  31170. }
  31171. }
  31172. }
  31173. void InterprocessConnection::connectionMadeInt()
  31174. {
  31175. if (! callbackConnectionState)
  31176. {
  31177. callbackConnectionState = true;
  31178. if (useMessageThread)
  31179. postMessage (new Message (messageMagicNumber, 1, 0, 0));
  31180. else
  31181. connectionMade();
  31182. }
  31183. }
  31184. void InterprocessConnection::connectionLostInt()
  31185. {
  31186. if (callbackConnectionState)
  31187. {
  31188. callbackConnectionState = false;
  31189. if (useMessageThread)
  31190. postMessage (new Message (messageMagicNumber, 2, 0, 0));
  31191. else
  31192. connectionLost();
  31193. }
  31194. }
  31195. void InterprocessConnection::deliverDataInt (const MemoryBlock& data)
  31196. {
  31197. jassert (callbackConnectionState);
  31198. if (useMessageThread)
  31199. postMessage (new Message (messageMagicNumber, 0, 0, new MemoryBlock (data)));
  31200. else
  31201. messageReceived (data);
  31202. }
  31203. bool InterprocessConnection::readNextMessageInt()
  31204. {
  31205. const int maximumMessageSize = 1024 * 1024 * 10; // sanity check
  31206. uint32 messageHeader[2];
  31207. const int bytes = (socket != 0) ? socket->read (messageHeader, sizeof (messageHeader), true)
  31208. : pipe->read (messageHeader, sizeof (messageHeader), pipeReceiveMessageTimeout);
  31209. if (bytes == sizeof (messageHeader)
  31210. && ByteOrder::swapIfBigEndian (messageHeader[0]) == magicMessageHeader)
  31211. {
  31212. int bytesInMessage = (int) ByteOrder::swapIfBigEndian (messageHeader[1]);
  31213. if (bytesInMessage > 0 && bytesInMessage < maximumMessageSize)
  31214. {
  31215. MemoryBlock messageData (bytesInMessage, true);
  31216. int bytesRead = 0;
  31217. while (bytesInMessage > 0)
  31218. {
  31219. if (threadShouldExit())
  31220. return false;
  31221. const int numThisTime = jmin (bytesInMessage, 65536);
  31222. const int bytesIn = (socket != 0) ? socket->read (static_cast <char*> (messageData.getData()) + bytesRead, numThisTime, true)
  31223. : pipe->read (static_cast <char*> (messageData.getData()) + bytesRead, numThisTime, pipeReceiveMessageTimeout);
  31224. if (bytesIn <= 0)
  31225. break;
  31226. bytesRead += bytesIn;
  31227. bytesInMessage -= bytesIn;
  31228. }
  31229. if (bytesRead >= 0)
  31230. deliverDataInt (messageData);
  31231. }
  31232. }
  31233. else if (bytes < 0)
  31234. {
  31235. {
  31236. const ScopedLock sl (pipeAndSocketLock);
  31237. socket = 0;
  31238. }
  31239. connectionLostInt();
  31240. return false;
  31241. }
  31242. return true;
  31243. }
  31244. void InterprocessConnection::run()
  31245. {
  31246. while (! threadShouldExit())
  31247. {
  31248. if (socket != 0)
  31249. {
  31250. const int ready = socket->waitUntilReady (true, 0);
  31251. if (ready < 0)
  31252. {
  31253. {
  31254. const ScopedLock sl (pipeAndSocketLock);
  31255. socket = 0;
  31256. }
  31257. connectionLostInt();
  31258. break;
  31259. }
  31260. else if (ready > 0)
  31261. {
  31262. if (! readNextMessageInt())
  31263. break;
  31264. }
  31265. else
  31266. {
  31267. Thread::sleep (2);
  31268. }
  31269. }
  31270. else if (pipe != 0)
  31271. {
  31272. if (! pipe->isOpen())
  31273. {
  31274. {
  31275. const ScopedLock sl (pipeAndSocketLock);
  31276. pipe = 0;
  31277. }
  31278. connectionLostInt();
  31279. break;
  31280. }
  31281. else
  31282. {
  31283. if (! readNextMessageInt())
  31284. break;
  31285. }
  31286. }
  31287. else
  31288. {
  31289. break;
  31290. }
  31291. }
  31292. }
  31293. END_JUCE_NAMESPACE
  31294. /*** End of inlined file: juce_InterprocessConnection.cpp ***/
  31295. /*** Start of inlined file: juce_InterprocessConnectionServer.cpp ***/
  31296. BEGIN_JUCE_NAMESPACE
  31297. InterprocessConnectionServer::InterprocessConnectionServer()
  31298. : Thread ("Juce IPC server")
  31299. {
  31300. }
  31301. InterprocessConnectionServer::~InterprocessConnectionServer()
  31302. {
  31303. stop();
  31304. }
  31305. bool InterprocessConnectionServer::beginWaitingForSocket (const int portNumber)
  31306. {
  31307. stop();
  31308. socket = new StreamingSocket();
  31309. if (socket->createListener (portNumber))
  31310. {
  31311. startThread();
  31312. return true;
  31313. }
  31314. socket = 0;
  31315. return false;
  31316. }
  31317. void InterprocessConnectionServer::stop()
  31318. {
  31319. signalThreadShouldExit();
  31320. if (socket != 0)
  31321. socket->close();
  31322. stopThread (4000);
  31323. socket = 0;
  31324. }
  31325. void InterprocessConnectionServer::run()
  31326. {
  31327. while ((! threadShouldExit()) && socket != 0)
  31328. {
  31329. ScopedPointer <StreamingSocket> clientSocket (socket->waitForNextConnection());
  31330. if (clientSocket != 0)
  31331. {
  31332. InterprocessConnection* newConnection = createConnectionObject();
  31333. if (newConnection != 0)
  31334. newConnection->initialiseWithSocket (clientSocket.release());
  31335. }
  31336. }
  31337. }
  31338. END_JUCE_NAMESPACE
  31339. /*** End of inlined file: juce_InterprocessConnectionServer.cpp ***/
  31340. /*** Start of inlined file: juce_Message.cpp ***/
  31341. BEGIN_JUCE_NAMESPACE
  31342. Message::Message() throw()
  31343. : intParameter1 (0),
  31344. intParameter2 (0),
  31345. intParameter3 (0),
  31346. pointerParameter (0)
  31347. {
  31348. }
  31349. Message::Message (const int intParameter1_,
  31350. const int intParameter2_,
  31351. const int intParameter3_,
  31352. void* const pointerParameter_) throw()
  31353. : intParameter1 (intParameter1_),
  31354. intParameter2 (intParameter2_),
  31355. intParameter3 (intParameter3_),
  31356. pointerParameter (pointerParameter_)
  31357. {
  31358. }
  31359. Message::~Message() throw()
  31360. {
  31361. }
  31362. END_JUCE_NAMESPACE
  31363. /*** End of inlined file: juce_Message.cpp ***/
  31364. /*** Start of inlined file: juce_MessageListener.cpp ***/
  31365. BEGIN_JUCE_NAMESPACE
  31366. MessageListener::MessageListener() throw()
  31367. {
  31368. // are you trying to create a messagelistener before or after juce has been intialised??
  31369. jassert (MessageManager::instance != 0);
  31370. if (MessageManager::instance != 0)
  31371. MessageManager::instance->messageListeners.add (this);
  31372. }
  31373. MessageListener::~MessageListener()
  31374. {
  31375. if (MessageManager::instance != 0)
  31376. MessageManager::instance->messageListeners.removeValue (this);
  31377. }
  31378. void MessageListener::postMessage (Message* const message) const throw()
  31379. {
  31380. message->messageRecipient = const_cast <MessageListener*> (this);
  31381. if (MessageManager::instance == 0)
  31382. MessageManager::getInstance();
  31383. MessageManager::instance->postMessageToQueue (message);
  31384. }
  31385. bool MessageListener::isValidMessageListener() const throw()
  31386. {
  31387. return (MessageManager::instance != 0)
  31388. && MessageManager::instance->messageListeners.contains (this);
  31389. }
  31390. END_JUCE_NAMESPACE
  31391. /*** End of inlined file: juce_MessageListener.cpp ***/
  31392. /*** Start of inlined file: juce_MessageManager.cpp ***/
  31393. BEGIN_JUCE_NAMESPACE
  31394. // platform-specific functions..
  31395. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages);
  31396. bool juce_postMessageToSystemQueue (Message* message);
  31397. MessageManager* MessageManager::instance = 0;
  31398. static const int quitMessageId = 0xfffff321;
  31399. MessageManager::MessageManager() throw()
  31400. : quitMessagePosted (false),
  31401. quitMessageReceived (false),
  31402. threadWithLock (0)
  31403. {
  31404. messageThreadId = Thread::getCurrentThreadId();
  31405. }
  31406. MessageManager::~MessageManager() throw()
  31407. {
  31408. broadcastListeners = 0;
  31409. doPlatformSpecificShutdown();
  31410. // If you hit this assertion, then you've probably leaked a Component or some other
  31411. // kind of MessageListener object...
  31412. jassert (messageListeners.size() == 0);
  31413. jassert (instance == this);
  31414. instance = 0; // do this last in case this instance is still needed by doPlatformSpecificShutdown()
  31415. }
  31416. MessageManager* MessageManager::getInstance() throw()
  31417. {
  31418. if (instance == 0)
  31419. {
  31420. instance = new MessageManager();
  31421. doPlatformSpecificInitialisation();
  31422. }
  31423. return instance;
  31424. }
  31425. void MessageManager::postMessageToQueue (Message* const message)
  31426. {
  31427. if (quitMessagePosted || ! juce_postMessageToSystemQueue (message))
  31428. delete message;
  31429. }
  31430. CallbackMessage::CallbackMessage() throw() {}
  31431. CallbackMessage::~CallbackMessage() throw() {}
  31432. void CallbackMessage::post()
  31433. {
  31434. if (MessageManager::instance != 0)
  31435. MessageManager::instance->postCallbackMessage (this);
  31436. }
  31437. void MessageManager::postCallbackMessage (Message* const message)
  31438. {
  31439. message->messageRecipient = 0;
  31440. postMessageToQueue (message);
  31441. }
  31442. // not for public use..
  31443. void MessageManager::deliverMessage (Message* const message)
  31444. {
  31445. const ScopedPointer <Message> messageDeleter (message);
  31446. MessageListener* const recipient = message->messageRecipient;
  31447. JUCE_TRY
  31448. {
  31449. if (messageListeners.contains (recipient))
  31450. {
  31451. recipient->handleMessage (*message);
  31452. }
  31453. else if (recipient == 0)
  31454. {
  31455. if (message->intParameter1 == quitMessageId)
  31456. {
  31457. quitMessageReceived = true;
  31458. }
  31459. else
  31460. {
  31461. CallbackMessage* const cm = dynamic_cast <CallbackMessage*> (message);
  31462. if (cm != 0)
  31463. cm->messageCallback();
  31464. }
  31465. }
  31466. }
  31467. JUCE_CATCH_EXCEPTION
  31468. }
  31469. #if ! (JUCE_MAC || JUCE_IOS)
  31470. void MessageManager::runDispatchLoop()
  31471. {
  31472. jassert (isThisTheMessageThread()); // must only be called by the message thread
  31473. runDispatchLoopUntil (-1);
  31474. }
  31475. void MessageManager::stopDispatchLoop()
  31476. {
  31477. Message* const m = new Message (quitMessageId, 0, 0, 0);
  31478. m->messageRecipient = 0;
  31479. postMessageToQueue (m);
  31480. quitMessagePosted = true;
  31481. }
  31482. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  31483. {
  31484. jassert (isThisTheMessageThread()); // must only be called by the message thread
  31485. const int64 endTime = Time::currentTimeMillis() + millisecondsToRunFor;
  31486. while ((millisecondsToRunFor < 0 || endTime > Time::currentTimeMillis())
  31487. && ! quitMessageReceived)
  31488. {
  31489. JUCE_TRY
  31490. {
  31491. if (! juce_dispatchNextMessageOnSystemQueue (millisecondsToRunFor >= 0))
  31492. {
  31493. const int msToWait = (int) (endTime - Time::currentTimeMillis());
  31494. if (msToWait > 0)
  31495. Thread::sleep (jmin (5, msToWait));
  31496. }
  31497. }
  31498. JUCE_CATCH_EXCEPTION
  31499. }
  31500. return ! quitMessageReceived;
  31501. }
  31502. #endif
  31503. void MessageManager::deliverBroadcastMessage (const String& value)
  31504. {
  31505. if (broadcastListeners != 0)
  31506. broadcastListeners->sendActionMessage (value);
  31507. }
  31508. void MessageManager::registerBroadcastListener (ActionListener* const listener)
  31509. {
  31510. if (broadcastListeners == 0)
  31511. broadcastListeners = new ActionListenerList();
  31512. broadcastListeners->addActionListener (listener);
  31513. }
  31514. void MessageManager::deregisterBroadcastListener (ActionListener* const listener)
  31515. {
  31516. if (broadcastListeners != 0)
  31517. broadcastListeners->removeActionListener (listener);
  31518. }
  31519. bool MessageManager::isThisTheMessageThread() const throw()
  31520. {
  31521. return Thread::getCurrentThreadId() == messageThreadId;
  31522. }
  31523. void MessageManager::setCurrentThreadAsMessageThread()
  31524. {
  31525. if (messageThreadId != Thread::getCurrentThreadId())
  31526. {
  31527. messageThreadId = Thread::getCurrentThreadId();
  31528. // This is needed on windows to make sure the message window is created by this thread
  31529. doPlatformSpecificShutdown();
  31530. doPlatformSpecificInitialisation();
  31531. }
  31532. }
  31533. bool MessageManager::currentThreadHasLockedMessageManager() const throw()
  31534. {
  31535. const Thread::ThreadID thisThread = Thread::getCurrentThreadId();
  31536. return thisThread == messageThreadId || thisThread == threadWithLock;
  31537. }
  31538. /* The only safe way to lock the message thread while another thread does
  31539. some work is by posting a special message, whose purpose is to tie up the event
  31540. loop until the other thread has finished its business.
  31541. Any other approach can get horribly deadlocked if the OS uses its own hidden locks which
  31542. get locked before making an event callback, because if the same OS lock gets indirectly
  31543. accessed from another thread inside a MM lock, you're screwed. (this is exactly what happens
  31544. in Cocoa).
  31545. */
  31546. class MessageManagerLock::SharedEvents : public ReferenceCountedObject
  31547. {
  31548. public:
  31549. SharedEvents() {}
  31550. ~SharedEvents() {}
  31551. /* This class just holds a couple of events to communicate between the BlockingMessage
  31552. and the MessageManagerLock. Because both of these objects may be deleted at any time,
  31553. this shared data must be kept in a separate, ref-counted container. */
  31554. WaitableEvent lockedEvent, releaseEvent;
  31555. private:
  31556. SharedEvents (const SharedEvents&);
  31557. SharedEvents& operator= (const SharedEvents&);
  31558. };
  31559. class MessageManagerLock::BlockingMessage : public CallbackMessage
  31560. {
  31561. public:
  31562. BlockingMessage (MessageManagerLock::SharedEvents* const events_) : events (events_) {}
  31563. ~BlockingMessage() throw() {}
  31564. void messageCallback()
  31565. {
  31566. events->lockedEvent.signal();
  31567. events->releaseEvent.wait();
  31568. }
  31569. juce_UseDebuggingNewOperator
  31570. private:
  31571. ReferenceCountedObjectPtr <MessageManagerLock::SharedEvents> events;
  31572. BlockingMessage (const BlockingMessage&);
  31573. BlockingMessage& operator= (const BlockingMessage&);
  31574. };
  31575. MessageManagerLock::MessageManagerLock (Thread* const threadToCheck)
  31576. : sharedEvents (0),
  31577. locked (false)
  31578. {
  31579. init (threadToCheck, 0);
  31580. }
  31581. MessageManagerLock::MessageManagerLock (ThreadPoolJob* const jobToCheckForExitSignal)
  31582. : sharedEvents (0),
  31583. locked (false)
  31584. {
  31585. init (0, jobToCheckForExitSignal);
  31586. }
  31587. void MessageManagerLock::init (Thread* const threadToCheck, ThreadPoolJob* const job)
  31588. {
  31589. if (MessageManager::instance != 0)
  31590. {
  31591. if (MessageManager::instance->currentThreadHasLockedMessageManager())
  31592. {
  31593. locked = true; // either we're on the message thread, or this is a re-entrant call.
  31594. }
  31595. else
  31596. {
  31597. if (threadToCheck == 0 && job == 0)
  31598. {
  31599. MessageManager::instance->lockingLock.enter();
  31600. }
  31601. else
  31602. {
  31603. while (! MessageManager::instance->lockingLock.tryEnter())
  31604. {
  31605. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  31606. || (job != 0 && job->shouldExit()))
  31607. return;
  31608. Thread::sleep (1);
  31609. }
  31610. }
  31611. sharedEvents = new SharedEvents();
  31612. sharedEvents->incReferenceCount();
  31613. (new BlockingMessage (sharedEvents))->post();
  31614. while (! sharedEvents->lockedEvent.wait (50))
  31615. {
  31616. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  31617. || (job != 0 && job->shouldExit()))
  31618. {
  31619. sharedEvents->releaseEvent.signal();
  31620. sharedEvents->decReferenceCount();
  31621. sharedEvents = 0;
  31622. MessageManager::instance->lockingLock.exit();
  31623. return;
  31624. }
  31625. }
  31626. jassert (MessageManager::instance->threadWithLock == 0);
  31627. MessageManager::instance->threadWithLock = Thread::getCurrentThreadId();
  31628. locked = true;
  31629. }
  31630. }
  31631. }
  31632. MessageManagerLock::~MessageManagerLock() throw()
  31633. {
  31634. if (sharedEvents != 0)
  31635. {
  31636. jassert (MessageManager::instance == 0 || MessageManager::instance->currentThreadHasLockedMessageManager());
  31637. sharedEvents->releaseEvent.signal();
  31638. sharedEvents->decReferenceCount();
  31639. if (MessageManager::instance != 0)
  31640. {
  31641. MessageManager::instance->threadWithLock = 0;
  31642. MessageManager::instance->lockingLock.exit();
  31643. }
  31644. }
  31645. }
  31646. END_JUCE_NAMESPACE
  31647. /*** End of inlined file: juce_MessageManager.cpp ***/
  31648. /*** Start of inlined file: juce_MultiTimer.cpp ***/
  31649. BEGIN_JUCE_NAMESPACE
  31650. class MultiTimer::MultiTimerCallback : public Timer
  31651. {
  31652. public:
  31653. MultiTimerCallback (const int timerId_, MultiTimer& owner_)
  31654. : timerId (timerId_),
  31655. owner (owner_)
  31656. {
  31657. }
  31658. ~MultiTimerCallback()
  31659. {
  31660. }
  31661. void timerCallback()
  31662. {
  31663. owner.timerCallback (timerId);
  31664. }
  31665. const int timerId;
  31666. private:
  31667. MultiTimer& owner;
  31668. };
  31669. MultiTimer::MultiTimer() throw()
  31670. {
  31671. }
  31672. MultiTimer::MultiTimer (const MultiTimer&) throw()
  31673. {
  31674. }
  31675. MultiTimer::~MultiTimer()
  31676. {
  31677. const ScopedLock sl (timerListLock);
  31678. timers.clear();
  31679. }
  31680. void MultiTimer::startTimer (const int timerId, const int intervalInMilliseconds) throw()
  31681. {
  31682. const ScopedLock sl (timerListLock);
  31683. for (int i = timers.size(); --i >= 0;)
  31684. {
  31685. MultiTimerCallback* const t = timers.getUnchecked(i);
  31686. if (t->timerId == timerId)
  31687. {
  31688. t->startTimer (intervalInMilliseconds);
  31689. return;
  31690. }
  31691. }
  31692. MultiTimerCallback* const newTimer = new MultiTimerCallback (timerId, *this);
  31693. timers.add (newTimer);
  31694. newTimer->startTimer (intervalInMilliseconds);
  31695. }
  31696. void MultiTimer::stopTimer (const int timerId) throw()
  31697. {
  31698. const ScopedLock sl (timerListLock);
  31699. for (int i = timers.size(); --i >= 0;)
  31700. {
  31701. MultiTimerCallback* const t = timers.getUnchecked(i);
  31702. if (t->timerId == timerId)
  31703. t->stopTimer();
  31704. }
  31705. }
  31706. bool MultiTimer::isTimerRunning (const int timerId) const throw()
  31707. {
  31708. const ScopedLock sl (timerListLock);
  31709. for (int i = timers.size(); --i >= 0;)
  31710. {
  31711. const MultiTimerCallback* const t = timers.getUnchecked(i);
  31712. if (t->timerId == timerId)
  31713. return t->isTimerRunning();
  31714. }
  31715. return false;
  31716. }
  31717. int MultiTimer::getTimerInterval (const int timerId) const throw()
  31718. {
  31719. const ScopedLock sl (timerListLock);
  31720. for (int i = timers.size(); --i >= 0;)
  31721. {
  31722. const MultiTimerCallback* const t = timers.getUnchecked(i);
  31723. if (t->timerId == timerId)
  31724. return t->getTimerInterval();
  31725. }
  31726. return 0;
  31727. }
  31728. END_JUCE_NAMESPACE
  31729. /*** End of inlined file: juce_MultiTimer.cpp ***/
  31730. /*** Start of inlined file: juce_Timer.cpp ***/
  31731. BEGIN_JUCE_NAMESPACE
  31732. class InternalTimerThread : private Thread,
  31733. private MessageListener,
  31734. private DeletedAtShutdown,
  31735. private AsyncUpdater
  31736. {
  31737. public:
  31738. InternalTimerThread()
  31739. : Thread ("Juce Timer"),
  31740. firstTimer (0),
  31741. callbackNeeded (0)
  31742. {
  31743. triggerAsyncUpdate();
  31744. }
  31745. ~InternalTimerThread() throw()
  31746. {
  31747. stopThread (4000);
  31748. jassert (instance == this || instance == 0);
  31749. if (instance == this)
  31750. instance = 0;
  31751. }
  31752. void run()
  31753. {
  31754. uint32 lastTime = Time::getMillisecondCounter();
  31755. while (! threadShouldExit())
  31756. {
  31757. const uint32 now = Time::getMillisecondCounter();
  31758. if (now <= lastTime)
  31759. {
  31760. wait (2);
  31761. continue;
  31762. }
  31763. const int elapsed = now - lastTime;
  31764. lastTime = now;
  31765. int timeUntilFirstTimer = 1000;
  31766. {
  31767. const ScopedLock sl (lock);
  31768. decrementAllCounters (elapsed);
  31769. if (firstTimer != 0)
  31770. timeUntilFirstTimer = firstTimer->countdownMs;
  31771. }
  31772. if (timeUntilFirstTimer <= 0)
  31773. {
  31774. /* If we managed to set the atomic boolean to true then send a message, this is needed
  31775. as a memory barrier so the message won't be sent before callbackNeeded is set to true,
  31776. but if it fails it means the message-thread changed the value from under us so at least
  31777. some processing is happenening and we can just loop around and try again
  31778. */
  31779. if (callbackNeeded.compareAndSetBool (1, 0))
  31780. {
  31781. postMessage (new Message());
  31782. /* Sometimes our message can get discarded by the OS (e.g. when running as an RTAS
  31783. when the app has a modal loop), so this is how long to wait before assuming the
  31784. message has been lost and trying again.
  31785. */
  31786. const uint32 messageDeliveryTimeout = now + 2000;
  31787. while (callbackNeeded.get() != 0)
  31788. {
  31789. wait (4);
  31790. if (threadShouldExit())
  31791. return;
  31792. if (Time::getMillisecondCounter() > messageDeliveryTimeout)
  31793. break;
  31794. }
  31795. }
  31796. }
  31797. else
  31798. {
  31799. // don't wait for too long because running this loop also helps keep the
  31800. // Time::getApproximateMillisecondTimer value stay up-to-date
  31801. wait (jlimit (1, 50, timeUntilFirstTimer));
  31802. }
  31803. }
  31804. }
  31805. void callTimers()
  31806. {
  31807. const ScopedLock sl (lock);
  31808. while (firstTimer != 0 && firstTimer->countdownMs <= 0)
  31809. {
  31810. Timer* const t = firstTimer;
  31811. t->countdownMs = t->periodMs;
  31812. removeTimer (t);
  31813. addTimer (t);
  31814. const ScopedUnlock ul (lock);
  31815. JUCE_TRY
  31816. {
  31817. t->timerCallback();
  31818. }
  31819. JUCE_CATCH_EXCEPTION
  31820. }
  31821. /* This is needed as a memory barrier to make sure all processing of current timers is done
  31822. before the boolean is set. This set should never fail since if it was false in the first place,
  31823. we wouldn't get a message (so it can't be changed from false to true from under us), and if we
  31824. get a message then the value is true and the other thread can only set it to true again and
  31825. we will get another callback to set it to false.
  31826. */
  31827. callbackNeeded.set (0);
  31828. }
  31829. void handleMessage (const Message&)
  31830. {
  31831. callTimers();
  31832. }
  31833. void callTimersSynchronously()
  31834. {
  31835. if (! isThreadRunning())
  31836. {
  31837. // (This is relied on by some plugins in cases where the MM has
  31838. // had to restart and the async callback never started)
  31839. cancelPendingUpdate();
  31840. triggerAsyncUpdate();
  31841. }
  31842. callTimers();
  31843. }
  31844. static void callAnyTimersSynchronously()
  31845. {
  31846. if (InternalTimerThread::instance != 0)
  31847. InternalTimerThread::instance->callTimersSynchronously();
  31848. }
  31849. static inline void add (Timer* const tim) throw()
  31850. {
  31851. if (instance == 0)
  31852. instance = new InternalTimerThread();
  31853. const ScopedLock sl (instance->lock);
  31854. instance->addTimer (tim);
  31855. }
  31856. static inline void remove (Timer* const tim) throw()
  31857. {
  31858. if (instance != 0)
  31859. {
  31860. const ScopedLock sl (instance->lock);
  31861. instance->removeTimer (tim);
  31862. }
  31863. }
  31864. static inline void resetCounter (Timer* const tim,
  31865. const int newCounter) throw()
  31866. {
  31867. if (instance != 0)
  31868. {
  31869. tim->countdownMs = newCounter;
  31870. tim->periodMs = newCounter;
  31871. if ((tim->next != 0 && tim->next->countdownMs < tim->countdownMs)
  31872. || (tim->previous != 0 && tim->previous->countdownMs > tim->countdownMs))
  31873. {
  31874. const ScopedLock sl (instance->lock);
  31875. instance->removeTimer (tim);
  31876. instance->addTimer (tim);
  31877. }
  31878. }
  31879. }
  31880. private:
  31881. friend class Timer;
  31882. static InternalTimerThread* instance;
  31883. static CriticalSection lock;
  31884. Timer* volatile firstTimer;
  31885. Atomic <int> callbackNeeded;
  31886. void addTimer (Timer* const t) throw()
  31887. {
  31888. #if JUCE_DEBUG
  31889. Timer* tt = firstTimer;
  31890. while (tt != 0)
  31891. {
  31892. // trying to add a timer that's already here - shouldn't get to this point,
  31893. // so if you get this assertion, let me know!
  31894. jassert (tt != t);
  31895. tt = tt->next;
  31896. }
  31897. jassert (t->previous == 0 && t->next == 0);
  31898. #endif
  31899. Timer* i = firstTimer;
  31900. if (i == 0 || i->countdownMs > t->countdownMs)
  31901. {
  31902. t->next = firstTimer;
  31903. firstTimer = t;
  31904. }
  31905. else
  31906. {
  31907. while (i->next != 0 && i->next->countdownMs <= t->countdownMs)
  31908. i = i->next;
  31909. jassert (i != 0);
  31910. t->next = i->next;
  31911. t->previous = i;
  31912. i->next = t;
  31913. }
  31914. if (t->next != 0)
  31915. t->next->previous = t;
  31916. jassert ((t->next == 0 || t->next->countdownMs >= t->countdownMs)
  31917. && (t->previous == 0 || t->previous->countdownMs <= t->countdownMs));
  31918. notify();
  31919. }
  31920. void removeTimer (Timer* const t) throw()
  31921. {
  31922. #if JUCE_DEBUG
  31923. Timer* tt = firstTimer;
  31924. bool found = false;
  31925. while (tt != 0)
  31926. {
  31927. if (tt == t)
  31928. {
  31929. found = true;
  31930. break;
  31931. }
  31932. tt = tt->next;
  31933. }
  31934. // trying to remove a timer that's not here - shouldn't get to this point,
  31935. // so if you get this assertion, let me know!
  31936. jassert (found);
  31937. #endif
  31938. if (t->previous != 0)
  31939. {
  31940. jassert (firstTimer != t);
  31941. t->previous->next = t->next;
  31942. }
  31943. else
  31944. {
  31945. jassert (firstTimer == t);
  31946. firstTimer = t->next;
  31947. }
  31948. if (t->next != 0)
  31949. t->next->previous = t->previous;
  31950. t->next = 0;
  31951. t->previous = 0;
  31952. }
  31953. void decrementAllCounters (const int numMillisecs) const
  31954. {
  31955. Timer* t = firstTimer;
  31956. while (t != 0)
  31957. {
  31958. t->countdownMs -= numMillisecs;
  31959. t = t->next;
  31960. }
  31961. }
  31962. void handleAsyncUpdate()
  31963. {
  31964. startThread (7);
  31965. }
  31966. InternalTimerThread (const InternalTimerThread&);
  31967. InternalTimerThread& operator= (const InternalTimerThread&);
  31968. };
  31969. InternalTimerThread* InternalTimerThread::instance = 0;
  31970. CriticalSection InternalTimerThread::lock;
  31971. void juce_callAnyTimersSynchronously()
  31972. {
  31973. InternalTimerThread::callAnyTimersSynchronously();
  31974. }
  31975. #if JUCE_DEBUG
  31976. static SortedSet <Timer*> activeTimers;
  31977. #endif
  31978. Timer::Timer() throw()
  31979. : countdownMs (0),
  31980. periodMs (0),
  31981. previous (0),
  31982. next (0)
  31983. {
  31984. #if JUCE_DEBUG
  31985. activeTimers.add (this);
  31986. #endif
  31987. }
  31988. Timer::Timer (const Timer&) throw()
  31989. : countdownMs (0),
  31990. periodMs (0),
  31991. previous (0),
  31992. next (0)
  31993. {
  31994. #if JUCE_DEBUG
  31995. activeTimers.add (this);
  31996. #endif
  31997. }
  31998. Timer::~Timer()
  31999. {
  32000. stopTimer();
  32001. #if JUCE_DEBUG
  32002. activeTimers.removeValue (this);
  32003. #endif
  32004. }
  32005. void Timer::startTimer (const int interval) throw()
  32006. {
  32007. const ScopedLock sl (InternalTimerThread::lock);
  32008. #if JUCE_DEBUG
  32009. // this isn't a valid object! Your timer might be a dangling pointer or something..
  32010. jassert (activeTimers.contains (this));
  32011. #endif
  32012. if (periodMs == 0)
  32013. {
  32014. countdownMs = interval;
  32015. periodMs = jmax (1, interval);
  32016. InternalTimerThread::add (this);
  32017. }
  32018. else
  32019. {
  32020. InternalTimerThread::resetCounter (this, interval);
  32021. }
  32022. }
  32023. void Timer::stopTimer() throw()
  32024. {
  32025. const ScopedLock sl (InternalTimerThread::lock);
  32026. #if JUCE_DEBUG
  32027. // this isn't a valid object! Your timer might be a dangling pointer or something..
  32028. jassert (activeTimers.contains (this));
  32029. #endif
  32030. if (periodMs > 0)
  32031. {
  32032. InternalTimerThread::remove (this);
  32033. periodMs = 0;
  32034. }
  32035. }
  32036. END_JUCE_NAMESPACE
  32037. /*** End of inlined file: juce_Timer.cpp ***/
  32038. #endif
  32039. #if JUCE_BUILD_GUI
  32040. /*** Start of inlined file: juce_Component.cpp ***/
  32041. BEGIN_JUCE_NAMESPACE
  32042. #define checkMessageManagerIsLocked jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  32043. enum ComponentMessageNumbers
  32044. {
  32045. customCommandMessage = 0x7fff0001,
  32046. exitModalStateMessage = 0x7fff0002
  32047. };
  32048. Component* Component::currentlyFocusedComponent = 0;
  32049. class Component::MouseListenerList
  32050. {
  32051. public:
  32052. MouseListenerList()
  32053. : numDeepMouseListeners (0)
  32054. {
  32055. }
  32056. ~MouseListenerList()
  32057. {
  32058. }
  32059. void addListener (MouseListener* const newListener, const bool wantsEventsForAllNestedChildComponents)
  32060. {
  32061. if (! listeners.contains (newListener))
  32062. {
  32063. if (wantsEventsForAllNestedChildComponents)
  32064. {
  32065. listeners.insert (0, newListener);
  32066. ++numDeepMouseListeners;
  32067. }
  32068. else
  32069. {
  32070. listeners.add (newListener);
  32071. }
  32072. }
  32073. }
  32074. void removeListener (MouseListener* const listenerToRemove)
  32075. {
  32076. const int index = listeners.indexOf (listenerToRemove);
  32077. if (index >= 0)
  32078. {
  32079. if (index < numDeepMouseListeners)
  32080. --numDeepMouseListeners;
  32081. listeners.remove (index);
  32082. }
  32083. }
  32084. static void sendMouseEvent (Component* comp, BailOutChecker& checker,
  32085. void (MouseListener::*eventMethod) (const MouseEvent&), const MouseEvent& e)
  32086. {
  32087. if (checker.shouldBailOut())
  32088. return;
  32089. {
  32090. MouseListenerList* const list = comp->mouseListeners_;
  32091. if (list != 0)
  32092. {
  32093. for (int i = list->listeners.size(); --i >= 0;)
  32094. {
  32095. (list->listeners.getUnchecked(i)->*eventMethod) (e);
  32096. if (checker.shouldBailOut())
  32097. return;
  32098. i = jmin (i, list->listeners.size());
  32099. }
  32100. }
  32101. }
  32102. Component* p = comp->parentComponent_;
  32103. while (p != 0)
  32104. {
  32105. MouseListenerList* const list = p->mouseListeners_;
  32106. if (list != 0 && list->numDeepMouseListeners > 0)
  32107. {
  32108. BailOutChecker checker2 (comp, p);
  32109. for (int i = list->numDeepMouseListeners; --i >= 0;)
  32110. {
  32111. (list->listeners.getUnchecked(i)->*eventMethod) (e);
  32112. if (checker2.shouldBailOut())
  32113. return;
  32114. i = jmin (i, list->numDeepMouseListeners);
  32115. }
  32116. }
  32117. p = p->parentComponent_;
  32118. }
  32119. }
  32120. static void sendWheelEvent (Component* comp, BailOutChecker& checker, const MouseEvent& e,
  32121. const float wheelIncrementX, const float wheelIncrementY)
  32122. {
  32123. if (checker.shouldBailOut())
  32124. return;
  32125. {
  32126. MouseListenerList* const list = comp->mouseListeners_;
  32127. if (list != 0)
  32128. {
  32129. for (int i = list->listeners.size(); --i >= 0;)
  32130. {
  32131. list->listeners.getUnchecked(i)->mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  32132. if (checker.shouldBailOut())
  32133. return;
  32134. i = jmin (i, list->listeners.size());
  32135. }
  32136. }
  32137. }
  32138. Component* p = comp->parentComponent_;
  32139. while (p != 0)
  32140. {
  32141. MouseListenerList* const list = p->mouseListeners_;
  32142. if (list != 0 && list->numDeepMouseListeners > 0)
  32143. {
  32144. BailOutChecker checker2 (comp, p);
  32145. for (int i = list->numDeepMouseListeners; --i >= 0;)
  32146. {
  32147. list->listeners.getUnchecked(i)->mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  32148. if (checker2.shouldBailOut())
  32149. return;
  32150. i = jmin (i, list->numDeepMouseListeners);
  32151. }
  32152. }
  32153. p = p->parentComponent_;
  32154. }
  32155. }
  32156. private:
  32157. Array <MouseListener*> listeners;
  32158. int numDeepMouseListeners;
  32159. MouseListenerList (const MouseListenerList&);
  32160. MouseListenerList& operator= (const MouseListenerList&);
  32161. };
  32162. Component::Component()
  32163. : parentComponent_ (0),
  32164. lookAndFeel_ (0),
  32165. effect_ (0),
  32166. bufferedImage_ (0),
  32167. componentFlags_ (0),
  32168. componentTransparency (0)
  32169. {
  32170. }
  32171. Component::Component (const String& name)
  32172. : componentName_ (name),
  32173. parentComponent_ (0),
  32174. lookAndFeel_ (0),
  32175. effect_ (0),
  32176. bufferedImage_ (0),
  32177. componentFlags_ (0),
  32178. componentTransparency (0)
  32179. {
  32180. }
  32181. Component::~Component()
  32182. {
  32183. static_jassert (sizeof (flags) <= sizeof (componentFlags_));
  32184. componentListeners.call (&ComponentListener::componentBeingDeleted, *this);
  32185. if (parentComponent_ != 0)
  32186. {
  32187. parentComponent_->removeChildComponent (this);
  32188. }
  32189. else if ((currentlyFocusedComponent == this)
  32190. || isParentOf (currentlyFocusedComponent))
  32191. {
  32192. giveAwayFocus();
  32193. }
  32194. if (flags.hasHeavyweightPeerFlag)
  32195. removeFromDesktop();
  32196. for (int i = childComponentList_.size(); --i >= 0;)
  32197. childComponentList_.getUnchecked(i)->parentComponent_ = 0;
  32198. }
  32199. void Component::setName (const String& name)
  32200. {
  32201. // if component methods are being called from threads other than the message
  32202. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32203. checkMessageManagerIsLocked
  32204. if (componentName_ != name)
  32205. {
  32206. componentName_ = name;
  32207. if (flags.hasHeavyweightPeerFlag)
  32208. {
  32209. ComponentPeer* const peer = getPeer();
  32210. jassert (peer != 0);
  32211. if (peer != 0)
  32212. peer->setTitle (name);
  32213. }
  32214. BailOutChecker checker (this);
  32215. componentListeners.callChecked (checker, &ComponentListener::componentNameChanged, *this);
  32216. }
  32217. }
  32218. void Component::setVisible (bool shouldBeVisible)
  32219. {
  32220. if (flags.visibleFlag != shouldBeVisible)
  32221. {
  32222. // if component methods are being called from threads other than the message
  32223. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32224. checkMessageManagerIsLocked
  32225. SafePointer<Component> safePointer (this);
  32226. flags.visibleFlag = shouldBeVisible;
  32227. internalRepaint (0, 0, getWidth(), getHeight());
  32228. sendFakeMouseMove();
  32229. if (! shouldBeVisible)
  32230. {
  32231. if (currentlyFocusedComponent == this
  32232. || isParentOf (currentlyFocusedComponent))
  32233. {
  32234. if (parentComponent_ != 0)
  32235. parentComponent_->grabKeyboardFocus();
  32236. else
  32237. giveAwayFocus();
  32238. }
  32239. }
  32240. if (safePointer != 0)
  32241. {
  32242. sendVisibilityChangeMessage();
  32243. if (safePointer != 0 && flags.hasHeavyweightPeerFlag)
  32244. {
  32245. ComponentPeer* const peer = getPeer();
  32246. jassert (peer != 0);
  32247. if (peer != 0)
  32248. {
  32249. peer->setVisible (shouldBeVisible);
  32250. internalHierarchyChanged();
  32251. }
  32252. }
  32253. }
  32254. }
  32255. }
  32256. void Component::visibilityChanged()
  32257. {
  32258. }
  32259. void Component::sendVisibilityChangeMessage()
  32260. {
  32261. BailOutChecker checker (this);
  32262. visibilityChanged();
  32263. if (! checker.shouldBailOut())
  32264. componentListeners.callChecked (checker, &ComponentListener::componentVisibilityChanged, *this);
  32265. }
  32266. bool Component::isShowing() const
  32267. {
  32268. if (flags.visibleFlag)
  32269. {
  32270. if (parentComponent_ != 0)
  32271. {
  32272. return parentComponent_->isShowing();
  32273. }
  32274. else
  32275. {
  32276. const ComponentPeer* const peer = getPeer();
  32277. return peer != 0 && ! peer->isMinimised();
  32278. }
  32279. }
  32280. return false;
  32281. }
  32282. bool Component::isValidComponent() const
  32283. {
  32284. return (this != 0) && isValidMessageListener();
  32285. }
  32286. void* Component::getWindowHandle() const
  32287. {
  32288. const ComponentPeer* const peer = getPeer();
  32289. if (peer != 0)
  32290. return peer->getNativeHandle();
  32291. return 0;
  32292. }
  32293. void Component::addToDesktop (int styleWanted, void* nativeWindowToAttachTo)
  32294. {
  32295. // if component methods are being called from threads other than the message
  32296. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32297. checkMessageManagerIsLocked
  32298. if (isOpaque())
  32299. styleWanted &= ~ComponentPeer::windowIsSemiTransparent;
  32300. else
  32301. styleWanted |= ComponentPeer::windowIsSemiTransparent;
  32302. int currentStyleFlags = 0;
  32303. // don't use getPeer(), so that we only get the peer that's specifically
  32304. // for this comp, and not for one of its parents.
  32305. ComponentPeer* peer = ComponentPeer::getPeerFor (this);
  32306. if (peer != 0)
  32307. currentStyleFlags = peer->getStyleFlags();
  32308. if (styleWanted != currentStyleFlags || ! flags.hasHeavyweightPeerFlag)
  32309. {
  32310. SafePointer<Component> safePointer (this);
  32311. #if JUCE_LINUX
  32312. // it's wise to give the component a non-zero size before
  32313. // putting it on the desktop, as X windows get confused by this, and
  32314. // a (1, 1) minimum size is enforced here.
  32315. setSize (jmax (1, getWidth()),
  32316. jmax (1, getHeight()));
  32317. #endif
  32318. const Point<int> topLeft (relativePositionToGlobal (Point<int> (0, 0)));
  32319. bool wasFullscreen = false;
  32320. bool wasMinimised = false;
  32321. ComponentBoundsConstrainer* currentConstainer = 0;
  32322. Rectangle<int> oldNonFullScreenBounds;
  32323. if (peer != 0)
  32324. {
  32325. wasFullscreen = peer->isFullScreen();
  32326. wasMinimised = peer->isMinimised();
  32327. currentConstainer = peer->getConstrainer();
  32328. oldNonFullScreenBounds = peer->getNonFullScreenBounds();
  32329. removeFromDesktop();
  32330. setTopLeftPosition (topLeft.getX(), topLeft.getY());
  32331. }
  32332. if (parentComponent_ != 0)
  32333. parentComponent_->removeChildComponent (this);
  32334. if (safePointer != 0)
  32335. {
  32336. flags.hasHeavyweightPeerFlag = true;
  32337. peer = createNewPeer (styleWanted, nativeWindowToAttachTo);
  32338. Desktop::getInstance().addDesktopComponent (this);
  32339. bounds_.setPosition (topLeft);
  32340. peer->setBounds (topLeft.getX(), topLeft.getY(), getWidth(), getHeight(), false);
  32341. peer->setVisible (isVisible());
  32342. if (wasFullscreen)
  32343. {
  32344. peer->setFullScreen (true);
  32345. peer->setNonFullScreenBounds (oldNonFullScreenBounds);
  32346. }
  32347. if (wasMinimised)
  32348. peer->setMinimised (true);
  32349. if (isAlwaysOnTop())
  32350. peer->setAlwaysOnTop (true);
  32351. peer->setConstrainer (currentConstainer);
  32352. repaint();
  32353. }
  32354. internalHierarchyChanged();
  32355. }
  32356. }
  32357. void Component::removeFromDesktop()
  32358. {
  32359. // if component methods are being called from threads other than the message
  32360. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32361. checkMessageManagerIsLocked
  32362. if (flags.hasHeavyweightPeerFlag)
  32363. {
  32364. ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  32365. flags.hasHeavyweightPeerFlag = false;
  32366. jassert (peer != 0);
  32367. delete peer;
  32368. Desktop::getInstance().removeDesktopComponent (this);
  32369. }
  32370. }
  32371. bool Component::isOnDesktop() const throw()
  32372. {
  32373. return flags.hasHeavyweightPeerFlag;
  32374. }
  32375. void Component::userTriedToCloseWindow()
  32376. {
  32377. /* This means that the user's trying to get rid of your window with the 'close window' system
  32378. menu option (on windows) or possibly the task manager - you should really handle this
  32379. and delete or hide your component in an appropriate way.
  32380. If you want to ignore the event and don't want to trigger this assertion, just override
  32381. this method and do nothing.
  32382. */
  32383. jassertfalse;
  32384. }
  32385. void Component::minimisationStateChanged (bool)
  32386. {
  32387. }
  32388. void Component::setOpaque (const bool shouldBeOpaque)
  32389. {
  32390. if (shouldBeOpaque != flags.opaqueFlag)
  32391. {
  32392. flags.opaqueFlag = shouldBeOpaque;
  32393. if (flags.hasHeavyweightPeerFlag)
  32394. {
  32395. const ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  32396. if (peer != 0)
  32397. {
  32398. // to make it recreate the heavyweight window
  32399. addToDesktop (peer->getStyleFlags());
  32400. }
  32401. }
  32402. repaint();
  32403. }
  32404. }
  32405. bool Component::isOpaque() const throw()
  32406. {
  32407. return flags.opaqueFlag;
  32408. }
  32409. void Component::setBufferedToImage (const bool shouldBeBuffered)
  32410. {
  32411. if (shouldBeBuffered != flags.bufferToImageFlag)
  32412. {
  32413. bufferedImage_ = Image::null;
  32414. flags.bufferToImageFlag = shouldBeBuffered;
  32415. }
  32416. }
  32417. void Component::toFront (const bool setAsForeground)
  32418. {
  32419. // if component methods are being called from threads other than the message
  32420. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32421. checkMessageManagerIsLocked
  32422. if (flags.hasHeavyweightPeerFlag)
  32423. {
  32424. ComponentPeer* const peer = getPeer();
  32425. if (peer != 0)
  32426. {
  32427. peer->toFront (setAsForeground);
  32428. if (setAsForeground && ! hasKeyboardFocus (true))
  32429. grabKeyboardFocus();
  32430. }
  32431. }
  32432. else if (parentComponent_ != 0)
  32433. {
  32434. Array<Component*>& childList = parentComponent_->childComponentList_;
  32435. if (childList.getLast() != this)
  32436. {
  32437. const int index = childList.indexOf (this);
  32438. if (index >= 0)
  32439. {
  32440. int insertIndex = -1;
  32441. if (! flags.alwaysOnTopFlag)
  32442. {
  32443. insertIndex = childList.size() - 1;
  32444. while (insertIndex > 0 && childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  32445. --insertIndex;
  32446. }
  32447. if (index != insertIndex)
  32448. {
  32449. childList.move (index, insertIndex);
  32450. sendFakeMouseMove();
  32451. repaintParent();
  32452. }
  32453. }
  32454. }
  32455. if (setAsForeground)
  32456. {
  32457. internalBroughtToFront();
  32458. grabKeyboardFocus();
  32459. }
  32460. }
  32461. }
  32462. void Component::toBehind (Component* const other)
  32463. {
  32464. if (other != 0 && other != this)
  32465. {
  32466. // the two components must belong to the same parent..
  32467. jassert (parentComponent_ == other->parentComponent_);
  32468. if (parentComponent_ != 0)
  32469. {
  32470. Array<Component*>& childList = parentComponent_->childComponentList_;
  32471. const int index = childList.indexOf (this);
  32472. if (index >= 0 && childList [index + 1] != other)
  32473. {
  32474. int otherIndex = childList.indexOf (other);
  32475. if (otherIndex >= 0)
  32476. {
  32477. if (index < otherIndex)
  32478. --otherIndex;
  32479. childList.move (index, otherIndex);
  32480. sendFakeMouseMove();
  32481. repaintParent();
  32482. }
  32483. }
  32484. }
  32485. else if (isOnDesktop())
  32486. {
  32487. jassert (other->isOnDesktop());
  32488. if (other->isOnDesktop())
  32489. {
  32490. ComponentPeer* const us = getPeer();
  32491. ComponentPeer* const them = other->getPeer();
  32492. jassert (us != 0 && them != 0);
  32493. if (us != 0 && them != 0)
  32494. us->toBehind (them);
  32495. }
  32496. }
  32497. }
  32498. }
  32499. void Component::toBack()
  32500. {
  32501. Array<Component*>& childList = parentComponent_->childComponentList_;
  32502. if (isOnDesktop())
  32503. {
  32504. jassertfalse; //xxx need to add this to native window
  32505. }
  32506. else if (parentComponent_ != 0 && childList.getFirst() != this)
  32507. {
  32508. const int index = childList.indexOf (this);
  32509. if (index > 0)
  32510. {
  32511. int insertIndex = 0;
  32512. if (flags.alwaysOnTopFlag)
  32513. {
  32514. while (insertIndex < childList.size()
  32515. && ! childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  32516. {
  32517. ++insertIndex;
  32518. }
  32519. }
  32520. if (index != insertIndex)
  32521. {
  32522. childList.move (index, insertIndex);
  32523. sendFakeMouseMove();
  32524. repaintParent();
  32525. }
  32526. }
  32527. }
  32528. }
  32529. void Component::setAlwaysOnTop (const bool shouldStayOnTop)
  32530. {
  32531. if (shouldStayOnTop != flags.alwaysOnTopFlag)
  32532. {
  32533. flags.alwaysOnTopFlag = shouldStayOnTop;
  32534. if (isOnDesktop())
  32535. {
  32536. ComponentPeer* const peer = getPeer();
  32537. jassert (peer != 0);
  32538. if (peer != 0)
  32539. {
  32540. if (! peer->setAlwaysOnTop (shouldStayOnTop))
  32541. {
  32542. // some kinds of peer can't change their always-on-top status, so
  32543. // for these, we'll need to create a new window
  32544. const int oldFlags = peer->getStyleFlags();
  32545. removeFromDesktop();
  32546. addToDesktop (oldFlags);
  32547. }
  32548. }
  32549. }
  32550. if (shouldStayOnTop)
  32551. toFront (false);
  32552. internalHierarchyChanged();
  32553. }
  32554. }
  32555. bool Component::isAlwaysOnTop() const throw()
  32556. {
  32557. return flags.alwaysOnTopFlag;
  32558. }
  32559. int Component::proportionOfWidth (const float proportion) const throw()
  32560. {
  32561. return roundToInt (proportion * bounds_.getWidth());
  32562. }
  32563. int Component::proportionOfHeight (const float proportion) const throw()
  32564. {
  32565. return roundToInt (proportion * bounds_.getHeight());
  32566. }
  32567. int Component::getParentWidth() const throw()
  32568. {
  32569. return (parentComponent_ != 0) ? parentComponent_->getWidth()
  32570. : getParentMonitorArea().getWidth();
  32571. }
  32572. int Component::getParentHeight() const throw()
  32573. {
  32574. return (parentComponent_ != 0) ? parentComponent_->getHeight()
  32575. : getParentMonitorArea().getHeight();
  32576. }
  32577. int Component::getScreenX() const
  32578. {
  32579. return getScreenPosition().getX();
  32580. }
  32581. int Component::getScreenY() const
  32582. {
  32583. return getScreenPosition().getY();
  32584. }
  32585. const Point<int> Component::getScreenPosition() const
  32586. {
  32587. return (parentComponent_ != 0) ? parentComponent_->getScreenPosition() + getPosition()
  32588. : (flags.hasHeavyweightPeerFlag ? getPeer()->getScreenPosition()
  32589. : getPosition());
  32590. }
  32591. const Rectangle<int> Component::getScreenBounds() const
  32592. {
  32593. return bounds_.withPosition (getScreenPosition());
  32594. }
  32595. const Point<int> Component::relativePositionToGlobal (const Point<int>& relativePosition) const
  32596. {
  32597. const Component* c = this;
  32598. Point<int> p (relativePosition);
  32599. do
  32600. {
  32601. if (c->flags.hasHeavyweightPeerFlag)
  32602. return c->getPeer()->relativePositionToGlobal (p);
  32603. p += c->getPosition();
  32604. c = c->parentComponent_;
  32605. }
  32606. while (c != 0);
  32607. return p;
  32608. }
  32609. const Point<int> Component::globalPositionToRelative (const Point<int>& screenPosition) const
  32610. {
  32611. if (flags.hasHeavyweightPeerFlag)
  32612. {
  32613. return getPeer()->globalPositionToRelative (screenPosition);
  32614. }
  32615. else
  32616. {
  32617. if (parentComponent_ != 0)
  32618. return parentComponent_->globalPositionToRelative (screenPosition) - getPosition();
  32619. return screenPosition - getPosition();
  32620. }
  32621. }
  32622. const Point<int> Component::relativePositionToOtherComponent (const Component* const targetComponent, const Point<int>& positionRelativeToThis) const
  32623. {
  32624. Point<int> p (positionRelativeToThis);
  32625. if (targetComponent != 0)
  32626. {
  32627. const Component* c = this;
  32628. do
  32629. {
  32630. if (c == targetComponent)
  32631. return p;
  32632. if (c->flags.hasHeavyweightPeerFlag)
  32633. {
  32634. p = c->getPeer()->relativePositionToGlobal (p);
  32635. break;
  32636. }
  32637. p += c->getPosition();
  32638. c = c->parentComponent_;
  32639. }
  32640. while (c != 0);
  32641. p = targetComponent->globalPositionToRelative (p);
  32642. }
  32643. return p;
  32644. }
  32645. void Component::setBounds (const int x, const int y, int w, int h)
  32646. {
  32647. // if component methods are being called from threads other than the message
  32648. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32649. checkMessageManagerIsLocked
  32650. if (w < 0) w = 0;
  32651. if (h < 0) h = 0;
  32652. const bool wasResized = (getWidth() != w || getHeight() != h);
  32653. const bool wasMoved = (getX() != x || getY() != y);
  32654. #if JUCE_DEBUG
  32655. // It's a very bad idea to try to resize a window during its paint() method!
  32656. jassert (! (flags.isInsidePaintCall && wasResized && isOnDesktop()));
  32657. #endif
  32658. if (wasMoved || wasResized)
  32659. {
  32660. if (flags.visibleFlag)
  32661. {
  32662. // send a fake mouse move to trigger enter/exit messages if needed..
  32663. sendFakeMouseMove();
  32664. if (! flags.hasHeavyweightPeerFlag)
  32665. repaintParent();
  32666. }
  32667. bounds_.setBounds (x, y, w, h);
  32668. if (wasResized)
  32669. repaint();
  32670. else if (! flags.hasHeavyweightPeerFlag)
  32671. repaintParent();
  32672. if (flags.hasHeavyweightPeerFlag)
  32673. {
  32674. ComponentPeer* const peer = getPeer();
  32675. if (peer != 0)
  32676. {
  32677. if (wasMoved && wasResized)
  32678. peer->setBounds (getX(), getY(), getWidth(), getHeight(), false);
  32679. else if (wasMoved)
  32680. peer->setPosition (getX(), getY());
  32681. else if (wasResized)
  32682. peer->setSize (getWidth(), getHeight());
  32683. }
  32684. }
  32685. sendMovedResizedMessages (wasMoved, wasResized);
  32686. }
  32687. }
  32688. void Component::sendMovedResizedMessages (const bool wasMoved, const bool wasResized)
  32689. {
  32690. JUCE_TRY
  32691. {
  32692. if (wasMoved)
  32693. moved();
  32694. if (wasResized)
  32695. {
  32696. resized();
  32697. for (int i = childComponentList_.size(); --i >= 0;)
  32698. {
  32699. childComponentList_.getUnchecked(i)->parentSizeChanged();
  32700. i = jmin (i, childComponentList_.size());
  32701. }
  32702. }
  32703. BailOutChecker checker (this);
  32704. if (parentComponent_ != 0)
  32705. parentComponent_->childBoundsChanged (this);
  32706. if (! checker.shouldBailOut())
  32707. componentListeners.callChecked (checker, &ComponentListener::componentMovedOrResized,
  32708. *this, wasMoved, wasResized);
  32709. }
  32710. JUCE_CATCH_EXCEPTION
  32711. }
  32712. void Component::setSize (const int w, const int h)
  32713. {
  32714. setBounds (getX(), getY(), w, h);
  32715. }
  32716. void Component::setTopLeftPosition (const int x, const int y)
  32717. {
  32718. setBounds (x, y, getWidth(), getHeight());
  32719. }
  32720. void Component::setTopRightPosition (const int x, const int y)
  32721. {
  32722. setTopLeftPosition (x - getWidth(), y);
  32723. }
  32724. void Component::setBounds (const Rectangle<int>& r)
  32725. {
  32726. setBounds (r.getX(),
  32727. r.getY(),
  32728. r.getWidth(),
  32729. r.getHeight());
  32730. }
  32731. void Component::setBoundsRelative (const float x, const float y,
  32732. const float w, const float h)
  32733. {
  32734. const int pw = getParentWidth();
  32735. const int ph = getParentHeight();
  32736. setBounds (roundToInt (x * pw),
  32737. roundToInt (y * ph),
  32738. roundToInt (w * pw),
  32739. roundToInt (h * ph));
  32740. }
  32741. void Component::setCentrePosition (const int x, const int y)
  32742. {
  32743. setTopLeftPosition (x - getWidth() / 2,
  32744. y - getHeight() / 2);
  32745. }
  32746. void Component::setCentreRelative (const float x, const float y)
  32747. {
  32748. setCentrePosition (roundToInt (getParentWidth() * x),
  32749. roundToInt (getParentHeight() * y));
  32750. }
  32751. void Component::centreWithSize (const int width, const int height)
  32752. {
  32753. const Rectangle<int> parentArea (getParentOrMainMonitorBounds());
  32754. setBounds (parentArea.getCentreX() - width / 2,
  32755. parentArea.getCentreY() - height / 2,
  32756. width, height);
  32757. }
  32758. void Component::setBoundsInset (const BorderSize& borders)
  32759. {
  32760. setBounds (borders.subtractedFrom (getParentOrMainMonitorBounds()));
  32761. }
  32762. void Component::setBoundsToFit (int x, int y, int width, int height,
  32763. const Justification& justification,
  32764. const bool onlyReduceInSize)
  32765. {
  32766. // it's no good calling this method unless both the component and
  32767. // target rectangle have a finite size.
  32768. jassert (getWidth() > 0 && getHeight() > 0 && width > 0 && height > 0);
  32769. if (getWidth() > 0 && getHeight() > 0
  32770. && width > 0 && height > 0)
  32771. {
  32772. int newW, newH;
  32773. if (onlyReduceInSize && getWidth() <= width && getHeight() <= height)
  32774. {
  32775. newW = getWidth();
  32776. newH = getHeight();
  32777. }
  32778. else
  32779. {
  32780. const double imageRatio = getHeight() / (double) getWidth();
  32781. const double targetRatio = height / (double) width;
  32782. if (imageRatio <= targetRatio)
  32783. {
  32784. newW = width;
  32785. newH = jmin (height, roundToInt (newW * imageRatio));
  32786. }
  32787. else
  32788. {
  32789. newH = height;
  32790. newW = jmin (width, roundToInt (newH / imageRatio));
  32791. }
  32792. }
  32793. if (newW > 0 && newH > 0)
  32794. {
  32795. int newX, newY;
  32796. justification.applyToRectangle (newX, newY, newW, newH,
  32797. x, y, width, height);
  32798. setBounds (newX, newY, newW, newH);
  32799. }
  32800. }
  32801. }
  32802. bool Component::hitTest (int x, int y)
  32803. {
  32804. if (! flags.ignoresMouseClicksFlag)
  32805. return true;
  32806. if (flags.allowChildMouseClicksFlag)
  32807. {
  32808. for (int i = getNumChildComponents(); --i >= 0;)
  32809. {
  32810. Component* const c = getChildComponent (i);
  32811. if (c->isVisible()
  32812. && c->bounds_.contains (x, y)
  32813. && c->hitTest (x - c->getX(),
  32814. y - c->getY()))
  32815. {
  32816. return true;
  32817. }
  32818. }
  32819. }
  32820. return false;
  32821. }
  32822. void Component::setInterceptsMouseClicks (const bool allowClicks,
  32823. const bool allowClicksOnChildComponents) throw()
  32824. {
  32825. flags.ignoresMouseClicksFlag = ! allowClicks;
  32826. flags.allowChildMouseClicksFlag = allowClicksOnChildComponents;
  32827. }
  32828. void Component::getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  32829. bool& allowsClicksOnChildComponents) const throw()
  32830. {
  32831. allowsClicksOnThisComponent = ! flags.ignoresMouseClicksFlag;
  32832. allowsClicksOnChildComponents = flags.allowChildMouseClicksFlag;
  32833. }
  32834. bool Component::contains (const int x, const int y)
  32835. {
  32836. if (((unsigned int) x) < (unsigned int) getWidth()
  32837. && ((unsigned int) y) < (unsigned int) getHeight()
  32838. && hitTest (x, y))
  32839. {
  32840. if (parentComponent_ != 0)
  32841. {
  32842. return parentComponent_->contains (x + getX(),
  32843. y + getY());
  32844. }
  32845. else if (flags.hasHeavyweightPeerFlag)
  32846. {
  32847. const ComponentPeer* const peer = getPeer();
  32848. if (peer != 0)
  32849. return peer->contains (Point<int> (x, y), true);
  32850. }
  32851. }
  32852. return false;
  32853. }
  32854. bool Component::reallyContains (int x, int y, const bool returnTrueIfWithinAChild)
  32855. {
  32856. if (! contains (x, y))
  32857. return false;
  32858. Component* p = this;
  32859. while (p->parentComponent_ != 0)
  32860. {
  32861. x += p->getX();
  32862. y += p->getY();
  32863. p = p->parentComponent_;
  32864. }
  32865. const Component* const c = p->getComponentAt (x, y);
  32866. return (c == this) || (returnTrueIfWithinAChild && isParentOf (c));
  32867. }
  32868. Component* Component::getComponentAt (const Point<int>& position)
  32869. {
  32870. return getComponentAt (position.getX(), position.getY());
  32871. }
  32872. Component* Component::getComponentAt (const int x, const int y)
  32873. {
  32874. if (flags.visibleFlag
  32875. && ((unsigned int) x) < (unsigned int) getWidth()
  32876. && ((unsigned int) y) < (unsigned int) getHeight()
  32877. && hitTest (x, y))
  32878. {
  32879. for (int i = childComponentList_.size(); --i >= 0;)
  32880. {
  32881. Component* const child = childComponentList_.getUnchecked(i);
  32882. Component* const c = child->getComponentAt (x - child->getX(),
  32883. y - child->getY());
  32884. if (c != 0)
  32885. return c;
  32886. }
  32887. return this;
  32888. }
  32889. return 0;
  32890. }
  32891. void Component::addChildComponent (Component* const child, int zOrder)
  32892. {
  32893. // if component methods are being called from threads other than the message
  32894. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32895. checkMessageManagerIsLocked
  32896. if (child != 0 && child->parentComponent_ != this)
  32897. {
  32898. if (child->parentComponent_ != 0)
  32899. child->parentComponent_->removeChildComponent (child);
  32900. else
  32901. child->removeFromDesktop();
  32902. child->parentComponent_ = this;
  32903. if (child->isVisible())
  32904. child->repaintParent();
  32905. if (! child->isAlwaysOnTop())
  32906. {
  32907. if (zOrder < 0 || zOrder > childComponentList_.size())
  32908. zOrder = childComponentList_.size();
  32909. while (zOrder > 0)
  32910. {
  32911. if (! childComponentList_.getUnchecked (zOrder - 1)->isAlwaysOnTop())
  32912. break;
  32913. --zOrder;
  32914. }
  32915. }
  32916. childComponentList_.insert (zOrder, child);
  32917. child->internalHierarchyChanged();
  32918. internalChildrenChanged();
  32919. }
  32920. }
  32921. void Component::addAndMakeVisible (Component* const child, int zOrder)
  32922. {
  32923. if (child != 0)
  32924. {
  32925. child->setVisible (true);
  32926. addChildComponent (child, zOrder);
  32927. }
  32928. }
  32929. void Component::removeChildComponent (Component* const child)
  32930. {
  32931. removeChildComponent (childComponentList_.indexOf (child));
  32932. }
  32933. Component* Component::removeChildComponent (const int index)
  32934. {
  32935. // if component methods are being called from threads other than the message
  32936. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32937. checkMessageManagerIsLocked
  32938. Component* const child = childComponentList_ [index];
  32939. if (child != 0)
  32940. {
  32941. sendFakeMouseMove();
  32942. child->repaintParent();
  32943. childComponentList_.remove (index);
  32944. child->parentComponent_ = 0;
  32945. JUCE_TRY
  32946. {
  32947. if ((currentlyFocusedComponent == child)
  32948. || child->isParentOf (currentlyFocusedComponent))
  32949. {
  32950. // get rid first to force the grabKeyboardFocus to change to us.
  32951. giveAwayFocus();
  32952. grabKeyboardFocus();
  32953. }
  32954. }
  32955. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  32956. catch (const std::exception& e)
  32957. {
  32958. currentlyFocusedComponent = 0;
  32959. Desktop::getInstance().triggerFocusCallback();
  32960. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  32961. }
  32962. catch (...)
  32963. {
  32964. currentlyFocusedComponent = 0;
  32965. Desktop::getInstance().triggerFocusCallback();
  32966. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  32967. }
  32968. #endif
  32969. child->internalHierarchyChanged();
  32970. internalChildrenChanged();
  32971. }
  32972. return child;
  32973. }
  32974. void Component::removeAllChildren()
  32975. {
  32976. while (childComponentList_.size() > 0)
  32977. removeChildComponent (childComponentList_.size() - 1);
  32978. }
  32979. void Component::deleteAllChildren()
  32980. {
  32981. while (childComponentList_.size() > 0)
  32982. delete (removeChildComponent (childComponentList_.size() - 1));
  32983. }
  32984. int Component::getNumChildComponents() const throw()
  32985. {
  32986. return childComponentList_.size();
  32987. }
  32988. Component* Component::getChildComponent (const int index) const throw()
  32989. {
  32990. return childComponentList_ [index];
  32991. }
  32992. int Component::getIndexOfChildComponent (const Component* const child) const throw()
  32993. {
  32994. return childComponentList_.indexOf (const_cast <Component*> (child));
  32995. }
  32996. Component* Component::getTopLevelComponent() const throw()
  32997. {
  32998. const Component* comp = this;
  32999. while (comp->parentComponent_ != 0)
  33000. comp = comp->parentComponent_;
  33001. return const_cast <Component*> (comp);
  33002. }
  33003. bool Component::isParentOf (const Component* possibleChild) const throw()
  33004. {
  33005. if (! possibleChild->isValidComponent())
  33006. {
  33007. jassert (possibleChild == 0);
  33008. return false;
  33009. }
  33010. while (possibleChild != 0)
  33011. {
  33012. possibleChild = possibleChild->parentComponent_;
  33013. if (possibleChild == this)
  33014. return true;
  33015. }
  33016. return false;
  33017. }
  33018. void Component::parentHierarchyChanged()
  33019. {
  33020. }
  33021. void Component::childrenChanged()
  33022. {
  33023. }
  33024. void Component::internalChildrenChanged()
  33025. {
  33026. if (componentListeners.isEmpty())
  33027. {
  33028. childrenChanged();
  33029. }
  33030. else
  33031. {
  33032. BailOutChecker checker (this);
  33033. childrenChanged();
  33034. if (! checker.shouldBailOut())
  33035. componentListeners.callChecked (checker, &ComponentListener::componentChildrenChanged, *this);
  33036. }
  33037. }
  33038. void Component::internalHierarchyChanged()
  33039. {
  33040. BailOutChecker checker (this);
  33041. parentHierarchyChanged();
  33042. if (checker.shouldBailOut())
  33043. return;
  33044. componentListeners.callChecked (checker, &ComponentListener::componentParentHierarchyChanged, *this);
  33045. if (checker.shouldBailOut())
  33046. return;
  33047. for (int i = childComponentList_.size(); --i >= 0;)
  33048. {
  33049. childComponentList_.getUnchecked (i)->internalHierarchyChanged();
  33050. if (checker.shouldBailOut())
  33051. {
  33052. // you really shouldn't delete the parent component during a callback telling you
  33053. // that it's changed..
  33054. jassertfalse;
  33055. return;
  33056. }
  33057. i = jmin (i, childComponentList_.size());
  33058. }
  33059. }
  33060. void* Component::runModalLoopCallback (void* userData)
  33061. {
  33062. return (void*) (pointer_sized_int) static_cast <Component*> (userData)->runModalLoop();
  33063. }
  33064. int Component::runModalLoop()
  33065. {
  33066. if (! MessageManager::getInstance()->isThisTheMessageThread())
  33067. {
  33068. // use a callback so this can be called from non-gui threads
  33069. return (int) (pointer_sized_int) MessageManager::getInstance()
  33070. ->callFunctionOnMessageThread (&runModalLoopCallback, this);
  33071. }
  33072. if (! isCurrentlyModal())
  33073. enterModalState (true);
  33074. return ModalComponentManager::getInstance()->runEventLoopForCurrentComponent();
  33075. }
  33076. void Component::enterModalState (const bool takeKeyboardFocus_, ModalComponentManager::Callback* const callback)
  33077. {
  33078. // if component methods are being called from threads other than the message
  33079. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33080. checkMessageManagerIsLocked
  33081. // Check for an attempt to make a component modal when it already is!
  33082. // This can cause nasty problems..
  33083. jassert (! flags.currentlyModalFlag);
  33084. if (! isCurrentlyModal())
  33085. {
  33086. ModalComponentManager::getInstance()->startModal (this, callback);
  33087. flags.currentlyModalFlag = true;
  33088. setVisible (true);
  33089. if (takeKeyboardFocus_)
  33090. grabKeyboardFocus();
  33091. }
  33092. }
  33093. void Component::exitModalState (const int returnValue)
  33094. {
  33095. if (isCurrentlyModal())
  33096. {
  33097. if (MessageManager::getInstance()->isThisTheMessageThread())
  33098. {
  33099. ModalComponentManager::getInstance()->endModal (this, returnValue);
  33100. flags.currentlyModalFlag = false;
  33101. bringModalComponentToFront();
  33102. }
  33103. else
  33104. {
  33105. postMessage (new Message (exitModalStateMessage, returnValue, 0, 0));
  33106. }
  33107. }
  33108. }
  33109. bool Component::isCurrentlyModal() const throw()
  33110. {
  33111. return flags.currentlyModalFlag
  33112. && getCurrentlyModalComponent() == this;
  33113. }
  33114. bool Component::isCurrentlyBlockedByAnotherModalComponent() const
  33115. {
  33116. Component* const mc = getCurrentlyModalComponent();
  33117. return mc != 0
  33118. && mc != this
  33119. && (! mc->isParentOf (this))
  33120. && ! mc->canModalEventBeSentToComponent (this);
  33121. }
  33122. int JUCE_CALLTYPE Component::getNumCurrentlyModalComponents() throw()
  33123. {
  33124. return ModalComponentManager::getInstance()->getNumModalComponents();
  33125. }
  33126. Component* JUCE_CALLTYPE Component::getCurrentlyModalComponent (int index) throw()
  33127. {
  33128. return ModalComponentManager::getInstance()->getModalComponent (index);
  33129. }
  33130. void Component::bringModalComponentToFront()
  33131. {
  33132. ComponentPeer* lastOne = 0;
  33133. for (int i = 0; i < getNumCurrentlyModalComponents(); ++i)
  33134. {
  33135. Component* const c = getCurrentlyModalComponent (i);
  33136. if (c == 0)
  33137. break;
  33138. ComponentPeer* peer = c->getPeer();
  33139. if (peer != 0 && peer != lastOne)
  33140. {
  33141. if (lastOne == 0)
  33142. {
  33143. peer->toFront (true);
  33144. peer->grabFocus();
  33145. }
  33146. else
  33147. peer->toBehind (lastOne);
  33148. lastOne = peer;
  33149. }
  33150. }
  33151. }
  33152. void Component::setBroughtToFrontOnMouseClick (const bool shouldBeBroughtToFront) throw()
  33153. {
  33154. flags.bringToFrontOnClickFlag = shouldBeBroughtToFront;
  33155. }
  33156. bool Component::isBroughtToFrontOnMouseClick() const throw()
  33157. {
  33158. return flags.bringToFrontOnClickFlag;
  33159. }
  33160. void Component::setMouseCursor (const MouseCursor& cursor)
  33161. {
  33162. if (cursor_ != cursor)
  33163. {
  33164. cursor_ = cursor;
  33165. if (flags.visibleFlag)
  33166. updateMouseCursor();
  33167. }
  33168. }
  33169. const MouseCursor Component::getMouseCursor()
  33170. {
  33171. return cursor_;
  33172. }
  33173. void Component::updateMouseCursor() const
  33174. {
  33175. sendFakeMouseMove();
  33176. }
  33177. void Component::setRepaintsOnMouseActivity (const bool shouldRepaint) throw()
  33178. {
  33179. flags.repaintOnMouseActivityFlag = shouldRepaint;
  33180. }
  33181. void Component::setAlpha (const float newAlpha)
  33182. {
  33183. const uint8 newIntAlpha = (uint8) (255 - jlimit (0, 255, roundToInt (newAlpha * 255.0)));
  33184. if (componentTransparency != newIntAlpha)
  33185. {
  33186. componentTransparency = newIntAlpha;
  33187. if (flags.hasHeavyweightPeerFlag)
  33188. {
  33189. ComponentPeer* const peer = getPeer();
  33190. if (peer != 0)
  33191. peer->setAlpha (newAlpha);
  33192. }
  33193. else
  33194. {
  33195. repaint();
  33196. }
  33197. }
  33198. }
  33199. float Component::getAlpha() const
  33200. {
  33201. return (255 - componentTransparency) / 255.0f;
  33202. }
  33203. void Component::repaintParent()
  33204. {
  33205. if (flags.visibleFlag)
  33206. internalRepaint (0, 0, getWidth(), getHeight());
  33207. }
  33208. void Component::repaint()
  33209. {
  33210. repaint (0, 0, getWidth(), getHeight());
  33211. }
  33212. void Component::repaint (const int x, const int y,
  33213. const int w, const int h)
  33214. {
  33215. bufferedImage_ = Image::null;
  33216. if (flags.visibleFlag)
  33217. internalRepaint (x, y, w, h);
  33218. }
  33219. void Component::repaint (const Rectangle<int>& area)
  33220. {
  33221. repaint (area.getX(), area.getY(), area.getWidth(), area.getHeight());
  33222. }
  33223. void Component::internalRepaint (int x, int y, int w, int h)
  33224. {
  33225. // if component methods are being called from threads other than the message
  33226. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33227. checkMessageManagerIsLocked
  33228. if (x < 0)
  33229. {
  33230. w += x;
  33231. x = 0;
  33232. }
  33233. if (x + w > getWidth())
  33234. w = getWidth() - x;
  33235. if (w > 0)
  33236. {
  33237. if (y < 0)
  33238. {
  33239. h += y;
  33240. y = 0;
  33241. }
  33242. if (y + h > getHeight())
  33243. h = getHeight() - y;
  33244. if (h > 0)
  33245. {
  33246. if (parentComponent_ != 0)
  33247. {
  33248. x += getX();
  33249. y += getY();
  33250. if (parentComponent_->flags.visibleFlag)
  33251. parentComponent_->internalRepaint (x, y, w, h);
  33252. }
  33253. else if (flags.hasHeavyweightPeerFlag)
  33254. {
  33255. ComponentPeer* const peer = getPeer();
  33256. if (peer != 0)
  33257. peer->repaint (Rectangle<int> (x, y, w, h));
  33258. }
  33259. }
  33260. }
  33261. }
  33262. void Component::renderComponent (Graphics& g)
  33263. {
  33264. const Rectangle<int> clipBounds (g.getClipBounds());
  33265. g.saveState();
  33266. clipObscuredRegions (g, clipBounds, 0, 0);
  33267. if (! g.isClipEmpty())
  33268. {
  33269. if (flags.bufferToImageFlag)
  33270. {
  33271. if (bufferedImage_.isNull())
  33272. {
  33273. bufferedImage_ = Image (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33274. getWidth(), getHeight(), ! flags.opaqueFlag, Image::NativeImage);
  33275. Graphics imG (bufferedImage_);
  33276. paint (imG);
  33277. }
  33278. g.setColour (Colours::black.withAlpha (getAlpha()));
  33279. g.drawImageAt (bufferedImage_, 0, 0);
  33280. }
  33281. else
  33282. {
  33283. paint (g);
  33284. }
  33285. }
  33286. g.restoreState();
  33287. for (int i = 0; i < childComponentList_.size(); ++i)
  33288. {
  33289. Component* const child = childComponentList_.getUnchecked (i);
  33290. if (child->isVisible() && clipBounds.intersects (child->getBounds()))
  33291. {
  33292. g.saveState();
  33293. if (g.reduceClipRegion (child->getBounds()))
  33294. {
  33295. for (int j = i + 1; j < childComponentList_.size(); ++j)
  33296. {
  33297. const Component* const sibling = childComponentList_.getUnchecked (j);
  33298. if (sibling->flags.opaqueFlag && sibling->isVisible())
  33299. g.excludeClipRegion (sibling->getBounds());
  33300. }
  33301. if (! g.isClipEmpty())
  33302. {
  33303. g.setOrigin (child->getX(), child->getY());
  33304. child->paintEntireComponent (g, false);
  33305. }
  33306. }
  33307. g.restoreState();
  33308. }
  33309. }
  33310. g.saveState();
  33311. paintOverChildren (g);
  33312. g.restoreState();
  33313. }
  33314. void Component::paintEntireComponent (Graphics& g, bool ignoreAlphaLevel)
  33315. {
  33316. jassert (! g.isClipEmpty());
  33317. #if JUCE_DEBUG
  33318. flags.isInsidePaintCall = true;
  33319. #endif
  33320. if (effect_ != 0)
  33321. {
  33322. Image effectImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33323. getWidth(), getHeight(), ! flags.opaqueFlag, Image::NativeImage);
  33324. {
  33325. Graphics g2 (effectImage);
  33326. renderComponent (g2);
  33327. }
  33328. effect_->applyEffect (effectImage, g, ignoreAlphaLevel ? 1.0f : getAlpha());
  33329. }
  33330. else
  33331. {
  33332. if (componentTransparency > 0 && ! ignoreAlphaLevel)
  33333. {
  33334. if (componentTransparency < 255)
  33335. {
  33336. Image temp (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33337. getWidth(), getHeight(), ! flags.opaqueFlag, Image::NativeImage);
  33338. {
  33339. Graphics tempG (temp);
  33340. tempG.reduceClipRegion (g.getClipBounds());
  33341. paintEntireComponent (tempG, true);
  33342. }
  33343. g.setColour (Colours::black.withAlpha (getAlpha()));
  33344. g.drawImageAt (temp, 0, 0);
  33345. }
  33346. }
  33347. else
  33348. {
  33349. renderComponent (g);
  33350. }
  33351. }
  33352. #if JUCE_DEBUG
  33353. flags.isInsidePaintCall = false;
  33354. #endif
  33355. }
  33356. const Image Component::createComponentSnapshot (const Rectangle<int>& areaToGrab,
  33357. const bool clipImageToComponentBounds)
  33358. {
  33359. Rectangle<int> r (areaToGrab);
  33360. if (clipImageToComponentBounds)
  33361. r = r.getIntersection (getLocalBounds());
  33362. Image componentImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33363. jmax (1, r.getWidth()),
  33364. jmax (1, r.getHeight()),
  33365. true);
  33366. Graphics imageContext (componentImage);
  33367. imageContext.setOrigin (-r.getX(), -r.getY());
  33368. paintEntireComponent (imageContext, true);
  33369. return componentImage;
  33370. }
  33371. void Component::setComponentEffect (ImageEffectFilter* const effect)
  33372. {
  33373. if (effect_ != effect)
  33374. {
  33375. effect_ = effect;
  33376. repaint();
  33377. }
  33378. }
  33379. LookAndFeel& Component::getLookAndFeel() const throw()
  33380. {
  33381. const Component* c = this;
  33382. do
  33383. {
  33384. if (c->lookAndFeel_ != 0)
  33385. return *(c->lookAndFeel_);
  33386. c = c->parentComponent_;
  33387. }
  33388. while (c != 0);
  33389. return LookAndFeel::getDefaultLookAndFeel();
  33390. }
  33391. void Component::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  33392. {
  33393. if (lookAndFeel_ != newLookAndFeel)
  33394. {
  33395. lookAndFeel_ = newLookAndFeel;
  33396. sendLookAndFeelChange();
  33397. }
  33398. }
  33399. void Component::lookAndFeelChanged()
  33400. {
  33401. }
  33402. void Component::sendLookAndFeelChange()
  33403. {
  33404. repaint();
  33405. lookAndFeelChanged();
  33406. // (it's not a great idea to do anything that would delete this component
  33407. // during the lookAndFeelChanged() callback)
  33408. jassert (isValidComponent());
  33409. SafePointer<Component> safePointer (this);
  33410. for (int i = childComponentList_.size(); --i >= 0;)
  33411. {
  33412. childComponentList_.getUnchecked (i)->sendLookAndFeelChange();
  33413. if (safePointer == 0)
  33414. return;
  33415. i = jmin (i, childComponentList_.size());
  33416. }
  33417. }
  33418. namespace ComponentHelpers
  33419. {
  33420. const Identifier getColourPropertyId (const int colourId)
  33421. {
  33422. String s;
  33423. s.preallocateStorage (18);
  33424. s << "jcclr_" << String::toHexString (colourId);
  33425. return s;
  33426. }
  33427. }
  33428. const Colour Component::findColour (const int colourId, const bool inheritFromParent) const
  33429. {
  33430. var* const v = properties.getVarPointer (ComponentHelpers::getColourPropertyId (colourId));
  33431. if (v != 0)
  33432. return Colour ((int) *v);
  33433. if (inheritFromParent && parentComponent_ != 0)
  33434. return parentComponent_->findColour (colourId, true);
  33435. return getLookAndFeel().findColour (colourId);
  33436. }
  33437. bool Component::isColourSpecified (const int colourId) const
  33438. {
  33439. return properties.contains (ComponentHelpers::getColourPropertyId (colourId));
  33440. }
  33441. void Component::removeColour (const int colourId)
  33442. {
  33443. if (properties.remove (ComponentHelpers::getColourPropertyId (colourId)))
  33444. colourChanged();
  33445. }
  33446. void Component::setColour (const int colourId, const Colour& colour)
  33447. {
  33448. if (properties.set (ComponentHelpers::getColourPropertyId (colourId), (int) colour.getARGB()))
  33449. colourChanged();
  33450. }
  33451. void Component::copyAllExplicitColoursTo (Component& target) const
  33452. {
  33453. bool changed = false;
  33454. for (int i = properties.size(); --i >= 0;)
  33455. {
  33456. const Identifier name (properties.getName(i));
  33457. if (name.toString().startsWith ("jcclr_"))
  33458. if (target.properties.set (name, properties [name]))
  33459. changed = true;
  33460. }
  33461. if (changed)
  33462. target.colourChanged();
  33463. }
  33464. void Component::colourChanged()
  33465. {
  33466. }
  33467. const Rectangle<int> Component::getLocalBounds() const throw()
  33468. {
  33469. return Rectangle<int> (getWidth(), getHeight());
  33470. }
  33471. const Rectangle<int> Component::getParentOrMainMonitorBounds() const
  33472. {
  33473. return parentComponent_ != 0 ? parentComponent_->getLocalBounds()
  33474. : Desktop::getInstance().getMainMonitorArea();
  33475. }
  33476. const Rectangle<int> Component::getUnclippedArea() const
  33477. {
  33478. int x = 0, y = 0, w = getWidth(), h = getHeight();
  33479. Component* p = parentComponent_;
  33480. int px = getX();
  33481. int py = getY();
  33482. while (p != 0)
  33483. {
  33484. if (! Rectangle<int>::intersectRectangles (x, y, w, h, -px, -py, p->getWidth(), p->getHeight()))
  33485. return Rectangle<int>();
  33486. px += p->getX();
  33487. py += p->getY();
  33488. p = p->parentComponent_;
  33489. }
  33490. return Rectangle<int> (x, y, w, h);
  33491. }
  33492. void Component::clipObscuredRegions (Graphics& g, const Rectangle<int>& clipRect,
  33493. const int deltaX, const int deltaY) const
  33494. {
  33495. for (int i = childComponentList_.size(); --i >= 0;)
  33496. {
  33497. const Component* const c = childComponentList_.getUnchecked(i);
  33498. if (c->isVisible())
  33499. {
  33500. const Rectangle<int> newClip (clipRect.getIntersection (c->bounds_));
  33501. if (! newClip.isEmpty())
  33502. {
  33503. if (c->isOpaque())
  33504. {
  33505. g.excludeClipRegion (newClip.translated (deltaX, deltaY));
  33506. }
  33507. else
  33508. {
  33509. c->clipObscuredRegions (g, newClip.translated (-c->getX(), -c->getY()),
  33510. c->getX() + deltaX,
  33511. c->getY() + deltaY);
  33512. }
  33513. }
  33514. }
  33515. }
  33516. }
  33517. void Component::getVisibleArea (RectangleList& result, const bool includeSiblings) const
  33518. {
  33519. result.clear();
  33520. const Rectangle<int> unclipped (getUnclippedArea());
  33521. if (! unclipped.isEmpty())
  33522. {
  33523. result.add (unclipped);
  33524. if (includeSiblings)
  33525. {
  33526. const Component* const c = getTopLevelComponent();
  33527. c->subtractObscuredRegions (result, c->relativePositionToOtherComponent (this, Point<int>()),
  33528. c->getLocalBounds(), this);
  33529. }
  33530. subtractObscuredRegions (result, Point<int>(), unclipped, 0);
  33531. result.consolidate();
  33532. }
  33533. }
  33534. void Component::subtractObscuredRegions (RectangleList& result,
  33535. const Point<int>& delta,
  33536. const Rectangle<int>& clipRect,
  33537. const Component* const compToAvoid) const
  33538. {
  33539. for (int i = childComponentList_.size(); --i >= 0;)
  33540. {
  33541. const Component* const c = childComponentList_.getUnchecked(i);
  33542. if (c != compToAvoid && c->isVisible())
  33543. {
  33544. if (c->isOpaque())
  33545. {
  33546. Rectangle<int> childBounds (c->bounds_.getIntersection (clipRect));
  33547. childBounds.translate (delta.getX(), delta.getY());
  33548. result.subtract (childBounds);
  33549. }
  33550. else
  33551. {
  33552. Rectangle<int> newClip (clipRect.getIntersection (c->bounds_));
  33553. newClip.translate (-c->getX(), -c->getY());
  33554. c->subtractObscuredRegions (result, c->getPosition() + delta,
  33555. newClip, compToAvoid);
  33556. }
  33557. }
  33558. }
  33559. }
  33560. void Component::mouseEnter (const MouseEvent&)
  33561. {
  33562. // base class does nothing
  33563. }
  33564. void Component::mouseExit (const MouseEvent&)
  33565. {
  33566. // base class does nothing
  33567. }
  33568. void Component::mouseDown (const MouseEvent&)
  33569. {
  33570. // base class does nothing
  33571. }
  33572. void Component::mouseUp (const MouseEvent&)
  33573. {
  33574. // base class does nothing
  33575. }
  33576. void Component::mouseDrag (const MouseEvent&)
  33577. {
  33578. // base class does nothing
  33579. }
  33580. void Component::mouseMove (const MouseEvent&)
  33581. {
  33582. // base class does nothing
  33583. }
  33584. void Component::mouseDoubleClick (const MouseEvent&)
  33585. {
  33586. // base class does nothing
  33587. }
  33588. void Component::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  33589. {
  33590. // the base class just passes this event up to its parent..
  33591. if (parentComponent_ != 0)
  33592. parentComponent_->mouseWheelMove (e.getEventRelativeTo (parentComponent_),
  33593. wheelIncrementX, wheelIncrementY);
  33594. }
  33595. void Component::resized()
  33596. {
  33597. // base class does nothing
  33598. }
  33599. void Component::moved()
  33600. {
  33601. // base class does nothing
  33602. }
  33603. void Component::childBoundsChanged (Component*)
  33604. {
  33605. // base class does nothing
  33606. }
  33607. void Component::parentSizeChanged()
  33608. {
  33609. // base class does nothing
  33610. }
  33611. void Component::addComponentListener (ComponentListener* const newListener)
  33612. {
  33613. jassert (isValidComponent());
  33614. componentListeners.add (newListener);
  33615. }
  33616. void Component::removeComponentListener (ComponentListener* const listenerToRemove)
  33617. {
  33618. jassert (isValidComponent());
  33619. componentListeners.remove (listenerToRemove);
  33620. }
  33621. void Component::inputAttemptWhenModal()
  33622. {
  33623. bringModalComponentToFront();
  33624. getLookAndFeel().playAlertSound();
  33625. }
  33626. bool Component::canModalEventBeSentToComponent (const Component*)
  33627. {
  33628. return false;
  33629. }
  33630. void Component::internalModalInputAttempt()
  33631. {
  33632. Component* const current = getCurrentlyModalComponent();
  33633. if (current != 0)
  33634. current->inputAttemptWhenModal();
  33635. }
  33636. void Component::paint (Graphics&)
  33637. {
  33638. // all painting is done in the subclasses
  33639. jassert (! isOpaque()); // if your component's opaque, you've gotta paint it!
  33640. }
  33641. void Component::paintOverChildren (Graphics&)
  33642. {
  33643. // all painting is done in the subclasses
  33644. }
  33645. void Component::handleMessage (const Message& message)
  33646. {
  33647. if (message.intParameter1 == exitModalStateMessage)
  33648. {
  33649. exitModalState (message.intParameter2);
  33650. }
  33651. else if (message.intParameter1 == customCommandMessage)
  33652. {
  33653. handleCommandMessage (message.intParameter2);
  33654. }
  33655. }
  33656. void Component::postCommandMessage (const int commandId)
  33657. {
  33658. postMessage (new Message (customCommandMessage, commandId, 0, 0));
  33659. }
  33660. void Component::handleCommandMessage (int)
  33661. {
  33662. // used by subclasses
  33663. }
  33664. void Component::addMouseListener (MouseListener* const newListener,
  33665. const bool wantsEventsForAllNestedChildComponents)
  33666. {
  33667. // if component methods are being called from threads other than the message
  33668. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33669. checkMessageManagerIsLocked
  33670. // If you register a component as a mouselistener for itself, it'll receive all the events
  33671. // twice - once via the direct callback that all components get anyway, and then again as a listener!
  33672. jassert ((newListener != this) || wantsEventsForAllNestedChildComponents);
  33673. if (mouseListeners_ == 0)
  33674. mouseListeners_ = new MouseListenerList();
  33675. mouseListeners_->addListener (newListener, wantsEventsForAllNestedChildComponents);
  33676. }
  33677. void Component::removeMouseListener (MouseListener* const listenerToRemove)
  33678. {
  33679. // if component methods are being called from threads other than the message
  33680. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33681. checkMessageManagerIsLocked
  33682. if (mouseListeners_ != 0)
  33683. mouseListeners_->removeListener (listenerToRemove);
  33684. }
  33685. void Component::internalMouseEnter (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33686. {
  33687. if (isCurrentlyBlockedByAnotherModalComponent())
  33688. {
  33689. // if something else is modal, always just show a normal mouse cursor
  33690. source.showMouseCursor (MouseCursor::NormalCursor);
  33691. return;
  33692. }
  33693. if (! flags.mouseInsideFlag)
  33694. {
  33695. flags.mouseInsideFlag = true;
  33696. flags.mouseOverFlag = true;
  33697. flags.draggingFlag = false;
  33698. BailOutChecker checker (this);
  33699. if (flags.repaintOnMouseActivityFlag)
  33700. repaint();
  33701. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33702. this, this, time, relativePos, time, 0, false);
  33703. mouseEnter (me);
  33704. if (checker.shouldBailOut())
  33705. return;
  33706. Desktop::getInstance().resetTimer();
  33707. Desktop::getInstance().mouseListeners.callChecked (checker, &MouseListener::mouseEnter, me);
  33708. MouseListenerList::sendMouseEvent (this, checker, &MouseListener::mouseEnter, me);
  33709. }
  33710. }
  33711. void Component::internalMouseExit (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33712. {
  33713. BailOutChecker checker (this);
  33714. if (flags.draggingFlag)
  33715. {
  33716. internalMouseUp (source, relativePos, time, source.getCurrentModifiers().getRawFlags());
  33717. if (checker.shouldBailOut())
  33718. return;
  33719. }
  33720. if (flags.mouseInsideFlag || flags.mouseOverFlag)
  33721. {
  33722. flags.mouseInsideFlag = false;
  33723. flags.mouseOverFlag = false;
  33724. flags.draggingFlag = false;
  33725. if (flags.repaintOnMouseActivityFlag)
  33726. repaint();
  33727. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33728. this, this, time, relativePos, time, 0, false);
  33729. mouseExit (me);
  33730. if (checker.shouldBailOut())
  33731. return;
  33732. Desktop::getInstance().resetTimer();
  33733. Desktop::getInstance().mouseListeners.callChecked (checker, &MouseListener::mouseExit, me);
  33734. MouseListenerList::sendMouseEvent (this, checker, &MouseListener::mouseExit, me);
  33735. }
  33736. }
  33737. class InternalDragRepeater : public Timer
  33738. {
  33739. public:
  33740. InternalDragRepeater()
  33741. {}
  33742. ~InternalDragRepeater()
  33743. {
  33744. clearSingletonInstance();
  33745. }
  33746. juce_DeclareSingleton_SingleThreaded_Minimal (InternalDragRepeater)
  33747. void timerCallback()
  33748. {
  33749. Desktop& desktop = Desktop::getInstance();
  33750. int numMiceDown = 0;
  33751. for (int i = desktop.getNumMouseSources(); --i >= 0;)
  33752. {
  33753. MouseInputSource* const source = desktop.getMouseSource(i);
  33754. if (source->isDragging())
  33755. {
  33756. source->triggerFakeMove();
  33757. ++numMiceDown;
  33758. }
  33759. }
  33760. if (numMiceDown == 0)
  33761. deleteInstance();
  33762. }
  33763. juce_UseDebuggingNewOperator
  33764. private:
  33765. InternalDragRepeater (const InternalDragRepeater&);
  33766. InternalDragRepeater& operator= (const InternalDragRepeater&);
  33767. };
  33768. juce_ImplementSingleton_SingleThreaded (InternalDragRepeater)
  33769. void Component::beginDragAutoRepeat (const int interval)
  33770. {
  33771. if (interval > 0)
  33772. {
  33773. if (InternalDragRepeater::getInstance()->getTimerInterval() != interval)
  33774. InternalDragRepeater::getInstance()->startTimer (interval);
  33775. }
  33776. else
  33777. {
  33778. InternalDragRepeater::deleteInstance();
  33779. }
  33780. }
  33781. void Component::internalMouseDown (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33782. {
  33783. Desktop& desktop = Desktop::getInstance();
  33784. BailOutChecker checker (this);
  33785. if (isCurrentlyBlockedByAnotherModalComponent())
  33786. {
  33787. internalModalInputAttempt();
  33788. if (checker.shouldBailOut())
  33789. return;
  33790. // If processing the input attempt has exited the modal loop, we'll allow the event
  33791. // to be delivered..
  33792. if (isCurrentlyBlockedByAnotherModalComponent())
  33793. {
  33794. // allow blocked mouse-events to go to global listeners..
  33795. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33796. this, this, time, relativePos, time,
  33797. source.getNumberOfMultipleClicks(), false);
  33798. desktop.resetTimer();
  33799. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDown, me);
  33800. return;
  33801. }
  33802. }
  33803. {
  33804. Component* c = this;
  33805. while (c != 0)
  33806. {
  33807. if (c->isBroughtToFrontOnMouseClick())
  33808. {
  33809. c->toFront (true);
  33810. if (checker.shouldBailOut())
  33811. return;
  33812. }
  33813. c = c->parentComponent_;
  33814. }
  33815. }
  33816. if (! flags.dontFocusOnMouseClickFlag)
  33817. {
  33818. grabFocusInternal (focusChangedByMouseClick);
  33819. if (checker.shouldBailOut())
  33820. return;
  33821. }
  33822. flags.draggingFlag = true;
  33823. flags.mouseOverFlag = true;
  33824. if (flags.repaintOnMouseActivityFlag)
  33825. repaint();
  33826. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33827. this, this, time, relativePos, time,
  33828. source.getNumberOfMultipleClicks(), false);
  33829. mouseDown (me);
  33830. if (checker.shouldBailOut())
  33831. return;
  33832. desktop.resetTimer();
  33833. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDown, me);
  33834. MouseListenerList::sendMouseEvent (this, checker, &MouseListener::mouseDown, me);
  33835. }
  33836. void Component::internalMouseUp (MouseInputSource& source, const Point<int>& relativePos, const Time& time, const ModifierKeys& oldModifiers)
  33837. {
  33838. if (flags.draggingFlag)
  33839. {
  33840. Desktop& desktop = Desktop::getInstance();
  33841. flags.draggingFlag = false;
  33842. BailOutChecker checker (this);
  33843. if (flags.repaintOnMouseActivityFlag)
  33844. repaint();
  33845. const MouseEvent me (source, relativePos,
  33846. oldModifiers, this, this, time,
  33847. globalPositionToRelative (source.getLastMouseDownPosition()),
  33848. source.getLastMouseDownTime(),
  33849. source.getNumberOfMultipleClicks(),
  33850. source.hasMouseMovedSignificantlySincePressed());
  33851. mouseUp (me);
  33852. if (checker.shouldBailOut())
  33853. return;
  33854. desktop.resetTimer();
  33855. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseUp, me);
  33856. MouseListenerList::sendMouseEvent (this, checker, &MouseListener::mouseUp, me);
  33857. if (checker.shouldBailOut())
  33858. return;
  33859. // check for double-click
  33860. if (me.getNumberOfClicks() >= 2)
  33861. {
  33862. mouseDoubleClick (me);
  33863. if (checker.shouldBailOut())
  33864. return;
  33865. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDoubleClick, me);
  33866. MouseListenerList::sendMouseEvent (this, checker, &MouseListener::mouseDoubleClick, me);
  33867. }
  33868. }
  33869. }
  33870. void Component::internalMouseDrag (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33871. {
  33872. if (flags.draggingFlag)
  33873. {
  33874. Desktop& desktop = Desktop::getInstance();
  33875. flags.mouseOverFlag = reallyContains (relativePos.getX(), relativePos.getY(), false);
  33876. BailOutChecker checker (this);
  33877. const MouseEvent me (source, relativePos,
  33878. source.getCurrentModifiers(), this, this, time,
  33879. globalPositionToRelative (source.getLastMouseDownPosition()),
  33880. source.getLastMouseDownTime(),
  33881. source.getNumberOfMultipleClicks(),
  33882. source.hasMouseMovedSignificantlySincePressed());
  33883. mouseDrag (me);
  33884. if (checker.shouldBailOut())
  33885. return;
  33886. desktop.resetTimer();
  33887. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDrag, me);
  33888. MouseListenerList::sendMouseEvent (this, checker, &MouseListener::mouseDrag, me);
  33889. }
  33890. }
  33891. void Component::internalMouseMove (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33892. {
  33893. Desktop& desktop = Desktop::getInstance();
  33894. BailOutChecker checker (this);
  33895. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33896. this, this, time, relativePos,
  33897. time, 0, false);
  33898. if (isCurrentlyBlockedByAnotherModalComponent())
  33899. {
  33900. // allow blocked mouse-events to go to global listeners..
  33901. desktop.sendMouseMove();
  33902. }
  33903. else
  33904. {
  33905. flags.mouseOverFlag = true;
  33906. mouseMove (me);
  33907. if (checker.shouldBailOut())
  33908. return;
  33909. desktop.resetTimer();
  33910. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseMove, me);
  33911. MouseListenerList::sendMouseEvent (this, checker, &MouseListener::mouseMove, me);
  33912. }
  33913. }
  33914. void Component::internalMouseWheel (MouseInputSource& source, const Point<int>& relativePos,
  33915. const Time& time, const float amountX, const float amountY)
  33916. {
  33917. Desktop& desktop = Desktop::getInstance();
  33918. BailOutChecker checker (this);
  33919. const float wheelIncrementX = amountX / 256.0f;
  33920. const float wheelIncrementY = amountY / 256.0f;
  33921. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33922. this, this, time, relativePos, time, 0, false);
  33923. if (isCurrentlyBlockedByAnotherModalComponent())
  33924. {
  33925. // allow blocked mouse-events to go to global listeners..
  33926. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheelIncrementX, wheelIncrementY);
  33927. }
  33928. else
  33929. {
  33930. mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  33931. if (checker.shouldBailOut())
  33932. return;
  33933. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheelIncrementX, wheelIncrementY);
  33934. MouseListenerList::sendWheelEvent (this, checker, me, wheelIncrementX, wheelIncrementY);
  33935. }
  33936. }
  33937. void Component::sendFakeMouseMove() const
  33938. {
  33939. Desktop::getInstance().getMainMouseSource().triggerFakeMove();
  33940. }
  33941. void Component::broughtToFront()
  33942. {
  33943. }
  33944. void Component::internalBroughtToFront()
  33945. {
  33946. if (! isValidComponent())
  33947. return;
  33948. if (flags.hasHeavyweightPeerFlag)
  33949. Desktop::getInstance().componentBroughtToFront (this);
  33950. BailOutChecker checker (this);
  33951. broughtToFront();
  33952. if (checker.shouldBailOut())
  33953. return;
  33954. componentListeners.callChecked (checker, &ComponentListener::componentBroughtToFront, *this);
  33955. if (checker.shouldBailOut())
  33956. return;
  33957. // When brought to the front and there's a modal component blocking this one,
  33958. // we need to bring the modal one to the front instead..
  33959. Component* const cm = getCurrentlyModalComponent();
  33960. if (cm != 0 && cm->getTopLevelComponent() != getTopLevelComponent())
  33961. bringModalComponentToFront();
  33962. }
  33963. void Component::focusGained (FocusChangeType)
  33964. {
  33965. // base class does nothing
  33966. }
  33967. void Component::internalFocusGain (const FocusChangeType cause)
  33968. {
  33969. SafePointer<Component> safePointer (this);
  33970. focusGained (cause);
  33971. if (safePointer != 0)
  33972. internalChildFocusChange (cause);
  33973. }
  33974. void Component::focusLost (FocusChangeType)
  33975. {
  33976. // base class does nothing
  33977. }
  33978. void Component::internalFocusLoss (const FocusChangeType cause)
  33979. {
  33980. SafePointer<Component> safePointer (this);
  33981. focusLost (focusChangedDirectly);
  33982. if (safePointer != 0)
  33983. internalChildFocusChange (cause);
  33984. }
  33985. void Component::focusOfChildComponentChanged (FocusChangeType /*cause*/)
  33986. {
  33987. // base class does nothing
  33988. }
  33989. void Component::internalChildFocusChange (FocusChangeType cause)
  33990. {
  33991. const bool childIsNowFocused = hasKeyboardFocus (true);
  33992. if (flags.childCompFocusedFlag != childIsNowFocused)
  33993. {
  33994. flags.childCompFocusedFlag = childIsNowFocused;
  33995. SafePointer<Component> safePointer (this);
  33996. focusOfChildComponentChanged (cause);
  33997. if (safePointer == 0)
  33998. return;
  33999. }
  34000. if (parentComponent_ != 0)
  34001. parentComponent_->internalChildFocusChange (cause);
  34002. }
  34003. bool Component::isEnabled() const throw()
  34004. {
  34005. return (! flags.isDisabledFlag)
  34006. && (parentComponent_ == 0 || parentComponent_->isEnabled());
  34007. }
  34008. void Component::setEnabled (const bool shouldBeEnabled)
  34009. {
  34010. if (flags.isDisabledFlag == shouldBeEnabled)
  34011. {
  34012. flags.isDisabledFlag = ! shouldBeEnabled;
  34013. // if any parent components are disabled, setting our flag won't make a difference,
  34014. // so no need to send a change message
  34015. if (parentComponent_ == 0 || parentComponent_->isEnabled())
  34016. sendEnablementChangeMessage();
  34017. }
  34018. }
  34019. void Component::sendEnablementChangeMessage()
  34020. {
  34021. SafePointer<Component> safePointer (this);
  34022. enablementChanged();
  34023. if (safePointer == 0)
  34024. return;
  34025. for (int i = getNumChildComponents(); --i >= 0;)
  34026. {
  34027. Component* const c = getChildComponent (i);
  34028. if (c != 0)
  34029. {
  34030. c->sendEnablementChangeMessage();
  34031. if (safePointer == 0)
  34032. return;
  34033. }
  34034. }
  34035. }
  34036. void Component::enablementChanged()
  34037. {
  34038. }
  34039. void Component::setWantsKeyboardFocus (const bool wantsFocus) throw()
  34040. {
  34041. flags.wantsFocusFlag = wantsFocus;
  34042. }
  34043. void Component::setMouseClickGrabsKeyboardFocus (const bool shouldGrabFocus)
  34044. {
  34045. flags.dontFocusOnMouseClickFlag = ! shouldGrabFocus;
  34046. }
  34047. bool Component::getMouseClickGrabsKeyboardFocus() const throw()
  34048. {
  34049. return ! flags.dontFocusOnMouseClickFlag;
  34050. }
  34051. bool Component::getWantsKeyboardFocus() const throw()
  34052. {
  34053. return flags.wantsFocusFlag && ! flags.isDisabledFlag;
  34054. }
  34055. void Component::setFocusContainer (const bool shouldBeFocusContainer) throw()
  34056. {
  34057. flags.isFocusContainerFlag = shouldBeFocusContainer;
  34058. }
  34059. bool Component::isFocusContainer() const throw()
  34060. {
  34061. return flags.isFocusContainerFlag;
  34062. }
  34063. static const Identifier juce_explicitFocusOrderId ("_jexfo");
  34064. int Component::getExplicitFocusOrder() const
  34065. {
  34066. return properties [juce_explicitFocusOrderId];
  34067. }
  34068. void Component::setExplicitFocusOrder (const int newFocusOrderIndex)
  34069. {
  34070. properties.set (juce_explicitFocusOrderId, newFocusOrderIndex);
  34071. }
  34072. KeyboardFocusTraverser* Component::createFocusTraverser()
  34073. {
  34074. if (flags.isFocusContainerFlag || parentComponent_ == 0)
  34075. return new KeyboardFocusTraverser();
  34076. return parentComponent_->createFocusTraverser();
  34077. }
  34078. void Component::takeKeyboardFocus (const FocusChangeType cause)
  34079. {
  34080. // give the focus to this component
  34081. if (currentlyFocusedComponent != this)
  34082. {
  34083. JUCE_TRY
  34084. {
  34085. // get the focus onto our desktop window
  34086. ComponentPeer* const peer = getPeer();
  34087. if (peer != 0)
  34088. {
  34089. SafePointer<Component> safePointer (this);
  34090. peer->grabFocus();
  34091. if (peer->isFocused() && currentlyFocusedComponent != this)
  34092. {
  34093. SafePointer<Component> componentLosingFocus (currentlyFocusedComponent);
  34094. currentlyFocusedComponent = this;
  34095. Desktop::getInstance().triggerFocusCallback();
  34096. // call this after setting currentlyFocusedComponent so that the one that's
  34097. // losing it has a chance to see where focus is going
  34098. if (componentLosingFocus != 0)
  34099. componentLosingFocus->internalFocusLoss (cause);
  34100. if (currentlyFocusedComponent == this)
  34101. {
  34102. focusGained (cause);
  34103. if (safePointer != 0)
  34104. internalChildFocusChange (cause);
  34105. }
  34106. }
  34107. }
  34108. }
  34109. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  34110. catch (const std::exception& e)
  34111. {
  34112. currentlyFocusedComponent = 0;
  34113. Desktop::getInstance().triggerFocusCallback();
  34114. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  34115. }
  34116. catch (...)
  34117. {
  34118. currentlyFocusedComponent = 0;
  34119. Desktop::getInstance().triggerFocusCallback();
  34120. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  34121. }
  34122. #endif
  34123. }
  34124. }
  34125. void Component::grabFocusInternal (const FocusChangeType cause, const bool canTryParent)
  34126. {
  34127. if (isShowing())
  34128. {
  34129. if (flags.wantsFocusFlag && (isEnabled() || parentComponent_ == 0))
  34130. {
  34131. takeKeyboardFocus (cause);
  34132. }
  34133. else
  34134. {
  34135. if (isParentOf (currentlyFocusedComponent)
  34136. && currentlyFocusedComponent->isShowing())
  34137. {
  34138. // do nothing if the focused component is actually a child of ours..
  34139. }
  34140. else
  34141. {
  34142. // find the default child component..
  34143. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  34144. if (traverser != 0)
  34145. {
  34146. Component* const defaultComp = traverser->getDefaultComponent (this);
  34147. traverser = 0;
  34148. if (defaultComp != 0)
  34149. {
  34150. defaultComp->grabFocusInternal (cause, false);
  34151. return;
  34152. }
  34153. }
  34154. if (canTryParent && parentComponent_ != 0)
  34155. {
  34156. // if no children want it and we're allowed to try our parent comp,
  34157. // then pass up to parent, which will try our siblings.
  34158. parentComponent_->grabFocusInternal (cause, true);
  34159. }
  34160. }
  34161. }
  34162. }
  34163. }
  34164. void Component::grabKeyboardFocus()
  34165. {
  34166. // if component methods are being called from threads other than the message
  34167. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  34168. checkMessageManagerIsLocked
  34169. grabFocusInternal (focusChangedDirectly);
  34170. }
  34171. void Component::moveKeyboardFocusToSibling (const bool moveToNext)
  34172. {
  34173. // if component methods are being called from threads other than the message
  34174. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  34175. checkMessageManagerIsLocked
  34176. if (parentComponent_ != 0)
  34177. {
  34178. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  34179. if (traverser != 0)
  34180. {
  34181. Component* const nextComp = moveToNext ? traverser->getNextComponent (this)
  34182. : traverser->getPreviousComponent (this);
  34183. traverser = 0;
  34184. if (nextComp != 0)
  34185. {
  34186. if (nextComp->isCurrentlyBlockedByAnotherModalComponent())
  34187. {
  34188. SafePointer<Component> nextCompPointer (nextComp);
  34189. internalModalInputAttempt();
  34190. if (nextCompPointer == 0 || nextComp->isCurrentlyBlockedByAnotherModalComponent())
  34191. return;
  34192. }
  34193. nextComp->grabFocusInternal (focusChangedByTabKey);
  34194. return;
  34195. }
  34196. }
  34197. parentComponent_->moveKeyboardFocusToSibling (moveToNext);
  34198. }
  34199. }
  34200. bool Component::hasKeyboardFocus (const bool trueIfChildIsFocused) const
  34201. {
  34202. return (currentlyFocusedComponent == this)
  34203. || (trueIfChildIsFocused && isParentOf (currentlyFocusedComponent));
  34204. }
  34205. Component* JUCE_CALLTYPE Component::getCurrentlyFocusedComponent() throw()
  34206. {
  34207. return currentlyFocusedComponent;
  34208. }
  34209. void Component::giveAwayFocus()
  34210. {
  34211. // use a copy so we can clear the value before the call
  34212. SafePointer<Component> componentLosingFocus (currentlyFocusedComponent);
  34213. currentlyFocusedComponent = 0;
  34214. Desktop::getInstance().triggerFocusCallback();
  34215. if (componentLosingFocus != 0)
  34216. componentLosingFocus->internalFocusLoss (focusChangedDirectly);
  34217. }
  34218. bool Component::isMouseOver() const throw()
  34219. {
  34220. return flags.mouseOverFlag;
  34221. }
  34222. bool Component::isMouseButtonDown() const throw()
  34223. {
  34224. return flags.draggingFlag;
  34225. }
  34226. bool Component::isMouseOverOrDragging() const throw()
  34227. {
  34228. return flags.mouseOverFlag || flags.draggingFlag;
  34229. }
  34230. bool JUCE_CALLTYPE Component::isMouseButtonDownAnywhere() throw()
  34231. {
  34232. return ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown();
  34233. }
  34234. const Point<int> Component::getMouseXYRelative() const
  34235. {
  34236. return globalPositionToRelative (Desktop::getMousePosition());
  34237. }
  34238. const Rectangle<int> Component::getParentMonitorArea() const
  34239. {
  34240. return Desktop::getInstance()
  34241. .getMonitorAreaContaining (relativePositionToGlobal (getLocalBounds().getCentre()));
  34242. }
  34243. void Component::addKeyListener (KeyListener* const newListener)
  34244. {
  34245. if (keyListeners_ == 0)
  34246. keyListeners_ = new Array <KeyListener*>();
  34247. keyListeners_->addIfNotAlreadyThere (newListener);
  34248. }
  34249. void Component::removeKeyListener (KeyListener* const listenerToRemove)
  34250. {
  34251. if (keyListeners_ != 0)
  34252. keyListeners_->removeValue (listenerToRemove);
  34253. }
  34254. bool Component::keyPressed (const KeyPress&)
  34255. {
  34256. return false;
  34257. }
  34258. bool Component::keyStateChanged (const bool /*isKeyDown*/)
  34259. {
  34260. return false;
  34261. }
  34262. void Component::modifierKeysChanged (const ModifierKeys& modifiers)
  34263. {
  34264. if (parentComponent_ != 0)
  34265. parentComponent_->modifierKeysChanged (modifiers);
  34266. }
  34267. void Component::internalModifierKeysChanged()
  34268. {
  34269. sendFakeMouseMove();
  34270. modifierKeysChanged (ModifierKeys::getCurrentModifiers());
  34271. }
  34272. ComponentPeer* Component::getPeer() const
  34273. {
  34274. if (flags.hasHeavyweightPeerFlag)
  34275. return ComponentPeer::getPeerFor (this);
  34276. else if (parentComponent_ != 0)
  34277. return parentComponent_->getPeer();
  34278. else
  34279. return 0;
  34280. }
  34281. Component::BailOutChecker::BailOutChecker (Component* const component1, Component* const component2_)
  34282. : safePointer1 (component1), safePointer2 (component2_), component2 (component2_)
  34283. {
  34284. jassert (component1 != 0);
  34285. }
  34286. bool Component::BailOutChecker::shouldBailOut() const throw()
  34287. {
  34288. return safePointer1 == 0 || safePointer2.getComponent() != component2;
  34289. }
  34290. END_JUCE_NAMESPACE
  34291. /*** End of inlined file: juce_Component.cpp ***/
  34292. /*** Start of inlined file: juce_ComponentListener.cpp ***/
  34293. BEGIN_JUCE_NAMESPACE
  34294. void ComponentListener::componentMovedOrResized (Component&, bool, bool) {}
  34295. void ComponentListener::componentBroughtToFront (Component&) {}
  34296. void ComponentListener::componentVisibilityChanged (Component&) {}
  34297. void ComponentListener::componentChildrenChanged (Component&) {}
  34298. void ComponentListener::componentParentHierarchyChanged (Component&) {}
  34299. void ComponentListener::componentNameChanged (Component&) {}
  34300. void ComponentListener::componentBeingDeleted (Component&) {}
  34301. END_JUCE_NAMESPACE
  34302. /*** End of inlined file: juce_ComponentListener.cpp ***/
  34303. /*** Start of inlined file: juce_Desktop.cpp ***/
  34304. BEGIN_JUCE_NAMESPACE
  34305. Desktop::Desktop()
  34306. : mouseClickCounter (0),
  34307. kioskModeComponent (0),
  34308. allowedOrientations (allOrientations)
  34309. {
  34310. createMouseInputSources();
  34311. refreshMonitorSizes();
  34312. }
  34313. Desktop::~Desktop()
  34314. {
  34315. jassert (instance == this);
  34316. instance = 0;
  34317. // doh! If you don't delete all your windows before exiting, you're going to
  34318. // be leaking memory!
  34319. jassert (desktopComponents.size() == 0);
  34320. }
  34321. Desktop& JUCE_CALLTYPE Desktop::getInstance()
  34322. {
  34323. if (instance == 0)
  34324. instance = new Desktop();
  34325. return *instance;
  34326. }
  34327. Desktop* Desktop::instance = 0;
  34328. extern void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords,
  34329. const bool clipToWorkArea);
  34330. void Desktop::refreshMonitorSizes()
  34331. {
  34332. const Array <Rectangle<int> > oldClipped (monitorCoordsClipped);
  34333. const Array <Rectangle<int> > oldUnclipped (monitorCoordsUnclipped);
  34334. monitorCoordsClipped.clear();
  34335. monitorCoordsUnclipped.clear();
  34336. juce_updateMultiMonitorInfo (monitorCoordsClipped, true);
  34337. juce_updateMultiMonitorInfo (monitorCoordsUnclipped, false);
  34338. jassert (monitorCoordsClipped.size() == monitorCoordsUnclipped.size());
  34339. if (oldClipped != monitorCoordsClipped
  34340. || oldUnclipped != monitorCoordsUnclipped)
  34341. {
  34342. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  34343. {
  34344. ComponentPeer* const p = ComponentPeer::getPeer (i);
  34345. if (p != 0)
  34346. p->handleScreenSizeChange();
  34347. }
  34348. }
  34349. }
  34350. int Desktop::getNumDisplayMonitors() const throw()
  34351. {
  34352. return monitorCoordsClipped.size();
  34353. }
  34354. const Rectangle<int> Desktop::getDisplayMonitorCoordinates (const int index, const bool clippedToWorkArea) const throw()
  34355. {
  34356. return clippedToWorkArea ? monitorCoordsClipped [index]
  34357. : monitorCoordsUnclipped [index];
  34358. }
  34359. const RectangleList Desktop::getAllMonitorDisplayAreas (const bool clippedToWorkArea) const throw()
  34360. {
  34361. RectangleList rl;
  34362. for (int i = 0; i < getNumDisplayMonitors(); ++i)
  34363. rl.addWithoutMerging (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  34364. return rl;
  34365. }
  34366. const Rectangle<int> Desktop::getMainMonitorArea (const bool clippedToWorkArea) const throw()
  34367. {
  34368. return getDisplayMonitorCoordinates (0, clippedToWorkArea);
  34369. }
  34370. const Rectangle<int> Desktop::getMonitorAreaContaining (const Point<int>& position, const bool clippedToWorkArea) const
  34371. {
  34372. Rectangle<int> best (getMainMonitorArea (clippedToWorkArea));
  34373. double bestDistance = 1.0e10;
  34374. for (int i = getNumDisplayMonitors(); --i >= 0;)
  34375. {
  34376. const Rectangle<int> rect (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  34377. if (rect.contains (position))
  34378. return rect;
  34379. const double distance = rect.getCentre().getDistanceFrom (position);
  34380. if (distance < bestDistance)
  34381. {
  34382. bestDistance = distance;
  34383. best = rect;
  34384. }
  34385. }
  34386. return best;
  34387. }
  34388. int Desktop::getNumComponents() const throw()
  34389. {
  34390. return desktopComponents.size();
  34391. }
  34392. Component* Desktop::getComponent (const int index) const throw()
  34393. {
  34394. return desktopComponents [index];
  34395. }
  34396. Component* Desktop::findComponentAt (const Point<int>& screenPosition) const
  34397. {
  34398. for (int i = desktopComponents.size(); --i >= 0;)
  34399. {
  34400. Component* const c = desktopComponents.getUnchecked(i);
  34401. const Point<int> relative (c->globalPositionToRelative (screenPosition));
  34402. if (c->contains (relative.getX(), relative.getY()))
  34403. return c->getComponentAt (relative.getX(), relative.getY());
  34404. }
  34405. return 0;
  34406. }
  34407. void Desktop::addDesktopComponent (Component* const c)
  34408. {
  34409. jassert (c != 0);
  34410. jassert (! desktopComponents.contains (c));
  34411. desktopComponents.addIfNotAlreadyThere (c);
  34412. }
  34413. void Desktop::removeDesktopComponent (Component* const c)
  34414. {
  34415. desktopComponents.removeValue (c);
  34416. }
  34417. void Desktop::componentBroughtToFront (Component* const c)
  34418. {
  34419. const int index = desktopComponents.indexOf (c);
  34420. jassert (index >= 0);
  34421. if (index >= 0)
  34422. {
  34423. int newIndex = -1;
  34424. if (! c->isAlwaysOnTop())
  34425. {
  34426. newIndex = desktopComponents.size();
  34427. while (newIndex > 0 && desktopComponents.getUnchecked (newIndex - 1)->isAlwaysOnTop())
  34428. --newIndex;
  34429. --newIndex;
  34430. }
  34431. desktopComponents.move (index, newIndex);
  34432. }
  34433. }
  34434. const Point<int> Desktop::getLastMouseDownPosition() throw()
  34435. {
  34436. return getInstance().getMainMouseSource().getLastMouseDownPosition();
  34437. }
  34438. int Desktop::getMouseButtonClickCounter() throw()
  34439. {
  34440. return getInstance().mouseClickCounter;
  34441. }
  34442. void Desktop::incrementMouseClickCounter() throw()
  34443. {
  34444. ++mouseClickCounter;
  34445. }
  34446. int Desktop::getNumDraggingMouseSources() const throw()
  34447. {
  34448. int num = 0;
  34449. for (int i = mouseSources.size(); --i >= 0;)
  34450. if (mouseSources.getUnchecked(i)->isDragging())
  34451. ++num;
  34452. return num;
  34453. }
  34454. MouseInputSource* Desktop::getDraggingMouseSource (int index) const throw()
  34455. {
  34456. int num = 0;
  34457. for (int i = mouseSources.size(); --i >= 0;)
  34458. {
  34459. MouseInputSource* const mi = mouseSources.getUnchecked(i);
  34460. if (mi->isDragging())
  34461. {
  34462. if (index == num)
  34463. return mi;
  34464. ++num;
  34465. }
  34466. }
  34467. return 0;
  34468. }
  34469. void Desktop::addFocusChangeListener (FocusChangeListener* const listener)
  34470. {
  34471. focusListeners.add (listener);
  34472. }
  34473. void Desktop::removeFocusChangeListener (FocusChangeListener* const listener)
  34474. {
  34475. focusListeners.remove (listener);
  34476. }
  34477. void Desktop::triggerFocusCallback()
  34478. {
  34479. triggerAsyncUpdate();
  34480. }
  34481. void Desktop::handleAsyncUpdate()
  34482. {
  34483. Component* currentFocus = Component::getCurrentlyFocusedComponent();
  34484. focusListeners.call (&FocusChangeListener::globalFocusChanged, currentFocus);
  34485. }
  34486. void Desktop::addGlobalMouseListener (MouseListener* const listener)
  34487. {
  34488. mouseListeners.add (listener);
  34489. resetTimer();
  34490. }
  34491. void Desktop::removeGlobalMouseListener (MouseListener* const listener)
  34492. {
  34493. mouseListeners.remove (listener);
  34494. resetTimer();
  34495. }
  34496. void Desktop::timerCallback()
  34497. {
  34498. if (lastFakeMouseMove != getMousePosition())
  34499. sendMouseMove();
  34500. }
  34501. void Desktop::sendMouseMove()
  34502. {
  34503. if (! mouseListeners.isEmpty())
  34504. {
  34505. startTimer (20);
  34506. lastFakeMouseMove = getMousePosition();
  34507. Component* const target = findComponentAt (lastFakeMouseMove);
  34508. if (target != 0)
  34509. {
  34510. Component::BailOutChecker checker (target);
  34511. const Point<int> pos (target->globalPositionToRelative (lastFakeMouseMove));
  34512. const Time now (Time::getCurrentTime());
  34513. const MouseEvent me (getMainMouseSource(), pos, ModifierKeys::getCurrentModifiers(),
  34514. target, target, now, pos, now, 0, false);
  34515. if (me.mods.isAnyMouseButtonDown())
  34516. mouseListeners.callChecked (checker, &MouseListener::mouseDrag, me);
  34517. else
  34518. mouseListeners.callChecked (checker, &MouseListener::mouseMove, me);
  34519. }
  34520. }
  34521. }
  34522. void Desktop::resetTimer()
  34523. {
  34524. if (mouseListeners.size() == 0)
  34525. stopTimer();
  34526. else
  34527. startTimer (100);
  34528. lastFakeMouseMove = getMousePosition();
  34529. }
  34530. extern void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars);
  34531. void Desktop::setKioskModeComponent (Component* componentToUse, const bool allowMenusAndBars)
  34532. {
  34533. if (kioskModeComponent != componentToUse)
  34534. {
  34535. // agh! Don't delete a component without first stopping it being the kiosk comp
  34536. jassert (kioskModeComponent == 0 || kioskModeComponent->isValidComponent());
  34537. // agh! Don't remove a component from the desktop if it's the kiosk comp!
  34538. jassert (kioskModeComponent == 0 || kioskModeComponent->isOnDesktop());
  34539. if (kioskModeComponent->isValidComponent())
  34540. {
  34541. juce_setKioskComponent (kioskModeComponent, false, allowMenusAndBars);
  34542. kioskModeComponent->setBounds (kioskComponentOriginalBounds);
  34543. }
  34544. kioskModeComponent = componentToUse;
  34545. if (kioskModeComponent != 0)
  34546. {
  34547. jassert (kioskModeComponent->isValidComponent());
  34548. // Only components that are already on the desktop can be put into kiosk mode!
  34549. jassert (kioskModeComponent->isOnDesktop());
  34550. kioskComponentOriginalBounds = kioskModeComponent->getBounds();
  34551. juce_setKioskComponent (kioskModeComponent, true, allowMenusAndBars);
  34552. }
  34553. }
  34554. }
  34555. void Desktop::setOrientationsEnabled (const int newOrientations)
  34556. {
  34557. // Dodgy set of flags being passed here! Make sure you specify at least one permitted orientation.
  34558. jassert (newOrientations != 0 && (newOrientations & ~allOrientations) == 0);
  34559. allowedOrientations = newOrientations;
  34560. }
  34561. bool Desktop::isOrientationEnabled (const DisplayOrientation orientation) const throw()
  34562. {
  34563. // Make sure you only pass one valid flag in here...
  34564. jassert (orientation == upright || orientation == upsideDown || orientation == rotatedClockwise || orientation == rotatedAntiClockwise);
  34565. return (allowedOrientations & orientation) != 0;
  34566. }
  34567. END_JUCE_NAMESPACE
  34568. /*** End of inlined file: juce_Desktop.cpp ***/
  34569. /*** Start of inlined file: juce_ModalComponentManager.cpp ***/
  34570. BEGIN_JUCE_NAMESPACE
  34571. class ModalComponentManager::ModalItem : public ComponentListener
  34572. {
  34573. public:
  34574. ModalItem (Component* const comp, Callback* const callback)
  34575. : component (comp), returnValue (0), isActive (true), isDeleted (false)
  34576. {
  34577. if (callback != 0)
  34578. callbacks.add (callback);
  34579. jassert (comp != 0);
  34580. component->addComponentListener (this);
  34581. }
  34582. ~ModalItem()
  34583. {
  34584. if (! isDeleted)
  34585. component->removeComponentListener (this);
  34586. }
  34587. void componentBeingDeleted (Component&)
  34588. {
  34589. isDeleted = true;
  34590. cancel();
  34591. }
  34592. void componentVisibilityChanged (Component&)
  34593. {
  34594. if (! component->isShowing())
  34595. cancel();
  34596. }
  34597. void componentParentHierarchyChanged (Component&)
  34598. {
  34599. if (! component->isShowing())
  34600. cancel();
  34601. }
  34602. void cancel()
  34603. {
  34604. if (isActive)
  34605. {
  34606. isActive = false;
  34607. ModalComponentManager::getInstance()->triggerAsyncUpdate();
  34608. }
  34609. }
  34610. Component* component;
  34611. OwnedArray<Callback> callbacks;
  34612. int returnValue;
  34613. bool isActive, isDeleted;
  34614. private:
  34615. ModalItem (const ModalItem&);
  34616. ModalItem& operator= (const ModalItem&);
  34617. };
  34618. ModalComponentManager::ModalComponentManager()
  34619. {
  34620. }
  34621. ModalComponentManager::~ModalComponentManager()
  34622. {
  34623. clearSingletonInstance();
  34624. }
  34625. juce_ImplementSingleton_SingleThreaded (ModalComponentManager);
  34626. void ModalComponentManager::startModal (Component* component, Callback* callback)
  34627. {
  34628. if (component != 0)
  34629. stack.add (new ModalItem (component, callback));
  34630. }
  34631. void ModalComponentManager::attachCallback (Component* component, Callback* callback)
  34632. {
  34633. if (callback != 0)
  34634. {
  34635. ScopedPointer<Callback> callbackDeleter (callback);
  34636. for (int i = stack.size(); --i >= 0;)
  34637. {
  34638. ModalItem* const item = stack.getUnchecked(i);
  34639. if (item->component == component)
  34640. {
  34641. item->callbacks.add (callback);
  34642. callbackDeleter.release();
  34643. break;
  34644. }
  34645. }
  34646. }
  34647. }
  34648. void ModalComponentManager::endModal (Component* component)
  34649. {
  34650. for (int i = stack.size(); --i >= 0;)
  34651. {
  34652. ModalItem* const item = stack.getUnchecked(i);
  34653. if (item->component == component)
  34654. item->cancel();
  34655. }
  34656. }
  34657. void ModalComponentManager::endModal (Component* component, int returnValue)
  34658. {
  34659. for (int i = stack.size(); --i >= 0;)
  34660. {
  34661. ModalItem* const item = stack.getUnchecked(i);
  34662. if (item->component == component)
  34663. {
  34664. item->returnValue = returnValue;
  34665. item->cancel();
  34666. }
  34667. }
  34668. }
  34669. int ModalComponentManager::getNumModalComponents() const
  34670. {
  34671. int n = 0;
  34672. for (int i = 0; i < stack.size(); ++i)
  34673. if (stack.getUnchecked(i)->isActive)
  34674. ++n;
  34675. return n;
  34676. }
  34677. Component* ModalComponentManager::getModalComponent (const int index) const
  34678. {
  34679. int n = 0;
  34680. for (int i = stack.size(); --i >= 0;)
  34681. {
  34682. const ModalItem* const item = stack.getUnchecked(i);
  34683. if (item->isActive)
  34684. if (n++ == index)
  34685. return item->component;
  34686. }
  34687. return 0;
  34688. }
  34689. bool ModalComponentManager::isModal (Component* const comp) const
  34690. {
  34691. for (int i = stack.size(); --i >= 0;)
  34692. {
  34693. const ModalItem* const item = stack.getUnchecked(i);
  34694. if (item->isActive && item->component == comp)
  34695. return true;
  34696. }
  34697. return false;
  34698. }
  34699. bool ModalComponentManager::isFrontModalComponent (Component* const comp) const
  34700. {
  34701. return comp == getModalComponent (0);
  34702. }
  34703. void ModalComponentManager::handleAsyncUpdate()
  34704. {
  34705. for (int i = stack.size(); --i >= 0;)
  34706. {
  34707. const ModalItem* const item = stack.getUnchecked(i);
  34708. if (! item->isActive)
  34709. {
  34710. for (int j = item->callbacks.size(); --j >= 0;)
  34711. item->callbacks.getUnchecked(j)->modalStateFinished (item->returnValue);
  34712. stack.remove (i);
  34713. }
  34714. }
  34715. }
  34716. class ModalComponentManager::ReturnValueRetriever : public ModalComponentManager::Callback
  34717. {
  34718. public:
  34719. ReturnValueRetriever (int& value_, bool& finished_) : value (value_), finished (finished_) {}
  34720. ~ReturnValueRetriever() {}
  34721. void modalStateFinished (int returnValue)
  34722. {
  34723. finished = true;
  34724. value = returnValue;
  34725. }
  34726. private:
  34727. int& value;
  34728. bool& finished;
  34729. ReturnValueRetriever (const ReturnValueRetriever&);
  34730. ReturnValueRetriever& operator= (const ReturnValueRetriever&);
  34731. };
  34732. int ModalComponentManager::runEventLoopForCurrentComponent()
  34733. {
  34734. // This can only be run from the message thread!
  34735. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  34736. Component* currentlyModal = getModalComponent (0);
  34737. if (currentlyModal == 0)
  34738. return 0;
  34739. Component::SafePointer<Component> prevFocused (Component::getCurrentlyFocusedComponent());
  34740. int returnValue = 0;
  34741. bool finished = false;
  34742. attachCallback (currentlyModal, new ReturnValueRetriever (returnValue, finished));
  34743. JUCE_TRY
  34744. {
  34745. while (! finished)
  34746. {
  34747. if (! MessageManager::getInstance()->runDispatchLoopUntil (20))
  34748. break;
  34749. }
  34750. }
  34751. JUCE_CATCH_EXCEPTION
  34752. if (prevFocused != 0)
  34753. prevFocused->grabKeyboardFocus();
  34754. return returnValue;
  34755. }
  34756. END_JUCE_NAMESPACE
  34757. /*** End of inlined file: juce_ModalComponentManager.cpp ***/
  34758. /*** Start of inlined file: juce_ArrowButton.cpp ***/
  34759. BEGIN_JUCE_NAMESPACE
  34760. ArrowButton::ArrowButton (const String& name,
  34761. float arrowDirectionInRadians,
  34762. const Colour& arrowColour)
  34763. : Button (name),
  34764. colour (arrowColour)
  34765. {
  34766. path.lineTo (0.0f, 1.0f);
  34767. path.lineTo (1.0f, 0.5f);
  34768. path.closeSubPath();
  34769. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * arrowDirectionInRadians,
  34770. 0.5f, 0.5f));
  34771. setComponentEffect (&shadow);
  34772. buttonStateChanged();
  34773. }
  34774. ArrowButton::~ArrowButton()
  34775. {
  34776. }
  34777. void ArrowButton::paintButton (Graphics& g,
  34778. bool /*isMouseOverButton*/,
  34779. bool /*isButtonDown*/)
  34780. {
  34781. g.setColour (colour);
  34782. g.fillPath (path, path.getTransformToScaleToFit ((float) offset,
  34783. (float) offset,
  34784. (float) (getWidth() - 3),
  34785. (float) (getHeight() - 3),
  34786. false));
  34787. }
  34788. void ArrowButton::buttonStateChanged()
  34789. {
  34790. offset = (isDown()) ? 1 : 0;
  34791. shadow.setShadowProperties ((isDown()) ? 1.2f : 3.0f,
  34792. 0.3f, -1, 0);
  34793. }
  34794. END_JUCE_NAMESPACE
  34795. /*** End of inlined file: juce_ArrowButton.cpp ***/
  34796. /*** Start of inlined file: juce_Button.cpp ***/
  34797. BEGIN_JUCE_NAMESPACE
  34798. class Button::RepeatTimer : public Timer
  34799. {
  34800. public:
  34801. RepeatTimer (Button& owner_) : owner (owner_) {}
  34802. void timerCallback() { owner.repeatTimerCallback(); }
  34803. juce_UseDebuggingNewOperator
  34804. private:
  34805. Button& owner;
  34806. RepeatTimer (const RepeatTimer&);
  34807. RepeatTimer& operator= (const RepeatTimer&);
  34808. };
  34809. Button::Button (const String& name)
  34810. : Component (name),
  34811. text (name),
  34812. buttonPressTime (0),
  34813. lastTimeCallbackTime (0),
  34814. commandManagerToUse (0),
  34815. autoRepeatDelay (-1),
  34816. autoRepeatSpeed (0),
  34817. autoRepeatMinimumDelay (-1),
  34818. radioGroupId (0),
  34819. commandID (0),
  34820. connectedEdgeFlags (0),
  34821. buttonState (buttonNormal),
  34822. lastToggleState (false),
  34823. clickTogglesState (false),
  34824. needsToRelease (false),
  34825. needsRepainting (false),
  34826. isKeyDown (false),
  34827. triggerOnMouseDown (false),
  34828. generateTooltip (false)
  34829. {
  34830. setWantsKeyboardFocus (true);
  34831. isOn.addListener (this);
  34832. }
  34833. Button::~Button()
  34834. {
  34835. isOn.removeListener (this);
  34836. if (commandManagerToUse != 0)
  34837. commandManagerToUse->removeListener (this);
  34838. repeatTimer = 0;
  34839. clearShortcuts();
  34840. }
  34841. void Button::setButtonText (const String& newText)
  34842. {
  34843. if (text != newText)
  34844. {
  34845. text = newText;
  34846. repaint();
  34847. }
  34848. }
  34849. void Button::setTooltip (const String& newTooltip)
  34850. {
  34851. SettableTooltipClient::setTooltip (newTooltip);
  34852. generateTooltip = false;
  34853. }
  34854. const String Button::getTooltip()
  34855. {
  34856. if (generateTooltip && commandManagerToUse != 0 && commandID != 0)
  34857. {
  34858. String tt (commandManagerToUse->getDescriptionOfCommand (commandID));
  34859. Array <KeyPress> keyPresses (commandManagerToUse->getKeyMappings()->getKeyPressesAssignedToCommand (commandID));
  34860. for (int i = 0; i < keyPresses.size(); ++i)
  34861. {
  34862. const String key (keyPresses.getReference(i).getTextDescription());
  34863. tt << " [";
  34864. if (key.length() == 1)
  34865. tt << TRANS("shortcut") << ": '" << key << "']";
  34866. else
  34867. tt << key << ']';
  34868. }
  34869. return tt;
  34870. }
  34871. return SettableTooltipClient::getTooltip();
  34872. }
  34873. void Button::setConnectedEdges (const int connectedEdgeFlags_)
  34874. {
  34875. if (connectedEdgeFlags != connectedEdgeFlags_)
  34876. {
  34877. connectedEdgeFlags = connectedEdgeFlags_;
  34878. repaint();
  34879. }
  34880. }
  34881. void Button::setToggleState (const bool shouldBeOn,
  34882. const bool sendChangeNotification)
  34883. {
  34884. if (shouldBeOn != lastToggleState)
  34885. {
  34886. if (isOn != shouldBeOn) // this test means that if the value is void rather than explicitly set to
  34887. isOn = shouldBeOn; // false, it won't be changed unless the required value is true.
  34888. lastToggleState = shouldBeOn;
  34889. repaint();
  34890. if (sendChangeNotification)
  34891. {
  34892. Component::SafePointer<Component> deletionWatcher (this);
  34893. sendClickMessage (ModifierKeys());
  34894. if (deletionWatcher == 0)
  34895. return;
  34896. }
  34897. if (lastToggleState)
  34898. turnOffOtherButtonsInGroup (sendChangeNotification);
  34899. }
  34900. }
  34901. void Button::setClickingTogglesState (const bool shouldToggle) throw()
  34902. {
  34903. clickTogglesState = shouldToggle;
  34904. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  34905. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  34906. // it is that this button represents, and the button will update its state to reflect this
  34907. // in the applicationCommandListChanged() method.
  34908. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  34909. }
  34910. bool Button::getClickingTogglesState() const throw()
  34911. {
  34912. return clickTogglesState;
  34913. }
  34914. void Button::valueChanged (Value& value)
  34915. {
  34916. if (value.refersToSameSourceAs (isOn))
  34917. setToggleState (isOn.getValue(), true);
  34918. }
  34919. void Button::setRadioGroupId (const int newGroupId)
  34920. {
  34921. if (radioGroupId != newGroupId)
  34922. {
  34923. radioGroupId = newGroupId;
  34924. if (lastToggleState)
  34925. turnOffOtherButtonsInGroup (true);
  34926. }
  34927. }
  34928. void Button::turnOffOtherButtonsInGroup (const bool sendChangeNotification)
  34929. {
  34930. Component* const p = getParentComponent();
  34931. if (p != 0 && radioGroupId != 0)
  34932. {
  34933. Component::SafePointer<Component> deletionWatcher (this);
  34934. for (int i = p->getNumChildComponents(); --i >= 0;)
  34935. {
  34936. Component* const c = p->getChildComponent (i);
  34937. if (c != this)
  34938. {
  34939. Button* const b = dynamic_cast <Button*> (c);
  34940. if (b != 0 && b->getRadioGroupId() == radioGroupId)
  34941. {
  34942. b->setToggleState (false, sendChangeNotification);
  34943. if (deletionWatcher == 0)
  34944. return;
  34945. }
  34946. }
  34947. }
  34948. }
  34949. }
  34950. void Button::enablementChanged()
  34951. {
  34952. updateState (0);
  34953. repaint();
  34954. }
  34955. Button::ButtonState Button::updateState (const MouseEvent* const e)
  34956. {
  34957. ButtonState state = buttonNormal;
  34958. if (isEnabled() && isVisible() && ! isCurrentlyBlockedByAnotherModalComponent())
  34959. {
  34960. Point<int> mousePos;
  34961. if (e == 0)
  34962. mousePos = getMouseXYRelative();
  34963. else
  34964. mousePos = e->getEventRelativeTo (this).getPosition();
  34965. const bool over = reallyContains (mousePos.getX(), mousePos.getY(), true);
  34966. const bool down = isMouseButtonDown();
  34967. if ((down && (over || (triggerOnMouseDown && buttonState == buttonDown))) || isKeyDown)
  34968. state = buttonDown;
  34969. else if (over)
  34970. state = buttonOver;
  34971. }
  34972. setState (state);
  34973. return state;
  34974. }
  34975. void Button::setState (const ButtonState newState)
  34976. {
  34977. if (buttonState != newState)
  34978. {
  34979. buttonState = newState;
  34980. repaint();
  34981. if (buttonState == buttonDown)
  34982. {
  34983. buttonPressTime = Time::getApproximateMillisecondCounter();
  34984. lastTimeCallbackTime = buttonPressTime;
  34985. }
  34986. sendStateMessage();
  34987. }
  34988. }
  34989. bool Button::isDown() const throw()
  34990. {
  34991. return buttonState == buttonDown;
  34992. }
  34993. bool Button::isOver() const throw()
  34994. {
  34995. return buttonState != buttonNormal;
  34996. }
  34997. void Button::buttonStateChanged()
  34998. {
  34999. }
  35000. uint32 Button::getMillisecondsSinceButtonDown() const throw()
  35001. {
  35002. const uint32 now = Time::getApproximateMillisecondCounter();
  35003. return now > buttonPressTime ? now - buttonPressTime : 0;
  35004. }
  35005. void Button::setTriggeredOnMouseDown (const bool isTriggeredOnMouseDown) throw()
  35006. {
  35007. triggerOnMouseDown = isTriggeredOnMouseDown;
  35008. }
  35009. void Button::clicked()
  35010. {
  35011. }
  35012. void Button::clicked (const ModifierKeys& /*modifiers*/)
  35013. {
  35014. clicked();
  35015. }
  35016. static const int clickMessageId = 0x2f3f4f99;
  35017. void Button::triggerClick()
  35018. {
  35019. postCommandMessage (clickMessageId);
  35020. }
  35021. void Button::internalClickCallback (const ModifierKeys& modifiers)
  35022. {
  35023. if (clickTogglesState)
  35024. setToggleState ((radioGroupId != 0) || ! lastToggleState, false);
  35025. sendClickMessage (modifiers);
  35026. }
  35027. void Button::flashButtonState()
  35028. {
  35029. if (isEnabled())
  35030. {
  35031. needsToRelease = true;
  35032. setState (buttonDown);
  35033. getRepeatTimer().startTimer (100);
  35034. }
  35035. }
  35036. void Button::handleCommandMessage (int commandId)
  35037. {
  35038. if (commandId == clickMessageId)
  35039. {
  35040. if (isEnabled())
  35041. {
  35042. flashButtonState();
  35043. internalClickCallback (ModifierKeys::getCurrentModifiers());
  35044. }
  35045. }
  35046. else
  35047. {
  35048. Component::handleCommandMessage (commandId);
  35049. }
  35050. }
  35051. void Button::addButtonListener (Listener* const newListener)
  35052. {
  35053. buttonListeners.add (newListener);
  35054. }
  35055. void Button::removeButtonListener (Listener* const listener)
  35056. {
  35057. buttonListeners.remove (listener);
  35058. }
  35059. void Button::sendClickMessage (const ModifierKeys& modifiers)
  35060. {
  35061. Component::BailOutChecker checker (this);
  35062. if (commandManagerToUse != 0 && commandID != 0)
  35063. {
  35064. ApplicationCommandTarget::InvocationInfo info (commandID);
  35065. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromButton;
  35066. info.originatingComponent = this;
  35067. commandManagerToUse->invoke (info, true);
  35068. }
  35069. clicked (modifiers);
  35070. if (! checker.shouldBailOut())
  35071. buttonListeners.callChecked (checker, &ButtonListener::buttonClicked, this); // (can't use Button::Listener due to idiotic VC2005 bug)
  35072. }
  35073. void Button::sendStateMessage()
  35074. {
  35075. Component::BailOutChecker checker (this);
  35076. buttonStateChanged();
  35077. if (! checker.shouldBailOut())
  35078. buttonListeners.callChecked (checker, &ButtonListener::buttonStateChanged, this);
  35079. }
  35080. void Button::paint (Graphics& g)
  35081. {
  35082. if (needsToRelease && isEnabled())
  35083. {
  35084. needsToRelease = false;
  35085. needsRepainting = true;
  35086. }
  35087. paintButton (g, isOver(), isDown());
  35088. }
  35089. void Button::mouseEnter (const MouseEvent& e)
  35090. {
  35091. updateState (&e);
  35092. }
  35093. void Button::mouseExit (const MouseEvent& e)
  35094. {
  35095. updateState (&e);
  35096. }
  35097. void Button::mouseDown (const MouseEvent& e)
  35098. {
  35099. updateState (&e);
  35100. if (isDown())
  35101. {
  35102. if (autoRepeatDelay >= 0)
  35103. getRepeatTimer().startTimer (autoRepeatDelay);
  35104. if (triggerOnMouseDown)
  35105. internalClickCallback (e.mods);
  35106. }
  35107. }
  35108. void Button::mouseUp (const MouseEvent& e)
  35109. {
  35110. const bool wasDown = isDown();
  35111. updateState (&e);
  35112. if (wasDown && isOver() && ! triggerOnMouseDown)
  35113. internalClickCallback (e.mods);
  35114. }
  35115. void Button::mouseDrag (const MouseEvent& e)
  35116. {
  35117. const ButtonState oldState = buttonState;
  35118. updateState (&e);
  35119. if (autoRepeatDelay >= 0 && buttonState != oldState && isDown())
  35120. getRepeatTimer().startTimer (autoRepeatSpeed);
  35121. }
  35122. void Button::focusGained (FocusChangeType)
  35123. {
  35124. updateState (0);
  35125. repaint();
  35126. }
  35127. void Button::focusLost (FocusChangeType)
  35128. {
  35129. updateState (0);
  35130. repaint();
  35131. }
  35132. void Button::setVisible (bool shouldBeVisible)
  35133. {
  35134. if (shouldBeVisible != isVisible())
  35135. {
  35136. Component::setVisible (shouldBeVisible);
  35137. if (! shouldBeVisible)
  35138. needsToRelease = false;
  35139. updateState (0);
  35140. }
  35141. else
  35142. {
  35143. Component::setVisible (shouldBeVisible);
  35144. }
  35145. }
  35146. void Button::parentHierarchyChanged()
  35147. {
  35148. Component* const newKeySource = (shortcuts.size() == 0) ? 0 : getTopLevelComponent();
  35149. if (newKeySource != keySource.getComponent())
  35150. {
  35151. if (keySource != 0)
  35152. keySource->removeKeyListener (this);
  35153. keySource = newKeySource;
  35154. if (keySource != 0)
  35155. keySource->addKeyListener (this);
  35156. }
  35157. }
  35158. void Button::setCommandToTrigger (ApplicationCommandManager* const commandManagerToUse_,
  35159. const int commandID_,
  35160. const bool generateTooltip_)
  35161. {
  35162. commandID = commandID_;
  35163. generateTooltip = generateTooltip_;
  35164. if (commandManagerToUse != commandManagerToUse_)
  35165. {
  35166. if (commandManagerToUse != 0)
  35167. commandManagerToUse->removeListener (this);
  35168. commandManagerToUse = commandManagerToUse_;
  35169. if (commandManagerToUse != 0)
  35170. commandManagerToUse->addListener (this);
  35171. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  35172. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  35173. // it is that this button represents, and the button will update its state to reflect this
  35174. // in the applicationCommandListChanged() method.
  35175. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  35176. }
  35177. if (commandManagerToUse != 0)
  35178. applicationCommandListChanged();
  35179. else
  35180. setEnabled (true);
  35181. }
  35182. void Button::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  35183. {
  35184. if (info.commandID == commandID
  35185. && (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) == 0)
  35186. {
  35187. flashButtonState();
  35188. }
  35189. }
  35190. void Button::applicationCommandListChanged()
  35191. {
  35192. if (commandManagerToUse != 0)
  35193. {
  35194. ApplicationCommandInfo info (0);
  35195. ApplicationCommandTarget* const target = commandManagerToUse->getTargetForCommand (commandID, info);
  35196. setEnabled (target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0);
  35197. if (target != 0)
  35198. setToggleState ((info.flags & ApplicationCommandInfo::isTicked) != 0, false);
  35199. }
  35200. }
  35201. void Button::addShortcut (const KeyPress& key)
  35202. {
  35203. if (key.isValid())
  35204. {
  35205. jassert (! isRegisteredForShortcut (key)); // already registered!
  35206. shortcuts.add (key);
  35207. parentHierarchyChanged();
  35208. }
  35209. }
  35210. void Button::clearShortcuts()
  35211. {
  35212. shortcuts.clear();
  35213. parentHierarchyChanged();
  35214. }
  35215. bool Button::isShortcutPressed() const
  35216. {
  35217. if (! isCurrentlyBlockedByAnotherModalComponent())
  35218. {
  35219. for (int i = shortcuts.size(); --i >= 0;)
  35220. if (shortcuts.getReference(i).isCurrentlyDown())
  35221. return true;
  35222. }
  35223. return false;
  35224. }
  35225. bool Button::isRegisteredForShortcut (const KeyPress& key) const
  35226. {
  35227. for (int i = shortcuts.size(); --i >= 0;)
  35228. if (key == shortcuts.getReference(i))
  35229. return true;
  35230. return false;
  35231. }
  35232. bool Button::keyStateChanged (const bool, Component*)
  35233. {
  35234. if (! isEnabled())
  35235. return false;
  35236. const bool wasDown = isKeyDown;
  35237. isKeyDown = isShortcutPressed();
  35238. if (autoRepeatDelay >= 0 && (isKeyDown && ! wasDown))
  35239. getRepeatTimer().startTimer (autoRepeatDelay);
  35240. updateState (0);
  35241. if (isEnabled() && wasDown && ! isKeyDown)
  35242. {
  35243. internalClickCallback (ModifierKeys::getCurrentModifiers());
  35244. // (return immediately - this button may now have been deleted)
  35245. return true;
  35246. }
  35247. return wasDown || isKeyDown;
  35248. }
  35249. bool Button::keyPressed (const KeyPress&, Component*)
  35250. {
  35251. // returning true will avoid forwarding events for keys that we're using as shortcuts
  35252. return isShortcutPressed();
  35253. }
  35254. bool Button::keyPressed (const KeyPress& key)
  35255. {
  35256. if (isEnabled() && key.isKeyCode (KeyPress::returnKey))
  35257. {
  35258. triggerClick();
  35259. return true;
  35260. }
  35261. return false;
  35262. }
  35263. void Button::setRepeatSpeed (const int initialDelayMillisecs,
  35264. const int repeatMillisecs,
  35265. const int minimumDelayInMillisecs) throw()
  35266. {
  35267. autoRepeatDelay = initialDelayMillisecs;
  35268. autoRepeatSpeed = repeatMillisecs;
  35269. autoRepeatMinimumDelay = jmin (autoRepeatSpeed, minimumDelayInMillisecs);
  35270. }
  35271. void Button::repeatTimerCallback()
  35272. {
  35273. if (needsRepainting)
  35274. {
  35275. getRepeatTimer().stopTimer();
  35276. updateState (0);
  35277. needsRepainting = false;
  35278. }
  35279. else if (autoRepeatSpeed > 0 && (isKeyDown || (updateState (0) == buttonDown)))
  35280. {
  35281. int repeatSpeed = autoRepeatSpeed;
  35282. if (autoRepeatMinimumDelay >= 0)
  35283. {
  35284. double timeHeldDown = jmin (1.0, getMillisecondsSinceButtonDown() / 4000.0);
  35285. timeHeldDown *= timeHeldDown;
  35286. repeatSpeed = repeatSpeed + (int) (timeHeldDown * (autoRepeatMinimumDelay - repeatSpeed));
  35287. }
  35288. repeatSpeed = jmax (1, repeatSpeed);
  35289. getRepeatTimer().startTimer (repeatSpeed);
  35290. const uint32 now = Time::getApproximateMillisecondCounter();
  35291. const int numTimesToCallback = (now > lastTimeCallbackTime) ? jmax (1, (int) (now - lastTimeCallbackTime) / repeatSpeed) : 1;
  35292. lastTimeCallbackTime = now;
  35293. Component::SafePointer<Component> deletionWatcher (this);
  35294. for (int i = numTimesToCallback; --i >= 0;)
  35295. {
  35296. internalClickCallback (ModifierKeys::getCurrentModifiers());
  35297. if (deletionWatcher == 0 || ! isDown())
  35298. return;
  35299. }
  35300. }
  35301. else if (! needsToRelease)
  35302. {
  35303. getRepeatTimer().stopTimer();
  35304. }
  35305. }
  35306. Button::RepeatTimer& Button::getRepeatTimer()
  35307. {
  35308. if (repeatTimer == 0)
  35309. repeatTimer = new RepeatTimer (*this);
  35310. return *repeatTimer;
  35311. }
  35312. END_JUCE_NAMESPACE
  35313. /*** End of inlined file: juce_Button.cpp ***/
  35314. /*** Start of inlined file: juce_DrawableButton.cpp ***/
  35315. BEGIN_JUCE_NAMESPACE
  35316. DrawableButton::DrawableButton (const String& name,
  35317. const DrawableButton::ButtonStyle buttonStyle)
  35318. : Button (name),
  35319. style (buttonStyle),
  35320. edgeIndent (3)
  35321. {
  35322. if (buttonStyle == ImageOnButtonBackground)
  35323. {
  35324. backgroundOff = Colour (0xffbbbbff);
  35325. backgroundOn = Colour (0xff3333ff);
  35326. }
  35327. else
  35328. {
  35329. backgroundOff = Colours::transparentBlack;
  35330. backgroundOn = Colour (0xaabbbbff);
  35331. }
  35332. }
  35333. DrawableButton::~DrawableButton()
  35334. {
  35335. deleteImages();
  35336. }
  35337. void DrawableButton::deleteImages()
  35338. {
  35339. }
  35340. void DrawableButton::setImages (const Drawable* normal,
  35341. const Drawable* over,
  35342. const Drawable* down,
  35343. const Drawable* disabled,
  35344. const Drawable* normalOn,
  35345. const Drawable* overOn,
  35346. const Drawable* downOn,
  35347. const Drawable* disabledOn)
  35348. {
  35349. deleteImages();
  35350. jassert (normal != 0); // you really need to give it at least a normal image..
  35351. if (normal != 0)
  35352. normalImage = normal->createCopy();
  35353. if (over != 0)
  35354. overImage = over->createCopy();
  35355. if (down != 0)
  35356. downImage = down->createCopy();
  35357. if (disabled != 0)
  35358. disabledImage = disabled->createCopy();
  35359. if (normalOn != 0)
  35360. normalImageOn = normalOn->createCopy();
  35361. if (overOn != 0)
  35362. overImageOn = overOn->createCopy();
  35363. if (downOn != 0)
  35364. downImageOn = downOn->createCopy();
  35365. if (disabledOn != 0)
  35366. disabledImageOn = disabledOn->createCopy();
  35367. repaint();
  35368. }
  35369. void DrawableButton::setButtonStyle (const DrawableButton::ButtonStyle newStyle)
  35370. {
  35371. if (style != newStyle)
  35372. {
  35373. style = newStyle;
  35374. repaint();
  35375. }
  35376. }
  35377. void DrawableButton::setBackgroundColours (const Colour& toggledOffColour,
  35378. const Colour& toggledOnColour)
  35379. {
  35380. if (backgroundOff != toggledOffColour
  35381. || backgroundOn != toggledOnColour)
  35382. {
  35383. backgroundOff = toggledOffColour;
  35384. backgroundOn = toggledOnColour;
  35385. repaint();
  35386. }
  35387. }
  35388. const Colour& DrawableButton::getBackgroundColour() const throw()
  35389. {
  35390. return getToggleState() ? backgroundOn
  35391. : backgroundOff;
  35392. }
  35393. void DrawableButton::setEdgeIndent (const int numPixelsIndent)
  35394. {
  35395. edgeIndent = numPixelsIndent;
  35396. repaint();
  35397. }
  35398. void DrawableButton::paintButton (Graphics& g,
  35399. bool isMouseOverButton,
  35400. bool isButtonDown)
  35401. {
  35402. Rectangle<int> imageSpace;
  35403. if (style == ImageOnButtonBackground)
  35404. {
  35405. const int insetX = getWidth() / 4;
  35406. const int insetY = getHeight() / 4;
  35407. imageSpace.setBounds (insetX, insetY, getWidth() - insetX * 2, getHeight() - insetY * 2);
  35408. getLookAndFeel().drawButtonBackground (g, *this,
  35409. getBackgroundColour(),
  35410. isMouseOverButton,
  35411. isButtonDown);
  35412. }
  35413. else
  35414. {
  35415. g.fillAll (getBackgroundColour());
  35416. const int textH = (style == ImageAboveTextLabel)
  35417. ? jmin (16, proportionOfHeight (0.25f))
  35418. : 0;
  35419. const int indentX = jmin (edgeIndent, proportionOfWidth (0.3f));
  35420. const int indentY = jmin (edgeIndent, proportionOfHeight (0.3f));
  35421. imageSpace.setBounds (indentX, indentY,
  35422. getWidth() - indentX * 2,
  35423. getHeight() - indentY * 2 - textH);
  35424. if (textH > 0)
  35425. {
  35426. g.setFont ((float) textH);
  35427. g.setColour (findColour (DrawableButton::textColourId)
  35428. .withMultipliedAlpha (isEnabled() ? 1.0f : 0.4f));
  35429. g.drawFittedText (getButtonText(),
  35430. 2, getHeight() - textH - 1,
  35431. getWidth() - 4, textH,
  35432. Justification::centred, 1);
  35433. }
  35434. }
  35435. g.setImageResamplingQuality (Graphics::mediumResamplingQuality);
  35436. g.setOpacity (1.0f);
  35437. const Drawable* imageToDraw = 0;
  35438. if (isEnabled())
  35439. {
  35440. imageToDraw = getCurrentImage();
  35441. }
  35442. else
  35443. {
  35444. imageToDraw = getToggleState() ? disabledImageOn
  35445. : disabledImage;
  35446. if (imageToDraw == 0)
  35447. {
  35448. g.setOpacity (0.4f);
  35449. imageToDraw = getNormalImage();
  35450. }
  35451. }
  35452. if (imageToDraw != 0)
  35453. {
  35454. if (style == ImageRaw)
  35455. imageToDraw->draw (g, 1.0f);
  35456. else
  35457. imageToDraw->drawWithin (g, imageSpace.toFloat(), RectanglePlacement::centred, 1.0f);
  35458. }
  35459. }
  35460. const Drawable* DrawableButton::getCurrentImage() const throw()
  35461. {
  35462. if (isDown())
  35463. return getDownImage();
  35464. if (isOver())
  35465. return getOverImage();
  35466. return getNormalImage();
  35467. }
  35468. const Drawable* DrawableButton::getNormalImage() const throw()
  35469. {
  35470. return (getToggleState() && normalImageOn != 0) ? normalImageOn
  35471. : normalImage;
  35472. }
  35473. const Drawable* DrawableButton::getOverImage() const throw()
  35474. {
  35475. const Drawable* d = normalImage;
  35476. if (getToggleState())
  35477. {
  35478. if (overImageOn != 0)
  35479. d = overImageOn;
  35480. else if (normalImageOn != 0)
  35481. d = normalImageOn;
  35482. else if (overImage != 0)
  35483. d = overImage;
  35484. }
  35485. else
  35486. {
  35487. if (overImage != 0)
  35488. d = overImage;
  35489. }
  35490. return d;
  35491. }
  35492. const Drawable* DrawableButton::getDownImage() const throw()
  35493. {
  35494. const Drawable* d = normalImage;
  35495. if (getToggleState())
  35496. {
  35497. if (downImageOn != 0)
  35498. d = downImageOn;
  35499. else if (overImageOn != 0)
  35500. d = overImageOn;
  35501. else if (normalImageOn != 0)
  35502. d = normalImageOn;
  35503. else if (downImage != 0)
  35504. d = downImage;
  35505. else
  35506. d = getOverImage();
  35507. }
  35508. else
  35509. {
  35510. if (downImage != 0)
  35511. d = downImage;
  35512. else
  35513. d = getOverImage();
  35514. }
  35515. return d;
  35516. }
  35517. END_JUCE_NAMESPACE
  35518. /*** End of inlined file: juce_DrawableButton.cpp ***/
  35519. /*** Start of inlined file: juce_HyperlinkButton.cpp ***/
  35520. BEGIN_JUCE_NAMESPACE
  35521. HyperlinkButton::HyperlinkButton (const String& linkText,
  35522. const URL& linkURL)
  35523. : Button (linkText),
  35524. url (linkURL),
  35525. font (14.0f, Font::underlined),
  35526. resizeFont (true),
  35527. justification (Justification::centred)
  35528. {
  35529. setMouseCursor (MouseCursor::PointingHandCursor);
  35530. setTooltip (linkURL.toString (false));
  35531. }
  35532. HyperlinkButton::~HyperlinkButton()
  35533. {
  35534. }
  35535. void HyperlinkButton::setFont (const Font& newFont,
  35536. const bool resizeToMatchComponentHeight,
  35537. const Justification& justificationType)
  35538. {
  35539. font = newFont;
  35540. resizeFont = resizeToMatchComponentHeight;
  35541. justification = justificationType;
  35542. repaint();
  35543. }
  35544. void HyperlinkButton::setURL (const URL& newURL) throw()
  35545. {
  35546. url = newURL;
  35547. setTooltip (newURL.toString (false));
  35548. }
  35549. const Font HyperlinkButton::getFontToUse() const
  35550. {
  35551. Font f (font);
  35552. if (resizeFont)
  35553. f.setHeight (getHeight() * 0.7f);
  35554. return f;
  35555. }
  35556. void HyperlinkButton::changeWidthToFitText()
  35557. {
  35558. setSize (getFontToUse().getStringWidth (getName()) + 6, getHeight());
  35559. }
  35560. void HyperlinkButton::colourChanged()
  35561. {
  35562. repaint();
  35563. }
  35564. void HyperlinkButton::clicked()
  35565. {
  35566. if (url.isWellFormed())
  35567. url.launchInDefaultBrowser();
  35568. }
  35569. void HyperlinkButton::paintButton (Graphics& g,
  35570. bool isMouseOverButton,
  35571. bool isButtonDown)
  35572. {
  35573. const Colour textColour (findColour (textColourId));
  35574. if (isEnabled())
  35575. g.setColour ((isMouseOverButton) ? textColour.darker ((isButtonDown) ? 1.3f : 0.4f)
  35576. : textColour);
  35577. else
  35578. g.setColour (textColour.withMultipliedAlpha (0.4f));
  35579. g.setFont (getFontToUse());
  35580. g.drawText (getButtonText(),
  35581. 2, 0, getWidth() - 2, getHeight(),
  35582. justification.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  35583. true);
  35584. }
  35585. END_JUCE_NAMESPACE
  35586. /*** End of inlined file: juce_HyperlinkButton.cpp ***/
  35587. /*** Start of inlined file: juce_ImageButton.cpp ***/
  35588. BEGIN_JUCE_NAMESPACE
  35589. ImageButton::ImageButton (const String& text_)
  35590. : Button (text_),
  35591. scaleImageToFit (true),
  35592. preserveProportions (true),
  35593. alphaThreshold (0),
  35594. imageX (0),
  35595. imageY (0),
  35596. imageW (0),
  35597. imageH (0),
  35598. normalImage (0),
  35599. overImage (0),
  35600. downImage (0)
  35601. {
  35602. }
  35603. ImageButton::~ImageButton()
  35604. {
  35605. }
  35606. void ImageButton::setImages (const bool resizeButtonNowToFitThisImage,
  35607. const bool rescaleImagesWhenButtonSizeChanges,
  35608. const bool preserveImageProportions,
  35609. const Image& normalImage_,
  35610. const float imageOpacityWhenNormal,
  35611. const Colour& overlayColourWhenNormal,
  35612. const Image& overImage_,
  35613. const float imageOpacityWhenOver,
  35614. const Colour& overlayColourWhenOver,
  35615. const Image& downImage_,
  35616. const float imageOpacityWhenDown,
  35617. const Colour& overlayColourWhenDown,
  35618. const float hitTestAlphaThreshold)
  35619. {
  35620. normalImage = normalImage_;
  35621. overImage = overImage_;
  35622. downImage = downImage_;
  35623. if (resizeButtonNowToFitThisImage && normalImage.isValid())
  35624. {
  35625. imageW = normalImage.getWidth();
  35626. imageH = normalImage.getHeight();
  35627. setSize (imageW, imageH);
  35628. }
  35629. scaleImageToFit = rescaleImagesWhenButtonSizeChanges;
  35630. preserveProportions = preserveImageProportions;
  35631. normalOpacity = imageOpacityWhenNormal;
  35632. normalOverlay = overlayColourWhenNormal;
  35633. overOpacity = imageOpacityWhenOver;
  35634. overOverlay = overlayColourWhenOver;
  35635. downOpacity = imageOpacityWhenDown;
  35636. downOverlay = overlayColourWhenDown;
  35637. alphaThreshold = (unsigned char) jlimit (0, 0xff, roundToInt (255.0f * hitTestAlphaThreshold));
  35638. repaint();
  35639. }
  35640. const Image ImageButton::getCurrentImage() const
  35641. {
  35642. if (isDown() || getToggleState())
  35643. return getDownImage();
  35644. if (isOver())
  35645. return getOverImage();
  35646. return getNormalImage();
  35647. }
  35648. const Image ImageButton::getNormalImage() const
  35649. {
  35650. return normalImage;
  35651. }
  35652. const Image ImageButton::getOverImage() const
  35653. {
  35654. return overImage.isValid() ? overImage
  35655. : normalImage;
  35656. }
  35657. const Image ImageButton::getDownImage() const
  35658. {
  35659. return downImage.isValid() ? downImage
  35660. : getOverImage();
  35661. }
  35662. void ImageButton::paintButton (Graphics& g,
  35663. bool isMouseOverButton,
  35664. bool isButtonDown)
  35665. {
  35666. if (! isEnabled())
  35667. {
  35668. isMouseOverButton = false;
  35669. isButtonDown = false;
  35670. }
  35671. Image im (getCurrentImage());
  35672. if (im.isValid())
  35673. {
  35674. const int iw = im.getWidth();
  35675. const int ih = im.getHeight();
  35676. imageW = getWidth();
  35677. imageH = getHeight();
  35678. imageX = (imageW - iw) >> 1;
  35679. imageY = (imageH - ih) >> 1;
  35680. if (scaleImageToFit)
  35681. {
  35682. if (preserveProportions)
  35683. {
  35684. int newW, newH;
  35685. const float imRatio = ih / (float)iw;
  35686. const float destRatio = imageH / (float)imageW;
  35687. if (imRatio > destRatio)
  35688. {
  35689. newW = roundToInt (imageH / imRatio);
  35690. newH = imageH;
  35691. }
  35692. else
  35693. {
  35694. newW = imageW;
  35695. newH = roundToInt (imageW * imRatio);
  35696. }
  35697. imageX = (imageW - newW) / 2;
  35698. imageY = (imageH - newH) / 2;
  35699. imageW = newW;
  35700. imageH = newH;
  35701. }
  35702. else
  35703. {
  35704. imageX = 0;
  35705. imageY = 0;
  35706. }
  35707. }
  35708. if (! scaleImageToFit)
  35709. {
  35710. imageW = iw;
  35711. imageH = ih;
  35712. }
  35713. getLookAndFeel().drawImageButton (g, &im, imageX, imageY, imageW, imageH,
  35714. isButtonDown ? downOverlay
  35715. : (isMouseOverButton ? overOverlay
  35716. : normalOverlay),
  35717. isButtonDown ? downOpacity
  35718. : (isMouseOverButton ? overOpacity
  35719. : normalOpacity),
  35720. *this);
  35721. }
  35722. }
  35723. bool ImageButton::hitTest (int x, int y)
  35724. {
  35725. if (alphaThreshold == 0)
  35726. return true;
  35727. Image im (getCurrentImage());
  35728. return im.isNull() || (imageW > 0 && imageH > 0
  35729. && alphaThreshold < im.getPixelAt (((x - imageX) * im.getWidth()) / imageW,
  35730. ((y - imageY) * im.getHeight()) / imageH).getAlpha());
  35731. }
  35732. END_JUCE_NAMESPACE
  35733. /*** End of inlined file: juce_ImageButton.cpp ***/
  35734. /*** Start of inlined file: juce_ShapeButton.cpp ***/
  35735. BEGIN_JUCE_NAMESPACE
  35736. ShapeButton::ShapeButton (const String& text_,
  35737. const Colour& normalColour_,
  35738. const Colour& overColour_,
  35739. const Colour& downColour_)
  35740. : Button (text_),
  35741. normalColour (normalColour_),
  35742. overColour (overColour_),
  35743. downColour (downColour_),
  35744. maintainShapeProportions (false),
  35745. outlineWidth (0.0f)
  35746. {
  35747. }
  35748. ShapeButton::~ShapeButton()
  35749. {
  35750. }
  35751. void ShapeButton::setColours (const Colour& newNormalColour,
  35752. const Colour& newOverColour,
  35753. const Colour& newDownColour)
  35754. {
  35755. normalColour = newNormalColour;
  35756. overColour = newOverColour;
  35757. downColour = newDownColour;
  35758. }
  35759. void ShapeButton::setOutline (const Colour& newOutlineColour,
  35760. const float newOutlineWidth)
  35761. {
  35762. outlineColour = newOutlineColour;
  35763. outlineWidth = newOutlineWidth;
  35764. }
  35765. void ShapeButton::setShape (const Path& newShape,
  35766. const bool resizeNowToFitThisShape,
  35767. const bool maintainShapeProportions_,
  35768. const bool hasShadow)
  35769. {
  35770. shape = newShape;
  35771. maintainShapeProportions = maintainShapeProportions_;
  35772. shadow.setShadowProperties (3.0f, 0.5f, 0, 0);
  35773. setComponentEffect ((hasShadow) ? &shadow : 0);
  35774. if (resizeNowToFitThisShape)
  35775. {
  35776. Rectangle<float> bounds (shape.getBounds());
  35777. if (hasShadow)
  35778. bounds.expand (4.0f, 4.0f);
  35779. shape.applyTransform (AffineTransform::translation (-bounds.getX(), -bounds.getY()));
  35780. setSize (1 + (int) (bounds.getWidth() + outlineWidth),
  35781. 1 + (int) (bounds.getHeight() + outlineWidth));
  35782. }
  35783. }
  35784. void ShapeButton::paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  35785. {
  35786. if (! isEnabled())
  35787. {
  35788. isMouseOverButton = false;
  35789. isButtonDown = false;
  35790. }
  35791. g.setColour ((isButtonDown) ? downColour
  35792. : (isMouseOverButton) ? overColour
  35793. : normalColour);
  35794. int w = getWidth();
  35795. int h = getHeight();
  35796. if (getComponentEffect() != 0)
  35797. {
  35798. w -= 4;
  35799. h -= 4;
  35800. }
  35801. const float offset = (outlineWidth * 0.5f) + (isButtonDown ? 1.5f : 0.0f);
  35802. const AffineTransform trans (shape.getTransformToScaleToFit (offset, offset,
  35803. w - offset - outlineWidth,
  35804. h - offset - outlineWidth,
  35805. maintainShapeProportions));
  35806. g.fillPath (shape, trans);
  35807. if (outlineWidth > 0.0f)
  35808. {
  35809. g.setColour (outlineColour);
  35810. g.strokePath (shape, PathStrokeType (outlineWidth), trans);
  35811. }
  35812. }
  35813. END_JUCE_NAMESPACE
  35814. /*** End of inlined file: juce_ShapeButton.cpp ***/
  35815. /*** Start of inlined file: juce_TextButton.cpp ***/
  35816. BEGIN_JUCE_NAMESPACE
  35817. TextButton::TextButton (const String& name,
  35818. const String& toolTip)
  35819. : Button (name)
  35820. {
  35821. setTooltip (toolTip);
  35822. }
  35823. TextButton::~TextButton()
  35824. {
  35825. }
  35826. void TextButton::paintButton (Graphics& g,
  35827. bool isMouseOverButton,
  35828. bool isButtonDown)
  35829. {
  35830. getLookAndFeel().drawButtonBackground (g, *this,
  35831. findColour (getToggleState() ? buttonOnColourId
  35832. : buttonColourId),
  35833. isMouseOverButton,
  35834. isButtonDown);
  35835. getLookAndFeel().drawButtonText (g, *this,
  35836. isMouseOverButton,
  35837. isButtonDown);
  35838. }
  35839. void TextButton::colourChanged()
  35840. {
  35841. repaint();
  35842. }
  35843. const Font TextButton::getFont()
  35844. {
  35845. return Font (jmin (15.0f, getHeight() * 0.6f));
  35846. }
  35847. void TextButton::changeWidthToFitText (const int newHeight)
  35848. {
  35849. if (newHeight >= 0)
  35850. setSize (jmax (1, getWidth()), newHeight);
  35851. setSize (getFont().getStringWidth (getButtonText()) + getHeight(),
  35852. getHeight());
  35853. }
  35854. END_JUCE_NAMESPACE
  35855. /*** End of inlined file: juce_TextButton.cpp ***/
  35856. /*** Start of inlined file: juce_ToggleButton.cpp ***/
  35857. BEGIN_JUCE_NAMESPACE
  35858. ToggleButton::ToggleButton (const String& buttonText)
  35859. : Button (buttonText)
  35860. {
  35861. setClickingTogglesState (true);
  35862. }
  35863. ToggleButton::~ToggleButton()
  35864. {
  35865. }
  35866. void ToggleButton::paintButton (Graphics& g,
  35867. bool isMouseOverButton,
  35868. bool isButtonDown)
  35869. {
  35870. getLookAndFeel().drawToggleButton (g, *this,
  35871. isMouseOverButton,
  35872. isButtonDown);
  35873. }
  35874. void ToggleButton::changeWidthToFitText()
  35875. {
  35876. getLookAndFeel().changeToggleButtonWidthToFitText (*this);
  35877. }
  35878. void ToggleButton::colourChanged()
  35879. {
  35880. repaint();
  35881. }
  35882. END_JUCE_NAMESPACE
  35883. /*** End of inlined file: juce_ToggleButton.cpp ***/
  35884. /*** Start of inlined file: juce_ToolbarButton.cpp ***/
  35885. BEGIN_JUCE_NAMESPACE
  35886. ToolbarButton::ToolbarButton (const int itemId_,
  35887. const String& buttonText,
  35888. Drawable* const normalImage_,
  35889. Drawable* const toggledOnImage_)
  35890. : ToolbarItemComponent (itemId_, buttonText, true),
  35891. normalImage (normalImage_),
  35892. toggledOnImage (toggledOnImage_)
  35893. {
  35894. jassert (normalImage_ != 0);
  35895. }
  35896. ToolbarButton::~ToolbarButton()
  35897. {
  35898. }
  35899. bool ToolbarButton::getToolbarItemSizes (int toolbarDepth,
  35900. bool /*isToolbarVertical*/,
  35901. int& preferredSize,
  35902. int& minSize, int& maxSize)
  35903. {
  35904. preferredSize = minSize = maxSize = toolbarDepth;
  35905. return true;
  35906. }
  35907. void ToolbarButton::paintButtonArea (Graphics& g,
  35908. int width, int height,
  35909. bool /*isMouseOver*/,
  35910. bool /*isMouseDown*/)
  35911. {
  35912. Drawable* d = normalImage;
  35913. if (getToggleState() && toggledOnImage != 0)
  35914. d = toggledOnImage;
  35915. const Rectangle<float> area (0.0f, 0.0f, (float) width, (float) height);
  35916. if (! isEnabled())
  35917. {
  35918. Image im (Image::ARGB, width, height, true);
  35919. {
  35920. Graphics g2 (im);
  35921. d->drawWithin (g2, area, RectanglePlacement::centred, 1.0f);
  35922. }
  35923. im.desaturate();
  35924. g.drawImageAt (im, 0, 0);
  35925. }
  35926. else
  35927. {
  35928. d->drawWithin (g, area, RectanglePlacement::centred, 1.0f);
  35929. }
  35930. }
  35931. void ToolbarButton::contentAreaChanged (const Rectangle<int>&)
  35932. {
  35933. }
  35934. END_JUCE_NAMESPACE
  35935. /*** End of inlined file: juce_ToolbarButton.cpp ***/
  35936. /*** Start of inlined file: juce_CodeDocument.cpp ***/
  35937. BEGIN_JUCE_NAMESPACE
  35938. class CodeDocumentLine
  35939. {
  35940. public:
  35941. CodeDocumentLine (const juce_wchar* const line_,
  35942. const int lineLength_,
  35943. const int numNewLineChars,
  35944. const int lineStartInFile_)
  35945. : line (line_, lineLength_),
  35946. lineStartInFile (lineStartInFile_),
  35947. lineLength (lineLength_),
  35948. lineLengthWithoutNewLines (lineLength_ - numNewLineChars)
  35949. {
  35950. }
  35951. ~CodeDocumentLine()
  35952. {
  35953. }
  35954. static void createLines (Array <CodeDocumentLine*>& newLines, const String& text)
  35955. {
  35956. const juce_wchar* const t = text;
  35957. int pos = 0;
  35958. while (t [pos] != 0)
  35959. {
  35960. const int startOfLine = pos;
  35961. int numNewLineChars = 0;
  35962. while (t[pos] != 0)
  35963. {
  35964. if (t[pos] == '\r')
  35965. {
  35966. ++numNewLineChars;
  35967. ++pos;
  35968. if (t[pos] == '\n')
  35969. {
  35970. ++numNewLineChars;
  35971. ++pos;
  35972. }
  35973. break;
  35974. }
  35975. if (t[pos] == '\n')
  35976. {
  35977. ++numNewLineChars;
  35978. ++pos;
  35979. break;
  35980. }
  35981. ++pos;
  35982. }
  35983. newLines.add (new CodeDocumentLine (t + startOfLine, pos - startOfLine,
  35984. numNewLineChars, startOfLine));
  35985. }
  35986. jassert (pos == text.length());
  35987. }
  35988. bool endsWithLineBreak() const throw()
  35989. {
  35990. return lineLengthWithoutNewLines != lineLength;
  35991. }
  35992. void updateLength() throw()
  35993. {
  35994. lineLengthWithoutNewLines = lineLength = line.length();
  35995. while (lineLengthWithoutNewLines > 0
  35996. && (line [lineLengthWithoutNewLines - 1] == '\n'
  35997. || line [lineLengthWithoutNewLines - 1] == '\r'))
  35998. {
  35999. --lineLengthWithoutNewLines;
  36000. }
  36001. }
  36002. String line;
  36003. int lineStartInFile, lineLength, lineLengthWithoutNewLines;
  36004. };
  36005. CodeDocument::Iterator::Iterator (CodeDocument* const document_)
  36006. : document (document_),
  36007. currentLine (document_->lines[0]),
  36008. line (0),
  36009. position (0)
  36010. {
  36011. }
  36012. CodeDocument::Iterator::Iterator (const CodeDocument::Iterator& other)
  36013. : document (other.document),
  36014. currentLine (other.currentLine),
  36015. line (other.line),
  36016. position (other.position)
  36017. {
  36018. }
  36019. CodeDocument::Iterator& CodeDocument::Iterator::operator= (const CodeDocument::Iterator& other) throw()
  36020. {
  36021. document = other.document;
  36022. currentLine = other.currentLine;
  36023. line = other.line;
  36024. position = other.position;
  36025. return *this;
  36026. }
  36027. CodeDocument::Iterator::~Iterator() throw()
  36028. {
  36029. }
  36030. juce_wchar CodeDocument::Iterator::nextChar()
  36031. {
  36032. if (currentLine == 0)
  36033. return 0;
  36034. jassert (currentLine == document->lines.getUnchecked (line));
  36035. const juce_wchar result = currentLine->line [position - currentLine->lineStartInFile];
  36036. if (++position >= currentLine->lineStartInFile + currentLine->lineLength)
  36037. {
  36038. ++line;
  36039. currentLine = document->lines [line];
  36040. }
  36041. return result;
  36042. }
  36043. void CodeDocument::Iterator::skip()
  36044. {
  36045. if (currentLine != 0)
  36046. {
  36047. jassert (currentLine == document->lines.getUnchecked (line));
  36048. if (++position >= currentLine->lineStartInFile + currentLine->lineLength)
  36049. {
  36050. ++line;
  36051. currentLine = document->lines [line];
  36052. }
  36053. }
  36054. }
  36055. void CodeDocument::Iterator::skipToEndOfLine()
  36056. {
  36057. if (currentLine != 0)
  36058. {
  36059. jassert (currentLine == document->lines.getUnchecked (line));
  36060. ++line;
  36061. currentLine = document->lines [line];
  36062. if (currentLine != 0)
  36063. position = currentLine->lineStartInFile;
  36064. else
  36065. position = document->getNumCharacters();
  36066. }
  36067. }
  36068. juce_wchar CodeDocument::Iterator::peekNextChar() const
  36069. {
  36070. if (currentLine == 0)
  36071. return 0;
  36072. jassert (currentLine == document->lines.getUnchecked (line));
  36073. return const_cast <const String&> (currentLine->line) [position - currentLine->lineStartInFile];
  36074. }
  36075. void CodeDocument::Iterator::skipWhitespace()
  36076. {
  36077. while (CharacterFunctions::isWhitespace (peekNextChar()))
  36078. skip();
  36079. }
  36080. bool CodeDocument::Iterator::isEOF() const throw()
  36081. {
  36082. return currentLine == 0;
  36083. }
  36084. CodeDocument::Position::Position() throw()
  36085. : owner (0), characterPos (0), line (0),
  36086. indexInLine (0), positionMaintained (false)
  36087. {
  36088. }
  36089. CodeDocument::Position::Position (const CodeDocument* const ownerDocument,
  36090. const int line_, const int indexInLine_) throw()
  36091. : owner (const_cast <CodeDocument*> (ownerDocument)),
  36092. characterPos (0), line (line_),
  36093. indexInLine (indexInLine_), positionMaintained (false)
  36094. {
  36095. setLineAndIndex (line_, indexInLine_);
  36096. }
  36097. CodeDocument::Position::Position (const CodeDocument* const ownerDocument,
  36098. const int characterPos_) throw()
  36099. : owner (const_cast <CodeDocument*> (ownerDocument)),
  36100. positionMaintained (false)
  36101. {
  36102. setPosition (characterPos_);
  36103. }
  36104. CodeDocument::Position::Position (const Position& other) throw()
  36105. : owner (other.owner), characterPos (other.characterPos), line (other.line),
  36106. indexInLine (other.indexInLine), positionMaintained (false)
  36107. {
  36108. jassert (*this == other);
  36109. }
  36110. CodeDocument::Position::~Position()
  36111. {
  36112. setPositionMaintained (false);
  36113. }
  36114. CodeDocument::Position& CodeDocument::Position::operator= (const Position& other)
  36115. {
  36116. if (this != &other)
  36117. {
  36118. const bool wasPositionMaintained = positionMaintained;
  36119. if (owner != other.owner)
  36120. setPositionMaintained (false);
  36121. owner = other.owner;
  36122. line = other.line;
  36123. indexInLine = other.indexInLine;
  36124. characterPos = other.characterPos;
  36125. setPositionMaintained (wasPositionMaintained);
  36126. jassert (*this == other);
  36127. }
  36128. return *this;
  36129. }
  36130. bool CodeDocument::Position::operator== (const Position& other) const throw()
  36131. {
  36132. jassert ((characterPos == other.characterPos)
  36133. == (line == other.line && indexInLine == other.indexInLine));
  36134. return characterPos == other.characterPos
  36135. && line == other.line
  36136. && indexInLine == other.indexInLine
  36137. && owner == other.owner;
  36138. }
  36139. bool CodeDocument::Position::operator!= (const Position& other) const throw()
  36140. {
  36141. return ! operator== (other);
  36142. }
  36143. void CodeDocument::Position::setLineAndIndex (const int newLine, const int newIndexInLine)
  36144. {
  36145. jassert (owner != 0);
  36146. if (owner->lines.size() == 0)
  36147. {
  36148. line = 0;
  36149. indexInLine = 0;
  36150. characterPos = 0;
  36151. }
  36152. else
  36153. {
  36154. if (newLine >= owner->lines.size())
  36155. {
  36156. line = owner->lines.size() - 1;
  36157. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  36158. jassert (l != 0);
  36159. indexInLine = l->lineLengthWithoutNewLines;
  36160. characterPos = l->lineStartInFile + indexInLine;
  36161. }
  36162. else
  36163. {
  36164. line = jmax (0, newLine);
  36165. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  36166. jassert (l != 0);
  36167. if (l->lineLengthWithoutNewLines > 0)
  36168. indexInLine = jlimit (0, l->lineLengthWithoutNewLines, newIndexInLine);
  36169. else
  36170. indexInLine = 0;
  36171. characterPos = l->lineStartInFile + indexInLine;
  36172. }
  36173. }
  36174. }
  36175. void CodeDocument::Position::setPosition (const int newPosition)
  36176. {
  36177. jassert (owner != 0);
  36178. line = 0;
  36179. indexInLine = 0;
  36180. characterPos = 0;
  36181. if (newPosition > 0)
  36182. {
  36183. int lineStart = 0;
  36184. int lineEnd = owner->lines.size();
  36185. for (;;)
  36186. {
  36187. if (lineEnd - lineStart < 4)
  36188. {
  36189. for (int i = lineStart; i < lineEnd; ++i)
  36190. {
  36191. CodeDocumentLine* const l = owner->lines.getUnchecked (i);
  36192. int index = newPosition - l->lineStartInFile;
  36193. if (index >= 0 && (index < l->lineLength || i == lineEnd - 1))
  36194. {
  36195. line = i;
  36196. indexInLine = jmin (l->lineLengthWithoutNewLines, index);
  36197. characterPos = l->lineStartInFile + indexInLine;
  36198. }
  36199. }
  36200. break;
  36201. }
  36202. else
  36203. {
  36204. const int midIndex = (lineStart + lineEnd + 1) / 2;
  36205. CodeDocumentLine* const mid = owner->lines.getUnchecked (midIndex);
  36206. if (newPosition >= mid->lineStartInFile)
  36207. lineStart = midIndex;
  36208. else
  36209. lineEnd = midIndex;
  36210. }
  36211. }
  36212. }
  36213. }
  36214. void CodeDocument::Position::moveBy (int characterDelta)
  36215. {
  36216. jassert (owner != 0);
  36217. if (characterDelta == 1)
  36218. {
  36219. setPosition (getPosition());
  36220. // If moving right, make sure we don't get stuck between the \r and \n characters..
  36221. if (line < owner->lines.size())
  36222. {
  36223. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  36224. if (indexInLine + characterDelta < l->lineLength
  36225. && indexInLine + characterDelta >= l->lineLengthWithoutNewLines + 1)
  36226. ++characterDelta;
  36227. }
  36228. }
  36229. setPosition (characterPos + characterDelta);
  36230. }
  36231. const CodeDocument::Position CodeDocument::Position::movedBy (const int characterDelta) const
  36232. {
  36233. CodeDocument::Position p (*this);
  36234. p.moveBy (characterDelta);
  36235. return p;
  36236. }
  36237. const CodeDocument::Position CodeDocument::Position::movedByLines (const int deltaLines) const
  36238. {
  36239. CodeDocument::Position p (*this);
  36240. p.setLineAndIndex (getLineNumber() + deltaLines, getIndexInLine());
  36241. return p;
  36242. }
  36243. const juce_wchar CodeDocument::Position::getCharacter() const
  36244. {
  36245. const CodeDocumentLine* const l = owner->lines [line];
  36246. return l == 0 ? 0 : l->line [getIndexInLine()];
  36247. }
  36248. const String CodeDocument::Position::getLineText() const
  36249. {
  36250. const CodeDocumentLine* const l = owner->lines [line];
  36251. return l == 0 ? String::empty : l->line;
  36252. }
  36253. void CodeDocument::Position::setPositionMaintained (const bool isMaintained)
  36254. {
  36255. if (isMaintained != positionMaintained)
  36256. {
  36257. positionMaintained = isMaintained;
  36258. if (owner != 0)
  36259. {
  36260. if (isMaintained)
  36261. {
  36262. jassert (! owner->positionsToMaintain.contains (this));
  36263. owner->positionsToMaintain.add (this);
  36264. }
  36265. else
  36266. {
  36267. // If this happens, you may have deleted the document while there are Position objects that are still using it...
  36268. jassert (owner->positionsToMaintain.contains (this));
  36269. owner->positionsToMaintain.removeValue (this);
  36270. }
  36271. }
  36272. }
  36273. }
  36274. CodeDocument::CodeDocument()
  36275. : undoManager (std::numeric_limits<int>::max(), 10000),
  36276. currentActionIndex (0),
  36277. indexOfSavedState (-1),
  36278. maximumLineLength (-1),
  36279. newLineChars ("\r\n")
  36280. {
  36281. }
  36282. CodeDocument::~CodeDocument()
  36283. {
  36284. }
  36285. const String CodeDocument::getAllContent() const
  36286. {
  36287. return getTextBetween (Position (this, 0),
  36288. Position (this, lines.size(), 0));
  36289. }
  36290. const String CodeDocument::getTextBetween (const Position& start, const Position& end) const
  36291. {
  36292. if (end.getPosition() <= start.getPosition())
  36293. return String::empty;
  36294. const int startLine = start.getLineNumber();
  36295. const int endLine = end.getLineNumber();
  36296. if (startLine == endLine)
  36297. {
  36298. CodeDocumentLine* const line = lines [startLine];
  36299. return (line == 0) ? String::empty : line->line.substring (start.getIndexInLine(), end.getIndexInLine());
  36300. }
  36301. String result;
  36302. result.preallocateStorage (end.getPosition() - start.getPosition() + 4);
  36303. String::Concatenator concatenator (result);
  36304. const int maxLine = jmin (lines.size() - 1, endLine);
  36305. for (int i = jmax (0, startLine); i <= maxLine; ++i)
  36306. {
  36307. const CodeDocumentLine* line = lines.getUnchecked(i);
  36308. int len = line->lineLength;
  36309. if (i == startLine)
  36310. {
  36311. const int index = start.getIndexInLine();
  36312. concatenator.append (line->line.substring (index, len));
  36313. }
  36314. else if (i == endLine)
  36315. {
  36316. len = end.getIndexInLine();
  36317. concatenator.append (line->line.substring (0, len));
  36318. }
  36319. else
  36320. {
  36321. concatenator.append (line->line);
  36322. }
  36323. }
  36324. return result;
  36325. }
  36326. int CodeDocument::getNumCharacters() const throw()
  36327. {
  36328. const CodeDocumentLine* const lastLine = lines.getLast();
  36329. return (lastLine == 0) ? 0 : lastLine->lineStartInFile + lastLine->lineLength;
  36330. }
  36331. const String CodeDocument::getLine (const int lineIndex) const throw()
  36332. {
  36333. const CodeDocumentLine* const line = lines [lineIndex];
  36334. return (line == 0) ? String::empty : line->line;
  36335. }
  36336. int CodeDocument::getMaximumLineLength() throw()
  36337. {
  36338. if (maximumLineLength < 0)
  36339. {
  36340. maximumLineLength = 0;
  36341. for (int i = lines.size(); --i >= 0;)
  36342. maximumLineLength = jmax (maximumLineLength, lines.getUnchecked(i)->lineLength);
  36343. }
  36344. return maximumLineLength;
  36345. }
  36346. void CodeDocument::deleteSection (const Position& startPosition, const Position& endPosition)
  36347. {
  36348. remove (startPosition.getPosition(), endPosition.getPosition(), true);
  36349. }
  36350. void CodeDocument::insertText (const Position& position, const String& text)
  36351. {
  36352. insert (text, position.getPosition(), true);
  36353. }
  36354. void CodeDocument::replaceAllContent (const String& newContent)
  36355. {
  36356. remove (0, getNumCharacters(), true);
  36357. insert (newContent, 0, true);
  36358. }
  36359. bool CodeDocument::loadFromStream (InputStream& stream)
  36360. {
  36361. replaceAllContent (stream.readEntireStreamAsString());
  36362. setSavePoint();
  36363. clearUndoHistory();
  36364. return true;
  36365. }
  36366. bool CodeDocument::writeToStream (OutputStream& stream)
  36367. {
  36368. for (int i = 0; i < lines.size(); ++i)
  36369. {
  36370. String temp (lines.getUnchecked(i)->line); // use a copy to avoid bloating the memory footprint of the stored string.
  36371. const char* utf8 = temp.toUTF8();
  36372. if (! stream.write (utf8, (int) strlen (utf8)))
  36373. return false;
  36374. }
  36375. return true;
  36376. }
  36377. void CodeDocument::setNewLineCharacters (const String& newLine) throw()
  36378. {
  36379. jassert (newLine == "\r\n" || newLine == "\n" || newLine == "\r");
  36380. newLineChars = newLine;
  36381. }
  36382. void CodeDocument::newTransaction()
  36383. {
  36384. undoManager.beginNewTransaction (String::empty);
  36385. }
  36386. void CodeDocument::undo()
  36387. {
  36388. newTransaction();
  36389. undoManager.undo();
  36390. }
  36391. void CodeDocument::redo()
  36392. {
  36393. undoManager.redo();
  36394. }
  36395. void CodeDocument::clearUndoHistory()
  36396. {
  36397. undoManager.clearUndoHistory();
  36398. }
  36399. void CodeDocument::setSavePoint() throw()
  36400. {
  36401. indexOfSavedState = currentActionIndex;
  36402. }
  36403. bool CodeDocument::hasChangedSinceSavePoint() const throw()
  36404. {
  36405. return currentActionIndex != indexOfSavedState;
  36406. }
  36407. namespace CodeDocumentHelpers
  36408. {
  36409. int getCharacterType (const juce_wchar character) throw()
  36410. {
  36411. return (CharacterFunctions::isLetterOrDigit (character) || character == '_')
  36412. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  36413. }
  36414. }
  36415. const CodeDocument::Position CodeDocument::findWordBreakAfter (const Position& position) const throw()
  36416. {
  36417. Position p (position);
  36418. const int maxDistance = 256;
  36419. int i = 0;
  36420. while (i < maxDistance
  36421. && CharacterFunctions::isWhitespace (p.getCharacter())
  36422. && (i == 0 || (p.getCharacter() != '\n'
  36423. && p.getCharacter() != '\r')))
  36424. {
  36425. ++i;
  36426. p.moveBy (1);
  36427. }
  36428. if (i == 0)
  36429. {
  36430. const int type = CodeDocumentHelpers::getCharacterType (p.getCharacter());
  36431. while (i < maxDistance && type == CodeDocumentHelpers::getCharacterType (p.getCharacter()))
  36432. {
  36433. ++i;
  36434. p.moveBy (1);
  36435. }
  36436. while (i < maxDistance
  36437. && CharacterFunctions::isWhitespace (p.getCharacter())
  36438. && (i == 0 || (p.getCharacter() != '\n'
  36439. && p.getCharacter() != '\r')))
  36440. {
  36441. ++i;
  36442. p.moveBy (1);
  36443. }
  36444. }
  36445. return p;
  36446. }
  36447. const CodeDocument::Position CodeDocument::findWordBreakBefore (const Position& position) const throw()
  36448. {
  36449. Position p (position);
  36450. const int maxDistance = 256;
  36451. int i = 0;
  36452. bool stoppedAtLineStart = false;
  36453. while (i < maxDistance)
  36454. {
  36455. const juce_wchar c = p.movedBy (-1).getCharacter();
  36456. if (c == '\r' || c == '\n')
  36457. {
  36458. stoppedAtLineStart = true;
  36459. if (i > 0)
  36460. break;
  36461. }
  36462. if (! CharacterFunctions::isWhitespace (c))
  36463. break;
  36464. p.moveBy (-1);
  36465. ++i;
  36466. }
  36467. if (i < maxDistance && ! stoppedAtLineStart)
  36468. {
  36469. const int type = CodeDocumentHelpers::getCharacterType (p.movedBy (-1).getCharacter());
  36470. while (i < maxDistance && type == CodeDocumentHelpers::getCharacterType (p.movedBy (-1).getCharacter()))
  36471. {
  36472. p.moveBy (-1);
  36473. ++i;
  36474. }
  36475. }
  36476. return p;
  36477. }
  36478. void CodeDocument::checkLastLineStatus()
  36479. {
  36480. while (lines.size() > 0
  36481. && lines.getLast()->lineLength == 0
  36482. && (lines.size() == 1 || ! lines.getUnchecked (lines.size() - 2)->endsWithLineBreak()))
  36483. {
  36484. // remove any empty lines at the end if the preceding line doesn't end in a newline.
  36485. lines.removeLast();
  36486. }
  36487. const CodeDocumentLine* const lastLine = lines.getLast();
  36488. if (lastLine != 0 && lastLine->endsWithLineBreak())
  36489. {
  36490. // check that there's an empty line at the end if the preceding one ends in a newline..
  36491. lines.add (new CodeDocumentLine (String::empty, 0, 0, lastLine->lineStartInFile + lastLine->lineLength));
  36492. }
  36493. }
  36494. void CodeDocument::addListener (CodeDocument::Listener* const listener) throw()
  36495. {
  36496. listeners.add (listener);
  36497. }
  36498. void CodeDocument::removeListener (CodeDocument::Listener* const listener) throw()
  36499. {
  36500. listeners.remove (listener);
  36501. }
  36502. void CodeDocument::sendListenerChangeMessage (const int startLine, const int endLine)
  36503. {
  36504. Position startPos (this, startLine, 0);
  36505. Position endPos (this, endLine, 0);
  36506. listeners.call (&CodeDocument::Listener::codeDocumentChanged, startPos, endPos);
  36507. }
  36508. class CodeDocumentInsertAction : public UndoableAction
  36509. {
  36510. CodeDocument& owner;
  36511. const String text;
  36512. int insertPos;
  36513. CodeDocumentInsertAction (const CodeDocumentInsertAction&);
  36514. CodeDocumentInsertAction& operator= (const CodeDocumentInsertAction&);
  36515. public:
  36516. CodeDocumentInsertAction (CodeDocument& owner_, const String& text_, const int insertPos_) throw()
  36517. : owner (owner_),
  36518. text (text_),
  36519. insertPos (insertPos_)
  36520. {
  36521. }
  36522. ~CodeDocumentInsertAction() {}
  36523. bool perform()
  36524. {
  36525. owner.currentActionIndex++;
  36526. owner.insert (text, insertPos, false);
  36527. return true;
  36528. }
  36529. bool undo()
  36530. {
  36531. owner.currentActionIndex--;
  36532. owner.remove (insertPos, insertPos + text.length(), false);
  36533. return true;
  36534. }
  36535. int getSizeInUnits() { return text.length() + 32; }
  36536. };
  36537. void CodeDocument::insert (const String& text, const int insertPos, const bool undoable)
  36538. {
  36539. if (text.isEmpty())
  36540. return;
  36541. if (undoable)
  36542. {
  36543. undoManager.perform (new CodeDocumentInsertAction (*this, text, insertPos));
  36544. }
  36545. else
  36546. {
  36547. Position pos (this, insertPos);
  36548. const int firstAffectedLine = pos.getLineNumber();
  36549. int lastAffectedLine = firstAffectedLine + 1;
  36550. CodeDocumentLine* const firstLine = lines [firstAffectedLine];
  36551. String textInsideOriginalLine (text);
  36552. if (firstLine != 0)
  36553. {
  36554. const int index = pos.getIndexInLine();
  36555. textInsideOriginalLine = firstLine->line.substring (0, index)
  36556. + textInsideOriginalLine
  36557. + firstLine->line.substring (index);
  36558. }
  36559. maximumLineLength = -1;
  36560. Array <CodeDocumentLine*> newLines;
  36561. CodeDocumentLine::createLines (newLines, textInsideOriginalLine);
  36562. jassert (newLines.size() > 0);
  36563. CodeDocumentLine* const newFirstLine = newLines.getUnchecked (0);
  36564. newFirstLine->lineStartInFile = firstLine != 0 ? firstLine->lineStartInFile : 0;
  36565. lines.set (firstAffectedLine, newFirstLine);
  36566. if (newLines.size() > 1)
  36567. {
  36568. for (int i = 1; i < newLines.size(); ++i)
  36569. {
  36570. CodeDocumentLine* const l = newLines.getUnchecked (i);
  36571. lines.insert (firstAffectedLine + i, l);
  36572. }
  36573. lastAffectedLine = lines.size();
  36574. }
  36575. int i, lineStart = newFirstLine->lineStartInFile;
  36576. for (i = firstAffectedLine; i < lines.size(); ++i)
  36577. {
  36578. CodeDocumentLine* const l = lines.getUnchecked (i);
  36579. l->lineStartInFile = lineStart;
  36580. lineStart += l->lineLength;
  36581. }
  36582. checkLastLineStatus();
  36583. const int newTextLength = text.length();
  36584. for (i = 0; i < positionsToMaintain.size(); ++i)
  36585. {
  36586. CodeDocument::Position* const p = positionsToMaintain.getUnchecked(i);
  36587. if (p->getPosition() >= insertPos)
  36588. p->setPosition (p->getPosition() + newTextLength);
  36589. }
  36590. sendListenerChangeMessage (firstAffectedLine, lastAffectedLine);
  36591. }
  36592. }
  36593. class CodeDocumentDeleteAction : public UndoableAction
  36594. {
  36595. CodeDocument& owner;
  36596. int startPos, endPos;
  36597. String removedText;
  36598. CodeDocumentDeleteAction (const CodeDocumentDeleteAction&);
  36599. CodeDocumentDeleteAction& operator= (const CodeDocumentDeleteAction&);
  36600. public:
  36601. CodeDocumentDeleteAction (CodeDocument& owner_, const int startPos_, const int endPos_) throw()
  36602. : owner (owner_),
  36603. startPos (startPos_),
  36604. endPos (endPos_)
  36605. {
  36606. removedText = owner.getTextBetween (CodeDocument::Position (&owner, startPos),
  36607. CodeDocument::Position (&owner, endPos));
  36608. }
  36609. ~CodeDocumentDeleteAction() {}
  36610. bool perform()
  36611. {
  36612. owner.currentActionIndex++;
  36613. owner.remove (startPos, endPos, false);
  36614. return true;
  36615. }
  36616. bool undo()
  36617. {
  36618. owner.currentActionIndex--;
  36619. owner.insert (removedText, startPos, false);
  36620. return true;
  36621. }
  36622. int getSizeInUnits() { return removedText.length() + 32; }
  36623. };
  36624. void CodeDocument::remove (const int startPos, const int endPos, const bool undoable)
  36625. {
  36626. if (endPos <= startPos)
  36627. return;
  36628. if (undoable)
  36629. {
  36630. undoManager.perform (new CodeDocumentDeleteAction (*this, startPos, endPos));
  36631. }
  36632. else
  36633. {
  36634. Position startPosition (this, startPos);
  36635. Position endPosition (this, endPos);
  36636. maximumLineLength = -1;
  36637. const int firstAffectedLine = startPosition.getLineNumber();
  36638. const int endLine = endPosition.getLineNumber();
  36639. int lastAffectedLine = firstAffectedLine + 1;
  36640. CodeDocumentLine* const firstLine = lines.getUnchecked (firstAffectedLine);
  36641. if (firstAffectedLine == endLine)
  36642. {
  36643. firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine())
  36644. + firstLine->line.substring (endPosition.getIndexInLine());
  36645. firstLine->updateLength();
  36646. }
  36647. else
  36648. {
  36649. lastAffectedLine = lines.size();
  36650. CodeDocumentLine* const lastLine = lines.getUnchecked (endLine);
  36651. jassert (lastLine != 0);
  36652. firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine())
  36653. + lastLine->line.substring (endPosition.getIndexInLine());
  36654. firstLine->updateLength();
  36655. int numLinesToRemove = endLine - firstAffectedLine;
  36656. lines.removeRange (firstAffectedLine + 1, numLinesToRemove);
  36657. }
  36658. int i;
  36659. for (i = firstAffectedLine + 1; i < lines.size(); ++i)
  36660. {
  36661. CodeDocumentLine* const l = lines.getUnchecked (i);
  36662. const CodeDocumentLine* const previousLine = lines.getUnchecked (i - 1);
  36663. l->lineStartInFile = previousLine->lineStartInFile + previousLine->lineLength;
  36664. }
  36665. checkLastLineStatus();
  36666. const int totalChars = getNumCharacters();
  36667. for (i = 0; i < positionsToMaintain.size(); ++i)
  36668. {
  36669. CodeDocument::Position* p = positionsToMaintain.getUnchecked(i);
  36670. if (p->getPosition() > startPosition.getPosition())
  36671. p->setPosition (jmax (startPos, p->getPosition() + startPos - endPos));
  36672. if (p->getPosition() > totalChars)
  36673. p->setPosition (totalChars);
  36674. }
  36675. sendListenerChangeMessage (firstAffectedLine, lastAffectedLine);
  36676. }
  36677. }
  36678. END_JUCE_NAMESPACE
  36679. /*** End of inlined file: juce_CodeDocument.cpp ***/
  36680. /*** Start of inlined file: juce_CodeEditorComponent.cpp ***/
  36681. BEGIN_JUCE_NAMESPACE
  36682. class CodeEditorComponent::CaretComponent : public Component,
  36683. public Timer
  36684. {
  36685. public:
  36686. CaretComponent (CodeEditorComponent& owner_)
  36687. : owner (owner_)
  36688. {
  36689. setAlwaysOnTop (true);
  36690. setInterceptsMouseClicks (false, false);
  36691. }
  36692. void paint (Graphics& g)
  36693. {
  36694. g.fillAll (findColour (CodeEditorComponent::caretColourId));
  36695. }
  36696. void timerCallback()
  36697. {
  36698. setVisible (shouldBeShown() && ! isVisible());
  36699. }
  36700. void updatePosition()
  36701. {
  36702. startTimer (400);
  36703. setVisible (shouldBeShown());
  36704. setBounds (owner.getCharacterBounds (owner.getCaretPos()).withWidth (2));
  36705. }
  36706. private:
  36707. CodeEditorComponent& owner;
  36708. CaretComponent (const CaretComponent&);
  36709. CaretComponent& operator= (const CaretComponent&);
  36710. bool shouldBeShown() const { return owner.hasKeyboardFocus (true); }
  36711. };
  36712. class CodeEditorComponent::CodeEditorLine
  36713. {
  36714. public:
  36715. CodeEditorLine() throw()
  36716. : highlightColumnStart (0), highlightColumnEnd (0)
  36717. {
  36718. }
  36719. ~CodeEditorLine() throw()
  36720. {
  36721. }
  36722. bool update (CodeDocument& document, int lineNum,
  36723. CodeDocument::Iterator& source,
  36724. CodeTokeniser* analyser, const int spacesPerTab,
  36725. const CodeDocument::Position& selectionStart,
  36726. const CodeDocument::Position& selectionEnd)
  36727. {
  36728. Array <SyntaxToken> newTokens;
  36729. newTokens.ensureStorageAllocated (8);
  36730. if (analyser == 0)
  36731. {
  36732. newTokens.add (SyntaxToken (document.getLine (lineNum), -1));
  36733. }
  36734. else if (lineNum < document.getNumLines())
  36735. {
  36736. const CodeDocument::Position pos (&document, lineNum, 0);
  36737. createTokens (pos.getPosition(), pos.getLineText(),
  36738. source, analyser, newTokens);
  36739. }
  36740. replaceTabsWithSpaces (newTokens, spacesPerTab);
  36741. int newHighlightStart = 0;
  36742. int newHighlightEnd = 0;
  36743. if (selectionStart.getLineNumber() <= lineNum && selectionEnd.getLineNumber() >= lineNum)
  36744. {
  36745. const String line (document.getLine (lineNum));
  36746. CodeDocument::Position lineStart (&document, lineNum, 0), lineEnd (&document, lineNum + 1, 0);
  36747. newHighlightStart = indexToColumn (jmax (0, selectionStart.getPosition() - lineStart.getPosition()),
  36748. line, spacesPerTab);
  36749. newHighlightEnd = indexToColumn (jmin (lineEnd.getPosition() - lineStart.getPosition(), selectionEnd.getPosition() - lineStart.getPosition()),
  36750. line, spacesPerTab);
  36751. }
  36752. if (newHighlightStart != highlightColumnStart || newHighlightEnd != highlightColumnEnd)
  36753. {
  36754. highlightColumnStart = newHighlightStart;
  36755. highlightColumnEnd = newHighlightEnd;
  36756. }
  36757. else
  36758. {
  36759. if (tokens.size() == newTokens.size())
  36760. {
  36761. bool allTheSame = true;
  36762. for (int i = newTokens.size(); --i >= 0;)
  36763. {
  36764. if (tokens.getReference(i) != newTokens.getReference(i))
  36765. {
  36766. allTheSame = false;
  36767. break;
  36768. }
  36769. }
  36770. if (allTheSame)
  36771. return false;
  36772. }
  36773. }
  36774. tokens.swapWithArray (newTokens);
  36775. return true;
  36776. }
  36777. void draw (CodeEditorComponent& owner, Graphics& g, const Font& font,
  36778. float x, const int y, const int baselineOffset, const int lineHeight,
  36779. const Colour& highlightColour) const
  36780. {
  36781. if (highlightColumnStart < highlightColumnEnd)
  36782. {
  36783. g.setColour (highlightColour);
  36784. g.fillRect (roundToInt (x + highlightColumnStart * owner.getCharWidth()), y,
  36785. roundToInt ((highlightColumnEnd - highlightColumnStart) * owner.getCharWidth()), lineHeight);
  36786. }
  36787. int lastType = std::numeric_limits<int>::min();
  36788. for (int i = 0; i < tokens.size(); ++i)
  36789. {
  36790. SyntaxToken& token = tokens.getReference(i);
  36791. if (lastType != token.tokenType)
  36792. {
  36793. lastType = token.tokenType;
  36794. g.setColour (owner.getColourForTokenType (lastType));
  36795. }
  36796. g.drawSingleLineText (token.text, roundToInt (x), y + baselineOffset);
  36797. if (i < tokens.size() - 1)
  36798. {
  36799. if (token.width < 0)
  36800. token.width = font.getStringWidthFloat (token.text);
  36801. x += token.width;
  36802. }
  36803. }
  36804. }
  36805. private:
  36806. struct SyntaxToken
  36807. {
  36808. String text;
  36809. int tokenType;
  36810. float width;
  36811. SyntaxToken (const String& text_, const int type) throw()
  36812. : text (text_), tokenType (type), width (-1.0f)
  36813. {
  36814. }
  36815. bool operator!= (const SyntaxToken& other) const throw()
  36816. {
  36817. return text != other.text || tokenType != other.tokenType;
  36818. }
  36819. };
  36820. Array <SyntaxToken> tokens;
  36821. int highlightColumnStart, highlightColumnEnd;
  36822. static void createTokens (int startPosition, const String& lineText,
  36823. CodeDocument::Iterator& source,
  36824. CodeTokeniser* analyser,
  36825. Array <SyntaxToken>& newTokens)
  36826. {
  36827. CodeDocument::Iterator lastIterator (source);
  36828. const int lineLength = lineText.length();
  36829. for (;;)
  36830. {
  36831. int tokenType = analyser->readNextToken (source);
  36832. int tokenStart = lastIterator.getPosition();
  36833. int tokenEnd = source.getPosition();
  36834. if (tokenEnd <= tokenStart)
  36835. break;
  36836. tokenEnd -= startPosition;
  36837. if (tokenEnd > 0)
  36838. {
  36839. tokenStart -= startPosition;
  36840. newTokens.add (SyntaxToken (lineText.substring (jmax (0, tokenStart), tokenEnd),
  36841. tokenType));
  36842. if (tokenEnd >= lineLength)
  36843. break;
  36844. }
  36845. lastIterator = source;
  36846. }
  36847. source = lastIterator;
  36848. }
  36849. static void replaceTabsWithSpaces (Array <SyntaxToken>& tokens, const int spacesPerTab)
  36850. {
  36851. int x = 0;
  36852. for (int i = 0; i < tokens.size(); ++i)
  36853. {
  36854. SyntaxToken& t = tokens.getReference(i);
  36855. for (;;)
  36856. {
  36857. int tabPos = t.text.indexOfChar ('\t');
  36858. if (tabPos < 0)
  36859. break;
  36860. const int spacesNeeded = spacesPerTab - ((tabPos + x) % spacesPerTab);
  36861. t.text = t.text.replaceSection (tabPos, 1, String::repeatedString (" ", spacesNeeded));
  36862. }
  36863. x += t.text.length();
  36864. }
  36865. }
  36866. int indexToColumn (int index, const String& line, int spacesPerTab) const throw()
  36867. {
  36868. jassert (index <= line.length());
  36869. int col = 0;
  36870. for (int i = 0; i < index; ++i)
  36871. {
  36872. if (line[i] != '\t')
  36873. ++col;
  36874. else
  36875. col += spacesPerTab - (col % spacesPerTab);
  36876. }
  36877. return col;
  36878. }
  36879. };
  36880. CodeEditorComponent::CodeEditorComponent (CodeDocument& document_,
  36881. CodeTokeniser* const codeTokeniser_)
  36882. : document (document_),
  36883. firstLineOnScreen (0),
  36884. gutter (5),
  36885. spacesPerTab (4),
  36886. lineHeight (0),
  36887. linesOnScreen (0),
  36888. columnsOnScreen (0),
  36889. scrollbarThickness (16),
  36890. columnToTryToMaintain (-1),
  36891. useSpacesForTabs (false),
  36892. xOffset (0),
  36893. verticalScrollBar (true),
  36894. horizontalScrollBar (false),
  36895. codeTokeniser (codeTokeniser_)
  36896. {
  36897. caretPos = CodeDocument::Position (&document_, 0, 0);
  36898. caretPos.setPositionMaintained (true);
  36899. selectionStart = CodeDocument::Position (&document_, 0, 0);
  36900. selectionStart.setPositionMaintained (true);
  36901. selectionEnd = CodeDocument::Position (&document_, 0, 0);
  36902. selectionEnd.setPositionMaintained (true);
  36903. setOpaque (true);
  36904. setMouseCursor (MouseCursor (MouseCursor::IBeamCursor));
  36905. setWantsKeyboardFocus (true);
  36906. addAndMakeVisible (&verticalScrollBar);
  36907. verticalScrollBar.setSingleStepSize (1.0);
  36908. addAndMakeVisible (&horizontalScrollBar);
  36909. horizontalScrollBar.setSingleStepSize (1.0);
  36910. addAndMakeVisible (caret = new CaretComponent (*this));
  36911. Font f (12.0f);
  36912. f.setTypefaceName (Font::getDefaultMonospacedFontName());
  36913. setFont (f);
  36914. resetToDefaultColours();
  36915. verticalScrollBar.addListener (this);
  36916. horizontalScrollBar.addListener (this);
  36917. document.addListener (this);
  36918. }
  36919. CodeEditorComponent::~CodeEditorComponent()
  36920. {
  36921. document.removeListener (this);
  36922. }
  36923. void CodeEditorComponent::loadContent (const String& newContent)
  36924. {
  36925. clearCachedIterators (0);
  36926. document.replaceAllContent (newContent);
  36927. document.clearUndoHistory();
  36928. document.setSavePoint();
  36929. caretPos.setPosition (0);
  36930. selectionStart.setPosition (0);
  36931. selectionEnd.setPosition (0);
  36932. scrollToLine (0);
  36933. }
  36934. bool CodeEditorComponent::isTextInputActive() const
  36935. {
  36936. return true;
  36937. }
  36938. void CodeEditorComponent::codeDocumentChanged (const CodeDocument::Position& affectedTextStart,
  36939. const CodeDocument::Position& affectedTextEnd)
  36940. {
  36941. clearCachedIterators (affectedTextStart.getLineNumber());
  36942. triggerAsyncUpdate();
  36943. caret->updatePosition();
  36944. columnToTryToMaintain = -1;
  36945. if (affectedTextEnd.getPosition() >= selectionStart.getPosition()
  36946. && affectedTextStart.getPosition() <= selectionEnd.getPosition())
  36947. deselectAll();
  36948. if (caretPos.getPosition() > affectedTextEnd.getPosition()
  36949. || caretPos.getPosition() < affectedTextStart.getPosition())
  36950. moveCaretTo (affectedTextStart, false);
  36951. updateScrollBars();
  36952. }
  36953. void CodeEditorComponent::resized()
  36954. {
  36955. linesOnScreen = (getHeight() - scrollbarThickness) / lineHeight;
  36956. columnsOnScreen = (int) ((getWidth() - scrollbarThickness) / charWidth);
  36957. lines.clear();
  36958. rebuildLineTokens();
  36959. caret->updatePosition();
  36960. verticalScrollBar.setBounds (getWidth() - scrollbarThickness, 0, scrollbarThickness, getHeight() - scrollbarThickness);
  36961. horizontalScrollBar.setBounds (gutter, getHeight() - scrollbarThickness, getWidth() - scrollbarThickness - gutter, scrollbarThickness);
  36962. updateScrollBars();
  36963. }
  36964. void CodeEditorComponent::paint (Graphics& g)
  36965. {
  36966. handleUpdateNowIfNeeded();
  36967. g.fillAll (findColour (CodeEditorComponent::backgroundColourId));
  36968. g.reduceClipRegion (gutter, 0, verticalScrollBar.getX() - gutter, horizontalScrollBar.getY());
  36969. g.setFont (font);
  36970. const int baselineOffset = (int) font.getAscent();
  36971. const Colour defaultColour (findColour (CodeEditorComponent::defaultTextColourId));
  36972. const Colour highlightColour (findColour (CodeEditorComponent::highlightColourId));
  36973. const Rectangle<int> clip (g.getClipBounds());
  36974. const int firstLineToDraw = jmax (0, clip.getY() / lineHeight);
  36975. const int lastLineToDraw = jmin (lines.size(), clip.getBottom() / lineHeight + 1);
  36976. for (int j = firstLineToDraw; j < lastLineToDraw; ++j)
  36977. {
  36978. lines.getUnchecked(j)->draw (*this, g, font,
  36979. (float) (gutter - xOffset * charWidth),
  36980. lineHeight * j, baselineOffset, lineHeight,
  36981. highlightColour);
  36982. }
  36983. }
  36984. void CodeEditorComponent::setScrollbarThickness (const int thickness)
  36985. {
  36986. if (scrollbarThickness != thickness)
  36987. {
  36988. scrollbarThickness = thickness;
  36989. resized();
  36990. }
  36991. }
  36992. void CodeEditorComponent::handleAsyncUpdate()
  36993. {
  36994. rebuildLineTokens();
  36995. }
  36996. void CodeEditorComponent::rebuildLineTokens()
  36997. {
  36998. cancelPendingUpdate();
  36999. const int numNeeded = linesOnScreen + 1;
  37000. int minLineToRepaint = numNeeded;
  37001. int maxLineToRepaint = 0;
  37002. if (numNeeded != lines.size())
  37003. {
  37004. lines.clear();
  37005. for (int i = numNeeded; --i >= 0;)
  37006. lines.add (new CodeEditorLine());
  37007. minLineToRepaint = 0;
  37008. maxLineToRepaint = numNeeded;
  37009. }
  37010. jassert (numNeeded == lines.size());
  37011. CodeDocument::Iterator source (&document);
  37012. getIteratorForPosition (CodeDocument::Position (&document, firstLineOnScreen, 0).getPosition(), source);
  37013. for (int i = 0; i < numNeeded; ++i)
  37014. {
  37015. CodeEditorLine* const line = lines.getUnchecked(i);
  37016. if (line->update (document, firstLineOnScreen + i, source, codeTokeniser, spacesPerTab,
  37017. selectionStart, selectionEnd))
  37018. {
  37019. minLineToRepaint = jmin (minLineToRepaint, i);
  37020. maxLineToRepaint = jmax (maxLineToRepaint, i);
  37021. }
  37022. }
  37023. if (minLineToRepaint <= maxLineToRepaint)
  37024. {
  37025. repaint (gutter, lineHeight * minLineToRepaint - 1,
  37026. verticalScrollBar.getX() - gutter,
  37027. lineHeight * (1 + maxLineToRepaint - minLineToRepaint) + 2);
  37028. }
  37029. }
  37030. void CodeEditorComponent::moveCaretTo (const CodeDocument::Position& newPos, const bool highlighting)
  37031. {
  37032. caretPos = newPos;
  37033. columnToTryToMaintain = -1;
  37034. if (highlighting)
  37035. {
  37036. if (dragType == notDragging)
  37037. {
  37038. if (abs (caretPos.getPosition() - selectionStart.getPosition())
  37039. < abs (caretPos.getPosition() - selectionEnd.getPosition()))
  37040. dragType = draggingSelectionStart;
  37041. else
  37042. dragType = draggingSelectionEnd;
  37043. }
  37044. if (dragType == draggingSelectionStart)
  37045. {
  37046. selectionStart = caretPos;
  37047. if (selectionEnd.getPosition() < selectionStart.getPosition())
  37048. {
  37049. const CodeDocument::Position temp (selectionStart);
  37050. selectionStart = selectionEnd;
  37051. selectionEnd = temp;
  37052. dragType = draggingSelectionEnd;
  37053. }
  37054. }
  37055. else
  37056. {
  37057. selectionEnd = caretPos;
  37058. if (selectionEnd.getPosition() < selectionStart.getPosition())
  37059. {
  37060. const CodeDocument::Position temp (selectionStart);
  37061. selectionStart = selectionEnd;
  37062. selectionEnd = temp;
  37063. dragType = draggingSelectionStart;
  37064. }
  37065. }
  37066. triggerAsyncUpdate();
  37067. }
  37068. else
  37069. {
  37070. deselectAll();
  37071. }
  37072. caret->updatePosition();
  37073. scrollToKeepCaretOnScreen();
  37074. updateScrollBars();
  37075. }
  37076. void CodeEditorComponent::deselectAll()
  37077. {
  37078. if (selectionStart != selectionEnd)
  37079. triggerAsyncUpdate();
  37080. selectionStart = caretPos;
  37081. selectionEnd = caretPos;
  37082. }
  37083. void CodeEditorComponent::updateScrollBars()
  37084. {
  37085. verticalScrollBar.setRangeLimits (0, jmax (document.getNumLines(), firstLineOnScreen + linesOnScreen));
  37086. verticalScrollBar.setCurrentRange (firstLineOnScreen, linesOnScreen);
  37087. horizontalScrollBar.setRangeLimits (0, jmax ((double) document.getMaximumLineLength(), xOffset + columnsOnScreen));
  37088. horizontalScrollBar.setCurrentRange (xOffset, columnsOnScreen);
  37089. }
  37090. void CodeEditorComponent::scrollToLineInternal (int newFirstLineOnScreen)
  37091. {
  37092. newFirstLineOnScreen = jlimit (0, jmax (0, document.getNumLines() - 1),
  37093. newFirstLineOnScreen);
  37094. if (newFirstLineOnScreen != firstLineOnScreen)
  37095. {
  37096. firstLineOnScreen = newFirstLineOnScreen;
  37097. caret->updatePosition();
  37098. updateCachedIterators (firstLineOnScreen);
  37099. triggerAsyncUpdate();
  37100. }
  37101. }
  37102. void CodeEditorComponent::scrollToColumnInternal (double column)
  37103. {
  37104. const double newOffset = jlimit (0.0, document.getMaximumLineLength() + 3.0, column);
  37105. if (xOffset != newOffset)
  37106. {
  37107. xOffset = newOffset;
  37108. caret->updatePosition();
  37109. repaint();
  37110. }
  37111. }
  37112. void CodeEditorComponent::scrollToLine (int newFirstLineOnScreen)
  37113. {
  37114. scrollToLineInternal (newFirstLineOnScreen);
  37115. updateScrollBars();
  37116. }
  37117. void CodeEditorComponent::scrollToColumn (int newFirstColumnOnScreen)
  37118. {
  37119. scrollToColumnInternal (newFirstColumnOnScreen);
  37120. updateScrollBars();
  37121. }
  37122. void CodeEditorComponent::scrollBy (int deltaLines)
  37123. {
  37124. scrollToLine (firstLineOnScreen + deltaLines);
  37125. }
  37126. void CodeEditorComponent::scrollToKeepCaretOnScreen()
  37127. {
  37128. if (caretPos.getLineNumber() < firstLineOnScreen)
  37129. scrollBy (caretPos.getLineNumber() - firstLineOnScreen);
  37130. else if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen)
  37131. scrollBy (caretPos.getLineNumber() - (firstLineOnScreen + linesOnScreen - 1));
  37132. const int column = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine());
  37133. if (column >= xOffset + columnsOnScreen - 1)
  37134. scrollToColumn (column + 1 - columnsOnScreen);
  37135. else if (column < xOffset)
  37136. scrollToColumn (column);
  37137. }
  37138. const Rectangle<int> CodeEditorComponent::getCharacterBounds (const CodeDocument::Position& pos) const
  37139. {
  37140. return Rectangle<int> (roundToInt ((gutter - xOffset * charWidth) + indexToColumn (pos.getLineNumber(), pos.getIndexInLine()) * charWidth),
  37141. (pos.getLineNumber() - firstLineOnScreen) * lineHeight,
  37142. roundToInt (charWidth),
  37143. lineHeight);
  37144. }
  37145. const CodeDocument::Position CodeEditorComponent::getPositionAt (int x, int y)
  37146. {
  37147. const int line = y / lineHeight + firstLineOnScreen;
  37148. const int column = roundToInt ((x - (gutter - xOffset * charWidth)) / charWidth);
  37149. const int index = columnToIndex (line, column);
  37150. return CodeDocument::Position (&document, line, index);
  37151. }
  37152. void CodeEditorComponent::insertTextAtCaret (const String& newText)
  37153. {
  37154. document.deleteSection (selectionStart, selectionEnd);
  37155. if (newText.isNotEmpty())
  37156. document.insertText (caretPos, newText);
  37157. scrollToKeepCaretOnScreen();
  37158. }
  37159. void CodeEditorComponent::insertTabAtCaret()
  37160. {
  37161. if (CharacterFunctions::isWhitespace (caretPos.getCharacter())
  37162. && caretPos.getLineNumber() == caretPos.movedBy (1).getLineNumber())
  37163. {
  37164. moveCaretTo (document.findWordBreakAfter (caretPos), false);
  37165. }
  37166. if (useSpacesForTabs)
  37167. {
  37168. const int caretCol = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine());
  37169. const int spacesNeeded = spacesPerTab - (caretCol % spacesPerTab);
  37170. insertTextAtCaret (String::repeatedString (" ", spacesNeeded));
  37171. }
  37172. else
  37173. {
  37174. insertTextAtCaret ("\t");
  37175. }
  37176. }
  37177. void CodeEditorComponent::cut()
  37178. {
  37179. insertTextAtCaret (String::empty);
  37180. }
  37181. void CodeEditorComponent::copy()
  37182. {
  37183. newTransaction();
  37184. const String selection (document.getTextBetween (selectionStart, selectionEnd));
  37185. if (selection.isNotEmpty())
  37186. SystemClipboard::copyTextToClipboard (selection);
  37187. }
  37188. void CodeEditorComponent::copyThenCut()
  37189. {
  37190. copy();
  37191. cut();
  37192. newTransaction();
  37193. }
  37194. void CodeEditorComponent::paste()
  37195. {
  37196. newTransaction();
  37197. const String clip (SystemClipboard::getTextFromClipboard());
  37198. if (clip.isNotEmpty())
  37199. insertTextAtCaret (clip);
  37200. newTransaction();
  37201. }
  37202. void CodeEditorComponent::cursorLeft (const bool moveInWholeWordSteps, const bool selecting)
  37203. {
  37204. newTransaction();
  37205. if (moveInWholeWordSteps)
  37206. moveCaretTo (document.findWordBreakBefore (caretPos), selecting);
  37207. else
  37208. moveCaretTo (caretPos.movedBy (-1), selecting);
  37209. }
  37210. void CodeEditorComponent::cursorRight (const bool moveInWholeWordSteps, const bool selecting)
  37211. {
  37212. newTransaction();
  37213. if (moveInWholeWordSteps)
  37214. moveCaretTo (document.findWordBreakAfter (caretPos), selecting);
  37215. else
  37216. moveCaretTo (caretPos.movedBy (1), selecting);
  37217. }
  37218. void CodeEditorComponent::moveLineDelta (const int delta, const bool selecting)
  37219. {
  37220. CodeDocument::Position pos (caretPos);
  37221. const int newLineNum = pos.getLineNumber() + delta;
  37222. if (columnToTryToMaintain < 0)
  37223. columnToTryToMaintain = indexToColumn (pos.getLineNumber(), pos.getIndexInLine());
  37224. pos.setLineAndIndex (newLineNum, columnToIndex (newLineNum, columnToTryToMaintain));
  37225. const int colToMaintain = columnToTryToMaintain;
  37226. moveCaretTo (pos, selecting);
  37227. columnToTryToMaintain = colToMaintain;
  37228. }
  37229. void CodeEditorComponent::cursorDown (const bool selecting)
  37230. {
  37231. newTransaction();
  37232. if (caretPos.getLineNumber() == document.getNumLines() - 1)
  37233. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting);
  37234. else
  37235. moveLineDelta (1, selecting);
  37236. }
  37237. void CodeEditorComponent::cursorUp (const bool selecting)
  37238. {
  37239. newTransaction();
  37240. if (caretPos.getLineNumber() == 0)
  37241. moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting);
  37242. else
  37243. moveLineDelta (-1, selecting);
  37244. }
  37245. void CodeEditorComponent::pageDown (const bool selecting)
  37246. {
  37247. newTransaction();
  37248. scrollBy (jlimit (0, linesOnScreen, 1 + document.getNumLines() - firstLineOnScreen - linesOnScreen));
  37249. moveLineDelta (linesOnScreen, selecting);
  37250. }
  37251. void CodeEditorComponent::pageUp (const bool selecting)
  37252. {
  37253. newTransaction();
  37254. scrollBy (-linesOnScreen);
  37255. moveLineDelta (-linesOnScreen, selecting);
  37256. }
  37257. void CodeEditorComponent::scrollUp()
  37258. {
  37259. newTransaction();
  37260. scrollBy (1);
  37261. if (caretPos.getLineNumber() < firstLineOnScreen)
  37262. moveLineDelta (1, false);
  37263. }
  37264. void CodeEditorComponent::scrollDown()
  37265. {
  37266. newTransaction();
  37267. scrollBy (-1);
  37268. if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen)
  37269. moveLineDelta (-1, false);
  37270. }
  37271. void CodeEditorComponent::goToStartOfDocument (const bool selecting)
  37272. {
  37273. newTransaction();
  37274. moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting);
  37275. }
  37276. namespace CodeEditorHelpers
  37277. {
  37278. int findFirstNonWhitespaceChar (const String& line) throw()
  37279. {
  37280. const int len = line.length();
  37281. for (int i = 0; i < len; ++i)
  37282. if (! CharacterFunctions::isWhitespace (line [i]))
  37283. return i;
  37284. return 0;
  37285. }
  37286. }
  37287. void CodeEditorComponent::goToStartOfLine (const bool selecting)
  37288. {
  37289. newTransaction();
  37290. int index = CodeEditorHelpers::findFirstNonWhitespaceChar (caretPos.getLineText());
  37291. if (index >= caretPos.getIndexInLine() && caretPos.getIndexInLine() > 0)
  37292. index = 0;
  37293. moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), index), selecting);
  37294. }
  37295. void CodeEditorComponent::goToEndOfDocument (const bool selecting)
  37296. {
  37297. newTransaction();
  37298. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting);
  37299. }
  37300. void CodeEditorComponent::goToEndOfLine (const bool selecting)
  37301. {
  37302. newTransaction();
  37303. moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), std::numeric_limits<int>::max()), selecting);
  37304. }
  37305. void CodeEditorComponent::backspace (const bool moveInWholeWordSteps)
  37306. {
  37307. if (moveInWholeWordSteps)
  37308. {
  37309. cut(); // in case something is already highlighted
  37310. moveCaretTo (document.findWordBreakBefore (caretPos), true);
  37311. }
  37312. else
  37313. {
  37314. if (selectionStart == selectionEnd)
  37315. selectionStart.moveBy (-1);
  37316. }
  37317. cut();
  37318. }
  37319. void CodeEditorComponent::deleteForward (const bool moveInWholeWordSteps)
  37320. {
  37321. if (moveInWholeWordSteps)
  37322. {
  37323. cut(); // in case something is already highlighted
  37324. moveCaretTo (document.findWordBreakAfter (caretPos), true);
  37325. }
  37326. else
  37327. {
  37328. if (selectionStart == selectionEnd)
  37329. selectionEnd.moveBy (1);
  37330. else
  37331. newTransaction();
  37332. }
  37333. cut();
  37334. }
  37335. void CodeEditorComponent::selectAll()
  37336. {
  37337. newTransaction();
  37338. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), false);
  37339. moveCaretTo (CodeDocument::Position (&document, 0, 0), true);
  37340. }
  37341. void CodeEditorComponent::undo()
  37342. {
  37343. document.undo();
  37344. scrollToKeepCaretOnScreen();
  37345. }
  37346. void CodeEditorComponent::redo()
  37347. {
  37348. document.redo();
  37349. scrollToKeepCaretOnScreen();
  37350. }
  37351. void CodeEditorComponent::newTransaction()
  37352. {
  37353. document.newTransaction();
  37354. startTimer (600);
  37355. }
  37356. void CodeEditorComponent::timerCallback()
  37357. {
  37358. newTransaction();
  37359. }
  37360. const Range<int> CodeEditorComponent::getHighlightedRegion() const
  37361. {
  37362. return Range<int> (selectionStart.getPosition(), selectionEnd.getPosition());
  37363. }
  37364. void CodeEditorComponent::setHighlightedRegion (const Range<int>& newRange)
  37365. {
  37366. moveCaretTo (CodeDocument::Position (&document, newRange.getStart()), false);
  37367. moveCaretTo (CodeDocument::Position (&document, newRange.getEnd()), true);
  37368. }
  37369. const String CodeEditorComponent::getTextInRange (const Range<int>& range) const
  37370. {
  37371. return document.getTextBetween (CodeDocument::Position (&document, range.getStart()),
  37372. CodeDocument::Position (&document, range.getEnd()));
  37373. }
  37374. bool CodeEditorComponent::keyPressed (const KeyPress& key)
  37375. {
  37376. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  37377. const bool shiftDown = key.getModifiers().isShiftDown();
  37378. if (key.isKeyCode (KeyPress::leftKey))
  37379. {
  37380. cursorLeft (moveInWholeWordSteps, shiftDown);
  37381. }
  37382. else if (key.isKeyCode (KeyPress::rightKey))
  37383. {
  37384. cursorRight (moveInWholeWordSteps, shiftDown);
  37385. }
  37386. else if (key.isKeyCode (KeyPress::upKey))
  37387. {
  37388. if (key.getModifiers().isCtrlDown() && ! shiftDown)
  37389. scrollDown();
  37390. #if JUCE_MAC
  37391. else if (key.getModifiers().isCommandDown())
  37392. goToStartOfDocument (shiftDown);
  37393. #endif
  37394. else
  37395. cursorUp (shiftDown);
  37396. }
  37397. else if (key.isKeyCode (KeyPress::downKey))
  37398. {
  37399. if (key.getModifiers().isCtrlDown() && ! shiftDown)
  37400. scrollUp();
  37401. #if JUCE_MAC
  37402. else if (key.getModifiers().isCommandDown())
  37403. goToEndOfDocument (shiftDown);
  37404. #endif
  37405. else
  37406. cursorDown (shiftDown);
  37407. }
  37408. else if (key.isKeyCode (KeyPress::pageDownKey))
  37409. {
  37410. pageDown (shiftDown);
  37411. }
  37412. else if (key.isKeyCode (KeyPress::pageUpKey))
  37413. {
  37414. pageUp (shiftDown);
  37415. }
  37416. else if (key.isKeyCode (KeyPress::homeKey))
  37417. {
  37418. if (moveInWholeWordSteps)
  37419. goToStartOfDocument (shiftDown);
  37420. else
  37421. goToStartOfLine (shiftDown);
  37422. }
  37423. else if (key.isKeyCode (KeyPress::endKey))
  37424. {
  37425. if (moveInWholeWordSteps)
  37426. goToEndOfDocument (shiftDown);
  37427. else
  37428. goToEndOfLine (shiftDown);
  37429. }
  37430. else if (key.isKeyCode (KeyPress::backspaceKey))
  37431. {
  37432. backspace (moveInWholeWordSteps);
  37433. }
  37434. else if (key.isKeyCode (KeyPress::deleteKey))
  37435. {
  37436. deleteForward (moveInWholeWordSteps);
  37437. }
  37438. else if (key == KeyPress ('c', ModifierKeys::commandModifier, 0))
  37439. {
  37440. copy();
  37441. }
  37442. else if (key == KeyPress ('x', ModifierKeys::commandModifier, 0))
  37443. {
  37444. copyThenCut();
  37445. }
  37446. else if (key == KeyPress ('v', ModifierKeys::commandModifier, 0))
  37447. {
  37448. paste();
  37449. }
  37450. else if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  37451. {
  37452. undo();
  37453. }
  37454. else if (key == KeyPress ('y', ModifierKeys::commandModifier, 0)
  37455. || key == KeyPress ('z', ModifierKeys::commandModifier | ModifierKeys::shiftModifier, 0))
  37456. {
  37457. redo();
  37458. }
  37459. else if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  37460. {
  37461. selectAll();
  37462. }
  37463. else if (key == KeyPress::tabKey || key.getTextCharacter() == '\t')
  37464. {
  37465. insertTabAtCaret();
  37466. }
  37467. else if (key == KeyPress::returnKey)
  37468. {
  37469. newTransaction();
  37470. insertTextAtCaret (document.getNewLineCharacters());
  37471. }
  37472. else if (key.isKeyCode (KeyPress::escapeKey))
  37473. {
  37474. newTransaction();
  37475. }
  37476. else if (key.getTextCharacter() >= ' ')
  37477. {
  37478. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  37479. }
  37480. else
  37481. {
  37482. return false;
  37483. }
  37484. return true;
  37485. }
  37486. void CodeEditorComponent::mouseDown (const MouseEvent& e)
  37487. {
  37488. newTransaction();
  37489. dragType = notDragging;
  37490. if (! e.mods.isPopupMenu())
  37491. {
  37492. beginDragAutoRepeat (100);
  37493. moveCaretTo (getPositionAt (e.x, e.y), e.mods.isShiftDown());
  37494. }
  37495. else
  37496. {
  37497. /*PopupMenu m;
  37498. addPopupMenuItems (m, &e);
  37499. const int result = m.show();
  37500. if (result != 0)
  37501. performPopupMenuAction (result);
  37502. */
  37503. }
  37504. }
  37505. void CodeEditorComponent::mouseDrag (const MouseEvent& e)
  37506. {
  37507. if (! e.mods.isPopupMenu())
  37508. moveCaretTo (getPositionAt (e.x, e.y), true);
  37509. }
  37510. void CodeEditorComponent::mouseUp (const MouseEvent&)
  37511. {
  37512. newTransaction();
  37513. beginDragAutoRepeat (0);
  37514. dragType = notDragging;
  37515. }
  37516. void CodeEditorComponent::mouseDoubleClick (const MouseEvent& e)
  37517. {
  37518. CodeDocument::Position tokenStart (getPositionAt (e.x, e.y));
  37519. CodeDocument::Position tokenEnd (tokenStart);
  37520. if (e.getNumberOfClicks() > 2)
  37521. {
  37522. tokenStart.setLineAndIndex (tokenStart.getLineNumber(), 0);
  37523. tokenEnd.setLineAndIndex (tokenStart.getLineNumber() + 1, 0);
  37524. }
  37525. else
  37526. {
  37527. while (CharacterFunctions::isLetterOrDigit (tokenEnd.getCharacter()))
  37528. tokenEnd.moveBy (1);
  37529. tokenStart = tokenEnd;
  37530. while (tokenStart.getIndexInLine() > 0
  37531. && CharacterFunctions::isLetterOrDigit (tokenStart.movedBy (-1).getCharacter()))
  37532. tokenStart.moveBy (-1);
  37533. }
  37534. moveCaretTo (tokenEnd, false);
  37535. moveCaretTo (tokenStart, true);
  37536. }
  37537. void CodeEditorComponent::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  37538. {
  37539. if ((verticalScrollBar.isVisible() && wheelIncrementY != 0)
  37540. || (horizontalScrollBar.isVisible() && wheelIncrementX != 0))
  37541. {
  37542. verticalScrollBar.mouseWheelMove (e, 0, wheelIncrementY);
  37543. horizontalScrollBar.mouseWheelMove (e, wheelIncrementX, 0);
  37544. }
  37545. else
  37546. {
  37547. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  37548. }
  37549. }
  37550. void CodeEditorComponent::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart)
  37551. {
  37552. if (scrollBarThatHasMoved == &verticalScrollBar)
  37553. scrollToLineInternal ((int) newRangeStart);
  37554. else
  37555. scrollToColumnInternal (newRangeStart);
  37556. }
  37557. void CodeEditorComponent::focusGained (FocusChangeType)
  37558. {
  37559. caret->updatePosition();
  37560. }
  37561. void CodeEditorComponent::focusLost (FocusChangeType)
  37562. {
  37563. caret->updatePosition();
  37564. }
  37565. void CodeEditorComponent::setTabSize (const int numSpaces, const bool insertSpaces)
  37566. {
  37567. useSpacesForTabs = insertSpaces;
  37568. if (spacesPerTab != numSpaces)
  37569. {
  37570. spacesPerTab = numSpaces;
  37571. triggerAsyncUpdate();
  37572. }
  37573. }
  37574. int CodeEditorComponent::indexToColumn (int lineNum, int index) const throw()
  37575. {
  37576. const String line (document.getLine (lineNum));
  37577. jassert (index <= line.length());
  37578. int col = 0;
  37579. for (int i = 0; i < index; ++i)
  37580. {
  37581. if (line[i] != '\t')
  37582. ++col;
  37583. else
  37584. col += getTabSize() - (col % getTabSize());
  37585. }
  37586. return col;
  37587. }
  37588. int CodeEditorComponent::columnToIndex (int lineNum, int column) const throw()
  37589. {
  37590. const String line (document.getLine (lineNum));
  37591. const int lineLength = line.length();
  37592. int i, col = 0;
  37593. for (i = 0; i < lineLength; ++i)
  37594. {
  37595. if (line[i] != '\t')
  37596. ++col;
  37597. else
  37598. col += getTabSize() - (col % getTabSize());
  37599. if (col > column)
  37600. break;
  37601. }
  37602. return i;
  37603. }
  37604. void CodeEditorComponent::setFont (const Font& newFont)
  37605. {
  37606. font = newFont;
  37607. charWidth = font.getStringWidthFloat ("0");
  37608. lineHeight = roundToInt (font.getHeight());
  37609. resized();
  37610. }
  37611. void CodeEditorComponent::resetToDefaultColours()
  37612. {
  37613. coloursForTokenCategories.clear();
  37614. if (codeTokeniser != 0)
  37615. {
  37616. for (int i = codeTokeniser->getTokenTypes().size(); --i >= 0;)
  37617. setColourForTokenType (i, codeTokeniser->getDefaultColour (i));
  37618. }
  37619. }
  37620. void CodeEditorComponent::setColourForTokenType (const int tokenType, const Colour& colour)
  37621. {
  37622. jassert (tokenType < 256);
  37623. while (coloursForTokenCategories.size() < tokenType)
  37624. coloursForTokenCategories.add (Colours::black);
  37625. coloursForTokenCategories.set (tokenType, colour);
  37626. repaint();
  37627. }
  37628. const Colour CodeEditorComponent::getColourForTokenType (const int tokenType) const
  37629. {
  37630. if (((unsigned int) tokenType) >= (unsigned int) coloursForTokenCategories.size())
  37631. return findColour (CodeEditorComponent::defaultTextColourId);
  37632. return coloursForTokenCategories.getReference (tokenType);
  37633. }
  37634. void CodeEditorComponent::clearCachedIterators (const int firstLineToBeInvalid)
  37635. {
  37636. int i;
  37637. for (i = cachedIterators.size(); --i >= 0;)
  37638. if (cachedIterators.getUnchecked (i)->getLine() < firstLineToBeInvalid)
  37639. break;
  37640. cachedIterators.removeRange (jmax (0, i - 1), cachedIterators.size());
  37641. }
  37642. void CodeEditorComponent::updateCachedIterators (int maxLineNum)
  37643. {
  37644. const int maxNumCachedPositions = 5000;
  37645. const int linesBetweenCachedSources = jmax (10, document.getNumLines() / maxNumCachedPositions);
  37646. if (cachedIterators.size() == 0)
  37647. cachedIterators.add (new CodeDocument::Iterator (&document));
  37648. if (codeTokeniser == 0)
  37649. return;
  37650. for (;;)
  37651. {
  37652. CodeDocument::Iterator* last = cachedIterators.getLast();
  37653. if (last->getLine() >= maxLineNum)
  37654. break;
  37655. CodeDocument::Iterator* t = new CodeDocument::Iterator (*last);
  37656. cachedIterators.add (t);
  37657. const int targetLine = last->getLine() + linesBetweenCachedSources;
  37658. for (;;)
  37659. {
  37660. codeTokeniser->readNextToken (*t);
  37661. if (t->getLine() >= targetLine)
  37662. break;
  37663. if (t->isEOF())
  37664. return;
  37665. }
  37666. }
  37667. }
  37668. void CodeEditorComponent::getIteratorForPosition (int position, CodeDocument::Iterator& source)
  37669. {
  37670. if (codeTokeniser == 0)
  37671. return;
  37672. for (int i = cachedIterators.size(); --i >= 0;)
  37673. {
  37674. CodeDocument::Iterator* t = cachedIterators.getUnchecked (i);
  37675. if (t->getPosition() <= position)
  37676. {
  37677. source = *t;
  37678. break;
  37679. }
  37680. }
  37681. while (source.getPosition() < position)
  37682. {
  37683. const CodeDocument::Iterator original (source);
  37684. codeTokeniser->readNextToken (source);
  37685. if (source.getPosition() > position || source.isEOF())
  37686. {
  37687. source = original;
  37688. break;
  37689. }
  37690. }
  37691. }
  37692. END_JUCE_NAMESPACE
  37693. /*** End of inlined file: juce_CodeEditorComponent.cpp ***/
  37694. /*** Start of inlined file: juce_CPlusPlusCodeTokeniser.cpp ***/
  37695. BEGIN_JUCE_NAMESPACE
  37696. CPlusPlusCodeTokeniser::CPlusPlusCodeTokeniser()
  37697. {
  37698. }
  37699. CPlusPlusCodeTokeniser::~CPlusPlusCodeTokeniser()
  37700. {
  37701. }
  37702. namespace CppTokeniser
  37703. {
  37704. static bool isIdentifierStart (const juce_wchar c) throw()
  37705. {
  37706. return CharacterFunctions::isLetter (c)
  37707. || c == '_' || c == '@';
  37708. }
  37709. static bool isIdentifierBody (const juce_wchar c) throw()
  37710. {
  37711. return CharacterFunctions::isLetterOrDigit (c)
  37712. || c == '_' || c == '@';
  37713. }
  37714. static bool isReservedKeyword (const juce_wchar* const token, const int tokenLength) throw()
  37715. {
  37716. static const juce_wchar* const keywords2Char[] =
  37717. { JUCE_T("if"), JUCE_T("do"), JUCE_T("or"), JUCE_T("id"), 0 };
  37718. static const juce_wchar* const keywords3Char[] =
  37719. { JUCE_T("for"), JUCE_T("int"), JUCE_T("new"), JUCE_T("try"), JUCE_T("xor"), JUCE_T("and"), JUCE_T("asm"), JUCE_T("not"), 0 };
  37720. static const juce_wchar* const keywords4Char[] =
  37721. { JUCE_T("bool"), JUCE_T("void"), JUCE_T("this"), JUCE_T("true"), JUCE_T("long"), JUCE_T("else"), JUCE_T("char"),
  37722. JUCE_T("enum"), JUCE_T("case"), JUCE_T("goto"), JUCE_T("auto"), 0 };
  37723. static const juce_wchar* const keywords5Char[] =
  37724. { JUCE_T("while"), JUCE_T("bitor"), JUCE_T("break"), JUCE_T("catch"), JUCE_T("class"), JUCE_T("compl"), JUCE_T("const"), JUCE_T("false"),
  37725. JUCE_T("float"), JUCE_T("short"), JUCE_T("throw"), JUCE_T("union"), JUCE_T("using"), JUCE_T("or_eq"), 0 };
  37726. static const juce_wchar* const keywords6Char[] =
  37727. { JUCE_T("return"), JUCE_T("struct"), JUCE_T("and_eq"), JUCE_T("bitand"), JUCE_T("delete"), JUCE_T("double"), JUCE_T("extern"),
  37728. JUCE_T("friend"), JUCE_T("inline"), JUCE_T("not_eq"), JUCE_T("public"), JUCE_T("sizeof"), JUCE_T("static"), JUCE_T("signed"),
  37729. JUCE_T("switch"), JUCE_T("typeid"), JUCE_T("wchar_t"), JUCE_T("xor_eq"), 0};
  37730. static const juce_wchar* const keywordsOther[] =
  37731. { JUCE_T("const_cast"), JUCE_T("continue"), JUCE_T("default"), JUCE_T("explicit"), JUCE_T("mutable"), JUCE_T("namespace"),
  37732. JUCE_T("operator"), JUCE_T("private"), JUCE_T("protected"), JUCE_T("register"), JUCE_T("reinterpret_cast"), JUCE_T("static_cast"),
  37733. JUCE_T("template"), JUCE_T("typedef"), JUCE_T("typename"), JUCE_T("unsigned"), JUCE_T("virtual"), JUCE_T("volatile"),
  37734. JUCE_T("@implementation"), JUCE_T("@interface"), JUCE_T("@end"), JUCE_T("@synthesize"), JUCE_T("@dynamic"), JUCE_T("@public"),
  37735. JUCE_T("@private"), JUCE_T("@property"), JUCE_T("@protected"), JUCE_T("@class"), 0 };
  37736. const juce_wchar* const* k;
  37737. switch (tokenLength)
  37738. {
  37739. case 2: k = keywords2Char; break;
  37740. case 3: k = keywords3Char; break;
  37741. case 4: k = keywords4Char; break;
  37742. case 5: k = keywords5Char; break;
  37743. case 6: k = keywords6Char; break;
  37744. default:
  37745. if (tokenLength < 2 || tokenLength > 16)
  37746. return false;
  37747. k = keywordsOther;
  37748. break;
  37749. }
  37750. int i = 0;
  37751. while (k[i] != 0)
  37752. {
  37753. if (k[i][0] == token[0] && CharacterFunctions::compare (k[i], token) == 0)
  37754. return true;
  37755. ++i;
  37756. }
  37757. return false;
  37758. }
  37759. static int parseIdentifier (CodeDocument::Iterator& source) throw()
  37760. {
  37761. int tokenLength = 0;
  37762. juce_wchar possibleIdentifier [19];
  37763. while (isIdentifierBody (source.peekNextChar()))
  37764. {
  37765. const juce_wchar c = source.nextChar();
  37766. if (tokenLength < numElementsInArray (possibleIdentifier) - 1)
  37767. possibleIdentifier [tokenLength] = c;
  37768. ++tokenLength;
  37769. }
  37770. if (tokenLength > 1 && tokenLength <= 16)
  37771. {
  37772. possibleIdentifier [tokenLength] = 0;
  37773. if (isReservedKeyword (possibleIdentifier, tokenLength))
  37774. return CPlusPlusCodeTokeniser::tokenType_builtInKeyword;
  37775. }
  37776. return CPlusPlusCodeTokeniser::tokenType_identifier;
  37777. }
  37778. static bool skipNumberSuffix (CodeDocument::Iterator& source)
  37779. {
  37780. const juce_wchar c = source.peekNextChar();
  37781. if (c == 'l' || c == 'L' || c == 'u' || c == 'U')
  37782. source.skip();
  37783. if (CharacterFunctions::isLetterOrDigit (source.peekNextChar()))
  37784. return false;
  37785. return true;
  37786. }
  37787. static bool isHexDigit (const juce_wchar c) throw()
  37788. {
  37789. return (c >= '0' && c <= '9')
  37790. || (c >= 'a' && c <= 'f')
  37791. || (c >= 'A' && c <= 'F');
  37792. }
  37793. static bool parseHexLiteral (CodeDocument::Iterator& source) throw()
  37794. {
  37795. if (source.nextChar() != '0')
  37796. return false;
  37797. juce_wchar c = source.nextChar();
  37798. if (c != 'x' && c != 'X')
  37799. return false;
  37800. int numDigits = 0;
  37801. while (isHexDigit (source.peekNextChar()))
  37802. {
  37803. ++numDigits;
  37804. source.skip();
  37805. }
  37806. if (numDigits == 0)
  37807. return false;
  37808. return skipNumberSuffix (source);
  37809. }
  37810. static bool isOctalDigit (const juce_wchar c) throw()
  37811. {
  37812. return c >= '0' && c <= '7';
  37813. }
  37814. static bool parseOctalLiteral (CodeDocument::Iterator& source) throw()
  37815. {
  37816. if (source.nextChar() != '0')
  37817. return false;
  37818. if (! isOctalDigit (source.nextChar()))
  37819. return false;
  37820. while (isOctalDigit (source.peekNextChar()))
  37821. source.skip();
  37822. return skipNumberSuffix (source);
  37823. }
  37824. static bool isDecimalDigit (const juce_wchar c) throw()
  37825. {
  37826. return c >= '0' && c <= '9';
  37827. }
  37828. static bool parseDecimalLiteral (CodeDocument::Iterator& source) throw()
  37829. {
  37830. int numChars = 0;
  37831. while (isDecimalDigit (source.peekNextChar()))
  37832. {
  37833. ++numChars;
  37834. source.skip();
  37835. }
  37836. if (numChars == 0)
  37837. return false;
  37838. return skipNumberSuffix (source);
  37839. }
  37840. static bool parseFloatLiteral (CodeDocument::Iterator& source) throw()
  37841. {
  37842. int numDigits = 0;
  37843. while (isDecimalDigit (source.peekNextChar()))
  37844. {
  37845. source.skip();
  37846. ++numDigits;
  37847. }
  37848. const bool hasPoint = (source.peekNextChar() == '.');
  37849. if (hasPoint)
  37850. {
  37851. source.skip();
  37852. while (isDecimalDigit (source.peekNextChar()))
  37853. {
  37854. source.skip();
  37855. ++numDigits;
  37856. }
  37857. }
  37858. if (numDigits == 0)
  37859. return false;
  37860. juce_wchar c = source.peekNextChar();
  37861. const bool hasExponent = (c == 'e' || c == 'E');
  37862. if (hasExponent)
  37863. {
  37864. source.skip();
  37865. c = source.peekNextChar();
  37866. if (c == '+' || c == '-')
  37867. source.skip();
  37868. int numExpDigits = 0;
  37869. while (isDecimalDigit (source.peekNextChar()))
  37870. {
  37871. source.skip();
  37872. ++numExpDigits;
  37873. }
  37874. if (numExpDigits == 0)
  37875. return false;
  37876. }
  37877. c = source.peekNextChar();
  37878. if (c == 'f' || c == 'F')
  37879. source.skip();
  37880. else if (! (hasExponent || hasPoint))
  37881. return false;
  37882. return true;
  37883. }
  37884. static int parseNumber (CodeDocument::Iterator& source)
  37885. {
  37886. const CodeDocument::Iterator original (source);
  37887. if (parseFloatLiteral (source))
  37888. return CPlusPlusCodeTokeniser::tokenType_floatLiteral;
  37889. source = original;
  37890. if (parseHexLiteral (source))
  37891. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37892. source = original;
  37893. if (parseOctalLiteral (source))
  37894. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37895. source = original;
  37896. if (parseDecimalLiteral (source))
  37897. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37898. source = original;
  37899. source.skip();
  37900. return CPlusPlusCodeTokeniser::tokenType_error;
  37901. }
  37902. static void skipQuotedString (CodeDocument::Iterator& source) throw()
  37903. {
  37904. const juce_wchar quote = source.nextChar();
  37905. for (;;)
  37906. {
  37907. const juce_wchar c = source.nextChar();
  37908. if (c == quote || c == 0)
  37909. break;
  37910. if (c == '\\')
  37911. source.skip();
  37912. }
  37913. }
  37914. static void skipComment (CodeDocument::Iterator& source) throw()
  37915. {
  37916. bool lastWasStar = false;
  37917. for (;;)
  37918. {
  37919. const juce_wchar c = source.nextChar();
  37920. if (c == 0 || (c == '/' && lastWasStar))
  37921. break;
  37922. lastWasStar = (c == '*');
  37923. }
  37924. }
  37925. }
  37926. int CPlusPlusCodeTokeniser::readNextToken (CodeDocument::Iterator& source)
  37927. {
  37928. int result = tokenType_error;
  37929. source.skipWhitespace();
  37930. juce_wchar firstChar = source.peekNextChar();
  37931. switch (firstChar)
  37932. {
  37933. case 0:
  37934. source.skip();
  37935. break;
  37936. case '0':
  37937. case '1':
  37938. case '2':
  37939. case '3':
  37940. case '4':
  37941. case '5':
  37942. case '6':
  37943. case '7':
  37944. case '8':
  37945. case '9':
  37946. result = CppTokeniser::parseNumber (source);
  37947. break;
  37948. case '.':
  37949. result = CppTokeniser::parseNumber (source);
  37950. if (result == tokenType_error)
  37951. result = tokenType_punctuation;
  37952. break;
  37953. case ',':
  37954. case ';':
  37955. case ':':
  37956. source.skip();
  37957. result = tokenType_punctuation;
  37958. break;
  37959. case '(':
  37960. case ')':
  37961. case '{':
  37962. case '}':
  37963. case '[':
  37964. case ']':
  37965. source.skip();
  37966. result = tokenType_bracket;
  37967. break;
  37968. case '"':
  37969. case '\'':
  37970. CppTokeniser::skipQuotedString (source);
  37971. result = tokenType_stringLiteral;
  37972. break;
  37973. case '+':
  37974. result = tokenType_operator;
  37975. source.skip();
  37976. if (source.peekNextChar() == '+')
  37977. source.skip();
  37978. else if (source.peekNextChar() == '=')
  37979. source.skip();
  37980. break;
  37981. case '-':
  37982. source.skip();
  37983. result = CppTokeniser::parseNumber (source);
  37984. if (result == tokenType_error)
  37985. {
  37986. result = tokenType_operator;
  37987. if (source.peekNextChar() == '-')
  37988. source.skip();
  37989. else if (source.peekNextChar() == '=')
  37990. source.skip();
  37991. }
  37992. break;
  37993. case '*':
  37994. case '%':
  37995. case '=':
  37996. case '!':
  37997. result = tokenType_operator;
  37998. source.skip();
  37999. if (source.peekNextChar() == '=')
  38000. source.skip();
  38001. break;
  38002. case '/':
  38003. result = tokenType_operator;
  38004. source.skip();
  38005. if (source.peekNextChar() == '=')
  38006. {
  38007. source.skip();
  38008. }
  38009. else if (source.peekNextChar() == '/')
  38010. {
  38011. result = tokenType_comment;
  38012. source.skipToEndOfLine();
  38013. }
  38014. else if (source.peekNextChar() == '*')
  38015. {
  38016. source.skip();
  38017. result = tokenType_comment;
  38018. CppTokeniser::skipComment (source);
  38019. }
  38020. break;
  38021. case '?':
  38022. case '~':
  38023. source.skip();
  38024. result = tokenType_operator;
  38025. break;
  38026. case '<':
  38027. source.skip();
  38028. result = tokenType_operator;
  38029. if (source.peekNextChar() == '=')
  38030. {
  38031. source.skip();
  38032. }
  38033. else if (source.peekNextChar() == '<')
  38034. {
  38035. source.skip();
  38036. if (source.peekNextChar() == '=')
  38037. source.skip();
  38038. }
  38039. break;
  38040. case '>':
  38041. source.skip();
  38042. result = tokenType_operator;
  38043. if (source.peekNextChar() == '=')
  38044. {
  38045. source.skip();
  38046. }
  38047. else if (source.peekNextChar() == '<')
  38048. {
  38049. source.skip();
  38050. if (source.peekNextChar() == '=')
  38051. source.skip();
  38052. }
  38053. break;
  38054. case '|':
  38055. source.skip();
  38056. result = tokenType_operator;
  38057. if (source.peekNextChar() == '=')
  38058. {
  38059. source.skip();
  38060. }
  38061. else if (source.peekNextChar() == '|')
  38062. {
  38063. source.skip();
  38064. if (source.peekNextChar() == '=')
  38065. source.skip();
  38066. }
  38067. break;
  38068. case '&':
  38069. source.skip();
  38070. result = tokenType_operator;
  38071. if (source.peekNextChar() == '=')
  38072. {
  38073. source.skip();
  38074. }
  38075. else if (source.peekNextChar() == '&')
  38076. {
  38077. source.skip();
  38078. if (source.peekNextChar() == '=')
  38079. source.skip();
  38080. }
  38081. break;
  38082. case '^':
  38083. source.skip();
  38084. result = tokenType_operator;
  38085. if (source.peekNextChar() == '=')
  38086. {
  38087. source.skip();
  38088. }
  38089. else if (source.peekNextChar() == '^')
  38090. {
  38091. source.skip();
  38092. if (source.peekNextChar() == '=')
  38093. source.skip();
  38094. }
  38095. break;
  38096. case '#':
  38097. result = tokenType_preprocessor;
  38098. source.skipToEndOfLine();
  38099. break;
  38100. default:
  38101. if (CppTokeniser::isIdentifierStart (firstChar))
  38102. result = CppTokeniser::parseIdentifier (source);
  38103. else
  38104. source.skip();
  38105. break;
  38106. }
  38107. return result;
  38108. }
  38109. const StringArray CPlusPlusCodeTokeniser::getTokenTypes()
  38110. {
  38111. const char* const types[] =
  38112. {
  38113. "Error",
  38114. "Comment",
  38115. "C++ keyword",
  38116. "Identifier",
  38117. "Integer literal",
  38118. "Float literal",
  38119. "String literal",
  38120. "Operator",
  38121. "Bracket",
  38122. "Punctuation",
  38123. "Preprocessor line",
  38124. 0
  38125. };
  38126. return StringArray (types);
  38127. }
  38128. const Colour CPlusPlusCodeTokeniser::getDefaultColour (const int tokenType)
  38129. {
  38130. const uint32 colours[] =
  38131. {
  38132. 0xffcc0000, // error
  38133. 0xff00aa00, // comment
  38134. 0xff0000cc, // keyword
  38135. 0xff000000, // identifier
  38136. 0xff880000, // int literal
  38137. 0xff885500, // float literal
  38138. 0xff990099, // string literal
  38139. 0xff225500, // operator
  38140. 0xff000055, // bracket
  38141. 0xff004400, // punctuation
  38142. 0xff660000 // preprocessor
  38143. };
  38144. if (tokenType >= 0 && tokenType < numElementsInArray (colours))
  38145. return Colour (colours [tokenType]);
  38146. return Colours::black;
  38147. }
  38148. bool CPlusPlusCodeTokeniser::isReservedKeyword (const String& token) throw()
  38149. {
  38150. return CppTokeniser::isReservedKeyword (token, token.length());
  38151. }
  38152. END_JUCE_NAMESPACE
  38153. /*** End of inlined file: juce_CPlusPlusCodeTokeniser.cpp ***/
  38154. /*** Start of inlined file: juce_ComboBox.cpp ***/
  38155. BEGIN_JUCE_NAMESPACE
  38156. ComboBox::ComboBox (const String& name)
  38157. : Component (name),
  38158. lastCurrentId (0),
  38159. isButtonDown (false),
  38160. separatorPending (false),
  38161. menuActive (false),
  38162. label (0)
  38163. {
  38164. noChoicesMessage = TRANS("(no choices)");
  38165. setRepaintsOnMouseActivity (true);
  38166. lookAndFeelChanged();
  38167. currentId.addListener (this);
  38168. }
  38169. ComboBox::~ComboBox()
  38170. {
  38171. currentId.removeListener (this);
  38172. if (menuActive)
  38173. PopupMenu::dismissAllActiveMenus();
  38174. label = 0;
  38175. deleteAllChildren();
  38176. }
  38177. void ComboBox::setEditableText (const bool isEditable)
  38178. {
  38179. if (label->isEditableOnSingleClick() != isEditable || label->isEditableOnDoubleClick() != isEditable)
  38180. {
  38181. label->setEditable (isEditable, isEditable, false);
  38182. setWantsKeyboardFocus (! isEditable);
  38183. resized();
  38184. }
  38185. }
  38186. bool ComboBox::isTextEditable() const throw()
  38187. {
  38188. return label->isEditable();
  38189. }
  38190. void ComboBox::setJustificationType (const Justification& justification)
  38191. {
  38192. label->setJustificationType (justification);
  38193. }
  38194. const Justification ComboBox::getJustificationType() const throw()
  38195. {
  38196. return label->getJustificationType();
  38197. }
  38198. void ComboBox::setTooltip (const String& newTooltip)
  38199. {
  38200. SettableTooltipClient::setTooltip (newTooltip);
  38201. label->setTooltip (newTooltip);
  38202. }
  38203. void ComboBox::addItem (const String& newItemText, const int newItemId)
  38204. {
  38205. // you can't add empty strings to the list..
  38206. jassert (newItemText.isNotEmpty());
  38207. // IDs must be non-zero, as zero is used to indicate a lack of selecion.
  38208. jassert (newItemId != 0);
  38209. // you shouldn't use duplicate item IDs!
  38210. jassert (getItemForId (newItemId) == 0);
  38211. if (newItemText.isNotEmpty() && newItemId != 0)
  38212. {
  38213. if (separatorPending)
  38214. {
  38215. separatorPending = false;
  38216. ItemInfo* const item = new ItemInfo();
  38217. item->itemId = 0;
  38218. item->isEnabled = false;
  38219. item->isHeading = false;
  38220. items.add (item);
  38221. }
  38222. ItemInfo* const item = new ItemInfo();
  38223. item->name = newItemText;
  38224. item->itemId = newItemId;
  38225. item->isEnabled = true;
  38226. item->isHeading = false;
  38227. items.add (item);
  38228. }
  38229. }
  38230. void ComboBox::addSeparator()
  38231. {
  38232. separatorPending = (items.size() > 0);
  38233. }
  38234. void ComboBox::addSectionHeading (const String& headingName)
  38235. {
  38236. // you can't add empty strings to the list..
  38237. jassert (headingName.isNotEmpty());
  38238. if (headingName.isNotEmpty())
  38239. {
  38240. if (separatorPending)
  38241. {
  38242. separatorPending = false;
  38243. ItemInfo* const item = new ItemInfo();
  38244. item->itemId = 0;
  38245. item->isEnabled = false;
  38246. item->isHeading = false;
  38247. items.add (item);
  38248. }
  38249. ItemInfo* const item = new ItemInfo();
  38250. item->name = headingName;
  38251. item->itemId = 0;
  38252. item->isEnabled = true;
  38253. item->isHeading = true;
  38254. items.add (item);
  38255. }
  38256. }
  38257. void ComboBox::setItemEnabled (const int itemId, const bool shouldBeEnabled)
  38258. {
  38259. ItemInfo* const item = getItemForId (itemId);
  38260. if (item != 0)
  38261. item->isEnabled = shouldBeEnabled;
  38262. }
  38263. void ComboBox::changeItemText (const int itemId, const String& newText)
  38264. {
  38265. ItemInfo* const item = getItemForId (itemId);
  38266. jassert (item != 0);
  38267. if (item != 0)
  38268. item->name = newText;
  38269. }
  38270. void ComboBox::clear (const bool dontSendChangeMessage)
  38271. {
  38272. items.clear();
  38273. separatorPending = false;
  38274. if (! label->isEditable())
  38275. setSelectedItemIndex (-1, dontSendChangeMessage);
  38276. }
  38277. bool ComboBox::ItemInfo::isSeparator() const throw()
  38278. {
  38279. return name.isEmpty();
  38280. }
  38281. bool ComboBox::ItemInfo::isRealItem() const throw()
  38282. {
  38283. return ! (isHeading || name.isEmpty());
  38284. }
  38285. ComboBox::ItemInfo* ComboBox::getItemForId (const int itemId) const throw()
  38286. {
  38287. if (itemId != 0)
  38288. {
  38289. for (int i = items.size(); --i >= 0;)
  38290. if (items.getUnchecked(i)->itemId == itemId)
  38291. return items.getUnchecked(i);
  38292. }
  38293. return 0;
  38294. }
  38295. ComboBox::ItemInfo* ComboBox::getItemForIndex (const int index) const throw()
  38296. {
  38297. int n = 0;
  38298. for (int i = 0; i < items.size(); ++i)
  38299. {
  38300. ItemInfo* const item = items.getUnchecked(i);
  38301. if (item->isRealItem())
  38302. if (n++ == index)
  38303. return item;
  38304. }
  38305. return 0;
  38306. }
  38307. int ComboBox::getNumItems() const throw()
  38308. {
  38309. int n = 0;
  38310. for (int i = items.size(); --i >= 0;)
  38311. if (items.getUnchecked(i)->isRealItem())
  38312. ++n;
  38313. return n;
  38314. }
  38315. const String ComboBox::getItemText (const int index) const
  38316. {
  38317. const ItemInfo* const item = getItemForIndex (index);
  38318. if (item != 0)
  38319. return item->name;
  38320. return String::empty;
  38321. }
  38322. int ComboBox::getItemId (const int index) const throw()
  38323. {
  38324. const ItemInfo* const item = getItemForIndex (index);
  38325. return (item != 0) ? item->itemId : 0;
  38326. }
  38327. int ComboBox::indexOfItemId (const int itemId) const throw()
  38328. {
  38329. int n = 0;
  38330. for (int i = 0; i < items.size(); ++i)
  38331. {
  38332. const ItemInfo* const item = items.getUnchecked(i);
  38333. if (item->isRealItem())
  38334. {
  38335. if (item->itemId == itemId)
  38336. return n;
  38337. ++n;
  38338. }
  38339. }
  38340. return -1;
  38341. }
  38342. int ComboBox::getSelectedItemIndex() const
  38343. {
  38344. int index = indexOfItemId (currentId.getValue());
  38345. if (getText() != getItemText (index))
  38346. index = -1;
  38347. return index;
  38348. }
  38349. void ComboBox::setSelectedItemIndex (const int index, const bool dontSendChangeMessage)
  38350. {
  38351. setSelectedId (getItemId (index), dontSendChangeMessage);
  38352. }
  38353. int ComboBox::getSelectedId() const throw()
  38354. {
  38355. const ItemInfo* const item = getItemForId (currentId.getValue());
  38356. return (item != 0 && getText() == item->name) ? item->itemId : 0;
  38357. }
  38358. void ComboBox::setSelectedId (const int newItemId, const bool dontSendChangeMessage)
  38359. {
  38360. const ItemInfo* const item = getItemForId (newItemId);
  38361. const String newItemText (item != 0 ? item->name : String::empty);
  38362. if (lastCurrentId != newItemId || label->getText() != newItemText)
  38363. {
  38364. if (! dontSendChangeMessage)
  38365. triggerAsyncUpdate();
  38366. label->setText (newItemText, false);
  38367. lastCurrentId = newItemId;
  38368. currentId = newItemId;
  38369. repaint(); // for the benefit of the 'none selected' text
  38370. }
  38371. }
  38372. void ComboBox::valueChanged (Value&)
  38373. {
  38374. if (lastCurrentId != (int) currentId.getValue())
  38375. setSelectedId (currentId.getValue(), false);
  38376. }
  38377. const String ComboBox::getText() const
  38378. {
  38379. return label->getText();
  38380. }
  38381. void ComboBox::setText (const String& newText, const bool dontSendChangeMessage)
  38382. {
  38383. for (int i = items.size(); --i >= 0;)
  38384. {
  38385. const ItemInfo* const item = items.getUnchecked(i);
  38386. if (item->isRealItem()
  38387. && item->name == newText)
  38388. {
  38389. setSelectedId (item->itemId, dontSendChangeMessage);
  38390. return;
  38391. }
  38392. }
  38393. lastCurrentId = 0;
  38394. currentId = 0;
  38395. if (label->getText() != newText)
  38396. {
  38397. label->setText (newText, false);
  38398. if (! dontSendChangeMessage)
  38399. triggerAsyncUpdate();
  38400. }
  38401. repaint();
  38402. }
  38403. void ComboBox::showEditor()
  38404. {
  38405. jassert (isTextEditable()); // you probably shouldn't do this to a non-editable combo box?
  38406. label->showEditor();
  38407. }
  38408. void ComboBox::setTextWhenNothingSelected (const String& newMessage)
  38409. {
  38410. if (textWhenNothingSelected != newMessage)
  38411. {
  38412. textWhenNothingSelected = newMessage;
  38413. repaint();
  38414. }
  38415. }
  38416. const String ComboBox::getTextWhenNothingSelected() const
  38417. {
  38418. return textWhenNothingSelected;
  38419. }
  38420. void ComboBox::setTextWhenNoChoicesAvailable (const String& newMessage)
  38421. {
  38422. noChoicesMessage = newMessage;
  38423. }
  38424. const String ComboBox::getTextWhenNoChoicesAvailable() const
  38425. {
  38426. return noChoicesMessage;
  38427. }
  38428. void ComboBox::paint (Graphics& g)
  38429. {
  38430. getLookAndFeel().drawComboBox (g,
  38431. getWidth(),
  38432. getHeight(),
  38433. isButtonDown,
  38434. label->getRight(),
  38435. 0,
  38436. getWidth() - label->getRight(),
  38437. getHeight(),
  38438. *this);
  38439. if (textWhenNothingSelected.isNotEmpty()
  38440. && label->getText().isEmpty()
  38441. && ! label->isBeingEdited())
  38442. {
  38443. g.setColour (findColour (textColourId).withMultipliedAlpha (0.5f));
  38444. g.setFont (label->getFont());
  38445. g.drawFittedText (textWhenNothingSelected,
  38446. label->getX() + 2, label->getY() + 1,
  38447. label->getWidth() - 4, label->getHeight() - 2,
  38448. label->getJustificationType(),
  38449. jmax (1, (int) (label->getHeight() / label->getFont().getHeight())));
  38450. }
  38451. }
  38452. void ComboBox::resized()
  38453. {
  38454. if (getHeight() > 0 && getWidth() > 0)
  38455. getLookAndFeel().positionComboBoxText (*this, *label);
  38456. }
  38457. void ComboBox::enablementChanged()
  38458. {
  38459. repaint();
  38460. }
  38461. void ComboBox::lookAndFeelChanged()
  38462. {
  38463. repaint();
  38464. Label* const newLabel = getLookAndFeel().createComboBoxTextBox (*this);
  38465. if (label != 0)
  38466. {
  38467. newLabel->setEditable (label->isEditable());
  38468. newLabel->setJustificationType (label->getJustificationType());
  38469. newLabel->setTooltip (label->getTooltip());
  38470. newLabel->setText (label->getText(), false);
  38471. }
  38472. label = newLabel;
  38473. addAndMakeVisible (newLabel);
  38474. newLabel->addListener (this);
  38475. newLabel->addMouseListener (this, false);
  38476. newLabel->setColour (Label::backgroundColourId, Colours::transparentBlack);
  38477. newLabel->setColour (Label::textColourId, findColour (ComboBox::textColourId));
  38478. newLabel->setColour (TextEditor::textColourId, findColour (ComboBox::textColourId));
  38479. newLabel->setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  38480. newLabel->setColour (TextEditor::highlightColourId, findColour (TextEditor::highlightColourId));
  38481. newLabel->setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  38482. resized();
  38483. }
  38484. void ComboBox::colourChanged()
  38485. {
  38486. lookAndFeelChanged();
  38487. }
  38488. bool ComboBox::keyPressed (const KeyPress& key)
  38489. {
  38490. bool used = false;
  38491. if (key.isKeyCode (KeyPress::upKey)
  38492. || key.isKeyCode (KeyPress::leftKey))
  38493. {
  38494. setSelectedItemIndex (jmax (0, getSelectedItemIndex() - 1));
  38495. used = true;
  38496. }
  38497. else if (key.isKeyCode (KeyPress::downKey)
  38498. || key.isKeyCode (KeyPress::rightKey))
  38499. {
  38500. setSelectedItemIndex (jmin (getSelectedItemIndex() + 1, getNumItems() - 1));
  38501. used = true;
  38502. }
  38503. else if (key.isKeyCode (KeyPress::returnKey))
  38504. {
  38505. showPopup();
  38506. used = true;
  38507. }
  38508. return used;
  38509. }
  38510. bool ComboBox::keyStateChanged (const bool isKeyDown)
  38511. {
  38512. // only forward key events that aren't used by this component
  38513. return isKeyDown
  38514. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  38515. || KeyPress::isKeyCurrentlyDown (KeyPress::leftKey)
  38516. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  38517. || KeyPress::isKeyCurrentlyDown (KeyPress::rightKey));
  38518. }
  38519. void ComboBox::focusGained (FocusChangeType)
  38520. {
  38521. repaint();
  38522. }
  38523. void ComboBox::focusLost (FocusChangeType)
  38524. {
  38525. repaint();
  38526. }
  38527. void ComboBox::labelTextChanged (Label*)
  38528. {
  38529. triggerAsyncUpdate();
  38530. }
  38531. class ComboBox::Callback : public ModalComponentManager::Callback
  38532. {
  38533. public:
  38534. Callback (ComboBox* const box_)
  38535. : box (box_)
  38536. {
  38537. }
  38538. void modalStateFinished (int returnValue)
  38539. {
  38540. if (box != 0)
  38541. {
  38542. box->menuActive = false;
  38543. if (returnValue != 0)
  38544. box->setSelectedId (returnValue);
  38545. }
  38546. }
  38547. private:
  38548. Component::SafePointer<ComboBox> box;
  38549. Callback (const Callback&);
  38550. Callback& operator= (const Callback&);
  38551. };
  38552. void ComboBox::showPopup()
  38553. {
  38554. if (! menuActive)
  38555. {
  38556. const int selectedId = getSelectedId();
  38557. PopupMenu menu;
  38558. menu.setLookAndFeel (&getLookAndFeel());
  38559. for (int i = 0; i < items.size(); ++i)
  38560. {
  38561. const ItemInfo* const item = items.getUnchecked(i);
  38562. if (item->isSeparator())
  38563. menu.addSeparator();
  38564. else if (item->isHeading)
  38565. menu.addSectionHeader (item->name);
  38566. else
  38567. menu.addItem (item->itemId, item->name,
  38568. item->isEnabled, item->itemId == selectedId);
  38569. }
  38570. if (items.size() == 0)
  38571. menu.addItem (1, noChoicesMessage, false);
  38572. menuActive = true;
  38573. menu.showAt (this, selectedId, getWidth(), 1, jlimit (12, 24, getHeight()),
  38574. new Callback (this));
  38575. }
  38576. }
  38577. void ComboBox::mouseDown (const MouseEvent& e)
  38578. {
  38579. beginDragAutoRepeat (300);
  38580. isButtonDown = isEnabled();
  38581. if (isButtonDown
  38582. && (e.eventComponent == this || ! label->isEditable()))
  38583. {
  38584. showPopup();
  38585. }
  38586. }
  38587. void ComboBox::mouseDrag (const MouseEvent& e)
  38588. {
  38589. beginDragAutoRepeat (50);
  38590. if (isButtonDown && ! e.mouseWasClicked())
  38591. showPopup();
  38592. }
  38593. void ComboBox::mouseUp (const MouseEvent& e2)
  38594. {
  38595. if (isButtonDown)
  38596. {
  38597. isButtonDown = false;
  38598. repaint();
  38599. const MouseEvent e (e2.getEventRelativeTo (this));
  38600. if (reallyContains (e.x, e.y, true)
  38601. && (e2.eventComponent == this || ! label->isEditable()))
  38602. {
  38603. showPopup();
  38604. }
  38605. }
  38606. }
  38607. void ComboBox::addListener (Listener* const listener)
  38608. {
  38609. listeners.add (listener);
  38610. }
  38611. void ComboBox::removeListener (Listener* const listener)
  38612. {
  38613. listeners.remove (listener);
  38614. }
  38615. void ComboBox::handleAsyncUpdate()
  38616. {
  38617. Component::BailOutChecker checker (this);
  38618. listeners.callChecked (checker, &ComboBoxListener::comboBoxChanged, this); // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  38619. }
  38620. END_JUCE_NAMESPACE
  38621. /*** End of inlined file: juce_ComboBox.cpp ***/
  38622. /*** Start of inlined file: juce_Label.cpp ***/
  38623. BEGIN_JUCE_NAMESPACE
  38624. Label::Label (const String& componentName,
  38625. const String& labelText)
  38626. : Component (componentName),
  38627. textValue (labelText),
  38628. lastTextValue (labelText),
  38629. font (15.0f),
  38630. justification (Justification::centredLeft),
  38631. ownerComponent (0),
  38632. horizontalBorderSize (5),
  38633. verticalBorderSize (1),
  38634. minimumHorizontalScale (0.7f),
  38635. editSingleClick (false),
  38636. editDoubleClick (false),
  38637. lossOfFocusDiscardsChanges (false)
  38638. {
  38639. setColour (TextEditor::textColourId, Colours::black);
  38640. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  38641. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  38642. textValue.addListener (this);
  38643. }
  38644. Label::~Label()
  38645. {
  38646. textValue.removeListener (this);
  38647. if (ownerComponent != 0)
  38648. ownerComponent->removeComponentListener (this);
  38649. editor = 0;
  38650. }
  38651. void Label::setText (const String& newText,
  38652. const bool broadcastChangeMessage)
  38653. {
  38654. hideEditor (true);
  38655. if (lastTextValue != newText)
  38656. {
  38657. lastTextValue = newText;
  38658. textValue = newText;
  38659. repaint();
  38660. textWasChanged();
  38661. if (ownerComponent != 0)
  38662. componentMovedOrResized (*ownerComponent, true, true);
  38663. if (broadcastChangeMessage)
  38664. callChangeListeners();
  38665. }
  38666. }
  38667. const String Label::getText (const bool returnActiveEditorContents) const
  38668. {
  38669. return (returnActiveEditorContents && isBeingEdited())
  38670. ? editor->getText()
  38671. : textValue.toString();
  38672. }
  38673. void Label::valueChanged (Value&)
  38674. {
  38675. if (lastTextValue != textValue.toString())
  38676. setText (textValue.toString(), true);
  38677. }
  38678. void Label::setFont (const Font& newFont)
  38679. {
  38680. if (font != newFont)
  38681. {
  38682. font = newFont;
  38683. repaint();
  38684. }
  38685. }
  38686. const Font& Label::getFont() const throw()
  38687. {
  38688. return font;
  38689. }
  38690. void Label::setEditable (const bool editOnSingleClick,
  38691. const bool editOnDoubleClick,
  38692. const bool lossOfFocusDiscardsChanges_)
  38693. {
  38694. editSingleClick = editOnSingleClick;
  38695. editDoubleClick = editOnDoubleClick;
  38696. lossOfFocusDiscardsChanges = lossOfFocusDiscardsChanges_;
  38697. setWantsKeyboardFocus (editOnSingleClick || editOnDoubleClick);
  38698. setFocusContainer (editOnSingleClick || editOnDoubleClick);
  38699. }
  38700. void Label::setJustificationType (const Justification& newJustification)
  38701. {
  38702. if (justification != newJustification)
  38703. {
  38704. justification = newJustification;
  38705. repaint();
  38706. }
  38707. }
  38708. void Label::setBorderSize (int h, int v)
  38709. {
  38710. if (horizontalBorderSize != h || verticalBorderSize != v)
  38711. {
  38712. horizontalBorderSize = h;
  38713. verticalBorderSize = v;
  38714. repaint();
  38715. }
  38716. }
  38717. Component* Label::getAttachedComponent() const
  38718. {
  38719. return static_cast<Component*> (ownerComponent);
  38720. }
  38721. void Label::attachToComponent (Component* owner,
  38722. const bool onLeft)
  38723. {
  38724. if (ownerComponent != 0)
  38725. ownerComponent->removeComponentListener (this);
  38726. ownerComponent = owner;
  38727. leftOfOwnerComp = onLeft;
  38728. if (ownerComponent != 0)
  38729. {
  38730. setVisible (owner->isVisible());
  38731. ownerComponent->addComponentListener (this);
  38732. componentParentHierarchyChanged (*ownerComponent);
  38733. componentMovedOrResized (*ownerComponent, true, true);
  38734. }
  38735. }
  38736. void Label::componentMovedOrResized (Component& component, bool /*wasMoved*/, bool /*wasResized*/)
  38737. {
  38738. if (leftOfOwnerComp)
  38739. {
  38740. setSize (jmin (getFont().getStringWidth (textValue.toString()) + 8, component.getX()),
  38741. component.getHeight());
  38742. setTopRightPosition (component.getX(), component.getY());
  38743. }
  38744. else
  38745. {
  38746. setSize (component.getWidth(),
  38747. 8 + roundToInt (getFont().getHeight()));
  38748. setTopLeftPosition (component.getX(), component.getY() - getHeight());
  38749. }
  38750. }
  38751. void Label::componentParentHierarchyChanged (Component& component)
  38752. {
  38753. if (component.getParentComponent() != 0)
  38754. component.getParentComponent()->addChildComponent (this);
  38755. }
  38756. void Label::componentVisibilityChanged (Component& component)
  38757. {
  38758. setVisible (component.isVisible());
  38759. }
  38760. void Label::textWasEdited()
  38761. {
  38762. }
  38763. void Label::textWasChanged()
  38764. {
  38765. }
  38766. void Label::showEditor()
  38767. {
  38768. if (editor == 0)
  38769. {
  38770. addAndMakeVisible (editor = createEditorComponent());
  38771. editor->setText (getText(), false);
  38772. editor->addListener (this);
  38773. editor->grabKeyboardFocus();
  38774. editor->setHighlightedRegion (Range<int> (0, textValue.toString().length()));
  38775. editor->addListener (this);
  38776. resized();
  38777. repaint();
  38778. editorShown (editor);
  38779. enterModalState (false);
  38780. editor->grabKeyboardFocus();
  38781. }
  38782. }
  38783. void Label::editorShown (TextEditor* /*editorComponent*/)
  38784. {
  38785. }
  38786. void Label::editorAboutToBeHidden (TextEditor* /*editorComponent*/)
  38787. {
  38788. }
  38789. bool Label::updateFromTextEditorContents()
  38790. {
  38791. jassert (editor != 0);
  38792. const String newText (editor->getText());
  38793. if (textValue.toString() != newText)
  38794. {
  38795. lastTextValue = newText;
  38796. textValue = newText;
  38797. repaint();
  38798. textWasChanged();
  38799. if (ownerComponent != 0)
  38800. componentMovedOrResized (*ownerComponent, true, true);
  38801. return true;
  38802. }
  38803. return false;
  38804. }
  38805. void Label::hideEditor (const bool discardCurrentEditorContents)
  38806. {
  38807. if (editor != 0)
  38808. {
  38809. Component::SafePointer<Component> deletionChecker (this);
  38810. editorAboutToBeHidden (editor);
  38811. const bool changed = (! discardCurrentEditorContents)
  38812. && updateFromTextEditorContents();
  38813. editor = 0;
  38814. repaint();
  38815. if (changed)
  38816. textWasEdited();
  38817. if (deletionChecker != 0)
  38818. exitModalState (0);
  38819. if (changed && deletionChecker != 0)
  38820. callChangeListeners();
  38821. }
  38822. }
  38823. void Label::inputAttemptWhenModal()
  38824. {
  38825. if (editor != 0)
  38826. {
  38827. if (lossOfFocusDiscardsChanges)
  38828. textEditorEscapeKeyPressed (*editor);
  38829. else
  38830. textEditorReturnKeyPressed (*editor);
  38831. }
  38832. }
  38833. bool Label::isBeingEdited() const throw()
  38834. {
  38835. return editor != 0;
  38836. }
  38837. TextEditor* Label::createEditorComponent()
  38838. {
  38839. TextEditor* const ed = new TextEditor (getName());
  38840. ed->setFont (font);
  38841. // copy these colours from our own settings..
  38842. const int cols[] = { TextEditor::backgroundColourId,
  38843. TextEditor::textColourId,
  38844. TextEditor::highlightColourId,
  38845. TextEditor::highlightedTextColourId,
  38846. TextEditor::caretColourId,
  38847. TextEditor::outlineColourId,
  38848. TextEditor::focusedOutlineColourId,
  38849. TextEditor::shadowColourId };
  38850. for (int i = 0; i < numElementsInArray (cols); ++i)
  38851. ed->setColour (cols[i], findColour (cols[i]));
  38852. return ed;
  38853. }
  38854. void Label::paint (Graphics& g)
  38855. {
  38856. getLookAndFeel().drawLabel (g, *this);
  38857. }
  38858. void Label::mouseUp (const MouseEvent& e)
  38859. {
  38860. if (editSingleClick
  38861. && e.mouseWasClicked()
  38862. && contains (e.x, e.y)
  38863. && ! e.mods.isPopupMenu())
  38864. {
  38865. showEditor();
  38866. }
  38867. }
  38868. void Label::mouseDoubleClick (const MouseEvent& e)
  38869. {
  38870. if (editDoubleClick && ! e.mods.isPopupMenu())
  38871. showEditor();
  38872. }
  38873. void Label::resized()
  38874. {
  38875. if (editor != 0)
  38876. editor->setBoundsInset (BorderSize (0));
  38877. }
  38878. void Label::focusGained (FocusChangeType cause)
  38879. {
  38880. if (editSingleClick && cause == focusChangedByTabKey)
  38881. showEditor();
  38882. }
  38883. void Label::enablementChanged()
  38884. {
  38885. repaint();
  38886. }
  38887. void Label::colourChanged()
  38888. {
  38889. repaint();
  38890. }
  38891. void Label::setMinimumHorizontalScale (const float newScale)
  38892. {
  38893. if (minimumHorizontalScale != newScale)
  38894. {
  38895. minimumHorizontalScale = newScale;
  38896. repaint();
  38897. }
  38898. }
  38899. // We'll use a custom focus traverser here to make sure focus goes from the
  38900. // text editor to another component rather than back to the label itself.
  38901. class LabelKeyboardFocusTraverser : public KeyboardFocusTraverser
  38902. {
  38903. public:
  38904. LabelKeyboardFocusTraverser() {}
  38905. Component* getNextComponent (Component* current)
  38906. {
  38907. return KeyboardFocusTraverser::getNextComponent (dynamic_cast <TextEditor*> (current) != 0
  38908. ? current->getParentComponent() : current);
  38909. }
  38910. Component* getPreviousComponent (Component* current)
  38911. {
  38912. return KeyboardFocusTraverser::getPreviousComponent (dynamic_cast <TextEditor*> (current) != 0
  38913. ? current->getParentComponent() : current);
  38914. }
  38915. };
  38916. KeyboardFocusTraverser* Label::createFocusTraverser()
  38917. {
  38918. return new LabelKeyboardFocusTraverser();
  38919. }
  38920. void Label::addListener (Listener* const listener)
  38921. {
  38922. listeners.add (listener);
  38923. }
  38924. void Label::removeListener (Listener* const listener)
  38925. {
  38926. listeners.remove (listener);
  38927. }
  38928. void Label::callChangeListeners()
  38929. {
  38930. Component::BailOutChecker checker (this);
  38931. listeners.callChecked (checker, &LabelListener::labelTextChanged, this); // (can't use Label::Listener due to idiotic VC2005 bug)
  38932. }
  38933. void Label::textEditorTextChanged (TextEditor& ed)
  38934. {
  38935. if (editor != 0)
  38936. {
  38937. jassert (&ed == editor);
  38938. if (! (hasKeyboardFocus (true) || isCurrentlyBlockedByAnotherModalComponent()))
  38939. {
  38940. if (lossOfFocusDiscardsChanges)
  38941. textEditorEscapeKeyPressed (ed);
  38942. else
  38943. textEditorReturnKeyPressed (ed);
  38944. }
  38945. }
  38946. }
  38947. void Label::textEditorReturnKeyPressed (TextEditor& ed)
  38948. {
  38949. if (editor != 0)
  38950. {
  38951. jassert (&ed == editor);
  38952. (void) ed;
  38953. const bool changed = updateFromTextEditorContents();
  38954. hideEditor (true);
  38955. if (changed)
  38956. {
  38957. Component::SafePointer<Component> deletionChecker (this);
  38958. textWasEdited();
  38959. if (deletionChecker != 0)
  38960. callChangeListeners();
  38961. }
  38962. }
  38963. }
  38964. void Label::textEditorEscapeKeyPressed (TextEditor& ed)
  38965. {
  38966. if (editor != 0)
  38967. {
  38968. jassert (&ed == editor);
  38969. (void) ed;
  38970. editor->setText (textValue.toString(), false);
  38971. hideEditor (true);
  38972. }
  38973. }
  38974. void Label::textEditorFocusLost (TextEditor& ed)
  38975. {
  38976. textEditorTextChanged (ed);
  38977. }
  38978. END_JUCE_NAMESPACE
  38979. /*** End of inlined file: juce_Label.cpp ***/
  38980. /*** Start of inlined file: juce_ListBox.cpp ***/
  38981. BEGIN_JUCE_NAMESPACE
  38982. class ListBoxRowComponent : public Component,
  38983. public TooltipClient
  38984. {
  38985. public:
  38986. ListBoxRowComponent (ListBox& owner_)
  38987. : owner (owner_), row (-1),
  38988. selected (false), isDragging (false), selectRowOnMouseUp (false)
  38989. {
  38990. }
  38991. void paint (Graphics& g)
  38992. {
  38993. if (owner.getModel() != 0)
  38994. owner.getModel()->paintListBoxItem (row, g, getWidth(), getHeight(), selected);
  38995. }
  38996. void update (const int row_, const bool selected_)
  38997. {
  38998. if (row != row_ || selected != selected_)
  38999. {
  39000. repaint();
  39001. row = row_;
  39002. selected = selected_;
  39003. }
  39004. if (owner.getModel() != 0)
  39005. {
  39006. customComponent = owner.getModel()->refreshComponentForRow (row_, selected_, customComponent.release());
  39007. if (customComponent != 0)
  39008. {
  39009. addAndMakeVisible (customComponent);
  39010. customComponent->setBounds (getLocalBounds());
  39011. }
  39012. }
  39013. }
  39014. void mouseDown (const MouseEvent& e)
  39015. {
  39016. isDragging = false;
  39017. selectRowOnMouseUp = false;
  39018. if (isEnabled())
  39019. {
  39020. if (! selected)
  39021. {
  39022. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  39023. if (owner.getModel() != 0)
  39024. owner.getModel()->listBoxItemClicked (row, e);
  39025. }
  39026. else
  39027. {
  39028. selectRowOnMouseUp = true;
  39029. }
  39030. }
  39031. }
  39032. void mouseUp (const MouseEvent& e)
  39033. {
  39034. if (isEnabled() && selectRowOnMouseUp && ! isDragging)
  39035. {
  39036. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  39037. if (owner.getModel() != 0)
  39038. owner.getModel()->listBoxItemClicked (row, e);
  39039. }
  39040. }
  39041. void mouseDoubleClick (const MouseEvent& e)
  39042. {
  39043. if (owner.getModel() != 0 && isEnabled())
  39044. owner.getModel()->listBoxItemDoubleClicked (row, e);
  39045. }
  39046. void mouseDrag (const MouseEvent& e)
  39047. {
  39048. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  39049. {
  39050. const SparseSet<int> selectedRows (owner.getSelectedRows());
  39051. if (selectedRows.size() > 0)
  39052. {
  39053. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  39054. if (dragDescription.isNotEmpty())
  39055. {
  39056. isDragging = true;
  39057. owner.startDragAndDrop (e, dragDescription);
  39058. }
  39059. }
  39060. }
  39061. }
  39062. void resized()
  39063. {
  39064. if (customComponent != 0)
  39065. customComponent->setBounds (getLocalBounds());
  39066. }
  39067. const String getTooltip()
  39068. {
  39069. if (owner.getModel() != 0)
  39070. return owner.getModel()->getTooltipForRow (row);
  39071. return String::empty;
  39072. }
  39073. juce_UseDebuggingNewOperator
  39074. ScopedPointer<Component> customComponent;
  39075. private:
  39076. ListBox& owner;
  39077. int row;
  39078. bool selected, isDragging, selectRowOnMouseUp;
  39079. ListBoxRowComponent (const ListBoxRowComponent&);
  39080. ListBoxRowComponent& operator= (const ListBoxRowComponent&);
  39081. };
  39082. class ListViewport : public Viewport
  39083. {
  39084. public:
  39085. ListViewport (ListBox& owner_)
  39086. : owner (owner_)
  39087. {
  39088. setWantsKeyboardFocus (false);
  39089. Component* const content = new Component();
  39090. setViewedComponent (content);
  39091. content->addMouseListener (this, false);
  39092. content->setWantsKeyboardFocus (false);
  39093. }
  39094. ~ListViewport()
  39095. {
  39096. }
  39097. ListBoxRowComponent* getComponentForRow (const int row) const throw()
  39098. {
  39099. return rows [row % jmax (1, rows.size())];
  39100. }
  39101. ListBoxRowComponent* getComponentForRowIfOnscreen (const int row) const throw()
  39102. {
  39103. return (row >= firstIndex && row < firstIndex + rows.size())
  39104. ? getComponentForRow (row) : 0;
  39105. }
  39106. int getRowNumberOfComponent (Component* const rowComponent) const throw()
  39107. {
  39108. const int index = getIndexOfChildComponent (rowComponent);
  39109. const int num = rows.size();
  39110. for (int i = num; --i >= 0;)
  39111. if (((firstIndex + i) % jmax (1, num)) == index)
  39112. return firstIndex + i;
  39113. return -1;
  39114. }
  39115. void visibleAreaChanged (int, int, int, int)
  39116. {
  39117. updateVisibleArea (true);
  39118. if (owner.getModel() != 0)
  39119. owner.getModel()->listWasScrolled();
  39120. }
  39121. void updateVisibleArea (const bool makeSureItUpdatesContent)
  39122. {
  39123. hasUpdated = false;
  39124. const int newX = getViewedComponent()->getX();
  39125. int newY = getViewedComponent()->getY();
  39126. const int newW = jmax (owner.minimumRowWidth, getMaximumVisibleWidth());
  39127. const int newH = owner.totalItems * owner.getRowHeight();
  39128. if (newY + newH < getMaximumVisibleHeight() && newH > getMaximumVisibleHeight())
  39129. newY = getMaximumVisibleHeight() - newH;
  39130. getViewedComponent()->setBounds (newX, newY, newW, newH);
  39131. if (makeSureItUpdatesContent && ! hasUpdated)
  39132. updateContents();
  39133. }
  39134. void updateContents()
  39135. {
  39136. hasUpdated = true;
  39137. const int rowHeight = owner.getRowHeight();
  39138. if (rowHeight > 0)
  39139. {
  39140. const int y = getViewPositionY();
  39141. const int w = getViewedComponent()->getWidth();
  39142. const int numNeeded = 2 + getMaximumVisibleHeight() / rowHeight;
  39143. rows.removeRange (numNeeded, rows.size());
  39144. while (numNeeded > rows.size())
  39145. {
  39146. ListBoxRowComponent* newRow = new ListBoxRowComponent (owner);
  39147. rows.add (newRow);
  39148. getViewedComponent()->addAndMakeVisible (newRow);
  39149. }
  39150. firstIndex = y / rowHeight;
  39151. firstWholeIndex = (y + rowHeight - 1) / rowHeight;
  39152. lastWholeIndex = (y + getMaximumVisibleHeight() - 1) / rowHeight;
  39153. for (int i = 0; i < numNeeded; ++i)
  39154. {
  39155. const int row = i + firstIndex;
  39156. ListBoxRowComponent* const rowComp = getComponentForRow (row);
  39157. if (rowComp != 0)
  39158. {
  39159. rowComp->setBounds (0, row * rowHeight, w, rowHeight);
  39160. rowComp->update (row, owner.isRowSelected (row));
  39161. }
  39162. }
  39163. }
  39164. if (owner.headerComponent != 0)
  39165. owner.headerComponent->setBounds (owner.outlineThickness + getViewedComponent()->getX(),
  39166. owner.outlineThickness,
  39167. jmax (owner.getWidth() - owner.outlineThickness * 2,
  39168. getViewedComponent()->getWidth()),
  39169. owner.headerComponent->getHeight());
  39170. }
  39171. void selectRow (const int row, const int rowHeight, const bool dontScroll,
  39172. const int lastRowSelected, const int totalItems, const bool isMouseClick)
  39173. {
  39174. hasUpdated = false;
  39175. if (row < firstWholeIndex && ! dontScroll)
  39176. {
  39177. setViewPosition (getViewPositionX(), row * rowHeight);
  39178. }
  39179. else if (row >= lastWholeIndex && ! dontScroll)
  39180. {
  39181. const int rowsOnScreen = lastWholeIndex - firstWholeIndex;
  39182. if (row >= lastRowSelected + rowsOnScreen
  39183. && rowsOnScreen < totalItems - 1
  39184. && ! isMouseClick)
  39185. {
  39186. setViewPosition (getViewPositionX(),
  39187. jlimit (0, jmax (0, totalItems - rowsOnScreen), row) * rowHeight);
  39188. }
  39189. else
  39190. {
  39191. setViewPosition (getViewPositionX(),
  39192. jmax (0, (row + 1) * rowHeight - getMaximumVisibleHeight()));
  39193. }
  39194. }
  39195. if (! hasUpdated)
  39196. updateContents();
  39197. }
  39198. void scrollToEnsureRowIsOnscreen (const int row, const int rowHeight)
  39199. {
  39200. if (row < firstWholeIndex)
  39201. {
  39202. setViewPosition (getViewPositionX(), row * rowHeight);
  39203. }
  39204. else if (row >= lastWholeIndex)
  39205. {
  39206. setViewPosition (getViewPositionX(),
  39207. jmax (0, (row + 1) * rowHeight - getMaximumVisibleHeight()));
  39208. }
  39209. }
  39210. void paint (Graphics& g)
  39211. {
  39212. if (isOpaque())
  39213. g.fillAll (owner.findColour (ListBox::backgroundColourId));
  39214. }
  39215. bool keyPressed (const KeyPress& key)
  39216. {
  39217. if (key.isKeyCode (KeyPress::upKey)
  39218. || key.isKeyCode (KeyPress::downKey)
  39219. || key.isKeyCode (KeyPress::pageUpKey)
  39220. || key.isKeyCode (KeyPress::pageDownKey)
  39221. || key.isKeyCode (KeyPress::homeKey)
  39222. || key.isKeyCode (KeyPress::endKey))
  39223. {
  39224. // we want to avoid these keypresses going to the viewport, and instead allow
  39225. // them to pass up to our listbox..
  39226. return false;
  39227. }
  39228. return Viewport::keyPressed (key);
  39229. }
  39230. juce_UseDebuggingNewOperator
  39231. private:
  39232. ListBox& owner;
  39233. OwnedArray<ListBoxRowComponent> rows;
  39234. int firstIndex, firstWholeIndex, lastWholeIndex;
  39235. bool hasUpdated;
  39236. ListViewport (const ListViewport&);
  39237. ListViewport& operator= (const ListViewport&);
  39238. };
  39239. ListBox::ListBox (const String& name, ListBoxModel* const model_)
  39240. : Component (name),
  39241. model (model_),
  39242. totalItems (0),
  39243. rowHeight (22),
  39244. minimumRowWidth (0),
  39245. outlineThickness (0),
  39246. lastRowSelected (-1),
  39247. mouseMoveSelects (false),
  39248. multipleSelection (false),
  39249. hasDoneInitialUpdate (false)
  39250. {
  39251. addAndMakeVisible (viewport = new ListViewport (*this));
  39252. setWantsKeyboardFocus (true);
  39253. colourChanged();
  39254. }
  39255. ListBox::~ListBox()
  39256. {
  39257. headerComponent = 0;
  39258. viewport = 0;
  39259. }
  39260. void ListBox::setModel (ListBoxModel* const newModel)
  39261. {
  39262. if (model != newModel)
  39263. {
  39264. model = newModel;
  39265. updateContent();
  39266. }
  39267. }
  39268. void ListBox::setMultipleSelectionEnabled (bool b)
  39269. {
  39270. multipleSelection = b;
  39271. }
  39272. void ListBox::setMouseMoveSelectsRows (bool b)
  39273. {
  39274. mouseMoveSelects = b;
  39275. if (b)
  39276. addMouseListener (this, true);
  39277. }
  39278. void ListBox::paint (Graphics& g)
  39279. {
  39280. if (! hasDoneInitialUpdate)
  39281. updateContent();
  39282. g.fillAll (findColour (backgroundColourId));
  39283. }
  39284. void ListBox::paintOverChildren (Graphics& g)
  39285. {
  39286. if (outlineThickness > 0)
  39287. {
  39288. g.setColour (findColour (outlineColourId));
  39289. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  39290. }
  39291. }
  39292. void ListBox::resized()
  39293. {
  39294. viewport->setBoundsInset (BorderSize (outlineThickness + ((headerComponent != 0) ? headerComponent->getHeight() : 0),
  39295. outlineThickness,
  39296. outlineThickness,
  39297. outlineThickness));
  39298. viewport->setSingleStepSizes (20, getRowHeight());
  39299. viewport->updateVisibleArea (false);
  39300. }
  39301. void ListBox::visibilityChanged()
  39302. {
  39303. viewport->updateVisibleArea (true);
  39304. }
  39305. Viewport* ListBox::getViewport() const throw()
  39306. {
  39307. return viewport;
  39308. }
  39309. void ListBox::updateContent()
  39310. {
  39311. hasDoneInitialUpdate = true;
  39312. totalItems = (model != 0) ? model->getNumRows() : 0;
  39313. bool selectionChanged = false;
  39314. if (selected [selected.size() - 1] >= totalItems)
  39315. {
  39316. selected.removeRange (Range <int> (totalItems, std::numeric_limits<int>::max()));
  39317. lastRowSelected = getSelectedRow (0);
  39318. selectionChanged = true;
  39319. }
  39320. viewport->updateVisibleArea (isVisible());
  39321. viewport->resized();
  39322. if (selectionChanged && model != 0)
  39323. model->selectedRowsChanged (lastRowSelected);
  39324. }
  39325. void ListBox::selectRow (const int row,
  39326. bool dontScroll,
  39327. bool deselectOthersFirst)
  39328. {
  39329. selectRowInternal (row, dontScroll, deselectOthersFirst, false);
  39330. }
  39331. void ListBox::selectRowInternal (const int row,
  39332. bool dontScroll,
  39333. bool deselectOthersFirst,
  39334. bool isMouseClick)
  39335. {
  39336. if (! multipleSelection)
  39337. deselectOthersFirst = true;
  39338. if ((! isRowSelected (row))
  39339. || (deselectOthersFirst && getNumSelectedRows() > 1))
  39340. {
  39341. if (((unsigned int) row) < (unsigned int) totalItems)
  39342. {
  39343. if (deselectOthersFirst)
  39344. selected.clear();
  39345. selected.addRange (Range<int> (row, row + 1));
  39346. if (getHeight() == 0 || getWidth() == 0)
  39347. dontScroll = true;
  39348. viewport->selectRow (row, getRowHeight(), dontScroll,
  39349. lastRowSelected, totalItems, isMouseClick);
  39350. lastRowSelected = row;
  39351. model->selectedRowsChanged (row);
  39352. }
  39353. else
  39354. {
  39355. if (deselectOthersFirst)
  39356. deselectAllRows();
  39357. }
  39358. }
  39359. }
  39360. void ListBox::deselectRow (const int row)
  39361. {
  39362. if (selected.contains (row))
  39363. {
  39364. selected.removeRange (Range <int> (row, row + 1));
  39365. if (row == lastRowSelected)
  39366. lastRowSelected = getSelectedRow (0);
  39367. viewport->updateContents();
  39368. model->selectedRowsChanged (lastRowSelected);
  39369. }
  39370. }
  39371. void ListBox::setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  39372. const bool sendNotificationEventToModel)
  39373. {
  39374. selected = setOfRowsToBeSelected;
  39375. selected.removeRange (Range <int> (totalItems, std::numeric_limits<int>::max()));
  39376. if (! isRowSelected (lastRowSelected))
  39377. lastRowSelected = getSelectedRow (0);
  39378. viewport->updateContents();
  39379. if ((model != 0) && sendNotificationEventToModel)
  39380. model->selectedRowsChanged (lastRowSelected);
  39381. }
  39382. const SparseSet<int> ListBox::getSelectedRows() const
  39383. {
  39384. return selected;
  39385. }
  39386. void ListBox::selectRangeOfRows (int firstRow, int lastRow)
  39387. {
  39388. if (multipleSelection && (firstRow != lastRow))
  39389. {
  39390. const int numRows = totalItems - 1;
  39391. firstRow = jlimit (0, jmax (0, numRows), firstRow);
  39392. lastRow = jlimit (0, jmax (0, numRows), lastRow);
  39393. selected.addRange (Range <int> (jmin (firstRow, lastRow),
  39394. jmax (firstRow, lastRow) + 1));
  39395. selected.removeRange (Range <int> (lastRow, lastRow + 1));
  39396. }
  39397. selectRowInternal (lastRow, false, false, true);
  39398. }
  39399. void ListBox::flipRowSelection (const int row)
  39400. {
  39401. if (isRowSelected (row))
  39402. deselectRow (row);
  39403. else
  39404. selectRowInternal (row, false, false, true);
  39405. }
  39406. void ListBox::deselectAllRows()
  39407. {
  39408. if (! selected.isEmpty())
  39409. {
  39410. selected.clear();
  39411. lastRowSelected = -1;
  39412. viewport->updateContents();
  39413. if (model != 0)
  39414. model->selectedRowsChanged (lastRowSelected);
  39415. }
  39416. }
  39417. void ListBox::selectRowsBasedOnModifierKeys (const int row,
  39418. const ModifierKeys& mods)
  39419. {
  39420. if (multipleSelection && mods.isCommandDown())
  39421. {
  39422. flipRowSelection (row);
  39423. }
  39424. else if (multipleSelection && mods.isShiftDown() && lastRowSelected >= 0)
  39425. {
  39426. selectRangeOfRows (lastRowSelected, row);
  39427. }
  39428. else if ((! mods.isPopupMenu()) || ! isRowSelected (row))
  39429. {
  39430. selectRowInternal (row, false, true, true);
  39431. }
  39432. }
  39433. int ListBox::getNumSelectedRows() const
  39434. {
  39435. return selected.size();
  39436. }
  39437. int ListBox::getSelectedRow (const int index) const
  39438. {
  39439. return (((unsigned int) index) < (unsigned int) selected.size())
  39440. ? selected [index] : -1;
  39441. }
  39442. bool ListBox::isRowSelected (const int row) const
  39443. {
  39444. return selected.contains (row);
  39445. }
  39446. int ListBox::getLastRowSelected() const
  39447. {
  39448. return (isRowSelected (lastRowSelected)) ? lastRowSelected : -1;
  39449. }
  39450. int ListBox::getRowContainingPosition (const int x, const int y) const throw()
  39451. {
  39452. if (((unsigned int) x) < (unsigned int) getWidth())
  39453. {
  39454. const int row = (viewport->getViewPositionY() + y - viewport->getY()) / rowHeight;
  39455. if (((unsigned int) row) < (unsigned int) totalItems)
  39456. return row;
  39457. }
  39458. return -1;
  39459. }
  39460. int ListBox::getInsertionIndexForPosition (const int x, const int y) const throw()
  39461. {
  39462. if (((unsigned int) x) < (unsigned int) getWidth())
  39463. {
  39464. const int row = (viewport->getViewPositionY() + y + rowHeight / 2 - viewport->getY()) / rowHeight;
  39465. return jlimit (0, totalItems, row);
  39466. }
  39467. return -1;
  39468. }
  39469. Component* ListBox::getComponentForRowNumber (const int row) const throw()
  39470. {
  39471. ListBoxRowComponent* const listRowComp = viewport->getComponentForRowIfOnscreen (row);
  39472. return listRowComp != 0 ? static_cast <Component*> (listRowComp->customComponent) : 0;
  39473. }
  39474. int ListBox::getRowNumberOfComponent (Component* const rowComponent) const throw()
  39475. {
  39476. return viewport->getRowNumberOfComponent (rowComponent);
  39477. }
  39478. const Rectangle<int> ListBox::getRowPosition (const int rowNumber,
  39479. const bool relativeToComponentTopLeft) const throw()
  39480. {
  39481. int y = viewport->getY() + rowHeight * rowNumber;
  39482. if (relativeToComponentTopLeft)
  39483. y -= viewport->getViewPositionY();
  39484. return Rectangle<int> (viewport->getX(), y,
  39485. viewport->getViewedComponent()->getWidth(), rowHeight);
  39486. }
  39487. void ListBox::setVerticalPosition (const double proportion)
  39488. {
  39489. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  39490. viewport->setViewPosition (viewport->getViewPositionX(),
  39491. jmax (0, roundToInt (proportion * offscreen)));
  39492. }
  39493. double ListBox::getVerticalPosition() const
  39494. {
  39495. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  39496. return (offscreen > 0) ? viewport->getViewPositionY() / (double) offscreen
  39497. : 0;
  39498. }
  39499. int ListBox::getVisibleRowWidth() const throw()
  39500. {
  39501. return viewport->getViewWidth();
  39502. }
  39503. void ListBox::scrollToEnsureRowIsOnscreen (const int row)
  39504. {
  39505. viewport->scrollToEnsureRowIsOnscreen (row, getRowHeight());
  39506. }
  39507. bool ListBox::keyPressed (const KeyPress& key)
  39508. {
  39509. const int numVisibleRows = viewport->getHeight() / getRowHeight();
  39510. const bool multiple = multipleSelection
  39511. && (lastRowSelected >= 0)
  39512. && (key.getModifiers().isShiftDown()
  39513. || key.getModifiers().isCtrlDown()
  39514. || key.getModifiers().isCommandDown());
  39515. if (key.isKeyCode (KeyPress::upKey))
  39516. {
  39517. if (multiple)
  39518. selectRangeOfRows (lastRowSelected, lastRowSelected - 1);
  39519. else
  39520. selectRow (jmax (0, lastRowSelected - 1));
  39521. }
  39522. else if (key.isKeyCode (KeyPress::returnKey)
  39523. && isRowSelected (lastRowSelected))
  39524. {
  39525. if (model != 0)
  39526. model->returnKeyPressed (lastRowSelected);
  39527. }
  39528. else if (key.isKeyCode (KeyPress::pageUpKey))
  39529. {
  39530. if (multiple)
  39531. selectRangeOfRows (lastRowSelected, lastRowSelected - numVisibleRows);
  39532. else
  39533. selectRow (jmax (0, jmax (0, lastRowSelected) - numVisibleRows));
  39534. }
  39535. else if (key.isKeyCode (KeyPress::pageDownKey))
  39536. {
  39537. if (multiple)
  39538. selectRangeOfRows (lastRowSelected, lastRowSelected + numVisibleRows);
  39539. else
  39540. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + numVisibleRows));
  39541. }
  39542. else if (key.isKeyCode (KeyPress::homeKey))
  39543. {
  39544. if (multiple && key.getModifiers().isShiftDown())
  39545. selectRangeOfRows (lastRowSelected, 0);
  39546. else
  39547. selectRow (0);
  39548. }
  39549. else if (key.isKeyCode (KeyPress::endKey))
  39550. {
  39551. if (multiple && key.getModifiers().isShiftDown())
  39552. selectRangeOfRows (lastRowSelected, totalItems - 1);
  39553. else
  39554. selectRow (totalItems - 1);
  39555. }
  39556. else if (key.isKeyCode (KeyPress::downKey))
  39557. {
  39558. if (multiple)
  39559. selectRangeOfRows (lastRowSelected, lastRowSelected + 1);
  39560. else
  39561. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + 1));
  39562. }
  39563. else if ((key.isKeyCode (KeyPress::deleteKey) || key.isKeyCode (KeyPress::backspaceKey))
  39564. && isRowSelected (lastRowSelected))
  39565. {
  39566. if (model != 0)
  39567. model->deleteKeyPressed (lastRowSelected);
  39568. }
  39569. else if (multiple && key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  39570. {
  39571. selectRangeOfRows (0, std::numeric_limits<int>::max());
  39572. }
  39573. else
  39574. {
  39575. return false;
  39576. }
  39577. return true;
  39578. }
  39579. bool ListBox::keyStateChanged (const bool isKeyDown)
  39580. {
  39581. return isKeyDown
  39582. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  39583. || KeyPress::isKeyCurrentlyDown (KeyPress::pageUpKey)
  39584. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  39585. || KeyPress::isKeyCurrentlyDown (KeyPress::pageDownKey)
  39586. || KeyPress::isKeyCurrentlyDown (KeyPress::homeKey)
  39587. || KeyPress::isKeyCurrentlyDown (KeyPress::endKey)
  39588. || KeyPress::isKeyCurrentlyDown (KeyPress::returnKey));
  39589. }
  39590. void ListBox::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  39591. {
  39592. getHorizontalScrollBar()->mouseWheelMove (e, wheelIncrementX, 0);
  39593. getVerticalScrollBar()->mouseWheelMove (e, 0, wheelIncrementY);
  39594. }
  39595. void ListBox::mouseMove (const MouseEvent& e)
  39596. {
  39597. if (mouseMoveSelects)
  39598. {
  39599. const MouseEvent e2 (e.getEventRelativeTo (this));
  39600. selectRow (getRowContainingPosition (e2.x, e2.y), true);
  39601. }
  39602. }
  39603. void ListBox::mouseExit (const MouseEvent& e)
  39604. {
  39605. mouseMove (e);
  39606. }
  39607. void ListBox::mouseUp (const MouseEvent& e)
  39608. {
  39609. if (e.mouseWasClicked() && model != 0)
  39610. model->backgroundClicked();
  39611. }
  39612. void ListBox::setRowHeight (const int newHeight)
  39613. {
  39614. rowHeight = jmax (1, newHeight);
  39615. viewport->setSingleStepSizes (20, rowHeight);
  39616. updateContent();
  39617. }
  39618. int ListBox::getNumRowsOnScreen() const throw()
  39619. {
  39620. return viewport->getMaximumVisibleHeight() / rowHeight;
  39621. }
  39622. void ListBox::setMinimumContentWidth (const int newMinimumWidth)
  39623. {
  39624. minimumRowWidth = newMinimumWidth;
  39625. updateContent();
  39626. }
  39627. int ListBox::getVisibleContentWidth() const throw()
  39628. {
  39629. return viewport->getMaximumVisibleWidth();
  39630. }
  39631. ScrollBar* ListBox::getVerticalScrollBar() const throw()
  39632. {
  39633. return viewport->getVerticalScrollBar();
  39634. }
  39635. ScrollBar* ListBox::getHorizontalScrollBar() const throw()
  39636. {
  39637. return viewport->getHorizontalScrollBar();
  39638. }
  39639. void ListBox::colourChanged()
  39640. {
  39641. setOpaque (findColour (backgroundColourId).isOpaque());
  39642. viewport->setOpaque (isOpaque());
  39643. repaint();
  39644. }
  39645. void ListBox::setOutlineThickness (const int outlineThickness_)
  39646. {
  39647. outlineThickness = outlineThickness_;
  39648. resized();
  39649. }
  39650. void ListBox::setHeaderComponent (Component* const newHeaderComponent)
  39651. {
  39652. if (newHeaderComponent != headerComponent)
  39653. {
  39654. headerComponent = newHeaderComponent;
  39655. addAndMakeVisible (newHeaderComponent);
  39656. ListBox::resized();
  39657. }
  39658. }
  39659. void ListBox::repaintRow (const int rowNumber) throw()
  39660. {
  39661. repaint (getRowPosition (rowNumber, true));
  39662. }
  39663. const Image ListBox::createSnapshotOfSelectedRows (int& imageX, int& imageY)
  39664. {
  39665. Rectangle<int> imageArea;
  39666. const int firstRow = getRowContainingPosition (0, 0);
  39667. int i;
  39668. for (i = getNumRowsOnScreen() + 2; --i >= 0;)
  39669. {
  39670. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  39671. if (rowComp != 0 && isRowSelected (firstRow + i))
  39672. {
  39673. const Point<int> pos (rowComp->relativePositionToOtherComponent (this, Point<int>()));
  39674. const Rectangle<int> rowRect (pos.getX(), pos.getY(), rowComp->getWidth(), rowComp->getHeight());
  39675. imageArea = imageArea.getUnion (rowRect);
  39676. }
  39677. }
  39678. imageArea = imageArea.getIntersection (getLocalBounds());
  39679. imageX = imageArea.getX();
  39680. imageY = imageArea.getY();
  39681. Image snapshot (Image::ARGB, imageArea.getWidth(), imageArea.getHeight(), true, Image::NativeImage);
  39682. for (i = getNumRowsOnScreen() + 2; --i >= 0;)
  39683. {
  39684. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  39685. if (rowComp != 0 && isRowSelected (firstRow + i))
  39686. {
  39687. const Point<int> pos (rowComp->relativePositionToOtherComponent (this, Point<int>()));
  39688. Graphics g (snapshot);
  39689. g.setOrigin (pos.getX() - imageX, pos.getY() - imageY);
  39690. if (g.reduceClipRegion (rowComp->getLocalBounds()))
  39691. rowComp->paintEntireComponent (g, false);
  39692. }
  39693. }
  39694. return snapshot;
  39695. }
  39696. void ListBox::startDragAndDrop (const MouseEvent& e, const String& dragDescription)
  39697. {
  39698. DragAndDropContainer* const dragContainer
  39699. = DragAndDropContainer::findParentDragContainerFor (this);
  39700. if (dragContainer != 0)
  39701. {
  39702. int x, y;
  39703. Image dragImage (createSnapshotOfSelectedRows (x, y));
  39704. dragImage.multiplyAllAlphas (0.6f);
  39705. MouseEvent e2 (e.getEventRelativeTo (this));
  39706. const Point<int> p (x - e2.x, y - e2.y);
  39707. dragContainer->startDragging (dragDescription, this, dragImage, true, &p);
  39708. }
  39709. else
  39710. {
  39711. // to be able to do a drag-and-drop operation, the listbox needs to
  39712. // be inside a component which is also a DragAndDropContainer.
  39713. jassertfalse;
  39714. }
  39715. }
  39716. Component* ListBoxModel::refreshComponentForRow (int, bool, Component* existingComponentToUpdate)
  39717. {
  39718. (void) existingComponentToUpdate;
  39719. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  39720. return 0;
  39721. }
  39722. void ListBoxModel::listBoxItemClicked (int, const MouseEvent&) {}
  39723. void ListBoxModel::listBoxItemDoubleClicked (int, const MouseEvent&) {}
  39724. void ListBoxModel::backgroundClicked() {}
  39725. void ListBoxModel::selectedRowsChanged (int) {}
  39726. void ListBoxModel::deleteKeyPressed (int) {}
  39727. void ListBoxModel::returnKeyPressed (int) {}
  39728. void ListBoxModel::listWasScrolled() {}
  39729. const String ListBoxModel::getDragSourceDescription (const SparseSet<int>&) { return String::empty; }
  39730. const String ListBoxModel::getTooltipForRow (int) { return String::empty; }
  39731. END_JUCE_NAMESPACE
  39732. /*** End of inlined file: juce_ListBox.cpp ***/
  39733. /*** Start of inlined file: juce_ProgressBar.cpp ***/
  39734. BEGIN_JUCE_NAMESPACE
  39735. ProgressBar::ProgressBar (double& progress_)
  39736. : progress (progress_),
  39737. displayPercentage (true),
  39738. lastCallbackTime (0)
  39739. {
  39740. currentValue = jlimit (0.0, 1.0, progress);
  39741. }
  39742. ProgressBar::~ProgressBar()
  39743. {
  39744. }
  39745. void ProgressBar::setPercentageDisplay (const bool shouldDisplayPercentage)
  39746. {
  39747. displayPercentage = shouldDisplayPercentage;
  39748. repaint();
  39749. }
  39750. void ProgressBar::setTextToDisplay (const String& text)
  39751. {
  39752. displayPercentage = false;
  39753. displayedMessage = text;
  39754. }
  39755. void ProgressBar::lookAndFeelChanged()
  39756. {
  39757. setOpaque (findColour (backgroundColourId).isOpaque());
  39758. }
  39759. void ProgressBar::colourChanged()
  39760. {
  39761. lookAndFeelChanged();
  39762. }
  39763. void ProgressBar::paint (Graphics& g)
  39764. {
  39765. String text;
  39766. if (displayPercentage)
  39767. {
  39768. if (currentValue >= 0 && currentValue <= 1.0)
  39769. text << roundToInt (currentValue * 100.0) << '%';
  39770. }
  39771. else
  39772. {
  39773. text = displayedMessage;
  39774. }
  39775. getLookAndFeel().drawProgressBar (g, *this,
  39776. getWidth(), getHeight(),
  39777. currentValue, text);
  39778. }
  39779. void ProgressBar::visibilityChanged()
  39780. {
  39781. if (isVisible())
  39782. startTimer (30);
  39783. else
  39784. stopTimer();
  39785. }
  39786. void ProgressBar::timerCallback()
  39787. {
  39788. double newProgress = progress;
  39789. const uint32 now = Time::getMillisecondCounter();
  39790. const int timeSinceLastCallback = (int) (now - lastCallbackTime);
  39791. lastCallbackTime = now;
  39792. if (currentValue != newProgress
  39793. || newProgress < 0 || newProgress >= 1.0
  39794. || currentMessage != displayedMessage)
  39795. {
  39796. if (currentValue < newProgress
  39797. && newProgress >= 0 && newProgress < 1.0
  39798. && currentValue >= 0 && currentValue < 1.0)
  39799. {
  39800. newProgress = jmin (currentValue + 0.0008 * timeSinceLastCallback,
  39801. newProgress);
  39802. }
  39803. currentValue = newProgress;
  39804. currentMessage = displayedMessage;
  39805. repaint();
  39806. }
  39807. }
  39808. END_JUCE_NAMESPACE
  39809. /*** End of inlined file: juce_ProgressBar.cpp ***/
  39810. /*** Start of inlined file: juce_Slider.cpp ***/
  39811. BEGIN_JUCE_NAMESPACE
  39812. class SliderPopupDisplayComponent : public BubbleComponent
  39813. {
  39814. public:
  39815. SliderPopupDisplayComponent (Slider* const owner_)
  39816. : owner (owner_),
  39817. font (15.0f, Font::bold)
  39818. {
  39819. setAlwaysOnTop (true);
  39820. }
  39821. ~SliderPopupDisplayComponent()
  39822. {
  39823. }
  39824. void paintContent (Graphics& g, int w, int h)
  39825. {
  39826. g.setFont (font);
  39827. g.setColour (Colours::black);
  39828. g.drawFittedText (text, 0, 0, w, h, Justification::centred, 1);
  39829. }
  39830. void getContentSize (int& w, int& h)
  39831. {
  39832. w = font.getStringWidth (text) + 18;
  39833. h = (int) (font.getHeight() * 1.6f);
  39834. }
  39835. void updatePosition (const String& newText)
  39836. {
  39837. if (text != newText)
  39838. {
  39839. text = newText;
  39840. repaint();
  39841. }
  39842. BubbleComponent::setPosition (owner);
  39843. }
  39844. juce_UseDebuggingNewOperator
  39845. private:
  39846. Slider* owner;
  39847. Font font;
  39848. String text;
  39849. SliderPopupDisplayComponent (const SliderPopupDisplayComponent&);
  39850. SliderPopupDisplayComponent& operator= (const SliderPopupDisplayComponent&);
  39851. };
  39852. Slider::Slider (const String& name)
  39853. : Component (name),
  39854. lastCurrentValue (0),
  39855. lastValueMin (0),
  39856. lastValueMax (0),
  39857. minimum (0),
  39858. maximum (10),
  39859. interval (0),
  39860. skewFactor (1.0),
  39861. velocityModeSensitivity (1.0),
  39862. velocityModeOffset (0.0),
  39863. velocityModeThreshold (1),
  39864. rotaryStart (float_Pi * 1.2f),
  39865. rotaryEnd (float_Pi * 2.8f),
  39866. numDecimalPlaces (7),
  39867. sliderRegionStart (0),
  39868. sliderRegionSize (1),
  39869. sliderBeingDragged (-1),
  39870. pixelsForFullDragExtent (250),
  39871. style (LinearHorizontal),
  39872. textBoxPos (TextBoxLeft),
  39873. textBoxWidth (80),
  39874. textBoxHeight (20),
  39875. incDecButtonMode (incDecButtonsNotDraggable),
  39876. editableText (true),
  39877. doubleClickToValue (false),
  39878. isVelocityBased (false),
  39879. userKeyOverridesVelocity (true),
  39880. rotaryStop (true),
  39881. incDecButtonsSideBySide (false),
  39882. sendChangeOnlyOnRelease (false),
  39883. popupDisplayEnabled (false),
  39884. menuEnabled (false),
  39885. menuShown (false),
  39886. scrollWheelEnabled (true),
  39887. snapsToMousePos (true),
  39888. valueBox (0),
  39889. incButton (0),
  39890. decButton (0),
  39891. popupDisplay (0),
  39892. parentForPopupDisplay (0)
  39893. {
  39894. setWantsKeyboardFocus (false);
  39895. setRepaintsOnMouseActivity (true);
  39896. lookAndFeelChanged();
  39897. updateText();
  39898. currentValue.addListener (this);
  39899. valueMin.addListener (this);
  39900. valueMax.addListener (this);
  39901. }
  39902. Slider::~Slider()
  39903. {
  39904. currentValue.removeListener (this);
  39905. valueMin.removeListener (this);
  39906. valueMax.removeListener (this);
  39907. popupDisplay = 0;
  39908. deleteAllChildren();
  39909. }
  39910. void Slider::handleAsyncUpdate()
  39911. {
  39912. cancelPendingUpdate();
  39913. Component::BailOutChecker checker (this);
  39914. listeners.callChecked (checker, &SliderListener::sliderValueChanged, this); // (can't use Slider::Listener due to idiotic VC2005 bug)
  39915. }
  39916. void Slider::sendDragStart()
  39917. {
  39918. startedDragging();
  39919. Component::BailOutChecker checker (this);
  39920. listeners.callChecked (checker, &SliderListener::sliderDragStarted, this);
  39921. }
  39922. void Slider::sendDragEnd()
  39923. {
  39924. stoppedDragging();
  39925. sliderBeingDragged = -1;
  39926. Component::BailOutChecker checker (this);
  39927. listeners.callChecked (checker, &SliderListener::sliderDragEnded, this);
  39928. }
  39929. void Slider::addListener (Listener* const listener)
  39930. {
  39931. listeners.add (listener);
  39932. }
  39933. void Slider::removeListener (Listener* const listener)
  39934. {
  39935. listeners.remove (listener);
  39936. }
  39937. void Slider::setSliderStyle (const SliderStyle newStyle)
  39938. {
  39939. if (style != newStyle)
  39940. {
  39941. style = newStyle;
  39942. repaint();
  39943. lookAndFeelChanged();
  39944. }
  39945. }
  39946. void Slider::setRotaryParameters (const float startAngleRadians,
  39947. const float endAngleRadians,
  39948. const bool stopAtEnd)
  39949. {
  39950. // make sure the values are sensible..
  39951. jassert (rotaryStart >= 0 && rotaryEnd >= 0);
  39952. jassert (rotaryStart < float_Pi * 4.0f && rotaryEnd < float_Pi * 4.0f);
  39953. jassert (rotaryStart < rotaryEnd);
  39954. rotaryStart = startAngleRadians;
  39955. rotaryEnd = endAngleRadians;
  39956. rotaryStop = stopAtEnd;
  39957. }
  39958. void Slider::setVelocityBasedMode (const bool velBased)
  39959. {
  39960. isVelocityBased = velBased;
  39961. }
  39962. void Slider::setVelocityModeParameters (const double sensitivity,
  39963. const int threshold,
  39964. const double offset,
  39965. const bool userCanPressKeyToSwapMode)
  39966. {
  39967. jassert (threshold >= 0);
  39968. jassert (sensitivity > 0);
  39969. jassert (offset >= 0);
  39970. velocityModeSensitivity = sensitivity;
  39971. velocityModeOffset = offset;
  39972. velocityModeThreshold = threshold;
  39973. userKeyOverridesVelocity = userCanPressKeyToSwapMode;
  39974. }
  39975. void Slider::setSkewFactor (const double factor)
  39976. {
  39977. skewFactor = factor;
  39978. }
  39979. void Slider::setSkewFactorFromMidPoint (const double sliderValueToShowAtMidPoint)
  39980. {
  39981. if (maximum > minimum)
  39982. skewFactor = log (0.5) / log ((sliderValueToShowAtMidPoint - minimum)
  39983. / (maximum - minimum));
  39984. }
  39985. void Slider::setMouseDragSensitivity (const int distanceForFullScaleDrag)
  39986. {
  39987. jassert (distanceForFullScaleDrag > 0);
  39988. pixelsForFullDragExtent = distanceForFullScaleDrag;
  39989. }
  39990. void Slider::setIncDecButtonsMode (const IncDecButtonMode mode)
  39991. {
  39992. if (incDecButtonMode != mode)
  39993. {
  39994. incDecButtonMode = mode;
  39995. lookAndFeelChanged();
  39996. }
  39997. }
  39998. void Slider::setTextBoxStyle (const TextEntryBoxPosition newPosition,
  39999. const bool isReadOnly,
  40000. const int textEntryBoxWidth,
  40001. const int textEntryBoxHeight)
  40002. {
  40003. if (textBoxPos != newPosition
  40004. || editableText != (! isReadOnly)
  40005. || textBoxWidth != textEntryBoxWidth
  40006. || textBoxHeight != textEntryBoxHeight)
  40007. {
  40008. textBoxPos = newPosition;
  40009. editableText = ! isReadOnly;
  40010. textBoxWidth = textEntryBoxWidth;
  40011. textBoxHeight = textEntryBoxHeight;
  40012. repaint();
  40013. lookAndFeelChanged();
  40014. }
  40015. }
  40016. void Slider::setTextBoxIsEditable (const bool shouldBeEditable)
  40017. {
  40018. editableText = shouldBeEditable;
  40019. if (valueBox != 0)
  40020. valueBox->setEditable (shouldBeEditable && isEnabled());
  40021. }
  40022. void Slider::showTextBox()
  40023. {
  40024. jassert (editableText); // this should probably be avoided in read-only sliders.
  40025. if (valueBox != 0)
  40026. valueBox->showEditor();
  40027. }
  40028. void Slider::hideTextBox (const bool discardCurrentEditorContents)
  40029. {
  40030. if (valueBox != 0)
  40031. {
  40032. valueBox->hideEditor (discardCurrentEditorContents);
  40033. if (discardCurrentEditorContents)
  40034. updateText();
  40035. }
  40036. }
  40037. void Slider::setChangeNotificationOnlyOnRelease (const bool onlyNotifyOnRelease)
  40038. {
  40039. sendChangeOnlyOnRelease = onlyNotifyOnRelease;
  40040. }
  40041. void Slider::setSliderSnapsToMousePosition (const bool shouldSnapToMouse)
  40042. {
  40043. snapsToMousePos = shouldSnapToMouse;
  40044. }
  40045. void Slider::setPopupDisplayEnabled (const bool enabled,
  40046. Component* const parentComponentToUse)
  40047. {
  40048. popupDisplayEnabled = enabled;
  40049. parentForPopupDisplay = parentComponentToUse;
  40050. }
  40051. void Slider::colourChanged()
  40052. {
  40053. lookAndFeelChanged();
  40054. }
  40055. void Slider::lookAndFeelChanged()
  40056. {
  40057. const String previousTextBoxContent (valueBox != 0 ? valueBox->getText()
  40058. : getTextFromValue (currentValue.getValue()));
  40059. deleteAllChildren();
  40060. valueBox = 0;
  40061. LookAndFeel& lf = getLookAndFeel();
  40062. if (textBoxPos != NoTextBox)
  40063. {
  40064. addAndMakeVisible (valueBox = getLookAndFeel().createSliderTextBox (*this));
  40065. valueBox->setWantsKeyboardFocus (false);
  40066. valueBox->setText (previousTextBoxContent, false);
  40067. valueBox->setEditable (editableText && isEnabled());
  40068. valueBox->addListener (this);
  40069. if (style == LinearBar)
  40070. valueBox->addMouseListener (this, false);
  40071. valueBox->setTooltip (getTooltip());
  40072. }
  40073. if (style == IncDecButtons)
  40074. {
  40075. addAndMakeVisible (incButton = lf.createSliderButton (true));
  40076. incButton->addButtonListener (this);
  40077. addAndMakeVisible (decButton = lf.createSliderButton (false));
  40078. decButton->addButtonListener (this);
  40079. if (incDecButtonMode != incDecButtonsNotDraggable)
  40080. {
  40081. incButton->addMouseListener (this, false);
  40082. decButton->addMouseListener (this, false);
  40083. }
  40084. else
  40085. {
  40086. incButton->setRepeatSpeed (300, 100, 20);
  40087. incButton->addMouseListener (decButton, false);
  40088. decButton->setRepeatSpeed (300, 100, 20);
  40089. decButton->addMouseListener (incButton, false);
  40090. }
  40091. incButton->setTooltip (getTooltip());
  40092. decButton->setTooltip (getTooltip());
  40093. }
  40094. setComponentEffect (lf.getSliderEffect());
  40095. resized();
  40096. repaint();
  40097. }
  40098. void Slider::setRange (const double newMin,
  40099. const double newMax,
  40100. const double newInt)
  40101. {
  40102. if (minimum != newMin
  40103. || maximum != newMax
  40104. || interval != newInt)
  40105. {
  40106. minimum = newMin;
  40107. maximum = newMax;
  40108. interval = newInt;
  40109. // figure out the number of DPs needed to display all values at this
  40110. // interval setting.
  40111. numDecimalPlaces = 7;
  40112. if (newInt != 0)
  40113. {
  40114. int v = abs ((int) (newInt * 10000000));
  40115. while ((v % 10) == 0)
  40116. {
  40117. --numDecimalPlaces;
  40118. v /= 10;
  40119. }
  40120. }
  40121. // keep the current values inside the new range..
  40122. if (style != TwoValueHorizontal && style != TwoValueVertical)
  40123. {
  40124. setValue (getValue(), false, false);
  40125. }
  40126. else
  40127. {
  40128. setMinValue (getMinValue(), false, false);
  40129. setMaxValue (getMaxValue(), false, false);
  40130. }
  40131. updateText();
  40132. }
  40133. }
  40134. void Slider::triggerChangeMessage (const bool synchronous)
  40135. {
  40136. if (synchronous)
  40137. handleAsyncUpdate();
  40138. else
  40139. triggerAsyncUpdate();
  40140. valueChanged();
  40141. }
  40142. void Slider::valueChanged (Value& value)
  40143. {
  40144. if (value.refersToSameSourceAs (currentValue))
  40145. {
  40146. if (style != TwoValueHorizontal && style != TwoValueVertical)
  40147. setValue (currentValue.getValue(), false, false);
  40148. }
  40149. else if (value.refersToSameSourceAs (valueMin))
  40150. setMinValue (valueMin.getValue(), false, false, true);
  40151. else if (value.refersToSameSourceAs (valueMax))
  40152. setMaxValue (valueMax.getValue(), false, false, true);
  40153. }
  40154. double Slider::getValue() const
  40155. {
  40156. // for a two-value style slider, you should use the getMinValue() and getMaxValue()
  40157. // methods to get the two values.
  40158. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  40159. return currentValue.getValue();
  40160. }
  40161. void Slider::setValue (double newValue,
  40162. const bool sendUpdateMessage,
  40163. const bool sendMessageSynchronously)
  40164. {
  40165. // for a two-value style slider, you should use the setMinValue() and setMaxValue()
  40166. // methods to set the two values.
  40167. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  40168. newValue = constrainedValue (newValue);
  40169. if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  40170. {
  40171. jassert ((double) valueMin.getValue() <= (double) valueMax.getValue());
  40172. newValue = jlimit ((double) valueMin.getValue(),
  40173. (double) valueMax.getValue(),
  40174. newValue);
  40175. }
  40176. if (newValue != lastCurrentValue)
  40177. {
  40178. if (valueBox != 0)
  40179. valueBox->hideEditor (true);
  40180. lastCurrentValue = newValue;
  40181. currentValue = newValue;
  40182. updateText();
  40183. repaint();
  40184. if (popupDisplay != 0)
  40185. {
  40186. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  40187. ->updatePosition (getTextFromValue (newValue));
  40188. popupDisplay->repaint();
  40189. }
  40190. if (sendUpdateMessage)
  40191. triggerChangeMessage (sendMessageSynchronously);
  40192. }
  40193. }
  40194. double Slider::getMinValue() const
  40195. {
  40196. // The minimum value only applies to sliders that are in two- or three-value mode.
  40197. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40198. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40199. return valueMin.getValue();
  40200. }
  40201. double Slider::getMaxValue() const
  40202. {
  40203. // The maximum value only applies to sliders that are in two- or three-value mode.
  40204. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40205. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40206. return valueMax.getValue();
  40207. }
  40208. void Slider::setMinValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  40209. {
  40210. // The minimum value only applies to sliders that are in two- or three-value mode.
  40211. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40212. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40213. newValue = constrainedValue (newValue);
  40214. if (style == TwoValueHorizontal || style == TwoValueVertical)
  40215. {
  40216. if (allowNudgingOfOtherValues && newValue > (double) valueMax.getValue())
  40217. setMaxValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40218. newValue = jmin ((double) valueMax.getValue(), newValue);
  40219. }
  40220. else
  40221. {
  40222. if (allowNudgingOfOtherValues && newValue > lastCurrentValue)
  40223. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40224. newValue = jmin (lastCurrentValue, newValue);
  40225. }
  40226. if (lastValueMin != newValue)
  40227. {
  40228. lastValueMin = newValue;
  40229. valueMin = newValue;
  40230. repaint();
  40231. if (popupDisplay != 0)
  40232. {
  40233. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  40234. ->updatePosition (getTextFromValue (newValue));
  40235. popupDisplay->repaint();
  40236. }
  40237. if (sendUpdateMessage)
  40238. triggerChangeMessage (sendMessageSynchronously);
  40239. }
  40240. }
  40241. void Slider::setMaxValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  40242. {
  40243. // The maximum value only applies to sliders that are in two- or three-value mode.
  40244. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40245. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40246. newValue = constrainedValue (newValue);
  40247. if (style == TwoValueHorizontal || style == TwoValueVertical)
  40248. {
  40249. if (allowNudgingOfOtherValues && newValue < (double) valueMin.getValue())
  40250. setMinValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40251. newValue = jmax ((double) valueMin.getValue(), newValue);
  40252. }
  40253. else
  40254. {
  40255. if (allowNudgingOfOtherValues && newValue < lastCurrentValue)
  40256. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40257. newValue = jmax (lastCurrentValue, newValue);
  40258. }
  40259. if (lastValueMax != newValue)
  40260. {
  40261. lastValueMax = newValue;
  40262. valueMax = newValue;
  40263. repaint();
  40264. if (popupDisplay != 0)
  40265. {
  40266. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  40267. ->updatePosition (getTextFromValue (valueMax.getValue()));
  40268. popupDisplay->repaint();
  40269. }
  40270. if (sendUpdateMessage)
  40271. triggerChangeMessage (sendMessageSynchronously);
  40272. }
  40273. }
  40274. void Slider::setDoubleClickReturnValue (const bool isDoubleClickEnabled,
  40275. const double valueToSetOnDoubleClick)
  40276. {
  40277. doubleClickToValue = isDoubleClickEnabled;
  40278. doubleClickReturnValue = valueToSetOnDoubleClick;
  40279. }
  40280. double Slider::getDoubleClickReturnValue (bool& isEnabled_) const
  40281. {
  40282. isEnabled_ = doubleClickToValue;
  40283. return doubleClickReturnValue;
  40284. }
  40285. void Slider::updateText()
  40286. {
  40287. if (valueBox != 0)
  40288. valueBox->setText (getTextFromValue (currentValue.getValue()), false);
  40289. }
  40290. void Slider::setTextValueSuffix (const String& suffix)
  40291. {
  40292. if (textSuffix != suffix)
  40293. {
  40294. textSuffix = suffix;
  40295. updateText();
  40296. }
  40297. }
  40298. const String Slider::getTextValueSuffix() const
  40299. {
  40300. return textSuffix;
  40301. }
  40302. const String Slider::getTextFromValue (double v)
  40303. {
  40304. if (getNumDecimalPlacesToDisplay() > 0)
  40305. return String (v, getNumDecimalPlacesToDisplay()) + getTextValueSuffix();
  40306. else
  40307. return String (roundToInt (v)) + getTextValueSuffix();
  40308. }
  40309. double Slider::getValueFromText (const String& text)
  40310. {
  40311. String t (text.trimStart());
  40312. if (t.endsWith (textSuffix))
  40313. t = t.substring (0, t.length() - textSuffix.length());
  40314. while (t.startsWithChar ('+'))
  40315. t = t.substring (1).trimStart();
  40316. return t.initialSectionContainingOnly ("0123456789.,-")
  40317. .getDoubleValue();
  40318. }
  40319. double Slider::proportionOfLengthToValue (double proportion)
  40320. {
  40321. if (skewFactor != 1.0 && proportion > 0.0)
  40322. proportion = exp (log (proportion) / skewFactor);
  40323. return minimum + (maximum - minimum) * proportion;
  40324. }
  40325. double Slider::valueToProportionOfLength (double value)
  40326. {
  40327. const double n = (value - minimum) / (maximum - minimum);
  40328. return skewFactor == 1.0 ? n : pow (n, skewFactor);
  40329. }
  40330. double Slider::snapValue (double attemptedValue, const bool)
  40331. {
  40332. return attemptedValue;
  40333. }
  40334. void Slider::startedDragging()
  40335. {
  40336. }
  40337. void Slider::stoppedDragging()
  40338. {
  40339. }
  40340. void Slider::valueChanged()
  40341. {
  40342. }
  40343. void Slider::enablementChanged()
  40344. {
  40345. repaint();
  40346. }
  40347. void Slider::setPopupMenuEnabled (const bool menuEnabled_)
  40348. {
  40349. menuEnabled = menuEnabled_;
  40350. }
  40351. void Slider::setScrollWheelEnabled (const bool enabled)
  40352. {
  40353. scrollWheelEnabled = enabled;
  40354. }
  40355. void Slider::labelTextChanged (Label* label)
  40356. {
  40357. const double newValue = snapValue (getValueFromText (label->getText()), false);
  40358. if (newValue != (double) currentValue.getValue())
  40359. {
  40360. sendDragStart();
  40361. setValue (newValue, true, true);
  40362. sendDragEnd();
  40363. }
  40364. updateText(); // force a clean-up of the text, needed in case setValue() hasn't done this.
  40365. }
  40366. void Slider::buttonClicked (Button* button)
  40367. {
  40368. if (style == IncDecButtons)
  40369. {
  40370. sendDragStart();
  40371. if (button == incButton)
  40372. setValue (snapValue (getValue() + interval, false), true, true);
  40373. else if (button == decButton)
  40374. setValue (snapValue (getValue() - interval, false), true, true);
  40375. sendDragEnd();
  40376. }
  40377. }
  40378. double Slider::constrainedValue (double value) const
  40379. {
  40380. if (interval > 0)
  40381. value = minimum + interval * std::floor ((value - minimum) / interval + 0.5);
  40382. if (value <= minimum || maximum <= minimum)
  40383. value = minimum;
  40384. else if (value >= maximum)
  40385. value = maximum;
  40386. return value;
  40387. }
  40388. float Slider::getLinearSliderPos (const double value)
  40389. {
  40390. double sliderPosProportional;
  40391. if (maximum > minimum)
  40392. {
  40393. if (value < minimum)
  40394. {
  40395. sliderPosProportional = 0.0;
  40396. }
  40397. else if (value > maximum)
  40398. {
  40399. sliderPosProportional = 1.0;
  40400. }
  40401. else
  40402. {
  40403. sliderPosProportional = valueToProportionOfLength (value);
  40404. jassert (sliderPosProportional >= 0 && sliderPosProportional <= 1.0);
  40405. }
  40406. }
  40407. else
  40408. {
  40409. sliderPosProportional = 0.5;
  40410. }
  40411. if (isVertical() || style == IncDecButtons)
  40412. sliderPosProportional = 1.0 - sliderPosProportional;
  40413. return (float) (sliderRegionStart + sliderPosProportional * sliderRegionSize);
  40414. }
  40415. bool Slider::isHorizontal() const
  40416. {
  40417. return style == LinearHorizontal
  40418. || style == LinearBar
  40419. || style == TwoValueHorizontal
  40420. || style == ThreeValueHorizontal;
  40421. }
  40422. bool Slider::isVertical() const
  40423. {
  40424. return style == LinearVertical
  40425. || style == TwoValueVertical
  40426. || style == ThreeValueVertical;
  40427. }
  40428. bool Slider::incDecDragDirectionIsHorizontal() const
  40429. {
  40430. return incDecButtonMode == incDecButtonsDraggable_Horizontal
  40431. || (incDecButtonMode == incDecButtonsDraggable_AutoDirection && incDecButtonsSideBySide);
  40432. }
  40433. float Slider::getPositionOfValue (const double value)
  40434. {
  40435. if (isHorizontal() || isVertical())
  40436. {
  40437. return getLinearSliderPos (value);
  40438. }
  40439. else
  40440. {
  40441. jassertfalse; // not a valid call on a slider that doesn't work linearly!
  40442. return 0.0f;
  40443. }
  40444. }
  40445. void Slider::paint (Graphics& g)
  40446. {
  40447. if (style != IncDecButtons)
  40448. {
  40449. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  40450. {
  40451. const float sliderPos = (float) valueToProportionOfLength (lastCurrentValue);
  40452. jassert (sliderPos >= 0 && sliderPos <= 1.0f);
  40453. getLookAndFeel().drawRotarySlider (g,
  40454. sliderRect.getX(),
  40455. sliderRect.getY(),
  40456. sliderRect.getWidth(),
  40457. sliderRect.getHeight(),
  40458. sliderPos,
  40459. rotaryStart, rotaryEnd,
  40460. *this);
  40461. }
  40462. else
  40463. {
  40464. getLookAndFeel().drawLinearSlider (g,
  40465. sliderRect.getX(),
  40466. sliderRect.getY(),
  40467. sliderRect.getWidth(),
  40468. sliderRect.getHeight(),
  40469. getLinearSliderPos (lastCurrentValue),
  40470. getLinearSliderPos (lastValueMin),
  40471. getLinearSliderPos (lastValueMax),
  40472. style,
  40473. *this);
  40474. }
  40475. if (style == LinearBar && valueBox == 0)
  40476. {
  40477. g.setColour (findColour (Slider::textBoxOutlineColourId));
  40478. g.drawRect (0, 0, getWidth(), getHeight(), 1);
  40479. }
  40480. }
  40481. }
  40482. void Slider::resized()
  40483. {
  40484. int minXSpace = 0;
  40485. int minYSpace = 0;
  40486. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  40487. minXSpace = 30;
  40488. else
  40489. minYSpace = 15;
  40490. const int tbw = jmax (0, jmin (textBoxWidth, getWidth() - minXSpace));
  40491. const int tbh = jmax (0, jmin (textBoxHeight, getHeight() - minYSpace));
  40492. if (style == LinearBar)
  40493. {
  40494. if (valueBox != 0)
  40495. valueBox->setBounds (getLocalBounds());
  40496. }
  40497. else
  40498. {
  40499. if (textBoxPos == NoTextBox)
  40500. {
  40501. sliderRect = getLocalBounds();
  40502. }
  40503. else if (textBoxPos == TextBoxLeft)
  40504. {
  40505. valueBox->setBounds (0, (getHeight() - tbh) / 2, tbw, tbh);
  40506. sliderRect.setBounds (tbw, 0, getWidth() - tbw, getHeight());
  40507. }
  40508. else if (textBoxPos == TextBoxRight)
  40509. {
  40510. valueBox->setBounds (getWidth() - tbw, (getHeight() - tbh) / 2, tbw, tbh);
  40511. sliderRect.setBounds (0, 0, getWidth() - tbw, getHeight());
  40512. }
  40513. else if (textBoxPos == TextBoxAbove)
  40514. {
  40515. valueBox->setBounds ((getWidth() - tbw) / 2, 0, tbw, tbh);
  40516. sliderRect.setBounds (0, tbh, getWidth(), getHeight() - tbh);
  40517. }
  40518. else if (textBoxPos == TextBoxBelow)
  40519. {
  40520. valueBox->setBounds ((getWidth() - tbw) / 2, getHeight() - tbh, tbw, tbh);
  40521. sliderRect.setBounds (0, 0, getWidth(), getHeight() - tbh);
  40522. }
  40523. }
  40524. const int indent = getLookAndFeel().getSliderThumbRadius (*this);
  40525. if (style == LinearBar)
  40526. {
  40527. const int barIndent = 1;
  40528. sliderRegionStart = barIndent;
  40529. sliderRegionSize = getWidth() - barIndent * 2;
  40530. sliderRect.setBounds (sliderRegionStart, barIndent,
  40531. sliderRegionSize, getHeight() - barIndent * 2);
  40532. }
  40533. else if (isHorizontal())
  40534. {
  40535. sliderRegionStart = sliderRect.getX() + indent;
  40536. sliderRegionSize = jmax (1, sliderRect.getWidth() - indent * 2);
  40537. sliderRect.setBounds (sliderRegionStart, sliderRect.getY(),
  40538. sliderRegionSize, sliderRect.getHeight());
  40539. }
  40540. else if (isVertical())
  40541. {
  40542. sliderRegionStart = sliderRect.getY() + indent;
  40543. sliderRegionSize = jmax (1, sliderRect.getHeight() - indent * 2);
  40544. sliderRect.setBounds (sliderRect.getX(), sliderRegionStart,
  40545. sliderRect.getWidth(), sliderRegionSize);
  40546. }
  40547. else
  40548. {
  40549. sliderRegionStart = 0;
  40550. sliderRegionSize = 100;
  40551. }
  40552. if (style == IncDecButtons)
  40553. {
  40554. Rectangle<int> buttonRect (sliderRect);
  40555. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  40556. buttonRect.expand (-2, 0);
  40557. else
  40558. buttonRect.expand (0, -2);
  40559. incDecButtonsSideBySide = buttonRect.getWidth() > buttonRect.getHeight();
  40560. if (incDecButtonsSideBySide)
  40561. {
  40562. decButton->setBounds (buttonRect.getX(),
  40563. buttonRect.getY(),
  40564. buttonRect.getWidth() / 2,
  40565. buttonRect.getHeight());
  40566. decButton->setConnectedEdges (Button::ConnectedOnRight);
  40567. incButton->setBounds (buttonRect.getCentreX(),
  40568. buttonRect.getY(),
  40569. buttonRect.getWidth() / 2,
  40570. buttonRect.getHeight());
  40571. incButton->setConnectedEdges (Button::ConnectedOnLeft);
  40572. }
  40573. else
  40574. {
  40575. incButton->setBounds (buttonRect.getX(),
  40576. buttonRect.getY(),
  40577. buttonRect.getWidth(),
  40578. buttonRect.getHeight() / 2);
  40579. incButton->setConnectedEdges (Button::ConnectedOnBottom);
  40580. decButton->setBounds (buttonRect.getX(),
  40581. buttonRect.getCentreY(),
  40582. buttonRect.getWidth(),
  40583. buttonRect.getHeight() / 2);
  40584. decButton->setConnectedEdges (Button::ConnectedOnTop);
  40585. }
  40586. }
  40587. }
  40588. void Slider::focusOfChildComponentChanged (FocusChangeType)
  40589. {
  40590. repaint();
  40591. }
  40592. void Slider::mouseDown (const MouseEvent& e)
  40593. {
  40594. mouseWasHidden = false;
  40595. incDecDragged = false;
  40596. mouseXWhenLastDragged = e.x;
  40597. mouseYWhenLastDragged = e.y;
  40598. mouseDragStartX = e.getMouseDownX();
  40599. mouseDragStartY = e.getMouseDownY();
  40600. if (isEnabled())
  40601. {
  40602. if (e.mods.isPopupMenu() && menuEnabled)
  40603. {
  40604. menuShown = true;
  40605. PopupMenu m;
  40606. m.setLookAndFeel (&getLookAndFeel());
  40607. m.addItem (1, TRANS ("velocity-sensitive mode"), true, isVelocityBased);
  40608. m.addSeparator();
  40609. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  40610. {
  40611. PopupMenu rotaryMenu;
  40612. rotaryMenu.addItem (2, TRANS ("use circular dragging"), true, style == Rotary);
  40613. rotaryMenu.addItem (3, TRANS ("use left-right dragging"), true, style == RotaryHorizontalDrag);
  40614. rotaryMenu.addItem (4, TRANS ("use up-down dragging"), true, style == RotaryVerticalDrag);
  40615. m.addSubMenu (TRANS ("rotary mode"), rotaryMenu);
  40616. }
  40617. const int r = m.show();
  40618. if (r == 1)
  40619. {
  40620. setVelocityBasedMode (! isVelocityBased);
  40621. }
  40622. else if (r == 2)
  40623. {
  40624. setSliderStyle (Rotary);
  40625. }
  40626. else if (r == 3)
  40627. {
  40628. setSliderStyle (RotaryHorizontalDrag);
  40629. }
  40630. else if (r == 4)
  40631. {
  40632. setSliderStyle (RotaryVerticalDrag);
  40633. }
  40634. }
  40635. else if (maximum > minimum)
  40636. {
  40637. menuShown = false;
  40638. if (valueBox != 0)
  40639. valueBox->hideEditor (true);
  40640. sliderBeingDragged = 0;
  40641. if (style == TwoValueHorizontal
  40642. || style == TwoValueVertical
  40643. || style == ThreeValueHorizontal
  40644. || style == ThreeValueVertical)
  40645. {
  40646. const float mousePos = (float) (isVertical() ? e.y : e.x);
  40647. const float normalPosDistance = std::abs (getLinearSliderPos (currentValue.getValue()) - mousePos);
  40648. const float minPosDistance = std::abs (getLinearSliderPos (valueMin.getValue()) - 0.1f - mousePos);
  40649. const float maxPosDistance = std::abs (getLinearSliderPos (valueMax.getValue()) + 0.1f - mousePos);
  40650. if (style == TwoValueHorizontal || style == TwoValueVertical)
  40651. {
  40652. if (maxPosDistance <= minPosDistance)
  40653. sliderBeingDragged = 2;
  40654. else
  40655. sliderBeingDragged = 1;
  40656. }
  40657. else if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  40658. {
  40659. if (normalPosDistance >= minPosDistance && maxPosDistance >= minPosDistance)
  40660. sliderBeingDragged = 1;
  40661. else if (normalPosDistance >= maxPosDistance)
  40662. sliderBeingDragged = 2;
  40663. }
  40664. }
  40665. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  40666. lastAngle = rotaryStart + (rotaryEnd - rotaryStart)
  40667. * valueToProportionOfLength (currentValue.getValue());
  40668. valueWhenLastDragged = ((sliderBeingDragged == 2) ? valueMax
  40669. : ((sliderBeingDragged == 1) ? valueMin
  40670. : currentValue)).getValue();
  40671. valueOnMouseDown = valueWhenLastDragged;
  40672. if (popupDisplayEnabled)
  40673. {
  40674. SliderPopupDisplayComponent* const popup = new SliderPopupDisplayComponent (this);
  40675. popupDisplay = popup;
  40676. if (parentForPopupDisplay != 0)
  40677. {
  40678. parentForPopupDisplay->addChildComponent (popup);
  40679. }
  40680. else
  40681. {
  40682. popup->addToDesktop (0);
  40683. }
  40684. popup->setVisible (true);
  40685. }
  40686. sendDragStart();
  40687. mouseDrag (e);
  40688. }
  40689. }
  40690. }
  40691. void Slider::mouseUp (const MouseEvent&)
  40692. {
  40693. if (isEnabled()
  40694. && (! menuShown)
  40695. && (maximum > minimum)
  40696. && (style != IncDecButtons || incDecDragged))
  40697. {
  40698. restoreMouseIfHidden();
  40699. if (sendChangeOnlyOnRelease && valueOnMouseDown != (double) currentValue.getValue())
  40700. triggerChangeMessage (false);
  40701. sendDragEnd();
  40702. popupDisplay = 0;
  40703. if (style == IncDecButtons)
  40704. {
  40705. incButton->setState (Button::buttonNormal);
  40706. decButton->setState (Button::buttonNormal);
  40707. }
  40708. }
  40709. }
  40710. void Slider::restoreMouseIfHidden()
  40711. {
  40712. if (mouseWasHidden)
  40713. {
  40714. mouseWasHidden = false;
  40715. for (int i = Desktop::getInstance().getNumMouseSources(); --i >= 0;)
  40716. Desktop::getInstance().getMouseSource(i)->enableUnboundedMouseMovement (false);
  40717. const double pos = (sliderBeingDragged == 2) ? getMaxValue()
  40718. : ((sliderBeingDragged == 1) ? getMinValue()
  40719. : (double) currentValue.getValue());
  40720. Point<int> mousePos;
  40721. if (style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  40722. {
  40723. mousePos = Desktop::getLastMouseDownPosition();
  40724. if (style == RotaryHorizontalDrag)
  40725. {
  40726. const double posDiff = valueToProportionOfLength (pos) - valueToProportionOfLength (valueOnMouseDown);
  40727. mousePos += Point<int> (roundToInt (pixelsForFullDragExtent * posDiff), 0);
  40728. }
  40729. else
  40730. {
  40731. const double posDiff = valueToProportionOfLength (valueOnMouseDown) - valueToProportionOfLength (pos);
  40732. mousePos += Point<int> (0, roundToInt (pixelsForFullDragExtent * posDiff));
  40733. }
  40734. }
  40735. else
  40736. {
  40737. const int pixelPos = (int) getLinearSliderPos (pos);
  40738. mousePos = relativePositionToGlobal (Point<int> (isHorizontal() ? pixelPos : (getWidth() / 2),
  40739. isVertical() ? pixelPos : (getHeight() / 2)));
  40740. }
  40741. Desktop::setMousePosition (mousePos);
  40742. }
  40743. }
  40744. void Slider::modifierKeysChanged (const ModifierKeys& modifiers)
  40745. {
  40746. if (isEnabled()
  40747. && style != IncDecButtons
  40748. && style != Rotary
  40749. && isVelocityBased == modifiers.isAnyModifierKeyDown())
  40750. {
  40751. restoreMouseIfHidden();
  40752. }
  40753. }
  40754. namespace SliderHelpers
  40755. {
  40756. double smallestAngleBetween (double a1, double a2) throw()
  40757. {
  40758. return jmin (std::abs (a1 - a2),
  40759. std::abs (a1 + double_Pi * 2.0 - a2),
  40760. std::abs (a2 + double_Pi * 2.0 - a1));
  40761. }
  40762. }
  40763. void Slider::mouseDrag (const MouseEvent& e)
  40764. {
  40765. if (isEnabled()
  40766. && (! menuShown)
  40767. && (maximum > minimum))
  40768. {
  40769. if (style == Rotary)
  40770. {
  40771. int dx = e.x - sliderRect.getCentreX();
  40772. int dy = e.y - sliderRect.getCentreY();
  40773. if (dx * dx + dy * dy > 25)
  40774. {
  40775. double angle = std::atan2 ((double) dx, (double) -dy);
  40776. while (angle < 0.0)
  40777. angle += double_Pi * 2.0;
  40778. if (rotaryStop && ! e.mouseWasClicked())
  40779. {
  40780. if (std::abs (angle - lastAngle) > double_Pi)
  40781. {
  40782. if (angle >= lastAngle)
  40783. angle -= double_Pi * 2.0;
  40784. else
  40785. angle += double_Pi * 2.0;
  40786. }
  40787. if (angle >= lastAngle)
  40788. angle = jmin (angle, (double) jmax (rotaryStart, rotaryEnd));
  40789. else
  40790. angle = jmax (angle, (double) jmin (rotaryStart, rotaryEnd));
  40791. }
  40792. else
  40793. {
  40794. while (angle < rotaryStart)
  40795. angle += double_Pi * 2.0;
  40796. if (angle > rotaryEnd)
  40797. {
  40798. if (SliderHelpers::smallestAngleBetween (angle, rotaryStart)
  40799. <= SliderHelpers::smallestAngleBetween (angle, rotaryEnd))
  40800. angle = rotaryStart;
  40801. else
  40802. angle = rotaryEnd;
  40803. }
  40804. }
  40805. const double proportion = (angle - rotaryStart) / (rotaryEnd - rotaryStart);
  40806. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, proportion));
  40807. lastAngle = angle;
  40808. }
  40809. }
  40810. else
  40811. {
  40812. if (style == LinearBar && e.mouseWasClicked()
  40813. && valueBox != 0 && valueBox->isEditable())
  40814. return;
  40815. if (style == IncDecButtons && ! incDecDragged)
  40816. {
  40817. if (e.getDistanceFromDragStart() < 10 || e.mouseWasClicked())
  40818. return;
  40819. incDecDragged = true;
  40820. mouseDragStartX = e.x;
  40821. mouseDragStartY = e.y;
  40822. }
  40823. if ((isVelocityBased == (userKeyOverridesVelocity ? e.mods.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::commandModifier | ModifierKeys::altModifier)
  40824. : false))
  40825. || ((maximum - minimum) / sliderRegionSize < interval))
  40826. {
  40827. const int mousePos = (isHorizontal() || style == RotaryHorizontalDrag) ? e.x : e.y;
  40828. double scaledMousePos = (mousePos - sliderRegionStart) / (double) sliderRegionSize;
  40829. if (style == RotaryHorizontalDrag
  40830. || style == RotaryVerticalDrag
  40831. || style == IncDecButtons
  40832. || ((style == LinearHorizontal || style == LinearVertical || style == LinearBar)
  40833. && ! snapsToMousePos))
  40834. {
  40835. const int mouseDiff = (style == RotaryHorizontalDrag
  40836. || style == LinearHorizontal
  40837. || style == LinearBar
  40838. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  40839. ? e.x - mouseDragStartX
  40840. : mouseDragStartY - e.y;
  40841. double newPos = valueToProportionOfLength (valueOnMouseDown)
  40842. + mouseDiff * (1.0 / pixelsForFullDragExtent);
  40843. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, newPos));
  40844. if (style == IncDecButtons)
  40845. {
  40846. incButton->setState (mouseDiff < 0 ? Button::buttonNormal : Button::buttonDown);
  40847. decButton->setState (mouseDiff > 0 ? Button::buttonNormal : Button::buttonDown);
  40848. }
  40849. }
  40850. else
  40851. {
  40852. if (isVertical())
  40853. scaledMousePos = 1.0 - scaledMousePos;
  40854. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, scaledMousePos));
  40855. }
  40856. }
  40857. else
  40858. {
  40859. const int mouseDiff = (isHorizontal() || style == RotaryHorizontalDrag
  40860. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  40861. ? e.x - mouseXWhenLastDragged
  40862. : e.y - mouseYWhenLastDragged;
  40863. const double maxSpeed = jmax (200, sliderRegionSize);
  40864. double speed = jlimit (0.0, maxSpeed, (double) abs (mouseDiff));
  40865. if (speed != 0)
  40866. {
  40867. speed = 0.2 * velocityModeSensitivity
  40868. * (1.0 + std::sin (double_Pi * (1.5 + jmin (0.5, velocityModeOffset
  40869. + jmax (0.0, (double) (speed - velocityModeThreshold))
  40870. / maxSpeed))));
  40871. if (mouseDiff < 0)
  40872. speed = -speed;
  40873. if (isVertical() || style == RotaryVerticalDrag
  40874. || (style == IncDecButtons && ! incDecDragDirectionIsHorizontal()))
  40875. speed = -speed;
  40876. const double currentPos = valueToProportionOfLength (valueWhenLastDragged);
  40877. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + speed));
  40878. e.source.enableUnboundedMouseMovement (true, false);
  40879. mouseWasHidden = true;
  40880. }
  40881. }
  40882. }
  40883. valueWhenLastDragged = jlimit (minimum, maximum, valueWhenLastDragged);
  40884. if (sliderBeingDragged == 0)
  40885. {
  40886. setValue (snapValue (valueWhenLastDragged, true),
  40887. ! sendChangeOnlyOnRelease, true);
  40888. }
  40889. else if (sliderBeingDragged == 1)
  40890. {
  40891. setMinValue (snapValue (valueWhenLastDragged, true),
  40892. ! sendChangeOnlyOnRelease, false, true);
  40893. if (e.mods.isShiftDown())
  40894. setMaxValue (getMinValue() + minMaxDiff, false, false, true);
  40895. else
  40896. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  40897. }
  40898. else
  40899. {
  40900. jassert (sliderBeingDragged == 2);
  40901. setMaxValue (snapValue (valueWhenLastDragged, true),
  40902. ! sendChangeOnlyOnRelease, false, true);
  40903. if (e.mods.isShiftDown())
  40904. setMinValue (getMaxValue() - minMaxDiff, false, false, true);
  40905. else
  40906. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  40907. }
  40908. mouseXWhenLastDragged = e.x;
  40909. mouseYWhenLastDragged = e.y;
  40910. }
  40911. }
  40912. void Slider::mouseDoubleClick (const MouseEvent&)
  40913. {
  40914. if (doubleClickToValue
  40915. && isEnabled()
  40916. && style != IncDecButtons
  40917. && minimum <= doubleClickReturnValue
  40918. && maximum >= doubleClickReturnValue)
  40919. {
  40920. sendDragStart();
  40921. setValue (doubleClickReturnValue, true, true);
  40922. sendDragEnd();
  40923. }
  40924. }
  40925. void Slider::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  40926. {
  40927. if (scrollWheelEnabled && isEnabled()
  40928. && style != TwoValueHorizontal
  40929. && style != TwoValueVertical)
  40930. {
  40931. if (maximum > minimum && ! e.mods.isAnyMouseButtonDown())
  40932. {
  40933. if (valueBox != 0)
  40934. valueBox->hideEditor (false);
  40935. const double value = (double) currentValue.getValue();
  40936. const double proportionDelta = (wheelIncrementX != 0 ? -wheelIncrementX : wheelIncrementY) * 0.15f;
  40937. const double currentPos = valueToProportionOfLength (value);
  40938. const double newValue = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + proportionDelta));
  40939. double delta = (newValue != value)
  40940. ? jmax (std::abs (newValue - value), interval) : 0;
  40941. if (value > newValue)
  40942. delta = -delta;
  40943. sendDragStart();
  40944. setValue (snapValue (value + delta, false), true, true);
  40945. sendDragEnd();
  40946. }
  40947. }
  40948. else
  40949. {
  40950. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  40951. }
  40952. }
  40953. void SliderListener::sliderDragStarted (Slider*) // (can't write Slider::Listener due to idiotic VC2005 bug)
  40954. {
  40955. }
  40956. void SliderListener::sliderDragEnded (Slider*)
  40957. {
  40958. }
  40959. END_JUCE_NAMESPACE
  40960. /*** End of inlined file: juce_Slider.cpp ***/
  40961. /*** Start of inlined file: juce_TableHeaderComponent.cpp ***/
  40962. BEGIN_JUCE_NAMESPACE
  40963. class DragOverlayComp : public Component
  40964. {
  40965. public:
  40966. DragOverlayComp (const Image& image_)
  40967. : image (image_)
  40968. {
  40969. image.duplicateIfShared();
  40970. image.multiplyAllAlphas (0.8f);
  40971. setAlwaysOnTop (true);
  40972. }
  40973. ~DragOverlayComp()
  40974. {
  40975. }
  40976. void paint (Graphics& g)
  40977. {
  40978. g.drawImageAt (image, 0, 0);
  40979. }
  40980. private:
  40981. Image image;
  40982. DragOverlayComp (const DragOverlayComp&);
  40983. DragOverlayComp& operator= (const DragOverlayComp&);
  40984. };
  40985. TableHeaderComponent::TableHeaderComponent()
  40986. : columnsChanged (false),
  40987. columnsResized (false),
  40988. sortChanged (false),
  40989. menuActive (true),
  40990. stretchToFit (false),
  40991. columnIdBeingResized (0),
  40992. columnIdBeingDragged (0),
  40993. columnIdUnderMouse (0),
  40994. lastDeliberateWidth (0)
  40995. {
  40996. }
  40997. TableHeaderComponent::~TableHeaderComponent()
  40998. {
  40999. dragOverlayComp = 0;
  41000. }
  41001. void TableHeaderComponent::setPopupMenuActive (const bool hasMenu)
  41002. {
  41003. menuActive = hasMenu;
  41004. }
  41005. bool TableHeaderComponent::isPopupMenuActive() const { return menuActive; }
  41006. int TableHeaderComponent::getNumColumns (const bool onlyCountVisibleColumns) const
  41007. {
  41008. if (onlyCountVisibleColumns)
  41009. {
  41010. int num = 0;
  41011. for (int i = columns.size(); --i >= 0;)
  41012. if (columns.getUnchecked(i)->isVisible())
  41013. ++num;
  41014. return num;
  41015. }
  41016. else
  41017. {
  41018. return columns.size();
  41019. }
  41020. }
  41021. const String TableHeaderComponent::getColumnName (const int columnId) const
  41022. {
  41023. const ColumnInfo* const ci = getInfoForId (columnId);
  41024. return ci != 0 ? ci->name : String::empty;
  41025. }
  41026. void TableHeaderComponent::setColumnName (const int columnId, const String& newName)
  41027. {
  41028. ColumnInfo* const ci = getInfoForId (columnId);
  41029. if (ci != 0 && ci->name != newName)
  41030. {
  41031. ci->name = newName;
  41032. sendColumnsChanged();
  41033. }
  41034. }
  41035. void TableHeaderComponent::addColumn (const String& columnName,
  41036. const int columnId,
  41037. const int width,
  41038. const int minimumWidth,
  41039. const int maximumWidth,
  41040. const int propertyFlags,
  41041. const int insertIndex)
  41042. {
  41043. // can't have a duplicate or null ID!
  41044. jassert (columnId != 0 && getIndexOfColumnId (columnId, false) < 0);
  41045. jassert (width > 0);
  41046. ColumnInfo* const ci = new ColumnInfo();
  41047. ci->name = columnName;
  41048. ci->id = columnId;
  41049. ci->width = width;
  41050. ci->lastDeliberateWidth = width;
  41051. ci->minimumWidth = minimumWidth;
  41052. ci->maximumWidth = maximumWidth;
  41053. if (ci->maximumWidth < 0)
  41054. ci->maximumWidth = std::numeric_limits<int>::max();
  41055. jassert (ci->maximumWidth >= ci->minimumWidth);
  41056. ci->propertyFlags = propertyFlags;
  41057. columns.insert (insertIndex, ci);
  41058. sendColumnsChanged();
  41059. }
  41060. void TableHeaderComponent::removeColumn (const int columnIdToRemove)
  41061. {
  41062. const int index = getIndexOfColumnId (columnIdToRemove, false);
  41063. if (index >= 0)
  41064. {
  41065. columns.remove (index);
  41066. sortChanged = true;
  41067. sendColumnsChanged();
  41068. }
  41069. }
  41070. void TableHeaderComponent::removeAllColumns()
  41071. {
  41072. if (columns.size() > 0)
  41073. {
  41074. columns.clear();
  41075. sendColumnsChanged();
  41076. }
  41077. }
  41078. void TableHeaderComponent::moveColumn (const int columnId, int newIndex)
  41079. {
  41080. const int currentIndex = getIndexOfColumnId (columnId, false);
  41081. newIndex = visibleIndexToTotalIndex (newIndex);
  41082. if (columns [currentIndex] != 0 && currentIndex != newIndex)
  41083. {
  41084. columns.move (currentIndex, newIndex);
  41085. sendColumnsChanged();
  41086. }
  41087. }
  41088. int TableHeaderComponent::getColumnWidth (const int columnId) const
  41089. {
  41090. const ColumnInfo* const ci = getInfoForId (columnId);
  41091. return ci != 0 ? ci->width : 0;
  41092. }
  41093. void TableHeaderComponent::setColumnWidth (const int columnId, const int newWidth)
  41094. {
  41095. ColumnInfo* const ci = getInfoForId (columnId);
  41096. if (ci != 0 && ci->width != newWidth)
  41097. {
  41098. const int numColumns = getNumColumns (true);
  41099. ci->lastDeliberateWidth = ci->width
  41100. = jlimit (ci->minimumWidth, ci->maximumWidth, newWidth);
  41101. if (stretchToFit)
  41102. {
  41103. const int index = getIndexOfColumnId (columnId, true) + 1;
  41104. if (((unsigned int) index) < (unsigned int) numColumns)
  41105. {
  41106. const int x = getColumnPosition (index).getX();
  41107. if (lastDeliberateWidth == 0)
  41108. lastDeliberateWidth = getTotalWidth();
  41109. resizeColumnsToFit (visibleIndexToTotalIndex (index), lastDeliberateWidth - x);
  41110. }
  41111. }
  41112. repaint();
  41113. columnsResized = true;
  41114. triggerAsyncUpdate();
  41115. }
  41116. }
  41117. int TableHeaderComponent::getIndexOfColumnId (const int columnId, const bool onlyCountVisibleColumns) const
  41118. {
  41119. int n = 0;
  41120. for (int i = 0; i < columns.size(); ++i)
  41121. {
  41122. if ((! onlyCountVisibleColumns) || columns.getUnchecked(i)->isVisible())
  41123. {
  41124. if (columns.getUnchecked(i)->id == columnId)
  41125. return n;
  41126. ++n;
  41127. }
  41128. }
  41129. return -1;
  41130. }
  41131. int TableHeaderComponent::getColumnIdOfIndex (int index, const bool onlyCountVisibleColumns) const
  41132. {
  41133. if (onlyCountVisibleColumns)
  41134. index = visibleIndexToTotalIndex (index);
  41135. const ColumnInfo* const ci = columns [index];
  41136. return (ci != 0) ? ci->id : 0;
  41137. }
  41138. const Rectangle<int> TableHeaderComponent::getColumnPosition (const int index) const
  41139. {
  41140. int x = 0, width = 0, n = 0;
  41141. for (int i = 0; i < columns.size(); ++i)
  41142. {
  41143. x += width;
  41144. if (columns.getUnchecked(i)->isVisible())
  41145. {
  41146. width = columns.getUnchecked(i)->width;
  41147. if (n++ == index)
  41148. break;
  41149. }
  41150. else
  41151. {
  41152. width = 0;
  41153. }
  41154. }
  41155. return Rectangle<int> (x, 0, width, getHeight());
  41156. }
  41157. int TableHeaderComponent::getColumnIdAtX (const int xToFind) const
  41158. {
  41159. if (xToFind >= 0)
  41160. {
  41161. int x = 0;
  41162. for (int i = 0; i < columns.size(); ++i)
  41163. {
  41164. const ColumnInfo* const ci = columns.getUnchecked(i);
  41165. if (ci->isVisible())
  41166. {
  41167. x += ci->width;
  41168. if (xToFind < x)
  41169. return ci->id;
  41170. }
  41171. }
  41172. }
  41173. return 0;
  41174. }
  41175. int TableHeaderComponent::getTotalWidth() const
  41176. {
  41177. int w = 0;
  41178. for (int i = columns.size(); --i >= 0;)
  41179. if (columns.getUnchecked(i)->isVisible())
  41180. w += columns.getUnchecked(i)->width;
  41181. return w;
  41182. }
  41183. void TableHeaderComponent::setStretchToFitActive (const bool shouldStretchToFit)
  41184. {
  41185. stretchToFit = shouldStretchToFit;
  41186. lastDeliberateWidth = getTotalWidth();
  41187. resized();
  41188. }
  41189. bool TableHeaderComponent::isStretchToFitActive() const
  41190. {
  41191. return stretchToFit;
  41192. }
  41193. void TableHeaderComponent::resizeAllColumnsToFit (int targetTotalWidth)
  41194. {
  41195. if (stretchToFit && getWidth() > 0
  41196. && columnIdBeingResized == 0 && columnIdBeingDragged == 0)
  41197. {
  41198. lastDeliberateWidth = targetTotalWidth;
  41199. resizeColumnsToFit (0, targetTotalWidth);
  41200. }
  41201. }
  41202. void TableHeaderComponent::resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth)
  41203. {
  41204. targetTotalWidth = jmax (targetTotalWidth, 0);
  41205. StretchableObjectResizer sor;
  41206. int i;
  41207. for (i = firstColumnIndex; i < columns.size(); ++i)
  41208. {
  41209. ColumnInfo* const ci = columns.getUnchecked(i);
  41210. if (ci->isVisible())
  41211. sor.addItem (ci->lastDeliberateWidth, ci->minimumWidth, ci->maximumWidth);
  41212. }
  41213. sor.resizeToFit (targetTotalWidth);
  41214. int visIndex = 0;
  41215. for (i = firstColumnIndex; i < columns.size(); ++i)
  41216. {
  41217. ColumnInfo* const ci = columns.getUnchecked(i);
  41218. if (ci->isVisible())
  41219. {
  41220. const int newWidth = jlimit (ci->minimumWidth, ci->maximumWidth,
  41221. (int) std::floor (sor.getItemSize (visIndex++)));
  41222. if (newWidth != ci->width)
  41223. {
  41224. ci->width = newWidth;
  41225. repaint();
  41226. columnsResized = true;
  41227. triggerAsyncUpdate();
  41228. }
  41229. }
  41230. }
  41231. }
  41232. void TableHeaderComponent::setColumnVisible (const int columnId, const bool shouldBeVisible)
  41233. {
  41234. ColumnInfo* const ci = getInfoForId (columnId);
  41235. if (ci != 0 && shouldBeVisible != ci->isVisible())
  41236. {
  41237. if (shouldBeVisible)
  41238. ci->propertyFlags |= visible;
  41239. else
  41240. ci->propertyFlags &= ~visible;
  41241. sendColumnsChanged();
  41242. resized();
  41243. }
  41244. }
  41245. bool TableHeaderComponent::isColumnVisible (const int columnId) const
  41246. {
  41247. const ColumnInfo* const ci = getInfoForId (columnId);
  41248. return ci != 0 && ci->isVisible();
  41249. }
  41250. void TableHeaderComponent::setSortColumnId (const int columnId, const bool sortForwards)
  41251. {
  41252. if (getSortColumnId() != columnId || isSortedForwards() != sortForwards)
  41253. {
  41254. for (int i = columns.size(); --i >= 0;)
  41255. columns.getUnchecked(i)->propertyFlags &= ~(sortedForwards | sortedBackwards);
  41256. ColumnInfo* const ci = getInfoForId (columnId);
  41257. if (ci != 0)
  41258. ci->propertyFlags |= (sortForwards ? sortedForwards : sortedBackwards);
  41259. reSortTable();
  41260. }
  41261. }
  41262. int TableHeaderComponent::getSortColumnId() const
  41263. {
  41264. for (int i = columns.size(); --i >= 0;)
  41265. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  41266. return columns.getUnchecked(i)->id;
  41267. return 0;
  41268. }
  41269. bool TableHeaderComponent::isSortedForwards() const
  41270. {
  41271. for (int i = columns.size(); --i >= 0;)
  41272. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  41273. return (columns.getUnchecked(i)->propertyFlags & sortedForwards) != 0;
  41274. return true;
  41275. }
  41276. void TableHeaderComponent::reSortTable()
  41277. {
  41278. sortChanged = true;
  41279. repaint();
  41280. triggerAsyncUpdate();
  41281. }
  41282. const String TableHeaderComponent::toString() const
  41283. {
  41284. String s;
  41285. XmlElement doc ("TABLELAYOUT");
  41286. doc.setAttribute ("sortedCol", getSortColumnId());
  41287. doc.setAttribute ("sortForwards", isSortedForwards());
  41288. for (int i = 0; i < columns.size(); ++i)
  41289. {
  41290. const ColumnInfo* const ci = columns.getUnchecked (i);
  41291. XmlElement* const e = doc.createNewChildElement ("COLUMN");
  41292. e->setAttribute ("id", ci->id);
  41293. e->setAttribute ("visible", ci->isVisible());
  41294. e->setAttribute ("width", ci->width);
  41295. }
  41296. return doc.createDocument (String::empty, true, false);
  41297. }
  41298. void TableHeaderComponent::restoreFromString (const String& storedVersion)
  41299. {
  41300. XmlDocument doc (storedVersion);
  41301. ScopedPointer <XmlElement> storedXml (doc.getDocumentElement());
  41302. int index = 0;
  41303. if (storedXml != 0 && storedXml->hasTagName ("TABLELAYOUT"))
  41304. {
  41305. forEachXmlChildElement (*storedXml, col)
  41306. {
  41307. const int tabId = col->getIntAttribute ("id");
  41308. ColumnInfo* const ci = getInfoForId (tabId);
  41309. if (ci != 0)
  41310. {
  41311. columns.move (columns.indexOf (ci), index);
  41312. ci->width = col->getIntAttribute ("width");
  41313. setColumnVisible (tabId, col->getBoolAttribute ("visible"));
  41314. }
  41315. ++index;
  41316. }
  41317. columnsResized = true;
  41318. sendColumnsChanged();
  41319. setSortColumnId (storedXml->getIntAttribute ("sortedCol"),
  41320. storedXml->getBoolAttribute ("sortForwards", true));
  41321. }
  41322. }
  41323. void TableHeaderComponent::addListener (Listener* const newListener)
  41324. {
  41325. listeners.addIfNotAlreadyThere (newListener);
  41326. }
  41327. void TableHeaderComponent::removeListener (Listener* const listenerToRemove)
  41328. {
  41329. listeners.removeValue (listenerToRemove);
  41330. }
  41331. void TableHeaderComponent::columnClicked (int columnId, const ModifierKeys& mods)
  41332. {
  41333. const ColumnInfo* const ci = getInfoForId (columnId);
  41334. if (ci != 0 && (ci->propertyFlags & sortable) != 0 && ! mods.isPopupMenu())
  41335. setSortColumnId (columnId, (ci->propertyFlags & sortedForwards) == 0);
  41336. }
  41337. void TableHeaderComponent::addMenuItems (PopupMenu& menu, const int /*columnIdClicked*/)
  41338. {
  41339. for (int i = 0; i < columns.size(); ++i)
  41340. {
  41341. const ColumnInfo* const ci = columns.getUnchecked(i);
  41342. if ((ci->propertyFlags & appearsOnColumnMenu) != 0)
  41343. menu.addItem (ci->id, ci->name,
  41344. (ci->propertyFlags & (sortedForwards | sortedBackwards)) == 0,
  41345. isColumnVisible (ci->id));
  41346. }
  41347. }
  41348. void TableHeaderComponent::reactToMenuItem (const int menuReturnId, const int /*columnIdClicked*/)
  41349. {
  41350. if (getIndexOfColumnId (menuReturnId, false) >= 0)
  41351. setColumnVisible (menuReturnId, ! isColumnVisible (menuReturnId));
  41352. }
  41353. void TableHeaderComponent::paint (Graphics& g)
  41354. {
  41355. LookAndFeel& lf = getLookAndFeel();
  41356. lf.drawTableHeaderBackground (g, *this);
  41357. const Rectangle<int> clip (g.getClipBounds());
  41358. int x = 0;
  41359. for (int i = 0; i < columns.size(); ++i)
  41360. {
  41361. const ColumnInfo* const ci = columns.getUnchecked(i);
  41362. if (ci->isVisible())
  41363. {
  41364. if (x + ci->width > clip.getX()
  41365. && (ci->id != columnIdBeingDragged
  41366. || dragOverlayComp == 0
  41367. || ! dragOverlayComp->isVisible()))
  41368. {
  41369. g.saveState();
  41370. g.setOrigin (x, 0);
  41371. g.reduceClipRegion (0, 0, ci->width, getHeight());
  41372. lf.drawTableHeaderColumn (g, ci->name, ci->id, ci->width, getHeight(),
  41373. ci->id == columnIdUnderMouse,
  41374. ci->id == columnIdUnderMouse && isMouseButtonDown(),
  41375. ci->propertyFlags);
  41376. g.restoreState();
  41377. }
  41378. x += ci->width;
  41379. if (x >= clip.getRight())
  41380. break;
  41381. }
  41382. }
  41383. }
  41384. void TableHeaderComponent::resized()
  41385. {
  41386. }
  41387. void TableHeaderComponent::mouseMove (const MouseEvent& e)
  41388. {
  41389. updateColumnUnderMouse (e.x, e.y);
  41390. }
  41391. void TableHeaderComponent::mouseEnter (const MouseEvent& e)
  41392. {
  41393. updateColumnUnderMouse (e.x, e.y);
  41394. }
  41395. void TableHeaderComponent::mouseExit (const MouseEvent& e)
  41396. {
  41397. updateColumnUnderMouse (e.x, e.y);
  41398. }
  41399. void TableHeaderComponent::mouseDown (const MouseEvent& e)
  41400. {
  41401. repaint();
  41402. columnIdBeingResized = 0;
  41403. columnIdBeingDragged = 0;
  41404. if (columnIdUnderMouse != 0)
  41405. {
  41406. draggingColumnOffset = e.x - getColumnPosition (getIndexOfColumnId (columnIdUnderMouse, true)).getX();
  41407. if (e.mods.isPopupMenu())
  41408. columnClicked (columnIdUnderMouse, e.mods);
  41409. }
  41410. if (menuActive && e.mods.isPopupMenu())
  41411. showColumnChooserMenu (columnIdUnderMouse);
  41412. }
  41413. void TableHeaderComponent::mouseDrag (const MouseEvent& e)
  41414. {
  41415. if (columnIdBeingResized == 0
  41416. && columnIdBeingDragged == 0
  41417. && ! (e.mouseWasClicked() || e.mods.isPopupMenu()))
  41418. {
  41419. dragOverlayComp = 0;
  41420. columnIdBeingResized = getResizeDraggerAt (e.getMouseDownX());
  41421. if (columnIdBeingResized != 0)
  41422. {
  41423. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  41424. initialColumnWidth = ci->width;
  41425. }
  41426. else
  41427. {
  41428. beginDrag (e);
  41429. }
  41430. }
  41431. if (columnIdBeingResized != 0)
  41432. {
  41433. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  41434. if (ci != 0)
  41435. {
  41436. int w = jlimit (ci->minimumWidth, ci->maximumWidth,
  41437. initialColumnWidth + e.getDistanceFromDragStartX());
  41438. if (stretchToFit)
  41439. {
  41440. // prevent us dragging a column too far right if we're in stretch-to-fit mode
  41441. int minWidthOnRight = 0;
  41442. for (int i = getIndexOfColumnId (columnIdBeingResized, false) + 1; i < columns.size(); ++i)
  41443. if (columns.getUnchecked (i)->isVisible())
  41444. minWidthOnRight += columns.getUnchecked (i)->minimumWidth;
  41445. const Rectangle<int> currentPos (getColumnPosition (getIndexOfColumnId (columnIdBeingResized, true)));
  41446. w = jmax (ci->minimumWidth, jmin (w, getWidth() - minWidthOnRight - currentPos.getX()));
  41447. }
  41448. setColumnWidth (columnIdBeingResized, w);
  41449. }
  41450. }
  41451. else if (columnIdBeingDragged != 0)
  41452. {
  41453. if (e.y >= -50 && e.y < getHeight() + 50)
  41454. {
  41455. if (dragOverlayComp != 0)
  41456. {
  41457. dragOverlayComp->setVisible (true);
  41458. dragOverlayComp->setBounds (jlimit (0,
  41459. jmax (0, getTotalWidth() - dragOverlayComp->getWidth()),
  41460. e.x - draggingColumnOffset),
  41461. 0,
  41462. dragOverlayComp->getWidth(),
  41463. getHeight());
  41464. for (int i = columns.size(); --i >= 0;)
  41465. {
  41466. const int currentIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  41467. int newIndex = currentIndex;
  41468. if (newIndex > 0)
  41469. {
  41470. // if the previous column isn't draggable, we can't move our column
  41471. // past it, because that'd change the undraggable column's position..
  41472. const ColumnInfo* const previous = columns.getUnchecked (newIndex - 1);
  41473. if ((previous->propertyFlags & draggable) != 0)
  41474. {
  41475. const int leftOfPrevious = getColumnPosition (newIndex - 1).getX();
  41476. const int rightOfCurrent = getColumnPosition (newIndex).getRight();
  41477. if (abs (dragOverlayComp->getX() - leftOfPrevious)
  41478. < abs (dragOverlayComp->getRight() - rightOfCurrent))
  41479. {
  41480. --newIndex;
  41481. }
  41482. }
  41483. }
  41484. if (newIndex < columns.size() - 1)
  41485. {
  41486. // if the next column isn't draggable, we can't move our column
  41487. // past it, because that'd change the undraggable column's position..
  41488. const ColumnInfo* const nextCol = columns.getUnchecked (newIndex + 1);
  41489. if ((nextCol->propertyFlags & draggable) != 0)
  41490. {
  41491. const int leftOfCurrent = getColumnPosition (newIndex).getX();
  41492. const int rightOfNext = getColumnPosition (newIndex + 1).getRight();
  41493. if (abs (dragOverlayComp->getX() - leftOfCurrent)
  41494. > abs (dragOverlayComp->getRight() - rightOfNext))
  41495. {
  41496. ++newIndex;
  41497. }
  41498. }
  41499. }
  41500. if (newIndex != currentIndex)
  41501. moveColumn (columnIdBeingDragged, newIndex);
  41502. else
  41503. break;
  41504. }
  41505. }
  41506. }
  41507. else
  41508. {
  41509. endDrag (draggingColumnOriginalIndex);
  41510. }
  41511. }
  41512. }
  41513. void TableHeaderComponent::beginDrag (const MouseEvent& e)
  41514. {
  41515. if (columnIdBeingDragged == 0)
  41516. {
  41517. columnIdBeingDragged = getColumnIdAtX (e.getMouseDownX());
  41518. const ColumnInfo* const ci = getInfoForId (columnIdBeingDragged);
  41519. if (ci == 0 || (ci->propertyFlags & draggable) == 0)
  41520. {
  41521. columnIdBeingDragged = 0;
  41522. }
  41523. else
  41524. {
  41525. draggingColumnOriginalIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  41526. const Rectangle<int> columnRect (getColumnPosition (draggingColumnOriginalIndex));
  41527. const int temp = columnIdBeingDragged;
  41528. columnIdBeingDragged = 0;
  41529. addAndMakeVisible (dragOverlayComp = new DragOverlayComp (createComponentSnapshot (columnRect, false)));
  41530. columnIdBeingDragged = temp;
  41531. dragOverlayComp->setBounds (columnRect);
  41532. for (int i = listeners.size(); --i >= 0;)
  41533. {
  41534. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, columnIdBeingDragged);
  41535. i = jmin (i, listeners.size() - 1);
  41536. }
  41537. }
  41538. }
  41539. }
  41540. void TableHeaderComponent::endDrag (const int finalIndex)
  41541. {
  41542. if (columnIdBeingDragged != 0)
  41543. {
  41544. moveColumn (columnIdBeingDragged, finalIndex);
  41545. columnIdBeingDragged = 0;
  41546. repaint();
  41547. for (int i = listeners.size(); --i >= 0;)
  41548. {
  41549. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, 0);
  41550. i = jmin (i, listeners.size() - 1);
  41551. }
  41552. }
  41553. }
  41554. void TableHeaderComponent::mouseUp (const MouseEvent& e)
  41555. {
  41556. mouseDrag (e);
  41557. for (int i = columns.size(); --i >= 0;)
  41558. if (columns.getUnchecked (i)->isVisible())
  41559. columns.getUnchecked (i)->lastDeliberateWidth = columns.getUnchecked (i)->width;
  41560. columnIdBeingResized = 0;
  41561. repaint();
  41562. endDrag (getIndexOfColumnId (columnIdBeingDragged, true));
  41563. updateColumnUnderMouse (e.x, e.y);
  41564. if (columnIdUnderMouse != 0 && e.mouseWasClicked() && ! e.mods.isPopupMenu())
  41565. columnClicked (columnIdUnderMouse, e.mods);
  41566. dragOverlayComp = 0;
  41567. }
  41568. const MouseCursor TableHeaderComponent::getMouseCursor()
  41569. {
  41570. if (columnIdBeingResized != 0 || (getResizeDraggerAt (getMouseXYRelative().getX()) != 0 && ! isMouseButtonDown()))
  41571. return MouseCursor (MouseCursor::LeftRightResizeCursor);
  41572. return Component::getMouseCursor();
  41573. }
  41574. bool TableHeaderComponent::ColumnInfo::isVisible() const
  41575. {
  41576. return (propertyFlags & TableHeaderComponent::visible) != 0;
  41577. }
  41578. TableHeaderComponent::ColumnInfo* TableHeaderComponent::getInfoForId (const int id) const
  41579. {
  41580. for (int i = columns.size(); --i >= 0;)
  41581. if (columns.getUnchecked(i)->id == id)
  41582. return columns.getUnchecked(i);
  41583. return 0;
  41584. }
  41585. int TableHeaderComponent::visibleIndexToTotalIndex (const int visibleIndex) const
  41586. {
  41587. int n = 0;
  41588. for (int i = 0; i < columns.size(); ++i)
  41589. {
  41590. if (columns.getUnchecked(i)->isVisible())
  41591. {
  41592. if (n == visibleIndex)
  41593. return i;
  41594. ++n;
  41595. }
  41596. }
  41597. return -1;
  41598. }
  41599. void TableHeaderComponent::sendColumnsChanged()
  41600. {
  41601. if (stretchToFit && lastDeliberateWidth > 0)
  41602. resizeAllColumnsToFit (lastDeliberateWidth);
  41603. repaint();
  41604. columnsChanged = true;
  41605. triggerAsyncUpdate();
  41606. }
  41607. void TableHeaderComponent::handleAsyncUpdate()
  41608. {
  41609. const bool changed = columnsChanged || sortChanged;
  41610. const bool sized = columnsResized || changed;
  41611. const bool sorted = sortChanged;
  41612. columnsChanged = false;
  41613. columnsResized = false;
  41614. sortChanged = false;
  41615. if (sorted)
  41616. {
  41617. for (int i = listeners.size(); --i >= 0;)
  41618. {
  41619. listeners.getUnchecked(i)->tableSortOrderChanged (this);
  41620. i = jmin (i, listeners.size() - 1);
  41621. }
  41622. }
  41623. if (changed)
  41624. {
  41625. for (int i = listeners.size(); --i >= 0;)
  41626. {
  41627. listeners.getUnchecked(i)->tableColumnsChanged (this);
  41628. i = jmin (i, listeners.size() - 1);
  41629. }
  41630. }
  41631. if (sized)
  41632. {
  41633. for (int i = listeners.size(); --i >= 0;)
  41634. {
  41635. listeners.getUnchecked(i)->tableColumnsResized (this);
  41636. i = jmin (i, listeners.size() - 1);
  41637. }
  41638. }
  41639. }
  41640. int TableHeaderComponent::getResizeDraggerAt (const int mouseX) const
  41641. {
  41642. if (((unsigned int) mouseX) < (unsigned int) getWidth())
  41643. {
  41644. const int draggableDistance = 3;
  41645. int x = 0;
  41646. for (int i = 0; i < columns.size(); ++i)
  41647. {
  41648. const ColumnInfo* const ci = columns.getUnchecked(i);
  41649. if (ci->isVisible())
  41650. {
  41651. if (abs (mouseX - (x + ci->width)) <= draggableDistance
  41652. && (ci->propertyFlags & resizable) != 0)
  41653. return ci->id;
  41654. x += ci->width;
  41655. }
  41656. }
  41657. }
  41658. return 0;
  41659. }
  41660. void TableHeaderComponent::updateColumnUnderMouse (int x, int y)
  41661. {
  41662. const int newCol = (reallyContains (x, y, true) && getResizeDraggerAt (x) == 0)
  41663. ? getColumnIdAtX (x) : 0;
  41664. if (newCol != columnIdUnderMouse)
  41665. {
  41666. columnIdUnderMouse = newCol;
  41667. repaint();
  41668. }
  41669. }
  41670. void TableHeaderComponent::showColumnChooserMenu (const int columnIdClicked)
  41671. {
  41672. PopupMenu m;
  41673. addMenuItems (m, columnIdClicked);
  41674. if (m.getNumItems() > 0)
  41675. {
  41676. m.setLookAndFeel (&getLookAndFeel());
  41677. const int result = m.show();
  41678. if (result != 0)
  41679. reactToMenuItem (result, columnIdClicked);
  41680. }
  41681. }
  41682. void TableHeaderComponent::Listener::tableColumnDraggingChanged (TableHeaderComponent*, int)
  41683. {
  41684. }
  41685. END_JUCE_NAMESPACE
  41686. /*** End of inlined file: juce_TableHeaderComponent.cpp ***/
  41687. /*** Start of inlined file: juce_TableListBox.cpp ***/
  41688. BEGIN_JUCE_NAMESPACE
  41689. static const char* const tableColumnPropertyTag = "_tableColumnID";
  41690. class TableListRowComp : public Component,
  41691. public TooltipClient
  41692. {
  41693. public:
  41694. TableListRowComp (TableListBox& owner_)
  41695. : owner (owner_),
  41696. row (-1),
  41697. isSelected (false)
  41698. {
  41699. }
  41700. ~TableListRowComp()
  41701. {
  41702. deleteAllChildren();
  41703. }
  41704. void paint (Graphics& g)
  41705. {
  41706. TableListBoxModel* const model = owner.getModel();
  41707. if (model != 0)
  41708. {
  41709. const TableHeaderComponent* const header = owner.getHeader();
  41710. model->paintRowBackground (g, row, getWidth(), getHeight(), isSelected);
  41711. const int numColumns = header->getNumColumns (true);
  41712. for (int i = 0; i < numColumns; ++i)
  41713. {
  41714. if (! columnsWithComponents [i])
  41715. {
  41716. const int columnId = header->getColumnIdOfIndex (i, true);
  41717. Rectangle<int> columnRect (header->getColumnPosition (i));
  41718. columnRect.setSize (columnRect.getWidth(), getHeight());
  41719. g.saveState();
  41720. g.reduceClipRegion (columnRect);
  41721. g.setOrigin (columnRect.getX(), 0);
  41722. model->paintCell (g, row, columnId, columnRect.getWidth(), columnRect.getHeight(), isSelected);
  41723. g.restoreState();
  41724. }
  41725. }
  41726. }
  41727. }
  41728. void update (const int newRow, const bool isNowSelected)
  41729. {
  41730. if (newRow != row || isNowSelected != isSelected)
  41731. {
  41732. row = newRow;
  41733. isSelected = isNowSelected;
  41734. repaint();
  41735. deleteAllChildren();
  41736. }
  41737. if (row < owner.getNumRows())
  41738. {
  41739. jassert (row >= 0);
  41740. const Identifier tagPropertyName ("_tableLastUseNum");
  41741. const int newTag = Random::getSystemRandom().nextInt();
  41742. const TableHeaderComponent* const header = owner.getHeader();
  41743. const int numColumns = header->getNumColumns (true);
  41744. columnsWithComponents.clear();
  41745. if (owner.getModel() != 0)
  41746. {
  41747. for (int i = 0; i < numColumns; ++i)
  41748. {
  41749. const int columnId = header->getColumnIdOfIndex (i, true);
  41750. Component* const newComp
  41751. = owner.getModel()->refreshComponentForCell (row, columnId, isSelected,
  41752. findChildComponentForColumn (columnId));
  41753. if (newComp != 0)
  41754. {
  41755. addAndMakeVisible (newComp);
  41756. newComp->getProperties().set (tagPropertyName, newTag);
  41757. newComp->getProperties().set (tableColumnPropertyTag, columnId);
  41758. const Rectangle<int> columnRect (header->getColumnPosition (i));
  41759. newComp->setBounds (columnRect.getX(), 0, columnRect.getWidth(), getHeight());
  41760. columnsWithComponents.setBit (i);
  41761. }
  41762. }
  41763. }
  41764. for (int i = getNumChildComponents(); --i >= 0;)
  41765. {
  41766. Component* const c = getChildComponent (i);
  41767. if ((int) c->getProperties() [tagPropertyName] != newTag)
  41768. delete c;
  41769. }
  41770. }
  41771. else
  41772. {
  41773. columnsWithComponents.clear();
  41774. deleteAllChildren();
  41775. }
  41776. }
  41777. void resized()
  41778. {
  41779. for (int i = getNumChildComponents(); --i >= 0;)
  41780. {
  41781. Component* const c = getChildComponent (i);
  41782. const int columnId = c->getProperties() [tableColumnPropertyTag];
  41783. if (columnId != 0)
  41784. {
  41785. const Rectangle<int> columnRect (owner.getHeader()->getColumnPosition (owner.getHeader()->getIndexOfColumnId (columnId, true)));
  41786. c->setBounds (columnRect.getX(), 0, columnRect.getWidth(), getHeight());
  41787. }
  41788. }
  41789. }
  41790. void mouseDown (const MouseEvent& e)
  41791. {
  41792. isDragging = false;
  41793. selectRowOnMouseUp = false;
  41794. if (isEnabled())
  41795. {
  41796. if (! isSelected)
  41797. {
  41798. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  41799. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  41800. if (columnId != 0 && owner.getModel() != 0)
  41801. owner.getModel()->cellClicked (row, columnId, e);
  41802. }
  41803. else
  41804. {
  41805. selectRowOnMouseUp = true;
  41806. }
  41807. }
  41808. }
  41809. void mouseDrag (const MouseEvent& e)
  41810. {
  41811. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  41812. {
  41813. const SparseSet<int> selectedRows (owner.getSelectedRows());
  41814. if (selectedRows.size() > 0)
  41815. {
  41816. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  41817. if (dragDescription.isNotEmpty())
  41818. {
  41819. isDragging = true;
  41820. owner.startDragAndDrop (e, dragDescription);
  41821. }
  41822. }
  41823. }
  41824. }
  41825. void mouseUp (const MouseEvent& e)
  41826. {
  41827. if (selectRowOnMouseUp && e.mouseWasClicked() && isEnabled())
  41828. {
  41829. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  41830. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  41831. if (columnId != 0 && owner.getModel() != 0)
  41832. owner.getModel()->cellClicked (row, columnId, e);
  41833. }
  41834. }
  41835. void mouseDoubleClick (const MouseEvent& e)
  41836. {
  41837. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  41838. if (columnId != 0 && owner.getModel() != 0)
  41839. owner.getModel()->cellDoubleClicked (row, columnId, e);
  41840. }
  41841. const String getTooltip()
  41842. {
  41843. const int columnId = owner.getHeader()->getColumnIdAtX (getMouseXYRelative().getX());
  41844. if (columnId != 0 && owner.getModel() != 0)
  41845. return owner.getModel()->getCellTooltip (row, columnId);
  41846. return String::empty;
  41847. }
  41848. Component* findChildComponentForColumn (const int columnId) const
  41849. {
  41850. for (int i = getNumChildComponents(); --i >= 0;)
  41851. {
  41852. Component* const c = getChildComponent (i);
  41853. if ((int) c->getProperties() [tableColumnPropertyTag] == columnId)
  41854. return c;
  41855. }
  41856. return 0;
  41857. }
  41858. juce_UseDebuggingNewOperator
  41859. private:
  41860. TableListBox& owner;
  41861. int row;
  41862. bool isSelected, isDragging, selectRowOnMouseUp;
  41863. BigInteger columnsWithComponents;
  41864. TableListRowComp (const TableListRowComp&);
  41865. TableListRowComp& operator= (const TableListRowComp&);
  41866. };
  41867. class TableListBoxHeader : public TableHeaderComponent
  41868. {
  41869. public:
  41870. TableListBoxHeader (TableListBox& owner_)
  41871. : owner (owner_)
  41872. {
  41873. }
  41874. void addMenuItems (PopupMenu& menu, int columnIdClicked)
  41875. {
  41876. if (owner.isAutoSizeMenuOptionShown())
  41877. {
  41878. menu.addItem (autoSizeColumnId, TRANS("Auto-size this column"), columnIdClicked != 0);
  41879. menu.addItem (autoSizeAllId, TRANS("Auto-size all columns"), owner.getHeader()->getNumColumns (true) > 0);
  41880. menu.addSeparator();
  41881. }
  41882. TableHeaderComponent::addMenuItems (menu, columnIdClicked);
  41883. }
  41884. void reactToMenuItem (int menuReturnId, int columnIdClicked)
  41885. {
  41886. if (menuReturnId == autoSizeColumnId)
  41887. {
  41888. owner.autoSizeColumn (columnIdClicked);
  41889. }
  41890. else if (menuReturnId == autoSizeAllId)
  41891. {
  41892. owner.autoSizeAllColumns();
  41893. }
  41894. else
  41895. {
  41896. TableHeaderComponent::reactToMenuItem (menuReturnId, columnIdClicked);
  41897. }
  41898. }
  41899. juce_UseDebuggingNewOperator
  41900. private:
  41901. TableListBox& owner;
  41902. enum { autoSizeColumnId = 0xf836743, autoSizeAllId = 0xf836744 };
  41903. TableListBoxHeader (const TableListBoxHeader&);
  41904. TableListBoxHeader& operator= (const TableListBoxHeader&);
  41905. };
  41906. TableListBox::TableListBox (const String& name, TableListBoxModel* const model_)
  41907. : ListBox (name, 0),
  41908. model (model_),
  41909. autoSizeOptionsShown (true)
  41910. {
  41911. ListBox::model = this;
  41912. header = new TableListBoxHeader (*this);
  41913. header->setSize (100, 28);
  41914. header->addListener (this);
  41915. setHeaderComponent (header);
  41916. }
  41917. TableListBox::~TableListBox()
  41918. {
  41919. header = 0;
  41920. }
  41921. void TableListBox::setModel (TableListBoxModel* const newModel)
  41922. {
  41923. if (model != newModel)
  41924. {
  41925. model = newModel;
  41926. updateContent();
  41927. }
  41928. }
  41929. int TableListBox::getHeaderHeight() const
  41930. {
  41931. return header->getHeight();
  41932. }
  41933. void TableListBox::setHeaderHeight (const int newHeight)
  41934. {
  41935. header->setSize (header->getWidth(), newHeight);
  41936. resized();
  41937. }
  41938. void TableListBox::autoSizeColumn (const int columnId)
  41939. {
  41940. const int width = model != 0 ? model->getColumnAutoSizeWidth (columnId) : 0;
  41941. if (width > 0)
  41942. header->setColumnWidth (columnId, width);
  41943. }
  41944. void TableListBox::autoSizeAllColumns()
  41945. {
  41946. for (int i = 0; i < header->getNumColumns (true); ++i)
  41947. autoSizeColumn (header->getColumnIdOfIndex (i, true));
  41948. }
  41949. void TableListBox::setAutoSizeMenuOptionShown (const bool shouldBeShown)
  41950. {
  41951. autoSizeOptionsShown = shouldBeShown;
  41952. }
  41953. bool TableListBox::isAutoSizeMenuOptionShown() const
  41954. {
  41955. return autoSizeOptionsShown;
  41956. }
  41957. const Rectangle<int> TableListBox::getCellPosition (const int columnId,
  41958. const int rowNumber,
  41959. const bool relativeToComponentTopLeft) const
  41960. {
  41961. Rectangle<int> headerCell (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  41962. if (relativeToComponentTopLeft)
  41963. headerCell.translate (header->getX(), 0);
  41964. const Rectangle<int> row (getRowPosition (rowNumber, relativeToComponentTopLeft));
  41965. return Rectangle<int> (headerCell.getX(), row.getY(),
  41966. headerCell.getWidth(), row.getHeight());
  41967. }
  41968. Component* TableListBox::getCellComponent (int columnId, int rowNumber) const
  41969. {
  41970. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (rowNumber));
  41971. return rowComp != 0 ? rowComp->findChildComponentForColumn (columnId) : 0;
  41972. }
  41973. void TableListBox::scrollToEnsureColumnIsOnscreen (const int columnId)
  41974. {
  41975. ScrollBar* const scrollbar = getHorizontalScrollBar();
  41976. if (scrollbar != 0)
  41977. {
  41978. const Rectangle<int> pos (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  41979. double x = scrollbar->getCurrentRangeStart();
  41980. const double w = scrollbar->getCurrentRangeSize();
  41981. if (pos.getX() < x)
  41982. x = pos.getX();
  41983. else if (pos.getRight() > x + w)
  41984. x += jmax (0.0, pos.getRight() - (x + w));
  41985. scrollbar->setCurrentRangeStart (x);
  41986. }
  41987. }
  41988. int TableListBox::getNumRows()
  41989. {
  41990. return model != 0 ? model->getNumRows() : 0;
  41991. }
  41992. void TableListBox::paintListBoxItem (int, Graphics&, int, int, bool)
  41993. {
  41994. }
  41995. Component* TableListBox::refreshComponentForRow (int rowNumber, bool isRowSelected_, Component* existingComponentToUpdate)
  41996. {
  41997. if (existingComponentToUpdate == 0)
  41998. existingComponentToUpdate = new TableListRowComp (*this);
  41999. static_cast <TableListRowComp*> (existingComponentToUpdate)->update (rowNumber, isRowSelected_);
  42000. return existingComponentToUpdate;
  42001. }
  42002. void TableListBox::selectedRowsChanged (int row)
  42003. {
  42004. if (model != 0)
  42005. model->selectedRowsChanged (row);
  42006. }
  42007. void TableListBox::deleteKeyPressed (int row)
  42008. {
  42009. if (model != 0)
  42010. model->deleteKeyPressed (row);
  42011. }
  42012. void TableListBox::returnKeyPressed (int row)
  42013. {
  42014. if (model != 0)
  42015. model->returnKeyPressed (row);
  42016. }
  42017. void TableListBox::backgroundClicked()
  42018. {
  42019. if (model != 0)
  42020. model->backgroundClicked();
  42021. }
  42022. void TableListBox::listWasScrolled()
  42023. {
  42024. if (model != 0)
  42025. model->listWasScrolled();
  42026. }
  42027. void TableListBox::tableColumnsChanged (TableHeaderComponent*)
  42028. {
  42029. setMinimumContentWidth (header->getTotalWidth());
  42030. repaint();
  42031. updateColumnComponents();
  42032. }
  42033. void TableListBox::tableColumnsResized (TableHeaderComponent*)
  42034. {
  42035. setMinimumContentWidth (header->getTotalWidth());
  42036. repaint();
  42037. updateColumnComponents();
  42038. }
  42039. void TableListBox::tableSortOrderChanged (TableHeaderComponent*)
  42040. {
  42041. if (model != 0)
  42042. model->sortOrderChanged (header->getSortColumnId(),
  42043. header->isSortedForwards());
  42044. }
  42045. void TableListBox::tableColumnDraggingChanged (TableHeaderComponent*, int columnIdNowBeingDragged_)
  42046. {
  42047. columnIdNowBeingDragged = columnIdNowBeingDragged_;
  42048. repaint();
  42049. }
  42050. void TableListBox::resized()
  42051. {
  42052. ListBox::resized();
  42053. header->resizeAllColumnsToFit (getVisibleContentWidth());
  42054. setMinimumContentWidth (header->getTotalWidth());
  42055. }
  42056. void TableListBox::updateColumnComponents() const
  42057. {
  42058. const int firstRow = getRowContainingPosition (0, 0);
  42059. for (int i = firstRow + getNumRowsOnScreen() + 2; --i >= firstRow;)
  42060. {
  42061. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (i));
  42062. if (rowComp != 0)
  42063. rowComp->resized();
  42064. }
  42065. }
  42066. void TableListBoxModel::cellClicked (int, int, const MouseEvent&)
  42067. {
  42068. }
  42069. void TableListBoxModel::cellDoubleClicked (int, int, const MouseEvent&)
  42070. {
  42071. }
  42072. void TableListBoxModel::backgroundClicked()
  42073. {
  42074. }
  42075. void TableListBoxModel::sortOrderChanged (int, const bool)
  42076. {
  42077. }
  42078. int TableListBoxModel::getColumnAutoSizeWidth (int)
  42079. {
  42080. return 0;
  42081. }
  42082. void TableListBoxModel::selectedRowsChanged (int)
  42083. {
  42084. }
  42085. void TableListBoxModel::deleteKeyPressed (int)
  42086. {
  42087. }
  42088. void TableListBoxModel::returnKeyPressed (int)
  42089. {
  42090. }
  42091. void TableListBoxModel::listWasScrolled()
  42092. {
  42093. }
  42094. const String TableListBoxModel::getCellTooltip (int /*rowNumber*/, int /*columnId*/)
  42095. {
  42096. return String::empty;
  42097. }
  42098. const String TableListBoxModel::getDragSourceDescription (const SparseSet<int>&)
  42099. {
  42100. return String::empty;
  42101. }
  42102. Component* TableListBoxModel::refreshComponentForCell (int, int, bool, Component* existingComponentToUpdate)
  42103. {
  42104. (void) existingComponentToUpdate;
  42105. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  42106. return 0;
  42107. }
  42108. END_JUCE_NAMESPACE
  42109. /*** End of inlined file: juce_TableListBox.cpp ***/
  42110. /*** Start of inlined file: juce_TextEditor.cpp ***/
  42111. BEGIN_JUCE_NAMESPACE
  42112. // a word or space that can't be broken down any further
  42113. struct TextAtom
  42114. {
  42115. String atomText;
  42116. float width;
  42117. int numChars;
  42118. bool isWhitespace() const { return CharacterFunctions::isWhitespace (atomText[0]); }
  42119. bool isNewLine() const { return atomText[0] == '\r' || atomText[0] == '\n'; }
  42120. const String getText (const juce_wchar passwordCharacter) const
  42121. {
  42122. if (passwordCharacter == 0)
  42123. return atomText;
  42124. else
  42125. return String::repeatedString (String::charToString (passwordCharacter),
  42126. atomText.length());
  42127. }
  42128. const String getTrimmedText (const juce_wchar passwordCharacter) const
  42129. {
  42130. if (passwordCharacter == 0)
  42131. return atomText.substring (0, numChars);
  42132. else if (isNewLine())
  42133. return String::empty;
  42134. else
  42135. return String::repeatedString (String::charToString (passwordCharacter), numChars);
  42136. }
  42137. };
  42138. // a run of text with a single font and colour
  42139. class TextEditor::UniformTextSection
  42140. {
  42141. public:
  42142. UniformTextSection (const String& text,
  42143. const Font& font_,
  42144. const Colour& colour_,
  42145. const juce_wchar passwordCharacter)
  42146. : font (font_),
  42147. colour (colour_)
  42148. {
  42149. initialiseAtoms (text, passwordCharacter);
  42150. }
  42151. UniformTextSection (const UniformTextSection& other)
  42152. : font (other.font),
  42153. colour (other.colour)
  42154. {
  42155. atoms.ensureStorageAllocated (other.atoms.size());
  42156. for (int i = 0; i < other.atoms.size(); ++i)
  42157. atoms.add (new TextAtom (*other.atoms.getUnchecked(i)));
  42158. }
  42159. ~UniformTextSection()
  42160. {
  42161. // (no need to delete the atoms, as they're explicitly deleted by the caller)
  42162. }
  42163. void clear()
  42164. {
  42165. for (int i = atoms.size(); --i >= 0;)
  42166. delete getAtom(i);
  42167. atoms.clear();
  42168. }
  42169. int getNumAtoms() const
  42170. {
  42171. return atoms.size();
  42172. }
  42173. TextAtom* getAtom (const int index) const throw()
  42174. {
  42175. return atoms.getUnchecked (index);
  42176. }
  42177. void append (const UniformTextSection& other, const juce_wchar passwordCharacter)
  42178. {
  42179. if (other.atoms.size() > 0)
  42180. {
  42181. TextAtom* const lastAtom = atoms.getLast();
  42182. int i = 0;
  42183. if (lastAtom != 0)
  42184. {
  42185. if (! CharacterFunctions::isWhitespace (lastAtom->atomText.getLastCharacter()))
  42186. {
  42187. TextAtom* const first = other.getAtom(0);
  42188. if (! CharacterFunctions::isWhitespace (first->atomText[0]))
  42189. {
  42190. lastAtom->atomText += first->atomText;
  42191. lastAtom->numChars = (uint16) (lastAtom->numChars + first->numChars);
  42192. lastAtom->width = font.getStringWidthFloat (lastAtom->getText (passwordCharacter));
  42193. delete first;
  42194. ++i;
  42195. }
  42196. }
  42197. }
  42198. atoms.ensureStorageAllocated (atoms.size() + other.atoms.size() - i);
  42199. while (i < other.atoms.size())
  42200. {
  42201. atoms.add (other.getAtom(i));
  42202. ++i;
  42203. }
  42204. }
  42205. }
  42206. UniformTextSection* split (const int indexToBreakAt,
  42207. const juce_wchar passwordCharacter)
  42208. {
  42209. UniformTextSection* const section2 = new UniformTextSection (String::empty,
  42210. font, colour,
  42211. passwordCharacter);
  42212. int index = 0;
  42213. for (int i = 0; i < atoms.size(); ++i)
  42214. {
  42215. TextAtom* const atom = getAtom(i);
  42216. const int nextIndex = index + atom->numChars;
  42217. if (index == indexToBreakAt)
  42218. {
  42219. int j;
  42220. for (j = i; j < atoms.size(); ++j)
  42221. section2->atoms.add (getAtom (j));
  42222. for (j = atoms.size(); --j >= i;)
  42223. atoms.remove (j);
  42224. break;
  42225. }
  42226. else if (indexToBreakAt >= index && indexToBreakAt < nextIndex)
  42227. {
  42228. TextAtom* const secondAtom = new TextAtom();
  42229. secondAtom->atomText = atom->atomText.substring (indexToBreakAt - index);
  42230. secondAtom->width = font.getStringWidthFloat (secondAtom->getText (passwordCharacter));
  42231. secondAtom->numChars = (uint16) secondAtom->atomText.length();
  42232. section2->atoms.add (secondAtom);
  42233. atom->atomText = atom->atomText.substring (0, indexToBreakAt - index);
  42234. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  42235. atom->numChars = (uint16) (indexToBreakAt - index);
  42236. int j;
  42237. for (j = i + 1; j < atoms.size(); ++j)
  42238. section2->atoms.add (getAtom (j));
  42239. for (j = atoms.size(); --j > i;)
  42240. atoms.remove (j);
  42241. break;
  42242. }
  42243. index = nextIndex;
  42244. }
  42245. return section2;
  42246. }
  42247. void appendAllText (String::Concatenator& concatenator) const
  42248. {
  42249. for (int i = 0; i < atoms.size(); ++i)
  42250. concatenator.append (getAtom(i)->atomText);
  42251. }
  42252. void appendSubstring (String::Concatenator& concatenator,
  42253. const Range<int>& range) const
  42254. {
  42255. int index = 0;
  42256. for (int i = 0; i < atoms.size(); ++i)
  42257. {
  42258. const TextAtom* const atom = getAtom (i);
  42259. const int nextIndex = index + atom->numChars;
  42260. if (range.getStart() < nextIndex)
  42261. {
  42262. if (range.getEnd() <= index)
  42263. break;
  42264. const Range<int> r ((range - index).getIntersectionWith (Range<int> (0, (int) atom->numChars)));
  42265. if (! r.isEmpty())
  42266. concatenator.append (atom->atomText.substring (r.getStart(), r.getEnd()));
  42267. }
  42268. index = nextIndex;
  42269. }
  42270. }
  42271. int getTotalLength() const
  42272. {
  42273. int total = 0;
  42274. for (int i = atoms.size(); --i >= 0;)
  42275. total += getAtom(i)->numChars;
  42276. return total;
  42277. }
  42278. void setFont (const Font& newFont,
  42279. const juce_wchar passwordCharacter)
  42280. {
  42281. if (font != newFont)
  42282. {
  42283. font = newFont;
  42284. for (int i = atoms.size(); --i >= 0;)
  42285. {
  42286. TextAtom* const atom = atoms.getUnchecked(i);
  42287. atom->width = newFont.getStringWidthFloat (atom->getText (passwordCharacter));
  42288. }
  42289. }
  42290. }
  42291. juce_UseDebuggingNewOperator
  42292. Font font;
  42293. Colour colour;
  42294. private:
  42295. Array <TextAtom*> atoms;
  42296. void initialiseAtoms (const String& textToParse,
  42297. const juce_wchar passwordCharacter)
  42298. {
  42299. int i = 0;
  42300. const int len = textToParse.length();
  42301. const juce_wchar* const text = textToParse;
  42302. while (i < len)
  42303. {
  42304. int start = i;
  42305. // create a whitespace atom unless it starts with non-ws
  42306. if (CharacterFunctions::isWhitespace (text[i])
  42307. && text[i] != '\r'
  42308. && text[i] != '\n')
  42309. {
  42310. while (i < len
  42311. && CharacterFunctions::isWhitespace (text[i])
  42312. && text[i] != '\r'
  42313. && text[i] != '\n')
  42314. {
  42315. ++i;
  42316. }
  42317. }
  42318. else
  42319. {
  42320. if (text[i] == '\r')
  42321. {
  42322. ++i;
  42323. if ((i < len) && (text[i] == '\n'))
  42324. {
  42325. ++start;
  42326. ++i;
  42327. }
  42328. }
  42329. else if (text[i] == '\n')
  42330. {
  42331. ++i;
  42332. }
  42333. else
  42334. {
  42335. while ((i < len) && ! CharacterFunctions::isWhitespace (text[i]))
  42336. ++i;
  42337. }
  42338. }
  42339. TextAtom* const atom = new TextAtom();
  42340. atom->atomText = String (text + start, i - start);
  42341. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  42342. atom->numChars = (uint16) (i - start);
  42343. atoms.add (atom);
  42344. }
  42345. }
  42346. UniformTextSection& operator= (const UniformTextSection& other);
  42347. };
  42348. class TextEditor::Iterator
  42349. {
  42350. public:
  42351. Iterator (const Array <UniformTextSection*>& sections_,
  42352. const float wordWrapWidth_,
  42353. const juce_wchar passwordCharacter_)
  42354. : indexInText (0),
  42355. lineY (0),
  42356. lineHeight (0),
  42357. maxDescent (0),
  42358. atomX (0),
  42359. atomRight (0),
  42360. atom (0),
  42361. currentSection (0),
  42362. sections (sections_),
  42363. sectionIndex (0),
  42364. atomIndex (0),
  42365. wordWrapWidth (wordWrapWidth_),
  42366. passwordCharacter (passwordCharacter_)
  42367. {
  42368. jassert (wordWrapWidth_ > 0);
  42369. if (sections.size() > 0)
  42370. {
  42371. currentSection = sections.getUnchecked (sectionIndex);
  42372. if (currentSection != 0)
  42373. beginNewLine();
  42374. }
  42375. }
  42376. Iterator (const Iterator& other)
  42377. : indexInText (other.indexInText),
  42378. lineY (other.lineY),
  42379. lineHeight (other.lineHeight),
  42380. maxDescent (other.maxDescent),
  42381. atomX (other.atomX),
  42382. atomRight (other.atomRight),
  42383. atom (other.atom),
  42384. currentSection (other.currentSection),
  42385. sections (other.sections),
  42386. sectionIndex (other.sectionIndex),
  42387. atomIndex (other.atomIndex),
  42388. wordWrapWidth (other.wordWrapWidth),
  42389. passwordCharacter (other.passwordCharacter),
  42390. tempAtom (other.tempAtom)
  42391. {
  42392. }
  42393. ~Iterator()
  42394. {
  42395. }
  42396. bool next()
  42397. {
  42398. if (atom == &tempAtom)
  42399. {
  42400. const int numRemaining = tempAtom.atomText.length() - tempAtom.numChars;
  42401. if (numRemaining > 0)
  42402. {
  42403. tempAtom.atomText = tempAtom.atomText.substring (tempAtom.numChars);
  42404. atomX = 0;
  42405. if (tempAtom.numChars > 0)
  42406. lineY += lineHeight;
  42407. indexInText += tempAtom.numChars;
  42408. GlyphArrangement g;
  42409. g.addLineOfText (currentSection->font, atom->getText (passwordCharacter), 0.0f, 0.0f);
  42410. int split;
  42411. for (split = 0; split < g.getNumGlyphs(); ++split)
  42412. if (shouldWrap (g.getGlyph (split).getRight()))
  42413. break;
  42414. if (split > 0 && split <= numRemaining)
  42415. {
  42416. tempAtom.numChars = (uint16) split;
  42417. tempAtom.width = g.getGlyph (split - 1).getRight();
  42418. atomRight = atomX + tempAtom.width;
  42419. return true;
  42420. }
  42421. }
  42422. }
  42423. bool forceNewLine = false;
  42424. if (sectionIndex >= sections.size())
  42425. {
  42426. moveToEndOfLastAtom();
  42427. return false;
  42428. }
  42429. else if (atomIndex >= currentSection->getNumAtoms() - 1)
  42430. {
  42431. if (atomIndex >= currentSection->getNumAtoms())
  42432. {
  42433. if (++sectionIndex >= sections.size())
  42434. {
  42435. moveToEndOfLastAtom();
  42436. return false;
  42437. }
  42438. atomIndex = 0;
  42439. currentSection = sections.getUnchecked (sectionIndex);
  42440. }
  42441. else
  42442. {
  42443. const TextAtom* const lastAtom = currentSection->getAtom (atomIndex);
  42444. if (! lastAtom->isWhitespace())
  42445. {
  42446. // handle the case where the last atom in a section is actually part of the same
  42447. // word as the first atom of the next section...
  42448. float right = atomRight + lastAtom->width;
  42449. float lineHeight2 = lineHeight;
  42450. float maxDescent2 = maxDescent;
  42451. for (int section = sectionIndex + 1; section < sections.size(); ++section)
  42452. {
  42453. const UniformTextSection* const s = sections.getUnchecked (section);
  42454. if (s->getNumAtoms() == 0)
  42455. break;
  42456. const TextAtom* const nextAtom = s->getAtom (0);
  42457. if (nextAtom->isWhitespace())
  42458. break;
  42459. right += nextAtom->width;
  42460. lineHeight2 = jmax (lineHeight2, s->font.getHeight());
  42461. maxDescent2 = jmax (maxDescent2, s->font.getDescent());
  42462. if (shouldWrap (right))
  42463. {
  42464. lineHeight = lineHeight2;
  42465. maxDescent = maxDescent2;
  42466. forceNewLine = true;
  42467. break;
  42468. }
  42469. if (s->getNumAtoms() > 1)
  42470. break;
  42471. }
  42472. }
  42473. }
  42474. }
  42475. if (atom != 0)
  42476. {
  42477. atomX = atomRight;
  42478. indexInText += atom->numChars;
  42479. if (atom->isNewLine())
  42480. beginNewLine();
  42481. }
  42482. atom = currentSection->getAtom (atomIndex);
  42483. atomRight = atomX + atom->width;
  42484. ++atomIndex;
  42485. if (shouldWrap (atomRight) || forceNewLine)
  42486. {
  42487. if (atom->isWhitespace())
  42488. {
  42489. // leave whitespace at the end of a line, but truncate it to avoid scrolling
  42490. atomRight = jmin (atomRight, wordWrapWidth);
  42491. }
  42492. else
  42493. {
  42494. atomRight = atom->width;
  42495. if (shouldWrap (atomRight)) // atom too big to fit on a line, so break it up..
  42496. {
  42497. tempAtom = *atom;
  42498. tempAtom.width = 0;
  42499. tempAtom.numChars = 0;
  42500. atom = &tempAtom;
  42501. if (atomX > 0)
  42502. beginNewLine();
  42503. return next();
  42504. }
  42505. beginNewLine();
  42506. return true;
  42507. }
  42508. }
  42509. return true;
  42510. }
  42511. void beginNewLine()
  42512. {
  42513. atomX = 0;
  42514. lineY += lineHeight;
  42515. int tempSectionIndex = sectionIndex;
  42516. int tempAtomIndex = atomIndex;
  42517. const UniformTextSection* section = sections.getUnchecked (tempSectionIndex);
  42518. lineHeight = section->font.getHeight();
  42519. maxDescent = section->font.getDescent();
  42520. float x = (atom != 0) ? atom->width : 0;
  42521. while (! shouldWrap (x))
  42522. {
  42523. if (tempSectionIndex >= sections.size())
  42524. break;
  42525. bool checkSize = false;
  42526. if (tempAtomIndex >= section->getNumAtoms())
  42527. {
  42528. if (++tempSectionIndex >= sections.size())
  42529. break;
  42530. tempAtomIndex = 0;
  42531. section = sections.getUnchecked (tempSectionIndex);
  42532. checkSize = true;
  42533. }
  42534. const TextAtom* const nextAtom = section->getAtom (tempAtomIndex);
  42535. if (nextAtom == 0)
  42536. break;
  42537. x += nextAtom->width;
  42538. if (shouldWrap (x) || nextAtom->isNewLine())
  42539. break;
  42540. if (checkSize)
  42541. {
  42542. lineHeight = jmax (lineHeight, section->font.getHeight());
  42543. maxDescent = jmax (maxDescent, section->font.getDescent());
  42544. }
  42545. ++tempAtomIndex;
  42546. }
  42547. }
  42548. void draw (Graphics& g, const UniformTextSection*& lastSection) const
  42549. {
  42550. if (passwordCharacter != 0 || ! atom->isWhitespace())
  42551. {
  42552. if (lastSection != currentSection)
  42553. {
  42554. lastSection = currentSection;
  42555. g.setColour (currentSection->colour);
  42556. g.setFont (currentSection->font);
  42557. }
  42558. jassert (atom->getTrimmedText (passwordCharacter).isNotEmpty());
  42559. GlyphArrangement ga;
  42560. ga.addLineOfText (currentSection->font,
  42561. atom->getTrimmedText (passwordCharacter),
  42562. atomX,
  42563. (float) roundToInt (lineY + lineHeight - maxDescent));
  42564. ga.draw (g);
  42565. }
  42566. }
  42567. void drawSelection (Graphics& g,
  42568. const Range<int>& selection) const
  42569. {
  42570. const int startX = roundToInt (indexToX (selection.getStart()));
  42571. const int endX = roundToInt (indexToX (selection.getEnd()));
  42572. const int y = roundToInt (lineY);
  42573. const int nextY = roundToInt (lineY + lineHeight);
  42574. g.fillRect (startX, y, endX - startX, nextY - y);
  42575. }
  42576. void drawSelectedText (Graphics& g,
  42577. const Range<int>& selection,
  42578. const Colour& selectedTextColour) const
  42579. {
  42580. if (passwordCharacter != 0 || ! atom->isWhitespace())
  42581. {
  42582. GlyphArrangement ga;
  42583. ga.addLineOfText (currentSection->font,
  42584. atom->getTrimmedText (passwordCharacter),
  42585. atomX,
  42586. (float) roundToInt (lineY + lineHeight - maxDescent));
  42587. if (selection.getEnd() < indexInText + atom->numChars)
  42588. {
  42589. GlyphArrangement ga2 (ga);
  42590. ga2.removeRangeOfGlyphs (0, selection.getEnd() - indexInText);
  42591. ga.removeRangeOfGlyphs (selection.getEnd() - indexInText, -1);
  42592. g.setColour (currentSection->colour);
  42593. ga2.draw (g);
  42594. }
  42595. if (selection.getStart() > indexInText)
  42596. {
  42597. GlyphArrangement ga2 (ga);
  42598. ga2.removeRangeOfGlyphs (selection.getStart() - indexInText, -1);
  42599. ga.removeRangeOfGlyphs (0, selection.getStart() - indexInText);
  42600. g.setColour (currentSection->colour);
  42601. ga2.draw (g);
  42602. }
  42603. g.setColour (selectedTextColour);
  42604. ga.draw (g);
  42605. }
  42606. }
  42607. float indexToX (const int indexToFind) const
  42608. {
  42609. if (indexToFind <= indexInText)
  42610. return atomX;
  42611. if (indexToFind >= indexInText + atom->numChars)
  42612. return atomRight;
  42613. GlyphArrangement g;
  42614. g.addLineOfText (currentSection->font,
  42615. atom->getText (passwordCharacter),
  42616. atomX, 0.0f);
  42617. if (indexToFind - indexInText >= g.getNumGlyphs())
  42618. return atomRight;
  42619. return jmin (atomRight, g.getGlyph (indexToFind - indexInText).getLeft());
  42620. }
  42621. int xToIndex (const float xToFind) const
  42622. {
  42623. if (xToFind <= atomX || atom->isNewLine())
  42624. return indexInText;
  42625. if (xToFind >= atomRight)
  42626. return indexInText + atom->numChars;
  42627. GlyphArrangement g;
  42628. g.addLineOfText (currentSection->font,
  42629. atom->getText (passwordCharacter),
  42630. atomX, 0.0f);
  42631. int j;
  42632. for (j = 0; j < g.getNumGlyphs(); ++j)
  42633. if ((g.getGlyph(j).getLeft() + g.getGlyph(j).getRight()) / 2 > xToFind)
  42634. break;
  42635. return indexInText + j;
  42636. }
  42637. bool getCharPosition (const int index, float& cx, float& cy, float& lineHeight_)
  42638. {
  42639. while (next())
  42640. {
  42641. if (indexInText + atom->numChars > index)
  42642. {
  42643. cx = indexToX (index);
  42644. cy = lineY;
  42645. lineHeight_ = lineHeight;
  42646. return true;
  42647. }
  42648. }
  42649. cx = atomX;
  42650. cy = lineY;
  42651. lineHeight_ = lineHeight;
  42652. return false;
  42653. }
  42654. juce_UseDebuggingNewOperator
  42655. int indexInText;
  42656. float lineY, lineHeight, maxDescent;
  42657. float atomX, atomRight;
  42658. const TextAtom* atom;
  42659. const UniformTextSection* currentSection;
  42660. private:
  42661. const Array <UniformTextSection*>& sections;
  42662. int sectionIndex, atomIndex;
  42663. const float wordWrapWidth;
  42664. const juce_wchar passwordCharacter;
  42665. TextAtom tempAtom;
  42666. Iterator& operator= (const Iterator&);
  42667. void moveToEndOfLastAtom()
  42668. {
  42669. if (atom != 0)
  42670. {
  42671. atomX = atomRight;
  42672. if (atom->isNewLine())
  42673. {
  42674. atomX = 0.0f;
  42675. lineY += lineHeight;
  42676. }
  42677. }
  42678. }
  42679. bool shouldWrap (const float x) const
  42680. {
  42681. return (x - 0.0001f) >= wordWrapWidth;
  42682. }
  42683. };
  42684. class TextEditor::InsertAction : public UndoableAction
  42685. {
  42686. TextEditor& owner;
  42687. const String text;
  42688. const int insertIndex, oldCaretPos, newCaretPos;
  42689. const Font font;
  42690. const Colour colour;
  42691. InsertAction (const InsertAction&);
  42692. InsertAction& operator= (const InsertAction&);
  42693. public:
  42694. InsertAction (TextEditor& owner_,
  42695. const String& text_,
  42696. const int insertIndex_,
  42697. const Font& font_,
  42698. const Colour& colour_,
  42699. const int oldCaretPos_,
  42700. const int newCaretPos_)
  42701. : owner (owner_),
  42702. text (text_),
  42703. insertIndex (insertIndex_),
  42704. oldCaretPos (oldCaretPos_),
  42705. newCaretPos (newCaretPos_),
  42706. font (font_),
  42707. colour (colour_)
  42708. {
  42709. }
  42710. ~InsertAction()
  42711. {
  42712. }
  42713. bool perform()
  42714. {
  42715. owner.insert (text, insertIndex, font, colour, 0, newCaretPos);
  42716. return true;
  42717. }
  42718. bool undo()
  42719. {
  42720. owner.remove (Range<int> (insertIndex, insertIndex + text.length()), 0, oldCaretPos);
  42721. return true;
  42722. }
  42723. int getSizeInUnits()
  42724. {
  42725. return text.length() + 16;
  42726. }
  42727. };
  42728. class TextEditor::RemoveAction : public UndoableAction
  42729. {
  42730. TextEditor& owner;
  42731. const Range<int> range;
  42732. const int oldCaretPos, newCaretPos;
  42733. Array <UniformTextSection*> removedSections;
  42734. RemoveAction (const RemoveAction&);
  42735. RemoveAction& operator= (const RemoveAction&);
  42736. public:
  42737. RemoveAction (TextEditor& owner_,
  42738. const Range<int> range_,
  42739. const int oldCaretPos_,
  42740. const int newCaretPos_,
  42741. const Array <UniformTextSection*>& removedSections_)
  42742. : owner (owner_),
  42743. range (range_),
  42744. oldCaretPos (oldCaretPos_),
  42745. newCaretPos (newCaretPos_),
  42746. removedSections (removedSections_)
  42747. {
  42748. }
  42749. ~RemoveAction()
  42750. {
  42751. for (int i = removedSections.size(); --i >= 0;)
  42752. {
  42753. UniformTextSection* const section = removedSections.getUnchecked (i);
  42754. section->clear();
  42755. delete section;
  42756. }
  42757. }
  42758. bool perform()
  42759. {
  42760. owner.remove (range, 0, newCaretPos);
  42761. return true;
  42762. }
  42763. bool undo()
  42764. {
  42765. owner.reinsert (range.getStart(), removedSections);
  42766. owner.moveCursorTo (oldCaretPos, false);
  42767. return true;
  42768. }
  42769. int getSizeInUnits()
  42770. {
  42771. int n = 0;
  42772. for (int i = removedSections.size(); --i >= 0;)
  42773. n += removedSections.getUnchecked (i)->getTotalLength();
  42774. return n + 16;
  42775. }
  42776. };
  42777. class TextEditor::TextHolderComponent : public Component,
  42778. public Timer,
  42779. public Value::Listener
  42780. {
  42781. public:
  42782. TextHolderComponent (TextEditor& owner_)
  42783. : owner (owner_)
  42784. {
  42785. setWantsKeyboardFocus (false);
  42786. setInterceptsMouseClicks (false, true);
  42787. owner.getTextValue().addListener (this);
  42788. }
  42789. ~TextHolderComponent()
  42790. {
  42791. owner.getTextValue().removeListener (this);
  42792. }
  42793. void paint (Graphics& g)
  42794. {
  42795. owner.drawContent (g);
  42796. }
  42797. void timerCallback()
  42798. {
  42799. owner.timerCallbackInt();
  42800. }
  42801. const MouseCursor getMouseCursor()
  42802. {
  42803. return owner.getMouseCursor();
  42804. }
  42805. void valueChanged (Value&)
  42806. {
  42807. owner.textWasChangedByValue();
  42808. }
  42809. private:
  42810. TextEditor& owner;
  42811. TextHolderComponent (const TextHolderComponent&);
  42812. TextHolderComponent& operator= (const TextHolderComponent&);
  42813. };
  42814. class TextEditorViewport : public Viewport
  42815. {
  42816. public:
  42817. TextEditorViewport (TextEditor* const owner_)
  42818. : owner (owner_), lastWordWrapWidth (0), rentrant (false)
  42819. {
  42820. }
  42821. ~TextEditorViewport()
  42822. {
  42823. }
  42824. void visibleAreaChanged (int, int, int, int)
  42825. {
  42826. if (! rentrant) // it's rare, but possible to get into a feedback loop as the viewport's scrollbars
  42827. // appear and disappear, causing the wrap width to change.
  42828. {
  42829. const float wordWrapWidth = owner->getWordWrapWidth();
  42830. if (wordWrapWidth != lastWordWrapWidth)
  42831. {
  42832. lastWordWrapWidth = wordWrapWidth;
  42833. rentrant = true;
  42834. owner->updateTextHolderSize();
  42835. rentrant = false;
  42836. }
  42837. }
  42838. }
  42839. private:
  42840. TextEditor* const owner;
  42841. float lastWordWrapWidth;
  42842. bool rentrant;
  42843. TextEditorViewport (const TextEditorViewport&);
  42844. TextEditorViewport& operator= (const TextEditorViewport&);
  42845. };
  42846. namespace TextEditorDefs
  42847. {
  42848. const int flashSpeedIntervalMs = 380;
  42849. const int textChangeMessageId = 0x10003001;
  42850. const int returnKeyMessageId = 0x10003002;
  42851. const int escapeKeyMessageId = 0x10003003;
  42852. const int focusLossMessageId = 0x10003004;
  42853. const int maxActionsPerTransaction = 100;
  42854. static int getCharacterCategory (const juce_wchar character)
  42855. {
  42856. return CharacterFunctions::isLetterOrDigit (character)
  42857. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  42858. }
  42859. }
  42860. TextEditor::TextEditor (const String& name,
  42861. const juce_wchar passwordCharacter_)
  42862. : Component (name),
  42863. borderSize (1, 1, 1, 3),
  42864. readOnly (false),
  42865. multiline (false),
  42866. wordWrap (false),
  42867. returnKeyStartsNewLine (false),
  42868. caretVisible (true),
  42869. popupMenuEnabled (true),
  42870. selectAllTextWhenFocused (false),
  42871. scrollbarVisible (true),
  42872. wasFocused (false),
  42873. caretFlashState (true),
  42874. keepCursorOnScreen (true),
  42875. tabKeyUsed (false),
  42876. menuActive (false),
  42877. valueTextNeedsUpdating (false),
  42878. cursorX (0),
  42879. cursorY (0),
  42880. cursorHeight (0),
  42881. maxTextLength (0),
  42882. leftIndent (4),
  42883. topIndent (4),
  42884. lastTransactionTime (0),
  42885. currentFont (14.0f),
  42886. totalNumChars (0),
  42887. caretPosition (0),
  42888. passwordCharacter (passwordCharacter_),
  42889. dragType (notDragging)
  42890. {
  42891. setOpaque (true);
  42892. addAndMakeVisible (viewport = new TextEditorViewport (this));
  42893. viewport->setViewedComponent (textHolder = new TextHolderComponent (*this));
  42894. viewport->setWantsKeyboardFocus (false);
  42895. viewport->setScrollBarsShown (false, false);
  42896. setMouseCursor (MouseCursor::IBeamCursor);
  42897. setWantsKeyboardFocus (true);
  42898. }
  42899. TextEditor::~TextEditor()
  42900. {
  42901. textValue.referTo (Value());
  42902. clearInternal (0);
  42903. viewport = 0;
  42904. textHolder = 0;
  42905. }
  42906. void TextEditor::newTransaction()
  42907. {
  42908. lastTransactionTime = Time::getApproximateMillisecondCounter();
  42909. undoManager.beginNewTransaction();
  42910. }
  42911. void TextEditor::doUndoRedo (const bool isRedo)
  42912. {
  42913. if (! isReadOnly())
  42914. {
  42915. if (isRedo ? undoManager.redo()
  42916. : undoManager.undo())
  42917. {
  42918. scrollToMakeSureCursorIsVisible();
  42919. repaint();
  42920. textChanged();
  42921. }
  42922. }
  42923. }
  42924. void TextEditor::setMultiLine (const bool shouldBeMultiLine,
  42925. const bool shouldWordWrap)
  42926. {
  42927. if (multiline != shouldBeMultiLine
  42928. || wordWrap != (shouldWordWrap && shouldBeMultiLine))
  42929. {
  42930. multiline = shouldBeMultiLine;
  42931. wordWrap = shouldWordWrap && shouldBeMultiLine;
  42932. viewport->setScrollBarsShown (scrollbarVisible && multiline,
  42933. scrollbarVisible && multiline);
  42934. viewport->setViewPosition (0, 0);
  42935. resized();
  42936. scrollToMakeSureCursorIsVisible();
  42937. }
  42938. }
  42939. bool TextEditor::isMultiLine() const
  42940. {
  42941. return multiline;
  42942. }
  42943. void TextEditor::setScrollbarsShown (bool shown)
  42944. {
  42945. if (scrollbarVisible != shown)
  42946. {
  42947. scrollbarVisible = shown;
  42948. shown = shown && isMultiLine();
  42949. viewport->setScrollBarsShown (shown, shown);
  42950. }
  42951. }
  42952. void TextEditor::setReadOnly (const bool shouldBeReadOnly)
  42953. {
  42954. if (readOnly != shouldBeReadOnly)
  42955. {
  42956. readOnly = shouldBeReadOnly;
  42957. enablementChanged();
  42958. }
  42959. }
  42960. bool TextEditor::isReadOnly() const
  42961. {
  42962. return readOnly || ! isEnabled();
  42963. }
  42964. bool TextEditor::isTextInputActive() const
  42965. {
  42966. return ! isReadOnly();
  42967. }
  42968. void TextEditor::setReturnKeyStartsNewLine (const bool shouldStartNewLine)
  42969. {
  42970. returnKeyStartsNewLine = shouldStartNewLine;
  42971. }
  42972. void TextEditor::setTabKeyUsedAsCharacter (const bool shouldTabKeyBeUsed)
  42973. {
  42974. tabKeyUsed = shouldTabKeyBeUsed;
  42975. }
  42976. void TextEditor::setPopupMenuEnabled (const bool b)
  42977. {
  42978. popupMenuEnabled = b;
  42979. }
  42980. void TextEditor::setSelectAllWhenFocused (const bool b)
  42981. {
  42982. selectAllTextWhenFocused = b;
  42983. }
  42984. const Font TextEditor::getFont() const
  42985. {
  42986. return currentFont;
  42987. }
  42988. void TextEditor::setFont (const Font& newFont)
  42989. {
  42990. currentFont = newFont;
  42991. scrollToMakeSureCursorIsVisible();
  42992. }
  42993. void TextEditor::applyFontToAllText (const Font& newFont)
  42994. {
  42995. currentFont = newFont;
  42996. const Colour overallColour (findColour (textColourId));
  42997. for (int i = sections.size(); --i >= 0;)
  42998. {
  42999. UniformTextSection* const uts = sections.getUnchecked (i);
  43000. uts->setFont (newFont, passwordCharacter);
  43001. uts->colour = overallColour;
  43002. }
  43003. coalesceSimilarSections();
  43004. updateTextHolderSize();
  43005. scrollToMakeSureCursorIsVisible();
  43006. repaint();
  43007. }
  43008. void TextEditor::colourChanged()
  43009. {
  43010. setOpaque (findColour (backgroundColourId).isOpaque());
  43011. repaint();
  43012. }
  43013. void TextEditor::setCaretVisible (const bool shouldCaretBeVisible)
  43014. {
  43015. caretVisible = shouldCaretBeVisible;
  43016. if (shouldCaretBeVisible)
  43017. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43018. setMouseCursor (shouldCaretBeVisible ? MouseCursor::IBeamCursor
  43019. : MouseCursor::NormalCursor);
  43020. }
  43021. void TextEditor::setInputRestrictions (const int maxLen,
  43022. const String& chars)
  43023. {
  43024. maxTextLength = jmax (0, maxLen);
  43025. allowedCharacters = chars;
  43026. }
  43027. void TextEditor::setTextToShowWhenEmpty (const String& text, const Colour& colourToUse)
  43028. {
  43029. textToShowWhenEmpty = text;
  43030. colourForTextWhenEmpty = colourToUse;
  43031. }
  43032. void TextEditor::setPasswordCharacter (const juce_wchar newPasswordCharacter)
  43033. {
  43034. if (passwordCharacter != newPasswordCharacter)
  43035. {
  43036. passwordCharacter = newPasswordCharacter;
  43037. resized();
  43038. repaint();
  43039. }
  43040. }
  43041. void TextEditor::setScrollBarThickness (const int newThicknessPixels)
  43042. {
  43043. viewport->setScrollBarThickness (newThicknessPixels);
  43044. }
  43045. void TextEditor::setScrollBarButtonVisibility (const bool buttonsVisible)
  43046. {
  43047. viewport->setScrollBarButtonVisibility (buttonsVisible);
  43048. }
  43049. void TextEditor::clear()
  43050. {
  43051. clearInternal (0);
  43052. updateTextHolderSize();
  43053. undoManager.clearUndoHistory();
  43054. }
  43055. void TextEditor::setText (const String& newText,
  43056. const bool sendTextChangeMessage)
  43057. {
  43058. const int newLength = newText.length();
  43059. if (newLength != getTotalNumChars() || getText() != newText)
  43060. {
  43061. const int oldCursorPos = caretPosition;
  43062. const bool cursorWasAtEnd = oldCursorPos >= getTotalNumChars();
  43063. clearInternal (0);
  43064. insert (newText, 0, currentFont, findColour (textColourId), 0, caretPosition);
  43065. // if you're adding text with line-feeds to a single-line text editor, it
  43066. // ain't gonna look right!
  43067. jassert (multiline || ! newText.containsAnyOf ("\r\n"));
  43068. if (cursorWasAtEnd && ! isMultiLine())
  43069. moveCursorTo (getTotalNumChars(), false);
  43070. else
  43071. moveCursorTo (oldCursorPos, false);
  43072. if (sendTextChangeMessage)
  43073. textChanged();
  43074. updateTextHolderSize();
  43075. scrollToMakeSureCursorIsVisible();
  43076. undoManager.clearUndoHistory();
  43077. repaint();
  43078. }
  43079. }
  43080. Value& TextEditor::getTextValue()
  43081. {
  43082. if (valueTextNeedsUpdating)
  43083. {
  43084. valueTextNeedsUpdating = false;
  43085. textValue = getText();
  43086. }
  43087. return textValue;
  43088. }
  43089. void TextEditor::textWasChangedByValue()
  43090. {
  43091. if (textValue.getValueSource().getReferenceCount() > 1)
  43092. setText (textValue.getValue());
  43093. }
  43094. void TextEditor::textChanged()
  43095. {
  43096. updateTextHolderSize();
  43097. postCommandMessage (TextEditorDefs::textChangeMessageId);
  43098. if (textValue.getValueSource().getReferenceCount() > 1)
  43099. {
  43100. valueTextNeedsUpdating = false;
  43101. textValue = getText();
  43102. }
  43103. }
  43104. void TextEditor::returnPressed()
  43105. {
  43106. postCommandMessage (TextEditorDefs::returnKeyMessageId);
  43107. }
  43108. void TextEditor::escapePressed()
  43109. {
  43110. postCommandMessage (TextEditorDefs::escapeKeyMessageId);
  43111. }
  43112. void TextEditor::addListener (Listener* const newListener)
  43113. {
  43114. listeners.add (newListener);
  43115. }
  43116. void TextEditor::removeListener (Listener* const listenerToRemove)
  43117. {
  43118. listeners.remove (listenerToRemove);
  43119. }
  43120. void TextEditor::timerCallbackInt()
  43121. {
  43122. const bool newState = (! caretFlashState) && ! isCurrentlyBlockedByAnotherModalComponent();
  43123. if (caretFlashState != newState)
  43124. {
  43125. caretFlashState = newState;
  43126. if (caretFlashState)
  43127. wasFocused = true;
  43128. if (caretVisible
  43129. && hasKeyboardFocus (false)
  43130. && ! isReadOnly())
  43131. {
  43132. repaintCaret();
  43133. }
  43134. }
  43135. const unsigned int now = Time::getApproximateMillisecondCounter();
  43136. if (now > lastTransactionTime + 200)
  43137. newTransaction();
  43138. }
  43139. void TextEditor::repaintCaret()
  43140. {
  43141. if (! findColour (caretColourId).isTransparent())
  43142. repaint (borderSize.getLeft() + textHolder->getX() + leftIndent + roundToInt (cursorX) - 1,
  43143. borderSize.getTop() + textHolder->getY() + topIndent + roundToInt (cursorY) - 1,
  43144. 4,
  43145. roundToInt (cursorHeight) + 2);
  43146. }
  43147. void TextEditor::repaintText (const Range<int>& range)
  43148. {
  43149. if (! range.isEmpty())
  43150. {
  43151. float x = 0, y = 0, lh = currentFont.getHeight();
  43152. const float wordWrapWidth = getWordWrapWidth();
  43153. if (wordWrapWidth > 0)
  43154. {
  43155. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43156. i.getCharPosition (range.getStart(), x, y, lh);
  43157. const int y1 = (int) y;
  43158. int y2;
  43159. if (range.getEnd() >= getTotalNumChars())
  43160. {
  43161. y2 = textHolder->getHeight();
  43162. }
  43163. else
  43164. {
  43165. i.getCharPosition (range.getEnd(), x, y, lh);
  43166. y2 = (int) (y + lh * 2.0f);
  43167. }
  43168. textHolder->repaint (0, y1, textHolder->getWidth(), y2 - y1);
  43169. }
  43170. }
  43171. }
  43172. void TextEditor::moveCaret (int newCaretPos)
  43173. {
  43174. if (newCaretPos < 0)
  43175. newCaretPos = 0;
  43176. else if (newCaretPos > getTotalNumChars())
  43177. newCaretPos = getTotalNumChars();
  43178. if (newCaretPos != getCaretPosition())
  43179. {
  43180. repaintCaret();
  43181. caretFlashState = true;
  43182. caretPosition = newCaretPos;
  43183. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43184. scrollToMakeSureCursorIsVisible();
  43185. repaintCaret();
  43186. }
  43187. }
  43188. void TextEditor::setCaretPosition (const int newIndex)
  43189. {
  43190. moveCursorTo (newIndex, false);
  43191. }
  43192. int TextEditor::getCaretPosition() const
  43193. {
  43194. return caretPosition;
  43195. }
  43196. void TextEditor::scrollEditorToPositionCaret (const int desiredCaretX,
  43197. const int desiredCaretY)
  43198. {
  43199. updateCaretPosition();
  43200. int vx = roundToInt (cursorX) - desiredCaretX;
  43201. int vy = roundToInt (cursorY) - desiredCaretY;
  43202. if (desiredCaretX < jmax (1, proportionOfWidth (0.05f)))
  43203. {
  43204. vx += desiredCaretX - proportionOfWidth (0.2f);
  43205. }
  43206. else if (desiredCaretX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  43207. {
  43208. vx += desiredCaretX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  43209. }
  43210. vx = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), vx);
  43211. if (! isMultiLine())
  43212. {
  43213. vy = viewport->getViewPositionY();
  43214. }
  43215. else
  43216. {
  43217. vy = jlimit (0, jmax (0, textHolder->getHeight() - viewport->getMaximumVisibleHeight()), vy);
  43218. const int curH = roundToInt (cursorHeight);
  43219. if (desiredCaretY < 0)
  43220. {
  43221. vy = jmax (0, desiredCaretY + vy);
  43222. }
  43223. else if (desiredCaretY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  43224. {
  43225. vy += desiredCaretY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  43226. }
  43227. }
  43228. viewport->setViewPosition (vx, vy);
  43229. }
  43230. const Rectangle<int> TextEditor::getCaretRectangle()
  43231. {
  43232. updateCaretPosition();
  43233. return Rectangle<int> (roundToInt (cursorX) - viewport->getX(),
  43234. roundToInt (cursorY) - viewport->getY(),
  43235. 1, roundToInt (cursorHeight));
  43236. }
  43237. float TextEditor::getWordWrapWidth() const
  43238. {
  43239. return (wordWrap) ? (float) (viewport->getMaximumVisibleWidth() - leftIndent - leftIndent / 2)
  43240. : 1.0e10f;
  43241. }
  43242. void TextEditor::updateTextHolderSize()
  43243. {
  43244. const float wordWrapWidth = getWordWrapWidth();
  43245. if (wordWrapWidth > 0)
  43246. {
  43247. float maxWidth = 0.0f;
  43248. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43249. while (i.next())
  43250. maxWidth = jmax (maxWidth, i.atomRight);
  43251. const int w = leftIndent + roundToInt (maxWidth);
  43252. const int h = topIndent + roundToInt (jmax (i.lineY + i.lineHeight,
  43253. currentFont.getHeight()));
  43254. textHolder->setSize (w + 1, h + 1);
  43255. }
  43256. }
  43257. int TextEditor::getTextWidth() const
  43258. {
  43259. return textHolder->getWidth();
  43260. }
  43261. int TextEditor::getTextHeight() const
  43262. {
  43263. return textHolder->getHeight();
  43264. }
  43265. void TextEditor::setIndents (const int newLeftIndent,
  43266. const int newTopIndent)
  43267. {
  43268. leftIndent = newLeftIndent;
  43269. topIndent = newTopIndent;
  43270. }
  43271. void TextEditor::setBorder (const BorderSize& border)
  43272. {
  43273. borderSize = border;
  43274. resized();
  43275. }
  43276. const BorderSize TextEditor::getBorder() const
  43277. {
  43278. return borderSize;
  43279. }
  43280. void TextEditor::setScrollToShowCursor (const bool shouldScrollToShowCursor)
  43281. {
  43282. keepCursorOnScreen = shouldScrollToShowCursor;
  43283. }
  43284. void TextEditor::updateCaretPosition()
  43285. {
  43286. cursorHeight = currentFont.getHeight(); // (in case the text is empty and the call below doesn't set this value)
  43287. getCharPosition (caretPosition, cursorX, cursorY, cursorHeight);
  43288. }
  43289. void TextEditor::scrollToMakeSureCursorIsVisible()
  43290. {
  43291. updateCaretPosition();
  43292. if (keepCursorOnScreen)
  43293. {
  43294. int x = viewport->getViewPositionX();
  43295. int y = viewport->getViewPositionY();
  43296. const int relativeCursorX = roundToInt (cursorX) - x;
  43297. const int relativeCursorY = roundToInt (cursorY) - y;
  43298. if (relativeCursorX < jmax (1, proportionOfWidth (0.05f)))
  43299. {
  43300. x += relativeCursorX - proportionOfWidth (0.2f);
  43301. }
  43302. else if (relativeCursorX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  43303. {
  43304. x += relativeCursorX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  43305. }
  43306. x = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), x);
  43307. if (! isMultiLine())
  43308. {
  43309. y = (getHeight() - textHolder->getHeight() - topIndent) / -2;
  43310. }
  43311. else
  43312. {
  43313. const int curH = roundToInt (cursorHeight);
  43314. if (relativeCursorY < 0)
  43315. {
  43316. y = jmax (0, relativeCursorY + y);
  43317. }
  43318. else if (relativeCursorY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  43319. {
  43320. y += relativeCursorY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  43321. }
  43322. }
  43323. viewport->setViewPosition (x, y);
  43324. }
  43325. }
  43326. void TextEditor::moveCursorTo (const int newPosition,
  43327. const bool isSelecting)
  43328. {
  43329. if (isSelecting)
  43330. {
  43331. moveCaret (newPosition);
  43332. const Range<int> oldSelection (selection);
  43333. if (dragType == notDragging)
  43334. {
  43335. if (abs (getCaretPosition() - selection.getStart()) < abs (getCaretPosition() - selection.getEnd()))
  43336. dragType = draggingSelectionStart;
  43337. else
  43338. dragType = draggingSelectionEnd;
  43339. }
  43340. if (dragType == draggingSelectionStart)
  43341. {
  43342. if (getCaretPosition() >= selection.getEnd())
  43343. dragType = draggingSelectionEnd;
  43344. selection = Range<int>::between (getCaretPosition(), selection.getEnd());
  43345. }
  43346. else
  43347. {
  43348. if (getCaretPosition() < selection.getStart())
  43349. dragType = draggingSelectionStart;
  43350. selection = Range<int>::between (getCaretPosition(), selection.getStart());
  43351. }
  43352. repaintText (selection.getUnionWith (oldSelection));
  43353. }
  43354. else
  43355. {
  43356. dragType = notDragging;
  43357. repaintText (selection);
  43358. moveCaret (newPosition);
  43359. selection = Range<int>::emptyRange (getCaretPosition());
  43360. }
  43361. }
  43362. int TextEditor::getTextIndexAt (const int x,
  43363. const int y)
  43364. {
  43365. return indexAtPosition ((float) (x + viewport->getViewPositionX() - leftIndent),
  43366. (float) (y + viewport->getViewPositionY() - topIndent));
  43367. }
  43368. void TextEditor::insertTextAtCaret (const String& newText_)
  43369. {
  43370. String newText (newText_);
  43371. if (allowedCharacters.isNotEmpty())
  43372. newText = newText.retainCharacters (allowedCharacters);
  43373. if ((! returnKeyStartsNewLine) && newText == "\n")
  43374. {
  43375. returnPressed();
  43376. return;
  43377. }
  43378. if (! isMultiLine())
  43379. newText = newText.replaceCharacters ("\r\n", " ");
  43380. else
  43381. newText = newText.replace ("\r\n", "\n");
  43382. const int newCaretPos = selection.getStart() + newText.length();
  43383. const int insertIndex = selection.getStart();
  43384. remove (selection, getUndoManager(),
  43385. newText.isNotEmpty() ? newCaretPos - 1 : newCaretPos);
  43386. if (maxTextLength > 0)
  43387. newText = newText.substring (0, maxTextLength - getTotalNumChars());
  43388. if (newText.isNotEmpty())
  43389. insert (newText,
  43390. insertIndex,
  43391. currentFont,
  43392. findColour (textColourId),
  43393. getUndoManager(),
  43394. newCaretPos);
  43395. textChanged();
  43396. }
  43397. void TextEditor::setHighlightedRegion (const Range<int>& newSelection)
  43398. {
  43399. moveCursorTo (newSelection.getStart(), false);
  43400. moveCursorTo (newSelection.getEnd(), true);
  43401. }
  43402. void TextEditor::copy()
  43403. {
  43404. if (passwordCharacter == 0)
  43405. {
  43406. const String selectedText (getHighlightedText());
  43407. if (selectedText.isNotEmpty())
  43408. SystemClipboard::copyTextToClipboard (selectedText);
  43409. }
  43410. }
  43411. void TextEditor::paste()
  43412. {
  43413. if (! isReadOnly())
  43414. {
  43415. const String clip (SystemClipboard::getTextFromClipboard());
  43416. if (clip.isNotEmpty())
  43417. insertTextAtCaret (clip);
  43418. }
  43419. }
  43420. void TextEditor::cut()
  43421. {
  43422. if (! isReadOnly())
  43423. {
  43424. moveCaret (selection.getEnd());
  43425. insertTextAtCaret (String::empty);
  43426. }
  43427. }
  43428. void TextEditor::drawContent (Graphics& g)
  43429. {
  43430. const float wordWrapWidth = getWordWrapWidth();
  43431. if (wordWrapWidth > 0)
  43432. {
  43433. g.setOrigin (leftIndent, topIndent);
  43434. const Rectangle<int> clip (g.getClipBounds());
  43435. Colour selectedTextColour;
  43436. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43437. while (i.lineY + 200.0 < clip.getY() && i.next())
  43438. {}
  43439. if (! selection.isEmpty())
  43440. {
  43441. g.setColour (findColour (highlightColourId)
  43442. .withMultipliedAlpha (hasKeyboardFocus (true) ? 1.0f : 0.5f));
  43443. selectedTextColour = findColour (highlightedTextColourId);
  43444. Iterator i2 (i);
  43445. while (i2.next() && i2.lineY < clip.getBottom())
  43446. {
  43447. if (i2.lineY + i2.lineHeight >= clip.getY()
  43448. && selection.intersects (Range<int> (i2.indexInText, i2.indexInText + i2.atom->numChars)))
  43449. {
  43450. i2.drawSelection (g, selection);
  43451. }
  43452. }
  43453. }
  43454. const UniformTextSection* lastSection = 0;
  43455. while (i.next() && i.lineY < clip.getBottom())
  43456. {
  43457. if (i.lineY + i.lineHeight >= clip.getY())
  43458. {
  43459. if (selection.intersects (Range<int> (i.indexInText, i.indexInText + i.atom->numChars)))
  43460. {
  43461. i.drawSelectedText (g, selection, selectedTextColour);
  43462. lastSection = 0;
  43463. }
  43464. else
  43465. {
  43466. i.draw (g, lastSection);
  43467. }
  43468. }
  43469. }
  43470. }
  43471. }
  43472. void TextEditor::paint (Graphics& g)
  43473. {
  43474. getLookAndFeel().fillTextEditorBackground (g, getWidth(), getHeight(), *this);
  43475. }
  43476. void TextEditor::paintOverChildren (Graphics& g)
  43477. {
  43478. if (caretFlashState
  43479. && hasKeyboardFocus (false)
  43480. && caretVisible
  43481. && ! isReadOnly())
  43482. {
  43483. g.setColour (findColour (caretColourId));
  43484. g.fillRect (borderSize.getLeft() + textHolder->getX() + leftIndent + cursorX,
  43485. borderSize.getTop() + textHolder->getY() + topIndent + cursorY,
  43486. 2.0f, cursorHeight);
  43487. }
  43488. if (textToShowWhenEmpty.isNotEmpty()
  43489. && (! hasKeyboardFocus (false))
  43490. && getTotalNumChars() == 0)
  43491. {
  43492. g.setColour (colourForTextWhenEmpty);
  43493. g.setFont (getFont());
  43494. if (isMultiLine())
  43495. {
  43496. g.drawText (textToShowWhenEmpty,
  43497. 0, 0, getWidth(), getHeight(),
  43498. Justification::centred, true);
  43499. }
  43500. else
  43501. {
  43502. g.drawText (textToShowWhenEmpty,
  43503. leftIndent, topIndent,
  43504. viewport->getWidth() - leftIndent,
  43505. viewport->getHeight() - topIndent,
  43506. Justification::centredLeft, true);
  43507. }
  43508. }
  43509. getLookAndFeel().drawTextEditorOutline (g, getWidth(), getHeight(), *this);
  43510. }
  43511. class TextEditorMenuPerformer : public ModalComponentManager::Callback
  43512. {
  43513. public:
  43514. TextEditorMenuPerformer (TextEditor* const editor_)
  43515. : editor (editor_)
  43516. {
  43517. }
  43518. void modalStateFinished (int returnValue)
  43519. {
  43520. if (editor != 0 && returnValue != 0)
  43521. editor->performPopupMenuAction (returnValue);
  43522. }
  43523. private:
  43524. Component::SafePointer<TextEditor> editor;
  43525. TextEditorMenuPerformer (const TextEditorMenuPerformer&);
  43526. TextEditorMenuPerformer& operator= (const TextEditorMenuPerformer&);
  43527. };
  43528. void TextEditor::mouseDown (const MouseEvent& e)
  43529. {
  43530. beginDragAutoRepeat (100);
  43531. newTransaction();
  43532. if (wasFocused || ! selectAllTextWhenFocused)
  43533. {
  43534. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  43535. {
  43536. moveCursorTo (getTextIndexAt (e.x, e.y),
  43537. e.mods.isShiftDown());
  43538. }
  43539. else
  43540. {
  43541. PopupMenu m;
  43542. m.setLookAndFeel (&getLookAndFeel());
  43543. addPopupMenuItems (m, &e);
  43544. m.show (0, 0, 0, 0, new TextEditorMenuPerformer (this));
  43545. }
  43546. }
  43547. }
  43548. void TextEditor::mouseDrag (const MouseEvent& e)
  43549. {
  43550. if (wasFocused || ! selectAllTextWhenFocused)
  43551. {
  43552. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  43553. {
  43554. moveCursorTo (getTextIndexAt (e.x, e.y), true);
  43555. }
  43556. }
  43557. }
  43558. void TextEditor::mouseUp (const MouseEvent& e)
  43559. {
  43560. newTransaction();
  43561. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43562. if (wasFocused || ! selectAllTextWhenFocused)
  43563. {
  43564. if (e.mouseWasClicked() && ! (popupMenuEnabled && e.mods.isPopupMenu()))
  43565. {
  43566. moveCaret (getTextIndexAt (e.x, e.y));
  43567. }
  43568. }
  43569. wasFocused = true;
  43570. }
  43571. void TextEditor::mouseDoubleClick (const MouseEvent& e)
  43572. {
  43573. int tokenEnd = getTextIndexAt (e.x, e.y);
  43574. int tokenStart = tokenEnd;
  43575. if (e.getNumberOfClicks() > 3)
  43576. {
  43577. tokenStart = 0;
  43578. tokenEnd = getTotalNumChars();
  43579. }
  43580. else
  43581. {
  43582. const String t (getText());
  43583. const int totalLength = getTotalNumChars();
  43584. while (tokenEnd < totalLength)
  43585. {
  43586. // (note the slight bodge here - it's because iswalnum only checks for alphabetic chars in the current locale)
  43587. if (CharacterFunctions::isLetterOrDigit (t [tokenEnd]) || t [tokenEnd] > 128)
  43588. ++tokenEnd;
  43589. else
  43590. break;
  43591. }
  43592. tokenStart = tokenEnd;
  43593. while (tokenStart > 0)
  43594. {
  43595. // (note the slight bodge here - it's because iswalnum only checks for alphabetic chars in the current locale)
  43596. if (CharacterFunctions::isLetterOrDigit (t [tokenStart - 1]) || t [tokenStart - 1] > 128)
  43597. --tokenStart;
  43598. else
  43599. break;
  43600. }
  43601. if (e.getNumberOfClicks() > 2)
  43602. {
  43603. while (tokenEnd < totalLength)
  43604. {
  43605. if (t [tokenEnd] != '\r' && t [tokenEnd] != '\n')
  43606. ++tokenEnd;
  43607. else
  43608. break;
  43609. }
  43610. while (tokenStart > 0)
  43611. {
  43612. if (t [tokenStart - 1] != '\r' && t [tokenStart - 1] != '\n')
  43613. --tokenStart;
  43614. else
  43615. break;
  43616. }
  43617. }
  43618. }
  43619. moveCursorTo (tokenEnd, false);
  43620. moveCursorTo (tokenStart, true);
  43621. }
  43622. void TextEditor::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  43623. {
  43624. if (! viewport->useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  43625. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  43626. }
  43627. bool TextEditor::keyPressed (const KeyPress& key)
  43628. {
  43629. if (isReadOnly() && key != KeyPress ('c', ModifierKeys::commandModifier, 0))
  43630. return false;
  43631. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  43632. if (key.isKeyCode (KeyPress::leftKey)
  43633. || key.isKeyCode (KeyPress::upKey))
  43634. {
  43635. newTransaction();
  43636. int newPos;
  43637. if (isMultiLine() && key.isKeyCode (KeyPress::upKey))
  43638. newPos = indexAtPosition (cursorX, cursorY - 1);
  43639. else if (moveInWholeWordSteps)
  43640. newPos = findWordBreakBefore (getCaretPosition());
  43641. else
  43642. newPos = getCaretPosition() - 1;
  43643. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  43644. }
  43645. else if (key.isKeyCode (KeyPress::rightKey)
  43646. || key.isKeyCode (KeyPress::downKey))
  43647. {
  43648. newTransaction();
  43649. int newPos;
  43650. if (isMultiLine() && key.isKeyCode (KeyPress::downKey))
  43651. newPos = indexAtPosition (cursorX, cursorY + cursorHeight + 1);
  43652. else if (moveInWholeWordSteps)
  43653. newPos = findWordBreakAfter (getCaretPosition());
  43654. else
  43655. newPos = getCaretPosition() + 1;
  43656. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  43657. }
  43658. else if (key.isKeyCode (KeyPress::pageDownKey) && isMultiLine())
  43659. {
  43660. newTransaction();
  43661. moveCursorTo (indexAtPosition (cursorX, cursorY + cursorHeight + viewport->getViewHeight()),
  43662. key.getModifiers().isShiftDown());
  43663. }
  43664. else if (key.isKeyCode (KeyPress::pageUpKey) && isMultiLine())
  43665. {
  43666. newTransaction();
  43667. moveCursorTo (indexAtPosition (cursorX, cursorY - viewport->getViewHeight()),
  43668. key.getModifiers().isShiftDown());
  43669. }
  43670. else if (key.isKeyCode (KeyPress::homeKey))
  43671. {
  43672. newTransaction();
  43673. if (isMultiLine() && ! moveInWholeWordSteps)
  43674. moveCursorTo (indexAtPosition (0.0f, cursorY),
  43675. key.getModifiers().isShiftDown());
  43676. else
  43677. moveCursorTo (0, key.getModifiers().isShiftDown());
  43678. }
  43679. else if (key.isKeyCode (KeyPress::endKey))
  43680. {
  43681. newTransaction();
  43682. if (isMultiLine() && ! moveInWholeWordSteps)
  43683. moveCursorTo (indexAtPosition ((float) textHolder->getWidth(), cursorY),
  43684. key.getModifiers().isShiftDown());
  43685. else
  43686. moveCursorTo (getTotalNumChars(), key.getModifiers().isShiftDown());
  43687. }
  43688. else if (key.isKeyCode (KeyPress::backspaceKey))
  43689. {
  43690. if (moveInWholeWordSteps)
  43691. {
  43692. moveCursorTo (findWordBreakBefore (getCaretPosition()), true);
  43693. }
  43694. else
  43695. {
  43696. if (selection.isEmpty() && selection.getStart() > 0)
  43697. selection.setStart (selection.getEnd() - 1);
  43698. }
  43699. cut();
  43700. }
  43701. else if (key.isKeyCode (KeyPress::deleteKey))
  43702. {
  43703. if (key.getModifiers().isShiftDown())
  43704. copy();
  43705. if (selection.isEmpty() && selection.getStart() < getTotalNumChars())
  43706. selection.setEnd (selection.getStart() + 1);
  43707. cut();
  43708. }
  43709. else if (key == KeyPress ('c', ModifierKeys::commandModifier, 0)
  43710. || key == KeyPress (KeyPress::insertKey, ModifierKeys::ctrlModifier, 0))
  43711. {
  43712. newTransaction();
  43713. copy();
  43714. }
  43715. else if (key == KeyPress ('x', ModifierKeys::commandModifier, 0))
  43716. {
  43717. newTransaction();
  43718. copy();
  43719. cut();
  43720. }
  43721. else if (key == KeyPress ('v', ModifierKeys::commandModifier, 0)
  43722. || key == KeyPress (KeyPress::insertKey, ModifierKeys::shiftModifier, 0))
  43723. {
  43724. newTransaction();
  43725. paste();
  43726. }
  43727. else if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  43728. {
  43729. newTransaction();
  43730. doUndoRedo (false);
  43731. }
  43732. else if (key == KeyPress ('y', ModifierKeys::commandModifier, 0))
  43733. {
  43734. newTransaction();
  43735. doUndoRedo (true);
  43736. }
  43737. else if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  43738. {
  43739. newTransaction();
  43740. moveCursorTo (getTotalNumChars(), false);
  43741. moveCursorTo (0, true);
  43742. }
  43743. else if (key == KeyPress::returnKey)
  43744. {
  43745. newTransaction();
  43746. insertTextAtCaret ("\n");
  43747. }
  43748. else if (key.isKeyCode (KeyPress::escapeKey))
  43749. {
  43750. newTransaction();
  43751. moveCursorTo (getCaretPosition(), false);
  43752. escapePressed();
  43753. }
  43754. else if (key.getTextCharacter() >= ' '
  43755. || (tabKeyUsed && (key.getTextCharacter() == '\t')))
  43756. {
  43757. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  43758. lastTransactionTime = Time::getApproximateMillisecondCounter();
  43759. }
  43760. else
  43761. {
  43762. return false;
  43763. }
  43764. return true;
  43765. }
  43766. bool TextEditor::keyStateChanged (const bool isKeyDown)
  43767. {
  43768. if (! isKeyDown)
  43769. return false;
  43770. #if JUCE_WINDOWS
  43771. if (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0).isCurrentlyDown())
  43772. return false; // We need to explicitly allow alt-F4 to pass through on Windows
  43773. #endif
  43774. // (overridden to avoid forwarding key events to the parent)
  43775. return ! ModifierKeys::getCurrentModifiers().isCommandDown();
  43776. }
  43777. const int baseMenuItemID = 0x7fff0000;
  43778. void TextEditor::addPopupMenuItems (PopupMenu& m, const MouseEvent*)
  43779. {
  43780. const bool writable = ! isReadOnly();
  43781. if (passwordCharacter == 0)
  43782. {
  43783. m.addItem (baseMenuItemID + 1, TRANS("cut"), writable);
  43784. m.addItem (baseMenuItemID + 2, TRANS("copy"), ! selection.isEmpty());
  43785. m.addItem (baseMenuItemID + 3, TRANS("paste"), writable);
  43786. }
  43787. m.addItem (baseMenuItemID + 4, TRANS("delete"), writable);
  43788. m.addSeparator();
  43789. m.addItem (baseMenuItemID + 5, TRANS("select all"));
  43790. m.addSeparator();
  43791. if (getUndoManager() != 0)
  43792. {
  43793. m.addItem (baseMenuItemID + 6, TRANS("undo"), undoManager.canUndo());
  43794. m.addItem (baseMenuItemID + 7, TRANS("redo"), undoManager.canRedo());
  43795. }
  43796. }
  43797. void TextEditor::performPopupMenuAction (const int menuItemID)
  43798. {
  43799. switch (menuItemID)
  43800. {
  43801. case baseMenuItemID + 1:
  43802. copy();
  43803. cut();
  43804. break;
  43805. case baseMenuItemID + 2:
  43806. copy();
  43807. break;
  43808. case baseMenuItemID + 3:
  43809. paste();
  43810. break;
  43811. case baseMenuItemID + 4:
  43812. cut();
  43813. break;
  43814. case baseMenuItemID + 5:
  43815. moveCursorTo (getTotalNumChars(), false);
  43816. moveCursorTo (0, true);
  43817. break;
  43818. case baseMenuItemID + 6:
  43819. doUndoRedo (false);
  43820. break;
  43821. case baseMenuItemID + 7:
  43822. doUndoRedo (true);
  43823. break;
  43824. default:
  43825. break;
  43826. }
  43827. }
  43828. void TextEditor::focusGained (FocusChangeType)
  43829. {
  43830. newTransaction();
  43831. caretFlashState = true;
  43832. if (selectAllTextWhenFocused)
  43833. {
  43834. moveCursorTo (0, false);
  43835. moveCursorTo (getTotalNumChars(), true);
  43836. }
  43837. repaint();
  43838. if (caretVisible)
  43839. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43840. ComponentPeer* const peer = getPeer();
  43841. if (peer != 0 && ! isReadOnly())
  43842. peer->textInputRequired (getScreenPosition() - peer->getScreenPosition());
  43843. }
  43844. void TextEditor::focusLost (FocusChangeType)
  43845. {
  43846. newTransaction();
  43847. wasFocused = false;
  43848. textHolder->stopTimer();
  43849. caretFlashState = false;
  43850. postCommandMessage (TextEditorDefs::focusLossMessageId);
  43851. repaint();
  43852. }
  43853. void TextEditor::resized()
  43854. {
  43855. viewport->setBoundsInset (borderSize);
  43856. viewport->setSingleStepSizes (16, roundToInt (currentFont.getHeight()));
  43857. updateTextHolderSize();
  43858. if (! isMultiLine())
  43859. {
  43860. scrollToMakeSureCursorIsVisible();
  43861. }
  43862. else
  43863. {
  43864. updateCaretPosition();
  43865. }
  43866. }
  43867. void TextEditor::handleCommandMessage (const int commandId)
  43868. {
  43869. Component::BailOutChecker checker (this);
  43870. switch (commandId)
  43871. {
  43872. case TextEditorDefs::textChangeMessageId:
  43873. listeners.callChecked (checker, &TextEditor::Listener::textEditorTextChanged, (TextEditor&) *this);
  43874. break;
  43875. case TextEditorDefs::returnKeyMessageId:
  43876. listeners.callChecked (checker, &TextEditor::Listener::textEditorReturnKeyPressed, (TextEditor&) *this);
  43877. break;
  43878. case TextEditorDefs::escapeKeyMessageId:
  43879. listeners.callChecked (checker, &TextEditor::Listener::textEditorEscapeKeyPressed, (TextEditor&) *this);
  43880. break;
  43881. case TextEditorDefs::focusLossMessageId:
  43882. listeners.callChecked (checker, &TextEditor::Listener::textEditorFocusLost, (TextEditor&) *this);
  43883. break;
  43884. default:
  43885. jassertfalse;
  43886. break;
  43887. }
  43888. }
  43889. void TextEditor::enablementChanged()
  43890. {
  43891. setMouseCursor (isReadOnly() ? MouseCursor::NormalCursor
  43892. : MouseCursor::IBeamCursor);
  43893. repaint();
  43894. }
  43895. UndoManager* TextEditor::getUndoManager() throw()
  43896. {
  43897. return isReadOnly() ? 0 : &undoManager;
  43898. }
  43899. void TextEditor::clearInternal (UndoManager* const um)
  43900. {
  43901. remove (Range<int> (0, getTotalNumChars()), um, caretPosition);
  43902. }
  43903. void TextEditor::insert (const String& text,
  43904. const int insertIndex,
  43905. const Font& font,
  43906. const Colour& colour,
  43907. UndoManager* const um,
  43908. const int caretPositionToMoveTo)
  43909. {
  43910. if (text.isNotEmpty())
  43911. {
  43912. if (um != 0)
  43913. {
  43914. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  43915. newTransaction();
  43916. um->perform (new InsertAction (*this, text, insertIndex, font, colour,
  43917. caretPosition, caretPositionToMoveTo));
  43918. }
  43919. else
  43920. {
  43921. repaintText (Range<int> (insertIndex, getTotalNumChars())); // must do this before and after changing the data, in case
  43922. // a line gets moved due to word wrap
  43923. int index = 0;
  43924. int nextIndex = 0;
  43925. for (int i = 0; i < sections.size(); ++i)
  43926. {
  43927. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  43928. if (insertIndex == index)
  43929. {
  43930. sections.insert (i, new UniformTextSection (text,
  43931. font, colour,
  43932. passwordCharacter));
  43933. break;
  43934. }
  43935. else if (insertIndex > index && insertIndex < nextIndex)
  43936. {
  43937. splitSection (i, insertIndex - index);
  43938. sections.insert (i + 1, new UniformTextSection (text,
  43939. font, colour,
  43940. passwordCharacter));
  43941. break;
  43942. }
  43943. index = nextIndex;
  43944. }
  43945. if (nextIndex == insertIndex)
  43946. sections.add (new UniformTextSection (text,
  43947. font, colour,
  43948. passwordCharacter));
  43949. coalesceSimilarSections();
  43950. totalNumChars = -1;
  43951. valueTextNeedsUpdating = true;
  43952. moveCursorTo (caretPositionToMoveTo, false);
  43953. repaintText (Range<int> (insertIndex, getTotalNumChars()));
  43954. }
  43955. }
  43956. }
  43957. void TextEditor::reinsert (const int insertIndex,
  43958. const Array <UniformTextSection*>& sectionsToInsert)
  43959. {
  43960. int index = 0;
  43961. int nextIndex = 0;
  43962. for (int i = 0; i < sections.size(); ++i)
  43963. {
  43964. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  43965. if (insertIndex == index)
  43966. {
  43967. for (int j = sectionsToInsert.size(); --j >= 0;)
  43968. sections.insert (i, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  43969. break;
  43970. }
  43971. else if (insertIndex > index && insertIndex < nextIndex)
  43972. {
  43973. splitSection (i, insertIndex - index);
  43974. for (int j = sectionsToInsert.size(); --j >= 0;)
  43975. sections.insert (i + 1, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  43976. break;
  43977. }
  43978. index = nextIndex;
  43979. }
  43980. if (nextIndex == insertIndex)
  43981. {
  43982. for (int j = 0; j < sectionsToInsert.size(); ++j)
  43983. sections.add (new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  43984. }
  43985. coalesceSimilarSections();
  43986. totalNumChars = -1;
  43987. valueTextNeedsUpdating = true;
  43988. }
  43989. void TextEditor::remove (const Range<int>& range,
  43990. UndoManager* const um,
  43991. const int caretPositionToMoveTo)
  43992. {
  43993. if (! range.isEmpty())
  43994. {
  43995. int index = 0;
  43996. for (int i = 0; i < sections.size(); ++i)
  43997. {
  43998. const int nextIndex = index + sections.getUnchecked(i)->getTotalLength();
  43999. if (range.getStart() > index && range.getStart() < nextIndex)
  44000. {
  44001. splitSection (i, range.getStart() - index);
  44002. --i;
  44003. }
  44004. else if (range.getEnd() > index && range.getEnd() < nextIndex)
  44005. {
  44006. splitSection (i, range.getEnd() - index);
  44007. --i;
  44008. }
  44009. else
  44010. {
  44011. index = nextIndex;
  44012. if (index > range.getEnd())
  44013. break;
  44014. }
  44015. }
  44016. index = 0;
  44017. if (um != 0)
  44018. {
  44019. Array <UniformTextSection*> removedSections;
  44020. for (int i = 0; i < sections.size(); ++i)
  44021. {
  44022. if (range.getEnd() <= range.getStart())
  44023. break;
  44024. UniformTextSection* const section = sections.getUnchecked (i);
  44025. const int nextIndex = index + section->getTotalLength();
  44026. if (range.getStart() <= index && range.getEnd() >= nextIndex)
  44027. removedSections.add (new UniformTextSection (*section));
  44028. index = nextIndex;
  44029. }
  44030. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  44031. newTransaction();
  44032. um->perform (new RemoveAction (*this, range, caretPosition,
  44033. caretPositionToMoveTo, removedSections));
  44034. }
  44035. else
  44036. {
  44037. Range<int> remainingRange (range);
  44038. for (int i = 0; i < sections.size(); ++i)
  44039. {
  44040. UniformTextSection* const section = sections.getUnchecked (i);
  44041. const int nextIndex = index + section->getTotalLength();
  44042. if (remainingRange.getStart() <= index && remainingRange.getEnd() >= nextIndex)
  44043. {
  44044. sections.remove(i);
  44045. section->clear();
  44046. delete section;
  44047. remainingRange.setEnd (remainingRange.getEnd() - (nextIndex - index));
  44048. if (remainingRange.isEmpty())
  44049. break;
  44050. --i;
  44051. }
  44052. else
  44053. {
  44054. index = nextIndex;
  44055. }
  44056. }
  44057. coalesceSimilarSections();
  44058. totalNumChars = -1;
  44059. valueTextNeedsUpdating = true;
  44060. moveCursorTo (caretPositionToMoveTo, false);
  44061. repaintText (Range<int> (range.getStart(), getTotalNumChars()));
  44062. }
  44063. }
  44064. }
  44065. const String TextEditor::getText() const
  44066. {
  44067. String t;
  44068. t.preallocateStorage (getTotalNumChars());
  44069. String::Concatenator concatenator (t);
  44070. for (int i = 0; i < sections.size(); ++i)
  44071. sections.getUnchecked (i)->appendAllText (concatenator);
  44072. return t;
  44073. }
  44074. const String TextEditor::getTextInRange (const Range<int>& range) const
  44075. {
  44076. String t;
  44077. if (! range.isEmpty())
  44078. {
  44079. t.preallocateStorage (jmin (getTotalNumChars(), range.getLength()));
  44080. String::Concatenator concatenator (t);
  44081. int index = 0;
  44082. for (int i = 0; i < sections.size(); ++i)
  44083. {
  44084. const UniformTextSection* const s = sections.getUnchecked (i);
  44085. const int nextIndex = index + s->getTotalLength();
  44086. if (range.getStart() < nextIndex)
  44087. {
  44088. if (range.getEnd() <= index)
  44089. break;
  44090. s->appendSubstring (concatenator, range - index);
  44091. }
  44092. index = nextIndex;
  44093. }
  44094. }
  44095. return t;
  44096. }
  44097. const String TextEditor::getHighlightedText() const
  44098. {
  44099. return getTextInRange (selection);
  44100. }
  44101. int TextEditor::getTotalNumChars() const
  44102. {
  44103. if (totalNumChars < 0)
  44104. {
  44105. totalNumChars = 0;
  44106. for (int i = sections.size(); --i >= 0;)
  44107. totalNumChars += sections.getUnchecked (i)->getTotalLength();
  44108. }
  44109. return totalNumChars;
  44110. }
  44111. bool TextEditor::isEmpty() const
  44112. {
  44113. return getTotalNumChars() == 0;
  44114. }
  44115. void TextEditor::getCharPosition (const int index, float& cx, float& cy, float& lineHeight) const
  44116. {
  44117. const float wordWrapWidth = getWordWrapWidth();
  44118. if (wordWrapWidth > 0 && sections.size() > 0)
  44119. {
  44120. Iterator i (sections, wordWrapWidth, passwordCharacter);
  44121. i.getCharPosition (index, cx, cy, lineHeight);
  44122. }
  44123. else
  44124. {
  44125. cx = cy = 0;
  44126. lineHeight = currentFont.getHeight();
  44127. }
  44128. }
  44129. int TextEditor::indexAtPosition (const float x, const float y)
  44130. {
  44131. const float wordWrapWidth = getWordWrapWidth();
  44132. if (wordWrapWidth > 0)
  44133. {
  44134. Iterator i (sections, wordWrapWidth, passwordCharacter);
  44135. while (i.next())
  44136. {
  44137. if (i.lineY + i.lineHeight > y)
  44138. {
  44139. if (i.lineY > y)
  44140. return jmax (0, i.indexInText - 1);
  44141. if (i.atomX >= x)
  44142. return i.indexInText;
  44143. if (x < i.atomRight)
  44144. return i.xToIndex (x);
  44145. }
  44146. }
  44147. }
  44148. return getTotalNumChars();
  44149. }
  44150. int TextEditor::findWordBreakAfter (const int position) const
  44151. {
  44152. const String t (getTextInRange (Range<int> (position, position + 512)));
  44153. const int totalLength = t.length();
  44154. int i = 0;
  44155. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  44156. ++i;
  44157. const int type = TextEditorDefs::getCharacterCategory (t[i]);
  44158. while (i < totalLength && type == TextEditorDefs::getCharacterCategory (t[i]))
  44159. ++i;
  44160. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  44161. ++i;
  44162. return position + i;
  44163. }
  44164. int TextEditor::findWordBreakBefore (const int position) const
  44165. {
  44166. if (position <= 0)
  44167. return 0;
  44168. const int startOfBuffer = jmax (0, position - 512);
  44169. const String t (getTextInRange (Range<int> (startOfBuffer, position)));
  44170. int i = position - startOfBuffer;
  44171. while (i > 0 && CharacterFunctions::isWhitespace (t [i - 1]))
  44172. --i;
  44173. if (i > 0)
  44174. {
  44175. const int type = TextEditorDefs::getCharacterCategory (t [i - 1]);
  44176. while (i > 0 && type == TextEditorDefs::getCharacterCategory (t [i - 1]))
  44177. --i;
  44178. }
  44179. jassert (startOfBuffer + i >= 0);
  44180. return startOfBuffer + i;
  44181. }
  44182. void TextEditor::splitSection (const int sectionIndex,
  44183. const int charToSplitAt)
  44184. {
  44185. jassert (sections[sectionIndex] != 0);
  44186. sections.insert (sectionIndex + 1,
  44187. sections.getUnchecked (sectionIndex)->split (charToSplitAt, passwordCharacter));
  44188. }
  44189. void TextEditor::coalesceSimilarSections()
  44190. {
  44191. for (int i = 0; i < sections.size() - 1; ++i)
  44192. {
  44193. UniformTextSection* const s1 = sections.getUnchecked (i);
  44194. UniformTextSection* const s2 = sections.getUnchecked (i + 1);
  44195. if (s1->font == s2->font
  44196. && s1->colour == s2->colour)
  44197. {
  44198. s1->append (*s2, passwordCharacter);
  44199. sections.remove (i + 1);
  44200. delete s2;
  44201. --i;
  44202. }
  44203. }
  44204. }
  44205. END_JUCE_NAMESPACE
  44206. /*** End of inlined file: juce_TextEditor.cpp ***/
  44207. /*** Start of inlined file: juce_Toolbar.cpp ***/
  44208. BEGIN_JUCE_NAMESPACE
  44209. const char* const Toolbar::toolbarDragDescriptor = "_toolbarItem_";
  44210. class ToolbarSpacerComp : public ToolbarItemComponent
  44211. {
  44212. public:
  44213. ToolbarSpacerComp (const int itemId_, const float fixedSize_, const bool drawBar_)
  44214. : ToolbarItemComponent (itemId_, String::empty, false),
  44215. fixedSize (fixedSize_),
  44216. drawBar (drawBar_)
  44217. {
  44218. }
  44219. ~ToolbarSpacerComp()
  44220. {
  44221. }
  44222. bool getToolbarItemSizes (int toolbarThickness, bool /*isToolbarVertical*/,
  44223. int& preferredSize, int& minSize, int& maxSize)
  44224. {
  44225. if (fixedSize <= 0)
  44226. {
  44227. preferredSize = toolbarThickness * 2;
  44228. minSize = 4;
  44229. maxSize = 32768;
  44230. }
  44231. else
  44232. {
  44233. maxSize = roundToInt (toolbarThickness * fixedSize);
  44234. minSize = drawBar ? maxSize : jmin (4, maxSize);
  44235. preferredSize = maxSize;
  44236. if (getEditingMode() == editableOnPalette)
  44237. preferredSize = maxSize = toolbarThickness / (drawBar ? 3 : 2);
  44238. }
  44239. return true;
  44240. }
  44241. void paintButtonArea (Graphics&, int, int, bool, bool)
  44242. {
  44243. }
  44244. void contentAreaChanged (const Rectangle<int>&)
  44245. {
  44246. }
  44247. int getResizeOrder() const throw()
  44248. {
  44249. return fixedSize <= 0 ? 0 : 1;
  44250. }
  44251. void paint (Graphics& g)
  44252. {
  44253. const int w = getWidth();
  44254. const int h = getHeight();
  44255. if (drawBar)
  44256. {
  44257. g.setColour (findColour (Toolbar::separatorColourId, true));
  44258. const float thickness = 0.2f;
  44259. if (isToolbarVertical())
  44260. g.fillRect (w * 0.1f, h * (0.5f - thickness * 0.5f), w * 0.8f, h * thickness);
  44261. else
  44262. g.fillRect (w * (0.5f - thickness * 0.5f), h * 0.1f, w * thickness, h * 0.8f);
  44263. }
  44264. if (getEditingMode() != normalMode && ! drawBar)
  44265. {
  44266. g.setColour (findColour (Toolbar::separatorColourId, true));
  44267. const int indentX = jmin (2, (w - 3) / 2);
  44268. const int indentY = jmin (2, (h - 3) / 2);
  44269. g.drawRect (indentX, indentY, w - indentX * 2, h - indentY * 2, 1);
  44270. if (fixedSize <= 0)
  44271. {
  44272. float x1, y1, x2, y2, x3, y3, x4, y4, hw, hl;
  44273. if (isToolbarVertical())
  44274. {
  44275. x1 = w * 0.5f;
  44276. y1 = h * 0.4f;
  44277. x2 = x1;
  44278. y2 = indentX * 2.0f;
  44279. x3 = x1;
  44280. y3 = h * 0.6f;
  44281. x4 = x1;
  44282. y4 = h - y2;
  44283. hw = w * 0.15f;
  44284. hl = w * 0.2f;
  44285. }
  44286. else
  44287. {
  44288. x1 = w * 0.4f;
  44289. y1 = h * 0.5f;
  44290. x2 = indentX * 2.0f;
  44291. y2 = y1;
  44292. x3 = w * 0.6f;
  44293. y3 = y1;
  44294. x4 = w - x2;
  44295. y4 = y1;
  44296. hw = h * 0.15f;
  44297. hl = h * 0.2f;
  44298. }
  44299. Path p;
  44300. p.addArrow (Line<float> (x1, y1, x2, y2), 1.5f, hw, hl);
  44301. p.addArrow (Line<float> (x3, y3, x4, y4), 1.5f, hw, hl);
  44302. g.fillPath (p);
  44303. }
  44304. }
  44305. }
  44306. juce_UseDebuggingNewOperator
  44307. private:
  44308. const float fixedSize;
  44309. const bool drawBar;
  44310. ToolbarSpacerComp (const ToolbarSpacerComp&);
  44311. ToolbarSpacerComp& operator= (const ToolbarSpacerComp&);
  44312. };
  44313. class Toolbar::MissingItemsComponent : public PopupMenuCustomComponent
  44314. {
  44315. public:
  44316. MissingItemsComponent (Toolbar& owner_, const int height_)
  44317. : PopupMenuCustomComponent (true),
  44318. owner (owner_),
  44319. height (height_)
  44320. {
  44321. for (int i = owner_.items.size(); --i >= 0;)
  44322. {
  44323. ToolbarItemComponent* const tc = owner_.items.getUnchecked(i);
  44324. if (dynamic_cast <ToolbarSpacerComp*> (tc) == 0 && ! tc->isVisible())
  44325. {
  44326. oldIndexes.insert (0, i);
  44327. addAndMakeVisible (tc, 0);
  44328. }
  44329. }
  44330. layout (400);
  44331. }
  44332. ~MissingItemsComponent()
  44333. {
  44334. // deleting the toolbar while its menu it open??
  44335. jassert (owner.isValidComponent());
  44336. for (int i = 0; i < getNumChildComponents(); ++i)
  44337. {
  44338. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  44339. if (tc != 0)
  44340. {
  44341. tc->setVisible (false);
  44342. const int index = oldIndexes.remove (i);
  44343. owner.addChildComponent (tc, index);
  44344. --i;
  44345. }
  44346. }
  44347. owner.resized();
  44348. }
  44349. void layout (const int preferredWidth)
  44350. {
  44351. const int indent = 8;
  44352. int x = indent;
  44353. int y = indent;
  44354. int maxX = 0;
  44355. for (int i = 0; i < getNumChildComponents(); ++i)
  44356. {
  44357. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  44358. if (tc != 0)
  44359. {
  44360. int preferredSize = 1, minSize = 1, maxSize = 1;
  44361. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  44362. {
  44363. if (x + preferredSize > preferredWidth && x > indent)
  44364. {
  44365. x = indent;
  44366. y += height;
  44367. }
  44368. tc->setBounds (x, y, preferredSize, height);
  44369. x += preferredSize;
  44370. maxX = jmax (maxX, x);
  44371. }
  44372. }
  44373. }
  44374. setSize (maxX + 8, y + height + 8);
  44375. }
  44376. void getIdealSize (int& idealWidth, int& idealHeight)
  44377. {
  44378. idealWidth = getWidth();
  44379. idealHeight = getHeight();
  44380. }
  44381. juce_UseDebuggingNewOperator
  44382. private:
  44383. Toolbar& owner;
  44384. const int height;
  44385. Array <int> oldIndexes;
  44386. MissingItemsComponent (const MissingItemsComponent&);
  44387. MissingItemsComponent& operator= (const MissingItemsComponent&);
  44388. };
  44389. Toolbar::Toolbar()
  44390. : vertical (false),
  44391. isEditingActive (false),
  44392. toolbarStyle (Toolbar::iconsOnly)
  44393. {
  44394. addChildComponent (missingItemsButton = getLookAndFeel().createToolbarMissingItemsButton (*this));
  44395. missingItemsButton->setAlwaysOnTop (true);
  44396. missingItemsButton->addButtonListener (this);
  44397. }
  44398. Toolbar::~Toolbar()
  44399. {
  44400. deleteAllChildren();
  44401. }
  44402. void Toolbar::setVertical (const bool shouldBeVertical)
  44403. {
  44404. if (vertical != shouldBeVertical)
  44405. {
  44406. vertical = shouldBeVertical;
  44407. resized();
  44408. }
  44409. }
  44410. void Toolbar::clear()
  44411. {
  44412. for (int i = items.size(); --i >= 0;)
  44413. {
  44414. ToolbarItemComponent* const tc = items.getUnchecked(i);
  44415. items.remove (i);
  44416. delete tc;
  44417. }
  44418. resized();
  44419. }
  44420. ToolbarItemComponent* Toolbar::createItem (ToolbarItemFactory& factory, const int itemId)
  44421. {
  44422. if (itemId == ToolbarItemFactory::separatorBarId)
  44423. return new ToolbarSpacerComp (itemId, 0.1f, true);
  44424. else if (itemId == ToolbarItemFactory::spacerId)
  44425. return new ToolbarSpacerComp (itemId, 0.5f, false);
  44426. else if (itemId == ToolbarItemFactory::flexibleSpacerId)
  44427. return new ToolbarSpacerComp (itemId, 0, false);
  44428. return factory.createItem (itemId);
  44429. }
  44430. void Toolbar::addItemInternal (ToolbarItemFactory& factory,
  44431. const int itemId,
  44432. const int insertIndex)
  44433. {
  44434. // An ID can't be zero - this might indicate a mistake somewhere?
  44435. jassert (itemId != 0);
  44436. ToolbarItemComponent* const tc = createItem (factory, itemId);
  44437. if (tc != 0)
  44438. {
  44439. #if JUCE_DEBUG
  44440. Array <int> allowedIds;
  44441. factory.getAllToolbarItemIds (allowedIds);
  44442. // If your factory can create an item for a given ID, it must also return
  44443. // that ID from its getAllToolbarItemIds() method!
  44444. jassert (allowedIds.contains (itemId));
  44445. #endif
  44446. items.insert (insertIndex, tc);
  44447. addAndMakeVisible (tc, insertIndex);
  44448. }
  44449. }
  44450. void Toolbar::addItem (ToolbarItemFactory& factory,
  44451. const int itemId,
  44452. const int insertIndex)
  44453. {
  44454. addItemInternal (factory, itemId, insertIndex);
  44455. resized();
  44456. }
  44457. void Toolbar::addDefaultItems (ToolbarItemFactory& factoryToUse)
  44458. {
  44459. Array <int> ids;
  44460. factoryToUse.getDefaultItemSet (ids);
  44461. clear();
  44462. for (int i = 0; i < ids.size(); ++i)
  44463. addItemInternal (factoryToUse, ids.getUnchecked (i), -1);
  44464. resized();
  44465. }
  44466. void Toolbar::removeToolbarItem (const int itemIndex)
  44467. {
  44468. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  44469. if (tc != 0)
  44470. {
  44471. items.removeValue (tc);
  44472. delete tc;
  44473. resized();
  44474. }
  44475. }
  44476. int Toolbar::getNumItems() const throw()
  44477. {
  44478. return items.size();
  44479. }
  44480. int Toolbar::getItemId (const int itemIndex) const throw()
  44481. {
  44482. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  44483. return tc != 0 ? tc->getItemId() : 0;
  44484. }
  44485. ToolbarItemComponent* Toolbar::getItemComponent (const int itemIndex) const throw()
  44486. {
  44487. return items [itemIndex];
  44488. }
  44489. ToolbarItemComponent* Toolbar::getNextActiveComponent (int index, const int delta) const
  44490. {
  44491. for (;;)
  44492. {
  44493. index += delta;
  44494. ToolbarItemComponent* const tc = getItemComponent (index);
  44495. if (tc == 0)
  44496. break;
  44497. if (tc->isActive)
  44498. return tc;
  44499. }
  44500. return 0;
  44501. }
  44502. void Toolbar::setStyle (const ToolbarItemStyle& newStyle)
  44503. {
  44504. if (toolbarStyle != newStyle)
  44505. {
  44506. toolbarStyle = newStyle;
  44507. updateAllItemPositions (false);
  44508. }
  44509. }
  44510. const String Toolbar::toString() const
  44511. {
  44512. String s ("TB:");
  44513. for (int i = 0; i < getNumItems(); ++i)
  44514. s << getItemId(i) << ' ';
  44515. return s.trimEnd();
  44516. }
  44517. bool Toolbar::restoreFromString (ToolbarItemFactory& factoryToUse,
  44518. const String& savedVersion)
  44519. {
  44520. if (! savedVersion.startsWith ("TB:"))
  44521. return false;
  44522. StringArray tokens;
  44523. tokens.addTokens (savedVersion.substring (3), false);
  44524. clear();
  44525. for (int i = 0; i < tokens.size(); ++i)
  44526. addItemInternal (factoryToUse, tokens[i].getIntValue(), -1);
  44527. resized();
  44528. return true;
  44529. }
  44530. void Toolbar::paint (Graphics& g)
  44531. {
  44532. getLookAndFeel().paintToolbarBackground (g, getWidth(), getHeight(), *this);
  44533. }
  44534. int Toolbar::getThickness() const throw()
  44535. {
  44536. return vertical ? getWidth() : getHeight();
  44537. }
  44538. int Toolbar::getLength() const throw()
  44539. {
  44540. return vertical ? getHeight() : getWidth();
  44541. }
  44542. void Toolbar::setEditingActive (const bool active)
  44543. {
  44544. if (isEditingActive != active)
  44545. {
  44546. isEditingActive = active;
  44547. updateAllItemPositions (false);
  44548. }
  44549. }
  44550. void Toolbar::resized()
  44551. {
  44552. updateAllItemPositions (false);
  44553. }
  44554. void Toolbar::updateAllItemPositions (const bool animate)
  44555. {
  44556. if (getWidth() > 0 && getHeight() > 0)
  44557. {
  44558. StretchableObjectResizer resizer;
  44559. int i;
  44560. for (i = 0; i < items.size(); ++i)
  44561. {
  44562. ToolbarItemComponent* const tc = items.getUnchecked(i);
  44563. tc->setEditingMode (isEditingActive ? ToolbarItemComponent::editableOnToolbar
  44564. : ToolbarItemComponent::normalMode);
  44565. tc->setStyle (toolbarStyle);
  44566. ToolbarSpacerComp* const spacer = dynamic_cast <ToolbarSpacerComp*> (tc);
  44567. int preferredSize = 1, minSize = 1, maxSize = 1;
  44568. if (tc->getToolbarItemSizes (getThickness(), isVertical(),
  44569. preferredSize, minSize, maxSize))
  44570. {
  44571. tc->isActive = true;
  44572. resizer.addItem (preferredSize, minSize, maxSize,
  44573. spacer != 0 ? spacer->getResizeOrder() : 2);
  44574. }
  44575. else
  44576. {
  44577. tc->isActive = false;
  44578. tc->setVisible (false);
  44579. }
  44580. }
  44581. resizer.resizeToFit (getLength());
  44582. int totalLength = 0;
  44583. for (i = 0; i < resizer.getNumItems(); ++i)
  44584. totalLength += (int) resizer.getItemSize (i);
  44585. const bool itemsOffTheEnd = totalLength > getLength();
  44586. const int extrasButtonSize = getThickness() / 2;
  44587. missingItemsButton->setSize (extrasButtonSize, extrasButtonSize);
  44588. missingItemsButton->setVisible (itemsOffTheEnd);
  44589. missingItemsButton->setEnabled (! isEditingActive);
  44590. if (vertical)
  44591. missingItemsButton->setCentrePosition (getWidth() / 2,
  44592. getHeight() - 4 - extrasButtonSize / 2);
  44593. else
  44594. missingItemsButton->setCentrePosition (getWidth() - 4 - extrasButtonSize / 2,
  44595. getHeight() / 2);
  44596. const int maxLength = itemsOffTheEnd ? (vertical ? missingItemsButton->getY()
  44597. : missingItemsButton->getX()) - 4
  44598. : getLength();
  44599. int pos = 0, activeIndex = 0;
  44600. for (i = 0; i < items.size(); ++i)
  44601. {
  44602. ToolbarItemComponent* const tc = items.getUnchecked(i);
  44603. if (tc->isActive)
  44604. {
  44605. const int size = (int) resizer.getItemSize (activeIndex++);
  44606. Rectangle<int> newBounds;
  44607. if (vertical)
  44608. newBounds.setBounds (0, pos, getWidth(), size);
  44609. else
  44610. newBounds.setBounds (pos, 0, size, getHeight());
  44611. if (animate)
  44612. {
  44613. Desktop::getInstance().getAnimator().animateComponent (tc, newBounds, 1.0f, 200, false, 3.0, 0.0);
  44614. }
  44615. else
  44616. {
  44617. Desktop::getInstance().getAnimator().cancelAnimation (tc, false);
  44618. tc->setBounds (newBounds);
  44619. }
  44620. pos += size;
  44621. tc->setVisible (pos <= maxLength
  44622. && ((! tc->isBeingDragged)
  44623. || tc->getEditingMode() == ToolbarItemComponent::editableOnPalette));
  44624. }
  44625. }
  44626. }
  44627. }
  44628. void Toolbar::buttonClicked (Button*)
  44629. {
  44630. jassert (missingItemsButton->isShowing());
  44631. if (missingItemsButton->isShowing())
  44632. {
  44633. PopupMenu m;
  44634. m.addCustomItem (1, new MissingItemsComponent (*this, getThickness()));
  44635. m.showAt (missingItemsButton);
  44636. }
  44637. }
  44638. bool Toolbar::isInterestedInDragSource (const String& sourceDescription,
  44639. Component* /*sourceComponent*/)
  44640. {
  44641. return sourceDescription == toolbarDragDescriptor && isEditingActive;
  44642. }
  44643. void Toolbar::itemDragMove (const String&, Component* sourceComponent, int x, int y)
  44644. {
  44645. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  44646. if (tc != 0)
  44647. {
  44648. if (getNumItems() == 0)
  44649. {
  44650. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  44651. {
  44652. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  44653. if (palette != 0)
  44654. palette->replaceComponent (tc);
  44655. }
  44656. else
  44657. {
  44658. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  44659. }
  44660. items.add (tc);
  44661. addChildComponent (tc);
  44662. updateAllItemPositions (false);
  44663. }
  44664. else
  44665. {
  44666. for (int i = getNumItems(); --i >= 0;)
  44667. {
  44668. int currentIndex = getIndexOfChildComponent (tc);
  44669. if (currentIndex < 0)
  44670. {
  44671. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  44672. {
  44673. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  44674. if (palette != 0)
  44675. palette->replaceComponent (tc);
  44676. }
  44677. else
  44678. {
  44679. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  44680. }
  44681. items.add (tc);
  44682. addChildComponent (tc);
  44683. currentIndex = getIndexOfChildComponent (tc);
  44684. updateAllItemPositions (true);
  44685. }
  44686. int newIndex = currentIndex;
  44687. const int dragObjectLeft = vertical ? (y - tc->dragOffsetY) : (x - tc->dragOffsetX);
  44688. const int dragObjectRight = dragObjectLeft + (vertical ? tc->getHeight() : tc->getWidth());
  44689. const Rectangle<int> current (Desktop::getInstance().getAnimator()
  44690. .getComponentDestination (getChildComponent (newIndex)));
  44691. ToolbarItemComponent* const prev = getNextActiveComponent (newIndex, -1);
  44692. if (prev != 0)
  44693. {
  44694. const Rectangle<int> previousPos (Desktop::getInstance().getAnimator().getComponentDestination (prev));
  44695. if (abs (dragObjectLeft - (vertical ? previousPos.getY() : previousPos.getX())
  44696. < abs (dragObjectRight - (vertical ? current.getBottom() : current.getRight()))))
  44697. {
  44698. newIndex = getIndexOfChildComponent (prev);
  44699. }
  44700. }
  44701. ToolbarItemComponent* const next = getNextActiveComponent (newIndex, 1);
  44702. if (next != 0)
  44703. {
  44704. const Rectangle<int> nextPos (Desktop::getInstance().getAnimator().getComponentDestination (next));
  44705. if (abs (dragObjectLeft - (vertical ? current.getY() : current.getX())
  44706. > abs (dragObjectRight - (vertical ? nextPos.getBottom() : nextPos.getRight()))))
  44707. {
  44708. newIndex = getIndexOfChildComponent (next) + 1;
  44709. }
  44710. }
  44711. if (newIndex != currentIndex)
  44712. {
  44713. items.removeValue (tc);
  44714. removeChildComponent (tc);
  44715. addChildComponent (tc, newIndex);
  44716. items.insert (newIndex, tc);
  44717. updateAllItemPositions (true);
  44718. }
  44719. else
  44720. {
  44721. break;
  44722. }
  44723. }
  44724. }
  44725. }
  44726. }
  44727. void Toolbar::itemDragExit (const String&, Component* sourceComponent)
  44728. {
  44729. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  44730. if (tc != 0)
  44731. {
  44732. if (isParentOf (tc))
  44733. {
  44734. items.removeValue (tc);
  44735. removeChildComponent (tc);
  44736. updateAllItemPositions (true);
  44737. }
  44738. }
  44739. }
  44740. void Toolbar::itemDropped (const String&, Component*, int, int)
  44741. {
  44742. }
  44743. void Toolbar::mouseDown (const MouseEvent& e)
  44744. {
  44745. if (e.mods.isPopupMenu())
  44746. {
  44747. }
  44748. }
  44749. class ToolbarCustomisationDialog : public DialogWindow
  44750. {
  44751. public:
  44752. ToolbarCustomisationDialog (ToolbarItemFactory& factory,
  44753. Toolbar* const toolbar_,
  44754. const int optionFlags)
  44755. : DialogWindow (TRANS("Add/remove items from toolbar"), Colours::white, true, true),
  44756. toolbar (toolbar_)
  44757. {
  44758. setContentComponent (new CustomiserPanel (factory, toolbar, optionFlags), true, true);
  44759. setResizable (true, true);
  44760. setResizeLimits (400, 300, 1500, 1000);
  44761. positionNearBar();
  44762. }
  44763. ~ToolbarCustomisationDialog()
  44764. {
  44765. setContentComponent (0, true);
  44766. }
  44767. void closeButtonPressed()
  44768. {
  44769. setVisible (false);
  44770. }
  44771. bool canModalEventBeSentToComponent (const Component* comp)
  44772. {
  44773. return toolbar->isParentOf (comp);
  44774. }
  44775. void positionNearBar()
  44776. {
  44777. const Rectangle<int> screenSize (toolbar->getParentMonitorArea());
  44778. const int tbx = toolbar->getScreenX();
  44779. const int tby = toolbar->getScreenY();
  44780. const int gap = 8;
  44781. int x, y;
  44782. if (toolbar->isVertical())
  44783. {
  44784. y = tby;
  44785. if (tbx > screenSize.getCentreX())
  44786. x = tbx - getWidth() - gap;
  44787. else
  44788. x = tbx + toolbar->getWidth() + gap;
  44789. }
  44790. else
  44791. {
  44792. x = tbx + (toolbar->getWidth() - getWidth()) / 2;
  44793. if (tby > screenSize.getCentreY())
  44794. y = tby - getHeight() - gap;
  44795. else
  44796. y = tby + toolbar->getHeight() + gap;
  44797. }
  44798. setTopLeftPosition (x, y);
  44799. }
  44800. private:
  44801. Toolbar* const toolbar;
  44802. class CustomiserPanel : public Component,
  44803. private ComboBoxListener, // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  44804. private ButtonListener
  44805. {
  44806. public:
  44807. CustomiserPanel (ToolbarItemFactory& factory_,
  44808. Toolbar* const toolbar_,
  44809. const int optionFlags)
  44810. : factory (factory_),
  44811. toolbar (toolbar_),
  44812. palette (factory_, toolbar_),
  44813. instructions (String::empty, TRANS ("You can drag the items above and drop them onto a toolbar to add them.\n\n"
  44814. "Items on the toolbar can also be dragged around to change their order, or dragged off the edge to delete them.")),
  44815. defaultButton (TRANS ("Restore to default set of items"))
  44816. {
  44817. addAndMakeVisible (&palette);
  44818. if ((optionFlags & (Toolbar::allowIconsOnlyChoice
  44819. | Toolbar::allowIconsWithTextChoice
  44820. | Toolbar::allowTextOnlyChoice)) != 0)
  44821. {
  44822. addAndMakeVisible (&styleBox);
  44823. styleBox.setEditableText (false);
  44824. if ((optionFlags & Toolbar::allowIconsOnlyChoice) != 0) styleBox.addItem (TRANS("Show icons only"), 1);
  44825. if ((optionFlags & Toolbar::allowIconsWithTextChoice) != 0) styleBox.addItem (TRANS("Show icons and descriptions"), 2);
  44826. if ((optionFlags & Toolbar::allowTextOnlyChoice) != 0) styleBox.addItem (TRANS("Show descriptions only"), 3);
  44827. int selectedStyle = 0;
  44828. switch (toolbar_->getStyle())
  44829. {
  44830. case Toolbar::iconsOnly: selectedStyle = 1; break;
  44831. case Toolbar::iconsWithText: selectedStyle = 2; break;
  44832. case Toolbar::textOnly: selectedStyle = 3; break;
  44833. }
  44834. styleBox.setSelectedId (selectedStyle);
  44835. styleBox.addListener (this);
  44836. }
  44837. if ((optionFlags & Toolbar::showResetToDefaultsButton) != 0)
  44838. {
  44839. addAndMakeVisible (&defaultButton);
  44840. defaultButton.addButtonListener (this);
  44841. }
  44842. addAndMakeVisible (&instructions);
  44843. instructions.setFont (Font (13.0f));
  44844. setSize (500, 300);
  44845. }
  44846. void comboBoxChanged (ComboBox*)
  44847. {
  44848. switch (styleBox.getSelectedId())
  44849. {
  44850. case 1: toolbar->setStyle (Toolbar::iconsOnly); break;
  44851. case 2: toolbar->setStyle (Toolbar::iconsWithText); break;
  44852. case 3: toolbar->setStyle (Toolbar::textOnly); break;
  44853. }
  44854. palette.resized(); // to make it update the styles
  44855. }
  44856. void buttonClicked (Button*)
  44857. {
  44858. toolbar->addDefaultItems (factory);
  44859. }
  44860. void paint (Graphics& g)
  44861. {
  44862. Colour background;
  44863. DialogWindow* const dw = findParentComponentOfClass ((DialogWindow*) 0);
  44864. if (dw != 0)
  44865. background = dw->getBackgroundColour();
  44866. g.setColour (background.contrasting().withAlpha (0.3f));
  44867. g.fillRect (palette.getX(), palette.getBottom() - 1, palette.getWidth(), 1);
  44868. }
  44869. void resized()
  44870. {
  44871. palette.setBounds (0, 0, getWidth(), getHeight() - 120);
  44872. styleBox.setBounds (10, getHeight() - 110, 200, 22);
  44873. defaultButton.changeWidthToFitText (22);
  44874. defaultButton.setTopLeftPosition (240, getHeight() - 110);
  44875. instructions.setBounds (10, getHeight() - 80, getWidth() - 20, 80);
  44876. }
  44877. private:
  44878. ToolbarItemFactory& factory;
  44879. Toolbar* const toolbar;
  44880. ToolbarItemPalette palette;
  44881. Label instructions;
  44882. ComboBox styleBox;
  44883. TextButton defaultButton;
  44884. };
  44885. };
  44886. void Toolbar::showCustomisationDialog (ToolbarItemFactory& factory, const int optionFlags)
  44887. {
  44888. setEditingActive (true);
  44889. ToolbarCustomisationDialog dw (factory, this, optionFlags);
  44890. dw.runModalLoop();
  44891. jassert (isValidComponent()); // ? deleting the toolbar while it's being edited?
  44892. setEditingActive (false);
  44893. }
  44894. END_JUCE_NAMESPACE
  44895. /*** End of inlined file: juce_Toolbar.cpp ***/
  44896. /*** Start of inlined file: juce_ToolbarItemComponent.cpp ***/
  44897. BEGIN_JUCE_NAMESPACE
  44898. ToolbarItemFactory::ToolbarItemFactory()
  44899. {
  44900. }
  44901. ToolbarItemFactory::~ToolbarItemFactory()
  44902. {
  44903. }
  44904. class ItemDragAndDropOverlayComponent : public Component
  44905. {
  44906. public:
  44907. ItemDragAndDropOverlayComponent()
  44908. : isDragging (false)
  44909. {
  44910. setAlwaysOnTop (true);
  44911. setRepaintsOnMouseActivity (true);
  44912. setMouseCursor (MouseCursor::DraggingHandCursor);
  44913. }
  44914. ~ItemDragAndDropOverlayComponent()
  44915. {
  44916. }
  44917. void paint (Graphics& g)
  44918. {
  44919. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44920. if (isMouseOverOrDragging()
  44921. && tc != 0
  44922. && tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  44923. {
  44924. g.setColour (findColour (Toolbar::editingModeOutlineColourId, true));
  44925. g.drawRect (0, 0, getWidth(), getHeight(),
  44926. jmin (2, (getWidth() - 1) / 2, (getHeight() - 1) / 2));
  44927. }
  44928. }
  44929. void mouseDown (const MouseEvent& e)
  44930. {
  44931. isDragging = false;
  44932. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44933. if (tc != 0)
  44934. {
  44935. tc->dragOffsetX = e.x;
  44936. tc->dragOffsetY = e.y;
  44937. }
  44938. }
  44939. void mouseDrag (const MouseEvent& e)
  44940. {
  44941. if (! (isDragging || e.mouseWasClicked()))
  44942. {
  44943. isDragging = true;
  44944. DragAndDropContainer* const dnd = DragAndDropContainer::findParentDragContainerFor (this);
  44945. if (dnd != 0)
  44946. {
  44947. dnd->startDragging (Toolbar::toolbarDragDescriptor, getParentComponent(), Image::null, true);
  44948. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44949. if (tc != 0)
  44950. {
  44951. tc->isBeingDragged = true;
  44952. if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  44953. tc->setVisible (false);
  44954. }
  44955. }
  44956. }
  44957. }
  44958. void mouseUp (const MouseEvent&)
  44959. {
  44960. isDragging = false;
  44961. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44962. if (tc != 0)
  44963. {
  44964. tc->isBeingDragged = false;
  44965. Toolbar* const tb = tc->getToolbar();
  44966. if (tb != 0)
  44967. tb->updateAllItemPositions (true);
  44968. else if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  44969. delete tc;
  44970. }
  44971. }
  44972. void parentSizeChanged()
  44973. {
  44974. setBounds (0, 0, getParentWidth(), getParentHeight());
  44975. }
  44976. juce_UseDebuggingNewOperator
  44977. private:
  44978. bool isDragging;
  44979. ItemDragAndDropOverlayComponent (const ItemDragAndDropOverlayComponent&);
  44980. ItemDragAndDropOverlayComponent& operator= (const ItemDragAndDropOverlayComponent&);
  44981. };
  44982. ToolbarItemComponent::ToolbarItemComponent (const int itemId_,
  44983. const String& labelText,
  44984. const bool isBeingUsedAsAButton_)
  44985. : Button (labelText),
  44986. itemId (itemId_),
  44987. mode (normalMode),
  44988. toolbarStyle (Toolbar::iconsOnly),
  44989. dragOffsetX (0),
  44990. dragOffsetY (0),
  44991. isActive (true),
  44992. isBeingDragged (false),
  44993. isBeingUsedAsAButton (isBeingUsedAsAButton_)
  44994. {
  44995. // Your item ID can't be 0!
  44996. jassert (itemId_ != 0);
  44997. }
  44998. ToolbarItemComponent::~ToolbarItemComponent()
  44999. {
  45000. jassert (overlayComp == 0 || overlayComp->isValidComponent());
  45001. overlayComp = 0;
  45002. }
  45003. Toolbar* ToolbarItemComponent::getToolbar() const
  45004. {
  45005. return dynamic_cast <Toolbar*> (getParentComponent());
  45006. }
  45007. bool ToolbarItemComponent::isToolbarVertical() const
  45008. {
  45009. const Toolbar* const t = getToolbar();
  45010. return t != 0 && t->isVertical();
  45011. }
  45012. void ToolbarItemComponent::setStyle (const Toolbar::ToolbarItemStyle& newStyle)
  45013. {
  45014. if (toolbarStyle != newStyle)
  45015. {
  45016. toolbarStyle = newStyle;
  45017. repaint();
  45018. resized();
  45019. }
  45020. }
  45021. void ToolbarItemComponent::paintButton (Graphics& g, const bool over, const bool down)
  45022. {
  45023. if (isBeingUsedAsAButton)
  45024. getLookAndFeel().paintToolbarButtonBackground (g, getWidth(), getHeight(),
  45025. over, down, *this);
  45026. if (toolbarStyle != Toolbar::iconsOnly)
  45027. {
  45028. const int indent = contentArea.getX();
  45029. int y = indent;
  45030. int h = getHeight() - indent * 2;
  45031. if (toolbarStyle == Toolbar::iconsWithText)
  45032. {
  45033. y = contentArea.getBottom() + indent / 2;
  45034. h -= contentArea.getHeight();
  45035. }
  45036. getLookAndFeel().paintToolbarButtonLabel (g, indent, y, getWidth() - indent * 2, h,
  45037. getButtonText(), *this);
  45038. }
  45039. if (! contentArea.isEmpty())
  45040. {
  45041. g.saveState();
  45042. g.reduceClipRegion (contentArea);
  45043. g.setOrigin (contentArea.getX(), contentArea.getY());
  45044. paintButtonArea (g, contentArea.getWidth(), contentArea.getHeight(), over, down);
  45045. g.restoreState();
  45046. }
  45047. }
  45048. void ToolbarItemComponent::resized()
  45049. {
  45050. if (toolbarStyle != Toolbar::textOnly)
  45051. {
  45052. const int indent = jmin (proportionOfWidth (0.08f),
  45053. proportionOfHeight (0.08f));
  45054. contentArea = Rectangle<int> (indent, indent,
  45055. getWidth() - indent * 2,
  45056. toolbarStyle == Toolbar::iconsWithText ? proportionOfHeight (0.55f)
  45057. : (getHeight() - indent * 2));
  45058. }
  45059. else
  45060. {
  45061. contentArea = Rectangle<int>();
  45062. }
  45063. contentAreaChanged (contentArea);
  45064. }
  45065. void ToolbarItemComponent::setEditingMode (const ToolbarEditingMode newMode)
  45066. {
  45067. if (mode != newMode)
  45068. {
  45069. mode = newMode;
  45070. repaint();
  45071. if (mode == normalMode)
  45072. {
  45073. jassert (overlayComp == 0 || overlayComp->isValidComponent());
  45074. overlayComp = 0;
  45075. }
  45076. else if (overlayComp == 0)
  45077. {
  45078. addAndMakeVisible (overlayComp = new ItemDragAndDropOverlayComponent());
  45079. overlayComp->parentSizeChanged();
  45080. }
  45081. resized();
  45082. }
  45083. }
  45084. END_JUCE_NAMESPACE
  45085. /*** End of inlined file: juce_ToolbarItemComponent.cpp ***/
  45086. /*** Start of inlined file: juce_ToolbarItemPalette.cpp ***/
  45087. BEGIN_JUCE_NAMESPACE
  45088. ToolbarItemPalette::ToolbarItemPalette (ToolbarItemFactory& factory_,
  45089. Toolbar* const toolbar_)
  45090. : factory (factory_),
  45091. toolbar (toolbar_)
  45092. {
  45093. Component* const itemHolder = new Component();
  45094. viewport.setViewedComponent (itemHolder);
  45095. Array <int> allIds;
  45096. factory_.getAllToolbarItemIds (allIds);
  45097. for (int i = 0; i < allIds.size(); ++i)
  45098. {
  45099. ToolbarItemComponent* const tc = Toolbar::createItem (factory_, allIds.getUnchecked (i));
  45100. jassert (tc != 0);
  45101. if (tc != 0)
  45102. {
  45103. itemHolder->addAndMakeVisible (tc);
  45104. tc->setEditingMode (ToolbarItemComponent::editableOnPalette);
  45105. }
  45106. }
  45107. addAndMakeVisible (&viewport);
  45108. }
  45109. ToolbarItemPalette::~ToolbarItemPalette()
  45110. {
  45111. viewport.getViewedComponent()->deleteAllChildren();
  45112. }
  45113. void ToolbarItemPalette::resized()
  45114. {
  45115. viewport.setBoundsInset (BorderSize (1));
  45116. Component* const itemHolder = viewport.getViewedComponent();
  45117. const int indent = 8;
  45118. const int preferredWidth = viewport.getWidth() - viewport.getScrollBarThickness() - indent;
  45119. const int height = toolbar->getThickness();
  45120. int x = indent;
  45121. int y = indent;
  45122. int maxX = 0;
  45123. for (int i = 0; i < itemHolder->getNumChildComponents(); ++i)
  45124. {
  45125. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (itemHolder->getChildComponent (i));
  45126. if (tc != 0)
  45127. {
  45128. tc->setStyle (toolbar->getStyle());
  45129. int preferredSize = 1, minSize = 1, maxSize = 1;
  45130. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  45131. {
  45132. if (x + preferredSize > preferredWidth && x > indent)
  45133. {
  45134. x = indent;
  45135. y += height;
  45136. }
  45137. tc->setBounds (x, y, preferredSize, height);
  45138. x += preferredSize + 8;
  45139. maxX = jmax (maxX, x);
  45140. }
  45141. }
  45142. }
  45143. itemHolder->setSize (maxX, y + height + 8);
  45144. }
  45145. void ToolbarItemPalette::replaceComponent (ToolbarItemComponent* const comp)
  45146. {
  45147. ToolbarItemComponent* const tc = Toolbar::createItem (factory, comp->getItemId());
  45148. jassert (tc != 0);
  45149. if (tc != 0)
  45150. {
  45151. tc->setBounds (comp->getBounds());
  45152. tc->setStyle (toolbar->getStyle());
  45153. tc->setEditingMode (comp->getEditingMode());
  45154. viewport.getViewedComponent()->addAndMakeVisible (tc, getIndexOfChildComponent (comp));
  45155. }
  45156. }
  45157. END_JUCE_NAMESPACE
  45158. /*** End of inlined file: juce_ToolbarItemPalette.cpp ***/
  45159. /*** Start of inlined file: juce_TreeView.cpp ***/
  45160. BEGIN_JUCE_NAMESPACE
  45161. class TreeViewContentComponent : public Component,
  45162. public TooltipClient
  45163. {
  45164. public:
  45165. TreeViewContentComponent (TreeView& owner_)
  45166. : owner (owner_),
  45167. buttonUnderMouse (0),
  45168. isDragging (false)
  45169. {
  45170. }
  45171. ~TreeViewContentComponent()
  45172. {
  45173. }
  45174. void mouseDown (const MouseEvent& e)
  45175. {
  45176. updateButtonUnderMouse (e);
  45177. isDragging = false;
  45178. needSelectionOnMouseUp = false;
  45179. Rectangle<int> pos;
  45180. TreeViewItem* const item = findItemAt (e.y, pos);
  45181. if (item == 0)
  45182. return;
  45183. // (if the open/close buttons are hidden, we'll treat clicks to the left of the item
  45184. // as selection clicks)
  45185. if (e.x < pos.getX() && owner.openCloseButtonsVisible)
  45186. {
  45187. if (e.x >= pos.getX() - owner.getIndentSize())
  45188. item->setOpen (! item->isOpen());
  45189. // (clicks to the left of an open/close button are ignored)
  45190. }
  45191. else
  45192. {
  45193. // mouse-down inside the body of the item..
  45194. if (! owner.isMultiSelectEnabled())
  45195. item->setSelected (true, true);
  45196. else if (item->isSelected())
  45197. needSelectionOnMouseUp = ! e.mods.isPopupMenu();
  45198. else
  45199. selectBasedOnModifiers (item, e.mods);
  45200. if (e.x >= pos.getX())
  45201. item->itemClicked (e.withNewPosition (e.getPosition() - pos.getPosition()));
  45202. }
  45203. }
  45204. void mouseUp (const MouseEvent& e)
  45205. {
  45206. updateButtonUnderMouse (e);
  45207. if (needSelectionOnMouseUp && e.mouseWasClicked())
  45208. {
  45209. Rectangle<int> pos;
  45210. TreeViewItem* const item = findItemAt (e.y, pos);
  45211. if (item != 0)
  45212. selectBasedOnModifiers (item, e.mods);
  45213. }
  45214. }
  45215. void mouseDoubleClick (const MouseEvent& e)
  45216. {
  45217. if (e.getNumberOfClicks() != 3) // ignore triple clicks
  45218. {
  45219. Rectangle<int> pos;
  45220. TreeViewItem* const item = findItemAt (e.y, pos);
  45221. if (item != 0 && (e.x >= pos.getX() || ! owner.openCloseButtonsVisible))
  45222. item->itemDoubleClicked (e.withNewPosition (e.getPosition() - pos.getPosition()));
  45223. }
  45224. }
  45225. void mouseDrag (const MouseEvent& e)
  45226. {
  45227. if (isEnabled()
  45228. && ! (isDragging || e.mouseWasClicked()
  45229. || e.getDistanceFromDragStart() < 5
  45230. || e.mods.isPopupMenu()))
  45231. {
  45232. isDragging = true;
  45233. Rectangle<int> pos;
  45234. TreeViewItem* const item = findItemAt (e.getMouseDownY(), pos);
  45235. if (item != 0 && e.getMouseDownX() >= pos.getX())
  45236. {
  45237. const String dragDescription (item->getDragSourceDescription());
  45238. if (dragDescription.isNotEmpty())
  45239. {
  45240. DragAndDropContainer* const dragContainer
  45241. = DragAndDropContainer::findParentDragContainerFor (this);
  45242. if (dragContainer != 0)
  45243. {
  45244. pos.setSize (pos.getWidth(), item->itemHeight);
  45245. Image dragImage (Component::createComponentSnapshot (pos, true));
  45246. dragImage.multiplyAllAlphas (0.6f);
  45247. Point<int> imageOffset (pos.getPosition() - e.getPosition());
  45248. dragContainer->startDragging (dragDescription, &owner, dragImage, true, &imageOffset);
  45249. }
  45250. else
  45251. {
  45252. // to be able to do a drag-and-drop operation, the treeview needs to
  45253. // be inside a component which is also a DragAndDropContainer.
  45254. jassertfalse;
  45255. }
  45256. }
  45257. }
  45258. }
  45259. }
  45260. void mouseMove (const MouseEvent& e)
  45261. {
  45262. updateButtonUnderMouse (e);
  45263. }
  45264. void mouseExit (const MouseEvent& e)
  45265. {
  45266. updateButtonUnderMouse (e);
  45267. }
  45268. void paint (Graphics& g)
  45269. {
  45270. if (owner.rootItem != 0)
  45271. {
  45272. owner.handleAsyncUpdate();
  45273. if (! owner.rootItemVisible)
  45274. g.setOrigin (0, -owner.rootItem->itemHeight);
  45275. owner.rootItem->paintRecursively (g, getWidth());
  45276. }
  45277. }
  45278. TreeViewItem* findItemAt (int y, Rectangle<int>& itemPosition) const
  45279. {
  45280. if (owner.rootItem != 0)
  45281. {
  45282. owner.handleAsyncUpdate();
  45283. if (! owner.rootItemVisible)
  45284. y += owner.rootItem->itemHeight;
  45285. TreeViewItem* const ti = owner.rootItem->findItemRecursively (y);
  45286. if (ti != 0)
  45287. itemPosition = ti->getItemPosition (false);
  45288. return ti;
  45289. }
  45290. return 0;
  45291. }
  45292. void updateComponents()
  45293. {
  45294. const int visibleTop = -getY();
  45295. const int visibleBottom = visibleTop + getParentHeight();
  45296. {
  45297. for (int i = items.size(); --i >= 0;)
  45298. items.getUnchecked(i)->shouldKeep = false;
  45299. }
  45300. {
  45301. TreeViewItem* item = owner.rootItem;
  45302. int y = (item != 0 && ! owner.rootItemVisible) ? -item->itemHeight : 0;
  45303. while (item != 0 && y < visibleBottom)
  45304. {
  45305. y += item->itemHeight;
  45306. if (y >= visibleTop)
  45307. {
  45308. RowItem* const ri = findItem (item->uid);
  45309. if (ri != 0)
  45310. {
  45311. ri->shouldKeep = true;
  45312. }
  45313. else
  45314. {
  45315. Component* const comp = item->createItemComponent();
  45316. if (comp != 0)
  45317. {
  45318. items.add (new RowItem (item, comp, item->uid));
  45319. addAndMakeVisible (comp);
  45320. }
  45321. }
  45322. }
  45323. item = item->getNextVisibleItem (true);
  45324. }
  45325. }
  45326. for (int i = items.size(); --i >= 0;)
  45327. {
  45328. RowItem* const ri = items.getUnchecked(i);
  45329. bool keep = false;
  45330. if (isParentOf (ri->component))
  45331. {
  45332. if (ri->shouldKeep)
  45333. {
  45334. Rectangle<int> pos (ri->item->getItemPosition (false));
  45335. pos.setSize (pos.getWidth(), ri->item->itemHeight);
  45336. if (pos.getBottom() >= visibleTop && pos.getY() < visibleBottom)
  45337. {
  45338. keep = true;
  45339. ri->component->setBounds (pos);
  45340. }
  45341. }
  45342. if ((! keep) && isMouseDraggingInChildCompOf (ri->component))
  45343. {
  45344. keep = true;
  45345. ri->component->setSize (0, 0);
  45346. }
  45347. }
  45348. if (! keep)
  45349. items.remove (i);
  45350. }
  45351. }
  45352. void updateButtonUnderMouse (const MouseEvent& e)
  45353. {
  45354. TreeViewItem* newItem = 0;
  45355. if (owner.openCloseButtonsVisible)
  45356. {
  45357. Rectangle<int> pos;
  45358. TreeViewItem* item = findItemAt (e.y, pos);
  45359. if (item != 0 && e.x < pos.getX() && e.x >= pos.getX() - owner.getIndentSize())
  45360. {
  45361. newItem = item;
  45362. if (! newItem->mightContainSubItems())
  45363. newItem = 0;
  45364. }
  45365. }
  45366. if (buttonUnderMouse != newItem)
  45367. {
  45368. if (buttonUnderMouse != 0 && containsItem (buttonUnderMouse))
  45369. {
  45370. const Rectangle<int> r (buttonUnderMouse->getItemPosition (false));
  45371. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  45372. }
  45373. buttonUnderMouse = newItem;
  45374. if (buttonUnderMouse != 0)
  45375. {
  45376. const Rectangle<int> r (buttonUnderMouse->getItemPosition (false));
  45377. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  45378. }
  45379. }
  45380. }
  45381. bool isMouseOverButton (TreeViewItem* const item) const throw()
  45382. {
  45383. return item == buttonUnderMouse;
  45384. }
  45385. void resized()
  45386. {
  45387. owner.itemsChanged();
  45388. }
  45389. const String getTooltip()
  45390. {
  45391. Rectangle<int> pos;
  45392. TreeViewItem* const item = findItemAt (getMouseXYRelative().getY(), pos);
  45393. if (item != 0)
  45394. return item->getTooltip();
  45395. return owner.getTooltip();
  45396. }
  45397. juce_UseDebuggingNewOperator
  45398. private:
  45399. TreeView& owner;
  45400. struct RowItem
  45401. {
  45402. RowItem (TreeViewItem* const item_, Component* const component_, const int itemUID)
  45403. : component (component_), item (item_), uid (itemUID), shouldKeep (true)
  45404. {
  45405. }
  45406. ~RowItem()
  45407. {
  45408. component.deleteAndZero();
  45409. }
  45410. Component::SafePointer<Component> component;
  45411. TreeViewItem* item;
  45412. int uid;
  45413. bool shouldKeep;
  45414. };
  45415. OwnedArray <RowItem> items;
  45416. TreeViewItem* buttonUnderMouse;
  45417. bool isDragging, needSelectionOnMouseUp;
  45418. void selectBasedOnModifiers (TreeViewItem* const item, const ModifierKeys& modifiers)
  45419. {
  45420. TreeViewItem* firstSelected = 0;
  45421. if (modifiers.isShiftDown() && ((firstSelected = owner.getSelectedItem (0)) != 0))
  45422. {
  45423. TreeViewItem* const lastSelected = owner.getSelectedItem (owner.getNumSelectedItems() - 1);
  45424. jassert (lastSelected != 0);
  45425. int rowStart = firstSelected->getRowNumberInTree();
  45426. int rowEnd = lastSelected->getRowNumberInTree();
  45427. if (rowStart > rowEnd)
  45428. swapVariables (rowStart, rowEnd);
  45429. int ourRow = item->getRowNumberInTree();
  45430. int otherEnd = ourRow < rowEnd ? rowStart : rowEnd;
  45431. if (ourRow > otherEnd)
  45432. swapVariables (ourRow, otherEnd);
  45433. for (int i = ourRow; i <= otherEnd; ++i)
  45434. owner.getItemOnRow (i)->setSelected (true, false);
  45435. }
  45436. else
  45437. {
  45438. const bool cmd = modifiers.isCommandDown();
  45439. item->setSelected ((! cmd) || ! item->isSelected(), ! cmd);
  45440. }
  45441. }
  45442. bool containsItem (TreeViewItem* const item) const throw()
  45443. {
  45444. for (int i = items.size(); --i >= 0;)
  45445. if (items.getUnchecked(i)->item == item)
  45446. return true;
  45447. return false;
  45448. }
  45449. RowItem* findItem (const int uid) const throw()
  45450. {
  45451. for (int i = items.size(); --i >= 0;)
  45452. {
  45453. RowItem* const ri = items.getUnchecked(i);
  45454. if (ri->uid == uid)
  45455. return ri;
  45456. }
  45457. return 0;
  45458. }
  45459. static bool isMouseDraggingInChildCompOf (Component* const comp)
  45460. {
  45461. for (int i = Desktop::getInstance().getNumMouseSources(); --i >= 0;)
  45462. {
  45463. MouseInputSource* const source = Desktop::getInstance().getMouseSource(i);
  45464. if (source->isDragging())
  45465. {
  45466. Component* const underMouse = source->getComponentUnderMouse();
  45467. if (underMouse != 0 && (comp == underMouse || comp->isParentOf (underMouse)))
  45468. return true;
  45469. }
  45470. }
  45471. return false;
  45472. }
  45473. TreeViewContentComponent (const TreeViewContentComponent&);
  45474. TreeViewContentComponent& operator= (const TreeViewContentComponent&);
  45475. };
  45476. class TreeView::TreeViewport : public Viewport
  45477. {
  45478. public:
  45479. TreeViewport() throw() : lastX (-1) {}
  45480. ~TreeViewport() throw() {}
  45481. void updateComponents (const bool triggerResize = false)
  45482. {
  45483. TreeViewContentComponent* const tvc = static_cast <TreeViewContentComponent*> (getViewedComponent());
  45484. if (tvc != 0)
  45485. {
  45486. if (triggerResize)
  45487. tvc->resized();
  45488. else
  45489. tvc->updateComponents();
  45490. }
  45491. repaint();
  45492. }
  45493. void visibleAreaChanged (int x, int, int, int)
  45494. {
  45495. const bool hasScrolledSideways = (x != lastX);
  45496. lastX = x;
  45497. updateComponents (hasScrolledSideways);
  45498. }
  45499. juce_UseDebuggingNewOperator
  45500. private:
  45501. int lastX;
  45502. TreeViewport (const TreeViewport&);
  45503. TreeViewport& operator= (const TreeViewport&);
  45504. };
  45505. TreeView::TreeView (const String& componentName)
  45506. : Component (componentName),
  45507. rootItem (0),
  45508. indentSize (24),
  45509. defaultOpenness (false),
  45510. needsRecalculating (true),
  45511. rootItemVisible (true),
  45512. multiSelectEnabled (false),
  45513. openCloseButtonsVisible (true)
  45514. {
  45515. addAndMakeVisible (viewport = new TreeViewport());
  45516. viewport->setViewedComponent (new TreeViewContentComponent (*this));
  45517. viewport->setWantsKeyboardFocus (false);
  45518. setWantsKeyboardFocus (true);
  45519. }
  45520. TreeView::~TreeView()
  45521. {
  45522. if (rootItem != 0)
  45523. rootItem->setOwnerView (0);
  45524. }
  45525. void TreeView::setRootItem (TreeViewItem* const newRootItem)
  45526. {
  45527. if (rootItem != newRootItem)
  45528. {
  45529. if (newRootItem != 0)
  45530. {
  45531. jassert (newRootItem->ownerView == 0); // can't use a tree item in more than one tree at once..
  45532. if (newRootItem->ownerView != 0)
  45533. newRootItem->ownerView->setRootItem (0);
  45534. }
  45535. if (rootItem != 0)
  45536. rootItem->setOwnerView (0);
  45537. rootItem = newRootItem;
  45538. if (newRootItem != 0)
  45539. newRootItem->setOwnerView (this);
  45540. needsRecalculating = true;
  45541. handleAsyncUpdate();
  45542. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  45543. {
  45544. rootItem->setOpen (false); // force a re-open
  45545. rootItem->setOpen (true);
  45546. }
  45547. }
  45548. }
  45549. void TreeView::deleteRootItem()
  45550. {
  45551. const ScopedPointer <TreeViewItem> deleter (rootItem);
  45552. setRootItem (0);
  45553. }
  45554. void TreeView::setRootItemVisible (const bool shouldBeVisible)
  45555. {
  45556. rootItemVisible = shouldBeVisible;
  45557. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  45558. {
  45559. rootItem->setOpen (false); // force a re-open
  45560. rootItem->setOpen (true);
  45561. }
  45562. itemsChanged();
  45563. }
  45564. void TreeView::colourChanged()
  45565. {
  45566. setOpaque (findColour (backgroundColourId).isOpaque());
  45567. repaint();
  45568. }
  45569. void TreeView::setIndentSize (const int newIndentSize)
  45570. {
  45571. if (indentSize != newIndentSize)
  45572. {
  45573. indentSize = newIndentSize;
  45574. resized();
  45575. }
  45576. }
  45577. void TreeView::setDefaultOpenness (const bool isOpenByDefault)
  45578. {
  45579. if (defaultOpenness != isOpenByDefault)
  45580. {
  45581. defaultOpenness = isOpenByDefault;
  45582. itemsChanged();
  45583. }
  45584. }
  45585. void TreeView::setMultiSelectEnabled (const bool canMultiSelect)
  45586. {
  45587. multiSelectEnabled = canMultiSelect;
  45588. }
  45589. void TreeView::setOpenCloseButtonsVisible (const bool shouldBeVisible)
  45590. {
  45591. if (openCloseButtonsVisible != shouldBeVisible)
  45592. {
  45593. openCloseButtonsVisible = shouldBeVisible;
  45594. itemsChanged();
  45595. }
  45596. }
  45597. Viewport* TreeView::getViewport() const throw()
  45598. {
  45599. return viewport;
  45600. }
  45601. void TreeView::clearSelectedItems()
  45602. {
  45603. if (rootItem != 0)
  45604. rootItem->deselectAllRecursively();
  45605. }
  45606. int TreeView::getNumSelectedItems() const throw()
  45607. {
  45608. return (rootItem != 0) ? rootItem->countSelectedItemsRecursively() : 0;
  45609. }
  45610. TreeViewItem* TreeView::getSelectedItem (const int index) const throw()
  45611. {
  45612. return (rootItem != 0) ? rootItem->getSelectedItemWithIndex (index) : 0;
  45613. }
  45614. int TreeView::getNumRowsInTree() const
  45615. {
  45616. if (rootItem != 0)
  45617. return rootItem->getNumRows() - (rootItemVisible ? 0 : 1);
  45618. return 0;
  45619. }
  45620. TreeViewItem* TreeView::getItemOnRow (int index) const
  45621. {
  45622. if (! rootItemVisible)
  45623. ++index;
  45624. if (rootItem != 0 && index >= 0)
  45625. return rootItem->getItemOnRow (index);
  45626. return 0;
  45627. }
  45628. TreeViewItem* TreeView::getItemAt (int y) const throw()
  45629. {
  45630. TreeViewContentComponent* const tc = static_cast <TreeViewContentComponent*> (viewport->getViewedComponent());
  45631. Rectangle<int> pos;
  45632. return tc->findItemAt (relativePositionToOtherComponent (tc, Point<int> (0, y)).getY(), pos);
  45633. }
  45634. TreeViewItem* TreeView::findItemFromIdentifierString (const String& identifierString) const
  45635. {
  45636. if (rootItem == 0)
  45637. return 0;
  45638. return rootItem->findItemFromIdentifierString (identifierString);
  45639. }
  45640. XmlElement* TreeView::getOpennessState (const bool alsoIncludeScrollPosition) const
  45641. {
  45642. XmlElement* e = 0;
  45643. if (rootItem != 0)
  45644. {
  45645. e = rootItem->getOpennessState();
  45646. if (e != 0 && alsoIncludeScrollPosition)
  45647. e->setAttribute ("scrollPos", viewport->getViewPositionY());
  45648. }
  45649. return e;
  45650. }
  45651. void TreeView::restoreOpennessState (const XmlElement& newState)
  45652. {
  45653. if (rootItem != 0)
  45654. {
  45655. rootItem->restoreOpennessState (newState);
  45656. if (newState.hasAttribute ("scrollPos"))
  45657. viewport->setViewPosition (viewport->getViewPositionX(),
  45658. newState.getIntAttribute ("scrollPos"));
  45659. }
  45660. }
  45661. void TreeView::paint (Graphics& g)
  45662. {
  45663. g.fillAll (findColour (backgroundColourId));
  45664. }
  45665. void TreeView::resized()
  45666. {
  45667. viewport->setBounds (getLocalBounds());
  45668. itemsChanged();
  45669. handleAsyncUpdate();
  45670. }
  45671. void TreeView::enablementChanged()
  45672. {
  45673. repaint();
  45674. }
  45675. void TreeView::moveSelectedRow (int delta)
  45676. {
  45677. if (delta == 0)
  45678. return;
  45679. int rowSelected = 0;
  45680. TreeViewItem* const firstSelected = getSelectedItem (0);
  45681. if (firstSelected != 0)
  45682. rowSelected = firstSelected->getRowNumberInTree();
  45683. rowSelected = jlimit (0, getNumRowsInTree() - 1, rowSelected + delta);
  45684. for (;;)
  45685. {
  45686. TreeViewItem* item = getItemOnRow (rowSelected);
  45687. if (item != 0)
  45688. {
  45689. if (! item->canBeSelected())
  45690. {
  45691. // if the row we want to highlight doesn't allow it, try skipping
  45692. // to the next item..
  45693. const int nextRowToTry = jlimit (0, getNumRowsInTree() - 1,
  45694. rowSelected + (delta < 0 ? -1 : 1));
  45695. if (rowSelected != nextRowToTry)
  45696. {
  45697. rowSelected = nextRowToTry;
  45698. continue;
  45699. }
  45700. else
  45701. {
  45702. break;
  45703. }
  45704. }
  45705. item->setSelected (true, true);
  45706. scrollToKeepItemVisible (item);
  45707. }
  45708. break;
  45709. }
  45710. }
  45711. void TreeView::scrollToKeepItemVisible (TreeViewItem* item)
  45712. {
  45713. if (item != 0 && item->ownerView == this)
  45714. {
  45715. handleAsyncUpdate();
  45716. item = item->getDeepestOpenParentItem();
  45717. int y = item->y;
  45718. int viewTop = viewport->getViewPositionY();
  45719. if (y < viewTop)
  45720. {
  45721. viewport->setViewPosition (viewport->getViewPositionX(), y);
  45722. }
  45723. else if (y + item->itemHeight > viewTop + viewport->getViewHeight())
  45724. {
  45725. viewport->setViewPosition (viewport->getViewPositionX(),
  45726. (y + item->itemHeight) - viewport->getViewHeight());
  45727. }
  45728. }
  45729. }
  45730. bool TreeView::keyPressed (const KeyPress& key)
  45731. {
  45732. if (key.isKeyCode (KeyPress::upKey))
  45733. {
  45734. moveSelectedRow (-1);
  45735. }
  45736. else if (key.isKeyCode (KeyPress::downKey))
  45737. {
  45738. moveSelectedRow (1);
  45739. }
  45740. else if (key.isKeyCode (KeyPress::pageDownKey) || key.isKeyCode (KeyPress::pageUpKey))
  45741. {
  45742. if (rootItem != 0)
  45743. {
  45744. int rowsOnScreen = getHeight() / jmax (1, rootItem->itemHeight);
  45745. if (key.isKeyCode (KeyPress::pageUpKey))
  45746. rowsOnScreen = -rowsOnScreen;
  45747. moveSelectedRow (rowsOnScreen);
  45748. }
  45749. }
  45750. else if (key.isKeyCode (KeyPress::homeKey))
  45751. {
  45752. moveSelectedRow (-0x3fffffff);
  45753. }
  45754. else if (key.isKeyCode (KeyPress::endKey))
  45755. {
  45756. moveSelectedRow (0x3fffffff);
  45757. }
  45758. else if (key.isKeyCode (KeyPress::returnKey))
  45759. {
  45760. TreeViewItem* const firstSelected = getSelectedItem (0);
  45761. if (firstSelected != 0)
  45762. firstSelected->setOpen (! firstSelected->isOpen());
  45763. }
  45764. else if (key.isKeyCode (KeyPress::leftKey))
  45765. {
  45766. TreeViewItem* const firstSelected = getSelectedItem (0);
  45767. if (firstSelected != 0)
  45768. {
  45769. if (firstSelected->isOpen())
  45770. {
  45771. firstSelected->setOpen (false);
  45772. }
  45773. else
  45774. {
  45775. TreeViewItem* parent = firstSelected->parentItem;
  45776. if ((! rootItemVisible) && parent == rootItem)
  45777. parent = 0;
  45778. if (parent != 0)
  45779. {
  45780. parent->setSelected (true, true);
  45781. scrollToKeepItemVisible (parent);
  45782. }
  45783. }
  45784. }
  45785. }
  45786. else if (key.isKeyCode (KeyPress::rightKey))
  45787. {
  45788. TreeViewItem* const firstSelected = getSelectedItem (0);
  45789. if (firstSelected != 0)
  45790. {
  45791. if (firstSelected->isOpen() || ! firstSelected->mightContainSubItems())
  45792. moveSelectedRow (1);
  45793. else
  45794. firstSelected->setOpen (true);
  45795. }
  45796. }
  45797. else
  45798. {
  45799. return false;
  45800. }
  45801. return true;
  45802. }
  45803. void TreeView::itemsChanged() throw()
  45804. {
  45805. needsRecalculating = true;
  45806. repaint();
  45807. triggerAsyncUpdate();
  45808. }
  45809. void TreeView::handleAsyncUpdate()
  45810. {
  45811. if (needsRecalculating)
  45812. {
  45813. needsRecalculating = false;
  45814. const ScopedLock sl (nodeAlterationLock);
  45815. if (rootItem != 0)
  45816. rootItem->updatePositions (rootItemVisible ? 0 : -rootItem->itemHeight);
  45817. viewport->updateComponents();
  45818. if (rootItem != 0)
  45819. {
  45820. viewport->getViewedComponent()
  45821. ->setSize (jmax (viewport->getMaximumVisibleWidth(), rootItem->totalWidth),
  45822. rootItem->totalHeight - (rootItemVisible ? 0 : rootItem->itemHeight));
  45823. }
  45824. else
  45825. {
  45826. viewport->getViewedComponent()->setSize (0, 0);
  45827. }
  45828. }
  45829. }
  45830. class TreeView::InsertPointHighlight : public Component
  45831. {
  45832. public:
  45833. InsertPointHighlight()
  45834. : lastItem (0)
  45835. {
  45836. setSize (100, 12);
  45837. setAlwaysOnTop (true);
  45838. setInterceptsMouseClicks (false, false);
  45839. }
  45840. void setTargetPosition (TreeViewItem* const item, int insertIndex, const int x, const int y, const int width) throw()
  45841. {
  45842. lastItem = item;
  45843. lastIndex = insertIndex;
  45844. const int offset = getHeight() / 2;
  45845. setBounds (x - offset, y - offset, width - (x - offset), getHeight());
  45846. }
  45847. void paint (Graphics& g)
  45848. {
  45849. Path p;
  45850. const float h = (float) getHeight();
  45851. p.addEllipse (2.0f, 2.0f, h - 4.0f, h - 4.0f);
  45852. p.startNewSubPath (h - 2.0f, h / 2.0f);
  45853. p.lineTo ((float) getWidth(), h / 2.0f);
  45854. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  45855. g.strokePath (p, PathStrokeType (2.0f));
  45856. }
  45857. TreeViewItem* lastItem;
  45858. int lastIndex;
  45859. private:
  45860. InsertPointHighlight (const InsertPointHighlight&);
  45861. InsertPointHighlight& operator= (const InsertPointHighlight&);
  45862. };
  45863. class TreeView::TargetGroupHighlight : public Component
  45864. {
  45865. public:
  45866. TargetGroupHighlight()
  45867. {
  45868. setAlwaysOnTop (true);
  45869. setInterceptsMouseClicks (false, false);
  45870. }
  45871. void setTargetPosition (TreeViewItem* const item) throw()
  45872. {
  45873. Rectangle<int> r (item->getItemPosition (true));
  45874. r.setHeight (item->getItemHeight());
  45875. setBounds (r);
  45876. }
  45877. void paint (Graphics& g)
  45878. {
  45879. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  45880. g.drawRoundedRectangle (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 3.0f, 2.0f);
  45881. }
  45882. private:
  45883. TargetGroupHighlight (const TargetGroupHighlight&);
  45884. TargetGroupHighlight& operator= (const TargetGroupHighlight&);
  45885. };
  45886. void TreeView::showDragHighlight (TreeViewItem* item, int insertIndex, int x, int y) throw()
  45887. {
  45888. beginDragAutoRepeat (100);
  45889. if (dragInsertPointHighlight == 0)
  45890. {
  45891. addAndMakeVisible (dragInsertPointHighlight = new InsertPointHighlight());
  45892. addAndMakeVisible (dragTargetGroupHighlight = new TargetGroupHighlight());
  45893. }
  45894. dragInsertPointHighlight->setTargetPosition (item, insertIndex, x, y, viewport->getViewWidth());
  45895. dragTargetGroupHighlight->setTargetPosition (item);
  45896. }
  45897. void TreeView::hideDragHighlight() throw()
  45898. {
  45899. dragInsertPointHighlight = 0;
  45900. dragTargetGroupHighlight = 0;
  45901. }
  45902. TreeViewItem* TreeView::getInsertPosition (int& x, int& y, int& insertIndex,
  45903. const StringArray& files, const String& sourceDescription,
  45904. Component* sourceComponent) const throw()
  45905. {
  45906. insertIndex = 0;
  45907. TreeViewItem* item = getItemAt (y);
  45908. if (item == 0)
  45909. return 0;
  45910. Rectangle<int> itemPos (item->getItemPosition (true));
  45911. insertIndex = item->getIndexInParent();
  45912. const int oldY = y;
  45913. y = itemPos.getY();
  45914. if (item->getNumSubItems() == 0 || ! item->isOpen())
  45915. {
  45916. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  45917. : item->isInterestedInDragSource (sourceDescription, sourceComponent))
  45918. {
  45919. // Check if we're trying to drag into an empty group item..
  45920. if (oldY > itemPos.getY() + itemPos.getHeight() / 4
  45921. && oldY < itemPos.getBottom() - itemPos.getHeight() / 4)
  45922. {
  45923. insertIndex = 0;
  45924. x = itemPos.getX() + getIndentSize();
  45925. y = itemPos.getBottom();
  45926. return item;
  45927. }
  45928. }
  45929. }
  45930. if (oldY > itemPos.getCentreY())
  45931. {
  45932. y += item->getItemHeight();
  45933. while (item->isLastOfSiblings() && item->parentItem != 0
  45934. && item->parentItem->parentItem != 0)
  45935. {
  45936. if (x > itemPos.getX())
  45937. break;
  45938. item = item->parentItem;
  45939. itemPos = item->getItemPosition (true);
  45940. insertIndex = item->getIndexInParent();
  45941. }
  45942. ++insertIndex;
  45943. }
  45944. x = itemPos.getX();
  45945. return item->parentItem;
  45946. }
  45947. void TreeView::handleDrag (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y)
  45948. {
  45949. const bool scrolled = viewport->autoScroll (x, y, 20, 10);
  45950. int insertIndex;
  45951. TreeViewItem* const item = getInsertPosition (x, y, insertIndex, files, sourceDescription, sourceComponent);
  45952. if (item != 0)
  45953. {
  45954. if (scrolled || dragInsertPointHighlight == 0
  45955. || dragInsertPointHighlight->lastItem != item
  45956. || dragInsertPointHighlight->lastIndex != insertIndex)
  45957. {
  45958. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  45959. : item->isInterestedInDragSource (sourceDescription, sourceComponent))
  45960. showDragHighlight (item, insertIndex, x, y);
  45961. else
  45962. hideDragHighlight();
  45963. }
  45964. }
  45965. else
  45966. {
  45967. hideDragHighlight();
  45968. }
  45969. }
  45970. void TreeView::handleDrop (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y)
  45971. {
  45972. hideDragHighlight();
  45973. int insertIndex;
  45974. TreeViewItem* const item = getInsertPosition (x, y, insertIndex, files, sourceDescription, sourceComponent);
  45975. if (item != 0)
  45976. {
  45977. if (files.size() > 0)
  45978. {
  45979. if (item->isInterestedInFileDrag (files))
  45980. item->filesDropped (files, insertIndex);
  45981. }
  45982. else
  45983. {
  45984. if (item->isInterestedInDragSource (sourceDescription, sourceComponent))
  45985. item->itemDropped (sourceDescription, sourceComponent, insertIndex);
  45986. }
  45987. }
  45988. }
  45989. bool TreeView::isInterestedInFileDrag (const StringArray&)
  45990. {
  45991. return true;
  45992. }
  45993. void TreeView::fileDragEnter (const StringArray& files, int x, int y)
  45994. {
  45995. fileDragMove (files, x, y);
  45996. }
  45997. void TreeView::fileDragMove (const StringArray& files, int x, int y)
  45998. {
  45999. handleDrag (files, String::empty, 0, x, y);
  46000. }
  46001. void TreeView::fileDragExit (const StringArray&)
  46002. {
  46003. hideDragHighlight();
  46004. }
  46005. void TreeView::filesDropped (const StringArray& files, int x, int y)
  46006. {
  46007. handleDrop (files, String::empty, 0, x, y);
  46008. }
  46009. bool TreeView::isInterestedInDragSource (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  46010. {
  46011. return true;
  46012. }
  46013. void TreeView::itemDragEnter (const String& sourceDescription, Component* sourceComponent, int x, int y)
  46014. {
  46015. itemDragMove (sourceDescription, sourceComponent, x, y);
  46016. }
  46017. void TreeView::itemDragMove (const String& sourceDescription, Component* sourceComponent, int x, int y)
  46018. {
  46019. handleDrag (StringArray(), sourceDescription, sourceComponent, x, y);
  46020. }
  46021. void TreeView::itemDragExit (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  46022. {
  46023. hideDragHighlight();
  46024. }
  46025. void TreeView::itemDropped (const String& sourceDescription, Component* sourceComponent, int x, int y)
  46026. {
  46027. handleDrop (StringArray(), sourceDescription, sourceComponent, x, y);
  46028. }
  46029. enum TreeViewOpenness
  46030. {
  46031. opennessDefault = 0,
  46032. opennessClosed = 1,
  46033. opennessOpen = 2
  46034. };
  46035. TreeViewItem::TreeViewItem()
  46036. : ownerView (0),
  46037. parentItem (0),
  46038. y (0),
  46039. itemHeight (0),
  46040. totalHeight (0),
  46041. selected (false),
  46042. redrawNeeded (true),
  46043. drawLinesInside (true),
  46044. drawsInLeftMargin (false),
  46045. openness (opennessDefault)
  46046. {
  46047. static int nextUID = 0;
  46048. uid = nextUID++;
  46049. }
  46050. TreeViewItem::~TreeViewItem()
  46051. {
  46052. }
  46053. const String TreeViewItem::getUniqueName() const
  46054. {
  46055. return String::empty;
  46056. }
  46057. void TreeViewItem::itemOpennessChanged (bool)
  46058. {
  46059. }
  46060. int TreeViewItem::getNumSubItems() const throw()
  46061. {
  46062. return subItems.size();
  46063. }
  46064. TreeViewItem* TreeViewItem::getSubItem (const int index) const throw()
  46065. {
  46066. return subItems [index];
  46067. }
  46068. void TreeViewItem::clearSubItems()
  46069. {
  46070. if (subItems.size() > 0)
  46071. {
  46072. if (ownerView != 0)
  46073. {
  46074. const ScopedLock sl (ownerView->nodeAlterationLock);
  46075. subItems.clear();
  46076. treeHasChanged();
  46077. }
  46078. else
  46079. {
  46080. subItems.clear();
  46081. }
  46082. }
  46083. }
  46084. void TreeViewItem::addSubItem (TreeViewItem* const newItem, const int insertPosition)
  46085. {
  46086. if (newItem != 0)
  46087. {
  46088. newItem->parentItem = this;
  46089. newItem->setOwnerView (ownerView);
  46090. newItem->y = 0;
  46091. newItem->itemHeight = newItem->getItemHeight();
  46092. newItem->totalHeight = 0;
  46093. newItem->itemWidth = newItem->getItemWidth();
  46094. newItem->totalWidth = 0;
  46095. if (ownerView != 0)
  46096. {
  46097. const ScopedLock sl (ownerView->nodeAlterationLock);
  46098. subItems.insert (insertPosition, newItem);
  46099. treeHasChanged();
  46100. if (newItem->isOpen())
  46101. newItem->itemOpennessChanged (true);
  46102. }
  46103. else
  46104. {
  46105. subItems.insert (insertPosition, newItem);
  46106. if (newItem->isOpen())
  46107. newItem->itemOpennessChanged (true);
  46108. }
  46109. }
  46110. }
  46111. void TreeViewItem::removeSubItem (const int index, const bool deleteItem)
  46112. {
  46113. if (ownerView != 0)
  46114. {
  46115. const ScopedLock sl (ownerView->nodeAlterationLock);
  46116. if (((unsigned int) index) < (unsigned int) subItems.size())
  46117. {
  46118. subItems.remove (index, deleteItem);
  46119. treeHasChanged();
  46120. }
  46121. }
  46122. else
  46123. {
  46124. subItems.remove (index, deleteItem);
  46125. }
  46126. }
  46127. bool TreeViewItem::isOpen() const throw()
  46128. {
  46129. if (openness == opennessDefault)
  46130. return ownerView != 0 && ownerView->defaultOpenness;
  46131. else
  46132. return openness == opennessOpen;
  46133. }
  46134. void TreeViewItem::setOpen (const bool shouldBeOpen)
  46135. {
  46136. if (isOpen() != shouldBeOpen)
  46137. {
  46138. openness = shouldBeOpen ? opennessOpen
  46139. : opennessClosed;
  46140. treeHasChanged();
  46141. itemOpennessChanged (isOpen());
  46142. }
  46143. }
  46144. bool TreeViewItem::isSelected() const throw()
  46145. {
  46146. return selected;
  46147. }
  46148. void TreeViewItem::deselectAllRecursively()
  46149. {
  46150. setSelected (false, false);
  46151. for (int i = 0; i < subItems.size(); ++i)
  46152. subItems.getUnchecked(i)->deselectAllRecursively();
  46153. }
  46154. void TreeViewItem::setSelected (const bool shouldBeSelected,
  46155. const bool deselectOtherItemsFirst)
  46156. {
  46157. if (shouldBeSelected && ! canBeSelected())
  46158. return;
  46159. if (deselectOtherItemsFirst)
  46160. getTopLevelItem()->deselectAllRecursively();
  46161. if (shouldBeSelected != selected)
  46162. {
  46163. selected = shouldBeSelected;
  46164. if (ownerView != 0)
  46165. ownerView->repaint();
  46166. itemSelectionChanged (shouldBeSelected);
  46167. }
  46168. }
  46169. void TreeViewItem::paintItem (Graphics&, int, int)
  46170. {
  46171. }
  46172. void TreeViewItem::paintOpenCloseButton (Graphics& g, int width, int height, bool isMouseOver)
  46173. {
  46174. ownerView->getLookAndFeel()
  46175. .drawTreeviewPlusMinusBox (g, 0, 0, width, height, ! isOpen(), isMouseOver);
  46176. }
  46177. void TreeViewItem::itemClicked (const MouseEvent&)
  46178. {
  46179. }
  46180. void TreeViewItem::itemDoubleClicked (const MouseEvent&)
  46181. {
  46182. if (mightContainSubItems())
  46183. setOpen (! isOpen());
  46184. }
  46185. void TreeViewItem::itemSelectionChanged (bool)
  46186. {
  46187. }
  46188. const String TreeViewItem::getTooltip()
  46189. {
  46190. return String::empty;
  46191. }
  46192. const String TreeViewItem::getDragSourceDescription()
  46193. {
  46194. return String::empty;
  46195. }
  46196. bool TreeViewItem::isInterestedInFileDrag (const StringArray&)
  46197. {
  46198. return false;
  46199. }
  46200. void TreeViewItem::filesDropped (const StringArray& /*files*/, int /*insertIndex*/)
  46201. {
  46202. }
  46203. bool TreeViewItem::isInterestedInDragSource (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  46204. {
  46205. return false;
  46206. }
  46207. void TreeViewItem::itemDropped (const String& /*sourceDescription*/, Component* /*sourceComponent*/, int /*insertIndex*/)
  46208. {
  46209. }
  46210. const Rectangle<int> TreeViewItem::getItemPosition (const bool relativeToTreeViewTopLeft) const throw()
  46211. {
  46212. const int indentX = getIndentX();
  46213. int width = itemWidth;
  46214. if (ownerView != 0 && width < 0)
  46215. width = ownerView->viewport->getViewWidth() - indentX;
  46216. Rectangle<int> r (indentX, y, jmax (0, width), totalHeight);
  46217. if (relativeToTreeViewTopLeft)
  46218. r -= ownerView->viewport->getViewPosition();
  46219. return r;
  46220. }
  46221. void TreeViewItem::treeHasChanged() const throw()
  46222. {
  46223. if (ownerView != 0)
  46224. ownerView->itemsChanged();
  46225. }
  46226. void TreeViewItem::repaintItem() const
  46227. {
  46228. if (ownerView != 0 && areAllParentsOpen())
  46229. {
  46230. Rectangle<int> r (getItemPosition (true));
  46231. r.setLeft (0);
  46232. ownerView->viewport->repaint (r);
  46233. }
  46234. }
  46235. bool TreeViewItem::areAllParentsOpen() const throw()
  46236. {
  46237. return parentItem == 0
  46238. || (parentItem->isOpen() && parentItem->areAllParentsOpen());
  46239. }
  46240. void TreeViewItem::updatePositions (int newY)
  46241. {
  46242. y = newY;
  46243. itemHeight = getItemHeight();
  46244. totalHeight = itemHeight;
  46245. itemWidth = getItemWidth();
  46246. totalWidth = jmax (itemWidth, 0) + getIndentX();
  46247. if (isOpen())
  46248. {
  46249. newY += totalHeight;
  46250. for (int i = 0; i < subItems.size(); ++i)
  46251. {
  46252. TreeViewItem* const ti = subItems.getUnchecked(i);
  46253. ti->updatePositions (newY);
  46254. newY += ti->totalHeight;
  46255. totalHeight += ti->totalHeight;
  46256. totalWidth = jmax (totalWidth, ti->totalWidth);
  46257. }
  46258. }
  46259. }
  46260. TreeViewItem* TreeViewItem::getDeepestOpenParentItem() throw()
  46261. {
  46262. TreeViewItem* result = this;
  46263. TreeViewItem* item = this;
  46264. while (item->parentItem != 0)
  46265. {
  46266. item = item->parentItem;
  46267. if (! item->isOpen())
  46268. result = item;
  46269. }
  46270. return result;
  46271. }
  46272. void TreeViewItem::setOwnerView (TreeView* const newOwner) throw()
  46273. {
  46274. ownerView = newOwner;
  46275. for (int i = subItems.size(); --i >= 0;)
  46276. subItems.getUnchecked(i)->setOwnerView (newOwner);
  46277. }
  46278. int TreeViewItem::getIndentX() const throw()
  46279. {
  46280. const int indentWidth = ownerView->getIndentSize();
  46281. int x = ownerView->rootItemVisible ? indentWidth : 0;
  46282. if (! ownerView->openCloseButtonsVisible)
  46283. x -= indentWidth;
  46284. TreeViewItem* p = parentItem;
  46285. while (p != 0)
  46286. {
  46287. x += indentWidth;
  46288. p = p->parentItem;
  46289. }
  46290. return x;
  46291. }
  46292. void TreeViewItem::setDrawsInLeftMargin (bool canDrawInLeftMargin) throw()
  46293. {
  46294. drawsInLeftMargin = canDrawInLeftMargin;
  46295. }
  46296. void TreeViewItem::paintRecursively (Graphics& g, int width)
  46297. {
  46298. jassert (ownerView != 0);
  46299. if (ownerView == 0)
  46300. return;
  46301. const int indent = getIndentX();
  46302. const int itemW = itemWidth < 0 ? width - indent : itemWidth;
  46303. {
  46304. g.saveState();
  46305. g.setOrigin (indent, 0);
  46306. if (g.reduceClipRegion (drawsInLeftMargin ? -indent : 0, 0,
  46307. drawsInLeftMargin ? itemW + indent : itemW, itemHeight))
  46308. paintItem (g, itemW, itemHeight);
  46309. g.restoreState();
  46310. }
  46311. g.setColour (ownerView->findColour (TreeView::linesColourId));
  46312. const float halfH = itemHeight * 0.5f;
  46313. int depth = 0;
  46314. TreeViewItem* p = parentItem;
  46315. while (p != 0)
  46316. {
  46317. ++depth;
  46318. p = p->parentItem;
  46319. }
  46320. if (! ownerView->rootItemVisible)
  46321. --depth;
  46322. const int indentWidth = ownerView->getIndentSize();
  46323. if (depth >= 0 && ownerView->openCloseButtonsVisible)
  46324. {
  46325. float x = (depth + 0.5f) * indentWidth;
  46326. if (depth >= 0)
  46327. {
  46328. if (parentItem != 0 && parentItem->drawLinesInside)
  46329. g.drawLine (x, 0, x, isLastOfSiblings() ? halfH : (float) itemHeight);
  46330. if ((parentItem != 0 && parentItem->drawLinesInside)
  46331. || (parentItem == 0 && drawLinesInside))
  46332. g.drawLine (x, halfH, x + indentWidth / 2, halfH);
  46333. }
  46334. p = parentItem;
  46335. int d = depth;
  46336. while (p != 0 && --d >= 0)
  46337. {
  46338. x -= (float) indentWidth;
  46339. if ((p->parentItem == 0 || p->parentItem->drawLinesInside)
  46340. && ! p->isLastOfSiblings())
  46341. {
  46342. g.drawLine (x, 0, x, (float) itemHeight);
  46343. }
  46344. p = p->parentItem;
  46345. }
  46346. if (mightContainSubItems())
  46347. {
  46348. g.saveState();
  46349. g.setOrigin (depth * indentWidth, 0);
  46350. g.reduceClipRegion (0, 0, indentWidth, itemHeight);
  46351. paintOpenCloseButton (g, indentWidth, itemHeight,
  46352. static_cast <TreeViewContentComponent*> (ownerView->viewport->getViewedComponent())
  46353. ->isMouseOverButton (this));
  46354. g.restoreState();
  46355. }
  46356. }
  46357. if (isOpen())
  46358. {
  46359. const Rectangle<int> clip (g.getClipBounds());
  46360. for (int i = 0; i < subItems.size(); ++i)
  46361. {
  46362. TreeViewItem* const ti = subItems.getUnchecked(i);
  46363. const int relY = ti->y - y;
  46364. if (relY >= clip.getBottom())
  46365. break;
  46366. if (relY + ti->totalHeight >= clip.getY())
  46367. {
  46368. g.saveState();
  46369. g.setOrigin (0, relY);
  46370. if (g.reduceClipRegion (0, 0, width, ti->totalHeight))
  46371. ti->paintRecursively (g, width);
  46372. g.restoreState();
  46373. }
  46374. }
  46375. }
  46376. }
  46377. bool TreeViewItem::isLastOfSiblings() const throw()
  46378. {
  46379. return parentItem == 0
  46380. || parentItem->subItems.getLast() == this;
  46381. }
  46382. int TreeViewItem::getIndexInParent() const throw()
  46383. {
  46384. return parentItem == 0 ? 0
  46385. : parentItem->subItems.indexOf (this);
  46386. }
  46387. TreeViewItem* TreeViewItem::getTopLevelItem() throw()
  46388. {
  46389. return parentItem == 0 ? this
  46390. : parentItem->getTopLevelItem();
  46391. }
  46392. int TreeViewItem::getNumRows() const throw()
  46393. {
  46394. int num = 1;
  46395. if (isOpen())
  46396. {
  46397. for (int i = subItems.size(); --i >= 0;)
  46398. num += subItems.getUnchecked(i)->getNumRows();
  46399. }
  46400. return num;
  46401. }
  46402. TreeViewItem* TreeViewItem::getItemOnRow (int index) throw()
  46403. {
  46404. if (index == 0)
  46405. return this;
  46406. if (index > 0 && isOpen())
  46407. {
  46408. --index;
  46409. for (int i = 0; i < subItems.size(); ++i)
  46410. {
  46411. TreeViewItem* const item = subItems.getUnchecked(i);
  46412. if (index == 0)
  46413. return item;
  46414. const int numRows = item->getNumRows();
  46415. if (numRows > index)
  46416. return item->getItemOnRow (index);
  46417. index -= numRows;
  46418. }
  46419. }
  46420. return 0;
  46421. }
  46422. TreeViewItem* TreeViewItem::findItemRecursively (int targetY) throw()
  46423. {
  46424. if (((unsigned int) targetY) < (unsigned int) totalHeight)
  46425. {
  46426. const int h = itemHeight;
  46427. if (targetY < h)
  46428. return this;
  46429. if (isOpen())
  46430. {
  46431. targetY -= h;
  46432. for (int i = 0; i < subItems.size(); ++i)
  46433. {
  46434. TreeViewItem* const ti = subItems.getUnchecked(i);
  46435. if (targetY < ti->totalHeight)
  46436. return ti->findItemRecursively (targetY);
  46437. targetY -= ti->totalHeight;
  46438. }
  46439. }
  46440. }
  46441. return 0;
  46442. }
  46443. int TreeViewItem::countSelectedItemsRecursively() const throw()
  46444. {
  46445. int total = isSelected() ? 1 : 0;
  46446. for (int i = subItems.size(); --i >= 0;)
  46447. total += subItems.getUnchecked(i)->countSelectedItemsRecursively();
  46448. return total;
  46449. }
  46450. TreeViewItem* TreeViewItem::getSelectedItemWithIndex (int index) throw()
  46451. {
  46452. if (isSelected())
  46453. {
  46454. if (index == 0)
  46455. return this;
  46456. --index;
  46457. }
  46458. if (index >= 0)
  46459. {
  46460. for (int i = 0; i < subItems.size(); ++i)
  46461. {
  46462. TreeViewItem* const item = subItems.getUnchecked(i);
  46463. TreeViewItem* const found = item->getSelectedItemWithIndex (index);
  46464. if (found != 0)
  46465. return found;
  46466. index -= item->countSelectedItemsRecursively();
  46467. }
  46468. }
  46469. return 0;
  46470. }
  46471. int TreeViewItem::getRowNumberInTree() const throw()
  46472. {
  46473. if (parentItem != 0 && ownerView != 0)
  46474. {
  46475. int n = 1 + parentItem->getRowNumberInTree();
  46476. int ourIndex = parentItem->subItems.indexOf (this);
  46477. jassert (ourIndex >= 0);
  46478. while (--ourIndex >= 0)
  46479. n += parentItem->subItems [ourIndex]->getNumRows();
  46480. if (parentItem->parentItem == 0
  46481. && ! ownerView->rootItemVisible)
  46482. --n;
  46483. return n;
  46484. }
  46485. else
  46486. {
  46487. return 0;
  46488. }
  46489. }
  46490. void TreeViewItem::setLinesDrawnForSubItems (const bool drawLines) throw()
  46491. {
  46492. drawLinesInside = drawLines;
  46493. }
  46494. TreeViewItem* TreeViewItem::getNextVisibleItem (const bool recurse) const throw()
  46495. {
  46496. if (recurse && isOpen() && subItems.size() > 0)
  46497. return subItems [0];
  46498. if (parentItem != 0)
  46499. {
  46500. const int nextIndex = parentItem->subItems.indexOf (this) + 1;
  46501. if (nextIndex >= parentItem->subItems.size())
  46502. return parentItem->getNextVisibleItem (false);
  46503. return parentItem->subItems [nextIndex];
  46504. }
  46505. return 0;
  46506. }
  46507. const String TreeViewItem::getItemIdentifierString() const
  46508. {
  46509. String s;
  46510. if (parentItem != 0)
  46511. s = parentItem->getItemIdentifierString();
  46512. return s + "/" + getUniqueName().replaceCharacter ('/', '\\');
  46513. }
  46514. TreeViewItem* TreeViewItem::findItemFromIdentifierString (const String& identifierString)
  46515. {
  46516. const String thisId (getUniqueName());
  46517. if (thisId == identifierString)
  46518. return this;
  46519. if (identifierString.startsWith (thisId + "/"))
  46520. {
  46521. const String remainingPath (identifierString.substring (thisId.length() + 1));
  46522. bool wasOpen = isOpen();
  46523. setOpen (true);
  46524. for (int i = subItems.size(); --i >= 0;)
  46525. {
  46526. TreeViewItem* item = subItems.getUnchecked(i)->findItemFromIdentifierString (remainingPath);
  46527. if (item != 0)
  46528. return item;
  46529. }
  46530. setOpen (wasOpen);
  46531. }
  46532. return 0;
  46533. }
  46534. void TreeViewItem::restoreOpennessState (const XmlElement& e) throw()
  46535. {
  46536. if (e.hasTagName ("CLOSED"))
  46537. {
  46538. setOpen (false);
  46539. }
  46540. else if (e.hasTagName ("OPEN"))
  46541. {
  46542. setOpen (true);
  46543. forEachXmlChildElement (e, n)
  46544. {
  46545. const String id (n->getStringAttribute ("id"));
  46546. for (int i = 0; i < subItems.size(); ++i)
  46547. {
  46548. TreeViewItem* const ti = subItems.getUnchecked(i);
  46549. if (ti->getUniqueName() == id)
  46550. {
  46551. ti->restoreOpennessState (*n);
  46552. break;
  46553. }
  46554. }
  46555. }
  46556. }
  46557. }
  46558. XmlElement* TreeViewItem::getOpennessState() const throw()
  46559. {
  46560. const String name (getUniqueName());
  46561. if (name.isNotEmpty())
  46562. {
  46563. XmlElement* e;
  46564. if (isOpen())
  46565. {
  46566. e = new XmlElement ("OPEN");
  46567. for (int i = 0; i < subItems.size(); ++i)
  46568. e->addChildElement (subItems.getUnchecked(i)->getOpennessState());
  46569. }
  46570. else
  46571. {
  46572. e = new XmlElement ("CLOSED");
  46573. }
  46574. e->setAttribute ("id", name);
  46575. return e;
  46576. }
  46577. else
  46578. {
  46579. // trying to save the openness for an element that has no name - this won't
  46580. // work because it needs the names to identify what to open.
  46581. jassertfalse;
  46582. }
  46583. return 0;
  46584. }
  46585. END_JUCE_NAMESPACE
  46586. /*** End of inlined file: juce_TreeView.cpp ***/
  46587. /*** Start of inlined file: juce_DirectoryContentsDisplayComponent.cpp ***/
  46588. BEGIN_JUCE_NAMESPACE
  46589. DirectoryContentsDisplayComponent::DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow)
  46590. : fileList (listToShow)
  46591. {
  46592. }
  46593. DirectoryContentsDisplayComponent::~DirectoryContentsDisplayComponent()
  46594. {
  46595. }
  46596. FileBrowserListener::~FileBrowserListener()
  46597. {
  46598. }
  46599. void DirectoryContentsDisplayComponent::addListener (FileBrowserListener* const listener)
  46600. {
  46601. listeners.add (listener);
  46602. }
  46603. void DirectoryContentsDisplayComponent::removeListener (FileBrowserListener* const listener)
  46604. {
  46605. listeners.remove (listener);
  46606. }
  46607. void DirectoryContentsDisplayComponent::sendSelectionChangeMessage()
  46608. {
  46609. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  46610. listeners.callChecked (checker, &FileBrowserListener::selectionChanged);
  46611. }
  46612. void DirectoryContentsDisplayComponent::sendMouseClickMessage (const File& file, const MouseEvent& e)
  46613. {
  46614. if (fileList.getDirectory().exists())
  46615. {
  46616. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  46617. listeners.callChecked (checker, &FileBrowserListener::fileClicked, file, e);
  46618. }
  46619. }
  46620. void DirectoryContentsDisplayComponent::sendDoubleClickMessage (const File& file)
  46621. {
  46622. if (fileList.getDirectory().exists())
  46623. {
  46624. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  46625. listeners.callChecked (checker, &FileBrowserListener::fileDoubleClicked, file);
  46626. }
  46627. }
  46628. END_JUCE_NAMESPACE
  46629. /*** End of inlined file: juce_DirectoryContentsDisplayComponent.cpp ***/
  46630. /*** Start of inlined file: juce_DirectoryContentsList.cpp ***/
  46631. BEGIN_JUCE_NAMESPACE
  46632. DirectoryContentsList::DirectoryContentsList (const FileFilter* const fileFilter_,
  46633. TimeSliceThread& thread_)
  46634. : fileFilter (fileFilter_),
  46635. thread (thread_),
  46636. fileTypeFlags (File::ignoreHiddenFiles | File::findFiles),
  46637. fileFindHandle (0),
  46638. shouldStop (true)
  46639. {
  46640. }
  46641. DirectoryContentsList::~DirectoryContentsList()
  46642. {
  46643. clear();
  46644. }
  46645. void DirectoryContentsList::setIgnoresHiddenFiles (const bool shouldIgnoreHiddenFiles)
  46646. {
  46647. setTypeFlags (shouldIgnoreHiddenFiles ? (fileTypeFlags | File::ignoreHiddenFiles)
  46648. : (fileTypeFlags & ~File::ignoreHiddenFiles));
  46649. }
  46650. bool DirectoryContentsList::ignoresHiddenFiles() const
  46651. {
  46652. return (fileTypeFlags & File::ignoreHiddenFiles) != 0;
  46653. }
  46654. const File& DirectoryContentsList::getDirectory() const
  46655. {
  46656. return root;
  46657. }
  46658. void DirectoryContentsList::setDirectory (const File& directory,
  46659. const bool includeDirectories,
  46660. const bool includeFiles)
  46661. {
  46662. jassert (includeDirectories || includeFiles); // you have to speciify at least one of these!
  46663. if (directory != root)
  46664. {
  46665. clear();
  46666. root = directory;
  46667. // (this forces a refresh when setTypeFlags() is called, rather than triggering two refreshes)
  46668. fileTypeFlags &= ~(File::findDirectories | File::findFiles);
  46669. }
  46670. int newFlags = fileTypeFlags;
  46671. if (includeDirectories) newFlags |= File::findDirectories; else newFlags &= ~File::findDirectories;
  46672. if (includeFiles) newFlags |= File::findFiles; else newFlags &= ~File::findFiles;
  46673. setTypeFlags (newFlags);
  46674. }
  46675. void DirectoryContentsList::setTypeFlags (const int newFlags)
  46676. {
  46677. if (fileTypeFlags != newFlags)
  46678. {
  46679. fileTypeFlags = newFlags;
  46680. refresh();
  46681. }
  46682. }
  46683. void DirectoryContentsList::clear()
  46684. {
  46685. shouldStop = true;
  46686. thread.removeTimeSliceClient (this);
  46687. fileFindHandle = 0;
  46688. if (files.size() > 0)
  46689. {
  46690. files.clear();
  46691. changed();
  46692. }
  46693. }
  46694. void DirectoryContentsList::refresh()
  46695. {
  46696. clear();
  46697. if (root.isDirectory())
  46698. {
  46699. fileFindHandle = new DirectoryIterator (root, false, "*", fileTypeFlags);
  46700. shouldStop = false;
  46701. thread.addTimeSliceClient (this);
  46702. }
  46703. }
  46704. int DirectoryContentsList::getNumFiles() const
  46705. {
  46706. return files.size();
  46707. }
  46708. bool DirectoryContentsList::getFileInfo (const int index,
  46709. FileInfo& result) const
  46710. {
  46711. const ScopedLock sl (fileListLock);
  46712. const FileInfo* const info = files [index];
  46713. if (info != 0)
  46714. {
  46715. result = *info;
  46716. return true;
  46717. }
  46718. return false;
  46719. }
  46720. const File DirectoryContentsList::getFile (const int index) const
  46721. {
  46722. const ScopedLock sl (fileListLock);
  46723. const FileInfo* const info = files [index];
  46724. if (info != 0)
  46725. return root.getChildFile (info->filename);
  46726. return File::nonexistent;
  46727. }
  46728. bool DirectoryContentsList::isStillLoading() const
  46729. {
  46730. return fileFindHandle != 0;
  46731. }
  46732. void DirectoryContentsList::changed()
  46733. {
  46734. sendChangeMessage (this);
  46735. }
  46736. bool DirectoryContentsList::useTimeSlice()
  46737. {
  46738. const uint32 startTime = Time::getApproximateMillisecondCounter();
  46739. bool hasChanged = false;
  46740. for (int i = 100; --i >= 0;)
  46741. {
  46742. if (! checkNextFile (hasChanged))
  46743. {
  46744. if (hasChanged)
  46745. changed();
  46746. return false;
  46747. }
  46748. if (shouldStop || (Time::getApproximateMillisecondCounter() > startTime + 150))
  46749. break;
  46750. }
  46751. if (hasChanged)
  46752. changed();
  46753. return true;
  46754. }
  46755. bool DirectoryContentsList::checkNextFile (bool& hasChanged)
  46756. {
  46757. if (fileFindHandle != 0)
  46758. {
  46759. bool fileFoundIsDir, isHidden, isReadOnly;
  46760. int64 fileSize;
  46761. Time modTime, creationTime;
  46762. if (fileFindHandle->next (&fileFoundIsDir, &isHidden, &fileSize,
  46763. &modTime, &creationTime, &isReadOnly))
  46764. {
  46765. if (addFile (fileFindHandle->getFile(), fileFoundIsDir,
  46766. fileSize, modTime, creationTime, isReadOnly))
  46767. {
  46768. hasChanged = true;
  46769. }
  46770. return true;
  46771. }
  46772. else
  46773. {
  46774. fileFindHandle = 0;
  46775. }
  46776. }
  46777. return false;
  46778. }
  46779. int DirectoryContentsList::compareElements (const DirectoryContentsList::FileInfo* const first,
  46780. const DirectoryContentsList::FileInfo* const second)
  46781. {
  46782. #if JUCE_WINDOWS
  46783. if (first->isDirectory != second->isDirectory)
  46784. return first->isDirectory ? -1 : 1;
  46785. #endif
  46786. return first->filename.compareIgnoreCase (second->filename);
  46787. }
  46788. bool DirectoryContentsList::addFile (const File& file,
  46789. const bool isDir,
  46790. const int64 fileSize,
  46791. const Time& modTime,
  46792. const Time& creationTime,
  46793. const bool isReadOnly)
  46794. {
  46795. if (fileFilter == 0
  46796. || ((! isDir) && fileFilter->isFileSuitable (file))
  46797. || (isDir && fileFilter->isDirectorySuitable (file)))
  46798. {
  46799. ScopedPointer <FileInfo> info (new FileInfo());
  46800. info->filename = file.getFileName();
  46801. info->fileSize = fileSize;
  46802. info->modificationTime = modTime;
  46803. info->creationTime = creationTime;
  46804. info->isDirectory = isDir;
  46805. info->isReadOnly = isReadOnly;
  46806. const ScopedLock sl (fileListLock);
  46807. for (int i = files.size(); --i >= 0;)
  46808. if (files.getUnchecked(i)->filename == info->filename)
  46809. return false;
  46810. files.addSorted (*this, info.release());
  46811. return true;
  46812. }
  46813. return false;
  46814. }
  46815. END_JUCE_NAMESPACE
  46816. /*** End of inlined file: juce_DirectoryContentsList.cpp ***/
  46817. /*** Start of inlined file: juce_FileBrowserComponent.cpp ***/
  46818. BEGIN_JUCE_NAMESPACE
  46819. FileBrowserComponent::FileBrowserComponent (int flags_,
  46820. const File& initialFileOrDirectory,
  46821. const FileFilter* fileFilter_,
  46822. FilePreviewComponent* previewComp_)
  46823. : FileFilter (String::empty),
  46824. fileFilter (fileFilter_),
  46825. flags (flags_),
  46826. previewComp (previewComp_),
  46827. currentPathBox ("path"),
  46828. fileLabel ("f", TRANS ("file:")),
  46829. thread ("Juce FileBrowser")
  46830. {
  46831. // You need to specify one or other of the open/save flags..
  46832. jassert ((flags & (saveMode | openMode)) != 0);
  46833. jassert ((flags & (saveMode | openMode)) != (saveMode | openMode));
  46834. // You need to specify at least one of these flags..
  46835. jassert ((flags & (canSelectFiles | canSelectDirectories)) != 0);
  46836. String filename;
  46837. if (initialFileOrDirectory == File::nonexistent)
  46838. {
  46839. currentRoot = File::getCurrentWorkingDirectory();
  46840. }
  46841. else if (initialFileOrDirectory.isDirectory())
  46842. {
  46843. currentRoot = initialFileOrDirectory;
  46844. }
  46845. else
  46846. {
  46847. chosenFiles.add (initialFileOrDirectory);
  46848. currentRoot = initialFileOrDirectory.getParentDirectory();
  46849. filename = initialFileOrDirectory.getFileName();
  46850. }
  46851. fileList = new DirectoryContentsList (this, thread);
  46852. if ((flags & useTreeView) != 0)
  46853. {
  46854. FileTreeComponent* const tree = new FileTreeComponent (*fileList);
  46855. fileListComponent = tree;
  46856. if ((flags & canSelectMultipleItems) != 0)
  46857. tree->setMultiSelectEnabled (true);
  46858. addAndMakeVisible (tree);
  46859. }
  46860. else
  46861. {
  46862. FileListComponent* const list = new FileListComponent (*fileList);
  46863. fileListComponent = list;
  46864. list->setOutlineThickness (1);
  46865. if ((flags & canSelectMultipleItems) != 0)
  46866. list->setMultipleSelectionEnabled (true);
  46867. addAndMakeVisible (list);
  46868. }
  46869. fileListComponent->addListener (this);
  46870. addAndMakeVisible (&currentPathBox);
  46871. currentPathBox.setEditableText (true);
  46872. StringArray rootNames, rootPaths;
  46873. const BigInteger separators (getRoots (rootNames, rootPaths));
  46874. for (int i = 0; i < rootNames.size(); ++i)
  46875. {
  46876. if (separators [i])
  46877. currentPathBox.addSeparator();
  46878. currentPathBox.addItem (rootNames[i], i + 1);
  46879. }
  46880. currentPathBox.addSeparator();
  46881. currentPathBox.addListener (this);
  46882. addAndMakeVisible (&filenameBox);
  46883. filenameBox.setMultiLine (false);
  46884. filenameBox.setSelectAllWhenFocused (true);
  46885. filenameBox.setText (filename, false);
  46886. filenameBox.addListener (this);
  46887. filenameBox.setReadOnly ((flags & (filenameBoxIsReadOnly | canSelectMultipleItems)) != 0);
  46888. addAndMakeVisible (&fileLabel);
  46889. fileLabel.attachToComponent (&filenameBox, true);
  46890. addAndMakeVisible (goUpButton = getLookAndFeel().createFileBrowserGoUpButton());
  46891. goUpButton->addButtonListener (this);
  46892. goUpButton->setTooltip (TRANS ("go up to parent directory"));
  46893. if (previewComp != 0)
  46894. addAndMakeVisible (previewComp);
  46895. setRoot (currentRoot);
  46896. thread.startThread (4);
  46897. }
  46898. FileBrowserComponent::~FileBrowserComponent()
  46899. {
  46900. fileListComponent = 0;
  46901. fileList = 0;
  46902. thread.stopThread (10000);
  46903. }
  46904. void FileBrowserComponent::addListener (FileBrowserListener* const newListener)
  46905. {
  46906. listeners.add (newListener);
  46907. }
  46908. void FileBrowserComponent::removeListener (FileBrowserListener* const listener)
  46909. {
  46910. listeners.remove (listener);
  46911. }
  46912. bool FileBrowserComponent::isSaveMode() const throw()
  46913. {
  46914. return (flags & saveMode) != 0;
  46915. }
  46916. int FileBrowserComponent::getNumSelectedFiles() const throw()
  46917. {
  46918. if (chosenFiles.size() == 0 && currentFileIsValid())
  46919. return 1;
  46920. return chosenFiles.size();
  46921. }
  46922. const File FileBrowserComponent::getSelectedFile (int index) const throw()
  46923. {
  46924. if ((flags & canSelectDirectories) != 0 && filenameBox.getText().isEmpty())
  46925. return currentRoot;
  46926. if (! filenameBox.isReadOnly())
  46927. return currentRoot.getChildFile (filenameBox.getText());
  46928. return chosenFiles[index];
  46929. }
  46930. bool FileBrowserComponent::currentFileIsValid() const
  46931. {
  46932. if (isSaveMode())
  46933. return ! getSelectedFile (0).isDirectory();
  46934. else
  46935. return getSelectedFile (0).exists();
  46936. }
  46937. const File FileBrowserComponent::getHighlightedFile() const throw()
  46938. {
  46939. return fileListComponent->getSelectedFile (0);
  46940. }
  46941. void FileBrowserComponent::deselectAllFiles()
  46942. {
  46943. fileListComponent->deselectAllFiles();
  46944. }
  46945. bool FileBrowserComponent::isFileSuitable (const File& file) const
  46946. {
  46947. return (flags & canSelectFiles) != 0 && (fileFilter == 0 || fileFilter->isFileSuitable (file));
  46948. }
  46949. bool FileBrowserComponent::isDirectorySuitable (const File&) const
  46950. {
  46951. return true;
  46952. }
  46953. bool FileBrowserComponent::isFileOrDirSuitable (const File& f) const
  46954. {
  46955. if (f.isDirectory())
  46956. return (flags & canSelectDirectories) != 0 && (fileFilter == 0 || fileFilter->isDirectorySuitable (f));
  46957. return (flags & canSelectFiles) != 0 && f.exists()
  46958. && (fileFilter == 0 || fileFilter->isFileSuitable (f));
  46959. }
  46960. const File FileBrowserComponent::getRoot() const
  46961. {
  46962. return currentRoot;
  46963. }
  46964. void FileBrowserComponent::setRoot (const File& newRootDirectory)
  46965. {
  46966. if (currentRoot != newRootDirectory)
  46967. {
  46968. fileListComponent->scrollToTop();
  46969. String path (newRootDirectory.getFullPathName());
  46970. if (path.isEmpty())
  46971. path = File::separatorString;
  46972. StringArray rootNames, rootPaths;
  46973. getRoots (rootNames, rootPaths);
  46974. if (! rootPaths.contains (path, true))
  46975. {
  46976. bool alreadyListed = false;
  46977. for (int i = currentPathBox.getNumItems(); --i >= 0;)
  46978. {
  46979. if (currentPathBox.getItemText (i).equalsIgnoreCase (path))
  46980. {
  46981. alreadyListed = true;
  46982. break;
  46983. }
  46984. }
  46985. if (! alreadyListed)
  46986. currentPathBox.addItem (path, currentPathBox.getNumItems() + 2);
  46987. }
  46988. }
  46989. currentRoot = newRootDirectory;
  46990. fileList->setDirectory (currentRoot, true, true);
  46991. String currentRootName (currentRoot.getFullPathName());
  46992. if (currentRootName.isEmpty())
  46993. currentRootName = File::separatorString;
  46994. currentPathBox.setText (currentRootName, true);
  46995. goUpButton->setEnabled (currentRoot.getParentDirectory().isDirectory()
  46996. && currentRoot.getParentDirectory() != currentRoot);
  46997. }
  46998. void FileBrowserComponent::goUp()
  46999. {
  47000. setRoot (getRoot().getParentDirectory());
  47001. }
  47002. void FileBrowserComponent::refresh()
  47003. {
  47004. fileList->refresh();
  47005. }
  47006. const String FileBrowserComponent::getActionVerb() const
  47007. {
  47008. return isSaveMode() ? TRANS("Save") : TRANS("Open");
  47009. }
  47010. FilePreviewComponent* FileBrowserComponent::getPreviewComponent() const throw()
  47011. {
  47012. return previewComp;
  47013. }
  47014. void FileBrowserComponent::resized()
  47015. {
  47016. getLookAndFeel()
  47017. .layoutFileBrowserComponent (*this, fileListComponent, previewComp,
  47018. &currentPathBox, &filenameBox, goUpButton);
  47019. }
  47020. void FileBrowserComponent::sendListenerChangeMessage()
  47021. {
  47022. Component::BailOutChecker checker (this);
  47023. if (previewComp != 0)
  47024. previewComp->selectedFileChanged (getSelectedFile (0));
  47025. // You shouldn't delete the browser when the file gets changed!
  47026. jassert (! checker.shouldBailOut());
  47027. listeners.callChecked (checker, &FileBrowserListener::selectionChanged);
  47028. }
  47029. void FileBrowserComponent::selectionChanged()
  47030. {
  47031. StringArray newFilenames;
  47032. bool resetChosenFiles = true;
  47033. for (int i = 0; i < fileListComponent->getNumSelectedFiles(); ++i)
  47034. {
  47035. const File f (fileListComponent->getSelectedFile (i));
  47036. if (isFileOrDirSuitable (f))
  47037. {
  47038. if (resetChosenFiles)
  47039. {
  47040. chosenFiles.clear();
  47041. resetChosenFiles = false;
  47042. }
  47043. chosenFiles.add (f);
  47044. newFilenames.add (f.getRelativePathFrom (getRoot()));
  47045. }
  47046. }
  47047. if (newFilenames.size() > 0)
  47048. filenameBox.setText (newFilenames.joinIntoString (", "), false);
  47049. sendListenerChangeMessage();
  47050. }
  47051. void FileBrowserComponent::fileClicked (const File& f, const MouseEvent& e)
  47052. {
  47053. Component::BailOutChecker checker (this);
  47054. listeners.callChecked (checker, &FileBrowserListener::fileClicked, f, e);
  47055. }
  47056. void FileBrowserComponent::fileDoubleClicked (const File& f)
  47057. {
  47058. if (f.isDirectory())
  47059. {
  47060. setRoot (f);
  47061. if ((flags & canSelectDirectories) != 0)
  47062. filenameBox.setText (String::empty);
  47063. }
  47064. else
  47065. {
  47066. Component::BailOutChecker checker (this);
  47067. listeners.callChecked (checker, &FileBrowserListener::fileDoubleClicked, f);
  47068. }
  47069. }
  47070. bool FileBrowserComponent::keyPressed (const KeyPress& key)
  47071. {
  47072. (void) key;
  47073. #if JUCE_LINUX || JUCE_WINDOWS
  47074. if (key.getModifiers().isCommandDown()
  47075. && (key.getKeyCode() == 'H' || key.getKeyCode() == 'h'))
  47076. {
  47077. fileList->setIgnoresHiddenFiles (! fileList->ignoresHiddenFiles());
  47078. fileList->refresh();
  47079. return true;
  47080. }
  47081. #endif
  47082. return false;
  47083. }
  47084. void FileBrowserComponent::textEditorTextChanged (TextEditor&)
  47085. {
  47086. sendListenerChangeMessage();
  47087. }
  47088. void FileBrowserComponent::textEditorReturnKeyPressed (TextEditor&)
  47089. {
  47090. if (filenameBox.getText().containsChar (File::separator))
  47091. {
  47092. const File f (currentRoot.getChildFile (filenameBox.getText()));
  47093. if (f.isDirectory())
  47094. {
  47095. setRoot (f);
  47096. chosenFiles.clear();
  47097. filenameBox.setText (String::empty);
  47098. }
  47099. else
  47100. {
  47101. setRoot (f.getParentDirectory());
  47102. chosenFiles.clear();
  47103. chosenFiles.add (f);
  47104. filenameBox.setText (f.getFileName());
  47105. }
  47106. }
  47107. else
  47108. {
  47109. fileDoubleClicked (getSelectedFile (0));
  47110. }
  47111. }
  47112. void FileBrowserComponent::textEditorEscapeKeyPressed (TextEditor&)
  47113. {
  47114. }
  47115. void FileBrowserComponent::textEditorFocusLost (TextEditor&)
  47116. {
  47117. if (! isSaveMode())
  47118. selectionChanged();
  47119. }
  47120. void FileBrowserComponent::buttonClicked (Button*)
  47121. {
  47122. goUp();
  47123. }
  47124. void FileBrowserComponent::comboBoxChanged (ComboBox*)
  47125. {
  47126. const String newText (currentPathBox.getText().trim().unquoted());
  47127. if (newText.isNotEmpty())
  47128. {
  47129. const int index = currentPathBox.getSelectedId() - 1;
  47130. StringArray rootNames, rootPaths;
  47131. getRoots (rootNames, rootPaths);
  47132. if (rootPaths [index].isNotEmpty())
  47133. {
  47134. setRoot (File (rootPaths [index]));
  47135. }
  47136. else
  47137. {
  47138. File f (newText);
  47139. for (;;)
  47140. {
  47141. if (f.isDirectory())
  47142. {
  47143. setRoot (f);
  47144. break;
  47145. }
  47146. if (f.getParentDirectory() == f)
  47147. break;
  47148. f = f.getParentDirectory();
  47149. }
  47150. }
  47151. }
  47152. }
  47153. const BigInteger FileBrowserComponent::getRoots (StringArray& rootNames, StringArray& rootPaths)
  47154. {
  47155. BigInteger separators;
  47156. #if JUCE_WINDOWS
  47157. Array<File> roots;
  47158. File::findFileSystemRoots (roots);
  47159. rootPaths.clear();
  47160. for (int i = 0; i < roots.size(); ++i)
  47161. {
  47162. const File& drive = roots.getReference(i);
  47163. String name (drive.getFullPathName());
  47164. rootPaths.add (name);
  47165. if (drive.isOnHardDisk())
  47166. {
  47167. String volume (drive.getVolumeLabel());
  47168. if (volume.isEmpty())
  47169. volume = TRANS("Hard Drive");
  47170. name << " [" << volume << ']';
  47171. }
  47172. else if (drive.isOnCDRomDrive())
  47173. {
  47174. name << TRANS(" [CD/DVD drive]");
  47175. }
  47176. rootNames.add (name);
  47177. }
  47178. separators.setBit (rootPaths.size());
  47179. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  47180. rootNames.add ("Documents");
  47181. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  47182. rootNames.add ("Desktop");
  47183. #endif
  47184. #if JUCE_MAC
  47185. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  47186. rootNames.add ("Home folder");
  47187. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  47188. rootNames.add ("Documents");
  47189. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  47190. rootNames.add ("Desktop");
  47191. separators.setBit (rootPaths.size());
  47192. Array <File> volumes;
  47193. File vol ("/Volumes");
  47194. vol.findChildFiles (volumes, File::findDirectories, false);
  47195. for (int i = 0; i < volumes.size(); ++i)
  47196. {
  47197. const File& volume = volumes.getReference(i);
  47198. if (volume.isDirectory() && ! volume.getFileName().startsWithChar ('.'))
  47199. {
  47200. rootPaths.add (volume.getFullPathName());
  47201. rootNames.add (volume.getFileName());
  47202. }
  47203. }
  47204. #endif
  47205. #if JUCE_LINUX
  47206. rootPaths.add ("/");
  47207. rootNames.add ("/");
  47208. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  47209. rootNames.add ("Home folder");
  47210. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  47211. rootNames.add ("Desktop");
  47212. #endif
  47213. return separators;
  47214. }
  47215. END_JUCE_NAMESPACE
  47216. /*** End of inlined file: juce_FileBrowserComponent.cpp ***/
  47217. /*** Start of inlined file: juce_FileChooser.cpp ***/
  47218. BEGIN_JUCE_NAMESPACE
  47219. FileChooser::FileChooser (const String& chooserBoxTitle,
  47220. const File& currentFileOrDirectory,
  47221. const String& fileFilters,
  47222. const bool useNativeDialogBox_)
  47223. : title (chooserBoxTitle),
  47224. filters (fileFilters),
  47225. startingFile (currentFileOrDirectory),
  47226. useNativeDialogBox (useNativeDialogBox_)
  47227. {
  47228. #if JUCE_LINUX
  47229. useNativeDialogBox = false;
  47230. #endif
  47231. if (! fileFilters.containsNonWhitespaceChars())
  47232. filters = "*";
  47233. }
  47234. FileChooser::~FileChooser()
  47235. {
  47236. }
  47237. bool FileChooser::browseForFileToOpen (FilePreviewComponent* previewComponent)
  47238. {
  47239. return showDialog (false, true, false, false, false, previewComponent);
  47240. }
  47241. bool FileChooser::browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent)
  47242. {
  47243. return showDialog (false, true, false, false, true, previewComponent);
  47244. }
  47245. bool FileChooser::browseForMultipleFilesOrDirectories (FilePreviewComponent* previewComponent)
  47246. {
  47247. return showDialog (true, true, false, false, true, previewComponent);
  47248. }
  47249. bool FileChooser::browseForFileToSave (const bool warnAboutOverwritingExistingFiles)
  47250. {
  47251. return showDialog (false, true, true, warnAboutOverwritingExistingFiles, false, 0);
  47252. }
  47253. bool FileChooser::browseForDirectory()
  47254. {
  47255. return showDialog (true, false, false, false, false, 0);
  47256. }
  47257. const File FileChooser::getResult() const
  47258. {
  47259. // if you've used a multiple-file select, you should use the getResults() method
  47260. // to retrieve all the files that were chosen.
  47261. jassert (results.size() <= 1);
  47262. return results.getFirst();
  47263. }
  47264. const Array<File>& FileChooser::getResults() const
  47265. {
  47266. return results;
  47267. }
  47268. bool FileChooser::showDialog (const bool selectsDirectories,
  47269. const bool selectsFiles,
  47270. const bool isSave,
  47271. const bool warnAboutOverwritingExistingFiles,
  47272. const bool selectMultipleFiles,
  47273. FilePreviewComponent* const previewComponent)
  47274. {
  47275. Component::SafePointer<Component> previouslyFocused (Component::getCurrentlyFocusedComponent());
  47276. results.clear();
  47277. // the preview component needs to be the right size before you pass it in here..
  47278. jassert (previewComponent == 0 || (previewComponent->getWidth() > 10
  47279. && previewComponent->getHeight() > 10));
  47280. #if JUCE_WINDOWS
  47281. if (useNativeDialogBox && ! (selectsFiles && selectsDirectories))
  47282. #elif JUCE_MAC
  47283. if (useNativeDialogBox && (previewComponent == 0))
  47284. #else
  47285. if (false)
  47286. #endif
  47287. {
  47288. showPlatformDialog (results, title, startingFile, filters,
  47289. selectsDirectories, selectsFiles, isSave,
  47290. warnAboutOverwritingExistingFiles,
  47291. selectMultipleFiles,
  47292. previewComponent);
  47293. }
  47294. else
  47295. {
  47296. WildcardFileFilter wildcard (selectsFiles ? filters : String::empty,
  47297. selectsDirectories ? "*" : String::empty,
  47298. String::empty);
  47299. int flags = isSave ? FileBrowserComponent::saveMode
  47300. : FileBrowserComponent::openMode;
  47301. if (selectsFiles)
  47302. flags |= FileBrowserComponent::canSelectFiles;
  47303. if (selectsDirectories)
  47304. {
  47305. flags |= FileBrowserComponent::canSelectDirectories;
  47306. if (! isSave)
  47307. flags |= FileBrowserComponent::filenameBoxIsReadOnly;
  47308. }
  47309. if (selectMultipleFiles)
  47310. flags |= FileBrowserComponent::canSelectMultipleItems;
  47311. FileBrowserComponent browserComponent (flags, startingFile, &wildcard, previewComponent);
  47312. FileChooserDialogBox box (title, String::empty,
  47313. browserComponent,
  47314. warnAboutOverwritingExistingFiles,
  47315. browserComponent.findColour (AlertWindow::backgroundColourId));
  47316. if (box.show())
  47317. {
  47318. for (int i = 0; i < browserComponent.getNumSelectedFiles(); ++i)
  47319. results.add (browserComponent.getSelectedFile (i));
  47320. }
  47321. }
  47322. if (previouslyFocused != 0)
  47323. previouslyFocused->grabKeyboardFocus();
  47324. return results.size() > 0;
  47325. }
  47326. FilePreviewComponent::FilePreviewComponent()
  47327. {
  47328. }
  47329. FilePreviewComponent::~FilePreviewComponent()
  47330. {
  47331. }
  47332. END_JUCE_NAMESPACE
  47333. /*** End of inlined file: juce_FileChooser.cpp ***/
  47334. /*** Start of inlined file: juce_FileChooserDialogBox.cpp ***/
  47335. BEGIN_JUCE_NAMESPACE
  47336. FileChooserDialogBox::FileChooserDialogBox (const String& name,
  47337. const String& instructions,
  47338. FileBrowserComponent& chooserComponent,
  47339. const bool warnAboutOverwritingExistingFiles_,
  47340. const Colour& backgroundColour)
  47341. : ResizableWindow (name, backgroundColour, true),
  47342. warnAboutOverwritingExistingFiles (warnAboutOverwritingExistingFiles_)
  47343. {
  47344. setContentComponent (content = new ContentComponent (name, instructions, chooserComponent));
  47345. setResizable (true, true);
  47346. setResizeLimits (300, 300, 1200, 1000);
  47347. content->okButton.addButtonListener (this);
  47348. content->cancelButton.addButtonListener (this);
  47349. content->chooserComponent.addListener (this);
  47350. }
  47351. FileChooserDialogBox::~FileChooserDialogBox()
  47352. {
  47353. content->chooserComponent.removeListener (this);
  47354. }
  47355. bool FileChooserDialogBox::show (int w, int h)
  47356. {
  47357. return showAt (-1, -1, w, h);
  47358. }
  47359. bool FileChooserDialogBox::showAt (int x, int y, int w, int h)
  47360. {
  47361. if (w <= 0)
  47362. {
  47363. Component* const previewComp = content->chooserComponent.getPreviewComponent();
  47364. if (previewComp != 0)
  47365. w = 400 + previewComp->getWidth();
  47366. else
  47367. w = 600;
  47368. }
  47369. if (h <= 0)
  47370. h = 500;
  47371. if (x < 0 || y < 0)
  47372. centreWithSize (w, h);
  47373. else
  47374. setBounds (x, y, w, h);
  47375. const bool ok = (runModalLoop() != 0);
  47376. setVisible (false);
  47377. return ok;
  47378. }
  47379. void FileChooserDialogBox::buttonClicked (Button* button)
  47380. {
  47381. if (button == &(content->okButton))
  47382. {
  47383. if (warnAboutOverwritingExistingFiles
  47384. && content->chooserComponent.isSaveMode()
  47385. && content->chooserComponent.getSelectedFile(0).exists())
  47386. {
  47387. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  47388. TRANS("File already exists"),
  47389. TRANS("There's already a file called:")
  47390. + "\n\n" + content->chooserComponent.getSelectedFile(0).getFullPathName()
  47391. + "\n\n" + TRANS("Are you sure you want to overwrite it?"),
  47392. TRANS("overwrite"),
  47393. TRANS("cancel")))
  47394. {
  47395. return;
  47396. }
  47397. }
  47398. exitModalState (1);
  47399. }
  47400. else if (button == &(content->cancelButton))
  47401. {
  47402. closeButtonPressed();
  47403. }
  47404. }
  47405. void FileChooserDialogBox::closeButtonPressed()
  47406. {
  47407. setVisible (false);
  47408. }
  47409. void FileChooserDialogBox::selectionChanged()
  47410. {
  47411. content->okButton.setEnabled (content->chooserComponent.currentFileIsValid());
  47412. }
  47413. void FileChooserDialogBox::fileClicked (const File&, const MouseEvent&)
  47414. {
  47415. }
  47416. void FileChooserDialogBox::fileDoubleClicked (const File&)
  47417. {
  47418. selectionChanged();
  47419. content->okButton.triggerClick();
  47420. }
  47421. FileChooserDialogBox::ContentComponent::ContentComponent (const String& name, const String& instructions_, FileBrowserComponent& chooserComponent_)
  47422. : Component (name), instructions (instructions_),
  47423. chooserComponent (chooserComponent_),
  47424. okButton (chooserComponent_.getActionVerb()),
  47425. cancelButton (TRANS ("Cancel"))
  47426. {
  47427. addAndMakeVisible (&chooserComponent);
  47428. addAndMakeVisible (&okButton);
  47429. okButton.setEnabled (chooserComponent.currentFileIsValid());
  47430. okButton.addShortcut (KeyPress (KeyPress::returnKey, 0, 0));
  47431. addAndMakeVisible (&cancelButton);
  47432. cancelButton.addShortcut (KeyPress (KeyPress::escapeKey, 0, 0));
  47433. setInterceptsMouseClicks (false, true);
  47434. }
  47435. FileChooserDialogBox::ContentComponent::~ContentComponent()
  47436. {
  47437. }
  47438. void FileChooserDialogBox::ContentComponent::paint (Graphics& g)
  47439. {
  47440. g.setColour (getLookAndFeel().findColour (FileChooserDialogBox::titleTextColourId));
  47441. text.draw (g);
  47442. }
  47443. void FileChooserDialogBox::ContentComponent::resized()
  47444. {
  47445. getLookAndFeel().createFileChooserHeaderText (getName(), instructions, text, getWidth());
  47446. const Rectangle<float> bb (text.getBoundingBox (0, text.getNumGlyphs(), false));
  47447. const int y = roundToInt (bb.getBottom()) + 10;
  47448. const int buttonHeight = 26;
  47449. const int buttonY = getHeight() - buttonHeight - 8;
  47450. chooserComponent.setBounds (0, y, getWidth(), buttonY - y - 20);
  47451. okButton.setBounds (proportionOfWidth (0.25f), buttonY,
  47452. proportionOfWidth (0.2f), buttonHeight);
  47453. cancelButton.setBounds (proportionOfWidth (0.55f), buttonY,
  47454. proportionOfWidth (0.2f), buttonHeight);
  47455. }
  47456. END_JUCE_NAMESPACE
  47457. /*** End of inlined file: juce_FileChooserDialogBox.cpp ***/
  47458. /*** Start of inlined file: juce_FileFilter.cpp ***/
  47459. BEGIN_JUCE_NAMESPACE
  47460. FileFilter::FileFilter (const String& filterDescription)
  47461. : description (filterDescription)
  47462. {
  47463. }
  47464. FileFilter::~FileFilter()
  47465. {
  47466. }
  47467. const String& FileFilter::getDescription() const throw()
  47468. {
  47469. return description;
  47470. }
  47471. END_JUCE_NAMESPACE
  47472. /*** End of inlined file: juce_FileFilter.cpp ***/
  47473. /*** Start of inlined file: juce_FileListComponent.cpp ***/
  47474. BEGIN_JUCE_NAMESPACE
  47475. const Image juce_createIconForFile (const File& file);
  47476. FileListComponent::FileListComponent (DirectoryContentsList& listToShow)
  47477. : ListBox (String::empty, 0),
  47478. DirectoryContentsDisplayComponent (listToShow)
  47479. {
  47480. setModel (this);
  47481. fileList.addChangeListener (this);
  47482. }
  47483. FileListComponent::~FileListComponent()
  47484. {
  47485. fileList.removeChangeListener (this);
  47486. }
  47487. int FileListComponent::getNumSelectedFiles() const
  47488. {
  47489. return getNumSelectedRows();
  47490. }
  47491. const File FileListComponent::getSelectedFile (int index) const
  47492. {
  47493. return fileList.getFile (getSelectedRow (index));
  47494. }
  47495. void FileListComponent::deselectAllFiles()
  47496. {
  47497. deselectAllRows();
  47498. }
  47499. void FileListComponent::scrollToTop()
  47500. {
  47501. getVerticalScrollBar()->setCurrentRangeStart (0);
  47502. }
  47503. void FileListComponent::changeListenerCallback (void*)
  47504. {
  47505. updateContent();
  47506. if (lastDirectory != fileList.getDirectory())
  47507. {
  47508. lastDirectory = fileList.getDirectory();
  47509. deselectAllRows();
  47510. }
  47511. }
  47512. class FileListItemComponent : public Component,
  47513. public TimeSliceClient,
  47514. public AsyncUpdater
  47515. {
  47516. public:
  47517. FileListItemComponent (FileListComponent& owner_, TimeSliceThread& thread_)
  47518. : owner (owner_), thread (thread_),
  47519. highlighted (false), index (0), icon (0)
  47520. {
  47521. }
  47522. ~FileListItemComponent()
  47523. {
  47524. thread.removeTimeSliceClient (this);
  47525. clearIcon();
  47526. }
  47527. void paint (Graphics& g)
  47528. {
  47529. getLookAndFeel().drawFileBrowserRow (g, getWidth(), getHeight(),
  47530. file.getFileName(),
  47531. &icon,
  47532. fileSize, modTime,
  47533. isDirectory, highlighted,
  47534. index, owner);
  47535. }
  47536. void mouseDown (const MouseEvent& e)
  47537. {
  47538. owner.selectRowsBasedOnModifierKeys (index, e.mods);
  47539. owner.sendMouseClickMessage (file, e);
  47540. }
  47541. void mouseDoubleClick (const MouseEvent&)
  47542. {
  47543. owner.sendDoubleClickMessage (file);
  47544. }
  47545. void update (const File& root,
  47546. const DirectoryContentsList::FileInfo* const fileInfo,
  47547. const int index_,
  47548. const bool highlighted_)
  47549. {
  47550. thread.removeTimeSliceClient (this);
  47551. if (highlighted_ != highlighted
  47552. || index_ != index)
  47553. {
  47554. index = index_;
  47555. highlighted = highlighted_;
  47556. repaint();
  47557. }
  47558. File newFile;
  47559. String newFileSize;
  47560. String newModTime;
  47561. if (fileInfo != 0)
  47562. {
  47563. newFile = root.getChildFile (fileInfo->filename);
  47564. newFileSize = File::descriptionOfSizeInBytes (fileInfo->fileSize);
  47565. newModTime = fileInfo->modificationTime.formatted ("%d %b '%y %H:%M");
  47566. }
  47567. if (newFile != file
  47568. || fileSize != newFileSize
  47569. || modTime != newModTime)
  47570. {
  47571. file = newFile;
  47572. fileSize = newFileSize;
  47573. modTime = newModTime;
  47574. isDirectory = fileInfo != 0 && fileInfo->isDirectory;
  47575. repaint();
  47576. clearIcon();
  47577. }
  47578. if (file != File::nonexistent && icon.isNull() && ! isDirectory)
  47579. {
  47580. updateIcon (true);
  47581. if (! icon.isValid())
  47582. thread.addTimeSliceClient (this);
  47583. }
  47584. }
  47585. bool useTimeSlice()
  47586. {
  47587. updateIcon (false);
  47588. return false;
  47589. }
  47590. void handleAsyncUpdate()
  47591. {
  47592. repaint();
  47593. }
  47594. juce_UseDebuggingNewOperator
  47595. private:
  47596. FileListComponent& owner;
  47597. TimeSliceThread& thread;
  47598. bool highlighted;
  47599. int index;
  47600. File file;
  47601. String fileSize;
  47602. String modTime;
  47603. Image icon;
  47604. bool isDirectory;
  47605. void clearIcon()
  47606. {
  47607. icon = Image::null;
  47608. }
  47609. void updateIcon (const bool onlyUpdateIfCached)
  47610. {
  47611. if (icon.isNull())
  47612. {
  47613. const int hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
  47614. Image im (ImageCache::getFromHashCode (hashCode));
  47615. if (im.isNull() && ! onlyUpdateIfCached)
  47616. {
  47617. im = juce_createIconForFile (file);
  47618. if (im.isValid())
  47619. ImageCache::addImageToCache (im, hashCode);
  47620. }
  47621. if (im.isValid())
  47622. {
  47623. icon = im;
  47624. triggerAsyncUpdate();
  47625. }
  47626. }
  47627. }
  47628. };
  47629. int FileListComponent::getNumRows()
  47630. {
  47631. return fileList.getNumFiles();
  47632. }
  47633. void FileListComponent::paintListBoxItem (int, Graphics&, int, int, bool)
  47634. {
  47635. }
  47636. Component* FileListComponent::refreshComponentForRow (int row, bool isSelected, Component* existingComponentToUpdate)
  47637. {
  47638. FileListItemComponent* comp = dynamic_cast <FileListItemComponent*> (existingComponentToUpdate);
  47639. if (comp == 0)
  47640. {
  47641. delete existingComponentToUpdate;
  47642. comp = new FileListItemComponent (*this, fileList.getTimeSliceThread());
  47643. }
  47644. DirectoryContentsList::FileInfo fileInfo;
  47645. if (fileList.getFileInfo (row, fileInfo))
  47646. comp->update (fileList.getDirectory(), &fileInfo, row, isSelected);
  47647. else
  47648. comp->update (fileList.getDirectory(), 0, row, isSelected);
  47649. return comp;
  47650. }
  47651. void FileListComponent::selectedRowsChanged (int /*lastRowSelected*/)
  47652. {
  47653. sendSelectionChangeMessage();
  47654. }
  47655. void FileListComponent::deleteKeyPressed (int /*currentSelectedRow*/)
  47656. {
  47657. }
  47658. void FileListComponent::returnKeyPressed (int currentSelectedRow)
  47659. {
  47660. sendDoubleClickMessage (fileList.getFile (currentSelectedRow));
  47661. }
  47662. END_JUCE_NAMESPACE
  47663. /*** End of inlined file: juce_FileListComponent.cpp ***/
  47664. /*** Start of inlined file: juce_FilenameComponent.cpp ***/
  47665. BEGIN_JUCE_NAMESPACE
  47666. FilenameComponent::FilenameComponent (const String& name,
  47667. const File& currentFile,
  47668. const bool canEditFilename,
  47669. const bool isDirectory,
  47670. const bool isForSaving,
  47671. const String& fileBrowserWildcard,
  47672. const String& enforcedSuffix_,
  47673. const String& textWhenNothingSelected)
  47674. : Component (name),
  47675. maxRecentFiles (30),
  47676. isDir (isDirectory),
  47677. isSaving (isForSaving),
  47678. isFileDragOver (false),
  47679. wildcard (fileBrowserWildcard),
  47680. enforcedSuffix (enforcedSuffix_)
  47681. {
  47682. addAndMakeVisible (&filenameBox);
  47683. filenameBox.setEditableText (canEditFilename);
  47684. filenameBox.addListener (this);
  47685. filenameBox.setTextWhenNothingSelected (textWhenNothingSelected);
  47686. filenameBox.setTextWhenNoChoicesAvailable (TRANS("(no recently seleced files)"));
  47687. setBrowseButtonText ("...");
  47688. setCurrentFile (currentFile, true);
  47689. }
  47690. FilenameComponent::~FilenameComponent()
  47691. {
  47692. }
  47693. void FilenameComponent::paintOverChildren (Graphics& g)
  47694. {
  47695. if (isFileDragOver)
  47696. {
  47697. g.setColour (Colours::red.withAlpha (0.2f));
  47698. g.drawRect (0, 0, getWidth(), getHeight(), 3);
  47699. }
  47700. }
  47701. void FilenameComponent::resized()
  47702. {
  47703. getLookAndFeel().layoutFilenameComponent (*this, &filenameBox, browseButton);
  47704. }
  47705. void FilenameComponent::setBrowseButtonText (const String& newBrowseButtonText)
  47706. {
  47707. browseButtonText = newBrowseButtonText;
  47708. lookAndFeelChanged();
  47709. }
  47710. void FilenameComponent::lookAndFeelChanged()
  47711. {
  47712. browseButton = 0;
  47713. addAndMakeVisible (browseButton = getLookAndFeel().createFilenameComponentBrowseButton (browseButtonText));
  47714. browseButton->setConnectedEdges (Button::ConnectedOnLeft);
  47715. resized();
  47716. browseButton->addButtonListener (this);
  47717. }
  47718. void FilenameComponent::setTooltip (const String& newTooltip)
  47719. {
  47720. SettableTooltipClient::setTooltip (newTooltip);
  47721. filenameBox.setTooltip (newTooltip);
  47722. }
  47723. void FilenameComponent::setDefaultBrowseTarget (const File& newDefaultDirectory)
  47724. {
  47725. defaultBrowseFile = newDefaultDirectory;
  47726. }
  47727. void FilenameComponent::buttonClicked (Button*)
  47728. {
  47729. FileChooser fc (TRANS("Choose a new file"),
  47730. getCurrentFile() == File::nonexistent ? defaultBrowseFile
  47731. : getCurrentFile(),
  47732. wildcard);
  47733. if (isDir ? fc.browseForDirectory()
  47734. : (isSaving ? fc.browseForFileToSave (false)
  47735. : fc.browseForFileToOpen()))
  47736. {
  47737. setCurrentFile (fc.getResult(), true);
  47738. }
  47739. }
  47740. void FilenameComponent::comboBoxChanged (ComboBox*)
  47741. {
  47742. setCurrentFile (getCurrentFile(), true);
  47743. }
  47744. bool FilenameComponent::isInterestedInFileDrag (const StringArray&)
  47745. {
  47746. return true;
  47747. }
  47748. void FilenameComponent::filesDropped (const StringArray& filenames, int, int)
  47749. {
  47750. isFileDragOver = false;
  47751. repaint();
  47752. const File f (filenames[0]);
  47753. if (f.exists() && (f.isDirectory() == isDir))
  47754. setCurrentFile (f, true);
  47755. }
  47756. void FilenameComponent::fileDragEnter (const StringArray&, int, int)
  47757. {
  47758. isFileDragOver = true;
  47759. repaint();
  47760. }
  47761. void FilenameComponent::fileDragExit (const StringArray&)
  47762. {
  47763. isFileDragOver = false;
  47764. repaint();
  47765. }
  47766. const File FilenameComponent::getCurrentFile() const
  47767. {
  47768. File f (filenameBox.getText());
  47769. if (enforcedSuffix.isNotEmpty())
  47770. f = f.withFileExtension (enforcedSuffix);
  47771. return f;
  47772. }
  47773. void FilenameComponent::setCurrentFile (File newFile,
  47774. const bool addToRecentlyUsedList,
  47775. const bool sendChangeNotification)
  47776. {
  47777. if (enforcedSuffix.isNotEmpty())
  47778. newFile = newFile.withFileExtension (enforcedSuffix);
  47779. if (newFile.getFullPathName() != lastFilename)
  47780. {
  47781. lastFilename = newFile.getFullPathName();
  47782. if (addToRecentlyUsedList)
  47783. addRecentlyUsedFile (newFile);
  47784. filenameBox.setText (lastFilename, true);
  47785. if (sendChangeNotification)
  47786. triggerAsyncUpdate();
  47787. }
  47788. }
  47789. void FilenameComponent::setFilenameIsEditable (const bool shouldBeEditable)
  47790. {
  47791. filenameBox.setEditableText (shouldBeEditable);
  47792. }
  47793. const StringArray FilenameComponent::getRecentlyUsedFilenames() const
  47794. {
  47795. StringArray names;
  47796. for (int i = 0; i < filenameBox.getNumItems(); ++i)
  47797. names.add (filenameBox.getItemText (i));
  47798. return names;
  47799. }
  47800. void FilenameComponent::setRecentlyUsedFilenames (const StringArray& filenames)
  47801. {
  47802. if (filenames != getRecentlyUsedFilenames())
  47803. {
  47804. filenameBox.clear();
  47805. for (int i = 0; i < jmin (filenames.size(), maxRecentFiles); ++i)
  47806. filenameBox.addItem (filenames[i], i + 1);
  47807. }
  47808. }
  47809. void FilenameComponent::setMaxNumberOfRecentFiles (const int newMaximum)
  47810. {
  47811. maxRecentFiles = jmax (1, newMaximum);
  47812. setRecentlyUsedFilenames (getRecentlyUsedFilenames());
  47813. }
  47814. void FilenameComponent::addRecentlyUsedFile (const File& file)
  47815. {
  47816. StringArray files (getRecentlyUsedFilenames());
  47817. if (file.getFullPathName().isNotEmpty())
  47818. {
  47819. files.removeString (file.getFullPathName(), true);
  47820. files.insert (0, file.getFullPathName());
  47821. setRecentlyUsedFilenames (files);
  47822. }
  47823. }
  47824. void FilenameComponent::addListener (FilenameComponentListener* const listener)
  47825. {
  47826. listeners.add (listener);
  47827. }
  47828. void FilenameComponent::removeListener (FilenameComponentListener* const listener)
  47829. {
  47830. listeners.remove (listener);
  47831. }
  47832. void FilenameComponent::handleAsyncUpdate()
  47833. {
  47834. Component::BailOutChecker checker (this);
  47835. listeners.callChecked (checker, &FilenameComponentListener::filenameComponentChanged, this);
  47836. }
  47837. END_JUCE_NAMESPACE
  47838. /*** End of inlined file: juce_FilenameComponent.cpp ***/
  47839. /*** Start of inlined file: juce_FileSearchPathListComponent.cpp ***/
  47840. BEGIN_JUCE_NAMESPACE
  47841. FileSearchPathListComponent::FileSearchPathListComponent()
  47842. : addButton ("+"),
  47843. removeButton ("-"),
  47844. changeButton (TRANS ("change...")),
  47845. upButton (String::empty, DrawableButton::ImageOnButtonBackground),
  47846. downButton (String::empty, DrawableButton::ImageOnButtonBackground)
  47847. {
  47848. listBox.setModel (this);
  47849. addAndMakeVisible (&listBox);
  47850. listBox.setColour (ListBox::backgroundColourId, Colours::black.withAlpha (0.02f));
  47851. listBox.setColour (ListBox::outlineColourId, Colours::black.withAlpha (0.1f));
  47852. listBox.setOutlineThickness (1);
  47853. addAndMakeVisible (&addButton);
  47854. addButton.addButtonListener (this);
  47855. addButton.setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  47856. addAndMakeVisible (&removeButton);
  47857. removeButton.addButtonListener (this);
  47858. removeButton.setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  47859. addAndMakeVisible (&changeButton);
  47860. changeButton.addButtonListener (this);
  47861. addAndMakeVisible (&upButton);
  47862. upButton.addButtonListener (this);
  47863. {
  47864. Path arrowPath;
  47865. arrowPath.addArrow (Line<float> (50.0f, 100.0f, 50.0f, 0.0f), 40.0f, 100.0f, 50.0f);
  47866. DrawablePath arrowImage;
  47867. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  47868. arrowImage.setPath (arrowPath);
  47869. upButton.setImages (&arrowImage);
  47870. }
  47871. addAndMakeVisible (&downButton);
  47872. downButton.addButtonListener (this);
  47873. {
  47874. Path arrowPath;
  47875. arrowPath.addArrow (Line<float> (50.0f, 0.0f, 50.0f, 100.0f), 40.0f, 100.0f, 50.0f);
  47876. DrawablePath arrowImage;
  47877. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  47878. arrowImage.setPath (arrowPath);
  47879. downButton.setImages (&arrowImage);
  47880. }
  47881. updateButtons();
  47882. }
  47883. FileSearchPathListComponent::~FileSearchPathListComponent()
  47884. {
  47885. }
  47886. void FileSearchPathListComponent::updateButtons()
  47887. {
  47888. const bool anythingSelected = listBox.getNumSelectedRows() > 0;
  47889. removeButton.setEnabled (anythingSelected);
  47890. changeButton.setEnabled (anythingSelected);
  47891. upButton.setEnabled (anythingSelected);
  47892. downButton.setEnabled (anythingSelected);
  47893. }
  47894. void FileSearchPathListComponent::changed()
  47895. {
  47896. listBox.updateContent();
  47897. listBox.repaint();
  47898. updateButtons();
  47899. }
  47900. void FileSearchPathListComponent::setPath (const FileSearchPath& newPath)
  47901. {
  47902. if (newPath.toString() != path.toString())
  47903. {
  47904. path = newPath;
  47905. changed();
  47906. }
  47907. }
  47908. void FileSearchPathListComponent::setDefaultBrowseTarget (const File& newDefaultDirectory)
  47909. {
  47910. defaultBrowseTarget = newDefaultDirectory;
  47911. }
  47912. int FileSearchPathListComponent::getNumRows()
  47913. {
  47914. return path.getNumPaths();
  47915. }
  47916. void FileSearchPathListComponent::paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected)
  47917. {
  47918. if (rowIsSelected)
  47919. g.fillAll (findColour (TextEditor::highlightColourId));
  47920. g.setColour (findColour (ListBox::textColourId));
  47921. Font f (height * 0.7f);
  47922. f.setHorizontalScale (0.9f);
  47923. g.setFont (f);
  47924. g.drawText (path [rowNumber].getFullPathName(),
  47925. 4, 0, width - 6, height,
  47926. Justification::centredLeft, true);
  47927. }
  47928. void FileSearchPathListComponent::deleteKeyPressed (int row)
  47929. {
  47930. if (((unsigned int) row) < (unsigned int) path.getNumPaths())
  47931. {
  47932. path.remove (row);
  47933. changed();
  47934. }
  47935. }
  47936. void FileSearchPathListComponent::returnKeyPressed (int row)
  47937. {
  47938. FileChooser chooser (TRANS("Change folder..."), path [row], "*");
  47939. if (chooser.browseForDirectory())
  47940. {
  47941. path.remove (row);
  47942. path.add (chooser.getResult(), row);
  47943. changed();
  47944. }
  47945. }
  47946. void FileSearchPathListComponent::listBoxItemDoubleClicked (int row, const MouseEvent&)
  47947. {
  47948. returnKeyPressed (row);
  47949. }
  47950. void FileSearchPathListComponent::selectedRowsChanged (int)
  47951. {
  47952. updateButtons();
  47953. }
  47954. void FileSearchPathListComponent::paint (Graphics& g)
  47955. {
  47956. g.fillAll (findColour (backgroundColourId));
  47957. }
  47958. void FileSearchPathListComponent::resized()
  47959. {
  47960. const int buttonH = 22;
  47961. const int buttonY = getHeight() - buttonH - 4;
  47962. listBox.setBounds (2, 2, getWidth() - 4, buttonY - 5);
  47963. addButton.setBounds (2, buttonY, buttonH, buttonH);
  47964. removeButton.setBounds (addButton.getRight(), buttonY, buttonH, buttonH);
  47965. changeButton.changeWidthToFitText (buttonH);
  47966. downButton.setSize (buttonH * 2, buttonH);
  47967. upButton.setSize (buttonH * 2, buttonH);
  47968. downButton.setTopRightPosition (getWidth() - 2, buttonY);
  47969. upButton.setTopRightPosition (downButton.getX() - 4, buttonY);
  47970. changeButton.setTopRightPosition (upButton.getX() - 8, buttonY);
  47971. }
  47972. bool FileSearchPathListComponent::isInterestedInFileDrag (const StringArray&)
  47973. {
  47974. return true;
  47975. }
  47976. void FileSearchPathListComponent::filesDropped (const StringArray& filenames, int, int mouseY)
  47977. {
  47978. for (int i = filenames.size(); --i >= 0;)
  47979. {
  47980. const File f (filenames[i]);
  47981. if (f.isDirectory())
  47982. {
  47983. const int row = listBox.getRowContainingPosition (0, mouseY - listBox.getY());
  47984. path.add (f, row);
  47985. changed();
  47986. }
  47987. }
  47988. }
  47989. void FileSearchPathListComponent::buttonClicked (Button* button)
  47990. {
  47991. const int currentRow = listBox.getSelectedRow();
  47992. if (button == &removeButton)
  47993. {
  47994. deleteKeyPressed (currentRow);
  47995. }
  47996. else if (button == &addButton)
  47997. {
  47998. File start (defaultBrowseTarget);
  47999. if (start == File::nonexistent)
  48000. start = path [0];
  48001. if (start == File::nonexistent)
  48002. start = File::getCurrentWorkingDirectory();
  48003. FileChooser chooser (TRANS("Add a folder..."), start, "*");
  48004. if (chooser.browseForDirectory())
  48005. {
  48006. path.add (chooser.getResult(), currentRow);
  48007. }
  48008. }
  48009. else if (button == &changeButton)
  48010. {
  48011. returnKeyPressed (currentRow);
  48012. }
  48013. else if (button == &upButton)
  48014. {
  48015. if (currentRow > 0 && currentRow < path.getNumPaths())
  48016. {
  48017. const File f (path[currentRow]);
  48018. path.remove (currentRow);
  48019. path.add (f, currentRow - 1);
  48020. listBox.selectRow (currentRow - 1);
  48021. }
  48022. }
  48023. else if (button == &downButton)
  48024. {
  48025. if (currentRow >= 0 && currentRow < path.getNumPaths() - 1)
  48026. {
  48027. const File f (path[currentRow]);
  48028. path.remove (currentRow);
  48029. path.add (f, currentRow + 1);
  48030. listBox.selectRow (currentRow + 1);
  48031. }
  48032. }
  48033. changed();
  48034. }
  48035. END_JUCE_NAMESPACE
  48036. /*** End of inlined file: juce_FileSearchPathListComponent.cpp ***/
  48037. /*** Start of inlined file: juce_FileTreeComponent.cpp ***/
  48038. BEGIN_JUCE_NAMESPACE
  48039. const Image juce_createIconForFile (const File& file);
  48040. class FileListTreeItem : public TreeViewItem,
  48041. public TimeSliceClient,
  48042. public AsyncUpdater,
  48043. public ChangeListener
  48044. {
  48045. public:
  48046. FileListTreeItem (FileTreeComponent& owner_,
  48047. DirectoryContentsList* const parentContentsList_,
  48048. const int indexInContentsList_,
  48049. const File& file_,
  48050. TimeSliceThread& thread_)
  48051. : file (file_),
  48052. owner (owner_),
  48053. parentContentsList (parentContentsList_),
  48054. indexInContentsList (indexInContentsList_),
  48055. subContentsList (0),
  48056. canDeleteSubContentsList (false),
  48057. thread (thread_),
  48058. icon (0)
  48059. {
  48060. DirectoryContentsList::FileInfo fileInfo;
  48061. if (parentContentsList_ != 0
  48062. && parentContentsList_->getFileInfo (indexInContentsList_, fileInfo))
  48063. {
  48064. fileSize = File::descriptionOfSizeInBytes (fileInfo.fileSize);
  48065. modTime = fileInfo.modificationTime.formatted ("%d %b '%y %H:%M");
  48066. isDirectory = fileInfo.isDirectory;
  48067. }
  48068. else
  48069. {
  48070. isDirectory = true;
  48071. }
  48072. }
  48073. ~FileListTreeItem()
  48074. {
  48075. thread.removeTimeSliceClient (this);
  48076. clearSubItems();
  48077. if (canDeleteSubContentsList)
  48078. delete subContentsList;
  48079. }
  48080. bool mightContainSubItems() { return isDirectory; }
  48081. const String getUniqueName() const { return file.getFullPathName(); }
  48082. int getItemHeight() const { return 22; }
  48083. const String getDragSourceDescription() { return owner.getDragAndDropDescription(); }
  48084. void itemOpennessChanged (bool isNowOpen)
  48085. {
  48086. if (isNowOpen)
  48087. {
  48088. clearSubItems();
  48089. isDirectory = file.isDirectory();
  48090. if (isDirectory)
  48091. {
  48092. if (subContentsList == 0)
  48093. {
  48094. jassert (parentContentsList != 0);
  48095. DirectoryContentsList* const l = new DirectoryContentsList (parentContentsList->getFilter(), thread);
  48096. l->setDirectory (file, true, true);
  48097. setSubContentsList (l);
  48098. canDeleteSubContentsList = true;
  48099. }
  48100. changeListenerCallback (0);
  48101. }
  48102. }
  48103. }
  48104. void setSubContentsList (DirectoryContentsList* newList)
  48105. {
  48106. jassert (subContentsList == 0);
  48107. subContentsList = newList;
  48108. newList->addChangeListener (this);
  48109. }
  48110. void changeListenerCallback (void*)
  48111. {
  48112. clearSubItems();
  48113. if (isOpen() && subContentsList != 0)
  48114. {
  48115. for (int i = 0; i < subContentsList->getNumFiles(); ++i)
  48116. {
  48117. FileListTreeItem* const item
  48118. = new FileListTreeItem (owner, subContentsList, i, subContentsList->getFile(i), thread);
  48119. addSubItem (item);
  48120. }
  48121. }
  48122. }
  48123. void paintItem (Graphics& g, int width, int height)
  48124. {
  48125. if (file != File::nonexistent)
  48126. {
  48127. updateIcon (true);
  48128. if (icon.isNull())
  48129. thread.addTimeSliceClient (this);
  48130. }
  48131. owner.getLookAndFeel()
  48132. .drawFileBrowserRow (g, width, height,
  48133. file.getFileName(),
  48134. &icon, fileSize, modTime,
  48135. isDirectory, isSelected(),
  48136. indexInContentsList, owner);
  48137. }
  48138. void itemClicked (const MouseEvent& e)
  48139. {
  48140. owner.sendMouseClickMessage (file, e);
  48141. }
  48142. void itemDoubleClicked (const MouseEvent& e)
  48143. {
  48144. TreeViewItem::itemDoubleClicked (e);
  48145. owner.sendDoubleClickMessage (file);
  48146. }
  48147. void itemSelectionChanged (bool)
  48148. {
  48149. owner.sendSelectionChangeMessage();
  48150. }
  48151. bool useTimeSlice()
  48152. {
  48153. updateIcon (false);
  48154. thread.removeTimeSliceClient (this);
  48155. return false;
  48156. }
  48157. void handleAsyncUpdate()
  48158. {
  48159. owner.repaint();
  48160. }
  48161. const File file;
  48162. juce_UseDebuggingNewOperator
  48163. private:
  48164. FileTreeComponent& owner;
  48165. DirectoryContentsList* parentContentsList;
  48166. int indexInContentsList;
  48167. DirectoryContentsList* subContentsList;
  48168. bool isDirectory, canDeleteSubContentsList;
  48169. TimeSliceThread& thread;
  48170. Image icon;
  48171. String fileSize;
  48172. String modTime;
  48173. void updateIcon (const bool onlyUpdateIfCached)
  48174. {
  48175. if (icon.isNull())
  48176. {
  48177. const int hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
  48178. Image im (ImageCache::getFromHashCode (hashCode));
  48179. if (im.isNull() && ! onlyUpdateIfCached)
  48180. {
  48181. im = juce_createIconForFile (file);
  48182. if (im.isValid())
  48183. ImageCache::addImageToCache (im, hashCode);
  48184. }
  48185. if (im.isValid())
  48186. {
  48187. icon = im;
  48188. triggerAsyncUpdate();
  48189. }
  48190. }
  48191. }
  48192. };
  48193. FileTreeComponent::FileTreeComponent (DirectoryContentsList& listToShow)
  48194. : DirectoryContentsDisplayComponent (listToShow)
  48195. {
  48196. FileListTreeItem* const root
  48197. = new FileListTreeItem (*this, 0, 0, listToShow.getDirectory(),
  48198. listToShow.getTimeSliceThread());
  48199. root->setSubContentsList (&listToShow);
  48200. setRootItemVisible (false);
  48201. setRootItem (root);
  48202. }
  48203. FileTreeComponent::~FileTreeComponent()
  48204. {
  48205. deleteRootItem();
  48206. }
  48207. const File FileTreeComponent::getSelectedFile (const int index) const
  48208. {
  48209. const FileListTreeItem* const item = dynamic_cast <const FileListTreeItem*> (getSelectedItem (index));
  48210. return item != 0 ? item->file
  48211. : File::nonexistent;
  48212. }
  48213. void FileTreeComponent::deselectAllFiles()
  48214. {
  48215. clearSelectedItems();
  48216. }
  48217. void FileTreeComponent::scrollToTop()
  48218. {
  48219. getViewport()->getVerticalScrollBar()->setCurrentRangeStart (0);
  48220. }
  48221. void FileTreeComponent::setDragAndDropDescription (const String& description)
  48222. {
  48223. dragAndDropDescription = description;
  48224. }
  48225. END_JUCE_NAMESPACE
  48226. /*** End of inlined file: juce_FileTreeComponent.cpp ***/
  48227. /*** Start of inlined file: juce_ImagePreviewComponent.cpp ***/
  48228. BEGIN_JUCE_NAMESPACE
  48229. ImagePreviewComponent::ImagePreviewComponent()
  48230. {
  48231. }
  48232. ImagePreviewComponent::~ImagePreviewComponent()
  48233. {
  48234. }
  48235. void ImagePreviewComponent::getThumbSize (int& w, int& h) const
  48236. {
  48237. const int availableW = proportionOfWidth (0.97f);
  48238. const int availableH = getHeight() - 13 * 4;
  48239. const double scale = jmin (1.0,
  48240. availableW / (double) w,
  48241. availableH / (double) h);
  48242. w = roundToInt (scale * w);
  48243. h = roundToInt (scale * h);
  48244. }
  48245. void ImagePreviewComponent::selectedFileChanged (const File& file)
  48246. {
  48247. if (fileToLoad != file)
  48248. {
  48249. fileToLoad = file;
  48250. startTimer (100);
  48251. }
  48252. }
  48253. void ImagePreviewComponent::timerCallback()
  48254. {
  48255. stopTimer();
  48256. currentThumbnail = Image::null;
  48257. currentDetails = String::empty;
  48258. repaint();
  48259. ScopedPointer <FileInputStream> in (fileToLoad.createInputStream());
  48260. if (in != 0)
  48261. {
  48262. ImageFileFormat* const format = ImageFileFormat::findImageFormatForStream (*in);
  48263. if (format != 0)
  48264. {
  48265. currentThumbnail = format->decodeImage (*in);
  48266. if (currentThumbnail.isValid())
  48267. {
  48268. int w = currentThumbnail.getWidth();
  48269. int h = currentThumbnail.getHeight();
  48270. currentDetails
  48271. << fileToLoad.getFileName() << "\n"
  48272. << format->getFormatName() << "\n"
  48273. << w << " x " << h << " pixels\n"
  48274. << File::descriptionOfSizeInBytes (fileToLoad.getSize());
  48275. getThumbSize (w, h);
  48276. currentThumbnail = currentThumbnail.rescaled (w, h);
  48277. }
  48278. }
  48279. }
  48280. }
  48281. void ImagePreviewComponent::paint (Graphics& g)
  48282. {
  48283. if (currentThumbnail.isValid())
  48284. {
  48285. g.setFont (13.0f);
  48286. int w = currentThumbnail.getWidth();
  48287. int h = currentThumbnail.getHeight();
  48288. getThumbSize (w, h);
  48289. const int numLines = 4;
  48290. const int totalH = 13 * numLines + h + 4;
  48291. const int y = (getHeight() - totalH) / 2;
  48292. g.drawImageWithin (currentThumbnail,
  48293. (getWidth() - w) / 2, y, w, h,
  48294. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  48295. false);
  48296. g.drawFittedText (currentDetails,
  48297. 0, y + h + 4, getWidth(), 100,
  48298. Justification::centredTop, numLines);
  48299. }
  48300. }
  48301. END_JUCE_NAMESPACE
  48302. /*** End of inlined file: juce_ImagePreviewComponent.cpp ***/
  48303. /*** Start of inlined file: juce_WildcardFileFilter.cpp ***/
  48304. BEGIN_JUCE_NAMESPACE
  48305. WildcardFileFilter::WildcardFileFilter (const String& fileWildcardPatterns,
  48306. const String& directoryWildcardPatterns,
  48307. const String& description_)
  48308. : FileFilter (description_.isEmpty() ? fileWildcardPatterns
  48309. : (description_ + " (" + fileWildcardPatterns + ")"))
  48310. {
  48311. parse (fileWildcardPatterns, fileWildcards);
  48312. parse (directoryWildcardPatterns, directoryWildcards);
  48313. }
  48314. WildcardFileFilter::~WildcardFileFilter()
  48315. {
  48316. }
  48317. bool WildcardFileFilter::isFileSuitable (const File& file) const
  48318. {
  48319. return match (file, fileWildcards);
  48320. }
  48321. bool WildcardFileFilter::isDirectorySuitable (const File& file) const
  48322. {
  48323. return match (file, directoryWildcards);
  48324. }
  48325. void WildcardFileFilter::parse (const String& pattern, StringArray& result)
  48326. {
  48327. result.addTokens (pattern.toLowerCase(), ";,", "\"'");
  48328. result.trim();
  48329. result.removeEmptyStrings();
  48330. // special case for *.*, because people use it to mean "any file", but it
  48331. // would actually ignore files with no extension.
  48332. for (int i = result.size(); --i >= 0;)
  48333. if (result[i] == "*.*")
  48334. result.set (i, "*");
  48335. }
  48336. bool WildcardFileFilter::match (const File& file, const StringArray& wildcards)
  48337. {
  48338. const String filename (file.getFileName());
  48339. for (int i = wildcards.size(); --i >= 0;)
  48340. if (filename.matchesWildcard (wildcards[i], true))
  48341. return true;
  48342. return false;
  48343. }
  48344. END_JUCE_NAMESPACE
  48345. /*** End of inlined file: juce_WildcardFileFilter.cpp ***/
  48346. /*** Start of inlined file: juce_KeyboardFocusTraverser.cpp ***/
  48347. BEGIN_JUCE_NAMESPACE
  48348. KeyboardFocusTraverser::KeyboardFocusTraverser()
  48349. {
  48350. }
  48351. KeyboardFocusTraverser::~KeyboardFocusTraverser()
  48352. {
  48353. }
  48354. namespace KeyboardFocusHelpers
  48355. {
  48356. // This will sort a set of components, so that they are ordered in terms of
  48357. // left-to-right and then top-to-bottom.
  48358. class ScreenPositionComparator
  48359. {
  48360. public:
  48361. ScreenPositionComparator() {}
  48362. static int compareElements (const Component* const first, const Component* const second)
  48363. {
  48364. int explicitOrder1 = first->getExplicitFocusOrder();
  48365. if (explicitOrder1 <= 0)
  48366. explicitOrder1 = std::numeric_limits<int>::max() / 2;
  48367. int explicitOrder2 = second->getExplicitFocusOrder();
  48368. if (explicitOrder2 <= 0)
  48369. explicitOrder2 = std::numeric_limits<int>::max() / 2;
  48370. if (explicitOrder1 != explicitOrder2)
  48371. return explicitOrder1 - explicitOrder2;
  48372. const int diff = first->getY() - second->getY();
  48373. return (diff == 0) ? first->getX() - second->getX()
  48374. : diff;
  48375. }
  48376. };
  48377. static void findAllFocusableComponents (Component* const parent, Array <Component*>& comps)
  48378. {
  48379. if (parent->getNumChildComponents() > 0)
  48380. {
  48381. Array <Component*> localComps;
  48382. ScreenPositionComparator comparator;
  48383. int i;
  48384. for (i = parent->getNumChildComponents(); --i >= 0;)
  48385. {
  48386. Component* const c = parent->getChildComponent (i);
  48387. if (c->isVisible() && c->isEnabled())
  48388. localComps.addSorted (comparator, c);
  48389. }
  48390. for (i = 0; i < localComps.size(); ++i)
  48391. {
  48392. Component* const c = localComps.getUnchecked (i);
  48393. if (c->getWantsKeyboardFocus())
  48394. comps.add (c);
  48395. if (! c->isFocusContainer())
  48396. findAllFocusableComponents (c, comps);
  48397. }
  48398. }
  48399. }
  48400. }
  48401. namespace KeyboardFocusHelpers
  48402. {
  48403. Component* getIncrementedComponent (Component* const current, const int delta)
  48404. {
  48405. Component* focusContainer = current->getParentComponent();
  48406. if (focusContainer != 0)
  48407. {
  48408. while (focusContainer->getParentComponent() != 0 && ! focusContainer->isFocusContainer())
  48409. focusContainer = focusContainer->getParentComponent();
  48410. if (focusContainer != 0)
  48411. {
  48412. Array <Component*> comps;
  48413. KeyboardFocusHelpers::findAllFocusableComponents (focusContainer, comps);
  48414. if (comps.size() > 0)
  48415. {
  48416. const int index = comps.indexOf (current);
  48417. return comps [(index + comps.size() + delta) % comps.size()];
  48418. }
  48419. }
  48420. }
  48421. return 0;
  48422. }
  48423. }
  48424. Component* KeyboardFocusTraverser::getNextComponent (Component* current)
  48425. {
  48426. return KeyboardFocusHelpers::getIncrementedComponent (current, 1);
  48427. }
  48428. Component* KeyboardFocusTraverser::getPreviousComponent (Component* current)
  48429. {
  48430. return KeyboardFocusHelpers::getIncrementedComponent (current, -1);
  48431. }
  48432. Component* KeyboardFocusTraverser::getDefaultComponent (Component* parentComponent)
  48433. {
  48434. Array <Component*> comps;
  48435. if (parentComponent != 0)
  48436. KeyboardFocusHelpers::findAllFocusableComponents (parentComponent, comps);
  48437. return comps.getFirst();
  48438. }
  48439. END_JUCE_NAMESPACE
  48440. /*** End of inlined file: juce_KeyboardFocusTraverser.cpp ***/
  48441. /*** Start of inlined file: juce_KeyListener.cpp ***/
  48442. BEGIN_JUCE_NAMESPACE
  48443. bool KeyListener::keyStateChanged (const bool, Component*)
  48444. {
  48445. return false;
  48446. }
  48447. END_JUCE_NAMESPACE
  48448. /*** End of inlined file: juce_KeyListener.cpp ***/
  48449. /*** Start of inlined file: juce_KeyMappingEditorComponent.cpp ***/
  48450. BEGIN_JUCE_NAMESPACE
  48451. // N.B. these two includes are put here deliberately to avoid problems with
  48452. // old GCCs failing on long include paths
  48453. class KeyMappingChangeButton : public Button
  48454. {
  48455. public:
  48456. KeyMappingChangeButton (KeyMappingEditorComponent& owner_,
  48457. const CommandID commandID_,
  48458. const String& keyName,
  48459. const int keyNum_)
  48460. : Button (keyName),
  48461. owner (owner_),
  48462. commandID (commandID_),
  48463. keyNum (keyNum_)
  48464. {
  48465. setWantsKeyboardFocus (false);
  48466. setTriggeredOnMouseDown (keyNum >= 0);
  48467. setTooltip (keyNum_ < 0 ? TRANS("adds a new key-mapping")
  48468. : TRANS("click to change this key-mapping"));
  48469. }
  48470. void paintButton (Graphics& g, bool /*isOver*/, bool /*isDown*/)
  48471. {
  48472. getLookAndFeel().drawKeymapChangeButton (g, getWidth(), getHeight(), *this,
  48473. keyNum >= 0 ? getName() : String::empty);
  48474. }
  48475. void clicked()
  48476. {
  48477. if (keyNum >= 0)
  48478. {
  48479. // existing key clicked..
  48480. PopupMenu m;
  48481. m.addItem (1, TRANS("change this key-mapping"));
  48482. m.addSeparator();
  48483. m.addItem (2, TRANS("remove this key-mapping"));
  48484. const int res = m.show();
  48485. if (res == 1)
  48486. {
  48487. owner.assignNewKey (commandID, keyNum);
  48488. }
  48489. else if (res == 2)
  48490. {
  48491. owner.getMappings()->removeKeyPress (commandID, keyNum);
  48492. }
  48493. }
  48494. else
  48495. {
  48496. // + button pressed..
  48497. owner.assignNewKey (commandID, -1);
  48498. }
  48499. }
  48500. void fitToContent (const int h) throw()
  48501. {
  48502. if (keyNum < 0)
  48503. {
  48504. setSize (h, h);
  48505. }
  48506. else
  48507. {
  48508. Font f (h * 0.6f);
  48509. setSize (jlimit (h * 4, h * 8, 6 + f.getStringWidth (getName())), h);
  48510. }
  48511. }
  48512. juce_UseDebuggingNewOperator
  48513. private:
  48514. KeyMappingEditorComponent& owner;
  48515. const CommandID commandID;
  48516. const int keyNum;
  48517. KeyMappingChangeButton (const KeyMappingChangeButton&);
  48518. KeyMappingChangeButton& operator= (const KeyMappingChangeButton&);
  48519. };
  48520. class KeyMappingItemComponent : public Component
  48521. {
  48522. public:
  48523. KeyMappingItemComponent (KeyMappingEditorComponent& owner_, const CommandID commandID_)
  48524. : owner (owner_), commandID (commandID_)
  48525. {
  48526. setInterceptsMouseClicks (false, true);
  48527. const bool isReadOnly = owner.isCommandReadOnly (commandID);
  48528. const Array <KeyPress> keyPresses (owner.getMappings()->getKeyPressesAssignedToCommand (commandID));
  48529. for (int i = 0; i < jmin ((int) maxNumAssignments, keyPresses.size()); ++i)
  48530. {
  48531. KeyMappingChangeButton* const kb
  48532. = new KeyMappingChangeButton (owner, commandID,
  48533. owner.getDescriptionForKeyPress (keyPresses.getReference (i)), i);
  48534. kb->setEnabled (! isReadOnly);
  48535. addAndMakeVisible (kb);
  48536. }
  48537. KeyMappingChangeButton* const kb
  48538. = new KeyMappingChangeButton (owner, commandID, String::empty, -1);
  48539. addChildComponent (kb);
  48540. kb->setVisible (keyPresses.size() < (int) maxNumAssignments && ! isReadOnly);
  48541. }
  48542. ~KeyMappingItemComponent()
  48543. {
  48544. deleteAllChildren();
  48545. }
  48546. void paint (Graphics& g)
  48547. {
  48548. g.setFont (getHeight() * 0.7f);
  48549. g.setColour (findColour (KeyMappingEditorComponent::textColourId));
  48550. g.drawFittedText (owner.getMappings()->getCommandManager()->getNameOfCommand (commandID),
  48551. 4, 0, jmax (40, getChildComponent (0)->getX() - 5), getHeight(),
  48552. Justification::centredLeft, true);
  48553. }
  48554. void resized()
  48555. {
  48556. int x = getWidth() - 4;
  48557. for (int i = getNumChildComponents(); --i >= 0;)
  48558. {
  48559. KeyMappingChangeButton* const kb = dynamic_cast <KeyMappingChangeButton*> (getChildComponent (i));
  48560. kb->fitToContent (getHeight() - 2);
  48561. kb->setTopRightPosition (x, 1);
  48562. x -= kb->getWidth() + 5;
  48563. }
  48564. }
  48565. enum { maxNumAssignments = 3 };
  48566. juce_UseDebuggingNewOperator
  48567. private:
  48568. KeyMappingEditorComponent& owner;
  48569. const CommandID commandID;
  48570. KeyMappingItemComponent (const KeyMappingItemComponent&);
  48571. KeyMappingItemComponent& operator= (const KeyMappingItemComponent&);
  48572. };
  48573. class KeyMappingTreeViewItem : public TreeViewItem
  48574. {
  48575. public:
  48576. KeyMappingTreeViewItem (KeyMappingEditorComponent& owner_, const CommandID commandID_)
  48577. : owner (owner_), commandID (commandID_)
  48578. {
  48579. }
  48580. const String getUniqueName() const { return String ((int) commandID) + "_id"; }
  48581. bool mightContainSubItems() { return false; }
  48582. int getItemHeight() const { return 20; }
  48583. Component* createItemComponent()
  48584. {
  48585. return new KeyMappingItemComponent (owner, commandID);
  48586. }
  48587. juce_UseDebuggingNewOperator
  48588. private:
  48589. KeyMappingEditorComponent& owner;
  48590. const CommandID commandID;
  48591. KeyMappingTreeViewItem (const KeyMappingTreeViewItem&);
  48592. KeyMappingTreeViewItem& operator= (const KeyMappingTreeViewItem&);
  48593. };
  48594. class KeyCategoryTreeViewItem : public TreeViewItem
  48595. {
  48596. public:
  48597. KeyCategoryTreeViewItem (KeyMappingEditorComponent& owner_, const String& name)
  48598. : owner (owner_), categoryName (name)
  48599. {
  48600. }
  48601. const String getUniqueName() const { return categoryName + "_cat"; }
  48602. bool mightContainSubItems() { return true; }
  48603. int getItemHeight() const { return 28; }
  48604. void paintItem (Graphics& g, int width, int height)
  48605. {
  48606. g.setFont (height * 0.6f, Font::bold);
  48607. g.setColour (owner.findColour (KeyMappingEditorComponent::textColourId));
  48608. g.drawText (categoryName,
  48609. 2, 0, width - 2, height,
  48610. Justification::centredLeft, true);
  48611. }
  48612. void itemOpennessChanged (bool isNowOpen)
  48613. {
  48614. if (isNowOpen)
  48615. {
  48616. if (getNumSubItems() == 0)
  48617. {
  48618. Array <CommandID> commands (owner.getMappings()->getCommandManager()->getCommandsInCategory (categoryName));
  48619. for (int i = 0; i < commands.size(); ++i)
  48620. {
  48621. if (owner.shouldCommandBeIncluded (commands[i]))
  48622. addSubItem (new KeyMappingTreeViewItem (owner, commands[i]));
  48623. }
  48624. }
  48625. }
  48626. else
  48627. {
  48628. clearSubItems();
  48629. }
  48630. }
  48631. juce_UseDebuggingNewOperator
  48632. private:
  48633. KeyMappingEditorComponent& owner;
  48634. String categoryName;
  48635. KeyCategoryTreeViewItem (const KeyCategoryTreeViewItem&);
  48636. KeyCategoryTreeViewItem& operator= (const KeyCategoryTreeViewItem&);
  48637. };
  48638. KeyMappingEditorComponent::KeyMappingEditorComponent (KeyPressMappingSet* const mappingManager,
  48639. const bool showResetToDefaultButton)
  48640. : mappings (mappingManager),
  48641. resetButton (TRANS ("reset to defaults"))
  48642. {
  48643. jassert (mappingManager != 0); // can't be null!
  48644. mappingManager->addChangeListener (this);
  48645. setLinesDrawnForSubItems (false);
  48646. if (showResetToDefaultButton)
  48647. {
  48648. addAndMakeVisible (&resetButton);
  48649. resetButton.addButtonListener (this);
  48650. }
  48651. addAndMakeVisible (&tree);
  48652. tree.setColour (TreeView::backgroundColourId, findColour (backgroundColourId));
  48653. tree.setRootItemVisible (false);
  48654. tree.setDefaultOpenness (true);
  48655. tree.setRootItem (this);
  48656. }
  48657. KeyMappingEditorComponent::~KeyMappingEditorComponent()
  48658. {
  48659. mappings->removeChangeListener (this);
  48660. }
  48661. bool KeyMappingEditorComponent::mightContainSubItems()
  48662. {
  48663. return true;
  48664. }
  48665. const String KeyMappingEditorComponent::getUniqueName() const
  48666. {
  48667. return "keys";
  48668. }
  48669. void KeyMappingEditorComponent::setColours (const Colour& mainBackground,
  48670. const Colour& textColour)
  48671. {
  48672. setColour (backgroundColourId, mainBackground);
  48673. setColour (textColourId, textColour);
  48674. tree.setColour (TreeView::backgroundColourId, mainBackground);
  48675. }
  48676. void KeyMappingEditorComponent::parentHierarchyChanged()
  48677. {
  48678. changeListenerCallback (0);
  48679. }
  48680. void KeyMappingEditorComponent::resized()
  48681. {
  48682. int h = getHeight();
  48683. if (resetButton.isVisible())
  48684. {
  48685. const int buttonHeight = 20;
  48686. h -= buttonHeight + 8;
  48687. int x = getWidth() - 8;
  48688. resetButton.changeWidthToFitText (buttonHeight);
  48689. resetButton.setTopRightPosition (x, h + 6);
  48690. }
  48691. tree.setBounds (0, 0, getWidth(), h);
  48692. }
  48693. void KeyMappingEditorComponent::buttonClicked (Button* button)
  48694. {
  48695. if (button == &resetButton)
  48696. {
  48697. if (AlertWindow::showOkCancelBox (AlertWindow::QuestionIcon,
  48698. TRANS("Reset to defaults"),
  48699. TRANS("Are you sure you want to reset all the key-mappings to their default state?"),
  48700. TRANS("Reset")))
  48701. {
  48702. mappings->resetToDefaultMappings();
  48703. }
  48704. }
  48705. }
  48706. void KeyMappingEditorComponent::changeListenerCallback (void*)
  48707. {
  48708. ScopedPointer <XmlElement> oldOpenness (tree.getOpennessState (true));
  48709. clearSubItems();
  48710. const StringArray categories (mappings->getCommandManager()->getCommandCategories());
  48711. for (int i = 0; i < categories.size(); ++i)
  48712. {
  48713. const Array <CommandID> commands (mappings->getCommandManager()->getCommandsInCategory (categories[i]));
  48714. int count = 0;
  48715. for (int j = 0; j < commands.size(); ++j)
  48716. if (shouldCommandBeIncluded (commands[j]))
  48717. ++count;
  48718. if (count > 0)
  48719. addSubItem (new KeyCategoryTreeViewItem (*this, categories[i]));
  48720. }
  48721. if (oldOpenness != 0)
  48722. tree.restoreOpennessState (*oldOpenness);
  48723. }
  48724. class KeyEntryWindow : public AlertWindow
  48725. {
  48726. public:
  48727. KeyEntryWindow (KeyMappingEditorComponent& owner_)
  48728. : AlertWindow (TRANS("New key-mapping"),
  48729. TRANS("Please press a key combination now..."),
  48730. AlertWindow::NoIcon),
  48731. owner (owner_)
  48732. {
  48733. addButton (TRANS("ok"), 1);
  48734. addButton (TRANS("cancel"), 0);
  48735. // (avoid return + escape keys getting processed by the buttons..)
  48736. for (int i = getNumChildComponents(); --i >= 0;)
  48737. getChildComponent (i)->setWantsKeyboardFocus (false);
  48738. setWantsKeyboardFocus (true);
  48739. grabKeyboardFocus();
  48740. }
  48741. ~KeyEntryWindow()
  48742. {
  48743. }
  48744. bool keyPressed (const KeyPress& key)
  48745. {
  48746. lastPress = key;
  48747. String message (TRANS("Key: ") + owner.getDescriptionForKeyPress (key));
  48748. const CommandID previousCommand = owner.getMappings()->findCommandForKeyPress (key);
  48749. if (previousCommand != 0)
  48750. {
  48751. message << "\n\n"
  48752. << TRANS("(Currently assigned to \"")
  48753. << owner.getMappings()->getCommandManager()->getNameOfCommand (previousCommand)
  48754. << "\")";
  48755. }
  48756. setMessage (message);
  48757. return true;
  48758. }
  48759. bool keyStateChanged (bool)
  48760. {
  48761. return true;
  48762. }
  48763. KeyPress lastPress;
  48764. juce_UseDebuggingNewOperator
  48765. private:
  48766. KeyMappingEditorComponent& owner;
  48767. KeyEntryWindow (const KeyEntryWindow&);
  48768. KeyEntryWindow& operator= (const KeyEntryWindow&);
  48769. };
  48770. void KeyMappingEditorComponent::assignNewKey (const CommandID commandID, const int index)
  48771. {
  48772. KeyEntryWindow entryWindow (*this);
  48773. if (entryWindow.runModalLoop() != 0)
  48774. {
  48775. entryWindow.setVisible (false);
  48776. if (entryWindow.lastPress.isValid())
  48777. {
  48778. const CommandID previousCommand = mappings->findCommandForKeyPress (entryWindow.lastPress);
  48779. if (previousCommand != 0)
  48780. {
  48781. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  48782. TRANS("Change key-mapping"),
  48783. TRANS("This key is already assigned to the command \"")
  48784. + mappings->getCommandManager()->getNameOfCommand (previousCommand)
  48785. + TRANS("\"\n\nDo you want to re-assign it to this new command instead?"),
  48786. TRANS("re-assign"),
  48787. TRANS("cancel")))
  48788. {
  48789. return;
  48790. }
  48791. }
  48792. mappings->removeKeyPress (entryWindow.lastPress);
  48793. if (index >= 0)
  48794. mappings->removeKeyPress (commandID, index);
  48795. mappings->addKeyPress (commandID, entryWindow.lastPress, index);
  48796. }
  48797. }
  48798. }
  48799. bool KeyMappingEditorComponent::shouldCommandBeIncluded (const CommandID commandID)
  48800. {
  48801. const ApplicationCommandInfo* const ci = mappings->getCommandManager()->getCommandForID (commandID);
  48802. return (ci != 0) && ((ci->flags & ApplicationCommandInfo::hiddenFromKeyEditor) == 0);
  48803. }
  48804. bool KeyMappingEditorComponent::isCommandReadOnly (const CommandID commandID)
  48805. {
  48806. const ApplicationCommandInfo* const ci = mappings->getCommandManager()->getCommandForID (commandID);
  48807. return (ci != 0) && ((ci->flags & ApplicationCommandInfo::readOnlyInKeyEditor) != 0);
  48808. }
  48809. const String KeyMappingEditorComponent::getDescriptionForKeyPress (const KeyPress& key)
  48810. {
  48811. return key.getTextDescription();
  48812. }
  48813. END_JUCE_NAMESPACE
  48814. /*** End of inlined file: juce_KeyMappingEditorComponent.cpp ***/
  48815. /*** Start of inlined file: juce_KeyPress.cpp ***/
  48816. BEGIN_JUCE_NAMESPACE
  48817. KeyPress::KeyPress() throw()
  48818. : keyCode (0),
  48819. mods (0),
  48820. textCharacter (0)
  48821. {
  48822. }
  48823. KeyPress::KeyPress (const int keyCode_,
  48824. const ModifierKeys& mods_,
  48825. const juce_wchar textCharacter_) throw()
  48826. : keyCode (keyCode_),
  48827. mods (mods_),
  48828. textCharacter (textCharacter_)
  48829. {
  48830. }
  48831. KeyPress::KeyPress (const int keyCode_) throw()
  48832. : keyCode (keyCode_),
  48833. textCharacter (0)
  48834. {
  48835. }
  48836. KeyPress::KeyPress (const KeyPress& other) throw()
  48837. : keyCode (other.keyCode),
  48838. mods (other.mods),
  48839. textCharacter (other.textCharacter)
  48840. {
  48841. }
  48842. KeyPress& KeyPress::operator= (const KeyPress& other) throw()
  48843. {
  48844. keyCode = other.keyCode;
  48845. mods = other.mods;
  48846. textCharacter = other.textCharacter;
  48847. return *this;
  48848. }
  48849. bool KeyPress::operator== (const KeyPress& other) const throw()
  48850. {
  48851. return mods.getRawFlags() == other.mods.getRawFlags()
  48852. && (textCharacter == other.textCharacter
  48853. || textCharacter == 0
  48854. || other.textCharacter == 0)
  48855. && (keyCode == other.keyCode
  48856. || (keyCode < 256
  48857. && other.keyCode < 256
  48858. && CharacterFunctions::toLowerCase ((juce_wchar) keyCode)
  48859. == CharacterFunctions::toLowerCase ((juce_wchar) other.keyCode)));
  48860. }
  48861. bool KeyPress::operator!= (const KeyPress& other) const throw()
  48862. {
  48863. return ! operator== (other);
  48864. }
  48865. bool KeyPress::isCurrentlyDown() const
  48866. {
  48867. return isKeyCurrentlyDown (keyCode)
  48868. && (ModifierKeys::getCurrentModifiers().getRawFlags() & ModifierKeys::allKeyboardModifiers)
  48869. == (mods.getRawFlags() & ModifierKeys::allKeyboardModifiers);
  48870. }
  48871. namespace KeyPressHelpers
  48872. {
  48873. struct KeyNameAndCode
  48874. {
  48875. const char* name;
  48876. int code;
  48877. };
  48878. static const KeyNameAndCode translations[] =
  48879. {
  48880. { "spacebar", KeyPress::spaceKey },
  48881. { "return", KeyPress::returnKey },
  48882. { "escape", KeyPress::escapeKey },
  48883. { "backspace", KeyPress::backspaceKey },
  48884. { "cursor left", KeyPress::leftKey },
  48885. { "cursor right", KeyPress::rightKey },
  48886. { "cursor up", KeyPress::upKey },
  48887. { "cursor down", KeyPress::downKey },
  48888. { "page up", KeyPress::pageUpKey },
  48889. { "page down", KeyPress::pageDownKey },
  48890. { "home", KeyPress::homeKey },
  48891. { "end", KeyPress::endKey },
  48892. { "delete", KeyPress::deleteKey },
  48893. { "insert", KeyPress::insertKey },
  48894. { "tab", KeyPress::tabKey },
  48895. { "play", KeyPress::playKey },
  48896. { "stop", KeyPress::stopKey },
  48897. { "fast forward", KeyPress::fastForwardKey },
  48898. { "rewind", KeyPress::rewindKey }
  48899. };
  48900. static const String numberPadPrefix() { return "numpad "; }
  48901. }
  48902. const KeyPress KeyPress::createFromDescription (const String& desc)
  48903. {
  48904. int modifiers = 0;
  48905. if (desc.containsWholeWordIgnoreCase ("ctrl")
  48906. || desc.containsWholeWordIgnoreCase ("control")
  48907. || desc.containsWholeWordIgnoreCase ("ctl"))
  48908. modifiers |= ModifierKeys::ctrlModifier;
  48909. if (desc.containsWholeWordIgnoreCase ("shift")
  48910. || desc.containsWholeWordIgnoreCase ("shft"))
  48911. modifiers |= ModifierKeys::shiftModifier;
  48912. if (desc.containsWholeWordIgnoreCase ("alt")
  48913. || desc.containsWholeWordIgnoreCase ("option"))
  48914. modifiers |= ModifierKeys::altModifier;
  48915. if (desc.containsWholeWordIgnoreCase ("command")
  48916. || desc.containsWholeWordIgnoreCase ("cmd"))
  48917. modifiers |= ModifierKeys::commandModifier;
  48918. int key = 0;
  48919. for (int i = 0; i < numElementsInArray (KeyPressHelpers::translations); ++i)
  48920. {
  48921. if (desc.containsWholeWordIgnoreCase (String (KeyPressHelpers::translations[i].name)))
  48922. {
  48923. key = KeyPressHelpers::translations[i].code;
  48924. break;
  48925. }
  48926. }
  48927. if (key == 0)
  48928. {
  48929. // see if it's a numpad key..
  48930. if (desc.containsIgnoreCase (KeyPressHelpers::numberPadPrefix()))
  48931. {
  48932. const juce_wchar lastChar = desc.trimEnd().getLastCharacter();
  48933. if (lastChar >= '0' && lastChar <= '9')
  48934. key = numberPad0 + lastChar - '0';
  48935. else if (lastChar == '+')
  48936. key = numberPadAdd;
  48937. else if (lastChar == '-')
  48938. key = numberPadSubtract;
  48939. else if (lastChar == '*')
  48940. key = numberPadMultiply;
  48941. else if (lastChar == '/')
  48942. key = numberPadDivide;
  48943. else if (lastChar == '.')
  48944. key = numberPadDecimalPoint;
  48945. else if (lastChar == '=')
  48946. key = numberPadEquals;
  48947. else if (desc.endsWith ("separator"))
  48948. key = numberPadSeparator;
  48949. else if (desc.endsWith ("delete"))
  48950. key = numberPadDelete;
  48951. }
  48952. if (key == 0)
  48953. {
  48954. // see if it's a function key..
  48955. if (! desc.containsChar ('#')) // avoid mistaking hex-codes like "#f1"
  48956. for (int i = 1; i <= 12; ++i)
  48957. if (desc.containsWholeWordIgnoreCase ("f" + String (i)))
  48958. key = F1Key + i - 1;
  48959. if (key == 0)
  48960. {
  48961. // give up and use the hex code..
  48962. const int hexCode = desc.fromFirstOccurrenceOf ("#", false, false)
  48963. .toLowerCase()
  48964. .retainCharacters ("0123456789abcdef")
  48965. .getHexValue32();
  48966. if (hexCode > 0)
  48967. key = hexCode;
  48968. else
  48969. key = CharacterFunctions::toUpperCase (desc.getLastCharacter());
  48970. }
  48971. }
  48972. }
  48973. return KeyPress (key, ModifierKeys (modifiers), 0);
  48974. }
  48975. const String KeyPress::getTextDescription() const
  48976. {
  48977. String desc;
  48978. if (keyCode > 0)
  48979. {
  48980. // some keyboard layouts use a shift-key to get the slash, but in those cases, we
  48981. // want to store it as being a slash, not shift+whatever.
  48982. if (textCharacter == '/')
  48983. return "/";
  48984. if (mods.isCtrlDown())
  48985. desc << "ctrl + ";
  48986. if (mods.isShiftDown())
  48987. desc << "shift + ";
  48988. #if JUCE_MAC
  48989. // only do this on the mac, because on Windows ctrl and command are the same,
  48990. // and this would get confusing
  48991. if (mods.isCommandDown())
  48992. desc << "command + ";
  48993. if (mods.isAltDown())
  48994. desc << "option + ";
  48995. #else
  48996. if (mods.isAltDown())
  48997. desc << "alt + ";
  48998. #endif
  48999. for (int i = 0; i < numElementsInArray (KeyPressHelpers::translations); ++i)
  49000. if (keyCode == KeyPressHelpers::translations[i].code)
  49001. return desc + KeyPressHelpers::translations[i].name;
  49002. if (keyCode >= F1Key && keyCode <= F16Key)
  49003. desc << 'F' << (1 + keyCode - F1Key);
  49004. else if (keyCode >= numberPad0 && keyCode <= numberPad9)
  49005. desc << KeyPressHelpers::numberPadPrefix() << (keyCode - numberPad0);
  49006. else if (keyCode >= 33 && keyCode < 176)
  49007. desc += CharacterFunctions::toUpperCase ((juce_wchar) keyCode);
  49008. else if (keyCode == numberPadAdd)
  49009. desc << KeyPressHelpers::numberPadPrefix() << '+';
  49010. else if (keyCode == numberPadSubtract)
  49011. desc << KeyPressHelpers::numberPadPrefix() << '-';
  49012. else if (keyCode == numberPadMultiply)
  49013. desc << KeyPressHelpers::numberPadPrefix() << '*';
  49014. else if (keyCode == numberPadDivide)
  49015. desc << KeyPressHelpers::numberPadPrefix() << '/';
  49016. else if (keyCode == numberPadSeparator)
  49017. desc << KeyPressHelpers::numberPadPrefix() << "separator";
  49018. else if (keyCode == numberPadDecimalPoint)
  49019. desc << KeyPressHelpers::numberPadPrefix() << '.';
  49020. else if (keyCode == numberPadDelete)
  49021. desc << KeyPressHelpers::numberPadPrefix() << "delete";
  49022. else
  49023. desc << '#' << String::toHexString (keyCode);
  49024. }
  49025. return desc;
  49026. }
  49027. END_JUCE_NAMESPACE
  49028. /*** End of inlined file: juce_KeyPress.cpp ***/
  49029. /*** Start of inlined file: juce_KeyPressMappingSet.cpp ***/
  49030. BEGIN_JUCE_NAMESPACE
  49031. KeyPressMappingSet::KeyPressMappingSet (ApplicationCommandManager* const commandManager_)
  49032. : commandManager (commandManager_)
  49033. {
  49034. // A manager is needed to get the descriptions of commands, and will be called when
  49035. // a command is invoked. So you can't leave this null..
  49036. jassert (commandManager_ != 0);
  49037. Desktop::getInstance().addFocusChangeListener (this);
  49038. }
  49039. KeyPressMappingSet::KeyPressMappingSet (const KeyPressMappingSet& other)
  49040. : commandManager (other.commandManager)
  49041. {
  49042. Desktop::getInstance().addFocusChangeListener (this);
  49043. }
  49044. KeyPressMappingSet::~KeyPressMappingSet()
  49045. {
  49046. Desktop::getInstance().removeFocusChangeListener (this);
  49047. }
  49048. const Array <KeyPress> KeyPressMappingSet::getKeyPressesAssignedToCommand (const CommandID commandID) const
  49049. {
  49050. for (int i = 0; i < mappings.size(); ++i)
  49051. if (mappings.getUnchecked(i)->commandID == commandID)
  49052. return mappings.getUnchecked (i)->keypresses;
  49053. return Array <KeyPress> ();
  49054. }
  49055. void KeyPressMappingSet::addKeyPress (const CommandID commandID,
  49056. const KeyPress& newKeyPress,
  49057. int insertIndex)
  49058. {
  49059. // If you specify an upper-case letter but no shift key, how is the user supposed to press it!?
  49060. // Stick to lower-case letters when defining a keypress, to avoid ambiguity.
  49061. jassert (! (CharacterFunctions::isUpperCase (newKeyPress.getTextCharacter())
  49062. && ! newKeyPress.getModifiers().isShiftDown()));
  49063. if (findCommandForKeyPress (newKeyPress) != commandID)
  49064. {
  49065. removeKeyPress (newKeyPress);
  49066. if (newKeyPress.isValid())
  49067. {
  49068. for (int i = mappings.size(); --i >= 0;)
  49069. {
  49070. if (mappings.getUnchecked(i)->commandID == commandID)
  49071. {
  49072. mappings.getUnchecked(i)->keypresses.insert (insertIndex, newKeyPress);
  49073. sendChangeMessage (this);
  49074. return;
  49075. }
  49076. }
  49077. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  49078. if (ci != 0)
  49079. {
  49080. CommandMapping* const cm = new CommandMapping();
  49081. cm->commandID = commandID;
  49082. cm->keypresses.add (newKeyPress);
  49083. cm->wantsKeyUpDownCallbacks = (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) != 0;
  49084. mappings.add (cm);
  49085. sendChangeMessage (this);
  49086. }
  49087. }
  49088. }
  49089. }
  49090. void KeyPressMappingSet::resetToDefaultMappings()
  49091. {
  49092. mappings.clear();
  49093. for (int i = 0; i < commandManager->getNumCommands(); ++i)
  49094. {
  49095. const ApplicationCommandInfo* const ci = commandManager->getCommandForIndex (i);
  49096. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  49097. {
  49098. addKeyPress (ci->commandID,
  49099. ci->defaultKeypresses.getReference (j));
  49100. }
  49101. }
  49102. sendChangeMessage (this);
  49103. }
  49104. void KeyPressMappingSet::resetToDefaultMapping (const CommandID commandID)
  49105. {
  49106. clearAllKeyPresses (commandID);
  49107. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  49108. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  49109. {
  49110. addKeyPress (ci->commandID,
  49111. ci->defaultKeypresses.getReference (j));
  49112. }
  49113. }
  49114. void KeyPressMappingSet::clearAllKeyPresses()
  49115. {
  49116. if (mappings.size() > 0)
  49117. {
  49118. sendChangeMessage (this);
  49119. mappings.clear();
  49120. }
  49121. }
  49122. void KeyPressMappingSet::clearAllKeyPresses (const CommandID commandID)
  49123. {
  49124. for (int i = mappings.size(); --i >= 0;)
  49125. {
  49126. if (mappings.getUnchecked(i)->commandID == commandID)
  49127. {
  49128. mappings.remove (i);
  49129. sendChangeMessage (this);
  49130. }
  49131. }
  49132. }
  49133. void KeyPressMappingSet::removeKeyPress (const KeyPress& keypress)
  49134. {
  49135. if (keypress.isValid())
  49136. {
  49137. for (int i = mappings.size(); --i >= 0;)
  49138. {
  49139. CommandMapping* const cm = mappings.getUnchecked(i);
  49140. for (int j = cm->keypresses.size(); --j >= 0;)
  49141. {
  49142. if (keypress == cm->keypresses [j])
  49143. {
  49144. cm->keypresses.remove (j);
  49145. sendChangeMessage (this);
  49146. }
  49147. }
  49148. }
  49149. }
  49150. }
  49151. void KeyPressMappingSet::removeKeyPress (const CommandID commandID, const int keyPressIndex)
  49152. {
  49153. for (int i = mappings.size(); --i >= 0;)
  49154. {
  49155. if (mappings.getUnchecked(i)->commandID == commandID)
  49156. {
  49157. mappings.getUnchecked(i)->keypresses.remove (keyPressIndex);
  49158. sendChangeMessage (this);
  49159. break;
  49160. }
  49161. }
  49162. }
  49163. CommandID KeyPressMappingSet::findCommandForKeyPress (const KeyPress& keyPress) const throw()
  49164. {
  49165. for (int i = 0; i < mappings.size(); ++i)
  49166. if (mappings.getUnchecked(i)->keypresses.contains (keyPress))
  49167. return mappings.getUnchecked(i)->commandID;
  49168. return 0;
  49169. }
  49170. bool KeyPressMappingSet::containsMapping (const CommandID commandID, const KeyPress& keyPress) const throw()
  49171. {
  49172. for (int i = mappings.size(); --i >= 0;)
  49173. if (mappings.getUnchecked(i)->commandID == commandID)
  49174. return mappings.getUnchecked(i)->keypresses.contains (keyPress);
  49175. return false;
  49176. }
  49177. void KeyPressMappingSet::invokeCommand (const CommandID commandID,
  49178. const KeyPress& key,
  49179. const bool isKeyDown,
  49180. const int millisecsSinceKeyPressed,
  49181. Component* const originatingComponent) const
  49182. {
  49183. ApplicationCommandTarget::InvocationInfo info (commandID);
  49184. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromKeyPress;
  49185. info.isKeyDown = isKeyDown;
  49186. info.keyPress = key;
  49187. info.millisecsSinceKeyPressed = millisecsSinceKeyPressed;
  49188. info.originatingComponent = originatingComponent;
  49189. commandManager->invoke (info, false);
  49190. }
  49191. bool KeyPressMappingSet::restoreFromXml (const XmlElement& xmlVersion)
  49192. {
  49193. if (xmlVersion.hasTagName ("KEYMAPPINGS"))
  49194. {
  49195. if (xmlVersion.getBoolAttribute ("basedOnDefaults", true))
  49196. {
  49197. // if the XML was created as a set of differences from the default mappings,
  49198. // (i.e. by calling createXml (true)), then we need to first restore the defaults.
  49199. resetToDefaultMappings();
  49200. }
  49201. else
  49202. {
  49203. // if the XML was created calling createXml (false), then we need to clear all
  49204. // the keys and treat the xml as describing the entire set of mappings.
  49205. clearAllKeyPresses();
  49206. }
  49207. forEachXmlChildElement (xmlVersion, map)
  49208. {
  49209. const CommandID commandId = map->getStringAttribute ("commandId").getHexValue32();
  49210. if (commandId != 0)
  49211. {
  49212. const KeyPress key (KeyPress::createFromDescription (map->getStringAttribute ("key")));
  49213. if (map->hasTagName ("MAPPING"))
  49214. {
  49215. addKeyPress (commandId, key);
  49216. }
  49217. else if (map->hasTagName ("UNMAPPING"))
  49218. {
  49219. if (containsMapping (commandId, key))
  49220. removeKeyPress (key);
  49221. }
  49222. }
  49223. }
  49224. return true;
  49225. }
  49226. return false;
  49227. }
  49228. XmlElement* KeyPressMappingSet::createXml (const bool saveDifferencesFromDefaultSet) const
  49229. {
  49230. ScopedPointer <KeyPressMappingSet> defaultSet;
  49231. if (saveDifferencesFromDefaultSet)
  49232. {
  49233. defaultSet = new KeyPressMappingSet (commandManager);
  49234. defaultSet->resetToDefaultMappings();
  49235. }
  49236. XmlElement* const doc = new XmlElement ("KEYMAPPINGS");
  49237. doc->setAttribute ("basedOnDefaults", saveDifferencesFromDefaultSet);
  49238. int i;
  49239. for (i = 0; i < mappings.size(); ++i)
  49240. {
  49241. const CommandMapping* const cm = mappings.getUnchecked(i);
  49242. for (int j = 0; j < cm->keypresses.size(); ++j)
  49243. {
  49244. if (defaultSet == 0
  49245. || ! defaultSet->containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  49246. {
  49247. XmlElement* const map = doc->createNewChildElement ("MAPPING");
  49248. map->setAttribute ("commandId", String::toHexString ((int) cm->commandID));
  49249. map->setAttribute ("description", commandManager->getDescriptionOfCommand (cm->commandID));
  49250. map->setAttribute ("key", cm->keypresses.getReference (j).getTextDescription());
  49251. }
  49252. }
  49253. }
  49254. if (defaultSet != 0)
  49255. {
  49256. for (i = 0; i < defaultSet->mappings.size(); ++i)
  49257. {
  49258. const CommandMapping* const cm = defaultSet->mappings.getUnchecked(i);
  49259. for (int j = 0; j < cm->keypresses.size(); ++j)
  49260. {
  49261. if (! containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  49262. {
  49263. XmlElement* const map = doc->createNewChildElement ("UNMAPPING");
  49264. map->setAttribute ("commandId", String::toHexString ((int) cm->commandID));
  49265. map->setAttribute ("description", commandManager->getDescriptionOfCommand (cm->commandID));
  49266. map->setAttribute ("key", cm->keypresses.getReference (j).getTextDescription());
  49267. }
  49268. }
  49269. }
  49270. }
  49271. return doc;
  49272. }
  49273. bool KeyPressMappingSet::keyPressed (const KeyPress& key,
  49274. Component* originatingComponent)
  49275. {
  49276. bool used = false;
  49277. const CommandID commandID = findCommandForKeyPress (key);
  49278. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  49279. if (ci != 0
  49280. && (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) == 0)
  49281. {
  49282. ApplicationCommandInfo info (0);
  49283. if (commandManager->getTargetForCommand (commandID, info) != 0
  49284. && (info.flags & ApplicationCommandInfo::isDisabled) == 0)
  49285. {
  49286. invokeCommand (commandID, key, true, 0, originatingComponent);
  49287. used = true;
  49288. }
  49289. else
  49290. {
  49291. if (originatingComponent != 0)
  49292. originatingComponent->getLookAndFeel().playAlertSound();
  49293. }
  49294. }
  49295. return used;
  49296. }
  49297. bool KeyPressMappingSet::keyStateChanged (const bool /*isKeyDown*/, Component* originatingComponent)
  49298. {
  49299. bool used = false;
  49300. const uint32 now = Time::getMillisecondCounter();
  49301. for (int i = mappings.size(); --i >= 0;)
  49302. {
  49303. CommandMapping* const cm = mappings.getUnchecked(i);
  49304. if (cm->wantsKeyUpDownCallbacks)
  49305. {
  49306. for (int j = cm->keypresses.size(); --j >= 0;)
  49307. {
  49308. const KeyPress key (cm->keypresses.getReference (j));
  49309. const bool isDown = key.isCurrentlyDown();
  49310. int keyPressEntryIndex = 0;
  49311. bool wasDown = false;
  49312. for (int k = keysDown.size(); --k >= 0;)
  49313. {
  49314. if (key == keysDown.getUnchecked(k)->key)
  49315. {
  49316. keyPressEntryIndex = k;
  49317. wasDown = true;
  49318. used = true;
  49319. break;
  49320. }
  49321. }
  49322. if (isDown != wasDown)
  49323. {
  49324. int millisecs = 0;
  49325. if (isDown)
  49326. {
  49327. KeyPressTime* const k = new KeyPressTime();
  49328. k->key = key;
  49329. k->timeWhenPressed = now;
  49330. keysDown.add (k);
  49331. }
  49332. else
  49333. {
  49334. const uint32 pressTime = keysDown.getUnchecked (keyPressEntryIndex)->timeWhenPressed;
  49335. if (now > pressTime)
  49336. millisecs = now - pressTime;
  49337. keysDown.remove (keyPressEntryIndex);
  49338. }
  49339. invokeCommand (cm->commandID, key, isDown, millisecs, originatingComponent);
  49340. used = true;
  49341. }
  49342. }
  49343. }
  49344. }
  49345. return used;
  49346. }
  49347. void KeyPressMappingSet::globalFocusChanged (Component* focusedComponent)
  49348. {
  49349. if (focusedComponent != 0)
  49350. focusedComponent->keyStateChanged (false);
  49351. }
  49352. END_JUCE_NAMESPACE
  49353. /*** End of inlined file: juce_KeyPressMappingSet.cpp ***/
  49354. /*** Start of inlined file: juce_ModifierKeys.cpp ***/
  49355. BEGIN_JUCE_NAMESPACE
  49356. ModifierKeys::ModifierKeys (const int flags_) throw()
  49357. : flags (flags_)
  49358. {
  49359. }
  49360. ModifierKeys::ModifierKeys (const ModifierKeys& other) throw()
  49361. : flags (other.flags)
  49362. {
  49363. }
  49364. ModifierKeys& ModifierKeys::operator= (const ModifierKeys& other) throw()
  49365. {
  49366. flags = other.flags;
  49367. return *this;
  49368. }
  49369. ModifierKeys ModifierKeys::currentModifiers;
  49370. const ModifierKeys ModifierKeys::getCurrentModifiers() throw()
  49371. {
  49372. return currentModifiers;
  49373. }
  49374. int ModifierKeys::getNumMouseButtonsDown() const throw()
  49375. {
  49376. int num = 0;
  49377. if (isLeftButtonDown()) ++num;
  49378. if (isRightButtonDown()) ++num;
  49379. if (isMiddleButtonDown()) ++num;
  49380. return num;
  49381. }
  49382. END_JUCE_NAMESPACE
  49383. /*** End of inlined file: juce_ModifierKeys.cpp ***/
  49384. /*** Start of inlined file: juce_ComponentAnimator.cpp ***/
  49385. BEGIN_JUCE_NAMESPACE
  49386. class ComponentAnimator::AnimationTask
  49387. {
  49388. public:
  49389. AnimationTask (Component* const comp)
  49390. : component (comp)
  49391. {
  49392. }
  49393. void reset (const Rectangle<int>& finalBounds,
  49394. float finalAlpha,
  49395. int millisecondsToSpendMoving,
  49396. bool useProxyComponent,
  49397. double startSpeed_, double endSpeed_)
  49398. {
  49399. msElapsed = 0;
  49400. msTotal = jmax (1, millisecondsToSpendMoving);
  49401. lastProgress = 0;
  49402. destination = finalBounds;
  49403. destAlpha = finalAlpha;
  49404. isMoving = (finalBounds != component->getBounds());
  49405. isChangingAlpha = (finalAlpha != component->getAlpha());
  49406. left = component->getX();
  49407. top = component->getY();
  49408. right = component->getRight();
  49409. bottom = component->getBottom();
  49410. alpha = component->getAlpha();
  49411. const double invTotalDistance = 4.0 / (startSpeed_ + endSpeed_ + 2.0);
  49412. startSpeed = jmax (0.0, startSpeed_ * invTotalDistance);
  49413. midSpeed = invTotalDistance;
  49414. endSpeed = jmax (0.0, endSpeed_ * invTotalDistance);
  49415. if (useProxyComponent)
  49416. proxy = new ProxyComponent (*component);
  49417. else
  49418. proxy = 0;
  49419. component->setVisible (! useProxyComponent);
  49420. }
  49421. bool useTimeslice (const int elapsed)
  49422. {
  49423. Component* const c = proxy != 0 ? static_cast <Component*> (proxy)
  49424. : static_cast <Component*> (component);
  49425. if (c != 0)
  49426. {
  49427. msElapsed += elapsed;
  49428. double newProgress = msElapsed / (double) msTotal;
  49429. if (newProgress >= 0 && newProgress < 1.0)
  49430. {
  49431. newProgress = timeToDistance (newProgress);
  49432. const double delta = (newProgress - lastProgress) / (1.0 - lastProgress);
  49433. jassert (newProgress >= lastProgress);
  49434. lastProgress = newProgress;
  49435. if (delta < 1.0)
  49436. {
  49437. bool stillBusy = false;
  49438. if (isMoving)
  49439. {
  49440. left += (destination.getX() - left) * delta;
  49441. top += (destination.getY() - top) * delta;
  49442. right += (destination.getRight() - right) * delta;
  49443. bottom += (destination.getBottom() - bottom) * delta;
  49444. const Rectangle<int> newBounds (roundToInt (left),
  49445. roundToInt (top),
  49446. roundToInt (right - left),
  49447. roundToInt (bottom - top));
  49448. if (newBounds != destination)
  49449. {
  49450. c->setBounds (newBounds);
  49451. stillBusy = true;
  49452. }
  49453. }
  49454. if (isChangingAlpha)
  49455. {
  49456. alpha += (destAlpha - alpha) * delta;
  49457. c->setAlpha ((float) alpha);
  49458. stillBusy = true;
  49459. }
  49460. if (stillBusy)
  49461. return true;
  49462. }
  49463. }
  49464. }
  49465. moveToFinalDestination();
  49466. return false;
  49467. }
  49468. void moveToFinalDestination()
  49469. {
  49470. if (component != 0)
  49471. {
  49472. component->setAlpha ((float) destAlpha);
  49473. component->setBounds (destination);
  49474. }
  49475. }
  49476. class ProxyComponent : public Component
  49477. {
  49478. public:
  49479. ProxyComponent (Component& component)
  49480. : image (component.createComponentSnapshot (component.getLocalBounds()))
  49481. {
  49482. setBounds (component.getBounds());
  49483. setAlpha (component.getAlpha());
  49484. setInterceptsMouseClicks (false, false);
  49485. Component* const parent = component.getParentComponent();
  49486. if (parent != 0)
  49487. parent->addAndMakeVisible (this);
  49488. else if (component.isOnDesktop() && component.getPeer() != 0)
  49489. addToDesktop (component.getPeer()->getStyleFlags());
  49490. else
  49491. jassertfalse; // seem to be trying to animate a component that's not visible..
  49492. setVisible (true);
  49493. toBehind (&component);
  49494. }
  49495. void paint (Graphics& g)
  49496. {
  49497. g.setOpacity (1.0f);
  49498. g.drawImage (image, 0, 0, getWidth(), getHeight(),
  49499. 0, 0, image.getWidth(), image.getHeight());
  49500. }
  49501. juce_UseDebuggingNewOperator
  49502. private:
  49503. Image image;
  49504. ProxyComponent (const ProxyComponent&);
  49505. ProxyComponent& operator= (const ProxyComponent&);
  49506. };
  49507. Component::SafePointer<Component> component;
  49508. ScopedPointer<Component> proxy;
  49509. Rectangle<int> destination;
  49510. double destAlpha;
  49511. int msElapsed, msTotal;
  49512. double startSpeed, midSpeed, endSpeed, lastProgress;
  49513. double left, top, right, bottom, alpha;
  49514. bool isMoving, isChangingAlpha;
  49515. private:
  49516. double timeToDistance (const double time) const throw()
  49517. {
  49518. return (time < 0.5) ? time * (startSpeed + time * (midSpeed - startSpeed))
  49519. : 0.5 * (startSpeed + 0.5 * (midSpeed - startSpeed))
  49520. + (time - 0.5) * (midSpeed + (time - 0.5) * (endSpeed - midSpeed));
  49521. }
  49522. };
  49523. ComponentAnimator::ComponentAnimator()
  49524. : lastTime (0)
  49525. {
  49526. }
  49527. ComponentAnimator::~ComponentAnimator()
  49528. {
  49529. }
  49530. ComponentAnimator::AnimationTask* ComponentAnimator::findTaskFor (Component* const component) const
  49531. {
  49532. for (int i = tasks.size(); --i >= 0;)
  49533. if (component == tasks.getUnchecked(i)->component.getComponent())
  49534. return tasks.getUnchecked(i);
  49535. return 0;
  49536. }
  49537. void ComponentAnimator::animateComponent (Component* const component,
  49538. const Rectangle<int>& finalBounds,
  49539. const float finalAlpha,
  49540. const int millisecondsToSpendMoving,
  49541. const bool useProxyComponent,
  49542. const double startSpeed,
  49543. const double endSpeed)
  49544. {
  49545. // the speeds must be 0 or greater!
  49546. jassert (startSpeed >= 0 && endSpeed >= 0)
  49547. if (component != 0)
  49548. {
  49549. AnimationTask* at = findTaskFor (component);
  49550. if (at == 0)
  49551. {
  49552. at = new AnimationTask (component);
  49553. tasks.add (at);
  49554. sendChangeMessage (this);
  49555. }
  49556. at->reset (finalBounds, finalAlpha, millisecondsToSpendMoving,
  49557. useProxyComponent, startSpeed, endSpeed);
  49558. if (! isTimerRunning())
  49559. {
  49560. lastTime = Time::getMillisecondCounter();
  49561. startTimer (1000 / 50);
  49562. }
  49563. }
  49564. }
  49565. void ComponentAnimator::fadeOut (Component* component, int millisecondsToTake)
  49566. {
  49567. if (component != 0)
  49568. {
  49569. if (component->isShowing() && millisecondsToTake > 0)
  49570. animateComponent (component, component->getBounds(), 0.0f, millisecondsToTake, true, 1.0, 1.0);
  49571. component->setVisible (false);
  49572. }
  49573. }
  49574. void ComponentAnimator::fadeIn (Component* component, int millisecondsToTake)
  49575. {
  49576. if (component != 0 && ! (component->isVisible() && component->getAlpha() == 1.0f))
  49577. {
  49578. component->setAlpha (0.0f);
  49579. component->setVisible (true);
  49580. animateComponent (component, component->getBounds(), 1.0f, millisecondsToTake, false, 1.0, 1.0);
  49581. }
  49582. }
  49583. void ComponentAnimator::cancelAllAnimations (const bool moveComponentsToTheirFinalPositions)
  49584. {
  49585. if (tasks.size() > 0)
  49586. {
  49587. if (moveComponentsToTheirFinalPositions)
  49588. for (int i = tasks.size(); --i >= 0;)
  49589. tasks.getUnchecked(i)->moveToFinalDestination();
  49590. tasks.clear();
  49591. sendChangeMessage (this);
  49592. }
  49593. }
  49594. void ComponentAnimator::cancelAnimation (Component* const component,
  49595. const bool moveComponentToItsFinalPosition)
  49596. {
  49597. AnimationTask* const at = findTaskFor (component);
  49598. if (at != 0)
  49599. {
  49600. if (moveComponentToItsFinalPosition)
  49601. at->moveToFinalDestination();
  49602. tasks.removeObject (at);
  49603. sendChangeMessage (this);
  49604. }
  49605. }
  49606. const Rectangle<int> ComponentAnimator::getComponentDestination (Component* const component)
  49607. {
  49608. jassert (component != 0);
  49609. AnimationTask* const at = findTaskFor (component);
  49610. if (at != 0)
  49611. return at->destination;
  49612. return component->getBounds();
  49613. }
  49614. bool ComponentAnimator::isAnimating (Component* component) const
  49615. {
  49616. return findTaskFor (component) != 0;
  49617. }
  49618. void ComponentAnimator::timerCallback()
  49619. {
  49620. const uint32 timeNow = Time::getMillisecondCounter();
  49621. if (lastTime == 0 || lastTime == timeNow)
  49622. lastTime = timeNow;
  49623. const int elapsed = timeNow - lastTime;
  49624. for (int i = tasks.size(); --i >= 0;)
  49625. {
  49626. if (! tasks.getUnchecked(i)->useTimeslice (elapsed))
  49627. {
  49628. tasks.remove (i);
  49629. sendChangeMessage (this);
  49630. }
  49631. }
  49632. lastTime = timeNow;
  49633. if (tasks.size() == 0)
  49634. stopTimer();
  49635. }
  49636. END_JUCE_NAMESPACE
  49637. /*** End of inlined file: juce_ComponentAnimator.cpp ***/
  49638. /*** Start of inlined file: juce_ComponentBoundsConstrainer.cpp ***/
  49639. BEGIN_JUCE_NAMESPACE
  49640. ComponentBoundsConstrainer::ComponentBoundsConstrainer() throw()
  49641. : minW (0),
  49642. maxW (0x3fffffff),
  49643. minH (0),
  49644. maxH (0x3fffffff),
  49645. minOffTop (0),
  49646. minOffLeft (0),
  49647. minOffBottom (0),
  49648. minOffRight (0),
  49649. aspectRatio (0.0)
  49650. {
  49651. }
  49652. ComponentBoundsConstrainer::~ComponentBoundsConstrainer()
  49653. {
  49654. }
  49655. void ComponentBoundsConstrainer::setMinimumWidth (const int minimumWidth) throw()
  49656. {
  49657. minW = minimumWidth;
  49658. }
  49659. void ComponentBoundsConstrainer::setMaximumWidth (const int maximumWidth) throw()
  49660. {
  49661. maxW = maximumWidth;
  49662. }
  49663. void ComponentBoundsConstrainer::setMinimumHeight (const int minimumHeight) throw()
  49664. {
  49665. minH = minimumHeight;
  49666. }
  49667. void ComponentBoundsConstrainer::setMaximumHeight (const int maximumHeight) throw()
  49668. {
  49669. maxH = maximumHeight;
  49670. }
  49671. void ComponentBoundsConstrainer::setMinimumSize (const int minimumWidth, const int minimumHeight) throw()
  49672. {
  49673. jassert (maxW >= minimumWidth);
  49674. jassert (maxH >= minimumHeight);
  49675. jassert (minimumWidth > 0 && minimumHeight > 0);
  49676. minW = minimumWidth;
  49677. minH = minimumHeight;
  49678. if (minW > maxW)
  49679. maxW = minW;
  49680. if (minH > maxH)
  49681. maxH = minH;
  49682. }
  49683. void ComponentBoundsConstrainer::setMaximumSize (const int maximumWidth, const int maximumHeight) throw()
  49684. {
  49685. jassert (maximumWidth >= minW);
  49686. jassert (maximumHeight >= minH);
  49687. jassert (maximumWidth > 0 && maximumHeight > 0);
  49688. maxW = jmax (minW, maximumWidth);
  49689. maxH = jmax (minH, maximumHeight);
  49690. }
  49691. void ComponentBoundsConstrainer::setSizeLimits (const int minimumWidth,
  49692. const int minimumHeight,
  49693. const int maximumWidth,
  49694. const int maximumHeight) throw()
  49695. {
  49696. jassert (maximumWidth >= minimumWidth);
  49697. jassert (maximumHeight >= minimumHeight);
  49698. jassert (maximumWidth > 0 && maximumHeight > 0);
  49699. jassert (minimumWidth > 0 && minimumHeight > 0);
  49700. minW = jmax (0, minimumWidth);
  49701. minH = jmax (0, minimumHeight);
  49702. maxW = jmax (minW, maximumWidth);
  49703. maxH = jmax (minH, maximumHeight);
  49704. }
  49705. void ComponentBoundsConstrainer::setMinimumOnscreenAmounts (const int minimumWhenOffTheTop,
  49706. const int minimumWhenOffTheLeft,
  49707. const int minimumWhenOffTheBottom,
  49708. const int minimumWhenOffTheRight) throw()
  49709. {
  49710. minOffTop = minimumWhenOffTheTop;
  49711. minOffLeft = minimumWhenOffTheLeft;
  49712. minOffBottom = minimumWhenOffTheBottom;
  49713. minOffRight = minimumWhenOffTheRight;
  49714. }
  49715. void ComponentBoundsConstrainer::setFixedAspectRatio (const double widthOverHeight) throw()
  49716. {
  49717. aspectRatio = jmax (0.0, widthOverHeight);
  49718. }
  49719. double ComponentBoundsConstrainer::getFixedAspectRatio() const throw()
  49720. {
  49721. return aspectRatio;
  49722. }
  49723. void ComponentBoundsConstrainer::setBoundsForComponent (Component* const component,
  49724. const Rectangle<int>& targetBounds,
  49725. const bool isStretchingTop,
  49726. const bool isStretchingLeft,
  49727. const bool isStretchingBottom,
  49728. const bool isStretchingRight)
  49729. {
  49730. jassert (component != 0);
  49731. Rectangle<int> limits, bounds (targetBounds);
  49732. BorderSize border;
  49733. Component* const parent = component->getParentComponent();
  49734. if (parent == 0)
  49735. {
  49736. ComponentPeer* peer = component->getPeer();
  49737. if (peer != 0)
  49738. border = peer->getFrameSize();
  49739. limits = Desktop::getInstance().getMonitorAreaContaining (bounds.getCentre());
  49740. }
  49741. else
  49742. {
  49743. limits.setSize (parent->getWidth(), parent->getHeight());
  49744. }
  49745. border.addTo (bounds);
  49746. checkBounds (bounds,
  49747. border.addedTo (component->getBounds()), limits,
  49748. isStretchingTop, isStretchingLeft,
  49749. isStretchingBottom, isStretchingRight);
  49750. border.subtractFrom (bounds);
  49751. applyBoundsToComponent (component, bounds);
  49752. }
  49753. void ComponentBoundsConstrainer::checkComponentBounds (Component* component)
  49754. {
  49755. setBoundsForComponent (component, component->getBounds(),
  49756. false, false, false, false);
  49757. }
  49758. void ComponentBoundsConstrainer::applyBoundsToComponent (Component* component,
  49759. const Rectangle<int>& bounds)
  49760. {
  49761. component->setBounds (bounds);
  49762. }
  49763. void ComponentBoundsConstrainer::resizeStart()
  49764. {
  49765. }
  49766. void ComponentBoundsConstrainer::resizeEnd()
  49767. {
  49768. }
  49769. void ComponentBoundsConstrainer::checkBounds (Rectangle<int>& bounds,
  49770. const Rectangle<int>& old,
  49771. const Rectangle<int>& limits,
  49772. const bool isStretchingTop,
  49773. const bool isStretchingLeft,
  49774. const bool isStretchingBottom,
  49775. const bool isStretchingRight)
  49776. {
  49777. // constrain the size if it's being stretched..
  49778. if (isStretchingLeft)
  49779. bounds.setLeft (jlimit (old.getRight() - maxW, old.getRight() - minW, bounds.getX()));
  49780. if (isStretchingRight)
  49781. bounds.setWidth (jlimit (minW, maxW, bounds.getWidth()));
  49782. if (isStretchingTop)
  49783. bounds.setTop (jlimit (old.getBottom() - maxH, old.getBottom() - minH, bounds.getY()));
  49784. if (isStretchingBottom)
  49785. bounds.setHeight (jlimit (minH, maxH, bounds.getHeight()));
  49786. if (bounds.isEmpty())
  49787. return;
  49788. if (minOffTop > 0)
  49789. {
  49790. const int limit = limits.getY() + jmin (minOffTop - bounds.getHeight(), 0);
  49791. if (bounds.getY() < limit)
  49792. {
  49793. if (isStretchingTop)
  49794. bounds.setTop (limits.getY());
  49795. else
  49796. bounds.setY (limit);
  49797. }
  49798. }
  49799. if (minOffLeft > 0)
  49800. {
  49801. const int limit = limits.getX() + jmin (minOffLeft - bounds.getWidth(), 0);
  49802. if (bounds.getX() < limit)
  49803. {
  49804. if (isStretchingLeft)
  49805. bounds.setLeft (limits.getX());
  49806. else
  49807. bounds.setX (limit);
  49808. }
  49809. }
  49810. if (minOffBottom > 0)
  49811. {
  49812. const int limit = limits.getBottom() - jmin (minOffBottom, bounds.getHeight());
  49813. if (bounds.getY() > limit)
  49814. {
  49815. if (isStretchingBottom)
  49816. bounds.setBottom (limits.getBottom());
  49817. else
  49818. bounds.setY (limit);
  49819. }
  49820. }
  49821. if (minOffRight > 0)
  49822. {
  49823. const int limit = limits.getRight() - jmin (minOffRight, bounds.getWidth());
  49824. if (bounds.getX() > limit)
  49825. {
  49826. if (isStretchingRight)
  49827. bounds.setRight (limits.getRight());
  49828. else
  49829. bounds.setX (limit);
  49830. }
  49831. }
  49832. // constrain the aspect ratio if one has been specified..
  49833. if (aspectRatio > 0.0)
  49834. {
  49835. bool adjustWidth;
  49836. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  49837. {
  49838. adjustWidth = true;
  49839. }
  49840. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  49841. {
  49842. adjustWidth = false;
  49843. }
  49844. else
  49845. {
  49846. const double oldRatio = (old.getHeight() > 0) ? std::abs (old.getWidth() / (double) old.getHeight()) : 0.0;
  49847. const double newRatio = std::abs (bounds.getWidth() / (double) bounds.getHeight());
  49848. adjustWidth = (oldRatio > newRatio);
  49849. }
  49850. if (adjustWidth)
  49851. {
  49852. bounds.setWidth (roundToInt (bounds.getHeight() * aspectRatio));
  49853. if (bounds.getWidth() > maxW || bounds.getWidth() < minW)
  49854. {
  49855. bounds.setWidth (jlimit (minW, maxW, bounds.getWidth()));
  49856. bounds.setHeight (roundToInt (bounds.getWidth() / aspectRatio));
  49857. }
  49858. }
  49859. else
  49860. {
  49861. bounds.setHeight (roundToInt (bounds.getWidth() / aspectRatio));
  49862. if (bounds.getHeight() > maxH || bounds.getHeight() < minH)
  49863. {
  49864. bounds.setHeight (jlimit (minH, maxH, bounds.getHeight()));
  49865. bounds.setWidth (roundToInt (bounds.getHeight() * aspectRatio));
  49866. }
  49867. }
  49868. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  49869. {
  49870. bounds.setX (old.getX() + (old.getWidth() - bounds.getWidth()) / 2);
  49871. }
  49872. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  49873. {
  49874. bounds.setY (old.getY() + (old.getHeight() - bounds.getHeight()) / 2);
  49875. }
  49876. else
  49877. {
  49878. if (isStretchingLeft)
  49879. bounds.setX (old.getRight() - bounds.getWidth());
  49880. if (isStretchingTop)
  49881. bounds.setY (old.getBottom() - bounds.getHeight());
  49882. }
  49883. }
  49884. jassert (! bounds.isEmpty());
  49885. }
  49886. END_JUCE_NAMESPACE
  49887. /*** End of inlined file: juce_ComponentBoundsConstrainer.cpp ***/
  49888. /*** Start of inlined file: juce_ComponentMovementWatcher.cpp ***/
  49889. BEGIN_JUCE_NAMESPACE
  49890. ComponentMovementWatcher::ComponentMovementWatcher (Component* const component_)
  49891. : component (component_),
  49892. lastPeer (0),
  49893. reentrant (false)
  49894. {
  49895. jassert (component != 0); // can't use this with a null pointer..
  49896. component->addComponentListener (this);
  49897. registerWithParentComps();
  49898. }
  49899. ComponentMovementWatcher::~ComponentMovementWatcher()
  49900. {
  49901. component->removeComponentListener (this);
  49902. unregister();
  49903. }
  49904. void ComponentMovementWatcher::componentParentHierarchyChanged (Component&)
  49905. {
  49906. // agh! don't delete the target component without deleting this object first!
  49907. jassert (component != 0);
  49908. if (! reentrant)
  49909. {
  49910. reentrant = true;
  49911. ComponentPeer* const peer = component->getPeer();
  49912. if (peer != lastPeer)
  49913. {
  49914. componentPeerChanged();
  49915. if (component == 0)
  49916. return;
  49917. lastPeer = peer;
  49918. }
  49919. unregister();
  49920. registerWithParentComps();
  49921. reentrant = false;
  49922. componentMovedOrResized (*component, true, true);
  49923. }
  49924. }
  49925. void ComponentMovementWatcher::componentMovedOrResized (Component&, bool wasMoved, bool wasResized)
  49926. {
  49927. // agh! don't delete the target component without deleting this object first!
  49928. jassert (component != 0);
  49929. if (wasMoved)
  49930. {
  49931. const Point<int> pos (component->relativePositionToOtherComponent (component->getTopLevelComponent(), Point<int>()));
  49932. wasMoved = lastBounds.getPosition() != pos;
  49933. lastBounds.setPosition (pos);
  49934. }
  49935. wasResized = (lastBounds.getWidth() != component->getWidth() || lastBounds.getHeight() != component->getHeight());
  49936. lastBounds.setSize (component->getWidth(), component->getHeight());
  49937. if (wasMoved || wasResized)
  49938. componentMovedOrResized (wasMoved, wasResized);
  49939. }
  49940. void ComponentMovementWatcher::registerWithParentComps()
  49941. {
  49942. Component* p = component->getParentComponent();
  49943. while (p != 0)
  49944. {
  49945. p->addComponentListener (this);
  49946. registeredParentComps.add (p);
  49947. p = p->getParentComponent();
  49948. }
  49949. }
  49950. void ComponentMovementWatcher::unregister()
  49951. {
  49952. for (int i = registeredParentComps.size(); --i >= 0;)
  49953. registeredParentComps.getUnchecked(i)->removeComponentListener (this);
  49954. registeredParentComps.clear();
  49955. }
  49956. END_JUCE_NAMESPACE
  49957. /*** End of inlined file: juce_ComponentMovementWatcher.cpp ***/
  49958. /*** Start of inlined file: juce_GroupComponent.cpp ***/
  49959. BEGIN_JUCE_NAMESPACE
  49960. GroupComponent::GroupComponent (const String& componentName,
  49961. const String& labelText)
  49962. : Component (componentName),
  49963. text (labelText),
  49964. justification (Justification::left)
  49965. {
  49966. setInterceptsMouseClicks (false, true);
  49967. }
  49968. GroupComponent::~GroupComponent()
  49969. {
  49970. }
  49971. void GroupComponent::setText (const String& newText)
  49972. {
  49973. if (text != newText)
  49974. {
  49975. text = newText;
  49976. repaint();
  49977. }
  49978. }
  49979. const String GroupComponent::getText() const
  49980. {
  49981. return text;
  49982. }
  49983. void GroupComponent::setTextLabelPosition (const Justification& newJustification)
  49984. {
  49985. if (justification != newJustification)
  49986. {
  49987. justification = newJustification;
  49988. repaint();
  49989. }
  49990. }
  49991. void GroupComponent::paint (Graphics& g)
  49992. {
  49993. getLookAndFeel()
  49994. .drawGroupComponentOutline (g, getWidth(), getHeight(),
  49995. text, justification,
  49996. *this);
  49997. }
  49998. void GroupComponent::enablementChanged()
  49999. {
  50000. repaint();
  50001. }
  50002. void GroupComponent::colourChanged()
  50003. {
  50004. repaint();
  50005. }
  50006. END_JUCE_NAMESPACE
  50007. /*** End of inlined file: juce_GroupComponent.cpp ***/
  50008. /*** Start of inlined file: juce_MultiDocumentPanel.cpp ***/
  50009. BEGIN_JUCE_NAMESPACE
  50010. MultiDocumentPanelWindow::MultiDocumentPanelWindow (const Colour& backgroundColour)
  50011. : DocumentWindow (String::empty, backgroundColour,
  50012. DocumentWindow::maximiseButton | DocumentWindow::closeButton, false)
  50013. {
  50014. }
  50015. MultiDocumentPanelWindow::~MultiDocumentPanelWindow()
  50016. {
  50017. }
  50018. void MultiDocumentPanelWindow::maximiseButtonPressed()
  50019. {
  50020. MultiDocumentPanel* const owner = getOwner();
  50021. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  50022. if (owner != 0)
  50023. owner->setLayoutMode (MultiDocumentPanel::MaximisedWindowsWithTabs);
  50024. }
  50025. void MultiDocumentPanelWindow::closeButtonPressed()
  50026. {
  50027. MultiDocumentPanel* const owner = getOwner();
  50028. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  50029. if (owner != 0)
  50030. owner->closeDocument (getContentComponent(), true);
  50031. }
  50032. void MultiDocumentPanelWindow::activeWindowStatusChanged()
  50033. {
  50034. DocumentWindow::activeWindowStatusChanged();
  50035. updateOrder();
  50036. }
  50037. void MultiDocumentPanelWindow::broughtToFront()
  50038. {
  50039. DocumentWindow::broughtToFront();
  50040. updateOrder();
  50041. }
  50042. void MultiDocumentPanelWindow::updateOrder()
  50043. {
  50044. MultiDocumentPanel* const owner = getOwner();
  50045. if (owner != 0)
  50046. owner->updateOrder();
  50047. }
  50048. MultiDocumentPanel* MultiDocumentPanelWindow::getOwner() const throw()
  50049. {
  50050. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  50051. return findParentComponentOfClass ((MultiDocumentPanel*) 0);
  50052. }
  50053. class MDITabbedComponentInternal : public TabbedComponent
  50054. {
  50055. public:
  50056. MDITabbedComponentInternal()
  50057. : TabbedComponent (TabbedButtonBar::TabsAtTop)
  50058. {
  50059. }
  50060. ~MDITabbedComponentInternal()
  50061. {
  50062. }
  50063. void currentTabChanged (int, const String&)
  50064. {
  50065. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  50066. MultiDocumentPanel* const owner = findParentComponentOfClass ((MultiDocumentPanel*) 0);
  50067. if (owner != 0)
  50068. owner->updateOrder();
  50069. }
  50070. };
  50071. MultiDocumentPanel::MultiDocumentPanel()
  50072. : mode (MaximisedWindowsWithTabs),
  50073. backgroundColour (Colours::lightblue),
  50074. maximumNumDocuments (0),
  50075. numDocsBeforeTabsUsed (0)
  50076. {
  50077. setOpaque (true);
  50078. }
  50079. MultiDocumentPanel::~MultiDocumentPanel()
  50080. {
  50081. closeAllDocuments (false);
  50082. }
  50083. namespace MultiDocHelpers
  50084. {
  50085. bool shouldDeleteComp (Component* const c)
  50086. {
  50087. return c->getProperties() ["mdiDocumentDelete_"];
  50088. }
  50089. }
  50090. bool MultiDocumentPanel::closeAllDocuments (const bool checkItsOkToCloseFirst)
  50091. {
  50092. while (components.size() > 0)
  50093. if (! closeDocument (components.getLast(), checkItsOkToCloseFirst))
  50094. return false;
  50095. return true;
  50096. }
  50097. MultiDocumentPanelWindow* MultiDocumentPanel::createNewDocumentWindow()
  50098. {
  50099. return new MultiDocumentPanelWindow (backgroundColour);
  50100. }
  50101. void MultiDocumentPanel::addWindow (Component* component)
  50102. {
  50103. MultiDocumentPanelWindow* const dw = createNewDocumentWindow();
  50104. dw->setResizable (true, false);
  50105. dw->setContentComponent (component, false, true);
  50106. dw->setName (component->getName());
  50107. const var bkg (component->getProperties() ["mdiDocumentBkg_"]);
  50108. dw->setBackgroundColour (bkg.isVoid() ? backgroundColour : Colour ((int) bkg));
  50109. int x = 4;
  50110. Component* const topComp = getChildComponent (getNumChildComponents() - 1);
  50111. if (topComp != 0 && topComp->getX() == x && topComp->getY() == x)
  50112. x += 16;
  50113. dw->setTopLeftPosition (x, x);
  50114. const var pos (component->getProperties() ["mdiDocumentPos_"]);
  50115. if (pos.toString().isNotEmpty())
  50116. dw->restoreWindowStateFromString (pos.toString());
  50117. addAndMakeVisible (dw);
  50118. dw->toFront (true);
  50119. }
  50120. bool MultiDocumentPanel::addDocument (Component* const component,
  50121. const Colour& docColour,
  50122. const bool deleteWhenRemoved)
  50123. {
  50124. // If you try passing a full DocumentWindow or ResizableWindow in here, you'll end up
  50125. // with a frame-within-a-frame! Just pass in the bare content component.
  50126. jassert (dynamic_cast <ResizableWindow*> (component) == 0);
  50127. if (component == 0 || (maximumNumDocuments > 0 && components.size() >= maximumNumDocuments))
  50128. return false;
  50129. components.add (component);
  50130. component->getProperties().set ("mdiDocumentDelete_", deleteWhenRemoved);
  50131. component->getProperties().set ("mdiDocumentBkg_", (int) docColour.getARGB());
  50132. component->addComponentListener (this);
  50133. if (mode == FloatingWindows)
  50134. {
  50135. if (isFullscreenWhenOneDocument())
  50136. {
  50137. if (components.size() == 1)
  50138. {
  50139. addAndMakeVisible (component);
  50140. }
  50141. else
  50142. {
  50143. if (components.size() == 2)
  50144. addWindow (components.getFirst());
  50145. addWindow (component);
  50146. }
  50147. }
  50148. else
  50149. {
  50150. addWindow (component);
  50151. }
  50152. }
  50153. else
  50154. {
  50155. if (tabComponent == 0 && components.size() > numDocsBeforeTabsUsed)
  50156. {
  50157. addAndMakeVisible (tabComponent = new MDITabbedComponentInternal());
  50158. Array <Component*> temp (components);
  50159. for (int i = 0; i < temp.size(); ++i)
  50160. tabComponent->addTab (temp[i]->getName(), docColour, temp[i], false);
  50161. resized();
  50162. }
  50163. else
  50164. {
  50165. if (tabComponent != 0)
  50166. tabComponent->addTab (component->getName(), docColour, component, false);
  50167. else
  50168. addAndMakeVisible (component);
  50169. }
  50170. setActiveDocument (component);
  50171. }
  50172. resized();
  50173. activeDocumentChanged();
  50174. return true;
  50175. }
  50176. bool MultiDocumentPanel::closeDocument (Component* component,
  50177. const bool checkItsOkToCloseFirst)
  50178. {
  50179. if (components.contains (component))
  50180. {
  50181. if (checkItsOkToCloseFirst && ! tryToCloseDocument (component))
  50182. return false;
  50183. component->removeComponentListener (this);
  50184. const bool shouldDelete = MultiDocHelpers::shouldDeleteComp (component);
  50185. component->getProperties().remove ("mdiDocumentDelete_");
  50186. component->getProperties().remove ("mdiDocumentBkg_");
  50187. if (mode == FloatingWindows)
  50188. {
  50189. for (int i = getNumChildComponents(); --i >= 0;)
  50190. {
  50191. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50192. if (dw != 0 && dw->getContentComponent() == component)
  50193. {
  50194. dw->setContentComponent (0, false);
  50195. delete dw;
  50196. break;
  50197. }
  50198. }
  50199. if (shouldDelete)
  50200. delete component;
  50201. components.removeValue (component);
  50202. if (isFullscreenWhenOneDocument() && components.size() == 1)
  50203. {
  50204. for (int i = getNumChildComponents(); --i >= 0;)
  50205. {
  50206. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50207. if (dw != 0)
  50208. {
  50209. dw->setContentComponent (0, false);
  50210. delete dw;
  50211. }
  50212. }
  50213. addAndMakeVisible (components.getFirst());
  50214. }
  50215. }
  50216. else
  50217. {
  50218. jassert (components.indexOf (component) >= 0);
  50219. if (tabComponent != 0)
  50220. {
  50221. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  50222. if (tabComponent->getTabContentComponent (i) == component)
  50223. tabComponent->removeTab (i);
  50224. }
  50225. else
  50226. {
  50227. removeChildComponent (component);
  50228. }
  50229. if (shouldDelete)
  50230. delete component;
  50231. if (tabComponent != 0 && tabComponent->getNumTabs() <= numDocsBeforeTabsUsed)
  50232. tabComponent = 0;
  50233. components.removeValue (component);
  50234. if (components.size() > 0 && tabComponent == 0)
  50235. addAndMakeVisible (components.getFirst());
  50236. }
  50237. resized();
  50238. activeDocumentChanged();
  50239. }
  50240. else
  50241. {
  50242. jassertfalse;
  50243. }
  50244. return true;
  50245. }
  50246. int MultiDocumentPanel::getNumDocuments() const throw()
  50247. {
  50248. return components.size();
  50249. }
  50250. Component* MultiDocumentPanel::getDocument (const int index) const throw()
  50251. {
  50252. return components [index];
  50253. }
  50254. Component* MultiDocumentPanel::getActiveDocument() const throw()
  50255. {
  50256. if (mode == FloatingWindows)
  50257. {
  50258. for (int i = getNumChildComponents(); --i >= 0;)
  50259. {
  50260. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50261. if (dw != 0 && dw->isActiveWindow())
  50262. return dw->getContentComponent();
  50263. }
  50264. }
  50265. return components.getLast();
  50266. }
  50267. void MultiDocumentPanel::setActiveDocument (Component* component)
  50268. {
  50269. if (mode == FloatingWindows)
  50270. {
  50271. component = getContainerComp (component);
  50272. if (component != 0)
  50273. component->toFront (true);
  50274. }
  50275. else if (tabComponent != 0)
  50276. {
  50277. jassert (components.indexOf (component) >= 0);
  50278. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  50279. {
  50280. if (tabComponent->getTabContentComponent (i) == component)
  50281. {
  50282. tabComponent->setCurrentTabIndex (i);
  50283. break;
  50284. }
  50285. }
  50286. }
  50287. else
  50288. {
  50289. component->grabKeyboardFocus();
  50290. }
  50291. }
  50292. void MultiDocumentPanel::activeDocumentChanged()
  50293. {
  50294. }
  50295. void MultiDocumentPanel::setMaximumNumDocuments (const int newNumber)
  50296. {
  50297. maximumNumDocuments = newNumber;
  50298. }
  50299. void MultiDocumentPanel::useFullscreenWhenOneDocument (const bool shouldUseTabs)
  50300. {
  50301. numDocsBeforeTabsUsed = shouldUseTabs ? 1 : 0;
  50302. }
  50303. bool MultiDocumentPanel::isFullscreenWhenOneDocument() const throw()
  50304. {
  50305. return numDocsBeforeTabsUsed != 0;
  50306. }
  50307. void MultiDocumentPanel::setLayoutMode (const LayoutMode newLayoutMode)
  50308. {
  50309. if (mode != newLayoutMode)
  50310. {
  50311. mode = newLayoutMode;
  50312. if (mode == FloatingWindows)
  50313. {
  50314. tabComponent = 0;
  50315. }
  50316. else
  50317. {
  50318. for (int i = getNumChildComponents(); --i >= 0;)
  50319. {
  50320. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50321. if (dw != 0)
  50322. {
  50323. dw->getContentComponent()->getProperties().set ("mdiDocumentPos_", dw->getWindowStateAsString());
  50324. dw->setContentComponent (0, false);
  50325. delete dw;
  50326. }
  50327. }
  50328. }
  50329. resized();
  50330. const Array <Component*> tempComps (components);
  50331. components.clear();
  50332. for (int i = 0; i < tempComps.size(); ++i)
  50333. {
  50334. Component* const c = tempComps.getUnchecked(i);
  50335. addDocument (c,
  50336. Colour ((int) c->getProperties().getWithDefault ("mdiDocumentBkg_", (int) Colours::white.getARGB())),
  50337. MultiDocHelpers::shouldDeleteComp (c));
  50338. }
  50339. }
  50340. }
  50341. void MultiDocumentPanel::setBackgroundColour (const Colour& newBackgroundColour)
  50342. {
  50343. if (backgroundColour != newBackgroundColour)
  50344. {
  50345. backgroundColour = newBackgroundColour;
  50346. setOpaque (newBackgroundColour.isOpaque());
  50347. repaint();
  50348. }
  50349. }
  50350. void MultiDocumentPanel::paint (Graphics& g)
  50351. {
  50352. g.fillAll (backgroundColour);
  50353. }
  50354. void MultiDocumentPanel::resized()
  50355. {
  50356. if (mode == MaximisedWindowsWithTabs || components.size() == numDocsBeforeTabsUsed)
  50357. {
  50358. for (int i = getNumChildComponents(); --i >= 0;)
  50359. getChildComponent (i)->setBounds (getLocalBounds());
  50360. }
  50361. setWantsKeyboardFocus (components.size() == 0);
  50362. }
  50363. Component* MultiDocumentPanel::getContainerComp (Component* c) const
  50364. {
  50365. if (mode == FloatingWindows)
  50366. {
  50367. for (int i = 0; i < getNumChildComponents(); ++i)
  50368. {
  50369. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50370. if (dw != 0 && dw->getContentComponent() == c)
  50371. {
  50372. c = dw;
  50373. break;
  50374. }
  50375. }
  50376. }
  50377. return c;
  50378. }
  50379. void MultiDocumentPanel::componentNameChanged (Component&)
  50380. {
  50381. if (mode == FloatingWindows)
  50382. {
  50383. for (int i = 0; i < getNumChildComponents(); ++i)
  50384. {
  50385. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50386. if (dw != 0)
  50387. dw->setName (dw->getContentComponent()->getName());
  50388. }
  50389. }
  50390. else if (tabComponent != 0)
  50391. {
  50392. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  50393. tabComponent->setTabName (i, tabComponent->getTabContentComponent (i)->getName());
  50394. }
  50395. }
  50396. void MultiDocumentPanel::updateOrder()
  50397. {
  50398. const Array <Component*> oldList (components);
  50399. if (mode == FloatingWindows)
  50400. {
  50401. components.clear();
  50402. for (int i = 0; i < getNumChildComponents(); ++i)
  50403. {
  50404. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50405. if (dw != 0)
  50406. components.add (dw->getContentComponent());
  50407. }
  50408. }
  50409. else
  50410. {
  50411. if (tabComponent != 0)
  50412. {
  50413. Component* const current = tabComponent->getCurrentContentComponent();
  50414. if (current != 0)
  50415. {
  50416. components.removeValue (current);
  50417. components.add (current);
  50418. }
  50419. }
  50420. }
  50421. if (components != oldList)
  50422. activeDocumentChanged();
  50423. }
  50424. END_JUCE_NAMESPACE
  50425. /*** End of inlined file: juce_MultiDocumentPanel.cpp ***/
  50426. /*** Start of inlined file: juce_ResizableBorderComponent.cpp ***/
  50427. BEGIN_JUCE_NAMESPACE
  50428. ResizableBorderComponent::Zone::Zone (int zoneFlags) throw()
  50429. : zone (zoneFlags)
  50430. {
  50431. }
  50432. ResizableBorderComponent::Zone::Zone (const ResizableBorderComponent::Zone& other) throw() : zone (other.zone) {}
  50433. ResizableBorderComponent::Zone& ResizableBorderComponent::Zone::operator= (const ResizableBorderComponent::Zone& other) throw() { zone = other.zone; return *this; }
  50434. bool ResizableBorderComponent::Zone::operator== (const ResizableBorderComponent::Zone& other) const throw() { return zone == other.zone; }
  50435. bool ResizableBorderComponent::Zone::operator!= (const ResizableBorderComponent::Zone& other) const throw() { return zone != other.zone; }
  50436. const ResizableBorderComponent::Zone ResizableBorderComponent::Zone::fromPositionOnBorder (const Rectangle<int>& totalSize,
  50437. const BorderSize& border,
  50438. const Point<int>& position)
  50439. {
  50440. int z = 0;
  50441. if (totalSize.contains (position)
  50442. && ! border.subtractedFrom (totalSize).contains (position))
  50443. {
  50444. const int minW = jmax (totalSize.getWidth() / 10, jmin (10, totalSize.getWidth() / 3));
  50445. if (position.getX() < jmax (border.getLeft(), minW))
  50446. z |= left;
  50447. else if (position.getX() >= totalSize.getWidth() - jmax (border.getRight(), minW))
  50448. z |= right;
  50449. const int minH = jmax (totalSize.getHeight() / 10, jmin (10, totalSize.getHeight() / 3));
  50450. if (position.getY() < jmax (border.getTop(), minH))
  50451. z |= top;
  50452. else if (position.getY() >= totalSize.getHeight() - jmax (border.getBottom(), minH))
  50453. z |= bottom;
  50454. }
  50455. return Zone (z);
  50456. }
  50457. const MouseCursor ResizableBorderComponent::Zone::getMouseCursor() const throw()
  50458. {
  50459. MouseCursor::StandardCursorType mc = MouseCursor::NormalCursor;
  50460. switch (zone)
  50461. {
  50462. case (left | top): mc = MouseCursor::TopLeftCornerResizeCursor; break;
  50463. case top: mc = MouseCursor::TopEdgeResizeCursor; break;
  50464. case (right | top): mc = MouseCursor::TopRightCornerResizeCursor; break;
  50465. case left: mc = MouseCursor::LeftEdgeResizeCursor; break;
  50466. case right: mc = MouseCursor::RightEdgeResizeCursor; break;
  50467. case (left | bottom): mc = MouseCursor::BottomLeftCornerResizeCursor; break;
  50468. case bottom: mc = MouseCursor::BottomEdgeResizeCursor; break;
  50469. case (right | bottom): mc = MouseCursor::BottomRightCornerResizeCursor; break;
  50470. default: break;
  50471. }
  50472. return mc;
  50473. }
  50474. ResizableBorderComponent::ResizableBorderComponent (Component* const componentToResize,
  50475. ComponentBoundsConstrainer* const constrainer_)
  50476. : component (componentToResize),
  50477. constrainer (constrainer_),
  50478. borderSize (5),
  50479. mouseZone (0)
  50480. {
  50481. }
  50482. ResizableBorderComponent::~ResizableBorderComponent()
  50483. {
  50484. }
  50485. void ResizableBorderComponent::paint (Graphics& g)
  50486. {
  50487. getLookAndFeel().drawResizableFrame (g, getWidth(), getHeight(), borderSize);
  50488. }
  50489. void ResizableBorderComponent::mouseEnter (const MouseEvent& e)
  50490. {
  50491. updateMouseZone (e);
  50492. }
  50493. void ResizableBorderComponent::mouseMove (const MouseEvent& e)
  50494. {
  50495. updateMouseZone (e);
  50496. }
  50497. void ResizableBorderComponent::mouseDown (const MouseEvent& e)
  50498. {
  50499. if (component == 0)
  50500. {
  50501. jassertfalse; // You've deleted the component that this resizer was supposed to be using!
  50502. return;
  50503. }
  50504. updateMouseZone (e);
  50505. originalBounds = component->getBounds();
  50506. if (constrainer != 0)
  50507. constrainer->resizeStart();
  50508. }
  50509. void ResizableBorderComponent::mouseDrag (const MouseEvent& e)
  50510. {
  50511. if (component == 0)
  50512. {
  50513. jassertfalse; // You've deleted the component that this resizer was supposed to be using!
  50514. return;
  50515. }
  50516. const Rectangle<int> bounds (mouseZone.resizeRectangleBy (originalBounds, e.getOffsetFromDragStart()));
  50517. if (constrainer != 0)
  50518. constrainer->setBoundsForComponent (component, bounds,
  50519. mouseZone.isDraggingTopEdge(),
  50520. mouseZone.isDraggingLeftEdge(),
  50521. mouseZone.isDraggingBottomEdge(),
  50522. mouseZone.isDraggingRightEdge());
  50523. else
  50524. component->setBounds (bounds);
  50525. }
  50526. void ResizableBorderComponent::mouseUp (const MouseEvent&)
  50527. {
  50528. if (constrainer != 0)
  50529. constrainer->resizeEnd();
  50530. }
  50531. bool ResizableBorderComponent::hitTest (int x, int y)
  50532. {
  50533. return x < borderSize.getLeft()
  50534. || x >= getWidth() - borderSize.getRight()
  50535. || y < borderSize.getTop()
  50536. || y >= getHeight() - borderSize.getBottom();
  50537. }
  50538. void ResizableBorderComponent::setBorderThickness (const BorderSize& newBorderSize)
  50539. {
  50540. if (borderSize != newBorderSize)
  50541. {
  50542. borderSize = newBorderSize;
  50543. repaint();
  50544. }
  50545. }
  50546. const BorderSize ResizableBorderComponent::getBorderThickness() const
  50547. {
  50548. return borderSize;
  50549. }
  50550. void ResizableBorderComponent::updateMouseZone (const MouseEvent& e)
  50551. {
  50552. Zone newZone (Zone::fromPositionOnBorder (getLocalBounds(), borderSize, e.getPosition()));
  50553. if (mouseZone != newZone)
  50554. {
  50555. mouseZone = newZone;
  50556. setMouseCursor (newZone.getMouseCursor());
  50557. }
  50558. }
  50559. END_JUCE_NAMESPACE
  50560. /*** End of inlined file: juce_ResizableBorderComponent.cpp ***/
  50561. /*** Start of inlined file: juce_ResizableCornerComponent.cpp ***/
  50562. BEGIN_JUCE_NAMESPACE
  50563. ResizableCornerComponent::ResizableCornerComponent (Component* const componentToResize,
  50564. ComponentBoundsConstrainer* const constrainer_)
  50565. : component (componentToResize),
  50566. constrainer (constrainer_)
  50567. {
  50568. setRepaintsOnMouseActivity (true);
  50569. setMouseCursor (MouseCursor::BottomRightCornerResizeCursor);
  50570. }
  50571. ResizableCornerComponent::~ResizableCornerComponent()
  50572. {
  50573. }
  50574. void ResizableCornerComponent::paint (Graphics& g)
  50575. {
  50576. getLookAndFeel()
  50577. .drawCornerResizer (g, getWidth(), getHeight(),
  50578. isMouseOverOrDragging(),
  50579. isMouseButtonDown());
  50580. }
  50581. void ResizableCornerComponent::mouseDown (const MouseEvent&)
  50582. {
  50583. if (component == 0)
  50584. {
  50585. jassertfalse; // You've deleted the component that this resizer is supposed to be controlling!
  50586. return;
  50587. }
  50588. originalBounds = component->getBounds();
  50589. if (constrainer != 0)
  50590. constrainer->resizeStart();
  50591. }
  50592. void ResizableCornerComponent::mouseDrag (const MouseEvent& e)
  50593. {
  50594. if (component == 0)
  50595. {
  50596. jassertfalse; // You've deleted the component that this resizer is supposed to be controlling!
  50597. return;
  50598. }
  50599. Rectangle<int> r (originalBounds.withSize (originalBounds.getWidth() + e.getDistanceFromDragStartX(),
  50600. originalBounds.getHeight() + e.getDistanceFromDragStartY()));
  50601. if (constrainer != 0)
  50602. constrainer->setBoundsForComponent (component, r, false, false, true, true);
  50603. else
  50604. component->setBounds (r);
  50605. }
  50606. void ResizableCornerComponent::mouseUp (const MouseEvent&)
  50607. {
  50608. if (constrainer != 0)
  50609. constrainer->resizeStart();
  50610. }
  50611. bool ResizableCornerComponent::hitTest (int x, int y)
  50612. {
  50613. if (getWidth() <= 0)
  50614. return false;
  50615. const int yAtX = getHeight() - (getHeight() * x / getWidth());
  50616. return y >= yAtX - getHeight() / 4;
  50617. }
  50618. END_JUCE_NAMESPACE
  50619. /*** End of inlined file: juce_ResizableCornerComponent.cpp ***/
  50620. /*** Start of inlined file: juce_ScrollBar.cpp ***/
  50621. BEGIN_JUCE_NAMESPACE
  50622. class ScrollBar::ScrollbarButton : public Button
  50623. {
  50624. public:
  50625. int direction;
  50626. ScrollbarButton (const int direction_, ScrollBar& owner_)
  50627. : Button (String::empty),
  50628. direction (direction_),
  50629. owner (owner_)
  50630. {
  50631. setWantsKeyboardFocus (false);
  50632. }
  50633. ~ScrollbarButton()
  50634. {
  50635. }
  50636. void paintButton (Graphics& g, bool over, bool down)
  50637. {
  50638. getLookAndFeel()
  50639. .drawScrollbarButton (g, owner,
  50640. getWidth(), getHeight(),
  50641. direction,
  50642. owner.isVertical(),
  50643. over, down);
  50644. }
  50645. void clicked()
  50646. {
  50647. owner.moveScrollbarInSteps ((direction == 1 || direction == 2) ? 1 : -1);
  50648. }
  50649. juce_UseDebuggingNewOperator
  50650. private:
  50651. ScrollBar& owner;
  50652. ScrollbarButton (const ScrollbarButton&);
  50653. ScrollbarButton& operator= (const ScrollbarButton&);
  50654. };
  50655. ScrollBar::ScrollBar (const bool vertical_,
  50656. const bool buttonsAreVisible)
  50657. : totalRange (0.0, 1.0),
  50658. visibleRange (0.0, 0.1),
  50659. singleStepSize (0.1),
  50660. thumbAreaStart (0),
  50661. thumbAreaSize (0),
  50662. thumbStart (0),
  50663. thumbSize (0),
  50664. initialDelayInMillisecs (100),
  50665. repeatDelayInMillisecs (50),
  50666. minimumDelayInMillisecs (10),
  50667. vertical (vertical_),
  50668. isDraggingThumb (false),
  50669. autohides (true)
  50670. {
  50671. setButtonVisibility (buttonsAreVisible);
  50672. setRepaintsOnMouseActivity (true);
  50673. setFocusContainer (true);
  50674. }
  50675. ScrollBar::~ScrollBar()
  50676. {
  50677. upButton = 0;
  50678. downButton = 0;
  50679. }
  50680. void ScrollBar::setRangeLimits (const Range<double>& newRangeLimit)
  50681. {
  50682. if (totalRange != newRangeLimit)
  50683. {
  50684. totalRange = newRangeLimit;
  50685. setCurrentRange (visibleRange);
  50686. updateThumbPosition();
  50687. }
  50688. }
  50689. void ScrollBar::setRangeLimits (const double newMinimum, const double newMaximum)
  50690. {
  50691. jassert (newMaximum >= newMinimum); // these can't be the wrong way round!
  50692. setRangeLimits (Range<double> (newMinimum, newMaximum));
  50693. }
  50694. void ScrollBar::setCurrentRange (const Range<double>& newRange)
  50695. {
  50696. const Range<double> constrainedRange (totalRange.constrainRange (newRange));
  50697. if (visibleRange != constrainedRange)
  50698. {
  50699. visibleRange = constrainedRange;
  50700. updateThumbPosition();
  50701. triggerAsyncUpdate();
  50702. }
  50703. }
  50704. void ScrollBar::setCurrentRange (const double newStart, const double newSize)
  50705. {
  50706. setCurrentRange (Range<double> (newStart, newStart + newSize));
  50707. }
  50708. void ScrollBar::setCurrentRangeStart (const double newStart)
  50709. {
  50710. setCurrentRange (visibleRange.movedToStartAt (newStart));
  50711. }
  50712. void ScrollBar::setSingleStepSize (const double newSingleStepSize)
  50713. {
  50714. singleStepSize = newSingleStepSize;
  50715. }
  50716. void ScrollBar::moveScrollbarInSteps (const int howManySteps)
  50717. {
  50718. setCurrentRange (visibleRange + howManySteps * singleStepSize);
  50719. }
  50720. void ScrollBar::moveScrollbarInPages (const int howManyPages)
  50721. {
  50722. setCurrentRange (visibleRange + howManyPages * visibleRange.getLength());
  50723. }
  50724. void ScrollBar::scrollToTop()
  50725. {
  50726. setCurrentRange (visibleRange.movedToStartAt (getMinimumRangeLimit()));
  50727. }
  50728. void ScrollBar::scrollToBottom()
  50729. {
  50730. setCurrentRange (visibleRange.movedToEndAt (getMaximumRangeLimit()));
  50731. }
  50732. void ScrollBar::setButtonRepeatSpeed (const int initialDelayInMillisecs_,
  50733. const int repeatDelayInMillisecs_,
  50734. const int minimumDelayInMillisecs_)
  50735. {
  50736. initialDelayInMillisecs = initialDelayInMillisecs_;
  50737. repeatDelayInMillisecs = repeatDelayInMillisecs_;
  50738. minimumDelayInMillisecs = minimumDelayInMillisecs_;
  50739. if (upButton != 0)
  50740. {
  50741. upButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50742. downButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50743. }
  50744. }
  50745. void ScrollBar::addListener (Listener* const listener)
  50746. {
  50747. listeners.add (listener);
  50748. }
  50749. void ScrollBar::removeListener (Listener* const listener)
  50750. {
  50751. listeners.remove (listener);
  50752. }
  50753. void ScrollBar::handleAsyncUpdate()
  50754. {
  50755. double start = visibleRange.getStart(); // (need to use a temp variable for VC7 compatibility)
  50756. listeners.call (&ScrollBar::Listener::scrollBarMoved, this, start);
  50757. }
  50758. void ScrollBar::updateThumbPosition()
  50759. {
  50760. int newThumbSize = roundToInt (totalRange.getLength() > 0 ? (visibleRange.getLength() * thumbAreaSize) / totalRange.getLength()
  50761. : thumbAreaSize);
  50762. if (newThumbSize < getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50763. newThumbSize = jmin (getLookAndFeel().getMinimumScrollbarThumbSize (*this), thumbAreaSize - 1);
  50764. if (newThumbSize > thumbAreaSize)
  50765. newThumbSize = thumbAreaSize;
  50766. int newThumbStart = thumbAreaStart;
  50767. if (totalRange.getLength() > visibleRange.getLength())
  50768. newThumbStart += roundToInt (((visibleRange.getStart() - totalRange.getStart()) * (thumbAreaSize - newThumbSize))
  50769. / (totalRange.getLength() - visibleRange.getLength()));
  50770. setVisible ((! autohides) || (totalRange.getLength() > visibleRange.getLength() && visibleRange.getLength() > 0.0));
  50771. if (thumbStart != newThumbStart || thumbSize != newThumbSize)
  50772. {
  50773. const int repaintStart = jmin (thumbStart, newThumbStart) - 4;
  50774. const int repaintSize = jmax (thumbStart + thumbSize, newThumbStart + newThumbSize) + 8 - repaintStart;
  50775. if (vertical)
  50776. repaint (0, repaintStart, getWidth(), repaintSize);
  50777. else
  50778. repaint (repaintStart, 0, repaintSize, getHeight());
  50779. thumbStart = newThumbStart;
  50780. thumbSize = newThumbSize;
  50781. }
  50782. }
  50783. void ScrollBar::setOrientation (const bool shouldBeVertical)
  50784. {
  50785. if (vertical != shouldBeVertical)
  50786. {
  50787. vertical = shouldBeVertical;
  50788. if (upButton != 0)
  50789. {
  50790. upButton->direction = vertical ? 0 : 3;
  50791. downButton->direction = vertical ? 2 : 1;
  50792. }
  50793. updateThumbPosition();
  50794. }
  50795. }
  50796. void ScrollBar::setButtonVisibility (const bool buttonsAreVisible)
  50797. {
  50798. upButton = 0;
  50799. downButton = 0;
  50800. if (buttonsAreVisible)
  50801. {
  50802. addAndMakeVisible (upButton = new ScrollbarButton (vertical ? 0 : 3, *this));
  50803. addAndMakeVisible (downButton = new ScrollbarButton (vertical ? 2 : 1, *this));
  50804. setButtonRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50805. }
  50806. updateThumbPosition();
  50807. }
  50808. void ScrollBar::setAutoHide (const bool shouldHideWhenFullRange)
  50809. {
  50810. autohides = shouldHideWhenFullRange;
  50811. updateThumbPosition();
  50812. }
  50813. bool ScrollBar::autoHides() const throw()
  50814. {
  50815. return autohides;
  50816. }
  50817. void ScrollBar::paint (Graphics& g)
  50818. {
  50819. if (thumbAreaSize > 0)
  50820. {
  50821. LookAndFeel& lf = getLookAndFeel();
  50822. const int thumb = (thumbAreaSize > lf.getMinimumScrollbarThumbSize (*this))
  50823. ? thumbSize : 0;
  50824. if (vertical)
  50825. {
  50826. lf.drawScrollbar (g, *this,
  50827. 0, thumbAreaStart,
  50828. getWidth(), thumbAreaSize,
  50829. vertical,
  50830. thumbStart, thumb,
  50831. isMouseOver(), isMouseButtonDown());
  50832. }
  50833. else
  50834. {
  50835. lf.drawScrollbar (g, *this,
  50836. thumbAreaStart, 0,
  50837. thumbAreaSize, getHeight(),
  50838. vertical,
  50839. thumbStart, thumb,
  50840. isMouseOver(), isMouseButtonDown());
  50841. }
  50842. }
  50843. }
  50844. void ScrollBar::lookAndFeelChanged()
  50845. {
  50846. setComponentEffect (getLookAndFeel().getScrollbarEffect());
  50847. }
  50848. void ScrollBar::resized()
  50849. {
  50850. const int length = ((vertical) ? getHeight() : getWidth());
  50851. const int buttonSize = (upButton != 0) ? jmin (getLookAndFeel().getScrollbarButtonSize (*this), (length >> 1))
  50852. : 0;
  50853. if (length < 32 + getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50854. {
  50855. thumbAreaStart = length >> 1;
  50856. thumbAreaSize = 0;
  50857. }
  50858. else
  50859. {
  50860. thumbAreaStart = buttonSize;
  50861. thumbAreaSize = length - (buttonSize << 1);
  50862. }
  50863. if (upButton != 0)
  50864. {
  50865. if (vertical)
  50866. {
  50867. upButton->setBounds (0, 0, getWidth(), buttonSize);
  50868. downButton->setBounds (0, thumbAreaStart + thumbAreaSize, getWidth(), buttonSize);
  50869. }
  50870. else
  50871. {
  50872. upButton->setBounds (0, 0, buttonSize, getHeight());
  50873. downButton->setBounds (thumbAreaStart + thumbAreaSize, 0, buttonSize, getHeight());
  50874. }
  50875. }
  50876. updateThumbPosition();
  50877. }
  50878. void ScrollBar::mouseDown (const MouseEvent& e)
  50879. {
  50880. isDraggingThumb = false;
  50881. lastMousePos = vertical ? e.y : e.x;
  50882. dragStartMousePos = lastMousePos;
  50883. dragStartRange = visibleRange.getStart();
  50884. if (dragStartMousePos < thumbStart)
  50885. {
  50886. moveScrollbarInPages (-1);
  50887. startTimer (400);
  50888. }
  50889. else if (dragStartMousePos >= thumbStart + thumbSize)
  50890. {
  50891. moveScrollbarInPages (1);
  50892. startTimer (400);
  50893. }
  50894. else
  50895. {
  50896. isDraggingThumb = (thumbAreaSize > getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50897. && (thumbAreaSize > thumbSize);
  50898. }
  50899. }
  50900. void ScrollBar::mouseDrag (const MouseEvent& e)
  50901. {
  50902. if (isDraggingThumb)
  50903. {
  50904. const int deltaPixels = ((vertical) ? e.y : e.x) - dragStartMousePos;
  50905. setCurrentRangeStart (dragStartRange
  50906. + deltaPixels * (totalRange.getLength() - visibleRange.getLength())
  50907. / (thumbAreaSize - thumbSize));
  50908. }
  50909. else
  50910. {
  50911. lastMousePos = (vertical) ? e.y : e.x;
  50912. }
  50913. }
  50914. void ScrollBar::mouseUp (const MouseEvent&)
  50915. {
  50916. isDraggingThumb = false;
  50917. stopTimer();
  50918. repaint();
  50919. }
  50920. void ScrollBar::mouseWheelMove (const MouseEvent&,
  50921. float wheelIncrementX,
  50922. float wheelIncrementY)
  50923. {
  50924. float increment = vertical ? wheelIncrementY : wheelIncrementX;
  50925. if (increment < 0)
  50926. increment = jmin (increment * 10.0f, -1.0f);
  50927. else if (increment > 0)
  50928. increment = jmax (increment * 10.0f, 1.0f);
  50929. setCurrentRange (visibleRange - singleStepSize * increment);
  50930. }
  50931. void ScrollBar::timerCallback()
  50932. {
  50933. if (isMouseButtonDown())
  50934. {
  50935. startTimer (40);
  50936. if (lastMousePos < thumbStart)
  50937. setCurrentRange (visibleRange - visibleRange.getLength());
  50938. else if (lastMousePos > thumbStart + thumbSize)
  50939. setCurrentRangeStart (visibleRange.getEnd());
  50940. }
  50941. else
  50942. {
  50943. stopTimer();
  50944. }
  50945. }
  50946. bool ScrollBar::keyPressed (const KeyPress& key)
  50947. {
  50948. if (! isVisible())
  50949. return false;
  50950. if (key.isKeyCode (KeyPress::upKey) || key.isKeyCode (KeyPress::leftKey))
  50951. moveScrollbarInSteps (-1);
  50952. else if (key.isKeyCode (KeyPress::downKey) || key.isKeyCode (KeyPress::rightKey))
  50953. moveScrollbarInSteps (1);
  50954. else if (key.isKeyCode (KeyPress::pageUpKey))
  50955. moveScrollbarInPages (-1);
  50956. else if (key.isKeyCode (KeyPress::pageDownKey))
  50957. moveScrollbarInPages (1);
  50958. else if (key.isKeyCode (KeyPress::homeKey))
  50959. scrollToTop();
  50960. else if (key.isKeyCode (KeyPress::endKey))
  50961. scrollToBottom();
  50962. else
  50963. return false;
  50964. return true;
  50965. }
  50966. END_JUCE_NAMESPACE
  50967. /*** End of inlined file: juce_ScrollBar.cpp ***/
  50968. /*** Start of inlined file: juce_StretchableLayoutManager.cpp ***/
  50969. BEGIN_JUCE_NAMESPACE
  50970. StretchableLayoutManager::StretchableLayoutManager()
  50971. : totalSize (0)
  50972. {
  50973. }
  50974. StretchableLayoutManager::~StretchableLayoutManager()
  50975. {
  50976. }
  50977. void StretchableLayoutManager::clearAllItems()
  50978. {
  50979. items.clear();
  50980. totalSize = 0;
  50981. }
  50982. void StretchableLayoutManager::setItemLayout (const int itemIndex,
  50983. const double minimumSize,
  50984. const double maximumSize,
  50985. const double preferredSize)
  50986. {
  50987. ItemLayoutProperties* layout = getInfoFor (itemIndex);
  50988. if (layout == 0)
  50989. {
  50990. layout = new ItemLayoutProperties();
  50991. layout->itemIndex = itemIndex;
  50992. int i;
  50993. for (i = 0; i < items.size(); ++i)
  50994. if (items.getUnchecked (i)->itemIndex > itemIndex)
  50995. break;
  50996. items.insert (i, layout);
  50997. }
  50998. layout->minSize = minimumSize;
  50999. layout->maxSize = maximumSize;
  51000. layout->preferredSize = preferredSize;
  51001. layout->currentSize = 0;
  51002. }
  51003. bool StretchableLayoutManager::getItemLayout (const int itemIndex,
  51004. double& minimumSize,
  51005. double& maximumSize,
  51006. double& preferredSize) const
  51007. {
  51008. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  51009. if (layout != 0)
  51010. {
  51011. minimumSize = layout->minSize;
  51012. maximumSize = layout->maxSize;
  51013. preferredSize = layout->preferredSize;
  51014. return true;
  51015. }
  51016. return false;
  51017. }
  51018. void StretchableLayoutManager::setTotalSize (const int newTotalSize)
  51019. {
  51020. totalSize = newTotalSize;
  51021. fitComponentsIntoSpace (0, items.size(), totalSize, 0);
  51022. }
  51023. int StretchableLayoutManager::getItemCurrentPosition (const int itemIndex) const
  51024. {
  51025. int pos = 0;
  51026. for (int i = 0; i < itemIndex; ++i)
  51027. {
  51028. const ItemLayoutProperties* const layout = getInfoFor (i);
  51029. if (layout != 0)
  51030. pos += layout->currentSize;
  51031. }
  51032. return pos;
  51033. }
  51034. int StretchableLayoutManager::getItemCurrentAbsoluteSize (const int itemIndex) const
  51035. {
  51036. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  51037. if (layout != 0)
  51038. return layout->currentSize;
  51039. return 0;
  51040. }
  51041. double StretchableLayoutManager::getItemCurrentRelativeSize (const int itemIndex) const
  51042. {
  51043. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  51044. if (layout != 0)
  51045. return -layout->currentSize / (double) totalSize;
  51046. return 0;
  51047. }
  51048. void StretchableLayoutManager::setItemPosition (const int itemIndex,
  51049. int newPosition)
  51050. {
  51051. for (int i = items.size(); --i >= 0;)
  51052. {
  51053. const ItemLayoutProperties* const layout = items.getUnchecked(i);
  51054. if (layout->itemIndex == itemIndex)
  51055. {
  51056. int realTotalSize = jmax (totalSize, getMinimumSizeOfItems (0, items.size()));
  51057. const int minSizeAfterThisComp = getMinimumSizeOfItems (i, items.size());
  51058. const int maxSizeAfterThisComp = getMaximumSizeOfItems (i + 1, items.size());
  51059. newPosition = jmax (newPosition, totalSize - maxSizeAfterThisComp - layout->currentSize);
  51060. newPosition = jmin (newPosition, realTotalSize - minSizeAfterThisComp);
  51061. int endPos = fitComponentsIntoSpace (0, i, newPosition, 0);
  51062. endPos += layout->currentSize;
  51063. fitComponentsIntoSpace (i + 1, items.size(), totalSize - endPos, endPos);
  51064. updatePrefSizesToMatchCurrentPositions();
  51065. break;
  51066. }
  51067. }
  51068. }
  51069. void StretchableLayoutManager::layOutComponents (Component** const components,
  51070. int numComponents,
  51071. int x, int y, int w, int h,
  51072. const bool vertically,
  51073. const bool resizeOtherDimension)
  51074. {
  51075. setTotalSize (vertically ? h : w);
  51076. int pos = vertically ? y : x;
  51077. for (int i = 0; i < numComponents; ++i)
  51078. {
  51079. const ItemLayoutProperties* const layout = getInfoFor (i);
  51080. if (layout != 0)
  51081. {
  51082. Component* const c = components[i];
  51083. if (c != 0)
  51084. {
  51085. if (i == numComponents - 1)
  51086. {
  51087. // if it's the last item, crop it to exactly fit the available space..
  51088. if (resizeOtherDimension)
  51089. {
  51090. if (vertically)
  51091. c->setBounds (x, pos, w, jmax (layout->currentSize, h - pos));
  51092. else
  51093. c->setBounds (pos, y, jmax (layout->currentSize, w - pos), h);
  51094. }
  51095. else
  51096. {
  51097. if (vertically)
  51098. c->setBounds (c->getX(), pos, c->getWidth(), jmax (layout->currentSize, h - pos));
  51099. else
  51100. c->setBounds (pos, c->getY(), jmax (layout->currentSize, w - pos), c->getHeight());
  51101. }
  51102. }
  51103. else
  51104. {
  51105. if (resizeOtherDimension)
  51106. {
  51107. if (vertically)
  51108. c->setBounds (x, pos, w, layout->currentSize);
  51109. else
  51110. c->setBounds (pos, y, layout->currentSize, h);
  51111. }
  51112. else
  51113. {
  51114. if (vertically)
  51115. c->setBounds (c->getX(), pos, c->getWidth(), layout->currentSize);
  51116. else
  51117. c->setBounds (pos, c->getY(), layout->currentSize, c->getHeight());
  51118. }
  51119. }
  51120. }
  51121. pos += layout->currentSize;
  51122. }
  51123. }
  51124. }
  51125. StretchableLayoutManager::ItemLayoutProperties* StretchableLayoutManager::getInfoFor (const int itemIndex) const
  51126. {
  51127. for (int i = items.size(); --i >= 0;)
  51128. if (items.getUnchecked(i)->itemIndex == itemIndex)
  51129. return items.getUnchecked(i);
  51130. return 0;
  51131. }
  51132. int StretchableLayoutManager::fitComponentsIntoSpace (const int startIndex,
  51133. const int endIndex,
  51134. const int availableSpace,
  51135. int startPos)
  51136. {
  51137. // calculate the total sizes
  51138. int i;
  51139. double totalIdealSize = 0.0;
  51140. int totalMinimums = 0;
  51141. for (i = startIndex; i < endIndex; ++i)
  51142. {
  51143. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51144. layout->currentSize = sizeToRealSize (layout->minSize, totalSize);
  51145. totalMinimums += layout->currentSize;
  51146. totalIdealSize += sizeToRealSize (layout->preferredSize, totalSize);
  51147. }
  51148. if (totalIdealSize <= 0)
  51149. totalIdealSize = 1.0;
  51150. // now calc the best sizes..
  51151. int extraSpace = availableSpace - totalMinimums;
  51152. while (extraSpace > 0)
  51153. {
  51154. int numWantingMoreSpace = 0;
  51155. int numHavingTakenExtraSpace = 0;
  51156. // first figure out how many comps want a slice of the extra space..
  51157. for (i = startIndex; i < endIndex; ++i)
  51158. {
  51159. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51160. double sizeWanted = sizeToRealSize (layout->preferredSize, totalSize);
  51161. const int bestSize = jlimit (layout->currentSize,
  51162. jmax (layout->currentSize,
  51163. sizeToRealSize (layout->maxSize, totalSize)),
  51164. roundToInt (sizeWanted * availableSpace / totalIdealSize));
  51165. if (bestSize > layout->currentSize)
  51166. ++numWantingMoreSpace;
  51167. }
  51168. // ..share out the extra space..
  51169. for (i = startIndex; i < endIndex; ++i)
  51170. {
  51171. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51172. double sizeWanted = sizeToRealSize (layout->preferredSize, totalSize);
  51173. int bestSize = jlimit (layout->currentSize,
  51174. jmax (layout->currentSize, sizeToRealSize (layout->maxSize, totalSize)),
  51175. roundToInt (sizeWanted * availableSpace / totalIdealSize));
  51176. const int extraWanted = bestSize - layout->currentSize;
  51177. if (extraWanted > 0)
  51178. {
  51179. const int extraAllowed = jmin (extraWanted,
  51180. extraSpace / jmax (1, numWantingMoreSpace));
  51181. if (extraAllowed > 0)
  51182. {
  51183. ++numHavingTakenExtraSpace;
  51184. --numWantingMoreSpace;
  51185. layout->currentSize += extraAllowed;
  51186. extraSpace -= extraAllowed;
  51187. }
  51188. }
  51189. }
  51190. if (numHavingTakenExtraSpace <= 0)
  51191. break;
  51192. }
  51193. // ..and calculate the end position
  51194. for (i = startIndex; i < endIndex; ++i)
  51195. {
  51196. ItemLayoutProperties* const layout = items.getUnchecked(i);
  51197. startPos += layout->currentSize;
  51198. }
  51199. return startPos;
  51200. }
  51201. int StretchableLayoutManager::getMinimumSizeOfItems (const int startIndex,
  51202. const int endIndex) const
  51203. {
  51204. int totalMinimums = 0;
  51205. for (int i = startIndex; i < endIndex; ++i)
  51206. totalMinimums += sizeToRealSize (items.getUnchecked (i)->minSize, totalSize);
  51207. return totalMinimums;
  51208. }
  51209. int StretchableLayoutManager::getMaximumSizeOfItems (const int startIndex, const int endIndex) const
  51210. {
  51211. int totalMaximums = 0;
  51212. for (int i = startIndex; i < endIndex; ++i)
  51213. totalMaximums += sizeToRealSize (items.getUnchecked (i)->maxSize, totalSize);
  51214. return totalMaximums;
  51215. }
  51216. void StretchableLayoutManager::updatePrefSizesToMatchCurrentPositions()
  51217. {
  51218. for (int i = 0; i < items.size(); ++i)
  51219. {
  51220. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51221. layout->preferredSize
  51222. = (layout->preferredSize < 0) ? getItemCurrentRelativeSize (i)
  51223. : getItemCurrentAbsoluteSize (i);
  51224. }
  51225. }
  51226. int StretchableLayoutManager::sizeToRealSize (double size, int totalSpace)
  51227. {
  51228. if (size < 0)
  51229. size *= -totalSpace;
  51230. return roundToInt (size);
  51231. }
  51232. END_JUCE_NAMESPACE
  51233. /*** End of inlined file: juce_StretchableLayoutManager.cpp ***/
  51234. /*** Start of inlined file: juce_StretchableLayoutResizerBar.cpp ***/
  51235. BEGIN_JUCE_NAMESPACE
  51236. StretchableLayoutResizerBar::StretchableLayoutResizerBar (StretchableLayoutManager* layout_,
  51237. const int itemIndex_,
  51238. const bool isVertical_)
  51239. : layout (layout_),
  51240. itemIndex (itemIndex_),
  51241. isVertical (isVertical_)
  51242. {
  51243. setRepaintsOnMouseActivity (true);
  51244. setMouseCursor (MouseCursor (isVertical_ ? MouseCursor::LeftRightResizeCursor
  51245. : MouseCursor::UpDownResizeCursor));
  51246. }
  51247. StretchableLayoutResizerBar::~StretchableLayoutResizerBar()
  51248. {
  51249. }
  51250. void StretchableLayoutResizerBar::paint (Graphics& g)
  51251. {
  51252. getLookAndFeel().drawStretchableLayoutResizerBar (g,
  51253. getWidth(), getHeight(),
  51254. isVertical,
  51255. isMouseOver(),
  51256. isMouseButtonDown());
  51257. }
  51258. void StretchableLayoutResizerBar::mouseDown (const MouseEvent&)
  51259. {
  51260. mouseDownPos = layout->getItemCurrentPosition (itemIndex);
  51261. }
  51262. void StretchableLayoutResizerBar::mouseDrag (const MouseEvent& e)
  51263. {
  51264. const int desiredPos = mouseDownPos + (isVertical ? e.getDistanceFromDragStartX()
  51265. : e.getDistanceFromDragStartY());
  51266. layout->setItemPosition (itemIndex, desiredPos);
  51267. hasBeenMoved();
  51268. }
  51269. void StretchableLayoutResizerBar::hasBeenMoved()
  51270. {
  51271. if (getParentComponent() != 0)
  51272. getParentComponent()->resized();
  51273. }
  51274. END_JUCE_NAMESPACE
  51275. /*** End of inlined file: juce_StretchableLayoutResizerBar.cpp ***/
  51276. /*** Start of inlined file: juce_StretchableObjectResizer.cpp ***/
  51277. BEGIN_JUCE_NAMESPACE
  51278. StretchableObjectResizer::StretchableObjectResizer()
  51279. {
  51280. }
  51281. StretchableObjectResizer::~StretchableObjectResizer()
  51282. {
  51283. }
  51284. void StretchableObjectResizer::addItem (const double size,
  51285. const double minSize, const double maxSize,
  51286. const int order)
  51287. {
  51288. // the order must be >= 0 but less than the maximum integer value.
  51289. jassert (order >= 0 && order < std::numeric_limits<int>::max());
  51290. Item* const item = new Item();
  51291. item->size = size;
  51292. item->minSize = minSize;
  51293. item->maxSize = maxSize;
  51294. item->order = order;
  51295. items.add (item);
  51296. }
  51297. double StretchableObjectResizer::getItemSize (const int index) const throw()
  51298. {
  51299. const Item* const it = items [index];
  51300. return it != 0 ? it->size : 0;
  51301. }
  51302. void StretchableObjectResizer::resizeToFit (const double targetSize)
  51303. {
  51304. int order = 0;
  51305. for (;;)
  51306. {
  51307. double currentSize = 0;
  51308. double minSize = 0;
  51309. double maxSize = 0;
  51310. int nextHighestOrder = std::numeric_limits<int>::max();
  51311. for (int i = 0; i < items.size(); ++i)
  51312. {
  51313. const Item* const it = items.getUnchecked(i);
  51314. currentSize += it->size;
  51315. if (it->order <= order)
  51316. {
  51317. minSize += it->minSize;
  51318. maxSize += it->maxSize;
  51319. }
  51320. else
  51321. {
  51322. minSize += it->size;
  51323. maxSize += it->size;
  51324. nextHighestOrder = jmin (nextHighestOrder, it->order);
  51325. }
  51326. }
  51327. const double thisIterationTarget = jlimit (minSize, maxSize, targetSize);
  51328. if (thisIterationTarget >= currentSize)
  51329. {
  51330. const double availableExtraSpace = maxSize - currentSize;
  51331. const double targetAmountOfExtraSpace = thisIterationTarget - currentSize;
  51332. const double scale = targetAmountOfExtraSpace / availableExtraSpace;
  51333. for (int i = 0; i < items.size(); ++i)
  51334. {
  51335. Item* const it = items.getUnchecked(i);
  51336. if (it->order <= order)
  51337. it->size = jmin (it->maxSize, it->size + (it->maxSize - it->size) * scale);
  51338. }
  51339. }
  51340. else
  51341. {
  51342. const double amountOfSlack = currentSize - minSize;
  51343. const double targetAmountOfSlack = thisIterationTarget - minSize;
  51344. const double scale = targetAmountOfSlack / amountOfSlack;
  51345. for (int i = 0; i < items.size(); ++i)
  51346. {
  51347. Item* const it = items.getUnchecked(i);
  51348. if (it->order <= order)
  51349. it->size = jmax (it->minSize, it->minSize + (it->size - it->minSize) * scale);
  51350. }
  51351. }
  51352. if (nextHighestOrder < std::numeric_limits<int>::max())
  51353. order = nextHighestOrder;
  51354. else
  51355. break;
  51356. }
  51357. }
  51358. END_JUCE_NAMESPACE
  51359. /*** End of inlined file: juce_StretchableObjectResizer.cpp ***/
  51360. /*** Start of inlined file: juce_TabbedButtonBar.cpp ***/
  51361. BEGIN_JUCE_NAMESPACE
  51362. TabBarButton::TabBarButton (const String& name,
  51363. TabbedButtonBar* const owner_,
  51364. const int index)
  51365. : Button (name),
  51366. owner (owner_),
  51367. tabIndex (index),
  51368. overlapPixels (0)
  51369. {
  51370. shadow.setShadowProperties (2.2f, 0.7f, 0, 0);
  51371. setComponentEffect (&shadow);
  51372. setWantsKeyboardFocus (false);
  51373. }
  51374. TabBarButton::~TabBarButton()
  51375. {
  51376. }
  51377. void TabBarButton::paintButton (Graphics& g,
  51378. bool isMouseOverButton,
  51379. bool isButtonDown)
  51380. {
  51381. int x, y, w, h;
  51382. getActiveArea (x, y, w, h);
  51383. g.setOrigin (x, y);
  51384. getLookAndFeel()
  51385. .drawTabButton (g, w, h,
  51386. owner->getTabBackgroundColour (tabIndex),
  51387. tabIndex, getButtonText(), *this,
  51388. owner->getOrientation(),
  51389. isMouseOverButton, isButtonDown,
  51390. getToggleState());
  51391. }
  51392. void TabBarButton::clicked (const ModifierKeys& mods)
  51393. {
  51394. if (mods.isPopupMenu())
  51395. owner->popupMenuClickOnTab (tabIndex, getButtonText());
  51396. else
  51397. owner->setCurrentTabIndex (tabIndex);
  51398. }
  51399. bool TabBarButton::hitTest (int mx, int my)
  51400. {
  51401. int x, y, w, h;
  51402. getActiveArea (x, y, w, h);
  51403. if (owner->getOrientation() == TabbedButtonBar::TabsAtLeft
  51404. || owner->getOrientation() == TabbedButtonBar::TabsAtRight)
  51405. {
  51406. if (((unsigned int) mx) < (unsigned int) getWidth()
  51407. && my >= y + overlapPixels
  51408. && my < y + h - overlapPixels)
  51409. return true;
  51410. }
  51411. else
  51412. {
  51413. if (mx >= x + overlapPixels && mx < x + w - overlapPixels
  51414. && ((unsigned int) my) < (unsigned int) getHeight())
  51415. return true;
  51416. }
  51417. Path p;
  51418. getLookAndFeel()
  51419. .createTabButtonShape (p, w, h, tabIndex, getButtonText(), *this,
  51420. owner->getOrientation(),
  51421. false, false, getToggleState());
  51422. return p.contains ((float) (mx - x),
  51423. (float) (my - y));
  51424. }
  51425. int TabBarButton::getBestTabLength (const int depth)
  51426. {
  51427. return jlimit (depth * 2,
  51428. depth * 7,
  51429. getLookAndFeel().getTabButtonBestWidth (tabIndex, getButtonText(), depth, *this));
  51430. }
  51431. void TabBarButton::getActiveArea (int& x, int& y, int& w, int& h)
  51432. {
  51433. x = 0;
  51434. y = 0;
  51435. int r = getWidth();
  51436. int b = getHeight();
  51437. const int spaceAroundImage = getLookAndFeel().getTabButtonSpaceAroundImage();
  51438. if (owner->getOrientation() != TabbedButtonBar::TabsAtLeft)
  51439. r -= spaceAroundImage;
  51440. if (owner->getOrientation() != TabbedButtonBar::TabsAtRight)
  51441. x += spaceAroundImage;
  51442. if (owner->getOrientation() != TabbedButtonBar::TabsAtBottom)
  51443. y += spaceAroundImage;
  51444. if (owner->getOrientation() != TabbedButtonBar::TabsAtTop)
  51445. b -= spaceAroundImage;
  51446. w = r - x;
  51447. h = b - y;
  51448. }
  51449. class TabAreaBehindFrontButtonComponent : public Component
  51450. {
  51451. public:
  51452. TabAreaBehindFrontButtonComponent (TabbedButtonBar* const owner_)
  51453. : owner (owner_)
  51454. {
  51455. setInterceptsMouseClicks (false, false);
  51456. }
  51457. ~TabAreaBehindFrontButtonComponent()
  51458. {
  51459. }
  51460. void paint (Graphics& g)
  51461. {
  51462. getLookAndFeel()
  51463. .drawTabAreaBehindFrontButton (g, getWidth(), getHeight(),
  51464. *owner, owner->getOrientation());
  51465. }
  51466. void enablementChanged()
  51467. {
  51468. repaint();
  51469. }
  51470. private:
  51471. TabbedButtonBar* const owner;
  51472. TabAreaBehindFrontButtonComponent (const TabAreaBehindFrontButtonComponent&);
  51473. TabAreaBehindFrontButtonComponent& operator= (const TabAreaBehindFrontButtonComponent&);
  51474. };
  51475. TabbedButtonBar::TabbedButtonBar (const Orientation orientation_)
  51476. : orientation (orientation_),
  51477. currentTabIndex (-1)
  51478. {
  51479. setInterceptsMouseClicks (false, true);
  51480. addAndMakeVisible (behindFrontTab = new TabAreaBehindFrontButtonComponent (this));
  51481. setFocusContainer (true);
  51482. }
  51483. TabbedButtonBar::~TabbedButtonBar()
  51484. {
  51485. extraTabsButton = 0;
  51486. deleteAllChildren();
  51487. }
  51488. void TabbedButtonBar::setOrientation (const Orientation newOrientation)
  51489. {
  51490. orientation = newOrientation;
  51491. for (int i = getNumChildComponents(); --i >= 0;)
  51492. getChildComponent (i)->resized();
  51493. resized();
  51494. }
  51495. TabBarButton* TabbedButtonBar::createTabButton (const String& name, const int index)
  51496. {
  51497. return new TabBarButton (name, this, index);
  51498. }
  51499. void TabbedButtonBar::clearTabs()
  51500. {
  51501. tabs.clear();
  51502. tabColours.clear();
  51503. currentTabIndex = -1;
  51504. extraTabsButton = 0;
  51505. removeChildComponent (behindFrontTab);
  51506. deleteAllChildren();
  51507. addChildComponent (behindFrontTab);
  51508. setCurrentTabIndex (-1);
  51509. }
  51510. void TabbedButtonBar::addTab (const String& tabName,
  51511. const Colour& tabBackgroundColour,
  51512. int insertIndex)
  51513. {
  51514. jassert (tabName.isNotEmpty()); // you have to give them all a name..
  51515. if (tabName.isNotEmpty())
  51516. {
  51517. if (((unsigned int) insertIndex) > (unsigned int) tabs.size())
  51518. insertIndex = tabs.size();
  51519. for (int i = tabs.size(); --i >= insertIndex;)
  51520. {
  51521. TabBarButton* const tb = getTabButton (i);
  51522. if (tb != 0)
  51523. tb->tabIndex++;
  51524. }
  51525. tabs.insert (insertIndex, tabName);
  51526. tabColours.insert (insertIndex, tabBackgroundColour);
  51527. TabBarButton* const tb = createTabButton (tabName, insertIndex);
  51528. jassert (tb != 0); // your createTabButton() mustn't return zero!
  51529. addAndMakeVisible (tb, insertIndex);
  51530. resized();
  51531. if (currentTabIndex < 0)
  51532. setCurrentTabIndex (0);
  51533. }
  51534. }
  51535. void TabbedButtonBar::setTabName (const int tabIndex,
  51536. const String& newName)
  51537. {
  51538. if (((unsigned int) tabIndex) < (unsigned int) tabs.size()
  51539. && tabs[tabIndex] != newName)
  51540. {
  51541. tabs.set (tabIndex, newName);
  51542. TabBarButton* const tb = getTabButton (tabIndex);
  51543. if (tb != 0)
  51544. tb->setButtonText (newName);
  51545. resized();
  51546. }
  51547. }
  51548. void TabbedButtonBar::removeTab (const int tabIndex)
  51549. {
  51550. if (((unsigned int) tabIndex) < (unsigned int) tabs.size())
  51551. {
  51552. const int oldTabIndex = currentTabIndex;
  51553. if (currentTabIndex == tabIndex)
  51554. currentTabIndex = -1;
  51555. tabs.remove (tabIndex);
  51556. tabColours.remove (tabIndex);
  51557. delete getTabButton (tabIndex);
  51558. for (int i = tabIndex + 1; i <= tabs.size(); ++i)
  51559. {
  51560. TabBarButton* const tb = getTabButton (i);
  51561. if (tb != 0)
  51562. tb->tabIndex--;
  51563. }
  51564. resized();
  51565. setCurrentTabIndex (jlimit (0, jmax (0, tabs.size() - 1), oldTabIndex));
  51566. }
  51567. }
  51568. void TabbedButtonBar::moveTab (const int currentIndex,
  51569. const int newIndex)
  51570. {
  51571. tabs.move (currentIndex, newIndex);
  51572. tabColours.move (currentIndex, newIndex);
  51573. resized();
  51574. }
  51575. int TabbedButtonBar::getNumTabs() const
  51576. {
  51577. return tabs.size();
  51578. }
  51579. const StringArray TabbedButtonBar::getTabNames() const
  51580. {
  51581. return tabs;
  51582. }
  51583. void TabbedButtonBar::setCurrentTabIndex (int newIndex, const bool sendChangeMessage_)
  51584. {
  51585. if (currentTabIndex != newIndex)
  51586. {
  51587. if (((unsigned int) newIndex) >= (unsigned int) tabs.size())
  51588. newIndex = -1;
  51589. currentTabIndex = newIndex;
  51590. for (int i = 0; i < getNumChildComponents(); ++i)
  51591. {
  51592. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  51593. if (tb != 0)
  51594. tb->setToggleState (tb->tabIndex == newIndex, false);
  51595. }
  51596. resized();
  51597. if (sendChangeMessage_)
  51598. sendChangeMessage (this);
  51599. currentTabChanged (newIndex, newIndex >= 0 ? tabs [newIndex] : String::empty);
  51600. }
  51601. }
  51602. TabBarButton* TabbedButtonBar::getTabButton (const int index) const
  51603. {
  51604. for (int i = getNumChildComponents(); --i >= 0;)
  51605. {
  51606. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  51607. if (tb != 0 && tb->tabIndex == index)
  51608. return tb;
  51609. }
  51610. return 0;
  51611. }
  51612. void TabbedButtonBar::lookAndFeelChanged()
  51613. {
  51614. extraTabsButton = 0;
  51615. resized();
  51616. }
  51617. void TabbedButtonBar::resized()
  51618. {
  51619. const double minimumScale = 0.7;
  51620. int depth = getWidth();
  51621. int length = getHeight();
  51622. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  51623. swapVariables (depth, length);
  51624. const int overlap = getLookAndFeel().getTabButtonOverlap (depth)
  51625. + getLookAndFeel().getTabButtonSpaceAroundImage() * 2;
  51626. int i, totalLength = overlap;
  51627. int numVisibleButtons = tabs.size();
  51628. for (i = 0; i < getNumChildComponents(); ++i)
  51629. {
  51630. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  51631. if (tb != 0)
  51632. {
  51633. totalLength += tb->getBestTabLength (depth) - overlap;
  51634. tb->overlapPixels = overlap / 2;
  51635. }
  51636. }
  51637. double scale = 1.0;
  51638. if (totalLength > length)
  51639. scale = jmax (minimumScale, length / (double) totalLength);
  51640. const bool isTooBig = totalLength * scale > length;
  51641. int tabsButtonPos = 0;
  51642. if (isTooBig)
  51643. {
  51644. if (extraTabsButton == 0)
  51645. {
  51646. addAndMakeVisible (extraTabsButton = getLookAndFeel().createTabBarExtrasButton());
  51647. extraTabsButton->addButtonListener (this);
  51648. extraTabsButton->setAlwaysOnTop (true);
  51649. extraTabsButton->setTriggeredOnMouseDown (true);
  51650. }
  51651. const int buttonSize = jmin (proportionOfWidth (0.7f), proportionOfHeight (0.7f));
  51652. extraTabsButton->setSize (buttonSize, buttonSize);
  51653. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  51654. {
  51655. tabsButtonPos = getWidth() - buttonSize / 2 - 1;
  51656. extraTabsButton->setCentrePosition (tabsButtonPos, getHeight() / 2);
  51657. }
  51658. else
  51659. {
  51660. tabsButtonPos = getHeight() - buttonSize / 2 - 1;
  51661. extraTabsButton->setCentrePosition (getWidth() / 2, tabsButtonPos);
  51662. }
  51663. totalLength = 0;
  51664. for (i = 0; i < tabs.size(); ++i)
  51665. {
  51666. TabBarButton* const tb = getTabButton (i);
  51667. if (tb != 0)
  51668. {
  51669. const int newLength = totalLength + tb->getBestTabLength (depth);
  51670. if (i > 0 && newLength * minimumScale > tabsButtonPos)
  51671. {
  51672. totalLength += overlap;
  51673. break;
  51674. }
  51675. numVisibleButtons = i + 1;
  51676. totalLength = newLength - overlap;
  51677. }
  51678. }
  51679. scale = jmax (minimumScale, tabsButtonPos / (double) totalLength);
  51680. }
  51681. else
  51682. {
  51683. extraTabsButton = 0;
  51684. }
  51685. int pos = 0;
  51686. TabBarButton* frontTab = 0;
  51687. for (i = 0; i < tabs.size(); ++i)
  51688. {
  51689. TabBarButton* const tb = getTabButton (i);
  51690. if (tb != 0)
  51691. {
  51692. const int bestLength = roundToInt (scale * tb->getBestTabLength (depth));
  51693. if (i < numVisibleButtons)
  51694. {
  51695. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  51696. tb->setBounds (pos, 0, bestLength, getHeight());
  51697. else
  51698. tb->setBounds (0, pos, getWidth(), bestLength);
  51699. tb->toBack();
  51700. if (tb->tabIndex == currentTabIndex)
  51701. frontTab = tb;
  51702. tb->setVisible (true);
  51703. }
  51704. else
  51705. {
  51706. tb->setVisible (false);
  51707. }
  51708. pos += bestLength - overlap;
  51709. }
  51710. }
  51711. behindFrontTab->setBounds (getLocalBounds());
  51712. if (frontTab != 0)
  51713. {
  51714. frontTab->toFront (false);
  51715. behindFrontTab->toBehind (frontTab);
  51716. }
  51717. }
  51718. const Colour TabbedButtonBar::getTabBackgroundColour (const int tabIndex)
  51719. {
  51720. return tabColours [tabIndex];
  51721. }
  51722. void TabbedButtonBar::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  51723. {
  51724. if (((unsigned int) tabIndex) < (unsigned int) tabColours.size()
  51725. && tabColours [tabIndex] != newColour)
  51726. {
  51727. tabColours.set (tabIndex, newColour);
  51728. repaint();
  51729. }
  51730. }
  51731. void TabbedButtonBar::buttonClicked (Button* button)
  51732. {
  51733. if (button == extraTabsButton)
  51734. {
  51735. PopupMenu m;
  51736. for (int i = 0; i < tabs.size(); ++i)
  51737. {
  51738. TabBarButton* const tb = getTabButton (i);
  51739. if (tb != 0 && ! tb->isVisible())
  51740. m.addItem (tb->tabIndex + 1, tabs[i], true, i == currentTabIndex);
  51741. }
  51742. const int res = m.showAt (extraTabsButton);
  51743. if (res != 0)
  51744. setCurrentTabIndex (res - 1);
  51745. }
  51746. }
  51747. void TabbedButtonBar::currentTabChanged (const int, const String&)
  51748. {
  51749. }
  51750. void TabbedButtonBar::popupMenuClickOnTab (const int, const String&)
  51751. {
  51752. }
  51753. END_JUCE_NAMESPACE
  51754. /*** End of inlined file: juce_TabbedButtonBar.cpp ***/
  51755. /*** Start of inlined file: juce_TabbedComponent.cpp ***/
  51756. BEGIN_JUCE_NAMESPACE
  51757. class TabCompButtonBar : public TabbedButtonBar
  51758. {
  51759. public:
  51760. TabCompButtonBar (TabbedComponent* const owner_,
  51761. const TabbedButtonBar::Orientation orientation_)
  51762. : TabbedButtonBar (orientation_),
  51763. owner (owner_)
  51764. {
  51765. }
  51766. ~TabCompButtonBar()
  51767. {
  51768. }
  51769. void currentTabChanged (int newCurrentTabIndex, const String& newTabName)
  51770. {
  51771. owner->changeCallback (newCurrentTabIndex, newTabName);
  51772. }
  51773. void popupMenuClickOnTab (int tabIndex, const String& tabName)
  51774. {
  51775. owner->popupMenuClickOnTab (tabIndex, tabName);
  51776. }
  51777. const Colour getTabBackgroundColour (const int tabIndex)
  51778. {
  51779. return owner->tabs->getTabBackgroundColour (tabIndex);
  51780. }
  51781. TabBarButton* createTabButton (const String& tabName, int tabIndex)
  51782. {
  51783. return owner->createTabButton (tabName, tabIndex);
  51784. }
  51785. juce_UseDebuggingNewOperator
  51786. private:
  51787. TabbedComponent* const owner;
  51788. TabCompButtonBar (const TabCompButtonBar&);
  51789. TabCompButtonBar& operator= (const TabCompButtonBar&);
  51790. };
  51791. TabbedComponent::TabbedComponent (const TabbedButtonBar::Orientation orientation)
  51792. : panelComponent (0),
  51793. tabDepth (30),
  51794. outlineThickness (1),
  51795. edgeIndent (0)
  51796. {
  51797. addAndMakeVisible (tabs = new TabCompButtonBar (this, orientation));
  51798. }
  51799. TabbedComponent::~TabbedComponent()
  51800. {
  51801. clearTabs();
  51802. delete tabs;
  51803. }
  51804. void TabbedComponent::setOrientation (const TabbedButtonBar::Orientation orientation)
  51805. {
  51806. tabs->setOrientation (orientation);
  51807. resized();
  51808. }
  51809. TabbedButtonBar::Orientation TabbedComponent::getOrientation() const throw()
  51810. {
  51811. return tabs->getOrientation();
  51812. }
  51813. void TabbedComponent::setTabBarDepth (const int newDepth)
  51814. {
  51815. if (tabDepth != newDepth)
  51816. {
  51817. tabDepth = newDepth;
  51818. resized();
  51819. }
  51820. }
  51821. TabBarButton* TabbedComponent::createTabButton (const String& tabName, const int tabIndex)
  51822. {
  51823. return new TabBarButton (tabName, tabs, tabIndex);
  51824. }
  51825. const Identifier TabbedComponent::deleteComponentId ("deleteByTabComp_");
  51826. void TabbedComponent::clearTabs()
  51827. {
  51828. if (panelComponent != 0)
  51829. {
  51830. panelComponent->setVisible (false);
  51831. removeChildComponent (panelComponent);
  51832. panelComponent = 0;
  51833. }
  51834. tabs->clearTabs();
  51835. for (int i = contentComponents.size(); --i >= 0;)
  51836. {
  51837. Component* const c = contentComponents.getUnchecked(i);
  51838. // be careful not to delete these components until they've been removed from the tab component
  51839. jassert (c == 0 || c->isValidComponent());
  51840. if (c != 0 && (bool) c->getProperties() [deleteComponentId])
  51841. delete c;
  51842. }
  51843. contentComponents.clear();
  51844. }
  51845. void TabbedComponent::addTab (const String& tabName,
  51846. const Colour& tabBackgroundColour,
  51847. Component* const contentComponent,
  51848. const bool deleteComponentWhenNotNeeded,
  51849. const int insertIndex)
  51850. {
  51851. contentComponents.insert (insertIndex, contentComponent);
  51852. if (contentComponent != 0)
  51853. contentComponent->getProperties().set (deleteComponentId, deleteComponentWhenNotNeeded);
  51854. tabs->addTab (tabName, tabBackgroundColour, insertIndex);
  51855. }
  51856. void TabbedComponent::setTabName (const int tabIndex, const String& newName)
  51857. {
  51858. tabs->setTabName (tabIndex, newName);
  51859. }
  51860. void TabbedComponent::removeTab (const int tabIndex)
  51861. {
  51862. Component* const c = contentComponents [tabIndex];
  51863. if (c != 0 && (bool) c->getProperties() [deleteComponentId])
  51864. {
  51865. if (c == panelComponent)
  51866. panelComponent = 0;
  51867. delete c;
  51868. }
  51869. contentComponents.remove (tabIndex);
  51870. tabs->removeTab (tabIndex);
  51871. }
  51872. int TabbedComponent::getNumTabs() const
  51873. {
  51874. return tabs->getNumTabs();
  51875. }
  51876. const StringArray TabbedComponent::getTabNames() const
  51877. {
  51878. return tabs->getTabNames();
  51879. }
  51880. Component* TabbedComponent::getTabContentComponent (const int tabIndex) const throw()
  51881. {
  51882. return contentComponents [tabIndex];
  51883. }
  51884. const Colour TabbedComponent::getTabBackgroundColour (const int tabIndex) const throw()
  51885. {
  51886. return tabs->getTabBackgroundColour (tabIndex);
  51887. }
  51888. void TabbedComponent::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  51889. {
  51890. tabs->setTabBackgroundColour (tabIndex, newColour);
  51891. if (getCurrentTabIndex() == tabIndex)
  51892. repaint();
  51893. }
  51894. void TabbedComponent::setCurrentTabIndex (const int newTabIndex, const bool sendChangeMessage)
  51895. {
  51896. tabs->setCurrentTabIndex (newTabIndex, sendChangeMessage);
  51897. }
  51898. int TabbedComponent::getCurrentTabIndex() const
  51899. {
  51900. return tabs->getCurrentTabIndex();
  51901. }
  51902. const String& TabbedComponent::getCurrentTabName() const
  51903. {
  51904. return tabs->getCurrentTabName();
  51905. }
  51906. void TabbedComponent::setOutline (int thickness)
  51907. {
  51908. outlineThickness = thickness;
  51909. repaint();
  51910. }
  51911. void TabbedComponent::setIndent (const int indentThickness)
  51912. {
  51913. edgeIndent = indentThickness;
  51914. }
  51915. void TabbedComponent::paint (Graphics& g)
  51916. {
  51917. g.fillAll (findColour (backgroundColourId));
  51918. const TabbedButtonBar::Orientation o = getOrientation();
  51919. int x = 0;
  51920. int y = 0;
  51921. int r = getWidth();
  51922. int b = getHeight();
  51923. if (o == TabbedButtonBar::TabsAtTop)
  51924. y += tabDepth;
  51925. else if (o == TabbedButtonBar::TabsAtBottom)
  51926. b -= tabDepth;
  51927. else if (o == TabbedButtonBar::TabsAtLeft)
  51928. x += tabDepth;
  51929. else if (o == TabbedButtonBar::TabsAtRight)
  51930. r -= tabDepth;
  51931. g.reduceClipRegion (x, y, r - x, b - y);
  51932. g.fillAll (tabs->getTabBackgroundColour (getCurrentTabIndex()));
  51933. if (outlineThickness > 0)
  51934. {
  51935. if (o == TabbedButtonBar::TabsAtTop)
  51936. --y;
  51937. else if (o == TabbedButtonBar::TabsAtBottom)
  51938. ++b;
  51939. else if (o == TabbedButtonBar::TabsAtLeft)
  51940. --x;
  51941. else if (o == TabbedButtonBar::TabsAtRight)
  51942. ++r;
  51943. g.setColour (findColour (outlineColourId));
  51944. g.drawRect (x, y, r - x, b - y, outlineThickness);
  51945. }
  51946. }
  51947. void TabbedComponent::resized()
  51948. {
  51949. const TabbedButtonBar::Orientation o = getOrientation();
  51950. const int indent = edgeIndent + outlineThickness;
  51951. BorderSize indents (indent);
  51952. if (o == TabbedButtonBar::TabsAtTop)
  51953. {
  51954. tabs->setBounds (0, 0, getWidth(), tabDepth);
  51955. indents.setTop (tabDepth + edgeIndent);
  51956. }
  51957. else if (o == TabbedButtonBar::TabsAtBottom)
  51958. {
  51959. tabs->setBounds (0, getHeight() - tabDepth, getWidth(), tabDepth);
  51960. indents.setBottom (tabDepth + edgeIndent);
  51961. }
  51962. else if (o == TabbedButtonBar::TabsAtLeft)
  51963. {
  51964. tabs->setBounds (0, 0, tabDepth, getHeight());
  51965. indents.setLeft (tabDepth + edgeIndent);
  51966. }
  51967. else if (o == TabbedButtonBar::TabsAtRight)
  51968. {
  51969. tabs->setBounds (getWidth() - tabDepth, 0, tabDepth, getHeight());
  51970. indents.setRight (tabDepth + edgeIndent);
  51971. }
  51972. const Rectangle<int> bounds (indents.subtractedFrom (getLocalBounds()));
  51973. for (int i = contentComponents.size(); --i >= 0;)
  51974. if (contentComponents.getUnchecked (i) != 0)
  51975. contentComponents.getUnchecked (i)->setBounds (bounds);
  51976. }
  51977. void TabbedComponent::lookAndFeelChanged()
  51978. {
  51979. for (int i = contentComponents.size(); --i >= 0;)
  51980. if (contentComponents.getUnchecked (i) != 0)
  51981. contentComponents.getUnchecked (i)->lookAndFeelChanged();
  51982. }
  51983. void TabbedComponent::changeCallback (const int newCurrentTabIndex,
  51984. const String& newTabName)
  51985. {
  51986. if (panelComponent != 0)
  51987. {
  51988. panelComponent->setVisible (false);
  51989. removeChildComponent (panelComponent);
  51990. panelComponent = 0;
  51991. }
  51992. if (getCurrentTabIndex() >= 0)
  51993. {
  51994. panelComponent = contentComponents [getCurrentTabIndex()];
  51995. if (panelComponent != 0)
  51996. {
  51997. // do these ops as two stages instead of addAndMakeVisible() so that the
  51998. // component has always got a parent when it gets the visibilityChanged() callback
  51999. addChildComponent (panelComponent);
  52000. panelComponent->setVisible (true);
  52001. panelComponent->toFront (true);
  52002. }
  52003. repaint();
  52004. }
  52005. resized();
  52006. currentTabChanged (newCurrentTabIndex, newTabName);
  52007. }
  52008. void TabbedComponent::currentTabChanged (const int, const String&)
  52009. {
  52010. }
  52011. void TabbedComponent::popupMenuClickOnTab (const int, const String&)
  52012. {
  52013. }
  52014. END_JUCE_NAMESPACE
  52015. /*** End of inlined file: juce_TabbedComponent.cpp ***/
  52016. /*** Start of inlined file: juce_Viewport.cpp ***/
  52017. BEGIN_JUCE_NAMESPACE
  52018. Viewport::Viewport (const String& componentName)
  52019. : Component (componentName),
  52020. scrollBarThickness (0),
  52021. singleStepX (16),
  52022. singleStepY (16),
  52023. showHScrollbar (true),
  52024. showVScrollbar (true),
  52025. verticalScrollBar (true),
  52026. horizontalScrollBar (false)
  52027. {
  52028. // content holder is used to clip the contents so they don't overlap the scrollbars
  52029. addAndMakeVisible (&contentHolder);
  52030. contentHolder.setInterceptsMouseClicks (false, true);
  52031. addChildComponent (&verticalScrollBar);
  52032. addChildComponent (&horizontalScrollBar);
  52033. verticalScrollBar.addListener (this);
  52034. horizontalScrollBar.addListener (this);
  52035. setInterceptsMouseClicks (false, true);
  52036. setWantsKeyboardFocus (true);
  52037. }
  52038. Viewport::~Viewport()
  52039. {
  52040. contentHolder.deleteAllChildren();
  52041. }
  52042. void Viewport::visibleAreaChanged (int, int, int, int)
  52043. {
  52044. }
  52045. void Viewport::setViewedComponent (Component* const newViewedComponent)
  52046. {
  52047. if (contentComp.getComponent() != newViewedComponent)
  52048. {
  52049. {
  52050. ScopedPointer<Component> oldCompDeleter (contentComp);
  52051. contentComp = 0;
  52052. }
  52053. contentComp = newViewedComponent;
  52054. if (contentComp != 0)
  52055. {
  52056. contentComp->setTopLeftPosition (0, 0);
  52057. contentHolder.addAndMakeVisible (contentComp);
  52058. contentComp->addComponentListener (this);
  52059. }
  52060. updateVisibleArea();
  52061. }
  52062. }
  52063. int Viewport::getMaximumVisibleWidth() const
  52064. {
  52065. return contentHolder.getWidth();
  52066. }
  52067. int Viewport::getMaximumVisibleHeight() const
  52068. {
  52069. return contentHolder.getHeight();
  52070. }
  52071. void Viewport::setViewPosition (const int xPixelsOffset, const int yPixelsOffset)
  52072. {
  52073. if (contentComp != 0)
  52074. contentComp->setTopLeftPosition (jmax (jmin (0, contentHolder.getWidth() - contentComp->getWidth()), jmin (0, -xPixelsOffset)),
  52075. jmax (jmin (0, contentHolder.getHeight() - contentComp->getHeight()), jmin (0, -yPixelsOffset)));
  52076. }
  52077. void Viewport::setViewPosition (const Point<int>& newPosition)
  52078. {
  52079. setViewPosition (newPosition.getX(), newPosition.getY());
  52080. }
  52081. void Viewport::setViewPositionProportionately (const double x, const double y)
  52082. {
  52083. if (contentComp != 0)
  52084. setViewPosition (jmax (0, roundToInt (x * (contentComp->getWidth() - getWidth()))),
  52085. jmax (0, roundToInt (y * (contentComp->getHeight() - getHeight()))));
  52086. }
  52087. bool Viewport::autoScroll (const int mouseX, const int mouseY, const int activeBorderThickness, const int maximumSpeed)
  52088. {
  52089. if (contentComp != 0)
  52090. {
  52091. int dx = 0, dy = 0;
  52092. if (horizontalScrollBar.isVisible() || contentComp->getX() < 0 || contentComp->getRight() > getWidth())
  52093. {
  52094. if (mouseX < activeBorderThickness)
  52095. dx = activeBorderThickness - mouseX;
  52096. else if (mouseX >= contentHolder.getWidth() - activeBorderThickness)
  52097. dx = (contentHolder.getWidth() - activeBorderThickness) - mouseX;
  52098. if (dx < 0)
  52099. dx = jmax (dx, -maximumSpeed, contentHolder.getWidth() - contentComp->getRight());
  52100. else
  52101. dx = jmin (dx, maximumSpeed, -contentComp->getX());
  52102. }
  52103. if (verticalScrollBar.isVisible() || contentComp->getY() < 0 || contentComp->getBottom() > getHeight())
  52104. {
  52105. if (mouseY < activeBorderThickness)
  52106. dy = activeBorderThickness - mouseY;
  52107. else if (mouseY >= contentHolder.getHeight() - activeBorderThickness)
  52108. dy = (contentHolder.getHeight() - activeBorderThickness) - mouseY;
  52109. if (dy < 0)
  52110. dy = jmax (dy, -maximumSpeed, contentHolder.getHeight() - contentComp->getBottom());
  52111. else
  52112. dy = jmin (dy, maximumSpeed, -contentComp->getY());
  52113. }
  52114. if (dx != 0 || dy != 0)
  52115. {
  52116. contentComp->setTopLeftPosition (contentComp->getX() + dx,
  52117. contentComp->getY() + dy);
  52118. return true;
  52119. }
  52120. }
  52121. return false;
  52122. }
  52123. void Viewport::componentMovedOrResized (Component&, bool, bool)
  52124. {
  52125. updateVisibleArea();
  52126. }
  52127. void Viewport::resized()
  52128. {
  52129. updateVisibleArea();
  52130. }
  52131. void Viewport::updateVisibleArea()
  52132. {
  52133. const int scrollbarWidth = getScrollBarThickness();
  52134. const bool canShowAnyBars = getWidth() > scrollbarWidth && getHeight() > scrollbarWidth;
  52135. const bool canShowHBar = showHScrollbar && canShowAnyBars;
  52136. const bool canShowVBar = showVScrollbar && canShowAnyBars;
  52137. bool hBarVisible = canShowHBar && ! horizontalScrollBar.autoHides();
  52138. bool vBarVisible = canShowVBar && ! verticalScrollBar.autoHides();
  52139. Rectangle<int> contentArea (getLocalBounds());
  52140. if (contentComp != 0 && ! contentArea.contains (contentComp->getBounds()))
  52141. {
  52142. hBarVisible = canShowHBar && (hBarVisible || contentComp->getX() < 0 || contentComp->getRight() > contentArea.getWidth());
  52143. vBarVisible = canShowVBar && (vBarVisible || contentComp->getY() < 0 || contentComp->getBottom() > contentArea.getHeight());
  52144. if (vBarVisible)
  52145. contentArea.setWidth (getWidth() - scrollbarWidth);
  52146. if (hBarVisible)
  52147. contentArea.setHeight (getHeight() - scrollbarWidth);
  52148. if (! contentArea.contains (contentComp->getBounds()))
  52149. {
  52150. hBarVisible = canShowHBar && (hBarVisible || contentComp->getRight() > contentArea.getWidth());
  52151. vBarVisible = canShowVBar && (vBarVisible || contentComp->getBottom() > contentArea.getHeight());
  52152. }
  52153. }
  52154. if (vBarVisible)
  52155. contentArea.setWidth (getWidth() - scrollbarWidth);
  52156. if (hBarVisible)
  52157. contentArea.setHeight (getHeight() - scrollbarWidth);
  52158. contentHolder.setBounds (contentArea);
  52159. Rectangle<int> contentBounds;
  52160. if (contentComp != 0)
  52161. contentBounds = contentComp->getBounds();
  52162. const Point<int> visibleOrigin (-contentBounds.getPosition());
  52163. if (hBarVisible)
  52164. {
  52165. horizontalScrollBar.setBounds (0, contentArea.getHeight(), contentArea.getWidth(), scrollbarWidth);
  52166. horizontalScrollBar.setRangeLimits (0.0, contentBounds.getWidth());
  52167. horizontalScrollBar.setCurrentRange (visibleOrigin.getX(), contentArea.getWidth());
  52168. horizontalScrollBar.setSingleStepSize (singleStepX);
  52169. horizontalScrollBar.cancelPendingUpdate();
  52170. }
  52171. if (vBarVisible)
  52172. {
  52173. verticalScrollBar.setBounds (contentArea.getWidth(), 0, scrollbarWidth, contentArea.getHeight());
  52174. verticalScrollBar.setRangeLimits (0.0, contentBounds.getHeight());
  52175. verticalScrollBar.setCurrentRange (visibleOrigin.getY(), contentArea.getHeight());
  52176. verticalScrollBar.setSingleStepSize (singleStepY);
  52177. verticalScrollBar.cancelPendingUpdate();
  52178. }
  52179. // Force the visibility *after* setting the ranges to avoid flicker caused by edge conditions in the numbers.
  52180. horizontalScrollBar.setVisible (hBarVisible);
  52181. verticalScrollBar.setVisible (vBarVisible);
  52182. const Rectangle<int> visibleArea (visibleOrigin.getX(), visibleOrigin.getY(),
  52183. jmin (contentBounds.getWidth() - visibleOrigin.getX(), contentArea.getWidth()),
  52184. jmin (contentBounds.getHeight() - visibleOrigin.getY(), contentArea.getHeight()));
  52185. if (lastVisibleArea != visibleArea)
  52186. {
  52187. lastVisibleArea = visibleArea;
  52188. visibleAreaChanged (visibleArea.getX(), visibleArea.getY(), visibleArea.getWidth(), visibleArea.getHeight());
  52189. }
  52190. horizontalScrollBar.handleUpdateNowIfNeeded();
  52191. verticalScrollBar.handleUpdateNowIfNeeded();
  52192. }
  52193. void Viewport::setSingleStepSizes (const int stepX, const int stepY)
  52194. {
  52195. if (singleStepX != stepX || singleStepY != stepY)
  52196. {
  52197. singleStepX = stepX;
  52198. singleStepY = stepY;
  52199. updateVisibleArea();
  52200. }
  52201. }
  52202. void Viewport::setScrollBarsShown (const bool showVerticalScrollbarIfNeeded,
  52203. const bool showHorizontalScrollbarIfNeeded)
  52204. {
  52205. if (showVScrollbar != showVerticalScrollbarIfNeeded
  52206. || showHScrollbar != showHorizontalScrollbarIfNeeded)
  52207. {
  52208. showVScrollbar = showVerticalScrollbarIfNeeded;
  52209. showHScrollbar = showHorizontalScrollbarIfNeeded;
  52210. updateVisibleArea();
  52211. }
  52212. }
  52213. void Viewport::setScrollBarThickness (const int thickness)
  52214. {
  52215. if (scrollBarThickness != thickness)
  52216. {
  52217. scrollBarThickness = thickness;
  52218. updateVisibleArea();
  52219. }
  52220. }
  52221. int Viewport::getScrollBarThickness() const
  52222. {
  52223. return scrollBarThickness > 0 ? scrollBarThickness
  52224. : getLookAndFeel().getDefaultScrollbarWidth();
  52225. }
  52226. void Viewport::setScrollBarButtonVisibility (const bool buttonsVisible)
  52227. {
  52228. verticalScrollBar.setButtonVisibility (buttonsVisible);
  52229. horizontalScrollBar.setButtonVisibility (buttonsVisible);
  52230. }
  52231. void Viewport::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart)
  52232. {
  52233. const int newRangeStartInt = roundToInt (newRangeStart);
  52234. if (scrollBarThatHasMoved == &horizontalScrollBar)
  52235. {
  52236. setViewPosition (newRangeStartInt, getViewPositionY());
  52237. }
  52238. else if (scrollBarThatHasMoved == &verticalScrollBar)
  52239. {
  52240. setViewPosition (getViewPositionX(), newRangeStartInt);
  52241. }
  52242. }
  52243. void Viewport::mouseWheelMove (const MouseEvent& e, const float wheelIncrementX, const float wheelIncrementY)
  52244. {
  52245. if (! useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  52246. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  52247. }
  52248. bool Viewport::useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  52249. {
  52250. if (! (e.mods.isAltDown() || e.mods.isCtrlDown()))
  52251. {
  52252. const bool hasVertBar = verticalScrollBar.isVisible();
  52253. const bool hasHorzBar = horizontalScrollBar.isVisible();
  52254. if (hasHorzBar || hasVertBar)
  52255. {
  52256. if (wheelIncrementX != 0)
  52257. {
  52258. wheelIncrementX *= 14.0f * singleStepX;
  52259. wheelIncrementX = (wheelIncrementX < 0) ? jmin (wheelIncrementX, -1.0f)
  52260. : jmax (wheelIncrementX, 1.0f);
  52261. }
  52262. if (wheelIncrementY != 0)
  52263. {
  52264. wheelIncrementY *= 14.0f * singleStepY;
  52265. wheelIncrementY = (wheelIncrementY < 0) ? jmin (wheelIncrementY, -1.0f)
  52266. : jmax (wheelIncrementY, 1.0f);
  52267. }
  52268. Point<int> pos (getViewPosition());
  52269. if (wheelIncrementX != 0 && wheelIncrementY != 0 && hasHorzBar && hasVertBar)
  52270. {
  52271. pos.setX (pos.getX() - roundToInt (wheelIncrementX));
  52272. pos.setY (pos.getY() - roundToInt (wheelIncrementY));
  52273. }
  52274. else if (hasHorzBar && (wheelIncrementX != 0 || e.mods.isShiftDown() || ! hasVertBar))
  52275. {
  52276. if (wheelIncrementX == 0 && ! hasVertBar)
  52277. wheelIncrementX = wheelIncrementY;
  52278. pos.setX (pos.getX() - roundToInt (wheelIncrementX));
  52279. }
  52280. else if (hasVertBar && wheelIncrementY != 0)
  52281. {
  52282. pos.setY (pos.getY() - roundToInt (wheelIncrementY));
  52283. }
  52284. if (pos != getViewPosition())
  52285. {
  52286. setViewPosition (pos);
  52287. return true;
  52288. }
  52289. }
  52290. }
  52291. return false;
  52292. }
  52293. bool Viewport::keyPressed (const KeyPress& key)
  52294. {
  52295. const bool isUpDownKey = key.isKeyCode (KeyPress::upKey)
  52296. || key.isKeyCode (KeyPress::downKey)
  52297. || key.isKeyCode (KeyPress::pageUpKey)
  52298. || key.isKeyCode (KeyPress::pageDownKey)
  52299. || key.isKeyCode (KeyPress::homeKey)
  52300. || key.isKeyCode (KeyPress::endKey);
  52301. if (verticalScrollBar.isVisible() && isUpDownKey)
  52302. return verticalScrollBar.keyPressed (key);
  52303. const bool isLeftRightKey = key.isKeyCode (KeyPress::leftKey)
  52304. || key.isKeyCode (KeyPress::rightKey);
  52305. if (horizontalScrollBar.isVisible() && (isUpDownKey || isLeftRightKey))
  52306. return horizontalScrollBar.keyPressed (key);
  52307. return false;
  52308. }
  52309. END_JUCE_NAMESPACE
  52310. /*** End of inlined file: juce_Viewport.cpp ***/
  52311. /*** Start of inlined file: juce_LookAndFeel.cpp ***/
  52312. BEGIN_JUCE_NAMESPACE
  52313. namespace LookAndFeelHelpers
  52314. {
  52315. void createRoundedPath (Path& p,
  52316. const float x, const float y,
  52317. const float w, const float h,
  52318. const float cs,
  52319. const bool curveTopLeft, const bool curveTopRight,
  52320. const bool curveBottomLeft, const bool curveBottomRight) throw()
  52321. {
  52322. const float cs2 = 2.0f * cs;
  52323. if (curveTopLeft)
  52324. {
  52325. p.startNewSubPath (x, y + cs);
  52326. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  52327. }
  52328. else
  52329. {
  52330. p.startNewSubPath (x, y);
  52331. }
  52332. if (curveTopRight)
  52333. {
  52334. p.lineTo (x + w - cs, y);
  52335. p.addArc (x + w - cs2, y, cs2, cs2, 0.0f, float_Pi * 0.5f);
  52336. }
  52337. else
  52338. {
  52339. p.lineTo (x + w, y);
  52340. }
  52341. if (curveBottomRight)
  52342. {
  52343. p.lineTo (x + w, y + h - cs);
  52344. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  52345. }
  52346. else
  52347. {
  52348. p.lineTo (x + w, y + h);
  52349. }
  52350. if (curveBottomLeft)
  52351. {
  52352. p.lineTo (x + cs, y + h);
  52353. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  52354. }
  52355. else
  52356. {
  52357. p.lineTo (x, y + h);
  52358. }
  52359. p.closeSubPath();
  52360. }
  52361. const Colour createBaseColour (const Colour& buttonColour,
  52362. const bool hasKeyboardFocus,
  52363. const bool isMouseOverButton,
  52364. const bool isButtonDown) throw()
  52365. {
  52366. const float sat = hasKeyboardFocus ? 1.3f : 0.9f;
  52367. const Colour baseColour (buttonColour.withMultipliedSaturation (sat));
  52368. if (isButtonDown)
  52369. return baseColour.contrasting (0.2f);
  52370. else if (isMouseOverButton)
  52371. return baseColour.contrasting (0.1f);
  52372. return baseColour;
  52373. }
  52374. const TextLayout layoutTooltipText (const String& text) throw()
  52375. {
  52376. const float tooltipFontSize = 12.0f;
  52377. const int maxToolTipWidth = 400;
  52378. const Font f (tooltipFontSize, Font::bold);
  52379. TextLayout tl (text, f);
  52380. tl.layout (maxToolTipWidth, Justification::left, true);
  52381. return tl;
  52382. }
  52383. }
  52384. LookAndFeel::LookAndFeel()
  52385. {
  52386. /* if this fails it means you're trying to create a LookAndFeel object before
  52387. the static Colours have been initialised. That ain't gonna work. It probably
  52388. means that you're using a static LookAndFeel object and that your compiler has
  52389. decided to intialise it before the Colours class.
  52390. */
  52391. jassert (Colours::white == Colour (0xffffffff));
  52392. // set up the standard set of colours..
  52393. const int textButtonColour = 0xffbbbbff;
  52394. const int textHighlightColour = 0x401111ee;
  52395. const int standardOutlineColour = 0xb2808080;
  52396. static const int standardColours[] =
  52397. {
  52398. TextButton::buttonColourId, textButtonColour,
  52399. TextButton::buttonOnColourId, 0xff4444ff,
  52400. TextButton::textColourOnId, 0xff000000,
  52401. TextButton::textColourOffId, 0xff000000,
  52402. ComboBox::buttonColourId, 0xffbbbbff,
  52403. ComboBox::outlineColourId, standardOutlineColour,
  52404. ToggleButton::textColourId, 0xff000000,
  52405. TextEditor::backgroundColourId, 0xffffffff,
  52406. TextEditor::textColourId, 0xff000000,
  52407. TextEditor::highlightColourId, textHighlightColour,
  52408. TextEditor::highlightedTextColourId, 0xff000000,
  52409. TextEditor::caretColourId, 0xff000000,
  52410. TextEditor::outlineColourId, 0x00000000,
  52411. TextEditor::focusedOutlineColourId, textButtonColour,
  52412. TextEditor::shadowColourId, 0x38000000,
  52413. Label::backgroundColourId, 0x00000000,
  52414. Label::textColourId, 0xff000000,
  52415. Label::outlineColourId, 0x00000000,
  52416. ScrollBar::backgroundColourId, 0x00000000,
  52417. ScrollBar::thumbColourId, 0xffffffff,
  52418. ScrollBar::trackColourId, 0xffffffff,
  52419. TreeView::linesColourId, 0x4c000000,
  52420. TreeView::backgroundColourId, 0x00000000,
  52421. TreeView::dragAndDropIndicatorColourId, 0x80ff0000,
  52422. PopupMenu::backgroundColourId, 0xffffffff,
  52423. PopupMenu::textColourId, 0xff000000,
  52424. PopupMenu::headerTextColourId, 0xff000000,
  52425. PopupMenu::highlightedTextColourId, 0xffffffff,
  52426. PopupMenu::highlightedBackgroundColourId, 0x991111aa,
  52427. ComboBox::textColourId, 0xff000000,
  52428. ComboBox::backgroundColourId, 0xffffffff,
  52429. ComboBox::arrowColourId, 0x99000000,
  52430. ListBox::backgroundColourId, 0xffffffff,
  52431. ListBox::outlineColourId, standardOutlineColour,
  52432. ListBox::textColourId, 0xff000000,
  52433. Slider::backgroundColourId, 0x00000000,
  52434. Slider::thumbColourId, textButtonColour,
  52435. Slider::trackColourId, 0x7fffffff,
  52436. Slider::rotarySliderFillColourId, 0x7f0000ff,
  52437. Slider::rotarySliderOutlineColourId, 0x66000000,
  52438. Slider::textBoxTextColourId, 0xff000000,
  52439. Slider::textBoxBackgroundColourId, 0xffffffff,
  52440. Slider::textBoxHighlightColourId, textHighlightColour,
  52441. Slider::textBoxOutlineColourId, standardOutlineColour,
  52442. ResizableWindow::backgroundColourId, 0xff777777,
  52443. //DocumentWindow::textColourId, 0xff000000, // (this is deliberately not set)
  52444. AlertWindow::backgroundColourId, 0xffededed,
  52445. AlertWindow::textColourId, 0xff000000,
  52446. AlertWindow::outlineColourId, 0xff666666,
  52447. ProgressBar::backgroundColourId, 0xffeeeeee,
  52448. ProgressBar::foregroundColourId, 0xffaaaaee,
  52449. TooltipWindow::backgroundColourId, 0xffeeeebb,
  52450. TooltipWindow::textColourId, 0xff000000,
  52451. TooltipWindow::outlineColourId, 0x4c000000,
  52452. TabbedComponent::backgroundColourId, 0x00000000,
  52453. TabbedComponent::outlineColourId, 0xff777777,
  52454. TabbedButtonBar::tabOutlineColourId, 0x80000000,
  52455. TabbedButtonBar::frontOutlineColourId, 0x90000000,
  52456. Toolbar::backgroundColourId, 0xfff6f8f9,
  52457. Toolbar::separatorColourId, 0x4c000000,
  52458. Toolbar::buttonMouseOverBackgroundColourId, 0x4c0000ff,
  52459. Toolbar::buttonMouseDownBackgroundColourId, 0x800000ff,
  52460. Toolbar::labelTextColourId, 0xff000000,
  52461. Toolbar::editingModeOutlineColourId, 0xffff0000,
  52462. HyperlinkButton::textColourId, 0xcc1111ee,
  52463. GroupComponent::outlineColourId, 0x66000000,
  52464. GroupComponent::textColourId, 0xff000000,
  52465. DirectoryContentsDisplayComponent::highlightColourId, textHighlightColour,
  52466. DirectoryContentsDisplayComponent::textColourId, 0xff000000,
  52467. 0x1000440, /*LassoComponent::lassoFillColourId*/ 0x66dddddd,
  52468. 0x1000441, /*LassoComponent::lassoOutlineColourId*/ 0x99111111,
  52469. MidiKeyboardComponent::whiteNoteColourId, 0xffffffff,
  52470. MidiKeyboardComponent::blackNoteColourId, 0xff000000,
  52471. MidiKeyboardComponent::keySeparatorLineColourId, 0x66000000,
  52472. MidiKeyboardComponent::mouseOverKeyOverlayColourId, 0x80ffff00,
  52473. MidiKeyboardComponent::keyDownOverlayColourId, 0xffb6b600,
  52474. MidiKeyboardComponent::textLabelColourId, 0xff000000,
  52475. MidiKeyboardComponent::upDownButtonBackgroundColourId, 0xffd3d3d3,
  52476. MidiKeyboardComponent::upDownButtonArrowColourId, 0xff000000,
  52477. CodeEditorComponent::backgroundColourId, 0xffffffff,
  52478. CodeEditorComponent::caretColourId, 0xff000000,
  52479. CodeEditorComponent::highlightColourId, textHighlightColour,
  52480. CodeEditorComponent::defaultTextColourId, 0xff000000,
  52481. ColourSelector::backgroundColourId, 0xffe5e5e5,
  52482. ColourSelector::labelTextColourId, 0xff000000,
  52483. KeyMappingEditorComponent::backgroundColourId, 0x00000000,
  52484. KeyMappingEditorComponent::textColourId, 0xff000000,
  52485. FileSearchPathListComponent::backgroundColourId, 0xffffffff,
  52486. FileChooserDialogBox::titleTextColourId, 0xff000000,
  52487. DrawableButton::textColourId, 0xff000000,
  52488. };
  52489. for (int i = 0; i < numElementsInArray (standardColours); i += 2)
  52490. setColour (standardColours [i], Colour (standardColours [i + 1]));
  52491. static String defaultSansName, defaultSerifName, defaultFixedName;
  52492. if (defaultSansName.isEmpty())
  52493. Font::getPlatformDefaultFontNames (defaultSansName, defaultSerifName, defaultFixedName);
  52494. defaultSans = defaultSansName;
  52495. defaultSerif = defaultSerifName;
  52496. defaultFixed = defaultFixedName;
  52497. }
  52498. LookAndFeel::~LookAndFeel()
  52499. {
  52500. }
  52501. const Colour LookAndFeel::findColour (const int colourId) const throw()
  52502. {
  52503. const int index = colourIds.indexOf (colourId);
  52504. if (index >= 0)
  52505. return colours [index];
  52506. jassertfalse;
  52507. return Colours::black;
  52508. }
  52509. void LookAndFeel::setColour (const int colourId, const Colour& colour) throw()
  52510. {
  52511. const int index = colourIds.indexOf (colourId);
  52512. if (index >= 0)
  52513. {
  52514. colours.set (index, colour);
  52515. }
  52516. else
  52517. {
  52518. colourIds.add (colourId);
  52519. colours.add (colour);
  52520. }
  52521. }
  52522. bool LookAndFeel::isColourSpecified (const int colourId) const throw()
  52523. {
  52524. return colourIds.contains (colourId);
  52525. }
  52526. static LookAndFeel* defaultLF = 0;
  52527. static LookAndFeel* currentDefaultLF = 0;
  52528. LookAndFeel& LookAndFeel::getDefaultLookAndFeel() throw()
  52529. {
  52530. // if this happens, your app hasn't initialised itself properly.. if you're
  52531. // trying to hack your own main() function, have a look at
  52532. // JUCEApplication::initialiseForGUI()
  52533. jassert (currentDefaultLF != 0);
  52534. return *currentDefaultLF;
  52535. }
  52536. void LookAndFeel::setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) throw()
  52537. {
  52538. if (newDefaultLookAndFeel == 0)
  52539. {
  52540. if (defaultLF == 0)
  52541. defaultLF = new LookAndFeel();
  52542. newDefaultLookAndFeel = defaultLF;
  52543. }
  52544. currentDefaultLF = newDefaultLookAndFeel;
  52545. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  52546. {
  52547. Component* const c = Desktop::getInstance().getComponent (i);
  52548. if (c != 0)
  52549. c->sendLookAndFeelChange();
  52550. }
  52551. }
  52552. void LookAndFeel::clearDefaultLookAndFeel() throw()
  52553. {
  52554. if (currentDefaultLF == defaultLF)
  52555. currentDefaultLF = 0;
  52556. deleteAndZero (defaultLF);
  52557. }
  52558. const Typeface::Ptr LookAndFeel::getTypefaceForFont (const Font& font)
  52559. {
  52560. String faceName (font.getTypefaceName());
  52561. if (faceName == Font::getDefaultSansSerifFontName())
  52562. faceName = defaultSans;
  52563. else if (faceName == Font::getDefaultSerifFontName())
  52564. faceName = defaultSerif;
  52565. else if (faceName == Font::getDefaultMonospacedFontName())
  52566. faceName = defaultFixed;
  52567. Font f (font);
  52568. f.setTypefaceName (faceName);
  52569. return Typeface::createSystemTypefaceFor (f);
  52570. }
  52571. void LookAndFeel::setDefaultSansSerifTypefaceName (const String& newName)
  52572. {
  52573. defaultSans = newName;
  52574. }
  52575. const MouseCursor LookAndFeel::getMouseCursorFor (Component& component)
  52576. {
  52577. return component.getMouseCursor();
  52578. }
  52579. void LookAndFeel::drawButtonBackground (Graphics& g,
  52580. Button& button,
  52581. const Colour& backgroundColour,
  52582. bool isMouseOverButton,
  52583. bool isButtonDown)
  52584. {
  52585. const int width = button.getWidth();
  52586. const int height = button.getHeight();
  52587. const float outlineThickness = button.isEnabled() ? ((isButtonDown || isMouseOverButton) ? 1.2f : 0.7f) : 0.4f;
  52588. const float halfThickness = outlineThickness * 0.5f;
  52589. const float indentL = button.isConnectedOnLeft() ? 0.1f : halfThickness;
  52590. const float indentR = button.isConnectedOnRight() ? 0.1f : halfThickness;
  52591. const float indentT = button.isConnectedOnTop() ? 0.1f : halfThickness;
  52592. const float indentB = button.isConnectedOnBottom() ? 0.1f : halfThickness;
  52593. const Colour baseColour (LookAndFeelHelpers::createBaseColour (backgroundColour,
  52594. button.hasKeyboardFocus (true),
  52595. isMouseOverButton, isButtonDown)
  52596. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  52597. drawGlassLozenge (g,
  52598. indentL,
  52599. indentT,
  52600. width - indentL - indentR,
  52601. height - indentT - indentB,
  52602. baseColour, outlineThickness, -1.0f,
  52603. button.isConnectedOnLeft(),
  52604. button.isConnectedOnRight(),
  52605. button.isConnectedOnTop(),
  52606. button.isConnectedOnBottom());
  52607. }
  52608. const Font LookAndFeel::getFontForTextButton (TextButton& button)
  52609. {
  52610. return button.getFont();
  52611. }
  52612. void LookAndFeel::drawButtonText (Graphics& g, TextButton& button,
  52613. bool /*isMouseOverButton*/, bool /*isButtonDown*/)
  52614. {
  52615. Font font (getFontForTextButton (button));
  52616. g.setFont (font);
  52617. g.setColour (button.findColour (button.getToggleState() ? TextButton::textColourOnId
  52618. : TextButton::textColourOffId)
  52619. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  52620. const int yIndent = jmin (4, button.proportionOfHeight (0.3f));
  52621. const int cornerSize = jmin (button.getHeight(), button.getWidth()) / 2;
  52622. const int fontHeight = roundToInt (font.getHeight() * 0.6f);
  52623. const int leftIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnLeft() ? 4 : 2));
  52624. const int rightIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnRight() ? 4 : 2));
  52625. g.drawFittedText (button.getButtonText(),
  52626. leftIndent,
  52627. yIndent,
  52628. button.getWidth() - leftIndent - rightIndent,
  52629. button.getHeight() - yIndent * 2,
  52630. Justification::centred, 2);
  52631. }
  52632. void LookAndFeel::drawTickBox (Graphics& g,
  52633. Component& component,
  52634. float x, float y, float w, float h,
  52635. const bool ticked,
  52636. const bool isEnabled,
  52637. const bool isMouseOverButton,
  52638. const bool isButtonDown)
  52639. {
  52640. const float boxSize = w * 0.7f;
  52641. drawGlassSphere (g, x, y + (h - boxSize) * 0.5f, boxSize,
  52642. LookAndFeelHelpers::createBaseColour (component.findColour (TextButton::buttonColourId)
  52643. .withMultipliedAlpha (isEnabled ? 1.0f : 0.5f),
  52644. true, isMouseOverButton, isButtonDown),
  52645. isEnabled ? ((isButtonDown || isMouseOverButton) ? 1.1f : 0.5f) : 0.3f);
  52646. if (ticked)
  52647. {
  52648. Path tick;
  52649. tick.startNewSubPath (1.5f, 3.0f);
  52650. tick.lineTo (3.0f, 6.0f);
  52651. tick.lineTo (6.0f, 0.0f);
  52652. g.setColour (isEnabled ? Colours::black : Colours::grey);
  52653. const AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f)
  52654. .translated (x, y));
  52655. g.strokePath (tick, PathStrokeType (2.5f), trans);
  52656. }
  52657. }
  52658. void LookAndFeel::drawToggleButton (Graphics& g,
  52659. ToggleButton& button,
  52660. bool isMouseOverButton,
  52661. bool isButtonDown)
  52662. {
  52663. if (button.hasKeyboardFocus (true))
  52664. {
  52665. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  52666. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  52667. }
  52668. float fontSize = jmin (15.0f, button.getHeight() * 0.75f);
  52669. const float tickWidth = fontSize * 1.1f;
  52670. drawTickBox (g, button, 4.0f, (button.getHeight() - tickWidth) * 0.5f,
  52671. tickWidth, tickWidth,
  52672. button.getToggleState(),
  52673. button.isEnabled(),
  52674. isMouseOverButton,
  52675. isButtonDown);
  52676. g.setColour (button.findColour (ToggleButton::textColourId));
  52677. g.setFont (fontSize);
  52678. if (! button.isEnabled())
  52679. g.setOpacity (0.5f);
  52680. const int textX = (int) tickWidth + 5;
  52681. g.drawFittedText (button.getButtonText(),
  52682. textX, 0,
  52683. button.getWidth() - textX - 2, button.getHeight(),
  52684. Justification::centredLeft, 10);
  52685. }
  52686. void LookAndFeel::changeToggleButtonWidthToFitText (ToggleButton& button)
  52687. {
  52688. Font font (jmin (15.0f, button.getHeight() * 0.6f));
  52689. const int tickWidth = jmin (24, button.getHeight());
  52690. button.setSize (font.getStringWidth (button.getButtonText()) + tickWidth + 8,
  52691. button.getHeight());
  52692. }
  52693. AlertWindow* LookAndFeel::createAlertWindow (const String& title,
  52694. const String& message,
  52695. const String& button1,
  52696. const String& button2,
  52697. const String& button3,
  52698. AlertWindow::AlertIconType iconType,
  52699. int numButtons,
  52700. Component* associatedComponent)
  52701. {
  52702. AlertWindow* aw = new AlertWindow (title, message, iconType, associatedComponent);
  52703. if (numButtons == 1)
  52704. {
  52705. aw->addButton (button1, 0,
  52706. KeyPress (KeyPress::escapeKey, 0, 0),
  52707. KeyPress (KeyPress::returnKey, 0, 0));
  52708. }
  52709. else
  52710. {
  52711. const KeyPress button1ShortCut (CharacterFunctions::toLowerCase (button1[0]), 0, 0);
  52712. KeyPress button2ShortCut (CharacterFunctions::toLowerCase (button2[0]), 0, 0);
  52713. if (button1ShortCut == button2ShortCut)
  52714. button2ShortCut = KeyPress();
  52715. if (numButtons == 2)
  52716. {
  52717. aw->addButton (button1, 1, KeyPress (KeyPress::returnKey, 0, 0), button1ShortCut);
  52718. aw->addButton (button2, 0, KeyPress (KeyPress::escapeKey, 0, 0), button2ShortCut);
  52719. }
  52720. else if (numButtons == 3)
  52721. {
  52722. aw->addButton (button1, 1, button1ShortCut);
  52723. aw->addButton (button2, 2, button2ShortCut);
  52724. aw->addButton (button3, 0, KeyPress (KeyPress::escapeKey, 0, 0));
  52725. }
  52726. }
  52727. return aw;
  52728. }
  52729. void LookAndFeel::drawAlertBox (Graphics& g,
  52730. AlertWindow& alert,
  52731. const Rectangle<int>& textArea,
  52732. TextLayout& textLayout)
  52733. {
  52734. g.fillAll (alert.findColour (AlertWindow::backgroundColourId));
  52735. int iconSpaceUsed = 0;
  52736. Justification alignment (Justification::horizontallyCentred);
  52737. const int iconWidth = 80;
  52738. int iconSize = jmin (iconWidth + 50, alert.getHeight() + 20);
  52739. if (alert.containsAnyExtraComponents() || alert.getNumButtons() > 2)
  52740. iconSize = jmin (iconSize, textArea.getHeight() + 50);
  52741. const Rectangle<int> iconRect (iconSize / -10, iconSize / -10,
  52742. iconSize, iconSize);
  52743. if (alert.getAlertType() != AlertWindow::NoIcon)
  52744. {
  52745. Path icon;
  52746. uint32 colour;
  52747. char character;
  52748. if (alert.getAlertType() == AlertWindow::WarningIcon)
  52749. {
  52750. colour = 0x55ff5555;
  52751. character = '!';
  52752. icon.addTriangle (iconRect.getX() + iconRect.getWidth() * 0.5f, (float) iconRect.getY(),
  52753. (float) iconRect.getRight(), (float) iconRect.getBottom(),
  52754. (float) iconRect.getX(), (float) iconRect.getBottom());
  52755. icon = icon.createPathWithRoundedCorners (5.0f);
  52756. }
  52757. else
  52758. {
  52759. colour = alert.getAlertType() == AlertWindow::InfoIcon ? 0x605555ff : 0x40b69900;
  52760. character = alert.getAlertType() == AlertWindow::InfoIcon ? 'i' : '?';
  52761. icon.addEllipse ((float) iconRect.getX(), (float) iconRect.getY(),
  52762. (float) iconRect.getWidth(), (float) iconRect.getHeight());
  52763. }
  52764. GlyphArrangement ga;
  52765. ga.addFittedText (Font (iconRect.getHeight() * 0.9f, Font::bold),
  52766. String::charToString (character),
  52767. (float) iconRect.getX(), (float) iconRect.getY(),
  52768. (float) iconRect.getWidth(), (float) iconRect.getHeight(),
  52769. Justification::centred, false);
  52770. ga.createPath (icon);
  52771. icon.setUsingNonZeroWinding (false);
  52772. g.setColour (Colour (colour));
  52773. g.fillPath (icon);
  52774. iconSpaceUsed = iconWidth;
  52775. alignment = Justification::left;
  52776. }
  52777. g.setColour (alert.findColour (AlertWindow::textColourId));
  52778. textLayout.drawWithin (g,
  52779. textArea.getX() + iconSpaceUsed, textArea.getY(),
  52780. textArea.getWidth() - iconSpaceUsed, textArea.getHeight(),
  52781. alignment.getFlags() | Justification::top);
  52782. g.setColour (alert.findColour (AlertWindow::outlineColourId));
  52783. g.drawRect (0, 0, alert.getWidth(), alert.getHeight());
  52784. }
  52785. int LookAndFeel::getAlertBoxWindowFlags()
  52786. {
  52787. return ComponentPeer::windowAppearsOnTaskbar
  52788. | ComponentPeer::windowHasDropShadow;
  52789. }
  52790. int LookAndFeel::getAlertWindowButtonHeight()
  52791. {
  52792. return 28;
  52793. }
  52794. const Font LookAndFeel::getAlertWindowFont()
  52795. {
  52796. return Font (12.0f);
  52797. }
  52798. void LookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  52799. int width, int height,
  52800. double progress, const String& textToShow)
  52801. {
  52802. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  52803. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  52804. g.fillAll (background);
  52805. if (progress >= 0.0f && progress < 1.0f)
  52806. {
  52807. drawGlassLozenge (g, 1.0f, 1.0f,
  52808. (float) jlimit (0.0, width - 2.0, progress * (width - 2.0)),
  52809. (float) (height - 2),
  52810. foreground,
  52811. 0.5f, 0.0f,
  52812. true, true, true, true);
  52813. }
  52814. else
  52815. {
  52816. // spinning bar..
  52817. g.setColour (foreground);
  52818. const int stripeWidth = height * 2;
  52819. const int position = (Time::getMillisecondCounter() / 15) % stripeWidth;
  52820. Path p;
  52821. for (float x = (float) (- position); x < width + stripeWidth; x += stripeWidth)
  52822. p.addQuadrilateral (x, 0.0f,
  52823. x + stripeWidth * 0.5f, 0.0f,
  52824. x, (float) height,
  52825. x - stripeWidth * 0.5f, (float) height);
  52826. Image im (Image::ARGB, width, height, true);
  52827. {
  52828. Graphics g2 (im);
  52829. drawGlassLozenge (g2, 1.0f, 1.0f,
  52830. (float) (width - 2),
  52831. (float) (height - 2),
  52832. foreground,
  52833. 0.5f, 0.0f,
  52834. true, true, true, true);
  52835. }
  52836. g.setTiledImageFill (im, 0, 0, 0.85f);
  52837. g.fillPath (p);
  52838. }
  52839. if (textToShow.isNotEmpty())
  52840. {
  52841. g.setColour (Colour::contrasting (background, foreground));
  52842. g.setFont (height * 0.6f);
  52843. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  52844. }
  52845. }
  52846. void LookAndFeel::drawSpinningWaitAnimation (Graphics& g, const Colour& colour, int x, int y, int w, int h)
  52847. {
  52848. const float radius = jmin (w, h) * 0.4f;
  52849. const float thickness = radius * 0.15f;
  52850. Path p;
  52851. p.addRoundedRectangle (radius * 0.4f, thickness * -0.5f,
  52852. radius * 0.6f, thickness,
  52853. thickness * 0.5f);
  52854. const float cx = x + w * 0.5f;
  52855. const float cy = y + h * 0.5f;
  52856. const uint32 animationIndex = (Time::getMillisecondCounter() / (1000 / 10)) % 12;
  52857. for (int i = 0; i < 12; ++i)
  52858. {
  52859. const int n = (i + 12 - animationIndex) % 12;
  52860. g.setColour (colour.withMultipliedAlpha ((n + 1) / 12.0f));
  52861. g.fillPath (p, AffineTransform::rotation (i * (float_Pi / 6.0f))
  52862. .translated (cx, cy));
  52863. }
  52864. }
  52865. void LookAndFeel::drawScrollbarButton (Graphics& g,
  52866. ScrollBar& scrollbar,
  52867. int width, int height,
  52868. int buttonDirection,
  52869. bool /*isScrollbarVertical*/,
  52870. bool /*isMouseOverButton*/,
  52871. bool isButtonDown)
  52872. {
  52873. Path p;
  52874. if (buttonDirection == 0)
  52875. p.addTriangle (width * 0.5f, height * 0.2f,
  52876. width * 0.1f, height * 0.7f,
  52877. width * 0.9f, height * 0.7f);
  52878. else if (buttonDirection == 1)
  52879. p.addTriangle (width * 0.8f, height * 0.5f,
  52880. width * 0.3f, height * 0.1f,
  52881. width * 0.3f, height * 0.9f);
  52882. else if (buttonDirection == 2)
  52883. p.addTriangle (width * 0.5f, height * 0.8f,
  52884. width * 0.1f, height * 0.3f,
  52885. width * 0.9f, height * 0.3f);
  52886. else if (buttonDirection == 3)
  52887. p.addTriangle (width * 0.2f, height * 0.5f,
  52888. width * 0.7f, height * 0.1f,
  52889. width * 0.7f, height * 0.9f);
  52890. if (isButtonDown)
  52891. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId).contrasting (0.2f));
  52892. else
  52893. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId));
  52894. g.fillPath (p);
  52895. g.setColour (Colour (0x80000000));
  52896. g.strokePath (p, PathStrokeType (0.5f));
  52897. }
  52898. void LookAndFeel::drawScrollbar (Graphics& g,
  52899. ScrollBar& scrollbar,
  52900. int x, int y,
  52901. int width, int height,
  52902. bool isScrollbarVertical,
  52903. int thumbStartPosition,
  52904. int thumbSize,
  52905. bool /*isMouseOver*/,
  52906. bool /*isMouseDown*/)
  52907. {
  52908. g.fillAll (scrollbar.findColour (ScrollBar::backgroundColourId));
  52909. Path slotPath, thumbPath;
  52910. const float slotIndent = jmin (width, height) > 15 ? 1.0f : 0.0f;
  52911. const float slotIndentx2 = slotIndent * 2.0f;
  52912. const float thumbIndent = slotIndent + 1.0f;
  52913. const float thumbIndentx2 = thumbIndent * 2.0f;
  52914. float gx1 = 0.0f, gy1 = 0.0f, gx2 = 0.0f, gy2 = 0.0f;
  52915. if (isScrollbarVertical)
  52916. {
  52917. slotPath.addRoundedRectangle (x + slotIndent,
  52918. y + slotIndent,
  52919. width - slotIndentx2,
  52920. height - slotIndentx2,
  52921. (width - slotIndentx2) * 0.5f);
  52922. if (thumbSize > 0)
  52923. thumbPath.addRoundedRectangle (x + thumbIndent,
  52924. thumbStartPosition + thumbIndent,
  52925. width - thumbIndentx2,
  52926. thumbSize - thumbIndentx2,
  52927. (width - thumbIndentx2) * 0.5f);
  52928. gx1 = (float) x;
  52929. gx2 = x + width * 0.7f;
  52930. }
  52931. else
  52932. {
  52933. slotPath.addRoundedRectangle (x + slotIndent,
  52934. y + slotIndent,
  52935. width - slotIndentx2,
  52936. height - slotIndentx2,
  52937. (height - slotIndentx2) * 0.5f);
  52938. if (thumbSize > 0)
  52939. thumbPath.addRoundedRectangle (thumbStartPosition + thumbIndent,
  52940. y + thumbIndent,
  52941. thumbSize - thumbIndentx2,
  52942. height - thumbIndentx2,
  52943. (height - thumbIndentx2) * 0.5f);
  52944. gy1 = (float) y;
  52945. gy2 = y + height * 0.7f;
  52946. }
  52947. const Colour thumbColour (scrollbar.findColour (ScrollBar::thumbColourId));
  52948. g.setGradientFill (ColourGradient (thumbColour.overlaidWith (Colour (0x44000000)), gx1, gy1,
  52949. thumbColour.overlaidWith (Colour (0x19000000)), gx2, gy2, false));
  52950. g.fillPath (slotPath);
  52951. if (isScrollbarVertical)
  52952. {
  52953. gx1 = x + width * 0.6f;
  52954. gx2 = (float) x + width;
  52955. }
  52956. else
  52957. {
  52958. gy1 = y + height * 0.6f;
  52959. gy2 = (float) y + height;
  52960. }
  52961. g.setGradientFill (ColourGradient (Colours::transparentBlack,gx1, gy1,
  52962. Colour (0x19000000), gx2, gy2, false));
  52963. g.fillPath (slotPath);
  52964. g.setColour (thumbColour);
  52965. g.fillPath (thumbPath);
  52966. g.setGradientFill (ColourGradient (Colour (0x10000000), gx1, gy1,
  52967. Colours::transparentBlack, gx2, gy2, false));
  52968. g.saveState();
  52969. if (isScrollbarVertical)
  52970. g.reduceClipRegion (x + width / 2, y, width, height);
  52971. else
  52972. g.reduceClipRegion (x, y + height / 2, width, height);
  52973. g.fillPath (thumbPath);
  52974. g.restoreState();
  52975. g.setColour (Colour (0x4c000000));
  52976. g.strokePath (thumbPath, PathStrokeType (0.4f));
  52977. }
  52978. ImageEffectFilter* LookAndFeel::getScrollbarEffect()
  52979. {
  52980. return 0;
  52981. }
  52982. int LookAndFeel::getMinimumScrollbarThumbSize (ScrollBar& scrollbar)
  52983. {
  52984. return jmin (scrollbar.getWidth(), scrollbar.getHeight()) * 2;
  52985. }
  52986. int LookAndFeel::getDefaultScrollbarWidth()
  52987. {
  52988. return 18;
  52989. }
  52990. int LookAndFeel::getScrollbarButtonSize (ScrollBar& scrollbar)
  52991. {
  52992. return 2 + (scrollbar.isVertical() ? scrollbar.getWidth()
  52993. : scrollbar.getHeight());
  52994. }
  52995. const Path LookAndFeel::getTickShape (const float height)
  52996. {
  52997. static const unsigned char tickShapeData[] =
  52998. {
  52999. 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,
  53000. 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,
  53001. 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,
  53002. 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,
  53003. 96,140,68,0,128,188,67,0,224,168,68,0,0,119,67,99,101
  53004. };
  53005. Path p;
  53006. p.loadPathFromData (tickShapeData, sizeof (tickShapeData));
  53007. p.scaleToFit (0, 0, height * 2.0f, height, true);
  53008. return p;
  53009. }
  53010. const Path LookAndFeel::getCrossShape (const float height)
  53011. {
  53012. static const unsigned char crossShapeData[] =
  53013. {
  53014. 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,
  53015. 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,
  53016. 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,
  53017. 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,
  53018. 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,
  53019. 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,
  53020. 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
  53021. };
  53022. Path p;
  53023. p.loadPathFromData (crossShapeData, sizeof (crossShapeData));
  53024. p.scaleToFit (0, 0, height * 2.0f, height, true);
  53025. return p;
  53026. }
  53027. void LookAndFeel::drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus, bool /*isMouseOver*/)
  53028. {
  53029. const int boxSize = ((jmin (16, w, h) << 1) / 3) | 1;
  53030. x += (w - boxSize) >> 1;
  53031. y += (h - boxSize) >> 1;
  53032. w = boxSize;
  53033. h = boxSize;
  53034. g.setColour (Colour (0xe5ffffff));
  53035. g.fillRect (x, y, w, h);
  53036. g.setColour (Colour (0x80000000));
  53037. g.drawRect (x, y, w, h);
  53038. const float size = boxSize / 2 + 1.0f;
  53039. const float centre = (float) (boxSize / 2);
  53040. g.fillRect (x + (w - size) * 0.5f, y + centre, size, 1.0f);
  53041. if (isPlus)
  53042. g.fillRect (x + centre, y + (h - size) * 0.5f, 1.0f, size);
  53043. }
  53044. void LookAndFeel::drawBubble (Graphics& g,
  53045. float tipX, float tipY,
  53046. float boxX, float boxY,
  53047. float boxW, float boxH)
  53048. {
  53049. int side = 0;
  53050. if (tipX < boxX)
  53051. side = 1;
  53052. else if (tipX > boxX + boxW)
  53053. side = 3;
  53054. else if (tipY > boxY + boxH)
  53055. side = 2;
  53056. const float indent = 2.0f;
  53057. Path p;
  53058. p.addBubble (boxX + indent,
  53059. boxY + indent,
  53060. boxW - indent * 2.0f,
  53061. boxH - indent * 2.0f,
  53062. 5.0f,
  53063. tipX, tipY,
  53064. side,
  53065. 0.5f,
  53066. jmin (15.0f, boxW * 0.3f, boxH * 0.3f));
  53067. //xxx need to take comp as param for colour
  53068. g.setColour (findColour (TooltipWindow::backgroundColourId).withAlpha (0.9f));
  53069. g.fillPath (p);
  53070. //xxx as above
  53071. g.setColour (findColour (TooltipWindow::textColourId).withAlpha (0.4f));
  53072. g.strokePath (p, PathStrokeType (1.33f));
  53073. }
  53074. const Font LookAndFeel::getPopupMenuFont()
  53075. {
  53076. return Font (17.0f);
  53077. }
  53078. void LookAndFeel::getIdealPopupMenuItemSize (const String& text,
  53079. const bool isSeparator,
  53080. int standardMenuItemHeight,
  53081. int& idealWidth,
  53082. int& idealHeight)
  53083. {
  53084. if (isSeparator)
  53085. {
  53086. idealWidth = 50;
  53087. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight / 2 : 10;
  53088. }
  53089. else
  53090. {
  53091. Font font (getPopupMenuFont());
  53092. if (standardMenuItemHeight > 0 && font.getHeight() > standardMenuItemHeight / 1.3f)
  53093. font.setHeight (standardMenuItemHeight / 1.3f);
  53094. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight : roundToInt (font.getHeight() * 1.3f);
  53095. idealWidth = font.getStringWidth (text) + idealHeight * 2;
  53096. }
  53097. }
  53098. void LookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  53099. {
  53100. const Colour background (findColour (PopupMenu::backgroundColourId));
  53101. g.fillAll (background);
  53102. g.setColour (background.overlaidWith (Colour (0x2badd8e6)));
  53103. for (int i = 0; i < height; i += 3)
  53104. g.fillRect (0, i, width, 1);
  53105. #if ! JUCE_MAC
  53106. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.6f));
  53107. g.drawRect (0, 0, width, height);
  53108. #endif
  53109. }
  53110. void LookAndFeel::drawPopupMenuUpDownArrow (Graphics& g,
  53111. int width, int height,
  53112. bool isScrollUpArrow)
  53113. {
  53114. const Colour background (findColour (PopupMenu::backgroundColourId));
  53115. g.setGradientFill (ColourGradient (background, 0.0f, height * 0.5f,
  53116. background.withAlpha (0.0f),
  53117. 0.0f, isScrollUpArrow ? ((float) height) : 0.0f,
  53118. false));
  53119. g.fillRect (1, 1, width - 2, height - 2);
  53120. const float hw = width * 0.5f;
  53121. const float arrowW = height * 0.3f;
  53122. const float y1 = height * (isScrollUpArrow ? 0.6f : 0.3f);
  53123. const float y2 = height * (isScrollUpArrow ? 0.3f : 0.6f);
  53124. Path p;
  53125. p.addTriangle (hw - arrowW, y1,
  53126. hw + arrowW, y1,
  53127. hw, y2);
  53128. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.5f));
  53129. g.fillPath (p);
  53130. }
  53131. void LookAndFeel::drawPopupMenuItem (Graphics& g,
  53132. int width, int height,
  53133. const bool isSeparator,
  53134. const bool isActive,
  53135. const bool isHighlighted,
  53136. const bool isTicked,
  53137. const bool hasSubMenu,
  53138. const String& text,
  53139. const String& shortcutKeyText,
  53140. Image* image,
  53141. const Colour* const textColourToUse)
  53142. {
  53143. const float halfH = height * 0.5f;
  53144. if (isSeparator)
  53145. {
  53146. const float separatorIndent = 5.5f;
  53147. g.setColour (Colour (0x33000000));
  53148. g.drawLine (separatorIndent, halfH, width - separatorIndent, halfH);
  53149. g.setColour (Colour (0x66ffffff));
  53150. g.drawLine (separatorIndent, halfH + 1.0f, width - separatorIndent, halfH + 1.0f);
  53151. }
  53152. else
  53153. {
  53154. Colour textColour (findColour (PopupMenu::textColourId));
  53155. if (textColourToUse != 0)
  53156. textColour = *textColourToUse;
  53157. if (isHighlighted)
  53158. {
  53159. g.setColour (findColour (PopupMenu::highlightedBackgroundColourId));
  53160. g.fillRect (1, 1, width - 2, height - 2);
  53161. g.setColour (findColour (PopupMenu::highlightedTextColourId));
  53162. }
  53163. else
  53164. {
  53165. g.setColour (textColour);
  53166. }
  53167. if (! isActive)
  53168. g.setOpacity (0.3f);
  53169. Font font (getPopupMenuFont());
  53170. if (font.getHeight() > height / 1.3f)
  53171. font.setHeight (height / 1.3f);
  53172. g.setFont (font);
  53173. const int leftBorder = (height * 5) / 4;
  53174. const int rightBorder = 4;
  53175. if (image != 0)
  53176. {
  53177. g.drawImageWithin (*image,
  53178. 2, 1, leftBorder - 4, height - 2,
  53179. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize, false);
  53180. }
  53181. else if (isTicked)
  53182. {
  53183. const Path tick (getTickShape (1.0f));
  53184. const float th = font.getAscent();
  53185. const float ty = halfH - th * 0.5f;
  53186. g.fillPath (tick, tick.getTransformToScaleToFit (2.0f, ty, (float) (leftBorder - 4),
  53187. th, true));
  53188. }
  53189. g.drawFittedText (text,
  53190. leftBorder, 0,
  53191. width - (leftBorder + rightBorder), height,
  53192. Justification::centredLeft, 1);
  53193. if (shortcutKeyText.isNotEmpty())
  53194. {
  53195. Font f2 (font);
  53196. f2.setHeight (f2.getHeight() * 0.75f);
  53197. f2.setHorizontalScale (0.95f);
  53198. g.setFont (f2);
  53199. g.drawText (shortcutKeyText,
  53200. leftBorder,
  53201. 0,
  53202. width - (leftBorder + rightBorder + 4),
  53203. height,
  53204. Justification::centredRight,
  53205. true);
  53206. }
  53207. if (hasSubMenu)
  53208. {
  53209. const float arrowH = 0.6f * getPopupMenuFont().getAscent();
  53210. const float x = width - height * 0.6f;
  53211. Path p;
  53212. p.addTriangle (x, halfH - arrowH * 0.5f,
  53213. x, halfH + arrowH * 0.5f,
  53214. x + arrowH * 0.6f, halfH);
  53215. g.fillPath (p);
  53216. }
  53217. }
  53218. }
  53219. int LookAndFeel::getMenuWindowFlags()
  53220. {
  53221. return ComponentPeer::windowHasDropShadow;
  53222. }
  53223. void LookAndFeel::drawMenuBarBackground (Graphics& g, int width, int height,
  53224. bool, MenuBarComponent& menuBar)
  53225. {
  53226. const Colour baseColour (LookAndFeelHelpers::createBaseColour (menuBar.findColour (PopupMenu::backgroundColourId), false, false, false));
  53227. if (menuBar.isEnabled())
  53228. {
  53229. drawShinyButtonShape (g,
  53230. -4.0f, 0.0f,
  53231. width + 8.0f, (float) height,
  53232. 0.0f,
  53233. baseColour,
  53234. 0.4f,
  53235. true, true, true, true);
  53236. }
  53237. else
  53238. {
  53239. g.fillAll (baseColour);
  53240. }
  53241. }
  53242. const Font LookAndFeel::getMenuBarFont (MenuBarComponent& menuBar, int /*itemIndex*/, const String& /*itemText*/)
  53243. {
  53244. return Font (menuBar.getHeight() * 0.7f);
  53245. }
  53246. int LookAndFeel::getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText)
  53247. {
  53248. return getMenuBarFont (menuBar, itemIndex, itemText)
  53249. .getStringWidth (itemText) + menuBar.getHeight();
  53250. }
  53251. void LookAndFeel::drawMenuBarItem (Graphics& g,
  53252. int width, int height,
  53253. int itemIndex,
  53254. const String& itemText,
  53255. bool isMouseOverItem,
  53256. bool isMenuOpen,
  53257. bool /*isMouseOverBar*/,
  53258. MenuBarComponent& menuBar)
  53259. {
  53260. if (! menuBar.isEnabled())
  53261. {
  53262. g.setColour (menuBar.findColour (PopupMenu::textColourId)
  53263. .withMultipliedAlpha (0.5f));
  53264. }
  53265. else if (isMenuOpen || isMouseOverItem)
  53266. {
  53267. g.fillAll (menuBar.findColour (PopupMenu::highlightedBackgroundColourId));
  53268. g.setColour (menuBar.findColour (PopupMenu::highlightedTextColourId));
  53269. }
  53270. else
  53271. {
  53272. g.setColour (menuBar.findColour (PopupMenu::textColourId));
  53273. }
  53274. g.setFont (getMenuBarFont (menuBar, itemIndex, itemText));
  53275. g.drawFittedText (itemText, 0, 0, width, height, Justification::centred, 1);
  53276. }
  53277. void LookAndFeel::fillTextEditorBackground (Graphics& g, int /*width*/, int /*height*/,
  53278. TextEditor& textEditor)
  53279. {
  53280. g.fillAll (textEditor.findColour (TextEditor::backgroundColourId));
  53281. }
  53282. void LookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  53283. {
  53284. if (textEditor.isEnabled())
  53285. {
  53286. if (textEditor.hasKeyboardFocus (true) && ! textEditor.isReadOnly())
  53287. {
  53288. const int border = 2;
  53289. g.setColour (textEditor.findColour (TextEditor::focusedOutlineColourId));
  53290. g.drawRect (0, 0, width, height, border);
  53291. g.setOpacity (1.0f);
  53292. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId).withMultipliedAlpha (0.75f));
  53293. g.drawBevel (0, 0, width, height + 2, border + 2, shadowColour, shadowColour);
  53294. }
  53295. else
  53296. {
  53297. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  53298. g.drawRect (0, 0, width, height);
  53299. g.setOpacity (1.0f);
  53300. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId));
  53301. g.drawBevel (0, 0, width, height + 2, 3, shadowColour, shadowColour);
  53302. }
  53303. }
  53304. }
  53305. void LookAndFeel::drawComboBox (Graphics& g, int width, int height,
  53306. const bool isButtonDown,
  53307. int buttonX, int buttonY,
  53308. int buttonW, int buttonH,
  53309. ComboBox& box)
  53310. {
  53311. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  53312. if (box.isEnabled() && box.hasKeyboardFocus (false))
  53313. {
  53314. g.setColour (box.findColour (TextButton::buttonColourId));
  53315. g.drawRect (0, 0, width, height, 2);
  53316. }
  53317. else
  53318. {
  53319. g.setColour (box.findColour (ComboBox::outlineColourId));
  53320. g.drawRect (0, 0, width, height);
  53321. }
  53322. const float outlineThickness = box.isEnabled() ? (isButtonDown ? 1.2f : 0.5f) : 0.3f;
  53323. const Colour baseColour (LookAndFeelHelpers::createBaseColour (box.findColour (ComboBox::buttonColourId),
  53324. box.hasKeyboardFocus (true),
  53325. false, isButtonDown)
  53326. .withMultipliedAlpha (box.isEnabled() ? 1.0f : 0.5f));
  53327. drawGlassLozenge (g,
  53328. buttonX + outlineThickness, buttonY + outlineThickness,
  53329. buttonW - outlineThickness * 2.0f, buttonH - outlineThickness * 2.0f,
  53330. baseColour, outlineThickness, -1.0f,
  53331. true, true, true, true);
  53332. if (box.isEnabled())
  53333. {
  53334. const float arrowX = 0.3f;
  53335. const float arrowH = 0.2f;
  53336. Path p;
  53337. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  53338. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  53339. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  53340. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  53341. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  53342. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  53343. g.setColour (box.findColour (ComboBox::arrowColourId));
  53344. g.fillPath (p);
  53345. }
  53346. }
  53347. const Font LookAndFeel::getComboBoxFont (ComboBox& box)
  53348. {
  53349. return Font (jmin (15.0f, box.getHeight() * 0.85f));
  53350. }
  53351. Label* LookAndFeel::createComboBoxTextBox (ComboBox&)
  53352. {
  53353. return new Label (String::empty, String::empty);
  53354. }
  53355. void LookAndFeel::positionComboBoxText (ComboBox& box, Label& label)
  53356. {
  53357. label.setBounds (1, 1,
  53358. box.getWidth() + 3 - box.getHeight(),
  53359. box.getHeight() - 2);
  53360. label.setFont (getComboBoxFont (box));
  53361. }
  53362. void LookAndFeel::drawLabel (Graphics& g, Label& label)
  53363. {
  53364. g.fillAll (label.findColour (Label::backgroundColourId));
  53365. if (! label.isBeingEdited())
  53366. {
  53367. const float alpha = label.isEnabled() ? 1.0f : 0.5f;
  53368. g.setColour (label.findColour (Label::textColourId).withMultipliedAlpha (alpha));
  53369. g.setFont (label.getFont());
  53370. g.drawFittedText (label.getText(),
  53371. label.getHorizontalBorderSize(),
  53372. label.getVerticalBorderSize(),
  53373. label.getWidth() - 2 * label.getHorizontalBorderSize(),
  53374. label.getHeight() - 2 * label.getVerticalBorderSize(),
  53375. label.getJustificationType(),
  53376. jmax (1, (int) (label.getHeight() / label.getFont().getHeight())),
  53377. label.getMinimumHorizontalScale());
  53378. g.setColour (label.findColour (Label::outlineColourId).withMultipliedAlpha (alpha));
  53379. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  53380. }
  53381. else if (label.isEnabled())
  53382. {
  53383. g.setColour (label.findColour (Label::outlineColourId));
  53384. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  53385. }
  53386. }
  53387. void LookAndFeel::drawLinearSliderBackground (Graphics& g,
  53388. int x, int y,
  53389. int width, int height,
  53390. float /*sliderPos*/,
  53391. float /*minSliderPos*/,
  53392. float /*maxSliderPos*/,
  53393. const Slider::SliderStyle /*style*/,
  53394. Slider& slider)
  53395. {
  53396. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  53397. const Colour trackColour (slider.findColour (Slider::trackColourId));
  53398. const Colour gradCol1 (trackColour.overlaidWith (Colours::black.withAlpha (slider.isEnabled() ? 0.25f : 0.13f)));
  53399. const Colour gradCol2 (trackColour.overlaidWith (Colour (0x14000000)));
  53400. Path indent;
  53401. if (slider.isHorizontal())
  53402. {
  53403. const float iy = y + height * 0.5f - sliderRadius * 0.5f;
  53404. const float ih = sliderRadius;
  53405. g.setGradientFill (ColourGradient (gradCol1, 0.0f, iy,
  53406. gradCol2, 0.0f, iy + ih, false));
  53407. indent.addRoundedRectangle (x - sliderRadius * 0.5f, iy,
  53408. width + sliderRadius, ih,
  53409. 5.0f);
  53410. g.fillPath (indent);
  53411. }
  53412. else
  53413. {
  53414. const float ix = x + width * 0.5f - sliderRadius * 0.5f;
  53415. const float iw = sliderRadius;
  53416. g.setGradientFill (ColourGradient (gradCol1, ix, 0.0f,
  53417. gradCol2, ix + iw, 0.0f, false));
  53418. indent.addRoundedRectangle (ix, y - sliderRadius * 0.5f,
  53419. iw, height + sliderRadius,
  53420. 5.0f);
  53421. g.fillPath (indent);
  53422. }
  53423. g.setColour (Colour (0x4c000000));
  53424. g.strokePath (indent, PathStrokeType (0.5f));
  53425. }
  53426. void LookAndFeel::drawLinearSliderThumb (Graphics& g,
  53427. int x, int y,
  53428. int width, int height,
  53429. float sliderPos,
  53430. float minSliderPos,
  53431. float maxSliderPos,
  53432. const Slider::SliderStyle style,
  53433. Slider& slider)
  53434. {
  53435. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  53436. Colour knobColour (LookAndFeelHelpers::createBaseColour (slider.findColour (Slider::thumbColourId),
  53437. slider.hasKeyboardFocus (false) && slider.isEnabled(),
  53438. slider.isMouseOverOrDragging() && slider.isEnabled(),
  53439. slider.isMouseButtonDown() && slider.isEnabled()));
  53440. const float outlineThickness = slider.isEnabled() ? 0.8f : 0.3f;
  53441. if (style == Slider::LinearHorizontal || style == Slider::LinearVertical)
  53442. {
  53443. float kx, ky;
  53444. if (style == Slider::LinearVertical)
  53445. {
  53446. kx = x + width * 0.5f;
  53447. ky = sliderPos;
  53448. }
  53449. else
  53450. {
  53451. kx = sliderPos;
  53452. ky = y + height * 0.5f;
  53453. }
  53454. drawGlassSphere (g,
  53455. kx - sliderRadius,
  53456. ky - sliderRadius,
  53457. sliderRadius * 2.0f,
  53458. knobColour, outlineThickness);
  53459. }
  53460. else
  53461. {
  53462. if (style == Slider::ThreeValueVertical)
  53463. {
  53464. drawGlassSphere (g, x + width * 0.5f - sliderRadius,
  53465. sliderPos - sliderRadius,
  53466. sliderRadius * 2.0f,
  53467. knobColour, outlineThickness);
  53468. }
  53469. else if (style == Slider::ThreeValueHorizontal)
  53470. {
  53471. drawGlassSphere (g,sliderPos - sliderRadius,
  53472. y + height * 0.5f - sliderRadius,
  53473. sliderRadius * 2.0f,
  53474. knobColour, outlineThickness);
  53475. }
  53476. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  53477. {
  53478. const float sr = jmin (sliderRadius, width * 0.4f);
  53479. drawGlassPointer (g, jmax (0.0f, x + width * 0.5f - sliderRadius * 2.0f),
  53480. minSliderPos - sliderRadius,
  53481. sliderRadius * 2.0f, knobColour, outlineThickness, 1);
  53482. drawGlassPointer (g, jmin (x + width - sliderRadius * 2.0f, x + width * 0.5f), maxSliderPos - sr,
  53483. sliderRadius * 2.0f, knobColour, outlineThickness, 3);
  53484. }
  53485. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  53486. {
  53487. const float sr = jmin (sliderRadius, height * 0.4f);
  53488. drawGlassPointer (g, minSliderPos - sr,
  53489. jmax (0.0f, y + height * 0.5f - sliderRadius * 2.0f),
  53490. sliderRadius * 2.0f, knobColour, outlineThickness, 2);
  53491. drawGlassPointer (g, maxSliderPos - sliderRadius,
  53492. jmin (y + height - sliderRadius * 2.0f, y + height * 0.5f),
  53493. sliderRadius * 2.0f, knobColour, outlineThickness, 4);
  53494. }
  53495. }
  53496. }
  53497. void LookAndFeel::drawLinearSlider (Graphics& g,
  53498. int x, int y,
  53499. int width, int height,
  53500. float sliderPos,
  53501. float minSliderPos,
  53502. float maxSliderPos,
  53503. const Slider::SliderStyle style,
  53504. Slider& slider)
  53505. {
  53506. g.fillAll (slider.findColour (Slider::backgroundColourId));
  53507. if (style == Slider::LinearBar)
  53508. {
  53509. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  53510. Colour baseColour (LookAndFeelHelpers::createBaseColour (slider.findColour (Slider::thumbColourId)
  53511. .withMultipliedSaturation (slider.isEnabled() ? 1.0f : 0.5f),
  53512. false, isMouseOver,
  53513. isMouseOver || slider.isMouseButtonDown()));
  53514. drawShinyButtonShape (g,
  53515. (float) x, (float) y, sliderPos - (float) x, (float) height, 0.0f,
  53516. baseColour,
  53517. slider.isEnabled() ? 0.9f : 0.3f,
  53518. true, true, true, true);
  53519. }
  53520. else
  53521. {
  53522. drawLinearSliderBackground (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  53523. drawLinearSliderThumb (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  53524. }
  53525. }
  53526. int LookAndFeel::getSliderThumbRadius (Slider& slider)
  53527. {
  53528. return jmin (7,
  53529. slider.getHeight() / 2,
  53530. slider.getWidth() / 2) + 2;
  53531. }
  53532. void LookAndFeel::drawRotarySlider (Graphics& g,
  53533. int x, int y,
  53534. int width, int height,
  53535. float sliderPos,
  53536. const float rotaryStartAngle,
  53537. const float rotaryEndAngle,
  53538. Slider& slider)
  53539. {
  53540. const float radius = jmin (width / 2, height / 2) - 2.0f;
  53541. const float centreX = x + width * 0.5f;
  53542. const float centreY = y + height * 0.5f;
  53543. const float rx = centreX - radius;
  53544. const float ry = centreY - radius;
  53545. const float rw = radius * 2.0f;
  53546. const float angle = rotaryStartAngle + sliderPos * (rotaryEndAngle - rotaryStartAngle);
  53547. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  53548. if (radius > 12.0f)
  53549. {
  53550. if (slider.isEnabled())
  53551. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  53552. else
  53553. g.setColour (Colour (0x80808080));
  53554. const float thickness = 0.7f;
  53555. {
  53556. Path filledArc;
  53557. filledArc.addPieSegment (rx, ry, rw, rw,
  53558. rotaryStartAngle,
  53559. angle,
  53560. thickness);
  53561. g.fillPath (filledArc);
  53562. }
  53563. if (thickness > 0)
  53564. {
  53565. const float innerRadius = radius * 0.2f;
  53566. Path p;
  53567. p.addTriangle (-innerRadius, 0.0f,
  53568. 0.0f, -radius * thickness * 1.1f,
  53569. innerRadius, 0.0f);
  53570. p.addEllipse (-innerRadius, -innerRadius, innerRadius * 2.0f, innerRadius * 2.0f);
  53571. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  53572. }
  53573. if (slider.isEnabled())
  53574. g.setColour (slider.findColour (Slider::rotarySliderOutlineColourId));
  53575. else
  53576. g.setColour (Colour (0x80808080));
  53577. Path outlineArc;
  53578. outlineArc.addPieSegment (rx, ry, rw, rw, rotaryStartAngle, rotaryEndAngle, thickness);
  53579. outlineArc.closeSubPath();
  53580. g.strokePath (outlineArc, PathStrokeType (slider.isEnabled() ? (isMouseOver ? 2.0f : 1.2f) : 0.3f));
  53581. }
  53582. else
  53583. {
  53584. if (slider.isEnabled())
  53585. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  53586. else
  53587. g.setColour (Colour (0x80808080));
  53588. Path p;
  53589. p.addEllipse (-0.4f * rw, -0.4f * rw, rw * 0.8f, rw * 0.8f);
  53590. PathStrokeType (rw * 0.1f).createStrokedPath (p, p);
  53591. p.addLineSegment (Line<float> (0.0f, 0.0f, 0.0f, -radius), rw * 0.2f);
  53592. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  53593. }
  53594. }
  53595. Button* LookAndFeel::createSliderButton (const bool isIncrement)
  53596. {
  53597. return new TextButton (isIncrement ? "+" : "-", String::empty);
  53598. }
  53599. class SliderLabelComp : public Label
  53600. {
  53601. public:
  53602. SliderLabelComp() : Label (String::empty, String::empty) {}
  53603. ~SliderLabelComp() {}
  53604. void mouseWheelMove (const MouseEvent&, float, float) {}
  53605. };
  53606. Label* LookAndFeel::createSliderTextBox (Slider& slider)
  53607. {
  53608. Label* const l = new SliderLabelComp();
  53609. l->setJustificationType (Justification::centred);
  53610. l->setColour (Label::textColourId, slider.findColour (Slider::textBoxTextColourId));
  53611. l->setColour (Label::backgroundColourId,
  53612. (slider.getSliderStyle() == Slider::LinearBar) ? Colours::transparentBlack
  53613. : slider.findColour (Slider::textBoxBackgroundColourId));
  53614. l->setColour (Label::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  53615. l->setColour (TextEditor::textColourId, slider.findColour (Slider::textBoxTextColourId));
  53616. l->setColour (TextEditor::backgroundColourId,
  53617. slider.findColour (Slider::textBoxBackgroundColourId)
  53618. .withAlpha (slider.getSliderStyle() == Slider::LinearBar ? 0.7f : 1.0f));
  53619. l->setColour (TextEditor::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  53620. return l;
  53621. }
  53622. ImageEffectFilter* LookAndFeel::getSliderEffect()
  53623. {
  53624. return 0;
  53625. }
  53626. void LookAndFeel::getTooltipSize (const String& tipText, int& width, int& height)
  53627. {
  53628. const TextLayout tl (LookAndFeelHelpers::layoutTooltipText (tipText));
  53629. width = tl.getWidth() + 14;
  53630. height = tl.getHeight() + 6;
  53631. }
  53632. void LookAndFeel::drawTooltip (Graphics& g, const String& text, int width, int height)
  53633. {
  53634. g.fillAll (findColour (TooltipWindow::backgroundColourId));
  53635. const Colour textCol (findColour (TooltipWindow::textColourId));
  53636. #if ! JUCE_MAC // The mac windows already have a non-optional 1 pix outline, so don't double it here..
  53637. g.setColour (findColour (TooltipWindow::outlineColourId));
  53638. g.drawRect (0, 0, width, height, 1);
  53639. #endif
  53640. const TextLayout tl (LookAndFeelHelpers::layoutTooltipText (text));
  53641. g.setColour (findColour (TooltipWindow::textColourId));
  53642. tl.drawWithin (g, 0, 0, width, height, Justification::centred);
  53643. }
  53644. Button* LookAndFeel::createFilenameComponentBrowseButton (const String& text)
  53645. {
  53646. return new TextButton (text, TRANS("click to browse for a different file"));
  53647. }
  53648. void LookAndFeel::layoutFilenameComponent (FilenameComponent& filenameComp,
  53649. ComboBox* filenameBox,
  53650. Button* browseButton)
  53651. {
  53652. browseButton->setSize (80, filenameComp.getHeight());
  53653. TextButton* const tb = dynamic_cast <TextButton*> (browseButton);
  53654. if (tb != 0)
  53655. tb->changeWidthToFitText();
  53656. browseButton->setTopRightPosition (filenameComp.getWidth(), 0);
  53657. filenameBox->setBounds (0, 0, browseButton->getX(), filenameComp.getHeight());
  53658. }
  53659. void LookAndFeel::drawImageButton (Graphics& g, Image* image,
  53660. int imageX, int imageY, int imageW, int imageH,
  53661. const Colour& overlayColour,
  53662. float imageOpacity,
  53663. ImageButton& button)
  53664. {
  53665. if (! button.isEnabled())
  53666. imageOpacity *= 0.3f;
  53667. if (! overlayColour.isOpaque())
  53668. {
  53669. g.setOpacity (imageOpacity);
  53670. g.drawImage (*image, imageX, imageY, imageW, imageH,
  53671. 0, 0, image->getWidth(), image->getHeight(), false);
  53672. }
  53673. if (! overlayColour.isTransparent())
  53674. {
  53675. g.setColour (overlayColour);
  53676. g.drawImage (*image, imageX, imageY, imageW, imageH,
  53677. 0, 0, image->getWidth(), image->getHeight(), true);
  53678. }
  53679. }
  53680. void LookAndFeel::drawCornerResizer (Graphics& g,
  53681. int w, int h,
  53682. bool /*isMouseOver*/,
  53683. bool /*isMouseDragging*/)
  53684. {
  53685. const float lineThickness = jmin (w, h) * 0.075f;
  53686. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  53687. {
  53688. g.setColour (Colours::lightgrey);
  53689. g.drawLine (w * i,
  53690. h + 1.0f,
  53691. w + 1.0f,
  53692. h * i,
  53693. lineThickness);
  53694. g.setColour (Colours::darkgrey);
  53695. g.drawLine (w * i + lineThickness,
  53696. h + 1.0f,
  53697. w + 1.0f,
  53698. h * i + lineThickness,
  53699. lineThickness);
  53700. }
  53701. }
  53702. void LookAndFeel::drawResizableFrame (Graphics& g, int w, int h, const BorderSize& border)
  53703. {
  53704. if (! border.isEmpty())
  53705. {
  53706. const Rectangle<int> fullSize (0, 0, w, h);
  53707. const Rectangle<int> centreArea (border.subtractedFrom (fullSize));
  53708. g.saveState();
  53709. g.excludeClipRegion (centreArea);
  53710. g.setColour (Colour (0x50000000));
  53711. g.drawRect (fullSize);
  53712. g.setColour (Colour (0x19000000));
  53713. g.drawRect (centreArea.expanded (1, 1));
  53714. g.restoreState();
  53715. }
  53716. }
  53717. void LookAndFeel::fillResizableWindowBackground (Graphics& g, int /*w*/, int /*h*/,
  53718. const BorderSize& /*border*/, ResizableWindow& window)
  53719. {
  53720. g.fillAll (window.getBackgroundColour());
  53721. }
  53722. void LookAndFeel::drawResizableWindowBorder (Graphics&, int /*w*/, int /*h*/,
  53723. const BorderSize& /*border*/, ResizableWindow&)
  53724. {
  53725. }
  53726. void LookAndFeel::drawDocumentWindowTitleBar (DocumentWindow& window,
  53727. Graphics& g, int w, int h,
  53728. int titleSpaceX, int titleSpaceW,
  53729. const Image* icon,
  53730. bool drawTitleTextOnLeft)
  53731. {
  53732. const bool isActive = window.isActiveWindow();
  53733. g.setGradientFill (ColourGradient (window.getBackgroundColour(),
  53734. 0.0f, 0.0f,
  53735. window.getBackgroundColour().contrasting (isActive ? 0.15f : 0.05f),
  53736. 0.0f, (float) h, false));
  53737. g.fillAll();
  53738. Font font (h * 0.65f, Font::bold);
  53739. g.setFont (font);
  53740. int textW = font.getStringWidth (window.getName());
  53741. int iconW = 0;
  53742. int iconH = 0;
  53743. if (icon != 0)
  53744. {
  53745. iconH = (int) font.getHeight();
  53746. iconW = icon->getWidth() * iconH / icon->getHeight() + 4;
  53747. }
  53748. textW = jmin (titleSpaceW, textW + iconW);
  53749. int textX = drawTitleTextOnLeft ? titleSpaceX
  53750. : jmax (titleSpaceX, (w - textW) / 2);
  53751. if (textX + textW > titleSpaceX + titleSpaceW)
  53752. textX = titleSpaceX + titleSpaceW - textW;
  53753. if (icon != 0)
  53754. {
  53755. g.setOpacity (isActive ? 1.0f : 0.6f);
  53756. g.drawImageWithin (*icon, textX, (h - iconH) / 2, iconW, iconH,
  53757. RectanglePlacement::centred, false);
  53758. textX += iconW;
  53759. textW -= iconW;
  53760. }
  53761. if (window.isColourSpecified (DocumentWindow::textColourId) || isColourSpecified (DocumentWindow::textColourId))
  53762. g.setColour (findColour (DocumentWindow::textColourId));
  53763. else
  53764. g.setColour (window.getBackgroundColour().contrasting (isActive ? 0.7f : 0.4f));
  53765. g.drawText (window.getName(), textX, 0, textW, h, Justification::centredLeft, true);
  53766. }
  53767. class GlassWindowButton : public Button
  53768. {
  53769. public:
  53770. GlassWindowButton (const String& name, const Colour& col,
  53771. const Path& normalShape_,
  53772. const Path& toggledShape_) throw()
  53773. : Button (name),
  53774. colour (col),
  53775. normalShape (normalShape_),
  53776. toggledShape (toggledShape_)
  53777. {
  53778. }
  53779. ~GlassWindowButton()
  53780. {
  53781. }
  53782. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  53783. {
  53784. float alpha = isMouseOverButton ? (isButtonDown ? 1.0f : 0.8f) : 0.55f;
  53785. if (! isEnabled())
  53786. alpha *= 0.5f;
  53787. float x = 0, y = 0, diam;
  53788. if (getWidth() < getHeight())
  53789. {
  53790. diam = (float) getWidth();
  53791. y = (getHeight() - getWidth()) * 0.5f;
  53792. }
  53793. else
  53794. {
  53795. diam = (float) getHeight();
  53796. y = (getWidth() - getHeight()) * 0.5f;
  53797. }
  53798. x += diam * 0.05f;
  53799. y += diam * 0.05f;
  53800. diam *= 0.9f;
  53801. g.setGradientFill (ColourGradient (Colour::greyLevel (0.9f).withAlpha (alpha), 0, y + diam,
  53802. Colour::greyLevel (0.6f).withAlpha (alpha), 0, y, false));
  53803. g.fillEllipse (x, y, diam, diam);
  53804. x += 2.0f;
  53805. y += 2.0f;
  53806. diam -= 4.0f;
  53807. LookAndFeel::drawGlassSphere (g, x, y, diam, colour.withAlpha (alpha), 1.0f);
  53808. Path& p = getToggleState() ? toggledShape : normalShape;
  53809. const AffineTransform t (p.getTransformToScaleToFit (x + diam * 0.3f, y + diam * 0.3f,
  53810. diam * 0.4f, diam * 0.4f, true));
  53811. g.setColour (Colours::black.withAlpha (alpha * 0.6f));
  53812. g.fillPath (p, t);
  53813. }
  53814. juce_UseDebuggingNewOperator
  53815. private:
  53816. Colour colour;
  53817. Path normalShape, toggledShape;
  53818. GlassWindowButton (const GlassWindowButton&);
  53819. GlassWindowButton& operator= (const GlassWindowButton&);
  53820. };
  53821. Button* LookAndFeel::createDocumentWindowButton (int buttonType)
  53822. {
  53823. Path shape;
  53824. const float crossThickness = 0.25f;
  53825. if (buttonType == DocumentWindow::closeButton)
  53826. {
  53827. shape.addLineSegment (Line<float> (0.0f, 0.0f, 1.0f, 1.0f), crossThickness * 1.4f);
  53828. shape.addLineSegment (Line<float> (1.0f, 0.0f, 0.0f, 1.0f), crossThickness * 1.4f);
  53829. return new GlassWindowButton ("close", Colour (0xffdd1100), shape, shape);
  53830. }
  53831. else if (buttonType == DocumentWindow::minimiseButton)
  53832. {
  53833. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), crossThickness);
  53834. return new GlassWindowButton ("minimise", Colour (0xffaa8811), shape, shape);
  53835. }
  53836. else if (buttonType == DocumentWindow::maximiseButton)
  53837. {
  53838. shape.addLineSegment (Line<float> (0.5f, 0.0f, 0.5f, 1.0f), crossThickness);
  53839. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), crossThickness);
  53840. Path fullscreenShape;
  53841. fullscreenShape.startNewSubPath (45.0f, 100.0f);
  53842. fullscreenShape.lineTo (0.0f, 100.0f);
  53843. fullscreenShape.lineTo (0.0f, 0.0f);
  53844. fullscreenShape.lineTo (100.0f, 0.0f);
  53845. fullscreenShape.lineTo (100.0f, 45.0f);
  53846. fullscreenShape.addRectangle (45.0f, 45.0f, 100.0f, 100.0f);
  53847. PathStrokeType (30.0f).createStrokedPath (fullscreenShape, fullscreenShape);
  53848. return new GlassWindowButton ("maximise", Colour (0xff119911), shape, fullscreenShape);
  53849. }
  53850. jassertfalse;
  53851. return 0;
  53852. }
  53853. void LookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  53854. int titleBarX,
  53855. int titleBarY,
  53856. int titleBarW,
  53857. int titleBarH,
  53858. Button* minimiseButton,
  53859. Button* maximiseButton,
  53860. Button* closeButton,
  53861. bool positionTitleBarButtonsOnLeft)
  53862. {
  53863. const int buttonW = titleBarH - titleBarH / 8;
  53864. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  53865. : titleBarX + titleBarW - buttonW - buttonW / 4;
  53866. if (closeButton != 0)
  53867. {
  53868. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53869. x += positionTitleBarButtonsOnLeft ? buttonW : -(buttonW + buttonW / 4);
  53870. }
  53871. if (positionTitleBarButtonsOnLeft)
  53872. swapVariables (minimiseButton, maximiseButton);
  53873. if (maximiseButton != 0)
  53874. {
  53875. maximiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53876. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  53877. }
  53878. if (minimiseButton != 0)
  53879. minimiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53880. }
  53881. int LookAndFeel::getDefaultMenuBarHeight()
  53882. {
  53883. return 24;
  53884. }
  53885. DropShadower* LookAndFeel::createDropShadowerForComponent (Component*)
  53886. {
  53887. return new DropShadower (0.4f, 1, 5, 10);
  53888. }
  53889. void LookAndFeel::drawStretchableLayoutResizerBar (Graphics& g,
  53890. int w, int h,
  53891. bool /*isVerticalBar*/,
  53892. bool isMouseOver,
  53893. bool isMouseDragging)
  53894. {
  53895. float alpha = 0.5f;
  53896. if (isMouseOver || isMouseDragging)
  53897. {
  53898. g.fillAll (Colour (0x190000ff));
  53899. alpha = 1.0f;
  53900. }
  53901. const float cx = w * 0.5f;
  53902. const float cy = h * 0.5f;
  53903. const float cr = jmin (w, h) * 0.4f;
  53904. g.setGradientFill (ColourGradient (Colours::white.withAlpha (alpha), cx + cr * 0.1f, cy + cr,
  53905. Colours::black.withAlpha (alpha), cx, cy - cr * 4.0f,
  53906. true));
  53907. g.fillEllipse (cx - cr, cy - cr, cr * 2.0f, cr * 2.0f);
  53908. }
  53909. void LookAndFeel::drawGroupComponentOutline (Graphics& g, int width, int height,
  53910. const String& text,
  53911. const Justification& position,
  53912. GroupComponent& group)
  53913. {
  53914. const float textH = 15.0f;
  53915. const float indent = 3.0f;
  53916. const float textEdgeGap = 4.0f;
  53917. float cs = 5.0f;
  53918. Font f (textH);
  53919. Path p;
  53920. float x = indent;
  53921. float y = f.getAscent() - 3.0f;
  53922. float w = jmax (0.0f, width - x * 2.0f);
  53923. float h = jmax (0.0f, height - y - indent);
  53924. cs = jmin (cs, w * 0.5f, h * 0.5f);
  53925. const float cs2 = 2.0f * cs;
  53926. float textW = text.isEmpty() ? 0 : jlimit (0.0f, jmax (0.0f, w - cs2 - textEdgeGap * 2), f.getStringWidth (text) + textEdgeGap * 2.0f);
  53927. float textX = cs + textEdgeGap;
  53928. if (position.testFlags (Justification::horizontallyCentred))
  53929. textX = cs + (w - cs2 - textW) * 0.5f;
  53930. else if (position.testFlags (Justification::right))
  53931. textX = w - cs - textW - textEdgeGap;
  53932. p.startNewSubPath (x + textX + textW, y);
  53933. p.lineTo (x + w - cs, y);
  53934. p.addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  53935. p.lineTo (x + w, y + h - cs);
  53936. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  53937. p.lineTo (x + cs, y + h);
  53938. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  53939. p.lineTo (x, y + cs);
  53940. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  53941. p.lineTo (x + textX, y);
  53942. const float alpha = group.isEnabled() ? 1.0f : 0.5f;
  53943. g.setColour (group.findColour (GroupComponent::outlineColourId)
  53944. .withMultipliedAlpha (alpha));
  53945. g.strokePath (p, PathStrokeType (2.0f));
  53946. g.setColour (group.findColour (GroupComponent::textColourId)
  53947. .withMultipliedAlpha (alpha));
  53948. g.setFont (f);
  53949. g.drawText (text,
  53950. roundToInt (x + textX), 0,
  53951. roundToInt (textW),
  53952. roundToInt (textH),
  53953. Justification::centred, true);
  53954. }
  53955. int LookAndFeel::getTabButtonOverlap (int tabDepth)
  53956. {
  53957. return 1 + tabDepth / 3;
  53958. }
  53959. int LookAndFeel::getTabButtonSpaceAroundImage()
  53960. {
  53961. return 4;
  53962. }
  53963. void LookAndFeel::createTabButtonShape (Path& p,
  53964. int width, int height,
  53965. int /*tabIndex*/,
  53966. const String& /*text*/,
  53967. Button& /*button*/,
  53968. TabbedButtonBar::Orientation orientation,
  53969. const bool /*isMouseOver*/,
  53970. const bool /*isMouseDown*/,
  53971. const bool /*isFrontTab*/)
  53972. {
  53973. const float w = (float) width;
  53974. const float h = (float) height;
  53975. float length = w;
  53976. float depth = h;
  53977. if (orientation == TabbedButtonBar::TabsAtLeft
  53978. || orientation == TabbedButtonBar::TabsAtRight)
  53979. {
  53980. swapVariables (length, depth);
  53981. }
  53982. const float indent = (float) getTabButtonOverlap ((int) depth);
  53983. const float overhang = 4.0f;
  53984. if (orientation == TabbedButtonBar::TabsAtLeft)
  53985. {
  53986. p.startNewSubPath (w, 0.0f);
  53987. p.lineTo (0.0f, indent);
  53988. p.lineTo (0.0f, h - indent);
  53989. p.lineTo (w, h);
  53990. p.lineTo (w + overhang, h + overhang);
  53991. p.lineTo (w + overhang, -overhang);
  53992. }
  53993. else if (orientation == TabbedButtonBar::TabsAtRight)
  53994. {
  53995. p.startNewSubPath (0.0f, 0.0f);
  53996. p.lineTo (w, indent);
  53997. p.lineTo (w, h - indent);
  53998. p.lineTo (0.0f, h);
  53999. p.lineTo (-overhang, h + overhang);
  54000. p.lineTo (-overhang, -overhang);
  54001. }
  54002. else if (orientation == TabbedButtonBar::TabsAtBottom)
  54003. {
  54004. p.startNewSubPath (0.0f, 0.0f);
  54005. p.lineTo (indent, h);
  54006. p.lineTo (w - indent, h);
  54007. p.lineTo (w, 0.0f);
  54008. p.lineTo (w + overhang, -overhang);
  54009. p.lineTo (-overhang, -overhang);
  54010. }
  54011. else
  54012. {
  54013. p.startNewSubPath (0.0f, h);
  54014. p.lineTo (indent, 0.0f);
  54015. p.lineTo (w - indent, 0.0f);
  54016. p.lineTo (w, h);
  54017. p.lineTo (w + overhang, h + overhang);
  54018. p.lineTo (-overhang, h + overhang);
  54019. }
  54020. p.closeSubPath();
  54021. p = p.createPathWithRoundedCorners (3.0f);
  54022. }
  54023. void LookAndFeel::fillTabButtonShape (Graphics& g,
  54024. const Path& path,
  54025. const Colour& preferredColour,
  54026. int /*tabIndex*/,
  54027. const String& /*text*/,
  54028. Button& button,
  54029. TabbedButtonBar::Orientation /*orientation*/,
  54030. const bool /*isMouseOver*/,
  54031. const bool /*isMouseDown*/,
  54032. const bool isFrontTab)
  54033. {
  54034. g.setColour (isFrontTab ? preferredColour
  54035. : preferredColour.withMultipliedAlpha (0.9f));
  54036. g.fillPath (path);
  54037. g.setColour (button.findColour (isFrontTab ? TabbedButtonBar::frontOutlineColourId
  54038. : TabbedButtonBar::tabOutlineColourId, false)
  54039. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  54040. g.strokePath (path, PathStrokeType (isFrontTab ? 1.0f : 0.5f));
  54041. }
  54042. void LookAndFeel::drawTabButtonText (Graphics& g,
  54043. int x, int y, int w, int h,
  54044. const Colour& preferredBackgroundColour,
  54045. int /*tabIndex*/,
  54046. const String& text,
  54047. Button& button,
  54048. TabbedButtonBar::Orientation orientation,
  54049. const bool isMouseOver,
  54050. const bool isMouseDown,
  54051. const bool isFrontTab)
  54052. {
  54053. int length = w;
  54054. int depth = h;
  54055. if (orientation == TabbedButtonBar::TabsAtLeft
  54056. || orientation == TabbedButtonBar::TabsAtRight)
  54057. {
  54058. swapVariables (length, depth);
  54059. }
  54060. Font font (depth * 0.6f);
  54061. font.setUnderline (button.hasKeyboardFocus (false));
  54062. GlyphArrangement textLayout;
  54063. textLayout.addFittedText (font, text.trim(),
  54064. 0.0f, 0.0f, (float) length, (float) depth,
  54065. Justification::centred,
  54066. jmax (1, depth / 12));
  54067. AffineTransform transform;
  54068. if (orientation == TabbedButtonBar::TabsAtLeft)
  54069. {
  54070. transform = transform.rotated (float_Pi * -0.5f)
  54071. .translated ((float) x, (float) (y + h));
  54072. }
  54073. else if (orientation == TabbedButtonBar::TabsAtRight)
  54074. {
  54075. transform = transform.rotated (float_Pi * 0.5f)
  54076. .translated ((float) (x + w), (float) y);
  54077. }
  54078. else
  54079. {
  54080. transform = transform.translated ((float) x, (float) y);
  54081. }
  54082. if (isFrontTab && (button.isColourSpecified (TabbedButtonBar::frontTextColourId) || isColourSpecified (TabbedButtonBar::frontTextColourId)))
  54083. g.setColour (findColour (TabbedButtonBar::frontTextColourId));
  54084. else if (button.isColourSpecified (TabbedButtonBar::tabTextColourId) || isColourSpecified (TabbedButtonBar::tabTextColourId))
  54085. g.setColour (findColour (TabbedButtonBar::tabTextColourId));
  54086. else
  54087. g.setColour (preferredBackgroundColour.contrasting());
  54088. if (! (isMouseOver || isMouseDown))
  54089. g.setOpacity (0.8f);
  54090. if (! button.isEnabled())
  54091. g.setOpacity (0.3f);
  54092. textLayout.draw (g, transform);
  54093. }
  54094. int LookAndFeel::getTabButtonBestWidth (int /*tabIndex*/,
  54095. const String& text,
  54096. int tabDepth,
  54097. Button&)
  54098. {
  54099. Font f (tabDepth * 0.6f);
  54100. return f.getStringWidth (text.trim()) + getTabButtonOverlap (tabDepth) * 2;
  54101. }
  54102. void LookAndFeel::drawTabButton (Graphics& g,
  54103. int w, int h,
  54104. const Colour& preferredColour,
  54105. int tabIndex,
  54106. const String& text,
  54107. Button& button,
  54108. TabbedButtonBar::Orientation orientation,
  54109. const bool isMouseOver,
  54110. const bool isMouseDown,
  54111. const bool isFrontTab)
  54112. {
  54113. int length = w;
  54114. int depth = h;
  54115. if (orientation == TabbedButtonBar::TabsAtLeft
  54116. || orientation == TabbedButtonBar::TabsAtRight)
  54117. {
  54118. swapVariables (length, depth);
  54119. }
  54120. Path tabShape;
  54121. createTabButtonShape (tabShape, w, h,
  54122. tabIndex, text, button, orientation,
  54123. isMouseOver, isMouseDown, isFrontTab);
  54124. fillTabButtonShape (g, tabShape, preferredColour,
  54125. tabIndex, text, button, orientation,
  54126. isMouseOver, isMouseDown, isFrontTab);
  54127. const int indent = getTabButtonOverlap (depth);
  54128. int x = 0, y = 0;
  54129. if (orientation == TabbedButtonBar::TabsAtLeft
  54130. || orientation == TabbedButtonBar::TabsAtRight)
  54131. {
  54132. y += indent;
  54133. h -= indent * 2;
  54134. }
  54135. else
  54136. {
  54137. x += indent;
  54138. w -= indent * 2;
  54139. }
  54140. drawTabButtonText (g, x, y, w, h, preferredColour,
  54141. tabIndex, text, button, orientation,
  54142. isMouseOver, isMouseDown, isFrontTab);
  54143. }
  54144. void LookAndFeel::drawTabAreaBehindFrontButton (Graphics& g,
  54145. int w, int h,
  54146. TabbedButtonBar& tabBar,
  54147. TabbedButtonBar::Orientation orientation)
  54148. {
  54149. const float shadowSize = 0.2f;
  54150. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  54151. Rectangle<int> shadowRect;
  54152. if (orientation == TabbedButtonBar::TabsAtLeft)
  54153. {
  54154. x1 = (float) w;
  54155. x2 = w * (1.0f - shadowSize);
  54156. shadowRect.setBounds ((int) x2, 0, w - (int) x2, h);
  54157. }
  54158. else if (orientation == TabbedButtonBar::TabsAtRight)
  54159. {
  54160. x2 = w * shadowSize;
  54161. shadowRect.setBounds (0, 0, (int) x2, h);
  54162. }
  54163. else if (orientation == TabbedButtonBar::TabsAtBottom)
  54164. {
  54165. y2 = h * shadowSize;
  54166. shadowRect.setBounds (0, 0, w, (int) y2);
  54167. }
  54168. else
  54169. {
  54170. y1 = (float) h;
  54171. y2 = h * (1.0f - shadowSize);
  54172. shadowRect.setBounds (0, (int) y2, w, h - (int) y2);
  54173. }
  54174. g.setGradientFill (ColourGradient (Colours::black.withAlpha (tabBar.isEnabled() ? 0.3f : 0.15f), x1, y1,
  54175. Colours::transparentBlack, x2, y2, false));
  54176. shadowRect.expand (2, 2);
  54177. g.fillRect (shadowRect);
  54178. g.setColour (Colour (0x80000000));
  54179. if (orientation == TabbedButtonBar::TabsAtLeft)
  54180. {
  54181. g.fillRect (w - 1, 0, 1, h);
  54182. }
  54183. else if (orientation == TabbedButtonBar::TabsAtRight)
  54184. {
  54185. g.fillRect (0, 0, 1, h);
  54186. }
  54187. else if (orientation == TabbedButtonBar::TabsAtBottom)
  54188. {
  54189. g.fillRect (0, 0, w, 1);
  54190. }
  54191. else
  54192. {
  54193. g.fillRect (0, h - 1, w, 1);
  54194. }
  54195. }
  54196. Button* LookAndFeel::createTabBarExtrasButton()
  54197. {
  54198. const float thickness = 7.0f;
  54199. const float indent = 22.0f;
  54200. Path p;
  54201. p.addEllipse (-10.0f, -10.0f, 120.0f, 120.0f);
  54202. DrawablePath ellipse;
  54203. ellipse.setPath (p);
  54204. ellipse.setFill (Colour (0x99ffffff));
  54205. p.clear();
  54206. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  54207. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  54208. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  54209. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  54210. p.setUsingNonZeroWinding (false);
  54211. DrawablePath dp;
  54212. dp.setPath (p);
  54213. dp.setFill (Colour (0x59000000));
  54214. DrawableComposite normalImage;
  54215. normalImage.insertDrawable (ellipse);
  54216. normalImage.insertDrawable (dp);
  54217. dp.setFill (Colour (0xcc000000));
  54218. DrawableComposite overImage;
  54219. overImage.insertDrawable (ellipse);
  54220. overImage.insertDrawable (dp);
  54221. DrawableButton* db = new DrawableButton ("tabs", DrawableButton::ImageFitted);
  54222. db->setImages (&normalImage, &overImage, 0);
  54223. return db;
  54224. }
  54225. void LookAndFeel::drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header)
  54226. {
  54227. g.fillAll (Colours::white);
  54228. const int w = header.getWidth();
  54229. const int h = header.getHeight();
  54230. g.setGradientFill (ColourGradient (Colour (0xffe8ebf9), 0.0f, h * 0.5f,
  54231. Colour (0xfff6f8f9), 0.0f, h - 1.0f,
  54232. false));
  54233. g.fillRect (0, h / 2, w, h);
  54234. g.setColour (Colour (0x33000000));
  54235. g.fillRect (0, h - 1, w, 1);
  54236. for (int i = header.getNumColumns (true); --i >= 0;)
  54237. g.fillRect (header.getColumnPosition (i).getRight() - 1, 0, 1, h - 1);
  54238. }
  54239. void LookAndFeel::drawTableHeaderColumn (Graphics& g, const String& columnName, int /*columnId*/,
  54240. int width, int height,
  54241. bool isMouseOver, bool isMouseDown,
  54242. int columnFlags)
  54243. {
  54244. if (isMouseDown)
  54245. g.fillAll (Colour (0x8899aadd));
  54246. else if (isMouseOver)
  54247. g.fillAll (Colour (0x5599aadd));
  54248. int rightOfText = width - 4;
  54249. if ((columnFlags & (TableHeaderComponent::sortedForwards | TableHeaderComponent::sortedBackwards)) != 0)
  54250. {
  54251. const float top = height * ((columnFlags & TableHeaderComponent::sortedForwards) != 0 ? 0.35f : (1.0f - 0.35f));
  54252. const float bottom = height - top;
  54253. const float w = height * 0.5f;
  54254. const float x = rightOfText - (w * 1.25f);
  54255. rightOfText = (int) x;
  54256. Path sortArrow;
  54257. sortArrow.addTriangle (x, bottom, x + w * 0.5f, top, x + w, bottom);
  54258. g.setColour (Colour (0x99000000));
  54259. g.fillPath (sortArrow);
  54260. }
  54261. g.setColour (Colours::black);
  54262. g.setFont (height * 0.5f, Font::bold);
  54263. const int textX = 4;
  54264. g.drawFittedText (columnName, textX, 0, rightOfText - textX, height, Justification::centredLeft, 1);
  54265. }
  54266. void LookAndFeel::paintToolbarBackground (Graphics& g, int w, int h, Toolbar& toolbar)
  54267. {
  54268. const Colour background (toolbar.findColour (Toolbar::backgroundColourId));
  54269. g.setGradientFill (ColourGradient (background, 0.0f, 0.0f,
  54270. background.darker (0.1f),
  54271. toolbar.isVertical() ? w - 1.0f : 0.0f,
  54272. toolbar.isVertical() ? 0.0f : h - 1.0f,
  54273. false));
  54274. g.fillAll();
  54275. }
  54276. Button* LookAndFeel::createToolbarMissingItemsButton (Toolbar& /*toolbar*/)
  54277. {
  54278. return createTabBarExtrasButton();
  54279. }
  54280. void LookAndFeel::paintToolbarButtonBackground (Graphics& g, int /*width*/, int /*height*/,
  54281. bool isMouseOver, bool isMouseDown,
  54282. ToolbarItemComponent& component)
  54283. {
  54284. if (isMouseDown)
  54285. g.fillAll (component.findColour (Toolbar::buttonMouseDownBackgroundColourId, true));
  54286. else if (isMouseOver)
  54287. g.fillAll (component.findColour (Toolbar::buttonMouseOverBackgroundColourId, true));
  54288. }
  54289. void LookAndFeel::paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  54290. const String& text, ToolbarItemComponent& component)
  54291. {
  54292. g.setColour (component.findColour (Toolbar::labelTextColourId, true)
  54293. .withAlpha (component.isEnabled() ? 1.0f : 0.25f));
  54294. const float fontHeight = jmin (14.0f, height * 0.85f);
  54295. g.setFont (fontHeight);
  54296. g.drawFittedText (text,
  54297. x, y, width, height,
  54298. Justification::centred,
  54299. jmax (1, height / (int) fontHeight));
  54300. }
  54301. void LookAndFeel::drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  54302. bool isOpen, int width, int height)
  54303. {
  54304. const int buttonSize = (height * 3) / 4;
  54305. const int buttonIndent = (height - buttonSize) / 2;
  54306. drawTreeviewPlusMinusBox (g, buttonIndent, buttonIndent, buttonSize, buttonSize, ! isOpen, false);
  54307. const int textX = buttonIndent * 2 + buttonSize + 2;
  54308. g.setColour (Colours::black);
  54309. g.setFont (height * 0.7f, Font::bold);
  54310. g.drawText (name, textX, 0, width - textX - 4, height, Justification::centredLeft, true);
  54311. }
  54312. void LookAndFeel::drawPropertyComponentBackground (Graphics& g, int width, int height,
  54313. PropertyComponent&)
  54314. {
  54315. g.setColour (Colour (0x66ffffff));
  54316. g.fillRect (0, 0, width, height - 1);
  54317. }
  54318. void LookAndFeel::drawPropertyComponentLabel (Graphics& g, int, int height,
  54319. PropertyComponent& component)
  54320. {
  54321. g.setColour (Colours::black);
  54322. if (! component.isEnabled())
  54323. g.setOpacity (0.6f);
  54324. g.setFont (jmin (height, 24) * 0.65f);
  54325. const Rectangle<int> r (getPropertyComponentContentPosition (component));
  54326. g.drawFittedText (component.getName(),
  54327. 3, r.getY(), r.getX() - 5, r.getHeight(),
  54328. Justification::centredLeft, 2);
  54329. }
  54330. const Rectangle<int> LookAndFeel::getPropertyComponentContentPosition (PropertyComponent& component)
  54331. {
  54332. return Rectangle<int> (component.getWidth() / 3, 1,
  54333. component.getWidth() - component.getWidth() / 3 - 1, component.getHeight() - 3);
  54334. }
  54335. void LookAndFeel::drawCallOutBoxBackground (CallOutBox& box, Graphics& g, const Path& path)
  54336. {
  54337. Image content (Image::ARGB, box.getWidth(), box.getHeight(), true);
  54338. {
  54339. Graphics g2 (content);
  54340. g2.setColour (Colour::greyLevel (0.23f).withAlpha (0.9f));
  54341. g2.fillPath (path);
  54342. g2.setColour (Colours::white.withAlpha (0.8f));
  54343. g2.strokePath (path, PathStrokeType (2.0f));
  54344. }
  54345. DropShadowEffect shadow;
  54346. shadow.setShadowProperties (5.0f, 0.4f, 0, 2);
  54347. shadow.applyEffect (content, g, 1.0f);
  54348. }
  54349. void LookAndFeel::createFileChooserHeaderText (const String& title,
  54350. const String& instructions,
  54351. GlyphArrangement& text,
  54352. int width)
  54353. {
  54354. text.clear();
  54355. text.addJustifiedText (Font (17.0f, Font::bold), title,
  54356. 8.0f, 22.0f, width - 16.0f,
  54357. Justification::centred);
  54358. text.addJustifiedText (Font (14.0f), instructions,
  54359. 8.0f, 24.0f + 16.0f, width - 16.0f,
  54360. Justification::centred);
  54361. }
  54362. void LookAndFeel::drawFileBrowserRow (Graphics& g, int width, int height,
  54363. const String& filename, Image* icon,
  54364. const String& fileSizeDescription,
  54365. const String& fileTimeDescription,
  54366. const bool isDirectory,
  54367. const bool isItemSelected,
  54368. const int /*itemIndex*/,
  54369. DirectoryContentsDisplayComponent&)
  54370. {
  54371. if (isItemSelected)
  54372. g.fillAll (findColour (DirectoryContentsDisplayComponent::highlightColourId));
  54373. const int x = 32;
  54374. g.setColour (Colours::black);
  54375. if (icon != 0 && icon->isValid())
  54376. {
  54377. g.drawImageWithin (*icon, 2, 2, x - 4, height - 4,
  54378. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  54379. false);
  54380. }
  54381. else
  54382. {
  54383. const Drawable* d = isDirectory ? getDefaultFolderImage()
  54384. : getDefaultDocumentFileImage();
  54385. if (d != 0)
  54386. d->drawWithin (g, Rectangle<float> (2.0f, 2.0f, x - 4.0f, height - 4.0f),
  54387. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize, 1.0f);
  54388. }
  54389. g.setColour (findColour (DirectoryContentsDisplayComponent::textColourId));
  54390. g.setFont (height * 0.7f);
  54391. if (width > 450 && ! isDirectory)
  54392. {
  54393. const int sizeX = roundToInt (width * 0.7f);
  54394. const int dateX = roundToInt (width * 0.8f);
  54395. g.drawFittedText (filename,
  54396. x, 0, sizeX - x, height,
  54397. Justification::centredLeft, 1);
  54398. g.setFont (height * 0.5f);
  54399. g.setColour (Colours::darkgrey);
  54400. if (! isDirectory)
  54401. {
  54402. g.drawFittedText (fileSizeDescription,
  54403. sizeX, 0, dateX - sizeX - 8, height,
  54404. Justification::centredRight, 1);
  54405. g.drawFittedText (fileTimeDescription,
  54406. dateX, 0, width - 8 - dateX, height,
  54407. Justification::centredRight, 1);
  54408. }
  54409. }
  54410. else
  54411. {
  54412. g.drawFittedText (filename,
  54413. x, 0, width - x, height,
  54414. Justification::centredLeft, 1);
  54415. }
  54416. }
  54417. Button* LookAndFeel::createFileBrowserGoUpButton()
  54418. {
  54419. DrawableButton* goUpButton = new DrawableButton ("up", DrawableButton::ImageOnButtonBackground);
  54420. Path arrowPath;
  54421. arrowPath.addArrow (Line<float> (50.0f, 100.0f, 50.0f, 0.0f), 40.0f, 100.0f, 50.0f);
  54422. DrawablePath arrowImage;
  54423. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  54424. arrowImage.setPath (arrowPath);
  54425. goUpButton->setImages (&arrowImage);
  54426. return goUpButton;
  54427. }
  54428. void LookAndFeel::layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  54429. DirectoryContentsDisplayComponent* fileListComponent,
  54430. FilePreviewComponent* previewComp,
  54431. ComboBox* currentPathBox,
  54432. TextEditor* filenameBox,
  54433. Button* goUpButton)
  54434. {
  54435. const int x = 8;
  54436. int w = browserComp.getWidth() - x - x;
  54437. if (previewComp != 0)
  54438. {
  54439. const int previewWidth = w / 3;
  54440. previewComp->setBounds (x + w - previewWidth, 0, previewWidth, browserComp.getHeight());
  54441. w -= previewWidth + 4;
  54442. }
  54443. int y = 4;
  54444. const int controlsHeight = 22;
  54445. const int bottomSectionHeight = controlsHeight + 8;
  54446. const int upButtonWidth = 50;
  54447. currentPathBox->setBounds (x, y, w - upButtonWidth - 6, controlsHeight);
  54448. goUpButton->setBounds (x + w - upButtonWidth, y, upButtonWidth, controlsHeight);
  54449. y += controlsHeight + 4;
  54450. Component* const listAsComp = dynamic_cast <Component*> (fileListComponent);
  54451. listAsComp->setBounds (x, y, w, browserComp.getHeight() - y - bottomSectionHeight);
  54452. y = listAsComp->getBottom() + 4;
  54453. filenameBox->setBounds (x + 50, y, w - 50, controlsHeight);
  54454. }
  54455. // Pulls a drawable out of compressed valuetree data..
  54456. Drawable* LookAndFeel::loadDrawableFromData (const void* data, size_t numBytes)
  54457. {
  54458. MemoryInputStream m (data, numBytes, false);
  54459. GZIPDecompressorInputStream gz (m);
  54460. ValueTree drawable (ValueTree::readFromStream (gz));
  54461. return Drawable::createFromValueTree (drawable.getChild (0), 0);
  54462. }
  54463. const Drawable* LookAndFeel::getDefaultFolderImage()
  54464. {
  54465. if (folderImage == 0)
  54466. {
  54467. static const unsigned char drawableData[] =
  54468. { 120,218,197,86,77,111,27,55,16,229,182,161,237,6,61,39,233,77,63,192,38,56,195,225,215,209,105,210,2,141,13,20,201,193,109,111,178,181,178,183,145,181,130,180,110,145,127,159,199,93,73,137,87,53,218,91,109,192,160,151,179,156,55,111,222,188,229,155,247,
  54469. 231,87,231,175,47,222,170,234,155,229,244,190,86,213,115,253,102,61,253,123,122,189,168,85,51,83,213,119,250,238,221,47,231,151,175,223,169,170,250,121,221,62,172,84,245,172,60,63,209,243,118,49,171,215,170,107,87,23,245,188,83,213,145,182,167,19,91,
  54470. 254,127,223,220,222,117,37,68,82,40,143,174,219,174,107,239,135,168,147,18,37,108,85,245,237,46,207,70,33,249,175,211,238,78,85,186,28,253,76,175,73,109,186,117,251,177,190,106,102,229,241,247,58,24,103,203,15,101,245,103,219,44,187,15,221,39,0,172,142,
  54471. 245,125,211,1,196,205,116,181,125,114,164,175,31,186,78,45,219,229,31,245,186,189,106,150,179,102,121,139,100,154,240,231,167,102,177,64,72,247,105,213,23,122,187,158,206,154,122,217,169,85,57,18,1,47,53,101,107,18,135,204,167,147,192,201,216,20,114,
  54472. 244,195,62,171,234,7,125,198,100,136,216,145,149,211,9,57,103,40,249,72,219,8,167,170,87,250,140,162,199,123,226,3,34,82,202,134,131,13,172,74,170,233,162,0,177,234,166,93,180,15,235,141,170,206,180,157,204,231,150,156,159,207,39,195,50,214,88,18,150,
  54473. 245,205,124,250,104,169,212,135,158,19,144,53,20,112,172,55,237,2,132,13,199,149,130,230,115,145,112,147,147,82,61,157,32,238,178,253,11,145,213,138,10,52,138,38,103,111,99,164,211,137,139,198,35,177,35,167,212,143,15,215,205,13,160,109,163,172,225,152,
  54474. 16,232,17,149,140,103,144,158,146,90,113,217,12,6,197,167,236,3,54,5,181,101,73,54,138,90,245,165,227,120,18,252,150,77,15,242,188,228,204,81,169,139,102,249,5,68,192,145,14,244,112,1,145,29,94,137,96,235,49,136,151,58,246,32,88,192,161,88,176,76,226,
  54475. 36,247,24,176,7,232,62,16,83,42,155,201,160,30,222,65,72,98,82,76,33,198,254,197,96,124,10,150,243,8,130,48,228,36,94,124,6,4,43,38,0,142,205,99,30,4,221,13,33,230,220,71,177,65,49,142,243,150,7,1,51,20,2,5,96,96,84,225,56,217,188,3,33,46,24,228,112,
  54476. 69,69,12,68,228,108,242,99,16,165,118,208,28,51,200,98,87,42,74,62,209,24,4,206,48,22,153,125,132,220,196,56,15,234,99,216,130,0,141,38,74,162,130,48,35,163,141,94,196,245,32,94,104,7,154,132,209,40,108,162,165,232,153,165,17,4,138,201,176,135,58,49,
  54477. 165,130,122,108,114,54,28,240,64,17,89,188,79,177,116,149,10,4,246,91,30,94,104,112,96,226,144,131,144,142,98,78,177,7,128,81,242,224,140,36,249,80,208,145,196,12,202,15,16,60,161,200,69,187,169,213,86,198,123,87,224,255,199,21,94,105,134,72,40,177,245,
  54478. 14,182,32,232,54,196,231,100,111,11,189,168,201,39,177,84,102,38,139,177,168,74,210,87,174,64,20,138,160,67,111,10,4,98,196,97,60,158,118,133,25,111,173,224,171,37,97,185,119,133,221,242,63,184,194,140,71,174,240,252,145,43,72,32,147,146,147,4,104,104,
  54479. 117,134,10,18,12,107,212,40,72,148,57,6,71,69,135,222,248,16,160,168,3,169,144,55,201,69,41,147,137,134,99,50,97,8,178,85,43,217,140,201,151,192,152,10,242,190,24,11,59,183,29,25,42,115,236,98,14,229,252,32,80,66,0,162,17,136,72,6,67,5,45,242,224,10,
  54480. 193,102,71,50,6,17,129,212,18,115,105,150,80,169,45,123,222,141,76,178,70,32,55,24,90,217,132,71,73,200,57,238,204,3,136,49,144,185,55,183,190,20,137,52,246,47,113,232,158,69,35,49,145,208,129,193,56,178,77,135,230,145,113,22,140,69,74,20,146,2,120,218,
  54481. 155,135,48,32,10,89,30,156,165,204,254,222,193,160,12,19,49,6,210,59,11,70,62,4,31,15,64,196,2,157,98,33,58,1,104,32,152,50,31,128,64,148,183,197,108,209,89,107,240,41,75,36,123,16,208,108,180,44,236,250,182,227,27,20,137,118,76,60,165,137,221,92,94,
  54482. 78,215,31,235,245,230,183,242,229,30,214,251,251,195,145,94,148,15,253,170,221,52,93,211,46,7,109,171,81,208,177,94,247,119,132,47,81,186,92,22,246,7,255,254,15,7,107,141,171,197,191,156,123,162,135,187,198,227,131,113,219,80,159,1,4,239,223,231,0,0 };
  54483. folderImage = loadDrawableFromData (drawableData, sizeof (drawableData));
  54484. }
  54485. return folderImage;
  54486. }
  54487. const Drawable* LookAndFeel::getDefaultDocumentFileImage()
  54488. {
  54489. if (documentImage == 0)
  54490. {
  54491. static const unsigned char drawableData[] =
  54492. { 120,218,213,88,77,115,219,54,16,37,147,208,246,228,214,75,155,246,164,123,29,12,176,216,197,199,49,105,218,94,156,153,78,114,72,219,155,108,75,137,26,89,212,200,116,59,233,175,239,3,105,201,164,68,50,158,166,233,76,196,11,69,60,173,128,197,123,139,183,
  54493. 124,241,234,217,155,103,207,207,126,204,242,7,171,233,213,44,203,31,23,47,54,211,191,166,231,203,89,182,184,204,242,147,226,195,165,219,252,125,150,229,249,207,155,242,102,157,229,143,210,227,199,197,101,121,113,115,53,91,85,89,85,174,207,102,243,42,
  54494. 203,143,10,125,58,209,233,251,171,197,219,119,85,250,173,97,151,30,157,151,85,85,94,53,168,147,132,50,226,179,252,225,246,143,174,179,44,63,254,101,90,189,203,242,34,5,127,84,172,77,118,93,109,202,247,179,55,139,203,244,248,97,161,179,63,202,197,170,
  54495. 122,93,125,192,196,242,227,226,106,81,205,54,217,197,116,125,251,228,168,56,191,169,170,108,85,174,126,159,109,202,55,139,213,229,98,245,182,249,97,254,240,167,197,114,137,5,86,31,214,245,111,175,203,37,254,230,162,92,150,55,155,180,148,249,237,39,203,
  54496. 94,215,127,58,10,213,245,39,203,234,249,102,249,87,47,203,63,129,204,49,227,252,73,225,149,145,104,131,245,254,116,34,202,82,164,16,153,179,236,108,177,234,7,49,41,237,130,144,167,17,144,15,42,104,239,93,12,35,32,99,68,9,187,24,125,7,244,77,23,36,164,
  54497. 40,56,226,61,12,107,229,130,215,100,105,24,227,89,17,246,211,105,55,140,49,218,43,207,100,245,72,28,195,70,17,230,201,118,8,243,164,139,233,95,88,23,52,152,162,54,104,48,217,237,105,15,111,91,107,253,131,160,118,34,239,69,128,54,232,135,101,121,61,203,
  54498. 110,169,181,147,2,253,159,82,48,180,229,247,167,74,193,41,141,188,35,93,241,116,18,148,113,214,120,207,113,47,19,109,16,51,182,153,193,5,59,2,10,90,69,114,218,135,48,2,50,198,43,171,189,152,81,144,88,108,85,136,78,246,64,54,42,163,35,69,30,3,121,82,38,
  54499. 98,81,98,70,64,70,139,34,111,163,167,49,144,13,202,138,179,58,220,23,52,180,186,54,104,48,79,109,208,96,198,219,19,31,220,187,118,10,6,65,237,100,222,139,5,109,80,191,30,236,151,162,135,147,142,30,68,105,182,58,6,22,84,43,229,124,148,116,97,145,55,231,
  54500. 139,11,76,228,16,37,14,48,205,145,77,134,34,176,55,152,182,200,57,99,93,204,144,145,253,65,97,229,132,72,104,63,62,71,21,140,54,186,41,226,59,84,19,63,130,15,222,235,224,185,59,104,27,226,68,101,153,241,227,177,248,29,20,136,26,8,252,178,183,241,219,
  54501. 131,137,160,209,107,109,92,79,124,16,211,184,104,93,77,130,110,124,2,65,172,67,201,60,157,88,163,2,91,99,92,216,198,55,78,69,75,190,150,119,84,98,200,71,150,109,124,36,204,227,52,8,33,229,223,68,167,173,167,131,248,137,212,226,141,19,233,160,154,248,
  54502. 144,142,195,140,137,185,59,104,15,247,119,40,126,23,69,81,200,242,110,254,123,20,49,94,112,110,245,199,111,241,167,87,36,252,101,138,132,149,22,22,38,65,134,29,182,139,24,230,192,31,144,184,133,130,72,44,131,210,142,111,147,216,30,76,123,30,113,206,242,
  54503. 150,196,157,65,129,130,76,180,194,61,34,225,160,5,228,233,160,118,34,137,26,202,115,212,29,108,72,134,243,223,90,114,226,199,226,119,80,6,245,152,197,122,217,146,184,53,24,140,210,30,21,59,80,79,124,182,202,71,207,218,112,159,72,80,53,140,109,68,2,191,
  54504. 227,217,210,78,36,94,137,88,231,82,157,8,176,61,0,122,191,19,137,3,255,13,39,183,228,20,193,151,144,119,166,79,36,40,253,156,138,72,11,181,19,137,14,46,176,217,27,180,135,251,219,31,255,235,61,148,165,96,72,122,118,23,229,81,52,135,24,250,163,183,216,
  54505. 211,43,17,217,151,136,253,116,137,28,53,188,127,92,188,221,76,47,23,169,59,90,167,144,141,239,197,86,104,141,189,60,157,80,84,142,140,4,31,154,241,122,105,132,41,107,13,201,39,86,120,24,82,114,206,198,6,96,27,227,172,36,232,168,201,36,219,24,113,62,163,
  54506. 154,101,233,143,166,203,102,26,141,206,174,179,252,89,161,39,243,249,197,121,186,38,233,246,146,211,53,1,123,56,194,231,122,143,103,179,217,60,204,167,19,147,110,41,93,173,219,123,72,89,248,35,173,16,220,50,179,111,60,181,24,88,103,156,235,7,78,248,14,
  54507. 4,119,78,162,93,60,112,35,109,16,124,126,12,17,71,67,24,1,165,142,1,181,215,248,56,6,66,235,193,137,167,61,22,30,5,3,27,101,71,64,169,25,112,216,2,63,22,169,110,43,18,200,140,129,208,160,88,44,220,208,125,65,67,171,107,131,6,243,212,6,13,102,188,61,241,
  54508. 225,189,107,165,96,16,212,78,230,189,88,208,6,245,235,214,237,235,150,62,167,110,155,106,170,53,133,192,117,193,20,84,78,74,174,98,39,92,156,8,112,21,46,80,106,12,209,207,225,228,16,113,59,225,126,87,60,133,25,209,34,36,2,99,242,52,197,48,30,75,244,247,
  54509. 212,238,246,182,173,221,185,78,215,127,167,221,162,163,221,250,152,217,146,196,222,145,100,223,235,105,108,28,250,149,212,74,224,86,2,213,118,110,119,204,224,144,208,38,214,131,200,14,214,223,120,189,230,53,1,193,70,133,154,131,56,223,16,229,48,188,14,
  54510. 201,205,213,121,71,233,68,89,15,124,103,37,53,26,11,118,176,127,169,88,166,158,219,178,117,173,83,108,75,95,55,68,186,193,53,246,146,206,127,6,63,53,78,58,228,204,155,224,113,74,91,232,221,195,240,105,215,34,29,138,64,128,183,8,130,233,71,173,56,54,101,
  54511. 99,75,186,111,65,58,28,229,145,82,19,152,12,99,180,81,130,131,75,234,229,220,247,53,231,154,79,205,185,185,155,199,249,172,38,85,253,204,76,68,95,92,204,207,255,221,75,178,227,14,187,224,224,97,202,172,173,219,12,167,130,133,9,54,135,245,92,176,29,134,
  54512. 165,110,139,141,18,16,223,29,188,183,65,207,144,106,144,151,143,128,224,176,168,110,140,32,62,56,110,219,195,54,235,20,68,209,216,34,232,21,6,41,234,157,39,211,201,107,160,230,66,225,56,153,9,101,21,37,237,150,204,14,115,208,22,221,54,216,230,33,116,
  54513. 14,65,14,44,19,8,236,73,71,246,182,110,125,224,75,132,195,214,247,163,36,51,252,84,76,124,37,212,100,88,62,183,179,76,67,217,218,242,244,229,116,243,126,182,185,254,21,105,126,208,220,239,94,229,30,21,203,244,202,117,93,94,47,170,69,185,106,246,60,219,
  54514. 3,29,23,155,250,109,237,29,170,72,175,109,119,129,127,235,9,92,20,85,185,254,72,220,147,162,121,235,219,13,44,144,225,63,241,244,165,51,0,0 };
  54515. documentImage = loadDrawableFromData (drawableData, sizeof (drawableData));
  54516. }
  54517. return documentImage;
  54518. }
  54519. void LookAndFeel::playAlertSound()
  54520. {
  54521. PlatformUtilities::beep();
  54522. }
  54523. void LookAndFeel::drawLevelMeter (Graphics& g, int width, int height, float level)
  54524. {
  54525. g.setColour (Colours::white.withAlpha (0.7f));
  54526. g.fillRoundedRectangle (0.0f, 0.0f, (float) width, (float) height, 3.0f);
  54527. g.setColour (Colours::black.withAlpha (0.2f));
  54528. g.drawRoundedRectangle (1.0f, 1.0f, width - 2.0f, height - 2.0f, 3.0f, 1.0f);
  54529. const int totalBlocks = 7;
  54530. const int numBlocks = roundToInt (totalBlocks * level);
  54531. const float w = (width - 6.0f) / (float) totalBlocks;
  54532. for (int i = 0; i < totalBlocks; ++i)
  54533. {
  54534. if (i >= numBlocks)
  54535. g.setColour (Colours::lightblue.withAlpha (0.6f));
  54536. else
  54537. g.setColour (i < totalBlocks - 1 ? Colours::blue.withAlpha (0.5f)
  54538. : Colours::red);
  54539. g.fillRoundedRectangle (3.0f + i * w + w * 0.1f, 3.0f, w * 0.8f, height - 6.0f, w * 0.4f);
  54540. }
  54541. }
  54542. void LookAndFeel::drawKeymapChangeButton (Graphics& g, int width, int height, Button& button, const String& keyDescription)
  54543. {
  54544. const Colour textColour (button.findColour (KeyMappingEditorComponent::textColourId, true));
  54545. if (keyDescription.isNotEmpty())
  54546. {
  54547. if (button.isEnabled())
  54548. {
  54549. const float alpha = button.isDown() ? 0.3f : (button.isOver() ? 0.15f : 0.08f);
  54550. g.fillAll (textColour.withAlpha (alpha));
  54551. g.setOpacity (0.3f);
  54552. g.drawBevel (0, 0, width, height, 2);
  54553. }
  54554. g.setColour (textColour);
  54555. g.setFont (height * 0.6f);
  54556. g.drawFittedText (keyDescription,
  54557. 3, 0, width - 6, height,
  54558. Justification::centred, 1);
  54559. }
  54560. else
  54561. {
  54562. const float thickness = 7.0f;
  54563. const float indent = 22.0f;
  54564. Path p;
  54565. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  54566. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  54567. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  54568. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  54569. p.setUsingNonZeroWinding (false);
  54570. g.setColour (textColour.withAlpha (button.isDown() ? 0.7f : (button.isOver() ? 0.5f : 0.3f)));
  54571. g.fillPath (p, p.getTransformToScaleToFit (2.0f, 2.0f, width - 4.0f, height - 4.0f, true));
  54572. }
  54573. if (button.hasKeyboardFocus (false))
  54574. {
  54575. g.setColour (textColour.withAlpha (0.4f));
  54576. g.drawRect (0, 0, width, height);
  54577. }
  54578. }
  54579. void LookAndFeel::drawShinyButtonShape (Graphics& g,
  54580. float x, float y, float w, float h,
  54581. float maxCornerSize,
  54582. const Colour& baseColour,
  54583. const float strokeWidth,
  54584. const bool flatOnLeft,
  54585. const bool flatOnRight,
  54586. const bool flatOnTop,
  54587. const bool flatOnBottom) throw()
  54588. {
  54589. if (w <= strokeWidth * 1.1f || h <= strokeWidth * 1.1f)
  54590. return;
  54591. const float cs = jmin (maxCornerSize, w * 0.5f, h * 0.5f);
  54592. Path outline;
  54593. LookAndFeelHelpers::createRoundedPath (outline, x, y, w, h, cs,
  54594. ! (flatOnLeft || flatOnTop),
  54595. ! (flatOnRight || flatOnTop),
  54596. ! (flatOnLeft || flatOnBottom),
  54597. ! (flatOnRight || flatOnBottom));
  54598. ColourGradient cg (baseColour, 0.0f, y,
  54599. baseColour.overlaidWith (Colour (0x070000ff)), 0.0f, y + h,
  54600. false);
  54601. cg.addColour (0.5, baseColour.overlaidWith (Colour (0x33ffffff)));
  54602. cg.addColour (0.51, baseColour.overlaidWith (Colour (0x110000ff)));
  54603. g.setGradientFill (cg);
  54604. g.fillPath (outline);
  54605. g.setColour (Colour (0x80000000));
  54606. g.strokePath (outline, PathStrokeType (strokeWidth));
  54607. }
  54608. void LookAndFeel::drawGlassSphere (Graphics& g,
  54609. const float x, const float y,
  54610. const float diameter,
  54611. const Colour& colour,
  54612. const float outlineThickness) throw()
  54613. {
  54614. if (diameter <= outlineThickness)
  54615. return;
  54616. Path p;
  54617. p.addEllipse (x, y, diameter, diameter);
  54618. {
  54619. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  54620. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  54621. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  54622. g.setGradientFill (cg);
  54623. g.fillPath (p);
  54624. }
  54625. g.setGradientFill (ColourGradient (Colours::white, 0, y + diameter * 0.06f,
  54626. Colours::transparentWhite, 0, y + diameter * 0.3f, false));
  54627. g.fillEllipse (x + diameter * 0.2f, y + diameter * 0.05f, diameter * 0.6f, diameter * 0.4f);
  54628. ColourGradient cg (Colours::transparentBlack,
  54629. x + diameter * 0.5f, y + diameter * 0.5f,
  54630. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  54631. x, y + diameter * 0.5f, true);
  54632. cg.addColour (0.7, Colours::transparentBlack);
  54633. cg.addColour (0.8, Colours::black.withAlpha (0.1f * outlineThickness));
  54634. g.setGradientFill (cg);
  54635. g.fillPath (p);
  54636. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  54637. g.drawEllipse (x, y, diameter, diameter, outlineThickness);
  54638. }
  54639. void LookAndFeel::drawGlassPointer (Graphics& g,
  54640. const float x, const float y,
  54641. const float diameter,
  54642. const Colour& colour, const float outlineThickness,
  54643. const int direction) throw()
  54644. {
  54645. if (diameter <= outlineThickness)
  54646. return;
  54647. Path p;
  54648. p.startNewSubPath (x + diameter * 0.5f, y);
  54649. p.lineTo (x + diameter, y + diameter * 0.6f);
  54650. p.lineTo (x + diameter, y + diameter);
  54651. p.lineTo (x, y + diameter);
  54652. p.lineTo (x, y + diameter * 0.6f);
  54653. p.closeSubPath();
  54654. p.applyTransform (AffineTransform::rotation (direction * (float_Pi * 0.5f), x + diameter * 0.5f, y + diameter * 0.5f));
  54655. {
  54656. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  54657. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  54658. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  54659. g.setGradientFill (cg);
  54660. g.fillPath (p);
  54661. }
  54662. ColourGradient cg (Colours::transparentBlack,
  54663. x + diameter * 0.5f, y + diameter * 0.5f,
  54664. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  54665. x - diameter * 0.2f, y + diameter * 0.5f, true);
  54666. cg.addColour (0.5, Colours::transparentBlack);
  54667. cg.addColour (0.7, Colours::black.withAlpha (0.07f * outlineThickness));
  54668. g.setGradientFill (cg);
  54669. g.fillPath (p);
  54670. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  54671. g.strokePath (p, PathStrokeType (outlineThickness));
  54672. }
  54673. void LookAndFeel::drawGlassLozenge (Graphics& g,
  54674. const float x, const float y,
  54675. const float width, const float height,
  54676. const Colour& colour,
  54677. const float outlineThickness,
  54678. const float cornerSize,
  54679. const bool flatOnLeft,
  54680. const bool flatOnRight,
  54681. const bool flatOnTop,
  54682. const bool flatOnBottom) throw()
  54683. {
  54684. if (width <= outlineThickness || height <= outlineThickness)
  54685. return;
  54686. const int intX = (int) x;
  54687. const int intY = (int) y;
  54688. const int intW = (int) width;
  54689. const int intH = (int) height;
  54690. const float cs = cornerSize < 0 ? jmin (width * 0.5f, height * 0.5f) : cornerSize;
  54691. const float edgeBlurRadius = height * 0.75f + (height - cs * 2.0f);
  54692. const int intEdge = (int) edgeBlurRadius;
  54693. Path outline;
  54694. LookAndFeelHelpers::createRoundedPath (outline, x, y, width, height, cs,
  54695. ! (flatOnLeft || flatOnTop),
  54696. ! (flatOnRight || flatOnTop),
  54697. ! (flatOnLeft || flatOnBottom),
  54698. ! (flatOnRight || flatOnBottom));
  54699. {
  54700. ColourGradient cg (colour.darker (0.2f), 0, y,
  54701. colour.darker (0.2f), 0, y + height, false);
  54702. cg.addColour (0.03, colour.withMultipliedAlpha (0.3f));
  54703. cg.addColour (0.4, colour);
  54704. cg.addColour (0.97, colour.withMultipliedAlpha (0.3f));
  54705. g.setGradientFill (cg);
  54706. g.fillPath (outline);
  54707. }
  54708. ColourGradient cg (Colours::transparentBlack, x + edgeBlurRadius, y + height * 0.5f,
  54709. colour.darker (0.2f), x, y + height * 0.5f, true);
  54710. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.5f) / edgeBlurRadius), Colours::transparentBlack);
  54711. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.25f) / edgeBlurRadius), colour.darker (0.2f).withMultipliedAlpha (0.3f));
  54712. if (! (flatOnLeft || flatOnTop || flatOnBottom))
  54713. {
  54714. g.saveState();
  54715. g.setGradientFill (cg);
  54716. g.reduceClipRegion (intX, intY, intEdge, intH);
  54717. g.fillPath (outline);
  54718. g.restoreState();
  54719. }
  54720. if (! (flatOnRight || flatOnTop || flatOnBottom))
  54721. {
  54722. cg.point1.setX (x + width - edgeBlurRadius);
  54723. cg.point2.setX (x + width);
  54724. g.saveState();
  54725. g.setGradientFill (cg);
  54726. g.reduceClipRegion (intX + intW - intEdge, intY, 2 + intEdge, intH);
  54727. g.fillPath (outline);
  54728. g.restoreState();
  54729. }
  54730. {
  54731. const float leftIndent = flatOnLeft ? 0.0f : cs * 0.4f;
  54732. const float rightIndent = flatOnRight ? 0.0f : cs * 0.4f;
  54733. Path highlight;
  54734. LookAndFeelHelpers::createRoundedPath (highlight,
  54735. x + leftIndent,
  54736. y + cs * 0.1f,
  54737. width - (leftIndent + rightIndent),
  54738. height * 0.4f, cs * 0.4f,
  54739. ! (flatOnLeft || flatOnTop),
  54740. ! (flatOnRight || flatOnTop),
  54741. ! (flatOnLeft || flatOnBottom),
  54742. ! (flatOnRight || flatOnBottom));
  54743. g.setGradientFill (ColourGradient (colour.brighter (10.0f), 0, y + height * 0.06f,
  54744. Colours::transparentWhite, 0, y + height * 0.4f, false));
  54745. g.fillPath (highlight);
  54746. }
  54747. g.setColour (colour.darker().withMultipliedAlpha (1.5f));
  54748. g.strokePath (outline, PathStrokeType (outlineThickness));
  54749. }
  54750. END_JUCE_NAMESPACE
  54751. /*** End of inlined file: juce_LookAndFeel.cpp ***/
  54752. /*** Start of inlined file: juce_OldSchoolLookAndFeel.cpp ***/
  54753. BEGIN_JUCE_NAMESPACE
  54754. OldSchoolLookAndFeel::OldSchoolLookAndFeel()
  54755. {
  54756. setColour (TextButton::buttonColourId, Colour (0xffbbbbff));
  54757. setColour (ListBox::outlineColourId, findColour (ComboBox::outlineColourId));
  54758. setColour (ScrollBar::thumbColourId, Colour (0xffbbbbdd));
  54759. setColour (ScrollBar::backgroundColourId, Colours::transparentBlack);
  54760. setColour (Slider::thumbColourId, Colours::white);
  54761. setColour (Slider::trackColourId, Colour (0x7f000000));
  54762. setColour (Slider::textBoxOutlineColourId, Colours::grey);
  54763. setColour (ProgressBar::backgroundColourId, Colours::white.withAlpha (0.6f));
  54764. setColour (ProgressBar::foregroundColourId, Colours::green.withAlpha (0.7f));
  54765. setColour (PopupMenu::backgroundColourId, Colour (0xffeef5f8));
  54766. setColour (PopupMenu::highlightedBackgroundColourId, Colour (0xbfa4c2ce));
  54767. setColour (PopupMenu::highlightedTextColourId, Colours::black);
  54768. setColour (TextEditor::focusedOutlineColourId, findColour (TextButton::buttonColourId));
  54769. scrollbarShadow.setShadowProperties (2.2f, 0.5f, 0, 0);
  54770. }
  54771. OldSchoolLookAndFeel::~OldSchoolLookAndFeel()
  54772. {
  54773. }
  54774. void OldSchoolLookAndFeel::drawButtonBackground (Graphics& g,
  54775. Button& button,
  54776. const Colour& backgroundColour,
  54777. bool isMouseOverButton,
  54778. bool isButtonDown)
  54779. {
  54780. const int width = button.getWidth();
  54781. const int height = button.getHeight();
  54782. const float indent = 2.0f;
  54783. const int cornerSize = jmin (roundToInt (width * 0.4f),
  54784. roundToInt (height * 0.4f));
  54785. Path p;
  54786. p.addRoundedRectangle (indent, indent,
  54787. width - indent * 2.0f,
  54788. height - indent * 2.0f,
  54789. (float) cornerSize);
  54790. Colour bc (backgroundColour.withMultipliedSaturation (0.3f));
  54791. if (isMouseOverButton)
  54792. {
  54793. if (isButtonDown)
  54794. bc = bc.brighter();
  54795. else if (bc.getBrightness() > 0.5f)
  54796. bc = bc.darker (0.1f);
  54797. else
  54798. bc = bc.brighter (0.1f);
  54799. }
  54800. g.setColour (bc);
  54801. g.fillPath (p);
  54802. g.setColour (bc.contrasting().withAlpha ((isMouseOverButton) ? 0.6f : 0.4f));
  54803. g.strokePath (p, PathStrokeType ((isMouseOverButton) ? 2.0f : 1.4f));
  54804. }
  54805. void OldSchoolLookAndFeel::drawTickBox (Graphics& g,
  54806. Component& /*component*/,
  54807. float x, float y, float w, float h,
  54808. const bool ticked,
  54809. const bool isEnabled,
  54810. const bool /*isMouseOverButton*/,
  54811. const bool isButtonDown)
  54812. {
  54813. Path box;
  54814. box.addRoundedRectangle (0.0f, 2.0f, 6.0f, 6.0f, 1.0f);
  54815. g.setColour (isEnabled ? Colours::blue.withAlpha (isButtonDown ? 0.3f : 0.1f)
  54816. : Colours::lightgrey.withAlpha (0.1f));
  54817. AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f).translated (x, y));
  54818. g.fillPath (box, trans);
  54819. g.setColour (Colours::black.withAlpha (0.6f));
  54820. g.strokePath (box, PathStrokeType (0.9f), trans);
  54821. if (ticked)
  54822. {
  54823. Path tick;
  54824. tick.startNewSubPath (1.5f, 3.0f);
  54825. tick.lineTo (3.0f, 6.0f);
  54826. tick.lineTo (6.0f, 0.0f);
  54827. g.setColour (isEnabled ? Colours::black : Colours::grey);
  54828. g.strokePath (tick, PathStrokeType (2.5f), trans);
  54829. }
  54830. }
  54831. void OldSchoolLookAndFeel::drawToggleButton (Graphics& g,
  54832. ToggleButton& button,
  54833. bool isMouseOverButton,
  54834. bool isButtonDown)
  54835. {
  54836. if (button.hasKeyboardFocus (true))
  54837. {
  54838. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  54839. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  54840. }
  54841. const int tickWidth = jmin (20, button.getHeight() - 4);
  54842. drawTickBox (g, button, 4.0f, (button.getHeight() - tickWidth) * 0.5f,
  54843. (float) tickWidth, (float) tickWidth,
  54844. button.getToggleState(),
  54845. button.isEnabled(),
  54846. isMouseOverButton,
  54847. isButtonDown);
  54848. g.setColour (button.findColour (ToggleButton::textColourId));
  54849. g.setFont (jmin (15.0f, button.getHeight() * 0.6f));
  54850. if (! button.isEnabled())
  54851. g.setOpacity (0.5f);
  54852. const int textX = tickWidth + 5;
  54853. g.drawFittedText (button.getButtonText(),
  54854. textX, 4,
  54855. button.getWidth() - textX - 2, button.getHeight() - 8,
  54856. Justification::centredLeft, 10);
  54857. }
  54858. void OldSchoolLookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  54859. int width, int height,
  54860. double progress, const String& textToShow)
  54861. {
  54862. if (progress < 0 || progress >= 1.0)
  54863. {
  54864. LookAndFeel::drawProgressBar (g, progressBar, width, height, progress, textToShow);
  54865. }
  54866. else
  54867. {
  54868. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  54869. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  54870. g.fillAll (background);
  54871. g.setColour (foreground);
  54872. g.fillRect (1, 1,
  54873. jlimit (0, width - 2, roundToInt (progress * (width - 2))),
  54874. height - 2);
  54875. if (textToShow.isNotEmpty())
  54876. {
  54877. g.setColour (Colour::contrasting (background, foreground));
  54878. g.setFont (height * 0.6f);
  54879. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  54880. }
  54881. }
  54882. }
  54883. void OldSchoolLookAndFeel::drawScrollbarButton (Graphics& g,
  54884. ScrollBar& bar,
  54885. int width, int height,
  54886. int buttonDirection,
  54887. bool isScrollbarVertical,
  54888. bool isMouseOverButton,
  54889. bool isButtonDown)
  54890. {
  54891. if (isScrollbarVertical)
  54892. width -= 2;
  54893. else
  54894. height -= 2;
  54895. Path p;
  54896. if (buttonDirection == 0)
  54897. p.addTriangle (width * 0.5f, height * 0.2f,
  54898. width * 0.1f, height * 0.7f,
  54899. width * 0.9f, height * 0.7f);
  54900. else if (buttonDirection == 1)
  54901. p.addTriangle (width * 0.8f, height * 0.5f,
  54902. width * 0.3f, height * 0.1f,
  54903. width * 0.3f, height * 0.9f);
  54904. else if (buttonDirection == 2)
  54905. p.addTriangle (width * 0.5f, height * 0.8f,
  54906. width * 0.1f, height * 0.3f,
  54907. width * 0.9f, height * 0.3f);
  54908. else if (buttonDirection == 3)
  54909. p.addTriangle (width * 0.2f, height * 0.5f,
  54910. width * 0.7f, height * 0.1f,
  54911. width * 0.7f, height * 0.9f);
  54912. if (isButtonDown)
  54913. g.setColour (Colours::white);
  54914. else if (isMouseOverButton)
  54915. g.setColour (Colours::white.withAlpha (0.7f));
  54916. else
  54917. g.setColour (bar.findColour (ScrollBar::thumbColourId).withAlpha (0.5f));
  54918. g.fillPath (p);
  54919. g.setColour (Colours::black.withAlpha (0.5f));
  54920. g.strokePath (p, PathStrokeType (0.5f));
  54921. }
  54922. void OldSchoolLookAndFeel::drawScrollbar (Graphics& g,
  54923. ScrollBar& bar,
  54924. int x, int y,
  54925. int width, int height,
  54926. bool isScrollbarVertical,
  54927. int thumbStartPosition,
  54928. int thumbSize,
  54929. bool isMouseOver,
  54930. bool isMouseDown)
  54931. {
  54932. g.fillAll (bar.findColour (ScrollBar::backgroundColourId));
  54933. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  54934. .withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.15f));
  54935. if (thumbSize > 0.0f)
  54936. {
  54937. Rectangle<int> thumb;
  54938. if (isScrollbarVertical)
  54939. {
  54940. width -= 2;
  54941. g.fillRect (x + roundToInt (width * 0.35f), y,
  54942. roundToInt (width * 0.3f), height);
  54943. thumb.setBounds (x + 1, thumbStartPosition,
  54944. width - 2, thumbSize);
  54945. }
  54946. else
  54947. {
  54948. height -= 2;
  54949. g.fillRect (x, y + roundToInt (height * 0.35f),
  54950. width, roundToInt (height * 0.3f));
  54951. thumb.setBounds (thumbStartPosition, y + 1,
  54952. thumbSize, height - 2);
  54953. }
  54954. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  54955. .withAlpha ((isMouseOver || isMouseDown) ? 0.95f : 0.7f));
  54956. g.fillRect (thumb);
  54957. g.setColour (Colours::black.withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.25f));
  54958. g.drawRect (thumb.getX(), thumb.getY(), thumb.getWidth(), thumb.getHeight());
  54959. if (thumbSize > 16)
  54960. {
  54961. for (int i = 3; --i >= 0;)
  54962. {
  54963. const float linePos = thumbStartPosition + thumbSize / 2 + (i - 1) * 4.0f;
  54964. g.setColour (Colours::black.withAlpha (0.15f));
  54965. if (isScrollbarVertical)
  54966. {
  54967. g.drawLine (x + width * 0.2f, linePos, width * 0.8f, linePos);
  54968. g.setColour (Colours::white.withAlpha (0.15f));
  54969. g.drawLine (width * 0.2f, linePos - 1, width * 0.8f, linePos - 1);
  54970. }
  54971. else
  54972. {
  54973. g.drawLine (linePos, height * 0.2f, linePos, height * 0.8f);
  54974. g.setColour (Colours::white.withAlpha (0.15f));
  54975. g.drawLine (linePos - 1, height * 0.2f, linePos - 1, height * 0.8f);
  54976. }
  54977. }
  54978. }
  54979. }
  54980. }
  54981. ImageEffectFilter* OldSchoolLookAndFeel::getScrollbarEffect()
  54982. {
  54983. return &scrollbarShadow;
  54984. }
  54985. void OldSchoolLookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  54986. {
  54987. g.fillAll (findColour (PopupMenu::backgroundColourId));
  54988. g.setColour (Colours::black.withAlpha (0.6f));
  54989. g.drawRect (0, 0, width, height);
  54990. }
  54991. void OldSchoolLookAndFeel::drawMenuBarBackground (Graphics& g, int /*width*/, int /*height*/,
  54992. bool, MenuBarComponent& menuBar)
  54993. {
  54994. g.fillAll (menuBar.findColour (PopupMenu::backgroundColourId));
  54995. }
  54996. void OldSchoolLookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  54997. {
  54998. if (textEditor.isEnabled())
  54999. {
  55000. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  55001. g.drawRect (0, 0, width, height);
  55002. }
  55003. }
  55004. void OldSchoolLookAndFeel::drawComboBox (Graphics& g, int width, int height,
  55005. const bool isButtonDown,
  55006. int buttonX, int buttonY,
  55007. int buttonW, int buttonH,
  55008. ComboBox& box)
  55009. {
  55010. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  55011. g.setColour (box.findColour ((isButtonDown) ? ComboBox::buttonColourId
  55012. : ComboBox::backgroundColourId));
  55013. g.fillRect (buttonX, buttonY, buttonW, buttonH);
  55014. g.setColour (box.findColour (ComboBox::outlineColourId));
  55015. g.drawRect (0, 0, width, height);
  55016. const float arrowX = 0.2f;
  55017. const float arrowH = 0.3f;
  55018. if (box.isEnabled())
  55019. {
  55020. Path p;
  55021. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  55022. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  55023. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  55024. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  55025. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  55026. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  55027. g.setColour (box.findColour ((isButtonDown) ? ComboBox::backgroundColourId
  55028. : ComboBox::buttonColourId));
  55029. g.fillPath (p);
  55030. }
  55031. }
  55032. const Font OldSchoolLookAndFeel::getComboBoxFont (ComboBox& box)
  55033. {
  55034. Font f (jmin (15.0f, box.getHeight() * 0.85f));
  55035. f.setHorizontalScale (0.9f);
  55036. return f;
  55037. }
  55038. static void drawTriangle (Graphics& g, float x1, float y1, float x2, float y2, float x3, float y3, const Colour& fill, const Colour& outline) throw()
  55039. {
  55040. Path p;
  55041. p.addTriangle (x1, y1, x2, y2, x3, y3);
  55042. g.setColour (fill);
  55043. g.fillPath (p);
  55044. g.setColour (outline);
  55045. g.strokePath (p, PathStrokeType (0.3f));
  55046. }
  55047. void OldSchoolLookAndFeel::drawLinearSlider (Graphics& g,
  55048. int x, int y,
  55049. int w, int h,
  55050. float sliderPos,
  55051. float minSliderPos,
  55052. float maxSliderPos,
  55053. const Slider::SliderStyle style,
  55054. Slider& slider)
  55055. {
  55056. g.fillAll (slider.findColour (Slider::backgroundColourId));
  55057. if (style == Slider::LinearBar)
  55058. {
  55059. g.setColour (slider.findColour (Slider::thumbColourId));
  55060. g.fillRect (x, y, (int) sliderPos - x, h);
  55061. g.setColour (slider.findColour (Slider::textBoxTextColourId).withMultipliedAlpha (0.5f));
  55062. g.drawRect (x, y, (int) sliderPos - x, h);
  55063. }
  55064. else
  55065. {
  55066. g.setColour (slider.findColour (Slider::trackColourId)
  55067. .withMultipliedAlpha (slider.isEnabled() ? 1.0f : 0.3f));
  55068. if (slider.isHorizontal())
  55069. {
  55070. g.fillRect (x, y + roundToInt (h * 0.6f),
  55071. w, roundToInt (h * 0.2f));
  55072. }
  55073. else
  55074. {
  55075. g.fillRect (x + roundToInt (w * 0.5f - jmin (3.0f, w * 0.1f)), y,
  55076. jmin (4, roundToInt (w * 0.2f)), h);
  55077. }
  55078. float alpha = 0.35f;
  55079. if (slider.isEnabled())
  55080. alpha = slider.isMouseOverOrDragging() ? 1.0f : 0.7f;
  55081. const Colour fill (slider.findColour (Slider::thumbColourId).withAlpha (alpha));
  55082. const Colour outline (Colours::black.withAlpha (slider.isEnabled() ? 0.7f : 0.35f));
  55083. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  55084. {
  55085. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), minSliderPos,
  55086. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos - 7.0f,
  55087. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos,
  55088. fill, outline);
  55089. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), maxSliderPos,
  55090. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos,
  55091. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos + 7.0f,
  55092. fill, outline);
  55093. }
  55094. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  55095. {
  55096. drawTriangle (g, minSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  55097. minSliderPos - 7.0f, y + h * 0.9f ,
  55098. minSliderPos, y + h * 0.9f,
  55099. fill, outline);
  55100. drawTriangle (g, maxSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  55101. maxSliderPos, y + h * 0.9f,
  55102. maxSliderPos + 7.0f, y + h * 0.9f,
  55103. fill, outline);
  55104. }
  55105. if (style == Slider::LinearHorizontal || style == Slider::ThreeValueHorizontal)
  55106. {
  55107. drawTriangle (g, sliderPos, y + h * 0.9f,
  55108. sliderPos - 7.0f, y + h * 0.2f,
  55109. sliderPos + 7.0f, y + h * 0.2f,
  55110. fill, outline);
  55111. }
  55112. else if (style == Slider::LinearVertical || style == Slider::ThreeValueVertical)
  55113. {
  55114. drawTriangle (g, x + w * 0.5f - jmin (4.0f, w * 0.3f), sliderPos,
  55115. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos - 7.0f,
  55116. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos + 7.0f,
  55117. fill, outline);
  55118. }
  55119. }
  55120. }
  55121. Button* OldSchoolLookAndFeel::createSliderButton (const bool isIncrement)
  55122. {
  55123. if (isIncrement)
  55124. return new ArrowButton ("u", 0.75f, Colours::white.withAlpha (0.8f));
  55125. else
  55126. return new ArrowButton ("d", 0.25f, Colours::white.withAlpha (0.8f));
  55127. }
  55128. ImageEffectFilter* OldSchoolLookAndFeel::getSliderEffect()
  55129. {
  55130. return &scrollbarShadow;
  55131. }
  55132. int OldSchoolLookAndFeel::getSliderThumbRadius (Slider&)
  55133. {
  55134. return 8;
  55135. }
  55136. void OldSchoolLookAndFeel::drawCornerResizer (Graphics& g,
  55137. int w, int h,
  55138. bool isMouseOver,
  55139. bool isMouseDragging)
  55140. {
  55141. g.setColour ((isMouseOver || isMouseDragging) ? Colours::lightgrey
  55142. : Colours::darkgrey);
  55143. const float lineThickness = jmin (w, h) * 0.1f;
  55144. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  55145. {
  55146. g.drawLine (w * i,
  55147. h + 1.0f,
  55148. w + 1.0f,
  55149. h * i,
  55150. lineThickness);
  55151. }
  55152. }
  55153. Button* OldSchoolLookAndFeel::createDocumentWindowButton (int buttonType)
  55154. {
  55155. Path shape;
  55156. if (buttonType == DocumentWindow::closeButton)
  55157. {
  55158. shape.addLineSegment (Line<float> (0.0f, 0.0f, 1.0f, 1.0f), 0.35f);
  55159. shape.addLineSegment (Line<float> (1.0f, 0.0f, 0.0f, 1.0f), 0.35f);
  55160. ShapeButton* const b = new ShapeButton ("close",
  55161. Colour (0x7fff3333),
  55162. Colour (0xd7ff3333),
  55163. Colour (0xf7ff3333));
  55164. b->setShape (shape, true, true, true);
  55165. return b;
  55166. }
  55167. else if (buttonType == DocumentWindow::minimiseButton)
  55168. {
  55169. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), 0.25f);
  55170. DrawableButton* b = new DrawableButton ("minimise", DrawableButton::ImageFitted);
  55171. DrawablePath dp;
  55172. dp.setPath (shape);
  55173. dp.setFill (Colours::black.withAlpha (0.3f));
  55174. b->setImages (&dp);
  55175. return b;
  55176. }
  55177. else if (buttonType == DocumentWindow::maximiseButton)
  55178. {
  55179. shape.addLineSegment (Line<float> (0.5f, 0.0f, 0.5f, 1.0f), 0.25f);
  55180. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), 0.25f);
  55181. DrawableButton* b = new DrawableButton ("maximise", DrawableButton::ImageFitted);
  55182. DrawablePath dp;
  55183. dp.setPath (shape);
  55184. dp.setFill (Colours::black.withAlpha (0.3f));
  55185. b->setImages (&dp);
  55186. return b;
  55187. }
  55188. jassertfalse;
  55189. return 0;
  55190. }
  55191. void OldSchoolLookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  55192. int titleBarX,
  55193. int titleBarY,
  55194. int titleBarW,
  55195. int titleBarH,
  55196. Button* minimiseButton,
  55197. Button* maximiseButton,
  55198. Button* closeButton,
  55199. bool positionTitleBarButtonsOnLeft)
  55200. {
  55201. titleBarY += titleBarH / 8;
  55202. titleBarH -= titleBarH / 4;
  55203. const int buttonW = titleBarH;
  55204. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  55205. : titleBarX + titleBarW - buttonW - 4;
  55206. if (closeButton != 0)
  55207. {
  55208. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  55209. x += positionTitleBarButtonsOnLeft ? buttonW + buttonW / 5
  55210. : -(buttonW + buttonW / 5);
  55211. }
  55212. if (positionTitleBarButtonsOnLeft)
  55213. swapVariables (minimiseButton, maximiseButton);
  55214. if (maximiseButton != 0)
  55215. {
  55216. maximiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  55217. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  55218. }
  55219. if (minimiseButton != 0)
  55220. minimiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  55221. }
  55222. END_JUCE_NAMESPACE
  55223. /*** End of inlined file: juce_OldSchoolLookAndFeel.cpp ***/
  55224. /*** Start of inlined file: juce_MenuBarComponent.cpp ***/
  55225. BEGIN_JUCE_NAMESPACE
  55226. MenuBarComponent::MenuBarComponent (MenuBarModel* model_)
  55227. : model (0),
  55228. itemUnderMouse (-1),
  55229. currentPopupIndex (-1),
  55230. topLevelIndexClicked (0),
  55231. lastMouseX (0),
  55232. lastMouseY (0)
  55233. {
  55234. setRepaintsOnMouseActivity (true);
  55235. setWantsKeyboardFocus (false);
  55236. setMouseClickGrabsKeyboardFocus (false);
  55237. setModel (model_);
  55238. }
  55239. MenuBarComponent::~MenuBarComponent()
  55240. {
  55241. setModel (0);
  55242. Desktop::getInstance().removeGlobalMouseListener (this);
  55243. }
  55244. MenuBarModel* MenuBarComponent::getModel() const throw()
  55245. {
  55246. return model;
  55247. }
  55248. void MenuBarComponent::setModel (MenuBarModel* const newModel)
  55249. {
  55250. if (model != newModel)
  55251. {
  55252. if (model != 0)
  55253. model->removeListener (this);
  55254. model = newModel;
  55255. if (model != 0)
  55256. model->addListener (this);
  55257. repaint();
  55258. menuBarItemsChanged (0);
  55259. }
  55260. }
  55261. void MenuBarComponent::paint (Graphics& g)
  55262. {
  55263. const bool isMouseOverBar = currentPopupIndex >= 0 || itemUnderMouse >= 0 || isMouseOver();
  55264. getLookAndFeel().drawMenuBarBackground (g,
  55265. getWidth(),
  55266. getHeight(),
  55267. isMouseOverBar,
  55268. *this);
  55269. if (model != 0)
  55270. {
  55271. for (int i = 0; i < menuNames.size(); ++i)
  55272. {
  55273. g.saveState();
  55274. g.setOrigin (xPositions [i], 0);
  55275. g.reduceClipRegion (0, 0, xPositions[i + 1] - xPositions[i], getHeight());
  55276. getLookAndFeel().drawMenuBarItem (g,
  55277. xPositions[i + 1] - xPositions[i],
  55278. getHeight(),
  55279. i,
  55280. menuNames[i],
  55281. i == itemUnderMouse,
  55282. i == currentPopupIndex,
  55283. isMouseOverBar,
  55284. *this);
  55285. g.restoreState();
  55286. }
  55287. }
  55288. }
  55289. void MenuBarComponent::resized()
  55290. {
  55291. xPositions.clear();
  55292. int x = 0;
  55293. xPositions.add (x);
  55294. for (int i = 0; i < menuNames.size(); ++i)
  55295. {
  55296. x += getLookAndFeel().getMenuBarItemWidth (*this, i, menuNames[i]);
  55297. xPositions.add (x);
  55298. }
  55299. }
  55300. int MenuBarComponent::getItemAt (const int x, const int y)
  55301. {
  55302. for (int i = 0; i < xPositions.size(); ++i)
  55303. if (x >= xPositions[i] && x < xPositions[i + 1])
  55304. return reallyContains (x, y, true) ? i : -1;
  55305. return -1;
  55306. }
  55307. void MenuBarComponent::repaintMenuItem (int index)
  55308. {
  55309. if (((unsigned int) index) < (unsigned int) xPositions.size())
  55310. {
  55311. const int x1 = xPositions [index];
  55312. const int x2 = xPositions [index + 1];
  55313. repaint (x1 - 2, 0, x2 - x1 + 4, getHeight());
  55314. }
  55315. }
  55316. void MenuBarComponent::setItemUnderMouse (const int index)
  55317. {
  55318. if (itemUnderMouse != index)
  55319. {
  55320. repaintMenuItem (itemUnderMouse);
  55321. itemUnderMouse = index;
  55322. repaintMenuItem (itemUnderMouse);
  55323. }
  55324. }
  55325. void MenuBarComponent::setOpenItem (int index)
  55326. {
  55327. if (currentPopupIndex != index)
  55328. {
  55329. repaintMenuItem (currentPopupIndex);
  55330. currentPopupIndex = index;
  55331. repaintMenuItem (currentPopupIndex);
  55332. if (index >= 0)
  55333. Desktop::getInstance().addGlobalMouseListener (this);
  55334. else
  55335. Desktop::getInstance().removeGlobalMouseListener (this);
  55336. }
  55337. }
  55338. void MenuBarComponent::updateItemUnderMouse (int x, int y)
  55339. {
  55340. setItemUnderMouse (getItemAt (x, y));
  55341. }
  55342. class MenuBarComponent::AsyncCallback : public ModalComponentManager::Callback
  55343. {
  55344. public:
  55345. AsyncCallback (MenuBarComponent* const bar_, const int topLevelIndex_)
  55346. : bar (bar_), topLevelIndex (topLevelIndex_)
  55347. {
  55348. }
  55349. ~AsyncCallback() {}
  55350. void modalStateFinished (int returnValue)
  55351. {
  55352. if (bar != 0)
  55353. bar->menuDismissed (topLevelIndex, returnValue);
  55354. }
  55355. private:
  55356. Component::SafePointer<MenuBarComponent> bar;
  55357. const int topLevelIndex;
  55358. AsyncCallback (const AsyncCallback&);
  55359. AsyncCallback& operator= (const AsyncCallback&);
  55360. };
  55361. void MenuBarComponent::showMenu (int index)
  55362. {
  55363. if (index != currentPopupIndex)
  55364. {
  55365. PopupMenu::dismissAllActiveMenus();
  55366. menuBarItemsChanged (0);
  55367. setOpenItem (index);
  55368. setItemUnderMouse (index);
  55369. if (index >= 0)
  55370. {
  55371. PopupMenu m (model->getMenuForIndex (itemUnderMouse,
  55372. menuNames [itemUnderMouse]));
  55373. if (m.lookAndFeel == 0)
  55374. m.setLookAndFeel (&getLookAndFeel());
  55375. const Rectangle<int> itemPos (xPositions [index], 0, xPositions [index + 1] - xPositions [index], getHeight());
  55376. m.showMenu (itemPos + getScreenPosition(),
  55377. 0, itemPos.getWidth(), 0, 0, true, this,
  55378. new AsyncCallback (this, index));
  55379. }
  55380. }
  55381. }
  55382. void MenuBarComponent::menuDismissed (int topLevelIndex, int itemId)
  55383. {
  55384. topLevelIndexClicked = topLevelIndex;
  55385. postCommandMessage (itemId);
  55386. }
  55387. void MenuBarComponent::handleCommandMessage (int commandId)
  55388. {
  55389. const Point<int> mousePos (getMouseXYRelative());
  55390. updateItemUnderMouse (mousePos.getX(), mousePos.getY());
  55391. if (currentPopupIndex == topLevelIndexClicked)
  55392. setOpenItem (-1);
  55393. if (commandId != 0 && model != 0)
  55394. model->menuItemSelected (commandId, topLevelIndexClicked);
  55395. }
  55396. void MenuBarComponent::mouseEnter (const MouseEvent& e)
  55397. {
  55398. if (e.eventComponent == this)
  55399. updateItemUnderMouse (e.x, e.y);
  55400. }
  55401. void MenuBarComponent::mouseExit (const MouseEvent& e)
  55402. {
  55403. if (e.eventComponent == this)
  55404. updateItemUnderMouse (e.x, e.y);
  55405. }
  55406. void MenuBarComponent::mouseDown (const MouseEvent& e)
  55407. {
  55408. if (currentPopupIndex < 0)
  55409. {
  55410. const MouseEvent e2 (e.getEventRelativeTo (this));
  55411. updateItemUnderMouse (e2.x, e2.y);
  55412. currentPopupIndex = -2;
  55413. showMenu (itemUnderMouse);
  55414. }
  55415. }
  55416. void MenuBarComponent::mouseDrag (const MouseEvent& e)
  55417. {
  55418. const MouseEvent e2 (e.getEventRelativeTo (this));
  55419. const int item = getItemAt (e2.x, e2.y);
  55420. if (item >= 0)
  55421. showMenu (item);
  55422. }
  55423. void MenuBarComponent::mouseUp (const MouseEvent& e)
  55424. {
  55425. const MouseEvent e2 (e.getEventRelativeTo (this));
  55426. updateItemUnderMouse (e2.x, e2.y);
  55427. if (itemUnderMouse < 0 && getLocalBounds().contains (e2.x, e2.y))
  55428. {
  55429. setOpenItem (-1);
  55430. PopupMenu::dismissAllActiveMenus();
  55431. }
  55432. }
  55433. void MenuBarComponent::mouseMove (const MouseEvent& e)
  55434. {
  55435. const MouseEvent e2 (e.getEventRelativeTo (this));
  55436. if (lastMouseX != e2.x || lastMouseY != e2.y)
  55437. {
  55438. if (currentPopupIndex >= 0)
  55439. {
  55440. const int item = getItemAt (e2.x, e2.y);
  55441. if (item >= 0)
  55442. showMenu (item);
  55443. }
  55444. else
  55445. {
  55446. updateItemUnderMouse (e2.x, e2.y);
  55447. }
  55448. lastMouseX = e2.x;
  55449. lastMouseY = e2.y;
  55450. }
  55451. }
  55452. bool MenuBarComponent::keyPressed (const KeyPress& key)
  55453. {
  55454. bool used = false;
  55455. const int numMenus = menuNames.size();
  55456. const int currentIndex = jlimit (0, menuNames.size() - 1, currentPopupIndex);
  55457. if (key.isKeyCode (KeyPress::leftKey))
  55458. {
  55459. showMenu ((currentIndex + numMenus - 1) % numMenus);
  55460. used = true;
  55461. }
  55462. else if (key.isKeyCode (KeyPress::rightKey))
  55463. {
  55464. showMenu ((currentIndex + 1) % numMenus);
  55465. used = true;
  55466. }
  55467. return used;
  55468. }
  55469. void MenuBarComponent::menuBarItemsChanged (MenuBarModel* /*menuBarModel*/)
  55470. {
  55471. StringArray newNames;
  55472. if (model != 0)
  55473. newNames = model->getMenuBarNames();
  55474. if (newNames != menuNames)
  55475. {
  55476. menuNames = newNames;
  55477. repaint();
  55478. resized();
  55479. }
  55480. }
  55481. void MenuBarComponent::menuCommandInvoked (MenuBarModel* /*menuBarModel*/,
  55482. const ApplicationCommandTarget::InvocationInfo& info)
  55483. {
  55484. if (model == 0 || (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) != 0)
  55485. return;
  55486. for (int i = 0; i < menuNames.size(); ++i)
  55487. {
  55488. const PopupMenu menu (model->getMenuForIndex (i, menuNames [i]));
  55489. if (menu.containsCommandItem (info.commandID))
  55490. {
  55491. setItemUnderMouse (i);
  55492. startTimer (200);
  55493. break;
  55494. }
  55495. }
  55496. }
  55497. void MenuBarComponent::timerCallback()
  55498. {
  55499. stopTimer();
  55500. const Point<int> mousePos (getMouseXYRelative());
  55501. updateItemUnderMouse (mousePos.getX(), mousePos.getY());
  55502. }
  55503. END_JUCE_NAMESPACE
  55504. /*** End of inlined file: juce_MenuBarComponent.cpp ***/
  55505. /*** Start of inlined file: juce_MenuBarModel.cpp ***/
  55506. BEGIN_JUCE_NAMESPACE
  55507. MenuBarModel::MenuBarModel() throw()
  55508. : manager (0)
  55509. {
  55510. }
  55511. MenuBarModel::~MenuBarModel()
  55512. {
  55513. setApplicationCommandManagerToWatch (0);
  55514. }
  55515. void MenuBarModel::menuItemsChanged()
  55516. {
  55517. triggerAsyncUpdate();
  55518. }
  55519. void MenuBarModel::setApplicationCommandManagerToWatch (ApplicationCommandManager* const newManager) throw()
  55520. {
  55521. if (manager != newManager)
  55522. {
  55523. if (manager != 0)
  55524. manager->removeListener (this);
  55525. manager = newManager;
  55526. if (manager != 0)
  55527. manager->addListener (this);
  55528. }
  55529. }
  55530. void MenuBarModel::addListener (Listener* const newListener) throw()
  55531. {
  55532. listeners.add (newListener);
  55533. }
  55534. void MenuBarModel::removeListener (Listener* const listenerToRemove) throw()
  55535. {
  55536. // Trying to remove a listener that isn't on the list!
  55537. // If this assertion happens because this object is a dangling pointer, make sure you've not
  55538. // deleted this menu model while it's still being used by something (e.g. by a MenuBarComponent)
  55539. jassert (listeners.contains (listenerToRemove));
  55540. listeners.remove (listenerToRemove);
  55541. }
  55542. void MenuBarModel::handleAsyncUpdate()
  55543. {
  55544. listeners.call (&MenuBarModel::Listener::menuBarItemsChanged, this);
  55545. }
  55546. void MenuBarModel::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  55547. {
  55548. listeners.call (&MenuBarModel::Listener::menuCommandInvoked, this, info);
  55549. }
  55550. void MenuBarModel::applicationCommandListChanged()
  55551. {
  55552. menuItemsChanged();
  55553. }
  55554. END_JUCE_NAMESPACE
  55555. /*** End of inlined file: juce_MenuBarModel.cpp ***/
  55556. /*** Start of inlined file: juce_PopupMenu.cpp ***/
  55557. BEGIN_JUCE_NAMESPACE
  55558. class PopupMenu::Item
  55559. {
  55560. public:
  55561. Item()
  55562. : itemId (0), active (true), isSeparator (true), isTicked (false),
  55563. usesColour (false), customComp (0), commandManager (0)
  55564. {
  55565. }
  55566. Item (const int itemId_,
  55567. const String& text_,
  55568. const bool active_,
  55569. const bool isTicked_,
  55570. const Image& im,
  55571. const Colour& textColour_,
  55572. const bool usesColour_,
  55573. PopupMenuCustomComponent* const customComp_,
  55574. const PopupMenu* const subMenu_,
  55575. ApplicationCommandManager* const commandManager_)
  55576. : itemId (itemId_), text (text_), textColour (textColour_),
  55577. active (active_), isSeparator (false), isTicked (isTicked_),
  55578. usesColour (usesColour_), image (im), customComp (customComp_),
  55579. commandManager (commandManager_)
  55580. {
  55581. if (subMenu_ != 0)
  55582. subMenu = new PopupMenu (*subMenu_);
  55583. if (commandManager_ != 0 && itemId_ != 0)
  55584. {
  55585. String shortcutKey;
  55586. Array <KeyPress> keyPresses (commandManager_->getKeyMappings()
  55587. ->getKeyPressesAssignedToCommand (itemId_));
  55588. for (int i = 0; i < keyPresses.size(); ++i)
  55589. {
  55590. const String key (keyPresses.getReference(i).getTextDescription());
  55591. if (shortcutKey.isNotEmpty())
  55592. shortcutKey << ", ";
  55593. if (key.length() == 1)
  55594. shortcutKey << "shortcut: '" << key << '\'';
  55595. else
  55596. shortcutKey << key;
  55597. }
  55598. shortcutKey = shortcutKey.trim();
  55599. if (shortcutKey.isNotEmpty())
  55600. text << "<end>" << shortcutKey;
  55601. }
  55602. }
  55603. Item (const Item& other)
  55604. : itemId (other.itemId),
  55605. text (other.text),
  55606. textColour (other.textColour),
  55607. active (other.active),
  55608. isSeparator (other.isSeparator),
  55609. isTicked (other.isTicked),
  55610. usesColour (other.usesColour),
  55611. image (other.image),
  55612. customComp (other.customComp),
  55613. commandManager (other.commandManager)
  55614. {
  55615. if (other.subMenu != 0)
  55616. subMenu = new PopupMenu (*(other.subMenu));
  55617. }
  55618. ~Item()
  55619. {
  55620. customComp = 0;
  55621. }
  55622. bool canBeTriggered() const throw()
  55623. {
  55624. return active && ! (isSeparator || (subMenu != 0));
  55625. }
  55626. bool hasActiveSubMenu() const throw()
  55627. {
  55628. return active && (subMenu != 0);
  55629. }
  55630. const int itemId;
  55631. String text;
  55632. const Colour textColour;
  55633. const bool active, isSeparator, isTicked, usesColour;
  55634. Image image;
  55635. ReferenceCountedObjectPtr <PopupMenuCustomComponent> customComp;
  55636. ScopedPointer <PopupMenu> subMenu;
  55637. ApplicationCommandManager* const commandManager;
  55638. juce_UseDebuggingNewOperator
  55639. private:
  55640. Item& operator= (const Item&);
  55641. };
  55642. class PopupMenu::ItemComponent : public Component
  55643. {
  55644. public:
  55645. ItemComponent (const PopupMenu::Item& itemInfo_)
  55646. : itemInfo (itemInfo_),
  55647. isHighlighted (false)
  55648. {
  55649. if (itemInfo.customComp != 0)
  55650. addAndMakeVisible (itemInfo.customComp);
  55651. }
  55652. ~ItemComponent()
  55653. {
  55654. if (itemInfo.customComp != 0)
  55655. removeChildComponent (itemInfo.customComp);
  55656. }
  55657. void getIdealSize (int& idealWidth,
  55658. int& idealHeight,
  55659. const int standardItemHeight)
  55660. {
  55661. if (itemInfo.customComp != 0)
  55662. {
  55663. itemInfo.customComp->getIdealSize (idealWidth, idealHeight);
  55664. }
  55665. else
  55666. {
  55667. getLookAndFeel().getIdealPopupMenuItemSize (itemInfo.text,
  55668. itemInfo.isSeparator,
  55669. standardItemHeight,
  55670. idealWidth,
  55671. idealHeight);
  55672. }
  55673. }
  55674. void paint (Graphics& g)
  55675. {
  55676. if (itemInfo.customComp == 0)
  55677. {
  55678. String mainText (itemInfo.text);
  55679. String endText;
  55680. const int endIndex = mainText.indexOf ("<end>");
  55681. if (endIndex >= 0)
  55682. {
  55683. endText = mainText.substring (endIndex + 5).trim();
  55684. mainText = mainText.substring (0, endIndex);
  55685. }
  55686. getLookAndFeel()
  55687. .drawPopupMenuItem (g, getWidth(), getHeight(),
  55688. itemInfo.isSeparator,
  55689. itemInfo.active,
  55690. isHighlighted,
  55691. itemInfo.isTicked,
  55692. itemInfo.subMenu != 0,
  55693. mainText, endText,
  55694. itemInfo.image.isValid() ? &itemInfo.image : 0,
  55695. itemInfo.usesColour ? &(itemInfo.textColour) : 0);
  55696. }
  55697. }
  55698. void resized()
  55699. {
  55700. if (getNumChildComponents() > 0)
  55701. getChildComponent(0)->setBounds (2, 0, getWidth() - 4, getHeight());
  55702. }
  55703. void setHighlighted (bool shouldBeHighlighted)
  55704. {
  55705. shouldBeHighlighted = shouldBeHighlighted && itemInfo.active;
  55706. if (isHighlighted != shouldBeHighlighted)
  55707. {
  55708. isHighlighted = shouldBeHighlighted;
  55709. if (itemInfo.customComp != 0)
  55710. {
  55711. itemInfo.customComp->isHighlighted = shouldBeHighlighted;
  55712. itemInfo.customComp->repaint();
  55713. }
  55714. repaint();
  55715. }
  55716. }
  55717. PopupMenu::Item itemInfo;
  55718. juce_UseDebuggingNewOperator
  55719. private:
  55720. bool isHighlighted;
  55721. ItemComponent (const ItemComponent&);
  55722. ItemComponent& operator= (const ItemComponent&);
  55723. };
  55724. namespace PopupMenuSettings
  55725. {
  55726. static const int scrollZone = 24;
  55727. static const int borderSize = 2;
  55728. static const int timerInterval = 50;
  55729. static const int dismissCommandId = 0x6287345f;
  55730. }
  55731. class PopupMenu::Window : public Component,
  55732. private Timer
  55733. {
  55734. public:
  55735. Window()
  55736. : Component ("menu"),
  55737. owner (0),
  55738. currentChild (0),
  55739. activeSubMenu (0),
  55740. managerOfChosenCommand (0),
  55741. minimumWidth (0),
  55742. maximumNumColumns (7),
  55743. standardItemHeight (0),
  55744. isOver (false),
  55745. hasBeenOver (false),
  55746. isDown (false),
  55747. needsToScroll (false),
  55748. hideOnExit (false),
  55749. disableMouseMoves (false),
  55750. hasAnyJuceCompHadFocus (false),
  55751. numColumns (0),
  55752. contentHeight (0),
  55753. childYOffset (0),
  55754. timeEnteredCurrentChildComp (0),
  55755. scrollAcceleration (1.0)
  55756. {
  55757. menuCreationTime = lastFocused = lastScroll = Time::getMillisecondCounter();
  55758. setWantsKeyboardFocus (true);
  55759. setMouseClickGrabsKeyboardFocus (false);
  55760. setAlwaysOnTop (true);
  55761. Desktop::getInstance().addGlobalMouseListener (this);
  55762. getActiveWindows().add (this);
  55763. }
  55764. ~Window()
  55765. {
  55766. getActiveWindows().removeValue (this);
  55767. Desktop::getInstance().removeGlobalMouseListener (this);
  55768. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  55769. activeSubMenu = 0;
  55770. deleteAllChildren();
  55771. }
  55772. static Window* create (const PopupMenu& menu,
  55773. const bool dismissOnMouseUp,
  55774. Window* const owner_,
  55775. const Rectangle<int>& target,
  55776. const int minimumWidth,
  55777. const int maximumNumColumns,
  55778. const int standardItemHeight,
  55779. const bool alignToRectangle,
  55780. const int itemIdThatMustBeVisible,
  55781. ApplicationCommandManager** managerOfChosenCommand,
  55782. Component* const componentAttachedTo)
  55783. {
  55784. if (menu.items.size() > 0)
  55785. {
  55786. int totalItems = 0;
  55787. ScopedPointer <Window> mw (new Window());
  55788. mw->setLookAndFeel (menu.lookAndFeel);
  55789. mw->setWantsKeyboardFocus (false);
  55790. mw->setOpaque (mw->getLookAndFeel().findColour (PopupMenu::backgroundColourId).isOpaque() || ! Desktop::canUseSemiTransparentWindows());
  55791. mw->minimumWidth = minimumWidth;
  55792. mw->maximumNumColumns = maximumNumColumns;
  55793. mw->standardItemHeight = standardItemHeight;
  55794. mw->dismissOnMouseUp = dismissOnMouseUp;
  55795. for (int i = 0; i < menu.items.size(); ++i)
  55796. {
  55797. PopupMenu::Item* const item = menu.items.getUnchecked(i);
  55798. mw->addItem (*item);
  55799. ++totalItems;
  55800. }
  55801. if (totalItems > 0)
  55802. {
  55803. mw->owner = owner_;
  55804. mw->managerOfChosenCommand = managerOfChosenCommand;
  55805. mw->componentAttachedTo = componentAttachedTo;
  55806. mw->componentAttachedToOriginal = componentAttachedTo;
  55807. mw->calculateWindowPos (target, alignToRectangle);
  55808. mw->setTopLeftPosition (mw->windowPos.getX(),
  55809. mw->windowPos.getY());
  55810. mw->updateYPositions();
  55811. if (itemIdThatMustBeVisible != 0)
  55812. {
  55813. const int y = target.getY() - mw->windowPos.getY();
  55814. mw->ensureItemIsVisible (itemIdThatMustBeVisible,
  55815. (((unsigned int) y) < (unsigned int) mw->windowPos.getHeight()) ? y : -1);
  55816. }
  55817. mw->resizeToBestWindowPos();
  55818. mw->addToDesktop (ComponentPeer::windowIsTemporary
  55819. | mw->getLookAndFeel().getMenuWindowFlags());
  55820. return mw.release();
  55821. }
  55822. }
  55823. return 0;
  55824. }
  55825. void paint (Graphics& g)
  55826. {
  55827. if (isOpaque())
  55828. g.fillAll (Colours::white);
  55829. getLookAndFeel().drawPopupMenuBackground (g, getWidth(), getHeight());
  55830. }
  55831. void paintOverChildren (Graphics& g)
  55832. {
  55833. if (isScrolling())
  55834. {
  55835. LookAndFeel& lf = getLookAndFeel();
  55836. if (isScrollZoneActive (false))
  55837. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, true);
  55838. if (isScrollZoneActive (true))
  55839. {
  55840. g.setOrigin (0, getHeight() - PopupMenuSettings::scrollZone);
  55841. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, false);
  55842. }
  55843. }
  55844. }
  55845. bool isScrollZoneActive (bool bottomOne) const
  55846. {
  55847. return isScrolling()
  55848. && (bottomOne
  55849. ? childYOffset < contentHeight - windowPos.getHeight()
  55850. : childYOffset > 0);
  55851. }
  55852. void addItem (const PopupMenu::Item& item)
  55853. {
  55854. PopupMenu::ItemComponent* const mic = new PopupMenu::ItemComponent (item);
  55855. addAndMakeVisible (mic);
  55856. int itemW = 80;
  55857. int itemH = 16;
  55858. mic->getIdealSize (itemW, itemH, standardItemHeight);
  55859. mic->setSize (itemW, jlimit (2, 600, itemH));
  55860. mic->addMouseListener (this, false);
  55861. }
  55862. // hide this and all sub-comps
  55863. void hide (const PopupMenu::Item* const item, const bool makeInvisible)
  55864. {
  55865. if (isVisible())
  55866. {
  55867. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  55868. activeSubMenu = 0;
  55869. currentChild = 0;
  55870. exitModalState (item != 0 ? item->itemId : 0);
  55871. if (makeInvisible)
  55872. setVisible (false);
  55873. if (item != 0
  55874. && item->commandManager != 0
  55875. && item->itemId != 0)
  55876. {
  55877. *managerOfChosenCommand = item->commandManager;
  55878. }
  55879. }
  55880. }
  55881. void dismissMenu (const PopupMenu::Item* const item)
  55882. {
  55883. if (owner != 0)
  55884. {
  55885. owner->dismissMenu (item);
  55886. }
  55887. else
  55888. {
  55889. if (item != 0)
  55890. {
  55891. // need a copy of this on the stack as the one passed in will get deleted during this call
  55892. const PopupMenu::Item mi (*item);
  55893. hide (&mi, false);
  55894. }
  55895. else
  55896. {
  55897. hide (0, false);
  55898. }
  55899. }
  55900. }
  55901. void mouseMove (const MouseEvent&)
  55902. {
  55903. timerCallback();
  55904. }
  55905. void mouseDown (const MouseEvent&)
  55906. {
  55907. timerCallback();
  55908. }
  55909. void mouseDrag (const MouseEvent&)
  55910. {
  55911. timerCallback();
  55912. }
  55913. void mouseUp (const MouseEvent&)
  55914. {
  55915. timerCallback();
  55916. }
  55917. void mouseWheelMove (const MouseEvent&, float /*amountX*/, float amountY)
  55918. {
  55919. alterChildYPos (roundToInt (-10.0f * amountY * PopupMenuSettings::scrollZone));
  55920. lastMouse = Point<int> (-1, -1);
  55921. }
  55922. bool keyPressed (const KeyPress& key)
  55923. {
  55924. if (key.isKeyCode (KeyPress::downKey))
  55925. {
  55926. selectNextItem (1);
  55927. }
  55928. else if (key.isKeyCode (KeyPress::upKey))
  55929. {
  55930. selectNextItem (-1);
  55931. }
  55932. else if (key.isKeyCode (KeyPress::leftKey))
  55933. {
  55934. if (owner != 0)
  55935. {
  55936. Component::SafePointer<Window> parentWindow (owner);
  55937. PopupMenu::ItemComponent* currentChildOfParent = parentWindow->currentChild;
  55938. hide (0, true);
  55939. if (parentWindow != 0)
  55940. parentWindow->setCurrentlyHighlightedChild (currentChildOfParent);
  55941. disableTimerUntilMouseMoves();
  55942. }
  55943. else if (componentAttachedTo != 0)
  55944. {
  55945. componentAttachedTo->keyPressed (key);
  55946. }
  55947. }
  55948. else if (key.isKeyCode (KeyPress::rightKey))
  55949. {
  55950. disableTimerUntilMouseMoves();
  55951. if (showSubMenuFor (currentChild))
  55952. {
  55953. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  55954. if (activeSubMenu != 0 && activeSubMenu->isVisible())
  55955. activeSubMenu->selectNextItem (1);
  55956. }
  55957. else if (componentAttachedTo != 0)
  55958. {
  55959. componentAttachedTo->keyPressed (key);
  55960. }
  55961. }
  55962. else if (key.isKeyCode (KeyPress::returnKey))
  55963. {
  55964. triggerCurrentlyHighlightedItem();
  55965. }
  55966. else if (key.isKeyCode (KeyPress::escapeKey))
  55967. {
  55968. dismissMenu (0);
  55969. }
  55970. else
  55971. {
  55972. return false;
  55973. }
  55974. return true;
  55975. }
  55976. void inputAttemptWhenModal()
  55977. {
  55978. Component::SafePointer<Component> deletionChecker (this);
  55979. timerCallback();
  55980. if (deletionChecker != 0 && ! isOverAnyMenu())
  55981. {
  55982. if (componentAttachedTo != 0)
  55983. {
  55984. // we want to dismiss the menu, but if we do it synchronously, then
  55985. // the mouse-click will be allowed to pass through. That's good, except
  55986. // when the user clicks on the button that orginally popped the menu up,
  55987. // as they'll expect the menu to go away, and in fact it'll just
  55988. // come back. So only dismiss synchronously if they're not on the original
  55989. // comp that we're attached to.
  55990. const Point<int> mousePos (componentAttachedTo->getMouseXYRelative());
  55991. if (componentAttachedTo->reallyContains (mousePos.getX(), mousePos.getY(), true))
  55992. {
  55993. postCommandMessage (PopupMenuSettings::dismissCommandId); // dismiss asynchrounously
  55994. return;
  55995. }
  55996. }
  55997. dismissMenu (0);
  55998. }
  55999. }
  56000. void handleCommandMessage (int commandId)
  56001. {
  56002. Component::handleCommandMessage (commandId);
  56003. if (commandId == PopupMenuSettings::dismissCommandId)
  56004. dismissMenu (0);
  56005. }
  56006. void timerCallback()
  56007. {
  56008. if (! isVisible())
  56009. return;
  56010. if (componentAttachedTo != componentAttachedToOriginal)
  56011. {
  56012. dismissMenu (0);
  56013. return;
  56014. }
  56015. Window* currentlyModalWindow = dynamic_cast <Window*> (Component::getCurrentlyModalComponent());
  56016. if (currentlyModalWindow != 0 && ! treeContains (currentlyModalWindow))
  56017. return;
  56018. startTimer (PopupMenuSettings::timerInterval); // do this in case it was called from a mouse
  56019. // move rather than a real timer callback
  56020. const Point<int> globalMousePos (Desktop::getMousePosition());
  56021. const Point<int> localMousePos (globalPositionToRelative (globalMousePos));
  56022. const uint32 now = Time::getMillisecondCounter();
  56023. if (now > timeEnteredCurrentChildComp + 100
  56024. && reallyContains (localMousePos.getX(), localMousePos.getY(), true)
  56025. && currentChild->isValidComponent()
  56026. && (! disableMouseMoves)
  56027. && ! (activeSubMenu != 0 && activeSubMenu->isVisible()))
  56028. {
  56029. showSubMenuFor (currentChild);
  56030. }
  56031. if (globalMousePos != lastMouse || now > lastMouseMoveTime + 350)
  56032. {
  56033. highlightItemUnderMouse (globalMousePos, localMousePos);
  56034. }
  56035. bool overScrollArea = false;
  56036. if (isScrolling()
  56037. && (isOver || (isDown && ((unsigned int) localMousePos.getX()) < (unsigned int) getWidth()))
  56038. && ((isScrollZoneActive (false) && localMousePos.getY() < PopupMenuSettings::scrollZone)
  56039. || (isScrollZoneActive (true) && localMousePos.getY() > getHeight() - PopupMenuSettings::scrollZone)))
  56040. {
  56041. if (now > lastScroll + 20)
  56042. {
  56043. scrollAcceleration = jmin (4.0, scrollAcceleration * 1.04);
  56044. int amount = 0;
  56045. for (int i = 0; i < getNumChildComponents() && amount == 0; ++i)
  56046. amount = ((int) scrollAcceleration) * getChildComponent (i)->getHeight();
  56047. alterChildYPos (localMousePos.getY() < PopupMenuSettings::scrollZone ? -amount : amount);
  56048. lastScroll = now;
  56049. }
  56050. overScrollArea = true;
  56051. lastMouse = Point<int> (-1, -1); // trigger a mouse-move
  56052. }
  56053. else
  56054. {
  56055. scrollAcceleration = 1.0;
  56056. }
  56057. const bool wasDown = isDown;
  56058. bool isOverAny = isOverAnyMenu();
  56059. if (hideOnExit && hasBeenOver && (! isOverAny) && activeSubMenu != 0)
  56060. {
  56061. activeSubMenu->updateMouseOverStatus (globalMousePos);
  56062. isOverAny = isOverAnyMenu();
  56063. }
  56064. if (hideOnExit && hasBeenOver && ! isOverAny)
  56065. {
  56066. hide (0, true);
  56067. }
  56068. else
  56069. {
  56070. isDown = hasBeenOver
  56071. && (ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown()
  56072. || ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown());
  56073. bool anyFocused = Process::isForegroundProcess();
  56074. if (anyFocused && Component::getCurrentlyFocusedComponent() == 0)
  56075. {
  56076. // because no component at all may have focus, our test here will
  56077. // only be triggered when something has focus and then loses it.
  56078. anyFocused = ! hasAnyJuceCompHadFocus;
  56079. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  56080. {
  56081. if (ComponentPeer::getPeer (i)->isFocused())
  56082. {
  56083. anyFocused = true;
  56084. hasAnyJuceCompHadFocus = true;
  56085. break;
  56086. }
  56087. }
  56088. }
  56089. if (! anyFocused)
  56090. {
  56091. if (now > lastFocused + 10)
  56092. {
  56093. wasHiddenBecauseOfAppChange() = true;
  56094. dismissMenu (0);
  56095. return; // may have been deleted by the previous call..
  56096. }
  56097. }
  56098. else if (wasDown && now > menuCreationTime + 250
  56099. && ! (isDown || overScrollArea))
  56100. {
  56101. isOver = reallyContains (localMousePos.getX(), localMousePos.getY(), true);
  56102. if (isOver)
  56103. {
  56104. triggerCurrentlyHighlightedItem();
  56105. }
  56106. else if ((hasBeenOver || ! dismissOnMouseUp) && ! isOverAny)
  56107. {
  56108. dismissMenu (0);
  56109. }
  56110. return; // may have been deleted by the previous calls..
  56111. }
  56112. else
  56113. {
  56114. lastFocused = now;
  56115. }
  56116. }
  56117. }
  56118. static Array<Window*>& getActiveWindows()
  56119. {
  56120. static Array<Window*> activeMenuWindows;
  56121. return activeMenuWindows;
  56122. }
  56123. static bool& wasHiddenBecauseOfAppChange() throw()
  56124. {
  56125. static bool b = false;
  56126. return b;
  56127. }
  56128. juce_UseDebuggingNewOperator
  56129. private:
  56130. Window* owner;
  56131. PopupMenu::ItemComponent* currentChild;
  56132. ScopedPointer <Window> activeSubMenu;
  56133. ApplicationCommandManager** managerOfChosenCommand;
  56134. Component::SafePointer<Component> componentAttachedTo;
  56135. Component* componentAttachedToOriginal;
  56136. Rectangle<int> windowPos;
  56137. Point<int> lastMouse;
  56138. int minimumWidth, maximumNumColumns, standardItemHeight;
  56139. bool isOver, hasBeenOver, isDown, needsToScroll;
  56140. bool dismissOnMouseUp, hideOnExit, disableMouseMoves, hasAnyJuceCompHadFocus;
  56141. int numColumns, contentHeight, childYOffset;
  56142. Array <int> columnWidths;
  56143. uint32 menuCreationTime, lastFocused, lastScroll, lastMouseMoveTime, timeEnteredCurrentChildComp;
  56144. double scrollAcceleration;
  56145. bool overlaps (const Rectangle<int>& r) const
  56146. {
  56147. return r.intersects (getBounds())
  56148. || (owner != 0 && owner->overlaps (r));
  56149. }
  56150. bool isOverAnyMenu() const
  56151. {
  56152. return (owner != 0) ? owner->isOverAnyMenu()
  56153. : isOverChildren();
  56154. }
  56155. bool isOverChildren() const
  56156. {
  56157. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  56158. return isVisible()
  56159. && (isOver || (activeSubMenu != 0 && activeSubMenu->isOverChildren()));
  56160. }
  56161. void updateMouseOverStatus (const Point<int>& globalMousePos)
  56162. {
  56163. const Point<int> relPos (globalPositionToRelative (globalMousePos));
  56164. isOver = reallyContains (relPos.getX(), relPos.getY(), true);
  56165. if (activeSubMenu != 0)
  56166. activeSubMenu->updateMouseOverStatus (globalMousePos);
  56167. }
  56168. bool treeContains (const Window* const window) const throw()
  56169. {
  56170. const Window* mw = this;
  56171. while (mw->owner != 0)
  56172. mw = mw->owner;
  56173. while (mw != 0)
  56174. {
  56175. if (mw == window)
  56176. return true;
  56177. mw = mw->activeSubMenu;
  56178. }
  56179. return false;
  56180. }
  56181. void calculateWindowPos (const Rectangle<int>& target, const bool alignToRectangle)
  56182. {
  56183. const Rectangle<int> mon (Desktop::getInstance()
  56184. .getMonitorAreaContaining (target.getCentre(),
  56185. #if JUCE_MAC
  56186. true));
  56187. #else
  56188. false)); // on windows, don't stop the menu overlapping the taskbar
  56189. #endif
  56190. int x, y, widthToUse, heightToUse;
  56191. layoutMenuItems (mon.getWidth() - 24, widthToUse, heightToUse);
  56192. if (alignToRectangle)
  56193. {
  56194. x = target.getX();
  56195. const int spaceUnder = mon.getHeight() - (target.getBottom() - mon.getY());
  56196. const int spaceOver = target.getY() - mon.getY();
  56197. if (heightToUse < spaceUnder - 30 || spaceUnder >= spaceOver)
  56198. y = target.getBottom();
  56199. else
  56200. y = target.getY() - heightToUse;
  56201. }
  56202. else
  56203. {
  56204. bool tendTowardsRight = target.getCentreX() < mon.getCentreX();
  56205. if (owner != 0)
  56206. {
  56207. if (owner->owner != 0)
  56208. {
  56209. const bool ownerGoingRight = (owner->getX() + owner->getWidth() / 2
  56210. > owner->owner->getX() + owner->owner->getWidth() / 2);
  56211. if (ownerGoingRight && target.getRight() + widthToUse < mon.getRight() - 4)
  56212. tendTowardsRight = true;
  56213. else if ((! ownerGoingRight) && target.getX() > widthToUse + 4)
  56214. tendTowardsRight = false;
  56215. }
  56216. else if (target.getRight() + widthToUse < mon.getRight() - 32)
  56217. {
  56218. tendTowardsRight = true;
  56219. }
  56220. }
  56221. const int biggestSpace = jmax (mon.getRight() - target.getRight(),
  56222. target.getX() - mon.getX()) - 32;
  56223. if (biggestSpace < widthToUse)
  56224. {
  56225. layoutMenuItems (biggestSpace + target.getWidth() / 3, widthToUse, heightToUse);
  56226. if (numColumns > 1)
  56227. layoutMenuItems (biggestSpace - 4, widthToUse, heightToUse);
  56228. tendTowardsRight = (mon.getRight() - target.getRight()) >= (target.getX() - mon.getX());
  56229. }
  56230. if (tendTowardsRight)
  56231. x = jmin (mon.getRight() - widthToUse - 4, target.getRight());
  56232. else
  56233. x = jmax (mon.getX() + 4, target.getX() - widthToUse);
  56234. y = target.getY();
  56235. if (target.getCentreY() > mon.getCentreY())
  56236. y = jmax (mon.getY(), target.getBottom() - heightToUse);
  56237. }
  56238. x = jmax (mon.getX() + 1, jmin (mon.getRight() - (widthToUse + 6), x));
  56239. y = jmax (mon.getY() + 1, jmin (mon.getBottom() - (heightToUse + 6), y));
  56240. windowPos.setBounds (x, y, widthToUse, heightToUse);
  56241. // sets this flag if it's big enough to obscure any of its parent menus
  56242. hideOnExit = (owner != 0)
  56243. && owner->windowPos.intersects (windowPos.expanded (-4, -4));
  56244. }
  56245. void layoutMenuItems (const int maxMenuW, int& width, int& height)
  56246. {
  56247. numColumns = 0;
  56248. contentHeight = 0;
  56249. const int maxMenuH = getParentHeight() - 24;
  56250. int totalW;
  56251. do
  56252. {
  56253. ++numColumns;
  56254. totalW = workOutBestSize (maxMenuW);
  56255. if (totalW > maxMenuW)
  56256. {
  56257. numColumns = jmax (1, numColumns - 1);
  56258. totalW = workOutBestSize (maxMenuW); // to update col widths
  56259. break;
  56260. }
  56261. else if (totalW > maxMenuW / 2 || contentHeight < maxMenuH)
  56262. {
  56263. break;
  56264. }
  56265. } while (numColumns < maximumNumColumns);
  56266. const int actualH = jmin (contentHeight, maxMenuH);
  56267. needsToScroll = contentHeight > actualH;
  56268. width = updateYPositions();
  56269. height = actualH + PopupMenuSettings::borderSize * 2;
  56270. }
  56271. int workOutBestSize (const int maxMenuW)
  56272. {
  56273. int totalW = 0;
  56274. contentHeight = 0;
  56275. int childNum = 0;
  56276. for (int col = 0; col < numColumns; ++col)
  56277. {
  56278. int i, colW = 50, colH = 0;
  56279. const int numChildren = jmin (getNumChildComponents() - childNum,
  56280. (getNumChildComponents() + numColumns - 1) / numColumns);
  56281. for (i = numChildren; --i >= 0;)
  56282. {
  56283. colW = jmax (colW, getChildComponent (childNum + i)->getWidth());
  56284. colH += getChildComponent (childNum + i)->getHeight();
  56285. }
  56286. colW = jmin (maxMenuW / jmax (1, numColumns - 2), colW + PopupMenuSettings::borderSize * 2);
  56287. columnWidths.set (col, colW);
  56288. totalW += colW;
  56289. contentHeight = jmax (contentHeight, colH);
  56290. childNum += numChildren;
  56291. }
  56292. if (totalW < minimumWidth)
  56293. {
  56294. totalW = minimumWidth;
  56295. for (int col = 0; col < numColumns; ++col)
  56296. columnWidths.set (0, totalW / numColumns);
  56297. }
  56298. return totalW;
  56299. }
  56300. void ensureItemIsVisible (const int itemId, int wantedY)
  56301. {
  56302. jassert (itemId != 0)
  56303. for (int i = getNumChildComponents(); --i >= 0;)
  56304. {
  56305. PopupMenu::ItemComponent* const m = static_cast <PopupMenu::ItemComponent*> (getChildComponent (i));
  56306. if (m != 0
  56307. && m->itemInfo.itemId == itemId
  56308. && windowPos.getHeight() > PopupMenuSettings::scrollZone * 4)
  56309. {
  56310. const int currentY = m->getY();
  56311. if (wantedY > 0 || currentY < 0 || m->getBottom() > windowPos.getHeight())
  56312. {
  56313. if (wantedY < 0)
  56314. wantedY = jlimit (PopupMenuSettings::scrollZone,
  56315. jmax (PopupMenuSettings::scrollZone,
  56316. windowPos.getHeight() - (PopupMenuSettings::scrollZone + m->getHeight())),
  56317. currentY);
  56318. const Rectangle<int> mon (Desktop::getInstance().getMonitorAreaContaining (windowPos.getPosition(), true));
  56319. int deltaY = wantedY - currentY;
  56320. windowPos.setSize (jmin (windowPos.getWidth(), mon.getWidth()),
  56321. jmin (windowPos.getHeight(), mon.getHeight()));
  56322. const int newY = jlimit (mon.getY(),
  56323. mon.getBottom() - windowPos.getHeight(),
  56324. windowPos.getY() + deltaY);
  56325. deltaY -= newY - windowPos.getY();
  56326. childYOffset -= deltaY;
  56327. windowPos.setPosition (windowPos.getX(), newY);
  56328. updateYPositions();
  56329. }
  56330. break;
  56331. }
  56332. }
  56333. }
  56334. void resizeToBestWindowPos()
  56335. {
  56336. Rectangle<int> r (windowPos);
  56337. if (childYOffset < 0)
  56338. {
  56339. r.setBounds (r.getX(), r.getY() - childYOffset,
  56340. r.getWidth(), r.getHeight() + childYOffset);
  56341. }
  56342. else if (childYOffset > 0)
  56343. {
  56344. const int spaceAtBottom = r.getHeight() - (contentHeight - childYOffset);
  56345. if (spaceAtBottom > 0)
  56346. r.setSize (r.getWidth(), r.getHeight() - spaceAtBottom);
  56347. }
  56348. setBounds (r);
  56349. updateYPositions();
  56350. }
  56351. void alterChildYPos (const int delta)
  56352. {
  56353. if (isScrolling())
  56354. {
  56355. childYOffset += delta;
  56356. if (delta < 0)
  56357. {
  56358. childYOffset = jmax (childYOffset, 0);
  56359. }
  56360. else if (delta > 0)
  56361. {
  56362. childYOffset = jmin (childYOffset,
  56363. contentHeight - windowPos.getHeight() + PopupMenuSettings::borderSize);
  56364. }
  56365. updateYPositions();
  56366. }
  56367. else
  56368. {
  56369. childYOffset = 0;
  56370. }
  56371. resizeToBestWindowPos();
  56372. repaint();
  56373. }
  56374. int updateYPositions()
  56375. {
  56376. int x = 0;
  56377. int childNum = 0;
  56378. for (int col = 0; col < numColumns; ++col)
  56379. {
  56380. const int numChildren = jmin (getNumChildComponents() - childNum,
  56381. (getNumChildComponents() + numColumns - 1) / numColumns);
  56382. const int colW = columnWidths [col];
  56383. int y = PopupMenuSettings::borderSize - (childYOffset + (getY() - windowPos.getY()));
  56384. for (int i = 0; i < numChildren; ++i)
  56385. {
  56386. Component* const c = getChildComponent (childNum + i);
  56387. c->setBounds (x, y, colW, c->getHeight());
  56388. y += c->getHeight();
  56389. }
  56390. x += colW;
  56391. childNum += numChildren;
  56392. }
  56393. return x;
  56394. }
  56395. bool isScrolling() const throw()
  56396. {
  56397. return childYOffset != 0 || needsToScroll;
  56398. }
  56399. void setCurrentlyHighlightedChild (PopupMenu::ItemComponent* const child)
  56400. {
  56401. if (currentChild->isValidComponent())
  56402. currentChild->setHighlighted (false);
  56403. currentChild = child;
  56404. if (currentChild != 0)
  56405. {
  56406. currentChild->setHighlighted (true);
  56407. timeEnteredCurrentChildComp = Time::getApproximateMillisecondCounter();
  56408. }
  56409. }
  56410. bool showSubMenuFor (PopupMenu::ItemComponent* const childComp)
  56411. {
  56412. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  56413. activeSubMenu = 0;
  56414. if (childComp->isValidComponent() && childComp->itemInfo.hasActiveSubMenu())
  56415. {
  56416. activeSubMenu = Window::create (*(childComp->itemInfo.subMenu),
  56417. dismissOnMouseUp,
  56418. this,
  56419. childComp->getScreenBounds(),
  56420. 0, maximumNumColumns,
  56421. standardItemHeight,
  56422. false, 0, managerOfChosenCommand,
  56423. componentAttachedTo);
  56424. if (activeSubMenu != 0)
  56425. {
  56426. activeSubMenu->setVisible (true);
  56427. activeSubMenu->enterModalState (false);
  56428. activeSubMenu->toFront (false);
  56429. return true;
  56430. }
  56431. }
  56432. return false;
  56433. }
  56434. void highlightItemUnderMouse (const Point<int>& globalMousePos, const Point<int>& localMousePos)
  56435. {
  56436. isOver = reallyContains (localMousePos.getX(), localMousePos.getY(), true);
  56437. if (isOver)
  56438. hasBeenOver = true;
  56439. if (lastMouse.getDistanceFrom (globalMousePos) > 2)
  56440. {
  56441. lastMouseMoveTime = Time::getApproximateMillisecondCounter();
  56442. if (disableMouseMoves && isOver)
  56443. disableMouseMoves = false;
  56444. }
  56445. if (disableMouseMoves || (activeSubMenu != 0 && activeSubMenu->isOverChildren()))
  56446. return;
  56447. bool isMovingTowardsMenu = false;
  56448. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent())
  56449. if (isOver && (activeSubMenu != 0) && globalMousePos != lastMouse)
  56450. {
  56451. // try to intelligently guess whether the user is moving the mouse towards a currently-open
  56452. // submenu. To do this, look at whether the mouse stays inside a triangular region that
  56453. // extends from the last mouse pos to the submenu's rectangle..
  56454. float subX = (float) activeSubMenu->getScreenX();
  56455. if (activeSubMenu->getX() > getX())
  56456. {
  56457. lastMouse -= Point<int> (2, 0); // to enlarge the triangle a bit, in case the mouse only moves a couple of pixels
  56458. }
  56459. else
  56460. {
  56461. lastMouse += Point<int> (2, 0);
  56462. subX += activeSubMenu->getWidth();
  56463. }
  56464. Path areaTowardsSubMenu;
  56465. areaTowardsSubMenu.addTriangle ((float) lastMouse.getX(),
  56466. (float) lastMouse.getY(),
  56467. subX,
  56468. (float) activeSubMenu->getScreenY(),
  56469. subX,
  56470. (float) (activeSubMenu->getScreenY() + activeSubMenu->getHeight()));
  56471. isMovingTowardsMenu = areaTowardsSubMenu.contains ((float) globalMousePos.getX(), (float) globalMousePos.getY());
  56472. }
  56473. lastMouse = globalMousePos;
  56474. if (! isMovingTowardsMenu)
  56475. {
  56476. Component* c = getComponentAt (localMousePos.getX(), localMousePos.getY());
  56477. if (c == this)
  56478. c = 0;
  56479. PopupMenu::ItemComponent* mic = dynamic_cast <PopupMenu::ItemComponent*> (c);
  56480. if (mic == 0 && c != 0)
  56481. mic = c->findParentComponentOfClass ((PopupMenu::ItemComponent*) 0);
  56482. if (mic != currentChild
  56483. && (isOver || (activeSubMenu == 0) || ! activeSubMenu->isVisible()))
  56484. {
  56485. if (isOver && (c != 0) && (activeSubMenu != 0))
  56486. {
  56487. activeSubMenu->hide (0, true);
  56488. }
  56489. if (! isOver)
  56490. mic = 0;
  56491. setCurrentlyHighlightedChild (mic);
  56492. }
  56493. }
  56494. }
  56495. void triggerCurrentlyHighlightedItem()
  56496. {
  56497. if (currentChild->isValidComponent()
  56498. && currentChild->itemInfo.canBeTriggered()
  56499. && (currentChild->itemInfo.customComp == 0
  56500. || currentChild->itemInfo.customComp->isTriggeredAutomatically))
  56501. {
  56502. dismissMenu (&currentChild->itemInfo);
  56503. }
  56504. }
  56505. void selectNextItem (const int delta)
  56506. {
  56507. disableTimerUntilMouseMoves();
  56508. PopupMenu::ItemComponent* mic = 0;
  56509. bool wasLastOne = (currentChild == 0);
  56510. const int numItems = getNumChildComponents();
  56511. for (int i = 0; i < numItems + 1; ++i)
  56512. {
  56513. int index = (delta > 0) ? i : (numItems - 1 - i);
  56514. index = (index + numItems) % numItems;
  56515. mic = dynamic_cast <PopupMenu::ItemComponent*> (getChildComponent (index));
  56516. if (mic != 0 && (mic->itemInfo.canBeTriggered() || mic->itemInfo.hasActiveSubMenu())
  56517. && wasLastOne)
  56518. break;
  56519. if (mic == currentChild)
  56520. wasLastOne = true;
  56521. }
  56522. setCurrentlyHighlightedChild (mic);
  56523. }
  56524. void disableTimerUntilMouseMoves()
  56525. {
  56526. disableMouseMoves = true;
  56527. if (owner != 0)
  56528. owner->disableTimerUntilMouseMoves();
  56529. }
  56530. Window (const Window&);
  56531. Window& operator= (const Window&);
  56532. };
  56533. PopupMenu::PopupMenu()
  56534. : lookAndFeel (0),
  56535. separatorPending (false)
  56536. {
  56537. }
  56538. PopupMenu::PopupMenu (const PopupMenu& other)
  56539. : lookAndFeel (other.lookAndFeel),
  56540. separatorPending (false)
  56541. {
  56542. items.addCopiesOf (other.items);
  56543. }
  56544. PopupMenu& PopupMenu::operator= (const PopupMenu& other)
  56545. {
  56546. if (this != &other)
  56547. {
  56548. lookAndFeel = other.lookAndFeel;
  56549. clear();
  56550. items.addCopiesOf (other.items);
  56551. }
  56552. return *this;
  56553. }
  56554. PopupMenu::~PopupMenu()
  56555. {
  56556. clear();
  56557. }
  56558. void PopupMenu::clear()
  56559. {
  56560. items.clear();
  56561. separatorPending = false;
  56562. }
  56563. void PopupMenu::addSeparatorIfPending()
  56564. {
  56565. if (separatorPending)
  56566. {
  56567. separatorPending = false;
  56568. if (items.size() > 0)
  56569. items.add (new Item());
  56570. }
  56571. }
  56572. void PopupMenu::addItem (const int itemResultId,
  56573. const String& itemText,
  56574. const bool isActive,
  56575. const bool isTicked,
  56576. const Image& iconToUse)
  56577. {
  56578. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  56579. // didn't pick anything, so you shouldn't use it as the id
  56580. // for an item..
  56581. addSeparatorIfPending();
  56582. items.add (new Item (itemResultId, itemText, isActive, isTicked, iconToUse,
  56583. Colours::black, false, 0, 0, 0));
  56584. }
  56585. void PopupMenu::addCommandItem (ApplicationCommandManager* commandManager,
  56586. const int commandID,
  56587. const String& displayName)
  56588. {
  56589. jassert (commandManager != 0 && commandID != 0);
  56590. const ApplicationCommandInfo* const registeredInfo = commandManager->getCommandForID (commandID);
  56591. if (registeredInfo != 0)
  56592. {
  56593. ApplicationCommandInfo info (*registeredInfo);
  56594. ApplicationCommandTarget* const target = commandManager->getTargetForCommand (commandID, info);
  56595. addSeparatorIfPending();
  56596. items.add (new Item (commandID,
  56597. displayName.isNotEmpty() ? displayName
  56598. : info.shortName,
  56599. target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0,
  56600. (info.flags & ApplicationCommandInfo::isTicked) != 0,
  56601. Image::null,
  56602. Colours::black,
  56603. false,
  56604. 0, 0,
  56605. commandManager));
  56606. }
  56607. }
  56608. void PopupMenu::addColouredItem (const int itemResultId,
  56609. const String& itemText,
  56610. const Colour& itemTextColour,
  56611. const bool isActive,
  56612. const bool isTicked,
  56613. const Image& iconToUse)
  56614. {
  56615. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  56616. // didn't pick anything, so you shouldn't use it as the id
  56617. // for an item..
  56618. addSeparatorIfPending();
  56619. items.add (new Item (itemResultId, itemText, isActive, isTicked, iconToUse,
  56620. itemTextColour, true, 0, 0, 0));
  56621. }
  56622. void PopupMenu::addCustomItem (const int itemResultId,
  56623. PopupMenuCustomComponent* const customComponent)
  56624. {
  56625. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  56626. // didn't pick anything, so you shouldn't use it as the id
  56627. // for an item..
  56628. addSeparatorIfPending();
  56629. items.add (new Item (itemResultId, String::empty, true, false, Image::null,
  56630. Colours::black, false, customComponent, 0, 0));
  56631. }
  56632. class NormalComponentWrapper : public PopupMenuCustomComponent
  56633. {
  56634. public:
  56635. NormalComponentWrapper (Component* const comp,
  56636. const int w, const int h,
  56637. const bool triggerMenuItemAutomaticallyWhenClicked)
  56638. : PopupMenuCustomComponent (triggerMenuItemAutomaticallyWhenClicked),
  56639. width (w),
  56640. height (h)
  56641. {
  56642. addAndMakeVisible (comp);
  56643. }
  56644. ~NormalComponentWrapper() {}
  56645. void getIdealSize (int& idealWidth, int& idealHeight)
  56646. {
  56647. idealWidth = width;
  56648. idealHeight = height;
  56649. }
  56650. void resized()
  56651. {
  56652. if (getChildComponent(0) != 0)
  56653. getChildComponent(0)->setBounds (getLocalBounds());
  56654. }
  56655. juce_UseDebuggingNewOperator
  56656. private:
  56657. const int width, height;
  56658. NormalComponentWrapper (const NormalComponentWrapper&);
  56659. NormalComponentWrapper& operator= (const NormalComponentWrapper&);
  56660. };
  56661. void PopupMenu::addCustomItem (const int itemResultId,
  56662. Component* customComponent,
  56663. int idealWidth, int idealHeight,
  56664. const bool triggerMenuItemAutomaticallyWhenClicked)
  56665. {
  56666. addCustomItem (itemResultId,
  56667. new NormalComponentWrapper (customComponent,
  56668. idealWidth, idealHeight,
  56669. triggerMenuItemAutomaticallyWhenClicked));
  56670. }
  56671. void PopupMenu::addSubMenu (const String& subMenuName,
  56672. const PopupMenu& subMenu,
  56673. const bool isActive,
  56674. const Image& iconToUse,
  56675. const bool isTicked)
  56676. {
  56677. addSeparatorIfPending();
  56678. items.add (new Item (0, subMenuName, isActive && (subMenu.getNumItems() > 0), isTicked,
  56679. iconToUse, Colours::black, false, 0, &subMenu, 0));
  56680. }
  56681. void PopupMenu::addSeparator()
  56682. {
  56683. separatorPending = true;
  56684. }
  56685. class HeaderItemComponent : public PopupMenuCustomComponent
  56686. {
  56687. public:
  56688. HeaderItemComponent (const String& name)
  56689. : PopupMenuCustomComponent (false)
  56690. {
  56691. setName (name);
  56692. }
  56693. ~HeaderItemComponent()
  56694. {
  56695. }
  56696. void paint (Graphics& g)
  56697. {
  56698. Font f (getLookAndFeel().getPopupMenuFont());
  56699. f.setBold (true);
  56700. g.setFont (f);
  56701. g.setColour (findColour (PopupMenu::headerTextColourId));
  56702. g.drawFittedText (getName(),
  56703. 12, 0, getWidth() - 16, proportionOfHeight (0.8f),
  56704. Justification::bottomLeft, 1);
  56705. }
  56706. void getIdealSize (int& idealWidth,
  56707. int& idealHeight)
  56708. {
  56709. getLookAndFeel().getIdealPopupMenuItemSize (getName(), false, -1, idealWidth, idealHeight);
  56710. idealHeight += idealHeight / 2;
  56711. idealWidth += idealWidth / 4;
  56712. }
  56713. juce_UseDebuggingNewOperator
  56714. };
  56715. void PopupMenu::addSectionHeader (const String& title)
  56716. {
  56717. addCustomItem (0X4734a34f, new HeaderItemComponent (title));
  56718. }
  56719. // This invokes any command manager commands and deletes the menu window when it is dismissed
  56720. class PopupMenuCompletionCallback : public ModalComponentManager::Callback
  56721. {
  56722. public:
  56723. PopupMenuCompletionCallback()
  56724. : managerOfChosenCommand (0)
  56725. {
  56726. }
  56727. ~PopupMenuCompletionCallback() {}
  56728. void modalStateFinished (int result)
  56729. {
  56730. if (managerOfChosenCommand != 0 && result != 0)
  56731. {
  56732. ApplicationCommandTarget::InvocationInfo info (result);
  56733. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  56734. managerOfChosenCommand->invoke (info, true);
  56735. }
  56736. // (this would be the place to fade out the component, if that's what's required)
  56737. component = 0;
  56738. }
  56739. ApplicationCommandManager* managerOfChosenCommand;
  56740. ScopedPointer<Component> component;
  56741. private:
  56742. PopupMenuCompletionCallback (const PopupMenuCompletionCallback&);
  56743. PopupMenuCompletionCallback& operator= (const PopupMenuCompletionCallback&);
  56744. };
  56745. int PopupMenu::showMenu (const Rectangle<int>& target,
  56746. const int itemIdThatMustBeVisible,
  56747. const int minimumWidth,
  56748. const int maximumNumColumns,
  56749. const int standardItemHeight,
  56750. const bool alignToRectangle,
  56751. Component* const componentAttachedTo,
  56752. ModalComponentManager::Callback* userCallback)
  56753. {
  56754. ScopedPointer<ModalComponentManager::Callback> userCallbackDeleter (userCallback);
  56755. Component::SafePointer<Component> prevFocused (Component::getCurrentlyFocusedComponent());
  56756. Component::SafePointer<Component> prevTopLevel ((prevFocused != 0) ? prevFocused->getTopLevelComponent() : 0);
  56757. Window::wasHiddenBecauseOfAppChange() = false;
  56758. PopupMenuCompletionCallback* callback = new PopupMenuCompletionCallback();
  56759. ScopedPointer<PopupMenuCompletionCallback> callbackDeleter (callback);
  56760. callback->component = Window::create (*this, ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown(),
  56761. 0, target, minimumWidth, maximumNumColumns > 0 ? maximumNumColumns : 7,
  56762. standardItemHeight, alignToRectangle, itemIdThatMustBeVisible,
  56763. &callback->managerOfChosenCommand, componentAttachedTo);
  56764. if (callback->component == 0)
  56765. return 0;
  56766. callback->component->enterModalState (false, userCallbackDeleter.release());
  56767. callback->component->toFront (false); // need to do this after making it modal, or it could
  56768. // be stuck behind other comps that are already modal..
  56769. ModalComponentManager::getInstance()->attachCallback (callback->component, callback);
  56770. callbackDeleter.release();
  56771. if (userCallback != 0)
  56772. return 0;
  56773. const int result = callback->component->runModalLoop();
  56774. if (! Window::wasHiddenBecauseOfAppChange())
  56775. {
  56776. if (prevTopLevel != 0)
  56777. prevTopLevel->toFront (true);
  56778. if (prevFocused != 0)
  56779. prevFocused->grabKeyboardFocus();
  56780. }
  56781. return result;
  56782. }
  56783. int PopupMenu::show (const int itemIdThatMustBeVisible,
  56784. const int minimumWidth,
  56785. const int maximumNumColumns,
  56786. const int standardItemHeight,
  56787. ModalComponentManager::Callback* callback)
  56788. {
  56789. const Point<int> mousePos (Desktop::getMousePosition());
  56790. return showAt (mousePos.getX(), mousePos.getY(),
  56791. itemIdThatMustBeVisible,
  56792. minimumWidth,
  56793. maximumNumColumns,
  56794. standardItemHeight,
  56795. callback);
  56796. }
  56797. int PopupMenu::showAt (const int screenX,
  56798. const int screenY,
  56799. const int itemIdThatMustBeVisible,
  56800. const int minimumWidth,
  56801. const int maximumNumColumns,
  56802. const int standardItemHeight,
  56803. ModalComponentManager::Callback* callback)
  56804. {
  56805. return showMenu (Rectangle<int> (screenX, screenY, 1, 1),
  56806. itemIdThatMustBeVisible,
  56807. minimumWidth, maximumNumColumns,
  56808. standardItemHeight,
  56809. false, 0, callback);
  56810. }
  56811. int PopupMenu::showAt (Component* componentToAttachTo,
  56812. const int itemIdThatMustBeVisible,
  56813. const int minimumWidth,
  56814. const int maximumNumColumns,
  56815. const int standardItemHeight,
  56816. ModalComponentManager::Callback* callback)
  56817. {
  56818. if (componentToAttachTo != 0)
  56819. {
  56820. return showMenu (componentToAttachTo->getScreenBounds(),
  56821. itemIdThatMustBeVisible,
  56822. minimumWidth,
  56823. maximumNumColumns,
  56824. standardItemHeight,
  56825. true, componentToAttachTo, callback);
  56826. }
  56827. else
  56828. {
  56829. return show (itemIdThatMustBeVisible,
  56830. minimumWidth,
  56831. maximumNumColumns,
  56832. standardItemHeight,
  56833. callback);
  56834. }
  56835. }
  56836. void JUCE_CALLTYPE PopupMenu::dismissAllActiveMenus()
  56837. {
  56838. for (int i = Window::getActiveWindows().size(); --i >= 0;)
  56839. {
  56840. Window* const pmw = Window::getActiveWindows()[i];
  56841. if (pmw != 0)
  56842. pmw->dismissMenu (0);
  56843. }
  56844. }
  56845. int PopupMenu::getNumItems() const throw()
  56846. {
  56847. int num = 0;
  56848. for (int i = items.size(); --i >= 0;)
  56849. if (! (items.getUnchecked(i))->isSeparator)
  56850. ++num;
  56851. return num;
  56852. }
  56853. bool PopupMenu::containsCommandItem (const int commandID) const
  56854. {
  56855. for (int i = items.size(); --i >= 0;)
  56856. {
  56857. const Item* mi = items.getUnchecked (i);
  56858. if ((mi->itemId == commandID && mi->commandManager != 0)
  56859. || (mi->subMenu != 0 && mi->subMenu->containsCommandItem (commandID)))
  56860. {
  56861. return true;
  56862. }
  56863. }
  56864. return false;
  56865. }
  56866. bool PopupMenu::containsAnyActiveItems() const throw()
  56867. {
  56868. for (int i = items.size(); --i >= 0;)
  56869. {
  56870. const Item* const mi = items.getUnchecked (i);
  56871. if (mi->subMenu != 0)
  56872. {
  56873. if (mi->subMenu->containsAnyActiveItems())
  56874. return true;
  56875. }
  56876. else if (mi->active)
  56877. {
  56878. return true;
  56879. }
  56880. }
  56881. return false;
  56882. }
  56883. void PopupMenu::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  56884. {
  56885. lookAndFeel = newLookAndFeel;
  56886. }
  56887. PopupMenuCustomComponent::PopupMenuCustomComponent (const bool isTriggeredAutomatically_)
  56888. : isHighlighted (false),
  56889. isTriggeredAutomatically (isTriggeredAutomatically_)
  56890. {
  56891. }
  56892. PopupMenuCustomComponent::~PopupMenuCustomComponent()
  56893. {
  56894. }
  56895. void PopupMenuCustomComponent::triggerMenuItem()
  56896. {
  56897. PopupMenu::ItemComponent* const mic = dynamic_cast <PopupMenu::ItemComponent*> (getParentComponent());
  56898. if (mic != 0)
  56899. {
  56900. PopupMenu::Window* const pmw = dynamic_cast <PopupMenu::Window*> (mic->getParentComponent());
  56901. if (pmw != 0)
  56902. {
  56903. pmw->dismissMenu (&mic->itemInfo);
  56904. }
  56905. else
  56906. {
  56907. // something must have gone wrong with the component hierarchy if this happens..
  56908. jassertfalse;
  56909. }
  56910. }
  56911. else
  56912. {
  56913. // why isn't this component inside a menu? Not much point triggering the item if
  56914. // there's no menu.
  56915. jassertfalse;
  56916. }
  56917. }
  56918. PopupMenu::MenuItemIterator::MenuItemIterator (const PopupMenu& menu_)
  56919. : subMenu (0),
  56920. itemId (0),
  56921. isSeparator (false),
  56922. isTicked (false),
  56923. isEnabled (false),
  56924. isCustomComponent (false),
  56925. isSectionHeader (false),
  56926. customColour (0),
  56927. customImage (0),
  56928. menu (menu_),
  56929. index (0)
  56930. {
  56931. }
  56932. PopupMenu::MenuItemIterator::~MenuItemIterator()
  56933. {
  56934. }
  56935. bool PopupMenu::MenuItemIterator::next()
  56936. {
  56937. if (index >= menu.items.size())
  56938. return false;
  56939. const Item* const item = menu.items.getUnchecked (index);
  56940. ++index;
  56941. itemName = item->customComp != 0 ? item->customComp->getName() : item->text;
  56942. subMenu = item->subMenu;
  56943. itemId = item->itemId;
  56944. isSeparator = item->isSeparator;
  56945. isTicked = item->isTicked;
  56946. isEnabled = item->active;
  56947. isSectionHeader = dynamic_cast <HeaderItemComponent*> ((PopupMenuCustomComponent*) item->customComp) != 0;
  56948. isCustomComponent = (! isSectionHeader) && item->customComp != 0;
  56949. customColour = item->usesColour ? &(item->textColour) : 0;
  56950. customImage = item->image;
  56951. commandManager = item->commandManager;
  56952. return true;
  56953. }
  56954. END_JUCE_NAMESPACE
  56955. /*** End of inlined file: juce_PopupMenu.cpp ***/
  56956. /*** Start of inlined file: juce_ComponentDragger.cpp ***/
  56957. BEGIN_JUCE_NAMESPACE
  56958. ComponentDragger::ComponentDragger()
  56959. : constrainer (0)
  56960. {
  56961. }
  56962. ComponentDragger::~ComponentDragger()
  56963. {
  56964. }
  56965. void ComponentDragger::startDraggingComponent (Component* const componentToDrag,
  56966. ComponentBoundsConstrainer* const constrainer_)
  56967. {
  56968. jassert (componentToDrag->isValidComponent());
  56969. if (componentToDrag != 0)
  56970. {
  56971. constrainer = constrainer_;
  56972. originalPos = componentToDrag->relativePositionToGlobal (Point<int>());
  56973. }
  56974. }
  56975. void ComponentDragger::dragComponent (Component* const componentToDrag, const MouseEvent& e)
  56976. {
  56977. jassert (componentToDrag->isValidComponent());
  56978. jassert (e.mods.isAnyMouseButtonDown()); // (the event has to be a drag event..)
  56979. if (componentToDrag != 0)
  56980. {
  56981. Rectangle<int> bounds (componentToDrag->getBounds().withPosition (originalPos));
  56982. const Component* const parentComp = componentToDrag->getParentComponent();
  56983. if (parentComp != 0)
  56984. bounds.setPosition (parentComp->globalPositionToRelative (originalPos));
  56985. bounds.setPosition (bounds.getPosition() + e.getOffsetFromDragStart());
  56986. if (constrainer != 0)
  56987. constrainer->setBoundsForComponent (componentToDrag, bounds, false, false, false, false);
  56988. else
  56989. componentToDrag->setBounds (bounds);
  56990. }
  56991. }
  56992. END_JUCE_NAMESPACE
  56993. /*** End of inlined file: juce_ComponentDragger.cpp ***/
  56994. /*** Start of inlined file: juce_DragAndDropContainer.cpp ***/
  56995. BEGIN_JUCE_NAMESPACE
  56996. bool juce_performDragDropFiles (const StringArray& files, const bool copyFiles, bool& shouldStop);
  56997. bool juce_performDragDropText (const String& text, bool& shouldStop);
  56998. class DragImageComponent : public Component,
  56999. public Timer
  57000. {
  57001. public:
  57002. DragImageComponent (const Image& im,
  57003. const String& desc,
  57004. Component* const sourceComponent,
  57005. Component* const mouseDragSource_,
  57006. DragAndDropContainer* const o,
  57007. const Point<int>& imageOffset_)
  57008. : image (im),
  57009. source (sourceComponent),
  57010. mouseDragSource (mouseDragSource_),
  57011. owner (o),
  57012. dragDesc (desc),
  57013. imageOffset (imageOffset_),
  57014. hasCheckedForExternalDrag (false),
  57015. drawImage (true)
  57016. {
  57017. setSize (im.getWidth(), im.getHeight());
  57018. if (mouseDragSource == 0)
  57019. mouseDragSource = source;
  57020. mouseDragSource->addMouseListener (this, false);
  57021. startTimer (200);
  57022. setInterceptsMouseClicks (false, false);
  57023. setAlwaysOnTop (true);
  57024. }
  57025. ~DragImageComponent()
  57026. {
  57027. if (owner->dragImageComponent == this)
  57028. owner->dragImageComponent.release();
  57029. if (mouseDragSource != 0)
  57030. {
  57031. mouseDragSource->removeMouseListener (this);
  57032. if (getCurrentlyOver() != 0 && getCurrentlyOver()->isInterestedInDragSource (dragDesc, source))
  57033. getCurrentlyOver()->itemDragExit (dragDesc, source);
  57034. }
  57035. }
  57036. void paint (Graphics& g)
  57037. {
  57038. if (isOpaque())
  57039. g.fillAll (Colours::white);
  57040. if (drawImage)
  57041. {
  57042. g.setOpacity (1.0f);
  57043. g.drawImageAt (image, 0, 0);
  57044. }
  57045. }
  57046. DragAndDropTarget* findTarget (const Point<int>& screenPos, Point<int>& relativePos)
  57047. {
  57048. Component* hit = getParentComponent();
  57049. if (hit == 0)
  57050. {
  57051. hit = Desktop::getInstance().findComponentAt (screenPos);
  57052. }
  57053. else
  57054. {
  57055. const Point<int> relPos (hit->globalPositionToRelative (screenPos));
  57056. hit = hit->getComponentAt (relPos.getX(), relPos.getY());
  57057. }
  57058. // (note: use a local copy of the dragDesc member in case the callback runs
  57059. // a modal loop and deletes this object before the method completes)
  57060. const String dragDescLocal (dragDesc);
  57061. while (hit != 0)
  57062. {
  57063. DragAndDropTarget* const ddt = dynamic_cast <DragAndDropTarget*> (hit);
  57064. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  57065. {
  57066. relativePos = hit->globalPositionToRelative (screenPos);
  57067. return ddt;
  57068. }
  57069. hit = hit->getParentComponent();
  57070. }
  57071. return 0;
  57072. }
  57073. void mouseUp (const MouseEvent& e)
  57074. {
  57075. if (e.originalComponent != this)
  57076. {
  57077. if (mouseDragSource != 0)
  57078. mouseDragSource->removeMouseListener (this);
  57079. bool dropAccepted = false;
  57080. DragAndDropTarget* ddt = 0;
  57081. Point<int> relPos;
  57082. if (isVisible())
  57083. {
  57084. setVisible (false);
  57085. ddt = findTarget (e.getScreenPosition(), relPos);
  57086. // fade this component and remove it - it'll be deleted later by the timer callback
  57087. dropAccepted = ddt != 0;
  57088. setVisible (true);
  57089. if (dropAccepted || source == 0)
  57090. {
  57091. Desktop::getInstance().getAnimator().fadeOut (this, 120);
  57092. }
  57093. else
  57094. {
  57095. const Point<int> target (source->relativePositionToGlobal (source->getLocalBounds().getCentre()));
  57096. const Point<int> ourCentre (relativePositionToGlobal (getLocalBounds().getCentre()));
  57097. Desktop::getInstance().getAnimator().animateComponent (this,
  57098. getBounds() + (target - ourCentre),
  57099. 0.0f, 120,
  57100. true, 1.0, 1.0);
  57101. }
  57102. }
  57103. if (getParentComponent() != 0)
  57104. getParentComponent()->removeChildComponent (this);
  57105. if (dropAccepted && ddt != 0)
  57106. {
  57107. // (note: use a local copy of the dragDesc member in case the callback runs
  57108. // a modal loop and deletes this object before the method completes)
  57109. const String dragDescLocal (dragDesc);
  57110. currentlyOverComp = 0;
  57111. ddt->itemDropped (dragDescLocal, source, relPos.getX(), relPos.getY());
  57112. }
  57113. // careful - this object could now be deleted..
  57114. }
  57115. }
  57116. void updateLocation (const bool canDoExternalDrag, const Point<int>& screenPos)
  57117. {
  57118. // (note: use a local copy of the dragDesc member in case the callback runs
  57119. // a modal loop and deletes this object before it returns)
  57120. const String dragDescLocal (dragDesc);
  57121. Point<int> newPos (screenPos + imageOffset);
  57122. if (getParentComponent() != 0)
  57123. newPos = getParentComponent()->globalPositionToRelative (newPos);
  57124. //if (newX != getX() || newY != getY())
  57125. {
  57126. setTopLeftPosition (newPos.getX(), newPos.getY());
  57127. Point<int> relPos;
  57128. DragAndDropTarget* const ddt = findTarget (screenPos, relPos);
  57129. Component* ddtComp = dynamic_cast <Component*> (ddt);
  57130. drawImage = (ddt == 0) || ddt->shouldDrawDragImageWhenOver();
  57131. if (ddtComp != currentlyOverComp)
  57132. {
  57133. if (currentlyOverComp != 0 && source != 0
  57134. && getCurrentlyOver()->isInterestedInDragSource (dragDescLocal, source))
  57135. {
  57136. getCurrentlyOver()->itemDragExit (dragDescLocal, source);
  57137. }
  57138. currentlyOverComp = ddtComp;
  57139. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  57140. ddt->itemDragEnter (dragDescLocal, source, relPos.getX(), relPos.getY());
  57141. }
  57142. DragAndDropTarget* target = getCurrentlyOver();
  57143. if (target != 0 && target->isInterestedInDragSource (dragDescLocal, source))
  57144. target->itemDragMove (dragDescLocal, source, relPos.getX(), relPos.getY());
  57145. if (getCurrentlyOver() == 0 && canDoExternalDrag && ! hasCheckedForExternalDrag)
  57146. {
  57147. if (Desktop::getInstance().findComponentAt (screenPos) == 0)
  57148. {
  57149. hasCheckedForExternalDrag = true;
  57150. StringArray files;
  57151. bool canMoveFiles = false;
  57152. if (owner->shouldDropFilesWhenDraggedExternally (dragDescLocal, source, files, canMoveFiles)
  57153. && files.size() > 0)
  57154. {
  57155. Component::SafePointer<Component> cdw (this);
  57156. setVisible (false);
  57157. if (ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown())
  57158. DragAndDropContainer::performExternalDragDropOfFiles (files, canMoveFiles);
  57159. if (cdw != 0)
  57160. delete this;
  57161. return;
  57162. }
  57163. }
  57164. }
  57165. }
  57166. }
  57167. void mouseDrag (const MouseEvent& e)
  57168. {
  57169. if (e.originalComponent != this)
  57170. updateLocation (true, e.getScreenPosition());
  57171. }
  57172. void timerCallback()
  57173. {
  57174. if (source == 0)
  57175. {
  57176. delete this;
  57177. }
  57178. else if (! isMouseButtonDownAnywhere())
  57179. {
  57180. if (mouseDragSource != 0)
  57181. mouseDragSource->removeMouseListener (this);
  57182. delete this;
  57183. }
  57184. }
  57185. private:
  57186. Image image;
  57187. Component::SafePointer<Component> source;
  57188. Component::SafePointer<Component> mouseDragSource;
  57189. DragAndDropContainer* const owner;
  57190. Component::SafePointer<Component> currentlyOverComp;
  57191. DragAndDropTarget* getCurrentlyOver()
  57192. {
  57193. return dynamic_cast <DragAndDropTarget*> (static_cast <Component*> (currentlyOverComp));
  57194. }
  57195. String dragDesc;
  57196. const Point<int> imageOffset;
  57197. bool hasCheckedForExternalDrag, drawImage;
  57198. DragImageComponent (const DragImageComponent&);
  57199. DragImageComponent& operator= (const DragImageComponent&);
  57200. };
  57201. DragAndDropContainer::DragAndDropContainer()
  57202. {
  57203. }
  57204. DragAndDropContainer::~DragAndDropContainer()
  57205. {
  57206. dragImageComponent = 0;
  57207. }
  57208. void DragAndDropContainer::startDragging (const String& sourceDescription,
  57209. Component* sourceComponent,
  57210. const Image& dragImage_,
  57211. const bool allowDraggingToExternalWindows,
  57212. const Point<int>* imageOffsetFromMouse)
  57213. {
  57214. Image dragImage (dragImage_);
  57215. if (dragImageComponent == 0)
  57216. {
  57217. Component* const thisComp = dynamic_cast <Component*> (this);
  57218. if (thisComp == 0)
  57219. {
  57220. jassertfalse; // Your DragAndDropContainer needs to be a Component!
  57221. return;
  57222. }
  57223. MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource (0);
  57224. if (draggingSource == 0 || ! draggingSource->isDragging())
  57225. {
  57226. jassertfalse; // You must call startDragging() from within a mouseDown or mouseDrag callback!
  57227. return;
  57228. }
  57229. const Point<int> lastMouseDown (Desktop::getLastMouseDownPosition());
  57230. Point<int> imageOffset;
  57231. if (dragImage.isNull())
  57232. {
  57233. dragImage = sourceComponent->createComponentSnapshot (sourceComponent->getLocalBounds())
  57234. .convertedToFormat (Image::ARGB);
  57235. dragImage.multiplyAllAlphas (0.6f);
  57236. const int lo = 150;
  57237. const int hi = 400;
  57238. Point<int> relPos (sourceComponent->globalPositionToRelative (lastMouseDown));
  57239. Point<int> clipped (dragImage.getBounds().getConstrainedPoint (relPos));
  57240. for (int y = dragImage.getHeight(); --y >= 0;)
  57241. {
  57242. const double dy = (y - clipped.getY()) * (y - clipped.getY());
  57243. for (int x = dragImage.getWidth(); --x >= 0;)
  57244. {
  57245. const int dx = x - clipped.getX();
  57246. const int distance = roundToInt (std::sqrt (dx * dx + dy));
  57247. if (distance > lo)
  57248. {
  57249. const float alpha = (distance > hi) ? 0
  57250. : (hi - distance) / (float) (hi - lo)
  57251. + Random::getSystemRandom().nextFloat() * 0.008f;
  57252. dragImage.multiplyAlphaAt (x, y, alpha);
  57253. }
  57254. }
  57255. }
  57256. imageOffset = -clipped;
  57257. }
  57258. else
  57259. {
  57260. if (imageOffsetFromMouse == 0)
  57261. imageOffset = -dragImage.getBounds().getCentre();
  57262. else
  57263. imageOffset = -(dragImage.getBounds().getConstrainedPoint (-*imageOffsetFromMouse));
  57264. }
  57265. dragImageComponent = new DragImageComponent (dragImage, sourceDescription, sourceComponent,
  57266. draggingSource->getComponentUnderMouse(), this, imageOffset);
  57267. currentDragDesc = sourceDescription;
  57268. if (allowDraggingToExternalWindows)
  57269. {
  57270. if (! Desktop::canUseSemiTransparentWindows())
  57271. dragImageComponent->setOpaque (true);
  57272. dragImageComponent->addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  57273. | ComponentPeer::windowIsTemporary
  57274. | ComponentPeer::windowIgnoresKeyPresses);
  57275. }
  57276. else
  57277. thisComp->addChildComponent (dragImageComponent);
  57278. static_cast <DragImageComponent*> (static_cast <Component*> (dragImageComponent))->updateLocation (false, lastMouseDown);
  57279. dragImageComponent->setVisible (true);
  57280. }
  57281. }
  57282. bool DragAndDropContainer::isDragAndDropActive() const
  57283. {
  57284. return dragImageComponent != 0;
  57285. }
  57286. const String DragAndDropContainer::getCurrentDragDescription() const
  57287. {
  57288. return (dragImageComponent != 0) ? currentDragDesc
  57289. : String::empty;
  57290. }
  57291. DragAndDropContainer* DragAndDropContainer::findParentDragContainerFor (Component* c)
  57292. {
  57293. return c == 0 ? 0 : c->findParentComponentOfClass ((DragAndDropContainer*) 0);
  57294. }
  57295. bool DragAndDropContainer::shouldDropFilesWhenDraggedExternally (const String&, Component*, StringArray&, bool&)
  57296. {
  57297. return false;
  57298. }
  57299. void DragAndDropTarget::itemDragEnter (const String&, Component*, int, int)
  57300. {
  57301. }
  57302. void DragAndDropTarget::itemDragMove (const String&, Component*, int, int)
  57303. {
  57304. }
  57305. void DragAndDropTarget::itemDragExit (const String&, Component*)
  57306. {
  57307. }
  57308. bool DragAndDropTarget::shouldDrawDragImageWhenOver()
  57309. {
  57310. return true;
  57311. }
  57312. void FileDragAndDropTarget::fileDragEnter (const StringArray&, int, int)
  57313. {
  57314. }
  57315. void FileDragAndDropTarget::fileDragMove (const StringArray&, int, int)
  57316. {
  57317. }
  57318. void FileDragAndDropTarget::fileDragExit (const StringArray&)
  57319. {
  57320. }
  57321. END_JUCE_NAMESPACE
  57322. /*** End of inlined file: juce_DragAndDropContainer.cpp ***/
  57323. /*** Start of inlined file: juce_MouseCursor.cpp ***/
  57324. BEGIN_JUCE_NAMESPACE
  57325. class MouseCursor::SharedCursorHandle
  57326. {
  57327. public:
  57328. explicit SharedCursorHandle (const MouseCursor::StandardCursorType type)
  57329. : handle (createStandardMouseCursor (type)),
  57330. refCount (1),
  57331. standardType (type),
  57332. isStandard (true)
  57333. {
  57334. }
  57335. SharedCursorHandle (const Image& image, const int hotSpotX, const int hotSpotY)
  57336. : handle (createMouseCursorFromImage (image, hotSpotX, hotSpotY)),
  57337. refCount (1),
  57338. standardType (MouseCursor::NormalCursor),
  57339. isStandard (false)
  57340. {
  57341. }
  57342. static SharedCursorHandle* createStandard (const MouseCursor::StandardCursorType type)
  57343. {
  57344. const ScopedLock sl (getLock());
  57345. for (int i = 0; i < getCursors().size(); ++i)
  57346. {
  57347. SharedCursorHandle* const sc = getCursors().getUnchecked(i);
  57348. if (sc->standardType == type)
  57349. return sc->retain();
  57350. }
  57351. SharedCursorHandle* const sc = new SharedCursorHandle (type);
  57352. getCursors().add (sc);
  57353. return sc;
  57354. }
  57355. SharedCursorHandle* retain() throw()
  57356. {
  57357. ++refCount;
  57358. return this;
  57359. }
  57360. void release()
  57361. {
  57362. if (--refCount == 0)
  57363. {
  57364. if (isStandard)
  57365. {
  57366. const ScopedLock sl (getLock());
  57367. getCursors().removeValue (this);
  57368. }
  57369. delete this;
  57370. }
  57371. }
  57372. void* getHandle() const throw() { return handle; }
  57373. juce_UseDebuggingNewOperator
  57374. private:
  57375. void* const handle;
  57376. Atomic <int> refCount;
  57377. const MouseCursor::StandardCursorType standardType;
  57378. const bool isStandard;
  57379. static CriticalSection& getLock()
  57380. {
  57381. static CriticalSection lock;
  57382. return lock;
  57383. }
  57384. static Array <SharedCursorHandle*>& getCursors()
  57385. {
  57386. static Array <SharedCursorHandle*> cursors;
  57387. return cursors;
  57388. }
  57389. ~SharedCursorHandle()
  57390. {
  57391. deleteMouseCursor (handle, isStandard);
  57392. }
  57393. SharedCursorHandle& operator= (const SharedCursorHandle&);
  57394. };
  57395. MouseCursor::MouseCursor()
  57396. : cursorHandle (0)
  57397. {
  57398. }
  57399. MouseCursor::MouseCursor (const StandardCursorType type)
  57400. : cursorHandle (type != MouseCursor::NormalCursor ? SharedCursorHandle::createStandard (type) : 0)
  57401. {
  57402. }
  57403. MouseCursor::MouseCursor (const Image& image, const int hotSpotX, const int hotSpotY)
  57404. : cursorHandle (new SharedCursorHandle (image, hotSpotX, hotSpotY))
  57405. {
  57406. }
  57407. MouseCursor::MouseCursor (const MouseCursor& other)
  57408. : cursorHandle (other.cursorHandle == 0 ? 0 : other.cursorHandle->retain())
  57409. {
  57410. }
  57411. MouseCursor::~MouseCursor()
  57412. {
  57413. if (cursorHandle != 0)
  57414. cursorHandle->release();
  57415. }
  57416. MouseCursor& MouseCursor::operator= (const MouseCursor& other)
  57417. {
  57418. if (other.cursorHandle != 0)
  57419. other.cursorHandle->retain();
  57420. if (cursorHandle != 0)
  57421. cursorHandle->release();
  57422. cursorHandle = other.cursorHandle;
  57423. return *this;
  57424. }
  57425. bool MouseCursor::operator== (const MouseCursor& other) const throw()
  57426. {
  57427. return getHandle() == other.getHandle();
  57428. }
  57429. bool MouseCursor::operator!= (const MouseCursor& other) const throw()
  57430. {
  57431. return getHandle() != other.getHandle();
  57432. }
  57433. void* MouseCursor::getHandle() const throw()
  57434. {
  57435. return cursorHandle != 0 ? cursorHandle->getHandle() : 0;
  57436. }
  57437. void MouseCursor::showWaitCursor()
  57438. {
  57439. Desktop::getInstance().getMainMouseSource().showMouseCursor (MouseCursor::WaitCursor);
  57440. }
  57441. void MouseCursor::hideWaitCursor()
  57442. {
  57443. Desktop::getInstance().getMainMouseSource().revealCursor();
  57444. }
  57445. END_JUCE_NAMESPACE
  57446. /*** End of inlined file: juce_MouseCursor.cpp ***/
  57447. /*** Start of inlined file: juce_MouseEvent.cpp ***/
  57448. BEGIN_JUCE_NAMESPACE
  57449. MouseEvent::MouseEvent (MouseInputSource& source_,
  57450. const Point<int>& position,
  57451. const ModifierKeys& mods_,
  57452. Component* const eventComponent_,
  57453. Component* const originator,
  57454. const Time& eventTime_,
  57455. const Point<int> mouseDownPos_,
  57456. const Time& mouseDownTime_,
  57457. const int numberOfClicks_,
  57458. const bool mouseWasDragged) throw()
  57459. : x (position.getX()),
  57460. y (position.getY()),
  57461. mods (mods_),
  57462. eventComponent (eventComponent_),
  57463. originalComponent (originator),
  57464. eventTime (eventTime_),
  57465. source (source_),
  57466. mouseDownPos (mouseDownPos_),
  57467. mouseDownTime (mouseDownTime_),
  57468. numberOfClicks (numberOfClicks_),
  57469. wasMovedSinceMouseDown (mouseWasDragged)
  57470. {
  57471. }
  57472. MouseEvent::~MouseEvent() throw()
  57473. {
  57474. }
  57475. const MouseEvent MouseEvent::getEventRelativeTo (Component* const otherComponent) const throw()
  57476. {
  57477. if (otherComponent == 0)
  57478. {
  57479. jassertfalse;
  57480. return *this;
  57481. }
  57482. return MouseEvent (source, eventComponent->relativePositionToOtherComponent (otherComponent, getPosition()),
  57483. mods, otherComponent, originalComponent, eventTime,
  57484. eventComponent->relativePositionToOtherComponent (otherComponent, mouseDownPos),
  57485. mouseDownTime, numberOfClicks, wasMovedSinceMouseDown);
  57486. }
  57487. const MouseEvent MouseEvent::withNewPosition (const Point<int>& newPosition) const throw()
  57488. {
  57489. return MouseEvent (source, newPosition, mods, eventComponent, originalComponent,
  57490. eventTime, mouseDownPos, mouseDownTime,
  57491. numberOfClicks, wasMovedSinceMouseDown);
  57492. }
  57493. bool MouseEvent::mouseWasClicked() const throw()
  57494. {
  57495. return ! wasMovedSinceMouseDown;
  57496. }
  57497. int MouseEvent::getMouseDownX() const throw()
  57498. {
  57499. return mouseDownPos.getX();
  57500. }
  57501. int MouseEvent::getMouseDownY() const throw()
  57502. {
  57503. return mouseDownPos.getY();
  57504. }
  57505. const Point<int> MouseEvent::getMouseDownPosition() const throw()
  57506. {
  57507. return mouseDownPos;
  57508. }
  57509. int MouseEvent::getDistanceFromDragStartX() const throw()
  57510. {
  57511. return x - mouseDownPos.getX();
  57512. }
  57513. int MouseEvent::getDistanceFromDragStartY() const throw()
  57514. {
  57515. return y - mouseDownPos.getY();
  57516. }
  57517. int MouseEvent::getDistanceFromDragStart() const throw()
  57518. {
  57519. return mouseDownPos.getDistanceFrom (getPosition());
  57520. }
  57521. const Point<int> MouseEvent::getOffsetFromDragStart() const throw()
  57522. {
  57523. return getPosition() - mouseDownPos;
  57524. }
  57525. int MouseEvent::getLengthOfMousePress() const throw()
  57526. {
  57527. if (mouseDownTime.toMilliseconds() > 0)
  57528. return jmax (0, (int) (eventTime - mouseDownTime).inMilliseconds());
  57529. return 0;
  57530. }
  57531. const Point<int> MouseEvent::getPosition() const throw()
  57532. {
  57533. return Point<int> (x, y);
  57534. }
  57535. int MouseEvent::getScreenX() const
  57536. {
  57537. return getScreenPosition().getX();
  57538. }
  57539. int MouseEvent::getScreenY() const
  57540. {
  57541. return getScreenPosition().getY();
  57542. }
  57543. const Point<int> MouseEvent::getScreenPosition() const
  57544. {
  57545. return eventComponent->relativePositionToGlobal (Point<int> (x, y));
  57546. }
  57547. int MouseEvent::getMouseDownScreenX() const
  57548. {
  57549. return getMouseDownScreenPosition().getX();
  57550. }
  57551. int MouseEvent::getMouseDownScreenY() const
  57552. {
  57553. return getMouseDownScreenPosition().getY();
  57554. }
  57555. const Point<int> MouseEvent::getMouseDownScreenPosition() const
  57556. {
  57557. return eventComponent->relativePositionToGlobal (mouseDownPos);
  57558. }
  57559. int MouseEvent::doubleClickTimeOutMs = 400;
  57560. void MouseEvent::setDoubleClickTimeout (const int newTime) throw()
  57561. {
  57562. doubleClickTimeOutMs = newTime;
  57563. }
  57564. int MouseEvent::getDoubleClickTimeout() throw()
  57565. {
  57566. return doubleClickTimeOutMs;
  57567. }
  57568. END_JUCE_NAMESPACE
  57569. /*** End of inlined file: juce_MouseEvent.cpp ***/
  57570. /*** Start of inlined file: juce_MouseInputSource.cpp ***/
  57571. BEGIN_JUCE_NAMESPACE
  57572. class MouseInputSourceInternal : public AsyncUpdater
  57573. {
  57574. public:
  57575. MouseInputSourceInternal (MouseInputSource& source_, const int index_, const bool isMouseDevice_)
  57576. : index (index_), isMouseDevice (isMouseDevice_), source (source_), lastPeer (0),
  57577. isUnboundedMouseModeOn (false), isCursorVisibleUntilOffscreen (false), currentCursorHandle (0),
  57578. mouseEventCounter (0), lastTime (0)
  57579. {
  57580. zerostruct (mouseDowns);
  57581. }
  57582. ~MouseInputSourceInternal()
  57583. {
  57584. }
  57585. bool isDragging() const throw()
  57586. {
  57587. return buttonState.isAnyMouseButtonDown();
  57588. }
  57589. Component* getComponentUnderMouse() const
  57590. {
  57591. return static_cast <Component*> (componentUnderMouse);
  57592. }
  57593. const ModifierKeys getCurrentModifiers() const
  57594. {
  57595. return ModifierKeys::getCurrentModifiers().withoutMouseButtons().withFlags (buttonState.getRawFlags());
  57596. }
  57597. ComponentPeer* getPeer()
  57598. {
  57599. if (! ComponentPeer::isValidPeer (lastPeer))
  57600. lastPeer = 0;
  57601. return lastPeer;
  57602. }
  57603. Component* findComponentAt (const Point<int>& screenPos)
  57604. {
  57605. ComponentPeer* const peer = getPeer();
  57606. if (peer != 0)
  57607. {
  57608. Component* const comp = peer->getComponent();
  57609. const Point<int> relativePos (comp->globalPositionToRelative (screenPos));
  57610. // (the contains() call is needed to test for overlapping desktop windows)
  57611. if (comp->contains (relativePos.getX(), relativePos.getY()))
  57612. return comp->getComponentAt (relativePos);
  57613. }
  57614. return 0;
  57615. }
  57616. const Point<int> getScreenPosition() const throw()
  57617. {
  57618. return lastScreenPos + unboundedMouseOffset;
  57619. }
  57620. void sendMouseEnter (Component* const comp, const Point<int>& screenPos, const int64 time)
  57621. {
  57622. //DBG ("Mouse " + String (source.getIndex()) + " enter: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57623. comp->internalMouseEnter (source, comp->globalPositionToRelative (screenPos), time);
  57624. }
  57625. void sendMouseExit (Component* const comp, const Point<int>& screenPos, const int64 time)
  57626. {
  57627. //DBG ("Mouse " + String (source.getIndex()) + " exit: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57628. comp->internalMouseExit (source, comp->globalPositionToRelative (screenPos), time);
  57629. }
  57630. void sendMouseMove (Component* const comp, const Point<int>& screenPos, const int64 time)
  57631. {
  57632. //DBG ("Mouse " + String (source.getIndex()) + " move: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57633. comp->internalMouseMove (source, comp->globalPositionToRelative (screenPos), time);
  57634. }
  57635. void sendMouseDown (Component* const comp, const Point<int>& screenPos, const int64 time)
  57636. {
  57637. //DBG ("Mouse " + String (source.getIndex()) + " down: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57638. comp->internalMouseDown (source, comp->globalPositionToRelative (screenPos), time);
  57639. }
  57640. void sendMouseDrag (Component* const comp, const Point<int>& screenPos, const int64 time)
  57641. {
  57642. //DBG ("Mouse " + String (source.getIndex()) + " drag: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57643. comp->internalMouseDrag (source, comp->globalPositionToRelative (screenPos), time);
  57644. }
  57645. void sendMouseUp (Component* const comp, const Point<int>& screenPos, const int64 time)
  57646. {
  57647. //DBG ("Mouse " + String (source.getIndex()) + " up: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57648. comp->internalMouseUp (source, comp->globalPositionToRelative (screenPos), time, getCurrentModifiers());
  57649. }
  57650. void sendMouseWheel (Component* const comp, const Point<int>& screenPos, const int64 time, float x, float y)
  57651. {
  57652. //DBG ("Mouse " + String (source.getIndex()) + " wheel: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57653. comp->internalMouseWheel (source, comp->globalPositionToRelative (screenPos), time, x, y);
  57654. }
  57655. // (returns true if the button change caused a modal event loop)
  57656. bool setButtons (const Point<int>& screenPos, const int64 time, const ModifierKeys& newButtonState)
  57657. {
  57658. if (buttonState == newButtonState)
  57659. return false;
  57660. setScreenPos (screenPos, time, false);
  57661. // (ignore secondary clicks when there's already a button down)
  57662. if (buttonState.isAnyMouseButtonDown() == newButtonState.isAnyMouseButtonDown())
  57663. {
  57664. buttonState = newButtonState;
  57665. return false;
  57666. }
  57667. const int lastCounter = mouseEventCounter;
  57668. if (buttonState.isAnyMouseButtonDown())
  57669. {
  57670. Component* const current = getComponentUnderMouse();
  57671. if (current != 0)
  57672. sendMouseUp (current, screenPos + unboundedMouseOffset, time);
  57673. enableUnboundedMouseMovement (false, false);
  57674. }
  57675. buttonState = newButtonState;
  57676. if (buttonState.isAnyMouseButtonDown())
  57677. {
  57678. Desktop::getInstance().incrementMouseClickCounter();
  57679. Component* const current = getComponentUnderMouse();
  57680. if (current != 0)
  57681. {
  57682. registerMouseDown (screenPos, time, current, buttonState);
  57683. sendMouseDown (current, screenPos, time);
  57684. }
  57685. }
  57686. return lastCounter != mouseEventCounter;
  57687. }
  57688. void setComponentUnderMouse (Component* const newComponent, const Point<int>& screenPos, const int64 time)
  57689. {
  57690. Component* current = getComponentUnderMouse();
  57691. if (newComponent != current)
  57692. {
  57693. Component::SafePointer<Component> safeNewComp (newComponent);
  57694. const ModifierKeys originalButtonState (buttonState);
  57695. if (current != 0)
  57696. {
  57697. setButtons (screenPos, time, ModifierKeys());
  57698. sendMouseExit (current, screenPos, time);
  57699. buttonState = originalButtonState;
  57700. }
  57701. componentUnderMouse = safeNewComp;
  57702. current = getComponentUnderMouse();
  57703. if (current != 0)
  57704. sendMouseEnter (current, screenPos, time);
  57705. revealCursor (false);
  57706. setButtons (screenPos, time, originalButtonState);
  57707. }
  57708. }
  57709. void setPeer (ComponentPeer* const newPeer, const Point<int>& screenPos, const int64 time)
  57710. {
  57711. ModifierKeys::updateCurrentModifiers();
  57712. if (newPeer != lastPeer)
  57713. {
  57714. setComponentUnderMouse (0, screenPos, time);
  57715. lastPeer = newPeer;
  57716. setComponentUnderMouse (findComponentAt (screenPos), screenPos, time);
  57717. }
  57718. }
  57719. void setScreenPos (const Point<int>& newScreenPos, const int64 time, const bool forceUpdate)
  57720. {
  57721. if (! isDragging())
  57722. setComponentUnderMouse (findComponentAt (newScreenPos), newScreenPos, time);
  57723. if (newScreenPos != lastScreenPos || forceUpdate)
  57724. {
  57725. cancelPendingUpdate();
  57726. lastScreenPos = newScreenPos;
  57727. Component* const current = getComponentUnderMouse();
  57728. if (current != 0)
  57729. {
  57730. if (isDragging())
  57731. {
  57732. registerMouseDrag (newScreenPos);
  57733. sendMouseDrag (current, newScreenPos + unboundedMouseOffset, time);
  57734. if (isUnboundedMouseModeOn)
  57735. handleUnboundedDrag (current);
  57736. }
  57737. else
  57738. {
  57739. sendMouseMove (current, newScreenPos, time);
  57740. }
  57741. }
  57742. revealCursor (false);
  57743. }
  57744. }
  57745. void handleEvent (ComponentPeer* const newPeer, const Point<int>& positionWithinPeer, const int64 time, const ModifierKeys& newMods)
  57746. {
  57747. jassert (newPeer != 0);
  57748. lastTime = time;
  57749. ++mouseEventCounter;
  57750. const Point<int> screenPos (newPeer->relativePositionToGlobal (positionWithinPeer));
  57751. if (isDragging() && newMods.isAnyMouseButtonDown())
  57752. {
  57753. setScreenPos (screenPos, time, false);
  57754. }
  57755. else
  57756. {
  57757. setPeer (newPeer, screenPos, time);
  57758. ComponentPeer* peer = getPeer();
  57759. if (peer != 0)
  57760. {
  57761. if (setButtons (screenPos, time, newMods))
  57762. return; // some modal events have been dispatched, so the current event is now out-of-date
  57763. peer = getPeer();
  57764. if (peer != 0)
  57765. setScreenPos (screenPos, time, false);
  57766. }
  57767. }
  57768. }
  57769. void handleWheel (ComponentPeer* const peer, const Point<int>& positionWithinPeer, int64 time, float x, float y)
  57770. {
  57771. jassert (peer != 0);
  57772. lastTime = time;
  57773. ++mouseEventCounter;
  57774. const Point<int> screenPos (peer->relativePositionToGlobal (positionWithinPeer));
  57775. setPeer (peer, screenPos, time);
  57776. setScreenPos (screenPos, time, false);
  57777. triggerFakeMove();
  57778. if (! isDragging())
  57779. {
  57780. Component* current = getComponentUnderMouse();
  57781. if (current != 0)
  57782. sendMouseWheel (current, screenPos, time, x, y);
  57783. }
  57784. }
  57785. const Time getLastMouseDownTime() const throw()
  57786. {
  57787. return Time (mouseDowns[0].time);
  57788. }
  57789. const Point<int> getLastMouseDownPosition() const throw()
  57790. {
  57791. return mouseDowns[0].position;
  57792. }
  57793. int getNumberOfMultipleClicks() const throw()
  57794. {
  57795. int numClicks = 0;
  57796. if (mouseDowns[0].time != 0)
  57797. {
  57798. if (! mouseMovedSignificantlySincePressed)
  57799. ++numClicks;
  57800. for (int i = 1; i < numElementsInArray (mouseDowns); ++i)
  57801. {
  57802. if (mouseDowns[0].canBePartOfMultipleClickWith (mouseDowns[1], (int) (MouseEvent::getDoubleClickTimeout() * (1.0 + 0.25 * (i - 1)))))
  57803. ++numClicks;
  57804. else
  57805. break;
  57806. }
  57807. }
  57808. return numClicks;
  57809. }
  57810. bool hasMouseMovedSignificantlySincePressed() const throw()
  57811. {
  57812. return mouseMovedSignificantlySincePressed
  57813. || lastTime > mouseDowns[0].time + 300;
  57814. }
  57815. void triggerFakeMove()
  57816. {
  57817. triggerAsyncUpdate();
  57818. }
  57819. void handleAsyncUpdate()
  57820. {
  57821. setScreenPos (lastScreenPos, jmax (lastTime, Time::currentTimeMillis()), true);
  57822. }
  57823. void enableUnboundedMouseMovement (bool enable, bool keepCursorVisibleUntilOffscreen)
  57824. {
  57825. enable = enable && isDragging();
  57826. isCursorVisibleUntilOffscreen = keepCursorVisibleUntilOffscreen;
  57827. if (enable != isUnboundedMouseModeOn)
  57828. {
  57829. if ((! enable) && ((! isCursorVisibleUntilOffscreen) || ! unboundedMouseOffset.isOrigin()))
  57830. {
  57831. // when released, return the mouse to within the component's bounds
  57832. Component* current = getComponentUnderMouse();
  57833. if (current != 0)
  57834. Desktop::setMousePosition (current->getScreenBounds()
  57835. .getConstrainedPoint (lastScreenPos));
  57836. }
  57837. isUnboundedMouseModeOn = enable;
  57838. unboundedMouseOffset = Point<int>();
  57839. revealCursor (true);
  57840. }
  57841. }
  57842. void handleUnboundedDrag (Component* current)
  57843. {
  57844. const Rectangle<int> screenArea (current->getParentMonitorArea().expanded (-2, -2));
  57845. if (! screenArea.contains (lastScreenPos))
  57846. {
  57847. const Point<int> componentCentre (current->getScreenBounds().getCentre());
  57848. unboundedMouseOffset += (lastScreenPos - componentCentre);
  57849. Desktop::setMousePosition (componentCentre);
  57850. }
  57851. else if (isCursorVisibleUntilOffscreen
  57852. && (! unboundedMouseOffset.isOrigin())
  57853. && screenArea.contains (lastScreenPos + unboundedMouseOffset))
  57854. {
  57855. Desktop::setMousePosition (lastScreenPos + unboundedMouseOffset);
  57856. unboundedMouseOffset = Point<int>();
  57857. }
  57858. }
  57859. void showMouseCursor (MouseCursor cursor, bool forcedUpdate)
  57860. {
  57861. if (isUnboundedMouseModeOn && ((! unboundedMouseOffset.isOrigin()) || ! isCursorVisibleUntilOffscreen))
  57862. {
  57863. cursor = MouseCursor::NoCursor;
  57864. forcedUpdate = true;
  57865. }
  57866. if (forcedUpdate || cursor.getHandle() != currentCursorHandle)
  57867. {
  57868. currentCursorHandle = cursor.getHandle();
  57869. cursor.showInWindow (getPeer());
  57870. }
  57871. }
  57872. void hideCursor()
  57873. {
  57874. showMouseCursor (MouseCursor::NoCursor, true);
  57875. }
  57876. void revealCursor (bool forcedUpdate)
  57877. {
  57878. MouseCursor mc (MouseCursor::NormalCursor);
  57879. Component* current = getComponentUnderMouse();
  57880. if (current != 0)
  57881. mc = current->getLookAndFeel().getMouseCursorFor (*current);
  57882. showMouseCursor (mc, forcedUpdate);
  57883. }
  57884. int index;
  57885. bool isMouseDevice;
  57886. Point<int> lastScreenPos;
  57887. ModifierKeys buttonState;
  57888. private:
  57889. MouseInputSource& source;
  57890. Component::SafePointer<Component> componentUnderMouse;
  57891. ComponentPeer* lastPeer;
  57892. Point<int> unboundedMouseOffset;
  57893. bool isUnboundedMouseModeOn, isCursorVisibleUntilOffscreen;
  57894. void* currentCursorHandle;
  57895. int mouseEventCounter;
  57896. struct RecentMouseDown
  57897. {
  57898. Point<int> position;
  57899. int64 time;
  57900. Component* component;
  57901. ModifierKeys buttons;
  57902. bool canBePartOfMultipleClickWith (const RecentMouseDown& other, int maxTimeBetween) const
  57903. {
  57904. return time - other.time < maxTimeBetween
  57905. && abs (position.getX() - other.position.getX()) < 8
  57906. && abs (position.getY() - other.position.getY()) < 8
  57907. && buttons == other.buttons;;
  57908. }
  57909. };
  57910. RecentMouseDown mouseDowns[4];
  57911. bool mouseMovedSignificantlySincePressed;
  57912. int64 lastTime;
  57913. void registerMouseDown (const Point<int>& screenPos, const int64 time,
  57914. Component* const component, const ModifierKeys& modifiers) throw()
  57915. {
  57916. for (int i = numElementsInArray (mouseDowns); --i > 0;)
  57917. mouseDowns[i] = mouseDowns[i - 1];
  57918. mouseDowns[0].position = screenPos;
  57919. mouseDowns[0].time = time;
  57920. mouseDowns[0].component = component;
  57921. mouseDowns[0].buttons = modifiers.withOnlyMouseButtons();
  57922. mouseMovedSignificantlySincePressed = false;
  57923. }
  57924. void registerMouseDrag (const Point<int>& screenPos) throw()
  57925. {
  57926. mouseMovedSignificantlySincePressed = mouseMovedSignificantlySincePressed
  57927. || mouseDowns[0].position.getDistanceFrom (screenPos) >= 4;
  57928. }
  57929. MouseInputSourceInternal (const MouseInputSourceInternal&);
  57930. MouseInputSourceInternal& operator= (const MouseInputSourceInternal&);
  57931. };
  57932. MouseInputSource::MouseInputSource (const int index, const bool isMouseDevice)
  57933. {
  57934. pimpl = new MouseInputSourceInternal (*this, index, isMouseDevice);
  57935. }
  57936. MouseInputSource::~MouseInputSource()
  57937. {
  57938. }
  57939. bool MouseInputSource::isMouse() const { return pimpl->isMouseDevice; }
  57940. bool MouseInputSource::isTouch() const { return ! isMouse(); }
  57941. bool MouseInputSource::canHover() const { return isMouse(); }
  57942. bool MouseInputSource::hasMouseWheel() const { return isMouse(); }
  57943. int MouseInputSource::getIndex() const { return pimpl->index; }
  57944. bool MouseInputSource::isDragging() const { return pimpl->isDragging(); }
  57945. const Point<int> MouseInputSource::getScreenPosition() const { return pimpl->getScreenPosition(); }
  57946. const ModifierKeys MouseInputSource::getCurrentModifiers() const { return pimpl->getCurrentModifiers(); }
  57947. Component* MouseInputSource::getComponentUnderMouse() const { return pimpl->getComponentUnderMouse(); }
  57948. void MouseInputSource::triggerFakeMove() const { pimpl->triggerFakeMove(); }
  57949. int MouseInputSource::getNumberOfMultipleClicks() const throw() { return pimpl->getNumberOfMultipleClicks(); }
  57950. const Time MouseInputSource::getLastMouseDownTime() const throw() { return pimpl->getLastMouseDownTime(); }
  57951. const Point<int> MouseInputSource::getLastMouseDownPosition() const throw() { return pimpl->getLastMouseDownPosition(); }
  57952. bool MouseInputSource::hasMouseMovedSignificantlySincePressed() const throw() { return pimpl->hasMouseMovedSignificantlySincePressed(); }
  57953. bool MouseInputSource::canDoUnboundedMovement() const throw() { return isMouse(); }
  57954. void MouseInputSource::enableUnboundedMouseMovement (bool isEnabled, bool keepCursorVisibleUntilOffscreen) { pimpl->enableUnboundedMouseMovement (isEnabled, keepCursorVisibleUntilOffscreen); }
  57955. bool MouseInputSource::hasMouseCursor() const throw() { return isMouse(); }
  57956. void MouseInputSource::showMouseCursor (const MouseCursor& cursor) { pimpl->showMouseCursor (cursor, false); }
  57957. void MouseInputSource::hideCursor() { pimpl->hideCursor(); }
  57958. void MouseInputSource::revealCursor() { pimpl->revealCursor (false); }
  57959. void MouseInputSource::forceMouseCursorUpdate() { pimpl->revealCursor (true); }
  57960. void MouseInputSource::handleEvent (ComponentPeer* peer, const Point<int>& positionWithinPeer, const int64 time, const ModifierKeys& mods)
  57961. {
  57962. pimpl->handleEvent (peer, positionWithinPeer, time, mods.withOnlyMouseButtons());
  57963. }
  57964. void MouseInputSource::handleWheel (ComponentPeer* const peer, const Point<int>& positionWithinPeer, const int64 time, const float x, const float y)
  57965. {
  57966. pimpl->handleWheel (peer, positionWithinPeer, time, x, y);
  57967. }
  57968. END_JUCE_NAMESPACE
  57969. /*** End of inlined file: juce_MouseInputSource.cpp ***/
  57970. /*** Start of inlined file: juce_MouseHoverDetector.cpp ***/
  57971. BEGIN_JUCE_NAMESPACE
  57972. MouseHoverDetector::MouseHoverDetector (const int hoverTimeMillisecs_)
  57973. : source (0),
  57974. hoverTimeMillisecs (hoverTimeMillisecs_),
  57975. hasJustHovered (false)
  57976. {
  57977. internalTimer.owner = this;
  57978. }
  57979. MouseHoverDetector::~MouseHoverDetector()
  57980. {
  57981. setHoverComponent (0);
  57982. }
  57983. void MouseHoverDetector::setHoverTimeMillisecs (const int newTimeInMillisecs)
  57984. {
  57985. hoverTimeMillisecs = newTimeInMillisecs;
  57986. }
  57987. void MouseHoverDetector::setHoverComponent (Component* const newSourceComponent)
  57988. {
  57989. if (source != newSourceComponent)
  57990. {
  57991. internalTimer.stopTimer();
  57992. hasJustHovered = false;
  57993. if (source != 0)
  57994. {
  57995. // ! you need to delete the hover detector before deleting its component
  57996. jassert (source->isValidComponent());
  57997. source->removeMouseListener (&internalTimer);
  57998. }
  57999. source = newSourceComponent;
  58000. if (newSourceComponent != 0)
  58001. newSourceComponent->addMouseListener (&internalTimer, false);
  58002. }
  58003. }
  58004. void MouseHoverDetector::hoverTimerCallback()
  58005. {
  58006. internalTimer.stopTimer();
  58007. if (source != 0)
  58008. {
  58009. const Point<int> pos (source->getMouseXYRelative());
  58010. if (source->reallyContains (pos.getX(), pos.getY(), false))
  58011. {
  58012. hasJustHovered = true;
  58013. mouseHovered (pos.getX(), pos.getY());
  58014. }
  58015. }
  58016. }
  58017. void MouseHoverDetector::checkJustHoveredCallback()
  58018. {
  58019. if (hasJustHovered)
  58020. {
  58021. hasJustHovered = false;
  58022. mouseMovedAfterHover();
  58023. }
  58024. }
  58025. void MouseHoverDetector::HoverDetectorInternal::timerCallback()
  58026. {
  58027. owner->hoverTimerCallback();
  58028. }
  58029. void MouseHoverDetector::HoverDetectorInternal::mouseEnter (const MouseEvent&)
  58030. {
  58031. stopTimer();
  58032. owner->checkJustHoveredCallback();
  58033. }
  58034. void MouseHoverDetector::HoverDetectorInternal::mouseExit (const MouseEvent&)
  58035. {
  58036. stopTimer();
  58037. owner->checkJustHoveredCallback();
  58038. }
  58039. void MouseHoverDetector::HoverDetectorInternal::mouseDown (const MouseEvent&)
  58040. {
  58041. stopTimer();
  58042. owner->checkJustHoveredCallback();
  58043. }
  58044. void MouseHoverDetector::HoverDetectorInternal::mouseUp (const MouseEvent&)
  58045. {
  58046. stopTimer();
  58047. owner->checkJustHoveredCallback();
  58048. }
  58049. void MouseHoverDetector::HoverDetectorInternal::mouseMove (const MouseEvent& e)
  58050. {
  58051. if (lastX != e.x || lastY != e.y) // to avoid fake mouse-moves setting it off
  58052. {
  58053. lastX = e.x;
  58054. lastY = e.y;
  58055. if (owner->source != 0)
  58056. startTimer (owner->hoverTimeMillisecs);
  58057. owner->checkJustHoveredCallback();
  58058. }
  58059. }
  58060. void MouseHoverDetector::HoverDetectorInternal::mouseWheelMove (const MouseEvent&, float, float)
  58061. {
  58062. stopTimer();
  58063. owner->checkJustHoveredCallback();
  58064. }
  58065. END_JUCE_NAMESPACE
  58066. /*** End of inlined file: juce_MouseHoverDetector.cpp ***/
  58067. /*** Start of inlined file: juce_MouseListener.cpp ***/
  58068. BEGIN_JUCE_NAMESPACE
  58069. void MouseListener::mouseEnter (const MouseEvent&)
  58070. {
  58071. }
  58072. void MouseListener::mouseExit (const MouseEvent&)
  58073. {
  58074. }
  58075. void MouseListener::mouseDown (const MouseEvent&)
  58076. {
  58077. }
  58078. void MouseListener::mouseUp (const MouseEvent&)
  58079. {
  58080. }
  58081. void MouseListener::mouseDrag (const MouseEvent&)
  58082. {
  58083. }
  58084. void MouseListener::mouseMove (const MouseEvent&)
  58085. {
  58086. }
  58087. void MouseListener::mouseDoubleClick (const MouseEvent&)
  58088. {
  58089. }
  58090. void MouseListener::mouseWheelMove (const MouseEvent&, float, float)
  58091. {
  58092. }
  58093. END_JUCE_NAMESPACE
  58094. /*** End of inlined file: juce_MouseListener.cpp ***/
  58095. /*** Start of inlined file: juce_BooleanPropertyComponent.cpp ***/
  58096. BEGIN_JUCE_NAMESPACE
  58097. BooleanPropertyComponent::BooleanPropertyComponent (const String& name,
  58098. const String& buttonTextWhenTrue,
  58099. const String& buttonTextWhenFalse)
  58100. : PropertyComponent (name),
  58101. onText (buttonTextWhenTrue),
  58102. offText (buttonTextWhenFalse)
  58103. {
  58104. addAndMakeVisible (&button);
  58105. button.setClickingTogglesState (false);
  58106. button.addButtonListener (this);
  58107. }
  58108. BooleanPropertyComponent::BooleanPropertyComponent (const Value& valueToControl,
  58109. const String& name,
  58110. const String& buttonText)
  58111. : PropertyComponent (name),
  58112. onText (buttonText),
  58113. offText (buttonText)
  58114. {
  58115. addAndMakeVisible (&button);
  58116. button.setClickingTogglesState (false);
  58117. button.setButtonText (buttonText);
  58118. button.getToggleStateValue().referTo (valueToControl);
  58119. button.setClickingTogglesState (true);
  58120. }
  58121. BooleanPropertyComponent::~BooleanPropertyComponent()
  58122. {
  58123. }
  58124. void BooleanPropertyComponent::setState (const bool newState)
  58125. {
  58126. button.setToggleState (newState, true);
  58127. }
  58128. bool BooleanPropertyComponent::getState() const
  58129. {
  58130. return button.getToggleState();
  58131. }
  58132. void BooleanPropertyComponent::paint (Graphics& g)
  58133. {
  58134. PropertyComponent::paint (g);
  58135. g.setColour (Colours::white);
  58136. g.fillRect (button.getBounds());
  58137. g.setColour (findColour (ComboBox::outlineColourId));
  58138. g.drawRect (button.getBounds());
  58139. }
  58140. void BooleanPropertyComponent::refresh()
  58141. {
  58142. button.setToggleState (getState(), false);
  58143. button.setButtonText (button.getToggleState() ? onText : offText);
  58144. }
  58145. void BooleanPropertyComponent::buttonClicked (Button*)
  58146. {
  58147. setState (! getState());
  58148. }
  58149. END_JUCE_NAMESPACE
  58150. /*** End of inlined file: juce_BooleanPropertyComponent.cpp ***/
  58151. /*** Start of inlined file: juce_ButtonPropertyComponent.cpp ***/
  58152. BEGIN_JUCE_NAMESPACE
  58153. ButtonPropertyComponent::ButtonPropertyComponent (const String& name,
  58154. const bool triggerOnMouseDown)
  58155. : PropertyComponent (name)
  58156. {
  58157. addAndMakeVisible (&button);
  58158. button.setTriggeredOnMouseDown (triggerOnMouseDown);
  58159. button.addButtonListener (this);
  58160. }
  58161. ButtonPropertyComponent::~ButtonPropertyComponent()
  58162. {
  58163. }
  58164. void ButtonPropertyComponent::refresh()
  58165. {
  58166. button.setButtonText (getButtonText());
  58167. }
  58168. void ButtonPropertyComponent::buttonClicked (Button*)
  58169. {
  58170. buttonClicked();
  58171. }
  58172. END_JUCE_NAMESPACE
  58173. /*** End of inlined file: juce_ButtonPropertyComponent.cpp ***/
  58174. /*** Start of inlined file: juce_ChoicePropertyComponent.cpp ***/
  58175. BEGIN_JUCE_NAMESPACE
  58176. class ChoicePropertyComponent::RemapperValueSource : public Value::ValueSource,
  58177. public Value::Listener
  58178. {
  58179. public:
  58180. RemapperValueSource (const Value& sourceValue_, const Array<var>& mappings_)
  58181. : sourceValue (sourceValue_),
  58182. mappings (mappings_)
  58183. {
  58184. sourceValue.addListener (this);
  58185. }
  58186. ~RemapperValueSource() {}
  58187. const var getValue() const
  58188. {
  58189. return mappings.indexOf (sourceValue.getValue()) + 1;
  58190. }
  58191. void setValue (const var& newValue)
  58192. {
  58193. const var remappedVal (mappings [(int) newValue - 1]);
  58194. if (remappedVal != sourceValue)
  58195. sourceValue = remappedVal;
  58196. }
  58197. void valueChanged (Value&)
  58198. {
  58199. sendChangeMessage (true);
  58200. }
  58201. juce_UseDebuggingNewOperator
  58202. protected:
  58203. Value sourceValue;
  58204. Array<var> mappings;
  58205. RemapperValueSource (const RemapperValueSource&);
  58206. const RemapperValueSource& operator= (const RemapperValueSource&);
  58207. };
  58208. ChoicePropertyComponent::ChoicePropertyComponent (const String& name)
  58209. : PropertyComponent (name),
  58210. isCustomClass (true)
  58211. {
  58212. }
  58213. ChoicePropertyComponent::ChoicePropertyComponent (const Value& valueToControl,
  58214. const String& name,
  58215. const StringArray& choices_,
  58216. const Array <var>& correspondingValues)
  58217. : PropertyComponent (name),
  58218. choices (choices_),
  58219. isCustomClass (false)
  58220. {
  58221. // The array of corresponding values must contain one value for each of the items in
  58222. // the choices array!
  58223. jassert (correspondingValues.size() == choices.size());
  58224. createComboBox();
  58225. comboBox.getSelectedIdAsValue().referTo (Value (new RemapperValueSource (valueToControl, correspondingValues)));
  58226. }
  58227. ChoicePropertyComponent::~ChoicePropertyComponent()
  58228. {
  58229. }
  58230. void ChoicePropertyComponent::createComboBox()
  58231. {
  58232. addAndMakeVisible (&comboBox);
  58233. for (int i = 0; i < choices.size(); ++i)
  58234. {
  58235. if (choices[i].isNotEmpty())
  58236. comboBox.addItem (choices[i], i + 1);
  58237. else
  58238. comboBox.addSeparator();
  58239. }
  58240. comboBox.setEditableText (false);
  58241. }
  58242. void ChoicePropertyComponent::setIndex (const int /*newIndex*/)
  58243. {
  58244. jassertfalse; // you need to override this method in your subclass!
  58245. }
  58246. int ChoicePropertyComponent::getIndex() const
  58247. {
  58248. jassertfalse; // you need to override this method in your subclass!
  58249. return -1;
  58250. }
  58251. const StringArray& ChoicePropertyComponent::getChoices() const
  58252. {
  58253. return choices;
  58254. }
  58255. void ChoicePropertyComponent::refresh()
  58256. {
  58257. if (isCustomClass)
  58258. {
  58259. if (! comboBox.isVisible())
  58260. {
  58261. createComboBox();
  58262. comboBox.addListener (this);
  58263. }
  58264. comboBox.setSelectedId (getIndex() + 1, true);
  58265. }
  58266. }
  58267. void ChoicePropertyComponent::comboBoxChanged (ComboBox*)
  58268. {
  58269. if (isCustomClass)
  58270. {
  58271. const int newIndex = comboBox.getSelectedId() - 1;
  58272. if (newIndex != getIndex())
  58273. setIndex (newIndex);
  58274. }
  58275. }
  58276. END_JUCE_NAMESPACE
  58277. /*** End of inlined file: juce_ChoicePropertyComponent.cpp ***/
  58278. /*** Start of inlined file: juce_PropertyComponent.cpp ***/
  58279. BEGIN_JUCE_NAMESPACE
  58280. PropertyComponent::PropertyComponent (const String& name,
  58281. const int preferredHeight_)
  58282. : Component (name),
  58283. preferredHeight (preferredHeight_)
  58284. {
  58285. jassert (name.isNotEmpty());
  58286. }
  58287. PropertyComponent::~PropertyComponent()
  58288. {
  58289. }
  58290. void PropertyComponent::paint (Graphics& g)
  58291. {
  58292. getLookAndFeel().drawPropertyComponentBackground (g, getWidth(), getHeight(), *this);
  58293. getLookAndFeel().drawPropertyComponentLabel (g, getWidth(), getHeight(), *this);
  58294. }
  58295. void PropertyComponent::resized()
  58296. {
  58297. if (getNumChildComponents() > 0)
  58298. getChildComponent (0)->setBounds (getLookAndFeel().getPropertyComponentContentPosition (*this));
  58299. }
  58300. void PropertyComponent::enablementChanged()
  58301. {
  58302. repaint();
  58303. }
  58304. END_JUCE_NAMESPACE
  58305. /*** End of inlined file: juce_PropertyComponent.cpp ***/
  58306. /*** Start of inlined file: juce_PropertyPanel.cpp ***/
  58307. BEGIN_JUCE_NAMESPACE
  58308. class PropertyPanel::PropertyHolderComponent : public Component
  58309. {
  58310. public:
  58311. PropertyHolderComponent()
  58312. {
  58313. }
  58314. ~PropertyHolderComponent()
  58315. {
  58316. deleteAllChildren();
  58317. }
  58318. void paint (Graphics&)
  58319. {
  58320. }
  58321. void updateLayout (int width);
  58322. void refreshAll() const;
  58323. private:
  58324. PropertyHolderComponent (const PropertyHolderComponent&);
  58325. PropertyHolderComponent& operator= (const PropertyHolderComponent&);
  58326. };
  58327. class PropertySectionComponent : public Component
  58328. {
  58329. public:
  58330. PropertySectionComponent (const String& sectionTitle,
  58331. const Array <PropertyComponent*>& newProperties,
  58332. const bool open)
  58333. : Component (sectionTitle),
  58334. titleHeight (sectionTitle.isNotEmpty() ? 22 : 0),
  58335. isOpen_ (open)
  58336. {
  58337. for (int i = newProperties.size(); --i >= 0;)
  58338. {
  58339. addAndMakeVisible (newProperties.getUnchecked(i));
  58340. newProperties.getUnchecked(i)->refresh();
  58341. }
  58342. }
  58343. ~PropertySectionComponent()
  58344. {
  58345. deleteAllChildren();
  58346. }
  58347. void paint (Graphics& g)
  58348. {
  58349. if (titleHeight > 0)
  58350. getLookAndFeel().drawPropertyPanelSectionHeader (g, getName(), isOpen(), getWidth(), titleHeight);
  58351. }
  58352. void resized()
  58353. {
  58354. int y = titleHeight;
  58355. for (int i = getNumChildComponents(); --i >= 0;)
  58356. {
  58357. PropertyComponent* const pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  58358. if (pec != 0)
  58359. {
  58360. const int prefH = pec->getPreferredHeight();
  58361. pec->setBounds (1, y, getWidth() - 2, prefH);
  58362. y += prefH;
  58363. }
  58364. }
  58365. }
  58366. int getPreferredHeight() const
  58367. {
  58368. int y = titleHeight;
  58369. if (isOpen())
  58370. {
  58371. for (int i = 0; i < getNumChildComponents(); ++i)
  58372. {
  58373. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  58374. if (pec != 0)
  58375. y += pec->getPreferredHeight();
  58376. }
  58377. }
  58378. return y;
  58379. }
  58380. void setOpen (const bool open)
  58381. {
  58382. if (isOpen_ != open)
  58383. {
  58384. isOpen_ = open;
  58385. for (int i = 0; i < getNumChildComponents(); ++i)
  58386. {
  58387. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  58388. if (pec != 0)
  58389. pec->setVisible (open);
  58390. }
  58391. // (unable to use the syntax findParentComponentOfClass <DragAndDropContainer> () because of a VC6 compiler bug)
  58392. PropertyPanel* const pp = findParentComponentOfClass ((PropertyPanel*) 0);
  58393. if (pp != 0)
  58394. pp->resized();
  58395. }
  58396. }
  58397. bool isOpen() const
  58398. {
  58399. return isOpen_;
  58400. }
  58401. void refreshAll() const
  58402. {
  58403. for (int i = 0; i < getNumChildComponents(); ++i)
  58404. {
  58405. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  58406. if (pec != 0)
  58407. pec->refresh();
  58408. }
  58409. }
  58410. void mouseDown (const MouseEvent&)
  58411. {
  58412. }
  58413. void mouseUp (const MouseEvent& e)
  58414. {
  58415. if (e.getMouseDownX() < titleHeight
  58416. && e.x < titleHeight
  58417. && e.y < titleHeight
  58418. && e.getNumberOfClicks() != 2)
  58419. {
  58420. setOpen (! isOpen());
  58421. }
  58422. }
  58423. void mouseDoubleClick (const MouseEvent& e)
  58424. {
  58425. if (e.y < titleHeight)
  58426. setOpen (! isOpen());
  58427. }
  58428. private:
  58429. int titleHeight;
  58430. bool isOpen_;
  58431. PropertySectionComponent (const PropertySectionComponent&);
  58432. PropertySectionComponent& operator= (const PropertySectionComponent&);
  58433. };
  58434. void PropertyPanel::PropertyHolderComponent::updateLayout (const int width)
  58435. {
  58436. int y = 0;
  58437. for (int i = getNumChildComponents(); --i >= 0;)
  58438. {
  58439. PropertySectionComponent* const section
  58440. = dynamic_cast <PropertySectionComponent*> (getChildComponent (i));
  58441. if (section != 0)
  58442. {
  58443. const int prefH = section->getPreferredHeight();
  58444. section->setBounds (0, y, width, prefH);
  58445. y += prefH;
  58446. }
  58447. }
  58448. setSize (width, y);
  58449. repaint();
  58450. }
  58451. void PropertyPanel::PropertyHolderComponent::refreshAll() const
  58452. {
  58453. for (int i = getNumChildComponents(); --i >= 0;)
  58454. {
  58455. PropertySectionComponent* const section
  58456. = dynamic_cast <PropertySectionComponent*> (getChildComponent (i));
  58457. if (section != 0)
  58458. section->refreshAll();
  58459. }
  58460. }
  58461. PropertyPanel::PropertyPanel()
  58462. {
  58463. messageWhenEmpty = TRANS("(nothing selected)");
  58464. addAndMakeVisible (&viewport);
  58465. viewport.setViewedComponent (propertyHolderComponent = new PropertyHolderComponent());
  58466. viewport.setFocusContainer (true);
  58467. }
  58468. PropertyPanel::~PropertyPanel()
  58469. {
  58470. clear();
  58471. }
  58472. void PropertyPanel::paint (Graphics& g)
  58473. {
  58474. if (propertyHolderComponent->getNumChildComponents() == 0)
  58475. {
  58476. g.setColour (Colours::black.withAlpha (0.5f));
  58477. g.setFont (14.0f);
  58478. g.drawText (messageWhenEmpty, 0, 0, getWidth(), 30,
  58479. Justification::centred, true);
  58480. }
  58481. }
  58482. void PropertyPanel::resized()
  58483. {
  58484. viewport.setBounds (getLocalBounds());
  58485. updatePropHolderLayout();
  58486. }
  58487. void PropertyPanel::clear()
  58488. {
  58489. if (propertyHolderComponent->getNumChildComponents() > 0)
  58490. {
  58491. propertyHolderComponent->deleteAllChildren();
  58492. repaint();
  58493. }
  58494. }
  58495. void PropertyPanel::addProperties (const Array <PropertyComponent*>& newProperties)
  58496. {
  58497. if (propertyHolderComponent->getNumChildComponents() == 0)
  58498. repaint();
  58499. propertyHolderComponent->addAndMakeVisible (new PropertySectionComponent (String::empty,
  58500. newProperties,
  58501. true), 0);
  58502. updatePropHolderLayout();
  58503. }
  58504. void PropertyPanel::addSection (const String& sectionTitle,
  58505. const Array <PropertyComponent*>& newProperties,
  58506. const bool shouldBeOpen)
  58507. {
  58508. jassert (sectionTitle.isNotEmpty());
  58509. if (propertyHolderComponent->getNumChildComponents() == 0)
  58510. repaint();
  58511. propertyHolderComponent->addAndMakeVisible (new PropertySectionComponent (sectionTitle,
  58512. newProperties,
  58513. shouldBeOpen), 0);
  58514. updatePropHolderLayout();
  58515. }
  58516. void PropertyPanel::updatePropHolderLayout() const
  58517. {
  58518. const int maxWidth = viewport.getMaximumVisibleWidth();
  58519. propertyHolderComponent->updateLayout (maxWidth);
  58520. const int newMaxWidth = viewport.getMaximumVisibleWidth();
  58521. if (maxWidth != newMaxWidth)
  58522. {
  58523. // need to do this twice because of scrollbars changing the size, etc.
  58524. propertyHolderComponent->updateLayout (newMaxWidth);
  58525. }
  58526. }
  58527. void PropertyPanel::refreshAll() const
  58528. {
  58529. propertyHolderComponent->refreshAll();
  58530. }
  58531. const StringArray PropertyPanel::getSectionNames() const
  58532. {
  58533. StringArray s;
  58534. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  58535. {
  58536. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  58537. if (section != 0 && section->getName().isNotEmpty())
  58538. s.add (section->getName());
  58539. }
  58540. return s;
  58541. }
  58542. bool PropertyPanel::isSectionOpen (const int sectionIndex) const
  58543. {
  58544. int index = 0;
  58545. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  58546. {
  58547. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  58548. if (section != 0 && section->getName().isNotEmpty())
  58549. {
  58550. if (index == sectionIndex)
  58551. return section->isOpen();
  58552. ++index;
  58553. }
  58554. }
  58555. return false;
  58556. }
  58557. void PropertyPanel::setSectionOpen (const int sectionIndex, const bool shouldBeOpen)
  58558. {
  58559. int index = 0;
  58560. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  58561. {
  58562. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  58563. if (section != 0 && section->getName().isNotEmpty())
  58564. {
  58565. if (index == sectionIndex)
  58566. {
  58567. section->setOpen (shouldBeOpen);
  58568. break;
  58569. }
  58570. ++index;
  58571. }
  58572. }
  58573. }
  58574. void PropertyPanel::setSectionEnabled (const int sectionIndex, const bool shouldBeEnabled)
  58575. {
  58576. int index = 0;
  58577. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  58578. {
  58579. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  58580. if (section != 0 && section->getName().isNotEmpty())
  58581. {
  58582. if (index == sectionIndex)
  58583. {
  58584. section->setEnabled (shouldBeEnabled);
  58585. break;
  58586. }
  58587. ++index;
  58588. }
  58589. }
  58590. }
  58591. XmlElement* PropertyPanel::getOpennessState() const
  58592. {
  58593. XmlElement* const xml = new XmlElement ("PROPERTYPANELSTATE");
  58594. xml->setAttribute ("scrollPos", viewport.getViewPositionY());
  58595. const StringArray sections (getSectionNames());
  58596. for (int i = 0; i < sections.size(); ++i)
  58597. {
  58598. if (sections[i].isNotEmpty())
  58599. {
  58600. XmlElement* const e = xml->createNewChildElement ("SECTION");
  58601. e->setAttribute ("name", sections[i]);
  58602. e->setAttribute ("open", isSectionOpen (i) ? 1 : 0);
  58603. }
  58604. }
  58605. return xml;
  58606. }
  58607. void PropertyPanel::restoreOpennessState (const XmlElement& xml)
  58608. {
  58609. if (xml.hasTagName ("PROPERTYPANELSTATE"))
  58610. {
  58611. const StringArray sections (getSectionNames());
  58612. forEachXmlChildElementWithTagName (xml, e, "SECTION")
  58613. {
  58614. setSectionOpen (sections.indexOf (e->getStringAttribute ("name")),
  58615. e->getBoolAttribute ("open"));
  58616. }
  58617. viewport.setViewPosition (viewport.getViewPositionX(),
  58618. xml.getIntAttribute ("scrollPos", viewport.getViewPositionY()));
  58619. }
  58620. }
  58621. void PropertyPanel::setMessageWhenEmpty (const String& newMessage)
  58622. {
  58623. if (messageWhenEmpty != newMessage)
  58624. {
  58625. messageWhenEmpty = newMessage;
  58626. repaint();
  58627. }
  58628. }
  58629. const String& PropertyPanel::getMessageWhenEmpty() const
  58630. {
  58631. return messageWhenEmpty;
  58632. }
  58633. END_JUCE_NAMESPACE
  58634. /*** End of inlined file: juce_PropertyPanel.cpp ***/
  58635. /*** Start of inlined file: juce_SliderPropertyComponent.cpp ***/
  58636. BEGIN_JUCE_NAMESPACE
  58637. SliderPropertyComponent::SliderPropertyComponent (const String& name,
  58638. const double rangeMin,
  58639. const double rangeMax,
  58640. const double interval,
  58641. const double skewFactor)
  58642. : PropertyComponent (name)
  58643. {
  58644. addAndMakeVisible (&slider);
  58645. slider.setRange (rangeMin, rangeMax, interval);
  58646. slider.setSkewFactor (skewFactor);
  58647. slider.setSliderStyle (Slider::LinearBar);
  58648. slider.addListener (this);
  58649. }
  58650. SliderPropertyComponent::SliderPropertyComponent (const Value& valueToControl,
  58651. const String& name,
  58652. const double rangeMin,
  58653. const double rangeMax,
  58654. const double interval,
  58655. const double skewFactor)
  58656. : PropertyComponent (name)
  58657. {
  58658. addAndMakeVisible (&slider);
  58659. slider.setRange (rangeMin, rangeMax, interval);
  58660. slider.setSkewFactor (skewFactor);
  58661. slider.setSliderStyle (Slider::LinearBar);
  58662. slider.getValueObject().referTo (valueToControl);
  58663. }
  58664. SliderPropertyComponent::~SliderPropertyComponent()
  58665. {
  58666. }
  58667. void SliderPropertyComponent::setValue (const double /*newValue*/)
  58668. {
  58669. }
  58670. double SliderPropertyComponent::getValue() const
  58671. {
  58672. return slider.getValue();
  58673. }
  58674. void SliderPropertyComponent::refresh()
  58675. {
  58676. slider.setValue (getValue(), false);
  58677. }
  58678. void SliderPropertyComponent::sliderValueChanged (Slider*)
  58679. {
  58680. if (getValue() != slider.getValue())
  58681. setValue (slider.getValue());
  58682. }
  58683. END_JUCE_NAMESPACE
  58684. /*** End of inlined file: juce_SliderPropertyComponent.cpp ***/
  58685. /*** Start of inlined file: juce_TextPropertyComponent.cpp ***/
  58686. BEGIN_JUCE_NAMESPACE
  58687. class TextPropLabel : public Label
  58688. {
  58689. public:
  58690. TextPropLabel (TextPropertyComponent& owner_,
  58691. const int maxChars_, const bool isMultiline_)
  58692. : Label (String::empty, String::empty),
  58693. owner (owner_),
  58694. maxChars (maxChars_),
  58695. isMultiline (isMultiline_)
  58696. {
  58697. setEditable (true, true, false);
  58698. setColour (backgroundColourId, Colours::white);
  58699. setColour (outlineColourId, findColour (ComboBox::outlineColourId));
  58700. }
  58701. TextEditor* createEditorComponent()
  58702. {
  58703. TextEditor* const textEditor = Label::createEditorComponent();
  58704. textEditor->setInputRestrictions (maxChars);
  58705. if (isMultiline)
  58706. {
  58707. textEditor->setMultiLine (true, true);
  58708. textEditor->setReturnKeyStartsNewLine (true);
  58709. }
  58710. return textEditor;
  58711. }
  58712. void textWasEdited()
  58713. {
  58714. owner.textWasEdited();
  58715. }
  58716. private:
  58717. TextPropertyComponent& owner;
  58718. int maxChars;
  58719. bool isMultiline;
  58720. };
  58721. TextPropertyComponent::TextPropertyComponent (const String& name,
  58722. const int maxNumChars,
  58723. const bool isMultiLine)
  58724. : PropertyComponent (name)
  58725. {
  58726. createEditor (maxNumChars, isMultiLine);
  58727. }
  58728. TextPropertyComponent::TextPropertyComponent (const Value& valueToControl,
  58729. const String& name,
  58730. const int maxNumChars,
  58731. const bool isMultiLine)
  58732. : PropertyComponent (name)
  58733. {
  58734. createEditor (maxNumChars, isMultiLine);
  58735. textEditor->getTextValue().referTo (valueToControl);
  58736. }
  58737. TextPropertyComponent::~TextPropertyComponent()
  58738. {
  58739. }
  58740. void TextPropertyComponent::setText (const String& newText)
  58741. {
  58742. textEditor->setText (newText, true);
  58743. }
  58744. const String TextPropertyComponent::getText() const
  58745. {
  58746. return textEditor->getText();
  58747. }
  58748. void TextPropertyComponent::createEditor (const int maxNumChars, const bool isMultiLine)
  58749. {
  58750. addAndMakeVisible (textEditor = new TextPropLabel (*this, maxNumChars, isMultiLine));
  58751. if (isMultiLine)
  58752. {
  58753. textEditor->setJustificationType (Justification::topLeft);
  58754. preferredHeight = 120;
  58755. }
  58756. }
  58757. void TextPropertyComponent::refresh()
  58758. {
  58759. textEditor->setText (getText(), false);
  58760. }
  58761. void TextPropertyComponent::textWasEdited()
  58762. {
  58763. const String newText (textEditor->getText());
  58764. if (getText() != newText)
  58765. setText (newText);
  58766. }
  58767. END_JUCE_NAMESPACE
  58768. /*** End of inlined file: juce_TextPropertyComponent.cpp ***/
  58769. /*** Start of inlined file: juce_AudioDeviceSelectorComponent.cpp ***/
  58770. BEGIN_JUCE_NAMESPACE
  58771. class SimpleDeviceManagerInputLevelMeter : public Component,
  58772. public Timer
  58773. {
  58774. public:
  58775. SimpleDeviceManagerInputLevelMeter (AudioDeviceManager* const manager_)
  58776. : manager (manager_),
  58777. level (0)
  58778. {
  58779. startTimer (50);
  58780. manager->enableInputLevelMeasurement (true);
  58781. }
  58782. ~SimpleDeviceManagerInputLevelMeter()
  58783. {
  58784. manager->enableInputLevelMeasurement (false);
  58785. }
  58786. void timerCallback()
  58787. {
  58788. const float newLevel = (float) manager->getCurrentInputLevel();
  58789. if (std::abs (level - newLevel) > 0.005f)
  58790. {
  58791. level = newLevel;
  58792. repaint();
  58793. }
  58794. }
  58795. void paint (Graphics& g)
  58796. {
  58797. getLookAndFeel().drawLevelMeter (g, getWidth(), getHeight(),
  58798. (float) exp (log (level) / 3.0)); // (add a bit of a skew to make the level more obvious)
  58799. }
  58800. private:
  58801. AudioDeviceManager* const manager;
  58802. float level;
  58803. SimpleDeviceManagerInputLevelMeter (const SimpleDeviceManagerInputLevelMeter&);
  58804. SimpleDeviceManagerInputLevelMeter& operator= (const SimpleDeviceManagerInputLevelMeter&);
  58805. };
  58806. class AudioDeviceSelectorComponent::MidiInputSelectorComponentListBox : public ListBox,
  58807. public ListBoxModel
  58808. {
  58809. public:
  58810. MidiInputSelectorComponentListBox (AudioDeviceManager& deviceManager_,
  58811. const String& noItemsMessage_,
  58812. const int minNumber_,
  58813. const int maxNumber_)
  58814. : ListBox (String::empty, 0),
  58815. deviceManager (deviceManager_),
  58816. noItemsMessage (noItemsMessage_),
  58817. minNumber (minNumber_),
  58818. maxNumber (maxNumber_)
  58819. {
  58820. items = MidiInput::getDevices();
  58821. setModel (this);
  58822. setOutlineThickness (1);
  58823. }
  58824. ~MidiInputSelectorComponentListBox()
  58825. {
  58826. }
  58827. int getNumRows()
  58828. {
  58829. return items.size();
  58830. }
  58831. void paintListBoxItem (int row,
  58832. Graphics& g,
  58833. int width, int height,
  58834. bool rowIsSelected)
  58835. {
  58836. if (((unsigned int) row) < (unsigned int) items.size())
  58837. {
  58838. if (rowIsSelected)
  58839. g.fillAll (findColour (TextEditor::highlightColourId)
  58840. .withMultipliedAlpha (0.3f));
  58841. const String item (items [row]);
  58842. bool enabled = deviceManager.isMidiInputEnabled (item);
  58843. const int x = getTickX();
  58844. const float tickW = height * 0.75f;
  58845. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  58846. enabled, true, true, false);
  58847. g.setFont (height * 0.6f);
  58848. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  58849. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  58850. }
  58851. }
  58852. void listBoxItemClicked (int row, const MouseEvent& e)
  58853. {
  58854. selectRow (row);
  58855. if (e.x < getTickX())
  58856. flipEnablement (row);
  58857. }
  58858. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  58859. {
  58860. flipEnablement (row);
  58861. }
  58862. void returnKeyPressed (int row)
  58863. {
  58864. flipEnablement (row);
  58865. }
  58866. void paint (Graphics& g)
  58867. {
  58868. ListBox::paint (g);
  58869. if (items.size() == 0)
  58870. {
  58871. g.setColour (Colours::grey);
  58872. g.setFont (13.0f);
  58873. g.drawText (noItemsMessage,
  58874. 0, 0, getWidth(), getHeight() / 2,
  58875. Justification::centred, true);
  58876. }
  58877. }
  58878. int getBestHeight (const int preferredHeight)
  58879. {
  58880. const int extra = getOutlineThickness() * 2;
  58881. return jmax (getRowHeight() * 2 + extra,
  58882. jmin (getRowHeight() * getNumRows() + extra,
  58883. preferredHeight));
  58884. }
  58885. juce_UseDebuggingNewOperator
  58886. private:
  58887. AudioDeviceManager& deviceManager;
  58888. const String noItemsMessage;
  58889. StringArray items;
  58890. int minNumber, maxNumber;
  58891. void flipEnablement (const int row)
  58892. {
  58893. if (((unsigned int) row) < (unsigned int) items.size())
  58894. {
  58895. const String item (items [row]);
  58896. deviceManager.setMidiInputEnabled (item, ! deviceManager.isMidiInputEnabled (item));
  58897. }
  58898. }
  58899. int getTickX() const
  58900. {
  58901. return getRowHeight() + 5;
  58902. }
  58903. MidiInputSelectorComponentListBox (const MidiInputSelectorComponentListBox&);
  58904. MidiInputSelectorComponentListBox& operator= (const MidiInputSelectorComponentListBox&);
  58905. };
  58906. class AudioDeviceSettingsPanel : public Component,
  58907. public ChangeListener,
  58908. public ComboBoxListener, // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  58909. public ButtonListener
  58910. {
  58911. public:
  58912. AudioDeviceSettingsPanel (AudioIODeviceType* type_,
  58913. AudioIODeviceType::DeviceSetupDetails& setup_,
  58914. const bool hideAdvancedOptionsWithButton)
  58915. : type (type_),
  58916. setup (setup_)
  58917. {
  58918. if (hideAdvancedOptionsWithButton)
  58919. {
  58920. addAndMakeVisible (showAdvancedSettingsButton = new TextButton (TRANS("Show advanced settings...")));
  58921. showAdvancedSettingsButton->addButtonListener (this);
  58922. }
  58923. type->scanForDevices();
  58924. setup.manager->addChangeListener (this);
  58925. changeListenerCallback (0);
  58926. }
  58927. ~AudioDeviceSettingsPanel()
  58928. {
  58929. setup.manager->removeChangeListener (this);
  58930. }
  58931. void resized()
  58932. {
  58933. const int lx = proportionOfWidth (0.35f);
  58934. const int w = proportionOfWidth (0.4f);
  58935. const int h = 24;
  58936. const int space = 6;
  58937. const int dh = h + space;
  58938. int y = 0;
  58939. if (outputDeviceDropDown != 0)
  58940. {
  58941. outputDeviceDropDown->setBounds (lx, y, w, h);
  58942. if (testButton != 0)
  58943. testButton->setBounds (proportionOfWidth (0.77f),
  58944. outputDeviceDropDown->getY(),
  58945. proportionOfWidth (0.18f),
  58946. h);
  58947. y += dh;
  58948. }
  58949. if (inputDeviceDropDown != 0)
  58950. {
  58951. inputDeviceDropDown->setBounds (lx, y, w, h);
  58952. inputLevelMeter->setBounds (proportionOfWidth (0.77f),
  58953. inputDeviceDropDown->getY(),
  58954. proportionOfWidth (0.18f),
  58955. h);
  58956. y += dh;
  58957. }
  58958. const int maxBoxHeight = 100;//(getHeight() - y - dh * 2) / numBoxes;
  58959. if (outputChanList != 0)
  58960. {
  58961. const int bh = outputChanList->getBestHeight (maxBoxHeight);
  58962. outputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  58963. y += bh + space;
  58964. }
  58965. if (inputChanList != 0)
  58966. {
  58967. const int bh = inputChanList->getBestHeight (maxBoxHeight);
  58968. inputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  58969. y += bh + space;
  58970. }
  58971. y += space * 2;
  58972. if (showAdvancedSettingsButton != 0)
  58973. {
  58974. showAdvancedSettingsButton->changeWidthToFitText (h);
  58975. showAdvancedSettingsButton->setTopLeftPosition (lx, y);
  58976. }
  58977. if (sampleRateDropDown != 0)
  58978. {
  58979. sampleRateDropDown->setVisible (showAdvancedSettingsButton == 0
  58980. || ! showAdvancedSettingsButton->isVisible());
  58981. sampleRateDropDown->setBounds (lx, y, w, h);
  58982. y += dh;
  58983. }
  58984. if (bufferSizeDropDown != 0)
  58985. {
  58986. bufferSizeDropDown->setVisible (showAdvancedSettingsButton == 0
  58987. || ! showAdvancedSettingsButton->isVisible());
  58988. bufferSizeDropDown->setBounds (lx, y, w, h);
  58989. y += dh;
  58990. }
  58991. if (showUIButton != 0)
  58992. {
  58993. showUIButton->setVisible (showAdvancedSettingsButton == 0
  58994. || ! showAdvancedSettingsButton->isVisible());
  58995. showUIButton->changeWidthToFitText (h);
  58996. showUIButton->setTopLeftPosition (lx, y);
  58997. }
  58998. }
  58999. void comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  59000. {
  59001. if (comboBoxThatHasChanged == 0)
  59002. return;
  59003. AudioDeviceManager::AudioDeviceSetup config;
  59004. setup.manager->getAudioDeviceSetup (config);
  59005. String error;
  59006. if (comboBoxThatHasChanged == outputDeviceDropDown
  59007. || comboBoxThatHasChanged == inputDeviceDropDown)
  59008. {
  59009. if (outputDeviceDropDown != 0)
  59010. config.outputDeviceName = outputDeviceDropDown->getSelectedId() < 0 ? String::empty
  59011. : outputDeviceDropDown->getText();
  59012. if (inputDeviceDropDown != 0)
  59013. config.inputDeviceName = inputDeviceDropDown->getSelectedId() < 0 ? String::empty
  59014. : inputDeviceDropDown->getText();
  59015. if (! type->hasSeparateInputsAndOutputs())
  59016. config.inputDeviceName = config.outputDeviceName;
  59017. if (comboBoxThatHasChanged == inputDeviceDropDown)
  59018. config.useDefaultInputChannels = true;
  59019. else
  59020. config.useDefaultOutputChannels = true;
  59021. error = setup.manager->setAudioDeviceSetup (config, true);
  59022. showCorrectDeviceName (inputDeviceDropDown, true);
  59023. showCorrectDeviceName (outputDeviceDropDown, false);
  59024. updateControlPanelButton();
  59025. resized();
  59026. }
  59027. else if (comboBoxThatHasChanged == sampleRateDropDown)
  59028. {
  59029. if (sampleRateDropDown->getSelectedId() > 0)
  59030. {
  59031. config.sampleRate = sampleRateDropDown->getSelectedId();
  59032. error = setup.manager->setAudioDeviceSetup (config, true);
  59033. }
  59034. }
  59035. else if (comboBoxThatHasChanged == bufferSizeDropDown)
  59036. {
  59037. if (bufferSizeDropDown->getSelectedId() > 0)
  59038. {
  59039. config.bufferSize = bufferSizeDropDown->getSelectedId();
  59040. error = setup.manager->setAudioDeviceSetup (config, true);
  59041. }
  59042. }
  59043. if (error.isNotEmpty())
  59044. {
  59045. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  59046. "Error when trying to open audio device!",
  59047. error);
  59048. }
  59049. }
  59050. void buttonClicked (Button* button)
  59051. {
  59052. if (button == showAdvancedSettingsButton)
  59053. {
  59054. showAdvancedSettingsButton->setVisible (false);
  59055. resized();
  59056. }
  59057. else if (button == showUIButton)
  59058. {
  59059. AudioIODevice* const device = setup.manager->getCurrentAudioDevice();
  59060. if (device != 0 && device->showControlPanel())
  59061. {
  59062. setup.manager->closeAudioDevice();
  59063. setup.manager->restartLastAudioDevice();
  59064. getTopLevelComponent()->toFront (true);
  59065. }
  59066. }
  59067. else if (button == testButton && testButton != 0)
  59068. {
  59069. setup.manager->playTestSound();
  59070. }
  59071. }
  59072. void updateControlPanelButton()
  59073. {
  59074. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  59075. showUIButton = 0;
  59076. if (currentDevice != 0 && currentDevice->hasControlPanel())
  59077. {
  59078. addAndMakeVisible (showUIButton = new TextButton (TRANS ("show this device's control panel"),
  59079. TRANS ("opens the device's own control panel")));
  59080. showUIButton->addButtonListener (this);
  59081. }
  59082. resized();
  59083. }
  59084. void changeListenerCallback (void*)
  59085. {
  59086. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  59087. if (setup.maxNumOutputChannels > 0 || ! type->hasSeparateInputsAndOutputs())
  59088. {
  59089. if (outputDeviceDropDown == 0)
  59090. {
  59091. outputDeviceDropDown = new ComboBox (String::empty);
  59092. outputDeviceDropDown->addListener (this);
  59093. addAndMakeVisible (outputDeviceDropDown);
  59094. outputDeviceLabel = new Label (String::empty,
  59095. type->hasSeparateInputsAndOutputs() ? TRANS ("output:")
  59096. : TRANS ("device:"));
  59097. outputDeviceLabel->attachToComponent (outputDeviceDropDown, true);
  59098. if (setup.maxNumOutputChannels > 0)
  59099. {
  59100. addAndMakeVisible (testButton = new TextButton (TRANS ("Test")));
  59101. testButton->addButtonListener (this);
  59102. }
  59103. }
  59104. addNamesToDeviceBox (*outputDeviceDropDown, false);
  59105. }
  59106. if (setup.maxNumInputChannels > 0 && type->hasSeparateInputsAndOutputs())
  59107. {
  59108. if (inputDeviceDropDown == 0)
  59109. {
  59110. inputDeviceDropDown = new ComboBox (String::empty);
  59111. inputDeviceDropDown->addListener (this);
  59112. addAndMakeVisible (inputDeviceDropDown);
  59113. inputDeviceLabel = new Label (String::empty, TRANS ("input:"));
  59114. inputDeviceLabel->attachToComponent (inputDeviceDropDown, true);
  59115. addAndMakeVisible (inputLevelMeter
  59116. = new SimpleDeviceManagerInputLevelMeter (setup.manager));
  59117. }
  59118. addNamesToDeviceBox (*inputDeviceDropDown, true);
  59119. }
  59120. updateControlPanelButton();
  59121. showCorrectDeviceName (inputDeviceDropDown, true);
  59122. showCorrectDeviceName (outputDeviceDropDown, false);
  59123. if (currentDevice != 0)
  59124. {
  59125. if (setup.maxNumOutputChannels > 0
  59126. && setup.minNumOutputChannels < setup.manager->getCurrentAudioDevice()->getOutputChannelNames().size())
  59127. {
  59128. if (outputChanList == 0)
  59129. {
  59130. addAndMakeVisible (outputChanList
  59131. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioOutputType,
  59132. TRANS ("(no audio output channels found)")));
  59133. outputChanLabel = new Label (String::empty, TRANS ("active output channels:"));
  59134. outputChanLabel->attachToComponent (outputChanList, true);
  59135. }
  59136. outputChanList->refresh();
  59137. }
  59138. else
  59139. {
  59140. outputChanLabel = 0;
  59141. outputChanList = 0;
  59142. }
  59143. if (setup.maxNumInputChannels > 0
  59144. && setup.minNumInputChannels < setup.manager->getCurrentAudioDevice()->getInputChannelNames().size())
  59145. {
  59146. if (inputChanList == 0)
  59147. {
  59148. addAndMakeVisible (inputChanList
  59149. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioInputType,
  59150. TRANS ("(no audio input channels found)")));
  59151. inputChanLabel = new Label (String::empty, TRANS ("active input channels:"));
  59152. inputChanLabel->attachToComponent (inputChanList, true);
  59153. }
  59154. inputChanList->refresh();
  59155. }
  59156. else
  59157. {
  59158. inputChanLabel = 0;
  59159. inputChanList = 0;
  59160. }
  59161. // sample rate..
  59162. {
  59163. if (sampleRateDropDown == 0)
  59164. {
  59165. addAndMakeVisible (sampleRateDropDown = new ComboBox (String::empty));
  59166. sampleRateLabel = new Label (String::empty, TRANS ("sample rate:"));
  59167. sampleRateLabel->attachToComponent (sampleRateDropDown, true);
  59168. }
  59169. else
  59170. {
  59171. sampleRateDropDown->clear();
  59172. sampleRateDropDown->removeListener (this);
  59173. }
  59174. const int numRates = currentDevice->getNumSampleRates();
  59175. for (int i = 0; i < numRates; ++i)
  59176. {
  59177. const int rate = roundToInt (currentDevice->getSampleRate (i));
  59178. sampleRateDropDown->addItem (String (rate) + " Hz", rate);
  59179. }
  59180. sampleRateDropDown->setSelectedId (roundToInt (currentDevice->getCurrentSampleRate()), true);
  59181. sampleRateDropDown->addListener (this);
  59182. }
  59183. // buffer size
  59184. {
  59185. if (bufferSizeDropDown == 0)
  59186. {
  59187. addAndMakeVisible (bufferSizeDropDown = new ComboBox (String::empty));
  59188. bufferSizeLabel = new Label (String::empty, TRANS ("audio buffer size:"));
  59189. bufferSizeLabel->attachToComponent (bufferSizeDropDown, true);
  59190. }
  59191. else
  59192. {
  59193. bufferSizeDropDown->clear();
  59194. bufferSizeDropDown->removeListener (this);
  59195. }
  59196. const int numBufferSizes = currentDevice->getNumBufferSizesAvailable();
  59197. double currentRate = currentDevice->getCurrentSampleRate();
  59198. if (currentRate == 0)
  59199. currentRate = 48000.0;
  59200. for (int i = 0; i < numBufferSizes; ++i)
  59201. {
  59202. const int bs = currentDevice->getBufferSizeSamples (i);
  59203. bufferSizeDropDown->addItem (String (bs)
  59204. + " samples ("
  59205. + String (bs * 1000.0 / currentRate, 1)
  59206. + " ms)",
  59207. bs);
  59208. }
  59209. bufferSizeDropDown->setSelectedId (currentDevice->getCurrentBufferSizeSamples(), true);
  59210. bufferSizeDropDown->addListener (this);
  59211. }
  59212. }
  59213. else
  59214. {
  59215. jassert (setup.manager->getCurrentAudioDevice() == 0); // not the correct device type!
  59216. sampleRateLabel = 0;
  59217. bufferSizeLabel = 0;
  59218. sampleRateDropDown = 0;
  59219. bufferSizeDropDown = 0;
  59220. if (outputDeviceDropDown != 0)
  59221. outputDeviceDropDown->setSelectedId (-1, true);
  59222. if (inputDeviceDropDown != 0)
  59223. inputDeviceDropDown->setSelectedId (-1, true);
  59224. }
  59225. resized();
  59226. setSize (getWidth(), getLowestY() + 4);
  59227. }
  59228. private:
  59229. AudioIODeviceType* const type;
  59230. const AudioIODeviceType::DeviceSetupDetails setup;
  59231. ScopedPointer<ComboBox> outputDeviceDropDown, inputDeviceDropDown, sampleRateDropDown, bufferSizeDropDown;
  59232. ScopedPointer<Label> outputDeviceLabel, inputDeviceLabel, sampleRateLabel, bufferSizeLabel, inputChanLabel, outputChanLabel;
  59233. ScopedPointer<TextButton> testButton;
  59234. ScopedPointer<Component> inputLevelMeter;
  59235. ScopedPointer<TextButton> showUIButton, showAdvancedSettingsButton;
  59236. void showCorrectDeviceName (ComboBox* const box, const bool isInput)
  59237. {
  59238. if (box != 0)
  59239. {
  59240. AudioIODevice* const currentDevice = dynamic_cast <AudioIODevice*> (setup.manager->getCurrentAudioDevice());
  59241. const int index = type->getIndexOfDevice (currentDevice, isInput);
  59242. box->setSelectedId (index + 1, true);
  59243. if (testButton != 0 && ! isInput)
  59244. testButton->setEnabled (index >= 0);
  59245. }
  59246. }
  59247. void addNamesToDeviceBox (ComboBox& combo, bool isInputs)
  59248. {
  59249. const StringArray devs (type->getDeviceNames (isInputs));
  59250. combo.clear (true);
  59251. for (int i = 0; i < devs.size(); ++i)
  59252. combo.addItem (devs[i], i + 1);
  59253. combo.addItem (TRANS("<< none >>"), -1);
  59254. combo.setSelectedId (-1, true);
  59255. }
  59256. int getLowestY() const
  59257. {
  59258. int y = 0;
  59259. for (int i = getNumChildComponents(); --i >= 0;)
  59260. y = jmax (y, getChildComponent (i)->getBottom());
  59261. return y;
  59262. }
  59263. public:
  59264. class ChannelSelectorListBox : public ListBox,
  59265. public ListBoxModel
  59266. {
  59267. public:
  59268. enum BoxType
  59269. {
  59270. audioInputType,
  59271. audioOutputType
  59272. };
  59273. ChannelSelectorListBox (const AudioIODeviceType::DeviceSetupDetails& setup_,
  59274. const BoxType type_,
  59275. const String& noItemsMessage_)
  59276. : ListBox (String::empty, 0),
  59277. setup (setup_),
  59278. type (type_),
  59279. noItemsMessage (noItemsMessage_)
  59280. {
  59281. refresh();
  59282. setModel (this);
  59283. setOutlineThickness (1);
  59284. }
  59285. ~ChannelSelectorListBox()
  59286. {
  59287. }
  59288. void refresh()
  59289. {
  59290. items.clear();
  59291. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  59292. if (currentDevice != 0)
  59293. {
  59294. if (type == audioInputType)
  59295. items = currentDevice->getInputChannelNames();
  59296. else if (type == audioOutputType)
  59297. items = currentDevice->getOutputChannelNames();
  59298. if (setup.useStereoPairs)
  59299. {
  59300. StringArray pairs;
  59301. for (int i = 0; i < items.size(); i += 2)
  59302. {
  59303. const String name (items[i]);
  59304. const String name2 (items[i + 1]);
  59305. String commonBit;
  59306. for (int j = 0; j < name.length(); ++j)
  59307. if (name.substring (0, j).equalsIgnoreCase (name2.substring (0, j)))
  59308. commonBit = name.substring (0, j);
  59309. // Make sure we only split the name at a space, because otherwise, things
  59310. // like "input 11" + "input 12" would become "input 11 + 2"
  59311. while (commonBit.isNotEmpty() && ! CharacterFunctions::isWhitespace (commonBit.getLastCharacter()))
  59312. commonBit = commonBit.dropLastCharacters (1);
  59313. pairs.add (name.trim() + " + " + name2.substring (commonBit.length()).trim());
  59314. }
  59315. items = pairs;
  59316. }
  59317. }
  59318. updateContent();
  59319. repaint();
  59320. }
  59321. int getNumRows()
  59322. {
  59323. return items.size();
  59324. }
  59325. void paintListBoxItem (int row,
  59326. Graphics& g,
  59327. int width, int height,
  59328. bool rowIsSelected)
  59329. {
  59330. if (((unsigned int) row) < (unsigned int) items.size())
  59331. {
  59332. if (rowIsSelected)
  59333. g.fillAll (findColour (TextEditor::highlightColourId)
  59334. .withMultipliedAlpha (0.3f));
  59335. const String item (items [row]);
  59336. bool enabled = false;
  59337. AudioDeviceManager::AudioDeviceSetup config;
  59338. setup.manager->getAudioDeviceSetup (config);
  59339. if (setup.useStereoPairs)
  59340. {
  59341. if (type == audioInputType)
  59342. enabled = config.inputChannels [row * 2] || config.inputChannels [row * 2 + 1];
  59343. else if (type == audioOutputType)
  59344. enabled = config.outputChannels [row * 2] || config.outputChannels [row * 2 + 1];
  59345. }
  59346. else
  59347. {
  59348. if (type == audioInputType)
  59349. enabled = config.inputChannels [row];
  59350. else if (type == audioOutputType)
  59351. enabled = config.outputChannels [row];
  59352. }
  59353. const int x = getTickX();
  59354. const float tickW = height * 0.75f;
  59355. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  59356. enabled, true, true, false);
  59357. g.setFont (height * 0.6f);
  59358. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  59359. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  59360. }
  59361. }
  59362. void listBoxItemClicked (int row, const MouseEvent& e)
  59363. {
  59364. selectRow (row);
  59365. if (e.x < getTickX())
  59366. flipEnablement (row);
  59367. }
  59368. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  59369. {
  59370. flipEnablement (row);
  59371. }
  59372. void returnKeyPressed (int row)
  59373. {
  59374. flipEnablement (row);
  59375. }
  59376. void paint (Graphics& g)
  59377. {
  59378. ListBox::paint (g);
  59379. if (items.size() == 0)
  59380. {
  59381. g.setColour (Colours::grey);
  59382. g.setFont (13.0f);
  59383. g.drawText (noItemsMessage,
  59384. 0, 0, getWidth(), getHeight() / 2,
  59385. Justification::centred, true);
  59386. }
  59387. }
  59388. int getBestHeight (int maxHeight)
  59389. {
  59390. return getRowHeight() * jlimit (2, jmax (2, maxHeight / getRowHeight()),
  59391. getNumRows())
  59392. + getOutlineThickness() * 2;
  59393. }
  59394. juce_UseDebuggingNewOperator
  59395. private:
  59396. const AudioIODeviceType::DeviceSetupDetails setup;
  59397. const BoxType type;
  59398. const String noItemsMessage;
  59399. StringArray items;
  59400. void flipEnablement (const int row)
  59401. {
  59402. jassert (type == audioInputType || type == audioOutputType);
  59403. if (((unsigned int) row) < (unsigned int) items.size())
  59404. {
  59405. AudioDeviceManager::AudioDeviceSetup config;
  59406. setup.manager->getAudioDeviceSetup (config);
  59407. if (setup.useStereoPairs)
  59408. {
  59409. BigInteger bits;
  59410. BigInteger& original = (type == audioInputType ? config.inputChannels
  59411. : config.outputChannels);
  59412. int i;
  59413. for (i = 0; i < 256; i += 2)
  59414. bits.setBit (i / 2, original [i] || original [i + 1]);
  59415. if (type == audioInputType)
  59416. {
  59417. config.useDefaultInputChannels = false;
  59418. flipBit (bits, row, setup.minNumInputChannels / 2, setup.maxNumInputChannels / 2);
  59419. }
  59420. else
  59421. {
  59422. config.useDefaultOutputChannels = false;
  59423. flipBit (bits, row, setup.minNumOutputChannels / 2, setup.maxNumOutputChannels / 2);
  59424. }
  59425. for (i = 0; i < 256; ++i)
  59426. original.setBit (i, bits [i / 2]);
  59427. }
  59428. else
  59429. {
  59430. if (type == audioInputType)
  59431. {
  59432. config.useDefaultInputChannels = false;
  59433. flipBit (config.inputChannels, row, setup.minNumInputChannels, setup.maxNumInputChannels);
  59434. }
  59435. else
  59436. {
  59437. config.useDefaultOutputChannels = false;
  59438. flipBit (config.outputChannels, row, setup.minNumOutputChannels, setup.maxNumOutputChannels);
  59439. }
  59440. }
  59441. String error (setup.manager->setAudioDeviceSetup (config, true));
  59442. if (! error.isEmpty())
  59443. {
  59444. //xxx
  59445. }
  59446. }
  59447. }
  59448. static void flipBit (BigInteger& chans, int index, int minNumber, int maxNumber)
  59449. {
  59450. const int numActive = chans.countNumberOfSetBits();
  59451. if (chans [index])
  59452. {
  59453. if (numActive > minNumber)
  59454. chans.setBit (index, false);
  59455. }
  59456. else
  59457. {
  59458. if (numActive >= maxNumber)
  59459. {
  59460. const int firstActiveChan = chans.findNextSetBit();
  59461. chans.setBit (index > firstActiveChan
  59462. ? firstActiveChan : chans.getHighestBit(),
  59463. false);
  59464. }
  59465. chans.setBit (index, true);
  59466. }
  59467. }
  59468. int getTickX() const
  59469. {
  59470. return getRowHeight() + 5;
  59471. }
  59472. ChannelSelectorListBox (const ChannelSelectorListBox&);
  59473. ChannelSelectorListBox& operator= (const ChannelSelectorListBox&);
  59474. };
  59475. private:
  59476. ScopedPointer<ChannelSelectorListBox> inputChanList, outputChanList;
  59477. AudioDeviceSettingsPanel (const AudioDeviceSettingsPanel&);
  59478. AudioDeviceSettingsPanel& operator= (const AudioDeviceSettingsPanel&);
  59479. };
  59480. AudioDeviceSelectorComponent::AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager_,
  59481. const int minInputChannels_,
  59482. const int maxInputChannels_,
  59483. const int minOutputChannels_,
  59484. const int maxOutputChannels_,
  59485. const bool showMidiInputOptions,
  59486. const bool showMidiOutputSelector,
  59487. const bool showChannelsAsStereoPairs_,
  59488. const bool hideAdvancedOptionsWithButton_)
  59489. : deviceManager (deviceManager_),
  59490. deviceTypeDropDown (0),
  59491. deviceTypeDropDownLabel (0),
  59492. minOutputChannels (minOutputChannels_),
  59493. maxOutputChannels (maxOutputChannels_),
  59494. minInputChannels (minInputChannels_),
  59495. maxInputChannels (maxInputChannels_),
  59496. showChannelsAsStereoPairs (showChannelsAsStereoPairs_),
  59497. hideAdvancedOptionsWithButton (hideAdvancedOptionsWithButton_)
  59498. {
  59499. jassert (minOutputChannels >= 0 && minOutputChannels <= maxOutputChannels);
  59500. jassert (minInputChannels >= 0 && minInputChannels <= maxInputChannels);
  59501. if (deviceManager_.getAvailableDeviceTypes().size() > 1)
  59502. {
  59503. deviceTypeDropDown = new ComboBox (String::empty);
  59504. for (int i = 0; i < deviceManager_.getAvailableDeviceTypes().size(); ++i)
  59505. {
  59506. deviceTypeDropDown
  59507. ->addItem (deviceManager_.getAvailableDeviceTypes().getUnchecked(i)->getTypeName(),
  59508. i + 1);
  59509. }
  59510. addAndMakeVisible (deviceTypeDropDown);
  59511. deviceTypeDropDown->addListener (this);
  59512. deviceTypeDropDownLabel = new Label (String::empty, TRANS ("audio device type:"));
  59513. deviceTypeDropDownLabel->setJustificationType (Justification::centredRight);
  59514. deviceTypeDropDownLabel->attachToComponent (deviceTypeDropDown, true);
  59515. }
  59516. if (showMidiInputOptions)
  59517. {
  59518. addAndMakeVisible (midiInputsList
  59519. = new MidiInputSelectorComponentListBox (deviceManager,
  59520. TRANS("(no midi inputs available)"),
  59521. 0, 0));
  59522. midiInputsLabel = new Label (String::empty, TRANS ("active midi inputs:"));
  59523. midiInputsLabel->setJustificationType (Justification::topRight);
  59524. midiInputsLabel->attachToComponent (midiInputsList, true);
  59525. }
  59526. else
  59527. {
  59528. midiInputsList = 0;
  59529. midiInputsLabel = 0;
  59530. }
  59531. if (showMidiOutputSelector)
  59532. {
  59533. addAndMakeVisible (midiOutputSelector = new ComboBox (String::empty));
  59534. midiOutputSelector->addListener (this);
  59535. midiOutputLabel = new Label ("lm", TRANS("Midi Output:"));
  59536. midiOutputLabel->attachToComponent (midiOutputSelector, true);
  59537. }
  59538. else
  59539. {
  59540. midiOutputSelector = 0;
  59541. midiOutputLabel = 0;
  59542. }
  59543. deviceManager_.addChangeListener (this);
  59544. changeListenerCallback (0);
  59545. }
  59546. AudioDeviceSelectorComponent::~AudioDeviceSelectorComponent()
  59547. {
  59548. deviceManager.removeChangeListener (this);
  59549. }
  59550. void AudioDeviceSelectorComponent::resized()
  59551. {
  59552. const int lx = proportionOfWidth (0.35f);
  59553. const int w = proportionOfWidth (0.4f);
  59554. const int h = 24;
  59555. const int space = 6;
  59556. const int dh = h + space;
  59557. int y = 15;
  59558. if (deviceTypeDropDown != 0)
  59559. {
  59560. deviceTypeDropDown->setBounds (lx, y, proportionOfWidth (0.3f), h);
  59561. y += dh + space * 2;
  59562. }
  59563. if (audioDeviceSettingsComp != 0)
  59564. {
  59565. audioDeviceSettingsComp->setBounds (0, y, getWidth(), audioDeviceSettingsComp->getHeight());
  59566. y += audioDeviceSettingsComp->getHeight() + space;
  59567. }
  59568. if (midiInputsList != 0)
  59569. {
  59570. const int bh = midiInputsList->getBestHeight (jmin (h * 8, getHeight() - y - space - h));
  59571. midiInputsList->setBounds (lx, y, w, bh);
  59572. y += bh + space;
  59573. }
  59574. if (midiOutputSelector != 0)
  59575. midiOutputSelector->setBounds (lx, y, w, h);
  59576. }
  59577. void AudioDeviceSelectorComponent::childBoundsChanged (Component* child)
  59578. {
  59579. if (child == audioDeviceSettingsComp)
  59580. resized();
  59581. }
  59582. void AudioDeviceSelectorComponent::buttonClicked (Button*)
  59583. {
  59584. AudioIODevice* const device = deviceManager.getCurrentAudioDevice();
  59585. if (device != 0 && device->hasControlPanel())
  59586. {
  59587. if (device->showControlPanel())
  59588. deviceManager.restartLastAudioDevice();
  59589. getTopLevelComponent()->toFront (true);
  59590. }
  59591. }
  59592. void AudioDeviceSelectorComponent::comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  59593. {
  59594. if (comboBoxThatHasChanged == deviceTypeDropDown)
  59595. {
  59596. AudioIODeviceType* const type = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown->getSelectedId() - 1];
  59597. if (type != 0)
  59598. {
  59599. audioDeviceSettingsComp = 0;
  59600. deviceManager.setCurrentAudioDeviceType (type->getTypeName(), true);
  59601. changeListenerCallback (0); // needed in case the type hasn't actally changed
  59602. }
  59603. }
  59604. else if (comboBoxThatHasChanged == midiOutputSelector)
  59605. {
  59606. deviceManager.setDefaultMidiOutput (midiOutputSelector->getText());
  59607. }
  59608. }
  59609. void AudioDeviceSelectorComponent::changeListenerCallback (void*)
  59610. {
  59611. if (deviceTypeDropDown != 0)
  59612. {
  59613. deviceTypeDropDown->setText (deviceManager.getCurrentAudioDeviceType(), false);
  59614. }
  59615. if (audioDeviceSettingsComp == 0
  59616. || audioDeviceSettingsCompType != deviceManager.getCurrentAudioDeviceType())
  59617. {
  59618. audioDeviceSettingsCompType = deviceManager.getCurrentAudioDeviceType();
  59619. audioDeviceSettingsComp = 0;
  59620. AudioIODeviceType* const type
  59621. = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown == 0
  59622. ? 0 : deviceTypeDropDown->getSelectedId() - 1];
  59623. if (type != 0)
  59624. {
  59625. AudioIODeviceType::DeviceSetupDetails details;
  59626. details.manager = &deviceManager;
  59627. details.minNumInputChannels = minInputChannels;
  59628. details.maxNumInputChannels = maxInputChannels;
  59629. details.minNumOutputChannels = minOutputChannels;
  59630. details.maxNumOutputChannels = maxOutputChannels;
  59631. details.useStereoPairs = showChannelsAsStereoPairs;
  59632. audioDeviceSettingsComp = new AudioDeviceSettingsPanel (type, details, hideAdvancedOptionsWithButton);
  59633. if (audioDeviceSettingsComp != 0)
  59634. {
  59635. addAndMakeVisible (audioDeviceSettingsComp);
  59636. audioDeviceSettingsComp->resized();
  59637. }
  59638. }
  59639. }
  59640. if (midiInputsList != 0)
  59641. {
  59642. midiInputsList->updateContent();
  59643. midiInputsList->repaint();
  59644. }
  59645. if (midiOutputSelector != 0)
  59646. {
  59647. midiOutputSelector->clear();
  59648. const StringArray midiOuts (MidiOutput::getDevices());
  59649. midiOutputSelector->addItem (TRANS("<< none >>"), -1);
  59650. midiOutputSelector->addSeparator();
  59651. for (int i = 0; i < midiOuts.size(); ++i)
  59652. midiOutputSelector->addItem (midiOuts[i], i + 1);
  59653. int current = -1;
  59654. if (deviceManager.getDefaultMidiOutput() != 0)
  59655. current = 1 + midiOuts.indexOf (deviceManager.getDefaultMidiOutputName());
  59656. midiOutputSelector->setSelectedId (current, true);
  59657. }
  59658. resized();
  59659. }
  59660. END_JUCE_NAMESPACE
  59661. /*** End of inlined file: juce_AudioDeviceSelectorComponent.cpp ***/
  59662. /*** Start of inlined file: juce_BubbleComponent.cpp ***/
  59663. BEGIN_JUCE_NAMESPACE
  59664. BubbleComponent::BubbleComponent()
  59665. : side (0),
  59666. allowablePlacements (above | below | left | right),
  59667. arrowTipX (0.0f),
  59668. arrowTipY (0.0f)
  59669. {
  59670. setInterceptsMouseClicks (false, false);
  59671. shadow.setShadowProperties (5.0f, 0.35f, 0, 0);
  59672. setComponentEffect (&shadow);
  59673. }
  59674. BubbleComponent::~BubbleComponent()
  59675. {
  59676. }
  59677. void BubbleComponent::paint (Graphics& g)
  59678. {
  59679. int x = content.getX();
  59680. int y = content.getY();
  59681. int w = content.getWidth();
  59682. int h = content.getHeight();
  59683. int cw, ch;
  59684. getContentSize (cw, ch);
  59685. if (side == 3)
  59686. x += w - cw;
  59687. else if (side != 1)
  59688. x += (w - cw) / 2;
  59689. w = cw;
  59690. if (side == 2)
  59691. y += h - ch;
  59692. else if (side != 0)
  59693. y += (h - ch) / 2;
  59694. h = ch;
  59695. getLookAndFeel().drawBubble (g, arrowTipX, arrowTipY,
  59696. (float) x, (float) y,
  59697. (float) w, (float) h);
  59698. const int cx = x + (w - cw) / 2;
  59699. const int cy = y + (h - ch) / 2;
  59700. const int indent = 3;
  59701. g.setOrigin (cx + indent, cy + indent);
  59702. g.reduceClipRegion (0, 0, cw - indent * 2, ch - indent * 2);
  59703. paintContent (g, cw - indent * 2, ch - indent * 2);
  59704. }
  59705. void BubbleComponent::setAllowedPlacement (const int newPlacement)
  59706. {
  59707. allowablePlacements = newPlacement;
  59708. }
  59709. void BubbleComponent::setPosition (Component* componentToPointTo)
  59710. {
  59711. jassert (componentToPointTo->isValidComponent());
  59712. Point<int> pos;
  59713. if (getParentComponent() != 0)
  59714. pos = componentToPointTo->relativePositionToOtherComponent (getParentComponent(), pos);
  59715. else
  59716. pos = componentToPointTo->relativePositionToGlobal (pos);
  59717. setPosition (Rectangle<int> (pos.getX(), pos.getY(), componentToPointTo->getWidth(), componentToPointTo->getHeight()));
  59718. }
  59719. void BubbleComponent::setPosition (const int arrowTipX_,
  59720. const int arrowTipY_)
  59721. {
  59722. setPosition (Rectangle<int> (arrowTipX_, arrowTipY_, 1, 1));
  59723. }
  59724. void BubbleComponent::setPosition (const Rectangle<int>& rectangleToPointTo)
  59725. {
  59726. Rectangle<int> availableSpace (getParentComponent() != 0 ? getParentComponent()->getLocalBounds()
  59727. : getParentMonitorArea());
  59728. int x = 0;
  59729. int y = 0;
  59730. int w = 150;
  59731. int h = 30;
  59732. getContentSize (w, h);
  59733. w += 30;
  59734. h += 30;
  59735. const float edgeIndent = 2.0f;
  59736. const int arrowLength = jmin (10, h / 3, w / 3);
  59737. int spaceAbove = ((allowablePlacements & above) != 0) ? jmax (0, rectangleToPointTo.getY() - availableSpace.getY()) : -1;
  59738. int spaceBelow = ((allowablePlacements & below) != 0) ? jmax (0, availableSpace.getBottom() - rectangleToPointTo.getBottom()) : -1;
  59739. int spaceLeft = ((allowablePlacements & left) != 0) ? jmax (0, rectangleToPointTo.getX() - availableSpace.getX()) : -1;
  59740. int spaceRight = ((allowablePlacements & right) != 0) ? jmax (0, availableSpace.getRight() - rectangleToPointTo.getRight()) : -1;
  59741. // look at whether the component is elongated, and if so, try to position next to its longer dimension.
  59742. if (rectangleToPointTo.getWidth() > rectangleToPointTo.getHeight() * 2
  59743. && (spaceAbove > h + 20 || spaceBelow > h + 20))
  59744. {
  59745. spaceLeft = spaceRight = 0;
  59746. }
  59747. else if (rectangleToPointTo.getWidth() < rectangleToPointTo.getHeight() / 2
  59748. && (spaceLeft > w + 20 || spaceRight > w + 20))
  59749. {
  59750. spaceAbove = spaceBelow = 0;
  59751. }
  59752. if (jmax (spaceAbove, spaceBelow) >= jmax (spaceLeft, spaceRight))
  59753. {
  59754. x = rectangleToPointTo.getX() + (rectangleToPointTo.getWidth() - w) / 2;
  59755. arrowTipX = w * 0.5f;
  59756. content.setSize (w, h - arrowLength);
  59757. if (spaceAbove >= spaceBelow)
  59758. {
  59759. // above
  59760. y = rectangleToPointTo.getY() - h;
  59761. content.setPosition (0, 0);
  59762. arrowTipY = h - edgeIndent;
  59763. side = 2;
  59764. }
  59765. else
  59766. {
  59767. // below
  59768. y = rectangleToPointTo.getBottom();
  59769. content.setPosition (0, arrowLength);
  59770. arrowTipY = edgeIndent;
  59771. side = 0;
  59772. }
  59773. }
  59774. else
  59775. {
  59776. y = rectangleToPointTo.getY() + (rectangleToPointTo.getHeight() - h) / 2;
  59777. arrowTipY = h * 0.5f;
  59778. content.setSize (w - arrowLength, h);
  59779. if (spaceLeft > spaceRight)
  59780. {
  59781. // on the left
  59782. x = rectangleToPointTo.getX() - w;
  59783. content.setPosition (0, 0);
  59784. arrowTipX = w - edgeIndent;
  59785. side = 3;
  59786. }
  59787. else
  59788. {
  59789. // on the right
  59790. x = rectangleToPointTo.getRight();
  59791. content.setPosition (arrowLength, 0);
  59792. arrowTipX = edgeIndent;
  59793. side = 1;
  59794. }
  59795. }
  59796. setBounds (x, y, w, h);
  59797. }
  59798. END_JUCE_NAMESPACE
  59799. /*** End of inlined file: juce_BubbleComponent.cpp ***/
  59800. /*** Start of inlined file: juce_BubbleMessageComponent.cpp ***/
  59801. BEGIN_JUCE_NAMESPACE
  59802. BubbleMessageComponent::BubbleMessageComponent (int fadeOutLengthMs)
  59803. : fadeOutLength (fadeOutLengthMs),
  59804. deleteAfterUse (false)
  59805. {
  59806. }
  59807. BubbleMessageComponent::~BubbleMessageComponent()
  59808. {
  59809. Desktop::getInstance().getAnimator().fadeOut (this, fadeOutLength);
  59810. }
  59811. void BubbleMessageComponent::showAt (int x, int y,
  59812. const String& text,
  59813. const int numMillisecondsBeforeRemoving,
  59814. const bool removeWhenMouseClicked,
  59815. const bool deleteSelfAfterUse)
  59816. {
  59817. textLayout.clear();
  59818. textLayout.setText (text, Font (14.0f));
  59819. textLayout.layout (256, Justification::centredLeft, true);
  59820. setPosition (x, y);
  59821. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  59822. }
  59823. void BubbleMessageComponent::showAt (Component* const component,
  59824. const String& text,
  59825. const int numMillisecondsBeforeRemoving,
  59826. const bool removeWhenMouseClicked,
  59827. const bool deleteSelfAfterUse)
  59828. {
  59829. textLayout.clear();
  59830. textLayout.setText (text, Font (14.0f));
  59831. textLayout.layout (256, Justification::centredLeft, true);
  59832. setPosition (component);
  59833. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  59834. }
  59835. void BubbleMessageComponent::init (const int numMillisecondsBeforeRemoving,
  59836. const bool removeWhenMouseClicked,
  59837. const bool deleteSelfAfterUse)
  59838. {
  59839. setVisible (true);
  59840. deleteAfterUse = deleteSelfAfterUse;
  59841. if (numMillisecondsBeforeRemoving > 0)
  59842. expiryTime = Time::getMillisecondCounter() + numMillisecondsBeforeRemoving;
  59843. else
  59844. expiryTime = 0;
  59845. startTimer (77);
  59846. mouseClickCounter = Desktop::getInstance().getMouseButtonClickCounter();
  59847. if (! (removeWhenMouseClicked && isShowing()))
  59848. mouseClickCounter += 0xfffff;
  59849. repaint();
  59850. }
  59851. void BubbleMessageComponent::getContentSize (int& w, int& h)
  59852. {
  59853. w = textLayout.getWidth() + 16;
  59854. h = textLayout.getHeight() + 16;
  59855. }
  59856. void BubbleMessageComponent::paintContent (Graphics& g, int w, int h)
  59857. {
  59858. g.setColour (findColour (TooltipWindow::textColourId));
  59859. textLayout.drawWithin (g, 0, 0, w, h, Justification::centred);
  59860. }
  59861. void BubbleMessageComponent::timerCallback()
  59862. {
  59863. if (Desktop::getInstance().getMouseButtonClickCounter() > mouseClickCounter)
  59864. {
  59865. stopTimer();
  59866. setVisible (false);
  59867. if (deleteAfterUse)
  59868. delete this;
  59869. }
  59870. else if (expiryTime != 0 && Time::getMillisecondCounter() > expiryTime)
  59871. {
  59872. stopTimer();
  59873. if (deleteAfterUse)
  59874. delete this;
  59875. else
  59876. Desktop::getInstance().getAnimator().fadeOut (this, fadeOutLength);
  59877. }
  59878. }
  59879. END_JUCE_NAMESPACE
  59880. /*** End of inlined file: juce_BubbleMessageComponent.cpp ***/
  59881. /*** Start of inlined file: juce_ColourSelector.cpp ***/
  59882. BEGIN_JUCE_NAMESPACE
  59883. class ColourComponentSlider : public Slider
  59884. {
  59885. public:
  59886. ColourComponentSlider (const String& name)
  59887. : Slider (name)
  59888. {
  59889. setRange (0.0, 255.0, 1.0);
  59890. }
  59891. const String getTextFromValue (double value)
  59892. {
  59893. return String::toHexString ((int) value).toUpperCase().paddedLeft ('0', 2);
  59894. }
  59895. double getValueFromText (const String& text)
  59896. {
  59897. return (double) text.getHexValue32();
  59898. }
  59899. private:
  59900. ColourComponentSlider (const ColourComponentSlider&);
  59901. ColourComponentSlider& operator= (const ColourComponentSlider&);
  59902. };
  59903. class ColourSpaceMarker : public Component
  59904. {
  59905. public:
  59906. ColourSpaceMarker()
  59907. {
  59908. setInterceptsMouseClicks (false, false);
  59909. }
  59910. void paint (Graphics& g)
  59911. {
  59912. g.setColour (Colour::greyLevel (0.1f));
  59913. g.drawEllipse (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 1.0f);
  59914. g.setColour (Colour::greyLevel (0.9f));
  59915. g.drawEllipse (2.0f, 2.0f, getWidth() - 4.0f, getHeight() - 4.0f, 1.0f);
  59916. }
  59917. private:
  59918. ColourSpaceMarker (const ColourSpaceMarker&);
  59919. ColourSpaceMarker& operator= (const ColourSpaceMarker&);
  59920. };
  59921. class ColourSelector::ColourSpaceView : public Component
  59922. {
  59923. public:
  59924. ColourSpaceView (ColourSelector& owner_,
  59925. float& h_, float& s_, float& v_,
  59926. const int edgeSize)
  59927. : owner (owner_),
  59928. h (h_), s (s_), v (v_),
  59929. lastHue (0.0f),
  59930. edge (edgeSize)
  59931. {
  59932. addAndMakeVisible (&marker);
  59933. setMouseCursor (MouseCursor::CrosshairCursor);
  59934. }
  59935. void paint (Graphics& g)
  59936. {
  59937. if (colours.isNull())
  59938. {
  59939. const int width = getWidth() / 2;
  59940. const int height = getHeight() / 2;
  59941. colours = Image (Image::RGB, width, height, false);
  59942. Image::BitmapData pixels (colours, true);
  59943. for (int y = 0; y < height; ++y)
  59944. {
  59945. const float val = 1.0f - y / (float) height;
  59946. for (int x = 0; x < width; ++x)
  59947. {
  59948. const float sat = x / (float) width;
  59949. pixels.setPixelColour (x, y, Colour (h, sat, val, 1.0f));
  59950. }
  59951. }
  59952. }
  59953. g.setOpacity (1.0f);
  59954. g.drawImage (colours, edge, edge, getWidth() - edge * 2, getHeight() - edge * 2,
  59955. 0, 0, colours.getWidth(), colours.getHeight());
  59956. }
  59957. void mouseDown (const MouseEvent& e)
  59958. {
  59959. mouseDrag (e);
  59960. }
  59961. void mouseDrag (const MouseEvent& e)
  59962. {
  59963. const float sat = (e.x - edge) / (float) (getWidth() - edge * 2);
  59964. const float val = 1.0f - (e.y - edge) / (float) (getHeight() - edge * 2);
  59965. owner.setSV (sat, val);
  59966. }
  59967. void updateIfNeeded()
  59968. {
  59969. if (lastHue != h)
  59970. {
  59971. lastHue = h;
  59972. colours = Image::null;
  59973. repaint();
  59974. }
  59975. updateMarker();
  59976. }
  59977. void resized()
  59978. {
  59979. colours = Image::null;
  59980. updateMarker();
  59981. }
  59982. private:
  59983. ColourSelector& owner;
  59984. float& h;
  59985. float& s;
  59986. float& v;
  59987. float lastHue;
  59988. ColourSpaceMarker marker;
  59989. const int edge;
  59990. Image colours;
  59991. void updateMarker()
  59992. {
  59993. marker.setBounds (roundToInt ((getWidth() - edge * 2) * s),
  59994. roundToInt ((getHeight() - edge * 2) * (1.0f - v)),
  59995. edge * 2, edge * 2);
  59996. }
  59997. ColourSpaceView (const ColourSpaceView&);
  59998. ColourSpaceView& operator= (const ColourSpaceView&);
  59999. };
  60000. class HueSelectorMarker : public Component
  60001. {
  60002. public:
  60003. HueSelectorMarker()
  60004. {
  60005. setInterceptsMouseClicks (false, false);
  60006. }
  60007. void paint (Graphics& g)
  60008. {
  60009. Path p;
  60010. p.addTriangle (1.0f, 1.0f,
  60011. getWidth() * 0.3f, getHeight() * 0.5f,
  60012. 1.0f, getHeight() - 1.0f);
  60013. p.addTriangle (getWidth() - 1.0f, 1.0f,
  60014. getWidth() * 0.7f, getHeight() * 0.5f,
  60015. getWidth() - 1.0f, getHeight() - 1.0f);
  60016. g.setColour (Colours::white.withAlpha (0.75f));
  60017. g.fillPath (p);
  60018. g.setColour (Colours::black.withAlpha (0.75f));
  60019. g.strokePath (p, PathStrokeType (1.2f));
  60020. }
  60021. private:
  60022. HueSelectorMarker (const HueSelectorMarker&);
  60023. HueSelectorMarker& operator= (const HueSelectorMarker&);
  60024. };
  60025. class ColourSelector::HueSelectorComp : public Component
  60026. {
  60027. public:
  60028. HueSelectorComp (ColourSelector& owner_,
  60029. float& h_, float& s_, float& v_,
  60030. const int edgeSize)
  60031. : owner (owner_),
  60032. h (h_), s (s_), v (v_),
  60033. lastHue (0.0f),
  60034. edge (edgeSize)
  60035. {
  60036. addAndMakeVisible (&marker);
  60037. }
  60038. void paint (Graphics& g)
  60039. {
  60040. const float yScale = 1.0f / (getHeight() - edge * 2);
  60041. const Rectangle<int> clip (g.getClipBounds());
  60042. for (int y = jmin (clip.getBottom(), getHeight() - edge); --y >= jmax (edge, clip.getY());)
  60043. {
  60044. g.setColour (Colour ((y - edge) * yScale, 1.0f, 1.0f, 1.0f));
  60045. g.fillRect (edge, y, getWidth() - edge * 2, 1);
  60046. }
  60047. }
  60048. void resized()
  60049. {
  60050. marker.setBounds (0, roundToInt ((getHeight() - edge * 2) * h),
  60051. getWidth(), edge * 2);
  60052. }
  60053. void mouseDown (const MouseEvent& e)
  60054. {
  60055. mouseDrag (e);
  60056. }
  60057. void mouseDrag (const MouseEvent& e)
  60058. {
  60059. const float hue = (e.y - edge) / (float) (getHeight() - edge * 2);
  60060. owner.setHue (hue);
  60061. }
  60062. void updateIfNeeded()
  60063. {
  60064. resized();
  60065. }
  60066. private:
  60067. ColourSelector& owner;
  60068. float& h;
  60069. float& s;
  60070. float& v;
  60071. float lastHue;
  60072. HueSelectorMarker marker;
  60073. const int edge;
  60074. HueSelectorComp (const HueSelectorComp&);
  60075. HueSelectorComp& operator= (const HueSelectorComp&);
  60076. };
  60077. class ColourSelector::SwatchComponent : public Component
  60078. {
  60079. public:
  60080. SwatchComponent (ColourSelector& owner_, int index_)
  60081. : owner (owner_), index (index_)
  60082. {
  60083. }
  60084. void paint (Graphics& g)
  60085. {
  60086. const Colour colour (owner.getSwatchColour (index));
  60087. g.fillCheckerBoard (getLocalBounds(), 6, 6,
  60088. Colour (0xffdddddd).overlaidWith (colour),
  60089. Colour (0xffffffff).overlaidWith (colour));
  60090. }
  60091. void mouseDown (const MouseEvent&)
  60092. {
  60093. PopupMenu m;
  60094. m.addItem (1, TRANS("Use this swatch as the current colour"));
  60095. m.addSeparator();
  60096. m.addItem (2, TRANS("Set this swatch to the current colour"));
  60097. const int r = m.showAt (this);
  60098. if (r == 1)
  60099. {
  60100. owner.setCurrentColour (owner.getSwatchColour (index));
  60101. }
  60102. else if (r == 2)
  60103. {
  60104. if (owner.getSwatchColour (index) != owner.getCurrentColour())
  60105. {
  60106. owner.setSwatchColour (index, owner.getCurrentColour());
  60107. repaint();
  60108. }
  60109. }
  60110. }
  60111. private:
  60112. ColourSelector& owner;
  60113. const int index;
  60114. SwatchComponent (const SwatchComponent&);
  60115. SwatchComponent& operator= (const SwatchComponent&);
  60116. };
  60117. ColourSelector::ColourSelector (const int flags_,
  60118. const int edgeGap_,
  60119. const int gapAroundColourSpaceComponent)
  60120. : colour (Colours::white),
  60121. colourSpace (0),
  60122. hueSelector (0),
  60123. flags (flags_),
  60124. edgeGap (edgeGap_)
  60125. {
  60126. // not much point having a selector with no components in it!
  60127. jassert ((flags_ & (showColourAtTop | showSliders | showColourspace)) != 0);
  60128. updateHSV();
  60129. if ((flags & showSliders) != 0)
  60130. {
  60131. addAndMakeVisible (sliders[0] = new ColourComponentSlider (TRANS ("red")));
  60132. addAndMakeVisible (sliders[1] = new ColourComponentSlider (TRANS ("green")));
  60133. addAndMakeVisible (sliders[2] = new ColourComponentSlider (TRANS ("blue")));
  60134. addChildComponent (sliders[3] = new ColourComponentSlider (TRANS ("alpha")));
  60135. sliders[3]->setVisible ((flags & showAlphaChannel) != 0);
  60136. for (int i = 4; --i >= 0;)
  60137. sliders[i]->addListener (this);
  60138. }
  60139. else
  60140. {
  60141. zeromem (sliders, sizeof (sliders));
  60142. }
  60143. if ((flags & showColourspace) != 0)
  60144. {
  60145. addAndMakeVisible (colourSpace = new ColourSpaceView (*this, h, s, v, gapAroundColourSpaceComponent));
  60146. addAndMakeVisible (hueSelector = new HueSelectorComp (*this, h, s, v, gapAroundColourSpaceComponent));
  60147. }
  60148. update();
  60149. }
  60150. ColourSelector::~ColourSelector()
  60151. {
  60152. dispatchPendingMessages();
  60153. swatchComponents.clear();
  60154. deleteAllChildren();
  60155. }
  60156. const Colour ColourSelector::getCurrentColour() const
  60157. {
  60158. return ((flags & showAlphaChannel) != 0) ? colour
  60159. : colour.withAlpha ((uint8) 0xff);
  60160. }
  60161. void ColourSelector::setCurrentColour (const Colour& c)
  60162. {
  60163. if (c != colour)
  60164. {
  60165. colour = ((flags & showAlphaChannel) != 0) ? c : c.withAlpha ((uint8) 0xff);
  60166. updateHSV();
  60167. update();
  60168. }
  60169. }
  60170. void ColourSelector::setHue (float newH)
  60171. {
  60172. newH = jlimit (0.0f, 1.0f, newH);
  60173. if (h != newH)
  60174. {
  60175. h = newH;
  60176. colour = Colour (h, s, v, colour.getFloatAlpha());
  60177. update();
  60178. }
  60179. }
  60180. void ColourSelector::setSV (float newS, float newV)
  60181. {
  60182. newS = jlimit (0.0f, 1.0f, newS);
  60183. newV = jlimit (0.0f, 1.0f, newV);
  60184. if (s != newS || v != newV)
  60185. {
  60186. s = newS;
  60187. v = newV;
  60188. colour = Colour (h, s, v, colour.getFloatAlpha());
  60189. update();
  60190. }
  60191. }
  60192. void ColourSelector::updateHSV()
  60193. {
  60194. colour.getHSB (h, s, v);
  60195. }
  60196. void ColourSelector::update()
  60197. {
  60198. if (sliders[0] != 0)
  60199. {
  60200. sliders[0]->setValue ((int) colour.getRed());
  60201. sliders[1]->setValue ((int) colour.getGreen());
  60202. sliders[2]->setValue ((int) colour.getBlue());
  60203. sliders[3]->setValue ((int) colour.getAlpha());
  60204. }
  60205. if (colourSpace != 0)
  60206. {
  60207. colourSpace->updateIfNeeded();
  60208. hueSelector->updateIfNeeded();
  60209. }
  60210. if ((flags & showColourAtTop) != 0)
  60211. repaint (previewArea);
  60212. sendChangeMessage (this);
  60213. }
  60214. void ColourSelector::paint (Graphics& g)
  60215. {
  60216. g.fillAll (findColour (backgroundColourId));
  60217. if ((flags & showColourAtTop) != 0)
  60218. {
  60219. const Colour currentColour (getCurrentColour());
  60220. g.fillCheckerBoard (previewArea, 10, 10,
  60221. Colour (0xffdddddd).overlaidWith (currentColour),
  60222. Colour (0xffffffff).overlaidWith (currentColour));
  60223. g.setColour (Colours::white.overlaidWith (currentColour).contrasting());
  60224. g.setFont (14.0f, true);
  60225. g.drawText (currentColour.toDisplayString ((flags & showAlphaChannel) != 0),
  60226. previewArea.getX(), previewArea.getY(), previewArea.getWidth(), previewArea.getHeight(),
  60227. Justification::centred, false);
  60228. }
  60229. if ((flags & showSliders) != 0)
  60230. {
  60231. g.setColour (findColour (labelTextColourId));
  60232. g.setFont (11.0f);
  60233. for (int i = 4; --i >= 0;)
  60234. {
  60235. if (sliders[i]->isVisible())
  60236. g.drawText (sliders[i]->getName() + ":",
  60237. 0, sliders[i]->getY(),
  60238. sliders[i]->getX() - 8, sliders[i]->getHeight(),
  60239. Justification::centredRight, false);
  60240. }
  60241. }
  60242. }
  60243. void ColourSelector::resized()
  60244. {
  60245. const int swatchesPerRow = 8;
  60246. const int swatchHeight = 22;
  60247. const int numSliders = ((flags & showAlphaChannel) != 0) ? 4 : 3;
  60248. const int numSwatches = getNumSwatches();
  60249. const int swatchSpace = numSwatches > 0 ? edgeGap + swatchHeight * ((numSwatches + 7) / swatchesPerRow) : 0;
  60250. const int sliderSpace = ((flags & showSliders) != 0) ? jmin (22 * numSliders + edgeGap, proportionOfHeight (0.3f)) : 0;
  60251. const int topSpace = ((flags & showColourAtTop) != 0) ? jmin (30 + edgeGap * 2, proportionOfHeight (0.2f)) : edgeGap;
  60252. previewArea.setBounds (edgeGap, edgeGap, getWidth() - edgeGap * 2, topSpace - edgeGap * 2);
  60253. int y = topSpace;
  60254. if ((flags & showColourspace) != 0)
  60255. {
  60256. const int hueWidth = jmin (50, proportionOfWidth (0.15f));
  60257. colourSpace->setBounds (edgeGap, y,
  60258. getWidth() - hueWidth - edgeGap - 4,
  60259. getHeight() - topSpace - sliderSpace - swatchSpace - edgeGap);
  60260. hueSelector->setBounds (colourSpace->getRight() + 4, y,
  60261. getWidth() - edgeGap - (colourSpace->getRight() + 4),
  60262. colourSpace->getHeight());
  60263. y = getHeight() - sliderSpace - swatchSpace - edgeGap;
  60264. }
  60265. if ((flags & showSliders) != 0)
  60266. {
  60267. const int sliderHeight = jmax (4, sliderSpace / numSliders);
  60268. for (int i = 0; i < numSliders; ++i)
  60269. {
  60270. sliders[i]->setBounds (proportionOfWidth (0.2f), y,
  60271. proportionOfWidth (0.72f), sliderHeight - 2);
  60272. y += sliderHeight;
  60273. }
  60274. }
  60275. if (numSwatches > 0)
  60276. {
  60277. const int startX = 8;
  60278. const int xGap = 4;
  60279. const int yGap = 4;
  60280. const int swatchWidth = (getWidth() - startX * 2) / swatchesPerRow;
  60281. y += edgeGap;
  60282. if (swatchComponents.size() != numSwatches)
  60283. {
  60284. swatchComponents.clear();
  60285. for (int i = 0; i < numSwatches; ++i)
  60286. {
  60287. SwatchComponent* const sc = new SwatchComponent (*this, i);
  60288. swatchComponents.add (sc);
  60289. addAndMakeVisible (sc);
  60290. }
  60291. }
  60292. int x = startX;
  60293. for (int i = 0; i < swatchComponents.size(); ++i)
  60294. {
  60295. SwatchComponent* const sc = swatchComponents.getUnchecked(i);
  60296. sc->setBounds (x + xGap / 2,
  60297. y + yGap / 2,
  60298. swatchWidth - xGap,
  60299. swatchHeight - yGap);
  60300. if (((i + 1) % swatchesPerRow) == 0)
  60301. {
  60302. x = startX;
  60303. y += swatchHeight;
  60304. }
  60305. else
  60306. {
  60307. x += swatchWidth;
  60308. }
  60309. }
  60310. }
  60311. }
  60312. void ColourSelector::sliderValueChanged (Slider*)
  60313. {
  60314. if (sliders[0] != 0)
  60315. setCurrentColour (Colour ((uint8) sliders[0]->getValue(),
  60316. (uint8) sliders[1]->getValue(),
  60317. (uint8) sliders[2]->getValue(),
  60318. (uint8) sliders[3]->getValue()));
  60319. }
  60320. int ColourSelector::getNumSwatches() const
  60321. {
  60322. return 0;
  60323. }
  60324. const Colour ColourSelector::getSwatchColour (const int) const
  60325. {
  60326. jassertfalse; // if you've overridden getNumSwatches(), you also need to implement this method
  60327. return Colours::black;
  60328. }
  60329. void ColourSelector::setSwatchColour (const int, const Colour&) const
  60330. {
  60331. jassertfalse; // if you've overridden getNumSwatches(), you also need to implement this method
  60332. }
  60333. END_JUCE_NAMESPACE
  60334. /*** End of inlined file: juce_ColourSelector.cpp ***/
  60335. /*** Start of inlined file: juce_DropShadower.cpp ***/
  60336. BEGIN_JUCE_NAMESPACE
  60337. class ShadowWindow : public Component
  60338. {
  60339. Component* owner;
  60340. Image shadowImageSections [12];
  60341. const int type; // 0 = left, 1 = right, 2 = top, 3 = bottom. left + right are full-height
  60342. public:
  60343. ShadowWindow (Component* const owner_,
  60344. const int type_,
  60345. const Image shadowImageSections_ [12])
  60346. : owner (owner_),
  60347. type (type_)
  60348. {
  60349. for (int i = 0; i < numElementsInArray (shadowImageSections); ++i)
  60350. shadowImageSections [i] = shadowImageSections_ [i];
  60351. setInterceptsMouseClicks (false, false);
  60352. if (owner_->isOnDesktop())
  60353. {
  60354. setSize (1, 1); // to keep the OS happy by not having zero-size windows
  60355. addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  60356. | ComponentPeer::windowIsTemporary
  60357. | ComponentPeer::windowIgnoresKeyPresses);
  60358. }
  60359. else if (owner_->getParentComponent() != 0)
  60360. {
  60361. owner_->getParentComponent()->addChildComponent (this);
  60362. }
  60363. }
  60364. ~ShadowWindow()
  60365. {
  60366. }
  60367. void paint (Graphics& g)
  60368. {
  60369. const Image& topLeft = shadowImageSections [type * 3];
  60370. const Image& bottomRight = shadowImageSections [type * 3 + 1];
  60371. const Image& filler = shadowImageSections [type * 3 + 2];
  60372. g.setOpacity (1.0f);
  60373. if (type < 2)
  60374. {
  60375. int imH = jmin (topLeft.getHeight(), getHeight() / 2);
  60376. g.drawImage (topLeft,
  60377. 0, 0, topLeft.getWidth(), imH,
  60378. 0, 0, topLeft.getWidth(), imH);
  60379. imH = jmin (bottomRight.getHeight(), getHeight() - getHeight() / 2);
  60380. g.drawImage (bottomRight,
  60381. 0, getHeight() - imH, bottomRight.getWidth(), imH,
  60382. 0, bottomRight.getHeight() - imH, bottomRight.getWidth(), imH);
  60383. g.setTiledImageFill (filler, 0, 0, 1.0f);
  60384. g.fillRect (0, topLeft.getHeight(), getWidth(), getHeight() - (topLeft.getHeight() + bottomRight.getHeight()));
  60385. }
  60386. else
  60387. {
  60388. int imW = jmin (topLeft.getWidth(), getWidth() / 2);
  60389. g.drawImage (topLeft,
  60390. 0, 0, imW, topLeft.getHeight(),
  60391. 0, 0, imW, topLeft.getHeight());
  60392. imW = jmin (bottomRight.getWidth(), getWidth() - getWidth() / 2);
  60393. g.drawImage (bottomRight,
  60394. getWidth() - imW, 0, imW, bottomRight.getHeight(),
  60395. bottomRight.getWidth() - imW, 0, imW, bottomRight.getHeight());
  60396. g.setTiledImageFill (filler, 0, 0, 1.0f);
  60397. g.fillRect (topLeft.getWidth(), 0, getWidth() - (topLeft.getWidth() + bottomRight.getWidth()), getHeight());
  60398. }
  60399. }
  60400. void resized()
  60401. {
  60402. repaint(); // (needed for correct repainting)
  60403. }
  60404. private:
  60405. ShadowWindow (const ShadowWindow&);
  60406. ShadowWindow& operator= (const ShadowWindow&);
  60407. };
  60408. DropShadower::DropShadower (const float alpha_,
  60409. const int xOffset_,
  60410. const int yOffset_,
  60411. const float blurRadius_)
  60412. : owner (0),
  60413. numShadows (0),
  60414. shadowEdge (jmax (xOffset_, yOffset_) + (int) blurRadius_),
  60415. xOffset (xOffset_),
  60416. yOffset (yOffset_),
  60417. alpha (alpha_),
  60418. blurRadius (blurRadius_),
  60419. inDestructor (false),
  60420. reentrant (false)
  60421. {
  60422. }
  60423. DropShadower::~DropShadower()
  60424. {
  60425. if (owner != 0)
  60426. owner->removeComponentListener (this);
  60427. inDestructor = true;
  60428. deleteShadowWindows();
  60429. }
  60430. void DropShadower::deleteShadowWindows()
  60431. {
  60432. if (numShadows > 0)
  60433. {
  60434. int i;
  60435. for (i = numShadows; --i >= 0;)
  60436. delete shadowWindows[i];
  60437. numShadows = 0;
  60438. }
  60439. }
  60440. void DropShadower::setOwner (Component* componentToFollow)
  60441. {
  60442. if (componentToFollow != owner)
  60443. {
  60444. if (owner != 0)
  60445. owner->removeComponentListener (this);
  60446. // (the component can't be null)
  60447. jassert (componentToFollow != 0);
  60448. owner = componentToFollow;
  60449. jassert (owner != 0);
  60450. jassert (owner->isOpaque()); // doesn't work properly for semi-transparent comps!
  60451. owner->addComponentListener (this);
  60452. updateShadows();
  60453. }
  60454. }
  60455. void DropShadower::componentMovedOrResized (Component&, bool /*wasMoved*/, bool /*wasResized*/)
  60456. {
  60457. updateShadows();
  60458. }
  60459. void DropShadower::componentBroughtToFront (Component&)
  60460. {
  60461. bringShadowWindowsToFront();
  60462. }
  60463. void DropShadower::componentChildrenChanged (Component&)
  60464. {
  60465. }
  60466. void DropShadower::componentParentHierarchyChanged (Component&)
  60467. {
  60468. deleteShadowWindows();
  60469. updateShadows();
  60470. }
  60471. void DropShadower::componentVisibilityChanged (Component&)
  60472. {
  60473. updateShadows();
  60474. }
  60475. void DropShadower::updateShadows()
  60476. {
  60477. if (reentrant || inDestructor || (owner == 0))
  60478. return;
  60479. reentrant = true;
  60480. ComponentPeer* const nw = owner->getPeer();
  60481. const bool isOwnerVisible = owner->isVisible()
  60482. && (nw == 0 || ! nw->isMinimised());
  60483. const bool createShadowWindows = numShadows == 0
  60484. && owner->getWidth() > 0
  60485. && owner->getHeight() > 0
  60486. && isOwnerVisible
  60487. && (Desktop::canUseSemiTransparentWindows()
  60488. || owner->getParentComponent() != 0);
  60489. if (createShadowWindows)
  60490. {
  60491. // keep a cached version of the image to save doing the gaussian too often
  60492. String imageId;
  60493. imageId << shadowEdge << ',' << xOffset << ',' << yOffset << ',' << alpha;
  60494. const int hash = imageId.hashCode();
  60495. Image bigIm (ImageCache::getFromHashCode (hash));
  60496. if (bigIm.isNull())
  60497. {
  60498. bigIm = Image (Image::ARGB, shadowEdge * 5, shadowEdge * 5, true, Image::NativeImage);
  60499. Graphics bigG (bigIm);
  60500. bigG.setColour (Colours::black.withAlpha (alpha));
  60501. bigG.fillRect (shadowEdge + xOffset,
  60502. shadowEdge + yOffset,
  60503. bigIm.getWidth() - (shadowEdge * 2),
  60504. bigIm.getHeight() - (shadowEdge * 2));
  60505. ImageConvolutionKernel blurKernel (roundToInt (blurRadius * 2.0f));
  60506. blurKernel.createGaussianBlur (blurRadius);
  60507. blurKernel.applyToImage (bigIm, bigIm,
  60508. Rectangle<int> (xOffset, yOffset,
  60509. bigIm.getWidth(), bigIm.getHeight()));
  60510. ImageCache::addImageToCache (bigIm, hash);
  60511. }
  60512. const int iw = bigIm.getWidth();
  60513. const int ih = bigIm.getHeight();
  60514. const int shadowEdge2 = shadowEdge * 2;
  60515. setShadowImage (bigIm, 0, shadowEdge, shadowEdge2, 0, 0);
  60516. setShadowImage (bigIm, 1, shadowEdge, shadowEdge2, 0, ih - shadowEdge2);
  60517. setShadowImage (bigIm, 2, shadowEdge, shadowEdge, 0, shadowEdge2);
  60518. setShadowImage (bigIm, 3, shadowEdge, shadowEdge2, iw - shadowEdge, 0);
  60519. setShadowImage (bigIm, 4, shadowEdge, shadowEdge2, iw - shadowEdge, ih - shadowEdge2);
  60520. setShadowImage (bigIm, 5, shadowEdge, shadowEdge, iw - shadowEdge, shadowEdge2);
  60521. setShadowImage (bigIm, 6, shadowEdge, shadowEdge, shadowEdge, 0);
  60522. setShadowImage (bigIm, 7, shadowEdge, shadowEdge, iw - shadowEdge2, 0);
  60523. setShadowImage (bigIm, 8, shadowEdge, shadowEdge, shadowEdge2, 0);
  60524. setShadowImage (bigIm, 9, shadowEdge, shadowEdge, shadowEdge, ih - shadowEdge);
  60525. setShadowImage (bigIm, 10, shadowEdge, shadowEdge, iw - shadowEdge2, ih - shadowEdge);
  60526. setShadowImage (bigIm, 11, shadowEdge, shadowEdge, shadowEdge2, ih - shadowEdge);
  60527. for (int i = 0; i < 4; ++i)
  60528. {
  60529. shadowWindows[numShadows] = new ShadowWindow (owner, i, shadowImageSections);
  60530. ++numShadows;
  60531. }
  60532. }
  60533. if (numShadows > 0)
  60534. {
  60535. for (int i = numShadows; --i >= 0;)
  60536. {
  60537. shadowWindows[i]->setAlwaysOnTop (owner->isAlwaysOnTop());
  60538. shadowWindows[i]->setVisible (isOwnerVisible);
  60539. }
  60540. const int x = owner->getX();
  60541. const int y = owner->getY() - shadowEdge;
  60542. const int w = owner->getWidth();
  60543. const int h = owner->getHeight() + shadowEdge + shadowEdge;
  60544. shadowWindows[0]->setBounds (x - shadowEdge,
  60545. y,
  60546. shadowEdge,
  60547. h);
  60548. shadowWindows[1]->setBounds (x + w,
  60549. y,
  60550. shadowEdge,
  60551. h);
  60552. shadowWindows[2]->setBounds (x,
  60553. y,
  60554. w,
  60555. shadowEdge);
  60556. shadowWindows[3]->setBounds (x,
  60557. owner->getBottom(),
  60558. w,
  60559. shadowEdge);
  60560. }
  60561. reentrant = false;
  60562. if (createShadowWindows)
  60563. bringShadowWindowsToFront();
  60564. }
  60565. void DropShadower::setShadowImage (const Image& src, const int num, const int w, const int h,
  60566. const int sx, const int sy)
  60567. {
  60568. shadowImageSections[num] = Image (Image::ARGB, w, h, true, Image::NativeImage);
  60569. Graphics g (shadowImageSections[num]);
  60570. g.drawImage (src, 0, 0, w, h, sx, sy, w, h);
  60571. }
  60572. void DropShadower::bringShadowWindowsToFront()
  60573. {
  60574. if (! (inDestructor || reentrant))
  60575. {
  60576. updateShadows();
  60577. reentrant = true;
  60578. for (int i = numShadows; --i >= 0;)
  60579. shadowWindows[i]->toBehind (owner);
  60580. reentrant = false;
  60581. }
  60582. }
  60583. END_JUCE_NAMESPACE
  60584. /*** End of inlined file: juce_DropShadower.cpp ***/
  60585. /*** Start of inlined file: juce_MagnifierComponent.cpp ***/
  60586. BEGIN_JUCE_NAMESPACE
  60587. class MagnifyingPeer : public ComponentPeer
  60588. {
  60589. public:
  60590. MagnifyingPeer (Component* const component_,
  60591. MagnifierComponent* const magnifierComp_)
  60592. : ComponentPeer (component_, 0),
  60593. magnifierComp (magnifierComp_)
  60594. {
  60595. }
  60596. ~MagnifyingPeer()
  60597. {
  60598. }
  60599. void* getNativeHandle() const { return 0; }
  60600. void setVisible (bool) {}
  60601. void setTitle (const String&) {}
  60602. void setPosition (int, int) {}
  60603. void setSize (int, int) {}
  60604. void setBounds (int, int, int, int, bool) {}
  60605. void setMinimised (bool) {}
  60606. void setAlpha (float /*newAlpha*/) {}
  60607. bool isMinimised() const { return false; }
  60608. void setFullScreen (bool) {}
  60609. bool isFullScreen() const { return false; }
  60610. const BorderSize getFrameSize() const { return BorderSize (0); }
  60611. bool setAlwaysOnTop (bool) { return true; }
  60612. void toFront (bool) {}
  60613. void toBehind (ComponentPeer*) {}
  60614. void setIcon (const Image&) {}
  60615. bool isFocused() const
  60616. {
  60617. return magnifierComp->hasKeyboardFocus (true);
  60618. }
  60619. void grabFocus()
  60620. {
  60621. ComponentPeer* peer = magnifierComp->getPeer();
  60622. if (peer != 0)
  60623. peer->grabFocus();
  60624. }
  60625. void textInputRequired (const Point<int>& position)
  60626. {
  60627. ComponentPeer* peer = magnifierComp->getPeer();
  60628. if (peer != 0)
  60629. peer->textInputRequired (position);
  60630. }
  60631. const Rectangle<int> getBounds() const
  60632. {
  60633. return Rectangle<int> (magnifierComp->getScreenX(), magnifierComp->getScreenY(),
  60634. component->getWidth(), component->getHeight());
  60635. }
  60636. const Point<int> getScreenPosition() const
  60637. {
  60638. return magnifierComp->getScreenPosition();
  60639. }
  60640. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition)
  60641. {
  60642. const double zoom = magnifierComp->getScaleFactor();
  60643. return magnifierComp->relativePositionToGlobal (Point<int> (roundToInt (relativePosition.getX() * zoom),
  60644. roundToInt (relativePosition.getY() * zoom)));
  60645. }
  60646. const Point<int> globalPositionToRelative (const Point<int>& screenPosition)
  60647. {
  60648. const Point<int> p (magnifierComp->globalPositionToRelative (screenPosition));
  60649. const double zoom = magnifierComp->getScaleFactor();
  60650. return Point<int> (roundToInt (p.getX() / zoom),
  60651. roundToInt (p.getY() / zoom));
  60652. }
  60653. bool contains (const Point<int>& position, bool) const
  60654. {
  60655. return ((unsigned int) position.getX()) < (unsigned int) magnifierComp->getWidth()
  60656. && ((unsigned int) position.getY()) < (unsigned int) magnifierComp->getHeight();
  60657. }
  60658. void repaint (const Rectangle<int>& area)
  60659. {
  60660. const double zoom = magnifierComp->getScaleFactor();
  60661. magnifierComp->repaint ((int) (area.getX() * zoom),
  60662. (int) (area.getY() * zoom),
  60663. roundToInt (area.getWidth() * zoom) + 1,
  60664. roundToInt (area.getHeight() * zoom) + 1);
  60665. }
  60666. void performAnyPendingRepaintsNow()
  60667. {
  60668. }
  60669. juce_UseDebuggingNewOperator
  60670. private:
  60671. MagnifierComponent* const magnifierComp;
  60672. MagnifyingPeer (const MagnifyingPeer&);
  60673. MagnifyingPeer& operator= (const MagnifyingPeer&);
  60674. };
  60675. class PeerHolderComp : public Component
  60676. {
  60677. public:
  60678. PeerHolderComp (MagnifierComponent* const magnifierComp_)
  60679. : magnifierComp (magnifierComp_)
  60680. {
  60681. setVisible (true);
  60682. }
  60683. ~PeerHolderComp()
  60684. {
  60685. }
  60686. ComponentPeer* createNewPeer (int, void*)
  60687. {
  60688. return new MagnifyingPeer (this, magnifierComp);
  60689. }
  60690. void childBoundsChanged (Component* c)
  60691. {
  60692. if (c != 0)
  60693. {
  60694. setSize (c->getWidth(), c->getHeight());
  60695. magnifierComp->childBoundsChanged (this);
  60696. }
  60697. }
  60698. void mouseWheelMove (const MouseEvent& e, float ix, float iy)
  60699. {
  60700. // unhandled mouse wheel moves can be referred upwards to the parent comp..
  60701. Component* const p = magnifierComp->getParentComponent();
  60702. if (p != 0)
  60703. p->mouseWheelMove (e.getEventRelativeTo (p), ix, iy);
  60704. }
  60705. private:
  60706. MagnifierComponent* const magnifierComp;
  60707. PeerHolderComp (const PeerHolderComp&);
  60708. PeerHolderComp& operator= (const PeerHolderComp&);
  60709. };
  60710. MagnifierComponent::MagnifierComponent (Component* const content_,
  60711. const bool deleteContentCompWhenNoLongerNeeded)
  60712. : content (content_),
  60713. scaleFactor (0.0),
  60714. peer (0),
  60715. deleteContent (deleteContentCompWhenNoLongerNeeded),
  60716. quality (Graphics::lowResamplingQuality),
  60717. mouseSource (0, true)
  60718. {
  60719. holderComp = new PeerHolderComp (this);
  60720. setScaleFactor (1.0);
  60721. }
  60722. MagnifierComponent::~MagnifierComponent()
  60723. {
  60724. delete holderComp;
  60725. if (deleteContent)
  60726. delete content;
  60727. }
  60728. void MagnifierComponent::setScaleFactor (double newScaleFactor)
  60729. {
  60730. jassert (newScaleFactor > 0.0); // hmm - unlikely to work well with a negative scale factor
  60731. newScaleFactor = jlimit (1.0 / 8.0, 1000.0, newScaleFactor);
  60732. if (scaleFactor != newScaleFactor)
  60733. {
  60734. scaleFactor = newScaleFactor;
  60735. if (scaleFactor == 1.0)
  60736. {
  60737. holderComp->removeFromDesktop();
  60738. peer = 0;
  60739. addChildComponent (content);
  60740. childBoundsChanged (content);
  60741. }
  60742. else
  60743. {
  60744. holderComp->addAndMakeVisible (content);
  60745. holderComp->childBoundsChanged (content);
  60746. childBoundsChanged (holderComp);
  60747. holderComp->addToDesktop (0);
  60748. peer = holderComp->getPeer();
  60749. }
  60750. repaint();
  60751. }
  60752. }
  60753. void MagnifierComponent::setResamplingQuality (Graphics::ResamplingQuality newQuality)
  60754. {
  60755. quality = newQuality;
  60756. }
  60757. void MagnifierComponent::paint (Graphics& g)
  60758. {
  60759. const int w = holderComp->getWidth();
  60760. const int h = holderComp->getHeight();
  60761. if (w == 0 || h == 0)
  60762. return;
  60763. const Rectangle<int> r (g.getClipBounds());
  60764. const int srcX = (int) (r.getX() / scaleFactor);
  60765. const int srcY = (int) (r.getY() / scaleFactor);
  60766. int srcW = roundToInt (r.getRight() / scaleFactor) - srcX;
  60767. int srcH = roundToInt (r.getBottom() / scaleFactor) - srcY;
  60768. if (scaleFactor >= 1.0)
  60769. {
  60770. ++srcW;
  60771. ++srcH;
  60772. }
  60773. Image temp (Image::ARGB, jmax (w, srcX + srcW), jmax (h, srcY + srcH), false);
  60774. const Rectangle<int> area (srcX, srcY, srcW, srcH);
  60775. temp.clear (area);
  60776. {
  60777. Graphics g2 (temp);
  60778. g2.reduceClipRegion (area);
  60779. holderComp->paintEntireComponent (g2, false);
  60780. }
  60781. g.setImageResamplingQuality (quality);
  60782. g.drawImageTransformed (temp, AffineTransform::scale ((float) scaleFactor, (float) scaleFactor), false);
  60783. }
  60784. void MagnifierComponent::childBoundsChanged (Component* c)
  60785. {
  60786. if (c != 0)
  60787. setSize (roundToInt (c->getWidth() * scaleFactor),
  60788. roundToInt (c->getHeight() * scaleFactor));
  60789. }
  60790. void MagnifierComponent::passOnMouseEventToPeer (const MouseEvent& e)
  60791. {
  60792. if (peer != 0)
  60793. mouseSource.handleEvent (peer, Point<int> (scaleInt (e.x), scaleInt (e.y)),
  60794. e.eventTime.toMilliseconds(), ModifierKeys::getCurrentModifiers());
  60795. }
  60796. void MagnifierComponent::mouseDown (const MouseEvent& e)
  60797. {
  60798. passOnMouseEventToPeer (e);
  60799. }
  60800. void MagnifierComponent::mouseUp (const MouseEvent& e)
  60801. {
  60802. passOnMouseEventToPeer (e);
  60803. }
  60804. void MagnifierComponent::mouseDrag (const MouseEvent& e)
  60805. {
  60806. passOnMouseEventToPeer (e);
  60807. }
  60808. void MagnifierComponent::mouseMove (const MouseEvent& e)
  60809. {
  60810. passOnMouseEventToPeer (e);
  60811. }
  60812. void MagnifierComponent::mouseEnter (const MouseEvent& e)
  60813. {
  60814. passOnMouseEventToPeer (e);
  60815. }
  60816. void MagnifierComponent::mouseExit (const MouseEvent& e)
  60817. {
  60818. passOnMouseEventToPeer (e);
  60819. }
  60820. void MagnifierComponent::mouseWheelMove (const MouseEvent& e, float ix, float iy)
  60821. {
  60822. if (peer != 0)
  60823. peer->handleMouseWheel (e.source.getIndex(),
  60824. Point<int> (scaleInt (e.x), scaleInt (e.y)), e.eventTime.toMilliseconds(),
  60825. ix * 256.0f, iy * 256.0f);
  60826. else
  60827. Component::mouseWheelMove (e, ix, iy);
  60828. }
  60829. int MagnifierComponent::scaleInt (const int n) const
  60830. {
  60831. return roundToInt (n / scaleFactor);
  60832. }
  60833. END_JUCE_NAMESPACE
  60834. /*** End of inlined file: juce_MagnifierComponent.cpp ***/
  60835. /*** Start of inlined file: juce_MidiKeyboardComponent.cpp ***/
  60836. BEGIN_JUCE_NAMESPACE
  60837. class MidiKeyboardUpDownButton : public Button
  60838. {
  60839. public:
  60840. MidiKeyboardUpDownButton (MidiKeyboardComponent& owner_, const int delta_)
  60841. : Button (String::empty),
  60842. owner (owner_),
  60843. delta (delta_)
  60844. {
  60845. setOpaque (true);
  60846. }
  60847. void clicked()
  60848. {
  60849. int note = owner.getLowestVisibleKey();
  60850. if (delta < 0)
  60851. note = (note - 1) / 12;
  60852. else
  60853. note = note / 12 + 1;
  60854. owner.setLowestVisibleKey (note * 12);
  60855. }
  60856. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  60857. {
  60858. owner.drawUpDownButton (g, getWidth(), getHeight(),
  60859. isMouseOverButton, isButtonDown,
  60860. delta > 0);
  60861. }
  60862. private:
  60863. MidiKeyboardComponent& owner;
  60864. const int delta;
  60865. MidiKeyboardUpDownButton (const MidiKeyboardUpDownButton&);
  60866. MidiKeyboardUpDownButton& operator= (const MidiKeyboardUpDownButton&);
  60867. };
  60868. MidiKeyboardComponent::MidiKeyboardComponent (MidiKeyboardState& state_,
  60869. const Orientation orientation_)
  60870. : state (state_),
  60871. xOffset (0),
  60872. blackNoteLength (1),
  60873. keyWidth (16.0f),
  60874. orientation (orientation_),
  60875. midiChannel (1),
  60876. midiInChannelMask (0xffff),
  60877. velocity (1.0f),
  60878. noteUnderMouse (-1),
  60879. mouseDownNote (-1),
  60880. rangeStart (0),
  60881. rangeEnd (127),
  60882. firstKey (12 * 4),
  60883. canScroll (true),
  60884. mouseDragging (false),
  60885. useMousePositionForVelocity (true),
  60886. keyMappingOctave (6),
  60887. octaveNumForMiddleC (3)
  60888. {
  60889. addChildComponent (scrollDown = new MidiKeyboardUpDownButton (*this, -1));
  60890. addChildComponent (scrollUp = new MidiKeyboardUpDownButton (*this, 1));
  60891. // initialise with a default set of querty key-mappings..
  60892. const char* const keymap = "awsedftgyhujkolp;";
  60893. for (int i = String (keymap).length(); --i >= 0;)
  60894. setKeyPressForNote (KeyPress (keymap[i], 0, 0), i);
  60895. setOpaque (true);
  60896. setWantsKeyboardFocus (true);
  60897. state.addListener (this);
  60898. }
  60899. MidiKeyboardComponent::~MidiKeyboardComponent()
  60900. {
  60901. state.removeListener (this);
  60902. jassert (mouseDownNote < 0 && keysPressed.countNumberOfSetBits() == 0); // leaving stuck notes!
  60903. }
  60904. void MidiKeyboardComponent::setKeyWidth (const float widthInPixels)
  60905. {
  60906. keyWidth = widthInPixels;
  60907. resized();
  60908. }
  60909. void MidiKeyboardComponent::setOrientation (const Orientation newOrientation)
  60910. {
  60911. if (orientation != newOrientation)
  60912. {
  60913. orientation = newOrientation;
  60914. resized();
  60915. }
  60916. }
  60917. void MidiKeyboardComponent::setAvailableRange (const int lowestNote,
  60918. const int highestNote)
  60919. {
  60920. jassert (lowestNote >= 0 && lowestNote <= 127);
  60921. jassert (highestNote >= 0 && highestNote <= 127);
  60922. jassert (lowestNote <= highestNote);
  60923. if (rangeStart != lowestNote || rangeEnd != highestNote)
  60924. {
  60925. rangeStart = jlimit (0, 127, lowestNote);
  60926. rangeEnd = jlimit (0, 127, highestNote);
  60927. firstKey = jlimit (rangeStart, rangeEnd, firstKey);
  60928. resized();
  60929. }
  60930. }
  60931. void MidiKeyboardComponent::setLowestVisibleKey (int noteNumber)
  60932. {
  60933. noteNumber = jlimit (rangeStart, rangeEnd, noteNumber);
  60934. if (noteNumber != firstKey)
  60935. {
  60936. firstKey = noteNumber;
  60937. sendChangeMessage (this);
  60938. resized();
  60939. }
  60940. }
  60941. void MidiKeyboardComponent::setScrollButtonsVisible (const bool canScroll_)
  60942. {
  60943. if (canScroll != canScroll_)
  60944. {
  60945. canScroll = canScroll_;
  60946. resized();
  60947. }
  60948. }
  60949. void MidiKeyboardComponent::colourChanged()
  60950. {
  60951. repaint();
  60952. }
  60953. void MidiKeyboardComponent::setMidiChannel (const int midiChannelNumber)
  60954. {
  60955. jassert (midiChannelNumber > 0 && midiChannelNumber <= 16);
  60956. if (midiChannel != midiChannelNumber)
  60957. {
  60958. resetAnyKeysInUse();
  60959. midiChannel = jlimit (1, 16, midiChannelNumber);
  60960. }
  60961. }
  60962. void MidiKeyboardComponent::setMidiChannelsToDisplay (const int midiChannelMask)
  60963. {
  60964. midiInChannelMask = midiChannelMask;
  60965. triggerAsyncUpdate();
  60966. }
  60967. void MidiKeyboardComponent::setVelocity (const float velocity_, const bool useMousePositionForVelocity_)
  60968. {
  60969. velocity = jlimit (0.0f, 1.0f, velocity_);
  60970. useMousePositionForVelocity = useMousePositionForVelocity_;
  60971. }
  60972. void MidiKeyboardComponent::getKeyPosition (int midiNoteNumber, const float keyWidth_, int& x, int& w) const
  60973. {
  60974. jassert (midiNoteNumber >= 0 && midiNoteNumber < 128);
  60975. static const float blackNoteWidth = 0.7f;
  60976. static const float notePos[] = { 0.0f, 1 - blackNoteWidth * 0.6f,
  60977. 1.0f, 2 - blackNoteWidth * 0.4f,
  60978. 2.0f, 3.0f, 4 - blackNoteWidth * 0.7f,
  60979. 4.0f, 5 - blackNoteWidth * 0.5f,
  60980. 5.0f, 6 - blackNoteWidth * 0.3f,
  60981. 6.0f };
  60982. static const float widths[] = { 1.0f, blackNoteWidth,
  60983. 1.0f, blackNoteWidth,
  60984. 1.0f, 1.0f, blackNoteWidth,
  60985. 1.0f, blackNoteWidth,
  60986. 1.0f, blackNoteWidth,
  60987. 1.0f };
  60988. const int octave = midiNoteNumber / 12;
  60989. const int note = midiNoteNumber % 12;
  60990. x = roundToInt (octave * 7.0f * keyWidth_ + notePos [note] * keyWidth_);
  60991. w = roundToInt (widths [note] * keyWidth_);
  60992. }
  60993. void MidiKeyboardComponent::getKeyPos (int midiNoteNumber, int& x, int& w) const
  60994. {
  60995. getKeyPosition (midiNoteNumber, keyWidth, x, w);
  60996. int rx, rw;
  60997. getKeyPosition (rangeStart, keyWidth, rx, rw);
  60998. x -= xOffset + rx;
  60999. }
  61000. int MidiKeyboardComponent::getKeyStartPosition (const int midiNoteNumber) const
  61001. {
  61002. int x, y;
  61003. getKeyPos (midiNoteNumber, x, y);
  61004. return x;
  61005. }
  61006. const uint8 MidiKeyboardComponent::whiteNotes[] = { 0, 2, 4, 5, 7, 9, 11 };
  61007. const uint8 MidiKeyboardComponent::blackNotes[] = { 1, 3, 6, 8, 10 };
  61008. int MidiKeyboardComponent::xyToNote (const Point<int>& pos, float& mousePositionVelocity)
  61009. {
  61010. if (! reallyContains (pos.getX(), pos.getY(), false))
  61011. return -1;
  61012. Point<int> p (pos);
  61013. if (orientation != horizontalKeyboard)
  61014. {
  61015. p = Point<int> (p.getY(), p.getX());
  61016. if (orientation == verticalKeyboardFacingLeft)
  61017. p = Point<int> (p.getX(), getWidth() - p.getY());
  61018. else
  61019. p = Point<int> (getHeight() - p.getX(), p.getY());
  61020. }
  61021. return remappedXYToNote (p + Point<int> (xOffset, 0), mousePositionVelocity);
  61022. }
  61023. int MidiKeyboardComponent::remappedXYToNote (const Point<int>& pos, float& mousePositionVelocity) const
  61024. {
  61025. if (pos.getY() < blackNoteLength)
  61026. {
  61027. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  61028. {
  61029. for (int i = 0; i < 5; ++i)
  61030. {
  61031. const int note = octaveStart + blackNotes [i];
  61032. if (note >= rangeStart && note <= rangeEnd)
  61033. {
  61034. int kx, kw;
  61035. getKeyPos (note, kx, kw);
  61036. kx += xOffset;
  61037. if (pos.getX() >= kx && pos.getX() < kx + kw)
  61038. {
  61039. mousePositionVelocity = pos.getY() / (float) blackNoteLength;
  61040. return note;
  61041. }
  61042. }
  61043. }
  61044. }
  61045. }
  61046. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  61047. {
  61048. for (int i = 0; i < 7; ++i)
  61049. {
  61050. const int note = octaveStart + whiteNotes [i];
  61051. if (note >= rangeStart && note <= rangeEnd)
  61052. {
  61053. int kx, kw;
  61054. getKeyPos (note, kx, kw);
  61055. kx += xOffset;
  61056. if (pos.getX() >= kx && pos.getX() < kx + kw)
  61057. {
  61058. const int whiteNoteLength = (orientation == horizontalKeyboard) ? getHeight() : getWidth();
  61059. mousePositionVelocity = pos.getY() / (float) whiteNoteLength;
  61060. return note;
  61061. }
  61062. }
  61063. }
  61064. }
  61065. mousePositionVelocity = 0;
  61066. return -1;
  61067. }
  61068. void MidiKeyboardComponent::repaintNote (const int noteNum)
  61069. {
  61070. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  61071. {
  61072. int x, w;
  61073. getKeyPos (noteNum, x, w);
  61074. if (orientation == horizontalKeyboard)
  61075. repaint (x, 0, w, getHeight());
  61076. else if (orientation == verticalKeyboardFacingLeft)
  61077. repaint (0, x, getWidth(), w);
  61078. else if (orientation == verticalKeyboardFacingRight)
  61079. repaint (0, getHeight() - x - w, getWidth(), w);
  61080. }
  61081. }
  61082. void MidiKeyboardComponent::paint (Graphics& g)
  61083. {
  61084. g.fillAll (Colours::white.overlaidWith (findColour (whiteNoteColourId)));
  61085. const Colour lineColour (findColour (keySeparatorLineColourId));
  61086. const Colour textColour (findColour (textLabelColourId));
  61087. int x, w, octave;
  61088. for (octave = 0; octave < 128; octave += 12)
  61089. {
  61090. for (int white = 0; white < 7; ++white)
  61091. {
  61092. const int noteNum = octave + whiteNotes [white];
  61093. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  61094. {
  61095. getKeyPos (noteNum, x, w);
  61096. if (orientation == horizontalKeyboard)
  61097. drawWhiteNote (noteNum, g, x, 0, w, getHeight(),
  61098. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  61099. noteUnderMouse == noteNum,
  61100. lineColour, textColour);
  61101. else if (orientation == verticalKeyboardFacingLeft)
  61102. drawWhiteNote (noteNum, g, 0, x, getWidth(), w,
  61103. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  61104. noteUnderMouse == noteNum,
  61105. lineColour, textColour);
  61106. else if (orientation == verticalKeyboardFacingRight)
  61107. drawWhiteNote (noteNum, g, 0, getHeight() - x - w, getWidth(), w,
  61108. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  61109. noteUnderMouse == noteNum,
  61110. lineColour, textColour);
  61111. }
  61112. }
  61113. }
  61114. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  61115. if (orientation == verticalKeyboardFacingLeft)
  61116. {
  61117. x1 = getWidth() - 1.0f;
  61118. x2 = getWidth() - 5.0f;
  61119. }
  61120. else if (orientation == verticalKeyboardFacingRight)
  61121. x2 = 5.0f;
  61122. else
  61123. y2 = 5.0f;
  61124. g.setGradientFill (ColourGradient (Colours::black.withAlpha (0.3f), x1, y1,
  61125. Colours::transparentBlack, x2, y2, false));
  61126. getKeyPos (rangeEnd, x, w);
  61127. x += w;
  61128. if (orientation == verticalKeyboardFacingLeft)
  61129. g.fillRect (getWidth() - 5, 0, 5, x);
  61130. else if (orientation == verticalKeyboardFacingRight)
  61131. g.fillRect (0, 0, 5, x);
  61132. else
  61133. g.fillRect (0, 0, x, 5);
  61134. g.setColour (lineColour);
  61135. if (orientation == verticalKeyboardFacingLeft)
  61136. g.fillRect (0, 0, 1, x);
  61137. else if (orientation == verticalKeyboardFacingRight)
  61138. g.fillRect (getWidth() - 1, 0, 1, x);
  61139. else
  61140. g.fillRect (0, getHeight() - 1, x, 1);
  61141. const Colour blackNoteColour (findColour (blackNoteColourId));
  61142. for (octave = 0; octave < 128; octave += 12)
  61143. {
  61144. for (int black = 0; black < 5; ++black)
  61145. {
  61146. const int noteNum = octave + blackNotes [black];
  61147. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  61148. {
  61149. getKeyPos (noteNum, x, w);
  61150. if (orientation == horizontalKeyboard)
  61151. drawBlackNote (noteNum, g, x, 0, w, blackNoteLength,
  61152. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  61153. noteUnderMouse == noteNum,
  61154. blackNoteColour);
  61155. else if (orientation == verticalKeyboardFacingLeft)
  61156. drawBlackNote (noteNum, g, getWidth() - blackNoteLength, x, blackNoteLength, w,
  61157. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  61158. noteUnderMouse == noteNum,
  61159. blackNoteColour);
  61160. else if (orientation == verticalKeyboardFacingRight)
  61161. drawBlackNote (noteNum, g, 0, getHeight() - x - w, blackNoteLength, w,
  61162. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  61163. noteUnderMouse == noteNum,
  61164. blackNoteColour);
  61165. }
  61166. }
  61167. }
  61168. }
  61169. void MidiKeyboardComponent::drawWhiteNote (int midiNoteNumber,
  61170. Graphics& g, int x, int y, int w, int h,
  61171. bool isDown, bool isOver,
  61172. const Colour& lineColour,
  61173. const Colour& textColour)
  61174. {
  61175. Colour c (Colours::transparentWhite);
  61176. if (isDown)
  61177. c = findColour (keyDownOverlayColourId);
  61178. if (isOver)
  61179. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  61180. g.setColour (c);
  61181. g.fillRect (x, y, w, h);
  61182. const String text (getWhiteNoteText (midiNoteNumber));
  61183. if (! text.isEmpty())
  61184. {
  61185. g.setColour (textColour);
  61186. Font f (jmin (12.0f, keyWidth * 0.9f));
  61187. f.setHorizontalScale (0.8f);
  61188. g.setFont (f);
  61189. Justification justification (Justification::centredBottom);
  61190. if (orientation == verticalKeyboardFacingLeft)
  61191. justification = Justification::centredLeft;
  61192. else if (orientation == verticalKeyboardFacingRight)
  61193. justification = Justification::centredRight;
  61194. g.drawFittedText (text, x + 2, y + 2, w - 4, h - 4, justification, 1);
  61195. }
  61196. g.setColour (lineColour);
  61197. if (orientation == horizontalKeyboard)
  61198. g.fillRect (x, y, 1, h);
  61199. else if (orientation == verticalKeyboardFacingLeft)
  61200. g.fillRect (x, y, w, 1);
  61201. else if (orientation == verticalKeyboardFacingRight)
  61202. g.fillRect (x, y + h - 1, w, 1);
  61203. if (midiNoteNumber == rangeEnd)
  61204. {
  61205. if (orientation == horizontalKeyboard)
  61206. g.fillRect (x + w, y, 1, h);
  61207. else if (orientation == verticalKeyboardFacingLeft)
  61208. g.fillRect (x, y + h, w, 1);
  61209. else if (orientation == verticalKeyboardFacingRight)
  61210. g.fillRect (x, y - 1, w, 1);
  61211. }
  61212. }
  61213. void MidiKeyboardComponent::drawBlackNote (int /*midiNoteNumber*/,
  61214. Graphics& g, int x, int y, int w, int h,
  61215. bool isDown, bool isOver,
  61216. const Colour& noteFillColour)
  61217. {
  61218. Colour c (noteFillColour);
  61219. if (isDown)
  61220. c = c.overlaidWith (findColour (keyDownOverlayColourId));
  61221. if (isOver)
  61222. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  61223. g.setColour (c);
  61224. g.fillRect (x, y, w, h);
  61225. if (isDown)
  61226. {
  61227. g.setColour (noteFillColour);
  61228. g.drawRect (x, y, w, h);
  61229. }
  61230. else
  61231. {
  61232. const int xIndent = jmax (1, jmin (w, h) / 8);
  61233. g.setColour (c.brighter());
  61234. if (orientation == horizontalKeyboard)
  61235. g.fillRect (x + xIndent, y, w - xIndent * 2, 7 * h / 8);
  61236. else if (orientation == verticalKeyboardFacingLeft)
  61237. g.fillRect (x + w / 8, y + xIndent, w - w / 8, h - xIndent * 2);
  61238. else if (orientation == verticalKeyboardFacingRight)
  61239. g.fillRect (x, y + xIndent, 7 * w / 8, h - xIndent * 2);
  61240. }
  61241. }
  61242. void MidiKeyboardComponent::setOctaveForMiddleC (const int octaveNumForMiddleC_)
  61243. {
  61244. octaveNumForMiddleC = octaveNumForMiddleC_;
  61245. repaint();
  61246. }
  61247. const String MidiKeyboardComponent::getWhiteNoteText (const int midiNoteNumber)
  61248. {
  61249. if (keyWidth > 14.0f && midiNoteNumber % 12 == 0)
  61250. return MidiMessage::getMidiNoteName (midiNoteNumber, true, true, octaveNumForMiddleC);
  61251. return String::empty;
  61252. }
  61253. void MidiKeyboardComponent::drawUpDownButton (Graphics& g, int w, int h,
  61254. const bool isMouseOver_,
  61255. const bool isButtonDown,
  61256. const bool movesOctavesUp)
  61257. {
  61258. g.fillAll (findColour (upDownButtonBackgroundColourId));
  61259. float angle;
  61260. if (orientation == MidiKeyboardComponent::horizontalKeyboard)
  61261. angle = movesOctavesUp ? 0.0f : 0.5f;
  61262. else if (orientation == MidiKeyboardComponent::verticalKeyboardFacingLeft)
  61263. angle = movesOctavesUp ? 0.25f : 0.75f;
  61264. else
  61265. angle = movesOctavesUp ? 0.75f : 0.25f;
  61266. Path path;
  61267. path.lineTo (0.0f, 1.0f);
  61268. path.lineTo (1.0f, 0.5f);
  61269. path.closeSubPath();
  61270. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * angle, 0.5f, 0.5f));
  61271. g.setColour (findColour (upDownButtonArrowColourId)
  61272. .withAlpha (isButtonDown ? 1.0f : (isMouseOver_ ? 0.6f : 0.4f)));
  61273. g.fillPath (path, path.getTransformToScaleToFit (1.0f, 1.0f,
  61274. w - 2.0f,
  61275. h - 2.0f,
  61276. true));
  61277. }
  61278. void MidiKeyboardComponent::resized()
  61279. {
  61280. int w = getWidth();
  61281. int h = getHeight();
  61282. if (w > 0 && h > 0)
  61283. {
  61284. if (orientation != horizontalKeyboard)
  61285. swapVariables (w, h);
  61286. blackNoteLength = roundToInt (h * 0.7f);
  61287. int kx2, kw2;
  61288. getKeyPos (rangeEnd, kx2, kw2);
  61289. kx2 += kw2;
  61290. if (firstKey != rangeStart)
  61291. {
  61292. int kx1, kw1;
  61293. getKeyPos (rangeStart, kx1, kw1);
  61294. if (kx2 - kx1 <= w)
  61295. {
  61296. firstKey = rangeStart;
  61297. sendChangeMessage (this);
  61298. repaint();
  61299. }
  61300. }
  61301. const bool showScrollButtons = canScroll && (firstKey > rangeStart || kx2 > w + xOffset * 2);
  61302. scrollDown->setVisible (showScrollButtons);
  61303. scrollUp->setVisible (showScrollButtons);
  61304. xOffset = 0;
  61305. if (showScrollButtons)
  61306. {
  61307. const int scrollButtonW = jmin (12, w / 2);
  61308. if (orientation == horizontalKeyboard)
  61309. {
  61310. scrollDown->setBounds (0, 0, scrollButtonW, getHeight());
  61311. scrollUp->setBounds (getWidth() - scrollButtonW, 0, scrollButtonW, getHeight());
  61312. }
  61313. else if (orientation == verticalKeyboardFacingLeft)
  61314. {
  61315. scrollDown->setBounds (0, 0, getWidth(), scrollButtonW);
  61316. scrollUp->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  61317. }
  61318. else if (orientation == verticalKeyboardFacingRight)
  61319. {
  61320. scrollDown->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  61321. scrollUp->setBounds (0, 0, getWidth(), scrollButtonW);
  61322. }
  61323. int endOfLastKey, kw;
  61324. getKeyPos (rangeEnd, endOfLastKey, kw);
  61325. endOfLastKey += kw;
  61326. float mousePositionVelocity;
  61327. const int spaceAvailable = w - scrollButtonW * 2;
  61328. const int lastStartKey = remappedXYToNote (Point<int> (endOfLastKey - spaceAvailable, 0), mousePositionVelocity) + 1;
  61329. if (lastStartKey >= 0 && firstKey > lastStartKey)
  61330. {
  61331. firstKey = jlimit (rangeStart, rangeEnd, lastStartKey);
  61332. sendChangeMessage (this);
  61333. }
  61334. int newOffset = 0;
  61335. getKeyPos (firstKey, newOffset, kw);
  61336. xOffset = newOffset - scrollButtonW;
  61337. }
  61338. else
  61339. {
  61340. firstKey = rangeStart;
  61341. }
  61342. timerCallback();
  61343. repaint();
  61344. }
  61345. }
  61346. void MidiKeyboardComponent::handleNoteOn (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/, float /*velocity*/)
  61347. {
  61348. triggerAsyncUpdate();
  61349. }
  61350. void MidiKeyboardComponent::handleNoteOff (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/)
  61351. {
  61352. triggerAsyncUpdate();
  61353. }
  61354. void MidiKeyboardComponent::handleAsyncUpdate()
  61355. {
  61356. for (int i = rangeStart; i <= rangeEnd; ++i)
  61357. {
  61358. if (keysCurrentlyDrawnDown[i] != state.isNoteOnForChannels (midiInChannelMask, i))
  61359. {
  61360. keysCurrentlyDrawnDown.setBit (i, state.isNoteOnForChannels (midiInChannelMask, i));
  61361. repaintNote (i);
  61362. }
  61363. }
  61364. }
  61365. void MidiKeyboardComponent::resetAnyKeysInUse()
  61366. {
  61367. if (keysPressed.countNumberOfSetBits() > 0 || mouseDownNote > 0)
  61368. {
  61369. state.allNotesOff (midiChannel);
  61370. keysPressed.clear();
  61371. mouseDownNote = -1;
  61372. }
  61373. }
  61374. void MidiKeyboardComponent::updateNoteUnderMouse (const Point<int>& pos)
  61375. {
  61376. float mousePositionVelocity = 0.0f;
  61377. const int newNote = (mouseDragging || isMouseOver())
  61378. ? xyToNote (pos, mousePositionVelocity) : -1;
  61379. if (noteUnderMouse != newNote)
  61380. {
  61381. if (mouseDownNote >= 0)
  61382. {
  61383. state.noteOff (midiChannel, mouseDownNote);
  61384. mouseDownNote = -1;
  61385. }
  61386. if (mouseDragging && newNote >= 0)
  61387. {
  61388. if (! useMousePositionForVelocity)
  61389. mousePositionVelocity = 1.0f;
  61390. state.noteOn (midiChannel, newNote, mousePositionVelocity * velocity);
  61391. mouseDownNote = newNote;
  61392. }
  61393. repaintNote (noteUnderMouse);
  61394. noteUnderMouse = newNote;
  61395. repaintNote (noteUnderMouse);
  61396. }
  61397. else if (mouseDownNote >= 0 && ! mouseDragging)
  61398. {
  61399. state.noteOff (midiChannel, mouseDownNote);
  61400. mouseDownNote = -1;
  61401. }
  61402. }
  61403. void MidiKeyboardComponent::mouseMove (const MouseEvent& e)
  61404. {
  61405. updateNoteUnderMouse (e.getPosition());
  61406. stopTimer();
  61407. }
  61408. void MidiKeyboardComponent::mouseDrag (const MouseEvent& e)
  61409. {
  61410. float mousePositionVelocity;
  61411. const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
  61412. if (newNote >= 0)
  61413. mouseDraggedToKey (newNote, e);
  61414. updateNoteUnderMouse (e.getPosition());
  61415. }
  61416. bool MidiKeyboardComponent::mouseDownOnKey (int /*midiNoteNumber*/, const MouseEvent&)
  61417. {
  61418. return true;
  61419. }
  61420. void MidiKeyboardComponent::mouseDraggedToKey (int /*midiNoteNumber*/, const MouseEvent&)
  61421. {
  61422. }
  61423. void MidiKeyboardComponent::mouseDown (const MouseEvent& e)
  61424. {
  61425. float mousePositionVelocity;
  61426. const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
  61427. mouseDragging = false;
  61428. if (newNote >= 0 && mouseDownOnKey (newNote, e))
  61429. {
  61430. repaintNote (noteUnderMouse);
  61431. noteUnderMouse = -1;
  61432. mouseDragging = true;
  61433. updateNoteUnderMouse (e.getPosition());
  61434. startTimer (500);
  61435. }
  61436. }
  61437. void MidiKeyboardComponent::mouseUp (const MouseEvent& e)
  61438. {
  61439. mouseDragging = false;
  61440. updateNoteUnderMouse (e.getPosition());
  61441. stopTimer();
  61442. }
  61443. void MidiKeyboardComponent::mouseEnter (const MouseEvent& e)
  61444. {
  61445. updateNoteUnderMouse (e.getPosition());
  61446. }
  61447. void MidiKeyboardComponent::mouseExit (const MouseEvent& e)
  61448. {
  61449. updateNoteUnderMouse (e.getPosition());
  61450. }
  61451. void MidiKeyboardComponent::mouseWheelMove (const MouseEvent&, float ix, float iy)
  61452. {
  61453. setLowestVisibleKey (getLowestVisibleKey() + roundToInt ((ix != 0 ? ix : iy) * 5.0f));
  61454. }
  61455. void MidiKeyboardComponent::timerCallback()
  61456. {
  61457. updateNoteUnderMouse (getMouseXYRelative());
  61458. }
  61459. void MidiKeyboardComponent::clearKeyMappings()
  61460. {
  61461. resetAnyKeysInUse();
  61462. keyPressNotes.clear();
  61463. keyPresses.clear();
  61464. }
  61465. void MidiKeyboardComponent::setKeyPressForNote (const KeyPress& key,
  61466. const int midiNoteOffsetFromC)
  61467. {
  61468. removeKeyPressForNote (midiNoteOffsetFromC);
  61469. keyPressNotes.add (midiNoteOffsetFromC);
  61470. keyPresses.add (key);
  61471. }
  61472. void MidiKeyboardComponent::removeKeyPressForNote (const int midiNoteOffsetFromC)
  61473. {
  61474. for (int i = keyPressNotes.size(); --i >= 0;)
  61475. {
  61476. if (keyPressNotes.getUnchecked (i) == midiNoteOffsetFromC)
  61477. {
  61478. keyPressNotes.remove (i);
  61479. keyPresses.remove (i);
  61480. }
  61481. }
  61482. }
  61483. void MidiKeyboardComponent::setKeyPressBaseOctave (const int newOctaveNumber)
  61484. {
  61485. jassert (newOctaveNumber >= 0 && newOctaveNumber <= 10);
  61486. keyMappingOctave = newOctaveNumber;
  61487. }
  61488. bool MidiKeyboardComponent::keyStateChanged (const bool /*isKeyDown*/)
  61489. {
  61490. bool keyPressUsed = false;
  61491. for (int i = keyPresses.size(); --i >= 0;)
  61492. {
  61493. const int note = 12 * keyMappingOctave + keyPressNotes.getUnchecked (i);
  61494. if (keyPresses.getReference(i).isCurrentlyDown())
  61495. {
  61496. if (! keysPressed [note])
  61497. {
  61498. keysPressed.setBit (note);
  61499. state.noteOn (midiChannel, note, velocity);
  61500. keyPressUsed = true;
  61501. }
  61502. }
  61503. else
  61504. {
  61505. if (keysPressed [note])
  61506. {
  61507. keysPressed.clearBit (note);
  61508. state.noteOff (midiChannel, note);
  61509. keyPressUsed = true;
  61510. }
  61511. }
  61512. }
  61513. return keyPressUsed;
  61514. }
  61515. void MidiKeyboardComponent::focusLost (FocusChangeType)
  61516. {
  61517. resetAnyKeysInUse();
  61518. }
  61519. END_JUCE_NAMESPACE
  61520. /*** End of inlined file: juce_MidiKeyboardComponent.cpp ***/
  61521. /*** Start of inlined file: juce_OpenGLComponent.cpp ***/
  61522. #if JUCE_OPENGL
  61523. BEGIN_JUCE_NAMESPACE
  61524. extern void juce_glViewport (const int w, const int h);
  61525. OpenGLPixelFormat::OpenGLPixelFormat (const int bitsPerRGBComponent,
  61526. const int alphaBits_,
  61527. const int depthBufferBits_,
  61528. const int stencilBufferBits_)
  61529. : redBits (bitsPerRGBComponent),
  61530. greenBits (bitsPerRGBComponent),
  61531. blueBits (bitsPerRGBComponent),
  61532. alphaBits (alphaBits_),
  61533. depthBufferBits (depthBufferBits_),
  61534. stencilBufferBits (stencilBufferBits_),
  61535. accumulationBufferRedBits (0),
  61536. accumulationBufferGreenBits (0),
  61537. accumulationBufferBlueBits (0),
  61538. accumulationBufferAlphaBits (0),
  61539. fullSceneAntiAliasingNumSamples (0)
  61540. {
  61541. }
  61542. OpenGLPixelFormat::OpenGLPixelFormat (const OpenGLPixelFormat& other)
  61543. : redBits (other.redBits),
  61544. greenBits (other.greenBits),
  61545. blueBits (other.blueBits),
  61546. alphaBits (other.alphaBits),
  61547. depthBufferBits (other.depthBufferBits),
  61548. stencilBufferBits (other.stencilBufferBits),
  61549. accumulationBufferRedBits (other.accumulationBufferRedBits),
  61550. accumulationBufferGreenBits (other.accumulationBufferGreenBits),
  61551. accumulationBufferBlueBits (other.accumulationBufferBlueBits),
  61552. accumulationBufferAlphaBits (other.accumulationBufferAlphaBits),
  61553. fullSceneAntiAliasingNumSamples (other.fullSceneAntiAliasingNumSamples)
  61554. {
  61555. }
  61556. OpenGLPixelFormat& OpenGLPixelFormat::operator= (const OpenGLPixelFormat& other)
  61557. {
  61558. redBits = other.redBits;
  61559. greenBits = other.greenBits;
  61560. blueBits = other.blueBits;
  61561. alphaBits = other.alphaBits;
  61562. depthBufferBits = other.depthBufferBits;
  61563. stencilBufferBits = other.stencilBufferBits;
  61564. accumulationBufferRedBits = other.accumulationBufferRedBits;
  61565. accumulationBufferGreenBits = other.accumulationBufferGreenBits;
  61566. accumulationBufferBlueBits = other.accumulationBufferBlueBits;
  61567. accumulationBufferAlphaBits = other.accumulationBufferAlphaBits;
  61568. fullSceneAntiAliasingNumSamples = other.fullSceneAntiAliasingNumSamples;
  61569. return *this;
  61570. }
  61571. bool OpenGLPixelFormat::operator== (const OpenGLPixelFormat& other) const
  61572. {
  61573. return redBits == other.redBits
  61574. && greenBits == other.greenBits
  61575. && blueBits == other.blueBits
  61576. && alphaBits == other.alphaBits
  61577. && depthBufferBits == other.depthBufferBits
  61578. && stencilBufferBits == other.stencilBufferBits
  61579. && accumulationBufferRedBits == other.accumulationBufferRedBits
  61580. && accumulationBufferGreenBits == other.accumulationBufferGreenBits
  61581. && accumulationBufferBlueBits == other.accumulationBufferBlueBits
  61582. && accumulationBufferAlphaBits == other.accumulationBufferAlphaBits
  61583. && fullSceneAntiAliasingNumSamples == other.fullSceneAntiAliasingNumSamples;
  61584. }
  61585. static Array<OpenGLContext*> knownContexts;
  61586. OpenGLContext::OpenGLContext() throw()
  61587. {
  61588. knownContexts.add (this);
  61589. }
  61590. OpenGLContext::~OpenGLContext()
  61591. {
  61592. knownContexts.removeValue (this);
  61593. }
  61594. OpenGLContext* OpenGLContext::getCurrentContext()
  61595. {
  61596. for (int i = knownContexts.size(); --i >= 0;)
  61597. {
  61598. OpenGLContext* const oglc = knownContexts.getUnchecked(i);
  61599. if (oglc->isActive())
  61600. return oglc;
  61601. }
  61602. return 0;
  61603. }
  61604. class OpenGLComponent::OpenGLComponentWatcher : public ComponentMovementWatcher
  61605. {
  61606. public:
  61607. OpenGLComponentWatcher (OpenGLComponent* const owner_)
  61608. : ComponentMovementWatcher (owner_),
  61609. owner (owner_),
  61610. wasShowing (false)
  61611. {
  61612. }
  61613. ~OpenGLComponentWatcher() {}
  61614. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  61615. {
  61616. owner->updateContextPosition();
  61617. }
  61618. void componentPeerChanged()
  61619. {
  61620. const ScopedLock sl (owner->getContextLock());
  61621. owner->deleteContext();
  61622. }
  61623. void componentVisibilityChanged (Component&)
  61624. {
  61625. const bool isShowingNow = owner->isShowing();
  61626. if (wasShowing != isShowingNow)
  61627. {
  61628. wasShowing = isShowingNow;
  61629. if (! isShowingNow)
  61630. {
  61631. const ScopedLock sl (owner->getContextLock());
  61632. owner->deleteContext();
  61633. }
  61634. }
  61635. }
  61636. juce_UseDebuggingNewOperator
  61637. private:
  61638. OpenGLComponent* const owner;
  61639. bool wasShowing;
  61640. };
  61641. OpenGLComponent::OpenGLComponent (const OpenGLType type_)
  61642. : type (type_),
  61643. contextToShareListsWith (0),
  61644. needToUpdateViewport (true)
  61645. {
  61646. setOpaque (true);
  61647. componentWatcher = new OpenGLComponentWatcher (this);
  61648. }
  61649. OpenGLComponent::~OpenGLComponent()
  61650. {
  61651. deleteContext();
  61652. componentWatcher = 0;
  61653. }
  61654. void OpenGLComponent::deleteContext()
  61655. {
  61656. const ScopedLock sl (contextLock);
  61657. context = 0;
  61658. }
  61659. void OpenGLComponent::updateContextPosition()
  61660. {
  61661. needToUpdateViewport = true;
  61662. if (getWidth() > 0 && getHeight() > 0)
  61663. {
  61664. Component* const topComp = getTopLevelComponent();
  61665. if (topComp->getPeer() != 0)
  61666. {
  61667. const ScopedLock sl (contextLock);
  61668. if (context != 0)
  61669. context->updateWindowPosition (getScreenX() - topComp->getScreenX(),
  61670. getScreenY() - topComp->getScreenY(),
  61671. getWidth(),
  61672. getHeight(),
  61673. topComp->getHeight());
  61674. }
  61675. }
  61676. }
  61677. const OpenGLPixelFormat OpenGLComponent::getPixelFormat() const
  61678. {
  61679. OpenGLPixelFormat pf;
  61680. const ScopedLock sl (contextLock);
  61681. if (context != 0)
  61682. pf = context->getPixelFormat();
  61683. return pf;
  61684. }
  61685. void OpenGLComponent::setPixelFormat (const OpenGLPixelFormat& formatToUse)
  61686. {
  61687. if (! (preferredPixelFormat == formatToUse))
  61688. {
  61689. const ScopedLock sl (contextLock);
  61690. deleteContext();
  61691. preferredPixelFormat = formatToUse;
  61692. }
  61693. }
  61694. void OpenGLComponent::shareWith (OpenGLContext* c)
  61695. {
  61696. if (contextToShareListsWith != c)
  61697. {
  61698. const ScopedLock sl (contextLock);
  61699. deleteContext();
  61700. contextToShareListsWith = c;
  61701. }
  61702. }
  61703. bool OpenGLComponent::makeCurrentContextActive()
  61704. {
  61705. if (context == 0)
  61706. {
  61707. const ScopedLock sl (contextLock);
  61708. if (isShowing() && getTopLevelComponent()->getPeer() != 0)
  61709. {
  61710. context = createContext();
  61711. if (context != 0)
  61712. {
  61713. updateContextPosition();
  61714. if (context->makeActive())
  61715. newOpenGLContextCreated();
  61716. }
  61717. }
  61718. }
  61719. return context != 0 && context->makeActive();
  61720. }
  61721. void OpenGLComponent::makeCurrentContextInactive()
  61722. {
  61723. if (context != 0)
  61724. context->makeInactive();
  61725. }
  61726. bool OpenGLComponent::isActiveContext() const throw()
  61727. {
  61728. return context != 0 && context->isActive();
  61729. }
  61730. void OpenGLComponent::swapBuffers()
  61731. {
  61732. if (context != 0)
  61733. context->swapBuffers();
  61734. }
  61735. void OpenGLComponent::paint (Graphics&)
  61736. {
  61737. if (renderAndSwapBuffers())
  61738. {
  61739. ComponentPeer* const peer = getPeer();
  61740. if (peer != 0)
  61741. {
  61742. const Point<int> topLeft (getScreenPosition() - peer->getScreenPosition());
  61743. peer->addMaskedRegion (topLeft.getX(), topLeft.getY(), getWidth(), getHeight());
  61744. }
  61745. }
  61746. }
  61747. bool OpenGLComponent::renderAndSwapBuffers()
  61748. {
  61749. const ScopedLock sl (contextLock);
  61750. if (! makeCurrentContextActive())
  61751. return false;
  61752. if (needToUpdateViewport)
  61753. {
  61754. needToUpdateViewport = false;
  61755. juce_glViewport (getWidth(), getHeight());
  61756. }
  61757. renderOpenGL();
  61758. swapBuffers();
  61759. return true;
  61760. }
  61761. void OpenGLComponent::internalRepaint (int x, int y, int w, int h)
  61762. {
  61763. Component::internalRepaint (x, y, w, h);
  61764. if (context != 0)
  61765. context->repaint();
  61766. }
  61767. END_JUCE_NAMESPACE
  61768. #endif
  61769. /*** End of inlined file: juce_OpenGLComponent.cpp ***/
  61770. /*** Start of inlined file: juce_PreferencesPanel.cpp ***/
  61771. BEGIN_JUCE_NAMESPACE
  61772. PreferencesPanel::PreferencesPanel()
  61773. : buttonSize (70)
  61774. {
  61775. }
  61776. PreferencesPanel::~PreferencesPanel()
  61777. {
  61778. }
  61779. void PreferencesPanel::addSettingsPage (const String& title,
  61780. const Drawable* icon,
  61781. const Drawable* overIcon,
  61782. const Drawable* downIcon)
  61783. {
  61784. DrawableButton* const button = new DrawableButton (title, DrawableButton::ImageAboveTextLabel);
  61785. buttons.add (button);
  61786. button->setImages (icon, overIcon, downIcon);
  61787. button->setRadioGroupId (1);
  61788. button->addButtonListener (this);
  61789. button->setClickingTogglesState (true);
  61790. button->setWantsKeyboardFocus (false);
  61791. addAndMakeVisible (button);
  61792. resized();
  61793. if (currentPage == 0)
  61794. setCurrentPage (title);
  61795. }
  61796. void PreferencesPanel::addSettingsPage (const String& title, const void* imageData, const int imageDataSize)
  61797. {
  61798. DrawableImage icon, iconOver, iconDown;
  61799. icon.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61800. iconOver.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61801. iconOver.setOverlayColour (Colours::black.withAlpha (0.12f));
  61802. iconDown.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61803. iconDown.setOverlayColour (Colours::black.withAlpha (0.25f));
  61804. addSettingsPage (title, &icon, &iconOver, &iconDown);
  61805. }
  61806. void PreferencesPanel::showInDialogBox (const String& dialogTitle, int dialogWidth, int dialogHeight, const Colour& backgroundColour)
  61807. {
  61808. setSize (dialogWidth, dialogHeight);
  61809. DialogWindow::showModalDialog (dialogTitle, this, 0, backgroundColour, false);
  61810. }
  61811. void PreferencesPanel::resized()
  61812. {
  61813. for (int i = 0; i < buttons.size(); ++i)
  61814. buttons.getUnchecked(i)->setBounds (i * buttonSize, 0, buttonSize, buttonSize);
  61815. if (currentPage != 0)
  61816. currentPage->setBounds (getLocalBounds().withTop (buttonSize + 5));
  61817. }
  61818. void PreferencesPanel::paint (Graphics& g)
  61819. {
  61820. g.setColour (Colours::grey);
  61821. g.fillRect (0, buttonSize + 2, getWidth(), 1);
  61822. }
  61823. void PreferencesPanel::setCurrentPage (const String& pageName)
  61824. {
  61825. if (currentPageName != pageName)
  61826. {
  61827. currentPageName = pageName;
  61828. currentPage = 0;
  61829. currentPage = createComponentForPage (pageName);
  61830. if (currentPage != 0)
  61831. {
  61832. addAndMakeVisible (currentPage);
  61833. currentPage->toBack();
  61834. resized();
  61835. }
  61836. for (int i = 0; i < buttons.size(); ++i)
  61837. {
  61838. if (buttons.getUnchecked(i)->getName() == pageName)
  61839. {
  61840. buttons.getUnchecked(i)->setToggleState (true, false);
  61841. break;
  61842. }
  61843. }
  61844. }
  61845. }
  61846. void PreferencesPanel::buttonClicked (Button*)
  61847. {
  61848. for (int i = 0; i < buttons.size(); ++i)
  61849. {
  61850. if (buttons.getUnchecked(i)->getToggleState())
  61851. {
  61852. setCurrentPage (buttons.getUnchecked(i)->getName());
  61853. break;
  61854. }
  61855. }
  61856. }
  61857. END_JUCE_NAMESPACE
  61858. /*** End of inlined file: juce_PreferencesPanel.cpp ***/
  61859. /*** Start of inlined file: juce_SystemTrayIconComponent.cpp ***/
  61860. #if JUCE_WINDOWS || JUCE_LINUX
  61861. BEGIN_JUCE_NAMESPACE
  61862. SystemTrayIconComponent::SystemTrayIconComponent()
  61863. {
  61864. addToDesktop (0);
  61865. }
  61866. SystemTrayIconComponent::~SystemTrayIconComponent()
  61867. {
  61868. }
  61869. END_JUCE_NAMESPACE
  61870. #endif
  61871. /*** End of inlined file: juce_SystemTrayIconComponent.cpp ***/
  61872. /*** Start of inlined file: juce_AlertWindow.cpp ***/
  61873. BEGIN_JUCE_NAMESPACE
  61874. class AlertWindowTextEditor : public TextEditor
  61875. {
  61876. public:
  61877. AlertWindowTextEditor (const String& name, const bool isPasswordBox)
  61878. : TextEditor (name, isPasswordBox ? getDefaultPasswordChar() : 0)
  61879. {
  61880. setSelectAllWhenFocused (true);
  61881. }
  61882. ~AlertWindowTextEditor()
  61883. {
  61884. }
  61885. void returnPressed()
  61886. {
  61887. // pass these up the component hierarchy to be trigger the buttons
  61888. getParentComponent()->keyPressed (KeyPress (KeyPress::returnKey, 0, '\n'));
  61889. }
  61890. void escapePressed()
  61891. {
  61892. // pass these up the component hierarchy to be trigger the buttons
  61893. getParentComponent()->keyPressed (KeyPress (KeyPress::escapeKey, 0, 0));
  61894. }
  61895. private:
  61896. AlertWindowTextEditor (const AlertWindowTextEditor&);
  61897. AlertWindowTextEditor& operator= (const AlertWindowTextEditor&);
  61898. static juce_wchar getDefaultPasswordChar() throw()
  61899. {
  61900. #if JUCE_LINUX
  61901. return 0x2022;
  61902. #else
  61903. return 0x25cf;
  61904. #endif
  61905. }
  61906. };
  61907. AlertWindow::AlertWindow (const String& title,
  61908. const String& message,
  61909. AlertIconType iconType,
  61910. Component* associatedComponent_)
  61911. : TopLevelWindow (title, true),
  61912. alertIconType (iconType),
  61913. associatedComponent (associatedComponent_)
  61914. {
  61915. if (message.isEmpty())
  61916. text = " "; // to force an update if the message is empty
  61917. setMessage (message);
  61918. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  61919. {
  61920. Component* const c = Desktop::getInstance().getComponent (i);
  61921. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  61922. {
  61923. setAlwaysOnTop (true);
  61924. break;
  61925. }
  61926. }
  61927. if (! JUCEApplication::isStandaloneApp())
  61928. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  61929. lookAndFeelChanged();
  61930. constrainer.setMinimumOnscreenAmounts (0x10000, 0x10000, 0x10000, 0x10000);
  61931. }
  61932. AlertWindow::~AlertWindow()
  61933. {
  61934. for (int i = customComps.size(); --i >= 0;)
  61935. removeChildComponent ((Component*) customComps[i]);
  61936. deleteAllChildren();
  61937. }
  61938. void AlertWindow::userTriedToCloseWindow()
  61939. {
  61940. exitModalState (0);
  61941. }
  61942. void AlertWindow::setMessage (const String& message)
  61943. {
  61944. const String newMessage (message.substring (0, 2048));
  61945. if (text != newMessage)
  61946. {
  61947. text = newMessage;
  61948. font.setHeight (15.0f);
  61949. Font titleFont (font.getHeight() * 1.1f, Font::bold);
  61950. textLayout.setText (getName() + "\n\n", titleFont);
  61951. textLayout.appendText (text, font);
  61952. updateLayout (true);
  61953. repaint();
  61954. }
  61955. }
  61956. void AlertWindow::buttonClicked (Button* button)
  61957. {
  61958. for (int i = 0; i < buttons.size(); i++)
  61959. {
  61960. TextButton* const c = (TextButton*) buttons[i];
  61961. if (button->getName() == c->getName())
  61962. {
  61963. if (c->getParentComponent() != 0)
  61964. c->getParentComponent()->exitModalState (c->getCommandID());
  61965. break;
  61966. }
  61967. }
  61968. }
  61969. void AlertWindow::addButton (const String& name,
  61970. const int returnValue,
  61971. const KeyPress& shortcutKey1,
  61972. const KeyPress& shortcutKey2)
  61973. {
  61974. TextButton* const b = new TextButton (name, String::empty);
  61975. b->setWantsKeyboardFocus (true);
  61976. b->setMouseClickGrabsKeyboardFocus (false);
  61977. b->setCommandToTrigger (0, returnValue, false);
  61978. b->addShortcut (shortcutKey1);
  61979. b->addShortcut (shortcutKey2);
  61980. b->addButtonListener (this);
  61981. b->changeWidthToFitText (getLookAndFeel().getAlertWindowButtonHeight());
  61982. addAndMakeVisible (b, 0);
  61983. buttons.add (b);
  61984. updateLayout (false);
  61985. }
  61986. int AlertWindow::getNumButtons() const
  61987. {
  61988. return buttons.size();
  61989. }
  61990. void AlertWindow::triggerButtonClick (const String& buttonName)
  61991. {
  61992. for (int i = buttons.size(); --i >= 0;)
  61993. {
  61994. TextButton* const b = (TextButton*) buttons[i];
  61995. if (buttonName == b->getName())
  61996. {
  61997. b->triggerClick();
  61998. break;
  61999. }
  62000. }
  62001. }
  62002. void AlertWindow::addTextEditor (const String& name,
  62003. const String& initialContents,
  62004. const String& onScreenLabel,
  62005. const bool isPasswordBox)
  62006. {
  62007. AlertWindowTextEditor* const tc = new AlertWindowTextEditor (name, isPasswordBox);
  62008. tc->setColour (TextEditor::outlineColourId, findColour (ComboBox::outlineColourId));
  62009. tc->setFont (font);
  62010. tc->setText (initialContents);
  62011. tc->setCaretPosition (initialContents.length());
  62012. addAndMakeVisible (tc);
  62013. textBoxes.add (tc);
  62014. allComps.add (tc);
  62015. textboxNames.add (onScreenLabel);
  62016. updateLayout (false);
  62017. }
  62018. TextEditor* AlertWindow::getTextEditor (const String& nameOfTextEditor) const
  62019. {
  62020. for (int i = textBoxes.size(); --i >= 0;)
  62021. if (static_cast <TextEditor*> (textBoxes.getUnchecked(i))->getName() == nameOfTextEditor)
  62022. return static_cast <TextEditor*> (textBoxes.getUnchecked(i));
  62023. return 0;
  62024. }
  62025. const String AlertWindow::getTextEditorContents (const String& nameOfTextEditor) const
  62026. {
  62027. TextEditor* const t = getTextEditor (nameOfTextEditor);
  62028. return t != 0 ? t->getText() : String::empty;
  62029. }
  62030. void AlertWindow::addComboBox (const String& name,
  62031. const StringArray& items,
  62032. const String& onScreenLabel)
  62033. {
  62034. ComboBox* const cb = new ComboBox (name);
  62035. for (int i = 0; i < items.size(); ++i)
  62036. cb->addItem (items[i], i + 1);
  62037. addAndMakeVisible (cb);
  62038. cb->setSelectedItemIndex (0);
  62039. comboBoxes.add (cb);
  62040. allComps.add (cb);
  62041. comboBoxNames.add (onScreenLabel);
  62042. updateLayout (false);
  62043. }
  62044. ComboBox* AlertWindow::getComboBoxComponent (const String& nameOfList) const
  62045. {
  62046. for (int i = comboBoxes.size(); --i >= 0;)
  62047. if (((ComboBox*) comboBoxes[i])->getName() == nameOfList)
  62048. return (ComboBox*) comboBoxes[i];
  62049. return 0;
  62050. }
  62051. class AlertTextComp : public TextEditor
  62052. {
  62053. public:
  62054. AlertTextComp (const String& message,
  62055. const Font& font)
  62056. {
  62057. setReadOnly (true);
  62058. setMultiLine (true, true);
  62059. setCaretVisible (false);
  62060. setScrollbarsShown (true);
  62061. lookAndFeelChanged();
  62062. setWantsKeyboardFocus (false);
  62063. setFont (font);
  62064. setText (message, false);
  62065. bestWidth = 2 * (int) std::sqrt (font.getHeight() * font.getStringWidth (message));
  62066. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  62067. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  62068. setColour (TextEditor::shadowColourId, Colours::transparentBlack);
  62069. }
  62070. ~AlertTextComp()
  62071. {
  62072. }
  62073. int getPreferredWidth() const throw() { return bestWidth; }
  62074. void updateLayout (const int width)
  62075. {
  62076. TextLayout text;
  62077. text.appendText (getText(), getFont());
  62078. text.layout (width - 8, Justification::topLeft, true);
  62079. setSize (width, jmin (width, text.getHeight() + (int) getFont().getHeight()));
  62080. }
  62081. private:
  62082. int bestWidth;
  62083. AlertTextComp (const AlertTextComp&);
  62084. AlertTextComp& operator= (const AlertTextComp&);
  62085. };
  62086. void AlertWindow::addTextBlock (const String& textBlock)
  62087. {
  62088. AlertTextComp* const c = new AlertTextComp (textBlock, font);
  62089. textBlocks.add (c);
  62090. allComps.add (c);
  62091. addAndMakeVisible (c);
  62092. updateLayout (false);
  62093. }
  62094. void AlertWindow::addProgressBarComponent (double& progressValue)
  62095. {
  62096. ProgressBar* const pb = new ProgressBar (progressValue);
  62097. progressBars.add (pb);
  62098. allComps.add (pb);
  62099. addAndMakeVisible (pb);
  62100. updateLayout (false);
  62101. }
  62102. void AlertWindow::addCustomComponent (Component* const component)
  62103. {
  62104. customComps.add (component);
  62105. allComps.add (component);
  62106. addAndMakeVisible (component);
  62107. updateLayout (false);
  62108. }
  62109. int AlertWindow::getNumCustomComponents() const
  62110. {
  62111. return customComps.size();
  62112. }
  62113. Component* AlertWindow::getCustomComponent (const int index) const
  62114. {
  62115. return (Component*) customComps [index];
  62116. }
  62117. Component* AlertWindow::removeCustomComponent (const int index)
  62118. {
  62119. Component* const c = getCustomComponent (index);
  62120. if (c != 0)
  62121. {
  62122. customComps.removeValue (c);
  62123. allComps.removeValue (c);
  62124. removeChildComponent (c);
  62125. updateLayout (false);
  62126. }
  62127. return c;
  62128. }
  62129. void AlertWindow::paint (Graphics& g)
  62130. {
  62131. getLookAndFeel().drawAlertBox (g, *this, textArea, textLayout);
  62132. g.setColour (findColour (textColourId));
  62133. g.setFont (getLookAndFeel().getAlertWindowFont());
  62134. int i;
  62135. for (i = textBoxes.size(); --i >= 0;)
  62136. {
  62137. const TextEditor* const te = (TextEditor*) textBoxes[i];
  62138. g.drawFittedText (textboxNames[i],
  62139. te->getX(), te->getY() - 14,
  62140. te->getWidth(), 14,
  62141. Justification::centredLeft, 1);
  62142. }
  62143. for (i = comboBoxNames.size(); --i >= 0;)
  62144. {
  62145. const ComboBox* const cb = (ComboBox*) comboBoxes[i];
  62146. g.drawFittedText (comboBoxNames[i],
  62147. cb->getX(), cb->getY() - 14,
  62148. cb->getWidth(), 14,
  62149. Justification::centredLeft, 1);
  62150. }
  62151. for (i = customComps.size(); --i >= 0;)
  62152. {
  62153. const Component* const c = (Component*) customComps[i];
  62154. g.drawFittedText (c->getName(),
  62155. c->getX(), c->getY() - 14,
  62156. c->getWidth(), 14,
  62157. Justification::centredLeft, 1);
  62158. }
  62159. }
  62160. void AlertWindow::updateLayout (const bool onlyIncreaseSize)
  62161. {
  62162. const int titleH = 24;
  62163. const int iconWidth = 80;
  62164. const int wid = jmax (font.getStringWidth (text),
  62165. font.getStringWidth (getName()));
  62166. const int sw = (int) std::sqrt (font.getHeight() * wid);
  62167. int w = jmin (300 + sw * 2, (int) (getParentWidth() * 0.7f));
  62168. const int edgeGap = 10;
  62169. const int labelHeight = 18;
  62170. int iconSpace;
  62171. if (alertIconType == NoIcon)
  62172. {
  62173. textLayout.layout (w, Justification::horizontallyCentred, true);
  62174. iconSpace = 0;
  62175. }
  62176. else
  62177. {
  62178. textLayout.layout (w, Justification::left, true);
  62179. iconSpace = iconWidth;
  62180. }
  62181. w = jmax (350, textLayout.getWidth() + iconSpace + edgeGap * 4);
  62182. w = jmin (w, (int) (getParentWidth() * 0.7f));
  62183. const int textLayoutH = textLayout.getHeight();
  62184. const int textBottom = 16 + titleH + textLayoutH;
  62185. int h = textBottom;
  62186. int buttonW = 40;
  62187. int i;
  62188. for (i = 0; i < buttons.size(); ++i)
  62189. buttonW += 16 + ((const TextButton*) buttons[i])->getWidth();
  62190. w = jmax (buttonW, w);
  62191. h += (textBoxes.size() + comboBoxes.size() + progressBars.size()) * 50;
  62192. if (buttons.size() > 0)
  62193. h += 20 + ((TextButton*) buttons[0])->getHeight();
  62194. for (i = customComps.size(); --i >= 0;)
  62195. {
  62196. Component* c = (Component*) customComps[i];
  62197. w = jmax (w, (c->getWidth() * 100) / 80);
  62198. h += 10 + c->getHeight();
  62199. if (c->getName().isNotEmpty())
  62200. h += labelHeight;
  62201. }
  62202. for (i = textBlocks.size(); --i >= 0;)
  62203. {
  62204. const AlertTextComp* const ac = (AlertTextComp*) textBlocks[i];
  62205. w = jmax (w, ac->getPreferredWidth());
  62206. }
  62207. w = jmin (w, (int) (getParentWidth() * 0.7f));
  62208. for (i = textBlocks.size(); --i >= 0;)
  62209. {
  62210. AlertTextComp* const ac = (AlertTextComp*) textBlocks[i];
  62211. ac->updateLayout ((int) (w * 0.8f));
  62212. h += ac->getHeight() + 10;
  62213. }
  62214. h = jmin (getParentHeight() - 50, h);
  62215. if (onlyIncreaseSize)
  62216. {
  62217. w = jmax (w, getWidth());
  62218. h = jmax (h, getHeight());
  62219. }
  62220. if (! isVisible())
  62221. {
  62222. centreAroundComponent (associatedComponent, w, h);
  62223. }
  62224. else
  62225. {
  62226. const int cx = getX() + getWidth() / 2;
  62227. const int cy = getY() + getHeight() / 2;
  62228. setBounds (cx - w / 2,
  62229. cy - h / 2,
  62230. w, h);
  62231. }
  62232. textArea.setBounds (edgeGap, edgeGap, w - (edgeGap * 2), h - edgeGap);
  62233. const int spacer = 16;
  62234. int totalWidth = -spacer;
  62235. for (i = buttons.size(); --i >= 0;)
  62236. totalWidth += ((TextButton*) buttons[i])->getWidth() + spacer;
  62237. int x = (w - totalWidth) / 2;
  62238. int y = (int) (getHeight() * 0.95f);
  62239. for (i = 0; i < buttons.size(); ++i)
  62240. {
  62241. TextButton* const c = (TextButton*) buttons[i];
  62242. int ny = proportionOfHeight (0.95f) - c->getHeight();
  62243. c->setTopLeftPosition (x, ny);
  62244. if (ny < y)
  62245. y = ny;
  62246. x += c->getWidth() + spacer;
  62247. c->toFront (false);
  62248. }
  62249. y = textBottom;
  62250. for (i = 0; i < allComps.size(); ++i)
  62251. {
  62252. Component* const c = (Component*) allComps[i];
  62253. h = 22;
  62254. const int comboIndex = comboBoxes.indexOf (c);
  62255. if (comboIndex >= 0 && comboBoxNames [comboIndex].isNotEmpty())
  62256. y += labelHeight;
  62257. const int tbIndex = textBoxes.indexOf (c);
  62258. if (tbIndex >= 0 && textboxNames[tbIndex].isNotEmpty())
  62259. y += labelHeight;
  62260. if (customComps.contains (c))
  62261. {
  62262. if (c->getName().isNotEmpty())
  62263. y += labelHeight;
  62264. c->setTopLeftPosition (proportionOfWidth (0.1f), y);
  62265. h = c->getHeight();
  62266. }
  62267. else if (textBlocks.contains (c))
  62268. {
  62269. c->setTopLeftPosition ((getWidth() - c->getWidth()) / 2, y);
  62270. h = c->getHeight();
  62271. }
  62272. else
  62273. {
  62274. c->setBounds (proportionOfWidth (0.1f), y, proportionOfWidth (0.8f), h);
  62275. }
  62276. y += h + 10;
  62277. }
  62278. setWantsKeyboardFocus (getNumChildComponents() == 0);
  62279. }
  62280. bool AlertWindow::containsAnyExtraComponents() const
  62281. {
  62282. return textBoxes.size()
  62283. + comboBoxes.size()
  62284. + progressBars.size()
  62285. + customComps.size() > 0;
  62286. }
  62287. void AlertWindow::mouseDown (const MouseEvent&)
  62288. {
  62289. dragger.startDraggingComponent (this, &constrainer);
  62290. }
  62291. void AlertWindow::mouseDrag (const MouseEvent& e)
  62292. {
  62293. dragger.dragComponent (this, e);
  62294. }
  62295. bool AlertWindow::keyPressed (const KeyPress& key)
  62296. {
  62297. for (int i = buttons.size(); --i >= 0;)
  62298. {
  62299. TextButton* const b = (TextButton*) buttons[i];
  62300. if (b->isRegisteredForShortcut (key))
  62301. {
  62302. b->triggerClick();
  62303. return true;
  62304. }
  62305. }
  62306. if (key.isKeyCode (KeyPress::escapeKey) && buttons.size() == 0)
  62307. {
  62308. exitModalState (0);
  62309. return true;
  62310. }
  62311. else if (key.isKeyCode (KeyPress::returnKey) && buttons.size() == 1)
  62312. {
  62313. ((TextButton*) buttons.getFirst())->triggerClick();
  62314. return true;
  62315. }
  62316. return false;
  62317. }
  62318. void AlertWindow::lookAndFeelChanged()
  62319. {
  62320. const int newFlags = getLookAndFeel().getAlertBoxWindowFlags();
  62321. setUsingNativeTitleBar ((newFlags & ComponentPeer::windowHasTitleBar) != 0);
  62322. setDropShadowEnabled (isOpaque() && (newFlags & ComponentPeer::windowHasDropShadow) != 0);
  62323. }
  62324. int AlertWindow::getDesktopWindowStyleFlags() const
  62325. {
  62326. return getLookAndFeel().getAlertBoxWindowFlags();
  62327. }
  62328. struct AlertWindowInfo
  62329. {
  62330. String title, message, button1, button2, button3;
  62331. AlertWindow::AlertIconType iconType;
  62332. int numButtons;
  62333. Component::SafePointer<Component> associatedComponent;
  62334. int run() const
  62335. {
  62336. return (int) (pointer_sized_int)
  62337. MessageManager::getInstance()->callFunctionOnMessageThread (showCallback, (void*) this);
  62338. }
  62339. private:
  62340. int show() const
  62341. {
  62342. LookAndFeel& lf = associatedComponent != 0 ? associatedComponent->getLookAndFeel()
  62343. : LookAndFeel::getDefaultLookAndFeel();
  62344. ScopedPointer <Component> alertBox (lf.createAlertWindow (title, message, button1, button2, button3,
  62345. iconType, numButtons, associatedComponent));
  62346. jassert (alertBox != 0); // you have to return one of these!
  62347. return alertBox->runModalLoop();
  62348. }
  62349. static void* showCallback (void* userData)
  62350. {
  62351. return (void*) (pointer_sized_int) ((const AlertWindowInfo*) userData)->show();
  62352. }
  62353. };
  62354. void AlertWindow::showMessageBox (AlertIconType iconType,
  62355. const String& title,
  62356. const String& message,
  62357. const String& buttonText,
  62358. Component* associatedComponent)
  62359. {
  62360. AlertWindowInfo info;
  62361. info.title = title;
  62362. info.message = message;
  62363. info.button1 = buttonText.isEmpty() ? TRANS("ok") : buttonText;
  62364. info.iconType = iconType;
  62365. info.numButtons = 1;
  62366. info.associatedComponent = associatedComponent;
  62367. info.run();
  62368. }
  62369. bool AlertWindow::showOkCancelBox (AlertIconType iconType,
  62370. const String& title,
  62371. const String& message,
  62372. const String& button1Text,
  62373. const String& button2Text,
  62374. Component* associatedComponent)
  62375. {
  62376. AlertWindowInfo info;
  62377. info.title = title;
  62378. info.message = message;
  62379. info.button1 = button1Text.isEmpty() ? TRANS("ok") : button1Text;
  62380. info.button2 = button2Text.isEmpty() ? TRANS("cancel") : button2Text;
  62381. info.iconType = iconType;
  62382. info.numButtons = 2;
  62383. info.associatedComponent = associatedComponent;
  62384. return info.run() != 0;
  62385. }
  62386. int AlertWindow::showYesNoCancelBox (AlertIconType iconType,
  62387. const String& title,
  62388. const String& message,
  62389. const String& button1Text,
  62390. const String& button2Text,
  62391. const String& button3Text,
  62392. Component* associatedComponent)
  62393. {
  62394. AlertWindowInfo info;
  62395. info.title = title;
  62396. info.message = message;
  62397. info.button1 = button1Text.isEmpty() ? TRANS("yes") : button1Text;
  62398. info.button2 = button2Text.isEmpty() ? TRANS("no") : button2Text;
  62399. info.button3 = button3Text.isEmpty() ? TRANS("cancel") : button3Text;
  62400. info.iconType = iconType;
  62401. info.numButtons = 3;
  62402. info.associatedComponent = associatedComponent;
  62403. return info.run();
  62404. }
  62405. END_JUCE_NAMESPACE
  62406. /*** End of inlined file: juce_AlertWindow.cpp ***/
  62407. /*** Start of inlined file: juce_CallOutBox.cpp ***/
  62408. BEGIN_JUCE_NAMESPACE
  62409. CallOutBox::CallOutBox (Component& contentComponent,
  62410. Component& componentToPointTo,
  62411. Component* const parentComponent)
  62412. : borderSpace (20), arrowSize (16.0f), content (contentComponent)
  62413. {
  62414. addAndMakeVisible (&content);
  62415. if (parentComponent != 0)
  62416. {
  62417. parentComponent->addChildComponent (this);
  62418. updatePosition (componentToPointTo.getLocalBounds()
  62419. + componentToPointTo.relativePositionToOtherComponent (parentComponent, Point<int>()),
  62420. parentComponent->getLocalBounds());
  62421. setVisible (true);
  62422. }
  62423. else
  62424. {
  62425. if (! JUCEApplication::isStandaloneApp())
  62426. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  62427. updatePosition (componentToPointTo.getScreenBounds(),
  62428. componentToPointTo.getParentMonitorArea());
  62429. addToDesktop (ComponentPeer::windowIsTemporary);
  62430. }
  62431. }
  62432. CallOutBox::~CallOutBox()
  62433. {
  62434. }
  62435. void CallOutBox::setArrowSize (const float newSize)
  62436. {
  62437. arrowSize = newSize;
  62438. borderSpace = jmax (20, (int) arrowSize);
  62439. refreshPath();
  62440. }
  62441. void CallOutBox::paint (Graphics& g)
  62442. {
  62443. if (background.isNull())
  62444. {
  62445. background = Image (Image::ARGB, getWidth(), getHeight(), true);
  62446. Graphics g (background);
  62447. getLookAndFeel().drawCallOutBoxBackground (*this, g, outline);
  62448. }
  62449. g.setColour (Colours::black);
  62450. g.drawImageAt (background, 0, 0);
  62451. }
  62452. void CallOutBox::resized()
  62453. {
  62454. content.setTopLeftPosition (borderSpace, borderSpace);
  62455. refreshPath();
  62456. }
  62457. void CallOutBox::moved()
  62458. {
  62459. refreshPath();
  62460. }
  62461. void CallOutBox::childBoundsChanged (Component*)
  62462. {
  62463. updatePosition (targetArea, availableArea);
  62464. }
  62465. bool CallOutBox::hitTest (int x, int y)
  62466. {
  62467. return outline.contains ((float) x, (float) y);
  62468. }
  62469. enum { callOutBoxDismissCommandId = 0x4f83a04b };
  62470. void CallOutBox::inputAttemptWhenModal()
  62471. {
  62472. const Point<int> mousePos (getMouseXYRelative() + getBounds().getPosition());
  62473. if (targetArea.contains (mousePos))
  62474. {
  62475. // if you click on the area that originally popped-up the callout, you expect it
  62476. // to get rid of the box, but deleting the box here allows the click to pass through and
  62477. // probably re-trigger it, so we need to dismiss the box asynchronously to consume the click..
  62478. postCommandMessage (callOutBoxDismissCommandId);
  62479. }
  62480. else
  62481. {
  62482. exitModalState (0);
  62483. setVisible (false);
  62484. }
  62485. }
  62486. void CallOutBox::handleCommandMessage (int commandId)
  62487. {
  62488. Component::handleCommandMessage (commandId);
  62489. if (commandId == callOutBoxDismissCommandId)
  62490. {
  62491. exitModalState (0);
  62492. setVisible (false);
  62493. }
  62494. }
  62495. bool CallOutBox::keyPressed (const KeyPress& key)
  62496. {
  62497. if (key.isKeyCode (KeyPress::escapeKey))
  62498. {
  62499. inputAttemptWhenModal();
  62500. return true;
  62501. }
  62502. return false;
  62503. }
  62504. void CallOutBox::updatePosition (const Rectangle<int>& newAreaToPointTo, const Rectangle<int>& newAreaToFitIn)
  62505. {
  62506. targetArea = newAreaToPointTo;
  62507. availableArea = newAreaToFitIn;
  62508. Rectangle<int> bounds (0, 0,
  62509. content.getWidth() + borderSpace * 2,
  62510. content.getHeight() + borderSpace * 2);
  62511. const int hw = bounds.getWidth() / 2;
  62512. const int hh = bounds.getHeight() / 2;
  62513. const float hwReduced = (float) (hw - borderSpace * 3);
  62514. const float hhReduced = (float) (hh - borderSpace * 3);
  62515. const float arrowIndent = borderSpace - arrowSize;
  62516. Point<float> targets[4] = { Point<float> ((float) targetArea.getCentreX(), (float) targetArea.getBottom()),
  62517. Point<float> ((float) targetArea.getRight(), (float) targetArea.getCentreY()),
  62518. Point<float> ((float) targetArea.getX(), (float) targetArea.getCentreY()),
  62519. Point<float> ((float) targetArea.getCentreX(), (float) targetArea.getY()) };
  62520. Line<float> lines[4] = { Line<float> (targets[0].translated (-hwReduced, hh - arrowIndent), targets[0].translated (hwReduced, hh - arrowIndent)),
  62521. Line<float> (targets[1].translated (hw - arrowIndent, -hhReduced), targets[1].translated (hw - arrowIndent, hhReduced)),
  62522. Line<float> (targets[2].translated (-(hw - arrowIndent), -hhReduced), targets[2].translated (-(hw - arrowIndent), hhReduced)),
  62523. Line<float> (targets[3].translated (-hwReduced, -(hh - arrowIndent)), targets[3].translated (hwReduced, -(hh - arrowIndent))) };
  62524. const Rectangle<float> centrePointArea (newAreaToFitIn.reduced (hw, hh).toFloat());
  62525. float nearest = 1.0e9f;
  62526. for (int i = 0; i < 4; ++i)
  62527. {
  62528. Line<float> constrainedLine (centrePointArea.getConstrainedPoint (lines[i].getStart()),
  62529. centrePointArea.getConstrainedPoint (lines[i].getEnd()));
  62530. const Point<float> centre (constrainedLine.findNearestPointTo (centrePointArea.getCentre()));
  62531. float distanceFromCentre = centre.getDistanceFrom (centrePointArea.getCentre());
  62532. if (! (centrePointArea.contains (lines[i].getStart()) || centrePointArea.contains (lines[i].getEnd())))
  62533. distanceFromCentre *= 2.0f;
  62534. if (distanceFromCentre < nearest)
  62535. {
  62536. nearest = distanceFromCentre;
  62537. targetPoint = targets[i];
  62538. bounds.setPosition ((int) (centre.getX() - hw),
  62539. (int) (centre.getY() - hh));
  62540. }
  62541. }
  62542. setBounds (bounds);
  62543. }
  62544. void CallOutBox::refreshPath()
  62545. {
  62546. repaint();
  62547. background = Image::null;
  62548. outline.clear();
  62549. const float gap = 4.5f;
  62550. const float cornerSize = 9.0f;
  62551. const float cornerSize2 = 2.0f * cornerSize;
  62552. const float arrowBaseWidth = arrowSize * 0.7f;
  62553. const float left = content.getX() - gap, top = content.getY() - gap, right = content.getRight() + gap, bottom = content.getBottom() + gap;
  62554. const float targetX = targetPoint.getX() - getX(), targetY = targetPoint.getY() - getY();
  62555. outline.startNewSubPath (left + cornerSize, top);
  62556. if (targetY <= top)
  62557. {
  62558. outline.lineTo (targetX - arrowBaseWidth, top);
  62559. outline.lineTo (targetX, targetY);
  62560. outline.lineTo (targetX + arrowBaseWidth, top);
  62561. }
  62562. outline.lineTo (right - cornerSize, top);
  62563. outline.addArc (right - cornerSize2, top, cornerSize2, cornerSize2, 0, float_Pi * 0.5f);
  62564. if (targetX >= right)
  62565. {
  62566. outline.lineTo (right, targetY - arrowBaseWidth);
  62567. outline.lineTo (targetX, targetY);
  62568. outline.lineTo (right, targetY + arrowBaseWidth);
  62569. }
  62570. outline.lineTo (right, bottom - cornerSize);
  62571. outline.addArc (right - cornerSize2, bottom - cornerSize2, cornerSize2, cornerSize2, float_Pi * 0.5f, float_Pi);
  62572. if (targetY >= bottom)
  62573. {
  62574. outline.lineTo (targetX + arrowBaseWidth, bottom);
  62575. outline.lineTo (targetX, targetY);
  62576. outline.lineTo (targetX - arrowBaseWidth, bottom);
  62577. }
  62578. outline.lineTo (left + cornerSize, bottom);
  62579. outline.addArc (left, bottom - cornerSize2, cornerSize2, cornerSize2, float_Pi, float_Pi * 1.5f);
  62580. if (targetX <= left)
  62581. {
  62582. outline.lineTo (left, targetY + arrowBaseWidth);
  62583. outline.lineTo (targetX, targetY);
  62584. outline.lineTo (left, targetY - arrowBaseWidth);
  62585. }
  62586. outline.lineTo (left, top + cornerSize);
  62587. outline.addArc (left, top, cornerSize2, cornerSize2, float_Pi * 1.5f, float_Pi * 2.0f - 0.05f);
  62588. outline.closeSubPath();
  62589. }
  62590. END_JUCE_NAMESPACE
  62591. /*** End of inlined file: juce_CallOutBox.cpp ***/
  62592. /*** Start of inlined file: juce_ComponentPeer.cpp ***/
  62593. BEGIN_JUCE_NAMESPACE
  62594. //#define JUCE_ENABLE_REPAINT_DEBUGGING 1
  62595. static Array <ComponentPeer*> heavyweightPeers;
  62596. ComponentPeer::ComponentPeer (Component* const component_, const int styleFlags_)
  62597. : component (component_),
  62598. styleFlags (styleFlags_),
  62599. lastPaintTime (0),
  62600. constrainer (0),
  62601. lastDragAndDropCompUnderMouse (0),
  62602. fakeMouseMessageSent (false),
  62603. isWindowMinimised (false)
  62604. {
  62605. heavyweightPeers.add (this);
  62606. }
  62607. ComponentPeer::~ComponentPeer()
  62608. {
  62609. heavyweightPeers.removeValue (this);
  62610. Desktop::getInstance().triggerFocusCallback();
  62611. }
  62612. int ComponentPeer::getNumPeers() throw()
  62613. {
  62614. return heavyweightPeers.size();
  62615. }
  62616. ComponentPeer* ComponentPeer::getPeer (const int index) throw()
  62617. {
  62618. return heavyweightPeers [index];
  62619. }
  62620. ComponentPeer* ComponentPeer::getPeerFor (const Component* const component) throw()
  62621. {
  62622. for (int i = heavyweightPeers.size(); --i >= 0;)
  62623. {
  62624. ComponentPeer* const peer = heavyweightPeers.getUnchecked(i);
  62625. if (peer->getComponent() == component)
  62626. return peer;
  62627. }
  62628. return 0;
  62629. }
  62630. bool ComponentPeer::isValidPeer (const ComponentPeer* const peer) throw()
  62631. {
  62632. return heavyweightPeers.contains (const_cast <ComponentPeer*> (peer));
  62633. }
  62634. void ComponentPeer::updateCurrentModifiers() throw()
  62635. {
  62636. ModifierKeys::updateCurrentModifiers();
  62637. }
  62638. void ComponentPeer::handleMouseEvent (const int touchIndex, const Point<int>& positionWithinPeer, const ModifierKeys& newMods, const int64 time)
  62639. {
  62640. MouseInputSource* const mouse = Desktop::getInstance().getMouseSource (touchIndex);
  62641. jassert (mouse != 0); // not enough sources!
  62642. mouse->handleEvent (this, positionWithinPeer, time, newMods);
  62643. }
  62644. void ComponentPeer::handleMouseWheel (const int touchIndex, const Point<int>& positionWithinPeer, const int64 time, const float x, const float y)
  62645. {
  62646. MouseInputSource* const mouse = Desktop::getInstance().getMouseSource (touchIndex);
  62647. jassert (mouse != 0); // not enough sources!
  62648. mouse->handleWheel (this, positionWithinPeer, time, x, y);
  62649. }
  62650. void ComponentPeer::handlePaint (LowLevelGraphicsContext& contextToPaintTo)
  62651. {
  62652. Graphics g (&contextToPaintTo);
  62653. #if JUCE_ENABLE_REPAINT_DEBUGGING
  62654. g.saveState();
  62655. #endif
  62656. JUCE_TRY
  62657. {
  62658. component->paintEntireComponent (g, true);
  62659. }
  62660. JUCE_CATCH_EXCEPTION
  62661. #if JUCE_ENABLE_REPAINT_DEBUGGING
  62662. // enabling this code will fill all areas that get repainted with a colour overlay, to show
  62663. // clearly when things are being repainted.
  62664. {
  62665. g.restoreState();
  62666. g.fillAll (Colour ((uint8) Random::getSystemRandom().nextInt (255),
  62667. (uint8) Random::getSystemRandom().nextInt (255),
  62668. (uint8) Random::getSystemRandom().nextInt (255),
  62669. (uint8) 0x50));
  62670. }
  62671. #endif
  62672. /** If this fails, it's probably be because your CPU floating-point precision mode has
  62673. been set to low.. This setting is sometimes changed by things like Direct3D, and can
  62674. mess up a lot of the calculations that the library needs to do.
  62675. */
  62676. jassert (roundToInt (10.1f) == 10);
  62677. }
  62678. bool ComponentPeer::handleKeyPress (const int keyCode,
  62679. const juce_wchar textCharacter)
  62680. {
  62681. updateCurrentModifiers();
  62682. Component* target = Component::getCurrentlyFocusedComponent() != 0
  62683. ? Component::getCurrentlyFocusedComponent()
  62684. : component;
  62685. if (target->isCurrentlyBlockedByAnotherModalComponent())
  62686. {
  62687. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  62688. if (currentModalComp != 0)
  62689. target = currentModalComp;
  62690. }
  62691. const KeyPress keyInfo (keyCode,
  62692. ModifierKeys::getCurrentModifiers().getRawFlags()
  62693. & ModifierKeys::allKeyboardModifiers,
  62694. textCharacter);
  62695. bool keyWasUsed = false;
  62696. while (target != 0)
  62697. {
  62698. const Component::SafePointer<Component> deletionChecker (target);
  62699. if (target->keyListeners_ != 0)
  62700. {
  62701. for (int i = target->keyListeners_->size(); --i >= 0;)
  62702. {
  62703. keyWasUsed = target->keyListeners_->getUnchecked(i)->keyPressed (keyInfo, target);
  62704. if (keyWasUsed || deletionChecker == 0)
  62705. return keyWasUsed;
  62706. i = jmin (i, target->keyListeners_->size());
  62707. }
  62708. }
  62709. keyWasUsed = target->keyPressed (keyInfo);
  62710. if (keyWasUsed || deletionChecker == 0)
  62711. break;
  62712. if (keyInfo.isKeyCode (KeyPress::tabKey) && Component::getCurrentlyFocusedComponent() != 0)
  62713. {
  62714. Component* const currentlyFocused = Component::getCurrentlyFocusedComponent();
  62715. currentlyFocused->moveKeyboardFocusToSibling (! keyInfo.getModifiers().isShiftDown());
  62716. keyWasUsed = (currentlyFocused != Component::getCurrentlyFocusedComponent());
  62717. break;
  62718. }
  62719. target = target->parentComponent_;
  62720. }
  62721. return keyWasUsed;
  62722. }
  62723. bool ComponentPeer::handleKeyUpOrDown (const bool isKeyDown)
  62724. {
  62725. updateCurrentModifiers();
  62726. Component* target = Component::getCurrentlyFocusedComponent() != 0
  62727. ? Component::getCurrentlyFocusedComponent()
  62728. : component;
  62729. if (target->isCurrentlyBlockedByAnotherModalComponent())
  62730. {
  62731. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  62732. if (currentModalComp != 0)
  62733. target = currentModalComp;
  62734. }
  62735. bool keyWasUsed = false;
  62736. while (target != 0)
  62737. {
  62738. const Component::SafePointer<Component> deletionChecker (target);
  62739. keyWasUsed = target->keyStateChanged (isKeyDown);
  62740. if (keyWasUsed || deletionChecker == 0)
  62741. break;
  62742. if (target->keyListeners_ != 0)
  62743. {
  62744. for (int i = target->keyListeners_->size(); --i >= 0;)
  62745. {
  62746. keyWasUsed = target->keyListeners_->getUnchecked(i)->keyStateChanged (isKeyDown, target);
  62747. if (keyWasUsed || deletionChecker == 0)
  62748. return keyWasUsed;
  62749. i = jmin (i, target->keyListeners_->size());
  62750. }
  62751. }
  62752. target = target->parentComponent_;
  62753. }
  62754. return keyWasUsed;
  62755. }
  62756. void ComponentPeer::handleModifierKeysChange()
  62757. {
  62758. updateCurrentModifiers();
  62759. Component* target = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  62760. if (target == 0)
  62761. target = Component::getCurrentlyFocusedComponent();
  62762. if (target == 0)
  62763. target = component;
  62764. if (target != 0)
  62765. target->internalModifierKeysChanged();
  62766. }
  62767. TextInputTarget* ComponentPeer::findCurrentTextInputTarget()
  62768. {
  62769. Component* const c = Component::getCurrentlyFocusedComponent();
  62770. if (component->isParentOf (c))
  62771. {
  62772. TextInputTarget* const ti = dynamic_cast <TextInputTarget*> (c);
  62773. if (ti != 0 && ti->isTextInputActive())
  62774. return ti;
  62775. }
  62776. return 0;
  62777. }
  62778. void ComponentPeer::handleBroughtToFront()
  62779. {
  62780. updateCurrentModifiers();
  62781. if (component != 0)
  62782. component->internalBroughtToFront();
  62783. }
  62784. void ComponentPeer::setConstrainer (ComponentBoundsConstrainer* const newConstrainer) throw()
  62785. {
  62786. constrainer = newConstrainer;
  62787. }
  62788. void ComponentPeer::handleMovedOrResized()
  62789. {
  62790. jassert (component->isValidComponent());
  62791. updateCurrentModifiers();
  62792. const bool nowMinimised = isMinimised();
  62793. if (component->flags.hasHeavyweightPeerFlag && ! nowMinimised)
  62794. {
  62795. const Component::SafePointer<Component> deletionChecker (component);
  62796. const Rectangle<int> newBounds (getBounds());
  62797. const bool wasMoved = (component->getPosition() != newBounds.getPosition());
  62798. const bool wasResized = (component->getWidth() != newBounds.getWidth() || component->getHeight() != newBounds.getHeight());
  62799. if (wasMoved || wasResized)
  62800. {
  62801. component->bounds_ = newBounds;
  62802. if (wasResized)
  62803. component->repaint();
  62804. component->sendMovedResizedMessages (wasMoved, wasResized);
  62805. if (deletionChecker == 0)
  62806. return;
  62807. }
  62808. }
  62809. if (isWindowMinimised != nowMinimised)
  62810. {
  62811. isWindowMinimised = nowMinimised;
  62812. component->minimisationStateChanged (nowMinimised);
  62813. component->sendVisibilityChangeMessage();
  62814. }
  62815. if (! isFullScreen())
  62816. lastNonFullscreenBounds = component->getBounds();
  62817. }
  62818. void ComponentPeer::handleFocusGain()
  62819. {
  62820. updateCurrentModifiers();
  62821. if (component->isParentOf (lastFocusedComponent))
  62822. {
  62823. Component::currentlyFocusedComponent = lastFocusedComponent;
  62824. Desktop::getInstance().triggerFocusCallback();
  62825. lastFocusedComponent->internalFocusGain (Component::focusChangedDirectly);
  62826. }
  62827. else
  62828. {
  62829. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  62830. component->grabKeyboardFocus();
  62831. else
  62832. Component::bringModalComponentToFront();
  62833. }
  62834. }
  62835. void ComponentPeer::handleFocusLoss()
  62836. {
  62837. updateCurrentModifiers();
  62838. if (component->hasKeyboardFocus (true))
  62839. {
  62840. lastFocusedComponent = Component::currentlyFocusedComponent;
  62841. if (lastFocusedComponent != 0)
  62842. {
  62843. Component::currentlyFocusedComponent = 0;
  62844. Desktop::getInstance().triggerFocusCallback();
  62845. lastFocusedComponent->internalFocusLoss (Component::focusChangedByMouseClick);
  62846. }
  62847. }
  62848. }
  62849. Component* ComponentPeer::getLastFocusedSubcomponent() const throw()
  62850. {
  62851. return (component->isParentOf (lastFocusedComponent) && lastFocusedComponent->isShowing())
  62852. ? static_cast <Component*> (lastFocusedComponent)
  62853. : component;
  62854. }
  62855. void ComponentPeer::handleScreenSizeChange()
  62856. {
  62857. updateCurrentModifiers();
  62858. component->parentSizeChanged();
  62859. handleMovedOrResized();
  62860. }
  62861. void ComponentPeer::setNonFullScreenBounds (const Rectangle<int>& newBounds) throw()
  62862. {
  62863. lastNonFullscreenBounds = newBounds;
  62864. }
  62865. const Rectangle<int>& ComponentPeer::getNonFullScreenBounds() const throw()
  62866. {
  62867. return lastNonFullscreenBounds;
  62868. }
  62869. namespace ComponentPeerHelpers
  62870. {
  62871. FileDragAndDropTarget* findDragAndDropTarget (Component* c,
  62872. const StringArray& files,
  62873. FileDragAndDropTarget* const lastOne)
  62874. {
  62875. while (c != 0)
  62876. {
  62877. FileDragAndDropTarget* const t = dynamic_cast <FileDragAndDropTarget*> (c);
  62878. if (t != 0 && (t == lastOne || t->isInterestedInFileDrag (files)))
  62879. return t;
  62880. c = c->getParentComponent();
  62881. }
  62882. return 0;
  62883. }
  62884. }
  62885. void ComponentPeer::handleFileDragMove (const StringArray& files, const Point<int>& position)
  62886. {
  62887. updateCurrentModifiers();
  62888. FileDragAndDropTarget* lastTarget
  62889. = dynamic_cast<FileDragAndDropTarget*> (static_cast<Component*> (dragAndDropTargetComponent));
  62890. FileDragAndDropTarget* newTarget = 0;
  62891. Component* const compUnderMouse = component->getComponentAt (position);
  62892. if (compUnderMouse != lastDragAndDropCompUnderMouse)
  62893. {
  62894. lastDragAndDropCompUnderMouse = compUnderMouse;
  62895. newTarget = ComponentPeerHelpers::findDragAndDropTarget (compUnderMouse, files, lastTarget);
  62896. if (newTarget != lastTarget)
  62897. {
  62898. if (lastTarget != 0)
  62899. lastTarget->fileDragExit (files);
  62900. dragAndDropTargetComponent = 0;
  62901. if (newTarget != 0)
  62902. {
  62903. dragAndDropTargetComponent = dynamic_cast <Component*> (newTarget);
  62904. const Point<int> pos (component->relativePositionToOtherComponent (dragAndDropTargetComponent, position));
  62905. newTarget->fileDragEnter (files, pos.getX(), pos.getY());
  62906. }
  62907. }
  62908. }
  62909. else
  62910. {
  62911. newTarget = lastTarget;
  62912. }
  62913. if (newTarget != 0)
  62914. {
  62915. Component* const targetComp = dynamic_cast <Component*> (newTarget);
  62916. const Point<int> pos (component->relativePositionToOtherComponent (targetComp, position));
  62917. newTarget->fileDragMove (files, pos.getX(), pos.getY());
  62918. }
  62919. }
  62920. void ComponentPeer::handleFileDragExit (const StringArray& files)
  62921. {
  62922. handleFileDragMove (files, Point<int> (-1, -1));
  62923. jassert (dragAndDropTargetComponent == 0);
  62924. lastDragAndDropCompUnderMouse = 0;
  62925. }
  62926. void ComponentPeer::handleFileDragDrop (const StringArray& files, const Point<int>& position)
  62927. {
  62928. handleFileDragMove (files, position);
  62929. if (dragAndDropTargetComponent != 0)
  62930. {
  62931. FileDragAndDropTarget* const target
  62932. = dynamic_cast<FileDragAndDropTarget*> (static_cast<Component*> (dragAndDropTargetComponent));
  62933. dragAndDropTargetComponent = 0;
  62934. lastDragAndDropCompUnderMouse = 0;
  62935. if (target != 0)
  62936. {
  62937. Component* const targetComp = dynamic_cast <Component*> (target);
  62938. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  62939. {
  62940. targetComp->internalModalInputAttempt();
  62941. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  62942. return;
  62943. }
  62944. const Point<int> pos (component->relativePositionToOtherComponent (targetComp, position));
  62945. target->filesDropped (files, pos.getX(), pos.getY());
  62946. }
  62947. }
  62948. }
  62949. void ComponentPeer::handleUserClosingWindow()
  62950. {
  62951. updateCurrentModifiers();
  62952. component->userTriedToCloseWindow();
  62953. }
  62954. void ComponentPeer::bringModalComponentToFront()
  62955. {
  62956. Component::bringModalComponentToFront();
  62957. }
  62958. void ComponentPeer::clearMaskedRegion()
  62959. {
  62960. maskedRegion.clear();
  62961. }
  62962. void ComponentPeer::addMaskedRegion (int x, int y, int w, int h)
  62963. {
  62964. maskedRegion.add (x, y, w, h);
  62965. }
  62966. const StringArray ComponentPeer::getAvailableRenderingEngines()
  62967. {
  62968. StringArray s;
  62969. s.add ("Software Renderer");
  62970. return s;
  62971. }
  62972. int ComponentPeer::getCurrentRenderingEngine() throw()
  62973. {
  62974. return 0;
  62975. }
  62976. void ComponentPeer::setCurrentRenderingEngine (int /*index*/)
  62977. {
  62978. }
  62979. END_JUCE_NAMESPACE
  62980. /*** End of inlined file: juce_ComponentPeer.cpp ***/
  62981. /*** Start of inlined file: juce_DialogWindow.cpp ***/
  62982. BEGIN_JUCE_NAMESPACE
  62983. DialogWindow::DialogWindow (const String& name,
  62984. const Colour& backgroundColour_,
  62985. const bool escapeKeyTriggersCloseButton_,
  62986. const bool addToDesktop_)
  62987. : DocumentWindow (name, backgroundColour_, DocumentWindow::closeButton, addToDesktop_),
  62988. escapeKeyTriggersCloseButton (escapeKeyTriggersCloseButton_)
  62989. {
  62990. }
  62991. DialogWindow::~DialogWindow()
  62992. {
  62993. }
  62994. void DialogWindow::resized()
  62995. {
  62996. DocumentWindow::resized();
  62997. const KeyPress esc (KeyPress::escapeKey, 0, 0);
  62998. if (escapeKeyTriggersCloseButton
  62999. && getCloseButton() != 0
  63000. && ! getCloseButton()->isRegisteredForShortcut (esc))
  63001. {
  63002. getCloseButton()->addShortcut (esc);
  63003. }
  63004. }
  63005. class TempDialogWindow : public DialogWindow
  63006. {
  63007. public:
  63008. TempDialogWindow (const String& title, const Colour& colour, const bool escapeCloses)
  63009. : DialogWindow (title, colour, escapeCloses, true)
  63010. {
  63011. if (! JUCEApplication::isStandaloneApp())
  63012. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  63013. }
  63014. ~TempDialogWindow()
  63015. {
  63016. }
  63017. void closeButtonPressed()
  63018. {
  63019. setVisible (false);
  63020. }
  63021. private:
  63022. TempDialogWindow (const TempDialogWindow&);
  63023. TempDialogWindow& operator= (const TempDialogWindow&);
  63024. };
  63025. int DialogWindow::showModalDialog (const String& dialogTitle,
  63026. Component* contentComponent,
  63027. Component* componentToCentreAround,
  63028. const Colour& colour,
  63029. const bool escapeKeyTriggersCloseButton,
  63030. const bool shouldBeResizable,
  63031. const bool useBottomRightCornerResizer)
  63032. {
  63033. TempDialogWindow dw (dialogTitle, colour, escapeKeyTriggersCloseButton);
  63034. dw.setContentComponent (contentComponent, true, true);
  63035. dw.centreAroundComponent (componentToCentreAround, dw.getWidth(), dw.getHeight());
  63036. dw.setResizable (shouldBeResizable, useBottomRightCornerResizer);
  63037. const int result = dw.runModalLoop();
  63038. dw.setContentComponent (0, false);
  63039. return result;
  63040. }
  63041. END_JUCE_NAMESPACE
  63042. /*** End of inlined file: juce_DialogWindow.cpp ***/
  63043. /*** Start of inlined file: juce_DocumentWindow.cpp ***/
  63044. BEGIN_JUCE_NAMESPACE
  63045. class DocumentWindow::ButtonListenerProxy : public ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  63046. {
  63047. public:
  63048. ButtonListenerProxy (DocumentWindow& owner_)
  63049. : owner (owner_)
  63050. {
  63051. }
  63052. void buttonClicked (Button* button)
  63053. {
  63054. if (button == owner.getMinimiseButton())
  63055. owner.minimiseButtonPressed();
  63056. else if (button == owner.getMaximiseButton())
  63057. owner.maximiseButtonPressed();
  63058. else if (button == owner.getCloseButton())
  63059. owner.closeButtonPressed();
  63060. }
  63061. juce_UseDebuggingNewOperator
  63062. private:
  63063. DocumentWindow& owner;
  63064. ButtonListenerProxy (const ButtonListenerProxy&);
  63065. ButtonListenerProxy& operator= (const ButtonListenerProxy&);
  63066. };
  63067. DocumentWindow::DocumentWindow (const String& title,
  63068. const Colour& backgroundColour,
  63069. const int requiredButtons_,
  63070. const bool addToDesktop_)
  63071. : ResizableWindow (title, backgroundColour, addToDesktop_),
  63072. titleBarHeight (26),
  63073. menuBarHeight (24),
  63074. requiredButtons (requiredButtons_),
  63075. #if JUCE_MAC
  63076. positionTitleBarButtonsOnLeft (true),
  63077. #else
  63078. positionTitleBarButtonsOnLeft (false),
  63079. #endif
  63080. drawTitleTextCentred (true),
  63081. menuBarModel (0)
  63082. {
  63083. setResizeLimits (128, 128, 32768, 32768);
  63084. lookAndFeelChanged();
  63085. }
  63086. DocumentWindow::~DocumentWindow()
  63087. {
  63088. for (int i = numElementsInArray (titleBarButtons); --i >= 0;)
  63089. titleBarButtons[i] = 0;
  63090. menuBar = 0;
  63091. }
  63092. void DocumentWindow::repaintTitleBar()
  63093. {
  63094. repaint (getTitleBarArea());
  63095. }
  63096. void DocumentWindow::setName (const String& newName)
  63097. {
  63098. if (newName != getName())
  63099. {
  63100. Component::setName (newName);
  63101. repaintTitleBar();
  63102. }
  63103. }
  63104. void DocumentWindow::setIcon (const Image& imageToUse)
  63105. {
  63106. titleBarIcon = imageToUse;
  63107. repaintTitleBar();
  63108. }
  63109. void DocumentWindow::setTitleBarHeight (const int newHeight)
  63110. {
  63111. titleBarHeight = newHeight;
  63112. resized();
  63113. repaintTitleBar();
  63114. }
  63115. void DocumentWindow::setTitleBarButtonsRequired (const int requiredButtons_,
  63116. const bool positionTitleBarButtonsOnLeft_)
  63117. {
  63118. requiredButtons = requiredButtons_;
  63119. positionTitleBarButtonsOnLeft = positionTitleBarButtonsOnLeft_;
  63120. lookAndFeelChanged();
  63121. }
  63122. void DocumentWindow::setTitleBarTextCentred (const bool textShouldBeCentred)
  63123. {
  63124. drawTitleTextCentred = textShouldBeCentred;
  63125. repaintTitleBar();
  63126. }
  63127. void DocumentWindow::setMenuBar (MenuBarModel* menuBarModel_,
  63128. const int menuBarHeight_)
  63129. {
  63130. if (menuBarModel != menuBarModel_)
  63131. {
  63132. menuBar = 0;
  63133. menuBarModel = menuBarModel_;
  63134. menuBarHeight = (menuBarHeight_ > 0) ? menuBarHeight_
  63135. : getLookAndFeel().getDefaultMenuBarHeight();
  63136. if (menuBarModel != 0)
  63137. {
  63138. // (call the Component method directly to avoid the assertion in ResizableWindow)
  63139. Component::addAndMakeVisible (menuBar = new MenuBarComponent (menuBarModel));
  63140. menuBar->setEnabled (isActiveWindow());
  63141. }
  63142. resized();
  63143. }
  63144. }
  63145. void DocumentWindow::closeButtonPressed()
  63146. {
  63147. /* If you've got a close button, you have to override this method to get
  63148. rid of your window!
  63149. If the window is just a pop-up, you should override this method and make
  63150. it delete the window in whatever way is appropriate for your app. E.g. you
  63151. might just want to call "delete this".
  63152. If your app is centred around this window such that the whole app should quit when
  63153. the window is closed, then you will probably want to use this method as an opportunity
  63154. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  63155. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  63156. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  63157. or closing it via the taskbar icon on Windows).
  63158. */
  63159. jassertfalse;
  63160. }
  63161. void DocumentWindow::minimiseButtonPressed()
  63162. {
  63163. setMinimised (true);
  63164. }
  63165. void DocumentWindow::maximiseButtonPressed()
  63166. {
  63167. setFullScreen (! isFullScreen());
  63168. }
  63169. void DocumentWindow::paint (Graphics& g)
  63170. {
  63171. ResizableWindow::paint (g);
  63172. if (resizableBorder == 0)
  63173. {
  63174. g.setColour (getBackgroundColour().overlaidWith (Colour (0x80000000)));
  63175. const BorderSize border (getBorderThickness());
  63176. g.fillRect (0, 0, getWidth(), border.getTop());
  63177. g.fillRect (0, border.getTop(), border.getLeft(), getHeight() - border.getTopAndBottom());
  63178. g.fillRect (getWidth() - border.getRight(), border.getTop(), border.getRight(), getHeight() - border.getTopAndBottom());
  63179. g.fillRect (0, getHeight() - border.getBottom(), getWidth(), border.getBottom());
  63180. }
  63181. const Rectangle<int> titleBarArea (getTitleBarArea());
  63182. g.reduceClipRegion (titleBarArea);
  63183. g.setOrigin (titleBarArea.getX(), titleBarArea.getY());
  63184. int titleSpaceX1 = 6;
  63185. int titleSpaceX2 = titleBarArea.getWidth() - 6;
  63186. for (int i = 0; i < 3; ++i)
  63187. {
  63188. if (titleBarButtons[i] != 0)
  63189. {
  63190. if (positionTitleBarButtonsOnLeft)
  63191. titleSpaceX1 = jmax (titleSpaceX1, titleBarButtons[i]->getRight() + (getWidth() - titleBarButtons[i]->getRight()) / 8);
  63192. else
  63193. titleSpaceX2 = jmin (titleSpaceX2, titleBarButtons[i]->getX() - (titleBarButtons[i]->getX() / 8));
  63194. }
  63195. }
  63196. getLookAndFeel().drawDocumentWindowTitleBar (*this, g,
  63197. titleBarArea.getWidth(),
  63198. titleBarArea.getHeight(),
  63199. titleSpaceX1,
  63200. jmax (1, titleSpaceX2 - titleSpaceX1),
  63201. titleBarIcon.isValid() ? &titleBarIcon : 0,
  63202. ! drawTitleTextCentred);
  63203. }
  63204. void DocumentWindow::resized()
  63205. {
  63206. ResizableWindow::resized();
  63207. if (titleBarButtons[1] != 0)
  63208. titleBarButtons[1]->setToggleState (isFullScreen(), false);
  63209. const Rectangle<int> titleBarArea (getTitleBarArea());
  63210. getLookAndFeel()
  63211. .positionDocumentWindowButtons (*this,
  63212. titleBarArea.getX(), titleBarArea.getY(),
  63213. titleBarArea.getWidth(), titleBarArea.getHeight(),
  63214. titleBarButtons[0],
  63215. titleBarButtons[1],
  63216. titleBarButtons[2],
  63217. positionTitleBarButtonsOnLeft);
  63218. if (menuBar != 0)
  63219. menuBar->setBounds (titleBarArea.getX(), titleBarArea.getBottom(),
  63220. titleBarArea.getWidth(), menuBarHeight);
  63221. }
  63222. const BorderSize DocumentWindow::getBorderThickness()
  63223. {
  63224. return BorderSize ((isFullScreen() || isUsingNativeTitleBar())
  63225. ? 0 : (resizableBorder != 0 ? 4 : 1));
  63226. }
  63227. const BorderSize DocumentWindow::getContentComponentBorder()
  63228. {
  63229. BorderSize border (getBorderThickness());
  63230. border.setTop (border.getTop()
  63231. + (isUsingNativeTitleBar() ? 0 : titleBarHeight)
  63232. + (menuBar != 0 ? menuBarHeight : 0));
  63233. return border;
  63234. }
  63235. int DocumentWindow::getTitleBarHeight() const
  63236. {
  63237. return isUsingNativeTitleBar() ? 0 : jmin (titleBarHeight, getHeight() - 4);
  63238. }
  63239. const Rectangle<int> DocumentWindow::getTitleBarArea()
  63240. {
  63241. const BorderSize border (getBorderThickness());
  63242. return Rectangle<int> (border.getLeft(), border.getTop(),
  63243. getWidth() - border.getLeftAndRight(),
  63244. getTitleBarHeight());
  63245. }
  63246. Button* DocumentWindow::getCloseButton() const throw()
  63247. {
  63248. return titleBarButtons[2];
  63249. }
  63250. Button* DocumentWindow::getMinimiseButton() const throw()
  63251. {
  63252. return titleBarButtons[0];
  63253. }
  63254. Button* DocumentWindow::getMaximiseButton() const throw()
  63255. {
  63256. return titleBarButtons[1];
  63257. }
  63258. int DocumentWindow::getDesktopWindowStyleFlags() const
  63259. {
  63260. int styleFlags = ResizableWindow::getDesktopWindowStyleFlags();
  63261. if ((requiredButtons & minimiseButton) != 0)
  63262. styleFlags |= ComponentPeer::windowHasMinimiseButton;
  63263. if ((requiredButtons & maximiseButton) != 0)
  63264. styleFlags |= ComponentPeer::windowHasMaximiseButton;
  63265. if ((requiredButtons & closeButton) != 0)
  63266. styleFlags |= ComponentPeer::windowHasCloseButton;
  63267. return styleFlags;
  63268. }
  63269. void DocumentWindow::lookAndFeelChanged()
  63270. {
  63271. int i;
  63272. for (i = numElementsInArray (titleBarButtons); --i >= 0;)
  63273. titleBarButtons[i] = 0;
  63274. if (! isUsingNativeTitleBar())
  63275. {
  63276. titleBarButtons[0] = ((requiredButtons & minimiseButton) != 0)
  63277. ? getLookAndFeel().createDocumentWindowButton (minimiseButton) : 0;
  63278. titleBarButtons[1] = ((requiredButtons & maximiseButton) != 0)
  63279. ? getLookAndFeel().createDocumentWindowButton (maximiseButton) : 0;
  63280. titleBarButtons[2] = ((requiredButtons & closeButton) != 0)
  63281. ? getLookAndFeel().createDocumentWindowButton (closeButton) : 0;
  63282. for (i = 0; i < 3; ++i)
  63283. {
  63284. if (titleBarButtons[i] != 0)
  63285. {
  63286. if (buttonListener == 0)
  63287. buttonListener = new ButtonListenerProxy (*this);
  63288. titleBarButtons[i]->addButtonListener (buttonListener);
  63289. titleBarButtons[i]->setWantsKeyboardFocus (false);
  63290. // (call the Component method directly to avoid the assertion in ResizableWindow)
  63291. Component::addAndMakeVisible (titleBarButtons[i]);
  63292. }
  63293. }
  63294. if (getCloseButton() != 0)
  63295. {
  63296. #if JUCE_MAC
  63297. getCloseButton()->addShortcut (KeyPress ('w', ModifierKeys::commandModifier, 0));
  63298. #else
  63299. getCloseButton()->addShortcut (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0));
  63300. #endif
  63301. }
  63302. }
  63303. activeWindowStatusChanged();
  63304. ResizableWindow::lookAndFeelChanged();
  63305. }
  63306. void DocumentWindow::parentHierarchyChanged()
  63307. {
  63308. lookAndFeelChanged();
  63309. }
  63310. void DocumentWindow::activeWindowStatusChanged()
  63311. {
  63312. ResizableWindow::activeWindowStatusChanged();
  63313. for (int i = numElementsInArray (titleBarButtons); --i >= 0;)
  63314. if (titleBarButtons[i] != 0)
  63315. titleBarButtons[i]->setEnabled (isActiveWindow());
  63316. if (menuBar != 0)
  63317. menuBar->setEnabled (isActiveWindow());
  63318. }
  63319. void DocumentWindow::mouseDoubleClick (const MouseEvent& e)
  63320. {
  63321. if (getTitleBarArea().contains (e.x, e.y)
  63322. && getMaximiseButton() != 0)
  63323. {
  63324. getMaximiseButton()->triggerClick();
  63325. }
  63326. }
  63327. void DocumentWindow::userTriedToCloseWindow()
  63328. {
  63329. closeButtonPressed();
  63330. }
  63331. END_JUCE_NAMESPACE
  63332. /*** End of inlined file: juce_DocumentWindow.cpp ***/
  63333. /*** Start of inlined file: juce_ResizableWindow.cpp ***/
  63334. BEGIN_JUCE_NAMESPACE
  63335. ResizableWindow::ResizableWindow (const String& name,
  63336. const bool addToDesktop_)
  63337. : TopLevelWindow (name, addToDesktop_),
  63338. resizeToFitContent (false),
  63339. fullscreen (false),
  63340. lastNonFullScreenPos (50, 50, 256, 256),
  63341. constrainer (0)
  63342. #if JUCE_DEBUG
  63343. , hasBeenResized (false)
  63344. #endif
  63345. {
  63346. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  63347. lastNonFullScreenPos.setBounds (50, 50, 256, 256);
  63348. if (addToDesktop_)
  63349. Component::addToDesktop (getDesktopWindowStyleFlags());
  63350. }
  63351. ResizableWindow::ResizableWindow (const String& name,
  63352. const Colour& backgroundColour_,
  63353. const bool addToDesktop_)
  63354. : TopLevelWindow (name, addToDesktop_),
  63355. resizeToFitContent (false),
  63356. fullscreen (false),
  63357. lastNonFullScreenPos (50, 50, 256, 256),
  63358. constrainer (0)
  63359. #if JUCE_DEBUG
  63360. , hasBeenResized (false)
  63361. #endif
  63362. {
  63363. setBackgroundColour (backgroundColour_);
  63364. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  63365. if (addToDesktop_)
  63366. Component::addToDesktop (getDesktopWindowStyleFlags());
  63367. }
  63368. ResizableWindow::~ResizableWindow()
  63369. {
  63370. resizableCorner = 0;
  63371. resizableBorder = 0;
  63372. contentComponent.deleteAndZero();
  63373. // have you been adding your own components directly to this window..? tut tut tut.
  63374. // Read the instructions for using a ResizableWindow!
  63375. jassert (getNumChildComponents() == 0);
  63376. }
  63377. int ResizableWindow::getDesktopWindowStyleFlags() const
  63378. {
  63379. int styleFlags = TopLevelWindow::getDesktopWindowStyleFlags();
  63380. if (isResizable() && (styleFlags & ComponentPeer::windowHasTitleBar) != 0)
  63381. styleFlags |= ComponentPeer::windowIsResizable;
  63382. return styleFlags;
  63383. }
  63384. void ResizableWindow::setContentComponent (Component* const newContentComponent,
  63385. const bool deleteOldOne,
  63386. const bool resizeToFit)
  63387. {
  63388. resizeToFitContent = resizeToFit;
  63389. if (newContentComponent != static_cast <Component*> (contentComponent))
  63390. {
  63391. if (deleteOldOne)
  63392. contentComponent.deleteAndZero(); // (avoid using a scoped pointer for this, so that it survives
  63393. // external deletion of the content comp)
  63394. else
  63395. removeChildComponent (contentComponent);
  63396. contentComponent = newContentComponent;
  63397. Component::addAndMakeVisible (contentComponent);
  63398. }
  63399. if (resizeToFit)
  63400. childBoundsChanged (contentComponent);
  63401. resized(); // must always be called to position the new content comp
  63402. }
  63403. void ResizableWindow::setContentComponentSize (int width, int height)
  63404. {
  63405. jassert (width > 0 && height > 0); // not a great idea to give it a zero size..
  63406. const BorderSize border (getContentComponentBorder());
  63407. setSize (width + border.getLeftAndRight(),
  63408. height + border.getTopAndBottom());
  63409. }
  63410. const BorderSize ResizableWindow::getBorderThickness()
  63411. {
  63412. return BorderSize (isUsingNativeTitleBar() ? 0 : ((resizableBorder != 0 && ! isFullScreen()) ? 5 : 3));
  63413. }
  63414. const BorderSize ResizableWindow::getContentComponentBorder()
  63415. {
  63416. return getBorderThickness();
  63417. }
  63418. void ResizableWindow::moved()
  63419. {
  63420. updateLastPos();
  63421. }
  63422. void ResizableWindow::visibilityChanged()
  63423. {
  63424. TopLevelWindow::visibilityChanged();
  63425. updateLastPos();
  63426. }
  63427. void ResizableWindow::resized()
  63428. {
  63429. if (resizableBorder != 0)
  63430. {
  63431. #if JUCE_WINDOWS || JUCE_LINUX
  63432. // hide the resizable border if the OS already provides one..
  63433. resizableBorder->setVisible (! (isFullScreen() || isUsingNativeTitleBar()));
  63434. #else
  63435. resizableBorder->setVisible (! isFullScreen());
  63436. #endif
  63437. resizableBorder->setBorderThickness (getBorderThickness());
  63438. resizableBorder->setSize (getWidth(), getHeight());
  63439. resizableBorder->toBack();
  63440. }
  63441. if (resizableCorner != 0)
  63442. {
  63443. #if JUCE_MAC
  63444. // hide the resizable border if the OS already provides one..
  63445. resizableCorner->setVisible (! (isFullScreen() || isUsingNativeTitleBar()));
  63446. #else
  63447. resizableCorner->setVisible (! isFullScreen());
  63448. #endif
  63449. const int resizerSize = 18;
  63450. resizableCorner->setBounds (getWidth() - resizerSize,
  63451. getHeight() - resizerSize,
  63452. resizerSize, resizerSize);
  63453. }
  63454. if (contentComponent != 0)
  63455. contentComponent->setBoundsInset (getContentComponentBorder());
  63456. updateLastPos();
  63457. #if JUCE_DEBUG
  63458. hasBeenResized = true;
  63459. #endif
  63460. }
  63461. void ResizableWindow::childBoundsChanged (Component* child)
  63462. {
  63463. if ((child == contentComponent) && (child != 0) && resizeToFitContent)
  63464. {
  63465. // not going to look very good if this component has a zero size..
  63466. jassert (child->getWidth() > 0);
  63467. jassert (child->getHeight() > 0);
  63468. const BorderSize borders (getContentComponentBorder());
  63469. setSize (child->getWidth() + borders.getLeftAndRight(),
  63470. child->getHeight() + borders.getTopAndBottom());
  63471. }
  63472. }
  63473. void ResizableWindow::activeWindowStatusChanged()
  63474. {
  63475. const BorderSize border (getContentComponentBorder());
  63476. Rectangle<int> area (getLocalBounds());
  63477. repaint (area.removeFromTop (border.getTop()));
  63478. repaint (area.removeFromLeft (border.getLeft()));
  63479. repaint (area.removeFromRight (border.getRight()));
  63480. repaint (area.removeFromBottom (border.getBottom()));
  63481. }
  63482. void ResizableWindow::setResizable (const bool shouldBeResizable,
  63483. const bool useBottomRightCornerResizer)
  63484. {
  63485. if (shouldBeResizable)
  63486. {
  63487. if (useBottomRightCornerResizer)
  63488. {
  63489. resizableBorder = 0;
  63490. if (resizableCorner == 0)
  63491. {
  63492. Component::addChildComponent (resizableCorner = new ResizableCornerComponent (this, constrainer));
  63493. resizableCorner->setAlwaysOnTop (true);
  63494. }
  63495. }
  63496. else
  63497. {
  63498. resizableCorner = 0;
  63499. if (resizableBorder == 0)
  63500. Component::addChildComponent (resizableBorder = new ResizableBorderComponent (this, constrainer));
  63501. }
  63502. }
  63503. else
  63504. {
  63505. resizableCorner = 0;
  63506. resizableBorder = 0;
  63507. }
  63508. if (isUsingNativeTitleBar())
  63509. recreateDesktopWindow();
  63510. childBoundsChanged (contentComponent);
  63511. resized();
  63512. }
  63513. bool ResizableWindow::isResizable() const throw()
  63514. {
  63515. return resizableCorner != 0
  63516. || resizableBorder != 0;
  63517. }
  63518. void ResizableWindow::setResizeLimits (const int newMinimumWidth,
  63519. const int newMinimumHeight,
  63520. const int newMaximumWidth,
  63521. const int newMaximumHeight) throw()
  63522. {
  63523. // if you've set up a custom constrainer then these settings won't have any effect..
  63524. jassert (constrainer == &defaultConstrainer || constrainer == 0);
  63525. if (constrainer == 0)
  63526. setConstrainer (&defaultConstrainer);
  63527. defaultConstrainer.setSizeLimits (newMinimumWidth, newMinimumHeight,
  63528. newMaximumWidth, newMaximumHeight);
  63529. setBoundsConstrained (getBounds());
  63530. }
  63531. void ResizableWindow::setConstrainer (ComponentBoundsConstrainer* newConstrainer)
  63532. {
  63533. if (constrainer != newConstrainer)
  63534. {
  63535. constrainer = newConstrainer;
  63536. const bool useBottomRightCornerResizer = resizableCorner != 0;
  63537. const bool shouldBeResizable = useBottomRightCornerResizer || resizableBorder != 0;
  63538. resizableCorner = 0;
  63539. resizableBorder = 0;
  63540. setResizable (shouldBeResizable, useBottomRightCornerResizer);
  63541. ComponentPeer* const peer = getPeer();
  63542. if (peer != 0)
  63543. peer->setConstrainer (newConstrainer);
  63544. }
  63545. }
  63546. void ResizableWindow::setBoundsConstrained (const Rectangle<int>& bounds)
  63547. {
  63548. if (constrainer != 0)
  63549. constrainer->setBoundsForComponent (this, bounds, false, false, false, false);
  63550. else
  63551. setBounds (bounds);
  63552. }
  63553. void ResizableWindow::paint (Graphics& g)
  63554. {
  63555. getLookAndFeel().fillResizableWindowBackground (g, getWidth(), getHeight(),
  63556. getBorderThickness(), *this);
  63557. if (! isFullScreen())
  63558. {
  63559. getLookAndFeel().drawResizableWindowBorder (g, getWidth(), getHeight(),
  63560. getBorderThickness(), *this);
  63561. }
  63562. #if JUCE_DEBUG
  63563. /* If this fails, then you've probably written a subclass with a resized()
  63564. callback but forgotten to make it call its parent class's resized() method.
  63565. It's important when you override methods like resized(), moved(),
  63566. etc., that you make sure the base class methods also get called.
  63567. Of course you shouldn't really be overriding ResizableWindow::resized() anyway,
  63568. because your content should all be inside the content component - and it's the
  63569. content component's resized() method that you should be using to do your
  63570. layout.
  63571. */
  63572. jassert (hasBeenResized || (getWidth() == 0 && getHeight() == 0));
  63573. #endif
  63574. }
  63575. void ResizableWindow::lookAndFeelChanged()
  63576. {
  63577. resized();
  63578. if (isOnDesktop())
  63579. {
  63580. Component::addToDesktop (getDesktopWindowStyleFlags());
  63581. ComponentPeer* const peer = getPeer();
  63582. if (peer != 0)
  63583. peer->setConstrainer (constrainer);
  63584. }
  63585. }
  63586. const Colour ResizableWindow::getBackgroundColour() const throw()
  63587. {
  63588. return findColour (backgroundColourId, false);
  63589. }
  63590. void ResizableWindow::setBackgroundColour (const Colour& newColour)
  63591. {
  63592. Colour backgroundColour (newColour);
  63593. if (! Desktop::canUseSemiTransparentWindows())
  63594. backgroundColour = newColour.withAlpha (1.0f);
  63595. setColour (backgroundColourId, backgroundColour);
  63596. setOpaque (backgroundColour.isOpaque());
  63597. repaint();
  63598. }
  63599. bool ResizableWindow::isFullScreen() const
  63600. {
  63601. if (isOnDesktop())
  63602. {
  63603. ComponentPeer* const peer = getPeer();
  63604. return peer != 0 && peer->isFullScreen();
  63605. }
  63606. return fullscreen;
  63607. }
  63608. void ResizableWindow::setFullScreen (const bool shouldBeFullScreen)
  63609. {
  63610. if (shouldBeFullScreen != isFullScreen())
  63611. {
  63612. updateLastPos();
  63613. fullscreen = shouldBeFullScreen;
  63614. if (isOnDesktop())
  63615. {
  63616. ComponentPeer* const peer = getPeer();
  63617. if (peer != 0)
  63618. {
  63619. // keep a copy of this intact in case the real one gets messed-up while we're un-maximising
  63620. const Rectangle<int> lastPos (lastNonFullScreenPos);
  63621. peer->setFullScreen (shouldBeFullScreen);
  63622. if ((! shouldBeFullScreen) && ! lastPos.isEmpty())
  63623. setBounds (lastPos);
  63624. }
  63625. else
  63626. {
  63627. jassertfalse;
  63628. }
  63629. }
  63630. else
  63631. {
  63632. if (shouldBeFullScreen)
  63633. setBounds (0, 0, getParentWidth(), getParentHeight());
  63634. else
  63635. setBounds (lastNonFullScreenPos);
  63636. }
  63637. resized();
  63638. }
  63639. }
  63640. bool ResizableWindow::isMinimised() const
  63641. {
  63642. ComponentPeer* const peer = getPeer();
  63643. return (peer != 0) && peer->isMinimised();
  63644. }
  63645. void ResizableWindow::setMinimised (const bool shouldMinimise)
  63646. {
  63647. if (shouldMinimise != isMinimised())
  63648. {
  63649. ComponentPeer* const peer = getPeer();
  63650. if (peer != 0)
  63651. {
  63652. updateLastPos();
  63653. peer->setMinimised (shouldMinimise);
  63654. }
  63655. else
  63656. {
  63657. jassertfalse;
  63658. }
  63659. }
  63660. }
  63661. void ResizableWindow::updateLastPos()
  63662. {
  63663. if (isShowing() && ! (isFullScreen() || isMinimised()))
  63664. {
  63665. lastNonFullScreenPos = getBounds();
  63666. }
  63667. }
  63668. void ResizableWindow::parentSizeChanged()
  63669. {
  63670. if (isFullScreen() && getParentComponent() != 0)
  63671. {
  63672. setBounds (0, 0, getParentWidth(), getParentHeight());
  63673. }
  63674. }
  63675. const String ResizableWindow::getWindowStateAsString()
  63676. {
  63677. updateLastPos();
  63678. return (isFullScreen() ? "fs " : "") + lastNonFullScreenPos.toString();
  63679. }
  63680. bool ResizableWindow::restoreWindowStateFromString (const String& s)
  63681. {
  63682. StringArray tokens;
  63683. tokens.addTokens (s, false);
  63684. tokens.removeEmptyStrings();
  63685. tokens.trim();
  63686. const bool fs = tokens[0].startsWithIgnoreCase ("fs");
  63687. const int firstCoord = fs ? 1 : 0;
  63688. if (tokens.size() != firstCoord + 4)
  63689. return false;
  63690. Rectangle<int> newPos (tokens[firstCoord].getIntValue(),
  63691. tokens[firstCoord + 1].getIntValue(),
  63692. tokens[firstCoord + 2].getIntValue(),
  63693. tokens[firstCoord + 3].getIntValue());
  63694. if (newPos.isEmpty())
  63695. return false;
  63696. const Rectangle<int> screen (Desktop::getInstance().getMonitorAreaContaining (newPos.getCentre()));
  63697. ComponentPeer* const peer = isOnDesktop() ? getPeer() : 0;
  63698. if (peer != 0)
  63699. peer->getFrameSize().addTo (newPos);
  63700. if (! screen.contains (newPos))
  63701. {
  63702. newPos.setSize (jmin (newPos.getWidth(), screen.getWidth()),
  63703. jmin (newPos.getHeight(), screen.getHeight()));
  63704. newPos.setPosition (jlimit (screen.getX(), screen.getRight() - newPos.getWidth(), newPos.getX()),
  63705. jlimit (screen.getY(), screen.getBottom() - newPos.getHeight(), newPos.getY()));
  63706. }
  63707. if (peer != 0)
  63708. {
  63709. peer->getFrameSize().subtractFrom (newPos);
  63710. peer->setNonFullScreenBounds (newPos);
  63711. }
  63712. lastNonFullScreenPos = newPos;
  63713. setFullScreen (fs);
  63714. if (! fs)
  63715. setBoundsConstrained (newPos);
  63716. return true;
  63717. }
  63718. void ResizableWindow::mouseDown (const MouseEvent&)
  63719. {
  63720. if (! isFullScreen())
  63721. dragger.startDraggingComponent (this, constrainer);
  63722. }
  63723. void ResizableWindow::mouseDrag (const MouseEvent& e)
  63724. {
  63725. if (! isFullScreen())
  63726. dragger.dragComponent (this, e);
  63727. }
  63728. #if JUCE_DEBUG
  63729. void ResizableWindow::addChildComponent (Component* const child, int zOrder)
  63730. {
  63731. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  63732. manages its child components automatically, and if you add your own it'll cause
  63733. trouble. Instead, use setContentComponent() to give it a component which
  63734. will be automatically resized and kept in the right place - then you can add
  63735. subcomponents to the content comp. See the notes for the ResizableWindow class
  63736. for more info.
  63737. If you really know what you're doing and want to avoid this assertion, just call
  63738. Component::addChildComponent directly.
  63739. */
  63740. jassertfalse;
  63741. Component::addChildComponent (child, zOrder);
  63742. }
  63743. void ResizableWindow::addAndMakeVisible (Component* const child, int zOrder)
  63744. {
  63745. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  63746. manages its child components automatically, and if you add your own it'll cause
  63747. trouble. Instead, use setContentComponent() to give it a component which
  63748. will be automatically resized and kept in the right place - then you can add
  63749. subcomponents to the content comp. See the notes for the ResizableWindow class
  63750. for more info.
  63751. If you really know what you're doing and want to avoid this assertion, just call
  63752. Component::addAndMakeVisible directly.
  63753. */
  63754. jassertfalse;
  63755. Component::addAndMakeVisible (child, zOrder);
  63756. }
  63757. #endif
  63758. END_JUCE_NAMESPACE
  63759. /*** End of inlined file: juce_ResizableWindow.cpp ***/
  63760. /*** Start of inlined file: juce_SplashScreen.cpp ***/
  63761. BEGIN_JUCE_NAMESPACE
  63762. SplashScreen::SplashScreen()
  63763. {
  63764. setOpaque (true);
  63765. }
  63766. SplashScreen::~SplashScreen()
  63767. {
  63768. }
  63769. void SplashScreen::show (const String& title,
  63770. const Image& backgroundImage_,
  63771. const int minimumTimeToDisplayFor,
  63772. const bool useDropShadow,
  63773. const bool removeOnMouseClick)
  63774. {
  63775. backgroundImage = backgroundImage_;
  63776. jassert (backgroundImage_.isValid());
  63777. if (backgroundImage_.isValid())
  63778. {
  63779. setOpaque (! backgroundImage_.hasAlphaChannel());
  63780. show (title,
  63781. backgroundImage_.getWidth(),
  63782. backgroundImage_.getHeight(),
  63783. minimumTimeToDisplayFor,
  63784. useDropShadow,
  63785. removeOnMouseClick);
  63786. }
  63787. }
  63788. void SplashScreen::show (const String& title,
  63789. const int width,
  63790. const int height,
  63791. const int minimumTimeToDisplayFor,
  63792. const bool useDropShadow,
  63793. const bool removeOnMouseClick)
  63794. {
  63795. setName (title);
  63796. setAlwaysOnTop (true);
  63797. setVisible (true);
  63798. centreWithSize (width, height);
  63799. addToDesktop (useDropShadow ? ComponentPeer::windowHasDropShadow : 0);
  63800. toFront (false);
  63801. MessageManager::getInstance()->runDispatchLoopUntil (300);
  63802. repaint();
  63803. originalClickCounter = removeOnMouseClick
  63804. ? Desktop::getMouseButtonClickCounter()
  63805. : std::numeric_limits<int>::max();
  63806. earliestTimeToDelete = Time::getCurrentTime() + RelativeTime::milliseconds (minimumTimeToDisplayFor);
  63807. startTimer (50);
  63808. }
  63809. void SplashScreen::paint (Graphics& g)
  63810. {
  63811. g.setOpacity (1.0f);
  63812. g.drawImage (backgroundImage,
  63813. 0, 0, getWidth(), getHeight(),
  63814. 0, 0, backgroundImage.getWidth(), backgroundImage.getHeight());
  63815. }
  63816. void SplashScreen::timerCallback()
  63817. {
  63818. if (Time::getCurrentTime() > earliestTimeToDelete
  63819. || Desktop::getMouseButtonClickCounter() > originalClickCounter)
  63820. {
  63821. delete this;
  63822. }
  63823. }
  63824. END_JUCE_NAMESPACE
  63825. /*** End of inlined file: juce_SplashScreen.cpp ***/
  63826. /*** Start of inlined file: juce_ThreadWithProgressWindow.cpp ***/
  63827. BEGIN_JUCE_NAMESPACE
  63828. ThreadWithProgressWindow::ThreadWithProgressWindow (const String& title,
  63829. const bool hasProgressBar,
  63830. const bool hasCancelButton,
  63831. const int timeOutMsWhenCancelling_,
  63832. const String& cancelButtonText)
  63833. : Thread ("Juce Progress Window"),
  63834. progress (0.0),
  63835. timeOutMsWhenCancelling (timeOutMsWhenCancelling_)
  63836. {
  63837. alertWindow = LookAndFeel::getDefaultLookAndFeel()
  63838. .createAlertWindow (title, String::empty, cancelButtonText,
  63839. String::empty, String::empty,
  63840. AlertWindow::NoIcon, hasCancelButton ? 1 : 0, 0);
  63841. if (hasProgressBar)
  63842. alertWindow->addProgressBarComponent (progress);
  63843. }
  63844. ThreadWithProgressWindow::~ThreadWithProgressWindow()
  63845. {
  63846. stopThread (timeOutMsWhenCancelling);
  63847. }
  63848. bool ThreadWithProgressWindow::runThread (const int priority)
  63849. {
  63850. startThread (priority);
  63851. startTimer (100);
  63852. {
  63853. const ScopedLock sl (messageLock);
  63854. alertWindow->setMessage (message);
  63855. }
  63856. const bool finishedNaturally = alertWindow->runModalLoop() != 0;
  63857. stopThread (timeOutMsWhenCancelling);
  63858. alertWindow->setVisible (false);
  63859. return finishedNaturally;
  63860. }
  63861. void ThreadWithProgressWindow::setProgress (const double newProgress)
  63862. {
  63863. progress = newProgress;
  63864. }
  63865. void ThreadWithProgressWindow::setStatusMessage (const String& newStatusMessage)
  63866. {
  63867. const ScopedLock sl (messageLock);
  63868. message = newStatusMessage;
  63869. }
  63870. void ThreadWithProgressWindow::timerCallback()
  63871. {
  63872. if (! isThreadRunning())
  63873. {
  63874. // thread has finished normally..
  63875. alertWindow->exitModalState (1);
  63876. alertWindow->setVisible (false);
  63877. }
  63878. else
  63879. {
  63880. const ScopedLock sl (messageLock);
  63881. alertWindow->setMessage (message);
  63882. }
  63883. }
  63884. END_JUCE_NAMESPACE
  63885. /*** End of inlined file: juce_ThreadWithProgressWindow.cpp ***/
  63886. /*** Start of inlined file: juce_TooltipWindow.cpp ***/
  63887. BEGIN_JUCE_NAMESPACE
  63888. TooltipWindow::TooltipWindow (Component* const parentComponent,
  63889. const int millisecondsBeforeTipAppears_)
  63890. : Component ("tooltip"),
  63891. millisecondsBeforeTipAppears (millisecondsBeforeTipAppears_),
  63892. mouseClicks (0),
  63893. lastHideTime (0),
  63894. lastComponentUnderMouse (0),
  63895. changedCompsSinceShown (true)
  63896. {
  63897. if (Desktop::getInstance().getMainMouseSource().canHover())
  63898. startTimer (123);
  63899. setAlwaysOnTop (true);
  63900. setOpaque (true);
  63901. if (parentComponent != 0)
  63902. parentComponent->addChildComponent (this);
  63903. }
  63904. TooltipWindow::~TooltipWindow()
  63905. {
  63906. hide();
  63907. }
  63908. void TooltipWindow::setMillisecondsBeforeTipAppears (const int newTimeMs) throw()
  63909. {
  63910. millisecondsBeforeTipAppears = newTimeMs;
  63911. }
  63912. void TooltipWindow::paint (Graphics& g)
  63913. {
  63914. getLookAndFeel().drawTooltip (g, tipShowing, getWidth(), getHeight());
  63915. }
  63916. void TooltipWindow::mouseEnter (const MouseEvent&)
  63917. {
  63918. hide();
  63919. }
  63920. void TooltipWindow::showFor (const String& tip)
  63921. {
  63922. jassert (tip.isNotEmpty());
  63923. if (tipShowing != tip)
  63924. repaint();
  63925. tipShowing = tip;
  63926. Point<int> mousePos (Desktop::getMousePosition());
  63927. if (getParentComponent() != 0)
  63928. mousePos = getParentComponent()->globalPositionToRelative (mousePos);
  63929. int x, y, w, h;
  63930. getLookAndFeel().getTooltipSize (tip, w, h);
  63931. if (mousePos.getX() > getParentWidth() / 2)
  63932. x = mousePos.getX() - (w + 12);
  63933. else
  63934. x = mousePos.getX() + 24;
  63935. if (mousePos.getY() > getParentHeight() / 2)
  63936. y = mousePos.getY() - (h + 6);
  63937. else
  63938. y = mousePos.getY() + 6;
  63939. setBounds (x, y, w, h);
  63940. setVisible (true);
  63941. if (getParentComponent() == 0)
  63942. {
  63943. addToDesktop (ComponentPeer::windowHasDropShadow
  63944. | ComponentPeer::windowIsTemporary
  63945. | ComponentPeer::windowIgnoresKeyPresses);
  63946. }
  63947. toFront (false);
  63948. }
  63949. const String TooltipWindow::getTipFor (Component* const c)
  63950. {
  63951. if (c != 0
  63952. && Process::isForegroundProcess()
  63953. && ! Component::isMouseButtonDownAnywhere())
  63954. {
  63955. TooltipClient* const ttc = dynamic_cast <TooltipClient*> (c);
  63956. if (ttc != 0 && ! c->isCurrentlyBlockedByAnotherModalComponent())
  63957. return ttc->getTooltip();
  63958. }
  63959. return String::empty;
  63960. }
  63961. void TooltipWindow::hide()
  63962. {
  63963. tipShowing = String::empty;
  63964. removeFromDesktop();
  63965. setVisible (false);
  63966. }
  63967. void TooltipWindow::timerCallback()
  63968. {
  63969. const unsigned int now = Time::getApproximateMillisecondCounter();
  63970. Component* const newComp = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  63971. const String newTip (getTipFor (newComp));
  63972. const bool tipChanged = (newTip != lastTipUnderMouse || newComp != lastComponentUnderMouse);
  63973. lastComponentUnderMouse = newComp;
  63974. lastTipUnderMouse = newTip;
  63975. const int clickCount = Desktop::getInstance().getMouseButtonClickCounter();
  63976. const bool mouseWasClicked = clickCount > mouseClicks;
  63977. mouseClicks = clickCount;
  63978. const Point<int> mousePos (Desktop::getMousePosition());
  63979. const bool mouseMovedQuickly = mousePos.getDistanceFrom (lastMousePos) > 12;
  63980. lastMousePos = mousePos;
  63981. if (tipChanged || mouseWasClicked || mouseMovedQuickly)
  63982. lastCompChangeTime = now;
  63983. if (isVisible() || now < lastHideTime + 500)
  63984. {
  63985. // if a tip is currently visible (or has just disappeared), update to a new one
  63986. // immediately if needed..
  63987. if (newComp == 0 || mouseWasClicked || newTip.isEmpty())
  63988. {
  63989. if (isVisible())
  63990. {
  63991. lastHideTime = now;
  63992. hide();
  63993. }
  63994. }
  63995. else if (tipChanged)
  63996. {
  63997. showFor (newTip);
  63998. }
  63999. }
  64000. else
  64001. {
  64002. // if there isn't currently a tip, but one is needed, only let it
  64003. // appear after a timeout..
  64004. if (newTip.isNotEmpty()
  64005. && newTip != tipShowing
  64006. && now > lastCompChangeTime + millisecondsBeforeTipAppears)
  64007. {
  64008. showFor (newTip);
  64009. }
  64010. }
  64011. }
  64012. END_JUCE_NAMESPACE
  64013. /*** End of inlined file: juce_TooltipWindow.cpp ***/
  64014. /*** Start of inlined file: juce_TopLevelWindow.cpp ***/
  64015. BEGIN_JUCE_NAMESPACE
  64016. /** Keeps track of the active top level window.
  64017. */
  64018. class TopLevelWindowManager : public Timer,
  64019. public DeletedAtShutdown
  64020. {
  64021. public:
  64022. TopLevelWindowManager()
  64023. : currentActive (0)
  64024. {
  64025. }
  64026. ~TopLevelWindowManager()
  64027. {
  64028. clearSingletonInstance();
  64029. }
  64030. juce_DeclareSingleton_SingleThreaded_Minimal (TopLevelWindowManager)
  64031. void timerCallback()
  64032. {
  64033. startTimer (jmin (1731, getTimerInterval() * 2));
  64034. TopLevelWindow* active = 0;
  64035. if (Process::isForegroundProcess())
  64036. {
  64037. active = currentActive;
  64038. Component* const c = Component::getCurrentlyFocusedComponent();
  64039. TopLevelWindow* tlw = dynamic_cast <TopLevelWindow*> (c);
  64040. if (tlw == 0 && c != 0)
  64041. // (unable to use the syntax findParentComponentOfClass <TopLevelWindow> () because of a VC6 compiler bug)
  64042. tlw = c->findParentComponentOfClass ((TopLevelWindow*) 0);
  64043. if (tlw != 0)
  64044. active = tlw;
  64045. }
  64046. if (active != currentActive)
  64047. {
  64048. currentActive = active;
  64049. for (int i = windows.size(); --i >= 0;)
  64050. {
  64051. TopLevelWindow* const tlw = windows.getUnchecked (i);
  64052. tlw->setWindowActive (isWindowActive (tlw));
  64053. i = jmin (i, windows.size() - 1);
  64054. }
  64055. Desktop::getInstance().triggerFocusCallback();
  64056. }
  64057. }
  64058. bool addWindow (TopLevelWindow* const w)
  64059. {
  64060. windows.add (w);
  64061. startTimer (10);
  64062. return isWindowActive (w);
  64063. }
  64064. void removeWindow (TopLevelWindow* const w)
  64065. {
  64066. startTimer (10);
  64067. if (currentActive == w)
  64068. currentActive = 0;
  64069. windows.removeValue (w);
  64070. if (windows.size() == 0)
  64071. deleteInstance();
  64072. }
  64073. Array <TopLevelWindow*> windows;
  64074. private:
  64075. TopLevelWindow* currentActive;
  64076. bool isWindowActive (TopLevelWindow* const tlw) const
  64077. {
  64078. return (tlw == currentActive
  64079. || tlw->isParentOf (currentActive)
  64080. || tlw->hasKeyboardFocus (true))
  64081. && tlw->isShowing();
  64082. }
  64083. TopLevelWindowManager (const TopLevelWindowManager&);
  64084. TopLevelWindowManager& operator= (const TopLevelWindowManager&);
  64085. };
  64086. juce_ImplementSingleton_SingleThreaded (TopLevelWindowManager)
  64087. void juce_CheckCurrentlyFocusedTopLevelWindow()
  64088. {
  64089. if (TopLevelWindowManager::getInstanceWithoutCreating() != 0)
  64090. TopLevelWindowManager::getInstanceWithoutCreating()->startTimer (20);
  64091. }
  64092. TopLevelWindow::TopLevelWindow (const String& name,
  64093. const bool addToDesktop_)
  64094. : Component (name),
  64095. useDropShadow (true),
  64096. useNativeTitleBar (false),
  64097. windowIsActive_ (false)
  64098. {
  64099. setOpaque (true);
  64100. if (addToDesktop_)
  64101. Component::addToDesktop (getDesktopWindowStyleFlags());
  64102. else
  64103. setDropShadowEnabled (true);
  64104. setWantsKeyboardFocus (true);
  64105. setBroughtToFrontOnMouseClick (true);
  64106. windowIsActive_ = TopLevelWindowManager::getInstance()->addWindow (this);
  64107. }
  64108. TopLevelWindow::~TopLevelWindow()
  64109. {
  64110. shadower = 0;
  64111. TopLevelWindowManager::getInstance()->removeWindow (this);
  64112. }
  64113. void TopLevelWindow::focusOfChildComponentChanged (FocusChangeType)
  64114. {
  64115. if (hasKeyboardFocus (true))
  64116. TopLevelWindowManager::getInstance()->timerCallback();
  64117. else
  64118. TopLevelWindowManager::getInstance()->startTimer (10);
  64119. }
  64120. void TopLevelWindow::setWindowActive (const bool isNowActive)
  64121. {
  64122. if (windowIsActive_ != isNowActive)
  64123. {
  64124. windowIsActive_ = isNowActive;
  64125. activeWindowStatusChanged();
  64126. }
  64127. }
  64128. void TopLevelWindow::activeWindowStatusChanged()
  64129. {
  64130. }
  64131. void TopLevelWindow::parentHierarchyChanged()
  64132. {
  64133. setDropShadowEnabled (useDropShadow);
  64134. }
  64135. void TopLevelWindow::visibilityChanged()
  64136. {
  64137. if (isShowing())
  64138. toFront (true);
  64139. }
  64140. int TopLevelWindow::getDesktopWindowStyleFlags() const
  64141. {
  64142. int styleFlags = ComponentPeer::windowAppearsOnTaskbar;
  64143. if (useDropShadow)
  64144. styleFlags |= ComponentPeer::windowHasDropShadow;
  64145. if (useNativeTitleBar)
  64146. styleFlags |= ComponentPeer::windowHasTitleBar;
  64147. return styleFlags;
  64148. }
  64149. void TopLevelWindow::setDropShadowEnabled (const bool useShadow)
  64150. {
  64151. useDropShadow = useShadow;
  64152. if (isOnDesktop())
  64153. {
  64154. shadower = 0;
  64155. Component::addToDesktop (getDesktopWindowStyleFlags());
  64156. }
  64157. else
  64158. {
  64159. if (useShadow && isOpaque())
  64160. {
  64161. if (shadower == 0)
  64162. {
  64163. shadower = getLookAndFeel().createDropShadowerForComponent (this);
  64164. if (shadower != 0)
  64165. shadower->setOwner (this);
  64166. }
  64167. }
  64168. else
  64169. {
  64170. shadower = 0;
  64171. }
  64172. }
  64173. }
  64174. void TopLevelWindow::setUsingNativeTitleBar (const bool useNativeTitleBar_)
  64175. {
  64176. if (useNativeTitleBar != useNativeTitleBar_)
  64177. {
  64178. useNativeTitleBar = useNativeTitleBar_;
  64179. recreateDesktopWindow();
  64180. sendLookAndFeelChange();
  64181. }
  64182. }
  64183. void TopLevelWindow::recreateDesktopWindow()
  64184. {
  64185. if (isOnDesktop())
  64186. {
  64187. Component::addToDesktop (getDesktopWindowStyleFlags());
  64188. toFront (true);
  64189. }
  64190. }
  64191. void TopLevelWindow::addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo)
  64192. {
  64193. /* It's not recommended to change the desktop window flags directly for a TopLevelWindow,
  64194. because this class needs to make sure its layout corresponds with settings like whether
  64195. it's got a native title bar or not.
  64196. If you need custom flags for your window, you can override the getDesktopWindowStyleFlags()
  64197. method. If you do this, it's best to call the base class's getDesktopWindowStyleFlags()
  64198. method, then add or remove whatever flags are necessary from this value before returning it.
  64199. */
  64200. jassert ((windowStyleFlags & ~ComponentPeer::windowIsSemiTransparent)
  64201. == (getDesktopWindowStyleFlags() & ~ComponentPeer::windowIsSemiTransparent));
  64202. Component::addToDesktop (windowStyleFlags, nativeWindowToAttachTo);
  64203. if (windowStyleFlags != getDesktopWindowStyleFlags())
  64204. sendLookAndFeelChange();
  64205. }
  64206. void TopLevelWindow::centreAroundComponent (Component* c, const int width, const int height)
  64207. {
  64208. if (c == 0)
  64209. c = TopLevelWindow::getActiveTopLevelWindow();
  64210. if (c == 0)
  64211. {
  64212. centreWithSize (width, height);
  64213. }
  64214. else
  64215. {
  64216. Point<int> p (c->relativePositionToGlobal (Point<int> ((c->getWidth() - width) / 2,
  64217. (c->getHeight() - height) / 2)));
  64218. Rectangle<int> parentArea (c->getParentMonitorArea());
  64219. if (getParentComponent() != 0)
  64220. {
  64221. p = getParentComponent()->globalPositionToRelative (p);
  64222. parentArea.setBounds (0, 0, getParentWidth(), getParentHeight());
  64223. }
  64224. parentArea.reduce (12, 12);
  64225. setBounds (jlimit (parentArea.getX(), jmax (parentArea.getX(), parentArea.getRight() - width), p.getX()),
  64226. jlimit (parentArea.getY(), jmax (parentArea.getY(), parentArea.getBottom() - height), p.getY()),
  64227. width, height);
  64228. }
  64229. }
  64230. int TopLevelWindow::getNumTopLevelWindows() throw()
  64231. {
  64232. return TopLevelWindowManager::getInstance()->windows.size();
  64233. }
  64234. TopLevelWindow* TopLevelWindow::getTopLevelWindow (const int index) throw()
  64235. {
  64236. return static_cast <TopLevelWindow*> (TopLevelWindowManager::getInstance()->windows [index]);
  64237. }
  64238. TopLevelWindow* TopLevelWindow::getActiveTopLevelWindow() throw()
  64239. {
  64240. TopLevelWindow* best = 0;
  64241. int bestNumTWLParents = -1;
  64242. for (int i = TopLevelWindow::getNumTopLevelWindows(); --i >= 0;)
  64243. {
  64244. TopLevelWindow* const tlw = TopLevelWindow::getTopLevelWindow (i);
  64245. if (tlw->isActiveWindow())
  64246. {
  64247. int numTWLParents = 0;
  64248. const Component* c = tlw->getParentComponent();
  64249. while (c != 0)
  64250. {
  64251. if (dynamic_cast <const TopLevelWindow*> (c) != 0)
  64252. ++numTWLParents;
  64253. c = c->getParentComponent();
  64254. }
  64255. if (bestNumTWLParents < numTWLParents)
  64256. {
  64257. best = tlw;
  64258. bestNumTWLParents = numTWLParents;
  64259. }
  64260. }
  64261. }
  64262. return best;
  64263. }
  64264. END_JUCE_NAMESPACE
  64265. /*** End of inlined file: juce_TopLevelWindow.cpp ***/
  64266. /*** Start of inlined file: juce_RelativeCoordinate.cpp ***/
  64267. BEGIN_JUCE_NAMESPACE
  64268. namespace RelativeCoordinateHelpers
  64269. {
  64270. static void skipComma (const juce_wchar* const s, int& i)
  64271. {
  64272. while (CharacterFunctions::isWhitespace (s[i]))
  64273. ++i;
  64274. if (s[i] == ',')
  64275. ++i;
  64276. }
  64277. }
  64278. const String RelativeCoordinate::Strings::parent ("parent");
  64279. const String RelativeCoordinate::Strings::left ("left");
  64280. const String RelativeCoordinate::Strings::right ("right");
  64281. const String RelativeCoordinate::Strings::top ("top");
  64282. const String RelativeCoordinate::Strings::bottom ("bottom");
  64283. const String RelativeCoordinate::Strings::parentLeft ("parent.left");
  64284. const String RelativeCoordinate::Strings::parentTop ("parent.top");
  64285. const String RelativeCoordinate::Strings::parentRight ("parent.right");
  64286. const String RelativeCoordinate::Strings::parentBottom ("parent.bottom");
  64287. RelativeCoordinate::RelativeCoordinate()
  64288. {
  64289. }
  64290. RelativeCoordinate::RelativeCoordinate (const Expression& term_)
  64291. : term (term_)
  64292. {
  64293. }
  64294. RelativeCoordinate::RelativeCoordinate (const RelativeCoordinate& other)
  64295. : term (other.term)
  64296. {
  64297. }
  64298. RelativeCoordinate& RelativeCoordinate::operator= (const RelativeCoordinate& other)
  64299. {
  64300. term = other.term;
  64301. return *this;
  64302. }
  64303. RelativeCoordinate::RelativeCoordinate (const double absoluteDistanceFromOrigin)
  64304. : term (absoluteDistanceFromOrigin)
  64305. {
  64306. }
  64307. RelativeCoordinate::RelativeCoordinate (const String& s)
  64308. {
  64309. try
  64310. {
  64311. term = Expression (s);
  64312. }
  64313. catch (...)
  64314. {}
  64315. }
  64316. RelativeCoordinate::~RelativeCoordinate()
  64317. {
  64318. }
  64319. bool RelativeCoordinate::operator== (const RelativeCoordinate& other) const throw()
  64320. {
  64321. return term.toString() == other.term.toString();
  64322. }
  64323. bool RelativeCoordinate::operator!= (const RelativeCoordinate& other) const throw()
  64324. {
  64325. return ! operator== (other);
  64326. }
  64327. double RelativeCoordinate::resolve (const Expression::EvaluationContext* context) const
  64328. {
  64329. try
  64330. {
  64331. if (context != 0)
  64332. return term.evaluate (*context);
  64333. else
  64334. return term.evaluate();
  64335. }
  64336. catch (...)
  64337. {}
  64338. return 0.0;
  64339. }
  64340. bool RelativeCoordinate::isRecursive (const Expression::EvaluationContext* context) const
  64341. {
  64342. try
  64343. {
  64344. if (context != 0)
  64345. term.evaluate (*context);
  64346. else
  64347. term.evaluate();
  64348. }
  64349. catch (...)
  64350. {
  64351. return true;
  64352. }
  64353. return false;
  64354. }
  64355. void RelativeCoordinate::moveToAbsolute (double newPos, const Expression::EvaluationContext* context)
  64356. {
  64357. try
  64358. {
  64359. if (context != 0)
  64360. {
  64361. term = term.adjustedToGiveNewResult (newPos, *context);
  64362. }
  64363. else
  64364. {
  64365. Expression::EvaluationContext defaultContext;
  64366. term = term.adjustedToGiveNewResult (newPos, defaultContext);
  64367. }
  64368. }
  64369. catch (...)
  64370. {}
  64371. }
  64372. bool RelativeCoordinate::references (const String& coordName, const Expression::EvaluationContext* context) const
  64373. {
  64374. try
  64375. {
  64376. return term.referencesSymbol (coordName, context);
  64377. }
  64378. catch (...)
  64379. {}
  64380. return false;
  64381. }
  64382. bool RelativeCoordinate::isDynamic() const
  64383. {
  64384. return term.usesAnySymbols();
  64385. }
  64386. const String RelativeCoordinate::toString() const
  64387. {
  64388. return term.toString();
  64389. }
  64390. void RelativeCoordinate::renameSymbolIfUsed (const String& oldName, const String& newName)
  64391. {
  64392. jassert (newName.isNotEmpty() && newName.toLowerCase().containsOnly ("abcdefghijklmnopqrstuvwxyz0123456789_"));
  64393. if (term.referencesSymbol (oldName, 0))
  64394. term = term.withRenamedSymbol (oldName, newName);
  64395. }
  64396. RelativePoint::RelativePoint()
  64397. {
  64398. }
  64399. RelativePoint::RelativePoint (const Point<float>& absolutePoint)
  64400. : x (absolutePoint.getX()), y (absolutePoint.getY())
  64401. {
  64402. }
  64403. RelativePoint::RelativePoint (const float x_, const float y_)
  64404. : x (x_), y (y_)
  64405. {
  64406. }
  64407. RelativePoint::RelativePoint (const RelativeCoordinate& x_, const RelativeCoordinate& y_)
  64408. : x (x_), y (y_)
  64409. {
  64410. }
  64411. RelativePoint::RelativePoint (const String& s)
  64412. {
  64413. int i = 0;
  64414. x = RelativeCoordinate (Expression::parse (s, i));
  64415. RelativeCoordinateHelpers::skipComma (s, i);
  64416. y = RelativeCoordinate (Expression::parse (s, i));
  64417. }
  64418. bool RelativePoint::operator== (const RelativePoint& other) const throw()
  64419. {
  64420. return x == other.x && y == other.y;
  64421. }
  64422. bool RelativePoint::operator!= (const RelativePoint& other) const throw()
  64423. {
  64424. return ! operator== (other);
  64425. }
  64426. const Point<float> RelativePoint::resolve (const Expression::EvaluationContext* context) const
  64427. {
  64428. return Point<float> ((float) x.resolve (context),
  64429. (float) y.resolve (context));
  64430. }
  64431. void RelativePoint::moveToAbsolute (const Point<float>& newPos, const Expression::EvaluationContext* context)
  64432. {
  64433. x.moveToAbsolute (newPos.getX(), context);
  64434. y.moveToAbsolute (newPos.getY(), context);
  64435. }
  64436. const String RelativePoint::toString() const
  64437. {
  64438. return x.toString() + ", " + y.toString();
  64439. }
  64440. void RelativePoint::renameSymbolIfUsed (const String& oldName, const String& newName)
  64441. {
  64442. x.renameSymbolIfUsed (oldName, newName);
  64443. y.renameSymbolIfUsed (oldName, newName);
  64444. }
  64445. bool RelativePoint::isDynamic() const
  64446. {
  64447. return x.isDynamic() || y.isDynamic();
  64448. }
  64449. RelativeRectangle::RelativeRectangle()
  64450. {
  64451. }
  64452. RelativeRectangle::RelativeRectangle (const RelativeCoordinate& left_, const RelativeCoordinate& right_,
  64453. const RelativeCoordinate& top_, const RelativeCoordinate& bottom_)
  64454. : left (left_), right (right_), top (top_), bottom (bottom_)
  64455. {
  64456. }
  64457. RelativeRectangle::RelativeRectangle (const Rectangle<float>& rect, const String& componentName)
  64458. : left (rect.getX()),
  64459. right (Expression::symbol (componentName + "." + RelativeCoordinate::Strings::left) + Expression ((double) rect.getWidth())),
  64460. top (rect.getY()),
  64461. bottom (Expression::symbol (componentName + "." + RelativeCoordinate::Strings::top) + Expression ((double) rect.getHeight()))
  64462. {
  64463. }
  64464. RelativeRectangle::RelativeRectangle (const String& s)
  64465. {
  64466. int i = 0;
  64467. left = RelativeCoordinate (Expression::parse (s, i));
  64468. RelativeCoordinateHelpers::skipComma (s, i);
  64469. top = RelativeCoordinate (Expression::parse (s, i));
  64470. RelativeCoordinateHelpers::skipComma (s, i);
  64471. right = RelativeCoordinate (Expression::parse (s, i));
  64472. RelativeCoordinateHelpers::skipComma (s, i);
  64473. bottom = RelativeCoordinate (Expression::parse (s, i));
  64474. }
  64475. bool RelativeRectangle::operator== (const RelativeRectangle& other) const throw()
  64476. {
  64477. return left == other.left && top == other.top && right == other.right && bottom == other.bottom;
  64478. }
  64479. bool RelativeRectangle::operator!= (const RelativeRectangle& other) const throw()
  64480. {
  64481. return ! operator== (other);
  64482. }
  64483. const Rectangle<float> RelativeRectangle::resolve (const Expression::EvaluationContext* context) const
  64484. {
  64485. const double l = left.resolve (context);
  64486. const double r = right.resolve (context);
  64487. const double t = top.resolve (context);
  64488. const double b = bottom.resolve (context);
  64489. return Rectangle<float> ((float) l, (float) t, (float) (r - l), (float) (b - t));
  64490. }
  64491. void RelativeRectangle::moveToAbsolute (const Rectangle<float>& newPos, const Expression::EvaluationContext* context)
  64492. {
  64493. left.moveToAbsolute (newPos.getX(), context);
  64494. right.moveToAbsolute (newPos.getRight(), context);
  64495. top.moveToAbsolute (newPos.getY(), context);
  64496. bottom.moveToAbsolute (newPos.getBottom(), context);
  64497. }
  64498. const String RelativeRectangle::toString() const
  64499. {
  64500. return left.toString() + ", " + top.toString() + ", " + right.toString() + ", " + bottom.toString();
  64501. }
  64502. void RelativeRectangle::renameSymbolIfUsed (const String& oldName, const String& newName)
  64503. {
  64504. left.renameSymbolIfUsed (oldName, newName);
  64505. right.renameSymbolIfUsed (oldName, newName);
  64506. top.renameSymbolIfUsed (oldName, newName);
  64507. bottom.renameSymbolIfUsed (oldName, newName);
  64508. }
  64509. RelativePointPath::RelativePointPath()
  64510. : usesNonZeroWinding (true),
  64511. containsDynamicPoints (false)
  64512. {
  64513. }
  64514. RelativePointPath::RelativePointPath (const RelativePointPath& other)
  64515. : usesNonZeroWinding (true),
  64516. containsDynamicPoints (false)
  64517. {
  64518. ValueTree state (DrawablePath::valueTreeType);
  64519. other.writeTo (state, 0);
  64520. parse (state);
  64521. }
  64522. RelativePointPath::RelativePointPath (const ValueTree& drawable)
  64523. : usesNonZeroWinding (true),
  64524. containsDynamicPoints (false)
  64525. {
  64526. parse (drawable);
  64527. }
  64528. RelativePointPath::RelativePointPath (const Path& path)
  64529. {
  64530. usesNonZeroWinding = path.isUsingNonZeroWinding();
  64531. Path::Iterator i (path);
  64532. while (i.next())
  64533. {
  64534. switch (i.elementType)
  64535. {
  64536. case Path::Iterator::startNewSubPath: elements.add (new StartSubPath (RelativePoint (i.x1, i.y1))); break;
  64537. case Path::Iterator::lineTo: elements.add (new LineTo (RelativePoint (i.x1, i.y1))); break;
  64538. case Path::Iterator::quadraticTo: elements.add (new QuadraticTo (RelativePoint (i.x1, i.y1), RelativePoint (i.x2, i.y2))); break;
  64539. case Path::Iterator::cubicTo: elements.add (new CubicTo (RelativePoint (i.x1, i.y1), RelativePoint (i.x2, i.y2), RelativePoint (i.x3, i.y3))); break;
  64540. case Path::Iterator::closePath: elements.add (new CloseSubPath()); break;
  64541. default: jassertfalse; break;
  64542. }
  64543. }
  64544. }
  64545. void RelativePointPath::writeTo (ValueTree state, UndoManager* undoManager) const
  64546. {
  64547. DrawablePath::ValueTreeWrapper wrapper (state);
  64548. wrapper.setUsesNonZeroWinding (usesNonZeroWinding, undoManager);
  64549. ValueTree pathTree (wrapper.getPathState());
  64550. pathTree.removeAllChildren (undoManager);
  64551. for (int i = 0; i < elements.size(); ++i)
  64552. pathTree.addChild (elements.getUnchecked(i)->createTree(), -1, undoManager);
  64553. }
  64554. void RelativePointPath::parse (const ValueTree& state)
  64555. {
  64556. DrawablePath::ValueTreeWrapper wrapper (state);
  64557. usesNonZeroWinding = wrapper.usesNonZeroWinding();
  64558. RelativePoint points[3];
  64559. const ValueTree pathTree (wrapper.getPathState());
  64560. const int num = pathTree.getNumChildren();
  64561. for (int i = 0; i < num; ++i)
  64562. {
  64563. const DrawablePath::ValueTreeWrapper::Element e (pathTree.getChild(i));
  64564. const int numCps = e.getNumControlPoints();
  64565. for (int j = 0; j < numCps; ++j)
  64566. {
  64567. points[j] = e.getControlPoint (j);
  64568. containsDynamicPoints = containsDynamicPoints || points[j].isDynamic();
  64569. }
  64570. const Identifier type (e.getType());
  64571. if (type == DrawablePath::ValueTreeWrapper::Element::startSubPathElement)
  64572. elements.add (new StartSubPath (points[0]));
  64573. else if (type == DrawablePath::ValueTreeWrapper::Element::closeSubPathElement)
  64574. elements.add (new CloseSubPath());
  64575. else if (type == DrawablePath::ValueTreeWrapper::Element::lineToElement)
  64576. elements.add (new LineTo (points[0]));
  64577. else if (type == DrawablePath::ValueTreeWrapper::Element::quadraticToElement)
  64578. elements.add (new QuadraticTo (points[0], points[1]));
  64579. else if (type == DrawablePath::ValueTreeWrapper::Element::cubicToElement)
  64580. elements.add (new CubicTo (points[0], points[1], points[2]));
  64581. else
  64582. jassertfalse;
  64583. }
  64584. }
  64585. RelativePointPath::~RelativePointPath()
  64586. {
  64587. }
  64588. void RelativePointPath::swapWith (RelativePointPath& other) throw()
  64589. {
  64590. elements.swapWithArray (other.elements);
  64591. swapVariables (usesNonZeroWinding, other.usesNonZeroWinding);
  64592. }
  64593. void RelativePointPath::createPath (Path& path, Expression::EvaluationContext* coordFinder)
  64594. {
  64595. for (int i = 0; i < elements.size(); ++i)
  64596. elements.getUnchecked(i)->addToPath (path, coordFinder);
  64597. }
  64598. bool RelativePointPath::containsAnyDynamicPoints() const
  64599. {
  64600. return containsDynamicPoints;
  64601. }
  64602. RelativePointPath::ElementBase::ElementBase (const ElementType type_) : type (type_)
  64603. {
  64604. }
  64605. RelativePointPath::StartSubPath::StartSubPath (const RelativePoint& pos)
  64606. : ElementBase (startSubPathElement), startPos (pos)
  64607. {
  64608. }
  64609. const ValueTree RelativePointPath::StartSubPath::createTree() const
  64610. {
  64611. ValueTree v (DrawablePath::ValueTreeWrapper::Element::startSubPathElement);
  64612. v.setProperty (DrawablePath::ValueTreeWrapper::point1, startPos.toString(), 0);
  64613. return v;
  64614. }
  64615. void RelativePointPath::StartSubPath::addToPath (Path& path, Expression::EvaluationContext* coordFinder) const
  64616. {
  64617. path.startNewSubPath (startPos.resolve (coordFinder));
  64618. }
  64619. RelativePoint* RelativePointPath::StartSubPath::getControlPoints (int& numPoints)
  64620. {
  64621. numPoints = 1;
  64622. return &startPos;
  64623. }
  64624. RelativePointPath::CloseSubPath::CloseSubPath()
  64625. : ElementBase (closeSubPathElement)
  64626. {
  64627. }
  64628. const ValueTree RelativePointPath::CloseSubPath::createTree() const
  64629. {
  64630. return ValueTree (DrawablePath::ValueTreeWrapper::Element::closeSubPathElement);
  64631. }
  64632. void RelativePointPath::CloseSubPath::addToPath (Path& path, Expression::EvaluationContext*) const
  64633. {
  64634. path.closeSubPath();
  64635. }
  64636. RelativePoint* RelativePointPath::CloseSubPath::getControlPoints (int& numPoints)
  64637. {
  64638. numPoints = 0;
  64639. return 0;
  64640. }
  64641. RelativePointPath::LineTo::LineTo (const RelativePoint& endPoint_)
  64642. : ElementBase (lineToElement), endPoint (endPoint_)
  64643. {
  64644. }
  64645. const ValueTree RelativePointPath::LineTo::createTree() const
  64646. {
  64647. ValueTree v (DrawablePath::ValueTreeWrapper::Element::lineToElement);
  64648. v.setProperty (DrawablePath::ValueTreeWrapper::point1, endPoint.toString(), 0);
  64649. return v;
  64650. }
  64651. void RelativePointPath::LineTo::addToPath (Path& path, Expression::EvaluationContext* coordFinder) const
  64652. {
  64653. path.lineTo (endPoint.resolve (coordFinder));
  64654. }
  64655. RelativePoint* RelativePointPath::LineTo::getControlPoints (int& numPoints)
  64656. {
  64657. numPoints = 1;
  64658. return &endPoint;
  64659. }
  64660. RelativePointPath::QuadraticTo::QuadraticTo (const RelativePoint& controlPoint, const RelativePoint& endPoint)
  64661. : ElementBase (quadraticToElement)
  64662. {
  64663. controlPoints[0] = controlPoint;
  64664. controlPoints[1] = endPoint;
  64665. }
  64666. const ValueTree RelativePointPath::QuadraticTo::createTree() const
  64667. {
  64668. ValueTree v (DrawablePath::ValueTreeWrapper::Element::quadraticToElement);
  64669. v.setProperty (DrawablePath::ValueTreeWrapper::point1, controlPoints[0].toString(), 0);
  64670. v.setProperty (DrawablePath::ValueTreeWrapper::point2, controlPoints[1].toString(), 0);
  64671. return v;
  64672. }
  64673. void RelativePointPath::QuadraticTo::addToPath (Path& path, Expression::EvaluationContext* coordFinder) const
  64674. {
  64675. path.quadraticTo (controlPoints[0].resolve (coordFinder),
  64676. controlPoints[1].resolve (coordFinder));
  64677. }
  64678. RelativePoint* RelativePointPath::QuadraticTo::getControlPoints (int& numPoints)
  64679. {
  64680. numPoints = 2;
  64681. return controlPoints;
  64682. }
  64683. RelativePointPath::CubicTo::CubicTo (const RelativePoint& controlPoint1, const RelativePoint& controlPoint2, const RelativePoint& endPoint)
  64684. : ElementBase (cubicToElement)
  64685. {
  64686. controlPoints[0] = controlPoint1;
  64687. controlPoints[1] = controlPoint2;
  64688. controlPoints[2] = endPoint;
  64689. }
  64690. const ValueTree RelativePointPath::CubicTo::createTree() const
  64691. {
  64692. ValueTree v (DrawablePath::ValueTreeWrapper::Element::cubicToElement);
  64693. v.setProperty (DrawablePath::ValueTreeWrapper::point1, controlPoints[0].toString(), 0);
  64694. v.setProperty (DrawablePath::ValueTreeWrapper::point2, controlPoints[1].toString(), 0);
  64695. v.setProperty (DrawablePath::ValueTreeWrapper::point3, controlPoints[2].toString(), 0);
  64696. return v;
  64697. }
  64698. void RelativePointPath::CubicTo::addToPath (Path& path, Expression::EvaluationContext* coordFinder) const
  64699. {
  64700. path.cubicTo (controlPoints[0].resolve (coordFinder),
  64701. controlPoints[1].resolve (coordFinder),
  64702. controlPoints[2].resolve (coordFinder));
  64703. }
  64704. RelativePoint* RelativePointPath::CubicTo::getControlPoints (int& numPoints)
  64705. {
  64706. numPoints = 3;
  64707. return controlPoints;
  64708. }
  64709. RelativeParallelogram::RelativeParallelogram()
  64710. {
  64711. }
  64712. RelativeParallelogram::RelativeParallelogram (const Rectangle<float>& r)
  64713. : topLeft (r.getTopLeft()), topRight (r.getTopRight()), bottomLeft (r.getBottomLeft())
  64714. {
  64715. }
  64716. RelativeParallelogram::RelativeParallelogram (const RelativePoint& topLeft_, const RelativePoint& topRight_, const RelativePoint& bottomLeft_)
  64717. : topLeft (topLeft_), topRight (topRight_), bottomLeft (bottomLeft_)
  64718. {
  64719. }
  64720. RelativeParallelogram::RelativeParallelogram (const String& topLeft_, const String& topRight_, const String& bottomLeft_)
  64721. : topLeft (topLeft_), topRight (topRight_), bottomLeft (bottomLeft_)
  64722. {
  64723. }
  64724. RelativeParallelogram::~RelativeParallelogram()
  64725. {
  64726. }
  64727. void RelativeParallelogram::resolveThreePoints (Point<float>* points, Expression::EvaluationContext* const coordFinder) const
  64728. {
  64729. points[0] = topLeft.resolve (coordFinder);
  64730. points[1] = topRight.resolve (coordFinder);
  64731. points[2] = bottomLeft.resolve (coordFinder);
  64732. }
  64733. void RelativeParallelogram::resolveFourCorners (Point<float>* points, Expression::EvaluationContext* const coordFinder) const
  64734. {
  64735. resolveThreePoints (points, coordFinder);
  64736. points[3] = points[1] + (points[2] - points[0]);
  64737. }
  64738. const Rectangle<float> RelativeParallelogram::getBounds (Expression::EvaluationContext* const coordFinder) const
  64739. {
  64740. Point<float> points[4];
  64741. resolveFourCorners (points, coordFinder);
  64742. return Rectangle<float>::findAreaContainingPoints (points, 4);
  64743. }
  64744. void RelativeParallelogram::getPath (Path& path, Expression::EvaluationContext* const coordFinder) const
  64745. {
  64746. Point<float> points[4];
  64747. resolveFourCorners (points, coordFinder);
  64748. path.startNewSubPath (points[0]);
  64749. path.lineTo (points[1]);
  64750. path.lineTo (points[3]);
  64751. path.lineTo (points[2]);
  64752. path.closeSubPath();
  64753. }
  64754. const AffineTransform RelativeParallelogram::resetToPerpendicular (Expression::EvaluationContext* const coordFinder)
  64755. {
  64756. Point<float> corners[3];
  64757. resolveThreePoints (corners, coordFinder);
  64758. const Line<float> top (corners[0], corners[1]);
  64759. const Line<float> left (corners[0], corners[2]);
  64760. const Point<float> newTopRight (corners[0] + Point<float> (top.getLength(), 0.0f));
  64761. const Point<float> newBottomLeft (corners[0] + Point<float> (0.0f, left.getLength()));
  64762. topRight.moveToAbsolute (newTopRight, coordFinder);
  64763. bottomLeft.moveToAbsolute (newBottomLeft, coordFinder);
  64764. return AffineTransform::fromTargetPoints (corners[0].getX(), corners[0].getY(), corners[0].getX(), corners[0].getY(),
  64765. corners[1].getX(), corners[1].getY(), newTopRight.getX(), newTopRight.getY(),
  64766. corners[2].getX(), corners[2].getY(), newBottomLeft.getX(), newBottomLeft.getY());
  64767. }
  64768. bool RelativeParallelogram::operator== (const RelativeParallelogram& other) const throw()
  64769. {
  64770. return topLeft == other.topLeft && topRight == other.topRight && bottomLeft == other.bottomLeft;
  64771. }
  64772. bool RelativeParallelogram::operator!= (const RelativeParallelogram& other) const throw()
  64773. {
  64774. return ! operator== (other);
  64775. }
  64776. const Point<float> RelativeParallelogram::getInternalCoordForPoint (const Point<float>* const corners, Point<float> target) throw()
  64777. {
  64778. const Point<float> tr (corners[1] - corners[0]);
  64779. const Point<float> bl (corners[2] - corners[0]);
  64780. target -= corners[0];
  64781. return Point<float> (Line<float> (Point<float>(), tr).getIntersection (Line<float> (target, target - bl)).getDistanceFromOrigin(),
  64782. Line<float> (Point<float>(), bl).getIntersection (Line<float> (target, target - tr)).getDistanceFromOrigin());
  64783. }
  64784. const Point<float> RelativeParallelogram::getPointForInternalCoord (const Point<float>* const corners, const Point<float>& point) throw()
  64785. {
  64786. return corners[0]
  64787. + Line<float> (Point<float>(), corners[1] - corners[0]).getPointAlongLine (point.getX())
  64788. + Line<float> (Point<float>(), corners[2] - corners[0]).getPointAlongLine (point.getY());
  64789. }
  64790. END_JUCE_NAMESPACE
  64791. /*** End of inlined file: juce_RelativeCoordinate.cpp ***/
  64792. #endif
  64793. #if JUCE_BUILD_MISC // (put these in misc to balance the file sizes and avoid problems in iphone build)
  64794. /*** Start of inlined file: juce_Colour.cpp ***/
  64795. BEGIN_JUCE_NAMESPACE
  64796. namespace ColourHelpers
  64797. {
  64798. static uint8 floatAlphaToInt (const float alpha) throw()
  64799. {
  64800. return (uint8) jlimit (0, 0xff, roundToInt (alpha * 255.0f));
  64801. }
  64802. static void convertHSBtoRGB (float h, float s, float v,
  64803. uint8& r, uint8& g, uint8& b) throw()
  64804. {
  64805. v = jlimit (0.0f, 1.0f, v);
  64806. v *= 255.0f;
  64807. const uint8 intV = (uint8) roundToInt (v);
  64808. if (s <= 0)
  64809. {
  64810. r = intV;
  64811. g = intV;
  64812. b = intV;
  64813. }
  64814. else
  64815. {
  64816. s = jmin (1.0f, s);
  64817. h = jlimit (0.0f, 1.0f, h);
  64818. h = (h - std::floor (h)) * 6.0f + 0.00001f; // need a small adjustment to compensate for rounding errors
  64819. const float f = h - std::floor (h);
  64820. const uint8 x = (uint8) roundToInt (v * (1.0f - s));
  64821. const float y = v * (1.0f - s * f);
  64822. const float z = v * (1.0f - (s * (1.0f - f)));
  64823. if (h < 1.0f)
  64824. {
  64825. r = intV;
  64826. g = (uint8) roundToInt (z);
  64827. b = x;
  64828. }
  64829. else if (h < 2.0f)
  64830. {
  64831. r = (uint8) roundToInt (y);
  64832. g = intV;
  64833. b = x;
  64834. }
  64835. else if (h < 3.0f)
  64836. {
  64837. r = x;
  64838. g = intV;
  64839. b = (uint8) roundToInt (z);
  64840. }
  64841. else if (h < 4.0f)
  64842. {
  64843. r = x;
  64844. g = (uint8) roundToInt (y);
  64845. b = intV;
  64846. }
  64847. else if (h < 5.0f)
  64848. {
  64849. r = (uint8) roundToInt (z);
  64850. g = x;
  64851. b = intV;
  64852. }
  64853. else if (h < 6.0f)
  64854. {
  64855. r = intV;
  64856. g = x;
  64857. b = (uint8) roundToInt (y);
  64858. }
  64859. else
  64860. {
  64861. r = 0;
  64862. g = 0;
  64863. b = 0;
  64864. }
  64865. }
  64866. }
  64867. }
  64868. Colour::Colour() throw()
  64869. : argb (0)
  64870. {
  64871. }
  64872. Colour::Colour (const Colour& other) throw()
  64873. : argb (other.argb)
  64874. {
  64875. }
  64876. Colour& Colour::operator= (const Colour& other) throw()
  64877. {
  64878. argb = other.argb;
  64879. return *this;
  64880. }
  64881. bool Colour::operator== (const Colour& other) const throw()
  64882. {
  64883. return argb.getARGB() == other.argb.getARGB();
  64884. }
  64885. bool Colour::operator!= (const Colour& other) const throw()
  64886. {
  64887. return argb.getARGB() != other.argb.getARGB();
  64888. }
  64889. Colour::Colour (const uint32 argb_) throw()
  64890. : argb (argb_)
  64891. {
  64892. }
  64893. Colour::Colour (const uint8 red,
  64894. const uint8 green,
  64895. const uint8 blue) throw()
  64896. {
  64897. argb.setARGB (0xff, red, green, blue);
  64898. }
  64899. const Colour Colour::fromRGB (const uint8 red,
  64900. const uint8 green,
  64901. const uint8 blue) throw()
  64902. {
  64903. return Colour (red, green, blue);
  64904. }
  64905. Colour::Colour (const uint8 red,
  64906. const uint8 green,
  64907. const uint8 blue,
  64908. const uint8 alpha) throw()
  64909. {
  64910. argb.setARGB (alpha, red, green, blue);
  64911. }
  64912. const Colour Colour::fromRGBA (const uint8 red,
  64913. const uint8 green,
  64914. const uint8 blue,
  64915. const uint8 alpha) throw()
  64916. {
  64917. return Colour (red, green, blue, alpha);
  64918. }
  64919. Colour::Colour (const uint8 red,
  64920. const uint8 green,
  64921. const uint8 blue,
  64922. const float alpha) throw()
  64923. {
  64924. argb.setARGB (ColourHelpers::floatAlphaToInt (alpha), red, green, blue);
  64925. }
  64926. const Colour Colour::fromRGBAFloat (const uint8 red,
  64927. const uint8 green,
  64928. const uint8 blue,
  64929. const float alpha) throw()
  64930. {
  64931. return Colour (red, green, blue, alpha);
  64932. }
  64933. Colour::Colour (const float hue,
  64934. const float saturation,
  64935. const float brightness,
  64936. const float alpha) throw()
  64937. {
  64938. uint8 r = getRed(), g = getGreen(), b = getBlue();
  64939. ColourHelpers::convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  64940. argb.setARGB (ColourHelpers::floatAlphaToInt (alpha), r, g, b);
  64941. }
  64942. const Colour Colour::fromHSV (const float hue,
  64943. const float saturation,
  64944. const float brightness,
  64945. const float alpha) throw()
  64946. {
  64947. return Colour (hue, saturation, brightness, alpha);
  64948. }
  64949. Colour::Colour (const float hue,
  64950. const float saturation,
  64951. const float brightness,
  64952. const uint8 alpha) throw()
  64953. {
  64954. uint8 r = getRed(), g = getGreen(), b = getBlue();
  64955. ColourHelpers::convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  64956. argb.setARGB (alpha, r, g, b);
  64957. }
  64958. Colour::~Colour() throw()
  64959. {
  64960. }
  64961. const PixelARGB Colour::getPixelARGB() const throw()
  64962. {
  64963. PixelARGB p (argb);
  64964. p.premultiply();
  64965. return p;
  64966. }
  64967. uint32 Colour::getARGB() const throw()
  64968. {
  64969. return argb.getARGB();
  64970. }
  64971. bool Colour::isTransparent() const throw()
  64972. {
  64973. return getAlpha() == 0;
  64974. }
  64975. bool Colour::isOpaque() const throw()
  64976. {
  64977. return getAlpha() == 0xff;
  64978. }
  64979. const Colour Colour::withAlpha (const uint8 newAlpha) const throw()
  64980. {
  64981. PixelARGB newCol (argb);
  64982. newCol.setAlpha (newAlpha);
  64983. return Colour (newCol.getARGB());
  64984. }
  64985. const Colour Colour::withAlpha (const float newAlpha) const throw()
  64986. {
  64987. jassert (newAlpha >= 0 && newAlpha <= 1.0f);
  64988. PixelARGB newCol (argb);
  64989. newCol.setAlpha (ColourHelpers::floatAlphaToInt (newAlpha));
  64990. return Colour (newCol.getARGB());
  64991. }
  64992. const Colour Colour::withMultipliedAlpha (const float alphaMultiplier) const throw()
  64993. {
  64994. jassert (alphaMultiplier >= 0);
  64995. PixelARGB newCol (argb);
  64996. newCol.setAlpha ((uint8) jmin (0xff, roundToInt (alphaMultiplier * newCol.getAlpha())));
  64997. return Colour (newCol.getARGB());
  64998. }
  64999. const Colour Colour::overlaidWith (const Colour& src) const throw()
  65000. {
  65001. const int destAlpha = getAlpha();
  65002. if (destAlpha > 0)
  65003. {
  65004. const int invA = 0xff - (int) src.getAlpha();
  65005. const int resA = 0xff - (((0xff - destAlpha) * invA) >> 8);
  65006. if (resA > 0)
  65007. {
  65008. const int da = (invA * destAlpha) / resA;
  65009. return Colour ((uint8) (src.getRed() + ((((int) getRed() - src.getRed()) * da) >> 8)),
  65010. (uint8) (src.getGreen() + ((((int) getGreen() - src.getGreen()) * da) >> 8)),
  65011. (uint8) (src.getBlue() + ((((int) getBlue() - src.getBlue()) * da) >> 8)),
  65012. (uint8) resA);
  65013. }
  65014. return *this;
  65015. }
  65016. else
  65017. {
  65018. return src;
  65019. }
  65020. }
  65021. const Colour Colour::interpolatedWith (const Colour& other, float proportionOfOther) const throw()
  65022. {
  65023. if (proportionOfOther <= 0)
  65024. return *this;
  65025. if (proportionOfOther >= 1.0f)
  65026. return other;
  65027. PixelARGB c1 (getPixelARGB());
  65028. const PixelARGB c2 (other.getPixelARGB());
  65029. c1.tween (c2, roundToInt (proportionOfOther * 255.0f));
  65030. c1.unpremultiply();
  65031. return Colour (c1.getARGB());
  65032. }
  65033. float Colour::getFloatRed() const throw()
  65034. {
  65035. return getRed() / 255.0f;
  65036. }
  65037. float Colour::getFloatGreen() const throw()
  65038. {
  65039. return getGreen() / 255.0f;
  65040. }
  65041. float Colour::getFloatBlue() const throw()
  65042. {
  65043. return getBlue() / 255.0f;
  65044. }
  65045. float Colour::getFloatAlpha() const throw()
  65046. {
  65047. return getAlpha() / 255.0f;
  65048. }
  65049. void Colour::getHSB (float& h, float& s, float& v) const throw()
  65050. {
  65051. const int r = getRed();
  65052. const int g = getGreen();
  65053. const int b = getBlue();
  65054. const int hi = jmax (r, g, b);
  65055. const int lo = jmin (r, g, b);
  65056. if (hi != 0)
  65057. {
  65058. s = (hi - lo) / (float) hi;
  65059. if (s != 0)
  65060. {
  65061. const float invDiff = 1.0f / (hi - lo);
  65062. const float red = (hi - r) * invDiff;
  65063. const float green = (hi - g) * invDiff;
  65064. const float blue = (hi - b) * invDiff;
  65065. if (r == hi)
  65066. h = blue - green;
  65067. else if (g == hi)
  65068. h = 2.0f + red - blue;
  65069. else
  65070. h = 4.0f + green - red;
  65071. h *= 1.0f / 6.0f;
  65072. if (h < 0)
  65073. ++h;
  65074. }
  65075. else
  65076. {
  65077. h = 0;
  65078. }
  65079. }
  65080. else
  65081. {
  65082. s = 0;
  65083. h = 0;
  65084. }
  65085. v = hi / 255.0f;
  65086. }
  65087. float Colour::getHue() const throw()
  65088. {
  65089. float h, s, b;
  65090. getHSB (h, s, b);
  65091. return h;
  65092. }
  65093. const Colour Colour::withHue (const float hue) const throw()
  65094. {
  65095. float h, s, b;
  65096. getHSB (h, s, b);
  65097. return Colour (hue, s, b, getAlpha());
  65098. }
  65099. const Colour Colour::withRotatedHue (const float amountToRotate) const throw()
  65100. {
  65101. float h, s, b;
  65102. getHSB (h, s, b);
  65103. h += amountToRotate;
  65104. h -= std::floor (h);
  65105. return Colour (h, s, b, getAlpha());
  65106. }
  65107. float Colour::getSaturation() const throw()
  65108. {
  65109. float h, s, b;
  65110. getHSB (h, s, b);
  65111. return s;
  65112. }
  65113. const Colour Colour::withSaturation (const float saturation) const throw()
  65114. {
  65115. float h, s, b;
  65116. getHSB (h, s, b);
  65117. return Colour (h, saturation, b, getAlpha());
  65118. }
  65119. const Colour Colour::withMultipliedSaturation (const float amount) const throw()
  65120. {
  65121. float h, s, b;
  65122. getHSB (h, s, b);
  65123. return Colour (h, jmin (1.0f, s * amount), b, getAlpha());
  65124. }
  65125. float Colour::getBrightness() const throw()
  65126. {
  65127. float h, s, b;
  65128. getHSB (h, s, b);
  65129. return b;
  65130. }
  65131. const Colour Colour::withBrightness (const float brightness) const throw()
  65132. {
  65133. float h, s, b;
  65134. getHSB (h, s, b);
  65135. return Colour (h, s, brightness, getAlpha());
  65136. }
  65137. const Colour Colour::withMultipliedBrightness (const float amount) const throw()
  65138. {
  65139. float h, s, b;
  65140. getHSB (h, s, b);
  65141. b *= amount;
  65142. if (b > 1.0f)
  65143. b = 1.0f;
  65144. return Colour (h, s, b, getAlpha());
  65145. }
  65146. const Colour Colour::brighter (float amount) const throw()
  65147. {
  65148. amount = 1.0f / (1.0f + amount);
  65149. return Colour ((uint8) (255 - (amount * (255 - getRed()))),
  65150. (uint8) (255 - (amount * (255 - getGreen()))),
  65151. (uint8) (255 - (amount * (255 - getBlue()))),
  65152. getAlpha());
  65153. }
  65154. const Colour Colour::darker (float amount) const throw()
  65155. {
  65156. amount = 1.0f / (1.0f + amount);
  65157. return Colour ((uint8) (amount * getRed()),
  65158. (uint8) (amount * getGreen()),
  65159. (uint8) (amount * getBlue()),
  65160. getAlpha());
  65161. }
  65162. const Colour Colour::greyLevel (const float brightness) throw()
  65163. {
  65164. const uint8 level
  65165. = (uint8) jlimit (0x00, 0xff, roundToInt (brightness * 255.0f));
  65166. return Colour (level, level, level);
  65167. }
  65168. const Colour Colour::contrasting (const float amount) const throw()
  65169. {
  65170. return overlaidWith ((((int) getRed() + (int) getGreen() + (int) getBlue() >= 3 * 128)
  65171. ? Colours::black
  65172. : Colours::white).withAlpha (amount));
  65173. }
  65174. const Colour Colour::contrasting (const Colour& colour1,
  65175. const Colour& colour2) throw()
  65176. {
  65177. const float b1 = colour1.getBrightness();
  65178. const float b2 = colour2.getBrightness();
  65179. float best = 0.0f;
  65180. float bestDist = 0.0f;
  65181. for (float i = 0.0f; i < 1.0f; i += 0.02f)
  65182. {
  65183. const float d1 = std::abs (i - b1);
  65184. const float d2 = std::abs (i - b2);
  65185. const float dist = jmin (d1, d2, 1.0f - d1, 1.0f - d2);
  65186. if (dist > bestDist)
  65187. {
  65188. best = i;
  65189. bestDist = dist;
  65190. }
  65191. }
  65192. return colour1.overlaidWith (colour2.withMultipliedAlpha (0.5f))
  65193. .withBrightness (best);
  65194. }
  65195. const String Colour::toString() const
  65196. {
  65197. return String::toHexString ((int) argb.getARGB());
  65198. }
  65199. const Colour Colour::fromString (const String& encodedColourString)
  65200. {
  65201. return Colour ((uint32) encodedColourString.getHexValue32());
  65202. }
  65203. const String Colour::toDisplayString (const bool includeAlphaValue) const
  65204. {
  65205. return String::toHexString ((int) (argb.getARGB() & (includeAlphaValue ? 0xffffffff : 0xffffff)))
  65206. .paddedLeft ('0', includeAlphaValue ? 8 : 6)
  65207. .toUpperCase();
  65208. }
  65209. END_JUCE_NAMESPACE
  65210. /*** End of inlined file: juce_Colour.cpp ***/
  65211. /*** Start of inlined file: juce_ColourGradient.cpp ***/
  65212. BEGIN_JUCE_NAMESPACE
  65213. ColourGradient::ColourGradient() throw()
  65214. {
  65215. #if JUCE_DEBUG
  65216. point1.setX (987654.0f);
  65217. #endif
  65218. }
  65219. ColourGradient::ColourGradient (const Colour& colour1, const float x1_, const float y1_,
  65220. const Colour& colour2, const float x2_, const float y2_,
  65221. const bool isRadial_)
  65222. : point1 (x1_, y1_),
  65223. point2 (x2_, y2_),
  65224. isRadial (isRadial_)
  65225. {
  65226. colours.add (ColourPoint (0.0, colour1));
  65227. colours.add (ColourPoint (1.0, colour2));
  65228. }
  65229. ColourGradient::~ColourGradient()
  65230. {
  65231. }
  65232. bool ColourGradient::operator== (const ColourGradient& other) const throw()
  65233. {
  65234. return point1 == other.point1 && point2 == other.point2
  65235. && isRadial == other.isRadial
  65236. && colours == other.colours;
  65237. }
  65238. bool ColourGradient::operator!= (const ColourGradient& other) const throw()
  65239. {
  65240. return ! operator== (other);
  65241. }
  65242. void ColourGradient::clearColours()
  65243. {
  65244. colours.clear();
  65245. }
  65246. int ColourGradient::addColour (const double proportionAlongGradient, const Colour& colour)
  65247. {
  65248. // must be within the two end-points
  65249. jassert (proportionAlongGradient >= 0 && proportionAlongGradient <= 1.0);
  65250. const double pos = jlimit (0.0, 1.0, proportionAlongGradient);
  65251. int i;
  65252. for (i = 0; i < colours.size(); ++i)
  65253. if (colours.getReference(i).position > pos)
  65254. break;
  65255. colours.insert (i, ColourPoint (pos, colour));
  65256. return i;
  65257. }
  65258. void ColourGradient::removeColour (int index)
  65259. {
  65260. jassert (index > 0 && index < colours.size() - 1);
  65261. colours.remove (index);
  65262. }
  65263. void ColourGradient::multiplyOpacity (const float multiplier) throw()
  65264. {
  65265. for (int i = 0; i < colours.size(); ++i)
  65266. {
  65267. Colour& c = colours.getReference(i).colour;
  65268. c = c.withMultipliedAlpha (multiplier);
  65269. }
  65270. }
  65271. int ColourGradient::getNumColours() const throw()
  65272. {
  65273. return colours.size();
  65274. }
  65275. double ColourGradient::getColourPosition (const int index) const throw()
  65276. {
  65277. if (((unsigned int) index) < (unsigned int) colours.size())
  65278. return colours.getReference (index).position;
  65279. return 0;
  65280. }
  65281. const Colour ColourGradient::getColour (const int index) const throw()
  65282. {
  65283. if (((unsigned int) index) < (unsigned int) colours.size())
  65284. return colours.getReference (index).colour;
  65285. return Colour();
  65286. }
  65287. void ColourGradient::setColour (int index, const Colour& newColour) throw()
  65288. {
  65289. if (((unsigned int) index) < (unsigned int) colours.size())
  65290. colours.getReference (index).colour = newColour;
  65291. }
  65292. const Colour ColourGradient::getColourAtPosition (const double position) const throw()
  65293. {
  65294. jassert (colours.getReference(0).position == 0); // the first colour specified has to go at position 0
  65295. if (position <= 0 || colours.size() <= 1)
  65296. return colours.getReference(0).colour;
  65297. int i = colours.size() - 1;
  65298. while (position < colours.getReference(i).position)
  65299. --i;
  65300. const ColourPoint& p1 = colours.getReference (i);
  65301. if (i >= colours.size() - 1)
  65302. return p1.colour;
  65303. const ColourPoint& p2 = colours.getReference (i + 1);
  65304. return p1.colour.interpolatedWith (p2.colour, (float) ((position - p1.position) / (p2.position - p1.position)));
  65305. }
  65306. int ColourGradient::createLookupTable (const AffineTransform& transform, HeapBlock <PixelARGB>& lookupTable) const
  65307. {
  65308. #if JUCE_DEBUG
  65309. // trying to use the object without setting its co-ordinates? Have a careful read of
  65310. // the comments for the constructors.
  65311. jassert (point1.getX() != 987654.0f);
  65312. #endif
  65313. const int numEntries = jlimit (1, jmax (1, (colours.size() - 1) << 8),
  65314. 3 * (int) point1.transformedBy (transform)
  65315. .getDistanceFrom (point2.transformedBy (transform)));
  65316. lookupTable.malloc (numEntries);
  65317. if (colours.size() >= 2)
  65318. {
  65319. jassert (colours.getReference(0).position == 0); // the first colour specified has to go at position 0
  65320. PixelARGB pix1 (colours.getReference (0).colour.getPixelARGB());
  65321. int index = 0;
  65322. for (int j = 1; j < colours.size(); ++j)
  65323. {
  65324. const ColourPoint& p = colours.getReference (j);
  65325. const int numToDo = roundToInt (p.position * (numEntries - 1)) - index;
  65326. const PixelARGB pix2 (p.colour.getPixelARGB());
  65327. for (int i = 0; i < numToDo; ++i)
  65328. {
  65329. jassert (index >= 0 && index < numEntries);
  65330. lookupTable[index] = pix1;
  65331. lookupTable[index].tween (pix2, (i << 8) / numToDo);
  65332. ++index;
  65333. }
  65334. pix1 = pix2;
  65335. }
  65336. while (index < numEntries)
  65337. lookupTable [index++] = pix1;
  65338. }
  65339. else
  65340. {
  65341. jassertfalse; // no colours specified!
  65342. }
  65343. return numEntries;
  65344. }
  65345. bool ColourGradient::isOpaque() const throw()
  65346. {
  65347. for (int i = 0; i < colours.size(); ++i)
  65348. if (! colours.getReference(i).colour.isOpaque())
  65349. return false;
  65350. return true;
  65351. }
  65352. bool ColourGradient::isInvisible() const throw()
  65353. {
  65354. for (int i = 0; i < colours.size(); ++i)
  65355. if (! colours.getReference(i).colour.isTransparent())
  65356. return false;
  65357. return true;
  65358. }
  65359. END_JUCE_NAMESPACE
  65360. /*** End of inlined file: juce_ColourGradient.cpp ***/
  65361. /*** Start of inlined file: juce_Colours.cpp ***/
  65362. BEGIN_JUCE_NAMESPACE
  65363. const Colour Colours::transparentBlack (0);
  65364. const Colour Colours::transparentWhite (0x00ffffff);
  65365. const Colour Colours::aliceblue (0xfff0f8ff);
  65366. const Colour Colours::antiquewhite (0xfffaebd7);
  65367. const Colour Colours::aqua (0xff00ffff);
  65368. const Colour Colours::aquamarine (0xff7fffd4);
  65369. const Colour Colours::azure (0xfff0ffff);
  65370. const Colour Colours::beige (0xfff5f5dc);
  65371. const Colour Colours::bisque (0xffffe4c4);
  65372. const Colour Colours::black (0xff000000);
  65373. const Colour Colours::blanchedalmond (0xffffebcd);
  65374. const Colour Colours::blue (0xff0000ff);
  65375. const Colour Colours::blueviolet (0xff8a2be2);
  65376. const Colour Colours::brown (0xffa52a2a);
  65377. const Colour Colours::burlywood (0xffdeb887);
  65378. const Colour Colours::cadetblue (0xff5f9ea0);
  65379. const Colour Colours::chartreuse (0xff7fff00);
  65380. const Colour Colours::chocolate (0xffd2691e);
  65381. const Colour Colours::coral (0xffff7f50);
  65382. const Colour Colours::cornflowerblue (0xff6495ed);
  65383. const Colour Colours::cornsilk (0xfffff8dc);
  65384. const Colour Colours::crimson (0xffdc143c);
  65385. const Colour Colours::cyan (0xff00ffff);
  65386. const Colour Colours::darkblue (0xff00008b);
  65387. const Colour Colours::darkcyan (0xff008b8b);
  65388. const Colour Colours::darkgoldenrod (0xffb8860b);
  65389. const Colour Colours::darkgrey (0xff555555);
  65390. const Colour Colours::darkgreen (0xff006400);
  65391. const Colour Colours::darkkhaki (0xffbdb76b);
  65392. const Colour Colours::darkmagenta (0xff8b008b);
  65393. const Colour Colours::darkolivegreen (0xff556b2f);
  65394. const Colour Colours::darkorange (0xffff8c00);
  65395. const Colour Colours::darkorchid (0xff9932cc);
  65396. const Colour Colours::darkred (0xff8b0000);
  65397. const Colour Colours::darksalmon (0xffe9967a);
  65398. const Colour Colours::darkseagreen (0xff8fbc8f);
  65399. const Colour Colours::darkslateblue (0xff483d8b);
  65400. const Colour Colours::darkslategrey (0xff2f4f4f);
  65401. const Colour Colours::darkturquoise (0xff00ced1);
  65402. const Colour Colours::darkviolet (0xff9400d3);
  65403. const Colour Colours::deeppink (0xffff1493);
  65404. const Colour Colours::deepskyblue (0xff00bfff);
  65405. const Colour Colours::dimgrey (0xff696969);
  65406. const Colour Colours::dodgerblue (0xff1e90ff);
  65407. const Colour Colours::firebrick (0xffb22222);
  65408. const Colour Colours::floralwhite (0xfffffaf0);
  65409. const Colour Colours::forestgreen (0xff228b22);
  65410. const Colour Colours::fuchsia (0xffff00ff);
  65411. const Colour Colours::gainsboro (0xffdcdcdc);
  65412. const Colour Colours::gold (0xffffd700);
  65413. const Colour Colours::goldenrod (0xffdaa520);
  65414. const Colour Colours::grey (0xff808080);
  65415. const Colour Colours::green (0xff008000);
  65416. const Colour Colours::greenyellow (0xffadff2f);
  65417. const Colour Colours::honeydew (0xfff0fff0);
  65418. const Colour Colours::hotpink (0xffff69b4);
  65419. const Colour Colours::indianred (0xffcd5c5c);
  65420. const Colour Colours::indigo (0xff4b0082);
  65421. const Colour Colours::ivory (0xfffffff0);
  65422. const Colour Colours::khaki (0xfff0e68c);
  65423. const Colour Colours::lavender (0xffe6e6fa);
  65424. const Colour Colours::lavenderblush (0xfffff0f5);
  65425. const Colour Colours::lemonchiffon (0xfffffacd);
  65426. const Colour Colours::lightblue (0xffadd8e6);
  65427. const Colour Colours::lightcoral (0xfff08080);
  65428. const Colour Colours::lightcyan (0xffe0ffff);
  65429. const Colour Colours::lightgoldenrodyellow (0xfffafad2);
  65430. const Colour Colours::lightgreen (0xff90ee90);
  65431. const Colour Colours::lightgrey (0xffd3d3d3);
  65432. const Colour Colours::lightpink (0xffffb6c1);
  65433. const Colour Colours::lightsalmon (0xffffa07a);
  65434. const Colour Colours::lightseagreen (0xff20b2aa);
  65435. const Colour Colours::lightskyblue (0xff87cefa);
  65436. const Colour Colours::lightslategrey (0xff778899);
  65437. const Colour Colours::lightsteelblue (0xffb0c4de);
  65438. const Colour Colours::lightyellow (0xffffffe0);
  65439. const Colour Colours::lime (0xff00ff00);
  65440. const Colour Colours::limegreen (0xff32cd32);
  65441. const Colour Colours::linen (0xfffaf0e6);
  65442. const Colour Colours::magenta (0xffff00ff);
  65443. const Colour Colours::maroon (0xff800000);
  65444. const Colour Colours::mediumaquamarine (0xff66cdaa);
  65445. const Colour Colours::mediumblue (0xff0000cd);
  65446. const Colour Colours::mediumorchid (0xffba55d3);
  65447. const Colour Colours::mediumpurple (0xff9370db);
  65448. const Colour Colours::mediumseagreen (0xff3cb371);
  65449. const Colour Colours::mediumslateblue (0xff7b68ee);
  65450. const Colour Colours::mediumspringgreen (0xff00fa9a);
  65451. const Colour Colours::mediumturquoise (0xff48d1cc);
  65452. const Colour Colours::mediumvioletred (0xffc71585);
  65453. const Colour Colours::midnightblue (0xff191970);
  65454. const Colour Colours::mintcream (0xfff5fffa);
  65455. const Colour Colours::mistyrose (0xffffe4e1);
  65456. const Colour Colours::navajowhite (0xffffdead);
  65457. const Colour Colours::navy (0xff000080);
  65458. const Colour Colours::oldlace (0xfffdf5e6);
  65459. const Colour Colours::olive (0xff808000);
  65460. const Colour Colours::olivedrab (0xff6b8e23);
  65461. const Colour Colours::orange (0xffffa500);
  65462. const Colour Colours::orangered (0xffff4500);
  65463. const Colour Colours::orchid (0xffda70d6);
  65464. const Colour Colours::palegoldenrod (0xffeee8aa);
  65465. const Colour Colours::palegreen (0xff98fb98);
  65466. const Colour Colours::paleturquoise (0xffafeeee);
  65467. const Colour Colours::palevioletred (0xffdb7093);
  65468. const Colour Colours::papayawhip (0xffffefd5);
  65469. const Colour Colours::peachpuff (0xffffdab9);
  65470. const Colour Colours::peru (0xffcd853f);
  65471. const Colour Colours::pink (0xffffc0cb);
  65472. const Colour Colours::plum (0xffdda0dd);
  65473. const Colour Colours::powderblue (0xffb0e0e6);
  65474. const Colour Colours::purple (0xff800080);
  65475. const Colour Colours::red (0xffff0000);
  65476. const Colour Colours::rosybrown (0xffbc8f8f);
  65477. const Colour Colours::royalblue (0xff4169e1);
  65478. const Colour Colours::saddlebrown (0xff8b4513);
  65479. const Colour Colours::salmon (0xfffa8072);
  65480. const Colour Colours::sandybrown (0xfff4a460);
  65481. const Colour Colours::seagreen (0xff2e8b57);
  65482. const Colour Colours::seashell (0xfffff5ee);
  65483. const Colour Colours::sienna (0xffa0522d);
  65484. const Colour Colours::silver (0xffc0c0c0);
  65485. const Colour Colours::skyblue (0xff87ceeb);
  65486. const Colour Colours::slateblue (0xff6a5acd);
  65487. const Colour Colours::slategrey (0xff708090);
  65488. const Colour Colours::snow (0xfffffafa);
  65489. const Colour Colours::springgreen (0xff00ff7f);
  65490. const Colour Colours::steelblue (0xff4682b4);
  65491. const Colour Colours::tan (0xffd2b48c);
  65492. const Colour Colours::teal (0xff008080);
  65493. const Colour Colours::thistle (0xffd8bfd8);
  65494. const Colour Colours::tomato (0xffff6347);
  65495. const Colour Colours::turquoise (0xff40e0d0);
  65496. const Colour Colours::violet (0xffee82ee);
  65497. const Colour Colours::wheat (0xfff5deb3);
  65498. const Colour Colours::white (0xffffffff);
  65499. const Colour Colours::whitesmoke (0xfff5f5f5);
  65500. const Colour Colours::yellow (0xffffff00);
  65501. const Colour Colours::yellowgreen (0xff9acd32);
  65502. const Colour Colours::findColourForName (const String& colourName,
  65503. const Colour& defaultColour)
  65504. {
  65505. static const int presets[] =
  65506. {
  65507. // (first value is the string's hashcode, second is ARGB)
  65508. 0x05978fff, 0xff000000, /* black */
  65509. 0x06bdcc29, 0xffffffff, /* white */
  65510. 0x002e305a, 0xff0000ff, /* blue */
  65511. 0x00308adf, 0xff808080, /* grey */
  65512. 0x05e0cf03, 0xff008000, /* green */
  65513. 0x0001b891, 0xffff0000, /* red */
  65514. 0xd43c6474, 0xffffff00, /* yellow */
  65515. 0x620886da, 0xfff0f8ff, /* aliceblue */
  65516. 0x20a2676a, 0xfffaebd7, /* antiquewhite */
  65517. 0x002dcebc, 0xff00ffff, /* aqua */
  65518. 0x46bb5f7e, 0xff7fffd4, /* aquamarine */
  65519. 0x0590228f, 0xfff0ffff, /* azure */
  65520. 0x05947fe4, 0xfff5f5dc, /* beige */
  65521. 0xad388e35, 0xffffe4c4, /* bisque */
  65522. 0x00674f7e, 0xffffebcd, /* blanchedalmond */
  65523. 0x39129959, 0xff8a2be2, /* blueviolet */
  65524. 0x059a8136, 0xffa52a2a, /* brown */
  65525. 0x89cea8f9, 0xffdeb887, /* burlywood */
  65526. 0x0fa260cf, 0xff5f9ea0, /* cadetblue */
  65527. 0x6b748956, 0xff7fff00, /* chartreuse */
  65528. 0x2903623c, 0xffd2691e, /* chocolate */
  65529. 0x05a74431, 0xffff7f50, /* coral */
  65530. 0x618d42dd, 0xff6495ed, /* cornflowerblue */
  65531. 0xe4b479fd, 0xfffff8dc, /* cornsilk */
  65532. 0x3d8c4edf, 0xffdc143c, /* crimson */
  65533. 0x002ed323, 0xff00ffff, /* cyan */
  65534. 0x67cc74d0, 0xff00008b, /* darkblue */
  65535. 0x67cd1799, 0xff008b8b, /* darkcyan */
  65536. 0x31bbd168, 0xffb8860b, /* darkgoldenrod */
  65537. 0x67cecf55, 0xff555555, /* darkgrey */
  65538. 0x920b194d, 0xff006400, /* darkgreen */
  65539. 0x923edd4c, 0xffbdb76b, /* darkkhaki */
  65540. 0x5c293873, 0xff8b008b, /* darkmagenta */
  65541. 0x6b6671fe, 0xff556b2f, /* darkolivegreen */
  65542. 0xbcfd2524, 0xffff8c00, /* darkorange */
  65543. 0xbcfdf799, 0xff9932cc, /* darkorchid */
  65544. 0x55ee0d5b, 0xff8b0000, /* darkred */
  65545. 0xc2e5f564, 0xffe9967a, /* darksalmon */
  65546. 0x61be858a, 0xff8fbc8f, /* darkseagreen */
  65547. 0xc2b0f2bd, 0xff483d8b, /* darkslateblue */
  65548. 0xc2b34d42, 0xff2f4f4f, /* darkslategrey */
  65549. 0x7cf2b06b, 0xff00ced1, /* darkturquoise */
  65550. 0xc8769375, 0xff9400d3, /* darkviolet */
  65551. 0x25832862, 0xffff1493, /* deeppink */
  65552. 0xfcad568f, 0xff00bfff, /* deepskyblue */
  65553. 0x634c8b67, 0xff696969, /* dimgrey */
  65554. 0x45c1ce55, 0xff1e90ff, /* dodgerblue */
  65555. 0xef19e3cb, 0xffb22222, /* firebrick */
  65556. 0xb852b195, 0xfffffaf0, /* floralwhite */
  65557. 0xd086fd06, 0xff228b22, /* forestgreen */
  65558. 0xe106b6d7, 0xffff00ff, /* fuchsia */
  65559. 0x7880d61e, 0xffdcdcdc, /* gainsboro */
  65560. 0x00308060, 0xffffd700, /* gold */
  65561. 0xb3b3bc1e, 0xffdaa520, /* goldenrod */
  65562. 0xbab8a537, 0xffadff2f, /* greenyellow */
  65563. 0xe4cacafb, 0xfff0fff0, /* honeydew */
  65564. 0x41892743, 0xffff69b4, /* hotpink */
  65565. 0xd5796f1a, 0xffcd5c5c, /* indianred */
  65566. 0xb969fed2, 0xff4b0082, /* indigo */
  65567. 0x05fef6a9, 0xfffffff0, /* ivory */
  65568. 0x06149302, 0xfff0e68c, /* khaki */
  65569. 0xad5a05c7, 0xffe6e6fa, /* lavender */
  65570. 0x7c4d5b99, 0xfffff0f5, /* lavenderblush */
  65571. 0x195756f0, 0xfffffacd, /* lemonchiffon */
  65572. 0x28e4ea70, 0xffadd8e6, /* lightblue */
  65573. 0xf3c7ccdb, 0xfff08080, /* lightcoral */
  65574. 0x28e58d39, 0xffe0ffff, /* lightcyan */
  65575. 0x21234e3c, 0xfffafad2, /* lightgoldenrodyellow */
  65576. 0xf40157ad, 0xff90ee90, /* lightgreen */
  65577. 0x28e744f5, 0xffd3d3d3, /* lightgrey */
  65578. 0x28eb3b8c, 0xffffb6c1, /* lightpink */
  65579. 0x9fb78304, 0xffffa07a, /* lightsalmon */
  65580. 0x50632b2a, 0xff20b2aa, /* lightseagreen */
  65581. 0x68fb7b25, 0xff87cefa, /* lightskyblue */
  65582. 0xa8a35ba2, 0xff778899, /* lightslategrey */
  65583. 0xa20d484f, 0xffb0c4de, /* lightsteelblue */
  65584. 0xaa2cf10a, 0xffffffe0, /* lightyellow */
  65585. 0x0032afd5, 0xff00ff00, /* lime */
  65586. 0x607bbc4e, 0xff32cd32, /* limegreen */
  65587. 0x06234efa, 0xfffaf0e6, /* linen */
  65588. 0x316858a9, 0xffff00ff, /* magenta */
  65589. 0xbf8ca470, 0xff800000, /* maroon */
  65590. 0xbd58e0b3, 0xff66cdaa, /* mediumaquamarine */
  65591. 0x967dfd4f, 0xff0000cd, /* mediumblue */
  65592. 0x056f5c58, 0xffba55d3, /* mediumorchid */
  65593. 0x07556b71, 0xff9370db, /* mediumpurple */
  65594. 0x5369b689, 0xff3cb371, /* mediumseagreen */
  65595. 0x066be19e, 0xff7b68ee, /* mediumslateblue */
  65596. 0x3256b281, 0xff00fa9a, /* mediumspringgreen */
  65597. 0xc0ad9f4c, 0xff48d1cc, /* mediumturquoise */
  65598. 0x628e63dd, 0xffc71585, /* mediumvioletred */
  65599. 0x168eb32a, 0xff191970, /* midnightblue */
  65600. 0x4306b960, 0xfff5fffa, /* mintcream */
  65601. 0x4cbc0e6b, 0xffffe4e1, /* mistyrose */
  65602. 0xe97218a6, 0xffffdead, /* navajowhite */
  65603. 0x00337bb6, 0xff000080, /* navy */
  65604. 0xadd2d33e, 0xfffdf5e6, /* oldlace */
  65605. 0x064ee1db, 0xff808000, /* olive */
  65606. 0x9e33a98a, 0xff6b8e23, /* olivedrab */
  65607. 0xc3de262e, 0xffffa500, /* orange */
  65608. 0x58bebba3, 0xffff4500, /* orangered */
  65609. 0xc3def8a3, 0xffda70d6, /* orchid */
  65610. 0x28cb4834, 0xffeee8aa, /* palegoldenrod */
  65611. 0x3d9dd619, 0xff98fb98, /* palegreen */
  65612. 0x74022737, 0xffafeeee, /* paleturquoise */
  65613. 0x15e2ebc8, 0xffdb7093, /* palevioletred */
  65614. 0x5fd898e2, 0xffffefd5, /* papayawhip */
  65615. 0x93e1b776, 0xffffdab9, /* peachpuff */
  65616. 0x003472f8, 0xffcd853f, /* peru */
  65617. 0x00348176, 0xffffc0cb, /* pink */
  65618. 0x00348d94, 0xffdda0dd, /* plum */
  65619. 0xd036be93, 0xffb0e0e6, /* powderblue */
  65620. 0xc5c507bc, 0xff800080, /* purple */
  65621. 0xa89d65b3, 0xffbc8f8f, /* rosybrown */
  65622. 0xbd9413e1, 0xff4169e1, /* royalblue */
  65623. 0xf456044f, 0xff8b4513, /* saddlebrown */
  65624. 0xc9c6f66e, 0xfffa8072, /* salmon */
  65625. 0x0bb131e1, 0xfff4a460, /* sandybrown */
  65626. 0x34636c14, 0xff2e8b57, /* seagreen */
  65627. 0x3507fb41, 0xfffff5ee, /* seashell */
  65628. 0xca348772, 0xffa0522d, /* sienna */
  65629. 0xca37d30d, 0xffc0c0c0, /* silver */
  65630. 0x80da74fb, 0xff87ceeb, /* skyblue */
  65631. 0x44a8dd73, 0xff6a5acd, /* slateblue */
  65632. 0x44ab37f8, 0xff708090, /* slategrey */
  65633. 0x0035f183, 0xfffffafa, /* snow */
  65634. 0xd5440d16, 0xff00ff7f, /* springgreen */
  65635. 0x3e1524a5, 0xff4682b4, /* steelblue */
  65636. 0x0001bfa1, 0xffd2b48c, /* tan */
  65637. 0x0036425c, 0xff008080, /* teal */
  65638. 0xafc8858f, 0xffd8bfd8, /* thistle */
  65639. 0xcc41600a, 0xffff6347, /* tomato */
  65640. 0xfeea9b21, 0xff40e0d0, /* turquoise */
  65641. 0xcf57947f, 0xffee82ee, /* violet */
  65642. 0x06bdbae7, 0xfff5deb3, /* wheat */
  65643. 0x10802ee6, 0xfff5f5f5, /* whitesmoke */
  65644. 0xe1b5130f, 0xff9acd32 /* yellowgreen */
  65645. };
  65646. const int hash = colourName.trim().toLowerCase().hashCode();
  65647. for (int i = 0; i < numElementsInArray (presets); i += 2)
  65648. if (presets [i] == hash)
  65649. return Colour (presets [i + 1]);
  65650. return defaultColour;
  65651. }
  65652. END_JUCE_NAMESPACE
  65653. /*** End of inlined file: juce_Colours.cpp ***/
  65654. /*** Start of inlined file: juce_EdgeTable.cpp ***/
  65655. BEGIN_JUCE_NAMESPACE
  65656. const int juce_edgeTableDefaultEdgesPerLine = 32;
  65657. EdgeTable::EdgeTable (const Rectangle<int>& bounds_,
  65658. const Path& path, const AffineTransform& transform)
  65659. : bounds (bounds_),
  65660. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65661. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65662. needToCheckEmptinesss (true)
  65663. {
  65664. table.malloc ((bounds.getHeight() + 1) * lineStrideElements);
  65665. int* t = table;
  65666. for (int i = bounds.getHeight(); --i >= 0;)
  65667. {
  65668. *t = 0;
  65669. t += lineStrideElements;
  65670. }
  65671. const int topLimit = bounds.getY() << 8;
  65672. const int heightLimit = bounds.getHeight() << 8;
  65673. const int leftLimit = bounds.getX() << 8;
  65674. const int rightLimit = bounds.getRight() << 8;
  65675. PathFlatteningIterator iter (path, transform);
  65676. while (iter.next())
  65677. {
  65678. int y1 = roundToInt (iter.y1 * 256.0f);
  65679. int y2 = roundToInt (iter.y2 * 256.0f);
  65680. if (y1 != y2)
  65681. {
  65682. y1 -= topLimit;
  65683. y2 -= topLimit;
  65684. const int startY = y1;
  65685. int direction = -1;
  65686. if (y1 > y2)
  65687. {
  65688. swapVariables (y1, y2);
  65689. direction = 1;
  65690. }
  65691. if (y1 < 0)
  65692. y1 = 0;
  65693. if (y2 > heightLimit)
  65694. y2 = heightLimit;
  65695. if (y1 < y2)
  65696. {
  65697. const double startX = 256.0f * iter.x1;
  65698. const double multiplier = (iter.x2 - iter.x1) / (iter.y2 - iter.y1);
  65699. const int stepSize = jlimit (1, 256, 256 / (1 + (int) std::abs (multiplier)));
  65700. do
  65701. {
  65702. const int step = jmin (stepSize, y2 - y1, 256 - (y1 & 255));
  65703. int x = roundToInt (startX + multiplier * ((y1 + (step >> 1)) - startY));
  65704. if (x < leftLimit)
  65705. x = leftLimit;
  65706. else if (x >= rightLimit)
  65707. x = rightLimit - 1;
  65708. addEdgePoint (x, y1 >> 8, direction * step);
  65709. y1 += step;
  65710. }
  65711. while (y1 < y2);
  65712. }
  65713. }
  65714. }
  65715. sanitiseLevels (path.isUsingNonZeroWinding());
  65716. }
  65717. EdgeTable::EdgeTable (const Rectangle<int>& rectangleToAdd)
  65718. : bounds (rectangleToAdd),
  65719. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65720. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65721. needToCheckEmptinesss (true)
  65722. {
  65723. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65724. table[0] = 0;
  65725. const int x1 = rectangleToAdd.getX() << 8;
  65726. const int x2 = rectangleToAdd.getRight() << 8;
  65727. int* t = table;
  65728. for (int i = rectangleToAdd.getHeight(); --i >= 0;)
  65729. {
  65730. t[0] = 2;
  65731. t[1] = x1;
  65732. t[2] = 255;
  65733. t[3] = x2;
  65734. t[4] = 0;
  65735. t += lineStrideElements;
  65736. }
  65737. }
  65738. EdgeTable::EdgeTable (const RectangleList& rectanglesToAdd)
  65739. : bounds (rectanglesToAdd.getBounds()),
  65740. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65741. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65742. needToCheckEmptinesss (true)
  65743. {
  65744. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65745. int* t = table;
  65746. for (int i = bounds.getHeight(); --i >= 0;)
  65747. {
  65748. *t = 0;
  65749. t += lineStrideElements;
  65750. }
  65751. for (RectangleList::Iterator iter (rectanglesToAdd); iter.next();)
  65752. {
  65753. const Rectangle<int>* const r = iter.getRectangle();
  65754. const int x1 = r->getX() << 8;
  65755. const int x2 = r->getRight() << 8;
  65756. int y = r->getY() - bounds.getY();
  65757. for (int j = r->getHeight(); --j >= 0;)
  65758. {
  65759. addEdgePoint (x1, y, 255);
  65760. addEdgePoint (x2, y, -255);
  65761. ++y;
  65762. }
  65763. }
  65764. sanitiseLevels (true);
  65765. }
  65766. EdgeTable::EdgeTable (const Rectangle<float>& rectangleToAdd)
  65767. : bounds (Rectangle<int> ((int) std::floor (rectangleToAdd.getX()),
  65768. roundToInt (rectangleToAdd.getY() * 256.0f) >> 8,
  65769. 2 + (int) rectangleToAdd.getWidth(),
  65770. 2 + (int) rectangleToAdd.getHeight())),
  65771. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65772. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65773. needToCheckEmptinesss (true)
  65774. {
  65775. jassert (! rectangleToAdd.isEmpty());
  65776. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65777. table[0] = 0;
  65778. const int x1 = roundToInt (rectangleToAdd.getX() * 256.0f);
  65779. const int x2 = roundToInt (rectangleToAdd.getRight() * 256.0f);
  65780. int y1 = roundToInt (rectangleToAdd.getY() * 256.0f) - (bounds.getY() << 8);
  65781. jassert (y1 < 256);
  65782. int y2 = roundToInt (rectangleToAdd.getBottom() * 256.0f) - (bounds.getY() << 8);
  65783. if (x2 <= x1 || y2 <= y1)
  65784. {
  65785. bounds.setHeight (0);
  65786. return;
  65787. }
  65788. int lineY = 0;
  65789. int* t = table;
  65790. if ((y1 >> 8) == (y2 >> 8))
  65791. {
  65792. t[0] = 2;
  65793. t[1] = x1;
  65794. t[2] = y2 - y1;
  65795. t[3] = x2;
  65796. t[4] = 0;
  65797. ++lineY;
  65798. t += lineStrideElements;
  65799. }
  65800. else
  65801. {
  65802. t[0] = 2;
  65803. t[1] = x1;
  65804. t[2] = 255 - (y1 & 255);
  65805. t[3] = x2;
  65806. t[4] = 0;
  65807. ++lineY;
  65808. t += lineStrideElements;
  65809. while (lineY < (y2 >> 8))
  65810. {
  65811. t[0] = 2;
  65812. t[1] = x1;
  65813. t[2] = 255;
  65814. t[3] = x2;
  65815. t[4] = 0;
  65816. ++lineY;
  65817. t += lineStrideElements;
  65818. }
  65819. jassert (lineY < bounds.getHeight());
  65820. t[0] = 2;
  65821. t[1] = x1;
  65822. t[2] = y2 & 255;
  65823. t[3] = x2;
  65824. t[4] = 0;
  65825. ++lineY;
  65826. t += lineStrideElements;
  65827. }
  65828. while (lineY < bounds.getHeight())
  65829. {
  65830. t[0] = 0;
  65831. t += lineStrideElements;
  65832. ++lineY;
  65833. }
  65834. }
  65835. EdgeTable::EdgeTable (const EdgeTable& other)
  65836. {
  65837. operator= (other);
  65838. }
  65839. EdgeTable& EdgeTable::operator= (const EdgeTable& other)
  65840. {
  65841. bounds = other.bounds;
  65842. maxEdgesPerLine = other.maxEdgesPerLine;
  65843. lineStrideElements = other.lineStrideElements;
  65844. needToCheckEmptinesss = other.needToCheckEmptinesss;
  65845. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65846. copyEdgeTableData (table, lineStrideElements, other.table, lineStrideElements, bounds.getHeight());
  65847. return *this;
  65848. }
  65849. EdgeTable::~EdgeTable()
  65850. {
  65851. }
  65852. void EdgeTable::copyEdgeTableData (int* dest, const int destLineStride, const int* src, const int srcLineStride, int numLines) throw()
  65853. {
  65854. while (--numLines >= 0)
  65855. {
  65856. memcpy (dest, src, (src[0] * 2 + 1) * sizeof (int));
  65857. src += srcLineStride;
  65858. dest += destLineStride;
  65859. }
  65860. }
  65861. void EdgeTable::sanitiseLevels (const bool useNonZeroWinding) throw()
  65862. {
  65863. // Convert the table from relative windings to absolute levels..
  65864. int* lineStart = table;
  65865. for (int i = bounds.getHeight(); --i >= 0;)
  65866. {
  65867. int* line = lineStart;
  65868. lineStart += lineStrideElements;
  65869. int num = *line;
  65870. if (num == 0)
  65871. continue;
  65872. int level = 0;
  65873. if (useNonZeroWinding)
  65874. {
  65875. while (--num > 0)
  65876. {
  65877. line += 2;
  65878. level += *line;
  65879. int corrected = abs (level);
  65880. if (corrected >> 8)
  65881. corrected = 255;
  65882. *line = corrected;
  65883. }
  65884. }
  65885. else
  65886. {
  65887. while (--num > 0)
  65888. {
  65889. line += 2;
  65890. level += *line;
  65891. int corrected = abs (level);
  65892. if (corrected >> 8)
  65893. {
  65894. corrected &= 511;
  65895. if (corrected >> 8)
  65896. corrected = 511 - corrected;
  65897. }
  65898. *line = corrected;
  65899. }
  65900. }
  65901. line[2] = 0; // force the last level to 0, just in case something went wrong in creating the table
  65902. }
  65903. }
  65904. void EdgeTable::remapTableForNumEdges (const int newNumEdgesPerLine) throw()
  65905. {
  65906. if (newNumEdgesPerLine != maxEdgesPerLine)
  65907. {
  65908. maxEdgesPerLine = newNumEdgesPerLine;
  65909. jassert (bounds.getHeight() > 0);
  65910. const int newLineStrideElements = maxEdgesPerLine * 2 + 1;
  65911. HeapBlock <int> newTable (bounds.getHeight() * newLineStrideElements);
  65912. copyEdgeTableData (newTable, newLineStrideElements, table, lineStrideElements, bounds.getHeight());
  65913. table.swapWith (newTable);
  65914. lineStrideElements = newLineStrideElements;
  65915. }
  65916. }
  65917. void EdgeTable::optimiseTable() throw()
  65918. {
  65919. int maxLineElements = 0;
  65920. for (int i = bounds.getHeight(); --i >= 0;)
  65921. maxLineElements = jmax (maxLineElements, table [i * lineStrideElements]);
  65922. remapTableForNumEdges (maxLineElements);
  65923. }
  65924. void EdgeTable::addEdgePoint (const int x, const int y, const int winding) throw()
  65925. {
  65926. jassert (y >= 0 && y < bounds.getHeight());
  65927. int* line = table + lineStrideElements * y;
  65928. const int numPoints = line[0];
  65929. int n = numPoints << 1;
  65930. if (n > 0)
  65931. {
  65932. while (n > 0)
  65933. {
  65934. const int cx = line [n - 1];
  65935. if (cx <= x)
  65936. {
  65937. if (cx == x)
  65938. {
  65939. line [n] += winding;
  65940. return;
  65941. }
  65942. break;
  65943. }
  65944. n -= 2;
  65945. }
  65946. if (numPoints >= maxEdgesPerLine)
  65947. {
  65948. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  65949. jassert (numPoints < maxEdgesPerLine);
  65950. line = table + lineStrideElements * y;
  65951. }
  65952. memmove (line + (n + 3), line + (n + 1), sizeof (int) * ((numPoints << 1) - n));
  65953. }
  65954. line [n + 1] = x;
  65955. line [n + 2] = winding;
  65956. line[0]++;
  65957. }
  65958. void EdgeTable::translate (float dx, const int dy) throw()
  65959. {
  65960. bounds.translate ((int) std::floor (dx), dy);
  65961. int* lineStart = table;
  65962. const int intDx = (int) (dx * 256.0f);
  65963. for (int i = bounds.getHeight(); --i >= 0;)
  65964. {
  65965. int* line = lineStart;
  65966. lineStart += lineStrideElements;
  65967. int num = *line++;
  65968. while (--num >= 0)
  65969. {
  65970. *line += intDx;
  65971. line += 2;
  65972. }
  65973. }
  65974. }
  65975. void EdgeTable::intersectWithEdgeTableLine (const int y, const int* otherLine) throw()
  65976. {
  65977. jassert (y >= 0 && y < bounds.getHeight());
  65978. int* dest = table + lineStrideElements * y;
  65979. if (dest[0] == 0)
  65980. return;
  65981. int otherNumPoints = *otherLine;
  65982. if (otherNumPoints == 0)
  65983. {
  65984. *dest = 0;
  65985. return;
  65986. }
  65987. const int right = bounds.getRight() << 8;
  65988. // optimise for the common case where our line lies entirely within a
  65989. // single pair of points, as happens when clipping to a simple rect.
  65990. if (otherNumPoints == 2 && otherLine[2] >= 255)
  65991. {
  65992. clipEdgeTableLineToRange (dest, otherLine[1], jmin (right, otherLine[3]));
  65993. return;
  65994. }
  65995. ++otherLine;
  65996. const size_t lineSizeBytes = (dest[0] * 2 + 1) * sizeof (int);
  65997. int* temp = static_cast<int*> (alloca (lineSizeBytes));
  65998. memcpy (temp, dest, lineSizeBytes);
  65999. const int* src1 = temp;
  66000. int srcNum1 = *src1++;
  66001. int x1 = *src1++;
  66002. const int* src2 = otherLine;
  66003. int srcNum2 = otherNumPoints;
  66004. int x2 = *src2++;
  66005. int destIndex = 0, destTotal = 0;
  66006. int level1 = 0, level2 = 0;
  66007. int lastX = std::numeric_limits<int>::min(), lastLevel = 0;
  66008. while (srcNum1 > 0 && srcNum2 > 0)
  66009. {
  66010. int nextX;
  66011. if (x1 < x2)
  66012. {
  66013. nextX = x1;
  66014. level1 = *src1++;
  66015. x1 = *src1++;
  66016. --srcNum1;
  66017. }
  66018. else if (x1 == x2)
  66019. {
  66020. nextX = x1;
  66021. level1 = *src1++;
  66022. level2 = *src2++;
  66023. x1 = *src1++;
  66024. x2 = *src2++;
  66025. --srcNum1;
  66026. --srcNum2;
  66027. }
  66028. else
  66029. {
  66030. nextX = x2;
  66031. level2 = *src2++;
  66032. x2 = *src2++;
  66033. --srcNum2;
  66034. }
  66035. if (nextX > lastX)
  66036. {
  66037. if (nextX >= right)
  66038. break;
  66039. lastX = nextX;
  66040. const int nextLevel = (level1 * (level2 + 1)) >> 8;
  66041. jassert (((unsigned int) nextLevel) < (unsigned int) 256);
  66042. if (nextLevel != lastLevel)
  66043. {
  66044. if (destTotal >= maxEdgesPerLine)
  66045. {
  66046. dest[0] = destTotal;
  66047. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  66048. dest = table + lineStrideElements * y;
  66049. }
  66050. ++destTotal;
  66051. lastLevel = nextLevel;
  66052. dest[++destIndex] = nextX;
  66053. dest[++destIndex] = nextLevel;
  66054. }
  66055. }
  66056. }
  66057. if (lastLevel > 0)
  66058. {
  66059. if (destTotal >= maxEdgesPerLine)
  66060. {
  66061. dest[0] = destTotal;
  66062. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  66063. dest = table + lineStrideElements * y;
  66064. }
  66065. ++destTotal;
  66066. dest[++destIndex] = right;
  66067. dest[++destIndex] = 0;
  66068. }
  66069. dest[0] = destTotal;
  66070. #if JUCE_DEBUG
  66071. int last = std::numeric_limits<int>::min();
  66072. for (int i = 0; i < dest[0]; ++i)
  66073. {
  66074. jassert (dest[i * 2 + 1] > last);
  66075. last = dest[i * 2 + 1];
  66076. }
  66077. jassert (dest [dest[0] * 2] == 0);
  66078. #endif
  66079. }
  66080. void EdgeTable::clipEdgeTableLineToRange (int* dest, const int x1, const int x2) throw()
  66081. {
  66082. int* lastItem = dest + (dest[0] * 2 - 1);
  66083. if (x2 < lastItem[0])
  66084. {
  66085. if (x2 <= dest[1])
  66086. {
  66087. dest[0] = 0;
  66088. return;
  66089. }
  66090. while (x2 < lastItem[-2])
  66091. {
  66092. --(dest[0]);
  66093. lastItem -= 2;
  66094. }
  66095. lastItem[0] = x2;
  66096. lastItem[1] = 0;
  66097. }
  66098. if (x1 > dest[1])
  66099. {
  66100. while (lastItem[0] > x1)
  66101. lastItem -= 2;
  66102. const int itemsRemoved = (int) (lastItem - (dest + 1)) / 2;
  66103. if (itemsRemoved > 0)
  66104. {
  66105. dest[0] -= itemsRemoved;
  66106. memmove (dest + 1, lastItem, dest[0] * (sizeof (int) * 2));
  66107. }
  66108. dest[1] = x1;
  66109. }
  66110. }
  66111. void EdgeTable::clipToRectangle (const Rectangle<int>& r) throw()
  66112. {
  66113. const Rectangle<int> clipped (r.getIntersection (bounds));
  66114. if (clipped.isEmpty())
  66115. {
  66116. needToCheckEmptinesss = false;
  66117. bounds.setHeight (0);
  66118. }
  66119. else
  66120. {
  66121. const int top = clipped.getY() - bounds.getY();
  66122. const int bottom = clipped.getBottom() - bounds.getY();
  66123. if (bottom < bounds.getHeight())
  66124. bounds.setHeight (bottom);
  66125. if (clipped.getRight() < bounds.getRight())
  66126. bounds.setRight (clipped.getRight());
  66127. for (int i = top; --i >= 0;)
  66128. table [lineStrideElements * i] = 0;
  66129. if (clipped.getX() > bounds.getX())
  66130. {
  66131. const int x1 = clipped.getX() << 8;
  66132. const int x2 = jmin (bounds.getRight(), clipped.getRight()) << 8;
  66133. int* line = table + lineStrideElements * top;
  66134. for (int i = bottom - top; --i >= 0;)
  66135. {
  66136. if (line[0] != 0)
  66137. clipEdgeTableLineToRange (line, x1, x2);
  66138. line += lineStrideElements;
  66139. }
  66140. }
  66141. needToCheckEmptinesss = true;
  66142. }
  66143. }
  66144. void EdgeTable::excludeRectangle (const Rectangle<int>& r) throw()
  66145. {
  66146. const Rectangle<int> clipped (r.getIntersection (bounds));
  66147. if (! clipped.isEmpty())
  66148. {
  66149. const int top = clipped.getY() - bounds.getY();
  66150. const int bottom = clipped.getBottom() - bounds.getY();
  66151. //XXX optimise here by shortening the table if it fills top or bottom
  66152. const int rectLine[] = { 4, std::numeric_limits<int>::min(), 255,
  66153. clipped.getX() << 8, 0,
  66154. clipped.getRight() << 8, 255,
  66155. std::numeric_limits<int>::max(), 0 };
  66156. for (int i = top; i < bottom; ++i)
  66157. intersectWithEdgeTableLine (i, rectLine);
  66158. needToCheckEmptinesss = true;
  66159. }
  66160. }
  66161. void EdgeTable::clipToEdgeTable (const EdgeTable& other)
  66162. {
  66163. const Rectangle<int> clipped (other.bounds.getIntersection (bounds));
  66164. if (clipped.isEmpty())
  66165. {
  66166. needToCheckEmptinesss = false;
  66167. bounds.setHeight (0);
  66168. }
  66169. else
  66170. {
  66171. const int top = clipped.getY() - bounds.getY();
  66172. const int bottom = clipped.getBottom() - bounds.getY();
  66173. if (bottom < bounds.getHeight())
  66174. bounds.setHeight (bottom);
  66175. if (clipped.getRight() < bounds.getRight())
  66176. bounds.setRight (clipped.getRight());
  66177. int i = 0;
  66178. for (i = top; --i >= 0;)
  66179. table [lineStrideElements * i] = 0;
  66180. const int* otherLine = other.table + other.lineStrideElements * (clipped.getY() - other.bounds.getY());
  66181. for (i = top; i < bottom; ++i)
  66182. {
  66183. intersectWithEdgeTableLine (i, otherLine);
  66184. otherLine += other.lineStrideElements;
  66185. }
  66186. needToCheckEmptinesss = true;
  66187. }
  66188. }
  66189. void EdgeTable::clipLineToMask (int x, int y, const uint8* mask, int maskStride, int numPixels) throw()
  66190. {
  66191. y -= bounds.getY();
  66192. if (y < 0 || y >= bounds.getHeight())
  66193. return;
  66194. needToCheckEmptinesss = true;
  66195. if (numPixels <= 0)
  66196. {
  66197. table [lineStrideElements * y] = 0;
  66198. return;
  66199. }
  66200. int* tempLine = static_cast<int*> (alloca ((numPixels * 2 + 4) * sizeof (int)));
  66201. int destIndex = 0, lastLevel = 0;
  66202. while (--numPixels >= 0)
  66203. {
  66204. const int alpha = *mask;
  66205. mask += maskStride;
  66206. if (alpha != lastLevel)
  66207. {
  66208. tempLine[++destIndex] = (x << 8);
  66209. tempLine[++destIndex] = alpha;
  66210. lastLevel = alpha;
  66211. }
  66212. ++x;
  66213. }
  66214. if (lastLevel > 0)
  66215. {
  66216. tempLine[++destIndex] = (x << 8);
  66217. tempLine[++destIndex] = 0;
  66218. }
  66219. tempLine[0] = destIndex >> 1;
  66220. intersectWithEdgeTableLine (y, tempLine);
  66221. }
  66222. bool EdgeTable::isEmpty() throw()
  66223. {
  66224. if (needToCheckEmptinesss)
  66225. {
  66226. needToCheckEmptinesss = false;
  66227. int* t = table;
  66228. for (int i = bounds.getHeight(); --i >= 0;)
  66229. {
  66230. if (t[0] > 1)
  66231. return false;
  66232. t += lineStrideElements;
  66233. }
  66234. bounds.setHeight (0);
  66235. }
  66236. return bounds.getHeight() == 0;
  66237. }
  66238. END_JUCE_NAMESPACE
  66239. /*** End of inlined file: juce_EdgeTable.cpp ***/
  66240. /*** Start of inlined file: juce_FillType.cpp ***/
  66241. BEGIN_JUCE_NAMESPACE
  66242. FillType::FillType() throw()
  66243. : colour (0xff000000), image (0)
  66244. {
  66245. }
  66246. FillType::FillType (const Colour& colour_) throw()
  66247. : colour (colour_), image (0)
  66248. {
  66249. }
  66250. FillType::FillType (const ColourGradient& gradient_)
  66251. : colour (0xff000000), gradient (new ColourGradient (gradient_)), image (0)
  66252. {
  66253. }
  66254. FillType::FillType (const Image& image_, const AffineTransform& transform_) throw()
  66255. : colour (0xff000000), image (image_), transform (transform_)
  66256. {
  66257. }
  66258. FillType::FillType (const FillType& other)
  66259. : colour (other.colour),
  66260. gradient (other.gradient != 0 ? new ColourGradient (*other.gradient) : 0),
  66261. image (other.image), transform (other.transform)
  66262. {
  66263. }
  66264. FillType& FillType::operator= (const FillType& other)
  66265. {
  66266. if (this != &other)
  66267. {
  66268. colour = other.colour;
  66269. gradient = (other.gradient != 0 ? new ColourGradient (*other.gradient) : 0);
  66270. image = other.image;
  66271. transform = other.transform;
  66272. }
  66273. return *this;
  66274. }
  66275. FillType::~FillType() throw()
  66276. {
  66277. }
  66278. bool FillType::operator== (const FillType& other) const
  66279. {
  66280. return colour == other.colour && image == other.image
  66281. && transform == other.transform
  66282. && (gradient == other.gradient
  66283. || (gradient != 0 && other.gradient != 0 && *gradient == *other.gradient));
  66284. }
  66285. bool FillType::operator!= (const FillType& other) const
  66286. {
  66287. return ! operator== (other);
  66288. }
  66289. void FillType::setColour (const Colour& newColour) throw()
  66290. {
  66291. gradient = 0;
  66292. image = Image::null;
  66293. colour = newColour;
  66294. }
  66295. void FillType::setGradient (const ColourGradient& newGradient)
  66296. {
  66297. if (gradient != 0)
  66298. {
  66299. *gradient = newGradient;
  66300. }
  66301. else
  66302. {
  66303. image = Image::null;
  66304. gradient = new ColourGradient (newGradient);
  66305. colour = Colours::black;
  66306. }
  66307. }
  66308. void FillType::setTiledImage (const Image& image_, const AffineTransform& transform_) throw()
  66309. {
  66310. gradient = 0;
  66311. image = image_;
  66312. transform = transform_;
  66313. colour = Colours::black;
  66314. }
  66315. void FillType::setOpacity (const float newOpacity) throw()
  66316. {
  66317. colour = colour.withAlpha (newOpacity);
  66318. }
  66319. bool FillType::isInvisible() const throw()
  66320. {
  66321. return colour.isTransparent() || (gradient != 0 && gradient->isInvisible());
  66322. }
  66323. END_JUCE_NAMESPACE
  66324. /*** End of inlined file: juce_FillType.cpp ***/
  66325. /*** Start of inlined file: juce_Graphics.cpp ***/
  66326. BEGIN_JUCE_NAMESPACE
  66327. namespace
  66328. {
  66329. template <typename Type>
  66330. bool areCoordsSensibleNumbers (Type x, Type y, Type w, Type h)
  66331. {
  66332. const int maxVal = 0x3fffffff;
  66333. return (int) x >= -maxVal && (int) x <= maxVal
  66334. && (int) y >= -maxVal && (int) y <= maxVal
  66335. && (int) w >= -maxVal && (int) w <= maxVal
  66336. && (int) h >= -maxVal && (int) h <= maxVal;
  66337. }
  66338. }
  66339. LowLevelGraphicsContext::LowLevelGraphicsContext()
  66340. {
  66341. }
  66342. LowLevelGraphicsContext::~LowLevelGraphicsContext()
  66343. {
  66344. }
  66345. Graphics::Graphics (const Image& imageToDrawOnto)
  66346. : context (imageToDrawOnto.createLowLevelContext()),
  66347. contextToDelete (context),
  66348. saveStatePending (false)
  66349. {
  66350. }
  66351. Graphics::Graphics (LowLevelGraphicsContext* const internalContext) throw()
  66352. : context (internalContext),
  66353. saveStatePending (false)
  66354. {
  66355. }
  66356. Graphics::~Graphics()
  66357. {
  66358. }
  66359. void Graphics::resetToDefaultState()
  66360. {
  66361. saveStateIfPending();
  66362. context->setFill (FillType());
  66363. context->setFont (Font());
  66364. context->setInterpolationQuality (Graphics::mediumResamplingQuality);
  66365. }
  66366. bool Graphics::isVectorDevice() const
  66367. {
  66368. return context->isVectorDevice();
  66369. }
  66370. bool Graphics::reduceClipRegion (const Rectangle<int>& area)
  66371. {
  66372. saveStateIfPending();
  66373. return context->clipToRectangle (area);
  66374. }
  66375. bool Graphics::reduceClipRegion (const int x, const int y, const int w, const int h)
  66376. {
  66377. return reduceClipRegion (Rectangle<int> (x, y, w, h));
  66378. }
  66379. bool Graphics::reduceClipRegion (const RectangleList& clipRegion)
  66380. {
  66381. saveStateIfPending();
  66382. return context->clipToRectangleList (clipRegion);
  66383. }
  66384. bool Graphics::reduceClipRegion (const Path& path, const AffineTransform& transform)
  66385. {
  66386. saveStateIfPending();
  66387. context->clipToPath (path, transform);
  66388. return ! context->isClipEmpty();
  66389. }
  66390. bool Graphics::reduceClipRegion (const Image& image, const AffineTransform& transform)
  66391. {
  66392. saveStateIfPending();
  66393. context->clipToImageAlpha (image, transform);
  66394. return ! context->isClipEmpty();
  66395. }
  66396. void Graphics::excludeClipRegion (const Rectangle<int>& rectangleToExclude)
  66397. {
  66398. saveStateIfPending();
  66399. context->excludeClipRectangle (rectangleToExclude);
  66400. }
  66401. bool Graphics::isClipEmpty() const
  66402. {
  66403. return context->isClipEmpty();
  66404. }
  66405. const Rectangle<int> Graphics::getClipBounds() const
  66406. {
  66407. return context->getClipBounds();
  66408. }
  66409. void Graphics::saveState()
  66410. {
  66411. saveStateIfPending();
  66412. saveStatePending = true;
  66413. }
  66414. void Graphics::restoreState()
  66415. {
  66416. if (saveStatePending)
  66417. saveStatePending = false;
  66418. else
  66419. context->restoreState();
  66420. }
  66421. void Graphics::saveStateIfPending()
  66422. {
  66423. if (saveStatePending)
  66424. {
  66425. saveStatePending = false;
  66426. context->saveState();
  66427. }
  66428. }
  66429. void Graphics::setOrigin (const int newOriginX, const int newOriginY)
  66430. {
  66431. saveStateIfPending();
  66432. context->setOrigin (newOriginX, newOriginY);
  66433. }
  66434. bool Graphics::clipRegionIntersects (const Rectangle<int>& area) const
  66435. {
  66436. return context->clipRegionIntersects (area);
  66437. }
  66438. void Graphics::setColour (const Colour& newColour)
  66439. {
  66440. saveStateIfPending();
  66441. context->setFill (newColour);
  66442. }
  66443. void Graphics::setOpacity (const float newOpacity)
  66444. {
  66445. saveStateIfPending();
  66446. context->setOpacity (newOpacity);
  66447. }
  66448. void Graphics::setGradientFill (const ColourGradient& gradient)
  66449. {
  66450. setFillType (gradient);
  66451. }
  66452. void Graphics::setTiledImageFill (const Image& imageToUse, const int anchorX, const int anchorY, const float opacity)
  66453. {
  66454. saveStateIfPending();
  66455. context->setFill (FillType (imageToUse, AffineTransform::translation ((float) anchorX, (float) anchorY)));
  66456. context->setOpacity (opacity);
  66457. }
  66458. void Graphics::setFillType (const FillType& newFill)
  66459. {
  66460. saveStateIfPending();
  66461. context->setFill (newFill);
  66462. }
  66463. void Graphics::setFont (const Font& newFont)
  66464. {
  66465. saveStateIfPending();
  66466. context->setFont (newFont);
  66467. }
  66468. void Graphics::setFont (const float newFontHeight, const int newFontStyleFlags)
  66469. {
  66470. saveStateIfPending();
  66471. Font f (context->getFont());
  66472. f.setSizeAndStyle (newFontHeight, newFontStyleFlags, 1.0f, 0);
  66473. context->setFont (f);
  66474. }
  66475. const Font Graphics::getCurrentFont() const
  66476. {
  66477. return context->getFont();
  66478. }
  66479. void Graphics::drawSingleLineText (const String& text, const int startX, const int baselineY) const
  66480. {
  66481. if (text.isNotEmpty()
  66482. && startX < context->getClipBounds().getRight())
  66483. {
  66484. GlyphArrangement arr;
  66485. arr.addLineOfText (context->getFont(), text, (float) startX, (float) baselineY);
  66486. arr.draw (*this);
  66487. }
  66488. }
  66489. void Graphics::drawTextAsPath (const String& text, const AffineTransform& transform) const
  66490. {
  66491. if (text.isNotEmpty())
  66492. {
  66493. GlyphArrangement arr;
  66494. arr.addLineOfText (context->getFont(), text, 0.0f, 0.0f);
  66495. arr.draw (*this, transform);
  66496. }
  66497. }
  66498. void Graphics::drawMultiLineText (const String& text, const int startX, const int baselineY, const int maximumLineWidth) const
  66499. {
  66500. if (text.isNotEmpty()
  66501. && startX < context->getClipBounds().getRight())
  66502. {
  66503. GlyphArrangement arr;
  66504. arr.addJustifiedText (context->getFont(), text,
  66505. (float) startX, (float) baselineY, (float) maximumLineWidth,
  66506. Justification::left);
  66507. arr.draw (*this);
  66508. }
  66509. }
  66510. void Graphics::drawText (const String& text,
  66511. const int x, const int y, const int width, const int height,
  66512. const Justification& justificationType,
  66513. const bool useEllipsesIfTooBig) const
  66514. {
  66515. if (text.isNotEmpty() && context->clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66516. {
  66517. GlyphArrangement arr;
  66518. arr.addCurtailedLineOfText (context->getFont(), text,
  66519. 0.0f, 0.0f, (float) width,
  66520. useEllipsesIfTooBig);
  66521. arr.justifyGlyphs (0, arr.getNumGlyphs(),
  66522. (float) x, (float) y, (float) width, (float) height,
  66523. justificationType);
  66524. arr.draw (*this);
  66525. }
  66526. }
  66527. void Graphics::drawFittedText (const String& text,
  66528. const int x, const int y, const int width, const int height,
  66529. const Justification& justification,
  66530. const int maximumNumberOfLines,
  66531. const float minimumHorizontalScale) const
  66532. {
  66533. if (text.isNotEmpty()
  66534. && width > 0 && height > 0
  66535. && context->clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66536. {
  66537. GlyphArrangement arr;
  66538. arr.addFittedText (context->getFont(), text,
  66539. (float) x, (float) y, (float) width, (float) height,
  66540. justification,
  66541. maximumNumberOfLines,
  66542. minimumHorizontalScale);
  66543. arr.draw (*this);
  66544. }
  66545. }
  66546. void Graphics::fillRect (int x, int y, int width, int height) const
  66547. {
  66548. // passing in a silly number can cause maths problems in rendering!
  66549. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66550. context->fillRect (Rectangle<int> (x, y, width, height), false);
  66551. }
  66552. void Graphics::fillRect (const Rectangle<int>& r) const
  66553. {
  66554. context->fillRect (r, false);
  66555. }
  66556. void Graphics::fillRect (const float x, const float y, const float width, const float height) const
  66557. {
  66558. // passing in a silly number can cause maths problems in rendering!
  66559. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66560. Path p;
  66561. p.addRectangle (x, y, width, height);
  66562. fillPath (p);
  66563. }
  66564. void Graphics::setPixel (int x, int y) const
  66565. {
  66566. context->fillRect (Rectangle<int> (x, y, 1, 1), false);
  66567. }
  66568. void Graphics::fillAll() const
  66569. {
  66570. fillRect (context->getClipBounds());
  66571. }
  66572. void Graphics::fillAll (const Colour& colourToUse) const
  66573. {
  66574. if (! colourToUse.isTransparent())
  66575. {
  66576. const Rectangle<int> clip (context->getClipBounds());
  66577. context->saveState();
  66578. context->setFill (colourToUse);
  66579. context->fillRect (clip, false);
  66580. context->restoreState();
  66581. }
  66582. }
  66583. void Graphics::fillPath (const Path& path, const AffineTransform& transform) const
  66584. {
  66585. if ((! context->isClipEmpty()) && ! path.isEmpty())
  66586. context->fillPath (path, transform);
  66587. }
  66588. void Graphics::strokePath (const Path& path,
  66589. const PathStrokeType& strokeType,
  66590. const AffineTransform& transform) const
  66591. {
  66592. Path stroke;
  66593. strokeType.createStrokedPath (stroke, path, transform);
  66594. fillPath (stroke);
  66595. }
  66596. void Graphics::drawRect (const int x, const int y, const int width, const int height,
  66597. const int lineThickness) const
  66598. {
  66599. // passing in a silly number can cause maths problems in rendering!
  66600. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66601. context->fillRect (Rectangle<int> (x, y, width, lineThickness), false);
  66602. context->fillRect (Rectangle<int> (x, y + lineThickness, lineThickness, height - lineThickness * 2), false);
  66603. context->fillRect (Rectangle<int> (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2), false);
  66604. context->fillRect (Rectangle<int> (x, y + height - lineThickness, width, lineThickness), false);
  66605. }
  66606. void Graphics::drawRect (const float x, const float y, const float width, const float height, const float lineThickness) const
  66607. {
  66608. // passing in a silly number can cause maths problems in rendering!
  66609. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66610. Path p;
  66611. p.addRectangle (x, y, width, lineThickness);
  66612. p.addRectangle (x, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  66613. p.addRectangle (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  66614. p.addRectangle (x, y + height - lineThickness, width, lineThickness);
  66615. fillPath (p);
  66616. }
  66617. void Graphics::drawRect (const Rectangle<int>& r, const int lineThickness) const
  66618. {
  66619. drawRect (r.getX(), r.getY(), r.getWidth(), r.getHeight(), lineThickness);
  66620. }
  66621. void Graphics::drawBevel (const int x, const int y, const int width, const int height,
  66622. const int bevelThickness, const Colour& topLeftColour, const Colour& bottomRightColour,
  66623. const bool useGradient, const bool sharpEdgeOnOutside) const
  66624. {
  66625. // passing in a silly number can cause maths problems in rendering!
  66626. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66627. if (clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66628. {
  66629. context->saveState();
  66630. const float oldOpacity = 1.0f;//xxx state->colour.getFloatAlpha();
  66631. const float ramp = oldOpacity / bevelThickness;
  66632. for (int i = bevelThickness; --i >= 0;)
  66633. {
  66634. const float op = useGradient ? ramp * (sharpEdgeOnOutside ? bevelThickness - i : i)
  66635. : oldOpacity;
  66636. context->setFill (topLeftColour.withMultipliedAlpha (op));
  66637. context->fillRect (Rectangle<int> (x + i, y + i, width - i * 2, 1), false);
  66638. context->setFill (topLeftColour.withMultipliedAlpha (op * 0.75f));
  66639. context->fillRect (Rectangle<int> (x + i, y + i + 1, 1, height - i * 2 - 2), false);
  66640. context->setFill (bottomRightColour.withMultipliedAlpha (op));
  66641. context->fillRect (Rectangle<int> (x + i, y + height - i - 1, width - i * 2, 1), false);
  66642. context->setFill (bottomRightColour.withMultipliedAlpha (op * 0.75f));
  66643. context->fillRect (Rectangle<int> (x + width - i - 1, y + i + 1, 1, height - i * 2 - 2), false);
  66644. }
  66645. context->restoreState();
  66646. }
  66647. }
  66648. void Graphics::fillEllipse (const float x, const float y, const float width, const float height) const
  66649. {
  66650. // passing in a silly number can cause maths problems in rendering!
  66651. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66652. Path p;
  66653. p.addEllipse (x, y, width, height);
  66654. fillPath (p);
  66655. }
  66656. void Graphics::drawEllipse (const float x, const float y, const float width, const float height,
  66657. const float lineThickness) const
  66658. {
  66659. // passing in a silly number can cause maths problems in rendering!
  66660. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66661. Path p;
  66662. p.addEllipse (x, y, width, height);
  66663. strokePath (p, PathStrokeType (lineThickness));
  66664. }
  66665. void Graphics::fillRoundedRectangle (const float x, const float y, const float width, const float height, const float cornerSize) const
  66666. {
  66667. // passing in a silly number can cause maths problems in rendering!
  66668. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66669. Path p;
  66670. p.addRoundedRectangle (x, y, width, height, cornerSize);
  66671. fillPath (p);
  66672. }
  66673. void Graphics::fillRoundedRectangle (const Rectangle<float>& r, const float cornerSize) const
  66674. {
  66675. fillRoundedRectangle (r.getX(), r.getY(), r.getWidth(), r.getHeight(), cornerSize);
  66676. }
  66677. void Graphics::drawRoundedRectangle (const float x, const float y, const float width, const float height,
  66678. const float cornerSize, const float lineThickness) const
  66679. {
  66680. // passing in a silly number can cause maths problems in rendering!
  66681. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66682. Path p;
  66683. p.addRoundedRectangle (x, y, width, height, cornerSize);
  66684. strokePath (p, PathStrokeType (lineThickness));
  66685. }
  66686. void Graphics::drawRoundedRectangle (const Rectangle<float>& r, const float cornerSize, const float lineThickness) const
  66687. {
  66688. drawRoundedRectangle (r.getX(), r.getY(), r.getWidth(), r.getHeight(), cornerSize, lineThickness);
  66689. }
  66690. void Graphics::drawArrow (const Line<float>& line, const float lineThickness, const float arrowheadWidth, const float arrowheadLength) const
  66691. {
  66692. Path p;
  66693. p.addArrow (line, lineThickness, arrowheadWidth, arrowheadLength);
  66694. fillPath (p);
  66695. }
  66696. void Graphics::fillCheckerBoard (const Rectangle<int>& area,
  66697. const int checkWidth, const int checkHeight,
  66698. const Colour& colour1, const Colour& colour2) const
  66699. {
  66700. jassert (checkWidth > 0 && checkHeight > 0); // can't be zero or less!
  66701. if (checkWidth > 0 && checkHeight > 0)
  66702. {
  66703. context->saveState();
  66704. if (colour1 == colour2)
  66705. {
  66706. context->setFill (colour1);
  66707. context->fillRect (area, false);
  66708. }
  66709. else
  66710. {
  66711. const Rectangle<int> clipped (context->getClipBounds().getIntersection (area));
  66712. if (! clipped.isEmpty())
  66713. {
  66714. context->clipToRectangle (clipped);
  66715. const int checkNumX = (clipped.getX() - area.getX()) / checkWidth;
  66716. const int checkNumY = (clipped.getY() - area.getY()) / checkHeight;
  66717. const int startX = area.getX() + checkNumX * checkWidth;
  66718. const int startY = area.getY() + checkNumY * checkHeight;
  66719. const int right = clipped.getRight();
  66720. const int bottom = clipped.getBottom();
  66721. for (int i = 0; i < 2; ++i)
  66722. {
  66723. context->setFill (i == ((checkNumX ^ checkNumY) & 1) ? colour1 : colour2);
  66724. int cy = i;
  66725. for (int y = startY; y < bottom; y += checkHeight)
  66726. for (int x = startX + (cy++ & 1) * checkWidth; x < right; x += checkWidth * 2)
  66727. context->fillRect (Rectangle<int> (x, y, checkWidth, checkHeight), false);
  66728. }
  66729. }
  66730. }
  66731. context->restoreState();
  66732. }
  66733. }
  66734. void Graphics::drawVerticalLine (const int x, float top, float bottom) const
  66735. {
  66736. context->drawVerticalLine (x, top, bottom);
  66737. }
  66738. void Graphics::drawHorizontalLine (const int y, float left, float right) const
  66739. {
  66740. context->drawHorizontalLine (y, left, right);
  66741. }
  66742. void Graphics::drawLine (float x1, float y1, float x2, float y2) const
  66743. {
  66744. context->drawLine (Line<float> (x1, y1, x2, y2));
  66745. }
  66746. void Graphics::drawLine (const float startX, const float startY,
  66747. const float endX, const float endY,
  66748. const float lineThickness) const
  66749. {
  66750. drawLine (Line<float> (startX, startY, endX, endY),lineThickness);
  66751. }
  66752. void Graphics::drawLine (const Line<float>& line) const
  66753. {
  66754. drawLine (line.getStartX(), line.getStartY(), line.getEndX(), line.getEndY());
  66755. }
  66756. void Graphics::drawLine (const Line<float>& line, const float lineThickness) const
  66757. {
  66758. Path p;
  66759. p.addLineSegment (line, lineThickness);
  66760. fillPath (p);
  66761. }
  66762. void Graphics::drawDashedLine (const float startX, const float startY,
  66763. const float endX, const float endY,
  66764. const float* const dashLengths,
  66765. const int numDashLengths,
  66766. const float lineThickness) const
  66767. {
  66768. const double dx = endX - startX;
  66769. const double dy = endY - startY;
  66770. const double totalLen = juce_hypot (dx, dy);
  66771. if (totalLen >= 0.5)
  66772. {
  66773. const double onePixAlpha = 1.0 / totalLen;
  66774. double alpha = 0.0;
  66775. float x = startX;
  66776. float y = startY;
  66777. int n = 0;
  66778. while (alpha < 1.0f)
  66779. {
  66780. alpha = jmin (1.0, alpha + dashLengths[n++] * onePixAlpha);
  66781. n = n % numDashLengths;
  66782. const float oldX = x;
  66783. const float oldY = y;
  66784. x = (float) (startX + dx * alpha);
  66785. y = (float) (startY + dy * alpha);
  66786. if ((n & 1) != 0)
  66787. {
  66788. if (lineThickness != 1.0f)
  66789. drawLine (oldX, oldY, x, y, lineThickness);
  66790. else
  66791. drawLine (oldX, oldY, x, y);
  66792. }
  66793. }
  66794. }
  66795. }
  66796. void Graphics::setImageResamplingQuality (const Graphics::ResamplingQuality newQuality)
  66797. {
  66798. saveStateIfPending();
  66799. context->setInterpolationQuality (newQuality);
  66800. }
  66801. void Graphics::drawImageAt (const Image& imageToDraw,
  66802. const int topLeftX, const int topLeftY,
  66803. const bool fillAlphaChannelWithCurrentBrush) const
  66804. {
  66805. const int imageW = imageToDraw.getWidth();
  66806. const int imageH = imageToDraw.getHeight();
  66807. drawImage (imageToDraw,
  66808. topLeftX, topLeftY, imageW, imageH,
  66809. 0, 0, imageW, imageH,
  66810. fillAlphaChannelWithCurrentBrush);
  66811. }
  66812. void Graphics::drawImageWithin (const Image& imageToDraw,
  66813. const int destX, const int destY,
  66814. const int destW, const int destH,
  66815. const RectanglePlacement& placementWithinTarget,
  66816. const bool fillAlphaChannelWithCurrentBrush) const
  66817. {
  66818. // passing in a silly number can cause maths problems in rendering!
  66819. jassert (areCoordsSensibleNumbers (destX, destY, destW, destH));
  66820. if (imageToDraw.isValid())
  66821. {
  66822. const int imageW = imageToDraw.getWidth();
  66823. const int imageH = imageToDraw.getHeight();
  66824. if (imageW > 0 && imageH > 0)
  66825. {
  66826. double newX = 0.0, newY = 0.0;
  66827. double newW = imageW;
  66828. double newH = imageH;
  66829. placementWithinTarget.applyTo (newX, newY, newW, newH,
  66830. destX, destY, destW, destH);
  66831. if (newW > 0 && newH > 0)
  66832. {
  66833. drawImage (imageToDraw,
  66834. roundToInt (newX), roundToInt (newY),
  66835. roundToInt (newW), roundToInt (newH),
  66836. 0, 0, imageW, imageH,
  66837. fillAlphaChannelWithCurrentBrush);
  66838. }
  66839. }
  66840. }
  66841. }
  66842. void Graphics::drawImage (const Image& imageToDraw,
  66843. int dx, int dy, int dw, int dh,
  66844. int sx, int sy, int sw, int sh,
  66845. const bool fillAlphaChannelWithCurrentBrush) const
  66846. {
  66847. // passing in a silly number can cause maths problems in rendering!
  66848. jassert (areCoordsSensibleNumbers (dx, dy, dw, dh));
  66849. jassert (areCoordsSensibleNumbers (sx, sy, sw, sh));
  66850. if (imageToDraw.isValid() && context->clipRegionIntersects (Rectangle<int> (dx, dy, dw, dh)))
  66851. {
  66852. drawImageTransformed (imageToDraw.getClippedImage (Rectangle<int> (sx, sy, sw, sh)),
  66853. AffineTransform::scale (dw / (float) sw, dh / (float) sh)
  66854. .translated ((float) dx, (float) dy),
  66855. fillAlphaChannelWithCurrentBrush);
  66856. }
  66857. }
  66858. void Graphics::drawImageTransformed (const Image& imageToDraw,
  66859. const AffineTransform& transform,
  66860. const bool fillAlphaChannelWithCurrentBrush) const
  66861. {
  66862. if (imageToDraw.isValid() && ! context->isClipEmpty())
  66863. {
  66864. if (fillAlphaChannelWithCurrentBrush)
  66865. {
  66866. context->saveState();
  66867. context->clipToImageAlpha (imageToDraw, transform);
  66868. fillAll();
  66869. context->restoreState();
  66870. }
  66871. else
  66872. {
  66873. context->drawImage (imageToDraw, transform, false);
  66874. }
  66875. }
  66876. }
  66877. END_JUCE_NAMESPACE
  66878. /*** End of inlined file: juce_Graphics.cpp ***/
  66879. /*** Start of inlined file: juce_Justification.cpp ***/
  66880. BEGIN_JUCE_NAMESPACE
  66881. Justification::Justification (const Justification& other) throw()
  66882. : flags (other.flags)
  66883. {
  66884. }
  66885. Justification& Justification::operator= (const Justification& other) throw()
  66886. {
  66887. flags = other.flags;
  66888. return *this;
  66889. }
  66890. int Justification::getOnlyVerticalFlags() const throw()
  66891. {
  66892. return flags & (top | bottom | verticallyCentred);
  66893. }
  66894. int Justification::getOnlyHorizontalFlags() const throw()
  66895. {
  66896. return flags & (left | right | horizontallyCentred | horizontallyJustified);
  66897. }
  66898. void Justification::applyToRectangle (int& x, int& y,
  66899. const int w, const int h,
  66900. const int spaceX, const int spaceY,
  66901. const int spaceW, const int spaceH) const throw()
  66902. {
  66903. if ((flags & horizontallyCentred) != 0)
  66904. x = spaceX + ((spaceW - w) >> 1);
  66905. else if ((flags & right) != 0)
  66906. x = spaceX + spaceW - w;
  66907. else
  66908. x = spaceX;
  66909. if ((flags & verticallyCentred) != 0)
  66910. y = spaceY + ((spaceH - h) >> 1);
  66911. else if ((flags & bottom) != 0)
  66912. y = spaceY + spaceH - h;
  66913. else
  66914. y = spaceY;
  66915. }
  66916. END_JUCE_NAMESPACE
  66917. /*** End of inlined file: juce_Justification.cpp ***/
  66918. /*** Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp ***/
  66919. BEGIN_JUCE_NAMESPACE
  66920. // this will throw an assertion if you try to draw something that's not
  66921. // possible in postscript
  66922. #define WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS 0
  66923. #if JUCE_DEBUG && WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS
  66924. #define notPossibleInPostscriptAssert jassertfalse
  66925. #else
  66926. #define notPossibleInPostscriptAssert
  66927. #endif
  66928. LowLevelGraphicsPostScriptRenderer::LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  66929. const String& documentTitle,
  66930. const int totalWidth_,
  66931. const int totalHeight_)
  66932. : out (resultingPostScript),
  66933. totalWidth (totalWidth_),
  66934. totalHeight (totalHeight_),
  66935. needToClip (true)
  66936. {
  66937. stateStack.add (new SavedState());
  66938. stateStack.getLast()->clip = Rectangle<int> (totalWidth_, totalHeight_);
  66939. const float scale = jmin ((520.0f / totalWidth_), (750.0f / totalHeight));
  66940. out << "%!PS-Adobe-3.0 EPSF-3.0"
  66941. "\n%%BoundingBox: 0 0 600 824"
  66942. "\n%%Pages: 0"
  66943. "\n%%Creator: Raw Material Software JUCE"
  66944. "\n%%Title: " << documentTitle <<
  66945. "\n%%CreationDate: none"
  66946. "\n%%LanguageLevel: 2"
  66947. "\n%%EndComments"
  66948. "\n%%BeginProlog"
  66949. "\n%%BeginResource: JRes"
  66950. "\n/bd {bind def} bind def"
  66951. "\n/c {setrgbcolor} bd"
  66952. "\n/m {moveto} bd"
  66953. "\n/l {lineto} bd"
  66954. "\n/rl {rlineto} bd"
  66955. "\n/ct {curveto} bd"
  66956. "\n/cp {closepath} bd"
  66957. "\n/pr {3 index 3 index moveto 1 index 0 rlineto 0 1 index rlineto pop neg 0 rlineto pop pop closepath} bd"
  66958. "\n/doclip {initclip newpath} bd"
  66959. "\n/endclip {clip newpath} bd"
  66960. "\n%%EndResource"
  66961. "\n%%EndProlog"
  66962. "\n%%BeginSetup"
  66963. "\n%%EndSetup"
  66964. "\n%%Page: 1 1"
  66965. "\n%%BeginPageSetup"
  66966. "\n%%EndPageSetup\n\n"
  66967. << "40 800 translate\n"
  66968. << scale << ' ' << scale << " scale\n\n";
  66969. }
  66970. LowLevelGraphicsPostScriptRenderer::~LowLevelGraphicsPostScriptRenderer()
  66971. {
  66972. }
  66973. bool LowLevelGraphicsPostScriptRenderer::isVectorDevice() const
  66974. {
  66975. return true;
  66976. }
  66977. void LowLevelGraphicsPostScriptRenderer::setOrigin (int x, int y)
  66978. {
  66979. if (x != 0 || y != 0)
  66980. {
  66981. stateStack.getLast()->xOffset += x;
  66982. stateStack.getLast()->yOffset += y;
  66983. needToClip = true;
  66984. }
  66985. }
  66986. bool LowLevelGraphicsPostScriptRenderer::clipToRectangle (const Rectangle<int>& r)
  66987. {
  66988. needToClip = true;
  66989. return stateStack.getLast()->clip.clipTo (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  66990. }
  66991. bool LowLevelGraphicsPostScriptRenderer::clipToRectangleList (const RectangleList& clipRegion)
  66992. {
  66993. needToClip = true;
  66994. return stateStack.getLast()->clip.clipTo (clipRegion);
  66995. }
  66996. void LowLevelGraphicsPostScriptRenderer::excludeClipRectangle (const Rectangle<int>& r)
  66997. {
  66998. needToClip = true;
  66999. stateStack.getLast()->clip.subtract (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  67000. }
  67001. void LowLevelGraphicsPostScriptRenderer::clipToPath (const Path& path, const AffineTransform& transform)
  67002. {
  67003. writeClip();
  67004. Path p (path);
  67005. p.applyTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset));
  67006. writePath (p);
  67007. out << "clip\n";
  67008. }
  67009. void LowLevelGraphicsPostScriptRenderer::clipToImageAlpha (const Image& /*sourceImage*/, const AffineTransform& /*transform*/)
  67010. {
  67011. needToClip = true;
  67012. jassertfalse; // xxx
  67013. }
  67014. bool LowLevelGraphicsPostScriptRenderer::clipRegionIntersects (const Rectangle<int>& r)
  67015. {
  67016. return stateStack.getLast()->clip.intersectsRectangle (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  67017. }
  67018. const Rectangle<int> LowLevelGraphicsPostScriptRenderer::getClipBounds() const
  67019. {
  67020. return stateStack.getLast()->clip.getBounds().translated (-stateStack.getLast()->xOffset,
  67021. -stateStack.getLast()->yOffset);
  67022. }
  67023. bool LowLevelGraphicsPostScriptRenderer::isClipEmpty() const
  67024. {
  67025. return stateStack.getLast()->clip.isEmpty();
  67026. }
  67027. LowLevelGraphicsPostScriptRenderer::SavedState::SavedState()
  67028. : xOffset (0),
  67029. yOffset (0)
  67030. {
  67031. }
  67032. LowLevelGraphicsPostScriptRenderer::SavedState::~SavedState()
  67033. {
  67034. }
  67035. void LowLevelGraphicsPostScriptRenderer::saveState()
  67036. {
  67037. stateStack.add (new SavedState (*stateStack.getLast()));
  67038. }
  67039. void LowLevelGraphicsPostScriptRenderer::restoreState()
  67040. {
  67041. jassert (stateStack.size() > 0);
  67042. if (stateStack.size() > 0)
  67043. stateStack.removeLast();
  67044. }
  67045. void LowLevelGraphicsPostScriptRenderer::writeClip()
  67046. {
  67047. if (needToClip)
  67048. {
  67049. needToClip = false;
  67050. out << "doclip ";
  67051. int itemsOnLine = 0;
  67052. for (RectangleList::Iterator i (stateStack.getLast()->clip); i.next();)
  67053. {
  67054. if (++itemsOnLine == 6)
  67055. {
  67056. itemsOnLine = 0;
  67057. out << '\n';
  67058. }
  67059. const Rectangle<int>& r = *i.getRectangle();
  67060. out << r.getX() << ' ' << -r.getY() << ' '
  67061. << r.getWidth() << ' ' << -r.getHeight() << " pr ";
  67062. }
  67063. out << "endclip\n";
  67064. }
  67065. }
  67066. void LowLevelGraphicsPostScriptRenderer::writeColour (const Colour& colour)
  67067. {
  67068. Colour c (Colours::white.overlaidWith (colour));
  67069. if (lastColour != c)
  67070. {
  67071. lastColour = c;
  67072. out << String (c.getFloatRed(), 3) << ' '
  67073. << String (c.getFloatGreen(), 3) << ' '
  67074. << String (c.getFloatBlue(), 3) << " c\n";
  67075. }
  67076. }
  67077. void LowLevelGraphicsPostScriptRenderer::writeXY (const float x, const float y) const
  67078. {
  67079. out << String (x, 2) << ' '
  67080. << String (-y, 2) << ' ';
  67081. }
  67082. void LowLevelGraphicsPostScriptRenderer::writePath (const Path& path) const
  67083. {
  67084. out << "newpath ";
  67085. float lastX = 0.0f;
  67086. float lastY = 0.0f;
  67087. int itemsOnLine = 0;
  67088. Path::Iterator i (path);
  67089. while (i.next())
  67090. {
  67091. if (++itemsOnLine == 4)
  67092. {
  67093. itemsOnLine = 0;
  67094. out << '\n';
  67095. }
  67096. switch (i.elementType)
  67097. {
  67098. case Path::Iterator::startNewSubPath:
  67099. writeXY (i.x1, i.y1);
  67100. lastX = i.x1;
  67101. lastY = i.y1;
  67102. out << "m ";
  67103. break;
  67104. case Path::Iterator::lineTo:
  67105. writeXY (i.x1, i.y1);
  67106. lastX = i.x1;
  67107. lastY = i.y1;
  67108. out << "l ";
  67109. break;
  67110. case Path::Iterator::quadraticTo:
  67111. {
  67112. const float cp1x = lastX + (i.x1 - lastX) * 2.0f / 3.0f;
  67113. const float cp1y = lastY + (i.y1 - lastY) * 2.0f / 3.0f;
  67114. const float cp2x = cp1x + (i.x2 - lastX) / 3.0f;
  67115. const float cp2y = cp1y + (i.y2 - lastY) / 3.0f;
  67116. writeXY (cp1x, cp1y);
  67117. writeXY (cp2x, cp2y);
  67118. writeXY (i.x2, i.y2);
  67119. out << "ct ";
  67120. lastX = i.x2;
  67121. lastY = i.y2;
  67122. }
  67123. break;
  67124. case Path::Iterator::cubicTo:
  67125. writeXY (i.x1, i.y1);
  67126. writeXY (i.x2, i.y2);
  67127. writeXY (i.x3, i.y3);
  67128. out << "ct ";
  67129. lastX = i.x3;
  67130. lastY = i.y3;
  67131. break;
  67132. case Path::Iterator::closePath:
  67133. out << "cp ";
  67134. break;
  67135. default:
  67136. jassertfalse;
  67137. break;
  67138. }
  67139. }
  67140. out << '\n';
  67141. }
  67142. void LowLevelGraphicsPostScriptRenderer::writeTransform (const AffineTransform& trans) const
  67143. {
  67144. out << "[ "
  67145. << trans.mat00 << ' '
  67146. << trans.mat10 << ' '
  67147. << trans.mat01 << ' '
  67148. << trans.mat11 << ' '
  67149. << trans.mat02 << ' '
  67150. << trans.mat12 << " ] concat ";
  67151. }
  67152. void LowLevelGraphicsPostScriptRenderer::setFill (const FillType& fillType)
  67153. {
  67154. stateStack.getLast()->fillType = fillType;
  67155. }
  67156. void LowLevelGraphicsPostScriptRenderer::setOpacity (float /*opacity*/)
  67157. {
  67158. }
  67159. void LowLevelGraphicsPostScriptRenderer::setInterpolationQuality (Graphics::ResamplingQuality /*quality*/)
  67160. {
  67161. }
  67162. void LowLevelGraphicsPostScriptRenderer::fillRect (const Rectangle<int>& r, const bool /*replaceExistingContents*/)
  67163. {
  67164. if (stateStack.getLast()->fillType.isColour())
  67165. {
  67166. writeClip();
  67167. writeColour (stateStack.getLast()->fillType.colour);
  67168. Rectangle<int> r2 (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  67169. out << r2.getX() << ' ' << -r2.getBottom() << ' ' << r2.getWidth() << ' ' << r2.getHeight() << " rectfill\n";
  67170. }
  67171. else
  67172. {
  67173. Path p;
  67174. p.addRectangle (r);
  67175. fillPath (p, AffineTransform::identity);
  67176. }
  67177. }
  67178. void LowLevelGraphicsPostScriptRenderer::fillPath (const Path& path, const AffineTransform& t)
  67179. {
  67180. if (stateStack.getLast()->fillType.isColour())
  67181. {
  67182. writeClip();
  67183. Path p (path);
  67184. p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset,
  67185. (float) stateStack.getLast()->yOffset));
  67186. writePath (p);
  67187. writeColour (stateStack.getLast()->fillType.colour);
  67188. out << "fill\n";
  67189. }
  67190. else if (stateStack.getLast()->fillType.isGradient())
  67191. {
  67192. // this doesn't work correctly yet - it could be improved to handle solid gradients, but
  67193. // postscript can't do semi-transparent ones.
  67194. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  67195. writeClip();
  67196. out << "gsave ";
  67197. {
  67198. Path p (path);
  67199. p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset));
  67200. writePath (p);
  67201. out << "clip\n";
  67202. }
  67203. const Rectangle<int> bounds (stateStack.getLast()->clip.getBounds());
  67204. // ideally this would draw lots of lines or ellipses to approximate the gradient, but for the
  67205. // time-being, this just fills it with the average colour..
  67206. writeColour (stateStack.getLast()->fillType.gradient->getColourAtPosition (0.5f));
  67207. out << bounds.getX() << ' ' << -bounds.getBottom() << ' ' << bounds.getWidth() << ' ' << bounds.getHeight() << " rectfill\n";
  67208. out << "grestore\n";
  67209. }
  67210. }
  67211. void LowLevelGraphicsPostScriptRenderer::writeImage (const Image& im,
  67212. const int sx, const int sy,
  67213. const int maxW, const int maxH) const
  67214. {
  67215. out << "{<\n";
  67216. const int w = jmin (maxW, im.getWidth());
  67217. const int h = jmin (maxH, im.getHeight());
  67218. int charsOnLine = 0;
  67219. const Image::BitmapData srcData (im, 0, 0, w, h);
  67220. Colour pixel;
  67221. for (int y = h; --y >= 0;)
  67222. {
  67223. for (int x = 0; x < w; ++x)
  67224. {
  67225. const uint8* pixelData = srcData.getPixelPointer (x, y);
  67226. if (x >= sx && y >= sy)
  67227. {
  67228. if (im.isARGB())
  67229. {
  67230. PixelARGB p (*(const PixelARGB*) pixelData);
  67231. p.unpremultiply();
  67232. pixel = Colours::white.overlaidWith (Colour (p.getARGB()));
  67233. }
  67234. else if (im.isRGB())
  67235. {
  67236. pixel = Colour (((const PixelRGB*) pixelData)->getARGB());
  67237. }
  67238. else
  67239. {
  67240. pixel = Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixelData);
  67241. }
  67242. }
  67243. else
  67244. {
  67245. pixel = Colours::transparentWhite;
  67246. }
  67247. const uint8 pixelValues[3] = { pixel.getRed(), pixel.getGreen(), pixel.getBlue() };
  67248. out << String::toHexString (pixelValues, 3, 0);
  67249. charsOnLine += 3;
  67250. if (charsOnLine > 100)
  67251. {
  67252. out << '\n';
  67253. charsOnLine = 0;
  67254. }
  67255. }
  67256. }
  67257. out << "\n>}\n";
  67258. }
  67259. void LowLevelGraphicsPostScriptRenderer::drawImage (const Image& sourceImage, const AffineTransform& transform, const bool /*fillEntireClipAsTiles*/)
  67260. {
  67261. const int w = sourceImage.getWidth();
  67262. const int h = sourceImage.getHeight();
  67263. writeClip();
  67264. out << "gsave ";
  67265. writeTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset)
  67266. .scaled (1.0f, -1.0f));
  67267. RectangleList imageClip;
  67268. sourceImage.createSolidAreaMask (imageClip, 0.5f);
  67269. out << "newpath ";
  67270. int itemsOnLine = 0;
  67271. for (RectangleList::Iterator i (imageClip); i.next();)
  67272. {
  67273. if (++itemsOnLine == 6)
  67274. {
  67275. out << '\n';
  67276. itemsOnLine = 0;
  67277. }
  67278. const Rectangle<int>& r = *i.getRectangle();
  67279. out << r.getX() << ' ' << r.getY() << ' ' << r.getWidth() << ' ' << r.getHeight() << " pr ";
  67280. }
  67281. out << " clip newpath\n";
  67282. out << w << ' ' << h << " scale\n";
  67283. out << w << ' ' << h << " 8 [" << w << " 0 0 -" << h << ' ' << (int) 0 << ' ' << h << " ]\n";
  67284. writeImage (sourceImage, 0, 0, w, h);
  67285. out << "false 3 colorimage grestore\n";
  67286. needToClip = true;
  67287. }
  67288. void LowLevelGraphicsPostScriptRenderer::drawLine (const Line <float>& line)
  67289. {
  67290. Path p;
  67291. p.addLineSegment (line, 1.0f);
  67292. fillPath (p, AffineTransform::identity);
  67293. }
  67294. void LowLevelGraphicsPostScriptRenderer::drawVerticalLine (const int x, float top, float bottom)
  67295. {
  67296. drawLine (Line<float> ((float) x, top, (float) x, bottom));
  67297. }
  67298. void LowLevelGraphicsPostScriptRenderer::drawHorizontalLine (const int y, float left, float right)
  67299. {
  67300. drawLine (Line<float> (left, (float) y, right, (float) y));
  67301. }
  67302. void LowLevelGraphicsPostScriptRenderer::setFont (const Font& newFont)
  67303. {
  67304. stateStack.getLast()->font = newFont;
  67305. }
  67306. const Font LowLevelGraphicsPostScriptRenderer::getFont()
  67307. {
  67308. return stateStack.getLast()->font;
  67309. }
  67310. void LowLevelGraphicsPostScriptRenderer::drawGlyph (int glyphNumber, const AffineTransform& transform)
  67311. {
  67312. Path p;
  67313. Font& font = stateStack.getLast()->font;
  67314. font.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  67315. fillPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight()).followedBy (transform));
  67316. }
  67317. END_JUCE_NAMESPACE
  67318. /*** End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp ***/
  67319. /*** Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp ***/
  67320. BEGIN_JUCE_NAMESPACE
  67321. #if (JUCE_WINDOWS || JUCE_LINUX) && ! JUCE_64BIT
  67322. #define JUCE_USE_SSE_INSTRUCTIONS 1
  67323. #endif
  67324. #if JUCE_MSVC
  67325. #pragma warning (push)
  67326. #pragma warning (disable: 4127) // "expression is constant" warning
  67327. #if JUCE_DEBUG
  67328. #pragma optimize ("t", on) // optimise just this file, to avoid sluggish graphics when debugging
  67329. #pragma warning (disable: 4714) // warning about forcedinline methods not being inlined
  67330. #endif
  67331. #endif
  67332. namespace SoftwareRendererClasses
  67333. {
  67334. template <class PixelType, bool replaceExisting = false>
  67335. class SolidColourEdgeTableRenderer
  67336. {
  67337. public:
  67338. SolidColourEdgeTableRenderer (const Image::BitmapData& data_, const PixelARGB& colour)
  67339. : data (data_),
  67340. sourceColour (colour)
  67341. {
  67342. if (sizeof (PixelType) == 3)
  67343. {
  67344. areRGBComponentsEqual = sourceColour.getRed() == sourceColour.getGreen()
  67345. && sourceColour.getGreen() == sourceColour.getBlue();
  67346. filler[0].set (sourceColour);
  67347. filler[1].set (sourceColour);
  67348. filler[2].set (sourceColour);
  67349. filler[3].set (sourceColour);
  67350. }
  67351. }
  67352. forcedinline void setEdgeTableYPos (const int y) throw()
  67353. {
  67354. linePixels = (PixelType*) data.getLinePointer (y);
  67355. }
  67356. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  67357. {
  67358. if (replaceExisting)
  67359. linePixels[x].set (sourceColour);
  67360. else
  67361. linePixels[x].blend (sourceColour, alphaLevel);
  67362. }
  67363. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67364. {
  67365. if (replaceExisting)
  67366. linePixels[x].set (sourceColour);
  67367. else
  67368. linePixels[x].blend (sourceColour);
  67369. }
  67370. forcedinline void handleEdgeTableLine (const int x, const int width, const int alphaLevel) const throw()
  67371. {
  67372. PixelARGB p (sourceColour);
  67373. p.multiplyAlpha (alphaLevel);
  67374. PixelType* dest = linePixels + x;
  67375. if (replaceExisting || p.getAlpha() >= 0xff)
  67376. replaceLine (dest, p, width);
  67377. else
  67378. blendLine (dest, p, width);
  67379. }
  67380. forcedinline void handleEdgeTableLineFull (const int x, const int width) const throw()
  67381. {
  67382. PixelType* dest = linePixels + x;
  67383. if (replaceExisting || sourceColour.getAlpha() >= 0xff)
  67384. replaceLine (dest, sourceColour, width);
  67385. else
  67386. blendLine (dest, sourceColour, width);
  67387. }
  67388. private:
  67389. const Image::BitmapData& data;
  67390. PixelType* linePixels;
  67391. PixelARGB sourceColour;
  67392. PixelRGB filler [4];
  67393. bool areRGBComponentsEqual;
  67394. inline void blendLine (PixelType* dest, const PixelARGB& colour, int width) const throw()
  67395. {
  67396. do
  67397. {
  67398. dest->blend (colour);
  67399. ++dest;
  67400. } while (--width > 0);
  67401. }
  67402. forcedinline void replaceLine (PixelRGB* dest, const PixelARGB& colour, int width) const throw()
  67403. {
  67404. if (areRGBComponentsEqual) // if all the component values are the same, we can cheat..
  67405. {
  67406. memset (dest, colour.getRed(), width * 3);
  67407. }
  67408. else
  67409. {
  67410. if (width >> 5)
  67411. {
  67412. const int* const intFiller = reinterpret_cast<const int*> (filler);
  67413. while (width > 8 && (((pointer_sized_int) dest) & 7) != 0)
  67414. {
  67415. dest->set (colour);
  67416. ++dest;
  67417. --width;
  67418. }
  67419. while (width > 4)
  67420. {
  67421. int* d = reinterpret_cast<int*> (dest);
  67422. *d++ = intFiller[0];
  67423. *d++ = intFiller[1];
  67424. *d++ = intFiller[2];
  67425. dest = reinterpret_cast<PixelRGB*> (d);
  67426. width -= 4;
  67427. }
  67428. }
  67429. while (--width >= 0)
  67430. {
  67431. dest->set (colour);
  67432. ++dest;
  67433. }
  67434. }
  67435. }
  67436. forcedinline void replaceLine (PixelAlpha* const dest, const PixelARGB& colour, int const width) const throw()
  67437. {
  67438. memset (dest, colour.getAlpha(), width);
  67439. }
  67440. forcedinline void replaceLine (PixelARGB* dest, const PixelARGB& colour, int width) const throw()
  67441. {
  67442. do
  67443. {
  67444. dest->set (colour);
  67445. ++dest;
  67446. } while (--width > 0);
  67447. }
  67448. SolidColourEdgeTableRenderer (const SolidColourEdgeTableRenderer&);
  67449. SolidColourEdgeTableRenderer& operator= (const SolidColourEdgeTableRenderer&);
  67450. };
  67451. class LinearGradientPixelGenerator
  67452. {
  67453. public:
  67454. LinearGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform& transform, const PixelARGB* const lookupTable_, const int numEntries_)
  67455. : lookupTable (lookupTable_), numEntries (numEntries_)
  67456. {
  67457. jassert (numEntries_ >= 0);
  67458. Point<float> p1 (gradient.point1);
  67459. Point<float> p2 (gradient.point2);
  67460. if (! transform.isIdentity())
  67461. {
  67462. const Line<float> l (p2, p1);
  67463. Point<float> p3 = l.getPointAlongLine (0.0f, 100.0f);
  67464. p1.applyTransform (transform);
  67465. p2.applyTransform (transform);
  67466. p3.applyTransform (transform);
  67467. p2 = Line<float> (p2, p3).findNearestPointTo (p1);
  67468. }
  67469. vertical = std::abs (p1.getX() - p2.getX()) < 0.001f;
  67470. horizontal = std::abs (p1.getY() - p2.getY()) < 0.001f;
  67471. if (vertical)
  67472. {
  67473. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.getY() - p1.getY()));
  67474. start = roundToInt (p1.getY() * scale);
  67475. }
  67476. else if (horizontal)
  67477. {
  67478. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.getX() - p1.getX()));
  67479. start = roundToInt (p1.getX() * scale);
  67480. }
  67481. else
  67482. {
  67483. grad = (p2.getY() - p1.getY()) / (double) (p1.getX() - p2.getX());
  67484. yTerm = p1.getY() - p1.getX() / grad;
  67485. scale = roundToInt ((numEntries << (int) numScaleBits) / (yTerm * grad - (p2.getY() * grad - p2.getX())));
  67486. grad *= scale;
  67487. }
  67488. }
  67489. forcedinline void setY (const int y) throw()
  67490. {
  67491. if (vertical)
  67492. linePix = lookupTable [jlimit (0, numEntries, (y * scale - start) >> (int) numScaleBits)];
  67493. else if (! horizontal)
  67494. start = roundToInt ((y - yTerm) * grad);
  67495. }
  67496. inline const PixelARGB getPixel (const int x) const throw()
  67497. {
  67498. return vertical ? linePix
  67499. : lookupTable [jlimit (0, numEntries, (x * scale - start) >> (int) numScaleBits)];
  67500. }
  67501. private:
  67502. const PixelARGB* const lookupTable;
  67503. const int numEntries;
  67504. PixelARGB linePix;
  67505. int start, scale;
  67506. double grad, yTerm;
  67507. bool vertical, horizontal;
  67508. enum { numScaleBits = 12 };
  67509. LinearGradientPixelGenerator (const LinearGradientPixelGenerator&);
  67510. LinearGradientPixelGenerator& operator= (const LinearGradientPixelGenerator&);
  67511. };
  67512. class RadialGradientPixelGenerator
  67513. {
  67514. public:
  67515. RadialGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform&,
  67516. const PixelARGB* const lookupTable_, const int numEntries_)
  67517. : lookupTable (lookupTable_),
  67518. numEntries (numEntries_),
  67519. gx1 (gradient.point1.getX()),
  67520. gy1 (gradient.point1.getY())
  67521. {
  67522. jassert (numEntries_ >= 0);
  67523. const Point<float> diff (gradient.point1 - gradient.point2);
  67524. maxDist = diff.getX() * diff.getX() + diff.getY() * diff.getY();
  67525. invScale = numEntries / std::sqrt (maxDist);
  67526. jassert (roundToInt (std::sqrt (maxDist) * invScale) <= numEntries);
  67527. }
  67528. forcedinline void setY (const int y) throw()
  67529. {
  67530. dy = y - gy1;
  67531. dy *= dy;
  67532. }
  67533. inline const PixelARGB getPixel (const int px) const throw()
  67534. {
  67535. double x = px - gx1;
  67536. x *= x;
  67537. x += dy;
  67538. return lookupTable [x >= maxDist ? numEntries : roundToInt (std::sqrt (x) * invScale)];
  67539. }
  67540. protected:
  67541. const PixelARGB* const lookupTable;
  67542. const int numEntries;
  67543. const double gx1, gy1;
  67544. double maxDist, invScale, dy;
  67545. RadialGradientPixelGenerator (const RadialGradientPixelGenerator&);
  67546. RadialGradientPixelGenerator& operator= (const RadialGradientPixelGenerator&);
  67547. };
  67548. class TransformedRadialGradientPixelGenerator : public RadialGradientPixelGenerator
  67549. {
  67550. public:
  67551. TransformedRadialGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform& transform,
  67552. const PixelARGB* const lookupTable_, const int numEntries_)
  67553. : RadialGradientPixelGenerator (gradient, transform, lookupTable_, numEntries_),
  67554. inverseTransform (transform.inverted())
  67555. {
  67556. tM10 = inverseTransform.mat10;
  67557. tM00 = inverseTransform.mat00;
  67558. }
  67559. forcedinline void setY (const int y) throw()
  67560. {
  67561. lineYM01 = inverseTransform.mat01 * y + inverseTransform.mat02 - gx1;
  67562. lineYM11 = inverseTransform.mat11 * y + inverseTransform.mat12 - gy1;
  67563. }
  67564. inline const PixelARGB getPixel (const int px) const throw()
  67565. {
  67566. double x = px;
  67567. const double y = tM10 * x + lineYM11;
  67568. x = tM00 * x + lineYM01;
  67569. x *= x;
  67570. x += y * y;
  67571. if (x >= maxDist)
  67572. return lookupTable [numEntries];
  67573. else
  67574. return lookupTable [jmin (numEntries, roundToInt (std::sqrt (x) * invScale))];
  67575. }
  67576. private:
  67577. double tM10, tM00, lineYM01, lineYM11;
  67578. const AffineTransform inverseTransform;
  67579. TransformedRadialGradientPixelGenerator (const TransformedRadialGradientPixelGenerator&);
  67580. TransformedRadialGradientPixelGenerator& operator= (const TransformedRadialGradientPixelGenerator&);
  67581. };
  67582. template <class PixelType, class GradientType>
  67583. class GradientEdgeTableRenderer : public GradientType
  67584. {
  67585. public:
  67586. GradientEdgeTableRenderer (const Image::BitmapData& destData_, const ColourGradient& gradient, const AffineTransform& transform,
  67587. const PixelARGB* const lookupTable_, const int numEntries_)
  67588. : GradientType (gradient, transform, lookupTable_, numEntries_ - 1),
  67589. destData (destData_)
  67590. {
  67591. }
  67592. forcedinline void setEdgeTableYPos (const int y) throw()
  67593. {
  67594. linePixels = (PixelType*) destData.getLinePointer (y);
  67595. GradientType::setY (y);
  67596. }
  67597. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  67598. {
  67599. linePixels[x].blend (GradientType::getPixel (x), alphaLevel);
  67600. }
  67601. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67602. {
  67603. linePixels[x].blend (GradientType::getPixel (x));
  67604. }
  67605. void handleEdgeTableLine (int x, int width, const int alphaLevel) const throw()
  67606. {
  67607. PixelType* dest = linePixels + x;
  67608. if (alphaLevel < 0xff)
  67609. {
  67610. do
  67611. {
  67612. (dest++)->blend (GradientType::getPixel (x++), alphaLevel);
  67613. } while (--width > 0);
  67614. }
  67615. else
  67616. {
  67617. do
  67618. {
  67619. (dest++)->blend (GradientType::getPixel (x++));
  67620. } while (--width > 0);
  67621. }
  67622. }
  67623. void handleEdgeTableLineFull (int x, int width) const throw()
  67624. {
  67625. PixelType* dest = linePixels + x;
  67626. do
  67627. {
  67628. (dest++)->blend (GradientType::getPixel (x++));
  67629. } while (--width > 0);
  67630. }
  67631. private:
  67632. const Image::BitmapData& destData;
  67633. PixelType* linePixels;
  67634. GradientEdgeTableRenderer (const GradientEdgeTableRenderer&);
  67635. GradientEdgeTableRenderer& operator= (const GradientEdgeTableRenderer&);
  67636. };
  67637. namespace
  67638. {
  67639. forcedinline int safeModulo (int n, const int divisor) throw()
  67640. {
  67641. jassert (divisor > 0);
  67642. n %= divisor;
  67643. return (n < 0) ? (n + divisor) : n;
  67644. }
  67645. }
  67646. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  67647. class ImageFillEdgeTableRenderer
  67648. {
  67649. public:
  67650. ImageFillEdgeTableRenderer (const Image::BitmapData& destData_,
  67651. const Image::BitmapData& srcData_,
  67652. const int extraAlpha_,
  67653. const int x, const int y)
  67654. : destData (destData_),
  67655. srcData (srcData_),
  67656. extraAlpha (extraAlpha_ + 1),
  67657. xOffset (repeatPattern ? safeModulo (x, srcData_.width) - srcData_.width : x),
  67658. yOffset (repeatPattern ? safeModulo (y, srcData_.height) - srcData_.height : y)
  67659. {
  67660. }
  67661. forcedinline void setEdgeTableYPos (int y) throw()
  67662. {
  67663. linePixels = (DestPixelType*) destData.getLinePointer (y);
  67664. y -= yOffset;
  67665. if (repeatPattern)
  67666. {
  67667. jassert (y >= 0);
  67668. y %= srcData.height;
  67669. }
  67670. sourceLineStart = (SrcPixelType*) srcData.getLinePointer (y);
  67671. }
  67672. forcedinline void handleEdgeTablePixel (const int x, int alphaLevel) const throw()
  67673. {
  67674. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  67675. linePixels[x].blend (sourceLineStart [repeatPattern ? ((x - xOffset) % srcData.width) : (x - xOffset)], alphaLevel);
  67676. }
  67677. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67678. {
  67679. linePixels[x].blend (sourceLineStart [repeatPattern ? ((x - xOffset) % srcData.width) : (x - xOffset)], extraAlpha);
  67680. }
  67681. void handleEdgeTableLine (int x, int width, int alphaLevel) const throw()
  67682. {
  67683. DestPixelType* dest = linePixels + x;
  67684. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  67685. x -= xOffset;
  67686. jassert (repeatPattern || (x >= 0 && x + width <= srcData.width));
  67687. if (alphaLevel < 0xfe)
  67688. {
  67689. do
  67690. {
  67691. dest++ ->blend (sourceLineStart [repeatPattern ? (x++ % srcData.width) : x++], alphaLevel);
  67692. } while (--width > 0);
  67693. }
  67694. else
  67695. {
  67696. if (repeatPattern)
  67697. {
  67698. do
  67699. {
  67700. dest++ ->blend (sourceLineStart [x++ % srcData.width]);
  67701. } while (--width > 0);
  67702. }
  67703. else
  67704. {
  67705. copyRow (dest, sourceLineStart + x, width);
  67706. }
  67707. }
  67708. }
  67709. void handleEdgeTableLineFull (int x, int width) const throw()
  67710. {
  67711. DestPixelType* dest = linePixels + x;
  67712. x -= xOffset;
  67713. jassert (repeatPattern || (x >= 0 && x + width <= srcData.width));
  67714. if (extraAlpha < 0xfe)
  67715. {
  67716. do
  67717. {
  67718. dest++ ->blend (sourceLineStart [repeatPattern ? (x++ % srcData.width) : x++], extraAlpha);
  67719. } while (--width > 0);
  67720. }
  67721. else
  67722. {
  67723. if (repeatPattern)
  67724. {
  67725. do
  67726. {
  67727. dest++ ->blend (sourceLineStart [x++ % srcData.width]);
  67728. } while (--width > 0);
  67729. }
  67730. else
  67731. {
  67732. copyRow (dest, sourceLineStart + x, width);
  67733. }
  67734. }
  67735. }
  67736. void clipEdgeTableLine (EdgeTable& et, int x, int y, int width)
  67737. {
  67738. jassert (x - xOffset >= 0 && x + width - xOffset <= srcData.width);
  67739. SrcPixelType* s = (SrcPixelType*) srcData.getLinePointer (y - yOffset);
  67740. uint8* mask = (uint8*) (s + x - xOffset);
  67741. if (sizeof (SrcPixelType) == sizeof (PixelARGB))
  67742. mask += PixelARGB::indexA;
  67743. et.clipLineToMask (x, y, mask, sizeof (SrcPixelType), width);
  67744. }
  67745. private:
  67746. const Image::BitmapData& destData;
  67747. const Image::BitmapData& srcData;
  67748. const int extraAlpha, xOffset, yOffset;
  67749. DestPixelType* linePixels;
  67750. SrcPixelType* sourceLineStart;
  67751. template <class PixelType1, class PixelType2>
  67752. forcedinline static void copyRow (PixelType1* dest, PixelType2* src, int width) throw()
  67753. {
  67754. do
  67755. {
  67756. dest++ ->blend (*src++);
  67757. } while (--width > 0);
  67758. }
  67759. forcedinline static void copyRow (PixelRGB* dest, PixelRGB* src, int width) throw()
  67760. {
  67761. memcpy (dest, src, width * sizeof (PixelRGB));
  67762. }
  67763. ImageFillEdgeTableRenderer (const ImageFillEdgeTableRenderer&);
  67764. ImageFillEdgeTableRenderer& operator= (const ImageFillEdgeTableRenderer&);
  67765. };
  67766. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  67767. class TransformedImageFillEdgeTableRenderer
  67768. {
  67769. public:
  67770. TransformedImageFillEdgeTableRenderer (const Image::BitmapData& destData_,
  67771. const Image::BitmapData& srcData_,
  67772. const AffineTransform& transform,
  67773. const int extraAlpha_,
  67774. const bool betterQuality_)
  67775. : interpolator (transform),
  67776. destData (destData_),
  67777. srcData (srcData_),
  67778. extraAlpha (extraAlpha_ + 1),
  67779. betterQuality (betterQuality_),
  67780. pixelOffset (betterQuality_ ? 0.5f : 0.0f),
  67781. pixelOffsetInt (betterQuality_ ? -128 : 0),
  67782. maxX (srcData_.width - 1),
  67783. maxY (srcData_.height - 1),
  67784. scratchSize (2048)
  67785. {
  67786. scratchBuffer.malloc (scratchSize);
  67787. }
  67788. ~TransformedImageFillEdgeTableRenderer()
  67789. {
  67790. }
  67791. forcedinline void setEdgeTableYPos (const int newY) throw()
  67792. {
  67793. y = newY;
  67794. linePixels = (DestPixelType*) destData.getLinePointer (newY);
  67795. }
  67796. forcedinline void handleEdgeTablePixel (const int x, int alphaLevel) throw()
  67797. {
  67798. alphaLevel *= extraAlpha;
  67799. alphaLevel >>= 8;
  67800. SrcPixelType p;
  67801. generate (&p, x, 1);
  67802. linePixels[x].blend (p, alphaLevel);
  67803. }
  67804. forcedinline void handleEdgeTablePixelFull (const int x) throw()
  67805. {
  67806. SrcPixelType p;
  67807. generate (&p, x, 1);
  67808. linePixels[x].blend (p, extraAlpha);
  67809. }
  67810. void handleEdgeTableLine (const int x, int width, int alphaLevel) throw()
  67811. {
  67812. if (width > scratchSize)
  67813. {
  67814. scratchSize = width;
  67815. scratchBuffer.malloc (scratchSize);
  67816. }
  67817. SrcPixelType* span = scratchBuffer;
  67818. generate (span, x, width);
  67819. DestPixelType* dest = linePixels + x;
  67820. alphaLevel *= extraAlpha;
  67821. alphaLevel >>= 8;
  67822. if (alphaLevel < 0xfe)
  67823. {
  67824. do
  67825. {
  67826. dest++ ->blend (*span++, alphaLevel);
  67827. } while (--width > 0);
  67828. }
  67829. else
  67830. {
  67831. do
  67832. {
  67833. dest++ ->blend (*span++);
  67834. } while (--width > 0);
  67835. }
  67836. }
  67837. forcedinline void handleEdgeTableLineFull (const int x, int width) throw()
  67838. {
  67839. handleEdgeTableLine (x, width, 255);
  67840. }
  67841. void clipEdgeTableLine (EdgeTable& et, int x, int y_, int width)
  67842. {
  67843. if (width > scratchSize)
  67844. {
  67845. scratchSize = width;
  67846. scratchBuffer.malloc (scratchSize);
  67847. }
  67848. y = y_;
  67849. generate (scratchBuffer, x, width);
  67850. et.clipLineToMask (x, y_,
  67851. reinterpret_cast<uint8*> (scratchBuffer.getData()) + SrcPixelType::indexA,
  67852. sizeof (SrcPixelType), width);
  67853. }
  67854. private:
  67855. void generate (PixelARGB* dest, const int x, int numPixels) throw()
  67856. {
  67857. this->interpolator.setStartOfLine (x + pixelOffset, y + pixelOffset, numPixels);
  67858. do
  67859. {
  67860. int hiResX, hiResY;
  67861. this->interpolator.next (hiResX, hiResY);
  67862. hiResX += pixelOffsetInt;
  67863. hiResY += pixelOffsetInt;
  67864. int loResX = hiResX >> 8;
  67865. int loResY = hiResY >> 8;
  67866. if (repeatPattern)
  67867. {
  67868. loResX = safeModulo (loResX, srcData.width);
  67869. loResY = safeModulo (loResY, srcData.height);
  67870. }
  67871. if (betterQuality
  67872. && ((unsigned int) loResX) < (unsigned int) maxX
  67873. && ((unsigned int) loResY) < (unsigned int) maxY)
  67874. {
  67875. uint32 c[4] = { 256 * 128, 256 * 128, 256 * 128, 256 * 128 };
  67876. hiResX &= 255;
  67877. hiResY &= 255;
  67878. const uint8* src = this->srcData.getPixelPointer (loResX, loResY);
  67879. uint32 weight = (256 - hiResX) * (256 - hiResY);
  67880. c[0] += weight * src[0];
  67881. c[1] += weight * src[1];
  67882. c[2] += weight * src[2];
  67883. c[3] += weight * src[3];
  67884. weight = hiResX * (256 - hiResY);
  67885. c[0] += weight * src[4];
  67886. c[1] += weight * src[5];
  67887. c[2] += weight * src[6];
  67888. c[3] += weight * src[7];
  67889. src += this->srcData.lineStride;
  67890. weight = (256 - hiResX) * hiResY;
  67891. c[0] += weight * src[0];
  67892. c[1] += weight * src[1];
  67893. c[2] += weight * src[2];
  67894. c[3] += weight * src[3];
  67895. weight = hiResX * hiResY;
  67896. c[0] += weight * src[4];
  67897. c[1] += weight * src[5];
  67898. c[2] += weight * src[6];
  67899. c[3] += weight * src[7];
  67900. dest->setARGB ((uint8) (c[PixelARGB::indexA] >> 16),
  67901. (uint8) (c[PixelARGB::indexR] >> 16),
  67902. (uint8) (c[PixelARGB::indexG] >> 16),
  67903. (uint8) (c[PixelARGB::indexB] >> 16));
  67904. }
  67905. else
  67906. {
  67907. if (! repeatPattern)
  67908. {
  67909. // Beyond the edges, just repeat the edge pixels and leave the anti-aliasing to be handled by the edgetable
  67910. if (loResX < 0) loResX = 0;
  67911. if (loResY < 0) loResY = 0;
  67912. if (loResX > maxX) loResX = maxX;
  67913. if (loResY > maxY) loResY = maxY;
  67914. }
  67915. dest->set (*(const PixelARGB*) this->srcData.getPixelPointer (loResX, loResY));
  67916. }
  67917. ++dest;
  67918. } while (--numPixels > 0);
  67919. }
  67920. void generate (PixelRGB* dest, const int x, int numPixels) throw()
  67921. {
  67922. this->interpolator.setStartOfLine (x + pixelOffset, y + pixelOffset, numPixels);
  67923. do
  67924. {
  67925. int hiResX, hiResY;
  67926. this->interpolator.next (hiResX, hiResY);
  67927. hiResX += pixelOffsetInt;
  67928. hiResY += pixelOffsetInt;
  67929. int loResX = hiResX >> 8;
  67930. int loResY = hiResY >> 8;
  67931. if (repeatPattern)
  67932. {
  67933. loResX = safeModulo (loResX, srcData.width);
  67934. loResY = safeModulo (loResY, srcData.height);
  67935. }
  67936. if (betterQuality
  67937. && ((unsigned int) loResX) < (unsigned int) maxX
  67938. && ((unsigned int) loResY) < (unsigned int) maxY)
  67939. {
  67940. uint32 c[3] = { 256 * 128, 256 * 128, 256 * 128 };
  67941. hiResX &= 255;
  67942. hiResY &= 255;
  67943. const uint8* src = this->srcData.getPixelPointer (loResX, loResY);
  67944. unsigned int weight = (256 - hiResX) * (256 - hiResY);
  67945. c[0] += weight * src[0];
  67946. c[1] += weight * src[1];
  67947. c[2] += weight * src[2];
  67948. weight = hiResX * (256 - hiResY);
  67949. c[0] += weight * src[3];
  67950. c[1] += weight * src[4];
  67951. c[2] += weight * src[5];
  67952. src += this->srcData.lineStride;
  67953. weight = (256 - hiResX) * hiResY;
  67954. c[0] += weight * src[0];
  67955. c[1] += weight * src[1];
  67956. c[2] += weight * src[2];
  67957. weight = hiResX * hiResY;
  67958. c[0] += weight * src[3];
  67959. c[1] += weight * src[4];
  67960. c[2] += weight * src[5];
  67961. dest->setARGB ((uint8) 255,
  67962. (uint8) (c[PixelRGB::indexR] >> 16),
  67963. (uint8) (c[PixelRGB::indexG] >> 16),
  67964. (uint8) (c[PixelRGB::indexB] >> 16));
  67965. }
  67966. else
  67967. {
  67968. if (! repeatPattern)
  67969. {
  67970. // Beyond the edges, just repeat the edge pixels and leave the anti-aliasing to be handled by the edgetable
  67971. if (loResX < 0) loResX = 0;
  67972. if (loResY < 0) loResY = 0;
  67973. if (loResX > maxX) loResX = maxX;
  67974. if (loResY > maxY) loResY = maxY;
  67975. }
  67976. dest->set (*(const PixelRGB*) this->srcData.getPixelPointer (loResX, loResY));
  67977. }
  67978. ++dest;
  67979. } while (--numPixels > 0);
  67980. }
  67981. void generate (PixelAlpha* dest, const int x, int numPixels) throw()
  67982. {
  67983. this->interpolator.setStartOfLine (x + pixelOffset, y + pixelOffset, numPixels);
  67984. do
  67985. {
  67986. int hiResX, hiResY;
  67987. this->interpolator.next (hiResX, hiResY);
  67988. hiResX += pixelOffsetInt;
  67989. hiResY += pixelOffsetInt;
  67990. int loResX = hiResX >> 8;
  67991. int loResY = hiResY >> 8;
  67992. if (repeatPattern)
  67993. {
  67994. loResX = safeModulo (loResX, srcData.width);
  67995. loResY = safeModulo (loResY, srcData.height);
  67996. }
  67997. if (betterQuality
  67998. && ((unsigned int) loResX) < (unsigned int) maxX
  67999. && ((unsigned int) loResY) < (unsigned int) maxY)
  68000. {
  68001. hiResX &= 255;
  68002. hiResY &= 255;
  68003. const uint8* src = this->srcData.getPixelPointer (loResX, loResY);
  68004. uint32 c = 256 * 128;
  68005. c += src[0] * ((256 - hiResX) * (256 - hiResY));
  68006. c += src[1] * (hiResX * (256 - hiResY));
  68007. src += this->srcData.lineStride;
  68008. c += src[0] * ((256 - hiResX) * hiResY);
  68009. c += src[1] * (hiResX * hiResY);
  68010. *((uint8*) dest) = (uint8) c;
  68011. }
  68012. else
  68013. {
  68014. if (! repeatPattern)
  68015. {
  68016. // Beyond the edges, just repeat the edge pixels and leave the anti-aliasing to be handled by the edgetable
  68017. if (loResX < 0) loResX = 0;
  68018. if (loResY < 0) loResY = 0;
  68019. if (loResX > maxX) loResX = maxX;
  68020. if (loResY > maxY) loResY = maxY;
  68021. }
  68022. *((uint8*) dest) = *(this->srcData.getPixelPointer (loResX, loResY));
  68023. }
  68024. ++dest;
  68025. } while (--numPixels > 0);
  68026. }
  68027. class TransformedImageSpanInterpolator
  68028. {
  68029. public:
  68030. TransformedImageSpanInterpolator (const AffineTransform& transform) throw()
  68031. : inverseTransform (transform.inverted())
  68032. {}
  68033. void setStartOfLine (float x, float y, const int numPixels) throw()
  68034. {
  68035. float x1 = x, y1 = y;
  68036. x += numPixels;
  68037. inverseTransform.transformPoints (x1, y1, x, y);
  68038. xBresenham.set ((int) (x1 * 256.0f), (int) (x * 256.0f), numPixels);
  68039. yBresenham.set ((int) (y1 * 256.0f), (int) (y * 256.0f), numPixels);
  68040. }
  68041. void next (int& x, int& y) throw()
  68042. {
  68043. x = xBresenham.n;
  68044. xBresenham.stepToNext();
  68045. y = yBresenham.n;
  68046. yBresenham.stepToNext();
  68047. }
  68048. private:
  68049. class BresenhamInterpolator
  68050. {
  68051. public:
  68052. BresenhamInterpolator() throw() {}
  68053. void set (const int n1, const int n2, const int numSteps_) throw()
  68054. {
  68055. numSteps = jmax (1, numSteps_);
  68056. step = (n2 - n1) / numSteps;
  68057. remainder = modulo = (n2 - n1) % numSteps;
  68058. n = n1;
  68059. if (modulo <= 0)
  68060. {
  68061. modulo += numSteps;
  68062. remainder += numSteps;
  68063. --step;
  68064. }
  68065. modulo -= numSteps;
  68066. }
  68067. forcedinline void stepToNext() throw()
  68068. {
  68069. modulo += remainder;
  68070. n += step;
  68071. if (modulo > 0)
  68072. {
  68073. modulo -= numSteps;
  68074. ++n;
  68075. }
  68076. }
  68077. int n;
  68078. private:
  68079. int numSteps, step, modulo, remainder;
  68080. };
  68081. const AffineTransform inverseTransform;
  68082. BresenhamInterpolator xBresenham, yBresenham;
  68083. TransformedImageSpanInterpolator (const TransformedImageSpanInterpolator&);
  68084. TransformedImageSpanInterpolator& operator= (const TransformedImageSpanInterpolator&);
  68085. };
  68086. TransformedImageSpanInterpolator interpolator;
  68087. const Image::BitmapData& destData;
  68088. const Image::BitmapData& srcData;
  68089. const int extraAlpha;
  68090. const bool betterQuality;
  68091. const float pixelOffset;
  68092. const int pixelOffsetInt, maxX, maxY;
  68093. int y;
  68094. DestPixelType* linePixels;
  68095. HeapBlock <SrcPixelType> scratchBuffer;
  68096. int scratchSize;
  68097. TransformedImageFillEdgeTableRenderer (const TransformedImageFillEdgeTableRenderer&);
  68098. TransformedImageFillEdgeTableRenderer& operator= (const TransformedImageFillEdgeTableRenderer&);
  68099. };
  68100. class ClipRegionBase : public ReferenceCountedObject
  68101. {
  68102. public:
  68103. ClipRegionBase() {}
  68104. virtual ~ClipRegionBase() {}
  68105. typedef ReferenceCountedObjectPtr<ClipRegionBase> Ptr;
  68106. virtual const Ptr clone() const = 0;
  68107. virtual const Ptr applyClipTo (const Ptr& target) const = 0;
  68108. virtual const Ptr clipToRectangle (const Rectangle<int>& r) = 0;
  68109. virtual const Ptr clipToRectangleList (const RectangleList& r) = 0;
  68110. virtual const Ptr excludeClipRectangle (const Rectangle<int>& r) = 0;
  68111. virtual const Ptr clipToPath (const Path& p, const AffineTransform& transform) = 0;
  68112. virtual const Ptr clipToEdgeTable (const EdgeTable& et) = 0;
  68113. virtual const Ptr clipToImageAlpha (const Image& image, const AffineTransform& t, const bool betterQuality) = 0;
  68114. virtual bool clipRegionIntersects (const Rectangle<int>& r) const = 0;
  68115. virtual const Rectangle<int> getClipBounds() const = 0;
  68116. virtual void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const = 0;
  68117. virtual void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const = 0;
  68118. virtual void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const = 0;
  68119. virtual void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const = 0;
  68120. virtual void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& t, bool betterQuality, bool tiledFill) const = 0;
  68121. virtual void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const = 0;
  68122. protected:
  68123. template <class Iterator>
  68124. static void renderImageTransformedInternal (Iterator& iter, const Image::BitmapData& destData, const Image::BitmapData& srcData,
  68125. const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill)
  68126. {
  68127. switch (destData.pixelFormat)
  68128. {
  68129. case Image::ARGB:
  68130. switch (srcData.pixelFormat)
  68131. {
  68132. case Image::ARGB:
  68133. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68134. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68135. break;
  68136. case Image::RGB:
  68137. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68138. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68139. break;
  68140. default:
  68141. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68142. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68143. break;
  68144. }
  68145. break;
  68146. case Image::RGB:
  68147. switch (srcData.pixelFormat)
  68148. {
  68149. case Image::ARGB:
  68150. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68151. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68152. break;
  68153. case Image::RGB:
  68154. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68155. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68156. break;
  68157. default:
  68158. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68159. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68160. break;
  68161. }
  68162. break;
  68163. default:
  68164. switch (srcData.pixelFormat)
  68165. {
  68166. case Image::ARGB:
  68167. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68168. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68169. break;
  68170. case Image::RGB:
  68171. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68172. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68173. break;
  68174. default:
  68175. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68176. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68177. break;
  68178. }
  68179. break;
  68180. }
  68181. }
  68182. template <class Iterator>
  68183. static void renderImageUntransformedInternal (Iterator& iter, const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill)
  68184. {
  68185. switch (destData.pixelFormat)
  68186. {
  68187. case Image::ARGB:
  68188. switch (srcData.pixelFormat)
  68189. {
  68190. case Image::ARGB:
  68191. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68192. else { ImageFillEdgeTableRenderer <PixelARGB, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68193. break;
  68194. case Image::RGB:
  68195. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68196. else { ImageFillEdgeTableRenderer <PixelARGB, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68197. break;
  68198. default:
  68199. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68200. else { ImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68201. break;
  68202. }
  68203. break;
  68204. case Image::RGB:
  68205. switch (srcData.pixelFormat)
  68206. {
  68207. case Image::ARGB:
  68208. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68209. else { ImageFillEdgeTableRenderer <PixelRGB, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68210. break;
  68211. case Image::RGB:
  68212. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68213. else { ImageFillEdgeTableRenderer <PixelRGB, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68214. break;
  68215. default:
  68216. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68217. else { ImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68218. break;
  68219. }
  68220. break;
  68221. default:
  68222. switch (srcData.pixelFormat)
  68223. {
  68224. case Image::ARGB:
  68225. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68226. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68227. break;
  68228. case Image::RGB:
  68229. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68230. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68231. break;
  68232. default:
  68233. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68234. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68235. break;
  68236. }
  68237. break;
  68238. }
  68239. }
  68240. template <class Iterator, class DestPixelType>
  68241. static void renderSolidFill (Iterator& iter, const Image::BitmapData& destData, const PixelARGB& fillColour, const bool replaceContents, DestPixelType*)
  68242. {
  68243. jassert (destData.pixelStride == sizeof (DestPixelType));
  68244. if (replaceContents)
  68245. {
  68246. SolidColourEdgeTableRenderer <DestPixelType, true> r (destData, fillColour);
  68247. iter.iterate (r);
  68248. }
  68249. else
  68250. {
  68251. SolidColourEdgeTableRenderer <DestPixelType, false> r (destData, fillColour);
  68252. iter.iterate (r);
  68253. }
  68254. }
  68255. template <class Iterator, class DestPixelType>
  68256. static void renderGradient (Iterator& iter, const Image::BitmapData& destData, const ColourGradient& g, const AffineTransform& transform,
  68257. const PixelARGB* const lookupTable, const int numLookupEntries, const bool isIdentity, DestPixelType*)
  68258. {
  68259. jassert (destData.pixelStride == sizeof (DestPixelType));
  68260. if (g.isRadial)
  68261. {
  68262. if (isIdentity)
  68263. {
  68264. GradientEdgeTableRenderer <DestPixelType, RadialGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  68265. iter.iterate (renderer);
  68266. }
  68267. else
  68268. {
  68269. GradientEdgeTableRenderer <DestPixelType, TransformedRadialGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  68270. iter.iterate (renderer);
  68271. }
  68272. }
  68273. else
  68274. {
  68275. GradientEdgeTableRenderer <DestPixelType, LinearGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  68276. iter.iterate (renderer);
  68277. }
  68278. }
  68279. };
  68280. class ClipRegion_EdgeTable : public ClipRegionBase
  68281. {
  68282. public:
  68283. ClipRegion_EdgeTable (const EdgeTable& e) : edgeTable (e) {}
  68284. ClipRegion_EdgeTable (const Rectangle<int>& r) : edgeTable (r) {}
  68285. ClipRegion_EdgeTable (const Rectangle<float>& r) : edgeTable (r) {}
  68286. ClipRegion_EdgeTable (const RectangleList& r) : edgeTable (r) {}
  68287. ClipRegion_EdgeTable (const Rectangle<int>& bounds, const Path& p, const AffineTransform& t) : edgeTable (bounds, p, t) {}
  68288. ClipRegion_EdgeTable (const ClipRegion_EdgeTable& other) : edgeTable (other.edgeTable) {}
  68289. ~ClipRegion_EdgeTable() {}
  68290. const Ptr clone() const
  68291. {
  68292. return new ClipRegion_EdgeTable (*this);
  68293. }
  68294. const Ptr applyClipTo (const Ptr& target) const
  68295. {
  68296. return target->clipToEdgeTable (edgeTable);
  68297. }
  68298. const Ptr clipToRectangle (const Rectangle<int>& r)
  68299. {
  68300. edgeTable.clipToRectangle (r);
  68301. return edgeTable.isEmpty() ? 0 : this;
  68302. }
  68303. const Ptr clipToRectangleList (const RectangleList& r)
  68304. {
  68305. RectangleList inverse (edgeTable.getMaximumBounds());
  68306. if (inverse.subtract (r))
  68307. for (RectangleList::Iterator iter (inverse); iter.next();)
  68308. edgeTable.excludeRectangle (*iter.getRectangle());
  68309. return edgeTable.isEmpty() ? 0 : this;
  68310. }
  68311. const Ptr excludeClipRectangle (const Rectangle<int>& r)
  68312. {
  68313. edgeTable.excludeRectangle (r);
  68314. return edgeTable.isEmpty() ? 0 : this;
  68315. }
  68316. const Ptr clipToPath (const Path& p, const AffineTransform& transform)
  68317. {
  68318. EdgeTable et (edgeTable.getMaximumBounds(), p, transform);
  68319. edgeTable.clipToEdgeTable (et);
  68320. return edgeTable.isEmpty() ? 0 : this;
  68321. }
  68322. const Ptr clipToEdgeTable (const EdgeTable& et)
  68323. {
  68324. edgeTable.clipToEdgeTable (et);
  68325. return edgeTable.isEmpty() ? 0 : this;
  68326. }
  68327. const Ptr clipToImageAlpha (const Image& image, const AffineTransform& transform, const bool betterQuality)
  68328. {
  68329. const Image::BitmapData srcData (image, false);
  68330. if (transform.isOnlyTranslation())
  68331. {
  68332. // If our translation doesn't involve any distortion, just use a simple blit..
  68333. const int tx = (int) (transform.getTranslationX() * 256.0f);
  68334. const int ty = (int) (transform.getTranslationY() * 256.0f);
  68335. if ((! betterQuality) || ((tx | ty) & 224) == 0)
  68336. {
  68337. const int imageX = ((tx + 128) >> 8);
  68338. const int imageY = ((ty + 128) >> 8);
  68339. if (image.getFormat() == Image::ARGB)
  68340. straightClipImage (srcData, imageX, imageY, (PixelARGB*) 0);
  68341. else
  68342. straightClipImage (srcData, imageX, imageY, (PixelAlpha*) 0);
  68343. return edgeTable.isEmpty() ? 0 : this;
  68344. }
  68345. }
  68346. if (transform.isSingularity())
  68347. return 0;
  68348. {
  68349. Path p;
  68350. p.addRectangle (0, 0, (float) srcData.width, (float) srcData.height);
  68351. EdgeTable et2 (edgeTable.getMaximumBounds(), p, transform);
  68352. edgeTable.clipToEdgeTable (et2);
  68353. }
  68354. if (! edgeTable.isEmpty())
  68355. {
  68356. if (image.getFormat() == Image::ARGB)
  68357. transformedClipImage (srcData, transform, betterQuality, (PixelARGB*) 0);
  68358. else
  68359. transformedClipImage (srcData, transform, betterQuality, (PixelAlpha*) 0);
  68360. }
  68361. return edgeTable.isEmpty() ? 0 : this;
  68362. }
  68363. bool clipRegionIntersects (const Rectangle<int>& r) const
  68364. {
  68365. return edgeTable.getMaximumBounds().intersects (r);
  68366. }
  68367. const Rectangle<int> getClipBounds() const
  68368. {
  68369. return edgeTable.getMaximumBounds();
  68370. }
  68371. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const
  68372. {
  68373. const Rectangle<int> totalClip (edgeTable.getMaximumBounds());
  68374. const Rectangle<int> clipped (totalClip.getIntersection (area));
  68375. if (! clipped.isEmpty())
  68376. {
  68377. ClipRegion_EdgeTable et (clipped);
  68378. et.edgeTable.clipToEdgeTable (edgeTable);
  68379. et.fillAllWithColour (destData, colour, replaceContents);
  68380. }
  68381. }
  68382. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const
  68383. {
  68384. const Rectangle<float> totalClip (edgeTable.getMaximumBounds().toFloat());
  68385. const Rectangle<float> clipped (totalClip.getIntersection (area));
  68386. if (! clipped.isEmpty())
  68387. {
  68388. ClipRegion_EdgeTable et (clipped);
  68389. et.edgeTable.clipToEdgeTable (edgeTable);
  68390. et.fillAllWithColour (destData, colour, false);
  68391. }
  68392. }
  68393. void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const
  68394. {
  68395. switch (destData.pixelFormat)
  68396. {
  68397. case Image::ARGB: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelARGB*) 0); break;
  68398. case Image::RGB: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelRGB*) 0); break;
  68399. default: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  68400. }
  68401. }
  68402. void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const
  68403. {
  68404. HeapBlock <PixelARGB> lookupTable;
  68405. const int numLookupEntries = gradient.createLookupTable (transform, lookupTable);
  68406. jassert (numLookupEntries > 0);
  68407. switch (destData.pixelFormat)
  68408. {
  68409. case Image::ARGB: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelARGB*) 0); break;
  68410. case Image::RGB: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelRGB*) 0); break;
  68411. default: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelAlpha*) 0); break;
  68412. }
  68413. }
  68414. void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill) const
  68415. {
  68416. renderImageTransformedInternal (edgeTable, destData, srcData, alpha, transform, betterQuality, tiledFill);
  68417. }
  68418. void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const
  68419. {
  68420. renderImageUntransformedInternal (edgeTable, destData, srcData, alpha, x, y, tiledFill);
  68421. }
  68422. EdgeTable edgeTable;
  68423. private:
  68424. template <class SrcPixelType>
  68425. void transformedClipImage (const Image::BitmapData& srcData, const AffineTransform& transform, const bool betterQuality, const SrcPixelType*)
  68426. {
  68427. TransformedImageFillEdgeTableRenderer <SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, transform, 255, betterQuality);
  68428. for (int y = 0; y < edgeTable.getMaximumBounds().getHeight(); ++y)
  68429. renderer.clipEdgeTableLine (edgeTable, edgeTable.getMaximumBounds().getX(), y + edgeTable.getMaximumBounds().getY(),
  68430. edgeTable.getMaximumBounds().getWidth());
  68431. }
  68432. template <class SrcPixelType>
  68433. void straightClipImage (const Image::BitmapData& srcData, int imageX, int imageY, const SrcPixelType*)
  68434. {
  68435. Rectangle<int> r (imageX, imageY, srcData.width, srcData.height);
  68436. edgeTable.clipToRectangle (r);
  68437. ImageFillEdgeTableRenderer <SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, 255, imageX, imageY);
  68438. for (int y = 0; y < r.getHeight(); ++y)
  68439. renderer.clipEdgeTableLine (edgeTable, r.getX(), y + r.getY(), r.getWidth());
  68440. }
  68441. ClipRegion_EdgeTable& operator= (const ClipRegion_EdgeTable&);
  68442. };
  68443. class ClipRegion_RectangleList : public ClipRegionBase
  68444. {
  68445. public:
  68446. ClipRegion_RectangleList (const Rectangle<int>& r) : clip (r) {}
  68447. ClipRegion_RectangleList (const RectangleList& r) : clip (r) {}
  68448. ClipRegion_RectangleList (const ClipRegion_RectangleList& other) : clip (other.clip) {}
  68449. ~ClipRegion_RectangleList() {}
  68450. const Ptr clone() const
  68451. {
  68452. return new ClipRegion_RectangleList (*this);
  68453. }
  68454. const Ptr applyClipTo (const Ptr& target) const
  68455. {
  68456. return target->clipToRectangleList (clip);
  68457. }
  68458. const Ptr clipToRectangle (const Rectangle<int>& r)
  68459. {
  68460. clip.clipTo (r);
  68461. return clip.isEmpty() ? 0 : this;
  68462. }
  68463. const Ptr clipToRectangleList (const RectangleList& r)
  68464. {
  68465. clip.clipTo (r);
  68466. return clip.isEmpty() ? 0 : this;
  68467. }
  68468. const Ptr excludeClipRectangle (const Rectangle<int>& r)
  68469. {
  68470. clip.subtract (r);
  68471. return clip.isEmpty() ? 0 : this;
  68472. }
  68473. const Ptr clipToPath (const Path& p, const AffineTransform& transform)
  68474. {
  68475. return Ptr (new ClipRegion_EdgeTable (clip))->clipToPath (p, transform);
  68476. }
  68477. const Ptr clipToEdgeTable (const EdgeTable& et)
  68478. {
  68479. return Ptr (new ClipRegion_EdgeTable (clip))->clipToEdgeTable (et);
  68480. }
  68481. const Ptr clipToImageAlpha (const Image& image, const AffineTransform& transform, const bool betterQuality)
  68482. {
  68483. return Ptr (new ClipRegion_EdgeTable (clip))->clipToImageAlpha (image, transform, betterQuality);
  68484. }
  68485. bool clipRegionIntersects (const Rectangle<int>& r) const
  68486. {
  68487. return clip.intersects (r);
  68488. }
  68489. const Rectangle<int> getClipBounds() const
  68490. {
  68491. return clip.getBounds();
  68492. }
  68493. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const
  68494. {
  68495. SubRectangleIterator iter (clip, area);
  68496. switch (destData.pixelFormat)
  68497. {
  68498. case Image::ARGB: renderSolidFill (iter, destData, colour, replaceContents, (PixelARGB*) 0); break;
  68499. case Image::RGB: renderSolidFill (iter, destData, colour, replaceContents, (PixelRGB*) 0); break;
  68500. default: renderSolidFill (iter, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  68501. }
  68502. }
  68503. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const
  68504. {
  68505. SubRectangleIteratorFloat iter (clip, area);
  68506. switch (destData.pixelFormat)
  68507. {
  68508. case Image::ARGB: renderSolidFill (iter, destData, colour, false, (PixelARGB*) 0); break;
  68509. case Image::RGB: renderSolidFill (iter, destData, colour, false, (PixelRGB*) 0); break;
  68510. default: renderSolidFill (iter, destData, colour, false, (PixelAlpha*) 0); break;
  68511. }
  68512. }
  68513. void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const
  68514. {
  68515. switch (destData.pixelFormat)
  68516. {
  68517. case Image::ARGB: renderSolidFill (*this, destData, colour, replaceContents, (PixelARGB*) 0); break;
  68518. case Image::RGB: renderSolidFill (*this, destData, colour, replaceContents, (PixelRGB*) 0); break;
  68519. default: renderSolidFill (*this, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  68520. }
  68521. }
  68522. void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const
  68523. {
  68524. HeapBlock <PixelARGB> lookupTable;
  68525. const int numLookupEntries = gradient.createLookupTable (transform, lookupTable);
  68526. jassert (numLookupEntries > 0);
  68527. switch (destData.pixelFormat)
  68528. {
  68529. case Image::ARGB: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelARGB*) 0); break;
  68530. case Image::RGB: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelRGB*) 0); break;
  68531. default: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelAlpha*) 0); break;
  68532. }
  68533. }
  68534. void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill) const
  68535. {
  68536. renderImageTransformedInternal (*this, destData, srcData, alpha, transform, betterQuality, tiledFill);
  68537. }
  68538. void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const
  68539. {
  68540. renderImageUntransformedInternal (*this, destData, srcData, alpha, x, y, tiledFill);
  68541. }
  68542. RectangleList clip;
  68543. template <class Renderer>
  68544. void iterate (Renderer& r) const throw()
  68545. {
  68546. RectangleList::Iterator iter (clip);
  68547. while (iter.next())
  68548. {
  68549. const Rectangle<int> rect (*iter.getRectangle());
  68550. const int x = rect.getX();
  68551. const int w = rect.getWidth();
  68552. jassert (w > 0);
  68553. const int bottom = rect.getBottom();
  68554. for (int y = rect.getY(); y < bottom; ++y)
  68555. {
  68556. r.setEdgeTableYPos (y);
  68557. r.handleEdgeTableLineFull (x, w);
  68558. }
  68559. }
  68560. }
  68561. private:
  68562. class SubRectangleIterator
  68563. {
  68564. public:
  68565. SubRectangleIterator (const RectangleList& clip_, const Rectangle<int>& area_)
  68566. : clip (clip_), area (area_)
  68567. {
  68568. }
  68569. template <class Renderer>
  68570. void iterate (Renderer& r) const throw()
  68571. {
  68572. RectangleList::Iterator iter (clip);
  68573. while (iter.next())
  68574. {
  68575. const Rectangle<int> rect (iter.getRectangle()->getIntersection (area));
  68576. if (! rect.isEmpty())
  68577. {
  68578. const int x = rect.getX();
  68579. const int w = rect.getWidth();
  68580. const int bottom = rect.getBottom();
  68581. for (int y = rect.getY(); y < bottom; ++y)
  68582. {
  68583. r.setEdgeTableYPos (y);
  68584. r.handleEdgeTableLineFull (x, w);
  68585. }
  68586. }
  68587. }
  68588. }
  68589. private:
  68590. const RectangleList& clip;
  68591. const Rectangle<int> area;
  68592. SubRectangleIterator (const SubRectangleIterator&);
  68593. SubRectangleIterator& operator= (const SubRectangleIterator&);
  68594. };
  68595. class SubRectangleIteratorFloat
  68596. {
  68597. public:
  68598. SubRectangleIteratorFloat (const RectangleList& clip_, const Rectangle<float>& area_)
  68599. : clip (clip_), area (area_)
  68600. {
  68601. }
  68602. template <class Renderer>
  68603. void iterate (Renderer& r) const throw()
  68604. {
  68605. int left = roundToInt (area.getX() * 256.0f);
  68606. int top = roundToInt (area.getY() * 256.0f);
  68607. int right = roundToInt (area.getRight() * 256.0f);
  68608. int bottom = roundToInt (area.getBottom() * 256.0f);
  68609. int totalTop, totalLeft, totalBottom, totalRight;
  68610. int topAlpha, leftAlpha, bottomAlpha, rightAlpha;
  68611. if ((top >> 8) == (bottom >> 8))
  68612. {
  68613. topAlpha = bottom - top;
  68614. bottomAlpha = 0;
  68615. totalTop = top >> 8;
  68616. totalBottom = bottom = top = totalTop + 1;
  68617. }
  68618. else
  68619. {
  68620. if ((top & 255) == 0)
  68621. {
  68622. topAlpha = 0;
  68623. top = totalTop = (top >> 8);
  68624. }
  68625. else
  68626. {
  68627. topAlpha = 255 - (top & 255);
  68628. totalTop = (top >> 8);
  68629. top = totalTop + 1;
  68630. }
  68631. bottomAlpha = bottom & 255;
  68632. bottom >>= 8;
  68633. totalBottom = bottom + (bottomAlpha != 0 ? 1 : 0);
  68634. }
  68635. if ((left >> 8) == (right >> 8))
  68636. {
  68637. leftAlpha = right - left;
  68638. rightAlpha = 0;
  68639. totalLeft = (left >> 8);
  68640. totalRight = right = left = totalLeft + 1;
  68641. }
  68642. else
  68643. {
  68644. if ((left & 255) == 0)
  68645. {
  68646. leftAlpha = 0;
  68647. left = totalLeft = (left >> 8);
  68648. }
  68649. else
  68650. {
  68651. leftAlpha = 255 - (left & 255);
  68652. totalLeft = (left >> 8);
  68653. left = totalLeft + 1;
  68654. }
  68655. rightAlpha = right & 255;
  68656. right >>= 8;
  68657. totalRight = right + (rightAlpha != 0 ? 1 : 0);
  68658. }
  68659. RectangleList::Iterator iter (clip);
  68660. while (iter.next())
  68661. {
  68662. const int clipLeft = iter.getRectangle()->getX();
  68663. const int clipRight = iter.getRectangle()->getRight();
  68664. const int clipTop = iter.getRectangle()->getY();
  68665. const int clipBottom = iter.getRectangle()->getBottom();
  68666. if (totalBottom > clipTop && totalTop < clipBottom && totalRight > clipLeft && totalLeft < clipRight)
  68667. {
  68668. if (right - left == 1 && leftAlpha + rightAlpha == 0) // special case for 1-pix vertical lines
  68669. {
  68670. if (topAlpha != 0 && totalTop >= clipTop)
  68671. {
  68672. r.setEdgeTableYPos (totalTop);
  68673. r.handleEdgeTablePixel (left, topAlpha);
  68674. }
  68675. const int endY = jmin (bottom, clipBottom);
  68676. for (int y = jmax (clipTop, top); y < endY; ++y)
  68677. {
  68678. r.setEdgeTableYPos (y);
  68679. r.handleEdgeTablePixelFull (left);
  68680. }
  68681. if (bottomAlpha != 0 && bottom < clipBottom)
  68682. {
  68683. r.setEdgeTableYPos (bottom);
  68684. r.handleEdgeTablePixel (left, bottomAlpha);
  68685. }
  68686. }
  68687. else
  68688. {
  68689. const int clippedLeft = jmax (left, clipLeft);
  68690. const int clippedWidth = jmin (right, clipRight) - clippedLeft;
  68691. const bool doLeftAlpha = leftAlpha != 0 && totalLeft >= clipLeft;
  68692. const bool doRightAlpha = rightAlpha != 0 && right < clipRight;
  68693. if (topAlpha != 0 && totalTop >= clipTop)
  68694. {
  68695. r.setEdgeTableYPos (totalTop);
  68696. if (doLeftAlpha)
  68697. r.handleEdgeTablePixel (totalLeft, (leftAlpha * topAlpha) >> 8);
  68698. if (clippedWidth > 0)
  68699. r.handleEdgeTableLine (clippedLeft, clippedWidth, topAlpha);
  68700. if (doRightAlpha)
  68701. r.handleEdgeTablePixel (right, (rightAlpha * topAlpha) >> 8);
  68702. }
  68703. const int endY = jmin (bottom, clipBottom);
  68704. for (int y = jmax (clipTop, top); y < endY; ++y)
  68705. {
  68706. r.setEdgeTableYPos (y);
  68707. if (doLeftAlpha)
  68708. r.handleEdgeTablePixel (totalLeft, leftAlpha);
  68709. if (clippedWidth > 0)
  68710. r.handleEdgeTableLineFull (clippedLeft, clippedWidth);
  68711. if (doRightAlpha)
  68712. r.handleEdgeTablePixel (right, rightAlpha);
  68713. }
  68714. if (bottomAlpha != 0 && bottom < clipBottom)
  68715. {
  68716. r.setEdgeTableYPos (bottom);
  68717. if (doLeftAlpha)
  68718. r.handleEdgeTablePixel (totalLeft, (leftAlpha * bottomAlpha) >> 8);
  68719. if (clippedWidth > 0)
  68720. r.handleEdgeTableLine (clippedLeft, clippedWidth, bottomAlpha);
  68721. if (doRightAlpha)
  68722. r.handleEdgeTablePixel (right, (rightAlpha * bottomAlpha) >> 8);
  68723. }
  68724. }
  68725. }
  68726. }
  68727. }
  68728. private:
  68729. const RectangleList& clip;
  68730. const Rectangle<float>& area;
  68731. SubRectangleIteratorFloat (const SubRectangleIteratorFloat&);
  68732. SubRectangleIteratorFloat& operator= (const SubRectangleIteratorFloat&);
  68733. };
  68734. ClipRegion_RectangleList& operator= (const ClipRegion_RectangleList&);
  68735. };
  68736. }
  68737. class LowLevelGraphicsSoftwareRenderer::SavedState
  68738. {
  68739. public:
  68740. SavedState (const Rectangle<int>& clip_, const int xOffset_, const int yOffset_)
  68741. : clip (new SoftwareRendererClasses::ClipRegion_RectangleList (clip_)),
  68742. xOffset (xOffset_), yOffset (yOffset_), interpolationQuality (Graphics::mediumResamplingQuality)
  68743. {
  68744. }
  68745. SavedState (const RectangleList& clip_, const int xOffset_, const int yOffset_)
  68746. : clip (new SoftwareRendererClasses::ClipRegion_RectangleList (clip_)),
  68747. xOffset (xOffset_), yOffset (yOffset_), interpolationQuality (Graphics::mediumResamplingQuality)
  68748. {
  68749. }
  68750. SavedState (const SavedState& other)
  68751. : clip (other.clip), xOffset (other.xOffset), yOffset (other.yOffset), font (other.font),
  68752. fillType (other.fillType), interpolationQuality (other.interpolationQuality)
  68753. {
  68754. }
  68755. ~SavedState()
  68756. {
  68757. }
  68758. void setOrigin (const int x, const int y) throw()
  68759. {
  68760. xOffset += x;
  68761. yOffset += y;
  68762. }
  68763. bool clipToRectangle (const Rectangle<int>& r)
  68764. {
  68765. if (clip != 0)
  68766. {
  68767. cloneClipIfMultiplyReferenced();
  68768. clip = clip->clipToRectangle (r.translated (xOffset, yOffset));
  68769. }
  68770. return clip != 0;
  68771. }
  68772. bool clipToRectangleList (const RectangleList& r)
  68773. {
  68774. if (clip != 0)
  68775. {
  68776. cloneClipIfMultiplyReferenced();
  68777. RectangleList offsetList (r);
  68778. offsetList.offsetAll (xOffset, yOffset);
  68779. clip = clip->clipToRectangleList (offsetList);
  68780. }
  68781. return clip != 0;
  68782. }
  68783. bool excludeClipRectangle (const Rectangle<int>& r)
  68784. {
  68785. if (clip != 0)
  68786. {
  68787. cloneClipIfMultiplyReferenced();
  68788. clip = clip->excludeClipRectangle (r.translated (xOffset, yOffset));
  68789. }
  68790. return clip != 0;
  68791. }
  68792. void clipToPath (const Path& p, const AffineTransform& transform)
  68793. {
  68794. if (clip != 0)
  68795. {
  68796. cloneClipIfMultiplyReferenced();
  68797. clip = clip->clipToPath (p, transform.translated ((float) xOffset, (float) yOffset));
  68798. }
  68799. }
  68800. void clipToImageAlpha (const Image& image, const AffineTransform& t)
  68801. {
  68802. if (clip != 0)
  68803. {
  68804. if (image.hasAlphaChannel())
  68805. {
  68806. cloneClipIfMultiplyReferenced();
  68807. clip = clip->clipToImageAlpha (image, t.translated ((float) xOffset, (float) yOffset),
  68808. interpolationQuality != Graphics::lowResamplingQuality);
  68809. }
  68810. else
  68811. {
  68812. Path p;
  68813. p.addRectangle (image.getBounds());
  68814. clipToPath (p, t);
  68815. }
  68816. }
  68817. }
  68818. bool clipRegionIntersects (const Rectangle<int>& r) const
  68819. {
  68820. return clip != 0 && clip->clipRegionIntersects (r.translated (xOffset, yOffset));
  68821. }
  68822. const Rectangle<int> getClipBounds() const
  68823. {
  68824. return clip == 0 ? Rectangle<int>() : clip->getClipBounds().translated (-xOffset, -yOffset);
  68825. }
  68826. void fillRect (Image& image, const Rectangle<int>& r, const bool replaceContents)
  68827. {
  68828. if (clip != 0)
  68829. {
  68830. if (fillType.isColour())
  68831. {
  68832. Image::BitmapData destData (image, true);
  68833. clip->fillRectWithColour (destData, r.translated (xOffset, yOffset), fillType.colour.getPixelARGB(), replaceContents);
  68834. }
  68835. else
  68836. {
  68837. const Rectangle<int> totalClip (clip->getClipBounds());
  68838. const Rectangle<int> clipped (totalClip.getIntersection (r.translated (xOffset, yOffset)));
  68839. if (! clipped.isEmpty())
  68840. fillShape (image, new SoftwareRendererClasses::ClipRegion_RectangleList (clipped), false);
  68841. }
  68842. }
  68843. }
  68844. void fillRect (Image& image, const Rectangle<float>& r)
  68845. {
  68846. if (clip != 0)
  68847. {
  68848. if (fillType.isColour())
  68849. {
  68850. Image::BitmapData destData (image, true);
  68851. clip->fillRectWithColour (destData, r.translated ((float) xOffset, (float) yOffset), fillType.colour.getPixelARGB());
  68852. }
  68853. else
  68854. {
  68855. const Rectangle<float> totalClip (clip->getClipBounds().toFloat());
  68856. const Rectangle<float> clipped (totalClip.getIntersection (r.translated ((float) xOffset, (float) yOffset)));
  68857. if (! clipped.isEmpty())
  68858. fillShape (image, new SoftwareRendererClasses::ClipRegion_EdgeTable (clipped), false);
  68859. }
  68860. }
  68861. }
  68862. void fillPath (Image& image, const Path& path, const AffineTransform& transform)
  68863. {
  68864. if (clip != 0)
  68865. fillShape (image, new SoftwareRendererClasses::ClipRegion_EdgeTable (clip->getClipBounds(), path, transform.translated ((float) xOffset, (float) yOffset)), false);
  68866. }
  68867. void fillEdgeTable (Image& image, const EdgeTable& edgeTable, const float x, const int y)
  68868. {
  68869. if (clip != 0)
  68870. {
  68871. SoftwareRendererClasses::ClipRegion_EdgeTable* edgeTableClip = new SoftwareRendererClasses::ClipRegion_EdgeTable (edgeTable);
  68872. SoftwareRendererClasses::ClipRegionBase::Ptr shapeToFill (edgeTableClip);
  68873. edgeTableClip->edgeTable.translate (x + xOffset, y + yOffset);
  68874. fillShape (image, shapeToFill, false);
  68875. }
  68876. }
  68877. void fillShape (Image& image, SoftwareRendererClasses::ClipRegionBase::Ptr shapeToFill, const bool replaceContents)
  68878. {
  68879. jassert (clip != 0);
  68880. shapeToFill = clip->applyClipTo (shapeToFill);
  68881. if (shapeToFill != 0)
  68882. {
  68883. Image::BitmapData destData (image, true);
  68884. if (fillType.isGradient())
  68885. {
  68886. jassert (! replaceContents); // that option is just for solid colours
  68887. ColourGradient g2 (*(fillType.gradient));
  68888. g2.multiplyOpacity (fillType.getOpacity());
  68889. AffineTransform transform (fillType.transform.translated (xOffset - 0.5f, yOffset - 0.5f));
  68890. const bool isIdentity = transform.isOnlyTranslation();
  68891. if (isIdentity)
  68892. {
  68893. // If our translation doesn't involve any distortion, we can speed it up..
  68894. g2.point1.applyTransform (transform);
  68895. g2.point2.applyTransform (transform);
  68896. transform = AffineTransform::identity;
  68897. }
  68898. shapeToFill->fillAllWithGradient (destData, g2, transform, isIdentity);
  68899. }
  68900. else if (fillType.isTiledImage())
  68901. {
  68902. renderImage (image, fillType.image, fillType.transform, shapeToFill);
  68903. }
  68904. else
  68905. {
  68906. shapeToFill->fillAllWithColour (destData, fillType.colour.getPixelARGB(), replaceContents);
  68907. }
  68908. }
  68909. }
  68910. void renderImage (Image& destImage, const Image& sourceImage, const AffineTransform& t, const SoftwareRendererClasses::ClipRegionBase* const tiledFillClipRegion)
  68911. {
  68912. const AffineTransform transform (t.translated ((float) xOffset, (float) yOffset));
  68913. const Image::BitmapData destData (destImage, true);
  68914. const Image::BitmapData srcData (sourceImage, false);
  68915. const int alpha = fillType.colour.getAlpha();
  68916. const bool betterQuality = (interpolationQuality != Graphics::lowResamplingQuality);
  68917. if (transform.isOnlyTranslation())
  68918. {
  68919. // If our translation doesn't involve any distortion, just use a simple blit..
  68920. int tx = (int) (transform.getTranslationX() * 256.0f);
  68921. int ty = (int) (transform.getTranslationY() * 256.0f);
  68922. if ((! betterQuality) || ((tx | ty) & 224) == 0)
  68923. {
  68924. tx = ((tx + 128) >> 8);
  68925. ty = ((ty + 128) >> 8);
  68926. if (tiledFillClipRegion != 0)
  68927. {
  68928. tiledFillClipRegion->renderImageUntransformed (destData, srcData, alpha, tx, ty, true);
  68929. }
  68930. else
  68931. {
  68932. SoftwareRendererClasses::ClipRegionBase::Ptr c (new SoftwareRendererClasses::ClipRegion_EdgeTable (Rectangle<int> (tx, ty, sourceImage.getWidth(), sourceImage.getHeight()).getIntersection (destImage.getBounds())));
  68933. c = clip->applyClipTo (c);
  68934. if (c != 0)
  68935. c->renderImageUntransformed (destData, srcData, alpha, tx, ty, false);
  68936. }
  68937. return;
  68938. }
  68939. }
  68940. if (transform.isSingularity())
  68941. return;
  68942. if (tiledFillClipRegion != 0)
  68943. {
  68944. tiledFillClipRegion->renderImageTransformed (destData, srcData, alpha, transform, betterQuality, true);
  68945. }
  68946. else
  68947. {
  68948. Path p;
  68949. p.addRectangle (sourceImage.getBounds());
  68950. SoftwareRendererClasses::ClipRegionBase::Ptr c (clip->clone());
  68951. c = c->clipToPath (p, transform);
  68952. if (c != 0)
  68953. c->renderImageTransformed (destData, srcData, alpha, transform, betterQuality, false);
  68954. }
  68955. }
  68956. SoftwareRendererClasses::ClipRegionBase::Ptr clip;
  68957. int xOffset, yOffset;
  68958. Font font;
  68959. FillType fillType;
  68960. Graphics::ResamplingQuality interpolationQuality;
  68961. private:
  68962. void cloneClipIfMultiplyReferenced()
  68963. {
  68964. if (clip->getReferenceCount() > 1)
  68965. clip = clip->clone();
  68966. }
  68967. SavedState& operator= (const SavedState&);
  68968. };
  68969. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (const Image& image_)
  68970. : image (image_)
  68971. {
  68972. currentState = new SavedState (image_.getBounds(), 0, 0);
  68973. }
  68974. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (const Image& image_, const int xOffset, const int yOffset,
  68975. const RectangleList& initialClip)
  68976. : image (image_)
  68977. {
  68978. currentState = new SavedState (initialClip, xOffset, yOffset);
  68979. }
  68980. LowLevelGraphicsSoftwareRenderer::~LowLevelGraphicsSoftwareRenderer()
  68981. {
  68982. }
  68983. bool LowLevelGraphicsSoftwareRenderer::isVectorDevice() const
  68984. {
  68985. return false;
  68986. }
  68987. void LowLevelGraphicsSoftwareRenderer::setOrigin (int x, int y)
  68988. {
  68989. currentState->setOrigin (x, y);
  68990. }
  68991. bool LowLevelGraphicsSoftwareRenderer::clipToRectangle (const Rectangle<int>& r)
  68992. {
  68993. return currentState->clipToRectangle (r);
  68994. }
  68995. bool LowLevelGraphicsSoftwareRenderer::clipToRectangleList (const RectangleList& clipRegion)
  68996. {
  68997. return currentState->clipToRectangleList (clipRegion);
  68998. }
  68999. void LowLevelGraphicsSoftwareRenderer::excludeClipRectangle (const Rectangle<int>& r)
  69000. {
  69001. currentState->excludeClipRectangle (r);
  69002. }
  69003. void LowLevelGraphicsSoftwareRenderer::clipToPath (const Path& path, const AffineTransform& transform)
  69004. {
  69005. currentState->clipToPath (path, transform);
  69006. }
  69007. void LowLevelGraphicsSoftwareRenderer::clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  69008. {
  69009. currentState->clipToImageAlpha (sourceImage, transform);
  69010. }
  69011. bool LowLevelGraphicsSoftwareRenderer::clipRegionIntersects (const Rectangle<int>& r)
  69012. {
  69013. return currentState->clipRegionIntersects (r);
  69014. }
  69015. const Rectangle<int> LowLevelGraphicsSoftwareRenderer::getClipBounds() const
  69016. {
  69017. return currentState->getClipBounds();
  69018. }
  69019. bool LowLevelGraphicsSoftwareRenderer::isClipEmpty() const
  69020. {
  69021. return currentState->clip == 0;
  69022. }
  69023. void LowLevelGraphicsSoftwareRenderer::saveState()
  69024. {
  69025. stateStack.add (new SavedState (*currentState));
  69026. }
  69027. void LowLevelGraphicsSoftwareRenderer::restoreState()
  69028. {
  69029. SavedState* const top = stateStack.getLast();
  69030. if (top != 0)
  69031. {
  69032. currentState = top;
  69033. stateStack.removeLast (1, false);
  69034. }
  69035. else
  69036. {
  69037. jassertfalse; // trying to pop with an empty stack!
  69038. }
  69039. }
  69040. void LowLevelGraphicsSoftwareRenderer::setFill (const FillType& fillType)
  69041. {
  69042. currentState->fillType = fillType;
  69043. }
  69044. void LowLevelGraphicsSoftwareRenderer::setOpacity (float newOpacity)
  69045. {
  69046. currentState->fillType.setOpacity (newOpacity);
  69047. }
  69048. void LowLevelGraphicsSoftwareRenderer::setInterpolationQuality (Graphics::ResamplingQuality quality)
  69049. {
  69050. currentState->interpolationQuality = quality;
  69051. }
  69052. void LowLevelGraphicsSoftwareRenderer::fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  69053. {
  69054. currentState->fillRect (image, r, replaceExistingContents);
  69055. }
  69056. void LowLevelGraphicsSoftwareRenderer::fillPath (const Path& path, const AffineTransform& transform)
  69057. {
  69058. currentState->fillPath (image, path, transform);
  69059. }
  69060. void LowLevelGraphicsSoftwareRenderer::drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  69061. {
  69062. currentState->renderImage (image, sourceImage, transform,
  69063. fillEntireClipAsTiles ? currentState->clip : 0);
  69064. }
  69065. void LowLevelGraphicsSoftwareRenderer::drawLine (const Line <float>& line)
  69066. {
  69067. Path p;
  69068. p.addLineSegment (line, 1.0f);
  69069. fillPath (p, AffineTransform::identity);
  69070. }
  69071. void LowLevelGraphicsSoftwareRenderer::drawVerticalLine (const int x, float top, float bottom)
  69072. {
  69073. if (bottom > top)
  69074. currentState->fillRect (image, Rectangle<float> ((float) x, top, 1.0f, bottom - top));
  69075. }
  69076. void LowLevelGraphicsSoftwareRenderer::drawHorizontalLine (const int y, float left, float right)
  69077. {
  69078. if (right > left)
  69079. currentState->fillRect (image, Rectangle<float> (left, (float) y, right - left, 1.0f));
  69080. }
  69081. class LowLevelGraphicsSoftwareRenderer::CachedGlyph
  69082. {
  69083. public:
  69084. CachedGlyph() : glyph (0), lastAccessCount (0) {}
  69085. ~CachedGlyph() {}
  69086. void draw (SavedState& state, Image& image, const float x, const float y) const
  69087. {
  69088. if (edgeTable != 0)
  69089. state.fillEdgeTable (image, *edgeTable, x, roundToInt (y));
  69090. }
  69091. void generate (const Font& newFont, const int glyphNumber)
  69092. {
  69093. font = newFont;
  69094. glyph = glyphNumber;
  69095. edgeTable = 0;
  69096. Path glyphPath;
  69097. font.getTypeface()->getOutlineForGlyph (glyphNumber, glyphPath);
  69098. if (! glyphPath.isEmpty())
  69099. {
  69100. const float fontHeight = font.getHeight();
  69101. const AffineTransform transform (AffineTransform::scale (fontHeight * font.getHorizontalScale(), fontHeight)
  69102. #if JUCE_MAC || JUCE_IOS
  69103. .translated (0.0f, -0.5f)
  69104. #endif
  69105. );
  69106. edgeTable = new EdgeTable (glyphPath.getBoundsTransformed (transform).getSmallestIntegerContainer().expanded (1, 0),
  69107. glyphPath, transform);
  69108. }
  69109. }
  69110. int glyph, lastAccessCount;
  69111. Font font;
  69112. juce_UseDebuggingNewOperator
  69113. private:
  69114. ScopedPointer <EdgeTable> edgeTable;
  69115. CachedGlyph (const CachedGlyph&);
  69116. CachedGlyph& operator= (const CachedGlyph&);
  69117. };
  69118. class LowLevelGraphicsSoftwareRenderer::GlyphCache : private DeletedAtShutdown
  69119. {
  69120. public:
  69121. GlyphCache()
  69122. : accessCounter (0), hits (0), misses (0)
  69123. {
  69124. for (int i = 120; --i >= 0;)
  69125. glyphs.add (new CachedGlyph());
  69126. }
  69127. ~GlyphCache()
  69128. {
  69129. clearSingletonInstance();
  69130. }
  69131. juce_DeclareSingleton_SingleThreaded_Minimal (GlyphCache);
  69132. void drawGlyph (SavedState& state, Image& image, const Font& font, const int glyphNumber, float x, float y)
  69133. {
  69134. ++accessCounter;
  69135. int oldestCounter = std::numeric_limits<int>::max();
  69136. CachedGlyph* oldest = 0;
  69137. for (int i = glyphs.size(); --i >= 0;)
  69138. {
  69139. CachedGlyph* const glyph = glyphs.getUnchecked (i);
  69140. if (glyph->glyph == glyphNumber && glyph->font == font)
  69141. {
  69142. ++hits;
  69143. glyph->lastAccessCount = accessCounter;
  69144. glyph->draw (state, image, x, y);
  69145. return;
  69146. }
  69147. if (glyph->lastAccessCount <= oldestCounter)
  69148. {
  69149. oldestCounter = glyph->lastAccessCount;
  69150. oldest = glyph;
  69151. }
  69152. }
  69153. if (hits + ++misses > (glyphs.size() << 4))
  69154. {
  69155. if (misses * 2 > hits)
  69156. {
  69157. for (int i = 32; --i >= 0;)
  69158. glyphs.add (new CachedGlyph());
  69159. }
  69160. hits = misses = 0;
  69161. oldest = glyphs.getLast();
  69162. }
  69163. jassert (oldest != 0);
  69164. oldest->lastAccessCount = accessCounter;
  69165. oldest->generate (font, glyphNumber);
  69166. oldest->draw (state, image, x, y);
  69167. }
  69168. juce_UseDebuggingNewOperator
  69169. private:
  69170. friend class OwnedArray <CachedGlyph>;
  69171. OwnedArray <CachedGlyph> glyphs;
  69172. int accessCounter, hits, misses;
  69173. GlyphCache (const GlyphCache&);
  69174. GlyphCache& operator= (const GlyphCache&);
  69175. };
  69176. juce_ImplementSingleton_SingleThreaded (LowLevelGraphicsSoftwareRenderer::GlyphCache);
  69177. void LowLevelGraphicsSoftwareRenderer::setFont (const Font& newFont)
  69178. {
  69179. currentState->font = newFont;
  69180. }
  69181. const Font LowLevelGraphicsSoftwareRenderer::getFont()
  69182. {
  69183. return currentState->font;
  69184. }
  69185. void LowLevelGraphicsSoftwareRenderer::drawGlyph (int glyphNumber, const AffineTransform& transform)
  69186. {
  69187. Font& f = currentState->font;
  69188. if (transform.isOnlyTranslation())
  69189. {
  69190. GlyphCache::getInstance()->drawGlyph (*currentState, image, f, glyphNumber,
  69191. transform.getTranslationX(),
  69192. transform.getTranslationY());
  69193. }
  69194. else
  69195. {
  69196. Path p;
  69197. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  69198. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight()).followedBy (transform));
  69199. }
  69200. }
  69201. #if JUCE_MSVC
  69202. #pragma warning (pop)
  69203. #if JUCE_DEBUG
  69204. #pragma optimize ("", on) // resets optimisations to the project defaults
  69205. #endif
  69206. #endif
  69207. END_JUCE_NAMESPACE
  69208. /*** End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp ***/
  69209. /*** Start of inlined file: juce_RectanglePlacement.cpp ***/
  69210. BEGIN_JUCE_NAMESPACE
  69211. RectanglePlacement::RectanglePlacement (const RectanglePlacement& other) throw()
  69212. : flags (other.flags)
  69213. {
  69214. }
  69215. RectanglePlacement& RectanglePlacement::operator= (const RectanglePlacement& other) throw()
  69216. {
  69217. flags = other.flags;
  69218. return *this;
  69219. }
  69220. void RectanglePlacement::applyTo (double& x, double& y,
  69221. double& w, double& h,
  69222. const double dx, const double dy,
  69223. const double dw, const double dh) const throw()
  69224. {
  69225. if (w == 0 || h == 0)
  69226. return;
  69227. if ((flags & stretchToFit) != 0)
  69228. {
  69229. x = dx;
  69230. y = dy;
  69231. w = dw;
  69232. h = dh;
  69233. }
  69234. else
  69235. {
  69236. double scale = (flags & fillDestination) != 0 ? jmax (dw / w, dh / h)
  69237. : jmin (dw / w, dh / h);
  69238. if ((flags & onlyReduceInSize) != 0)
  69239. scale = jmin (scale, 1.0);
  69240. if ((flags & onlyIncreaseInSize) != 0)
  69241. scale = jmax (scale, 1.0);
  69242. w *= scale;
  69243. h *= scale;
  69244. if ((flags & xLeft) != 0)
  69245. x = dx;
  69246. else if ((flags & xRight) != 0)
  69247. x = dx + dw - w;
  69248. else
  69249. x = dx + (dw - w) * 0.5;
  69250. if ((flags & yTop) != 0)
  69251. y = dy;
  69252. else if ((flags & yBottom) != 0)
  69253. y = dy + dh - h;
  69254. else
  69255. y = dy + (dh - h) * 0.5;
  69256. }
  69257. }
  69258. const AffineTransform RectanglePlacement::getTransformToFit (const Rectangle<float>& source, const Rectangle<float>& destination) const throw()
  69259. {
  69260. if (source.isEmpty())
  69261. return AffineTransform::identity;
  69262. float w = source.getWidth();
  69263. float h = source.getHeight();
  69264. const float scaleX = destination.getWidth() / w;
  69265. const float scaleY = destination.getHeight() / h;
  69266. if ((flags & stretchToFit) != 0)
  69267. return AffineTransform::translation (-source.getX(), -source.getY())
  69268. .scaled (scaleX, scaleY)
  69269. .translated (destination.getX(), destination.getY());
  69270. float scale = (flags & fillDestination) != 0 ? jmax (scaleX, scaleY)
  69271. : jmin (scaleX, scaleY);
  69272. if ((flags & onlyReduceInSize) != 0)
  69273. scale = jmin (scale, 1.0f);
  69274. if ((flags & onlyIncreaseInSize) != 0)
  69275. scale = jmax (scale, 1.0f);
  69276. w *= scale;
  69277. h *= scale;
  69278. float newX = destination.getX();
  69279. float newY = destination.getY();
  69280. if ((flags & xRight) != 0)
  69281. newX += destination.getWidth() - w; // right
  69282. else if ((flags & xLeft) == 0)
  69283. newX += (destination.getWidth() - w) / 2.0f; // centre
  69284. if ((flags & yBottom) != 0)
  69285. newY += destination.getHeight() - h; // bottom
  69286. else if ((flags & yTop) == 0)
  69287. newY += (destination.getHeight() - h) / 2.0f; // centre
  69288. return AffineTransform::translation (-source.getX(), -source.getY())
  69289. .scaled (scale, scale)
  69290. .translated (newX, newY);
  69291. }
  69292. END_JUCE_NAMESPACE
  69293. /*** End of inlined file: juce_RectanglePlacement.cpp ***/
  69294. /*** Start of inlined file: juce_Drawable.cpp ***/
  69295. BEGIN_JUCE_NAMESPACE
  69296. Drawable::RenderingContext::RenderingContext (Graphics& g_,
  69297. const AffineTransform& transform_,
  69298. const float opacity_) throw()
  69299. : g (g_),
  69300. transform (transform_),
  69301. opacity (opacity_)
  69302. {
  69303. }
  69304. Drawable::Drawable()
  69305. : parent (0)
  69306. {
  69307. }
  69308. Drawable::~Drawable()
  69309. {
  69310. }
  69311. void Drawable::draw (Graphics& g, const float opacity, const AffineTransform& transform) const
  69312. {
  69313. render (RenderingContext (g, transform, opacity));
  69314. }
  69315. void Drawable::drawAt (Graphics& g, const float x, const float y, const float opacity) const
  69316. {
  69317. draw (g, opacity, AffineTransform::translation (x, y));
  69318. }
  69319. void Drawable::drawWithin (Graphics& g,
  69320. const Rectangle<float>& destArea,
  69321. const RectanglePlacement& placement,
  69322. const float opacity) const
  69323. {
  69324. if (! destArea.isEmpty())
  69325. draw (g, opacity, placement.getTransformToFit (getBounds(), destArea));
  69326. }
  69327. Drawable* Drawable::createFromImageData (const void* data, const size_t numBytes)
  69328. {
  69329. Drawable* result = 0;
  69330. Image image (ImageFileFormat::loadFrom (data, (int) numBytes));
  69331. if (image.isValid())
  69332. {
  69333. DrawableImage* const di = new DrawableImage();
  69334. di->setImage (image);
  69335. result = di;
  69336. }
  69337. else
  69338. {
  69339. const String asString (String::createStringFromData (data, (int) numBytes));
  69340. XmlDocument doc (asString);
  69341. ScopedPointer <XmlElement> outer (doc.getDocumentElement (true));
  69342. if (outer != 0 && outer->hasTagName ("svg"))
  69343. {
  69344. ScopedPointer <XmlElement> svg (doc.getDocumentElement());
  69345. if (svg != 0)
  69346. result = Drawable::createFromSVG (*svg);
  69347. }
  69348. }
  69349. return result;
  69350. }
  69351. Drawable* Drawable::createFromImageDataStream (InputStream& dataSource)
  69352. {
  69353. MemoryOutputStream mo;
  69354. mo.writeFromInputStream (dataSource, -1);
  69355. return createFromImageData (mo.getData(), mo.getDataSize());
  69356. }
  69357. Drawable* Drawable::createFromImageFile (const File& file)
  69358. {
  69359. const ScopedPointer <FileInputStream> fin (file.createInputStream());
  69360. return fin != 0 ? createFromImageDataStream (*fin) : 0;
  69361. }
  69362. Drawable* Drawable::createFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  69363. {
  69364. return createChildFromValueTree (0, tree, imageProvider);
  69365. }
  69366. Drawable* Drawable::createChildFromValueTree (DrawableComposite* parent, const ValueTree& tree, ImageProvider* imageProvider)
  69367. {
  69368. const Identifier type (tree.getType());
  69369. Drawable* d = 0;
  69370. if (type == DrawablePath::valueTreeType)
  69371. d = new DrawablePath();
  69372. else if (type == DrawableComposite::valueTreeType)
  69373. d = new DrawableComposite();
  69374. else if (type == DrawableRectangle::valueTreeType)
  69375. d = new DrawableRectangle();
  69376. else if (type == DrawableImage::valueTreeType)
  69377. d = new DrawableImage();
  69378. else if (type == DrawableText::valueTreeType)
  69379. d = new DrawableText();
  69380. if (d != 0)
  69381. {
  69382. d->parent = parent;
  69383. d->refreshFromValueTree (tree, imageProvider);
  69384. }
  69385. return d;
  69386. }
  69387. const Identifier Drawable::ValueTreeWrapperBase::idProperty ("id");
  69388. Drawable::ValueTreeWrapperBase::ValueTreeWrapperBase (const ValueTree& state_)
  69389. : state (state_)
  69390. {
  69391. }
  69392. Drawable::ValueTreeWrapperBase::~ValueTreeWrapperBase()
  69393. {
  69394. }
  69395. const String Drawable::ValueTreeWrapperBase::getID() const
  69396. {
  69397. return state [idProperty];
  69398. }
  69399. void Drawable::ValueTreeWrapperBase::setID (const String& newID, UndoManager* const undoManager)
  69400. {
  69401. if (newID.isEmpty())
  69402. state.removeProperty (idProperty, undoManager);
  69403. else
  69404. state.setProperty (idProperty, newID, undoManager);
  69405. }
  69406. END_JUCE_NAMESPACE
  69407. /*** End of inlined file: juce_Drawable.cpp ***/
  69408. /*** Start of inlined file: juce_DrawableShape.cpp ***/
  69409. BEGIN_JUCE_NAMESPACE
  69410. DrawableShape::DrawableShape()
  69411. : strokeType (0.0f),
  69412. mainFill (Colours::black),
  69413. strokeFill (Colours::black),
  69414. pathNeedsUpdating (true),
  69415. strokeNeedsUpdating (true)
  69416. {
  69417. }
  69418. DrawableShape::DrawableShape (const DrawableShape& other)
  69419. : strokeType (other.strokeType),
  69420. mainFill (other.mainFill),
  69421. strokeFill (other.strokeFill),
  69422. pathNeedsUpdating (true),
  69423. strokeNeedsUpdating (true)
  69424. {
  69425. }
  69426. DrawableShape::~DrawableShape()
  69427. {
  69428. }
  69429. void DrawableShape::setFill (const FillType& newFill)
  69430. {
  69431. mainFill = newFill;
  69432. }
  69433. void DrawableShape::setStrokeFill (const FillType& newFill)
  69434. {
  69435. strokeFill = newFill;
  69436. }
  69437. void DrawableShape::setStrokeType (const PathStrokeType& newStrokeType)
  69438. {
  69439. strokeType = newStrokeType;
  69440. strokeNeedsUpdating = true;
  69441. }
  69442. void DrawableShape::setStrokeThickness (const float newThickness)
  69443. {
  69444. setStrokeType (PathStrokeType (newThickness, strokeType.getJointStyle(), strokeType.getEndStyle()));
  69445. }
  69446. bool DrawableShape::isStrokeVisible() const throw()
  69447. {
  69448. return strokeType.getStrokeThickness() > 0.0f && ! strokeFill.isInvisible();
  69449. }
  69450. void DrawableShape::setBrush (const Drawable::RenderingContext& context, const FillType& type)
  69451. {
  69452. FillType f (type);
  69453. if (f.isGradient())
  69454. f.gradient->multiplyOpacity (context.opacity);
  69455. else
  69456. f.setOpacity (f.getOpacity() * context.opacity);
  69457. f.transform = f.transform.followedBy (context.transform);
  69458. context.g.setFillType (f);
  69459. }
  69460. bool DrawableShape::refreshFillTypes (const FillAndStrokeState& newState,
  69461. Expression::EvaluationContext* /*nameFinder*/,
  69462. ImageProvider* imageProvider)
  69463. {
  69464. bool hasChanged = false;
  69465. {
  69466. const FillType f (newState.getMainFill (parent, imageProvider));
  69467. if (mainFill != f)
  69468. {
  69469. hasChanged = true;
  69470. mainFill = f;
  69471. }
  69472. }
  69473. {
  69474. const FillType f (newState.getStrokeFill (parent, imageProvider));
  69475. if (strokeFill != f)
  69476. {
  69477. hasChanged = true;
  69478. strokeFill = f;
  69479. }
  69480. }
  69481. return hasChanged;
  69482. }
  69483. void DrawableShape::writeTo (FillAndStrokeState& state, ImageProvider* imageProvider, UndoManager* undoManager) const
  69484. {
  69485. state.setMainFill (mainFill, 0, 0, 0, imageProvider, undoManager);
  69486. state.setStrokeFill (strokeFill, 0, 0, 0, imageProvider, undoManager);
  69487. state.setStrokeType (strokeType, undoManager);
  69488. }
  69489. void DrawableShape::render (const Drawable::RenderingContext& context) const
  69490. {
  69491. setBrush (context, mainFill);
  69492. context.g.fillPath (getCachedPath(), context.transform);
  69493. if (isStrokeVisible())
  69494. {
  69495. setBrush (context, strokeFill);
  69496. context.g.fillPath (getCachedStrokePath(), context.transform);
  69497. }
  69498. }
  69499. void DrawableShape::pathChanged()
  69500. {
  69501. pathNeedsUpdating = true;
  69502. }
  69503. void DrawableShape::strokeChanged()
  69504. {
  69505. strokeNeedsUpdating = true;
  69506. }
  69507. void DrawableShape::invalidatePoints()
  69508. {
  69509. pathNeedsUpdating = true;
  69510. strokeNeedsUpdating = true;
  69511. }
  69512. const Path& DrawableShape::getCachedPath() const
  69513. {
  69514. if (pathNeedsUpdating)
  69515. {
  69516. pathNeedsUpdating = false;
  69517. if (rebuildPath (cachedPath))
  69518. strokeNeedsUpdating = true;
  69519. }
  69520. return cachedPath;
  69521. }
  69522. const Path& DrawableShape::getCachedStrokePath() const
  69523. {
  69524. if (strokeNeedsUpdating)
  69525. {
  69526. cachedStroke.clear();
  69527. strokeType.createStrokedPath (cachedStroke, getCachedPath(), AffineTransform::identity, 4.0f);
  69528. strokeNeedsUpdating = false; // (must be called after getCachedPath)
  69529. }
  69530. return cachedStroke;
  69531. }
  69532. const Rectangle<float> DrawableShape::getBounds() const
  69533. {
  69534. if (isStrokeVisible())
  69535. return getCachedStrokePath().getBounds();
  69536. else
  69537. return getCachedPath().getBounds();
  69538. }
  69539. bool DrawableShape::hitTest (float x, float y) const
  69540. {
  69541. return getCachedPath().contains (x, y)
  69542. || (isStrokeVisible() && getCachedStrokePath().contains (x, y));
  69543. }
  69544. const Identifier DrawableShape::FillAndStrokeState::type ("type");
  69545. const Identifier DrawableShape::FillAndStrokeState::colour ("colour");
  69546. const Identifier DrawableShape::FillAndStrokeState::colours ("colours");
  69547. const Identifier DrawableShape::FillAndStrokeState::fill ("Fill");
  69548. const Identifier DrawableShape::FillAndStrokeState::stroke ("Stroke");
  69549. const Identifier DrawableShape::FillAndStrokeState::path ("Path");
  69550. const Identifier DrawableShape::FillAndStrokeState::jointStyle ("jointStyle");
  69551. const Identifier DrawableShape::FillAndStrokeState::capStyle ("capStyle");
  69552. const Identifier DrawableShape::FillAndStrokeState::strokeWidth ("strokeWidth");
  69553. const Identifier DrawableShape::FillAndStrokeState::gradientPoint1 ("point1");
  69554. const Identifier DrawableShape::FillAndStrokeState::gradientPoint2 ("point2");
  69555. const Identifier DrawableShape::FillAndStrokeState::gradientPoint3 ("point3");
  69556. const Identifier DrawableShape::FillAndStrokeState::radial ("radial");
  69557. const Identifier DrawableShape::FillAndStrokeState::imageId ("imageId");
  69558. const Identifier DrawableShape::FillAndStrokeState::imageOpacity ("imageOpacity");
  69559. DrawableShape::FillAndStrokeState::FillAndStrokeState (const ValueTree& state_)
  69560. : Drawable::ValueTreeWrapperBase (state_)
  69561. {
  69562. }
  69563. const FillType DrawableShape::FillAndStrokeState::getMainFill (Expression::EvaluationContext* nameFinder,
  69564. ImageProvider* imageProvider) const
  69565. {
  69566. return readFillType (state.getChildWithName (fill), 0, 0, 0, nameFinder, imageProvider);
  69567. }
  69568. ValueTree DrawableShape::FillAndStrokeState::getMainFillState()
  69569. {
  69570. ValueTree v (state.getChildWithName (fill));
  69571. if (v.isValid())
  69572. return v;
  69573. setMainFill (Colours::black, 0, 0, 0, 0, 0);
  69574. return getMainFillState();
  69575. }
  69576. void DrawableShape::FillAndStrokeState::setMainFill (const FillType& newFill, const RelativePoint* gp1, const RelativePoint* gp2,
  69577. const RelativePoint* gp3, ImageProvider* imageProvider, UndoManager* undoManager)
  69578. {
  69579. ValueTree v (state.getOrCreateChildWithName (fill, undoManager));
  69580. writeFillType (v, newFill, gp1, gp2, gp3, imageProvider, undoManager);
  69581. }
  69582. const FillType DrawableShape::FillAndStrokeState::getStrokeFill (Expression::EvaluationContext* nameFinder,
  69583. ImageProvider* imageProvider) const
  69584. {
  69585. return readFillType (state.getChildWithName (stroke), 0, 0, 0, nameFinder, imageProvider);
  69586. }
  69587. ValueTree DrawableShape::FillAndStrokeState::getStrokeFillState()
  69588. {
  69589. ValueTree v (state.getChildWithName (stroke));
  69590. if (v.isValid())
  69591. return v;
  69592. setStrokeFill (Colours::black, 0, 0, 0, 0, 0);
  69593. return getStrokeFillState();
  69594. }
  69595. void DrawableShape::FillAndStrokeState::setStrokeFill (const FillType& newFill, const RelativePoint* gp1, const RelativePoint* gp2,
  69596. const RelativePoint* gp3, ImageProvider* imageProvider, UndoManager* undoManager)
  69597. {
  69598. ValueTree v (state.getOrCreateChildWithName (stroke, undoManager));
  69599. writeFillType (v, newFill, gp1, gp2, gp3, imageProvider, undoManager);
  69600. }
  69601. const PathStrokeType DrawableShape::FillAndStrokeState::getStrokeType() const
  69602. {
  69603. const String jointStyleString (state [jointStyle].toString());
  69604. const String capStyleString (state [capStyle].toString());
  69605. return PathStrokeType (state [strokeWidth],
  69606. jointStyleString == "curved" ? PathStrokeType::curved
  69607. : (jointStyleString == "bevel" ? PathStrokeType::beveled
  69608. : PathStrokeType::mitered),
  69609. capStyleString == "square" ? PathStrokeType::square
  69610. : (capStyleString == "round" ? PathStrokeType::rounded
  69611. : PathStrokeType::butt));
  69612. }
  69613. void DrawableShape::FillAndStrokeState::setStrokeType (const PathStrokeType& newStrokeType, UndoManager* undoManager)
  69614. {
  69615. state.setProperty (strokeWidth, (double) newStrokeType.getStrokeThickness(), undoManager);
  69616. state.setProperty (jointStyle, newStrokeType.getJointStyle() == PathStrokeType::mitered
  69617. ? "miter" : (newStrokeType.getJointStyle() == PathStrokeType::curved ? "curved" : "bevel"), undoManager);
  69618. state.setProperty (capStyle, newStrokeType.getEndStyle() == PathStrokeType::butt
  69619. ? "butt" : (newStrokeType.getEndStyle() == PathStrokeType::square ? "square" : "round"), undoManager);
  69620. }
  69621. const FillType DrawableShape::FillAndStrokeState::readFillType (const ValueTree& v, RelativePoint* const gp1, RelativePoint* const gp2, RelativePoint* const gp3,
  69622. Expression::EvaluationContext* const nameFinder, ImageProvider* imageProvider)
  69623. {
  69624. const String newType (v[type].toString());
  69625. if (newType == "solid")
  69626. {
  69627. const String colourString (v [colour].toString());
  69628. return FillType (Colour (colourString.isEmpty() ? (uint32) 0xff000000
  69629. : (uint32) colourString.getHexValue32()));
  69630. }
  69631. else if (newType == "gradient")
  69632. {
  69633. RelativePoint p1 (v [gradientPoint1]), p2 (v [gradientPoint2]), p3 (v [gradientPoint3]);
  69634. ColourGradient g;
  69635. if (gp1 != 0) *gp1 = p1;
  69636. if (gp2 != 0) *gp2 = p2;
  69637. if (gp3 != 0) *gp3 = p3;
  69638. g.point1 = p1.resolve (nameFinder);
  69639. g.point2 = p2.resolve (nameFinder);
  69640. g.isRadial = v[radial];
  69641. StringArray colourSteps;
  69642. colourSteps.addTokens (v[colours].toString(), false);
  69643. for (int i = 0; i < colourSteps.size() / 2; ++i)
  69644. g.addColour (colourSteps[i * 2].getDoubleValue(),
  69645. Colour ((uint32) colourSteps[i * 2 + 1].getHexValue32()));
  69646. FillType fillType (g);
  69647. if (g.isRadial)
  69648. {
  69649. const Point<float> point3 (p3.resolve (nameFinder));
  69650. const Point<float> point3Source (g.point1.getX() + g.point2.getY() - g.point1.getY(),
  69651. g.point1.getY() + g.point1.getX() - g.point2.getX());
  69652. fillType.transform = AffineTransform::fromTargetPoints (g.point1.getX(), g.point1.getY(), g.point1.getX(), g.point1.getY(),
  69653. g.point2.getX(), g.point2.getY(), g.point2.getX(), g.point2.getY(),
  69654. point3Source.getX(), point3Source.getY(), point3.getX(), point3.getY());
  69655. }
  69656. return fillType;
  69657. }
  69658. else if (newType == "image")
  69659. {
  69660. Image im;
  69661. if (imageProvider != 0)
  69662. im = imageProvider->getImageForIdentifier (v[imageId]);
  69663. FillType f (im, AffineTransform::identity);
  69664. f.setOpacity ((float) v.getProperty (imageOpacity, 1.0f));
  69665. return f;
  69666. }
  69667. jassert (! v.isValid());
  69668. return FillType();
  69669. }
  69670. namespace DrawableShapeHelpers
  69671. {
  69672. const Point<float> calcThirdGradientPoint (const FillType& fillType)
  69673. {
  69674. const ColourGradient& g = *fillType.gradient;
  69675. const Point<float> point3Source (g.point1.getX() + g.point2.getY() - g.point1.getY(),
  69676. g.point1.getY() + g.point1.getX() - g.point2.getX());
  69677. return point3Source.transformedBy (fillType.transform);
  69678. }
  69679. }
  69680. void DrawableShape::FillAndStrokeState::writeFillType (ValueTree& v, const FillType& fillType,
  69681. const RelativePoint* const gp1, const RelativePoint* const gp2, const RelativePoint* gp3,
  69682. ImageProvider* imageProvider, UndoManager* const undoManager)
  69683. {
  69684. if (fillType.isColour())
  69685. {
  69686. v.setProperty (type, "solid", undoManager);
  69687. v.setProperty (colour, String::toHexString ((int) fillType.colour.getARGB()), undoManager);
  69688. }
  69689. else if (fillType.isGradient())
  69690. {
  69691. v.setProperty (type, "gradient", undoManager);
  69692. v.setProperty (gradientPoint1, gp1 != 0 ? gp1->toString() : fillType.gradient->point1.toString(), undoManager);
  69693. v.setProperty (gradientPoint2, gp2 != 0 ? gp2->toString() : fillType.gradient->point2.toString(), undoManager);
  69694. v.setProperty (gradientPoint3, gp3 != 0 ? gp3->toString() : DrawableShapeHelpers::calcThirdGradientPoint (fillType).toString(), undoManager);
  69695. v.setProperty (radial, fillType.gradient->isRadial, undoManager);
  69696. String s;
  69697. for (int i = 0; i < fillType.gradient->getNumColours(); ++i)
  69698. s << ' ' << fillType.gradient->getColourPosition (i)
  69699. << ' ' << String::toHexString ((int) fillType.gradient->getColour(i).getARGB());
  69700. v.setProperty (colours, s.trimStart(), undoManager);
  69701. }
  69702. else if (fillType.isTiledImage())
  69703. {
  69704. v.setProperty (type, "image", undoManager);
  69705. if (imageProvider != 0)
  69706. v.setProperty (imageId, imageProvider->getIdentifierForImage (fillType.image), undoManager);
  69707. if (fillType.getOpacity() < 1.0f)
  69708. v.setProperty (imageOpacity, fillType.getOpacity(), undoManager);
  69709. else
  69710. v.removeProperty (imageOpacity, undoManager);
  69711. }
  69712. else
  69713. {
  69714. jassertfalse;
  69715. }
  69716. }
  69717. END_JUCE_NAMESPACE
  69718. /*** End of inlined file: juce_DrawableShape.cpp ***/
  69719. /*** Start of inlined file: juce_DrawableComposite.cpp ***/
  69720. BEGIN_JUCE_NAMESPACE
  69721. DrawableComposite::DrawableComposite()
  69722. : bounds (Point<float>(), Point<float> (100.0f, 0.0f), Point<float> (0.0f, 100.0f))
  69723. {
  69724. setContentArea (RelativeRectangle (RelativeCoordinate (0.0),
  69725. RelativeCoordinate (100.0),
  69726. RelativeCoordinate (0.0),
  69727. RelativeCoordinate (100.0)));
  69728. }
  69729. DrawableComposite::DrawableComposite (const DrawableComposite& other)
  69730. {
  69731. bounds = other.bounds;
  69732. for (int i = 0; i < other.drawables.size(); ++i)
  69733. drawables.add (other.drawables.getUnchecked(i)->createCopy());
  69734. markersX.addCopiesOf (other.markersX);
  69735. markersY.addCopiesOf (other.markersY);
  69736. }
  69737. DrawableComposite::~DrawableComposite()
  69738. {
  69739. }
  69740. void DrawableComposite::insertDrawable (Drawable* drawable, const int index)
  69741. {
  69742. if (drawable != 0)
  69743. {
  69744. jassert (! drawables.contains (drawable)); // trying to add a drawable that's already in here!
  69745. jassert (drawable->parent == 0); // A drawable can only live inside one parent at a time!
  69746. drawables.insert (index, drawable);
  69747. drawable->parent = this;
  69748. }
  69749. }
  69750. void DrawableComposite::insertDrawable (const Drawable& drawable, const int index)
  69751. {
  69752. insertDrawable (drawable.createCopy(), index);
  69753. }
  69754. void DrawableComposite::removeDrawable (const int index, const bool deleteDrawable)
  69755. {
  69756. drawables.remove (index, deleteDrawable);
  69757. }
  69758. Drawable* DrawableComposite::getDrawableWithName (const String& name) const throw()
  69759. {
  69760. for (int i = drawables.size(); --i >= 0;)
  69761. if (drawables.getUnchecked(i)->getName() == name)
  69762. return drawables.getUnchecked(i);
  69763. return 0;
  69764. }
  69765. void DrawableComposite::bringToFront (const int index)
  69766. {
  69767. if (index >= 0 && index < drawables.size() - 1)
  69768. drawables.move (index, -1);
  69769. }
  69770. void DrawableComposite::setBoundingBox (const RelativeParallelogram& newBoundingBox)
  69771. {
  69772. bounds = newBoundingBox;
  69773. }
  69774. DrawableComposite::Marker::Marker (const DrawableComposite::Marker& other)
  69775. : name (other.name), position (other.position)
  69776. {
  69777. }
  69778. DrawableComposite::Marker::Marker (const String& name_, const RelativeCoordinate& position_)
  69779. : name (name_), position (position_)
  69780. {
  69781. }
  69782. bool DrawableComposite::Marker::operator!= (const DrawableComposite::Marker& other) const throw()
  69783. {
  69784. return name != other.name || position != other.position;
  69785. }
  69786. const char* const DrawableComposite::contentLeftMarkerName ("left");
  69787. const char* const DrawableComposite::contentRightMarkerName ("right");
  69788. const char* const DrawableComposite::contentTopMarkerName ("top");
  69789. const char* const DrawableComposite::contentBottomMarkerName ("bottom");
  69790. const RelativeRectangle DrawableComposite::getContentArea() const
  69791. {
  69792. jassert (markersX.size() >= 2 && getMarker (true, 0)->name == contentLeftMarkerName && getMarker (true, 1)->name == contentRightMarkerName);
  69793. jassert (markersY.size() >= 2 && getMarker (false, 0)->name == contentTopMarkerName && getMarker (false, 1)->name == contentBottomMarkerName);
  69794. return RelativeRectangle (markersX.getUnchecked(0)->position, markersX.getUnchecked(1)->position,
  69795. markersY.getUnchecked(0)->position, markersY.getUnchecked(1)->position);
  69796. }
  69797. void DrawableComposite::setContentArea (const RelativeRectangle& newArea)
  69798. {
  69799. setMarker (contentLeftMarkerName, true, newArea.left);
  69800. setMarker (contentRightMarkerName, true, newArea.right);
  69801. setMarker (contentTopMarkerName, false, newArea.top);
  69802. setMarker (contentBottomMarkerName, false, newArea.bottom);
  69803. }
  69804. void DrawableComposite::resetBoundingBoxToContentArea()
  69805. {
  69806. const RelativeRectangle content (getContentArea());
  69807. setBoundingBox (RelativeParallelogram (RelativePoint (content.left, content.top),
  69808. RelativePoint (content.right, content.top),
  69809. RelativePoint (content.left, content.bottom)));
  69810. }
  69811. void DrawableComposite::resetContentAreaAndBoundingBoxToFitChildren()
  69812. {
  69813. const Rectangle<float> bounds (getUntransformedBounds (false));
  69814. setContentArea (RelativeRectangle (RelativeCoordinate (bounds.getX()),
  69815. RelativeCoordinate (bounds.getRight()),
  69816. RelativeCoordinate (bounds.getY()),
  69817. RelativeCoordinate (bounds.getBottom())));
  69818. resetBoundingBoxToContentArea();
  69819. }
  69820. int DrawableComposite::getNumMarkers (const bool xAxis) const throw()
  69821. {
  69822. return (xAxis ? markersX : markersY).size();
  69823. }
  69824. const DrawableComposite::Marker* DrawableComposite::getMarker (const bool xAxis, const int index) const throw()
  69825. {
  69826. return (xAxis ? markersX : markersY) [index];
  69827. }
  69828. void DrawableComposite::setMarker (const String& name, const bool xAxis, const RelativeCoordinate& position)
  69829. {
  69830. OwnedArray <Marker>& markers = (xAxis ? markersX : markersY);
  69831. for (int i = 0; i < markers.size(); ++i)
  69832. {
  69833. Marker* const m = markers.getUnchecked(i);
  69834. if (m->name == name)
  69835. {
  69836. if (m->position != position)
  69837. {
  69838. m->position = position;
  69839. invalidatePoints();
  69840. }
  69841. return;
  69842. }
  69843. }
  69844. (xAxis ? markersX : markersY).add (new Marker (name, position));
  69845. invalidatePoints();
  69846. }
  69847. void DrawableComposite::removeMarker (const bool xAxis, const int index)
  69848. {
  69849. jassert (index >= 2);
  69850. if (index >= 2)
  69851. (xAxis ? markersX : markersY).remove (index);
  69852. }
  69853. const AffineTransform DrawableComposite::calculateTransform() const
  69854. {
  69855. Point<float> resolved[3];
  69856. bounds.resolveThreePoints (resolved, parent);
  69857. const Rectangle<float> content (getContentArea().resolve (parent));
  69858. return AffineTransform::fromTargetPoints (content.getX(), content.getY(), resolved[0].getX(), resolved[0].getY(),
  69859. content.getRight(), content.getY(), resolved[1].getX(), resolved[1].getY(),
  69860. content.getX(), content.getBottom(), resolved[2].getX(), resolved[2].getY());
  69861. }
  69862. void DrawableComposite::render (const Drawable::RenderingContext& context) const
  69863. {
  69864. if (drawables.size() > 0 && context.opacity > 0)
  69865. {
  69866. if (context.opacity >= 1.0f || drawables.size() == 1)
  69867. {
  69868. Drawable::RenderingContext contextCopy (context);
  69869. contextCopy.transform = calculateTransform().followedBy (context.transform);
  69870. for (int i = 0; i < drawables.size(); ++i)
  69871. drawables.getUnchecked(i)->render (contextCopy);
  69872. }
  69873. else
  69874. {
  69875. // To correctly render a whole composite layer with an overall transparency,
  69876. // we need to render everything opaquely into a temp buffer, then blend that
  69877. // with the target opacity...
  69878. const Rectangle<int> clipBounds (context.g.getClipBounds());
  69879. if (! clipBounds.isEmpty())
  69880. {
  69881. Image tempImage (Image::ARGB, clipBounds.getWidth(), clipBounds.getHeight(), true);
  69882. {
  69883. Graphics tempG (tempImage);
  69884. tempG.setOrigin (-clipBounds.getX(), -clipBounds.getY());
  69885. Drawable::RenderingContext tempContext (tempG, context.transform, 1.0f);
  69886. render (tempContext);
  69887. }
  69888. context.g.setOpacity (context.opacity);
  69889. context.g.drawImageAt (tempImage, clipBounds.getX(), clipBounds.getY());
  69890. }
  69891. }
  69892. }
  69893. }
  69894. const Expression DrawableComposite::getSymbolValue (const String& symbol, const String& member) const
  69895. {
  69896. jassert (member.isEmpty()) // the only symbols available in a Drawable are markers.
  69897. int i;
  69898. for (i = 0; i < markersX.size(); ++i)
  69899. {
  69900. Marker* const m = markersX.getUnchecked(i);
  69901. if (m->name == symbol)
  69902. return m->position.getExpression();
  69903. }
  69904. for (i = 0; i < markersY.size(); ++i)
  69905. {
  69906. Marker* const m = markersY.getUnchecked(i);
  69907. if (m->name == symbol)
  69908. return m->position.getExpression();
  69909. }
  69910. throw Expression::EvaluationError (symbol, member);
  69911. }
  69912. const Rectangle<float> DrawableComposite::getUntransformedBounds (const bool includeMarkers) const
  69913. {
  69914. Rectangle<float> bounds;
  69915. int i;
  69916. for (i = 0; i < drawables.size(); ++i)
  69917. bounds = bounds.getUnion (drawables.getUnchecked(i)->getBounds());
  69918. if (includeMarkers)
  69919. {
  69920. if (markersX.size() > 0)
  69921. {
  69922. float minX = std::numeric_limits<float>::max();
  69923. float maxX = std::numeric_limits<float>::min();
  69924. for (i = markersX.size(); --i >= 0;)
  69925. {
  69926. const Marker* m = markersX.getUnchecked(i);
  69927. const float pos = (float) m->position.resolve (this);
  69928. minX = jmin (minX, pos);
  69929. maxX = jmax (maxX, pos);
  69930. }
  69931. if (minX <= maxX)
  69932. {
  69933. if (bounds.getHeight() > 0)
  69934. {
  69935. minX = jmin (minX, bounds.getX());
  69936. maxX = jmax (maxX, bounds.getRight());
  69937. }
  69938. bounds.setLeft (minX);
  69939. bounds.setWidth (maxX - minX);
  69940. }
  69941. }
  69942. if (markersY.size() > 0)
  69943. {
  69944. float minY = std::numeric_limits<float>::max();
  69945. float maxY = std::numeric_limits<float>::min();
  69946. for (i = markersY.size(); --i >= 0;)
  69947. {
  69948. const Marker* m = markersY.getUnchecked(i);
  69949. const float pos = (float) m->position.resolve (this);
  69950. minY = jmin (minY, pos);
  69951. maxY = jmax (maxY, pos);
  69952. }
  69953. if (minY <= maxY)
  69954. {
  69955. if (bounds.getHeight() > 0)
  69956. {
  69957. minY = jmin (minY, bounds.getY());
  69958. maxY = jmax (maxY, bounds.getBottom());
  69959. }
  69960. bounds.setTop (minY);
  69961. bounds.setHeight (maxY - minY);
  69962. }
  69963. }
  69964. }
  69965. return bounds;
  69966. }
  69967. const Rectangle<float> DrawableComposite::getBounds() const
  69968. {
  69969. return getUntransformedBounds (true).transformed (calculateTransform());
  69970. }
  69971. bool DrawableComposite::hitTest (float x, float y) const
  69972. {
  69973. calculateTransform().inverted().transformPoint (x, y);
  69974. for (int i = 0; i < drawables.size(); ++i)
  69975. if (drawables.getUnchecked(i)->hitTest (x, y))
  69976. return true;
  69977. return false;
  69978. }
  69979. Drawable* DrawableComposite::createCopy() const
  69980. {
  69981. return new DrawableComposite (*this);
  69982. }
  69983. void DrawableComposite::invalidatePoints()
  69984. {
  69985. for (int i = 0; i < drawables.size(); ++i)
  69986. drawables.getUnchecked(i)->invalidatePoints();
  69987. }
  69988. const Identifier DrawableComposite::valueTreeType ("Group");
  69989. const Identifier DrawableComposite::ValueTreeWrapper::topLeft ("topLeft");
  69990. const Identifier DrawableComposite::ValueTreeWrapper::topRight ("topRight");
  69991. const Identifier DrawableComposite::ValueTreeWrapper::bottomLeft ("bottomLeft");
  69992. const Identifier DrawableComposite::ValueTreeWrapper::childGroupTag ("Drawables");
  69993. const Identifier DrawableComposite::ValueTreeWrapper::markerGroupTagX ("MarkersX");
  69994. const Identifier DrawableComposite::ValueTreeWrapper::markerGroupTagY ("MarkersY");
  69995. const Identifier DrawableComposite::ValueTreeWrapper::markerTag ("Marker");
  69996. const Identifier DrawableComposite::ValueTreeWrapper::nameProperty ("name");
  69997. const Identifier DrawableComposite::ValueTreeWrapper::posProperty ("position");
  69998. DrawableComposite::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  69999. : ValueTreeWrapperBase (state_)
  70000. {
  70001. jassert (state.hasType (valueTreeType));
  70002. }
  70003. ValueTree DrawableComposite::ValueTreeWrapper::getChildList() const
  70004. {
  70005. return state.getChildWithName (childGroupTag);
  70006. }
  70007. ValueTree DrawableComposite::ValueTreeWrapper::getChildListCreating (UndoManager* undoManager)
  70008. {
  70009. return state.getOrCreateChildWithName (childGroupTag, undoManager);
  70010. }
  70011. int DrawableComposite::ValueTreeWrapper::getNumDrawables() const
  70012. {
  70013. return getChildList().getNumChildren();
  70014. }
  70015. ValueTree DrawableComposite::ValueTreeWrapper::getDrawableState (int index) const
  70016. {
  70017. return getChildList().getChild (index);
  70018. }
  70019. ValueTree DrawableComposite::ValueTreeWrapper::getDrawableWithId (const String& objectId, bool recursive) const
  70020. {
  70021. if (getID() == objectId)
  70022. return state;
  70023. if (! recursive)
  70024. {
  70025. return getChildList().getChildWithProperty (idProperty, objectId);
  70026. }
  70027. else
  70028. {
  70029. const ValueTree childList (getChildList());
  70030. for (int i = getNumDrawables(); --i >= 0;)
  70031. {
  70032. const ValueTree& child = childList.getChild (i);
  70033. if (child [Drawable::ValueTreeWrapperBase::idProperty] == objectId)
  70034. return child;
  70035. if (child.hasType (DrawableComposite::valueTreeType))
  70036. {
  70037. ValueTree v (DrawableComposite::ValueTreeWrapper (child).getDrawableWithId (objectId, true));
  70038. if (v.isValid())
  70039. return v;
  70040. }
  70041. }
  70042. return ValueTree::invalid;
  70043. }
  70044. }
  70045. int DrawableComposite::ValueTreeWrapper::indexOfDrawable (const ValueTree& item) const
  70046. {
  70047. return getChildList().indexOf (item);
  70048. }
  70049. void DrawableComposite::ValueTreeWrapper::addDrawable (const ValueTree& newDrawableState, int index, UndoManager* undoManager)
  70050. {
  70051. getChildListCreating (undoManager).addChild (newDrawableState, index, undoManager);
  70052. }
  70053. void DrawableComposite::ValueTreeWrapper::moveDrawableOrder (int currentIndex, int newIndex, UndoManager* undoManager)
  70054. {
  70055. getChildListCreating (undoManager).moveChild (currentIndex, newIndex, undoManager);
  70056. }
  70057. void DrawableComposite::ValueTreeWrapper::removeDrawable (const ValueTree& child, UndoManager* undoManager)
  70058. {
  70059. getChildList().removeChild (child, undoManager);
  70060. }
  70061. const RelativeParallelogram DrawableComposite::ValueTreeWrapper::getBoundingBox() const
  70062. {
  70063. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  70064. state.getProperty (topRight, "100, 0"),
  70065. state.getProperty (bottomLeft, "0, 100"));
  70066. }
  70067. void DrawableComposite::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  70068. {
  70069. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  70070. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  70071. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  70072. }
  70073. void DrawableComposite::ValueTreeWrapper::resetBoundingBoxToContentArea (UndoManager* undoManager)
  70074. {
  70075. const RelativeRectangle content (getContentArea());
  70076. setBoundingBox (RelativeParallelogram (RelativePoint (content.left, content.top),
  70077. RelativePoint (content.right, content.top),
  70078. RelativePoint (content.left, content.bottom)), undoManager);
  70079. }
  70080. const RelativeRectangle DrawableComposite::ValueTreeWrapper::getContentArea() const
  70081. {
  70082. return RelativeRectangle (getMarker (true, getMarkerState (true, 0)).position,
  70083. getMarker (true, getMarkerState (true, 1)).position,
  70084. getMarker (false, getMarkerState (false, 0)).position,
  70085. getMarker (false, getMarkerState (false, 1)).position);
  70086. }
  70087. void DrawableComposite::ValueTreeWrapper::setContentArea (const RelativeRectangle& newArea, UndoManager* undoManager)
  70088. {
  70089. setMarker (true, Marker (contentLeftMarkerName, newArea.left), undoManager);
  70090. setMarker (true, Marker (contentRightMarkerName, newArea.right), undoManager);
  70091. setMarker (false, Marker (contentTopMarkerName, newArea.top), undoManager);
  70092. setMarker (false, Marker (contentBottomMarkerName, newArea.bottom), undoManager);
  70093. }
  70094. ValueTree DrawableComposite::ValueTreeWrapper::getMarkerList (bool xAxis) const
  70095. {
  70096. return state.getChildWithName (xAxis ? markerGroupTagX : markerGroupTagY);
  70097. }
  70098. ValueTree DrawableComposite::ValueTreeWrapper::getMarkerListCreating (bool xAxis, UndoManager* undoManager)
  70099. {
  70100. return state.getOrCreateChildWithName (xAxis ? markerGroupTagX : markerGroupTagY, undoManager);
  70101. }
  70102. int DrawableComposite::ValueTreeWrapper::getNumMarkers (bool xAxis) const
  70103. {
  70104. return getMarkerList (xAxis).getNumChildren();
  70105. }
  70106. const ValueTree DrawableComposite::ValueTreeWrapper::getMarkerState (bool xAxis, int index) const
  70107. {
  70108. return getMarkerList (xAxis).getChild (index);
  70109. }
  70110. const ValueTree DrawableComposite::ValueTreeWrapper::getMarkerState (bool xAxis, const String& name) const
  70111. {
  70112. return getMarkerList (xAxis).getChildWithProperty (nameProperty, name);
  70113. }
  70114. bool DrawableComposite::ValueTreeWrapper::containsMarker (bool xAxis, const ValueTree& state) const
  70115. {
  70116. return state.isAChildOf (getMarkerList (xAxis));
  70117. }
  70118. const DrawableComposite::Marker DrawableComposite::ValueTreeWrapper::getMarker (bool xAxis, const ValueTree& state) const
  70119. {
  70120. (void) xAxis;
  70121. jassert (containsMarker (xAxis, state));
  70122. return Marker (state [nameProperty], RelativeCoordinate (state [posProperty].toString()));
  70123. }
  70124. void DrawableComposite::ValueTreeWrapper::setMarker (bool xAxis, const Marker& m, UndoManager* undoManager)
  70125. {
  70126. ValueTree markerList (getMarkerListCreating (xAxis, undoManager));
  70127. ValueTree marker (markerList.getChildWithProperty (nameProperty, m.name));
  70128. if (marker.isValid())
  70129. {
  70130. marker.setProperty (posProperty, m.position.toString(), undoManager);
  70131. }
  70132. else
  70133. {
  70134. marker = ValueTree (markerTag);
  70135. marker.setProperty (nameProperty, m.name, 0);
  70136. marker.setProperty (posProperty, m.position.toString(), 0);
  70137. markerList.addChild (marker, -1, undoManager);
  70138. }
  70139. }
  70140. void DrawableComposite::ValueTreeWrapper::removeMarker (bool xAxis, const ValueTree& state, UndoManager* undoManager)
  70141. {
  70142. if (state [nameProperty].toString() != contentLeftMarkerName
  70143. && state [nameProperty].toString() != contentRightMarkerName
  70144. && state [nameProperty].toString() != contentTopMarkerName
  70145. && state [nameProperty].toString() != contentBottomMarkerName)
  70146. return getMarkerList (xAxis).removeChild (state, undoManager);
  70147. }
  70148. const Rectangle<float> DrawableComposite::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  70149. {
  70150. const ValueTreeWrapper wrapper (tree);
  70151. setName (wrapper.getID());
  70152. Rectangle<float> damage;
  70153. bool redrawAll = false;
  70154. const RelativeParallelogram newBounds (wrapper.getBoundingBox());
  70155. if (bounds != newBounds)
  70156. {
  70157. redrawAll = true;
  70158. damage = getBounds();
  70159. bounds = newBounds;
  70160. }
  70161. const int numMarkersX = wrapper.getNumMarkers (true);
  70162. const int numMarkersY = wrapper.getNumMarkers (false);
  70163. // Remove deleted markers...
  70164. if (markersX.size() > numMarkersX || markersY.size() > numMarkersY)
  70165. {
  70166. if (! redrawAll)
  70167. {
  70168. redrawAll = true;
  70169. damage = getBounds();
  70170. }
  70171. markersX.removeRange (jmax (2, numMarkersX), markersX.size());
  70172. markersY.removeRange (jmax (2, numMarkersY), markersY.size());
  70173. }
  70174. // Update markers and add new ones..
  70175. int i;
  70176. for (i = 0; i < numMarkersX; ++i)
  70177. {
  70178. const Marker newMarker (wrapper.getMarker (true, wrapper.getMarkerState (true, i)));
  70179. Marker* m = markersX[i];
  70180. if (m == 0 || newMarker != *m)
  70181. {
  70182. if (! redrawAll)
  70183. {
  70184. redrawAll = true;
  70185. damage = getBounds();
  70186. }
  70187. if (m == 0)
  70188. markersX.add (new Marker (newMarker));
  70189. else
  70190. *m = newMarker;
  70191. }
  70192. }
  70193. for (i = 0; i < numMarkersY; ++i)
  70194. {
  70195. const Marker newMarker (wrapper.getMarker (false, wrapper.getMarkerState (false, i)));
  70196. Marker* m = markersY[i];
  70197. if (m == 0 || newMarker != *m)
  70198. {
  70199. if (! redrawAll)
  70200. {
  70201. redrawAll = true;
  70202. damage = getBounds();
  70203. }
  70204. if (m == 0)
  70205. markersY.add (new Marker (newMarker));
  70206. else
  70207. *m = newMarker;
  70208. }
  70209. }
  70210. // Remove deleted drawables..
  70211. for (i = drawables.size(); --i >= wrapper.getNumDrawables();)
  70212. {
  70213. Drawable* const d = drawables.getUnchecked(i);
  70214. if (! redrawAll)
  70215. damage = damage.getUnion (d->getBounds());
  70216. d->parent = 0;
  70217. drawables.remove (i);
  70218. }
  70219. // Update drawables and add new ones..
  70220. for (i = 0; i < wrapper.getNumDrawables(); ++i)
  70221. {
  70222. const ValueTree newDrawable (wrapper.getDrawableState (i));
  70223. Drawable* d = drawables[i];
  70224. if (d != 0)
  70225. {
  70226. if (newDrawable.hasType (d->getValueTreeType()))
  70227. {
  70228. const Rectangle<float> area (d->refreshFromValueTree (newDrawable, imageProvider));
  70229. if (! redrawAll)
  70230. damage = damage.getUnion (area);
  70231. }
  70232. else
  70233. {
  70234. if (! redrawAll)
  70235. damage = damage.getUnion (d->getBounds());
  70236. d = createChildFromValueTree (this, newDrawable, imageProvider);
  70237. drawables.set (i, d);
  70238. if (! redrawAll)
  70239. damage = damage.getUnion (d->getBounds());
  70240. }
  70241. }
  70242. else
  70243. {
  70244. d = createChildFromValueTree (this, newDrawable, imageProvider);
  70245. drawables.set (i, d);
  70246. if (! redrawAll)
  70247. damage = damage.getUnion (d->getBounds());
  70248. }
  70249. }
  70250. invalidatePoints();
  70251. if (redrawAll)
  70252. damage = damage.getUnion (getBounds());
  70253. else if (! damage.isEmpty())
  70254. damage = damage.transformed (calculateTransform());
  70255. return damage;
  70256. }
  70257. const ValueTree DrawableComposite::createValueTree (ImageProvider* imageProvider) const
  70258. {
  70259. ValueTree tree (valueTreeType);
  70260. ValueTreeWrapper v (tree);
  70261. v.setID (getName(), 0);
  70262. v.setBoundingBox (bounds, 0);
  70263. int i;
  70264. for (i = 0; i < drawables.size(); ++i)
  70265. v.addDrawable (drawables.getUnchecked(i)->createValueTree (imageProvider), -1, 0);
  70266. for (i = 0; i < markersX.size(); ++i)
  70267. v.setMarker (true, *markersX.getUnchecked(i), 0);
  70268. for (i = 0; i < markersY.size(); ++i)
  70269. v.setMarker (false, *markersY.getUnchecked(i), 0);
  70270. return tree;
  70271. }
  70272. END_JUCE_NAMESPACE
  70273. /*** End of inlined file: juce_DrawableComposite.cpp ***/
  70274. /*** Start of inlined file: juce_DrawableImage.cpp ***/
  70275. BEGIN_JUCE_NAMESPACE
  70276. DrawableImage::DrawableImage()
  70277. : image (0),
  70278. opacity (1.0f),
  70279. overlayColour (0x00000000)
  70280. {
  70281. bounds.topRight = RelativePoint (Point<float> (1.0f, 0.0f));
  70282. bounds.bottomLeft = RelativePoint (Point<float> (0.0f, 1.0f));
  70283. }
  70284. DrawableImage::DrawableImage (const DrawableImage& other)
  70285. : image (other.image),
  70286. opacity (other.opacity),
  70287. overlayColour (other.overlayColour),
  70288. bounds (other.bounds)
  70289. {
  70290. }
  70291. DrawableImage::~DrawableImage()
  70292. {
  70293. }
  70294. void DrawableImage::setImage (const Image& imageToUse)
  70295. {
  70296. image = imageToUse;
  70297. if (image.isValid())
  70298. {
  70299. bounds.topLeft = RelativePoint (Point<float> (0.0f, 0.0f));
  70300. bounds.topRight = RelativePoint (Point<float> ((float) image.getWidth(), 0.0f));
  70301. bounds.bottomLeft = RelativePoint (Point<float> (0.0f, (float) image.getHeight()));
  70302. }
  70303. }
  70304. void DrawableImage::setOpacity (const float newOpacity)
  70305. {
  70306. opacity = newOpacity;
  70307. }
  70308. void DrawableImage::setOverlayColour (const Colour& newOverlayColour)
  70309. {
  70310. overlayColour = newOverlayColour;
  70311. }
  70312. void DrawableImage::setBoundingBox (const RelativeParallelogram& newBounds)
  70313. {
  70314. bounds = newBounds;
  70315. }
  70316. const AffineTransform DrawableImage::calculateTransform() const
  70317. {
  70318. if (image.isNull())
  70319. return AffineTransform::identity;
  70320. Point<float> resolved[3];
  70321. bounds.resolveThreePoints (resolved, parent);
  70322. const Point<float> tr (resolved[0] + (resolved[1] - resolved[0]) / (float) image.getWidth());
  70323. const Point<float> bl (resolved[0] + (resolved[2] - resolved[0]) / (float) image.getHeight());
  70324. return AffineTransform::fromTargetPoints (resolved[0].getX(), resolved[0].getY(),
  70325. tr.getX(), tr.getY(),
  70326. bl.getX(), bl.getY());
  70327. }
  70328. void DrawableImage::render (const Drawable::RenderingContext& context) const
  70329. {
  70330. if (image.isValid())
  70331. {
  70332. const AffineTransform t (calculateTransform().followedBy (context.transform));
  70333. if (opacity > 0.0f && ! overlayColour.isOpaque())
  70334. {
  70335. context.g.setOpacity (context.opacity * opacity);
  70336. context.g.drawImageTransformed (image, t, false);
  70337. }
  70338. if (! overlayColour.isTransparent())
  70339. {
  70340. context.g.setColour (overlayColour.withMultipliedAlpha (context.opacity));
  70341. context.g.drawImageTransformed (image, t, true);
  70342. }
  70343. }
  70344. }
  70345. const Rectangle<float> DrawableImage::getBounds() const
  70346. {
  70347. if (image.isNull())
  70348. return Rectangle<float>();
  70349. return bounds.getBounds (parent);
  70350. }
  70351. bool DrawableImage::hitTest (float x, float y) const
  70352. {
  70353. if (image.isNull())
  70354. return false;
  70355. calculateTransform().inverted().transformPoint (x, y);
  70356. const int ix = roundToInt (x);
  70357. const int iy = roundToInt (y);
  70358. return ix >= 0
  70359. && iy >= 0
  70360. && ix < image.getWidth()
  70361. && iy < image.getHeight()
  70362. && image.getPixelAt (ix, iy).getAlpha() >= 127;
  70363. }
  70364. Drawable* DrawableImage::createCopy() const
  70365. {
  70366. return new DrawableImage (*this);
  70367. }
  70368. void DrawableImage::invalidatePoints()
  70369. {
  70370. }
  70371. const Identifier DrawableImage::valueTreeType ("Image");
  70372. const Identifier DrawableImage::ValueTreeWrapper::opacity ("opacity");
  70373. const Identifier DrawableImage::ValueTreeWrapper::overlay ("overlay");
  70374. const Identifier DrawableImage::ValueTreeWrapper::image ("image");
  70375. const Identifier DrawableImage::ValueTreeWrapper::topLeft ("topLeft");
  70376. const Identifier DrawableImage::ValueTreeWrapper::topRight ("topRight");
  70377. const Identifier DrawableImage::ValueTreeWrapper::bottomLeft ("bottomLeft");
  70378. DrawableImage::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70379. : ValueTreeWrapperBase (state_)
  70380. {
  70381. jassert (state.hasType (valueTreeType));
  70382. }
  70383. const var DrawableImage::ValueTreeWrapper::getImageIdentifier() const
  70384. {
  70385. return state [image];
  70386. }
  70387. Value DrawableImage::ValueTreeWrapper::getImageIdentifierValue (UndoManager* undoManager)
  70388. {
  70389. return state.getPropertyAsValue (image, undoManager);
  70390. }
  70391. void DrawableImage::ValueTreeWrapper::setImageIdentifier (const var& newIdentifier, UndoManager* undoManager)
  70392. {
  70393. state.setProperty (image, newIdentifier, undoManager);
  70394. }
  70395. float DrawableImage::ValueTreeWrapper::getOpacity() const
  70396. {
  70397. return (float) state.getProperty (opacity, 1.0);
  70398. }
  70399. Value DrawableImage::ValueTreeWrapper::getOpacityValue (UndoManager* undoManager)
  70400. {
  70401. if (! state.hasProperty (opacity))
  70402. state.setProperty (opacity, 1.0, undoManager);
  70403. return state.getPropertyAsValue (opacity, undoManager);
  70404. }
  70405. void DrawableImage::ValueTreeWrapper::setOpacity (float newOpacity, UndoManager* undoManager)
  70406. {
  70407. state.setProperty (opacity, newOpacity, undoManager);
  70408. }
  70409. const Colour DrawableImage::ValueTreeWrapper::getOverlayColour() const
  70410. {
  70411. return Colour (state [overlay].toString().getHexValue32());
  70412. }
  70413. void DrawableImage::ValueTreeWrapper::setOverlayColour (const Colour& newColour, UndoManager* undoManager)
  70414. {
  70415. if (newColour.isTransparent())
  70416. state.removeProperty (overlay, undoManager);
  70417. else
  70418. state.setProperty (overlay, String::toHexString ((int) newColour.getARGB()), undoManager);
  70419. }
  70420. Value DrawableImage::ValueTreeWrapper::getOverlayColourValue (UndoManager* undoManager)
  70421. {
  70422. return state.getPropertyAsValue (overlay, undoManager);
  70423. }
  70424. const RelativeParallelogram DrawableImage::ValueTreeWrapper::getBoundingBox() const
  70425. {
  70426. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  70427. state.getProperty (topRight, "100, 0"),
  70428. state.getProperty (bottomLeft, "0, 100"));
  70429. }
  70430. void DrawableImage::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  70431. {
  70432. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  70433. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  70434. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  70435. }
  70436. const Rectangle<float> DrawableImage::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  70437. {
  70438. const ValueTreeWrapper controller (tree);
  70439. setName (controller.getID());
  70440. const float newOpacity = controller.getOpacity();
  70441. const Colour newOverlayColour (controller.getOverlayColour());
  70442. Image newImage;
  70443. const var imageIdentifier (controller.getImageIdentifier());
  70444. jassert (imageProvider != 0 || imageIdentifier.isVoid()); // if you're using images, you need to provide something that can load and save them!
  70445. if (imageProvider != 0)
  70446. newImage = imageProvider->getImageForIdentifier (imageIdentifier);
  70447. const RelativeParallelogram newBounds (controller.getBoundingBox());
  70448. if (newOpacity != opacity || overlayColour != newOverlayColour || image != newImage || bounds != newBounds)
  70449. {
  70450. const Rectangle<float> damage (getBounds());
  70451. opacity = newOpacity;
  70452. overlayColour = newOverlayColour;
  70453. bounds = newBounds;
  70454. image = newImage;
  70455. return damage.getUnion (getBounds());
  70456. }
  70457. return Rectangle<float>();
  70458. }
  70459. const ValueTree DrawableImage::createValueTree (ImageProvider* imageProvider) const
  70460. {
  70461. ValueTree tree (valueTreeType);
  70462. ValueTreeWrapper v (tree);
  70463. v.setID (getName(), 0);
  70464. v.setOpacity (opacity, 0);
  70465. v.setOverlayColour (overlayColour, 0);
  70466. v.setBoundingBox (bounds, 0);
  70467. if (image.isValid())
  70468. {
  70469. jassert (imageProvider != 0); // if you're using images, you need to provide something that can load and save them!
  70470. if (imageProvider != 0)
  70471. v.setImageIdentifier (imageProvider->getIdentifierForImage (image), 0);
  70472. }
  70473. return tree;
  70474. }
  70475. END_JUCE_NAMESPACE
  70476. /*** End of inlined file: juce_DrawableImage.cpp ***/
  70477. /*** Start of inlined file: juce_DrawablePath.cpp ***/
  70478. BEGIN_JUCE_NAMESPACE
  70479. DrawablePath::DrawablePath()
  70480. {
  70481. }
  70482. DrawablePath::DrawablePath (const DrawablePath& other)
  70483. : DrawableShape (other)
  70484. {
  70485. if (other.relativePath != 0)
  70486. relativePath = new RelativePointPath (*other.relativePath);
  70487. else
  70488. cachedPath = other.cachedPath;
  70489. }
  70490. DrawablePath::~DrawablePath()
  70491. {
  70492. }
  70493. Drawable* DrawablePath::createCopy() const
  70494. {
  70495. return new DrawablePath (*this);
  70496. }
  70497. void DrawablePath::setPath (const Path& newPath)
  70498. {
  70499. cachedPath = newPath;
  70500. strokeChanged();
  70501. }
  70502. const Path& DrawablePath::getPath() const
  70503. {
  70504. return getCachedPath();
  70505. }
  70506. const Path& DrawablePath::getStrokePath() const
  70507. {
  70508. return getCachedStrokePath();
  70509. }
  70510. bool DrawablePath::rebuildPath (Path& path) const
  70511. {
  70512. if (relativePath != 0)
  70513. {
  70514. path.clear();
  70515. relativePath->createPath (path, parent);
  70516. return true;
  70517. }
  70518. return false;
  70519. }
  70520. const Identifier DrawablePath::valueTreeType ("Path");
  70521. const Identifier DrawablePath::ValueTreeWrapper::nonZeroWinding ("nonZeroWinding");
  70522. const Identifier DrawablePath::ValueTreeWrapper::point1 ("p1");
  70523. const Identifier DrawablePath::ValueTreeWrapper::point2 ("p2");
  70524. const Identifier DrawablePath::ValueTreeWrapper::point3 ("p3");
  70525. DrawablePath::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70526. : FillAndStrokeState (state_)
  70527. {
  70528. jassert (state.hasType (valueTreeType));
  70529. }
  70530. ValueTree DrawablePath::ValueTreeWrapper::getPathState()
  70531. {
  70532. return state.getOrCreateChildWithName (path, 0);
  70533. }
  70534. bool DrawablePath::ValueTreeWrapper::usesNonZeroWinding() const
  70535. {
  70536. return state [nonZeroWinding];
  70537. }
  70538. void DrawablePath::ValueTreeWrapper::setUsesNonZeroWinding (bool b, UndoManager* undoManager)
  70539. {
  70540. state.setProperty (nonZeroWinding, b, undoManager);
  70541. }
  70542. const Identifier DrawablePath::ValueTreeWrapper::Element::mode ("mode");
  70543. const Identifier DrawablePath::ValueTreeWrapper::Element::startSubPathElement ("Move");
  70544. const Identifier DrawablePath::ValueTreeWrapper::Element::closeSubPathElement ("Close");
  70545. const Identifier DrawablePath::ValueTreeWrapper::Element::lineToElement ("Line");
  70546. const Identifier DrawablePath::ValueTreeWrapper::Element::quadraticToElement ("Quad");
  70547. const Identifier DrawablePath::ValueTreeWrapper::Element::cubicToElement ("Cubic");
  70548. const char* DrawablePath::ValueTreeWrapper::Element::cornerMode = "corner";
  70549. const char* DrawablePath::ValueTreeWrapper::Element::roundedMode = "round";
  70550. const char* DrawablePath::ValueTreeWrapper::Element::symmetricMode = "symm";
  70551. DrawablePath::ValueTreeWrapper::Element::Element (const ValueTree& state_)
  70552. : state (state_)
  70553. {
  70554. }
  70555. DrawablePath::ValueTreeWrapper::Element::~Element()
  70556. {
  70557. }
  70558. DrawablePath::ValueTreeWrapper DrawablePath::ValueTreeWrapper::Element::getParent() const
  70559. {
  70560. return ValueTreeWrapper (state.getParent().getParent());
  70561. }
  70562. DrawablePath::ValueTreeWrapper::Element DrawablePath::ValueTreeWrapper::Element::getPreviousElement() const
  70563. {
  70564. return Element (state.getSibling (-1));
  70565. }
  70566. int DrawablePath::ValueTreeWrapper::Element::getNumControlPoints() const throw()
  70567. {
  70568. const Identifier i (state.getType());
  70569. if (i == startSubPathElement || i == lineToElement) return 1;
  70570. if (i == quadraticToElement) return 2;
  70571. if (i == cubicToElement) return 3;
  70572. return 0;
  70573. }
  70574. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getControlPoint (const int index) const
  70575. {
  70576. jassert (index >= 0 && index < getNumControlPoints());
  70577. return RelativePoint (state [index == 0 ? point1 : (index == 1 ? point2 : point3)].toString());
  70578. }
  70579. Value DrawablePath::ValueTreeWrapper::Element::getControlPointValue (int index, UndoManager* undoManager) const
  70580. {
  70581. jassert (index >= 0 && index < getNumControlPoints());
  70582. return state.getPropertyAsValue (index == 0 ? point1 : (index == 1 ? point2 : point3), undoManager);
  70583. }
  70584. void DrawablePath::ValueTreeWrapper::Element::setControlPoint (const int index, const RelativePoint& point, UndoManager* undoManager)
  70585. {
  70586. jassert (index >= 0 && index < getNumControlPoints());
  70587. return state.setProperty (index == 0 ? point1 : (index == 1 ? point2 : point3), point.toString(), undoManager);
  70588. }
  70589. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getStartPoint() const
  70590. {
  70591. const Identifier i (state.getType());
  70592. if (i == startSubPathElement)
  70593. return getControlPoint (0);
  70594. jassert (i == lineToElement || i == quadraticToElement || i == cubicToElement || i == closeSubPathElement);
  70595. return getPreviousElement().getEndPoint();
  70596. }
  70597. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getEndPoint() const
  70598. {
  70599. const Identifier i (state.getType());
  70600. if (i == startSubPathElement || i == lineToElement) return getControlPoint (0);
  70601. if (i == quadraticToElement) return getControlPoint (1);
  70602. if (i == cubicToElement) return getControlPoint (2);
  70603. jassert (i == closeSubPathElement);
  70604. return RelativePoint();
  70605. }
  70606. float DrawablePath::ValueTreeWrapper::Element::getLength (Expression::EvaluationContext* nameFinder) const
  70607. {
  70608. const Identifier i (state.getType());
  70609. if (i == lineToElement || i == closeSubPathElement)
  70610. return getEndPoint().resolve (nameFinder).getDistanceFrom (getStartPoint().resolve (nameFinder));
  70611. if (i == cubicToElement)
  70612. {
  70613. Path p;
  70614. p.startNewSubPath (getStartPoint().resolve (nameFinder));
  70615. p.cubicTo (getControlPoint (0).resolve (nameFinder), getControlPoint (1).resolve (nameFinder), getControlPoint (2).resolve (nameFinder));
  70616. return p.getLength();
  70617. }
  70618. if (i == quadraticToElement)
  70619. {
  70620. Path p;
  70621. p.startNewSubPath (getStartPoint().resolve (nameFinder));
  70622. p.quadraticTo (getControlPoint (0).resolve (nameFinder), getControlPoint (1).resolve (nameFinder));
  70623. return p.getLength();
  70624. }
  70625. jassert (i == startSubPathElement);
  70626. return 0;
  70627. }
  70628. const String DrawablePath::ValueTreeWrapper::Element::getModeOfEndPoint() const
  70629. {
  70630. return state [mode].toString();
  70631. }
  70632. void DrawablePath::ValueTreeWrapper::Element::setModeOfEndPoint (const String& newMode, UndoManager* undoManager)
  70633. {
  70634. if (state.hasType (cubicToElement))
  70635. state.setProperty (mode, newMode, undoManager);
  70636. }
  70637. void DrawablePath::ValueTreeWrapper::Element::convertToLine (UndoManager* undoManager)
  70638. {
  70639. const Identifier i (state.getType());
  70640. if (i == quadraticToElement || i == cubicToElement)
  70641. {
  70642. ValueTree newState (lineToElement);
  70643. Element e (newState);
  70644. e.setControlPoint (0, getEndPoint(), undoManager);
  70645. state = newState;
  70646. }
  70647. }
  70648. void DrawablePath::ValueTreeWrapper::Element::convertToCubic (Expression::EvaluationContext* nameFinder, UndoManager* undoManager)
  70649. {
  70650. const Identifier i (state.getType());
  70651. if (i == lineToElement || i == quadraticToElement)
  70652. {
  70653. ValueTree newState (cubicToElement);
  70654. Element e (newState);
  70655. const RelativePoint start (getStartPoint());
  70656. const RelativePoint end (getEndPoint());
  70657. const Point<float> startResolved (start.resolve (nameFinder));
  70658. const Point<float> endResolved (end.resolve (nameFinder));
  70659. e.setControlPoint (0, startResolved + (endResolved - startResolved) * 0.3f, undoManager);
  70660. e.setControlPoint (1, startResolved + (endResolved - startResolved) * 0.7f, undoManager);
  70661. e.setControlPoint (2, end, undoManager);
  70662. state = newState;
  70663. }
  70664. }
  70665. void DrawablePath::ValueTreeWrapper::Element::convertToPathBreak (UndoManager* undoManager)
  70666. {
  70667. const Identifier i (state.getType());
  70668. if (i != startSubPathElement)
  70669. {
  70670. ValueTree newState (startSubPathElement);
  70671. Element e (newState);
  70672. e.setControlPoint (0, getEndPoint(), undoManager);
  70673. state = newState;
  70674. }
  70675. }
  70676. namespace DrawablePathHelpers
  70677. {
  70678. const Point<float> findCubicSubdivisionPoint (float proportion, const Point<float> points[4])
  70679. {
  70680. const Point<float> mid1 (points[0] + (points[1] - points[0]) * proportion),
  70681. mid2 (points[1] + (points[2] - points[1]) * proportion),
  70682. mid3 (points[2] + (points[3] - points[2]) * proportion);
  70683. const Point<float> newCp1 (mid1 + (mid2 - mid1) * proportion),
  70684. newCp2 (mid2 + (mid3 - mid2) * proportion);
  70685. return newCp1 + (newCp2 - newCp1) * proportion;
  70686. }
  70687. const Point<float> findQuadraticSubdivisionPoint (float proportion, const Point<float> points[3])
  70688. {
  70689. const Point<float> mid1 (points[0] + (points[1] - points[0]) * proportion),
  70690. mid2 (points[1] + (points[2] - points[1]) * proportion);
  70691. return mid1 + (mid2 - mid1) * proportion;
  70692. }
  70693. }
  70694. float DrawablePath::ValueTreeWrapper::Element::findProportionAlongLine (const Point<float>& targetPoint, Expression::EvaluationContext* nameFinder) const
  70695. {
  70696. using namespace DrawablePathHelpers;
  70697. const Identifier i (state.getType());
  70698. float bestProp = 0;
  70699. if (i == cubicToElement)
  70700. {
  70701. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getControlPoint (1)), rp4 (getEndPoint());
  70702. const Point<float> points[] = { rp1.resolve (nameFinder), rp2.resolve (nameFinder), rp3.resolve (nameFinder), rp4.resolve (nameFinder) };
  70703. float bestDistance = std::numeric_limits<float>::max();
  70704. for (int i = 110; --i >= 0;)
  70705. {
  70706. float prop = i > 10 ? ((i - 10) / 100.0f) : (bestProp + ((i - 5) / 1000.0f));
  70707. const Point<float> centre (findCubicSubdivisionPoint (prop, points));
  70708. const float distance = centre.getDistanceFrom (targetPoint);
  70709. if (distance < bestDistance)
  70710. {
  70711. bestProp = prop;
  70712. bestDistance = distance;
  70713. }
  70714. }
  70715. }
  70716. else if (i == quadraticToElement)
  70717. {
  70718. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getEndPoint());
  70719. const Point<float> points[] = { rp1.resolve (nameFinder), rp2.resolve (nameFinder), rp3.resolve (nameFinder) };
  70720. float bestDistance = std::numeric_limits<float>::max();
  70721. for (int i = 110; --i >= 0;)
  70722. {
  70723. float prop = i > 10 ? ((i - 10) / 100.0f) : (bestProp + ((i - 5) / 1000.0f));
  70724. const Point<float> centre (findQuadraticSubdivisionPoint ((float) prop, points));
  70725. const float distance = centre.getDistanceFrom (targetPoint);
  70726. if (distance < bestDistance)
  70727. {
  70728. bestProp = prop;
  70729. bestDistance = distance;
  70730. }
  70731. }
  70732. }
  70733. else if (i == lineToElement)
  70734. {
  70735. RelativePoint rp1 (getStartPoint()), rp2 (getEndPoint());
  70736. const Line<float> line (rp1.resolve (nameFinder), rp2.resolve (nameFinder));
  70737. bestProp = line.findNearestProportionalPositionTo (targetPoint);
  70738. }
  70739. return bestProp;
  70740. }
  70741. ValueTree DrawablePath::ValueTreeWrapper::Element::insertPoint (const Point<float>& targetPoint, Expression::EvaluationContext* nameFinder, UndoManager* undoManager)
  70742. {
  70743. ValueTree newTree;
  70744. const Identifier i (state.getType());
  70745. if (i == cubicToElement)
  70746. {
  70747. float bestProp = findProportionAlongLine (targetPoint, nameFinder);
  70748. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getControlPoint (1)), rp4 (getEndPoint());
  70749. const Point<float> points[] = { rp1.resolve (nameFinder), rp2.resolve (nameFinder), rp3.resolve (nameFinder), rp4.resolve (nameFinder) };
  70750. const Point<float> mid1 (points[0] + (points[1] - points[0]) * bestProp),
  70751. mid2 (points[1] + (points[2] - points[1]) * bestProp),
  70752. mid3 (points[2] + (points[3] - points[2]) * bestProp);
  70753. const Point<float> newCp1 (mid1 + (mid2 - mid1) * bestProp),
  70754. newCp2 (mid2 + (mid3 - mid2) * bestProp);
  70755. const Point<float> newCentre (newCp1 + (newCp2 - newCp1) * bestProp);
  70756. setControlPoint (0, mid1, undoManager);
  70757. setControlPoint (1, newCp1, undoManager);
  70758. setControlPoint (2, newCentre, undoManager);
  70759. setModeOfEndPoint (roundedMode, undoManager);
  70760. Element newElement (newTree = ValueTree (cubicToElement));
  70761. newElement.setControlPoint (0, newCp2, 0);
  70762. newElement.setControlPoint (1, mid3, 0);
  70763. newElement.setControlPoint (2, rp4, 0);
  70764. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  70765. }
  70766. else if (i == quadraticToElement)
  70767. {
  70768. float bestProp = findProportionAlongLine (targetPoint, nameFinder);
  70769. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getEndPoint());
  70770. const Point<float> points[] = { rp1.resolve (nameFinder), rp2.resolve (nameFinder), rp3.resolve (nameFinder) };
  70771. const Point<float> mid1 (points[0] + (points[1] - points[0]) * bestProp),
  70772. mid2 (points[1] + (points[2] - points[1]) * bestProp);
  70773. const Point<float> newCentre (mid1 + (mid2 - mid1) * bestProp);
  70774. setControlPoint (0, mid1, undoManager);
  70775. setControlPoint (1, newCentre, undoManager);
  70776. setModeOfEndPoint (roundedMode, undoManager);
  70777. Element newElement (newTree = ValueTree (quadraticToElement));
  70778. newElement.setControlPoint (0, mid2, 0);
  70779. newElement.setControlPoint (1, rp3, 0);
  70780. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  70781. }
  70782. else if (i == lineToElement)
  70783. {
  70784. RelativePoint rp1 (getStartPoint()), rp2 (getEndPoint());
  70785. const Line<float> line (rp1.resolve (nameFinder), rp2.resolve (nameFinder));
  70786. const Point<float> newPoint (line.findNearestPointTo (targetPoint));
  70787. setControlPoint (0, newPoint, undoManager);
  70788. Element newElement (newTree = ValueTree (lineToElement));
  70789. newElement.setControlPoint (0, rp2, 0);
  70790. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  70791. }
  70792. else if (i == closeSubPathElement)
  70793. {
  70794. }
  70795. return newTree;
  70796. }
  70797. void DrawablePath::ValueTreeWrapper::Element::removePoint (UndoManager* undoManager)
  70798. {
  70799. state.getParent().removeChild (state, undoManager);
  70800. }
  70801. const Rectangle<float> DrawablePath::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  70802. {
  70803. Rectangle<float> damageRect;
  70804. ValueTreeWrapper v (tree);
  70805. setName (v.getID());
  70806. bool needsRedraw = refreshFillTypes (v, parent, imageProvider);
  70807. ScopedPointer<RelativePointPath> newRelativePath (new RelativePointPath (tree));
  70808. Path newPath;
  70809. newRelativePath->createPath (newPath, parent);
  70810. if (! newRelativePath->containsAnyDynamicPoints())
  70811. newRelativePath = 0;
  70812. const PathStrokeType newStroke (v.getStrokeType());
  70813. if (strokeType != newStroke || cachedPath != newPath)
  70814. {
  70815. damageRect = getBounds();
  70816. cachedPath.swapWithPath (newPath);
  70817. strokeChanged();
  70818. strokeType = newStroke;
  70819. needsRedraw = true;
  70820. }
  70821. relativePath = newRelativePath;
  70822. if (needsRedraw)
  70823. damageRect = damageRect.getUnion (getBounds());
  70824. return damageRect;
  70825. }
  70826. const ValueTree DrawablePath::createValueTree (ImageProvider* imageProvider) const
  70827. {
  70828. ValueTree tree (valueTreeType);
  70829. ValueTreeWrapper v (tree);
  70830. v.setID (getName(), 0);
  70831. writeTo (v, imageProvider, 0);
  70832. if (relativePath != 0)
  70833. {
  70834. relativePath->writeTo (tree, 0);
  70835. }
  70836. else
  70837. {
  70838. RelativePointPath rp (getCachedPath());
  70839. rp.writeTo (tree, 0);
  70840. }
  70841. return tree;
  70842. }
  70843. END_JUCE_NAMESPACE
  70844. /*** End of inlined file: juce_DrawablePath.cpp ***/
  70845. /*** Start of inlined file: juce_DrawableRectangle.cpp ***/
  70846. BEGIN_JUCE_NAMESPACE
  70847. DrawableRectangle::DrawableRectangle()
  70848. {
  70849. }
  70850. DrawableRectangle::DrawableRectangle (const DrawableRectangle& other)
  70851. : DrawableShape (other)
  70852. {
  70853. }
  70854. DrawableRectangle::~DrawableRectangle()
  70855. {
  70856. }
  70857. Drawable* DrawableRectangle::createCopy() const
  70858. {
  70859. return new DrawableRectangle (*this);
  70860. }
  70861. void DrawableRectangle::setRectangle (const RelativeParallelogram& newBounds)
  70862. {
  70863. bounds = newBounds;
  70864. pathChanged();
  70865. strokeChanged();
  70866. }
  70867. void DrawableRectangle::setCornerSize (const RelativePoint& newSize)
  70868. {
  70869. cornerSize = newSize;
  70870. pathChanged();
  70871. strokeChanged();
  70872. }
  70873. bool DrawableRectangle::rebuildPath (Path& path) const
  70874. {
  70875. Point<float> points[3];
  70876. bounds.resolveThreePoints (points, parent);
  70877. const float w = Line<float> (points[0], points[1]).getLength();
  70878. const float h = Line<float> (points[0], points[2]).getLength();
  70879. const float cornerSizeX = (float) cornerSize.x.resolve (parent);
  70880. const float cornerSizeY = (float) cornerSize.y.resolve (parent);
  70881. path.clear();
  70882. if (cornerSizeX > 0 && cornerSizeY > 0)
  70883. path.addRoundedRectangle (0, 0, w, h, cornerSizeX, cornerSizeY);
  70884. else
  70885. path.addRectangle (0, 0, w, h);
  70886. path.applyTransform (AffineTransform::fromTargetPoints (0, 0, points[0].getX(), points[0].getY(),
  70887. w, 0, points[1].getX(), points[1].getY(),
  70888. 0, h, points[2].getX(), points[2].getY()));
  70889. return true;
  70890. }
  70891. const AffineTransform DrawableRectangle::calculateTransform() const
  70892. {
  70893. Point<float> resolved[3];
  70894. bounds.resolveThreePoints (resolved, parent);
  70895. return AffineTransform::fromTargetPoints (resolved[0].getX(), resolved[0].getY(),
  70896. resolved[1].getX(), resolved[1].getY(),
  70897. resolved[2].getX(), resolved[2].getY());
  70898. }
  70899. const Identifier DrawableRectangle::valueTreeType ("Rectangle");
  70900. const Identifier DrawableRectangle::ValueTreeWrapper::topLeft ("topLeft");
  70901. const Identifier DrawableRectangle::ValueTreeWrapper::topRight ("topRight");
  70902. const Identifier DrawableRectangle::ValueTreeWrapper::bottomLeft ("bottomLeft");
  70903. const Identifier DrawableRectangle::ValueTreeWrapper::cornerSize ("cornerSize");
  70904. DrawableRectangle::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70905. : FillAndStrokeState (state_)
  70906. {
  70907. jassert (state.hasType (valueTreeType));
  70908. }
  70909. const RelativeParallelogram DrawableRectangle::ValueTreeWrapper::getRectangle() const
  70910. {
  70911. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  70912. state.getProperty (topRight, "100, 0"),
  70913. state.getProperty (bottomLeft, "0, 100"));
  70914. }
  70915. void DrawableRectangle::ValueTreeWrapper::setRectangle (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  70916. {
  70917. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  70918. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  70919. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  70920. }
  70921. void DrawableRectangle::ValueTreeWrapper::setCornerSize (const RelativePoint& newSize, UndoManager* undoManager)
  70922. {
  70923. state.setProperty (cornerSize, newSize.toString(), undoManager);
  70924. }
  70925. const RelativePoint DrawableRectangle::ValueTreeWrapper::getCornerSize() const
  70926. {
  70927. return RelativePoint (state [cornerSize]);
  70928. }
  70929. Value DrawableRectangle::ValueTreeWrapper::getCornerSizeValue (UndoManager* undoManager) const
  70930. {
  70931. return state.getPropertyAsValue (cornerSize, undoManager);
  70932. }
  70933. const Rectangle<float> DrawableRectangle::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  70934. {
  70935. Rectangle<float> damageRect;
  70936. ValueTreeWrapper v (tree);
  70937. setName (v.getID());
  70938. bool needsRedraw = refreshFillTypes (v, parent, imageProvider);
  70939. RelativeParallelogram newBounds (v.getRectangle());
  70940. const PathStrokeType newStroke (v.getStrokeType());
  70941. const RelativePoint newCornerSize (v.getCornerSize());
  70942. if (strokeType != newStroke || newBounds != bounds || newCornerSize != cornerSize)
  70943. {
  70944. damageRect = getBounds();
  70945. bounds = newBounds;
  70946. strokeType = newStroke;
  70947. cornerSize = newCornerSize;
  70948. pathChanged();
  70949. strokeChanged();
  70950. needsRedraw = true;
  70951. }
  70952. if (needsRedraw)
  70953. damageRect = damageRect.getUnion (getBounds());
  70954. return damageRect;
  70955. }
  70956. const ValueTree DrawableRectangle::createValueTree (ImageProvider* imageProvider) const
  70957. {
  70958. ValueTree tree (valueTreeType);
  70959. ValueTreeWrapper v (tree);
  70960. v.setID (getName(), 0);
  70961. writeTo (v, imageProvider, 0);
  70962. v.setRectangle (bounds, 0);
  70963. v.setCornerSize (cornerSize, 0);
  70964. return tree;
  70965. }
  70966. END_JUCE_NAMESPACE
  70967. /*** End of inlined file: juce_DrawableRectangle.cpp ***/
  70968. /*** Start of inlined file: juce_DrawableText.cpp ***/
  70969. BEGIN_JUCE_NAMESPACE
  70970. DrawableText::DrawableText()
  70971. : colour (Colours::black),
  70972. justification (Justification::centredLeft)
  70973. {
  70974. setBoundingBox (RelativeParallelogram (RelativePoint (0.0f, 0.0f),
  70975. RelativePoint (50.0f, 0.0f),
  70976. RelativePoint (0.0f, 20.0f)));
  70977. setFont (Font (15.0f), true);
  70978. }
  70979. DrawableText::DrawableText (const DrawableText& other)
  70980. : bounds (other.bounds),
  70981. fontSizeControlPoint (other.fontSizeControlPoint),
  70982. font (other.font),
  70983. text (other.text),
  70984. colour (other.colour),
  70985. justification (other.justification)
  70986. {
  70987. }
  70988. DrawableText::~DrawableText()
  70989. {
  70990. }
  70991. void DrawableText::setText (const String& newText)
  70992. {
  70993. text = newText;
  70994. }
  70995. void DrawableText::setColour (const Colour& newColour)
  70996. {
  70997. colour = newColour;
  70998. }
  70999. void DrawableText::setFont (const Font& newFont, bool applySizeAndScale)
  71000. {
  71001. font = newFont;
  71002. if (applySizeAndScale)
  71003. {
  71004. Point<float> corners[3];
  71005. bounds.resolveThreePoints (corners, parent);
  71006. setFontSizeControlPoint (RelativePoint (RelativeParallelogram::getPointForInternalCoord (corners,
  71007. Point<float> (font.getHorizontalScale() * font.getHeight(), font.getHeight()))));
  71008. }
  71009. }
  71010. void DrawableText::setJustification (const Justification& newJustification)
  71011. {
  71012. justification = newJustification;
  71013. }
  71014. void DrawableText::setBoundingBox (const RelativeParallelogram& newBounds)
  71015. {
  71016. bounds = newBounds;
  71017. }
  71018. void DrawableText::setFontSizeControlPoint (const RelativePoint& newPoint)
  71019. {
  71020. fontSizeControlPoint = newPoint;
  71021. }
  71022. void DrawableText::render (const Drawable::RenderingContext& context) const
  71023. {
  71024. Point<float> points[3];
  71025. bounds.resolveThreePoints (points, parent);
  71026. const float w = Line<float> (points[0], points[1]).getLength();
  71027. const float h = Line<float> (points[0], points[2]).getLength();
  71028. const Point<float> fontCoords (bounds.getInternalCoordForPoint (points, fontSizeControlPoint.resolve (parent)));
  71029. const float fontHeight = jlimit (0.01f, jmax (0.01f, h), fontCoords.getY());
  71030. const float fontWidth = jlimit (0.01f, jmax (0.01f, w), fontCoords.getX());
  71031. Font f (font);
  71032. f.setHeight (fontHeight);
  71033. f.setHorizontalScale (fontWidth / fontHeight);
  71034. context.g.setColour (colour.withMultipliedAlpha (context.opacity));
  71035. GlyphArrangement ga;
  71036. ga.addFittedText (f, text, 0, 0, w, h, justification, 0x100000);
  71037. ga.draw (context.g,
  71038. AffineTransform::fromTargetPoints (0, 0, points[0].getX(), points[0].getY(),
  71039. w, 0, points[1].getX(), points[1].getY(),
  71040. 0, h, points[2].getX(), points[2].getY())
  71041. .followedBy (context.transform));
  71042. }
  71043. const Rectangle<float> DrawableText::getBounds() const
  71044. {
  71045. return bounds.getBounds (parent);
  71046. }
  71047. bool DrawableText::hitTest (float x, float y) const
  71048. {
  71049. Path p;
  71050. bounds.getPath (p, parent);
  71051. return p.contains (x, y);
  71052. }
  71053. Drawable* DrawableText::createCopy() const
  71054. {
  71055. return new DrawableText (*this);
  71056. }
  71057. void DrawableText::invalidatePoints()
  71058. {
  71059. }
  71060. const Identifier DrawableText::valueTreeType ("Text");
  71061. const Identifier DrawableText::ValueTreeWrapper::text ("text");
  71062. const Identifier DrawableText::ValueTreeWrapper::colour ("colour");
  71063. const Identifier DrawableText::ValueTreeWrapper::font ("font");
  71064. const Identifier DrawableText::ValueTreeWrapper::justification ("justification");
  71065. const Identifier DrawableText::ValueTreeWrapper::topLeft ("topLeft");
  71066. const Identifier DrawableText::ValueTreeWrapper::topRight ("topRight");
  71067. const Identifier DrawableText::ValueTreeWrapper::bottomLeft ("bottomLeft");
  71068. const Identifier DrawableText::ValueTreeWrapper::fontSizeAnchor ("fontSizeAnchor");
  71069. DrawableText::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  71070. : ValueTreeWrapperBase (state_)
  71071. {
  71072. jassert (state.hasType (valueTreeType));
  71073. }
  71074. const String DrawableText::ValueTreeWrapper::getText() const
  71075. {
  71076. return state [text].toString();
  71077. }
  71078. void DrawableText::ValueTreeWrapper::setText (const String& newText, UndoManager* undoManager)
  71079. {
  71080. state.setProperty (text, newText, undoManager);
  71081. }
  71082. Value DrawableText::ValueTreeWrapper::getTextValue (UndoManager* undoManager)
  71083. {
  71084. return state.getPropertyAsValue (text, undoManager);
  71085. }
  71086. const Colour DrawableText::ValueTreeWrapper::getColour() const
  71087. {
  71088. return Colour::fromString (state [colour].toString());
  71089. }
  71090. void DrawableText::ValueTreeWrapper::setColour (const Colour& newColour, UndoManager* undoManager)
  71091. {
  71092. state.setProperty (colour, newColour.toString(), undoManager);
  71093. }
  71094. const Justification DrawableText::ValueTreeWrapper::getJustification() const
  71095. {
  71096. return Justification ((int) state [justification]);
  71097. }
  71098. void DrawableText::ValueTreeWrapper::setJustification (const Justification& newJustification, UndoManager* undoManager)
  71099. {
  71100. state.setProperty (justification, newJustification.getFlags(), undoManager);
  71101. }
  71102. const Font DrawableText::ValueTreeWrapper::getFont() const
  71103. {
  71104. return Font::fromString (state [font]);
  71105. }
  71106. void DrawableText::ValueTreeWrapper::setFont (const Font& newFont, UndoManager* undoManager)
  71107. {
  71108. state.setProperty (font, newFont.toString(), undoManager);
  71109. }
  71110. Value DrawableText::ValueTreeWrapper::getFontValue (UndoManager* undoManager)
  71111. {
  71112. return state.getPropertyAsValue (font, undoManager);
  71113. }
  71114. const RelativeParallelogram DrawableText::ValueTreeWrapper::getBoundingBox() const
  71115. {
  71116. return RelativeParallelogram (state [topLeft].toString(), state [topRight].toString(), state [bottomLeft].toString());
  71117. }
  71118. void DrawableText::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  71119. {
  71120. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  71121. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  71122. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  71123. }
  71124. const RelativePoint DrawableText::ValueTreeWrapper::getFontSizeControlPoint() const
  71125. {
  71126. return state [fontSizeAnchor].toString();
  71127. }
  71128. void DrawableText::ValueTreeWrapper::setFontSizeControlPoint (const RelativePoint& p, UndoManager* undoManager)
  71129. {
  71130. state.setProperty (fontSizeAnchor, p.toString(), undoManager);
  71131. }
  71132. const Rectangle<float> DrawableText::refreshFromValueTree (const ValueTree& tree, ImageProvider*)
  71133. {
  71134. ValueTreeWrapper v (tree);
  71135. setName (v.getID());
  71136. const RelativeParallelogram newBounds (v.getBoundingBox());
  71137. const RelativePoint newFontPoint (v.getFontSizeControlPoint());
  71138. const Colour newColour (v.getColour());
  71139. const Justification newJustification (v.getJustification());
  71140. const String newText (v.getText());
  71141. const Font newFont (v.getFont());
  71142. if (text != newText || font != newFont || justification != newJustification
  71143. || colour != newColour || bounds != newBounds || newFontPoint != fontSizeControlPoint)
  71144. {
  71145. const Rectangle<float> damage (getBounds());
  71146. setBoundingBox (newBounds);
  71147. setFontSizeControlPoint (newFontPoint);
  71148. setColour (newColour);
  71149. setFont (newFont, false);
  71150. setJustification (newJustification);
  71151. setText (newText);
  71152. return damage.getUnion (getBounds());
  71153. }
  71154. return Rectangle<float>();
  71155. }
  71156. const ValueTree DrawableText::createValueTree (ImageProvider*) const
  71157. {
  71158. ValueTree tree (valueTreeType);
  71159. ValueTreeWrapper v (tree);
  71160. v.setID (getName(), 0);
  71161. v.setText (text, 0);
  71162. v.setFont (font, 0);
  71163. v.setJustification (justification, 0);
  71164. v.setColour (colour, 0);
  71165. v.setBoundingBox (bounds, 0);
  71166. v.setFontSizeControlPoint (fontSizeControlPoint, 0);
  71167. return tree;
  71168. }
  71169. END_JUCE_NAMESPACE
  71170. /*** End of inlined file: juce_DrawableText.cpp ***/
  71171. /*** Start of inlined file: juce_SVGParser.cpp ***/
  71172. BEGIN_JUCE_NAMESPACE
  71173. class SVGState
  71174. {
  71175. public:
  71176. SVGState (const XmlElement* const topLevel)
  71177. : topLevelXml (topLevel),
  71178. elementX (0), elementY (0),
  71179. width (512), height (512),
  71180. viewBoxW (0), viewBoxH (0)
  71181. {
  71182. }
  71183. ~SVGState()
  71184. {
  71185. }
  71186. Drawable* parseSVGElement (const XmlElement& xml)
  71187. {
  71188. if (! xml.hasTagName ("svg"))
  71189. return 0;
  71190. DrawableComposite* const drawable = new DrawableComposite();
  71191. drawable->setName (xml.getStringAttribute ("id"));
  71192. SVGState newState (*this);
  71193. if (xml.hasAttribute ("transform"))
  71194. newState.addTransform (xml);
  71195. newState.elementX = getCoordLength (xml.getStringAttribute ("x", String (newState.elementX)), viewBoxW);
  71196. newState.elementY = getCoordLength (xml.getStringAttribute ("y", String (newState.elementY)), viewBoxH);
  71197. newState.width = getCoordLength (xml.getStringAttribute ("width", String (newState.width)), viewBoxW);
  71198. newState.height = getCoordLength (xml.getStringAttribute ("height", String (newState.height)), viewBoxH);
  71199. if (xml.hasAttribute ("viewBox"))
  71200. {
  71201. const String viewParams (xml.getStringAttribute ("viewBox"));
  71202. int i = 0;
  71203. float vx, vy, vw, vh;
  71204. if (parseCoords (viewParams, vx, vy, i, true)
  71205. && parseCoords (viewParams, vw, vh, i, true)
  71206. && vw > 0
  71207. && vh > 0)
  71208. {
  71209. newState.viewBoxW = vw;
  71210. newState.viewBoxH = vh;
  71211. int placementFlags = 0;
  71212. const String aspect (xml.getStringAttribute ("preserveAspectRatio"));
  71213. if (aspect.containsIgnoreCase ("none"))
  71214. {
  71215. placementFlags = RectanglePlacement::stretchToFit;
  71216. }
  71217. else
  71218. {
  71219. if (aspect.containsIgnoreCase ("slice"))
  71220. placementFlags |= RectanglePlacement::fillDestination;
  71221. if (aspect.containsIgnoreCase ("xMin"))
  71222. placementFlags |= RectanglePlacement::xLeft;
  71223. else if (aspect.containsIgnoreCase ("xMax"))
  71224. placementFlags |= RectanglePlacement::xRight;
  71225. else
  71226. placementFlags |= RectanglePlacement::xMid;
  71227. if (aspect.containsIgnoreCase ("yMin"))
  71228. placementFlags |= RectanglePlacement::yTop;
  71229. else if (aspect.containsIgnoreCase ("yMax"))
  71230. placementFlags |= RectanglePlacement::yBottom;
  71231. else
  71232. placementFlags |= RectanglePlacement::yMid;
  71233. }
  71234. const RectanglePlacement placement (placementFlags);
  71235. newState.transform
  71236. = placement.getTransformToFit (Rectangle<float> (vx, vy, vw, vh),
  71237. Rectangle<float> (0.0f, 0.0f, newState.width, newState.height))
  71238. .followedBy (newState.transform);
  71239. }
  71240. }
  71241. else
  71242. {
  71243. if (viewBoxW == 0)
  71244. newState.viewBoxW = newState.width;
  71245. if (viewBoxH == 0)
  71246. newState.viewBoxH = newState.height;
  71247. }
  71248. newState.parseSubElements (xml, drawable);
  71249. drawable->resetContentAreaAndBoundingBoxToFitChildren();
  71250. return drawable;
  71251. }
  71252. private:
  71253. const XmlElement* const topLevelXml;
  71254. float elementX, elementY, width, height, viewBoxW, viewBoxH;
  71255. AffineTransform transform;
  71256. String cssStyleText;
  71257. void parseSubElements (const XmlElement& xml, DrawableComposite* const parentDrawable)
  71258. {
  71259. forEachXmlChildElement (xml, e)
  71260. {
  71261. Drawable* d = 0;
  71262. if (e->hasTagName ("g")) d = parseGroupElement (*e);
  71263. else if (e->hasTagName ("svg")) d = parseSVGElement (*e);
  71264. else if (e->hasTagName ("path")) d = parsePath (*e);
  71265. else if (e->hasTagName ("rect")) d = parseRect (*e);
  71266. else if (e->hasTagName ("circle")) d = parseCircle (*e);
  71267. else if (e->hasTagName ("ellipse")) d = parseEllipse (*e);
  71268. else if (e->hasTagName ("line")) d = parseLine (*e);
  71269. else if (e->hasTagName ("polyline")) d = parsePolygon (*e, true);
  71270. else if (e->hasTagName ("polygon")) d = parsePolygon (*e, false);
  71271. else if (e->hasTagName ("text")) d = parseText (*e);
  71272. else if (e->hasTagName ("switch")) d = parseSwitch (*e);
  71273. else if (e->hasTagName ("style")) parseCSSStyle (*e);
  71274. parentDrawable->insertDrawable (d);
  71275. }
  71276. }
  71277. DrawableComposite* parseSwitch (const XmlElement& xml)
  71278. {
  71279. const XmlElement* const group = xml.getChildByName ("g");
  71280. if (group != 0)
  71281. return parseGroupElement (*group);
  71282. return 0;
  71283. }
  71284. DrawableComposite* parseGroupElement (const XmlElement& xml)
  71285. {
  71286. DrawableComposite* const drawable = new DrawableComposite();
  71287. drawable->setName (xml.getStringAttribute ("id"));
  71288. if (xml.hasAttribute ("transform"))
  71289. {
  71290. SVGState newState (*this);
  71291. newState.addTransform (xml);
  71292. newState.parseSubElements (xml, drawable);
  71293. }
  71294. else
  71295. {
  71296. parseSubElements (xml, drawable);
  71297. }
  71298. drawable->resetContentAreaAndBoundingBoxToFitChildren();
  71299. return drawable;
  71300. }
  71301. Drawable* parsePath (const XmlElement& xml) const
  71302. {
  71303. const String d (xml.getStringAttribute ("d").trimStart());
  71304. Path path;
  71305. if (getStyleAttribute (&xml, "fill-rule").trim().equalsIgnoreCase ("evenodd"))
  71306. path.setUsingNonZeroWinding (false);
  71307. int index = 0;
  71308. float lastX = 0, lastY = 0;
  71309. float lastX2 = 0, lastY2 = 0;
  71310. juce_wchar lastCommandChar = 0;
  71311. bool isRelative = true;
  71312. bool carryOn = true;
  71313. const String validCommandChars ("MmLlHhVvCcSsQqTtAaZz");
  71314. while (d[index] != 0)
  71315. {
  71316. float x, y, x2, y2, x3, y3;
  71317. if (validCommandChars.containsChar (d[index]))
  71318. {
  71319. lastCommandChar = d [index++];
  71320. isRelative = (lastCommandChar >= 'a' && lastCommandChar <= 'z');
  71321. }
  71322. switch (lastCommandChar)
  71323. {
  71324. case 'M':
  71325. case 'm':
  71326. case 'L':
  71327. case 'l':
  71328. if (parseCoords (d, x, y, index, false))
  71329. {
  71330. if (isRelative)
  71331. {
  71332. x += lastX;
  71333. y += lastY;
  71334. }
  71335. if (lastCommandChar == 'M' || lastCommandChar == 'm')
  71336. {
  71337. path.startNewSubPath (x, y);
  71338. lastCommandChar = 'l';
  71339. }
  71340. else
  71341. path.lineTo (x, y);
  71342. lastX2 = lastX;
  71343. lastY2 = lastY;
  71344. lastX = x;
  71345. lastY = y;
  71346. }
  71347. else
  71348. {
  71349. ++index;
  71350. }
  71351. break;
  71352. case 'H':
  71353. case 'h':
  71354. if (parseCoord (d, x, index, false, true))
  71355. {
  71356. if (isRelative)
  71357. x += lastX;
  71358. path.lineTo (x, lastY);
  71359. lastX2 = lastX;
  71360. lastX = x;
  71361. }
  71362. else
  71363. {
  71364. ++index;
  71365. }
  71366. break;
  71367. case 'V':
  71368. case 'v':
  71369. if (parseCoord (d, y, index, false, false))
  71370. {
  71371. if (isRelative)
  71372. y += lastY;
  71373. path.lineTo (lastX, y);
  71374. lastY2 = lastY;
  71375. lastY = y;
  71376. }
  71377. else
  71378. {
  71379. ++index;
  71380. }
  71381. break;
  71382. case 'C':
  71383. case 'c':
  71384. if (parseCoords (d, x, y, index, false)
  71385. && parseCoords (d, x2, y2, index, false)
  71386. && parseCoords (d, x3, y3, index, false))
  71387. {
  71388. if (isRelative)
  71389. {
  71390. x += lastX;
  71391. y += lastY;
  71392. x2 += lastX;
  71393. y2 += lastY;
  71394. x3 += lastX;
  71395. y3 += lastY;
  71396. }
  71397. path.cubicTo (x, y, x2, y2, x3, y3);
  71398. lastX2 = x2;
  71399. lastY2 = y2;
  71400. lastX = x3;
  71401. lastY = y3;
  71402. }
  71403. else
  71404. {
  71405. ++index;
  71406. }
  71407. break;
  71408. case 'S':
  71409. case 's':
  71410. if (parseCoords (d, x, y, index, false)
  71411. && parseCoords (d, x3, y3, index, false))
  71412. {
  71413. if (isRelative)
  71414. {
  71415. x += lastX;
  71416. y += lastY;
  71417. x3 += lastX;
  71418. y3 += lastY;
  71419. }
  71420. x2 = lastX + (lastX - lastX2);
  71421. y2 = lastY + (lastY - lastY2);
  71422. path.cubicTo (x2, y2, x, y, x3, y3);
  71423. lastX2 = x;
  71424. lastY2 = y;
  71425. lastX = x3;
  71426. lastY = y3;
  71427. }
  71428. else
  71429. {
  71430. ++index;
  71431. }
  71432. break;
  71433. case 'Q':
  71434. case 'q':
  71435. if (parseCoords (d, x, y, index, false)
  71436. && parseCoords (d, x2, y2, index, false))
  71437. {
  71438. if (isRelative)
  71439. {
  71440. x += lastX;
  71441. y += lastY;
  71442. x2 += lastX;
  71443. y2 += lastY;
  71444. }
  71445. path.quadraticTo (x, y, x2, y2);
  71446. lastX2 = x;
  71447. lastY2 = y;
  71448. lastX = x2;
  71449. lastY = y2;
  71450. }
  71451. else
  71452. {
  71453. ++index;
  71454. }
  71455. break;
  71456. case 'T':
  71457. case 't':
  71458. if (parseCoords (d, x, y, index, false))
  71459. {
  71460. if (isRelative)
  71461. {
  71462. x += lastX;
  71463. y += lastY;
  71464. }
  71465. x2 = lastX + (lastX - lastX2);
  71466. y2 = lastY + (lastY - lastY2);
  71467. path.quadraticTo (x2, y2, x, y);
  71468. lastX2 = x2;
  71469. lastY2 = y2;
  71470. lastX = x;
  71471. lastY = y;
  71472. }
  71473. else
  71474. {
  71475. ++index;
  71476. }
  71477. break;
  71478. case 'A':
  71479. case 'a':
  71480. if (parseCoords (d, x, y, index, false))
  71481. {
  71482. String num;
  71483. if (parseNextNumber (d, num, index, false))
  71484. {
  71485. const float angle = num.getFloatValue() * (180.0f / float_Pi);
  71486. if (parseNextNumber (d, num, index, false))
  71487. {
  71488. const bool largeArc = num.getIntValue() != 0;
  71489. if (parseNextNumber (d, num, index, false))
  71490. {
  71491. const bool sweep = num.getIntValue() != 0;
  71492. if (parseCoords (d, x2, y2, index, false))
  71493. {
  71494. if (isRelative)
  71495. {
  71496. x2 += lastX;
  71497. y2 += lastY;
  71498. }
  71499. if (lastX != x2 || lastY != y2)
  71500. {
  71501. double centreX, centreY, startAngle, deltaAngle;
  71502. double rx = x, ry = y;
  71503. endpointToCentreParameters (lastX, lastY, x2, y2,
  71504. angle, largeArc, sweep,
  71505. rx, ry, centreX, centreY,
  71506. startAngle, deltaAngle);
  71507. path.addCentredArc ((float) centreX, (float) centreY,
  71508. (float) rx, (float) ry,
  71509. angle, (float) startAngle, (float) (startAngle + deltaAngle),
  71510. false);
  71511. path.lineTo (x2, y2);
  71512. }
  71513. lastX2 = lastX;
  71514. lastY2 = lastY;
  71515. lastX = x2;
  71516. lastY = y2;
  71517. }
  71518. }
  71519. }
  71520. }
  71521. }
  71522. else
  71523. {
  71524. ++index;
  71525. }
  71526. break;
  71527. case 'Z':
  71528. case 'z':
  71529. path.closeSubPath();
  71530. while (CharacterFunctions::isWhitespace (d [index]))
  71531. ++index;
  71532. break;
  71533. default:
  71534. carryOn = false;
  71535. break;
  71536. }
  71537. if (! carryOn)
  71538. break;
  71539. }
  71540. return parseShape (xml, path);
  71541. }
  71542. Drawable* parseRect (const XmlElement& xml) const
  71543. {
  71544. Path rect;
  71545. const bool hasRX = xml.hasAttribute ("rx");
  71546. const bool hasRY = xml.hasAttribute ("ry");
  71547. if (hasRX || hasRY)
  71548. {
  71549. float rx = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  71550. float ry = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  71551. if (! hasRX)
  71552. rx = ry;
  71553. else if (! hasRY)
  71554. ry = rx;
  71555. rect.addRoundedRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  71556. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  71557. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  71558. getCoordLength (xml.getStringAttribute ("height"), viewBoxH),
  71559. rx, ry);
  71560. }
  71561. else
  71562. {
  71563. rect.addRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  71564. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  71565. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  71566. getCoordLength (xml.getStringAttribute ("height"), viewBoxH));
  71567. }
  71568. return parseShape (xml, rect);
  71569. }
  71570. Drawable* parseCircle (const XmlElement& xml) const
  71571. {
  71572. Path circle;
  71573. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  71574. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  71575. const float radius = getCoordLength (xml.getStringAttribute ("r"), viewBoxW);
  71576. circle.addEllipse (cx - radius, cy - radius, radius * 2.0f, radius * 2.0f);
  71577. return parseShape (xml, circle);
  71578. }
  71579. Drawable* parseEllipse (const XmlElement& xml) const
  71580. {
  71581. Path ellipse;
  71582. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  71583. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  71584. const float radiusX = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  71585. const float radiusY = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  71586. ellipse.addEllipse (cx - radiusX, cy - radiusY, radiusX * 2.0f, radiusY * 2.0f);
  71587. return parseShape (xml, ellipse);
  71588. }
  71589. Drawable* parseLine (const XmlElement& xml) const
  71590. {
  71591. Path line;
  71592. const float x1 = getCoordLength (xml.getStringAttribute ("x1"), viewBoxW);
  71593. const float y1 = getCoordLength (xml.getStringAttribute ("y1"), viewBoxH);
  71594. const float x2 = getCoordLength (xml.getStringAttribute ("x2"), viewBoxW);
  71595. const float y2 = getCoordLength (xml.getStringAttribute ("y2"), viewBoxH);
  71596. line.startNewSubPath (x1, y1);
  71597. line.lineTo (x2, y2);
  71598. return parseShape (xml, line);
  71599. }
  71600. Drawable* parsePolygon (const XmlElement& xml, const bool isPolyline) const
  71601. {
  71602. const String points (xml.getStringAttribute ("points"));
  71603. Path path;
  71604. int index = 0;
  71605. float x, y;
  71606. if (parseCoords (points, x, y, index, true))
  71607. {
  71608. float firstX = x;
  71609. float firstY = y;
  71610. float lastX = 0, lastY = 0;
  71611. path.startNewSubPath (x, y);
  71612. while (parseCoords (points, x, y, index, true))
  71613. {
  71614. lastX = x;
  71615. lastY = y;
  71616. path.lineTo (x, y);
  71617. }
  71618. if ((! isPolyline) || (firstX == lastX && firstY == lastY))
  71619. path.closeSubPath();
  71620. }
  71621. return parseShape (xml, path);
  71622. }
  71623. Drawable* parseShape (const XmlElement& xml, Path& path,
  71624. const bool shouldParseTransform = true) const
  71625. {
  71626. if (shouldParseTransform && xml.hasAttribute ("transform"))
  71627. {
  71628. SVGState newState (*this);
  71629. newState.addTransform (xml);
  71630. return newState.parseShape (xml, path, false);
  71631. }
  71632. DrawablePath* dp = new DrawablePath();
  71633. dp->setName (xml.getStringAttribute ("id"));
  71634. dp->setFill (Colours::transparentBlack);
  71635. path.applyTransform (transform);
  71636. dp->setPath (path);
  71637. Path::Iterator iter (path);
  71638. bool containsClosedSubPath = false;
  71639. while (iter.next())
  71640. {
  71641. if (iter.elementType == Path::Iterator::closePath)
  71642. {
  71643. containsClosedSubPath = true;
  71644. break;
  71645. }
  71646. }
  71647. dp->setFill (getPathFillType (path,
  71648. getStyleAttribute (&xml, "fill"),
  71649. getStyleAttribute (&xml, "fill-opacity"),
  71650. getStyleAttribute (&xml, "opacity"),
  71651. containsClosedSubPath ? Colours::black
  71652. : Colours::transparentBlack));
  71653. const String strokeType (getStyleAttribute (&xml, "stroke"));
  71654. if (strokeType.isNotEmpty() && ! strokeType.equalsIgnoreCase ("none"))
  71655. {
  71656. dp->setStrokeFill (getPathFillType (path, strokeType,
  71657. getStyleAttribute (&xml, "stroke-opacity"),
  71658. getStyleAttribute (&xml, "opacity"),
  71659. Colours::transparentBlack));
  71660. dp->setStrokeType (getStrokeFor (&xml));
  71661. }
  71662. return dp;
  71663. }
  71664. const XmlElement* findLinkedElement (const XmlElement* e) const
  71665. {
  71666. const String id (e->getStringAttribute ("xlink:href"));
  71667. if (! id.startsWithChar ('#'))
  71668. return 0;
  71669. return findElementForId (topLevelXml, id.substring (1));
  71670. }
  71671. void addGradientStopsIn (ColourGradient& cg, const XmlElement* const fillXml) const
  71672. {
  71673. if (fillXml == 0)
  71674. return;
  71675. forEachXmlChildElementWithTagName (*fillXml, e, "stop")
  71676. {
  71677. int index = 0;
  71678. Colour col (parseColour (getStyleAttribute (e, "stop-color"), index, Colours::black));
  71679. const String opacity (getStyleAttribute (e, "stop-opacity", "1"));
  71680. col = col.withMultipliedAlpha (jlimit (0.0f, 1.0f, opacity.getFloatValue()));
  71681. double offset = e->getDoubleAttribute ("offset");
  71682. if (e->getStringAttribute ("offset").containsChar ('%'))
  71683. offset *= 0.01;
  71684. cg.addColour (jlimit (0.0, 1.0, offset), col);
  71685. }
  71686. }
  71687. const FillType getPathFillType (const Path& path,
  71688. const String& fill,
  71689. const String& fillOpacity,
  71690. const String& overallOpacity,
  71691. const Colour& defaultColour) const
  71692. {
  71693. float opacity = 1.0f;
  71694. if (overallOpacity.isNotEmpty())
  71695. opacity = jlimit (0.0f, 1.0f, overallOpacity.getFloatValue());
  71696. if (fillOpacity.isNotEmpty())
  71697. opacity *= (jlimit (0.0f, 1.0f, fillOpacity.getFloatValue()));
  71698. if (fill.startsWithIgnoreCase ("url"))
  71699. {
  71700. const String id (fill.fromFirstOccurrenceOf ("#", false, false)
  71701. .upToLastOccurrenceOf (")", false, false).trim());
  71702. const XmlElement* const fillXml = findElementForId (topLevelXml, id);
  71703. if (fillXml != 0
  71704. && (fillXml->hasTagName ("linearGradient")
  71705. || fillXml->hasTagName ("radialGradient")))
  71706. {
  71707. const XmlElement* inheritedFrom = findLinkedElement (fillXml);
  71708. ColourGradient gradient;
  71709. addGradientStopsIn (gradient, inheritedFrom);
  71710. addGradientStopsIn (gradient, fillXml);
  71711. if (gradient.getNumColours() > 0)
  71712. {
  71713. gradient.addColour (0.0, gradient.getColour (0));
  71714. gradient.addColour (1.0, gradient.getColour (gradient.getNumColours() - 1));
  71715. }
  71716. else
  71717. {
  71718. gradient.addColour (0.0, Colours::black);
  71719. gradient.addColour (1.0, Colours::black);
  71720. }
  71721. if (overallOpacity.isNotEmpty())
  71722. gradient.multiplyOpacity (overallOpacity.getFloatValue());
  71723. jassert (gradient.getNumColours() > 0);
  71724. gradient.isRadial = fillXml->hasTagName ("radialGradient");
  71725. float gradientWidth = viewBoxW;
  71726. float gradientHeight = viewBoxH;
  71727. float dx = 0.0f;
  71728. float dy = 0.0f;
  71729. const bool userSpace = fillXml->getStringAttribute ("gradientUnits").equalsIgnoreCase ("userSpaceOnUse");
  71730. if (! userSpace)
  71731. {
  71732. const Rectangle<float> bounds (path.getBounds());
  71733. dx = bounds.getX();
  71734. dy = bounds.getY();
  71735. gradientWidth = bounds.getWidth();
  71736. gradientHeight = bounds.getHeight();
  71737. }
  71738. if (gradient.isRadial)
  71739. {
  71740. if (userSpace)
  71741. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("cx", "50%"), gradientWidth),
  71742. dy + getCoordLength (fillXml->getStringAttribute ("cy", "50%"), gradientHeight));
  71743. else
  71744. gradient.point1.setXY (dx + gradientWidth * getCoordLength (fillXml->getStringAttribute ("cx", "50%"), 1.0f),
  71745. dy + gradientHeight * getCoordLength (fillXml->getStringAttribute ("cy", "50%"), 1.0f));
  71746. const float radius = getCoordLength (fillXml->getStringAttribute ("r", "50%"), gradientWidth);
  71747. gradient.point2 = gradient.point1 + Point<float> (radius, 0.0f);
  71748. //xxx (the fx, fy focal point isn't handled properly here..)
  71749. }
  71750. else
  71751. {
  71752. if (userSpace)
  71753. {
  71754. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x1", "0%"), gradientWidth),
  71755. dy + getCoordLength (fillXml->getStringAttribute ("y1", "0%"), gradientHeight));
  71756. gradient.point2.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x2", "100%"), gradientWidth),
  71757. dy + getCoordLength (fillXml->getStringAttribute ("y2", "0%"), gradientHeight));
  71758. }
  71759. else
  71760. {
  71761. gradient.point1.setXY (dx + gradientWidth * getCoordLength (fillXml->getStringAttribute ("x1", "0%"), 1.0f),
  71762. dy + gradientHeight * getCoordLength (fillXml->getStringAttribute ("y1", "0%"), 1.0f));
  71763. gradient.point2.setXY (dx + gradientWidth * getCoordLength (fillXml->getStringAttribute ("x2", "100%"), 1.0f),
  71764. dy + gradientHeight * getCoordLength (fillXml->getStringAttribute ("y2", "0%"), 1.0f));
  71765. }
  71766. if (gradient.point1 == gradient.point2)
  71767. return Colour (gradient.getColour (gradient.getNumColours() - 1));
  71768. }
  71769. FillType type (gradient);
  71770. type.transform = parseTransform (fillXml->getStringAttribute ("gradientTransform"))
  71771. .followedBy (transform);
  71772. return type;
  71773. }
  71774. }
  71775. if (fill.equalsIgnoreCase ("none"))
  71776. return Colours::transparentBlack;
  71777. int i = 0;
  71778. const Colour colour (parseColour (fill, i, defaultColour));
  71779. return colour.withMultipliedAlpha (opacity);
  71780. }
  71781. const PathStrokeType getStrokeFor (const XmlElement* const xml) const
  71782. {
  71783. const String strokeWidth (getStyleAttribute (xml, "stroke-width"));
  71784. const String cap (getStyleAttribute (xml, "stroke-linecap"));
  71785. const String join (getStyleAttribute (xml, "stroke-linejoin"));
  71786. //const String mitreLimit (getStyleAttribute (xml, "stroke-miterlimit"));
  71787. //const String dashArray (getStyleAttribute (xml, "stroke-dasharray"));
  71788. //const String dashOffset (getStyleAttribute (xml, "stroke-dashoffset"));
  71789. PathStrokeType::JointStyle joinStyle = PathStrokeType::mitered;
  71790. PathStrokeType::EndCapStyle capStyle = PathStrokeType::butt;
  71791. if (join.equalsIgnoreCase ("round"))
  71792. joinStyle = PathStrokeType::curved;
  71793. else if (join.equalsIgnoreCase ("bevel"))
  71794. joinStyle = PathStrokeType::beveled;
  71795. if (cap.equalsIgnoreCase ("round"))
  71796. capStyle = PathStrokeType::rounded;
  71797. else if (cap.equalsIgnoreCase ("square"))
  71798. capStyle = PathStrokeType::square;
  71799. float ox = 0.0f, oy = 0.0f;
  71800. float x = getCoordLength (strokeWidth, viewBoxW), y = 0.0f;
  71801. transform.transformPoints (ox, oy, x, y);
  71802. return PathStrokeType (strokeWidth.isNotEmpty() ? juce_hypotf (x - ox, y - oy) : 1.0f,
  71803. joinStyle, capStyle);
  71804. }
  71805. Drawable* parseText (const XmlElement& xml)
  71806. {
  71807. Array <float> xCoords, yCoords, dxCoords, dyCoords;
  71808. getCoordList (xCoords, getInheritedAttribute (&xml, "x"), true, true);
  71809. getCoordList (yCoords, getInheritedAttribute (&xml, "y"), true, false);
  71810. getCoordList (dxCoords, getInheritedAttribute (&xml, "dx"), true, true);
  71811. getCoordList (dyCoords, getInheritedAttribute (&xml, "dy"), true, false);
  71812. //xxx not done text yet!
  71813. forEachXmlChildElement (xml, e)
  71814. {
  71815. if (e->isTextElement())
  71816. {
  71817. const String text (e->getText());
  71818. Path path;
  71819. Drawable* s = parseShape (*e, path);
  71820. delete s; // xxx not finished!
  71821. }
  71822. else if (e->hasTagName ("tspan"))
  71823. {
  71824. Drawable* s = parseText (*e);
  71825. delete s; // xxx not finished!
  71826. }
  71827. }
  71828. return 0;
  71829. }
  71830. void addTransform (const XmlElement& xml)
  71831. {
  71832. transform = parseTransform (xml.getStringAttribute ("transform"))
  71833. .followedBy (transform);
  71834. }
  71835. bool parseCoord (const String& s, float& value, int& index,
  71836. const bool allowUnits, const bool isX) const
  71837. {
  71838. String number;
  71839. if (! parseNextNumber (s, number, index, allowUnits))
  71840. {
  71841. value = 0;
  71842. return false;
  71843. }
  71844. value = getCoordLength (number, isX ? viewBoxW : viewBoxH);
  71845. return true;
  71846. }
  71847. bool parseCoords (const String& s, float& x, float& y,
  71848. int& index, const bool allowUnits) const
  71849. {
  71850. return parseCoord (s, x, index, allowUnits, true)
  71851. && parseCoord (s, y, index, allowUnits, false);
  71852. }
  71853. float getCoordLength (const String& s, const float sizeForProportions) const
  71854. {
  71855. float n = s.getFloatValue();
  71856. const int len = s.length();
  71857. if (len > 2)
  71858. {
  71859. const float dpi = 96.0f;
  71860. const juce_wchar n1 = s [len - 2];
  71861. const juce_wchar n2 = s [len - 1];
  71862. if (n1 == 'i' && n2 == 'n')
  71863. n *= dpi;
  71864. else if (n1 == 'm' && n2 == 'm')
  71865. n *= dpi / 25.4f;
  71866. else if (n1 == 'c' && n2 == 'm')
  71867. n *= dpi / 2.54f;
  71868. else if (n1 == 'p' && n2 == 'c')
  71869. n *= 15.0f;
  71870. else if (n2 == '%')
  71871. n *= 0.01f * sizeForProportions;
  71872. }
  71873. return n;
  71874. }
  71875. void getCoordList (Array <float>& coords, const String& list,
  71876. const bool allowUnits, const bool isX) const
  71877. {
  71878. int index = 0;
  71879. float value;
  71880. while (parseCoord (list, value, index, allowUnits, isX))
  71881. coords.add (value);
  71882. }
  71883. void parseCSSStyle (const XmlElement& xml)
  71884. {
  71885. cssStyleText = xml.getAllSubText() + "\n" + cssStyleText;
  71886. }
  71887. const String getStyleAttribute (const XmlElement* xml, const String& attributeName,
  71888. const String& defaultValue = String::empty) const
  71889. {
  71890. if (xml->hasAttribute (attributeName))
  71891. return xml->getStringAttribute (attributeName, defaultValue);
  71892. const String styleAtt (xml->getStringAttribute ("style"));
  71893. if (styleAtt.isNotEmpty())
  71894. {
  71895. const String value (getAttributeFromStyleList (styleAtt, attributeName, String::empty));
  71896. if (value.isNotEmpty())
  71897. return value;
  71898. }
  71899. else if (xml->hasAttribute ("class"))
  71900. {
  71901. const String className ("." + xml->getStringAttribute ("class"));
  71902. int index = cssStyleText.indexOfIgnoreCase (className + " ");
  71903. if (index < 0)
  71904. index = cssStyleText.indexOfIgnoreCase (className + "{");
  71905. if (index >= 0)
  71906. {
  71907. const int openBracket = cssStyleText.indexOfChar (index, '{');
  71908. if (openBracket > index)
  71909. {
  71910. const int closeBracket = cssStyleText.indexOfChar (openBracket, '}');
  71911. if (closeBracket > openBracket)
  71912. {
  71913. const String value (getAttributeFromStyleList (cssStyleText.substring (openBracket + 1, closeBracket), attributeName, defaultValue));
  71914. if (value.isNotEmpty())
  71915. return value;
  71916. }
  71917. }
  71918. }
  71919. }
  71920. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  71921. if (xml != 0)
  71922. return getStyleAttribute (xml, attributeName, defaultValue);
  71923. return defaultValue;
  71924. }
  71925. const String getInheritedAttribute (const XmlElement* xml, const String& attributeName) const
  71926. {
  71927. if (xml->hasAttribute (attributeName))
  71928. return xml->getStringAttribute (attributeName);
  71929. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  71930. if (xml != 0)
  71931. return getInheritedAttribute (xml, attributeName);
  71932. return String::empty;
  71933. }
  71934. static bool isIdentifierChar (const juce_wchar c)
  71935. {
  71936. return CharacterFunctions::isLetter (c) || c == '-';
  71937. }
  71938. static const String getAttributeFromStyleList (const String& list, const String& attributeName, const String& defaultValue)
  71939. {
  71940. int i = 0;
  71941. for (;;)
  71942. {
  71943. i = list.indexOf (i, attributeName);
  71944. if (i < 0)
  71945. break;
  71946. if ((i == 0 || (i > 0 && ! isIdentifierChar (list [i - 1])))
  71947. && ! isIdentifierChar (list [i + attributeName.length()]))
  71948. {
  71949. i = list.indexOfChar (i, ':');
  71950. if (i < 0)
  71951. break;
  71952. int end = list.indexOfChar (i, ';');
  71953. if (end < 0)
  71954. end = 0x7ffff;
  71955. return list.substring (i + 1, end).trim();
  71956. }
  71957. ++i;
  71958. }
  71959. return defaultValue;
  71960. }
  71961. static bool parseNextNumber (const String& source, String& value, int& index, const bool allowUnits)
  71962. {
  71963. const juce_wchar* const s = source;
  71964. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == ',')
  71965. ++index;
  71966. int start = index;
  71967. if (CharacterFunctions::isDigit (s[index]) || s[index] == '.' || s[index] == '-')
  71968. ++index;
  71969. while (CharacterFunctions::isDigit (s[index]) || s[index] == '.')
  71970. ++index;
  71971. if ((s[index] == 'e' || s[index] == 'E')
  71972. && (CharacterFunctions::isDigit (s[index + 1])
  71973. || s[index + 1] == '-'
  71974. || s[index + 1] == '+'))
  71975. {
  71976. index += 2;
  71977. while (CharacterFunctions::isDigit (s[index]))
  71978. ++index;
  71979. }
  71980. if (allowUnits)
  71981. {
  71982. while (CharacterFunctions::isLetter (s[index]))
  71983. ++index;
  71984. }
  71985. if (index == start)
  71986. return false;
  71987. value = String (s + start, index - start);
  71988. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == ',')
  71989. ++index;
  71990. return true;
  71991. }
  71992. static const Colour parseColour (const String& s, int& index, const Colour& defaultColour)
  71993. {
  71994. if (s [index] == '#')
  71995. {
  71996. uint32 hex [6];
  71997. zeromem (hex, sizeof (hex));
  71998. int numChars = 0;
  71999. for (int i = 6; --i >= 0;)
  72000. {
  72001. const int hexValue = CharacterFunctions::getHexDigitValue (s [++index]);
  72002. if (hexValue >= 0)
  72003. hex [numChars++] = hexValue;
  72004. else
  72005. break;
  72006. }
  72007. if (numChars <= 3)
  72008. return Colour ((uint8) (hex [0] * 0x11),
  72009. (uint8) (hex [1] * 0x11),
  72010. (uint8) (hex [2] * 0x11));
  72011. else
  72012. return Colour ((uint8) ((hex [0] << 4) + hex [1]),
  72013. (uint8) ((hex [2] << 4) + hex [3]),
  72014. (uint8) ((hex [4] << 4) + hex [5]));
  72015. }
  72016. else if (s [index] == 'r'
  72017. && s [index + 1] == 'g'
  72018. && s [index + 2] == 'b')
  72019. {
  72020. const int openBracket = s.indexOfChar (index, '(');
  72021. const int closeBracket = s.indexOfChar (openBracket, ')');
  72022. if (openBracket >= 3 && closeBracket > openBracket)
  72023. {
  72024. index = closeBracket;
  72025. StringArray tokens;
  72026. tokens.addTokens (s.substring (openBracket + 1, closeBracket), ",", "");
  72027. tokens.trim();
  72028. tokens.removeEmptyStrings();
  72029. if (tokens[0].containsChar ('%'))
  72030. return Colour ((uint8) roundToInt (2.55 * tokens[0].getDoubleValue()),
  72031. (uint8) roundToInt (2.55 * tokens[1].getDoubleValue()),
  72032. (uint8) roundToInt (2.55 * tokens[2].getDoubleValue()));
  72033. else
  72034. return Colour ((uint8) tokens[0].getIntValue(),
  72035. (uint8) tokens[1].getIntValue(),
  72036. (uint8) tokens[2].getIntValue());
  72037. }
  72038. }
  72039. return Colours::findColourForName (s, defaultColour);
  72040. }
  72041. static const AffineTransform parseTransform (String t)
  72042. {
  72043. AffineTransform result;
  72044. while (t.isNotEmpty())
  72045. {
  72046. StringArray tokens;
  72047. tokens.addTokens (t.fromFirstOccurrenceOf ("(", false, false)
  72048. .upToFirstOccurrenceOf (")", false, false),
  72049. ", ", String::empty);
  72050. tokens.removeEmptyStrings (true);
  72051. float numbers [6];
  72052. for (int i = 0; i < 6; ++i)
  72053. numbers[i] = tokens[i].getFloatValue();
  72054. AffineTransform trans;
  72055. if (t.startsWithIgnoreCase ("matrix"))
  72056. {
  72057. trans = AffineTransform (numbers[0], numbers[2], numbers[4],
  72058. numbers[1], numbers[3], numbers[5]);
  72059. }
  72060. else if (t.startsWithIgnoreCase ("translate"))
  72061. {
  72062. jassert (tokens.size() == 2);
  72063. trans = AffineTransform::translation (numbers[0], numbers[1]);
  72064. }
  72065. else if (t.startsWithIgnoreCase ("scale"))
  72066. {
  72067. if (tokens.size() == 1)
  72068. trans = AffineTransform::scale (numbers[0], numbers[0]);
  72069. else
  72070. trans = AffineTransform::scale (numbers[0], numbers[1]);
  72071. }
  72072. else if (t.startsWithIgnoreCase ("rotate"))
  72073. {
  72074. if (tokens.size() != 3)
  72075. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi));
  72076. else
  72077. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi),
  72078. numbers[1], numbers[2]);
  72079. }
  72080. else if (t.startsWithIgnoreCase ("skewX"))
  72081. {
  72082. trans = AffineTransform (1.0f, std::tan (numbers[0] * (float_Pi / 180.0f)), 0.0f,
  72083. 0.0f, 1.0f, 0.0f);
  72084. }
  72085. else if (t.startsWithIgnoreCase ("skewY"))
  72086. {
  72087. trans = AffineTransform (1.0f, 0.0f, 0.0f,
  72088. std::tan (numbers[0] * (float_Pi / 180.0f)), 1.0f, 0.0f);
  72089. }
  72090. result = trans.followedBy (result);
  72091. t = t.fromFirstOccurrenceOf (")", false, false).trimStart();
  72092. }
  72093. return result;
  72094. }
  72095. static void endpointToCentreParameters (const double x1, const double y1,
  72096. const double x2, const double y2,
  72097. const double angle,
  72098. const bool largeArc, const bool sweep,
  72099. double& rx, double& ry,
  72100. double& centreX, double& centreY,
  72101. double& startAngle, double& deltaAngle)
  72102. {
  72103. const double midX = (x1 - x2) * 0.5;
  72104. const double midY = (y1 - y2) * 0.5;
  72105. const double cosAngle = cos (angle);
  72106. const double sinAngle = sin (angle);
  72107. const double xp = cosAngle * midX + sinAngle * midY;
  72108. const double yp = cosAngle * midY - sinAngle * midX;
  72109. const double xp2 = xp * xp;
  72110. const double yp2 = yp * yp;
  72111. double rx2 = rx * rx;
  72112. double ry2 = ry * ry;
  72113. const double s = (xp2 / rx2) + (yp2 / ry2);
  72114. double c;
  72115. if (s <= 1.0)
  72116. {
  72117. c = std::sqrt (jmax (0.0, ((rx2 * ry2) - (rx2 * yp2) - (ry2 * xp2))
  72118. / (( rx2 * yp2) + (ry2 * xp2))));
  72119. if (largeArc == sweep)
  72120. c = -c;
  72121. }
  72122. else
  72123. {
  72124. const double s2 = std::sqrt (s);
  72125. rx *= s2;
  72126. ry *= s2;
  72127. rx2 = rx * rx;
  72128. ry2 = ry * ry;
  72129. c = 0;
  72130. }
  72131. const double cpx = ((rx * yp) / ry) * c;
  72132. const double cpy = ((-ry * xp) / rx) * c;
  72133. centreX = ((x1 + x2) * 0.5) + (cosAngle * cpx) - (sinAngle * cpy);
  72134. centreY = ((y1 + y2) * 0.5) + (sinAngle * cpx) + (cosAngle * cpy);
  72135. const double ux = (xp - cpx) / rx;
  72136. const double uy = (yp - cpy) / ry;
  72137. const double vx = (-xp - cpx) / rx;
  72138. const double vy = (-yp - cpy) / ry;
  72139. const double length = juce_hypot (ux, uy);
  72140. startAngle = acos (jlimit (-1.0, 1.0, ux / length));
  72141. if (uy < 0)
  72142. startAngle = -startAngle;
  72143. startAngle += double_Pi * 0.5;
  72144. deltaAngle = acos (jlimit (-1.0, 1.0, ((ux * vx) + (uy * vy))
  72145. / (length * juce_hypot (vx, vy))));
  72146. if ((ux * vy) - (uy * vx) < 0)
  72147. deltaAngle = -deltaAngle;
  72148. if (sweep)
  72149. {
  72150. if (deltaAngle < 0)
  72151. deltaAngle += double_Pi * 2.0;
  72152. }
  72153. else
  72154. {
  72155. if (deltaAngle > 0)
  72156. deltaAngle -= double_Pi * 2.0;
  72157. }
  72158. deltaAngle = fmod (deltaAngle, double_Pi * 2.0);
  72159. }
  72160. static const XmlElement* findElementForId (const XmlElement* const parent, const String& id)
  72161. {
  72162. forEachXmlChildElement (*parent, e)
  72163. {
  72164. if (e->compareAttribute ("id", id))
  72165. return e;
  72166. const XmlElement* const found = findElementForId (e, id);
  72167. if (found != 0)
  72168. return found;
  72169. }
  72170. return 0;
  72171. }
  72172. SVGState& operator= (const SVGState&);
  72173. };
  72174. Drawable* Drawable::createFromSVG (const XmlElement& svgDocument)
  72175. {
  72176. SVGState state (&svgDocument);
  72177. return state.parseSVGElement (svgDocument);
  72178. }
  72179. END_JUCE_NAMESPACE
  72180. /*** End of inlined file: juce_SVGParser.cpp ***/
  72181. /*** Start of inlined file: juce_DropShadowEffect.cpp ***/
  72182. BEGIN_JUCE_NAMESPACE
  72183. #if JUCE_MSVC && JUCE_DEBUG
  72184. #pragma optimize ("t", on)
  72185. #endif
  72186. DropShadowEffect::DropShadowEffect()
  72187. : offsetX (0),
  72188. offsetY (0),
  72189. radius (4),
  72190. opacity (0.6f)
  72191. {
  72192. }
  72193. DropShadowEffect::~DropShadowEffect()
  72194. {
  72195. }
  72196. void DropShadowEffect::setShadowProperties (const float newRadius,
  72197. const float newOpacity,
  72198. const int newShadowOffsetX,
  72199. const int newShadowOffsetY)
  72200. {
  72201. radius = jmax (1.1f, newRadius);
  72202. offsetX = newShadowOffsetX;
  72203. offsetY = newShadowOffsetY;
  72204. opacity = newOpacity;
  72205. }
  72206. void DropShadowEffect::applyEffect (Image& image, Graphics& g, float alpha)
  72207. {
  72208. const int w = image.getWidth();
  72209. const int h = image.getHeight();
  72210. Image shadowImage (Image::SingleChannel, w, h, false);
  72211. const Image::BitmapData srcData (image, false);
  72212. const Image::BitmapData destData (shadowImage, true);
  72213. const int filter = roundToInt (63.0f / radius);
  72214. const int radiusMinus1 = roundToInt ((radius - 1.0f) * 63.0f);
  72215. for (int x = w; --x >= 0;)
  72216. {
  72217. int shadowAlpha = 0;
  72218. const PixelARGB* src = ((const PixelARGB*) srcData.data) + x;
  72219. uint8* shadowPix = destData.data + x;
  72220. for (int y = h; --y >= 0;)
  72221. {
  72222. shadowAlpha = ((shadowAlpha * radiusMinus1 + (src->getAlpha() << 6)) * filter) >> 12;
  72223. *shadowPix = (uint8) shadowAlpha;
  72224. src = (const PixelARGB*) (((const uint8*) src) + srcData.lineStride);
  72225. shadowPix += destData.lineStride;
  72226. }
  72227. }
  72228. for (int y = h; --y >= 0;)
  72229. {
  72230. int shadowAlpha = 0;
  72231. uint8* shadowPix = destData.getLinePointer (y);
  72232. for (int x = w; --x >= 0;)
  72233. {
  72234. shadowAlpha = ((shadowAlpha * radiusMinus1 + (*shadowPix << 6)) * filter) >> 12;
  72235. *shadowPix++ = (uint8) shadowAlpha;
  72236. }
  72237. }
  72238. g.setColour (Colours::black.withAlpha (opacity * alpha));
  72239. g.drawImageAt (shadowImage, offsetX, offsetY, true);
  72240. g.setOpacity (alpha);
  72241. g.drawImageAt (image, 0, 0);
  72242. }
  72243. #if JUCE_MSVC && JUCE_DEBUG
  72244. #pragma optimize ("", on) // resets optimisations to the project defaults
  72245. #endif
  72246. END_JUCE_NAMESPACE
  72247. /*** End of inlined file: juce_DropShadowEffect.cpp ***/
  72248. /*** Start of inlined file: juce_GlowEffect.cpp ***/
  72249. BEGIN_JUCE_NAMESPACE
  72250. GlowEffect::GlowEffect()
  72251. : radius (2.0f),
  72252. colour (Colours::white)
  72253. {
  72254. }
  72255. GlowEffect::~GlowEffect()
  72256. {
  72257. }
  72258. void GlowEffect::setGlowProperties (const float newRadius,
  72259. const Colour& newColour)
  72260. {
  72261. radius = newRadius;
  72262. colour = newColour;
  72263. }
  72264. void GlowEffect::applyEffect (Image& image, Graphics& g, float alpha)
  72265. {
  72266. Image temp (image.getFormat(), image.getWidth(), image.getHeight(), true);
  72267. ImageConvolutionKernel blurKernel (roundToInt (radius * 2.0f));
  72268. blurKernel.createGaussianBlur (radius);
  72269. blurKernel.rescaleAllValues (radius);
  72270. blurKernel.applyToImage (temp, image, image.getBounds());
  72271. g.setColour (colour.withMultipliedAlpha (alpha));
  72272. g.drawImageAt (temp, 0, 0, true);
  72273. g.setOpacity (alpha);
  72274. g.drawImageAt (image, 0, 0, false);
  72275. }
  72276. END_JUCE_NAMESPACE
  72277. /*** End of inlined file: juce_GlowEffect.cpp ***/
  72278. /*** Start of inlined file: juce_Font.cpp ***/
  72279. BEGIN_JUCE_NAMESPACE
  72280. namespace FontValues
  72281. {
  72282. static float limitFontHeight (const float height) throw()
  72283. {
  72284. return jlimit (0.1f, 10000.0f, height);
  72285. }
  72286. static const float defaultFontHeight = 14.0f;
  72287. static String fallbackFont;
  72288. }
  72289. Font::SharedFontInternal::SharedFontInternal (const String& typefaceName_, const float height_, const float horizontalScale_,
  72290. const float kerning_, const float ascent_, const int styleFlags_,
  72291. Typeface* const typeface_) throw()
  72292. : typefaceName (typefaceName_),
  72293. height (height_),
  72294. horizontalScale (horizontalScale_),
  72295. kerning (kerning_),
  72296. ascent (ascent_),
  72297. styleFlags (styleFlags_),
  72298. typeface (typeface_)
  72299. {
  72300. }
  72301. Font::SharedFontInternal::SharedFontInternal (const SharedFontInternal& other) throw()
  72302. : typefaceName (other.typefaceName),
  72303. height (other.height),
  72304. horizontalScale (other.horizontalScale),
  72305. kerning (other.kerning),
  72306. ascent (other.ascent),
  72307. styleFlags (other.styleFlags),
  72308. typeface (other.typeface)
  72309. {
  72310. }
  72311. Font::Font()
  72312. : font (new SharedFontInternal (getDefaultSansSerifFontName(), FontValues::defaultFontHeight,
  72313. 1.0f, 0, 0, Font::plain, 0))
  72314. {
  72315. }
  72316. Font::Font (const float fontHeight, const int styleFlags_)
  72317. : font (new SharedFontInternal (getDefaultSansSerifFontName(), FontValues::limitFontHeight (fontHeight),
  72318. 1.0f, 0, 0, styleFlags_, 0))
  72319. {
  72320. }
  72321. Font::Font (const String& typefaceName_,
  72322. const float fontHeight,
  72323. const int styleFlags_)
  72324. : font (new SharedFontInternal (typefaceName_, FontValues::limitFontHeight (fontHeight),
  72325. 1.0f, 0, 0, styleFlags_, 0))
  72326. {
  72327. }
  72328. Font::Font (const Font& other) throw()
  72329. : font (other.font)
  72330. {
  72331. }
  72332. Font& Font::operator= (const Font& other) throw()
  72333. {
  72334. font = other.font;
  72335. return *this;
  72336. }
  72337. Font::~Font() throw()
  72338. {
  72339. }
  72340. Font::Font (const Typeface::Ptr& typeface)
  72341. : font (new SharedFontInternal (typeface->getName(), FontValues::defaultFontHeight,
  72342. 1.0f, 0, 0, Font::plain, typeface))
  72343. {
  72344. }
  72345. bool Font::operator== (const Font& other) const throw()
  72346. {
  72347. return font == other.font
  72348. || (font->height == other.font->height
  72349. && font->styleFlags == other.font->styleFlags
  72350. && font->horizontalScale == other.font->horizontalScale
  72351. && font->kerning == other.font->kerning
  72352. && font->typefaceName == other.font->typefaceName);
  72353. }
  72354. bool Font::operator!= (const Font& other) const throw()
  72355. {
  72356. return ! operator== (other);
  72357. }
  72358. void Font::dupeInternalIfShared()
  72359. {
  72360. if (font->getReferenceCount() > 1)
  72361. font = new SharedFontInternal (*font);
  72362. }
  72363. const String Font::getDefaultSansSerifFontName()
  72364. {
  72365. static const String name ("<Sans-Serif>");
  72366. return name;
  72367. }
  72368. const String Font::getDefaultSerifFontName()
  72369. {
  72370. static const String name ("<Serif>");
  72371. return name;
  72372. }
  72373. const String Font::getDefaultMonospacedFontName()
  72374. {
  72375. static const String name ("<Monospaced>");
  72376. return name;
  72377. }
  72378. void Font::setTypefaceName (const String& faceName)
  72379. {
  72380. if (faceName != font->typefaceName)
  72381. {
  72382. dupeInternalIfShared();
  72383. font->typefaceName = faceName;
  72384. font->typeface = 0;
  72385. font->ascent = 0;
  72386. }
  72387. }
  72388. const String Font::getFallbackFontName()
  72389. {
  72390. return FontValues::fallbackFont;
  72391. }
  72392. void Font::setFallbackFontName (const String& name)
  72393. {
  72394. FontValues::fallbackFont = name;
  72395. }
  72396. void Font::setHeight (float newHeight)
  72397. {
  72398. newHeight = FontValues::limitFontHeight (newHeight);
  72399. if (font->height != newHeight)
  72400. {
  72401. dupeInternalIfShared();
  72402. font->height = newHeight;
  72403. }
  72404. }
  72405. void Font::setHeightWithoutChangingWidth (float newHeight)
  72406. {
  72407. newHeight = FontValues::limitFontHeight (newHeight);
  72408. if (font->height != newHeight)
  72409. {
  72410. dupeInternalIfShared();
  72411. font->horizontalScale *= (font->height / newHeight);
  72412. font->height = newHeight;
  72413. }
  72414. }
  72415. void Font::setStyleFlags (const int newFlags)
  72416. {
  72417. if (font->styleFlags != newFlags)
  72418. {
  72419. dupeInternalIfShared();
  72420. font->styleFlags = newFlags;
  72421. font->typeface = 0;
  72422. font->ascent = 0;
  72423. }
  72424. }
  72425. void Font::setSizeAndStyle (float newHeight,
  72426. const int newStyleFlags,
  72427. const float newHorizontalScale,
  72428. const float newKerningAmount)
  72429. {
  72430. newHeight = FontValues::limitFontHeight (newHeight);
  72431. if (font->height != newHeight
  72432. || font->horizontalScale != newHorizontalScale
  72433. || font->kerning != newKerningAmount)
  72434. {
  72435. dupeInternalIfShared();
  72436. font->height = newHeight;
  72437. font->horizontalScale = newHorizontalScale;
  72438. font->kerning = newKerningAmount;
  72439. }
  72440. setStyleFlags (newStyleFlags);
  72441. }
  72442. void Font::setHorizontalScale (const float scaleFactor)
  72443. {
  72444. dupeInternalIfShared();
  72445. font->horizontalScale = scaleFactor;
  72446. }
  72447. void Font::setExtraKerningFactor (const float extraKerning)
  72448. {
  72449. dupeInternalIfShared();
  72450. font->kerning = extraKerning;
  72451. }
  72452. void Font::setBold (const bool shouldBeBold)
  72453. {
  72454. setStyleFlags (shouldBeBold ? (font->styleFlags | bold)
  72455. : (font->styleFlags & ~bold));
  72456. }
  72457. const Font Font::boldened() const
  72458. {
  72459. Font f (*this);
  72460. f.setBold (true);
  72461. return f;
  72462. }
  72463. bool Font::isBold() const throw()
  72464. {
  72465. return (font->styleFlags & bold) != 0;
  72466. }
  72467. void Font::setItalic (const bool shouldBeItalic)
  72468. {
  72469. setStyleFlags (shouldBeItalic ? (font->styleFlags | italic)
  72470. : (font->styleFlags & ~italic));
  72471. }
  72472. const Font Font::italicised() const
  72473. {
  72474. Font f (*this);
  72475. f.setItalic (true);
  72476. return f;
  72477. }
  72478. bool Font::isItalic() const throw()
  72479. {
  72480. return (font->styleFlags & italic) != 0;
  72481. }
  72482. void Font::setUnderline (const bool shouldBeUnderlined)
  72483. {
  72484. setStyleFlags (shouldBeUnderlined ? (font->styleFlags | underlined)
  72485. : (font->styleFlags & ~underlined));
  72486. }
  72487. bool Font::isUnderlined() const throw()
  72488. {
  72489. return (font->styleFlags & underlined) != 0;
  72490. }
  72491. float Font::getAscent() const
  72492. {
  72493. if (font->ascent == 0)
  72494. font->ascent = getTypeface()->getAscent();
  72495. return font->height * font->ascent;
  72496. }
  72497. float Font::getDescent() const
  72498. {
  72499. return font->height - getAscent();
  72500. }
  72501. int Font::getStringWidth (const String& text) const
  72502. {
  72503. return roundToInt (getStringWidthFloat (text));
  72504. }
  72505. float Font::getStringWidthFloat (const String& text) const
  72506. {
  72507. float w = getTypeface()->getStringWidth (text);
  72508. if (font->kerning != 0)
  72509. w += font->kerning * text.length();
  72510. return w * font->height * font->horizontalScale;
  72511. }
  72512. void Font::getGlyphPositions (const String& text, Array <int>& glyphs, Array <float>& xOffsets) const
  72513. {
  72514. getTypeface()->getGlyphPositions (text, glyphs, xOffsets);
  72515. const float scale = font->height * font->horizontalScale;
  72516. const int num = xOffsets.size();
  72517. if (num > 0)
  72518. {
  72519. float* const x = &(xOffsets.getReference(0));
  72520. if (font->kerning != 0)
  72521. {
  72522. for (int i = 0; i < num; ++i)
  72523. x[i] = (x[i] + i * font->kerning) * scale;
  72524. }
  72525. else
  72526. {
  72527. for (int i = 0; i < num; ++i)
  72528. x[i] *= scale;
  72529. }
  72530. }
  72531. }
  72532. void Font::findFonts (Array<Font>& destArray)
  72533. {
  72534. const StringArray names (findAllTypefaceNames());
  72535. for (int i = 0; i < names.size(); ++i)
  72536. destArray.add (Font (names[i], FontValues::defaultFontHeight, Font::plain));
  72537. }
  72538. const String Font::toString() const
  72539. {
  72540. String s (getTypefaceName());
  72541. if (s == getDefaultSansSerifFontName())
  72542. s = String::empty;
  72543. else
  72544. s += "; ";
  72545. s += String (getHeight(), 1);
  72546. if (isBold())
  72547. s += " bold";
  72548. if (isItalic())
  72549. s += " italic";
  72550. return s;
  72551. }
  72552. const Font Font::fromString (const String& fontDescription)
  72553. {
  72554. String name;
  72555. const int separator = fontDescription.indexOfChar (';');
  72556. if (separator > 0)
  72557. name = fontDescription.substring (0, separator).trim();
  72558. if (name.isEmpty())
  72559. name = getDefaultSansSerifFontName();
  72560. String sizeAndStyle (fontDescription.substring (separator + 1));
  72561. float height = sizeAndStyle.getFloatValue();
  72562. if (height <= 0)
  72563. height = 10.0f;
  72564. int flags = Font::plain;
  72565. if (sizeAndStyle.containsIgnoreCase ("bold"))
  72566. flags |= Font::bold;
  72567. if (sizeAndStyle.containsIgnoreCase ("italic"))
  72568. flags |= Font::italic;
  72569. return Font (name, height, flags);
  72570. }
  72571. class TypefaceCache : public DeletedAtShutdown
  72572. {
  72573. public:
  72574. TypefaceCache (int numToCache = 10)
  72575. : counter (1)
  72576. {
  72577. while (--numToCache >= 0)
  72578. faces.add (new CachedFace());
  72579. }
  72580. ~TypefaceCache()
  72581. {
  72582. clearSingletonInstance();
  72583. }
  72584. juce_DeclareSingleton_SingleThreaded_Minimal (TypefaceCache)
  72585. const Typeface::Ptr findTypefaceFor (const Font& font)
  72586. {
  72587. const int flags = font.getStyleFlags() & (Font::bold | Font::italic);
  72588. const String faceName (font.getTypefaceName());
  72589. int i;
  72590. for (i = faces.size(); --i >= 0;)
  72591. {
  72592. CachedFace* const face = faces.getUnchecked(i);
  72593. if (face->flags == flags
  72594. && face->typefaceName == faceName)
  72595. {
  72596. face->lastUsageCount = ++counter;
  72597. return face->typeFace;
  72598. }
  72599. }
  72600. int replaceIndex = 0;
  72601. int bestLastUsageCount = std::numeric_limits<int>::max();
  72602. for (i = faces.size(); --i >= 0;)
  72603. {
  72604. const int lu = faces.getUnchecked(i)->lastUsageCount;
  72605. if (bestLastUsageCount > lu)
  72606. {
  72607. bestLastUsageCount = lu;
  72608. replaceIndex = i;
  72609. }
  72610. }
  72611. CachedFace* const face = faces.getUnchecked (replaceIndex);
  72612. face->typefaceName = faceName;
  72613. face->flags = flags;
  72614. face->lastUsageCount = ++counter;
  72615. face->typeFace = LookAndFeel::getDefaultLookAndFeel().getTypefaceForFont (font);
  72616. jassert (face->typeFace != 0); // the look and feel must return a typeface!
  72617. return face->typeFace;
  72618. }
  72619. juce_UseDebuggingNewOperator
  72620. private:
  72621. struct CachedFace
  72622. {
  72623. CachedFace() throw()
  72624. : lastUsageCount (0), flags (-1)
  72625. {
  72626. }
  72627. String typefaceName;
  72628. int lastUsageCount;
  72629. int flags;
  72630. Typeface::Ptr typeFace;
  72631. };
  72632. int counter;
  72633. OwnedArray <CachedFace> faces;
  72634. TypefaceCache (const TypefaceCache&);
  72635. TypefaceCache& operator= (const TypefaceCache&);
  72636. };
  72637. juce_ImplementSingleton_SingleThreaded (TypefaceCache)
  72638. Typeface* Font::getTypeface() const
  72639. {
  72640. if (font->typeface == 0)
  72641. font->typeface = TypefaceCache::getInstance()->findTypefaceFor (*this);
  72642. return font->typeface;
  72643. }
  72644. END_JUCE_NAMESPACE
  72645. /*** End of inlined file: juce_Font.cpp ***/
  72646. /*** Start of inlined file: juce_GlyphArrangement.cpp ***/
  72647. BEGIN_JUCE_NAMESPACE
  72648. PositionedGlyph::PositionedGlyph (const float x_, const float y_, const float w_, const Font& font_,
  72649. const juce_wchar character_, const int glyph_)
  72650. : x (x_),
  72651. y (y_),
  72652. w (w_),
  72653. font (font_),
  72654. character (character_),
  72655. glyph (glyph_)
  72656. {
  72657. }
  72658. PositionedGlyph::PositionedGlyph (const PositionedGlyph& other)
  72659. : x (other.x),
  72660. y (other.y),
  72661. w (other.w),
  72662. font (other.font),
  72663. character (other.character),
  72664. glyph (other.glyph)
  72665. {
  72666. }
  72667. void PositionedGlyph::draw (const Graphics& g) const
  72668. {
  72669. if (! isWhitespace())
  72670. {
  72671. g.getInternalContext()->setFont (font);
  72672. g.getInternalContext()->drawGlyph (glyph, AffineTransform::translation (x, y));
  72673. }
  72674. }
  72675. void PositionedGlyph::draw (const Graphics& g,
  72676. const AffineTransform& transform) const
  72677. {
  72678. if (! isWhitespace())
  72679. {
  72680. g.getInternalContext()->setFont (font);
  72681. g.getInternalContext()->drawGlyph (glyph, AffineTransform::translation (x, y)
  72682. .followedBy (transform));
  72683. }
  72684. }
  72685. void PositionedGlyph::createPath (Path& path) const
  72686. {
  72687. if (! isWhitespace())
  72688. {
  72689. Typeface* const t = font.getTypeface();
  72690. if (t != 0)
  72691. {
  72692. Path p;
  72693. t->getOutlineForGlyph (glyph, p);
  72694. path.addPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight())
  72695. .translated (x, y));
  72696. }
  72697. }
  72698. }
  72699. bool PositionedGlyph::hitTest (float px, float py) const
  72700. {
  72701. if (getBounds().contains (px, py) && ! isWhitespace())
  72702. {
  72703. Typeface* const t = font.getTypeface();
  72704. if (t != 0)
  72705. {
  72706. Path p;
  72707. t->getOutlineForGlyph (glyph, p);
  72708. AffineTransform::translation (-x, -y)
  72709. .scaled (1.0f / (font.getHeight() * font.getHorizontalScale()), 1.0f / font.getHeight())
  72710. .transformPoint (px, py);
  72711. return p.contains (px, py);
  72712. }
  72713. }
  72714. return false;
  72715. }
  72716. void PositionedGlyph::moveBy (const float deltaX,
  72717. const float deltaY)
  72718. {
  72719. x += deltaX;
  72720. y += deltaY;
  72721. }
  72722. GlyphArrangement::GlyphArrangement()
  72723. {
  72724. glyphs.ensureStorageAllocated (128);
  72725. }
  72726. GlyphArrangement::GlyphArrangement (const GlyphArrangement& other)
  72727. {
  72728. addGlyphArrangement (other);
  72729. }
  72730. GlyphArrangement& GlyphArrangement::operator= (const GlyphArrangement& other)
  72731. {
  72732. if (this != &other)
  72733. {
  72734. clear();
  72735. addGlyphArrangement (other);
  72736. }
  72737. return *this;
  72738. }
  72739. GlyphArrangement::~GlyphArrangement()
  72740. {
  72741. }
  72742. void GlyphArrangement::clear()
  72743. {
  72744. glyphs.clear();
  72745. }
  72746. PositionedGlyph& GlyphArrangement::getGlyph (const int index) const
  72747. {
  72748. jassert (((unsigned int) index) < (unsigned int) glyphs.size());
  72749. return *glyphs [index];
  72750. }
  72751. void GlyphArrangement::addGlyphArrangement (const GlyphArrangement& other)
  72752. {
  72753. glyphs.ensureStorageAllocated (glyphs.size() + other.glyphs.size());
  72754. glyphs.addCopiesOf (other.glyphs);
  72755. }
  72756. void GlyphArrangement::removeRangeOfGlyphs (int startIndex, const int num)
  72757. {
  72758. glyphs.removeRange (startIndex, num < 0 ? glyphs.size() : num);
  72759. }
  72760. void GlyphArrangement::addLineOfText (const Font& font,
  72761. const String& text,
  72762. const float xOffset,
  72763. const float yOffset)
  72764. {
  72765. addCurtailedLineOfText (font, text,
  72766. xOffset, yOffset,
  72767. 1.0e10f, false);
  72768. }
  72769. void GlyphArrangement::addCurtailedLineOfText (const Font& font,
  72770. const String& text,
  72771. float xOffset,
  72772. const float yOffset,
  72773. const float maxWidthPixels,
  72774. const bool useEllipsis)
  72775. {
  72776. if (text.isNotEmpty())
  72777. {
  72778. Array <int> newGlyphs;
  72779. Array <float> xOffsets;
  72780. font.getGlyphPositions (text, newGlyphs, xOffsets);
  72781. const int textLen = newGlyphs.size();
  72782. const juce_wchar* const unicodeText = text;
  72783. for (int i = 0; i < textLen; ++i)
  72784. {
  72785. const float thisX = xOffsets.getUnchecked (i);
  72786. const float nextX = xOffsets.getUnchecked (i + 1);
  72787. if (nextX > maxWidthPixels + 1.0f)
  72788. {
  72789. // curtail the string if it's too wide..
  72790. if (useEllipsis && textLen > 3 && glyphs.size() >= 3)
  72791. insertEllipsis (font, xOffset + maxWidthPixels, 0, glyphs.size());
  72792. break;
  72793. }
  72794. else
  72795. {
  72796. glyphs.add (new PositionedGlyph (xOffset + thisX, yOffset, nextX - thisX,
  72797. font, unicodeText[i], newGlyphs.getUnchecked(i)));
  72798. }
  72799. }
  72800. }
  72801. }
  72802. int GlyphArrangement::insertEllipsis (const Font& font, const float maxXPos,
  72803. const int startIndex, int endIndex)
  72804. {
  72805. int numDeleted = 0;
  72806. if (glyphs.size() > 0)
  72807. {
  72808. Array<int> dotGlyphs;
  72809. Array<float> dotXs;
  72810. font.getGlyphPositions ("..", dotGlyphs, dotXs);
  72811. const float dx = dotXs[1];
  72812. float xOffset = 0.0f, yOffset = 0.0f;
  72813. while (endIndex > startIndex)
  72814. {
  72815. const PositionedGlyph* pg = glyphs.getUnchecked (--endIndex);
  72816. xOffset = pg->x;
  72817. yOffset = pg->y;
  72818. glyphs.remove (endIndex);
  72819. ++numDeleted;
  72820. if (xOffset + dx * 3 <= maxXPos)
  72821. break;
  72822. }
  72823. for (int i = 3; --i >= 0;)
  72824. {
  72825. glyphs.insert (endIndex++, new PositionedGlyph (xOffset, yOffset, dx,
  72826. font, '.', dotGlyphs.getFirst()));
  72827. --numDeleted;
  72828. xOffset += dx;
  72829. if (xOffset > maxXPos)
  72830. break;
  72831. }
  72832. }
  72833. return numDeleted;
  72834. }
  72835. void GlyphArrangement::addJustifiedText (const Font& font,
  72836. const String& text,
  72837. float x, float y,
  72838. const float maxLineWidth,
  72839. const Justification& horizontalLayout)
  72840. {
  72841. int lineStartIndex = glyphs.size();
  72842. addLineOfText (font, text, x, y);
  72843. const float originalY = y;
  72844. while (lineStartIndex < glyphs.size())
  72845. {
  72846. int i = lineStartIndex;
  72847. if (glyphs.getUnchecked(i)->getCharacter() != '\n'
  72848. && glyphs.getUnchecked(i)->getCharacter() != '\r')
  72849. ++i;
  72850. const float lineMaxX = glyphs.getUnchecked (lineStartIndex)->getLeft() + maxLineWidth;
  72851. int lastWordBreakIndex = -1;
  72852. while (i < glyphs.size())
  72853. {
  72854. const PositionedGlyph* pg = glyphs.getUnchecked (i);
  72855. const juce_wchar c = pg->getCharacter();
  72856. if (c == '\r' || c == '\n')
  72857. {
  72858. ++i;
  72859. if (c == '\r' && i < glyphs.size()
  72860. && glyphs.getUnchecked(i)->getCharacter() == '\n')
  72861. ++i;
  72862. break;
  72863. }
  72864. else if (pg->isWhitespace())
  72865. {
  72866. lastWordBreakIndex = i + 1;
  72867. }
  72868. else if (pg->getRight() - 0.0001f >= lineMaxX)
  72869. {
  72870. if (lastWordBreakIndex >= 0)
  72871. i = lastWordBreakIndex;
  72872. break;
  72873. }
  72874. ++i;
  72875. }
  72876. const float currentLineStartX = glyphs.getUnchecked (lineStartIndex)->getLeft();
  72877. float currentLineEndX = currentLineStartX;
  72878. for (int j = i; --j >= lineStartIndex;)
  72879. {
  72880. if (! glyphs.getUnchecked (j)->isWhitespace())
  72881. {
  72882. currentLineEndX = glyphs.getUnchecked (j)->getRight();
  72883. break;
  72884. }
  72885. }
  72886. float deltaX = 0.0f;
  72887. if (horizontalLayout.testFlags (Justification::horizontallyJustified))
  72888. spreadOutLine (lineStartIndex, i - lineStartIndex, maxLineWidth);
  72889. else if (horizontalLayout.testFlags (Justification::horizontallyCentred))
  72890. deltaX = (maxLineWidth - (currentLineEndX - currentLineStartX)) * 0.5f;
  72891. else if (horizontalLayout.testFlags (Justification::right))
  72892. deltaX = maxLineWidth - (currentLineEndX - currentLineStartX);
  72893. moveRangeOfGlyphs (lineStartIndex, i - lineStartIndex,
  72894. x + deltaX - currentLineStartX, y - originalY);
  72895. lineStartIndex = i;
  72896. y += font.getHeight();
  72897. }
  72898. }
  72899. void GlyphArrangement::addFittedText (const Font& f,
  72900. const String& text,
  72901. const float x, const float y,
  72902. const float width, const float height,
  72903. const Justification& layout,
  72904. int maximumLines,
  72905. const float minimumHorizontalScale)
  72906. {
  72907. // doesn't make much sense if this is outside a sensible range of 0.5 to 1.0
  72908. jassert (minimumHorizontalScale > 0 && minimumHorizontalScale <= 1.0f);
  72909. if (text.containsAnyOf ("\r\n"))
  72910. {
  72911. GlyphArrangement ga;
  72912. ga.addJustifiedText (f, text, x, y, width, layout);
  72913. const Rectangle<float> bb (ga.getBoundingBox (0, -1, false));
  72914. float dy = y - bb.getY();
  72915. if (layout.testFlags (Justification::verticallyCentred))
  72916. dy += (height - bb.getHeight()) * 0.5f;
  72917. else if (layout.testFlags (Justification::bottom))
  72918. dy += height - bb.getHeight();
  72919. ga.moveRangeOfGlyphs (0, -1, 0.0f, dy);
  72920. glyphs.ensureStorageAllocated (glyphs.size() + ga.glyphs.size());
  72921. for (int i = 0; i < ga.glyphs.size(); ++i)
  72922. glyphs.add (ga.glyphs.getUnchecked (i));
  72923. ga.glyphs.clear (false);
  72924. return;
  72925. }
  72926. int startIndex = glyphs.size();
  72927. addLineOfText (f, text.trim(), x, y);
  72928. if (glyphs.size() > startIndex)
  72929. {
  72930. float lineWidth = glyphs.getUnchecked (glyphs.size() - 1)->getRight()
  72931. - glyphs.getUnchecked (startIndex)->getLeft();
  72932. if (lineWidth <= 0)
  72933. return;
  72934. if (lineWidth * minimumHorizontalScale < width)
  72935. {
  72936. if (lineWidth > width)
  72937. stretchRangeOfGlyphs (startIndex, glyphs.size() - startIndex,
  72938. width / lineWidth);
  72939. justifyGlyphs (startIndex, glyphs.size() - startIndex,
  72940. x, y, width, height, layout);
  72941. }
  72942. else if (maximumLines <= 1)
  72943. {
  72944. fitLineIntoSpace (startIndex, glyphs.size() - startIndex,
  72945. x, y, width, height, f, layout, minimumHorizontalScale);
  72946. }
  72947. else
  72948. {
  72949. Font font (f);
  72950. String txt (text.trim());
  72951. const int length = txt.length();
  72952. const int originalStartIndex = startIndex;
  72953. int numLines = 1;
  72954. if (length <= 12 && ! txt.containsAnyOf (" -\t\r\n"))
  72955. maximumLines = 1;
  72956. maximumLines = jmin (maximumLines, length);
  72957. while (numLines < maximumLines)
  72958. {
  72959. ++numLines;
  72960. const float newFontHeight = height / (float) numLines;
  72961. if (newFontHeight < font.getHeight())
  72962. {
  72963. font.setHeight (jmax (8.0f, newFontHeight));
  72964. removeRangeOfGlyphs (startIndex, -1);
  72965. addLineOfText (font, txt, x, y);
  72966. lineWidth = glyphs.getUnchecked (glyphs.size() - 1)->getRight()
  72967. - glyphs.getUnchecked (startIndex)->getLeft();
  72968. }
  72969. if (numLines > lineWidth / width || newFontHeight < 8.0f)
  72970. break;
  72971. }
  72972. if (numLines < 1)
  72973. numLines = 1;
  72974. float lineY = y;
  72975. float widthPerLine = lineWidth / numLines;
  72976. int lastLineStartIndex = 0;
  72977. for (int line = 0; line < numLines; ++line)
  72978. {
  72979. int i = startIndex;
  72980. lastLineStartIndex = i;
  72981. float lineStartX = glyphs.getUnchecked (startIndex)->getLeft();
  72982. if (line == numLines - 1)
  72983. {
  72984. widthPerLine = width;
  72985. i = glyphs.size();
  72986. }
  72987. else
  72988. {
  72989. while (i < glyphs.size())
  72990. {
  72991. lineWidth = (glyphs.getUnchecked (i)->getRight() - lineStartX);
  72992. if (lineWidth > widthPerLine)
  72993. {
  72994. // got to a point where the line's too long, so skip forward to find a
  72995. // good place to break it..
  72996. const int searchStartIndex = i;
  72997. while (i < glyphs.size())
  72998. {
  72999. if ((glyphs.getUnchecked (i)->getRight() - lineStartX) * minimumHorizontalScale < width)
  73000. {
  73001. if (glyphs.getUnchecked (i)->isWhitespace()
  73002. || glyphs.getUnchecked (i)->getCharacter() == '-')
  73003. {
  73004. ++i;
  73005. break;
  73006. }
  73007. }
  73008. else
  73009. {
  73010. // can't find a suitable break, so try looking backwards..
  73011. i = searchStartIndex;
  73012. for (int back = 1; back < jmin (5, i - startIndex - 1); ++back)
  73013. {
  73014. if (glyphs.getUnchecked (i - back)->isWhitespace()
  73015. || glyphs.getUnchecked (i - back)->getCharacter() == '-')
  73016. {
  73017. i -= back - 1;
  73018. break;
  73019. }
  73020. }
  73021. break;
  73022. }
  73023. ++i;
  73024. }
  73025. break;
  73026. }
  73027. ++i;
  73028. }
  73029. int wsStart = i;
  73030. while (wsStart > 0 && glyphs.getUnchecked (wsStart - 1)->isWhitespace())
  73031. --wsStart;
  73032. int wsEnd = i;
  73033. while (wsEnd < glyphs.size() && glyphs.getUnchecked (wsEnd)->isWhitespace())
  73034. ++wsEnd;
  73035. removeRangeOfGlyphs (wsStart, wsEnd - wsStart);
  73036. i = jmax (wsStart, startIndex + 1);
  73037. }
  73038. i -= fitLineIntoSpace (startIndex, i - startIndex,
  73039. x, lineY, width, font.getHeight(), font,
  73040. layout.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  73041. minimumHorizontalScale);
  73042. startIndex = i;
  73043. lineY += font.getHeight();
  73044. if (startIndex >= glyphs.size())
  73045. break;
  73046. }
  73047. justifyGlyphs (originalStartIndex, glyphs.size() - originalStartIndex,
  73048. x, y, width, height, layout.getFlags() & ~Justification::horizontallyJustified);
  73049. }
  73050. }
  73051. }
  73052. void GlyphArrangement::moveRangeOfGlyphs (int startIndex, int num,
  73053. const float dx, const float dy)
  73054. {
  73055. jassert (startIndex >= 0);
  73056. if (dx != 0.0f || dy != 0.0f)
  73057. {
  73058. if (num < 0 || startIndex + num > glyphs.size())
  73059. num = glyphs.size() - startIndex;
  73060. while (--num >= 0)
  73061. glyphs.getUnchecked (startIndex++)->moveBy (dx, dy);
  73062. }
  73063. }
  73064. int GlyphArrangement::fitLineIntoSpace (int start, int numGlyphs, float x, float y, float w, float h, const Font& font,
  73065. const Justification& justification, float minimumHorizontalScale)
  73066. {
  73067. int numDeleted = 0;
  73068. const float lineStartX = glyphs.getUnchecked (start)->getLeft();
  73069. float lineWidth = glyphs.getUnchecked (start + numGlyphs - 1)->getRight() - lineStartX;
  73070. if (lineWidth > w)
  73071. {
  73072. if (minimumHorizontalScale < 1.0f)
  73073. {
  73074. stretchRangeOfGlyphs (start, numGlyphs, jmax (minimumHorizontalScale, w / lineWidth));
  73075. lineWidth = glyphs.getUnchecked (start + numGlyphs - 1)->getRight() - lineStartX - 0.5f;
  73076. }
  73077. if (lineWidth > w)
  73078. {
  73079. numDeleted = insertEllipsis (font, lineStartX + w, start, start + numGlyphs);
  73080. numGlyphs -= numDeleted;
  73081. }
  73082. }
  73083. justifyGlyphs (start, numGlyphs, x, y, w, h, justification);
  73084. return numDeleted;
  73085. }
  73086. void GlyphArrangement::stretchRangeOfGlyphs (int startIndex, int num,
  73087. const float horizontalScaleFactor)
  73088. {
  73089. jassert (startIndex >= 0);
  73090. if (num < 0 || startIndex + num > glyphs.size())
  73091. num = glyphs.size() - startIndex;
  73092. if (num > 0)
  73093. {
  73094. const float xAnchor = glyphs.getUnchecked (startIndex)->getLeft();
  73095. while (--num >= 0)
  73096. {
  73097. PositionedGlyph* const pg = glyphs.getUnchecked (startIndex++);
  73098. pg->x = xAnchor + (pg->x - xAnchor) * horizontalScaleFactor;
  73099. pg->font.setHorizontalScale (pg->font.getHorizontalScale() * horizontalScaleFactor);
  73100. pg->w *= horizontalScaleFactor;
  73101. }
  73102. }
  73103. }
  73104. const Rectangle<float> GlyphArrangement::getBoundingBox (int startIndex, int num, const bool includeWhitespace) const
  73105. {
  73106. jassert (startIndex >= 0);
  73107. if (num < 0 || startIndex + num > glyphs.size())
  73108. num = glyphs.size() - startIndex;
  73109. Rectangle<float> result;
  73110. while (--num >= 0)
  73111. {
  73112. const PositionedGlyph* const pg = glyphs.getUnchecked (startIndex++);
  73113. if (includeWhitespace || ! pg->isWhitespace())
  73114. result = result.getUnion (pg->getBounds());
  73115. }
  73116. return result;
  73117. }
  73118. void GlyphArrangement::justifyGlyphs (const int startIndex, const int num,
  73119. const float x, const float y, const float width, const float height,
  73120. const Justification& justification)
  73121. {
  73122. jassert (num >= 0 && startIndex >= 0);
  73123. if (glyphs.size() > 0 && num > 0)
  73124. {
  73125. const Rectangle<float> bb (getBoundingBox (startIndex, num, ! justification.testFlags (Justification::horizontallyJustified
  73126. | Justification::horizontallyCentred)));
  73127. float deltaX = 0.0f;
  73128. if (justification.testFlags (Justification::horizontallyJustified))
  73129. deltaX = x - bb.getX();
  73130. else if (justification.testFlags (Justification::horizontallyCentred))
  73131. deltaX = x + (width - bb.getWidth()) * 0.5f - bb.getX();
  73132. else if (justification.testFlags (Justification::right))
  73133. deltaX = (x + width) - bb.getRight();
  73134. else
  73135. deltaX = x - bb.getX();
  73136. float deltaY = 0.0f;
  73137. if (justification.testFlags (Justification::top))
  73138. deltaY = y - bb.getY();
  73139. else if (justification.testFlags (Justification::bottom))
  73140. deltaY = (y + height) - bb.getBottom();
  73141. else
  73142. deltaY = y + (height - bb.getHeight()) * 0.5f - bb.getY();
  73143. moveRangeOfGlyphs (startIndex, num, deltaX, deltaY);
  73144. if (justification.testFlags (Justification::horizontallyJustified))
  73145. {
  73146. int lineStart = 0;
  73147. float baseY = glyphs.getUnchecked (startIndex)->getBaselineY();
  73148. int i;
  73149. for (i = 0; i < num; ++i)
  73150. {
  73151. const float glyphY = glyphs.getUnchecked (startIndex + i)->getBaselineY();
  73152. if (glyphY != baseY)
  73153. {
  73154. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  73155. lineStart = i;
  73156. baseY = glyphY;
  73157. }
  73158. }
  73159. if (i > lineStart)
  73160. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  73161. }
  73162. }
  73163. }
  73164. void GlyphArrangement::spreadOutLine (const int start, const int num, const float targetWidth)
  73165. {
  73166. if (start + num < glyphs.size()
  73167. && glyphs.getUnchecked (start + num - 1)->getCharacter() != '\r'
  73168. && glyphs.getUnchecked (start + num - 1)->getCharacter() != '\n')
  73169. {
  73170. int numSpaces = 0;
  73171. int spacesAtEnd = 0;
  73172. for (int i = 0; i < num; ++i)
  73173. {
  73174. if (glyphs.getUnchecked (start + i)->isWhitespace())
  73175. {
  73176. ++spacesAtEnd;
  73177. ++numSpaces;
  73178. }
  73179. else
  73180. {
  73181. spacesAtEnd = 0;
  73182. }
  73183. }
  73184. numSpaces -= spacesAtEnd;
  73185. if (numSpaces > 0)
  73186. {
  73187. const float startX = glyphs.getUnchecked (start)->getLeft();
  73188. const float endX = glyphs.getUnchecked (start + num - 1 - spacesAtEnd)->getRight();
  73189. const float extraPaddingBetweenWords
  73190. = (targetWidth - (endX - startX)) / (float) numSpaces;
  73191. float deltaX = 0.0f;
  73192. for (int i = 0; i < num; ++i)
  73193. {
  73194. glyphs.getUnchecked (start + i)->moveBy (deltaX, 0.0f);
  73195. if (glyphs.getUnchecked (start + i)->isWhitespace())
  73196. deltaX += extraPaddingBetweenWords;
  73197. }
  73198. }
  73199. }
  73200. }
  73201. void GlyphArrangement::draw (const Graphics& g) const
  73202. {
  73203. for (int i = 0; i < glyphs.size(); ++i)
  73204. {
  73205. const PositionedGlyph* const pg = glyphs.getUnchecked(i);
  73206. if (pg->font.isUnderlined())
  73207. {
  73208. const float lineThickness = (pg->font.getDescent()) * 0.3f;
  73209. float nextX = pg->x + pg->w;
  73210. if (i < glyphs.size() - 1 && glyphs.getUnchecked (i + 1)->y == pg->y)
  73211. nextX = glyphs.getUnchecked (i + 1)->x;
  73212. g.fillRect (pg->x, pg->y + lineThickness * 2.0f,
  73213. nextX - pg->x, lineThickness);
  73214. }
  73215. pg->draw (g);
  73216. }
  73217. }
  73218. void GlyphArrangement::draw (const Graphics& g, const AffineTransform& transform) const
  73219. {
  73220. for (int i = 0; i < glyphs.size(); ++i)
  73221. {
  73222. const PositionedGlyph* const pg = glyphs.getUnchecked(i);
  73223. if (pg->font.isUnderlined())
  73224. {
  73225. const float lineThickness = (pg->font.getDescent()) * 0.3f;
  73226. float nextX = pg->x + pg->w;
  73227. if (i < glyphs.size() - 1 && glyphs.getUnchecked (i + 1)->y == pg->y)
  73228. nextX = glyphs.getUnchecked (i + 1)->x;
  73229. Path p;
  73230. p.addLineSegment (Line<float> (pg->x, pg->y + lineThickness * 2.0f,
  73231. nextX, pg->y + lineThickness * 2.0f),
  73232. lineThickness);
  73233. g.fillPath (p, transform);
  73234. }
  73235. pg->draw (g, transform);
  73236. }
  73237. }
  73238. void GlyphArrangement::createPath (Path& path) const
  73239. {
  73240. for (int i = 0; i < glyphs.size(); ++i)
  73241. glyphs.getUnchecked (i)->createPath (path);
  73242. }
  73243. int GlyphArrangement::findGlyphIndexAt (float x, float y) const
  73244. {
  73245. for (int i = 0; i < glyphs.size(); ++i)
  73246. if (glyphs.getUnchecked (i)->hitTest (x, y))
  73247. return i;
  73248. return -1;
  73249. }
  73250. END_JUCE_NAMESPACE
  73251. /*** End of inlined file: juce_GlyphArrangement.cpp ***/
  73252. /*** Start of inlined file: juce_TextLayout.cpp ***/
  73253. BEGIN_JUCE_NAMESPACE
  73254. class TextLayout::Token
  73255. {
  73256. public:
  73257. String text;
  73258. Font font;
  73259. int x, y, w, h;
  73260. int line, lineHeight;
  73261. bool isWhitespace, isNewLine;
  73262. Token (const String& t,
  73263. const Font& f,
  73264. const bool isWhitespace_)
  73265. : text (t),
  73266. font (f),
  73267. x(0),
  73268. y(0),
  73269. isWhitespace (isWhitespace_)
  73270. {
  73271. w = font.getStringWidth (t);
  73272. h = roundToInt (f.getHeight());
  73273. isNewLine = t.containsChar ('\n') || t.containsChar ('\r');
  73274. }
  73275. Token (const Token& other)
  73276. : text (other.text),
  73277. font (other.font),
  73278. x (other.x),
  73279. y (other.y),
  73280. w (other.w),
  73281. h (other.h),
  73282. line (other.line),
  73283. lineHeight (other.lineHeight),
  73284. isWhitespace (other.isWhitespace),
  73285. isNewLine (other.isNewLine)
  73286. {
  73287. }
  73288. ~Token()
  73289. {
  73290. }
  73291. void draw (Graphics& g,
  73292. const int xOffset,
  73293. const int yOffset)
  73294. {
  73295. if (! isWhitespace)
  73296. {
  73297. g.setFont (font);
  73298. g.drawSingleLineText (text.trimEnd(),
  73299. xOffset + x,
  73300. yOffset + y + (lineHeight - h)
  73301. + roundToInt (font.getAscent()));
  73302. }
  73303. }
  73304. juce_UseDebuggingNewOperator
  73305. };
  73306. TextLayout::TextLayout()
  73307. : totalLines (0)
  73308. {
  73309. tokens.ensureStorageAllocated (64);
  73310. }
  73311. TextLayout::TextLayout (const String& text, const Font& font)
  73312. : totalLines (0)
  73313. {
  73314. tokens.ensureStorageAllocated (64);
  73315. appendText (text, font);
  73316. }
  73317. TextLayout::TextLayout (const TextLayout& other)
  73318. : totalLines (0)
  73319. {
  73320. *this = other;
  73321. }
  73322. TextLayout& TextLayout::operator= (const TextLayout& other)
  73323. {
  73324. if (this != &other)
  73325. {
  73326. clear();
  73327. totalLines = other.totalLines;
  73328. tokens.addCopiesOf (other.tokens);
  73329. }
  73330. return *this;
  73331. }
  73332. TextLayout::~TextLayout()
  73333. {
  73334. clear();
  73335. }
  73336. void TextLayout::clear()
  73337. {
  73338. tokens.clear();
  73339. totalLines = 0;
  73340. }
  73341. bool TextLayout::isEmpty() const
  73342. {
  73343. return tokens.size() == 0;
  73344. }
  73345. void TextLayout::appendText (const String& text, const Font& font)
  73346. {
  73347. const juce_wchar* t = text;
  73348. String currentString;
  73349. int lastCharType = 0;
  73350. for (;;)
  73351. {
  73352. const juce_wchar c = *t++;
  73353. if (c == 0)
  73354. break;
  73355. int charType;
  73356. if (c == '\r' || c == '\n')
  73357. {
  73358. charType = 0;
  73359. }
  73360. else if (CharacterFunctions::isWhitespace (c))
  73361. {
  73362. charType = 2;
  73363. }
  73364. else
  73365. {
  73366. charType = 1;
  73367. }
  73368. if (charType == 0 || charType != lastCharType)
  73369. {
  73370. if (currentString.isNotEmpty())
  73371. {
  73372. tokens.add (new Token (currentString, font,
  73373. lastCharType == 2 || lastCharType == 0));
  73374. }
  73375. currentString = String::charToString (c);
  73376. if (c == '\r' && *t == '\n')
  73377. currentString += *t++;
  73378. }
  73379. else
  73380. {
  73381. currentString += c;
  73382. }
  73383. lastCharType = charType;
  73384. }
  73385. if (currentString.isNotEmpty())
  73386. tokens.add (new Token (currentString, font, lastCharType == 2));
  73387. }
  73388. void TextLayout::setText (const String& text, const Font& font)
  73389. {
  73390. clear();
  73391. appendText (text, font);
  73392. }
  73393. void TextLayout::layout (int maxWidth,
  73394. const Justification& justification,
  73395. const bool attemptToBalanceLineLengths)
  73396. {
  73397. if (attemptToBalanceLineLengths)
  73398. {
  73399. const int originalW = maxWidth;
  73400. int bestWidth = maxWidth;
  73401. float bestLineProportion = 0.0f;
  73402. while (maxWidth > originalW / 2)
  73403. {
  73404. layout (maxWidth, justification, false);
  73405. if (getNumLines() <= 1)
  73406. return;
  73407. const int lastLineW = getLineWidth (getNumLines() - 1);
  73408. const int lastButOneLineW = getLineWidth (getNumLines() - 2);
  73409. const float prop = lastLineW / (float) lastButOneLineW;
  73410. if (prop > 0.9f)
  73411. return;
  73412. if (prop > bestLineProportion)
  73413. {
  73414. bestLineProportion = prop;
  73415. bestWidth = maxWidth;
  73416. }
  73417. maxWidth -= 10;
  73418. }
  73419. layout (bestWidth, justification, false);
  73420. }
  73421. else
  73422. {
  73423. int x = 0;
  73424. int y = 0;
  73425. int h = 0;
  73426. totalLines = 0;
  73427. int i;
  73428. for (i = 0; i < tokens.size(); ++i)
  73429. {
  73430. Token* const t = tokens.getUnchecked(i);
  73431. t->x = x;
  73432. t->y = y;
  73433. t->line = totalLines;
  73434. x += t->w;
  73435. h = jmax (h, t->h);
  73436. const Token* nextTok = tokens [i + 1];
  73437. if (nextTok == 0)
  73438. break;
  73439. if (t->isNewLine || ((! nextTok->isWhitespace) && x + nextTok->w > maxWidth))
  73440. {
  73441. // finished a line, so go back and update the heights of the things on it
  73442. for (int j = i; j >= 0; --j)
  73443. {
  73444. Token* const tok = tokens.getUnchecked(j);
  73445. if (tok->line == totalLines)
  73446. tok->lineHeight = h;
  73447. else
  73448. break;
  73449. }
  73450. x = 0;
  73451. y += h;
  73452. h = 0;
  73453. ++totalLines;
  73454. }
  73455. }
  73456. // finished a line, so go back and update the heights of the things on it
  73457. for (int j = jmin (i, tokens.size() - 1); j >= 0; --j)
  73458. {
  73459. Token* const t = tokens.getUnchecked(j);
  73460. if (t->line == totalLines)
  73461. t->lineHeight = h;
  73462. else
  73463. break;
  73464. }
  73465. ++totalLines;
  73466. if (! justification.testFlags (Justification::left))
  73467. {
  73468. int totalW = getWidth();
  73469. for (i = totalLines; --i >= 0;)
  73470. {
  73471. const int lineW = getLineWidth (i);
  73472. int dx = 0;
  73473. if (justification.testFlags (Justification::horizontallyCentred))
  73474. dx = (totalW - lineW) / 2;
  73475. else if (justification.testFlags (Justification::right))
  73476. dx = totalW - lineW;
  73477. for (int j = tokens.size(); --j >= 0;)
  73478. {
  73479. Token* const t = tokens.getUnchecked(j);
  73480. if (t->line == i)
  73481. t->x += dx;
  73482. }
  73483. }
  73484. }
  73485. }
  73486. }
  73487. int TextLayout::getLineWidth (const int lineNumber) const
  73488. {
  73489. int maxW = 0;
  73490. for (int i = tokens.size(); --i >= 0;)
  73491. {
  73492. const Token* const t = tokens.getUnchecked(i);
  73493. if (t->line == lineNumber && ! t->isWhitespace)
  73494. maxW = jmax (maxW, t->x + t->w);
  73495. }
  73496. return maxW;
  73497. }
  73498. int TextLayout::getWidth() const
  73499. {
  73500. int maxW = 0;
  73501. for (int i = tokens.size(); --i >= 0;)
  73502. {
  73503. const Token* const t = tokens.getUnchecked(i);
  73504. if (! t->isWhitespace)
  73505. maxW = jmax (maxW, t->x + t->w);
  73506. }
  73507. return maxW;
  73508. }
  73509. int TextLayout::getHeight() const
  73510. {
  73511. int maxH = 0;
  73512. for (int i = tokens.size(); --i >= 0;)
  73513. {
  73514. const Token* const t = tokens.getUnchecked(i);
  73515. if (! t->isWhitespace)
  73516. maxH = jmax (maxH, t->y + t->h);
  73517. }
  73518. return maxH;
  73519. }
  73520. void TextLayout::draw (Graphics& g,
  73521. const int xOffset,
  73522. const int yOffset) const
  73523. {
  73524. for (int i = tokens.size(); --i >= 0;)
  73525. tokens.getUnchecked(i)->draw (g, xOffset, yOffset);
  73526. }
  73527. void TextLayout::drawWithin (Graphics& g,
  73528. int x, int y, int w, int h,
  73529. const Justification& justification) const
  73530. {
  73531. justification.applyToRectangle (x, y, getWidth(), getHeight(),
  73532. x, y, w, h);
  73533. draw (g, x, y);
  73534. }
  73535. END_JUCE_NAMESPACE
  73536. /*** End of inlined file: juce_TextLayout.cpp ***/
  73537. /*** Start of inlined file: juce_Typeface.cpp ***/
  73538. BEGIN_JUCE_NAMESPACE
  73539. Typeface::Typeface (const String& name_) throw()
  73540. : name (name_)
  73541. {
  73542. }
  73543. Typeface::~Typeface()
  73544. {
  73545. }
  73546. class CustomTypeface::GlyphInfo
  73547. {
  73548. public:
  73549. GlyphInfo (const juce_wchar character_, const Path& path_, const float width_) throw()
  73550. : character (character_), path (path_), width (width_)
  73551. {
  73552. }
  73553. ~GlyphInfo() throw()
  73554. {
  73555. }
  73556. struct KerningPair
  73557. {
  73558. juce_wchar character2;
  73559. float kerningAmount;
  73560. };
  73561. void addKerningPair (const juce_wchar subsequentCharacter,
  73562. const float extraKerningAmount) throw()
  73563. {
  73564. KerningPair kp;
  73565. kp.character2 = subsequentCharacter;
  73566. kp.kerningAmount = extraKerningAmount;
  73567. kerningPairs.add (kp);
  73568. }
  73569. float getHorizontalSpacing (const juce_wchar subsequentCharacter) const throw()
  73570. {
  73571. if (subsequentCharacter != 0)
  73572. {
  73573. for (int i = kerningPairs.size(); --i >= 0;)
  73574. if (kerningPairs.getReference(i).character2 == subsequentCharacter)
  73575. return width + kerningPairs.getReference(i).kerningAmount;
  73576. }
  73577. return width;
  73578. }
  73579. const juce_wchar character;
  73580. const Path path;
  73581. float width;
  73582. Array <KerningPair> kerningPairs;
  73583. juce_UseDebuggingNewOperator
  73584. private:
  73585. GlyphInfo (const GlyphInfo&);
  73586. GlyphInfo& operator= (const GlyphInfo&);
  73587. };
  73588. CustomTypeface::CustomTypeface()
  73589. : Typeface (String::empty)
  73590. {
  73591. clear();
  73592. }
  73593. CustomTypeface::CustomTypeface (InputStream& serialisedTypefaceStream)
  73594. : Typeface (String::empty)
  73595. {
  73596. clear();
  73597. GZIPDecompressorInputStream gzin (serialisedTypefaceStream);
  73598. BufferedInputStream in (gzin, 32768);
  73599. name = in.readString();
  73600. isBold = in.readBool();
  73601. isItalic = in.readBool();
  73602. ascent = in.readFloat();
  73603. defaultCharacter = (juce_wchar) in.readShort();
  73604. int i, numChars = in.readInt();
  73605. for (i = 0; i < numChars; ++i)
  73606. {
  73607. const juce_wchar c = (juce_wchar) in.readShort();
  73608. const float width = in.readFloat();
  73609. Path p;
  73610. p.loadPathFromStream (in);
  73611. addGlyph (c, p, width);
  73612. }
  73613. const int numKerningPairs = in.readInt();
  73614. for (i = 0; i < numKerningPairs; ++i)
  73615. {
  73616. const juce_wchar char1 = (juce_wchar) in.readShort();
  73617. const juce_wchar char2 = (juce_wchar) in.readShort();
  73618. addKerningPair (char1, char2, in.readFloat());
  73619. }
  73620. }
  73621. CustomTypeface::~CustomTypeface()
  73622. {
  73623. }
  73624. void CustomTypeface::clear()
  73625. {
  73626. defaultCharacter = 0;
  73627. ascent = 1.0f;
  73628. isBold = isItalic = false;
  73629. zeromem (lookupTable, sizeof (lookupTable));
  73630. glyphs.clear();
  73631. }
  73632. void CustomTypeface::setCharacteristics (const String& name_, const float ascent_, const bool isBold_,
  73633. const bool isItalic_, const juce_wchar defaultCharacter_) throw()
  73634. {
  73635. name = name_;
  73636. defaultCharacter = defaultCharacter_;
  73637. ascent = ascent_;
  73638. isBold = isBold_;
  73639. isItalic = isItalic_;
  73640. }
  73641. void CustomTypeface::addGlyph (const juce_wchar character, const Path& path, const float width) throw()
  73642. {
  73643. // Check that you're not trying to add the same character twice..
  73644. jassert (findGlyph (character, false) == 0);
  73645. if (((unsigned int) character) < (unsigned int) numElementsInArray (lookupTable))
  73646. lookupTable [character] = (short) glyphs.size();
  73647. glyphs.add (new GlyphInfo (character, path, width));
  73648. }
  73649. void CustomTypeface::addKerningPair (const juce_wchar char1, const juce_wchar char2, const float extraAmount) throw()
  73650. {
  73651. if (extraAmount != 0)
  73652. {
  73653. GlyphInfo* const g = findGlyph (char1, true);
  73654. jassert (g != 0); // can only add kerning pairs for characters that exist!
  73655. if (g != 0)
  73656. g->addKerningPair (char2, extraAmount);
  73657. }
  73658. }
  73659. CustomTypeface::GlyphInfo* CustomTypeface::findGlyph (const juce_wchar character, const bool loadIfNeeded) throw()
  73660. {
  73661. if (((unsigned int) character) < (unsigned int) numElementsInArray (lookupTable) && lookupTable [character] > 0)
  73662. return glyphs [(int) lookupTable [(int) character]];
  73663. for (int i = 0; i < glyphs.size(); ++i)
  73664. {
  73665. GlyphInfo* const g = glyphs.getUnchecked(i);
  73666. if (g->character == character)
  73667. return g;
  73668. }
  73669. if (loadIfNeeded && loadGlyphIfPossible (character))
  73670. return findGlyph (character, false);
  73671. return 0;
  73672. }
  73673. CustomTypeface::GlyphInfo* CustomTypeface::findGlyphSubstituting (const juce_wchar character) throw()
  73674. {
  73675. GlyphInfo* glyph = findGlyph (character, true);
  73676. if (glyph == 0)
  73677. {
  73678. if (CharacterFunctions::isWhitespace (character) && character != L' ')
  73679. glyph = findGlyph (L' ', true);
  73680. if (glyph == 0)
  73681. {
  73682. const Font fallbackFont (Font::getFallbackFontName(), 10, 0);
  73683. Typeface* const fallbackTypeface = fallbackFont.getTypeface();
  73684. if (fallbackTypeface != 0 && fallbackTypeface != this)
  73685. {
  73686. //xxx
  73687. }
  73688. if (glyph == 0)
  73689. glyph = findGlyph (defaultCharacter, true);
  73690. }
  73691. }
  73692. return glyph;
  73693. }
  73694. bool CustomTypeface::loadGlyphIfPossible (const juce_wchar /*characterNeeded*/)
  73695. {
  73696. return false;
  73697. }
  73698. void CustomTypeface::addGlyphsFromOtherTypeface (Typeface& typefaceToCopy, juce_wchar characterStartIndex, int numCharacters) throw()
  73699. {
  73700. setCharacteristics (name, typefaceToCopy.getAscent(), isBold, isItalic, defaultCharacter);
  73701. for (int i = 0; i < numCharacters; ++i)
  73702. {
  73703. const juce_wchar c = (juce_wchar) (characterStartIndex + i);
  73704. Array <int> glyphIndexes;
  73705. Array <float> offsets;
  73706. typefaceToCopy.getGlyphPositions (String::charToString (c), glyphIndexes, offsets);
  73707. const int glyphIndex = glyphIndexes.getFirst();
  73708. if (glyphIndex >= 0 && glyphIndexes.size() > 0)
  73709. {
  73710. const float glyphWidth = offsets[1];
  73711. Path p;
  73712. typefaceToCopy.getOutlineForGlyph (glyphIndex, p);
  73713. addGlyph (c, p, glyphWidth);
  73714. for (int j = glyphs.size() - 1; --j >= 0;)
  73715. {
  73716. const juce_wchar char2 = glyphs.getUnchecked (j)->character;
  73717. glyphIndexes.clearQuick();
  73718. offsets.clearQuick();
  73719. typefaceToCopy.getGlyphPositions (String::charToString (c) + String::charToString (char2), glyphIndexes, offsets);
  73720. if (offsets.size() > 1)
  73721. addKerningPair (c, char2, offsets[1] - glyphWidth);
  73722. }
  73723. }
  73724. }
  73725. }
  73726. bool CustomTypeface::writeToStream (OutputStream& outputStream)
  73727. {
  73728. GZIPCompressorOutputStream out (&outputStream);
  73729. out.writeString (name);
  73730. out.writeBool (isBold);
  73731. out.writeBool (isItalic);
  73732. out.writeFloat (ascent);
  73733. out.writeShort ((short) (unsigned short) defaultCharacter);
  73734. out.writeInt (glyphs.size());
  73735. int i, numKerningPairs = 0;
  73736. for (i = 0; i < glyphs.size(); ++i)
  73737. {
  73738. const GlyphInfo* const g = glyphs.getUnchecked (i);
  73739. out.writeShort ((short) (unsigned short) g->character);
  73740. out.writeFloat (g->width);
  73741. g->path.writePathToStream (out);
  73742. numKerningPairs += g->kerningPairs.size();
  73743. }
  73744. out.writeInt (numKerningPairs);
  73745. for (i = 0; i < glyphs.size(); ++i)
  73746. {
  73747. const GlyphInfo* const g = glyphs.getUnchecked (i);
  73748. for (int j = 0; j < g->kerningPairs.size(); ++j)
  73749. {
  73750. const GlyphInfo::KerningPair& p = g->kerningPairs.getReference (j);
  73751. out.writeShort ((short) (unsigned short) g->character);
  73752. out.writeShort ((short) (unsigned short) p.character2);
  73753. out.writeFloat (p.kerningAmount);
  73754. }
  73755. }
  73756. return true;
  73757. }
  73758. float CustomTypeface::getAscent() const
  73759. {
  73760. return ascent;
  73761. }
  73762. float CustomTypeface::getDescent() const
  73763. {
  73764. return 1.0f - ascent;
  73765. }
  73766. float CustomTypeface::getStringWidth (const String& text)
  73767. {
  73768. float x = 0;
  73769. const juce_wchar* t = text;
  73770. while (*t != 0)
  73771. {
  73772. const GlyphInfo* const glyph = findGlyphSubstituting (*t++);
  73773. if (glyph != 0)
  73774. x += glyph->getHorizontalSpacing (*t);
  73775. }
  73776. return x;
  73777. }
  73778. void CustomTypeface::getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array<float>& xOffsets)
  73779. {
  73780. xOffsets.add (0);
  73781. float x = 0;
  73782. const juce_wchar* t = text;
  73783. while (*t != 0)
  73784. {
  73785. const juce_wchar c = *t++;
  73786. const GlyphInfo* const glyph = findGlyphSubstituting (c);
  73787. if (glyph != 0)
  73788. {
  73789. x += glyph->getHorizontalSpacing (*t);
  73790. resultGlyphs.add ((int) glyph->character);
  73791. xOffsets.add (x);
  73792. }
  73793. }
  73794. }
  73795. bool CustomTypeface::getOutlineForGlyph (int glyphNumber, Path& path)
  73796. {
  73797. const GlyphInfo* const glyph = findGlyphSubstituting ((juce_wchar) glyphNumber);
  73798. if (glyph != 0)
  73799. {
  73800. path = glyph->path;
  73801. return true;
  73802. }
  73803. return false;
  73804. }
  73805. END_JUCE_NAMESPACE
  73806. /*** End of inlined file: juce_Typeface.cpp ***/
  73807. /*** Start of inlined file: juce_AffineTransform.cpp ***/
  73808. BEGIN_JUCE_NAMESPACE
  73809. AffineTransform::AffineTransform() throw()
  73810. : mat00 (1.0f),
  73811. mat01 (0),
  73812. mat02 (0),
  73813. mat10 (0),
  73814. mat11 (1.0f),
  73815. mat12 (0)
  73816. {
  73817. }
  73818. AffineTransform::AffineTransform (const AffineTransform& other) throw()
  73819. : mat00 (other.mat00),
  73820. mat01 (other.mat01),
  73821. mat02 (other.mat02),
  73822. mat10 (other.mat10),
  73823. mat11 (other.mat11),
  73824. mat12 (other.mat12)
  73825. {
  73826. }
  73827. AffineTransform::AffineTransform (const float mat00_,
  73828. const float mat01_,
  73829. const float mat02_,
  73830. const float mat10_,
  73831. const float mat11_,
  73832. const float mat12_) throw()
  73833. : mat00 (mat00_),
  73834. mat01 (mat01_),
  73835. mat02 (mat02_),
  73836. mat10 (mat10_),
  73837. mat11 (mat11_),
  73838. mat12 (mat12_)
  73839. {
  73840. }
  73841. AffineTransform& AffineTransform::operator= (const AffineTransform& other) throw()
  73842. {
  73843. mat00 = other.mat00;
  73844. mat01 = other.mat01;
  73845. mat02 = other.mat02;
  73846. mat10 = other.mat10;
  73847. mat11 = other.mat11;
  73848. mat12 = other.mat12;
  73849. return *this;
  73850. }
  73851. bool AffineTransform::operator== (const AffineTransform& other) const throw()
  73852. {
  73853. return mat00 == other.mat00
  73854. && mat01 == other.mat01
  73855. && mat02 == other.mat02
  73856. && mat10 == other.mat10
  73857. && mat11 == other.mat11
  73858. && mat12 == other.mat12;
  73859. }
  73860. bool AffineTransform::operator!= (const AffineTransform& other) const throw()
  73861. {
  73862. return ! operator== (other);
  73863. }
  73864. bool AffineTransform::isIdentity() const throw()
  73865. {
  73866. return (mat01 == 0)
  73867. && (mat02 == 0)
  73868. && (mat10 == 0)
  73869. && (mat12 == 0)
  73870. && (mat00 == 1.0f)
  73871. && (mat11 == 1.0f);
  73872. }
  73873. const AffineTransform AffineTransform::identity;
  73874. const AffineTransform AffineTransform::followedBy (const AffineTransform& other) const throw()
  73875. {
  73876. return AffineTransform (other.mat00 * mat00 + other.mat01 * mat10,
  73877. other.mat00 * mat01 + other.mat01 * mat11,
  73878. other.mat00 * mat02 + other.mat01 * mat12 + other.mat02,
  73879. other.mat10 * mat00 + other.mat11 * mat10,
  73880. other.mat10 * mat01 + other.mat11 * mat11,
  73881. other.mat10 * mat02 + other.mat11 * mat12 + other.mat12);
  73882. }
  73883. const AffineTransform AffineTransform::followedBy (const float omat00,
  73884. const float omat01,
  73885. const float omat02,
  73886. const float omat10,
  73887. const float omat11,
  73888. const float omat12) const throw()
  73889. {
  73890. return AffineTransform (omat00 * mat00 + omat01 * mat10,
  73891. omat00 * mat01 + omat01 * mat11,
  73892. omat00 * mat02 + omat01 * mat12 + omat02,
  73893. omat10 * mat00 + omat11 * mat10,
  73894. omat10 * mat01 + omat11 * mat11,
  73895. omat10 * mat02 + omat11 * mat12 + omat12);
  73896. }
  73897. const AffineTransform AffineTransform::translated (const float dx,
  73898. const float dy) const throw()
  73899. {
  73900. return AffineTransform (mat00, mat01, mat02 + dx,
  73901. mat10, mat11, mat12 + dy);
  73902. }
  73903. const AffineTransform AffineTransform::translation (const float dx,
  73904. const float dy) throw()
  73905. {
  73906. return AffineTransform (1.0f, 0, dx,
  73907. 0, 1.0f, dy);
  73908. }
  73909. const AffineTransform AffineTransform::rotated (const float rad) const throw()
  73910. {
  73911. const float cosRad = std::cos (rad);
  73912. const float sinRad = std::sin (rad);
  73913. return followedBy (cosRad, -sinRad, 0,
  73914. sinRad, cosRad, 0);
  73915. }
  73916. const AffineTransform AffineTransform::rotation (const float rad) throw()
  73917. {
  73918. const float cosRad = std::cos (rad);
  73919. const float sinRad = std::sin (rad);
  73920. return AffineTransform (cosRad, -sinRad, 0,
  73921. sinRad, cosRad, 0);
  73922. }
  73923. const AffineTransform AffineTransform::rotated (const float angle,
  73924. const float pivotX,
  73925. const float pivotY) const throw()
  73926. {
  73927. return translated (-pivotX, -pivotY)
  73928. .rotated (angle)
  73929. .translated (pivotX, pivotY);
  73930. }
  73931. const AffineTransform AffineTransform::rotation (const float angle,
  73932. const float pivotX,
  73933. const float pivotY) throw()
  73934. {
  73935. return translation (-pivotX, -pivotY)
  73936. .rotated (angle)
  73937. .translated (pivotX, pivotY);
  73938. }
  73939. const AffineTransform AffineTransform::scaled (const float factorX,
  73940. const float factorY) const throw()
  73941. {
  73942. return AffineTransform (factorX * mat00, factorX * mat01, factorX * mat02,
  73943. factorY * mat10, factorY * mat11, factorY * mat12);
  73944. }
  73945. const AffineTransform AffineTransform::scale (const float factorX,
  73946. const float factorY) throw()
  73947. {
  73948. return AffineTransform (factorX, 0, 0,
  73949. 0, factorY, 0);
  73950. }
  73951. const AffineTransform AffineTransform::sheared (const float shearX,
  73952. const float shearY) const throw()
  73953. {
  73954. return followedBy (1.0f, shearX, 0,
  73955. shearY, 1.0f, 0);
  73956. }
  73957. const AffineTransform AffineTransform::inverted() const throw()
  73958. {
  73959. double determinant = (mat00 * mat11 - mat10 * mat01);
  73960. if (determinant != 0.0)
  73961. {
  73962. determinant = 1.0 / determinant;
  73963. const float dst00 = (float) (mat11 * determinant);
  73964. const float dst10 = (float) (-mat10 * determinant);
  73965. const float dst01 = (float) (-mat01 * determinant);
  73966. const float dst11 = (float) (mat00 * determinant);
  73967. return AffineTransform (dst00, dst01, -mat02 * dst00 - mat12 * dst01,
  73968. dst10, dst11, -mat02 * dst10 - mat12 * dst11);
  73969. }
  73970. else
  73971. {
  73972. // singularity..
  73973. return *this;
  73974. }
  73975. }
  73976. bool AffineTransform::isSingularity() const throw()
  73977. {
  73978. return (mat00 * mat11 - mat10 * mat01) == 0.0;
  73979. }
  73980. const AffineTransform AffineTransform::fromTargetPoints (const float x00, const float y00,
  73981. const float x10, const float y10,
  73982. const float x01, const float y01) throw()
  73983. {
  73984. return AffineTransform (x10 - x00, x01 - x00, x00,
  73985. y10 - y00, y01 - y00, y00);
  73986. }
  73987. const AffineTransform AffineTransform::fromTargetPoints (const float sx1, const float sy1, const float tx1, const float ty1,
  73988. const float sx2, const float sy2, const float tx2, const float ty2,
  73989. const float sx3, const float sy3, const float tx3, const float ty3) throw()
  73990. {
  73991. return fromTargetPoints (sx1, sy1, sx2, sy2, sx3, sy3)
  73992. .inverted()
  73993. .followedBy (fromTargetPoints (tx1, ty1, tx2, ty2, tx3, ty3));
  73994. }
  73995. bool AffineTransform::isOnlyTranslation() const throw()
  73996. {
  73997. return (mat01 == 0)
  73998. && (mat10 == 0)
  73999. && (mat00 == 1.0f)
  74000. && (mat11 == 1.0f);
  74001. }
  74002. END_JUCE_NAMESPACE
  74003. /*** End of inlined file: juce_AffineTransform.cpp ***/
  74004. /*** Start of inlined file: juce_BorderSize.cpp ***/
  74005. BEGIN_JUCE_NAMESPACE
  74006. BorderSize::BorderSize() throw()
  74007. : top (0),
  74008. left (0),
  74009. bottom (0),
  74010. right (0)
  74011. {
  74012. }
  74013. BorderSize::BorderSize (const BorderSize& other) throw()
  74014. : top (other.top),
  74015. left (other.left),
  74016. bottom (other.bottom),
  74017. right (other.right)
  74018. {
  74019. }
  74020. BorderSize::BorderSize (const int topGap,
  74021. const int leftGap,
  74022. const int bottomGap,
  74023. const int rightGap) throw()
  74024. : top (topGap),
  74025. left (leftGap),
  74026. bottom (bottomGap),
  74027. right (rightGap)
  74028. {
  74029. }
  74030. BorderSize::BorderSize (const int allGaps) throw()
  74031. : top (allGaps),
  74032. left (allGaps),
  74033. bottom (allGaps),
  74034. right (allGaps)
  74035. {
  74036. }
  74037. BorderSize::~BorderSize() throw()
  74038. {
  74039. }
  74040. void BorderSize::setTop (const int newTopGap) throw()
  74041. {
  74042. top = newTopGap;
  74043. }
  74044. void BorderSize::setLeft (const int newLeftGap) throw()
  74045. {
  74046. left = newLeftGap;
  74047. }
  74048. void BorderSize::setBottom (const int newBottomGap) throw()
  74049. {
  74050. bottom = newBottomGap;
  74051. }
  74052. void BorderSize::setRight (const int newRightGap) throw()
  74053. {
  74054. right = newRightGap;
  74055. }
  74056. const Rectangle<int> BorderSize::subtractedFrom (const Rectangle<int>& r) const throw()
  74057. {
  74058. return Rectangle<int> (r.getX() + left,
  74059. r.getY() + top,
  74060. r.getWidth() - (left + right),
  74061. r.getHeight() - (top + bottom));
  74062. }
  74063. void BorderSize::subtractFrom (Rectangle<int>& r) const throw()
  74064. {
  74065. r.setBounds (r.getX() + left,
  74066. r.getY() + top,
  74067. r.getWidth() - (left + right),
  74068. r.getHeight() - (top + bottom));
  74069. }
  74070. const Rectangle<int> BorderSize::addedTo (const Rectangle<int>& r) const throw()
  74071. {
  74072. return Rectangle<int> (r.getX() - left,
  74073. r.getY() - top,
  74074. r.getWidth() + (left + right),
  74075. r.getHeight() + (top + bottom));
  74076. }
  74077. void BorderSize::addTo (Rectangle<int>& r) const throw()
  74078. {
  74079. r.setBounds (r.getX() - left,
  74080. r.getY() - top,
  74081. r.getWidth() + (left + right),
  74082. r.getHeight() + (top + bottom));
  74083. }
  74084. bool BorderSize::operator== (const BorderSize& other) const throw()
  74085. {
  74086. return top == other.top
  74087. && left == other.left
  74088. && bottom == other.bottom
  74089. && right == other.right;
  74090. }
  74091. bool BorderSize::operator!= (const BorderSize& other) const throw()
  74092. {
  74093. return ! operator== (other);
  74094. }
  74095. END_JUCE_NAMESPACE
  74096. /*** End of inlined file: juce_BorderSize.cpp ***/
  74097. /*** Start of inlined file: juce_Path.cpp ***/
  74098. BEGIN_JUCE_NAMESPACE
  74099. // tests that some co-ords aren't NaNs
  74100. #define CHECK_COORDS_ARE_VALID(x, y) \
  74101. jassert (x == x && y == y);
  74102. namespace PathHelpers
  74103. {
  74104. static const float ellipseAngularIncrement = 0.05f;
  74105. static const String nextToken (const juce_wchar*& t)
  74106. {
  74107. while (CharacterFunctions::isWhitespace (*t))
  74108. ++t;
  74109. const juce_wchar* const start = t;
  74110. while (*t != 0 && ! CharacterFunctions::isWhitespace (*t))
  74111. ++t;
  74112. return String (start, (int) (t - start));
  74113. }
  74114. }
  74115. const float Path::lineMarker = 100001.0f;
  74116. const float Path::moveMarker = 100002.0f;
  74117. const float Path::quadMarker = 100003.0f;
  74118. const float Path::cubicMarker = 100004.0f;
  74119. const float Path::closeSubPathMarker = 100005.0f;
  74120. Path::Path()
  74121. : numElements (0),
  74122. pathXMin (0),
  74123. pathXMax (0),
  74124. pathYMin (0),
  74125. pathYMax (0),
  74126. useNonZeroWinding (true)
  74127. {
  74128. }
  74129. Path::~Path()
  74130. {
  74131. }
  74132. Path::Path (const Path& other)
  74133. : numElements (other.numElements),
  74134. pathXMin (other.pathXMin),
  74135. pathXMax (other.pathXMax),
  74136. pathYMin (other.pathYMin),
  74137. pathYMax (other.pathYMax),
  74138. useNonZeroWinding (other.useNonZeroWinding)
  74139. {
  74140. if (numElements > 0)
  74141. {
  74142. data.setAllocatedSize ((int) numElements);
  74143. memcpy (data.elements, other.data.elements, numElements * sizeof (float));
  74144. }
  74145. }
  74146. Path& Path::operator= (const Path& other)
  74147. {
  74148. if (this != &other)
  74149. {
  74150. data.ensureAllocatedSize ((int) other.numElements);
  74151. numElements = other.numElements;
  74152. pathXMin = other.pathXMin;
  74153. pathXMax = other.pathXMax;
  74154. pathYMin = other.pathYMin;
  74155. pathYMax = other.pathYMax;
  74156. useNonZeroWinding = other.useNonZeroWinding;
  74157. if (numElements > 0)
  74158. memcpy (data.elements, other.data.elements, numElements * sizeof (float));
  74159. }
  74160. return *this;
  74161. }
  74162. bool Path::operator== (const Path& other) const throw()
  74163. {
  74164. return ! operator!= (other);
  74165. }
  74166. bool Path::operator!= (const Path& other) const throw()
  74167. {
  74168. if (numElements != other.numElements || useNonZeroWinding != other.useNonZeroWinding)
  74169. return true;
  74170. for (size_t i = 0; i < numElements; ++i)
  74171. if (data.elements[i] != other.data.elements[i])
  74172. return true;
  74173. return false;
  74174. }
  74175. void Path::clear() throw()
  74176. {
  74177. numElements = 0;
  74178. pathXMin = 0;
  74179. pathYMin = 0;
  74180. pathYMax = 0;
  74181. pathXMax = 0;
  74182. }
  74183. void Path::swapWithPath (Path& other) throw()
  74184. {
  74185. data.swapWith (other.data);
  74186. swapVariables <size_t> (numElements, other.numElements);
  74187. swapVariables <float> (pathXMin, other.pathXMin);
  74188. swapVariables <float> (pathXMax, other.pathXMax);
  74189. swapVariables <float> (pathYMin, other.pathYMin);
  74190. swapVariables <float> (pathYMax, other.pathYMax);
  74191. swapVariables <bool> (useNonZeroWinding, other.useNonZeroWinding);
  74192. }
  74193. void Path::setUsingNonZeroWinding (const bool isNonZero) throw()
  74194. {
  74195. useNonZeroWinding = isNonZero;
  74196. }
  74197. void Path::scaleToFit (const float x, const float y, const float w, const float h,
  74198. const bool preserveProportions) throw()
  74199. {
  74200. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions));
  74201. }
  74202. bool Path::isEmpty() const throw()
  74203. {
  74204. size_t i = 0;
  74205. while (i < numElements)
  74206. {
  74207. const float type = data.elements [i++];
  74208. if (type == moveMarker)
  74209. {
  74210. i += 2;
  74211. }
  74212. else if (type == lineMarker
  74213. || type == quadMarker
  74214. || type == cubicMarker)
  74215. {
  74216. return false;
  74217. }
  74218. }
  74219. return true;
  74220. }
  74221. const Rectangle<float> Path::getBounds() const throw()
  74222. {
  74223. return Rectangle<float> (pathXMin, pathYMin,
  74224. pathXMax - pathXMin,
  74225. pathYMax - pathYMin);
  74226. }
  74227. const Rectangle<float> Path::getBoundsTransformed (const AffineTransform& transform) const throw()
  74228. {
  74229. return getBounds().transformed (transform);
  74230. }
  74231. void Path::startNewSubPath (const float x, const float y)
  74232. {
  74233. CHECK_COORDS_ARE_VALID (x, y);
  74234. if (numElements == 0)
  74235. {
  74236. pathXMin = pathXMax = x;
  74237. pathYMin = pathYMax = y;
  74238. }
  74239. else
  74240. {
  74241. pathXMin = jmin (pathXMin, x);
  74242. pathXMax = jmax (pathXMax, x);
  74243. pathYMin = jmin (pathYMin, y);
  74244. pathYMax = jmax (pathYMax, y);
  74245. }
  74246. data.ensureAllocatedSize ((int) numElements + 3);
  74247. data.elements [numElements++] = moveMarker;
  74248. data.elements [numElements++] = x;
  74249. data.elements [numElements++] = y;
  74250. }
  74251. void Path::startNewSubPath (const Point<float>& start)
  74252. {
  74253. startNewSubPath (start.getX(), start.getY());
  74254. }
  74255. void Path::lineTo (const float x, const float y)
  74256. {
  74257. CHECK_COORDS_ARE_VALID (x, y);
  74258. if (numElements == 0)
  74259. startNewSubPath (0, 0);
  74260. data.ensureAllocatedSize ((int) numElements + 3);
  74261. data.elements [numElements++] = lineMarker;
  74262. data.elements [numElements++] = x;
  74263. data.elements [numElements++] = y;
  74264. pathXMin = jmin (pathXMin, x);
  74265. pathXMax = jmax (pathXMax, x);
  74266. pathYMin = jmin (pathYMin, y);
  74267. pathYMax = jmax (pathYMax, y);
  74268. }
  74269. void Path::lineTo (const Point<float>& end)
  74270. {
  74271. lineTo (end.getX(), end.getY());
  74272. }
  74273. void Path::quadraticTo (const float x1, const float y1,
  74274. const float x2, const float y2)
  74275. {
  74276. CHECK_COORDS_ARE_VALID (x1, y1);
  74277. CHECK_COORDS_ARE_VALID (x2, y2);
  74278. if (numElements == 0)
  74279. startNewSubPath (0, 0);
  74280. data.ensureAllocatedSize ((int) numElements + 5);
  74281. data.elements [numElements++] = quadMarker;
  74282. data.elements [numElements++] = x1;
  74283. data.elements [numElements++] = y1;
  74284. data.elements [numElements++] = x2;
  74285. data.elements [numElements++] = y2;
  74286. pathXMin = jmin (pathXMin, x1, x2);
  74287. pathXMax = jmax (pathXMax, x1, x2);
  74288. pathYMin = jmin (pathYMin, y1, y2);
  74289. pathYMax = jmax (pathYMax, y1, y2);
  74290. }
  74291. void Path::quadraticTo (const Point<float>& controlPoint,
  74292. const Point<float>& endPoint)
  74293. {
  74294. quadraticTo (controlPoint.getX(), controlPoint.getY(),
  74295. endPoint.getX(), endPoint.getY());
  74296. }
  74297. void Path::cubicTo (const float x1, const float y1,
  74298. const float x2, const float y2,
  74299. const float x3, const float y3)
  74300. {
  74301. CHECK_COORDS_ARE_VALID (x1, y1);
  74302. CHECK_COORDS_ARE_VALID (x2, y2);
  74303. CHECK_COORDS_ARE_VALID (x3, y3);
  74304. if (numElements == 0)
  74305. startNewSubPath (0, 0);
  74306. data.ensureAllocatedSize ((int) numElements + 7);
  74307. data.elements [numElements++] = cubicMarker;
  74308. data.elements [numElements++] = x1;
  74309. data.elements [numElements++] = y1;
  74310. data.elements [numElements++] = x2;
  74311. data.elements [numElements++] = y2;
  74312. data.elements [numElements++] = x3;
  74313. data.elements [numElements++] = y3;
  74314. pathXMin = jmin (pathXMin, x1, x2, x3);
  74315. pathXMax = jmax (pathXMax, x1, x2, x3);
  74316. pathYMin = jmin (pathYMin, y1, y2, y3);
  74317. pathYMax = jmax (pathYMax, y1, y2, y3);
  74318. }
  74319. void Path::cubicTo (const Point<float>& controlPoint1,
  74320. const Point<float>& controlPoint2,
  74321. const Point<float>& endPoint)
  74322. {
  74323. cubicTo (controlPoint1.getX(), controlPoint1.getY(),
  74324. controlPoint2.getX(), controlPoint2.getY(),
  74325. endPoint.getX(), endPoint.getY());
  74326. }
  74327. void Path::closeSubPath()
  74328. {
  74329. if (numElements > 0
  74330. && data.elements [numElements - 1] != closeSubPathMarker)
  74331. {
  74332. data.ensureAllocatedSize ((int) numElements + 1);
  74333. data.elements [numElements++] = closeSubPathMarker;
  74334. }
  74335. }
  74336. const Point<float> Path::getCurrentPosition() const
  74337. {
  74338. size_t i = numElements - 1;
  74339. if (i > 0 && data.elements[i] == closeSubPathMarker)
  74340. {
  74341. while (i >= 0)
  74342. {
  74343. if (data.elements[i] == moveMarker)
  74344. {
  74345. i += 2;
  74346. break;
  74347. }
  74348. --i;
  74349. }
  74350. }
  74351. if (i > 0)
  74352. return Point<float> (data.elements [i - 1], data.elements [i]);
  74353. return Point<float>();
  74354. }
  74355. void Path::addRectangle (const float x, const float y,
  74356. const float w, const float h)
  74357. {
  74358. float x1 = x, y1 = y, x2 = x + w, y2 = y + h;
  74359. if (w < 0)
  74360. swapVariables (x1, x2);
  74361. if (h < 0)
  74362. swapVariables (y1, y2);
  74363. data.ensureAllocatedSize ((int) numElements + 13);
  74364. if (numElements == 0)
  74365. {
  74366. pathXMin = x1;
  74367. pathXMax = x2;
  74368. pathYMin = y1;
  74369. pathYMax = y2;
  74370. }
  74371. else
  74372. {
  74373. pathXMin = jmin (pathXMin, x1);
  74374. pathXMax = jmax (pathXMax, x2);
  74375. pathYMin = jmin (pathYMin, y1);
  74376. pathYMax = jmax (pathYMax, y2);
  74377. }
  74378. data.elements [numElements++] = moveMarker;
  74379. data.elements [numElements++] = x1;
  74380. data.elements [numElements++] = y2;
  74381. data.elements [numElements++] = lineMarker;
  74382. data.elements [numElements++] = x1;
  74383. data.elements [numElements++] = y1;
  74384. data.elements [numElements++] = lineMarker;
  74385. data.elements [numElements++] = x2;
  74386. data.elements [numElements++] = y1;
  74387. data.elements [numElements++] = lineMarker;
  74388. data.elements [numElements++] = x2;
  74389. data.elements [numElements++] = y2;
  74390. data.elements [numElements++] = closeSubPathMarker;
  74391. }
  74392. void Path::addRoundedRectangle (const float x, const float y,
  74393. const float w, const float h,
  74394. float csx,
  74395. float csy)
  74396. {
  74397. csx = jmin (csx, w * 0.5f);
  74398. csy = jmin (csy, h * 0.5f);
  74399. const float cs45x = csx * 0.45f;
  74400. const float cs45y = csy * 0.45f;
  74401. const float x2 = x + w;
  74402. const float y2 = y + h;
  74403. startNewSubPath (x + csx, y);
  74404. lineTo (x2 - csx, y);
  74405. cubicTo (x2 - cs45x, y, x2, y + cs45y, x2, y + csy);
  74406. lineTo (x2, y2 - csy);
  74407. cubicTo (x2, y2 - cs45y, x2 - cs45x, y2, x2 - csx, y2);
  74408. lineTo (x + csx, y2);
  74409. cubicTo (x + cs45x, y2, x, y2 - cs45y, x, y2 - csy);
  74410. lineTo (x, y + csy);
  74411. cubicTo (x, y + cs45y, x + cs45x, y, x + csx, y);
  74412. closeSubPath();
  74413. }
  74414. void Path::addRoundedRectangle (const float x, const float y,
  74415. const float w, const float h,
  74416. float cs)
  74417. {
  74418. addRoundedRectangle (x, y, w, h, cs, cs);
  74419. }
  74420. void Path::addTriangle (const float x1, const float y1,
  74421. const float x2, const float y2,
  74422. const float x3, const float y3)
  74423. {
  74424. startNewSubPath (x1, y1);
  74425. lineTo (x2, y2);
  74426. lineTo (x3, y3);
  74427. closeSubPath();
  74428. }
  74429. void Path::addQuadrilateral (const float x1, const float y1,
  74430. const float x2, const float y2,
  74431. const float x3, const float y3,
  74432. const float x4, const float y4)
  74433. {
  74434. startNewSubPath (x1, y1);
  74435. lineTo (x2, y2);
  74436. lineTo (x3, y3);
  74437. lineTo (x4, y4);
  74438. closeSubPath();
  74439. }
  74440. void Path::addEllipse (const float x, const float y,
  74441. const float w, const float h)
  74442. {
  74443. const float hw = w * 0.5f;
  74444. const float hw55 = hw * 0.55f;
  74445. const float hh = h * 0.5f;
  74446. const float hh55 = hh * 0.55f;
  74447. const float cx = x + hw;
  74448. const float cy = y + hh;
  74449. startNewSubPath (cx, cy - hh);
  74450. cubicTo (cx + hw55, cy - hh, cx + hw, cy - hh55, cx + hw, cy);
  74451. cubicTo (cx + hw, cy + hh55, cx + hw55, cy + hh, cx, cy + hh);
  74452. cubicTo (cx - hw55, cy + hh, cx - hw, cy + hh55, cx - hw, cy);
  74453. cubicTo (cx - hw, cy - hh55, cx - hw55, cy - hh, cx, cy - hh);
  74454. closeSubPath();
  74455. }
  74456. void Path::addArc (const float x, const float y,
  74457. const float w, const float h,
  74458. const float fromRadians,
  74459. const float toRadians,
  74460. const bool startAsNewSubPath)
  74461. {
  74462. const float radiusX = w / 2.0f;
  74463. const float radiusY = h / 2.0f;
  74464. addCentredArc (x + radiusX,
  74465. y + radiusY,
  74466. radiusX, radiusY,
  74467. 0.0f,
  74468. fromRadians, toRadians,
  74469. startAsNewSubPath);
  74470. }
  74471. void Path::addCentredArc (const float centreX, const float centreY,
  74472. const float radiusX, const float radiusY,
  74473. const float rotationOfEllipse,
  74474. const float fromRadians,
  74475. const float toRadians,
  74476. const bool startAsNewSubPath)
  74477. {
  74478. if (radiusX > 0.0f && radiusY > 0.0f)
  74479. {
  74480. const Point<float> centre (centreX, centreY);
  74481. const AffineTransform rotation (AffineTransform::rotation (rotationOfEllipse, centreX, centreY));
  74482. float angle = fromRadians;
  74483. if (startAsNewSubPath)
  74484. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  74485. if (fromRadians < toRadians)
  74486. {
  74487. if (startAsNewSubPath)
  74488. angle += PathHelpers::ellipseAngularIncrement;
  74489. while (angle < toRadians)
  74490. {
  74491. lineTo (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  74492. angle += PathHelpers::ellipseAngularIncrement;
  74493. }
  74494. }
  74495. else
  74496. {
  74497. if (startAsNewSubPath)
  74498. angle -= PathHelpers::ellipseAngularIncrement;
  74499. while (angle > toRadians)
  74500. {
  74501. lineTo (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  74502. angle -= PathHelpers::ellipseAngularIncrement;
  74503. }
  74504. }
  74505. lineTo (centre.getPointOnCircumference (radiusX, radiusY, toRadians).transformedBy (rotation));
  74506. }
  74507. }
  74508. void Path::addPieSegment (const float x, const float y,
  74509. const float width, const float height,
  74510. const float fromRadians,
  74511. const float toRadians,
  74512. const float innerCircleProportionalSize)
  74513. {
  74514. float radiusX = width * 0.5f;
  74515. float radiusY = height * 0.5f;
  74516. const Point<float> centre (x + radiusX, y + radiusY);
  74517. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, fromRadians));
  74518. addArc (x, y, width, height, fromRadians, toRadians);
  74519. if (std::abs (fromRadians - toRadians) > float_Pi * 1.999f)
  74520. {
  74521. closeSubPath();
  74522. if (innerCircleProportionalSize > 0)
  74523. {
  74524. radiusX *= innerCircleProportionalSize;
  74525. radiusY *= innerCircleProportionalSize;
  74526. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, toRadians));
  74527. addArc (centre.getX() - radiusX, centre.getY() - radiusY, radiusX * 2.0f, radiusY * 2.0f, toRadians, fromRadians);
  74528. }
  74529. }
  74530. else
  74531. {
  74532. if (innerCircleProportionalSize > 0)
  74533. {
  74534. radiusX *= innerCircleProportionalSize;
  74535. radiusY *= innerCircleProportionalSize;
  74536. addArc (centre.getX() - radiusX, centre.getY() - radiusY, radiusX * 2.0f, radiusY * 2.0f, toRadians, fromRadians);
  74537. }
  74538. else
  74539. {
  74540. lineTo (centre);
  74541. }
  74542. }
  74543. closeSubPath();
  74544. }
  74545. void Path::addLineSegment (const Line<float>& line, float lineThickness)
  74546. {
  74547. const Line<float> reversed (line.reversed());
  74548. lineThickness *= 0.5f;
  74549. startNewSubPath (line.getPointAlongLine (0, lineThickness));
  74550. lineTo (line.getPointAlongLine (0, -lineThickness));
  74551. lineTo (reversed.getPointAlongLine (0, lineThickness));
  74552. lineTo (reversed.getPointAlongLine (0, -lineThickness));
  74553. closeSubPath();
  74554. }
  74555. void Path::addArrow (const Line<float>& line, float lineThickness,
  74556. float arrowheadWidth, float arrowheadLength)
  74557. {
  74558. const Line<float> reversed (line.reversed());
  74559. lineThickness *= 0.5f;
  74560. arrowheadWidth *= 0.5f;
  74561. arrowheadLength = jmin (arrowheadLength, 0.8f * line.getLength());
  74562. startNewSubPath (line.getPointAlongLine (0, lineThickness));
  74563. lineTo (line.getPointAlongLine (0, -lineThickness));
  74564. lineTo (reversed.getPointAlongLine (arrowheadLength, lineThickness));
  74565. lineTo (reversed.getPointAlongLine (arrowheadLength, arrowheadWidth));
  74566. lineTo (line.getEnd());
  74567. lineTo (reversed.getPointAlongLine (arrowheadLength, -arrowheadWidth));
  74568. lineTo (reversed.getPointAlongLine (arrowheadLength, -lineThickness));
  74569. closeSubPath();
  74570. }
  74571. void Path::addPolygon (const Point<float>& centre, const int numberOfSides,
  74572. const float radius, const float startAngle)
  74573. {
  74574. jassert (numberOfSides > 1); // this would be silly.
  74575. if (numberOfSides > 1)
  74576. {
  74577. const float angleBetweenPoints = float_Pi * 2.0f / numberOfSides;
  74578. for (int i = 0; i < numberOfSides; ++i)
  74579. {
  74580. const float angle = startAngle + i * angleBetweenPoints;
  74581. const Point<float> p (centre.getPointOnCircumference (radius, angle));
  74582. if (i == 0)
  74583. startNewSubPath (p);
  74584. else
  74585. lineTo (p);
  74586. }
  74587. closeSubPath();
  74588. }
  74589. }
  74590. void Path::addStar (const Point<float>& centre, const int numberOfPoints,
  74591. const float innerRadius, const float outerRadius, const float startAngle)
  74592. {
  74593. jassert (numberOfPoints > 1); // this would be silly.
  74594. if (numberOfPoints > 1)
  74595. {
  74596. const float angleBetweenPoints = float_Pi * 2.0f / numberOfPoints;
  74597. for (int i = 0; i < numberOfPoints; ++i)
  74598. {
  74599. const float angle = startAngle + i * angleBetweenPoints;
  74600. const Point<float> p (centre.getPointOnCircumference (outerRadius, angle));
  74601. if (i == 0)
  74602. startNewSubPath (p);
  74603. else
  74604. lineTo (p);
  74605. lineTo (centre.getPointOnCircumference (innerRadius, angle + angleBetweenPoints * 0.5f));
  74606. }
  74607. closeSubPath();
  74608. }
  74609. }
  74610. void Path::addBubble (float x, float y,
  74611. float w, float h,
  74612. float cs,
  74613. float tipX,
  74614. float tipY,
  74615. int whichSide,
  74616. float arrowPos,
  74617. float arrowWidth)
  74618. {
  74619. if (w > 1.0f && h > 1.0f)
  74620. {
  74621. cs = jmin (cs, w * 0.5f, h * 0.5f);
  74622. const float cs2 = 2.0f * cs;
  74623. startNewSubPath (x + cs, y);
  74624. if (whichSide == 0)
  74625. {
  74626. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  74627. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  74628. lineTo (arrowX1, y);
  74629. lineTo (tipX, tipY);
  74630. lineTo (arrowX1 + halfArrowW * 2.0f, y);
  74631. }
  74632. lineTo (x + w - cs, y);
  74633. if (cs > 0.0f)
  74634. addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  74635. if (whichSide == 3)
  74636. {
  74637. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  74638. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  74639. lineTo (x + w, arrowY1);
  74640. lineTo (tipX, tipY);
  74641. lineTo (x + w, arrowY1 + halfArrowH * 2.0f);
  74642. }
  74643. lineTo (x + w, y + h - cs);
  74644. if (cs > 0.0f)
  74645. addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  74646. if (whichSide == 2)
  74647. {
  74648. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  74649. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  74650. lineTo (arrowX1 + halfArrowW * 2.0f, y + h);
  74651. lineTo (tipX, tipY);
  74652. lineTo (arrowX1, y + h);
  74653. }
  74654. lineTo (x + cs, y + h);
  74655. if (cs > 0.0f)
  74656. addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  74657. if (whichSide == 1)
  74658. {
  74659. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  74660. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  74661. lineTo (x, arrowY1 + halfArrowH * 2.0f);
  74662. lineTo (tipX, tipY);
  74663. lineTo (x, arrowY1);
  74664. }
  74665. lineTo (x, y + cs);
  74666. if (cs > 0.0f)
  74667. addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f - PathHelpers::ellipseAngularIncrement);
  74668. closeSubPath();
  74669. }
  74670. }
  74671. void Path::addPath (const Path& other)
  74672. {
  74673. size_t i = 0;
  74674. while (i < other.numElements)
  74675. {
  74676. const float type = other.data.elements [i++];
  74677. if (type == moveMarker)
  74678. {
  74679. startNewSubPath (other.data.elements [i],
  74680. other.data.elements [i + 1]);
  74681. i += 2;
  74682. }
  74683. else if (type == lineMarker)
  74684. {
  74685. lineTo (other.data.elements [i],
  74686. other.data.elements [i + 1]);
  74687. i += 2;
  74688. }
  74689. else if (type == quadMarker)
  74690. {
  74691. quadraticTo (other.data.elements [i],
  74692. other.data.elements [i + 1],
  74693. other.data.elements [i + 2],
  74694. other.data.elements [i + 3]);
  74695. i += 4;
  74696. }
  74697. else if (type == cubicMarker)
  74698. {
  74699. cubicTo (other.data.elements [i],
  74700. other.data.elements [i + 1],
  74701. other.data.elements [i + 2],
  74702. other.data.elements [i + 3],
  74703. other.data.elements [i + 4],
  74704. other.data.elements [i + 5]);
  74705. i += 6;
  74706. }
  74707. else if (type == closeSubPathMarker)
  74708. {
  74709. closeSubPath();
  74710. }
  74711. else
  74712. {
  74713. // something's gone wrong with the element list!
  74714. jassertfalse;
  74715. }
  74716. }
  74717. }
  74718. void Path::addPath (const Path& other,
  74719. const AffineTransform& transformToApply)
  74720. {
  74721. size_t i = 0;
  74722. while (i < other.numElements)
  74723. {
  74724. const float type = other.data.elements [i++];
  74725. if (type == closeSubPathMarker)
  74726. {
  74727. closeSubPath();
  74728. }
  74729. else
  74730. {
  74731. float x = other.data.elements [i++];
  74732. float y = other.data.elements [i++];
  74733. transformToApply.transformPoint (x, y);
  74734. if (type == moveMarker)
  74735. {
  74736. startNewSubPath (x, y);
  74737. }
  74738. else if (type == lineMarker)
  74739. {
  74740. lineTo (x, y);
  74741. }
  74742. else if (type == quadMarker)
  74743. {
  74744. float x2 = other.data.elements [i++];
  74745. float y2 = other.data.elements [i++];
  74746. transformToApply.transformPoint (x2, y2);
  74747. quadraticTo (x, y, x2, y2);
  74748. }
  74749. else if (type == cubicMarker)
  74750. {
  74751. float x2 = other.data.elements [i++];
  74752. float y2 = other.data.elements [i++];
  74753. float x3 = other.data.elements [i++];
  74754. float y3 = other.data.elements [i++];
  74755. transformToApply.transformPoints (x2, y2, x3, y3);
  74756. cubicTo (x, y, x2, y2, x3, y3);
  74757. }
  74758. else
  74759. {
  74760. // something's gone wrong with the element list!
  74761. jassertfalse;
  74762. }
  74763. }
  74764. }
  74765. }
  74766. void Path::applyTransform (const AffineTransform& transform) throw()
  74767. {
  74768. size_t i = 0;
  74769. pathYMin = pathXMin = 0;
  74770. pathYMax = pathXMax = 0;
  74771. bool setMaxMin = false;
  74772. while (i < numElements)
  74773. {
  74774. const float type = data.elements [i++];
  74775. if (type == moveMarker)
  74776. {
  74777. transform.transformPoint (data.elements [i], data.elements [i + 1]);
  74778. if (setMaxMin)
  74779. {
  74780. pathXMin = jmin (pathXMin, data.elements [i]);
  74781. pathXMax = jmax (pathXMax, data.elements [i]);
  74782. pathYMin = jmin (pathYMin, data.elements [i + 1]);
  74783. pathYMax = jmax (pathYMax, data.elements [i + 1]);
  74784. }
  74785. else
  74786. {
  74787. pathXMin = pathXMax = data.elements [i];
  74788. pathYMin = pathYMax = data.elements [i + 1];
  74789. setMaxMin = true;
  74790. }
  74791. i += 2;
  74792. }
  74793. else if (type == lineMarker)
  74794. {
  74795. transform.transformPoint (data.elements [i], data.elements [i + 1]);
  74796. pathXMin = jmin (pathXMin, data.elements [i]);
  74797. pathXMax = jmax (pathXMax, data.elements [i]);
  74798. pathYMin = jmin (pathYMin, data.elements [i + 1]);
  74799. pathYMax = jmax (pathYMax, data.elements [i + 1]);
  74800. i += 2;
  74801. }
  74802. else if (type == quadMarker)
  74803. {
  74804. transform.transformPoints (data.elements [i], data.elements [i + 1],
  74805. data.elements [i + 2], data.elements [i + 3]);
  74806. pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2]);
  74807. pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2]);
  74808. pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3]);
  74809. pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3]);
  74810. i += 4;
  74811. }
  74812. else if (type == cubicMarker)
  74813. {
  74814. transform.transformPoints (data.elements [i], data.elements [i + 1],
  74815. data.elements [i + 2], data.elements [i + 3],
  74816. data.elements [i + 4], data.elements [i + 5]);
  74817. pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
  74818. pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
  74819. pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
  74820. pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
  74821. i += 6;
  74822. }
  74823. }
  74824. }
  74825. const AffineTransform Path::getTransformToScaleToFit (const float x, const float y,
  74826. const float w, const float h,
  74827. const bool preserveProportions,
  74828. const Justification& justification) const
  74829. {
  74830. Rectangle<float> bounds (getBounds());
  74831. if (preserveProportions)
  74832. {
  74833. if (w <= 0 || h <= 0 || bounds.isEmpty())
  74834. return AffineTransform::identity;
  74835. float newW, newH;
  74836. const float srcRatio = bounds.getHeight() / bounds.getWidth();
  74837. if (srcRatio > h / w)
  74838. {
  74839. newW = h / srcRatio;
  74840. newH = h;
  74841. }
  74842. else
  74843. {
  74844. newW = w;
  74845. newH = w * srcRatio;
  74846. }
  74847. float newXCentre = x;
  74848. float newYCentre = y;
  74849. if (justification.testFlags (Justification::left))
  74850. newXCentre += newW * 0.5f;
  74851. else if (justification.testFlags (Justification::right))
  74852. newXCentre += w - newW * 0.5f;
  74853. else
  74854. newXCentre += w * 0.5f;
  74855. if (justification.testFlags (Justification::top))
  74856. newYCentre += newH * 0.5f;
  74857. else if (justification.testFlags (Justification::bottom))
  74858. newYCentre += h - newH * 0.5f;
  74859. else
  74860. newYCentre += h * 0.5f;
  74861. return AffineTransform::translation (bounds.getWidth() * -0.5f - bounds.getX(),
  74862. bounds.getHeight() * -0.5f - bounds.getY())
  74863. .scaled (newW / bounds.getWidth(), newH / bounds.getHeight())
  74864. .translated (newXCentre, newYCentre);
  74865. }
  74866. else
  74867. {
  74868. return AffineTransform::translation (-bounds.getX(), -bounds.getY())
  74869. .scaled (w / bounds.getWidth(), h / bounds.getHeight())
  74870. .translated (x, y);
  74871. }
  74872. }
  74873. bool Path::contains (const float x, const float y, const float tolerence) const
  74874. {
  74875. if (x <= pathXMin || x >= pathXMax
  74876. || y <= pathYMin || y >= pathYMax)
  74877. return false;
  74878. PathFlatteningIterator i (*this, AffineTransform::identity, tolerence);
  74879. int positiveCrossings = 0;
  74880. int negativeCrossings = 0;
  74881. while (i.next())
  74882. {
  74883. if ((i.y1 <= y && i.y2 > y) || (i.y2 <= y && i.y1 > y))
  74884. {
  74885. const float intersectX = i.x1 + (i.x2 - i.x1) * (y - i.y1) / (i.y2 - i.y1);
  74886. if (intersectX <= x)
  74887. {
  74888. if (i.y1 < i.y2)
  74889. ++positiveCrossings;
  74890. else
  74891. ++negativeCrossings;
  74892. }
  74893. }
  74894. }
  74895. return useNonZeroWinding ? (negativeCrossings != positiveCrossings)
  74896. : ((negativeCrossings + positiveCrossings) & 1) != 0;
  74897. }
  74898. bool Path::contains (const Point<float>& point, const float tolerence) const
  74899. {
  74900. return contains (point.getX(), point.getY(), tolerence);
  74901. }
  74902. bool Path::intersectsLine (const Line<float>& line, const float tolerence)
  74903. {
  74904. PathFlatteningIterator i (*this, AffineTransform::identity, tolerence);
  74905. Point<float> intersection;
  74906. while (i.next())
  74907. if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
  74908. return true;
  74909. return false;
  74910. }
  74911. const Line<float> Path::getClippedLine (const Line<float>& line, const bool keepSectionOutsidePath) const
  74912. {
  74913. Line<float> result (line);
  74914. const bool startInside = contains (line.getStart());
  74915. const bool endInside = contains (line.getEnd());
  74916. if (startInside == endInside)
  74917. {
  74918. if (keepSectionOutsidePath == startInside)
  74919. result = Line<float>();
  74920. }
  74921. else
  74922. {
  74923. PathFlatteningIterator i (*this, AffineTransform::identity);
  74924. Point<float> intersection;
  74925. while (i.next())
  74926. {
  74927. if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
  74928. {
  74929. if ((startInside && keepSectionOutsidePath) || (endInside && ! keepSectionOutsidePath))
  74930. result.setStart (intersection);
  74931. else
  74932. result.setEnd (intersection);
  74933. }
  74934. }
  74935. }
  74936. return result;
  74937. }
  74938. float Path::getLength (const AffineTransform& transform) const
  74939. {
  74940. float length = 0;
  74941. PathFlatteningIterator i (*this, transform);
  74942. while (i.next())
  74943. length += Line<float> (i.x1, i.y1, i.x2, i.y2).getLength();
  74944. return length;
  74945. }
  74946. const Point<float> Path::getPointAlongPath (float distanceFromStart, const AffineTransform& transform) const
  74947. {
  74948. PathFlatteningIterator i (*this, transform);
  74949. while (i.next())
  74950. {
  74951. const Line<float> line (i.x1, i.y1, i.x2, i.y2);
  74952. const float lineLength = line.getLength();
  74953. if (distanceFromStart <= lineLength)
  74954. return line.getPointAlongLine (distanceFromStart);
  74955. distanceFromStart -= lineLength;
  74956. }
  74957. return Point<float> (i.x2, i.y2);
  74958. }
  74959. float Path::getNearestPoint (const Point<float>& targetPoint, Point<float>& pointOnPath,
  74960. const AffineTransform& transform) const
  74961. {
  74962. PathFlatteningIterator i (*this, transform);
  74963. float bestPosition = 0, bestDistance = std::numeric_limits<float>::max();
  74964. float length = 0;
  74965. Point<float> pointOnLine;
  74966. while (i.next())
  74967. {
  74968. const Line<float> line (i.x1, i.y1, i.x2, i.y2);
  74969. const float distance = line.getDistanceFromPoint (targetPoint, pointOnLine);
  74970. if (distance < bestDistance)
  74971. {
  74972. bestDistance = distance;
  74973. bestPosition = length + pointOnLine.getDistanceFrom (line.getStart());
  74974. pointOnPath = pointOnLine;
  74975. }
  74976. length += line.getLength();
  74977. }
  74978. return bestPosition;
  74979. }
  74980. const Path Path::createPathWithRoundedCorners (const float cornerRadius) const
  74981. {
  74982. if (cornerRadius <= 0.01f)
  74983. return *this;
  74984. size_t indexOfPathStart = 0, indexOfPathStartThis = 0;
  74985. size_t n = 0;
  74986. bool lastWasLine = false, firstWasLine = false;
  74987. Path p;
  74988. while (n < numElements)
  74989. {
  74990. const float type = data.elements [n++];
  74991. if (type == moveMarker)
  74992. {
  74993. indexOfPathStart = p.numElements;
  74994. indexOfPathStartThis = n - 1;
  74995. const float x = data.elements [n++];
  74996. const float y = data.elements [n++];
  74997. p.startNewSubPath (x, y);
  74998. lastWasLine = false;
  74999. firstWasLine = (data.elements [n] == lineMarker);
  75000. }
  75001. else if (type == lineMarker || type == closeSubPathMarker)
  75002. {
  75003. float startX = 0, startY = 0, joinX = 0, joinY = 0, endX, endY;
  75004. if (type == lineMarker)
  75005. {
  75006. endX = data.elements [n++];
  75007. endY = data.elements [n++];
  75008. if (n > 8)
  75009. {
  75010. startX = data.elements [n - 8];
  75011. startY = data.elements [n - 7];
  75012. joinX = data.elements [n - 5];
  75013. joinY = data.elements [n - 4];
  75014. }
  75015. }
  75016. else
  75017. {
  75018. endX = data.elements [indexOfPathStartThis + 1];
  75019. endY = data.elements [indexOfPathStartThis + 2];
  75020. if (n > 6)
  75021. {
  75022. startX = data.elements [n - 6];
  75023. startY = data.elements [n - 5];
  75024. joinX = data.elements [n - 3];
  75025. joinY = data.elements [n - 2];
  75026. }
  75027. }
  75028. if (lastWasLine)
  75029. {
  75030. const double len1 = juce_hypot (startX - joinX,
  75031. startY - joinY);
  75032. if (len1 > 0)
  75033. {
  75034. const double propNeeded = jmin (0.5, cornerRadius / len1);
  75035. p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  75036. p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  75037. }
  75038. const double len2 = juce_hypot (endX - joinX,
  75039. endY - joinY);
  75040. if (len2 > 0)
  75041. {
  75042. const double propNeeded = jmin (0.5, cornerRadius / len2);
  75043. p.quadraticTo (joinX, joinY,
  75044. (float) (joinX + (endX - joinX) * propNeeded),
  75045. (float) (joinY + (endY - joinY) * propNeeded));
  75046. }
  75047. p.lineTo (endX, endY);
  75048. }
  75049. else if (type == lineMarker)
  75050. {
  75051. p.lineTo (endX, endY);
  75052. lastWasLine = true;
  75053. }
  75054. if (type == closeSubPathMarker)
  75055. {
  75056. if (firstWasLine)
  75057. {
  75058. startX = data.elements [n - 3];
  75059. startY = data.elements [n - 2];
  75060. joinX = endX;
  75061. joinY = endY;
  75062. endX = data.elements [indexOfPathStartThis + 4];
  75063. endY = data.elements [indexOfPathStartThis + 5];
  75064. const double len1 = juce_hypot (startX - joinX,
  75065. startY - joinY);
  75066. if (len1 > 0)
  75067. {
  75068. const double propNeeded = jmin (0.5, cornerRadius / len1);
  75069. p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  75070. p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  75071. }
  75072. const double len2 = juce_hypot (endX - joinX,
  75073. endY - joinY);
  75074. if (len2 > 0)
  75075. {
  75076. const double propNeeded = jmin (0.5, cornerRadius / len2);
  75077. endX = (float) (joinX + (endX - joinX) * propNeeded);
  75078. endY = (float) (joinY + (endY - joinY) * propNeeded);
  75079. p.quadraticTo (joinX, joinY, endX, endY);
  75080. p.data.elements [indexOfPathStart + 1] = endX;
  75081. p.data.elements [indexOfPathStart + 2] = endY;
  75082. }
  75083. }
  75084. p.closeSubPath();
  75085. }
  75086. }
  75087. else if (type == quadMarker)
  75088. {
  75089. lastWasLine = false;
  75090. const float x1 = data.elements [n++];
  75091. const float y1 = data.elements [n++];
  75092. const float x2 = data.elements [n++];
  75093. const float y2 = data.elements [n++];
  75094. p.quadraticTo (x1, y1, x2, y2);
  75095. }
  75096. else if (type == cubicMarker)
  75097. {
  75098. lastWasLine = false;
  75099. const float x1 = data.elements [n++];
  75100. const float y1 = data.elements [n++];
  75101. const float x2 = data.elements [n++];
  75102. const float y2 = data.elements [n++];
  75103. const float x3 = data.elements [n++];
  75104. const float y3 = data.elements [n++];
  75105. p.cubicTo (x1, y1, x2, y2, x3, y3);
  75106. }
  75107. }
  75108. return p;
  75109. }
  75110. void Path::loadPathFromStream (InputStream& source)
  75111. {
  75112. while (! source.isExhausted())
  75113. {
  75114. switch (source.readByte())
  75115. {
  75116. case 'm':
  75117. {
  75118. const float x = source.readFloat();
  75119. const float y = source.readFloat();
  75120. startNewSubPath (x, y);
  75121. break;
  75122. }
  75123. case 'l':
  75124. {
  75125. const float x = source.readFloat();
  75126. const float y = source.readFloat();
  75127. lineTo (x, y);
  75128. break;
  75129. }
  75130. case 'q':
  75131. {
  75132. const float x1 = source.readFloat();
  75133. const float y1 = source.readFloat();
  75134. const float x2 = source.readFloat();
  75135. const float y2 = source.readFloat();
  75136. quadraticTo (x1, y1, x2, y2);
  75137. break;
  75138. }
  75139. case 'b':
  75140. {
  75141. const float x1 = source.readFloat();
  75142. const float y1 = source.readFloat();
  75143. const float x2 = source.readFloat();
  75144. const float y2 = source.readFloat();
  75145. const float x3 = source.readFloat();
  75146. const float y3 = source.readFloat();
  75147. cubicTo (x1, y1, x2, y2, x3, y3);
  75148. break;
  75149. }
  75150. case 'c':
  75151. closeSubPath();
  75152. break;
  75153. case 'n':
  75154. useNonZeroWinding = true;
  75155. break;
  75156. case 'z':
  75157. useNonZeroWinding = false;
  75158. break;
  75159. case 'e':
  75160. return; // end of path marker
  75161. default:
  75162. jassertfalse; // illegal char in the stream
  75163. break;
  75164. }
  75165. }
  75166. }
  75167. void Path::loadPathFromData (const void* const pathData, const int numberOfBytes)
  75168. {
  75169. MemoryInputStream in (pathData, numberOfBytes, false);
  75170. loadPathFromStream (in);
  75171. }
  75172. void Path::writePathToStream (OutputStream& dest) const
  75173. {
  75174. dest.writeByte (useNonZeroWinding ? 'n' : 'z');
  75175. size_t i = 0;
  75176. while (i < numElements)
  75177. {
  75178. const float type = data.elements [i++];
  75179. if (type == moveMarker)
  75180. {
  75181. dest.writeByte ('m');
  75182. dest.writeFloat (data.elements [i++]);
  75183. dest.writeFloat (data.elements [i++]);
  75184. }
  75185. else if (type == lineMarker)
  75186. {
  75187. dest.writeByte ('l');
  75188. dest.writeFloat (data.elements [i++]);
  75189. dest.writeFloat (data.elements [i++]);
  75190. }
  75191. else if (type == quadMarker)
  75192. {
  75193. dest.writeByte ('q');
  75194. dest.writeFloat (data.elements [i++]);
  75195. dest.writeFloat (data.elements [i++]);
  75196. dest.writeFloat (data.elements [i++]);
  75197. dest.writeFloat (data.elements [i++]);
  75198. }
  75199. else if (type == cubicMarker)
  75200. {
  75201. dest.writeByte ('b');
  75202. dest.writeFloat (data.elements [i++]);
  75203. dest.writeFloat (data.elements [i++]);
  75204. dest.writeFloat (data.elements [i++]);
  75205. dest.writeFloat (data.elements [i++]);
  75206. dest.writeFloat (data.elements [i++]);
  75207. dest.writeFloat (data.elements [i++]);
  75208. }
  75209. else if (type == closeSubPathMarker)
  75210. {
  75211. dest.writeByte ('c');
  75212. }
  75213. }
  75214. dest.writeByte ('e'); // marks the end-of-path
  75215. }
  75216. const String Path::toString() const
  75217. {
  75218. MemoryOutputStream s (2048);
  75219. if (! useNonZeroWinding)
  75220. s << 'a';
  75221. size_t i = 0;
  75222. float lastMarker = 0.0f;
  75223. while (i < numElements)
  75224. {
  75225. const float marker = data.elements [i++];
  75226. char markerChar = 0;
  75227. int numCoords = 0;
  75228. if (marker == moveMarker)
  75229. {
  75230. markerChar = 'm';
  75231. numCoords = 2;
  75232. }
  75233. else if (marker == lineMarker)
  75234. {
  75235. markerChar = 'l';
  75236. numCoords = 2;
  75237. }
  75238. else if (marker == quadMarker)
  75239. {
  75240. markerChar = 'q';
  75241. numCoords = 4;
  75242. }
  75243. else if (marker == cubicMarker)
  75244. {
  75245. markerChar = 'c';
  75246. numCoords = 6;
  75247. }
  75248. else
  75249. {
  75250. jassert (marker == closeSubPathMarker);
  75251. markerChar = 'z';
  75252. }
  75253. if (marker != lastMarker)
  75254. {
  75255. if (s.getDataSize() != 0)
  75256. s << ' ';
  75257. s << markerChar;
  75258. lastMarker = marker;
  75259. }
  75260. while (--numCoords >= 0 && i < numElements)
  75261. {
  75262. String coord (data.elements [i++], 3);
  75263. while (coord.endsWithChar ('0') && coord != "0")
  75264. coord = coord.dropLastCharacters (1);
  75265. if (coord.endsWithChar ('.'))
  75266. coord = coord.dropLastCharacters (1);
  75267. if (s.getDataSize() != 0)
  75268. s << ' ';
  75269. s << coord;
  75270. }
  75271. }
  75272. return s.toUTF8();
  75273. }
  75274. void Path::restoreFromString (const String& stringVersion)
  75275. {
  75276. clear();
  75277. setUsingNonZeroWinding (true);
  75278. const juce_wchar* t = stringVersion;
  75279. juce_wchar marker = 'm';
  75280. int numValues = 2;
  75281. float values [6];
  75282. for (;;)
  75283. {
  75284. const String token (PathHelpers::nextToken (t));
  75285. const juce_wchar firstChar = token[0];
  75286. int startNum = 0;
  75287. if (firstChar == 0)
  75288. break;
  75289. if (firstChar == 'm' || firstChar == 'l')
  75290. {
  75291. marker = firstChar;
  75292. numValues = 2;
  75293. }
  75294. else if (firstChar == 'q')
  75295. {
  75296. marker = firstChar;
  75297. numValues = 4;
  75298. }
  75299. else if (firstChar == 'c')
  75300. {
  75301. marker = firstChar;
  75302. numValues = 6;
  75303. }
  75304. else if (firstChar == 'z')
  75305. {
  75306. marker = firstChar;
  75307. numValues = 0;
  75308. }
  75309. else if (firstChar == 'a')
  75310. {
  75311. setUsingNonZeroWinding (false);
  75312. continue;
  75313. }
  75314. else
  75315. {
  75316. ++startNum;
  75317. values [0] = token.getFloatValue();
  75318. }
  75319. for (int i = startNum; i < numValues; ++i)
  75320. values [i] = PathHelpers::nextToken (t).getFloatValue();
  75321. switch (marker)
  75322. {
  75323. case 'm': startNewSubPath (values[0], values[1]); break;
  75324. case 'l': lineTo (values[0], values[1]); break;
  75325. case 'q': quadraticTo (values[0], values[1], values[2], values[3]); break;
  75326. case 'c': cubicTo (values[0], values[1], values[2], values[3], values[4], values[5]); break;
  75327. case 'z': closeSubPath(); break;
  75328. default: jassertfalse; break; // illegal string format?
  75329. }
  75330. }
  75331. }
  75332. Path::Iterator::Iterator (const Path& path_)
  75333. : path (path_),
  75334. index (0)
  75335. {
  75336. }
  75337. Path::Iterator::~Iterator()
  75338. {
  75339. }
  75340. bool Path::Iterator::next()
  75341. {
  75342. const float* const elements = path.data.elements;
  75343. if (index < path.numElements)
  75344. {
  75345. const float type = elements [index++];
  75346. if (type == moveMarker)
  75347. {
  75348. elementType = startNewSubPath;
  75349. x1 = elements [index++];
  75350. y1 = elements [index++];
  75351. }
  75352. else if (type == lineMarker)
  75353. {
  75354. elementType = lineTo;
  75355. x1 = elements [index++];
  75356. y1 = elements [index++];
  75357. }
  75358. else if (type == quadMarker)
  75359. {
  75360. elementType = quadraticTo;
  75361. x1 = elements [index++];
  75362. y1 = elements [index++];
  75363. x2 = elements [index++];
  75364. y2 = elements [index++];
  75365. }
  75366. else if (type == cubicMarker)
  75367. {
  75368. elementType = cubicTo;
  75369. x1 = elements [index++];
  75370. y1 = elements [index++];
  75371. x2 = elements [index++];
  75372. y2 = elements [index++];
  75373. x3 = elements [index++];
  75374. y3 = elements [index++];
  75375. }
  75376. else if (type == closeSubPathMarker)
  75377. {
  75378. elementType = closePath;
  75379. }
  75380. return true;
  75381. }
  75382. return false;
  75383. }
  75384. END_JUCE_NAMESPACE
  75385. /*** End of inlined file: juce_Path.cpp ***/
  75386. /*** Start of inlined file: juce_PathIterator.cpp ***/
  75387. BEGIN_JUCE_NAMESPACE
  75388. #if JUCE_MSVC && JUCE_DEBUG
  75389. #pragma optimize ("t", on)
  75390. #endif
  75391. PathFlatteningIterator::PathFlatteningIterator (const Path& path_,
  75392. const AffineTransform& transform_,
  75393. float tolerence_)
  75394. : x2 (0),
  75395. y2 (0),
  75396. closesSubPath (false),
  75397. subPathIndex (-1),
  75398. path (path_),
  75399. transform (transform_),
  75400. points (path_.data.elements),
  75401. tolerence (tolerence_ * tolerence_),
  75402. subPathCloseX (0),
  75403. subPathCloseY (0),
  75404. isIdentityTransform (transform_.isIdentity()),
  75405. stackBase (32),
  75406. index (0),
  75407. stackSize (32)
  75408. {
  75409. stackPos = stackBase;
  75410. }
  75411. PathFlatteningIterator::~PathFlatteningIterator()
  75412. {
  75413. }
  75414. bool PathFlatteningIterator::next()
  75415. {
  75416. x1 = x2;
  75417. y1 = y2;
  75418. float x3 = 0;
  75419. float y3 = 0;
  75420. float x4 = 0;
  75421. float y4 = 0;
  75422. float type;
  75423. for (;;)
  75424. {
  75425. if (stackPos == stackBase)
  75426. {
  75427. if (index >= path.numElements)
  75428. {
  75429. return false;
  75430. }
  75431. else
  75432. {
  75433. type = points [index++];
  75434. if (type != Path::closeSubPathMarker)
  75435. {
  75436. x2 = points [index++];
  75437. y2 = points [index++];
  75438. if (type == Path::quadMarker)
  75439. {
  75440. x3 = points [index++];
  75441. y3 = points [index++];
  75442. if (! isIdentityTransform)
  75443. transform.transformPoints (x2, y2, x3, y3);
  75444. }
  75445. else if (type == Path::cubicMarker)
  75446. {
  75447. x3 = points [index++];
  75448. y3 = points [index++];
  75449. x4 = points [index++];
  75450. y4 = points [index++];
  75451. if (! isIdentityTransform)
  75452. transform.transformPoints (x2, y2, x3, y3, x4, y4);
  75453. }
  75454. else
  75455. {
  75456. if (! isIdentityTransform)
  75457. transform.transformPoint (x2, y2);
  75458. }
  75459. }
  75460. }
  75461. }
  75462. else
  75463. {
  75464. type = *--stackPos;
  75465. if (type != Path::closeSubPathMarker)
  75466. {
  75467. x2 = *--stackPos;
  75468. y2 = *--stackPos;
  75469. if (type == Path::quadMarker)
  75470. {
  75471. x3 = *--stackPos;
  75472. y3 = *--stackPos;
  75473. }
  75474. else if (type == Path::cubicMarker)
  75475. {
  75476. x3 = *--stackPos;
  75477. y3 = *--stackPos;
  75478. x4 = *--stackPos;
  75479. y4 = *--stackPos;
  75480. }
  75481. }
  75482. }
  75483. if (type == Path::lineMarker)
  75484. {
  75485. ++subPathIndex;
  75486. closesSubPath = (stackPos == stackBase)
  75487. && (index < path.numElements)
  75488. && (points [index] == Path::closeSubPathMarker)
  75489. && x2 == subPathCloseX
  75490. && y2 == subPathCloseY;
  75491. return true;
  75492. }
  75493. else if (type == Path::quadMarker)
  75494. {
  75495. const size_t offset = (size_t) (stackPos - stackBase);
  75496. if (offset >= stackSize - 10)
  75497. {
  75498. stackSize <<= 1;
  75499. stackBase.realloc (stackSize);
  75500. stackPos = stackBase + offset;
  75501. }
  75502. const float dx1 = x1 - x2;
  75503. const float dy1 = y1 - y2;
  75504. const float dx2 = x2 - x3;
  75505. const float dy2 = y2 - y3;
  75506. const float m1x = (x1 + x2) * 0.5f;
  75507. const float m1y = (y1 + y2) * 0.5f;
  75508. const float m2x = (x2 + x3) * 0.5f;
  75509. const float m2y = (y2 + y3) * 0.5f;
  75510. const float m3x = (m1x + m2x) * 0.5f;
  75511. const float m3y = (m1y + m2y) * 0.5f;
  75512. if (dx1*dx1 + dy1*dy1 + dx2*dx2 + dy2*dy2 > tolerence)
  75513. {
  75514. *stackPos++ = y3;
  75515. *stackPos++ = x3;
  75516. *stackPos++ = m2y;
  75517. *stackPos++ = m2x;
  75518. *stackPos++ = Path::quadMarker;
  75519. *stackPos++ = m3y;
  75520. *stackPos++ = m3x;
  75521. *stackPos++ = m1y;
  75522. *stackPos++ = m1x;
  75523. *stackPos++ = Path::quadMarker;
  75524. }
  75525. else
  75526. {
  75527. *stackPos++ = y3;
  75528. *stackPos++ = x3;
  75529. *stackPos++ = Path::lineMarker;
  75530. *stackPos++ = m3y;
  75531. *stackPos++ = m3x;
  75532. *stackPos++ = Path::lineMarker;
  75533. }
  75534. jassert (stackPos < stackBase + stackSize);
  75535. }
  75536. else if (type == Path::cubicMarker)
  75537. {
  75538. const size_t offset = (size_t) (stackPos - stackBase);
  75539. if (offset >= stackSize - 16)
  75540. {
  75541. stackSize <<= 1;
  75542. stackBase.realloc (stackSize);
  75543. stackPos = stackBase + offset;
  75544. }
  75545. const float dx1 = x1 - x2;
  75546. const float dy1 = y1 - y2;
  75547. const float dx2 = x2 - x3;
  75548. const float dy2 = y2 - y3;
  75549. const float dx3 = x3 - x4;
  75550. const float dy3 = y3 - y4;
  75551. const float m1x = (x1 + x2) * 0.5f;
  75552. const float m1y = (y1 + y2) * 0.5f;
  75553. const float m2x = (x3 + x2) * 0.5f;
  75554. const float m2y = (y3 + y2) * 0.5f;
  75555. const float m3x = (x3 + x4) * 0.5f;
  75556. const float m3y = (y3 + y4) * 0.5f;
  75557. const float m4x = (m1x + m2x) * 0.5f;
  75558. const float m4y = (m1y + m2y) * 0.5f;
  75559. const float m5x = (m3x + m2x) * 0.5f;
  75560. const float m5y = (m3y + m2y) * 0.5f;
  75561. if (dx1*dx1 + dy1*dy1 + dx2*dx2
  75562. + dy2*dy2 + dx3*dx3 + dy3*dy3 > tolerence)
  75563. {
  75564. *stackPos++ = y4;
  75565. *stackPos++ = x4;
  75566. *stackPos++ = m3y;
  75567. *stackPos++ = m3x;
  75568. *stackPos++ = m5y;
  75569. *stackPos++ = m5x;
  75570. *stackPos++ = Path::cubicMarker;
  75571. *stackPos++ = (m4y + m5y) * 0.5f;
  75572. *stackPos++ = (m4x + m5x) * 0.5f;
  75573. *stackPos++ = m4y;
  75574. *stackPos++ = m4x;
  75575. *stackPos++ = m1y;
  75576. *stackPos++ = m1x;
  75577. *stackPos++ = Path::cubicMarker;
  75578. }
  75579. else
  75580. {
  75581. *stackPos++ = y4;
  75582. *stackPos++ = x4;
  75583. *stackPos++ = Path::lineMarker;
  75584. *stackPos++ = m5y;
  75585. *stackPos++ = m5x;
  75586. *stackPos++ = Path::lineMarker;
  75587. *stackPos++ = m4y;
  75588. *stackPos++ = m4x;
  75589. *stackPos++ = Path::lineMarker;
  75590. }
  75591. }
  75592. else if (type == Path::closeSubPathMarker)
  75593. {
  75594. if (x2 != subPathCloseX || y2 != subPathCloseY)
  75595. {
  75596. x1 = x2;
  75597. y1 = y2;
  75598. x2 = subPathCloseX;
  75599. y2 = subPathCloseY;
  75600. closesSubPath = true;
  75601. return true;
  75602. }
  75603. }
  75604. else
  75605. {
  75606. jassert (type == Path::moveMarker);
  75607. subPathIndex = -1;
  75608. subPathCloseX = x1 = x2;
  75609. subPathCloseY = y1 = y2;
  75610. }
  75611. }
  75612. }
  75613. #if JUCE_MSVC && JUCE_DEBUG
  75614. #pragma optimize ("", on) // resets optimisations to the project defaults
  75615. #endif
  75616. END_JUCE_NAMESPACE
  75617. /*** End of inlined file: juce_PathIterator.cpp ***/
  75618. /*** Start of inlined file: juce_PathStrokeType.cpp ***/
  75619. BEGIN_JUCE_NAMESPACE
  75620. PathStrokeType::PathStrokeType (const float strokeThickness,
  75621. const JointStyle jointStyle_,
  75622. const EndCapStyle endStyle_) throw()
  75623. : thickness (strokeThickness),
  75624. jointStyle (jointStyle_),
  75625. endStyle (endStyle_)
  75626. {
  75627. }
  75628. PathStrokeType::PathStrokeType (const PathStrokeType& other) throw()
  75629. : thickness (other.thickness),
  75630. jointStyle (other.jointStyle),
  75631. endStyle (other.endStyle)
  75632. {
  75633. }
  75634. PathStrokeType& PathStrokeType::operator= (const PathStrokeType& other) throw()
  75635. {
  75636. thickness = other.thickness;
  75637. jointStyle = other.jointStyle;
  75638. endStyle = other.endStyle;
  75639. return *this;
  75640. }
  75641. PathStrokeType::~PathStrokeType() throw()
  75642. {
  75643. }
  75644. bool PathStrokeType::operator== (const PathStrokeType& other) const throw()
  75645. {
  75646. return thickness == other.thickness
  75647. && jointStyle == other.jointStyle
  75648. && endStyle == other.endStyle;
  75649. }
  75650. bool PathStrokeType::operator!= (const PathStrokeType& other) const throw()
  75651. {
  75652. return ! operator== (other);
  75653. }
  75654. namespace PathStrokeHelpers
  75655. {
  75656. static bool lineIntersection (const float x1, const float y1,
  75657. const float x2, const float y2,
  75658. const float x3, const float y3,
  75659. const float x4, const float y4,
  75660. float& intersectionX,
  75661. float& intersectionY,
  75662. float& distanceBeyondLine1EndSquared) throw()
  75663. {
  75664. if (x2 != x3 || y2 != y3)
  75665. {
  75666. const float dx1 = x2 - x1;
  75667. const float dy1 = y2 - y1;
  75668. const float dx2 = x4 - x3;
  75669. const float dy2 = y4 - y3;
  75670. const float divisor = dx1 * dy2 - dx2 * dy1;
  75671. if (divisor == 0)
  75672. {
  75673. if (! ((dx1 == 0 && dy1 == 0) || (dx2 == 0 && dy2 == 0)))
  75674. {
  75675. if (dy1 == 0 && dy2 != 0)
  75676. {
  75677. const float along = (y1 - y3) / dy2;
  75678. intersectionX = x3 + along * dx2;
  75679. intersectionY = y1;
  75680. distanceBeyondLine1EndSquared = intersectionX - x2;
  75681. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75682. if ((x2 > x1) == (intersectionX < x2))
  75683. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75684. return along >= 0 && along <= 1.0f;
  75685. }
  75686. else if (dy2 == 0 && dy1 != 0)
  75687. {
  75688. const float along = (y3 - y1) / dy1;
  75689. intersectionX = x1 + along * dx1;
  75690. intersectionY = y3;
  75691. distanceBeyondLine1EndSquared = (along - 1.0f) * dx1;
  75692. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75693. if (along < 1.0f)
  75694. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75695. return along >= 0 && along <= 1.0f;
  75696. }
  75697. else if (dx1 == 0 && dx2 != 0)
  75698. {
  75699. const float along = (x1 - x3) / dx2;
  75700. intersectionX = x1;
  75701. intersectionY = y3 + along * dy2;
  75702. distanceBeyondLine1EndSquared = intersectionY - y2;
  75703. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75704. if ((y2 > y1) == (intersectionY < y2))
  75705. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75706. return along >= 0 && along <= 1.0f;
  75707. }
  75708. else if (dx2 == 0 && dx1 != 0)
  75709. {
  75710. const float along = (x3 - x1) / dx1;
  75711. intersectionX = x3;
  75712. intersectionY = y1 + along * dy1;
  75713. distanceBeyondLine1EndSquared = (along - 1.0f) * dy1;
  75714. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75715. if (along < 1.0f)
  75716. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75717. return along >= 0 && along <= 1.0f;
  75718. }
  75719. }
  75720. intersectionX = 0.5f * (x2 + x3);
  75721. intersectionY = 0.5f * (y2 + y3);
  75722. distanceBeyondLine1EndSquared = 0.0f;
  75723. return false;
  75724. }
  75725. else
  75726. {
  75727. const float along1 = ((y1 - y3) * dx2 - (x1 - x3) * dy2) / divisor;
  75728. intersectionX = x1 + along1 * dx1;
  75729. intersectionY = y1 + along1 * dy1;
  75730. if (along1 >= 0 && along1 <= 1.0f)
  75731. {
  75732. const float along2 = ((y1 - y3) * dx1 - (x1 - x3) * dy1);
  75733. if (along2 >= 0 && along2 <= divisor)
  75734. {
  75735. distanceBeyondLine1EndSquared = 0.0f;
  75736. return true;
  75737. }
  75738. }
  75739. distanceBeyondLine1EndSquared = along1 - 1.0f;
  75740. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75741. distanceBeyondLine1EndSquared *= (dx1 * dx1 + dy1 * dy1);
  75742. if (along1 < 1.0f)
  75743. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75744. return false;
  75745. }
  75746. }
  75747. intersectionX = x2;
  75748. intersectionY = y2;
  75749. distanceBeyondLine1EndSquared = 0.0f;
  75750. return true;
  75751. }
  75752. static void addEdgeAndJoint (Path& destPath,
  75753. const PathStrokeType::JointStyle style,
  75754. const float maxMiterExtensionSquared, const float width,
  75755. const float x1, const float y1,
  75756. const float x2, const float y2,
  75757. const float x3, const float y3,
  75758. const float x4, const float y4,
  75759. const float midX, const float midY)
  75760. {
  75761. if (style == PathStrokeType::beveled
  75762. || (x3 == x4 && y3 == y4)
  75763. || (x1 == x2 && y1 == y2))
  75764. {
  75765. destPath.lineTo (x2, y2);
  75766. destPath.lineTo (x3, y3);
  75767. }
  75768. else
  75769. {
  75770. float jx, jy, distanceBeyondLine1EndSquared;
  75771. // if they intersect, use this point..
  75772. if (lineIntersection (x1, y1, x2, y2,
  75773. x3, y3, x4, y4,
  75774. jx, jy, distanceBeyondLine1EndSquared))
  75775. {
  75776. destPath.lineTo (jx, jy);
  75777. }
  75778. else
  75779. {
  75780. if (style == PathStrokeType::mitered)
  75781. {
  75782. if (distanceBeyondLine1EndSquared < maxMiterExtensionSquared
  75783. && distanceBeyondLine1EndSquared > 0.0f)
  75784. {
  75785. destPath.lineTo (jx, jy);
  75786. }
  75787. else
  75788. {
  75789. // the end sticks out too far, so just use a blunt joint
  75790. destPath.lineTo (x2, y2);
  75791. destPath.lineTo (x3, y3);
  75792. }
  75793. }
  75794. else
  75795. {
  75796. // curved joints
  75797. float angle1 = std::atan2 (x2 - midX, y2 - midY);
  75798. float angle2 = std::atan2 (x3 - midX, y3 - midY);
  75799. const float angleIncrement = 0.1f;
  75800. destPath.lineTo (x2, y2);
  75801. if (std::abs (angle1 - angle2) > angleIncrement)
  75802. {
  75803. if (angle2 > angle1 + float_Pi
  75804. || (angle2 < angle1 && angle2 >= angle1 - float_Pi))
  75805. {
  75806. if (angle2 > angle1)
  75807. angle2 -= float_Pi * 2.0f;
  75808. jassert (angle1 <= angle2 + float_Pi);
  75809. angle1 -= angleIncrement;
  75810. while (angle1 > angle2)
  75811. {
  75812. destPath.lineTo (midX + width * std::sin (angle1),
  75813. midY + width * std::cos (angle1));
  75814. angle1 -= angleIncrement;
  75815. }
  75816. }
  75817. else
  75818. {
  75819. if (angle1 > angle2)
  75820. angle1 -= float_Pi * 2.0f;
  75821. jassert (angle1 >= angle2 - float_Pi);
  75822. angle1 += angleIncrement;
  75823. while (angle1 < angle2)
  75824. {
  75825. destPath.lineTo (midX + width * std::sin (angle1),
  75826. midY + width * std::cos (angle1));
  75827. angle1 += angleIncrement;
  75828. }
  75829. }
  75830. }
  75831. destPath.lineTo (x3, y3);
  75832. }
  75833. }
  75834. }
  75835. }
  75836. static void addLineEnd (Path& destPath,
  75837. const PathStrokeType::EndCapStyle style,
  75838. const float x1, const float y1,
  75839. const float x2, const float y2,
  75840. const float width)
  75841. {
  75842. if (style == PathStrokeType::butt)
  75843. {
  75844. destPath.lineTo (x2, y2);
  75845. }
  75846. else
  75847. {
  75848. float offx1, offy1, offx2, offy2;
  75849. float dx = x2 - x1;
  75850. float dy = y2 - y1;
  75851. const float len = juce_hypotf (dx, dy);
  75852. if (len == 0)
  75853. {
  75854. offx1 = offx2 = x1;
  75855. offy1 = offy2 = y1;
  75856. }
  75857. else
  75858. {
  75859. const float offset = width / len;
  75860. dx *= offset;
  75861. dy *= offset;
  75862. offx1 = x1 + dy;
  75863. offy1 = y1 - dx;
  75864. offx2 = x2 + dy;
  75865. offy2 = y2 - dx;
  75866. }
  75867. if (style == PathStrokeType::square)
  75868. {
  75869. // sqaure ends
  75870. destPath.lineTo (offx1, offy1);
  75871. destPath.lineTo (offx2, offy2);
  75872. destPath.lineTo (x2, y2);
  75873. }
  75874. else
  75875. {
  75876. // rounded ends
  75877. const float midx = (offx1 + offx2) * 0.5f;
  75878. const float midy = (offy1 + offy2) * 0.5f;
  75879. destPath.cubicTo (x1 + (offx1 - x1) * 0.55f, y1 + (offy1 - y1) * 0.55f,
  75880. offx1 + (midx - offx1) * 0.45f, offy1 + (midy - offy1) * 0.45f,
  75881. midx, midy);
  75882. destPath.cubicTo (midx + (offx2 - midx) * 0.55f, midy + (offy2 - midy) * 0.55f,
  75883. offx2 + (x2 - offx2) * 0.45f, offy2 + (y2 - offy2) * 0.45f,
  75884. x2, y2);
  75885. }
  75886. }
  75887. }
  75888. struct Arrowhead
  75889. {
  75890. float startWidth, startLength;
  75891. float endWidth, endLength;
  75892. };
  75893. static void addArrowhead (Path& destPath,
  75894. const float x1, const float y1,
  75895. const float x2, const float y2,
  75896. const float tipX, const float tipY,
  75897. const float width,
  75898. const float arrowheadWidth)
  75899. {
  75900. Line<float> line (x1, y1, x2, y2);
  75901. destPath.lineTo (line.getPointAlongLine (-(arrowheadWidth / 2.0f - width), 0));
  75902. destPath.lineTo (tipX, tipY);
  75903. destPath.lineTo (line.getPointAlongLine (arrowheadWidth - (arrowheadWidth / 2.0f - width), 0));
  75904. destPath.lineTo (x2, y2);
  75905. }
  75906. struct LineSection
  75907. {
  75908. float x1, y1, x2, y2; // original line
  75909. float lx1, ly1, lx2, ly2; // the left-hand stroke
  75910. float rx1, ry1, rx2, ry2; // the right-hand stroke
  75911. };
  75912. static void shortenSubPath (Array<LineSection>& subPath, float amountAtStart, float amountAtEnd)
  75913. {
  75914. while (amountAtEnd > 0 && subPath.size() > 0)
  75915. {
  75916. LineSection& l = subPath.getReference (subPath.size() - 1);
  75917. float dx = l.rx2 - l.rx1;
  75918. float dy = l.ry2 - l.ry1;
  75919. const float len = juce_hypotf (dx, dy);
  75920. if (len <= amountAtEnd && subPath.size() > 1)
  75921. {
  75922. LineSection& prev = subPath.getReference (subPath.size() - 2);
  75923. prev.x2 = l.x2;
  75924. prev.y2 = l.y2;
  75925. subPath.removeLast();
  75926. amountAtEnd -= len;
  75927. }
  75928. else
  75929. {
  75930. const float prop = jmin (0.9999f, amountAtEnd / len);
  75931. dx *= prop;
  75932. dy *= prop;
  75933. l.rx1 += dx;
  75934. l.ry1 += dy;
  75935. l.lx2 += dx;
  75936. l.ly2 += dy;
  75937. break;
  75938. }
  75939. }
  75940. while (amountAtStart > 0 && subPath.size() > 0)
  75941. {
  75942. LineSection& l = subPath.getReference (0);
  75943. float dx = l.rx2 - l.rx1;
  75944. float dy = l.ry2 - l.ry1;
  75945. const float len = juce_hypotf (dx, dy);
  75946. if (len <= amountAtStart && subPath.size() > 1)
  75947. {
  75948. LineSection& next = subPath.getReference (1);
  75949. next.x1 = l.x1;
  75950. next.y1 = l.y1;
  75951. subPath.remove (0);
  75952. amountAtStart -= len;
  75953. }
  75954. else
  75955. {
  75956. const float prop = jmin (0.9999f, amountAtStart / len);
  75957. dx *= prop;
  75958. dy *= prop;
  75959. l.rx2 -= dx;
  75960. l.ry2 -= dy;
  75961. l.lx1 -= dx;
  75962. l.ly1 -= dy;
  75963. break;
  75964. }
  75965. }
  75966. }
  75967. static void addSubPath (Path& destPath, Array<LineSection>& subPath,
  75968. const bool isClosed, const float width, const float maxMiterExtensionSquared,
  75969. const PathStrokeType::JointStyle jointStyle, const PathStrokeType::EndCapStyle endStyle,
  75970. const Arrowhead* const arrowhead)
  75971. {
  75972. jassert (subPath.size() > 0);
  75973. if (arrowhead != 0)
  75974. shortenSubPath (subPath, arrowhead->startLength, arrowhead->endLength);
  75975. const LineSection& firstLine = subPath.getReference (0);
  75976. float lastX1 = firstLine.lx1;
  75977. float lastY1 = firstLine.ly1;
  75978. float lastX2 = firstLine.lx2;
  75979. float lastY2 = firstLine.ly2;
  75980. if (isClosed)
  75981. {
  75982. destPath.startNewSubPath (lastX1, lastY1);
  75983. }
  75984. else
  75985. {
  75986. destPath.startNewSubPath (firstLine.rx2, firstLine.ry2);
  75987. if (arrowhead != 0)
  75988. addArrowhead (destPath, firstLine.rx2, firstLine.ry2, lastX1, lastY1, firstLine.x1, firstLine.y1,
  75989. width, arrowhead->startWidth);
  75990. else
  75991. addLineEnd (destPath, endStyle, firstLine.rx2, firstLine.ry2, lastX1, lastY1, width);
  75992. }
  75993. int i;
  75994. for (i = 1; i < subPath.size(); ++i)
  75995. {
  75996. const LineSection& l = subPath.getReference (i);
  75997. addEdgeAndJoint (destPath, jointStyle,
  75998. maxMiterExtensionSquared, width,
  75999. lastX1, lastY1, lastX2, lastY2,
  76000. l.lx1, l.ly1, l.lx2, l.ly2,
  76001. l.x1, l.y1);
  76002. lastX1 = l.lx1;
  76003. lastY1 = l.ly1;
  76004. lastX2 = l.lx2;
  76005. lastY2 = l.ly2;
  76006. }
  76007. const LineSection& lastLine = subPath.getReference (subPath.size() - 1);
  76008. if (isClosed)
  76009. {
  76010. const LineSection& l = subPath.getReference (0);
  76011. addEdgeAndJoint (destPath, jointStyle,
  76012. maxMiterExtensionSquared, width,
  76013. lastX1, lastY1, lastX2, lastY2,
  76014. l.lx1, l.ly1, l.lx2, l.ly2,
  76015. l.x1, l.y1);
  76016. destPath.closeSubPath();
  76017. destPath.startNewSubPath (lastLine.rx1, lastLine.ry1);
  76018. }
  76019. else
  76020. {
  76021. destPath.lineTo (lastX2, lastY2);
  76022. if (arrowhead != 0)
  76023. addArrowhead (destPath, lastX2, lastY2, lastLine.rx1, lastLine.ry1, lastLine.x2, lastLine.y2,
  76024. width, arrowhead->endWidth);
  76025. else
  76026. addLineEnd (destPath, endStyle, lastX2, lastY2, lastLine.rx1, lastLine.ry1, width);
  76027. }
  76028. lastX1 = lastLine.rx1;
  76029. lastY1 = lastLine.ry1;
  76030. lastX2 = lastLine.rx2;
  76031. lastY2 = lastLine.ry2;
  76032. for (i = subPath.size() - 1; --i >= 0;)
  76033. {
  76034. const LineSection& l = subPath.getReference (i);
  76035. addEdgeAndJoint (destPath, jointStyle,
  76036. maxMiterExtensionSquared, width,
  76037. lastX1, lastY1, lastX2, lastY2,
  76038. l.rx1, l.ry1, l.rx2, l.ry2,
  76039. l.x2, l.y2);
  76040. lastX1 = l.rx1;
  76041. lastY1 = l.ry1;
  76042. lastX2 = l.rx2;
  76043. lastY2 = l.ry2;
  76044. }
  76045. if (isClosed)
  76046. {
  76047. addEdgeAndJoint (destPath, jointStyle,
  76048. maxMiterExtensionSquared, width,
  76049. lastX1, lastY1, lastX2, lastY2,
  76050. lastLine.rx1, lastLine.ry1, lastLine.rx2, lastLine.ry2,
  76051. lastLine.x2, lastLine.y2);
  76052. }
  76053. else
  76054. {
  76055. // do the last line
  76056. destPath.lineTo (lastX2, lastY2);
  76057. }
  76058. destPath.closeSubPath();
  76059. }
  76060. static void createStroke (const float thickness, const PathStrokeType::JointStyle jointStyle,
  76061. const PathStrokeType::EndCapStyle endStyle,
  76062. Path& destPath, const Path& source,
  76063. const AffineTransform& transform,
  76064. const float extraAccuracy, const Arrowhead* const arrowhead)
  76065. {
  76066. if (thickness <= 0)
  76067. {
  76068. destPath.clear();
  76069. return;
  76070. }
  76071. const Path* sourcePath = &source;
  76072. Path temp;
  76073. if (sourcePath == &destPath)
  76074. {
  76075. destPath.swapWithPath (temp);
  76076. sourcePath = &temp;
  76077. }
  76078. else
  76079. {
  76080. destPath.clear();
  76081. }
  76082. destPath.setUsingNonZeroWinding (true);
  76083. const float maxMiterExtensionSquared = 9.0f * thickness * thickness;
  76084. const float width = 0.5f * thickness;
  76085. // Iterate the path, creating a list of the
  76086. // left/right-hand lines along either side of it...
  76087. PathFlatteningIterator it (*sourcePath, transform, 9.0f / extraAccuracy);
  76088. Array <LineSection> subPath;
  76089. subPath.ensureStorageAllocated (512);
  76090. LineSection l;
  76091. l.x1 = 0;
  76092. l.y1 = 0;
  76093. const float minSegmentLength = 2.0f / (extraAccuracy * extraAccuracy);
  76094. while (it.next())
  76095. {
  76096. if (it.subPathIndex == 0)
  76097. {
  76098. if (subPath.size() > 0)
  76099. {
  76100. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  76101. subPath.clearQuick();
  76102. }
  76103. l.x1 = it.x1;
  76104. l.y1 = it.y1;
  76105. }
  76106. l.x2 = it.x2;
  76107. l.y2 = it.y2;
  76108. float dx = l.x2 - l.x1;
  76109. float dy = l.y2 - l.y1;
  76110. const float hypotSquared = dx*dx + dy*dy;
  76111. if (it.closesSubPath || hypotSquared > minSegmentLength || it.isLastInSubpath())
  76112. {
  76113. const float len = std::sqrt (hypotSquared);
  76114. if (len == 0)
  76115. {
  76116. l.rx1 = l.rx2 = l.lx1 = l.lx2 = l.x1;
  76117. l.ry1 = l.ry2 = l.ly1 = l.ly2 = l.y1;
  76118. }
  76119. else
  76120. {
  76121. const float offset = width / len;
  76122. dx *= offset;
  76123. dy *= offset;
  76124. l.rx2 = l.x1 - dy;
  76125. l.ry2 = l.y1 + dx;
  76126. l.lx1 = l.x1 + dy;
  76127. l.ly1 = l.y1 - dx;
  76128. l.lx2 = l.x2 + dy;
  76129. l.ly2 = l.y2 - dx;
  76130. l.rx1 = l.x2 - dy;
  76131. l.ry1 = l.y2 + dx;
  76132. }
  76133. subPath.add (l);
  76134. if (it.closesSubPath)
  76135. {
  76136. addSubPath (destPath, subPath, true, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  76137. subPath.clearQuick();
  76138. }
  76139. else
  76140. {
  76141. l.x1 = it.x2;
  76142. l.y1 = it.y2;
  76143. }
  76144. }
  76145. }
  76146. if (subPath.size() > 0)
  76147. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  76148. }
  76149. }
  76150. void PathStrokeType::createStrokedPath (Path& destPath, const Path& sourcePath,
  76151. const AffineTransform& transform, const float extraAccuracy) const
  76152. {
  76153. PathStrokeHelpers::createStroke (thickness, jointStyle, endStyle, destPath, sourcePath,
  76154. transform, extraAccuracy, 0);
  76155. }
  76156. void PathStrokeType::createDashedStroke (Path& destPath,
  76157. const Path& sourcePath,
  76158. const float* dashLengths,
  76159. int numDashLengths,
  76160. const AffineTransform& transform,
  76161. const float extraAccuracy) const
  76162. {
  76163. if (thickness <= 0)
  76164. return;
  76165. // this should really be an even number..
  76166. jassert ((numDashLengths & 1) == 0);
  76167. Path newDestPath;
  76168. PathFlatteningIterator it (sourcePath, transform, 9.0f / extraAccuracy);
  76169. bool first = true;
  76170. int dashNum = 0;
  76171. float pos = 0.0f, lineLen = 0.0f, lineEndPos = 0.0f;
  76172. float dx = 0.0f, dy = 0.0f;
  76173. for (;;)
  76174. {
  76175. const bool isSolid = ((dashNum & 1) == 0);
  76176. const float dashLen = dashLengths [dashNum++ % numDashLengths];
  76177. jassert (dashLen > 0); // must be a positive increment!
  76178. if (dashLen <= 0)
  76179. break;
  76180. pos += dashLen;
  76181. while (pos > lineEndPos)
  76182. {
  76183. if (! it.next())
  76184. {
  76185. if (isSolid && ! first)
  76186. newDestPath.lineTo (it.x2, it.y2);
  76187. createStrokedPath (destPath, newDestPath, AffineTransform::identity, extraAccuracy);
  76188. return;
  76189. }
  76190. if (isSolid && ! first)
  76191. newDestPath.lineTo (it.x1, it.y1);
  76192. else
  76193. newDestPath.startNewSubPath (it.x1, it.y1);
  76194. dx = it.x2 - it.x1;
  76195. dy = it.y2 - it.y1;
  76196. lineLen = juce_hypotf (dx, dy);
  76197. lineEndPos += lineLen;
  76198. first = it.closesSubPath;
  76199. }
  76200. const float alpha = (pos - (lineEndPos - lineLen)) / lineLen;
  76201. if (isSolid)
  76202. newDestPath.lineTo (it.x1 + dx * alpha,
  76203. it.y1 + dy * alpha);
  76204. else
  76205. newDestPath.startNewSubPath (it.x1 + dx * alpha,
  76206. it.y1 + dy * alpha);
  76207. }
  76208. }
  76209. void PathStrokeType::createStrokeWithArrowheads (Path& destPath,
  76210. const Path& sourcePath,
  76211. const float arrowheadStartWidth, const float arrowheadStartLength,
  76212. const float arrowheadEndWidth, const float arrowheadEndLength,
  76213. const AffineTransform& transform,
  76214. const float extraAccuracy) const
  76215. {
  76216. PathStrokeHelpers::Arrowhead head;
  76217. head.startWidth = arrowheadStartWidth;
  76218. head.startLength = arrowheadStartLength;
  76219. head.endWidth = arrowheadEndWidth;
  76220. head.endLength = arrowheadEndLength;
  76221. PathStrokeHelpers::createStroke (thickness, jointStyle, endStyle,
  76222. destPath, sourcePath, transform, extraAccuracy, &head);
  76223. }
  76224. END_JUCE_NAMESPACE
  76225. /*** End of inlined file: juce_PathStrokeType.cpp ***/
  76226. /*** Start of inlined file: juce_PositionedRectangle.cpp ***/
  76227. BEGIN_JUCE_NAMESPACE
  76228. PositionedRectangle::PositionedRectangle() throw()
  76229. : x (0.0),
  76230. y (0.0),
  76231. w (0.0),
  76232. h (0.0),
  76233. xMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  76234. yMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  76235. wMode (absoluteSize),
  76236. hMode (absoluteSize)
  76237. {
  76238. }
  76239. PositionedRectangle::PositionedRectangle (const PositionedRectangle& other) throw()
  76240. : x (other.x),
  76241. y (other.y),
  76242. w (other.w),
  76243. h (other.h),
  76244. xMode (other.xMode),
  76245. yMode (other.yMode),
  76246. wMode (other.wMode),
  76247. hMode (other.hMode)
  76248. {
  76249. }
  76250. PositionedRectangle& PositionedRectangle::operator= (const PositionedRectangle& other) throw()
  76251. {
  76252. x = other.x;
  76253. y = other.y;
  76254. w = other.w;
  76255. h = other.h;
  76256. xMode = other.xMode;
  76257. yMode = other.yMode;
  76258. wMode = other.wMode;
  76259. hMode = other.hMode;
  76260. return *this;
  76261. }
  76262. PositionedRectangle::~PositionedRectangle() throw()
  76263. {
  76264. }
  76265. bool PositionedRectangle::operator== (const PositionedRectangle& other) const throw()
  76266. {
  76267. return x == other.x
  76268. && y == other.y
  76269. && w == other.w
  76270. && h == other.h
  76271. && xMode == other.xMode
  76272. && yMode == other.yMode
  76273. && wMode == other.wMode
  76274. && hMode == other.hMode;
  76275. }
  76276. bool PositionedRectangle::operator!= (const PositionedRectangle& other) const throw()
  76277. {
  76278. return ! operator== (other);
  76279. }
  76280. PositionedRectangle::PositionedRectangle (const String& stringVersion) throw()
  76281. {
  76282. StringArray tokens;
  76283. tokens.addTokens (stringVersion, false);
  76284. decodePosString (tokens [0], xMode, x);
  76285. decodePosString (tokens [1], yMode, y);
  76286. decodeSizeString (tokens [2], wMode, w);
  76287. decodeSizeString (tokens [3], hMode, h);
  76288. }
  76289. const String PositionedRectangle::toString() const throw()
  76290. {
  76291. String s;
  76292. s.preallocateStorage (12);
  76293. addPosDescription (s, xMode, x);
  76294. s << ' ';
  76295. addPosDescription (s, yMode, y);
  76296. s << ' ';
  76297. addSizeDescription (s, wMode, w);
  76298. s << ' ';
  76299. addSizeDescription (s, hMode, h);
  76300. return s;
  76301. }
  76302. const Rectangle<int> PositionedRectangle::getRectangle (const Rectangle<int>& target) const throw()
  76303. {
  76304. jassert (! target.isEmpty());
  76305. double x_, y_, w_, h_;
  76306. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  76307. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  76308. return Rectangle<int> (roundToInt (x_), roundToInt (y_),
  76309. roundToInt (w_), roundToInt (h_));
  76310. }
  76311. void PositionedRectangle::getRectangleDouble (const Rectangle<int>& target,
  76312. double& x_, double& y_,
  76313. double& w_, double& h_) const throw()
  76314. {
  76315. jassert (! target.isEmpty());
  76316. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  76317. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  76318. }
  76319. void PositionedRectangle::applyToComponent (Component& comp) const throw()
  76320. {
  76321. comp.setBounds (getRectangle (Rectangle<int> (comp.getParentWidth(), comp.getParentHeight())));
  76322. }
  76323. void PositionedRectangle::updateFrom (const Rectangle<int>& rectangle,
  76324. const Rectangle<int>& target) throw()
  76325. {
  76326. updatePosAndSize (x, w, rectangle.getX(), rectangle.getWidth(), xMode, wMode, target.getX(), target.getWidth());
  76327. updatePosAndSize (y, h, rectangle.getY(), rectangle.getHeight(), yMode, hMode, target.getY(), target.getHeight());
  76328. }
  76329. void PositionedRectangle::updateFromDouble (const double newX, const double newY,
  76330. const double newW, const double newH,
  76331. const Rectangle<int>& target) throw()
  76332. {
  76333. updatePosAndSize (x, w, newX, newW, xMode, wMode, target.getX(), target.getWidth());
  76334. updatePosAndSize (y, h, newY, newH, yMode, hMode, target.getY(), target.getHeight());
  76335. }
  76336. void PositionedRectangle::updateFromComponent (const Component& comp) throw()
  76337. {
  76338. if (comp.getParentComponent() == 0 && ! comp.isOnDesktop())
  76339. updateFrom (comp.getBounds(), Rectangle<int>());
  76340. else
  76341. updateFrom (comp.getBounds(), Rectangle<int> (comp.getParentWidth(), comp.getParentHeight()));
  76342. }
  76343. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointX() const throw()
  76344. {
  76345. return (AnchorPoint) (xMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  76346. }
  76347. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeX() const throw()
  76348. {
  76349. return (PositionMode) (xMode & (absoluteFromParentTopLeft
  76350. | absoluteFromParentBottomRight
  76351. | absoluteFromParentCentre
  76352. | proportionOfParentSize));
  76353. }
  76354. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointY() const throw()
  76355. {
  76356. return (AnchorPoint) (yMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  76357. }
  76358. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeY() const throw()
  76359. {
  76360. return (PositionMode) (yMode & (absoluteFromParentTopLeft
  76361. | absoluteFromParentBottomRight
  76362. | absoluteFromParentCentre
  76363. | proportionOfParentSize));
  76364. }
  76365. PositionedRectangle::SizeMode PositionedRectangle::getWidthMode() const throw()
  76366. {
  76367. return (SizeMode) wMode;
  76368. }
  76369. PositionedRectangle::SizeMode PositionedRectangle::getHeightMode() const throw()
  76370. {
  76371. return (SizeMode) hMode;
  76372. }
  76373. void PositionedRectangle::setModes (const AnchorPoint xAnchor,
  76374. const PositionMode xMode_,
  76375. const AnchorPoint yAnchor,
  76376. const PositionMode yMode_,
  76377. const SizeMode widthMode,
  76378. const SizeMode heightMode,
  76379. const Rectangle<int>& target) throw()
  76380. {
  76381. if (xMode != (xAnchor | xMode_) || wMode != widthMode)
  76382. {
  76383. double tx, tw;
  76384. applyPosAndSize (tx, tw, x, w, xMode, wMode, target.getX(), target.getWidth());
  76385. xMode = (uint8) (xAnchor | xMode_);
  76386. wMode = (uint8) widthMode;
  76387. updatePosAndSize (x, w, tx, tw, xMode, wMode, target.getX(), target.getWidth());
  76388. }
  76389. if (yMode != (yAnchor | yMode_) || hMode != heightMode)
  76390. {
  76391. double ty, th;
  76392. applyPosAndSize (ty, th, y, h, yMode, hMode, target.getY(), target.getHeight());
  76393. yMode = (uint8) (yAnchor | yMode_);
  76394. hMode = (uint8) heightMode;
  76395. updatePosAndSize (y, h, ty, th, yMode, hMode, target.getY(), target.getHeight());
  76396. }
  76397. }
  76398. bool PositionedRectangle::isPositionAbsolute() const throw()
  76399. {
  76400. return xMode == absoluteFromParentTopLeft
  76401. && yMode == absoluteFromParentTopLeft
  76402. && wMode == absoluteSize
  76403. && hMode == absoluteSize;
  76404. }
  76405. void PositionedRectangle::addPosDescription (String& s, const uint8 mode, const double value) const throw()
  76406. {
  76407. if ((mode & proportionOfParentSize) != 0)
  76408. {
  76409. s << (roundToInt (value * 100000.0) / 1000.0) << '%';
  76410. }
  76411. else
  76412. {
  76413. s << (roundToInt (value * 100.0) / 100.0);
  76414. if ((mode & absoluteFromParentBottomRight) != 0)
  76415. s << 'R';
  76416. else if ((mode & absoluteFromParentCentre) != 0)
  76417. s << 'C';
  76418. }
  76419. if ((mode & anchorAtRightOrBottom) != 0)
  76420. s << 'r';
  76421. else if ((mode & anchorAtCentre) != 0)
  76422. s << 'c';
  76423. }
  76424. void PositionedRectangle::addSizeDescription (String& s, const uint8 mode, const double value) const throw()
  76425. {
  76426. if (mode == proportionalSize)
  76427. s << (roundToInt (value * 100000.0) / 1000.0) << '%';
  76428. else if (mode == parentSizeMinusAbsolute)
  76429. s << (roundToInt (value * 100.0) / 100.0) << 'M';
  76430. else
  76431. s << (roundToInt (value * 100.0) / 100.0);
  76432. }
  76433. void PositionedRectangle::decodePosString (const String& s, uint8& mode, double& value) throw()
  76434. {
  76435. if (s.containsChar ('r'))
  76436. mode = anchorAtRightOrBottom;
  76437. else if (s.containsChar ('c'))
  76438. mode = anchorAtCentre;
  76439. else
  76440. mode = anchorAtLeftOrTop;
  76441. if (s.containsChar ('%'))
  76442. {
  76443. mode |= proportionOfParentSize;
  76444. value = s.removeCharacters ("%rcRC").getDoubleValue() / 100.0;
  76445. }
  76446. else
  76447. {
  76448. if (s.containsChar ('R'))
  76449. mode |= absoluteFromParentBottomRight;
  76450. else if (s.containsChar ('C'))
  76451. mode |= absoluteFromParentCentre;
  76452. else
  76453. mode |= absoluteFromParentTopLeft;
  76454. value = s.removeCharacters ("rcRC").getDoubleValue();
  76455. }
  76456. }
  76457. void PositionedRectangle::decodeSizeString (const String& s, uint8& mode, double& value) throw()
  76458. {
  76459. if (s.containsChar ('%'))
  76460. {
  76461. mode = proportionalSize;
  76462. value = s.upToFirstOccurrenceOf ("%", false, false).getDoubleValue() / 100.0;
  76463. }
  76464. else if (s.containsChar ('M'))
  76465. {
  76466. mode = parentSizeMinusAbsolute;
  76467. value = s.getDoubleValue();
  76468. }
  76469. else
  76470. {
  76471. mode = absoluteSize;
  76472. value = s.getDoubleValue();
  76473. }
  76474. }
  76475. void PositionedRectangle::applyPosAndSize (double& xOut, double& wOut,
  76476. const double x_, const double w_,
  76477. const uint8 xMode_, const uint8 wMode_,
  76478. const int parentPos,
  76479. const int parentSize) const throw()
  76480. {
  76481. if (wMode_ == proportionalSize)
  76482. wOut = roundToInt (w_ * parentSize);
  76483. else if (wMode_ == parentSizeMinusAbsolute)
  76484. wOut = jmax (0, parentSize - roundToInt (w_));
  76485. else
  76486. wOut = roundToInt (w_);
  76487. if ((xMode_ & proportionOfParentSize) != 0)
  76488. xOut = parentPos + x_ * parentSize;
  76489. else if ((xMode_ & absoluteFromParentBottomRight) != 0)
  76490. xOut = (parentPos + parentSize) - x_;
  76491. else if ((xMode_ & absoluteFromParentCentre) != 0)
  76492. xOut = x_ + (parentPos + parentSize / 2);
  76493. else
  76494. xOut = x_ + parentPos;
  76495. if ((xMode_ & anchorAtRightOrBottom) != 0)
  76496. xOut -= wOut;
  76497. else if ((xMode_ & anchorAtCentre) != 0)
  76498. xOut -= wOut / 2;
  76499. }
  76500. void PositionedRectangle::updatePosAndSize (double& xOut, double& wOut,
  76501. double x_, const double w_,
  76502. const uint8 xMode_, const uint8 wMode_,
  76503. const int parentPos,
  76504. const int parentSize) const throw()
  76505. {
  76506. if (wMode_ == proportionalSize)
  76507. {
  76508. if (parentSize > 0)
  76509. wOut = w_ / parentSize;
  76510. }
  76511. else if (wMode_ == parentSizeMinusAbsolute)
  76512. wOut = parentSize - w_;
  76513. else
  76514. wOut = w_;
  76515. if ((xMode_ & anchorAtRightOrBottom) != 0)
  76516. x_ += w_;
  76517. else if ((xMode_ & anchorAtCentre) != 0)
  76518. x_ += w_ / 2;
  76519. if ((xMode_ & proportionOfParentSize) != 0)
  76520. {
  76521. if (parentSize > 0)
  76522. xOut = (x_ - parentPos) / parentSize;
  76523. }
  76524. else if ((xMode_ & absoluteFromParentBottomRight) != 0)
  76525. xOut = (parentPos + parentSize) - x_;
  76526. else if ((xMode_ & absoluteFromParentCentre) != 0)
  76527. xOut = x_ - (parentPos + parentSize / 2);
  76528. else
  76529. xOut = x_ - parentPos;
  76530. }
  76531. END_JUCE_NAMESPACE
  76532. /*** End of inlined file: juce_PositionedRectangle.cpp ***/
  76533. /*** Start of inlined file: juce_RectangleList.cpp ***/
  76534. BEGIN_JUCE_NAMESPACE
  76535. RectangleList::RectangleList() throw()
  76536. {
  76537. }
  76538. RectangleList::RectangleList (const Rectangle<int>& rect)
  76539. {
  76540. if (! rect.isEmpty())
  76541. rects.add (rect);
  76542. }
  76543. RectangleList::RectangleList (const RectangleList& other)
  76544. : rects (other.rects)
  76545. {
  76546. }
  76547. RectangleList& RectangleList::operator= (const RectangleList& other)
  76548. {
  76549. rects = other.rects;
  76550. return *this;
  76551. }
  76552. RectangleList::~RectangleList()
  76553. {
  76554. }
  76555. void RectangleList::clear()
  76556. {
  76557. rects.clearQuick();
  76558. }
  76559. const Rectangle<int> RectangleList::getRectangle (const int index) const throw()
  76560. {
  76561. if (((unsigned int) index) < (unsigned int) rects.size())
  76562. return rects.getReference (index);
  76563. return Rectangle<int>();
  76564. }
  76565. bool RectangleList::isEmpty() const throw()
  76566. {
  76567. return rects.size() == 0;
  76568. }
  76569. RectangleList::Iterator::Iterator (const RectangleList& list) throw()
  76570. : current (0),
  76571. owner (list),
  76572. index (list.rects.size())
  76573. {
  76574. }
  76575. RectangleList::Iterator::~Iterator()
  76576. {
  76577. }
  76578. bool RectangleList::Iterator::next() throw()
  76579. {
  76580. if (--index >= 0)
  76581. {
  76582. current = & (owner.rects.getReference (index));
  76583. return true;
  76584. }
  76585. return false;
  76586. }
  76587. void RectangleList::add (const Rectangle<int>& rect)
  76588. {
  76589. if (! rect.isEmpty())
  76590. {
  76591. if (rects.size() == 0)
  76592. {
  76593. rects.add (rect);
  76594. }
  76595. else
  76596. {
  76597. bool anyOverlaps = false;
  76598. int i;
  76599. for (i = rects.size(); --i >= 0;)
  76600. {
  76601. Rectangle<int>& ourRect = rects.getReference (i);
  76602. if (rect.intersects (ourRect))
  76603. {
  76604. if (rect.contains (ourRect))
  76605. rects.remove (i);
  76606. else if (! ourRect.reduceIfPartlyContainedIn (rect))
  76607. anyOverlaps = true;
  76608. }
  76609. }
  76610. if (anyOverlaps && rects.size() > 0)
  76611. {
  76612. RectangleList r (rect);
  76613. for (i = rects.size(); --i >= 0;)
  76614. {
  76615. const Rectangle<int>& ourRect = rects.getReference (i);
  76616. if (rect.intersects (ourRect))
  76617. {
  76618. r.subtract (ourRect);
  76619. if (r.rects.size() == 0)
  76620. return;
  76621. }
  76622. }
  76623. for (i = r.getNumRectangles(); --i >= 0;)
  76624. rects.add (r.rects.getReference (i));
  76625. }
  76626. else
  76627. {
  76628. rects.add (rect);
  76629. }
  76630. }
  76631. }
  76632. }
  76633. void RectangleList::addWithoutMerging (const Rectangle<int>& rect)
  76634. {
  76635. if (! rect.isEmpty())
  76636. rects.add (rect);
  76637. }
  76638. void RectangleList::add (const int x, const int y, const int w, const int h)
  76639. {
  76640. if (rects.size() == 0)
  76641. {
  76642. if (w > 0 && h > 0)
  76643. rects.add (Rectangle<int> (x, y, w, h));
  76644. }
  76645. else
  76646. {
  76647. add (Rectangle<int> (x, y, w, h));
  76648. }
  76649. }
  76650. void RectangleList::add (const RectangleList& other)
  76651. {
  76652. for (int i = 0; i < other.rects.size(); ++i)
  76653. add (other.rects.getReference (i));
  76654. }
  76655. void RectangleList::subtract (const Rectangle<int>& rect)
  76656. {
  76657. const int originalNumRects = rects.size();
  76658. if (originalNumRects > 0)
  76659. {
  76660. const int x1 = rect.x;
  76661. const int y1 = rect.y;
  76662. const int x2 = x1 + rect.w;
  76663. const int y2 = y1 + rect.h;
  76664. for (int i = getNumRectangles(); --i >= 0;)
  76665. {
  76666. Rectangle<int>& r = rects.getReference (i);
  76667. const int rx1 = r.x;
  76668. const int ry1 = r.y;
  76669. const int rx2 = rx1 + r.w;
  76670. const int ry2 = ry1 + r.h;
  76671. if (! (x2 <= rx1 || x1 >= rx2 || y2 <= ry1 || y1 >= ry2))
  76672. {
  76673. if (x1 > rx1 && x1 < rx2)
  76674. {
  76675. if (y1 <= ry1 && y2 >= ry2 && x2 >= rx2)
  76676. {
  76677. r.w = x1 - rx1;
  76678. }
  76679. else
  76680. {
  76681. r.x = x1;
  76682. r.w = rx2 - x1;
  76683. rects.insert (i + 1, Rectangle<int> (rx1, ry1, x1 - rx1, ry2 - ry1));
  76684. i += 2;
  76685. }
  76686. }
  76687. else if (x2 > rx1 && x2 < rx2)
  76688. {
  76689. r.x = x2;
  76690. r.w = rx2 - x2;
  76691. if (y1 > ry1 || y2 < ry2 || x1 > rx1)
  76692. {
  76693. rects.insert (i + 1, Rectangle<int> (rx1, ry1, x2 - rx1, ry2 - ry1));
  76694. i += 2;
  76695. }
  76696. }
  76697. else if (y1 > ry1 && y1 < ry2)
  76698. {
  76699. if (x1 <= rx1 && x2 >= rx2 && y2 >= ry2)
  76700. {
  76701. r.h = y1 - ry1;
  76702. }
  76703. else
  76704. {
  76705. r.y = y1;
  76706. r.h = ry2 - y1;
  76707. rects.insert (i + 1, Rectangle<int> (rx1, ry1, rx2 - rx1, y1 - ry1));
  76708. i += 2;
  76709. }
  76710. }
  76711. else if (y2 > ry1 && y2 < ry2)
  76712. {
  76713. r.y = y2;
  76714. r.h = ry2 - y2;
  76715. if (x1 > rx1 || x2 < rx2 || y1 > ry1)
  76716. {
  76717. rects.insert (i + 1, Rectangle<int> (rx1, ry1, rx2 - rx1, y2 - ry1));
  76718. i += 2;
  76719. }
  76720. }
  76721. else
  76722. {
  76723. rects.remove (i);
  76724. }
  76725. }
  76726. }
  76727. }
  76728. }
  76729. bool RectangleList::subtract (const RectangleList& otherList)
  76730. {
  76731. for (int i = otherList.rects.size(); --i >= 0 && rects.size() > 0;)
  76732. subtract (otherList.rects.getReference (i));
  76733. return rects.size() > 0;
  76734. }
  76735. bool RectangleList::clipTo (const Rectangle<int>& rect)
  76736. {
  76737. bool notEmpty = false;
  76738. if (rect.isEmpty())
  76739. {
  76740. clear();
  76741. }
  76742. else
  76743. {
  76744. for (int i = rects.size(); --i >= 0;)
  76745. {
  76746. Rectangle<int>& r = rects.getReference (i);
  76747. if (! rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76748. rects.remove (i);
  76749. else
  76750. notEmpty = true;
  76751. }
  76752. }
  76753. return notEmpty;
  76754. }
  76755. bool RectangleList::clipTo (const RectangleList& other)
  76756. {
  76757. if (rects.size() == 0)
  76758. return false;
  76759. RectangleList result;
  76760. for (int j = 0; j < rects.size(); ++j)
  76761. {
  76762. const Rectangle<int>& rect = rects.getReference (j);
  76763. for (int i = other.rects.size(); --i >= 0;)
  76764. {
  76765. Rectangle<int> r (other.rects.getReference (i));
  76766. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76767. result.rects.add (r);
  76768. }
  76769. }
  76770. swapWith (result);
  76771. return ! isEmpty();
  76772. }
  76773. bool RectangleList::getIntersectionWith (const Rectangle<int>& rect, RectangleList& destRegion) const
  76774. {
  76775. destRegion.clear();
  76776. if (! rect.isEmpty())
  76777. {
  76778. for (int i = rects.size(); --i >= 0;)
  76779. {
  76780. Rectangle<int> r (rects.getReference (i));
  76781. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76782. destRegion.rects.add (r);
  76783. }
  76784. }
  76785. return destRegion.rects.size() > 0;
  76786. }
  76787. void RectangleList::swapWith (RectangleList& otherList) throw()
  76788. {
  76789. rects.swapWithArray (otherList.rects);
  76790. }
  76791. void RectangleList::consolidate()
  76792. {
  76793. int i;
  76794. for (i = 0; i < getNumRectangles() - 1; ++i)
  76795. {
  76796. Rectangle<int>& r = rects.getReference (i);
  76797. const int rx1 = r.x;
  76798. const int ry1 = r.y;
  76799. const int rx2 = rx1 + r.w;
  76800. const int ry2 = ry1 + r.h;
  76801. for (int j = rects.size(); --j > i;)
  76802. {
  76803. Rectangle<int>& r2 = rects.getReference (j);
  76804. const int jrx1 = r2.x;
  76805. const int jry1 = r2.y;
  76806. const int jrx2 = jrx1 + r2.w;
  76807. const int jry2 = jry1 + r2.h;
  76808. // if the vertical edges of any blocks are touching and their horizontals don't
  76809. // line up, split them horizontally..
  76810. if (jrx1 == rx2 || jrx2 == rx1)
  76811. {
  76812. if (jry1 > ry1 && jry1 < ry2)
  76813. {
  76814. r.h = jry1 - ry1;
  76815. rects.add (Rectangle<int> (rx1, jry1, rx2 - rx1, ry2 - jry1));
  76816. i = -1;
  76817. break;
  76818. }
  76819. if (jry2 > ry1 && jry2 < ry2)
  76820. {
  76821. r.h = jry2 - ry1;
  76822. rects.add (Rectangle<int> (rx1, jry2, rx2 - rx1, ry2 - jry2));
  76823. i = -1;
  76824. break;
  76825. }
  76826. else if (ry1 > jry1 && ry1 < jry2)
  76827. {
  76828. r2.h = ry1 - jry1;
  76829. rects.add (Rectangle<int> (jrx1, ry1, jrx2 - jrx1, jry2 - ry1));
  76830. i = -1;
  76831. break;
  76832. }
  76833. else if (ry2 > jry1 && ry2 < jry2)
  76834. {
  76835. r2.h = ry2 - jry1;
  76836. rects.add (Rectangle<int> (jrx1, ry2, jrx2 - jrx1, jry2 - ry2));
  76837. i = -1;
  76838. break;
  76839. }
  76840. }
  76841. }
  76842. }
  76843. for (i = 0; i < rects.size() - 1; ++i)
  76844. {
  76845. Rectangle<int>& r = rects.getReference (i);
  76846. for (int j = rects.size(); --j > i;)
  76847. {
  76848. if (r.enlargeIfAdjacent (rects.getReference (j)))
  76849. {
  76850. rects.remove (j);
  76851. i = -1;
  76852. break;
  76853. }
  76854. }
  76855. }
  76856. }
  76857. bool RectangleList::containsPoint (const int x, const int y) const throw()
  76858. {
  76859. for (int i = getNumRectangles(); --i >= 0;)
  76860. if (rects.getReference (i).contains (x, y))
  76861. return true;
  76862. return false;
  76863. }
  76864. bool RectangleList::containsRectangle (const Rectangle<int>& rectangleToCheck) const
  76865. {
  76866. if (rects.size() > 1)
  76867. {
  76868. RectangleList r (rectangleToCheck);
  76869. for (int i = rects.size(); --i >= 0;)
  76870. {
  76871. r.subtract (rects.getReference (i));
  76872. if (r.rects.size() == 0)
  76873. return true;
  76874. }
  76875. }
  76876. else if (rects.size() > 0)
  76877. {
  76878. return rects.getReference (0).contains (rectangleToCheck);
  76879. }
  76880. return false;
  76881. }
  76882. bool RectangleList::intersectsRectangle (const Rectangle<int>& rectangleToCheck) const throw()
  76883. {
  76884. for (int i = rects.size(); --i >= 0;)
  76885. if (rects.getReference (i).intersects (rectangleToCheck))
  76886. return true;
  76887. return false;
  76888. }
  76889. bool RectangleList::intersects (const RectangleList& other) const throw()
  76890. {
  76891. for (int i = rects.size(); --i >= 0;)
  76892. if (other.intersectsRectangle (rects.getReference (i)))
  76893. return true;
  76894. return false;
  76895. }
  76896. const Rectangle<int> RectangleList::getBounds() const throw()
  76897. {
  76898. if (rects.size() <= 1)
  76899. {
  76900. if (rects.size() == 0)
  76901. return Rectangle<int>();
  76902. else
  76903. return rects.getReference (0);
  76904. }
  76905. else
  76906. {
  76907. const Rectangle<int>& r = rects.getReference (0);
  76908. int minX = r.x;
  76909. int minY = r.y;
  76910. int maxX = minX + r.w;
  76911. int maxY = minY + r.h;
  76912. for (int i = rects.size(); --i > 0;)
  76913. {
  76914. const Rectangle<int>& r2 = rects.getReference (i);
  76915. minX = jmin (minX, r2.x);
  76916. minY = jmin (minY, r2.y);
  76917. maxX = jmax (maxX, r2.getRight());
  76918. maxY = jmax (maxY, r2.getBottom());
  76919. }
  76920. return Rectangle<int> (minX, minY, maxX - minX, maxY - minY);
  76921. }
  76922. }
  76923. void RectangleList::offsetAll (const int dx, const int dy) throw()
  76924. {
  76925. for (int i = rects.size(); --i >= 0;)
  76926. {
  76927. Rectangle<int>& r = rects.getReference (i);
  76928. r.x += dx;
  76929. r.y += dy;
  76930. }
  76931. }
  76932. const Path RectangleList::toPath() const
  76933. {
  76934. Path p;
  76935. for (int i = rects.size(); --i >= 0;)
  76936. {
  76937. const Rectangle<int>& r = rects.getReference (i);
  76938. p.addRectangle ((float) r.x,
  76939. (float) r.y,
  76940. (float) r.w,
  76941. (float) r.h);
  76942. }
  76943. return p;
  76944. }
  76945. END_JUCE_NAMESPACE
  76946. /*** End of inlined file: juce_RectangleList.cpp ***/
  76947. /*** Start of inlined file: juce_Image.cpp ***/
  76948. BEGIN_JUCE_NAMESPACE
  76949. Image::SharedImage::SharedImage (const PixelFormat format_, const int width_, const int height_)
  76950. : format (format_), width (width_), height (height_)
  76951. {
  76952. jassert (format_ == RGB || format_ == ARGB || format_ == SingleChannel);
  76953. jassert (width > 0 && height > 0); // It's illegal to create a zero-sized image!
  76954. }
  76955. Image::SharedImage::~SharedImage()
  76956. {
  76957. }
  76958. inline uint8* Image::SharedImage::getPixelData (const int x, const int y) const throw()
  76959. {
  76960. return imageData + lineStride * y + pixelStride * x;
  76961. }
  76962. class SoftwareSharedImage : public Image::SharedImage
  76963. {
  76964. public:
  76965. SoftwareSharedImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  76966. : Image::SharedImage (format_, width_, height_)
  76967. {
  76968. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  76969. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  76970. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  76971. imageData = imageDataAllocated;
  76972. }
  76973. ~SoftwareSharedImage()
  76974. {
  76975. }
  76976. Image::ImageType getType() const
  76977. {
  76978. return Image::SoftwareImage;
  76979. }
  76980. LowLevelGraphicsContext* createLowLevelContext()
  76981. {
  76982. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  76983. }
  76984. SharedImage* clone()
  76985. {
  76986. SoftwareSharedImage* s = new SoftwareSharedImage (format, width, height, false);
  76987. memcpy (s->imageData, imageData, lineStride * height);
  76988. return s;
  76989. }
  76990. private:
  76991. HeapBlock<uint8> imageDataAllocated;
  76992. };
  76993. Image::SharedImage* Image::SharedImage::createSoftwareImage (Image::PixelFormat format, int width, int height, bool clearImage)
  76994. {
  76995. return new SoftwareSharedImage (format, width, height, clearImage);
  76996. }
  76997. class SubsectionSharedImage : public Image::SharedImage
  76998. {
  76999. public:
  77000. SubsectionSharedImage (Image::SharedImage* const image_, const Rectangle<int>& area_)
  77001. : Image::SharedImage (image_->getPixelFormat(), area_.getWidth(), area_.getHeight()),
  77002. image (image_), area (area_)
  77003. {
  77004. pixelStride = image_->getPixelStride();
  77005. lineStride = image_->getLineStride();
  77006. imageData = image_->getPixelData (area_.getX(), area_.getY());
  77007. }
  77008. ~SubsectionSharedImage() {}
  77009. Image::ImageType getType() const
  77010. {
  77011. return Image::SoftwareImage;
  77012. }
  77013. LowLevelGraphicsContext* createLowLevelContext()
  77014. {
  77015. LowLevelGraphicsContext* g = image->createLowLevelContext();
  77016. g->clipToRectangle (area);
  77017. g->setOrigin (area.getX(), area.getY());
  77018. return g;
  77019. }
  77020. SharedImage* clone()
  77021. {
  77022. return new SubsectionSharedImage (image->clone(), area);
  77023. }
  77024. private:
  77025. const ReferenceCountedObjectPtr<Image::SharedImage> image;
  77026. const Rectangle<int> area;
  77027. SubsectionSharedImage (const SubsectionSharedImage&);
  77028. SubsectionSharedImage& operator= (const SubsectionSharedImage&);
  77029. };
  77030. const Image Image::getClippedImage (const Rectangle<int>& area) const
  77031. {
  77032. if (area.contains (getBounds()))
  77033. return *this;
  77034. const Rectangle<int> validArea (area.getIntersection (getBounds()));
  77035. if (validArea.isEmpty())
  77036. return Image::null;
  77037. return Image (new SubsectionSharedImage (image, validArea));
  77038. }
  77039. Image::Image()
  77040. {
  77041. }
  77042. Image::Image (SharedImage* const instance)
  77043. : image (instance)
  77044. {
  77045. }
  77046. Image::Image (const PixelFormat format,
  77047. const int width, const int height,
  77048. const bool clearImage, const ImageType type)
  77049. : image (type == Image::NativeImage ? SharedImage::createNativeImage (format, width, height, clearImage)
  77050. : new SoftwareSharedImage (format, width, height, clearImage))
  77051. {
  77052. }
  77053. Image::Image (const Image& other)
  77054. : image (other.image)
  77055. {
  77056. }
  77057. Image& Image::operator= (const Image& other)
  77058. {
  77059. image = other.image;
  77060. return *this;
  77061. }
  77062. Image::~Image()
  77063. {
  77064. }
  77065. const Image Image::null;
  77066. LowLevelGraphicsContext* Image::createLowLevelContext() const
  77067. {
  77068. return image == 0 ? 0 : image->createLowLevelContext();
  77069. }
  77070. void Image::duplicateIfShared()
  77071. {
  77072. if (image != 0 && image->getReferenceCount() > 1)
  77073. image = image->clone();
  77074. }
  77075. const Image Image::rescaled (const int newWidth, const int newHeight, const Graphics::ResamplingQuality quality) const
  77076. {
  77077. if (image == 0 || (image->width == newWidth && image->height == newHeight))
  77078. return *this;
  77079. Image newImage (image->format, newWidth, newHeight, hasAlphaChannel(), image->getType());
  77080. Graphics g (newImage);
  77081. g.setImageResamplingQuality (quality);
  77082. g.drawImage (*this, 0, 0, newWidth, newHeight, 0, 0, image->width, image->height, false);
  77083. return newImage;
  77084. }
  77085. const Image Image::convertedToFormat (PixelFormat newFormat) const
  77086. {
  77087. if (image == 0 || newFormat == image->format)
  77088. return *this;
  77089. Image newImage (newFormat, image->width, image->height, false, image->getType());
  77090. if (newFormat == SingleChannel)
  77091. {
  77092. if (! hasAlphaChannel())
  77093. {
  77094. newImage.clear (getBounds(), Colours::black);
  77095. }
  77096. else
  77097. {
  77098. const BitmapData destData (newImage, 0, 0, image->width, image->height, true);
  77099. const BitmapData srcData (*this, 0, 0, image->width, image->height);
  77100. for (int y = 0; y < image->height; ++y)
  77101. {
  77102. const PixelARGB* src = (const PixelARGB*) srcData.getLinePointer(y);
  77103. uint8* dst = destData.getLinePointer (y);
  77104. for (int x = image->width; --x >= 0;)
  77105. {
  77106. *dst++ = src->getAlpha();
  77107. ++src;
  77108. }
  77109. }
  77110. }
  77111. }
  77112. else
  77113. {
  77114. if (hasAlphaChannel())
  77115. newImage.clear (getBounds());
  77116. Graphics g (newImage);
  77117. g.drawImageAt (*this, 0, 0);
  77118. }
  77119. return newImage;
  77120. }
  77121. NamedValueSet* Image::getProperties() const
  77122. {
  77123. return image == 0 ? 0 : &(image->userData);
  77124. }
  77125. Image::BitmapData::BitmapData (Image& image, const int x, const int y, const int w, const int h, const bool /*makeWritable*/)
  77126. : data (image.image == 0 ? 0 : image.image->getPixelData (x, y)),
  77127. pixelFormat (image.getFormat()),
  77128. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  77129. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  77130. width (w),
  77131. height (h)
  77132. {
  77133. jassert (data != 0);
  77134. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= image.getWidth() && y + h <= image.getHeight());
  77135. }
  77136. Image::BitmapData::BitmapData (const Image& image, const int x, const int y, const int w, const int h)
  77137. : data (image.image == 0 ? 0 : image.image->getPixelData (x, y)),
  77138. pixelFormat (image.getFormat()),
  77139. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  77140. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  77141. width (w),
  77142. height (h)
  77143. {
  77144. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= image.getWidth() && y + h <= image.getHeight());
  77145. }
  77146. Image::BitmapData::BitmapData (const Image& image, bool /*needsToBeWritable*/)
  77147. : data (image.image == 0 ? 0 : image.image->imageData),
  77148. pixelFormat (image.getFormat()),
  77149. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  77150. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  77151. width (image.getWidth()),
  77152. height (image.getHeight())
  77153. {
  77154. }
  77155. Image::BitmapData::~BitmapData()
  77156. {
  77157. }
  77158. const Colour Image::BitmapData::getPixelColour (const int x, const int y) const throw()
  77159. {
  77160. jassert (((unsigned int) x) < (unsigned int) width && ((unsigned int) y) < (unsigned int) height);
  77161. const uint8* const pixel = getPixelPointer (x, y);
  77162. switch (pixelFormat)
  77163. {
  77164. case Image::ARGB:
  77165. {
  77166. PixelARGB p (*(const PixelARGB*) pixel);
  77167. p.unpremultiply();
  77168. return Colour (p.getARGB());
  77169. }
  77170. case Image::RGB:
  77171. return Colour (((const PixelRGB*) pixel)->getARGB());
  77172. case Image::SingleChannel:
  77173. return Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixel);
  77174. default:
  77175. jassertfalse;
  77176. break;
  77177. }
  77178. return Colour();
  77179. }
  77180. void Image::BitmapData::setPixelColour (const int x, const int y, const Colour& colour) const throw()
  77181. {
  77182. jassert (((unsigned int) x) < (unsigned int) width && ((unsigned int) y) < (unsigned int) height);
  77183. uint8* const pixel = getPixelPointer (x, y);
  77184. const PixelARGB col (colour.getPixelARGB());
  77185. switch (pixelFormat)
  77186. {
  77187. case Image::ARGB: ((PixelARGB*) pixel)->set (col); break;
  77188. case Image::RGB: ((PixelRGB*) pixel)->set (col); break;
  77189. case Image::SingleChannel: *pixel = col.getAlpha(); break;
  77190. default: jassertfalse; break;
  77191. }
  77192. }
  77193. void Image::setPixelData (int x, int y, int w, int h,
  77194. const uint8* const sourcePixelData, const int sourceLineStride)
  77195. {
  77196. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= getWidth() && y + h <= getHeight());
  77197. if (Rectangle<int>::intersectRectangles (x, y, w, h, 0, 0, getWidth(), getHeight()))
  77198. {
  77199. const BitmapData dest (*this, x, y, w, h, true);
  77200. for (int i = 0; i < h; ++i)
  77201. {
  77202. memcpy (dest.getLinePointer(i),
  77203. sourcePixelData + sourceLineStride * i,
  77204. w * dest.pixelStride);
  77205. }
  77206. }
  77207. }
  77208. void Image::clear (const Rectangle<int>& area, const Colour& colourToClearTo)
  77209. {
  77210. const Rectangle<int> clipped (area.getIntersection (getBounds()));
  77211. if (! clipped.isEmpty())
  77212. {
  77213. const PixelARGB col (colourToClearTo.getPixelARGB());
  77214. const BitmapData destData (*this, clipped.getX(), clipped.getY(), clipped.getWidth(), clipped.getHeight(), true);
  77215. uint8* dest = destData.data;
  77216. int dh = clipped.getHeight();
  77217. while (--dh >= 0)
  77218. {
  77219. uint8* line = dest;
  77220. dest += destData.lineStride;
  77221. if (isARGB())
  77222. {
  77223. for (int x = clipped.getWidth(); --x >= 0;)
  77224. {
  77225. ((PixelARGB*) line)->set (col);
  77226. line += destData.pixelStride;
  77227. }
  77228. }
  77229. else if (isRGB())
  77230. {
  77231. for (int x = clipped.getWidth(); --x >= 0;)
  77232. {
  77233. ((PixelRGB*) line)->set (col);
  77234. line += destData.pixelStride;
  77235. }
  77236. }
  77237. else
  77238. {
  77239. for (int x = clipped.getWidth(); --x >= 0;)
  77240. {
  77241. *line = col.getAlpha();
  77242. line += destData.pixelStride;
  77243. }
  77244. }
  77245. }
  77246. }
  77247. }
  77248. const Colour Image::getPixelAt (const int x, const int y) const
  77249. {
  77250. if (((unsigned int) x) < (unsigned int) getWidth()
  77251. && ((unsigned int) y) < (unsigned int) getHeight())
  77252. {
  77253. const BitmapData srcData (*this, x, y, 1, 1);
  77254. return srcData.getPixelColour (0, 0);
  77255. }
  77256. return Colour();
  77257. }
  77258. void Image::setPixelAt (const int x, const int y, const Colour& colour)
  77259. {
  77260. if (((unsigned int) x) < (unsigned int) getWidth()
  77261. && ((unsigned int) y) < (unsigned int) getHeight())
  77262. {
  77263. const BitmapData destData (*this, x, y, 1, 1, true);
  77264. destData.setPixelColour (0, 0, colour);
  77265. }
  77266. }
  77267. void Image::multiplyAlphaAt (const int x, const int y, const float multiplier)
  77268. {
  77269. if (((unsigned int) x) < (unsigned int) getWidth()
  77270. && ((unsigned int) y) < (unsigned int) getHeight()
  77271. && hasAlphaChannel())
  77272. {
  77273. const BitmapData destData (*this, x, y, 1, 1, true);
  77274. if (isARGB())
  77275. ((PixelARGB*) destData.data)->multiplyAlpha (multiplier);
  77276. else
  77277. *(destData.data) = (uint8) (*(destData.data) * multiplier);
  77278. }
  77279. }
  77280. void Image::multiplyAllAlphas (const float amountToMultiplyBy)
  77281. {
  77282. if (hasAlphaChannel())
  77283. {
  77284. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), true);
  77285. if (isARGB())
  77286. {
  77287. for (int y = 0; y < destData.height; ++y)
  77288. {
  77289. uint8* p = destData.getLinePointer (y);
  77290. for (int x = 0; x < destData.width; ++x)
  77291. {
  77292. ((PixelARGB*) p)->multiplyAlpha (amountToMultiplyBy);
  77293. p += destData.pixelStride;
  77294. }
  77295. }
  77296. }
  77297. else
  77298. {
  77299. for (int y = 0; y < destData.height; ++y)
  77300. {
  77301. uint8* p = destData.getLinePointer (y);
  77302. for (int x = 0; x < destData.width; ++x)
  77303. {
  77304. *p = (uint8) (*p * amountToMultiplyBy);
  77305. p += destData.pixelStride;
  77306. }
  77307. }
  77308. }
  77309. }
  77310. else
  77311. {
  77312. jassertfalse; // can't do this without an alpha-channel!
  77313. }
  77314. }
  77315. void Image::desaturate()
  77316. {
  77317. if (isARGB() || isRGB())
  77318. {
  77319. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), true);
  77320. if (isARGB())
  77321. {
  77322. for (int y = 0; y < destData.height; ++y)
  77323. {
  77324. uint8* p = destData.getLinePointer (y);
  77325. for (int x = 0; x < destData.width; ++x)
  77326. {
  77327. ((PixelARGB*) p)->desaturate();
  77328. p += destData.pixelStride;
  77329. }
  77330. }
  77331. }
  77332. else
  77333. {
  77334. for (int y = 0; y < destData.height; ++y)
  77335. {
  77336. uint8* p = destData.getLinePointer (y);
  77337. for (int x = 0; x < destData.width; ++x)
  77338. {
  77339. ((PixelRGB*) p)->desaturate();
  77340. p += destData.pixelStride;
  77341. }
  77342. }
  77343. }
  77344. }
  77345. }
  77346. void Image::createSolidAreaMask (RectangleList& result, const float alphaThreshold) const
  77347. {
  77348. if (hasAlphaChannel())
  77349. {
  77350. const uint8 threshold = (uint8) jlimit (0, 255, roundToInt (alphaThreshold * 255.0f));
  77351. SparseSet<int> pixelsOnRow;
  77352. const BitmapData srcData (*this, 0, 0, getWidth(), getHeight());
  77353. for (int y = 0; y < srcData.height; ++y)
  77354. {
  77355. pixelsOnRow.clear();
  77356. const uint8* lineData = srcData.getLinePointer (y);
  77357. if (isARGB())
  77358. {
  77359. for (int x = 0; x < srcData.width; ++x)
  77360. {
  77361. if (((const PixelARGB*) lineData)->getAlpha() >= threshold)
  77362. pixelsOnRow.addRange (Range<int> (x, x + 1));
  77363. lineData += srcData.pixelStride;
  77364. }
  77365. }
  77366. else
  77367. {
  77368. for (int x = 0; x < srcData.width; ++x)
  77369. {
  77370. if (*lineData >= threshold)
  77371. pixelsOnRow.addRange (Range<int> (x, x + 1));
  77372. lineData += srcData.pixelStride;
  77373. }
  77374. }
  77375. for (int i = 0; i < pixelsOnRow.getNumRanges(); ++i)
  77376. {
  77377. const Range<int> range (pixelsOnRow.getRange (i));
  77378. result.add (Rectangle<int> (range.getStart(), y, range.getLength(), 1));
  77379. }
  77380. result.consolidate();
  77381. }
  77382. }
  77383. else
  77384. {
  77385. result.add (0, 0, getWidth(), getHeight());
  77386. }
  77387. }
  77388. void Image::moveImageSection (int dx, int dy,
  77389. int sx, int sy,
  77390. int w, int h)
  77391. {
  77392. if (dx < 0)
  77393. {
  77394. w += dx;
  77395. sx -= dx;
  77396. dx = 0;
  77397. }
  77398. if (dy < 0)
  77399. {
  77400. h += dy;
  77401. sy -= dy;
  77402. dy = 0;
  77403. }
  77404. if (sx < 0)
  77405. {
  77406. w += sx;
  77407. dx -= sx;
  77408. sx = 0;
  77409. }
  77410. if (sy < 0)
  77411. {
  77412. h += sy;
  77413. dy -= sy;
  77414. sy = 0;
  77415. }
  77416. const int minX = jmin (dx, sx);
  77417. const int minY = jmin (dy, sy);
  77418. w = jmin (w, getWidth() - jmax (sx, dx));
  77419. h = jmin (h, getHeight() - jmax (sy, dy));
  77420. if (w > 0 && h > 0)
  77421. {
  77422. const int maxX = jmax (dx, sx) + w;
  77423. const int maxY = jmax (dy, sy) + h;
  77424. const BitmapData destData (*this, minX, minY, maxX - minX, maxY - minY, true);
  77425. uint8* dst = destData.getPixelPointer (dx - minX, dy - minY);
  77426. const uint8* src = destData.getPixelPointer (sx - minX, sy - minY);
  77427. const int lineSize = destData.pixelStride * w;
  77428. if (dy > sy)
  77429. {
  77430. while (--h >= 0)
  77431. {
  77432. const int offset = h * destData.lineStride;
  77433. memmove (dst + offset, src + offset, lineSize);
  77434. }
  77435. }
  77436. else if (dst != src)
  77437. {
  77438. while (--h >= 0)
  77439. {
  77440. memmove (dst, src, lineSize);
  77441. dst += destData.lineStride;
  77442. src += destData.lineStride;
  77443. }
  77444. }
  77445. }
  77446. }
  77447. END_JUCE_NAMESPACE
  77448. /*** End of inlined file: juce_Image.cpp ***/
  77449. /*** Start of inlined file: juce_ImageCache.cpp ***/
  77450. BEGIN_JUCE_NAMESPACE
  77451. class ImageCache::Pimpl : public Timer,
  77452. public DeletedAtShutdown
  77453. {
  77454. public:
  77455. Pimpl()
  77456. : cacheTimeout (5000)
  77457. {
  77458. }
  77459. ~Pimpl()
  77460. {
  77461. clearSingletonInstance();
  77462. }
  77463. const Image getFromHashCode (const int64 hashCode)
  77464. {
  77465. const ScopedLock sl (lock);
  77466. for (int i = images.size(); --i >= 0;)
  77467. {
  77468. Item* const item = images.getUnchecked(i);
  77469. if (item->hashCode == hashCode)
  77470. return item->image;
  77471. }
  77472. return Image::null;
  77473. }
  77474. void addImageToCache (const Image& image, const int64 hashCode)
  77475. {
  77476. if (image.isValid())
  77477. {
  77478. if (! isTimerRunning())
  77479. startTimer (2000);
  77480. Item* const item = new Item();
  77481. item->hashCode = hashCode;
  77482. item->image = image;
  77483. item->lastUseTime = Time::getApproximateMillisecondCounter();
  77484. const ScopedLock sl (lock);
  77485. images.add (item);
  77486. }
  77487. }
  77488. void timerCallback()
  77489. {
  77490. const uint32 now = Time::getApproximateMillisecondCounter();
  77491. const ScopedLock sl (lock);
  77492. for (int i = images.size(); --i >= 0;)
  77493. {
  77494. Item* const item = images.getUnchecked(i);
  77495. if (item->image.getReferenceCount() <= 1)
  77496. {
  77497. if (now > item->lastUseTime + cacheTimeout || now < item->lastUseTime - 1000)
  77498. images.remove (i);
  77499. }
  77500. else
  77501. {
  77502. item->lastUseTime = now; // multiply-referenced, so this image is still in use.
  77503. }
  77504. }
  77505. if (images.size() == 0)
  77506. stopTimer();
  77507. }
  77508. struct Item
  77509. {
  77510. Image image;
  77511. int64 hashCode;
  77512. uint32 lastUseTime;
  77513. };
  77514. int cacheTimeout;
  77515. juce_DeclareSingleton_SingleThreaded_Minimal (ImageCache::Pimpl);
  77516. private:
  77517. OwnedArray<Item> images;
  77518. CriticalSection lock;
  77519. Pimpl (const Pimpl&);
  77520. Pimpl& operator= (const Pimpl&);
  77521. };
  77522. juce_ImplementSingleton_SingleThreaded (ImageCache::Pimpl);
  77523. const Image ImageCache::getFromHashCode (const int64 hashCode)
  77524. {
  77525. if (Pimpl::getInstanceWithoutCreating() != 0)
  77526. return Pimpl::getInstanceWithoutCreating()->getFromHashCode (hashCode);
  77527. return Image::null;
  77528. }
  77529. void ImageCache::addImageToCache (const Image& image, const int64 hashCode)
  77530. {
  77531. Pimpl::getInstance()->addImageToCache (image, hashCode);
  77532. }
  77533. const Image ImageCache::getFromFile (const File& file)
  77534. {
  77535. const int64 hashCode = file.hashCode64();
  77536. Image image (getFromHashCode (hashCode));
  77537. if (image.isNull())
  77538. {
  77539. image = ImageFileFormat::loadFrom (file);
  77540. addImageToCache (image, hashCode);
  77541. }
  77542. return image;
  77543. }
  77544. const Image ImageCache::getFromMemory (const void* imageData, const int dataSize)
  77545. {
  77546. const int64 hashCode = (int64) (pointer_sized_int) imageData;
  77547. Image image (getFromHashCode (hashCode));
  77548. if (image.isNull())
  77549. {
  77550. image = ImageFileFormat::loadFrom (imageData, dataSize);
  77551. addImageToCache (image, hashCode);
  77552. }
  77553. return image;
  77554. }
  77555. void ImageCache::setCacheTimeout (const int millisecs)
  77556. {
  77557. Pimpl::getInstance()->cacheTimeout = millisecs;
  77558. }
  77559. END_JUCE_NAMESPACE
  77560. /*** End of inlined file: juce_ImageCache.cpp ***/
  77561. /*** Start of inlined file: juce_ImageConvolutionKernel.cpp ***/
  77562. BEGIN_JUCE_NAMESPACE
  77563. ImageConvolutionKernel::ImageConvolutionKernel (const int size_)
  77564. : values (size_ * size_),
  77565. size (size_)
  77566. {
  77567. clear();
  77568. }
  77569. ImageConvolutionKernel::~ImageConvolutionKernel()
  77570. {
  77571. }
  77572. float ImageConvolutionKernel::getKernelValue (const int x, const int y) const throw()
  77573. {
  77574. if (((unsigned int) x) < (unsigned int) size
  77575. && ((unsigned int) y) < (unsigned int) size)
  77576. {
  77577. return values [x + y * size];
  77578. }
  77579. else
  77580. {
  77581. jassertfalse;
  77582. return 0;
  77583. }
  77584. }
  77585. void ImageConvolutionKernel::setKernelValue (const int x, const int y, const float value) throw()
  77586. {
  77587. if (((unsigned int) x) < (unsigned int) size
  77588. && ((unsigned int) y) < (unsigned int) size)
  77589. {
  77590. values [x + y * size] = value;
  77591. }
  77592. else
  77593. {
  77594. jassertfalse;
  77595. }
  77596. }
  77597. void ImageConvolutionKernel::clear()
  77598. {
  77599. for (int i = size * size; --i >= 0;)
  77600. values[i] = 0;
  77601. }
  77602. void ImageConvolutionKernel::setOverallSum (const float desiredTotalSum)
  77603. {
  77604. double currentTotal = 0.0;
  77605. for (int i = size * size; --i >= 0;)
  77606. currentTotal += values[i];
  77607. rescaleAllValues ((float) (desiredTotalSum / currentTotal));
  77608. }
  77609. void ImageConvolutionKernel::rescaleAllValues (const float multiplier)
  77610. {
  77611. for (int i = size * size; --i >= 0;)
  77612. values[i] *= multiplier;
  77613. }
  77614. void ImageConvolutionKernel::createGaussianBlur (const float radius)
  77615. {
  77616. const double radiusFactor = -1.0 / (radius * radius * 2);
  77617. const int centre = size >> 1;
  77618. for (int y = size; --y >= 0;)
  77619. {
  77620. for (int x = size; --x >= 0;)
  77621. {
  77622. const int cx = x - centre;
  77623. const int cy = y - centre;
  77624. values [x + y * size] = (float) exp (radiusFactor * (cx * cx + cy * cy));
  77625. }
  77626. }
  77627. setOverallSum (1.0f);
  77628. }
  77629. void ImageConvolutionKernel::applyToImage (Image& destImage,
  77630. const Image& sourceImage,
  77631. const Rectangle<int>& destinationArea) const
  77632. {
  77633. if (sourceImage == destImage)
  77634. {
  77635. destImage.duplicateIfShared();
  77636. }
  77637. else
  77638. {
  77639. if (sourceImage.getWidth() != destImage.getWidth()
  77640. || sourceImage.getHeight() != destImage.getHeight()
  77641. || sourceImage.getFormat() != destImage.getFormat())
  77642. {
  77643. jassertfalse;
  77644. return;
  77645. }
  77646. }
  77647. const Rectangle<int> area (destinationArea.getIntersection (destImage.getBounds()));
  77648. if (area.isEmpty())
  77649. return;
  77650. const int right = area.getRight();
  77651. const int bottom = area.getBottom();
  77652. const Image::BitmapData destData (destImage, area.getX(), area.getY(), area.getWidth(), area.getHeight(), true);
  77653. uint8* line = destData.data;
  77654. const Image::BitmapData srcData (sourceImage, false);
  77655. if (destData.pixelStride == 4)
  77656. {
  77657. for (int y = area.getY(); y < bottom; ++y)
  77658. {
  77659. uint8* dest = line;
  77660. line += destData.lineStride;
  77661. for (int x = area.getX(); x < right; ++x)
  77662. {
  77663. float c1 = 0;
  77664. float c2 = 0;
  77665. float c3 = 0;
  77666. float c4 = 0;
  77667. for (int yy = 0; yy < size; ++yy)
  77668. {
  77669. const int sy = y + yy - (size >> 1);
  77670. if (sy >= srcData.height)
  77671. break;
  77672. if (sy >= 0)
  77673. {
  77674. int sx = x - (size >> 1);
  77675. const uint8* src = srcData.getPixelPointer (sx, sy);
  77676. for (int xx = 0; xx < size; ++xx)
  77677. {
  77678. if (sx >= srcData.width)
  77679. break;
  77680. if (sx >= 0)
  77681. {
  77682. const float kernelMult = values [xx + yy * size];
  77683. c1 += kernelMult * *src++;
  77684. c2 += kernelMult * *src++;
  77685. c3 += kernelMult * *src++;
  77686. c4 += kernelMult * *src++;
  77687. }
  77688. else
  77689. {
  77690. src += 4;
  77691. }
  77692. ++sx;
  77693. }
  77694. }
  77695. }
  77696. *dest++ = (uint8) jmin (0xff, roundToInt (c1));
  77697. *dest++ = (uint8) jmin (0xff, roundToInt (c2));
  77698. *dest++ = (uint8) jmin (0xff, roundToInt (c3));
  77699. *dest++ = (uint8) jmin (0xff, roundToInt (c4));
  77700. }
  77701. }
  77702. }
  77703. else if (destData.pixelStride == 3)
  77704. {
  77705. for (int y = area.getY(); y < bottom; ++y)
  77706. {
  77707. uint8* dest = line;
  77708. line += destData.lineStride;
  77709. for (int x = area.getX(); x < right; ++x)
  77710. {
  77711. float c1 = 0;
  77712. float c2 = 0;
  77713. float c3 = 0;
  77714. for (int yy = 0; yy < size; ++yy)
  77715. {
  77716. const int sy = y + yy - (size >> 1);
  77717. if (sy >= srcData.height)
  77718. break;
  77719. if (sy >= 0)
  77720. {
  77721. int sx = x - (size >> 1);
  77722. const uint8* src = srcData.getPixelPointer (sx, sy);
  77723. for (int xx = 0; xx < size; ++xx)
  77724. {
  77725. if (sx >= srcData.width)
  77726. break;
  77727. if (sx >= 0)
  77728. {
  77729. const float kernelMult = values [xx + yy * size];
  77730. c1 += kernelMult * *src++;
  77731. c2 += kernelMult * *src++;
  77732. c3 += kernelMult * *src++;
  77733. }
  77734. else
  77735. {
  77736. src += 3;
  77737. }
  77738. ++sx;
  77739. }
  77740. }
  77741. }
  77742. *dest++ = (uint8) roundToInt (c1);
  77743. *dest++ = (uint8) roundToInt (c2);
  77744. *dest++ = (uint8) roundToInt (c3);
  77745. }
  77746. }
  77747. }
  77748. }
  77749. END_JUCE_NAMESPACE
  77750. /*** End of inlined file: juce_ImageConvolutionKernel.cpp ***/
  77751. /*** Start of inlined file: juce_ImageFileFormat.cpp ***/
  77752. BEGIN_JUCE_NAMESPACE
  77753. ImageFileFormat* ImageFileFormat::findImageFormatForStream (InputStream& input)
  77754. {
  77755. static PNGImageFormat png;
  77756. static JPEGImageFormat jpg;
  77757. static GIFImageFormat gif;
  77758. ImageFileFormat* formats[4];
  77759. int numFormats = 0;
  77760. formats [numFormats++] = &png;
  77761. formats [numFormats++] = &jpg;
  77762. formats [numFormats++] = &gif;
  77763. const int64 streamPos = input.getPosition();
  77764. for (int i = 0; i < numFormats; ++i)
  77765. {
  77766. const bool found = formats[i]->canUnderstand (input);
  77767. input.setPosition (streamPos);
  77768. if (found)
  77769. return formats[i];
  77770. }
  77771. return 0;
  77772. }
  77773. const Image ImageFileFormat::loadFrom (InputStream& input)
  77774. {
  77775. ImageFileFormat* const format = findImageFormatForStream (input);
  77776. if (format != 0)
  77777. return format->decodeImage (input);
  77778. return Image::null;
  77779. }
  77780. const Image ImageFileFormat::loadFrom (const File& file)
  77781. {
  77782. InputStream* const in = file.createInputStream();
  77783. if (in != 0)
  77784. {
  77785. BufferedInputStream b (in, 8192, true);
  77786. return loadFrom (b);
  77787. }
  77788. return Image::null;
  77789. }
  77790. const Image ImageFileFormat::loadFrom (const void* rawData, const int numBytes)
  77791. {
  77792. if (rawData != 0 && numBytes > 4)
  77793. {
  77794. MemoryInputStream stream (rawData, numBytes, false);
  77795. return loadFrom (stream);
  77796. }
  77797. return Image::null;
  77798. }
  77799. END_JUCE_NAMESPACE
  77800. /*** End of inlined file: juce_ImageFileFormat.cpp ***/
  77801. /*** Start of inlined file: juce_GIFLoader.cpp ***/
  77802. BEGIN_JUCE_NAMESPACE
  77803. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  77804. const Image juce_loadWithCoreImage (InputStream& input);
  77805. #else
  77806. class GIFLoader
  77807. {
  77808. public:
  77809. GIFLoader (InputStream& in)
  77810. : input (in),
  77811. dataBlockIsZero (false),
  77812. fresh (false),
  77813. finished (false)
  77814. {
  77815. currentBit = lastBit = lastByteIndex = 0;
  77816. maxCode = maxCodeSize = codeSize = setCodeSize = 0;
  77817. firstcode = oldcode = 0;
  77818. clearCode = end_code = 0;
  77819. int imageWidth, imageHeight;
  77820. int transparent = -1;
  77821. if (! getSizeFromHeader (imageWidth, imageHeight))
  77822. return;
  77823. if ((imageWidth <= 0) || (imageHeight <= 0))
  77824. return;
  77825. unsigned char buf [16];
  77826. if (in.read (buf, 3) != 3)
  77827. return;
  77828. int numColours = 2 << (buf[0] & 7);
  77829. if ((buf[0] & 0x80) != 0)
  77830. readPalette (numColours);
  77831. for (;;)
  77832. {
  77833. if (input.read (buf, 1) != 1 || buf[0] == ';')
  77834. break;
  77835. if (buf[0] == '!')
  77836. {
  77837. if (input.read (buf, 1) != 1)
  77838. break;
  77839. if (processExtension (buf[0], transparent) < 0)
  77840. break;
  77841. continue;
  77842. }
  77843. if (buf[0] != ',')
  77844. continue;
  77845. if (input.read (buf, 9) != 9)
  77846. break;
  77847. imageWidth = makeWord (buf[4], buf[5]);
  77848. imageHeight = makeWord (buf[6], buf[7]);
  77849. numColours = 2 << (buf[8] & 7);
  77850. if ((buf[8] & 0x80) != 0)
  77851. if (! readPalette (numColours))
  77852. break;
  77853. image = Image ((transparent >= 0) ? Image::ARGB : Image::RGB,
  77854. imageWidth, imageHeight, (transparent >= 0));
  77855. image.getProperties()->set ("originalImageHadAlpha", image.hasAlphaChannel());
  77856. readImage ((buf[8] & 0x40) != 0, transparent);
  77857. break;
  77858. }
  77859. }
  77860. ~GIFLoader() {}
  77861. Image image;
  77862. private:
  77863. InputStream& input;
  77864. uint8 buffer [300];
  77865. uint8 palette [256][4];
  77866. bool dataBlockIsZero, fresh, finished;
  77867. int currentBit, lastBit, lastByteIndex;
  77868. int codeSize, setCodeSize;
  77869. int maxCode, maxCodeSize;
  77870. int firstcode, oldcode;
  77871. int clearCode, end_code;
  77872. enum { maxGifCode = 1 << 12 };
  77873. int table [2] [maxGifCode];
  77874. int stack [2 * maxGifCode];
  77875. int *sp;
  77876. bool getSizeFromHeader (int& w, int& h)
  77877. {
  77878. char b[8];
  77879. if (input.read (b, 6) == 6)
  77880. {
  77881. if ((strncmp ("GIF87a", b, 6) == 0)
  77882. || (strncmp ("GIF89a", b, 6) == 0))
  77883. {
  77884. if (input.read (b, 4) == 4)
  77885. {
  77886. w = makeWord (b[0], b[1]);
  77887. h = makeWord (b[2], b[3]);
  77888. return true;
  77889. }
  77890. }
  77891. }
  77892. return false;
  77893. }
  77894. bool readPalette (const int numCols)
  77895. {
  77896. unsigned char rgb[4];
  77897. for (int i = 0; i < numCols; ++i)
  77898. {
  77899. input.read (rgb, 3);
  77900. palette [i][0] = rgb[0];
  77901. palette [i][1] = rgb[1];
  77902. palette [i][2] = rgb[2];
  77903. palette [i][3] = 0xff;
  77904. }
  77905. return true;
  77906. }
  77907. int readDataBlock (unsigned char* dest)
  77908. {
  77909. unsigned char n;
  77910. if (input.read (&n, 1) == 1)
  77911. {
  77912. dataBlockIsZero = (n == 0);
  77913. if (dataBlockIsZero || (input.read (dest, n) == n))
  77914. return n;
  77915. }
  77916. return -1;
  77917. }
  77918. int processExtension (const int type, int& transparent)
  77919. {
  77920. unsigned char b [300];
  77921. int n = 0;
  77922. if (type == 0xf9)
  77923. {
  77924. n = readDataBlock (b);
  77925. if (n < 0)
  77926. return 1;
  77927. if ((b[0] & 0x1) != 0)
  77928. transparent = b[3];
  77929. }
  77930. do
  77931. {
  77932. n = readDataBlock (b);
  77933. }
  77934. while (n > 0);
  77935. return n;
  77936. }
  77937. int readLZWByte (const bool initialise, const int inputCodeSize)
  77938. {
  77939. int code, incode, i;
  77940. if (initialise)
  77941. {
  77942. setCodeSize = inputCodeSize;
  77943. codeSize = setCodeSize + 1;
  77944. clearCode = 1 << setCodeSize;
  77945. end_code = clearCode + 1;
  77946. maxCodeSize = 2 * clearCode;
  77947. maxCode = clearCode + 2;
  77948. getCode (0, true);
  77949. fresh = true;
  77950. for (i = 0; i < clearCode; ++i)
  77951. {
  77952. table[0][i] = 0;
  77953. table[1][i] = i;
  77954. }
  77955. for (; i < maxGifCode; ++i)
  77956. {
  77957. table[0][i] = 0;
  77958. table[1][i] = 0;
  77959. }
  77960. sp = stack;
  77961. return 0;
  77962. }
  77963. else if (fresh)
  77964. {
  77965. fresh = false;
  77966. do
  77967. {
  77968. firstcode = oldcode
  77969. = getCode (codeSize, false);
  77970. }
  77971. while (firstcode == clearCode);
  77972. return firstcode;
  77973. }
  77974. if (sp > stack)
  77975. return *--sp;
  77976. while ((code = getCode (codeSize, false)) >= 0)
  77977. {
  77978. if (code == clearCode)
  77979. {
  77980. for (i = 0; i < clearCode; ++i)
  77981. {
  77982. table[0][i] = 0;
  77983. table[1][i] = i;
  77984. }
  77985. for (; i < maxGifCode; ++i)
  77986. {
  77987. table[0][i] = 0;
  77988. table[1][i] = 0;
  77989. }
  77990. codeSize = setCodeSize + 1;
  77991. maxCodeSize = 2 * clearCode;
  77992. maxCode = clearCode + 2;
  77993. sp = stack;
  77994. firstcode = oldcode = getCode (codeSize, false);
  77995. return firstcode;
  77996. }
  77997. else if (code == end_code)
  77998. {
  77999. if (dataBlockIsZero)
  78000. return -2;
  78001. unsigned char buf [260];
  78002. int n;
  78003. while ((n = readDataBlock (buf)) > 0)
  78004. {}
  78005. if (n != 0)
  78006. return -2;
  78007. }
  78008. incode = code;
  78009. if (code >= maxCode)
  78010. {
  78011. *sp++ = firstcode;
  78012. code = oldcode;
  78013. }
  78014. while (code >= clearCode)
  78015. {
  78016. *sp++ = table[1][code];
  78017. if (code == table[0][code])
  78018. return -2;
  78019. code = table[0][code];
  78020. }
  78021. *sp++ = firstcode = table[1][code];
  78022. if ((code = maxCode) < maxGifCode)
  78023. {
  78024. table[0][code] = oldcode;
  78025. table[1][code] = firstcode;
  78026. ++maxCode;
  78027. if ((maxCode >= maxCodeSize)
  78028. && (maxCodeSize < maxGifCode))
  78029. {
  78030. maxCodeSize <<= 1;
  78031. ++codeSize;
  78032. }
  78033. }
  78034. oldcode = incode;
  78035. if (sp > stack)
  78036. return *--sp;
  78037. }
  78038. return code;
  78039. }
  78040. int getCode (const int codeSize_, const bool initialise)
  78041. {
  78042. if (initialise)
  78043. {
  78044. currentBit = 0;
  78045. lastBit = 0;
  78046. finished = false;
  78047. return 0;
  78048. }
  78049. if ((currentBit + codeSize_) >= lastBit)
  78050. {
  78051. if (finished)
  78052. return -1;
  78053. buffer[0] = buffer [lastByteIndex - 2];
  78054. buffer[1] = buffer [lastByteIndex - 1];
  78055. const int n = readDataBlock (&buffer[2]);
  78056. if (n == 0)
  78057. finished = true;
  78058. lastByteIndex = 2 + n;
  78059. currentBit = (currentBit - lastBit) + 16;
  78060. lastBit = (2 + n) * 8 ;
  78061. }
  78062. int result = 0;
  78063. int i = currentBit;
  78064. for (int j = 0; j < codeSize_; ++j)
  78065. {
  78066. result |= ((buffer[i >> 3] & (1 << (i & 7))) != 0) << j;
  78067. ++i;
  78068. }
  78069. currentBit += codeSize_;
  78070. return result;
  78071. }
  78072. bool readImage (const int interlace, const int transparent)
  78073. {
  78074. unsigned char c;
  78075. if (input.read (&c, 1) != 1
  78076. || readLZWByte (true, c) < 0)
  78077. return false;
  78078. if (transparent >= 0)
  78079. {
  78080. palette [transparent][0] = 0;
  78081. palette [transparent][1] = 0;
  78082. palette [transparent][2] = 0;
  78083. palette [transparent][3] = 0;
  78084. }
  78085. int index;
  78086. int xpos = 0, ypos = 0, pass = 0;
  78087. const Image::BitmapData destData (image, true);
  78088. uint8* p = destData.data;
  78089. const bool hasAlpha = image.hasAlphaChannel();
  78090. while ((index = readLZWByte (false, c)) >= 0)
  78091. {
  78092. const uint8* const paletteEntry = palette [index];
  78093. if (hasAlpha)
  78094. {
  78095. ((PixelARGB*) p)->setARGB (paletteEntry[3],
  78096. paletteEntry[0],
  78097. paletteEntry[1],
  78098. paletteEntry[2]);
  78099. ((PixelARGB*) p)->premultiply();
  78100. }
  78101. else
  78102. {
  78103. ((PixelRGB*) p)->setARGB (0,
  78104. paletteEntry[0],
  78105. paletteEntry[1],
  78106. paletteEntry[2]);
  78107. }
  78108. p += destData.pixelStride;
  78109. ++xpos;
  78110. if (xpos == destData.width)
  78111. {
  78112. xpos = 0;
  78113. if (interlace)
  78114. {
  78115. switch (pass)
  78116. {
  78117. case 0:
  78118. case 1: ypos += 8; break;
  78119. case 2: ypos += 4; break;
  78120. case 3: ypos += 2; break;
  78121. }
  78122. while (ypos >= destData.height)
  78123. {
  78124. ++pass;
  78125. switch (pass)
  78126. {
  78127. case 1: ypos = 4; break;
  78128. case 2: ypos = 2; break;
  78129. case 3: ypos = 1; break;
  78130. default: return true;
  78131. }
  78132. }
  78133. }
  78134. else
  78135. {
  78136. ++ypos;
  78137. }
  78138. p = destData.getPixelPointer (xpos, ypos);
  78139. }
  78140. if (ypos >= destData.height)
  78141. break;
  78142. }
  78143. return true;
  78144. }
  78145. static inline int makeWord (const uint8 a, const uint8 b) { return (b << 8) | a; }
  78146. GIFLoader (const GIFLoader&);
  78147. GIFLoader& operator= (const GIFLoader&);
  78148. };
  78149. #endif
  78150. GIFImageFormat::GIFImageFormat() {}
  78151. GIFImageFormat::~GIFImageFormat() {}
  78152. const String GIFImageFormat::getFormatName() { return "GIF"; }
  78153. bool GIFImageFormat::canUnderstand (InputStream& in)
  78154. {
  78155. char header [4];
  78156. return (in.read (header, sizeof (header)) == sizeof (header))
  78157. && header[0] == 'G'
  78158. && header[1] == 'I'
  78159. && header[2] == 'F';
  78160. }
  78161. const Image GIFImageFormat::decodeImage (InputStream& in)
  78162. {
  78163. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  78164. return juce_loadWithCoreImage (in);
  78165. #else
  78166. const ScopedPointer <GIFLoader> loader (new GIFLoader (in));
  78167. return loader->image;
  78168. #endif
  78169. }
  78170. bool GIFImageFormat::writeImageToStream (const Image& /*sourceImage*/, OutputStream& /*destStream*/)
  78171. {
  78172. jassertfalse; // writing isn't implemented for GIFs!
  78173. return false;
  78174. }
  78175. END_JUCE_NAMESPACE
  78176. /*** End of inlined file: juce_GIFLoader.cpp ***/
  78177. #endif
  78178. //==============================================================================
  78179. // some files include lots of library code, so leave them to the end to avoid cluttering
  78180. // up the build for the clean files.
  78181. #if JUCE_BUILD_CORE
  78182. /*** Start of inlined file: juce_GZIPCompressorOutputStream.cpp ***/
  78183. namespace zlibNamespace
  78184. {
  78185. #if JUCE_INCLUDE_ZLIB_CODE
  78186. #undef OS_CODE
  78187. #undef fdopen
  78188. /*** Start of inlined file: zlib.h ***/
  78189. #ifndef ZLIB_H
  78190. #define ZLIB_H
  78191. /*** Start of inlined file: zconf.h ***/
  78192. /* @(#) $Id: zconf.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  78193. #ifndef ZCONF_H
  78194. #define ZCONF_H
  78195. // *** Just a few hacks here to make it compile nicely with Juce..
  78196. #define Z_PREFIX 1
  78197. #undef __MACTYPES__
  78198. #ifdef _MSC_VER
  78199. #pragma warning (disable : 4131 4127 4244 4267)
  78200. #endif
  78201. /*
  78202. * If you *really* need a unique prefix for all types and library functions,
  78203. * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
  78204. */
  78205. #ifdef Z_PREFIX
  78206. # define deflateInit_ z_deflateInit_
  78207. # define deflate z_deflate
  78208. # define deflateEnd z_deflateEnd
  78209. # define inflateInit_ z_inflateInit_
  78210. # define inflate z_inflate
  78211. # define inflateEnd z_inflateEnd
  78212. # define inflatePrime z_inflatePrime
  78213. # define inflateGetHeader z_inflateGetHeader
  78214. # define adler32_combine z_adler32_combine
  78215. # define crc32_combine z_crc32_combine
  78216. # define deflateInit2_ z_deflateInit2_
  78217. # define deflateSetDictionary z_deflateSetDictionary
  78218. # define deflateCopy z_deflateCopy
  78219. # define deflateReset z_deflateReset
  78220. # define deflateParams z_deflateParams
  78221. # define deflateBound z_deflateBound
  78222. # define deflatePrime z_deflatePrime
  78223. # define inflateInit2_ z_inflateInit2_
  78224. # define inflateSetDictionary z_inflateSetDictionary
  78225. # define inflateSync z_inflateSync
  78226. # define inflateSyncPoint z_inflateSyncPoint
  78227. # define inflateCopy z_inflateCopy
  78228. # define inflateReset z_inflateReset
  78229. # define inflateBack z_inflateBack
  78230. # define inflateBackEnd z_inflateBackEnd
  78231. # define compress z_compress
  78232. # define compress2 z_compress2
  78233. # define compressBound z_compressBound
  78234. # define uncompress z_uncompress
  78235. # define adler32 z_adler32
  78236. # define crc32 z_crc32
  78237. # define get_crc_table z_get_crc_table
  78238. # define zError z_zError
  78239. # define alloc_func z_alloc_func
  78240. # define free_func z_free_func
  78241. # define in_func z_in_func
  78242. # define out_func z_out_func
  78243. # define Byte z_Byte
  78244. # define uInt z_uInt
  78245. # define uLong z_uLong
  78246. # define Bytef z_Bytef
  78247. # define charf z_charf
  78248. # define intf z_intf
  78249. # define uIntf z_uIntf
  78250. # define uLongf z_uLongf
  78251. # define voidpf z_voidpf
  78252. # define voidp z_voidp
  78253. #endif
  78254. #if defined(__MSDOS__) && !defined(MSDOS)
  78255. # define MSDOS
  78256. #endif
  78257. #if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)
  78258. # define OS2
  78259. #endif
  78260. #if defined(_WINDOWS) && !defined(WINDOWS)
  78261. # define WINDOWS
  78262. #endif
  78263. #if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
  78264. # ifndef WIN32
  78265. # define WIN32
  78266. # endif
  78267. #endif
  78268. #if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
  78269. # if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
  78270. # ifndef SYS16BIT
  78271. # define SYS16BIT
  78272. # endif
  78273. # endif
  78274. #endif
  78275. /*
  78276. * Compile with -DMAXSEG_64K if the alloc function cannot allocate more
  78277. * than 64k bytes at a time (needed on systems with 16-bit int).
  78278. */
  78279. #ifdef SYS16BIT
  78280. # define MAXSEG_64K
  78281. #endif
  78282. #ifdef MSDOS
  78283. # define UNALIGNED_OK
  78284. #endif
  78285. #ifdef __STDC_VERSION__
  78286. # ifndef STDC
  78287. # define STDC
  78288. # endif
  78289. # if __STDC_VERSION__ >= 199901L
  78290. # ifndef STDC99
  78291. # define STDC99
  78292. # endif
  78293. # endif
  78294. #endif
  78295. #if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))
  78296. # define STDC
  78297. #endif
  78298. #if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))
  78299. # define STDC
  78300. #endif
  78301. #if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))
  78302. # define STDC
  78303. #endif
  78304. #if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))
  78305. # define STDC
  78306. #endif
  78307. #if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */
  78308. # define STDC
  78309. #endif
  78310. #ifndef STDC
  78311. # ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
  78312. # define const /* note: need a more gentle solution here */
  78313. # endif
  78314. #endif
  78315. /* Some Mac compilers merge all .h files incorrectly: */
  78316. #if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__)
  78317. # define NO_DUMMY_DECL
  78318. #endif
  78319. /* Maximum value for memLevel in deflateInit2 */
  78320. #ifndef MAX_MEM_LEVEL
  78321. # ifdef MAXSEG_64K
  78322. # define MAX_MEM_LEVEL 8
  78323. # else
  78324. # define MAX_MEM_LEVEL 9
  78325. # endif
  78326. #endif
  78327. /* Maximum value for windowBits in deflateInit2 and inflateInit2.
  78328. * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
  78329. * created by gzip. (Files created by minigzip can still be extracted by
  78330. * gzip.)
  78331. */
  78332. #ifndef MAX_WBITS
  78333. # define MAX_WBITS 15 /* 32K LZ77 window */
  78334. #endif
  78335. /* The memory requirements for deflate are (in bytes):
  78336. (1 << (windowBits+2)) + (1 << (memLevel+9))
  78337. that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values)
  78338. plus a few kilobytes for small objects. For example, if you want to reduce
  78339. the default memory requirements from 256K to 128K, compile with
  78340. make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
  78341. Of course this will generally degrade compression (there's no free lunch).
  78342. The memory requirements for inflate are (in bytes) 1 << windowBits
  78343. that is, 32K for windowBits=15 (default value) plus a few kilobytes
  78344. for small objects.
  78345. */
  78346. /* Type declarations */
  78347. #ifndef OF /* function prototypes */
  78348. # ifdef STDC
  78349. # define OF(args) args
  78350. # else
  78351. # define OF(args) ()
  78352. # endif
  78353. #endif
  78354. /* The following definitions for FAR are needed only for MSDOS mixed
  78355. * model programming (small or medium model with some far allocations).
  78356. * This was tested only with MSC; for other MSDOS compilers you may have
  78357. * to define NO_MEMCPY in zutil.h. If you don't need the mixed model,
  78358. * just define FAR to be empty.
  78359. */
  78360. #ifdef SYS16BIT
  78361. # if defined(M_I86SM) || defined(M_I86MM)
  78362. /* MSC small or medium model */
  78363. # define SMALL_MEDIUM
  78364. # ifdef _MSC_VER
  78365. # define FAR _far
  78366. # else
  78367. # define FAR far
  78368. # endif
  78369. # endif
  78370. # if (defined(__SMALL__) || defined(__MEDIUM__))
  78371. /* Turbo C small or medium model */
  78372. # define SMALL_MEDIUM
  78373. # ifdef __BORLANDC__
  78374. # define FAR _far
  78375. # else
  78376. # define FAR far
  78377. # endif
  78378. # endif
  78379. #endif
  78380. #if defined(WINDOWS) || defined(WIN32)
  78381. /* If building or using zlib as a DLL, define ZLIB_DLL.
  78382. * This is not mandatory, but it offers a little performance increase.
  78383. */
  78384. # ifdef ZLIB_DLL
  78385. # if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))
  78386. # ifdef ZLIB_INTERNAL
  78387. # define ZEXTERN extern __declspec(dllexport)
  78388. # else
  78389. # define ZEXTERN extern __declspec(dllimport)
  78390. # endif
  78391. # endif
  78392. # endif /* ZLIB_DLL */
  78393. /* If building or using zlib with the WINAPI/WINAPIV calling convention,
  78394. * define ZLIB_WINAPI.
  78395. * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.
  78396. */
  78397. # ifdef ZLIB_WINAPI
  78398. # ifdef FAR
  78399. # undef FAR
  78400. # endif
  78401. # include <windows.h>
  78402. /* No need for _export, use ZLIB.DEF instead. */
  78403. /* For complete Windows compatibility, use WINAPI, not __stdcall. */
  78404. # define ZEXPORT WINAPI
  78405. # ifdef WIN32
  78406. # define ZEXPORTVA WINAPIV
  78407. # else
  78408. # define ZEXPORTVA FAR CDECL
  78409. # endif
  78410. # endif
  78411. #endif
  78412. #if defined (__BEOS__)
  78413. # ifdef ZLIB_DLL
  78414. # ifdef ZLIB_INTERNAL
  78415. # define ZEXPORT __declspec(dllexport)
  78416. # define ZEXPORTVA __declspec(dllexport)
  78417. # else
  78418. # define ZEXPORT __declspec(dllimport)
  78419. # define ZEXPORTVA __declspec(dllimport)
  78420. # endif
  78421. # endif
  78422. #endif
  78423. #ifndef ZEXTERN
  78424. # define ZEXTERN extern
  78425. #endif
  78426. #ifndef ZEXPORT
  78427. # define ZEXPORT
  78428. #endif
  78429. #ifndef ZEXPORTVA
  78430. # define ZEXPORTVA
  78431. #endif
  78432. #ifndef FAR
  78433. # define FAR
  78434. #endif
  78435. #if !defined(__MACTYPES__)
  78436. typedef unsigned char Byte; /* 8 bits */
  78437. #endif
  78438. typedef unsigned int uInt; /* 16 bits or more */
  78439. typedef unsigned long uLong; /* 32 bits or more */
  78440. #ifdef SMALL_MEDIUM
  78441. /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
  78442. # define Bytef Byte FAR
  78443. #else
  78444. typedef Byte FAR Bytef;
  78445. #endif
  78446. typedef char FAR charf;
  78447. typedef int FAR intf;
  78448. typedef uInt FAR uIntf;
  78449. typedef uLong FAR uLongf;
  78450. #ifdef STDC
  78451. typedef void const *voidpc;
  78452. typedef void FAR *voidpf;
  78453. typedef void *voidp;
  78454. #else
  78455. typedef Byte const *voidpc;
  78456. typedef Byte FAR *voidpf;
  78457. typedef Byte *voidp;
  78458. #endif
  78459. #if 0 /* HAVE_UNISTD_H -- this line is updated by ./configure */
  78460. # include <sys/types.h> /* for off_t */
  78461. # include <unistd.h> /* for SEEK_* and off_t */
  78462. # ifdef VMS
  78463. # include <unixio.h> /* for off_t */
  78464. # endif
  78465. # define z_off_t off_t
  78466. #endif
  78467. #ifndef SEEK_SET
  78468. # define SEEK_SET 0 /* Seek from beginning of file. */
  78469. # define SEEK_CUR 1 /* Seek from current position. */
  78470. # define SEEK_END 2 /* Set file pointer to EOF plus "offset" */
  78471. #endif
  78472. #ifndef z_off_t
  78473. # define z_off_t long
  78474. #endif
  78475. #if defined(__OS400__)
  78476. # define NO_vsnprintf
  78477. #endif
  78478. #if defined(__MVS__)
  78479. # define NO_vsnprintf
  78480. # ifdef FAR
  78481. # undef FAR
  78482. # endif
  78483. #endif
  78484. /* MVS linker does not support external names larger than 8 bytes */
  78485. #if defined(__MVS__)
  78486. # pragma map(deflateInit_,"DEIN")
  78487. # pragma map(deflateInit2_,"DEIN2")
  78488. # pragma map(deflateEnd,"DEEND")
  78489. # pragma map(deflateBound,"DEBND")
  78490. # pragma map(inflateInit_,"ININ")
  78491. # pragma map(inflateInit2_,"ININ2")
  78492. # pragma map(inflateEnd,"INEND")
  78493. # pragma map(inflateSync,"INSY")
  78494. # pragma map(inflateSetDictionary,"INSEDI")
  78495. # pragma map(compressBound,"CMBND")
  78496. # pragma map(inflate_table,"INTABL")
  78497. # pragma map(inflate_fast,"INFA")
  78498. # pragma map(inflate_copyright,"INCOPY")
  78499. #endif
  78500. #endif /* ZCONF_H */
  78501. /*** End of inlined file: zconf.h ***/
  78502. #ifdef __cplusplus
  78503. //extern "C" {
  78504. #endif
  78505. #define ZLIB_VERSION "1.2.3"
  78506. #define ZLIB_VERNUM 0x1230
  78507. /*
  78508. The 'zlib' compression library provides in-memory compression and
  78509. decompression functions, including integrity checks of the uncompressed
  78510. data. This version of the library supports only one compression method
  78511. (deflation) but other algorithms will be added later and will have the same
  78512. stream interface.
  78513. Compression can be done in a single step if the buffers are large
  78514. enough (for example if an input file is mmap'ed), or can be done by
  78515. repeated calls of the compression function. In the latter case, the
  78516. application must provide more input and/or consume the output
  78517. (providing more output space) before each call.
  78518. The compressed data format used by default by the in-memory functions is
  78519. the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped
  78520. around a deflate stream, which is itself documented in RFC 1951.
  78521. The library also supports reading and writing files in gzip (.gz) format
  78522. with an interface similar to that of stdio using the functions that start
  78523. with "gz". The gzip format is different from the zlib format. gzip is a
  78524. gzip wrapper, documented in RFC 1952, wrapped around a deflate stream.
  78525. This library can optionally read and write gzip streams in memory as well.
  78526. The zlib format was designed to be compact and fast for use in memory
  78527. and on communications channels. The gzip format was designed for single-
  78528. file compression on file systems, has a larger header than zlib to maintain
  78529. directory information, and uses a different, slower check method than zlib.
  78530. The library does not install any signal handler. The decoder checks
  78531. the consistency of the compressed data, so the library should never
  78532. crash even in case of corrupted input.
  78533. */
  78534. typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size));
  78535. typedef void (*free_func) OF((voidpf opaque, voidpf address));
  78536. struct internal_state;
  78537. typedef struct z_stream_s {
  78538. Bytef *next_in; /* next input byte */
  78539. uInt avail_in; /* number of bytes available at next_in */
  78540. uLong total_in; /* total nb of input bytes read so far */
  78541. Bytef *next_out; /* next output byte should be put there */
  78542. uInt avail_out; /* remaining free space at next_out */
  78543. uLong total_out; /* total nb of bytes output so far */
  78544. char *msg; /* last error message, NULL if no error */
  78545. struct internal_state FAR *state; /* not visible by applications */
  78546. alloc_func zalloc; /* used to allocate the internal state */
  78547. free_func zfree; /* used to free the internal state */
  78548. voidpf opaque; /* private data object passed to zalloc and zfree */
  78549. int data_type; /* best guess about the data type: binary or text */
  78550. uLong adler; /* adler32 value of the uncompressed data */
  78551. uLong reserved; /* reserved for future use */
  78552. } z_stream;
  78553. typedef z_stream FAR *z_streamp;
  78554. /*
  78555. gzip header information passed to and from zlib routines. See RFC 1952
  78556. for more details on the meanings of these fields.
  78557. */
  78558. typedef struct gz_header_s {
  78559. int text; /* true if compressed data believed to be text */
  78560. uLong time; /* modification time */
  78561. int xflags; /* extra flags (not used when writing a gzip file) */
  78562. int os; /* operating system */
  78563. Bytef *extra; /* pointer to extra field or Z_NULL if none */
  78564. uInt extra_len; /* extra field length (valid if extra != Z_NULL) */
  78565. uInt extra_max; /* space at extra (only when reading header) */
  78566. Bytef *name; /* pointer to zero-terminated file name or Z_NULL */
  78567. uInt name_max; /* space at name (only when reading header) */
  78568. Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */
  78569. uInt comm_max; /* space at comment (only when reading header) */
  78570. int hcrc; /* true if there was or will be a header crc */
  78571. int done; /* true when done reading gzip header (not used
  78572. when writing a gzip file) */
  78573. } gz_header;
  78574. typedef gz_header FAR *gz_headerp;
  78575. /*
  78576. The application must update next_in and avail_in when avail_in has
  78577. dropped to zero. It must update next_out and avail_out when avail_out
  78578. has dropped to zero. The application must initialize zalloc, zfree and
  78579. opaque before calling the init function. All other fields are set by the
  78580. compression library and must not be updated by the application.
  78581. The opaque value provided by the application will be passed as the first
  78582. parameter for calls of zalloc and zfree. This can be useful for custom
  78583. memory management. The compression library attaches no meaning to the
  78584. opaque value.
  78585. zalloc must return Z_NULL if there is not enough memory for the object.
  78586. If zlib is used in a multi-threaded application, zalloc and zfree must be
  78587. thread safe.
  78588. On 16-bit systems, the functions zalloc and zfree must be able to allocate
  78589. exactly 65536 bytes, but will not be required to allocate more than this
  78590. if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS,
  78591. pointers returned by zalloc for objects of exactly 65536 bytes *must*
  78592. have their offset normalized to zero. The default allocation function
  78593. provided by this library ensures this (see zutil.c). To reduce memory
  78594. requirements and avoid any allocation of 64K objects, at the expense of
  78595. compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h).
  78596. The fields total_in and total_out can be used for statistics or
  78597. progress reports. After compression, total_in holds the total size of
  78598. the uncompressed data and may be saved for use in the decompressor
  78599. (particularly if the decompressor wants to decompress everything in
  78600. a single step).
  78601. */
  78602. /* constants */
  78603. #define Z_NO_FLUSH 0
  78604. #define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */
  78605. #define Z_SYNC_FLUSH 2
  78606. #define Z_FULL_FLUSH 3
  78607. #define Z_FINISH 4
  78608. #define Z_BLOCK 5
  78609. /* Allowed flush values; see deflate() and inflate() below for details */
  78610. #define Z_OK 0
  78611. #define Z_STREAM_END 1
  78612. #define Z_NEED_DICT 2
  78613. #define Z_ERRNO (-1)
  78614. #define Z_STREAM_ERROR (-2)
  78615. #define Z_DATA_ERROR (-3)
  78616. #define Z_MEM_ERROR (-4)
  78617. #define Z_BUF_ERROR (-5)
  78618. #define Z_VERSION_ERROR (-6)
  78619. /* Return codes for the compression/decompression functions. Negative
  78620. * values are errors, positive values are used for special but normal events.
  78621. */
  78622. #define Z_NO_COMPRESSION 0
  78623. #define Z_BEST_SPEED 1
  78624. #define Z_BEST_COMPRESSION 9
  78625. #define Z_DEFAULT_COMPRESSION (-1)
  78626. /* compression levels */
  78627. #define Z_FILTERED 1
  78628. #define Z_HUFFMAN_ONLY 2
  78629. #define Z_RLE 3
  78630. #define Z_FIXED 4
  78631. #define Z_DEFAULT_STRATEGY 0
  78632. /* compression strategy; see deflateInit2() below for details */
  78633. #define Z_BINARY 0
  78634. #define Z_TEXT 1
  78635. #define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */
  78636. #define Z_UNKNOWN 2
  78637. /* Possible values of the data_type field (though see inflate()) */
  78638. #define Z_DEFLATED 8
  78639. /* The deflate compression method (the only one supported in this version) */
  78640. #define Z_NULL 0 /* for initializing zalloc, zfree, opaque */
  78641. #define zlib_version zlibVersion()
  78642. /* for compatibility with versions < 1.0.2 */
  78643. /* basic functions */
  78644. //ZEXTERN const char * ZEXPORT zlibVersion OF((void));
  78645. /* The application can compare zlibVersion and ZLIB_VERSION for consistency.
  78646. If the first character differs, the library code actually used is
  78647. not compatible with the zlib.h header file used by the application.
  78648. This check is automatically made by deflateInit and inflateInit.
  78649. */
  78650. /*
  78651. ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level));
  78652. Initializes the internal stream state for compression. The fields
  78653. zalloc, zfree and opaque must be initialized before by the caller.
  78654. If zalloc and zfree are set to Z_NULL, deflateInit updates them to
  78655. use default allocation functions.
  78656. The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
  78657. 1 gives best speed, 9 gives best compression, 0 gives no compression at
  78658. all (the input data is simply copied a block at a time).
  78659. Z_DEFAULT_COMPRESSION requests a default compromise between speed and
  78660. compression (currently equivalent to level 6).
  78661. deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not
  78662. enough memory, Z_STREAM_ERROR if level is not a valid compression level,
  78663. Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
  78664. with the version assumed by the caller (ZLIB_VERSION).
  78665. msg is set to null if there is no error message. deflateInit does not
  78666. perform any compression: this will be done by deflate().
  78667. */
  78668. ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));
  78669. /*
  78670. deflate compresses as much data as possible, and stops when the input
  78671. buffer becomes empty or the output buffer becomes full. It may introduce some
  78672. output latency (reading input without producing any output) except when
  78673. forced to flush.
  78674. The detailed semantics are as follows. deflate performs one or both of the
  78675. following actions:
  78676. - Compress more input starting at next_in and update next_in and avail_in
  78677. accordingly. If not all input can be processed (because there is not
  78678. enough room in the output buffer), next_in and avail_in are updated and
  78679. processing will resume at this point for the next call of deflate().
  78680. - Provide more output starting at next_out and update next_out and avail_out
  78681. accordingly. This action is forced if the parameter flush is non zero.
  78682. Forcing flush frequently degrades the compression ratio, so this parameter
  78683. should be set only when necessary (in interactive applications).
  78684. Some output may be provided even if flush is not set.
  78685. Before the call of deflate(), the application should ensure that at least
  78686. one of the actions is possible, by providing more input and/or consuming
  78687. more output, and updating avail_in or avail_out accordingly; avail_out
  78688. should never be zero before the call. The application can consume the
  78689. compressed output when it wants, for example when the output buffer is full
  78690. (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK
  78691. and with zero avail_out, it must be called again after making room in the
  78692. output buffer because there might be more output pending.
  78693. Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to
  78694. decide how much data to accumualte before producing output, in order to
  78695. maximize compression.
  78696. If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
  78697. flushed to the output buffer and the output is aligned on a byte boundary, so
  78698. that the decompressor can get all input data available so far. (In particular
  78699. avail_in is zero after the call if enough output space has been provided
  78700. before the call.) Flushing may degrade compression for some compression
  78701. algorithms and so it should be used only when necessary.
  78702. If flush is set to Z_FULL_FLUSH, all output is flushed as with
  78703. Z_SYNC_FLUSH, and the compression state is reset so that decompression can
  78704. restart from this point if previous compressed data has been damaged or if
  78705. random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
  78706. compression.
  78707. If deflate returns with avail_out == 0, this function must be called again
  78708. with the same value of the flush parameter and more output space (updated
  78709. avail_out), until the flush is complete (deflate returns with non-zero
  78710. avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that
  78711. avail_out is greater than six to avoid repeated flush markers due to
  78712. avail_out == 0 on return.
  78713. If the parameter flush is set to Z_FINISH, pending input is processed,
  78714. pending output is flushed and deflate returns with Z_STREAM_END if there
  78715. was enough output space; if deflate returns with Z_OK, this function must be
  78716. called again with Z_FINISH and more output space (updated avail_out) but no
  78717. more input data, until it returns with Z_STREAM_END or an error. After
  78718. deflate has returned Z_STREAM_END, the only possible operations on the
  78719. stream are deflateReset or deflateEnd.
  78720. Z_FINISH can be used immediately after deflateInit if all the compression
  78721. is to be done in a single step. In this case, avail_out must be at least
  78722. the value returned by deflateBound (see below). If deflate does not return
  78723. Z_STREAM_END, then it must be called again as described above.
  78724. deflate() sets strm->adler to the adler32 checksum of all input read
  78725. so far (that is, total_in bytes).
  78726. deflate() may update strm->data_type if it can make a good guess about
  78727. the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered
  78728. binary. This field is only for information purposes and does not affect
  78729. the compression algorithm in any manner.
  78730. deflate() returns Z_OK if some progress has been made (more input
  78731. processed or more output produced), Z_STREAM_END if all input has been
  78732. consumed and all output has been produced (only when flush is set to
  78733. Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
  78734. if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible
  78735. (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not
  78736. fatal, and deflate() can be called again with more input and more output
  78737. space to continue compressing.
  78738. */
  78739. ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm));
  78740. /*
  78741. All dynamically allocated data structures for this stream are freed.
  78742. This function discards any unprocessed input and does not flush any
  78743. pending output.
  78744. deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
  78745. stream state was inconsistent, Z_DATA_ERROR if the stream was freed
  78746. prematurely (some input or output was discarded). In the error case,
  78747. msg may be set but then points to a static string (which must not be
  78748. deallocated).
  78749. */
  78750. /*
  78751. ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm));
  78752. Initializes the internal stream state for decompression. The fields
  78753. next_in, avail_in, zalloc, zfree and opaque must be initialized before by
  78754. the caller. If next_in is not Z_NULL and avail_in is large enough (the exact
  78755. value depends on the compression method), inflateInit determines the
  78756. compression method from the zlib header and allocates all data structures
  78757. accordingly; otherwise the allocation will be deferred to the first call of
  78758. inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to
  78759. use default allocation functions.
  78760. inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78761. memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
  78762. version assumed by the caller. msg is set to null if there is no error
  78763. message. inflateInit does not perform any decompression apart from reading
  78764. the zlib header if present: this will be done by inflate(). (So next_in and
  78765. avail_in may be modified, but next_out and avail_out are unchanged.)
  78766. */
  78767. ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush));
  78768. /*
  78769. inflate decompresses as much data as possible, and stops when the input
  78770. buffer becomes empty or the output buffer becomes full. It may introduce
  78771. some output latency (reading input without producing any output) except when
  78772. forced to flush.
  78773. The detailed semantics are as follows. inflate performs one or both of the
  78774. following actions:
  78775. - Decompress more input starting at next_in and update next_in and avail_in
  78776. accordingly. If not all input can be processed (because there is not
  78777. enough room in the output buffer), next_in is updated and processing
  78778. will resume at this point for the next call of inflate().
  78779. - Provide more output starting at next_out and update next_out and avail_out
  78780. accordingly. inflate() provides as much output as possible, until there
  78781. is no more input data or no more space in the output buffer (see below
  78782. about the flush parameter).
  78783. Before the call of inflate(), the application should ensure that at least
  78784. one of the actions is possible, by providing more input and/or consuming
  78785. more output, and updating the next_* and avail_* values accordingly.
  78786. The application can consume the uncompressed output when it wants, for
  78787. example when the output buffer is full (avail_out == 0), or after each
  78788. call of inflate(). If inflate returns Z_OK and with zero avail_out, it
  78789. must be called again after making room in the output buffer because there
  78790. might be more output pending.
  78791. The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH,
  78792. Z_FINISH, or Z_BLOCK. Z_SYNC_FLUSH requests that inflate() flush as much
  78793. output as possible to the output buffer. Z_BLOCK requests that inflate() stop
  78794. if and when it gets to the next deflate block boundary. When decoding the
  78795. zlib or gzip format, this will cause inflate() to return immediately after
  78796. the header and before the first block. When doing a raw inflate, inflate()
  78797. will go ahead and process the first block, and will return when it gets to
  78798. the end of that block, or when it runs out of data.
  78799. The Z_BLOCK option assists in appending to or combining deflate streams.
  78800. Also to assist in this, on return inflate() will set strm->data_type to the
  78801. number of unused bits in the last byte taken from strm->next_in, plus 64
  78802. if inflate() is currently decoding the last block in the deflate stream,
  78803. plus 128 if inflate() returned immediately after decoding an end-of-block
  78804. code or decoding the complete header up to just before the first byte of the
  78805. deflate stream. The end-of-block will not be indicated until all of the
  78806. uncompressed data from that block has been written to strm->next_out. The
  78807. number of unused bits may in general be greater than seven, except when
  78808. bit 7 of data_type is set, in which case the number of unused bits will be
  78809. less than eight.
  78810. inflate() should normally be called until it returns Z_STREAM_END or an
  78811. error. However if all decompression is to be performed in a single step
  78812. (a single call of inflate), the parameter flush should be set to
  78813. Z_FINISH. In this case all pending input is processed and all pending
  78814. output is flushed; avail_out must be large enough to hold all the
  78815. uncompressed data. (The size of the uncompressed data may have been saved
  78816. by the compressor for this purpose.) The next operation on this stream must
  78817. be inflateEnd to deallocate the decompression state. The use of Z_FINISH
  78818. is never required, but can be used to inform inflate that a faster approach
  78819. may be used for the single inflate() call.
  78820. In this implementation, inflate() always flushes as much output as
  78821. possible to the output buffer, and always uses the faster approach on the
  78822. first call. So the only effect of the flush parameter in this implementation
  78823. is on the return value of inflate(), as noted below, or when it returns early
  78824. because Z_BLOCK is used.
  78825. If a preset dictionary is needed after this call (see inflateSetDictionary
  78826. below), inflate sets strm->adler to the adler32 checksum of the dictionary
  78827. chosen by the compressor and returns Z_NEED_DICT; otherwise it sets
  78828. strm->adler to the adler32 checksum of all output produced so far (that is,
  78829. total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described
  78830. below. At the end of the stream, inflate() checks that its computed adler32
  78831. checksum is equal to that saved by the compressor and returns Z_STREAM_END
  78832. only if the checksum is correct.
  78833. inflate() will decompress and check either zlib-wrapped or gzip-wrapped
  78834. deflate data. The header type is detected automatically. Any information
  78835. contained in the gzip header is not retained, so applications that need that
  78836. information should instead use raw inflate, see inflateInit2() below, or
  78837. inflateBack() and perform their own processing of the gzip header and
  78838. trailer.
  78839. inflate() returns Z_OK if some progress has been made (more input processed
  78840. or more output produced), Z_STREAM_END if the end of the compressed data has
  78841. been reached and all uncompressed output has been produced, Z_NEED_DICT if a
  78842. preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
  78843. corrupted (input stream not conforming to the zlib format or incorrect check
  78844. value), Z_STREAM_ERROR if the stream structure was inconsistent (for example
  78845. if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory,
  78846. Z_BUF_ERROR if no progress is possible or if there was not enough room in the
  78847. output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and
  78848. inflate() can be called again with more input and more output space to
  78849. continue decompressing. If Z_DATA_ERROR is returned, the application may then
  78850. call inflateSync() to look for a good compression block if a partial recovery
  78851. of the data is desired.
  78852. */
  78853. ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm));
  78854. /*
  78855. All dynamically allocated data structures for this stream are freed.
  78856. This function discards any unprocessed input and does not flush any
  78857. pending output.
  78858. inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state
  78859. was inconsistent. In the error case, msg may be set but then points to a
  78860. static string (which must not be deallocated).
  78861. */
  78862. /* Advanced functions */
  78863. /*
  78864. The following functions are needed only in some special applications.
  78865. */
  78866. /*
  78867. ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm,
  78868. int level,
  78869. int method,
  78870. int windowBits,
  78871. int memLevel,
  78872. int strategy));
  78873. This is another version of deflateInit with more compression options. The
  78874. fields next_in, zalloc, zfree and opaque must be initialized before by
  78875. the caller.
  78876. The method parameter is the compression method. It must be Z_DEFLATED in
  78877. this version of the library.
  78878. The windowBits parameter is the base two logarithm of the window size
  78879. (the size of the history buffer). It should be in the range 8..15 for this
  78880. version of the library. Larger values of this parameter result in better
  78881. compression at the expense of memory usage. The default value is 15 if
  78882. deflateInit is used instead.
  78883. windowBits can also be -8..-15 for raw deflate. In this case, -windowBits
  78884. determines the window size. deflate() will then generate raw deflate data
  78885. with no zlib header or trailer, and will not compute an adler32 check value.
  78886. windowBits can also be greater than 15 for optional gzip encoding. Add
  78887. 16 to windowBits to write a simple gzip header and trailer around the
  78888. compressed data instead of a zlib wrapper. The gzip header will have no
  78889. file name, no extra data, no comment, no modification time (set to zero),
  78890. no header crc, and the operating system will be set to 255 (unknown). If a
  78891. gzip stream is being written, strm->adler is a crc32 instead of an adler32.
  78892. The memLevel parameter specifies how much memory should be allocated
  78893. for the internal compression state. memLevel=1 uses minimum memory but
  78894. is slow and reduces compression ratio; memLevel=9 uses maximum memory
  78895. for optimal speed. The default value is 8. See zconf.h for total memory
  78896. usage as a function of windowBits and memLevel.
  78897. The strategy parameter is used to tune the compression algorithm. Use the
  78898. value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
  78899. filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no
  78900. string match), or Z_RLE to limit match distances to one (run-length
  78901. encoding). Filtered data consists mostly of small values with a somewhat
  78902. random distribution. In this case, the compression algorithm is tuned to
  78903. compress them better. The effect of Z_FILTERED is to force more Huffman
  78904. coding and less string matching; it is somewhat intermediate between
  78905. Z_DEFAULT and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as
  78906. Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy
  78907. parameter only affects the compression ratio but not the correctness of the
  78908. compressed output even if it is not set appropriately. Z_FIXED prevents the
  78909. use of dynamic Huffman codes, allowing for a simpler decoder for special
  78910. applications.
  78911. deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78912. memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid
  78913. method). msg is set to null if there is no error message. deflateInit2 does
  78914. not perform any compression: this will be done by deflate().
  78915. */
  78916. ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm,
  78917. const Bytef *dictionary,
  78918. uInt dictLength));
  78919. /*
  78920. Initializes the compression dictionary from the given byte sequence
  78921. without producing any compressed output. This function must be called
  78922. immediately after deflateInit, deflateInit2 or deflateReset, before any
  78923. call of deflate. The compressor and decompressor must use exactly the same
  78924. dictionary (see inflateSetDictionary).
  78925. The dictionary should consist of strings (byte sequences) that are likely
  78926. to be encountered later in the data to be compressed, with the most commonly
  78927. used strings preferably put towards the end of the dictionary. Using a
  78928. dictionary is most useful when the data to be compressed is short and can be
  78929. predicted with good accuracy; the data can then be compressed better than
  78930. with the default empty dictionary.
  78931. Depending on the size of the compression data structures selected by
  78932. deflateInit or deflateInit2, a part of the dictionary may in effect be
  78933. discarded, for example if the dictionary is larger than the window size in
  78934. deflate or deflate2. Thus the strings most likely to be useful should be
  78935. put at the end of the dictionary, not at the front. In addition, the
  78936. current implementation of deflate will use at most the window size minus
  78937. 262 bytes of the provided dictionary.
  78938. Upon return of this function, strm->adler is set to the adler32 value
  78939. of the dictionary; the decompressor may later use this value to determine
  78940. which dictionary has been used by the compressor. (The adler32 value
  78941. applies to the whole dictionary even if only a subset of the dictionary is
  78942. actually used by the compressor.) If a raw deflate was requested, then the
  78943. adler32 value is not computed and strm->adler is not set.
  78944. deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
  78945. parameter is invalid (such as NULL dictionary) or the stream state is
  78946. inconsistent (for example if deflate has already been called for this stream
  78947. or if the compression method is bsort). deflateSetDictionary does not
  78948. perform any compression: this will be done by deflate().
  78949. */
  78950. ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest,
  78951. z_streamp source));
  78952. /*
  78953. Sets the destination stream as a complete copy of the source stream.
  78954. This function can be useful when several compression strategies will be
  78955. tried, for example when there are several ways of pre-processing the input
  78956. data with a filter. The streams that will be discarded should then be freed
  78957. by calling deflateEnd. Note that deflateCopy duplicates the internal
  78958. compression state which can be quite large, so this strategy is slow and
  78959. can consume lots of memory.
  78960. deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  78961. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  78962. (such as zalloc being NULL). msg is left unchanged in both source and
  78963. destination.
  78964. */
  78965. ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm));
  78966. /*
  78967. This function is equivalent to deflateEnd followed by deflateInit,
  78968. but does not free and reallocate all the internal compression state.
  78969. The stream will keep the same compression level and any other attributes
  78970. that may have been set by deflateInit2.
  78971. deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  78972. stream state was inconsistent (such as zalloc or state being NULL).
  78973. */
  78974. ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm,
  78975. int level,
  78976. int strategy));
  78977. /*
  78978. Dynamically update the compression level and compression strategy. The
  78979. interpretation of level and strategy is as in deflateInit2. This can be
  78980. used to switch between compression and straight copy of the input data, or
  78981. to switch to a different kind of input data requiring a different
  78982. strategy. If the compression level is changed, the input available so far
  78983. is compressed with the old level (and may be flushed); the new level will
  78984. take effect only at the next call of deflate().
  78985. Before the call of deflateParams, the stream state must be set as for
  78986. a call of deflate(), since the currently available input may have to
  78987. be compressed and flushed. In particular, strm->avail_out must be non-zero.
  78988. deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source
  78989. stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR
  78990. if strm->avail_out was zero.
  78991. */
  78992. ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm,
  78993. int good_length,
  78994. int max_lazy,
  78995. int nice_length,
  78996. int max_chain));
  78997. /*
  78998. Fine tune deflate's internal compression parameters. This should only be
  78999. used by someone who understands the algorithm used by zlib's deflate for
  79000. searching for the best matching string, and even then only by the most
  79001. fanatic optimizer trying to squeeze out the last compressed bit for their
  79002. specific input data. Read the deflate.c source code for the meaning of the
  79003. max_lazy, good_length, nice_length, and max_chain parameters.
  79004. deflateTune() can be called after deflateInit() or deflateInit2(), and
  79005. returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream.
  79006. */
  79007. ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm,
  79008. uLong sourceLen));
  79009. /*
  79010. deflateBound() returns an upper bound on the compressed size after
  79011. deflation of sourceLen bytes. It must be called after deflateInit()
  79012. or deflateInit2(). This would be used to allocate an output buffer
  79013. for deflation in a single pass, and so would be called before deflate().
  79014. */
  79015. ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm,
  79016. int bits,
  79017. int value));
  79018. /*
  79019. deflatePrime() inserts bits in the deflate output stream. The intent
  79020. is that this function is used to start off the deflate output with the
  79021. bits leftover from a previous deflate stream when appending to it. As such,
  79022. this function can only be used for raw deflate, and must be used before the
  79023. first deflate() call after a deflateInit2() or deflateReset(). bits must be
  79024. less than or equal to 16, and that many of the least significant bits of
  79025. value will be inserted in the output.
  79026. deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  79027. stream state was inconsistent.
  79028. */
  79029. ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm,
  79030. gz_headerp head));
  79031. /*
  79032. deflateSetHeader() provides gzip header information for when a gzip
  79033. stream is requested by deflateInit2(). deflateSetHeader() may be called
  79034. after deflateInit2() or deflateReset() and before the first call of
  79035. deflate(). The text, time, os, extra field, name, and comment information
  79036. in the provided gz_header structure are written to the gzip header (xflag is
  79037. ignored -- the extra flags are set according to the compression level). The
  79038. caller must assure that, if not Z_NULL, name and comment are terminated with
  79039. a zero byte, and that if extra is not Z_NULL, that extra_len bytes are
  79040. available there. If hcrc is true, a gzip header crc is included. Note that
  79041. the current versions of the command-line version of gzip (up through version
  79042. 1.3.x) do not support header crc's, and will report that it is a "multi-part
  79043. gzip file" and give up.
  79044. If deflateSetHeader is not used, the default gzip header has text false,
  79045. the time set to zero, and os set to 255, with no extra, name, or comment
  79046. fields. The gzip header is returned to the default state by deflateReset().
  79047. deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  79048. stream state was inconsistent.
  79049. */
  79050. /*
  79051. ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm,
  79052. int windowBits));
  79053. This is another version of inflateInit with an extra parameter. The
  79054. fields next_in, avail_in, zalloc, zfree and opaque must be initialized
  79055. before by the caller.
  79056. The windowBits parameter is the base two logarithm of the maximum window
  79057. size (the size of the history buffer). It should be in the range 8..15 for
  79058. this version of the library. The default value is 15 if inflateInit is used
  79059. instead. windowBits must be greater than or equal to the windowBits value
  79060. provided to deflateInit2() while compressing, or it must be equal to 15 if
  79061. deflateInit2() was not used. If a compressed stream with a larger window
  79062. size is given as input, inflate() will return with the error code
  79063. Z_DATA_ERROR instead of trying to allocate a larger window.
  79064. windowBits can also be -8..-15 for raw inflate. In this case, -windowBits
  79065. determines the window size. inflate() will then process raw deflate data,
  79066. not looking for a zlib or gzip header, not generating a check value, and not
  79067. looking for any check values for comparison at the end of the stream. This
  79068. is for use with other formats that use the deflate compressed data format
  79069. such as zip. Those formats provide their own check values. If a custom
  79070. format is developed using the raw deflate format for compressed data, it is
  79071. recommended that a check value such as an adler32 or a crc32 be applied to
  79072. the uncompressed data as is done in the zlib, gzip, and zip formats. For
  79073. most applications, the zlib format should be used as is. Note that comments
  79074. above on the use in deflateInit2() applies to the magnitude of windowBits.
  79075. windowBits can also be greater than 15 for optional gzip decoding. Add
  79076. 32 to windowBits to enable zlib and gzip decoding with automatic header
  79077. detection, or add 16 to decode only the gzip format (the zlib format will
  79078. return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is
  79079. a crc32 instead of an adler32.
  79080. inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  79081. memory, Z_STREAM_ERROR if a parameter is invalid (such as a null strm). msg
  79082. is set to null if there is no error message. inflateInit2 does not perform
  79083. any decompression apart from reading the zlib header if present: this will
  79084. be done by inflate(). (So next_in and avail_in may be modified, but next_out
  79085. and avail_out are unchanged.)
  79086. */
  79087. ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm,
  79088. const Bytef *dictionary,
  79089. uInt dictLength));
  79090. /*
  79091. Initializes the decompression dictionary from the given uncompressed byte
  79092. sequence. This function must be called immediately after a call of inflate,
  79093. if that call returned Z_NEED_DICT. The dictionary chosen by the compressor
  79094. can be determined from the adler32 value returned by that call of inflate.
  79095. The compressor and decompressor must use exactly the same dictionary (see
  79096. deflateSetDictionary). For raw inflate, this function can be called
  79097. immediately after inflateInit2() or inflateReset() and before any call of
  79098. inflate() to set the dictionary. The application must insure that the
  79099. dictionary that was used for compression is provided.
  79100. inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
  79101. parameter is invalid (such as NULL dictionary) or the stream state is
  79102. inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
  79103. expected one (incorrect adler32 value). inflateSetDictionary does not
  79104. perform any decompression: this will be done by subsequent calls of
  79105. inflate().
  79106. */
  79107. ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm));
  79108. /*
  79109. Skips invalid compressed data until a full flush point (see above the
  79110. description of deflate with Z_FULL_FLUSH) can be found, or until all
  79111. available input is skipped. No output is provided.
  79112. inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR
  79113. if no more input was provided, Z_DATA_ERROR if no flush point has been found,
  79114. or Z_STREAM_ERROR if the stream structure was inconsistent. In the success
  79115. case, the application may save the current current value of total_in which
  79116. indicates where valid compressed data was found. In the error case, the
  79117. application may repeatedly call inflateSync, providing more input each time,
  79118. until success or end of the input data.
  79119. */
  79120. ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest,
  79121. z_streamp source));
  79122. /*
  79123. Sets the destination stream as a complete copy of the source stream.
  79124. This function can be useful when randomly accessing a large stream. The
  79125. first pass through the stream can periodically record the inflate state,
  79126. allowing restarting inflate at those points when randomly accessing the
  79127. stream.
  79128. inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  79129. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  79130. (such as zalloc being NULL). msg is left unchanged in both source and
  79131. destination.
  79132. */
  79133. ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm));
  79134. /*
  79135. This function is equivalent to inflateEnd followed by inflateInit,
  79136. but does not free and reallocate all the internal decompression state.
  79137. The stream will keep attributes that may have been set by inflateInit2.
  79138. inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  79139. stream state was inconsistent (such as zalloc or state being NULL).
  79140. */
  79141. ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm,
  79142. int bits,
  79143. int value));
  79144. /*
  79145. This function inserts bits in the inflate input stream. The intent is
  79146. that this function is used to start inflating at a bit position in the
  79147. middle of a byte. The provided bits will be used before any bytes are used
  79148. from next_in. This function should only be used with raw inflate, and
  79149. should be used before the first inflate() call after inflateInit2() or
  79150. inflateReset(). bits must be less than or equal to 16, and that many of the
  79151. least significant bits of value will be inserted in the input.
  79152. inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  79153. stream state was inconsistent.
  79154. */
  79155. ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm,
  79156. gz_headerp head));
  79157. /*
  79158. inflateGetHeader() requests that gzip header information be stored in the
  79159. provided gz_header structure. inflateGetHeader() may be called after
  79160. inflateInit2() or inflateReset(), and before the first call of inflate().
  79161. As inflate() processes the gzip stream, head->done is zero until the header
  79162. is completed, at which time head->done is set to one. If a zlib stream is
  79163. being decoded, then head->done is set to -1 to indicate that there will be
  79164. no gzip header information forthcoming. Note that Z_BLOCK can be used to
  79165. force inflate() to return immediately after header processing is complete
  79166. and before any actual data is decompressed.
  79167. The text, time, xflags, and os fields are filled in with the gzip header
  79168. contents. hcrc is set to true if there is a header CRC. (The header CRC
  79169. was valid if done is set to one.) If extra is not Z_NULL, then extra_max
  79170. contains the maximum number of bytes to write to extra. Once done is true,
  79171. extra_len contains the actual extra field length, and extra contains the
  79172. extra field, or that field truncated if extra_max is less than extra_len.
  79173. If name is not Z_NULL, then up to name_max characters are written there,
  79174. terminated with a zero unless the length is greater than name_max. If
  79175. comment is not Z_NULL, then up to comm_max characters are written there,
  79176. terminated with a zero unless the length is greater than comm_max. When
  79177. any of extra, name, or comment are not Z_NULL and the respective field is
  79178. not present in the header, then that field is set to Z_NULL to signal its
  79179. absence. This allows the use of deflateSetHeader() with the returned
  79180. structure to duplicate the header. However if those fields are set to
  79181. allocated memory, then the application will need to save those pointers
  79182. elsewhere so that they can be eventually freed.
  79183. If inflateGetHeader is not used, then the header information is simply
  79184. discarded. The header is always checked for validity, including the header
  79185. CRC if present. inflateReset() will reset the process to discard the header
  79186. information. The application would need to call inflateGetHeader() again to
  79187. retrieve the header from the next gzip stream.
  79188. inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  79189. stream state was inconsistent.
  79190. */
  79191. /*
  79192. ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits,
  79193. unsigned char FAR *window));
  79194. Initialize the internal stream state for decompression using inflateBack()
  79195. calls. The fields zalloc, zfree and opaque in strm must be initialized
  79196. before the call. If zalloc and zfree are Z_NULL, then the default library-
  79197. derived memory allocation routines are used. windowBits is the base two
  79198. logarithm of the window size, in the range 8..15. window is a caller
  79199. supplied buffer of that size. Except for special applications where it is
  79200. assured that deflate was used with small window sizes, windowBits must be 15
  79201. and a 32K byte window must be supplied to be able to decompress general
  79202. deflate streams.
  79203. See inflateBack() for the usage of these routines.
  79204. inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of
  79205. the paramaters are invalid, Z_MEM_ERROR if the internal state could not
  79206. be allocated, or Z_VERSION_ERROR if the version of the library does not
  79207. match the version of the header file.
  79208. */
  79209. typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *));
  79210. typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned));
  79211. ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm,
  79212. in_func in, void FAR *in_desc,
  79213. out_func out, void FAR *out_desc));
  79214. /*
  79215. inflateBack() does a raw inflate with a single call using a call-back
  79216. interface for input and output. This is more efficient than inflate() for
  79217. file i/o applications in that it avoids copying between the output and the
  79218. sliding window by simply making the window itself the output buffer. This
  79219. function trusts the application to not change the output buffer passed by
  79220. the output function, at least until inflateBack() returns.
  79221. inflateBackInit() must be called first to allocate the internal state
  79222. and to initialize the state with the user-provided window buffer.
  79223. inflateBack() may then be used multiple times to inflate a complete, raw
  79224. deflate stream with each call. inflateBackEnd() is then called to free
  79225. the allocated state.
  79226. A raw deflate stream is one with no zlib or gzip header or trailer.
  79227. This routine would normally be used in a utility that reads zip or gzip
  79228. files and writes out uncompressed files. The utility would decode the
  79229. header and process the trailer on its own, hence this routine expects
  79230. only the raw deflate stream to decompress. This is different from the
  79231. normal behavior of inflate(), which expects either a zlib or gzip header and
  79232. trailer around the deflate stream.
  79233. inflateBack() uses two subroutines supplied by the caller that are then
  79234. called by inflateBack() for input and output. inflateBack() calls those
  79235. routines until it reads a complete deflate stream and writes out all of the
  79236. uncompressed data, or until it encounters an error. The function's
  79237. parameters and return types are defined above in the in_func and out_func
  79238. typedefs. inflateBack() will call in(in_desc, &buf) which should return the
  79239. number of bytes of provided input, and a pointer to that input in buf. If
  79240. there is no input available, in() must return zero--buf is ignored in that
  79241. case--and inflateBack() will return a buffer error. inflateBack() will call
  79242. out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out()
  79243. should return zero on success, or non-zero on failure. If out() returns
  79244. non-zero, inflateBack() will return with an error. Neither in() nor out()
  79245. are permitted to change the contents of the window provided to
  79246. inflateBackInit(), which is also the buffer that out() uses to write from.
  79247. The length written by out() will be at most the window size. Any non-zero
  79248. amount of input may be provided by in().
  79249. For convenience, inflateBack() can be provided input on the first call by
  79250. setting strm->next_in and strm->avail_in. If that input is exhausted, then
  79251. in() will be called. Therefore strm->next_in must be initialized before
  79252. calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called
  79253. immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in
  79254. must also be initialized, and then if strm->avail_in is not zero, input will
  79255. initially be taken from strm->next_in[0 .. strm->avail_in - 1].
  79256. The in_desc and out_desc parameters of inflateBack() is passed as the
  79257. first parameter of in() and out() respectively when they are called. These
  79258. descriptors can be optionally used to pass any information that the caller-
  79259. supplied in() and out() functions need to do their job.
  79260. On return, inflateBack() will set strm->next_in and strm->avail_in to
  79261. pass back any unused input that was provided by the last in() call. The
  79262. return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR
  79263. if in() or out() returned an error, Z_DATA_ERROR if there was a format
  79264. error in the deflate stream (in which case strm->msg is set to indicate the
  79265. nature of the error), or Z_STREAM_ERROR if the stream was not properly
  79266. initialized. In the case of Z_BUF_ERROR, an input or output error can be
  79267. distinguished using strm->next_in which will be Z_NULL only if in() returned
  79268. an error. If strm->next is not Z_NULL, then the Z_BUF_ERROR was due to
  79269. out() returning non-zero. (in() will always be called before out(), so
  79270. strm->next_in is assured to be defined if out() returns non-zero.) Note
  79271. that inflateBack() cannot return Z_OK.
  79272. */
  79273. ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm));
  79274. /*
  79275. All memory allocated by inflateBackInit() is freed.
  79276. inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream
  79277. state was inconsistent.
  79278. */
  79279. //ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void));
  79280. /* Return flags indicating compile-time options.
  79281. Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other:
  79282. 1.0: size of uInt
  79283. 3.2: size of uLong
  79284. 5.4: size of voidpf (pointer)
  79285. 7.6: size of z_off_t
  79286. Compiler, assembler, and debug options:
  79287. 8: DEBUG
  79288. 9: ASMV or ASMINF -- use ASM code
  79289. 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention
  79290. 11: 0 (reserved)
  79291. One-time table building (smaller code, but not thread-safe if true):
  79292. 12: BUILDFIXED -- build static block decoding tables when needed
  79293. 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed
  79294. 14,15: 0 (reserved)
  79295. Library content (indicates missing functionality):
  79296. 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking
  79297. deflate code when not needed)
  79298. 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect
  79299. and decode gzip streams (to avoid linking crc code)
  79300. 18-19: 0 (reserved)
  79301. Operation variations (changes in library functionality):
  79302. 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate
  79303. 21: FASTEST -- deflate algorithm with only one, lowest compression level
  79304. 22,23: 0 (reserved)
  79305. The sprintf variant used by gzprintf (zero is best):
  79306. 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format
  79307. 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure!
  79308. 26: 0 = returns value, 1 = void -- 1 means inferred string length returned
  79309. Remainder:
  79310. 27-31: 0 (reserved)
  79311. */
  79312. /* utility functions */
  79313. /*
  79314. The following utility functions are implemented on top of the
  79315. basic stream-oriented functions. To simplify the interface, some
  79316. default options are assumed (compression level and memory usage,
  79317. standard memory allocation functions). The source code of these
  79318. utility functions can easily be modified if you need special options.
  79319. */
  79320. ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen,
  79321. const Bytef *source, uLong sourceLen));
  79322. /*
  79323. Compresses the source buffer into the destination buffer. sourceLen is
  79324. the byte length of the source buffer. Upon entry, destLen is the total
  79325. size of the destination buffer, which must be at least the value returned
  79326. by compressBound(sourceLen). Upon exit, destLen is the actual size of the
  79327. compressed buffer.
  79328. This function can be used to compress a whole file at once if the
  79329. input file is mmap'ed.
  79330. compress returns Z_OK if success, Z_MEM_ERROR if there was not
  79331. enough memory, Z_BUF_ERROR if there was not enough room in the output
  79332. buffer.
  79333. */
  79334. ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen,
  79335. const Bytef *source, uLong sourceLen,
  79336. int level));
  79337. /*
  79338. Compresses the source buffer into the destination buffer. The level
  79339. parameter has the same meaning as in deflateInit. sourceLen is the byte
  79340. length of the source buffer. Upon entry, destLen is the total size of the
  79341. destination buffer, which must be at least the value returned by
  79342. compressBound(sourceLen). Upon exit, destLen is the actual size of the
  79343. compressed buffer.
  79344. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  79345. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  79346. Z_STREAM_ERROR if the level parameter is invalid.
  79347. */
  79348. ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen));
  79349. /*
  79350. compressBound() returns an upper bound on the compressed size after
  79351. compress() or compress2() on sourceLen bytes. It would be used before
  79352. a compress() or compress2() call to allocate the destination buffer.
  79353. */
  79354. ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen,
  79355. const Bytef *source, uLong sourceLen));
  79356. /*
  79357. Decompresses the source buffer into the destination buffer. sourceLen is
  79358. the byte length of the source buffer. Upon entry, destLen is the total
  79359. size of the destination buffer, which must be large enough to hold the
  79360. entire uncompressed data. (The size of the uncompressed data must have
  79361. been saved previously by the compressor and transmitted to the decompressor
  79362. by some mechanism outside the scope of this compression library.)
  79363. Upon exit, destLen is the actual size of the compressed buffer.
  79364. This function can be used to decompress a whole file at once if the
  79365. input file is mmap'ed.
  79366. uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
  79367. enough memory, Z_BUF_ERROR if there was not enough room in the output
  79368. buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete.
  79369. */
  79370. typedef voidp gzFile;
  79371. ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode));
  79372. /*
  79373. Opens a gzip (.gz) file for reading or writing. The mode parameter
  79374. is as in fopen ("rb" or "wb") but can also include a compression level
  79375. ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for
  79376. Huffman only compression as in "wb1h", or 'R' for run-length encoding
  79377. as in "wb1R". (See the description of deflateInit2 for more information
  79378. about the strategy parameter.)
  79379. gzopen can be used to read a file which is not in gzip format; in this
  79380. case gzread will directly read from the file without decompression.
  79381. gzopen returns NULL if the file could not be opened or if there was
  79382. insufficient memory to allocate the (de)compression state; errno
  79383. can be checked to distinguish the two cases (if errno is zero, the
  79384. zlib error is Z_MEM_ERROR). */
  79385. ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode));
  79386. /*
  79387. gzdopen() associates a gzFile with the file descriptor fd. File
  79388. descriptors are obtained from calls like open, dup, creat, pipe or
  79389. fileno (in the file has been previously opened with fopen).
  79390. The mode parameter is as in gzopen.
  79391. The next call of gzclose on the returned gzFile will also close the
  79392. file descriptor fd, just like fclose(fdopen(fd), mode) closes the file
  79393. descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode).
  79394. gzdopen returns NULL if there was insufficient memory to allocate
  79395. the (de)compression state.
  79396. */
  79397. ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy));
  79398. /*
  79399. Dynamically update the compression level or strategy. See the description
  79400. of deflateInit2 for the meaning of these parameters.
  79401. gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not
  79402. opened for writing.
  79403. */
  79404. ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len));
  79405. /*
  79406. Reads the given number of uncompressed bytes from the compressed file.
  79407. If the input file was not in gzip format, gzread copies the given number
  79408. of bytes into the buffer.
  79409. gzread returns the number of uncompressed bytes actually read (0 for
  79410. end of file, -1 for error). */
  79411. ZEXTERN int ZEXPORT gzwrite OF((gzFile file,
  79412. voidpc buf, unsigned len));
  79413. /*
  79414. Writes the given number of uncompressed bytes into the compressed file.
  79415. gzwrite returns the number of uncompressed bytes actually written
  79416. (0 in case of error).
  79417. */
  79418. ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...));
  79419. /*
  79420. Converts, formats, and writes the args to the compressed file under
  79421. control of the format string, as in fprintf. gzprintf returns the number of
  79422. uncompressed bytes actually written (0 in case of error). The number of
  79423. uncompressed bytes written is limited to 4095. The caller should assure that
  79424. this limit is not exceeded. If it is exceeded, then gzprintf() will return
  79425. return an error (0) with nothing written. In this case, there may also be a
  79426. buffer overflow with unpredictable consequences, which is possible only if
  79427. zlib was compiled with the insecure functions sprintf() or vsprintf()
  79428. because the secure snprintf() or vsnprintf() functions were not available.
  79429. */
  79430. ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s));
  79431. /*
  79432. Writes the given null-terminated string to the compressed file, excluding
  79433. the terminating null character.
  79434. gzputs returns the number of characters written, or -1 in case of error.
  79435. */
  79436. ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len));
  79437. /*
  79438. Reads bytes from the compressed file until len-1 characters are read, or
  79439. a newline character is read and transferred to buf, or an end-of-file
  79440. condition is encountered. The string is then terminated with a null
  79441. character.
  79442. gzgets returns buf, or Z_NULL in case of error.
  79443. */
  79444. ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c));
  79445. /*
  79446. Writes c, converted to an unsigned char, into the compressed file.
  79447. gzputc returns the value that was written, or -1 in case of error.
  79448. */
  79449. ZEXTERN int ZEXPORT gzgetc OF((gzFile file));
  79450. /*
  79451. Reads one byte from the compressed file. gzgetc returns this byte
  79452. or -1 in case of end of file or error.
  79453. */
  79454. ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file));
  79455. /*
  79456. Push one character back onto the stream to be read again later.
  79457. Only one character of push-back is allowed. gzungetc() returns the
  79458. character pushed, or -1 on failure. gzungetc() will fail if a
  79459. character has been pushed but not read yet, or if c is -1. The pushed
  79460. character will be discarded if the stream is repositioned with gzseek()
  79461. or gzrewind().
  79462. */
  79463. ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush));
  79464. /*
  79465. Flushes all pending output into the compressed file. The parameter
  79466. flush is as in the deflate() function. The return value is the zlib
  79467. error number (see function gzerror below). gzflush returns Z_OK if
  79468. the flush parameter is Z_FINISH and all output could be flushed.
  79469. gzflush should be called only when strictly necessary because it can
  79470. degrade compression.
  79471. */
  79472. ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file,
  79473. z_off_t offset, int whence));
  79474. /*
  79475. Sets the starting position for the next gzread or gzwrite on the
  79476. given compressed file. The offset represents a number of bytes in the
  79477. uncompressed data stream. The whence parameter is defined as in lseek(2);
  79478. the value SEEK_END is not supported.
  79479. If the file is opened for reading, this function is emulated but can be
  79480. extremely slow. If the file is opened for writing, only forward seeks are
  79481. supported; gzseek then compresses a sequence of zeroes up to the new
  79482. starting position.
  79483. gzseek returns the resulting offset location as measured in bytes from
  79484. the beginning of the uncompressed stream, or -1 in case of error, in
  79485. particular if the file is opened for writing and the new starting position
  79486. would be before the current position.
  79487. */
  79488. ZEXTERN int ZEXPORT gzrewind OF((gzFile file));
  79489. /*
  79490. Rewinds the given file. This function is supported only for reading.
  79491. gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
  79492. */
  79493. ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file));
  79494. /*
  79495. Returns the starting position for the next gzread or gzwrite on the
  79496. given compressed file. This position represents a number of bytes in the
  79497. uncompressed data stream.
  79498. gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
  79499. */
  79500. ZEXTERN int ZEXPORT gzeof OF((gzFile file));
  79501. /*
  79502. Returns 1 when EOF has previously been detected reading the given
  79503. input stream, otherwise zero.
  79504. */
  79505. ZEXTERN int ZEXPORT gzdirect OF((gzFile file));
  79506. /*
  79507. Returns 1 if file is being read directly without decompression, otherwise
  79508. zero.
  79509. */
  79510. ZEXTERN int ZEXPORT gzclose OF((gzFile file));
  79511. /*
  79512. Flushes all pending output if necessary, closes the compressed file
  79513. and deallocates all the (de)compression state. The return value is the zlib
  79514. error number (see function gzerror below).
  79515. */
  79516. ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum));
  79517. /*
  79518. Returns the error message for the last error which occurred on the
  79519. given compressed file. errnum is set to zlib error number. If an
  79520. error occurred in the file system and not in the compression library,
  79521. errnum is set to Z_ERRNO and the application may consult errno
  79522. to get the exact error code.
  79523. */
  79524. ZEXTERN void ZEXPORT gzclearerr OF((gzFile file));
  79525. /*
  79526. Clears the error and end-of-file flags for file. This is analogous to the
  79527. clearerr() function in stdio. This is useful for continuing to read a gzip
  79528. file that is being written concurrently.
  79529. */
  79530. /* checksum functions */
  79531. /*
  79532. These functions are not related to compression but are exported
  79533. anyway because they might be useful in applications using the
  79534. compression library.
  79535. */
  79536. ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len));
  79537. /*
  79538. Update a running Adler-32 checksum with the bytes buf[0..len-1] and
  79539. return the updated checksum. If buf is NULL, this function returns
  79540. the required initial value for the checksum.
  79541. An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
  79542. much faster. Usage example:
  79543. uLong adler = adler32(0L, Z_NULL, 0);
  79544. while (read_buffer(buffer, length) != EOF) {
  79545. adler = adler32(adler, buffer, length);
  79546. }
  79547. if (adler != original_adler) error();
  79548. */
  79549. ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2,
  79550. z_off_t len2));
  79551. /*
  79552. Combine two Adler-32 checksums into one. For two sequences of bytes, seq1
  79553. and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for
  79554. each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of
  79555. seq1 and seq2 concatenated, requiring only adler1, adler2, and len2.
  79556. */
  79557. ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len));
  79558. /*
  79559. Update a running CRC-32 with the bytes buf[0..len-1] and return the
  79560. updated CRC-32. If buf is NULL, this function returns the required initial
  79561. value for the for the crc. Pre- and post-conditioning (one's complement) is
  79562. performed within this function so it shouldn't be done by the application.
  79563. Usage example:
  79564. uLong crc = crc32(0L, Z_NULL, 0);
  79565. while (read_buffer(buffer, length) != EOF) {
  79566. crc = crc32(crc, buffer, length);
  79567. }
  79568. if (crc != original_crc) error();
  79569. */
  79570. ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2));
  79571. /*
  79572. Combine two CRC-32 check values into one. For two sequences of bytes,
  79573. seq1 and seq2 with lengths len1 and len2, CRC-32 check values were
  79574. calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32
  79575. check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and
  79576. len2.
  79577. */
  79578. /* various hacks, don't look :) */
  79579. /* deflateInit and inflateInit are macros to allow checking the zlib version
  79580. * and the compiler's view of z_stream:
  79581. */
  79582. ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level,
  79583. const char *version, int stream_size));
  79584. ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm,
  79585. const char *version, int stream_size));
  79586. ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method,
  79587. int windowBits, int memLevel,
  79588. int strategy, const char *version,
  79589. int stream_size));
  79590. ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits,
  79591. const char *version, int stream_size));
  79592. ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits,
  79593. unsigned char FAR *window,
  79594. const char *version,
  79595. int stream_size));
  79596. #define deflateInit(strm, level) \
  79597. deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream))
  79598. #define inflateInit(strm) \
  79599. inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream))
  79600. #define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
  79601. deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
  79602. (strategy), ZLIB_VERSION, sizeof(z_stream))
  79603. #define inflateInit2(strm, windowBits) \
  79604. inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream))
  79605. #define inflateBackInit(strm, windowBits, window) \
  79606. inflateBackInit_((strm), (windowBits), (window), \
  79607. ZLIB_VERSION, sizeof(z_stream))
  79608. #if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL)
  79609. struct internal_state {int dummy;}; /* hack for buggy compilers */
  79610. #endif
  79611. ZEXTERN const char * ZEXPORT zError OF((int));
  79612. ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp z));
  79613. ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void));
  79614. #ifdef __cplusplus
  79615. //}
  79616. #endif
  79617. #endif /* ZLIB_H */
  79618. /*** End of inlined file: zlib.h ***/
  79619. #undef OS_CODE
  79620. #else
  79621. #include <zlib.h>
  79622. #endif
  79623. }
  79624. BEGIN_JUCE_NAMESPACE
  79625. // internal helper object that holds the zlib structures so they don't have to be
  79626. // included publicly.
  79627. class GZIPCompressorOutputStream::GZIPCompressorHelper
  79628. {
  79629. public:
  79630. GZIPCompressorHelper (const int compressionLevel, const bool nowrap)
  79631. : data (0),
  79632. dataSize (0),
  79633. compLevel (compressionLevel),
  79634. strategy (0),
  79635. setParams (true),
  79636. streamIsValid (false),
  79637. finished (false),
  79638. shouldFinish (false)
  79639. {
  79640. using namespace zlibNamespace;
  79641. zerostruct (stream);
  79642. streamIsValid = (deflateInit2 (&stream, compLevel, Z_DEFLATED,
  79643. nowrap ? -MAX_WBITS : MAX_WBITS,
  79644. 8, strategy) == Z_OK);
  79645. }
  79646. ~GZIPCompressorHelper()
  79647. {
  79648. using namespace zlibNamespace;
  79649. if (streamIsValid)
  79650. deflateEnd (&stream);
  79651. }
  79652. bool needsInput() const throw()
  79653. {
  79654. return dataSize <= 0;
  79655. }
  79656. void setInput (const uint8* const newData, const int size) throw()
  79657. {
  79658. data = newData;
  79659. dataSize = size;
  79660. }
  79661. int doNextBlock (uint8* const dest, const int destSize) throw()
  79662. {
  79663. using namespace zlibNamespace;
  79664. if (streamIsValid)
  79665. {
  79666. stream.next_in = const_cast <uint8*> (data);
  79667. stream.next_out = dest;
  79668. stream.avail_in = dataSize;
  79669. stream.avail_out = destSize;
  79670. const int result = setParams ? deflateParams (&stream, compLevel, strategy)
  79671. : deflate (&stream, shouldFinish ? Z_FINISH : Z_NO_FLUSH);
  79672. setParams = false;
  79673. switch (result)
  79674. {
  79675. case Z_STREAM_END:
  79676. finished = true;
  79677. // Deliberate fall-through..
  79678. case Z_OK:
  79679. data += dataSize - stream.avail_in;
  79680. dataSize = stream.avail_in;
  79681. return destSize - stream.avail_out;
  79682. default:
  79683. break;
  79684. }
  79685. }
  79686. return 0;
  79687. }
  79688. enum { gzipCompBufferSize = 32768 };
  79689. private:
  79690. zlibNamespace::z_stream stream;
  79691. const uint8* data;
  79692. int dataSize, compLevel, strategy;
  79693. bool setParams, streamIsValid;
  79694. public:
  79695. bool finished, shouldFinish;
  79696. };
  79697. GZIPCompressorOutputStream::GZIPCompressorOutputStream (OutputStream* const destStream_,
  79698. int compressionLevel,
  79699. const bool deleteDestStream,
  79700. const bool noWrap)
  79701. : destStream (destStream_),
  79702. streamToDelete (deleteDestStream ? destStream_ : 0),
  79703. buffer ((size_t) GZIPCompressorHelper::gzipCompBufferSize)
  79704. {
  79705. if (compressionLevel < 1 || compressionLevel > 9)
  79706. compressionLevel = -1;
  79707. helper = new GZIPCompressorHelper (compressionLevel, noWrap);
  79708. }
  79709. GZIPCompressorOutputStream::~GZIPCompressorOutputStream()
  79710. {
  79711. flush();
  79712. }
  79713. void GZIPCompressorOutputStream::flush()
  79714. {
  79715. if (! helper->finished)
  79716. {
  79717. helper->shouldFinish = true;
  79718. while (! helper->finished)
  79719. doNextBlock();
  79720. }
  79721. destStream->flush();
  79722. }
  79723. bool GZIPCompressorOutputStream::write (const void* destBuffer, int howMany)
  79724. {
  79725. if (! helper->finished)
  79726. {
  79727. helper->setInput (static_cast <const uint8*> (destBuffer), howMany);
  79728. while (! helper->needsInput())
  79729. {
  79730. if (! doNextBlock())
  79731. return false;
  79732. }
  79733. }
  79734. return true;
  79735. }
  79736. bool GZIPCompressorOutputStream::doNextBlock()
  79737. {
  79738. const int len = helper->doNextBlock (buffer, (int) GZIPCompressorHelper::gzipCompBufferSize);
  79739. if (len > 0)
  79740. return destStream->write (buffer, len);
  79741. else
  79742. return true;
  79743. }
  79744. int64 GZIPCompressorOutputStream::getPosition()
  79745. {
  79746. return destStream->getPosition();
  79747. }
  79748. bool GZIPCompressorOutputStream::setPosition (int64 /*newPosition*/)
  79749. {
  79750. jassertfalse; // can't do it!
  79751. return false;
  79752. }
  79753. END_JUCE_NAMESPACE
  79754. /*** End of inlined file: juce_GZIPCompressorOutputStream.cpp ***/
  79755. /*** Start of inlined file: juce_GZIPDecompressorInputStream.cpp ***/
  79756. #if JUCE_MSVC
  79757. #pragma warning (push)
  79758. #pragma warning (disable: 4309 4305)
  79759. #endif
  79760. namespace zlibNamespace
  79761. {
  79762. #if JUCE_INCLUDE_ZLIB_CODE
  79763. #undef OS_CODE
  79764. #undef fdopen
  79765. #define ZLIB_INTERNAL
  79766. #define NO_DUMMY_DECL
  79767. /*** Start of inlined file: adler32.c ***/
  79768. /* @(#) $Id: adler32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79769. #define ZLIB_INTERNAL
  79770. #define BASE 65521UL /* largest prime smaller than 65536 */
  79771. #define NMAX 5552
  79772. /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
  79773. #define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;}
  79774. #define DO2(buf,i) DO1(buf,i); DO1(buf,i+1);
  79775. #define DO4(buf,i) DO2(buf,i); DO2(buf,i+2);
  79776. #define DO8(buf,i) DO4(buf,i); DO4(buf,i+4);
  79777. #define DO16(buf) DO8(buf,0); DO8(buf,8);
  79778. /* use NO_DIVIDE if your processor does not do division in hardware */
  79779. #ifdef NO_DIVIDE
  79780. # define MOD(a) \
  79781. do { \
  79782. if (a >= (BASE << 16)) a -= (BASE << 16); \
  79783. if (a >= (BASE << 15)) a -= (BASE << 15); \
  79784. if (a >= (BASE << 14)) a -= (BASE << 14); \
  79785. if (a >= (BASE << 13)) a -= (BASE << 13); \
  79786. if (a >= (BASE << 12)) a -= (BASE << 12); \
  79787. if (a >= (BASE << 11)) a -= (BASE << 11); \
  79788. if (a >= (BASE << 10)) a -= (BASE << 10); \
  79789. if (a >= (BASE << 9)) a -= (BASE << 9); \
  79790. if (a >= (BASE << 8)) a -= (BASE << 8); \
  79791. if (a >= (BASE << 7)) a -= (BASE << 7); \
  79792. if (a >= (BASE << 6)) a -= (BASE << 6); \
  79793. if (a >= (BASE << 5)) a -= (BASE << 5); \
  79794. if (a >= (BASE << 4)) a -= (BASE << 4); \
  79795. if (a >= (BASE << 3)) a -= (BASE << 3); \
  79796. if (a >= (BASE << 2)) a -= (BASE << 2); \
  79797. if (a >= (BASE << 1)) a -= (BASE << 1); \
  79798. if (a >= BASE) a -= BASE; \
  79799. } while (0)
  79800. # define MOD4(a) \
  79801. do { \
  79802. if (a >= (BASE << 4)) a -= (BASE << 4); \
  79803. if (a >= (BASE << 3)) a -= (BASE << 3); \
  79804. if (a >= (BASE << 2)) a -= (BASE << 2); \
  79805. if (a >= (BASE << 1)) a -= (BASE << 1); \
  79806. if (a >= BASE) a -= BASE; \
  79807. } while (0)
  79808. #else
  79809. # define MOD(a) a %= BASE
  79810. # define MOD4(a) a %= BASE
  79811. #endif
  79812. /* ========================================================================= */
  79813. uLong ZEXPORT adler32(uLong adler, const Bytef *buf, uInt len)
  79814. {
  79815. unsigned long sum2;
  79816. unsigned n;
  79817. /* split Adler-32 into component sums */
  79818. sum2 = (adler >> 16) & 0xffff;
  79819. adler &= 0xffff;
  79820. /* in case user likes doing a byte at a time, keep it fast */
  79821. if (len == 1) {
  79822. adler += buf[0];
  79823. if (adler >= BASE)
  79824. adler -= BASE;
  79825. sum2 += adler;
  79826. if (sum2 >= BASE)
  79827. sum2 -= BASE;
  79828. return adler | (sum2 << 16);
  79829. }
  79830. /* initial Adler-32 value (deferred check for len == 1 speed) */
  79831. if (buf == Z_NULL)
  79832. return 1L;
  79833. /* in case short lengths are provided, keep it somewhat fast */
  79834. if (len < 16) {
  79835. while (len--) {
  79836. adler += *buf++;
  79837. sum2 += adler;
  79838. }
  79839. if (adler >= BASE)
  79840. adler -= BASE;
  79841. MOD4(sum2); /* only added so many BASE's */
  79842. return adler | (sum2 << 16);
  79843. }
  79844. /* do length NMAX blocks -- requires just one modulo operation */
  79845. while (len >= NMAX) {
  79846. len -= NMAX;
  79847. n = NMAX / 16; /* NMAX is divisible by 16 */
  79848. do {
  79849. DO16(buf); /* 16 sums unrolled */
  79850. buf += 16;
  79851. } while (--n);
  79852. MOD(adler);
  79853. MOD(sum2);
  79854. }
  79855. /* do remaining bytes (less than NMAX, still just one modulo) */
  79856. if (len) { /* avoid modulos if none remaining */
  79857. while (len >= 16) {
  79858. len -= 16;
  79859. DO16(buf);
  79860. buf += 16;
  79861. }
  79862. while (len--) {
  79863. adler += *buf++;
  79864. sum2 += adler;
  79865. }
  79866. MOD(adler);
  79867. MOD(sum2);
  79868. }
  79869. /* return recombined sums */
  79870. return adler | (sum2 << 16);
  79871. }
  79872. /* ========================================================================= */
  79873. uLong ZEXPORT adler32_combine(uLong adler1, uLong adler2, z_off_t len2)
  79874. {
  79875. unsigned long sum1;
  79876. unsigned long sum2;
  79877. unsigned rem;
  79878. /* the derivation of this formula is left as an exercise for the reader */
  79879. rem = (unsigned)(len2 % BASE);
  79880. sum1 = adler1 & 0xffff;
  79881. sum2 = rem * sum1;
  79882. MOD(sum2);
  79883. sum1 += (adler2 & 0xffff) + BASE - 1;
  79884. sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem;
  79885. if (sum1 > BASE) sum1 -= BASE;
  79886. if (sum1 > BASE) sum1 -= BASE;
  79887. if (sum2 > (BASE << 1)) sum2 -= (BASE << 1);
  79888. if (sum2 > BASE) sum2 -= BASE;
  79889. return sum1 | (sum2 << 16);
  79890. }
  79891. /*** End of inlined file: adler32.c ***/
  79892. /*** Start of inlined file: compress.c ***/
  79893. /* @(#) $Id: compress.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79894. #define ZLIB_INTERNAL
  79895. /* ===========================================================================
  79896. Compresses the source buffer into the destination buffer. The level
  79897. parameter has the same meaning as in deflateInit. sourceLen is the byte
  79898. length of the source buffer. Upon entry, destLen is the total size of the
  79899. destination buffer, which must be at least 0.1% larger than sourceLen plus
  79900. 12 bytes. Upon exit, destLen is the actual size of the compressed buffer.
  79901. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  79902. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  79903. Z_STREAM_ERROR if the level parameter is invalid.
  79904. */
  79905. int ZEXPORT compress2 (Bytef *dest, uLongf *destLen, const Bytef *source,
  79906. uLong sourceLen, int level)
  79907. {
  79908. z_stream stream;
  79909. int err;
  79910. stream.next_in = (Bytef*)source;
  79911. stream.avail_in = (uInt)sourceLen;
  79912. #ifdef MAXSEG_64K
  79913. /* Check for source > 64K on 16-bit machine: */
  79914. if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;
  79915. #endif
  79916. stream.next_out = dest;
  79917. stream.avail_out = (uInt)*destLen;
  79918. if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
  79919. stream.zalloc = (alloc_func)0;
  79920. stream.zfree = (free_func)0;
  79921. stream.opaque = (voidpf)0;
  79922. err = deflateInit(&stream, level);
  79923. if (err != Z_OK) return err;
  79924. err = deflate(&stream, Z_FINISH);
  79925. if (err != Z_STREAM_END) {
  79926. deflateEnd(&stream);
  79927. return err == Z_OK ? Z_BUF_ERROR : err;
  79928. }
  79929. *destLen = stream.total_out;
  79930. err = deflateEnd(&stream);
  79931. return err;
  79932. }
  79933. /* ===========================================================================
  79934. */
  79935. int ZEXPORT compress (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen)
  79936. {
  79937. return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION);
  79938. }
  79939. /* ===========================================================================
  79940. If the default memLevel or windowBits for deflateInit() is changed, then
  79941. this function needs to be updated.
  79942. */
  79943. uLong ZEXPORT compressBound (uLong sourceLen)
  79944. {
  79945. return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + 11;
  79946. }
  79947. /*** End of inlined file: compress.c ***/
  79948. #undef DO1
  79949. #undef DO8
  79950. /*** Start of inlined file: crc32.c ***/
  79951. /* @(#) $Id: crc32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79952. /*
  79953. Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore
  79954. protection on the static variables used to control the first-use generation
  79955. of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should
  79956. first call get_crc_table() to initialize the tables before allowing more than
  79957. one thread to use crc32().
  79958. */
  79959. #ifdef MAKECRCH
  79960. # include <stdio.h>
  79961. # ifndef DYNAMIC_CRC_TABLE
  79962. # define DYNAMIC_CRC_TABLE
  79963. # endif /* !DYNAMIC_CRC_TABLE */
  79964. #endif /* MAKECRCH */
  79965. /*** Start of inlined file: zutil.h ***/
  79966. /* WARNING: this file should *not* be used by applications. It is
  79967. part of the implementation of the compression library and is
  79968. subject to change. Applications should only use zlib.h.
  79969. */
  79970. /* @(#) $Id: zutil.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79971. #ifndef ZUTIL_H
  79972. #define ZUTIL_H
  79973. #define ZLIB_INTERNAL
  79974. #ifdef STDC
  79975. # ifndef _WIN32_WCE
  79976. # include <stddef.h>
  79977. # endif
  79978. # include <string.h>
  79979. # include <stdlib.h>
  79980. #endif
  79981. #ifdef NO_ERRNO_H
  79982. # ifdef _WIN32_WCE
  79983. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  79984. * errno. We define it as a global variable to simplify porting.
  79985. * Its value is always 0 and should not be used. We rename it to
  79986. * avoid conflict with other libraries that use the same workaround.
  79987. */
  79988. # define errno z_errno
  79989. # endif
  79990. extern int errno;
  79991. #else
  79992. # ifndef _WIN32_WCE
  79993. # include <errno.h>
  79994. # endif
  79995. #endif
  79996. #ifndef local
  79997. # define local static
  79998. #endif
  79999. /* compile with -Dlocal if your debugger can't find static symbols */
  80000. typedef unsigned char uch;
  80001. typedef uch FAR uchf;
  80002. typedef unsigned short ush;
  80003. typedef ush FAR ushf;
  80004. typedef unsigned long ulg;
  80005. extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */
  80006. /* (size given to avoid silly warnings with Visual C++) */
  80007. #define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)]
  80008. #define ERR_RETURN(strm,err) \
  80009. return (strm->msg = (char*)ERR_MSG(err), (err))
  80010. /* To be used only when the state is known to be valid */
  80011. /* common constants */
  80012. #ifndef DEF_WBITS
  80013. # define DEF_WBITS MAX_WBITS
  80014. #endif
  80015. /* default windowBits for decompression. MAX_WBITS is for compression only */
  80016. #if MAX_MEM_LEVEL >= 8
  80017. # define DEF_MEM_LEVEL 8
  80018. #else
  80019. # define DEF_MEM_LEVEL MAX_MEM_LEVEL
  80020. #endif
  80021. /* default memLevel */
  80022. #define STORED_BLOCK 0
  80023. #define STATIC_TREES 1
  80024. #define DYN_TREES 2
  80025. /* The three kinds of block type */
  80026. #define MIN_MATCH 3
  80027. #define MAX_MATCH 258
  80028. /* The minimum and maximum match lengths */
  80029. #define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */
  80030. /* target dependencies */
  80031. #if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32))
  80032. # define OS_CODE 0x00
  80033. # if defined(__TURBOC__) || defined(__BORLANDC__)
  80034. # if(__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__))
  80035. /* Allow compilation with ANSI keywords only enabled */
  80036. void _Cdecl farfree( void *block );
  80037. void *_Cdecl farmalloc( unsigned long nbytes );
  80038. # else
  80039. # include <alloc.h>
  80040. # endif
  80041. # else /* MSC or DJGPP */
  80042. # include <malloc.h>
  80043. # endif
  80044. #endif
  80045. #ifdef AMIGA
  80046. # define OS_CODE 0x01
  80047. #endif
  80048. #if defined(VAXC) || defined(VMS)
  80049. # define OS_CODE 0x02
  80050. # define F_OPEN(name, mode) \
  80051. fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512")
  80052. #endif
  80053. #if defined(ATARI) || defined(atarist)
  80054. # define OS_CODE 0x05
  80055. #endif
  80056. #ifdef OS2
  80057. # define OS_CODE 0x06
  80058. # ifdef M_I86
  80059. #include <malloc.h>
  80060. # endif
  80061. #endif
  80062. #if defined(MACOS) || TARGET_OS_MAC
  80063. # define OS_CODE 0x07
  80064. # if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os
  80065. # include <unix.h> /* for fdopen */
  80066. # else
  80067. # ifndef fdopen
  80068. # define fdopen(fd,mode) NULL /* No fdopen() */
  80069. # endif
  80070. # endif
  80071. #endif
  80072. #ifdef TOPS20
  80073. # define OS_CODE 0x0a
  80074. #endif
  80075. #ifdef WIN32
  80076. # ifndef __CYGWIN__ /* Cygwin is Unix, not Win32 */
  80077. # define OS_CODE 0x0b
  80078. # endif
  80079. #endif
  80080. #ifdef __50SERIES /* Prime/PRIMOS */
  80081. # define OS_CODE 0x0f
  80082. #endif
  80083. #if defined(_BEOS_) || defined(RISCOS)
  80084. # define fdopen(fd,mode) NULL /* No fdopen() */
  80085. #endif
  80086. #if (defined(_MSC_VER) && (_MSC_VER > 600))
  80087. # if defined(_WIN32_WCE)
  80088. # define fdopen(fd,mode) NULL /* No fdopen() */
  80089. # ifndef _PTRDIFF_T_DEFINED
  80090. typedef int ptrdiff_t;
  80091. # define _PTRDIFF_T_DEFINED
  80092. # endif
  80093. # else
  80094. # define fdopen(fd,type) _fdopen(fd,type)
  80095. # endif
  80096. #endif
  80097. /* common defaults */
  80098. #ifndef OS_CODE
  80099. # define OS_CODE 0x03 /* assume Unix */
  80100. #endif
  80101. #ifndef F_OPEN
  80102. # define F_OPEN(name, mode) fopen((name), (mode))
  80103. #endif
  80104. /* functions */
  80105. #if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550)
  80106. # ifndef HAVE_VSNPRINTF
  80107. # define HAVE_VSNPRINTF
  80108. # endif
  80109. #endif
  80110. #if defined(__CYGWIN__)
  80111. # ifndef HAVE_VSNPRINTF
  80112. # define HAVE_VSNPRINTF
  80113. # endif
  80114. #endif
  80115. #ifndef HAVE_VSNPRINTF
  80116. # ifdef MSDOS
  80117. /* vsnprintf may exist on some MS-DOS compilers (DJGPP?),
  80118. but for now we just assume it doesn't. */
  80119. # define NO_vsnprintf
  80120. # endif
  80121. # ifdef __TURBOC__
  80122. # define NO_vsnprintf
  80123. # endif
  80124. # ifdef WIN32
  80125. /* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */
  80126. # if !defined(vsnprintf) && !defined(NO_vsnprintf)
  80127. # define vsnprintf _vsnprintf
  80128. # endif
  80129. # endif
  80130. # ifdef __SASC
  80131. # define NO_vsnprintf
  80132. # endif
  80133. #endif
  80134. #ifdef VMS
  80135. # define NO_vsnprintf
  80136. #endif
  80137. #if defined(pyr)
  80138. # define NO_MEMCPY
  80139. #endif
  80140. #if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__)
  80141. /* Use our own functions for small and medium model with MSC <= 5.0.
  80142. * You may have to use the same strategy for Borland C (untested).
  80143. * The __SC__ check is for Symantec.
  80144. */
  80145. # define NO_MEMCPY
  80146. #endif
  80147. #if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY)
  80148. # define HAVE_MEMCPY
  80149. #endif
  80150. #ifdef HAVE_MEMCPY
  80151. # ifdef SMALL_MEDIUM /* MSDOS small or medium model */
  80152. # define zmemcpy _fmemcpy
  80153. # define zmemcmp _fmemcmp
  80154. # define zmemzero(dest, len) _fmemset(dest, 0, len)
  80155. # else
  80156. # define zmemcpy memcpy
  80157. # define zmemcmp memcmp
  80158. # define zmemzero(dest, len) memset(dest, 0, len)
  80159. # endif
  80160. #else
  80161. extern void zmemcpy OF((Bytef* dest, const Bytef* source, uInt len));
  80162. extern int zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len));
  80163. extern void zmemzero OF((Bytef* dest, uInt len));
  80164. #endif
  80165. /* Diagnostic functions */
  80166. #ifdef DEBUG
  80167. # include <stdio.h>
  80168. extern int z_verbose;
  80169. extern void z_error OF((const char *m));
  80170. # define Assert(cond,msg) {if(!(cond)) z_error(msg);}
  80171. # define Trace(x) {if (z_verbose>=0) fprintf x ;}
  80172. # define Tracev(x) {if (z_verbose>0) fprintf x ;}
  80173. # define Tracevv(x) {if (z_verbose>1) fprintf x ;}
  80174. # define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;}
  80175. # define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;}
  80176. #else
  80177. # define Assert(cond,msg)
  80178. # define Trace(x)
  80179. # define Tracev(x)
  80180. # define Tracevv(x)
  80181. # define Tracec(c,x)
  80182. # define Tracecv(c,x)
  80183. #endif
  80184. voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size));
  80185. void zcfree OF((voidpf opaque, voidpf ptr));
  80186. #define ZALLOC(strm, items, size) \
  80187. (*((strm)->zalloc))((strm)->opaque, (items), (size))
  80188. #define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr))
  80189. #define TRY_FREE(s, p) {if (p) ZFREE(s, p);}
  80190. #endif /* ZUTIL_H */
  80191. /*** End of inlined file: zutil.h ***/
  80192. /* for STDC and FAR definitions */
  80193. #define local static
  80194. /* Find a four-byte integer type for crc32_little() and crc32_big(). */
  80195. #ifndef NOBYFOUR
  80196. # ifdef STDC /* need ANSI C limits.h to determine sizes */
  80197. # include <limits.h>
  80198. # define BYFOUR
  80199. # if (UINT_MAX == 0xffffffffUL)
  80200. typedef unsigned int u4;
  80201. # else
  80202. # if (ULONG_MAX == 0xffffffffUL)
  80203. typedef unsigned long u4;
  80204. # else
  80205. # if (USHRT_MAX == 0xffffffffUL)
  80206. typedef unsigned short u4;
  80207. # else
  80208. # undef BYFOUR /* can't find a four-byte integer type! */
  80209. # endif
  80210. # endif
  80211. # endif
  80212. # endif /* STDC */
  80213. #endif /* !NOBYFOUR */
  80214. /* Definitions for doing the crc four data bytes at a time. */
  80215. #ifdef BYFOUR
  80216. # define REV(w) (((w)>>24)+(((w)>>8)&0xff00)+ \
  80217. (((w)&0xff00)<<8)+(((w)&0xff)<<24))
  80218. local unsigned long crc32_little OF((unsigned long,
  80219. const unsigned char FAR *, unsigned));
  80220. local unsigned long crc32_big OF((unsigned long,
  80221. const unsigned char FAR *, unsigned));
  80222. # define TBLS 8
  80223. #else
  80224. # define TBLS 1
  80225. #endif /* BYFOUR */
  80226. /* Local functions for crc concatenation */
  80227. local unsigned long gf2_matrix_times OF((unsigned long *mat,
  80228. unsigned long vec));
  80229. local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat));
  80230. #ifdef DYNAMIC_CRC_TABLE
  80231. local volatile int crc_table_empty = 1;
  80232. local unsigned long FAR crc_table[TBLS][256];
  80233. local void make_crc_table OF((void));
  80234. #ifdef MAKECRCH
  80235. local void write_table OF((FILE *, const unsigned long FAR *));
  80236. #endif /* MAKECRCH */
  80237. /*
  80238. Generate tables for a byte-wise 32-bit CRC calculation on the polynomial:
  80239. 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.
  80240. Polynomials over GF(2) are represented in binary, one bit per coefficient,
  80241. with the lowest powers in the most significant bit. Then adding polynomials
  80242. is just exclusive-or, and multiplying a polynomial by x is a right shift by
  80243. one. If we call the above polynomial p, and represent a byte as the
  80244. polynomial q, also with the lowest power in the most significant bit (so the
  80245. byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
  80246. where a mod b means the remainder after dividing a by b.
  80247. This calculation is done using the shift-register method of multiplying and
  80248. taking the remainder. The register is initialized to zero, and for each
  80249. incoming bit, x^32 is added mod p to the register if the bit is a one (where
  80250. x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
  80251. x (which is shifting right by one and adding x^32 mod p if the bit shifted
  80252. out is a one). We start with the highest power (least significant bit) of
  80253. q and repeat for all eight bits of q.
  80254. The first table is simply the CRC of all possible eight bit values. This is
  80255. all the information needed to generate CRCs on data a byte at a time for all
  80256. combinations of CRC register values and incoming bytes. The remaining tables
  80257. allow for word-at-a-time CRC calculation for both big-endian and little-
  80258. endian machines, where a word is four bytes.
  80259. */
  80260. local void make_crc_table()
  80261. {
  80262. unsigned long c;
  80263. int n, k;
  80264. unsigned long poly; /* polynomial exclusive-or pattern */
  80265. /* terms of polynomial defining this crc (except x^32): */
  80266. static volatile int first = 1; /* flag to limit concurrent making */
  80267. static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
  80268. /* See if another task is already doing this (not thread-safe, but better
  80269. than nothing -- significantly reduces duration of vulnerability in
  80270. case the advice about DYNAMIC_CRC_TABLE is ignored) */
  80271. if (first) {
  80272. first = 0;
  80273. /* make exclusive-or pattern from polynomial (0xedb88320UL) */
  80274. poly = 0UL;
  80275. for (n = 0; n < sizeof(p)/sizeof(unsigned char); n++)
  80276. poly |= 1UL << (31 - p[n]);
  80277. /* generate a crc for every 8-bit value */
  80278. for (n = 0; n < 256; n++) {
  80279. c = (unsigned long)n;
  80280. for (k = 0; k < 8; k++)
  80281. c = c & 1 ? poly ^ (c >> 1) : c >> 1;
  80282. crc_table[0][n] = c;
  80283. }
  80284. #ifdef BYFOUR
  80285. /* generate crc for each value followed by one, two, and three zeros,
  80286. and then the byte reversal of those as well as the first table */
  80287. for (n = 0; n < 256; n++) {
  80288. c = crc_table[0][n];
  80289. crc_table[4][n] = REV(c);
  80290. for (k = 1; k < 4; k++) {
  80291. c = crc_table[0][c & 0xff] ^ (c >> 8);
  80292. crc_table[k][n] = c;
  80293. crc_table[k + 4][n] = REV(c);
  80294. }
  80295. }
  80296. #endif /* BYFOUR */
  80297. crc_table_empty = 0;
  80298. }
  80299. else { /* not first */
  80300. /* wait for the other guy to finish (not efficient, but rare) */
  80301. while (crc_table_empty)
  80302. ;
  80303. }
  80304. #ifdef MAKECRCH
  80305. /* write out CRC tables to crc32.h */
  80306. {
  80307. FILE *out;
  80308. out = fopen("crc32.h", "w");
  80309. if (out == NULL) return;
  80310. fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n");
  80311. fprintf(out, " * Generated automatically by crc32.c\n */\n\n");
  80312. fprintf(out, "local const unsigned long FAR ");
  80313. fprintf(out, "crc_table[TBLS][256] =\n{\n {\n");
  80314. write_table(out, crc_table[0]);
  80315. # ifdef BYFOUR
  80316. fprintf(out, "#ifdef BYFOUR\n");
  80317. for (k = 1; k < 8; k++) {
  80318. fprintf(out, " },\n {\n");
  80319. write_table(out, crc_table[k]);
  80320. }
  80321. fprintf(out, "#endif\n");
  80322. # endif /* BYFOUR */
  80323. fprintf(out, " }\n};\n");
  80324. fclose(out);
  80325. }
  80326. #endif /* MAKECRCH */
  80327. }
  80328. #ifdef MAKECRCH
  80329. local void write_table(out, table)
  80330. FILE *out;
  80331. const unsigned long FAR *table;
  80332. {
  80333. int n;
  80334. for (n = 0; n < 256; n++)
  80335. fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", table[n],
  80336. n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", "));
  80337. }
  80338. #endif /* MAKECRCH */
  80339. #else /* !DYNAMIC_CRC_TABLE */
  80340. /* ========================================================================
  80341. * Tables of CRC-32s of all single-byte values, made by make_crc_table().
  80342. */
  80343. /*** Start of inlined file: crc32.h ***/
  80344. local const unsigned long FAR crc_table[TBLS][256] =
  80345. {
  80346. {
  80347. 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL,
  80348. 0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL,
  80349. 0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL,
  80350. 0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL,
  80351. 0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL,
  80352. 0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL,
  80353. 0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL,
  80354. 0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL,
  80355. 0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL,
  80356. 0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL,
  80357. 0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL,
  80358. 0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL,
  80359. 0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL,
  80360. 0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL,
  80361. 0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL,
  80362. 0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL,
  80363. 0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL,
  80364. 0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL,
  80365. 0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL,
  80366. 0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL,
  80367. 0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL,
  80368. 0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL,
  80369. 0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL,
  80370. 0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL,
  80371. 0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL,
  80372. 0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL,
  80373. 0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL,
  80374. 0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL,
  80375. 0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL,
  80376. 0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL,
  80377. 0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL,
  80378. 0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL,
  80379. 0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL,
  80380. 0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL,
  80381. 0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL,
  80382. 0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL,
  80383. 0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL,
  80384. 0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL,
  80385. 0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL,
  80386. 0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL,
  80387. 0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL,
  80388. 0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL,
  80389. 0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL,
  80390. 0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL,
  80391. 0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL,
  80392. 0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL,
  80393. 0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL,
  80394. 0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL,
  80395. 0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL,
  80396. 0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL,
  80397. 0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL,
  80398. 0x2d02ef8dUL
  80399. #ifdef BYFOUR
  80400. },
  80401. {
  80402. 0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL,
  80403. 0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL,
  80404. 0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL,
  80405. 0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL,
  80406. 0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL,
  80407. 0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL,
  80408. 0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL,
  80409. 0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL,
  80410. 0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL,
  80411. 0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL,
  80412. 0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL,
  80413. 0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL,
  80414. 0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL,
  80415. 0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL,
  80416. 0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL,
  80417. 0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL,
  80418. 0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL,
  80419. 0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL,
  80420. 0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL,
  80421. 0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL,
  80422. 0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL,
  80423. 0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL,
  80424. 0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL,
  80425. 0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL,
  80426. 0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL,
  80427. 0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL,
  80428. 0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL,
  80429. 0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL,
  80430. 0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL,
  80431. 0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL,
  80432. 0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL,
  80433. 0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL,
  80434. 0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL,
  80435. 0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL,
  80436. 0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL,
  80437. 0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL,
  80438. 0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL,
  80439. 0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL,
  80440. 0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL,
  80441. 0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL,
  80442. 0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL,
  80443. 0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL,
  80444. 0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL,
  80445. 0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL,
  80446. 0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL,
  80447. 0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL,
  80448. 0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL,
  80449. 0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL,
  80450. 0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL,
  80451. 0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL,
  80452. 0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL,
  80453. 0x9324fd72UL
  80454. },
  80455. {
  80456. 0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL,
  80457. 0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL,
  80458. 0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL,
  80459. 0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL,
  80460. 0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL,
  80461. 0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL,
  80462. 0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL,
  80463. 0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL,
  80464. 0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL,
  80465. 0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL,
  80466. 0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL,
  80467. 0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL,
  80468. 0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL,
  80469. 0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL,
  80470. 0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL,
  80471. 0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL,
  80472. 0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL,
  80473. 0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL,
  80474. 0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL,
  80475. 0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL,
  80476. 0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL,
  80477. 0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL,
  80478. 0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL,
  80479. 0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL,
  80480. 0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL,
  80481. 0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL,
  80482. 0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL,
  80483. 0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL,
  80484. 0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL,
  80485. 0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL,
  80486. 0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL,
  80487. 0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL,
  80488. 0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL,
  80489. 0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL,
  80490. 0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL,
  80491. 0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL,
  80492. 0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL,
  80493. 0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL,
  80494. 0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL,
  80495. 0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL,
  80496. 0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL,
  80497. 0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL,
  80498. 0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL,
  80499. 0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL,
  80500. 0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL,
  80501. 0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL,
  80502. 0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL,
  80503. 0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL,
  80504. 0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL,
  80505. 0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL,
  80506. 0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL,
  80507. 0xbe9834edUL
  80508. },
  80509. {
  80510. 0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL,
  80511. 0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL,
  80512. 0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL,
  80513. 0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL,
  80514. 0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL,
  80515. 0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL,
  80516. 0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL,
  80517. 0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL,
  80518. 0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL,
  80519. 0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL,
  80520. 0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL,
  80521. 0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL,
  80522. 0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL,
  80523. 0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL,
  80524. 0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL,
  80525. 0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL,
  80526. 0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL,
  80527. 0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL,
  80528. 0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL,
  80529. 0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL,
  80530. 0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL,
  80531. 0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL,
  80532. 0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL,
  80533. 0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL,
  80534. 0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL,
  80535. 0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL,
  80536. 0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL,
  80537. 0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL,
  80538. 0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL,
  80539. 0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL,
  80540. 0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL,
  80541. 0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL,
  80542. 0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL,
  80543. 0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL,
  80544. 0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL,
  80545. 0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL,
  80546. 0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL,
  80547. 0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL,
  80548. 0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL,
  80549. 0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL,
  80550. 0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL,
  80551. 0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL,
  80552. 0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL,
  80553. 0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL,
  80554. 0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL,
  80555. 0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL,
  80556. 0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL,
  80557. 0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL,
  80558. 0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL,
  80559. 0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL,
  80560. 0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL,
  80561. 0xde0506f1UL
  80562. },
  80563. {
  80564. 0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL,
  80565. 0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL,
  80566. 0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL,
  80567. 0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL,
  80568. 0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL,
  80569. 0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL,
  80570. 0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL,
  80571. 0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL,
  80572. 0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL,
  80573. 0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL,
  80574. 0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL,
  80575. 0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL,
  80576. 0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL,
  80577. 0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL,
  80578. 0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL,
  80579. 0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL,
  80580. 0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL,
  80581. 0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL,
  80582. 0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL,
  80583. 0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL,
  80584. 0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL,
  80585. 0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL,
  80586. 0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL,
  80587. 0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL,
  80588. 0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL,
  80589. 0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL,
  80590. 0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL,
  80591. 0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL,
  80592. 0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL,
  80593. 0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL,
  80594. 0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL,
  80595. 0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL,
  80596. 0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL,
  80597. 0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL,
  80598. 0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL,
  80599. 0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL,
  80600. 0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL,
  80601. 0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL,
  80602. 0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL,
  80603. 0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL,
  80604. 0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL,
  80605. 0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL,
  80606. 0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL,
  80607. 0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL,
  80608. 0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL,
  80609. 0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL,
  80610. 0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL,
  80611. 0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL,
  80612. 0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL,
  80613. 0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL,
  80614. 0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL,
  80615. 0x8def022dUL
  80616. },
  80617. {
  80618. 0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL,
  80619. 0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL,
  80620. 0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL,
  80621. 0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL,
  80622. 0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL,
  80623. 0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL,
  80624. 0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL,
  80625. 0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL,
  80626. 0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL,
  80627. 0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL,
  80628. 0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL,
  80629. 0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL,
  80630. 0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL,
  80631. 0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL,
  80632. 0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL,
  80633. 0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL,
  80634. 0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL,
  80635. 0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL,
  80636. 0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL,
  80637. 0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL,
  80638. 0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL,
  80639. 0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL,
  80640. 0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL,
  80641. 0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL,
  80642. 0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL,
  80643. 0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL,
  80644. 0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL,
  80645. 0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL,
  80646. 0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL,
  80647. 0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL,
  80648. 0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL,
  80649. 0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL,
  80650. 0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL,
  80651. 0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL,
  80652. 0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL,
  80653. 0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL,
  80654. 0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL,
  80655. 0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL,
  80656. 0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL,
  80657. 0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL,
  80658. 0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL,
  80659. 0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL,
  80660. 0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL,
  80661. 0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL,
  80662. 0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL,
  80663. 0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL,
  80664. 0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL,
  80665. 0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL,
  80666. 0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL,
  80667. 0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL,
  80668. 0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL,
  80669. 0x72fd2493UL
  80670. },
  80671. {
  80672. 0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL,
  80673. 0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL,
  80674. 0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL,
  80675. 0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL,
  80676. 0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL,
  80677. 0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL,
  80678. 0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL,
  80679. 0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL,
  80680. 0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL,
  80681. 0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL,
  80682. 0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL,
  80683. 0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL,
  80684. 0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL,
  80685. 0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL,
  80686. 0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL,
  80687. 0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL,
  80688. 0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL,
  80689. 0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL,
  80690. 0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL,
  80691. 0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL,
  80692. 0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL,
  80693. 0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL,
  80694. 0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL,
  80695. 0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL,
  80696. 0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL,
  80697. 0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL,
  80698. 0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL,
  80699. 0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL,
  80700. 0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL,
  80701. 0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL,
  80702. 0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL,
  80703. 0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL,
  80704. 0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL,
  80705. 0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL,
  80706. 0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL,
  80707. 0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL,
  80708. 0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL,
  80709. 0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL,
  80710. 0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL,
  80711. 0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL,
  80712. 0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL,
  80713. 0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL,
  80714. 0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL,
  80715. 0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL,
  80716. 0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL,
  80717. 0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL,
  80718. 0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL,
  80719. 0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL,
  80720. 0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL,
  80721. 0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL,
  80722. 0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL,
  80723. 0xed3498beUL
  80724. },
  80725. {
  80726. 0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL,
  80727. 0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL,
  80728. 0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL,
  80729. 0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL,
  80730. 0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL,
  80731. 0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL,
  80732. 0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL,
  80733. 0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL,
  80734. 0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL,
  80735. 0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL,
  80736. 0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL,
  80737. 0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL,
  80738. 0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL,
  80739. 0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL,
  80740. 0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL,
  80741. 0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL,
  80742. 0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL,
  80743. 0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL,
  80744. 0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL,
  80745. 0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL,
  80746. 0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL,
  80747. 0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL,
  80748. 0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL,
  80749. 0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL,
  80750. 0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL,
  80751. 0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL,
  80752. 0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL,
  80753. 0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL,
  80754. 0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL,
  80755. 0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL,
  80756. 0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL,
  80757. 0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL,
  80758. 0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL,
  80759. 0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL,
  80760. 0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL,
  80761. 0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL,
  80762. 0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL,
  80763. 0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL,
  80764. 0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL,
  80765. 0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL,
  80766. 0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL,
  80767. 0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL,
  80768. 0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL,
  80769. 0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL,
  80770. 0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL,
  80771. 0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL,
  80772. 0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL,
  80773. 0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL,
  80774. 0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL,
  80775. 0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL,
  80776. 0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL,
  80777. 0xf10605deUL
  80778. #endif
  80779. }
  80780. };
  80781. /*** End of inlined file: crc32.h ***/
  80782. #endif /* DYNAMIC_CRC_TABLE */
  80783. /* =========================================================================
  80784. * This function can be used by asm versions of crc32()
  80785. */
  80786. const unsigned long FAR * ZEXPORT get_crc_table()
  80787. {
  80788. #ifdef DYNAMIC_CRC_TABLE
  80789. if (crc_table_empty)
  80790. make_crc_table();
  80791. #endif /* DYNAMIC_CRC_TABLE */
  80792. return (const unsigned long FAR *)crc_table;
  80793. }
  80794. /* ========================================================================= */
  80795. #define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8)
  80796. #define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1
  80797. /* ========================================================================= */
  80798. unsigned long ZEXPORT crc32 (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80799. {
  80800. if (buf == Z_NULL) return 0UL;
  80801. #ifdef DYNAMIC_CRC_TABLE
  80802. if (crc_table_empty)
  80803. make_crc_table();
  80804. #endif /* DYNAMIC_CRC_TABLE */
  80805. #ifdef BYFOUR
  80806. if (sizeof(void *) == sizeof(ptrdiff_t)) {
  80807. u4 endian;
  80808. endian = 1;
  80809. if (*((unsigned char *)(&endian)))
  80810. return crc32_little(crc, buf, len);
  80811. else
  80812. return crc32_big(crc, buf, len);
  80813. }
  80814. #endif /* BYFOUR */
  80815. crc = crc ^ 0xffffffffUL;
  80816. while (len >= 8) {
  80817. DO8;
  80818. len -= 8;
  80819. }
  80820. if (len) do {
  80821. DO1;
  80822. } while (--len);
  80823. return crc ^ 0xffffffffUL;
  80824. }
  80825. #ifdef BYFOUR
  80826. /* ========================================================================= */
  80827. #define DOLIT4 c ^= *buf4++; \
  80828. c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \
  80829. crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24]
  80830. #define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4
  80831. /* ========================================================================= */
  80832. local unsigned long crc32_little(unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80833. {
  80834. register u4 c;
  80835. register const u4 FAR *buf4;
  80836. c = (u4)crc;
  80837. c = ~c;
  80838. while (len && ((ptrdiff_t)buf & 3)) {
  80839. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  80840. len--;
  80841. }
  80842. buf4 = (const u4 FAR *)(const void FAR *)buf;
  80843. while (len >= 32) {
  80844. DOLIT32;
  80845. len -= 32;
  80846. }
  80847. while (len >= 4) {
  80848. DOLIT4;
  80849. len -= 4;
  80850. }
  80851. buf = (const unsigned char FAR *)buf4;
  80852. if (len) do {
  80853. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  80854. } while (--len);
  80855. c = ~c;
  80856. return (unsigned long)c;
  80857. }
  80858. /* ========================================================================= */
  80859. #define DOBIG4 c ^= *++buf4; \
  80860. c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \
  80861. crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24]
  80862. #define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4
  80863. /* ========================================================================= */
  80864. local unsigned long crc32_big (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80865. {
  80866. register u4 c;
  80867. register const u4 FAR *buf4;
  80868. c = REV((u4)crc);
  80869. c = ~c;
  80870. while (len && ((ptrdiff_t)buf & 3)) {
  80871. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  80872. len--;
  80873. }
  80874. buf4 = (const u4 FAR *)(const void FAR *)buf;
  80875. buf4--;
  80876. while (len >= 32) {
  80877. DOBIG32;
  80878. len -= 32;
  80879. }
  80880. while (len >= 4) {
  80881. DOBIG4;
  80882. len -= 4;
  80883. }
  80884. buf4++;
  80885. buf = (const unsigned char FAR *)buf4;
  80886. if (len) do {
  80887. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  80888. } while (--len);
  80889. c = ~c;
  80890. return (unsigned long)(REV(c));
  80891. }
  80892. #endif /* BYFOUR */
  80893. #define GF2_DIM 32 /* dimension of GF(2) vectors (length of CRC) */
  80894. /* ========================================================================= */
  80895. local unsigned long gf2_matrix_times (unsigned long *mat, unsigned long vec)
  80896. {
  80897. unsigned long sum;
  80898. sum = 0;
  80899. while (vec) {
  80900. if (vec & 1)
  80901. sum ^= *mat;
  80902. vec >>= 1;
  80903. mat++;
  80904. }
  80905. return sum;
  80906. }
  80907. /* ========================================================================= */
  80908. local void gf2_matrix_square (unsigned long *square, unsigned long *mat)
  80909. {
  80910. int n;
  80911. for (n = 0; n < GF2_DIM; n++)
  80912. square[n] = gf2_matrix_times(mat, mat[n]);
  80913. }
  80914. /* ========================================================================= */
  80915. uLong ZEXPORT crc32_combine (uLong crc1, uLong crc2, z_off_t len2)
  80916. {
  80917. int n;
  80918. unsigned long row;
  80919. unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */
  80920. unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */
  80921. /* degenerate case */
  80922. if (len2 == 0)
  80923. return crc1;
  80924. /* put operator for one zero bit in odd */
  80925. odd[0] = 0xedb88320L; /* CRC-32 polynomial */
  80926. row = 1;
  80927. for (n = 1; n < GF2_DIM; n++) {
  80928. odd[n] = row;
  80929. row <<= 1;
  80930. }
  80931. /* put operator for two zero bits in even */
  80932. gf2_matrix_square(even, odd);
  80933. /* put operator for four zero bits in odd */
  80934. gf2_matrix_square(odd, even);
  80935. /* apply len2 zeros to crc1 (first square will put the operator for one
  80936. zero byte, eight zero bits, in even) */
  80937. do {
  80938. /* apply zeros operator for this bit of len2 */
  80939. gf2_matrix_square(even, odd);
  80940. if (len2 & 1)
  80941. crc1 = gf2_matrix_times(even, crc1);
  80942. len2 >>= 1;
  80943. /* if no more bits set, then done */
  80944. if (len2 == 0)
  80945. break;
  80946. /* another iteration of the loop with odd and even swapped */
  80947. gf2_matrix_square(odd, even);
  80948. if (len2 & 1)
  80949. crc1 = gf2_matrix_times(odd, crc1);
  80950. len2 >>= 1;
  80951. /* if no more bits set, then done */
  80952. } while (len2 != 0);
  80953. /* return combined crc */
  80954. crc1 ^= crc2;
  80955. return crc1;
  80956. }
  80957. /*** End of inlined file: crc32.c ***/
  80958. /*** Start of inlined file: deflate.c ***/
  80959. /*
  80960. * ALGORITHM
  80961. *
  80962. * The "deflation" process depends on being able to identify portions
  80963. * of the input text which are identical to earlier input (within a
  80964. * sliding window trailing behind the input currently being processed).
  80965. *
  80966. * The most straightforward technique turns out to be the fastest for
  80967. * most input files: try all possible matches and select the longest.
  80968. * The key feature of this algorithm is that insertions into the string
  80969. * dictionary are very simple and thus fast, and deletions are avoided
  80970. * completely. Insertions are performed at each input character, whereas
  80971. * string matches are performed only when the previous match ends. So it
  80972. * is preferable to spend more time in matches to allow very fast string
  80973. * insertions and avoid deletions. The matching algorithm for small
  80974. * strings is inspired from that of Rabin & Karp. A brute force approach
  80975. * is used to find longer strings when a small match has been found.
  80976. * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
  80977. * (by Leonid Broukhis).
  80978. * A previous version of this file used a more sophisticated algorithm
  80979. * (by Fiala and Greene) which is guaranteed to run in linear amortized
  80980. * time, but has a larger average cost, uses more memory and is patented.
  80981. * However the F&G algorithm may be faster for some highly redundant
  80982. * files if the parameter max_chain_length (described below) is too large.
  80983. *
  80984. * ACKNOWLEDGEMENTS
  80985. *
  80986. * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
  80987. * I found it in 'freeze' written by Leonid Broukhis.
  80988. * Thanks to many people for bug reports and testing.
  80989. *
  80990. * REFERENCES
  80991. *
  80992. * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
  80993. * Available in http://www.ietf.org/rfc/rfc1951.txt
  80994. *
  80995. * A description of the Rabin and Karp algorithm is given in the book
  80996. * "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
  80997. *
  80998. * Fiala,E.R., and Greene,D.H.
  80999. * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
  81000. *
  81001. */
  81002. /* @(#) $Id: deflate.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  81003. /*** Start of inlined file: deflate.h ***/
  81004. /* WARNING: this file should *not* be used by applications. It is
  81005. part of the implementation of the compression library and is
  81006. subject to change. Applications should only use zlib.h.
  81007. */
  81008. /* @(#) $Id: deflate.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  81009. #ifndef DEFLATE_H
  81010. #define DEFLATE_H
  81011. /* define NO_GZIP when compiling if you want to disable gzip header and
  81012. trailer creation by deflate(). NO_GZIP would be used to avoid linking in
  81013. the crc code when it is not needed. For shared libraries, gzip encoding
  81014. should be left enabled. */
  81015. #ifndef NO_GZIP
  81016. # define GZIP
  81017. #endif
  81018. #define NO_DUMMY_DECL
  81019. /* ===========================================================================
  81020. * Internal compression state.
  81021. */
  81022. #define LENGTH_CODES 29
  81023. /* number of length codes, not counting the special END_BLOCK code */
  81024. #define LITERALS 256
  81025. /* number of literal bytes 0..255 */
  81026. #define L_CODES (LITERALS+1+LENGTH_CODES)
  81027. /* number of Literal or Length codes, including the END_BLOCK code */
  81028. #define D_CODES 30
  81029. /* number of distance codes */
  81030. #define BL_CODES 19
  81031. /* number of codes used to transfer the bit lengths */
  81032. #define HEAP_SIZE (2*L_CODES+1)
  81033. /* maximum heap size */
  81034. #define MAX_BITS 15
  81035. /* All codes must not exceed MAX_BITS bits */
  81036. #define INIT_STATE 42
  81037. #define EXTRA_STATE 69
  81038. #define NAME_STATE 73
  81039. #define COMMENT_STATE 91
  81040. #define HCRC_STATE 103
  81041. #define BUSY_STATE 113
  81042. #define FINISH_STATE 666
  81043. /* Stream status */
  81044. /* Data structure describing a single value and its code string. */
  81045. typedef struct ct_data_s {
  81046. union {
  81047. ush freq; /* frequency count */
  81048. ush code; /* bit string */
  81049. } fc;
  81050. union {
  81051. ush dad; /* father node in Huffman tree */
  81052. ush len; /* length of bit string */
  81053. } dl;
  81054. } FAR ct_data;
  81055. #define Freq fc.freq
  81056. #define Code fc.code
  81057. #define Dad dl.dad
  81058. #define Len dl.len
  81059. typedef struct static_tree_desc_s static_tree_desc;
  81060. typedef struct tree_desc_s {
  81061. ct_data *dyn_tree; /* the dynamic tree */
  81062. int max_code; /* largest code with non zero frequency */
  81063. static_tree_desc *stat_desc; /* the corresponding static tree */
  81064. } FAR tree_desc;
  81065. typedef ush Pos;
  81066. typedef Pos FAR Posf;
  81067. typedef unsigned IPos;
  81068. /* A Pos is an index in the character window. We use short instead of int to
  81069. * save space in the various tables. IPos is used only for parameter passing.
  81070. */
  81071. typedef struct internal_state {
  81072. z_streamp strm; /* pointer back to this zlib stream */
  81073. int status; /* as the name implies */
  81074. Bytef *pending_buf; /* output still pending */
  81075. ulg pending_buf_size; /* size of pending_buf */
  81076. Bytef *pending_out; /* next pending byte to output to the stream */
  81077. uInt pending; /* nb of bytes in the pending buffer */
  81078. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  81079. gz_headerp gzhead; /* gzip header information to write */
  81080. uInt gzindex; /* where in extra, name, or comment */
  81081. Byte method; /* STORED (for zip only) or DEFLATED */
  81082. int last_flush; /* value of flush param for previous deflate call */
  81083. /* used by deflate.c: */
  81084. uInt w_size; /* LZ77 window size (32K by default) */
  81085. uInt w_bits; /* log2(w_size) (8..16) */
  81086. uInt w_mask; /* w_size - 1 */
  81087. Bytef *window;
  81088. /* Sliding window. Input bytes are read into the second half of the window,
  81089. * and move to the first half later to keep a dictionary of at least wSize
  81090. * bytes. With this organization, matches are limited to a distance of
  81091. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  81092. * performed with a length multiple of the block size. Also, it limits
  81093. * the window size to 64K, which is quite useful on MSDOS.
  81094. * To do: use the user input buffer as sliding window.
  81095. */
  81096. ulg window_size;
  81097. /* Actual size of window: 2*wSize, except when the user input buffer
  81098. * is directly used as sliding window.
  81099. */
  81100. Posf *prev;
  81101. /* Link to older string with same hash index. To limit the size of this
  81102. * array to 64K, this link is maintained only for the last 32K strings.
  81103. * An index in this array is thus a window index modulo 32K.
  81104. */
  81105. Posf *head; /* Heads of the hash chains or NIL. */
  81106. uInt ins_h; /* hash index of string to be inserted */
  81107. uInt hash_size; /* number of elements in hash table */
  81108. uInt hash_bits; /* log2(hash_size) */
  81109. uInt hash_mask; /* hash_size-1 */
  81110. uInt hash_shift;
  81111. /* Number of bits by which ins_h must be shifted at each input
  81112. * step. It must be such that after MIN_MATCH steps, the oldest
  81113. * byte no longer takes part in the hash key, that is:
  81114. * hash_shift * MIN_MATCH >= hash_bits
  81115. */
  81116. long block_start;
  81117. /* Window position at the beginning of the current output block. Gets
  81118. * negative when the window is moved backwards.
  81119. */
  81120. uInt match_length; /* length of best match */
  81121. IPos prev_match; /* previous match */
  81122. int match_available; /* set if previous match exists */
  81123. uInt strstart; /* start of string to insert */
  81124. uInt match_start; /* start of matching string */
  81125. uInt lookahead; /* number of valid bytes ahead in window */
  81126. uInt prev_length;
  81127. /* Length of the best match at previous step. Matches not greater than this
  81128. * are discarded. This is used in the lazy match evaluation.
  81129. */
  81130. uInt max_chain_length;
  81131. /* To speed up deflation, hash chains are never searched beyond this
  81132. * length. A higher limit improves compression ratio but degrades the
  81133. * speed.
  81134. */
  81135. uInt max_lazy_match;
  81136. /* Attempt to find a better match only when the current match is strictly
  81137. * smaller than this value. This mechanism is used only for compression
  81138. * levels >= 4.
  81139. */
  81140. # define max_insert_length max_lazy_match
  81141. /* Insert new strings in the hash table only if the match length is not
  81142. * greater than this length. This saves time but degrades compression.
  81143. * max_insert_length is used only for compression levels <= 3.
  81144. */
  81145. int level; /* compression level (1..9) */
  81146. int strategy; /* favor or force Huffman coding*/
  81147. uInt good_match;
  81148. /* Use a faster search when the previous match is longer than this */
  81149. int nice_match; /* Stop searching when current match exceeds this */
  81150. /* used by trees.c: */
  81151. /* Didn't use ct_data typedef below to supress compiler warning */
  81152. struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  81153. struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  81154. struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  81155. struct tree_desc_s l_desc; /* desc. for literal tree */
  81156. struct tree_desc_s d_desc; /* desc. for distance tree */
  81157. struct tree_desc_s bl_desc; /* desc. for bit length tree */
  81158. ush bl_count[MAX_BITS+1];
  81159. /* number of codes at each bit length for an optimal tree */
  81160. int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  81161. int heap_len; /* number of elements in the heap */
  81162. int heap_max; /* element of largest frequency */
  81163. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  81164. * The same heap array is used to build all trees.
  81165. */
  81166. uch depth[2*L_CODES+1];
  81167. /* Depth of each subtree used as tie breaker for trees of equal frequency
  81168. */
  81169. uchf *l_buf; /* buffer for literals or lengths */
  81170. uInt lit_bufsize;
  81171. /* Size of match buffer for literals/lengths. There are 4 reasons for
  81172. * limiting lit_bufsize to 64K:
  81173. * - frequencies can be kept in 16 bit counters
  81174. * - if compression is not successful for the first block, all input
  81175. * data is still in the window so we can still emit a stored block even
  81176. * when input comes from standard input. (This can also be done for
  81177. * all blocks if lit_bufsize is not greater than 32K.)
  81178. * - if compression is not successful for a file smaller than 64K, we can
  81179. * even emit a stored file instead of a stored block (saving 5 bytes).
  81180. * This is applicable only for zip (not gzip or zlib).
  81181. * - creating new Huffman trees less frequently may not provide fast
  81182. * adaptation to changes in the input data statistics. (Take for
  81183. * example a binary file with poorly compressible code followed by
  81184. * a highly compressible string table.) Smaller buffer sizes give
  81185. * fast adaptation but have of course the overhead of transmitting
  81186. * trees more frequently.
  81187. * - I can't count above 4
  81188. */
  81189. uInt last_lit; /* running index in l_buf */
  81190. ushf *d_buf;
  81191. /* Buffer for distances. To simplify the code, d_buf and l_buf have
  81192. * the same number of elements. To use different lengths, an extra flag
  81193. * array would be necessary.
  81194. */
  81195. ulg opt_len; /* bit length of current block with optimal trees */
  81196. ulg static_len; /* bit length of current block with static trees */
  81197. uInt matches; /* number of string matches in current block */
  81198. int last_eob_len; /* bit length of EOB code for last block */
  81199. #ifdef DEBUG
  81200. ulg compressed_len; /* total bit length of compressed file mod 2^32 */
  81201. ulg bits_sent; /* bit length of compressed data sent mod 2^32 */
  81202. #endif
  81203. ush bi_buf;
  81204. /* Output buffer. bits are inserted starting at the bottom (least
  81205. * significant bits).
  81206. */
  81207. int bi_valid;
  81208. /* Number of valid bits in bi_buf. All bits above the last valid bit
  81209. * are always zero.
  81210. */
  81211. } FAR deflate_state;
  81212. /* Output a byte on the stream.
  81213. * IN assertion: there is enough room in pending_buf.
  81214. */
  81215. #define put_byte(s, c) {s->pending_buf[s->pending++] = (c);}
  81216. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  81217. /* Minimum amount of lookahead, except at the end of the input file.
  81218. * See deflate.c for comments about the MIN_MATCH+1.
  81219. */
  81220. #define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD)
  81221. /* In order to simplify the code, particularly on 16 bit machines, match
  81222. * distances are limited to MAX_DIST instead of WSIZE.
  81223. */
  81224. /* in trees.c */
  81225. void _tr_init OF((deflate_state *s));
  81226. int _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc));
  81227. void _tr_flush_block OF((deflate_state *s, charf *buf, ulg stored_len,
  81228. int eof));
  81229. void _tr_align OF((deflate_state *s));
  81230. void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len,
  81231. int eof));
  81232. #define d_code(dist) \
  81233. ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)])
  81234. /* Mapping from a distance to a distance code. dist is the distance - 1 and
  81235. * must not have side effects. _dist_code[256] and _dist_code[257] are never
  81236. * used.
  81237. */
  81238. #ifndef DEBUG
  81239. /* Inline versions of _tr_tally for speed: */
  81240. #if defined(GEN_TREES_H) || !defined(STDC)
  81241. extern uch _length_code[];
  81242. extern uch _dist_code[];
  81243. #else
  81244. extern const uch _length_code[];
  81245. extern const uch _dist_code[];
  81246. #endif
  81247. # define _tr_tally_lit(s, c, flush) \
  81248. { uch cc = (c); \
  81249. s->d_buf[s->last_lit] = 0; \
  81250. s->l_buf[s->last_lit++] = cc; \
  81251. s->dyn_ltree[cc].Freq++; \
  81252. flush = (s->last_lit == s->lit_bufsize-1); \
  81253. }
  81254. # define _tr_tally_dist(s, distance, length, flush) \
  81255. { uch len = (length); \
  81256. ush dist = (distance); \
  81257. s->d_buf[s->last_lit] = dist; \
  81258. s->l_buf[s->last_lit++] = len; \
  81259. dist--; \
  81260. s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \
  81261. s->dyn_dtree[d_code(dist)].Freq++; \
  81262. flush = (s->last_lit == s->lit_bufsize-1); \
  81263. }
  81264. #else
  81265. # define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c)
  81266. # define _tr_tally_dist(s, distance, length, flush) \
  81267. flush = _tr_tally(s, distance, length)
  81268. #endif
  81269. #endif /* DEFLATE_H */
  81270. /*** End of inlined file: deflate.h ***/
  81271. const char deflate_copyright[] =
  81272. " deflate 1.2.3 Copyright 1995-2005 Jean-loup Gailly ";
  81273. /*
  81274. If you use the zlib library in a product, an acknowledgment is welcome
  81275. in the documentation of your product. If for some reason you cannot
  81276. include such an acknowledgment, I would appreciate that you keep this
  81277. copyright string in the executable of your product.
  81278. */
  81279. /* ===========================================================================
  81280. * Function prototypes.
  81281. */
  81282. typedef enum {
  81283. need_more, /* block not completed, need more input or more output */
  81284. block_done, /* block flush performed */
  81285. finish_started, /* finish started, need only more output at next deflate */
  81286. finish_done /* finish done, accept no more input or output */
  81287. } block_state;
  81288. typedef block_state (*compress_func) OF((deflate_state *s, int flush));
  81289. /* Compression function. Returns the block state after the call. */
  81290. local void fill_window OF((deflate_state *s));
  81291. local block_state deflate_stored OF((deflate_state *s, int flush));
  81292. local block_state deflate_fast OF((deflate_state *s, int flush));
  81293. #ifndef FASTEST
  81294. local block_state deflate_slow OF((deflate_state *s, int flush));
  81295. #endif
  81296. local void lm_init OF((deflate_state *s));
  81297. local void putShortMSB OF((deflate_state *s, uInt b));
  81298. local void flush_pending OF((z_streamp strm));
  81299. local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size));
  81300. #ifndef FASTEST
  81301. #ifdef ASMV
  81302. void match_init OF((void)); /* asm code initialization */
  81303. uInt longest_match OF((deflate_state *s, IPos cur_match));
  81304. #else
  81305. local uInt longest_match OF((deflate_state *s, IPos cur_match));
  81306. #endif
  81307. #endif
  81308. local uInt longest_match_fast OF((deflate_state *s, IPos cur_match));
  81309. #ifdef DEBUG
  81310. local void check_match OF((deflate_state *s, IPos start, IPos match,
  81311. int length));
  81312. #endif
  81313. /* ===========================================================================
  81314. * Local data
  81315. */
  81316. #define NIL 0
  81317. /* Tail of hash chains */
  81318. #ifndef TOO_FAR
  81319. # define TOO_FAR 4096
  81320. #endif
  81321. /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
  81322. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  81323. /* Minimum amount of lookahead, except at the end of the input file.
  81324. * See deflate.c for comments about the MIN_MATCH+1.
  81325. */
  81326. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  81327. * the desired pack level (0..9). The values given below have been tuned to
  81328. * exclude worst case performance for pathological files. Better values may be
  81329. * found for specific files.
  81330. */
  81331. typedef struct config_s {
  81332. ush good_length; /* reduce lazy search above this match length */
  81333. ush max_lazy; /* do not perform lazy search above this match length */
  81334. ush nice_length; /* quit search above this match length */
  81335. ush max_chain;
  81336. compress_func func;
  81337. } config;
  81338. #ifdef FASTEST
  81339. local const config configuration_table[2] = {
  81340. /* good lazy nice chain */
  81341. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  81342. /* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */
  81343. #else
  81344. local const config configuration_table[10] = {
  81345. /* good lazy nice chain */
  81346. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  81347. /* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */
  81348. /* 2 */ {4, 5, 16, 8, deflate_fast},
  81349. /* 3 */ {4, 6, 32, 32, deflate_fast},
  81350. /* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */
  81351. /* 5 */ {8, 16, 32, 32, deflate_slow},
  81352. /* 6 */ {8, 16, 128, 128, deflate_slow},
  81353. /* 7 */ {8, 32, 128, 256, deflate_slow},
  81354. /* 8 */ {32, 128, 258, 1024, deflate_slow},
  81355. /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
  81356. #endif
  81357. /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
  81358. * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
  81359. * meaning.
  81360. */
  81361. #define EQUAL 0
  81362. /* result of memcmp for equal strings */
  81363. #ifndef NO_DUMMY_DECL
  81364. struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
  81365. #endif
  81366. /* ===========================================================================
  81367. * Update a hash value with the given input byte
  81368. * IN assertion: all calls to to UPDATE_HASH are made with consecutive
  81369. * input characters, so that a running hash key can be computed from the
  81370. * previous key instead of complete recalculation each time.
  81371. */
  81372. #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
  81373. /* ===========================================================================
  81374. * Insert string str in the dictionary and set match_head to the previous head
  81375. * of the hash chain (the most recent string with same hash key). Return
  81376. * the previous length of the hash chain.
  81377. * If this file is compiled with -DFASTEST, the compression level is forced
  81378. * to 1, and no hash chains are maintained.
  81379. * IN assertion: all calls to to INSERT_STRING are made with consecutive
  81380. * input characters and the first MIN_MATCH bytes of str are valid
  81381. * (except for the last MIN_MATCH-1 bytes of the input file).
  81382. */
  81383. #ifdef FASTEST
  81384. #define INSERT_STRING(s, str, match_head) \
  81385. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  81386. match_head = s->head[s->ins_h], \
  81387. s->head[s->ins_h] = (Pos)(str))
  81388. #else
  81389. #define INSERT_STRING(s, str, match_head) \
  81390. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  81391. match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
  81392. s->head[s->ins_h] = (Pos)(str))
  81393. #endif
  81394. /* ===========================================================================
  81395. * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
  81396. * prev[] will be initialized on the fly.
  81397. */
  81398. #define CLEAR_HASH(s) \
  81399. s->head[s->hash_size-1] = NIL; \
  81400. zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
  81401. /* ========================================================================= */
  81402. int ZEXPORT deflateInit_(z_streamp strm, int level, const char *version, int stream_size)
  81403. {
  81404. return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
  81405. Z_DEFAULT_STRATEGY, version, stream_size);
  81406. /* To do: ignore strm->next_in if we use it as window */
  81407. }
  81408. /* ========================================================================= */
  81409. int ZEXPORT deflateInit2_ (z_streamp strm, int level, int method, int windowBits, int memLevel, int strategy, const char *version, int stream_size)
  81410. {
  81411. deflate_state *s;
  81412. int wrap = 1;
  81413. static const char my_version[] = ZLIB_VERSION;
  81414. ushf *overlay;
  81415. /* We overlay pending_buf and d_buf+l_buf. This works since the average
  81416. * output size for (length,distance) codes is <= 24 bits.
  81417. */
  81418. if (version == Z_NULL || version[0] != my_version[0] ||
  81419. stream_size != sizeof(z_stream)) {
  81420. return Z_VERSION_ERROR;
  81421. }
  81422. if (strm == Z_NULL) return Z_STREAM_ERROR;
  81423. strm->msg = Z_NULL;
  81424. if (strm->zalloc == (alloc_func)0) {
  81425. strm->zalloc = zcalloc;
  81426. strm->opaque = (voidpf)0;
  81427. }
  81428. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  81429. #ifdef FASTEST
  81430. if (level != 0) level = 1;
  81431. #else
  81432. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  81433. #endif
  81434. if (windowBits < 0) { /* suppress zlib wrapper */
  81435. wrap = 0;
  81436. windowBits = -windowBits;
  81437. }
  81438. #ifdef GZIP
  81439. else if (windowBits > 15) {
  81440. wrap = 2; /* write gzip wrapper instead */
  81441. windowBits -= 16;
  81442. }
  81443. #endif
  81444. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
  81445. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  81446. strategy < 0 || strategy > Z_FIXED) {
  81447. return Z_STREAM_ERROR;
  81448. }
  81449. if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */
  81450. s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
  81451. if (s == Z_NULL) return Z_MEM_ERROR;
  81452. strm->state = (struct internal_state FAR *)s;
  81453. s->strm = strm;
  81454. s->wrap = wrap;
  81455. s->gzhead = Z_NULL;
  81456. s->w_bits = windowBits;
  81457. s->w_size = 1 << s->w_bits;
  81458. s->w_mask = s->w_size - 1;
  81459. s->hash_bits = memLevel + 7;
  81460. s->hash_size = 1 << s->hash_bits;
  81461. s->hash_mask = s->hash_size - 1;
  81462. s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
  81463. s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
  81464. s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos));
  81465. s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos));
  81466. s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  81467. overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  81468. s->pending_buf = (uchf *) overlay;
  81469. s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
  81470. if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
  81471. s->pending_buf == Z_NULL) {
  81472. s->status = FINISH_STATE;
  81473. strm->msg = (char*)ERR_MSG(Z_MEM_ERROR);
  81474. deflateEnd (strm);
  81475. return Z_MEM_ERROR;
  81476. }
  81477. s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  81478. s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  81479. s->level = level;
  81480. s->strategy = strategy;
  81481. s->method = (Byte)method;
  81482. return deflateReset(strm);
  81483. }
  81484. /* ========================================================================= */
  81485. int ZEXPORT deflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  81486. {
  81487. deflate_state *s;
  81488. uInt length = dictLength;
  81489. uInt n;
  81490. IPos hash_head = 0;
  81491. if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL ||
  81492. strm->state->wrap == 2 ||
  81493. (strm->state->wrap == 1 && strm->state->status != INIT_STATE))
  81494. return Z_STREAM_ERROR;
  81495. s = strm->state;
  81496. if (s->wrap)
  81497. strm->adler = adler32(strm->adler, dictionary, dictLength);
  81498. if (length < MIN_MATCH) return Z_OK;
  81499. if (length > MAX_DIST(s)) {
  81500. length = MAX_DIST(s);
  81501. dictionary += dictLength - length; /* use the tail of the dictionary */
  81502. }
  81503. zmemcpy(s->window, dictionary, length);
  81504. s->strstart = length;
  81505. s->block_start = (long)length;
  81506. /* Insert all strings in the hash table (except for the last two bytes).
  81507. * s->lookahead stays null, so s->ins_h will be recomputed at the next
  81508. * call of fill_window.
  81509. */
  81510. s->ins_h = s->window[0];
  81511. UPDATE_HASH(s, s->ins_h, s->window[1]);
  81512. for (n = 0; n <= length - MIN_MATCH; n++) {
  81513. INSERT_STRING(s, n, hash_head);
  81514. }
  81515. if (hash_head) hash_head = 0; /* to make compiler happy */
  81516. return Z_OK;
  81517. }
  81518. /* ========================================================================= */
  81519. int ZEXPORT deflateReset (z_streamp strm)
  81520. {
  81521. deflate_state *s;
  81522. if (strm == Z_NULL || strm->state == Z_NULL ||
  81523. strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) {
  81524. return Z_STREAM_ERROR;
  81525. }
  81526. strm->total_in = strm->total_out = 0;
  81527. strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
  81528. strm->data_type = Z_UNKNOWN;
  81529. s = (deflate_state *)strm->state;
  81530. s->pending = 0;
  81531. s->pending_out = s->pending_buf;
  81532. if (s->wrap < 0) {
  81533. s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
  81534. }
  81535. s->status = s->wrap ? INIT_STATE : BUSY_STATE;
  81536. strm->adler =
  81537. #ifdef GZIP
  81538. s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
  81539. #endif
  81540. adler32(0L, Z_NULL, 0);
  81541. s->last_flush = Z_NO_FLUSH;
  81542. _tr_init(s);
  81543. lm_init(s);
  81544. return Z_OK;
  81545. }
  81546. /* ========================================================================= */
  81547. int ZEXPORT deflateSetHeader (z_streamp strm, gz_headerp head)
  81548. {
  81549. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81550. if (strm->state->wrap != 2) return Z_STREAM_ERROR;
  81551. strm->state->gzhead = head;
  81552. return Z_OK;
  81553. }
  81554. /* ========================================================================= */
  81555. int ZEXPORT deflatePrime (z_streamp strm, int bits, int value)
  81556. {
  81557. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81558. strm->state->bi_valid = bits;
  81559. strm->state->bi_buf = (ush)(value & ((1 << bits) - 1));
  81560. return Z_OK;
  81561. }
  81562. /* ========================================================================= */
  81563. int ZEXPORT deflateParams (z_streamp strm, int level, int strategy)
  81564. {
  81565. deflate_state *s;
  81566. compress_func func;
  81567. int err = Z_OK;
  81568. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81569. s = strm->state;
  81570. #ifdef FASTEST
  81571. if (level != 0) level = 1;
  81572. #else
  81573. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  81574. #endif
  81575. if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
  81576. return Z_STREAM_ERROR;
  81577. }
  81578. func = configuration_table[s->level].func;
  81579. if (func != configuration_table[level].func && strm->total_in != 0) {
  81580. /* Flush the last buffer: */
  81581. err = deflate(strm, Z_PARTIAL_FLUSH);
  81582. }
  81583. if (s->level != level) {
  81584. s->level = level;
  81585. s->max_lazy_match = configuration_table[level].max_lazy;
  81586. s->good_match = configuration_table[level].good_length;
  81587. s->nice_match = configuration_table[level].nice_length;
  81588. s->max_chain_length = configuration_table[level].max_chain;
  81589. }
  81590. s->strategy = strategy;
  81591. return err;
  81592. }
  81593. /* ========================================================================= */
  81594. int ZEXPORT deflateTune (z_streamp strm, int good_length, int max_lazy, int nice_length, int max_chain)
  81595. {
  81596. deflate_state *s;
  81597. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81598. s = strm->state;
  81599. s->good_match = good_length;
  81600. s->max_lazy_match = max_lazy;
  81601. s->nice_match = nice_length;
  81602. s->max_chain_length = max_chain;
  81603. return Z_OK;
  81604. }
  81605. /* =========================================================================
  81606. * For the default windowBits of 15 and memLevel of 8, this function returns
  81607. * a close to exact, as well as small, upper bound on the compressed size.
  81608. * They are coded as constants here for a reason--if the #define's are
  81609. * changed, then this function needs to be changed as well. The return
  81610. * value for 15 and 8 only works for those exact settings.
  81611. *
  81612. * For any setting other than those defaults for windowBits and memLevel,
  81613. * the value returned is a conservative worst case for the maximum expansion
  81614. * resulting from using fixed blocks instead of stored blocks, which deflate
  81615. * can emit on compressed data for some combinations of the parameters.
  81616. *
  81617. * This function could be more sophisticated to provide closer upper bounds
  81618. * for every combination of windowBits and memLevel, as well as wrap.
  81619. * But even the conservative upper bound of about 14% expansion does not
  81620. * seem onerous for output buffer allocation.
  81621. */
  81622. uLong ZEXPORT deflateBound (z_streamp strm, uLong sourceLen)
  81623. {
  81624. deflate_state *s;
  81625. uLong destLen;
  81626. /* conservative upper bound */
  81627. destLen = sourceLen +
  81628. ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 11;
  81629. /* if can't get parameters, return conservative bound */
  81630. if (strm == Z_NULL || strm->state == Z_NULL)
  81631. return destLen;
  81632. /* if not default parameters, return conservative bound */
  81633. s = strm->state;
  81634. if (s->w_bits != 15 || s->hash_bits != 8 + 7)
  81635. return destLen;
  81636. /* default settings: return tight bound for that case */
  81637. return compressBound(sourceLen);
  81638. }
  81639. /* =========================================================================
  81640. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  81641. * IN assertion: the stream state is correct and there is enough room in
  81642. * pending_buf.
  81643. */
  81644. local void putShortMSB (deflate_state *s, uInt b)
  81645. {
  81646. put_byte(s, (Byte)(b >> 8));
  81647. put_byte(s, (Byte)(b & 0xff));
  81648. }
  81649. /* =========================================================================
  81650. * Flush as much pending output as possible. All deflate() output goes
  81651. * through this function so some applications may wish to modify it
  81652. * to avoid allocating a large strm->next_out buffer and copying into it.
  81653. * (See also read_buf()).
  81654. */
  81655. local void flush_pending (z_streamp strm)
  81656. {
  81657. unsigned len = strm->state->pending;
  81658. if (len > strm->avail_out) len = strm->avail_out;
  81659. if (len == 0) return;
  81660. zmemcpy(strm->next_out, strm->state->pending_out, len);
  81661. strm->next_out += len;
  81662. strm->state->pending_out += len;
  81663. strm->total_out += len;
  81664. strm->avail_out -= len;
  81665. strm->state->pending -= len;
  81666. if (strm->state->pending == 0) {
  81667. strm->state->pending_out = strm->state->pending_buf;
  81668. }
  81669. }
  81670. /* ========================================================================= */
  81671. int ZEXPORT deflate (z_streamp strm, int flush)
  81672. {
  81673. int old_flush; /* value of flush param for previous deflate call */
  81674. deflate_state *s;
  81675. if (strm == Z_NULL || strm->state == Z_NULL ||
  81676. flush > Z_FINISH || flush < 0) {
  81677. return Z_STREAM_ERROR;
  81678. }
  81679. s = strm->state;
  81680. if (strm->next_out == Z_NULL ||
  81681. (strm->next_in == Z_NULL && strm->avail_in != 0) ||
  81682. (s->status == FINISH_STATE && flush != Z_FINISH)) {
  81683. ERR_RETURN(strm, Z_STREAM_ERROR);
  81684. }
  81685. if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
  81686. s->strm = strm; /* just in case */
  81687. old_flush = s->last_flush;
  81688. s->last_flush = flush;
  81689. /* Write the header */
  81690. if (s->status == INIT_STATE) {
  81691. #ifdef GZIP
  81692. if (s->wrap == 2) {
  81693. strm->adler = crc32(0L, Z_NULL, 0);
  81694. put_byte(s, 31);
  81695. put_byte(s, 139);
  81696. put_byte(s, 8);
  81697. if (s->gzhead == NULL) {
  81698. put_byte(s, 0);
  81699. put_byte(s, 0);
  81700. put_byte(s, 0);
  81701. put_byte(s, 0);
  81702. put_byte(s, 0);
  81703. put_byte(s, s->level == 9 ? 2 :
  81704. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  81705. 4 : 0));
  81706. put_byte(s, OS_CODE);
  81707. s->status = BUSY_STATE;
  81708. }
  81709. else {
  81710. put_byte(s, (s->gzhead->text ? 1 : 0) +
  81711. (s->gzhead->hcrc ? 2 : 0) +
  81712. (s->gzhead->extra == Z_NULL ? 0 : 4) +
  81713. (s->gzhead->name == Z_NULL ? 0 : 8) +
  81714. (s->gzhead->comment == Z_NULL ? 0 : 16)
  81715. );
  81716. put_byte(s, (Byte)(s->gzhead->time & 0xff));
  81717. put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));
  81718. put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));
  81719. put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));
  81720. put_byte(s, s->level == 9 ? 2 :
  81721. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  81722. 4 : 0));
  81723. put_byte(s, s->gzhead->os & 0xff);
  81724. if (s->gzhead->extra != NULL) {
  81725. put_byte(s, s->gzhead->extra_len & 0xff);
  81726. put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
  81727. }
  81728. if (s->gzhead->hcrc)
  81729. strm->adler = crc32(strm->adler, s->pending_buf,
  81730. s->pending);
  81731. s->gzindex = 0;
  81732. s->status = EXTRA_STATE;
  81733. }
  81734. }
  81735. else
  81736. #endif
  81737. {
  81738. uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
  81739. uInt level_flags;
  81740. if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
  81741. level_flags = 0;
  81742. else if (s->level < 6)
  81743. level_flags = 1;
  81744. else if (s->level == 6)
  81745. level_flags = 2;
  81746. else
  81747. level_flags = 3;
  81748. header |= (level_flags << 6);
  81749. if (s->strstart != 0) header |= PRESET_DICT;
  81750. header += 31 - (header % 31);
  81751. s->status = BUSY_STATE;
  81752. putShortMSB(s, header);
  81753. /* Save the adler32 of the preset dictionary: */
  81754. if (s->strstart != 0) {
  81755. putShortMSB(s, (uInt)(strm->adler >> 16));
  81756. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  81757. }
  81758. strm->adler = adler32(0L, Z_NULL, 0);
  81759. }
  81760. }
  81761. #ifdef GZIP
  81762. if (s->status == EXTRA_STATE) {
  81763. if (s->gzhead->extra != NULL) {
  81764. uInt beg = s->pending; /* start of bytes to update crc */
  81765. while (s->gzindex < (s->gzhead->extra_len & 0xffff)) {
  81766. if (s->pending == s->pending_buf_size) {
  81767. if (s->gzhead->hcrc && s->pending > beg)
  81768. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81769. s->pending - beg);
  81770. flush_pending(strm);
  81771. beg = s->pending;
  81772. if (s->pending == s->pending_buf_size)
  81773. break;
  81774. }
  81775. put_byte(s, s->gzhead->extra[s->gzindex]);
  81776. s->gzindex++;
  81777. }
  81778. if (s->gzhead->hcrc && s->pending > beg)
  81779. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81780. s->pending - beg);
  81781. if (s->gzindex == s->gzhead->extra_len) {
  81782. s->gzindex = 0;
  81783. s->status = NAME_STATE;
  81784. }
  81785. }
  81786. else
  81787. s->status = NAME_STATE;
  81788. }
  81789. if (s->status == NAME_STATE) {
  81790. if (s->gzhead->name != NULL) {
  81791. uInt beg = s->pending; /* start of bytes to update crc */
  81792. int val;
  81793. do {
  81794. if (s->pending == s->pending_buf_size) {
  81795. if (s->gzhead->hcrc && s->pending > beg)
  81796. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81797. s->pending - beg);
  81798. flush_pending(strm);
  81799. beg = s->pending;
  81800. if (s->pending == s->pending_buf_size) {
  81801. val = 1;
  81802. break;
  81803. }
  81804. }
  81805. val = s->gzhead->name[s->gzindex++];
  81806. put_byte(s, val);
  81807. } while (val != 0);
  81808. if (s->gzhead->hcrc && s->pending > beg)
  81809. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81810. s->pending - beg);
  81811. if (val == 0) {
  81812. s->gzindex = 0;
  81813. s->status = COMMENT_STATE;
  81814. }
  81815. }
  81816. else
  81817. s->status = COMMENT_STATE;
  81818. }
  81819. if (s->status == COMMENT_STATE) {
  81820. if (s->gzhead->comment != NULL) {
  81821. uInt beg = s->pending; /* start of bytes to update crc */
  81822. int val;
  81823. do {
  81824. if (s->pending == s->pending_buf_size) {
  81825. if (s->gzhead->hcrc && s->pending > beg)
  81826. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81827. s->pending - beg);
  81828. flush_pending(strm);
  81829. beg = s->pending;
  81830. if (s->pending == s->pending_buf_size) {
  81831. val = 1;
  81832. break;
  81833. }
  81834. }
  81835. val = s->gzhead->comment[s->gzindex++];
  81836. put_byte(s, val);
  81837. } while (val != 0);
  81838. if (s->gzhead->hcrc && s->pending > beg)
  81839. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81840. s->pending - beg);
  81841. if (val == 0)
  81842. s->status = HCRC_STATE;
  81843. }
  81844. else
  81845. s->status = HCRC_STATE;
  81846. }
  81847. if (s->status == HCRC_STATE) {
  81848. if (s->gzhead->hcrc) {
  81849. if (s->pending + 2 > s->pending_buf_size)
  81850. flush_pending(strm);
  81851. if (s->pending + 2 <= s->pending_buf_size) {
  81852. put_byte(s, (Byte)(strm->adler & 0xff));
  81853. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  81854. strm->adler = crc32(0L, Z_NULL, 0);
  81855. s->status = BUSY_STATE;
  81856. }
  81857. }
  81858. else
  81859. s->status = BUSY_STATE;
  81860. }
  81861. #endif
  81862. /* Flush as much pending output as possible */
  81863. if (s->pending != 0) {
  81864. flush_pending(strm);
  81865. if (strm->avail_out == 0) {
  81866. /* Since avail_out is 0, deflate will be called again with
  81867. * more output space, but possibly with both pending and
  81868. * avail_in equal to zero. There won't be anything to do,
  81869. * but this is not an error situation so make sure we
  81870. * return OK instead of BUF_ERROR at next call of deflate:
  81871. */
  81872. s->last_flush = -1;
  81873. return Z_OK;
  81874. }
  81875. /* Make sure there is something to do and avoid duplicate consecutive
  81876. * flushes. For repeated and useless calls with Z_FINISH, we keep
  81877. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  81878. */
  81879. } else if (strm->avail_in == 0 && flush <= old_flush &&
  81880. flush != Z_FINISH) {
  81881. ERR_RETURN(strm, Z_BUF_ERROR);
  81882. }
  81883. /* User must not provide more input after the first FINISH: */
  81884. if (s->status == FINISH_STATE && strm->avail_in != 0) {
  81885. ERR_RETURN(strm, Z_BUF_ERROR);
  81886. }
  81887. /* Start a new block or continue the current one.
  81888. */
  81889. if (strm->avail_in != 0 || s->lookahead != 0 ||
  81890. (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
  81891. block_state bstate;
  81892. bstate = (*(configuration_table[s->level].func))(s, flush);
  81893. if (bstate == finish_started || bstate == finish_done) {
  81894. s->status = FINISH_STATE;
  81895. }
  81896. if (bstate == need_more || bstate == finish_started) {
  81897. if (strm->avail_out == 0) {
  81898. s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
  81899. }
  81900. return Z_OK;
  81901. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  81902. * of deflate should use the same flush parameter to make sure
  81903. * that the flush is complete. So we don't have to output an
  81904. * empty block here, this will be done at next call. This also
  81905. * ensures that for a very small output buffer, we emit at most
  81906. * one empty block.
  81907. */
  81908. }
  81909. if (bstate == block_done) {
  81910. if (flush == Z_PARTIAL_FLUSH) {
  81911. _tr_align(s);
  81912. } else { /* FULL_FLUSH or SYNC_FLUSH */
  81913. _tr_stored_block(s, (char*)0, 0L, 0);
  81914. /* For a full flush, this empty block will be recognized
  81915. * as a special marker by inflate_sync().
  81916. */
  81917. if (flush == Z_FULL_FLUSH) {
  81918. CLEAR_HASH(s); /* forget history */
  81919. }
  81920. }
  81921. flush_pending(strm);
  81922. if (strm->avail_out == 0) {
  81923. s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  81924. return Z_OK;
  81925. }
  81926. }
  81927. }
  81928. Assert(strm->avail_out > 0, "bug2");
  81929. if (flush != Z_FINISH) return Z_OK;
  81930. if (s->wrap <= 0) return Z_STREAM_END;
  81931. /* Write the trailer */
  81932. #ifdef GZIP
  81933. if (s->wrap == 2) {
  81934. put_byte(s, (Byte)(strm->adler & 0xff));
  81935. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  81936. put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
  81937. put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
  81938. put_byte(s, (Byte)(strm->total_in & 0xff));
  81939. put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
  81940. put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
  81941. put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
  81942. }
  81943. else
  81944. #endif
  81945. {
  81946. putShortMSB(s, (uInt)(strm->adler >> 16));
  81947. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  81948. }
  81949. flush_pending(strm);
  81950. /* If avail_out is zero, the application will call deflate again
  81951. * to flush the rest.
  81952. */
  81953. if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
  81954. return s->pending != 0 ? Z_OK : Z_STREAM_END;
  81955. }
  81956. /* ========================================================================= */
  81957. int ZEXPORT deflateEnd (z_streamp strm)
  81958. {
  81959. int status;
  81960. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81961. status = strm->state->status;
  81962. if (status != INIT_STATE &&
  81963. status != EXTRA_STATE &&
  81964. status != NAME_STATE &&
  81965. status != COMMENT_STATE &&
  81966. status != HCRC_STATE &&
  81967. status != BUSY_STATE &&
  81968. status != FINISH_STATE) {
  81969. return Z_STREAM_ERROR;
  81970. }
  81971. /* Deallocate in reverse order of allocations: */
  81972. TRY_FREE(strm, strm->state->pending_buf);
  81973. TRY_FREE(strm, strm->state->head);
  81974. TRY_FREE(strm, strm->state->prev);
  81975. TRY_FREE(strm, strm->state->window);
  81976. ZFREE(strm, strm->state);
  81977. strm->state = Z_NULL;
  81978. return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
  81979. }
  81980. /* =========================================================================
  81981. * Copy the source state to the destination state.
  81982. * To simplify the source, this is not supported for 16-bit MSDOS (which
  81983. * doesn't have enough memory anyway to duplicate compression states).
  81984. */
  81985. int ZEXPORT deflateCopy (z_streamp dest, z_streamp source)
  81986. {
  81987. #ifdef MAXSEG_64K
  81988. return Z_STREAM_ERROR;
  81989. #else
  81990. deflate_state *ds;
  81991. deflate_state *ss;
  81992. ushf *overlay;
  81993. if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
  81994. return Z_STREAM_ERROR;
  81995. }
  81996. ss = source->state;
  81997. zmemcpy(dest, source, sizeof(z_stream));
  81998. ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
  81999. if (ds == Z_NULL) return Z_MEM_ERROR;
  82000. dest->state = (struct internal_state FAR *) ds;
  82001. zmemcpy(ds, ss, sizeof(deflate_state));
  82002. ds->strm = dest;
  82003. ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
  82004. ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos));
  82005. ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos));
  82006. overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);
  82007. ds->pending_buf = (uchf *) overlay;
  82008. if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
  82009. ds->pending_buf == Z_NULL) {
  82010. deflateEnd (dest);
  82011. return Z_MEM_ERROR;
  82012. }
  82013. /* following zmemcpy do not work for 16-bit MSDOS */
  82014. zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
  82015. zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos));
  82016. zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos));
  82017. zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
  82018. ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
  82019. ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
  82020. ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
  82021. ds->l_desc.dyn_tree = ds->dyn_ltree;
  82022. ds->d_desc.dyn_tree = ds->dyn_dtree;
  82023. ds->bl_desc.dyn_tree = ds->bl_tree;
  82024. return Z_OK;
  82025. #endif /* MAXSEG_64K */
  82026. }
  82027. /* ===========================================================================
  82028. * Read a new buffer from the current input stream, update the adler32
  82029. * and total number of bytes read. All deflate() input goes through
  82030. * this function so some applications may wish to modify it to avoid
  82031. * allocating a large strm->next_in buffer and copying from it.
  82032. * (See also flush_pending()).
  82033. */
  82034. local int read_buf (z_streamp strm, Bytef *buf, unsigned size)
  82035. {
  82036. unsigned len = strm->avail_in;
  82037. if (len > size) len = size;
  82038. if (len == 0) return 0;
  82039. strm->avail_in -= len;
  82040. if (strm->state->wrap == 1) {
  82041. strm->adler = adler32(strm->adler, strm->next_in, len);
  82042. }
  82043. #ifdef GZIP
  82044. else if (strm->state->wrap == 2) {
  82045. strm->adler = crc32(strm->adler, strm->next_in, len);
  82046. }
  82047. #endif
  82048. zmemcpy(buf, strm->next_in, len);
  82049. strm->next_in += len;
  82050. strm->total_in += len;
  82051. return (int)len;
  82052. }
  82053. /* ===========================================================================
  82054. * Initialize the "longest match" routines for a new zlib stream
  82055. */
  82056. local void lm_init (deflate_state *s)
  82057. {
  82058. s->window_size = (ulg)2L*s->w_size;
  82059. CLEAR_HASH(s);
  82060. /* Set the default configuration parameters:
  82061. */
  82062. s->max_lazy_match = configuration_table[s->level].max_lazy;
  82063. s->good_match = configuration_table[s->level].good_length;
  82064. s->nice_match = configuration_table[s->level].nice_length;
  82065. s->max_chain_length = configuration_table[s->level].max_chain;
  82066. s->strstart = 0;
  82067. s->block_start = 0L;
  82068. s->lookahead = 0;
  82069. s->match_length = s->prev_length = MIN_MATCH-1;
  82070. s->match_available = 0;
  82071. s->ins_h = 0;
  82072. #ifndef FASTEST
  82073. #ifdef ASMV
  82074. match_init(); /* initialize the asm code */
  82075. #endif
  82076. #endif
  82077. }
  82078. #ifndef FASTEST
  82079. /* ===========================================================================
  82080. * Set match_start to the longest match starting at the given string and
  82081. * return its length. Matches shorter or equal to prev_length are discarded,
  82082. * in which case the result is equal to prev_length and match_start is
  82083. * garbage.
  82084. * IN assertions: cur_match is the head of the hash chain for the current
  82085. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  82086. * OUT assertion: the match length is not greater than s->lookahead.
  82087. */
  82088. #ifndef ASMV
  82089. /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
  82090. * match.S. The code will be functionally equivalent.
  82091. */
  82092. local uInt longest_match(deflate_state *s, IPos cur_match)
  82093. {
  82094. unsigned chain_length = s->max_chain_length;/* max hash chain length */
  82095. register Bytef *scan = s->window + s->strstart; /* current string */
  82096. register Bytef *match; /* matched string */
  82097. register int len; /* length of current match */
  82098. int best_len = s->prev_length; /* best match length so far */
  82099. int nice_match = s->nice_match; /* stop if match long enough */
  82100. IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
  82101. s->strstart - (IPos)MAX_DIST(s) : NIL;
  82102. /* Stop when cur_match becomes <= limit. To simplify the code,
  82103. * we prevent matches with the string of window index 0.
  82104. */
  82105. Posf *prev = s->prev;
  82106. uInt wmask = s->w_mask;
  82107. #ifdef UNALIGNED_OK
  82108. /* Compare two bytes at a time. Note: this is not always beneficial.
  82109. * Try with and without -DUNALIGNED_OK to check.
  82110. */
  82111. register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
  82112. register ush scan_start = *(ushf*)scan;
  82113. register ush scan_end = *(ushf*)(scan+best_len-1);
  82114. #else
  82115. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  82116. register Byte scan_end1 = scan[best_len-1];
  82117. register Byte scan_end = scan[best_len];
  82118. #endif
  82119. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  82120. * It is easy to get rid of this optimization if necessary.
  82121. */
  82122. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  82123. /* Do not waste too much time if we already have a good match: */
  82124. if (s->prev_length >= s->good_match) {
  82125. chain_length >>= 2;
  82126. }
  82127. /* Do not look for matches beyond the end of the input. This is necessary
  82128. * to make deflate deterministic.
  82129. */
  82130. if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
  82131. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  82132. do {
  82133. Assert(cur_match < s->strstart, "no future");
  82134. match = s->window + cur_match;
  82135. /* Skip to next match if the match length cannot increase
  82136. * or if the match length is less than 2. Note that the checks below
  82137. * for insufficient lookahead only occur occasionally for performance
  82138. * reasons. Therefore uninitialized memory will be accessed, and
  82139. * conditional jumps will be made that depend on those values.
  82140. * However the length of the match is limited to the lookahead, so
  82141. * the output of deflate is not affected by the uninitialized values.
  82142. */
  82143. #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
  82144. /* This code assumes sizeof(unsigned short) == 2. Do not use
  82145. * UNALIGNED_OK if your compiler uses a different size.
  82146. */
  82147. if (*(ushf*)(match+best_len-1) != scan_end ||
  82148. *(ushf*)match != scan_start) continue;
  82149. /* It is not necessary to compare scan[2] and match[2] since they are
  82150. * always equal when the other bytes match, given that the hash keys
  82151. * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
  82152. * strstart+3, +5, ... up to strstart+257. We check for insufficient
  82153. * lookahead only every 4th comparison; the 128th check will be made
  82154. * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
  82155. * necessary to put more guard bytes at the end of the window, or
  82156. * to check more often for insufficient lookahead.
  82157. */
  82158. Assert(scan[2] == match[2], "scan[2]?");
  82159. scan++, match++;
  82160. do {
  82161. } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  82162. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  82163. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  82164. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  82165. scan < strend);
  82166. /* The funny "do {}" generates better code on most compilers */
  82167. /* Here, scan <= window+strstart+257 */
  82168. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  82169. if (*scan == *match) scan++;
  82170. len = (MAX_MATCH - 1) - (int)(strend-scan);
  82171. scan = strend - (MAX_MATCH-1);
  82172. #else /* UNALIGNED_OK */
  82173. if (match[best_len] != scan_end ||
  82174. match[best_len-1] != scan_end1 ||
  82175. *match != *scan ||
  82176. *++match != scan[1]) continue;
  82177. /* The check at best_len-1 can be removed because it will be made
  82178. * again later. (This heuristic is not always a win.)
  82179. * It is not necessary to compare scan[2] and match[2] since they
  82180. * are always equal when the other bytes match, given that
  82181. * the hash keys are equal and that HASH_BITS >= 8.
  82182. */
  82183. scan += 2, match++;
  82184. Assert(*scan == *match, "match[2]?");
  82185. /* We check for insufficient lookahead only every 8th comparison;
  82186. * the 256th check will be made at strstart+258.
  82187. */
  82188. do {
  82189. } while (*++scan == *++match && *++scan == *++match &&
  82190. *++scan == *++match && *++scan == *++match &&
  82191. *++scan == *++match && *++scan == *++match &&
  82192. *++scan == *++match && *++scan == *++match &&
  82193. scan < strend);
  82194. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  82195. len = MAX_MATCH - (int)(strend - scan);
  82196. scan = strend - MAX_MATCH;
  82197. #endif /* UNALIGNED_OK */
  82198. if (len > best_len) {
  82199. s->match_start = cur_match;
  82200. best_len = len;
  82201. if (len >= nice_match) break;
  82202. #ifdef UNALIGNED_OK
  82203. scan_end = *(ushf*)(scan+best_len-1);
  82204. #else
  82205. scan_end1 = scan[best_len-1];
  82206. scan_end = scan[best_len];
  82207. #endif
  82208. }
  82209. } while ((cur_match = prev[cur_match & wmask]) > limit
  82210. && --chain_length != 0);
  82211. if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
  82212. return s->lookahead;
  82213. }
  82214. #endif /* ASMV */
  82215. #endif /* FASTEST */
  82216. /* ---------------------------------------------------------------------------
  82217. * Optimized version for level == 1 or strategy == Z_RLE only
  82218. */
  82219. local uInt longest_match_fast (deflate_state *s, IPos cur_match)
  82220. {
  82221. register Bytef *scan = s->window + s->strstart; /* current string */
  82222. register Bytef *match; /* matched string */
  82223. register int len; /* length of current match */
  82224. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  82225. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  82226. * It is easy to get rid of this optimization if necessary.
  82227. */
  82228. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  82229. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  82230. Assert(cur_match < s->strstart, "no future");
  82231. match = s->window + cur_match;
  82232. /* Return failure if the match length is less than 2:
  82233. */
  82234. if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
  82235. /* The check at best_len-1 can be removed because it will be made
  82236. * again later. (This heuristic is not always a win.)
  82237. * It is not necessary to compare scan[2] and match[2] since they
  82238. * are always equal when the other bytes match, given that
  82239. * the hash keys are equal and that HASH_BITS >= 8.
  82240. */
  82241. scan += 2, match += 2;
  82242. Assert(*scan == *match, "match[2]?");
  82243. /* We check for insufficient lookahead only every 8th comparison;
  82244. * the 256th check will be made at strstart+258.
  82245. */
  82246. do {
  82247. } while (*++scan == *++match && *++scan == *++match &&
  82248. *++scan == *++match && *++scan == *++match &&
  82249. *++scan == *++match && *++scan == *++match &&
  82250. *++scan == *++match && *++scan == *++match &&
  82251. scan < strend);
  82252. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  82253. len = MAX_MATCH - (int)(strend - scan);
  82254. if (len < MIN_MATCH) return MIN_MATCH - 1;
  82255. s->match_start = cur_match;
  82256. return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
  82257. }
  82258. #ifdef DEBUG
  82259. /* ===========================================================================
  82260. * Check that the match at match_start is indeed a match.
  82261. */
  82262. local void check_match(deflate_state *s, IPos start, IPos match, int length)
  82263. {
  82264. /* check that the match is indeed a match */
  82265. if (zmemcmp(s->window + match,
  82266. s->window + start, length) != EQUAL) {
  82267. fprintf(stderr, " start %u, match %u, length %d\n",
  82268. start, match, length);
  82269. do {
  82270. fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
  82271. } while (--length != 0);
  82272. z_error("invalid match");
  82273. }
  82274. if (z_verbose > 1) {
  82275. fprintf(stderr,"\\[%d,%d]", start-match, length);
  82276. do { putc(s->window[start++], stderr); } while (--length != 0);
  82277. }
  82278. }
  82279. #else
  82280. # define check_match(s, start, match, length)
  82281. #endif /* DEBUG */
  82282. /* ===========================================================================
  82283. * Fill the window when the lookahead becomes insufficient.
  82284. * Updates strstart and lookahead.
  82285. *
  82286. * IN assertion: lookahead < MIN_LOOKAHEAD
  82287. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  82288. * At least one byte has been read, or avail_in == 0; reads are
  82289. * performed for at least two bytes (required for the zip translate_eol
  82290. * option -- not supported here).
  82291. */
  82292. local void fill_window (deflate_state *s)
  82293. {
  82294. register unsigned n, m;
  82295. register Posf *p;
  82296. unsigned more; /* Amount of free space at the end of the window. */
  82297. uInt wsize = s->w_size;
  82298. do {
  82299. more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
  82300. /* Deal with !@#$% 64K limit: */
  82301. if (sizeof(int) <= 2) {
  82302. if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  82303. more = wsize;
  82304. } else if (more == (unsigned)(-1)) {
  82305. /* Very unlikely, but possible on 16 bit machine if
  82306. * strstart == 0 && lookahead == 1 (input done a byte at time)
  82307. */
  82308. more--;
  82309. }
  82310. }
  82311. /* If the window is almost full and there is insufficient lookahead,
  82312. * move the upper half to the lower one to make room in the upper half.
  82313. */
  82314. if (s->strstart >= wsize+MAX_DIST(s)) {
  82315. zmemcpy(s->window, s->window+wsize, (unsigned)wsize);
  82316. s->match_start -= wsize;
  82317. s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
  82318. s->block_start -= (long) wsize;
  82319. /* Slide the hash table (could be avoided with 32 bit values
  82320. at the expense of memory usage). We slide even when level == 0
  82321. to keep the hash table consistent if we switch back to level > 0
  82322. later. (Using level 0 permanently is not an optimal usage of
  82323. zlib, so we don't care about this pathological case.)
  82324. */
  82325. /* %%% avoid this when Z_RLE */
  82326. n = s->hash_size;
  82327. p = &s->head[n];
  82328. do {
  82329. m = *--p;
  82330. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  82331. } while (--n);
  82332. n = wsize;
  82333. #ifndef FASTEST
  82334. p = &s->prev[n];
  82335. do {
  82336. m = *--p;
  82337. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  82338. /* If n is not on any hash chain, prev[n] is garbage but
  82339. * its value will never be used.
  82340. */
  82341. } while (--n);
  82342. #endif
  82343. more += wsize;
  82344. }
  82345. if (s->strm->avail_in == 0) return;
  82346. /* If there was no sliding:
  82347. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  82348. * more == window_size - lookahead - strstart
  82349. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  82350. * => more >= window_size - 2*WSIZE + 2
  82351. * In the BIG_MEM or MMAP case (not yet supported),
  82352. * window_size == input_size + MIN_LOOKAHEAD &&
  82353. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  82354. * Otherwise, window_size == 2*WSIZE so more >= 2.
  82355. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  82356. */
  82357. Assert(more >= 2, "more < 2");
  82358. n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
  82359. s->lookahead += n;
  82360. /* Initialize the hash value now that we have some input: */
  82361. if (s->lookahead >= MIN_MATCH) {
  82362. s->ins_h = s->window[s->strstart];
  82363. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  82364. #if MIN_MATCH != 3
  82365. Call UPDATE_HASH() MIN_MATCH-3 more times
  82366. #endif
  82367. }
  82368. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  82369. * but this is not important since only literal bytes will be emitted.
  82370. */
  82371. } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
  82372. }
  82373. /* ===========================================================================
  82374. * Flush the current block, with given end-of-file flag.
  82375. * IN assertion: strstart is set to the end of the current match.
  82376. */
  82377. #define FLUSH_BLOCK_ONLY(s, eof) { \
  82378. _tr_flush_block(s, (s->block_start >= 0L ? \
  82379. (charf *)&s->window[(unsigned)s->block_start] : \
  82380. (charf *)Z_NULL), \
  82381. (ulg)((long)s->strstart - s->block_start), \
  82382. (eof)); \
  82383. s->block_start = s->strstart; \
  82384. flush_pending(s->strm); \
  82385. Tracev((stderr,"[FLUSH]")); \
  82386. }
  82387. /* Same but force premature exit if necessary. */
  82388. #define FLUSH_BLOCK(s, eof) { \
  82389. FLUSH_BLOCK_ONLY(s, eof); \
  82390. if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \
  82391. }
  82392. /* ===========================================================================
  82393. * Copy without compression as much as possible from the input stream, return
  82394. * the current block state.
  82395. * This function does not insert new strings in the dictionary since
  82396. * uncompressible data is probably not useful. This function is used
  82397. * only for the level=0 compression option.
  82398. * NOTE: this function should be optimized to avoid extra copying from
  82399. * window to pending_buf.
  82400. */
  82401. local block_state deflate_stored(deflate_state *s, int flush)
  82402. {
  82403. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  82404. * to pending_buf_size, and each stored block has a 5 byte header:
  82405. */
  82406. ulg max_block_size = 0xffff;
  82407. ulg max_start;
  82408. if (max_block_size > s->pending_buf_size - 5) {
  82409. max_block_size = s->pending_buf_size - 5;
  82410. }
  82411. /* Copy as much as possible from input to output: */
  82412. for (;;) {
  82413. /* Fill the window as much as possible: */
  82414. if (s->lookahead <= 1) {
  82415. Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  82416. s->block_start >= (long)s->w_size, "slide too late");
  82417. fill_window(s);
  82418. if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
  82419. if (s->lookahead == 0) break; /* flush the current block */
  82420. }
  82421. Assert(s->block_start >= 0L, "block gone");
  82422. s->strstart += s->lookahead;
  82423. s->lookahead = 0;
  82424. /* Emit a stored block if pending_buf will be full: */
  82425. max_start = s->block_start + max_block_size;
  82426. if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
  82427. /* strstart == 0 is possible when wraparound on 16-bit machine */
  82428. s->lookahead = (uInt)(s->strstart - max_start);
  82429. s->strstart = (uInt)max_start;
  82430. FLUSH_BLOCK(s, 0);
  82431. }
  82432. /* Flush if we may have to slide, otherwise block_start may become
  82433. * negative and the data will be gone:
  82434. */
  82435. if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
  82436. FLUSH_BLOCK(s, 0);
  82437. }
  82438. }
  82439. FLUSH_BLOCK(s, flush == Z_FINISH);
  82440. return flush == Z_FINISH ? finish_done : block_done;
  82441. }
  82442. /* ===========================================================================
  82443. * Compress as much as possible from the input stream, return the current
  82444. * block state.
  82445. * This function does not perform lazy evaluation of matches and inserts
  82446. * new strings in the dictionary only for unmatched strings or for short
  82447. * matches. It is used only for the fast compression options.
  82448. */
  82449. local block_state deflate_fast(deflate_state *s, int flush)
  82450. {
  82451. IPos hash_head = NIL; /* head of the hash chain */
  82452. int bflush; /* set if current block must be flushed */
  82453. for (;;) {
  82454. /* Make sure that we always have enough lookahead, except
  82455. * at the end of the input file. We need MAX_MATCH bytes
  82456. * for the next match, plus MIN_MATCH bytes to insert the
  82457. * string following the next match.
  82458. */
  82459. if (s->lookahead < MIN_LOOKAHEAD) {
  82460. fill_window(s);
  82461. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  82462. return need_more;
  82463. }
  82464. if (s->lookahead == 0) break; /* flush the current block */
  82465. }
  82466. /* Insert the string window[strstart .. strstart+2] in the
  82467. * dictionary, and set hash_head to the head of the hash chain:
  82468. */
  82469. if (s->lookahead >= MIN_MATCH) {
  82470. INSERT_STRING(s, s->strstart, hash_head);
  82471. }
  82472. /* Find the longest match, discarding those <= prev_length.
  82473. * At this point we have always match_length < MIN_MATCH
  82474. */
  82475. if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
  82476. /* To simplify the code, we prevent matches with the string
  82477. * of window index 0 (in particular we have to avoid a match
  82478. * of the string with itself at the start of the input file).
  82479. */
  82480. #ifdef FASTEST
  82481. if ((s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) ||
  82482. (s->strategy == Z_RLE && s->strstart - hash_head == 1)) {
  82483. s->match_length = longest_match_fast (s, hash_head);
  82484. }
  82485. #else
  82486. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  82487. s->match_length = longest_match (s, hash_head);
  82488. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  82489. s->match_length = longest_match_fast (s, hash_head);
  82490. }
  82491. #endif
  82492. /* longest_match() or longest_match_fast() sets match_start */
  82493. }
  82494. if (s->match_length >= MIN_MATCH) {
  82495. check_match(s, s->strstart, s->match_start, s->match_length);
  82496. _tr_tally_dist(s, s->strstart - s->match_start,
  82497. s->match_length - MIN_MATCH, bflush);
  82498. s->lookahead -= s->match_length;
  82499. /* Insert new strings in the hash table only if the match length
  82500. * is not too large. This saves time but degrades compression.
  82501. */
  82502. #ifndef FASTEST
  82503. if (s->match_length <= s->max_insert_length &&
  82504. s->lookahead >= MIN_MATCH) {
  82505. s->match_length--; /* string at strstart already in table */
  82506. do {
  82507. s->strstart++;
  82508. INSERT_STRING(s, s->strstart, hash_head);
  82509. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  82510. * always MIN_MATCH bytes ahead.
  82511. */
  82512. } while (--s->match_length != 0);
  82513. s->strstart++;
  82514. } else
  82515. #endif
  82516. {
  82517. s->strstart += s->match_length;
  82518. s->match_length = 0;
  82519. s->ins_h = s->window[s->strstart];
  82520. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  82521. #if MIN_MATCH != 3
  82522. Call UPDATE_HASH() MIN_MATCH-3 more times
  82523. #endif
  82524. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  82525. * matter since it will be recomputed at next deflate call.
  82526. */
  82527. }
  82528. } else {
  82529. /* No match, output a literal byte */
  82530. Tracevv((stderr,"%c", s->window[s->strstart]));
  82531. _tr_tally_lit (s, s->window[s->strstart], bflush);
  82532. s->lookahead--;
  82533. s->strstart++;
  82534. }
  82535. if (bflush) FLUSH_BLOCK(s, 0);
  82536. }
  82537. FLUSH_BLOCK(s, flush == Z_FINISH);
  82538. return flush == Z_FINISH ? finish_done : block_done;
  82539. }
  82540. #ifndef FASTEST
  82541. /* ===========================================================================
  82542. * Same as above, but achieves better compression. We use a lazy
  82543. * evaluation for matches: a match is finally adopted only if there is
  82544. * no better match at the next window position.
  82545. */
  82546. local block_state deflate_slow(deflate_state *s, int flush)
  82547. {
  82548. IPos hash_head = NIL; /* head of hash chain */
  82549. int bflush; /* set if current block must be flushed */
  82550. /* Process the input block. */
  82551. for (;;) {
  82552. /* Make sure that we always have enough lookahead, except
  82553. * at the end of the input file. We need MAX_MATCH bytes
  82554. * for the next match, plus MIN_MATCH bytes to insert the
  82555. * string following the next match.
  82556. */
  82557. if (s->lookahead < MIN_LOOKAHEAD) {
  82558. fill_window(s);
  82559. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  82560. return need_more;
  82561. }
  82562. if (s->lookahead == 0) break; /* flush the current block */
  82563. }
  82564. /* Insert the string window[strstart .. strstart+2] in the
  82565. * dictionary, and set hash_head to the head of the hash chain:
  82566. */
  82567. if (s->lookahead >= MIN_MATCH) {
  82568. INSERT_STRING(s, s->strstart, hash_head);
  82569. }
  82570. /* Find the longest match, discarding those <= prev_length.
  82571. */
  82572. s->prev_length = s->match_length, s->prev_match = s->match_start;
  82573. s->match_length = MIN_MATCH-1;
  82574. if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
  82575. s->strstart - hash_head <= MAX_DIST(s)) {
  82576. /* To simplify the code, we prevent matches with the string
  82577. * of window index 0 (in particular we have to avoid a match
  82578. * of the string with itself at the start of the input file).
  82579. */
  82580. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  82581. s->match_length = longest_match (s, hash_head);
  82582. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  82583. s->match_length = longest_match_fast (s, hash_head);
  82584. }
  82585. /* longest_match() or longest_match_fast() sets match_start */
  82586. if (s->match_length <= 5 && (s->strategy == Z_FILTERED
  82587. #if TOO_FAR <= 32767
  82588. || (s->match_length == MIN_MATCH &&
  82589. s->strstart - s->match_start > TOO_FAR)
  82590. #endif
  82591. )) {
  82592. /* If prev_match is also MIN_MATCH, match_start is garbage
  82593. * but we will ignore the current match anyway.
  82594. */
  82595. s->match_length = MIN_MATCH-1;
  82596. }
  82597. }
  82598. /* If there was a match at the previous step and the current
  82599. * match is not better, output the previous match:
  82600. */
  82601. if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
  82602. uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
  82603. /* Do not insert strings in hash table beyond this. */
  82604. check_match(s, s->strstart-1, s->prev_match, s->prev_length);
  82605. _tr_tally_dist(s, s->strstart -1 - s->prev_match,
  82606. s->prev_length - MIN_MATCH, bflush);
  82607. /* Insert in hash table all strings up to the end of the match.
  82608. * strstart-1 and strstart are already inserted. If there is not
  82609. * enough lookahead, the last two strings are not inserted in
  82610. * the hash table.
  82611. */
  82612. s->lookahead -= s->prev_length-1;
  82613. s->prev_length -= 2;
  82614. do {
  82615. if (++s->strstart <= max_insert) {
  82616. INSERT_STRING(s, s->strstart, hash_head);
  82617. }
  82618. } while (--s->prev_length != 0);
  82619. s->match_available = 0;
  82620. s->match_length = MIN_MATCH-1;
  82621. s->strstart++;
  82622. if (bflush) FLUSH_BLOCK(s, 0);
  82623. } else if (s->match_available) {
  82624. /* If there was no match at the previous position, output a
  82625. * single literal. If there was a match but the current match
  82626. * is longer, truncate the previous match to a single literal.
  82627. */
  82628. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  82629. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  82630. if (bflush) {
  82631. FLUSH_BLOCK_ONLY(s, 0);
  82632. }
  82633. s->strstart++;
  82634. s->lookahead--;
  82635. if (s->strm->avail_out == 0) return need_more;
  82636. } else {
  82637. /* There is no previous match to compare with, wait for
  82638. * the next step to decide.
  82639. */
  82640. s->match_available = 1;
  82641. s->strstart++;
  82642. s->lookahead--;
  82643. }
  82644. }
  82645. Assert (flush != Z_NO_FLUSH, "no flush?");
  82646. if (s->match_available) {
  82647. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  82648. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  82649. s->match_available = 0;
  82650. }
  82651. FLUSH_BLOCK(s, flush == Z_FINISH);
  82652. return flush == Z_FINISH ? finish_done : block_done;
  82653. }
  82654. #endif /* FASTEST */
  82655. #if 0
  82656. /* ===========================================================================
  82657. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  82658. * one. Do not maintain a hash table. (It will be regenerated if this run of
  82659. * deflate switches away from Z_RLE.)
  82660. */
  82661. local block_state deflate_rle(s, flush)
  82662. deflate_state *s;
  82663. int flush;
  82664. {
  82665. int bflush; /* set if current block must be flushed */
  82666. uInt run; /* length of run */
  82667. uInt max; /* maximum length of run */
  82668. uInt prev; /* byte at distance one to match */
  82669. Bytef *scan; /* scan for end of run */
  82670. for (;;) {
  82671. /* Make sure that we always have enough lookahead, except
  82672. * at the end of the input file. We need MAX_MATCH bytes
  82673. * for the longest encodable run.
  82674. */
  82675. if (s->lookahead < MAX_MATCH) {
  82676. fill_window(s);
  82677. if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) {
  82678. return need_more;
  82679. }
  82680. if (s->lookahead == 0) break; /* flush the current block */
  82681. }
  82682. /* See how many times the previous byte repeats */
  82683. run = 0;
  82684. if (s->strstart > 0) { /* if there is a previous byte, that is */
  82685. max = s->lookahead < MAX_MATCH ? s->lookahead : MAX_MATCH;
  82686. scan = s->window + s->strstart - 1;
  82687. prev = *scan++;
  82688. do {
  82689. if (*scan++ != prev)
  82690. break;
  82691. } while (++run < max);
  82692. }
  82693. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  82694. if (run >= MIN_MATCH) {
  82695. check_match(s, s->strstart, s->strstart - 1, run);
  82696. _tr_tally_dist(s, 1, run - MIN_MATCH, bflush);
  82697. s->lookahead -= run;
  82698. s->strstart += run;
  82699. } else {
  82700. /* No match, output a literal byte */
  82701. Tracevv((stderr,"%c", s->window[s->strstart]));
  82702. _tr_tally_lit (s, s->window[s->strstart], bflush);
  82703. s->lookahead--;
  82704. s->strstart++;
  82705. }
  82706. if (bflush) FLUSH_BLOCK(s, 0);
  82707. }
  82708. FLUSH_BLOCK(s, flush == Z_FINISH);
  82709. return flush == Z_FINISH ? finish_done : block_done;
  82710. }
  82711. #endif
  82712. /*** End of inlined file: deflate.c ***/
  82713. /*** Start of inlined file: inffast.c ***/
  82714. /*** Start of inlined file: inftrees.h ***/
  82715. /* WARNING: this file should *not* be used by applications. It is
  82716. part of the implementation of the compression library and is
  82717. subject to change. Applications should only use zlib.h.
  82718. */
  82719. #ifndef _INFTREES_H_
  82720. #define _INFTREES_H_
  82721. /* Structure for decoding tables. Each entry provides either the
  82722. information needed to do the operation requested by the code that
  82723. indexed that table entry, or it provides a pointer to another
  82724. table that indexes more bits of the code. op indicates whether
  82725. the entry is a pointer to another table, a literal, a length or
  82726. distance, an end-of-block, or an invalid code. For a table
  82727. pointer, the low four bits of op is the number of index bits of
  82728. that table. For a length or distance, the low four bits of op
  82729. is the number of extra bits to get after the code. bits is
  82730. the number of bits in this code or part of the code to drop off
  82731. of the bit buffer. val is the actual byte to output in the case
  82732. of a literal, the base length or distance, or the offset from
  82733. the current table to the next table. Each entry is four bytes. */
  82734. typedef struct {
  82735. unsigned char op; /* operation, extra bits, table bits */
  82736. unsigned char bits; /* bits in this part of the code */
  82737. unsigned short val; /* offset in table or code value */
  82738. } code;
  82739. /* op values as set by inflate_table():
  82740. 00000000 - literal
  82741. 0000tttt - table link, tttt != 0 is the number of table index bits
  82742. 0001eeee - length or distance, eeee is the number of extra bits
  82743. 01100000 - end of block
  82744. 01000000 - invalid code
  82745. */
  82746. /* Maximum size of dynamic tree. The maximum found in a long but non-
  82747. exhaustive search was 1444 code structures (852 for length/literals
  82748. and 592 for distances, the latter actually the result of an
  82749. exhaustive search). The true maximum is not known, but the value
  82750. below is more than safe. */
  82751. #define ENOUGH 2048
  82752. #define MAXD 592
  82753. /* Type of code to build for inftable() */
  82754. typedef enum {
  82755. CODES,
  82756. LENS,
  82757. DISTS
  82758. } codetype;
  82759. extern int inflate_table OF((codetype type, unsigned short FAR *lens,
  82760. unsigned codes, code FAR * FAR *table,
  82761. unsigned FAR *bits, unsigned short FAR *work));
  82762. #endif
  82763. /*** End of inlined file: inftrees.h ***/
  82764. /*** Start of inlined file: inflate.h ***/
  82765. /* WARNING: this file should *not* be used by applications. It is
  82766. part of the implementation of the compression library and is
  82767. subject to change. Applications should only use zlib.h.
  82768. */
  82769. #ifndef _INFLATE_H_
  82770. #define _INFLATE_H_
  82771. /* define NO_GZIP when compiling if you want to disable gzip header and
  82772. trailer decoding by inflate(). NO_GZIP would be used to avoid linking in
  82773. the crc code when it is not needed. For shared libraries, gzip decoding
  82774. should be left enabled. */
  82775. #ifndef NO_GZIP
  82776. # define GUNZIP
  82777. #endif
  82778. /* Possible inflate modes between inflate() calls */
  82779. typedef enum {
  82780. HEAD, /* i: waiting for magic header */
  82781. FLAGS, /* i: waiting for method and flags (gzip) */
  82782. TIME, /* i: waiting for modification time (gzip) */
  82783. OS, /* i: waiting for extra flags and operating system (gzip) */
  82784. EXLEN, /* i: waiting for extra length (gzip) */
  82785. EXTRA, /* i: waiting for extra bytes (gzip) */
  82786. NAME, /* i: waiting for end of file name (gzip) */
  82787. COMMENT, /* i: waiting for end of comment (gzip) */
  82788. HCRC, /* i: waiting for header crc (gzip) */
  82789. DICTID, /* i: waiting for dictionary check value */
  82790. DICT, /* waiting for inflateSetDictionary() call */
  82791. TYPE, /* i: waiting for type bits, including last-flag bit */
  82792. TYPEDO, /* i: same, but skip check to exit inflate on new block */
  82793. STORED, /* i: waiting for stored size (length and complement) */
  82794. COPY, /* i/o: waiting for input or output to copy stored block */
  82795. TABLE, /* i: waiting for dynamic block table lengths */
  82796. LENLENS, /* i: waiting for code length code lengths */
  82797. CODELENS, /* i: waiting for length/lit and distance code lengths */
  82798. LEN, /* i: waiting for length/lit code */
  82799. LENEXT, /* i: waiting for length extra bits */
  82800. DIST, /* i: waiting for distance code */
  82801. DISTEXT, /* i: waiting for distance extra bits */
  82802. MATCH, /* o: waiting for output space to copy string */
  82803. LIT, /* o: waiting for output space to write literal */
  82804. CHECK, /* i: waiting for 32-bit check value */
  82805. LENGTH, /* i: waiting for 32-bit length (gzip) */
  82806. DONE, /* finished check, done -- remain here until reset */
  82807. BAD, /* got a data error -- remain here until reset */
  82808. MEM, /* got an inflate() memory error -- remain here until reset */
  82809. SYNC /* looking for synchronization bytes to restart inflate() */
  82810. } inflate_mode;
  82811. /*
  82812. State transitions between above modes -
  82813. (most modes can go to the BAD or MEM mode -- not shown for clarity)
  82814. Process header:
  82815. HEAD -> (gzip) or (zlib)
  82816. (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME
  82817. NAME -> COMMENT -> HCRC -> TYPE
  82818. (zlib) -> DICTID or TYPE
  82819. DICTID -> DICT -> TYPE
  82820. Read deflate blocks:
  82821. TYPE -> STORED or TABLE or LEN or CHECK
  82822. STORED -> COPY -> TYPE
  82823. TABLE -> LENLENS -> CODELENS -> LEN
  82824. Read deflate codes:
  82825. LEN -> LENEXT or LIT or TYPE
  82826. LENEXT -> DIST -> DISTEXT -> MATCH -> LEN
  82827. LIT -> LEN
  82828. Process trailer:
  82829. CHECK -> LENGTH -> DONE
  82830. */
  82831. /* state maintained between inflate() calls. Approximately 7K bytes. */
  82832. struct inflate_state {
  82833. inflate_mode mode; /* current inflate mode */
  82834. int last; /* true if processing last block */
  82835. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  82836. int havedict; /* true if dictionary provided */
  82837. int flags; /* gzip header method and flags (0 if zlib) */
  82838. unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */
  82839. unsigned long check; /* protected copy of check value */
  82840. unsigned long total; /* protected copy of output count */
  82841. gz_headerp head; /* where to save gzip header information */
  82842. /* sliding window */
  82843. unsigned wbits; /* log base 2 of requested window size */
  82844. unsigned wsize; /* window size or zero if not using window */
  82845. unsigned whave; /* valid bytes in the window */
  82846. unsigned write; /* window write index */
  82847. unsigned char FAR *window; /* allocated sliding window, if needed */
  82848. /* bit accumulator */
  82849. unsigned long hold; /* input bit accumulator */
  82850. unsigned bits; /* number of bits in "in" */
  82851. /* for string and stored block copying */
  82852. unsigned length; /* literal or length of data to copy */
  82853. unsigned offset; /* distance back to copy string from */
  82854. /* for table and code decoding */
  82855. unsigned extra; /* extra bits needed */
  82856. /* fixed and dynamic code tables */
  82857. code const FAR *lencode; /* starting table for length/literal codes */
  82858. code const FAR *distcode; /* starting table for distance codes */
  82859. unsigned lenbits; /* index bits for lencode */
  82860. unsigned distbits; /* index bits for distcode */
  82861. /* dynamic table building */
  82862. unsigned ncode; /* number of code length code lengths */
  82863. unsigned nlen; /* number of length code lengths */
  82864. unsigned ndist; /* number of distance code lengths */
  82865. unsigned have; /* number of code lengths in lens[] */
  82866. code FAR *next; /* next available space in codes[] */
  82867. unsigned short lens[320]; /* temporary storage for code lengths */
  82868. unsigned short work[288]; /* work area for code table building */
  82869. code codes[ENOUGH]; /* space for code tables */
  82870. };
  82871. #endif
  82872. /*** End of inlined file: inflate.h ***/
  82873. /*** Start of inlined file: inffast.h ***/
  82874. /* WARNING: this file should *not* be used by applications. It is
  82875. part of the implementation of the compression library and is
  82876. subject to change. Applications should only use zlib.h.
  82877. */
  82878. void inflate_fast OF((z_streamp strm, unsigned start));
  82879. /*** End of inlined file: inffast.h ***/
  82880. #ifndef ASMINF
  82881. /* Allow machine dependent optimization for post-increment or pre-increment.
  82882. Based on testing to date,
  82883. Pre-increment preferred for:
  82884. - PowerPC G3 (Adler)
  82885. - MIPS R5000 (Randers-Pehrson)
  82886. Post-increment preferred for:
  82887. - none
  82888. No measurable difference:
  82889. - Pentium III (Anderson)
  82890. - M68060 (Nikl)
  82891. */
  82892. #ifdef POSTINC
  82893. # define OFF 0
  82894. # define PUP(a) *(a)++
  82895. #else
  82896. # define OFF 1
  82897. # define PUP(a) *++(a)
  82898. #endif
  82899. /*
  82900. Decode literal, length, and distance codes and write out the resulting
  82901. literal and match bytes until either not enough input or output is
  82902. available, an end-of-block is encountered, or a data error is encountered.
  82903. When large enough input and output buffers are supplied to inflate(), for
  82904. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  82905. inflate execution time is spent in this routine.
  82906. Entry assumptions:
  82907. state->mode == LEN
  82908. strm->avail_in >= 6
  82909. strm->avail_out >= 258
  82910. start >= strm->avail_out
  82911. state->bits < 8
  82912. On return, state->mode is one of:
  82913. LEN -- ran out of enough output space or enough available input
  82914. TYPE -- reached end of block code, inflate() to interpret next block
  82915. BAD -- error in block data
  82916. Notes:
  82917. - The maximum input bits used by a length/distance pair is 15 bits for the
  82918. length code, 5 bits for the length extra, 15 bits for the distance code,
  82919. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  82920. Therefore if strm->avail_in >= 6, then there is enough input to avoid
  82921. checking for available input while decoding.
  82922. - The maximum bytes that a single length/distance pair can output is 258
  82923. bytes, which is the maximum length that can be coded. inflate_fast()
  82924. requires strm->avail_out >= 258 for each loop to avoid checking for
  82925. output space.
  82926. */
  82927. void inflate_fast (z_streamp strm, unsigned start)
  82928. {
  82929. struct inflate_state FAR *state;
  82930. unsigned char FAR *in; /* local strm->next_in */
  82931. unsigned char FAR *last; /* while in < last, enough input available */
  82932. unsigned char FAR *out; /* local strm->next_out */
  82933. unsigned char FAR *beg; /* inflate()'s initial strm->next_out */
  82934. unsigned char FAR *end; /* while out < end, enough space available */
  82935. #ifdef INFLATE_STRICT
  82936. unsigned dmax; /* maximum distance from zlib header */
  82937. #endif
  82938. unsigned wsize; /* window size or zero if not using window */
  82939. unsigned whave; /* valid bytes in the window */
  82940. unsigned write; /* window write index */
  82941. unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */
  82942. unsigned long hold; /* local strm->hold */
  82943. unsigned bits; /* local strm->bits */
  82944. code const FAR *lcode; /* local strm->lencode */
  82945. code const FAR *dcode; /* local strm->distcode */
  82946. unsigned lmask; /* mask for first level of length codes */
  82947. unsigned dmask; /* mask for first level of distance codes */
  82948. code thisx; /* retrieved table entry */
  82949. unsigned op; /* code bits, operation, extra bits, or */
  82950. /* window position, window bytes to copy */
  82951. unsigned len; /* match length, unused bytes */
  82952. unsigned dist; /* match distance */
  82953. unsigned char FAR *from; /* where to copy match from */
  82954. /* copy state to local variables */
  82955. state = (struct inflate_state FAR *)strm->state;
  82956. in = strm->next_in - OFF;
  82957. last = in + (strm->avail_in - 5);
  82958. out = strm->next_out - OFF;
  82959. beg = out - (start - strm->avail_out);
  82960. end = out + (strm->avail_out - 257);
  82961. #ifdef INFLATE_STRICT
  82962. dmax = state->dmax;
  82963. #endif
  82964. wsize = state->wsize;
  82965. whave = state->whave;
  82966. write = state->write;
  82967. window = state->window;
  82968. hold = state->hold;
  82969. bits = state->bits;
  82970. lcode = state->lencode;
  82971. dcode = state->distcode;
  82972. lmask = (1U << state->lenbits) - 1;
  82973. dmask = (1U << state->distbits) - 1;
  82974. /* decode literals and length/distances until end-of-block or not enough
  82975. input data or output space */
  82976. do {
  82977. if (bits < 15) {
  82978. hold += (unsigned long)(PUP(in)) << bits;
  82979. bits += 8;
  82980. hold += (unsigned long)(PUP(in)) << bits;
  82981. bits += 8;
  82982. }
  82983. thisx = lcode[hold & lmask];
  82984. dolen:
  82985. op = (unsigned)(thisx.bits);
  82986. hold >>= op;
  82987. bits -= op;
  82988. op = (unsigned)(thisx.op);
  82989. if (op == 0) { /* literal */
  82990. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  82991. "inflate: literal '%c'\n" :
  82992. "inflate: literal 0x%02x\n", thisx.val));
  82993. PUP(out) = (unsigned char)(thisx.val);
  82994. }
  82995. else if (op & 16) { /* length base */
  82996. len = (unsigned)(thisx.val);
  82997. op &= 15; /* number of extra bits */
  82998. if (op) {
  82999. if (bits < op) {
  83000. hold += (unsigned long)(PUP(in)) << bits;
  83001. bits += 8;
  83002. }
  83003. len += (unsigned)hold & ((1U << op) - 1);
  83004. hold >>= op;
  83005. bits -= op;
  83006. }
  83007. Tracevv((stderr, "inflate: length %u\n", len));
  83008. if (bits < 15) {
  83009. hold += (unsigned long)(PUP(in)) << bits;
  83010. bits += 8;
  83011. hold += (unsigned long)(PUP(in)) << bits;
  83012. bits += 8;
  83013. }
  83014. thisx = dcode[hold & dmask];
  83015. dodist:
  83016. op = (unsigned)(thisx.bits);
  83017. hold >>= op;
  83018. bits -= op;
  83019. op = (unsigned)(thisx.op);
  83020. if (op & 16) { /* distance base */
  83021. dist = (unsigned)(thisx.val);
  83022. op &= 15; /* number of extra bits */
  83023. if (bits < op) {
  83024. hold += (unsigned long)(PUP(in)) << bits;
  83025. bits += 8;
  83026. if (bits < op) {
  83027. hold += (unsigned long)(PUP(in)) << bits;
  83028. bits += 8;
  83029. }
  83030. }
  83031. dist += (unsigned)hold & ((1U << op) - 1);
  83032. #ifdef INFLATE_STRICT
  83033. if (dist > dmax) {
  83034. strm->msg = (char *)"invalid distance too far back";
  83035. state->mode = BAD;
  83036. break;
  83037. }
  83038. #endif
  83039. hold >>= op;
  83040. bits -= op;
  83041. Tracevv((stderr, "inflate: distance %u\n", dist));
  83042. op = (unsigned)(out - beg); /* max distance in output */
  83043. if (dist > op) { /* see if copy from window */
  83044. op = dist - op; /* distance back in window */
  83045. if (op > whave) {
  83046. strm->msg = (char *)"invalid distance too far back";
  83047. state->mode = BAD;
  83048. break;
  83049. }
  83050. from = window - OFF;
  83051. if (write == 0) { /* very common case */
  83052. from += wsize - op;
  83053. if (op < len) { /* some from window */
  83054. len -= op;
  83055. do {
  83056. PUP(out) = PUP(from);
  83057. } while (--op);
  83058. from = out - dist; /* rest from output */
  83059. }
  83060. }
  83061. else if (write < op) { /* wrap around window */
  83062. from += wsize + write - op;
  83063. op -= write;
  83064. if (op < len) { /* some from end of window */
  83065. len -= op;
  83066. do {
  83067. PUP(out) = PUP(from);
  83068. } while (--op);
  83069. from = window - OFF;
  83070. if (write < len) { /* some from start of window */
  83071. op = write;
  83072. len -= op;
  83073. do {
  83074. PUP(out) = PUP(from);
  83075. } while (--op);
  83076. from = out - dist; /* rest from output */
  83077. }
  83078. }
  83079. }
  83080. else { /* contiguous in window */
  83081. from += write - op;
  83082. if (op < len) { /* some from window */
  83083. len -= op;
  83084. do {
  83085. PUP(out) = PUP(from);
  83086. } while (--op);
  83087. from = out - dist; /* rest from output */
  83088. }
  83089. }
  83090. while (len > 2) {
  83091. PUP(out) = PUP(from);
  83092. PUP(out) = PUP(from);
  83093. PUP(out) = PUP(from);
  83094. len -= 3;
  83095. }
  83096. if (len) {
  83097. PUP(out) = PUP(from);
  83098. if (len > 1)
  83099. PUP(out) = PUP(from);
  83100. }
  83101. }
  83102. else {
  83103. from = out - dist; /* copy direct from output */
  83104. do { /* minimum length is three */
  83105. PUP(out) = PUP(from);
  83106. PUP(out) = PUP(from);
  83107. PUP(out) = PUP(from);
  83108. len -= 3;
  83109. } while (len > 2);
  83110. if (len) {
  83111. PUP(out) = PUP(from);
  83112. if (len > 1)
  83113. PUP(out) = PUP(from);
  83114. }
  83115. }
  83116. }
  83117. else if ((op & 64) == 0) { /* 2nd level distance code */
  83118. thisx = dcode[thisx.val + (hold & ((1U << op) - 1))];
  83119. goto dodist;
  83120. }
  83121. else {
  83122. strm->msg = (char *)"invalid distance code";
  83123. state->mode = BAD;
  83124. break;
  83125. }
  83126. }
  83127. else if ((op & 64) == 0) { /* 2nd level length code */
  83128. thisx = lcode[thisx.val + (hold & ((1U << op) - 1))];
  83129. goto dolen;
  83130. }
  83131. else if (op & 32) { /* end-of-block */
  83132. Tracevv((stderr, "inflate: end of block\n"));
  83133. state->mode = TYPE;
  83134. break;
  83135. }
  83136. else {
  83137. strm->msg = (char *)"invalid literal/length code";
  83138. state->mode = BAD;
  83139. break;
  83140. }
  83141. } while (in < last && out < end);
  83142. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  83143. len = bits >> 3;
  83144. in -= len;
  83145. bits -= len << 3;
  83146. hold &= (1U << bits) - 1;
  83147. /* update state and return */
  83148. strm->next_in = in + OFF;
  83149. strm->next_out = out + OFF;
  83150. strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last));
  83151. strm->avail_out = (unsigned)(out < end ?
  83152. 257 + (end - out) : 257 - (out - end));
  83153. state->hold = hold;
  83154. state->bits = bits;
  83155. return;
  83156. }
  83157. /*
  83158. inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe):
  83159. - Using bit fields for code structure
  83160. - Different op definition to avoid & for extra bits (do & for table bits)
  83161. - Three separate decoding do-loops for direct, window, and write == 0
  83162. - Special case for distance > 1 copies to do overlapped load and store copy
  83163. - Explicit branch predictions (based on measured branch probabilities)
  83164. - Deferring match copy and interspersed it with decoding subsequent codes
  83165. - Swapping literal/length else
  83166. - Swapping window/direct else
  83167. - Larger unrolled copy loops (three is about right)
  83168. - Moving len -= 3 statement into middle of loop
  83169. */
  83170. #endif /* !ASMINF */
  83171. /*** End of inlined file: inffast.c ***/
  83172. #undef PULLBYTE
  83173. #undef LOAD
  83174. #undef RESTORE
  83175. #undef INITBITS
  83176. #undef NEEDBITS
  83177. #undef DROPBITS
  83178. #undef BYTEBITS
  83179. /*** Start of inlined file: inflate.c ***/
  83180. /*
  83181. * Change history:
  83182. *
  83183. * 1.2.beta0 24 Nov 2002
  83184. * - First version -- complete rewrite of inflate to simplify code, avoid
  83185. * creation of window when not needed, minimize use of window when it is
  83186. * needed, make inffast.c even faster, implement gzip decoding, and to
  83187. * improve code readability and style over the previous zlib inflate code
  83188. *
  83189. * 1.2.beta1 25 Nov 2002
  83190. * - Use pointers for available input and output checking in inffast.c
  83191. * - Remove input and output counters in inffast.c
  83192. * - Change inffast.c entry and loop from avail_in >= 7 to >= 6
  83193. * - Remove unnecessary second byte pull from length extra in inffast.c
  83194. * - Unroll direct copy to three copies per loop in inffast.c
  83195. *
  83196. * 1.2.beta2 4 Dec 2002
  83197. * - Change external routine names to reduce potential conflicts
  83198. * - Correct filename to inffixed.h for fixed tables in inflate.c
  83199. * - Make hbuf[] unsigned char to match parameter type in inflate.c
  83200. * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset)
  83201. * to avoid negation problem on Alphas (64 bit) in inflate.c
  83202. *
  83203. * 1.2.beta3 22 Dec 2002
  83204. * - Add comments on state->bits assertion in inffast.c
  83205. * - Add comments on op field in inftrees.h
  83206. * - Fix bug in reuse of allocated window after inflateReset()
  83207. * - Remove bit fields--back to byte structure for speed
  83208. * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths
  83209. * - Change post-increments to pre-increments in inflate_fast(), PPC biased?
  83210. * - Add compile time option, POSTINC, to use post-increments instead (Intel?)
  83211. * - Make MATCH copy in inflate() much faster for when inflate_fast() not used
  83212. * - Use local copies of stream next and avail values, as well as local bit
  83213. * buffer and bit count in inflate()--for speed when inflate_fast() not used
  83214. *
  83215. * 1.2.beta4 1 Jan 2003
  83216. * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings
  83217. * - Move a comment on output buffer sizes from inffast.c to inflate.c
  83218. * - Add comments in inffast.c to introduce the inflate_fast() routine
  83219. * - Rearrange window copies in inflate_fast() for speed and simplification
  83220. * - Unroll last copy for window match in inflate_fast()
  83221. * - Use local copies of window variables in inflate_fast() for speed
  83222. * - Pull out common write == 0 case for speed in inflate_fast()
  83223. * - Make op and len in inflate_fast() unsigned for consistency
  83224. * - Add FAR to lcode and dcode declarations in inflate_fast()
  83225. * - Simplified bad distance check in inflate_fast()
  83226. * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new
  83227. * source file infback.c to provide a call-back interface to inflate for
  83228. * programs like gzip and unzip -- uses window as output buffer to avoid
  83229. * window copying
  83230. *
  83231. * 1.2.beta5 1 Jan 2003
  83232. * - Improved inflateBack() interface to allow the caller to provide initial
  83233. * input in strm.
  83234. * - Fixed stored blocks bug in inflateBack()
  83235. *
  83236. * 1.2.beta6 4 Jan 2003
  83237. * - Added comments in inffast.c on effectiveness of POSTINC
  83238. * - Typecasting all around to reduce compiler warnings
  83239. * - Changed loops from while (1) or do {} while (1) to for (;;), again to
  83240. * make compilers happy
  83241. * - Changed type of window in inflateBackInit() to unsigned char *
  83242. *
  83243. * 1.2.beta7 27 Jan 2003
  83244. * - Changed many types to unsigned or unsigned short to avoid warnings
  83245. * - Added inflateCopy() function
  83246. *
  83247. * 1.2.0 9 Mar 2003
  83248. * - Changed inflateBack() interface to provide separate opaque descriptors
  83249. * for the in() and out() functions
  83250. * - Changed inflateBack() argument and in_func typedef to swap the length
  83251. * and buffer address return values for the input function
  83252. * - Check next_in and next_out for Z_NULL on entry to inflate()
  83253. *
  83254. * The history for versions after 1.2.0 are in ChangeLog in zlib distribution.
  83255. */
  83256. /*** Start of inlined file: inffast.h ***/
  83257. /* WARNING: this file should *not* be used by applications. It is
  83258. part of the implementation of the compression library and is
  83259. subject to change. Applications should only use zlib.h.
  83260. */
  83261. void inflate_fast OF((z_streamp strm, unsigned start));
  83262. /*** End of inlined file: inffast.h ***/
  83263. #ifdef MAKEFIXED
  83264. # ifndef BUILDFIXED
  83265. # define BUILDFIXED
  83266. # endif
  83267. #endif
  83268. /* function prototypes */
  83269. local void fixedtables OF((struct inflate_state FAR *state));
  83270. local int updatewindow OF((z_streamp strm, unsigned out));
  83271. #ifdef BUILDFIXED
  83272. void makefixed OF((void));
  83273. #endif
  83274. local unsigned syncsearch OF((unsigned FAR *have, unsigned char FAR *buf,
  83275. unsigned len));
  83276. int ZEXPORT inflateReset (z_streamp strm)
  83277. {
  83278. struct inflate_state FAR *state;
  83279. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83280. state = (struct inflate_state FAR *)strm->state;
  83281. strm->total_in = strm->total_out = state->total = 0;
  83282. strm->msg = Z_NULL;
  83283. strm->adler = 1; /* to support ill-conceived Java test suite */
  83284. state->mode = HEAD;
  83285. state->last = 0;
  83286. state->havedict = 0;
  83287. state->dmax = 32768U;
  83288. state->head = Z_NULL;
  83289. state->wsize = 0;
  83290. state->whave = 0;
  83291. state->write = 0;
  83292. state->hold = 0;
  83293. state->bits = 0;
  83294. state->lencode = state->distcode = state->next = state->codes;
  83295. Tracev((stderr, "inflate: reset\n"));
  83296. return Z_OK;
  83297. }
  83298. int ZEXPORT inflatePrime (z_streamp strm, int bits, int value)
  83299. {
  83300. struct inflate_state FAR *state;
  83301. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83302. state = (struct inflate_state FAR *)strm->state;
  83303. if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR;
  83304. value &= (1L << bits) - 1;
  83305. state->hold += value << state->bits;
  83306. state->bits += bits;
  83307. return Z_OK;
  83308. }
  83309. int ZEXPORT inflateInit2_(z_streamp strm, int windowBits, const char *version, int stream_size)
  83310. {
  83311. struct inflate_state FAR *state;
  83312. if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
  83313. stream_size != (int)(sizeof(z_stream)))
  83314. return Z_VERSION_ERROR;
  83315. if (strm == Z_NULL) return Z_STREAM_ERROR;
  83316. strm->msg = Z_NULL; /* in case we return an error */
  83317. if (strm->zalloc == (alloc_func)0) {
  83318. strm->zalloc = zcalloc;
  83319. strm->opaque = (voidpf)0;
  83320. }
  83321. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  83322. state = (struct inflate_state FAR *)
  83323. ZALLOC(strm, 1, sizeof(struct inflate_state));
  83324. if (state == Z_NULL) return Z_MEM_ERROR;
  83325. Tracev((stderr, "inflate: allocated\n"));
  83326. strm->state = (struct internal_state FAR *)state;
  83327. if (windowBits < 0) {
  83328. state->wrap = 0;
  83329. windowBits = -windowBits;
  83330. }
  83331. else {
  83332. state->wrap = (windowBits >> 4) + 1;
  83333. #ifdef GUNZIP
  83334. if (windowBits < 48) windowBits &= 15;
  83335. #endif
  83336. }
  83337. if (windowBits < 8 || windowBits > 15) {
  83338. ZFREE(strm, state);
  83339. strm->state = Z_NULL;
  83340. return Z_STREAM_ERROR;
  83341. }
  83342. state->wbits = (unsigned)windowBits;
  83343. state->window = Z_NULL;
  83344. return inflateReset(strm);
  83345. }
  83346. int ZEXPORT inflateInit_ (z_streamp strm, const char *version, int stream_size)
  83347. {
  83348. return inflateInit2_(strm, DEF_WBITS, version, stream_size);
  83349. }
  83350. /*
  83351. Return state with length and distance decoding tables and index sizes set to
  83352. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  83353. If BUILDFIXED is defined, then instead this routine builds the tables the
  83354. first time it's called, and returns those tables the first time and
  83355. thereafter. This reduces the size of the code by about 2K bytes, in
  83356. exchange for a little execution time. However, BUILDFIXED should not be
  83357. used for threaded applications, since the rewriting of the tables and virgin
  83358. may not be thread-safe.
  83359. */
  83360. local void fixedtables (struct inflate_state FAR *state)
  83361. {
  83362. #ifdef BUILDFIXED
  83363. static int virgin = 1;
  83364. static code *lenfix, *distfix;
  83365. static code fixed[544];
  83366. /* build fixed huffman tables if first call (may not be thread safe) */
  83367. if (virgin) {
  83368. unsigned sym, bits;
  83369. static code *next;
  83370. /* literal/length table */
  83371. sym = 0;
  83372. while (sym < 144) state->lens[sym++] = 8;
  83373. while (sym < 256) state->lens[sym++] = 9;
  83374. while (sym < 280) state->lens[sym++] = 7;
  83375. while (sym < 288) state->lens[sym++] = 8;
  83376. next = fixed;
  83377. lenfix = next;
  83378. bits = 9;
  83379. inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
  83380. /* distance table */
  83381. sym = 0;
  83382. while (sym < 32) state->lens[sym++] = 5;
  83383. distfix = next;
  83384. bits = 5;
  83385. inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
  83386. /* do this just once */
  83387. virgin = 0;
  83388. }
  83389. #else /* !BUILDFIXED */
  83390. /*** Start of inlined file: inffixed.h ***/
  83391. /* WARNING: this file should *not* be used by applications. It
  83392. is part of the implementation of the compression library and
  83393. is subject to change. Applications should only use zlib.h.
  83394. */
  83395. static const code lenfix[512] = {
  83396. {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48},
  83397. {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128},
  83398. {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59},
  83399. {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176},
  83400. {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20},
  83401. {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100},
  83402. {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8},
  83403. {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216},
  83404. {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76},
  83405. {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114},
  83406. {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},
  83407. {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148},
  83408. {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42},
  83409. {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86},
  83410. {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15},
  83411. {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236},
  83412. {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62},
  83413. {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},
  83414. {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31},
  83415. {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162},
  83416. {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25},
  83417. {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105},
  83418. {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4},
  83419. {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202},
  83420. {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69},
  83421. {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125},
  83422. {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13},
  83423. {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195},
  83424. {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35},
  83425. {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91},
  83426. {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19},
  83427. {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246},
  83428. {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55},
  83429. {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135},
  83430. {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99},
  83431. {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190},
  83432. {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16},
  83433. {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96},
  83434. {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6},
  83435. {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209},
  83436. {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},
  83437. {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116},
  83438. {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4},
  83439. {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153},
  83440. {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44},
  83441. {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82},
  83442. {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11},
  83443. {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},
  83444. {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58},
  83445. {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138},
  83446. {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51},
  83447. {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173},
  83448. {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30},
  83449. {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110},
  83450. {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0},
  83451. {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195},
  83452. {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65},
  83453. {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121},
  83454. {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},
  83455. {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258},
  83456. {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37},
  83457. {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93},
  83458. {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23},
  83459. {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251},
  83460. {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51},
  83461. {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},
  83462. {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67},
  83463. {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183},
  83464. {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23},
  83465. {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103},
  83466. {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9},
  83467. {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223},
  83468. {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79},
  83469. {0,9,255}
  83470. };
  83471. static const code distfix[32] = {
  83472. {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025},
  83473. {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193},
  83474. {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385},
  83475. {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577},
  83476. {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073},
  83477. {22,5,193},{64,5,0}
  83478. };
  83479. /*** End of inlined file: inffixed.h ***/
  83480. #endif /* BUILDFIXED */
  83481. state->lencode = lenfix;
  83482. state->lenbits = 9;
  83483. state->distcode = distfix;
  83484. state->distbits = 5;
  83485. }
  83486. #ifdef MAKEFIXED
  83487. #include <stdio.h>
  83488. /*
  83489. Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also
  83490. defines BUILDFIXED, so the tables are built on the fly. makefixed() writes
  83491. those tables to stdout, which would be piped to inffixed.h. A small program
  83492. can simply call makefixed to do this:
  83493. void makefixed(void);
  83494. int main(void)
  83495. {
  83496. makefixed();
  83497. return 0;
  83498. }
  83499. Then that can be linked with zlib built with MAKEFIXED defined and run:
  83500. a.out > inffixed.h
  83501. */
  83502. void makefixed()
  83503. {
  83504. unsigned low, size;
  83505. struct inflate_state state;
  83506. fixedtables(&state);
  83507. puts(" /* inffixed.h -- table for decoding fixed codes");
  83508. puts(" * Generated automatically by makefixed().");
  83509. puts(" */");
  83510. puts("");
  83511. puts(" /* WARNING: this file should *not* be used by applications.");
  83512. puts(" It is part of the implementation of this library and is");
  83513. puts(" subject to change. Applications should only use zlib.h.");
  83514. puts(" */");
  83515. puts("");
  83516. size = 1U << 9;
  83517. printf(" static const code lenfix[%u] = {", size);
  83518. low = 0;
  83519. for (;;) {
  83520. if ((low % 7) == 0) printf("\n ");
  83521. printf("{%u,%u,%d}", state.lencode[low].op, state.lencode[low].bits,
  83522. state.lencode[low].val);
  83523. if (++low == size) break;
  83524. putchar(',');
  83525. }
  83526. puts("\n };");
  83527. size = 1U << 5;
  83528. printf("\n static const code distfix[%u] = {", size);
  83529. low = 0;
  83530. for (;;) {
  83531. if ((low % 6) == 0) printf("\n ");
  83532. printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits,
  83533. state.distcode[low].val);
  83534. if (++low == size) break;
  83535. putchar(',');
  83536. }
  83537. puts("\n };");
  83538. }
  83539. #endif /* MAKEFIXED */
  83540. /*
  83541. Update the window with the last wsize (normally 32K) bytes written before
  83542. returning. If window does not exist yet, create it. This is only called
  83543. when a window is already in use, or when output has been written during this
  83544. inflate call, but the end of the deflate stream has not been reached yet.
  83545. It is also called to create a window for dictionary data when a dictionary
  83546. is loaded.
  83547. Providing output buffers larger than 32K to inflate() should provide a speed
  83548. advantage, since only the last 32K of output is copied to the sliding window
  83549. upon return from inflate(), and since all distances after the first 32K of
  83550. output will fall in the output data, making match copies simpler and faster.
  83551. The advantage may be dependent on the size of the processor's data caches.
  83552. */
  83553. local int updatewindow (z_streamp strm, unsigned out)
  83554. {
  83555. struct inflate_state FAR *state;
  83556. unsigned copy, dist;
  83557. state = (struct inflate_state FAR *)strm->state;
  83558. /* if it hasn't been done already, allocate space for the window */
  83559. if (state->window == Z_NULL) {
  83560. state->window = (unsigned char FAR *)
  83561. ZALLOC(strm, 1U << state->wbits,
  83562. sizeof(unsigned char));
  83563. if (state->window == Z_NULL) return 1;
  83564. }
  83565. /* if window not in use yet, initialize */
  83566. if (state->wsize == 0) {
  83567. state->wsize = 1U << state->wbits;
  83568. state->write = 0;
  83569. state->whave = 0;
  83570. }
  83571. /* copy state->wsize or less output bytes into the circular window */
  83572. copy = out - strm->avail_out;
  83573. if (copy >= state->wsize) {
  83574. zmemcpy(state->window, strm->next_out - state->wsize, state->wsize);
  83575. state->write = 0;
  83576. state->whave = state->wsize;
  83577. }
  83578. else {
  83579. dist = state->wsize - state->write;
  83580. if (dist > copy) dist = copy;
  83581. zmemcpy(state->window + state->write, strm->next_out - copy, dist);
  83582. copy -= dist;
  83583. if (copy) {
  83584. zmemcpy(state->window, strm->next_out - copy, copy);
  83585. state->write = copy;
  83586. state->whave = state->wsize;
  83587. }
  83588. else {
  83589. state->write += dist;
  83590. if (state->write == state->wsize) state->write = 0;
  83591. if (state->whave < state->wsize) state->whave += dist;
  83592. }
  83593. }
  83594. return 0;
  83595. }
  83596. /* Macros for inflate(): */
  83597. /* check function to use adler32() for zlib or crc32() for gzip */
  83598. #ifdef GUNZIP
  83599. # define UPDATE(check, buf, len) \
  83600. (state->flags ? crc32(check, buf, len) : adler32(check, buf, len))
  83601. #else
  83602. # define UPDATE(check, buf, len) adler32(check, buf, len)
  83603. #endif
  83604. /* check macros for header crc */
  83605. #ifdef GUNZIP
  83606. # define CRC2(check, word) \
  83607. do { \
  83608. hbuf[0] = (unsigned char)(word); \
  83609. hbuf[1] = (unsigned char)((word) >> 8); \
  83610. check = crc32(check, hbuf, 2); \
  83611. } while (0)
  83612. # define CRC4(check, word) \
  83613. do { \
  83614. hbuf[0] = (unsigned char)(word); \
  83615. hbuf[1] = (unsigned char)((word) >> 8); \
  83616. hbuf[2] = (unsigned char)((word) >> 16); \
  83617. hbuf[3] = (unsigned char)((word) >> 24); \
  83618. check = crc32(check, hbuf, 4); \
  83619. } while (0)
  83620. #endif
  83621. /* Load registers with state in inflate() for speed */
  83622. #define LOAD() \
  83623. do { \
  83624. put = strm->next_out; \
  83625. left = strm->avail_out; \
  83626. next = strm->next_in; \
  83627. have = strm->avail_in; \
  83628. hold = state->hold; \
  83629. bits = state->bits; \
  83630. } while (0)
  83631. /* Restore state from registers in inflate() */
  83632. #define RESTORE() \
  83633. do { \
  83634. strm->next_out = put; \
  83635. strm->avail_out = left; \
  83636. strm->next_in = next; \
  83637. strm->avail_in = have; \
  83638. state->hold = hold; \
  83639. state->bits = bits; \
  83640. } while (0)
  83641. /* Clear the input bit accumulator */
  83642. #define INITBITS() \
  83643. do { \
  83644. hold = 0; \
  83645. bits = 0; \
  83646. } while (0)
  83647. /* Get a byte of input into the bit accumulator, or return from inflate()
  83648. if there is no input available. */
  83649. #define PULLBYTE() \
  83650. do { \
  83651. if (have == 0) goto inf_leave; \
  83652. have--; \
  83653. hold += (unsigned long)(*next++) << bits; \
  83654. bits += 8; \
  83655. } while (0)
  83656. /* Assure that there are at least n bits in the bit accumulator. If there is
  83657. not enough available input to do that, then return from inflate(). */
  83658. #define NEEDBITS(n) \
  83659. do { \
  83660. while (bits < (unsigned)(n)) \
  83661. PULLBYTE(); \
  83662. } while (0)
  83663. /* Return the low n bits of the bit accumulator (n < 16) */
  83664. #define BITS(n) \
  83665. ((unsigned)hold & ((1U << (n)) - 1))
  83666. /* Remove n bits from the bit accumulator */
  83667. #define DROPBITS(n) \
  83668. do { \
  83669. hold >>= (n); \
  83670. bits -= (unsigned)(n); \
  83671. } while (0)
  83672. /* Remove zero to seven bits as needed to go to a byte boundary */
  83673. #define BYTEBITS() \
  83674. do { \
  83675. hold >>= bits & 7; \
  83676. bits -= bits & 7; \
  83677. } while (0)
  83678. /* Reverse the bytes in a 32-bit value */
  83679. #define REVERSE(q) \
  83680. ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \
  83681. (((q) & 0xff00) << 8) + (((q) & 0xff) << 24))
  83682. /*
  83683. inflate() uses a state machine to process as much input data and generate as
  83684. much output data as possible before returning. The state machine is
  83685. structured roughly as follows:
  83686. for (;;) switch (state) {
  83687. ...
  83688. case STATEn:
  83689. if (not enough input data or output space to make progress)
  83690. return;
  83691. ... make progress ...
  83692. state = STATEm;
  83693. break;
  83694. ...
  83695. }
  83696. so when inflate() is called again, the same case is attempted again, and
  83697. if the appropriate resources are provided, the machine proceeds to the
  83698. next state. The NEEDBITS() macro is usually the way the state evaluates
  83699. whether it can proceed or should return. NEEDBITS() does the return if
  83700. the requested bits are not available. The typical use of the BITS macros
  83701. is:
  83702. NEEDBITS(n);
  83703. ... do something with BITS(n) ...
  83704. DROPBITS(n);
  83705. where NEEDBITS(n) either returns from inflate() if there isn't enough
  83706. input left to load n bits into the accumulator, or it continues. BITS(n)
  83707. gives the low n bits in the accumulator. When done, DROPBITS(n) drops
  83708. the low n bits off the accumulator. INITBITS() clears the accumulator
  83709. and sets the number of available bits to zero. BYTEBITS() discards just
  83710. enough bits to put the accumulator on a byte boundary. After BYTEBITS()
  83711. and a NEEDBITS(8), then BITS(8) would return the next byte in the stream.
  83712. NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return
  83713. if there is no input available. The decoding of variable length codes uses
  83714. PULLBYTE() directly in order to pull just enough bytes to decode the next
  83715. code, and no more.
  83716. Some states loop until they get enough input, making sure that enough
  83717. state information is maintained to continue the loop where it left off
  83718. if NEEDBITS() returns in the loop. For example, want, need, and keep
  83719. would all have to actually be part of the saved state in case NEEDBITS()
  83720. returns:
  83721. case STATEw:
  83722. while (want < need) {
  83723. NEEDBITS(n);
  83724. keep[want++] = BITS(n);
  83725. DROPBITS(n);
  83726. }
  83727. state = STATEx;
  83728. case STATEx:
  83729. As shown above, if the next state is also the next case, then the break
  83730. is omitted.
  83731. A state may also return if there is not enough output space available to
  83732. complete that state. Those states are copying stored data, writing a
  83733. literal byte, and copying a matching string.
  83734. When returning, a "goto inf_leave" is used to update the total counters,
  83735. update the check value, and determine whether any progress has been made
  83736. during that inflate() call in order to return the proper return code.
  83737. Progress is defined as a change in either strm->avail_in or strm->avail_out.
  83738. When there is a window, goto inf_leave will update the window with the last
  83739. output written. If a goto inf_leave occurs in the middle of decompression
  83740. and there is no window currently, goto inf_leave will create one and copy
  83741. output to the window for the next call of inflate().
  83742. In this implementation, the flush parameter of inflate() only affects the
  83743. return code (per zlib.h). inflate() always writes as much as possible to
  83744. strm->next_out, given the space available and the provided input--the effect
  83745. documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers
  83746. the allocation of and copying into a sliding window until necessary, which
  83747. provides the effect documented in zlib.h for Z_FINISH when the entire input
  83748. stream available. So the only thing the flush parameter actually does is:
  83749. when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it
  83750. will return Z_BUF_ERROR if it has not reached the end of the stream.
  83751. */
  83752. int ZEXPORT inflate (z_streamp strm, int flush)
  83753. {
  83754. struct inflate_state FAR *state;
  83755. unsigned char FAR *next; /* next input */
  83756. unsigned char FAR *put; /* next output */
  83757. unsigned have, left; /* available input and output */
  83758. unsigned long hold; /* bit buffer */
  83759. unsigned bits; /* bits in bit buffer */
  83760. unsigned in, out; /* save starting available input and output */
  83761. unsigned copy; /* number of stored or match bytes to copy */
  83762. unsigned char FAR *from; /* where to copy match bytes from */
  83763. code thisx; /* current decoding table entry */
  83764. code last; /* parent table entry */
  83765. unsigned len; /* length to copy for repeats, bits to drop */
  83766. int ret; /* return code */
  83767. #ifdef GUNZIP
  83768. unsigned char hbuf[4]; /* buffer for gzip header crc calculation */
  83769. #endif
  83770. static const unsigned short order[19] = /* permutation of code lengths */
  83771. {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
  83772. if (strm == Z_NULL || strm->state == Z_NULL || strm->next_out == Z_NULL ||
  83773. (strm->next_in == Z_NULL && strm->avail_in != 0))
  83774. return Z_STREAM_ERROR;
  83775. state = (struct inflate_state FAR *)strm->state;
  83776. if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */
  83777. LOAD();
  83778. in = have;
  83779. out = left;
  83780. ret = Z_OK;
  83781. for (;;)
  83782. switch (state->mode) {
  83783. case HEAD:
  83784. if (state->wrap == 0) {
  83785. state->mode = TYPEDO;
  83786. break;
  83787. }
  83788. NEEDBITS(16);
  83789. #ifdef GUNZIP
  83790. if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */
  83791. state->check = crc32(0L, Z_NULL, 0);
  83792. CRC2(state->check, hold);
  83793. INITBITS();
  83794. state->mode = FLAGS;
  83795. break;
  83796. }
  83797. state->flags = 0; /* expect zlib header */
  83798. if (state->head != Z_NULL)
  83799. state->head->done = -1;
  83800. if (!(state->wrap & 1) || /* check if zlib header allowed */
  83801. #else
  83802. if (
  83803. #endif
  83804. ((BITS(8) << 8) + (hold >> 8)) % 31) {
  83805. strm->msg = (char *)"incorrect header check";
  83806. state->mode = BAD;
  83807. break;
  83808. }
  83809. if (BITS(4) != Z_DEFLATED) {
  83810. strm->msg = (char *)"unknown compression method";
  83811. state->mode = BAD;
  83812. break;
  83813. }
  83814. DROPBITS(4);
  83815. len = BITS(4) + 8;
  83816. if (len > state->wbits) {
  83817. strm->msg = (char *)"invalid window size";
  83818. state->mode = BAD;
  83819. break;
  83820. }
  83821. state->dmax = 1U << len;
  83822. Tracev((stderr, "inflate: zlib header ok\n"));
  83823. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  83824. state->mode = hold & 0x200 ? DICTID : TYPE;
  83825. INITBITS();
  83826. break;
  83827. #ifdef GUNZIP
  83828. case FLAGS:
  83829. NEEDBITS(16);
  83830. state->flags = (int)(hold);
  83831. if ((state->flags & 0xff) != Z_DEFLATED) {
  83832. strm->msg = (char *)"unknown compression method";
  83833. state->mode = BAD;
  83834. break;
  83835. }
  83836. if (state->flags & 0xe000) {
  83837. strm->msg = (char *)"unknown header flags set";
  83838. state->mode = BAD;
  83839. break;
  83840. }
  83841. if (state->head != Z_NULL)
  83842. state->head->text = (int)((hold >> 8) & 1);
  83843. if (state->flags & 0x0200) CRC2(state->check, hold);
  83844. INITBITS();
  83845. state->mode = TIME;
  83846. case TIME:
  83847. NEEDBITS(32);
  83848. if (state->head != Z_NULL)
  83849. state->head->time = hold;
  83850. if (state->flags & 0x0200) CRC4(state->check, hold);
  83851. INITBITS();
  83852. state->mode = OS;
  83853. case OS:
  83854. NEEDBITS(16);
  83855. if (state->head != Z_NULL) {
  83856. state->head->xflags = (int)(hold & 0xff);
  83857. state->head->os = (int)(hold >> 8);
  83858. }
  83859. if (state->flags & 0x0200) CRC2(state->check, hold);
  83860. INITBITS();
  83861. state->mode = EXLEN;
  83862. case EXLEN:
  83863. if (state->flags & 0x0400) {
  83864. NEEDBITS(16);
  83865. state->length = (unsigned)(hold);
  83866. if (state->head != Z_NULL)
  83867. state->head->extra_len = (unsigned)hold;
  83868. if (state->flags & 0x0200) CRC2(state->check, hold);
  83869. INITBITS();
  83870. }
  83871. else if (state->head != Z_NULL)
  83872. state->head->extra = Z_NULL;
  83873. state->mode = EXTRA;
  83874. case EXTRA:
  83875. if (state->flags & 0x0400) {
  83876. copy = state->length;
  83877. if (copy > have) copy = have;
  83878. if (copy) {
  83879. if (state->head != Z_NULL &&
  83880. state->head->extra != Z_NULL) {
  83881. len = state->head->extra_len - state->length;
  83882. zmemcpy(state->head->extra + len, next,
  83883. len + copy > state->head->extra_max ?
  83884. state->head->extra_max - len : copy);
  83885. }
  83886. if (state->flags & 0x0200)
  83887. state->check = crc32(state->check, next, copy);
  83888. have -= copy;
  83889. next += copy;
  83890. state->length -= copy;
  83891. }
  83892. if (state->length) goto inf_leave;
  83893. }
  83894. state->length = 0;
  83895. state->mode = NAME;
  83896. case NAME:
  83897. if (state->flags & 0x0800) {
  83898. if (have == 0) goto inf_leave;
  83899. copy = 0;
  83900. do {
  83901. len = (unsigned)(next[copy++]);
  83902. if (state->head != Z_NULL &&
  83903. state->head->name != Z_NULL &&
  83904. state->length < state->head->name_max)
  83905. state->head->name[state->length++] = len;
  83906. } while (len && copy < have);
  83907. if (state->flags & 0x0200)
  83908. state->check = crc32(state->check, next, copy);
  83909. have -= copy;
  83910. next += copy;
  83911. if (len) goto inf_leave;
  83912. }
  83913. else if (state->head != Z_NULL)
  83914. state->head->name = Z_NULL;
  83915. state->length = 0;
  83916. state->mode = COMMENT;
  83917. case COMMENT:
  83918. if (state->flags & 0x1000) {
  83919. if (have == 0) goto inf_leave;
  83920. copy = 0;
  83921. do {
  83922. len = (unsigned)(next[copy++]);
  83923. if (state->head != Z_NULL &&
  83924. state->head->comment != Z_NULL &&
  83925. state->length < state->head->comm_max)
  83926. state->head->comment[state->length++] = len;
  83927. } while (len && copy < have);
  83928. if (state->flags & 0x0200)
  83929. state->check = crc32(state->check, next, copy);
  83930. have -= copy;
  83931. next += copy;
  83932. if (len) goto inf_leave;
  83933. }
  83934. else if (state->head != Z_NULL)
  83935. state->head->comment = Z_NULL;
  83936. state->mode = HCRC;
  83937. case HCRC:
  83938. if (state->flags & 0x0200) {
  83939. NEEDBITS(16);
  83940. if (hold != (state->check & 0xffff)) {
  83941. strm->msg = (char *)"header crc mismatch";
  83942. state->mode = BAD;
  83943. break;
  83944. }
  83945. INITBITS();
  83946. }
  83947. if (state->head != Z_NULL) {
  83948. state->head->hcrc = (int)((state->flags >> 9) & 1);
  83949. state->head->done = 1;
  83950. }
  83951. strm->adler = state->check = crc32(0L, Z_NULL, 0);
  83952. state->mode = TYPE;
  83953. break;
  83954. #endif
  83955. case DICTID:
  83956. NEEDBITS(32);
  83957. strm->adler = state->check = REVERSE(hold);
  83958. INITBITS();
  83959. state->mode = DICT;
  83960. case DICT:
  83961. if (state->havedict == 0) {
  83962. RESTORE();
  83963. return Z_NEED_DICT;
  83964. }
  83965. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  83966. state->mode = TYPE;
  83967. case TYPE:
  83968. if (flush == Z_BLOCK) goto inf_leave;
  83969. case TYPEDO:
  83970. if (state->last) {
  83971. BYTEBITS();
  83972. state->mode = CHECK;
  83973. break;
  83974. }
  83975. NEEDBITS(3);
  83976. state->last = BITS(1);
  83977. DROPBITS(1);
  83978. switch (BITS(2)) {
  83979. case 0: /* stored block */
  83980. Tracev((stderr, "inflate: stored block%s\n",
  83981. state->last ? " (last)" : ""));
  83982. state->mode = STORED;
  83983. break;
  83984. case 1: /* fixed block */
  83985. fixedtables(state);
  83986. Tracev((stderr, "inflate: fixed codes block%s\n",
  83987. state->last ? " (last)" : ""));
  83988. state->mode = LEN; /* decode codes */
  83989. break;
  83990. case 2: /* dynamic block */
  83991. Tracev((stderr, "inflate: dynamic codes block%s\n",
  83992. state->last ? " (last)" : ""));
  83993. state->mode = TABLE;
  83994. break;
  83995. case 3:
  83996. strm->msg = (char *)"invalid block type";
  83997. state->mode = BAD;
  83998. }
  83999. DROPBITS(2);
  84000. break;
  84001. case STORED:
  84002. BYTEBITS(); /* go to byte boundary */
  84003. NEEDBITS(32);
  84004. if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
  84005. strm->msg = (char *)"invalid stored block lengths";
  84006. state->mode = BAD;
  84007. break;
  84008. }
  84009. state->length = (unsigned)hold & 0xffff;
  84010. Tracev((stderr, "inflate: stored length %u\n",
  84011. state->length));
  84012. INITBITS();
  84013. state->mode = COPY;
  84014. case COPY:
  84015. copy = state->length;
  84016. if (copy) {
  84017. if (copy > have) copy = have;
  84018. if (copy > left) copy = left;
  84019. if (copy == 0) goto inf_leave;
  84020. zmemcpy(put, next, copy);
  84021. have -= copy;
  84022. next += copy;
  84023. left -= copy;
  84024. put += copy;
  84025. state->length -= copy;
  84026. break;
  84027. }
  84028. Tracev((stderr, "inflate: stored end\n"));
  84029. state->mode = TYPE;
  84030. break;
  84031. case TABLE:
  84032. NEEDBITS(14);
  84033. state->nlen = BITS(5) + 257;
  84034. DROPBITS(5);
  84035. state->ndist = BITS(5) + 1;
  84036. DROPBITS(5);
  84037. state->ncode = BITS(4) + 4;
  84038. DROPBITS(4);
  84039. #ifndef PKZIP_BUG_WORKAROUND
  84040. if (state->nlen > 286 || state->ndist > 30) {
  84041. strm->msg = (char *)"too many length or distance symbols";
  84042. state->mode = BAD;
  84043. break;
  84044. }
  84045. #endif
  84046. Tracev((stderr, "inflate: table sizes ok\n"));
  84047. state->have = 0;
  84048. state->mode = LENLENS;
  84049. case LENLENS:
  84050. while (state->have < state->ncode) {
  84051. NEEDBITS(3);
  84052. state->lens[order[state->have++]] = (unsigned short)BITS(3);
  84053. DROPBITS(3);
  84054. }
  84055. while (state->have < 19)
  84056. state->lens[order[state->have++]] = 0;
  84057. state->next = state->codes;
  84058. state->lencode = (code const FAR *)(state->next);
  84059. state->lenbits = 7;
  84060. ret = inflate_table(CODES, state->lens, 19, &(state->next),
  84061. &(state->lenbits), state->work);
  84062. if (ret) {
  84063. strm->msg = (char *)"invalid code lengths set";
  84064. state->mode = BAD;
  84065. break;
  84066. }
  84067. Tracev((stderr, "inflate: code lengths ok\n"));
  84068. state->have = 0;
  84069. state->mode = CODELENS;
  84070. case CODELENS:
  84071. while (state->have < state->nlen + state->ndist) {
  84072. for (;;) {
  84073. thisx = state->lencode[BITS(state->lenbits)];
  84074. if ((unsigned)(thisx.bits) <= bits) break;
  84075. PULLBYTE();
  84076. }
  84077. if (thisx.val < 16) {
  84078. NEEDBITS(thisx.bits);
  84079. DROPBITS(thisx.bits);
  84080. state->lens[state->have++] = thisx.val;
  84081. }
  84082. else {
  84083. if (thisx.val == 16) {
  84084. NEEDBITS(thisx.bits + 2);
  84085. DROPBITS(thisx.bits);
  84086. if (state->have == 0) {
  84087. strm->msg = (char *)"invalid bit length repeat";
  84088. state->mode = BAD;
  84089. break;
  84090. }
  84091. len = state->lens[state->have - 1];
  84092. copy = 3 + BITS(2);
  84093. DROPBITS(2);
  84094. }
  84095. else if (thisx.val == 17) {
  84096. NEEDBITS(thisx.bits + 3);
  84097. DROPBITS(thisx.bits);
  84098. len = 0;
  84099. copy = 3 + BITS(3);
  84100. DROPBITS(3);
  84101. }
  84102. else {
  84103. NEEDBITS(thisx.bits + 7);
  84104. DROPBITS(thisx.bits);
  84105. len = 0;
  84106. copy = 11 + BITS(7);
  84107. DROPBITS(7);
  84108. }
  84109. if (state->have + copy > state->nlen + state->ndist) {
  84110. strm->msg = (char *)"invalid bit length repeat";
  84111. state->mode = BAD;
  84112. break;
  84113. }
  84114. while (copy--)
  84115. state->lens[state->have++] = (unsigned short)len;
  84116. }
  84117. }
  84118. /* handle error breaks in while */
  84119. if (state->mode == BAD) break;
  84120. /* build code tables */
  84121. state->next = state->codes;
  84122. state->lencode = (code const FAR *)(state->next);
  84123. state->lenbits = 9;
  84124. ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
  84125. &(state->lenbits), state->work);
  84126. if (ret) {
  84127. strm->msg = (char *)"invalid literal/lengths set";
  84128. state->mode = BAD;
  84129. break;
  84130. }
  84131. state->distcode = (code const FAR *)(state->next);
  84132. state->distbits = 6;
  84133. ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
  84134. &(state->next), &(state->distbits), state->work);
  84135. if (ret) {
  84136. strm->msg = (char *)"invalid distances set";
  84137. state->mode = BAD;
  84138. break;
  84139. }
  84140. Tracev((stderr, "inflate: codes ok\n"));
  84141. state->mode = LEN;
  84142. case LEN:
  84143. if (have >= 6 && left >= 258) {
  84144. RESTORE();
  84145. inflate_fast(strm, out);
  84146. LOAD();
  84147. break;
  84148. }
  84149. for (;;) {
  84150. thisx = state->lencode[BITS(state->lenbits)];
  84151. if ((unsigned)(thisx.bits) <= bits) break;
  84152. PULLBYTE();
  84153. }
  84154. if (thisx.op && (thisx.op & 0xf0) == 0) {
  84155. last = thisx;
  84156. for (;;) {
  84157. thisx = state->lencode[last.val +
  84158. (BITS(last.bits + last.op) >> last.bits)];
  84159. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  84160. PULLBYTE();
  84161. }
  84162. DROPBITS(last.bits);
  84163. }
  84164. DROPBITS(thisx.bits);
  84165. state->length = (unsigned)thisx.val;
  84166. if ((int)(thisx.op) == 0) {
  84167. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  84168. "inflate: literal '%c'\n" :
  84169. "inflate: literal 0x%02x\n", thisx.val));
  84170. state->mode = LIT;
  84171. break;
  84172. }
  84173. if (thisx.op & 32) {
  84174. Tracevv((stderr, "inflate: end of block\n"));
  84175. state->mode = TYPE;
  84176. break;
  84177. }
  84178. if (thisx.op & 64) {
  84179. strm->msg = (char *)"invalid literal/length code";
  84180. state->mode = BAD;
  84181. break;
  84182. }
  84183. state->extra = (unsigned)(thisx.op) & 15;
  84184. state->mode = LENEXT;
  84185. case LENEXT:
  84186. if (state->extra) {
  84187. NEEDBITS(state->extra);
  84188. state->length += BITS(state->extra);
  84189. DROPBITS(state->extra);
  84190. }
  84191. Tracevv((stderr, "inflate: length %u\n", state->length));
  84192. state->mode = DIST;
  84193. case DIST:
  84194. for (;;) {
  84195. thisx = state->distcode[BITS(state->distbits)];
  84196. if ((unsigned)(thisx.bits) <= bits) break;
  84197. PULLBYTE();
  84198. }
  84199. if ((thisx.op & 0xf0) == 0) {
  84200. last = thisx;
  84201. for (;;) {
  84202. thisx = state->distcode[last.val +
  84203. (BITS(last.bits + last.op) >> last.bits)];
  84204. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  84205. PULLBYTE();
  84206. }
  84207. DROPBITS(last.bits);
  84208. }
  84209. DROPBITS(thisx.bits);
  84210. if (thisx.op & 64) {
  84211. strm->msg = (char *)"invalid distance code";
  84212. state->mode = BAD;
  84213. break;
  84214. }
  84215. state->offset = (unsigned)thisx.val;
  84216. state->extra = (unsigned)(thisx.op) & 15;
  84217. state->mode = DISTEXT;
  84218. case DISTEXT:
  84219. if (state->extra) {
  84220. NEEDBITS(state->extra);
  84221. state->offset += BITS(state->extra);
  84222. DROPBITS(state->extra);
  84223. }
  84224. #ifdef INFLATE_STRICT
  84225. if (state->offset > state->dmax) {
  84226. strm->msg = (char *)"invalid distance too far back";
  84227. state->mode = BAD;
  84228. break;
  84229. }
  84230. #endif
  84231. if (state->offset > state->whave + out - left) {
  84232. strm->msg = (char *)"invalid distance too far back";
  84233. state->mode = BAD;
  84234. break;
  84235. }
  84236. Tracevv((stderr, "inflate: distance %u\n", state->offset));
  84237. state->mode = MATCH;
  84238. case MATCH:
  84239. if (left == 0) goto inf_leave;
  84240. copy = out - left;
  84241. if (state->offset > copy) { /* copy from window */
  84242. copy = state->offset - copy;
  84243. if (copy > state->write) {
  84244. copy -= state->write;
  84245. from = state->window + (state->wsize - copy);
  84246. }
  84247. else
  84248. from = state->window + (state->write - copy);
  84249. if (copy > state->length) copy = state->length;
  84250. }
  84251. else { /* copy from output */
  84252. from = put - state->offset;
  84253. copy = state->length;
  84254. }
  84255. if (copy > left) copy = left;
  84256. left -= copy;
  84257. state->length -= copy;
  84258. do {
  84259. *put++ = *from++;
  84260. } while (--copy);
  84261. if (state->length == 0) state->mode = LEN;
  84262. break;
  84263. case LIT:
  84264. if (left == 0) goto inf_leave;
  84265. *put++ = (unsigned char)(state->length);
  84266. left--;
  84267. state->mode = LEN;
  84268. break;
  84269. case CHECK:
  84270. if (state->wrap) {
  84271. NEEDBITS(32);
  84272. out -= left;
  84273. strm->total_out += out;
  84274. state->total += out;
  84275. if (out)
  84276. strm->adler = state->check =
  84277. UPDATE(state->check, put - out, out);
  84278. out = left;
  84279. if ((
  84280. #ifdef GUNZIP
  84281. state->flags ? hold :
  84282. #endif
  84283. REVERSE(hold)) != state->check) {
  84284. strm->msg = (char *)"incorrect data check";
  84285. state->mode = BAD;
  84286. break;
  84287. }
  84288. INITBITS();
  84289. Tracev((stderr, "inflate: check matches trailer\n"));
  84290. }
  84291. #ifdef GUNZIP
  84292. state->mode = LENGTH;
  84293. case LENGTH:
  84294. if (state->wrap && state->flags) {
  84295. NEEDBITS(32);
  84296. if (hold != (state->total & 0xffffffffUL)) {
  84297. strm->msg = (char *)"incorrect length check";
  84298. state->mode = BAD;
  84299. break;
  84300. }
  84301. INITBITS();
  84302. Tracev((stderr, "inflate: length matches trailer\n"));
  84303. }
  84304. #endif
  84305. state->mode = DONE;
  84306. case DONE:
  84307. ret = Z_STREAM_END;
  84308. goto inf_leave;
  84309. case BAD:
  84310. ret = Z_DATA_ERROR;
  84311. goto inf_leave;
  84312. case MEM:
  84313. return Z_MEM_ERROR;
  84314. case SYNC:
  84315. default:
  84316. return Z_STREAM_ERROR;
  84317. }
  84318. /*
  84319. Return from inflate(), updating the total counts and the check value.
  84320. If there was no progress during the inflate() call, return a buffer
  84321. error. Call updatewindow() to create and/or update the window state.
  84322. Note: a memory error from inflate() is non-recoverable.
  84323. */
  84324. inf_leave:
  84325. RESTORE();
  84326. if (state->wsize || (state->mode < CHECK && out != strm->avail_out))
  84327. if (updatewindow(strm, out)) {
  84328. state->mode = MEM;
  84329. return Z_MEM_ERROR;
  84330. }
  84331. in -= strm->avail_in;
  84332. out -= strm->avail_out;
  84333. strm->total_in += in;
  84334. strm->total_out += out;
  84335. state->total += out;
  84336. if (state->wrap && out)
  84337. strm->adler = state->check =
  84338. UPDATE(state->check, strm->next_out - out, out);
  84339. strm->data_type = state->bits + (state->last ? 64 : 0) +
  84340. (state->mode == TYPE ? 128 : 0);
  84341. if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
  84342. ret = Z_BUF_ERROR;
  84343. return ret;
  84344. }
  84345. int ZEXPORT inflateEnd (z_streamp strm)
  84346. {
  84347. struct inflate_state FAR *state;
  84348. if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
  84349. return Z_STREAM_ERROR;
  84350. state = (struct inflate_state FAR *)strm->state;
  84351. if (state->window != Z_NULL) ZFREE(strm, state->window);
  84352. ZFREE(strm, strm->state);
  84353. strm->state = Z_NULL;
  84354. Tracev((stderr, "inflate: end\n"));
  84355. return Z_OK;
  84356. }
  84357. int ZEXPORT inflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  84358. {
  84359. struct inflate_state FAR *state;
  84360. unsigned long id_;
  84361. /* check state */
  84362. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84363. state = (struct inflate_state FAR *)strm->state;
  84364. if (state->wrap != 0 && state->mode != DICT)
  84365. return Z_STREAM_ERROR;
  84366. /* check for correct dictionary id */
  84367. if (state->mode == DICT) {
  84368. id_ = adler32(0L, Z_NULL, 0);
  84369. id_ = adler32(id_, dictionary, dictLength);
  84370. if (id_ != state->check)
  84371. return Z_DATA_ERROR;
  84372. }
  84373. /* copy dictionary to window */
  84374. if (updatewindow(strm, strm->avail_out)) {
  84375. state->mode = MEM;
  84376. return Z_MEM_ERROR;
  84377. }
  84378. if (dictLength > state->wsize) {
  84379. zmemcpy(state->window, dictionary + dictLength - state->wsize,
  84380. state->wsize);
  84381. state->whave = state->wsize;
  84382. }
  84383. else {
  84384. zmemcpy(state->window + state->wsize - dictLength, dictionary,
  84385. dictLength);
  84386. state->whave = dictLength;
  84387. }
  84388. state->havedict = 1;
  84389. Tracev((stderr, "inflate: dictionary set\n"));
  84390. return Z_OK;
  84391. }
  84392. int ZEXPORT inflateGetHeader (z_streamp strm, gz_headerp head)
  84393. {
  84394. struct inflate_state FAR *state;
  84395. /* check state */
  84396. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84397. state = (struct inflate_state FAR *)strm->state;
  84398. if ((state->wrap & 2) == 0) return Z_STREAM_ERROR;
  84399. /* save header structure */
  84400. state->head = head;
  84401. head->done = 0;
  84402. return Z_OK;
  84403. }
  84404. /*
  84405. Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found
  84406. or when out of input. When called, *have is the number of pattern bytes
  84407. found in order so far, in 0..3. On return *have is updated to the new
  84408. state. If on return *have equals four, then the pattern was found and the
  84409. return value is how many bytes were read including the last byte of the
  84410. pattern. If *have is less than four, then the pattern has not been found
  84411. yet and the return value is len. In the latter case, syncsearch() can be
  84412. called again with more data and the *have state. *have is initialized to
  84413. zero for the first call.
  84414. */
  84415. local unsigned syncsearch (unsigned FAR *have, unsigned char FAR *buf, unsigned len)
  84416. {
  84417. unsigned got;
  84418. unsigned next;
  84419. got = *have;
  84420. next = 0;
  84421. while (next < len && got < 4) {
  84422. if ((int)(buf[next]) == (got < 2 ? 0 : 0xff))
  84423. got++;
  84424. else if (buf[next])
  84425. got = 0;
  84426. else
  84427. got = 4 - got;
  84428. next++;
  84429. }
  84430. *have = got;
  84431. return next;
  84432. }
  84433. int ZEXPORT inflateSync (z_streamp strm)
  84434. {
  84435. unsigned len; /* number of bytes to look at or looked at */
  84436. unsigned long in, out; /* temporary to save total_in and total_out */
  84437. unsigned char buf[4]; /* to restore bit buffer to byte string */
  84438. struct inflate_state FAR *state;
  84439. /* check parameters */
  84440. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84441. state = (struct inflate_state FAR *)strm->state;
  84442. if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR;
  84443. /* if first time, start search in bit buffer */
  84444. if (state->mode != SYNC) {
  84445. state->mode = SYNC;
  84446. state->hold <<= state->bits & 7;
  84447. state->bits -= state->bits & 7;
  84448. len = 0;
  84449. while (state->bits >= 8) {
  84450. buf[len++] = (unsigned char)(state->hold);
  84451. state->hold >>= 8;
  84452. state->bits -= 8;
  84453. }
  84454. state->have = 0;
  84455. syncsearch(&(state->have), buf, len);
  84456. }
  84457. /* search available input */
  84458. len = syncsearch(&(state->have), strm->next_in, strm->avail_in);
  84459. strm->avail_in -= len;
  84460. strm->next_in += len;
  84461. strm->total_in += len;
  84462. /* return no joy or set up to restart inflate() on a new block */
  84463. if (state->have != 4) return Z_DATA_ERROR;
  84464. in = strm->total_in; out = strm->total_out;
  84465. inflateReset(strm);
  84466. strm->total_in = in; strm->total_out = out;
  84467. state->mode = TYPE;
  84468. return Z_OK;
  84469. }
  84470. /*
  84471. Returns true if inflate is currently at the end of a block generated by
  84472. Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
  84473. implementation to provide an additional safety check. PPP uses
  84474. Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored
  84475. block. When decompressing, PPP checks that at the end of input packet,
  84476. inflate is waiting for these length bytes.
  84477. */
  84478. int ZEXPORT inflateSyncPoint (z_streamp strm)
  84479. {
  84480. struct inflate_state FAR *state;
  84481. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84482. state = (struct inflate_state FAR *)strm->state;
  84483. return state->mode == STORED && state->bits == 0;
  84484. }
  84485. int ZEXPORT inflateCopy(z_streamp dest, z_streamp source)
  84486. {
  84487. struct inflate_state FAR *state;
  84488. struct inflate_state FAR *copy;
  84489. unsigned char FAR *window;
  84490. unsigned wsize;
  84491. /* check input */
  84492. if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL ||
  84493. source->zalloc == (alloc_func)0 || source->zfree == (free_func)0)
  84494. return Z_STREAM_ERROR;
  84495. state = (struct inflate_state FAR *)source->state;
  84496. /* allocate space */
  84497. copy = (struct inflate_state FAR *)
  84498. ZALLOC(source, 1, sizeof(struct inflate_state));
  84499. if (copy == Z_NULL) return Z_MEM_ERROR;
  84500. window = Z_NULL;
  84501. if (state->window != Z_NULL) {
  84502. window = (unsigned char FAR *)
  84503. ZALLOC(source, 1U << state->wbits, sizeof(unsigned char));
  84504. if (window == Z_NULL) {
  84505. ZFREE(source, copy);
  84506. return Z_MEM_ERROR;
  84507. }
  84508. }
  84509. /* copy state */
  84510. zmemcpy(dest, source, sizeof(z_stream));
  84511. zmemcpy(copy, state, sizeof(struct inflate_state));
  84512. if (state->lencode >= state->codes &&
  84513. state->lencode <= state->codes + ENOUGH - 1) {
  84514. copy->lencode = copy->codes + (state->lencode - state->codes);
  84515. copy->distcode = copy->codes + (state->distcode - state->codes);
  84516. }
  84517. copy->next = copy->codes + (state->next - state->codes);
  84518. if (window != Z_NULL) {
  84519. wsize = 1U << state->wbits;
  84520. zmemcpy(window, state->window, wsize);
  84521. }
  84522. copy->window = window;
  84523. dest->state = (struct internal_state FAR *)copy;
  84524. return Z_OK;
  84525. }
  84526. /*** End of inlined file: inflate.c ***/
  84527. /*** Start of inlined file: inftrees.c ***/
  84528. #define MAXBITS 15
  84529. const char inflate_copyright[] =
  84530. " inflate 1.2.3 Copyright 1995-2005 Mark Adler ";
  84531. /*
  84532. If you use the zlib library in a product, an acknowledgment is welcome
  84533. in the documentation of your product. If for some reason you cannot
  84534. include such an acknowledgment, I would appreciate that you keep this
  84535. copyright string in the executable of your product.
  84536. */
  84537. /*
  84538. Build a set of tables to decode the provided canonical Huffman code.
  84539. The code lengths are lens[0..codes-1]. The result starts at *table,
  84540. whose indices are 0..2^bits-1. work is a writable array of at least
  84541. lens shorts, which is used as a work area. type is the type of code
  84542. to be generated, CODES, LENS, or DISTS. On return, zero is success,
  84543. -1 is an invalid code, and +1 means that ENOUGH isn't enough. table
  84544. on return points to the next available entry's address. bits is the
  84545. requested root table index bits, and on return it is the actual root
  84546. table index bits. It will differ if the request is greater than the
  84547. longest code or if it is less than the shortest code.
  84548. */
  84549. int inflate_table (codetype type,
  84550. unsigned short FAR *lens,
  84551. unsigned codes,
  84552. code FAR * FAR *table,
  84553. unsigned FAR *bits,
  84554. unsigned short FAR *work)
  84555. {
  84556. unsigned len; /* a code's length in bits */
  84557. unsigned sym; /* index of code symbols */
  84558. unsigned min, max; /* minimum and maximum code lengths */
  84559. unsigned root; /* number of index bits for root table */
  84560. unsigned curr; /* number of index bits for current table */
  84561. unsigned drop; /* code bits to drop for sub-table */
  84562. int left; /* number of prefix codes available */
  84563. unsigned used; /* code entries in table used */
  84564. unsigned huff; /* Huffman code */
  84565. unsigned incr; /* for incrementing code, index */
  84566. unsigned fill; /* index for replicating entries */
  84567. unsigned low; /* low bits for current root entry */
  84568. unsigned mask; /* mask for low root bits */
  84569. code thisx; /* table entry for duplication */
  84570. code FAR *next; /* next available space in table */
  84571. const unsigned short FAR *base; /* base value table to use */
  84572. const unsigned short FAR *extra; /* extra bits table to use */
  84573. int end; /* use base and extra for symbol > end */
  84574. unsigned short count[MAXBITS+1]; /* number of codes of each length */
  84575. unsigned short offs[MAXBITS+1]; /* offsets in table for each length */
  84576. static const unsigned short lbase[31] = { /* Length codes 257..285 base */
  84577. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  84578. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
  84579. static const unsigned short lext[31] = { /* Length codes 257..285 extra */
  84580. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  84581. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 201, 196};
  84582. static const unsigned short dbase[32] = { /* Distance codes 0..29 base */
  84583. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  84584. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  84585. 8193, 12289, 16385, 24577, 0, 0};
  84586. static const unsigned short dext[32] = { /* Distance codes 0..29 extra */
  84587. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  84588. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  84589. 28, 28, 29, 29, 64, 64};
  84590. /*
  84591. Process a set of code lengths to create a canonical Huffman code. The
  84592. code lengths are lens[0..codes-1]. Each length corresponds to the
  84593. symbols 0..codes-1. The Huffman code is generated by first sorting the
  84594. symbols by length from short to long, and retaining the symbol order
  84595. for codes with equal lengths. Then the code starts with all zero bits
  84596. for the first code of the shortest length, and the codes are integer
  84597. increments for the same length, and zeros are appended as the length
  84598. increases. For the deflate format, these bits are stored backwards
  84599. from their more natural integer increment ordering, and so when the
  84600. decoding tables are built in the large loop below, the integer codes
  84601. are incremented backwards.
  84602. This routine assumes, but does not check, that all of the entries in
  84603. lens[] are in the range 0..MAXBITS. The caller must assure this.
  84604. 1..MAXBITS is interpreted as that code length. zero means that that
  84605. symbol does not occur in this code.
  84606. The codes are sorted by computing a count of codes for each length,
  84607. creating from that a table of starting indices for each length in the
  84608. sorted table, and then entering the symbols in order in the sorted
  84609. table. The sorted table is work[], with that space being provided by
  84610. the caller.
  84611. The length counts are used for other purposes as well, i.e. finding
  84612. the minimum and maximum length codes, determining if there are any
  84613. codes at all, checking for a valid set of lengths, and looking ahead
  84614. at length counts to determine sub-table sizes when building the
  84615. decoding tables.
  84616. */
  84617. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  84618. for (len = 0; len <= MAXBITS; len++)
  84619. count[len] = 0;
  84620. for (sym = 0; sym < codes; sym++)
  84621. count[lens[sym]]++;
  84622. /* bound code lengths, force root to be within code lengths */
  84623. root = *bits;
  84624. for (max = MAXBITS; max >= 1; max--)
  84625. if (count[max] != 0) break;
  84626. if (root > max) root = max;
  84627. if (max == 0) { /* no symbols to code at all */
  84628. thisx.op = (unsigned char)64; /* invalid code marker */
  84629. thisx.bits = (unsigned char)1;
  84630. thisx.val = (unsigned short)0;
  84631. *(*table)++ = thisx; /* make a table to force an error */
  84632. *(*table)++ = thisx;
  84633. *bits = 1;
  84634. return 0; /* no symbols, but wait for decoding to report error */
  84635. }
  84636. for (min = 1; min <= MAXBITS; min++)
  84637. if (count[min] != 0) break;
  84638. if (root < min) root = min;
  84639. /* check for an over-subscribed or incomplete set of lengths */
  84640. left = 1;
  84641. for (len = 1; len <= MAXBITS; len++) {
  84642. left <<= 1;
  84643. left -= count[len];
  84644. if (left < 0) return -1; /* over-subscribed */
  84645. }
  84646. if (left > 0 && (type == CODES || max != 1))
  84647. return -1; /* incomplete set */
  84648. /* generate offsets into symbol table for each length for sorting */
  84649. offs[1] = 0;
  84650. for (len = 1; len < MAXBITS; len++)
  84651. offs[len + 1] = offs[len] + count[len];
  84652. /* sort symbols by length, by symbol order within each length */
  84653. for (sym = 0; sym < codes; sym++)
  84654. if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym;
  84655. /*
  84656. Create and fill in decoding tables. In this loop, the table being
  84657. filled is at next and has curr index bits. The code being used is huff
  84658. with length len. That code is converted to an index by dropping drop
  84659. bits off of the bottom. For codes where len is less than drop + curr,
  84660. those top drop + curr - len bits are incremented through all values to
  84661. fill the table with replicated entries.
  84662. root is the number of index bits for the root table. When len exceeds
  84663. root, sub-tables are created pointed to by the root entry with an index
  84664. of the low root bits of huff. This is saved in low to check for when a
  84665. new sub-table should be started. drop is zero when the root table is
  84666. being filled, and drop is root when sub-tables are being filled.
  84667. When a new sub-table is needed, it is necessary to look ahead in the
  84668. code lengths to determine what size sub-table is needed. The length
  84669. counts are used for this, and so count[] is decremented as codes are
  84670. entered in the tables.
  84671. used keeps track of how many table entries have been allocated from the
  84672. provided *table space. It is checked when a LENS table is being made
  84673. against the space in *table, ENOUGH, minus the maximum space needed by
  84674. the worst case distance code, MAXD. This should never happen, but the
  84675. sufficiency of ENOUGH has not been proven exhaustively, hence the check.
  84676. This assumes that when type == LENS, bits == 9.
  84677. sym increments through all symbols, and the loop terminates when
  84678. all codes of length max, i.e. all codes, have been processed. This
  84679. routine permits incomplete codes, so another loop after this one fills
  84680. in the rest of the decoding tables with invalid code markers.
  84681. */
  84682. /* set up for code type */
  84683. switch (type) {
  84684. case CODES:
  84685. base = extra = work; /* dummy value--not used */
  84686. end = 19;
  84687. break;
  84688. case LENS:
  84689. base = lbase;
  84690. base -= 257;
  84691. extra = lext;
  84692. extra -= 257;
  84693. end = 256;
  84694. break;
  84695. default: /* DISTS */
  84696. base = dbase;
  84697. extra = dext;
  84698. end = -1;
  84699. }
  84700. /* initialize state for loop */
  84701. huff = 0; /* starting code */
  84702. sym = 0; /* starting code symbol */
  84703. len = min; /* starting code length */
  84704. next = *table; /* current table to fill in */
  84705. curr = root; /* current table index bits */
  84706. drop = 0; /* current bits to drop from code for index */
  84707. low = (unsigned)(-1); /* trigger new sub-table when len > root */
  84708. used = 1U << root; /* use root table entries */
  84709. mask = used - 1; /* mask for comparing low */
  84710. /* check available table space */
  84711. if (type == LENS && used >= ENOUGH - MAXD)
  84712. return 1;
  84713. /* process all codes and make table entries */
  84714. for (;;) {
  84715. /* create table entry */
  84716. thisx.bits = (unsigned char)(len - drop);
  84717. if ((int)(work[sym]) < end) {
  84718. thisx.op = (unsigned char)0;
  84719. thisx.val = work[sym];
  84720. }
  84721. else if ((int)(work[sym]) > end) {
  84722. thisx.op = (unsigned char)(extra[work[sym]]);
  84723. thisx.val = base[work[sym]];
  84724. }
  84725. else {
  84726. thisx.op = (unsigned char)(32 + 64); /* end of block */
  84727. thisx.val = 0;
  84728. }
  84729. /* replicate for those indices with low len bits equal to huff */
  84730. incr = 1U << (len - drop);
  84731. fill = 1U << curr;
  84732. min = fill; /* save offset to next table */
  84733. do {
  84734. fill -= incr;
  84735. next[(huff >> drop) + fill] = thisx;
  84736. } while (fill != 0);
  84737. /* backwards increment the len-bit code huff */
  84738. incr = 1U << (len - 1);
  84739. while (huff & incr)
  84740. incr >>= 1;
  84741. if (incr != 0) {
  84742. huff &= incr - 1;
  84743. huff += incr;
  84744. }
  84745. else
  84746. huff = 0;
  84747. /* go to next symbol, update count, len */
  84748. sym++;
  84749. if (--(count[len]) == 0) {
  84750. if (len == max) break;
  84751. len = lens[work[sym]];
  84752. }
  84753. /* create new sub-table if needed */
  84754. if (len > root && (huff & mask) != low) {
  84755. /* if first time, transition to sub-tables */
  84756. if (drop == 0)
  84757. drop = root;
  84758. /* increment past last table */
  84759. next += min; /* here min is 1 << curr */
  84760. /* determine length of next table */
  84761. curr = len - drop;
  84762. left = (int)(1 << curr);
  84763. while (curr + drop < max) {
  84764. left -= count[curr + drop];
  84765. if (left <= 0) break;
  84766. curr++;
  84767. left <<= 1;
  84768. }
  84769. /* check for enough space */
  84770. used += 1U << curr;
  84771. if (type == LENS && used >= ENOUGH - MAXD)
  84772. return 1;
  84773. /* point entry in root table to sub-table */
  84774. low = huff & mask;
  84775. (*table)[low].op = (unsigned char)curr;
  84776. (*table)[low].bits = (unsigned char)root;
  84777. (*table)[low].val = (unsigned short)(next - *table);
  84778. }
  84779. }
  84780. /*
  84781. Fill in rest of table for incomplete codes. This loop is similar to the
  84782. loop above in incrementing huff for table indices. It is assumed that
  84783. len is equal to curr + drop, so there is no loop needed to increment
  84784. through high index bits. When the current sub-table is filled, the loop
  84785. drops back to the root table to fill in any remaining entries there.
  84786. */
  84787. thisx.op = (unsigned char)64; /* invalid code marker */
  84788. thisx.bits = (unsigned char)(len - drop);
  84789. thisx.val = (unsigned short)0;
  84790. while (huff != 0) {
  84791. /* when done with sub-table, drop back to root table */
  84792. if (drop != 0 && (huff & mask) != low) {
  84793. drop = 0;
  84794. len = root;
  84795. next = *table;
  84796. thisx.bits = (unsigned char)len;
  84797. }
  84798. /* put invalid code marker in table */
  84799. next[huff >> drop] = thisx;
  84800. /* backwards increment the len-bit code huff */
  84801. incr = 1U << (len - 1);
  84802. while (huff & incr)
  84803. incr >>= 1;
  84804. if (incr != 0) {
  84805. huff &= incr - 1;
  84806. huff += incr;
  84807. }
  84808. else
  84809. huff = 0;
  84810. }
  84811. /* set return parameters */
  84812. *table += used;
  84813. *bits = root;
  84814. return 0;
  84815. }
  84816. /*** End of inlined file: inftrees.c ***/
  84817. /*** Start of inlined file: trees.c ***/
  84818. /*
  84819. * ALGORITHM
  84820. *
  84821. * The "deflation" process uses several Huffman trees. The more
  84822. * common source values are represented by shorter bit sequences.
  84823. *
  84824. * Each code tree is stored in a compressed form which is itself
  84825. * a Huffman encoding of the lengths of all the code strings (in
  84826. * ascending order by source values). The actual code strings are
  84827. * reconstructed from the lengths in the inflate process, as described
  84828. * in the deflate specification.
  84829. *
  84830. * REFERENCES
  84831. *
  84832. * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
  84833. * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
  84834. *
  84835. * Storer, James A.
  84836. * Data Compression: Methods and Theory, pp. 49-50.
  84837. * Computer Science Press, 1988. ISBN 0-7167-8156-5.
  84838. *
  84839. * Sedgewick, R.
  84840. * Algorithms, p290.
  84841. * Addison-Wesley, 1983. ISBN 0-201-06672-6.
  84842. */
  84843. /* @(#) $Id: trees.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  84844. /* #define GEN_TREES_H */
  84845. #ifdef DEBUG
  84846. # include <ctype.h>
  84847. #endif
  84848. /* ===========================================================================
  84849. * Constants
  84850. */
  84851. #define MAX_BL_BITS 7
  84852. /* Bit length codes must not exceed MAX_BL_BITS bits */
  84853. #define END_BLOCK 256
  84854. /* end of block literal code */
  84855. #define REP_3_6 16
  84856. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  84857. #define REPZ_3_10 17
  84858. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  84859. #define REPZ_11_138 18
  84860. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  84861. local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
  84862. = {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};
  84863. local const int extra_dbits[D_CODES] /* extra bits for each distance code */
  84864. = {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};
  84865. local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
  84866. = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
  84867. local const uch bl_order[BL_CODES]
  84868. = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
  84869. /* The lengths of the bit length codes are sent in order of decreasing
  84870. * probability, to avoid transmitting the lengths for unused bit length codes.
  84871. */
  84872. #define Buf_size (8 * 2*sizeof(char))
  84873. /* Number of bits used within bi_buf. (bi_buf might be implemented on
  84874. * more than 16 bits on some systems.)
  84875. */
  84876. /* ===========================================================================
  84877. * Local data. These are initialized only once.
  84878. */
  84879. #define DIST_CODE_LEN 512 /* see definition of array dist_code below */
  84880. #if defined(GEN_TREES_H) || !defined(STDC)
  84881. /* non ANSI compilers may not accept trees.h */
  84882. local ct_data static_ltree[L_CODES+2];
  84883. /* The static literal tree. Since the bit lengths are imposed, there is no
  84884. * need for the L_CODES extra codes used during heap construction. However
  84885. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  84886. * below).
  84887. */
  84888. local ct_data static_dtree[D_CODES];
  84889. /* The static distance tree. (Actually a trivial tree since all codes use
  84890. * 5 bits.)
  84891. */
  84892. uch _dist_code[DIST_CODE_LEN];
  84893. /* Distance codes. The first 256 values correspond to the distances
  84894. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  84895. * the 15 bit distances.
  84896. */
  84897. uch _length_code[MAX_MATCH-MIN_MATCH+1];
  84898. /* length code for each normalized match length (0 == MIN_MATCH) */
  84899. local int base_length[LENGTH_CODES];
  84900. /* First normalized length for each code (0 = MIN_MATCH) */
  84901. local int base_dist[D_CODES];
  84902. /* First normalized distance for each code (0 = distance of 1) */
  84903. #else
  84904. /*** Start of inlined file: trees.h ***/
  84905. local const ct_data static_ltree[L_CODES+2] = {
  84906. {{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}},
  84907. {{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}},
  84908. {{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}},
  84909. {{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}},
  84910. {{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}},
  84911. {{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}},
  84912. {{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}},
  84913. {{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}},
  84914. {{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}},
  84915. {{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}},
  84916. {{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}},
  84917. {{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}},
  84918. {{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}},
  84919. {{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}},
  84920. {{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}},
  84921. {{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}},
  84922. {{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}},
  84923. {{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}},
  84924. {{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}},
  84925. {{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}},
  84926. {{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}},
  84927. {{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}},
  84928. {{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}},
  84929. {{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}},
  84930. {{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}},
  84931. {{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}},
  84932. {{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}},
  84933. {{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}},
  84934. {{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}},
  84935. {{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}},
  84936. {{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}},
  84937. {{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}},
  84938. {{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}},
  84939. {{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}},
  84940. {{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}},
  84941. {{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}},
  84942. {{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}},
  84943. {{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}},
  84944. {{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}},
  84945. {{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}},
  84946. {{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}},
  84947. {{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}},
  84948. {{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}},
  84949. {{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}},
  84950. {{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}},
  84951. {{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}},
  84952. {{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}},
  84953. {{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}},
  84954. {{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}},
  84955. {{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}},
  84956. {{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}},
  84957. {{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}},
  84958. {{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}},
  84959. {{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}},
  84960. {{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}},
  84961. {{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}},
  84962. {{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}},
  84963. {{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}}
  84964. };
  84965. local const ct_data static_dtree[D_CODES] = {
  84966. {{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}},
  84967. {{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}},
  84968. {{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}},
  84969. {{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}},
  84970. {{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}},
  84971. {{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}}
  84972. };
  84973. const uch _dist_code[DIST_CODE_LEN] = {
  84974. 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8,
  84975. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10,
  84976. 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
  84977. 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
  84978. 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
  84979. 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
  84980. 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  84981. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  84982. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  84983. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
  84984. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  84985. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  84986. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17,
  84987. 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
  84988. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  84989. 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  84990. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  84991. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
  84992. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  84993. 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  84994. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  84995. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  84996. 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  84997. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  84998. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  84999. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
  85000. };
  85001. const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {
  85002. 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12,
  85003. 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
  85004. 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
  85005. 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
  85006. 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
  85007. 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
  85008. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  85009. 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  85010. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  85011. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
  85012. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  85013. 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  85014. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
  85015. };
  85016. local const int base_length[LENGTH_CODES] = {
  85017. 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
  85018. 64, 80, 96, 112, 128, 160, 192, 224, 0
  85019. };
  85020. local const int base_dist[D_CODES] = {
  85021. 0, 1, 2, 3, 4, 6, 8, 12, 16, 24,
  85022. 32, 48, 64, 96, 128, 192, 256, 384, 512, 768,
  85023. 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576
  85024. };
  85025. /*** End of inlined file: trees.h ***/
  85026. #endif /* GEN_TREES_H */
  85027. struct static_tree_desc_s {
  85028. const ct_data *static_tree; /* static tree or NULL */
  85029. const intf *extra_bits; /* extra bits for each code or NULL */
  85030. int extra_base; /* base index for extra_bits */
  85031. int elems; /* max number of elements in the tree */
  85032. int max_length; /* max bit length for the codes */
  85033. };
  85034. local static_tree_desc static_l_desc =
  85035. {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
  85036. local static_tree_desc static_d_desc =
  85037. {static_dtree, extra_dbits, 0, D_CODES, MAX_BITS};
  85038. local static_tree_desc static_bl_desc =
  85039. {(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS};
  85040. /* ===========================================================================
  85041. * Local (static) routines in this file.
  85042. */
  85043. local void tr_static_init OF((void));
  85044. local void init_block OF((deflate_state *s));
  85045. local void pqdownheap OF((deflate_state *s, ct_data *tree, int k));
  85046. local void gen_bitlen OF((deflate_state *s, tree_desc *desc));
  85047. local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count));
  85048. local void build_tree OF((deflate_state *s, tree_desc *desc));
  85049. local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code));
  85050. local void send_tree OF((deflate_state *s, ct_data *tree, int max_code));
  85051. local int build_bl_tree OF((deflate_state *s));
  85052. local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
  85053. int blcodes));
  85054. local void compress_block OF((deflate_state *s, ct_data *ltree,
  85055. ct_data *dtree));
  85056. local void set_data_type OF((deflate_state *s));
  85057. local unsigned bi_reverse OF((unsigned value, int length));
  85058. local void bi_windup OF((deflate_state *s));
  85059. local void bi_flush OF((deflate_state *s));
  85060. local void copy_block OF((deflate_state *s, charf *buf, unsigned len,
  85061. int header));
  85062. #ifdef GEN_TREES_H
  85063. local void gen_trees_header OF((void));
  85064. #endif
  85065. #ifndef DEBUG
  85066. # define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
  85067. /* Send a code of the given tree. c and tree must not have side effects */
  85068. #else /* DEBUG */
  85069. # define send_code(s, c, tree) \
  85070. { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
  85071. send_bits(s, tree[c].Code, tree[c].Len); }
  85072. #endif
  85073. /* ===========================================================================
  85074. * Output a short LSB first on the stream.
  85075. * IN assertion: there is enough room in pendingBuf.
  85076. */
  85077. #define put_short(s, w) { \
  85078. put_byte(s, (uch)((w) & 0xff)); \
  85079. put_byte(s, (uch)((ush)(w) >> 8)); \
  85080. }
  85081. /* ===========================================================================
  85082. * Send a value on a given number of bits.
  85083. * IN assertion: length <= 16 and value fits in length bits.
  85084. */
  85085. #ifdef DEBUG
  85086. local void send_bits OF((deflate_state *s, int value, int length));
  85087. local void send_bits (deflate_state *s, int value, int length)
  85088. {
  85089. Tracevv((stderr," l %2d v %4x ", length, value));
  85090. Assert(length > 0 && length <= 15, "invalid length");
  85091. s->bits_sent += (ulg)length;
  85092. /* If not enough room in bi_buf, use (valid) bits from bi_buf and
  85093. * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
  85094. * unused bits in value.
  85095. */
  85096. if (s->bi_valid > (int)Buf_size - length) {
  85097. s->bi_buf |= (value << s->bi_valid);
  85098. put_short(s, s->bi_buf);
  85099. s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
  85100. s->bi_valid += length - Buf_size;
  85101. } else {
  85102. s->bi_buf |= value << s->bi_valid;
  85103. s->bi_valid += length;
  85104. }
  85105. }
  85106. #else /* !DEBUG */
  85107. #define send_bits(s, value, length) \
  85108. { int len = length;\
  85109. if (s->bi_valid > (int)Buf_size - len) {\
  85110. int val = value;\
  85111. s->bi_buf |= (val << s->bi_valid);\
  85112. put_short(s, s->bi_buf);\
  85113. s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
  85114. s->bi_valid += len - Buf_size;\
  85115. } else {\
  85116. s->bi_buf |= (value) << s->bi_valid;\
  85117. s->bi_valid += len;\
  85118. }\
  85119. }
  85120. #endif /* DEBUG */
  85121. /* the arguments must not have side effects */
  85122. /* ===========================================================================
  85123. * Initialize the various 'constant' tables.
  85124. */
  85125. local void tr_static_init()
  85126. {
  85127. #if defined(GEN_TREES_H) || !defined(STDC)
  85128. static int static_init_done = 0;
  85129. int n; /* iterates over tree elements */
  85130. int bits; /* bit counter */
  85131. int length; /* length value */
  85132. int code; /* code value */
  85133. int dist; /* distance index */
  85134. ush bl_count[MAX_BITS+1];
  85135. /* number of codes at each bit length for an optimal tree */
  85136. if (static_init_done) return;
  85137. /* For some embedded targets, global variables are not initialized: */
  85138. static_l_desc.static_tree = static_ltree;
  85139. static_l_desc.extra_bits = extra_lbits;
  85140. static_d_desc.static_tree = static_dtree;
  85141. static_d_desc.extra_bits = extra_dbits;
  85142. static_bl_desc.extra_bits = extra_blbits;
  85143. /* Initialize the mapping length (0..255) -> length code (0..28) */
  85144. length = 0;
  85145. for (code = 0; code < LENGTH_CODES-1; code++) {
  85146. base_length[code] = length;
  85147. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  85148. _length_code[length++] = (uch)code;
  85149. }
  85150. }
  85151. Assert (length == 256, "tr_static_init: length != 256");
  85152. /* Note that the length 255 (match length 258) can be represented
  85153. * in two different ways: code 284 + 5 bits or code 285, so we
  85154. * overwrite length_code[255] to use the best encoding:
  85155. */
  85156. _length_code[length-1] = (uch)code;
  85157. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  85158. dist = 0;
  85159. for (code = 0 ; code < 16; code++) {
  85160. base_dist[code] = dist;
  85161. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  85162. _dist_code[dist++] = (uch)code;
  85163. }
  85164. }
  85165. Assert (dist == 256, "tr_static_init: dist != 256");
  85166. dist >>= 7; /* from now on, all distances are divided by 128 */
  85167. for ( ; code < D_CODES; code++) {
  85168. base_dist[code] = dist << 7;
  85169. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  85170. _dist_code[256 + dist++] = (uch)code;
  85171. }
  85172. }
  85173. Assert (dist == 256, "tr_static_init: 256+dist != 512");
  85174. /* Construct the codes of the static literal tree */
  85175. for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
  85176. n = 0;
  85177. while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
  85178. while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
  85179. while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
  85180. while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
  85181. /* Codes 286 and 287 do not exist, but we must include them in the
  85182. * tree construction to get a canonical Huffman tree (longest code
  85183. * all ones)
  85184. */
  85185. gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
  85186. /* The static distance tree is trivial: */
  85187. for (n = 0; n < D_CODES; n++) {
  85188. static_dtree[n].Len = 5;
  85189. static_dtree[n].Code = bi_reverse((unsigned)n, 5);
  85190. }
  85191. static_init_done = 1;
  85192. # ifdef GEN_TREES_H
  85193. gen_trees_header();
  85194. # endif
  85195. #endif /* defined(GEN_TREES_H) || !defined(STDC) */
  85196. }
  85197. /* ===========================================================================
  85198. * Genererate the file trees.h describing the static trees.
  85199. */
  85200. #ifdef GEN_TREES_H
  85201. # ifndef DEBUG
  85202. # include <stdio.h>
  85203. # endif
  85204. # define SEPARATOR(i, last, width) \
  85205. ((i) == (last)? "\n};\n\n" : \
  85206. ((i) % (width) == (width)-1 ? ",\n" : ", "))
  85207. void gen_trees_header()
  85208. {
  85209. FILE *header = fopen("trees.h", "w");
  85210. int i;
  85211. Assert (header != NULL, "Can't open trees.h");
  85212. fprintf(header,
  85213. "/* header created automatically with -DGEN_TREES_H */\n\n");
  85214. fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
  85215. for (i = 0; i < L_CODES+2; i++) {
  85216. fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
  85217. static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
  85218. }
  85219. fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
  85220. for (i = 0; i < D_CODES; i++) {
  85221. fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
  85222. static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
  85223. }
  85224. fprintf(header, "const uch _dist_code[DIST_CODE_LEN] = {\n");
  85225. for (i = 0; i < DIST_CODE_LEN; i++) {
  85226. fprintf(header, "%2u%s", _dist_code[i],
  85227. SEPARATOR(i, DIST_CODE_LEN-1, 20));
  85228. }
  85229. fprintf(header, "const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
  85230. for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
  85231. fprintf(header, "%2u%s", _length_code[i],
  85232. SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
  85233. }
  85234. fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
  85235. for (i = 0; i < LENGTH_CODES; i++) {
  85236. fprintf(header, "%1u%s", base_length[i],
  85237. SEPARATOR(i, LENGTH_CODES-1, 20));
  85238. }
  85239. fprintf(header, "local const int base_dist[D_CODES] = {\n");
  85240. for (i = 0; i < D_CODES; i++) {
  85241. fprintf(header, "%5u%s", base_dist[i],
  85242. SEPARATOR(i, D_CODES-1, 10));
  85243. }
  85244. fclose(header);
  85245. }
  85246. #endif /* GEN_TREES_H */
  85247. /* ===========================================================================
  85248. * Initialize the tree data structures for a new zlib stream.
  85249. */
  85250. void _tr_init(deflate_state *s)
  85251. {
  85252. tr_static_init();
  85253. s->l_desc.dyn_tree = s->dyn_ltree;
  85254. s->l_desc.stat_desc = &static_l_desc;
  85255. s->d_desc.dyn_tree = s->dyn_dtree;
  85256. s->d_desc.stat_desc = &static_d_desc;
  85257. s->bl_desc.dyn_tree = s->bl_tree;
  85258. s->bl_desc.stat_desc = &static_bl_desc;
  85259. s->bi_buf = 0;
  85260. s->bi_valid = 0;
  85261. s->last_eob_len = 8; /* enough lookahead for inflate */
  85262. #ifdef DEBUG
  85263. s->compressed_len = 0L;
  85264. s->bits_sent = 0L;
  85265. #endif
  85266. /* Initialize the first block of the first file: */
  85267. init_block(s);
  85268. }
  85269. /* ===========================================================================
  85270. * Initialize a new block.
  85271. */
  85272. local void init_block (deflate_state *s)
  85273. {
  85274. int n; /* iterates over tree elements */
  85275. /* Initialize the trees. */
  85276. for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0;
  85277. for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0;
  85278. for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
  85279. s->dyn_ltree[END_BLOCK].Freq = 1;
  85280. s->opt_len = s->static_len = 0L;
  85281. s->last_lit = s->matches = 0;
  85282. }
  85283. #define SMALLEST 1
  85284. /* Index within the heap array of least frequent node in the Huffman tree */
  85285. /* ===========================================================================
  85286. * Remove the smallest element from the heap and recreate the heap with
  85287. * one less element. Updates heap and heap_len.
  85288. */
  85289. #define pqremove(s, tree, top) \
  85290. {\
  85291. top = s->heap[SMALLEST]; \
  85292. s->heap[SMALLEST] = s->heap[s->heap_len--]; \
  85293. pqdownheap(s, tree, SMALLEST); \
  85294. }
  85295. /* ===========================================================================
  85296. * Compares to subtrees, using the tree depth as tie breaker when
  85297. * the subtrees have equal frequency. This minimizes the worst case length.
  85298. */
  85299. #define smaller(tree, n, m, depth) \
  85300. (tree[n].Freq < tree[m].Freq || \
  85301. (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
  85302. /* ===========================================================================
  85303. * Restore the heap property by moving down the tree starting at node k,
  85304. * exchanging a node with the smallest of its two sons if necessary, stopping
  85305. * when the heap property is re-established (each father smaller than its
  85306. * two sons).
  85307. */
  85308. local void pqdownheap (deflate_state *s,
  85309. ct_data *tree, /* the tree to restore */
  85310. int k) /* node to move down */
  85311. {
  85312. int v = s->heap[k];
  85313. int j = k << 1; /* left son of k */
  85314. while (j <= s->heap_len) {
  85315. /* Set j to the smallest of the two sons: */
  85316. if (j < s->heap_len &&
  85317. smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
  85318. j++;
  85319. }
  85320. /* Exit if v is smaller than both sons */
  85321. if (smaller(tree, v, s->heap[j], s->depth)) break;
  85322. /* Exchange v with the smallest son */
  85323. s->heap[k] = s->heap[j]; k = j;
  85324. /* And continue down the tree, setting j to the left son of k */
  85325. j <<= 1;
  85326. }
  85327. s->heap[k] = v;
  85328. }
  85329. /* ===========================================================================
  85330. * Compute the optimal bit lengths for a tree and update the total bit length
  85331. * for the current block.
  85332. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  85333. * above are the tree nodes sorted by increasing frequency.
  85334. * OUT assertions: the field len is set to the optimal bit length, the
  85335. * array bl_count contains the frequencies for each bit length.
  85336. * The length opt_len is updated; static_len is also updated if stree is
  85337. * not null.
  85338. */
  85339. local void gen_bitlen (deflate_state *s, tree_desc *desc)
  85340. {
  85341. ct_data *tree = desc->dyn_tree;
  85342. int max_code = desc->max_code;
  85343. const ct_data *stree = desc->stat_desc->static_tree;
  85344. const intf *extra = desc->stat_desc->extra_bits;
  85345. int base = desc->stat_desc->extra_base;
  85346. int max_length = desc->stat_desc->max_length;
  85347. int h; /* heap index */
  85348. int n, m; /* iterate over the tree elements */
  85349. int bits; /* bit length */
  85350. int xbits; /* extra bits */
  85351. ush f; /* frequency */
  85352. int overflow = 0; /* number of elements with bit length too large */
  85353. for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
  85354. /* In a first pass, compute the optimal bit lengths (which may
  85355. * overflow in the case of the bit length tree).
  85356. */
  85357. tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
  85358. for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
  85359. n = s->heap[h];
  85360. bits = tree[tree[n].Dad].Len + 1;
  85361. if (bits > max_length) bits = max_length, overflow++;
  85362. tree[n].Len = (ush)bits;
  85363. /* We overwrite tree[n].Dad which is no longer needed */
  85364. if (n > max_code) continue; /* not a leaf node */
  85365. s->bl_count[bits]++;
  85366. xbits = 0;
  85367. if (n >= base) xbits = extra[n-base];
  85368. f = tree[n].Freq;
  85369. s->opt_len += (ulg)f * (bits + xbits);
  85370. if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);
  85371. }
  85372. if (overflow == 0) return;
  85373. Trace((stderr,"\nbit length overflow\n"));
  85374. /* This happens for example on obj2 and pic of the Calgary corpus */
  85375. /* Find the first bit length which could increase: */
  85376. do {
  85377. bits = max_length-1;
  85378. while (s->bl_count[bits] == 0) bits--;
  85379. s->bl_count[bits]--; /* move one leaf down the tree */
  85380. s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
  85381. s->bl_count[max_length]--;
  85382. /* The brother of the overflow item also moves one step up,
  85383. * but this does not affect bl_count[max_length]
  85384. */
  85385. overflow -= 2;
  85386. } while (overflow > 0);
  85387. /* Now recompute all bit lengths, scanning in increasing frequency.
  85388. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  85389. * lengths instead of fixing only the wrong ones. This idea is taken
  85390. * from 'ar' written by Haruhiko Okumura.)
  85391. */
  85392. for (bits = max_length; bits != 0; bits--) {
  85393. n = s->bl_count[bits];
  85394. while (n != 0) {
  85395. m = s->heap[--h];
  85396. if (m > max_code) continue;
  85397. if ((unsigned) tree[m].Len != (unsigned) bits) {
  85398. Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  85399. s->opt_len += ((long)bits - (long)tree[m].Len)
  85400. *(long)tree[m].Freq;
  85401. tree[m].Len = (ush)bits;
  85402. }
  85403. n--;
  85404. }
  85405. }
  85406. }
  85407. /* ===========================================================================
  85408. * Generate the codes for a given tree and bit counts (which need not be
  85409. * optimal).
  85410. * IN assertion: the array bl_count contains the bit length statistics for
  85411. * the given tree and the field len is set for all tree elements.
  85412. * OUT assertion: the field code is set for all tree elements of non
  85413. * zero code length.
  85414. */
  85415. local void gen_codes (ct_data *tree, /* the tree to decorate */
  85416. int max_code, /* largest code with non zero frequency */
  85417. ushf *bl_count) /* number of codes at each bit length */
  85418. {
  85419. ush next_code[MAX_BITS+1]; /* next code value for each bit length */
  85420. ush code = 0; /* running code value */
  85421. int bits; /* bit index */
  85422. int n; /* code index */
  85423. /* The distribution counts are first used to generate the code values
  85424. * without bit reversal.
  85425. */
  85426. for (bits = 1; bits <= MAX_BITS; bits++) {
  85427. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  85428. }
  85429. /* Check that the bit counts in bl_count are consistent. The last code
  85430. * must be all ones.
  85431. */
  85432. Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  85433. "inconsistent bit counts");
  85434. Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  85435. for (n = 0; n <= max_code; n++) {
  85436. int len = tree[n].Len;
  85437. if (len == 0) continue;
  85438. /* Now reverse the bits */
  85439. tree[n].Code = bi_reverse(next_code[len]++, len);
  85440. Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  85441. n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  85442. }
  85443. }
  85444. /* ===========================================================================
  85445. * Construct one Huffman tree and assigns the code bit strings and lengths.
  85446. * Update the total bit length for the current block.
  85447. * IN assertion: the field freq is set for all tree elements.
  85448. * OUT assertions: the fields len and code are set to the optimal bit length
  85449. * and corresponding code. The length opt_len is updated; static_len is
  85450. * also updated if stree is not null. The field max_code is set.
  85451. */
  85452. local void build_tree (deflate_state *s,
  85453. tree_desc *desc) /* the tree descriptor */
  85454. {
  85455. ct_data *tree = desc->dyn_tree;
  85456. const ct_data *stree = desc->stat_desc->static_tree;
  85457. int elems = desc->stat_desc->elems;
  85458. int n, m; /* iterate over heap elements */
  85459. int max_code = -1; /* largest code with non zero frequency */
  85460. int node; /* new node being created */
  85461. /* Construct the initial heap, with least frequent element in
  85462. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  85463. * heap[0] is not used.
  85464. */
  85465. s->heap_len = 0, s->heap_max = HEAP_SIZE;
  85466. for (n = 0; n < elems; n++) {
  85467. if (tree[n].Freq != 0) {
  85468. s->heap[++(s->heap_len)] = max_code = n;
  85469. s->depth[n] = 0;
  85470. } else {
  85471. tree[n].Len = 0;
  85472. }
  85473. }
  85474. /* The pkzip format requires that at least one distance code exists,
  85475. * and that at least one bit should be sent even if there is only one
  85476. * possible code. So to avoid special checks later on we force at least
  85477. * two codes of non zero frequency.
  85478. */
  85479. while (s->heap_len < 2) {
  85480. node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
  85481. tree[node].Freq = 1;
  85482. s->depth[node] = 0;
  85483. s->opt_len--; if (stree) s->static_len -= stree[node].Len;
  85484. /* node is 0 or 1 so it does not have extra bits */
  85485. }
  85486. desc->max_code = max_code;
  85487. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  85488. * establish sub-heaps of increasing lengths:
  85489. */
  85490. for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
  85491. /* Construct the Huffman tree by repeatedly combining the least two
  85492. * frequent nodes.
  85493. */
  85494. node = elems; /* next internal node of the tree */
  85495. do {
  85496. pqremove(s, tree, n); /* n = node of least frequency */
  85497. m = s->heap[SMALLEST]; /* m = node of next least frequency */
  85498. s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
  85499. s->heap[--(s->heap_max)] = m;
  85500. /* Create a new node father of n and m */
  85501. tree[node].Freq = tree[n].Freq + tree[m].Freq;
  85502. s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
  85503. s->depth[n] : s->depth[m]) + 1);
  85504. tree[n].Dad = tree[m].Dad = (ush)node;
  85505. #ifdef DUMP_BL_TREE
  85506. if (tree == s->bl_tree) {
  85507. fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
  85508. node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
  85509. }
  85510. #endif
  85511. /* and insert the new node in the heap */
  85512. s->heap[SMALLEST] = node++;
  85513. pqdownheap(s, tree, SMALLEST);
  85514. } while (s->heap_len >= 2);
  85515. s->heap[--(s->heap_max)] = s->heap[SMALLEST];
  85516. /* At this point, the fields freq and dad are set. We can now
  85517. * generate the bit lengths.
  85518. */
  85519. gen_bitlen(s, (tree_desc *)desc);
  85520. /* The field len is now set, we can generate the bit codes */
  85521. gen_codes ((ct_data *)tree, max_code, s->bl_count);
  85522. }
  85523. /* ===========================================================================
  85524. * Scan a literal or distance tree to determine the frequencies of the codes
  85525. * in the bit length tree.
  85526. */
  85527. local void scan_tree (deflate_state *s,
  85528. ct_data *tree, /* the tree to be scanned */
  85529. int max_code) /* and its largest code of non zero frequency */
  85530. {
  85531. int n; /* iterates over all tree elements */
  85532. int prevlen = -1; /* last emitted length */
  85533. int curlen; /* length of current code */
  85534. int nextlen = tree[0].Len; /* length of next code */
  85535. int count = 0; /* repeat count of the current code */
  85536. int max_count = 7; /* max repeat count */
  85537. int min_count = 4; /* min repeat count */
  85538. if (nextlen == 0) max_count = 138, min_count = 3;
  85539. tree[max_code+1].Len = (ush)0xffff; /* guard */
  85540. for (n = 0; n <= max_code; n++) {
  85541. curlen = nextlen; nextlen = tree[n+1].Len;
  85542. if (++count < max_count && curlen == nextlen) {
  85543. continue;
  85544. } else if (count < min_count) {
  85545. s->bl_tree[curlen].Freq += count;
  85546. } else if (curlen != 0) {
  85547. if (curlen != prevlen) s->bl_tree[curlen].Freq++;
  85548. s->bl_tree[REP_3_6].Freq++;
  85549. } else if (count <= 10) {
  85550. s->bl_tree[REPZ_3_10].Freq++;
  85551. } else {
  85552. s->bl_tree[REPZ_11_138].Freq++;
  85553. }
  85554. count = 0; prevlen = curlen;
  85555. if (nextlen == 0) {
  85556. max_count = 138, min_count = 3;
  85557. } else if (curlen == nextlen) {
  85558. max_count = 6, min_count = 3;
  85559. } else {
  85560. max_count = 7, min_count = 4;
  85561. }
  85562. }
  85563. }
  85564. /* ===========================================================================
  85565. * Send a literal or distance tree in compressed form, using the codes in
  85566. * bl_tree.
  85567. */
  85568. local void send_tree (deflate_state *s,
  85569. ct_data *tree, /* the tree to be scanned */
  85570. int max_code) /* and its largest code of non zero frequency */
  85571. {
  85572. int n; /* iterates over all tree elements */
  85573. int prevlen = -1; /* last emitted length */
  85574. int curlen; /* length of current code */
  85575. int nextlen = tree[0].Len; /* length of next code */
  85576. int count = 0; /* repeat count of the current code */
  85577. int max_count = 7; /* max repeat count */
  85578. int min_count = 4; /* min repeat count */
  85579. /* tree[max_code+1].Len = -1; */ /* guard already set */
  85580. if (nextlen == 0) max_count = 138, min_count = 3;
  85581. for (n = 0; n <= max_code; n++) {
  85582. curlen = nextlen; nextlen = tree[n+1].Len;
  85583. if (++count < max_count && curlen == nextlen) {
  85584. continue;
  85585. } else if (count < min_count) {
  85586. do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
  85587. } else if (curlen != 0) {
  85588. if (curlen != prevlen) {
  85589. send_code(s, curlen, s->bl_tree); count--;
  85590. }
  85591. Assert(count >= 3 && count <= 6, " 3_6?");
  85592. send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
  85593. } else if (count <= 10) {
  85594. send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
  85595. } else {
  85596. send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
  85597. }
  85598. count = 0; prevlen = curlen;
  85599. if (nextlen == 0) {
  85600. max_count = 138, min_count = 3;
  85601. } else if (curlen == nextlen) {
  85602. max_count = 6, min_count = 3;
  85603. } else {
  85604. max_count = 7, min_count = 4;
  85605. }
  85606. }
  85607. }
  85608. /* ===========================================================================
  85609. * Construct the Huffman tree for the bit lengths and return the index in
  85610. * bl_order of the last bit length code to send.
  85611. */
  85612. local int build_bl_tree (deflate_state *s)
  85613. {
  85614. int max_blindex; /* index of last bit length code of non zero freq */
  85615. /* Determine the bit length frequencies for literal and distance trees */
  85616. scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
  85617. scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
  85618. /* Build the bit length tree: */
  85619. build_tree(s, (tree_desc *)(&(s->bl_desc)));
  85620. /* opt_len now includes the length of the tree representations, except
  85621. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  85622. */
  85623. /* Determine the number of bit length codes to send. The pkzip format
  85624. * requires that at least 4 bit length codes be sent. (appnote.txt says
  85625. * 3 but the actual value used is 4.)
  85626. */
  85627. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  85628. if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
  85629. }
  85630. /* Update opt_len to include the bit length tree and counts */
  85631. s->opt_len += 3*(max_blindex+1) + 5+5+4;
  85632. Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  85633. s->opt_len, s->static_len));
  85634. return max_blindex;
  85635. }
  85636. /* ===========================================================================
  85637. * Send the header for a block using dynamic Huffman trees: the counts, the
  85638. * lengths of the bit length codes, the literal tree and the distance tree.
  85639. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  85640. */
  85641. local void send_all_trees (deflate_state *s,
  85642. int lcodes, int dcodes, int blcodes) /* number of codes for each tree */
  85643. {
  85644. int rank; /* index in bl_order */
  85645. Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  85646. Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  85647. "too many codes");
  85648. Tracev((stderr, "\nbl counts: "));
  85649. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  85650. send_bits(s, dcodes-1, 5);
  85651. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  85652. for (rank = 0; rank < blcodes; rank++) {
  85653. Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  85654. send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
  85655. }
  85656. Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  85657. send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
  85658. Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  85659. send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
  85660. Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  85661. }
  85662. /* ===========================================================================
  85663. * Send a stored block
  85664. */
  85665. void _tr_stored_block (deflate_state *s, charf *buf, ulg stored_len, int eof)
  85666. {
  85667. send_bits(s, (STORED_BLOCK<<1)+eof, 3); /* send block type */
  85668. #ifdef DEBUG
  85669. s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
  85670. s->compressed_len += (stored_len + 4) << 3;
  85671. #endif
  85672. copy_block(s, buf, (unsigned)stored_len, 1); /* with header */
  85673. }
  85674. /* ===========================================================================
  85675. * Send one empty static block to give enough lookahead for inflate.
  85676. * This takes 10 bits, of which 7 may remain in the bit buffer.
  85677. * The current inflate code requires 9 bits of lookahead. If the
  85678. * last two codes for the previous block (real code plus EOB) were coded
  85679. * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
  85680. * the last real code. In this case we send two empty static blocks instead
  85681. * of one. (There are no problems if the previous block is stored or fixed.)
  85682. * To simplify the code, we assume the worst case of last real code encoded
  85683. * on one bit only.
  85684. */
  85685. void _tr_align (deflate_state *s)
  85686. {
  85687. send_bits(s, STATIC_TREES<<1, 3);
  85688. send_code(s, END_BLOCK, static_ltree);
  85689. #ifdef DEBUG
  85690. s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
  85691. #endif
  85692. bi_flush(s);
  85693. /* Of the 10 bits for the empty block, we have already sent
  85694. * (10 - bi_valid) bits. The lookahead for the last real code (before
  85695. * the EOB of the previous block) was thus at least one plus the length
  85696. * of the EOB plus what we have just sent of the empty static block.
  85697. */
  85698. if (1 + s->last_eob_len + 10 - s->bi_valid < 9) {
  85699. send_bits(s, STATIC_TREES<<1, 3);
  85700. send_code(s, END_BLOCK, static_ltree);
  85701. #ifdef DEBUG
  85702. s->compressed_len += 10L;
  85703. #endif
  85704. bi_flush(s);
  85705. }
  85706. s->last_eob_len = 7;
  85707. }
  85708. /* ===========================================================================
  85709. * Determine the best encoding for the current block: dynamic trees, static
  85710. * trees or store, and output the encoded block to the zip file.
  85711. */
  85712. void _tr_flush_block (deflate_state *s,
  85713. charf *buf, /* input block, or NULL if too old */
  85714. ulg stored_len, /* length of input block */
  85715. int eof) /* true if this is the last block for a file */
  85716. {
  85717. ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  85718. int max_blindex = 0; /* index of last bit length code of non zero freq */
  85719. /* Build the Huffman trees unless a stored block is forced */
  85720. if (s->level > 0) {
  85721. /* Check if the file is binary or text */
  85722. if (stored_len > 0 && s->strm->data_type == Z_UNKNOWN)
  85723. set_data_type(s);
  85724. /* Construct the literal and distance trees */
  85725. build_tree(s, (tree_desc *)(&(s->l_desc)));
  85726. Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  85727. s->static_len));
  85728. build_tree(s, (tree_desc *)(&(s->d_desc)));
  85729. Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  85730. s->static_len));
  85731. /* At this point, opt_len and static_len are the total bit lengths of
  85732. * the compressed block data, excluding the tree representations.
  85733. */
  85734. /* Build the bit length tree for the above two trees, and get the index
  85735. * in bl_order of the last bit length code to send.
  85736. */
  85737. max_blindex = build_bl_tree(s);
  85738. /* Determine the best encoding. Compute the block lengths in bytes. */
  85739. opt_lenb = (s->opt_len+3+7)>>3;
  85740. static_lenb = (s->static_len+3+7)>>3;
  85741. Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  85742. opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  85743. s->last_lit));
  85744. if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
  85745. } else {
  85746. Assert(buf != (char*)0, "lost buf");
  85747. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  85748. }
  85749. #ifdef FORCE_STORED
  85750. if (buf != (char*)0) { /* force stored block */
  85751. #else
  85752. if (stored_len+4 <= opt_lenb && buf != (char*)0) {
  85753. /* 4: two words for the lengths */
  85754. #endif
  85755. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  85756. * Otherwise we can't have processed more than WSIZE input bytes since
  85757. * the last block flush, because compression would have been
  85758. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  85759. * transform a block into a stored block.
  85760. */
  85761. _tr_stored_block(s, buf, stored_len, eof);
  85762. #ifdef FORCE_STATIC
  85763. } else if (static_lenb >= 0) { /* force static trees */
  85764. #else
  85765. } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
  85766. #endif
  85767. send_bits(s, (STATIC_TREES<<1)+eof, 3);
  85768. compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
  85769. #ifdef DEBUG
  85770. s->compressed_len += 3 + s->static_len;
  85771. #endif
  85772. } else {
  85773. send_bits(s, (DYN_TREES<<1)+eof, 3);
  85774. send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
  85775. max_blindex+1);
  85776. compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
  85777. #ifdef DEBUG
  85778. s->compressed_len += 3 + s->opt_len;
  85779. #endif
  85780. }
  85781. Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  85782. /* The above check is made mod 2^32, for files larger than 512 MB
  85783. * and uLong implemented on 32 bits.
  85784. */
  85785. init_block(s);
  85786. if (eof) {
  85787. bi_windup(s);
  85788. #ifdef DEBUG
  85789. s->compressed_len += 7; /* align on byte boundary */
  85790. #endif
  85791. }
  85792. Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  85793. s->compressed_len-7*eof));
  85794. }
  85795. /* ===========================================================================
  85796. * Save the match info and tally the frequency counts. Return true if
  85797. * the current block must be flushed.
  85798. */
  85799. int _tr_tally (deflate_state *s,
  85800. unsigned dist, /* distance of matched string */
  85801. unsigned lc) /* match length-MIN_MATCH or unmatched char (if dist==0) */
  85802. {
  85803. s->d_buf[s->last_lit] = (ush)dist;
  85804. s->l_buf[s->last_lit++] = (uch)lc;
  85805. if (dist == 0) {
  85806. /* lc is the unmatched char */
  85807. s->dyn_ltree[lc].Freq++;
  85808. } else {
  85809. s->matches++;
  85810. /* Here, lc is the match length - MIN_MATCH */
  85811. dist--; /* dist = match distance - 1 */
  85812. Assert((ush)dist < (ush)MAX_DIST(s) &&
  85813. (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  85814. (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  85815. s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
  85816. s->dyn_dtree[d_code(dist)].Freq++;
  85817. }
  85818. #ifdef TRUNCATE_BLOCK
  85819. /* Try to guess if it is profitable to stop the current block here */
  85820. if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {
  85821. /* Compute an upper bound for the compressed length */
  85822. ulg out_length = (ulg)s->last_lit*8L;
  85823. ulg in_length = (ulg)((long)s->strstart - s->block_start);
  85824. int dcode;
  85825. for (dcode = 0; dcode < D_CODES; dcode++) {
  85826. out_length += (ulg)s->dyn_dtree[dcode].Freq *
  85827. (5L+extra_dbits[dcode]);
  85828. }
  85829. out_length >>= 3;
  85830. Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  85831. s->last_lit, in_length, out_length,
  85832. 100L - out_length*100L/in_length));
  85833. if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
  85834. }
  85835. #endif
  85836. return (s->last_lit == s->lit_bufsize-1);
  85837. /* We avoid equality with lit_bufsize because of wraparound at 64K
  85838. * on 16 bit machines and because stored blocks are restricted to
  85839. * 64K-1 bytes.
  85840. */
  85841. }
  85842. /* ===========================================================================
  85843. * Send the block data compressed using the given Huffman trees
  85844. */
  85845. local void compress_block (deflate_state *s,
  85846. ct_data *ltree, /* literal tree */
  85847. ct_data *dtree) /* distance tree */
  85848. {
  85849. unsigned dist; /* distance of matched string */
  85850. int lc; /* match length or unmatched char (if dist == 0) */
  85851. unsigned lx = 0; /* running index in l_buf */
  85852. unsigned code; /* the code to send */
  85853. int extra; /* number of extra bits to send */
  85854. if (s->last_lit != 0) do {
  85855. dist = s->d_buf[lx];
  85856. lc = s->l_buf[lx++];
  85857. if (dist == 0) {
  85858. send_code(s, lc, ltree); /* send a literal byte */
  85859. Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  85860. } else {
  85861. /* Here, lc is the match length - MIN_MATCH */
  85862. code = _length_code[lc];
  85863. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  85864. extra = extra_lbits[code];
  85865. if (extra != 0) {
  85866. lc -= base_length[code];
  85867. send_bits(s, lc, extra); /* send the extra length bits */
  85868. }
  85869. dist--; /* dist is now the match distance - 1 */
  85870. code = d_code(dist);
  85871. Assert (code < D_CODES, "bad d_code");
  85872. send_code(s, code, dtree); /* send the distance code */
  85873. extra = extra_dbits[code];
  85874. if (extra != 0) {
  85875. dist -= base_dist[code];
  85876. send_bits(s, dist, extra); /* send the extra distance bits */
  85877. }
  85878. } /* literal or match pair ? */
  85879. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  85880. Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  85881. "pendingBuf overflow");
  85882. } while (lx < s->last_lit);
  85883. send_code(s, END_BLOCK, ltree);
  85884. s->last_eob_len = ltree[END_BLOCK].Len;
  85885. }
  85886. /* ===========================================================================
  85887. * Set the data type to BINARY or TEXT, using a crude approximation:
  85888. * set it to Z_TEXT if all symbols are either printable characters (33 to 255)
  85889. * or white spaces (9 to 13, or 32); or set it to Z_BINARY otherwise.
  85890. * IN assertion: the fields Freq of dyn_ltree are set.
  85891. */
  85892. local void set_data_type (deflate_state *s)
  85893. {
  85894. int n;
  85895. for (n = 0; n < 9; n++)
  85896. if (s->dyn_ltree[n].Freq != 0)
  85897. break;
  85898. if (n == 9)
  85899. for (n = 14; n < 32; n++)
  85900. if (s->dyn_ltree[n].Freq != 0)
  85901. break;
  85902. s->strm->data_type = (n == 32) ? Z_TEXT : Z_BINARY;
  85903. }
  85904. /* ===========================================================================
  85905. * Reverse the first len bits of a code, using straightforward code (a faster
  85906. * method would use a table)
  85907. * IN assertion: 1 <= len <= 15
  85908. */
  85909. local unsigned bi_reverse (unsigned code, int len)
  85910. {
  85911. register unsigned res = 0;
  85912. do {
  85913. res |= code & 1;
  85914. code >>= 1, res <<= 1;
  85915. } while (--len > 0);
  85916. return res >> 1;
  85917. }
  85918. /* ===========================================================================
  85919. * Flush the bit buffer, keeping at most 7 bits in it.
  85920. */
  85921. local void bi_flush (deflate_state *s)
  85922. {
  85923. if (s->bi_valid == 16) {
  85924. put_short(s, s->bi_buf);
  85925. s->bi_buf = 0;
  85926. s->bi_valid = 0;
  85927. } else if (s->bi_valid >= 8) {
  85928. put_byte(s, (Byte)s->bi_buf);
  85929. s->bi_buf >>= 8;
  85930. s->bi_valid -= 8;
  85931. }
  85932. }
  85933. /* ===========================================================================
  85934. * Flush the bit buffer and align the output on a byte boundary
  85935. */
  85936. local void bi_windup (deflate_state *s)
  85937. {
  85938. if (s->bi_valid > 8) {
  85939. put_short(s, s->bi_buf);
  85940. } else if (s->bi_valid > 0) {
  85941. put_byte(s, (Byte)s->bi_buf);
  85942. }
  85943. s->bi_buf = 0;
  85944. s->bi_valid = 0;
  85945. #ifdef DEBUG
  85946. s->bits_sent = (s->bits_sent+7) & ~7;
  85947. #endif
  85948. }
  85949. /* ===========================================================================
  85950. * Copy a stored block, storing first the length and its
  85951. * one's complement if requested.
  85952. */
  85953. local void copy_block(deflate_state *s,
  85954. charf *buf, /* the input data */
  85955. unsigned len, /* its length */
  85956. int header) /* true if block header must be written */
  85957. {
  85958. bi_windup(s); /* align on byte boundary */
  85959. s->last_eob_len = 8; /* enough lookahead for inflate */
  85960. if (header) {
  85961. put_short(s, (ush)len);
  85962. put_short(s, (ush)~len);
  85963. #ifdef DEBUG
  85964. s->bits_sent += 2*16;
  85965. #endif
  85966. }
  85967. #ifdef DEBUG
  85968. s->bits_sent += (ulg)len<<3;
  85969. #endif
  85970. while (len--) {
  85971. put_byte(s, *buf++);
  85972. }
  85973. }
  85974. /*** End of inlined file: trees.c ***/
  85975. /*** Start of inlined file: zutil.c ***/
  85976. /* @(#) $Id: zutil.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  85977. #ifndef NO_DUMMY_DECL
  85978. struct internal_state {int dummy;}; /* for buggy compilers */
  85979. #endif
  85980. const char * const z_errmsg[10] = {
  85981. "need dictionary", /* Z_NEED_DICT 2 */
  85982. "stream end", /* Z_STREAM_END 1 */
  85983. "", /* Z_OK 0 */
  85984. "file error", /* Z_ERRNO (-1) */
  85985. "stream error", /* Z_STREAM_ERROR (-2) */
  85986. "data error", /* Z_DATA_ERROR (-3) */
  85987. "insufficient memory", /* Z_MEM_ERROR (-4) */
  85988. "buffer error", /* Z_BUF_ERROR (-5) */
  85989. "incompatible version",/* Z_VERSION_ERROR (-6) */
  85990. ""};
  85991. /*const char * ZEXPORT zlibVersion()
  85992. {
  85993. return ZLIB_VERSION;
  85994. }
  85995. uLong ZEXPORT zlibCompileFlags()
  85996. {
  85997. uLong flags;
  85998. flags = 0;
  85999. switch (sizeof(uInt)) {
  86000. case 2: break;
  86001. case 4: flags += 1; break;
  86002. case 8: flags += 2; break;
  86003. default: flags += 3;
  86004. }
  86005. switch (sizeof(uLong)) {
  86006. case 2: break;
  86007. case 4: flags += 1 << 2; break;
  86008. case 8: flags += 2 << 2; break;
  86009. default: flags += 3 << 2;
  86010. }
  86011. switch (sizeof(voidpf)) {
  86012. case 2: break;
  86013. case 4: flags += 1 << 4; break;
  86014. case 8: flags += 2 << 4; break;
  86015. default: flags += 3 << 4;
  86016. }
  86017. switch (sizeof(z_off_t)) {
  86018. case 2: break;
  86019. case 4: flags += 1 << 6; break;
  86020. case 8: flags += 2 << 6; break;
  86021. default: flags += 3 << 6;
  86022. }
  86023. #ifdef DEBUG
  86024. flags += 1 << 8;
  86025. #endif
  86026. #if defined(ASMV) || defined(ASMINF)
  86027. flags += 1 << 9;
  86028. #endif
  86029. #ifdef ZLIB_WINAPI
  86030. flags += 1 << 10;
  86031. #endif
  86032. #ifdef BUILDFIXED
  86033. flags += 1 << 12;
  86034. #endif
  86035. #ifdef DYNAMIC_CRC_TABLE
  86036. flags += 1 << 13;
  86037. #endif
  86038. #ifdef NO_GZCOMPRESS
  86039. flags += 1L << 16;
  86040. #endif
  86041. #ifdef NO_GZIP
  86042. flags += 1L << 17;
  86043. #endif
  86044. #ifdef PKZIP_BUG_WORKAROUND
  86045. flags += 1L << 20;
  86046. #endif
  86047. #ifdef FASTEST
  86048. flags += 1L << 21;
  86049. #endif
  86050. #ifdef STDC
  86051. # ifdef NO_vsnprintf
  86052. flags += 1L << 25;
  86053. # ifdef HAS_vsprintf_void
  86054. flags += 1L << 26;
  86055. # endif
  86056. # else
  86057. # ifdef HAS_vsnprintf_void
  86058. flags += 1L << 26;
  86059. # endif
  86060. # endif
  86061. #else
  86062. flags += 1L << 24;
  86063. # ifdef NO_snprintf
  86064. flags += 1L << 25;
  86065. # ifdef HAS_sprintf_void
  86066. flags += 1L << 26;
  86067. # endif
  86068. # else
  86069. # ifdef HAS_snprintf_void
  86070. flags += 1L << 26;
  86071. # endif
  86072. # endif
  86073. #endif
  86074. return flags;
  86075. }*/
  86076. #ifdef DEBUG
  86077. # ifndef verbose
  86078. # define verbose 0
  86079. # endif
  86080. int z_verbose = verbose;
  86081. void z_error (const char *m)
  86082. {
  86083. fprintf(stderr, "%s\n", m);
  86084. exit(1);
  86085. }
  86086. #endif
  86087. /* exported to allow conversion of error code to string for compress() and
  86088. * uncompress()
  86089. */
  86090. const char * ZEXPORT zError(int err)
  86091. {
  86092. return ERR_MSG(err);
  86093. }
  86094. #if defined(_WIN32_WCE)
  86095. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  86096. * errno. We define it as a global variable to simplify porting.
  86097. * Its value is always 0 and should not be used.
  86098. */
  86099. int errno = 0;
  86100. #endif
  86101. #ifndef HAVE_MEMCPY
  86102. void zmemcpy(dest, source, len)
  86103. Bytef* dest;
  86104. const Bytef* source;
  86105. uInt len;
  86106. {
  86107. if (len == 0) return;
  86108. do {
  86109. *dest++ = *source++; /* ??? to be unrolled */
  86110. } while (--len != 0);
  86111. }
  86112. int zmemcmp(s1, s2, len)
  86113. const Bytef* s1;
  86114. const Bytef* s2;
  86115. uInt len;
  86116. {
  86117. uInt j;
  86118. for (j = 0; j < len; j++) {
  86119. if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1;
  86120. }
  86121. return 0;
  86122. }
  86123. void zmemzero(dest, len)
  86124. Bytef* dest;
  86125. uInt len;
  86126. {
  86127. if (len == 0) return;
  86128. do {
  86129. *dest++ = 0; /* ??? to be unrolled */
  86130. } while (--len != 0);
  86131. }
  86132. #endif
  86133. #ifdef SYS16BIT
  86134. #ifdef __TURBOC__
  86135. /* Turbo C in 16-bit mode */
  86136. # define MY_ZCALLOC
  86137. /* Turbo C malloc() does not allow dynamic allocation of 64K bytes
  86138. * and farmalloc(64K) returns a pointer with an offset of 8, so we
  86139. * must fix the pointer. Warning: the pointer must be put back to its
  86140. * original form in order to free it, use zcfree().
  86141. */
  86142. #define MAX_PTR 10
  86143. /* 10*64K = 640K */
  86144. local int next_ptr = 0;
  86145. typedef struct ptr_table_s {
  86146. voidpf org_ptr;
  86147. voidpf new_ptr;
  86148. } ptr_table;
  86149. local ptr_table table[MAX_PTR];
  86150. /* This table is used to remember the original form of pointers
  86151. * to large buffers (64K). Such pointers are normalized with a zero offset.
  86152. * Since MSDOS is not a preemptive multitasking OS, this table is not
  86153. * protected from concurrent access. This hack doesn't work anyway on
  86154. * a protected system like OS/2. Use Microsoft C instead.
  86155. */
  86156. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  86157. {
  86158. voidpf buf = opaque; /* just to make some compilers happy */
  86159. ulg bsize = (ulg)items*size;
  86160. /* If we allocate less than 65520 bytes, we assume that farmalloc
  86161. * will return a usable pointer which doesn't have to be normalized.
  86162. */
  86163. if (bsize < 65520L) {
  86164. buf = farmalloc(bsize);
  86165. if (*(ush*)&buf != 0) return buf;
  86166. } else {
  86167. buf = farmalloc(bsize + 16L);
  86168. }
  86169. if (buf == NULL || next_ptr >= MAX_PTR) return NULL;
  86170. table[next_ptr].org_ptr = buf;
  86171. /* Normalize the pointer to seg:0 */
  86172. *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4;
  86173. *(ush*)&buf = 0;
  86174. table[next_ptr++].new_ptr = buf;
  86175. return buf;
  86176. }
  86177. void zcfree (voidpf opaque, voidpf ptr)
  86178. {
  86179. int n;
  86180. if (*(ush*)&ptr != 0) { /* object < 64K */
  86181. farfree(ptr);
  86182. return;
  86183. }
  86184. /* Find the original pointer */
  86185. for (n = 0; n < next_ptr; n++) {
  86186. if (ptr != table[n].new_ptr) continue;
  86187. farfree(table[n].org_ptr);
  86188. while (++n < next_ptr) {
  86189. table[n-1] = table[n];
  86190. }
  86191. next_ptr--;
  86192. return;
  86193. }
  86194. ptr = opaque; /* just to make some compilers happy */
  86195. Assert(0, "zcfree: ptr not found");
  86196. }
  86197. #endif /* __TURBOC__ */
  86198. #ifdef M_I86
  86199. /* Microsoft C in 16-bit mode */
  86200. # define MY_ZCALLOC
  86201. #if (!defined(_MSC_VER) || (_MSC_VER <= 600))
  86202. # define _halloc halloc
  86203. # define _hfree hfree
  86204. #endif
  86205. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  86206. {
  86207. if (opaque) opaque = 0; /* to make compiler happy */
  86208. return _halloc((long)items, size);
  86209. }
  86210. void zcfree (voidpf opaque, voidpf ptr)
  86211. {
  86212. if (opaque) opaque = 0; /* to make compiler happy */
  86213. _hfree(ptr);
  86214. }
  86215. #endif /* M_I86 */
  86216. #endif /* SYS16BIT */
  86217. #ifndef MY_ZCALLOC /* Any system without a special alloc function */
  86218. #ifndef STDC
  86219. extern voidp malloc OF((uInt size));
  86220. extern voidp calloc OF((uInt items, uInt size));
  86221. extern void free OF((voidpf ptr));
  86222. #endif
  86223. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  86224. {
  86225. if (opaque) items += size - size; /* make compiler happy */
  86226. return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) :
  86227. (voidpf)calloc(items, size);
  86228. }
  86229. void zcfree (voidpf opaque, voidpf ptr)
  86230. {
  86231. free(ptr);
  86232. if (opaque) return; /* make compiler happy */
  86233. }
  86234. #endif /* MY_ZCALLOC */
  86235. /*** End of inlined file: zutil.c ***/
  86236. #undef Byte
  86237. #else
  86238. #include <zlib.h>
  86239. #endif
  86240. }
  86241. #if JUCE_MSVC
  86242. #pragma warning (pop)
  86243. #endif
  86244. BEGIN_JUCE_NAMESPACE
  86245. // internal helper object that holds the zlib structures so they don't have to be
  86246. // included publicly.
  86247. class GZIPDecompressorInputStream::GZIPDecompressHelper
  86248. {
  86249. public:
  86250. GZIPDecompressHelper (const bool noWrap)
  86251. : finished (true),
  86252. needsDictionary (false),
  86253. error (true),
  86254. streamIsValid (false),
  86255. data (0),
  86256. dataSize (0)
  86257. {
  86258. using namespace zlibNamespace;
  86259. zerostruct (stream);
  86260. streamIsValid = (inflateInit2 (&stream, noWrap ? -MAX_WBITS : MAX_WBITS) == Z_OK);
  86261. finished = error = ! streamIsValid;
  86262. }
  86263. ~GZIPDecompressHelper()
  86264. {
  86265. using namespace zlibNamespace;
  86266. if (streamIsValid)
  86267. inflateEnd (&stream);
  86268. }
  86269. bool needsInput() const throw() { return dataSize <= 0; }
  86270. void setInput (uint8* const data_, const int size) throw()
  86271. {
  86272. data = data_;
  86273. dataSize = size;
  86274. }
  86275. int doNextBlock (uint8* const dest, const int destSize)
  86276. {
  86277. using namespace zlibNamespace;
  86278. if (streamIsValid && data != 0 && ! finished)
  86279. {
  86280. stream.next_in = data;
  86281. stream.next_out = dest;
  86282. stream.avail_in = dataSize;
  86283. stream.avail_out = destSize;
  86284. switch (inflate (&stream, Z_PARTIAL_FLUSH))
  86285. {
  86286. case Z_STREAM_END:
  86287. finished = true;
  86288. // deliberate fall-through
  86289. case Z_OK:
  86290. data += dataSize - stream.avail_in;
  86291. dataSize = stream.avail_in;
  86292. return destSize - stream.avail_out;
  86293. case Z_NEED_DICT:
  86294. needsDictionary = true;
  86295. data += dataSize - stream.avail_in;
  86296. dataSize = stream.avail_in;
  86297. break;
  86298. case Z_DATA_ERROR:
  86299. case Z_MEM_ERROR:
  86300. error = true;
  86301. default:
  86302. break;
  86303. }
  86304. }
  86305. return 0;
  86306. }
  86307. bool finished, needsDictionary, error, streamIsValid;
  86308. enum { gzipDecompBufferSize = 32768 };
  86309. private:
  86310. zlibNamespace::z_stream stream;
  86311. uint8* data;
  86312. int dataSize;
  86313. GZIPDecompressHelper (const GZIPDecompressHelper&);
  86314. GZIPDecompressHelper& operator= (const GZIPDecompressHelper&);
  86315. };
  86316. GZIPDecompressorInputStream::GZIPDecompressorInputStream (InputStream* const sourceStream_,
  86317. const bool deleteSourceWhenDestroyed,
  86318. const bool noWrap_,
  86319. const int64 uncompressedStreamLength_)
  86320. : sourceStream (sourceStream_),
  86321. streamToDelete (deleteSourceWhenDestroyed ? sourceStream_ : 0),
  86322. uncompressedStreamLength (uncompressedStreamLength_),
  86323. noWrap (noWrap_),
  86324. isEof (false),
  86325. activeBufferSize (0),
  86326. originalSourcePos (sourceStream_->getPosition()),
  86327. currentPos (0),
  86328. buffer ((size_t) GZIPDecompressHelper::gzipDecompBufferSize),
  86329. helper (new GZIPDecompressHelper (noWrap_))
  86330. {
  86331. }
  86332. GZIPDecompressorInputStream::GZIPDecompressorInputStream (InputStream& sourceStream_)
  86333. : sourceStream (&sourceStream_),
  86334. uncompressedStreamLength (-1),
  86335. noWrap (false),
  86336. isEof (false),
  86337. activeBufferSize (0),
  86338. originalSourcePos (sourceStream_.getPosition()),
  86339. currentPos (0),
  86340. buffer ((size_t) GZIPDecompressHelper::gzipDecompBufferSize),
  86341. helper (new GZIPDecompressHelper (false))
  86342. {
  86343. }
  86344. GZIPDecompressorInputStream::~GZIPDecompressorInputStream()
  86345. {
  86346. }
  86347. int64 GZIPDecompressorInputStream::getTotalLength()
  86348. {
  86349. return uncompressedStreamLength;
  86350. }
  86351. int GZIPDecompressorInputStream::read (void* destBuffer, int howMany)
  86352. {
  86353. if ((howMany > 0) && ! isEof)
  86354. {
  86355. jassert (destBuffer != 0);
  86356. if (destBuffer != 0)
  86357. {
  86358. int numRead = 0;
  86359. uint8* d = static_cast <uint8*> (destBuffer);
  86360. while (! helper->error)
  86361. {
  86362. const int n = helper->doNextBlock (d, howMany);
  86363. currentPos += n;
  86364. if (n == 0)
  86365. {
  86366. if (helper->finished || helper->needsDictionary)
  86367. {
  86368. isEof = true;
  86369. return numRead;
  86370. }
  86371. if (helper->needsInput())
  86372. {
  86373. activeBufferSize = sourceStream->read (buffer, (int) GZIPDecompressHelper::gzipDecompBufferSize);
  86374. if (activeBufferSize > 0)
  86375. {
  86376. helper->setInput (buffer, activeBufferSize);
  86377. }
  86378. else
  86379. {
  86380. isEof = true;
  86381. return numRead;
  86382. }
  86383. }
  86384. }
  86385. else
  86386. {
  86387. numRead += n;
  86388. howMany -= n;
  86389. d += n;
  86390. if (howMany <= 0)
  86391. return numRead;
  86392. }
  86393. }
  86394. }
  86395. }
  86396. return 0;
  86397. }
  86398. bool GZIPDecompressorInputStream::isExhausted()
  86399. {
  86400. return helper->error || isEof;
  86401. }
  86402. int64 GZIPDecompressorInputStream::getPosition()
  86403. {
  86404. return currentPos;
  86405. }
  86406. bool GZIPDecompressorInputStream::setPosition (int64 newPos)
  86407. {
  86408. if (newPos < currentPos)
  86409. {
  86410. // to go backwards, reset the stream and start again..
  86411. isEof = false;
  86412. activeBufferSize = 0;
  86413. currentPos = 0;
  86414. helper = new GZIPDecompressHelper (noWrap);
  86415. sourceStream->setPosition (originalSourcePos);
  86416. }
  86417. skipNextBytes (newPos - currentPos);
  86418. return true;
  86419. }
  86420. END_JUCE_NAMESPACE
  86421. /*** End of inlined file: juce_GZIPDecompressorInputStream.cpp ***/
  86422. #endif
  86423. #if JUCE_BUILD_NATIVE && ! JUCE_ONLY_BUILD_CORE_LIBRARY
  86424. /*** Start of inlined file: juce_FlacAudioFormat.cpp ***/
  86425. #if JUCE_USE_FLAC
  86426. #if JUCE_WINDOWS
  86427. #include <windows.h>
  86428. #endif
  86429. namespace FlacNamespace
  86430. {
  86431. #if JUCE_INCLUDE_FLAC_CODE
  86432. #if JUCE_MSVC
  86433. #pragma warning (disable : 4505) // (unreferenced static function removal warning)
  86434. #endif
  86435. #define FLAC__NO_DLL 1
  86436. #if ! defined (SIZE_MAX)
  86437. #define SIZE_MAX 0xffffffff
  86438. #endif
  86439. #define __STDC_LIMIT_MACROS 1
  86440. /*** Start of inlined file: all.h ***/
  86441. #ifndef FLAC__ALL_H
  86442. #define FLAC__ALL_H
  86443. /*** Start of inlined file: export.h ***/
  86444. #ifndef FLAC__EXPORT_H
  86445. #define FLAC__EXPORT_H
  86446. /** \file include/FLAC/export.h
  86447. *
  86448. * \brief
  86449. * This module contains #defines and symbols for exporting function
  86450. * calls, and providing version information and compiled-in features.
  86451. *
  86452. * See the \link flac_export export \endlink module.
  86453. */
  86454. /** \defgroup flac_export FLAC/export.h: export symbols
  86455. * \ingroup flac
  86456. *
  86457. * \brief
  86458. * This module contains #defines and symbols for exporting function
  86459. * calls, and providing version information and compiled-in features.
  86460. *
  86461. * If you are compiling with MSVC and will link to the static library
  86462. * (libFLAC.lib) you should define FLAC__NO_DLL in your project to
  86463. * make sure the symbols are exported properly.
  86464. *
  86465. * \{
  86466. */
  86467. #if defined(FLAC__NO_DLL) || !defined(_MSC_VER)
  86468. #define FLAC_API
  86469. #else
  86470. #ifdef FLAC_API_EXPORTS
  86471. #define FLAC_API _declspec(dllexport)
  86472. #else
  86473. #define FLAC_API _declspec(dllimport)
  86474. #endif
  86475. #endif
  86476. /** These #defines will mirror the libtool-based library version number, see
  86477. * http://www.gnu.org/software/libtool/manual.html#Libtool-versioning
  86478. */
  86479. #define FLAC_API_VERSION_CURRENT 10
  86480. #define FLAC_API_VERSION_REVISION 0 /**< see above */
  86481. #define FLAC_API_VERSION_AGE 2 /**< see above */
  86482. #ifdef __cplusplus
  86483. extern "C" {
  86484. #endif
  86485. /** \c 1 if the library has been compiled with support for Ogg FLAC, else \c 0. */
  86486. extern FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC;
  86487. #ifdef __cplusplus
  86488. }
  86489. #endif
  86490. /* \} */
  86491. #endif
  86492. /*** End of inlined file: export.h ***/
  86493. /*** Start of inlined file: assert.h ***/
  86494. #ifndef FLAC__ASSERT_H
  86495. #define FLAC__ASSERT_H
  86496. /* we need this since some compilers (like MSVC) leave assert()s on release code (and we don't want to use their ASSERT) */
  86497. #ifdef DEBUG
  86498. #include <assert.h>
  86499. #define FLAC__ASSERT(x) assert(x)
  86500. #define FLAC__ASSERT_DECLARATION(x) x
  86501. #else
  86502. #define FLAC__ASSERT(x)
  86503. #define FLAC__ASSERT_DECLARATION(x)
  86504. #endif
  86505. #endif
  86506. /*** End of inlined file: assert.h ***/
  86507. /*** Start of inlined file: callback.h ***/
  86508. #ifndef FLAC__CALLBACK_H
  86509. #define FLAC__CALLBACK_H
  86510. /*** Start of inlined file: ordinals.h ***/
  86511. #ifndef FLAC__ORDINALS_H
  86512. #define FLAC__ORDINALS_H
  86513. #if !(defined(_MSC_VER) || defined(__BORLANDC__) || defined(__EMX__))
  86514. #include <inttypes.h>
  86515. #endif
  86516. typedef signed char FLAC__int8;
  86517. typedef unsigned char FLAC__uint8;
  86518. #if defined(_MSC_VER) || defined(__BORLANDC__)
  86519. typedef __int16 FLAC__int16;
  86520. typedef __int32 FLAC__int32;
  86521. typedef __int64 FLAC__int64;
  86522. typedef unsigned __int16 FLAC__uint16;
  86523. typedef unsigned __int32 FLAC__uint32;
  86524. typedef unsigned __int64 FLAC__uint64;
  86525. #elif defined(__EMX__)
  86526. typedef short FLAC__int16;
  86527. typedef long FLAC__int32;
  86528. typedef long long FLAC__int64;
  86529. typedef unsigned short FLAC__uint16;
  86530. typedef unsigned long FLAC__uint32;
  86531. typedef unsigned long long FLAC__uint64;
  86532. #else
  86533. typedef int16_t FLAC__int16;
  86534. typedef int32_t FLAC__int32;
  86535. typedef int64_t FLAC__int64;
  86536. typedef uint16_t FLAC__uint16;
  86537. typedef uint32_t FLAC__uint32;
  86538. typedef uint64_t FLAC__uint64;
  86539. #endif
  86540. typedef int FLAC__bool;
  86541. typedef FLAC__uint8 FLAC__byte;
  86542. #ifdef true
  86543. #undef true
  86544. #endif
  86545. #ifdef false
  86546. #undef false
  86547. #endif
  86548. #ifndef __cplusplus
  86549. #define true 1
  86550. #define false 0
  86551. #endif
  86552. #endif
  86553. /*** End of inlined file: ordinals.h ***/
  86554. #include <stdlib.h> /* for size_t */
  86555. /** \file include/FLAC/callback.h
  86556. *
  86557. * \brief
  86558. * This module defines the structures for describing I/O callbacks
  86559. * to the other FLAC interfaces.
  86560. *
  86561. * See the detailed documentation for callbacks in the
  86562. * \link flac_callbacks callbacks \endlink module.
  86563. */
  86564. /** \defgroup flac_callbacks FLAC/callback.h: I/O callback structures
  86565. * \ingroup flac
  86566. *
  86567. * \brief
  86568. * This module defines the structures for describing I/O callbacks
  86569. * to the other FLAC interfaces.
  86570. *
  86571. * The purpose of the I/O callback functions is to create a common way
  86572. * for the metadata interfaces to handle I/O.
  86573. *
  86574. * Originally the metadata interfaces required filenames as the way of
  86575. * specifying FLAC files to operate on. This is problematic in some
  86576. * environments so there is an additional option to specify a set of
  86577. * callbacks for doing I/O on the FLAC file, instead of the filename.
  86578. *
  86579. * In addition to the callbacks, a FLAC__IOHandle type is defined as an
  86580. * opaque structure for a data source.
  86581. *
  86582. * The callback function prototypes are similar (but not identical) to the
  86583. * stdio functions fread, fwrite, fseek, ftell, feof, and fclose. If you use
  86584. * stdio streams to implement the callbacks, you can pass fread, fwrite, and
  86585. * fclose anywhere a FLAC__IOCallback_Read, FLAC__IOCallback_Write, or
  86586. * FLAC__IOCallback_Close is required, and a FILE* anywhere a FLAC__IOHandle
  86587. * is required. \warning You generally CANNOT directly use fseek or ftell
  86588. * for FLAC__IOCallback_Seek or FLAC__IOCallback_Tell since on most systems
  86589. * these use 32-bit offsets and FLAC requires 64-bit offsets to deal with
  86590. * large files. You will have to find an equivalent function (e.g. ftello),
  86591. * or write a wrapper. The same is true for feof() since this is usually
  86592. * implemented as a macro, not as a function whose address can be taken.
  86593. *
  86594. * \{
  86595. */
  86596. #ifdef __cplusplus
  86597. extern "C" {
  86598. #endif
  86599. /** This is the opaque handle type used by the callbacks. Typically
  86600. * this is a \c FILE* or address of a file descriptor.
  86601. */
  86602. typedef void* FLAC__IOHandle;
  86603. /** Signature for the read callback.
  86604. * The signature and semantics match POSIX fread() implementations
  86605. * and can generally be used interchangeably.
  86606. *
  86607. * \param ptr The address of the read buffer.
  86608. * \param size The size of the records to be read.
  86609. * \param nmemb The number of records to be read.
  86610. * \param handle The handle to the data source.
  86611. * \retval size_t
  86612. * The number of records read.
  86613. */
  86614. typedef size_t (*FLAC__IOCallback_Read) (void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  86615. /** Signature for the write callback.
  86616. * The signature and semantics match POSIX fwrite() implementations
  86617. * and can generally be used interchangeably.
  86618. *
  86619. * \param ptr The address of the write buffer.
  86620. * \param size The size of the records to be written.
  86621. * \param nmemb The number of records to be written.
  86622. * \param handle The handle to the data source.
  86623. * \retval size_t
  86624. * The number of records written.
  86625. */
  86626. typedef size_t (*FLAC__IOCallback_Write) (const void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  86627. /** Signature for the seek callback.
  86628. * The signature and semantics mostly match POSIX fseek() WITH ONE IMPORTANT
  86629. * EXCEPTION: the offset is a 64-bit type whereas fseek() is generally 'long'
  86630. * and 32-bits wide.
  86631. *
  86632. * \param handle The handle to the data source.
  86633. * \param offset The new position, relative to \a whence
  86634. * \param whence \c SEEK_SET, \c SEEK_CUR, or \c SEEK_END
  86635. * \retval int
  86636. * \c 0 on success, \c -1 on error.
  86637. */
  86638. typedef int (*FLAC__IOCallback_Seek) (FLAC__IOHandle handle, FLAC__int64 offset, int whence);
  86639. /** Signature for the tell callback.
  86640. * The signature and semantics mostly match POSIX ftell() WITH ONE IMPORTANT
  86641. * EXCEPTION: the offset is a 64-bit type whereas ftell() is generally 'long'
  86642. * and 32-bits wide.
  86643. *
  86644. * \param handle The handle to the data source.
  86645. * \retval FLAC__int64
  86646. * The current position on success, \c -1 on error.
  86647. */
  86648. typedef FLAC__int64 (*FLAC__IOCallback_Tell) (FLAC__IOHandle handle);
  86649. /** Signature for the EOF callback.
  86650. * The signature and semantics mostly match POSIX feof() but WATCHOUT:
  86651. * on many systems, feof() is a macro, so in this case a wrapper function
  86652. * must be provided instead.
  86653. *
  86654. * \param handle The handle to the data source.
  86655. * \retval int
  86656. * \c 0 if not at end of file, nonzero if at end of file.
  86657. */
  86658. typedef int (*FLAC__IOCallback_Eof) (FLAC__IOHandle handle);
  86659. /** Signature for the close callback.
  86660. * The signature and semantics match POSIX fclose() implementations
  86661. * and can generally be used interchangeably.
  86662. *
  86663. * \param handle The handle to the data source.
  86664. * \retval int
  86665. * \c 0 on success, \c EOF on error.
  86666. */
  86667. typedef int (*FLAC__IOCallback_Close) (FLAC__IOHandle handle);
  86668. /** A structure for holding a set of callbacks.
  86669. * Each FLAC interface that requires a FLAC__IOCallbacks structure will
  86670. * describe which of the callbacks are required. The ones that are not
  86671. * required may be set to NULL.
  86672. *
  86673. * If the seek requirement for an interface is optional, you can signify that
  86674. * a data sorce is not seekable by setting the \a seek field to \c NULL.
  86675. */
  86676. typedef struct {
  86677. FLAC__IOCallback_Read read;
  86678. FLAC__IOCallback_Write write;
  86679. FLAC__IOCallback_Seek seek;
  86680. FLAC__IOCallback_Tell tell;
  86681. FLAC__IOCallback_Eof eof;
  86682. FLAC__IOCallback_Close close;
  86683. } FLAC__IOCallbacks;
  86684. /* \} */
  86685. #ifdef __cplusplus
  86686. }
  86687. #endif
  86688. #endif
  86689. /*** End of inlined file: callback.h ***/
  86690. /*** Start of inlined file: format.h ***/
  86691. #ifndef FLAC__FORMAT_H
  86692. #define FLAC__FORMAT_H
  86693. #ifdef __cplusplus
  86694. extern "C" {
  86695. #endif
  86696. /** \file include/FLAC/format.h
  86697. *
  86698. * \brief
  86699. * This module contains structure definitions for the representation
  86700. * of FLAC format components in memory. These are the basic
  86701. * structures used by the rest of the interfaces.
  86702. *
  86703. * See the detailed documentation in the
  86704. * \link flac_format format \endlink module.
  86705. */
  86706. /** \defgroup flac_format FLAC/format.h: format components
  86707. * \ingroup flac
  86708. *
  86709. * \brief
  86710. * This module contains structure definitions for the representation
  86711. * of FLAC format components in memory. These are the basic
  86712. * structures used by the rest of the interfaces.
  86713. *
  86714. * First, you should be familiar with the
  86715. * <A HREF="../format.html">FLAC format</A>. Many of the values here
  86716. * follow directly from the specification. As a user of libFLAC, the
  86717. * interesting parts really are the structures that describe the frame
  86718. * header and metadata blocks.
  86719. *
  86720. * The format structures here are very primitive, designed to store
  86721. * information in an efficient way. Reading information from the
  86722. * structures is easy but creating or modifying them directly is
  86723. * more complex. For the most part, as a user of a library, editing
  86724. * is not necessary; however, for metadata blocks it is, so there are
  86725. * convenience functions provided in the \link flac_metadata metadata
  86726. * module \endlink to simplify the manipulation of metadata blocks.
  86727. *
  86728. * \note
  86729. * It's not the best convention, but symbols ending in _LEN are in bits
  86730. * and _LENGTH are in bytes. _LENGTH symbols are \#defines instead of
  86731. * global variables because they are usually used when declaring byte
  86732. * arrays and some compilers require compile-time knowledge of array
  86733. * sizes when declared on the stack.
  86734. *
  86735. * \{
  86736. */
  86737. /*
  86738. Most of the values described in this file are defined by the FLAC
  86739. format specification. There is nothing to tune here.
  86740. */
  86741. /** The largest legal metadata type code. */
  86742. #define FLAC__MAX_METADATA_TYPE_CODE (126u)
  86743. /** The minimum block size, in samples, permitted by the format. */
  86744. #define FLAC__MIN_BLOCK_SIZE (16u)
  86745. /** The maximum block size, in samples, permitted by the format. */
  86746. #define FLAC__MAX_BLOCK_SIZE (65535u)
  86747. /** The maximum block size, in samples, permitted by the FLAC subset for
  86748. * sample rates up to 48kHz. */
  86749. #define FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ (4608u)
  86750. /** The maximum number of channels permitted by the format. */
  86751. #define FLAC__MAX_CHANNELS (8u)
  86752. /** The minimum sample resolution permitted by the format. */
  86753. #define FLAC__MIN_BITS_PER_SAMPLE (4u)
  86754. /** The maximum sample resolution permitted by the format. */
  86755. #define FLAC__MAX_BITS_PER_SAMPLE (32u)
  86756. /** The maximum sample resolution permitted by libFLAC.
  86757. *
  86758. * \warning
  86759. * FLAC__MAX_BITS_PER_SAMPLE is the limit of the FLAC format. However,
  86760. * the reference encoder/decoder is currently limited to 24 bits because
  86761. * of prevalent 32-bit math, so make sure and use this value when
  86762. * appropriate.
  86763. */
  86764. #define FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE (24u)
  86765. /** The maximum sample rate permitted by the format. The value is
  86766. * ((2 ^ 16) - 1) * 10; see <A HREF="../format.html">FLAC format</A>
  86767. * as to why.
  86768. */
  86769. #define FLAC__MAX_SAMPLE_RATE (655350u)
  86770. /** The maximum LPC order permitted by the format. */
  86771. #define FLAC__MAX_LPC_ORDER (32u)
  86772. /** The maximum LPC order permitted by the FLAC subset for sample rates
  86773. * up to 48kHz. */
  86774. #define FLAC__SUBSET_MAX_LPC_ORDER_48000HZ (12u)
  86775. /** The minimum quantized linear predictor coefficient precision
  86776. * permitted by the format.
  86777. */
  86778. #define FLAC__MIN_QLP_COEFF_PRECISION (5u)
  86779. /** The maximum quantized linear predictor coefficient precision
  86780. * permitted by the format.
  86781. */
  86782. #define FLAC__MAX_QLP_COEFF_PRECISION (15u)
  86783. /** The maximum order of the fixed predictors permitted by the format. */
  86784. #define FLAC__MAX_FIXED_ORDER (4u)
  86785. /** The maximum Rice partition order permitted by the format. */
  86786. #define FLAC__MAX_RICE_PARTITION_ORDER (15u)
  86787. /** The maximum Rice partition order permitted by the FLAC Subset. */
  86788. #define FLAC__SUBSET_MAX_RICE_PARTITION_ORDER (8u)
  86789. /** The version string of the release, stamped onto the libraries and binaries.
  86790. *
  86791. * \note
  86792. * This does not correspond to the shared library version number, which
  86793. * is used to determine binary compatibility.
  86794. */
  86795. extern FLAC_API const char *FLAC__VERSION_STRING;
  86796. /** The vendor string inserted by the encoder into the VORBIS_COMMENT block.
  86797. * This is a NUL-terminated ASCII string; when inserted into the
  86798. * VORBIS_COMMENT the trailing null is stripped.
  86799. */
  86800. extern FLAC_API const char *FLAC__VENDOR_STRING;
  86801. /** The byte string representation of the beginning of a FLAC stream. */
  86802. extern FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4]; /* = "fLaC" */
  86803. /** The 32-bit integer big-endian representation of the beginning of
  86804. * a FLAC stream.
  86805. */
  86806. extern FLAC_API const unsigned FLAC__STREAM_SYNC; /* = 0x664C6143 */
  86807. /** The length of the FLAC signature in bits. */
  86808. extern FLAC_API const unsigned FLAC__STREAM_SYNC_LEN; /* = 32 bits */
  86809. /** The length of the FLAC signature in bytes. */
  86810. #define FLAC__STREAM_SYNC_LENGTH (4u)
  86811. /*****************************************************************************
  86812. *
  86813. * Subframe structures
  86814. *
  86815. *****************************************************************************/
  86816. /*****************************************************************************/
  86817. /** An enumeration of the available entropy coding methods. */
  86818. typedef enum {
  86819. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE = 0,
  86820. /**< Residual is coded by partitioning into contexts, each with it's own
  86821. * 4-bit Rice parameter. */
  86822. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 = 1
  86823. /**< Residual is coded by partitioning into contexts, each with it's own
  86824. * 5-bit Rice parameter. */
  86825. } FLAC__EntropyCodingMethodType;
  86826. /** Maps a FLAC__EntropyCodingMethodType to a C string.
  86827. *
  86828. * Using a FLAC__EntropyCodingMethodType as the index to this array will
  86829. * give the string equivalent. The contents should not be modified.
  86830. */
  86831. extern FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[];
  86832. /** Contents of a Rice partitioned residual
  86833. */
  86834. typedef struct {
  86835. unsigned *parameters;
  86836. /**< The Rice parameters for each context. */
  86837. unsigned *raw_bits;
  86838. /**< Widths for escape-coded partitions. Will be non-zero for escaped
  86839. * partitions and zero for unescaped partitions.
  86840. */
  86841. unsigned capacity_by_order;
  86842. /**< The capacity of the \a parameters and \a raw_bits arrays
  86843. * specified as an order, i.e. the number of array elements
  86844. * allocated is 2 ^ \a capacity_by_order.
  86845. */
  86846. } FLAC__EntropyCodingMethod_PartitionedRiceContents;
  86847. /** Header for a Rice partitioned residual. (c.f. <A HREF="../format.html#partitioned_rice">format specification</A>)
  86848. */
  86849. typedef struct {
  86850. unsigned order;
  86851. /**< The partition order, i.e. # of contexts = 2 ^ \a order. */
  86852. const FLAC__EntropyCodingMethod_PartitionedRiceContents *contents;
  86853. /**< The context's Rice parameters and/or raw bits. */
  86854. } FLAC__EntropyCodingMethod_PartitionedRice;
  86855. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN; /**< == 4 (bits) */
  86856. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN; /**< == 4 (bits) */
  86857. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN; /**< == 5 (bits) */
  86858. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN; /**< == 5 (bits) */
  86859. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  86860. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  86861. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER;
  86862. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  86863. /** Header for the entropy coding method. (c.f. <A HREF="../format.html#residual">format specification</A>)
  86864. */
  86865. typedef struct {
  86866. FLAC__EntropyCodingMethodType type;
  86867. union {
  86868. FLAC__EntropyCodingMethod_PartitionedRice partitioned_rice;
  86869. } data;
  86870. } FLAC__EntropyCodingMethod;
  86871. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN; /**< == 2 (bits) */
  86872. /*****************************************************************************/
  86873. /** An enumeration of the available subframe types. */
  86874. typedef enum {
  86875. FLAC__SUBFRAME_TYPE_CONSTANT = 0, /**< constant signal */
  86876. FLAC__SUBFRAME_TYPE_VERBATIM = 1, /**< uncompressed signal */
  86877. FLAC__SUBFRAME_TYPE_FIXED = 2, /**< fixed polynomial prediction */
  86878. FLAC__SUBFRAME_TYPE_LPC = 3 /**< linear prediction */
  86879. } FLAC__SubframeType;
  86880. /** Maps a FLAC__SubframeType to a C string.
  86881. *
  86882. * Using a FLAC__SubframeType as the index to this array will
  86883. * give the string equivalent. The contents should not be modified.
  86884. */
  86885. extern FLAC_API const char * const FLAC__SubframeTypeString[];
  86886. /** CONSTANT subframe. (c.f. <A HREF="../format.html#subframe_constant">format specification</A>)
  86887. */
  86888. typedef struct {
  86889. FLAC__int32 value; /**< The constant signal value. */
  86890. } FLAC__Subframe_Constant;
  86891. /** VERBATIM subframe. (c.f. <A HREF="../format.html#subframe_verbatim">format specification</A>)
  86892. */
  86893. typedef struct {
  86894. const FLAC__int32 *data; /**< A pointer to verbatim signal. */
  86895. } FLAC__Subframe_Verbatim;
  86896. /** FIXED subframe. (c.f. <A HREF="../format.html#subframe_fixed">format specification</A>)
  86897. */
  86898. typedef struct {
  86899. FLAC__EntropyCodingMethod entropy_coding_method;
  86900. /**< The residual coding method. */
  86901. unsigned order;
  86902. /**< The polynomial order. */
  86903. FLAC__int32 warmup[FLAC__MAX_FIXED_ORDER];
  86904. /**< Warmup samples to prime the predictor, length == order. */
  86905. const FLAC__int32 *residual;
  86906. /**< The residual signal, length == (blocksize minus order) samples. */
  86907. } FLAC__Subframe_Fixed;
  86908. /** LPC subframe. (c.f. <A HREF="../format.html#subframe_lpc">format specification</A>)
  86909. */
  86910. typedef struct {
  86911. FLAC__EntropyCodingMethod entropy_coding_method;
  86912. /**< The residual coding method. */
  86913. unsigned order;
  86914. /**< The FIR order. */
  86915. unsigned qlp_coeff_precision;
  86916. /**< Quantized FIR filter coefficient precision in bits. */
  86917. int quantization_level;
  86918. /**< The qlp coeff shift needed. */
  86919. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  86920. /**< FIR filter coefficients. */
  86921. FLAC__int32 warmup[FLAC__MAX_LPC_ORDER];
  86922. /**< Warmup samples to prime the predictor, length == order. */
  86923. const FLAC__int32 *residual;
  86924. /**< The residual signal, length == (blocksize minus order) samples. */
  86925. } FLAC__Subframe_LPC;
  86926. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN; /**< == 4 (bits) */
  86927. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN; /**< == 5 (bits) */
  86928. /** FLAC subframe structure. (c.f. <A HREF="../format.html#subframe">format specification</A>)
  86929. */
  86930. typedef struct {
  86931. FLAC__SubframeType type;
  86932. union {
  86933. FLAC__Subframe_Constant constant;
  86934. FLAC__Subframe_Fixed fixed;
  86935. FLAC__Subframe_LPC lpc;
  86936. FLAC__Subframe_Verbatim verbatim;
  86937. } data;
  86938. unsigned wasted_bits;
  86939. } FLAC__Subframe;
  86940. /** == 1 (bit)
  86941. *
  86942. * This used to be a zero-padding bit (hence the name
  86943. * FLAC__SUBFRAME_ZERO_PAD_LEN) but is now a reserved bit. It still has a
  86944. * mandatory value of \c 0 but in the future may take on the value \c 0 or \c 1
  86945. * to mean something else.
  86946. */
  86947. extern FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN;
  86948. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN; /**< == 6 (bits) */
  86949. extern FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN; /**< == 1 (bit) */
  86950. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK; /**< = 0x00 */
  86951. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK; /**< = 0x02 */
  86952. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK; /**< = 0x10 */
  86953. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK; /**< = 0x40 */
  86954. /*****************************************************************************/
  86955. /*****************************************************************************
  86956. *
  86957. * Frame structures
  86958. *
  86959. *****************************************************************************/
  86960. /** An enumeration of the available channel assignments. */
  86961. typedef enum {
  86962. FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT = 0, /**< independent channels */
  86963. FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE = 1, /**< left+side stereo */
  86964. FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE = 2, /**< right+side stereo */
  86965. FLAC__CHANNEL_ASSIGNMENT_MID_SIDE = 3 /**< mid+side stereo */
  86966. } FLAC__ChannelAssignment;
  86967. /** Maps a FLAC__ChannelAssignment to a C string.
  86968. *
  86969. * Using a FLAC__ChannelAssignment as the index to this array will
  86970. * give the string equivalent. The contents should not be modified.
  86971. */
  86972. extern FLAC_API const char * const FLAC__ChannelAssignmentString[];
  86973. /** An enumeration of the possible frame numbering methods. */
  86974. typedef enum {
  86975. FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER, /**< number contains the frame number */
  86976. FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER /**< number contains the sample number of first sample in frame */
  86977. } FLAC__FrameNumberType;
  86978. /** Maps a FLAC__FrameNumberType to a C string.
  86979. *
  86980. * Using a FLAC__FrameNumberType as the index to this array will
  86981. * give the string equivalent. The contents should not be modified.
  86982. */
  86983. extern FLAC_API const char * const FLAC__FrameNumberTypeString[];
  86984. /** FLAC frame header structure. (c.f. <A HREF="../format.html#frame_header">format specification</A>)
  86985. */
  86986. typedef struct {
  86987. unsigned blocksize;
  86988. /**< The number of samples per subframe. */
  86989. unsigned sample_rate;
  86990. /**< The sample rate in Hz. */
  86991. unsigned channels;
  86992. /**< The number of channels (== number of subframes). */
  86993. FLAC__ChannelAssignment channel_assignment;
  86994. /**< The channel assignment for the frame. */
  86995. unsigned bits_per_sample;
  86996. /**< The sample resolution. */
  86997. FLAC__FrameNumberType number_type;
  86998. /**< The numbering scheme used for the frame. As a convenience, the
  86999. * decoder will always convert a frame number to a sample number because
  87000. * the rules are complex. */
  87001. union {
  87002. FLAC__uint32 frame_number;
  87003. FLAC__uint64 sample_number;
  87004. } number;
  87005. /**< The frame number or sample number of first sample in frame;
  87006. * use the \a number_type value to determine which to use. */
  87007. FLAC__uint8 crc;
  87008. /**< CRC-8 (polynomial = x^8 + x^2 + x^1 + x^0, initialized with 0)
  87009. * of the raw frame header bytes, meaning everything before the CRC byte
  87010. * including the sync code.
  87011. */
  87012. } FLAC__FrameHeader;
  87013. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC; /**< == 0x3ffe; the frame header sync code */
  87014. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN; /**< == 14 (bits) */
  87015. extern FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN; /**< == 1 (bits) */
  87016. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN; /**< == 1 (bits) */
  87017. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN; /**< == 4 (bits) */
  87018. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN; /**< == 4 (bits) */
  87019. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN; /**< == 4 (bits) */
  87020. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN; /**< == 3 (bits) */
  87021. extern FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN; /**< == 1 (bit) */
  87022. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN; /**< == 8 (bits) */
  87023. /** FLAC frame footer structure. (c.f. <A HREF="../format.html#frame_footer">format specification</A>)
  87024. */
  87025. typedef struct {
  87026. FLAC__uint16 crc;
  87027. /**< CRC-16 (polynomial = x^16 + x^15 + x^2 + x^0, initialized with
  87028. * 0) of the bytes before the crc, back to and including the frame header
  87029. * sync code.
  87030. */
  87031. } FLAC__FrameFooter;
  87032. extern FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN; /**< == 16 (bits) */
  87033. /** FLAC frame structure. (c.f. <A HREF="../format.html#frame">format specification</A>)
  87034. */
  87035. typedef struct {
  87036. FLAC__FrameHeader header;
  87037. FLAC__Subframe subframes[FLAC__MAX_CHANNELS];
  87038. FLAC__FrameFooter footer;
  87039. } FLAC__Frame;
  87040. /*****************************************************************************/
  87041. /*****************************************************************************
  87042. *
  87043. * Meta-data structures
  87044. *
  87045. *****************************************************************************/
  87046. /** An enumeration of the available metadata block types. */
  87047. typedef enum {
  87048. FLAC__METADATA_TYPE_STREAMINFO = 0,
  87049. /**< <A HREF="../format.html#metadata_block_streaminfo">STREAMINFO</A> block */
  87050. FLAC__METADATA_TYPE_PADDING = 1,
  87051. /**< <A HREF="../format.html#metadata_block_padding">PADDING</A> block */
  87052. FLAC__METADATA_TYPE_APPLICATION = 2,
  87053. /**< <A HREF="../format.html#metadata_block_application">APPLICATION</A> block */
  87054. FLAC__METADATA_TYPE_SEEKTABLE = 3,
  87055. /**< <A HREF="../format.html#metadata_block_seektable">SEEKTABLE</A> block */
  87056. FLAC__METADATA_TYPE_VORBIS_COMMENT = 4,
  87057. /**< <A HREF="../format.html#metadata_block_vorbis_comment">VORBISCOMMENT</A> block (a.k.a. FLAC tags) */
  87058. FLAC__METADATA_TYPE_CUESHEET = 5,
  87059. /**< <A HREF="../format.html#metadata_block_cuesheet">CUESHEET</A> block */
  87060. FLAC__METADATA_TYPE_PICTURE = 6,
  87061. /**< <A HREF="../format.html#metadata_block_picture">PICTURE</A> block */
  87062. FLAC__METADATA_TYPE_UNDEFINED = 7
  87063. /**< marker to denote beginning of undefined type range; this number will increase as new metadata types are added */
  87064. } FLAC__MetadataType;
  87065. /** Maps a FLAC__MetadataType to a C string.
  87066. *
  87067. * Using a FLAC__MetadataType as the index to this array will
  87068. * give the string equivalent. The contents should not be modified.
  87069. */
  87070. extern FLAC_API const char * const FLAC__MetadataTypeString[];
  87071. /** FLAC STREAMINFO structure. (c.f. <A HREF="../format.html#metadata_block_streaminfo">format specification</A>)
  87072. */
  87073. typedef struct {
  87074. unsigned min_blocksize, max_blocksize;
  87075. unsigned min_framesize, max_framesize;
  87076. unsigned sample_rate;
  87077. unsigned channels;
  87078. unsigned bits_per_sample;
  87079. FLAC__uint64 total_samples;
  87080. FLAC__byte md5sum[16];
  87081. } FLAC__StreamMetadata_StreamInfo;
  87082. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  87083. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  87084. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN; /**< == 24 (bits) */
  87085. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN; /**< == 24 (bits) */
  87086. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN; /**< == 20 (bits) */
  87087. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN; /**< == 3 (bits) */
  87088. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN; /**< == 5 (bits) */
  87089. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN; /**< == 36 (bits) */
  87090. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN; /**< == 128 (bits) */
  87091. /** The total stream length of the STREAMINFO block in bytes. */
  87092. #define FLAC__STREAM_METADATA_STREAMINFO_LENGTH (34u)
  87093. /** FLAC PADDING structure. (c.f. <A HREF="../format.html#metadata_block_padding">format specification</A>)
  87094. */
  87095. typedef struct {
  87096. int dummy;
  87097. /**< Conceptually this is an empty struct since we don't store the
  87098. * padding bytes. Empty structs are not allowed by some C compilers,
  87099. * hence the dummy.
  87100. */
  87101. } FLAC__StreamMetadata_Padding;
  87102. /** FLAC APPLICATION structure. (c.f. <A HREF="../format.html#metadata_block_application">format specification</A>)
  87103. */
  87104. typedef struct {
  87105. FLAC__byte id[4];
  87106. FLAC__byte *data;
  87107. } FLAC__StreamMetadata_Application;
  87108. extern FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN; /**< == 32 (bits) */
  87109. /** SeekPoint structure used in SEEKTABLE blocks. (c.f. <A HREF="../format.html#seekpoint">format specification</A>)
  87110. */
  87111. typedef struct {
  87112. FLAC__uint64 sample_number;
  87113. /**< The sample number of the target frame. */
  87114. FLAC__uint64 stream_offset;
  87115. /**< The offset, in bytes, of the target frame with respect to
  87116. * beginning of the first frame. */
  87117. unsigned frame_samples;
  87118. /**< The number of samples in the target frame. */
  87119. } FLAC__StreamMetadata_SeekPoint;
  87120. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN; /**< == 64 (bits) */
  87121. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN; /**< == 64 (bits) */
  87122. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN; /**< == 16 (bits) */
  87123. /** The total stream length of a seek point in bytes. */
  87124. #define FLAC__STREAM_METADATA_SEEKPOINT_LENGTH (18u)
  87125. /** The value used in the \a sample_number field of
  87126. * FLAC__StreamMetadataSeekPoint used to indicate a placeholder
  87127. * point (== 0xffffffffffffffff).
  87128. */
  87129. extern FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  87130. /** FLAC SEEKTABLE structure. (c.f. <A HREF="../format.html#metadata_block_seektable">format specification</A>)
  87131. *
  87132. * \note From the format specification:
  87133. * - The seek points must be sorted by ascending sample number.
  87134. * - Each seek point's sample number must be the first sample of the
  87135. * target frame.
  87136. * - Each seek point's sample number must be unique within the table.
  87137. * - Existence of a SEEKTABLE block implies a correct setting of
  87138. * total_samples in the stream_info block.
  87139. * - Behavior is undefined when more than one SEEKTABLE block is
  87140. * present in a stream.
  87141. */
  87142. typedef struct {
  87143. unsigned num_points;
  87144. FLAC__StreamMetadata_SeekPoint *points;
  87145. } FLAC__StreamMetadata_SeekTable;
  87146. /** Vorbis comment entry structure used in VORBIS_COMMENT blocks. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  87147. *
  87148. * For convenience, the APIs maintain a trailing NUL character at the end of
  87149. * \a entry which is not counted toward \a length, i.e.
  87150. * \code strlen(entry) == length \endcode
  87151. */
  87152. typedef struct {
  87153. FLAC__uint32 length;
  87154. FLAC__byte *entry;
  87155. } FLAC__StreamMetadata_VorbisComment_Entry;
  87156. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN; /**< == 32 (bits) */
  87157. /** FLAC VORBIS_COMMENT structure. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  87158. */
  87159. typedef struct {
  87160. FLAC__StreamMetadata_VorbisComment_Entry vendor_string;
  87161. FLAC__uint32 num_comments;
  87162. FLAC__StreamMetadata_VorbisComment_Entry *comments;
  87163. } FLAC__StreamMetadata_VorbisComment;
  87164. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN; /**< == 32 (bits) */
  87165. /** FLAC CUESHEET track index structure. (See the
  87166. * <A HREF="../format.html#cuesheet_track_index">format specification</A> for
  87167. * the full description of each field.)
  87168. */
  87169. typedef struct {
  87170. FLAC__uint64 offset;
  87171. /**< Offset in samples, relative to the track offset, of the index
  87172. * point.
  87173. */
  87174. FLAC__byte number;
  87175. /**< The index point number. */
  87176. } FLAC__StreamMetadata_CueSheet_Index;
  87177. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN; /**< == 64 (bits) */
  87178. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN; /**< == 8 (bits) */
  87179. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN; /**< == 3*8 (bits) */
  87180. /** FLAC CUESHEET track structure. (See the
  87181. * <A HREF="../format.html#cuesheet_track">format specification</A> for
  87182. * the full description of each field.)
  87183. */
  87184. typedef struct {
  87185. FLAC__uint64 offset;
  87186. /**< Track offset in samples, relative to the beginning of the FLAC audio stream. */
  87187. FLAC__byte number;
  87188. /**< The track number. */
  87189. char isrc[13];
  87190. /**< Track ISRC. This is a 12-digit alphanumeric code plus a trailing \c NUL byte */
  87191. unsigned type:1;
  87192. /**< The track type: 0 for audio, 1 for non-audio. */
  87193. unsigned pre_emphasis:1;
  87194. /**< The pre-emphasis flag: 0 for no pre-emphasis, 1 for pre-emphasis. */
  87195. FLAC__byte num_indices;
  87196. /**< The number of track index points. */
  87197. FLAC__StreamMetadata_CueSheet_Index *indices;
  87198. /**< NULL if num_indices == 0, else pointer to array of index points. */
  87199. } FLAC__StreamMetadata_CueSheet_Track;
  87200. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN; /**< == 64 (bits) */
  87201. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN; /**< == 8 (bits) */
  87202. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN; /**< == 12*8 (bits) */
  87203. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN; /**< == 1 (bit) */
  87204. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN; /**< == 1 (bit) */
  87205. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN; /**< == 6+13*8 (bits) */
  87206. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN; /**< == 8 (bits) */
  87207. /** FLAC CUESHEET structure. (See the
  87208. * <A HREF="../format.html#metadata_block_cuesheet">format specification</A>
  87209. * for the full description of each field.)
  87210. */
  87211. typedef struct {
  87212. char media_catalog_number[129];
  87213. /**< Media catalog number, in ASCII printable characters 0x20-0x7e. In
  87214. * general, the media catalog number may be 0 to 128 bytes long; any
  87215. * unused characters should be right-padded with NUL characters.
  87216. */
  87217. FLAC__uint64 lead_in;
  87218. /**< The number of lead-in samples. */
  87219. FLAC__bool is_cd;
  87220. /**< \c true if CUESHEET corresponds to a Compact Disc, else \c false. */
  87221. unsigned num_tracks;
  87222. /**< The number of tracks. */
  87223. FLAC__StreamMetadata_CueSheet_Track *tracks;
  87224. /**< NULL if num_tracks == 0, else pointer to array of tracks. */
  87225. } FLAC__StreamMetadata_CueSheet;
  87226. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN; /**< == 128*8 (bits) */
  87227. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN; /**< == 64 (bits) */
  87228. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN; /**< == 1 (bit) */
  87229. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN; /**< == 7+258*8 (bits) */
  87230. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN; /**< == 8 (bits) */
  87231. /** An enumeration of the PICTURE types (see FLAC__StreamMetadataPicture and id3 v2.4 APIC tag). */
  87232. typedef enum {
  87233. FLAC__STREAM_METADATA_PICTURE_TYPE_OTHER = 0, /**< Other */
  87234. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD = 1, /**< 32x32 pixels 'file icon' (PNG only) */
  87235. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON = 2, /**< Other file icon */
  87236. FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER = 3, /**< Cover (front) */
  87237. FLAC__STREAM_METADATA_PICTURE_TYPE_BACK_COVER = 4, /**< Cover (back) */
  87238. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAFLET_PAGE = 5, /**< Leaflet page */
  87239. FLAC__STREAM_METADATA_PICTURE_TYPE_MEDIA = 6, /**< Media (e.g. label side of CD) */
  87240. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAD_ARTIST = 7, /**< Lead artist/lead performer/soloist */
  87241. FLAC__STREAM_METADATA_PICTURE_TYPE_ARTIST = 8, /**< Artist/performer */
  87242. FLAC__STREAM_METADATA_PICTURE_TYPE_CONDUCTOR = 9, /**< Conductor */
  87243. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND = 10, /**< Band/Orchestra */
  87244. FLAC__STREAM_METADATA_PICTURE_TYPE_COMPOSER = 11, /**< Composer */
  87245. FLAC__STREAM_METADATA_PICTURE_TYPE_LYRICIST = 12, /**< Lyricist/text writer */
  87246. FLAC__STREAM_METADATA_PICTURE_TYPE_RECORDING_LOCATION = 13, /**< Recording Location */
  87247. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_RECORDING = 14, /**< During recording */
  87248. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_PERFORMANCE = 15, /**< During performance */
  87249. FLAC__STREAM_METADATA_PICTURE_TYPE_VIDEO_SCREEN_CAPTURE = 16, /**< Movie/video screen capture */
  87250. FLAC__STREAM_METADATA_PICTURE_TYPE_FISH = 17, /**< A bright coloured fish */
  87251. FLAC__STREAM_METADATA_PICTURE_TYPE_ILLUSTRATION = 18, /**< Illustration */
  87252. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND_LOGOTYPE = 19, /**< Band/artist logotype */
  87253. FLAC__STREAM_METADATA_PICTURE_TYPE_PUBLISHER_LOGOTYPE = 20, /**< Publisher/Studio logotype */
  87254. FLAC__STREAM_METADATA_PICTURE_TYPE_UNDEFINED
  87255. } FLAC__StreamMetadata_Picture_Type;
  87256. /** Maps a FLAC__StreamMetadata_Picture_Type to a C string.
  87257. *
  87258. * Using a FLAC__StreamMetadata_Picture_Type as the index to this array
  87259. * will give the string equivalent. The contents should not be
  87260. * modified.
  87261. */
  87262. extern FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[];
  87263. /** FLAC PICTURE structure. (See the
  87264. * <A HREF="../format.html#metadata_block_picture">format specification</A>
  87265. * for the full description of each field.)
  87266. */
  87267. typedef struct {
  87268. FLAC__StreamMetadata_Picture_Type type;
  87269. /**< The kind of picture stored. */
  87270. char *mime_type;
  87271. /**< Picture data's MIME type, in ASCII printable characters
  87272. * 0x20-0x7e, NUL terminated. For best compatibility with players,
  87273. * use picture data of MIME type \c image/jpeg or \c image/png. A
  87274. * MIME type of '-->' is also allowed, in which case the picture
  87275. * data should be a complete URL. In file storage, the MIME type is
  87276. * stored as a 32-bit length followed by the ASCII string with no NUL
  87277. * terminator, but is converted to a plain C string in this structure
  87278. * for convenience.
  87279. */
  87280. FLAC__byte *description;
  87281. /**< Picture's description in UTF-8, NUL terminated. In file storage,
  87282. * the description is stored as a 32-bit length followed by the UTF-8
  87283. * string with no NUL terminator, but is converted to a plain C string
  87284. * in this structure for convenience.
  87285. */
  87286. FLAC__uint32 width;
  87287. /**< Picture's width in pixels. */
  87288. FLAC__uint32 height;
  87289. /**< Picture's height in pixels. */
  87290. FLAC__uint32 depth;
  87291. /**< Picture's color depth in bits-per-pixel. */
  87292. FLAC__uint32 colors;
  87293. /**< For indexed palettes (like GIF), picture's number of colors (the
  87294. * number of palette entries), or \c 0 for non-indexed (i.e. 2^depth).
  87295. */
  87296. FLAC__uint32 data_length;
  87297. /**< Length of binary picture data in bytes. */
  87298. FLAC__byte *data;
  87299. /**< Binary picture data. */
  87300. } FLAC__StreamMetadata_Picture;
  87301. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN; /**< == 32 (bits) */
  87302. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN; /**< == 32 (bits) */
  87303. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN; /**< == 32 (bits) */
  87304. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN; /**< == 32 (bits) */
  87305. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN; /**< == 32 (bits) */
  87306. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN; /**< == 32 (bits) */
  87307. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN; /**< == 32 (bits) */
  87308. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN; /**< == 32 (bits) */
  87309. /** Structure that is used when a metadata block of unknown type is loaded.
  87310. * The contents are opaque. The structure is used only internally to
  87311. * correctly handle unknown metadata.
  87312. */
  87313. typedef struct {
  87314. FLAC__byte *data;
  87315. } FLAC__StreamMetadata_Unknown;
  87316. /** FLAC metadata block structure. (c.f. <A HREF="../format.html#metadata_block">format specification</A>)
  87317. */
  87318. typedef struct {
  87319. FLAC__MetadataType type;
  87320. /**< The type of the metadata block; used determine which member of the
  87321. * \a data union to dereference. If type >= FLAC__METADATA_TYPE_UNDEFINED
  87322. * then \a data.unknown must be used. */
  87323. FLAC__bool is_last;
  87324. /**< \c true if this metadata block is the last, else \a false */
  87325. unsigned length;
  87326. /**< Length, in bytes, of the block data as it appears in the stream. */
  87327. union {
  87328. FLAC__StreamMetadata_StreamInfo stream_info;
  87329. FLAC__StreamMetadata_Padding padding;
  87330. FLAC__StreamMetadata_Application application;
  87331. FLAC__StreamMetadata_SeekTable seek_table;
  87332. FLAC__StreamMetadata_VorbisComment vorbis_comment;
  87333. FLAC__StreamMetadata_CueSheet cue_sheet;
  87334. FLAC__StreamMetadata_Picture picture;
  87335. FLAC__StreamMetadata_Unknown unknown;
  87336. } data;
  87337. /**< Polymorphic block data; use the \a type value to determine which
  87338. * to use. */
  87339. } FLAC__StreamMetadata;
  87340. extern FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN; /**< == 1 (bit) */
  87341. extern FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN; /**< == 7 (bits) */
  87342. extern FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN; /**< == 24 (bits) */
  87343. /** The total stream length of a metadata block header in bytes. */
  87344. #define FLAC__STREAM_METADATA_HEADER_LENGTH (4u)
  87345. /*****************************************************************************/
  87346. /*****************************************************************************
  87347. *
  87348. * Utility functions
  87349. *
  87350. *****************************************************************************/
  87351. /** Tests that a sample rate is valid for FLAC.
  87352. *
  87353. * \param sample_rate The sample rate to test for compliance.
  87354. * \retval FLAC__bool
  87355. * \c true if the given sample rate conforms to the specification, else
  87356. * \c false.
  87357. */
  87358. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate);
  87359. /** Tests that a sample rate is valid for the FLAC subset. The subset rules
  87360. * for valid sample rates are slightly more complex since the rate has to
  87361. * be expressible completely in the frame header.
  87362. *
  87363. * \param sample_rate The sample rate to test for compliance.
  87364. * \retval FLAC__bool
  87365. * \c true if the given sample rate conforms to the specification for the
  87366. * subset, else \c false.
  87367. */
  87368. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate);
  87369. /** Check a Vorbis comment entry name to see if it conforms to the Vorbis
  87370. * comment specification.
  87371. *
  87372. * Vorbis comment names must be composed only of characters from
  87373. * [0x20-0x3C,0x3E-0x7D].
  87374. *
  87375. * \param name A NUL-terminated string to be checked.
  87376. * \assert
  87377. * \code name != NULL \endcode
  87378. * \retval FLAC__bool
  87379. * \c false if entry name is illegal, else \c true.
  87380. */
  87381. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name);
  87382. /** Check a Vorbis comment entry value to see if it conforms to the Vorbis
  87383. * comment specification.
  87384. *
  87385. * Vorbis comment values must be valid UTF-8 sequences.
  87386. *
  87387. * \param value A string to be checked.
  87388. * \param length A the length of \a value in bytes. May be
  87389. * \c (unsigned)(-1) to indicate that \a value is a plain
  87390. * UTF-8 NUL-terminated string.
  87391. * \assert
  87392. * \code value != NULL \endcode
  87393. * \retval FLAC__bool
  87394. * \c false if entry name is illegal, else \c true.
  87395. */
  87396. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length);
  87397. /** Check a Vorbis comment entry to see if it conforms to the Vorbis
  87398. * comment specification.
  87399. *
  87400. * Vorbis comment entries must be of the form 'name=value', and 'name' and
  87401. * 'value' must be legal according to
  87402. * FLAC__format_vorbiscomment_entry_name_is_legal() and
  87403. * FLAC__format_vorbiscomment_entry_value_is_legal() respectively.
  87404. *
  87405. * \param entry An entry to be checked.
  87406. * \param length The length of \a entry in bytes.
  87407. * \assert
  87408. * \code value != NULL \endcode
  87409. * \retval FLAC__bool
  87410. * \c false if entry name is illegal, else \c true.
  87411. */
  87412. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length);
  87413. /** Check a seek table to see if it conforms to the FLAC specification.
  87414. * See the format specification for limits on the contents of the
  87415. * seek table.
  87416. *
  87417. * \param seek_table A pointer to a seek table to be checked.
  87418. * \assert
  87419. * \code seek_table != NULL \endcode
  87420. * \retval FLAC__bool
  87421. * \c false if seek table is illegal, else \c true.
  87422. */
  87423. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table);
  87424. /** Sort a seek table's seek points according to the format specification.
  87425. * This includes a "unique-ification" step to remove duplicates, i.e.
  87426. * seek points with identical \a sample_number values. Duplicate seek
  87427. * points are converted into placeholder points and sorted to the end of
  87428. * the table.
  87429. *
  87430. * \param seek_table A pointer to a seek table to be sorted.
  87431. * \assert
  87432. * \code seek_table != NULL \endcode
  87433. * \retval unsigned
  87434. * The number of duplicate seek points converted into placeholders.
  87435. */
  87436. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table);
  87437. /** Check a cue sheet to see if it conforms to the FLAC specification.
  87438. * See the format specification for limits on the contents of the
  87439. * cue sheet.
  87440. *
  87441. * \param cue_sheet A pointer to an existing cue sheet to be checked.
  87442. * \param check_cd_da_subset If \c true, check CUESHEET against more
  87443. * stringent requirements for a CD-DA (audio) disc.
  87444. * \param violation Address of a pointer to a string. If there is a
  87445. * violation, a pointer to a string explanation of the
  87446. * violation will be returned here. \a violation may be
  87447. * \c NULL if you don't need the returned string. Do not
  87448. * free the returned string; it will always point to static
  87449. * data.
  87450. * \assert
  87451. * \code cue_sheet != NULL \endcode
  87452. * \retval FLAC__bool
  87453. * \c false if cue sheet is illegal, else \c true.
  87454. */
  87455. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation);
  87456. /** Check picture data to see if it conforms to the FLAC specification.
  87457. * See the format specification for limits on the contents of the
  87458. * PICTURE block.
  87459. *
  87460. * \param picture A pointer to existing picture data to be checked.
  87461. * \param violation Address of a pointer to a string. If there is a
  87462. * violation, a pointer to a string explanation of the
  87463. * violation will be returned here. \a violation may be
  87464. * \c NULL if you don't need the returned string. Do not
  87465. * free the returned string; it will always point to static
  87466. * data.
  87467. * \assert
  87468. * \code picture != NULL \endcode
  87469. * \retval FLAC__bool
  87470. * \c false if picture data is illegal, else \c true.
  87471. */
  87472. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation);
  87473. /* \} */
  87474. #ifdef __cplusplus
  87475. }
  87476. #endif
  87477. #endif
  87478. /*** End of inlined file: format.h ***/
  87479. /*** Start of inlined file: metadata.h ***/
  87480. #ifndef FLAC__METADATA_H
  87481. #define FLAC__METADATA_H
  87482. #include <sys/types.h> /* for off_t */
  87483. /* --------------------------------------------------------------------
  87484. (For an example of how all these routines are used, see the source
  87485. code for the unit tests in src/test_libFLAC/metadata_*.c, or
  87486. metaflac in src/metaflac/)
  87487. ------------------------------------------------------------------*/
  87488. /** \file include/FLAC/metadata.h
  87489. *
  87490. * \brief
  87491. * This module provides functions for creating and manipulating FLAC
  87492. * metadata blocks in memory, and three progressively more powerful
  87493. * interfaces for traversing and editing metadata in FLAC files.
  87494. *
  87495. * See the detailed documentation for each interface in the
  87496. * \link flac_metadata metadata \endlink module.
  87497. */
  87498. /** \defgroup flac_metadata FLAC/metadata.h: metadata interfaces
  87499. * \ingroup flac
  87500. *
  87501. * \brief
  87502. * This module provides functions for creating and manipulating FLAC
  87503. * metadata blocks in memory, and three progressively more powerful
  87504. * interfaces for traversing and editing metadata in native FLAC files.
  87505. * Note that currently only the Chain interface (level 2) supports Ogg
  87506. * FLAC files, and it is read-only i.e. no writing back changed
  87507. * metadata to file.
  87508. *
  87509. * There are three metadata interfaces of increasing complexity:
  87510. *
  87511. * Level 0:
  87512. * Read-only access to the STREAMINFO, VORBIS_COMMENT, CUESHEET, and
  87513. * PICTURE blocks.
  87514. *
  87515. * Level 1:
  87516. * Read-write access to all metadata blocks. This level is write-
  87517. * efficient in most cases (more on this below), and uses less memory
  87518. * than level 2.
  87519. *
  87520. * Level 2:
  87521. * Read-write access to all metadata blocks. This level is write-
  87522. * efficient in all cases, but uses more memory since all metadata for
  87523. * the whole file is read into memory and manipulated before writing
  87524. * out again.
  87525. *
  87526. * What do we mean by efficient? Since FLAC metadata appears at the
  87527. * beginning of the file, when writing metadata back to a FLAC file
  87528. * it is possible to grow or shrink the metadata such that the entire
  87529. * file must be rewritten. However, if the size remains the same during
  87530. * changes or PADDING blocks are utilized, only the metadata needs to be
  87531. * overwritten, which is much faster.
  87532. *
  87533. * Efficient means the whole file is rewritten at most one time, and only
  87534. * when necessary. Level 1 is not efficient only in the case that you
  87535. * cause more than one metadata block to grow or shrink beyond what can
  87536. * be accomodated by padding. In this case you should probably use level
  87537. * 2, which allows you to edit all the metadata for a file in memory and
  87538. * write it out all at once.
  87539. *
  87540. * All levels know how to skip over and not disturb an ID3v2 tag at the
  87541. * front of the file.
  87542. *
  87543. * All levels access files via their filenames. In addition, level 2
  87544. * has additional alternative read and write functions that take an I/O
  87545. * handle and callbacks, for situations where access by filename is not
  87546. * possible.
  87547. *
  87548. * In addition to the three interfaces, this module defines functions for
  87549. * creating and manipulating various metadata objects in memory. As we see
  87550. * from the Format module, FLAC metadata blocks in memory are very primitive
  87551. * structures for storing information in an efficient way. Reading
  87552. * information from the structures is easy but creating or modifying them
  87553. * directly is more complex. The metadata object routines here facilitate
  87554. * this by taking care of the consistency and memory management drudgery.
  87555. *
  87556. * Unless you will be using the level 1 or 2 interfaces to modify existing
  87557. * metadata however, you will not probably not need these.
  87558. *
  87559. * From a dependency standpoint, none of the encoders or decoders require
  87560. * the metadata module. This is so that embedded users can strip out the
  87561. * metadata module from libFLAC to reduce the size and complexity.
  87562. */
  87563. #ifdef __cplusplus
  87564. extern "C" {
  87565. #endif
  87566. /** \defgroup flac_metadata_level0 FLAC/metadata.h: metadata level 0 interface
  87567. * \ingroup flac_metadata
  87568. *
  87569. * \brief
  87570. * The level 0 interface consists of individual routines to read the
  87571. * STREAMINFO, VORBIS_COMMENT, CUESHEET, and PICTURE blocks, requiring
  87572. * only a filename.
  87573. *
  87574. * They try to skip any ID3v2 tag at the head of the file.
  87575. *
  87576. * \{
  87577. */
  87578. /** Read the STREAMINFO metadata block of the given FLAC file. This function
  87579. * will try to skip any ID3v2 tag at the head of the file.
  87580. *
  87581. * \param filename The path to the FLAC file to read.
  87582. * \param streaminfo A pointer to space for the STREAMINFO block. Since
  87583. * FLAC__StreamMetadata is a simple structure with no
  87584. * memory allocation involved, you pass the address of
  87585. * an existing structure. It need not be initialized.
  87586. * \assert
  87587. * \code filename != NULL \endcode
  87588. * \code streaminfo != NULL \endcode
  87589. * \retval FLAC__bool
  87590. * \c true if a valid STREAMINFO block was read from \a filename. Returns
  87591. * \c false if there was a memory allocation error, a file decoder error,
  87592. * or the file contained no STREAMINFO block. (A memory allocation error
  87593. * is possible because this function must set up a file decoder.)
  87594. */
  87595. FLAC_API FLAC__bool FLAC__metadata_get_streaminfo(const char *filename, FLAC__StreamMetadata *streaminfo);
  87596. /** Read the VORBIS_COMMENT metadata block of the given FLAC file. This
  87597. * function will try to skip any ID3v2 tag at the head of the file.
  87598. *
  87599. * \param filename The path to the FLAC file to read.
  87600. * \param tags The address where the returned pointer will be
  87601. * stored. The \a tags object must be deleted by
  87602. * the caller using FLAC__metadata_object_delete().
  87603. * \assert
  87604. * \code filename != NULL \endcode
  87605. * \code tags != NULL \endcode
  87606. * \retval FLAC__bool
  87607. * \c true if a valid VORBIS_COMMENT block was read from \a filename,
  87608. * and \a *tags will be set to the address of the metadata structure.
  87609. * Returns \c false if there was a memory allocation error, a file
  87610. * decoder error, or the file contained no VORBIS_COMMENT block, and
  87611. * \a *tags will be set to \c NULL.
  87612. */
  87613. FLAC_API FLAC__bool FLAC__metadata_get_tags(const char *filename, FLAC__StreamMetadata **tags);
  87614. /** Read the CUESHEET metadata block of the given FLAC file. This
  87615. * function will try to skip any ID3v2 tag at the head of the file.
  87616. *
  87617. * \param filename The path to the FLAC file to read.
  87618. * \param cuesheet The address where the returned pointer will be
  87619. * stored. The \a cuesheet object must be deleted by
  87620. * the caller using FLAC__metadata_object_delete().
  87621. * \assert
  87622. * \code filename != NULL \endcode
  87623. * \code cuesheet != NULL \endcode
  87624. * \retval FLAC__bool
  87625. * \c true if a valid CUESHEET block was read from \a filename,
  87626. * and \a *cuesheet will be set to the address of the metadata
  87627. * structure. Returns \c false if there was a memory allocation
  87628. * error, a file decoder error, or the file contained no CUESHEET
  87629. * block, and \a *cuesheet will be set to \c NULL.
  87630. */
  87631. FLAC_API FLAC__bool FLAC__metadata_get_cuesheet(const char *filename, FLAC__StreamMetadata **cuesheet);
  87632. /** Read a PICTURE metadata block of the given FLAC file. This
  87633. * function will try to skip any ID3v2 tag at the head of the file.
  87634. * Since there can be more than one PICTURE block in a file, this
  87635. * function takes a number of parameters that act as constraints to
  87636. * the search. The PICTURE block with the largest area matching all
  87637. * the constraints will be returned, or \a *picture will be set to
  87638. * \c NULL if there was no such block.
  87639. *
  87640. * \param filename The path to the FLAC file to read.
  87641. * \param picture The address where the returned pointer will be
  87642. * stored. The \a picture object must be deleted by
  87643. * the caller using FLAC__metadata_object_delete().
  87644. * \param type The desired picture type. Use \c -1 to mean
  87645. * "any type".
  87646. * \param mime_type The desired MIME type, e.g. "image/jpeg". The
  87647. * string will be matched exactly. Use \c NULL to
  87648. * mean "any MIME type".
  87649. * \param description The desired description. The string will be
  87650. * matched exactly. Use \c NULL to mean "any
  87651. * description".
  87652. * \param max_width The maximum width in pixels desired. Use
  87653. * \c (unsigned)(-1) to mean "any width".
  87654. * \param max_height The maximum height in pixels desired. Use
  87655. * \c (unsigned)(-1) to mean "any height".
  87656. * \param max_depth The maximum color depth in bits-per-pixel desired.
  87657. * Use \c (unsigned)(-1) to mean "any depth".
  87658. * \param max_colors The maximum number of colors desired. Use
  87659. * \c (unsigned)(-1) to mean "any number of colors".
  87660. * \assert
  87661. * \code filename != NULL \endcode
  87662. * \code picture != NULL \endcode
  87663. * \retval FLAC__bool
  87664. * \c true if a valid PICTURE block was read from \a filename,
  87665. * and \a *picture will be set to the address of the metadata
  87666. * structure. Returns \c false if there was a memory allocation
  87667. * error, a file decoder error, or the file contained no PICTURE
  87668. * block, and \a *picture will be set to \c NULL.
  87669. */
  87670. 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);
  87671. /* \} */
  87672. /** \defgroup flac_metadata_level1 FLAC/metadata.h: metadata level 1 interface
  87673. * \ingroup flac_metadata
  87674. *
  87675. * \brief
  87676. * The level 1 interface provides read-write access to FLAC file metadata and
  87677. * operates directly on the FLAC file.
  87678. *
  87679. * The general usage of this interface is:
  87680. *
  87681. * - Create an iterator using FLAC__metadata_simple_iterator_new()
  87682. * - Attach it to a file using FLAC__metadata_simple_iterator_init() and check
  87683. * the exit code. Call FLAC__metadata_simple_iterator_is_writable() to
  87684. * see if the file is writable, or only read access is allowed.
  87685. * - Use FLAC__metadata_simple_iterator_next() and
  87686. * FLAC__metadata_simple_iterator_prev() to traverse the blocks.
  87687. * This is does not read the actual blocks themselves.
  87688. * FLAC__metadata_simple_iterator_next() is relatively fast.
  87689. * FLAC__metadata_simple_iterator_prev() is slower since it needs to search
  87690. * forward from the front of the file.
  87691. * - Use FLAC__metadata_simple_iterator_get_block_type() or
  87692. * FLAC__metadata_simple_iterator_get_block() to access the actual data at
  87693. * the current iterator position. The returned object is yours to modify
  87694. * and free.
  87695. * - Use FLAC__metadata_simple_iterator_set_block() to write a modified block
  87696. * back. You must have write permission to the original file. Make sure to
  87697. * read the whole comment to FLAC__metadata_simple_iterator_set_block()
  87698. * below.
  87699. * - Use FLAC__metadata_simple_iterator_insert_block_after() to add new blocks.
  87700. * Use the object creation functions from
  87701. * \link flac_metadata_object here \endlink to generate new objects.
  87702. * - Use FLAC__metadata_simple_iterator_delete_block() to remove the block
  87703. * currently referred to by the iterator, or replace it with padding.
  87704. * - Destroy the iterator with FLAC__metadata_simple_iterator_delete() when
  87705. * finished.
  87706. *
  87707. * \note
  87708. * The FLAC file remains open the whole time between
  87709. * FLAC__metadata_simple_iterator_init() and
  87710. * FLAC__metadata_simple_iterator_delete(), so make sure you are not altering
  87711. * the file during this time.
  87712. *
  87713. * \note
  87714. * Do not modify the \a is_last, \a length, or \a type fields of returned
  87715. * FLAC__StreamMetadata objects. These are managed automatically.
  87716. *
  87717. * \note
  87718. * If any of the modification functions
  87719. * (FLAC__metadata_simple_iterator_set_block(),
  87720. * FLAC__metadata_simple_iterator_delete_block(),
  87721. * FLAC__metadata_simple_iterator_insert_block_after(), etc.) return \c false,
  87722. * you should delete the iterator as it may no longer be valid.
  87723. *
  87724. * \{
  87725. */
  87726. struct FLAC__Metadata_SimpleIterator;
  87727. /** The opaque structure definition for the level 1 iterator type.
  87728. * See the
  87729. * \link flac_metadata_level1 metadata level 1 module \endlink
  87730. * for a detailed description.
  87731. */
  87732. typedef struct FLAC__Metadata_SimpleIterator FLAC__Metadata_SimpleIterator;
  87733. /** Status type for FLAC__Metadata_SimpleIterator.
  87734. *
  87735. * The iterator's current status can be obtained by calling FLAC__metadata_simple_iterator_status().
  87736. */
  87737. typedef enum {
  87738. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK = 0,
  87739. /**< The iterator is in the normal OK state */
  87740. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT,
  87741. /**< The data passed into a function violated the function's usage criteria */
  87742. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE,
  87743. /**< The iterator could not open the target file */
  87744. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_A_FLAC_FILE,
  87745. /**< The iterator could not find the FLAC signature at the start of the file */
  87746. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_WRITABLE,
  87747. /**< The iterator tried to write to a file that was not writable */
  87748. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_BAD_METADATA,
  87749. /**< The iterator encountered input that does not conform to the FLAC metadata specification */
  87750. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR,
  87751. /**< The iterator encountered an error while reading the FLAC file */
  87752. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR,
  87753. /**< The iterator encountered an error while seeking in the FLAC file */
  87754. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR,
  87755. /**< The iterator encountered an error while writing the FLAC file */
  87756. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_RENAME_ERROR,
  87757. /**< The iterator encountered an error renaming the FLAC file */
  87758. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_UNLINK_ERROR,
  87759. /**< The iterator encountered an error removing the temporary file */
  87760. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR,
  87761. /**< Memory allocation failed */
  87762. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_INTERNAL_ERROR
  87763. /**< The caller violated an assertion or an unexpected error occurred */
  87764. } FLAC__Metadata_SimpleIteratorStatus;
  87765. /** Maps a FLAC__Metadata_SimpleIteratorStatus to a C string.
  87766. *
  87767. * Using a FLAC__Metadata_SimpleIteratorStatus as the index to this array
  87768. * will give the string equivalent. The contents should not be modified.
  87769. */
  87770. extern FLAC_API const char * const FLAC__Metadata_SimpleIteratorStatusString[];
  87771. /** Create a new iterator instance.
  87772. *
  87773. * \retval FLAC__Metadata_SimpleIterator*
  87774. * \c NULL if there was an error allocating memory, else the new instance.
  87775. */
  87776. FLAC_API FLAC__Metadata_SimpleIterator *FLAC__metadata_simple_iterator_new(void);
  87777. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  87778. *
  87779. * \param iterator A pointer to an existing iterator.
  87780. * \assert
  87781. * \code iterator != NULL \endcode
  87782. */
  87783. FLAC_API void FLAC__metadata_simple_iterator_delete(FLAC__Metadata_SimpleIterator *iterator);
  87784. /** Get the current status of the iterator. Call this after a function
  87785. * returns \c false to get the reason for the error. Also resets the status
  87786. * to FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK.
  87787. *
  87788. * \param iterator A pointer to an existing iterator.
  87789. * \assert
  87790. * \code iterator != NULL \endcode
  87791. * \retval FLAC__Metadata_SimpleIteratorStatus
  87792. * The current status of the iterator.
  87793. */
  87794. FLAC_API FLAC__Metadata_SimpleIteratorStatus FLAC__metadata_simple_iterator_status(FLAC__Metadata_SimpleIterator *iterator);
  87795. /** Initialize the iterator to point to the first metadata block in the
  87796. * given FLAC file.
  87797. *
  87798. * \param iterator A pointer to an existing iterator.
  87799. * \param filename The path to the FLAC file.
  87800. * \param read_only If \c true, the FLAC file will be opened
  87801. * in read-only mode; if \c false, the FLAC
  87802. * file will be opened for edit even if no
  87803. * edits are performed.
  87804. * \param preserve_file_stats If \c true, the owner and modification
  87805. * time will be preserved even if the FLAC
  87806. * file is written to.
  87807. * \assert
  87808. * \code iterator != NULL \endcode
  87809. * \code filename != NULL \endcode
  87810. * \retval FLAC__bool
  87811. * \c false if a memory allocation error occurs, the file can't be
  87812. * opened, or another error occurs, else \c true.
  87813. */
  87814. 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);
  87815. /** Returns \c true if the FLAC file is writable. If \c false, calls to
  87816. * FLAC__metadata_simple_iterator_set_block() and
  87817. * FLAC__metadata_simple_iterator_insert_block_after() will fail.
  87818. *
  87819. * \param iterator A pointer to an existing iterator.
  87820. * \assert
  87821. * \code iterator != NULL \endcode
  87822. * \retval FLAC__bool
  87823. * See above.
  87824. */
  87825. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_writable(const FLAC__Metadata_SimpleIterator *iterator);
  87826. /** Moves the iterator forward one metadata block, returning \c false if
  87827. * already at the end.
  87828. *
  87829. * \param iterator A pointer to an existing initialized iterator.
  87830. * \assert
  87831. * \code iterator != NULL \endcode
  87832. * \a iterator has been successfully initialized with
  87833. * FLAC__metadata_simple_iterator_init()
  87834. * \retval FLAC__bool
  87835. * \c false if already at the last metadata block of the chain, else
  87836. * \c true.
  87837. */
  87838. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_next(FLAC__Metadata_SimpleIterator *iterator);
  87839. /** Moves the iterator backward one metadata block, returning \c false if
  87840. * already at the beginning.
  87841. *
  87842. * \param iterator A pointer to an existing initialized iterator.
  87843. * \assert
  87844. * \code iterator != NULL \endcode
  87845. * \a iterator has been successfully initialized with
  87846. * FLAC__metadata_simple_iterator_init()
  87847. * \retval FLAC__bool
  87848. * \c false if already at the first metadata block of the chain, else
  87849. * \c true.
  87850. */
  87851. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_prev(FLAC__Metadata_SimpleIterator *iterator);
  87852. /** Returns a flag telling if the current metadata block is the last.
  87853. *
  87854. * \param iterator A pointer to an existing initialized iterator.
  87855. * \assert
  87856. * \code iterator != NULL \endcode
  87857. * \a iterator has been successfully initialized with
  87858. * FLAC__metadata_simple_iterator_init()
  87859. * \retval FLAC__bool
  87860. * \c true if the current metadata block is the last in the file,
  87861. * else \c false.
  87862. */
  87863. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_last(const FLAC__Metadata_SimpleIterator *iterator);
  87864. /** Get the offset of the metadata block at the current position. This
  87865. * avoids reading the actual block data which can save time for large
  87866. * blocks.
  87867. *
  87868. * \param iterator A pointer to an existing initialized iterator.
  87869. * \assert
  87870. * \code iterator != NULL \endcode
  87871. * \a iterator has been successfully initialized with
  87872. * FLAC__metadata_simple_iterator_init()
  87873. * \retval off_t
  87874. * The offset of the metadata block at the current iterator position.
  87875. * This is the byte offset relative to the beginning of the file of
  87876. * the current metadata block's header.
  87877. */
  87878. FLAC_API off_t FLAC__metadata_simple_iterator_get_block_offset(const FLAC__Metadata_SimpleIterator *iterator);
  87879. /** Get the type of the metadata block at the current position. This
  87880. * avoids reading the actual block data which can save time for large
  87881. * blocks.
  87882. *
  87883. * \param iterator A pointer to an existing initialized iterator.
  87884. * \assert
  87885. * \code iterator != NULL \endcode
  87886. * \a iterator has been successfully initialized with
  87887. * FLAC__metadata_simple_iterator_init()
  87888. * \retval FLAC__MetadataType
  87889. * The type of the metadata block at the current iterator position.
  87890. */
  87891. FLAC_API FLAC__MetadataType FLAC__metadata_simple_iterator_get_block_type(const FLAC__Metadata_SimpleIterator *iterator);
  87892. /** Get the length of the metadata block at the current position. This
  87893. * avoids reading the actual block data which can save time for large
  87894. * blocks.
  87895. *
  87896. * \param iterator A pointer to an existing initialized iterator.
  87897. * \assert
  87898. * \code iterator != NULL \endcode
  87899. * \a iterator has been successfully initialized with
  87900. * FLAC__metadata_simple_iterator_init()
  87901. * \retval unsigned
  87902. * The length of the metadata block at the current iterator position.
  87903. * The is same length as that in the
  87904. * <a href="http://flac.sourceforge.net/format.html#metadata_block_header">metadata block header</a>,
  87905. * i.e. the length of the metadata body that follows the header.
  87906. */
  87907. FLAC_API unsigned FLAC__metadata_simple_iterator_get_block_length(const FLAC__Metadata_SimpleIterator *iterator);
  87908. /** Get the application ID of the \c APPLICATION block at the current
  87909. * position. This avoids reading the actual block data which can save
  87910. * time for large blocks.
  87911. *
  87912. * \param iterator A pointer to an existing initialized iterator.
  87913. * \param id A pointer to a buffer of at least \c 4 bytes where
  87914. * the ID will be stored.
  87915. * \assert
  87916. * \code iterator != NULL \endcode
  87917. * \code id != NULL \endcode
  87918. * \a iterator has been successfully initialized with
  87919. * FLAC__metadata_simple_iterator_init()
  87920. * \retval FLAC__bool
  87921. * \c true if the ID was successfully read, else \c false, in which
  87922. * case you should check FLAC__metadata_simple_iterator_status() to
  87923. * find out why. If the status is
  87924. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT, then the
  87925. * current metadata block is not an \c APPLICATION block. Otherwise
  87926. * if the status is
  87927. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR or
  87928. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR, an I/O error
  87929. * occurred and the iterator can no longer be used.
  87930. */
  87931. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_get_application_id(FLAC__Metadata_SimpleIterator *iterator, FLAC__byte *id);
  87932. /** Get the metadata block at the current position. You can modify the
  87933. * block but must use FLAC__metadata_simple_iterator_set_block() to
  87934. * write it back to the FLAC file.
  87935. *
  87936. * You must call FLAC__metadata_object_delete() on the returned object
  87937. * when you are finished with it.
  87938. *
  87939. * \param iterator A pointer to an existing initialized iterator.
  87940. * \assert
  87941. * \code iterator != NULL \endcode
  87942. * \a iterator has been successfully initialized with
  87943. * FLAC__metadata_simple_iterator_init()
  87944. * \retval FLAC__StreamMetadata*
  87945. * The current metadata block, or \c NULL if there was a memory
  87946. * allocation error.
  87947. */
  87948. FLAC_API FLAC__StreamMetadata *FLAC__metadata_simple_iterator_get_block(FLAC__Metadata_SimpleIterator *iterator);
  87949. /** Write a block back to the FLAC file. This function tries to be
  87950. * as efficient as possible; how the block is actually written is
  87951. * shown by the following:
  87952. *
  87953. * Existing block is a STREAMINFO block and the new block is a
  87954. * STREAMINFO block: the new block is written in place. Make sure
  87955. * you know what you're doing when changing the values of a
  87956. * STREAMINFO block.
  87957. *
  87958. * Existing block is a STREAMINFO block and the new block is a
  87959. * not a STREAMINFO block: this is an error since the first block
  87960. * must be a STREAMINFO block. Returns \c false without altering the
  87961. * file.
  87962. *
  87963. * Existing block is not a STREAMINFO block and the new block is a
  87964. * STREAMINFO block: this is an error since there may be only one
  87965. * STREAMINFO block. Returns \c false without altering the file.
  87966. *
  87967. * Existing block and new block are the same length: the existing
  87968. * block will be replaced by the new block, written in place.
  87969. *
  87970. * Existing block is longer than new block: if use_padding is \c true,
  87971. * the existing block will be overwritten in place with the new
  87972. * block followed by a PADDING block, if possible, to make the total
  87973. * size the same as the existing block. Remember that a padding
  87974. * block requires at least four bytes so if the difference in size
  87975. * between the new block and existing block is less than that, the
  87976. * entire file will have to be rewritten, using the new block's
  87977. * exact size. If use_padding is \c false, the entire file will be
  87978. * rewritten, replacing the existing block by the new block.
  87979. *
  87980. * Existing block is shorter than new block: if use_padding is \c true,
  87981. * the function will try and expand the new block into the following
  87982. * PADDING block, if it exists and doing so won't shrink the PADDING
  87983. * block to less than 4 bytes. If there is no following PADDING
  87984. * block, or it will shrink to less than 4 bytes, or use_padding is
  87985. * \c false, the entire file is rewritten, replacing the existing block
  87986. * with the new block. Note that in this case any following PADDING
  87987. * block is preserved as is.
  87988. *
  87989. * After writing the block, the iterator will remain in the same
  87990. * place, i.e. pointing to the new block.
  87991. *
  87992. * \param iterator A pointer to an existing initialized iterator.
  87993. * \param block The block to set.
  87994. * \param use_padding See above.
  87995. * \assert
  87996. * \code iterator != NULL \endcode
  87997. * \a iterator has been successfully initialized with
  87998. * FLAC__metadata_simple_iterator_init()
  87999. * \code block != NULL \endcode
  88000. * \retval FLAC__bool
  88001. * \c true if successful, else \c false.
  88002. */
  88003. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_set_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  88004. /** This is similar to FLAC__metadata_simple_iterator_set_block()
  88005. * except that instead of writing over an existing block, it appends
  88006. * a block after the existing block. \a use_padding is again used to
  88007. * tell the function to try an expand into following padding in an
  88008. * attempt to avoid rewriting the entire file.
  88009. *
  88010. * This function will fail and return \c false if given a STREAMINFO
  88011. * block.
  88012. *
  88013. * After writing the block, the iterator will be pointing to the
  88014. * new block.
  88015. *
  88016. * \param iterator A pointer to an existing initialized iterator.
  88017. * \param block The block to set.
  88018. * \param use_padding See above.
  88019. * \assert
  88020. * \code iterator != NULL \endcode
  88021. * \a iterator has been successfully initialized with
  88022. * FLAC__metadata_simple_iterator_init()
  88023. * \code block != NULL \endcode
  88024. * \retval FLAC__bool
  88025. * \c true if successful, else \c false.
  88026. */
  88027. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_insert_block_after(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  88028. /** Deletes the block at the current position. This will cause the
  88029. * entire FLAC file to be rewritten, unless \a use_padding is \c true,
  88030. * in which case the block will be replaced by an equal-sized PADDING
  88031. * block. The iterator will be left pointing to the block before the
  88032. * one just deleted.
  88033. *
  88034. * You may not delete the STREAMINFO block.
  88035. *
  88036. * \param iterator A pointer to an existing initialized iterator.
  88037. * \param use_padding See above.
  88038. * \assert
  88039. * \code iterator != NULL \endcode
  88040. * \a iterator has been successfully initialized with
  88041. * FLAC__metadata_simple_iterator_init()
  88042. * \retval FLAC__bool
  88043. * \c true if successful, else \c false.
  88044. */
  88045. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_delete_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__bool use_padding);
  88046. /* \} */
  88047. /** \defgroup flac_metadata_level2 FLAC/metadata.h: metadata level 2 interface
  88048. * \ingroup flac_metadata
  88049. *
  88050. * \brief
  88051. * The level 2 interface provides read-write access to FLAC file metadata;
  88052. * all metadata is read into memory, operated on in memory, and then written
  88053. * to file, which is more efficient than level 1 when editing multiple blocks.
  88054. *
  88055. * Currently Ogg FLAC is supported for read only, via
  88056. * FLAC__metadata_chain_read_ogg() but a subsequent
  88057. * FLAC__metadata_chain_write() will fail.
  88058. *
  88059. * The general usage of this interface is:
  88060. *
  88061. * - Create a new chain using FLAC__metadata_chain_new(). A chain is a
  88062. * linked list of FLAC metadata blocks.
  88063. * - Read all metadata into the the chain from a FLAC file using
  88064. * FLAC__metadata_chain_read() or FLAC__metadata_chain_read_ogg() and
  88065. * check the status.
  88066. * - Optionally, consolidate the padding using
  88067. * FLAC__metadata_chain_merge_padding() or
  88068. * FLAC__metadata_chain_sort_padding().
  88069. * - Create a new iterator using FLAC__metadata_iterator_new()
  88070. * - Initialize the iterator to point to the first element in the chain
  88071. * using FLAC__metadata_iterator_init()
  88072. * - Traverse the chain using FLAC__metadata_iterator_next and
  88073. * FLAC__metadata_iterator_prev().
  88074. * - Get a block for reading or modification using
  88075. * FLAC__metadata_iterator_get_block(). The pointer to the object
  88076. * inside the chain is returned, so the block is yours to modify.
  88077. * Changes will be reflected in the FLAC file when you write the
  88078. * chain. You can also add and delete blocks (see functions below).
  88079. * - When done, write out the chain using FLAC__metadata_chain_write().
  88080. * Make sure to read the whole comment to the function below.
  88081. * - Delete the chain using FLAC__metadata_chain_delete().
  88082. *
  88083. * \note
  88084. * Even though the FLAC file is not open while the chain is being
  88085. * manipulated, you must not alter the file externally during
  88086. * this time. The chain assumes the FLAC file will not change
  88087. * between the time of FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg()
  88088. * and FLAC__metadata_chain_write().
  88089. *
  88090. * \note
  88091. * Do not modify the is_last, length, or type fields of returned
  88092. * FLAC__StreamMetadata objects. These are managed automatically.
  88093. *
  88094. * \note
  88095. * The metadata objects returned by FLAC__metadata_iterator_get_block()
  88096. * are owned by the chain; do not FLAC__metadata_object_delete() them.
  88097. * In the same way, blocks passed to FLAC__metadata_iterator_set_block()
  88098. * become owned by the chain and they will be deleted when the chain is
  88099. * deleted.
  88100. *
  88101. * \{
  88102. */
  88103. struct FLAC__Metadata_Chain;
  88104. /** The opaque structure definition for the level 2 chain type.
  88105. */
  88106. typedef struct FLAC__Metadata_Chain FLAC__Metadata_Chain;
  88107. struct FLAC__Metadata_Iterator;
  88108. /** The opaque structure definition for the level 2 iterator type.
  88109. */
  88110. typedef struct FLAC__Metadata_Iterator FLAC__Metadata_Iterator;
  88111. typedef enum {
  88112. FLAC__METADATA_CHAIN_STATUS_OK = 0,
  88113. /**< The chain is in the normal OK state */
  88114. FLAC__METADATA_CHAIN_STATUS_ILLEGAL_INPUT,
  88115. /**< The data passed into a function violated the function's usage criteria */
  88116. FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE,
  88117. /**< The chain could not open the target file */
  88118. FLAC__METADATA_CHAIN_STATUS_NOT_A_FLAC_FILE,
  88119. /**< The chain could not find the FLAC signature at the start of the file */
  88120. FLAC__METADATA_CHAIN_STATUS_NOT_WRITABLE,
  88121. /**< The chain tried to write to a file that was not writable */
  88122. FLAC__METADATA_CHAIN_STATUS_BAD_METADATA,
  88123. /**< The chain encountered input that does not conform to the FLAC metadata specification */
  88124. FLAC__METADATA_CHAIN_STATUS_READ_ERROR,
  88125. /**< The chain encountered an error while reading the FLAC file */
  88126. FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR,
  88127. /**< The chain encountered an error while seeking in the FLAC file */
  88128. FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR,
  88129. /**< The chain encountered an error while writing the FLAC file */
  88130. FLAC__METADATA_CHAIN_STATUS_RENAME_ERROR,
  88131. /**< The chain encountered an error renaming the FLAC file */
  88132. FLAC__METADATA_CHAIN_STATUS_UNLINK_ERROR,
  88133. /**< The chain encountered an error removing the temporary file */
  88134. FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR,
  88135. /**< Memory allocation failed */
  88136. FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR,
  88137. /**< The caller violated an assertion or an unexpected error occurred */
  88138. FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS,
  88139. /**< One or more of the required callbacks was NULL */
  88140. FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH,
  88141. /**< FLAC__metadata_chain_write() was called on a chain read by
  88142. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  88143. * or
  88144. * FLAC__metadata_chain_write_with_callbacks()/FLAC__metadata_chain_write_with_callbacks_and_tempfile()
  88145. * was called on a chain read by
  88146. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  88147. * Matching read/write methods must always be used. */
  88148. FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL
  88149. /**< FLAC__metadata_chain_write_with_callbacks() was called when the
  88150. * chain write requires a tempfile; use
  88151. * FLAC__metadata_chain_write_with_callbacks_and_tempfile() instead.
  88152. * Or, FLAC__metadata_chain_write_with_callbacks_and_tempfile() was
  88153. * called when the chain write does not require a tempfile; use
  88154. * FLAC__metadata_chain_write_with_callbacks() instead.
  88155. * Always check FLAC__metadata_chain_check_if_tempfile_needed()
  88156. * before writing via callbacks. */
  88157. } FLAC__Metadata_ChainStatus;
  88158. /** Maps a FLAC__Metadata_ChainStatus to a C string.
  88159. *
  88160. * Using a FLAC__Metadata_ChainStatus as the index to this array
  88161. * will give the string equivalent. The contents should not be modified.
  88162. */
  88163. extern FLAC_API const char * const FLAC__Metadata_ChainStatusString[];
  88164. /*********** FLAC__Metadata_Chain ***********/
  88165. /** Create a new chain instance.
  88166. *
  88167. * \retval FLAC__Metadata_Chain*
  88168. * \c NULL if there was an error allocating memory, else the new instance.
  88169. */
  88170. FLAC_API FLAC__Metadata_Chain *FLAC__metadata_chain_new(void);
  88171. /** Free a chain instance. Deletes the object pointed to by \a chain.
  88172. *
  88173. * \param chain A pointer to an existing chain.
  88174. * \assert
  88175. * \code chain != NULL \endcode
  88176. */
  88177. FLAC_API void FLAC__metadata_chain_delete(FLAC__Metadata_Chain *chain);
  88178. /** Get the current status of the chain. Call this after a function
  88179. * returns \c false to get the reason for the error. Also resets the
  88180. * status to FLAC__METADATA_CHAIN_STATUS_OK.
  88181. *
  88182. * \param chain A pointer to an existing chain.
  88183. * \assert
  88184. * \code chain != NULL \endcode
  88185. * \retval FLAC__Metadata_ChainStatus
  88186. * The current status of the chain.
  88187. */
  88188. FLAC_API FLAC__Metadata_ChainStatus FLAC__metadata_chain_status(FLAC__Metadata_Chain *chain);
  88189. /** Read all metadata from a FLAC file into the chain.
  88190. *
  88191. * \param chain A pointer to an existing chain.
  88192. * \param filename The path to the FLAC file to read.
  88193. * \assert
  88194. * \code chain != NULL \endcode
  88195. * \code filename != NULL \endcode
  88196. * \retval FLAC__bool
  88197. * \c true if a valid list of metadata blocks was read from
  88198. * \a filename, else \c false. On failure, check the status with
  88199. * FLAC__metadata_chain_status().
  88200. */
  88201. FLAC_API FLAC__bool FLAC__metadata_chain_read(FLAC__Metadata_Chain *chain, const char *filename);
  88202. /** Read all metadata from an Ogg FLAC file into the chain.
  88203. *
  88204. * \note Ogg FLAC metadata data writing is not supported yet and
  88205. * FLAC__metadata_chain_write() will fail.
  88206. *
  88207. * \param chain A pointer to an existing chain.
  88208. * \param filename The path to the Ogg FLAC file to read.
  88209. * \assert
  88210. * \code chain != NULL \endcode
  88211. * \code filename != NULL \endcode
  88212. * \retval FLAC__bool
  88213. * \c true if a valid list of metadata blocks was read from
  88214. * \a filename, else \c false. On failure, check the status with
  88215. * FLAC__metadata_chain_status().
  88216. */
  88217. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg(FLAC__Metadata_Chain *chain, const char *filename);
  88218. /** Read all metadata from a FLAC stream into the chain via I/O callbacks.
  88219. *
  88220. * The \a handle need only be open for reading, but must be seekable.
  88221. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  88222. * for Windows).
  88223. *
  88224. * \param chain A pointer to an existing chain.
  88225. * \param handle The I/O handle of the FLAC stream to read. The
  88226. * handle will NOT be closed after the metadata is read;
  88227. * that is the duty of the caller.
  88228. * \param callbacks
  88229. * A set of callbacks to use for I/O. The mandatory
  88230. * callbacks are \a read, \a seek, and \a tell.
  88231. * \assert
  88232. * \code chain != NULL \endcode
  88233. * \retval FLAC__bool
  88234. * \c true if a valid list of metadata blocks was read from
  88235. * \a handle, else \c false. On failure, check the status with
  88236. * FLAC__metadata_chain_status().
  88237. */
  88238. FLAC_API FLAC__bool FLAC__metadata_chain_read_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  88239. /** Read all metadata from an Ogg FLAC stream into the chain via I/O callbacks.
  88240. *
  88241. * The \a handle need only be open for reading, but must be seekable.
  88242. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  88243. * for Windows).
  88244. *
  88245. * \note Ogg FLAC metadata data writing is not supported yet and
  88246. * FLAC__metadata_chain_write() will fail.
  88247. *
  88248. * \param chain A pointer to an existing chain.
  88249. * \param handle The I/O handle of the Ogg FLAC stream to read. The
  88250. * handle will NOT be closed after the metadata is read;
  88251. * that is the duty of the caller.
  88252. * \param callbacks
  88253. * A set of callbacks to use for I/O. The mandatory
  88254. * callbacks are \a read, \a seek, and \a tell.
  88255. * \assert
  88256. * \code chain != NULL \endcode
  88257. * \retval FLAC__bool
  88258. * \c true if a valid list of metadata blocks was read from
  88259. * \a handle, else \c false. On failure, check the status with
  88260. * FLAC__metadata_chain_status().
  88261. */
  88262. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  88263. /** Checks if writing the given chain would require the use of a
  88264. * temporary file, or if it could be written in place.
  88265. *
  88266. * Under certain conditions, padding can be utilized so that writing
  88267. * edited metadata back to the FLAC file does not require rewriting the
  88268. * entire file. If rewriting is required, then a temporary workfile is
  88269. * required. When writing metadata using callbacks, you must check
  88270. * this function to know whether to call
  88271. * FLAC__metadata_chain_write_with_callbacks() or
  88272. * FLAC__metadata_chain_write_with_callbacks_and_tempfile(). When
  88273. * writing with FLAC__metadata_chain_write(), the temporary file is
  88274. * handled internally.
  88275. *
  88276. * \param chain A pointer to an existing chain.
  88277. * \param use_padding
  88278. * Whether or not padding will be allowed to be used
  88279. * during the write. The value of \a use_padding given
  88280. * here must match the value later passed to
  88281. * FLAC__metadata_chain_write_with_callbacks() or
  88282. * FLAC__metadata_chain_write_with_callbacks_with_tempfile().
  88283. * \assert
  88284. * \code chain != NULL \endcode
  88285. * \retval FLAC__bool
  88286. * \c true if writing the current chain would require a tempfile, or
  88287. * \c false if metadata can be written in place.
  88288. */
  88289. FLAC_API FLAC__bool FLAC__metadata_chain_check_if_tempfile_needed(FLAC__Metadata_Chain *chain, FLAC__bool use_padding);
  88290. /** Write all metadata out to the FLAC file. This function tries to be as
  88291. * efficient as possible; how the metadata is actually written is shown by
  88292. * the following:
  88293. *
  88294. * If the current chain is the same size as the existing metadata, the new
  88295. * data is written in place.
  88296. *
  88297. * If the current chain is longer than the existing metadata, and
  88298. * \a use_padding is \c true, and the last block is a PADDING block of
  88299. * sufficient length, the function will truncate the final padding block
  88300. * so that the overall size of the metadata is the same as the existing
  88301. * metadata, and then just rewrite the metadata. Otherwise, if not all of
  88302. * the above conditions are met, the entire FLAC file must be rewritten.
  88303. * If you want to use padding this way it is a good idea to call
  88304. * FLAC__metadata_chain_sort_padding() first so that you have the maximum
  88305. * amount of padding to work with, unless you need to preserve ordering
  88306. * of the PADDING blocks for some reason.
  88307. *
  88308. * If the current chain is shorter than the existing metadata, and
  88309. * \a use_padding is \c true, and the final block is a PADDING block, the padding
  88310. * is extended to make the overall size the same as the existing data. If
  88311. * \a use_padding is \c true and the last block is not a PADDING block, a new
  88312. * PADDING block is added to the end of the new data to make it the same
  88313. * size as the existing data (if possible, see the note to
  88314. * FLAC__metadata_simple_iterator_set_block() about the four byte limit)
  88315. * and the new data is written in place. If none of the above apply or
  88316. * \a use_padding is \c false, the entire FLAC file is rewritten.
  88317. *
  88318. * If \a preserve_file_stats is \c true, the owner and modification time will
  88319. * be preserved even if the FLAC file is written.
  88320. *
  88321. * For this write function to be used, the chain must have been read with
  88322. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg(), not
  88323. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks().
  88324. *
  88325. * \param chain A pointer to an existing chain.
  88326. * \param use_padding See above.
  88327. * \param preserve_file_stats See above.
  88328. * \assert
  88329. * \code chain != NULL \endcode
  88330. * \retval FLAC__bool
  88331. * \c true if the write succeeded, else \c false. On failure,
  88332. * check the status with FLAC__metadata_chain_status().
  88333. */
  88334. FLAC_API FLAC__bool FLAC__metadata_chain_write(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__bool preserve_file_stats);
  88335. /** Write all metadata out to a FLAC stream via callbacks.
  88336. *
  88337. * (See FLAC__metadata_chain_write() for the details on how padding is
  88338. * used to write metadata in place if possible.)
  88339. *
  88340. * The \a handle must be open for updating and be seekable. The
  88341. * equivalent minimum stdio fopen() file mode is \c "r+" (or \c "r+b"
  88342. * for Windows).
  88343. *
  88344. * For this write function to be used, the chain must have been read with
  88345. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  88346. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  88347. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  88348. * \c false.
  88349. *
  88350. * \param chain A pointer to an existing chain.
  88351. * \param use_padding See FLAC__metadata_chain_write()
  88352. * \param handle The I/O handle of the FLAC stream to write. The
  88353. * handle will NOT be closed after the metadata is
  88354. * written; that is the duty of the caller.
  88355. * \param callbacks A set of callbacks to use for I/O. The mandatory
  88356. * callbacks are \a write and \a seek.
  88357. * \assert
  88358. * \code chain != NULL \endcode
  88359. * \retval FLAC__bool
  88360. * \c true if the write succeeded, else \c false. On failure,
  88361. * check the status with FLAC__metadata_chain_status().
  88362. */
  88363. FLAC_API FLAC__bool FLAC__metadata_chain_write_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  88364. /** Write all metadata out to a FLAC stream via callbacks.
  88365. *
  88366. * (See FLAC__metadata_chain_write() for the details on how padding is
  88367. * used to write metadata in place if possible.)
  88368. *
  88369. * This version of the write-with-callbacks function must be used when
  88370. * FLAC__metadata_chain_check_if_tempfile_needed() returns true. In
  88371. * this function, you must supply an I/O handle corresponding to the
  88372. * FLAC file to edit, and a temporary handle to which the new FLAC
  88373. * file will be written. It is the caller's job to move this temporary
  88374. * FLAC file on top of the original FLAC file to complete the metadata
  88375. * edit.
  88376. *
  88377. * The \a handle must be open for reading and be seekable. The
  88378. * equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  88379. * for Windows).
  88380. *
  88381. * The \a temp_handle must be open for writing. The
  88382. * equivalent minimum stdio fopen() file mode is \c "w" (or \c "wb"
  88383. * for Windows). It should be an empty stream, or at least positioned
  88384. * at the start-of-file (in which case it is the caller's duty to
  88385. * truncate it on return).
  88386. *
  88387. * For this write function to be used, the chain must have been read with
  88388. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  88389. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  88390. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  88391. * \c true.
  88392. *
  88393. * \param chain A pointer to an existing chain.
  88394. * \param use_padding See FLAC__metadata_chain_write()
  88395. * \param handle The I/O handle of the original FLAC stream to read.
  88396. * The handle will NOT be closed after the metadata is
  88397. * written; that is the duty of the caller.
  88398. * \param callbacks A set of callbacks to use for I/O on \a handle.
  88399. * The mandatory callbacks are \a read, \a seek, and
  88400. * \a eof.
  88401. * \param temp_handle The I/O handle of the FLAC stream to write. The
  88402. * handle will NOT be closed after the metadata is
  88403. * written; that is the duty of the caller.
  88404. * \param temp_callbacks
  88405. * A set of callbacks to use for I/O on temp_handle.
  88406. * The only mandatory callback is \a write.
  88407. * \assert
  88408. * \code chain != NULL \endcode
  88409. * \retval FLAC__bool
  88410. * \c true if the write succeeded, else \c false. On failure,
  88411. * check the status with FLAC__metadata_chain_status().
  88412. */
  88413. 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);
  88414. /** Merge adjacent PADDING blocks into a single block.
  88415. *
  88416. * \note This function does not write to the FLAC file, it only
  88417. * modifies the chain.
  88418. *
  88419. * \warning Any iterator on the current chain will become invalid after this
  88420. * call. You should delete the iterator and get a new one.
  88421. *
  88422. * \param chain A pointer to an existing chain.
  88423. * \assert
  88424. * \code chain != NULL \endcode
  88425. */
  88426. FLAC_API void FLAC__metadata_chain_merge_padding(FLAC__Metadata_Chain *chain);
  88427. /** This function will move all PADDING blocks to the end on the metadata,
  88428. * then merge them into a single block.
  88429. *
  88430. * \note This function does not write to the FLAC file, it only
  88431. * modifies the chain.
  88432. *
  88433. * \warning Any iterator on the current chain will become invalid after this
  88434. * call. You should delete the iterator and get a new one.
  88435. *
  88436. * \param chain A pointer to an existing chain.
  88437. * \assert
  88438. * \code chain != NULL \endcode
  88439. */
  88440. FLAC_API void FLAC__metadata_chain_sort_padding(FLAC__Metadata_Chain *chain);
  88441. /*********** FLAC__Metadata_Iterator ***********/
  88442. /** Create a new iterator instance.
  88443. *
  88444. * \retval FLAC__Metadata_Iterator*
  88445. * \c NULL if there was an error allocating memory, else the new instance.
  88446. */
  88447. FLAC_API FLAC__Metadata_Iterator *FLAC__metadata_iterator_new(void);
  88448. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  88449. *
  88450. * \param iterator A pointer to an existing iterator.
  88451. * \assert
  88452. * \code iterator != NULL \endcode
  88453. */
  88454. FLAC_API void FLAC__metadata_iterator_delete(FLAC__Metadata_Iterator *iterator);
  88455. /** Initialize the iterator to point to the first metadata block in the
  88456. * given chain.
  88457. *
  88458. * \param iterator A pointer to an existing iterator.
  88459. * \param chain A pointer to an existing and initialized (read) chain.
  88460. * \assert
  88461. * \code iterator != NULL \endcode
  88462. * \code chain != NULL \endcode
  88463. */
  88464. FLAC_API void FLAC__metadata_iterator_init(FLAC__Metadata_Iterator *iterator, FLAC__Metadata_Chain *chain);
  88465. /** Moves the iterator forward one metadata block, returning \c false if
  88466. * already at the end.
  88467. *
  88468. * \param iterator A pointer to an existing initialized iterator.
  88469. * \assert
  88470. * \code iterator != NULL \endcode
  88471. * \a iterator has been successfully initialized with
  88472. * FLAC__metadata_iterator_init()
  88473. * \retval FLAC__bool
  88474. * \c false if already at the last metadata block of the chain, else
  88475. * \c true.
  88476. */
  88477. FLAC_API FLAC__bool FLAC__metadata_iterator_next(FLAC__Metadata_Iterator *iterator);
  88478. /** Moves the iterator backward one metadata block, returning \c false if
  88479. * already at the beginning.
  88480. *
  88481. * \param iterator A pointer to an existing initialized iterator.
  88482. * \assert
  88483. * \code iterator != NULL \endcode
  88484. * \a iterator has been successfully initialized with
  88485. * FLAC__metadata_iterator_init()
  88486. * \retval FLAC__bool
  88487. * \c false if already at the first metadata block of the chain, else
  88488. * \c true.
  88489. */
  88490. FLAC_API FLAC__bool FLAC__metadata_iterator_prev(FLAC__Metadata_Iterator *iterator);
  88491. /** Get the type of the metadata block at the current position.
  88492. *
  88493. * \param iterator A pointer to an existing initialized iterator.
  88494. * \assert
  88495. * \code iterator != NULL \endcode
  88496. * \a iterator has been successfully initialized with
  88497. * FLAC__metadata_iterator_init()
  88498. * \retval FLAC__MetadataType
  88499. * The type of the metadata block at the current iterator position.
  88500. */
  88501. FLAC_API FLAC__MetadataType FLAC__metadata_iterator_get_block_type(const FLAC__Metadata_Iterator *iterator);
  88502. /** Get the metadata block at the current position. You can modify
  88503. * the block in place but must write the chain before the changes
  88504. * are reflected to the FLAC file. You do not need to call
  88505. * FLAC__metadata_iterator_set_block() to reflect the changes;
  88506. * the pointer returned by FLAC__metadata_iterator_get_block()
  88507. * points directly into the chain.
  88508. *
  88509. * \warning
  88510. * Do not call FLAC__metadata_object_delete() on the returned object;
  88511. * to delete a block use FLAC__metadata_iterator_delete_block().
  88512. *
  88513. * \param iterator A pointer to an existing initialized iterator.
  88514. * \assert
  88515. * \code iterator != NULL \endcode
  88516. * \a iterator has been successfully initialized with
  88517. * FLAC__metadata_iterator_init()
  88518. * \retval FLAC__StreamMetadata*
  88519. * The current metadata block.
  88520. */
  88521. FLAC_API FLAC__StreamMetadata *FLAC__metadata_iterator_get_block(FLAC__Metadata_Iterator *iterator);
  88522. /** Set the metadata block at the current position, replacing the existing
  88523. * block. The new block passed in becomes owned by the chain and it will be
  88524. * deleted when the chain is deleted.
  88525. *
  88526. * \param iterator A pointer to an existing initialized iterator.
  88527. * \param block A pointer to a metadata block.
  88528. * \assert
  88529. * \code iterator != NULL \endcode
  88530. * \a iterator has been successfully initialized with
  88531. * FLAC__metadata_iterator_init()
  88532. * \code block != NULL \endcode
  88533. * \retval FLAC__bool
  88534. * \c false if the conditions in the above description are not met, or
  88535. * a memory allocation error occurs, otherwise \c true.
  88536. */
  88537. FLAC_API FLAC__bool FLAC__metadata_iterator_set_block(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  88538. /** Removes the current block from the chain. If \a replace_with_padding is
  88539. * \c true, the block will instead be replaced with a padding block of equal
  88540. * size. You can not delete the STREAMINFO block. The iterator will be
  88541. * left pointing to the block before the one just "deleted", even if
  88542. * \a replace_with_padding is \c true.
  88543. *
  88544. * \param iterator A pointer to an existing initialized iterator.
  88545. * \param replace_with_padding See above.
  88546. * \assert
  88547. * \code iterator != NULL \endcode
  88548. * \a iterator has been successfully initialized with
  88549. * FLAC__metadata_iterator_init()
  88550. * \retval FLAC__bool
  88551. * \c false if the conditions in the above description are not met,
  88552. * otherwise \c true.
  88553. */
  88554. FLAC_API FLAC__bool FLAC__metadata_iterator_delete_block(FLAC__Metadata_Iterator *iterator, FLAC__bool replace_with_padding);
  88555. /** Insert a new block before the current block. You cannot insert a block
  88556. * before the first STREAMINFO block. You cannot insert a STREAMINFO block
  88557. * as there can be only one, the one that already exists at the head when you
  88558. * read in a chain. The chain takes ownership of the new block and it will be
  88559. * deleted when the chain is deleted. The iterator will be left pointing to
  88560. * the new block.
  88561. *
  88562. * \param iterator A pointer to an existing initialized iterator.
  88563. * \param block A pointer to a metadata block to insert.
  88564. * \assert
  88565. * \code iterator != NULL \endcode
  88566. * \a iterator has been successfully initialized with
  88567. * FLAC__metadata_iterator_init()
  88568. * \retval FLAC__bool
  88569. * \c false if the conditions in the above description are not met, or
  88570. * a memory allocation error occurs, otherwise \c true.
  88571. */
  88572. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_before(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  88573. /** Insert a new block after the current block. You cannot insert a STREAMINFO
  88574. * block as there can be only one, the one that already exists at the head when
  88575. * you read in a chain. The chain takes ownership of the new block and it will
  88576. * be deleted when the chain is deleted. The iterator will be left pointing to
  88577. * the new block.
  88578. *
  88579. * \param iterator A pointer to an existing initialized iterator.
  88580. * \param block A pointer to a metadata block to insert.
  88581. * \assert
  88582. * \code iterator != NULL \endcode
  88583. * \a iterator has been successfully initialized with
  88584. * FLAC__metadata_iterator_init()
  88585. * \retval FLAC__bool
  88586. * \c false if the conditions in the above description are not met, or
  88587. * a memory allocation error occurs, otherwise \c true.
  88588. */
  88589. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_after(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  88590. /* \} */
  88591. /** \defgroup flac_metadata_object FLAC/metadata.h: metadata object methods
  88592. * \ingroup flac_metadata
  88593. *
  88594. * \brief
  88595. * This module contains methods for manipulating FLAC metadata objects.
  88596. *
  88597. * Since many are variable length we have to be careful about the memory
  88598. * management. We decree that all pointers to data in the object are
  88599. * owned by the object and memory-managed by the object.
  88600. *
  88601. * Use the FLAC__metadata_object_new() and FLAC__metadata_object_delete()
  88602. * functions to create all instances. When using the
  88603. * FLAC__metadata_object_set_*() functions to set pointers to data, set
  88604. * \a copy to \c true to have the function make it's own copy of the data, or
  88605. * to \c false to give the object ownership of your data. In the latter case
  88606. * your pointer must be freeable by free() and will be free()d when the object
  88607. * is FLAC__metadata_object_delete()d. It is legal to pass a null pointer as
  88608. * the data pointer to a FLAC__metadata_object_set_*() function as long as
  88609. * the length argument is 0 and the \a copy argument is \c false.
  88610. *
  88611. * The FLAC__metadata_object_new() and FLAC__metadata_object_clone() function
  88612. * will return \c NULL in the case of a memory allocation error, otherwise a new
  88613. * object. The FLAC__metadata_object_set_*() functions return \c false in the
  88614. * case of a memory allocation error.
  88615. *
  88616. * We don't have the convenience of C++ here, so note that the library relies
  88617. * on you to keep the types straight. In other words, if you pass, for
  88618. * example, a FLAC__StreamMetadata* that represents a STREAMINFO block to
  88619. * FLAC__metadata_object_application_set_data(), you will get an assertion
  88620. * failure.
  88621. *
  88622. * For convenience the FLAC__metadata_object_vorbiscomment_*() functions
  88623. * maintain a trailing NUL on each Vorbis comment entry. This is not counted
  88624. * toward the length or stored in the stream, but it can make working with plain
  88625. * comments (those that don't contain embedded-NULs in the value) easier.
  88626. * Entries passed into these functions have trailing NULs added if missing, and
  88627. * returned entries are guaranteed to have a trailing NUL.
  88628. *
  88629. * The FLAC__metadata_object_vorbiscomment_*() functions that take a Vorbis
  88630. * comment entry/name/value will first validate that it complies with the Vorbis
  88631. * comment specification and return false if it does not.
  88632. *
  88633. * There is no need to recalculate the length field on metadata blocks you
  88634. * have modified. They will be calculated automatically before they are
  88635. * written back to a file.
  88636. *
  88637. * \{
  88638. */
  88639. /** Create a new metadata object instance of the given type.
  88640. *
  88641. * The object will be "empty"; i.e. values and data pointers will be \c 0,
  88642. * with the exception of FLAC__METADATA_TYPE_VORBIS_COMMENT, which will have
  88643. * the vendor string set (but zero comments).
  88644. *
  88645. * Do not pass in a value greater than or equal to
  88646. * \a FLAC__METADATA_TYPE_UNDEFINED unless you really know what you're
  88647. * doing.
  88648. *
  88649. * \param type Type of object to create
  88650. * \retval FLAC__StreamMetadata*
  88651. * \c NULL if there was an error allocating memory or the type code is
  88652. * greater than FLAC__MAX_METADATA_TYPE_CODE, else the new instance.
  88653. */
  88654. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_new(FLAC__MetadataType type);
  88655. /** Create a copy of an existing metadata object.
  88656. *
  88657. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  88658. * object is also copied. The caller takes ownership of the new block and
  88659. * is responsible for freeing it with FLAC__metadata_object_delete().
  88660. *
  88661. * \param object Pointer to object to copy.
  88662. * \assert
  88663. * \code object != NULL \endcode
  88664. * \retval FLAC__StreamMetadata*
  88665. * \c NULL if there was an error allocating memory, else the new instance.
  88666. */
  88667. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_clone(const FLAC__StreamMetadata *object);
  88668. /** Free a metadata object. Deletes the object pointed to by \a object.
  88669. *
  88670. * The delete is a "deep" delete, i.e. dynamically allocated data within the
  88671. * object is also deleted.
  88672. *
  88673. * \param object A pointer to an existing object.
  88674. * \assert
  88675. * \code object != NULL \endcode
  88676. */
  88677. FLAC_API void FLAC__metadata_object_delete(FLAC__StreamMetadata *object);
  88678. /** Compares two metadata objects.
  88679. *
  88680. * The compare is "deep", i.e. dynamically allocated data within the
  88681. * object is also compared.
  88682. *
  88683. * \param block1 A pointer to an existing object.
  88684. * \param block2 A pointer to an existing object.
  88685. * \assert
  88686. * \code block1 != NULL \endcode
  88687. * \code block2 != NULL \endcode
  88688. * \retval FLAC__bool
  88689. * \c true if objects are identical, else \c false.
  88690. */
  88691. FLAC_API FLAC__bool FLAC__metadata_object_is_equal(const FLAC__StreamMetadata *block1, const FLAC__StreamMetadata *block2);
  88692. /** Sets the application data of an APPLICATION block.
  88693. *
  88694. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  88695. * takes ownership of the pointer. The existing data will be freed if this
  88696. * function is successful, otherwise the original data will remain if \a copy
  88697. * is \c true and malloc() fails.
  88698. *
  88699. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  88700. *
  88701. * \param object A pointer to an existing APPLICATION object.
  88702. * \param data A pointer to the data to set.
  88703. * \param length The length of \a data in bytes.
  88704. * \param copy See above.
  88705. * \assert
  88706. * \code object != NULL \endcode
  88707. * \code object->type == FLAC__METADATA_TYPE_APPLICATION \endcode
  88708. * \code (data != NULL && length > 0) ||
  88709. * (data == NULL && length == 0 && copy == false) \endcode
  88710. * \retval FLAC__bool
  88711. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88712. */
  88713. FLAC_API FLAC__bool FLAC__metadata_object_application_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, unsigned length, FLAC__bool copy);
  88714. /** Resize the seekpoint array.
  88715. *
  88716. * If the size shrinks, elements will truncated; if it grows, new placeholder
  88717. * points will be added to the end.
  88718. *
  88719. * \param object A pointer to an existing SEEKTABLE object.
  88720. * \param new_num_points The desired length of the array; may be \c 0.
  88721. * \assert
  88722. * \code object != NULL \endcode
  88723. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88724. * \code (object->data.seek_table.points == NULL && object->data.seek_table.num_points == 0) ||
  88725. * (object->data.seek_table.points != NULL && object->data.seek_table.num_points > 0) \endcode
  88726. * \retval FLAC__bool
  88727. * \c false if memory allocation error, else \c true.
  88728. */
  88729. FLAC_API FLAC__bool FLAC__metadata_object_seektable_resize_points(FLAC__StreamMetadata *object, unsigned new_num_points);
  88730. /** Set a seekpoint in a seektable.
  88731. *
  88732. * \param object A pointer to an existing SEEKTABLE object.
  88733. * \param point_num Index into seekpoint array to set.
  88734. * \param point The point to set.
  88735. * \assert
  88736. * \code object != NULL \endcode
  88737. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88738. * \code object->data.seek_table.num_points > point_num \endcode
  88739. */
  88740. FLAC_API void FLAC__metadata_object_seektable_set_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  88741. /** Insert a seekpoint into a seektable.
  88742. *
  88743. * \param object A pointer to an existing SEEKTABLE object.
  88744. * \param point_num Index into seekpoint array to set.
  88745. * \param point The point to set.
  88746. * \assert
  88747. * \code object != NULL \endcode
  88748. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88749. * \code object->data.seek_table.num_points >= point_num \endcode
  88750. * \retval FLAC__bool
  88751. * \c false if memory allocation error, else \c true.
  88752. */
  88753. FLAC_API FLAC__bool FLAC__metadata_object_seektable_insert_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  88754. /** Delete a seekpoint from a seektable.
  88755. *
  88756. * \param object A pointer to an existing SEEKTABLE object.
  88757. * \param point_num Index into seekpoint array to set.
  88758. * \assert
  88759. * \code object != NULL \endcode
  88760. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88761. * \code object->data.seek_table.num_points > point_num \endcode
  88762. * \retval FLAC__bool
  88763. * \c false if memory allocation error, else \c true.
  88764. */
  88765. FLAC_API FLAC__bool FLAC__metadata_object_seektable_delete_point(FLAC__StreamMetadata *object, unsigned point_num);
  88766. /** Check a seektable to see if it conforms to the FLAC specification.
  88767. * See the format specification for limits on the contents of the
  88768. * seektable.
  88769. *
  88770. * \param object A pointer to an existing SEEKTABLE object.
  88771. * \assert
  88772. * \code object != NULL \endcode
  88773. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88774. * \retval FLAC__bool
  88775. * \c false if seek table is illegal, else \c true.
  88776. */
  88777. FLAC_API FLAC__bool FLAC__metadata_object_seektable_is_legal(const FLAC__StreamMetadata *object);
  88778. /** Append a number of placeholder points to the end of a seek table.
  88779. *
  88780. * \note
  88781. * As with the other ..._seektable_template_... functions, you should
  88782. * call FLAC__metadata_object_seektable_template_sort() when finished
  88783. * to make the seek table legal.
  88784. *
  88785. * \param object A pointer to an existing SEEKTABLE object.
  88786. * \param num The number of placeholder points to append.
  88787. * \assert
  88788. * \code object != NULL \endcode
  88789. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88790. * \retval FLAC__bool
  88791. * \c false if memory allocation fails, else \c true.
  88792. */
  88793. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_placeholders(FLAC__StreamMetadata *object, unsigned num);
  88794. /** Append a specific seek point template to the end of a seek table.
  88795. *
  88796. * \note
  88797. * As with the other ..._seektable_template_... functions, you should
  88798. * call FLAC__metadata_object_seektable_template_sort() when finished
  88799. * to make the seek table legal.
  88800. *
  88801. * \param object A pointer to an existing SEEKTABLE object.
  88802. * \param sample_number The sample number of the seek point template.
  88803. * \assert
  88804. * \code object != NULL \endcode
  88805. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88806. * \retval FLAC__bool
  88807. * \c false if memory allocation fails, else \c true.
  88808. */
  88809. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_point(FLAC__StreamMetadata *object, FLAC__uint64 sample_number);
  88810. /** Append specific seek point templates to the end of a seek table.
  88811. *
  88812. * \note
  88813. * As with the other ..._seektable_template_... functions, you should
  88814. * call FLAC__metadata_object_seektable_template_sort() when finished
  88815. * to make the seek table legal.
  88816. *
  88817. * \param object A pointer to an existing SEEKTABLE object.
  88818. * \param sample_numbers An array of sample numbers for the seek points.
  88819. * \param num The number of seek point templates to append.
  88820. * \assert
  88821. * \code object != NULL \endcode
  88822. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88823. * \retval FLAC__bool
  88824. * \c false if memory allocation fails, else \c true.
  88825. */
  88826. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_points(FLAC__StreamMetadata *object, FLAC__uint64 sample_numbers[], unsigned num);
  88827. /** Append a set of evenly-spaced seek point templates to the end of a
  88828. * seek table.
  88829. *
  88830. * \note
  88831. * As with the other ..._seektable_template_... functions, you should
  88832. * call FLAC__metadata_object_seektable_template_sort() when finished
  88833. * to make the seek table legal.
  88834. *
  88835. * \param object A pointer to an existing SEEKTABLE object.
  88836. * \param num The number of placeholder points to append.
  88837. * \param total_samples The total number of samples to be encoded;
  88838. * the seekpoints will be spaced approximately
  88839. * \a total_samples / \a num samples apart.
  88840. * \assert
  88841. * \code object != NULL \endcode
  88842. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88843. * \code total_samples > 0 \endcode
  88844. * \retval FLAC__bool
  88845. * \c false if memory allocation fails, else \c true.
  88846. */
  88847. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points(FLAC__StreamMetadata *object, unsigned num, FLAC__uint64 total_samples);
  88848. /** Append a set of evenly-spaced seek point templates to the end of a
  88849. * seek table.
  88850. *
  88851. * \note
  88852. * As with the other ..._seektable_template_... functions, you should
  88853. * call FLAC__metadata_object_seektable_template_sort() when finished
  88854. * to make the seek table legal.
  88855. *
  88856. * \param object A pointer to an existing SEEKTABLE object.
  88857. * \param samples The number of samples apart to space the placeholder
  88858. * points. The first point will be at sample \c 0, the
  88859. * second at sample \a samples, then 2*\a samples, and
  88860. * so on. As long as \a samples and \a total_samples
  88861. * are greater than \c 0, there will always be at least
  88862. * one seekpoint at sample \c 0.
  88863. * \param total_samples The total number of samples to be encoded;
  88864. * the seekpoints will be spaced
  88865. * \a samples samples apart.
  88866. * \assert
  88867. * \code object != NULL \endcode
  88868. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88869. * \code samples > 0 \endcode
  88870. * \code total_samples > 0 \endcode
  88871. * \retval FLAC__bool
  88872. * \c false if memory allocation fails, else \c true.
  88873. */
  88874. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points_by_samples(FLAC__StreamMetadata *object, unsigned samples, FLAC__uint64 total_samples);
  88875. /** Sort a seek table's seek points according to the format specification,
  88876. * removing duplicates.
  88877. *
  88878. * \param object A pointer to a seek table to be sorted.
  88879. * \param compact If \c false, behaves like FLAC__format_seektable_sort().
  88880. * If \c true, duplicates are deleted and the seek table is
  88881. * shrunk appropriately; the number of placeholder points
  88882. * present in the seek table will be the same after the call
  88883. * as before.
  88884. * \assert
  88885. * \code object != NULL \endcode
  88886. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88887. * \retval FLAC__bool
  88888. * \c false if realloc() fails, else \c true.
  88889. */
  88890. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_sort(FLAC__StreamMetadata *object, FLAC__bool compact);
  88891. /** Sets the vendor string in a VORBIS_COMMENT block.
  88892. *
  88893. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88894. * one already.
  88895. *
  88896. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88897. * takes ownership of the \c entry.entry pointer.
  88898. *
  88899. * \note If this function returns \c false, the caller still owns the
  88900. * pointer.
  88901. *
  88902. * \param object A pointer to an existing VORBIS_COMMENT object.
  88903. * \param entry The entry to set the vendor string to.
  88904. * \param copy See above.
  88905. * \assert
  88906. * \code object != NULL \endcode
  88907. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88908. * \code (entry.entry != NULL && entry.length > 0) ||
  88909. * (entry.entry == NULL && entry.length == 0) \endcode
  88910. * \retval FLAC__bool
  88911. * \c false if memory allocation fails or \a entry does not comply with the
  88912. * Vorbis comment specification, else \c true.
  88913. */
  88914. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_vendor_string(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88915. /** Resize the comment array.
  88916. *
  88917. * If the size shrinks, elements will truncated; if it grows, new empty
  88918. * fields will be added to the end.
  88919. *
  88920. * \param object A pointer to an existing VORBIS_COMMENT object.
  88921. * \param new_num_comments The desired length of the array; may be \c 0.
  88922. * \assert
  88923. * \code object != NULL \endcode
  88924. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88925. * \code (object->data.vorbis_comment.comments == NULL && object->data.vorbis_comment.num_comments == 0) ||
  88926. * (object->data.vorbis_comment.comments != NULL && object->data.vorbis_comment.num_comments > 0) \endcode
  88927. * \retval FLAC__bool
  88928. * \c false if memory allocation fails, else \c true.
  88929. */
  88930. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_resize_comments(FLAC__StreamMetadata *object, unsigned new_num_comments);
  88931. /** Sets a comment in a VORBIS_COMMENT block.
  88932. *
  88933. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88934. * one already.
  88935. *
  88936. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88937. * takes ownership of the \c entry.entry pointer.
  88938. *
  88939. * \note If this function returns \c false, the caller still owns the
  88940. * pointer.
  88941. *
  88942. * \param object A pointer to an existing VORBIS_COMMENT object.
  88943. * \param comment_num Index into comment array to set.
  88944. * \param entry The entry to set the comment to.
  88945. * \param copy See above.
  88946. * \assert
  88947. * \code object != NULL \endcode
  88948. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88949. * \code comment_num < object->data.vorbis_comment.num_comments \endcode
  88950. * \code (entry.entry != NULL && entry.length > 0) ||
  88951. * (entry.entry == NULL && entry.length == 0) \endcode
  88952. * \retval FLAC__bool
  88953. * \c false if memory allocation fails or \a entry does not comply with the
  88954. * Vorbis comment specification, else \c true.
  88955. */
  88956. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88957. /** Insert a comment in a VORBIS_COMMENT block at the given index.
  88958. *
  88959. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88960. * one already.
  88961. *
  88962. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88963. * takes ownership of the \c entry.entry pointer.
  88964. *
  88965. * \note If this function returns \c false, the caller still owns the
  88966. * pointer.
  88967. *
  88968. * \param object A pointer to an existing VORBIS_COMMENT object.
  88969. * \param comment_num The index at which to insert the comment. The comments
  88970. * at and after \a comment_num move right one position.
  88971. * To append a comment to the end, set \a comment_num to
  88972. * \c object->data.vorbis_comment.num_comments .
  88973. * \param entry The comment to insert.
  88974. * \param copy See above.
  88975. * \assert
  88976. * \code object != NULL \endcode
  88977. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88978. * \code object->data.vorbis_comment.num_comments >= comment_num \endcode
  88979. * \code (entry.entry != NULL && entry.length > 0) ||
  88980. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  88981. * \retval FLAC__bool
  88982. * \c false if memory allocation fails or \a entry does not comply with the
  88983. * Vorbis comment specification, else \c true.
  88984. */
  88985. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_insert_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88986. /** Appends a comment to a VORBIS_COMMENT block.
  88987. *
  88988. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88989. * one already.
  88990. *
  88991. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88992. * takes ownership of the \c entry.entry pointer.
  88993. *
  88994. * \note If this function returns \c false, the caller still owns the
  88995. * pointer.
  88996. *
  88997. * \param object A pointer to an existing VORBIS_COMMENT object.
  88998. * \param entry The comment to insert.
  88999. * \param copy See above.
  89000. * \assert
  89001. * \code object != NULL \endcode
  89002. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89003. * \code (entry.entry != NULL && entry.length > 0) ||
  89004. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  89005. * \retval FLAC__bool
  89006. * \c false if memory allocation fails or \a entry does not comply with the
  89007. * Vorbis comment specification, else \c true.
  89008. */
  89009. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_append_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  89010. /** Replaces comments in a VORBIS_COMMENT block with a new one.
  89011. *
  89012. * For convenience, a trailing NUL is added to the entry if it doesn't have
  89013. * one already.
  89014. *
  89015. * Depending on the the value of \a all, either all or just the first comment
  89016. * whose field name(s) match the given entry's name will be replaced by the
  89017. * given entry. If no comments match, \a entry will simply be appended.
  89018. *
  89019. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  89020. * takes ownership of the \c entry.entry pointer.
  89021. *
  89022. * \note If this function returns \c false, the caller still owns the
  89023. * pointer.
  89024. *
  89025. * \param object A pointer to an existing VORBIS_COMMENT object.
  89026. * \param entry The comment to insert.
  89027. * \param all If \c true, all comments whose field name matches
  89028. * \a entry's field name will be removed, and \a entry will
  89029. * be inserted at the position of the first matching
  89030. * comment. If \c false, only the first comment whose
  89031. * field name matches \a entry's field name will be
  89032. * replaced with \a entry.
  89033. * \param copy See above.
  89034. * \assert
  89035. * \code object != NULL \endcode
  89036. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89037. * \code (entry.entry != NULL && entry.length > 0) ||
  89038. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  89039. * \retval FLAC__bool
  89040. * \c false if memory allocation fails or \a entry does not comply with the
  89041. * Vorbis comment specification, else \c true.
  89042. */
  89043. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_replace_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool all, FLAC__bool copy);
  89044. /** Delete a comment in a VORBIS_COMMENT block at the given index.
  89045. *
  89046. * \param object A pointer to an existing VORBIS_COMMENT object.
  89047. * \param comment_num The index of the comment to delete.
  89048. * \assert
  89049. * \code object != NULL \endcode
  89050. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89051. * \code object->data.vorbis_comment.num_comments > comment_num \endcode
  89052. * \retval FLAC__bool
  89053. * \c false if realloc() fails, else \c true.
  89054. */
  89055. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_delete_comment(FLAC__StreamMetadata *object, unsigned comment_num);
  89056. /** Creates a Vorbis comment entry from NUL-terminated name and value strings.
  89057. *
  89058. * On return, the filled-in \a entry->entry pointer will point to malloc()ed
  89059. * memory and shall be owned by the caller. For convenience the entry will
  89060. * have a terminating NUL.
  89061. *
  89062. * \param entry A pointer to a Vorbis comment entry. The entry's
  89063. * \c entry pointer should not point to allocated
  89064. * memory as it will be overwritten.
  89065. * \param field_name The field name in ASCII, \c NUL terminated.
  89066. * \param field_value The field value in UTF-8, \c NUL terminated.
  89067. * \assert
  89068. * \code entry != NULL \endcode
  89069. * \code field_name != NULL \endcode
  89070. * \code field_value != NULL \endcode
  89071. * \retval FLAC__bool
  89072. * \c false if malloc() fails, or if \a field_name or \a field_value does
  89073. * not comply with the Vorbis comment specification, else \c true.
  89074. */
  89075. 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);
  89076. /** Splits a Vorbis comment entry into NUL-terminated name and value strings.
  89077. *
  89078. * The returned pointers to name and value will be allocated by malloc()
  89079. * and shall be owned by the caller.
  89080. *
  89081. * \param entry An existing Vorbis comment entry.
  89082. * \param field_name The address of where the returned pointer to the
  89083. * field name will be stored.
  89084. * \param field_value The address of where the returned pointer to the
  89085. * field value will be stored.
  89086. * \assert
  89087. * \code (entry.entry != NULL && entry.length > 0) \endcode
  89088. * \code memchr(entry.entry, '=', entry.length) != NULL \endcode
  89089. * \code field_name != NULL \endcode
  89090. * \code field_value != NULL \endcode
  89091. * \retval FLAC__bool
  89092. * \c false if memory allocation fails or \a entry does not comply with the
  89093. * Vorbis comment specification, else \c true.
  89094. */
  89095. 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);
  89096. /** Check if the given Vorbis comment entry's field name matches the given
  89097. * field name.
  89098. *
  89099. * \param entry An existing Vorbis comment entry.
  89100. * \param field_name The field name to check.
  89101. * \param field_name_length The length of \a field_name, not including the
  89102. * terminating \c NUL.
  89103. * \assert
  89104. * \code (entry.entry != NULL && entry.length > 0) \endcode
  89105. * \retval FLAC__bool
  89106. * \c true if the field names match, else \c false
  89107. */
  89108. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_matches(const FLAC__StreamMetadata_VorbisComment_Entry entry, const char *field_name, unsigned field_name_length);
  89109. /** Find a Vorbis comment with the given field name.
  89110. *
  89111. * The search begins at entry number \a offset; use an offset of 0 to
  89112. * search from the beginning of the comment array.
  89113. *
  89114. * \param object A pointer to an existing VORBIS_COMMENT object.
  89115. * \param offset The offset into the comment array from where to start
  89116. * the search.
  89117. * \param field_name The field name of the comment to find.
  89118. * \assert
  89119. * \code object != NULL \endcode
  89120. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89121. * \code field_name != NULL \endcode
  89122. * \retval int
  89123. * The offset in the comment array of the first comment whose field
  89124. * name matches \a field_name, or \c -1 if no match was found.
  89125. */
  89126. FLAC_API int FLAC__metadata_object_vorbiscomment_find_entry_from(const FLAC__StreamMetadata *object, unsigned offset, const char *field_name);
  89127. /** Remove first Vorbis comment matching the given field name.
  89128. *
  89129. * \param object A pointer to an existing VORBIS_COMMENT object.
  89130. * \param field_name The field name of comment to delete.
  89131. * \assert
  89132. * \code object != NULL \endcode
  89133. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89134. * \retval int
  89135. * \c -1 for memory allocation error, \c 0 for no matching entries,
  89136. * \c 1 for one matching entry deleted.
  89137. */
  89138. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entry_matching(FLAC__StreamMetadata *object, const char *field_name);
  89139. /** Remove all Vorbis comments matching the given field name.
  89140. *
  89141. * \param object A pointer to an existing VORBIS_COMMENT object.
  89142. * \param field_name The field name of comments to delete.
  89143. * \assert
  89144. * \code object != NULL \endcode
  89145. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89146. * \retval int
  89147. * \c -1 for memory allocation error, \c 0 for no matching entries,
  89148. * else the number of matching entries deleted.
  89149. */
  89150. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entries_matching(FLAC__StreamMetadata *object, const char *field_name);
  89151. /** Create a new CUESHEET track instance.
  89152. *
  89153. * The object will be "empty"; i.e. values and data pointers will be \c 0.
  89154. *
  89155. * \retval FLAC__StreamMetadata_CueSheet_Track*
  89156. * \c NULL if there was an error allocating memory, else the new instance.
  89157. */
  89158. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_new(void);
  89159. /** Create a copy of an existing CUESHEET track object.
  89160. *
  89161. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  89162. * object is also copied. The caller takes ownership of the new object and
  89163. * is responsible for freeing it with
  89164. * FLAC__metadata_object_cuesheet_track_delete().
  89165. *
  89166. * \param object Pointer to object to copy.
  89167. * \assert
  89168. * \code object != NULL \endcode
  89169. * \retval FLAC__StreamMetadata_CueSheet_Track*
  89170. * \c NULL if there was an error allocating memory, else the new instance.
  89171. */
  89172. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_clone(const FLAC__StreamMetadata_CueSheet_Track *object);
  89173. /** Delete a CUESHEET track object
  89174. *
  89175. * \param object A pointer to an existing CUESHEET track object.
  89176. * \assert
  89177. * \code object != NULL \endcode
  89178. */
  89179. FLAC_API void FLAC__metadata_object_cuesheet_track_delete(FLAC__StreamMetadata_CueSheet_Track *object);
  89180. /** Resize a track's index point array.
  89181. *
  89182. * If the size shrinks, elements will truncated; if it grows, new blank
  89183. * indices will be added to the end.
  89184. *
  89185. * \param object A pointer to an existing CUESHEET object.
  89186. * \param track_num The index of the track to modify. NOTE: this is not
  89187. * necessarily the same as the track's \a number field.
  89188. * \param new_num_indices The desired length of the array; may be \c 0.
  89189. * \assert
  89190. * \code object != NULL \endcode
  89191. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89192. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89193. * \code (object->data.cue_sheet.tracks[track_num].indices == NULL && object->data.cue_sheet.tracks[track_num].num_indices == 0) ||
  89194. * (object->data.cue_sheet.tracks[track_num].indices != NULL && object->data.cue_sheet.tracks[track_num].num_indices > 0) \endcode
  89195. * \retval FLAC__bool
  89196. * \c false if memory allocation error, else \c true.
  89197. */
  89198. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_resize_indices(FLAC__StreamMetadata *object, unsigned track_num, unsigned new_num_indices);
  89199. /** Insert an index point in a CUESHEET track at the given index.
  89200. *
  89201. * \param object A pointer to an existing CUESHEET object.
  89202. * \param track_num The index of the track to modify. NOTE: this is not
  89203. * necessarily the same as the track's \a number field.
  89204. * \param index_num The index into the track's index array at which to
  89205. * insert the index point. NOTE: this is not necessarily
  89206. * the same as the index point's \a number field. The
  89207. * indices at and after \a index_num move right one
  89208. * position. To append an index point to the end, set
  89209. * \a index_num to
  89210. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  89211. * \param index The index point to insert.
  89212. * \assert
  89213. * \code object != NULL \endcode
  89214. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89215. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89216. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  89217. * \retval FLAC__bool
  89218. * \c false if realloc() fails, else \c true.
  89219. */
  89220. 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);
  89221. /** Insert a blank index point in a CUESHEET track at the given index.
  89222. *
  89223. * A blank index point is one in which all field values are zero.
  89224. *
  89225. * \param object A pointer to an existing CUESHEET object.
  89226. * \param track_num The index of the track to modify. NOTE: this is not
  89227. * necessarily the same as the track's \a number field.
  89228. * \param index_num The index into the track's index array at which to
  89229. * insert the index point. NOTE: this is not necessarily
  89230. * the same as the index point's \a number field. The
  89231. * indices at and after \a index_num move right one
  89232. * position. To append an index point to the end, set
  89233. * \a index_num to
  89234. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  89235. * \assert
  89236. * \code object != NULL \endcode
  89237. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89238. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89239. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  89240. * \retval FLAC__bool
  89241. * \c false if realloc() fails, else \c true.
  89242. */
  89243. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_insert_blank_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  89244. /** Delete an index point in a CUESHEET track at the given index.
  89245. *
  89246. * \param object A pointer to an existing CUESHEET object.
  89247. * \param track_num The index into the track array of the track to
  89248. * modify. NOTE: this is not necessarily the same
  89249. * as the track's \a number field.
  89250. * \param index_num The index into the track's index array of the index
  89251. * to delete. NOTE: this is not necessarily the same
  89252. * as the index's \a number field.
  89253. * \assert
  89254. * \code object != NULL \endcode
  89255. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89256. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89257. * \code object->data.cue_sheet.tracks[track_num].num_indices > index_num \endcode
  89258. * \retval FLAC__bool
  89259. * \c false if realloc() fails, else \c true.
  89260. */
  89261. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_delete_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  89262. /** Resize the track array.
  89263. *
  89264. * If the size shrinks, elements will truncated; if it grows, new blank
  89265. * tracks will be added to the end.
  89266. *
  89267. * \param object A pointer to an existing CUESHEET object.
  89268. * \param new_num_tracks The desired length of the array; may be \c 0.
  89269. * \assert
  89270. * \code object != NULL \endcode
  89271. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89272. * \code (object->data.cue_sheet.tracks == NULL && object->data.cue_sheet.num_tracks == 0) ||
  89273. * (object->data.cue_sheet.tracks != NULL && object->data.cue_sheet.num_tracks > 0) \endcode
  89274. * \retval FLAC__bool
  89275. * \c false if memory allocation error, else \c true.
  89276. */
  89277. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_resize_tracks(FLAC__StreamMetadata *object, unsigned new_num_tracks);
  89278. /** Sets a track in a CUESHEET block.
  89279. *
  89280. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  89281. * takes ownership of the \a track pointer.
  89282. *
  89283. * \param object A pointer to an existing CUESHEET object.
  89284. * \param track_num Index into track array to set. NOTE: this is not
  89285. * necessarily the same as the track's \a number field.
  89286. * \param track The track to set the track to. You may safely pass in
  89287. * a const pointer if \a copy is \c true.
  89288. * \param copy See above.
  89289. * \assert
  89290. * \code object != NULL \endcode
  89291. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89292. * \code track_num < object->data.cue_sheet.num_tracks \endcode
  89293. * \code (track->indices != NULL && track->num_indices > 0) ||
  89294. * (track->indices == NULL && track->num_indices == 0)
  89295. * \retval FLAC__bool
  89296. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89297. */
  89298. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_set_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  89299. /** Insert a track in a CUESHEET block at the given index.
  89300. *
  89301. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  89302. * takes ownership of the \a track pointer.
  89303. *
  89304. * \param object A pointer to an existing CUESHEET object.
  89305. * \param track_num The index at which to insert the track. NOTE: this
  89306. * is not necessarily the same as the track's \a number
  89307. * field. The tracks at and after \a track_num move right
  89308. * one position. To append a track to the end, set
  89309. * \a track_num to \c object->data.cue_sheet.num_tracks .
  89310. * \param track The track to insert. You may safely pass in a const
  89311. * pointer if \a copy is \c true.
  89312. * \param copy See above.
  89313. * \assert
  89314. * \code object != NULL \endcode
  89315. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89316. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  89317. * \retval FLAC__bool
  89318. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89319. */
  89320. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  89321. /** Insert a blank track in a CUESHEET block at the given index.
  89322. *
  89323. * A blank track is one in which all field values are zero.
  89324. *
  89325. * \param object A pointer to an existing CUESHEET object.
  89326. * \param track_num The index at which to insert the track. NOTE: this
  89327. * is not necessarily the same as the track's \a number
  89328. * field. The tracks at and after \a track_num move right
  89329. * one position. To append a track to the end, set
  89330. * \a track_num to \c object->data.cue_sheet.num_tracks .
  89331. * \assert
  89332. * \code object != NULL \endcode
  89333. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89334. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  89335. * \retval FLAC__bool
  89336. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89337. */
  89338. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_blank_track(FLAC__StreamMetadata *object, unsigned track_num);
  89339. /** Delete a track in a CUESHEET block at the given index.
  89340. *
  89341. * \param object A pointer to an existing CUESHEET object.
  89342. * \param track_num The index into the track array of the track to
  89343. * delete. NOTE: this is not necessarily the same
  89344. * as the track's \a number field.
  89345. * \assert
  89346. * \code object != NULL \endcode
  89347. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89348. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89349. * \retval FLAC__bool
  89350. * \c false if realloc() fails, else \c true.
  89351. */
  89352. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_delete_track(FLAC__StreamMetadata *object, unsigned track_num);
  89353. /** Check a cue sheet to see if it conforms to the FLAC specification.
  89354. * See the format specification for limits on the contents of the
  89355. * cue sheet.
  89356. *
  89357. * \param object A pointer to an existing CUESHEET object.
  89358. * \param check_cd_da_subset If \c true, check CUESHEET against more
  89359. * stringent requirements for a CD-DA (audio) disc.
  89360. * \param violation Address of a pointer to a string. If there is a
  89361. * violation, a pointer to a string explanation of the
  89362. * violation will be returned here. \a violation may be
  89363. * \c NULL if you don't need the returned string. Do not
  89364. * free the returned string; it will always point to static
  89365. * data.
  89366. * \assert
  89367. * \code object != NULL \endcode
  89368. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89369. * \retval FLAC__bool
  89370. * \c false if cue sheet is illegal, else \c true.
  89371. */
  89372. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_is_legal(const FLAC__StreamMetadata *object, FLAC__bool check_cd_da_subset, const char **violation);
  89373. /** Calculate and return the CDDB/freedb ID for a cue sheet. The function
  89374. * assumes the cue sheet corresponds to a CD; the result is undefined
  89375. * if the cuesheet's is_cd bit is not set.
  89376. *
  89377. * \param object A pointer to an existing CUESHEET object.
  89378. * \assert
  89379. * \code object != NULL \endcode
  89380. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89381. * \retval FLAC__uint32
  89382. * The unsigned integer representation of the CDDB/freedb ID
  89383. */
  89384. FLAC_API FLAC__uint32 FLAC__metadata_object_cuesheet_calculate_cddb_id(const FLAC__StreamMetadata *object);
  89385. /** Sets the MIME type of a PICTURE block.
  89386. *
  89387. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  89388. * takes ownership of the pointer. The existing string will be freed if this
  89389. * function is successful, otherwise the original string will remain if \a copy
  89390. * is \c true and malloc() fails.
  89391. *
  89392. * \note It is safe to pass a const pointer to \a mime_type if \a copy is \c true.
  89393. *
  89394. * \param object A pointer to an existing PICTURE object.
  89395. * \param mime_type A pointer to the MIME type string. The string must be
  89396. * ASCII characters 0x20-0x7e, NUL-terminated. No validation
  89397. * is done.
  89398. * \param copy See above.
  89399. * \assert
  89400. * \code object != NULL \endcode
  89401. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89402. * \code (mime_type != NULL) \endcode
  89403. * \retval FLAC__bool
  89404. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89405. */
  89406. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_mime_type(FLAC__StreamMetadata *object, char *mime_type, FLAC__bool copy);
  89407. /** Sets the description of a PICTURE block.
  89408. *
  89409. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  89410. * takes ownership of the pointer. The existing string will be freed if this
  89411. * function is successful, otherwise the original string will remain if \a copy
  89412. * is \c true and malloc() fails.
  89413. *
  89414. * \note It is safe to pass a const pointer to \a description if \a copy is \c true.
  89415. *
  89416. * \param object A pointer to an existing PICTURE object.
  89417. * \param description A pointer to the description string. The string must be
  89418. * valid UTF-8, NUL-terminated. No validation is done.
  89419. * \param copy See above.
  89420. * \assert
  89421. * \code object != NULL \endcode
  89422. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89423. * \code (description != NULL) \endcode
  89424. * \retval FLAC__bool
  89425. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89426. */
  89427. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_description(FLAC__StreamMetadata *object, FLAC__byte *description, FLAC__bool copy);
  89428. /** Sets the picture data of a PICTURE block.
  89429. *
  89430. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  89431. * takes ownership of the pointer. Also sets the \a data_length field of the
  89432. * metadata object to what is passed in as the \a length parameter. The
  89433. * existing data will be freed if this function is successful, otherwise the
  89434. * original data and data_length will remain if \a copy is \c true and
  89435. * malloc() fails.
  89436. *
  89437. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  89438. *
  89439. * \param object A pointer to an existing PICTURE object.
  89440. * \param data A pointer to the data to set.
  89441. * \param length The length of \a data in bytes.
  89442. * \param copy See above.
  89443. * \assert
  89444. * \code object != NULL \endcode
  89445. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89446. * \code (data != NULL && length > 0) ||
  89447. * (data == NULL && length == 0 && copy == false) \endcode
  89448. * \retval FLAC__bool
  89449. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89450. */
  89451. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, FLAC__uint32 length, FLAC__bool copy);
  89452. /** Check a PICTURE block to see if it conforms to the FLAC specification.
  89453. * See the format specification for limits on the contents of the
  89454. * PICTURE block.
  89455. *
  89456. * \param object A pointer to existing PICTURE block to be checked.
  89457. * \param violation Address of a pointer to a string. If there is a
  89458. * violation, a pointer to a string explanation of the
  89459. * violation will be returned here. \a violation may be
  89460. * \c NULL if you don't need the returned string. Do not
  89461. * free the returned string; it will always point to static
  89462. * data.
  89463. * \assert
  89464. * \code object != NULL \endcode
  89465. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89466. * \retval FLAC__bool
  89467. * \c false if PICTURE block is illegal, else \c true.
  89468. */
  89469. FLAC_API FLAC__bool FLAC__metadata_object_picture_is_legal(const FLAC__StreamMetadata *object, const char **violation);
  89470. /* \} */
  89471. #ifdef __cplusplus
  89472. }
  89473. #endif
  89474. #endif
  89475. /*** End of inlined file: metadata.h ***/
  89476. /*** Start of inlined file: stream_decoder.h ***/
  89477. #ifndef FLAC__STREAM_DECODER_H
  89478. #define FLAC__STREAM_DECODER_H
  89479. #include <stdio.h> /* for FILE */
  89480. #ifdef __cplusplus
  89481. extern "C" {
  89482. #endif
  89483. /** \file include/FLAC/stream_decoder.h
  89484. *
  89485. * \brief
  89486. * This module contains the functions which implement the stream
  89487. * decoder.
  89488. *
  89489. * See the detailed documentation in the
  89490. * \link flac_stream_decoder stream decoder \endlink module.
  89491. */
  89492. /** \defgroup flac_decoder FLAC/ \*_decoder.h: decoder interfaces
  89493. * \ingroup flac
  89494. *
  89495. * \brief
  89496. * This module describes the decoder layers provided by libFLAC.
  89497. *
  89498. * The stream decoder can be used to decode complete streams either from
  89499. * the client via callbacks, or directly from a file, depending on how
  89500. * it is initialized. When decoding via callbacks, the client provides
  89501. * callbacks for reading FLAC data and writing decoded samples, and
  89502. * handling metadata and errors. If the client also supplies seek-related
  89503. * callback, the decoder function for sample-accurate seeking within the
  89504. * FLAC input is also available. When decoding from a file, the client
  89505. * needs only supply a filename or open \c FILE* and write/metadata/error
  89506. * callbacks; the rest of the callbacks are supplied internally. For more
  89507. * info see the \link flac_stream_decoder stream decoder \endlink module.
  89508. */
  89509. /** \defgroup flac_stream_decoder FLAC/stream_decoder.h: stream decoder interface
  89510. * \ingroup flac_decoder
  89511. *
  89512. * \brief
  89513. * This module contains the functions which implement the stream
  89514. * decoder.
  89515. *
  89516. * The stream decoder can decode native FLAC, and optionally Ogg FLAC
  89517. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  89518. *
  89519. * The basic usage of this decoder is as follows:
  89520. * - The program creates an instance of a decoder using
  89521. * FLAC__stream_decoder_new().
  89522. * - The program overrides the default settings using
  89523. * FLAC__stream_decoder_set_*() functions.
  89524. * - The program initializes the instance to validate the settings and
  89525. * prepare for decoding using
  89526. * - FLAC__stream_decoder_init_stream() or FLAC__stream_decoder_init_FILE()
  89527. * or FLAC__stream_decoder_init_file() for native FLAC,
  89528. * - FLAC__stream_decoder_init_ogg_stream() or FLAC__stream_decoder_init_ogg_FILE()
  89529. * or FLAC__stream_decoder_init_ogg_file() for Ogg FLAC
  89530. * - The program calls the FLAC__stream_decoder_process_*() functions
  89531. * to decode data, which subsequently calls the callbacks.
  89532. * - The program finishes the decoding with FLAC__stream_decoder_finish(),
  89533. * which flushes the input and output and resets the decoder to the
  89534. * uninitialized state.
  89535. * - The instance may be used again or deleted with
  89536. * FLAC__stream_decoder_delete().
  89537. *
  89538. * In more detail, the program will create a new instance by calling
  89539. * FLAC__stream_decoder_new(), then call FLAC__stream_decoder_set_*()
  89540. * functions to override the default decoder options, and call
  89541. * one of the FLAC__stream_decoder_init_*() functions.
  89542. *
  89543. * There are three initialization functions for native FLAC, one for
  89544. * setting up the decoder to decode FLAC data from the client via
  89545. * callbacks, and two for decoding directly from a FLAC file.
  89546. *
  89547. * For decoding via callbacks, use FLAC__stream_decoder_init_stream().
  89548. * You must also supply several callbacks for handling I/O. Some (like
  89549. * seeking) are optional, depending on the capabilities of the input.
  89550. *
  89551. * For decoding directly from a file, use FLAC__stream_decoder_init_FILE()
  89552. * or FLAC__stream_decoder_init_file(). Then you must only supply an open
  89553. * \c FILE* or filename and fewer callbacks; the decoder will handle
  89554. * the other callbacks internally.
  89555. *
  89556. * There are three similarly-named init functions for decoding from Ogg
  89557. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  89558. * library has been built with Ogg support.
  89559. *
  89560. * Once the decoder is initialized, your program will call one of several
  89561. * functions to start the decoding process:
  89562. *
  89563. * - FLAC__stream_decoder_process_single() - Tells the decoder to process at
  89564. * most one metadata block or audio frame and return, calling either the
  89565. * metadata callback or write callback, respectively, once. If the decoder
  89566. * loses sync it will return with only the error callback being called.
  89567. * - FLAC__stream_decoder_process_until_end_of_metadata() - Tells the decoder
  89568. * to process the stream from the current location and stop upon reaching
  89569. * the first audio frame. The client will get one metadata, write, or error
  89570. * callback per metadata block, audio frame, or sync error, respectively.
  89571. * - FLAC__stream_decoder_process_until_end_of_stream() - Tells the decoder
  89572. * to process the stream from the current location until the read callback
  89573. * returns FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM or
  89574. * FLAC__STREAM_DECODER_READ_STATUS_ABORT. The client will get one metadata,
  89575. * write, or error callback per metadata block, audio frame, or sync error,
  89576. * respectively.
  89577. *
  89578. * When the decoder has finished decoding (normally or through an abort),
  89579. * the instance is finished by calling FLAC__stream_decoder_finish(), which
  89580. * ensures the decoder is in the correct state and frees memory. Then the
  89581. * instance may be deleted with FLAC__stream_decoder_delete() or initialized
  89582. * again to decode another stream.
  89583. *
  89584. * Seeking is exposed through the FLAC__stream_decoder_seek_absolute() method.
  89585. * At any point after the stream decoder has been initialized, the client can
  89586. * call this function to seek to an exact sample within the stream.
  89587. * Subsequently, the first time the write callback is called it will be
  89588. * passed a (possibly partial) block starting at that sample.
  89589. *
  89590. * If the client cannot seek via the callback interface provided, but still
  89591. * has another way of seeking, it can flush the decoder using
  89592. * FLAC__stream_decoder_flush() and start feeding data from the new position
  89593. * through the read callback.
  89594. *
  89595. * The stream decoder also provides MD5 signature checking. If this is
  89596. * turned on before initialization, FLAC__stream_decoder_finish() will
  89597. * report when the decoded MD5 signature does not match the one stored
  89598. * in the STREAMINFO block. MD5 checking is automatically turned off
  89599. * (until the next FLAC__stream_decoder_reset()) if there is no signature
  89600. * in the STREAMINFO block or when a seek is attempted.
  89601. *
  89602. * The FLAC__stream_decoder_set_metadata_*() functions deserve special
  89603. * attention. By default, the decoder only calls the metadata_callback for
  89604. * the STREAMINFO block. These functions allow you to tell the decoder
  89605. * explicitly which blocks to parse and return via the metadata_callback
  89606. * and/or which to skip. Use a FLAC__stream_decoder_set_metadata_respond_all(),
  89607. * FLAC__stream_decoder_set_metadata_ignore() ... or FLAC__stream_decoder_set_metadata_ignore_all(),
  89608. * FLAC__stream_decoder_set_metadata_respond() ... sequence to exactly specify
  89609. * which blocks to return. Remember that metadata blocks can potentially
  89610. * be big (for example, cover art) so filtering out the ones you don't
  89611. * use can reduce the memory requirements of the decoder. Also note the
  89612. * special forms FLAC__stream_decoder_set_metadata_respond_application(id)
  89613. * and FLAC__stream_decoder_set_metadata_ignore_application(id) for
  89614. * filtering APPLICATION blocks based on the application ID.
  89615. *
  89616. * STREAMINFO and SEEKTABLE blocks are always parsed and used internally, but
  89617. * they still can legally be filtered from the metadata_callback.
  89618. *
  89619. * \note
  89620. * The "set" functions may only be called when the decoder is in the
  89621. * state FLAC__STREAM_DECODER_UNINITIALIZED, i.e. after
  89622. * FLAC__stream_decoder_new() or FLAC__stream_decoder_finish(), but
  89623. * before FLAC__stream_decoder_init_*(). If this is the case they will
  89624. * return \c true, otherwise \c false.
  89625. *
  89626. * \note
  89627. * FLAC__stream_decoder_finish() resets all settings to the constructor
  89628. * defaults, including the callbacks.
  89629. *
  89630. * \{
  89631. */
  89632. /** State values for a FLAC__StreamDecoder
  89633. *
  89634. * The decoder's state can be obtained by calling FLAC__stream_decoder_get_state().
  89635. */
  89636. typedef enum {
  89637. FLAC__STREAM_DECODER_SEARCH_FOR_METADATA = 0,
  89638. /**< The decoder is ready to search for metadata. */
  89639. FLAC__STREAM_DECODER_READ_METADATA,
  89640. /**< The decoder is ready to or is in the process of reading metadata. */
  89641. FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC,
  89642. /**< The decoder is ready to or is in the process of searching for the
  89643. * frame sync code.
  89644. */
  89645. FLAC__STREAM_DECODER_READ_FRAME,
  89646. /**< The decoder is ready to or is in the process of reading a frame. */
  89647. FLAC__STREAM_DECODER_END_OF_STREAM,
  89648. /**< The decoder has reached the end of the stream. */
  89649. FLAC__STREAM_DECODER_OGG_ERROR,
  89650. /**< An error occurred in the underlying Ogg layer. */
  89651. FLAC__STREAM_DECODER_SEEK_ERROR,
  89652. /**< An error occurred while seeking. The decoder must be flushed
  89653. * with FLAC__stream_decoder_flush() or reset with
  89654. * FLAC__stream_decoder_reset() before decoding can continue.
  89655. */
  89656. FLAC__STREAM_DECODER_ABORTED,
  89657. /**< The decoder was aborted by the read callback. */
  89658. FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR,
  89659. /**< An error occurred allocating memory. The decoder is in an invalid
  89660. * state and can no longer be used.
  89661. */
  89662. FLAC__STREAM_DECODER_UNINITIALIZED
  89663. /**< The decoder is in the uninitialized state; one of the
  89664. * FLAC__stream_decoder_init_*() functions must be called before samples
  89665. * can be processed.
  89666. */
  89667. } FLAC__StreamDecoderState;
  89668. /** Maps a FLAC__StreamDecoderState to a C string.
  89669. *
  89670. * Using a FLAC__StreamDecoderState as the index to this array
  89671. * will give the string equivalent. The contents should not be modified.
  89672. */
  89673. extern FLAC_API const char * const FLAC__StreamDecoderStateString[];
  89674. /** Possible return values for the FLAC__stream_decoder_init_*() functions.
  89675. */
  89676. typedef enum {
  89677. FLAC__STREAM_DECODER_INIT_STATUS_OK = 0,
  89678. /**< Initialization was successful. */
  89679. FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  89680. /**< The library was not compiled with support for the given container
  89681. * format.
  89682. */
  89683. FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS,
  89684. /**< A required callback was not supplied. */
  89685. FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR,
  89686. /**< An error occurred allocating memory. */
  89687. FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE,
  89688. /**< fopen() failed in FLAC__stream_decoder_init_file() or
  89689. * FLAC__stream_decoder_init_ogg_file(). */
  89690. FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED
  89691. /**< FLAC__stream_decoder_init_*() was called when the decoder was
  89692. * already initialized, usually because
  89693. * FLAC__stream_decoder_finish() was not called.
  89694. */
  89695. } FLAC__StreamDecoderInitStatus;
  89696. /** Maps a FLAC__StreamDecoderInitStatus to a C string.
  89697. *
  89698. * Using a FLAC__StreamDecoderInitStatus as the index to this array
  89699. * will give the string equivalent. The contents should not be modified.
  89700. */
  89701. extern FLAC_API const char * const FLAC__StreamDecoderInitStatusString[];
  89702. /** Return values for the FLAC__StreamDecoder read callback.
  89703. */
  89704. typedef enum {
  89705. FLAC__STREAM_DECODER_READ_STATUS_CONTINUE,
  89706. /**< The read was OK and decoding can continue. */
  89707. FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM,
  89708. /**< The read was attempted while at the end of the stream. Note that
  89709. * the client must only return this value when the read callback was
  89710. * called when already at the end of the stream. Otherwise, if the read
  89711. * itself moves to the end of the stream, the client should still return
  89712. * the data and \c FLAC__STREAM_DECODER_READ_STATUS_CONTINUE, and then on
  89713. * the next read callback it should return
  89714. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM with a byte count
  89715. * of \c 0.
  89716. */
  89717. FLAC__STREAM_DECODER_READ_STATUS_ABORT
  89718. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89719. } FLAC__StreamDecoderReadStatus;
  89720. /** Maps a FLAC__StreamDecoderReadStatus to a C string.
  89721. *
  89722. * Using a FLAC__StreamDecoderReadStatus as the index to this array
  89723. * will give the string equivalent. The contents should not be modified.
  89724. */
  89725. extern FLAC_API const char * const FLAC__StreamDecoderReadStatusString[];
  89726. /** Return values for the FLAC__StreamDecoder seek callback.
  89727. */
  89728. typedef enum {
  89729. FLAC__STREAM_DECODER_SEEK_STATUS_OK,
  89730. /**< The seek was OK and decoding can continue. */
  89731. FLAC__STREAM_DECODER_SEEK_STATUS_ERROR,
  89732. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89733. FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  89734. /**< Client does not support seeking. */
  89735. } FLAC__StreamDecoderSeekStatus;
  89736. /** Maps a FLAC__StreamDecoderSeekStatus to a C string.
  89737. *
  89738. * Using a FLAC__StreamDecoderSeekStatus as the index to this array
  89739. * will give the string equivalent. The contents should not be modified.
  89740. */
  89741. extern FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[];
  89742. /** Return values for the FLAC__StreamDecoder tell callback.
  89743. */
  89744. typedef enum {
  89745. FLAC__STREAM_DECODER_TELL_STATUS_OK,
  89746. /**< The tell was OK and decoding can continue. */
  89747. FLAC__STREAM_DECODER_TELL_STATUS_ERROR,
  89748. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89749. FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  89750. /**< Client does not support telling the position. */
  89751. } FLAC__StreamDecoderTellStatus;
  89752. /** Maps a FLAC__StreamDecoderTellStatus to a C string.
  89753. *
  89754. * Using a FLAC__StreamDecoderTellStatus as the index to this array
  89755. * will give the string equivalent. The contents should not be modified.
  89756. */
  89757. extern FLAC_API const char * const FLAC__StreamDecoderTellStatusString[];
  89758. /** Return values for the FLAC__StreamDecoder length callback.
  89759. */
  89760. typedef enum {
  89761. FLAC__STREAM_DECODER_LENGTH_STATUS_OK,
  89762. /**< The length call was OK and decoding can continue. */
  89763. FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR,
  89764. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89765. FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  89766. /**< Client does not support reporting the length. */
  89767. } FLAC__StreamDecoderLengthStatus;
  89768. /** Maps a FLAC__StreamDecoderLengthStatus to a C string.
  89769. *
  89770. * Using a FLAC__StreamDecoderLengthStatus as the index to this array
  89771. * will give the string equivalent. The contents should not be modified.
  89772. */
  89773. extern FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[];
  89774. /** Return values for the FLAC__StreamDecoder write callback.
  89775. */
  89776. typedef enum {
  89777. FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE,
  89778. /**< The write was OK and decoding can continue. */
  89779. FLAC__STREAM_DECODER_WRITE_STATUS_ABORT
  89780. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89781. } FLAC__StreamDecoderWriteStatus;
  89782. /** Maps a FLAC__StreamDecoderWriteStatus to a C string.
  89783. *
  89784. * Using a FLAC__StreamDecoderWriteStatus as the index to this array
  89785. * will give the string equivalent. The contents should not be modified.
  89786. */
  89787. extern FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[];
  89788. /** Possible values passed back to the FLAC__StreamDecoder error callback.
  89789. * \c FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC is the generic catch-
  89790. * all. The rest could be caused by bad sync (false synchronization on
  89791. * data that is not the start of a frame) or corrupted data. The error
  89792. * itself is the decoder's best guess at what happened assuming a correct
  89793. * sync. For example \c FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER
  89794. * could be caused by a correct sync on the start of a frame, but some
  89795. * data in the frame header was corrupted. Or it could be the result of
  89796. * syncing on a point the stream that looked like the starting of a frame
  89797. * but was not. \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  89798. * could be because the decoder encountered a valid frame made by a future
  89799. * version of the encoder which it cannot parse, or because of a false
  89800. * sync making it appear as though an encountered frame was generated by
  89801. * a future encoder.
  89802. */
  89803. typedef enum {
  89804. FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC,
  89805. /**< An error in the stream caused the decoder to lose synchronization. */
  89806. FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER,
  89807. /**< The decoder encountered a corrupted frame header. */
  89808. FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH,
  89809. /**< The frame's data did not match the CRC in the footer. */
  89810. FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  89811. /**< The decoder encountered reserved fields in use in the stream. */
  89812. } FLAC__StreamDecoderErrorStatus;
  89813. /** Maps a FLAC__StreamDecoderErrorStatus to a C string.
  89814. *
  89815. * Using a FLAC__StreamDecoderErrorStatus as the index to this array
  89816. * will give the string equivalent. The contents should not be modified.
  89817. */
  89818. extern FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[];
  89819. /***********************************************************************
  89820. *
  89821. * class FLAC__StreamDecoder
  89822. *
  89823. ***********************************************************************/
  89824. struct FLAC__StreamDecoderProtected;
  89825. struct FLAC__StreamDecoderPrivate;
  89826. /** The opaque structure definition for the stream decoder type.
  89827. * See the \link flac_stream_decoder stream decoder module \endlink
  89828. * for a detailed description.
  89829. */
  89830. typedef struct {
  89831. struct FLAC__StreamDecoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  89832. struct FLAC__StreamDecoderPrivate *private_; /* avoid the C++ keyword 'private' */
  89833. } FLAC__StreamDecoder;
  89834. /** Signature for the read callback.
  89835. *
  89836. * A function pointer matching this signature must be passed to
  89837. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89838. * called when the decoder needs more input data. The address of the
  89839. * buffer to be filled is supplied, along with the number of bytes the
  89840. * buffer can hold. The callback may choose to supply less data and
  89841. * modify the byte count but must be careful not to overflow the buffer.
  89842. * The callback then returns a status code chosen from
  89843. * FLAC__StreamDecoderReadStatus.
  89844. *
  89845. * Here is an example of a read callback for stdio streams:
  89846. * \code
  89847. * FLAC__StreamDecoderReadStatus read_cb(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  89848. * {
  89849. * FILE *file = ((MyClientData*)client_data)->file;
  89850. * if(*bytes > 0) {
  89851. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  89852. * if(ferror(file))
  89853. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  89854. * else if(*bytes == 0)
  89855. * return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  89856. * else
  89857. * return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  89858. * }
  89859. * else
  89860. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  89861. * }
  89862. * \endcode
  89863. *
  89864. * \note In general, FLAC__StreamDecoder functions which change the
  89865. * state should not be called on the \a decoder while in the callback.
  89866. *
  89867. * \param decoder The decoder instance calling the callback.
  89868. * \param buffer A pointer to a location for the callee to store
  89869. * data to be decoded.
  89870. * \param bytes A pointer to the size of the buffer. On entry
  89871. * to the callback, it contains the maximum number
  89872. * of bytes that may be stored in \a buffer. The
  89873. * callee must set it to the actual number of bytes
  89874. * stored (0 in case of error or end-of-stream) before
  89875. * returning.
  89876. * \param client_data The callee's client data set through
  89877. * FLAC__stream_decoder_init_*().
  89878. * \retval FLAC__StreamDecoderReadStatus
  89879. * The callee's return status. Note that the callback should return
  89880. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM if and only if
  89881. * zero bytes were read and there is no more data to be read.
  89882. */
  89883. typedef FLAC__StreamDecoderReadStatus (*FLAC__StreamDecoderReadCallback)(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  89884. /** Signature for the seek callback.
  89885. *
  89886. * A function pointer matching this signature may be passed to
  89887. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89888. * called when the decoder needs to seek the input stream. The decoder
  89889. * will pass the absolute byte offset to seek to, 0 meaning the
  89890. * beginning of the stream.
  89891. *
  89892. * Here is an example of a seek callback for stdio streams:
  89893. * \code
  89894. * FLAC__StreamDecoderSeekStatus seek_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  89895. * {
  89896. * FILE *file = ((MyClientData*)client_data)->file;
  89897. * if(file == stdin)
  89898. * return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  89899. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  89900. * return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  89901. * else
  89902. * return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  89903. * }
  89904. * \endcode
  89905. *
  89906. * \note In general, FLAC__StreamDecoder functions which change the
  89907. * state should not be called on the \a decoder while in the callback.
  89908. *
  89909. * \param decoder The decoder instance calling the callback.
  89910. * \param absolute_byte_offset The offset from the beginning of the stream
  89911. * to seek to.
  89912. * \param client_data The callee's client data set through
  89913. * FLAC__stream_decoder_init_*().
  89914. * \retval FLAC__StreamDecoderSeekStatus
  89915. * The callee's return status.
  89916. */
  89917. typedef FLAC__StreamDecoderSeekStatus (*FLAC__StreamDecoderSeekCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  89918. /** Signature for the tell callback.
  89919. *
  89920. * A function pointer matching this signature may be passed to
  89921. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89922. * called when the decoder wants to know the current position of the
  89923. * stream. The callback should return the byte offset from the
  89924. * beginning of the stream.
  89925. *
  89926. * Here is an example of a tell callback for stdio streams:
  89927. * \code
  89928. * FLAC__StreamDecoderTellStatus tell_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  89929. * {
  89930. * FILE *file = ((MyClientData*)client_data)->file;
  89931. * off_t pos;
  89932. * if(file == stdin)
  89933. * return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  89934. * else if((pos = ftello(file)) < 0)
  89935. * return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  89936. * else {
  89937. * *absolute_byte_offset = (FLAC__uint64)pos;
  89938. * return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  89939. * }
  89940. * }
  89941. * \endcode
  89942. *
  89943. * \note In general, FLAC__StreamDecoder functions which change the
  89944. * state should not be called on the \a decoder while in the callback.
  89945. *
  89946. * \param decoder The decoder instance calling the callback.
  89947. * \param absolute_byte_offset A pointer to storage for the current offset
  89948. * from the beginning of the stream.
  89949. * \param client_data The callee's client data set through
  89950. * FLAC__stream_decoder_init_*().
  89951. * \retval FLAC__StreamDecoderTellStatus
  89952. * The callee's return status.
  89953. */
  89954. typedef FLAC__StreamDecoderTellStatus (*FLAC__StreamDecoderTellCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  89955. /** Signature for the length callback.
  89956. *
  89957. * A function pointer matching this signature may be passed to
  89958. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89959. * called when the decoder wants to know the total length of the stream
  89960. * in bytes.
  89961. *
  89962. * Here is an example of a length callback for stdio streams:
  89963. * \code
  89964. * FLAC__StreamDecoderLengthStatus length_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  89965. * {
  89966. * FILE *file = ((MyClientData*)client_data)->file;
  89967. * struct stat filestats;
  89968. *
  89969. * if(file == stdin)
  89970. * return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  89971. * else if(fstat(fileno(file), &filestats) != 0)
  89972. * return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  89973. * else {
  89974. * *stream_length = (FLAC__uint64)filestats.st_size;
  89975. * return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  89976. * }
  89977. * }
  89978. * \endcode
  89979. *
  89980. * \note In general, FLAC__StreamDecoder functions which change the
  89981. * state should not be called on the \a decoder while in the callback.
  89982. *
  89983. * \param decoder The decoder instance calling the callback.
  89984. * \param stream_length A pointer to storage for the length of the stream
  89985. * in bytes.
  89986. * \param client_data The callee's client data set through
  89987. * FLAC__stream_decoder_init_*().
  89988. * \retval FLAC__StreamDecoderLengthStatus
  89989. * The callee's return status.
  89990. */
  89991. typedef FLAC__StreamDecoderLengthStatus (*FLAC__StreamDecoderLengthCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  89992. /** Signature for the EOF callback.
  89993. *
  89994. * A function pointer matching this signature may be passed to
  89995. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89996. * called when the decoder needs to know if the end of the stream has
  89997. * been reached.
  89998. *
  89999. * Here is an example of a EOF callback for stdio streams:
  90000. * FLAC__bool eof_cb(const FLAC__StreamDecoder *decoder, void *client_data)
  90001. * \code
  90002. * {
  90003. * FILE *file = ((MyClientData*)client_data)->file;
  90004. * return feof(file)? true : false;
  90005. * }
  90006. * \endcode
  90007. *
  90008. * \note In general, FLAC__StreamDecoder functions which change the
  90009. * state should not be called on the \a decoder while in the callback.
  90010. *
  90011. * \param decoder The decoder instance calling the callback.
  90012. * \param client_data The callee's client data set through
  90013. * FLAC__stream_decoder_init_*().
  90014. * \retval FLAC__bool
  90015. * \c true if the currently at the end of the stream, else \c false.
  90016. */
  90017. typedef FLAC__bool (*FLAC__StreamDecoderEofCallback)(const FLAC__StreamDecoder *decoder, void *client_data);
  90018. /** Signature for the write callback.
  90019. *
  90020. * A function pointer matching this signature must be passed to one of
  90021. * the FLAC__stream_decoder_init_*() functions.
  90022. * The supplied function will be called when the decoder has decoded a
  90023. * single audio frame. The decoder will pass the frame metadata as well
  90024. * as an array of pointers (one for each channel) pointing to the
  90025. * decoded audio.
  90026. *
  90027. * \note In general, FLAC__StreamDecoder functions which change the
  90028. * state should not be called on the \a decoder while in the callback.
  90029. *
  90030. * \param decoder The decoder instance calling the callback.
  90031. * \param frame The description of the decoded frame. See
  90032. * FLAC__Frame.
  90033. * \param buffer An array of pointers to decoded channels of data.
  90034. * Each pointer will point to an array of signed
  90035. * samples of length \a frame->header.blocksize.
  90036. * Channels will be ordered according to the FLAC
  90037. * specification; see the documentation for the
  90038. * <A HREF="../format.html#frame_header">frame header</A>.
  90039. * \param client_data The callee's client data set through
  90040. * FLAC__stream_decoder_init_*().
  90041. * \retval FLAC__StreamDecoderWriteStatus
  90042. * The callee's return status.
  90043. */
  90044. typedef FLAC__StreamDecoderWriteStatus (*FLAC__StreamDecoderWriteCallback)(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  90045. /** Signature for the metadata callback.
  90046. *
  90047. * A function pointer matching this signature must be passed to one of
  90048. * the FLAC__stream_decoder_init_*() functions.
  90049. * The supplied function will be called when the decoder has decoded a
  90050. * metadata block. In a valid FLAC file there will always be one
  90051. * \c STREAMINFO block, followed by zero or more other metadata blocks.
  90052. * These will be supplied by the decoder in the same order as they
  90053. * appear in the stream and always before the first audio frame (i.e.
  90054. * write callback). The metadata block that is passed in must not be
  90055. * modified, and it doesn't live beyond the callback, so you should make
  90056. * a copy of it with FLAC__metadata_object_clone() if you will need it
  90057. * elsewhere. Since metadata blocks can potentially be large, by
  90058. * default the decoder only calls the metadata callback for the
  90059. * \c STREAMINFO block; you can instruct the decoder to pass or filter
  90060. * other blocks with FLAC__stream_decoder_set_metadata_*() calls.
  90061. *
  90062. * \note In general, FLAC__StreamDecoder functions which change the
  90063. * state should not be called on the \a decoder while in the callback.
  90064. *
  90065. * \param decoder The decoder instance calling the callback.
  90066. * \param metadata The decoded metadata block.
  90067. * \param client_data The callee's client data set through
  90068. * FLAC__stream_decoder_init_*().
  90069. */
  90070. typedef void (*FLAC__StreamDecoderMetadataCallback)(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  90071. /** Signature for the error callback.
  90072. *
  90073. * A function pointer matching this signature must be passed to one of
  90074. * the FLAC__stream_decoder_init_*() functions.
  90075. * The supplied function will be called whenever an error occurs during
  90076. * decoding.
  90077. *
  90078. * \note In general, FLAC__StreamDecoder functions which change the
  90079. * state should not be called on the \a decoder while in the callback.
  90080. *
  90081. * \param decoder The decoder instance calling the callback.
  90082. * \param status The error encountered by the decoder.
  90083. * \param client_data The callee's client data set through
  90084. * FLAC__stream_decoder_init_*().
  90085. */
  90086. typedef void (*FLAC__StreamDecoderErrorCallback)(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  90087. /***********************************************************************
  90088. *
  90089. * Class constructor/destructor
  90090. *
  90091. ***********************************************************************/
  90092. /** Create a new stream decoder instance. The instance is created with
  90093. * default settings; see the individual FLAC__stream_decoder_set_*()
  90094. * functions for each setting's default.
  90095. *
  90096. * \retval FLAC__StreamDecoder*
  90097. * \c NULL if there was an error allocating memory, else the new instance.
  90098. */
  90099. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void);
  90100. /** Free a decoder instance. Deletes the object pointed to by \a decoder.
  90101. *
  90102. * \param decoder A pointer to an existing decoder.
  90103. * \assert
  90104. * \code decoder != NULL \endcode
  90105. */
  90106. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder);
  90107. /***********************************************************************
  90108. *
  90109. * Public class method prototypes
  90110. *
  90111. ***********************************************************************/
  90112. /** Set the serial number for the FLAC stream within the Ogg container.
  90113. * The default behavior is to use the serial number of the first Ogg
  90114. * page. Setting a serial number here will explicitly specify which
  90115. * stream is to be decoded.
  90116. *
  90117. * \note
  90118. * This does not need to be set for native FLAC decoding.
  90119. *
  90120. * \default \c use serial number of first page
  90121. * \param decoder A decoder instance to set.
  90122. * \param serial_number See above.
  90123. * \assert
  90124. * \code decoder != NULL \endcode
  90125. * \retval FLAC__bool
  90126. * \c false if the decoder is already initialized, else \c true.
  90127. */
  90128. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long serial_number);
  90129. /** Set the "MD5 signature checking" flag. If \c true, the decoder will
  90130. * compute the MD5 signature of the unencoded audio data while decoding
  90131. * and compare it to the signature from the STREAMINFO block, if it
  90132. * exists, during FLAC__stream_decoder_finish().
  90133. *
  90134. * MD5 signature checking will be turned off (until the next
  90135. * FLAC__stream_decoder_reset()) if there is no signature in the
  90136. * STREAMINFO block or when a seek is attempted.
  90137. *
  90138. * Clients that do not use the MD5 check should leave this off to speed
  90139. * up decoding.
  90140. *
  90141. * \default \c false
  90142. * \param decoder A decoder instance to set.
  90143. * \param value Flag value (see above).
  90144. * \assert
  90145. * \code decoder != NULL \endcode
  90146. * \retval FLAC__bool
  90147. * \c false if the decoder is already initialized, else \c true.
  90148. */
  90149. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value);
  90150. /** Direct the decoder to pass on all metadata blocks of type \a type.
  90151. *
  90152. * \default By default, only the \c STREAMINFO block is returned via the
  90153. * metadata callback.
  90154. * \param decoder A decoder instance to set.
  90155. * \param type See above.
  90156. * \assert
  90157. * \code decoder != NULL \endcode
  90158. * \a type is valid
  90159. * \retval FLAC__bool
  90160. * \c false if the decoder is already initialized, else \c true.
  90161. */
  90162. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  90163. /** Direct the decoder to pass on all APPLICATION metadata blocks of the
  90164. * given \a id.
  90165. *
  90166. * \default By default, only the \c STREAMINFO block is returned via the
  90167. * metadata callback.
  90168. * \param decoder A decoder instance to set.
  90169. * \param id See above.
  90170. * \assert
  90171. * \code decoder != NULL \endcode
  90172. * \code id != NULL \endcode
  90173. * \retval FLAC__bool
  90174. * \c false if the decoder is already initialized, else \c true.
  90175. */
  90176. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  90177. /** Direct the decoder to pass on all metadata blocks of any type.
  90178. *
  90179. * \default By default, only the \c STREAMINFO block is returned via the
  90180. * metadata callback.
  90181. * \param decoder A decoder instance to set.
  90182. * \assert
  90183. * \code decoder != NULL \endcode
  90184. * \retval FLAC__bool
  90185. * \c false if the decoder is already initialized, else \c true.
  90186. */
  90187. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder);
  90188. /** Direct the decoder to filter out all metadata blocks of type \a type.
  90189. *
  90190. * \default By default, only the \c STREAMINFO block is returned via the
  90191. * metadata callback.
  90192. * \param decoder A decoder instance to set.
  90193. * \param type See above.
  90194. * \assert
  90195. * \code decoder != NULL \endcode
  90196. * \a type is valid
  90197. * \retval FLAC__bool
  90198. * \c false if the decoder is already initialized, else \c true.
  90199. */
  90200. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  90201. /** Direct the decoder to filter out all APPLICATION metadata blocks of
  90202. * the given \a id.
  90203. *
  90204. * \default By default, only the \c STREAMINFO block is returned via the
  90205. * metadata callback.
  90206. * \param decoder A decoder instance to set.
  90207. * \param id See above.
  90208. * \assert
  90209. * \code decoder != NULL \endcode
  90210. * \code id != NULL \endcode
  90211. * \retval FLAC__bool
  90212. * \c false if the decoder is already initialized, else \c true.
  90213. */
  90214. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  90215. /** Direct the decoder to filter out all metadata blocks of any type.
  90216. *
  90217. * \default By default, only the \c STREAMINFO block is returned via the
  90218. * metadata callback.
  90219. * \param decoder A decoder instance to set.
  90220. * \assert
  90221. * \code decoder != NULL \endcode
  90222. * \retval FLAC__bool
  90223. * \c false if the decoder is already initialized, else \c true.
  90224. */
  90225. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder);
  90226. /** Get the current decoder state.
  90227. *
  90228. * \param decoder A decoder instance to query.
  90229. * \assert
  90230. * \code decoder != NULL \endcode
  90231. * \retval FLAC__StreamDecoderState
  90232. * The current decoder state.
  90233. */
  90234. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder);
  90235. /** Get the current decoder state as a C string.
  90236. *
  90237. * \param decoder A decoder instance to query.
  90238. * \assert
  90239. * \code decoder != NULL \endcode
  90240. * \retval const char *
  90241. * The decoder state as a C string. Do not modify the contents.
  90242. */
  90243. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder);
  90244. /** Get the "MD5 signature checking" flag.
  90245. * This is the value of the setting, not whether or not the decoder is
  90246. * currently checking the MD5 (remember, it can be turned off automatically
  90247. * by a seek). When the decoder is reset the flag will be restored to the
  90248. * value returned by this function.
  90249. *
  90250. * \param decoder A decoder instance to query.
  90251. * \assert
  90252. * \code decoder != NULL \endcode
  90253. * \retval FLAC__bool
  90254. * See above.
  90255. */
  90256. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder);
  90257. /** Get the total number of samples in the stream being decoded.
  90258. * Will only be valid after decoding has started and will contain the
  90259. * value from the \c STREAMINFO block. A value of \c 0 means "unknown".
  90260. *
  90261. * \param decoder A decoder instance to query.
  90262. * \assert
  90263. * \code decoder != NULL \endcode
  90264. * \retval unsigned
  90265. * See above.
  90266. */
  90267. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder);
  90268. /** Get the current number of channels in the stream being decoded.
  90269. * Will only be valid after decoding has started and will contain the
  90270. * value from the most recently decoded frame header.
  90271. *
  90272. * \param decoder A decoder instance to query.
  90273. * \assert
  90274. * \code decoder != NULL \endcode
  90275. * \retval unsigned
  90276. * See above.
  90277. */
  90278. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder);
  90279. /** Get the current channel assignment in the stream being decoded.
  90280. * Will only be valid after decoding has started and will contain the
  90281. * value from the most recently decoded frame header.
  90282. *
  90283. * \param decoder A decoder instance to query.
  90284. * \assert
  90285. * \code decoder != NULL \endcode
  90286. * \retval FLAC__ChannelAssignment
  90287. * See above.
  90288. */
  90289. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder);
  90290. /** Get the current sample resolution in the stream being decoded.
  90291. * Will only be valid after decoding has started and will contain the
  90292. * value from the most recently decoded frame header.
  90293. *
  90294. * \param decoder A decoder instance to query.
  90295. * \assert
  90296. * \code decoder != NULL \endcode
  90297. * \retval unsigned
  90298. * See above.
  90299. */
  90300. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder);
  90301. /** Get the current sample rate in Hz of the stream being decoded.
  90302. * Will only be valid after decoding has started and will contain the
  90303. * value from the most recently decoded frame header.
  90304. *
  90305. * \param decoder A decoder instance to query.
  90306. * \assert
  90307. * \code decoder != NULL \endcode
  90308. * \retval unsigned
  90309. * See above.
  90310. */
  90311. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder);
  90312. /** Get the current blocksize of the stream being decoded.
  90313. * Will only be valid after decoding has started and will contain the
  90314. * value from the most recently decoded frame header.
  90315. *
  90316. * \param decoder A decoder instance to query.
  90317. * \assert
  90318. * \code decoder != NULL \endcode
  90319. * \retval unsigned
  90320. * See above.
  90321. */
  90322. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder);
  90323. /** Returns the decoder's current read position within the stream.
  90324. * The position is the byte offset from the start of the stream.
  90325. * Bytes before this position have been fully decoded. Note that
  90326. * there may still be undecoded bytes in the decoder's read FIFO.
  90327. * The returned position is correct even after a seek.
  90328. *
  90329. * \warning This function currently only works for native FLAC,
  90330. * not Ogg FLAC streams.
  90331. *
  90332. * \param decoder A decoder instance to query.
  90333. * \param position Address at which to return the desired position.
  90334. * \assert
  90335. * \code decoder != NULL \endcode
  90336. * \code position != NULL \endcode
  90337. * \retval FLAC__bool
  90338. * \c true if successful, \c false if the stream is not native FLAC,
  90339. * or there was an error from the 'tell' callback or it returned
  90340. * \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED.
  90341. */
  90342. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position);
  90343. /** Initialize the decoder instance to decode native FLAC streams.
  90344. *
  90345. * This flavor of initialization sets up the decoder to decode from a
  90346. * native FLAC stream. I/O is performed via callbacks to the client.
  90347. * For decoding from a plain file via filename or open FILE*,
  90348. * FLAC__stream_decoder_init_file() and FLAC__stream_decoder_init_FILE()
  90349. * provide a simpler interface.
  90350. *
  90351. * This function should be called after FLAC__stream_decoder_new() and
  90352. * FLAC__stream_decoder_set_*() but before any of the
  90353. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90354. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90355. * if initialization succeeded.
  90356. *
  90357. * \param decoder An uninitialized decoder instance.
  90358. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  90359. * pointer must not be \c NULL.
  90360. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  90361. * pointer may be \c NULL if seeking is not
  90362. * supported. If \a seek_callback is not \c NULL then a
  90363. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  90364. * Alternatively, a dummy seek callback that just
  90365. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  90366. * may also be supplied, all though this is slightly
  90367. * less efficient for the decoder.
  90368. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  90369. * pointer may be \c NULL if not supported by the client. If
  90370. * \a seek_callback is not \c NULL then a
  90371. * \a tell_callback must also be supplied.
  90372. * Alternatively, a dummy tell callback that just
  90373. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  90374. * may also be supplied, all though this is slightly
  90375. * less efficient for the decoder.
  90376. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  90377. * pointer may be \c NULL if not supported by the client. If
  90378. * \a seek_callback is not \c NULL then a
  90379. * \a length_callback must also be supplied.
  90380. * Alternatively, a dummy length callback that just
  90381. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  90382. * may also be supplied, all though this is slightly
  90383. * less efficient for the decoder.
  90384. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  90385. * pointer may be \c NULL if not supported by the client. If
  90386. * \a seek_callback is not \c NULL then a
  90387. * \a eof_callback must also be supplied.
  90388. * Alternatively, a dummy length callback that just
  90389. * returns \c false
  90390. * may also be supplied, all though this is slightly
  90391. * less efficient for the decoder.
  90392. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90393. * pointer must not be \c NULL.
  90394. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90395. * pointer may be \c NULL if the callback is not
  90396. * desired.
  90397. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90398. * pointer must not be \c NULL.
  90399. * \param client_data This value will be supplied to callbacks in their
  90400. * \a client_data argument.
  90401. * \assert
  90402. * \code decoder != NULL \endcode
  90403. * \retval FLAC__StreamDecoderInitStatus
  90404. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90405. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90406. */
  90407. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  90408. FLAC__StreamDecoder *decoder,
  90409. FLAC__StreamDecoderReadCallback read_callback,
  90410. FLAC__StreamDecoderSeekCallback seek_callback,
  90411. FLAC__StreamDecoderTellCallback tell_callback,
  90412. FLAC__StreamDecoderLengthCallback length_callback,
  90413. FLAC__StreamDecoderEofCallback eof_callback,
  90414. FLAC__StreamDecoderWriteCallback write_callback,
  90415. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90416. FLAC__StreamDecoderErrorCallback error_callback,
  90417. void *client_data
  90418. );
  90419. /** Initialize the decoder instance to decode Ogg FLAC streams.
  90420. *
  90421. * This flavor of initialization sets up the decoder to decode from a
  90422. * FLAC stream in an Ogg container. I/O is performed via callbacks to the
  90423. * client. For decoding from a plain file via filename or open FILE*,
  90424. * FLAC__stream_decoder_init_ogg_file() and FLAC__stream_decoder_init_ogg_FILE()
  90425. * provide a simpler interface.
  90426. *
  90427. * This function should be called after FLAC__stream_decoder_new() and
  90428. * FLAC__stream_decoder_set_*() but before any of the
  90429. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90430. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90431. * if initialization succeeded.
  90432. *
  90433. * \note Support for Ogg FLAC in the library is optional. If this
  90434. * library has been built without support for Ogg FLAC, this function
  90435. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  90436. *
  90437. * \param decoder An uninitialized decoder instance.
  90438. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  90439. * pointer must not be \c NULL.
  90440. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  90441. * pointer may be \c NULL if seeking is not
  90442. * supported. If \a seek_callback is not \c NULL then a
  90443. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  90444. * Alternatively, a dummy seek callback that just
  90445. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  90446. * may also be supplied, all though this is slightly
  90447. * less efficient for the decoder.
  90448. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  90449. * pointer may be \c NULL if not supported by the client. If
  90450. * \a seek_callback is not \c NULL then a
  90451. * \a tell_callback must also be supplied.
  90452. * Alternatively, a dummy tell callback that just
  90453. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  90454. * may also be supplied, all though this is slightly
  90455. * less efficient for the decoder.
  90456. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  90457. * pointer may be \c NULL if not supported by the client. If
  90458. * \a seek_callback is not \c NULL then a
  90459. * \a length_callback must also be supplied.
  90460. * Alternatively, a dummy length callback that just
  90461. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  90462. * may also be supplied, all though this is slightly
  90463. * less efficient for the decoder.
  90464. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  90465. * pointer may be \c NULL if not supported by the client. If
  90466. * \a seek_callback is not \c NULL then a
  90467. * \a eof_callback must also be supplied.
  90468. * Alternatively, a dummy length callback that just
  90469. * returns \c false
  90470. * may also be supplied, all though this is slightly
  90471. * less efficient for the decoder.
  90472. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90473. * pointer must not be \c NULL.
  90474. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90475. * pointer may be \c NULL if the callback is not
  90476. * desired.
  90477. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90478. * pointer must not be \c NULL.
  90479. * \param client_data This value will be supplied to callbacks in their
  90480. * \a client_data argument.
  90481. * \assert
  90482. * \code decoder != NULL \endcode
  90483. * \retval FLAC__StreamDecoderInitStatus
  90484. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90485. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90486. */
  90487. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  90488. FLAC__StreamDecoder *decoder,
  90489. FLAC__StreamDecoderReadCallback read_callback,
  90490. FLAC__StreamDecoderSeekCallback seek_callback,
  90491. FLAC__StreamDecoderTellCallback tell_callback,
  90492. FLAC__StreamDecoderLengthCallback length_callback,
  90493. FLAC__StreamDecoderEofCallback eof_callback,
  90494. FLAC__StreamDecoderWriteCallback write_callback,
  90495. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90496. FLAC__StreamDecoderErrorCallback error_callback,
  90497. void *client_data
  90498. );
  90499. /** Initialize the decoder instance to decode native FLAC files.
  90500. *
  90501. * This flavor of initialization sets up the decoder to decode from a
  90502. * plain native FLAC file. For non-stdio streams, you must use
  90503. * FLAC__stream_decoder_init_stream() and provide callbacks for the I/O.
  90504. *
  90505. * This function should be called after FLAC__stream_decoder_new() and
  90506. * FLAC__stream_decoder_set_*() but before any of the
  90507. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90508. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90509. * if initialization succeeded.
  90510. *
  90511. * \param decoder An uninitialized decoder instance.
  90512. * \param file An open FLAC file. The file should have been
  90513. * opened with mode \c "rb" and rewound. The file
  90514. * becomes owned by the decoder and should not be
  90515. * manipulated by the client while decoding.
  90516. * Unless \a file is \c stdin, it will be closed
  90517. * when FLAC__stream_decoder_finish() is called.
  90518. * Note however that seeking will not work when
  90519. * decoding from \c stdout since it is not seekable.
  90520. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90521. * pointer must not be \c NULL.
  90522. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90523. * pointer may be \c NULL if the callback is not
  90524. * desired.
  90525. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90526. * pointer must not be \c NULL.
  90527. * \param client_data This value will be supplied to callbacks in their
  90528. * \a client_data argument.
  90529. * \assert
  90530. * \code decoder != NULL \endcode
  90531. * \code file != NULL \endcode
  90532. * \retval FLAC__StreamDecoderInitStatus
  90533. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90534. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90535. */
  90536. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  90537. FLAC__StreamDecoder *decoder,
  90538. FILE *file,
  90539. FLAC__StreamDecoderWriteCallback write_callback,
  90540. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90541. FLAC__StreamDecoderErrorCallback error_callback,
  90542. void *client_data
  90543. );
  90544. /** Initialize the decoder instance to decode Ogg FLAC files.
  90545. *
  90546. * This flavor of initialization sets up the decoder to decode from a
  90547. * plain Ogg FLAC file. For non-stdio streams, you must use
  90548. * FLAC__stream_decoder_init_ogg_stream() and provide callbacks for the I/O.
  90549. *
  90550. * This function should be called after FLAC__stream_decoder_new() and
  90551. * FLAC__stream_decoder_set_*() but before any of the
  90552. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90553. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90554. * if initialization succeeded.
  90555. *
  90556. * \note Support for Ogg FLAC in the library is optional. If this
  90557. * library has been built without support for Ogg FLAC, this function
  90558. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  90559. *
  90560. * \param decoder An uninitialized decoder instance.
  90561. * \param file An open FLAC file. The file should have been
  90562. * opened with mode \c "rb" and rewound. The file
  90563. * becomes owned by the decoder and should not be
  90564. * manipulated by the client while decoding.
  90565. * Unless \a file is \c stdin, it will be closed
  90566. * when FLAC__stream_decoder_finish() is called.
  90567. * Note however that seeking will not work when
  90568. * decoding from \c stdout since it is not seekable.
  90569. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90570. * pointer must not be \c NULL.
  90571. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90572. * pointer may be \c NULL if the callback is not
  90573. * desired.
  90574. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90575. * pointer must not be \c NULL.
  90576. * \param client_data This value will be supplied to callbacks in their
  90577. * \a client_data argument.
  90578. * \assert
  90579. * \code decoder != NULL \endcode
  90580. * \code file != NULL \endcode
  90581. * \retval FLAC__StreamDecoderInitStatus
  90582. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90583. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90584. */
  90585. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  90586. FLAC__StreamDecoder *decoder,
  90587. FILE *file,
  90588. FLAC__StreamDecoderWriteCallback write_callback,
  90589. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90590. FLAC__StreamDecoderErrorCallback error_callback,
  90591. void *client_data
  90592. );
  90593. /** Initialize the decoder instance to decode native FLAC files.
  90594. *
  90595. * This flavor of initialization sets up the decoder to decode from a plain
  90596. * native FLAC file. If POSIX fopen() semantics are not sufficient, (for
  90597. * example, with Unicode filenames on Windows), you must use
  90598. * FLAC__stream_decoder_init_FILE(), or FLAC__stream_decoder_init_stream()
  90599. * and provide callbacks for the I/O.
  90600. *
  90601. * This function should be called after FLAC__stream_decoder_new() and
  90602. * FLAC__stream_decoder_set_*() but before any of the
  90603. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90604. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90605. * if initialization succeeded.
  90606. *
  90607. * \param decoder An uninitialized decoder instance.
  90608. * \param filename The name of the file to decode from. The file will
  90609. * be opened with fopen(). Use \c NULL to decode from
  90610. * \c stdin. Note that \c stdin is not seekable.
  90611. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90612. * pointer must not be \c NULL.
  90613. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90614. * pointer may be \c NULL if the callback is not
  90615. * desired.
  90616. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90617. * pointer must not be \c NULL.
  90618. * \param client_data This value will be supplied to callbacks in their
  90619. * \a client_data argument.
  90620. * \assert
  90621. * \code decoder != NULL \endcode
  90622. * \retval FLAC__StreamDecoderInitStatus
  90623. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90624. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90625. */
  90626. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  90627. FLAC__StreamDecoder *decoder,
  90628. const char *filename,
  90629. FLAC__StreamDecoderWriteCallback write_callback,
  90630. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90631. FLAC__StreamDecoderErrorCallback error_callback,
  90632. void *client_data
  90633. );
  90634. /** Initialize the decoder instance to decode Ogg FLAC files.
  90635. *
  90636. * This flavor of initialization sets up the decoder to decode from a plain
  90637. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient, (for
  90638. * example, with Unicode filenames on Windows), you must use
  90639. * FLAC__stream_decoder_init_ogg_FILE(), or FLAC__stream_decoder_init_ogg_stream()
  90640. * and provide callbacks for the I/O.
  90641. *
  90642. * This function should be called after FLAC__stream_decoder_new() and
  90643. * FLAC__stream_decoder_set_*() but before any of the
  90644. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90645. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90646. * if initialization succeeded.
  90647. *
  90648. * \note Support for Ogg FLAC in the library is optional. If this
  90649. * library has been built without support for Ogg FLAC, this function
  90650. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  90651. *
  90652. * \param decoder An uninitialized decoder instance.
  90653. * \param filename The name of the file to decode from. The file will
  90654. * be opened with fopen(). Use \c NULL to decode from
  90655. * \c stdin. Note that \c stdin is not seekable.
  90656. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90657. * pointer must not be \c NULL.
  90658. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90659. * pointer may be \c NULL if the callback is not
  90660. * desired.
  90661. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90662. * pointer must not be \c NULL.
  90663. * \param client_data This value will be supplied to callbacks in their
  90664. * \a client_data argument.
  90665. * \assert
  90666. * \code decoder != NULL \endcode
  90667. * \retval FLAC__StreamDecoderInitStatus
  90668. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90669. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90670. */
  90671. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  90672. FLAC__StreamDecoder *decoder,
  90673. const char *filename,
  90674. FLAC__StreamDecoderWriteCallback write_callback,
  90675. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90676. FLAC__StreamDecoderErrorCallback error_callback,
  90677. void *client_data
  90678. );
  90679. /** Finish the decoding process.
  90680. * Flushes the decoding buffer, releases resources, resets the decoder
  90681. * settings to their defaults, and returns the decoder state to
  90682. * FLAC__STREAM_DECODER_UNINITIALIZED.
  90683. *
  90684. * In the event of a prematurely-terminated decode, it is not strictly
  90685. * necessary to call this immediately before FLAC__stream_decoder_delete()
  90686. * but it is good practice to match every FLAC__stream_decoder_init_*()
  90687. * with a FLAC__stream_decoder_finish().
  90688. *
  90689. * \param decoder An uninitialized decoder instance.
  90690. * \assert
  90691. * \code decoder != NULL \endcode
  90692. * \retval FLAC__bool
  90693. * \c false if MD5 checking is on AND a STREAMINFO block was available
  90694. * AND the MD5 signature in the STREAMINFO block was non-zero AND the
  90695. * signature does not match the one computed by the decoder; else
  90696. * \c true.
  90697. */
  90698. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder);
  90699. /** Flush the stream input.
  90700. * The decoder's input buffer will be cleared and the state set to
  90701. * \c FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC. This will also turn
  90702. * off MD5 checking.
  90703. *
  90704. * \param decoder A decoder instance.
  90705. * \assert
  90706. * \code decoder != NULL \endcode
  90707. * \retval FLAC__bool
  90708. * \c true if successful, else \c false if a memory allocation
  90709. * error occurs (in which case the state will be set to
  90710. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR).
  90711. */
  90712. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder);
  90713. /** Reset the decoding process.
  90714. * The decoder's input buffer will be cleared and the state set to
  90715. * \c FLAC__STREAM_DECODER_SEARCH_FOR_METADATA. This is similar to
  90716. * FLAC__stream_decoder_finish() except that the settings are
  90717. * preserved; there is no need to call FLAC__stream_decoder_init_*()
  90718. * before decoding again. MD5 checking will be restored to its original
  90719. * setting.
  90720. *
  90721. * If the decoder is seekable, or was initialized with
  90722. * FLAC__stream_decoder_init*_FILE() or FLAC__stream_decoder_init*_file(),
  90723. * the decoder will also attempt to seek to the beginning of the file.
  90724. * If this rewind fails, this function will return \c false. It follows
  90725. * that FLAC__stream_decoder_reset() cannot be used when decoding from
  90726. * \c stdin.
  90727. *
  90728. * If the decoder was initialized with FLAC__stream_encoder_init*_stream()
  90729. * and is not seekable (i.e. no seek callback was provided or the seek
  90730. * callback returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED), it
  90731. * is the duty of the client to start feeding data from the beginning of
  90732. * the stream on the next FLAC__stream_decoder_process() or
  90733. * FLAC__stream_decoder_process_interleaved() call.
  90734. *
  90735. * \param decoder A decoder instance.
  90736. * \assert
  90737. * \code decoder != NULL \endcode
  90738. * \retval FLAC__bool
  90739. * \c true if successful, else \c false if a memory allocation occurs
  90740. * (in which case the state will be set to
  90741. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR) or a seek error
  90742. * occurs (the state will be unchanged).
  90743. */
  90744. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder);
  90745. /** Decode one metadata block or audio frame.
  90746. * This version instructs the decoder to decode a either a single metadata
  90747. * block or a single frame and stop, unless the callbacks return a fatal
  90748. * error or the read callback returns
  90749. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90750. *
  90751. * As the decoder needs more input it will call the read callback.
  90752. * Depending on what was decoded, the metadata or write callback will be
  90753. * called with the decoded metadata block or audio frame.
  90754. *
  90755. * Unless there is a fatal read error or end of stream, this function
  90756. * will return once one whole frame is decoded. In other words, if the
  90757. * stream is not synchronized or points to a corrupt frame header, the
  90758. * decoder will continue to try and resync until it gets to a valid
  90759. * frame, then decode one frame, then return. If the decoder points to
  90760. * a frame whose frame CRC in the frame footer does not match the
  90761. * computed frame CRC, this function will issue a
  90762. * FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH error to the
  90763. * error callback, and return, having decoded one complete, although
  90764. * corrupt, frame. (Such corrupted frames are sent as silence of the
  90765. * correct length to the write callback.)
  90766. *
  90767. * \param decoder An initialized decoder instance.
  90768. * \assert
  90769. * \code decoder != NULL \endcode
  90770. * \retval FLAC__bool
  90771. * \c false if any fatal read, write, or memory allocation error
  90772. * occurred (meaning decoding must stop), else \c true; for more
  90773. * information about the decoder, check the decoder state with
  90774. * FLAC__stream_decoder_get_state().
  90775. */
  90776. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder);
  90777. /** Decode until the end of the metadata.
  90778. * This version instructs the decoder to decode from the current position
  90779. * and continue until all the metadata has been read, or until the
  90780. * callbacks return a fatal error or the read callback returns
  90781. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90782. *
  90783. * As the decoder needs more input it will call the read callback.
  90784. * As each metadata block is decoded, the metadata callback will be called
  90785. * with the decoded metadata.
  90786. *
  90787. * \param decoder An initialized decoder instance.
  90788. * \assert
  90789. * \code decoder != NULL \endcode
  90790. * \retval FLAC__bool
  90791. * \c false if any fatal read, write, or memory allocation error
  90792. * occurred (meaning decoding must stop), else \c true; for more
  90793. * information about the decoder, check the decoder state with
  90794. * FLAC__stream_decoder_get_state().
  90795. */
  90796. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder);
  90797. /** Decode until the end of the stream.
  90798. * This version instructs the decoder to decode from the current position
  90799. * and continue until the end of stream (the read callback returns
  90800. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM), or until the
  90801. * callbacks return a fatal error.
  90802. *
  90803. * As the decoder needs more input it will call the read callback.
  90804. * As each metadata block and frame is decoded, the metadata or write
  90805. * callback will be called with the decoded metadata or frame.
  90806. *
  90807. * \param decoder An initialized decoder instance.
  90808. * \assert
  90809. * \code decoder != NULL \endcode
  90810. * \retval FLAC__bool
  90811. * \c false if any fatal read, write, or memory allocation error
  90812. * occurred (meaning decoding must stop), else \c true; for more
  90813. * information about the decoder, check the decoder state with
  90814. * FLAC__stream_decoder_get_state().
  90815. */
  90816. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder);
  90817. /** Skip one audio frame.
  90818. * This version instructs the decoder to 'skip' a single frame and stop,
  90819. * unless the callbacks return a fatal error or the read callback returns
  90820. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90821. *
  90822. * The decoding flow is the same as what occurs when
  90823. * FLAC__stream_decoder_process_single() is called to process an audio
  90824. * frame, except that this function does not decode the parsed data into
  90825. * PCM or call the write callback. The integrity of the frame is still
  90826. * checked the same way as in the other process functions.
  90827. *
  90828. * This function will return once one whole frame is skipped, in the
  90829. * same way that FLAC__stream_decoder_process_single() will return once
  90830. * one whole frame is decoded.
  90831. *
  90832. * This function can be used in more quickly determining FLAC frame
  90833. * boundaries when decoding of the actual data is not needed, for
  90834. * example when an application is separating a FLAC stream into frames
  90835. * for editing or storing in a container. To do this, the application
  90836. * can use FLAC__stream_decoder_skip_single_frame() to quickly advance
  90837. * to the next frame, then use
  90838. * FLAC__stream_decoder_get_decode_position() to find the new frame
  90839. * boundary.
  90840. *
  90841. * This function should only be called when the stream has advanced
  90842. * past all the metadata, otherwise it will return \c false.
  90843. *
  90844. * \param decoder An initialized decoder instance not in a metadata
  90845. * state.
  90846. * \assert
  90847. * \code decoder != NULL \endcode
  90848. * \retval FLAC__bool
  90849. * \c false if any fatal read, write, or memory allocation error
  90850. * occurred (meaning decoding must stop), or if the decoder
  90851. * is in the FLAC__STREAM_DECODER_SEARCH_FOR_METADATA or
  90852. * FLAC__STREAM_DECODER_READ_METADATA state, else \c true; for more
  90853. * information about the decoder, check the decoder state with
  90854. * FLAC__stream_decoder_get_state().
  90855. */
  90856. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder);
  90857. /** Flush the input and seek to an absolute sample.
  90858. * Decoding will resume at the given sample. Note that because of
  90859. * this, the next write callback may contain a partial block. The
  90860. * client must support seeking the input or this function will fail
  90861. * and return \c false. Furthermore, if the decoder state is
  90862. * \c FLAC__STREAM_DECODER_SEEK_ERROR, then the decoder must be flushed
  90863. * with FLAC__stream_decoder_flush() or reset with
  90864. * FLAC__stream_decoder_reset() before decoding can continue.
  90865. *
  90866. * \param decoder A decoder instance.
  90867. * \param sample The target sample number to seek to.
  90868. * \assert
  90869. * \code decoder != NULL \endcode
  90870. * \retval FLAC__bool
  90871. * \c true if successful, else \c false.
  90872. */
  90873. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample);
  90874. /* \} */
  90875. #ifdef __cplusplus
  90876. }
  90877. #endif
  90878. #endif
  90879. /*** End of inlined file: stream_decoder.h ***/
  90880. /*** Start of inlined file: stream_encoder.h ***/
  90881. #ifndef FLAC__STREAM_ENCODER_H
  90882. #define FLAC__STREAM_ENCODER_H
  90883. #include <stdio.h> /* for FILE */
  90884. #ifdef __cplusplus
  90885. extern "C" {
  90886. #endif
  90887. /** \file include/FLAC/stream_encoder.h
  90888. *
  90889. * \brief
  90890. * This module contains the functions which implement the stream
  90891. * encoder.
  90892. *
  90893. * See the detailed documentation in the
  90894. * \link flac_stream_encoder stream encoder \endlink module.
  90895. */
  90896. /** \defgroup flac_encoder FLAC/ \*_encoder.h: encoder interfaces
  90897. * \ingroup flac
  90898. *
  90899. * \brief
  90900. * This module describes the encoder layers provided by libFLAC.
  90901. *
  90902. * The stream encoder can be used to encode complete streams either to the
  90903. * client via callbacks, or directly to a file, depending on how it is
  90904. * initialized. When encoding via callbacks, the client provides a write
  90905. * callback which will be called whenever FLAC data is ready to be written.
  90906. * If the client also supplies a seek callback, the encoder will also
  90907. * automatically handle the writing back of metadata discovered while
  90908. * encoding, like stream info, seek points offsets, etc. When encoding to
  90909. * a file, the client needs only supply a filename or open \c FILE* and an
  90910. * optional progress callback for periodic notification of progress; the
  90911. * write and seek callbacks are supplied internally. For more info see the
  90912. * \link flac_stream_encoder stream encoder \endlink module.
  90913. */
  90914. /** \defgroup flac_stream_encoder FLAC/stream_encoder.h: stream encoder interface
  90915. * \ingroup flac_encoder
  90916. *
  90917. * \brief
  90918. * This module contains the functions which implement the stream
  90919. * encoder.
  90920. *
  90921. * The stream encoder can encode to native FLAC, and optionally Ogg FLAC
  90922. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  90923. *
  90924. * The basic usage of this encoder is as follows:
  90925. * - The program creates an instance of an encoder using
  90926. * FLAC__stream_encoder_new().
  90927. * - The program overrides the default settings using
  90928. * FLAC__stream_encoder_set_*() functions. At a minimum, the following
  90929. * functions should be called:
  90930. * - FLAC__stream_encoder_set_channels()
  90931. * - FLAC__stream_encoder_set_bits_per_sample()
  90932. * - FLAC__stream_encoder_set_sample_rate()
  90933. * - FLAC__stream_encoder_set_ogg_serial_number() (if encoding to Ogg FLAC)
  90934. * - FLAC__stream_encoder_set_total_samples_estimate() (if known)
  90935. * - If the application wants to control the compression level or set its own
  90936. * metadata, then the following should also be called:
  90937. * - FLAC__stream_encoder_set_compression_level()
  90938. * - FLAC__stream_encoder_set_verify()
  90939. * - FLAC__stream_encoder_set_metadata()
  90940. * - The rest of the set functions should only be called if the client needs
  90941. * exact control over how the audio is compressed; thorough understanding
  90942. * of the FLAC format is necessary to achieve good results.
  90943. * - The program initializes the instance to validate the settings and
  90944. * prepare for encoding using
  90945. * - FLAC__stream_encoder_init_stream() or FLAC__stream_encoder_init_FILE()
  90946. * or FLAC__stream_encoder_init_file() for native FLAC
  90947. * - FLAC__stream_encoder_init_ogg_stream() or FLAC__stream_encoder_init_ogg_FILE()
  90948. * or FLAC__stream_encoder_init_ogg_file() for Ogg FLAC
  90949. * - The program calls FLAC__stream_encoder_process() or
  90950. * FLAC__stream_encoder_process_interleaved() to encode data, which
  90951. * subsequently calls the callbacks when there is encoder data ready
  90952. * to be written.
  90953. * - The program finishes the encoding with FLAC__stream_encoder_finish(),
  90954. * which causes the encoder to encode any data still in its input pipe,
  90955. * update the metadata with the final encoding statistics if output
  90956. * seeking is possible, and finally reset the encoder to the
  90957. * uninitialized state.
  90958. * - The instance may be used again or deleted with
  90959. * FLAC__stream_encoder_delete().
  90960. *
  90961. * In more detail, the stream encoder functions similarly to the
  90962. * \link flac_stream_decoder stream decoder \endlink, but has fewer
  90963. * callbacks and more options. Typically the client will create a new
  90964. * instance by calling FLAC__stream_encoder_new(), then set the necessary
  90965. * parameters with FLAC__stream_encoder_set_*(), and initialize it by
  90966. * calling one of the FLAC__stream_encoder_init_*() functions.
  90967. *
  90968. * Unlike the decoders, the stream encoder has many options that can
  90969. * affect the speed and compression ratio. When setting these parameters
  90970. * you should have some basic knowledge of the format (see the
  90971. * <A HREF="../documentation.html#format">user-level documentation</A>
  90972. * or the <A HREF="../format.html">formal description</A>). The
  90973. * FLAC__stream_encoder_set_*() functions themselves do not validate the
  90974. * values as many are interdependent. The FLAC__stream_encoder_init_*()
  90975. * functions will do this, so make sure to pay attention to the state
  90976. * returned by FLAC__stream_encoder_init_*() to make sure that it is
  90977. * FLAC__STREAM_ENCODER_INIT_STATUS_OK. Any parameters that are not set
  90978. * before FLAC__stream_encoder_init_*() will take on the defaults from
  90979. * the constructor.
  90980. *
  90981. * There are three initialization functions for native FLAC, one for
  90982. * setting up the encoder to encode FLAC data to the client via
  90983. * callbacks, and two for encoding directly to a file.
  90984. *
  90985. * For encoding via callbacks, use FLAC__stream_encoder_init_stream().
  90986. * You must also supply a write callback which will be called anytime
  90987. * there is raw encoded data to write. If the client can seek the output
  90988. * it is best to also supply seek and tell callbacks, as this allows the
  90989. * encoder to go back after encoding is finished to write back
  90990. * information that was collected while encoding, like seek point offsets,
  90991. * frame sizes, etc.
  90992. *
  90993. * For encoding directly to a file, use FLAC__stream_encoder_init_FILE()
  90994. * or FLAC__stream_encoder_init_file(). Then you must only supply a
  90995. * filename or open \c FILE*; the encoder will handle all the callbacks
  90996. * internally. You may also supply a progress callback for periodic
  90997. * notification of the encoding progress.
  90998. *
  90999. * There are three similarly-named init functions for encoding to Ogg
  91000. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  91001. * library has been built with Ogg support.
  91002. *
  91003. * The call to FLAC__stream_encoder_init_*() currently will also immediately
  91004. * call the write callback several times, once with the \c fLaC signature,
  91005. * and once for each encoded metadata block. Note that for Ogg FLAC
  91006. * encoding you will usually get at least twice the number of callbacks than
  91007. * with native FLAC, one for the Ogg page header and one for the page body.
  91008. *
  91009. * After initializing the instance, the client may feed audio data to the
  91010. * encoder in one of two ways:
  91011. *
  91012. * - Channel separate, through FLAC__stream_encoder_process() - The client
  91013. * will pass an array of pointers to buffers, one for each channel, to
  91014. * the encoder, each of the same length. The samples need not be
  91015. * block-aligned, but each channel should have the same number of samples.
  91016. * - Channel interleaved, through
  91017. * FLAC__stream_encoder_process_interleaved() - The client will pass a single
  91018. * pointer to data that is channel-interleaved (i.e. channel0_sample0,
  91019. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  91020. * Again, the samples need not be block-aligned but they must be
  91021. * sample-aligned, i.e. the first value should be channel0_sample0 and
  91022. * the last value channelN_sampleM.
  91023. *
  91024. * Note that for either process call, each sample in the buffers should be a
  91025. * signed integer, right-justified to the resolution set by
  91026. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the resolution
  91027. * is 16 bits per sample, the samples should all be in the range [-32768,32767].
  91028. *
  91029. * When the client is finished encoding data, it calls
  91030. * FLAC__stream_encoder_finish(), which causes the encoder to encode any
  91031. * data still in its input pipe, and call the metadata callback with the
  91032. * final encoding statistics. Then the instance may be deleted with
  91033. * FLAC__stream_encoder_delete() or initialized again to encode another
  91034. * stream.
  91035. *
  91036. * For programs that write their own metadata, but that do not know the
  91037. * actual metadata until after encoding, it is advantageous to instruct
  91038. * the encoder to write a PADDING block of the correct size, so that
  91039. * instead of rewriting the whole stream after encoding, the program can
  91040. * just overwrite the PADDING block. If only the maximum size of the
  91041. * metadata is known, the program can write a slightly larger padding
  91042. * block, then split it after encoding.
  91043. *
  91044. * Make sure you understand how lengths are calculated. All FLAC metadata
  91045. * blocks have a 4 byte header which contains the type and length. This
  91046. * length does not include the 4 bytes of the header. See the format page
  91047. * for the specification of metadata blocks and their lengths.
  91048. *
  91049. * \note
  91050. * If you are writing the FLAC data to a file via callbacks, make sure it
  91051. * is open for update (e.g. mode "w+" for stdio streams). This is because
  91052. * after the first encoding pass, the encoder will try to seek back to the
  91053. * beginning of the stream, to the STREAMINFO block, to write some data
  91054. * there. (If using FLAC__stream_encoder_init*_file() or
  91055. * FLAC__stream_encoder_init*_FILE(), the file is managed internally.)
  91056. *
  91057. * \note
  91058. * The "set" functions may only be called when the encoder is in the
  91059. * state FLAC__STREAM_ENCODER_UNINITIALIZED, i.e. after
  91060. * FLAC__stream_encoder_new() or FLAC__stream_encoder_finish(), but
  91061. * before FLAC__stream_encoder_init_*(). If this is the case they will
  91062. * return \c true, otherwise \c false.
  91063. *
  91064. * \note
  91065. * FLAC__stream_encoder_finish() resets all settings to the constructor
  91066. * defaults.
  91067. *
  91068. * \{
  91069. */
  91070. /** State values for a FLAC__StreamEncoder.
  91071. *
  91072. * The encoder's state can be obtained by calling FLAC__stream_encoder_get_state().
  91073. *
  91074. * If the encoder gets into any other state besides \c FLAC__STREAM_ENCODER_OK
  91075. * or \c FLAC__STREAM_ENCODER_UNINITIALIZED, it becomes invalid for encoding and
  91076. * must be deleted with FLAC__stream_encoder_delete().
  91077. */
  91078. typedef enum {
  91079. FLAC__STREAM_ENCODER_OK = 0,
  91080. /**< The encoder is in the normal OK state and samples can be processed. */
  91081. FLAC__STREAM_ENCODER_UNINITIALIZED,
  91082. /**< The encoder is in the uninitialized state; one of the
  91083. * FLAC__stream_encoder_init_*() functions must be called before samples
  91084. * can be processed.
  91085. */
  91086. FLAC__STREAM_ENCODER_OGG_ERROR,
  91087. /**< An error occurred in the underlying Ogg layer. */
  91088. FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR,
  91089. /**< An error occurred in the underlying verify stream decoder;
  91090. * check FLAC__stream_encoder_get_verify_decoder_state().
  91091. */
  91092. FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA,
  91093. /**< The verify decoder detected a mismatch between the original
  91094. * audio signal and the decoded audio signal.
  91095. */
  91096. FLAC__STREAM_ENCODER_CLIENT_ERROR,
  91097. /**< One of the callbacks returned a fatal error. */
  91098. FLAC__STREAM_ENCODER_IO_ERROR,
  91099. /**< An I/O error occurred while opening/reading/writing a file.
  91100. * Check \c errno.
  91101. */
  91102. FLAC__STREAM_ENCODER_FRAMING_ERROR,
  91103. /**< An error occurred while writing the stream; usually, the
  91104. * write_callback returned an error.
  91105. */
  91106. FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR
  91107. /**< Memory allocation failed. */
  91108. } FLAC__StreamEncoderState;
  91109. /** Maps a FLAC__StreamEncoderState to a C string.
  91110. *
  91111. * Using a FLAC__StreamEncoderState as the index to this array
  91112. * will give the string equivalent. The contents should not be modified.
  91113. */
  91114. extern FLAC_API const char * const FLAC__StreamEncoderStateString[];
  91115. /** Possible return values for the FLAC__stream_encoder_init_*() functions.
  91116. */
  91117. typedef enum {
  91118. FLAC__STREAM_ENCODER_INIT_STATUS_OK = 0,
  91119. /**< Initialization was successful. */
  91120. FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR,
  91121. /**< General failure to set up encoder; call FLAC__stream_encoder_get_state() for cause. */
  91122. FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  91123. /**< The library was not compiled with support for the given container
  91124. * format.
  91125. */
  91126. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS,
  91127. /**< A required callback was not supplied. */
  91128. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS,
  91129. /**< The encoder has an invalid setting for number of channels. */
  91130. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE,
  91131. /**< The encoder has an invalid setting for bits-per-sample.
  91132. * FLAC supports 4-32 bps but the reference encoder currently supports
  91133. * only up to 24 bps.
  91134. */
  91135. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE,
  91136. /**< The encoder has an invalid setting for the input sample rate. */
  91137. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE,
  91138. /**< The encoder has an invalid setting for the block size. */
  91139. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER,
  91140. /**< The encoder has an invalid setting for the maximum LPC order. */
  91141. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION,
  91142. /**< The encoder has an invalid setting for the precision of the quantized linear predictor coefficients. */
  91143. FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER,
  91144. /**< The specified block size is less than the maximum LPC order. */
  91145. FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE,
  91146. /**< The encoder is bound to the <A HREF="../format.html#subset">Subset</A> but other settings violate it. */
  91147. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA,
  91148. /**< The metadata input to the encoder is invalid, in one of the following ways:
  91149. * - FLAC__stream_encoder_set_metadata() was called with a null pointer but a block count > 0
  91150. * - One of the metadata blocks contains an undefined type
  91151. * - It contains an illegal CUESHEET as checked by FLAC__format_cuesheet_is_legal()
  91152. * - It contains an illegal SEEKTABLE as checked by FLAC__format_seektable_is_legal()
  91153. * - It contains more than one SEEKTABLE block or more than one VORBIS_COMMENT block
  91154. */
  91155. FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED
  91156. /**< FLAC__stream_encoder_init_*() was called when the encoder was
  91157. * already initialized, usually because
  91158. * FLAC__stream_encoder_finish() was not called.
  91159. */
  91160. } FLAC__StreamEncoderInitStatus;
  91161. /** Maps a FLAC__StreamEncoderInitStatus to a C string.
  91162. *
  91163. * Using a FLAC__StreamEncoderInitStatus as the index to this array
  91164. * will give the string equivalent. The contents should not be modified.
  91165. */
  91166. extern FLAC_API const char * const FLAC__StreamEncoderInitStatusString[];
  91167. /** Return values for the FLAC__StreamEncoder read callback.
  91168. */
  91169. typedef enum {
  91170. FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE,
  91171. /**< The read was OK and decoding can continue. */
  91172. FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM,
  91173. /**< The read was attempted at the end of the stream. */
  91174. FLAC__STREAM_ENCODER_READ_STATUS_ABORT,
  91175. /**< An unrecoverable error occurred. */
  91176. FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED
  91177. /**< Client does not support reading back from the output. */
  91178. } FLAC__StreamEncoderReadStatus;
  91179. /** Maps a FLAC__StreamEncoderReadStatus to a C string.
  91180. *
  91181. * Using a FLAC__StreamEncoderReadStatus as the index to this array
  91182. * will give the string equivalent. The contents should not be modified.
  91183. */
  91184. extern FLAC_API const char * const FLAC__StreamEncoderReadStatusString[];
  91185. /** Return values for the FLAC__StreamEncoder write callback.
  91186. */
  91187. typedef enum {
  91188. FLAC__STREAM_ENCODER_WRITE_STATUS_OK = 0,
  91189. /**< The write was OK and encoding can continue. */
  91190. FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR
  91191. /**< An unrecoverable error occurred. The encoder will return from the process call. */
  91192. } FLAC__StreamEncoderWriteStatus;
  91193. /** Maps a FLAC__StreamEncoderWriteStatus to a C string.
  91194. *
  91195. * Using a FLAC__StreamEncoderWriteStatus as the index to this array
  91196. * will give the string equivalent. The contents should not be modified.
  91197. */
  91198. extern FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[];
  91199. /** Return values for the FLAC__StreamEncoder seek callback.
  91200. */
  91201. typedef enum {
  91202. FLAC__STREAM_ENCODER_SEEK_STATUS_OK,
  91203. /**< The seek was OK and encoding can continue. */
  91204. FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR,
  91205. /**< An unrecoverable error occurred. */
  91206. FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  91207. /**< Client does not support seeking. */
  91208. } FLAC__StreamEncoderSeekStatus;
  91209. /** Maps a FLAC__StreamEncoderSeekStatus to a C string.
  91210. *
  91211. * Using a FLAC__StreamEncoderSeekStatus as the index to this array
  91212. * will give the string equivalent. The contents should not be modified.
  91213. */
  91214. extern FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[];
  91215. /** Return values for the FLAC__StreamEncoder tell callback.
  91216. */
  91217. typedef enum {
  91218. FLAC__STREAM_ENCODER_TELL_STATUS_OK,
  91219. /**< The tell was OK and encoding can continue. */
  91220. FLAC__STREAM_ENCODER_TELL_STATUS_ERROR,
  91221. /**< An unrecoverable error occurred. */
  91222. FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  91223. /**< Client does not support seeking. */
  91224. } FLAC__StreamEncoderTellStatus;
  91225. /** Maps a FLAC__StreamEncoderTellStatus to a C string.
  91226. *
  91227. * Using a FLAC__StreamEncoderTellStatus as the index to this array
  91228. * will give the string equivalent. The contents should not be modified.
  91229. */
  91230. extern FLAC_API const char * const FLAC__StreamEncoderTellStatusString[];
  91231. /***********************************************************************
  91232. *
  91233. * class FLAC__StreamEncoder
  91234. *
  91235. ***********************************************************************/
  91236. struct FLAC__StreamEncoderProtected;
  91237. struct FLAC__StreamEncoderPrivate;
  91238. /** The opaque structure definition for the stream encoder type.
  91239. * See the \link flac_stream_encoder stream encoder module \endlink
  91240. * for a detailed description.
  91241. */
  91242. typedef struct {
  91243. struct FLAC__StreamEncoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  91244. struct FLAC__StreamEncoderPrivate *private_; /* avoid the C++ keyword 'private' */
  91245. } FLAC__StreamEncoder;
  91246. /** Signature for the read callback.
  91247. *
  91248. * A function pointer matching this signature must be passed to
  91249. * FLAC__stream_encoder_init_ogg_stream() if seeking is supported.
  91250. * The supplied function will be called when the encoder needs to read back
  91251. * encoded data. This happens during the metadata callback, when the encoder
  91252. * has to read, modify, and rewrite the metadata (e.g. seekpoints) gathered
  91253. * while encoding. The address of the buffer to be filled is supplied, along
  91254. * with the number of bytes the buffer can hold. The callback may choose to
  91255. * supply less data and modify the byte count but must be careful not to
  91256. * overflow the buffer. The callback then returns a status code chosen from
  91257. * FLAC__StreamEncoderReadStatus.
  91258. *
  91259. * Here is an example of a read callback for stdio streams:
  91260. * \code
  91261. * FLAC__StreamEncoderReadStatus read_cb(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  91262. * {
  91263. * FILE *file = ((MyClientData*)client_data)->file;
  91264. * if(*bytes > 0) {
  91265. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  91266. * if(ferror(file))
  91267. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  91268. * else if(*bytes == 0)
  91269. * return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  91270. * else
  91271. * return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  91272. * }
  91273. * else
  91274. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  91275. * }
  91276. * \endcode
  91277. *
  91278. * \note In general, FLAC__StreamEncoder functions which change the
  91279. * state should not be called on the \a encoder while in the callback.
  91280. *
  91281. * \param encoder The encoder instance calling the callback.
  91282. * \param buffer A pointer to a location for the callee to store
  91283. * data to be encoded.
  91284. * \param bytes A pointer to the size of the buffer. On entry
  91285. * to the callback, it contains the maximum number
  91286. * of bytes that may be stored in \a buffer. The
  91287. * callee must set it to the actual number of bytes
  91288. * stored (0 in case of error or end-of-stream) before
  91289. * returning.
  91290. * \param client_data The callee's client data set through
  91291. * FLAC__stream_encoder_set_client_data().
  91292. * \retval FLAC__StreamEncoderReadStatus
  91293. * The callee's return status.
  91294. */
  91295. typedef FLAC__StreamEncoderReadStatus (*FLAC__StreamEncoderReadCallback)(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  91296. /** Signature for the write callback.
  91297. *
  91298. * A function pointer matching this signature must be passed to
  91299. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91300. * by the encoder anytime there is raw encoded data ready to write. It may
  91301. * include metadata mixed with encoded audio frames and the data is not
  91302. * guaranteed to be aligned on frame or metadata block boundaries.
  91303. *
  91304. * The only duty of the callback is to write out the \a bytes worth of data
  91305. * in \a buffer to the current position in the output stream. The arguments
  91306. * \a samples and \a current_frame are purely informational. If \a samples
  91307. * is greater than \c 0, then \a current_frame will hold the current frame
  91308. * number that is being written; otherwise it indicates that the write
  91309. * callback is being called to write metadata.
  91310. *
  91311. * \note
  91312. * Unlike when writing to native FLAC, when writing to Ogg FLAC the
  91313. * write callback will be called twice when writing each audio
  91314. * frame; once for the page header, and once for the page body.
  91315. * When writing the page header, the \a samples argument to the
  91316. * write callback will be \c 0.
  91317. *
  91318. * \note In general, FLAC__StreamEncoder functions which change the
  91319. * state should not be called on the \a encoder while in the callback.
  91320. *
  91321. * \param encoder The encoder instance calling the callback.
  91322. * \param buffer An array of encoded data of length \a bytes.
  91323. * \param bytes The byte length of \a buffer.
  91324. * \param samples The number of samples encoded by \a buffer.
  91325. * \c 0 has a special meaning; see above.
  91326. * \param current_frame The number of the current frame being encoded.
  91327. * \param client_data The callee's client data set through
  91328. * FLAC__stream_encoder_init_*().
  91329. * \retval FLAC__StreamEncoderWriteStatus
  91330. * The callee's return status.
  91331. */
  91332. typedef FLAC__StreamEncoderWriteStatus (*FLAC__StreamEncoderWriteCallback)(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data);
  91333. /** Signature for the seek callback.
  91334. *
  91335. * A function pointer matching this signature may be passed to
  91336. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91337. * when the encoder needs to seek the output stream. The encoder will pass
  91338. * the absolute byte offset to seek to, 0 meaning the beginning of the stream.
  91339. *
  91340. * Here is an example of a seek callback for stdio streams:
  91341. * \code
  91342. * FLAC__StreamEncoderSeekStatus seek_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  91343. * {
  91344. * FILE *file = ((MyClientData*)client_data)->file;
  91345. * if(file == stdin)
  91346. * return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  91347. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  91348. * return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  91349. * else
  91350. * return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  91351. * }
  91352. * \endcode
  91353. *
  91354. * \note In general, FLAC__StreamEncoder functions which change the
  91355. * state should not be called on the \a encoder while in the callback.
  91356. *
  91357. * \param encoder The encoder instance calling the callback.
  91358. * \param absolute_byte_offset The offset from the beginning of the stream
  91359. * to seek to.
  91360. * \param client_data The callee's client data set through
  91361. * FLAC__stream_encoder_init_*().
  91362. * \retval FLAC__StreamEncoderSeekStatus
  91363. * The callee's return status.
  91364. */
  91365. typedef FLAC__StreamEncoderSeekStatus (*FLAC__StreamEncoderSeekCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  91366. /** Signature for the tell callback.
  91367. *
  91368. * A function pointer matching this signature may be passed to
  91369. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91370. * when the encoder needs to know the current position of the output stream.
  91371. *
  91372. * \warning
  91373. * The callback must return the true current byte offset of the output to
  91374. * which the encoder is writing. If you are buffering the output, make
  91375. * sure and take this into account. If you are writing directly to a
  91376. * FILE* from your write callback, ftell() is sufficient. If you are
  91377. * writing directly to a file descriptor from your write callback, you
  91378. * can use lseek(fd, SEEK_CUR, 0). The encoder may later seek back to
  91379. * these points to rewrite metadata after encoding.
  91380. *
  91381. * Here is an example of a tell callback for stdio streams:
  91382. * \code
  91383. * FLAC__StreamEncoderTellStatus tell_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  91384. * {
  91385. * FILE *file = ((MyClientData*)client_data)->file;
  91386. * off_t pos;
  91387. * if(file == stdin)
  91388. * return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  91389. * else if((pos = ftello(file)) < 0)
  91390. * return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  91391. * else {
  91392. * *absolute_byte_offset = (FLAC__uint64)pos;
  91393. * return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  91394. * }
  91395. * }
  91396. * \endcode
  91397. *
  91398. * \note In general, FLAC__StreamEncoder functions which change the
  91399. * state should not be called on the \a encoder while in the callback.
  91400. *
  91401. * \param encoder The encoder instance calling the callback.
  91402. * \param absolute_byte_offset The address at which to store the current
  91403. * position of the output.
  91404. * \param client_data The callee's client data set through
  91405. * FLAC__stream_encoder_init_*().
  91406. * \retval FLAC__StreamEncoderTellStatus
  91407. * The callee's return status.
  91408. */
  91409. typedef FLAC__StreamEncoderTellStatus (*FLAC__StreamEncoderTellCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  91410. /** Signature for the metadata callback.
  91411. *
  91412. * A function pointer matching this signature may be passed to
  91413. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91414. * once at the end of encoding with the populated STREAMINFO structure. This
  91415. * is so the client can seek back to the beginning of the file and write the
  91416. * STREAMINFO block with the correct statistics after encoding (like
  91417. * minimum/maximum frame size and total samples).
  91418. *
  91419. * \note In general, FLAC__StreamEncoder functions which change the
  91420. * state should not be called on the \a encoder while in the callback.
  91421. *
  91422. * \param encoder The encoder instance calling the callback.
  91423. * \param metadata The final populated STREAMINFO block.
  91424. * \param client_data The callee's client data set through
  91425. * FLAC__stream_encoder_init_*().
  91426. */
  91427. typedef void (*FLAC__StreamEncoderMetadataCallback)(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data);
  91428. /** Signature for the progress callback.
  91429. *
  91430. * A function pointer matching this signature may be passed to
  91431. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE().
  91432. * The supplied function will be called when the encoder has finished
  91433. * writing a frame. The \c total_frames_estimate argument to the
  91434. * callback will be based on the value from
  91435. * FLAC__stream_encoder_set_total_samples_estimate().
  91436. *
  91437. * \note In general, FLAC__StreamEncoder functions which change the
  91438. * state should not be called on the \a encoder while in the callback.
  91439. *
  91440. * \param encoder The encoder instance calling the callback.
  91441. * \param bytes_written Bytes written so far.
  91442. * \param samples_written Samples written so far.
  91443. * \param frames_written Frames written so far.
  91444. * \param total_frames_estimate The estimate of the total number of
  91445. * frames to be written.
  91446. * \param client_data The callee's client data set through
  91447. * FLAC__stream_encoder_init_*().
  91448. */
  91449. 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);
  91450. /***********************************************************************
  91451. *
  91452. * Class constructor/destructor
  91453. *
  91454. ***********************************************************************/
  91455. /** Create a new stream encoder instance. The instance is created with
  91456. * default settings; see the individual FLAC__stream_encoder_set_*()
  91457. * functions for each setting's default.
  91458. *
  91459. * \retval FLAC__StreamEncoder*
  91460. * \c NULL if there was an error allocating memory, else the new instance.
  91461. */
  91462. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void);
  91463. /** Free an encoder instance. Deletes the object pointed to by \a encoder.
  91464. *
  91465. * \param encoder A pointer to an existing encoder.
  91466. * \assert
  91467. * \code encoder != NULL \endcode
  91468. */
  91469. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder);
  91470. /***********************************************************************
  91471. *
  91472. * Public class method prototypes
  91473. *
  91474. ***********************************************************************/
  91475. /** Set the serial number for the FLAC stream to use in the Ogg container.
  91476. *
  91477. * \note
  91478. * This does not need to be set for native FLAC encoding.
  91479. *
  91480. * \note
  91481. * It is recommended to set a serial number explicitly as the default of '0'
  91482. * may collide with other streams.
  91483. *
  91484. * \default \c 0
  91485. * \param encoder An encoder instance to set.
  91486. * \param serial_number See above.
  91487. * \assert
  91488. * \code encoder != NULL \endcode
  91489. * \retval FLAC__bool
  91490. * \c false if the encoder is already initialized, else \c true.
  91491. */
  91492. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long serial_number);
  91493. /** Set the "verify" flag. If \c true, the encoder will verify it's own
  91494. * encoded output by feeding it through an internal decoder and comparing
  91495. * the original signal against the decoded signal. If a mismatch occurs,
  91496. * the process call will return \c false. Note that this will slow the
  91497. * encoding process by the extra time required for decoding and comparison.
  91498. *
  91499. * \default \c false
  91500. * \param encoder An encoder instance to set.
  91501. * \param value Flag value (see above).
  91502. * \assert
  91503. * \code encoder != NULL \endcode
  91504. * \retval FLAC__bool
  91505. * \c false if the encoder is already initialized, else \c true.
  91506. */
  91507. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91508. /** Set the <A HREF="../format.html#subset">Subset</A> flag. If \c true,
  91509. * the encoder will comply with the Subset and will check the
  91510. * settings during FLAC__stream_encoder_init_*() to see if all settings
  91511. * comply. If \c false, the settings may take advantage of the full
  91512. * range that the format allows.
  91513. *
  91514. * Make sure you know what it entails before setting this to \c false.
  91515. *
  91516. * \default \c true
  91517. * \param encoder An encoder instance to set.
  91518. * \param value Flag value (see above).
  91519. * \assert
  91520. * \code encoder != NULL \endcode
  91521. * \retval FLAC__bool
  91522. * \c false if the encoder is already initialized, else \c true.
  91523. */
  91524. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91525. /** Set the number of channels to be encoded.
  91526. *
  91527. * \default \c 2
  91528. * \param encoder An encoder instance to set.
  91529. * \param value See above.
  91530. * \assert
  91531. * \code encoder != NULL \endcode
  91532. * \retval FLAC__bool
  91533. * \c false if the encoder is already initialized, else \c true.
  91534. */
  91535. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value);
  91536. /** Set the sample resolution of the input to be encoded.
  91537. *
  91538. * \warning
  91539. * Do not feed the encoder data that is wider than the value you
  91540. * set here or you will generate an invalid stream.
  91541. *
  91542. * \default \c 16
  91543. * \param encoder An encoder instance to set.
  91544. * \param value See above.
  91545. * \assert
  91546. * \code encoder != NULL \endcode
  91547. * \retval FLAC__bool
  91548. * \c false if the encoder is already initialized, else \c true.
  91549. */
  91550. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value);
  91551. /** Set the sample rate (in Hz) of the input to be encoded.
  91552. *
  91553. * \default \c 44100
  91554. * \param encoder An encoder instance to set.
  91555. * \param value See above.
  91556. * \assert
  91557. * \code encoder != NULL \endcode
  91558. * \retval FLAC__bool
  91559. * \c false if the encoder is already initialized, else \c true.
  91560. */
  91561. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value);
  91562. /** Set the compression level
  91563. *
  91564. * The compression level is roughly proportional to the amount of effort
  91565. * the encoder expends to compress the file. A higher level usually
  91566. * means more computation but higher compression. The default level is
  91567. * suitable for most applications.
  91568. *
  91569. * Currently the levels range from \c 0 (fastest, least compression) to
  91570. * \c 8 (slowest, most compression). A value larger than \c 8 will be
  91571. * treated as \c 8.
  91572. *
  91573. * This function automatically calls the following other \c _set_
  91574. * functions with appropriate values, so the client does not need to
  91575. * unless it specifically wants to override them:
  91576. * - FLAC__stream_encoder_set_do_mid_side_stereo()
  91577. * - FLAC__stream_encoder_set_loose_mid_side_stereo()
  91578. * - FLAC__stream_encoder_set_apodization()
  91579. * - FLAC__stream_encoder_set_max_lpc_order()
  91580. * - FLAC__stream_encoder_set_qlp_coeff_precision()
  91581. * - FLAC__stream_encoder_set_do_qlp_coeff_prec_search()
  91582. * - FLAC__stream_encoder_set_do_escape_coding()
  91583. * - FLAC__stream_encoder_set_do_exhaustive_model_search()
  91584. * - FLAC__stream_encoder_set_min_residual_partition_order()
  91585. * - FLAC__stream_encoder_set_max_residual_partition_order()
  91586. * - FLAC__stream_encoder_set_rice_parameter_search_dist()
  91587. *
  91588. * The actual values set for each level are:
  91589. * <table>
  91590. * <tr>
  91591. * <td><b>level</b><td>
  91592. * <td>do mid-side stereo<td>
  91593. * <td>loose mid-side stereo<td>
  91594. * <td>apodization<td>
  91595. * <td>max lpc order<td>
  91596. * <td>qlp coeff precision<td>
  91597. * <td>qlp coeff prec search<td>
  91598. * <td>escape coding<td>
  91599. * <td>exhaustive model search<td>
  91600. * <td>min residual partition order<td>
  91601. * <td>max residual partition order<td>
  91602. * <td>rice parameter search dist<td>
  91603. * </tr>
  91604. * <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>
  91605. * <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>
  91606. * <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>
  91607. * <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>
  91608. * <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>
  91609. * <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>
  91610. * <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>
  91611. * <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>
  91612. * <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>
  91613. * </table>
  91614. *
  91615. * \default \c 5
  91616. * \param encoder An encoder instance to set.
  91617. * \param value See above.
  91618. * \assert
  91619. * \code encoder != NULL \endcode
  91620. * \retval FLAC__bool
  91621. * \c false if the encoder is already initialized, else \c true.
  91622. */
  91623. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value);
  91624. /** Set the blocksize to use while encoding.
  91625. *
  91626. * The number of samples to use per frame. Use \c 0 to let the encoder
  91627. * estimate a blocksize; this is usually best.
  91628. *
  91629. * \default \c 0
  91630. * \param encoder An encoder instance to set.
  91631. * \param value See above.
  91632. * \assert
  91633. * \code encoder != NULL \endcode
  91634. * \retval FLAC__bool
  91635. * \c false if the encoder is already initialized, else \c true.
  91636. */
  91637. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value);
  91638. /** Set to \c true to enable mid-side encoding on stereo input. The
  91639. * number of channels must be 2 for this to have any effect. Set to
  91640. * \c false to use only independent channel coding.
  91641. *
  91642. * \default \c false
  91643. * \param encoder An encoder instance to set.
  91644. * \param value Flag value (see above).
  91645. * \assert
  91646. * \code encoder != NULL \endcode
  91647. * \retval FLAC__bool
  91648. * \c false if the encoder is already initialized, else \c true.
  91649. */
  91650. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91651. /** Set to \c true to enable adaptive switching between mid-side and
  91652. * left-right encoding on stereo input. Set to \c false to use
  91653. * exhaustive searching. Setting this to \c true requires
  91654. * FLAC__stream_encoder_set_do_mid_side_stereo() to also be set to
  91655. * \c true in order to have any effect.
  91656. *
  91657. * \default \c false
  91658. * \param encoder An encoder instance to set.
  91659. * \param value Flag value (see above).
  91660. * \assert
  91661. * \code encoder != NULL \endcode
  91662. * \retval FLAC__bool
  91663. * \c false if the encoder is already initialized, else \c true.
  91664. */
  91665. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91666. /** Sets the apodization function(s) the encoder will use when windowing
  91667. * audio data for LPC analysis.
  91668. *
  91669. * The \a specification is a plain ASCII string which specifies exactly
  91670. * which functions to use. There may be more than one (up to 32),
  91671. * separated by \c ';' characters. Some functions take one or more
  91672. * comma-separated arguments in parentheses.
  91673. *
  91674. * The available functions are \c bartlett, \c bartlett_hann,
  91675. * \c blackman, \c blackman_harris_4term_92db, \c connes, \c flattop,
  91676. * \c gauss(STDDEV), \c hamming, \c hann, \c kaiser_bessel, \c nuttall,
  91677. * \c rectangle, \c triangle, \c tukey(P), \c welch.
  91678. *
  91679. * For \c gauss(STDDEV), STDDEV specifies the standard deviation
  91680. * (0<STDDEV<=0.5).
  91681. *
  91682. * For \c tukey(P), P specifies the fraction of the window that is
  91683. * tapered (0<=P<=1). P=0 corresponds to \c rectangle and P=1
  91684. * corresponds to \c hann.
  91685. *
  91686. * Example specifications are \c "blackman" or
  91687. * \c "hann;triangle;tukey(0.5);tukey(0.25);tukey(0.125)"
  91688. *
  91689. * Any function that is specified erroneously is silently dropped. Up
  91690. * to 32 functions are kept, the rest are dropped. If the specification
  91691. * is empty the encoder defaults to \c "tukey(0.5)".
  91692. *
  91693. * When more than one function is specified, then for every subframe the
  91694. * encoder will try each of them separately and choose the window that
  91695. * results in the smallest compressed subframe.
  91696. *
  91697. * Note that each function specified causes the encoder to occupy a
  91698. * floating point array in which to store the window.
  91699. *
  91700. * \default \c "tukey(0.5)"
  91701. * \param encoder An encoder instance to set.
  91702. * \param specification See above.
  91703. * \assert
  91704. * \code encoder != NULL \endcode
  91705. * \code specification != NULL \endcode
  91706. * \retval FLAC__bool
  91707. * \c false if the encoder is already initialized, else \c true.
  91708. */
  91709. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification);
  91710. /** Set the maximum LPC order, or \c 0 to use only the fixed predictors.
  91711. *
  91712. * \default \c 0
  91713. * \param encoder An encoder instance to set.
  91714. * \param value See above.
  91715. * \assert
  91716. * \code encoder != NULL \endcode
  91717. * \retval FLAC__bool
  91718. * \c false if the encoder is already initialized, else \c true.
  91719. */
  91720. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value);
  91721. /** Set the precision, in bits, of the quantized linear predictor
  91722. * coefficients, or \c 0 to let the encoder select it based on the
  91723. * blocksize.
  91724. *
  91725. * \note
  91726. * In the current implementation, qlp_coeff_precision + bits_per_sample must
  91727. * be less than 32.
  91728. *
  91729. * \default \c 0
  91730. * \param encoder An encoder instance to set.
  91731. * \param value See above.
  91732. * \assert
  91733. * \code encoder != NULL \endcode
  91734. * \retval FLAC__bool
  91735. * \c false if the encoder is already initialized, else \c true.
  91736. */
  91737. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value);
  91738. /** Set to \c false to use only the specified quantized linear predictor
  91739. * coefficient precision, or \c true to search neighboring precision
  91740. * values and use the best one.
  91741. *
  91742. * \default \c false
  91743. * \param encoder An encoder instance to set.
  91744. * \param value See above.
  91745. * \assert
  91746. * \code encoder != NULL \endcode
  91747. * \retval FLAC__bool
  91748. * \c false if the encoder is already initialized, else \c true.
  91749. */
  91750. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91751. /** Deprecated. Setting this value has no effect.
  91752. *
  91753. * \default \c false
  91754. * \param encoder An encoder instance to set.
  91755. * \param value See above.
  91756. * \assert
  91757. * \code encoder != NULL \endcode
  91758. * \retval FLAC__bool
  91759. * \c false if the encoder is already initialized, else \c true.
  91760. */
  91761. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91762. /** Set to \c false to let the encoder estimate the best model order
  91763. * based on the residual signal energy, or \c true to force the
  91764. * encoder to evaluate all order models and select the best.
  91765. *
  91766. * \default \c false
  91767. * \param encoder An encoder instance to set.
  91768. * \param value See above.
  91769. * \assert
  91770. * \code encoder != NULL \endcode
  91771. * \retval FLAC__bool
  91772. * \c false if the encoder is already initialized, else \c true.
  91773. */
  91774. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91775. /** Set the minimum partition order to search when coding the residual.
  91776. * This is used in tandem with
  91777. * FLAC__stream_encoder_set_max_residual_partition_order().
  91778. *
  91779. * The partition order determines the context size in the residual.
  91780. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  91781. *
  91782. * Set both min and max values to \c 0 to force a single context,
  91783. * whose Rice parameter is based on the residual signal variance.
  91784. * Otherwise, set a min and max order, and the encoder will search
  91785. * all orders, using the mean of each context for its Rice parameter,
  91786. * and use the best.
  91787. *
  91788. * \default \c 0
  91789. * \param encoder An encoder instance to set.
  91790. * \param value See above.
  91791. * \assert
  91792. * \code encoder != NULL \endcode
  91793. * \retval FLAC__bool
  91794. * \c false if the encoder is already initialized, else \c true.
  91795. */
  91796. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  91797. /** Set the maximum partition order to search when coding the residual.
  91798. * This is used in tandem with
  91799. * FLAC__stream_encoder_set_min_residual_partition_order().
  91800. *
  91801. * The partition order determines the context size in the residual.
  91802. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  91803. *
  91804. * Set both min and max values to \c 0 to force a single context,
  91805. * whose Rice parameter is based on the residual signal variance.
  91806. * Otherwise, set a min and max order, and the encoder will search
  91807. * all orders, using the mean of each context for its Rice parameter,
  91808. * and use the best.
  91809. *
  91810. * \default \c 0
  91811. * \param encoder An encoder instance to set.
  91812. * \param value See above.
  91813. * \assert
  91814. * \code encoder != NULL \endcode
  91815. * \retval FLAC__bool
  91816. * \c false if the encoder is already initialized, else \c true.
  91817. */
  91818. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  91819. /** Deprecated. Setting this value has no effect.
  91820. *
  91821. * \default \c 0
  91822. * \param encoder An encoder instance to set.
  91823. * \param value See above.
  91824. * \assert
  91825. * \code encoder != NULL \endcode
  91826. * \retval FLAC__bool
  91827. * \c false if the encoder is already initialized, else \c true.
  91828. */
  91829. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value);
  91830. /** Set an estimate of the total samples that will be encoded.
  91831. * This is merely an estimate and may be set to \c 0 if unknown.
  91832. * This value will be written to the STREAMINFO block before encoding,
  91833. * and can remove the need for the caller to rewrite the value later
  91834. * if the value is known before encoding.
  91835. *
  91836. * \default \c 0
  91837. * \param encoder An encoder instance to set.
  91838. * \param value See above.
  91839. * \assert
  91840. * \code encoder != NULL \endcode
  91841. * \retval FLAC__bool
  91842. * \c false if the encoder is already initialized, else \c true.
  91843. */
  91844. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value);
  91845. /** Set the metadata blocks to be emitted to the stream before encoding.
  91846. * A value of \c NULL, \c 0 implies no metadata; otherwise, supply an
  91847. * array of pointers to metadata blocks. The array is non-const since
  91848. * the encoder may need to change the \a is_last flag inside them, and
  91849. * in some cases update seek point offsets. Otherwise, the encoder will
  91850. * not modify or free the blocks. It is up to the caller to free the
  91851. * metadata blocks after encoding finishes.
  91852. *
  91853. * \note
  91854. * The encoder stores only copies of the pointers in the \a metadata array;
  91855. * the metadata blocks themselves must survive at least until after
  91856. * FLAC__stream_encoder_finish() returns. Do not free the blocks until then.
  91857. *
  91858. * \note
  91859. * The STREAMINFO block is always written and no STREAMINFO block may
  91860. * occur in the supplied array.
  91861. *
  91862. * \note
  91863. * By default the encoder does not create a SEEKTABLE. If one is supplied
  91864. * in the \a metadata array, but the client has specified that it does not
  91865. * support seeking, then the SEEKTABLE will be written verbatim. However
  91866. * by itself this is not very useful as the client will not know the stream
  91867. * offsets for the seekpoints ahead of time. In order to get a proper
  91868. * seektable the client must support seeking. See next note.
  91869. *
  91870. * \note
  91871. * SEEKTABLE blocks are handled specially. Since you will not know
  91872. * the values for the seek point stream offsets, you should pass in
  91873. * a SEEKTABLE 'template', that is, a SEEKTABLE object with the
  91874. * required sample numbers (or placeholder points), with \c 0 for the
  91875. * \a frame_samples and \a stream_offset fields for each point. If the
  91876. * client has specified that it supports seeking by providing a seek
  91877. * callback to FLAC__stream_encoder_init_stream() or both seek AND read
  91878. * callback to FLAC__stream_encoder_init_ogg_stream() (or by using
  91879. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE()),
  91880. * then while it is encoding the encoder will fill the stream offsets in
  91881. * for you and when encoding is finished, it will seek back and write the
  91882. * real values into the SEEKTABLE block in the stream. There are helper
  91883. * routines for manipulating seektable template blocks; see metadata.h:
  91884. * FLAC__metadata_object_seektable_template_*(). If the client does
  91885. * not support seeking, the SEEKTABLE will have inaccurate offsets which
  91886. * will slow down or remove the ability to seek in the FLAC stream.
  91887. *
  91888. * \note
  91889. * The encoder instance \b will modify the first \c SEEKTABLE block
  91890. * as it transforms the template to a valid seektable while encoding,
  91891. * but it is still up to the caller to free all metadata blocks after
  91892. * encoding.
  91893. *
  91894. * \note
  91895. * A VORBIS_COMMENT block may be supplied. The vendor string in it
  91896. * will be ignored. libFLAC will use it's own vendor string. libFLAC
  91897. * will not modify the passed-in VORBIS_COMMENT's vendor string, it
  91898. * will simply write it's own into the stream. If no VORBIS_COMMENT
  91899. * block is present in the \a metadata array, libFLAC will write an
  91900. * empty one, containing only the vendor string.
  91901. *
  91902. * \note The Ogg FLAC mapping requires that the VORBIS_COMMENT block be
  91903. * the second metadata block of the stream. The encoder already supplies
  91904. * the STREAMINFO block automatically. If \a metadata does not contain a
  91905. * VORBIS_COMMENT block, the encoder will supply that too. Otherwise, if
  91906. * \a metadata does contain a VORBIS_COMMENT block and it is not the
  91907. * first, the init function will reorder \a metadata by moving the
  91908. * VORBIS_COMMENT block to the front; the relative ordering of the other
  91909. * blocks will remain as they were.
  91910. *
  91911. * \note The Ogg FLAC mapping limits the number of metadata blocks per
  91912. * stream to \c 65535. If \a num_blocks exceeds this the function will
  91913. * return \c false.
  91914. *
  91915. * \default \c NULL, 0
  91916. * \param encoder An encoder instance to set.
  91917. * \param metadata See above.
  91918. * \param num_blocks See above.
  91919. * \assert
  91920. * \code encoder != NULL \endcode
  91921. * \retval FLAC__bool
  91922. * \c false if the encoder is already initialized, else \c true.
  91923. * \c false if the encoder is already initialized, or if
  91924. * \a num_blocks > 65535 if encoding to Ogg FLAC, else \c true.
  91925. */
  91926. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks);
  91927. /** Get the current encoder state.
  91928. *
  91929. * \param encoder An encoder instance to query.
  91930. * \assert
  91931. * \code encoder != NULL \endcode
  91932. * \retval FLAC__StreamEncoderState
  91933. * The current encoder state.
  91934. */
  91935. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder);
  91936. /** Get the state of the verify stream decoder.
  91937. * Useful when the stream encoder state is
  91938. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR.
  91939. *
  91940. * \param encoder An encoder instance to query.
  91941. * \assert
  91942. * \code encoder != NULL \endcode
  91943. * \retval FLAC__StreamDecoderState
  91944. * The verify stream decoder state.
  91945. */
  91946. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder);
  91947. /** Get the current encoder state as a C string.
  91948. * This version automatically resolves
  91949. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR by getting the
  91950. * verify decoder's state.
  91951. *
  91952. * \param encoder A encoder instance to query.
  91953. * \assert
  91954. * \code encoder != NULL \endcode
  91955. * \retval const char *
  91956. * The encoder state as a C string. Do not modify the contents.
  91957. */
  91958. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder);
  91959. /** Get relevant values about the nature of a verify decoder error.
  91960. * Useful when the stream encoder state is
  91961. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR. The arguments should
  91962. * be addresses in which the stats will be returned, or NULL if value
  91963. * is not desired.
  91964. *
  91965. * \param encoder An encoder instance to query.
  91966. * \param absolute_sample The absolute sample number of the mismatch.
  91967. * \param frame_number The number of the frame in which the mismatch occurred.
  91968. * \param channel The channel in which the mismatch occurred.
  91969. * \param sample The number of the sample (relative to the frame) in
  91970. * which the mismatch occurred.
  91971. * \param expected The expected value for the sample in question.
  91972. * \param got The actual value returned by the decoder.
  91973. * \assert
  91974. * \code encoder != NULL \endcode
  91975. */
  91976. 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);
  91977. /** Get the "verify" flag.
  91978. *
  91979. * \param encoder An encoder instance to query.
  91980. * \assert
  91981. * \code encoder != NULL \endcode
  91982. * \retval FLAC__bool
  91983. * See FLAC__stream_encoder_set_verify().
  91984. */
  91985. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder);
  91986. /** Get the <A HREF="../format.html#subset>Subset</A> flag.
  91987. *
  91988. * \param encoder An encoder instance to query.
  91989. * \assert
  91990. * \code encoder != NULL \endcode
  91991. * \retval FLAC__bool
  91992. * See FLAC__stream_encoder_set_streamable_subset().
  91993. */
  91994. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder);
  91995. /** Get the number of input channels being processed.
  91996. *
  91997. * \param encoder An encoder instance to query.
  91998. * \assert
  91999. * \code encoder != NULL \endcode
  92000. * \retval unsigned
  92001. * See FLAC__stream_encoder_set_channels().
  92002. */
  92003. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder);
  92004. /** Get the input sample resolution setting.
  92005. *
  92006. * \param encoder An encoder instance to query.
  92007. * \assert
  92008. * \code encoder != NULL \endcode
  92009. * \retval unsigned
  92010. * See FLAC__stream_encoder_set_bits_per_sample().
  92011. */
  92012. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder);
  92013. /** Get the input sample rate setting.
  92014. *
  92015. * \param encoder An encoder instance to query.
  92016. * \assert
  92017. * \code encoder != NULL \endcode
  92018. * \retval unsigned
  92019. * See FLAC__stream_encoder_set_sample_rate().
  92020. */
  92021. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder);
  92022. /** Get the blocksize setting.
  92023. *
  92024. * \param encoder An encoder instance to query.
  92025. * \assert
  92026. * \code encoder != NULL \endcode
  92027. * \retval unsigned
  92028. * See FLAC__stream_encoder_set_blocksize().
  92029. */
  92030. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder);
  92031. /** Get the "mid/side stereo coding" flag.
  92032. *
  92033. * \param encoder An encoder instance to query.
  92034. * \assert
  92035. * \code encoder != NULL \endcode
  92036. * \retval FLAC__bool
  92037. * See FLAC__stream_encoder_get_do_mid_side_stereo().
  92038. */
  92039. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  92040. /** Get the "adaptive mid/side switching" flag.
  92041. *
  92042. * \param encoder An encoder instance to query.
  92043. * \assert
  92044. * \code encoder != NULL \endcode
  92045. * \retval FLAC__bool
  92046. * See FLAC__stream_encoder_set_loose_mid_side_stereo().
  92047. */
  92048. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  92049. /** Get the maximum LPC order setting.
  92050. *
  92051. * \param encoder An encoder instance to query.
  92052. * \assert
  92053. * \code encoder != NULL \endcode
  92054. * \retval unsigned
  92055. * See FLAC__stream_encoder_set_max_lpc_order().
  92056. */
  92057. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder);
  92058. /** Get the quantized linear predictor coefficient precision setting.
  92059. *
  92060. * \param encoder An encoder instance to query.
  92061. * \assert
  92062. * \code encoder != NULL \endcode
  92063. * \retval unsigned
  92064. * See FLAC__stream_encoder_set_qlp_coeff_precision().
  92065. */
  92066. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder);
  92067. /** Get the qlp coefficient precision search flag.
  92068. *
  92069. * \param encoder An encoder instance to query.
  92070. * \assert
  92071. * \code encoder != NULL \endcode
  92072. * \retval FLAC__bool
  92073. * See FLAC__stream_encoder_set_do_qlp_coeff_prec_search().
  92074. */
  92075. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder);
  92076. /** Get the "escape coding" flag.
  92077. *
  92078. * \param encoder An encoder instance to query.
  92079. * \assert
  92080. * \code encoder != NULL \endcode
  92081. * \retval FLAC__bool
  92082. * See FLAC__stream_encoder_set_do_escape_coding().
  92083. */
  92084. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder);
  92085. /** Get the exhaustive model search flag.
  92086. *
  92087. * \param encoder An encoder instance to query.
  92088. * \assert
  92089. * \code encoder != NULL \endcode
  92090. * \retval FLAC__bool
  92091. * See FLAC__stream_encoder_set_do_exhaustive_model_search().
  92092. */
  92093. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder);
  92094. /** Get the minimum residual partition order setting.
  92095. *
  92096. * \param encoder An encoder instance to query.
  92097. * \assert
  92098. * \code encoder != NULL \endcode
  92099. * \retval unsigned
  92100. * See FLAC__stream_encoder_set_min_residual_partition_order().
  92101. */
  92102. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder);
  92103. /** Get maximum residual partition order setting.
  92104. *
  92105. * \param encoder An encoder instance to query.
  92106. * \assert
  92107. * \code encoder != NULL \endcode
  92108. * \retval unsigned
  92109. * See FLAC__stream_encoder_set_max_residual_partition_order().
  92110. */
  92111. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder);
  92112. /** Get the Rice parameter search distance setting.
  92113. *
  92114. * \param encoder An encoder instance to query.
  92115. * \assert
  92116. * \code encoder != NULL \endcode
  92117. * \retval unsigned
  92118. * See FLAC__stream_encoder_set_rice_parameter_search_dist().
  92119. */
  92120. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder);
  92121. /** Get the previously set estimate of the total samples to be encoded.
  92122. * The encoder merely mimics back the value given to
  92123. * FLAC__stream_encoder_set_total_samples_estimate() since it has no
  92124. * other way of knowing how many samples the client will encode.
  92125. *
  92126. * \param encoder An encoder instance to set.
  92127. * \assert
  92128. * \code encoder != NULL \endcode
  92129. * \retval FLAC__uint64
  92130. * See FLAC__stream_encoder_get_total_samples_estimate().
  92131. */
  92132. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder);
  92133. /** Initialize the encoder instance to encode native FLAC streams.
  92134. *
  92135. * This flavor of initialization sets up the encoder to encode to a
  92136. * native FLAC stream. I/O is performed via callbacks to the client.
  92137. * For encoding to a plain file via filename or open \c FILE*,
  92138. * FLAC__stream_encoder_init_file() and FLAC__stream_encoder_init_FILE()
  92139. * provide a simpler interface.
  92140. *
  92141. * This function should be called after FLAC__stream_encoder_new() and
  92142. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92143. * or FLAC__stream_encoder_process_interleaved().
  92144. * initialization succeeded.
  92145. *
  92146. * The call to FLAC__stream_encoder_init_stream() currently will also
  92147. * immediately call the write callback several times, once with the \c fLaC
  92148. * signature, and once for each encoded metadata block.
  92149. *
  92150. * \param encoder An uninitialized encoder instance.
  92151. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  92152. * pointer must not be \c NULL.
  92153. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  92154. * pointer may be \c NULL if seeking is not
  92155. * supported. The encoder uses seeking to go back
  92156. * and write some some stream statistics to the
  92157. * STREAMINFO block; this is recommended but not
  92158. * necessary to create a valid FLAC stream. If
  92159. * \a seek_callback is not \c NULL then a
  92160. * \a tell_callback must also be supplied.
  92161. * Alternatively, a dummy seek callback that just
  92162. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  92163. * may also be supplied, all though this is slightly
  92164. * less efficient for the encoder.
  92165. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  92166. * pointer may be \c NULL if seeking is not
  92167. * supported. If \a seek_callback is \c NULL then
  92168. * this argument will be ignored. If
  92169. * \a seek_callback is not \c NULL then a
  92170. * \a tell_callback must also be supplied.
  92171. * Alternatively, a dummy tell callback that just
  92172. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  92173. * may also be supplied, all though this is slightly
  92174. * less efficient for the encoder.
  92175. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  92176. * pointer may be \c NULL if the callback is not
  92177. * desired. If the client provides a seek callback,
  92178. * this function is not necessary as the encoder
  92179. * will automatically seek back and update the
  92180. * STREAMINFO block. It may also be \c NULL if the
  92181. * client does not support seeking, since it will
  92182. * have no way of going back to update the
  92183. * STREAMINFO. However the client can still supply
  92184. * a callback if it would like to know the details
  92185. * from the STREAMINFO.
  92186. * \param client_data This value will be supplied to callbacks in their
  92187. * \a client_data argument.
  92188. * \assert
  92189. * \code encoder != NULL \endcode
  92190. * \retval FLAC__StreamEncoderInitStatus
  92191. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92192. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92193. */
  92194. 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);
  92195. /** Initialize the encoder instance to encode Ogg FLAC streams.
  92196. *
  92197. * This flavor of initialization sets up the encoder to encode to a FLAC
  92198. * stream in an Ogg container. I/O is performed via callbacks to the
  92199. * client. For encoding to a plain file via filename or open \c FILE*,
  92200. * FLAC__stream_encoder_init_ogg_file() and FLAC__stream_encoder_init_ogg_FILE()
  92201. * provide a simpler interface.
  92202. *
  92203. * This function should be called after FLAC__stream_encoder_new() and
  92204. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92205. * or FLAC__stream_encoder_process_interleaved().
  92206. * initialization succeeded.
  92207. *
  92208. * The call to FLAC__stream_encoder_init_ogg_stream() currently will also
  92209. * immediately call the write callback several times to write the metadata
  92210. * packets.
  92211. *
  92212. * \param encoder An uninitialized encoder instance.
  92213. * \param read_callback See FLAC__StreamEncoderReadCallback. This
  92214. * pointer must not be \c NULL if \a seek_callback
  92215. * is non-NULL since they are both needed to be
  92216. * able to write data back to the Ogg FLAC stream
  92217. * in the post-encode phase.
  92218. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  92219. * pointer must not be \c NULL.
  92220. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  92221. * pointer may be \c NULL if seeking is not
  92222. * supported. The encoder uses seeking to go back
  92223. * and write some some stream statistics to the
  92224. * STREAMINFO block; this is recommended but not
  92225. * necessary to create a valid FLAC stream. If
  92226. * \a seek_callback is not \c NULL then a
  92227. * \a tell_callback must also be supplied.
  92228. * Alternatively, a dummy seek callback that just
  92229. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  92230. * may also be supplied, all though this is slightly
  92231. * less efficient for the encoder.
  92232. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  92233. * pointer may be \c NULL if seeking is not
  92234. * supported. If \a seek_callback is \c NULL then
  92235. * this argument will be ignored. If
  92236. * \a seek_callback is not \c NULL then a
  92237. * \a tell_callback must also be supplied.
  92238. * Alternatively, a dummy tell callback that just
  92239. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  92240. * may also be supplied, all though this is slightly
  92241. * less efficient for the encoder.
  92242. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  92243. * pointer may be \c NULL if the callback is not
  92244. * desired. If the client provides a seek callback,
  92245. * this function is not necessary as the encoder
  92246. * will automatically seek back and update the
  92247. * STREAMINFO block. It may also be \c NULL if the
  92248. * client does not support seeking, since it will
  92249. * have no way of going back to update the
  92250. * STREAMINFO. However the client can still supply
  92251. * a callback if it would like to know the details
  92252. * from the STREAMINFO.
  92253. * \param client_data This value will be supplied to callbacks in their
  92254. * \a client_data argument.
  92255. * \assert
  92256. * \code encoder != NULL \endcode
  92257. * \retval FLAC__StreamEncoderInitStatus
  92258. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92259. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92260. */
  92261. 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);
  92262. /** Initialize the encoder instance to encode native FLAC files.
  92263. *
  92264. * This flavor of initialization sets up the encoder to encode to a
  92265. * plain native FLAC file. For non-stdio streams, you must use
  92266. * FLAC__stream_encoder_init_stream() and provide callbacks for the I/O.
  92267. *
  92268. * This function should be called after FLAC__stream_encoder_new() and
  92269. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92270. * or FLAC__stream_encoder_process_interleaved().
  92271. * initialization succeeded.
  92272. *
  92273. * \param encoder An uninitialized encoder instance.
  92274. * \param file An open file. The file should have been opened
  92275. * with mode \c "w+b" and rewound. The file
  92276. * becomes owned by the encoder and should not be
  92277. * manipulated by the client while encoding.
  92278. * Unless \a file is \c stdout, it will be closed
  92279. * when FLAC__stream_encoder_finish() is called.
  92280. * Note however that a proper SEEKTABLE cannot be
  92281. * created when encoding to \c stdout since it is
  92282. * not seekable.
  92283. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92284. * pointer may be \c NULL if the callback is not
  92285. * desired.
  92286. * \param client_data This value will be supplied to callbacks in their
  92287. * \a client_data argument.
  92288. * \assert
  92289. * \code encoder != NULL \endcode
  92290. * \code file != NULL \endcode
  92291. * \retval FLAC__StreamEncoderInitStatus
  92292. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92293. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92294. */
  92295. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92296. /** Initialize the encoder instance to encode Ogg FLAC files.
  92297. *
  92298. * This flavor of initialization sets up the encoder to encode to a
  92299. * plain Ogg FLAC file. For non-stdio streams, you must use
  92300. * FLAC__stream_encoder_init_ogg_stream() and provide callbacks for the I/O.
  92301. *
  92302. * This function should be called after FLAC__stream_encoder_new() and
  92303. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92304. * or FLAC__stream_encoder_process_interleaved().
  92305. * initialization succeeded.
  92306. *
  92307. * \param encoder An uninitialized encoder instance.
  92308. * \param file An open file. The file should have been opened
  92309. * with mode \c "w+b" and rewound. The file
  92310. * becomes owned by the encoder and should not be
  92311. * manipulated by the client while encoding.
  92312. * Unless \a file is \c stdout, it will be closed
  92313. * when FLAC__stream_encoder_finish() is called.
  92314. * Note however that a proper SEEKTABLE cannot be
  92315. * created when encoding to \c stdout since it is
  92316. * not seekable.
  92317. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92318. * pointer may be \c NULL if the callback is not
  92319. * desired.
  92320. * \param client_data This value will be supplied to callbacks in their
  92321. * \a client_data argument.
  92322. * \assert
  92323. * \code encoder != NULL \endcode
  92324. * \code file != NULL \endcode
  92325. * \retval FLAC__StreamEncoderInitStatus
  92326. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92327. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92328. */
  92329. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92330. /** Initialize the encoder instance to encode native FLAC files.
  92331. *
  92332. * This flavor of initialization sets up the encoder to encode to a plain
  92333. * FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  92334. * with Unicode filenames on Windows), you must use
  92335. * FLAC__stream_encoder_init_FILE(), or FLAC__stream_encoder_init_stream()
  92336. * and provide callbacks for the I/O.
  92337. *
  92338. * This function should be called after FLAC__stream_encoder_new() and
  92339. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92340. * or FLAC__stream_encoder_process_interleaved().
  92341. * initialization succeeded.
  92342. *
  92343. * \param encoder An uninitialized encoder instance.
  92344. * \param filename The name of the file to encode to. The file will
  92345. * be opened with fopen(). Use \c NULL to encode to
  92346. * \c stdout. Note however that a proper SEEKTABLE
  92347. * cannot be created when encoding to \c stdout since
  92348. * it is not seekable.
  92349. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92350. * pointer may be \c NULL if the callback is not
  92351. * desired.
  92352. * \param client_data This value will be supplied to callbacks in their
  92353. * \a client_data argument.
  92354. * \assert
  92355. * \code encoder != NULL \endcode
  92356. * \retval FLAC__StreamEncoderInitStatus
  92357. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92358. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92359. */
  92360. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92361. /** Initialize the encoder instance to encode Ogg FLAC files.
  92362. *
  92363. * This flavor of initialization sets up the encoder to encode to a plain
  92364. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  92365. * with Unicode filenames on Windows), you must use
  92366. * FLAC__stream_encoder_init_ogg_FILE(), or FLAC__stream_encoder_init_ogg_stream()
  92367. * and provide callbacks for the I/O.
  92368. *
  92369. * This function should be called after FLAC__stream_encoder_new() and
  92370. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92371. * or FLAC__stream_encoder_process_interleaved().
  92372. * initialization succeeded.
  92373. *
  92374. * \param encoder An uninitialized encoder instance.
  92375. * \param filename The name of the file to encode to. The file will
  92376. * be opened with fopen(). Use \c NULL to encode to
  92377. * \c stdout. Note however that a proper SEEKTABLE
  92378. * cannot be created when encoding to \c stdout since
  92379. * it is not seekable.
  92380. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92381. * pointer may be \c NULL if the callback is not
  92382. * desired.
  92383. * \param client_data This value will be supplied to callbacks in their
  92384. * \a client_data argument.
  92385. * \assert
  92386. * \code encoder != NULL \endcode
  92387. * \retval FLAC__StreamEncoderInitStatus
  92388. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92389. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92390. */
  92391. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92392. /** Finish the encoding process.
  92393. * Flushes the encoding buffer, releases resources, resets the encoder
  92394. * settings to their defaults, and returns the encoder state to
  92395. * FLAC__STREAM_ENCODER_UNINITIALIZED. Note that this can generate
  92396. * one or more write callbacks before returning, and will generate
  92397. * a metadata callback.
  92398. *
  92399. * Note that in the course of processing the last frame, errors can
  92400. * occur, so the caller should be sure to check the return value to
  92401. * ensure the file was encoded properly.
  92402. *
  92403. * In the event of a prematurely-terminated encode, it is not strictly
  92404. * necessary to call this immediately before FLAC__stream_encoder_delete()
  92405. * but it is good practice to match every FLAC__stream_encoder_init_*()
  92406. * with a FLAC__stream_encoder_finish().
  92407. *
  92408. * \param encoder An uninitialized encoder instance.
  92409. * \assert
  92410. * \code encoder != NULL \endcode
  92411. * \retval FLAC__bool
  92412. * \c false if an error occurred processing the last frame; or if verify
  92413. * mode is set (see FLAC__stream_encoder_set_verify()), there was a
  92414. * verify mismatch; else \c true. If \c false, caller should check the
  92415. * state with FLAC__stream_encoder_get_state() for more information
  92416. * about the error.
  92417. */
  92418. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder);
  92419. /** Submit data for encoding.
  92420. * This version allows you to supply the input data via an array of
  92421. * pointers, each pointer pointing to an array of \a samples samples
  92422. * representing one channel. The samples need not be block-aligned,
  92423. * but each channel should have the same number of samples. Each sample
  92424. * should be a signed integer, right-justified to the resolution set by
  92425. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  92426. * resolution is 16 bits per sample, the samples should all be in the
  92427. * range [-32768,32767].
  92428. *
  92429. * For applications where channel order is important, channels must
  92430. * follow the order as described in the
  92431. * <A HREF="../format.html#frame_header">frame header</A>.
  92432. *
  92433. * \param encoder An initialized encoder instance in the OK state.
  92434. * \param buffer An array of pointers to each channel's signal.
  92435. * \param samples The number of samples in one channel.
  92436. * \assert
  92437. * \code encoder != NULL \endcode
  92438. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  92439. * \retval FLAC__bool
  92440. * \c true if successful, else \c false; in this case, check the
  92441. * encoder state with FLAC__stream_encoder_get_state() to see what
  92442. * went wrong.
  92443. */
  92444. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples);
  92445. /** Submit data for encoding.
  92446. * This version allows you to supply the input data where the channels
  92447. * are interleaved into a single array (i.e. channel0_sample0,
  92448. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  92449. * The samples need not be block-aligned but they must be
  92450. * sample-aligned, i.e. the first value should be channel0_sample0
  92451. * and the last value channelN_sampleM. Each sample should be a signed
  92452. * integer, right-justified to the resolution set by
  92453. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  92454. * resolution is 16 bits per sample, the samples should all be in the
  92455. * range [-32768,32767].
  92456. *
  92457. * For applications where channel order is important, channels must
  92458. * follow the order as described in the
  92459. * <A HREF="../format.html#frame_header">frame header</A>.
  92460. *
  92461. * \param encoder An initialized encoder instance in the OK state.
  92462. * \param buffer An array of channel-interleaved data (see above).
  92463. * \param samples The number of samples in one channel, the same as for
  92464. * FLAC__stream_encoder_process(). For example, if
  92465. * encoding two channels, \c 1000 \a samples corresponds
  92466. * to a \a buffer of 2000 values.
  92467. * \assert
  92468. * \code encoder != NULL \endcode
  92469. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  92470. * \retval FLAC__bool
  92471. * \c true if successful, else \c false; in this case, check the
  92472. * encoder state with FLAC__stream_encoder_get_state() to see what
  92473. * went wrong.
  92474. */
  92475. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples);
  92476. /* \} */
  92477. #ifdef __cplusplus
  92478. }
  92479. #endif
  92480. #endif
  92481. /*** End of inlined file: stream_encoder.h ***/
  92482. #ifdef _MSC_VER
  92483. /* OPT: an MSVC built-in would be better */
  92484. static _inline FLAC__uint32 local_swap32_(FLAC__uint32 x)
  92485. {
  92486. x = ((x<<8)&0xFF00FF00) | ((x>>8)&0x00FF00FF);
  92487. return (x>>16) | (x<<16);
  92488. }
  92489. #endif
  92490. #if defined(_MSC_VER) && defined(_X86_)
  92491. /* OPT: an MSVC built-in would be better */
  92492. static void local_swap32_block_(FLAC__uint32 *start, FLAC__uint32 len)
  92493. {
  92494. __asm {
  92495. mov edx, start
  92496. mov ecx, len
  92497. test ecx, ecx
  92498. loop1:
  92499. jz done1
  92500. mov eax, [edx]
  92501. bswap eax
  92502. mov [edx], eax
  92503. add edx, 4
  92504. dec ecx
  92505. jmp short loop1
  92506. done1:
  92507. }
  92508. }
  92509. #endif
  92510. /** \mainpage
  92511. *
  92512. * \section intro Introduction
  92513. *
  92514. * This is the documentation for the FLAC C and C++ APIs. It is
  92515. * highly interconnected; this introduction should give you a top
  92516. * level idea of the structure and how to find the information you
  92517. * need. As a prerequisite you should have at least a basic
  92518. * knowledge of the FLAC format, documented
  92519. * <A HREF="../format.html">here</A>.
  92520. *
  92521. * \section c_api FLAC C API
  92522. *
  92523. * The FLAC C API is the interface to libFLAC, a set of structures
  92524. * describing the components of FLAC streams, and functions for
  92525. * encoding and decoding streams, as well as manipulating FLAC
  92526. * metadata in files. The public include files will be installed
  92527. * in your include area (for example /usr/include/FLAC/...).
  92528. *
  92529. * By writing a little code and linking against libFLAC, it is
  92530. * relatively easy to add FLAC support to another program. The
  92531. * library is licensed under <A HREF="../license.html">Xiph's BSD license</A>.
  92532. * Complete source code of libFLAC as well as the command-line
  92533. * encoder and plugins is available and is a useful source of
  92534. * examples.
  92535. *
  92536. * Aside from encoders and decoders, libFLAC provides a powerful
  92537. * metadata interface for manipulating metadata in FLAC files. It
  92538. * allows the user to add, delete, and modify FLAC metadata blocks
  92539. * and it can automatically take advantage of PADDING blocks to avoid
  92540. * rewriting the entire FLAC file when changing the size of the
  92541. * metadata.
  92542. *
  92543. * libFLAC usually only requires the standard C library and C math
  92544. * library. In particular, threading is not used so there is no
  92545. * dependency on a thread library. However, libFLAC does not use
  92546. * global variables and should be thread-safe.
  92547. *
  92548. * libFLAC also supports encoding to and decoding from Ogg FLAC.
  92549. * However the metadata editing interfaces currently have limited
  92550. * read-only support for Ogg FLAC files.
  92551. *
  92552. * \section cpp_api FLAC C++ API
  92553. *
  92554. * The FLAC C++ API is a set of classes that encapsulate the
  92555. * structures and functions in libFLAC. They provide slightly more
  92556. * functionality with respect to metadata but are otherwise
  92557. * equivalent. For the most part, they share the same usage as
  92558. * their counterparts in libFLAC, and the FLAC C API documentation
  92559. * can be used as a supplement. The public include files
  92560. * for the C++ API will be installed in your include area (for
  92561. * example /usr/include/FLAC++/...).
  92562. *
  92563. * libFLAC++ is also licensed under
  92564. * <A HREF="../license.html">Xiph's BSD license</A>.
  92565. *
  92566. * \section getting_started Getting Started
  92567. *
  92568. * A good starting point for learning the API is to browse through
  92569. * the <A HREF="modules.html">modules</A>. Modules are logical
  92570. * groupings of related functions or classes, which correspond roughly
  92571. * to header files or sections of header files. Each module includes a
  92572. * detailed description of the general usage of its functions or
  92573. * classes.
  92574. *
  92575. * From there you can go on to look at the documentation of
  92576. * individual functions. You can see different views of the individual
  92577. * functions through the links in top bar across this page.
  92578. *
  92579. * If you prefer a more hands-on approach, you can jump right to some
  92580. * <A HREF="../documentation_example_code.html">example code</A>.
  92581. *
  92582. * \section porting_guide Porting Guide
  92583. *
  92584. * Starting with FLAC 1.1.3 a \link porting Porting Guide \endlink
  92585. * has been introduced which gives detailed instructions on how to
  92586. * port your code to newer versions of FLAC.
  92587. *
  92588. * \section embedded_developers Embedded Developers
  92589. *
  92590. * libFLAC has grown larger over time as more functionality has been
  92591. * included, but much of it may be unnecessary for a particular embedded
  92592. * implementation. Unused parts may be pruned by some simple editing of
  92593. * src/libFLAC/Makefile.am. In general, the decoders, encoders, and
  92594. * metadata interface are all independent from each other.
  92595. *
  92596. * It is easiest to just describe the dependencies:
  92597. *
  92598. * - All modules depend on the \link flac_format Format \endlink module.
  92599. * - The decoders and encoders depend on the bitbuffer.
  92600. * - The decoder is independent of the encoder. The encoder uses the
  92601. * decoder because of the verify feature, but this can be removed if
  92602. * not needed.
  92603. * - Parts of the metadata interface require the stream decoder (but not
  92604. * the encoder).
  92605. * - Ogg support is selectable through the compile time macro
  92606. * \c FLAC__HAS_OGG.
  92607. *
  92608. * For example, if your application only requires the stream decoder, no
  92609. * encoder, and no metadata interface, you can remove the stream encoder
  92610. * and the metadata interface, which will greatly reduce the size of the
  92611. * library.
  92612. *
  92613. * Also, there are several places in the libFLAC code with comments marked
  92614. * with "OPT:" where a #define can be changed to enable code that might be
  92615. * faster on a specific platform. Experimenting with these can yield faster
  92616. * binaries.
  92617. */
  92618. /** \defgroup porting Porting Guide for New Versions
  92619. *
  92620. * This module describes differences in the library interfaces from
  92621. * version to version. It assists in the porting of code that uses
  92622. * the libraries to newer versions of FLAC.
  92623. *
  92624. * One simple facility for making porting easier that has been added
  92625. * in FLAC 1.1.3 is a set of \c #defines in \c export.h of each
  92626. * library's includes (e.g. \c include/FLAC/export.h). The
  92627. * \c #defines mirror the libraries'
  92628. * <A HREF="http://www.gnu.org/software/libtool/manual.html#Libtool-versioning">libtool version numbers</A>,
  92629. * e.g. in libFLAC there are \c FLAC_API_VERSION_CURRENT,
  92630. * \c FLAC_API_VERSION_REVISION, and \c FLAC_API_VERSION_AGE.
  92631. * These can be used to support multiple versions of an API during the
  92632. * transition phase, e.g.
  92633. *
  92634. * \code
  92635. * #if !defined(FLAC_API_VERSION_CURRENT) || FLAC_API_VERSION_CURRENT <= 7
  92636. * legacy code
  92637. * #else
  92638. * new code
  92639. * #endif
  92640. * \endcode
  92641. *
  92642. * The the source will work for multiple versions and the legacy code can
  92643. * easily be removed when the transition is complete.
  92644. *
  92645. * Another available symbol is FLAC_API_SUPPORTS_OGG_FLAC (defined in
  92646. * include/FLAC/export.h), which can be used to determine whether or not
  92647. * the library has been compiled with support for Ogg FLAC. This is
  92648. * simpler than trying to call an Ogg init function and catching the
  92649. * error.
  92650. */
  92651. /** \defgroup porting_1_1_2_to_1_1_3 Porting from FLAC 1.1.2 to 1.1.3
  92652. * \ingroup porting
  92653. *
  92654. * \brief
  92655. * This module describes porting from FLAC 1.1.2 to FLAC 1.1.3.
  92656. *
  92657. * The main change between the APIs in 1.1.2 and 1.1.3 is that they have
  92658. * been simplified. First, libOggFLAC has been merged into libFLAC and
  92659. * libOggFLAC++ has been merged into libFLAC++. Second, both the three
  92660. * decoding layers and three encoding layers have been merged into a
  92661. * single stream decoder and stream encoder. That is, the functionality
  92662. * of FLAC__SeekableStreamDecoder and FLAC__FileDecoder has been merged
  92663. * into FLAC__StreamDecoder, and FLAC__SeekableStreamEncoder and
  92664. * FLAC__FileEncoder into FLAC__StreamEncoder. Only the
  92665. * FLAC__StreamDecoder and FLAC__StreamEncoder remain. What this means
  92666. * is there is now a single API that can be used to encode or decode
  92667. * streams to/from native FLAC or Ogg FLAC and the single API can work
  92668. * on both seekable and non-seekable streams.
  92669. *
  92670. * Instead of creating an encoder or decoder of a certain layer, now the
  92671. * client will always create a FLAC__StreamEncoder or
  92672. * FLAC__StreamDecoder. The old layers are now differentiated by the
  92673. * initialization function. For example, for the decoder,
  92674. * FLAC__stream_decoder_init() has been replaced by
  92675. * FLAC__stream_decoder_init_stream(). This init function takes
  92676. * callbacks for the I/O, and the seeking callbacks are optional. This
  92677. * allows the client to use the same object for seekable and
  92678. * non-seekable streams. For decoding a FLAC file directly, the client
  92679. * can use FLAC__stream_decoder_init_file() and pass just a filename
  92680. * and fewer callbacks; most of the other callbacks are supplied
  92681. * internally. For situations where fopen()ing by filename is not
  92682. * possible (e.g. Unicode filenames on Windows) the client can instead
  92683. * open the file itself and supply the FILE* to
  92684. * FLAC__stream_decoder_init_FILE(). The init functions now returns a
  92685. * FLAC__StreamDecoderInitStatus instead of FLAC__StreamDecoderState.
  92686. * Since the callbacks and client data are now passed to the init
  92687. * function, the FLAC__stream_decoder_set_*_callback() functions and
  92688. * FLAC__stream_decoder_set_client_data() are no longer needed. The
  92689. * rest of the calls to the decoder are the same as before.
  92690. *
  92691. * There are counterpart init functions for Ogg FLAC, e.g.
  92692. * FLAC__stream_decoder_init_ogg_stream(). All the rest of the calls
  92693. * and callbacks are the same as for native FLAC.
  92694. *
  92695. * As an example, in FLAC 1.1.2 a seekable stream decoder would have
  92696. * been set up like so:
  92697. *
  92698. * \code
  92699. * FLAC__SeekableStreamDecoder *decoder = FLAC__seekable_stream_decoder_new();
  92700. * if(decoder == NULL) do_something;
  92701. * FLAC__seekable_stream_decoder_set_md5_checking(decoder, true);
  92702. * [... other settings ...]
  92703. * FLAC__seekable_stream_decoder_set_read_callback(decoder, my_read_callback);
  92704. * FLAC__seekable_stream_decoder_set_seek_callback(decoder, my_seek_callback);
  92705. * FLAC__seekable_stream_decoder_set_tell_callback(decoder, my_tell_callback);
  92706. * FLAC__seekable_stream_decoder_set_length_callback(decoder, my_length_callback);
  92707. * FLAC__seekable_stream_decoder_set_eof_callback(decoder, my_eof_callback);
  92708. * FLAC__seekable_stream_decoder_set_write_callback(decoder, my_write_callback);
  92709. * FLAC__seekable_stream_decoder_set_metadata_callback(decoder, my_metadata_callback);
  92710. * FLAC__seekable_stream_decoder_set_error_callback(decoder, my_error_callback);
  92711. * FLAC__seekable_stream_decoder_set_client_data(decoder, my_client_data);
  92712. * if(FLAC__seekable_stream_decoder_init(decoder) != FLAC__SEEKABLE_STREAM_DECODER_OK) do_something;
  92713. * \endcode
  92714. *
  92715. * In FLAC 1.1.3 it is like this:
  92716. *
  92717. * \code
  92718. * FLAC__StreamDecoder *decoder = FLAC__stream_decoder_new();
  92719. * if(decoder == NULL) do_something;
  92720. * FLAC__stream_decoder_set_md5_checking(decoder, true);
  92721. * [... other settings ...]
  92722. * if(FLAC__stream_decoder_init_stream(
  92723. * decoder,
  92724. * my_read_callback,
  92725. * my_seek_callback, // or NULL
  92726. * my_tell_callback, // or NULL
  92727. * my_length_callback, // or NULL
  92728. * my_eof_callback, // or NULL
  92729. * my_write_callback,
  92730. * my_metadata_callback, // or NULL
  92731. * my_error_callback,
  92732. * my_client_data
  92733. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92734. * \endcode
  92735. *
  92736. * or you could do;
  92737. *
  92738. * \code
  92739. * [...]
  92740. * FILE *file = fopen("somefile.flac","rb");
  92741. * if(file == NULL) do_somthing;
  92742. * if(FLAC__stream_decoder_init_FILE(
  92743. * decoder,
  92744. * file,
  92745. * my_write_callback,
  92746. * my_metadata_callback, // or NULL
  92747. * my_error_callback,
  92748. * my_client_data
  92749. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92750. * \endcode
  92751. *
  92752. * or just:
  92753. *
  92754. * \code
  92755. * [...]
  92756. * if(FLAC__stream_decoder_init_file(
  92757. * decoder,
  92758. * "somefile.flac",
  92759. * my_write_callback,
  92760. * my_metadata_callback, // or NULL
  92761. * my_error_callback,
  92762. * my_client_data
  92763. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92764. * \endcode
  92765. *
  92766. * Another small change to the decoder is in how it handles unparseable
  92767. * streams. Before, when the decoder found an unparseable stream
  92768. * (reserved for when the decoder encounters a stream from a future
  92769. * encoder that it can't parse), it changed the state to
  92770. * \c FLAC__STREAM_DECODER_UNPARSEABLE_STREAM. Now the decoder instead
  92771. * drops sync and calls the error callback with a new error code
  92772. * \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM. This is
  92773. * more robust. If your error callback does not discriminate on the the
  92774. * error state, your code does not need to be changed.
  92775. *
  92776. * The encoder now has a new setting:
  92777. * FLAC__stream_encoder_set_apodization(). This is for setting the
  92778. * method used to window the data before LPC analysis. You only need to
  92779. * add a call to this function if the default is not suitable. There
  92780. * are also two new convenience functions that may be useful:
  92781. * FLAC__metadata_object_cuesheet_calculate_cddb_id() and
  92782. * FLAC__metadata_get_cuesheet().
  92783. *
  92784. * The \a bytes parameter to FLAC__StreamDecoderReadCallback,
  92785. * FLAC__StreamEncoderReadCallback, and FLAC__StreamEncoderWriteCallback
  92786. * is now \c size_t instead of \c unsigned.
  92787. */
  92788. /** \defgroup porting_1_1_3_to_1_1_4 Porting from FLAC 1.1.3 to 1.1.4
  92789. * \ingroup porting
  92790. *
  92791. * \brief
  92792. * This module describes porting from FLAC 1.1.3 to FLAC 1.1.4.
  92793. *
  92794. * There were no changes to any of the interfaces from 1.1.3 to 1.1.4.
  92795. * There was a slight change in the implementation of
  92796. * FLAC__stream_encoder_set_metadata(); the function now makes a copy
  92797. * of the \a metadata array of pointers so the client no longer needs
  92798. * to maintain it after the call. The objects themselves that are
  92799. * pointed to by the array are still not copied though and must be
  92800. * maintained until the call to FLAC__stream_encoder_finish().
  92801. */
  92802. /** \defgroup porting_1_1_4_to_1_2_0 Porting from FLAC 1.1.4 to 1.2.0
  92803. * \ingroup porting
  92804. *
  92805. * \brief
  92806. * This module describes porting from FLAC 1.1.4 to FLAC 1.2.0.
  92807. *
  92808. * There were only very minor changes to the interfaces from 1.1.4 to 1.2.0.
  92809. * In libFLAC, \c FLAC__format_sample_rate_is_subset() was added.
  92810. * In libFLAC++, \c FLAC::Decoder::Stream::get_decode_position() was added.
  92811. *
  92812. * Finally, value of the constant \c FLAC__FRAME_HEADER_RESERVED_LEN
  92813. * has changed to reflect the conversion of one of the reserved bits
  92814. * into active use. It used to be \c 2 and now is \c 1. However the
  92815. * FLAC frame header length has not changed, so to skip the proper
  92816. * number of bits, use \c FLAC__FRAME_HEADER_RESERVED_LEN +
  92817. * \c FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN
  92818. */
  92819. /** \defgroup flac FLAC C API
  92820. *
  92821. * The FLAC C API is the interface to libFLAC, a set of structures
  92822. * describing the components of FLAC streams, and functions for
  92823. * encoding and decoding streams, as well as manipulating FLAC
  92824. * metadata in files.
  92825. *
  92826. * You should start with the format components as all other modules
  92827. * are dependent on it.
  92828. */
  92829. #endif
  92830. /*** End of inlined file: all.h ***/
  92831. /*** Start of inlined file: bitmath.c ***/
  92832. /*** Start of inlined file: juce_FlacHeader.h ***/
  92833. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92834. // tasks..
  92835. #define VERSION "1.2.1"
  92836. #define FLAC__NO_DLL 1
  92837. #if JUCE_MSVC
  92838. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92839. #endif
  92840. #if JUCE_MAC
  92841. #define FLAC__SYS_DARWIN 1
  92842. #endif
  92843. /*** End of inlined file: juce_FlacHeader.h ***/
  92844. #if JUCE_USE_FLAC
  92845. #if HAVE_CONFIG_H
  92846. # include <config.h>
  92847. #endif
  92848. /*** Start of inlined file: bitmath.h ***/
  92849. #ifndef FLAC__PRIVATE__BITMATH_H
  92850. #define FLAC__PRIVATE__BITMATH_H
  92851. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v);
  92852. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v);
  92853. unsigned FLAC__bitmath_silog2(int v);
  92854. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v);
  92855. #endif
  92856. /*** End of inlined file: bitmath.h ***/
  92857. /* An example of what FLAC__bitmath_ilog2() computes:
  92858. *
  92859. * ilog2( 0) = assertion failure
  92860. * ilog2( 1) = 0
  92861. * ilog2( 2) = 1
  92862. * ilog2( 3) = 1
  92863. * ilog2( 4) = 2
  92864. * ilog2( 5) = 2
  92865. * ilog2( 6) = 2
  92866. * ilog2( 7) = 2
  92867. * ilog2( 8) = 3
  92868. * ilog2( 9) = 3
  92869. * ilog2(10) = 3
  92870. * ilog2(11) = 3
  92871. * ilog2(12) = 3
  92872. * ilog2(13) = 3
  92873. * ilog2(14) = 3
  92874. * ilog2(15) = 3
  92875. * ilog2(16) = 4
  92876. * ilog2(17) = 4
  92877. * ilog2(18) = 4
  92878. */
  92879. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v)
  92880. {
  92881. unsigned l = 0;
  92882. FLAC__ASSERT(v > 0);
  92883. while(v >>= 1)
  92884. l++;
  92885. return l;
  92886. }
  92887. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v)
  92888. {
  92889. unsigned l = 0;
  92890. FLAC__ASSERT(v > 0);
  92891. while(v >>= 1)
  92892. l++;
  92893. return l;
  92894. }
  92895. /* An example of what FLAC__bitmath_silog2() computes:
  92896. *
  92897. * silog2(-10) = 5
  92898. * silog2(- 9) = 5
  92899. * silog2(- 8) = 4
  92900. * silog2(- 7) = 4
  92901. * silog2(- 6) = 4
  92902. * silog2(- 5) = 4
  92903. * silog2(- 4) = 3
  92904. * silog2(- 3) = 3
  92905. * silog2(- 2) = 2
  92906. * silog2(- 1) = 2
  92907. * silog2( 0) = 0
  92908. * silog2( 1) = 2
  92909. * silog2( 2) = 3
  92910. * silog2( 3) = 3
  92911. * silog2( 4) = 4
  92912. * silog2( 5) = 4
  92913. * silog2( 6) = 4
  92914. * silog2( 7) = 4
  92915. * silog2( 8) = 5
  92916. * silog2( 9) = 5
  92917. * silog2( 10) = 5
  92918. */
  92919. unsigned FLAC__bitmath_silog2(int v)
  92920. {
  92921. while(1) {
  92922. if(v == 0) {
  92923. return 0;
  92924. }
  92925. else if(v > 0) {
  92926. unsigned l = 0;
  92927. while(v) {
  92928. l++;
  92929. v >>= 1;
  92930. }
  92931. return l+1;
  92932. }
  92933. else if(v == -1) {
  92934. return 2;
  92935. }
  92936. else {
  92937. v++;
  92938. v = -v;
  92939. }
  92940. }
  92941. }
  92942. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v)
  92943. {
  92944. while(1) {
  92945. if(v == 0) {
  92946. return 0;
  92947. }
  92948. else if(v > 0) {
  92949. unsigned l = 0;
  92950. while(v) {
  92951. l++;
  92952. v >>= 1;
  92953. }
  92954. return l+1;
  92955. }
  92956. else if(v == -1) {
  92957. return 2;
  92958. }
  92959. else {
  92960. v++;
  92961. v = -v;
  92962. }
  92963. }
  92964. }
  92965. #endif
  92966. /*** End of inlined file: bitmath.c ***/
  92967. /*** Start of inlined file: bitreader.c ***/
  92968. /*** Start of inlined file: juce_FlacHeader.h ***/
  92969. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92970. // tasks..
  92971. #define VERSION "1.2.1"
  92972. #define FLAC__NO_DLL 1
  92973. #if JUCE_MSVC
  92974. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92975. #endif
  92976. #if JUCE_MAC
  92977. #define FLAC__SYS_DARWIN 1
  92978. #endif
  92979. /*** End of inlined file: juce_FlacHeader.h ***/
  92980. #if JUCE_USE_FLAC
  92981. #if HAVE_CONFIG_H
  92982. # include <config.h>
  92983. #endif
  92984. #include <stdlib.h> /* for malloc() */
  92985. #include <string.h> /* for memcpy(), memset() */
  92986. #ifdef _MSC_VER
  92987. #include <winsock.h> /* for ntohl() */
  92988. #elif defined FLAC__SYS_DARWIN
  92989. #include <machine/endian.h> /* for ntohl() */
  92990. #elif defined __MINGW32__
  92991. #include <winsock.h> /* for ntohl() */
  92992. #else
  92993. #include <netinet/in.h> /* for ntohl() */
  92994. #endif
  92995. /*** Start of inlined file: bitreader.h ***/
  92996. #ifndef FLAC__PRIVATE__BITREADER_H
  92997. #define FLAC__PRIVATE__BITREADER_H
  92998. #include <stdio.h> /* for FILE */
  92999. /*** Start of inlined file: cpu.h ***/
  93000. #ifndef FLAC__PRIVATE__CPU_H
  93001. #define FLAC__PRIVATE__CPU_H
  93002. #ifdef HAVE_CONFIG_H
  93003. #include <config.h>
  93004. #endif
  93005. typedef enum {
  93006. FLAC__CPUINFO_TYPE_IA32,
  93007. FLAC__CPUINFO_TYPE_PPC,
  93008. FLAC__CPUINFO_TYPE_UNKNOWN
  93009. } FLAC__CPUInfo_Type;
  93010. typedef struct {
  93011. FLAC__bool cpuid;
  93012. FLAC__bool bswap;
  93013. FLAC__bool cmov;
  93014. FLAC__bool mmx;
  93015. FLAC__bool fxsr;
  93016. FLAC__bool sse;
  93017. FLAC__bool sse2;
  93018. FLAC__bool sse3;
  93019. FLAC__bool ssse3;
  93020. FLAC__bool _3dnow;
  93021. FLAC__bool ext3dnow;
  93022. FLAC__bool extmmx;
  93023. } FLAC__CPUInfo_IA32;
  93024. typedef struct {
  93025. FLAC__bool altivec;
  93026. FLAC__bool ppc64;
  93027. } FLAC__CPUInfo_PPC;
  93028. typedef struct {
  93029. FLAC__bool use_asm;
  93030. FLAC__CPUInfo_Type type;
  93031. union {
  93032. FLAC__CPUInfo_IA32 ia32;
  93033. FLAC__CPUInfo_PPC ppc;
  93034. } data;
  93035. } FLAC__CPUInfo;
  93036. void FLAC__cpu_info(FLAC__CPUInfo *info);
  93037. #ifndef FLAC__NO_ASM
  93038. #ifdef FLAC__CPU_IA32
  93039. #ifdef FLAC__HAS_NASM
  93040. FLAC__uint32 FLAC__cpu_have_cpuid_asm_ia32(void);
  93041. void FLAC__cpu_info_asm_ia32(FLAC__uint32 *flags_edx, FLAC__uint32 *flags_ecx);
  93042. FLAC__uint32 FLAC__cpu_info_extended_amd_asm_ia32(void);
  93043. #endif
  93044. #endif
  93045. #endif
  93046. #endif
  93047. /*** End of inlined file: cpu.h ***/
  93048. /*
  93049. * opaque structure definition
  93050. */
  93051. struct FLAC__BitReader;
  93052. typedef struct FLAC__BitReader FLAC__BitReader;
  93053. typedef FLAC__bool (*FLAC__BitReaderReadCallback)(FLAC__byte buffer[], size_t *bytes, void *client_data);
  93054. /*
  93055. * construction, deletion, initialization, etc functions
  93056. */
  93057. FLAC__BitReader *FLAC__bitreader_new(void);
  93058. void FLAC__bitreader_delete(FLAC__BitReader *br);
  93059. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd);
  93060. void FLAC__bitreader_free(FLAC__BitReader *br); /* does not 'free(br)' */
  93061. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br);
  93062. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out);
  93063. /*
  93064. * CRC functions
  93065. */
  93066. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed);
  93067. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br);
  93068. /*
  93069. * info functions
  93070. */
  93071. FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br);
  93072. unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br);
  93073. unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br);
  93074. /*
  93075. * read functions
  93076. */
  93077. FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits);
  93078. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits);
  93079. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits);
  93080. FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val); /*only for bits=32*/
  93081. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits); /* WATCHOUT: does not CRC the skipped data! */ /*@@@@ add to unit tests */
  93082. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals); /* WATCHOUT: does not CRC the read data! */
  93083. 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! */
  93084. FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val);
  93085. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  93086. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  93087. #ifndef FLAC__NO_ASM
  93088. # ifdef FLAC__CPU_IA32
  93089. # ifdef FLAC__HAS_NASM
  93090. FLAC__bool FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  93091. # endif
  93092. # endif
  93093. #endif
  93094. #if 0 /* UNUSED */
  93095. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  93096. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter);
  93097. #endif
  93098. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen);
  93099. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen);
  93100. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br);
  93101. #endif
  93102. /*** End of inlined file: bitreader.h ***/
  93103. /*** Start of inlined file: crc.h ***/
  93104. #ifndef FLAC__PRIVATE__CRC_H
  93105. #define FLAC__PRIVATE__CRC_H
  93106. /* 8 bit CRC generator, MSB shifted first
  93107. ** polynomial = x^8 + x^2 + x^1 + x^0
  93108. ** init = 0
  93109. */
  93110. extern FLAC__byte const FLAC__crc8_table[256];
  93111. #define FLAC__CRC8_UPDATE(data, crc) (crc) = FLAC__crc8_table[(crc) ^ (data)];
  93112. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc);
  93113. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc);
  93114. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len);
  93115. /* 16 bit CRC generator, MSB shifted first
  93116. ** polynomial = x^16 + x^15 + x^2 + x^0
  93117. ** init = 0
  93118. */
  93119. extern unsigned FLAC__crc16_table[256];
  93120. #define FLAC__CRC16_UPDATE(data, crc) (((((crc)<<8) & 0xffff) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]))
  93121. /* this alternate may be faster on some systems/compilers */
  93122. #if 0
  93123. #define FLAC__CRC16_UPDATE(data, crc) ((((crc)<<8) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]) & 0xffff)
  93124. #endif
  93125. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len);
  93126. #endif
  93127. /*** End of inlined file: crc.h ***/
  93128. /* Things should be fastest when this matches the machine word size */
  93129. /* WATCHOUT: if you change this you must also change the following #defines down to COUNT_ZERO_MSBS below to match */
  93130. /* WATCHOUT: there are a few places where the code will not work unless brword is >= 32 bits wide */
  93131. /* also, some sections currently only have fast versions for 4 or 8 bytes per word */
  93132. typedef FLAC__uint32 brword;
  93133. #define FLAC__BYTES_PER_WORD 4
  93134. #define FLAC__BITS_PER_WORD 32
  93135. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  93136. /* SWAP_BE_WORD_TO_HOST swaps bytes in a brword (which is always big-endian) if necessary to match host byte order */
  93137. #if WORDS_BIGENDIAN
  93138. #define SWAP_BE_WORD_TO_HOST(x) (x)
  93139. #else
  93140. #if defined (_MSC_VER) && defined (_X86_)
  93141. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  93142. #else
  93143. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  93144. #endif
  93145. #endif
  93146. /* counts the # of zero MSBs in a word */
  93147. #define COUNT_ZERO_MSBS(word) ( \
  93148. (word) <= 0xffff ? \
  93149. ( (word) <= 0xff? byte_to_unary_table[word] + 24 : byte_to_unary_table[(word) >> 8] + 16 ) : \
  93150. ( (word) <= 0xffffff? byte_to_unary_table[word >> 16] + 8 : byte_to_unary_table[(word) >> 24] ) \
  93151. )
  93152. /* this alternate might be slightly faster on some systems/compilers: */
  93153. #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])) )
  93154. /*
  93155. * This should be at least twice as large as the largest number of words
  93156. * required to represent any 'number' (in any encoding) you are going to
  93157. * read. With FLAC this is on the order of maybe a few hundred bits.
  93158. * If the buffer is smaller than that, the decoder won't be able to read
  93159. * in a whole number that is in a variable length encoding (e.g. Rice).
  93160. * But to be practical it should be at least 1K bytes.
  93161. *
  93162. * Increase this number to decrease the number of read callbacks, at the
  93163. * expense of using more memory. Or decrease for the reverse effect,
  93164. * keeping in mind the limit from the first paragraph. The optimal size
  93165. * also depends on the CPU cache size and other factors; some twiddling
  93166. * may be necessary to squeeze out the best performance.
  93167. */
  93168. static const unsigned FLAC__BITREADER_DEFAULT_CAPACITY = 65536u / FLAC__BITS_PER_WORD; /* in words */
  93169. static const unsigned char byte_to_unary_table[] = {
  93170. 8, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4,
  93171. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  93172. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  93173. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  93174. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  93175. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  93176. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  93177. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  93178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
  93186. };
  93187. #ifdef min
  93188. #undef min
  93189. #endif
  93190. #define min(x,y) ((x)<(y)?(x):(y))
  93191. #ifdef max
  93192. #undef max
  93193. #endif
  93194. #define max(x,y) ((x)>(y)?(x):(y))
  93195. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  93196. #ifdef _MSC_VER
  93197. #define FLAC__U64L(x) x
  93198. #else
  93199. #define FLAC__U64L(x) x##LLU
  93200. #endif
  93201. #ifndef FLaC__INLINE
  93202. #define FLaC__INLINE
  93203. #endif
  93204. /* WATCHOUT: assembly routines rely on the order in which these fields are declared */
  93205. struct FLAC__BitReader {
  93206. /* any partially-consumed word at the head will stay right-justified as bits are consumed from the left */
  93207. /* any incomplete word at the tail will be left-justified, and bytes from the read callback are added on the right */
  93208. brword *buffer;
  93209. unsigned capacity; /* in words */
  93210. unsigned words; /* # of completed words in buffer */
  93211. unsigned bytes; /* # of bytes in incomplete word at buffer[words] */
  93212. unsigned consumed_words; /* #words ... */
  93213. unsigned consumed_bits; /* ... + (#bits of head word) already consumed from the front of buffer */
  93214. unsigned read_crc16; /* the running frame CRC */
  93215. unsigned crc16_align; /* the number of bits in the current consumed word that should not be CRC'd */
  93216. FLAC__BitReaderReadCallback read_callback;
  93217. void *client_data;
  93218. FLAC__CPUInfo cpu_info;
  93219. };
  93220. static FLaC__INLINE void crc16_update_word_(FLAC__BitReader *br, brword word)
  93221. {
  93222. register unsigned crc = br->read_crc16;
  93223. #if FLAC__BYTES_PER_WORD == 4
  93224. switch(br->crc16_align) {
  93225. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 24), crc);
  93226. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  93227. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  93228. case 24: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  93229. }
  93230. #elif FLAC__BYTES_PER_WORD == 8
  93231. switch(br->crc16_align) {
  93232. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 56), crc);
  93233. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 48) & 0xff), crc);
  93234. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 40) & 0xff), crc);
  93235. case 24: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 32) & 0xff), crc);
  93236. case 32: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 24) & 0xff), crc);
  93237. case 40: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  93238. case 48: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  93239. case 56: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  93240. }
  93241. #else
  93242. for( ; br->crc16_align < FLAC__BITS_PER_WORD; br->crc16_align += 8)
  93243. crc = FLAC__CRC16_UPDATE((unsigned)((word >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), crc);
  93244. br->read_crc16 = crc;
  93245. #endif
  93246. br->crc16_align = 0;
  93247. }
  93248. /* would be static except it needs to be called by asm routines */
  93249. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br)
  93250. {
  93251. unsigned start, end;
  93252. size_t bytes;
  93253. FLAC__byte *target;
  93254. /* first shift the unconsumed buffer data toward the front as much as possible */
  93255. if(br->consumed_words > 0) {
  93256. start = br->consumed_words;
  93257. end = br->words + (br->bytes? 1:0);
  93258. memmove(br->buffer, br->buffer+start, FLAC__BYTES_PER_WORD * (end - start));
  93259. br->words -= start;
  93260. br->consumed_words = 0;
  93261. }
  93262. /*
  93263. * set the target for reading, taking into account word alignment and endianness
  93264. */
  93265. bytes = (br->capacity - br->words) * FLAC__BYTES_PER_WORD - br->bytes;
  93266. if(bytes == 0)
  93267. return false; /* no space left, buffer is too small; see note for FLAC__BITREADER_DEFAULT_CAPACITY */
  93268. target = ((FLAC__byte*)(br->buffer+br->words)) + br->bytes;
  93269. /* before reading, if the existing reader looks like this (say brword is 32 bits wide)
  93270. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1 (partial tail word is left-justified)
  93271. * buffer[BE]: 11 22 33 44 55 ?? ?? ?? (shown layed out as bytes sequentially in memory)
  93272. * buffer[LE]: 44 33 22 11 ?? ?? ?? 55 (?? being don't-care)
  93273. * ^^-------target, bytes=3
  93274. * on LE machines, have to byteswap the odd tail word so nothing is
  93275. * overwritten:
  93276. */
  93277. #if WORDS_BIGENDIAN
  93278. #else
  93279. if(br->bytes)
  93280. br->buffer[br->words] = SWAP_BE_WORD_TO_HOST(br->buffer[br->words]);
  93281. #endif
  93282. /* now it looks like:
  93283. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1
  93284. * buffer[BE]: 11 22 33 44 55 ?? ?? ??
  93285. * buffer[LE]: 44 33 22 11 55 ?? ?? ??
  93286. * ^^-------target, bytes=3
  93287. */
  93288. /* read in the data; note that the callback may return a smaller number of bytes */
  93289. if(!br->read_callback(target, &bytes, br->client_data))
  93290. return false;
  93291. /* after reading bytes 66 77 88 99 AA BB CC DD EE FF from the client:
  93292. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  93293. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  93294. * buffer[LE]: 44 33 22 11 55 66 77 88 99 AA BB CC DD EE FF ??
  93295. * now have to byteswap on LE machines:
  93296. */
  93297. #if WORDS_BIGENDIAN
  93298. #else
  93299. end = (br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes + (FLAC__BYTES_PER_WORD-1)) / FLAC__BYTES_PER_WORD;
  93300. # if defined(_MSC_VER) && defined (_X86_) && (FLAC__BYTES_PER_WORD == 4)
  93301. if(br->cpu_info.type == FLAC__CPUINFO_TYPE_IA32 && br->cpu_info.data.ia32.bswap) {
  93302. start = br->words;
  93303. local_swap32_block_(br->buffer + start, end - start);
  93304. }
  93305. else
  93306. # endif
  93307. for(start = br->words; start < end; start++)
  93308. br->buffer[start] = SWAP_BE_WORD_TO_HOST(br->buffer[start]);
  93309. #endif
  93310. /* now it looks like:
  93311. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  93312. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  93313. * buffer[LE]: 44 33 22 11 88 77 66 55 CC BB AA 99 ?? FF EE DD
  93314. * finally we'll update the reader values:
  93315. */
  93316. end = br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes;
  93317. br->words = end / FLAC__BYTES_PER_WORD;
  93318. br->bytes = end % FLAC__BYTES_PER_WORD;
  93319. return true;
  93320. }
  93321. /***********************************************************************
  93322. *
  93323. * Class constructor/destructor
  93324. *
  93325. ***********************************************************************/
  93326. FLAC__BitReader *FLAC__bitreader_new(void)
  93327. {
  93328. FLAC__BitReader *br = (FLAC__BitReader*)calloc(1, sizeof(FLAC__BitReader));
  93329. /* calloc() implies:
  93330. memset(br, 0, sizeof(FLAC__BitReader));
  93331. br->buffer = 0;
  93332. br->capacity = 0;
  93333. br->words = br->bytes = 0;
  93334. br->consumed_words = br->consumed_bits = 0;
  93335. br->read_callback = 0;
  93336. br->client_data = 0;
  93337. */
  93338. return br;
  93339. }
  93340. void FLAC__bitreader_delete(FLAC__BitReader *br)
  93341. {
  93342. FLAC__ASSERT(0 != br);
  93343. FLAC__bitreader_free(br);
  93344. free(br);
  93345. }
  93346. /***********************************************************************
  93347. *
  93348. * Public class methods
  93349. *
  93350. ***********************************************************************/
  93351. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd)
  93352. {
  93353. FLAC__ASSERT(0 != br);
  93354. br->words = br->bytes = 0;
  93355. br->consumed_words = br->consumed_bits = 0;
  93356. br->capacity = FLAC__BITREADER_DEFAULT_CAPACITY;
  93357. br->buffer = (brword*)malloc(sizeof(brword) * br->capacity);
  93358. if(br->buffer == 0)
  93359. return false;
  93360. br->read_callback = rcb;
  93361. br->client_data = cd;
  93362. br->cpu_info = cpu;
  93363. return true;
  93364. }
  93365. void FLAC__bitreader_free(FLAC__BitReader *br)
  93366. {
  93367. FLAC__ASSERT(0 != br);
  93368. if(0 != br->buffer)
  93369. free(br->buffer);
  93370. br->buffer = 0;
  93371. br->capacity = 0;
  93372. br->words = br->bytes = 0;
  93373. br->consumed_words = br->consumed_bits = 0;
  93374. br->read_callback = 0;
  93375. br->client_data = 0;
  93376. }
  93377. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br)
  93378. {
  93379. br->words = br->bytes = 0;
  93380. br->consumed_words = br->consumed_bits = 0;
  93381. return true;
  93382. }
  93383. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out)
  93384. {
  93385. unsigned i, j;
  93386. if(br == 0) {
  93387. fprintf(out, "bitreader is NULL\n");
  93388. }
  93389. else {
  93390. 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);
  93391. for(i = 0; i < br->words; i++) {
  93392. fprintf(out, "%08X: ", i);
  93393. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  93394. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  93395. fprintf(out, ".");
  93396. else
  93397. fprintf(out, "%01u", br->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  93398. fprintf(out, "\n");
  93399. }
  93400. if(br->bytes > 0) {
  93401. fprintf(out, "%08X: ", i);
  93402. for(j = 0; j < br->bytes*8; j++)
  93403. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  93404. fprintf(out, ".");
  93405. else
  93406. fprintf(out, "%01u", br->buffer[i] & (1 << (br->bytes*8-j-1)) ? 1:0);
  93407. fprintf(out, "\n");
  93408. }
  93409. }
  93410. }
  93411. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed)
  93412. {
  93413. FLAC__ASSERT(0 != br);
  93414. FLAC__ASSERT(0 != br->buffer);
  93415. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  93416. br->read_crc16 = (unsigned)seed;
  93417. br->crc16_align = br->consumed_bits;
  93418. }
  93419. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br)
  93420. {
  93421. FLAC__ASSERT(0 != br);
  93422. FLAC__ASSERT(0 != br->buffer);
  93423. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  93424. FLAC__ASSERT(br->crc16_align <= br->consumed_bits);
  93425. /* CRC any tail bytes in a partially-consumed word */
  93426. if(br->consumed_bits) {
  93427. const brword tail = br->buffer[br->consumed_words];
  93428. for( ; br->crc16_align < br->consumed_bits; br->crc16_align += 8)
  93429. br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)((tail >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), br->read_crc16);
  93430. }
  93431. return br->read_crc16;
  93432. }
  93433. FLaC__INLINE FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br)
  93434. {
  93435. return ((br->consumed_bits & 7) == 0);
  93436. }
  93437. FLaC__INLINE unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br)
  93438. {
  93439. return 8 - (br->consumed_bits & 7);
  93440. }
  93441. FLaC__INLINE unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br)
  93442. {
  93443. return (br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits;
  93444. }
  93445. FLaC__INLINE FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits)
  93446. {
  93447. FLAC__ASSERT(0 != br);
  93448. FLAC__ASSERT(0 != br->buffer);
  93449. FLAC__ASSERT(bits <= 32);
  93450. FLAC__ASSERT((br->capacity*FLAC__BITS_PER_WORD) * 2 >= bits);
  93451. FLAC__ASSERT(br->consumed_words <= br->words);
  93452. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93453. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93454. if(bits == 0) { /* OPT: investigate if this can ever happen, maybe change to assertion */
  93455. *val = 0;
  93456. return true;
  93457. }
  93458. while((br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits < bits) {
  93459. if(!bitreader_read_from_client_(br))
  93460. return false;
  93461. }
  93462. if(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  93463. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  93464. if(br->consumed_bits) {
  93465. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93466. const unsigned n = FLAC__BITS_PER_WORD - br->consumed_bits;
  93467. const brword word = br->buffer[br->consumed_words];
  93468. if(bits < n) {
  93469. *val = (word & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (n-bits);
  93470. br->consumed_bits += bits;
  93471. return true;
  93472. }
  93473. *val = word & (FLAC__WORD_ALL_ONES >> br->consumed_bits);
  93474. bits -= n;
  93475. crc16_update_word_(br, word);
  93476. br->consumed_words++;
  93477. br->consumed_bits = 0;
  93478. 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 */
  93479. *val <<= bits;
  93480. *val |= (br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits));
  93481. br->consumed_bits = bits;
  93482. }
  93483. return true;
  93484. }
  93485. else {
  93486. const brword word = br->buffer[br->consumed_words];
  93487. if(bits < FLAC__BITS_PER_WORD) {
  93488. *val = word >> (FLAC__BITS_PER_WORD-bits);
  93489. br->consumed_bits = bits;
  93490. return true;
  93491. }
  93492. /* at this point 'bits' must be == FLAC__BITS_PER_WORD; because of previous assertions, it can't be larger */
  93493. *val = word;
  93494. crc16_update_word_(br, word);
  93495. br->consumed_words++;
  93496. return true;
  93497. }
  93498. }
  93499. else {
  93500. /* in this case we're starting our read at a partial tail word;
  93501. * the reader has guaranteed that we have at least 'bits' bits
  93502. * available to read, which makes this case simpler.
  93503. */
  93504. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  93505. if(br->consumed_bits) {
  93506. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93507. FLAC__ASSERT(br->consumed_bits + bits <= br->bytes*8);
  93508. *val = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (FLAC__BITS_PER_WORD-br->consumed_bits-bits);
  93509. br->consumed_bits += bits;
  93510. return true;
  93511. }
  93512. else {
  93513. *val = br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits);
  93514. br->consumed_bits += bits;
  93515. return true;
  93516. }
  93517. }
  93518. }
  93519. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits)
  93520. {
  93521. /* OPT: inline raw uint32 code here, or make into a macro if possible in the .h file */
  93522. if(!FLAC__bitreader_read_raw_uint32(br, (FLAC__uint32*)val, bits))
  93523. return false;
  93524. /* sign-extend: */
  93525. *val <<= (32-bits);
  93526. *val >>= (32-bits);
  93527. return true;
  93528. }
  93529. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits)
  93530. {
  93531. FLAC__uint32 hi, lo;
  93532. if(bits > 32) {
  93533. if(!FLAC__bitreader_read_raw_uint32(br, &hi, bits-32))
  93534. return false;
  93535. if(!FLAC__bitreader_read_raw_uint32(br, &lo, 32))
  93536. return false;
  93537. *val = hi;
  93538. *val <<= 32;
  93539. *val |= lo;
  93540. }
  93541. else {
  93542. if(!FLAC__bitreader_read_raw_uint32(br, &lo, bits))
  93543. return false;
  93544. *val = lo;
  93545. }
  93546. return true;
  93547. }
  93548. FLaC__INLINE FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val)
  93549. {
  93550. FLAC__uint32 x8, x32 = 0;
  93551. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  93552. if(!FLAC__bitreader_read_raw_uint32(br, &x32, 8))
  93553. return false;
  93554. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  93555. return false;
  93556. x32 |= (x8 << 8);
  93557. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  93558. return false;
  93559. x32 |= (x8 << 16);
  93560. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  93561. return false;
  93562. x32 |= (x8 << 24);
  93563. *val = x32;
  93564. return true;
  93565. }
  93566. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits)
  93567. {
  93568. /*
  93569. * OPT: a faster implementation is possible but probably not that useful
  93570. * since this is only called a couple of times in the metadata readers.
  93571. */
  93572. FLAC__ASSERT(0 != br);
  93573. FLAC__ASSERT(0 != br->buffer);
  93574. if(bits > 0) {
  93575. const unsigned n = br->consumed_bits & 7;
  93576. unsigned m;
  93577. FLAC__uint32 x;
  93578. if(n != 0) {
  93579. m = min(8-n, bits);
  93580. if(!FLAC__bitreader_read_raw_uint32(br, &x, m))
  93581. return false;
  93582. bits -= m;
  93583. }
  93584. m = bits / 8;
  93585. if(m > 0) {
  93586. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(br, m))
  93587. return false;
  93588. bits %= 8;
  93589. }
  93590. if(bits > 0) {
  93591. if(!FLAC__bitreader_read_raw_uint32(br, &x, bits))
  93592. return false;
  93593. }
  93594. }
  93595. return true;
  93596. }
  93597. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals)
  93598. {
  93599. FLAC__uint32 x;
  93600. FLAC__ASSERT(0 != br);
  93601. FLAC__ASSERT(0 != br->buffer);
  93602. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  93603. /* step 1: skip over partial head word to get word aligned */
  93604. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  93605. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93606. return false;
  93607. nvals--;
  93608. }
  93609. if(0 == nvals)
  93610. return true;
  93611. /* step 2: skip whole words in chunks */
  93612. while(nvals >= FLAC__BYTES_PER_WORD) {
  93613. if(br->consumed_words < br->words) {
  93614. br->consumed_words++;
  93615. nvals -= FLAC__BYTES_PER_WORD;
  93616. }
  93617. else if(!bitreader_read_from_client_(br))
  93618. return false;
  93619. }
  93620. /* step 3: skip any remainder from partial tail bytes */
  93621. while(nvals) {
  93622. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93623. return false;
  93624. nvals--;
  93625. }
  93626. return true;
  93627. }
  93628. FLAC__bool FLAC__bitreader_read_byte_block_aligned_no_crc(FLAC__BitReader *br, FLAC__byte *val, unsigned nvals)
  93629. {
  93630. FLAC__uint32 x;
  93631. FLAC__ASSERT(0 != br);
  93632. FLAC__ASSERT(0 != br->buffer);
  93633. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  93634. /* step 1: read from partial head word to get word aligned */
  93635. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  93636. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93637. return false;
  93638. *val++ = (FLAC__byte)x;
  93639. nvals--;
  93640. }
  93641. if(0 == nvals)
  93642. return true;
  93643. /* step 2: read whole words in chunks */
  93644. while(nvals >= FLAC__BYTES_PER_WORD) {
  93645. if(br->consumed_words < br->words) {
  93646. const brword word = br->buffer[br->consumed_words++];
  93647. #if FLAC__BYTES_PER_WORD == 4
  93648. val[0] = (FLAC__byte)(word >> 24);
  93649. val[1] = (FLAC__byte)(word >> 16);
  93650. val[2] = (FLAC__byte)(word >> 8);
  93651. val[3] = (FLAC__byte)word;
  93652. #elif FLAC__BYTES_PER_WORD == 8
  93653. val[0] = (FLAC__byte)(word >> 56);
  93654. val[1] = (FLAC__byte)(word >> 48);
  93655. val[2] = (FLAC__byte)(word >> 40);
  93656. val[3] = (FLAC__byte)(word >> 32);
  93657. val[4] = (FLAC__byte)(word >> 24);
  93658. val[5] = (FLAC__byte)(word >> 16);
  93659. val[6] = (FLAC__byte)(word >> 8);
  93660. val[7] = (FLAC__byte)word;
  93661. #else
  93662. for(x = 0; x < FLAC__BYTES_PER_WORD; x++)
  93663. val[x] = (FLAC__byte)(word >> (8*(FLAC__BYTES_PER_WORD-x-1)));
  93664. #endif
  93665. val += FLAC__BYTES_PER_WORD;
  93666. nvals -= FLAC__BYTES_PER_WORD;
  93667. }
  93668. else if(!bitreader_read_from_client_(br))
  93669. return false;
  93670. }
  93671. /* step 3: read any remainder from partial tail bytes */
  93672. while(nvals) {
  93673. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93674. return false;
  93675. *val++ = (FLAC__byte)x;
  93676. nvals--;
  93677. }
  93678. return true;
  93679. }
  93680. FLaC__INLINE FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val)
  93681. #if 0 /* slow but readable version */
  93682. {
  93683. unsigned bit;
  93684. FLAC__ASSERT(0 != br);
  93685. FLAC__ASSERT(0 != br->buffer);
  93686. *val = 0;
  93687. while(1) {
  93688. if(!FLAC__bitreader_read_bit(br, &bit))
  93689. return false;
  93690. if(bit)
  93691. break;
  93692. else
  93693. *val++;
  93694. }
  93695. return true;
  93696. }
  93697. #else
  93698. {
  93699. unsigned i;
  93700. FLAC__ASSERT(0 != br);
  93701. FLAC__ASSERT(0 != br->buffer);
  93702. *val = 0;
  93703. while(1) {
  93704. while(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  93705. brword b = br->buffer[br->consumed_words] << br->consumed_bits;
  93706. if(b) {
  93707. i = COUNT_ZERO_MSBS(b);
  93708. *val += i;
  93709. i++;
  93710. br->consumed_bits += i;
  93711. if(br->consumed_bits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(br->consumed_bits == FLAC__BITS_PER_WORD) */
  93712. crc16_update_word_(br, br->buffer[br->consumed_words]);
  93713. br->consumed_words++;
  93714. br->consumed_bits = 0;
  93715. }
  93716. return true;
  93717. }
  93718. else {
  93719. *val += FLAC__BITS_PER_WORD - br->consumed_bits;
  93720. crc16_update_word_(br, br->buffer[br->consumed_words]);
  93721. br->consumed_words++;
  93722. br->consumed_bits = 0;
  93723. /* didn't find stop bit yet, have to keep going... */
  93724. }
  93725. }
  93726. /* at this point we've eaten up all the whole words; have to try
  93727. * reading through any tail bytes before calling the read callback.
  93728. * this is a repeat of the above logic adjusted for the fact we
  93729. * don't have a whole word. note though if the client is feeding
  93730. * us data a byte at a time (unlikely), br->consumed_bits may not
  93731. * be zero.
  93732. */
  93733. if(br->bytes) {
  93734. const unsigned end = br->bytes * 8;
  93735. brword b = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << br->consumed_bits;
  93736. if(b) {
  93737. i = COUNT_ZERO_MSBS(b);
  93738. *val += i;
  93739. i++;
  93740. br->consumed_bits += i;
  93741. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  93742. return true;
  93743. }
  93744. else {
  93745. *val += end - br->consumed_bits;
  93746. br->consumed_bits += end;
  93747. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  93748. /* didn't find stop bit yet, have to keep going... */
  93749. }
  93750. }
  93751. if(!bitreader_read_from_client_(br))
  93752. return false;
  93753. }
  93754. }
  93755. #endif
  93756. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  93757. {
  93758. FLAC__uint32 lsbs = 0, msbs = 0;
  93759. unsigned uval;
  93760. FLAC__ASSERT(0 != br);
  93761. FLAC__ASSERT(0 != br->buffer);
  93762. FLAC__ASSERT(parameter <= 31);
  93763. /* read the unary MSBs and end bit */
  93764. if(!FLAC__bitreader_read_unary_unsigned(br, (unsigned int*) &msbs))
  93765. return false;
  93766. /* read the binary LSBs */
  93767. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, parameter))
  93768. return false;
  93769. /* compose the value */
  93770. uval = (msbs << parameter) | lsbs;
  93771. if(uval & 1)
  93772. *val = -((int)(uval >> 1)) - 1;
  93773. else
  93774. *val = (int)(uval >> 1);
  93775. return true;
  93776. }
  93777. /* this is by far the most heavily used reader call. it ain't pretty but it's fast */
  93778. /* a lot of the logic is copied, then adapted, from FLAC__bitreader_read_unary_unsigned() and FLAC__bitreader_read_raw_uint32() */
  93779. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter)
  93780. /* OPT: possibly faster version for use with MSVC */
  93781. #ifdef _MSC_VER
  93782. {
  93783. unsigned i;
  93784. unsigned uval = 0;
  93785. unsigned bits; /* the # of binary LSBs left to read to finish a rice codeword */
  93786. /* try and get br->consumed_words and br->consumed_bits into register;
  93787. * must remember to flush them back to *br before calling other
  93788. * bitwriter functions that use them, and before returning */
  93789. register unsigned cwords;
  93790. register unsigned cbits;
  93791. FLAC__ASSERT(0 != br);
  93792. FLAC__ASSERT(0 != br->buffer);
  93793. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93794. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93795. FLAC__ASSERT(parameter < 32);
  93796. /* 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 */
  93797. if(nvals == 0)
  93798. return true;
  93799. cbits = br->consumed_bits;
  93800. cwords = br->consumed_words;
  93801. while(1) {
  93802. /* read unary part */
  93803. while(1) {
  93804. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93805. brword b = br->buffer[cwords] << cbits;
  93806. if(b) {
  93807. #if 0 /* slower, probably due to bad register allocation... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32
  93808. __asm {
  93809. bsr eax, b
  93810. not eax
  93811. and eax, 31
  93812. mov i, eax
  93813. }
  93814. #else
  93815. i = COUNT_ZERO_MSBS(b);
  93816. #endif
  93817. uval += i;
  93818. bits = parameter;
  93819. i++;
  93820. cbits += i;
  93821. if(cbits == FLAC__BITS_PER_WORD) {
  93822. crc16_update_word_(br, br->buffer[cwords]);
  93823. cwords++;
  93824. cbits = 0;
  93825. }
  93826. goto break1;
  93827. }
  93828. else {
  93829. uval += FLAC__BITS_PER_WORD - cbits;
  93830. crc16_update_word_(br, br->buffer[cwords]);
  93831. cwords++;
  93832. cbits = 0;
  93833. /* didn't find stop bit yet, have to keep going... */
  93834. }
  93835. }
  93836. /* at this point we've eaten up all the whole words; have to try
  93837. * reading through any tail bytes before calling the read callback.
  93838. * this is a repeat of the above logic adjusted for the fact we
  93839. * don't have a whole word. note though if the client is feeding
  93840. * us data a byte at a time (unlikely), br->consumed_bits may not
  93841. * be zero.
  93842. */
  93843. if(br->bytes) {
  93844. const unsigned end = br->bytes * 8;
  93845. brword b = (br->buffer[cwords] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << cbits;
  93846. if(b) {
  93847. i = COUNT_ZERO_MSBS(b);
  93848. uval += i;
  93849. bits = parameter;
  93850. i++;
  93851. cbits += i;
  93852. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93853. goto break1;
  93854. }
  93855. else {
  93856. uval += end - cbits;
  93857. cbits += end;
  93858. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93859. /* didn't find stop bit yet, have to keep going... */
  93860. }
  93861. }
  93862. /* flush registers and read; bitreader_read_from_client_() does
  93863. * not touch br->consumed_bits at all but we still need to set
  93864. * it in case it fails and we have to return false.
  93865. */
  93866. br->consumed_bits = cbits;
  93867. br->consumed_words = cwords;
  93868. if(!bitreader_read_from_client_(br))
  93869. return false;
  93870. cwords = br->consumed_words;
  93871. }
  93872. break1:
  93873. /* read binary part */
  93874. FLAC__ASSERT(cwords <= br->words);
  93875. if(bits) {
  93876. while((br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits < bits) {
  93877. /* flush registers and read; bitreader_read_from_client_() does
  93878. * not touch br->consumed_bits at all but we still need to set
  93879. * it in case it fails and we have to return false.
  93880. */
  93881. br->consumed_bits = cbits;
  93882. br->consumed_words = cwords;
  93883. if(!bitreader_read_from_client_(br))
  93884. return false;
  93885. cwords = br->consumed_words;
  93886. }
  93887. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93888. if(cbits) {
  93889. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93890. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  93891. const brword word = br->buffer[cwords];
  93892. if(bits < n) {
  93893. uval <<= bits;
  93894. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-bits);
  93895. cbits += bits;
  93896. goto break2;
  93897. }
  93898. uval <<= n;
  93899. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  93900. bits -= n;
  93901. crc16_update_word_(br, word);
  93902. cwords++;
  93903. cbits = 0;
  93904. 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 */
  93905. uval <<= bits;
  93906. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits));
  93907. cbits = bits;
  93908. }
  93909. goto break2;
  93910. }
  93911. else {
  93912. FLAC__ASSERT(bits < FLAC__BITS_PER_WORD);
  93913. uval <<= bits;
  93914. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  93915. cbits = bits;
  93916. goto break2;
  93917. }
  93918. }
  93919. else {
  93920. /* in this case we're starting our read at a partial tail word;
  93921. * the reader has guaranteed that we have at least 'bits' bits
  93922. * available to read, which makes this case simpler.
  93923. */
  93924. uval <<= bits;
  93925. if(cbits) {
  93926. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93927. FLAC__ASSERT(cbits + bits <= br->bytes*8);
  93928. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-bits);
  93929. cbits += bits;
  93930. goto break2;
  93931. }
  93932. else {
  93933. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  93934. cbits += bits;
  93935. goto break2;
  93936. }
  93937. }
  93938. }
  93939. break2:
  93940. /* compose the value */
  93941. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  93942. /* are we done? */
  93943. --nvals;
  93944. if(nvals == 0) {
  93945. br->consumed_bits = cbits;
  93946. br->consumed_words = cwords;
  93947. return true;
  93948. }
  93949. uval = 0;
  93950. ++vals;
  93951. }
  93952. }
  93953. #else
  93954. {
  93955. unsigned i;
  93956. unsigned uval = 0;
  93957. /* try and get br->consumed_words and br->consumed_bits into register;
  93958. * must remember to flush them back to *br before calling other
  93959. * bitwriter functions that use them, and before returning */
  93960. register unsigned cwords;
  93961. register unsigned cbits;
  93962. unsigned ucbits; /* keep track of the number of unconsumed bits in the buffer */
  93963. FLAC__ASSERT(0 != br);
  93964. FLAC__ASSERT(0 != br->buffer);
  93965. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93966. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93967. FLAC__ASSERT(parameter < 32);
  93968. /* 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 */
  93969. if(nvals == 0)
  93970. return true;
  93971. cbits = br->consumed_bits;
  93972. cwords = br->consumed_words;
  93973. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  93974. while(1) {
  93975. /* read unary part */
  93976. while(1) {
  93977. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93978. brword b = br->buffer[cwords] << cbits;
  93979. if(b) {
  93980. #if 0 /* is not discernably faster... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32 && defined __GNUC__
  93981. asm volatile (
  93982. "bsrl %1, %0;"
  93983. "notl %0;"
  93984. "andl $31, %0;"
  93985. : "=r"(i)
  93986. : "r"(b)
  93987. );
  93988. #else
  93989. i = COUNT_ZERO_MSBS(b);
  93990. #endif
  93991. uval += i;
  93992. cbits += i;
  93993. cbits++; /* skip over stop bit */
  93994. if(cbits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(cbits == FLAC__BITS_PER_WORD) */
  93995. crc16_update_word_(br, br->buffer[cwords]);
  93996. cwords++;
  93997. cbits = 0;
  93998. }
  93999. goto break1;
  94000. }
  94001. else {
  94002. uval += FLAC__BITS_PER_WORD - cbits;
  94003. crc16_update_word_(br, br->buffer[cwords]);
  94004. cwords++;
  94005. cbits = 0;
  94006. /* didn't find stop bit yet, have to keep going... */
  94007. }
  94008. }
  94009. /* at this point we've eaten up all the whole words; have to try
  94010. * reading through any tail bytes before calling the read callback.
  94011. * this is a repeat of the above logic adjusted for the fact we
  94012. * don't have a whole word. note though if the client is feeding
  94013. * us data a byte at a time (unlikely), br->consumed_bits may not
  94014. * be zero.
  94015. */
  94016. if(br->bytes) {
  94017. const unsigned end = br->bytes * 8;
  94018. brword b = (br->buffer[cwords] & ~(FLAC__WORD_ALL_ONES >> end)) << cbits;
  94019. if(b) {
  94020. i = COUNT_ZERO_MSBS(b);
  94021. uval += i;
  94022. cbits += i;
  94023. cbits++; /* skip over stop bit */
  94024. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  94025. goto break1;
  94026. }
  94027. else {
  94028. uval += end - cbits;
  94029. cbits += end;
  94030. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  94031. /* didn't find stop bit yet, have to keep going... */
  94032. }
  94033. }
  94034. /* flush registers and read; bitreader_read_from_client_() does
  94035. * not touch br->consumed_bits at all but we still need to set
  94036. * it in case it fails and we have to return false.
  94037. */
  94038. br->consumed_bits = cbits;
  94039. br->consumed_words = cwords;
  94040. if(!bitreader_read_from_client_(br))
  94041. return false;
  94042. cwords = br->consumed_words;
  94043. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits + uval;
  94044. /* + uval to offset our count by the # of unary bits already
  94045. * consumed before the read, because we will add these back
  94046. * in all at once at break1
  94047. */
  94048. }
  94049. break1:
  94050. ucbits -= uval;
  94051. ucbits--; /* account for stop bit */
  94052. /* read binary part */
  94053. FLAC__ASSERT(cwords <= br->words);
  94054. if(parameter) {
  94055. while(ucbits < parameter) {
  94056. /* flush registers and read; bitreader_read_from_client_() does
  94057. * not touch br->consumed_bits at all but we still need to set
  94058. * it in case it fails and we have to return false.
  94059. */
  94060. br->consumed_bits = cbits;
  94061. br->consumed_words = cwords;
  94062. if(!bitreader_read_from_client_(br))
  94063. return false;
  94064. cwords = br->consumed_words;
  94065. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  94066. }
  94067. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  94068. if(cbits) {
  94069. /* this also works when consumed_bits==0, it's just slower than necessary for that case */
  94070. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  94071. const brword word = br->buffer[cwords];
  94072. if(parameter < n) {
  94073. uval <<= parameter;
  94074. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-parameter);
  94075. cbits += parameter;
  94076. }
  94077. else {
  94078. uval <<= n;
  94079. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  94080. crc16_update_word_(br, word);
  94081. cwords++;
  94082. cbits = parameter - n;
  94083. 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 */
  94084. uval <<= cbits;
  94085. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits));
  94086. }
  94087. }
  94088. }
  94089. else {
  94090. cbits = parameter;
  94091. uval <<= parameter;
  94092. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  94093. }
  94094. }
  94095. else {
  94096. /* in this case we're starting our read at a partial tail word;
  94097. * the reader has guaranteed that we have at least 'parameter'
  94098. * bits available to read, which makes this case simpler.
  94099. */
  94100. uval <<= parameter;
  94101. if(cbits) {
  94102. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  94103. FLAC__ASSERT(cbits + parameter <= br->bytes*8);
  94104. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-parameter);
  94105. cbits += parameter;
  94106. }
  94107. else {
  94108. cbits = parameter;
  94109. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  94110. }
  94111. }
  94112. }
  94113. ucbits -= parameter;
  94114. /* compose the value */
  94115. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  94116. /* are we done? */
  94117. --nvals;
  94118. if(nvals == 0) {
  94119. br->consumed_bits = cbits;
  94120. br->consumed_words = cwords;
  94121. return true;
  94122. }
  94123. uval = 0;
  94124. ++vals;
  94125. }
  94126. }
  94127. #endif
  94128. #if 0 /* UNUSED */
  94129. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  94130. {
  94131. FLAC__uint32 lsbs = 0, msbs = 0;
  94132. unsigned bit, uval, k;
  94133. FLAC__ASSERT(0 != br);
  94134. FLAC__ASSERT(0 != br->buffer);
  94135. k = FLAC__bitmath_ilog2(parameter);
  94136. /* read the unary MSBs and end bit */
  94137. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  94138. return false;
  94139. /* read the binary LSBs */
  94140. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  94141. return false;
  94142. if(parameter == 1u<<k) {
  94143. /* compose the value */
  94144. uval = (msbs << k) | lsbs;
  94145. }
  94146. else {
  94147. unsigned d = (1 << (k+1)) - parameter;
  94148. if(lsbs >= d) {
  94149. if(!FLAC__bitreader_read_bit(br, &bit))
  94150. return false;
  94151. lsbs <<= 1;
  94152. lsbs |= bit;
  94153. lsbs -= d;
  94154. }
  94155. /* compose the value */
  94156. uval = msbs * parameter + lsbs;
  94157. }
  94158. /* unfold unsigned to signed */
  94159. if(uval & 1)
  94160. *val = -((int)(uval >> 1)) - 1;
  94161. else
  94162. *val = (int)(uval >> 1);
  94163. return true;
  94164. }
  94165. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter)
  94166. {
  94167. FLAC__uint32 lsbs, msbs = 0;
  94168. unsigned bit, k;
  94169. FLAC__ASSERT(0 != br);
  94170. FLAC__ASSERT(0 != br->buffer);
  94171. k = FLAC__bitmath_ilog2(parameter);
  94172. /* read the unary MSBs and end bit */
  94173. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  94174. return false;
  94175. /* read the binary LSBs */
  94176. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  94177. return false;
  94178. if(parameter == 1u<<k) {
  94179. /* compose the value */
  94180. *val = (msbs << k) | lsbs;
  94181. }
  94182. else {
  94183. unsigned d = (1 << (k+1)) - parameter;
  94184. if(lsbs >= d) {
  94185. if(!FLAC__bitreader_read_bit(br, &bit))
  94186. return false;
  94187. lsbs <<= 1;
  94188. lsbs |= bit;
  94189. lsbs -= d;
  94190. }
  94191. /* compose the value */
  94192. *val = msbs * parameter + lsbs;
  94193. }
  94194. return true;
  94195. }
  94196. #endif /* UNUSED */
  94197. /* on return, if *val == 0xffffffff then the utf-8 sequence was invalid, but the return value will be true */
  94198. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen)
  94199. {
  94200. FLAC__uint32 v = 0;
  94201. FLAC__uint32 x;
  94202. unsigned i;
  94203. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94204. return false;
  94205. if(raw)
  94206. raw[(*rawlen)++] = (FLAC__byte)x;
  94207. if(!(x & 0x80)) { /* 0xxxxxxx */
  94208. v = x;
  94209. i = 0;
  94210. }
  94211. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  94212. v = x & 0x1F;
  94213. i = 1;
  94214. }
  94215. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  94216. v = x & 0x0F;
  94217. i = 2;
  94218. }
  94219. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  94220. v = x & 0x07;
  94221. i = 3;
  94222. }
  94223. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  94224. v = x & 0x03;
  94225. i = 4;
  94226. }
  94227. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  94228. v = x & 0x01;
  94229. i = 5;
  94230. }
  94231. else {
  94232. *val = 0xffffffff;
  94233. return true;
  94234. }
  94235. for( ; i; i--) {
  94236. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94237. return false;
  94238. if(raw)
  94239. raw[(*rawlen)++] = (FLAC__byte)x;
  94240. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  94241. *val = 0xffffffff;
  94242. return true;
  94243. }
  94244. v <<= 6;
  94245. v |= (x & 0x3F);
  94246. }
  94247. *val = v;
  94248. return true;
  94249. }
  94250. /* on return, if *val == 0xffffffffffffffff then the utf-8 sequence was invalid, but the return value will be true */
  94251. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen)
  94252. {
  94253. FLAC__uint64 v = 0;
  94254. FLAC__uint32 x;
  94255. unsigned i;
  94256. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94257. return false;
  94258. if(raw)
  94259. raw[(*rawlen)++] = (FLAC__byte)x;
  94260. if(!(x & 0x80)) { /* 0xxxxxxx */
  94261. v = x;
  94262. i = 0;
  94263. }
  94264. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  94265. v = x & 0x1F;
  94266. i = 1;
  94267. }
  94268. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  94269. v = x & 0x0F;
  94270. i = 2;
  94271. }
  94272. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  94273. v = x & 0x07;
  94274. i = 3;
  94275. }
  94276. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  94277. v = x & 0x03;
  94278. i = 4;
  94279. }
  94280. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  94281. v = x & 0x01;
  94282. i = 5;
  94283. }
  94284. else if(x & 0xFE && !(x & 0x01)) { /* 11111110 */
  94285. v = 0;
  94286. i = 6;
  94287. }
  94288. else {
  94289. *val = FLAC__U64L(0xffffffffffffffff);
  94290. return true;
  94291. }
  94292. for( ; i; i--) {
  94293. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94294. return false;
  94295. if(raw)
  94296. raw[(*rawlen)++] = (FLAC__byte)x;
  94297. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  94298. *val = FLAC__U64L(0xffffffffffffffff);
  94299. return true;
  94300. }
  94301. v <<= 6;
  94302. v |= (x & 0x3F);
  94303. }
  94304. *val = v;
  94305. return true;
  94306. }
  94307. #endif
  94308. /*** End of inlined file: bitreader.c ***/
  94309. /*** Start of inlined file: bitwriter.c ***/
  94310. /*** Start of inlined file: juce_FlacHeader.h ***/
  94311. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  94312. // tasks..
  94313. #define VERSION "1.2.1"
  94314. #define FLAC__NO_DLL 1
  94315. #if JUCE_MSVC
  94316. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  94317. #endif
  94318. #if JUCE_MAC
  94319. #define FLAC__SYS_DARWIN 1
  94320. #endif
  94321. /*** End of inlined file: juce_FlacHeader.h ***/
  94322. #if JUCE_USE_FLAC
  94323. #if HAVE_CONFIG_H
  94324. # include <config.h>
  94325. #endif
  94326. #include <stdlib.h> /* for malloc() */
  94327. #include <string.h> /* for memcpy(), memset() */
  94328. #ifdef _MSC_VER
  94329. #include <winsock.h> /* for ntohl() */
  94330. #elif defined FLAC__SYS_DARWIN
  94331. #include <machine/endian.h> /* for ntohl() */
  94332. #elif defined __MINGW32__
  94333. #include <winsock.h> /* for ntohl() */
  94334. #else
  94335. #include <netinet/in.h> /* for ntohl() */
  94336. #endif
  94337. #if 0 /* UNUSED */
  94338. #endif
  94339. /*** Start of inlined file: bitwriter.h ***/
  94340. #ifndef FLAC__PRIVATE__BITWRITER_H
  94341. #define FLAC__PRIVATE__BITWRITER_H
  94342. #include <stdio.h> /* for FILE */
  94343. /*
  94344. * opaque structure definition
  94345. */
  94346. struct FLAC__BitWriter;
  94347. typedef struct FLAC__BitWriter FLAC__BitWriter;
  94348. /*
  94349. * construction, deletion, initialization, etc functions
  94350. */
  94351. FLAC__BitWriter *FLAC__bitwriter_new(void);
  94352. void FLAC__bitwriter_delete(FLAC__BitWriter *bw);
  94353. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw);
  94354. void FLAC__bitwriter_free(FLAC__BitWriter *bw); /* does not 'free(buffer)' */
  94355. void FLAC__bitwriter_clear(FLAC__BitWriter *bw);
  94356. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out);
  94357. /*
  94358. * CRC functions
  94359. *
  94360. * non-const *bw because they have to cal FLAC__bitwriter_get_buffer()
  94361. */
  94362. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc);
  94363. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc);
  94364. /*
  94365. * info functions
  94366. */
  94367. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw);
  94368. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw); /* can be called anytime, returns total # of bits unconsumed */
  94369. /*
  94370. * direct buffer access
  94371. *
  94372. * there may be no calls on the bitwriter between get and release.
  94373. * the bitwriter continues to own the returned buffer.
  94374. * before get, bitwriter MUST be byte aligned: check with FLAC__bitwriter_is_byte_aligned()
  94375. */
  94376. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes);
  94377. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw);
  94378. /*
  94379. * write functions
  94380. */
  94381. FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits);
  94382. FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits);
  94383. FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits);
  94384. FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits);
  94385. FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val); /*only for bits=32*/
  94386. FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals);
  94387. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val);
  94388. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter);
  94389. #if 0 /* UNUSED */
  94390. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter);
  94391. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned val, unsigned parameter);
  94392. #endif
  94393. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter);
  94394. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter);
  94395. #if 0 /* UNUSED */
  94396. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter);
  94397. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned val, unsigned parameter);
  94398. #endif
  94399. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val);
  94400. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val);
  94401. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw);
  94402. #endif
  94403. /*** End of inlined file: bitwriter.h ***/
  94404. /*** Start of inlined file: alloc.h ***/
  94405. #ifndef FLAC__SHARE__ALLOC_H
  94406. #define FLAC__SHARE__ALLOC_H
  94407. #if HAVE_CONFIG_H
  94408. # include <config.h>
  94409. #endif
  94410. /* WATCHOUT: for c++ you may have to #define __STDC_LIMIT_MACROS 1 real early
  94411. * before #including this file, otherwise SIZE_MAX might not be defined
  94412. */
  94413. #include <limits.h> /* for SIZE_MAX */
  94414. #if !defined _MSC_VER && !defined __MINGW32__ && !defined __EMX__
  94415. #include <stdint.h> /* for SIZE_MAX in case limits.h didn't get it */
  94416. #endif
  94417. #include <stdlib.h> /* for size_t, malloc(), etc */
  94418. #ifndef SIZE_MAX
  94419. # ifndef SIZE_T_MAX
  94420. # ifdef _MSC_VER
  94421. # define SIZE_T_MAX UINT_MAX
  94422. # else
  94423. # error
  94424. # endif
  94425. # endif
  94426. # define SIZE_MAX SIZE_T_MAX
  94427. #endif
  94428. #ifndef FLaC__INLINE
  94429. #define FLaC__INLINE
  94430. #endif
  94431. /* avoid malloc()ing 0 bytes, see:
  94432. * https://www.securecoding.cert.org/confluence/display/seccode/MEM04-A.+Do+not+make+assumptions+about+the+result+of+allocating+0+bytes?focusedCommentId=5407003
  94433. */
  94434. static FLaC__INLINE void *safe_malloc_(size_t size)
  94435. {
  94436. /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94437. if(!size)
  94438. size++;
  94439. return malloc(size);
  94440. }
  94441. static FLaC__INLINE void *safe_calloc_(size_t nmemb, size_t size)
  94442. {
  94443. if(!nmemb || !size)
  94444. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94445. return calloc(nmemb, size);
  94446. }
  94447. /*@@@@ there's probably a better way to prevent overflows when allocating untrusted sums but this works for now */
  94448. static FLaC__INLINE void *safe_malloc_add_2op_(size_t size1, size_t size2)
  94449. {
  94450. size2 += size1;
  94451. if(size2 < size1)
  94452. return 0;
  94453. return safe_malloc_(size2);
  94454. }
  94455. static FLaC__INLINE void *safe_malloc_add_3op_(size_t size1, size_t size2, size_t size3)
  94456. {
  94457. size2 += size1;
  94458. if(size2 < size1)
  94459. return 0;
  94460. size3 += size2;
  94461. if(size3 < size2)
  94462. return 0;
  94463. return safe_malloc_(size3);
  94464. }
  94465. static FLaC__INLINE void *safe_malloc_add_4op_(size_t size1, size_t size2, size_t size3, size_t size4)
  94466. {
  94467. size2 += size1;
  94468. if(size2 < size1)
  94469. return 0;
  94470. size3 += size2;
  94471. if(size3 < size2)
  94472. return 0;
  94473. size4 += size3;
  94474. if(size4 < size3)
  94475. return 0;
  94476. return safe_malloc_(size4);
  94477. }
  94478. static FLaC__INLINE void *safe_malloc_mul_2op_(size_t size1, size_t size2)
  94479. #if 0
  94480. needs support for cases where sizeof(size_t) != 4
  94481. {
  94482. /* could be faster #ifdef'ing off SIZEOF_SIZE_T */
  94483. if(sizeof(size_t) == 4) {
  94484. if ((double)size1 * (double)size2 < 4294967296.0)
  94485. return malloc(size1*size2);
  94486. }
  94487. return 0;
  94488. }
  94489. #else
  94490. /* better? */
  94491. {
  94492. if(!size1 || !size2)
  94493. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94494. if(size1 > SIZE_MAX / size2)
  94495. return 0;
  94496. return malloc(size1*size2);
  94497. }
  94498. #endif
  94499. static FLaC__INLINE void *safe_malloc_mul_3op_(size_t size1, size_t size2, size_t size3)
  94500. {
  94501. if(!size1 || !size2 || !size3)
  94502. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94503. if(size1 > SIZE_MAX / size2)
  94504. return 0;
  94505. size1 *= size2;
  94506. if(size1 > SIZE_MAX / size3)
  94507. return 0;
  94508. return malloc(size1*size3);
  94509. }
  94510. /* size1*size2 + size3 */
  94511. static FLaC__INLINE void *safe_malloc_mul2add_(size_t size1, size_t size2, size_t size3)
  94512. {
  94513. if(!size1 || !size2)
  94514. return safe_malloc_(size3);
  94515. if(size1 > SIZE_MAX / size2)
  94516. return 0;
  94517. return safe_malloc_add_2op_(size1*size2, size3);
  94518. }
  94519. /* size1 * (size2 + size3) */
  94520. static FLaC__INLINE void *safe_malloc_muladd2_(size_t size1, size_t size2, size_t size3)
  94521. {
  94522. if(!size1 || (!size2 && !size3))
  94523. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94524. size2 += size3;
  94525. if(size2 < size3)
  94526. return 0;
  94527. return safe_malloc_mul_2op_(size1, size2);
  94528. }
  94529. static FLaC__INLINE void *safe_realloc_add_2op_(void *ptr, size_t size1, size_t size2)
  94530. {
  94531. size2 += size1;
  94532. if(size2 < size1)
  94533. return 0;
  94534. return realloc(ptr, size2);
  94535. }
  94536. static FLaC__INLINE void *safe_realloc_add_3op_(void *ptr, size_t size1, size_t size2, size_t size3)
  94537. {
  94538. size2 += size1;
  94539. if(size2 < size1)
  94540. return 0;
  94541. size3 += size2;
  94542. if(size3 < size2)
  94543. return 0;
  94544. return realloc(ptr, size3);
  94545. }
  94546. static FLaC__INLINE void *safe_realloc_add_4op_(void *ptr, size_t size1, size_t size2, size_t size3, size_t size4)
  94547. {
  94548. size2 += size1;
  94549. if(size2 < size1)
  94550. return 0;
  94551. size3 += size2;
  94552. if(size3 < size2)
  94553. return 0;
  94554. size4 += size3;
  94555. if(size4 < size3)
  94556. return 0;
  94557. return realloc(ptr, size4);
  94558. }
  94559. static FLaC__INLINE void *safe_realloc_mul_2op_(void *ptr, size_t size1, size_t size2)
  94560. {
  94561. if(!size1 || !size2)
  94562. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  94563. if(size1 > SIZE_MAX / size2)
  94564. return 0;
  94565. return realloc(ptr, size1*size2);
  94566. }
  94567. /* size1 * (size2 + size3) */
  94568. static FLaC__INLINE void *safe_realloc_muladd2_(void *ptr, size_t size1, size_t size2, size_t size3)
  94569. {
  94570. if(!size1 || (!size2 && !size3))
  94571. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  94572. size2 += size3;
  94573. if(size2 < size3)
  94574. return 0;
  94575. return safe_realloc_mul_2op_(ptr, size1, size2);
  94576. }
  94577. #endif
  94578. /*** End of inlined file: alloc.h ***/
  94579. /* Things should be fastest when this matches the machine word size */
  94580. /* WATCHOUT: if you change this you must also change the following #defines down to SWAP_BE_WORD_TO_HOST below to match */
  94581. /* WATCHOUT: there are a few places where the code will not work unless bwword is >= 32 bits wide */
  94582. typedef FLAC__uint32 bwword;
  94583. #define FLAC__BYTES_PER_WORD 4
  94584. #define FLAC__BITS_PER_WORD 32
  94585. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  94586. /* SWAP_BE_WORD_TO_HOST swaps bytes in a bwword (which is always big-endian) if necessary to match host byte order */
  94587. #if WORDS_BIGENDIAN
  94588. #define SWAP_BE_WORD_TO_HOST(x) (x)
  94589. #else
  94590. #ifdef _MSC_VER
  94591. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  94592. #else
  94593. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  94594. #endif
  94595. #endif
  94596. /*
  94597. * The default capacity here doesn't matter too much. The buffer always grows
  94598. * to hold whatever is written to it. Usually the encoder will stop adding at
  94599. * a frame or metadata block, then write that out and clear the buffer for the
  94600. * next one.
  94601. */
  94602. static const unsigned FLAC__BITWRITER_DEFAULT_CAPACITY = 32768u / sizeof(bwword); /* size in words */
  94603. /* When growing, increment 4K at a time */
  94604. static const unsigned FLAC__BITWRITER_DEFAULT_INCREMENT = 4096u / sizeof(bwword); /* size in words */
  94605. #define FLAC__WORDS_TO_BITS(words) ((words) * FLAC__BITS_PER_WORD)
  94606. #define FLAC__TOTAL_BITS(bw) (FLAC__WORDS_TO_BITS((bw)->words) + (bw)->bits)
  94607. #ifdef min
  94608. #undef min
  94609. #endif
  94610. #define min(x,y) ((x)<(y)?(x):(y))
  94611. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  94612. #ifdef _MSC_VER
  94613. #define FLAC__U64L(x) x
  94614. #else
  94615. #define FLAC__U64L(x) x##LLU
  94616. #endif
  94617. #ifndef FLaC__INLINE
  94618. #define FLaC__INLINE
  94619. #endif
  94620. struct FLAC__BitWriter {
  94621. bwword *buffer;
  94622. bwword accum; /* accumulator; bits are right-justified; when full, accum is appended to buffer */
  94623. unsigned capacity; /* capacity of buffer in words */
  94624. unsigned words; /* # of complete words in buffer */
  94625. unsigned bits; /* # of used bits in accum */
  94626. };
  94627. /* * WATCHOUT: The current implementation only grows the buffer. */
  94628. static FLAC__bool bitwriter_grow_(FLAC__BitWriter *bw, unsigned bits_to_add)
  94629. {
  94630. unsigned new_capacity;
  94631. bwword *new_buffer;
  94632. FLAC__ASSERT(0 != bw);
  94633. FLAC__ASSERT(0 != bw->buffer);
  94634. /* calculate total words needed to store 'bits_to_add' additional bits */
  94635. new_capacity = bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD);
  94636. /* it's possible (due to pessimism in the growth estimation that
  94637. * leads to this call) that we don't actually need to grow
  94638. */
  94639. if(bw->capacity >= new_capacity)
  94640. return true;
  94641. /* round up capacity increase to the nearest FLAC__BITWRITER_DEFAULT_INCREMENT */
  94642. if((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT)
  94643. new_capacity += FLAC__BITWRITER_DEFAULT_INCREMENT - ((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  94644. /* make sure we got everything right */
  94645. FLAC__ASSERT(0 == (new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  94646. FLAC__ASSERT(new_capacity > bw->capacity);
  94647. FLAC__ASSERT(new_capacity >= bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD));
  94648. new_buffer = (bwword*)safe_realloc_mul_2op_(bw->buffer, sizeof(bwword), /*times*/new_capacity);
  94649. if(new_buffer == 0)
  94650. return false;
  94651. bw->buffer = new_buffer;
  94652. bw->capacity = new_capacity;
  94653. return true;
  94654. }
  94655. /***********************************************************************
  94656. *
  94657. * Class constructor/destructor
  94658. *
  94659. ***********************************************************************/
  94660. FLAC__BitWriter *FLAC__bitwriter_new(void)
  94661. {
  94662. FLAC__BitWriter *bw = (FLAC__BitWriter*)calloc(1, sizeof(FLAC__BitWriter));
  94663. /* note that calloc() sets all members to 0 for us */
  94664. return bw;
  94665. }
  94666. void FLAC__bitwriter_delete(FLAC__BitWriter *bw)
  94667. {
  94668. FLAC__ASSERT(0 != bw);
  94669. FLAC__bitwriter_free(bw);
  94670. free(bw);
  94671. }
  94672. /***********************************************************************
  94673. *
  94674. * Public class methods
  94675. *
  94676. ***********************************************************************/
  94677. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw)
  94678. {
  94679. FLAC__ASSERT(0 != bw);
  94680. bw->words = bw->bits = 0;
  94681. bw->capacity = FLAC__BITWRITER_DEFAULT_CAPACITY;
  94682. bw->buffer = (bwword*)malloc(sizeof(bwword) * bw->capacity);
  94683. if(bw->buffer == 0)
  94684. return false;
  94685. return true;
  94686. }
  94687. void FLAC__bitwriter_free(FLAC__BitWriter *bw)
  94688. {
  94689. FLAC__ASSERT(0 != bw);
  94690. if(0 != bw->buffer)
  94691. free(bw->buffer);
  94692. bw->buffer = 0;
  94693. bw->capacity = 0;
  94694. bw->words = bw->bits = 0;
  94695. }
  94696. void FLAC__bitwriter_clear(FLAC__BitWriter *bw)
  94697. {
  94698. bw->words = bw->bits = 0;
  94699. }
  94700. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out)
  94701. {
  94702. unsigned i, j;
  94703. if(bw == 0) {
  94704. fprintf(out, "bitwriter is NULL\n");
  94705. }
  94706. else {
  94707. fprintf(out, "bitwriter: capacity=%u words=%u bits=%u total_bits=%u\n", bw->capacity, bw->words, bw->bits, FLAC__TOTAL_BITS(bw));
  94708. for(i = 0; i < bw->words; i++) {
  94709. fprintf(out, "%08X: ", i);
  94710. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  94711. fprintf(out, "%01u", bw->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  94712. fprintf(out, "\n");
  94713. }
  94714. if(bw->bits > 0) {
  94715. fprintf(out, "%08X: ", i);
  94716. for(j = 0; j < bw->bits; j++)
  94717. fprintf(out, "%01u", bw->accum & (1 << (bw->bits-j-1)) ? 1:0);
  94718. fprintf(out, "\n");
  94719. }
  94720. }
  94721. }
  94722. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc)
  94723. {
  94724. const FLAC__byte *buffer;
  94725. size_t bytes;
  94726. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  94727. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  94728. return false;
  94729. *crc = (FLAC__uint16)FLAC__crc16(buffer, bytes);
  94730. FLAC__bitwriter_release_buffer(bw);
  94731. return true;
  94732. }
  94733. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc)
  94734. {
  94735. const FLAC__byte *buffer;
  94736. size_t bytes;
  94737. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  94738. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  94739. return false;
  94740. *crc = FLAC__crc8(buffer, bytes);
  94741. FLAC__bitwriter_release_buffer(bw);
  94742. return true;
  94743. }
  94744. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw)
  94745. {
  94746. return ((bw->bits & 7) == 0);
  94747. }
  94748. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw)
  94749. {
  94750. return FLAC__TOTAL_BITS(bw);
  94751. }
  94752. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes)
  94753. {
  94754. FLAC__ASSERT((bw->bits & 7) == 0);
  94755. /* double protection */
  94756. if(bw->bits & 7)
  94757. return false;
  94758. /* if we have bits in the accumulator we have to flush those to the buffer first */
  94759. if(bw->bits) {
  94760. FLAC__ASSERT(bw->words <= bw->capacity);
  94761. if(bw->words == bw->capacity && !bitwriter_grow_(bw, FLAC__BITS_PER_WORD))
  94762. return false;
  94763. /* append bits as complete word to buffer, but don't change bw->accum or bw->bits */
  94764. bw->buffer[bw->words] = SWAP_BE_WORD_TO_HOST(bw->accum << (FLAC__BITS_PER_WORD-bw->bits));
  94765. }
  94766. /* now we can just return what we have */
  94767. *buffer = (FLAC__byte*)bw->buffer;
  94768. *bytes = (FLAC__BYTES_PER_WORD * bw->words) + (bw->bits >> 3);
  94769. return true;
  94770. }
  94771. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw)
  94772. {
  94773. /* nothing to do. in the future, strict checking of a 'writer-is-in-
  94774. * get-mode' flag could be added everywhere and then cleared here
  94775. */
  94776. (void)bw;
  94777. }
  94778. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits)
  94779. {
  94780. unsigned n;
  94781. FLAC__ASSERT(0 != bw);
  94782. FLAC__ASSERT(0 != bw->buffer);
  94783. if(bits == 0)
  94784. return true;
  94785. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94786. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  94787. return false;
  94788. /* first part gets to word alignment */
  94789. if(bw->bits) {
  94790. n = min(FLAC__BITS_PER_WORD - bw->bits, bits);
  94791. bw->accum <<= n;
  94792. bits -= n;
  94793. bw->bits += n;
  94794. if(bw->bits == FLAC__BITS_PER_WORD) {
  94795. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94796. bw->bits = 0;
  94797. }
  94798. else
  94799. return true;
  94800. }
  94801. /* do whole words */
  94802. while(bits >= FLAC__BITS_PER_WORD) {
  94803. bw->buffer[bw->words++] = 0;
  94804. bits -= FLAC__BITS_PER_WORD;
  94805. }
  94806. /* do any leftovers */
  94807. if(bits > 0) {
  94808. bw->accum = 0;
  94809. bw->bits = bits;
  94810. }
  94811. return true;
  94812. }
  94813. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits)
  94814. {
  94815. register unsigned left;
  94816. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  94817. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  94818. FLAC__ASSERT(0 != bw);
  94819. FLAC__ASSERT(0 != bw->buffer);
  94820. FLAC__ASSERT(bits <= 32);
  94821. if(bits == 0)
  94822. return true;
  94823. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94824. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  94825. return false;
  94826. left = FLAC__BITS_PER_WORD - bw->bits;
  94827. if(bits < left) {
  94828. bw->accum <<= bits;
  94829. bw->accum |= val;
  94830. bw->bits += bits;
  94831. }
  94832. 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 */
  94833. bw->accum <<= left;
  94834. bw->accum |= val >> (bw->bits = bits - left);
  94835. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94836. bw->accum = val;
  94837. }
  94838. else {
  94839. bw->accum = val;
  94840. bw->bits = 0;
  94841. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(val);
  94842. }
  94843. return true;
  94844. }
  94845. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits)
  94846. {
  94847. /* zero-out unused bits */
  94848. if(bits < 32)
  94849. val &= (~(0xffffffff << bits));
  94850. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  94851. }
  94852. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits)
  94853. {
  94854. /* this could be a little faster but it's not used for much */
  94855. if(bits > 32) {
  94856. return
  94857. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(val>>32), bits-32) &&
  94858. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 32);
  94859. }
  94860. else
  94861. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  94862. }
  94863. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val)
  94864. {
  94865. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  94866. if(!FLAC__bitwriter_write_raw_uint32(bw, val & 0xff, 8))
  94867. return false;
  94868. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>8) & 0xff, 8))
  94869. return false;
  94870. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>16) & 0xff, 8))
  94871. return false;
  94872. if(!FLAC__bitwriter_write_raw_uint32(bw, val>>24, 8))
  94873. return false;
  94874. return true;
  94875. }
  94876. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals)
  94877. {
  94878. unsigned i;
  94879. /* this could be faster but currently we don't need it to be since it's only used for writing metadata */
  94880. for(i = 0; i < nvals; i++) {
  94881. if(!FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(vals[i]), 8))
  94882. return false;
  94883. }
  94884. return true;
  94885. }
  94886. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val)
  94887. {
  94888. if(val < 32)
  94889. return FLAC__bitwriter_write_raw_uint32(bw, 1, ++val);
  94890. else
  94891. return
  94892. FLAC__bitwriter_write_zeroes(bw, val) &&
  94893. FLAC__bitwriter_write_raw_uint32(bw, 1, 1);
  94894. }
  94895. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter)
  94896. {
  94897. FLAC__uint32 uval;
  94898. FLAC__ASSERT(parameter < sizeof(unsigned)*8);
  94899. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  94900. uval = (val<<1) ^ (val>>31);
  94901. return 1 + parameter + (uval >> parameter);
  94902. }
  94903. #if 0 /* UNUSED */
  94904. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter)
  94905. {
  94906. unsigned bits, msbs, uval;
  94907. unsigned k;
  94908. FLAC__ASSERT(parameter > 0);
  94909. /* fold signed to unsigned */
  94910. if(val < 0)
  94911. uval = (unsigned)(((-(++val)) << 1) + 1);
  94912. else
  94913. uval = (unsigned)(val << 1);
  94914. k = FLAC__bitmath_ilog2(parameter);
  94915. if(parameter == 1u<<k) {
  94916. FLAC__ASSERT(k <= 30);
  94917. msbs = uval >> k;
  94918. bits = 1 + k + msbs;
  94919. }
  94920. else {
  94921. unsigned q, r, d;
  94922. d = (1 << (k+1)) - parameter;
  94923. q = uval / parameter;
  94924. r = uval - (q * parameter);
  94925. bits = 1 + q + k;
  94926. if(r >= d)
  94927. bits++;
  94928. }
  94929. return bits;
  94930. }
  94931. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned uval, unsigned parameter)
  94932. {
  94933. unsigned bits, msbs;
  94934. unsigned k;
  94935. FLAC__ASSERT(parameter > 0);
  94936. k = FLAC__bitmath_ilog2(parameter);
  94937. if(parameter == 1u<<k) {
  94938. FLAC__ASSERT(k <= 30);
  94939. msbs = uval >> k;
  94940. bits = 1 + k + msbs;
  94941. }
  94942. else {
  94943. unsigned q, r, d;
  94944. d = (1 << (k+1)) - parameter;
  94945. q = uval / parameter;
  94946. r = uval - (q * parameter);
  94947. bits = 1 + q + k;
  94948. if(r >= d)
  94949. bits++;
  94950. }
  94951. return bits;
  94952. }
  94953. #endif /* UNUSED */
  94954. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter)
  94955. {
  94956. unsigned total_bits, interesting_bits, msbs;
  94957. FLAC__uint32 uval, pattern;
  94958. FLAC__ASSERT(0 != bw);
  94959. FLAC__ASSERT(0 != bw->buffer);
  94960. FLAC__ASSERT(parameter < 8*sizeof(uval));
  94961. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  94962. uval = (val<<1) ^ (val>>31);
  94963. msbs = uval >> parameter;
  94964. interesting_bits = 1 + parameter;
  94965. total_bits = interesting_bits + msbs;
  94966. pattern = 1 << parameter; /* the unary end bit */
  94967. pattern |= (uval & ((1<<parameter)-1)); /* the binary LSBs */
  94968. if(total_bits <= 32)
  94969. return FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits);
  94970. else
  94971. return
  94972. FLAC__bitwriter_write_zeroes(bw, msbs) && /* write the unary MSBs */
  94973. FLAC__bitwriter_write_raw_uint32(bw, pattern, interesting_bits); /* write the unary end bit and binary LSBs */
  94974. }
  94975. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter)
  94976. {
  94977. const FLAC__uint32 mask1 = FLAC__WORD_ALL_ONES << parameter; /* we val|=mask1 to set the stop bit above it... */
  94978. const FLAC__uint32 mask2 = FLAC__WORD_ALL_ONES >> (31-parameter); /* ...then mask off the bits above the stop bit with val&=mask2*/
  94979. FLAC__uint32 uval;
  94980. unsigned left;
  94981. const unsigned lsbits = 1 + parameter;
  94982. unsigned msbits;
  94983. FLAC__ASSERT(0 != bw);
  94984. FLAC__ASSERT(0 != bw->buffer);
  94985. FLAC__ASSERT(parameter < 8*sizeof(bwword)-1);
  94986. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  94987. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  94988. while(nvals) {
  94989. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  94990. uval = (*vals<<1) ^ (*vals>>31);
  94991. msbits = uval >> parameter;
  94992. #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) */
  94993. if(bw->bits && bw->bits + msbits + lsbits <= FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  94994. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  94995. bw->bits = bw->bits + msbits + lsbits;
  94996. uval |= mask1; /* set stop bit */
  94997. uval &= mask2; /* mask off unused top bits */
  94998. /* NOT: bw->accum <<= msbits + lsbits because msbits+lsbits could be 32, then the shift would be a NOP */
  94999. bw->accum <<= msbits;
  95000. bw->accum <<= lsbits;
  95001. bw->accum |= uval;
  95002. if(bw->bits == FLAC__BITS_PER_WORD) {
  95003. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  95004. bw->bits = 0;
  95005. /* burying the capacity check down here means we have to grow the buffer a little if there are more vals to do */
  95006. if(bw->capacity <= bw->words && nvals > 1 && !bitwriter_grow_(bw, 1)) {
  95007. FLAC__ASSERT(bw->capacity == bw->words);
  95008. return false;
  95009. }
  95010. }
  95011. }
  95012. else {
  95013. #elif 1 /*@@@@@@ OPT: try this version with MSVC6 to see if better, not much difference for gcc-4 */
  95014. if(bw->bits && bw->bits + msbits + lsbits < FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  95015. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  95016. bw->bits = bw->bits + msbits + lsbits;
  95017. uval |= mask1; /* set stop bit */
  95018. uval &= mask2; /* mask off unused top bits */
  95019. bw->accum <<= msbits + lsbits;
  95020. bw->accum |= uval;
  95021. }
  95022. else {
  95023. #endif
  95024. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+msbits+lsbits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  95025. /* OPT: pessimism may cause flurry of false calls to grow_ which eat up all savings before it */
  95026. if(bw->capacity <= bw->words + bw->bits + msbits + 1/*lsbits always fit in 1 bwword*/ && !bitwriter_grow_(bw, msbits+lsbits))
  95027. return false;
  95028. if(msbits) {
  95029. /* first part gets to word alignment */
  95030. if(bw->bits) {
  95031. left = FLAC__BITS_PER_WORD - bw->bits;
  95032. if(msbits < left) {
  95033. bw->accum <<= msbits;
  95034. bw->bits += msbits;
  95035. goto break1;
  95036. }
  95037. else {
  95038. bw->accum <<= left;
  95039. msbits -= left;
  95040. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  95041. bw->bits = 0;
  95042. }
  95043. }
  95044. /* do whole words */
  95045. while(msbits >= FLAC__BITS_PER_WORD) {
  95046. bw->buffer[bw->words++] = 0;
  95047. msbits -= FLAC__BITS_PER_WORD;
  95048. }
  95049. /* do any leftovers */
  95050. if(msbits > 0) {
  95051. bw->accum = 0;
  95052. bw->bits = msbits;
  95053. }
  95054. }
  95055. break1:
  95056. uval |= mask1; /* set stop bit */
  95057. uval &= mask2; /* mask off unused top bits */
  95058. left = FLAC__BITS_PER_WORD - bw->bits;
  95059. if(lsbits < left) {
  95060. bw->accum <<= lsbits;
  95061. bw->accum |= uval;
  95062. bw->bits += lsbits;
  95063. }
  95064. else {
  95065. /* if bw->bits == 0, left==FLAC__BITS_PER_WORD which will always
  95066. * be > lsbits (because of previous assertions) so it would have
  95067. * triggered the (lsbits<left) case above.
  95068. */
  95069. FLAC__ASSERT(bw->bits);
  95070. FLAC__ASSERT(left < FLAC__BITS_PER_WORD);
  95071. bw->accum <<= left;
  95072. bw->accum |= uval >> (bw->bits = lsbits - left);
  95073. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  95074. bw->accum = uval;
  95075. }
  95076. #if 1
  95077. }
  95078. #endif
  95079. vals++;
  95080. nvals--;
  95081. }
  95082. return true;
  95083. }
  95084. #if 0 /* UNUSED */
  95085. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter)
  95086. {
  95087. unsigned total_bits, msbs, uval;
  95088. unsigned k;
  95089. FLAC__ASSERT(0 != bw);
  95090. FLAC__ASSERT(0 != bw->buffer);
  95091. FLAC__ASSERT(parameter > 0);
  95092. /* fold signed to unsigned */
  95093. if(val < 0)
  95094. uval = (unsigned)(((-(++val)) << 1) + 1);
  95095. else
  95096. uval = (unsigned)(val << 1);
  95097. k = FLAC__bitmath_ilog2(parameter);
  95098. if(parameter == 1u<<k) {
  95099. unsigned pattern;
  95100. FLAC__ASSERT(k <= 30);
  95101. msbs = uval >> k;
  95102. total_bits = 1 + k + msbs;
  95103. pattern = 1 << k; /* the unary end bit */
  95104. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  95105. if(total_bits <= 32) {
  95106. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  95107. return false;
  95108. }
  95109. else {
  95110. /* write the unary MSBs */
  95111. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  95112. return false;
  95113. /* write the unary end bit and binary LSBs */
  95114. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  95115. return false;
  95116. }
  95117. }
  95118. else {
  95119. unsigned q, r, d;
  95120. d = (1 << (k+1)) - parameter;
  95121. q = uval / parameter;
  95122. r = uval - (q * parameter);
  95123. /* write the unary MSBs */
  95124. if(!FLAC__bitwriter_write_zeroes(bw, q))
  95125. return false;
  95126. /* write the unary end bit */
  95127. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  95128. return false;
  95129. /* write the binary LSBs */
  95130. if(r >= d) {
  95131. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  95132. return false;
  95133. }
  95134. else {
  95135. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  95136. return false;
  95137. }
  95138. }
  95139. return true;
  95140. }
  95141. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned uval, unsigned parameter)
  95142. {
  95143. unsigned total_bits, msbs;
  95144. unsigned k;
  95145. FLAC__ASSERT(0 != bw);
  95146. FLAC__ASSERT(0 != bw->buffer);
  95147. FLAC__ASSERT(parameter > 0);
  95148. k = FLAC__bitmath_ilog2(parameter);
  95149. if(parameter == 1u<<k) {
  95150. unsigned pattern;
  95151. FLAC__ASSERT(k <= 30);
  95152. msbs = uval >> k;
  95153. total_bits = 1 + k + msbs;
  95154. pattern = 1 << k; /* the unary end bit */
  95155. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  95156. if(total_bits <= 32) {
  95157. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  95158. return false;
  95159. }
  95160. else {
  95161. /* write the unary MSBs */
  95162. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  95163. return false;
  95164. /* write the unary end bit and binary LSBs */
  95165. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  95166. return false;
  95167. }
  95168. }
  95169. else {
  95170. unsigned q, r, d;
  95171. d = (1 << (k+1)) - parameter;
  95172. q = uval / parameter;
  95173. r = uval - (q * parameter);
  95174. /* write the unary MSBs */
  95175. if(!FLAC__bitwriter_write_zeroes(bw, q))
  95176. return false;
  95177. /* write the unary end bit */
  95178. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  95179. return false;
  95180. /* write the binary LSBs */
  95181. if(r >= d) {
  95182. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  95183. return false;
  95184. }
  95185. else {
  95186. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  95187. return false;
  95188. }
  95189. }
  95190. return true;
  95191. }
  95192. #endif /* UNUSED */
  95193. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val)
  95194. {
  95195. FLAC__bool ok = 1;
  95196. FLAC__ASSERT(0 != bw);
  95197. FLAC__ASSERT(0 != bw->buffer);
  95198. FLAC__ASSERT(!(val & 0x80000000)); /* this version only handles 31 bits */
  95199. if(val < 0x80) {
  95200. return FLAC__bitwriter_write_raw_uint32(bw, val, 8);
  95201. }
  95202. else if(val < 0x800) {
  95203. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (val>>6), 8);
  95204. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95205. }
  95206. else if(val < 0x10000) {
  95207. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (val>>12), 8);
  95208. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  95209. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95210. }
  95211. else if(val < 0x200000) {
  95212. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (val>>18), 8);
  95213. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  95214. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  95215. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95216. }
  95217. else if(val < 0x4000000) {
  95218. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (val>>24), 8);
  95219. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  95220. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  95221. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  95222. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95223. }
  95224. else {
  95225. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (val>>30), 8);
  95226. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>24)&0x3F), 8);
  95227. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  95228. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  95229. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  95230. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95231. }
  95232. return ok;
  95233. }
  95234. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val)
  95235. {
  95236. FLAC__bool ok = 1;
  95237. FLAC__ASSERT(0 != bw);
  95238. FLAC__ASSERT(0 != bw->buffer);
  95239. FLAC__ASSERT(!(val & FLAC__U64L(0xFFFFFFF000000000))); /* this version only handles 36 bits */
  95240. if(val < 0x80) {
  95241. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 8);
  95242. }
  95243. else if(val < 0x800) {
  95244. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (FLAC__uint32)(val>>6), 8);
  95245. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95246. }
  95247. else if(val < 0x10000) {
  95248. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (FLAC__uint32)(val>>12), 8);
  95249. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95250. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95251. }
  95252. else if(val < 0x200000) {
  95253. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (FLAC__uint32)(val>>18), 8);
  95254. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95255. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95256. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95257. }
  95258. else if(val < 0x4000000) {
  95259. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (FLAC__uint32)(val>>24), 8);
  95260. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  95261. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95262. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95263. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95264. }
  95265. else if(val < 0x80000000) {
  95266. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (FLAC__uint32)(val>>30), 8);
  95267. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  95268. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  95269. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95270. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95271. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95272. }
  95273. else {
  95274. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFE, 8);
  95275. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>30)&0x3F), 8);
  95276. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  95277. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  95278. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95279. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95280. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95281. }
  95282. return ok;
  95283. }
  95284. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw)
  95285. {
  95286. /* 0-pad to byte boundary */
  95287. if(bw->bits & 7u)
  95288. return FLAC__bitwriter_write_zeroes(bw, 8 - (bw->bits & 7u));
  95289. else
  95290. return true;
  95291. }
  95292. #endif
  95293. /*** End of inlined file: bitwriter.c ***/
  95294. /*** Start of inlined file: cpu.c ***/
  95295. /*** Start of inlined file: juce_FlacHeader.h ***/
  95296. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95297. // tasks..
  95298. #define VERSION "1.2.1"
  95299. #define FLAC__NO_DLL 1
  95300. #if JUCE_MSVC
  95301. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95302. #endif
  95303. #if JUCE_MAC
  95304. #define FLAC__SYS_DARWIN 1
  95305. #endif
  95306. /*** End of inlined file: juce_FlacHeader.h ***/
  95307. #if JUCE_USE_FLAC
  95308. #if HAVE_CONFIG_H
  95309. # include <config.h>
  95310. #endif
  95311. #include <stdlib.h>
  95312. #include <stdio.h>
  95313. #if defined FLAC__CPU_IA32
  95314. # include <signal.h>
  95315. #elif defined FLAC__CPU_PPC
  95316. # if !defined FLAC__NO_ASM
  95317. # if defined FLAC__SYS_DARWIN
  95318. # include <sys/sysctl.h>
  95319. # include <mach/mach.h>
  95320. # include <mach/mach_host.h>
  95321. # include <mach/host_info.h>
  95322. # include <mach/machine.h>
  95323. # ifndef CPU_SUBTYPE_POWERPC_970
  95324. # define CPU_SUBTYPE_POWERPC_970 ((cpu_subtype_t) 100)
  95325. # endif
  95326. # else /* FLAC__SYS_DARWIN */
  95327. # include <signal.h>
  95328. # include <setjmp.h>
  95329. static sigjmp_buf jmpbuf;
  95330. static volatile sig_atomic_t canjump = 0;
  95331. static void sigill_handler (int sig)
  95332. {
  95333. if (!canjump) {
  95334. signal (sig, SIG_DFL);
  95335. raise (sig);
  95336. }
  95337. canjump = 0;
  95338. siglongjmp (jmpbuf, 1);
  95339. }
  95340. # endif /* FLAC__SYS_DARWIN */
  95341. # endif /* FLAC__NO_ASM */
  95342. #endif /* FLAC__CPU_PPC */
  95343. #if defined (__NetBSD__) || defined(__OpenBSD__)
  95344. #include <sys/param.h>
  95345. #include <sys/sysctl.h>
  95346. #include <machine/cpu.h>
  95347. #endif
  95348. #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
  95349. #include <sys/types.h>
  95350. #include <sys/sysctl.h>
  95351. #endif
  95352. #if defined(__APPLE__)
  95353. /* how to get sysctlbyname()? */
  95354. #endif
  95355. /* these are flags in EDX of CPUID AX=00000001 */
  95356. static const unsigned FLAC__CPUINFO_IA32_CPUID_CMOV = 0x00008000;
  95357. static const unsigned FLAC__CPUINFO_IA32_CPUID_MMX = 0x00800000;
  95358. static const unsigned FLAC__CPUINFO_IA32_CPUID_FXSR = 0x01000000;
  95359. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE = 0x02000000;
  95360. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE2 = 0x04000000;
  95361. /* these are flags in ECX of CPUID AX=00000001 */
  95362. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE3 = 0x00000001;
  95363. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSSE3 = 0x00000200;
  95364. /* these are flags in EDX of CPUID AX=80000001 */
  95365. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW = 0x80000000;
  95366. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW = 0x40000000;
  95367. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX = 0x00400000;
  95368. /*
  95369. * Extra stuff needed for detection of OS support for SSE on IA-32
  95370. */
  95371. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM && !defined FLAC__NO_SSE_OS && !defined FLAC__SSE_OS
  95372. # if defined(__linux__)
  95373. /*
  95374. * If the OS doesn't support SSE, we will get here with a SIGILL. We
  95375. * modify the return address to jump over the offending SSE instruction
  95376. * and also the operation following it that indicates the instruction
  95377. * executed successfully. In this way we use no global variables and
  95378. * stay thread-safe.
  95379. *
  95380. * 3 + 3 + 6:
  95381. * 3 bytes for "xorps xmm0,xmm0"
  95382. * 3 bytes for estimate of how long the follwing "inc var" instruction is
  95383. * 6 bytes extra in case our estimate is wrong
  95384. * 12 bytes puts us in the NOP "landing zone"
  95385. */
  95386. # undef USE_OBSOLETE_SIGCONTEXT_FLAVOR /* #define this to use the older signal handler method */
  95387. # ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  95388. static void sigill_handler_sse_os(int signal, struct sigcontext sc)
  95389. {
  95390. (void)signal;
  95391. sc.eip += 3 + 3 + 6;
  95392. }
  95393. # else
  95394. # include <sys/ucontext.h>
  95395. static void sigill_handler_sse_os(int signal, siginfo_t *si, void *uc)
  95396. {
  95397. (void)signal, (void)si;
  95398. ((ucontext_t*)uc)->uc_mcontext.gregs[14/*REG_EIP*/] += 3 + 3 + 6;
  95399. }
  95400. # endif
  95401. # elif defined(_MSC_VER)
  95402. # include <windows.h>
  95403. # undef USE_TRY_CATCH_FLAVOR /* #define this to use the try/catch method for catching illegal opcode exception */
  95404. # ifdef USE_TRY_CATCH_FLAVOR
  95405. # else
  95406. LONG CALLBACK sigill_handler_sse_os(EXCEPTION_POINTERS *ep)
  95407. {
  95408. if(ep->ExceptionRecord->ExceptionCode == EXCEPTION_ILLEGAL_INSTRUCTION) {
  95409. ep->ContextRecord->Eip += 3 + 3 + 6;
  95410. return EXCEPTION_CONTINUE_EXECUTION;
  95411. }
  95412. return EXCEPTION_CONTINUE_SEARCH;
  95413. }
  95414. # endif
  95415. # endif
  95416. #endif
  95417. void FLAC__cpu_info(FLAC__CPUInfo *info)
  95418. {
  95419. /*
  95420. * IA32-specific
  95421. */
  95422. #ifdef FLAC__CPU_IA32
  95423. info->type = FLAC__CPUINFO_TYPE_IA32;
  95424. #if !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  95425. info->use_asm = true; /* we assume a minimum of 80386 with FLAC__CPU_IA32 */
  95426. info->data.ia32.cpuid = FLAC__cpu_have_cpuid_asm_ia32()? true : false;
  95427. info->data.ia32.bswap = info->data.ia32.cpuid; /* CPUID => BSWAP since it came after */
  95428. info->data.ia32.cmov = false;
  95429. info->data.ia32.mmx = false;
  95430. info->data.ia32.fxsr = false;
  95431. info->data.ia32.sse = false;
  95432. info->data.ia32.sse2 = false;
  95433. info->data.ia32.sse3 = false;
  95434. info->data.ia32.ssse3 = false;
  95435. info->data.ia32._3dnow = false;
  95436. info->data.ia32.ext3dnow = false;
  95437. info->data.ia32.extmmx = false;
  95438. if(info->data.ia32.cpuid) {
  95439. /* http://www.sandpile.org/ia32/cpuid.htm */
  95440. FLAC__uint32 flags_edx, flags_ecx;
  95441. FLAC__cpu_info_asm_ia32(&flags_edx, &flags_ecx);
  95442. info->data.ia32.cmov = (flags_edx & FLAC__CPUINFO_IA32_CPUID_CMOV )? true : false;
  95443. info->data.ia32.mmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_MMX )? true : false;
  95444. info->data.ia32.fxsr = (flags_edx & FLAC__CPUINFO_IA32_CPUID_FXSR )? true : false;
  95445. info->data.ia32.sse = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE )? true : false;
  95446. info->data.ia32.sse2 = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE2 )? true : false;
  95447. info->data.ia32.sse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSE3 )? true : false;
  95448. info->data.ia32.ssse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSSE3)? true : false;
  95449. #ifdef FLAC__USE_3DNOW
  95450. flags_edx = FLAC__cpu_info_extended_amd_asm_ia32();
  95451. info->data.ia32._3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW )? true : false;
  95452. info->data.ia32.ext3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW)? true : false;
  95453. info->data.ia32.extmmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX )? true : false;
  95454. #else
  95455. info->data.ia32._3dnow = info->data.ia32.ext3dnow = info->data.ia32.extmmx = false;
  95456. #endif
  95457. #ifdef DEBUG
  95458. fprintf(stderr, "CPU info (IA-32):\n");
  95459. fprintf(stderr, " CPUID ...... %c\n", info->data.ia32.cpuid ? 'Y' : 'n');
  95460. fprintf(stderr, " BSWAP ...... %c\n", info->data.ia32.bswap ? 'Y' : 'n');
  95461. fprintf(stderr, " CMOV ....... %c\n", info->data.ia32.cmov ? 'Y' : 'n');
  95462. fprintf(stderr, " MMX ........ %c\n", info->data.ia32.mmx ? 'Y' : 'n');
  95463. fprintf(stderr, " FXSR ....... %c\n", info->data.ia32.fxsr ? 'Y' : 'n');
  95464. fprintf(stderr, " SSE ........ %c\n", info->data.ia32.sse ? 'Y' : 'n');
  95465. fprintf(stderr, " SSE2 ....... %c\n", info->data.ia32.sse2 ? 'Y' : 'n');
  95466. fprintf(stderr, " SSE3 ....... %c\n", info->data.ia32.sse3 ? 'Y' : 'n');
  95467. fprintf(stderr, " SSSE3 ...... %c\n", info->data.ia32.ssse3 ? 'Y' : 'n');
  95468. fprintf(stderr, " 3DNow! ..... %c\n", info->data.ia32._3dnow ? 'Y' : 'n');
  95469. fprintf(stderr, " 3DNow!-ext . %c\n", info->data.ia32.ext3dnow? 'Y' : 'n');
  95470. fprintf(stderr, " 3DNow!-MMX . %c\n", info->data.ia32.extmmx ? 'Y' : 'n');
  95471. #endif
  95472. /*
  95473. * now have to check for OS support of SSE/SSE2
  95474. */
  95475. if(info->data.ia32.fxsr || info->data.ia32.sse || info->data.ia32.sse2) {
  95476. #if defined FLAC__NO_SSE_OS
  95477. /* assume user knows better than us; turn it off */
  95478. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95479. #elif defined FLAC__SSE_OS
  95480. /* assume user knows better than us; leave as detected above */
  95481. #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__APPLE__)
  95482. int sse = 0;
  95483. size_t len;
  95484. /* at least one of these must work: */
  95485. len = sizeof(sse); sse = sse || (sysctlbyname("hw.instruction_sse", &sse, &len, NULL, 0) == 0 && sse);
  95486. len = sizeof(sse); sse = sse || (sysctlbyname("hw.optional.sse" , &sse, &len, NULL, 0) == 0 && sse); /* __APPLE__ ? */
  95487. if(!sse)
  95488. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95489. #elif defined(__NetBSD__) || defined (__OpenBSD__)
  95490. # if __NetBSD_Version__ >= 105250000 || (defined __OpenBSD__)
  95491. int val = 0, mib[2] = { CTL_MACHDEP, CPU_SSE };
  95492. size_t len = sizeof(val);
  95493. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  95494. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95495. else { /* double-check SSE2 */
  95496. mib[1] = CPU_SSE2;
  95497. len = sizeof(val);
  95498. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  95499. info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95500. }
  95501. # else
  95502. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95503. # endif
  95504. #elif defined(__linux__)
  95505. int sse = 0;
  95506. struct sigaction sigill_save;
  95507. #ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  95508. if(0 == sigaction(SIGILL, NULL, &sigill_save) && signal(SIGILL, (void (*)(int))sigill_handler_sse_os) != SIG_ERR)
  95509. #else
  95510. struct sigaction sigill_sse;
  95511. sigill_sse.sa_sigaction = sigill_handler_sse_os;
  95512. __sigemptyset(&sigill_sse.sa_mask);
  95513. 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 */
  95514. if(0 == sigaction(SIGILL, &sigill_sse, &sigill_save))
  95515. #endif
  95516. {
  95517. /* http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html */
  95518. /* see sigill_handler_sse_os() for an explanation of the following: */
  95519. asm volatile (
  95520. "xorl %0,%0\n\t" /* for some reason, still need to do this to clear 'sse' var */
  95521. "xorps %%xmm0,%%xmm0\n\t" /* will cause SIGILL if unsupported by OS */
  95522. "incl %0\n\t" /* SIGILL handler will jump over this */
  95523. /* landing zone */
  95524. "nop\n\t" /* SIGILL jump lands here if "inc" is 9 bytes */
  95525. "nop\n\t"
  95526. "nop\n\t"
  95527. "nop\n\t"
  95528. "nop\n\t"
  95529. "nop\n\t"
  95530. "nop\n\t" /* SIGILL jump lands here if "inc" is 3 bytes (expected) */
  95531. "nop\n\t"
  95532. "nop" /* SIGILL jump lands here if "inc" is 1 byte */
  95533. : "=r"(sse)
  95534. : "r"(sse)
  95535. );
  95536. sigaction(SIGILL, &sigill_save, NULL);
  95537. }
  95538. if(!sse)
  95539. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95540. #elif defined(_MSC_VER)
  95541. # ifdef USE_TRY_CATCH_FLAVOR
  95542. _try {
  95543. __asm {
  95544. # if _MSC_VER <= 1200
  95545. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  95546. _emit 0x0F
  95547. _emit 0x57
  95548. _emit 0xC0
  95549. # else
  95550. xorps xmm0,xmm0
  95551. # endif
  95552. }
  95553. }
  95554. _except(EXCEPTION_EXECUTE_HANDLER) {
  95555. if (_exception_code() == STATUS_ILLEGAL_INSTRUCTION)
  95556. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95557. }
  95558. # else
  95559. int sse = 0;
  95560. LPTOP_LEVEL_EXCEPTION_FILTER save = SetUnhandledExceptionFilter(sigill_handler_sse_os);
  95561. /* see GCC version above for explanation */
  95562. /* http://msdn2.microsoft.com/en-us/library/4ks26t93.aspx */
  95563. /* http://www.codeproject.com/cpp/gccasm.asp */
  95564. /* http://www.hick.org/~mmiller/msvc_inline_asm.html */
  95565. __asm {
  95566. # if _MSC_VER <= 1200
  95567. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  95568. _emit 0x0F
  95569. _emit 0x57
  95570. _emit 0xC0
  95571. # else
  95572. xorps xmm0,xmm0
  95573. # endif
  95574. inc sse
  95575. nop
  95576. nop
  95577. nop
  95578. nop
  95579. nop
  95580. nop
  95581. nop
  95582. nop
  95583. nop
  95584. }
  95585. SetUnhandledExceptionFilter(save);
  95586. if(!sse)
  95587. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95588. # endif
  95589. #else
  95590. /* no way to test, disable to be safe */
  95591. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95592. #endif
  95593. #ifdef DEBUG
  95594. fprintf(stderr, " SSE OS sup . %c\n", info->data.ia32.sse ? 'Y' : 'n');
  95595. #endif
  95596. }
  95597. }
  95598. #else
  95599. info->use_asm = false;
  95600. #endif
  95601. /*
  95602. * PPC-specific
  95603. */
  95604. #elif defined FLAC__CPU_PPC
  95605. info->type = FLAC__CPUINFO_TYPE_PPC;
  95606. # if !defined FLAC__NO_ASM
  95607. info->use_asm = true;
  95608. # ifdef FLAC__USE_ALTIVEC
  95609. # if defined FLAC__SYS_DARWIN
  95610. {
  95611. int val = 0, mib[2] = { CTL_HW, HW_VECTORUNIT };
  95612. size_t len = sizeof(val);
  95613. info->data.ppc.altivec = !(sysctl(mib, 2, &val, &len, NULL, 0) || !val);
  95614. }
  95615. {
  95616. host_basic_info_data_t hostInfo;
  95617. mach_msg_type_number_t infoCount;
  95618. infoCount = HOST_BASIC_INFO_COUNT;
  95619. host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)&hostInfo, &infoCount);
  95620. info->data.ppc.ppc64 = (hostInfo.cpu_type == CPU_TYPE_POWERPC) && (hostInfo.cpu_subtype == CPU_SUBTYPE_POWERPC_970);
  95621. }
  95622. # else /* FLAC__USE_ALTIVEC && !FLAC__SYS_DARWIN */
  95623. {
  95624. /* no Darwin, do it the brute-force way */
  95625. /* @@@@@@ this is not thread-safe; replace with SSE OS method above or remove */
  95626. info->data.ppc.altivec = 0;
  95627. info->data.ppc.ppc64 = 0;
  95628. signal (SIGILL, sigill_handler);
  95629. canjump = 0;
  95630. if (!sigsetjmp (jmpbuf, 1)) {
  95631. canjump = 1;
  95632. asm volatile (
  95633. "mtspr 256, %0\n\t"
  95634. "vand %%v0, %%v0, %%v0"
  95635. :
  95636. : "r" (-1)
  95637. );
  95638. info->data.ppc.altivec = 1;
  95639. }
  95640. canjump = 0;
  95641. if (!sigsetjmp (jmpbuf, 1)) {
  95642. int x = 0;
  95643. canjump = 1;
  95644. /* PPC64 hardware implements the cntlzd instruction */
  95645. asm volatile ("cntlzd %0, %1" : "=r" (x) : "r" (x) );
  95646. info->data.ppc.ppc64 = 1;
  95647. }
  95648. signal (SIGILL, SIG_DFL); /*@@@@@@ should save and restore old signal */
  95649. }
  95650. # endif
  95651. # else /* !FLAC__USE_ALTIVEC */
  95652. info->data.ppc.altivec = 0;
  95653. info->data.ppc.ppc64 = 0;
  95654. # endif
  95655. # else
  95656. info->use_asm = false;
  95657. # endif
  95658. /*
  95659. * unknown CPI
  95660. */
  95661. #else
  95662. info->type = FLAC__CPUINFO_TYPE_UNKNOWN;
  95663. info->use_asm = false;
  95664. #endif
  95665. }
  95666. #endif
  95667. /*** End of inlined file: cpu.c ***/
  95668. /*** Start of inlined file: crc.c ***/
  95669. /*** Start of inlined file: juce_FlacHeader.h ***/
  95670. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95671. // tasks..
  95672. #define VERSION "1.2.1"
  95673. #define FLAC__NO_DLL 1
  95674. #if JUCE_MSVC
  95675. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95676. #endif
  95677. #if JUCE_MAC
  95678. #define FLAC__SYS_DARWIN 1
  95679. #endif
  95680. /*** End of inlined file: juce_FlacHeader.h ***/
  95681. #if JUCE_USE_FLAC
  95682. #if HAVE_CONFIG_H
  95683. # include <config.h>
  95684. #endif
  95685. /* CRC-8, poly = x^8 + x^2 + x^1 + x^0, init = 0 */
  95686. FLAC__byte const FLAC__crc8_table[256] = {
  95687. 0x00, 0x07, 0x0E, 0x09, 0x1C, 0x1B, 0x12, 0x15,
  95688. 0x38, 0x3F, 0x36, 0x31, 0x24, 0x23, 0x2A, 0x2D,
  95689. 0x70, 0x77, 0x7E, 0x79, 0x6C, 0x6B, 0x62, 0x65,
  95690. 0x48, 0x4F, 0x46, 0x41, 0x54, 0x53, 0x5A, 0x5D,
  95691. 0xE0, 0xE7, 0xEE, 0xE9, 0xFC, 0xFB, 0xF2, 0xF5,
  95692. 0xD8, 0xDF, 0xD6, 0xD1, 0xC4, 0xC3, 0xCA, 0xCD,
  95693. 0x90, 0x97, 0x9E, 0x99, 0x8C, 0x8B, 0x82, 0x85,
  95694. 0xA8, 0xAF, 0xA6, 0xA1, 0xB4, 0xB3, 0xBA, 0xBD,
  95695. 0xC7, 0xC0, 0xC9, 0xCE, 0xDB, 0xDC, 0xD5, 0xD2,
  95696. 0xFF, 0xF8, 0xF1, 0xF6, 0xE3, 0xE4, 0xED, 0xEA,
  95697. 0xB7, 0xB0, 0xB9, 0xBE, 0xAB, 0xAC, 0xA5, 0xA2,
  95698. 0x8F, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9D, 0x9A,
  95699. 0x27, 0x20, 0x29, 0x2E, 0x3B, 0x3C, 0x35, 0x32,
  95700. 0x1F, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0D, 0x0A,
  95701. 0x57, 0x50, 0x59, 0x5E, 0x4B, 0x4C, 0x45, 0x42,
  95702. 0x6F, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7D, 0x7A,
  95703. 0x89, 0x8E, 0x87, 0x80, 0x95, 0x92, 0x9B, 0x9C,
  95704. 0xB1, 0xB6, 0xBF, 0xB8, 0xAD, 0xAA, 0xA3, 0xA4,
  95705. 0xF9, 0xFE, 0xF7, 0xF0, 0xE5, 0xE2, 0xEB, 0xEC,
  95706. 0xC1, 0xC6, 0xCF, 0xC8, 0xDD, 0xDA, 0xD3, 0xD4,
  95707. 0x69, 0x6E, 0x67, 0x60, 0x75, 0x72, 0x7B, 0x7C,
  95708. 0x51, 0x56, 0x5F, 0x58, 0x4D, 0x4A, 0x43, 0x44,
  95709. 0x19, 0x1E, 0x17, 0x10, 0x05, 0x02, 0x0B, 0x0C,
  95710. 0x21, 0x26, 0x2F, 0x28, 0x3D, 0x3A, 0x33, 0x34,
  95711. 0x4E, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5C, 0x5B,
  95712. 0x76, 0x71, 0x78, 0x7F, 0x6A, 0x6D, 0x64, 0x63,
  95713. 0x3E, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2C, 0x2B,
  95714. 0x06, 0x01, 0x08, 0x0F, 0x1A, 0x1D, 0x14, 0x13,
  95715. 0xAE, 0xA9, 0xA0, 0xA7, 0xB2, 0xB5, 0xBC, 0xBB,
  95716. 0x96, 0x91, 0x98, 0x9F, 0x8A, 0x8D, 0x84, 0x83,
  95717. 0xDE, 0xD9, 0xD0, 0xD7, 0xC2, 0xC5, 0xCC, 0xCB,
  95718. 0xE6, 0xE1, 0xE8, 0xEF, 0xFA, 0xFD, 0xF4, 0xF3
  95719. };
  95720. /* CRC-16, poly = x^16 + x^15 + x^2 + x^0, init = 0 */
  95721. unsigned FLAC__crc16_table[256] = {
  95722. 0x0000, 0x8005, 0x800f, 0x000a, 0x801b, 0x001e, 0x0014, 0x8011,
  95723. 0x8033, 0x0036, 0x003c, 0x8039, 0x0028, 0x802d, 0x8027, 0x0022,
  95724. 0x8063, 0x0066, 0x006c, 0x8069, 0x0078, 0x807d, 0x8077, 0x0072,
  95725. 0x0050, 0x8055, 0x805f, 0x005a, 0x804b, 0x004e, 0x0044, 0x8041,
  95726. 0x80c3, 0x00c6, 0x00cc, 0x80c9, 0x00d8, 0x80dd, 0x80d7, 0x00d2,
  95727. 0x00f0, 0x80f5, 0x80ff, 0x00fa, 0x80eb, 0x00ee, 0x00e4, 0x80e1,
  95728. 0x00a0, 0x80a5, 0x80af, 0x00aa, 0x80bb, 0x00be, 0x00b4, 0x80b1,
  95729. 0x8093, 0x0096, 0x009c, 0x8099, 0x0088, 0x808d, 0x8087, 0x0082,
  95730. 0x8183, 0x0186, 0x018c, 0x8189, 0x0198, 0x819d, 0x8197, 0x0192,
  95731. 0x01b0, 0x81b5, 0x81bf, 0x01ba, 0x81ab, 0x01ae, 0x01a4, 0x81a1,
  95732. 0x01e0, 0x81e5, 0x81ef, 0x01ea, 0x81fb, 0x01fe, 0x01f4, 0x81f1,
  95733. 0x81d3, 0x01d6, 0x01dc, 0x81d9, 0x01c8, 0x81cd, 0x81c7, 0x01c2,
  95734. 0x0140, 0x8145, 0x814f, 0x014a, 0x815b, 0x015e, 0x0154, 0x8151,
  95735. 0x8173, 0x0176, 0x017c, 0x8179, 0x0168, 0x816d, 0x8167, 0x0162,
  95736. 0x8123, 0x0126, 0x012c, 0x8129, 0x0138, 0x813d, 0x8137, 0x0132,
  95737. 0x0110, 0x8115, 0x811f, 0x011a, 0x810b, 0x010e, 0x0104, 0x8101,
  95738. 0x8303, 0x0306, 0x030c, 0x8309, 0x0318, 0x831d, 0x8317, 0x0312,
  95739. 0x0330, 0x8335, 0x833f, 0x033a, 0x832b, 0x032e, 0x0324, 0x8321,
  95740. 0x0360, 0x8365, 0x836f, 0x036a, 0x837b, 0x037e, 0x0374, 0x8371,
  95741. 0x8353, 0x0356, 0x035c, 0x8359, 0x0348, 0x834d, 0x8347, 0x0342,
  95742. 0x03c0, 0x83c5, 0x83cf, 0x03ca, 0x83db, 0x03de, 0x03d4, 0x83d1,
  95743. 0x83f3, 0x03f6, 0x03fc, 0x83f9, 0x03e8, 0x83ed, 0x83e7, 0x03e2,
  95744. 0x83a3, 0x03a6, 0x03ac, 0x83a9, 0x03b8, 0x83bd, 0x83b7, 0x03b2,
  95745. 0x0390, 0x8395, 0x839f, 0x039a, 0x838b, 0x038e, 0x0384, 0x8381,
  95746. 0x0280, 0x8285, 0x828f, 0x028a, 0x829b, 0x029e, 0x0294, 0x8291,
  95747. 0x82b3, 0x02b6, 0x02bc, 0x82b9, 0x02a8, 0x82ad, 0x82a7, 0x02a2,
  95748. 0x82e3, 0x02e6, 0x02ec, 0x82e9, 0x02f8, 0x82fd, 0x82f7, 0x02f2,
  95749. 0x02d0, 0x82d5, 0x82df, 0x02da, 0x82cb, 0x02ce, 0x02c4, 0x82c1,
  95750. 0x8243, 0x0246, 0x024c, 0x8249, 0x0258, 0x825d, 0x8257, 0x0252,
  95751. 0x0270, 0x8275, 0x827f, 0x027a, 0x826b, 0x026e, 0x0264, 0x8261,
  95752. 0x0220, 0x8225, 0x822f, 0x022a, 0x823b, 0x023e, 0x0234, 0x8231,
  95753. 0x8213, 0x0216, 0x021c, 0x8219, 0x0208, 0x820d, 0x8207, 0x0202
  95754. };
  95755. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc)
  95756. {
  95757. *crc = FLAC__crc8_table[*crc ^ data];
  95758. }
  95759. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc)
  95760. {
  95761. while(len--)
  95762. *crc = FLAC__crc8_table[*crc ^ *data++];
  95763. }
  95764. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len)
  95765. {
  95766. FLAC__uint8 crc = 0;
  95767. while(len--)
  95768. crc = FLAC__crc8_table[crc ^ *data++];
  95769. return crc;
  95770. }
  95771. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len)
  95772. {
  95773. unsigned crc = 0;
  95774. while(len--)
  95775. crc = ((crc<<8) ^ FLAC__crc16_table[(crc>>8) ^ *data++]) & 0xffff;
  95776. return crc;
  95777. }
  95778. #endif
  95779. /*** End of inlined file: crc.c ***/
  95780. /*** Start of inlined file: fixed.c ***/
  95781. /*** Start of inlined file: juce_FlacHeader.h ***/
  95782. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95783. // tasks..
  95784. #define VERSION "1.2.1"
  95785. #define FLAC__NO_DLL 1
  95786. #if JUCE_MSVC
  95787. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95788. #endif
  95789. #if JUCE_MAC
  95790. #define FLAC__SYS_DARWIN 1
  95791. #endif
  95792. /*** End of inlined file: juce_FlacHeader.h ***/
  95793. #if JUCE_USE_FLAC
  95794. #if HAVE_CONFIG_H
  95795. # include <config.h>
  95796. #endif
  95797. #include <math.h>
  95798. #include <string.h>
  95799. /*** Start of inlined file: fixed.h ***/
  95800. #ifndef FLAC__PRIVATE__FIXED_H
  95801. #define FLAC__PRIVATE__FIXED_H
  95802. #ifdef HAVE_CONFIG_H
  95803. #include <config.h>
  95804. #endif
  95805. /*** Start of inlined file: float.h ***/
  95806. #ifndef FLAC__PRIVATE__FLOAT_H
  95807. #define FLAC__PRIVATE__FLOAT_H
  95808. #ifdef HAVE_CONFIG_H
  95809. #include <config.h>
  95810. #endif
  95811. /*
  95812. * These typedefs make it easier to ensure that integer versions of
  95813. * the library really only contain integer operations. All the code
  95814. * in libFLAC should use FLAC__float and FLAC__double in place of
  95815. * float and double, and be protected by checks of the macro
  95816. * FLAC__INTEGER_ONLY_LIBRARY.
  95817. *
  95818. * FLAC__real is the basic floating point type used in LPC analysis.
  95819. */
  95820. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95821. typedef double FLAC__double;
  95822. typedef float FLAC__float;
  95823. /*
  95824. * WATCHOUT: changing FLAC__real will change the signatures of many
  95825. * functions that have assembly language equivalents and break them.
  95826. */
  95827. typedef float FLAC__real;
  95828. #else
  95829. /*
  95830. * The convention for FLAC__fixedpoint is to use the upper 16 bits
  95831. * for the integer part and lower 16 bits for the fractional part.
  95832. */
  95833. typedef FLAC__int32 FLAC__fixedpoint;
  95834. extern const FLAC__fixedpoint FLAC__FP_ZERO;
  95835. extern const FLAC__fixedpoint FLAC__FP_ONE_HALF;
  95836. extern const FLAC__fixedpoint FLAC__FP_ONE;
  95837. extern const FLAC__fixedpoint FLAC__FP_LN2;
  95838. extern const FLAC__fixedpoint FLAC__FP_E;
  95839. #define FLAC__fixedpoint_trunc(x) ((x)>>16)
  95840. #define FLAC__fixedpoint_mul(x, y) ( (FLAC__fixedpoint) ( ((FLAC__int64)(x)*(FLAC__int64)(y)) >> 16 ) )
  95841. #define FLAC__fixedpoint_div(x, y) ( (FLAC__fixedpoint) ( ( ((FLAC__int64)(x)<<32) / (FLAC__int64)(y) ) >> 16 ) )
  95842. /*
  95843. * FLAC__fixedpoint_log2()
  95844. * --------------------------------------------------------------------
  95845. * Returns the base-2 logarithm of the fixed-point number 'x' using an
  95846. * algorithm by Knuth for x >= 1.0
  95847. *
  95848. * 'fracbits' is the number of fractional bits of 'x'. 'fracbits' must
  95849. * be < 32 and evenly divisible by 4 (0 is OK but not very precise).
  95850. *
  95851. * 'precision' roughly limits the number of iterations that are done;
  95852. * use (unsigned)(-1) for maximum precision.
  95853. *
  95854. * If 'x' is less than one -- that is, x < (1<<fracbits) -- then this
  95855. * function will punt and return 0.
  95856. *
  95857. * The return value will also have 'fracbits' fractional bits.
  95858. */
  95859. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision);
  95860. #endif
  95861. #endif
  95862. /*** End of inlined file: float.h ***/
  95863. /*** Start of inlined file: format.h ***/
  95864. #ifndef FLAC__PRIVATE__FORMAT_H
  95865. #define FLAC__PRIVATE__FORMAT_H
  95866. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order);
  95867. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize);
  95868. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order);
  95869. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  95870. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  95871. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order);
  95872. #endif
  95873. /*** End of inlined file: format.h ***/
  95874. /*
  95875. * FLAC__fixed_compute_best_predictor()
  95876. * --------------------------------------------------------------------
  95877. * Compute the best fixed predictor and the expected bits-per-sample
  95878. * of the residual signal for each order. The _wide() version uses
  95879. * 64-bit integers which is statistically necessary when bits-per-
  95880. * sample + log2(blocksize) > 30
  95881. *
  95882. * IN data[0,data_len-1]
  95883. * IN data_len
  95884. * OUT residual_bits_per_sample[0,FLAC__MAX_FIXED_ORDER]
  95885. */
  95886. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95887. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  95888. # ifndef FLAC__NO_ASM
  95889. # ifdef FLAC__CPU_IA32
  95890. # ifdef FLAC__HAS_NASM
  95891. 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]);
  95892. # endif
  95893. # endif
  95894. # endif
  95895. 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]);
  95896. #else
  95897. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  95898. 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]);
  95899. #endif
  95900. /*
  95901. * FLAC__fixed_compute_residual()
  95902. * --------------------------------------------------------------------
  95903. * Compute the residual signal obtained from sutracting the predicted
  95904. * signal from the original.
  95905. *
  95906. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  95907. * IN data_len length of original signal
  95908. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  95909. * OUT residual[0,data_len-1] residual signal
  95910. */
  95911. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[]);
  95912. /*
  95913. * FLAC__fixed_restore_signal()
  95914. * --------------------------------------------------------------------
  95915. * Restore the original signal by summing the residual and the
  95916. * predictor.
  95917. *
  95918. * IN residual[0,data_len-1] residual signal
  95919. * IN data_len length of original signal
  95920. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  95921. * *** IMPORTANT: the caller must pass in the historical samples:
  95922. * IN data[-order,-1] previously-reconstructed historical samples
  95923. * OUT data[0,data_len-1] original signal
  95924. */
  95925. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[]);
  95926. #endif
  95927. /*** End of inlined file: fixed.h ***/
  95928. #ifndef M_LN2
  95929. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  95930. #define M_LN2 0.69314718055994530942
  95931. #endif
  95932. #ifdef min
  95933. #undef min
  95934. #endif
  95935. #define min(x,y) ((x) < (y)? (x) : (y))
  95936. #ifdef local_abs
  95937. #undef local_abs
  95938. #endif
  95939. #define local_abs(x) ((unsigned)((x)<0? -(x) : (x)))
  95940. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  95941. /* rbps stands for residual bits per sample
  95942. *
  95943. * (ln(2) * err)
  95944. * rbps = log (-----------)
  95945. * 2 ( n )
  95946. */
  95947. static FLAC__fixedpoint local__compute_rbps_integerized(FLAC__uint32 err, FLAC__uint32 n)
  95948. {
  95949. FLAC__uint32 rbps;
  95950. unsigned bits; /* the number of bits required to represent a number */
  95951. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  95952. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  95953. FLAC__ASSERT(err > 0);
  95954. FLAC__ASSERT(n > 0);
  95955. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  95956. if(err <= n)
  95957. return 0;
  95958. /*
  95959. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  95960. * These allow us later to know we won't lose too much precision in the
  95961. * fixed-point division (err<<fracbits)/n.
  95962. */
  95963. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2(err)+1);
  95964. err <<= fracbits;
  95965. err /= n;
  95966. /* err now holds err/n with fracbits fractional bits */
  95967. /*
  95968. * Whittle err down to 16 bits max. 16 significant bits is enough for
  95969. * our purposes.
  95970. */
  95971. FLAC__ASSERT(err > 0);
  95972. bits = FLAC__bitmath_ilog2(err)+1;
  95973. if(bits > 16) {
  95974. err >>= (bits-16);
  95975. fracbits -= (bits-16);
  95976. }
  95977. rbps = (FLAC__uint32)err;
  95978. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  95979. rbps *= FLAC__FP_LN2;
  95980. fracbits += 16;
  95981. FLAC__ASSERT(fracbits >= 0);
  95982. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  95983. {
  95984. const int f = fracbits & 3;
  95985. if(f) {
  95986. rbps >>= f;
  95987. fracbits -= f;
  95988. }
  95989. }
  95990. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  95991. if(rbps == 0)
  95992. return 0;
  95993. /*
  95994. * The return value must have 16 fractional bits. Since the whole part
  95995. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  95996. * must be >= -3, these assertion allows us to be able to shift rbps
  95997. * left if necessary to get 16 fracbits without losing any bits of the
  95998. * whole part of rbps.
  95999. *
  96000. * There is a slight chance due to accumulated error that the whole part
  96001. * will require 6 bits, so we use 6 in the assertion. Really though as
  96002. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  96003. */
  96004. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  96005. FLAC__ASSERT(fracbits >= -3);
  96006. /* now shift the decimal point into place */
  96007. if(fracbits < 16)
  96008. return rbps << (16-fracbits);
  96009. else if(fracbits > 16)
  96010. return rbps >> (fracbits-16);
  96011. else
  96012. return rbps;
  96013. }
  96014. static FLAC__fixedpoint local__compute_rbps_wide_integerized(FLAC__uint64 err, FLAC__uint32 n)
  96015. {
  96016. FLAC__uint32 rbps;
  96017. unsigned bits; /* the number of bits required to represent a number */
  96018. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  96019. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  96020. FLAC__ASSERT(err > 0);
  96021. FLAC__ASSERT(n > 0);
  96022. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  96023. if(err <= n)
  96024. return 0;
  96025. /*
  96026. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  96027. * These allow us later to know we won't lose too much precision in the
  96028. * fixed-point division (err<<fracbits)/n.
  96029. */
  96030. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2_wide(err)+1);
  96031. err <<= fracbits;
  96032. err /= n;
  96033. /* err now holds err/n with fracbits fractional bits */
  96034. /*
  96035. * Whittle err down to 16 bits max. 16 significant bits is enough for
  96036. * our purposes.
  96037. */
  96038. FLAC__ASSERT(err > 0);
  96039. bits = FLAC__bitmath_ilog2_wide(err)+1;
  96040. if(bits > 16) {
  96041. err >>= (bits-16);
  96042. fracbits -= (bits-16);
  96043. }
  96044. rbps = (FLAC__uint32)err;
  96045. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  96046. rbps *= FLAC__FP_LN2;
  96047. fracbits += 16;
  96048. FLAC__ASSERT(fracbits >= 0);
  96049. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  96050. {
  96051. const int f = fracbits & 3;
  96052. if(f) {
  96053. rbps >>= f;
  96054. fracbits -= f;
  96055. }
  96056. }
  96057. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  96058. if(rbps == 0)
  96059. return 0;
  96060. /*
  96061. * The return value must have 16 fractional bits. Since the whole part
  96062. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  96063. * must be >= -3, these assertion allows us to be able to shift rbps
  96064. * left if necessary to get 16 fracbits without losing any bits of the
  96065. * whole part of rbps.
  96066. *
  96067. * There is a slight chance due to accumulated error that the whole part
  96068. * will require 6 bits, so we use 6 in the assertion. Really though as
  96069. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  96070. */
  96071. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  96072. FLAC__ASSERT(fracbits >= -3);
  96073. /* now shift the decimal point into place */
  96074. if(fracbits < 16)
  96075. return rbps << (16-fracbits);
  96076. else if(fracbits > 16)
  96077. return rbps >> (fracbits-16);
  96078. else
  96079. return rbps;
  96080. }
  96081. #endif
  96082. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96083. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  96084. #else
  96085. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  96086. #endif
  96087. {
  96088. FLAC__int32 last_error_0 = data[-1];
  96089. FLAC__int32 last_error_1 = data[-1] - data[-2];
  96090. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  96091. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  96092. FLAC__int32 error, save;
  96093. FLAC__uint32 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  96094. unsigned i, order;
  96095. for(i = 0; i < data_len; i++) {
  96096. error = data[i] ; total_error_0 += local_abs(error); save = error;
  96097. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  96098. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  96099. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  96100. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  96101. }
  96102. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  96103. order = 0;
  96104. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  96105. order = 1;
  96106. else if(total_error_2 < min(total_error_3, total_error_4))
  96107. order = 2;
  96108. else if(total_error_3 < total_error_4)
  96109. order = 3;
  96110. else
  96111. order = 4;
  96112. /* Estimate the expected number of bits per residual signal sample. */
  96113. /* 'total_error*' is linearly related to the variance of the residual */
  96114. /* signal, so we use it directly to compute E(|x|) */
  96115. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  96116. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  96117. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  96118. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  96119. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  96120. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96121. 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);
  96122. 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);
  96123. 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);
  96124. 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);
  96125. 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);
  96126. #else
  96127. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_integerized(total_error_0, data_len) : 0;
  96128. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_integerized(total_error_1, data_len) : 0;
  96129. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_integerized(total_error_2, data_len) : 0;
  96130. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_integerized(total_error_3, data_len) : 0;
  96131. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_integerized(total_error_4, data_len) : 0;
  96132. #endif
  96133. return order;
  96134. }
  96135. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96136. 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])
  96137. #else
  96138. 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])
  96139. #endif
  96140. {
  96141. FLAC__int32 last_error_0 = data[-1];
  96142. FLAC__int32 last_error_1 = data[-1] - data[-2];
  96143. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  96144. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  96145. FLAC__int32 error, save;
  96146. /* total_error_* are 64-bits to avoid overflow when encoding
  96147. * erratic signals when the bits-per-sample and blocksize are
  96148. * large.
  96149. */
  96150. FLAC__uint64 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  96151. unsigned i, order;
  96152. for(i = 0; i < data_len; i++) {
  96153. error = data[i] ; total_error_0 += local_abs(error); save = error;
  96154. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  96155. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  96156. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  96157. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  96158. }
  96159. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  96160. order = 0;
  96161. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  96162. order = 1;
  96163. else if(total_error_2 < min(total_error_3, total_error_4))
  96164. order = 2;
  96165. else if(total_error_3 < total_error_4)
  96166. order = 3;
  96167. else
  96168. order = 4;
  96169. /* Estimate the expected number of bits per residual signal sample. */
  96170. /* 'total_error*' is linearly related to the variance of the residual */
  96171. /* signal, so we use it directly to compute E(|x|) */
  96172. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  96173. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  96174. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  96175. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  96176. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  96177. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96178. #if defined _MSC_VER || defined __MINGW32__
  96179. /* with MSVC you have to spoon feed it the casting */
  96180. 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);
  96181. 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);
  96182. 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);
  96183. 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);
  96184. 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);
  96185. #else
  96186. 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);
  96187. 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);
  96188. 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);
  96189. 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);
  96190. 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);
  96191. #endif
  96192. #else
  96193. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_wide_integerized(total_error_0, data_len) : 0;
  96194. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_wide_integerized(total_error_1, data_len) : 0;
  96195. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_wide_integerized(total_error_2, data_len) : 0;
  96196. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_wide_integerized(total_error_3, data_len) : 0;
  96197. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_wide_integerized(total_error_4, data_len) : 0;
  96198. #endif
  96199. return order;
  96200. }
  96201. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[])
  96202. {
  96203. const int idata_len = (int)data_len;
  96204. int i;
  96205. switch(order) {
  96206. case 0:
  96207. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  96208. memcpy(residual, data, sizeof(residual[0])*data_len);
  96209. break;
  96210. case 1:
  96211. for(i = 0; i < idata_len; i++)
  96212. residual[i] = data[i] - data[i-1];
  96213. break;
  96214. case 2:
  96215. for(i = 0; i < idata_len; i++)
  96216. #if 1 /* OPT: may be faster with some compilers on some systems */
  96217. residual[i] = data[i] - (data[i-1] << 1) + data[i-2];
  96218. #else
  96219. residual[i] = data[i] - 2*data[i-1] + data[i-2];
  96220. #endif
  96221. break;
  96222. case 3:
  96223. for(i = 0; i < idata_len; i++)
  96224. #if 1 /* OPT: may be faster with some compilers on some systems */
  96225. residual[i] = data[i] - (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) - data[i-3];
  96226. #else
  96227. residual[i] = data[i] - 3*data[i-1] + 3*data[i-2] - data[i-3];
  96228. #endif
  96229. break;
  96230. case 4:
  96231. for(i = 0; i < idata_len; i++)
  96232. #if 1 /* OPT: may be faster with some compilers on some systems */
  96233. residual[i] = data[i] - ((data[i-1]+data[i-3])<<2) + ((data[i-2]<<2) + (data[i-2]<<1)) + data[i-4];
  96234. #else
  96235. residual[i] = data[i] - 4*data[i-1] + 6*data[i-2] - 4*data[i-3] + data[i-4];
  96236. #endif
  96237. break;
  96238. default:
  96239. FLAC__ASSERT(0);
  96240. }
  96241. }
  96242. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[])
  96243. {
  96244. int i, idata_len = (int)data_len;
  96245. switch(order) {
  96246. case 0:
  96247. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  96248. memcpy(data, residual, sizeof(residual[0])*data_len);
  96249. break;
  96250. case 1:
  96251. for(i = 0; i < idata_len; i++)
  96252. data[i] = residual[i] + data[i-1];
  96253. break;
  96254. case 2:
  96255. for(i = 0; i < idata_len; i++)
  96256. #if 1 /* OPT: may be faster with some compilers on some systems */
  96257. data[i] = residual[i] + (data[i-1]<<1) - data[i-2];
  96258. #else
  96259. data[i] = residual[i] + 2*data[i-1] - data[i-2];
  96260. #endif
  96261. break;
  96262. case 3:
  96263. for(i = 0; i < idata_len; i++)
  96264. #if 1 /* OPT: may be faster with some compilers on some systems */
  96265. data[i] = residual[i] + (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) + data[i-3];
  96266. #else
  96267. data[i] = residual[i] + 3*data[i-1] - 3*data[i-2] + data[i-3];
  96268. #endif
  96269. break;
  96270. case 4:
  96271. for(i = 0; i < idata_len; i++)
  96272. #if 1 /* OPT: may be faster with some compilers on some systems */
  96273. data[i] = residual[i] + ((data[i-1]+data[i-3])<<2) - ((data[i-2]<<2) + (data[i-2]<<1)) - data[i-4];
  96274. #else
  96275. data[i] = residual[i] + 4*data[i-1] - 6*data[i-2] + 4*data[i-3] - data[i-4];
  96276. #endif
  96277. break;
  96278. default:
  96279. FLAC__ASSERT(0);
  96280. }
  96281. }
  96282. #endif
  96283. /*** End of inlined file: fixed.c ***/
  96284. /*** Start of inlined file: float.c ***/
  96285. /*** Start of inlined file: juce_FlacHeader.h ***/
  96286. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  96287. // tasks..
  96288. #define VERSION "1.2.1"
  96289. #define FLAC__NO_DLL 1
  96290. #if JUCE_MSVC
  96291. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  96292. #endif
  96293. #if JUCE_MAC
  96294. #define FLAC__SYS_DARWIN 1
  96295. #endif
  96296. /*** End of inlined file: juce_FlacHeader.h ***/
  96297. #if JUCE_USE_FLAC
  96298. #if HAVE_CONFIG_H
  96299. # include <config.h>
  96300. #endif
  96301. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  96302. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  96303. #ifdef _MSC_VER
  96304. #define FLAC__U64L(x) x
  96305. #else
  96306. #define FLAC__U64L(x) x##LLU
  96307. #endif
  96308. const FLAC__fixedpoint FLAC__FP_ZERO = 0;
  96309. const FLAC__fixedpoint FLAC__FP_ONE_HALF = 0x00008000;
  96310. const FLAC__fixedpoint FLAC__FP_ONE = 0x00010000;
  96311. const FLAC__fixedpoint FLAC__FP_LN2 = 45426;
  96312. const FLAC__fixedpoint FLAC__FP_E = 178145;
  96313. /* Lookup tables for Knuth's logarithm algorithm */
  96314. #define LOG2_LOOKUP_PRECISION 16
  96315. static const FLAC__uint32 log2_lookup[][LOG2_LOOKUP_PRECISION] = {
  96316. {
  96317. /*
  96318. * 0 fraction bits
  96319. */
  96320. /* undefined */ 0x00000000,
  96321. /* lg(2/1) = */ 0x00000001,
  96322. /* lg(4/3) = */ 0x00000000,
  96323. /* lg(8/7) = */ 0x00000000,
  96324. /* lg(16/15) = */ 0x00000000,
  96325. /* lg(32/31) = */ 0x00000000,
  96326. /* lg(64/63) = */ 0x00000000,
  96327. /* lg(128/127) = */ 0x00000000,
  96328. /* lg(256/255) = */ 0x00000000,
  96329. /* lg(512/511) = */ 0x00000000,
  96330. /* lg(1024/1023) = */ 0x00000000,
  96331. /* lg(2048/2047) = */ 0x00000000,
  96332. /* lg(4096/4095) = */ 0x00000000,
  96333. /* lg(8192/8191) = */ 0x00000000,
  96334. /* lg(16384/16383) = */ 0x00000000,
  96335. /* lg(32768/32767) = */ 0x00000000
  96336. },
  96337. {
  96338. /*
  96339. * 4 fraction bits
  96340. */
  96341. /* undefined */ 0x00000000,
  96342. /* lg(2/1) = */ 0x00000010,
  96343. /* lg(4/3) = */ 0x00000007,
  96344. /* lg(8/7) = */ 0x00000003,
  96345. /* lg(16/15) = */ 0x00000001,
  96346. /* lg(32/31) = */ 0x00000001,
  96347. /* lg(64/63) = */ 0x00000000,
  96348. /* lg(128/127) = */ 0x00000000,
  96349. /* lg(256/255) = */ 0x00000000,
  96350. /* lg(512/511) = */ 0x00000000,
  96351. /* lg(1024/1023) = */ 0x00000000,
  96352. /* lg(2048/2047) = */ 0x00000000,
  96353. /* lg(4096/4095) = */ 0x00000000,
  96354. /* lg(8192/8191) = */ 0x00000000,
  96355. /* lg(16384/16383) = */ 0x00000000,
  96356. /* lg(32768/32767) = */ 0x00000000
  96357. },
  96358. {
  96359. /*
  96360. * 8 fraction bits
  96361. */
  96362. /* undefined */ 0x00000000,
  96363. /* lg(2/1) = */ 0x00000100,
  96364. /* lg(4/3) = */ 0x0000006a,
  96365. /* lg(8/7) = */ 0x00000031,
  96366. /* lg(16/15) = */ 0x00000018,
  96367. /* lg(32/31) = */ 0x0000000c,
  96368. /* lg(64/63) = */ 0x00000006,
  96369. /* lg(128/127) = */ 0x00000003,
  96370. /* lg(256/255) = */ 0x00000001,
  96371. /* lg(512/511) = */ 0x00000001,
  96372. /* lg(1024/1023) = */ 0x00000000,
  96373. /* lg(2048/2047) = */ 0x00000000,
  96374. /* lg(4096/4095) = */ 0x00000000,
  96375. /* lg(8192/8191) = */ 0x00000000,
  96376. /* lg(16384/16383) = */ 0x00000000,
  96377. /* lg(32768/32767) = */ 0x00000000
  96378. },
  96379. {
  96380. /*
  96381. * 12 fraction bits
  96382. */
  96383. /* undefined */ 0x00000000,
  96384. /* lg(2/1) = */ 0x00001000,
  96385. /* lg(4/3) = */ 0x000006a4,
  96386. /* lg(8/7) = */ 0x00000315,
  96387. /* lg(16/15) = */ 0x0000017d,
  96388. /* lg(32/31) = */ 0x000000bc,
  96389. /* lg(64/63) = */ 0x0000005d,
  96390. /* lg(128/127) = */ 0x0000002e,
  96391. /* lg(256/255) = */ 0x00000017,
  96392. /* lg(512/511) = */ 0x0000000c,
  96393. /* lg(1024/1023) = */ 0x00000006,
  96394. /* lg(2048/2047) = */ 0x00000003,
  96395. /* lg(4096/4095) = */ 0x00000001,
  96396. /* lg(8192/8191) = */ 0x00000001,
  96397. /* lg(16384/16383) = */ 0x00000000,
  96398. /* lg(32768/32767) = */ 0x00000000
  96399. },
  96400. {
  96401. /*
  96402. * 16 fraction bits
  96403. */
  96404. /* undefined */ 0x00000000,
  96405. /* lg(2/1) = */ 0x00010000,
  96406. /* lg(4/3) = */ 0x00006a40,
  96407. /* lg(8/7) = */ 0x00003151,
  96408. /* lg(16/15) = */ 0x000017d6,
  96409. /* lg(32/31) = */ 0x00000bba,
  96410. /* lg(64/63) = */ 0x000005d1,
  96411. /* lg(128/127) = */ 0x000002e6,
  96412. /* lg(256/255) = */ 0x00000172,
  96413. /* lg(512/511) = */ 0x000000b9,
  96414. /* lg(1024/1023) = */ 0x0000005c,
  96415. /* lg(2048/2047) = */ 0x0000002e,
  96416. /* lg(4096/4095) = */ 0x00000017,
  96417. /* lg(8192/8191) = */ 0x0000000c,
  96418. /* lg(16384/16383) = */ 0x00000006,
  96419. /* lg(32768/32767) = */ 0x00000003
  96420. },
  96421. {
  96422. /*
  96423. * 20 fraction bits
  96424. */
  96425. /* undefined */ 0x00000000,
  96426. /* lg(2/1) = */ 0x00100000,
  96427. /* lg(4/3) = */ 0x0006a3fe,
  96428. /* lg(8/7) = */ 0x00031513,
  96429. /* lg(16/15) = */ 0x00017d60,
  96430. /* lg(32/31) = */ 0x0000bb9d,
  96431. /* lg(64/63) = */ 0x00005d10,
  96432. /* lg(128/127) = */ 0x00002e59,
  96433. /* lg(256/255) = */ 0x00001721,
  96434. /* lg(512/511) = */ 0x00000b8e,
  96435. /* lg(1024/1023) = */ 0x000005c6,
  96436. /* lg(2048/2047) = */ 0x000002e3,
  96437. /* lg(4096/4095) = */ 0x00000171,
  96438. /* lg(8192/8191) = */ 0x000000b9,
  96439. /* lg(16384/16383) = */ 0x0000005c,
  96440. /* lg(32768/32767) = */ 0x0000002e
  96441. },
  96442. {
  96443. /*
  96444. * 24 fraction bits
  96445. */
  96446. /* undefined */ 0x00000000,
  96447. /* lg(2/1) = */ 0x01000000,
  96448. /* lg(4/3) = */ 0x006a3fe6,
  96449. /* lg(8/7) = */ 0x00315130,
  96450. /* lg(16/15) = */ 0x0017d605,
  96451. /* lg(32/31) = */ 0x000bb9ca,
  96452. /* lg(64/63) = */ 0x0005d0fc,
  96453. /* lg(128/127) = */ 0x0002e58f,
  96454. /* lg(256/255) = */ 0x0001720e,
  96455. /* lg(512/511) = */ 0x0000b8d8,
  96456. /* lg(1024/1023) = */ 0x00005c61,
  96457. /* lg(2048/2047) = */ 0x00002e2d,
  96458. /* lg(4096/4095) = */ 0x00001716,
  96459. /* lg(8192/8191) = */ 0x00000b8b,
  96460. /* lg(16384/16383) = */ 0x000005c5,
  96461. /* lg(32768/32767) = */ 0x000002e3
  96462. },
  96463. {
  96464. /*
  96465. * 28 fraction bits
  96466. */
  96467. /* undefined */ 0x00000000,
  96468. /* lg(2/1) = */ 0x10000000,
  96469. /* lg(4/3) = */ 0x06a3fe5c,
  96470. /* lg(8/7) = */ 0x03151301,
  96471. /* lg(16/15) = */ 0x017d6049,
  96472. /* lg(32/31) = */ 0x00bb9ca6,
  96473. /* lg(64/63) = */ 0x005d0fba,
  96474. /* lg(128/127) = */ 0x002e58f7,
  96475. /* lg(256/255) = */ 0x001720da,
  96476. /* lg(512/511) = */ 0x000b8d87,
  96477. /* lg(1024/1023) = */ 0x0005c60b,
  96478. /* lg(2048/2047) = */ 0x0002e2d7,
  96479. /* lg(4096/4095) = */ 0x00017160,
  96480. /* lg(8192/8191) = */ 0x0000b8ad,
  96481. /* lg(16384/16383) = */ 0x00005c56,
  96482. /* lg(32768/32767) = */ 0x00002e2b
  96483. }
  96484. };
  96485. #if 0
  96486. static const FLAC__uint64 log2_lookup_wide[] = {
  96487. {
  96488. /*
  96489. * 32 fraction bits
  96490. */
  96491. /* undefined */ 0x00000000,
  96492. /* lg(2/1) = */ FLAC__U64L(0x100000000),
  96493. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c6),
  96494. /* lg(8/7) = */ FLAC__U64L(0x31513015),
  96495. /* lg(16/15) = */ FLAC__U64L(0x17d60497),
  96496. /* lg(32/31) = */ FLAC__U64L(0x0bb9ca65),
  96497. /* lg(64/63) = */ FLAC__U64L(0x05d0fba2),
  96498. /* lg(128/127) = */ FLAC__U64L(0x02e58f74),
  96499. /* lg(256/255) = */ FLAC__U64L(0x01720d9c),
  96500. /* lg(512/511) = */ FLAC__U64L(0x00b8d875),
  96501. /* lg(1024/1023) = */ FLAC__U64L(0x005c60aa),
  96502. /* lg(2048/2047) = */ FLAC__U64L(0x002e2d72),
  96503. /* lg(4096/4095) = */ FLAC__U64L(0x00171600),
  96504. /* lg(8192/8191) = */ FLAC__U64L(0x000b8ad2),
  96505. /* lg(16384/16383) = */ FLAC__U64L(0x0005c55d),
  96506. /* lg(32768/32767) = */ FLAC__U64L(0x0002e2ac)
  96507. },
  96508. {
  96509. /*
  96510. * 48 fraction bits
  96511. */
  96512. /* undefined */ 0x00000000,
  96513. /* lg(2/1) = */ FLAC__U64L(0x1000000000000),
  96514. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c60429),
  96515. /* lg(8/7) = */ FLAC__U64L(0x315130157f7a),
  96516. /* lg(16/15) = */ FLAC__U64L(0x17d60496cfbb),
  96517. /* lg(32/31) = */ FLAC__U64L(0xbb9ca64ecac),
  96518. /* lg(64/63) = */ FLAC__U64L(0x5d0fba187cd),
  96519. /* lg(128/127) = */ FLAC__U64L(0x2e58f7441ee),
  96520. /* lg(256/255) = */ FLAC__U64L(0x1720d9c06a8),
  96521. /* lg(512/511) = */ FLAC__U64L(0xb8d8752173),
  96522. /* lg(1024/1023) = */ FLAC__U64L(0x5c60aa252e),
  96523. /* lg(2048/2047) = */ FLAC__U64L(0x2e2d71b0d8),
  96524. /* lg(4096/4095) = */ FLAC__U64L(0x1716001719),
  96525. /* lg(8192/8191) = */ FLAC__U64L(0xb8ad1de1b),
  96526. /* lg(16384/16383) = */ FLAC__U64L(0x5c55d640d),
  96527. /* lg(32768/32767) = */ FLAC__U64L(0x2e2abcf52)
  96528. }
  96529. };
  96530. #endif
  96531. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision)
  96532. {
  96533. const FLAC__uint32 ONE = (1u << fracbits);
  96534. const FLAC__uint32 *table = log2_lookup[fracbits >> 2];
  96535. FLAC__ASSERT(fracbits < 32);
  96536. FLAC__ASSERT((fracbits & 0x3) == 0);
  96537. if(x < ONE)
  96538. return 0;
  96539. if(precision > LOG2_LOOKUP_PRECISION)
  96540. precision = LOG2_LOOKUP_PRECISION;
  96541. /* Knuth's algorithm for computing logarithms, optimized for base-2 with lookup tables */
  96542. {
  96543. FLAC__uint32 y = 0;
  96544. FLAC__uint32 z = x >> 1, k = 1;
  96545. while (x > ONE && k < precision) {
  96546. if (x - z >= ONE) {
  96547. x -= z;
  96548. z = x >> k;
  96549. y += table[k];
  96550. }
  96551. else {
  96552. z >>= 1;
  96553. k++;
  96554. }
  96555. }
  96556. return y;
  96557. }
  96558. }
  96559. #endif /* defined FLAC__INTEGER_ONLY_LIBRARY */
  96560. #endif
  96561. /*** End of inlined file: float.c ***/
  96562. /*** Start of inlined file: format.c ***/
  96563. /*** Start of inlined file: juce_FlacHeader.h ***/
  96564. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  96565. // tasks..
  96566. #define VERSION "1.2.1"
  96567. #define FLAC__NO_DLL 1
  96568. #if JUCE_MSVC
  96569. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  96570. #endif
  96571. #if JUCE_MAC
  96572. #define FLAC__SYS_DARWIN 1
  96573. #endif
  96574. /*** End of inlined file: juce_FlacHeader.h ***/
  96575. #if JUCE_USE_FLAC
  96576. #if HAVE_CONFIG_H
  96577. # include <config.h>
  96578. #endif
  96579. #include <stdio.h>
  96580. #include <stdlib.h> /* for qsort() */
  96581. #include <string.h> /* for memset() */
  96582. #ifndef FLaC__INLINE
  96583. #define FLaC__INLINE
  96584. #endif
  96585. #ifdef min
  96586. #undef min
  96587. #endif
  96588. #define min(a,b) ((a)<(b)?(a):(b))
  96589. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  96590. #ifdef _MSC_VER
  96591. #define FLAC__U64L(x) x
  96592. #else
  96593. #define FLAC__U64L(x) x##LLU
  96594. #endif
  96595. /* VERSION should come from configure */
  96596. FLAC_API const char *FLAC__VERSION_STRING = VERSION
  96597. ;
  96598. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINW32__
  96599. /* yet one more hack because of MSVC6: */
  96600. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC 1.2.1 20070917";
  96601. #else
  96602. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC " VERSION " 20070917";
  96603. #endif
  96604. FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4] = { 'f','L','a','C' };
  96605. FLAC_API const unsigned FLAC__STREAM_SYNC = 0x664C6143;
  96606. FLAC_API const unsigned FLAC__STREAM_SYNC_LEN = 32; /* bits */
  96607. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN = 16; /* bits */
  96608. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN = 16; /* bits */
  96609. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN = 24; /* bits */
  96610. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN = 24; /* bits */
  96611. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN = 20; /* bits */
  96612. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN = 3; /* bits */
  96613. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN = 5; /* bits */
  96614. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN = 36; /* bits */
  96615. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN = 128; /* bits */
  96616. FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN = 32; /* bits */
  96617. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN = 64; /* bits */
  96618. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN = 64; /* bits */
  96619. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN = 16; /* bits */
  96620. FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER = FLAC__U64L(0xffffffffffffffff);
  96621. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN = 32; /* bits */
  96622. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN = 32; /* bits */
  96623. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN = 64; /* bits */
  96624. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN = 8; /* bits */
  96625. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN = 3*8; /* bits */
  96626. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN = 64; /* bits */
  96627. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN = 8; /* bits */
  96628. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN = 12*8; /* bits */
  96629. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN = 1; /* bit */
  96630. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN = 1; /* bit */
  96631. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN = 6+13*8; /* bits */
  96632. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN = 8; /* bits */
  96633. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN = 128*8; /* bits */
  96634. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN = 64; /* bits */
  96635. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN = 1; /* bit */
  96636. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN = 7+258*8; /* bits */
  96637. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN = 8; /* bits */
  96638. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN = 32; /* bits */
  96639. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN = 32; /* bits */
  96640. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN = 32; /* bits */
  96641. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN = 32; /* bits */
  96642. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN = 32; /* bits */
  96643. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN = 32; /* bits */
  96644. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN = 32; /* bits */
  96645. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN = 32; /* bits */
  96646. FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN = 1; /* bits */
  96647. FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN = 7; /* bits */
  96648. FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN = 24; /* bits */
  96649. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC = 0x3ffe;
  96650. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN = 14; /* bits */
  96651. FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN = 1; /* bits */
  96652. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN = 1; /* bits */
  96653. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN = 4; /* bits */
  96654. FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN = 4; /* bits */
  96655. FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN = 4; /* bits */
  96656. FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN = 3; /* bits */
  96657. FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN = 1; /* bits */
  96658. FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN = 8; /* bits */
  96659. FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN = 16; /* bits */
  96660. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN = 2; /* bits */
  96661. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN = 4; /* bits */
  96662. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN = 4; /* bits */
  96663. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN = 5; /* bits */
  96664. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN = 5; /* bits */
  96665. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER = 15; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  96666. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER = 31; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  96667. FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[] = {
  96668. "PARTITIONED_RICE",
  96669. "PARTITIONED_RICE2"
  96670. };
  96671. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN = 4; /* bits */
  96672. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN = 5; /* bits */
  96673. FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN = 1; /* bits */
  96674. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN = 6; /* bits */
  96675. FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN = 1; /* bits */
  96676. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK = 0x00;
  96677. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK = 0x02;
  96678. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK = 0x10;
  96679. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK = 0x40;
  96680. FLAC_API const char * const FLAC__SubframeTypeString[] = {
  96681. "CONSTANT",
  96682. "VERBATIM",
  96683. "FIXED",
  96684. "LPC"
  96685. };
  96686. FLAC_API const char * const FLAC__ChannelAssignmentString[] = {
  96687. "INDEPENDENT",
  96688. "LEFT_SIDE",
  96689. "RIGHT_SIDE",
  96690. "MID_SIDE"
  96691. };
  96692. FLAC_API const char * const FLAC__FrameNumberTypeString[] = {
  96693. "FRAME_NUMBER_TYPE_FRAME_NUMBER",
  96694. "FRAME_NUMBER_TYPE_SAMPLE_NUMBER"
  96695. };
  96696. FLAC_API const char * const FLAC__MetadataTypeString[] = {
  96697. "STREAMINFO",
  96698. "PADDING",
  96699. "APPLICATION",
  96700. "SEEKTABLE",
  96701. "VORBIS_COMMENT",
  96702. "CUESHEET",
  96703. "PICTURE"
  96704. };
  96705. FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[] = {
  96706. "Other",
  96707. "32x32 pixels 'file icon' (PNG only)",
  96708. "Other file icon",
  96709. "Cover (front)",
  96710. "Cover (back)",
  96711. "Leaflet page",
  96712. "Media (e.g. label side of CD)",
  96713. "Lead artist/lead performer/soloist",
  96714. "Artist/performer",
  96715. "Conductor",
  96716. "Band/Orchestra",
  96717. "Composer",
  96718. "Lyricist/text writer",
  96719. "Recording Location",
  96720. "During recording",
  96721. "During performance",
  96722. "Movie/video screen capture",
  96723. "A bright coloured fish",
  96724. "Illustration",
  96725. "Band/artist logotype",
  96726. "Publisher/Studio logotype"
  96727. };
  96728. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate)
  96729. {
  96730. if(sample_rate == 0 || sample_rate > FLAC__MAX_SAMPLE_RATE) {
  96731. return false;
  96732. }
  96733. else
  96734. return true;
  96735. }
  96736. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate)
  96737. {
  96738. if(
  96739. !FLAC__format_sample_rate_is_valid(sample_rate) ||
  96740. (
  96741. sample_rate >= (1u << 16) &&
  96742. !(sample_rate % 1000 == 0 || sample_rate % 10 == 0)
  96743. )
  96744. ) {
  96745. return false;
  96746. }
  96747. else
  96748. return true;
  96749. }
  96750. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96751. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table)
  96752. {
  96753. unsigned i;
  96754. FLAC__uint64 prev_sample_number = 0;
  96755. FLAC__bool got_prev = false;
  96756. FLAC__ASSERT(0 != seek_table);
  96757. for(i = 0; i < seek_table->num_points; i++) {
  96758. if(got_prev) {
  96759. if(
  96760. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  96761. seek_table->points[i].sample_number <= prev_sample_number
  96762. )
  96763. return false;
  96764. }
  96765. prev_sample_number = seek_table->points[i].sample_number;
  96766. got_prev = true;
  96767. }
  96768. return true;
  96769. }
  96770. /* used as the sort predicate for qsort() */
  96771. static int JUCE_CDECL seekpoint_compare_(const FLAC__StreamMetadata_SeekPoint *l, const FLAC__StreamMetadata_SeekPoint *r)
  96772. {
  96773. /* we don't just 'return l->sample_number - r->sample_number' since the result (FLAC__int64) might overflow an 'int' */
  96774. if(l->sample_number == r->sample_number)
  96775. return 0;
  96776. else if(l->sample_number < r->sample_number)
  96777. return -1;
  96778. else
  96779. return 1;
  96780. }
  96781. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96782. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table)
  96783. {
  96784. unsigned i, j;
  96785. FLAC__bool first;
  96786. FLAC__ASSERT(0 != seek_table);
  96787. /* sort the seekpoints */
  96788. qsort(seek_table->points, seek_table->num_points, sizeof(FLAC__StreamMetadata_SeekPoint), (int (JUCE_CDECL *)(const void *, const void *))seekpoint_compare_);
  96789. /* uniquify the seekpoints */
  96790. first = true;
  96791. for(i = j = 0; i < seek_table->num_points; i++) {
  96792. if(seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER) {
  96793. if(!first) {
  96794. if(seek_table->points[i].sample_number == seek_table->points[j-1].sample_number)
  96795. continue;
  96796. }
  96797. }
  96798. first = false;
  96799. seek_table->points[j++] = seek_table->points[i];
  96800. }
  96801. for(i = j; i < seek_table->num_points; i++) {
  96802. seek_table->points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  96803. seek_table->points[i].stream_offset = 0;
  96804. seek_table->points[i].frame_samples = 0;
  96805. }
  96806. return j;
  96807. }
  96808. /*
  96809. * also disallows non-shortest-form encodings, c.f.
  96810. * http://www.unicode.org/versions/corrigendum1.html
  96811. * and a more clear explanation at the end of this section:
  96812. * http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  96813. */
  96814. static FLaC__INLINE unsigned utf8len_(const FLAC__byte *utf8)
  96815. {
  96816. FLAC__ASSERT(0 != utf8);
  96817. if ((utf8[0] & 0x80) == 0) {
  96818. return 1;
  96819. }
  96820. else if ((utf8[0] & 0xE0) == 0xC0 && (utf8[1] & 0xC0) == 0x80) {
  96821. if ((utf8[0] & 0xFE) == 0xC0) /* overlong sequence check */
  96822. return 0;
  96823. return 2;
  96824. }
  96825. else if ((utf8[0] & 0xF0) == 0xE0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80) {
  96826. if (utf8[0] == 0xE0 && (utf8[1] & 0xE0) == 0x80) /* overlong sequence check */
  96827. return 0;
  96828. /* illegal surrogates check (U+D800...U+DFFF and U+FFFE...U+FFFF) */
  96829. if (utf8[0] == 0xED && (utf8[1] & 0xE0) == 0xA0) /* D800-DFFF */
  96830. return 0;
  96831. if (utf8[0] == 0xEF && utf8[1] == 0xBF && (utf8[2] & 0xFE) == 0xBE) /* FFFE-FFFF */
  96832. return 0;
  96833. return 3;
  96834. }
  96835. else if ((utf8[0] & 0xF8) == 0xF0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80) {
  96836. if (utf8[0] == 0xF0 && (utf8[1] & 0xF0) == 0x80) /* overlong sequence check */
  96837. return 0;
  96838. return 4;
  96839. }
  96840. else if ((utf8[0] & 0xFC) == 0xF8 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80 && (utf8[4] & 0xC0) == 0x80) {
  96841. if (utf8[0] == 0xF8 && (utf8[1] & 0xF8) == 0x80) /* overlong sequence check */
  96842. return 0;
  96843. return 5;
  96844. }
  96845. 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) {
  96846. if (utf8[0] == 0xFC && (utf8[1] & 0xFC) == 0x80) /* overlong sequence check */
  96847. return 0;
  96848. return 6;
  96849. }
  96850. else {
  96851. return 0;
  96852. }
  96853. }
  96854. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name)
  96855. {
  96856. char c;
  96857. for(c = *name; c; c = *(++name))
  96858. if(c < 0x20 || c == 0x3d || c > 0x7d)
  96859. return false;
  96860. return true;
  96861. }
  96862. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length)
  96863. {
  96864. if(length == (unsigned)(-1)) {
  96865. while(*value) {
  96866. unsigned n = utf8len_(value);
  96867. if(n == 0)
  96868. return false;
  96869. value += n;
  96870. }
  96871. }
  96872. else {
  96873. const FLAC__byte *end = value + length;
  96874. while(value < end) {
  96875. unsigned n = utf8len_(value);
  96876. if(n == 0)
  96877. return false;
  96878. value += n;
  96879. }
  96880. if(value != end)
  96881. return false;
  96882. }
  96883. return true;
  96884. }
  96885. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length)
  96886. {
  96887. const FLAC__byte *s, *end;
  96888. for(s = entry, end = s + length; s < end && *s != '='; s++) {
  96889. if(*s < 0x20 || *s > 0x7D)
  96890. return false;
  96891. }
  96892. if(s == end)
  96893. return false;
  96894. s++; /* skip '=' */
  96895. while(s < end) {
  96896. unsigned n = utf8len_(s);
  96897. if(n == 0)
  96898. return false;
  96899. s += n;
  96900. }
  96901. if(s != end)
  96902. return false;
  96903. return true;
  96904. }
  96905. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96906. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation)
  96907. {
  96908. unsigned i, j;
  96909. if(check_cd_da_subset) {
  96910. if(cue_sheet->lead_in < 2 * 44100) {
  96911. if(violation) *violation = "CD-DA cue sheet must have a lead-in length of at least 2 seconds";
  96912. return false;
  96913. }
  96914. if(cue_sheet->lead_in % 588 != 0) {
  96915. if(violation) *violation = "CD-DA cue sheet lead-in length must be evenly divisible by 588 samples";
  96916. return false;
  96917. }
  96918. }
  96919. if(cue_sheet->num_tracks == 0) {
  96920. if(violation) *violation = "cue sheet must have at least one track (the lead-out)";
  96921. return false;
  96922. }
  96923. if(check_cd_da_subset && cue_sheet->tracks[cue_sheet->num_tracks-1].number != 170) {
  96924. if(violation) *violation = "CD-DA cue sheet must have a lead-out track number 170 (0xAA)";
  96925. return false;
  96926. }
  96927. for(i = 0; i < cue_sheet->num_tracks; i++) {
  96928. if(cue_sheet->tracks[i].number == 0) {
  96929. if(violation) *violation = "cue sheet may not have a track number 0";
  96930. return false;
  96931. }
  96932. if(check_cd_da_subset) {
  96933. if(!((cue_sheet->tracks[i].number >= 1 && cue_sheet->tracks[i].number <= 99) || cue_sheet->tracks[i].number == 170)) {
  96934. if(violation) *violation = "CD-DA cue sheet track number must be 1-99 or 170";
  96935. return false;
  96936. }
  96937. }
  96938. if(check_cd_da_subset && cue_sheet->tracks[i].offset % 588 != 0) {
  96939. if(violation) {
  96940. if(i == cue_sheet->num_tracks-1) /* the lead-out track... */
  96941. *violation = "CD-DA cue sheet lead-out offset must be evenly divisible by 588 samples";
  96942. else
  96943. *violation = "CD-DA cue sheet track offset must be evenly divisible by 588 samples";
  96944. }
  96945. return false;
  96946. }
  96947. if(i < cue_sheet->num_tracks - 1) {
  96948. if(cue_sheet->tracks[i].num_indices == 0) {
  96949. if(violation) *violation = "cue sheet track must have at least one index point";
  96950. return false;
  96951. }
  96952. if(cue_sheet->tracks[i].indices[0].number > 1) {
  96953. if(violation) *violation = "cue sheet track's first index number must be 0 or 1";
  96954. return false;
  96955. }
  96956. }
  96957. for(j = 0; j < cue_sheet->tracks[i].num_indices; j++) {
  96958. if(check_cd_da_subset && cue_sheet->tracks[i].indices[j].offset % 588 != 0) {
  96959. if(violation) *violation = "CD-DA cue sheet track index offset must be evenly divisible by 588 samples";
  96960. return false;
  96961. }
  96962. if(j > 0) {
  96963. if(cue_sheet->tracks[i].indices[j].number != cue_sheet->tracks[i].indices[j-1].number + 1) {
  96964. if(violation) *violation = "cue sheet track index numbers must increase by 1";
  96965. return false;
  96966. }
  96967. }
  96968. }
  96969. }
  96970. return true;
  96971. }
  96972. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96973. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation)
  96974. {
  96975. char *p;
  96976. FLAC__byte *b;
  96977. for(p = picture->mime_type; *p; p++) {
  96978. if(*p < 0x20 || *p > 0x7e) {
  96979. if(violation) *violation = "MIME type string must contain only printable ASCII characters (0x20-0x7e)";
  96980. return false;
  96981. }
  96982. }
  96983. for(b = picture->description; *b; ) {
  96984. unsigned n = utf8len_(b);
  96985. if(n == 0) {
  96986. if(violation) *violation = "description string must be valid UTF-8";
  96987. return false;
  96988. }
  96989. b += n;
  96990. }
  96991. return true;
  96992. }
  96993. /*
  96994. * These routines are private to libFLAC
  96995. */
  96996. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order)
  96997. {
  96998. return
  96999. FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(
  97000. FLAC__format_get_max_rice_partition_order_from_blocksize(blocksize),
  97001. blocksize,
  97002. predictor_order
  97003. );
  97004. }
  97005. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize)
  97006. {
  97007. unsigned max_rice_partition_order = 0;
  97008. while(!(blocksize & 1)) {
  97009. max_rice_partition_order++;
  97010. blocksize >>= 1;
  97011. }
  97012. return min(FLAC__MAX_RICE_PARTITION_ORDER, max_rice_partition_order);
  97013. }
  97014. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order)
  97015. {
  97016. unsigned max_rice_partition_order = limit;
  97017. while(max_rice_partition_order > 0 && (blocksize >> max_rice_partition_order) <= predictor_order)
  97018. max_rice_partition_order--;
  97019. FLAC__ASSERT(
  97020. (max_rice_partition_order == 0 && blocksize >= predictor_order) ||
  97021. (max_rice_partition_order > 0 && blocksize >> max_rice_partition_order > predictor_order)
  97022. );
  97023. return max_rice_partition_order;
  97024. }
  97025. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  97026. {
  97027. FLAC__ASSERT(0 != object);
  97028. object->parameters = 0;
  97029. object->raw_bits = 0;
  97030. object->capacity_by_order = 0;
  97031. }
  97032. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  97033. {
  97034. FLAC__ASSERT(0 != object);
  97035. if(0 != object->parameters)
  97036. free(object->parameters);
  97037. if(0 != object->raw_bits)
  97038. free(object->raw_bits);
  97039. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(object);
  97040. }
  97041. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order)
  97042. {
  97043. FLAC__ASSERT(0 != object);
  97044. FLAC__ASSERT(object->capacity_by_order > 0 || (0 == object->parameters && 0 == object->raw_bits));
  97045. if(object->capacity_by_order < max_partition_order) {
  97046. if(0 == (object->parameters = (unsigned*)realloc(object->parameters, sizeof(unsigned)*(1 << max_partition_order))))
  97047. return false;
  97048. if(0 == (object->raw_bits = (unsigned*)realloc(object->raw_bits, sizeof(unsigned)*(1 << max_partition_order))))
  97049. return false;
  97050. memset(object->raw_bits, 0, sizeof(unsigned)*(1 << max_partition_order));
  97051. object->capacity_by_order = max_partition_order;
  97052. }
  97053. return true;
  97054. }
  97055. #endif
  97056. /*** End of inlined file: format.c ***/
  97057. /*** Start of inlined file: lpc_flac.c ***/
  97058. /*** Start of inlined file: juce_FlacHeader.h ***/
  97059. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  97060. // tasks..
  97061. #define VERSION "1.2.1"
  97062. #define FLAC__NO_DLL 1
  97063. #if JUCE_MSVC
  97064. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  97065. #endif
  97066. #if JUCE_MAC
  97067. #define FLAC__SYS_DARWIN 1
  97068. #endif
  97069. /*** End of inlined file: juce_FlacHeader.h ***/
  97070. #if JUCE_USE_FLAC
  97071. #if HAVE_CONFIG_H
  97072. # include <config.h>
  97073. #endif
  97074. #include <math.h>
  97075. /*** Start of inlined file: lpc.h ***/
  97076. #ifndef FLAC__PRIVATE__LPC_H
  97077. #define FLAC__PRIVATE__LPC_H
  97078. #ifdef HAVE_CONFIG_H
  97079. #include <config.h>
  97080. #endif
  97081. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97082. /*
  97083. * FLAC__lpc_window_data()
  97084. * --------------------------------------------------------------------
  97085. * Applies the given window to the data.
  97086. * OPT: asm implementation
  97087. *
  97088. * IN in[0,data_len-1]
  97089. * IN window[0,data_len-1]
  97090. * OUT out[0,lag-1]
  97091. * IN data_len
  97092. */
  97093. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len);
  97094. /*
  97095. * FLAC__lpc_compute_autocorrelation()
  97096. * --------------------------------------------------------------------
  97097. * Compute the autocorrelation for lags between 0 and lag-1.
  97098. * Assumes data[] outside of [0,data_len-1] == 0.
  97099. * Asserts that lag > 0.
  97100. *
  97101. * IN data[0,data_len-1]
  97102. * IN data_len
  97103. * IN 0 < lag <= data_len
  97104. * OUT autoc[0,lag-1]
  97105. */
  97106. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97107. #ifndef FLAC__NO_ASM
  97108. # ifdef FLAC__CPU_IA32
  97109. # ifdef FLAC__HAS_NASM
  97110. void FLAC__lpc_compute_autocorrelation_asm_ia32(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97111. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97112. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97113. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97114. void FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97115. # endif
  97116. # endif
  97117. #endif
  97118. /*
  97119. * FLAC__lpc_compute_lp_coefficients()
  97120. * --------------------------------------------------------------------
  97121. * Computes LP coefficients for orders 1..max_order.
  97122. * Do not call if autoc[0] == 0.0. This means the signal is zero
  97123. * and there is no point in calculating a predictor.
  97124. *
  97125. * IN autoc[0,max_order] autocorrelation values
  97126. * IN 0 < max_order <= FLAC__MAX_LPC_ORDER max LP order to compute
  97127. * OUT lp_coeff[0,max_order-1][0,max_order-1] LP coefficients for each order
  97128. * *** IMPORTANT:
  97129. * *** lp_coeff[0,max_order-1][max_order,FLAC__MAX_LPC_ORDER-1] are untouched
  97130. * OUT error[0,max_order-1] error for each order (more
  97131. * specifically, the variance of
  97132. * the error signal times # of
  97133. * samples in the signal)
  97134. *
  97135. * Example: if max_order is 9, the LP coefficients for order 9 will be
  97136. * in lp_coeff[8][0,8], the LP coefficients for order 8 will be
  97137. * in lp_coeff[7][0,7], etc.
  97138. */
  97139. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[]);
  97140. /*
  97141. * FLAC__lpc_quantize_coefficients()
  97142. * --------------------------------------------------------------------
  97143. * Quantizes the LP coefficients. NOTE: precision + bits_per_sample
  97144. * must be less than 32 (sizeof(FLAC__int32)*8).
  97145. *
  97146. * IN lp_coeff[0,order-1] LP coefficients
  97147. * IN order LP order
  97148. * IN FLAC__MIN_QLP_COEFF_PRECISION < precision
  97149. * desired precision (in bits, including sign
  97150. * bit) of largest coefficient
  97151. * OUT qlp_coeff[0,order-1] quantized coefficients
  97152. * OUT shift # of bits to shift right to get approximated
  97153. * LP coefficients. NOTE: could be negative.
  97154. * RETURN 0 => quantization OK
  97155. * 1 => coefficients require too much shifting for *shift to
  97156. * fit in the LPC subframe header. 'shift' is unset.
  97157. * 2 => coefficients are all zero, which is bad. 'shift' is
  97158. * unset.
  97159. */
  97160. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift);
  97161. /*
  97162. * FLAC__lpc_compute_residual_from_qlp_coefficients()
  97163. * --------------------------------------------------------------------
  97164. * Compute the residual signal obtained from sutracting the predicted
  97165. * signal from the original.
  97166. *
  97167. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  97168. * IN data_len length of original signal
  97169. * IN qlp_coeff[0,order-1] quantized LP coefficients
  97170. * IN order > 0 LP order
  97171. * IN lp_quantization quantization of LP coefficients in bits
  97172. * OUT residual[0,data_len-1] residual signal
  97173. */
  97174. 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[]);
  97175. 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[]);
  97176. #ifndef FLAC__NO_ASM
  97177. # ifdef FLAC__CPU_IA32
  97178. # ifdef FLAC__HAS_NASM
  97179. 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[]);
  97180. 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[]);
  97181. # endif
  97182. # endif
  97183. #endif
  97184. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  97185. /*
  97186. * FLAC__lpc_restore_signal()
  97187. * --------------------------------------------------------------------
  97188. * Restore the original signal by summing the residual and the
  97189. * predictor.
  97190. *
  97191. * IN residual[0,data_len-1] residual signal
  97192. * IN data_len length of original signal
  97193. * IN qlp_coeff[0,order-1] quantized LP coefficients
  97194. * IN order > 0 LP order
  97195. * IN lp_quantization quantization of LP coefficients in bits
  97196. * *** IMPORTANT: the caller must pass in the historical samples:
  97197. * IN data[-order,-1] previously-reconstructed historical samples
  97198. * OUT data[0,data_len-1] original signal
  97199. */
  97200. 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[]);
  97201. 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[]);
  97202. #ifndef FLAC__NO_ASM
  97203. # ifdef FLAC__CPU_IA32
  97204. # ifdef FLAC__HAS_NASM
  97205. 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[]);
  97206. 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[]);
  97207. # endif /* FLAC__HAS_NASM */
  97208. # elif defined FLAC__CPU_PPC
  97209. 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[]);
  97210. 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[]);
  97211. # endif/* FLAC__CPU_IA32 || FLAC__CPU_PPC */
  97212. #endif /* FLAC__NO_ASM */
  97213. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97214. /*
  97215. * FLAC__lpc_compute_expected_bits_per_residual_sample()
  97216. * --------------------------------------------------------------------
  97217. * Compute the expected number of bits per residual signal sample
  97218. * based on the LP error (which is related to the residual variance).
  97219. *
  97220. * IN lpc_error >= 0.0 error returned from calculating LP coefficients
  97221. * IN total_samples > 0 # of samples in residual signal
  97222. * RETURN expected bits per sample
  97223. */
  97224. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples);
  97225. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale);
  97226. /*
  97227. * FLAC__lpc_compute_best_order()
  97228. * --------------------------------------------------------------------
  97229. * Compute the best order from the array of signal errors returned
  97230. * during coefficient computation.
  97231. *
  97232. * IN lpc_error[0,max_order-1] >= 0.0 error returned from calculating LP coefficients
  97233. * IN max_order > 0 max LP order
  97234. * IN total_samples > 0 # of samples in residual signal
  97235. * IN overhead_bits_per_order # of bits overhead for each increased LP order
  97236. * (includes warmup sample size and quantized LP coefficient)
  97237. * RETURN [1,max_order] best order
  97238. */
  97239. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order);
  97240. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  97241. #endif
  97242. /*** End of inlined file: lpc.h ***/
  97243. #if defined DEBUG || defined FLAC__OVERFLOW_DETECT || defined FLAC__OVERFLOW_DETECT_VERBOSE
  97244. #include <stdio.h>
  97245. #endif
  97246. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97247. #ifndef M_LN2
  97248. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  97249. #define M_LN2 0.69314718055994530942
  97250. #endif
  97251. /* OPT: #undef'ing this may improve the speed on some architectures */
  97252. #define FLAC__LPC_UNROLLED_FILTER_LOOPS
  97253. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len)
  97254. {
  97255. unsigned i;
  97256. for(i = 0; i < data_len; i++)
  97257. out[i] = in[i] * window[i];
  97258. }
  97259. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[])
  97260. {
  97261. /* a readable, but slower, version */
  97262. #if 0
  97263. FLAC__real d;
  97264. unsigned i;
  97265. FLAC__ASSERT(lag > 0);
  97266. FLAC__ASSERT(lag <= data_len);
  97267. /*
  97268. * Technically we should subtract the mean first like so:
  97269. * for(i = 0; i < data_len; i++)
  97270. * data[i] -= mean;
  97271. * but it appears not to make enough of a difference to matter, and
  97272. * most signals are already closely centered around zero
  97273. */
  97274. while(lag--) {
  97275. for(i = lag, d = 0.0; i < data_len; i++)
  97276. d += data[i] * data[i - lag];
  97277. autoc[lag] = d;
  97278. }
  97279. #endif
  97280. /*
  97281. * this version tends to run faster because of better data locality
  97282. * ('data_len' is usually much larger than 'lag')
  97283. */
  97284. FLAC__real d;
  97285. unsigned sample, coeff;
  97286. const unsigned limit = data_len - lag;
  97287. FLAC__ASSERT(lag > 0);
  97288. FLAC__ASSERT(lag <= data_len);
  97289. for(coeff = 0; coeff < lag; coeff++)
  97290. autoc[coeff] = 0.0;
  97291. for(sample = 0; sample <= limit; sample++) {
  97292. d = data[sample];
  97293. for(coeff = 0; coeff < lag; coeff++)
  97294. autoc[coeff] += d * data[sample+coeff];
  97295. }
  97296. for(; sample < data_len; sample++) {
  97297. d = data[sample];
  97298. for(coeff = 0; coeff < data_len - sample; coeff++)
  97299. autoc[coeff] += d * data[sample+coeff];
  97300. }
  97301. }
  97302. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[])
  97303. {
  97304. unsigned i, j;
  97305. FLAC__double r, err, ref[FLAC__MAX_LPC_ORDER], lpc[FLAC__MAX_LPC_ORDER];
  97306. FLAC__ASSERT(0 != max_order);
  97307. FLAC__ASSERT(0 < *max_order);
  97308. FLAC__ASSERT(*max_order <= FLAC__MAX_LPC_ORDER);
  97309. FLAC__ASSERT(autoc[0] != 0.0);
  97310. err = autoc[0];
  97311. for(i = 0; i < *max_order; i++) {
  97312. /* Sum up this iteration's reflection coefficient. */
  97313. r = -autoc[i+1];
  97314. for(j = 0; j < i; j++)
  97315. r -= lpc[j] * autoc[i-j];
  97316. ref[i] = (r/=err);
  97317. /* Update LPC coefficients and total error. */
  97318. lpc[i]=r;
  97319. for(j = 0; j < (i>>1); j++) {
  97320. FLAC__double tmp = lpc[j];
  97321. lpc[j] += r * lpc[i-1-j];
  97322. lpc[i-1-j] += r * tmp;
  97323. }
  97324. if(i & 1)
  97325. lpc[j] += lpc[j] * r;
  97326. err *= (1.0 - r * r);
  97327. /* save this order */
  97328. for(j = 0; j <= i; j++)
  97329. lp_coeff[i][j] = (FLAC__real)(-lpc[j]); /* negate FIR filter coeff to get predictor coeff */
  97330. error[i] = err;
  97331. /* see SF bug #1601812 http://sourceforge.net/tracker/index.php?func=detail&aid=1601812&group_id=13478&atid=113478 */
  97332. if(err == 0.0) {
  97333. *max_order = i+1;
  97334. return;
  97335. }
  97336. }
  97337. }
  97338. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift)
  97339. {
  97340. unsigned i;
  97341. FLAC__double cmax;
  97342. FLAC__int32 qmax, qmin;
  97343. FLAC__ASSERT(precision > 0);
  97344. FLAC__ASSERT(precision >= FLAC__MIN_QLP_COEFF_PRECISION);
  97345. /* drop one bit for the sign; from here on out we consider only |lp_coeff[i]| */
  97346. precision--;
  97347. qmax = 1 << precision;
  97348. qmin = -qmax;
  97349. qmax--;
  97350. /* calc cmax = max( |lp_coeff[i]| ) */
  97351. cmax = 0.0;
  97352. for(i = 0; i < order; i++) {
  97353. const FLAC__double d = fabs(lp_coeff[i]);
  97354. if(d > cmax)
  97355. cmax = d;
  97356. }
  97357. if(cmax <= 0.0) {
  97358. /* => coefficients are all 0, which means our constant-detect didn't work */
  97359. return 2;
  97360. }
  97361. else {
  97362. const int max_shiftlimit = (1 << (FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN-1)) - 1;
  97363. const int min_shiftlimit = -max_shiftlimit - 1;
  97364. int log2cmax;
  97365. (void)frexp(cmax, &log2cmax);
  97366. log2cmax--;
  97367. *shift = (int)precision - log2cmax - 1;
  97368. if(*shift > max_shiftlimit)
  97369. *shift = max_shiftlimit;
  97370. else if(*shift < min_shiftlimit)
  97371. return 1;
  97372. }
  97373. if(*shift >= 0) {
  97374. FLAC__double error = 0.0;
  97375. FLAC__int32 q;
  97376. for(i = 0; i < order; i++) {
  97377. error += lp_coeff[i] * (1 << *shift);
  97378. #if 1 /* unfortunately lround() is C99 */
  97379. if(error >= 0.0)
  97380. q = (FLAC__int32)(error + 0.5);
  97381. else
  97382. q = (FLAC__int32)(error - 0.5);
  97383. #else
  97384. q = lround(error);
  97385. #endif
  97386. #ifdef FLAC__OVERFLOW_DETECT
  97387. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  97388. 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]);
  97389. else if(q < qmin)
  97390. 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]);
  97391. #endif
  97392. if(q > qmax)
  97393. q = qmax;
  97394. else if(q < qmin)
  97395. q = qmin;
  97396. error -= q;
  97397. qlp_coeff[i] = q;
  97398. }
  97399. }
  97400. /* negative shift is very rare but due to design flaw, negative shift is
  97401. * a NOP in the decoder, so it must be handled specially by scaling down
  97402. * coeffs
  97403. */
  97404. else {
  97405. const int nshift = -(*shift);
  97406. FLAC__double error = 0.0;
  97407. FLAC__int32 q;
  97408. #ifdef DEBUG
  97409. fprintf(stderr,"FLAC__lpc_quantize_coefficients: negative shift=%d order=%u cmax=%f\n", *shift, order, cmax);
  97410. #endif
  97411. for(i = 0; i < order; i++) {
  97412. error += lp_coeff[i] / (1 << nshift);
  97413. #if 1 /* unfortunately lround() is C99 */
  97414. if(error >= 0.0)
  97415. q = (FLAC__int32)(error + 0.5);
  97416. else
  97417. q = (FLAC__int32)(error - 0.5);
  97418. #else
  97419. q = lround(error);
  97420. #endif
  97421. #ifdef FLAC__OVERFLOW_DETECT
  97422. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  97423. 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]);
  97424. else if(q < qmin)
  97425. 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]);
  97426. #endif
  97427. if(q > qmax)
  97428. q = qmax;
  97429. else if(q < qmin)
  97430. q = qmin;
  97431. error -= q;
  97432. qlp_coeff[i] = q;
  97433. }
  97434. *shift = 0;
  97435. }
  97436. return 0;
  97437. }
  97438. 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[])
  97439. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97440. {
  97441. FLAC__int64 sumo;
  97442. unsigned i, j;
  97443. FLAC__int32 sum;
  97444. const FLAC__int32 *history;
  97445. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97446. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97447. for(i=0;i<order;i++)
  97448. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97449. fprintf(stderr,"\n");
  97450. #endif
  97451. FLAC__ASSERT(order > 0);
  97452. for(i = 0; i < data_len; i++) {
  97453. sumo = 0;
  97454. sum = 0;
  97455. history = data;
  97456. for(j = 0; j < order; j++) {
  97457. sum += qlp_coeff[j] * (*(--history));
  97458. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  97459. #if defined _MSC_VER
  97460. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  97461. 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);
  97462. #else
  97463. if(sumo > 2147483647ll || sumo < -2147483648ll)
  97464. 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);
  97465. #endif
  97466. }
  97467. *(residual++) = *(data++) - (sum >> lp_quantization);
  97468. }
  97469. /* Here's a slower but clearer version:
  97470. for(i = 0; i < data_len; i++) {
  97471. sum = 0;
  97472. for(j = 0; j < order; j++)
  97473. sum += qlp_coeff[j] * data[i-j-1];
  97474. residual[i] = data[i] - (sum >> lp_quantization);
  97475. }
  97476. */
  97477. }
  97478. #else /* fully unrolled version for normal use */
  97479. {
  97480. int i;
  97481. FLAC__int32 sum;
  97482. FLAC__ASSERT(order > 0);
  97483. FLAC__ASSERT(order <= 32);
  97484. /*
  97485. * We do unique versions up to 12th order since that's the subset limit.
  97486. * Also they are roughly ordered to match frequency of occurrence to
  97487. * minimize branching.
  97488. */
  97489. if(order <= 12) {
  97490. if(order > 8) {
  97491. if(order > 10) {
  97492. if(order == 12) {
  97493. for(i = 0; i < (int)data_len; i++) {
  97494. sum = 0;
  97495. sum += qlp_coeff[11] * data[i-12];
  97496. sum += qlp_coeff[10] * data[i-11];
  97497. sum += qlp_coeff[9] * data[i-10];
  97498. sum += qlp_coeff[8] * data[i-9];
  97499. sum += qlp_coeff[7] * data[i-8];
  97500. sum += qlp_coeff[6] * data[i-7];
  97501. sum += qlp_coeff[5] * data[i-6];
  97502. sum += qlp_coeff[4] * data[i-5];
  97503. sum += qlp_coeff[3] * data[i-4];
  97504. sum += qlp_coeff[2] * data[i-3];
  97505. sum += qlp_coeff[1] * data[i-2];
  97506. sum += qlp_coeff[0] * data[i-1];
  97507. residual[i] = data[i] - (sum >> lp_quantization);
  97508. }
  97509. }
  97510. else { /* order == 11 */
  97511. for(i = 0; i < (int)data_len; i++) {
  97512. sum = 0;
  97513. sum += qlp_coeff[10] * data[i-11];
  97514. sum += qlp_coeff[9] * data[i-10];
  97515. sum += qlp_coeff[8] * data[i-9];
  97516. sum += qlp_coeff[7] * data[i-8];
  97517. sum += qlp_coeff[6] * data[i-7];
  97518. sum += qlp_coeff[5] * data[i-6];
  97519. sum += qlp_coeff[4] * data[i-5];
  97520. sum += qlp_coeff[3] * data[i-4];
  97521. sum += qlp_coeff[2] * data[i-3];
  97522. sum += qlp_coeff[1] * data[i-2];
  97523. sum += qlp_coeff[0] * data[i-1];
  97524. residual[i] = data[i] - (sum >> lp_quantization);
  97525. }
  97526. }
  97527. }
  97528. else {
  97529. if(order == 10) {
  97530. for(i = 0; i < (int)data_len; i++) {
  97531. sum = 0;
  97532. sum += qlp_coeff[9] * data[i-10];
  97533. sum += qlp_coeff[8] * data[i-9];
  97534. sum += qlp_coeff[7] * data[i-8];
  97535. sum += qlp_coeff[6] * data[i-7];
  97536. sum += qlp_coeff[5] * data[i-6];
  97537. sum += qlp_coeff[4] * data[i-5];
  97538. sum += qlp_coeff[3] * data[i-4];
  97539. sum += qlp_coeff[2] * data[i-3];
  97540. sum += qlp_coeff[1] * data[i-2];
  97541. sum += qlp_coeff[0] * data[i-1];
  97542. residual[i] = data[i] - (sum >> lp_quantization);
  97543. }
  97544. }
  97545. else { /* order == 9 */
  97546. for(i = 0; i < (int)data_len; i++) {
  97547. sum = 0;
  97548. sum += qlp_coeff[8] * data[i-9];
  97549. sum += qlp_coeff[7] * data[i-8];
  97550. sum += qlp_coeff[6] * data[i-7];
  97551. sum += qlp_coeff[5] * data[i-6];
  97552. sum += qlp_coeff[4] * data[i-5];
  97553. sum += qlp_coeff[3] * data[i-4];
  97554. sum += qlp_coeff[2] * data[i-3];
  97555. sum += qlp_coeff[1] * data[i-2];
  97556. sum += qlp_coeff[0] * data[i-1];
  97557. residual[i] = data[i] - (sum >> lp_quantization);
  97558. }
  97559. }
  97560. }
  97561. }
  97562. else if(order > 4) {
  97563. if(order > 6) {
  97564. if(order == 8) {
  97565. for(i = 0; i < (int)data_len; i++) {
  97566. sum = 0;
  97567. sum += qlp_coeff[7] * data[i-8];
  97568. sum += qlp_coeff[6] * data[i-7];
  97569. sum += qlp_coeff[5] * data[i-6];
  97570. sum += qlp_coeff[4] * data[i-5];
  97571. sum += qlp_coeff[3] * data[i-4];
  97572. sum += qlp_coeff[2] * data[i-3];
  97573. sum += qlp_coeff[1] * data[i-2];
  97574. sum += qlp_coeff[0] * data[i-1];
  97575. residual[i] = data[i] - (sum >> lp_quantization);
  97576. }
  97577. }
  97578. else { /* order == 7 */
  97579. for(i = 0; i < (int)data_len; i++) {
  97580. sum = 0;
  97581. sum += qlp_coeff[6] * data[i-7];
  97582. sum += qlp_coeff[5] * data[i-6];
  97583. sum += qlp_coeff[4] * data[i-5];
  97584. sum += qlp_coeff[3] * data[i-4];
  97585. sum += qlp_coeff[2] * data[i-3];
  97586. sum += qlp_coeff[1] * data[i-2];
  97587. sum += qlp_coeff[0] * data[i-1];
  97588. residual[i] = data[i] - (sum >> lp_quantization);
  97589. }
  97590. }
  97591. }
  97592. else {
  97593. if(order == 6) {
  97594. for(i = 0; i < (int)data_len; i++) {
  97595. sum = 0;
  97596. sum += qlp_coeff[5] * data[i-6];
  97597. sum += qlp_coeff[4] * data[i-5];
  97598. sum += qlp_coeff[3] * data[i-4];
  97599. sum += qlp_coeff[2] * data[i-3];
  97600. sum += qlp_coeff[1] * data[i-2];
  97601. sum += qlp_coeff[0] * data[i-1];
  97602. residual[i] = data[i] - (sum >> lp_quantization);
  97603. }
  97604. }
  97605. else { /* order == 5 */
  97606. for(i = 0; i < (int)data_len; i++) {
  97607. sum = 0;
  97608. sum += qlp_coeff[4] * data[i-5];
  97609. sum += qlp_coeff[3] * data[i-4];
  97610. sum += qlp_coeff[2] * data[i-3];
  97611. sum += qlp_coeff[1] * data[i-2];
  97612. sum += qlp_coeff[0] * data[i-1];
  97613. residual[i] = data[i] - (sum >> lp_quantization);
  97614. }
  97615. }
  97616. }
  97617. }
  97618. else {
  97619. if(order > 2) {
  97620. if(order == 4) {
  97621. for(i = 0; i < (int)data_len; i++) {
  97622. sum = 0;
  97623. sum += qlp_coeff[3] * data[i-4];
  97624. sum += qlp_coeff[2] * data[i-3];
  97625. sum += qlp_coeff[1] * data[i-2];
  97626. sum += qlp_coeff[0] * data[i-1];
  97627. residual[i] = data[i] - (sum >> lp_quantization);
  97628. }
  97629. }
  97630. else { /* order == 3 */
  97631. for(i = 0; i < (int)data_len; i++) {
  97632. sum = 0;
  97633. sum += qlp_coeff[2] * data[i-3];
  97634. sum += qlp_coeff[1] * data[i-2];
  97635. sum += qlp_coeff[0] * data[i-1];
  97636. residual[i] = data[i] - (sum >> lp_quantization);
  97637. }
  97638. }
  97639. }
  97640. else {
  97641. if(order == 2) {
  97642. for(i = 0; i < (int)data_len; i++) {
  97643. sum = 0;
  97644. sum += qlp_coeff[1] * data[i-2];
  97645. sum += qlp_coeff[0] * data[i-1];
  97646. residual[i] = data[i] - (sum >> lp_quantization);
  97647. }
  97648. }
  97649. else { /* order == 1 */
  97650. for(i = 0; i < (int)data_len; i++)
  97651. residual[i] = data[i] - ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  97652. }
  97653. }
  97654. }
  97655. }
  97656. else { /* order > 12 */
  97657. for(i = 0; i < (int)data_len; i++) {
  97658. sum = 0;
  97659. switch(order) {
  97660. case 32: sum += qlp_coeff[31] * data[i-32];
  97661. case 31: sum += qlp_coeff[30] * data[i-31];
  97662. case 30: sum += qlp_coeff[29] * data[i-30];
  97663. case 29: sum += qlp_coeff[28] * data[i-29];
  97664. case 28: sum += qlp_coeff[27] * data[i-28];
  97665. case 27: sum += qlp_coeff[26] * data[i-27];
  97666. case 26: sum += qlp_coeff[25] * data[i-26];
  97667. case 25: sum += qlp_coeff[24] * data[i-25];
  97668. case 24: sum += qlp_coeff[23] * data[i-24];
  97669. case 23: sum += qlp_coeff[22] * data[i-23];
  97670. case 22: sum += qlp_coeff[21] * data[i-22];
  97671. case 21: sum += qlp_coeff[20] * data[i-21];
  97672. case 20: sum += qlp_coeff[19] * data[i-20];
  97673. case 19: sum += qlp_coeff[18] * data[i-19];
  97674. case 18: sum += qlp_coeff[17] * data[i-18];
  97675. case 17: sum += qlp_coeff[16] * data[i-17];
  97676. case 16: sum += qlp_coeff[15] * data[i-16];
  97677. case 15: sum += qlp_coeff[14] * data[i-15];
  97678. case 14: sum += qlp_coeff[13] * data[i-14];
  97679. case 13: sum += qlp_coeff[12] * data[i-13];
  97680. sum += qlp_coeff[11] * data[i-12];
  97681. sum += qlp_coeff[10] * data[i-11];
  97682. sum += qlp_coeff[ 9] * data[i-10];
  97683. sum += qlp_coeff[ 8] * data[i- 9];
  97684. sum += qlp_coeff[ 7] * data[i- 8];
  97685. sum += qlp_coeff[ 6] * data[i- 7];
  97686. sum += qlp_coeff[ 5] * data[i- 6];
  97687. sum += qlp_coeff[ 4] * data[i- 5];
  97688. sum += qlp_coeff[ 3] * data[i- 4];
  97689. sum += qlp_coeff[ 2] * data[i- 3];
  97690. sum += qlp_coeff[ 1] * data[i- 2];
  97691. sum += qlp_coeff[ 0] * data[i- 1];
  97692. }
  97693. residual[i] = data[i] - (sum >> lp_quantization);
  97694. }
  97695. }
  97696. }
  97697. #endif
  97698. 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[])
  97699. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97700. {
  97701. unsigned i, j;
  97702. FLAC__int64 sum;
  97703. const FLAC__int32 *history;
  97704. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97705. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97706. for(i=0;i<order;i++)
  97707. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97708. fprintf(stderr,"\n");
  97709. #endif
  97710. FLAC__ASSERT(order > 0);
  97711. for(i = 0; i < data_len; i++) {
  97712. sum = 0;
  97713. history = data;
  97714. for(j = 0; j < order; j++)
  97715. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  97716. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  97717. #if defined _MSC_VER
  97718. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  97719. #else
  97720. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  97721. #endif
  97722. break;
  97723. }
  97724. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*data) - (sum >> lp_quantization)) > 32) {
  97725. #if defined _MSC_VER
  97726. 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));
  97727. #else
  97728. 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)));
  97729. #endif
  97730. break;
  97731. }
  97732. *(residual++) = *(data++) - (FLAC__int32)(sum >> lp_quantization);
  97733. }
  97734. }
  97735. #else /* fully unrolled version for normal use */
  97736. {
  97737. int i;
  97738. FLAC__int64 sum;
  97739. FLAC__ASSERT(order > 0);
  97740. FLAC__ASSERT(order <= 32);
  97741. /*
  97742. * We do unique versions up to 12th order since that's the subset limit.
  97743. * Also they are roughly ordered to match frequency of occurrence to
  97744. * minimize branching.
  97745. */
  97746. if(order <= 12) {
  97747. if(order > 8) {
  97748. if(order > 10) {
  97749. if(order == 12) {
  97750. for(i = 0; i < (int)data_len; i++) {
  97751. sum = 0;
  97752. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  97753. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97754. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97755. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97756. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97757. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97758. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97759. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97760. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97761. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97762. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97763. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97764. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97765. }
  97766. }
  97767. else { /* order == 11 */
  97768. for(i = 0; i < (int)data_len; i++) {
  97769. sum = 0;
  97770. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97771. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97772. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97773. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97774. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97775. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97776. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97777. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97778. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97779. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97780. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97781. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97782. }
  97783. }
  97784. }
  97785. else {
  97786. if(order == 10) {
  97787. for(i = 0; i < (int)data_len; i++) {
  97788. sum = 0;
  97789. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97790. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97791. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97792. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97793. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97794. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97795. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97796. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97797. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97798. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97799. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97800. }
  97801. }
  97802. else { /* order == 9 */
  97803. for(i = 0; i < (int)data_len; i++) {
  97804. sum = 0;
  97805. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97806. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97807. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97808. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97809. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97810. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97811. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97812. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97813. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97814. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97815. }
  97816. }
  97817. }
  97818. }
  97819. else if(order > 4) {
  97820. if(order > 6) {
  97821. if(order == 8) {
  97822. for(i = 0; i < (int)data_len; i++) {
  97823. sum = 0;
  97824. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97825. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97826. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97827. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97828. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97829. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97830. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97831. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97832. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97833. }
  97834. }
  97835. else { /* order == 7 */
  97836. for(i = 0; i < (int)data_len; i++) {
  97837. sum = 0;
  97838. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97839. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97840. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97841. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97842. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97843. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97844. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97845. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97846. }
  97847. }
  97848. }
  97849. else {
  97850. if(order == 6) {
  97851. for(i = 0; i < (int)data_len; i++) {
  97852. sum = 0;
  97853. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97854. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97855. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97856. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97857. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97858. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97859. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97860. }
  97861. }
  97862. else { /* order == 5 */
  97863. for(i = 0; i < (int)data_len; i++) {
  97864. sum = 0;
  97865. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97866. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97867. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97868. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97869. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97870. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97871. }
  97872. }
  97873. }
  97874. }
  97875. else {
  97876. if(order > 2) {
  97877. if(order == 4) {
  97878. for(i = 0; i < (int)data_len; i++) {
  97879. sum = 0;
  97880. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97881. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97882. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97883. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97884. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97885. }
  97886. }
  97887. else { /* order == 3 */
  97888. for(i = 0; i < (int)data_len; i++) {
  97889. sum = 0;
  97890. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97891. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97892. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97893. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97894. }
  97895. }
  97896. }
  97897. else {
  97898. if(order == 2) {
  97899. for(i = 0; i < (int)data_len; i++) {
  97900. sum = 0;
  97901. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97902. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97903. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97904. }
  97905. }
  97906. else { /* order == 1 */
  97907. for(i = 0; i < (int)data_len; i++)
  97908. residual[i] = data[i] - (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  97909. }
  97910. }
  97911. }
  97912. }
  97913. else { /* order > 12 */
  97914. for(i = 0; i < (int)data_len; i++) {
  97915. sum = 0;
  97916. switch(order) {
  97917. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  97918. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  97919. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  97920. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  97921. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  97922. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  97923. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  97924. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  97925. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  97926. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  97927. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  97928. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  97929. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  97930. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  97931. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  97932. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  97933. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  97934. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  97935. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  97936. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  97937. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  97938. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97939. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  97940. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  97941. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  97942. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  97943. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  97944. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  97945. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  97946. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  97947. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  97948. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  97949. }
  97950. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97951. }
  97952. }
  97953. }
  97954. #endif
  97955. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  97956. 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[])
  97957. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97958. {
  97959. FLAC__int64 sumo;
  97960. unsigned i, j;
  97961. FLAC__int32 sum;
  97962. const FLAC__int32 *r = residual, *history;
  97963. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97964. fprintf(stderr,"FLAC__lpc_restore_signal: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97965. for(i=0;i<order;i++)
  97966. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97967. fprintf(stderr,"\n");
  97968. #endif
  97969. FLAC__ASSERT(order > 0);
  97970. for(i = 0; i < data_len; i++) {
  97971. sumo = 0;
  97972. sum = 0;
  97973. history = data;
  97974. for(j = 0; j < order; j++) {
  97975. sum += qlp_coeff[j] * (*(--history));
  97976. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  97977. #if defined _MSC_VER
  97978. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  97979. 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);
  97980. #else
  97981. if(sumo > 2147483647ll || sumo < -2147483648ll)
  97982. 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);
  97983. #endif
  97984. }
  97985. *(data++) = *(r++) + (sum >> lp_quantization);
  97986. }
  97987. /* Here's a slower but clearer version:
  97988. for(i = 0; i < data_len; i++) {
  97989. sum = 0;
  97990. for(j = 0; j < order; j++)
  97991. sum += qlp_coeff[j] * data[i-j-1];
  97992. data[i] = residual[i] + (sum >> lp_quantization);
  97993. }
  97994. */
  97995. }
  97996. #else /* fully unrolled version for normal use */
  97997. {
  97998. int i;
  97999. FLAC__int32 sum;
  98000. FLAC__ASSERT(order > 0);
  98001. FLAC__ASSERT(order <= 32);
  98002. /*
  98003. * We do unique versions up to 12th order since that's the subset limit.
  98004. * Also they are roughly ordered to match frequency of occurrence to
  98005. * minimize branching.
  98006. */
  98007. if(order <= 12) {
  98008. if(order > 8) {
  98009. if(order > 10) {
  98010. if(order == 12) {
  98011. for(i = 0; i < (int)data_len; i++) {
  98012. sum = 0;
  98013. sum += qlp_coeff[11] * data[i-12];
  98014. sum += qlp_coeff[10] * data[i-11];
  98015. sum += qlp_coeff[9] * data[i-10];
  98016. sum += qlp_coeff[8] * data[i-9];
  98017. sum += qlp_coeff[7] * data[i-8];
  98018. sum += qlp_coeff[6] * data[i-7];
  98019. sum += qlp_coeff[5] * data[i-6];
  98020. sum += qlp_coeff[4] * data[i-5];
  98021. sum += qlp_coeff[3] * data[i-4];
  98022. sum += qlp_coeff[2] * data[i-3];
  98023. sum += qlp_coeff[1] * data[i-2];
  98024. sum += qlp_coeff[0] * data[i-1];
  98025. data[i] = residual[i] + (sum >> lp_quantization);
  98026. }
  98027. }
  98028. else { /* order == 11 */
  98029. for(i = 0; i < (int)data_len; i++) {
  98030. sum = 0;
  98031. sum += qlp_coeff[10] * data[i-11];
  98032. sum += qlp_coeff[9] * data[i-10];
  98033. sum += qlp_coeff[8] * data[i-9];
  98034. sum += qlp_coeff[7] * data[i-8];
  98035. sum += qlp_coeff[6] * data[i-7];
  98036. sum += qlp_coeff[5] * data[i-6];
  98037. sum += qlp_coeff[4] * data[i-5];
  98038. sum += qlp_coeff[3] * data[i-4];
  98039. sum += qlp_coeff[2] * data[i-3];
  98040. sum += qlp_coeff[1] * data[i-2];
  98041. sum += qlp_coeff[0] * data[i-1];
  98042. data[i] = residual[i] + (sum >> lp_quantization);
  98043. }
  98044. }
  98045. }
  98046. else {
  98047. if(order == 10) {
  98048. for(i = 0; i < (int)data_len; i++) {
  98049. sum = 0;
  98050. sum += qlp_coeff[9] * data[i-10];
  98051. sum += qlp_coeff[8] * data[i-9];
  98052. sum += qlp_coeff[7] * data[i-8];
  98053. sum += qlp_coeff[6] * data[i-7];
  98054. sum += qlp_coeff[5] * data[i-6];
  98055. sum += qlp_coeff[4] * data[i-5];
  98056. sum += qlp_coeff[3] * data[i-4];
  98057. sum += qlp_coeff[2] * data[i-3];
  98058. sum += qlp_coeff[1] * data[i-2];
  98059. sum += qlp_coeff[0] * data[i-1];
  98060. data[i] = residual[i] + (sum >> lp_quantization);
  98061. }
  98062. }
  98063. else { /* order == 9 */
  98064. for(i = 0; i < (int)data_len; i++) {
  98065. sum = 0;
  98066. sum += qlp_coeff[8] * data[i-9];
  98067. sum += qlp_coeff[7] * data[i-8];
  98068. sum += qlp_coeff[6] * data[i-7];
  98069. sum += qlp_coeff[5] * data[i-6];
  98070. sum += qlp_coeff[4] * data[i-5];
  98071. sum += qlp_coeff[3] * data[i-4];
  98072. sum += qlp_coeff[2] * data[i-3];
  98073. sum += qlp_coeff[1] * data[i-2];
  98074. sum += qlp_coeff[0] * data[i-1];
  98075. data[i] = residual[i] + (sum >> lp_quantization);
  98076. }
  98077. }
  98078. }
  98079. }
  98080. else if(order > 4) {
  98081. if(order > 6) {
  98082. if(order == 8) {
  98083. for(i = 0; i < (int)data_len; i++) {
  98084. sum = 0;
  98085. sum += qlp_coeff[7] * data[i-8];
  98086. sum += qlp_coeff[6] * data[i-7];
  98087. sum += qlp_coeff[5] * data[i-6];
  98088. sum += qlp_coeff[4] * data[i-5];
  98089. sum += qlp_coeff[3] * data[i-4];
  98090. sum += qlp_coeff[2] * data[i-3];
  98091. sum += qlp_coeff[1] * data[i-2];
  98092. sum += qlp_coeff[0] * data[i-1];
  98093. data[i] = residual[i] + (sum >> lp_quantization);
  98094. }
  98095. }
  98096. else { /* order == 7 */
  98097. for(i = 0; i < (int)data_len; i++) {
  98098. sum = 0;
  98099. sum += qlp_coeff[6] * data[i-7];
  98100. sum += qlp_coeff[5] * data[i-6];
  98101. sum += qlp_coeff[4] * data[i-5];
  98102. sum += qlp_coeff[3] * data[i-4];
  98103. sum += qlp_coeff[2] * data[i-3];
  98104. sum += qlp_coeff[1] * data[i-2];
  98105. sum += qlp_coeff[0] * data[i-1];
  98106. data[i] = residual[i] + (sum >> lp_quantization);
  98107. }
  98108. }
  98109. }
  98110. else {
  98111. if(order == 6) {
  98112. for(i = 0; i < (int)data_len; i++) {
  98113. sum = 0;
  98114. sum += qlp_coeff[5] * data[i-6];
  98115. sum += qlp_coeff[4] * data[i-5];
  98116. sum += qlp_coeff[3] * data[i-4];
  98117. sum += qlp_coeff[2] * data[i-3];
  98118. sum += qlp_coeff[1] * data[i-2];
  98119. sum += qlp_coeff[0] * data[i-1];
  98120. data[i] = residual[i] + (sum >> lp_quantization);
  98121. }
  98122. }
  98123. else { /* order == 5 */
  98124. for(i = 0; i < (int)data_len; i++) {
  98125. sum = 0;
  98126. sum += qlp_coeff[4] * data[i-5];
  98127. sum += qlp_coeff[3] * data[i-4];
  98128. sum += qlp_coeff[2] * data[i-3];
  98129. sum += qlp_coeff[1] * data[i-2];
  98130. sum += qlp_coeff[0] * data[i-1];
  98131. data[i] = residual[i] + (sum >> lp_quantization);
  98132. }
  98133. }
  98134. }
  98135. }
  98136. else {
  98137. if(order > 2) {
  98138. if(order == 4) {
  98139. for(i = 0; i < (int)data_len; i++) {
  98140. sum = 0;
  98141. sum += qlp_coeff[3] * data[i-4];
  98142. sum += qlp_coeff[2] * data[i-3];
  98143. sum += qlp_coeff[1] * data[i-2];
  98144. sum += qlp_coeff[0] * data[i-1];
  98145. data[i] = residual[i] + (sum >> lp_quantization);
  98146. }
  98147. }
  98148. else { /* order == 3 */
  98149. for(i = 0; i < (int)data_len; i++) {
  98150. sum = 0;
  98151. sum += qlp_coeff[2] * data[i-3];
  98152. sum += qlp_coeff[1] * data[i-2];
  98153. sum += qlp_coeff[0] * data[i-1];
  98154. data[i] = residual[i] + (sum >> lp_quantization);
  98155. }
  98156. }
  98157. }
  98158. else {
  98159. if(order == 2) {
  98160. for(i = 0; i < (int)data_len; i++) {
  98161. sum = 0;
  98162. sum += qlp_coeff[1] * data[i-2];
  98163. sum += qlp_coeff[0] * data[i-1];
  98164. data[i] = residual[i] + (sum >> lp_quantization);
  98165. }
  98166. }
  98167. else { /* order == 1 */
  98168. for(i = 0; i < (int)data_len; i++)
  98169. data[i] = residual[i] + ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  98170. }
  98171. }
  98172. }
  98173. }
  98174. else { /* order > 12 */
  98175. for(i = 0; i < (int)data_len; i++) {
  98176. sum = 0;
  98177. switch(order) {
  98178. case 32: sum += qlp_coeff[31] * data[i-32];
  98179. case 31: sum += qlp_coeff[30] * data[i-31];
  98180. case 30: sum += qlp_coeff[29] * data[i-30];
  98181. case 29: sum += qlp_coeff[28] * data[i-29];
  98182. case 28: sum += qlp_coeff[27] * data[i-28];
  98183. case 27: sum += qlp_coeff[26] * data[i-27];
  98184. case 26: sum += qlp_coeff[25] * data[i-26];
  98185. case 25: sum += qlp_coeff[24] * data[i-25];
  98186. case 24: sum += qlp_coeff[23] * data[i-24];
  98187. case 23: sum += qlp_coeff[22] * data[i-23];
  98188. case 22: sum += qlp_coeff[21] * data[i-22];
  98189. case 21: sum += qlp_coeff[20] * data[i-21];
  98190. case 20: sum += qlp_coeff[19] * data[i-20];
  98191. case 19: sum += qlp_coeff[18] * data[i-19];
  98192. case 18: sum += qlp_coeff[17] * data[i-18];
  98193. case 17: sum += qlp_coeff[16] * data[i-17];
  98194. case 16: sum += qlp_coeff[15] * data[i-16];
  98195. case 15: sum += qlp_coeff[14] * data[i-15];
  98196. case 14: sum += qlp_coeff[13] * data[i-14];
  98197. case 13: sum += qlp_coeff[12] * data[i-13];
  98198. sum += qlp_coeff[11] * data[i-12];
  98199. sum += qlp_coeff[10] * data[i-11];
  98200. sum += qlp_coeff[ 9] * data[i-10];
  98201. sum += qlp_coeff[ 8] * data[i- 9];
  98202. sum += qlp_coeff[ 7] * data[i- 8];
  98203. sum += qlp_coeff[ 6] * data[i- 7];
  98204. sum += qlp_coeff[ 5] * data[i- 6];
  98205. sum += qlp_coeff[ 4] * data[i- 5];
  98206. sum += qlp_coeff[ 3] * data[i- 4];
  98207. sum += qlp_coeff[ 2] * data[i- 3];
  98208. sum += qlp_coeff[ 1] * data[i- 2];
  98209. sum += qlp_coeff[ 0] * data[i- 1];
  98210. }
  98211. data[i] = residual[i] + (sum >> lp_quantization);
  98212. }
  98213. }
  98214. }
  98215. #endif
  98216. 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[])
  98217. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  98218. {
  98219. unsigned i, j;
  98220. FLAC__int64 sum;
  98221. const FLAC__int32 *r = residual, *history;
  98222. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  98223. fprintf(stderr,"FLAC__lpc_restore_signal_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  98224. for(i=0;i<order;i++)
  98225. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  98226. fprintf(stderr,"\n");
  98227. #endif
  98228. FLAC__ASSERT(order > 0);
  98229. for(i = 0; i < data_len; i++) {
  98230. sum = 0;
  98231. history = data;
  98232. for(j = 0; j < order; j++)
  98233. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  98234. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  98235. #ifdef _MSC_VER
  98236. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  98237. #else
  98238. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  98239. #endif
  98240. break;
  98241. }
  98242. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*r) + (sum >> lp_quantization)) > 32) {
  98243. #ifdef _MSC_VER
  98244. 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));
  98245. #else
  98246. 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)));
  98247. #endif
  98248. break;
  98249. }
  98250. *(data++) = *(r++) + (FLAC__int32)(sum >> lp_quantization);
  98251. }
  98252. }
  98253. #else /* fully unrolled version for normal use */
  98254. {
  98255. int i;
  98256. FLAC__int64 sum;
  98257. FLAC__ASSERT(order > 0);
  98258. FLAC__ASSERT(order <= 32);
  98259. /*
  98260. * We do unique versions up to 12th order since that's the subset limit.
  98261. * Also they are roughly ordered to match frequency of occurrence to
  98262. * minimize branching.
  98263. */
  98264. if(order <= 12) {
  98265. if(order > 8) {
  98266. if(order > 10) {
  98267. if(order == 12) {
  98268. for(i = 0; i < (int)data_len; i++) {
  98269. sum = 0;
  98270. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  98271. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  98272. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  98273. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98274. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98275. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98276. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98277. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98278. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98279. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98280. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98281. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98282. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98283. }
  98284. }
  98285. else { /* order == 11 */
  98286. for(i = 0; i < (int)data_len; i++) {
  98287. sum = 0;
  98288. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  98289. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  98290. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98291. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98292. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98293. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98294. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98295. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98296. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98297. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98298. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98299. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98300. }
  98301. }
  98302. }
  98303. else {
  98304. if(order == 10) {
  98305. for(i = 0; i < (int)data_len; i++) {
  98306. sum = 0;
  98307. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  98308. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98309. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98310. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98311. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98312. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98313. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98314. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98315. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98316. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98317. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98318. }
  98319. }
  98320. else { /* order == 9 */
  98321. for(i = 0; i < (int)data_len; i++) {
  98322. sum = 0;
  98323. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98324. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98325. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98326. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98327. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98328. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98329. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98330. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98331. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98332. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98333. }
  98334. }
  98335. }
  98336. }
  98337. else if(order > 4) {
  98338. if(order > 6) {
  98339. if(order == 8) {
  98340. for(i = 0; i < (int)data_len; i++) {
  98341. sum = 0;
  98342. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98343. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98344. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98345. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98346. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98347. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98348. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98349. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98350. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98351. }
  98352. }
  98353. else { /* order == 7 */
  98354. for(i = 0; i < (int)data_len; i++) {
  98355. sum = 0;
  98356. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98357. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98358. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98359. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98360. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98361. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98362. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98363. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98364. }
  98365. }
  98366. }
  98367. else {
  98368. if(order == 6) {
  98369. for(i = 0; i < (int)data_len; i++) {
  98370. sum = 0;
  98371. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98372. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98373. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98374. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98375. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98376. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98377. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98378. }
  98379. }
  98380. else { /* order == 5 */
  98381. for(i = 0; i < (int)data_len; i++) {
  98382. sum = 0;
  98383. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98384. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98385. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98386. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98387. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98388. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98389. }
  98390. }
  98391. }
  98392. }
  98393. else {
  98394. if(order > 2) {
  98395. if(order == 4) {
  98396. for(i = 0; i < (int)data_len; i++) {
  98397. sum = 0;
  98398. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98399. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98400. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98401. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98402. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98403. }
  98404. }
  98405. else { /* order == 3 */
  98406. for(i = 0; i < (int)data_len; i++) {
  98407. sum = 0;
  98408. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98409. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98410. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98411. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98412. }
  98413. }
  98414. }
  98415. else {
  98416. if(order == 2) {
  98417. for(i = 0; i < (int)data_len; i++) {
  98418. sum = 0;
  98419. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98420. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98421. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98422. }
  98423. }
  98424. else { /* order == 1 */
  98425. for(i = 0; i < (int)data_len; i++)
  98426. data[i] = residual[i] + (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  98427. }
  98428. }
  98429. }
  98430. }
  98431. else { /* order > 12 */
  98432. for(i = 0; i < (int)data_len; i++) {
  98433. sum = 0;
  98434. switch(order) {
  98435. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  98436. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  98437. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  98438. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  98439. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  98440. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  98441. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  98442. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  98443. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  98444. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  98445. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  98446. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  98447. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  98448. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  98449. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  98450. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  98451. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  98452. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  98453. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  98454. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  98455. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  98456. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  98457. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  98458. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  98459. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  98460. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  98461. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  98462. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  98463. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  98464. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  98465. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  98466. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  98467. }
  98468. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98469. }
  98470. }
  98471. }
  98472. #endif
  98473. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98474. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples)
  98475. {
  98476. FLAC__double error_scale;
  98477. FLAC__ASSERT(total_samples > 0);
  98478. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  98479. return FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(lpc_error, error_scale);
  98480. }
  98481. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale)
  98482. {
  98483. if(lpc_error > 0.0) {
  98484. FLAC__double bps = (FLAC__double)0.5 * log(error_scale * lpc_error) / M_LN2;
  98485. if(bps >= 0.0)
  98486. return bps;
  98487. else
  98488. return 0.0;
  98489. }
  98490. else if(lpc_error < 0.0) { /* error should not be negative but can happen due to inadequate floating-point resolution */
  98491. return 1e32;
  98492. }
  98493. else {
  98494. return 0.0;
  98495. }
  98496. }
  98497. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order)
  98498. {
  98499. 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 */
  98500. FLAC__double bits, best_bits, error_scale;
  98501. FLAC__ASSERT(max_order > 0);
  98502. FLAC__ASSERT(total_samples > 0);
  98503. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  98504. best_index = 0;
  98505. best_bits = (unsigned)(-1);
  98506. for(index = 0, order = 1; index < max_order; index++, order++) {
  98507. 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);
  98508. if(bits < best_bits) {
  98509. best_index = index;
  98510. best_bits = bits;
  98511. }
  98512. }
  98513. return best_index+1; /* +1 since index of lpc_error[] is order-1 */
  98514. }
  98515. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  98516. #endif
  98517. /*** End of inlined file: lpc_flac.c ***/
  98518. /*** Start of inlined file: md5.c ***/
  98519. /*** Start of inlined file: juce_FlacHeader.h ***/
  98520. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  98521. // tasks..
  98522. #define VERSION "1.2.1"
  98523. #define FLAC__NO_DLL 1
  98524. #if JUCE_MSVC
  98525. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  98526. #endif
  98527. #if JUCE_MAC
  98528. #define FLAC__SYS_DARWIN 1
  98529. #endif
  98530. /*** End of inlined file: juce_FlacHeader.h ***/
  98531. #if JUCE_USE_FLAC
  98532. #if HAVE_CONFIG_H
  98533. # include <config.h>
  98534. #endif
  98535. #include <stdlib.h> /* for malloc() */
  98536. #include <string.h> /* for memcpy() */
  98537. /*** Start of inlined file: md5.h ***/
  98538. #ifndef FLAC__PRIVATE__MD5_H
  98539. #define FLAC__PRIVATE__MD5_H
  98540. /*
  98541. * This is the header file for the MD5 message-digest algorithm.
  98542. * The algorithm is due to Ron Rivest. This code was
  98543. * written by Colin Plumb in 1993, no copyright is claimed.
  98544. * This code is in the public domain; do with it what you wish.
  98545. *
  98546. * Equivalent code is available from RSA Data Security, Inc.
  98547. * This code has been tested against that, and is equivalent,
  98548. * except that you don't need to include two pages of legalese
  98549. * with every copy.
  98550. *
  98551. * To compute the message digest of a chunk of bytes, declare an
  98552. * MD5Context structure, pass it to MD5Init, call MD5Update as
  98553. * needed on buffers full of bytes, and then call MD5Final, which
  98554. * will fill a supplied 16-byte array with the digest.
  98555. *
  98556. * Changed so as no longer to depend on Colin Plumb's `usual.h'
  98557. * header definitions; now uses stuff from dpkg's config.h
  98558. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  98559. * Still in the public domain.
  98560. *
  98561. * Josh Coalson: made some changes to integrate with libFLAC.
  98562. * Still in the public domain, with no warranty.
  98563. */
  98564. typedef struct {
  98565. FLAC__uint32 in[16];
  98566. FLAC__uint32 buf[4];
  98567. FLAC__uint32 bytes[2];
  98568. FLAC__byte *internal_buf;
  98569. size_t capacity;
  98570. } FLAC__MD5Context;
  98571. void FLAC__MD5Init(FLAC__MD5Context *context);
  98572. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *context);
  98573. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample);
  98574. #endif
  98575. /*** End of inlined file: md5.h ***/
  98576. #ifndef FLaC__INLINE
  98577. #define FLaC__INLINE
  98578. #endif
  98579. /*
  98580. * This code implements the MD5 message-digest algorithm.
  98581. * The algorithm is due to Ron Rivest. This code was
  98582. * written by Colin Plumb in 1993, no copyright is claimed.
  98583. * This code is in the public domain; do with it what you wish.
  98584. *
  98585. * Equivalent code is available from RSA Data Security, Inc.
  98586. * This code has been tested against that, and is equivalent,
  98587. * except that you don't need to include two pages of legalese
  98588. * with every copy.
  98589. *
  98590. * To compute the message digest of a chunk of bytes, declare an
  98591. * MD5Context structure, pass it to MD5Init, call MD5Update as
  98592. * needed on buffers full of bytes, and then call MD5Final, which
  98593. * will fill a supplied 16-byte array with the digest.
  98594. *
  98595. * Changed so as no longer to depend on Colin Plumb's `usual.h' header
  98596. * definitions; now uses stuff from dpkg's config.h.
  98597. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  98598. * Still in the public domain.
  98599. *
  98600. * Josh Coalson: made some changes to integrate with libFLAC.
  98601. * Still in the public domain.
  98602. */
  98603. /* The four core functions - F1 is optimized somewhat */
  98604. /* #define F1(x, y, z) (x & y | ~x & z) */
  98605. #define F1(x, y, z) (z ^ (x & (y ^ z)))
  98606. #define F2(x, y, z) F1(z, x, y)
  98607. #define F3(x, y, z) (x ^ y ^ z)
  98608. #define F4(x, y, z) (y ^ (x | ~z))
  98609. /* This is the central step in the MD5 algorithm. */
  98610. #define MD5STEP(f,w,x,y,z,in,s) \
  98611. (w += f(x,y,z) + in, w = (w<<s | w>>(32-s)) + x)
  98612. /*
  98613. * The core of the MD5 algorithm, this alters an existing MD5 hash to
  98614. * reflect the addition of 16 longwords of new data. MD5Update blocks
  98615. * the data and converts bytes into longwords for this routine.
  98616. */
  98617. static void FLAC__MD5Transform(FLAC__uint32 buf[4], FLAC__uint32 const in[16])
  98618. {
  98619. register FLAC__uint32 a, b, c, d;
  98620. a = buf[0];
  98621. b = buf[1];
  98622. c = buf[2];
  98623. d = buf[3];
  98624. MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
  98625. MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
  98626. MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
  98627. MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
  98628. MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
  98629. MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
  98630. MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
  98631. MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
  98632. MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
  98633. MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
  98634. MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
  98635. MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
  98636. MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
  98637. MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
  98638. MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
  98639. MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
  98640. MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
  98641. MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
  98642. MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
  98643. MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
  98644. MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
  98645. MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
  98646. MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
  98647. MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
  98648. MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
  98649. MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
  98650. MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
  98651. MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
  98652. MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
  98653. MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
  98654. MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
  98655. MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
  98656. MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
  98657. MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
  98658. MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
  98659. MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
  98660. MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
  98661. MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
  98662. MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
  98663. MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
  98664. MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
  98665. MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
  98666. MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
  98667. MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
  98668. MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
  98669. MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
  98670. MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
  98671. MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
  98672. MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
  98673. MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
  98674. MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
  98675. MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
  98676. MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
  98677. MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
  98678. MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
  98679. MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
  98680. MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
  98681. MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
  98682. MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
  98683. MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
  98684. MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
  98685. MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
  98686. MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
  98687. MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
  98688. buf[0] += a;
  98689. buf[1] += b;
  98690. buf[2] += c;
  98691. buf[3] += d;
  98692. }
  98693. #if WORDS_BIGENDIAN
  98694. //@@@@@@ OPT: use bswap/intrinsics
  98695. static void byteSwap(FLAC__uint32 *buf, unsigned words)
  98696. {
  98697. register FLAC__uint32 x;
  98698. do {
  98699. x = *buf;
  98700. x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff);
  98701. *buf++ = (x >> 16) | (x << 16);
  98702. } while (--words);
  98703. }
  98704. static void byteSwapX16(FLAC__uint32 *buf)
  98705. {
  98706. register FLAC__uint32 x;
  98707. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98708. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98709. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98710. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98711. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98712. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98713. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98714. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98715. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98716. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98717. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98718. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98719. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98720. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98721. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98722. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf = (x >> 16) | (x << 16);
  98723. }
  98724. #else
  98725. #define byteSwap(buf, words)
  98726. #define byteSwapX16(buf)
  98727. #endif
  98728. /*
  98729. * Update context to reflect the concatenation of another buffer full
  98730. * of bytes.
  98731. */
  98732. static void FLAC__MD5Update(FLAC__MD5Context *ctx, FLAC__byte const *buf, unsigned len)
  98733. {
  98734. FLAC__uint32 t;
  98735. /* Update byte count */
  98736. t = ctx->bytes[0];
  98737. if ((ctx->bytes[0] = t + len) < t)
  98738. ctx->bytes[1]++; /* Carry from low to high */
  98739. t = 64 - (t & 0x3f); /* Space available in ctx->in (at least 1) */
  98740. if (t > len) {
  98741. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, len);
  98742. return;
  98743. }
  98744. /* First chunk is an odd size */
  98745. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, t);
  98746. byteSwapX16(ctx->in);
  98747. FLAC__MD5Transform(ctx->buf, ctx->in);
  98748. buf += t;
  98749. len -= t;
  98750. /* Process data in 64-byte chunks */
  98751. while (len >= 64) {
  98752. memcpy(ctx->in, buf, 64);
  98753. byteSwapX16(ctx->in);
  98754. FLAC__MD5Transform(ctx->buf, ctx->in);
  98755. buf += 64;
  98756. len -= 64;
  98757. }
  98758. /* Handle any remaining bytes of data. */
  98759. memcpy(ctx->in, buf, len);
  98760. }
  98761. /*
  98762. * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
  98763. * initialization constants.
  98764. */
  98765. void FLAC__MD5Init(FLAC__MD5Context *ctx)
  98766. {
  98767. ctx->buf[0] = 0x67452301;
  98768. ctx->buf[1] = 0xefcdab89;
  98769. ctx->buf[2] = 0x98badcfe;
  98770. ctx->buf[3] = 0x10325476;
  98771. ctx->bytes[0] = 0;
  98772. ctx->bytes[1] = 0;
  98773. ctx->internal_buf = 0;
  98774. ctx->capacity = 0;
  98775. }
  98776. /*
  98777. * Final wrapup - pad to 64-byte boundary with the bit pattern
  98778. * 1 0* (64-bit count of bits processed, MSB-first)
  98779. */
  98780. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *ctx)
  98781. {
  98782. int count = ctx->bytes[0] & 0x3f; /* Number of bytes in ctx->in */
  98783. FLAC__byte *p = (FLAC__byte *)ctx->in + count;
  98784. /* Set the first char of padding to 0x80. There is always room. */
  98785. *p++ = 0x80;
  98786. /* Bytes of padding needed to make 56 bytes (-8..55) */
  98787. count = 56 - 1 - count;
  98788. if (count < 0) { /* Padding forces an extra block */
  98789. memset(p, 0, count + 8);
  98790. byteSwapX16(ctx->in);
  98791. FLAC__MD5Transform(ctx->buf, ctx->in);
  98792. p = (FLAC__byte *)ctx->in;
  98793. count = 56;
  98794. }
  98795. memset(p, 0, count);
  98796. byteSwap(ctx->in, 14);
  98797. /* Append length in bits and transform */
  98798. ctx->in[14] = ctx->bytes[0] << 3;
  98799. ctx->in[15] = ctx->bytes[1] << 3 | ctx->bytes[0] >> 29;
  98800. FLAC__MD5Transform(ctx->buf, ctx->in);
  98801. byteSwap(ctx->buf, 4);
  98802. memcpy(digest, ctx->buf, 16);
  98803. memset(ctx, 0, sizeof(ctx)); /* In case it's sensitive */
  98804. if(0 != ctx->internal_buf) {
  98805. free(ctx->internal_buf);
  98806. ctx->internal_buf = 0;
  98807. ctx->capacity = 0;
  98808. }
  98809. }
  98810. /*
  98811. * Convert the incoming audio signal to a byte stream
  98812. */
  98813. static void format_input_(FLAC__byte *buf, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  98814. {
  98815. unsigned channel, sample;
  98816. register FLAC__int32 a_word;
  98817. register FLAC__byte *buf_ = buf;
  98818. #if WORDS_BIGENDIAN
  98819. #else
  98820. if(channels == 2 && bytes_per_sample == 2) {
  98821. FLAC__int16 *buf1_ = ((FLAC__int16*)buf_) + 1;
  98822. memcpy(buf_, signal[0], sizeof(FLAC__int32) * samples);
  98823. for(sample = 0; sample < samples; sample++, buf1_+=2)
  98824. *buf1_ = (FLAC__int16)signal[1][sample];
  98825. }
  98826. else if(channels == 1 && bytes_per_sample == 2) {
  98827. FLAC__int16 *buf1_ = (FLAC__int16*)buf_;
  98828. for(sample = 0; sample < samples; sample++)
  98829. *buf1_++ = (FLAC__int16)signal[0][sample];
  98830. }
  98831. else
  98832. #endif
  98833. if(bytes_per_sample == 2) {
  98834. if(channels == 2) {
  98835. for(sample = 0; sample < samples; sample++) {
  98836. a_word = signal[0][sample];
  98837. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98838. *buf_++ = (FLAC__byte)a_word;
  98839. a_word = signal[1][sample];
  98840. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98841. *buf_++ = (FLAC__byte)a_word;
  98842. }
  98843. }
  98844. else if(channels == 1) {
  98845. for(sample = 0; sample < samples; sample++) {
  98846. a_word = signal[0][sample];
  98847. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98848. *buf_++ = (FLAC__byte)a_word;
  98849. }
  98850. }
  98851. else {
  98852. for(sample = 0; sample < samples; sample++) {
  98853. for(channel = 0; channel < channels; channel++) {
  98854. a_word = signal[channel][sample];
  98855. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98856. *buf_++ = (FLAC__byte)a_word;
  98857. }
  98858. }
  98859. }
  98860. }
  98861. else if(bytes_per_sample == 3) {
  98862. if(channels == 2) {
  98863. for(sample = 0; sample < samples; sample++) {
  98864. a_word = signal[0][sample];
  98865. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98866. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98867. *buf_++ = (FLAC__byte)a_word;
  98868. a_word = signal[1][sample];
  98869. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98870. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98871. *buf_++ = (FLAC__byte)a_word;
  98872. }
  98873. }
  98874. else if(channels == 1) {
  98875. for(sample = 0; sample < samples; sample++) {
  98876. a_word = signal[0][sample];
  98877. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98878. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98879. *buf_++ = (FLAC__byte)a_word;
  98880. }
  98881. }
  98882. else {
  98883. for(sample = 0; sample < samples; sample++) {
  98884. for(channel = 0; channel < channels; channel++) {
  98885. a_word = signal[channel][sample];
  98886. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98887. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98888. *buf_++ = (FLAC__byte)a_word;
  98889. }
  98890. }
  98891. }
  98892. }
  98893. else if(bytes_per_sample == 1) {
  98894. if(channels == 2) {
  98895. for(sample = 0; sample < samples; sample++) {
  98896. a_word = signal[0][sample];
  98897. *buf_++ = (FLAC__byte)a_word;
  98898. a_word = signal[1][sample];
  98899. *buf_++ = (FLAC__byte)a_word;
  98900. }
  98901. }
  98902. else if(channels == 1) {
  98903. for(sample = 0; sample < samples; sample++) {
  98904. a_word = signal[0][sample];
  98905. *buf_++ = (FLAC__byte)a_word;
  98906. }
  98907. }
  98908. else {
  98909. for(sample = 0; sample < samples; sample++) {
  98910. for(channel = 0; channel < channels; channel++) {
  98911. a_word = signal[channel][sample];
  98912. *buf_++ = (FLAC__byte)a_word;
  98913. }
  98914. }
  98915. }
  98916. }
  98917. else { /* bytes_per_sample == 4, maybe optimize more later */
  98918. for(sample = 0; sample < samples; sample++) {
  98919. for(channel = 0; channel < channels; channel++) {
  98920. a_word = signal[channel][sample];
  98921. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98922. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98923. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98924. *buf_++ = (FLAC__byte)a_word;
  98925. }
  98926. }
  98927. }
  98928. }
  98929. /*
  98930. * Convert the incoming audio signal to a byte stream and FLAC__MD5Update it.
  98931. */
  98932. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  98933. {
  98934. const size_t bytes_needed = (size_t)channels * (size_t)samples * (size_t)bytes_per_sample;
  98935. /* overflow check */
  98936. if((size_t)channels > SIZE_MAX / (size_t)bytes_per_sample)
  98937. return false;
  98938. if((size_t)channels * (size_t)bytes_per_sample > SIZE_MAX / (size_t)samples)
  98939. return false;
  98940. if(ctx->capacity < bytes_needed) {
  98941. FLAC__byte *tmp = (FLAC__byte*)realloc(ctx->internal_buf, bytes_needed);
  98942. if(0 == tmp) {
  98943. free(ctx->internal_buf);
  98944. if(0 == (ctx->internal_buf = (FLAC__byte*)safe_malloc_(bytes_needed)))
  98945. return false;
  98946. }
  98947. ctx->internal_buf = tmp;
  98948. ctx->capacity = bytes_needed;
  98949. }
  98950. format_input_(ctx->internal_buf, signal, channels, samples, bytes_per_sample);
  98951. FLAC__MD5Update(ctx, ctx->internal_buf, bytes_needed);
  98952. return true;
  98953. }
  98954. #endif
  98955. /*** End of inlined file: md5.c ***/
  98956. /*** Start of inlined file: memory.c ***/
  98957. /*** Start of inlined file: juce_FlacHeader.h ***/
  98958. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  98959. // tasks..
  98960. #define VERSION "1.2.1"
  98961. #define FLAC__NO_DLL 1
  98962. #if JUCE_MSVC
  98963. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  98964. #endif
  98965. #if JUCE_MAC
  98966. #define FLAC__SYS_DARWIN 1
  98967. #endif
  98968. /*** End of inlined file: juce_FlacHeader.h ***/
  98969. #if JUCE_USE_FLAC
  98970. #if HAVE_CONFIG_H
  98971. # include <config.h>
  98972. #endif
  98973. /*** Start of inlined file: memory.h ***/
  98974. #ifndef FLAC__PRIVATE__MEMORY_H
  98975. #define FLAC__PRIVATE__MEMORY_H
  98976. #ifdef HAVE_CONFIG_H
  98977. #include <config.h>
  98978. #endif
  98979. #include <stdlib.h> /* for size_t */
  98980. /* Returns the unaligned address returned by malloc.
  98981. * Use free() on this address to deallocate.
  98982. */
  98983. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address);
  98984. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer);
  98985. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer);
  98986. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer);
  98987. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer);
  98988. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98989. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer);
  98990. #endif
  98991. #endif
  98992. /*** End of inlined file: memory.h ***/
  98993. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address)
  98994. {
  98995. void *x;
  98996. FLAC__ASSERT(0 != aligned_address);
  98997. #ifdef FLAC__ALIGN_MALLOC_DATA
  98998. /* align on 32-byte (256-bit) boundary */
  98999. x = safe_malloc_add_2op_(bytes, /*+*/31);
  99000. #ifdef SIZEOF_VOIDP
  99001. #if SIZEOF_VOIDP == 4
  99002. /* could do *aligned_address = x + ((unsigned) (32 - (((unsigned)x) & 31))) & 31; */
  99003. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  99004. #elif SIZEOF_VOIDP == 8
  99005. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  99006. #else
  99007. # error Unsupported sizeof(void*)
  99008. #endif
  99009. #else
  99010. /* there's got to be a better way to do this right for all archs */
  99011. if(sizeof(void*) == sizeof(unsigned))
  99012. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  99013. else if(sizeof(void*) == sizeof(FLAC__uint64))
  99014. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  99015. else
  99016. return 0;
  99017. #endif
  99018. #else
  99019. x = safe_malloc_(bytes);
  99020. *aligned_address = x;
  99021. #endif
  99022. return x;
  99023. }
  99024. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer)
  99025. {
  99026. FLAC__int32 *pu; /* unaligned pointer */
  99027. union { /* union needed to comply with C99 pointer aliasing rules */
  99028. FLAC__int32 *pa; /* aligned pointer */
  99029. void *pv; /* aligned pointer alias */
  99030. } u;
  99031. FLAC__ASSERT(elements > 0);
  99032. FLAC__ASSERT(0 != unaligned_pointer);
  99033. FLAC__ASSERT(0 != aligned_pointer);
  99034. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  99035. pu = (FLAC__int32*)FLAC__memory_alloc_aligned(sizeof(*pu) * (size_t)elements, &u.pv);
  99036. if(0 == pu) {
  99037. return false;
  99038. }
  99039. else {
  99040. if(*unaligned_pointer != 0)
  99041. free(*unaligned_pointer);
  99042. *unaligned_pointer = pu;
  99043. *aligned_pointer = u.pa;
  99044. return true;
  99045. }
  99046. }
  99047. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer)
  99048. {
  99049. FLAC__uint32 *pu; /* unaligned pointer */
  99050. union { /* union needed to comply with C99 pointer aliasing rules */
  99051. FLAC__uint32 *pa; /* aligned pointer */
  99052. void *pv; /* aligned pointer alias */
  99053. } u;
  99054. FLAC__ASSERT(elements > 0);
  99055. FLAC__ASSERT(0 != unaligned_pointer);
  99056. FLAC__ASSERT(0 != aligned_pointer);
  99057. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  99058. pu = (FLAC__uint32*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  99059. if(0 == pu) {
  99060. return false;
  99061. }
  99062. else {
  99063. if(*unaligned_pointer != 0)
  99064. free(*unaligned_pointer);
  99065. *unaligned_pointer = pu;
  99066. *aligned_pointer = u.pa;
  99067. return true;
  99068. }
  99069. }
  99070. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer)
  99071. {
  99072. FLAC__uint64 *pu; /* unaligned pointer */
  99073. union { /* union needed to comply with C99 pointer aliasing rules */
  99074. FLAC__uint64 *pa; /* aligned pointer */
  99075. void *pv; /* aligned pointer alias */
  99076. } u;
  99077. FLAC__ASSERT(elements > 0);
  99078. FLAC__ASSERT(0 != unaligned_pointer);
  99079. FLAC__ASSERT(0 != aligned_pointer);
  99080. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  99081. pu = (FLAC__uint64*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  99082. if(0 == pu) {
  99083. return false;
  99084. }
  99085. else {
  99086. if(*unaligned_pointer != 0)
  99087. free(*unaligned_pointer);
  99088. *unaligned_pointer = pu;
  99089. *aligned_pointer = u.pa;
  99090. return true;
  99091. }
  99092. }
  99093. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer)
  99094. {
  99095. unsigned *pu; /* unaligned pointer */
  99096. union { /* union needed to comply with C99 pointer aliasing rules */
  99097. unsigned *pa; /* aligned pointer */
  99098. void *pv; /* aligned pointer alias */
  99099. } u;
  99100. FLAC__ASSERT(elements > 0);
  99101. FLAC__ASSERT(0 != unaligned_pointer);
  99102. FLAC__ASSERT(0 != aligned_pointer);
  99103. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  99104. pu = (unsigned*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  99105. if(0 == pu) {
  99106. return false;
  99107. }
  99108. else {
  99109. if(*unaligned_pointer != 0)
  99110. free(*unaligned_pointer);
  99111. *unaligned_pointer = pu;
  99112. *aligned_pointer = u.pa;
  99113. return true;
  99114. }
  99115. }
  99116. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99117. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer)
  99118. {
  99119. FLAC__real *pu; /* unaligned pointer */
  99120. union { /* union needed to comply with C99 pointer aliasing rules */
  99121. FLAC__real *pa; /* aligned pointer */
  99122. void *pv; /* aligned pointer alias */
  99123. } u;
  99124. FLAC__ASSERT(elements > 0);
  99125. FLAC__ASSERT(0 != unaligned_pointer);
  99126. FLAC__ASSERT(0 != aligned_pointer);
  99127. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  99128. pu = (FLAC__real*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  99129. if(0 == pu) {
  99130. return false;
  99131. }
  99132. else {
  99133. if(*unaligned_pointer != 0)
  99134. free(*unaligned_pointer);
  99135. *unaligned_pointer = pu;
  99136. *aligned_pointer = u.pa;
  99137. return true;
  99138. }
  99139. }
  99140. #endif
  99141. #endif
  99142. /*** End of inlined file: memory.c ***/
  99143. /*** Start of inlined file: stream_decoder.c ***/
  99144. /*** Start of inlined file: juce_FlacHeader.h ***/
  99145. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  99146. // tasks..
  99147. #define VERSION "1.2.1"
  99148. #define FLAC__NO_DLL 1
  99149. #if JUCE_MSVC
  99150. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  99151. #endif
  99152. #if JUCE_MAC
  99153. #define FLAC__SYS_DARWIN 1
  99154. #endif
  99155. /*** End of inlined file: juce_FlacHeader.h ***/
  99156. #if JUCE_USE_FLAC
  99157. #if HAVE_CONFIG_H
  99158. # include <config.h>
  99159. #endif
  99160. #if defined _MSC_VER || defined __MINGW32__
  99161. #include <io.h> /* for _setmode() */
  99162. #include <fcntl.h> /* for _O_BINARY */
  99163. #endif
  99164. #if defined __CYGWIN__ || defined __EMX__
  99165. #include <io.h> /* for setmode(), O_BINARY */
  99166. #include <fcntl.h> /* for _O_BINARY */
  99167. #endif
  99168. #include <stdio.h>
  99169. #include <stdlib.h> /* for malloc() */
  99170. #include <string.h> /* for memset/memcpy() */
  99171. #include <sys/stat.h> /* for stat() */
  99172. #include <sys/types.h> /* for off_t */
  99173. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  99174. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  99175. #define fseeko fseek
  99176. #define ftello ftell
  99177. #endif
  99178. #endif
  99179. /*** Start of inlined file: stream_decoder.h ***/
  99180. #ifndef FLAC__PROTECTED__STREAM_DECODER_H
  99181. #define FLAC__PROTECTED__STREAM_DECODER_H
  99182. #if FLAC__HAS_OGG
  99183. #include "include/private/ogg_decoder_aspect.h"
  99184. #endif
  99185. typedef struct FLAC__StreamDecoderProtected {
  99186. FLAC__StreamDecoderState state;
  99187. unsigned channels;
  99188. FLAC__ChannelAssignment channel_assignment;
  99189. unsigned bits_per_sample;
  99190. unsigned sample_rate; /* in Hz */
  99191. unsigned blocksize; /* in samples (per channel) */
  99192. FLAC__bool md5_checking; /* if true, generate MD5 signature of decoded data and compare against signature in the STREAMINFO metadata block */
  99193. #if FLAC__HAS_OGG
  99194. FLAC__OggDecoderAspect ogg_decoder_aspect;
  99195. #endif
  99196. } FLAC__StreamDecoderProtected;
  99197. /*
  99198. * return the number of input bytes consumed
  99199. */
  99200. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder);
  99201. #endif
  99202. /*** End of inlined file: stream_decoder.h ***/
  99203. #ifdef max
  99204. #undef max
  99205. #endif
  99206. #define max(a,b) ((a)>(b)?(a):(b))
  99207. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  99208. #ifdef _MSC_VER
  99209. #define FLAC__U64L(x) x
  99210. #else
  99211. #define FLAC__U64L(x) x##LLU
  99212. #endif
  99213. /* technically this should be in an "export.c" but this is convenient enough */
  99214. FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC =
  99215. #if FLAC__HAS_OGG
  99216. 1
  99217. #else
  99218. 0
  99219. #endif
  99220. ;
  99221. /***********************************************************************
  99222. *
  99223. * Private static data
  99224. *
  99225. ***********************************************************************/
  99226. static FLAC__byte ID3V2_TAG_[3] = { 'I', 'D', '3' };
  99227. /***********************************************************************
  99228. *
  99229. * Private class method prototypes
  99230. *
  99231. ***********************************************************************/
  99232. static void set_defaults_dec(FLAC__StreamDecoder *decoder);
  99233. static FILE *get_binary_stdin_(void);
  99234. static FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels);
  99235. static FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id);
  99236. static FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder);
  99237. static FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder);
  99238. static FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  99239. static FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  99240. static FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj);
  99241. static FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj);
  99242. static FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj);
  99243. static FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder);
  99244. static FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder);
  99245. static FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode);
  99246. static FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder);
  99247. static FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  99248. static FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  99249. static FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  99250. static FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  99251. static FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  99252. 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);
  99253. static FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder);
  99254. static FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data);
  99255. #if FLAC__HAS_OGG
  99256. static FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes);
  99257. static FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  99258. #endif
  99259. static FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[]);
  99260. static void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status);
  99261. static FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  99262. #if FLAC__HAS_OGG
  99263. static FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  99264. #endif
  99265. static FLAC__StreamDecoderReadStatus file_read_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  99266. static FLAC__StreamDecoderSeekStatus file_seek_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  99267. static FLAC__StreamDecoderTellStatus file_tell_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  99268. static FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  99269. static FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data);
  99270. /***********************************************************************
  99271. *
  99272. * Private class data
  99273. *
  99274. ***********************************************************************/
  99275. typedef struct FLAC__StreamDecoderPrivate {
  99276. #if FLAC__HAS_OGG
  99277. FLAC__bool is_ogg;
  99278. #endif
  99279. FLAC__StreamDecoderReadCallback read_callback;
  99280. FLAC__StreamDecoderSeekCallback seek_callback;
  99281. FLAC__StreamDecoderTellCallback tell_callback;
  99282. FLAC__StreamDecoderLengthCallback length_callback;
  99283. FLAC__StreamDecoderEofCallback eof_callback;
  99284. FLAC__StreamDecoderWriteCallback write_callback;
  99285. FLAC__StreamDecoderMetadataCallback metadata_callback;
  99286. FLAC__StreamDecoderErrorCallback error_callback;
  99287. /* generic 32-bit datapath: */
  99288. 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[]);
  99289. /* generic 64-bit datapath: */
  99290. 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[]);
  99291. /* for use when the signal is <= 16 bits-per-sample, or <= 15 bits-per-sample on a side channel (which requires 1 extra bit): */
  99292. 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[]);
  99293. /* 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: */
  99294. 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[]);
  99295. FLAC__bool (*local_bitreader_read_rice_signed_block)(FLAC__BitReader *br, int* vals, unsigned nvals, unsigned parameter);
  99296. void *client_data;
  99297. FILE *file; /* only used if FLAC__stream_decoder_init_file()/FLAC__stream_decoder_init_file() called, else NULL */
  99298. FLAC__BitReader *input;
  99299. FLAC__int32 *output[FLAC__MAX_CHANNELS];
  99300. FLAC__int32 *residual[FLAC__MAX_CHANNELS]; /* WATCHOUT: these are the aligned pointers; the real pointers that should be free()'d are residual_unaligned[] below */
  99301. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents[FLAC__MAX_CHANNELS];
  99302. unsigned output_capacity, output_channels;
  99303. FLAC__uint32 fixed_block_size, next_fixed_block_size;
  99304. FLAC__uint64 samples_decoded;
  99305. FLAC__bool has_stream_info, has_seek_table;
  99306. FLAC__StreamMetadata stream_info;
  99307. FLAC__StreamMetadata seek_table;
  99308. FLAC__bool metadata_filter[128]; /* MAGIC number 128 == total number of metadata block types == 1 << 7 */
  99309. FLAC__byte *metadata_filter_ids;
  99310. size_t metadata_filter_ids_count, metadata_filter_ids_capacity; /* units for both are IDs, not bytes */
  99311. FLAC__Frame frame;
  99312. FLAC__bool cached; /* true if there is a byte in lookahead */
  99313. FLAC__CPUInfo cpuinfo;
  99314. FLAC__byte header_warmup[2]; /* contains the sync code and reserved bits */
  99315. FLAC__byte lookahead; /* temp storage when we need to look ahead one byte in the stream */
  99316. /* unaligned (original) pointers to allocated data */
  99317. FLAC__int32 *residual_unaligned[FLAC__MAX_CHANNELS];
  99318. 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 */
  99319. FLAC__bool internal_reset_hack; /* used only during init() so we can call reset to set up the decoder without rewinding the input */
  99320. FLAC__bool is_seeking;
  99321. FLAC__MD5Context md5context;
  99322. FLAC__byte computed_md5sum[16]; /* this is the sum we computed from the decoded data */
  99323. /* (the rest of these are only used for seeking) */
  99324. FLAC__Frame last_frame; /* holds the info of the last frame we seeked to */
  99325. FLAC__uint64 first_frame_offset; /* hint to the seek routine of where in the stream the first audio frame starts */
  99326. FLAC__uint64 target_sample;
  99327. unsigned unparseable_frame_count; /* used to tell whether we're decoding a future version of FLAC or just got a bad sync */
  99328. #if FLAC__HAS_OGG
  99329. FLAC__bool got_a_frame; /* hack needed in Ogg FLAC seek routine to check when process_single() actually writes a frame */
  99330. #endif
  99331. } FLAC__StreamDecoderPrivate;
  99332. /***********************************************************************
  99333. *
  99334. * Public static class data
  99335. *
  99336. ***********************************************************************/
  99337. FLAC_API const char * const FLAC__StreamDecoderStateString[] = {
  99338. "FLAC__STREAM_DECODER_SEARCH_FOR_METADATA",
  99339. "FLAC__STREAM_DECODER_READ_METADATA",
  99340. "FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC",
  99341. "FLAC__STREAM_DECODER_READ_FRAME",
  99342. "FLAC__STREAM_DECODER_END_OF_STREAM",
  99343. "FLAC__STREAM_DECODER_OGG_ERROR",
  99344. "FLAC__STREAM_DECODER_SEEK_ERROR",
  99345. "FLAC__STREAM_DECODER_ABORTED",
  99346. "FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR",
  99347. "FLAC__STREAM_DECODER_UNINITIALIZED"
  99348. };
  99349. FLAC_API const char * const FLAC__StreamDecoderInitStatusString[] = {
  99350. "FLAC__STREAM_DECODER_INIT_STATUS_OK",
  99351. "FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  99352. "FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS",
  99353. "FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR",
  99354. "FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE",
  99355. "FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED"
  99356. };
  99357. FLAC_API const char * const FLAC__StreamDecoderReadStatusString[] = {
  99358. "FLAC__STREAM_DECODER_READ_STATUS_CONTINUE",
  99359. "FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM",
  99360. "FLAC__STREAM_DECODER_READ_STATUS_ABORT"
  99361. };
  99362. FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[] = {
  99363. "FLAC__STREAM_DECODER_SEEK_STATUS_OK",
  99364. "FLAC__STREAM_DECODER_SEEK_STATUS_ERROR",
  99365. "FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED"
  99366. };
  99367. FLAC_API const char * const FLAC__StreamDecoderTellStatusString[] = {
  99368. "FLAC__STREAM_DECODER_TELL_STATUS_OK",
  99369. "FLAC__STREAM_DECODER_TELL_STATUS_ERROR",
  99370. "FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED"
  99371. };
  99372. FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[] = {
  99373. "FLAC__STREAM_DECODER_LENGTH_STATUS_OK",
  99374. "FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR",
  99375. "FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED"
  99376. };
  99377. FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[] = {
  99378. "FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE",
  99379. "FLAC__STREAM_DECODER_WRITE_STATUS_ABORT"
  99380. };
  99381. FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[] = {
  99382. "FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC",
  99383. "FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER",
  99384. "FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH",
  99385. "FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM"
  99386. };
  99387. /***********************************************************************
  99388. *
  99389. * Class constructor/destructor
  99390. *
  99391. ***********************************************************************/
  99392. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void)
  99393. {
  99394. FLAC__StreamDecoder *decoder;
  99395. unsigned i;
  99396. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  99397. decoder = (FLAC__StreamDecoder*)calloc(1, sizeof(FLAC__StreamDecoder));
  99398. if(decoder == 0) {
  99399. return 0;
  99400. }
  99401. decoder->protected_ = (FLAC__StreamDecoderProtected*)calloc(1, sizeof(FLAC__StreamDecoderProtected));
  99402. if(decoder->protected_ == 0) {
  99403. free(decoder);
  99404. return 0;
  99405. }
  99406. decoder->private_ = (FLAC__StreamDecoderPrivate*)calloc(1, sizeof(FLAC__StreamDecoderPrivate));
  99407. if(decoder->private_ == 0) {
  99408. free(decoder->protected_);
  99409. free(decoder);
  99410. return 0;
  99411. }
  99412. decoder->private_->input = FLAC__bitreader_new();
  99413. if(decoder->private_->input == 0) {
  99414. free(decoder->private_);
  99415. free(decoder->protected_);
  99416. free(decoder);
  99417. return 0;
  99418. }
  99419. decoder->private_->metadata_filter_ids_capacity = 16;
  99420. if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)malloc((FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) * decoder->private_->metadata_filter_ids_capacity))) {
  99421. FLAC__bitreader_delete(decoder->private_->input);
  99422. free(decoder->private_);
  99423. free(decoder->protected_);
  99424. free(decoder);
  99425. return 0;
  99426. }
  99427. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99428. decoder->private_->output[i] = 0;
  99429. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  99430. }
  99431. decoder->private_->output_capacity = 0;
  99432. decoder->private_->output_channels = 0;
  99433. decoder->private_->has_seek_table = false;
  99434. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  99435. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&decoder->private_->partitioned_rice_contents[i]);
  99436. decoder->private_->file = 0;
  99437. set_defaults_dec(decoder);
  99438. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  99439. return decoder;
  99440. }
  99441. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder)
  99442. {
  99443. unsigned i;
  99444. FLAC__ASSERT(0 != decoder);
  99445. FLAC__ASSERT(0 != decoder->protected_);
  99446. FLAC__ASSERT(0 != decoder->private_);
  99447. FLAC__ASSERT(0 != decoder->private_->input);
  99448. (void)FLAC__stream_decoder_finish(decoder);
  99449. if(0 != decoder->private_->metadata_filter_ids)
  99450. free(decoder->private_->metadata_filter_ids);
  99451. FLAC__bitreader_delete(decoder->private_->input);
  99452. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  99453. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&decoder->private_->partitioned_rice_contents[i]);
  99454. free(decoder->private_);
  99455. free(decoder->protected_);
  99456. free(decoder);
  99457. }
  99458. /***********************************************************************
  99459. *
  99460. * Public class methods
  99461. *
  99462. ***********************************************************************/
  99463. static FLAC__StreamDecoderInitStatus init_stream_internal_dec(
  99464. FLAC__StreamDecoder *decoder,
  99465. FLAC__StreamDecoderReadCallback read_callback,
  99466. FLAC__StreamDecoderSeekCallback seek_callback,
  99467. FLAC__StreamDecoderTellCallback tell_callback,
  99468. FLAC__StreamDecoderLengthCallback length_callback,
  99469. FLAC__StreamDecoderEofCallback eof_callback,
  99470. FLAC__StreamDecoderWriteCallback write_callback,
  99471. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99472. FLAC__StreamDecoderErrorCallback error_callback,
  99473. void *client_data,
  99474. FLAC__bool is_ogg
  99475. )
  99476. {
  99477. FLAC__ASSERT(0 != decoder);
  99478. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99479. return FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
  99480. #if !FLAC__HAS_OGG
  99481. if(is_ogg)
  99482. return FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  99483. #endif
  99484. if(
  99485. 0 == read_callback ||
  99486. 0 == write_callback ||
  99487. 0 == error_callback ||
  99488. (seek_callback && (0 == tell_callback || 0 == length_callback || 0 == eof_callback))
  99489. )
  99490. return FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
  99491. #if FLAC__HAS_OGG
  99492. decoder->private_->is_ogg = is_ogg;
  99493. if(is_ogg && !FLAC__ogg_decoder_aspect_init(&decoder->protected_->ogg_decoder_aspect))
  99494. return decoder->protected_->state = FLAC__STREAM_DECODER_OGG_ERROR;
  99495. #endif
  99496. /*
  99497. * get the CPU info and set the function pointers
  99498. */
  99499. FLAC__cpu_info(&decoder->private_->cpuinfo);
  99500. /* first default to the non-asm routines */
  99501. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal;
  99502. decoder->private_->local_lpc_restore_signal_64bit = FLAC__lpc_restore_signal_wide;
  99503. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal;
  99504. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal;
  99505. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block;
  99506. /* now override with asm where appropriate */
  99507. #ifndef FLAC__NO_ASM
  99508. if(decoder->private_->cpuinfo.use_asm) {
  99509. #ifdef FLAC__CPU_IA32
  99510. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  99511. #ifdef FLAC__HAS_NASM
  99512. #if 1 /*@@@@@@ OPT: not clearly faster, needs more testing */
  99513. if(decoder->private_->cpuinfo.data.ia32.bswap)
  99514. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap;
  99515. #endif
  99516. if(decoder->private_->cpuinfo.data.ia32.mmx) {
  99517. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  99518. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32_mmx;
  99519. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32_mmx;
  99520. }
  99521. else {
  99522. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  99523. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32;
  99524. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32;
  99525. }
  99526. #endif
  99527. #elif defined FLAC__CPU_PPC
  99528. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_PPC);
  99529. if(decoder->private_->cpuinfo.data.ppc.altivec) {
  99530. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ppc_altivec_16;
  99531. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ppc_altivec_16_order8;
  99532. }
  99533. #endif
  99534. }
  99535. #endif
  99536. /* from here on, errors are fatal */
  99537. if(!FLAC__bitreader_init(decoder->private_->input, decoder->private_->cpuinfo, read_callback_, decoder)) {
  99538. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99539. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  99540. }
  99541. decoder->private_->read_callback = read_callback;
  99542. decoder->private_->seek_callback = seek_callback;
  99543. decoder->private_->tell_callback = tell_callback;
  99544. decoder->private_->length_callback = length_callback;
  99545. decoder->private_->eof_callback = eof_callback;
  99546. decoder->private_->write_callback = write_callback;
  99547. decoder->private_->metadata_callback = metadata_callback;
  99548. decoder->private_->error_callback = error_callback;
  99549. decoder->private_->client_data = client_data;
  99550. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  99551. decoder->private_->samples_decoded = 0;
  99552. decoder->private_->has_stream_info = false;
  99553. decoder->private_->cached = false;
  99554. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  99555. decoder->private_->is_seeking = false;
  99556. decoder->private_->internal_reset_hack = true; /* so the following reset does not try to rewind the input */
  99557. if(!FLAC__stream_decoder_reset(decoder)) {
  99558. /* above call sets the state for us */
  99559. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  99560. }
  99561. return FLAC__STREAM_DECODER_INIT_STATUS_OK;
  99562. }
  99563. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  99564. FLAC__StreamDecoder *decoder,
  99565. FLAC__StreamDecoderReadCallback read_callback,
  99566. FLAC__StreamDecoderSeekCallback seek_callback,
  99567. FLAC__StreamDecoderTellCallback tell_callback,
  99568. FLAC__StreamDecoderLengthCallback length_callback,
  99569. FLAC__StreamDecoderEofCallback eof_callback,
  99570. FLAC__StreamDecoderWriteCallback write_callback,
  99571. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99572. FLAC__StreamDecoderErrorCallback error_callback,
  99573. void *client_data
  99574. )
  99575. {
  99576. return init_stream_internal_dec(
  99577. decoder,
  99578. read_callback,
  99579. seek_callback,
  99580. tell_callback,
  99581. length_callback,
  99582. eof_callback,
  99583. write_callback,
  99584. metadata_callback,
  99585. error_callback,
  99586. client_data,
  99587. /*is_ogg=*/false
  99588. );
  99589. }
  99590. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  99591. FLAC__StreamDecoder *decoder,
  99592. FLAC__StreamDecoderReadCallback read_callback,
  99593. FLAC__StreamDecoderSeekCallback seek_callback,
  99594. FLAC__StreamDecoderTellCallback tell_callback,
  99595. FLAC__StreamDecoderLengthCallback length_callback,
  99596. FLAC__StreamDecoderEofCallback eof_callback,
  99597. FLAC__StreamDecoderWriteCallback write_callback,
  99598. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99599. FLAC__StreamDecoderErrorCallback error_callback,
  99600. void *client_data
  99601. )
  99602. {
  99603. return init_stream_internal_dec(
  99604. decoder,
  99605. read_callback,
  99606. seek_callback,
  99607. tell_callback,
  99608. length_callback,
  99609. eof_callback,
  99610. write_callback,
  99611. metadata_callback,
  99612. error_callback,
  99613. client_data,
  99614. /*is_ogg=*/true
  99615. );
  99616. }
  99617. static FLAC__StreamDecoderInitStatus init_FILE_internal_(
  99618. FLAC__StreamDecoder *decoder,
  99619. FILE *file,
  99620. FLAC__StreamDecoderWriteCallback write_callback,
  99621. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99622. FLAC__StreamDecoderErrorCallback error_callback,
  99623. void *client_data,
  99624. FLAC__bool is_ogg
  99625. )
  99626. {
  99627. FLAC__ASSERT(0 != decoder);
  99628. FLAC__ASSERT(0 != file);
  99629. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99630. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  99631. if(0 == write_callback || 0 == error_callback)
  99632. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  99633. /*
  99634. * To make sure that our file does not go unclosed after an error, we
  99635. * must assign the FILE pointer before any further error can occur in
  99636. * this routine.
  99637. */
  99638. if(file == stdin)
  99639. file = get_binary_stdin_(); /* just to be safe */
  99640. decoder->private_->file = file;
  99641. return init_stream_internal_dec(
  99642. decoder,
  99643. file_read_callback_dec,
  99644. decoder->private_->file == stdin? 0: file_seek_callback_dec,
  99645. decoder->private_->file == stdin? 0: file_tell_callback_dec,
  99646. decoder->private_->file == stdin? 0: file_length_callback_,
  99647. file_eof_callback_,
  99648. write_callback,
  99649. metadata_callback,
  99650. error_callback,
  99651. client_data,
  99652. is_ogg
  99653. );
  99654. }
  99655. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  99656. FLAC__StreamDecoder *decoder,
  99657. FILE *file,
  99658. FLAC__StreamDecoderWriteCallback write_callback,
  99659. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99660. FLAC__StreamDecoderErrorCallback error_callback,
  99661. void *client_data
  99662. )
  99663. {
  99664. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  99665. }
  99666. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  99667. FLAC__StreamDecoder *decoder,
  99668. FILE *file,
  99669. FLAC__StreamDecoderWriteCallback write_callback,
  99670. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99671. FLAC__StreamDecoderErrorCallback error_callback,
  99672. void *client_data
  99673. )
  99674. {
  99675. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  99676. }
  99677. static FLAC__StreamDecoderInitStatus init_file_internal_(
  99678. FLAC__StreamDecoder *decoder,
  99679. const char *filename,
  99680. FLAC__StreamDecoderWriteCallback write_callback,
  99681. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99682. FLAC__StreamDecoderErrorCallback error_callback,
  99683. void *client_data,
  99684. FLAC__bool is_ogg
  99685. )
  99686. {
  99687. FILE *file;
  99688. FLAC__ASSERT(0 != decoder);
  99689. /*
  99690. * To make sure that our file does not go unclosed after an error, we
  99691. * have to do the same entrance checks here that are later performed
  99692. * in FLAC__stream_decoder_init_FILE() before the FILE* is assigned.
  99693. */
  99694. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99695. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  99696. if(0 == write_callback || 0 == error_callback)
  99697. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  99698. file = filename? fopen(filename, "rb") : stdin;
  99699. if(0 == file)
  99700. return FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE;
  99701. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, is_ogg);
  99702. }
  99703. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  99704. FLAC__StreamDecoder *decoder,
  99705. const char *filename,
  99706. FLAC__StreamDecoderWriteCallback write_callback,
  99707. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99708. FLAC__StreamDecoderErrorCallback error_callback,
  99709. void *client_data
  99710. )
  99711. {
  99712. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  99713. }
  99714. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  99715. FLAC__StreamDecoder *decoder,
  99716. const char *filename,
  99717. FLAC__StreamDecoderWriteCallback write_callback,
  99718. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99719. FLAC__StreamDecoderErrorCallback error_callback,
  99720. void *client_data
  99721. )
  99722. {
  99723. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  99724. }
  99725. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder)
  99726. {
  99727. FLAC__bool md5_failed = false;
  99728. unsigned i;
  99729. FLAC__ASSERT(0 != decoder);
  99730. FLAC__ASSERT(0 != decoder->private_);
  99731. FLAC__ASSERT(0 != decoder->protected_);
  99732. if(decoder->protected_->state == FLAC__STREAM_DECODER_UNINITIALIZED)
  99733. return true;
  99734. /* see the comment in FLAC__seekable_stream_decoder_reset() as to why we
  99735. * always call FLAC__MD5Final()
  99736. */
  99737. FLAC__MD5Final(decoder->private_->computed_md5sum, &decoder->private_->md5context);
  99738. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  99739. free(decoder->private_->seek_table.data.seek_table.points);
  99740. decoder->private_->seek_table.data.seek_table.points = 0;
  99741. decoder->private_->has_seek_table = false;
  99742. }
  99743. FLAC__bitreader_free(decoder->private_->input);
  99744. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99745. /* WATCHOUT:
  99746. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  99747. * output arrays have a buffer of up to 3 zeroes in front
  99748. * (at negative indices) for alignment purposes; we use 4
  99749. * to keep the data well-aligned.
  99750. */
  99751. if(0 != decoder->private_->output[i]) {
  99752. free(decoder->private_->output[i]-4);
  99753. decoder->private_->output[i] = 0;
  99754. }
  99755. if(0 != decoder->private_->residual_unaligned[i]) {
  99756. free(decoder->private_->residual_unaligned[i]);
  99757. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  99758. }
  99759. }
  99760. decoder->private_->output_capacity = 0;
  99761. decoder->private_->output_channels = 0;
  99762. #if FLAC__HAS_OGG
  99763. if(decoder->private_->is_ogg)
  99764. FLAC__ogg_decoder_aspect_finish(&decoder->protected_->ogg_decoder_aspect);
  99765. #endif
  99766. if(0 != decoder->private_->file) {
  99767. if(decoder->private_->file != stdin)
  99768. fclose(decoder->private_->file);
  99769. decoder->private_->file = 0;
  99770. }
  99771. if(decoder->private_->do_md5_checking) {
  99772. if(memcmp(decoder->private_->stream_info.data.stream_info.md5sum, decoder->private_->computed_md5sum, 16))
  99773. md5_failed = true;
  99774. }
  99775. decoder->private_->is_seeking = false;
  99776. set_defaults_dec(decoder);
  99777. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  99778. return !md5_failed;
  99779. }
  99780. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long value)
  99781. {
  99782. FLAC__ASSERT(0 != decoder);
  99783. FLAC__ASSERT(0 != decoder->private_);
  99784. FLAC__ASSERT(0 != decoder->protected_);
  99785. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99786. return false;
  99787. #if FLAC__HAS_OGG
  99788. /* can't check decoder->private_->is_ogg since that's not set until init time */
  99789. FLAC__ogg_decoder_aspect_set_serial_number(&decoder->protected_->ogg_decoder_aspect, value);
  99790. return true;
  99791. #else
  99792. (void)value;
  99793. return false;
  99794. #endif
  99795. }
  99796. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value)
  99797. {
  99798. FLAC__ASSERT(0 != decoder);
  99799. FLAC__ASSERT(0 != decoder->protected_);
  99800. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99801. return false;
  99802. decoder->protected_->md5_checking = value;
  99803. return true;
  99804. }
  99805. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  99806. {
  99807. FLAC__ASSERT(0 != decoder);
  99808. FLAC__ASSERT(0 != decoder->private_);
  99809. FLAC__ASSERT(0 != decoder->protected_);
  99810. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  99811. /* double protection */
  99812. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  99813. return false;
  99814. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99815. return false;
  99816. decoder->private_->metadata_filter[type] = true;
  99817. if(type == FLAC__METADATA_TYPE_APPLICATION)
  99818. decoder->private_->metadata_filter_ids_count = 0;
  99819. return true;
  99820. }
  99821. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  99822. {
  99823. FLAC__ASSERT(0 != decoder);
  99824. FLAC__ASSERT(0 != decoder->private_);
  99825. FLAC__ASSERT(0 != decoder->protected_);
  99826. FLAC__ASSERT(0 != id);
  99827. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99828. return false;
  99829. if(decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  99830. return true;
  99831. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  99832. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  99833. 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))) {
  99834. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99835. return false;
  99836. }
  99837. decoder->private_->metadata_filter_ids_capacity *= 2;
  99838. }
  99839. 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));
  99840. decoder->private_->metadata_filter_ids_count++;
  99841. return true;
  99842. }
  99843. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder)
  99844. {
  99845. unsigned i;
  99846. FLAC__ASSERT(0 != decoder);
  99847. FLAC__ASSERT(0 != decoder->private_);
  99848. FLAC__ASSERT(0 != decoder->protected_);
  99849. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99850. return false;
  99851. for(i = 0; i < sizeof(decoder->private_->metadata_filter) / sizeof(decoder->private_->metadata_filter[0]); i++)
  99852. decoder->private_->metadata_filter[i] = true;
  99853. decoder->private_->metadata_filter_ids_count = 0;
  99854. return true;
  99855. }
  99856. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  99857. {
  99858. FLAC__ASSERT(0 != decoder);
  99859. FLAC__ASSERT(0 != decoder->private_);
  99860. FLAC__ASSERT(0 != decoder->protected_);
  99861. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  99862. /* double protection */
  99863. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  99864. return false;
  99865. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99866. return false;
  99867. decoder->private_->metadata_filter[type] = false;
  99868. if(type == FLAC__METADATA_TYPE_APPLICATION)
  99869. decoder->private_->metadata_filter_ids_count = 0;
  99870. return true;
  99871. }
  99872. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  99873. {
  99874. FLAC__ASSERT(0 != decoder);
  99875. FLAC__ASSERT(0 != decoder->private_);
  99876. FLAC__ASSERT(0 != decoder->protected_);
  99877. FLAC__ASSERT(0 != id);
  99878. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99879. return false;
  99880. if(!decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  99881. return true;
  99882. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  99883. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  99884. 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))) {
  99885. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99886. return false;
  99887. }
  99888. decoder->private_->metadata_filter_ids_capacity *= 2;
  99889. }
  99890. 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));
  99891. decoder->private_->metadata_filter_ids_count++;
  99892. return true;
  99893. }
  99894. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder)
  99895. {
  99896. FLAC__ASSERT(0 != decoder);
  99897. FLAC__ASSERT(0 != decoder->private_);
  99898. FLAC__ASSERT(0 != decoder->protected_);
  99899. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99900. return false;
  99901. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  99902. decoder->private_->metadata_filter_ids_count = 0;
  99903. return true;
  99904. }
  99905. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder)
  99906. {
  99907. FLAC__ASSERT(0 != decoder);
  99908. FLAC__ASSERT(0 != decoder->protected_);
  99909. return decoder->protected_->state;
  99910. }
  99911. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder)
  99912. {
  99913. return FLAC__StreamDecoderStateString[decoder->protected_->state];
  99914. }
  99915. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder)
  99916. {
  99917. FLAC__ASSERT(0 != decoder);
  99918. FLAC__ASSERT(0 != decoder->protected_);
  99919. return decoder->protected_->md5_checking;
  99920. }
  99921. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder)
  99922. {
  99923. FLAC__ASSERT(0 != decoder);
  99924. FLAC__ASSERT(0 != decoder->protected_);
  99925. return decoder->private_->has_stream_info? decoder->private_->stream_info.data.stream_info.total_samples : 0;
  99926. }
  99927. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder)
  99928. {
  99929. FLAC__ASSERT(0 != decoder);
  99930. FLAC__ASSERT(0 != decoder->protected_);
  99931. return decoder->protected_->channels;
  99932. }
  99933. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder)
  99934. {
  99935. FLAC__ASSERT(0 != decoder);
  99936. FLAC__ASSERT(0 != decoder->protected_);
  99937. return decoder->protected_->channel_assignment;
  99938. }
  99939. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder)
  99940. {
  99941. FLAC__ASSERT(0 != decoder);
  99942. FLAC__ASSERT(0 != decoder->protected_);
  99943. return decoder->protected_->bits_per_sample;
  99944. }
  99945. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder)
  99946. {
  99947. FLAC__ASSERT(0 != decoder);
  99948. FLAC__ASSERT(0 != decoder->protected_);
  99949. return decoder->protected_->sample_rate;
  99950. }
  99951. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder)
  99952. {
  99953. FLAC__ASSERT(0 != decoder);
  99954. FLAC__ASSERT(0 != decoder->protected_);
  99955. return decoder->protected_->blocksize;
  99956. }
  99957. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position)
  99958. {
  99959. FLAC__ASSERT(0 != decoder);
  99960. FLAC__ASSERT(0 != decoder->private_);
  99961. FLAC__ASSERT(0 != position);
  99962. #if FLAC__HAS_OGG
  99963. if(decoder->private_->is_ogg)
  99964. return false;
  99965. #endif
  99966. if(0 == decoder->private_->tell_callback)
  99967. return false;
  99968. if(decoder->private_->tell_callback(decoder, position, decoder->private_->client_data) != FLAC__STREAM_DECODER_TELL_STATUS_OK)
  99969. return false;
  99970. /* should never happen since all FLAC frames and metadata blocks are byte aligned, but check just in case */
  99971. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input))
  99972. return false;
  99973. FLAC__ASSERT(*position >= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder));
  99974. *position -= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder);
  99975. return true;
  99976. }
  99977. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder)
  99978. {
  99979. FLAC__ASSERT(0 != decoder);
  99980. FLAC__ASSERT(0 != decoder->private_);
  99981. FLAC__ASSERT(0 != decoder->protected_);
  99982. decoder->private_->samples_decoded = 0;
  99983. decoder->private_->do_md5_checking = false;
  99984. #if FLAC__HAS_OGG
  99985. if(decoder->private_->is_ogg)
  99986. FLAC__ogg_decoder_aspect_flush(&decoder->protected_->ogg_decoder_aspect);
  99987. #endif
  99988. if(!FLAC__bitreader_clear(decoder->private_->input)) {
  99989. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99990. return false;
  99991. }
  99992. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  99993. return true;
  99994. }
  99995. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder)
  99996. {
  99997. FLAC__ASSERT(0 != decoder);
  99998. FLAC__ASSERT(0 != decoder->private_);
  99999. FLAC__ASSERT(0 != decoder->protected_);
  100000. if(!FLAC__stream_decoder_flush(decoder)) {
  100001. /* above call sets the state for us */
  100002. return false;
  100003. }
  100004. #if FLAC__HAS_OGG
  100005. /*@@@ could go in !internal_reset_hack block below */
  100006. if(decoder->private_->is_ogg)
  100007. FLAC__ogg_decoder_aspect_reset(&decoder->protected_->ogg_decoder_aspect);
  100008. #endif
  100009. /* Rewind if necessary. If FLAC__stream_decoder_init() is calling us,
  100010. * (internal_reset_hack) don't try to rewind since we are already at
  100011. * the beginning of the stream and don't want to fail if the input is
  100012. * not seekable.
  100013. */
  100014. if(!decoder->private_->internal_reset_hack) {
  100015. if(decoder->private_->file == stdin)
  100016. return false; /* can't rewind stdin, reset fails */
  100017. if(decoder->private_->seek_callback && decoder->private_->seek_callback(decoder, 0, decoder->private_->client_data) == FLAC__STREAM_DECODER_SEEK_STATUS_ERROR)
  100018. return false; /* seekable and seek fails, reset fails */
  100019. }
  100020. else
  100021. decoder->private_->internal_reset_hack = false;
  100022. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_METADATA;
  100023. decoder->private_->has_stream_info = false;
  100024. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  100025. free(decoder->private_->seek_table.data.seek_table.points);
  100026. decoder->private_->seek_table.data.seek_table.points = 0;
  100027. decoder->private_->has_seek_table = false;
  100028. }
  100029. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  100030. /*
  100031. * This goes in reset() and not flush() because according to the spec, a
  100032. * fixed-blocksize stream must stay that way through the whole stream.
  100033. */
  100034. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  100035. /* We initialize the FLAC__MD5Context even though we may never use it. This
  100036. * is because md5 checking may be turned on to start and then turned off if
  100037. * a seek occurs. So we init the context here and finalize it in
  100038. * FLAC__stream_decoder_finish() to make sure things are always cleaned up
  100039. * properly.
  100040. */
  100041. FLAC__MD5Init(&decoder->private_->md5context);
  100042. decoder->private_->first_frame_offset = 0;
  100043. decoder->private_->unparseable_frame_count = 0;
  100044. return true;
  100045. }
  100046. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder)
  100047. {
  100048. FLAC__bool got_a_frame;
  100049. FLAC__ASSERT(0 != decoder);
  100050. FLAC__ASSERT(0 != decoder->protected_);
  100051. while(1) {
  100052. switch(decoder->protected_->state) {
  100053. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  100054. if(!find_metadata_(decoder))
  100055. return false; /* above function sets the status for us */
  100056. break;
  100057. case FLAC__STREAM_DECODER_READ_METADATA:
  100058. if(!read_metadata_(decoder))
  100059. return false; /* above function sets the status for us */
  100060. else
  100061. return true;
  100062. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  100063. if(!frame_sync_(decoder))
  100064. return true; /* above function sets the status for us */
  100065. break;
  100066. case FLAC__STREAM_DECODER_READ_FRAME:
  100067. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/true))
  100068. return false; /* above function sets the status for us */
  100069. if(got_a_frame)
  100070. return true; /* above function sets the status for us */
  100071. break;
  100072. case FLAC__STREAM_DECODER_END_OF_STREAM:
  100073. case FLAC__STREAM_DECODER_ABORTED:
  100074. return true;
  100075. default:
  100076. FLAC__ASSERT(0);
  100077. return false;
  100078. }
  100079. }
  100080. }
  100081. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder)
  100082. {
  100083. FLAC__ASSERT(0 != decoder);
  100084. FLAC__ASSERT(0 != decoder->protected_);
  100085. while(1) {
  100086. switch(decoder->protected_->state) {
  100087. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  100088. if(!find_metadata_(decoder))
  100089. return false; /* above function sets the status for us */
  100090. break;
  100091. case FLAC__STREAM_DECODER_READ_METADATA:
  100092. if(!read_metadata_(decoder))
  100093. return false; /* above function sets the status for us */
  100094. break;
  100095. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  100096. case FLAC__STREAM_DECODER_READ_FRAME:
  100097. case FLAC__STREAM_DECODER_END_OF_STREAM:
  100098. case FLAC__STREAM_DECODER_ABORTED:
  100099. return true;
  100100. default:
  100101. FLAC__ASSERT(0);
  100102. return false;
  100103. }
  100104. }
  100105. }
  100106. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder)
  100107. {
  100108. FLAC__bool dummy;
  100109. FLAC__ASSERT(0 != decoder);
  100110. FLAC__ASSERT(0 != decoder->protected_);
  100111. while(1) {
  100112. switch(decoder->protected_->state) {
  100113. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  100114. if(!find_metadata_(decoder))
  100115. return false; /* above function sets the status for us */
  100116. break;
  100117. case FLAC__STREAM_DECODER_READ_METADATA:
  100118. if(!read_metadata_(decoder))
  100119. return false; /* above function sets the status for us */
  100120. break;
  100121. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  100122. if(!frame_sync_(decoder))
  100123. return true; /* above function sets the status for us */
  100124. break;
  100125. case FLAC__STREAM_DECODER_READ_FRAME:
  100126. if(!read_frame_(decoder, &dummy, /*do_full_decode=*/true))
  100127. return false; /* above function sets the status for us */
  100128. break;
  100129. case FLAC__STREAM_DECODER_END_OF_STREAM:
  100130. case FLAC__STREAM_DECODER_ABORTED:
  100131. return true;
  100132. default:
  100133. FLAC__ASSERT(0);
  100134. return false;
  100135. }
  100136. }
  100137. }
  100138. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder)
  100139. {
  100140. FLAC__bool got_a_frame;
  100141. FLAC__ASSERT(0 != decoder);
  100142. FLAC__ASSERT(0 != decoder->protected_);
  100143. while(1) {
  100144. switch(decoder->protected_->state) {
  100145. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  100146. case FLAC__STREAM_DECODER_READ_METADATA:
  100147. return false; /* above function sets the status for us */
  100148. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  100149. if(!frame_sync_(decoder))
  100150. return true; /* above function sets the status for us */
  100151. break;
  100152. case FLAC__STREAM_DECODER_READ_FRAME:
  100153. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/false))
  100154. return false; /* above function sets the status for us */
  100155. if(got_a_frame)
  100156. return true; /* above function sets the status for us */
  100157. break;
  100158. case FLAC__STREAM_DECODER_END_OF_STREAM:
  100159. case FLAC__STREAM_DECODER_ABORTED:
  100160. return true;
  100161. default:
  100162. FLAC__ASSERT(0);
  100163. return false;
  100164. }
  100165. }
  100166. }
  100167. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample)
  100168. {
  100169. FLAC__uint64 length;
  100170. FLAC__ASSERT(0 != decoder);
  100171. if(
  100172. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA &&
  100173. decoder->protected_->state != FLAC__STREAM_DECODER_READ_METADATA &&
  100174. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC &&
  100175. decoder->protected_->state != FLAC__STREAM_DECODER_READ_FRAME &&
  100176. decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM
  100177. )
  100178. return false;
  100179. if(0 == decoder->private_->seek_callback)
  100180. return false;
  100181. FLAC__ASSERT(decoder->private_->seek_callback);
  100182. FLAC__ASSERT(decoder->private_->tell_callback);
  100183. FLAC__ASSERT(decoder->private_->length_callback);
  100184. FLAC__ASSERT(decoder->private_->eof_callback);
  100185. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder))
  100186. return false;
  100187. decoder->private_->is_seeking = true;
  100188. /* turn off md5 checking if a seek is attempted */
  100189. decoder->private_->do_md5_checking = false;
  100190. /* 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) */
  100191. if(decoder->private_->length_callback(decoder, &length, decoder->private_->client_data) != FLAC__STREAM_DECODER_LENGTH_STATUS_OK) {
  100192. decoder->private_->is_seeking = false;
  100193. return false;
  100194. }
  100195. /* if we haven't finished processing the metadata yet, do that so we have the STREAMINFO, SEEK_TABLE, and first_frame_offset */
  100196. if(
  100197. decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_METADATA ||
  100198. decoder->protected_->state == FLAC__STREAM_DECODER_READ_METADATA
  100199. ) {
  100200. if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder)) {
  100201. /* above call sets the state for us */
  100202. decoder->private_->is_seeking = false;
  100203. return false;
  100204. }
  100205. /* check this again in case we didn't know total_samples the first time */
  100206. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder)) {
  100207. decoder->private_->is_seeking = false;
  100208. return false;
  100209. }
  100210. }
  100211. {
  100212. const FLAC__bool ok =
  100213. #if FLAC__HAS_OGG
  100214. decoder->private_->is_ogg?
  100215. seek_to_absolute_sample_ogg_(decoder, length, sample) :
  100216. #endif
  100217. seek_to_absolute_sample_(decoder, length, sample)
  100218. ;
  100219. decoder->private_->is_seeking = false;
  100220. return ok;
  100221. }
  100222. }
  100223. /***********************************************************************
  100224. *
  100225. * Protected class methods
  100226. *
  100227. ***********************************************************************/
  100228. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder)
  100229. {
  100230. FLAC__ASSERT(0 != decoder);
  100231. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100232. FLAC__ASSERT(!(FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) & 7));
  100233. return FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) / 8;
  100234. }
  100235. /***********************************************************************
  100236. *
  100237. * Private class methods
  100238. *
  100239. ***********************************************************************/
  100240. void set_defaults_dec(FLAC__StreamDecoder *decoder)
  100241. {
  100242. #if FLAC__HAS_OGG
  100243. decoder->private_->is_ogg = false;
  100244. #endif
  100245. decoder->private_->read_callback = 0;
  100246. decoder->private_->seek_callback = 0;
  100247. decoder->private_->tell_callback = 0;
  100248. decoder->private_->length_callback = 0;
  100249. decoder->private_->eof_callback = 0;
  100250. decoder->private_->write_callback = 0;
  100251. decoder->private_->metadata_callback = 0;
  100252. decoder->private_->error_callback = 0;
  100253. decoder->private_->client_data = 0;
  100254. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  100255. decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] = true;
  100256. decoder->private_->metadata_filter_ids_count = 0;
  100257. decoder->protected_->md5_checking = false;
  100258. #if FLAC__HAS_OGG
  100259. FLAC__ogg_decoder_aspect_set_defaults(&decoder->protected_->ogg_decoder_aspect);
  100260. #endif
  100261. }
  100262. /*
  100263. * This will forcibly set stdin to binary mode (for OSes that require it)
  100264. */
  100265. FILE *get_binary_stdin_(void)
  100266. {
  100267. /* if something breaks here it is probably due to the presence or
  100268. * absence of an underscore before the identifiers 'setmode',
  100269. * 'fileno', and/or 'O_BINARY'; check your system header files.
  100270. */
  100271. #if defined _MSC_VER || defined __MINGW32__
  100272. _setmode(_fileno(stdin), _O_BINARY);
  100273. #elif defined __CYGWIN__
  100274. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  100275. setmode(_fileno(stdin), _O_BINARY);
  100276. #elif defined __EMX__
  100277. setmode(fileno(stdin), O_BINARY);
  100278. #endif
  100279. return stdin;
  100280. }
  100281. FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels)
  100282. {
  100283. unsigned i;
  100284. FLAC__int32 *tmp;
  100285. if(size <= decoder->private_->output_capacity && channels <= decoder->private_->output_channels)
  100286. return true;
  100287. /* simply using realloc() is not practical because the number of channels may change mid-stream */
  100288. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  100289. if(0 != decoder->private_->output[i]) {
  100290. free(decoder->private_->output[i]-4);
  100291. decoder->private_->output[i] = 0;
  100292. }
  100293. if(0 != decoder->private_->residual_unaligned[i]) {
  100294. free(decoder->private_->residual_unaligned[i]);
  100295. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  100296. }
  100297. }
  100298. for(i = 0; i < channels; i++) {
  100299. /* WATCHOUT:
  100300. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  100301. * output arrays have a buffer of up to 3 zeroes in front
  100302. * (at negative indices) for alignment purposes; we use 4
  100303. * to keep the data well-aligned.
  100304. */
  100305. tmp = (FLAC__int32*)safe_malloc_muladd2_(sizeof(FLAC__int32), /*times (*/size, /*+*/4/*)*/);
  100306. if(tmp == 0) {
  100307. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100308. return false;
  100309. }
  100310. memset(tmp, 0, sizeof(FLAC__int32)*4);
  100311. decoder->private_->output[i] = tmp + 4;
  100312. /* WATCHOUT:
  100313. * minimum of quadword alignment for PPC vector optimizations is REQUIRED:
  100314. */
  100315. if(!FLAC__memory_alloc_aligned_int32_array(size, &decoder->private_->residual_unaligned[i], &decoder->private_->residual[i])) {
  100316. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100317. return false;
  100318. }
  100319. }
  100320. decoder->private_->output_capacity = size;
  100321. decoder->private_->output_channels = channels;
  100322. return true;
  100323. }
  100324. FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id)
  100325. {
  100326. size_t i;
  100327. FLAC__ASSERT(0 != decoder);
  100328. FLAC__ASSERT(0 != decoder->private_);
  100329. for(i = 0; i < decoder->private_->metadata_filter_ids_count; i++)
  100330. if(0 == memcmp(decoder->private_->metadata_filter_ids + i * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8)))
  100331. return true;
  100332. return false;
  100333. }
  100334. FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder)
  100335. {
  100336. FLAC__uint32 x;
  100337. unsigned i, id_;
  100338. FLAC__bool first = true;
  100339. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100340. for(i = id_ = 0; i < 4; ) {
  100341. if(decoder->private_->cached) {
  100342. x = (FLAC__uint32)decoder->private_->lookahead;
  100343. decoder->private_->cached = false;
  100344. }
  100345. else {
  100346. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100347. return false; /* read_callback_ sets the state for us */
  100348. }
  100349. if(x == FLAC__STREAM_SYNC_STRING[i]) {
  100350. first = true;
  100351. i++;
  100352. id_ = 0;
  100353. continue;
  100354. }
  100355. if(x == ID3V2_TAG_[id_]) {
  100356. id_++;
  100357. i = 0;
  100358. if(id_ == 3) {
  100359. if(!skip_id3v2_tag_(decoder))
  100360. return false; /* skip_id3v2_tag_ sets the state for us */
  100361. }
  100362. continue;
  100363. }
  100364. id_ = 0;
  100365. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100366. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  100367. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100368. return false; /* read_callback_ sets the state for us */
  100369. /* 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 */
  100370. /* else we have to check if the second byte is the end of a sync code */
  100371. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100372. decoder->private_->lookahead = (FLAC__byte)x;
  100373. decoder->private_->cached = true;
  100374. }
  100375. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  100376. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  100377. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  100378. return true;
  100379. }
  100380. }
  100381. i = 0;
  100382. if(first) {
  100383. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100384. first = false;
  100385. }
  100386. }
  100387. decoder->protected_->state = FLAC__STREAM_DECODER_READ_METADATA;
  100388. return true;
  100389. }
  100390. FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder)
  100391. {
  100392. FLAC__bool is_last;
  100393. FLAC__uint32 i, x, type, length;
  100394. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100395. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_IS_LAST_LEN))
  100396. return false; /* read_callback_ sets the state for us */
  100397. is_last = x? true : false;
  100398. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &type, FLAC__STREAM_METADATA_TYPE_LEN))
  100399. return false; /* read_callback_ sets the state for us */
  100400. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &length, FLAC__STREAM_METADATA_LENGTH_LEN))
  100401. return false; /* read_callback_ sets the state for us */
  100402. if(type == FLAC__METADATA_TYPE_STREAMINFO) {
  100403. if(!read_metadata_streaminfo_(decoder, is_last, length))
  100404. return false;
  100405. decoder->private_->has_stream_info = true;
  100406. 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))
  100407. decoder->private_->do_md5_checking = false;
  100408. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] && decoder->private_->metadata_callback)
  100409. decoder->private_->metadata_callback(decoder, &decoder->private_->stream_info, decoder->private_->client_data);
  100410. }
  100411. else if(type == FLAC__METADATA_TYPE_SEEKTABLE) {
  100412. if(!read_metadata_seektable_(decoder, is_last, length))
  100413. return false;
  100414. decoder->private_->has_seek_table = true;
  100415. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_SEEKTABLE] && decoder->private_->metadata_callback)
  100416. decoder->private_->metadata_callback(decoder, &decoder->private_->seek_table, decoder->private_->client_data);
  100417. }
  100418. else {
  100419. FLAC__bool skip_it = !decoder->private_->metadata_filter[type];
  100420. unsigned real_length = length;
  100421. FLAC__StreamMetadata block;
  100422. block.is_last = is_last;
  100423. block.type = (FLAC__MetadataType)type;
  100424. block.length = length;
  100425. if(type == FLAC__METADATA_TYPE_APPLICATION) {
  100426. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8))
  100427. return false; /* read_callback_ sets the state for us */
  100428. if(real_length < FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) { /* underflow check */
  100429. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;/*@@@@@@ maybe wrong error? need to resync?*/
  100430. return false;
  100431. }
  100432. real_length -= FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8;
  100433. if(decoder->private_->metadata_filter_ids_count > 0 && has_id_filtered_(decoder, block.data.application.id))
  100434. skip_it = !skip_it;
  100435. }
  100436. if(skip_it) {
  100437. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  100438. return false; /* read_callback_ sets the state for us */
  100439. }
  100440. else {
  100441. switch(type) {
  100442. case FLAC__METADATA_TYPE_PADDING:
  100443. /* skip the padding bytes */
  100444. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  100445. return false; /* read_callback_ sets the state for us */
  100446. break;
  100447. case FLAC__METADATA_TYPE_APPLICATION:
  100448. /* remember, we read the ID already */
  100449. if(real_length > 0) {
  100450. if(0 == (block.data.application.data = (FLAC__byte*)malloc(real_length))) {
  100451. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100452. return false;
  100453. }
  100454. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.data, real_length))
  100455. return false; /* read_callback_ sets the state for us */
  100456. }
  100457. else
  100458. block.data.application.data = 0;
  100459. break;
  100460. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  100461. if(!read_metadata_vorbiscomment_(decoder, &block.data.vorbis_comment))
  100462. return false;
  100463. break;
  100464. case FLAC__METADATA_TYPE_CUESHEET:
  100465. if(!read_metadata_cuesheet_(decoder, &block.data.cue_sheet))
  100466. return false;
  100467. break;
  100468. case FLAC__METADATA_TYPE_PICTURE:
  100469. if(!read_metadata_picture_(decoder, &block.data.picture))
  100470. return false;
  100471. break;
  100472. case FLAC__METADATA_TYPE_STREAMINFO:
  100473. case FLAC__METADATA_TYPE_SEEKTABLE:
  100474. FLAC__ASSERT(0);
  100475. break;
  100476. default:
  100477. if(real_length > 0) {
  100478. if(0 == (block.data.unknown.data = (FLAC__byte*)malloc(real_length))) {
  100479. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100480. return false;
  100481. }
  100482. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.unknown.data, real_length))
  100483. return false; /* read_callback_ sets the state for us */
  100484. }
  100485. else
  100486. block.data.unknown.data = 0;
  100487. break;
  100488. }
  100489. if(!decoder->private_->is_seeking && decoder->private_->metadata_callback)
  100490. decoder->private_->metadata_callback(decoder, &block, decoder->private_->client_data);
  100491. /* now we have to free any malloc()ed data in the block */
  100492. switch(type) {
  100493. case FLAC__METADATA_TYPE_PADDING:
  100494. break;
  100495. case FLAC__METADATA_TYPE_APPLICATION:
  100496. if(0 != block.data.application.data)
  100497. free(block.data.application.data);
  100498. break;
  100499. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  100500. if(0 != block.data.vorbis_comment.vendor_string.entry)
  100501. free(block.data.vorbis_comment.vendor_string.entry);
  100502. if(block.data.vorbis_comment.num_comments > 0)
  100503. for(i = 0; i < block.data.vorbis_comment.num_comments; i++)
  100504. if(0 != block.data.vorbis_comment.comments[i].entry)
  100505. free(block.data.vorbis_comment.comments[i].entry);
  100506. if(0 != block.data.vorbis_comment.comments)
  100507. free(block.data.vorbis_comment.comments);
  100508. break;
  100509. case FLAC__METADATA_TYPE_CUESHEET:
  100510. if(block.data.cue_sheet.num_tracks > 0)
  100511. for(i = 0; i < block.data.cue_sheet.num_tracks; i++)
  100512. if(0 != block.data.cue_sheet.tracks[i].indices)
  100513. free(block.data.cue_sheet.tracks[i].indices);
  100514. if(0 != block.data.cue_sheet.tracks)
  100515. free(block.data.cue_sheet.tracks);
  100516. break;
  100517. case FLAC__METADATA_TYPE_PICTURE:
  100518. if(0 != block.data.picture.mime_type)
  100519. free(block.data.picture.mime_type);
  100520. if(0 != block.data.picture.description)
  100521. free(block.data.picture.description);
  100522. if(0 != block.data.picture.data)
  100523. free(block.data.picture.data);
  100524. break;
  100525. case FLAC__METADATA_TYPE_STREAMINFO:
  100526. case FLAC__METADATA_TYPE_SEEKTABLE:
  100527. FLAC__ASSERT(0);
  100528. default:
  100529. if(0 != block.data.unknown.data)
  100530. free(block.data.unknown.data);
  100531. break;
  100532. }
  100533. }
  100534. }
  100535. if(is_last) {
  100536. /* if this fails, it's OK, it's just a hint for the seek routine */
  100537. if(!FLAC__stream_decoder_get_decode_position(decoder, &decoder->private_->first_frame_offset))
  100538. decoder->private_->first_frame_offset = 0;
  100539. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100540. }
  100541. return true;
  100542. }
  100543. FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  100544. {
  100545. FLAC__uint32 x;
  100546. unsigned bits, used_bits = 0;
  100547. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100548. decoder->private_->stream_info.type = FLAC__METADATA_TYPE_STREAMINFO;
  100549. decoder->private_->stream_info.is_last = is_last;
  100550. decoder->private_->stream_info.length = length;
  100551. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN;
  100552. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, bits))
  100553. return false; /* read_callback_ sets the state for us */
  100554. decoder->private_->stream_info.data.stream_info.min_blocksize = x;
  100555. used_bits += bits;
  100556. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN;
  100557. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  100558. return false; /* read_callback_ sets the state for us */
  100559. decoder->private_->stream_info.data.stream_info.max_blocksize = x;
  100560. used_bits += bits;
  100561. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN;
  100562. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  100563. return false; /* read_callback_ sets the state for us */
  100564. decoder->private_->stream_info.data.stream_info.min_framesize = x;
  100565. used_bits += bits;
  100566. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN;
  100567. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  100568. return false; /* read_callback_ sets the state for us */
  100569. decoder->private_->stream_info.data.stream_info.max_framesize = x;
  100570. used_bits += bits;
  100571. bits = FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN;
  100572. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  100573. return false; /* read_callback_ sets the state for us */
  100574. decoder->private_->stream_info.data.stream_info.sample_rate = x;
  100575. used_bits += bits;
  100576. bits = FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN;
  100577. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  100578. return false; /* read_callback_ sets the state for us */
  100579. decoder->private_->stream_info.data.stream_info.channels = x+1;
  100580. used_bits += bits;
  100581. bits = FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN;
  100582. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  100583. return false; /* read_callback_ sets the state for us */
  100584. decoder->private_->stream_info.data.stream_info.bits_per_sample = x+1;
  100585. used_bits += bits;
  100586. bits = FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN;
  100587. 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))
  100588. return false; /* read_callback_ sets the state for us */
  100589. used_bits += bits;
  100590. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, decoder->private_->stream_info.data.stream_info.md5sum, 16))
  100591. return false; /* read_callback_ sets the state for us */
  100592. used_bits += 16*8;
  100593. /* skip the rest of the block */
  100594. FLAC__ASSERT(used_bits % 8 == 0);
  100595. length -= (used_bits / 8);
  100596. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  100597. return false; /* read_callback_ sets the state for us */
  100598. return true;
  100599. }
  100600. FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  100601. {
  100602. FLAC__uint32 i, x;
  100603. FLAC__uint64 xx;
  100604. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100605. decoder->private_->seek_table.type = FLAC__METADATA_TYPE_SEEKTABLE;
  100606. decoder->private_->seek_table.is_last = is_last;
  100607. decoder->private_->seek_table.length = length;
  100608. decoder->private_->seek_table.data.seek_table.num_points = length / FLAC__STREAM_METADATA_SEEKPOINT_LENGTH;
  100609. /* use realloc since we may pass through here several times (e.g. after seeking) */
  100610. 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)))) {
  100611. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100612. return false;
  100613. }
  100614. for(i = 0; i < decoder->private_->seek_table.data.seek_table.num_points; i++) {
  100615. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  100616. return false; /* read_callback_ sets the state for us */
  100617. decoder->private_->seek_table.data.seek_table.points[i].sample_number = xx;
  100618. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  100619. return false; /* read_callback_ sets the state for us */
  100620. decoder->private_->seek_table.data.seek_table.points[i].stream_offset = xx;
  100621. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  100622. return false; /* read_callback_ sets the state for us */
  100623. decoder->private_->seek_table.data.seek_table.points[i].frame_samples = x;
  100624. }
  100625. length -= (decoder->private_->seek_table.data.seek_table.num_points * FLAC__STREAM_METADATA_SEEKPOINT_LENGTH);
  100626. /* if there is a partial point left, skip over it */
  100627. if(length > 0) {
  100628. /*@@@ do a send_error_to_client_() here? there's an argument for either way */
  100629. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  100630. return false; /* read_callback_ sets the state for us */
  100631. }
  100632. return true;
  100633. }
  100634. FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj)
  100635. {
  100636. FLAC__uint32 i;
  100637. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100638. /* read vendor string */
  100639. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  100640. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->vendor_string.length))
  100641. return false; /* read_callback_ sets the state for us */
  100642. if(obj->vendor_string.length > 0) {
  100643. if(0 == (obj->vendor_string.entry = (FLAC__byte*)safe_malloc_add_2op_(obj->vendor_string.length, /*+*/1))) {
  100644. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100645. return false;
  100646. }
  100647. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->vendor_string.entry, obj->vendor_string.length))
  100648. return false; /* read_callback_ sets the state for us */
  100649. obj->vendor_string.entry[obj->vendor_string.length] = '\0';
  100650. }
  100651. else
  100652. obj->vendor_string.entry = 0;
  100653. /* read num comments */
  100654. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN == 32);
  100655. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->num_comments))
  100656. return false; /* read_callback_ sets the state for us */
  100657. /* read comments */
  100658. if(obj->num_comments > 0) {
  100659. if(0 == (obj->comments = (FLAC__StreamMetadata_VorbisComment_Entry*)safe_malloc_mul_2op_(obj->num_comments, /*times*/sizeof(FLAC__StreamMetadata_VorbisComment_Entry)))) {
  100660. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100661. return false;
  100662. }
  100663. for(i = 0; i < obj->num_comments; i++) {
  100664. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  100665. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->comments[i].length))
  100666. return false; /* read_callback_ sets the state for us */
  100667. if(obj->comments[i].length > 0) {
  100668. if(0 == (obj->comments[i].entry = (FLAC__byte*)safe_malloc_add_2op_(obj->comments[i].length, /*+*/1))) {
  100669. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100670. return false;
  100671. }
  100672. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->comments[i].entry, obj->comments[i].length))
  100673. return false; /* read_callback_ sets the state for us */
  100674. obj->comments[i].entry[obj->comments[i].length] = '\0';
  100675. }
  100676. else
  100677. obj->comments[i].entry = 0;
  100678. }
  100679. }
  100680. else {
  100681. obj->comments = 0;
  100682. }
  100683. return true;
  100684. }
  100685. FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj)
  100686. {
  100687. FLAC__uint32 i, j, x;
  100688. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100689. memset(obj, 0, sizeof(FLAC__StreamMetadata_CueSheet));
  100690. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  100691. 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))
  100692. return false; /* read_callback_ sets the state for us */
  100693. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &obj->lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  100694. return false; /* read_callback_ sets the state for us */
  100695. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  100696. return false; /* read_callback_ sets the state for us */
  100697. obj->is_cd = x? true : false;
  100698. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  100699. return false; /* read_callback_ sets the state for us */
  100700. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  100701. return false; /* read_callback_ sets the state for us */
  100702. obj->num_tracks = x;
  100703. if(obj->num_tracks > 0) {
  100704. if(0 == (obj->tracks = (FLAC__StreamMetadata_CueSheet_Track*)safe_calloc_(obj->num_tracks, sizeof(FLAC__StreamMetadata_CueSheet_Track)))) {
  100705. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100706. return false;
  100707. }
  100708. for(i = 0; i < obj->num_tracks; i++) {
  100709. FLAC__StreamMetadata_CueSheet_Track *track = &obj->tracks[i];
  100710. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  100711. return false; /* read_callback_ sets the state for us */
  100712. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  100713. return false; /* read_callback_ sets the state for us */
  100714. track->number = (FLAC__byte)x;
  100715. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  100716. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  100717. return false; /* read_callback_ sets the state for us */
  100718. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  100719. return false; /* read_callback_ sets the state for us */
  100720. track->type = x;
  100721. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  100722. return false; /* read_callback_ sets the state for us */
  100723. track->pre_emphasis = x;
  100724. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  100725. return false; /* read_callback_ sets the state for us */
  100726. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  100727. return false; /* read_callback_ sets the state for us */
  100728. track->num_indices = (FLAC__byte)x;
  100729. if(track->num_indices > 0) {
  100730. if(0 == (track->indices = (FLAC__StreamMetadata_CueSheet_Index*)safe_calloc_(track->num_indices, sizeof(FLAC__StreamMetadata_CueSheet_Index)))) {
  100731. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100732. return false;
  100733. }
  100734. for(j = 0; j < track->num_indices; j++) {
  100735. FLAC__StreamMetadata_CueSheet_Index *index = &track->indices[j];
  100736. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  100737. return false; /* read_callback_ sets the state for us */
  100738. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  100739. return false; /* read_callback_ sets the state for us */
  100740. index->number = (FLAC__byte)x;
  100741. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  100742. return false; /* read_callback_ sets the state for us */
  100743. }
  100744. }
  100745. }
  100746. }
  100747. return true;
  100748. }
  100749. FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj)
  100750. {
  100751. FLAC__uint32 x;
  100752. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100753. /* read type */
  100754. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  100755. return false; /* read_callback_ sets the state for us */
  100756. obj->type = (FLAC__StreamMetadata_Picture_Type) x;
  100757. /* read MIME type */
  100758. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  100759. return false; /* read_callback_ sets the state for us */
  100760. if(0 == (obj->mime_type = (char*)safe_malloc_add_2op_(x, /*+*/1))) {
  100761. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100762. return false;
  100763. }
  100764. if(x > 0) {
  100765. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)obj->mime_type, x))
  100766. return false; /* read_callback_ sets the state for us */
  100767. }
  100768. obj->mime_type[x] = '\0';
  100769. /* read description */
  100770. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  100771. return false; /* read_callback_ sets the state for us */
  100772. if(0 == (obj->description = (FLAC__byte*)safe_malloc_add_2op_(x, /*+*/1))) {
  100773. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100774. return false;
  100775. }
  100776. if(x > 0) {
  100777. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->description, x))
  100778. return false; /* read_callback_ sets the state for us */
  100779. }
  100780. obj->description[x] = '\0';
  100781. /* read width */
  100782. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  100783. return false; /* read_callback_ sets the state for us */
  100784. /* read height */
  100785. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  100786. return false; /* read_callback_ sets the state for us */
  100787. /* read depth */
  100788. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  100789. return false; /* read_callback_ sets the state for us */
  100790. /* read colors */
  100791. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  100792. return false; /* read_callback_ sets the state for us */
  100793. /* read data */
  100794. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &(obj->data_length), FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  100795. return false; /* read_callback_ sets the state for us */
  100796. if(0 == (obj->data = (FLAC__byte*)safe_malloc_(obj->data_length))) {
  100797. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100798. return false;
  100799. }
  100800. if(obj->data_length > 0) {
  100801. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->data, obj->data_length))
  100802. return false; /* read_callback_ sets the state for us */
  100803. }
  100804. return true;
  100805. }
  100806. FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder)
  100807. {
  100808. FLAC__uint32 x;
  100809. unsigned i, skip;
  100810. /* skip the version and flags bytes */
  100811. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 24))
  100812. return false; /* read_callback_ sets the state for us */
  100813. /* get the size (in bytes) to skip */
  100814. skip = 0;
  100815. for(i = 0; i < 4; i++) {
  100816. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100817. return false; /* read_callback_ sets the state for us */
  100818. skip <<= 7;
  100819. skip |= (x & 0x7f);
  100820. }
  100821. /* skip the rest of the tag */
  100822. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, skip))
  100823. return false; /* read_callback_ sets the state for us */
  100824. return true;
  100825. }
  100826. FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder)
  100827. {
  100828. FLAC__uint32 x;
  100829. FLAC__bool first = true;
  100830. /* If we know the total number of samples in the stream, stop if we've read that many. */
  100831. /* This will stop us, for example, from wasting time trying to sync on an ID3V1 tag. */
  100832. if(FLAC__stream_decoder_get_total_samples(decoder) > 0) {
  100833. if(decoder->private_->samples_decoded >= FLAC__stream_decoder_get_total_samples(decoder)) {
  100834. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  100835. return true;
  100836. }
  100837. }
  100838. /* make sure we're byte aligned */
  100839. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  100840. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  100841. return false; /* read_callback_ sets the state for us */
  100842. }
  100843. while(1) {
  100844. if(decoder->private_->cached) {
  100845. x = (FLAC__uint32)decoder->private_->lookahead;
  100846. decoder->private_->cached = false;
  100847. }
  100848. else {
  100849. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100850. return false; /* read_callback_ sets the state for us */
  100851. }
  100852. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100853. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  100854. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100855. return false; /* read_callback_ sets the state for us */
  100856. /* 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 */
  100857. /* else we have to check if the second byte is the end of a sync code */
  100858. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100859. decoder->private_->lookahead = (FLAC__byte)x;
  100860. decoder->private_->cached = true;
  100861. }
  100862. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  100863. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  100864. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  100865. return true;
  100866. }
  100867. }
  100868. if(first) {
  100869. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100870. first = false;
  100871. }
  100872. }
  100873. return true;
  100874. }
  100875. FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode)
  100876. {
  100877. unsigned channel;
  100878. unsigned i;
  100879. FLAC__int32 mid, side;
  100880. unsigned frame_crc; /* the one we calculate from the input stream */
  100881. FLAC__uint32 x;
  100882. *got_a_frame = false;
  100883. /* init the CRC */
  100884. frame_crc = 0;
  100885. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[0], frame_crc);
  100886. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[1], frame_crc);
  100887. FLAC__bitreader_reset_read_crc16(decoder->private_->input, (FLAC__uint16)frame_crc);
  100888. if(!read_frame_header_(decoder))
  100889. return false;
  100890. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means we didn't sync on a valid header */
  100891. return true;
  100892. if(!allocate_output_(decoder, decoder->private_->frame.header.blocksize, decoder->private_->frame.header.channels))
  100893. return false;
  100894. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  100895. /*
  100896. * first figure the correct bits-per-sample of the subframe
  100897. */
  100898. unsigned bps = decoder->private_->frame.header.bits_per_sample;
  100899. switch(decoder->private_->frame.header.channel_assignment) {
  100900. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  100901. /* no adjustment needed */
  100902. break;
  100903. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  100904. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100905. if(channel == 1)
  100906. bps++;
  100907. break;
  100908. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  100909. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100910. if(channel == 0)
  100911. bps++;
  100912. break;
  100913. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  100914. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100915. if(channel == 1)
  100916. bps++;
  100917. break;
  100918. default:
  100919. FLAC__ASSERT(0);
  100920. }
  100921. /*
  100922. * now read it
  100923. */
  100924. if(!read_subframe_(decoder, channel, bps, do_full_decode))
  100925. return false;
  100926. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  100927. return true;
  100928. }
  100929. if(!read_zero_padding_(decoder))
  100930. return false;
  100931. 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) */
  100932. return true;
  100933. /*
  100934. * Read the frame CRC-16 from the footer and check
  100935. */
  100936. frame_crc = FLAC__bitreader_get_read_crc16(decoder->private_->input);
  100937. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__FRAME_FOOTER_CRC_LEN))
  100938. return false; /* read_callback_ sets the state for us */
  100939. if(frame_crc == x) {
  100940. if(do_full_decode) {
  100941. /* Undo any special channel coding */
  100942. switch(decoder->private_->frame.header.channel_assignment) {
  100943. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  100944. /* do nothing */
  100945. break;
  100946. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  100947. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100948. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  100949. decoder->private_->output[1][i] = decoder->private_->output[0][i] - decoder->private_->output[1][i];
  100950. break;
  100951. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  100952. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100953. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  100954. decoder->private_->output[0][i] += decoder->private_->output[1][i];
  100955. break;
  100956. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  100957. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100958. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  100959. #if 1
  100960. mid = decoder->private_->output[0][i];
  100961. side = decoder->private_->output[1][i];
  100962. mid <<= 1;
  100963. mid |= (side & 1); /* i.e. if 'side' is odd... */
  100964. decoder->private_->output[0][i] = (mid + side) >> 1;
  100965. decoder->private_->output[1][i] = (mid - side) >> 1;
  100966. #else
  100967. /* OPT: without 'side' temp variable */
  100968. mid = (decoder->private_->output[0][i] << 1) | (decoder->private_->output[1][i] & 1); /* i.e. if 'side' is odd... */
  100969. decoder->private_->output[0][i] = (mid + decoder->private_->output[1][i]) >> 1;
  100970. decoder->private_->output[1][i] = (mid - decoder->private_->output[1][i]) >> 1;
  100971. #endif
  100972. }
  100973. break;
  100974. default:
  100975. FLAC__ASSERT(0);
  100976. break;
  100977. }
  100978. }
  100979. }
  100980. else {
  100981. /* Bad frame, emit error and zero the output signal */
  100982. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH);
  100983. if(do_full_decode) {
  100984. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  100985. memset(decoder->private_->output[channel], 0, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  100986. }
  100987. }
  100988. }
  100989. *got_a_frame = true;
  100990. /* we wait to update fixed_block_size until here, when we're sure we've got a proper frame and hence a correct blocksize */
  100991. if(decoder->private_->next_fixed_block_size)
  100992. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size;
  100993. /* put the latest values into the public section of the decoder instance */
  100994. decoder->protected_->channels = decoder->private_->frame.header.channels;
  100995. decoder->protected_->channel_assignment = decoder->private_->frame.header.channel_assignment;
  100996. decoder->protected_->bits_per_sample = decoder->private_->frame.header.bits_per_sample;
  100997. decoder->protected_->sample_rate = decoder->private_->frame.header.sample_rate;
  100998. decoder->protected_->blocksize = decoder->private_->frame.header.blocksize;
  100999. FLAC__ASSERT(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101000. decoder->private_->samples_decoded = decoder->private_->frame.header.number.sample_number + decoder->private_->frame.header.blocksize;
  101001. /* write it */
  101002. if(do_full_decode) {
  101003. if(write_audio_frame_to_client_(decoder, &decoder->private_->frame, (const FLAC__int32 * const *)decoder->private_->output) != FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE)
  101004. return false;
  101005. }
  101006. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101007. return true;
  101008. }
  101009. FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder)
  101010. {
  101011. FLAC__uint32 x;
  101012. FLAC__uint64 xx;
  101013. unsigned i, blocksize_hint = 0, sample_rate_hint = 0;
  101014. FLAC__byte crc8, raw_header[16]; /* MAGIC NUMBER based on the maximum frame header size, including CRC */
  101015. unsigned raw_header_len;
  101016. FLAC__bool is_unparseable = false;
  101017. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  101018. /* init the raw header with the saved bits from synchronization */
  101019. raw_header[0] = decoder->private_->header_warmup[0];
  101020. raw_header[1] = decoder->private_->header_warmup[1];
  101021. raw_header_len = 2;
  101022. /* check to make sure that reserved bit is 0 */
  101023. if(raw_header[1] & 0x02) /* MAGIC NUMBER */
  101024. is_unparseable = true;
  101025. /*
  101026. * Note that along the way as we read the header, we look for a sync
  101027. * code inside. If we find one it would indicate that our original
  101028. * sync was bad since there cannot be a sync code in a valid header.
  101029. *
  101030. * Three kinds of things can go wrong when reading the frame header:
  101031. * 1) We may have sync'ed incorrectly and not landed on a frame header.
  101032. * If we don't find a sync code, it can end up looking like we read
  101033. * a valid but unparseable header, until getting to the frame header
  101034. * CRC. Even then we could get a false positive on the CRC.
  101035. * 2) We may have sync'ed correctly but on an unparseable frame (from a
  101036. * future encoder).
  101037. * 3) We may be on a damaged frame which appears valid but unparseable.
  101038. *
  101039. * For all these reasons, we try and read a complete frame header as
  101040. * long as it seems valid, even if unparseable, up until the frame
  101041. * header CRC.
  101042. */
  101043. /*
  101044. * read in the raw header as bytes so we can CRC it, and parse it on the way
  101045. */
  101046. for(i = 0; i < 2; i++) {
  101047. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  101048. return false; /* read_callback_ sets the state for us */
  101049. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  101050. /* if we get here it means our original sync was erroneous since the sync code cannot appear in the header */
  101051. decoder->private_->lookahead = (FLAC__byte)x;
  101052. decoder->private_->cached = true;
  101053. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101054. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101055. return true;
  101056. }
  101057. raw_header[raw_header_len++] = (FLAC__byte)x;
  101058. }
  101059. switch(x = raw_header[2] >> 4) {
  101060. case 0:
  101061. is_unparseable = true;
  101062. break;
  101063. case 1:
  101064. decoder->private_->frame.header.blocksize = 192;
  101065. break;
  101066. case 2:
  101067. case 3:
  101068. case 4:
  101069. case 5:
  101070. decoder->private_->frame.header.blocksize = 576 << (x-2);
  101071. break;
  101072. case 6:
  101073. case 7:
  101074. blocksize_hint = x;
  101075. break;
  101076. case 8:
  101077. case 9:
  101078. case 10:
  101079. case 11:
  101080. case 12:
  101081. case 13:
  101082. case 14:
  101083. case 15:
  101084. decoder->private_->frame.header.blocksize = 256 << (x-8);
  101085. break;
  101086. default:
  101087. FLAC__ASSERT(0);
  101088. break;
  101089. }
  101090. switch(x = raw_header[2] & 0x0f) {
  101091. case 0:
  101092. if(decoder->private_->has_stream_info)
  101093. decoder->private_->frame.header.sample_rate = decoder->private_->stream_info.data.stream_info.sample_rate;
  101094. else
  101095. is_unparseable = true;
  101096. break;
  101097. case 1:
  101098. decoder->private_->frame.header.sample_rate = 88200;
  101099. break;
  101100. case 2:
  101101. decoder->private_->frame.header.sample_rate = 176400;
  101102. break;
  101103. case 3:
  101104. decoder->private_->frame.header.sample_rate = 192000;
  101105. break;
  101106. case 4:
  101107. decoder->private_->frame.header.sample_rate = 8000;
  101108. break;
  101109. case 5:
  101110. decoder->private_->frame.header.sample_rate = 16000;
  101111. break;
  101112. case 6:
  101113. decoder->private_->frame.header.sample_rate = 22050;
  101114. break;
  101115. case 7:
  101116. decoder->private_->frame.header.sample_rate = 24000;
  101117. break;
  101118. case 8:
  101119. decoder->private_->frame.header.sample_rate = 32000;
  101120. break;
  101121. case 9:
  101122. decoder->private_->frame.header.sample_rate = 44100;
  101123. break;
  101124. case 10:
  101125. decoder->private_->frame.header.sample_rate = 48000;
  101126. break;
  101127. case 11:
  101128. decoder->private_->frame.header.sample_rate = 96000;
  101129. break;
  101130. case 12:
  101131. case 13:
  101132. case 14:
  101133. sample_rate_hint = x;
  101134. break;
  101135. case 15:
  101136. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101137. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101138. return true;
  101139. default:
  101140. FLAC__ASSERT(0);
  101141. }
  101142. x = (unsigned)(raw_header[3] >> 4);
  101143. if(x & 8) {
  101144. decoder->private_->frame.header.channels = 2;
  101145. switch(x & 7) {
  101146. case 0:
  101147. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE;
  101148. break;
  101149. case 1:
  101150. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE;
  101151. break;
  101152. case 2:
  101153. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_MID_SIDE;
  101154. break;
  101155. default:
  101156. is_unparseable = true;
  101157. break;
  101158. }
  101159. }
  101160. else {
  101161. decoder->private_->frame.header.channels = (unsigned)x + 1;
  101162. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  101163. }
  101164. switch(x = (unsigned)(raw_header[3] & 0x0e) >> 1) {
  101165. case 0:
  101166. if(decoder->private_->has_stream_info)
  101167. decoder->private_->frame.header.bits_per_sample = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  101168. else
  101169. is_unparseable = true;
  101170. break;
  101171. case 1:
  101172. decoder->private_->frame.header.bits_per_sample = 8;
  101173. break;
  101174. case 2:
  101175. decoder->private_->frame.header.bits_per_sample = 12;
  101176. break;
  101177. case 4:
  101178. decoder->private_->frame.header.bits_per_sample = 16;
  101179. break;
  101180. case 5:
  101181. decoder->private_->frame.header.bits_per_sample = 20;
  101182. break;
  101183. case 6:
  101184. decoder->private_->frame.header.bits_per_sample = 24;
  101185. break;
  101186. case 3:
  101187. case 7:
  101188. is_unparseable = true;
  101189. break;
  101190. default:
  101191. FLAC__ASSERT(0);
  101192. break;
  101193. }
  101194. /* check to make sure that reserved bit is 0 */
  101195. if(raw_header[3] & 0x01) /* MAGIC NUMBER */
  101196. is_unparseable = true;
  101197. /* read the frame's starting sample number (or frame number as the case may be) */
  101198. if(
  101199. raw_header[1] & 0x01 ||
  101200. /*@@@ 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 */
  101201. (decoder->private_->has_stream_info && decoder->private_->stream_info.data.stream_info.min_blocksize != decoder->private_->stream_info.data.stream_info.max_blocksize)
  101202. ) { /* variable blocksize */
  101203. if(!FLAC__bitreader_read_utf8_uint64(decoder->private_->input, &xx, raw_header, &raw_header_len))
  101204. return false; /* read_callback_ sets the state for us */
  101205. if(xx == FLAC__U64L(0xffffffffffffffff)) { /* i.e. non-UTF8 code... */
  101206. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  101207. decoder->private_->cached = true;
  101208. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101209. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101210. return true;
  101211. }
  101212. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  101213. decoder->private_->frame.header.number.sample_number = xx;
  101214. }
  101215. else { /* fixed blocksize */
  101216. if(!FLAC__bitreader_read_utf8_uint32(decoder->private_->input, &x, raw_header, &raw_header_len))
  101217. return false; /* read_callback_ sets the state for us */
  101218. if(x == 0xffffffff) { /* i.e. non-UTF8 code... */
  101219. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  101220. decoder->private_->cached = true;
  101221. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101222. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101223. return true;
  101224. }
  101225. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  101226. decoder->private_->frame.header.number.frame_number = x;
  101227. }
  101228. if(blocksize_hint) {
  101229. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  101230. return false; /* read_callback_ sets the state for us */
  101231. raw_header[raw_header_len++] = (FLAC__byte)x;
  101232. if(blocksize_hint == 7) {
  101233. FLAC__uint32 _x;
  101234. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  101235. return false; /* read_callback_ sets the state for us */
  101236. raw_header[raw_header_len++] = (FLAC__byte)_x;
  101237. x = (x << 8) | _x;
  101238. }
  101239. decoder->private_->frame.header.blocksize = x+1;
  101240. }
  101241. if(sample_rate_hint) {
  101242. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  101243. return false; /* read_callback_ sets the state for us */
  101244. raw_header[raw_header_len++] = (FLAC__byte)x;
  101245. if(sample_rate_hint != 12) {
  101246. FLAC__uint32 _x;
  101247. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  101248. return false; /* read_callback_ sets the state for us */
  101249. raw_header[raw_header_len++] = (FLAC__byte)_x;
  101250. x = (x << 8) | _x;
  101251. }
  101252. if(sample_rate_hint == 12)
  101253. decoder->private_->frame.header.sample_rate = x*1000;
  101254. else if(sample_rate_hint == 13)
  101255. decoder->private_->frame.header.sample_rate = x;
  101256. else
  101257. decoder->private_->frame.header.sample_rate = x*10;
  101258. }
  101259. /* read the CRC-8 byte */
  101260. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  101261. return false; /* read_callback_ sets the state for us */
  101262. crc8 = (FLAC__byte)x;
  101263. if(FLAC__crc8(raw_header, raw_header_len) != crc8) {
  101264. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101265. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101266. return true;
  101267. }
  101268. /* calculate the sample number from the frame number if needed */
  101269. decoder->private_->next_fixed_block_size = 0;
  101270. if(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  101271. x = decoder->private_->frame.header.number.frame_number;
  101272. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  101273. if(decoder->private_->fixed_block_size)
  101274. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->fixed_block_size * (FLAC__uint64)x;
  101275. else if(decoder->private_->has_stream_info) {
  101276. if(decoder->private_->stream_info.data.stream_info.min_blocksize == decoder->private_->stream_info.data.stream_info.max_blocksize) {
  101277. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->stream_info.data.stream_info.min_blocksize * (FLAC__uint64)x;
  101278. decoder->private_->next_fixed_block_size = decoder->private_->stream_info.data.stream_info.max_blocksize;
  101279. }
  101280. else
  101281. is_unparseable = true;
  101282. }
  101283. else if(x == 0) {
  101284. decoder->private_->frame.header.number.sample_number = 0;
  101285. decoder->private_->next_fixed_block_size = decoder->private_->frame.header.blocksize;
  101286. }
  101287. else {
  101288. /* can only get here if the stream has invalid frame numbering and no STREAMINFO, so assume it's not the last (possibly short) frame */
  101289. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->frame.header.blocksize * (FLAC__uint64)x;
  101290. }
  101291. }
  101292. if(is_unparseable) {
  101293. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101294. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101295. return true;
  101296. }
  101297. return true;
  101298. }
  101299. FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  101300. {
  101301. FLAC__uint32 x;
  101302. FLAC__bool wasted_bits;
  101303. unsigned i;
  101304. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8)) /* MAGIC NUMBER */
  101305. return false; /* read_callback_ sets the state for us */
  101306. wasted_bits = (x & 1);
  101307. x &= 0xfe;
  101308. if(wasted_bits) {
  101309. unsigned u;
  101310. if(!FLAC__bitreader_read_unary_unsigned(decoder->private_->input, &u))
  101311. return false; /* read_callback_ sets the state for us */
  101312. decoder->private_->frame.subframes[channel].wasted_bits = u+1;
  101313. bps -= decoder->private_->frame.subframes[channel].wasted_bits;
  101314. }
  101315. else
  101316. decoder->private_->frame.subframes[channel].wasted_bits = 0;
  101317. /*
  101318. * Lots of magic numbers here
  101319. */
  101320. if(x & 0x80) {
  101321. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101322. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101323. return true;
  101324. }
  101325. else if(x == 0) {
  101326. if(!read_subframe_constant_(decoder, channel, bps, do_full_decode))
  101327. return false;
  101328. }
  101329. else if(x == 2) {
  101330. if(!read_subframe_verbatim_(decoder, channel, bps, do_full_decode))
  101331. return false;
  101332. }
  101333. else if(x < 16) {
  101334. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101335. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101336. return true;
  101337. }
  101338. else if(x <= 24) {
  101339. if(!read_subframe_fixed_(decoder, channel, bps, (x>>1)&7, do_full_decode))
  101340. return false;
  101341. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  101342. return true;
  101343. }
  101344. else if(x < 64) {
  101345. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101346. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101347. return true;
  101348. }
  101349. else {
  101350. if(!read_subframe_lpc_(decoder, channel, bps, ((x>>1)&31)+1, do_full_decode))
  101351. return false;
  101352. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  101353. return true;
  101354. }
  101355. if(wasted_bits && do_full_decode) {
  101356. x = decoder->private_->frame.subframes[channel].wasted_bits;
  101357. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  101358. decoder->private_->output[channel][i] <<= x;
  101359. }
  101360. return true;
  101361. }
  101362. FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  101363. {
  101364. FLAC__Subframe_Constant *subframe = &decoder->private_->frame.subframes[channel].data.constant;
  101365. FLAC__int32 x;
  101366. unsigned i;
  101367. FLAC__int32 *output = decoder->private_->output[channel];
  101368. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_CONSTANT;
  101369. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  101370. return false; /* read_callback_ sets the state for us */
  101371. subframe->value = x;
  101372. /* decode the subframe */
  101373. if(do_full_decode) {
  101374. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  101375. output[i] = x;
  101376. }
  101377. return true;
  101378. }
  101379. FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  101380. {
  101381. FLAC__Subframe_Fixed *subframe = &decoder->private_->frame.subframes[channel].data.fixed;
  101382. FLAC__int32 i32;
  101383. FLAC__uint32 u32;
  101384. unsigned u;
  101385. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_FIXED;
  101386. subframe->residual = decoder->private_->residual[channel];
  101387. subframe->order = order;
  101388. /* read warm-up samples */
  101389. for(u = 0; u < order; u++) {
  101390. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  101391. return false; /* read_callback_ sets the state for us */
  101392. subframe->warmup[u] = i32;
  101393. }
  101394. /* read entropy coding method info */
  101395. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  101396. return false; /* read_callback_ sets the state for us */
  101397. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  101398. switch(subframe->entropy_coding_method.type) {
  101399. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101400. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101401. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  101402. return false; /* read_callback_ sets the state for us */
  101403. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  101404. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  101405. break;
  101406. default:
  101407. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101408. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101409. return true;
  101410. }
  101411. /* read residual */
  101412. switch(subframe->entropy_coding_method.type) {
  101413. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101414. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101415. 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))
  101416. return false;
  101417. break;
  101418. default:
  101419. FLAC__ASSERT(0);
  101420. }
  101421. /* decode the subframe */
  101422. if(do_full_decode) {
  101423. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  101424. FLAC__fixed_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, order, decoder->private_->output[channel]+order);
  101425. }
  101426. return true;
  101427. }
  101428. FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  101429. {
  101430. FLAC__Subframe_LPC *subframe = &decoder->private_->frame.subframes[channel].data.lpc;
  101431. FLAC__int32 i32;
  101432. FLAC__uint32 u32;
  101433. unsigned u;
  101434. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_LPC;
  101435. subframe->residual = decoder->private_->residual[channel];
  101436. subframe->order = order;
  101437. /* read warm-up samples */
  101438. for(u = 0; u < order; u++) {
  101439. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  101440. return false; /* read_callback_ sets the state for us */
  101441. subframe->warmup[u] = i32;
  101442. }
  101443. /* read qlp coeff precision */
  101444. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  101445. return false; /* read_callback_ sets the state for us */
  101446. if(u32 == (1u << FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN) - 1) {
  101447. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101448. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101449. return true;
  101450. }
  101451. subframe->qlp_coeff_precision = u32+1;
  101452. /* read qlp shift */
  101453. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  101454. return false; /* read_callback_ sets the state for us */
  101455. subframe->quantization_level = i32;
  101456. /* read quantized lp coefficiencts */
  101457. for(u = 0; u < order; u++) {
  101458. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, subframe->qlp_coeff_precision))
  101459. return false; /* read_callback_ sets the state for us */
  101460. subframe->qlp_coeff[u] = i32;
  101461. }
  101462. /* read entropy coding method info */
  101463. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  101464. return false; /* read_callback_ sets the state for us */
  101465. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  101466. switch(subframe->entropy_coding_method.type) {
  101467. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101468. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101469. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  101470. return false; /* read_callback_ sets the state for us */
  101471. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  101472. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  101473. break;
  101474. default:
  101475. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101476. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101477. return true;
  101478. }
  101479. /* read residual */
  101480. switch(subframe->entropy_coding_method.type) {
  101481. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101482. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101483. 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))
  101484. return false;
  101485. break;
  101486. default:
  101487. FLAC__ASSERT(0);
  101488. }
  101489. /* decode the subframe */
  101490. if(do_full_decode) {
  101491. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  101492. /*@@@@@@ technically not pessimistic enough, should be more like
  101493. if( (FLAC__uint64)order * ((((FLAC__uint64)1)<<bps)-1) * ((1<<subframe->qlp_coeff_precision)-1) < (((FLAC__uint64)-1) << 32) )
  101494. */
  101495. if(bps + subframe->qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  101496. if(bps <= 16 && subframe->qlp_coeff_precision <= 16) {
  101497. if(order <= 8)
  101498. 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);
  101499. else
  101500. 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);
  101501. }
  101502. else
  101503. 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);
  101504. else
  101505. 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);
  101506. }
  101507. return true;
  101508. }
  101509. FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  101510. {
  101511. FLAC__Subframe_Verbatim *subframe = &decoder->private_->frame.subframes[channel].data.verbatim;
  101512. FLAC__int32 x, *residual = decoder->private_->residual[channel];
  101513. unsigned i;
  101514. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_VERBATIM;
  101515. subframe->data = residual;
  101516. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  101517. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  101518. return false; /* read_callback_ sets the state for us */
  101519. residual[i] = x;
  101520. }
  101521. /* decode the subframe */
  101522. if(do_full_decode)
  101523. memcpy(decoder->private_->output[channel], subframe->data, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  101524. return true;
  101525. }
  101526. 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)
  101527. {
  101528. FLAC__uint32 rice_parameter;
  101529. int i;
  101530. unsigned partition, sample, u;
  101531. const unsigned partitions = 1u << partition_order;
  101532. const unsigned partition_samples = partition_order > 0? decoder->private_->frame.header.blocksize >> partition_order : decoder->private_->frame.header.blocksize - predictor_order;
  101533. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  101534. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  101535. /* sanity checks */
  101536. if(partition_order == 0) {
  101537. if(decoder->private_->frame.header.blocksize < predictor_order) {
  101538. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101539. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101540. return true;
  101541. }
  101542. }
  101543. else {
  101544. if(partition_samples < predictor_order) {
  101545. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101546. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101547. return true;
  101548. }
  101549. }
  101550. if(!FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order))) {
  101551. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  101552. return false;
  101553. }
  101554. sample = 0;
  101555. for(partition = 0; partition < partitions; partition++) {
  101556. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, plen))
  101557. return false; /* read_callback_ sets the state for us */
  101558. partitioned_rice_contents->parameters[partition] = rice_parameter;
  101559. if(rice_parameter < pesc) {
  101560. partitioned_rice_contents->raw_bits[partition] = 0;
  101561. u = (partition_order == 0 || partition > 0)? partition_samples : partition_samples - predictor_order;
  101562. if(!decoder->private_->local_bitreader_read_rice_signed_block(decoder->private_->input, (int*) residual + sample, u, rice_parameter))
  101563. return false; /* read_callback_ sets the state for us */
  101564. sample += u;
  101565. }
  101566. else {
  101567. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  101568. return false; /* read_callback_ sets the state for us */
  101569. partitioned_rice_contents->raw_bits[partition] = rice_parameter;
  101570. for(u = (partition_order == 0 || partition > 0)? 0 : predictor_order; u < partition_samples; u++, sample++) {
  101571. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, (FLAC__int32*) &i, rice_parameter))
  101572. return false; /* read_callback_ sets the state for us */
  101573. residual[sample] = i;
  101574. }
  101575. }
  101576. }
  101577. return true;
  101578. }
  101579. FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder)
  101580. {
  101581. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  101582. FLAC__uint32 zero = 0;
  101583. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &zero, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  101584. return false; /* read_callback_ sets the state for us */
  101585. if(zero != 0) {
  101586. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101587. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101588. }
  101589. }
  101590. return true;
  101591. }
  101592. FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data)
  101593. {
  101594. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder *)client_data;
  101595. if(
  101596. #if FLAC__HAS_OGG
  101597. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  101598. !decoder->private_->is_ogg &&
  101599. #endif
  101600. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  101601. ) {
  101602. *bytes = 0;
  101603. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  101604. return false;
  101605. }
  101606. else if(*bytes > 0) {
  101607. /* While seeking, it is possible for our seek to land in the
  101608. * middle of audio data that looks exactly like a frame header
  101609. * from a future version of an encoder. When that happens, our
  101610. * error callback will get an
  101611. * FLAC__STREAM_DECODER_UNPARSEABLE_STREAM and increment its
  101612. * unparseable_frame_count. But there is a remote possibility
  101613. * that it is properly synced at such a "future-codec frame",
  101614. * so to make sure, we wait to see many "unparseable" errors in
  101615. * a row before bailing out.
  101616. */
  101617. if(decoder->private_->is_seeking && decoder->private_->unparseable_frame_count > 20) {
  101618. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  101619. return false;
  101620. }
  101621. else {
  101622. const FLAC__StreamDecoderReadStatus status =
  101623. #if FLAC__HAS_OGG
  101624. decoder->private_->is_ogg?
  101625. read_callback_ogg_aspect_(decoder, buffer, bytes) :
  101626. #endif
  101627. decoder->private_->read_callback(decoder, buffer, bytes, decoder->private_->client_data)
  101628. ;
  101629. if(status == FLAC__STREAM_DECODER_READ_STATUS_ABORT) {
  101630. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  101631. return false;
  101632. }
  101633. else if(*bytes == 0) {
  101634. if(
  101635. status == FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM ||
  101636. (
  101637. #if FLAC__HAS_OGG
  101638. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  101639. !decoder->private_->is_ogg &&
  101640. #endif
  101641. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  101642. )
  101643. ) {
  101644. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  101645. return false;
  101646. }
  101647. else
  101648. return true;
  101649. }
  101650. else
  101651. return true;
  101652. }
  101653. }
  101654. else {
  101655. /* abort to avoid a deadlock */
  101656. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  101657. return false;
  101658. }
  101659. /* [1] @@@ HACK NOTE: The end-of-stream checking has to be hacked around
  101660. * for Ogg FLAC. This is because the ogg decoder aspect can lose sync
  101661. * and at the same time hit the end of the stream (for example, seeking
  101662. * to a point that is after the beginning of the last Ogg page). There
  101663. * is no way to report an Ogg sync loss through the callbacks (see note
  101664. * in read_callback_ogg_aspect_()) so it returns CONTINUE with *bytes==0.
  101665. * So to keep the decoder from stopping at this point we gate the call
  101666. * to the eof_callback and let the Ogg decoder aspect set the
  101667. * end-of-stream state when it is needed.
  101668. */
  101669. }
  101670. #if FLAC__HAS_OGG
  101671. FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes)
  101672. {
  101673. switch(FLAC__ogg_decoder_aspect_read_callback_wrapper(&decoder->protected_->ogg_decoder_aspect, buffer, bytes, read_callback_proxy_, decoder, decoder->private_->client_data)) {
  101674. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK:
  101675. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101676. /* we don't really have a way to handle lost sync via read
  101677. * callback so we'll let it pass and let the underlying
  101678. * FLAC decoder catch the error
  101679. */
  101680. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_LOST_SYNC:
  101681. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101682. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM:
  101683. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  101684. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_NOT_FLAC:
  101685. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_UNSUPPORTED_MAPPING_VERSION:
  101686. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT:
  101687. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ERROR:
  101688. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_MEMORY_ALLOCATION_ERROR:
  101689. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101690. default:
  101691. FLAC__ASSERT(0);
  101692. /* double protection */
  101693. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101694. }
  101695. }
  101696. FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  101697. {
  101698. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder*)void_decoder;
  101699. switch(decoder->private_->read_callback(decoder, buffer, bytes, client_data)) {
  101700. case FLAC__STREAM_DECODER_READ_STATUS_CONTINUE:
  101701. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK;
  101702. case FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM:
  101703. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM;
  101704. case FLAC__STREAM_DECODER_READ_STATUS_ABORT:
  101705. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  101706. default:
  101707. /* double protection: */
  101708. FLAC__ASSERT(0);
  101709. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  101710. }
  101711. }
  101712. #endif
  101713. FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[])
  101714. {
  101715. if(decoder->private_->is_seeking) {
  101716. FLAC__uint64 this_frame_sample = frame->header.number.sample_number;
  101717. FLAC__uint64 next_frame_sample = this_frame_sample + (FLAC__uint64)frame->header.blocksize;
  101718. FLAC__uint64 target_sample = decoder->private_->target_sample;
  101719. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101720. #if FLAC__HAS_OGG
  101721. decoder->private_->got_a_frame = true;
  101722. #endif
  101723. decoder->private_->last_frame = *frame; /* save the frame */
  101724. if(this_frame_sample <= target_sample && target_sample < next_frame_sample) { /* we hit our target frame */
  101725. unsigned delta = (unsigned)(target_sample - this_frame_sample);
  101726. /* kick out of seek mode */
  101727. decoder->private_->is_seeking = false;
  101728. /* shift out the samples before target_sample */
  101729. if(delta > 0) {
  101730. unsigned channel;
  101731. const FLAC__int32 *newbuffer[FLAC__MAX_CHANNELS];
  101732. for(channel = 0; channel < frame->header.channels; channel++)
  101733. newbuffer[channel] = buffer[channel] + delta;
  101734. decoder->private_->last_frame.header.blocksize -= delta;
  101735. decoder->private_->last_frame.header.number.sample_number += (FLAC__uint64)delta;
  101736. /* write the relevant samples */
  101737. return decoder->private_->write_callback(decoder, &decoder->private_->last_frame, newbuffer, decoder->private_->client_data);
  101738. }
  101739. else {
  101740. /* write the relevant samples */
  101741. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  101742. }
  101743. }
  101744. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  101745. }
  101746. /*
  101747. * If we never got STREAMINFO, turn off MD5 checking to save
  101748. * cycles since we don't have a sum to compare to anyway
  101749. */
  101750. if(!decoder->private_->has_stream_info)
  101751. decoder->private_->do_md5_checking = false;
  101752. if(decoder->private_->do_md5_checking) {
  101753. if(!FLAC__MD5Accumulate(&decoder->private_->md5context, buffer, frame->header.channels, frame->header.blocksize, (frame->header.bits_per_sample+7) / 8))
  101754. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  101755. }
  101756. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  101757. }
  101758. void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status)
  101759. {
  101760. if(!decoder->private_->is_seeking)
  101761. decoder->private_->error_callback(decoder, status, decoder->private_->client_data);
  101762. else if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM)
  101763. decoder->private_->unparseable_frame_count++;
  101764. }
  101765. FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  101766. {
  101767. FLAC__uint64 first_frame_offset = decoder->private_->first_frame_offset, lower_bound, upper_bound, lower_bound_sample, upper_bound_sample, this_frame_sample;
  101768. FLAC__int64 pos = -1;
  101769. int i;
  101770. unsigned approx_bytes_per_frame;
  101771. FLAC__bool first_seek = true;
  101772. const FLAC__uint64 total_samples = FLAC__stream_decoder_get_total_samples(decoder);
  101773. const unsigned min_blocksize = decoder->private_->stream_info.data.stream_info.min_blocksize;
  101774. const unsigned max_blocksize = decoder->private_->stream_info.data.stream_info.max_blocksize;
  101775. const unsigned max_framesize = decoder->private_->stream_info.data.stream_info.max_framesize;
  101776. const unsigned min_framesize = decoder->private_->stream_info.data.stream_info.min_framesize;
  101777. /* take these from the current frame in case they've changed mid-stream */
  101778. unsigned channels = FLAC__stream_decoder_get_channels(decoder);
  101779. unsigned bps = FLAC__stream_decoder_get_bits_per_sample(decoder);
  101780. const FLAC__StreamMetadata_SeekTable *seek_table = decoder->private_->has_seek_table? &decoder->private_->seek_table.data.seek_table : 0;
  101781. /* use values from stream info if we didn't decode a frame */
  101782. if(channels == 0)
  101783. channels = decoder->private_->stream_info.data.stream_info.channels;
  101784. if(bps == 0)
  101785. bps = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  101786. /* we are just guessing here */
  101787. if(max_framesize > 0)
  101788. approx_bytes_per_frame = (max_framesize + min_framesize) / 2 + 1;
  101789. /*
  101790. * Check if it's a known fixed-blocksize stream. Note that though
  101791. * the spec doesn't allow zeroes in the STREAMINFO block, we may
  101792. * never get a STREAMINFO block when decoding so the value of
  101793. * min_blocksize might be zero.
  101794. */
  101795. else if(min_blocksize == max_blocksize && min_blocksize > 0) {
  101796. /* note there are no () around 'bps/8' to keep precision up since it's an integer calulation */
  101797. approx_bytes_per_frame = min_blocksize * channels * bps/8 + 64;
  101798. }
  101799. else
  101800. approx_bytes_per_frame = 4096 * channels * bps/8 + 64;
  101801. /*
  101802. * First, we set an upper and lower bound on where in the
  101803. * stream we will search. For now we assume the worst case
  101804. * scenario, which is our best guess at the beginning of
  101805. * the first frame and end of the stream.
  101806. */
  101807. lower_bound = first_frame_offset;
  101808. lower_bound_sample = 0;
  101809. upper_bound = stream_length;
  101810. upper_bound_sample = total_samples > 0 ? total_samples : target_sample /*estimate it*/;
  101811. /*
  101812. * Now we refine the bounds if we have a seektable with
  101813. * suitable points. Note that according to the spec they
  101814. * must be ordered by ascending sample number.
  101815. *
  101816. * Note: to protect against invalid seek tables we will ignore points
  101817. * that have frame_samples==0 or sample_number>=total_samples
  101818. */
  101819. if(seek_table) {
  101820. FLAC__uint64 new_lower_bound = lower_bound;
  101821. FLAC__uint64 new_upper_bound = upper_bound;
  101822. FLAC__uint64 new_lower_bound_sample = lower_bound_sample;
  101823. FLAC__uint64 new_upper_bound_sample = upper_bound_sample;
  101824. /* find the closest seek point <= target_sample, if it exists */
  101825. for(i = (int)seek_table->num_points - 1; i >= 0; i--) {
  101826. if(
  101827. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  101828. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  101829. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  101830. seek_table->points[i].sample_number <= target_sample
  101831. )
  101832. break;
  101833. }
  101834. if(i >= 0) { /* i.e. we found a suitable seek point... */
  101835. new_lower_bound = first_frame_offset + seek_table->points[i].stream_offset;
  101836. new_lower_bound_sample = seek_table->points[i].sample_number;
  101837. }
  101838. /* find the closest seek point > target_sample, if it exists */
  101839. for(i = 0; i < (int)seek_table->num_points; i++) {
  101840. if(
  101841. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  101842. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  101843. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  101844. seek_table->points[i].sample_number > target_sample
  101845. )
  101846. break;
  101847. }
  101848. if(i < (int)seek_table->num_points) { /* i.e. we found a suitable seek point... */
  101849. new_upper_bound = first_frame_offset + seek_table->points[i].stream_offset;
  101850. new_upper_bound_sample = seek_table->points[i].sample_number;
  101851. }
  101852. /* final protection against unsorted seek tables; keep original values if bogus */
  101853. if(new_upper_bound >= new_lower_bound) {
  101854. lower_bound = new_lower_bound;
  101855. upper_bound = new_upper_bound;
  101856. lower_bound_sample = new_lower_bound_sample;
  101857. upper_bound_sample = new_upper_bound_sample;
  101858. }
  101859. }
  101860. FLAC__ASSERT(upper_bound_sample >= lower_bound_sample);
  101861. /* there are 2 insidious ways that the following equality occurs, which
  101862. * we need to fix:
  101863. * 1) total_samples is 0 (unknown) and target_sample is 0
  101864. * 2) total_samples is 0 (unknown) and target_sample happens to be
  101865. * exactly equal to the last seek point in the seek table; this
  101866. * means there is no seek point above it, and upper_bound_samples
  101867. * remains equal to the estimate (of target_samples) we made above
  101868. * in either case it does not hurt to move upper_bound_sample up by 1
  101869. */
  101870. if(upper_bound_sample == lower_bound_sample)
  101871. upper_bound_sample++;
  101872. decoder->private_->target_sample = target_sample;
  101873. while(1) {
  101874. /* check if the bounds are still ok */
  101875. if (lower_bound_sample >= upper_bound_sample || lower_bound > upper_bound) {
  101876. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101877. return false;
  101878. }
  101879. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101880. #if defined _MSC_VER || defined __MINGW32__
  101881. /* with VC++ you have to spoon feed it the casting */
  101882. 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;
  101883. #else
  101884. 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;
  101885. #endif
  101886. #else
  101887. /* a little less accurate: */
  101888. if(upper_bound - lower_bound < 0xffffffff)
  101889. 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;
  101890. else /* @@@ WATCHOUT, ~2TB limit */
  101891. 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;
  101892. #endif
  101893. if(pos >= (FLAC__int64)upper_bound)
  101894. pos = (FLAC__int64)upper_bound - 1;
  101895. if(pos < (FLAC__int64)lower_bound)
  101896. pos = (FLAC__int64)lower_bound;
  101897. if(decoder->private_->seek_callback(decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  101898. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101899. return false;
  101900. }
  101901. if(!FLAC__stream_decoder_flush(decoder)) {
  101902. /* above call sets the state for us */
  101903. return false;
  101904. }
  101905. /* Now we need to get a frame. First we need to reset our
  101906. * unparseable_frame_count; if we get too many unparseable
  101907. * frames in a row, the read callback will return
  101908. * FLAC__STREAM_DECODER_READ_STATUS_ABORT, causing
  101909. * FLAC__stream_decoder_process_single() to return false.
  101910. */
  101911. decoder->private_->unparseable_frame_count = 0;
  101912. if(!FLAC__stream_decoder_process_single(decoder)) {
  101913. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101914. return false;
  101915. }
  101916. /* our write callback will change the state when it gets to the target frame */
  101917. /* 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 */
  101918. #if 0
  101919. /*@@@@@@ used to be the following; not clear if the check for end of stream is needed anymore */
  101920. if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_SEEKING && decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM)
  101921. break;
  101922. #endif
  101923. if(!decoder->private_->is_seeking)
  101924. break;
  101925. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101926. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  101927. if (0 == decoder->private_->samples_decoded || (this_frame_sample + decoder->private_->last_frame.header.blocksize >= upper_bound_sample && !first_seek)) {
  101928. if (pos == (FLAC__int64)lower_bound) {
  101929. /* can't move back any more than the first frame, something is fatally wrong */
  101930. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101931. return false;
  101932. }
  101933. /* our last move backwards wasn't big enough, try again */
  101934. approx_bytes_per_frame = approx_bytes_per_frame? approx_bytes_per_frame * 2 : 16;
  101935. continue;
  101936. }
  101937. /* allow one seek over upper bound, so we can get a correct upper_bound_sample for streams with unknown total_samples */
  101938. first_seek = false;
  101939. /* make sure we are not seeking in corrupted stream */
  101940. if (this_frame_sample < lower_bound_sample) {
  101941. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101942. return false;
  101943. }
  101944. /* we need to narrow the search */
  101945. if(target_sample < this_frame_sample) {
  101946. upper_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  101947. /*@@@@@@ what will decode position be if at end of stream? */
  101948. if(!FLAC__stream_decoder_get_decode_position(decoder, &upper_bound)) {
  101949. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101950. return false;
  101951. }
  101952. approx_bytes_per_frame = (unsigned)(2 * (upper_bound - pos) / 3 + 16);
  101953. }
  101954. else { /* target_sample >= this_frame_sample + this frame's blocksize */
  101955. lower_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  101956. if(!FLAC__stream_decoder_get_decode_position(decoder, &lower_bound)) {
  101957. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101958. return false;
  101959. }
  101960. approx_bytes_per_frame = (unsigned)(2 * (lower_bound - pos) / 3 + 16);
  101961. }
  101962. }
  101963. return true;
  101964. }
  101965. #if FLAC__HAS_OGG
  101966. FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  101967. {
  101968. FLAC__uint64 left_pos = 0, right_pos = stream_length;
  101969. FLAC__uint64 left_sample = 0, right_sample = FLAC__stream_decoder_get_total_samples(decoder);
  101970. FLAC__uint64 this_frame_sample = (FLAC__uint64)0 - 1;
  101971. FLAC__uint64 pos = 0; /* only initialized to avoid compiler warning */
  101972. FLAC__bool did_a_seek;
  101973. unsigned iteration = 0;
  101974. /* In the first iterations, we will calculate the target byte position
  101975. * by the distance from the target sample to left_sample and
  101976. * right_sample (let's call it "proportional search"). After that, we
  101977. * will switch to binary search.
  101978. */
  101979. unsigned BINARY_SEARCH_AFTER_ITERATION = 2;
  101980. /* We will switch to a linear search once our current sample is less
  101981. * than this number of samples ahead of the target sample
  101982. */
  101983. static const FLAC__uint64 LINEAR_SEARCH_WITHIN_SAMPLES = FLAC__MAX_BLOCK_SIZE * 2;
  101984. /* If the total number of samples is unknown, use a large value, and
  101985. * force binary search immediately.
  101986. */
  101987. if(right_sample == 0) {
  101988. right_sample = (FLAC__uint64)(-1);
  101989. BINARY_SEARCH_AFTER_ITERATION = 0;
  101990. }
  101991. decoder->private_->target_sample = target_sample;
  101992. for( ; ; iteration++) {
  101993. if (iteration == 0 || this_frame_sample > target_sample || target_sample - this_frame_sample > LINEAR_SEARCH_WITHIN_SAMPLES) {
  101994. if (iteration >= BINARY_SEARCH_AFTER_ITERATION) {
  101995. pos = (right_pos + left_pos) / 2;
  101996. }
  101997. else {
  101998. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101999. #if defined _MSC_VER || defined __MINGW32__
  102000. /* with MSVC you have to spoon feed it the casting */
  102001. 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));
  102002. #else
  102003. pos = (FLAC__uint64)((FLAC__double)(target_sample - left_sample) / (FLAC__double)(right_sample - left_sample) * (FLAC__double)(right_pos - left_pos));
  102004. #endif
  102005. #else
  102006. /* a little less accurate: */
  102007. if ((target_sample-left_sample <= 0xffffffff) && (right_pos-left_pos <= 0xffffffff))
  102008. pos = (FLAC__int64)(((target_sample-left_sample) * (right_pos-left_pos)) / (right_sample-left_sample));
  102009. else /* @@@ WATCHOUT, ~2TB limit */
  102010. pos = (FLAC__int64)((((target_sample-left_sample)>>8) * ((right_pos-left_pos)>>8)) / ((right_sample-left_sample)>>16));
  102011. #endif
  102012. /* @@@ TODO: might want to limit pos to some distance
  102013. * before EOF, to make sure we land before the last frame,
  102014. * thereby getting a this_frame_sample and so having a better
  102015. * estimate.
  102016. */
  102017. }
  102018. /* physical seek */
  102019. if(decoder->private_->seek_callback((FLAC__StreamDecoder*)decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  102020. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102021. return false;
  102022. }
  102023. if(!FLAC__stream_decoder_flush(decoder)) {
  102024. /* above call sets the state for us */
  102025. return false;
  102026. }
  102027. did_a_seek = true;
  102028. }
  102029. else
  102030. did_a_seek = false;
  102031. decoder->private_->got_a_frame = false;
  102032. if(!FLAC__stream_decoder_process_single(decoder)) {
  102033. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102034. return false;
  102035. }
  102036. if(!decoder->private_->got_a_frame) {
  102037. if(did_a_seek) {
  102038. /* this can happen if we seek to a point after the last frame; we drop
  102039. * to binary search right away in this case to avoid any wasted
  102040. * iterations of proportional search.
  102041. */
  102042. right_pos = pos;
  102043. BINARY_SEARCH_AFTER_ITERATION = 0;
  102044. }
  102045. else {
  102046. /* this can probably only happen if total_samples is unknown and the
  102047. * target_sample is past the end of the stream
  102048. */
  102049. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102050. return false;
  102051. }
  102052. }
  102053. /* our write callback will change the state when it gets to the target frame */
  102054. else if(!decoder->private_->is_seeking) {
  102055. break;
  102056. }
  102057. else {
  102058. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  102059. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  102060. if (did_a_seek) {
  102061. if (this_frame_sample <= target_sample) {
  102062. /* The 'equal' case should not happen, since
  102063. * FLAC__stream_decoder_process_single()
  102064. * should recognize that it has hit the
  102065. * target sample and we would exit through
  102066. * the 'break' above.
  102067. */
  102068. FLAC__ASSERT(this_frame_sample != target_sample);
  102069. left_sample = this_frame_sample;
  102070. /* sanity check to avoid infinite loop */
  102071. if (left_pos == pos) {
  102072. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102073. return false;
  102074. }
  102075. left_pos = pos;
  102076. }
  102077. else if(this_frame_sample > target_sample) {
  102078. right_sample = this_frame_sample;
  102079. /* sanity check to avoid infinite loop */
  102080. if (right_pos == pos) {
  102081. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102082. return false;
  102083. }
  102084. right_pos = pos;
  102085. }
  102086. }
  102087. }
  102088. }
  102089. return true;
  102090. }
  102091. #endif
  102092. FLAC__StreamDecoderReadStatus file_read_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  102093. {
  102094. (void)client_data;
  102095. if(*bytes > 0) {
  102096. *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, decoder->private_->file);
  102097. if(ferror(decoder->private_->file))
  102098. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  102099. else if(*bytes == 0)
  102100. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  102101. else
  102102. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  102103. }
  102104. else
  102105. return FLAC__STREAM_DECODER_READ_STATUS_ABORT; /* abort to avoid a deadlock */
  102106. }
  102107. FLAC__StreamDecoderSeekStatus file_seek_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  102108. {
  102109. (void)client_data;
  102110. if(decoder->private_->file == stdin)
  102111. return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  102112. else if(fseeko(decoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  102113. return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  102114. else
  102115. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  102116. }
  102117. FLAC__StreamDecoderTellStatus file_tell_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  102118. {
  102119. off_t pos;
  102120. (void)client_data;
  102121. if(decoder->private_->file == stdin)
  102122. return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  102123. else if((pos = ftello(decoder->private_->file)) < 0)
  102124. return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  102125. else {
  102126. *absolute_byte_offset = (FLAC__uint64)pos;
  102127. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  102128. }
  102129. }
  102130. FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  102131. {
  102132. struct stat filestats;
  102133. (void)client_data;
  102134. if(decoder->private_->file == stdin)
  102135. return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  102136. else if(fstat(fileno(decoder->private_->file), &filestats) != 0)
  102137. return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  102138. else {
  102139. *stream_length = (FLAC__uint64)filestats.st_size;
  102140. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  102141. }
  102142. }
  102143. FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data)
  102144. {
  102145. (void)client_data;
  102146. return feof(decoder->private_->file)? true : false;
  102147. }
  102148. #endif
  102149. /*** End of inlined file: stream_decoder.c ***/
  102150. /*** Start of inlined file: stream_encoder.c ***/
  102151. /*** Start of inlined file: juce_FlacHeader.h ***/
  102152. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  102153. // tasks..
  102154. #define VERSION "1.2.1"
  102155. #define FLAC__NO_DLL 1
  102156. #if JUCE_MSVC
  102157. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  102158. #endif
  102159. #if JUCE_MAC
  102160. #define FLAC__SYS_DARWIN 1
  102161. #endif
  102162. /*** End of inlined file: juce_FlacHeader.h ***/
  102163. #if JUCE_USE_FLAC
  102164. #if HAVE_CONFIG_H
  102165. # include <config.h>
  102166. #endif
  102167. #if defined _MSC_VER || defined __MINGW32__
  102168. #include <io.h> /* for _setmode() */
  102169. #include <fcntl.h> /* for _O_BINARY */
  102170. #endif
  102171. #if defined __CYGWIN__ || defined __EMX__
  102172. #include <io.h> /* for setmode(), O_BINARY */
  102173. #include <fcntl.h> /* for _O_BINARY */
  102174. #endif
  102175. #include <limits.h>
  102176. #include <stdio.h>
  102177. #include <stdlib.h> /* for malloc() */
  102178. #include <string.h> /* for memcpy() */
  102179. #include <sys/types.h> /* for off_t */
  102180. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  102181. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  102182. #define fseeko fseek
  102183. #define ftello ftell
  102184. #endif
  102185. #endif
  102186. /*** Start of inlined file: stream_encoder.h ***/
  102187. #ifndef FLAC__PROTECTED__STREAM_ENCODER_H
  102188. #define FLAC__PROTECTED__STREAM_ENCODER_H
  102189. #if FLAC__HAS_OGG
  102190. #include "private/ogg_encoder_aspect.h"
  102191. #endif
  102192. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102193. #define FLAC__MAX_APODIZATION_FUNCTIONS 32
  102194. typedef enum {
  102195. FLAC__APODIZATION_BARTLETT,
  102196. FLAC__APODIZATION_BARTLETT_HANN,
  102197. FLAC__APODIZATION_BLACKMAN,
  102198. FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE,
  102199. FLAC__APODIZATION_CONNES,
  102200. FLAC__APODIZATION_FLATTOP,
  102201. FLAC__APODIZATION_GAUSS,
  102202. FLAC__APODIZATION_HAMMING,
  102203. FLAC__APODIZATION_HANN,
  102204. FLAC__APODIZATION_KAISER_BESSEL,
  102205. FLAC__APODIZATION_NUTTALL,
  102206. FLAC__APODIZATION_RECTANGLE,
  102207. FLAC__APODIZATION_TRIANGLE,
  102208. FLAC__APODIZATION_TUKEY,
  102209. FLAC__APODIZATION_WELCH
  102210. } FLAC__ApodizationFunction;
  102211. typedef struct {
  102212. FLAC__ApodizationFunction type;
  102213. union {
  102214. struct {
  102215. FLAC__real stddev;
  102216. } gauss;
  102217. struct {
  102218. FLAC__real p;
  102219. } tukey;
  102220. } parameters;
  102221. } FLAC__ApodizationSpecification;
  102222. #endif // #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102223. typedef struct FLAC__StreamEncoderProtected {
  102224. FLAC__StreamEncoderState state;
  102225. FLAC__bool verify;
  102226. FLAC__bool streamable_subset;
  102227. FLAC__bool do_md5;
  102228. FLAC__bool do_mid_side_stereo;
  102229. FLAC__bool loose_mid_side_stereo;
  102230. unsigned channels;
  102231. unsigned bits_per_sample;
  102232. unsigned sample_rate;
  102233. unsigned blocksize;
  102234. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102235. unsigned num_apodizations;
  102236. FLAC__ApodizationSpecification apodizations[FLAC__MAX_APODIZATION_FUNCTIONS];
  102237. #endif
  102238. unsigned max_lpc_order;
  102239. unsigned qlp_coeff_precision;
  102240. FLAC__bool do_qlp_coeff_prec_search;
  102241. FLAC__bool do_exhaustive_model_search;
  102242. FLAC__bool do_escape_coding;
  102243. unsigned min_residual_partition_order;
  102244. unsigned max_residual_partition_order;
  102245. unsigned rice_parameter_search_dist;
  102246. FLAC__uint64 total_samples_estimate;
  102247. FLAC__StreamMetadata **metadata;
  102248. unsigned num_metadata_blocks;
  102249. FLAC__uint64 streaminfo_offset, seektable_offset, audio_offset;
  102250. #if FLAC__HAS_OGG
  102251. FLAC__OggEncoderAspect ogg_encoder_aspect;
  102252. #endif
  102253. } FLAC__StreamEncoderProtected;
  102254. #endif
  102255. /*** End of inlined file: stream_encoder.h ***/
  102256. #if FLAC__HAS_OGG
  102257. #include "include/private/ogg_helper.h"
  102258. #include "include/private/ogg_mapping.h"
  102259. #endif
  102260. /*** Start of inlined file: stream_encoder_framing.h ***/
  102261. #ifndef FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  102262. #define FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  102263. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw);
  102264. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw);
  102265. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102266. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102267. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102268. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102269. #endif
  102270. /*** End of inlined file: stream_encoder_framing.h ***/
  102271. /*** Start of inlined file: window.h ***/
  102272. #ifndef FLAC__PRIVATE__WINDOW_H
  102273. #define FLAC__PRIVATE__WINDOW_H
  102274. #ifdef HAVE_CONFIG_H
  102275. #include <config.h>
  102276. #endif
  102277. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102278. /*
  102279. * FLAC__window_*()
  102280. * --------------------------------------------------------------------
  102281. * Calculates window coefficients according to different apodization
  102282. * functions.
  102283. *
  102284. * OUT window[0,L-1]
  102285. * IN L (number of points in window)
  102286. */
  102287. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L);
  102288. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L);
  102289. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L);
  102290. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L);
  102291. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L);
  102292. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L);
  102293. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev); /* 0.0 < stddev <= 0.5 */
  102294. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L);
  102295. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L);
  102296. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L);
  102297. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L);
  102298. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L);
  102299. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L);
  102300. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p);
  102301. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L);
  102302. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  102303. #endif
  102304. /*** End of inlined file: window.h ***/
  102305. #ifndef FLaC__INLINE
  102306. #define FLaC__INLINE
  102307. #endif
  102308. #ifdef min
  102309. #undef min
  102310. #endif
  102311. #define min(x,y) ((x)<(y)?(x):(y))
  102312. #ifdef max
  102313. #undef max
  102314. #endif
  102315. #define max(x,y) ((x)>(y)?(x):(y))
  102316. /* Exact Rice codeword length calculation is off by default. The simple
  102317. * (and fast) estimation (of how many bits a residual value will be
  102318. * encoded with) in this encoder is very good, almost always yielding
  102319. * compression within 0.1% of exact calculation.
  102320. */
  102321. #undef EXACT_RICE_BITS_CALCULATION
  102322. /* Rice parameter searching is off by default. The simple (and fast)
  102323. * parameter estimation in this encoder is very good, almost always
  102324. * yielding compression within 0.1% of the optimal parameters.
  102325. */
  102326. #undef ENABLE_RICE_PARAMETER_SEARCH
  102327. typedef struct {
  102328. FLAC__int32 *data[FLAC__MAX_CHANNELS];
  102329. unsigned size; /* of each data[] in samples */
  102330. unsigned tail;
  102331. } verify_input_fifo;
  102332. typedef struct {
  102333. const FLAC__byte *data;
  102334. unsigned capacity;
  102335. unsigned bytes;
  102336. } verify_output;
  102337. typedef enum {
  102338. ENCODER_IN_MAGIC = 0,
  102339. ENCODER_IN_METADATA = 1,
  102340. ENCODER_IN_AUDIO = 2
  102341. } EncoderStateHint;
  102342. static struct CompressionLevels {
  102343. FLAC__bool do_mid_side_stereo;
  102344. FLAC__bool loose_mid_side_stereo;
  102345. unsigned max_lpc_order;
  102346. unsigned qlp_coeff_precision;
  102347. FLAC__bool do_qlp_coeff_prec_search;
  102348. FLAC__bool do_escape_coding;
  102349. FLAC__bool do_exhaustive_model_search;
  102350. unsigned min_residual_partition_order;
  102351. unsigned max_residual_partition_order;
  102352. unsigned rice_parameter_search_dist;
  102353. } compression_levels_[] = {
  102354. { false, false, 0, 0, false, false, false, 0, 3, 0 },
  102355. { true , true , 0, 0, false, false, false, 0, 3, 0 },
  102356. { true , false, 0, 0, false, false, false, 0, 3, 0 },
  102357. { false, false, 6, 0, false, false, false, 0, 4, 0 },
  102358. { true , true , 8, 0, false, false, false, 0, 4, 0 },
  102359. { true , false, 8, 0, false, false, false, 0, 5, 0 },
  102360. { true , false, 8, 0, false, false, false, 0, 6, 0 },
  102361. { true , false, 8, 0, false, false, true , 0, 6, 0 },
  102362. { true , false, 12, 0, false, false, true , 0, 6, 0 }
  102363. };
  102364. /***********************************************************************
  102365. *
  102366. * Private class method prototypes
  102367. *
  102368. ***********************************************************************/
  102369. static void set_defaults_enc(FLAC__StreamEncoder *encoder);
  102370. static void free_(FLAC__StreamEncoder *encoder);
  102371. static FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize);
  102372. static FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block);
  102373. static FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block);
  102374. static void update_metadata_(const FLAC__StreamEncoder *encoder);
  102375. #if FLAC__HAS_OGG
  102376. static void update_ogg_metadata_(FLAC__StreamEncoder *encoder);
  102377. #endif
  102378. static FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block);
  102379. static FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block);
  102380. static FLAC__bool process_subframe_(
  102381. FLAC__StreamEncoder *encoder,
  102382. unsigned min_partition_order,
  102383. unsigned max_partition_order,
  102384. const FLAC__FrameHeader *frame_header,
  102385. unsigned subframe_bps,
  102386. const FLAC__int32 integer_signal[],
  102387. FLAC__Subframe *subframe[2],
  102388. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  102389. FLAC__int32 *residual[2],
  102390. unsigned *best_subframe,
  102391. unsigned *best_bits
  102392. );
  102393. static FLAC__bool add_subframe_(
  102394. FLAC__StreamEncoder *encoder,
  102395. unsigned blocksize,
  102396. unsigned subframe_bps,
  102397. const FLAC__Subframe *subframe,
  102398. FLAC__BitWriter *frame
  102399. );
  102400. static unsigned evaluate_constant_subframe_(
  102401. FLAC__StreamEncoder *encoder,
  102402. const FLAC__int32 signal,
  102403. unsigned blocksize,
  102404. unsigned subframe_bps,
  102405. FLAC__Subframe *subframe
  102406. );
  102407. static unsigned evaluate_fixed_subframe_(
  102408. FLAC__StreamEncoder *encoder,
  102409. const FLAC__int32 signal[],
  102410. FLAC__int32 residual[],
  102411. FLAC__uint64 abs_residual_partition_sums[],
  102412. unsigned raw_bits_per_partition[],
  102413. unsigned blocksize,
  102414. unsigned subframe_bps,
  102415. unsigned order,
  102416. unsigned rice_parameter,
  102417. unsigned rice_parameter_limit,
  102418. unsigned min_partition_order,
  102419. unsigned max_partition_order,
  102420. FLAC__bool do_escape_coding,
  102421. unsigned rice_parameter_search_dist,
  102422. FLAC__Subframe *subframe,
  102423. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  102424. );
  102425. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102426. static unsigned evaluate_lpc_subframe_(
  102427. FLAC__StreamEncoder *encoder,
  102428. const FLAC__int32 signal[],
  102429. FLAC__int32 residual[],
  102430. FLAC__uint64 abs_residual_partition_sums[],
  102431. unsigned raw_bits_per_partition[],
  102432. const FLAC__real lp_coeff[],
  102433. unsigned blocksize,
  102434. unsigned subframe_bps,
  102435. unsigned order,
  102436. unsigned qlp_coeff_precision,
  102437. unsigned rice_parameter,
  102438. unsigned rice_parameter_limit,
  102439. unsigned min_partition_order,
  102440. unsigned max_partition_order,
  102441. FLAC__bool do_escape_coding,
  102442. unsigned rice_parameter_search_dist,
  102443. FLAC__Subframe *subframe,
  102444. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  102445. );
  102446. #endif
  102447. static unsigned evaluate_verbatim_subframe_(
  102448. FLAC__StreamEncoder *encoder,
  102449. const FLAC__int32 signal[],
  102450. unsigned blocksize,
  102451. unsigned subframe_bps,
  102452. FLAC__Subframe *subframe
  102453. );
  102454. static unsigned find_best_partition_order_(
  102455. struct FLAC__StreamEncoderPrivate *private_,
  102456. const FLAC__int32 residual[],
  102457. FLAC__uint64 abs_residual_partition_sums[],
  102458. unsigned raw_bits_per_partition[],
  102459. unsigned residual_samples,
  102460. unsigned predictor_order,
  102461. unsigned rice_parameter,
  102462. unsigned rice_parameter_limit,
  102463. unsigned min_partition_order,
  102464. unsigned max_partition_order,
  102465. unsigned bps,
  102466. FLAC__bool do_escape_coding,
  102467. unsigned rice_parameter_search_dist,
  102468. FLAC__EntropyCodingMethod *best_ecm
  102469. );
  102470. static void precompute_partition_info_sums_(
  102471. const FLAC__int32 residual[],
  102472. FLAC__uint64 abs_residual_partition_sums[],
  102473. unsigned residual_samples,
  102474. unsigned predictor_order,
  102475. unsigned min_partition_order,
  102476. unsigned max_partition_order,
  102477. unsigned bps
  102478. );
  102479. static void precompute_partition_info_escapes_(
  102480. const FLAC__int32 residual[],
  102481. unsigned raw_bits_per_partition[],
  102482. unsigned residual_samples,
  102483. unsigned predictor_order,
  102484. unsigned min_partition_order,
  102485. unsigned max_partition_order
  102486. );
  102487. static FLAC__bool set_partitioned_rice_(
  102488. #ifdef EXACT_RICE_BITS_CALCULATION
  102489. const FLAC__int32 residual[],
  102490. #endif
  102491. const FLAC__uint64 abs_residual_partition_sums[],
  102492. const unsigned raw_bits_per_partition[],
  102493. const unsigned residual_samples,
  102494. const unsigned predictor_order,
  102495. const unsigned suggested_rice_parameter,
  102496. const unsigned rice_parameter_limit,
  102497. const unsigned rice_parameter_search_dist,
  102498. const unsigned partition_order,
  102499. const FLAC__bool search_for_escapes,
  102500. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  102501. unsigned *bits
  102502. );
  102503. static unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples);
  102504. /* verify-related routines: */
  102505. static void append_to_verify_fifo_(
  102506. verify_input_fifo *fifo,
  102507. const FLAC__int32 * const input[],
  102508. unsigned input_offset,
  102509. unsigned channels,
  102510. unsigned wide_samples
  102511. );
  102512. static void append_to_verify_fifo_interleaved_(
  102513. verify_input_fifo *fifo,
  102514. const FLAC__int32 input[],
  102515. unsigned input_offset,
  102516. unsigned channels,
  102517. unsigned wide_samples
  102518. );
  102519. static FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  102520. static FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  102521. static void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  102522. static void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  102523. static FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  102524. static FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  102525. static FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  102526. 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);
  102527. static FILE *get_binary_stdout_(void);
  102528. /***********************************************************************
  102529. *
  102530. * Private class data
  102531. *
  102532. ***********************************************************************/
  102533. typedef struct FLAC__StreamEncoderPrivate {
  102534. unsigned input_capacity; /* current size (in samples) of the signal and residual buffers */
  102535. FLAC__int32 *integer_signal[FLAC__MAX_CHANNELS]; /* the integer version of the input signal */
  102536. FLAC__int32 *integer_signal_mid_side[2]; /* the integer version of the mid-side input signal (stereo only) */
  102537. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102538. FLAC__real *real_signal[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) the floating-point version of the input signal */
  102539. FLAC__real *real_signal_mid_side[2]; /* (@@@ currently unused) the floating-point version of the mid-side input signal (stereo only) */
  102540. FLAC__real *window[FLAC__MAX_APODIZATION_FUNCTIONS]; /* the pre-computed floating-point window for each apodization function */
  102541. FLAC__real *windowed_signal; /* the integer_signal[] * current window[] */
  102542. #endif
  102543. unsigned subframe_bps[FLAC__MAX_CHANNELS]; /* the effective bits per sample of the input signal (stream bps - wasted bits) */
  102544. unsigned subframe_bps_mid_side[2]; /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
  102545. FLAC__int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
  102546. FLAC__int32 *residual_workspace_mid_side[2][2];
  102547. FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
  102548. FLAC__Subframe subframe_workspace_mid_side[2][2];
  102549. FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
  102550. FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
  102551. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace[FLAC__MAX_CHANNELS][2];
  102552. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace_mid_side[FLAC__MAX_CHANNELS][2];
  102553. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr[FLAC__MAX_CHANNELS][2];
  102554. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr_mid_side[FLAC__MAX_CHANNELS][2];
  102555. unsigned best_subframe[FLAC__MAX_CHANNELS]; /* index (0 or 1) into 2nd dimension of the above workspaces */
  102556. unsigned best_subframe_mid_side[2];
  102557. unsigned best_subframe_bits[FLAC__MAX_CHANNELS]; /* size in bits of the best subframe for each channel */
  102558. unsigned best_subframe_bits_mid_side[2];
  102559. FLAC__uint64 *abs_residual_partition_sums; /* workspace where the sum of abs(candidate residual) for each partition is stored */
  102560. unsigned *raw_bits_per_partition; /* workspace where the sum of silog2(candidate residual) for each partition is stored */
  102561. FLAC__BitWriter *frame; /* the current frame being worked on */
  102562. unsigned loose_mid_side_stereo_frames; /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
  102563. unsigned loose_mid_side_stereo_frame_count; /* number of frames using the current channel assignment */
  102564. FLAC__ChannelAssignment last_channel_assignment;
  102565. FLAC__StreamMetadata streaminfo; /* scratchpad for STREAMINFO as it is built */
  102566. FLAC__StreamMetadata_SeekTable *seek_table; /* pointer into encoder->protected_->metadata_ where the seek table is */
  102567. unsigned current_sample_number;
  102568. unsigned current_frame_number;
  102569. FLAC__MD5Context md5context;
  102570. FLAC__CPUInfo cpuinfo;
  102571. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102572. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  102573. #else
  102574. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  102575. #endif
  102576. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102577. void (*local_lpc_compute_autocorrelation)(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  102578. 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[]);
  102579. 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[]);
  102580. 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[]);
  102581. #endif
  102582. FLAC__bool use_wide_by_block; /* use slow 64-bit versions of some functions because of the block size */
  102583. FLAC__bool use_wide_by_partition; /* use slow 64-bit versions of some functions because of the min partition order and blocksize */
  102584. FLAC__bool use_wide_by_order; /* use slow 64-bit versions of some functions because of the lpc order */
  102585. FLAC__bool disable_constant_subframes;
  102586. FLAC__bool disable_fixed_subframes;
  102587. FLAC__bool disable_verbatim_subframes;
  102588. #if FLAC__HAS_OGG
  102589. FLAC__bool is_ogg;
  102590. #endif
  102591. FLAC__StreamEncoderReadCallback read_callback; /* currently only needed for Ogg FLAC */
  102592. FLAC__StreamEncoderSeekCallback seek_callback;
  102593. FLAC__StreamEncoderTellCallback tell_callback;
  102594. FLAC__StreamEncoderWriteCallback write_callback;
  102595. FLAC__StreamEncoderMetadataCallback metadata_callback;
  102596. FLAC__StreamEncoderProgressCallback progress_callback;
  102597. void *client_data;
  102598. unsigned first_seekpoint_to_check;
  102599. FILE *file; /* only used when encoding to a file */
  102600. FLAC__uint64 bytes_written;
  102601. FLAC__uint64 samples_written;
  102602. unsigned frames_written;
  102603. unsigned total_frames_estimate;
  102604. /* unaligned (original) pointers to allocated data */
  102605. FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS];
  102606. FLAC__int32 *integer_signal_mid_side_unaligned[2];
  102607. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102608. FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) */
  102609. FLAC__real *real_signal_mid_side_unaligned[2]; /* (@@@ currently unused) */
  102610. FLAC__real *window_unaligned[FLAC__MAX_APODIZATION_FUNCTIONS];
  102611. FLAC__real *windowed_signal_unaligned;
  102612. #endif
  102613. FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2];
  102614. FLAC__int32 *residual_workspace_mid_side_unaligned[2][2];
  102615. FLAC__uint64 *abs_residual_partition_sums_unaligned;
  102616. unsigned *raw_bits_per_partition_unaligned;
  102617. /*
  102618. * These fields have been moved here from private function local
  102619. * declarations merely to save stack space during encoding.
  102620. */
  102621. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102622. FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER]; /* from process_subframe_() */
  102623. #endif
  102624. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_extra[2]; /* from find_best_partition_order_() */
  102625. /*
  102626. * The data for the verify section
  102627. */
  102628. struct {
  102629. FLAC__StreamDecoder *decoder;
  102630. EncoderStateHint state_hint;
  102631. FLAC__bool needs_magic_hack;
  102632. verify_input_fifo input_fifo;
  102633. verify_output output;
  102634. struct {
  102635. FLAC__uint64 absolute_sample;
  102636. unsigned frame_number;
  102637. unsigned channel;
  102638. unsigned sample;
  102639. FLAC__int32 expected;
  102640. FLAC__int32 got;
  102641. } error_stats;
  102642. } verify;
  102643. FLAC__bool is_being_deleted; /* if true, call to ..._finish() from ..._delete() will not call the callbacks */
  102644. } FLAC__StreamEncoderPrivate;
  102645. /***********************************************************************
  102646. *
  102647. * Public static class data
  102648. *
  102649. ***********************************************************************/
  102650. FLAC_API const char * const FLAC__StreamEncoderStateString[] = {
  102651. "FLAC__STREAM_ENCODER_OK",
  102652. "FLAC__STREAM_ENCODER_UNINITIALIZED",
  102653. "FLAC__STREAM_ENCODER_OGG_ERROR",
  102654. "FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR",
  102655. "FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA",
  102656. "FLAC__STREAM_ENCODER_CLIENT_ERROR",
  102657. "FLAC__STREAM_ENCODER_IO_ERROR",
  102658. "FLAC__STREAM_ENCODER_FRAMING_ERROR",
  102659. "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR"
  102660. };
  102661. FLAC_API const char * const FLAC__StreamEncoderInitStatusString[] = {
  102662. "FLAC__STREAM_ENCODER_INIT_STATUS_OK",
  102663. "FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR",
  102664. "FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  102665. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS",
  102666. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS",
  102667. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE",
  102668. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE",
  102669. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE",
  102670. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER",
  102671. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION",
  102672. "FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
  102673. "FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE",
  102674. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA",
  102675. "FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED"
  102676. };
  102677. FLAC_API const char * const FLAC__treamEncoderReadStatusString[] = {
  102678. "FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE",
  102679. "FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM",
  102680. "FLAC__STREAM_ENCODER_READ_STATUS_ABORT",
  102681. "FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED"
  102682. };
  102683. FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[] = {
  102684. "FLAC__STREAM_ENCODER_WRITE_STATUS_OK",
  102685. "FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR"
  102686. };
  102687. FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[] = {
  102688. "FLAC__STREAM_ENCODER_SEEK_STATUS_OK",
  102689. "FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR",
  102690. "FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED"
  102691. };
  102692. FLAC_API const char * const FLAC__StreamEncoderTellStatusString[] = {
  102693. "FLAC__STREAM_ENCODER_TELL_STATUS_OK",
  102694. "FLAC__STREAM_ENCODER_TELL_STATUS_ERROR",
  102695. "FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED"
  102696. };
  102697. /* Number of samples that will be overread to watch for end of stream. By
  102698. * 'overread', we mean that the FLAC__stream_encoder_process*() calls will
  102699. * always try to read blocksize+1 samples before encoding a block, so that
  102700. * even if the stream has a total sample count that is an integral multiple
  102701. * of the blocksize, we will still notice when we are encoding the last
  102702. * block. This is needed, for example, to correctly set the end-of-stream
  102703. * marker in Ogg FLAC.
  102704. *
  102705. * WATCHOUT: some parts of the code assert that OVERREAD_ == 1 and there's
  102706. * not really any reason to change it.
  102707. */
  102708. static const unsigned OVERREAD_ = 1;
  102709. /***********************************************************************
  102710. *
  102711. * Class constructor/destructor
  102712. *
  102713. */
  102714. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void)
  102715. {
  102716. FLAC__StreamEncoder *encoder;
  102717. unsigned i;
  102718. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  102719. encoder = (FLAC__StreamEncoder*)calloc(1, sizeof(FLAC__StreamEncoder));
  102720. if(encoder == 0) {
  102721. return 0;
  102722. }
  102723. encoder->protected_ = (FLAC__StreamEncoderProtected*)calloc(1, sizeof(FLAC__StreamEncoderProtected));
  102724. if(encoder->protected_ == 0) {
  102725. free(encoder);
  102726. return 0;
  102727. }
  102728. encoder->private_ = (FLAC__StreamEncoderPrivate*)calloc(1, sizeof(FLAC__StreamEncoderPrivate));
  102729. if(encoder->private_ == 0) {
  102730. free(encoder->protected_);
  102731. free(encoder);
  102732. return 0;
  102733. }
  102734. encoder->private_->frame = FLAC__bitwriter_new();
  102735. if(encoder->private_->frame == 0) {
  102736. free(encoder->private_);
  102737. free(encoder->protected_);
  102738. free(encoder);
  102739. return 0;
  102740. }
  102741. encoder->private_->file = 0;
  102742. set_defaults_enc(encoder);
  102743. encoder->private_->is_being_deleted = false;
  102744. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102745. encoder->private_->subframe_workspace_ptr[i][0] = &encoder->private_->subframe_workspace[i][0];
  102746. encoder->private_->subframe_workspace_ptr[i][1] = &encoder->private_->subframe_workspace[i][1];
  102747. }
  102748. for(i = 0; i < 2; i++) {
  102749. encoder->private_->subframe_workspace_ptr_mid_side[i][0] = &encoder->private_->subframe_workspace_mid_side[i][0];
  102750. encoder->private_->subframe_workspace_ptr_mid_side[i][1] = &encoder->private_->subframe_workspace_mid_side[i][1];
  102751. }
  102752. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102753. encoder->private_->partitioned_rice_contents_workspace_ptr[i][0] = &encoder->private_->partitioned_rice_contents_workspace[i][0];
  102754. encoder->private_->partitioned_rice_contents_workspace_ptr[i][1] = &encoder->private_->partitioned_rice_contents_workspace[i][1];
  102755. }
  102756. for(i = 0; i < 2; i++) {
  102757. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][0] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0];
  102758. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][1] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1];
  102759. }
  102760. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102761. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  102762. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  102763. }
  102764. for(i = 0; i < 2; i++) {
  102765. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  102766. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  102767. }
  102768. for(i = 0; i < 2; i++)
  102769. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_extra[i]);
  102770. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  102771. return encoder;
  102772. }
  102773. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder)
  102774. {
  102775. unsigned i;
  102776. FLAC__ASSERT(0 != encoder);
  102777. FLAC__ASSERT(0 != encoder->protected_);
  102778. FLAC__ASSERT(0 != encoder->private_);
  102779. FLAC__ASSERT(0 != encoder->private_->frame);
  102780. encoder->private_->is_being_deleted = true;
  102781. (void)FLAC__stream_encoder_finish(encoder);
  102782. if(0 != encoder->private_->verify.decoder)
  102783. FLAC__stream_decoder_delete(encoder->private_->verify.decoder);
  102784. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102785. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  102786. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  102787. }
  102788. for(i = 0; i < 2; i++) {
  102789. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  102790. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  102791. }
  102792. for(i = 0; i < 2; i++)
  102793. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_extra[i]);
  102794. FLAC__bitwriter_delete(encoder->private_->frame);
  102795. free(encoder->private_);
  102796. free(encoder->protected_);
  102797. free(encoder);
  102798. }
  102799. /***********************************************************************
  102800. *
  102801. * Public class methods
  102802. *
  102803. ***********************************************************************/
  102804. static FLAC__StreamEncoderInitStatus init_stream_internal_enc(
  102805. FLAC__StreamEncoder *encoder,
  102806. FLAC__StreamEncoderReadCallback read_callback,
  102807. FLAC__StreamEncoderWriteCallback write_callback,
  102808. FLAC__StreamEncoderSeekCallback seek_callback,
  102809. FLAC__StreamEncoderTellCallback tell_callback,
  102810. FLAC__StreamEncoderMetadataCallback metadata_callback,
  102811. void *client_data,
  102812. FLAC__bool is_ogg
  102813. )
  102814. {
  102815. unsigned i;
  102816. FLAC__bool metadata_has_seektable, metadata_has_vorbis_comment, metadata_picture_has_type1, metadata_picture_has_type2;
  102817. FLAC__ASSERT(0 != encoder);
  102818. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102819. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  102820. #if !FLAC__HAS_OGG
  102821. if(is_ogg)
  102822. return FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  102823. #endif
  102824. if(0 == write_callback || (seek_callback && 0 == tell_callback))
  102825. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS;
  102826. if(encoder->protected_->channels == 0 || encoder->protected_->channels > FLAC__MAX_CHANNELS)
  102827. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS;
  102828. if(encoder->protected_->channels != 2) {
  102829. encoder->protected_->do_mid_side_stereo = false;
  102830. encoder->protected_->loose_mid_side_stereo = false;
  102831. }
  102832. else if(!encoder->protected_->do_mid_side_stereo)
  102833. encoder->protected_->loose_mid_side_stereo = false;
  102834. if(encoder->protected_->bits_per_sample >= 32)
  102835. encoder->protected_->do_mid_side_stereo = false; /* since we currenty do 32-bit math, the side channel would have 33 bps and overflow */
  102836. if(encoder->protected_->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->protected_->bits_per_sample > FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE)
  102837. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE;
  102838. if(!FLAC__format_sample_rate_is_valid(encoder->protected_->sample_rate))
  102839. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE;
  102840. if(encoder->protected_->blocksize == 0) {
  102841. if(encoder->protected_->max_lpc_order == 0)
  102842. encoder->protected_->blocksize = 1152;
  102843. else
  102844. encoder->protected_->blocksize = 4096;
  102845. }
  102846. if(encoder->protected_->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->protected_->blocksize > FLAC__MAX_BLOCK_SIZE)
  102847. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE;
  102848. if(encoder->protected_->max_lpc_order > FLAC__MAX_LPC_ORDER)
  102849. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER;
  102850. if(encoder->protected_->blocksize < encoder->protected_->max_lpc_order)
  102851. return FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
  102852. if(encoder->protected_->qlp_coeff_precision == 0) {
  102853. if(encoder->protected_->bits_per_sample < 16) {
  102854. /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
  102855. /* @@@ until then we'll make a guess */
  102856. encoder->protected_->qlp_coeff_precision = max(FLAC__MIN_QLP_COEFF_PRECISION, 2 + encoder->protected_->bits_per_sample / 2);
  102857. }
  102858. else if(encoder->protected_->bits_per_sample == 16) {
  102859. if(encoder->protected_->blocksize <= 192)
  102860. encoder->protected_->qlp_coeff_precision = 7;
  102861. else if(encoder->protected_->blocksize <= 384)
  102862. encoder->protected_->qlp_coeff_precision = 8;
  102863. else if(encoder->protected_->blocksize <= 576)
  102864. encoder->protected_->qlp_coeff_precision = 9;
  102865. else if(encoder->protected_->blocksize <= 1152)
  102866. encoder->protected_->qlp_coeff_precision = 10;
  102867. else if(encoder->protected_->blocksize <= 2304)
  102868. encoder->protected_->qlp_coeff_precision = 11;
  102869. else if(encoder->protected_->blocksize <= 4608)
  102870. encoder->protected_->qlp_coeff_precision = 12;
  102871. else
  102872. encoder->protected_->qlp_coeff_precision = 13;
  102873. }
  102874. else {
  102875. if(encoder->protected_->blocksize <= 384)
  102876. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-2;
  102877. else if(encoder->protected_->blocksize <= 1152)
  102878. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-1;
  102879. else
  102880. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  102881. }
  102882. FLAC__ASSERT(encoder->protected_->qlp_coeff_precision <= FLAC__MAX_QLP_COEFF_PRECISION);
  102883. }
  102884. else if(encoder->protected_->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->protected_->qlp_coeff_precision > FLAC__MAX_QLP_COEFF_PRECISION)
  102885. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION;
  102886. if(encoder->protected_->streamable_subset) {
  102887. if(
  102888. encoder->protected_->blocksize != 192 &&
  102889. encoder->protected_->blocksize != 576 &&
  102890. encoder->protected_->blocksize != 1152 &&
  102891. encoder->protected_->blocksize != 2304 &&
  102892. encoder->protected_->blocksize != 4608 &&
  102893. encoder->protected_->blocksize != 256 &&
  102894. encoder->protected_->blocksize != 512 &&
  102895. encoder->protected_->blocksize != 1024 &&
  102896. encoder->protected_->blocksize != 2048 &&
  102897. encoder->protected_->blocksize != 4096 &&
  102898. encoder->protected_->blocksize != 8192 &&
  102899. encoder->protected_->blocksize != 16384
  102900. )
  102901. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102902. if(!FLAC__format_sample_rate_is_subset(encoder->protected_->sample_rate))
  102903. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102904. if(
  102905. encoder->protected_->bits_per_sample != 8 &&
  102906. encoder->protected_->bits_per_sample != 12 &&
  102907. encoder->protected_->bits_per_sample != 16 &&
  102908. encoder->protected_->bits_per_sample != 20 &&
  102909. encoder->protected_->bits_per_sample != 24
  102910. )
  102911. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102912. if(encoder->protected_->max_residual_partition_order > FLAC__SUBSET_MAX_RICE_PARTITION_ORDER)
  102913. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102914. if(
  102915. encoder->protected_->sample_rate <= 48000 &&
  102916. (
  102917. encoder->protected_->blocksize > FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ ||
  102918. encoder->protected_->max_lpc_order > FLAC__SUBSET_MAX_LPC_ORDER_48000HZ
  102919. )
  102920. ) {
  102921. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102922. }
  102923. }
  102924. if(encoder->protected_->max_residual_partition_order >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  102925. encoder->protected_->max_residual_partition_order = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
  102926. if(encoder->protected_->min_residual_partition_order >= encoder->protected_->max_residual_partition_order)
  102927. encoder->protected_->min_residual_partition_order = encoder->protected_->max_residual_partition_order;
  102928. #if FLAC__HAS_OGG
  102929. /* reorder metadata if necessary to ensure that any VORBIS_COMMENT is the first, according to the mapping spec */
  102930. if(is_ogg && 0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 1) {
  102931. unsigned i;
  102932. for(i = 1; i < encoder->protected_->num_metadata_blocks; i++) {
  102933. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  102934. FLAC__StreamMetadata *vc = encoder->protected_->metadata[i];
  102935. for( ; i > 0; i--)
  102936. encoder->protected_->metadata[i] = encoder->protected_->metadata[i-1];
  102937. encoder->protected_->metadata[0] = vc;
  102938. break;
  102939. }
  102940. }
  102941. }
  102942. #endif
  102943. /* keep track of any SEEKTABLE block */
  102944. if(0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0) {
  102945. unsigned i;
  102946. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  102947. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  102948. encoder->private_->seek_table = &encoder->protected_->metadata[i]->data.seek_table;
  102949. break; /* take only the first one */
  102950. }
  102951. }
  102952. }
  102953. /* validate metadata */
  102954. if(0 == encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0)
  102955. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102956. metadata_has_seektable = false;
  102957. metadata_has_vorbis_comment = false;
  102958. metadata_picture_has_type1 = false;
  102959. metadata_picture_has_type2 = false;
  102960. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  102961. const FLAC__StreamMetadata *m = encoder->protected_->metadata[i];
  102962. if(m->type == FLAC__METADATA_TYPE_STREAMINFO)
  102963. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102964. else if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  102965. if(metadata_has_seektable) /* only one is allowed */
  102966. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102967. metadata_has_seektable = true;
  102968. if(!FLAC__format_seektable_is_legal(&m->data.seek_table))
  102969. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102970. }
  102971. else if(m->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  102972. if(metadata_has_vorbis_comment) /* only one is allowed */
  102973. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102974. metadata_has_vorbis_comment = true;
  102975. }
  102976. else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
  102977. if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0))
  102978. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102979. }
  102980. else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
  102981. if(!FLAC__format_picture_is_legal(&m->data.picture, /*violation=*/0))
  102982. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102983. if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
  102984. if(metadata_picture_has_type1) /* there should only be 1 per stream */
  102985. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102986. metadata_picture_has_type1 = true;
  102987. /* standard icon must be 32x32 pixel PNG */
  102988. if(
  102989. m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD &&
  102990. (
  102991. (strcmp(m->data.picture.mime_type, "image/png") && strcmp(m->data.picture.mime_type, "-->")) ||
  102992. m->data.picture.width != 32 ||
  102993. m->data.picture.height != 32
  102994. )
  102995. )
  102996. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102997. }
  102998. else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
  102999. if(metadata_picture_has_type2) /* there should only be 1 per stream */
  103000. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103001. metadata_picture_has_type2 = true;
  103002. }
  103003. }
  103004. }
  103005. encoder->private_->input_capacity = 0;
  103006. for(i = 0; i < encoder->protected_->channels; i++) {
  103007. encoder->private_->integer_signal_unaligned[i] = encoder->private_->integer_signal[i] = 0;
  103008. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103009. encoder->private_->real_signal_unaligned[i] = encoder->private_->real_signal[i] = 0;
  103010. #endif
  103011. }
  103012. for(i = 0; i < 2; i++) {
  103013. encoder->private_->integer_signal_mid_side_unaligned[i] = encoder->private_->integer_signal_mid_side[i] = 0;
  103014. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103015. encoder->private_->real_signal_mid_side_unaligned[i] = encoder->private_->real_signal_mid_side[i] = 0;
  103016. #endif
  103017. }
  103018. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103019. for(i = 0; i < encoder->protected_->num_apodizations; i++)
  103020. encoder->private_->window_unaligned[i] = encoder->private_->window[i] = 0;
  103021. encoder->private_->windowed_signal_unaligned = encoder->private_->windowed_signal = 0;
  103022. #endif
  103023. for(i = 0; i < encoder->protected_->channels; i++) {
  103024. encoder->private_->residual_workspace_unaligned[i][0] = encoder->private_->residual_workspace[i][0] = 0;
  103025. encoder->private_->residual_workspace_unaligned[i][1] = encoder->private_->residual_workspace[i][1] = 0;
  103026. encoder->private_->best_subframe[i] = 0;
  103027. }
  103028. for(i = 0; i < 2; i++) {
  103029. encoder->private_->residual_workspace_mid_side_unaligned[i][0] = encoder->private_->residual_workspace_mid_side[i][0] = 0;
  103030. encoder->private_->residual_workspace_mid_side_unaligned[i][1] = encoder->private_->residual_workspace_mid_side[i][1] = 0;
  103031. encoder->private_->best_subframe_mid_side[i] = 0;
  103032. }
  103033. encoder->private_->abs_residual_partition_sums_unaligned = encoder->private_->abs_residual_partition_sums = 0;
  103034. encoder->private_->raw_bits_per_partition_unaligned = encoder->private_->raw_bits_per_partition = 0;
  103035. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103036. encoder->private_->loose_mid_side_stereo_frames = (unsigned)((FLAC__double)encoder->protected_->sample_rate * 0.4 / (FLAC__double)encoder->protected_->blocksize + 0.5);
  103037. #else
  103038. /* 26214 is the approximate fixed-point equivalent to 0.4 (0.4 * 2^16) */
  103039. /* sample rate can be up to 655350 Hz, and thus use 20 bits, so we do the multiply&divide by hand */
  103040. FLAC__ASSERT(FLAC__MAX_SAMPLE_RATE <= 655350);
  103041. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535);
  103042. FLAC__ASSERT(encoder->protected_->sample_rate <= 655350);
  103043. FLAC__ASSERT(encoder->protected_->blocksize <= 65535);
  103044. 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);
  103045. #endif
  103046. if(encoder->private_->loose_mid_side_stereo_frames == 0)
  103047. encoder->private_->loose_mid_side_stereo_frames = 1;
  103048. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  103049. encoder->private_->current_sample_number = 0;
  103050. encoder->private_->current_frame_number = 0;
  103051. encoder->private_->use_wide_by_block = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(encoder->protected_->blocksize)+1 > 30);
  103052. 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? */
  103053. encoder->private_->use_wide_by_partition = (false); /*@@@ need to set this */
  103054. /*
  103055. * get the CPU info and set the function pointers
  103056. */
  103057. FLAC__cpu_info(&encoder->private_->cpuinfo);
  103058. /* first default to the non-asm routines */
  103059. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103060. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
  103061. #endif
  103062. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor;
  103063. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103064. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients;
  103065. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide;
  103066. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients;
  103067. #endif
  103068. /* now override with asm where appropriate */
  103069. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103070. # ifndef FLAC__NO_ASM
  103071. if(encoder->private_->cpuinfo.use_asm) {
  103072. # ifdef FLAC__CPU_IA32
  103073. FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  103074. # ifdef FLAC__HAS_NASM
  103075. if(encoder->private_->cpuinfo.data.ia32.sse) {
  103076. if(encoder->protected_->max_lpc_order < 4)
  103077. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4;
  103078. else if(encoder->protected_->max_lpc_order < 8)
  103079. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8;
  103080. else if(encoder->protected_->max_lpc_order < 12)
  103081. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12;
  103082. else
  103083. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  103084. }
  103085. else if(encoder->private_->cpuinfo.data.ia32._3dnow)
  103086. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow;
  103087. else
  103088. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  103089. if(encoder->private_->cpuinfo.data.ia32.mmx) {
  103090. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  103091. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
  103092. }
  103093. else {
  103094. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  103095. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  103096. }
  103097. if(encoder->private_->cpuinfo.data.ia32.mmx && encoder->private_->cpuinfo.data.ia32.cmov)
  103098. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
  103099. # endif /* FLAC__HAS_NASM */
  103100. # endif /* FLAC__CPU_IA32 */
  103101. }
  103102. # endif /* !FLAC__NO_ASM */
  103103. #endif /* !FLAC__INTEGER_ONLY_LIBRARY */
  103104. /* finally override based on wide-ness if necessary */
  103105. if(encoder->private_->use_wide_by_block) {
  103106. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_wide;
  103107. }
  103108. /* set state to OK; from here on, errors are fatal and we'll override the state then */
  103109. encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
  103110. #if FLAC__HAS_OGG
  103111. encoder->private_->is_ogg = is_ogg;
  103112. if(is_ogg && !FLAC__ogg_encoder_aspect_init(&encoder->protected_->ogg_encoder_aspect)) {
  103113. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  103114. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103115. }
  103116. #endif
  103117. encoder->private_->read_callback = read_callback;
  103118. encoder->private_->write_callback = write_callback;
  103119. encoder->private_->seek_callback = seek_callback;
  103120. encoder->private_->tell_callback = tell_callback;
  103121. encoder->private_->metadata_callback = metadata_callback;
  103122. encoder->private_->client_data = client_data;
  103123. if(!resize_buffers_(encoder, encoder->protected_->blocksize)) {
  103124. /* the above function sets the state for us in case of an error */
  103125. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103126. }
  103127. if(!FLAC__bitwriter_init(encoder->private_->frame)) {
  103128. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  103129. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103130. }
  103131. /*
  103132. * Set up the verify stuff if necessary
  103133. */
  103134. if(encoder->protected_->verify) {
  103135. /*
  103136. * First, set up the fifo which will hold the
  103137. * original signal to compare against
  103138. */
  103139. encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize+OVERREAD_;
  103140. for(i = 0; i < encoder->protected_->channels; i++) {
  103141. 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))) {
  103142. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  103143. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103144. }
  103145. }
  103146. encoder->private_->verify.input_fifo.tail = 0;
  103147. /*
  103148. * Now set up a stream decoder for verification
  103149. */
  103150. encoder->private_->verify.decoder = FLAC__stream_decoder_new();
  103151. if(0 == encoder->private_->verify.decoder) {
  103152. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  103153. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103154. }
  103155. 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) {
  103156. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  103157. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103158. }
  103159. }
  103160. encoder->private_->verify.error_stats.absolute_sample = 0;
  103161. encoder->private_->verify.error_stats.frame_number = 0;
  103162. encoder->private_->verify.error_stats.channel = 0;
  103163. encoder->private_->verify.error_stats.sample = 0;
  103164. encoder->private_->verify.error_stats.expected = 0;
  103165. encoder->private_->verify.error_stats.got = 0;
  103166. /*
  103167. * These must be done before we write any metadata, because that
  103168. * calls the write_callback, which uses these values.
  103169. */
  103170. encoder->private_->first_seekpoint_to_check = 0;
  103171. encoder->private_->samples_written = 0;
  103172. encoder->protected_->streaminfo_offset = 0;
  103173. encoder->protected_->seektable_offset = 0;
  103174. encoder->protected_->audio_offset = 0;
  103175. /*
  103176. * write the stream header
  103177. */
  103178. if(encoder->protected_->verify)
  103179. encoder->private_->verify.state_hint = ENCODER_IN_MAGIC;
  103180. if(!FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN)) {
  103181. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103182. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103183. }
  103184. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  103185. /* the above function sets the state for us in case of an error */
  103186. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103187. }
  103188. /*
  103189. * write the STREAMINFO metadata block
  103190. */
  103191. if(encoder->protected_->verify)
  103192. encoder->private_->verify.state_hint = ENCODER_IN_METADATA;
  103193. encoder->private_->streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO;
  103194. encoder->private_->streaminfo.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
  103195. encoder->private_->streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
  103196. encoder->private_->streaminfo.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
  103197. encoder->private_->streaminfo.data.stream_info.max_blocksize = encoder->protected_->blocksize;
  103198. encoder->private_->streaminfo.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
  103199. encoder->private_->streaminfo.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
  103200. encoder->private_->streaminfo.data.stream_info.sample_rate = encoder->protected_->sample_rate;
  103201. encoder->private_->streaminfo.data.stream_info.channels = encoder->protected_->channels;
  103202. encoder->private_->streaminfo.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
  103203. encoder->private_->streaminfo.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
  103204. memset(encoder->private_->streaminfo.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
  103205. if(encoder->protected_->do_md5)
  103206. FLAC__MD5Init(&encoder->private_->md5context);
  103207. if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) {
  103208. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103209. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103210. }
  103211. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  103212. /* the above function sets the state for us in case of an error */
  103213. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103214. }
  103215. /*
  103216. * Now that the STREAMINFO block is written, we can init this to an
  103217. * absurdly-high value...
  103218. */
  103219. encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
  103220. /* ... and clear this to 0 */
  103221. encoder->private_->streaminfo.data.stream_info.total_samples = 0;
  103222. /*
  103223. * Check to see if the supplied metadata contains a VORBIS_COMMENT;
  103224. * if not, we will write an empty one (FLAC__add_metadata_block()
  103225. * automatically supplies the vendor string).
  103226. *
  103227. * WATCHOUT: the Ogg FLAC mapping requires us to write this block after
  103228. * the STREAMINFO. (In the case that metadata_has_vorbis_comment is
  103229. * true it will have already insured that the metadata list is properly
  103230. * ordered.)
  103231. */
  103232. if(!metadata_has_vorbis_comment) {
  103233. FLAC__StreamMetadata vorbis_comment;
  103234. vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
  103235. vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0);
  103236. vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */
  103237. vorbis_comment.data.vorbis_comment.vendor_string.length = 0;
  103238. vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
  103239. vorbis_comment.data.vorbis_comment.num_comments = 0;
  103240. vorbis_comment.data.vorbis_comment.comments = 0;
  103241. if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame)) {
  103242. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103243. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103244. }
  103245. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  103246. /* the above function sets the state for us in case of an error */
  103247. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103248. }
  103249. }
  103250. /*
  103251. * write the user's metadata blocks
  103252. */
  103253. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  103254. encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
  103255. if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame)) {
  103256. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103257. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103258. }
  103259. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  103260. /* the above function sets the state for us in case of an error */
  103261. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103262. }
  103263. }
  103264. /* now that all the metadata is written, we save the stream offset */
  103265. 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 */
  103266. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103267. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103268. }
  103269. if(encoder->protected_->verify)
  103270. encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
  103271. return FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  103272. }
  103273. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(
  103274. FLAC__StreamEncoder *encoder,
  103275. FLAC__StreamEncoderWriteCallback write_callback,
  103276. FLAC__StreamEncoderSeekCallback seek_callback,
  103277. FLAC__StreamEncoderTellCallback tell_callback,
  103278. FLAC__StreamEncoderMetadataCallback metadata_callback,
  103279. void *client_data
  103280. )
  103281. {
  103282. return init_stream_internal_enc(
  103283. encoder,
  103284. /*read_callback=*/0,
  103285. write_callback,
  103286. seek_callback,
  103287. tell_callback,
  103288. metadata_callback,
  103289. client_data,
  103290. /*is_ogg=*/false
  103291. );
  103292. }
  103293. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(
  103294. FLAC__StreamEncoder *encoder,
  103295. FLAC__StreamEncoderReadCallback read_callback,
  103296. FLAC__StreamEncoderWriteCallback write_callback,
  103297. FLAC__StreamEncoderSeekCallback seek_callback,
  103298. FLAC__StreamEncoderTellCallback tell_callback,
  103299. FLAC__StreamEncoderMetadataCallback metadata_callback,
  103300. void *client_data
  103301. )
  103302. {
  103303. return init_stream_internal_enc(
  103304. encoder,
  103305. read_callback,
  103306. write_callback,
  103307. seek_callback,
  103308. tell_callback,
  103309. metadata_callback,
  103310. client_data,
  103311. /*is_ogg=*/true
  103312. );
  103313. }
  103314. static FLAC__StreamEncoderInitStatus init_FILE_internal_enc(
  103315. FLAC__StreamEncoder *encoder,
  103316. FILE *file,
  103317. FLAC__StreamEncoderProgressCallback progress_callback,
  103318. void *client_data,
  103319. FLAC__bool is_ogg
  103320. )
  103321. {
  103322. FLAC__StreamEncoderInitStatus init_status;
  103323. FLAC__ASSERT(0 != encoder);
  103324. FLAC__ASSERT(0 != file);
  103325. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103326. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  103327. /* double protection */
  103328. if(file == 0) {
  103329. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  103330. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103331. }
  103332. /*
  103333. * To make sure that our file does not go unclosed after an error, we
  103334. * must assign the FILE pointer before any further error can occur in
  103335. * this routine.
  103336. */
  103337. if(file == stdout)
  103338. file = get_binary_stdout_(); /* just to be safe */
  103339. encoder->private_->file = file;
  103340. encoder->private_->progress_callback = progress_callback;
  103341. encoder->private_->bytes_written = 0;
  103342. encoder->private_->samples_written = 0;
  103343. encoder->private_->frames_written = 0;
  103344. init_status = init_stream_internal_enc(
  103345. encoder,
  103346. encoder->private_->file == stdout? 0 : is_ogg? file_read_callback_enc : 0,
  103347. file_write_callback_,
  103348. encoder->private_->file == stdout? 0 : file_seek_callback_enc,
  103349. encoder->private_->file == stdout? 0 : file_tell_callback_enc,
  103350. /*metadata_callback=*/0,
  103351. client_data,
  103352. is_ogg
  103353. );
  103354. if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
  103355. /* the above function sets the state for us in case of an error */
  103356. return init_status;
  103357. }
  103358. {
  103359. unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  103360. FLAC__ASSERT(blocksize != 0);
  103361. encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
  103362. }
  103363. return init_status;
  103364. }
  103365. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(
  103366. FLAC__StreamEncoder *encoder,
  103367. FILE *file,
  103368. FLAC__StreamEncoderProgressCallback progress_callback,
  103369. void *client_data
  103370. )
  103371. {
  103372. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/false);
  103373. }
  103374. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(
  103375. FLAC__StreamEncoder *encoder,
  103376. FILE *file,
  103377. FLAC__StreamEncoderProgressCallback progress_callback,
  103378. void *client_data
  103379. )
  103380. {
  103381. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/true);
  103382. }
  103383. static FLAC__StreamEncoderInitStatus init_file_internal_enc(
  103384. FLAC__StreamEncoder *encoder,
  103385. const char *filename,
  103386. FLAC__StreamEncoderProgressCallback progress_callback,
  103387. void *client_data,
  103388. FLAC__bool is_ogg
  103389. )
  103390. {
  103391. FILE *file;
  103392. FLAC__ASSERT(0 != encoder);
  103393. /*
  103394. * To make sure that our file does not go unclosed after an error, we
  103395. * have to do the same entrance checks here that are later performed
  103396. * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
  103397. */
  103398. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103399. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  103400. file = filename? fopen(filename, "w+b") : stdout;
  103401. if(file == 0) {
  103402. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  103403. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103404. }
  103405. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, is_ogg);
  103406. }
  103407. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(
  103408. FLAC__StreamEncoder *encoder,
  103409. const char *filename,
  103410. FLAC__StreamEncoderProgressCallback progress_callback,
  103411. void *client_data
  103412. )
  103413. {
  103414. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/false);
  103415. }
  103416. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(
  103417. FLAC__StreamEncoder *encoder,
  103418. const char *filename,
  103419. FLAC__StreamEncoderProgressCallback progress_callback,
  103420. void *client_data
  103421. )
  103422. {
  103423. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/true);
  103424. }
  103425. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
  103426. {
  103427. FLAC__bool error = false;
  103428. FLAC__ASSERT(0 != encoder);
  103429. FLAC__ASSERT(0 != encoder->private_);
  103430. FLAC__ASSERT(0 != encoder->protected_);
  103431. if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
  103432. return true;
  103433. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
  103434. if(encoder->private_->current_sample_number != 0) {
  103435. const FLAC__bool is_fractional_block = encoder->protected_->blocksize != encoder->private_->current_sample_number;
  103436. encoder->protected_->blocksize = encoder->private_->current_sample_number;
  103437. if(!process_frame_(encoder, is_fractional_block, /*is_last_block=*/true))
  103438. error = true;
  103439. }
  103440. }
  103441. if(encoder->protected_->do_md5)
  103442. FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
  103443. if(!encoder->private_->is_being_deleted) {
  103444. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK) {
  103445. if(encoder->private_->seek_callback) {
  103446. #if FLAC__HAS_OGG
  103447. if(encoder->private_->is_ogg)
  103448. update_ogg_metadata_(encoder);
  103449. else
  103450. #endif
  103451. update_metadata_(encoder);
  103452. /* check if an error occurred while updating metadata */
  103453. if(encoder->protected_->state != FLAC__STREAM_ENCODER_OK)
  103454. error = true;
  103455. }
  103456. if(encoder->private_->metadata_callback)
  103457. encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
  103458. }
  103459. if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder && !FLAC__stream_decoder_finish(encoder->private_->verify.decoder)) {
  103460. if(!error)
  103461. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  103462. error = true;
  103463. }
  103464. }
  103465. if(0 != encoder->private_->file) {
  103466. if(encoder->private_->file != stdout)
  103467. fclose(encoder->private_->file);
  103468. encoder->private_->file = 0;
  103469. }
  103470. #if FLAC__HAS_OGG
  103471. if(encoder->private_->is_ogg)
  103472. FLAC__ogg_encoder_aspect_finish(&encoder->protected_->ogg_encoder_aspect);
  103473. #endif
  103474. free_(encoder);
  103475. set_defaults_enc(encoder);
  103476. if(!error)
  103477. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  103478. return !error;
  103479. }
  103480. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long value)
  103481. {
  103482. FLAC__ASSERT(0 != encoder);
  103483. FLAC__ASSERT(0 != encoder->private_);
  103484. FLAC__ASSERT(0 != encoder->protected_);
  103485. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103486. return false;
  103487. #if FLAC__HAS_OGG
  103488. /* can't check encoder->private_->is_ogg since that's not set until init time */
  103489. FLAC__ogg_encoder_aspect_set_serial_number(&encoder->protected_->ogg_encoder_aspect, value);
  103490. return true;
  103491. #else
  103492. (void)value;
  103493. return false;
  103494. #endif
  103495. }
  103496. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103497. {
  103498. FLAC__ASSERT(0 != encoder);
  103499. FLAC__ASSERT(0 != encoder->private_);
  103500. FLAC__ASSERT(0 != encoder->protected_);
  103501. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103502. return false;
  103503. #ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  103504. encoder->protected_->verify = value;
  103505. #endif
  103506. return true;
  103507. }
  103508. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103509. {
  103510. FLAC__ASSERT(0 != encoder);
  103511. FLAC__ASSERT(0 != encoder->private_);
  103512. FLAC__ASSERT(0 != encoder->protected_);
  103513. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103514. return false;
  103515. encoder->protected_->streamable_subset = value;
  103516. return true;
  103517. }
  103518. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_md5(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103519. {
  103520. FLAC__ASSERT(0 != encoder);
  103521. FLAC__ASSERT(0 != encoder->private_);
  103522. FLAC__ASSERT(0 != encoder->protected_);
  103523. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103524. return false;
  103525. encoder->protected_->do_md5 = value;
  103526. return true;
  103527. }
  103528. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value)
  103529. {
  103530. FLAC__ASSERT(0 != encoder);
  103531. FLAC__ASSERT(0 != encoder->private_);
  103532. FLAC__ASSERT(0 != encoder->protected_);
  103533. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103534. return false;
  103535. encoder->protected_->channels = value;
  103536. return true;
  103537. }
  103538. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value)
  103539. {
  103540. FLAC__ASSERT(0 != encoder);
  103541. FLAC__ASSERT(0 != encoder->private_);
  103542. FLAC__ASSERT(0 != encoder->protected_);
  103543. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103544. return false;
  103545. encoder->protected_->bits_per_sample = value;
  103546. return true;
  103547. }
  103548. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
  103549. {
  103550. FLAC__ASSERT(0 != encoder);
  103551. FLAC__ASSERT(0 != encoder->private_);
  103552. FLAC__ASSERT(0 != encoder->protected_);
  103553. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103554. return false;
  103555. encoder->protected_->sample_rate = value;
  103556. return true;
  103557. }
  103558. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value)
  103559. {
  103560. FLAC__bool ok = true;
  103561. FLAC__ASSERT(0 != encoder);
  103562. FLAC__ASSERT(0 != encoder->private_);
  103563. FLAC__ASSERT(0 != encoder->protected_);
  103564. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103565. return false;
  103566. if(value >= sizeof(compression_levels_)/sizeof(compression_levels_[0]))
  103567. value = sizeof(compression_levels_)/sizeof(compression_levels_[0]) - 1;
  103568. ok &= FLAC__stream_encoder_set_do_mid_side_stereo (encoder, compression_levels_[value].do_mid_side_stereo);
  103569. ok &= FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, compression_levels_[value].loose_mid_side_stereo);
  103570. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103571. #if 0
  103572. /* was: */
  103573. ok &= FLAC__stream_encoder_set_apodization (encoder, compression_levels_[value].apodization);
  103574. /* but it's too hard to specify the string in a locale-specific way */
  103575. #else
  103576. encoder->protected_->num_apodizations = 1;
  103577. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  103578. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  103579. #endif
  103580. #endif
  103581. ok &= FLAC__stream_encoder_set_max_lpc_order (encoder, compression_levels_[value].max_lpc_order);
  103582. ok &= FLAC__stream_encoder_set_qlp_coeff_precision (encoder, compression_levels_[value].qlp_coeff_precision);
  103583. ok &= FLAC__stream_encoder_set_do_qlp_coeff_prec_search (encoder, compression_levels_[value].do_qlp_coeff_prec_search);
  103584. ok &= FLAC__stream_encoder_set_do_escape_coding (encoder, compression_levels_[value].do_escape_coding);
  103585. ok &= FLAC__stream_encoder_set_do_exhaustive_model_search (encoder, compression_levels_[value].do_exhaustive_model_search);
  103586. ok &= FLAC__stream_encoder_set_min_residual_partition_order(encoder, compression_levels_[value].min_residual_partition_order);
  103587. ok &= FLAC__stream_encoder_set_max_residual_partition_order(encoder, compression_levels_[value].max_residual_partition_order);
  103588. ok &= FLAC__stream_encoder_set_rice_parameter_search_dist (encoder, compression_levels_[value].rice_parameter_search_dist);
  103589. return ok;
  103590. }
  103591. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
  103592. {
  103593. FLAC__ASSERT(0 != encoder);
  103594. FLAC__ASSERT(0 != encoder->private_);
  103595. FLAC__ASSERT(0 != encoder->protected_);
  103596. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103597. return false;
  103598. encoder->protected_->blocksize = value;
  103599. return true;
  103600. }
  103601. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103602. {
  103603. FLAC__ASSERT(0 != encoder);
  103604. FLAC__ASSERT(0 != encoder->private_);
  103605. FLAC__ASSERT(0 != encoder->protected_);
  103606. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103607. return false;
  103608. encoder->protected_->do_mid_side_stereo = value;
  103609. return true;
  103610. }
  103611. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103612. {
  103613. FLAC__ASSERT(0 != encoder);
  103614. FLAC__ASSERT(0 != encoder->private_);
  103615. FLAC__ASSERT(0 != encoder->protected_);
  103616. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103617. return false;
  103618. encoder->protected_->loose_mid_side_stereo = value;
  103619. return true;
  103620. }
  103621. /*@@@@add to tests*/
  103622. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
  103623. {
  103624. FLAC__ASSERT(0 != encoder);
  103625. FLAC__ASSERT(0 != encoder->private_);
  103626. FLAC__ASSERT(0 != encoder->protected_);
  103627. FLAC__ASSERT(0 != specification);
  103628. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103629. return false;
  103630. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  103631. (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
  103632. #else
  103633. encoder->protected_->num_apodizations = 0;
  103634. while(1) {
  103635. const char *s = strchr(specification, ';');
  103636. const size_t n = s? (size_t)(s - specification) : strlen(specification);
  103637. if (n==8 && 0 == strncmp("bartlett" , specification, n))
  103638. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
  103639. else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
  103640. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
  103641. else if(n==8 && 0 == strncmp("blackman" , specification, n))
  103642. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
  103643. else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
  103644. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
  103645. else if(n==6 && 0 == strncmp("connes" , specification, n))
  103646. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
  103647. else if(n==7 && 0 == strncmp("flattop" , specification, n))
  103648. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
  103649. else if(n>7 && 0 == strncmp("gauss(" , specification, 6)) {
  103650. FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
  103651. if (stddev > 0.0 && stddev <= 0.5) {
  103652. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
  103653. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
  103654. }
  103655. }
  103656. else if(n==7 && 0 == strncmp("hamming" , specification, n))
  103657. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
  103658. else if(n==4 && 0 == strncmp("hann" , specification, n))
  103659. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
  103660. else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
  103661. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
  103662. else if(n==7 && 0 == strncmp("nuttall" , specification, n))
  103663. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
  103664. else if(n==9 && 0 == strncmp("rectangle" , specification, n))
  103665. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
  103666. else if(n==8 && 0 == strncmp("triangle" , specification, n))
  103667. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
  103668. else if(n>7 && 0 == strncmp("tukey(" , specification, 6)) {
  103669. FLAC__real p = (FLAC__real)strtod(specification+6, 0);
  103670. if (p >= 0.0 && p <= 1.0) {
  103671. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
  103672. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
  103673. }
  103674. }
  103675. else if(n==5 && 0 == strncmp("welch" , specification, n))
  103676. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
  103677. if (encoder->protected_->num_apodizations == 32)
  103678. break;
  103679. if (s)
  103680. specification = s+1;
  103681. else
  103682. break;
  103683. }
  103684. if(encoder->protected_->num_apodizations == 0) {
  103685. encoder->protected_->num_apodizations = 1;
  103686. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  103687. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  103688. }
  103689. #endif
  103690. return true;
  103691. }
  103692. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
  103693. {
  103694. FLAC__ASSERT(0 != encoder);
  103695. FLAC__ASSERT(0 != encoder->private_);
  103696. FLAC__ASSERT(0 != encoder->protected_);
  103697. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103698. return false;
  103699. encoder->protected_->max_lpc_order = value;
  103700. return true;
  103701. }
  103702. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
  103703. {
  103704. FLAC__ASSERT(0 != encoder);
  103705. FLAC__ASSERT(0 != encoder->private_);
  103706. FLAC__ASSERT(0 != encoder->protected_);
  103707. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103708. return false;
  103709. encoder->protected_->qlp_coeff_precision = value;
  103710. return true;
  103711. }
  103712. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103713. {
  103714. FLAC__ASSERT(0 != encoder);
  103715. FLAC__ASSERT(0 != encoder->private_);
  103716. FLAC__ASSERT(0 != encoder->protected_);
  103717. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103718. return false;
  103719. encoder->protected_->do_qlp_coeff_prec_search = value;
  103720. return true;
  103721. }
  103722. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103723. {
  103724. FLAC__ASSERT(0 != encoder);
  103725. FLAC__ASSERT(0 != encoder->private_);
  103726. FLAC__ASSERT(0 != encoder->protected_);
  103727. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103728. return false;
  103729. #if 0
  103730. /*@@@ deprecated: */
  103731. encoder->protected_->do_escape_coding = value;
  103732. #else
  103733. (void)value;
  103734. #endif
  103735. return true;
  103736. }
  103737. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103738. {
  103739. FLAC__ASSERT(0 != encoder);
  103740. FLAC__ASSERT(0 != encoder->private_);
  103741. FLAC__ASSERT(0 != encoder->protected_);
  103742. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103743. return false;
  103744. encoder->protected_->do_exhaustive_model_search = value;
  103745. return true;
  103746. }
  103747. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  103748. {
  103749. FLAC__ASSERT(0 != encoder);
  103750. FLAC__ASSERT(0 != encoder->private_);
  103751. FLAC__ASSERT(0 != encoder->protected_);
  103752. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103753. return false;
  103754. encoder->protected_->min_residual_partition_order = value;
  103755. return true;
  103756. }
  103757. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  103758. {
  103759. FLAC__ASSERT(0 != encoder);
  103760. FLAC__ASSERT(0 != encoder->private_);
  103761. FLAC__ASSERT(0 != encoder->protected_);
  103762. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103763. return false;
  103764. encoder->protected_->max_residual_partition_order = value;
  103765. return true;
  103766. }
  103767. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value)
  103768. {
  103769. FLAC__ASSERT(0 != encoder);
  103770. FLAC__ASSERT(0 != encoder->private_);
  103771. FLAC__ASSERT(0 != encoder->protected_);
  103772. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103773. return false;
  103774. #if 0
  103775. /*@@@ deprecated: */
  103776. encoder->protected_->rice_parameter_search_dist = value;
  103777. #else
  103778. (void)value;
  103779. #endif
  103780. return true;
  103781. }
  103782. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
  103783. {
  103784. FLAC__ASSERT(0 != encoder);
  103785. FLAC__ASSERT(0 != encoder->private_);
  103786. FLAC__ASSERT(0 != encoder->protected_);
  103787. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103788. return false;
  103789. encoder->protected_->total_samples_estimate = value;
  103790. return true;
  103791. }
  103792. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
  103793. {
  103794. FLAC__ASSERT(0 != encoder);
  103795. FLAC__ASSERT(0 != encoder->private_);
  103796. FLAC__ASSERT(0 != encoder->protected_);
  103797. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103798. return false;
  103799. if(0 == metadata)
  103800. num_blocks = 0;
  103801. if(0 == num_blocks)
  103802. metadata = 0;
  103803. /* realloc() does not do exactly what we want so... */
  103804. if(encoder->protected_->metadata) {
  103805. free(encoder->protected_->metadata);
  103806. encoder->protected_->metadata = 0;
  103807. encoder->protected_->num_metadata_blocks = 0;
  103808. }
  103809. if(num_blocks) {
  103810. FLAC__StreamMetadata **m;
  103811. if(0 == (m = (FLAC__StreamMetadata**)safe_malloc_mul_2op_(sizeof(m[0]), /*times*/num_blocks)))
  103812. return false;
  103813. memcpy(m, metadata, sizeof(m[0]) * num_blocks);
  103814. encoder->protected_->metadata = m;
  103815. encoder->protected_->num_metadata_blocks = num_blocks;
  103816. }
  103817. #if FLAC__HAS_OGG
  103818. if(!FLAC__ogg_encoder_aspect_set_num_metadata(&encoder->protected_->ogg_encoder_aspect, num_blocks))
  103819. return false;
  103820. #endif
  103821. return true;
  103822. }
  103823. /*
  103824. * These three functions are not static, but not publically exposed in
  103825. * include/FLAC/ either. They are used by the test suite.
  103826. */
  103827. FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103828. {
  103829. FLAC__ASSERT(0 != encoder);
  103830. FLAC__ASSERT(0 != encoder->private_);
  103831. FLAC__ASSERT(0 != encoder->protected_);
  103832. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103833. return false;
  103834. encoder->private_->disable_constant_subframes = value;
  103835. return true;
  103836. }
  103837. FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103838. {
  103839. FLAC__ASSERT(0 != encoder);
  103840. FLAC__ASSERT(0 != encoder->private_);
  103841. FLAC__ASSERT(0 != encoder->protected_);
  103842. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103843. return false;
  103844. encoder->private_->disable_fixed_subframes = value;
  103845. return true;
  103846. }
  103847. FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103848. {
  103849. FLAC__ASSERT(0 != encoder);
  103850. FLAC__ASSERT(0 != encoder->private_);
  103851. FLAC__ASSERT(0 != encoder->protected_);
  103852. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103853. return false;
  103854. encoder->private_->disable_verbatim_subframes = value;
  103855. return true;
  103856. }
  103857. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
  103858. {
  103859. FLAC__ASSERT(0 != encoder);
  103860. FLAC__ASSERT(0 != encoder->private_);
  103861. FLAC__ASSERT(0 != encoder->protected_);
  103862. return encoder->protected_->state;
  103863. }
  103864. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
  103865. {
  103866. FLAC__ASSERT(0 != encoder);
  103867. FLAC__ASSERT(0 != encoder->private_);
  103868. FLAC__ASSERT(0 != encoder->protected_);
  103869. if(encoder->protected_->verify)
  103870. return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
  103871. else
  103872. return FLAC__STREAM_DECODER_UNINITIALIZED;
  103873. }
  103874. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
  103875. {
  103876. FLAC__ASSERT(0 != encoder);
  103877. FLAC__ASSERT(0 != encoder->private_);
  103878. FLAC__ASSERT(0 != encoder->protected_);
  103879. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
  103880. return FLAC__StreamEncoderStateString[encoder->protected_->state];
  103881. else
  103882. return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
  103883. }
  103884. 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)
  103885. {
  103886. FLAC__ASSERT(0 != encoder);
  103887. FLAC__ASSERT(0 != encoder->private_);
  103888. FLAC__ASSERT(0 != encoder->protected_);
  103889. if(0 != absolute_sample)
  103890. *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
  103891. if(0 != frame_number)
  103892. *frame_number = encoder->private_->verify.error_stats.frame_number;
  103893. if(0 != channel)
  103894. *channel = encoder->private_->verify.error_stats.channel;
  103895. if(0 != sample)
  103896. *sample = encoder->private_->verify.error_stats.sample;
  103897. if(0 != expected)
  103898. *expected = encoder->private_->verify.error_stats.expected;
  103899. if(0 != got)
  103900. *got = encoder->private_->verify.error_stats.got;
  103901. }
  103902. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder)
  103903. {
  103904. FLAC__ASSERT(0 != encoder);
  103905. FLAC__ASSERT(0 != encoder->private_);
  103906. FLAC__ASSERT(0 != encoder->protected_);
  103907. return encoder->protected_->verify;
  103908. }
  103909. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
  103910. {
  103911. FLAC__ASSERT(0 != encoder);
  103912. FLAC__ASSERT(0 != encoder->private_);
  103913. FLAC__ASSERT(0 != encoder->protected_);
  103914. return encoder->protected_->streamable_subset;
  103915. }
  103916. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_md5(const FLAC__StreamEncoder *encoder)
  103917. {
  103918. FLAC__ASSERT(0 != encoder);
  103919. FLAC__ASSERT(0 != encoder->private_);
  103920. FLAC__ASSERT(0 != encoder->protected_);
  103921. return encoder->protected_->do_md5;
  103922. }
  103923. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
  103924. {
  103925. FLAC__ASSERT(0 != encoder);
  103926. FLAC__ASSERT(0 != encoder->private_);
  103927. FLAC__ASSERT(0 != encoder->protected_);
  103928. return encoder->protected_->channels;
  103929. }
  103930. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
  103931. {
  103932. FLAC__ASSERT(0 != encoder);
  103933. FLAC__ASSERT(0 != encoder->private_);
  103934. FLAC__ASSERT(0 != encoder->protected_);
  103935. return encoder->protected_->bits_per_sample;
  103936. }
  103937. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder)
  103938. {
  103939. FLAC__ASSERT(0 != encoder);
  103940. FLAC__ASSERT(0 != encoder->private_);
  103941. FLAC__ASSERT(0 != encoder->protected_);
  103942. return encoder->protected_->sample_rate;
  103943. }
  103944. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
  103945. {
  103946. FLAC__ASSERT(0 != encoder);
  103947. FLAC__ASSERT(0 != encoder->private_);
  103948. FLAC__ASSERT(0 != encoder->protected_);
  103949. return encoder->protected_->blocksize;
  103950. }
  103951. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  103952. {
  103953. FLAC__ASSERT(0 != encoder);
  103954. FLAC__ASSERT(0 != encoder->private_);
  103955. FLAC__ASSERT(0 != encoder->protected_);
  103956. return encoder->protected_->do_mid_side_stereo;
  103957. }
  103958. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  103959. {
  103960. FLAC__ASSERT(0 != encoder);
  103961. FLAC__ASSERT(0 != encoder->private_);
  103962. FLAC__ASSERT(0 != encoder->protected_);
  103963. return encoder->protected_->loose_mid_side_stereo;
  103964. }
  103965. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
  103966. {
  103967. FLAC__ASSERT(0 != encoder);
  103968. FLAC__ASSERT(0 != encoder->private_);
  103969. FLAC__ASSERT(0 != encoder->protected_);
  103970. return encoder->protected_->max_lpc_order;
  103971. }
  103972. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
  103973. {
  103974. FLAC__ASSERT(0 != encoder);
  103975. FLAC__ASSERT(0 != encoder->private_);
  103976. FLAC__ASSERT(0 != encoder->protected_);
  103977. return encoder->protected_->qlp_coeff_precision;
  103978. }
  103979. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
  103980. {
  103981. FLAC__ASSERT(0 != encoder);
  103982. FLAC__ASSERT(0 != encoder->private_);
  103983. FLAC__ASSERT(0 != encoder->protected_);
  103984. return encoder->protected_->do_qlp_coeff_prec_search;
  103985. }
  103986. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
  103987. {
  103988. FLAC__ASSERT(0 != encoder);
  103989. FLAC__ASSERT(0 != encoder->private_);
  103990. FLAC__ASSERT(0 != encoder->protected_);
  103991. return encoder->protected_->do_escape_coding;
  103992. }
  103993. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
  103994. {
  103995. FLAC__ASSERT(0 != encoder);
  103996. FLAC__ASSERT(0 != encoder->private_);
  103997. FLAC__ASSERT(0 != encoder->protected_);
  103998. return encoder->protected_->do_exhaustive_model_search;
  103999. }
  104000. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
  104001. {
  104002. FLAC__ASSERT(0 != encoder);
  104003. FLAC__ASSERT(0 != encoder->private_);
  104004. FLAC__ASSERT(0 != encoder->protected_);
  104005. return encoder->protected_->min_residual_partition_order;
  104006. }
  104007. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
  104008. {
  104009. FLAC__ASSERT(0 != encoder);
  104010. FLAC__ASSERT(0 != encoder->private_);
  104011. FLAC__ASSERT(0 != encoder->protected_);
  104012. return encoder->protected_->max_residual_partition_order;
  104013. }
  104014. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
  104015. {
  104016. FLAC__ASSERT(0 != encoder);
  104017. FLAC__ASSERT(0 != encoder->private_);
  104018. FLAC__ASSERT(0 != encoder->protected_);
  104019. return encoder->protected_->rice_parameter_search_dist;
  104020. }
  104021. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
  104022. {
  104023. FLAC__ASSERT(0 != encoder);
  104024. FLAC__ASSERT(0 != encoder->private_);
  104025. FLAC__ASSERT(0 != encoder->protected_);
  104026. return encoder->protected_->total_samples_estimate;
  104027. }
  104028. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
  104029. {
  104030. unsigned i, j = 0, channel;
  104031. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  104032. FLAC__ASSERT(0 != encoder);
  104033. FLAC__ASSERT(0 != encoder->private_);
  104034. FLAC__ASSERT(0 != encoder->protected_);
  104035. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  104036. do {
  104037. const unsigned n = min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j);
  104038. if(encoder->protected_->verify)
  104039. append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, n);
  104040. for(channel = 0; channel < channels; channel++)
  104041. memcpy(&encoder->private_->integer_signal[channel][encoder->private_->current_sample_number], &buffer[channel][j], sizeof(buffer[channel][0]) * n);
  104042. if(encoder->protected_->do_mid_side_stereo) {
  104043. FLAC__ASSERT(channels == 2);
  104044. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  104045. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  104046. encoder->private_->integer_signal_mid_side[1][i] = buffer[0][j] - buffer[1][j];
  104047. 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' ! */
  104048. }
  104049. }
  104050. else
  104051. j += n;
  104052. encoder->private_->current_sample_number += n;
  104053. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  104054. if(encoder->private_->current_sample_number > blocksize) {
  104055. FLAC__ASSERT(encoder->private_->current_sample_number == blocksize+OVERREAD_);
  104056. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  104057. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  104058. return false;
  104059. /* move unprocessed overread samples to beginnings of arrays */
  104060. for(channel = 0; channel < channels; channel++)
  104061. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  104062. if(encoder->protected_->do_mid_side_stereo) {
  104063. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  104064. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  104065. }
  104066. encoder->private_->current_sample_number = 1;
  104067. }
  104068. } while(j < samples);
  104069. return true;
  104070. }
  104071. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
  104072. {
  104073. unsigned i, j, k, channel;
  104074. FLAC__int32 x, mid, side;
  104075. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  104076. FLAC__ASSERT(0 != encoder);
  104077. FLAC__ASSERT(0 != encoder->private_);
  104078. FLAC__ASSERT(0 != encoder->protected_);
  104079. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  104080. j = k = 0;
  104081. /*
  104082. * we have several flavors of the same basic loop, optimized for
  104083. * different conditions:
  104084. */
  104085. if(encoder->protected_->do_mid_side_stereo && channels == 2) {
  104086. /*
  104087. * stereo coding: unroll channel loop
  104088. */
  104089. do {
  104090. if(encoder->protected_->verify)
  104091. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  104092. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  104093. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  104094. encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
  104095. x = buffer[k++];
  104096. encoder->private_->integer_signal[1][i] = x;
  104097. mid += x;
  104098. side -= x;
  104099. mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
  104100. encoder->private_->integer_signal_mid_side[1][i] = side;
  104101. encoder->private_->integer_signal_mid_side[0][i] = mid;
  104102. }
  104103. encoder->private_->current_sample_number = i;
  104104. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  104105. if(i > blocksize) {
  104106. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  104107. return false;
  104108. /* move unprocessed overread samples to beginnings of arrays */
  104109. FLAC__ASSERT(i == blocksize+OVERREAD_);
  104110. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  104111. encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][blocksize];
  104112. encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][blocksize];
  104113. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  104114. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  104115. encoder->private_->current_sample_number = 1;
  104116. }
  104117. } while(j < samples);
  104118. }
  104119. else {
  104120. /*
  104121. * independent channel coding: buffer each channel in inner loop
  104122. */
  104123. do {
  104124. if(encoder->protected_->verify)
  104125. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  104126. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  104127. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  104128. for(channel = 0; channel < channels; channel++)
  104129. encoder->private_->integer_signal[channel][i] = buffer[k++];
  104130. }
  104131. encoder->private_->current_sample_number = i;
  104132. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  104133. if(i > blocksize) {
  104134. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  104135. return false;
  104136. /* move unprocessed overread samples to beginnings of arrays */
  104137. FLAC__ASSERT(i == blocksize+OVERREAD_);
  104138. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  104139. for(channel = 0; channel < channels; channel++)
  104140. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  104141. encoder->private_->current_sample_number = 1;
  104142. }
  104143. } while(j < samples);
  104144. }
  104145. return true;
  104146. }
  104147. /***********************************************************************
  104148. *
  104149. * Private class methods
  104150. *
  104151. ***********************************************************************/
  104152. void set_defaults_enc(FLAC__StreamEncoder *encoder)
  104153. {
  104154. FLAC__ASSERT(0 != encoder);
  104155. #ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  104156. encoder->protected_->verify = true;
  104157. #else
  104158. encoder->protected_->verify = false;
  104159. #endif
  104160. encoder->protected_->streamable_subset = true;
  104161. encoder->protected_->do_md5 = true;
  104162. encoder->protected_->do_mid_side_stereo = false;
  104163. encoder->protected_->loose_mid_side_stereo = false;
  104164. encoder->protected_->channels = 2;
  104165. encoder->protected_->bits_per_sample = 16;
  104166. encoder->protected_->sample_rate = 44100;
  104167. encoder->protected_->blocksize = 0;
  104168. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104169. encoder->protected_->num_apodizations = 1;
  104170. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  104171. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  104172. #endif
  104173. encoder->protected_->max_lpc_order = 0;
  104174. encoder->protected_->qlp_coeff_precision = 0;
  104175. encoder->protected_->do_qlp_coeff_prec_search = false;
  104176. encoder->protected_->do_exhaustive_model_search = false;
  104177. encoder->protected_->do_escape_coding = false;
  104178. encoder->protected_->min_residual_partition_order = 0;
  104179. encoder->protected_->max_residual_partition_order = 0;
  104180. encoder->protected_->rice_parameter_search_dist = 0;
  104181. encoder->protected_->total_samples_estimate = 0;
  104182. encoder->protected_->metadata = 0;
  104183. encoder->protected_->num_metadata_blocks = 0;
  104184. encoder->private_->seek_table = 0;
  104185. encoder->private_->disable_constant_subframes = false;
  104186. encoder->private_->disable_fixed_subframes = false;
  104187. encoder->private_->disable_verbatim_subframes = false;
  104188. #if FLAC__HAS_OGG
  104189. encoder->private_->is_ogg = false;
  104190. #endif
  104191. encoder->private_->read_callback = 0;
  104192. encoder->private_->write_callback = 0;
  104193. encoder->private_->seek_callback = 0;
  104194. encoder->private_->tell_callback = 0;
  104195. encoder->private_->metadata_callback = 0;
  104196. encoder->private_->progress_callback = 0;
  104197. encoder->private_->client_data = 0;
  104198. #if FLAC__HAS_OGG
  104199. FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect);
  104200. #endif
  104201. }
  104202. void free_(FLAC__StreamEncoder *encoder)
  104203. {
  104204. unsigned i, channel;
  104205. FLAC__ASSERT(0 != encoder);
  104206. if(encoder->protected_->metadata) {
  104207. free(encoder->protected_->metadata);
  104208. encoder->protected_->metadata = 0;
  104209. encoder->protected_->num_metadata_blocks = 0;
  104210. }
  104211. for(i = 0; i < encoder->protected_->channels; i++) {
  104212. if(0 != encoder->private_->integer_signal_unaligned[i]) {
  104213. free(encoder->private_->integer_signal_unaligned[i]);
  104214. encoder->private_->integer_signal_unaligned[i] = 0;
  104215. }
  104216. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104217. if(0 != encoder->private_->real_signal_unaligned[i]) {
  104218. free(encoder->private_->real_signal_unaligned[i]);
  104219. encoder->private_->real_signal_unaligned[i] = 0;
  104220. }
  104221. #endif
  104222. }
  104223. for(i = 0; i < 2; i++) {
  104224. if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
  104225. free(encoder->private_->integer_signal_mid_side_unaligned[i]);
  104226. encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
  104227. }
  104228. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104229. if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
  104230. free(encoder->private_->real_signal_mid_side_unaligned[i]);
  104231. encoder->private_->real_signal_mid_side_unaligned[i] = 0;
  104232. }
  104233. #endif
  104234. }
  104235. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104236. for(i = 0; i < encoder->protected_->num_apodizations; i++) {
  104237. if(0 != encoder->private_->window_unaligned[i]) {
  104238. free(encoder->private_->window_unaligned[i]);
  104239. encoder->private_->window_unaligned[i] = 0;
  104240. }
  104241. }
  104242. if(0 != encoder->private_->windowed_signal_unaligned) {
  104243. free(encoder->private_->windowed_signal_unaligned);
  104244. encoder->private_->windowed_signal_unaligned = 0;
  104245. }
  104246. #endif
  104247. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104248. for(i = 0; i < 2; i++) {
  104249. if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
  104250. free(encoder->private_->residual_workspace_unaligned[channel][i]);
  104251. encoder->private_->residual_workspace_unaligned[channel][i] = 0;
  104252. }
  104253. }
  104254. }
  104255. for(channel = 0; channel < 2; channel++) {
  104256. for(i = 0; i < 2; i++) {
  104257. if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
  104258. free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
  104259. encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
  104260. }
  104261. }
  104262. }
  104263. if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
  104264. free(encoder->private_->abs_residual_partition_sums_unaligned);
  104265. encoder->private_->abs_residual_partition_sums_unaligned = 0;
  104266. }
  104267. if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
  104268. free(encoder->private_->raw_bits_per_partition_unaligned);
  104269. encoder->private_->raw_bits_per_partition_unaligned = 0;
  104270. }
  104271. if(encoder->protected_->verify) {
  104272. for(i = 0; i < encoder->protected_->channels; i++) {
  104273. if(0 != encoder->private_->verify.input_fifo.data[i]) {
  104274. free(encoder->private_->verify.input_fifo.data[i]);
  104275. encoder->private_->verify.input_fifo.data[i] = 0;
  104276. }
  104277. }
  104278. }
  104279. FLAC__bitwriter_free(encoder->private_->frame);
  104280. }
  104281. FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize)
  104282. {
  104283. FLAC__bool ok;
  104284. unsigned i, channel;
  104285. FLAC__ASSERT(new_blocksize > 0);
  104286. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  104287. FLAC__ASSERT(encoder->private_->current_sample_number == 0);
  104288. /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
  104289. if(new_blocksize <= encoder->private_->input_capacity)
  104290. return true;
  104291. ok = true;
  104292. /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx()
  104293. * requires that the input arrays (in our case the integer signals)
  104294. * have a buffer of up to 3 zeroes in front (at negative indices) for
  104295. * alignment purposes; we use 4 in front to keep the data well-aligned.
  104296. */
  104297. for(i = 0; ok && i < encoder->protected_->channels; i++) {
  104298. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
  104299. memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
  104300. encoder->private_->integer_signal[i] += 4;
  104301. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104302. #if 0 /* @@@ currently unused */
  104303. if(encoder->protected_->max_lpc_order > 0)
  104304. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
  104305. #endif
  104306. #endif
  104307. }
  104308. for(i = 0; ok && i < 2; i++) {
  104309. 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]);
  104310. memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
  104311. encoder->private_->integer_signal_mid_side[i] += 4;
  104312. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104313. #if 0 /* @@@ currently unused */
  104314. if(encoder->protected_->max_lpc_order > 0)
  104315. 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]);
  104316. #endif
  104317. #endif
  104318. }
  104319. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104320. if(ok && encoder->protected_->max_lpc_order > 0) {
  104321. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
  104322. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
  104323. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
  104324. }
  104325. #endif
  104326. for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
  104327. for(i = 0; ok && i < 2; i++) {
  104328. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
  104329. }
  104330. }
  104331. for(channel = 0; ok && channel < 2; channel++) {
  104332. for(i = 0; ok && i < 2; i++) {
  104333. 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]);
  104334. }
  104335. }
  104336. /* the *2 is an approximation to the series 1 + 1/2 + 1/4 + ... that sums tree occupies in a flat array */
  104337. /*@@@ 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) */
  104338. ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
  104339. if(encoder->protected_->do_escape_coding)
  104340. ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
  104341. /* now adjust the windows if the blocksize has changed */
  104342. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104343. if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) {
  104344. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
  104345. switch(encoder->protected_->apodizations[i].type) {
  104346. case FLAC__APODIZATION_BARTLETT:
  104347. FLAC__window_bartlett(encoder->private_->window[i], new_blocksize);
  104348. break;
  104349. case FLAC__APODIZATION_BARTLETT_HANN:
  104350. FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize);
  104351. break;
  104352. case FLAC__APODIZATION_BLACKMAN:
  104353. FLAC__window_blackman(encoder->private_->window[i], new_blocksize);
  104354. break;
  104355. case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
  104356. FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize);
  104357. break;
  104358. case FLAC__APODIZATION_CONNES:
  104359. FLAC__window_connes(encoder->private_->window[i], new_blocksize);
  104360. break;
  104361. case FLAC__APODIZATION_FLATTOP:
  104362. FLAC__window_flattop(encoder->private_->window[i], new_blocksize);
  104363. break;
  104364. case FLAC__APODIZATION_GAUSS:
  104365. FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev);
  104366. break;
  104367. case FLAC__APODIZATION_HAMMING:
  104368. FLAC__window_hamming(encoder->private_->window[i], new_blocksize);
  104369. break;
  104370. case FLAC__APODIZATION_HANN:
  104371. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  104372. break;
  104373. case FLAC__APODIZATION_KAISER_BESSEL:
  104374. FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize);
  104375. break;
  104376. case FLAC__APODIZATION_NUTTALL:
  104377. FLAC__window_nuttall(encoder->private_->window[i], new_blocksize);
  104378. break;
  104379. case FLAC__APODIZATION_RECTANGLE:
  104380. FLAC__window_rectangle(encoder->private_->window[i], new_blocksize);
  104381. break;
  104382. case FLAC__APODIZATION_TRIANGLE:
  104383. FLAC__window_triangle(encoder->private_->window[i], new_blocksize);
  104384. break;
  104385. case FLAC__APODIZATION_TUKEY:
  104386. FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p);
  104387. break;
  104388. case FLAC__APODIZATION_WELCH:
  104389. FLAC__window_welch(encoder->private_->window[i], new_blocksize);
  104390. break;
  104391. default:
  104392. FLAC__ASSERT(0);
  104393. /* double protection */
  104394. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  104395. break;
  104396. }
  104397. }
  104398. }
  104399. #endif
  104400. if(ok)
  104401. encoder->private_->input_capacity = new_blocksize;
  104402. else
  104403. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104404. return ok;
  104405. }
  104406. FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block)
  104407. {
  104408. const FLAC__byte *buffer;
  104409. size_t bytes;
  104410. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  104411. if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) {
  104412. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104413. return false;
  104414. }
  104415. if(encoder->protected_->verify) {
  104416. encoder->private_->verify.output.data = buffer;
  104417. encoder->private_->verify.output.bytes = bytes;
  104418. if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
  104419. encoder->private_->verify.needs_magic_hack = true;
  104420. }
  104421. else {
  104422. if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
  104423. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  104424. FLAC__bitwriter_clear(encoder->private_->frame);
  104425. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
  104426. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  104427. return false;
  104428. }
  104429. }
  104430. }
  104431. if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104432. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  104433. FLAC__bitwriter_clear(encoder->private_->frame);
  104434. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104435. return false;
  104436. }
  104437. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  104438. FLAC__bitwriter_clear(encoder->private_->frame);
  104439. if(samples > 0) {
  104440. encoder->private_->streaminfo.data.stream_info.min_framesize = min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
  104441. encoder->private_->streaminfo.data.stream_info.max_framesize = max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
  104442. }
  104443. return true;
  104444. }
  104445. FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block)
  104446. {
  104447. FLAC__StreamEncoderWriteStatus status;
  104448. FLAC__uint64 output_position = 0;
  104449. /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
  104450. if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
  104451. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104452. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  104453. }
  104454. /*
  104455. * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
  104456. */
  104457. if(samples == 0) {
  104458. FLAC__MetadataType type = (FLAC__MetadataType) (buffer[0] & 0x7f);
  104459. if(type == FLAC__METADATA_TYPE_STREAMINFO)
  104460. encoder->protected_->streaminfo_offset = output_position;
  104461. else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
  104462. encoder->protected_->seektable_offset = output_position;
  104463. }
  104464. /*
  104465. * Mark the current seek point if hit (if audio_offset == 0 that
  104466. * means we're still writing metadata and haven't hit the first
  104467. * frame yet)
  104468. */
  104469. if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
  104470. const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  104471. const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
  104472. const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
  104473. FLAC__uint64 test_sample;
  104474. unsigned i;
  104475. for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
  104476. test_sample = encoder->private_->seek_table->points[i].sample_number;
  104477. if(test_sample > frame_last_sample) {
  104478. break;
  104479. }
  104480. else if(test_sample >= frame_first_sample) {
  104481. encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
  104482. encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
  104483. encoder->private_->seek_table->points[i].frame_samples = blocksize;
  104484. encoder->private_->first_seekpoint_to_check++;
  104485. /* DO NOT: "break;" and here's why:
  104486. * The seektable template may contain more than one target
  104487. * sample for any given frame; we will keep looping, generating
  104488. * duplicate seekpoints for them, and we'll clean it up later,
  104489. * just before writing the seektable back to the metadata.
  104490. */
  104491. }
  104492. else {
  104493. encoder->private_->first_seekpoint_to_check++;
  104494. }
  104495. }
  104496. }
  104497. #if FLAC__HAS_OGG
  104498. if(encoder->private_->is_ogg) {
  104499. status = FLAC__ogg_encoder_aspect_write_callback_wrapper(
  104500. &encoder->protected_->ogg_encoder_aspect,
  104501. buffer,
  104502. bytes,
  104503. samples,
  104504. encoder->private_->current_frame_number,
  104505. is_last_block,
  104506. (FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback,
  104507. encoder,
  104508. encoder->private_->client_data
  104509. );
  104510. }
  104511. else
  104512. #endif
  104513. status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
  104514. if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104515. encoder->private_->bytes_written += bytes;
  104516. encoder->private_->samples_written += samples;
  104517. /* we keep a high watermark on the number of frames written because
  104518. * when the encoder goes back to write metadata, 'current_frame'
  104519. * will drop back to 0.
  104520. */
  104521. encoder->private_->frames_written = max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
  104522. }
  104523. else
  104524. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104525. return status;
  104526. }
  104527. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  104528. void update_metadata_(const FLAC__StreamEncoder *encoder)
  104529. {
  104530. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  104531. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  104532. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  104533. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  104534. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  104535. const unsigned bps = metadata->data.stream_info.bits_per_sample;
  104536. FLAC__StreamEncoderSeekStatus seek_status;
  104537. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  104538. /* All this is based on intimate knowledge of the stream header
  104539. * layout, but a change to the header format that would break this
  104540. * would also break all streams encoded in the previous format.
  104541. */
  104542. /*
  104543. * Write MD5 signature
  104544. */
  104545. {
  104546. const unsigned md5_offset =
  104547. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104548. (
  104549. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104550. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104551. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104552. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104553. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104554. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104555. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  104556. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  104557. ) / 8;
  104558. if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
  104559. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104560. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104561. return;
  104562. }
  104563. if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104564. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104565. return;
  104566. }
  104567. }
  104568. /*
  104569. * Write total samples
  104570. */
  104571. {
  104572. const unsigned total_samples_byte_offset =
  104573. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104574. (
  104575. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104576. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104577. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104578. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104579. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104580. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104581. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  104582. - 4
  104583. ) / 8;
  104584. b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
  104585. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  104586. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  104587. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  104588. b[4] = (FLAC__byte)(samples & 0xFF);
  104589. 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) {
  104590. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104591. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104592. return;
  104593. }
  104594. if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104595. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104596. return;
  104597. }
  104598. }
  104599. /*
  104600. * Write min/max framesize
  104601. */
  104602. {
  104603. const unsigned min_framesize_offset =
  104604. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104605. (
  104606. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104607. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  104608. ) / 8;
  104609. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  104610. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  104611. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  104612. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  104613. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  104614. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  104615. 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) {
  104616. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104617. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104618. return;
  104619. }
  104620. if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104621. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104622. return;
  104623. }
  104624. }
  104625. /*
  104626. * Write seektable
  104627. */
  104628. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  104629. unsigned i;
  104630. FLAC__format_seektable_sort(encoder->private_->seek_table);
  104631. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  104632. 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) {
  104633. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104634. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104635. return;
  104636. }
  104637. for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
  104638. FLAC__uint64 xx;
  104639. unsigned x;
  104640. xx = encoder->private_->seek_table->points[i].sample_number;
  104641. b[7] = (FLAC__byte)xx; xx >>= 8;
  104642. b[6] = (FLAC__byte)xx; xx >>= 8;
  104643. b[5] = (FLAC__byte)xx; xx >>= 8;
  104644. b[4] = (FLAC__byte)xx; xx >>= 8;
  104645. b[3] = (FLAC__byte)xx; xx >>= 8;
  104646. b[2] = (FLAC__byte)xx; xx >>= 8;
  104647. b[1] = (FLAC__byte)xx; xx >>= 8;
  104648. b[0] = (FLAC__byte)xx; xx >>= 8;
  104649. xx = encoder->private_->seek_table->points[i].stream_offset;
  104650. b[15] = (FLAC__byte)xx; xx >>= 8;
  104651. b[14] = (FLAC__byte)xx; xx >>= 8;
  104652. b[13] = (FLAC__byte)xx; xx >>= 8;
  104653. b[12] = (FLAC__byte)xx; xx >>= 8;
  104654. b[11] = (FLAC__byte)xx; xx >>= 8;
  104655. b[10] = (FLAC__byte)xx; xx >>= 8;
  104656. b[9] = (FLAC__byte)xx; xx >>= 8;
  104657. b[8] = (FLAC__byte)xx; xx >>= 8;
  104658. x = encoder->private_->seek_table->points[i].frame_samples;
  104659. b[17] = (FLAC__byte)x; x >>= 8;
  104660. b[16] = (FLAC__byte)x; x >>= 8;
  104661. if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104662. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104663. return;
  104664. }
  104665. }
  104666. }
  104667. }
  104668. #if FLAC__HAS_OGG
  104669. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  104670. void update_ogg_metadata_(FLAC__StreamEncoder *encoder)
  104671. {
  104672. /* the # of bytes in the 1st packet that precede the STREAMINFO */
  104673. static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH =
  104674. FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
  104675. FLAC__OGG_MAPPING_MAGIC_LENGTH +
  104676. FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
  104677. FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
  104678. FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
  104679. FLAC__STREAM_SYNC_LENGTH
  104680. ;
  104681. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  104682. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  104683. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  104684. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  104685. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  104686. ogg_page page;
  104687. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  104688. FLAC__ASSERT(0 != encoder->private_->seek_callback);
  104689. /* Pre-check that client supports seeking, since we don't want the
  104690. * ogg_helper code to ever have to deal with this condition.
  104691. */
  104692. if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED)
  104693. return;
  104694. /* All this is based on intimate knowledge of the stream header
  104695. * layout, but a change to the header format that would break this
  104696. * would also break all streams encoded in the previous format.
  104697. */
  104698. /**
  104699. ** Write STREAMINFO stats
  104700. **/
  104701. simple_ogg_page__init(&page);
  104702. if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  104703. simple_ogg_page__clear(&page);
  104704. return; /* state already set */
  104705. }
  104706. /*
  104707. * Write MD5 signature
  104708. */
  104709. {
  104710. const unsigned md5_offset =
  104711. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104712. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104713. (
  104714. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104715. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104716. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104717. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104718. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104719. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104720. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  104721. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  104722. ) / 8;
  104723. if(md5_offset + 16 > (unsigned)page.body_len) {
  104724. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104725. simple_ogg_page__clear(&page);
  104726. return;
  104727. }
  104728. memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16);
  104729. }
  104730. /*
  104731. * Write total samples
  104732. */
  104733. {
  104734. const unsigned total_samples_byte_offset =
  104735. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104736. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104737. (
  104738. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104739. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104740. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104741. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104742. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104743. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104744. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  104745. - 4
  104746. ) / 8;
  104747. if(total_samples_byte_offset + 5 > (unsigned)page.body_len) {
  104748. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104749. simple_ogg_page__clear(&page);
  104750. return;
  104751. }
  104752. b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0;
  104753. b[0] |= (FLAC__byte)((samples >> 32) & 0x0F);
  104754. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  104755. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  104756. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  104757. b[4] = (FLAC__byte)(samples & 0xFF);
  104758. memcpy(page.body + total_samples_byte_offset, b, 5);
  104759. }
  104760. /*
  104761. * Write min/max framesize
  104762. */
  104763. {
  104764. const unsigned min_framesize_offset =
  104765. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104766. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104767. (
  104768. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104769. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  104770. ) / 8;
  104771. if(min_framesize_offset + 6 > (unsigned)page.body_len) {
  104772. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104773. simple_ogg_page__clear(&page);
  104774. return;
  104775. }
  104776. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  104777. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  104778. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  104779. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  104780. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  104781. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  104782. memcpy(page.body + min_framesize_offset, b, 6);
  104783. }
  104784. if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  104785. simple_ogg_page__clear(&page);
  104786. return; /* state already set */
  104787. }
  104788. simple_ogg_page__clear(&page);
  104789. /*
  104790. * Write seektable
  104791. */
  104792. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  104793. unsigned i;
  104794. FLAC__byte *p;
  104795. FLAC__format_seektable_sort(encoder->private_->seek_table);
  104796. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  104797. simple_ogg_page__init(&page);
  104798. if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  104799. simple_ogg_page__clear(&page);
  104800. return; /* state already set */
  104801. }
  104802. if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) {
  104803. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104804. simple_ogg_page__clear(&page);
  104805. return;
  104806. }
  104807. for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) {
  104808. FLAC__uint64 xx;
  104809. unsigned x;
  104810. xx = encoder->private_->seek_table->points[i].sample_number;
  104811. b[7] = (FLAC__byte)xx; xx >>= 8;
  104812. b[6] = (FLAC__byte)xx; xx >>= 8;
  104813. b[5] = (FLAC__byte)xx; xx >>= 8;
  104814. b[4] = (FLAC__byte)xx; xx >>= 8;
  104815. b[3] = (FLAC__byte)xx; xx >>= 8;
  104816. b[2] = (FLAC__byte)xx; xx >>= 8;
  104817. b[1] = (FLAC__byte)xx; xx >>= 8;
  104818. b[0] = (FLAC__byte)xx; xx >>= 8;
  104819. xx = encoder->private_->seek_table->points[i].stream_offset;
  104820. b[15] = (FLAC__byte)xx; xx >>= 8;
  104821. b[14] = (FLAC__byte)xx; xx >>= 8;
  104822. b[13] = (FLAC__byte)xx; xx >>= 8;
  104823. b[12] = (FLAC__byte)xx; xx >>= 8;
  104824. b[11] = (FLAC__byte)xx; xx >>= 8;
  104825. b[10] = (FLAC__byte)xx; xx >>= 8;
  104826. b[9] = (FLAC__byte)xx; xx >>= 8;
  104827. b[8] = (FLAC__byte)xx; xx >>= 8;
  104828. x = encoder->private_->seek_table->points[i].frame_samples;
  104829. b[17] = (FLAC__byte)x; x >>= 8;
  104830. b[16] = (FLAC__byte)x; x >>= 8;
  104831. memcpy(p, b, 18);
  104832. }
  104833. if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  104834. simple_ogg_page__clear(&page);
  104835. return; /* state already set */
  104836. }
  104837. simple_ogg_page__clear(&page);
  104838. }
  104839. }
  104840. #endif
  104841. FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block)
  104842. {
  104843. FLAC__uint16 crc;
  104844. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  104845. /*
  104846. * Accumulate raw signal to the MD5 signature
  104847. */
  104848. 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)) {
  104849. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104850. return false;
  104851. }
  104852. /*
  104853. * Process the frame header and subframes into the frame bitbuffer
  104854. */
  104855. if(!process_subframes_(encoder, is_fractional_block)) {
  104856. /* the above function sets the state for us in case of an error */
  104857. return false;
  104858. }
  104859. /*
  104860. * Zero-pad the frame to a byte_boundary
  104861. */
  104862. if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) {
  104863. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104864. return false;
  104865. }
  104866. /*
  104867. * CRC-16 the whole thing
  104868. */
  104869. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  104870. if(
  104871. !FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) ||
  104872. !FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN)
  104873. ) {
  104874. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104875. return false;
  104876. }
  104877. /*
  104878. * Write it
  104879. */
  104880. if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) {
  104881. /* the above function sets the state for us in case of an error */
  104882. return false;
  104883. }
  104884. /*
  104885. * Get ready for the next frame
  104886. */
  104887. encoder->private_->current_sample_number = 0;
  104888. encoder->private_->current_frame_number++;
  104889. encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
  104890. return true;
  104891. }
  104892. FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block)
  104893. {
  104894. FLAC__FrameHeader frame_header;
  104895. unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
  104896. FLAC__bool do_independent, do_mid_side;
  104897. /*
  104898. * Calculate the min,max Rice partition orders
  104899. */
  104900. if(is_fractional_block) {
  104901. max_partition_order = 0;
  104902. }
  104903. else {
  104904. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
  104905. max_partition_order = min(max_partition_order, encoder->protected_->max_residual_partition_order);
  104906. }
  104907. min_partition_order = min(min_partition_order, max_partition_order);
  104908. /*
  104909. * Setup the frame
  104910. */
  104911. frame_header.blocksize = encoder->protected_->blocksize;
  104912. frame_header.sample_rate = encoder->protected_->sample_rate;
  104913. frame_header.channels = encoder->protected_->channels;
  104914. frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
  104915. frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
  104916. frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  104917. frame_header.number.frame_number = encoder->private_->current_frame_number;
  104918. /*
  104919. * Figure out what channel assignments to try
  104920. */
  104921. if(encoder->protected_->do_mid_side_stereo) {
  104922. if(encoder->protected_->loose_mid_side_stereo) {
  104923. if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
  104924. do_independent = true;
  104925. do_mid_side = true;
  104926. }
  104927. else {
  104928. do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
  104929. do_mid_side = !do_independent;
  104930. }
  104931. }
  104932. else {
  104933. do_independent = true;
  104934. do_mid_side = true;
  104935. }
  104936. }
  104937. else {
  104938. do_independent = true;
  104939. do_mid_side = false;
  104940. }
  104941. FLAC__ASSERT(do_independent || do_mid_side);
  104942. /*
  104943. * Check for wasted bits; set effective bps for each subframe
  104944. */
  104945. if(do_independent) {
  104946. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104947. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
  104948. encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
  104949. encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
  104950. }
  104951. }
  104952. if(do_mid_side) {
  104953. FLAC__ASSERT(encoder->protected_->channels == 2);
  104954. for(channel = 0; channel < 2; channel++) {
  104955. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
  104956. encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
  104957. encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
  104958. }
  104959. }
  104960. /*
  104961. * First do a normal encoding pass of each independent channel
  104962. */
  104963. if(do_independent) {
  104964. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104965. if(!
  104966. process_subframe_(
  104967. encoder,
  104968. min_partition_order,
  104969. max_partition_order,
  104970. &frame_header,
  104971. encoder->private_->subframe_bps[channel],
  104972. encoder->private_->integer_signal[channel],
  104973. encoder->private_->subframe_workspace_ptr[channel],
  104974. encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
  104975. encoder->private_->residual_workspace[channel],
  104976. encoder->private_->best_subframe+channel,
  104977. encoder->private_->best_subframe_bits+channel
  104978. )
  104979. )
  104980. return false;
  104981. }
  104982. }
  104983. /*
  104984. * Now do mid and side channels if requested
  104985. */
  104986. if(do_mid_side) {
  104987. FLAC__ASSERT(encoder->protected_->channels == 2);
  104988. for(channel = 0; channel < 2; channel++) {
  104989. if(!
  104990. process_subframe_(
  104991. encoder,
  104992. min_partition_order,
  104993. max_partition_order,
  104994. &frame_header,
  104995. encoder->private_->subframe_bps_mid_side[channel],
  104996. encoder->private_->integer_signal_mid_side[channel],
  104997. encoder->private_->subframe_workspace_ptr_mid_side[channel],
  104998. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
  104999. encoder->private_->residual_workspace_mid_side[channel],
  105000. encoder->private_->best_subframe_mid_side+channel,
  105001. encoder->private_->best_subframe_bits_mid_side+channel
  105002. )
  105003. )
  105004. return false;
  105005. }
  105006. }
  105007. /*
  105008. * Compose the frame bitbuffer
  105009. */
  105010. if(do_mid_side) {
  105011. unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
  105012. FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
  105013. FLAC__ChannelAssignment channel_assignment;
  105014. FLAC__ASSERT(encoder->protected_->channels == 2);
  105015. if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
  105016. channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
  105017. }
  105018. else {
  105019. unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
  105020. unsigned min_bits;
  105021. int ca;
  105022. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT == 0);
  105023. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE == 1);
  105024. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE == 2);
  105025. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_MID_SIDE == 3);
  105026. FLAC__ASSERT(do_independent && do_mid_side);
  105027. /* We have to figure out which channel assignent results in the smallest frame */
  105028. bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits [1];
  105029. bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE ] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits_mid_side[1];
  105030. bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits [1] + encoder->private_->best_subframe_bits_mid_side[1];
  105031. bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
  105032. channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  105033. min_bits = bits[channel_assignment];
  105034. for(ca = 1; ca <= 3; ca++) {
  105035. if(bits[ca] < min_bits) {
  105036. min_bits = bits[ca];
  105037. channel_assignment = (FLAC__ChannelAssignment)ca;
  105038. }
  105039. }
  105040. }
  105041. frame_header.channel_assignment = channel_assignment;
  105042. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  105043. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105044. return false;
  105045. }
  105046. switch(channel_assignment) {
  105047. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  105048. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  105049. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  105050. break;
  105051. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  105052. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  105053. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  105054. break;
  105055. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  105056. left_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  105057. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  105058. break;
  105059. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  105060. left_subframe = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
  105061. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  105062. break;
  105063. default:
  105064. FLAC__ASSERT(0);
  105065. }
  105066. switch(channel_assignment) {
  105067. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  105068. left_bps = encoder->private_->subframe_bps [0];
  105069. right_bps = encoder->private_->subframe_bps [1];
  105070. break;
  105071. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  105072. left_bps = encoder->private_->subframe_bps [0];
  105073. right_bps = encoder->private_->subframe_bps_mid_side[1];
  105074. break;
  105075. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  105076. left_bps = encoder->private_->subframe_bps_mid_side[1];
  105077. right_bps = encoder->private_->subframe_bps [1];
  105078. break;
  105079. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  105080. left_bps = encoder->private_->subframe_bps_mid_side[0];
  105081. right_bps = encoder->private_->subframe_bps_mid_side[1];
  105082. break;
  105083. default:
  105084. FLAC__ASSERT(0);
  105085. }
  105086. /* note that encoder_add_subframe_ sets the state for us in case of an error */
  105087. if(!add_subframe_(encoder, frame_header.blocksize, left_bps , left_subframe , encoder->private_->frame))
  105088. return false;
  105089. if(!add_subframe_(encoder, frame_header.blocksize, right_bps, right_subframe, encoder->private_->frame))
  105090. return false;
  105091. }
  105092. else {
  105093. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  105094. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105095. return false;
  105096. }
  105097. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  105098. 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)) {
  105099. /* the above function sets the state for us in case of an error */
  105100. return false;
  105101. }
  105102. }
  105103. }
  105104. if(encoder->protected_->loose_mid_side_stereo) {
  105105. encoder->private_->loose_mid_side_stereo_frame_count++;
  105106. if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
  105107. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  105108. }
  105109. encoder->private_->last_channel_assignment = frame_header.channel_assignment;
  105110. return true;
  105111. }
  105112. FLAC__bool process_subframe_(
  105113. FLAC__StreamEncoder *encoder,
  105114. unsigned min_partition_order,
  105115. unsigned max_partition_order,
  105116. const FLAC__FrameHeader *frame_header,
  105117. unsigned subframe_bps,
  105118. const FLAC__int32 integer_signal[],
  105119. FLAC__Subframe *subframe[2],
  105120. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  105121. FLAC__int32 *residual[2],
  105122. unsigned *best_subframe,
  105123. unsigned *best_bits
  105124. )
  105125. {
  105126. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105127. FLAC__float fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  105128. #else
  105129. FLAC__fixedpoint fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  105130. #endif
  105131. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105132. FLAC__double lpc_residual_bits_per_sample;
  105133. 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 */
  105134. FLAC__double lpc_error[FLAC__MAX_LPC_ORDER];
  105135. unsigned min_lpc_order, max_lpc_order, lpc_order;
  105136. unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
  105137. #endif
  105138. unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
  105139. unsigned rice_parameter;
  105140. unsigned _candidate_bits, _best_bits;
  105141. unsigned _best_subframe;
  105142. /* only use RICE2 partitions if stream bps > 16 */
  105143. 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;
  105144. FLAC__ASSERT(frame_header->blocksize > 0);
  105145. /* verbatim subframe is the baseline against which we measure other compressed subframes */
  105146. _best_subframe = 0;
  105147. if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
  105148. _best_bits = UINT_MAX;
  105149. else
  105150. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  105151. if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
  105152. unsigned signal_is_constant = false;
  105153. 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);
  105154. /* check for constant subframe */
  105155. if(
  105156. !encoder->private_->disable_constant_subframes &&
  105157. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105158. fixed_residual_bits_per_sample[1] == 0.0
  105159. #else
  105160. fixed_residual_bits_per_sample[1] == FLAC__FP_ZERO
  105161. #endif
  105162. ) {
  105163. /* the above means it's possible all samples are the same value; now double-check it: */
  105164. unsigned i;
  105165. signal_is_constant = true;
  105166. for(i = 1; i < frame_header->blocksize; i++) {
  105167. if(integer_signal[0] != integer_signal[i]) {
  105168. signal_is_constant = false;
  105169. break;
  105170. }
  105171. }
  105172. }
  105173. if(signal_is_constant) {
  105174. _candidate_bits = evaluate_constant_subframe_(encoder, integer_signal[0], frame_header->blocksize, subframe_bps, subframe[!_best_subframe]);
  105175. if(_candidate_bits < _best_bits) {
  105176. _best_subframe = !_best_subframe;
  105177. _best_bits = _candidate_bits;
  105178. }
  105179. }
  105180. else {
  105181. if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) {
  105182. /* encode fixed */
  105183. if(encoder->protected_->do_exhaustive_model_search) {
  105184. min_fixed_order = 0;
  105185. max_fixed_order = FLAC__MAX_FIXED_ORDER;
  105186. }
  105187. else {
  105188. min_fixed_order = max_fixed_order = guess_fixed_order;
  105189. }
  105190. if(max_fixed_order >= frame_header->blocksize)
  105191. max_fixed_order = frame_header->blocksize - 1;
  105192. for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
  105193. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105194. if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__float)subframe_bps)
  105195. continue; /* don't even try */
  105196. 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 */
  105197. #else
  105198. if(FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]) >= (int)subframe_bps)
  105199. continue; /* don't even try */
  105200. 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 */
  105201. #endif
  105202. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  105203. if(rice_parameter >= rice_parameter_limit) {
  105204. #ifdef DEBUG_VERBOSE
  105205. fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, rice_parameter_limit - 1);
  105206. #endif
  105207. rice_parameter = rice_parameter_limit - 1;
  105208. }
  105209. _candidate_bits =
  105210. evaluate_fixed_subframe_(
  105211. encoder,
  105212. integer_signal,
  105213. residual[!_best_subframe],
  105214. encoder->private_->abs_residual_partition_sums,
  105215. encoder->private_->raw_bits_per_partition,
  105216. frame_header->blocksize,
  105217. subframe_bps,
  105218. fixed_order,
  105219. rice_parameter,
  105220. rice_parameter_limit,
  105221. min_partition_order,
  105222. max_partition_order,
  105223. encoder->protected_->do_escape_coding,
  105224. encoder->protected_->rice_parameter_search_dist,
  105225. subframe[!_best_subframe],
  105226. partitioned_rice_contents[!_best_subframe]
  105227. );
  105228. if(_candidate_bits < _best_bits) {
  105229. _best_subframe = !_best_subframe;
  105230. _best_bits = _candidate_bits;
  105231. }
  105232. }
  105233. }
  105234. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105235. /* encode lpc */
  105236. if(encoder->protected_->max_lpc_order > 0) {
  105237. if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
  105238. max_lpc_order = frame_header->blocksize-1;
  105239. else
  105240. max_lpc_order = encoder->protected_->max_lpc_order;
  105241. if(max_lpc_order > 0) {
  105242. unsigned a;
  105243. for (a = 0; a < encoder->protected_->num_apodizations; a++) {
  105244. FLAC__lpc_window_data(integer_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize);
  105245. encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc);
  105246. /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
  105247. if(autoc[0] != 0.0) {
  105248. FLAC__lpc_compute_lp_coefficients(autoc, &max_lpc_order, encoder->private_->lp_coeff, lpc_error);
  105249. if(encoder->protected_->do_exhaustive_model_search) {
  105250. min_lpc_order = 1;
  105251. }
  105252. else {
  105253. const unsigned guess_lpc_order =
  105254. FLAC__lpc_compute_best_order(
  105255. lpc_error,
  105256. max_lpc_order,
  105257. frame_header->blocksize,
  105258. subframe_bps + (
  105259. encoder->protected_->do_qlp_coeff_prec_search?
  105260. FLAC__MIN_QLP_COEFF_PRECISION : /* have to guess; use the min possible size to avoid accidentally favoring lower orders */
  105261. encoder->protected_->qlp_coeff_precision
  105262. )
  105263. );
  105264. min_lpc_order = max_lpc_order = guess_lpc_order;
  105265. }
  105266. if(max_lpc_order >= frame_header->blocksize)
  105267. max_lpc_order = frame_header->blocksize - 1;
  105268. for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
  105269. lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
  105270. if(lpc_residual_bits_per_sample >= (FLAC__double)subframe_bps)
  105271. continue; /* don't even try */
  105272. rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
  105273. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  105274. if(rice_parameter >= rice_parameter_limit) {
  105275. #ifdef DEBUG_VERBOSE
  105276. fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, rice_parameter_limit - 1);
  105277. #endif
  105278. rice_parameter = rice_parameter_limit - 1;
  105279. }
  105280. if(encoder->protected_->do_qlp_coeff_prec_search) {
  105281. min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
  105282. /* try to ensure a 32-bit datapath throughout for 16bps(+1bps for side channel) or less */
  105283. if(subframe_bps <= 17) {
  105284. max_qlp_coeff_precision = min(32 - subframe_bps - lpc_order, FLAC__MAX_QLP_COEFF_PRECISION);
  105285. max_qlp_coeff_precision = max(max_qlp_coeff_precision, min_qlp_coeff_precision);
  105286. }
  105287. else
  105288. max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  105289. }
  105290. else {
  105291. min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
  105292. }
  105293. for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
  105294. _candidate_bits =
  105295. evaluate_lpc_subframe_(
  105296. encoder,
  105297. integer_signal,
  105298. residual[!_best_subframe],
  105299. encoder->private_->abs_residual_partition_sums,
  105300. encoder->private_->raw_bits_per_partition,
  105301. encoder->private_->lp_coeff[lpc_order-1],
  105302. frame_header->blocksize,
  105303. subframe_bps,
  105304. lpc_order,
  105305. qlp_coeff_precision,
  105306. rice_parameter,
  105307. rice_parameter_limit,
  105308. min_partition_order,
  105309. max_partition_order,
  105310. encoder->protected_->do_escape_coding,
  105311. encoder->protected_->rice_parameter_search_dist,
  105312. subframe[!_best_subframe],
  105313. partitioned_rice_contents[!_best_subframe]
  105314. );
  105315. if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
  105316. if(_candidate_bits < _best_bits) {
  105317. _best_subframe = !_best_subframe;
  105318. _best_bits = _candidate_bits;
  105319. }
  105320. }
  105321. }
  105322. }
  105323. }
  105324. }
  105325. }
  105326. }
  105327. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  105328. }
  105329. }
  105330. /* under rare circumstances this can happen when all but lpc subframe types are disabled: */
  105331. if(_best_bits == UINT_MAX) {
  105332. FLAC__ASSERT(_best_subframe == 0);
  105333. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  105334. }
  105335. *best_subframe = _best_subframe;
  105336. *best_bits = _best_bits;
  105337. return true;
  105338. }
  105339. FLAC__bool add_subframe_(
  105340. FLAC__StreamEncoder *encoder,
  105341. unsigned blocksize,
  105342. unsigned subframe_bps,
  105343. const FLAC__Subframe *subframe,
  105344. FLAC__BitWriter *frame
  105345. )
  105346. {
  105347. switch(subframe->type) {
  105348. case FLAC__SUBFRAME_TYPE_CONSTANT:
  105349. if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
  105350. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105351. return false;
  105352. }
  105353. break;
  105354. case FLAC__SUBFRAME_TYPE_FIXED:
  105355. if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
  105356. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105357. return false;
  105358. }
  105359. break;
  105360. case FLAC__SUBFRAME_TYPE_LPC:
  105361. if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
  105362. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105363. return false;
  105364. }
  105365. break;
  105366. case FLAC__SUBFRAME_TYPE_VERBATIM:
  105367. if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), blocksize, subframe_bps, subframe->wasted_bits, frame)) {
  105368. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105369. return false;
  105370. }
  105371. break;
  105372. default:
  105373. FLAC__ASSERT(0);
  105374. }
  105375. return true;
  105376. }
  105377. #define SPOTCHECK_ESTIMATE 0
  105378. #if SPOTCHECK_ESTIMATE
  105379. static void spotcheck_subframe_estimate_(
  105380. FLAC__StreamEncoder *encoder,
  105381. unsigned blocksize,
  105382. unsigned subframe_bps,
  105383. const FLAC__Subframe *subframe,
  105384. unsigned estimate
  105385. )
  105386. {
  105387. FLAC__bool ret;
  105388. FLAC__BitWriter *frame = FLAC__bitwriter_new();
  105389. if(frame == 0) {
  105390. fprintf(stderr, "EST: can't allocate frame\n");
  105391. return;
  105392. }
  105393. if(!FLAC__bitwriter_init(frame)) {
  105394. fprintf(stderr, "EST: can't init frame\n");
  105395. return;
  105396. }
  105397. ret = add_subframe_(encoder, blocksize, subframe_bps, subframe, frame);
  105398. FLAC__ASSERT(ret);
  105399. {
  105400. const unsigned actual = FLAC__bitwriter_get_input_bits_unconsumed(frame);
  105401. if(estimate != actual)
  105402. 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);
  105403. }
  105404. FLAC__bitwriter_delete(frame);
  105405. }
  105406. #endif
  105407. unsigned evaluate_constant_subframe_(
  105408. FLAC__StreamEncoder *encoder,
  105409. const FLAC__int32 signal,
  105410. unsigned blocksize,
  105411. unsigned subframe_bps,
  105412. FLAC__Subframe *subframe
  105413. )
  105414. {
  105415. unsigned estimate;
  105416. subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
  105417. subframe->data.constant.value = signal;
  105418. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + subframe_bps;
  105419. #if SPOTCHECK_ESTIMATE
  105420. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105421. #else
  105422. (void)encoder, (void)blocksize;
  105423. #endif
  105424. return estimate;
  105425. }
  105426. unsigned evaluate_fixed_subframe_(
  105427. FLAC__StreamEncoder *encoder,
  105428. const FLAC__int32 signal[],
  105429. FLAC__int32 residual[],
  105430. FLAC__uint64 abs_residual_partition_sums[],
  105431. unsigned raw_bits_per_partition[],
  105432. unsigned blocksize,
  105433. unsigned subframe_bps,
  105434. unsigned order,
  105435. unsigned rice_parameter,
  105436. unsigned rice_parameter_limit,
  105437. unsigned min_partition_order,
  105438. unsigned max_partition_order,
  105439. FLAC__bool do_escape_coding,
  105440. unsigned rice_parameter_search_dist,
  105441. FLAC__Subframe *subframe,
  105442. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  105443. )
  105444. {
  105445. unsigned i, residual_bits, estimate;
  105446. const unsigned residual_samples = blocksize - order;
  105447. FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
  105448. subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
  105449. subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  105450. subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  105451. subframe->data.fixed.residual = residual;
  105452. residual_bits =
  105453. find_best_partition_order_(
  105454. encoder->private_,
  105455. residual,
  105456. abs_residual_partition_sums,
  105457. raw_bits_per_partition,
  105458. residual_samples,
  105459. order,
  105460. rice_parameter,
  105461. rice_parameter_limit,
  105462. min_partition_order,
  105463. max_partition_order,
  105464. subframe_bps,
  105465. do_escape_coding,
  105466. rice_parameter_search_dist,
  105467. &subframe->data.fixed.entropy_coding_method
  105468. );
  105469. subframe->data.fixed.order = order;
  105470. for(i = 0; i < order; i++)
  105471. subframe->data.fixed.warmup[i] = signal[i];
  105472. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (order * subframe_bps) + residual_bits;
  105473. #if SPOTCHECK_ESTIMATE
  105474. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105475. #endif
  105476. return estimate;
  105477. }
  105478. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105479. unsigned evaluate_lpc_subframe_(
  105480. FLAC__StreamEncoder *encoder,
  105481. const FLAC__int32 signal[],
  105482. FLAC__int32 residual[],
  105483. FLAC__uint64 abs_residual_partition_sums[],
  105484. unsigned raw_bits_per_partition[],
  105485. const FLAC__real lp_coeff[],
  105486. unsigned blocksize,
  105487. unsigned subframe_bps,
  105488. unsigned order,
  105489. unsigned qlp_coeff_precision,
  105490. unsigned rice_parameter,
  105491. unsigned rice_parameter_limit,
  105492. unsigned min_partition_order,
  105493. unsigned max_partition_order,
  105494. FLAC__bool do_escape_coding,
  105495. unsigned rice_parameter_search_dist,
  105496. FLAC__Subframe *subframe,
  105497. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  105498. )
  105499. {
  105500. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  105501. unsigned i, residual_bits, estimate;
  105502. int quantization, ret;
  105503. const unsigned residual_samples = blocksize - order;
  105504. /* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */
  105505. if(subframe_bps <= 16) {
  105506. FLAC__ASSERT(order > 0);
  105507. FLAC__ASSERT(order <= FLAC__MAX_LPC_ORDER);
  105508. qlp_coeff_precision = min(qlp_coeff_precision, 32 - subframe_bps - FLAC__bitmath_ilog2(order));
  105509. }
  105510. ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, qlp_coeff, &quantization);
  105511. if(ret != 0)
  105512. return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
  105513. if(subframe_bps + qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  105514. if(subframe_bps <= 16 && qlp_coeff_precision <= 16)
  105515. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  105516. else
  105517. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  105518. else
  105519. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  105520. subframe->type = FLAC__SUBFRAME_TYPE_LPC;
  105521. subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  105522. subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  105523. subframe->data.lpc.residual = residual;
  105524. residual_bits =
  105525. find_best_partition_order_(
  105526. encoder->private_,
  105527. residual,
  105528. abs_residual_partition_sums,
  105529. raw_bits_per_partition,
  105530. residual_samples,
  105531. order,
  105532. rice_parameter,
  105533. rice_parameter_limit,
  105534. min_partition_order,
  105535. max_partition_order,
  105536. subframe_bps,
  105537. do_escape_coding,
  105538. rice_parameter_search_dist,
  105539. &subframe->data.lpc.entropy_coding_method
  105540. );
  105541. subframe->data.lpc.order = order;
  105542. subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
  105543. subframe->data.lpc.quantization_level = quantization;
  105544. memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER);
  105545. for(i = 0; i < order; i++)
  105546. subframe->data.lpc.warmup[i] = signal[i];
  105547. 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;
  105548. #if SPOTCHECK_ESTIMATE
  105549. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105550. #endif
  105551. return estimate;
  105552. }
  105553. #endif
  105554. unsigned evaluate_verbatim_subframe_(
  105555. FLAC__StreamEncoder *encoder,
  105556. const FLAC__int32 signal[],
  105557. unsigned blocksize,
  105558. unsigned subframe_bps,
  105559. FLAC__Subframe *subframe
  105560. )
  105561. {
  105562. unsigned estimate;
  105563. subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
  105564. subframe->data.verbatim.data = signal;
  105565. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (blocksize * subframe_bps);
  105566. #if SPOTCHECK_ESTIMATE
  105567. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105568. #else
  105569. (void)encoder;
  105570. #endif
  105571. return estimate;
  105572. }
  105573. unsigned find_best_partition_order_(
  105574. FLAC__StreamEncoderPrivate *private_,
  105575. const FLAC__int32 residual[],
  105576. FLAC__uint64 abs_residual_partition_sums[],
  105577. unsigned raw_bits_per_partition[],
  105578. unsigned residual_samples,
  105579. unsigned predictor_order,
  105580. unsigned rice_parameter,
  105581. unsigned rice_parameter_limit,
  105582. unsigned min_partition_order,
  105583. unsigned max_partition_order,
  105584. unsigned bps,
  105585. FLAC__bool do_escape_coding,
  105586. unsigned rice_parameter_search_dist,
  105587. FLAC__EntropyCodingMethod *best_ecm
  105588. )
  105589. {
  105590. unsigned residual_bits, best_residual_bits = 0;
  105591. unsigned best_parameters_index = 0;
  105592. unsigned best_partition_order = 0;
  105593. const unsigned blocksize = residual_samples + predictor_order;
  105594. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(max_partition_order, blocksize, predictor_order);
  105595. min_partition_order = min(min_partition_order, max_partition_order);
  105596. precompute_partition_info_sums_(residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order, bps);
  105597. if(do_escape_coding)
  105598. precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
  105599. {
  105600. int partition_order;
  105601. unsigned sum;
  105602. for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) {
  105603. if(!
  105604. set_partitioned_rice_(
  105605. #ifdef EXACT_RICE_BITS_CALCULATION
  105606. residual,
  105607. #endif
  105608. abs_residual_partition_sums+sum,
  105609. raw_bits_per_partition+sum,
  105610. residual_samples,
  105611. predictor_order,
  105612. rice_parameter,
  105613. rice_parameter_limit,
  105614. rice_parameter_search_dist,
  105615. (unsigned)partition_order,
  105616. do_escape_coding,
  105617. &private_->partitioned_rice_contents_extra[!best_parameters_index],
  105618. &residual_bits
  105619. )
  105620. )
  105621. {
  105622. FLAC__ASSERT(best_residual_bits != 0);
  105623. break;
  105624. }
  105625. sum += 1u << partition_order;
  105626. if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
  105627. best_residual_bits = residual_bits;
  105628. best_parameters_index = !best_parameters_index;
  105629. best_partition_order = partition_order;
  105630. }
  105631. }
  105632. }
  105633. best_ecm->data.partitioned_rice.order = best_partition_order;
  105634. {
  105635. /*
  105636. * We are allowed to de-const the pointer based on our special
  105637. * knowledge; it is const to the outside world.
  105638. */
  105639. FLAC__EntropyCodingMethod_PartitionedRiceContents* prc = (FLAC__EntropyCodingMethod_PartitionedRiceContents*)best_ecm->data.partitioned_rice.contents;
  105640. unsigned partition;
  105641. /* save best parameters and raw_bits */
  105642. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(prc, max(6, best_partition_order));
  105643. memcpy(prc->parameters, private_->partitioned_rice_contents_extra[best_parameters_index].parameters, sizeof(unsigned)*(1<<(best_partition_order)));
  105644. if(do_escape_coding)
  105645. memcpy(prc->raw_bits, private_->partitioned_rice_contents_extra[best_parameters_index].raw_bits, sizeof(unsigned)*(1<<(best_partition_order)));
  105646. /*
  105647. * Now need to check if the type should be changed to
  105648. * FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 based on the
  105649. * size of the rice parameters.
  105650. */
  105651. for(partition = 0; partition < (1u<<best_partition_order); partition++) {
  105652. if(prc->parameters[partition] >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
  105653. best_ecm->type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2;
  105654. break;
  105655. }
  105656. }
  105657. }
  105658. return best_residual_bits;
  105659. }
  105660. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  105661. extern void precompute_partition_info_sums_32bit_asm_ia32_(
  105662. const FLAC__int32 residual[],
  105663. FLAC__uint64 abs_residual_partition_sums[],
  105664. unsigned blocksize,
  105665. unsigned predictor_order,
  105666. unsigned min_partition_order,
  105667. unsigned max_partition_order
  105668. );
  105669. #endif
  105670. void precompute_partition_info_sums_(
  105671. const FLAC__int32 residual[],
  105672. FLAC__uint64 abs_residual_partition_sums[],
  105673. unsigned residual_samples,
  105674. unsigned predictor_order,
  105675. unsigned min_partition_order,
  105676. unsigned max_partition_order,
  105677. unsigned bps
  105678. )
  105679. {
  105680. const unsigned default_partition_samples = (residual_samples + predictor_order) >> max_partition_order;
  105681. unsigned partitions = 1u << max_partition_order;
  105682. FLAC__ASSERT(default_partition_samples > predictor_order);
  105683. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  105684. /* slightly pessimistic but still catches all common cases */
  105685. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  105686. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  105687. precompute_partition_info_sums_32bit_asm_ia32_(residual, abs_residual_partition_sums, residual_samples + predictor_order, predictor_order, min_partition_order, max_partition_order);
  105688. return;
  105689. }
  105690. #endif
  105691. /* first do max_partition_order */
  105692. {
  105693. unsigned partition, residual_sample, end = (unsigned)(-(int)predictor_order);
  105694. /* slightly pessimistic but still catches all common cases */
  105695. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  105696. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  105697. FLAC__uint32 abs_residual_partition_sum;
  105698. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105699. end += default_partition_samples;
  105700. abs_residual_partition_sum = 0;
  105701. for( ; residual_sample < end; residual_sample++)
  105702. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  105703. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  105704. }
  105705. }
  105706. else { /* have to pessimistically use 64 bits for accumulator */
  105707. FLAC__uint64 abs_residual_partition_sum;
  105708. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105709. end += default_partition_samples;
  105710. abs_residual_partition_sum = 0;
  105711. for( ; residual_sample < end; residual_sample++)
  105712. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  105713. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  105714. }
  105715. }
  105716. }
  105717. /* now merge partitions for lower orders */
  105718. {
  105719. unsigned from_partition = 0, to_partition = partitions;
  105720. int partition_order;
  105721. for(partition_order = (int)max_partition_order - 1; partition_order >= (int)min_partition_order; partition_order--) {
  105722. unsigned i;
  105723. partitions >>= 1;
  105724. for(i = 0; i < partitions; i++) {
  105725. abs_residual_partition_sums[to_partition++] =
  105726. abs_residual_partition_sums[from_partition ] +
  105727. abs_residual_partition_sums[from_partition+1];
  105728. from_partition += 2;
  105729. }
  105730. }
  105731. }
  105732. }
  105733. void precompute_partition_info_escapes_(
  105734. const FLAC__int32 residual[],
  105735. unsigned raw_bits_per_partition[],
  105736. unsigned residual_samples,
  105737. unsigned predictor_order,
  105738. unsigned min_partition_order,
  105739. unsigned max_partition_order
  105740. )
  105741. {
  105742. int partition_order;
  105743. unsigned from_partition, to_partition = 0;
  105744. const unsigned blocksize = residual_samples + predictor_order;
  105745. /* first do max_partition_order */
  105746. for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
  105747. FLAC__int32 r;
  105748. FLAC__uint32 rmax;
  105749. unsigned partition, partition_sample, partition_samples, residual_sample;
  105750. const unsigned partitions = 1u << partition_order;
  105751. const unsigned default_partition_samples = blocksize >> partition_order;
  105752. FLAC__ASSERT(default_partition_samples > predictor_order);
  105753. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105754. partition_samples = default_partition_samples;
  105755. if(partition == 0)
  105756. partition_samples -= predictor_order;
  105757. rmax = 0;
  105758. for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
  105759. r = residual[residual_sample++];
  105760. /* OPT: maybe faster: rmax |= r ^ (r>>31) */
  105761. if(r < 0)
  105762. rmax |= ~r;
  105763. else
  105764. rmax |= r;
  105765. }
  105766. /* now we know all residual values are in the range [-rmax-1,rmax] */
  105767. raw_bits_per_partition[partition] = rmax? FLAC__bitmath_ilog2(rmax) + 2 : 1;
  105768. }
  105769. to_partition = partitions;
  105770. break; /*@@@ yuck, should remove the 'for' loop instead */
  105771. }
  105772. /* now merge partitions for lower orders */
  105773. for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
  105774. unsigned m;
  105775. unsigned i;
  105776. const unsigned partitions = 1u << partition_order;
  105777. for(i = 0; i < partitions; i++) {
  105778. m = raw_bits_per_partition[from_partition];
  105779. from_partition++;
  105780. raw_bits_per_partition[to_partition] = max(m, raw_bits_per_partition[from_partition]);
  105781. from_partition++;
  105782. to_partition++;
  105783. }
  105784. }
  105785. }
  105786. #ifdef EXACT_RICE_BITS_CALCULATION
  105787. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  105788. const unsigned rice_parameter,
  105789. const unsigned partition_samples,
  105790. const FLAC__int32 *residual
  105791. )
  105792. {
  105793. unsigned i, partition_bits =
  105794. 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 */
  105795. (1+rice_parameter) * partition_samples /* 1 for unary stop bit + rice_parameter for the binary portion */
  105796. ;
  105797. for(i = 0; i < partition_samples; i++)
  105798. partition_bits += ( (FLAC__uint32)((residual[i]<<1)^(residual[i]>>31)) >> rice_parameter );
  105799. return partition_bits;
  105800. }
  105801. #else
  105802. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  105803. const unsigned rice_parameter,
  105804. const unsigned partition_samples,
  105805. const FLAC__uint64 abs_residual_partition_sum
  105806. )
  105807. {
  105808. return
  105809. 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 */
  105810. (1+rice_parameter) * partition_samples + /* 1 for unary stop bit + rice_parameter for the binary portion */
  105811. (
  105812. rice_parameter?
  105813. (unsigned)(abs_residual_partition_sum >> (rice_parameter-1)) /* rice_parameter-1 because the real coder sign-folds instead of using a sign bit */
  105814. : (unsigned)(abs_residual_partition_sum << 1) /* can't shift by negative number, so reverse */
  105815. )
  105816. - (partition_samples >> 1)
  105817. /* -(partition_samples>>1) to subtract out extra contributions to the abs_residual_partition_sum.
  105818. * The actual number of bits used is closer to the sum(for all i in the partition) of abs(residual[i])>>(rice_parameter-1)
  105819. * By using the abs_residual_partition sum, we also add in bits in the LSBs that would normally be shifted out.
  105820. * So the subtraction term tries to guess how many extra bits were contributed.
  105821. * If the LSBs are randomly distributed, this should average to 0.5 extra bits per sample.
  105822. */
  105823. ;
  105824. }
  105825. #endif
  105826. FLAC__bool set_partitioned_rice_(
  105827. #ifdef EXACT_RICE_BITS_CALCULATION
  105828. const FLAC__int32 residual[],
  105829. #endif
  105830. const FLAC__uint64 abs_residual_partition_sums[],
  105831. const unsigned raw_bits_per_partition[],
  105832. const unsigned residual_samples,
  105833. const unsigned predictor_order,
  105834. const unsigned suggested_rice_parameter,
  105835. const unsigned rice_parameter_limit,
  105836. const unsigned rice_parameter_search_dist,
  105837. const unsigned partition_order,
  105838. const FLAC__bool search_for_escapes,
  105839. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  105840. unsigned *bits
  105841. )
  105842. {
  105843. unsigned rice_parameter, partition_bits;
  105844. unsigned best_partition_bits, best_rice_parameter = 0;
  105845. unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
  105846. unsigned *parameters, *raw_bits;
  105847. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105848. unsigned min_rice_parameter, max_rice_parameter;
  105849. #else
  105850. (void)rice_parameter_search_dist;
  105851. #endif
  105852. FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  105853. FLAC__ASSERT(rice_parameter_limit <= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  105854. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order));
  105855. parameters = partitioned_rice_contents->parameters;
  105856. raw_bits = partitioned_rice_contents->raw_bits;
  105857. if(partition_order == 0) {
  105858. best_partition_bits = (unsigned)(-1);
  105859. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105860. if(rice_parameter_search_dist) {
  105861. if(suggested_rice_parameter < rice_parameter_search_dist)
  105862. min_rice_parameter = 0;
  105863. else
  105864. min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
  105865. max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
  105866. if(max_rice_parameter >= rice_parameter_limit) {
  105867. #ifdef DEBUG_VERBOSE
  105868. fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, rice_parameter_limit - 1);
  105869. #endif
  105870. max_rice_parameter = rice_parameter_limit - 1;
  105871. }
  105872. }
  105873. else
  105874. min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
  105875. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  105876. #else
  105877. rice_parameter = suggested_rice_parameter;
  105878. #endif
  105879. #ifdef EXACT_RICE_BITS_CALCULATION
  105880. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, residual);
  105881. #else
  105882. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, abs_residual_partition_sums[0]);
  105883. #endif
  105884. if(partition_bits < best_partition_bits) {
  105885. best_rice_parameter = rice_parameter;
  105886. best_partition_bits = partition_bits;
  105887. }
  105888. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105889. }
  105890. #endif
  105891. if(search_for_escapes) {
  105892. 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;
  105893. if(partition_bits <= best_partition_bits) {
  105894. raw_bits[0] = raw_bits_per_partition[0];
  105895. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  105896. best_partition_bits = partition_bits;
  105897. }
  105898. else
  105899. raw_bits[0] = 0;
  105900. }
  105901. parameters[0] = best_rice_parameter;
  105902. bits_ += best_partition_bits;
  105903. }
  105904. else {
  105905. unsigned partition, residual_sample;
  105906. unsigned partition_samples;
  105907. FLAC__uint64 mean, k;
  105908. const unsigned partitions = 1u << partition_order;
  105909. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105910. partition_samples = (residual_samples+predictor_order) >> partition_order;
  105911. if(partition == 0) {
  105912. if(partition_samples <= predictor_order)
  105913. return false;
  105914. else
  105915. partition_samples -= predictor_order;
  105916. }
  105917. mean = abs_residual_partition_sums[partition];
  105918. /* we are basically calculating the size in bits of the
  105919. * average residual magnitude in the partition:
  105920. * rice_parameter = floor(log2(mean/partition_samples))
  105921. * 'mean' is not a good name for the variable, it is
  105922. * actually the sum of magnitudes of all residual values
  105923. * in the partition, so the actual mean is
  105924. * mean/partition_samples
  105925. */
  105926. for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
  105927. ;
  105928. if(rice_parameter >= rice_parameter_limit) {
  105929. #ifdef DEBUG_VERBOSE
  105930. fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, rice_parameter_limit - 1);
  105931. #endif
  105932. rice_parameter = rice_parameter_limit - 1;
  105933. }
  105934. best_partition_bits = (unsigned)(-1);
  105935. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105936. if(rice_parameter_search_dist) {
  105937. if(rice_parameter < rice_parameter_search_dist)
  105938. min_rice_parameter = 0;
  105939. else
  105940. min_rice_parameter = rice_parameter - rice_parameter_search_dist;
  105941. max_rice_parameter = rice_parameter + rice_parameter_search_dist;
  105942. if(max_rice_parameter >= rice_parameter_limit) {
  105943. #ifdef DEBUG_VERBOSE
  105944. fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, rice_parameter_limit - 1);
  105945. #endif
  105946. max_rice_parameter = rice_parameter_limit - 1;
  105947. }
  105948. }
  105949. else
  105950. min_rice_parameter = max_rice_parameter = rice_parameter;
  105951. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  105952. #endif
  105953. #ifdef EXACT_RICE_BITS_CALCULATION
  105954. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, residual+residual_sample);
  105955. #else
  105956. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, abs_residual_partition_sums[partition]);
  105957. #endif
  105958. if(partition_bits < best_partition_bits) {
  105959. best_rice_parameter = rice_parameter;
  105960. best_partition_bits = partition_bits;
  105961. }
  105962. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105963. }
  105964. #endif
  105965. if(search_for_escapes) {
  105966. 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;
  105967. if(partition_bits <= best_partition_bits) {
  105968. raw_bits[partition] = raw_bits_per_partition[partition];
  105969. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  105970. best_partition_bits = partition_bits;
  105971. }
  105972. else
  105973. raw_bits[partition] = 0;
  105974. }
  105975. parameters[partition] = best_rice_parameter;
  105976. bits_ += best_partition_bits;
  105977. residual_sample += partition_samples;
  105978. }
  105979. }
  105980. *bits = bits_;
  105981. return true;
  105982. }
  105983. unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples)
  105984. {
  105985. unsigned i, shift;
  105986. FLAC__int32 x = 0;
  105987. for(i = 0; i < samples && !(x&1); i++)
  105988. x |= signal[i];
  105989. if(x == 0) {
  105990. shift = 0;
  105991. }
  105992. else {
  105993. for(shift = 0; !(x&1); shift++)
  105994. x >>= 1;
  105995. }
  105996. if(shift > 0) {
  105997. for(i = 0; i < samples; i++)
  105998. signal[i] >>= shift;
  105999. }
  106000. return shift;
  106001. }
  106002. void append_to_verify_fifo_(verify_input_fifo *fifo, const FLAC__int32 * const input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  106003. {
  106004. unsigned channel;
  106005. for(channel = 0; channel < channels; channel++)
  106006. memcpy(&fifo->data[channel][fifo->tail], &input[channel][input_offset], sizeof(FLAC__int32) * wide_samples);
  106007. fifo->tail += wide_samples;
  106008. FLAC__ASSERT(fifo->tail <= fifo->size);
  106009. }
  106010. void append_to_verify_fifo_interleaved_(verify_input_fifo *fifo, const FLAC__int32 input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  106011. {
  106012. unsigned channel;
  106013. unsigned sample, wide_sample;
  106014. unsigned tail = fifo->tail;
  106015. sample = input_offset * channels;
  106016. for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
  106017. for(channel = 0; channel < channels; channel++)
  106018. fifo->data[channel][tail] = input[sample++];
  106019. tail++;
  106020. }
  106021. fifo->tail = tail;
  106022. FLAC__ASSERT(fifo->tail <= fifo->size);
  106023. }
  106024. FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  106025. {
  106026. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  106027. const size_t encoded_bytes = encoder->private_->verify.output.bytes;
  106028. (void)decoder;
  106029. if(encoder->private_->verify.needs_magic_hack) {
  106030. FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH);
  106031. *bytes = FLAC__STREAM_SYNC_LENGTH;
  106032. memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes);
  106033. encoder->private_->verify.needs_magic_hack = false;
  106034. }
  106035. else {
  106036. if(encoded_bytes == 0) {
  106037. /*
  106038. * If we get here, a FIFO underflow has occurred,
  106039. * which means there is a bug somewhere.
  106040. */
  106041. FLAC__ASSERT(0);
  106042. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  106043. }
  106044. else if(encoded_bytes < *bytes)
  106045. *bytes = encoded_bytes;
  106046. memcpy(buffer, encoder->private_->verify.output.data, *bytes);
  106047. encoder->private_->verify.output.data += *bytes;
  106048. encoder->private_->verify.output.bytes -= *bytes;
  106049. }
  106050. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  106051. }
  106052. FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
  106053. {
  106054. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder *)client_data;
  106055. unsigned channel;
  106056. const unsigned channels = frame->header.channels;
  106057. const unsigned blocksize = frame->header.blocksize;
  106058. const unsigned bytes_per_block = sizeof(FLAC__int32) * blocksize;
  106059. (void)decoder;
  106060. for(channel = 0; channel < channels; channel++) {
  106061. if(0 != memcmp(buffer[channel], encoder->private_->verify.input_fifo.data[channel], bytes_per_block)) {
  106062. unsigned i, sample = 0;
  106063. FLAC__int32 expect = 0, got = 0;
  106064. for(i = 0; i < blocksize; i++) {
  106065. if(buffer[channel][i] != encoder->private_->verify.input_fifo.data[channel][i]) {
  106066. sample = i;
  106067. expect = (FLAC__int32)encoder->private_->verify.input_fifo.data[channel][i];
  106068. got = (FLAC__int32)buffer[channel][i];
  106069. break;
  106070. }
  106071. }
  106072. FLAC__ASSERT(i < blocksize);
  106073. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  106074. encoder->private_->verify.error_stats.absolute_sample = frame->header.number.sample_number + sample;
  106075. encoder->private_->verify.error_stats.frame_number = (unsigned)(frame->header.number.sample_number / blocksize);
  106076. encoder->private_->verify.error_stats.channel = channel;
  106077. encoder->private_->verify.error_stats.sample = sample;
  106078. encoder->private_->verify.error_stats.expected = expect;
  106079. encoder->private_->verify.error_stats.got = got;
  106080. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  106081. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  106082. }
  106083. }
  106084. /* dequeue the frame from the fifo */
  106085. encoder->private_->verify.input_fifo.tail -= blocksize;
  106086. FLAC__ASSERT(encoder->private_->verify.input_fifo.tail <= OVERREAD_);
  106087. for(channel = 0; channel < channels; channel++)
  106088. 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]));
  106089. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  106090. }
  106091. void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
  106092. {
  106093. (void)decoder, (void)metadata, (void)client_data;
  106094. }
  106095. void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
  106096. {
  106097. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  106098. (void)decoder, (void)status;
  106099. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  106100. }
  106101. FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  106102. {
  106103. (void)client_data;
  106104. *bytes = fread(buffer, 1, *bytes, encoder->private_->file);
  106105. if (*bytes == 0) {
  106106. if (feof(encoder->private_->file))
  106107. return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  106108. else if (ferror(encoder->private_->file))
  106109. return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  106110. }
  106111. return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  106112. }
  106113. FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  106114. {
  106115. (void)client_data;
  106116. if(fseeko(encoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  106117. return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  106118. else
  106119. return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  106120. }
  106121. FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  106122. {
  106123. off_t offset;
  106124. (void)client_data;
  106125. offset = ftello(encoder->private_->file);
  106126. if(offset < 0) {
  106127. return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  106128. }
  106129. else {
  106130. *absolute_byte_offset = (FLAC__uint64)offset;
  106131. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  106132. }
  106133. }
  106134. #ifdef FLAC__VALGRIND_TESTING
  106135. static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
  106136. {
  106137. size_t ret = fwrite(ptr, size, nmemb, stream);
  106138. if(!ferror(stream))
  106139. fflush(stream);
  106140. return ret;
  106141. }
  106142. #else
  106143. #define local__fwrite fwrite
  106144. #endif
  106145. FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data)
  106146. {
  106147. (void)client_data, (void)current_frame;
  106148. if(local__fwrite(buffer, sizeof(FLAC__byte), bytes, encoder->private_->file) == bytes) {
  106149. FLAC__bool call_it = 0 != encoder->private_->progress_callback && (
  106150. #if FLAC__HAS_OGG
  106151. /* We would like to be able to use 'samples > 0' in the
  106152. * clause here but currently because of the nature of our
  106153. * Ogg writing implementation, 'samples' is always 0 (see
  106154. * ogg_encoder_aspect.c). The downside is extra progress
  106155. * callbacks.
  106156. */
  106157. encoder->private_->is_ogg? true :
  106158. #endif
  106159. samples > 0
  106160. );
  106161. if(call_it) {
  106162. /* NOTE: We have to add +bytes, +samples, and +1 to the stats
  106163. * because at this point in the callback chain, the stats
  106164. * have not been updated. Only after we return and control
  106165. * gets back to write_frame_() are the stats updated
  106166. */
  106167. 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);
  106168. }
  106169. return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
  106170. }
  106171. else
  106172. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  106173. }
  106174. /*
  106175. * This will forcibly set stdout to binary mode (for OSes that require it)
  106176. */
  106177. FILE *get_binary_stdout_(void)
  106178. {
  106179. /* if something breaks here it is probably due to the presence or
  106180. * absence of an underscore before the identifiers 'setmode',
  106181. * 'fileno', and/or 'O_BINARY'; check your system header files.
  106182. */
  106183. #if defined _MSC_VER || defined __MINGW32__
  106184. _setmode(_fileno(stdout), _O_BINARY);
  106185. #elif defined __CYGWIN__
  106186. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  106187. setmode(_fileno(stdout), _O_BINARY);
  106188. #elif defined __EMX__
  106189. setmode(fileno(stdout), O_BINARY);
  106190. #endif
  106191. return stdout;
  106192. }
  106193. #endif
  106194. /*** End of inlined file: stream_encoder.c ***/
  106195. /*** Start of inlined file: stream_encoder_framing.c ***/
  106196. /*** Start of inlined file: juce_FlacHeader.h ***/
  106197. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  106198. // tasks..
  106199. #define VERSION "1.2.1"
  106200. #define FLAC__NO_DLL 1
  106201. #if JUCE_MSVC
  106202. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  106203. #endif
  106204. #if JUCE_MAC
  106205. #define FLAC__SYS_DARWIN 1
  106206. #endif
  106207. /*** End of inlined file: juce_FlacHeader.h ***/
  106208. #if JUCE_USE_FLAC
  106209. #if HAVE_CONFIG_H
  106210. # include <config.h>
  106211. #endif
  106212. #include <stdio.h>
  106213. #include <string.h> /* for strlen() */
  106214. #ifdef max
  106215. #undef max
  106216. #endif
  106217. #define max(x,y) ((x)>(y)?(x):(y))
  106218. static FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method);
  106219. 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);
  106220. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw)
  106221. {
  106222. unsigned i, j;
  106223. const unsigned vendor_string_length = (unsigned)strlen(FLAC__VENDOR_STRING);
  106224. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->is_last, FLAC__STREAM_METADATA_IS_LAST_LEN))
  106225. return false;
  106226. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->type, FLAC__STREAM_METADATA_TYPE_LEN))
  106227. return false;
  106228. /*
  106229. * First, for VORBIS_COMMENTs, adjust the length to reflect our vendor string
  106230. */
  106231. i = metadata->length;
  106232. if(metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  106233. FLAC__ASSERT(metadata->data.vorbis_comment.vendor_string.length == 0 || 0 != metadata->data.vorbis_comment.vendor_string.entry);
  106234. i -= metadata->data.vorbis_comment.vendor_string.length;
  106235. i += vendor_string_length;
  106236. }
  106237. FLAC__ASSERT(i < (1u << FLAC__STREAM_METADATA_LENGTH_LEN));
  106238. if(!FLAC__bitwriter_write_raw_uint32(bw, i, FLAC__STREAM_METADATA_LENGTH_LEN))
  106239. return false;
  106240. switch(metadata->type) {
  106241. case FLAC__METADATA_TYPE_STREAMINFO:
  106242. FLAC__ASSERT(metadata->data.stream_info.min_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN));
  106243. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN))
  106244. return false;
  106245. FLAC__ASSERT(metadata->data.stream_info.max_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN));
  106246. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  106247. return false;
  106248. FLAC__ASSERT(metadata->data.stream_info.min_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN));
  106249. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_framesize, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  106250. return false;
  106251. FLAC__ASSERT(metadata->data.stream_info.max_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN));
  106252. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_framesize, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  106253. return false;
  106254. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(metadata->data.stream_info.sample_rate));
  106255. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.sample_rate, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  106256. return false;
  106257. FLAC__ASSERT(metadata->data.stream_info.channels > 0);
  106258. FLAC__ASSERT(metadata->data.stream_info.channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN));
  106259. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.channels-1, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  106260. return false;
  106261. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample > 0);
  106262. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  106263. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.bits_per_sample-1, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  106264. return false;
  106265. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.stream_info.total_samples, FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN))
  106266. return false;
  106267. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.stream_info.md5sum, 16))
  106268. return false;
  106269. break;
  106270. case FLAC__METADATA_TYPE_PADDING:
  106271. if(!FLAC__bitwriter_write_zeroes(bw, metadata->length * 8))
  106272. return false;
  106273. break;
  106274. case FLAC__METADATA_TYPE_APPLICATION:
  106275. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8))
  106276. return false;
  106277. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.data, metadata->length - (FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8)))
  106278. return false;
  106279. break;
  106280. case FLAC__METADATA_TYPE_SEEKTABLE:
  106281. for(i = 0; i < metadata->data.seek_table.num_points; i++) {
  106282. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].sample_number, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  106283. return false;
  106284. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].stream_offset, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  106285. return false;
  106286. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.seek_table.points[i].frame_samples, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  106287. return false;
  106288. }
  106289. break;
  106290. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  106291. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, vendor_string_length))
  106292. return false;
  106293. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)FLAC__VENDOR_STRING, vendor_string_length))
  106294. return false;
  106295. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.num_comments))
  106296. return false;
  106297. for(i = 0; i < metadata->data.vorbis_comment.num_comments; i++) {
  106298. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.comments[i].length))
  106299. return false;
  106300. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.vorbis_comment.comments[i].entry, metadata->data.vorbis_comment.comments[i].length))
  106301. return false;
  106302. }
  106303. break;
  106304. case FLAC__METADATA_TYPE_CUESHEET:
  106305. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  106306. 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))
  106307. return false;
  106308. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.cue_sheet.lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  106309. return false;
  106310. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.is_cd? 1 : 0, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  106311. return false;
  106312. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  106313. return false;
  106314. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.num_tracks, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  106315. return false;
  106316. for(i = 0; i < metadata->data.cue_sheet.num_tracks; i++) {
  106317. const FLAC__StreamMetadata_CueSheet_Track *track = metadata->data.cue_sheet.tracks + i;
  106318. if(!FLAC__bitwriter_write_raw_uint64(bw, track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  106319. return false;
  106320. if(!FLAC__bitwriter_write_raw_uint32(bw, track->number, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  106321. return false;
  106322. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  106323. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  106324. return false;
  106325. if(!FLAC__bitwriter_write_raw_uint32(bw, track->type, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  106326. return false;
  106327. if(!FLAC__bitwriter_write_raw_uint32(bw, track->pre_emphasis, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  106328. return false;
  106329. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  106330. return false;
  106331. if(!FLAC__bitwriter_write_raw_uint32(bw, track->num_indices, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  106332. return false;
  106333. for(j = 0; j < track->num_indices; j++) {
  106334. const FLAC__StreamMetadata_CueSheet_Index *index = track->indices + j;
  106335. if(!FLAC__bitwriter_write_raw_uint64(bw, index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  106336. return false;
  106337. if(!FLAC__bitwriter_write_raw_uint32(bw, index->number, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  106338. return false;
  106339. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  106340. return false;
  106341. }
  106342. }
  106343. break;
  106344. case FLAC__METADATA_TYPE_PICTURE:
  106345. {
  106346. size_t len;
  106347. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.type, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  106348. return false;
  106349. len = strlen(metadata->data.picture.mime_type);
  106350. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  106351. return false;
  106352. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)metadata->data.picture.mime_type, len))
  106353. return false;
  106354. len = strlen((const char *)metadata->data.picture.description);
  106355. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  106356. return false;
  106357. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.description, len))
  106358. return false;
  106359. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  106360. return false;
  106361. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  106362. return false;
  106363. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  106364. return false;
  106365. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  106366. return false;
  106367. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.data_length, FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  106368. return false;
  106369. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.data, metadata->data.picture.data_length))
  106370. return false;
  106371. }
  106372. break;
  106373. default:
  106374. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.unknown.data, metadata->length))
  106375. return false;
  106376. break;
  106377. }
  106378. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  106379. return true;
  106380. }
  106381. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw)
  106382. {
  106383. unsigned u, blocksize_hint, sample_rate_hint;
  106384. FLAC__byte crc;
  106385. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  106386. if(!FLAC__bitwriter_write_raw_uint32(bw, FLAC__FRAME_HEADER_SYNC, FLAC__FRAME_HEADER_SYNC_LEN))
  106387. return false;
  106388. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_RESERVED_LEN))
  106389. return false;
  106390. if(!FLAC__bitwriter_write_raw_uint32(bw, (header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER)? 0 : 1, FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN))
  106391. return false;
  106392. FLAC__ASSERT(header->blocksize > 0 && header->blocksize <= FLAC__MAX_BLOCK_SIZE);
  106393. /* when this assertion holds true, any legal blocksize can be expressed in the frame header */
  106394. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535u);
  106395. blocksize_hint = 0;
  106396. switch(header->blocksize) {
  106397. case 192: u = 1; break;
  106398. case 576: u = 2; break;
  106399. case 1152: u = 3; break;
  106400. case 2304: u = 4; break;
  106401. case 4608: u = 5; break;
  106402. case 256: u = 8; break;
  106403. case 512: u = 9; break;
  106404. case 1024: u = 10; break;
  106405. case 2048: u = 11; break;
  106406. case 4096: u = 12; break;
  106407. case 8192: u = 13; break;
  106408. case 16384: u = 14; break;
  106409. case 32768: u = 15; break;
  106410. default:
  106411. if(header->blocksize <= 0x100)
  106412. blocksize_hint = u = 6;
  106413. else
  106414. blocksize_hint = u = 7;
  106415. break;
  106416. }
  106417. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BLOCK_SIZE_LEN))
  106418. return false;
  106419. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(header->sample_rate));
  106420. sample_rate_hint = 0;
  106421. switch(header->sample_rate) {
  106422. case 88200: u = 1; break;
  106423. case 176400: u = 2; break;
  106424. case 192000: u = 3; break;
  106425. case 8000: u = 4; break;
  106426. case 16000: u = 5; break;
  106427. case 22050: u = 6; break;
  106428. case 24000: u = 7; break;
  106429. case 32000: u = 8; break;
  106430. case 44100: u = 9; break;
  106431. case 48000: u = 10; break;
  106432. case 96000: u = 11; break;
  106433. default:
  106434. if(header->sample_rate <= 255000 && header->sample_rate % 1000 == 0)
  106435. sample_rate_hint = u = 12;
  106436. else if(header->sample_rate % 10 == 0)
  106437. sample_rate_hint = u = 14;
  106438. else if(header->sample_rate <= 0xffff)
  106439. sample_rate_hint = u = 13;
  106440. else
  106441. u = 0;
  106442. break;
  106443. }
  106444. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_SAMPLE_RATE_LEN))
  106445. return false;
  106446. FLAC__ASSERT(header->channels > 0 && header->channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN) && header->channels <= FLAC__MAX_CHANNELS);
  106447. switch(header->channel_assignment) {
  106448. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  106449. u = header->channels - 1;
  106450. break;
  106451. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  106452. FLAC__ASSERT(header->channels == 2);
  106453. u = 8;
  106454. break;
  106455. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  106456. FLAC__ASSERT(header->channels == 2);
  106457. u = 9;
  106458. break;
  106459. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  106460. FLAC__ASSERT(header->channels == 2);
  106461. u = 10;
  106462. break;
  106463. default:
  106464. FLAC__ASSERT(0);
  106465. }
  106466. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN))
  106467. return false;
  106468. FLAC__ASSERT(header->bits_per_sample > 0 && header->bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  106469. switch(header->bits_per_sample) {
  106470. case 8 : u = 1; break;
  106471. case 12: u = 2; break;
  106472. case 16: u = 4; break;
  106473. case 20: u = 5; break;
  106474. case 24: u = 6; break;
  106475. default: u = 0; break;
  106476. }
  106477. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN))
  106478. return false;
  106479. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_ZERO_PAD_LEN))
  106480. return false;
  106481. if(header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  106482. if(!FLAC__bitwriter_write_utf8_uint32(bw, header->number.frame_number))
  106483. return false;
  106484. }
  106485. else {
  106486. if(!FLAC__bitwriter_write_utf8_uint64(bw, header->number.sample_number))
  106487. return false;
  106488. }
  106489. if(blocksize_hint)
  106490. if(!FLAC__bitwriter_write_raw_uint32(bw, header->blocksize-1, (blocksize_hint==6)? 8:16))
  106491. return false;
  106492. switch(sample_rate_hint) {
  106493. case 12:
  106494. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 1000, 8))
  106495. return false;
  106496. break;
  106497. case 13:
  106498. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate, 16))
  106499. return false;
  106500. break;
  106501. case 14:
  106502. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 10, 16))
  106503. return false;
  106504. break;
  106505. }
  106506. /* write the CRC */
  106507. if(!FLAC__bitwriter_get_write_crc8(bw, &crc))
  106508. return false;
  106509. if(!FLAC__bitwriter_write_raw_uint32(bw, crc, FLAC__FRAME_HEADER_CRC_LEN))
  106510. return false;
  106511. return true;
  106512. }
  106513. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106514. {
  106515. FLAC__bool ok;
  106516. ok =
  106517. 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) &&
  106518. (wasted_bits? FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1) : true) &&
  106519. FLAC__bitwriter_write_raw_int32(bw, subframe->value, subframe_bps)
  106520. ;
  106521. return ok;
  106522. }
  106523. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106524. {
  106525. unsigned i;
  106526. 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))
  106527. return false;
  106528. if(wasted_bits)
  106529. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  106530. return false;
  106531. for(i = 0; i < subframe->order; i++)
  106532. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  106533. return false;
  106534. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  106535. return false;
  106536. switch(subframe->entropy_coding_method.type) {
  106537. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  106538. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  106539. if(!add_residual_partitioned_rice_(
  106540. bw,
  106541. subframe->residual,
  106542. residual_samples,
  106543. subframe->order,
  106544. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  106545. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  106546. subframe->entropy_coding_method.data.partitioned_rice.order,
  106547. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  106548. ))
  106549. return false;
  106550. break;
  106551. default:
  106552. FLAC__ASSERT(0);
  106553. }
  106554. return true;
  106555. }
  106556. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106557. {
  106558. unsigned i;
  106559. 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))
  106560. return false;
  106561. if(wasted_bits)
  106562. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  106563. return false;
  106564. for(i = 0; i < subframe->order; i++)
  106565. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  106566. return false;
  106567. if(!FLAC__bitwriter_write_raw_uint32(bw, subframe->qlp_coeff_precision-1, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  106568. return false;
  106569. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->quantization_level, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  106570. return false;
  106571. for(i = 0; i < subframe->order; i++)
  106572. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->qlp_coeff[i], subframe->qlp_coeff_precision))
  106573. return false;
  106574. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  106575. return false;
  106576. switch(subframe->entropy_coding_method.type) {
  106577. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  106578. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  106579. if(!add_residual_partitioned_rice_(
  106580. bw,
  106581. subframe->residual,
  106582. residual_samples,
  106583. subframe->order,
  106584. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  106585. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  106586. subframe->entropy_coding_method.data.partitioned_rice.order,
  106587. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  106588. ))
  106589. return false;
  106590. break;
  106591. default:
  106592. FLAC__ASSERT(0);
  106593. }
  106594. return true;
  106595. }
  106596. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106597. {
  106598. unsigned i;
  106599. const FLAC__int32 *signal = subframe->data;
  106600. 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))
  106601. return false;
  106602. if(wasted_bits)
  106603. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  106604. return false;
  106605. for(i = 0; i < samples; i++)
  106606. if(!FLAC__bitwriter_write_raw_int32(bw, signal[i], subframe_bps))
  106607. return false;
  106608. return true;
  106609. }
  106610. FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method)
  106611. {
  106612. if(!FLAC__bitwriter_write_raw_uint32(bw, method->type, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  106613. return false;
  106614. switch(method->type) {
  106615. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  106616. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  106617. if(!FLAC__bitwriter_write_raw_uint32(bw, method->data.partitioned_rice.order, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  106618. return false;
  106619. break;
  106620. default:
  106621. FLAC__ASSERT(0);
  106622. }
  106623. return true;
  106624. }
  106625. 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)
  106626. {
  106627. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  106628. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  106629. if(partition_order == 0) {
  106630. unsigned i;
  106631. if(raw_bits[0] == 0) {
  106632. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[0], plen))
  106633. return false;
  106634. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual, residual_samples, rice_parameters[0]))
  106635. return false;
  106636. }
  106637. else {
  106638. FLAC__ASSERT(rice_parameters[0] == 0);
  106639. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  106640. return false;
  106641. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[0], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  106642. return false;
  106643. for(i = 0; i < residual_samples; i++) {
  106644. if(!FLAC__bitwriter_write_raw_int32(bw, residual[i], raw_bits[0]))
  106645. return false;
  106646. }
  106647. }
  106648. return true;
  106649. }
  106650. else {
  106651. unsigned i, j, k = 0, k_last = 0;
  106652. unsigned partition_samples;
  106653. const unsigned default_partition_samples = (residual_samples+predictor_order) >> partition_order;
  106654. for(i = 0; i < (1u<<partition_order); i++) {
  106655. partition_samples = default_partition_samples;
  106656. if(i == 0)
  106657. partition_samples -= predictor_order;
  106658. k += partition_samples;
  106659. if(raw_bits[i] == 0) {
  106660. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[i], plen))
  106661. return false;
  106662. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual+k_last, k-k_last, rice_parameters[i]))
  106663. return false;
  106664. }
  106665. else {
  106666. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  106667. return false;
  106668. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[i], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  106669. return false;
  106670. for(j = k_last; j < k; j++) {
  106671. if(!FLAC__bitwriter_write_raw_int32(bw, residual[j], raw_bits[i]))
  106672. return false;
  106673. }
  106674. }
  106675. k_last = k;
  106676. }
  106677. return true;
  106678. }
  106679. }
  106680. #endif
  106681. /*** End of inlined file: stream_encoder_framing.c ***/
  106682. /*** Start of inlined file: window_flac.c ***/
  106683. /*** Start of inlined file: juce_FlacHeader.h ***/
  106684. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  106685. // tasks..
  106686. #define VERSION "1.2.1"
  106687. #define FLAC__NO_DLL 1
  106688. #if JUCE_MSVC
  106689. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  106690. #endif
  106691. #if JUCE_MAC
  106692. #define FLAC__SYS_DARWIN 1
  106693. #endif
  106694. /*** End of inlined file: juce_FlacHeader.h ***/
  106695. #if JUCE_USE_FLAC
  106696. #if HAVE_CONFIG_H
  106697. # include <config.h>
  106698. #endif
  106699. #include <math.h>
  106700. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  106701. #ifndef M_PI
  106702. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  106703. #define M_PI 3.14159265358979323846
  106704. #endif
  106705. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L)
  106706. {
  106707. const FLAC__int32 N = L - 1;
  106708. FLAC__int32 n;
  106709. if (L & 1) {
  106710. for (n = 0; n <= N/2; n++)
  106711. window[n] = 2.0f * n / (float)N;
  106712. for (; n <= N; n++)
  106713. window[n] = 2.0f - 2.0f * n / (float)N;
  106714. }
  106715. else {
  106716. for (n = 0; n <= L/2-1; n++)
  106717. window[n] = 2.0f * n / (float)N;
  106718. for (; n <= N; n++)
  106719. window[n] = 2.0f - 2.0f * (N-n) / (float)N;
  106720. }
  106721. }
  106722. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L)
  106723. {
  106724. const FLAC__int32 N = L - 1;
  106725. FLAC__int32 n;
  106726. for (n = 0; n < L; n++)
  106727. 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)));
  106728. }
  106729. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L)
  106730. {
  106731. const FLAC__int32 N = L - 1;
  106732. FLAC__int32 n;
  106733. for (n = 0; n < L; n++)
  106734. window[n] = (FLAC__real)(0.42f - 0.5f * cos(2.0f * M_PI * n / N) + 0.08f * cos(4.0f * M_PI * n / N));
  106735. }
  106736. /* 4-term -92dB side-lobe */
  106737. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L)
  106738. {
  106739. const FLAC__int32 N = L - 1;
  106740. FLAC__int32 n;
  106741. for (n = 0; n <= N; n++)
  106742. 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));
  106743. }
  106744. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L)
  106745. {
  106746. const FLAC__int32 N = L - 1;
  106747. const double N2 = (double)N / 2.;
  106748. FLAC__int32 n;
  106749. for (n = 0; n <= N; n++) {
  106750. double k = ((double)n - N2) / N2;
  106751. k = 1.0f - k * k;
  106752. window[n] = (FLAC__real)(k * k);
  106753. }
  106754. }
  106755. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L)
  106756. {
  106757. const FLAC__int32 N = L - 1;
  106758. FLAC__int32 n;
  106759. for (n = 0; n < L; n++)
  106760. 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));
  106761. }
  106762. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev)
  106763. {
  106764. const FLAC__int32 N = L - 1;
  106765. const double N2 = (double)N / 2.;
  106766. FLAC__int32 n;
  106767. for (n = 0; n <= N; n++) {
  106768. const double k = ((double)n - N2) / (stddev * N2);
  106769. window[n] = (FLAC__real)exp(-0.5f * k * k);
  106770. }
  106771. }
  106772. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L)
  106773. {
  106774. const FLAC__int32 N = L - 1;
  106775. FLAC__int32 n;
  106776. for (n = 0; n < L; n++)
  106777. window[n] = (FLAC__real)(0.54f - 0.46f * cos(2.0f * M_PI * n / N));
  106778. }
  106779. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L)
  106780. {
  106781. const FLAC__int32 N = L - 1;
  106782. FLAC__int32 n;
  106783. for (n = 0; n < L; n++)
  106784. window[n] = (FLAC__real)(0.5f - 0.5f * cos(2.0f * M_PI * n / N));
  106785. }
  106786. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L)
  106787. {
  106788. const FLAC__int32 N = L - 1;
  106789. FLAC__int32 n;
  106790. for (n = 0; n < L; n++)
  106791. 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));
  106792. }
  106793. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L)
  106794. {
  106795. const FLAC__int32 N = L - 1;
  106796. FLAC__int32 n;
  106797. for (n = 0; n < L; n++)
  106798. 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));
  106799. }
  106800. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L)
  106801. {
  106802. FLAC__int32 n;
  106803. for (n = 0; n < L; n++)
  106804. window[n] = 1.0f;
  106805. }
  106806. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L)
  106807. {
  106808. FLAC__int32 n;
  106809. if (L & 1) {
  106810. for (n = 1; n <= L+1/2; n++)
  106811. window[n-1] = 2.0f * n / ((float)L + 1.0f);
  106812. for (; n <= L; n++)
  106813. window[n-1] = - (float)(2 * (L - n + 1)) / ((float)L + 1.0f);
  106814. }
  106815. else {
  106816. for (n = 1; n <= L/2; n++)
  106817. window[n-1] = 2.0f * n / (float)L;
  106818. for (; n <= L; n++)
  106819. window[n-1] = ((float)(2 * (L - n)) + 1.0f) / (float)L;
  106820. }
  106821. }
  106822. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p)
  106823. {
  106824. if (p <= 0.0)
  106825. FLAC__window_rectangle(window, L);
  106826. else if (p >= 1.0)
  106827. FLAC__window_hann(window, L);
  106828. else {
  106829. const FLAC__int32 Np = (FLAC__int32)(p / 2.0f * L) - 1;
  106830. FLAC__int32 n;
  106831. /* start with rectangle... */
  106832. FLAC__window_rectangle(window, L);
  106833. /* ...replace ends with hann */
  106834. if (Np > 0) {
  106835. for (n = 0; n <= Np; n++) {
  106836. window[n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * n / Np));
  106837. window[L-Np-1+n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * (n+Np) / Np));
  106838. }
  106839. }
  106840. }
  106841. }
  106842. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L)
  106843. {
  106844. const FLAC__int32 N = L - 1;
  106845. const double N2 = (double)N / 2.;
  106846. FLAC__int32 n;
  106847. for (n = 0; n <= N; n++) {
  106848. const double k = ((double)n - N2) / N2;
  106849. window[n] = (FLAC__real)(1.0f - k * k);
  106850. }
  106851. }
  106852. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  106853. #endif
  106854. /*** End of inlined file: window_flac.c ***/
  106855. #else
  106856. #include <FLAC/all.h>
  106857. #endif
  106858. }
  106859. #undef max
  106860. #undef min
  106861. BEGIN_JUCE_NAMESPACE
  106862. static const char* const flacFormatName = "FLAC file";
  106863. static const char* const flacExtensions[] = { ".flac", 0 };
  106864. class FlacReader : public AudioFormatReader
  106865. {
  106866. public:
  106867. FlacReader (InputStream* const in)
  106868. : AudioFormatReader (in, TRANS (flacFormatName)),
  106869. reservoir (2, 0),
  106870. reservoirStart (0),
  106871. samplesInReservoir (0),
  106872. scanningForLength (false)
  106873. {
  106874. using namespace FlacNamespace;
  106875. lengthInSamples = 0;
  106876. decoder = FLAC__stream_decoder_new();
  106877. ok = FLAC__stream_decoder_init_stream (decoder,
  106878. readCallback_, seekCallback_, tellCallback_, lengthCallback_,
  106879. eofCallback_, writeCallback_, metadataCallback_, errorCallback_,
  106880. this) == FLAC__STREAM_DECODER_INIT_STATUS_OK;
  106881. if (ok)
  106882. {
  106883. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  106884. if (lengthInSamples == 0 && sampleRate > 0)
  106885. {
  106886. // the length hasn't been stored in the metadata, so we'll need to
  106887. // work it out the length the hard way, by scanning the whole file..
  106888. scanningForLength = true;
  106889. FLAC__stream_decoder_process_until_end_of_stream (decoder);
  106890. scanningForLength = false;
  106891. const int64 tempLength = lengthInSamples;
  106892. FLAC__stream_decoder_reset (decoder);
  106893. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  106894. lengthInSamples = tempLength;
  106895. }
  106896. }
  106897. }
  106898. ~FlacReader()
  106899. {
  106900. FlacNamespace::FLAC__stream_decoder_delete (decoder);
  106901. }
  106902. void useMetadata (const FlacNamespace::FLAC__StreamMetadata_StreamInfo& info)
  106903. {
  106904. sampleRate = info.sample_rate;
  106905. bitsPerSample = info.bits_per_sample;
  106906. lengthInSamples = (unsigned int) info.total_samples;
  106907. numChannels = info.channels;
  106908. reservoir.setSize (numChannels, 2 * info.max_blocksize, false, false, true);
  106909. }
  106910. // returns the number of samples read
  106911. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  106912. int64 startSampleInFile, int numSamples)
  106913. {
  106914. using namespace FlacNamespace;
  106915. if (! ok)
  106916. return false;
  106917. while (numSamples > 0)
  106918. {
  106919. if (startSampleInFile >= reservoirStart
  106920. && startSampleInFile < reservoirStart + samplesInReservoir)
  106921. {
  106922. const int num = (int) jmin ((int64) numSamples,
  106923. reservoirStart + samplesInReservoir - startSampleInFile);
  106924. jassert (num > 0);
  106925. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  106926. if (destSamples[i] != 0)
  106927. memcpy (destSamples[i] + startOffsetInDestBuffer,
  106928. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  106929. sizeof (int) * num);
  106930. startOffsetInDestBuffer += num;
  106931. startSampleInFile += num;
  106932. numSamples -= num;
  106933. }
  106934. else
  106935. {
  106936. if (startSampleInFile >= (int) lengthInSamples)
  106937. {
  106938. samplesInReservoir = 0;
  106939. }
  106940. else if (startSampleInFile < reservoirStart
  106941. || startSampleInFile > reservoirStart + jmax (samplesInReservoir, 511))
  106942. {
  106943. // had some problems with flac crashing if the read pos is aligned more
  106944. // accurately than this. Probably fixed in newer versions of the library, though.
  106945. reservoirStart = (int) (startSampleInFile & ~511);
  106946. samplesInReservoir = 0;
  106947. FLAC__stream_decoder_seek_absolute (decoder, (FLAC__uint64) reservoirStart);
  106948. }
  106949. else
  106950. {
  106951. reservoirStart += samplesInReservoir;
  106952. samplesInReservoir = 0;
  106953. FLAC__stream_decoder_process_single (decoder);
  106954. }
  106955. if (samplesInReservoir == 0)
  106956. break;
  106957. }
  106958. }
  106959. if (numSamples > 0)
  106960. {
  106961. for (int i = numDestChannels; --i >= 0;)
  106962. if (destSamples[i] != 0)
  106963. zeromem (destSamples[i] + startOffsetInDestBuffer,
  106964. sizeof (int) * numSamples);
  106965. }
  106966. return true;
  106967. }
  106968. void useSamples (const FlacNamespace::FLAC__int32* const buffer[], int numSamples)
  106969. {
  106970. if (scanningForLength)
  106971. {
  106972. lengthInSamples += numSamples;
  106973. }
  106974. else
  106975. {
  106976. if (numSamples > reservoir.getNumSamples())
  106977. reservoir.setSize (numChannels, numSamples, false, false, true);
  106978. const int bitsToShift = 32 - bitsPerSample;
  106979. for (int i = 0; i < (int) numChannels; ++i)
  106980. {
  106981. const FlacNamespace::FLAC__int32* src = buffer[i];
  106982. int n = i;
  106983. while (src == 0 && n > 0)
  106984. src = buffer [--n];
  106985. if (src != 0)
  106986. {
  106987. int* dest = reinterpret_cast<int*> (reservoir.getSampleData(i));
  106988. for (int j = 0; j < numSamples; ++j)
  106989. dest[j] = src[j] << bitsToShift;
  106990. }
  106991. }
  106992. samplesInReservoir = numSamples;
  106993. }
  106994. }
  106995. static FlacNamespace::FLAC__StreamDecoderReadStatus readCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__byte buffer[], size_t* bytes, void* client_data)
  106996. {
  106997. using namespace FlacNamespace;
  106998. *bytes = (size_t) static_cast <const FlacReader*> (client_data)->input->read (buffer, (int) *bytes);
  106999. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  107000. }
  107001. static FlacNamespace::FLAC__StreamDecoderSeekStatus seekCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64 absolute_byte_offset, void* client_data)
  107002. {
  107003. using namespace FlacNamespace;
  107004. static_cast <const FlacReader*> (client_data)->input->setPosition ((int) absolute_byte_offset);
  107005. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  107006. }
  107007. static FlacNamespace::FLAC__StreamDecoderTellStatus tellCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  107008. {
  107009. using namespace FlacNamespace;
  107010. *absolute_byte_offset = static_cast <const FlacReader*> (client_data)->input->getPosition();
  107011. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  107012. }
  107013. static FlacNamespace::FLAC__StreamDecoderLengthStatus lengthCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* stream_length, void* client_data)
  107014. {
  107015. using namespace FlacNamespace;
  107016. *stream_length = static_cast <const FlacReader*> (client_data)->input->getTotalLength();
  107017. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  107018. }
  107019. static FlacNamespace::FLAC__bool eofCallback_ (const FlacNamespace::FLAC__StreamDecoder*, void* client_data)
  107020. {
  107021. return static_cast <const FlacReader*> (client_data)->input->isExhausted();
  107022. }
  107023. static FlacNamespace::FLAC__StreamDecoderWriteStatus writeCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  107024. const FlacNamespace::FLAC__Frame* frame,
  107025. const FlacNamespace::FLAC__int32* const buffer[],
  107026. void* client_data)
  107027. {
  107028. using namespace FlacNamespace;
  107029. static_cast <FlacReader*> (client_data)->useSamples (buffer, frame->header.blocksize);
  107030. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  107031. }
  107032. static void metadataCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  107033. const FlacNamespace::FLAC__StreamMetadata* metadata,
  107034. void* client_data)
  107035. {
  107036. static_cast <FlacReader*> (client_data)->useMetadata (metadata->data.stream_info);
  107037. }
  107038. static void errorCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__StreamDecoderErrorStatus, void*)
  107039. {
  107040. }
  107041. juce_UseDebuggingNewOperator
  107042. private:
  107043. FlacNamespace::FLAC__StreamDecoder* decoder;
  107044. AudioSampleBuffer reservoir;
  107045. int reservoirStart, samplesInReservoir;
  107046. bool ok, scanningForLength;
  107047. FlacReader (const FlacReader&);
  107048. FlacReader& operator= (const FlacReader&);
  107049. };
  107050. class FlacWriter : public AudioFormatWriter
  107051. {
  107052. public:
  107053. FlacWriter (OutputStream* const out, double sampleRate_,
  107054. int numChannels_, int bitsPerSample_, int qualityOptionIndex)
  107055. : AudioFormatWriter (out, TRANS (flacFormatName),
  107056. sampleRate_, numChannels_, bitsPerSample_)
  107057. {
  107058. using namespace FlacNamespace;
  107059. encoder = FLAC__stream_encoder_new();
  107060. if (qualityOptionIndex > 0)
  107061. FLAC__stream_encoder_set_compression_level (encoder, jmin (8, qualityOptionIndex));
  107062. FLAC__stream_encoder_set_do_mid_side_stereo (encoder, numChannels == 2);
  107063. FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, numChannels == 2);
  107064. FLAC__stream_encoder_set_channels (encoder, numChannels);
  107065. FLAC__stream_encoder_set_bits_per_sample (encoder, jmin ((unsigned int) 24, bitsPerSample));
  107066. FLAC__stream_encoder_set_sample_rate (encoder, (unsigned int) sampleRate);
  107067. FLAC__stream_encoder_set_blocksize (encoder, 2048);
  107068. FLAC__stream_encoder_set_do_escape_coding (encoder, true);
  107069. ok = FLAC__stream_encoder_init_stream (encoder,
  107070. encodeWriteCallback, encodeSeekCallback,
  107071. encodeTellCallback, encodeMetadataCallback,
  107072. this) == FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  107073. }
  107074. ~FlacWriter()
  107075. {
  107076. if (ok)
  107077. {
  107078. FlacNamespace::FLAC__stream_encoder_finish (encoder);
  107079. output->flush();
  107080. }
  107081. else
  107082. {
  107083. output = 0; // to stop the base class deleting this, as it needs to be returned
  107084. // to the caller of createWriter()
  107085. }
  107086. FlacNamespace::FLAC__stream_encoder_delete (encoder);
  107087. }
  107088. bool write (const int** samplesToWrite, int numSamples)
  107089. {
  107090. using namespace FlacNamespace;
  107091. if (! ok)
  107092. return false;
  107093. int* buf[3];
  107094. const int bitsToShift = 32 - bitsPerSample;
  107095. if (bitsToShift > 0)
  107096. {
  107097. const int numChannelsToWrite = (samplesToWrite[1] == 0) ? 1 : 2;
  107098. HeapBlock<int> temp (numSamples * numChannelsToWrite);
  107099. buf[0] = temp.getData();
  107100. buf[1] = temp.getData() + numSamples;
  107101. buf[2] = 0;
  107102. for (int i = numChannelsToWrite; --i >= 0;)
  107103. {
  107104. if (samplesToWrite[i] != 0)
  107105. {
  107106. for (int j = 0; j < numSamples; ++j)
  107107. buf [i][j] = (samplesToWrite [i][j] >> bitsToShift);
  107108. }
  107109. }
  107110. samplesToWrite = const_cast<const int**> (buf);
  107111. }
  107112. return FLAC__stream_encoder_process (encoder,
  107113. (const FLAC__int32**) samplesToWrite,
  107114. numSamples) != 0;
  107115. }
  107116. bool writeData (const void* const data, const int size) const
  107117. {
  107118. return output->write (data, size);
  107119. }
  107120. static void packUint32 (FlacNamespace::FLAC__uint32 val, FlacNamespace::FLAC__byte* b, const int bytes)
  107121. {
  107122. using namespace FlacNamespace;
  107123. b += bytes;
  107124. for (int i = 0; i < bytes; ++i)
  107125. {
  107126. *(--b) = (FLAC__byte) (val & 0xff);
  107127. val >>= 8;
  107128. }
  107129. }
  107130. void writeMetaData (const FlacNamespace::FLAC__StreamMetadata* metadata)
  107131. {
  107132. using namespace FlacNamespace;
  107133. const FLAC__StreamMetadata_StreamInfo& info = metadata->data.stream_info;
  107134. unsigned char buffer [FLAC__STREAM_METADATA_STREAMINFO_LENGTH];
  107135. const unsigned int channelsMinus1 = info.channels - 1;
  107136. const unsigned int bitsMinus1 = info.bits_per_sample - 1;
  107137. packUint32 (info.min_blocksize, buffer, 2);
  107138. packUint32 (info.max_blocksize, buffer + 2, 2);
  107139. packUint32 (info.min_framesize, buffer + 4, 3);
  107140. packUint32 (info.max_framesize, buffer + 7, 3);
  107141. buffer[10] = (uint8) ((info.sample_rate >> 12) & 0xff);
  107142. buffer[11] = (uint8) ((info.sample_rate >> 4) & 0xff);
  107143. buffer[12] = (uint8) (((info.sample_rate & 0x0f) << 4) | (channelsMinus1 << 1) | (bitsMinus1 >> 4));
  107144. buffer[13] = (FLAC__byte) (((bitsMinus1 & 0x0f) << 4) | (unsigned int) ((info.total_samples >> 32) & 0x0f));
  107145. packUint32 ((FLAC__uint32) info.total_samples, buffer + 14, 4);
  107146. memcpy (buffer + 18, info.md5sum, 16);
  107147. const bool seekOk = output->setPosition (4);
  107148. (void) seekOk;
  107149. // if this fails, you've given it an output stream that can't seek! It needs
  107150. // to be able to seek back to write the header
  107151. jassert (seekOk);
  107152. output->writeIntBigEndian (FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  107153. output->write (buffer, FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  107154. }
  107155. static FlacNamespace::FLAC__StreamEncoderWriteStatus encodeWriteCallback (const FlacNamespace::FLAC__StreamEncoder*,
  107156. const FlacNamespace::FLAC__byte buffer[],
  107157. size_t bytes,
  107158. unsigned int /*samples*/,
  107159. unsigned int /*current_frame*/,
  107160. void* client_data)
  107161. {
  107162. using namespace FlacNamespace;
  107163. return static_cast <FlacWriter*> (client_data)->writeData (buffer, (int) bytes)
  107164. ? FLAC__STREAM_ENCODER_WRITE_STATUS_OK
  107165. : FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  107166. }
  107167. static FlacNamespace::FLAC__StreamEncoderSeekStatus encodeSeekCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64, void*)
  107168. {
  107169. using namespace FlacNamespace;
  107170. return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  107171. }
  107172. static FlacNamespace::FLAC__StreamEncoderTellStatus encodeTellCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  107173. {
  107174. using namespace FlacNamespace;
  107175. if (client_data == 0)
  107176. return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  107177. *absolute_byte_offset = (FLAC__uint64) static_cast <FlacWriter*> (client_data)->output->getPosition();
  107178. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  107179. }
  107180. static void encodeMetadataCallback (const FlacNamespace::FLAC__StreamEncoder*, const FlacNamespace::FLAC__StreamMetadata* metadata, void* client_data)
  107181. {
  107182. static_cast <FlacWriter*> (client_data)->writeMetaData (metadata);
  107183. }
  107184. juce_UseDebuggingNewOperator
  107185. bool ok;
  107186. private:
  107187. FlacNamespace::FLAC__StreamEncoder* encoder;
  107188. FlacWriter (const FlacWriter&);
  107189. FlacWriter& operator= (const FlacWriter&);
  107190. };
  107191. FlacAudioFormat::FlacAudioFormat()
  107192. : AudioFormat (TRANS (flacFormatName), StringArray (flacExtensions))
  107193. {
  107194. }
  107195. FlacAudioFormat::~FlacAudioFormat()
  107196. {
  107197. }
  107198. const Array <int> FlacAudioFormat::getPossibleSampleRates()
  107199. {
  107200. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 0 };
  107201. return Array <int> (rates);
  107202. }
  107203. const Array <int> FlacAudioFormat::getPossibleBitDepths()
  107204. {
  107205. const int depths[] = { 16, 24, 0 };
  107206. return Array <int> (depths);
  107207. }
  107208. bool FlacAudioFormat::canDoStereo() { return true; }
  107209. bool FlacAudioFormat::canDoMono() { return true; }
  107210. bool FlacAudioFormat::isCompressed() { return true; }
  107211. AudioFormatReader* FlacAudioFormat::createReaderFor (InputStream* in,
  107212. const bool deleteStreamIfOpeningFails)
  107213. {
  107214. ScopedPointer<FlacReader> r (new FlacReader (in));
  107215. if (r->sampleRate != 0)
  107216. return r.release();
  107217. if (! deleteStreamIfOpeningFails)
  107218. r->input = 0;
  107219. return 0;
  107220. }
  107221. AudioFormatWriter* FlacAudioFormat::createWriterFor (OutputStream* out,
  107222. double sampleRate,
  107223. unsigned int numberOfChannels,
  107224. int bitsPerSample,
  107225. const StringPairArray& /*metadataValues*/,
  107226. int qualityOptionIndex)
  107227. {
  107228. if (getPossibleBitDepths().contains (bitsPerSample))
  107229. {
  107230. ScopedPointer<FlacWriter> w (new FlacWriter (out, sampleRate, numberOfChannels, bitsPerSample, qualityOptionIndex));
  107231. if (w->ok)
  107232. return w.release();
  107233. }
  107234. return 0;
  107235. }
  107236. END_JUCE_NAMESPACE
  107237. #endif
  107238. /*** End of inlined file: juce_FlacAudioFormat.cpp ***/
  107239. /*** Start of inlined file: juce_OggVorbisAudioFormat.cpp ***/
  107240. #if JUCE_USE_OGGVORBIS
  107241. #if JUCE_MAC
  107242. #define __MACOSX__ 1
  107243. #endif
  107244. namespace OggVorbisNamespace
  107245. {
  107246. #if JUCE_INCLUDE_OGGVORBIS_CODE
  107247. /*** Start of inlined file: vorbisenc.h ***/
  107248. #ifndef _OV_ENC_H_
  107249. #define _OV_ENC_H_
  107250. #ifdef __cplusplus
  107251. extern "C"
  107252. {
  107253. #endif /* __cplusplus */
  107254. /*** Start of inlined file: codec.h ***/
  107255. #ifndef _vorbis_codec_h_
  107256. #define _vorbis_codec_h_
  107257. #ifdef __cplusplus
  107258. extern "C"
  107259. {
  107260. #endif /* __cplusplus */
  107261. /*** Start of inlined file: ogg.h ***/
  107262. #ifndef _OGG_H
  107263. #define _OGG_H
  107264. #ifdef __cplusplus
  107265. extern "C" {
  107266. #endif
  107267. /*** Start of inlined file: os_types.h ***/
  107268. #ifndef _OS_TYPES_H
  107269. #define _OS_TYPES_H
  107270. /* make it easy on the folks that want to compile the libs with a
  107271. different malloc than stdlib */
  107272. #define _ogg_malloc malloc
  107273. #define _ogg_calloc calloc
  107274. #define _ogg_realloc realloc
  107275. #define _ogg_free free
  107276. #if defined(_WIN32)
  107277. # if defined(__CYGWIN__)
  107278. # include <_G_config.h>
  107279. typedef _G_int64_t ogg_int64_t;
  107280. typedef _G_int32_t ogg_int32_t;
  107281. typedef _G_uint32_t ogg_uint32_t;
  107282. typedef _G_int16_t ogg_int16_t;
  107283. typedef _G_uint16_t ogg_uint16_t;
  107284. # elif defined(__MINGW32__)
  107285. typedef short ogg_int16_t;
  107286. typedef unsigned short ogg_uint16_t;
  107287. typedef int ogg_int32_t;
  107288. typedef unsigned int ogg_uint32_t;
  107289. typedef long long ogg_int64_t;
  107290. typedef unsigned long long ogg_uint64_t;
  107291. # elif defined(__MWERKS__)
  107292. typedef long long ogg_int64_t;
  107293. typedef int ogg_int32_t;
  107294. typedef unsigned int ogg_uint32_t;
  107295. typedef short ogg_int16_t;
  107296. typedef unsigned short ogg_uint16_t;
  107297. # else
  107298. /* MSVC/Borland */
  107299. typedef __int64 ogg_int64_t;
  107300. typedef __int32 ogg_int32_t;
  107301. typedef unsigned __int32 ogg_uint32_t;
  107302. typedef __int16 ogg_int16_t;
  107303. typedef unsigned __int16 ogg_uint16_t;
  107304. # endif
  107305. #elif defined(__MACOS__)
  107306. # include <sys/types.h>
  107307. typedef SInt16 ogg_int16_t;
  107308. typedef UInt16 ogg_uint16_t;
  107309. typedef SInt32 ogg_int32_t;
  107310. typedef UInt32 ogg_uint32_t;
  107311. typedef SInt64 ogg_int64_t;
  107312. #elif defined(__MACOSX__) /* MacOS X Framework build */
  107313. # include <sys/types.h>
  107314. typedef int16_t ogg_int16_t;
  107315. typedef u_int16_t ogg_uint16_t;
  107316. typedef int32_t ogg_int32_t;
  107317. typedef u_int32_t ogg_uint32_t;
  107318. typedef int64_t ogg_int64_t;
  107319. #elif defined(__BEOS__)
  107320. /* Be */
  107321. # include <inttypes.h>
  107322. typedef int16_t ogg_int16_t;
  107323. typedef u_int16_t ogg_uint16_t;
  107324. typedef int32_t ogg_int32_t;
  107325. typedef u_int32_t ogg_uint32_t;
  107326. typedef int64_t ogg_int64_t;
  107327. #elif defined (__EMX__)
  107328. /* OS/2 GCC */
  107329. typedef short ogg_int16_t;
  107330. typedef unsigned short ogg_uint16_t;
  107331. typedef int ogg_int32_t;
  107332. typedef unsigned int ogg_uint32_t;
  107333. typedef long long ogg_int64_t;
  107334. #elif defined (DJGPP)
  107335. /* DJGPP */
  107336. typedef short ogg_int16_t;
  107337. typedef int ogg_int32_t;
  107338. typedef unsigned int ogg_uint32_t;
  107339. typedef long long ogg_int64_t;
  107340. #elif defined(R5900)
  107341. /* PS2 EE */
  107342. typedef long ogg_int64_t;
  107343. typedef int ogg_int32_t;
  107344. typedef unsigned ogg_uint32_t;
  107345. typedef short ogg_int16_t;
  107346. #elif defined(__SYMBIAN32__)
  107347. /* Symbian GCC */
  107348. typedef signed short ogg_int16_t;
  107349. typedef unsigned short ogg_uint16_t;
  107350. typedef signed int ogg_int32_t;
  107351. typedef unsigned int ogg_uint32_t;
  107352. typedef long long int ogg_int64_t;
  107353. #else
  107354. # include <sys/types.h>
  107355. /*** Start of inlined file: config_types.h ***/
  107356. #ifndef __CONFIG_TYPES_H__
  107357. #define __CONFIG_TYPES_H__
  107358. typedef int16_t ogg_int16_t;
  107359. typedef unsigned short ogg_uint16_t;
  107360. typedef int32_t ogg_int32_t;
  107361. typedef unsigned int ogg_uint32_t;
  107362. typedef int64_t ogg_int64_t;
  107363. #endif
  107364. /*** End of inlined file: config_types.h ***/
  107365. #endif
  107366. #endif /* _OS_TYPES_H */
  107367. /*** End of inlined file: os_types.h ***/
  107368. typedef struct {
  107369. long endbyte;
  107370. int endbit;
  107371. unsigned char *buffer;
  107372. unsigned char *ptr;
  107373. long storage;
  107374. } oggpack_buffer;
  107375. /* ogg_page is used to encapsulate the data in one Ogg bitstream page *****/
  107376. typedef struct {
  107377. unsigned char *header;
  107378. long header_len;
  107379. unsigned char *body;
  107380. long body_len;
  107381. } ogg_page;
  107382. ogg_uint32_t ogg_bitreverse(ogg_uint32_t x){
  107383. x= ((x>>16)&0x0000ffffUL) | ((x<<16)&0xffff0000UL);
  107384. x= ((x>> 8)&0x00ff00ffUL) | ((x<< 8)&0xff00ff00UL);
  107385. x= ((x>> 4)&0x0f0f0f0fUL) | ((x<< 4)&0xf0f0f0f0UL);
  107386. x= ((x>> 2)&0x33333333UL) | ((x<< 2)&0xccccccccUL);
  107387. return((x>> 1)&0x55555555UL) | ((x<< 1)&0xaaaaaaaaUL);
  107388. }
  107389. /* ogg_stream_state contains the current encode/decode state of a logical
  107390. Ogg bitstream **********************************************************/
  107391. typedef struct {
  107392. unsigned char *body_data; /* bytes from packet bodies */
  107393. long body_storage; /* storage elements allocated */
  107394. long body_fill; /* elements stored; fill mark */
  107395. long body_returned; /* elements of fill returned */
  107396. int *lacing_vals; /* The values that will go to the segment table */
  107397. ogg_int64_t *granule_vals; /* granulepos values for headers. Not compact
  107398. this way, but it is simple coupled to the
  107399. lacing fifo */
  107400. long lacing_storage;
  107401. long lacing_fill;
  107402. long lacing_packet;
  107403. long lacing_returned;
  107404. unsigned char header[282]; /* working space for header encode */
  107405. int header_fill;
  107406. int e_o_s; /* set when we have buffered the last packet in the
  107407. logical bitstream */
  107408. int b_o_s; /* set after we've written the initial page
  107409. of a logical bitstream */
  107410. long serialno;
  107411. long pageno;
  107412. ogg_int64_t packetno; /* sequence number for decode; the framing
  107413. knows where there's a hole in the data,
  107414. but we need coupling so that the codec
  107415. (which is in a seperate abstraction
  107416. layer) also knows about the gap */
  107417. ogg_int64_t granulepos;
  107418. } ogg_stream_state;
  107419. /* ogg_packet is used to encapsulate the data and metadata belonging
  107420. to a single raw Ogg/Vorbis packet *************************************/
  107421. typedef struct {
  107422. unsigned char *packet;
  107423. long bytes;
  107424. long b_o_s;
  107425. long e_o_s;
  107426. ogg_int64_t granulepos;
  107427. ogg_int64_t packetno; /* sequence number for decode; the framing
  107428. knows where there's a hole in the data,
  107429. but we need coupling so that the codec
  107430. (which is in a seperate abstraction
  107431. layer) also knows about the gap */
  107432. } ogg_packet;
  107433. typedef struct {
  107434. unsigned char *data;
  107435. int storage;
  107436. int fill;
  107437. int returned;
  107438. int unsynced;
  107439. int headerbytes;
  107440. int bodybytes;
  107441. } ogg_sync_state;
  107442. /* Ogg BITSTREAM PRIMITIVES: bitstream ************************/
  107443. extern void oggpack_writeinit(oggpack_buffer *b);
  107444. extern void oggpack_writetrunc(oggpack_buffer *b,long bits);
  107445. extern void oggpack_writealign(oggpack_buffer *b);
  107446. extern void oggpack_writecopy(oggpack_buffer *b,void *source,long bits);
  107447. extern void oggpack_reset(oggpack_buffer *b);
  107448. extern void oggpack_writeclear(oggpack_buffer *b);
  107449. extern void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  107450. extern void oggpack_write(oggpack_buffer *b,unsigned long value,int bits);
  107451. extern long oggpack_look(oggpack_buffer *b,int bits);
  107452. extern long oggpack_look1(oggpack_buffer *b);
  107453. extern void oggpack_adv(oggpack_buffer *b,int bits);
  107454. extern void oggpack_adv1(oggpack_buffer *b);
  107455. extern long oggpack_read(oggpack_buffer *b,int bits);
  107456. extern long oggpack_read1(oggpack_buffer *b);
  107457. extern long oggpack_bytes(oggpack_buffer *b);
  107458. extern long oggpack_bits(oggpack_buffer *b);
  107459. extern unsigned char *oggpack_get_buffer(oggpack_buffer *b);
  107460. extern void oggpackB_writeinit(oggpack_buffer *b);
  107461. extern void oggpackB_writetrunc(oggpack_buffer *b,long bits);
  107462. extern void oggpackB_writealign(oggpack_buffer *b);
  107463. extern void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits);
  107464. extern void oggpackB_reset(oggpack_buffer *b);
  107465. extern void oggpackB_writeclear(oggpack_buffer *b);
  107466. extern void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  107467. extern void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits);
  107468. extern long oggpackB_look(oggpack_buffer *b,int bits);
  107469. extern long oggpackB_look1(oggpack_buffer *b);
  107470. extern void oggpackB_adv(oggpack_buffer *b,int bits);
  107471. extern void oggpackB_adv1(oggpack_buffer *b);
  107472. extern long oggpackB_read(oggpack_buffer *b,int bits);
  107473. extern long oggpackB_read1(oggpack_buffer *b);
  107474. extern long oggpackB_bytes(oggpack_buffer *b);
  107475. extern long oggpackB_bits(oggpack_buffer *b);
  107476. extern unsigned char *oggpackB_get_buffer(oggpack_buffer *b);
  107477. /* Ogg BITSTREAM PRIMITIVES: encoding **************************/
  107478. extern int ogg_stream_packetin(ogg_stream_state *os, ogg_packet *op);
  107479. extern int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og);
  107480. extern int ogg_stream_flush(ogg_stream_state *os, ogg_page *og);
  107481. /* Ogg BITSTREAM PRIMITIVES: decoding **************************/
  107482. extern int ogg_sync_init(ogg_sync_state *oy);
  107483. extern int ogg_sync_clear(ogg_sync_state *oy);
  107484. extern int ogg_sync_reset(ogg_sync_state *oy);
  107485. extern int ogg_sync_destroy(ogg_sync_state *oy);
  107486. extern char *ogg_sync_buffer(ogg_sync_state *oy, long size);
  107487. extern int ogg_sync_wrote(ogg_sync_state *oy, long bytes);
  107488. extern long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og);
  107489. extern int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og);
  107490. extern int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og);
  107491. extern int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op);
  107492. extern int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op);
  107493. /* Ogg BITSTREAM PRIMITIVES: general ***************************/
  107494. extern int ogg_stream_init(ogg_stream_state *os,int serialno);
  107495. extern int ogg_stream_clear(ogg_stream_state *os);
  107496. extern int ogg_stream_reset(ogg_stream_state *os);
  107497. extern int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno);
  107498. extern int ogg_stream_destroy(ogg_stream_state *os);
  107499. extern int ogg_stream_eos(ogg_stream_state *os);
  107500. extern void ogg_page_checksum_set(ogg_page *og);
  107501. extern int ogg_page_version(ogg_page *og);
  107502. extern int ogg_page_continued(ogg_page *og);
  107503. extern int ogg_page_bos(ogg_page *og);
  107504. extern int ogg_page_eos(ogg_page *og);
  107505. extern ogg_int64_t ogg_page_granulepos(ogg_page *og);
  107506. extern int ogg_page_serialno(ogg_page *og);
  107507. extern long ogg_page_pageno(ogg_page *og);
  107508. extern int ogg_page_packets(ogg_page *og);
  107509. extern void ogg_packet_clear(ogg_packet *op);
  107510. #ifdef __cplusplus
  107511. }
  107512. #endif
  107513. #endif /* _OGG_H */
  107514. /*** End of inlined file: ogg.h ***/
  107515. typedef struct vorbis_info{
  107516. int version;
  107517. int channels;
  107518. long rate;
  107519. /* The below bitrate declarations are *hints*.
  107520. Combinations of the three values carry the following implications:
  107521. all three set to the same value:
  107522. implies a fixed rate bitstream
  107523. only nominal set:
  107524. implies a VBR stream that averages the nominal bitrate. No hard
  107525. upper/lower limit
  107526. upper and or lower set:
  107527. implies a VBR bitstream that obeys the bitrate limits. nominal
  107528. may also be set to give a nominal rate.
  107529. none set:
  107530. the coder does not care to speculate.
  107531. */
  107532. long bitrate_upper;
  107533. long bitrate_nominal;
  107534. long bitrate_lower;
  107535. long bitrate_window;
  107536. void *codec_setup;
  107537. } vorbis_info;
  107538. /* vorbis_dsp_state buffers the current vorbis audio
  107539. analysis/synthesis state. The DSP state belongs to a specific
  107540. logical bitstream ****************************************************/
  107541. typedef struct vorbis_dsp_state{
  107542. int analysisp;
  107543. vorbis_info *vi;
  107544. float **pcm;
  107545. float **pcmret;
  107546. int pcm_storage;
  107547. int pcm_current;
  107548. int pcm_returned;
  107549. int preextrapolate;
  107550. int eofflag;
  107551. long lW;
  107552. long W;
  107553. long nW;
  107554. long centerW;
  107555. ogg_int64_t granulepos;
  107556. ogg_int64_t sequence;
  107557. ogg_int64_t glue_bits;
  107558. ogg_int64_t time_bits;
  107559. ogg_int64_t floor_bits;
  107560. ogg_int64_t res_bits;
  107561. void *backend_state;
  107562. } vorbis_dsp_state;
  107563. typedef struct vorbis_block{
  107564. /* necessary stream state for linking to the framing abstraction */
  107565. float **pcm; /* this is a pointer into local storage */
  107566. oggpack_buffer opb;
  107567. long lW;
  107568. long W;
  107569. long nW;
  107570. int pcmend;
  107571. int mode;
  107572. int eofflag;
  107573. ogg_int64_t granulepos;
  107574. ogg_int64_t sequence;
  107575. vorbis_dsp_state *vd; /* For read-only access of configuration */
  107576. /* local storage to avoid remallocing; it's up to the mapping to
  107577. structure it */
  107578. void *localstore;
  107579. long localtop;
  107580. long localalloc;
  107581. long totaluse;
  107582. struct alloc_chain *reap;
  107583. /* bitmetrics for the frame */
  107584. long glue_bits;
  107585. long time_bits;
  107586. long floor_bits;
  107587. long res_bits;
  107588. void *internal;
  107589. } vorbis_block;
  107590. /* vorbis_block is a single block of data to be processed as part of
  107591. the analysis/synthesis stream; it belongs to a specific logical
  107592. bitstream, but is independant from other vorbis_blocks belonging to
  107593. that logical bitstream. *************************************************/
  107594. struct alloc_chain{
  107595. void *ptr;
  107596. struct alloc_chain *next;
  107597. };
  107598. /* vorbis_info contains all the setup information specific to the
  107599. specific compression/decompression mode in progress (eg,
  107600. psychoacoustic settings, channel setup, options, codebook
  107601. etc). vorbis_info and substructures are in backends.h.
  107602. *********************************************************************/
  107603. /* the comments are not part of vorbis_info so that vorbis_info can be
  107604. static storage */
  107605. typedef struct vorbis_comment{
  107606. /* unlimited user comment fields. libvorbis writes 'libvorbis'
  107607. whatever vendor is set to in encode */
  107608. char **user_comments;
  107609. int *comment_lengths;
  107610. int comments;
  107611. char *vendor;
  107612. } vorbis_comment;
  107613. /* libvorbis encodes in two abstraction layers; first we perform DSP
  107614. and produce a packet (see docs/analysis.txt). The packet is then
  107615. coded into a framed OggSquish bitstream by the second layer (see
  107616. docs/framing.txt). Decode is the reverse process; we sync/frame
  107617. the bitstream and extract individual packets, then decode the
  107618. packet back into PCM audio.
  107619. The extra framing/packetizing is used in streaming formats, such as
  107620. files. Over the net (such as with UDP), the framing and
  107621. packetization aren't necessary as they're provided by the transport
  107622. and the streaming layer is not used */
  107623. /* Vorbis PRIMITIVES: general ***************************************/
  107624. extern void vorbis_info_init(vorbis_info *vi);
  107625. extern void vorbis_info_clear(vorbis_info *vi);
  107626. extern int vorbis_info_blocksize(vorbis_info *vi,int zo);
  107627. extern void vorbis_comment_init(vorbis_comment *vc);
  107628. extern void vorbis_comment_add(vorbis_comment *vc, char *comment);
  107629. extern void vorbis_comment_add_tag(vorbis_comment *vc,
  107630. const char *tag, char *contents);
  107631. extern char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count);
  107632. extern int vorbis_comment_query_count(vorbis_comment *vc, char *tag);
  107633. extern void vorbis_comment_clear(vorbis_comment *vc);
  107634. extern int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb);
  107635. extern int vorbis_block_clear(vorbis_block *vb);
  107636. extern void vorbis_dsp_clear(vorbis_dsp_state *v);
  107637. extern double vorbis_granule_time(vorbis_dsp_state *v,
  107638. ogg_int64_t granulepos);
  107639. /* Vorbis PRIMITIVES: analysis/DSP layer ****************************/
  107640. extern int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi);
  107641. extern int vorbis_commentheader_out(vorbis_comment *vc, ogg_packet *op);
  107642. extern int vorbis_analysis_headerout(vorbis_dsp_state *v,
  107643. vorbis_comment *vc,
  107644. ogg_packet *op,
  107645. ogg_packet *op_comm,
  107646. ogg_packet *op_code);
  107647. extern float **vorbis_analysis_buffer(vorbis_dsp_state *v,int vals);
  107648. extern int vorbis_analysis_wrote(vorbis_dsp_state *v,int vals);
  107649. extern int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb);
  107650. extern int vorbis_analysis(vorbis_block *vb,ogg_packet *op);
  107651. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  107652. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,
  107653. ogg_packet *op);
  107654. /* Vorbis PRIMITIVES: synthesis layer *******************************/
  107655. extern int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,
  107656. ogg_packet *op);
  107657. extern int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi);
  107658. extern int vorbis_synthesis_restart(vorbis_dsp_state *v);
  107659. extern int vorbis_synthesis(vorbis_block *vb,ogg_packet *op);
  107660. extern int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op);
  107661. extern int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb);
  107662. extern int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm);
  107663. extern int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm);
  107664. extern int vorbis_synthesis_read(vorbis_dsp_state *v,int samples);
  107665. extern long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op);
  107666. extern int vorbis_synthesis_halfrate(vorbis_info *v,int flag);
  107667. extern int vorbis_synthesis_halfrate_p(vorbis_info *v);
  107668. /* Vorbis ERRORS and return codes ***********************************/
  107669. #define OV_FALSE -1
  107670. #define OV_EOF -2
  107671. #define OV_HOLE -3
  107672. #define OV_EREAD -128
  107673. #define OV_EFAULT -129
  107674. #define OV_EIMPL -130
  107675. #define OV_EINVAL -131
  107676. #define OV_ENOTVORBIS -132
  107677. #define OV_EBADHEADER -133
  107678. #define OV_EVERSION -134
  107679. #define OV_ENOTAUDIO -135
  107680. #define OV_EBADPACKET -136
  107681. #define OV_EBADLINK -137
  107682. #define OV_ENOSEEK -138
  107683. #ifdef __cplusplus
  107684. }
  107685. #endif /* __cplusplus */
  107686. #endif
  107687. /*** End of inlined file: codec.h ***/
  107688. extern int vorbis_encode_init(vorbis_info *vi,
  107689. long channels,
  107690. long rate,
  107691. long max_bitrate,
  107692. long nominal_bitrate,
  107693. long min_bitrate);
  107694. extern int vorbis_encode_setup_managed(vorbis_info *vi,
  107695. long channels,
  107696. long rate,
  107697. long max_bitrate,
  107698. long nominal_bitrate,
  107699. long min_bitrate);
  107700. extern int vorbis_encode_setup_vbr(vorbis_info *vi,
  107701. long channels,
  107702. long rate,
  107703. float quality /* quality level from 0. (lo) to 1. (hi) */
  107704. );
  107705. extern int vorbis_encode_init_vbr(vorbis_info *vi,
  107706. long channels,
  107707. long rate,
  107708. float base_quality /* quality level from 0. (lo) to 1. (hi) */
  107709. );
  107710. extern int vorbis_encode_setup_init(vorbis_info *vi);
  107711. extern int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg);
  107712. /* deprecated rate management supported only for compatability */
  107713. #define OV_ECTL_RATEMANAGE_GET 0x10
  107714. #define OV_ECTL_RATEMANAGE_SET 0x11
  107715. #define OV_ECTL_RATEMANAGE_AVG 0x12
  107716. #define OV_ECTL_RATEMANAGE_HARD 0x13
  107717. struct ovectl_ratemanage_arg {
  107718. int management_active;
  107719. long bitrate_hard_min;
  107720. long bitrate_hard_max;
  107721. double bitrate_hard_window;
  107722. long bitrate_av_lo;
  107723. long bitrate_av_hi;
  107724. double bitrate_av_window;
  107725. double bitrate_av_window_center;
  107726. };
  107727. /* new rate setup */
  107728. #define OV_ECTL_RATEMANAGE2_GET 0x14
  107729. #define OV_ECTL_RATEMANAGE2_SET 0x15
  107730. struct ovectl_ratemanage2_arg {
  107731. int management_active;
  107732. long bitrate_limit_min_kbps;
  107733. long bitrate_limit_max_kbps;
  107734. long bitrate_limit_reservoir_bits;
  107735. double bitrate_limit_reservoir_bias;
  107736. long bitrate_average_kbps;
  107737. double bitrate_average_damping;
  107738. };
  107739. #define OV_ECTL_LOWPASS_GET 0x20
  107740. #define OV_ECTL_LOWPASS_SET 0x21
  107741. #define OV_ECTL_IBLOCK_GET 0x30
  107742. #define OV_ECTL_IBLOCK_SET 0x31
  107743. #ifdef __cplusplus
  107744. }
  107745. #endif /* __cplusplus */
  107746. #endif
  107747. /*** End of inlined file: vorbisenc.h ***/
  107748. /*** Start of inlined file: vorbisfile.h ***/
  107749. #ifndef _OV_FILE_H_
  107750. #define _OV_FILE_H_
  107751. #ifdef __cplusplus
  107752. extern "C"
  107753. {
  107754. #endif /* __cplusplus */
  107755. #include <stdio.h>
  107756. /* The function prototypes for the callbacks are basically the same as for
  107757. * the stdio functions fread, fseek, fclose, ftell.
  107758. * The one difference is that the FILE * arguments have been replaced with
  107759. * a void * - this is to be used as a pointer to whatever internal data these
  107760. * functions might need. In the stdio case, it's just a FILE * cast to a void *
  107761. *
  107762. * If you use other functions, check the docs for these functions and return
  107763. * the right values. For seek_func(), you *MUST* return -1 if the stream is
  107764. * unseekable
  107765. */
  107766. typedef struct {
  107767. size_t (*read_func) (void *ptr, size_t size, size_t nmemb, void *datasource);
  107768. int (*seek_func) (void *datasource, ogg_int64_t offset, int whence);
  107769. int (*close_func) (void *datasource);
  107770. long (*tell_func) (void *datasource);
  107771. } ov_callbacks;
  107772. #define NOTOPEN 0
  107773. #define PARTOPEN 1
  107774. #define OPENED 2
  107775. #define STREAMSET 3
  107776. #define INITSET 4
  107777. typedef struct OggVorbis_File {
  107778. void *datasource; /* Pointer to a FILE *, etc. */
  107779. int seekable;
  107780. ogg_int64_t offset;
  107781. ogg_int64_t end;
  107782. ogg_sync_state oy;
  107783. /* If the FILE handle isn't seekable (eg, a pipe), only the current
  107784. stream appears */
  107785. int links;
  107786. ogg_int64_t *offsets;
  107787. ogg_int64_t *dataoffsets;
  107788. long *serialnos;
  107789. ogg_int64_t *pcmlengths; /* overloaded to maintain binary
  107790. compatability; x2 size, stores both
  107791. beginning and end values */
  107792. vorbis_info *vi;
  107793. vorbis_comment *vc;
  107794. /* Decoding working state local storage */
  107795. ogg_int64_t pcm_offset;
  107796. int ready_state;
  107797. long current_serialno;
  107798. int current_link;
  107799. double bittrack;
  107800. double samptrack;
  107801. ogg_stream_state os; /* take physical pages, weld into a logical
  107802. stream of packets */
  107803. vorbis_dsp_state vd; /* central working state for the packet->PCM decoder */
  107804. vorbis_block vb; /* local working space for packet->PCM decode */
  107805. ov_callbacks callbacks;
  107806. } OggVorbis_File;
  107807. extern int ov_clear(OggVorbis_File *vf);
  107808. extern int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  107809. extern int ov_open_callbacks(void *datasource, OggVorbis_File *vf,
  107810. char *initial, long ibytes, ov_callbacks callbacks);
  107811. extern int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  107812. extern int ov_test_callbacks(void *datasource, OggVorbis_File *vf,
  107813. char *initial, long ibytes, ov_callbacks callbacks);
  107814. extern int ov_test_open(OggVorbis_File *vf);
  107815. extern long ov_bitrate(OggVorbis_File *vf,int i);
  107816. extern long ov_bitrate_instant(OggVorbis_File *vf);
  107817. extern long ov_streams(OggVorbis_File *vf);
  107818. extern long ov_seekable(OggVorbis_File *vf);
  107819. extern long ov_serialnumber(OggVorbis_File *vf,int i);
  107820. extern ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i);
  107821. extern ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i);
  107822. extern double ov_time_total(OggVorbis_File *vf,int i);
  107823. extern int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos);
  107824. extern int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos);
  107825. extern int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos);
  107826. extern int ov_time_seek(OggVorbis_File *vf,double pos);
  107827. extern int ov_time_seek_page(OggVorbis_File *vf,double pos);
  107828. extern int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107829. extern int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107830. extern int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107831. extern int ov_time_seek_lap(OggVorbis_File *vf,double pos);
  107832. extern int ov_time_seek_page_lap(OggVorbis_File *vf,double pos);
  107833. extern ogg_int64_t ov_raw_tell(OggVorbis_File *vf);
  107834. extern ogg_int64_t ov_pcm_tell(OggVorbis_File *vf);
  107835. extern double ov_time_tell(OggVorbis_File *vf);
  107836. extern vorbis_info *ov_info(OggVorbis_File *vf,int link);
  107837. extern vorbis_comment *ov_comment(OggVorbis_File *vf,int link);
  107838. extern long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int samples,
  107839. int *bitstream);
  107840. extern long ov_read(OggVorbis_File *vf,char *buffer,int length,
  107841. int bigendianp,int word,int sgned,int *bitstream);
  107842. extern int ov_crosslap(OggVorbis_File *vf1,OggVorbis_File *vf2);
  107843. extern int ov_halfrate(OggVorbis_File *vf,int flag);
  107844. extern int ov_halfrate_p(OggVorbis_File *vf);
  107845. #ifdef __cplusplus
  107846. }
  107847. #endif /* __cplusplus */
  107848. #endif
  107849. /*** End of inlined file: vorbisfile.h ***/
  107850. /*** Start of inlined file: bitwise.c ***/
  107851. /* We're 'LSb' endian; if we write a word but read individual bits,
  107852. then we'll read the lsb first */
  107853. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  107854. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  107855. // tasks..
  107856. #if JUCE_MSVC
  107857. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  107858. #endif
  107859. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  107860. #if JUCE_USE_OGGVORBIS
  107861. #include <string.h>
  107862. #include <stdlib.h>
  107863. #define BUFFER_INCREMENT 256
  107864. static const unsigned long mask[]=
  107865. {0x00000000,0x00000001,0x00000003,0x00000007,0x0000000f,
  107866. 0x0000001f,0x0000003f,0x0000007f,0x000000ff,0x000001ff,
  107867. 0x000003ff,0x000007ff,0x00000fff,0x00001fff,0x00003fff,
  107868. 0x00007fff,0x0000ffff,0x0001ffff,0x0003ffff,0x0007ffff,
  107869. 0x000fffff,0x001fffff,0x003fffff,0x007fffff,0x00ffffff,
  107870. 0x01ffffff,0x03ffffff,0x07ffffff,0x0fffffff,0x1fffffff,
  107871. 0x3fffffff,0x7fffffff,0xffffffff };
  107872. static const unsigned int mask8B[]=
  107873. {0x00,0x80,0xc0,0xe0,0xf0,0xf8,0xfc,0xfe,0xff};
  107874. void oggpack_writeinit(oggpack_buffer *b){
  107875. memset(b,0,sizeof(*b));
  107876. b->ptr=b->buffer=(unsigned char*) _ogg_malloc(BUFFER_INCREMENT);
  107877. b->buffer[0]='\0';
  107878. b->storage=BUFFER_INCREMENT;
  107879. }
  107880. void oggpackB_writeinit(oggpack_buffer *b){
  107881. oggpack_writeinit(b);
  107882. }
  107883. void oggpack_writetrunc(oggpack_buffer *b,long bits){
  107884. long bytes=bits>>3;
  107885. bits-=bytes*8;
  107886. b->ptr=b->buffer+bytes;
  107887. b->endbit=bits;
  107888. b->endbyte=bytes;
  107889. *b->ptr&=mask[bits];
  107890. }
  107891. void oggpackB_writetrunc(oggpack_buffer *b,long bits){
  107892. long bytes=bits>>3;
  107893. bits-=bytes*8;
  107894. b->ptr=b->buffer+bytes;
  107895. b->endbit=bits;
  107896. b->endbyte=bytes;
  107897. *b->ptr&=mask8B[bits];
  107898. }
  107899. /* Takes only up to 32 bits. */
  107900. void oggpack_write(oggpack_buffer *b,unsigned long value,int bits){
  107901. if(b->endbyte+4>=b->storage){
  107902. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  107903. b->storage+=BUFFER_INCREMENT;
  107904. b->ptr=b->buffer+b->endbyte;
  107905. }
  107906. value&=mask[bits];
  107907. bits+=b->endbit;
  107908. b->ptr[0]|=value<<b->endbit;
  107909. if(bits>=8){
  107910. b->ptr[1]=(unsigned char)(value>>(8-b->endbit));
  107911. if(bits>=16){
  107912. b->ptr[2]=(unsigned char)(value>>(16-b->endbit));
  107913. if(bits>=24){
  107914. b->ptr[3]=(unsigned char)(value>>(24-b->endbit));
  107915. if(bits>=32){
  107916. if(b->endbit)
  107917. b->ptr[4]=(unsigned char)(value>>(32-b->endbit));
  107918. else
  107919. b->ptr[4]=0;
  107920. }
  107921. }
  107922. }
  107923. }
  107924. b->endbyte+=bits/8;
  107925. b->ptr+=bits/8;
  107926. b->endbit=bits&7;
  107927. }
  107928. /* Takes only up to 32 bits. */
  107929. void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits){
  107930. if(b->endbyte+4>=b->storage){
  107931. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  107932. b->storage+=BUFFER_INCREMENT;
  107933. b->ptr=b->buffer+b->endbyte;
  107934. }
  107935. value=(value&mask[bits])<<(32-bits);
  107936. bits+=b->endbit;
  107937. b->ptr[0]|=value>>(24+b->endbit);
  107938. if(bits>=8){
  107939. b->ptr[1]=(unsigned char)(value>>(16+b->endbit));
  107940. if(bits>=16){
  107941. b->ptr[2]=(unsigned char)(value>>(8+b->endbit));
  107942. if(bits>=24){
  107943. b->ptr[3]=(unsigned char)(value>>(b->endbit));
  107944. if(bits>=32){
  107945. if(b->endbit)
  107946. b->ptr[4]=(unsigned char)(value<<(8-b->endbit));
  107947. else
  107948. b->ptr[4]=0;
  107949. }
  107950. }
  107951. }
  107952. }
  107953. b->endbyte+=bits/8;
  107954. b->ptr+=bits/8;
  107955. b->endbit=bits&7;
  107956. }
  107957. void oggpack_writealign(oggpack_buffer *b){
  107958. int bits=8-b->endbit;
  107959. if(bits<8)
  107960. oggpack_write(b,0,bits);
  107961. }
  107962. void oggpackB_writealign(oggpack_buffer *b){
  107963. int bits=8-b->endbit;
  107964. if(bits<8)
  107965. oggpackB_write(b,0,bits);
  107966. }
  107967. static void oggpack_writecopy_helper(oggpack_buffer *b,
  107968. void *source,
  107969. long bits,
  107970. void (*w)(oggpack_buffer *,
  107971. unsigned long,
  107972. int),
  107973. int msb){
  107974. unsigned char *ptr=(unsigned char *)source;
  107975. long bytes=bits/8;
  107976. bits-=bytes*8;
  107977. if(b->endbit){
  107978. int i;
  107979. /* unaligned copy. Do it the hard way. */
  107980. for(i=0;i<bytes;i++)
  107981. w(b,(unsigned long)(ptr[i]),8);
  107982. }else{
  107983. /* aligned block copy */
  107984. if(b->endbyte+bytes+1>=b->storage){
  107985. b->storage=b->endbyte+bytes+BUFFER_INCREMENT;
  107986. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage);
  107987. b->ptr=b->buffer+b->endbyte;
  107988. }
  107989. memmove(b->ptr,source,bytes);
  107990. b->ptr+=bytes;
  107991. b->endbyte+=bytes;
  107992. *b->ptr=0;
  107993. }
  107994. if(bits){
  107995. if(msb)
  107996. w(b,(unsigned long)(ptr[bytes]>>(8-bits)),bits);
  107997. else
  107998. w(b,(unsigned long)(ptr[bytes]),bits);
  107999. }
  108000. }
  108001. void oggpack_writecopy(oggpack_buffer *b,void *source,long bits){
  108002. oggpack_writecopy_helper(b,source,bits,oggpack_write,0);
  108003. }
  108004. void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits){
  108005. oggpack_writecopy_helper(b,source,bits,oggpackB_write,1);
  108006. }
  108007. void oggpack_reset(oggpack_buffer *b){
  108008. b->ptr=b->buffer;
  108009. b->buffer[0]=0;
  108010. b->endbit=b->endbyte=0;
  108011. }
  108012. void oggpackB_reset(oggpack_buffer *b){
  108013. oggpack_reset(b);
  108014. }
  108015. void oggpack_writeclear(oggpack_buffer *b){
  108016. _ogg_free(b->buffer);
  108017. memset(b,0,sizeof(*b));
  108018. }
  108019. void oggpackB_writeclear(oggpack_buffer *b){
  108020. oggpack_writeclear(b);
  108021. }
  108022. void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  108023. memset(b,0,sizeof(*b));
  108024. b->buffer=b->ptr=buf;
  108025. b->storage=bytes;
  108026. }
  108027. void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  108028. oggpack_readinit(b,buf,bytes);
  108029. }
  108030. /* Read in bits without advancing the bitptr; bits <= 32 */
  108031. long oggpack_look(oggpack_buffer *b,int bits){
  108032. unsigned long ret;
  108033. unsigned long m=mask[bits];
  108034. bits+=b->endbit;
  108035. if(b->endbyte+4>=b->storage){
  108036. /* not the main path */
  108037. if(b->endbyte*8+bits>b->storage*8)return(-1);
  108038. }
  108039. ret=b->ptr[0]>>b->endbit;
  108040. if(bits>8){
  108041. ret|=b->ptr[1]<<(8-b->endbit);
  108042. if(bits>16){
  108043. ret|=b->ptr[2]<<(16-b->endbit);
  108044. if(bits>24){
  108045. ret|=b->ptr[3]<<(24-b->endbit);
  108046. if(bits>32 && b->endbit)
  108047. ret|=b->ptr[4]<<(32-b->endbit);
  108048. }
  108049. }
  108050. }
  108051. return(m&ret);
  108052. }
  108053. /* Read in bits without advancing the bitptr; bits <= 32 */
  108054. long oggpackB_look(oggpack_buffer *b,int bits){
  108055. unsigned long ret;
  108056. int m=32-bits;
  108057. bits+=b->endbit;
  108058. if(b->endbyte+4>=b->storage){
  108059. /* not the main path */
  108060. if(b->endbyte*8+bits>b->storage*8)return(-1);
  108061. }
  108062. ret=b->ptr[0]<<(24+b->endbit);
  108063. if(bits>8){
  108064. ret|=b->ptr[1]<<(16+b->endbit);
  108065. if(bits>16){
  108066. ret|=b->ptr[2]<<(8+b->endbit);
  108067. if(bits>24){
  108068. ret|=b->ptr[3]<<(b->endbit);
  108069. if(bits>32 && b->endbit)
  108070. ret|=b->ptr[4]>>(8-b->endbit);
  108071. }
  108072. }
  108073. }
  108074. return ((ret&0xffffffff)>>(m>>1))>>((m+1)>>1);
  108075. }
  108076. long oggpack_look1(oggpack_buffer *b){
  108077. if(b->endbyte>=b->storage)return(-1);
  108078. return((b->ptr[0]>>b->endbit)&1);
  108079. }
  108080. long oggpackB_look1(oggpack_buffer *b){
  108081. if(b->endbyte>=b->storage)return(-1);
  108082. return((b->ptr[0]>>(7-b->endbit))&1);
  108083. }
  108084. void oggpack_adv(oggpack_buffer *b,int bits){
  108085. bits+=b->endbit;
  108086. b->ptr+=bits/8;
  108087. b->endbyte+=bits/8;
  108088. b->endbit=bits&7;
  108089. }
  108090. void oggpackB_adv(oggpack_buffer *b,int bits){
  108091. oggpack_adv(b,bits);
  108092. }
  108093. void oggpack_adv1(oggpack_buffer *b){
  108094. if(++(b->endbit)>7){
  108095. b->endbit=0;
  108096. b->ptr++;
  108097. b->endbyte++;
  108098. }
  108099. }
  108100. void oggpackB_adv1(oggpack_buffer *b){
  108101. oggpack_adv1(b);
  108102. }
  108103. /* bits <= 32 */
  108104. long oggpack_read(oggpack_buffer *b,int bits){
  108105. long ret;
  108106. unsigned long m=mask[bits];
  108107. bits+=b->endbit;
  108108. if(b->endbyte+4>=b->storage){
  108109. /* not the main path */
  108110. ret=-1L;
  108111. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  108112. }
  108113. ret=b->ptr[0]>>b->endbit;
  108114. if(bits>8){
  108115. ret|=b->ptr[1]<<(8-b->endbit);
  108116. if(bits>16){
  108117. ret|=b->ptr[2]<<(16-b->endbit);
  108118. if(bits>24){
  108119. ret|=b->ptr[3]<<(24-b->endbit);
  108120. if(bits>32 && b->endbit){
  108121. ret|=b->ptr[4]<<(32-b->endbit);
  108122. }
  108123. }
  108124. }
  108125. }
  108126. ret&=m;
  108127. overflow:
  108128. b->ptr+=bits/8;
  108129. b->endbyte+=bits/8;
  108130. b->endbit=bits&7;
  108131. return(ret);
  108132. }
  108133. /* bits <= 32 */
  108134. long oggpackB_read(oggpack_buffer *b,int bits){
  108135. long ret;
  108136. long m=32-bits;
  108137. bits+=b->endbit;
  108138. if(b->endbyte+4>=b->storage){
  108139. /* not the main path */
  108140. ret=-1L;
  108141. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  108142. }
  108143. ret=b->ptr[0]<<(24+b->endbit);
  108144. if(bits>8){
  108145. ret|=b->ptr[1]<<(16+b->endbit);
  108146. if(bits>16){
  108147. ret|=b->ptr[2]<<(8+b->endbit);
  108148. if(bits>24){
  108149. ret|=b->ptr[3]<<(b->endbit);
  108150. if(bits>32 && b->endbit)
  108151. ret|=b->ptr[4]>>(8-b->endbit);
  108152. }
  108153. }
  108154. }
  108155. ret=((ret&0xffffffffUL)>>(m>>1))>>((m+1)>>1);
  108156. overflow:
  108157. b->ptr+=bits/8;
  108158. b->endbyte+=bits/8;
  108159. b->endbit=bits&7;
  108160. return(ret);
  108161. }
  108162. long oggpack_read1(oggpack_buffer *b){
  108163. long ret;
  108164. if(b->endbyte>=b->storage){
  108165. /* not the main path */
  108166. ret=-1L;
  108167. goto overflow;
  108168. }
  108169. ret=(b->ptr[0]>>b->endbit)&1;
  108170. overflow:
  108171. b->endbit++;
  108172. if(b->endbit>7){
  108173. b->endbit=0;
  108174. b->ptr++;
  108175. b->endbyte++;
  108176. }
  108177. return(ret);
  108178. }
  108179. long oggpackB_read1(oggpack_buffer *b){
  108180. long ret;
  108181. if(b->endbyte>=b->storage){
  108182. /* not the main path */
  108183. ret=-1L;
  108184. goto overflow;
  108185. }
  108186. ret=(b->ptr[0]>>(7-b->endbit))&1;
  108187. overflow:
  108188. b->endbit++;
  108189. if(b->endbit>7){
  108190. b->endbit=0;
  108191. b->ptr++;
  108192. b->endbyte++;
  108193. }
  108194. return(ret);
  108195. }
  108196. long oggpack_bytes(oggpack_buffer *b){
  108197. return(b->endbyte+(b->endbit+7)/8);
  108198. }
  108199. long oggpack_bits(oggpack_buffer *b){
  108200. return(b->endbyte*8+b->endbit);
  108201. }
  108202. long oggpackB_bytes(oggpack_buffer *b){
  108203. return oggpack_bytes(b);
  108204. }
  108205. long oggpackB_bits(oggpack_buffer *b){
  108206. return oggpack_bits(b);
  108207. }
  108208. unsigned char *oggpack_get_buffer(oggpack_buffer *b){
  108209. return(b->buffer);
  108210. }
  108211. unsigned char *oggpackB_get_buffer(oggpack_buffer *b){
  108212. return oggpack_get_buffer(b);
  108213. }
  108214. /* Self test of the bitwise routines; everything else is based on
  108215. them, so they damned well better be solid. */
  108216. #ifdef _V_SELFTEST
  108217. #include <stdio.h>
  108218. static int ilog(unsigned int v){
  108219. int ret=0;
  108220. while(v){
  108221. ret++;
  108222. v>>=1;
  108223. }
  108224. return(ret);
  108225. }
  108226. oggpack_buffer o;
  108227. oggpack_buffer r;
  108228. void report(char *in){
  108229. fprintf(stderr,"%s",in);
  108230. exit(1);
  108231. }
  108232. void cliptest(unsigned long *b,int vals,int bits,int *comp,int compsize){
  108233. long bytes,i;
  108234. unsigned char *buffer;
  108235. oggpack_reset(&o);
  108236. for(i=0;i<vals;i++)
  108237. oggpack_write(&o,b[i],bits?bits:ilog(b[i]));
  108238. buffer=oggpack_get_buffer(&o);
  108239. bytes=oggpack_bytes(&o);
  108240. if(bytes!=compsize)report("wrong number of bytes!\n");
  108241. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  108242. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  108243. report("wrote incorrect value!\n");
  108244. }
  108245. oggpack_readinit(&r,buffer,bytes);
  108246. for(i=0;i<vals;i++){
  108247. int tbit=bits?bits:ilog(b[i]);
  108248. if(oggpack_look(&r,tbit)==-1)
  108249. report("out of data!\n");
  108250. if(oggpack_look(&r,tbit)!=(b[i]&mask[tbit]))
  108251. report("looked at incorrect value!\n");
  108252. if(tbit==1)
  108253. if(oggpack_look1(&r)!=(b[i]&mask[tbit]))
  108254. report("looked at single bit incorrect value!\n");
  108255. if(tbit==1){
  108256. if(oggpack_read1(&r)!=(b[i]&mask[tbit]))
  108257. report("read incorrect single bit value!\n");
  108258. }else{
  108259. if(oggpack_read(&r,tbit)!=(b[i]&mask[tbit]))
  108260. report("read incorrect value!\n");
  108261. }
  108262. }
  108263. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108264. }
  108265. void cliptestB(unsigned long *b,int vals,int bits,int *comp,int compsize){
  108266. long bytes,i;
  108267. unsigned char *buffer;
  108268. oggpackB_reset(&o);
  108269. for(i=0;i<vals;i++)
  108270. oggpackB_write(&o,b[i],bits?bits:ilog(b[i]));
  108271. buffer=oggpackB_get_buffer(&o);
  108272. bytes=oggpackB_bytes(&o);
  108273. if(bytes!=compsize)report("wrong number of bytes!\n");
  108274. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  108275. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  108276. report("wrote incorrect value!\n");
  108277. }
  108278. oggpackB_readinit(&r,buffer,bytes);
  108279. for(i=0;i<vals;i++){
  108280. int tbit=bits?bits:ilog(b[i]);
  108281. if(oggpackB_look(&r,tbit)==-1)
  108282. report("out of data!\n");
  108283. if(oggpackB_look(&r,tbit)!=(b[i]&mask[tbit]))
  108284. report("looked at incorrect value!\n");
  108285. if(tbit==1)
  108286. if(oggpackB_look1(&r)!=(b[i]&mask[tbit]))
  108287. report("looked at single bit incorrect value!\n");
  108288. if(tbit==1){
  108289. if(oggpackB_read1(&r)!=(b[i]&mask[tbit]))
  108290. report("read incorrect single bit value!\n");
  108291. }else{
  108292. if(oggpackB_read(&r,tbit)!=(b[i]&mask[tbit]))
  108293. report("read incorrect value!\n");
  108294. }
  108295. }
  108296. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108297. }
  108298. int main(void){
  108299. unsigned char *buffer;
  108300. long bytes,i;
  108301. static unsigned long testbuffer1[]=
  108302. {18,12,103948,4325,543,76,432,52,3,65,4,56,32,42,34,21,1,23,32,546,456,7,
  108303. 567,56,8,8,55,3,52,342,341,4,265,7,67,86,2199,21,7,1,5,1,4};
  108304. int test1size=43;
  108305. static unsigned long testbuffer2[]=
  108306. {216531625L,1237861823,56732452,131,3212421,12325343,34547562,12313212,
  108307. 1233432,534,5,346435231,14436467,7869299,76326614,167548585,
  108308. 85525151,0,12321,1,349528352};
  108309. int test2size=21;
  108310. static unsigned long testbuffer3[]=
  108311. {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,
  108312. 0,1,30,1,1,1,0,0,1,0,0,0,12,0,11,0,1,0,0,1};
  108313. int test3size=56;
  108314. static unsigned long large[]=
  108315. {2136531625L,2137861823,56732452,131,3212421,12325343,34547562,12313212,
  108316. 1233432,534,5,2146435231,14436467,7869299,76326614,167548585,
  108317. 85525151,0,12321,1,2146528352};
  108318. int onesize=33;
  108319. static int one[33]={146,25,44,151,195,15,153,176,233,131,196,65,85,172,47,40,
  108320. 34,242,223,136,35,222,211,86,171,50,225,135,214,75,172,
  108321. 223,4};
  108322. static int oneB[33]={150,101,131,33,203,15,204,216,105,193,156,65,84,85,222,
  108323. 8,139,145,227,126,34,55,244,171,85,100,39,195,173,18,
  108324. 245,251,128};
  108325. int twosize=6;
  108326. static int two[6]={61,255,255,251,231,29};
  108327. static int twoB[6]={247,63,255,253,249,120};
  108328. int threesize=54;
  108329. static int three[54]={169,2,232,252,91,132,156,36,89,13,123,176,144,32,254,
  108330. 142,224,85,59,121,144,79,124,23,67,90,90,216,79,23,83,
  108331. 58,135,196,61,55,129,183,54,101,100,170,37,127,126,10,
  108332. 100,52,4,14,18,86,77,1};
  108333. static int threeB[54]={206,128,42,153,57,8,183,251,13,89,36,30,32,144,183,
  108334. 130,59,240,121,59,85,223,19,228,180,134,33,107,74,98,
  108335. 233,253,196,135,63,2,110,114,50,155,90,127,37,170,104,
  108336. 200,20,254,4,58,106,176,144,0};
  108337. int foursize=38;
  108338. static int four[38]={18,6,163,252,97,194,104,131,32,1,7,82,137,42,129,11,72,
  108339. 132,60,220,112,8,196,109,64,179,86,9,137,195,208,122,169,
  108340. 28,2,133,0,1};
  108341. static int fourB[38]={36,48,102,83,243,24,52,7,4,35,132,10,145,21,2,93,2,41,
  108342. 1,219,184,16,33,184,54,149,170,132,18,30,29,98,229,67,
  108343. 129,10,4,32};
  108344. int fivesize=45;
  108345. static int five[45]={169,2,126,139,144,172,30,4,80,72,240,59,130,218,73,62,
  108346. 241,24,210,44,4,20,0,248,116,49,135,100,110,130,181,169,
  108347. 84,75,159,2,1,0,132,192,8,0,0,18,22};
  108348. static int fiveB[45]={1,84,145,111,245,100,128,8,56,36,40,71,126,78,213,226,
  108349. 124,105,12,0,133,128,0,162,233,242,67,152,77,205,77,
  108350. 172,150,169,129,79,128,0,6,4,32,0,27,9,0};
  108351. int sixsize=7;
  108352. static int six[7]={17,177,170,242,169,19,148};
  108353. static int sixB[7]={136,141,85,79,149,200,41};
  108354. /* Test read/write together */
  108355. /* Later we test against pregenerated bitstreams */
  108356. oggpack_writeinit(&o);
  108357. fprintf(stderr,"\nSmall preclipped packing (LSb): ");
  108358. cliptest(testbuffer1,test1size,0,one,onesize);
  108359. fprintf(stderr,"ok.");
  108360. fprintf(stderr,"\nNull bit call (LSb): ");
  108361. cliptest(testbuffer3,test3size,0,two,twosize);
  108362. fprintf(stderr,"ok.");
  108363. fprintf(stderr,"\nLarge preclipped packing (LSb): ");
  108364. cliptest(testbuffer2,test2size,0,three,threesize);
  108365. fprintf(stderr,"ok.");
  108366. fprintf(stderr,"\n32 bit preclipped packing (LSb): ");
  108367. oggpack_reset(&o);
  108368. for(i=0;i<test2size;i++)
  108369. oggpack_write(&o,large[i],32);
  108370. buffer=oggpack_get_buffer(&o);
  108371. bytes=oggpack_bytes(&o);
  108372. oggpack_readinit(&r,buffer,bytes);
  108373. for(i=0;i<test2size;i++){
  108374. if(oggpack_look(&r,32)==-1)report("out of data. failed!");
  108375. if(oggpack_look(&r,32)!=large[i]){
  108376. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpack_look(&r,32),large[i],
  108377. oggpack_look(&r,32),large[i]);
  108378. report("read incorrect value!\n");
  108379. }
  108380. oggpack_adv(&r,32);
  108381. }
  108382. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108383. fprintf(stderr,"ok.");
  108384. fprintf(stderr,"\nSmall unclipped packing (LSb): ");
  108385. cliptest(testbuffer1,test1size,7,four,foursize);
  108386. fprintf(stderr,"ok.");
  108387. fprintf(stderr,"\nLarge unclipped packing (LSb): ");
  108388. cliptest(testbuffer2,test2size,17,five,fivesize);
  108389. fprintf(stderr,"ok.");
  108390. fprintf(stderr,"\nSingle bit unclipped packing (LSb): ");
  108391. cliptest(testbuffer3,test3size,1,six,sixsize);
  108392. fprintf(stderr,"ok.");
  108393. fprintf(stderr,"\nTesting read past end (LSb): ");
  108394. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108395. for(i=0;i<64;i++){
  108396. if(oggpack_read(&r,1)!=0){
  108397. fprintf(stderr,"failed; got -1 prematurely.\n");
  108398. exit(1);
  108399. }
  108400. }
  108401. if(oggpack_look(&r,1)!=-1 ||
  108402. oggpack_read(&r,1)!=-1){
  108403. fprintf(stderr,"failed; read past end without -1.\n");
  108404. exit(1);
  108405. }
  108406. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108407. if(oggpack_read(&r,30)!=0 || oggpack_read(&r,16)!=0){
  108408. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  108409. exit(1);
  108410. }
  108411. if(oggpack_look(&r,18)!=0 ||
  108412. oggpack_look(&r,18)!=0){
  108413. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  108414. exit(1);
  108415. }
  108416. if(oggpack_look(&r,19)!=-1 ||
  108417. oggpack_look(&r,19)!=-1){
  108418. fprintf(stderr,"failed; read past end without -1.\n");
  108419. exit(1);
  108420. }
  108421. if(oggpack_look(&r,32)!=-1 ||
  108422. oggpack_look(&r,32)!=-1){
  108423. fprintf(stderr,"failed; read past end without -1.\n");
  108424. exit(1);
  108425. }
  108426. oggpack_writeclear(&o);
  108427. fprintf(stderr,"ok.\n");
  108428. /********** lazy, cut-n-paste retest with MSb packing ***********/
  108429. /* Test read/write together */
  108430. /* Later we test against pregenerated bitstreams */
  108431. oggpackB_writeinit(&o);
  108432. fprintf(stderr,"\nSmall preclipped packing (MSb): ");
  108433. cliptestB(testbuffer1,test1size,0,oneB,onesize);
  108434. fprintf(stderr,"ok.");
  108435. fprintf(stderr,"\nNull bit call (MSb): ");
  108436. cliptestB(testbuffer3,test3size,0,twoB,twosize);
  108437. fprintf(stderr,"ok.");
  108438. fprintf(stderr,"\nLarge preclipped packing (MSb): ");
  108439. cliptestB(testbuffer2,test2size,0,threeB,threesize);
  108440. fprintf(stderr,"ok.");
  108441. fprintf(stderr,"\n32 bit preclipped packing (MSb): ");
  108442. oggpackB_reset(&o);
  108443. for(i=0;i<test2size;i++)
  108444. oggpackB_write(&o,large[i],32);
  108445. buffer=oggpackB_get_buffer(&o);
  108446. bytes=oggpackB_bytes(&o);
  108447. oggpackB_readinit(&r,buffer,bytes);
  108448. for(i=0;i<test2size;i++){
  108449. if(oggpackB_look(&r,32)==-1)report("out of data. failed!");
  108450. if(oggpackB_look(&r,32)!=large[i]){
  108451. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpackB_look(&r,32),large[i],
  108452. oggpackB_look(&r,32),large[i]);
  108453. report("read incorrect value!\n");
  108454. }
  108455. oggpackB_adv(&r,32);
  108456. }
  108457. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108458. fprintf(stderr,"ok.");
  108459. fprintf(stderr,"\nSmall unclipped packing (MSb): ");
  108460. cliptestB(testbuffer1,test1size,7,fourB,foursize);
  108461. fprintf(stderr,"ok.");
  108462. fprintf(stderr,"\nLarge unclipped packing (MSb): ");
  108463. cliptestB(testbuffer2,test2size,17,fiveB,fivesize);
  108464. fprintf(stderr,"ok.");
  108465. fprintf(stderr,"\nSingle bit unclipped packing (MSb): ");
  108466. cliptestB(testbuffer3,test3size,1,sixB,sixsize);
  108467. fprintf(stderr,"ok.");
  108468. fprintf(stderr,"\nTesting read past end (MSb): ");
  108469. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108470. for(i=0;i<64;i++){
  108471. if(oggpackB_read(&r,1)!=0){
  108472. fprintf(stderr,"failed; got -1 prematurely.\n");
  108473. exit(1);
  108474. }
  108475. }
  108476. if(oggpackB_look(&r,1)!=-1 ||
  108477. oggpackB_read(&r,1)!=-1){
  108478. fprintf(stderr,"failed; read past end without -1.\n");
  108479. exit(1);
  108480. }
  108481. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108482. if(oggpackB_read(&r,30)!=0 || oggpackB_read(&r,16)!=0){
  108483. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  108484. exit(1);
  108485. }
  108486. if(oggpackB_look(&r,18)!=0 ||
  108487. oggpackB_look(&r,18)!=0){
  108488. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  108489. exit(1);
  108490. }
  108491. if(oggpackB_look(&r,19)!=-1 ||
  108492. oggpackB_look(&r,19)!=-1){
  108493. fprintf(stderr,"failed; read past end without -1.\n");
  108494. exit(1);
  108495. }
  108496. if(oggpackB_look(&r,32)!=-1 ||
  108497. oggpackB_look(&r,32)!=-1){
  108498. fprintf(stderr,"failed; read past end without -1.\n");
  108499. exit(1);
  108500. }
  108501. oggpackB_writeclear(&o);
  108502. fprintf(stderr,"ok.\n\n");
  108503. return(0);
  108504. }
  108505. #endif /* _V_SELFTEST */
  108506. #undef BUFFER_INCREMENT
  108507. #endif
  108508. /*** End of inlined file: bitwise.c ***/
  108509. /*** Start of inlined file: framing.c ***/
  108510. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  108511. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  108512. // tasks..
  108513. #if JUCE_MSVC
  108514. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  108515. #endif
  108516. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  108517. #if JUCE_USE_OGGVORBIS
  108518. #include <stdlib.h>
  108519. #include <string.h>
  108520. /* A complete description of Ogg framing exists in docs/framing.html */
  108521. int ogg_page_version(ogg_page *og){
  108522. return((int)(og->header[4]));
  108523. }
  108524. int ogg_page_continued(ogg_page *og){
  108525. return((int)(og->header[5]&0x01));
  108526. }
  108527. int ogg_page_bos(ogg_page *og){
  108528. return((int)(og->header[5]&0x02));
  108529. }
  108530. int ogg_page_eos(ogg_page *og){
  108531. return((int)(og->header[5]&0x04));
  108532. }
  108533. ogg_int64_t ogg_page_granulepos(ogg_page *og){
  108534. unsigned char *page=og->header;
  108535. ogg_int64_t granulepos=page[13]&(0xff);
  108536. granulepos= (granulepos<<8)|(page[12]&0xff);
  108537. granulepos= (granulepos<<8)|(page[11]&0xff);
  108538. granulepos= (granulepos<<8)|(page[10]&0xff);
  108539. granulepos= (granulepos<<8)|(page[9]&0xff);
  108540. granulepos= (granulepos<<8)|(page[8]&0xff);
  108541. granulepos= (granulepos<<8)|(page[7]&0xff);
  108542. granulepos= (granulepos<<8)|(page[6]&0xff);
  108543. return(granulepos);
  108544. }
  108545. int ogg_page_serialno(ogg_page *og){
  108546. return(og->header[14] |
  108547. (og->header[15]<<8) |
  108548. (og->header[16]<<16) |
  108549. (og->header[17]<<24));
  108550. }
  108551. long ogg_page_pageno(ogg_page *og){
  108552. return(og->header[18] |
  108553. (og->header[19]<<8) |
  108554. (og->header[20]<<16) |
  108555. (og->header[21]<<24));
  108556. }
  108557. /* returns the number of packets that are completed on this page (if
  108558. the leading packet is begun on a previous page, but ends on this
  108559. page, it's counted */
  108560. /* NOTE:
  108561. If a page consists of a packet begun on a previous page, and a new
  108562. packet begun (but not completed) on this page, the return will be:
  108563. ogg_page_packets(page) ==1,
  108564. ogg_page_continued(page) !=0
  108565. If a page happens to be a single packet that was begun on a
  108566. previous page, and spans to the next page (in the case of a three or
  108567. more page packet), the return will be:
  108568. ogg_page_packets(page) ==0,
  108569. ogg_page_continued(page) !=0
  108570. */
  108571. int ogg_page_packets(ogg_page *og){
  108572. int i,n=og->header[26],count=0;
  108573. for(i=0;i<n;i++)
  108574. if(og->header[27+i]<255)count++;
  108575. return(count);
  108576. }
  108577. #if 0
  108578. /* helper to initialize lookup for direct-table CRC (illustrative; we
  108579. use the static init below) */
  108580. static ogg_uint32_t _ogg_crc_entry(unsigned long index){
  108581. int i;
  108582. unsigned long r;
  108583. r = index << 24;
  108584. for (i=0; i<8; i++)
  108585. if (r & 0x80000000UL)
  108586. r = (r << 1) ^ 0x04c11db7; /* The same as the ethernet generator
  108587. polynomial, although we use an
  108588. unreflected alg and an init/final
  108589. of 0, not 0xffffffff */
  108590. else
  108591. r<<=1;
  108592. return (r & 0xffffffffUL);
  108593. }
  108594. #endif
  108595. static const ogg_uint32_t crc_lookup[256]={
  108596. 0x00000000,0x04c11db7,0x09823b6e,0x0d4326d9,
  108597. 0x130476dc,0x17c56b6b,0x1a864db2,0x1e475005,
  108598. 0x2608edb8,0x22c9f00f,0x2f8ad6d6,0x2b4bcb61,
  108599. 0x350c9b64,0x31cd86d3,0x3c8ea00a,0x384fbdbd,
  108600. 0x4c11db70,0x48d0c6c7,0x4593e01e,0x4152fda9,
  108601. 0x5f15adac,0x5bd4b01b,0x569796c2,0x52568b75,
  108602. 0x6a1936c8,0x6ed82b7f,0x639b0da6,0x675a1011,
  108603. 0x791d4014,0x7ddc5da3,0x709f7b7a,0x745e66cd,
  108604. 0x9823b6e0,0x9ce2ab57,0x91a18d8e,0x95609039,
  108605. 0x8b27c03c,0x8fe6dd8b,0x82a5fb52,0x8664e6e5,
  108606. 0xbe2b5b58,0xbaea46ef,0xb7a96036,0xb3687d81,
  108607. 0xad2f2d84,0xa9ee3033,0xa4ad16ea,0xa06c0b5d,
  108608. 0xd4326d90,0xd0f37027,0xddb056fe,0xd9714b49,
  108609. 0xc7361b4c,0xc3f706fb,0xceb42022,0xca753d95,
  108610. 0xf23a8028,0xf6fb9d9f,0xfbb8bb46,0xff79a6f1,
  108611. 0xe13ef6f4,0xe5ffeb43,0xe8bccd9a,0xec7dd02d,
  108612. 0x34867077,0x30476dc0,0x3d044b19,0x39c556ae,
  108613. 0x278206ab,0x23431b1c,0x2e003dc5,0x2ac12072,
  108614. 0x128e9dcf,0x164f8078,0x1b0ca6a1,0x1fcdbb16,
  108615. 0x018aeb13,0x054bf6a4,0x0808d07d,0x0cc9cdca,
  108616. 0x7897ab07,0x7c56b6b0,0x71159069,0x75d48dde,
  108617. 0x6b93dddb,0x6f52c06c,0x6211e6b5,0x66d0fb02,
  108618. 0x5e9f46bf,0x5a5e5b08,0x571d7dd1,0x53dc6066,
  108619. 0x4d9b3063,0x495a2dd4,0x44190b0d,0x40d816ba,
  108620. 0xaca5c697,0xa864db20,0xa527fdf9,0xa1e6e04e,
  108621. 0xbfa1b04b,0xbb60adfc,0xb6238b25,0xb2e29692,
  108622. 0x8aad2b2f,0x8e6c3698,0x832f1041,0x87ee0df6,
  108623. 0x99a95df3,0x9d684044,0x902b669d,0x94ea7b2a,
  108624. 0xe0b41de7,0xe4750050,0xe9362689,0xedf73b3e,
  108625. 0xf3b06b3b,0xf771768c,0xfa325055,0xfef34de2,
  108626. 0xc6bcf05f,0xc27dede8,0xcf3ecb31,0xcbffd686,
  108627. 0xd5b88683,0xd1799b34,0xdc3abded,0xd8fba05a,
  108628. 0x690ce0ee,0x6dcdfd59,0x608edb80,0x644fc637,
  108629. 0x7a089632,0x7ec98b85,0x738aad5c,0x774bb0eb,
  108630. 0x4f040d56,0x4bc510e1,0x46863638,0x42472b8f,
  108631. 0x5c007b8a,0x58c1663d,0x558240e4,0x51435d53,
  108632. 0x251d3b9e,0x21dc2629,0x2c9f00f0,0x285e1d47,
  108633. 0x36194d42,0x32d850f5,0x3f9b762c,0x3b5a6b9b,
  108634. 0x0315d626,0x07d4cb91,0x0a97ed48,0x0e56f0ff,
  108635. 0x1011a0fa,0x14d0bd4d,0x19939b94,0x1d528623,
  108636. 0xf12f560e,0xf5ee4bb9,0xf8ad6d60,0xfc6c70d7,
  108637. 0xe22b20d2,0xe6ea3d65,0xeba91bbc,0xef68060b,
  108638. 0xd727bbb6,0xd3e6a601,0xdea580d8,0xda649d6f,
  108639. 0xc423cd6a,0xc0e2d0dd,0xcda1f604,0xc960ebb3,
  108640. 0xbd3e8d7e,0xb9ff90c9,0xb4bcb610,0xb07daba7,
  108641. 0xae3afba2,0xaafbe615,0xa7b8c0cc,0xa379dd7b,
  108642. 0x9b3660c6,0x9ff77d71,0x92b45ba8,0x9675461f,
  108643. 0x8832161a,0x8cf30bad,0x81b02d74,0x857130c3,
  108644. 0x5d8a9099,0x594b8d2e,0x5408abf7,0x50c9b640,
  108645. 0x4e8ee645,0x4a4ffbf2,0x470cdd2b,0x43cdc09c,
  108646. 0x7b827d21,0x7f436096,0x7200464f,0x76c15bf8,
  108647. 0x68860bfd,0x6c47164a,0x61043093,0x65c52d24,
  108648. 0x119b4be9,0x155a565e,0x18197087,0x1cd86d30,
  108649. 0x029f3d35,0x065e2082,0x0b1d065b,0x0fdc1bec,
  108650. 0x3793a651,0x3352bbe6,0x3e119d3f,0x3ad08088,
  108651. 0x2497d08d,0x2056cd3a,0x2d15ebe3,0x29d4f654,
  108652. 0xc5a92679,0xc1683bce,0xcc2b1d17,0xc8ea00a0,
  108653. 0xd6ad50a5,0xd26c4d12,0xdf2f6bcb,0xdbee767c,
  108654. 0xe3a1cbc1,0xe760d676,0xea23f0af,0xeee2ed18,
  108655. 0xf0a5bd1d,0xf464a0aa,0xf9278673,0xfde69bc4,
  108656. 0x89b8fd09,0x8d79e0be,0x803ac667,0x84fbdbd0,
  108657. 0x9abc8bd5,0x9e7d9662,0x933eb0bb,0x97ffad0c,
  108658. 0xafb010b1,0xab710d06,0xa6322bdf,0xa2f33668,
  108659. 0xbcb4666d,0xb8757bda,0xb5365d03,0xb1f740b4};
  108660. /* init the encode/decode logical stream state */
  108661. int ogg_stream_init(ogg_stream_state *os,int serialno){
  108662. if(os){
  108663. memset(os,0,sizeof(*os));
  108664. os->body_storage=16*1024;
  108665. os->body_data=(unsigned char*) _ogg_malloc(os->body_storage*sizeof(*os->body_data));
  108666. os->lacing_storage=1024;
  108667. os->lacing_vals=(int*) _ogg_malloc(os->lacing_storage*sizeof(*os->lacing_vals));
  108668. os->granule_vals=(ogg_int64_t*) _ogg_malloc(os->lacing_storage*sizeof(*os->granule_vals));
  108669. os->serialno=serialno;
  108670. return(0);
  108671. }
  108672. return(-1);
  108673. }
  108674. /* _clear does not free os, only the non-flat storage within */
  108675. int ogg_stream_clear(ogg_stream_state *os){
  108676. if(os){
  108677. if(os->body_data)_ogg_free(os->body_data);
  108678. if(os->lacing_vals)_ogg_free(os->lacing_vals);
  108679. if(os->granule_vals)_ogg_free(os->granule_vals);
  108680. memset(os,0,sizeof(*os));
  108681. }
  108682. return(0);
  108683. }
  108684. int ogg_stream_destroy(ogg_stream_state *os){
  108685. if(os){
  108686. ogg_stream_clear(os);
  108687. _ogg_free(os);
  108688. }
  108689. return(0);
  108690. }
  108691. /* Helpers for ogg_stream_encode; this keeps the structure and
  108692. what's happening fairly clear */
  108693. static void _os_body_expand(ogg_stream_state *os,int needed){
  108694. if(os->body_storage<=os->body_fill+needed){
  108695. os->body_storage+=(needed+1024);
  108696. os->body_data=(unsigned char*) _ogg_realloc(os->body_data,os->body_storage*sizeof(*os->body_data));
  108697. }
  108698. }
  108699. static void _os_lacing_expand(ogg_stream_state *os,int needed){
  108700. if(os->lacing_storage<=os->lacing_fill+needed){
  108701. os->lacing_storage+=(needed+32);
  108702. os->lacing_vals=(int*)_ogg_realloc(os->lacing_vals,os->lacing_storage*sizeof(*os->lacing_vals));
  108703. os->granule_vals=(ogg_int64_t*)_ogg_realloc(os->granule_vals,os->lacing_storage*sizeof(*os->granule_vals));
  108704. }
  108705. }
  108706. /* checksum the page */
  108707. /* Direct table CRC; note that this will be faster in the future if we
  108708. perform the checksum silmultaneously with other copies */
  108709. void ogg_page_checksum_set(ogg_page *og){
  108710. if(og){
  108711. ogg_uint32_t crc_reg=0;
  108712. int i;
  108713. /* safety; needed for API behavior, but not framing code */
  108714. og->header[22]=0;
  108715. og->header[23]=0;
  108716. og->header[24]=0;
  108717. og->header[25]=0;
  108718. for(i=0;i<og->header_len;i++)
  108719. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->header[i]];
  108720. for(i=0;i<og->body_len;i++)
  108721. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->body[i]];
  108722. og->header[22]=(unsigned char)(crc_reg&0xff);
  108723. og->header[23]=(unsigned char)((crc_reg>>8)&0xff);
  108724. og->header[24]=(unsigned char)((crc_reg>>16)&0xff);
  108725. og->header[25]=(unsigned char)((crc_reg>>24)&0xff);
  108726. }
  108727. }
  108728. /* submit data to the internal buffer of the framing engine */
  108729. int ogg_stream_packetin(ogg_stream_state *os,ogg_packet *op){
  108730. int lacing_vals=op->bytes/255+1,i;
  108731. if(os->body_returned){
  108732. /* advance packet data according to the body_returned pointer. We
  108733. had to keep it around to return a pointer into the buffer last
  108734. call */
  108735. os->body_fill-=os->body_returned;
  108736. if(os->body_fill)
  108737. memmove(os->body_data,os->body_data+os->body_returned,
  108738. os->body_fill);
  108739. os->body_returned=0;
  108740. }
  108741. /* make sure we have the buffer storage */
  108742. _os_body_expand(os,op->bytes);
  108743. _os_lacing_expand(os,lacing_vals);
  108744. /* Copy in the submitted packet. Yes, the copy is a waste; this is
  108745. the liability of overly clean abstraction for the time being. It
  108746. will actually be fairly easy to eliminate the extra copy in the
  108747. future */
  108748. memcpy(os->body_data+os->body_fill,op->packet,op->bytes);
  108749. os->body_fill+=op->bytes;
  108750. /* Store lacing vals for this packet */
  108751. for(i=0;i<lacing_vals-1;i++){
  108752. os->lacing_vals[os->lacing_fill+i]=255;
  108753. os->granule_vals[os->lacing_fill+i]=os->granulepos;
  108754. }
  108755. os->lacing_vals[os->lacing_fill+i]=(op->bytes)%255;
  108756. os->granulepos=os->granule_vals[os->lacing_fill+i]=op->granulepos;
  108757. /* flag the first segment as the beginning of the packet */
  108758. os->lacing_vals[os->lacing_fill]|= 0x100;
  108759. os->lacing_fill+=lacing_vals;
  108760. /* for the sake of completeness */
  108761. os->packetno++;
  108762. if(op->e_o_s)os->e_o_s=1;
  108763. return(0);
  108764. }
  108765. /* This will flush remaining packets into a page (returning nonzero),
  108766. even if there is not enough data to trigger a flush normally
  108767. (undersized page). If there are no packets or partial packets to
  108768. flush, ogg_stream_flush returns 0. Note that ogg_stream_flush will
  108769. try to flush a normal sized page like ogg_stream_pageout; a call to
  108770. ogg_stream_flush does not guarantee that all packets have flushed.
  108771. Only a return value of 0 from ogg_stream_flush indicates all packet
  108772. data is flushed into pages.
  108773. since ogg_stream_flush will flush the last page in a stream even if
  108774. it's undersized, you almost certainly want to use ogg_stream_pageout
  108775. (and *not* ogg_stream_flush) unless you specifically need to flush
  108776. an page regardless of size in the middle of a stream. */
  108777. int ogg_stream_flush(ogg_stream_state *os,ogg_page *og){
  108778. int i;
  108779. int vals=0;
  108780. int maxvals=(os->lacing_fill>255?255:os->lacing_fill);
  108781. int bytes=0;
  108782. long acc=0;
  108783. ogg_int64_t granule_pos=-1;
  108784. if(maxvals==0)return(0);
  108785. /* construct a page */
  108786. /* decide how many segments to include */
  108787. /* If this is the initial header case, the first page must only include
  108788. the initial header packet */
  108789. if(os->b_o_s==0){ /* 'initial header page' case */
  108790. granule_pos=0;
  108791. for(vals=0;vals<maxvals;vals++){
  108792. if((os->lacing_vals[vals]&0x0ff)<255){
  108793. vals++;
  108794. break;
  108795. }
  108796. }
  108797. }else{
  108798. for(vals=0;vals<maxvals;vals++){
  108799. if(acc>4096)break;
  108800. acc+=os->lacing_vals[vals]&0x0ff;
  108801. if((os->lacing_vals[vals]&0xff)<255)
  108802. granule_pos=os->granule_vals[vals];
  108803. }
  108804. }
  108805. /* construct the header in temp storage */
  108806. memcpy(os->header,"OggS",4);
  108807. /* stream structure version */
  108808. os->header[4]=0x00;
  108809. /* continued packet flag? */
  108810. os->header[5]=0x00;
  108811. if((os->lacing_vals[0]&0x100)==0)os->header[5]|=0x01;
  108812. /* first page flag? */
  108813. if(os->b_o_s==0)os->header[5]|=0x02;
  108814. /* last page flag? */
  108815. if(os->e_o_s && os->lacing_fill==vals)os->header[5]|=0x04;
  108816. os->b_o_s=1;
  108817. /* 64 bits of PCM position */
  108818. for(i=6;i<14;i++){
  108819. os->header[i]=(unsigned char)(granule_pos&0xff);
  108820. granule_pos>>=8;
  108821. }
  108822. /* 32 bits of stream serial number */
  108823. {
  108824. long serialno=os->serialno;
  108825. for(i=14;i<18;i++){
  108826. os->header[i]=(unsigned char)(serialno&0xff);
  108827. serialno>>=8;
  108828. }
  108829. }
  108830. /* 32 bits of page counter (we have both counter and page header
  108831. because this val can roll over) */
  108832. if(os->pageno==-1)os->pageno=0; /* because someone called
  108833. stream_reset; this would be a
  108834. strange thing to do in an
  108835. encode stream, but it has
  108836. plausible uses */
  108837. {
  108838. long pageno=os->pageno++;
  108839. for(i=18;i<22;i++){
  108840. os->header[i]=(unsigned char)(pageno&0xff);
  108841. pageno>>=8;
  108842. }
  108843. }
  108844. /* zero for computation; filled in later */
  108845. os->header[22]=0;
  108846. os->header[23]=0;
  108847. os->header[24]=0;
  108848. os->header[25]=0;
  108849. /* segment table */
  108850. os->header[26]=(unsigned char)(vals&0xff);
  108851. for(i=0;i<vals;i++)
  108852. bytes+=os->header[i+27]=(unsigned char)(os->lacing_vals[i]&0xff);
  108853. /* set pointers in the ogg_page struct */
  108854. og->header=os->header;
  108855. og->header_len=os->header_fill=vals+27;
  108856. og->body=os->body_data+os->body_returned;
  108857. og->body_len=bytes;
  108858. /* advance the lacing data and set the body_returned pointer */
  108859. os->lacing_fill-=vals;
  108860. memmove(os->lacing_vals,os->lacing_vals+vals,os->lacing_fill*sizeof(*os->lacing_vals));
  108861. memmove(os->granule_vals,os->granule_vals+vals,os->lacing_fill*sizeof(*os->granule_vals));
  108862. os->body_returned+=bytes;
  108863. /* calculate the checksum */
  108864. ogg_page_checksum_set(og);
  108865. /* done */
  108866. return(1);
  108867. }
  108868. /* This constructs pages from buffered packet segments. The pointers
  108869. returned are to static buffers; do not free. The returned buffers are
  108870. good only until the next call (using the same ogg_stream_state) */
  108871. int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og){
  108872. if((os->e_o_s&&os->lacing_fill) || /* 'were done, now flush' case */
  108873. os->body_fill-os->body_returned > 4096 ||/* 'page nominal size' case */
  108874. os->lacing_fill>=255 || /* 'segment table full' case */
  108875. (os->lacing_fill&&!os->b_o_s)){ /* 'initial header page' case */
  108876. return(ogg_stream_flush(os,og));
  108877. }
  108878. /* not enough data to construct a page and not end of stream */
  108879. return(0);
  108880. }
  108881. int ogg_stream_eos(ogg_stream_state *os){
  108882. return os->e_o_s;
  108883. }
  108884. /* DECODING PRIMITIVES: packet streaming layer **********************/
  108885. /* This has two layers to place more of the multi-serialno and paging
  108886. control in the application's hands. First, we expose a data buffer
  108887. using ogg_sync_buffer(). The app either copies into the
  108888. buffer, or passes it directly to read(), etc. We then call
  108889. ogg_sync_wrote() to tell how many bytes we just added.
  108890. Pages are returned (pointers into the buffer in ogg_sync_state)
  108891. by ogg_sync_pageout(). The page is then submitted to
  108892. ogg_stream_pagein() along with the appropriate
  108893. ogg_stream_state* (ie, matching serialno). We then get raw
  108894. packets out calling ogg_stream_packetout() with a
  108895. ogg_stream_state. */
  108896. /* initialize the struct to a known state */
  108897. int ogg_sync_init(ogg_sync_state *oy){
  108898. if(oy){
  108899. memset(oy,0,sizeof(*oy));
  108900. }
  108901. return(0);
  108902. }
  108903. /* clear non-flat storage within */
  108904. int ogg_sync_clear(ogg_sync_state *oy){
  108905. if(oy){
  108906. if(oy->data)_ogg_free(oy->data);
  108907. ogg_sync_init(oy);
  108908. }
  108909. return(0);
  108910. }
  108911. int ogg_sync_destroy(ogg_sync_state *oy){
  108912. if(oy){
  108913. ogg_sync_clear(oy);
  108914. _ogg_free(oy);
  108915. }
  108916. return(0);
  108917. }
  108918. char *ogg_sync_buffer(ogg_sync_state *oy, long size){
  108919. /* first, clear out any space that has been previously returned */
  108920. if(oy->returned){
  108921. oy->fill-=oy->returned;
  108922. if(oy->fill>0)
  108923. memmove(oy->data,oy->data+oy->returned,oy->fill);
  108924. oy->returned=0;
  108925. }
  108926. if(size>oy->storage-oy->fill){
  108927. /* We need to extend the internal buffer */
  108928. long newsize=size+oy->fill+4096; /* an extra page to be nice */
  108929. if(oy->data)
  108930. oy->data=(unsigned char*) _ogg_realloc(oy->data,newsize);
  108931. else
  108932. oy->data=(unsigned char*) _ogg_malloc(newsize);
  108933. oy->storage=newsize;
  108934. }
  108935. /* expose a segment at least as large as requested at the fill mark */
  108936. return((char *)oy->data+oy->fill);
  108937. }
  108938. int ogg_sync_wrote(ogg_sync_state *oy, long bytes){
  108939. if(oy->fill+bytes>oy->storage)return(-1);
  108940. oy->fill+=bytes;
  108941. return(0);
  108942. }
  108943. /* sync the stream. This is meant to be useful for finding page
  108944. boundaries.
  108945. return values for this:
  108946. -n) skipped n bytes
  108947. 0) page not ready; more data (no bytes skipped)
  108948. n) page synced at current location; page length n bytes
  108949. */
  108950. long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og){
  108951. unsigned char *page=oy->data+oy->returned;
  108952. unsigned char *next;
  108953. long bytes=oy->fill-oy->returned;
  108954. if(oy->headerbytes==0){
  108955. int headerbytes,i;
  108956. if(bytes<27)return(0); /* not enough for a header */
  108957. /* verify capture pattern */
  108958. if(memcmp(page,"OggS",4))goto sync_fail;
  108959. headerbytes=page[26]+27;
  108960. if(bytes<headerbytes)return(0); /* not enough for header + seg table */
  108961. /* count up body length in the segment table */
  108962. for(i=0;i<page[26];i++)
  108963. oy->bodybytes+=page[27+i];
  108964. oy->headerbytes=headerbytes;
  108965. }
  108966. if(oy->bodybytes+oy->headerbytes>bytes)return(0);
  108967. /* The whole test page is buffered. Verify the checksum */
  108968. {
  108969. /* Grab the checksum bytes, set the header field to zero */
  108970. char chksum[4];
  108971. ogg_page log;
  108972. memcpy(chksum,page+22,4);
  108973. memset(page+22,0,4);
  108974. /* set up a temp page struct and recompute the checksum */
  108975. log.header=page;
  108976. log.header_len=oy->headerbytes;
  108977. log.body=page+oy->headerbytes;
  108978. log.body_len=oy->bodybytes;
  108979. ogg_page_checksum_set(&log);
  108980. /* Compare */
  108981. if(memcmp(chksum,page+22,4)){
  108982. /* D'oh. Mismatch! Corrupt page (or miscapture and not a page
  108983. at all) */
  108984. /* replace the computed checksum with the one actually read in */
  108985. memcpy(page+22,chksum,4);
  108986. /* Bad checksum. Lose sync */
  108987. goto sync_fail;
  108988. }
  108989. }
  108990. /* yes, have a whole page all ready to go */
  108991. {
  108992. unsigned char *page=oy->data+oy->returned;
  108993. long bytes;
  108994. if(og){
  108995. og->header=page;
  108996. og->header_len=oy->headerbytes;
  108997. og->body=page+oy->headerbytes;
  108998. og->body_len=oy->bodybytes;
  108999. }
  109000. oy->unsynced=0;
  109001. oy->returned+=(bytes=oy->headerbytes+oy->bodybytes);
  109002. oy->headerbytes=0;
  109003. oy->bodybytes=0;
  109004. return(bytes);
  109005. }
  109006. sync_fail:
  109007. oy->headerbytes=0;
  109008. oy->bodybytes=0;
  109009. /* search for possible capture */
  109010. next=(unsigned char*)memchr(page+1,'O',bytes-1);
  109011. if(!next)
  109012. next=oy->data+oy->fill;
  109013. oy->returned=next-oy->data;
  109014. return(-(next-page));
  109015. }
  109016. /* sync the stream and get a page. Keep trying until we find a page.
  109017. Supress 'sync errors' after reporting the first.
  109018. return values:
  109019. -1) recapture (hole in data)
  109020. 0) need more data
  109021. 1) page returned
  109022. Returns pointers into buffered data; invalidated by next call to
  109023. _stream, _clear, _init, or _buffer */
  109024. int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og){
  109025. /* all we need to do is verify a page at the head of the stream
  109026. buffer. If it doesn't verify, we look for the next potential
  109027. frame */
  109028. for(;;){
  109029. long ret=ogg_sync_pageseek(oy,og);
  109030. if(ret>0){
  109031. /* have a page */
  109032. return(1);
  109033. }
  109034. if(ret==0){
  109035. /* need more data */
  109036. return(0);
  109037. }
  109038. /* head did not start a synced page... skipped some bytes */
  109039. if(!oy->unsynced){
  109040. oy->unsynced=1;
  109041. return(-1);
  109042. }
  109043. /* loop. keep looking */
  109044. }
  109045. }
  109046. /* add the incoming page to the stream state; we decompose the page
  109047. into packet segments here as well. */
  109048. int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og){
  109049. unsigned char *header=og->header;
  109050. unsigned char *body=og->body;
  109051. long bodysize=og->body_len;
  109052. int segptr=0;
  109053. int version=ogg_page_version(og);
  109054. int continued=ogg_page_continued(og);
  109055. int bos=ogg_page_bos(og);
  109056. int eos=ogg_page_eos(og);
  109057. ogg_int64_t granulepos=ogg_page_granulepos(og);
  109058. int serialno=ogg_page_serialno(og);
  109059. long pageno=ogg_page_pageno(og);
  109060. int segments=header[26];
  109061. /* clean up 'returned data' */
  109062. {
  109063. long lr=os->lacing_returned;
  109064. long br=os->body_returned;
  109065. /* body data */
  109066. if(br){
  109067. os->body_fill-=br;
  109068. if(os->body_fill)
  109069. memmove(os->body_data,os->body_data+br,os->body_fill);
  109070. os->body_returned=0;
  109071. }
  109072. if(lr){
  109073. /* segment table */
  109074. if(os->lacing_fill-lr){
  109075. memmove(os->lacing_vals,os->lacing_vals+lr,
  109076. (os->lacing_fill-lr)*sizeof(*os->lacing_vals));
  109077. memmove(os->granule_vals,os->granule_vals+lr,
  109078. (os->lacing_fill-lr)*sizeof(*os->granule_vals));
  109079. }
  109080. os->lacing_fill-=lr;
  109081. os->lacing_packet-=lr;
  109082. os->lacing_returned=0;
  109083. }
  109084. }
  109085. /* check the serial number */
  109086. if(serialno!=os->serialno)return(-1);
  109087. if(version>0)return(-1);
  109088. _os_lacing_expand(os,segments+1);
  109089. /* are we in sequence? */
  109090. if(pageno!=os->pageno){
  109091. int i;
  109092. /* unroll previous partial packet (if any) */
  109093. for(i=os->lacing_packet;i<os->lacing_fill;i++)
  109094. os->body_fill-=os->lacing_vals[i]&0xff;
  109095. os->lacing_fill=os->lacing_packet;
  109096. /* make a note of dropped data in segment table */
  109097. if(os->pageno!=-1){
  109098. os->lacing_vals[os->lacing_fill++]=0x400;
  109099. os->lacing_packet++;
  109100. }
  109101. }
  109102. /* are we a 'continued packet' page? If so, we may need to skip
  109103. some segments */
  109104. if(continued){
  109105. if(os->lacing_fill<1 ||
  109106. os->lacing_vals[os->lacing_fill-1]==0x400){
  109107. bos=0;
  109108. for(;segptr<segments;segptr++){
  109109. int val=header[27+segptr];
  109110. body+=val;
  109111. bodysize-=val;
  109112. if(val<255){
  109113. segptr++;
  109114. break;
  109115. }
  109116. }
  109117. }
  109118. }
  109119. if(bodysize){
  109120. _os_body_expand(os,bodysize);
  109121. memcpy(os->body_data+os->body_fill,body,bodysize);
  109122. os->body_fill+=bodysize;
  109123. }
  109124. {
  109125. int saved=-1;
  109126. while(segptr<segments){
  109127. int val=header[27+segptr];
  109128. os->lacing_vals[os->lacing_fill]=val;
  109129. os->granule_vals[os->lacing_fill]=-1;
  109130. if(bos){
  109131. os->lacing_vals[os->lacing_fill]|=0x100;
  109132. bos=0;
  109133. }
  109134. if(val<255)saved=os->lacing_fill;
  109135. os->lacing_fill++;
  109136. segptr++;
  109137. if(val<255)os->lacing_packet=os->lacing_fill;
  109138. }
  109139. /* set the granulepos on the last granuleval of the last full packet */
  109140. if(saved!=-1){
  109141. os->granule_vals[saved]=granulepos;
  109142. }
  109143. }
  109144. if(eos){
  109145. os->e_o_s=1;
  109146. if(os->lacing_fill>0)
  109147. os->lacing_vals[os->lacing_fill-1]|=0x200;
  109148. }
  109149. os->pageno=pageno+1;
  109150. return(0);
  109151. }
  109152. /* clear things to an initial state. Good to call, eg, before seeking */
  109153. int ogg_sync_reset(ogg_sync_state *oy){
  109154. oy->fill=0;
  109155. oy->returned=0;
  109156. oy->unsynced=0;
  109157. oy->headerbytes=0;
  109158. oy->bodybytes=0;
  109159. return(0);
  109160. }
  109161. int ogg_stream_reset(ogg_stream_state *os){
  109162. os->body_fill=0;
  109163. os->body_returned=0;
  109164. os->lacing_fill=0;
  109165. os->lacing_packet=0;
  109166. os->lacing_returned=0;
  109167. os->header_fill=0;
  109168. os->e_o_s=0;
  109169. os->b_o_s=0;
  109170. os->pageno=-1;
  109171. os->packetno=0;
  109172. os->granulepos=0;
  109173. return(0);
  109174. }
  109175. int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno){
  109176. ogg_stream_reset(os);
  109177. os->serialno=serialno;
  109178. return(0);
  109179. }
  109180. static int _packetout(ogg_stream_state *os,ogg_packet *op,int adv){
  109181. /* The last part of decode. We have the stream broken into packet
  109182. segments. Now we need to group them into packets (or return the
  109183. out of sync markers) */
  109184. int ptr=os->lacing_returned;
  109185. if(os->lacing_packet<=ptr)return(0);
  109186. if(os->lacing_vals[ptr]&0x400){
  109187. /* we need to tell the codec there's a gap; it might need to
  109188. handle previous packet dependencies. */
  109189. os->lacing_returned++;
  109190. os->packetno++;
  109191. return(-1);
  109192. }
  109193. if(!op && !adv)return(1); /* just using peek as an inexpensive way
  109194. to ask if there's a whole packet
  109195. waiting */
  109196. /* Gather the whole packet. We'll have no holes or a partial packet */
  109197. {
  109198. int size=os->lacing_vals[ptr]&0xff;
  109199. int bytes=size;
  109200. int eos=os->lacing_vals[ptr]&0x200; /* last packet of the stream? */
  109201. int bos=os->lacing_vals[ptr]&0x100; /* first packet of the stream? */
  109202. while(size==255){
  109203. int val=os->lacing_vals[++ptr];
  109204. size=val&0xff;
  109205. if(val&0x200)eos=0x200;
  109206. bytes+=size;
  109207. }
  109208. if(op){
  109209. op->e_o_s=eos;
  109210. op->b_o_s=bos;
  109211. op->packet=os->body_data+os->body_returned;
  109212. op->packetno=os->packetno;
  109213. op->granulepos=os->granule_vals[ptr];
  109214. op->bytes=bytes;
  109215. }
  109216. if(adv){
  109217. os->body_returned+=bytes;
  109218. os->lacing_returned=ptr+1;
  109219. os->packetno++;
  109220. }
  109221. }
  109222. return(1);
  109223. }
  109224. int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op){
  109225. return _packetout(os,op,1);
  109226. }
  109227. int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op){
  109228. return _packetout(os,op,0);
  109229. }
  109230. void ogg_packet_clear(ogg_packet *op) {
  109231. _ogg_free(op->packet);
  109232. memset(op, 0, sizeof(*op));
  109233. }
  109234. #ifdef _V_SELFTEST
  109235. #include <stdio.h>
  109236. ogg_stream_state os_en, os_de;
  109237. ogg_sync_state oy;
  109238. void checkpacket(ogg_packet *op,int len, int no, int pos){
  109239. long j;
  109240. static int sequence=0;
  109241. static int lastno=0;
  109242. if(op->bytes!=len){
  109243. fprintf(stderr,"incorrect packet length!\n");
  109244. exit(1);
  109245. }
  109246. if(op->granulepos!=pos){
  109247. fprintf(stderr,"incorrect packet position!\n");
  109248. exit(1);
  109249. }
  109250. /* packet number just follows sequence/gap; adjust the input number
  109251. for that */
  109252. if(no==0){
  109253. sequence=0;
  109254. }else{
  109255. sequence++;
  109256. if(no>lastno+1)
  109257. sequence++;
  109258. }
  109259. lastno=no;
  109260. if(op->packetno!=sequence){
  109261. fprintf(stderr,"incorrect packet sequence %ld != %d\n",
  109262. (long)(op->packetno),sequence);
  109263. exit(1);
  109264. }
  109265. /* Test data */
  109266. for(j=0;j<op->bytes;j++)
  109267. if(op->packet[j]!=((j+no)&0xff)){
  109268. fprintf(stderr,"body data mismatch (1) at pos %ld: %x!=%lx!\n\n",
  109269. j,op->packet[j],(j+no)&0xff);
  109270. exit(1);
  109271. }
  109272. }
  109273. void check_page(unsigned char *data,const int *header,ogg_page *og){
  109274. long j;
  109275. /* Test data */
  109276. for(j=0;j<og->body_len;j++)
  109277. if(og->body[j]!=data[j]){
  109278. fprintf(stderr,"body data mismatch (2) at pos %ld: %x!=%x!\n\n",
  109279. j,data[j],og->body[j]);
  109280. exit(1);
  109281. }
  109282. /* Test header */
  109283. for(j=0;j<og->header_len;j++){
  109284. if(og->header[j]!=header[j]){
  109285. fprintf(stderr,"header content mismatch at pos %ld:\n",j);
  109286. for(j=0;j<header[26]+27;j++)
  109287. fprintf(stderr," (%ld)%02x:%02x",j,header[j],og->header[j]);
  109288. fprintf(stderr,"\n");
  109289. exit(1);
  109290. }
  109291. }
  109292. if(og->header_len!=header[26]+27){
  109293. fprintf(stderr,"header length incorrect! (%ld!=%d)\n",
  109294. og->header_len,header[26]+27);
  109295. exit(1);
  109296. }
  109297. }
  109298. void print_header(ogg_page *og){
  109299. int j;
  109300. fprintf(stderr,"\nHEADER:\n");
  109301. fprintf(stderr," capture: %c %c %c %c version: %d flags: %x\n",
  109302. og->header[0],og->header[1],og->header[2],og->header[3],
  109303. (int)og->header[4],(int)og->header[5]);
  109304. fprintf(stderr," granulepos: %d serialno: %d pageno: %ld\n",
  109305. (og->header[9]<<24)|(og->header[8]<<16)|
  109306. (og->header[7]<<8)|og->header[6],
  109307. (og->header[17]<<24)|(og->header[16]<<16)|
  109308. (og->header[15]<<8)|og->header[14],
  109309. ((long)(og->header[21])<<24)|(og->header[20]<<16)|
  109310. (og->header[19]<<8)|og->header[18]);
  109311. fprintf(stderr," checksum: %02x:%02x:%02x:%02x\n segments: %d (",
  109312. (int)og->header[22],(int)og->header[23],
  109313. (int)og->header[24],(int)og->header[25],
  109314. (int)og->header[26]);
  109315. for(j=27;j<og->header_len;j++)
  109316. fprintf(stderr,"%d ",(int)og->header[j]);
  109317. fprintf(stderr,")\n\n");
  109318. }
  109319. void copy_page(ogg_page *og){
  109320. unsigned char *temp=_ogg_malloc(og->header_len);
  109321. memcpy(temp,og->header,og->header_len);
  109322. og->header=temp;
  109323. temp=_ogg_malloc(og->body_len);
  109324. memcpy(temp,og->body,og->body_len);
  109325. og->body=temp;
  109326. }
  109327. void free_page(ogg_page *og){
  109328. _ogg_free (og->header);
  109329. _ogg_free (og->body);
  109330. }
  109331. void error(void){
  109332. fprintf(stderr,"error!\n");
  109333. exit(1);
  109334. }
  109335. /* 17 only */
  109336. const int head1_0[] = {0x4f,0x67,0x67,0x53,0,0x06,
  109337. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109338. 0x01,0x02,0x03,0x04,0,0,0,0,
  109339. 0x15,0xed,0xec,0x91,
  109340. 1,
  109341. 17};
  109342. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  109343. const int head1_1[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109344. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109345. 0x01,0x02,0x03,0x04,0,0,0,0,
  109346. 0x59,0x10,0x6c,0x2c,
  109347. 1,
  109348. 17};
  109349. const int head2_1[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109350. 0x07,0x18,0x00,0x00,0x00,0x00,0x00,0x00,
  109351. 0x01,0x02,0x03,0x04,1,0,0,0,
  109352. 0x89,0x33,0x85,0xce,
  109353. 13,
  109354. 254,255,0,255,1,255,245,255,255,0,
  109355. 255,255,90};
  109356. /* nil packets; beginning,middle,end */
  109357. const int head1_2[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109358. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109359. 0x01,0x02,0x03,0x04,0,0,0,0,
  109360. 0xff,0x7b,0x23,0x17,
  109361. 1,
  109362. 0};
  109363. const int head2_2[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109364. 0x07,0x28,0x00,0x00,0x00,0x00,0x00,0x00,
  109365. 0x01,0x02,0x03,0x04,1,0,0,0,
  109366. 0x5c,0x3f,0x66,0xcb,
  109367. 17,
  109368. 17,254,255,0,0,255,1,0,255,245,255,255,0,
  109369. 255,255,90,0};
  109370. /* large initial packet */
  109371. const int head1_3[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109372. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109373. 0x01,0x02,0x03,0x04,0,0,0,0,
  109374. 0x01,0x27,0x31,0xaa,
  109375. 18,
  109376. 255,255,255,255,255,255,255,255,
  109377. 255,255,255,255,255,255,255,255,255,10};
  109378. const int head2_3[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109379. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  109380. 0x01,0x02,0x03,0x04,1,0,0,0,
  109381. 0x7f,0x4e,0x8a,0xd2,
  109382. 4,
  109383. 255,4,255,0};
  109384. /* continuing packet test */
  109385. const int head1_4[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109386. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109387. 0x01,0x02,0x03,0x04,0,0,0,0,
  109388. 0xff,0x7b,0x23,0x17,
  109389. 1,
  109390. 0};
  109391. const int head2_4[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109392. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  109393. 0x01,0x02,0x03,0x04,1,0,0,0,
  109394. 0x54,0x05,0x51,0xc8,
  109395. 17,
  109396. 255,255,255,255,255,255,255,255,
  109397. 255,255,255,255,255,255,255,255,255};
  109398. const int head3_4[] = {0x4f,0x67,0x67,0x53,0,0x05,
  109399. 0x07,0x0c,0x00,0x00,0x00,0x00,0x00,0x00,
  109400. 0x01,0x02,0x03,0x04,2,0,0,0,
  109401. 0xc8,0xc3,0xcb,0xed,
  109402. 5,
  109403. 10,255,4,255,0};
  109404. /* page with the 255 segment limit */
  109405. const int head1_5[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109406. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109407. 0x01,0x02,0x03,0x04,0,0,0,0,
  109408. 0xff,0x7b,0x23,0x17,
  109409. 1,
  109410. 0};
  109411. const int head2_5[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109412. 0x07,0xfc,0x03,0x00,0x00,0x00,0x00,0x00,
  109413. 0x01,0x02,0x03,0x04,1,0,0,0,
  109414. 0xed,0x2a,0x2e,0xa7,
  109415. 255,
  109416. 10,10,10,10,10,10,10,10,
  109417. 10,10,10,10,10,10,10,10,
  109418. 10,10,10,10,10,10,10,10,
  109419. 10,10,10,10,10,10,10,10,
  109420. 10,10,10,10,10,10,10,10,
  109421. 10,10,10,10,10,10,10,10,
  109422. 10,10,10,10,10,10,10,10,
  109423. 10,10,10,10,10,10,10,10,
  109424. 10,10,10,10,10,10,10,10,
  109425. 10,10,10,10,10,10,10,10,
  109426. 10,10,10,10,10,10,10,10,
  109427. 10,10,10,10,10,10,10,10,
  109428. 10,10,10,10,10,10,10,10,
  109429. 10,10,10,10,10,10,10,10,
  109430. 10,10,10,10,10,10,10,10,
  109431. 10,10,10,10,10,10,10,10,
  109432. 10,10,10,10,10,10,10,10,
  109433. 10,10,10,10,10,10,10,10,
  109434. 10,10,10,10,10,10,10,10,
  109435. 10,10,10,10,10,10,10,10,
  109436. 10,10,10,10,10,10,10,10,
  109437. 10,10,10,10,10,10,10,10,
  109438. 10,10,10,10,10,10,10,10,
  109439. 10,10,10,10,10,10,10,10,
  109440. 10,10,10,10,10,10,10,10,
  109441. 10,10,10,10,10,10,10,10,
  109442. 10,10,10,10,10,10,10,10,
  109443. 10,10,10,10,10,10,10,10,
  109444. 10,10,10,10,10,10,10,10,
  109445. 10,10,10,10,10,10,10,10,
  109446. 10,10,10,10,10,10,10,10,
  109447. 10,10,10,10,10,10,10};
  109448. const int head3_5[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109449. 0x07,0x00,0x04,0x00,0x00,0x00,0x00,0x00,
  109450. 0x01,0x02,0x03,0x04,2,0,0,0,
  109451. 0x6c,0x3b,0x82,0x3d,
  109452. 1,
  109453. 50};
  109454. /* packet that overspans over an entire page */
  109455. const int head1_6[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109456. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109457. 0x01,0x02,0x03,0x04,0,0,0,0,
  109458. 0xff,0x7b,0x23,0x17,
  109459. 1,
  109460. 0};
  109461. const int head2_6[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109462. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  109463. 0x01,0x02,0x03,0x04,1,0,0,0,
  109464. 0x3c,0xd9,0x4d,0x3f,
  109465. 17,
  109466. 100,255,255,255,255,255,255,255,255,
  109467. 255,255,255,255,255,255,255,255};
  109468. const int head3_6[] = {0x4f,0x67,0x67,0x53,0,0x01,
  109469. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  109470. 0x01,0x02,0x03,0x04,2,0,0,0,
  109471. 0x01,0xd2,0xe5,0xe5,
  109472. 17,
  109473. 255,255,255,255,255,255,255,255,
  109474. 255,255,255,255,255,255,255,255,255};
  109475. const int head4_6[] = {0x4f,0x67,0x67,0x53,0,0x05,
  109476. 0x07,0x10,0x00,0x00,0x00,0x00,0x00,0x00,
  109477. 0x01,0x02,0x03,0x04,3,0,0,0,
  109478. 0xef,0xdd,0x88,0xde,
  109479. 7,
  109480. 255,255,75,255,4,255,0};
  109481. /* packet that overspans over an entire page */
  109482. const int head1_7[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109483. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109484. 0x01,0x02,0x03,0x04,0,0,0,0,
  109485. 0xff,0x7b,0x23,0x17,
  109486. 1,
  109487. 0};
  109488. const int head2_7[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109489. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  109490. 0x01,0x02,0x03,0x04,1,0,0,0,
  109491. 0x3c,0xd9,0x4d,0x3f,
  109492. 17,
  109493. 100,255,255,255,255,255,255,255,255,
  109494. 255,255,255,255,255,255,255,255};
  109495. const int head3_7[] = {0x4f,0x67,0x67,0x53,0,0x05,
  109496. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  109497. 0x01,0x02,0x03,0x04,2,0,0,0,
  109498. 0xd4,0xe0,0x60,0xe5,
  109499. 1,0};
  109500. void test_pack(const int *pl, const int **headers, int byteskip,
  109501. int pageskip, int packetskip){
  109502. unsigned char *data=_ogg_malloc(1024*1024); /* for scripted test cases only */
  109503. long inptr=0;
  109504. long outptr=0;
  109505. long deptr=0;
  109506. long depacket=0;
  109507. long granule_pos=7,pageno=0;
  109508. int i,j,packets,pageout=pageskip;
  109509. int eosflag=0;
  109510. int bosflag=0;
  109511. int byteskipcount=0;
  109512. ogg_stream_reset(&os_en);
  109513. ogg_stream_reset(&os_de);
  109514. ogg_sync_reset(&oy);
  109515. for(packets=0;packets<packetskip;packets++)
  109516. depacket+=pl[packets];
  109517. for(packets=0;;packets++)if(pl[packets]==-1)break;
  109518. for(i=0;i<packets;i++){
  109519. /* construct a test packet */
  109520. ogg_packet op;
  109521. int len=pl[i];
  109522. op.packet=data+inptr;
  109523. op.bytes=len;
  109524. op.e_o_s=(pl[i+1]<0?1:0);
  109525. op.granulepos=granule_pos;
  109526. granule_pos+=1024;
  109527. for(j=0;j<len;j++)data[inptr++]=i+j;
  109528. /* submit the test packet */
  109529. ogg_stream_packetin(&os_en,&op);
  109530. /* retrieve any finished pages */
  109531. {
  109532. ogg_page og;
  109533. while(ogg_stream_pageout(&os_en,&og)){
  109534. /* We have a page. Check it carefully */
  109535. fprintf(stderr,"%ld, ",pageno);
  109536. if(headers[pageno]==NULL){
  109537. fprintf(stderr,"coded too many pages!\n");
  109538. exit(1);
  109539. }
  109540. check_page(data+outptr,headers[pageno],&og);
  109541. outptr+=og.body_len;
  109542. pageno++;
  109543. if(pageskip){
  109544. bosflag=1;
  109545. pageskip--;
  109546. deptr+=og.body_len;
  109547. }
  109548. /* have a complete page; submit it to sync/decode */
  109549. {
  109550. ogg_page og_de;
  109551. ogg_packet op_de,op_de2;
  109552. char *buf=ogg_sync_buffer(&oy,og.header_len+og.body_len);
  109553. char *next=buf;
  109554. byteskipcount+=og.header_len;
  109555. if(byteskipcount>byteskip){
  109556. memcpy(next,og.header,byteskipcount-byteskip);
  109557. next+=byteskipcount-byteskip;
  109558. byteskipcount=byteskip;
  109559. }
  109560. byteskipcount+=og.body_len;
  109561. if(byteskipcount>byteskip){
  109562. memcpy(next,og.body,byteskipcount-byteskip);
  109563. next+=byteskipcount-byteskip;
  109564. byteskipcount=byteskip;
  109565. }
  109566. ogg_sync_wrote(&oy,next-buf);
  109567. while(1){
  109568. int ret=ogg_sync_pageout(&oy,&og_de);
  109569. if(ret==0)break;
  109570. if(ret<0)continue;
  109571. /* got a page. Happy happy. Verify that it's good. */
  109572. fprintf(stderr,"(%ld), ",pageout);
  109573. check_page(data+deptr,headers[pageout],&og_de);
  109574. deptr+=og_de.body_len;
  109575. pageout++;
  109576. /* submit it to deconstitution */
  109577. ogg_stream_pagein(&os_de,&og_de);
  109578. /* packets out? */
  109579. while(ogg_stream_packetpeek(&os_de,&op_de2)>0){
  109580. ogg_stream_packetpeek(&os_de,NULL);
  109581. ogg_stream_packetout(&os_de,&op_de); /* just catching them all */
  109582. /* verify peek and out match */
  109583. if(memcmp(&op_de,&op_de2,sizeof(op_de))){
  109584. fprintf(stderr,"packetout != packetpeek! pos=%ld\n",
  109585. depacket);
  109586. exit(1);
  109587. }
  109588. /* verify the packet! */
  109589. /* check data */
  109590. if(memcmp(data+depacket,op_de.packet,op_de.bytes)){
  109591. fprintf(stderr,"packet data mismatch in decode! pos=%ld\n",
  109592. depacket);
  109593. exit(1);
  109594. }
  109595. /* check bos flag */
  109596. if(bosflag==0 && op_de.b_o_s==0){
  109597. fprintf(stderr,"b_o_s flag not set on packet!\n");
  109598. exit(1);
  109599. }
  109600. if(bosflag && op_de.b_o_s){
  109601. fprintf(stderr,"b_o_s flag incorrectly set on packet!\n");
  109602. exit(1);
  109603. }
  109604. bosflag=1;
  109605. depacket+=op_de.bytes;
  109606. /* check eos flag */
  109607. if(eosflag){
  109608. fprintf(stderr,"Multiple decoded packets with eos flag!\n");
  109609. exit(1);
  109610. }
  109611. if(op_de.e_o_s)eosflag=1;
  109612. /* check granulepos flag */
  109613. if(op_de.granulepos!=-1){
  109614. fprintf(stderr," granule:%ld ",(long)op_de.granulepos);
  109615. }
  109616. }
  109617. }
  109618. }
  109619. }
  109620. }
  109621. }
  109622. _ogg_free(data);
  109623. if(headers[pageno]!=NULL){
  109624. fprintf(stderr,"did not write last page!\n");
  109625. exit(1);
  109626. }
  109627. if(headers[pageout]!=NULL){
  109628. fprintf(stderr,"did not decode last page!\n");
  109629. exit(1);
  109630. }
  109631. if(inptr!=outptr){
  109632. fprintf(stderr,"encoded page data incomplete!\n");
  109633. exit(1);
  109634. }
  109635. if(inptr!=deptr){
  109636. fprintf(stderr,"decoded page data incomplete!\n");
  109637. exit(1);
  109638. }
  109639. if(inptr!=depacket){
  109640. fprintf(stderr,"decoded packet data incomplete!\n");
  109641. exit(1);
  109642. }
  109643. if(!eosflag){
  109644. fprintf(stderr,"Never got a packet with EOS set!\n");
  109645. exit(1);
  109646. }
  109647. fprintf(stderr,"ok.\n");
  109648. }
  109649. int main(void){
  109650. ogg_stream_init(&os_en,0x04030201);
  109651. ogg_stream_init(&os_de,0x04030201);
  109652. ogg_sync_init(&oy);
  109653. /* Exercise each code path in the framing code. Also verify that
  109654. the checksums are working. */
  109655. {
  109656. /* 17 only */
  109657. const int packets[]={17, -1};
  109658. const int *headret[]={head1_0,NULL};
  109659. fprintf(stderr,"testing single page encoding... ");
  109660. test_pack(packets,headret,0,0,0);
  109661. }
  109662. {
  109663. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  109664. const int packets[]={17, 254, 255, 256, 500, 510, 600, -1};
  109665. const int *headret[]={head1_1,head2_1,NULL};
  109666. fprintf(stderr,"testing basic page encoding... ");
  109667. test_pack(packets,headret,0,0,0);
  109668. }
  109669. {
  109670. /* nil packets; beginning,middle,end */
  109671. const int packets[]={0,17, 254, 255, 0, 256, 0, 500, 510, 600, 0, -1};
  109672. const int *headret[]={head1_2,head2_2,NULL};
  109673. fprintf(stderr,"testing basic nil packets... ");
  109674. test_pack(packets,headret,0,0,0);
  109675. }
  109676. {
  109677. /* large initial packet */
  109678. const int packets[]={4345,259,255,-1};
  109679. const int *headret[]={head1_3,head2_3,NULL};
  109680. fprintf(stderr,"testing initial-packet lacing > 4k... ");
  109681. test_pack(packets,headret,0,0,0);
  109682. }
  109683. {
  109684. /* continuing packet test */
  109685. const int packets[]={0,4345,259,255,-1};
  109686. const int *headret[]={head1_4,head2_4,head3_4,NULL};
  109687. fprintf(stderr,"testing single packet page span... ");
  109688. test_pack(packets,headret,0,0,0);
  109689. }
  109690. /* page with the 255 segment limit */
  109691. {
  109692. const int packets[]={0,10,10,10,10,10,10,10,10,
  109693. 10,10,10,10,10,10,10,10,
  109694. 10,10,10,10,10,10,10,10,
  109695. 10,10,10,10,10,10,10,10,
  109696. 10,10,10,10,10,10,10,10,
  109697. 10,10,10,10,10,10,10,10,
  109698. 10,10,10,10,10,10,10,10,
  109699. 10,10,10,10,10,10,10,10,
  109700. 10,10,10,10,10,10,10,10,
  109701. 10,10,10,10,10,10,10,10,
  109702. 10,10,10,10,10,10,10,10,
  109703. 10,10,10,10,10,10,10,10,
  109704. 10,10,10,10,10,10,10,10,
  109705. 10,10,10,10,10,10,10,10,
  109706. 10,10,10,10,10,10,10,10,
  109707. 10,10,10,10,10,10,10,10,
  109708. 10,10,10,10,10,10,10,10,
  109709. 10,10,10,10,10,10,10,10,
  109710. 10,10,10,10,10,10,10,10,
  109711. 10,10,10,10,10,10,10,10,
  109712. 10,10,10,10,10,10,10,10,
  109713. 10,10,10,10,10,10,10,10,
  109714. 10,10,10,10,10,10,10,10,
  109715. 10,10,10,10,10,10,10,10,
  109716. 10,10,10,10,10,10,10,10,
  109717. 10,10,10,10,10,10,10,10,
  109718. 10,10,10,10,10,10,10,10,
  109719. 10,10,10,10,10,10,10,10,
  109720. 10,10,10,10,10,10,10,10,
  109721. 10,10,10,10,10,10,10,10,
  109722. 10,10,10,10,10,10,10,10,
  109723. 10,10,10,10,10,10,10,50,-1};
  109724. const int *headret[]={head1_5,head2_5,head3_5,NULL};
  109725. fprintf(stderr,"testing max packet segments... ");
  109726. test_pack(packets,headret,0,0,0);
  109727. }
  109728. {
  109729. /* packet that overspans over an entire page */
  109730. const int packets[]={0,100,9000,259,255,-1};
  109731. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  109732. fprintf(stderr,"testing very large packets... ");
  109733. test_pack(packets,headret,0,0,0);
  109734. }
  109735. {
  109736. /* test for the libogg 1.1.1 resync in large continuation bug
  109737. found by Josh Coalson) */
  109738. const int packets[]={0,100,9000,259,255,-1};
  109739. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  109740. fprintf(stderr,"testing continuation resync in very large packets... ");
  109741. test_pack(packets,headret,100,2,3);
  109742. }
  109743. {
  109744. /* term only page. why not? */
  109745. const int packets[]={0,100,4080,-1};
  109746. const int *headret[]={head1_7,head2_7,head3_7,NULL};
  109747. fprintf(stderr,"testing zero data page (1 nil packet)... ");
  109748. test_pack(packets,headret,0,0,0);
  109749. }
  109750. {
  109751. /* build a bunch of pages for testing */
  109752. unsigned char *data=_ogg_malloc(1024*1024);
  109753. int pl[]={0,100,4079,2956,2057,76,34,912,0,234,1000,1000,1000,300,-1};
  109754. int inptr=0,i,j;
  109755. ogg_page og[5];
  109756. ogg_stream_reset(&os_en);
  109757. for(i=0;pl[i]!=-1;i++){
  109758. ogg_packet op;
  109759. int len=pl[i];
  109760. op.packet=data+inptr;
  109761. op.bytes=len;
  109762. op.e_o_s=(pl[i+1]<0?1:0);
  109763. op.granulepos=(i+1)*1000;
  109764. for(j=0;j<len;j++)data[inptr++]=i+j;
  109765. ogg_stream_packetin(&os_en,&op);
  109766. }
  109767. _ogg_free(data);
  109768. /* retrieve finished pages */
  109769. for(i=0;i<5;i++){
  109770. if(ogg_stream_pageout(&os_en,&og[i])==0){
  109771. fprintf(stderr,"Too few pages output building sync tests!\n");
  109772. exit(1);
  109773. }
  109774. copy_page(&og[i]);
  109775. }
  109776. /* Test lost pages on pagein/packetout: no rollback */
  109777. {
  109778. ogg_page temp;
  109779. ogg_packet test;
  109780. fprintf(stderr,"Testing loss of pages... ");
  109781. ogg_sync_reset(&oy);
  109782. ogg_stream_reset(&os_de);
  109783. for(i=0;i<5;i++){
  109784. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  109785. og[i].header_len);
  109786. ogg_sync_wrote(&oy,og[i].header_len);
  109787. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  109788. ogg_sync_wrote(&oy,og[i].body_len);
  109789. }
  109790. ogg_sync_pageout(&oy,&temp);
  109791. ogg_stream_pagein(&os_de,&temp);
  109792. ogg_sync_pageout(&oy,&temp);
  109793. ogg_stream_pagein(&os_de,&temp);
  109794. ogg_sync_pageout(&oy,&temp);
  109795. /* skip */
  109796. ogg_sync_pageout(&oy,&temp);
  109797. ogg_stream_pagein(&os_de,&temp);
  109798. /* do we get the expected results/packets? */
  109799. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109800. checkpacket(&test,0,0,0);
  109801. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109802. checkpacket(&test,100,1,-1);
  109803. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109804. checkpacket(&test,4079,2,3000);
  109805. if(ogg_stream_packetout(&os_de,&test)!=-1){
  109806. fprintf(stderr,"Error: loss of page did not return error\n");
  109807. exit(1);
  109808. }
  109809. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109810. checkpacket(&test,76,5,-1);
  109811. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109812. checkpacket(&test,34,6,-1);
  109813. fprintf(stderr,"ok.\n");
  109814. }
  109815. /* Test lost pages on pagein/packetout: rollback with continuation */
  109816. {
  109817. ogg_page temp;
  109818. ogg_packet test;
  109819. fprintf(stderr,"Testing loss of pages (rollback required)... ");
  109820. ogg_sync_reset(&oy);
  109821. ogg_stream_reset(&os_de);
  109822. for(i=0;i<5;i++){
  109823. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  109824. og[i].header_len);
  109825. ogg_sync_wrote(&oy,og[i].header_len);
  109826. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  109827. ogg_sync_wrote(&oy,og[i].body_len);
  109828. }
  109829. ogg_sync_pageout(&oy,&temp);
  109830. ogg_stream_pagein(&os_de,&temp);
  109831. ogg_sync_pageout(&oy,&temp);
  109832. ogg_stream_pagein(&os_de,&temp);
  109833. ogg_sync_pageout(&oy,&temp);
  109834. ogg_stream_pagein(&os_de,&temp);
  109835. ogg_sync_pageout(&oy,&temp);
  109836. /* skip */
  109837. ogg_sync_pageout(&oy,&temp);
  109838. ogg_stream_pagein(&os_de,&temp);
  109839. /* do we get the expected results/packets? */
  109840. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109841. checkpacket(&test,0,0,0);
  109842. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109843. checkpacket(&test,100,1,-1);
  109844. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109845. checkpacket(&test,4079,2,3000);
  109846. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109847. checkpacket(&test,2956,3,4000);
  109848. if(ogg_stream_packetout(&os_de,&test)!=-1){
  109849. fprintf(stderr,"Error: loss of page did not return error\n");
  109850. exit(1);
  109851. }
  109852. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109853. checkpacket(&test,300,13,14000);
  109854. fprintf(stderr,"ok.\n");
  109855. }
  109856. /* the rest only test sync */
  109857. {
  109858. ogg_page og_de;
  109859. /* Test fractional page inputs: incomplete capture */
  109860. fprintf(stderr,"Testing sync on partial inputs... ");
  109861. ogg_sync_reset(&oy);
  109862. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109863. 3);
  109864. ogg_sync_wrote(&oy,3);
  109865. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109866. /* Test fractional page inputs: incomplete fixed header */
  109867. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+3,
  109868. 20);
  109869. ogg_sync_wrote(&oy,20);
  109870. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109871. /* Test fractional page inputs: incomplete header */
  109872. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+23,
  109873. 5);
  109874. ogg_sync_wrote(&oy,5);
  109875. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109876. /* Test fractional page inputs: incomplete body */
  109877. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+28,
  109878. og[1].header_len-28);
  109879. ogg_sync_wrote(&oy,og[1].header_len-28);
  109880. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109881. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,1000);
  109882. ogg_sync_wrote(&oy,1000);
  109883. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109884. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body+1000,
  109885. og[1].body_len-1000);
  109886. ogg_sync_wrote(&oy,og[1].body_len-1000);
  109887. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109888. fprintf(stderr,"ok.\n");
  109889. }
  109890. /* Test fractional page inputs: page + incomplete capture */
  109891. {
  109892. ogg_page og_de;
  109893. fprintf(stderr,"Testing sync on 1+partial inputs... ");
  109894. ogg_sync_reset(&oy);
  109895. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109896. og[1].header_len);
  109897. ogg_sync_wrote(&oy,og[1].header_len);
  109898. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109899. og[1].body_len);
  109900. ogg_sync_wrote(&oy,og[1].body_len);
  109901. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109902. 20);
  109903. ogg_sync_wrote(&oy,20);
  109904. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109905. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109906. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+20,
  109907. og[1].header_len-20);
  109908. ogg_sync_wrote(&oy,og[1].header_len-20);
  109909. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109910. og[1].body_len);
  109911. ogg_sync_wrote(&oy,og[1].body_len);
  109912. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109913. fprintf(stderr,"ok.\n");
  109914. }
  109915. /* Test recapture: garbage + page */
  109916. {
  109917. ogg_page og_de;
  109918. fprintf(stderr,"Testing search for capture... ");
  109919. ogg_sync_reset(&oy);
  109920. /* 'garbage' */
  109921. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109922. og[1].body_len);
  109923. ogg_sync_wrote(&oy,og[1].body_len);
  109924. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109925. og[1].header_len);
  109926. ogg_sync_wrote(&oy,og[1].header_len);
  109927. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109928. og[1].body_len);
  109929. ogg_sync_wrote(&oy,og[1].body_len);
  109930. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  109931. 20);
  109932. ogg_sync_wrote(&oy,20);
  109933. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109934. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109935. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109936. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header+20,
  109937. og[2].header_len-20);
  109938. ogg_sync_wrote(&oy,og[2].header_len-20);
  109939. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  109940. og[2].body_len);
  109941. ogg_sync_wrote(&oy,og[2].body_len);
  109942. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109943. fprintf(stderr,"ok.\n");
  109944. }
  109945. /* Test recapture: page + garbage + page */
  109946. {
  109947. ogg_page og_de;
  109948. fprintf(stderr,"Testing recapture... ");
  109949. ogg_sync_reset(&oy);
  109950. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109951. og[1].header_len);
  109952. ogg_sync_wrote(&oy,og[1].header_len);
  109953. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109954. og[1].body_len);
  109955. ogg_sync_wrote(&oy,og[1].body_len);
  109956. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  109957. og[2].header_len);
  109958. ogg_sync_wrote(&oy,og[2].header_len);
  109959. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  109960. og[2].header_len);
  109961. ogg_sync_wrote(&oy,og[2].header_len);
  109962. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109963. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  109964. og[2].body_len-5);
  109965. ogg_sync_wrote(&oy,og[2].body_len-5);
  109966. memcpy(ogg_sync_buffer(&oy,og[3].header_len),og[3].header,
  109967. og[3].header_len);
  109968. ogg_sync_wrote(&oy,og[3].header_len);
  109969. memcpy(ogg_sync_buffer(&oy,og[3].body_len),og[3].body,
  109970. og[3].body_len);
  109971. ogg_sync_wrote(&oy,og[3].body_len);
  109972. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109973. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109974. fprintf(stderr,"ok.\n");
  109975. }
  109976. /* Free page data that was previously copied */
  109977. {
  109978. for(i=0;i<5;i++){
  109979. free_page(&og[i]);
  109980. }
  109981. }
  109982. }
  109983. return(0);
  109984. }
  109985. #endif
  109986. #endif
  109987. /*** End of inlined file: framing.c ***/
  109988. /*** Start of inlined file: analysis.c ***/
  109989. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  109990. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  109991. // tasks..
  109992. #if JUCE_MSVC
  109993. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  109994. #endif
  109995. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  109996. #if JUCE_USE_OGGVORBIS
  109997. #include <stdio.h>
  109998. #include <string.h>
  109999. #include <math.h>
  110000. /*** Start of inlined file: codec_internal.h ***/
  110001. #ifndef _V_CODECI_H_
  110002. #define _V_CODECI_H_
  110003. /*** Start of inlined file: envelope.h ***/
  110004. #ifndef _V_ENVELOPE_
  110005. #define _V_ENVELOPE_
  110006. /*** Start of inlined file: mdct.h ***/
  110007. #ifndef _OGG_mdct_H_
  110008. #define _OGG_mdct_H_
  110009. /*#define MDCT_INTEGERIZED <- be warned there could be some hurt left here*/
  110010. #ifdef MDCT_INTEGERIZED
  110011. #define DATA_TYPE int
  110012. #define REG_TYPE register int
  110013. #define TRIGBITS 14
  110014. #define cPI3_8 6270
  110015. #define cPI2_8 11585
  110016. #define cPI1_8 15137
  110017. #define FLOAT_CONV(x) ((int)((x)*(1<<TRIGBITS)+.5))
  110018. #define MULT_NORM(x) ((x)>>TRIGBITS)
  110019. #define HALVE(x) ((x)>>1)
  110020. #else
  110021. #define DATA_TYPE float
  110022. #define REG_TYPE float
  110023. #define cPI3_8 .38268343236508977175F
  110024. #define cPI2_8 .70710678118654752441F
  110025. #define cPI1_8 .92387953251128675613F
  110026. #define FLOAT_CONV(x) (x)
  110027. #define MULT_NORM(x) (x)
  110028. #define HALVE(x) ((x)*.5f)
  110029. #endif
  110030. typedef struct {
  110031. int n;
  110032. int log2n;
  110033. DATA_TYPE *trig;
  110034. int *bitrev;
  110035. DATA_TYPE scale;
  110036. } mdct_lookup;
  110037. extern void mdct_init(mdct_lookup *lookup,int n);
  110038. extern void mdct_clear(mdct_lookup *l);
  110039. extern void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  110040. extern void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  110041. #endif
  110042. /*** End of inlined file: mdct.h ***/
  110043. #define VE_PRE 16
  110044. #define VE_WIN 4
  110045. #define VE_POST 2
  110046. #define VE_AMP (VE_PRE+VE_POST-1)
  110047. #define VE_BANDS 7
  110048. #define VE_NEARDC 15
  110049. #define VE_MINSTRETCH 2 /* a bit less than short block */
  110050. #define VE_MAXSTRETCH 12 /* one-third full block */
  110051. typedef struct {
  110052. float ampbuf[VE_AMP];
  110053. int ampptr;
  110054. float nearDC[VE_NEARDC];
  110055. float nearDC_acc;
  110056. float nearDC_partialacc;
  110057. int nearptr;
  110058. } envelope_filter_state;
  110059. typedef struct {
  110060. int begin;
  110061. int end;
  110062. float *window;
  110063. float total;
  110064. } envelope_band;
  110065. typedef struct {
  110066. int ch;
  110067. int winlength;
  110068. int searchstep;
  110069. float minenergy;
  110070. mdct_lookup mdct;
  110071. float *mdct_win;
  110072. envelope_band band[VE_BANDS];
  110073. envelope_filter_state *filter;
  110074. int stretch;
  110075. int *mark;
  110076. long storage;
  110077. long current;
  110078. long curmark;
  110079. long cursor;
  110080. } envelope_lookup;
  110081. extern void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi);
  110082. extern void _ve_envelope_clear(envelope_lookup *e);
  110083. extern long _ve_envelope_search(vorbis_dsp_state *v);
  110084. extern void _ve_envelope_shift(envelope_lookup *e,long shift);
  110085. extern int _ve_envelope_mark(vorbis_dsp_state *v);
  110086. #endif
  110087. /*** End of inlined file: envelope.h ***/
  110088. /*** Start of inlined file: codebook.h ***/
  110089. #ifndef _V_CODEBOOK_H_
  110090. #define _V_CODEBOOK_H_
  110091. /* This structure encapsulates huffman and VQ style encoding books; it
  110092. doesn't do anything specific to either.
  110093. valuelist/quantlist are nonNULL (and q_* significant) only if
  110094. there's entry->value mapping to be done.
  110095. If encode-side mapping must be done (and thus the entry needs to be
  110096. hunted), the auxiliary encode pointer will point to a decision
  110097. tree. This is true of both VQ and huffman, but is mostly useful
  110098. with VQ.
  110099. */
  110100. typedef struct static_codebook{
  110101. long dim; /* codebook dimensions (elements per vector) */
  110102. long entries; /* codebook entries */
  110103. long *lengthlist; /* codeword lengths in bits */
  110104. /* mapping ***************************************************************/
  110105. int maptype; /* 0=none
  110106. 1=implicitly populated values from map column
  110107. 2=listed arbitrary values */
  110108. /* The below does a linear, single monotonic sequence mapping. */
  110109. long q_min; /* packed 32 bit float; quant value 0 maps to minval */
  110110. long q_delta; /* packed 32 bit float; val 1 - val 0 == delta */
  110111. int q_quant; /* bits: 0 < quant <= 16 */
  110112. int q_sequencep; /* bitflag */
  110113. long *quantlist; /* map == 1: (int)(entries^(1/dim)) element column map
  110114. map == 2: list of dim*entries quantized entry vals
  110115. */
  110116. /* encode helpers ********************************************************/
  110117. struct encode_aux_nearestmatch *nearest_tree;
  110118. struct encode_aux_threshmatch *thresh_tree;
  110119. struct encode_aux_pigeonhole *pigeon_tree;
  110120. int allocedp;
  110121. } static_codebook;
  110122. /* this structures an arbitrary trained book to quickly find the
  110123. nearest cell match */
  110124. typedef struct encode_aux_nearestmatch{
  110125. /* pre-calculated partitioning tree */
  110126. long *ptr0;
  110127. long *ptr1;
  110128. long *p; /* decision points (each is an entry) */
  110129. long *q; /* decision points (each is an entry) */
  110130. long aux; /* number of tree entries */
  110131. long alloc;
  110132. } encode_aux_nearestmatch;
  110133. /* assumes a maptype of 1; encode side only, so that's OK */
  110134. typedef struct encode_aux_threshmatch{
  110135. float *quantthresh;
  110136. long *quantmap;
  110137. int quantvals;
  110138. int threshvals;
  110139. } encode_aux_threshmatch;
  110140. typedef struct encode_aux_pigeonhole{
  110141. float min;
  110142. float del;
  110143. int mapentries;
  110144. int quantvals;
  110145. long *pigeonmap;
  110146. long fittotal;
  110147. long *fitlist;
  110148. long *fitmap;
  110149. long *fitlength;
  110150. } encode_aux_pigeonhole;
  110151. typedef struct codebook{
  110152. long dim; /* codebook dimensions (elements per vector) */
  110153. long entries; /* codebook entries */
  110154. long used_entries; /* populated codebook entries */
  110155. const static_codebook *c;
  110156. /* for encode, the below are entry-ordered, fully populated */
  110157. /* for decode, the below are ordered by bitreversed codeword and only
  110158. used entries are populated */
  110159. float *valuelist; /* list of dim*entries actual entry values */
  110160. ogg_uint32_t *codelist; /* list of bitstream codewords for each entry */
  110161. int *dec_index; /* only used if sparseness collapsed */
  110162. char *dec_codelengths;
  110163. ogg_uint32_t *dec_firsttable;
  110164. int dec_firsttablen;
  110165. int dec_maxlength;
  110166. } codebook;
  110167. extern void vorbis_staticbook_clear(static_codebook *b);
  110168. extern void vorbis_staticbook_destroy(static_codebook *b);
  110169. extern int vorbis_book_init_encode(codebook *dest,const static_codebook *source);
  110170. extern int vorbis_book_init_decode(codebook *dest,const static_codebook *source);
  110171. extern void vorbis_book_clear(codebook *b);
  110172. extern float *_book_unquantize(const static_codebook *b,int n,int *map);
  110173. extern float *_book_logdist(const static_codebook *b,float *vals);
  110174. extern float _float32_unpack(long val);
  110175. extern long _float32_pack(float val);
  110176. extern int _best(codebook *book, float *a, int step);
  110177. extern int _ilog(unsigned int v);
  110178. extern long _book_maptype1_quantvals(const static_codebook *b);
  110179. extern int vorbis_book_besterror(codebook *book,float *a,int step,int addmul);
  110180. extern long vorbis_book_codeword(codebook *book,int entry);
  110181. extern long vorbis_book_codelen(codebook *book,int entry);
  110182. extern int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *b);
  110183. extern int vorbis_staticbook_unpack(oggpack_buffer *b,static_codebook *c);
  110184. extern int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b);
  110185. extern int vorbis_book_errorv(codebook *book, float *a);
  110186. extern int vorbis_book_encodev(codebook *book, int best,float *a,
  110187. oggpack_buffer *b);
  110188. extern long vorbis_book_decode(codebook *book, oggpack_buffer *b);
  110189. extern long vorbis_book_decodevs_add(codebook *book, float *a,
  110190. oggpack_buffer *b,int n);
  110191. extern long vorbis_book_decodev_set(codebook *book, float *a,
  110192. oggpack_buffer *b,int n);
  110193. extern long vorbis_book_decodev_add(codebook *book, float *a,
  110194. oggpack_buffer *b,int n);
  110195. extern long vorbis_book_decodevv_add(codebook *book, float **a,
  110196. long off,int ch,
  110197. oggpack_buffer *b,int n);
  110198. #endif
  110199. /*** End of inlined file: codebook.h ***/
  110200. #define BLOCKTYPE_IMPULSE 0
  110201. #define BLOCKTYPE_PADDING 1
  110202. #define BLOCKTYPE_TRANSITION 0
  110203. #define BLOCKTYPE_LONG 1
  110204. #define PACKETBLOBS 15
  110205. typedef struct vorbis_block_internal{
  110206. float **pcmdelay; /* this is a pointer into local storage */
  110207. float ampmax;
  110208. int blocktype;
  110209. oggpack_buffer *packetblob[PACKETBLOBS]; /* initialized, must be freed;
  110210. blob [PACKETBLOBS/2] points to
  110211. the oggpack_buffer in the
  110212. main vorbis_block */
  110213. } vorbis_block_internal;
  110214. typedef void vorbis_look_floor;
  110215. typedef void vorbis_look_residue;
  110216. typedef void vorbis_look_transform;
  110217. /* mode ************************************************************/
  110218. typedef struct {
  110219. int blockflag;
  110220. int windowtype;
  110221. int transformtype;
  110222. int mapping;
  110223. } vorbis_info_mode;
  110224. typedef void vorbis_info_floor;
  110225. typedef void vorbis_info_residue;
  110226. typedef void vorbis_info_mapping;
  110227. /*** Start of inlined file: psy.h ***/
  110228. #ifndef _V_PSY_H_
  110229. #define _V_PSY_H_
  110230. /*** Start of inlined file: smallft.h ***/
  110231. #ifndef _V_SMFT_H_
  110232. #define _V_SMFT_H_
  110233. typedef struct {
  110234. int n;
  110235. float *trigcache;
  110236. int *splitcache;
  110237. } drft_lookup;
  110238. extern void drft_forward(drft_lookup *l,float *data);
  110239. extern void drft_backward(drft_lookup *l,float *data);
  110240. extern void drft_init(drft_lookup *l,int n);
  110241. extern void drft_clear(drft_lookup *l);
  110242. #endif
  110243. /*** End of inlined file: smallft.h ***/
  110244. /*** Start of inlined file: backends.h ***/
  110245. /* this is exposed up here because we need it for static modes.
  110246. Lookups for each backend aren't exposed because there's no reason
  110247. to do so */
  110248. #ifndef _vorbis_backend_h_
  110249. #define _vorbis_backend_h_
  110250. /* this would all be simpler/shorter with templates, but.... */
  110251. /* Floor backend generic *****************************************/
  110252. typedef struct{
  110253. void (*pack) (vorbis_info_floor *,oggpack_buffer *);
  110254. vorbis_info_floor *(*unpack)(vorbis_info *,oggpack_buffer *);
  110255. vorbis_look_floor *(*look) (vorbis_dsp_state *,vorbis_info_floor *);
  110256. void (*free_info) (vorbis_info_floor *);
  110257. void (*free_look) (vorbis_look_floor *);
  110258. void *(*inverse1) (struct vorbis_block *,vorbis_look_floor *);
  110259. int (*inverse2) (struct vorbis_block *,vorbis_look_floor *,
  110260. void *buffer,float *);
  110261. } vorbis_func_floor;
  110262. typedef struct{
  110263. int order;
  110264. long rate;
  110265. long barkmap;
  110266. int ampbits;
  110267. int ampdB;
  110268. int numbooks; /* <= 16 */
  110269. int books[16];
  110270. float lessthan; /* encode-only config setting hacks for libvorbis */
  110271. float greaterthan; /* encode-only config setting hacks for libvorbis */
  110272. } vorbis_info_floor0;
  110273. #define VIF_POSIT 63
  110274. #define VIF_CLASS 16
  110275. #define VIF_PARTS 31
  110276. typedef struct{
  110277. int partitions; /* 0 to 31 */
  110278. int partitionclass[VIF_PARTS]; /* 0 to 15 */
  110279. int class_dim[VIF_CLASS]; /* 1 to 8 */
  110280. int class_subs[VIF_CLASS]; /* 0,1,2,3 (bits: 1<<n poss) */
  110281. int class_book[VIF_CLASS]; /* subs ^ dim entries */
  110282. int class_subbook[VIF_CLASS][8]; /* [VIF_CLASS][subs] */
  110283. int mult; /* 1 2 3 or 4 */
  110284. int postlist[VIF_POSIT+2]; /* first two implicit */
  110285. /* encode side analysis parameters */
  110286. float maxover;
  110287. float maxunder;
  110288. float maxerr;
  110289. float twofitweight;
  110290. float twofitatten;
  110291. int n;
  110292. } vorbis_info_floor1;
  110293. /* Residue backend generic *****************************************/
  110294. typedef struct{
  110295. void (*pack) (vorbis_info_residue *,oggpack_buffer *);
  110296. vorbis_info_residue *(*unpack)(vorbis_info *,oggpack_buffer *);
  110297. vorbis_look_residue *(*look) (vorbis_dsp_state *,
  110298. vorbis_info_residue *);
  110299. void (*free_info) (vorbis_info_residue *);
  110300. void (*free_look) (vorbis_look_residue *);
  110301. long **(*classx) (struct vorbis_block *,vorbis_look_residue *,
  110302. float **,int *,int);
  110303. int (*forward) (oggpack_buffer *,struct vorbis_block *,
  110304. vorbis_look_residue *,
  110305. float **,float **,int *,int,long **);
  110306. int (*inverse) (struct vorbis_block *,vorbis_look_residue *,
  110307. float **,int *,int);
  110308. } vorbis_func_residue;
  110309. typedef struct vorbis_info_residue0{
  110310. /* block-partitioned VQ coded straight residue */
  110311. long begin;
  110312. long end;
  110313. /* first stage (lossless partitioning) */
  110314. int grouping; /* group n vectors per partition */
  110315. int partitions; /* possible codebooks for a partition */
  110316. int groupbook; /* huffbook for partitioning */
  110317. int secondstages[64]; /* expanded out to pointers in lookup */
  110318. int booklist[256]; /* list of second stage books */
  110319. float classmetric1[64];
  110320. float classmetric2[64];
  110321. } vorbis_info_residue0;
  110322. /* Mapping backend generic *****************************************/
  110323. typedef struct{
  110324. void (*pack) (vorbis_info *,vorbis_info_mapping *,
  110325. oggpack_buffer *);
  110326. vorbis_info_mapping *(*unpack)(vorbis_info *,oggpack_buffer *);
  110327. void (*free_info) (vorbis_info_mapping *);
  110328. int (*forward) (struct vorbis_block *vb);
  110329. int (*inverse) (struct vorbis_block *vb,vorbis_info_mapping *);
  110330. } vorbis_func_mapping;
  110331. typedef struct vorbis_info_mapping0{
  110332. int submaps; /* <= 16 */
  110333. int chmuxlist[256]; /* up to 256 channels in a Vorbis stream */
  110334. int floorsubmap[16]; /* [mux] submap to floors */
  110335. int residuesubmap[16]; /* [mux] submap to residue */
  110336. int coupling_steps;
  110337. int coupling_mag[256];
  110338. int coupling_ang[256];
  110339. } vorbis_info_mapping0;
  110340. #endif
  110341. /*** End of inlined file: backends.h ***/
  110342. #ifndef EHMER_MAX
  110343. #define EHMER_MAX 56
  110344. #endif
  110345. /* psychoacoustic setup ********************************************/
  110346. #define P_BANDS 17 /* 62Hz to 16kHz */
  110347. #define P_LEVELS 8 /* 30dB to 100dB */
  110348. #define P_LEVEL_0 30. /* 30 dB */
  110349. #define P_NOISECURVES 3
  110350. #define NOISE_COMPAND_LEVELS 40
  110351. typedef struct vorbis_info_psy{
  110352. int blockflag;
  110353. float ath_adjatt;
  110354. float ath_maxatt;
  110355. float tone_masteratt[P_NOISECURVES];
  110356. float tone_centerboost;
  110357. float tone_decay;
  110358. float tone_abs_limit;
  110359. float toneatt[P_BANDS];
  110360. int noisemaskp;
  110361. float noisemaxsupp;
  110362. float noisewindowlo;
  110363. float noisewindowhi;
  110364. int noisewindowlomin;
  110365. int noisewindowhimin;
  110366. int noisewindowfixed;
  110367. float noiseoff[P_NOISECURVES][P_BANDS];
  110368. float noisecompand[NOISE_COMPAND_LEVELS];
  110369. float max_curve_dB;
  110370. int normal_channel_p;
  110371. int normal_point_p;
  110372. int normal_start;
  110373. int normal_partition;
  110374. double normal_thresh;
  110375. } vorbis_info_psy;
  110376. typedef struct{
  110377. int eighth_octave_lines;
  110378. /* for block long/short tuning; encode only */
  110379. float preecho_thresh[VE_BANDS];
  110380. float postecho_thresh[VE_BANDS];
  110381. float stretch_penalty;
  110382. float preecho_minenergy;
  110383. float ampmax_att_per_sec;
  110384. /* channel coupling config */
  110385. int coupling_pkHz[PACKETBLOBS];
  110386. int coupling_pointlimit[2][PACKETBLOBS];
  110387. int coupling_prepointamp[PACKETBLOBS];
  110388. int coupling_postpointamp[PACKETBLOBS];
  110389. int sliding_lowpass[2][PACKETBLOBS];
  110390. } vorbis_info_psy_global;
  110391. typedef struct {
  110392. float ampmax;
  110393. int channels;
  110394. vorbis_info_psy_global *gi;
  110395. int coupling_pointlimit[2][P_NOISECURVES];
  110396. } vorbis_look_psy_global;
  110397. typedef struct {
  110398. int n;
  110399. struct vorbis_info_psy *vi;
  110400. float ***tonecurves;
  110401. float **noiseoffset;
  110402. float *ath;
  110403. long *octave; /* in n.ocshift format */
  110404. long *bark;
  110405. long firstoc;
  110406. long shiftoc;
  110407. int eighth_octave_lines; /* power of two, please */
  110408. int total_octave_lines;
  110409. long rate; /* cache it */
  110410. float m_val; /* Masking compensation value */
  110411. } vorbis_look_psy;
  110412. extern void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  110413. vorbis_info_psy_global *gi,int n,long rate);
  110414. extern void _vp_psy_clear(vorbis_look_psy *p);
  110415. extern void *_vi_psy_dup(void *source);
  110416. extern void _vi_psy_free(vorbis_info_psy *i);
  110417. extern vorbis_info_psy *_vi_psy_copy(vorbis_info_psy *i);
  110418. extern void _vp_remove_floor(vorbis_look_psy *p,
  110419. float *mdct,
  110420. int *icodedflr,
  110421. float *residue,
  110422. int sliding_lowpass);
  110423. extern void _vp_noisemask(vorbis_look_psy *p,
  110424. float *logmdct,
  110425. float *logmask);
  110426. extern void _vp_tonemask(vorbis_look_psy *p,
  110427. float *logfft,
  110428. float *logmask,
  110429. float global_specmax,
  110430. float local_specmax);
  110431. extern void _vp_offset_and_mix(vorbis_look_psy *p,
  110432. float *noise,
  110433. float *tone,
  110434. int offset_select,
  110435. float *logmask,
  110436. float *mdct,
  110437. float *logmdct);
  110438. extern float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd);
  110439. extern float **_vp_quantize_couple_memo(vorbis_block *vb,
  110440. vorbis_info_psy_global *g,
  110441. vorbis_look_psy *p,
  110442. vorbis_info_mapping0 *vi,
  110443. float **mdct);
  110444. extern void _vp_couple(int blobno,
  110445. vorbis_info_psy_global *g,
  110446. vorbis_look_psy *p,
  110447. vorbis_info_mapping0 *vi,
  110448. float **res,
  110449. float **mag_memo,
  110450. int **mag_sort,
  110451. int **ifloor,
  110452. int *nonzero,
  110453. int sliding_lowpass);
  110454. extern void _vp_noise_normalize(vorbis_look_psy *p,
  110455. float *in,float *out,int *sortedindex);
  110456. extern void _vp_noise_normalize_sort(vorbis_look_psy *p,
  110457. float *magnitudes,int *sortedindex);
  110458. extern int **_vp_quantize_couple_sort(vorbis_block *vb,
  110459. vorbis_look_psy *p,
  110460. vorbis_info_mapping0 *vi,
  110461. float **mags);
  110462. extern void hf_reduction(vorbis_info_psy_global *g,
  110463. vorbis_look_psy *p,
  110464. vorbis_info_mapping0 *vi,
  110465. float **mdct);
  110466. #endif
  110467. /*** End of inlined file: psy.h ***/
  110468. /*** Start of inlined file: bitrate.h ***/
  110469. #ifndef _V_BITRATE_H_
  110470. #define _V_BITRATE_H_
  110471. /*** Start of inlined file: os.h ***/
  110472. #ifndef _OS_H
  110473. #define _OS_H
  110474. /********************************************************************
  110475. * *
  110476. * THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. *
  110477. * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
  110478. * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
  110479. * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
  110480. * *
  110481. * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2002 *
  110482. * by the XIPHOPHORUS Company http://www.xiph.org/ *
  110483. * *
  110484. ********************************************************************
  110485. function: #ifdef jail to whip a few platforms into the UNIX ideal.
  110486. last mod: $Id: os.h,v 1.1 2007/06/07 17:49:18 jules_rms Exp $
  110487. ********************************************************************/
  110488. #ifdef HAVE_CONFIG_H
  110489. #include "config.h"
  110490. #endif
  110491. #include <math.h>
  110492. /*** Start of inlined file: misc.h ***/
  110493. #ifndef _V_RANDOM_H_
  110494. #define _V_RANDOM_H_
  110495. extern int analysis_noisy;
  110496. extern void *_vorbis_block_alloc(vorbis_block *vb,long bytes);
  110497. extern void _vorbis_block_ripcord(vorbis_block *vb);
  110498. extern void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  110499. ogg_int64_t off);
  110500. #ifdef DEBUG_MALLOC
  110501. #define _VDBG_GRAPHFILE "malloc.m"
  110502. extern void *_VDBG_malloc(void *ptr,long bytes,char *file,long line);
  110503. extern void _VDBG_free(void *ptr,char *file,long line);
  110504. #ifndef MISC_C
  110505. #undef _ogg_malloc
  110506. #undef _ogg_calloc
  110507. #undef _ogg_realloc
  110508. #undef _ogg_free
  110509. #define _ogg_malloc(x) _VDBG_malloc(NULL,(x),__FILE__,__LINE__)
  110510. #define _ogg_calloc(x,y) _VDBG_malloc(NULL,(x)*(y),__FILE__,__LINE__)
  110511. #define _ogg_realloc(x,y) _VDBG_malloc((x),(y),__FILE__,__LINE__)
  110512. #define _ogg_free(x) _VDBG_free((x),__FILE__,__LINE__)
  110513. #endif
  110514. #endif
  110515. #endif
  110516. /*** End of inlined file: misc.h ***/
  110517. #ifndef _V_IFDEFJAIL_H_
  110518. # define _V_IFDEFJAIL_H_
  110519. # ifdef __GNUC__
  110520. # define STIN static __inline__
  110521. # elif _WIN32
  110522. # define STIN static __inline
  110523. # else
  110524. # define STIN static
  110525. # endif
  110526. #ifdef DJGPP
  110527. # define rint(x) (floor((x)+0.5f))
  110528. #endif
  110529. #ifndef M_PI
  110530. # define M_PI (3.1415926536f)
  110531. #endif
  110532. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  110533. # include <malloc.h>
  110534. # define rint(x) (floor((x)+0.5f))
  110535. # define NO_FLOAT_MATH_LIB
  110536. # define FAST_HYPOT(a, b) sqrt((a)*(a) + (b)*(b))
  110537. #endif
  110538. #if defined(__SYMBIAN32__) && defined(__WINS__)
  110539. void *_alloca(size_t size);
  110540. # define alloca _alloca
  110541. #endif
  110542. #ifndef FAST_HYPOT
  110543. # define FAST_HYPOT hypot
  110544. #endif
  110545. #endif
  110546. #ifdef HAVE_ALLOCA_H
  110547. # include <alloca.h>
  110548. #endif
  110549. #ifdef USE_MEMORY_H
  110550. # include <memory.h>
  110551. #endif
  110552. #ifndef min
  110553. # define min(x,y) ((x)>(y)?(y):(x))
  110554. #endif
  110555. #ifndef max
  110556. # define max(x,y) ((x)<(y)?(y):(x))
  110557. #endif
  110558. #if defined(__i386__) && defined(__GNUC__) && !defined(__BEOS__)
  110559. # define VORBIS_FPU_CONTROL
  110560. /* both GCC and MSVC are kinda stupid about rounding/casting to int.
  110561. Because of encapsulation constraints (GCC can't see inside the asm
  110562. block and so we end up doing stupid things like a store/load that
  110563. is collectively a noop), we do it this way */
  110564. /* we must set up the fpu before this works!! */
  110565. typedef ogg_int16_t vorbis_fpu_control;
  110566. static inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  110567. ogg_int16_t ret;
  110568. ogg_int16_t temp;
  110569. __asm__ __volatile__("fnstcw %0\n\t"
  110570. "movw %0,%%dx\n\t"
  110571. "orw $62463,%%dx\n\t"
  110572. "movw %%dx,%1\n\t"
  110573. "fldcw %1\n\t":"=m"(ret):"m"(temp): "dx");
  110574. *fpu=ret;
  110575. }
  110576. static inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  110577. __asm__ __volatile__("fldcw %0":: "m"(fpu));
  110578. }
  110579. /* assumes the FPU is in round mode! */
  110580. static inline int vorbis_ftoi(double f){ /* yes, double! Otherwise,
  110581. we get extra fst/fld to
  110582. truncate precision */
  110583. int i;
  110584. __asm__("fistl %0": "=m"(i) : "t"(f));
  110585. return(i);
  110586. }
  110587. #endif
  110588. #if defined(_WIN32) && defined(_X86_) && !defined(__GNUC__) && !defined(__BORLANDC__)
  110589. # define VORBIS_FPU_CONTROL
  110590. typedef ogg_int16_t vorbis_fpu_control;
  110591. static __inline int vorbis_ftoi(double f){
  110592. int i;
  110593. __asm{
  110594. fld f
  110595. fistp i
  110596. }
  110597. return i;
  110598. }
  110599. static __inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  110600. }
  110601. static __inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  110602. }
  110603. #endif
  110604. #ifndef VORBIS_FPU_CONTROL
  110605. typedef int vorbis_fpu_control;
  110606. static int vorbis_ftoi(double f){
  110607. return (int)(f+.5);
  110608. }
  110609. /* We don't have special code for this compiler/arch, so do it the slow way */
  110610. # define vorbis_fpu_setround(vorbis_fpu_control) {}
  110611. # define vorbis_fpu_restore(vorbis_fpu_control) {}
  110612. #endif
  110613. #endif /* _OS_H */
  110614. /*** End of inlined file: os.h ***/
  110615. /* encode side bitrate tracking */
  110616. typedef struct bitrate_manager_state {
  110617. int managed;
  110618. long avg_reservoir;
  110619. long minmax_reservoir;
  110620. long avg_bitsper;
  110621. long min_bitsper;
  110622. long max_bitsper;
  110623. long short_per_long;
  110624. double avgfloat;
  110625. vorbis_block *vb;
  110626. int choice;
  110627. } bitrate_manager_state;
  110628. typedef struct bitrate_manager_info{
  110629. long avg_rate;
  110630. long min_rate;
  110631. long max_rate;
  110632. long reservoir_bits;
  110633. double reservoir_bias;
  110634. double slew_damp;
  110635. } bitrate_manager_info;
  110636. extern void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bs);
  110637. extern void vorbis_bitrate_clear(bitrate_manager_state *bs);
  110638. extern int vorbis_bitrate_managed(vorbis_block *vb);
  110639. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  110640. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd, ogg_packet *op);
  110641. #endif
  110642. /*** End of inlined file: bitrate.h ***/
  110643. static int ilog(unsigned int v){
  110644. int ret=0;
  110645. while(v){
  110646. ret++;
  110647. v>>=1;
  110648. }
  110649. return(ret);
  110650. }
  110651. static int ilog2(unsigned int v){
  110652. int ret=0;
  110653. if(v)--v;
  110654. while(v){
  110655. ret++;
  110656. v>>=1;
  110657. }
  110658. return(ret);
  110659. }
  110660. typedef struct private_state {
  110661. /* local lookup storage */
  110662. envelope_lookup *ve; /* envelope lookup */
  110663. int window[2];
  110664. vorbis_look_transform **transform[2]; /* block, type */
  110665. drft_lookup fft_look[2];
  110666. int modebits;
  110667. vorbis_look_floor **flr;
  110668. vorbis_look_residue **residue;
  110669. vorbis_look_psy *psy;
  110670. vorbis_look_psy_global *psy_g_look;
  110671. /* local storage, only used on the encoding side. This way the
  110672. application does not need to worry about freeing some packets'
  110673. memory and not others'; packet storage is always tracked.
  110674. Cleared next call to a _dsp_ function */
  110675. unsigned char *header;
  110676. unsigned char *header1;
  110677. unsigned char *header2;
  110678. bitrate_manager_state bms;
  110679. ogg_int64_t sample_count;
  110680. } private_state;
  110681. /* codec_setup_info contains all the setup information specific to the
  110682. specific compression/decompression mode in progress (eg,
  110683. psychoacoustic settings, channel setup, options, codebook
  110684. etc).
  110685. *********************************************************************/
  110686. /*** Start of inlined file: highlevel.h ***/
  110687. typedef struct highlevel_byblocktype {
  110688. double tone_mask_setting;
  110689. double tone_peaklimit_setting;
  110690. double noise_bias_setting;
  110691. double noise_compand_setting;
  110692. } highlevel_byblocktype;
  110693. typedef struct highlevel_encode_setup {
  110694. void *setup;
  110695. int set_in_stone;
  110696. double base_setting;
  110697. double long_setting;
  110698. double short_setting;
  110699. double impulse_noisetune;
  110700. int managed;
  110701. long bitrate_min;
  110702. long bitrate_av;
  110703. double bitrate_av_damp;
  110704. long bitrate_max;
  110705. long bitrate_reservoir;
  110706. double bitrate_reservoir_bias;
  110707. int impulse_block_p;
  110708. int noise_normalize_p;
  110709. double stereo_point_setting;
  110710. double lowpass_kHz;
  110711. double ath_floating_dB;
  110712. double ath_absolute_dB;
  110713. double amplitude_track_dBpersec;
  110714. double trigger_setting;
  110715. highlevel_byblocktype block[4]; /* padding, impulse, transition, long */
  110716. } highlevel_encode_setup;
  110717. /*** End of inlined file: highlevel.h ***/
  110718. typedef struct codec_setup_info {
  110719. /* Vorbis supports only short and long blocks, but allows the
  110720. encoder to choose the sizes */
  110721. long blocksizes[2];
  110722. /* modes are the primary means of supporting on-the-fly different
  110723. blocksizes, different channel mappings (LR or M/A),
  110724. different residue backends, etc. Each mode consists of a
  110725. blocksize flag and a mapping (along with the mapping setup */
  110726. int modes;
  110727. int maps;
  110728. int floors;
  110729. int residues;
  110730. int books;
  110731. int psys; /* encode only */
  110732. vorbis_info_mode *mode_param[64];
  110733. int map_type[64];
  110734. vorbis_info_mapping *map_param[64];
  110735. int floor_type[64];
  110736. vorbis_info_floor *floor_param[64];
  110737. int residue_type[64];
  110738. vorbis_info_residue *residue_param[64];
  110739. static_codebook *book_param[256];
  110740. codebook *fullbooks;
  110741. vorbis_info_psy *psy_param[4]; /* encode only */
  110742. vorbis_info_psy_global psy_g_param;
  110743. bitrate_manager_info bi;
  110744. highlevel_encode_setup hi; /* used only by vorbisenc.c. It's a
  110745. highly redundant structure, but
  110746. improves clarity of program flow. */
  110747. int halfrate_flag; /* painless downsample for decode */
  110748. } codec_setup_info;
  110749. extern vorbis_look_psy_global *_vp_global_look(vorbis_info *vi);
  110750. extern void _vp_global_free(vorbis_look_psy_global *look);
  110751. #endif
  110752. /*** End of inlined file: codec_internal.h ***/
  110753. /*** Start of inlined file: registry.h ***/
  110754. #ifndef _V_REG_H_
  110755. #define _V_REG_H_
  110756. #define VI_TRANSFORMB 1
  110757. #define VI_WINDOWB 1
  110758. #define VI_TIMEB 1
  110759. #define VI_FLOORB 2
  110760. #define VI_RESB 3
  110761. #define VI_MAPB 1
  110762. extern vorbis_func_floor *_floor_P[];
  110763. extern vorbis_func_residue *_residue_P[];
  110764. extern vorbis_func_mapping *_mapping_P[];
  110765. #endif
  110766. /*** End of inlined file: registry.h ***/
  110767. /*** Start of inlined file: scales.h ***/
  110768. #ifndef _V_SCALES_H_
  110769. #define _V_SCALES_H_
  110770. #include <math.h>
  110771. /* 20log10(x) */
  110772. #define VORBIS_IEEE_FLOAT32 1
  110773. #ifdef VORBIS_IEEE_FLOAT32
  110774. static float unitnorm(float x){
  110775. union {
  110776. ogg_uint32_t i;
  110777. float f;
  110778. } ix;
  110779. ix.f = x;
  110780. ix.i = (ix.i & 0x80000000U) | (0x3f800000U);
  110781. return ix.f;
  110782. }
  110783. /* Segher was off (too high) by ~ .3 decibel. Center the conversion correctly. */
  110784. static float todB(const float *x){
  110785. union {
  110786. ogg_uint32_t i;
  110787. float f;
  110788. } ix;
  110789. ix.f = *x;
  110790. ix.i = ix.i&0x7fffffff;
  110791. return (float)(ix.i * 7.17711438e-7f -764.6161886f);
  110792. }
  110793. #define todB_nn(x) todB(x)
  110794. #else
  110795. static float unitnorm(float x){
  110796. if(x<0)return(-1.f);
  110797. return(1.f);
  110798. }
  110799. #define todB(x) (*(x)==0?-400.f:log(*(x)**(x))*4.34294480f)
  110800. #define todB_nn(x) (*(x)==0.f?-400.f:log(*(x))*8.6858896f)
  110801. #endif
  110802. #define fromdB(x) (exp((x)*.11512925f))
  110803. /* The bark scale equations are approximations, since the original
  110804. table was somewhat hand rolled. The below are chosen to have the
  110805. best possible fit to the rolled tables, thus their somewhat odd
  110806. appearance (these are more accurate and over a longer range than
  110807. the oft-quoted bark equations found in the texts I have). The
  110808. approximations are valid from 0 - 30kHz (nyquist) or so.
  110809. all f in Hz, z in Bark */
  110810. #define toBARK(n) (13.1f*atan(.00074f*(n))+2.24f*atan((n)*(n)*1.85e-8f)+1e-4f*(n))
  110811. #define fromBARK(z) (102.f*(z)-2.f*pow(z,2.f)+.4f*pow(z,3.f)+pow(1.46f,z)-1.f)
  110812. #define toMEL(n) (log(1.f+(n)*.001f)*1442.695f)
  110813. #define fromMEL(m) (1000.f*exp((m)/1442.695f)-1000.f)
  110814. /* Frequency to octave. We arbitrarily declare 63.5 Hz to be octave
  110815. 0.0 */
  110816. #define toOC(n) (log(n)*1.442695f-5.965784f)
  110817. #define fromOC(o) (exp(((o)+5.965784f)*.693147f))
  110818. #endif
  110819. /*** End of inlined file: scales.h ***/
  110820. int analysis_noisy=1;
  110821. /* decides between modes, dispatches to the appropriate mapping. */
  110822. int vorbis_analysis(vorbis_block *vb, ogg_packet *op){
  110823. int ret,i;
  110824. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  110825. vb->glue_bits=0;
  110826. vb->time_bits=0;
  110827. vb->floor_bits=0;
  110828. vb->res_bits=0;
  110829. /* first things first. Make sure encode is ready */
  110830. for(i=0;i<PACKETBLOBS;i++)
  110831. oggpack_reset(vbi->packetblob[i]);
  110832. /* we only have one mapping type (0), and we let the mapping code
  110833. itself figure out what soft mode to use. This allows easier
  110834. bitrate management */
  110835. if((ret=_mapping_P[0]->forward(vb)))
  110836. return(ret);
  110837. if(op){
  110838. if(vorbis_bitrate_managed(vb))
  110839. /* The app is using a bitmanaged mode... but not using the
  110840. bitrate management interface. */
  110841. return(OV_EINVAL);
  110842. op->packet=oggpack_get_buffer(&vb->opb);
  110843. op->bytes=oggpack_bytes(&vb->opb);
  110844. op->b_o_s=0;
  110845. op->e_o_s=vb->eofflag;
  110846. op->granulepos=vb->granulepos;
  110847. op->packetno=vb->sequence; /* for sake of completeness */
  110848. }
  110849. return(0);
  110850. }
  110851. /* there was no great place to put this.... */
  110852. void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,ogg_int64_t off){
  110853. int j;
  110854. FILE *of;
  110855. char buffer[80];
  110856. /* if(i==5870){*/
  110857. sprintf(buffer,"%s_%d.m",base,i);
  110858. of=fopen(buffer,"w");
  110859. if(!of)perror("failed to open data dump file");
  110860. for(j=0;j<n;j++){
  110861. if(bark){
  110862. float b=toBARK((4000.f*j/n)+.25);
  110863. fprintf(of,"%f ",b);
  110864. }else
  110865. if(off!=0)
  110866. fprintf(of,"%f ",(double)(j+off)/8000.);
  110867. else
  110868. fprintf(of,"%f ",(double)j);
  110869. if(dB){
  110870. float val;
  110871. if(v[j]==0.)
  110872. val=-140.;
  110873. else
  110874. val=todB(v+j);
  110875. fprintf(of,"%f\n",val);
  110876. }else{
  110877. fprintf(of,"%f\n",v[j]);
  110878. }
  110879. }
  110880. fclose(of);
  110881. /* } */
  110882. }
  110883. void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  110884. ogg_int64_t off){
  110885. if(analysis_noisy)_analysis_output_always(base,i,v,n,bark,dB,off);
  110886. }
  110887. #endif
  110888. /*** End of inlined file: analysis.c ***/
  110889. /*** Start of inlined file: bitrate.c ***/
  110890. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  110891. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110892. // tasks..
  110893. #if JUCE_MSVC
  110894. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110895. #endif
  110896. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  110897. #if JUCE_USE_OGGVORBIS
  110898. #include <stdlib.h>
  110899. #include <string.h>
  110900. #include <math.h>
  110901. /* compute bitrate tracking setup */
  110902. void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bm){
  110903. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  110904. bitrate_manager_info *bi=&ci->bi;
  110905. memset(bm,0,sizeof(*bm));
  110906. if(bi && (bi->reservoir_bits>0)){
  110907. long ratesamples=vi->rate;
  110908. int halfsamples=ci->blocksizes[0]>>1;
  110909. bm->short_per_long=ci->blocksizes[1]/ci->blocksizes[0];
  110910. bm->managed=1;
  110911. bm->avg_bitsper= rint(1.*bi->avg_rate*halfsamples/ratesamples);
  110912. bm->min_bitsper= rint(1.*bi->min_rate*halfsamples/ratesamples);
  110913. bm->max_bitsper= rint(1.*bi->max_rate*halfsamples/ratesamples);
  110914. bm->avgfloat=PACKETBLOBS/2;
  110915. /* not a necessary fix, but one that leads to a more balanced
  110916. typical initialization */
  110917. {
  110918. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  110919. bm->minmax_reservoir=desired_fill;
  110920. bm->avg_reservoir=desired_fill;
  110921. }
  110922. }
  110923. }
  110924. void vorbis_bitrate_clear(bitrate_manager_state *bm){
  110925. memset(bm,0,sizeof(*bm));
  110926. return;
  110927. }
  110928. int vorbis_bitrate_managed(vorbis_block *vb){
  110929. vorbis_dsp_state *vd=vb->vd;
  110930. private_state *b=(private_state*)vd->backend_state;
  110931. bitrate_manager_state *bm=&b->bms;
  110932. if(bm && bm->managed)return(1);
  110933. return(0);
  110934. }
  110935. /* finish taking in the block we just processed */
  110936. int vorbis_bitrate_addblock(vorbis_block *vb){
  110937. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  110938. vorbis_dsp_state *vd=vb->vd;
  110939. private_state *b=(private_state*)vd->backend_state;
  110940. bitrate_manager_state *bm=&b->bms;
  110941. vorbis_info *vi=vd->vi;
  110942. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110943. bitrate_manager_info *bi=&ci->bi;
  110944. int choice=rint(bm->avgfloat);
  110945. long this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110946. long min_target_bits=(vb->W?bm->min_bitsper*bm->short_per_long:bm->min_bitsper);
  110947. long max_target_bits=(vb->W?bm->max_bitsper*bm->short_per_long:bm->max_bitsper);
  110948. int samples=ci->blocksizes[vb->W]>>1;
  110949. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  110950. if(!bm->managed){
  110951. /* not a bitrate managed stream, but for API simplicity, we'll
  110952. buffer the packet to keep the code path clean */
  110953. if(bm->vb)return(-1); /* one has been submitted without
  110954. being claimed */
  110955. bm->vb=vb;
  110956. return(0);
  110957. }
  110958. bm->vb=vb;
  110959. /* look ahead for avg floater */
  110960. if(bm->avg_bitsper>0){
  110961. double slew=0.;
  110962. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  110963. double slewlimit= 15./bi->slew_damp;
  110964. /* choosing a new floater:
  110965. if we're over target, we slew down
  110966. if we're under target, we slew up
  110967. choose slew as follows: look through packetblobs of this frame
  110968. and set slew as the first in the appropriate direction that
  110969. gives us the slew we want. This may mean no slew if delta is
  110970. already favorable.
  110971. Then limit slew to slew max */
  110972. if(bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  110973. while(choice>0 && this_bits>avg_target_bits &&
  110974. bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  110975. choice--;
  110976. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110977. }
  110978. }else if(bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  110979. while(choice+1<PACKETBLOBS && this_bits<avg_target_bits &&
  110980. bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  110981. choice++;
  110982. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110983. }
  110984. }
  110985. slew=rint(choice-bm->avgfloat)/samples*vi->rate;
  110986. if(slew<-slewlimit)slew=-slewlimit;
  110987. if(slew>slewlimit)slew=slewlimit;
  110988. choice=rint(bm->avgfloat+= slew/vi->rate*samples);
  110989. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110990. }
  110991. /* enforce min(if used) on the current floater (if used) */
  110992. if(bm->min_bitsper>0){
  110993. /* do we need to force the bitrate up? */
  110994. if(this_bits<min_target_bits){
  110995. while(bm->minmax_reservoir-(min_target_bits-this_bits)<0){
  110996. choice++;
  110997. if(choice>=PACKETBLOBS)break;
  110998. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110999. }
  111000. }
  111001. }
  111002. /* enforce max (if used) on the current floater (if used) */
  111003. if(bm->max_bitsper>0){
  111004. /* do we need to force the bitrate down? */
  111005. if(this_bits>max_target_bits){
  111006. while(bm->minmax_reservoir+(this_bits-max_target_bits)>bi->reservoir_bits){
  111007. choice--;
  111008. if(choice<0)break;
  111009. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  111010. }
  111011. }
  111012. }
  111013. /* Choice of packetblobs now made based on floater, and min/max
  111014. requirements. Now boundary check extreme choices */
  111015. if(choice<0){
  111016. /* choosing a smaller packetblob is insufficient to trim bitrate.
  111017. frame will need to be truncated */
  111018. long maxsize=(max_target_bits+(bi->reservoir_bits-bm->minmax_reservoir))/8;
  111019. bm->choice=choice=0;
  111020. if(oggpack_bytes(vbi->packetblob[choice])>maxsize){
  111021. oggpack_writetrunc(vbi->packetblob[choice],maxsize*8);
  111022. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  111023. }
  111024. }else{
  111025. long minsize=(min_target_bits-bm->minmax_reservoir+7)/8;
  111026. if(choice>=PACKETBLOBS)
  111027. choice=PACKETBLOBS-1;
  111028. bm->choice=choice;
  111029. /* prop up bitrate according to demand. pad this frame out with zeroes */
  111030. minsize-=oggpack_bytes(vbi->packetblob[choice]);
  111031. while(minsize-->0)oggpack_write(vbi->packetblob[choice],0,8);
  111032. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  111033. }
  111034. /* now we have the final packet and the final packet size. Update statistics */
  111035. /* min and max reservoir */
  111036. if(bm->min_bitsper>0 || bm->max_bitsper>0){
  111037. if(max_target_bits>0 && this_bits>max_target_bits){
  111038. bm->minmax_reservoir+=(this_bits-max_target_bits);
  111039. }else if(min_target_bits>0 && this_bits<min_target_bits){
  111040. bm->minmax_reservoir+=(this_bits-min_target_bits);
  111041. }else{
  111042. /* inbetween; we want to take reservoir toward but not past desired_fill */
  111043. if(bm->minmax_reservoir>desired_fill){
  111044. if(max_target_bits>0){ /* logical bulletproofing against initialization state */
  111045. bm->minmax_reservoir+=(this_bits-max_target_bits);
  111046. if(bm->minmax_reservoir<desired_fill)bm->minmax_reservoir=desired_fill;
  111047. }else{
  111048. bm->minmax_reservoir=desired_fill;
  111049. }
  111050. }else{
  111051. if(min_target_bits>0){ /* logical bulletproofing against initialization state */
  111052. bm->minmax_reservoir+=(this_bits-min_target_bits);
  111053. if(bm->minmax_reservoir>desired_fill)bm->minmax_reservoir=desired_fill;
  111054. }else{
  111055. bm->minmax_reservoir=desired_fill;
  111056. }
  111057. }
  111058. }
  111059. }
  111060. /* avg reservoir */
  111061. if(bm->avg_bitsper>0){
  111062. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  111063. bm->avg_reservoir+=this_bits-avg_target_bits;
  111064. }
  111065. return(0);
  111066. }
  111067. int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,ogg_packet *op){
  111068. private_state *b=(private_state*)vd->backend_state;
  111069. bitrate_manager_state *bm=&b->bms;
  111070. vorbis_block *vb=bm->vb;
  111071. int choice=PACKETBLOBS/2;
  111072. if(!vb)return 0;
  111073. if(op){
  111074. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  111075. if(vorbis_bitrate_managed(vb))
  111076. choice=bm->choice;
  111077. op->packet=oggpack_get_buffer(vbi->packetblob[choice]);
  111078. op->bytes=oggpack_bytes(vbi->packetblob[choice]);
  111079. op->b_o_s=0;
  111080. op->e_o_s=vb->eofflag;
  111081. op->granulepos=vb->granulepos;
  111082. op->packetno=vb->sequence; /* for sake of completeness */
  111083. }
  111084. bm->vb=0;
  111085. return(1);
  111086. }
  111087. #endif
  111088. /*** End of inlined file: bitrate.c ***/
  111089. /*** Start of inlined file: block.c ***/
  111090. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  111091. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111092. // tasks..
  111093. #if JUCE_MSVC
  111094. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111095. #endif
  111096. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  111097. #if JUCE_USE_OGGVORBIS
  111098. #include <stdio.h>
  111099. #include <stdlib.h>
  111100. #include <string.h>
  111101. /*** Start of inlined file: window.h ***/
  111102. #ifndef _V_WINDOW_
  111103. #define _V_WINDOW_
  111104. extern float *_vorbis_window_get(int n);
  111105. extern void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  111106. int lW,int W,int nW);
  111107. #endif
  111108. /*** End of inlined file: window.h ***/
  111109. /*** Start of inlined file: lpc.h ***/
  111110. #ifndef _V_LPC_H_
  111111. #define _V_LPC_H_
  111112. /* simple linear scale LPC code */
  111113. extern float vorbis_lpc_from_data(float *data,float *lpc,int n,int m);
  111114. extern void vorbis_lpc_predict(float *coeff,float *prime,int m,
  111115. float *data,long n);
  111116. #endif
  111117. /*** End of inlined file: lpc.h ***/
  111118. /* pcm accumulator examples (not exhaustive):
  111119. <-------------- lW ---------------->
  111120. <--------------- W ---------------->
  111121. : .....|..... _______________ |
  111122. : .''' | '''_--- | |\ |
  111123. :.....''' |_____--- '''......| | \_______|
  111124. :.................|__________________|_______|__|______|
  111125. |<------ Sl ------>| > Sr < |endW
  111126. |beginSl |endSl | |endSr
  111127. |beginW |endlW |beginSr
  111128. |< lW >|
  111129. <--------------- W ---------------->
  111130. | | .. ______________ |
  111131. | | ' `/ | ---_ |
  111132. |___.'___/`. | ---_____|
  111133. |_______|__|_______|_________________|
  111134. | >|Sl|< |<------ Sr ----->|endW
  111135. | | |endSl |beginSr |endSr
  111136. |beginW | |endlW
  111137. mult[0] |beginSl mult[n]
  111138. <-------------- lW ----------------->
  111139. |<--W-->|
  111140. : .............. ___ | |
  111141. : .''' |`/ \ | |
  111142. :.....''' |/`....\|...|
  111143. :.........................|___|___|___|
  111144. |Sl |Sr |endW
  111145. | | |endSr
  111146. | |beginSr
  111147. | |endSl
  111148. |beginSl
  111149. |beginW
  111150. */
  111151. /* block abstraction setup *********************************************/
  111152. #ifndef WORD_ALIGN
  111153. #define WORD_ALIGN 8
  111154. #endif
  111155. int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb){
  111156. int i;
  111157. memset(vb,0,sizeof(*vb));
  111158. vb->vd=v;
  111159. vb->localalloc=0;
  111160. vb->localstore=NULL;
  111161. if(v->analysisp){
  111162. vorbis_block_internal *vbi=(vorbis_block_internal*)
  111163. (vb->internal=(vorbis_block_internal*)_ogg_calloc(1,sizeof(vorbis_block_internal)));
  111164. vbi->ampmax=-9999;
  111165. for(i=0;i<PACKETBLOBS;i++){
  111166. if(i==PACKETBLOBS/2){
  111167. vbi->packetblob[i]=&vb->opb;
  111168. }else{
  111169. vbi->packetblob[i]=
  111170. (oggpack_buffer*) _ogg_calloc(1,sizeof(oggpack_buffer));
  111171. }
  111172. oggpack_writeinit(vbi->packetblob[i]);
  111173. }
  111174. }
  111175. return(0);
  111176. }
  111177. void *_vorbis_block_alloc(vorbis_block *vb,long bytes){
  111178. bytes=(bytes+(WORD_ALIGN-1)) & ~(WORD_ALIGN-1);
  111179. if(bytes+vb->localtop>vb->localalloc){
  111180. /* can't just _ogg_realloc... there are outstanding pointers */
  111181. if(vb->localstore){
  111182. struct alloc_chain *link=(struct alloc_chain*)_ogg_malloc(sizeof(*link));
  111183. vb->totaluse+=vb->localtop;
  111184. link->next=vb->reap;
  111185. link->ptr=vb->localstore;
  111186. vb->reap=link;
  111187. }
  111188. /* highly conservative */
  111189. vb->localalloc=bytes;
  111190. vb->localstore=_ogg_malloc(vb->localalloc);
  111191. vb->localtop=0;
  111192. }
  111193. {
  111194. void *ret=(void *)(((char *)vb->localstore)+vb->localtop);
  111195. vb->localtop+=bytes;
  111196. return ret;
  111197. }
  111198. }
  111199. /* reap the chain, pull the ripcord */
  111200. void _vorbis_block_ripcord(vorbis_block *vb){
  111201. /* reap the chain */
  111202. struct alloc_chain *reap=vb->reap;
  111203. while(reap){
  111204. struct alloc_chain *next=reap->next;
  111205. _ogg_free(reap->ptr);
  111206. memset(reap,0,sizeof(*reap));
  111207. _ogg_free(reap);
  111208. reap=next;
  111209. }
  111210. /* consolidate storage */
  111211. if(vb->totaluse){
  111212. vb->localstore=_ogg_realloc(vb->localstore,vb->totaluse+vb->localalloc);
  111213. vb->localalloc+=vb->totaluse;
  111214. vb->totaluse=0;
  111215. }
  111216. /* pull the ripcord */
  111217. vb->localtop=0;
  111218. vb->reap=NULL;
  111219. }
  111220. int vorbis_block_clear(vorbis_block *vb){
  111221. int i;
  111222. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  111223. _vorbis_block_ripcord(vb);
  111224. if(vb->localstore)_ogg_free(vb->localstore);
  111225. if(vbi){
  111226. for(i=0;i<PACKETBLOBS;i++){
  111227. oggpack_writeclear(vbi->packetblob[i]);
  111228. if(i!=PACKETBLOBS/2)_ogg_free(vbi->packetblob[i]);
  111229. }
  111230. _ogg_free(vbi);
  111231. }
  111232. memset(vb,0,sizeof(*vb));
  111233. return(0);
  111234. }
  111235. /* Analysis side code, but directly related to blocking. Thus it's
  111236. here and not in analysis.c (which is for analysis transforms only).
  111237. The init is here because some of it is shared */
  111238. static int _vds_shared_init(vorbis_dsp_state *v,vorbis_info *vi,int encp){
  111239. int i;
  111240. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111241. private_state *b=NULL;
  111242. int hs;
  111243. if(ci==NULL) return 1;
  111244. hs=ci->halfrate_flag;
  111245. memset(v,0,sizeof(*v));
  111246. b=(private_state*) (v->backend_state=(private_state*)_ogg_calloc(1,sizeof(*b)));
  111247. v->vi=vi;
  111248. b->modebits=ilog2(ci->modes);
  111249. b->transform[0]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[0]));
  111250. b->transform[1]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[1]));
  111251. /* MDCT is tranform 0 */
  111252. b->transform[0][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  111253. b->transform[1][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  111254. mdct_init((mdct_lookup*)b->transform[0][0],ci->blocksizes[0]>>hs);
  111255. mdct_init((mdct_lookup*)b->transform[1][0],ci->blocksizes[1]>>hs);
  111256. /* Vorbis I uses only window type 0 */
  111257. b->window[0]=ilog2(ci->blocksizes[0])-6;
  111258. b->window[1]=ilog2(ci->blocksizes[1])-6;
  111259. if(encp){ /* encode/decode differ here */
  111260. /* analysis always needs an fft */
  111261. drft_init(&b->fft_look[0],ci->blocksizes[0]);
  111262. drft_init(&b->fft_look[1],ci->blocksizes[1]);
  111263. /* finish the codebooks */
  111264. if(!ci->fullbooks){
  111265. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  111266. for(i=0;i<ci->books;i++)
  111267. vorbis_book_init_encode(ci->fullbooks+i,ci->book_param[i]);
  111268. }
  111269. b->psy=(vorbis_look_psy*)_ogg_calloc(ci->psys,sizeof(*b->psy));
  111270. for(i=0;i<ci->psys;i++){
  111271. _vp_psy_init(b->psy+i,
  111272. ci->psy_param[i],
  111273. &ci->psy_g_param,
  111274. ci->blocksizes[ci->psy_param[i]->blockflag]/2,
  111275. vi->rate);
  111276. }
  111277. v->analysisp=1;
  111278. }else{
  111279. /* finish the codebooks */
  111280. if(!ci->fullbooks){
  111281. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  111282. for(i=0;i<ci->books;i++){
  111283. vorbis_book_init_decode(ci->fullbooks+i,ci->book_param[i]);
  111284. /* decode codebooks are now standalone after init */
  111285. vorbis_staticbook_destroy(ci->book_param[i]);
  111286. ci->book_param[i]=NULL;
  111287. }
  111288. }
  111289. }
  111290. /* initialize the storage vectors. blocksize[1] is small for encode,
  111291. but the correct size for decode */
  111292. v->pcm_storage=ci->blocksizes[1];
  111293. v->pcm=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcm));
  111294. v->pcmret=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcmret));
  111295. {
  111296. int i;
  111297. for(i=0;i<vi->channels;i++)
  111298. v->pcm[i]=(float*)_ogg_calloc(v->pcm_storage,sizeof(*v->pcm[i]));
  111299. }
  111300. /* all 1 (large block) or 0 (small block) */
  111301. /* explicitly set for the sake of clarity */
  111302. v->lW=0; /* previous window size */
  111303. v->W=0; /* current window size */
  111304. /* all vector indexes */
  111305. v->centerW=ci->blocksizes[1]/2;
  111306. v->pcm_current=v->centerW;
  111307. /* initialize all the backend lookups */
  111308. b->flr=(vorbis_look_floor**)_ogg_calloc(ci->floors,sizeof(*b->flr));
  111309. b->residue=(vorbis_look_residue**)_ogg_calloc(ci->residues,sizeof(*b->residue));
  111310. for(i=0;i<ci->floors;i++)
  111311. b->flr[i]=_floor_P[ci->floor_type[i]]->
  111312. look(v,ci->floor_param[i]);
  111313. for(i=0;i<ci->residues;i++)
  111314. b->residue[i]=_residue_P[ci->residue_type[i]]->
  111315. look(v,ci->residue_param[i]);
  111316. return 0;
  111317. }
  111318. /* arbitrary settings and spec-mandated numbers get filled in here */
  111319. int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi){
  111320. private_state *b=NULL;
  111321. if(_vds_shared_init(v,vi,1))return 1;
  111322. b=(private_state*)v->backend_state;
  111323. b->psy_g_look=_vp_global_look(vi);
  111324. /* Initialize the envelope state storage */
  111325. b->ve=(envelope_lookup*)_ogg_calloc(1,sizeof(*b->ve));
  111326. _ve_envelope_init(b->ve,vi);
  111327. vorbis_bitrate_init(vi,&b->bms);
  111328. /* compressed audio packets start after the headers
  111329. with sequence number 3 */
  111330. v->sequence=3;
  111331. return(0);
  111332. }
  111333. void vorbis_dsp_clear(vorbis_dsp_state *v){
  111334. int i;
  111335. if(v){
  111336. vorbis_info *vi=v->vi;
  111337. codec_setup_info *ci=(codec_setup_info*)(vi?vi->codec_setup:NULL);
  111338. private_state *b=(private_state*)v->backend_state;
  111339. if(b){
  111340. if(b->ve){
  111341. _ve_envelope_clear(b->ve);
  111342. _ogg_free(b->ve);
  111343. }
  111344. if(b->transform[0]){
  111345. mdct_clear((mdct_lookup*) b->transform[0][0]);
  111346. _ogg_free(b->transform[0][0]);
  111347. _ogg_free(b->transform[0]);
  111348. }
  111349. if(b->transform[1]){
  111350. mdct_clear((mdct_lookup*) b->transform[1][0]);
  111351. _ogg_free(b->transform[1][0]);
  111352. _ogg_free(b->transform[1]);
  111353. }
  111354. if(b->flr){
  111355. for(i=0;i<ci->floors;i++)
  111356. _floor_P[ci->floor_type[i]]->
  111357. free_look(b->flr[i]);
  111358. _ogg_free(b->flr);
  111359. }
  111360. if(b->residue){
  111361. for(i=0;i<ci->residues;i++)
  111362. _residue_P[ci->residue_type[i]]->
  111363. free_look(b->residue[i]);
  111364. _ogg_free(b->residue);
  111365. }
  111366. if(b->psy){
  111367. for(i=0;i<ci->psys;i++)
  111368. _vp_psy_clear(b->psy+i);
  111369. _ogg_free(b->psy);
  111370. }
  111371. if(b->psy_g_look)_vp_global_free(b->psy_g_look);
  111372. vorbis_bitrate_clear(&b->bms);
  111373. drft_clear(&b->fft_look[0]);
  111374. drft_clear(&b->fft_look[1]);
  111375. }
  111376. if(v->pcm){
  111377. for(i=0;i<vi->channels;i++)
  111378. if(v->pcm[i])_ogg_free(v->pcm[i]);
  111379. _ogg_free(v->pcm);
  111380. if(v->pcmret)_ogg_free(v->pcmret);
  111381. }
  111382. if(b){
  111383. /* free header, header1, header2 */
  111384. if(b->header)_ogg_free(b->header);
  111385. if(b->header1)_ogg_free(b->header1);
  111386. if(b->header2)_ogg_free(b->header2);
  111387. _ogg_free(b);
  111388. }
  111389. memset(v,0,sizeof(*v));
  111390. }
  111391. }
  111392. float **vorbis_analysis_buffer(vorbis_dsp_state *v, int vals){
  111393. int i;
  111394. vorbis_info *vi=v->vi;
  111395. private_state *b=(private_state*)v->backend_state;
  111396. /* free header, header1, header2 */
  111397. if(b->header)_ogg_free(b->header);b->header=NULL;
  111398. if(b->header1)_ogg_free(b->header1);b->header1=NULL;
  111399. if(b->header2)_ogg_free(b->header2);b->header2=NULL;
  111400. /* Do we have enough storage space for the requested buffer? If not,
  111401. expand the PCM (and envelope) storage */
  111402. if(v->pcm_current+vals>=v->pcm_storage){
  111403. v->pcm_storage=v->pcm_current+vals*2;
  111404. for(i=0;i<vi->channels;i++){
  111405. v->pcm[i]=(float*)_ogg_realloc(v->pcm[i],v->pcm_storage*sizeof(*v->pcm[i]));
  111406. }
  111407. }
  111408. for(i=0;i<vi->channels;i++)
  111409. v->pcmret[i]=v->pcm[i]+v->pcm_current;
  111410. return(v->pcmret);
  111411. }
  111412. static void _preextrapolate_helper(vorbis_dsp_state *v){
  111413. int i;
  111414. int order=32;
  111415. float *lpc=(float*)alloca(order*sizeof(*lpc));
  111416. float *work=(float*)alloca(v->pcm_current*sizeof(*work));
  111417. long j;
  111418. v->preextrapolate=1;
  111419. if(v->pcm_current-v->centerW>order*2){ /* safety */
  111420. for(i=0;i<v->vi->channels;i++){
  111421. /* need to run the extrapolation in reverse! */
  111422. for(j=0;j<v->pcm_current;j++)
  111423. work[j]=v->pcm[i][v->pcm_current-j-1];
  111424. /* prime as above */
  111425. vorbis_lpc_from_data(work,lpc,v->pcm_current-v->centerW,order);
  111426. /* run the predictor filter */
  111427. vorbis_lpc_predict(lpc,work+v->pcm_current-v->centerW-order,
  111428. order,
  111429. work+v->pcm_current-v->centerW,
  111430. v->centerW);
  111431. for(j=0;j<v->pcm_current;j++)
  111432. v->pcm[i][v->pcm_current-j-1]=work[j];
  111433. }
  111434. }
  111435. }
  111436. /* call with val<=0 to set eof */
  111437. int vorbis_analysis_wrote(vorbis_dsp_state *v, int vals){
  111438. vorbis_info *vi=v->vi;
  111439. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111440. if(vals<=0){
  111441. int order=32;
  111442. int i;
  111443. float *lpc=(float*) alloca(order*sizeof(*lpc));
  111444. /* if it wasn't done earlier (very short sample) */
  111445. if(!v->preextrapolate)
  111446. _preextrapolate_helper(v);
  111447. /* We're encoding the end of the stream. Just make sure we have
  111448. [at least] a few full blocks of zeroes at the end. */
  111449. /* actually, we don't want zeroes; that could drop a large
  111450. amplitude off a cliff, creating spread spectrum noise that will
  111451. suck to encode. Extrapolate for the sake of cleanliness. */
  111452. vorbis_analysis_buffer(v,ci->blocksizes[1]*3);
  111453. v->eofflag=v->pcm_current;
  111454. v->pcm_current+=ci->blocksizes[1]*3;
  111455. for(i=0;i<vi->channels;i++){
  111456. if(v->eofflag>order*2){
  111457. /* extrapolate with LPC to fill in */
  111458. long n;
  111459. /* make a predictor filter */
  111460. n=v->eofflag;
  111461. if(n>ci->blocksizes[1])n=ci->blocksizes[1];
  111462. vorbis_lpc_from_data(v->pcm[i]+v->eofflag-n,lpc,n,order);
  111463. /* run the predictor filter */
  111464. vorbis_lpc_predict(lpc,v->pcm[i]+v->eofflag-order,order,
  111465. v->pcm[i]+v->eofflag,v->pcm_current-v->eofflag);
  111466. }else{
  111467. /* not enough data to extrapolate (unlikely to happen due to
  111468. guarding the overlap, but bulletproof in case that
  111469. assumtion goes away). zeroes will do. */
  111470. memset(v->pcm[i]+v->eofflag,0,
  111471. (v->pcm_current-v->eofflag)*sizeof(*v->pcm[i]));
  111472. }
  111473. }
  111474. }else{
  111475. if(v->pcm_current+vals>v->pcm_storage)
  111476. return(OV_EINVAL);
  111477. v->pcm_current+=vals;
  111478. /* we may want to reverse extrapolate the beginning of a stream
  111479. too... in case we're beginning on a cliff! */
  111480. /* clumsy, but simple. It only runs once, so simple is good. */
  111481. if(!v->preextrapolate && v->pcm_current-v->centerW>ci->blocksizes[1])
  111482. _preextrapolate_helper(v);
  111483. }
  111484. return(0);
  111485. }
  111486. /* do the deltas, envelope shaping, pre-echo and determine the size of
  111487. the next block on which to continue analysis */
  111488. int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb){
  111489. int i;
  111490. vorbis_info *vi=v->vi;
  111491. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111492. private_state *b=(private_state*)v->backend_state;
  111493. vorbis_look_psy_global *g=b->psy_g_look;
  111494. long beginW=v->centerW-ci->blocksizes[v->W]/2,centerNext;
  111495. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  111496. /* check to see if we're started... */
  111497. if(!v->preextrapolate)return(0);
  111498. /* check to see if we're done... */
  111499. if(v->eofflag==-1)return(0);
  111500. /* By our invariant, we have lW, W and centerW set. Search for
  111501. the next boundary so we can determine nW (the next window size)
  111502. which lets us compute the shape of the current block's window */
  111503. /* we do an envelope search even on a single blocksize; we may still
  111504. be throwing more bits at impulses, and envelope search handles
  111505. marking impulses too. */
  111506. {
  111507. long bp=_ve_envelope_search(v);
  111508. if(bp==-1){
  111509. if(v->eofflag==0)return(0); /* not enough data currently to search for a
  111510. full long block */
  111511. v->nW=0;
  111512. }else{
  111513. if(ci->blocksizes[0]==ci->blocksizes[1])
  111514. v->nW=0;
  111515. else
  111516. v->nW=bp;
  111517. }
  111518. }
  111519. centerNext=v->centerW+ci->blocksizes[v->W]/4+ci->blocksizes[v->nW]/4;
  111520. {
  111521. /* center of next block + next block maximum right side. */
  111522. long blockbound=centerNext+ci->blocksizes[v->nW]/2;
  111523. if(v->pcm_current<blockbound)return(0); /* not enough data yet;
  111524. although this check is
  111525. less strict that the
  111526. _ve_envelope_search,
  111527. the search is not run
  111528. if we only use one
  111529. block size */
  111530. }
  111531. /* fill in the block. Note that for a short window, lW and nW are *short*
  111532. regardless of actual settings in the stream */
  111533. _vorbis_block_ripcord(vb);
  111534. vb->lW=v->lW;
  111535. vb->W=v->W;
  111536. vb->nW=v->nW;
  111537. if(v->W){
  111538. if(!v->lW || !v->nW){
  111539. vbi->blocktype=BLOCKTYPE_TRANSITION;
  111540. /*fprintf(stderr,"-");*/
  111541. }else{
  111542. vbi->blocktype=BLOCKTYPE_LONG;
  111543. /*fprintf(stderr,"_");*/
  111544. }
  111545. }else{
  111546. if(_ve_envelope_mark(v)){
  111547. vbi->blocktype=BLOCKTYPE_IMPULSE;
  111548. /*fprintf(stderr,"|");*/
  111549. }else{
  111550. vbi->blocktype=BLOCKTYPE_PADDING;
  111551. /*fprintf(stderr,".");*/
  111552. }
  111553. }
  111554. vb->vd=v;
  111555. vb->sequence=v->sequence++;
  111556. vb->granulepos=v->granulepos;
  111557. vb->pcmend=ci->blocksizes[v->W];
  111558. /* copy the vectors; this uses the local storage in vb */
  111559. /* this tracks 'strongest peak' for later psychoacoustics */
  111560. /* moved to the global psy state; clean this mess up */
  111561. if(vbi->ampmax>g->ampmax)g->ampmax=vbi->ampmax;
  111562. g->ampmax=_vp_ampmax_decay(g->ampmax,v);
  111563. vbi->ampmax=g->ampmax;
  111564. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  111565. vbi->pcmdelay=(float**)_vorbis_block_alloc(vb,sizeof(*vbi->pcmdelay)*vi->channels);
  111566. for(i=0;i<vi->channels;i++){
  111567. vbi->pcmdelay[i]=
  111568. (float*) _vorbis_block_alloc(vb,(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  111569. memcpy(vbi->pcmdelay[i],v->pcm[i],(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  111570. vb->pcm[i]=vbi->pcmdelay[i]+beginW;
  111571. /* before we added the delay
  111572. vb->pcm[i]=_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  111573. memcpy(vb->pcm[i],v->pcm[i]+beginW,ci->blocksizes[v->W]*sizeof(*vb->pcm[i]));
  111574. */
  111575. }
  111576. /* handle eof detection: eof==0 means that we've not yet received EOF
  111577. eof>0 marks the last 'real' sample in pcm[]
  111578. eof<0 'no more to do'; doesn't get here */
  111579. if(v->eofflag){
  111580. if(v->centerW>=v->eofflag){
  111581. v->eofflag=-1;
  111582. vb->eofflag=1;
  111583. return(1);
  111584. }
  111585. }
  111586. /* advance storage vectors and clean up */
  111587. {
  111588. int new_centerNext=ci->blocksizes[1]/2;
  111589. int movementW=centerNext-new_centerNext;
  111590. if(movementW>0){
  111591. _ve_envelope_shift(b->ve,movementW);
  111592. v->pcm_current-=movementW;
  111593. for(i=0;i<vi->channels;i++)
  111594. memmove(v->pcm[i],v->pcm[i]+movementW,
  111595. v->pcm_current*sizeof(*v->pcm[i]));
  111596. v->lW=v->W;
  111597. v->W=v->nW;
  111598. v->centerW=new_centerNext;
  111599. if(v->eofflag){
  111600. v->eofflag-=movementW;
  111601. if(v->eofflag<=0)v->eofflag=-1;
  111602. /* do not add padding to end of stream! */
  111603. if(v->centerW>=v->eofflag){
  111604. v->granulepos+=movementW-(v->centerW-v->eofflag);
  111605. }else{
  111606. v->granulepos+=movementW;
  111607. }
  111608. }else{
  111609. v->granulepos+=movementW;
  111610. }
  111611. }
  111612. }
  111613. /* done */
  111614. return(1);
  111615. }
  111616. int vorbis_synthesis_restart(vorbis_dsp_state *v){
  111617. vorbis_info *vi=v->vi;
  111618. codec_setup_info *ci;
  111619. int hs;
  111620. if(!v->backend_state)return -1;
  111621. if(!vi)return -1;
  111622. ci=(codec_setup_info*) vi->codec_setup;
  111623. if(!ci)return -1;
  111624. hs=ci->halfrate_flag;
  111625. v->centerW=ci->blocksizes[1]>>(hs+1);
  111626. v->pcm_current=v->centerW>>hs;
  111627. v->pcm_returned=-1;
  111628. v->granulepos=-1;
  111629. v->sequence=-1;
  111630. v->eofflag=0;
  111631. ((private_state *)(v->backend_state))->sample_count=-1;
  111632. return(0);
  111633. }
  111634. int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi){
  111635. if(_vds_shared_init(v,vi,0)) return 1;
  111636. vorbis_synthesis_restart(v);
  111637. return 0;
  111638. }
  111639. /* Unlike in analysis, the window is only partially applied for each
  111640. block. The time domain envelope is not yet handled at the point of
  111641. calling (as it relies on the previous block). */
  111642. int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb){
  111643. vorbis_info *vi=v->vi;
  111644. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111645. private_state *b=(private_state*)v->backend_state;
  111646. int hs=ci->halfrate_flag;
  111647. int i,j;
  111648. if(!vb)return(OV_EINVAL);
  111649. if(v->pcm_current>v->pcm_returned && v->pcm_returned!=-1)return(OV_EINVAL);
  111650. v->lW=v->W;
  111651. v->W=vb->W;
  111652. v->nW=-1;
  111653. if((v->sequence==-1)||
  111654. (v->sequence+1 != vb->sequence)){
  111655. v->granulepos=-1; /* out of sequence; lose count */
  111656. b->sample_count=-1;
  111657. }
  111658. v->sequence=vb->sequence;
  111659. if(vb->pcm){ /* no pcm to process if vorbis_synthesis_trackonly
  111660. was called on block */
  111661. int n=ci->blocksizes[v->W]>>(hs+1);
  111662. int n0=ci->blocksizes[0]>>(hs+1);
  111663. int n1=ci->blocksizes[1]>>(hs+1);
  111664. int thisCenter;
  111665. int prevCenter;
  111666. v->glue_bits+=vb->glue_bits;
  111667. v->time_bits+=vb->time_bits;
  111668. v->floor_bits+=vb->floor_bits;
  111669. v->res_bits+=vb->res_bits;
  111670. if(v->centerW){
  111671. thisCenter=n1;
  111672. prevCenter=0;
  111673. }else{
  111674. thisCenter=0;
  111675. prevCenter=n1;
  111676. }
  111677. /* v->pcm is now used like a two-stage double buffer. We don't want
  111678. to have to constantly shift *or* adjust memory usage. Don't
  111679. accept a new block until the old is shifted out */
  111680. for(j=0;j<vi->channels;j++){
  111681. /* the overlap/add section */
  111682. if(v->lW){
  111683. if(v->W){
  111684. /* large/large */
  111685. float *w=_vorbis_window_get(b->window[1]-hs);
  111686. float *pcm=v->pcm[j]+prevCenter;
  111687. float *p=vb->pcm[j];
  111688. for(i=0;i<n1;i++)
  111689. pcm[i]=pcm[i]*w[n1-i-1] + p[i]*w[i];
  111690. }else{
  111691. /* large/small */
  111692. float *w=_vorbis_window_get(b->window[0]-hs);
  111693. float *pcm=v->pcm[j]+prevCenter+n1/2-n0/2;
  111694. float *p=vb->pcm[j];
  111695. for(i=0;i<n0;i++)
  111696. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111697. }
  111698. }else{
  111699. if(v->W){
  111700. /* small/large */
  111701. float *w=_vorbis_window_get(b->window[0]-hs);
  111702. float *pcm=v->pcm[j]+prevCenter;
  111703. float *p=vb->pcm[j]+n1/2-n0/2;
  111704. for(i=0;i<n0;i++)
  111705. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111706. for(;i<n1/2+n0/2;i++)
  111707. pcm[i]=p[i];
  111708. }else{
  111709. /* small/small */
  111710. float *w=_vorbis_window_get(b->window[0]-hs);
  111711. float *pcm=v->pcm[j]+prevCenter;
  111712. float *p=vb->pcm[j];
  111713. for(i=0;i<n0;i++)
  111714. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111715. }
  111716. }
  111717. /* the copy section */
  111718. {
  111719. float *pcm=v->pcm[j]+thisCenter;
  111720. float *p=vb->pcm[j]+n;
  111721. for(i=0;i<n;i++)
  111722. pcm[i]=p[i];
  111723. }
  111724. }
  111725. if(v->centerW)
  111726. v->centerW=0;
  111727. else
  111728. v->centerW=n1;
  111729. /* deal with initial packet state; we do this using the explicit
  111730. pcm_returned==-1 flag otherwise we're sensitive to first block
  111731. being short or long */
  111732. if(v->pcm_returned==-1){
  111733. v->pcm_returned=thisCenter;
  111734. v->pcm_current=thisCenter;
  111735. }else{
  111736. v->pcm_returned=prevCenter;
  111737. v->pcm_current=prevCenter+
  111738. ((ci->blocksizes[v->lW]/4+
  111739. ci->blocksizes[v->W]/4)>>hs);
  111740. }
  111741. }
  111742. /* track the frame number... This is for convenience, but also
  111743. making sure our last packet doesn't end with added padding. If
  111744. the last packet is partial, the number of samples we'll have to
  111745. return will be past the vb->granulepos.
  111746. This is not foolproof! It will be confused if we begin
  111747. decoding at the last page after a seek or hole. In that case,
  111748. we don't have a starting point to judge where the last frame
  111749. is. For this reason, vorbisfile will always try to make sure
  111750. it reads the last two marked pages in proper sequence */
  111751. if(b->sample_count==-1){
  111752. b->sample_count=0;
  111753. }else{
  111754. b->sample_count+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  111755. }
  111756. if(v->granulepos==-1){
  111757. if(vb->granulepos!=-1){ /* only set if we have a position to set to */
  111758. v->granulepos=vb->granulepos;
  111759. /* is this a short page? */
  111760. if(b->sample_count>v->granulepos){
  111761. /* corner case; if this is both the first and last audio page,
  111762. then spec says the end is cut, not beginning */
  111763. if(vb->eofflag){
  111764. /* trim the end */
  111765. /* no preceeding granulepos; assume we started at zero (we'd
  111766. have to in a short single-page stream) */
  111767. /* granulepos could be -1 due to a seek, but that would result
  111768. in a long count, not short count */
  111769. v->pcm_current-=(b->sample_count-v->granulepos)>>hs;
  111770. }else{
  111771. /* trim the beginning */
  111772. v->pcm_returned+=(b->sample_count-v->granulepos)>>hs;
  111773. if(v->pcm_returned>v->pcm_current)
  111774. v->pcm_returned=v->pcm_current;
  111775. }
  111776. }
  111777. }
  111778. }else{
  111779. v->granulepos+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  111780. if(vb->granulepos!=-1 && v->granulepos!=vb->granulepos){
  111781. if(v->granulepos>vb->granulepos){
  111782. long extra=v->granulepos-vb->granulepos;
  111783. if(extra)
  111784. if(vb->eofflag){
  111785. /* partial last frame. Strip the extra samples off */
  111786. v->pcm_current-=extra>>hs;
  111787. } /* else {Shouldn't happen *unless* the bitstream is out of
  111788. spec. Either way, believe the bitstream } */
  111789. } /* else {Shouldn't happen *unless* the bitstream is out of
  111790. spec. Either way, believe the bitstream } */
  111791. v->granulepos=vb->granulepos;
  111792. }
  111793. }
  111794. /* Update, cleanup */
  111795. if(vb->eofflag)v->eofflag=1;
  111796. return(0);
  111797. }
  111798. /* pcm==NULL indicates we just want the pending samples, no more */
  111799. int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm){
  111800. vorbis_info *vi=v->vi;
  111801. if(v->pcm_returned>-1 && v->pcm_returned<v->pcm_current){
  111802. if(pcm){
  111803. int i;
  111804. for(i=0;i<vi->channels;i++)
  111805. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  111806. *pcm=v->pcmret;
  111807. }
  111808. return(v->pcm_current-v->pcm_returned);
  111809. }
  111810. return(0);
  111811. }
  111812. int vorbis_synthesis_read(vorbis_dsp_state *v,int n){
  111813. if(n && v->pcm_returned+n>v->pcm_current)return(OV_EINVAL);
  111814. v->pcm_returned+=n;
  111815. return(0);
  111816. }
  111817. /* intended for use with a specific vorbisfile feature; we want access
  111818. to the [usually synthetic/postextrapolated] buffer and lapping at
  111819. the end of a decode cycle, specifically, a half-short-block worth.
  111820. This funtion works like pcmout above, except it will also expose
  111821. this implicit buffer data not normally decoded. */
  111822. int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm){
  111823. vorbis_info *vi=v->vi;
  111824. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  111825. int hs=ci->halfrate_flag;
  111826. int n=ci->blocksizes[v->W]>>(hs+1);
  111827. int n0=ci->blocksizes[0]>>(hs+1);
  111828. int n1=ci->blocksizes[1]>>(hs+1);
  111829. int i,j;
  111830. if(v->pcm_returned<0)return 0;
  111831. /* our returned data ends at pcm_returned; because the synthesis pcm
  111832. buffer is a two-fragment ring, that means our data block may be
  111833. fragmented by buffering, wrapping or a short block not filling
  111834. out a buffer. To simplify things, we unfragment if it's at all
  111835. possibly needed. Otherwise, we'd need to call lapout more than
  111836. once as well as hold additional dsp state. Opt for
  111837. simplicity. */
  111838. /* centerW was advanced by blockin; it would be the center of the
  111839. *next* block */
  111840. if(v->centerW==n1){
  111841. /* the data buffer wraps; swap the halves */
  111842. /* slow, sure, small */
  111843. for(j=0;j<vi->channels;j++){
  111844. float *p=v->pcm[j];
  111845. for(i=0;i<n1;i++){
  111846. float temp=p[i];
  111847. p[i]=p[i+n1];
  111848. p[i+n1]=temp;
  111849. }
  111850. }
  111851. v->pcm_current-=n1;
  111852. v->pcm_returned-=n1;
  111853. v->centerW=0;
  111854. }
  111855. /* solidify buffer into contiguous space */
  111856. if((v->lW^v->W)==1){
  111857. /* long/short or short/long */
  111858. for(j=0;j<vi->channels;j++){
  111859. float *s=v->pcm[j];
  111860. float *d=v->pcm[j]+(n1-n0)/2;
  111861. for(i=(n1+n0)/2-1;i>=0;--i)
  111862. d[i]=s[i];
  111863. }
  111864. v->pcm_returned+=(n1-n0)/2;
  111865. v->pcm_current+=(n1-n0)/2;
  111866. }else{
  111867. if(v->lW==0){
  111868. /* short/short */
  111869. for(j=0;j<vi->channels;j++){
  111870. float *s=v->pcm[j];
  111871. float *d=v->pcm[j]+n1-n0;
  111872. for(i=n0-1;i>=0;--i)
  111873. d[i]=s[i];
  111874. }
  111875. v->pcm_returned+=n1-n0;
  111876. v->pcm_current+=n1-n0;
  111877. }
  111878. }
  111879. if(pcm){
  111880. int i;
  111881. for(i=0;i<vi->channels;i++)
  111882. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  111883. *pcm=v->pcmret;
  111884. }
  111885. return(n1+n-v->pcm_returned);
  111886. }
  111887. float *vorbis_window(vorbis_dsp_state *v,int W){
  111888. vorbis_info *vi=v->vi;
  111889. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  111890. int hs=ci->halfrate_flag;
  111891. private_state *b=(private_state*)v->backend_state;
  111892. if(b->window[W]-1<0)return NULL;
  111893. return _vorbis_window_get(b->window[W]-hs);
  111894. }
  111895. #endif
  111896. /*** End of inlined file: block.c ***/
  111897. /*** Start of inlined file: codebook.c ***/
  111898. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  111899. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111900. // tasks..
  111901. #if JUCE_MSVC
  111902. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111903. #endif
  111904. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  111905. #if JUCE_USE_OGGVORBIS
  111906. #include <stdlib.h>
  111907. #include <string.h>
  111908. #include <math.h>
  111909. /* packs the given codebook into the bitstream **************************/
  111910. int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *opb){
  111911. long i,j;
  111912. int ordered=0;
  111913. /* first the basic parameters */
  111914. oggpack_write(opb,0x564342,24);
  111915. oggpack_write(opb,c->dim,16);
  111916. oggpack_write(opb,c->entries,24);
  111917. /* pack the codewords. There are two packings; length ordered and
  111918. length random. Decide between the two now. */
  111919. for(i=1;i<c->entries;i++)
  111920. if(c->lengthlist[i-1]==0 || c->lengthlist[i]<c->lengthlist[i-1])break;
  111921. if(i==c->entries)ordered=1;
  111922. if(ordered){
  111923. /* length ordered. We only need to say how many codewords of
  111924. each length. The actual codewords are generated
  111925. deterministically */
  111926. long count=0;
  111927. oggpack_write(opb,1,1); /* ordered */
  111928. oggpack_write(opb,c->lengthlist[0]-1,5); /* 1 to 32 */
  111929. for(i=1;i<c->entries;i++){
  111930. long thisx=c->lengthlist[i];
  111931. long last=c->lengthlist[i-1];
  111932. if(thisx>last){
  111933. for(j=last;j<thisx;j++){
  111934. oggpack_write(opb,i-count,_ilog(c->entries-count));
  111935. count=i;
  111936. }
  111937. }
  111938. }
  111939. oggpack_write(opb,i-count,_ilog(c->entries-count));
  111940. }else{
  111941. /* length random. Again, we don't code the codeword itself, just
  111942. the length. This time, though, we have to encode each length */
  111943. oggpack_write(opb,0,1); /* unordered */
  111944. /* algortihmic mapping has use for 'unused entries', which we tag
  111945. here. The algorithmic mapping happens as usual, but the unused
  111946. entry has no codeword. */
  111947. for(i=0;i<c->entries;i++)
  111948. if(c->lengthlist[i]==0)break;
  111949. if(i==c->entries){
  111950. oggpack_write(opb,0,1); /* no unused entries */
  111951. for(i=0;i<c->entries;i++)
  111952. oggpack_write(opb,c->lengthlist[i]-1,5);
  111953. }else{
  111954. oggpack_write(opb,1,1); /* we have unused entries; thus we tag */
  111955. for(i=0;i<c->entries;i++){
  111956. if(c->lengthlist[i]==0){
  111957. oggpack_write(opb,0,1);
  111958. }else{
  111959. oggpack_write(opb,1,1);
  111960. oggpack_write(opb,c->lengthlist[i]-1,5);
  111961. }
  111962. }
  111963. }
  111964. }
  111965. /* is the entry number the desired return value, or do we have a
  111966. mapping? If we have a mapping, what type? */
  111967. oggpack_write(opb,c->maptype,4);
  111968. switch(c->maptype){
  111969. case 0:
  111970. /* no mapping */
  111971. break;
  111972. case 1:case 2:
  111973. /* implicitly populated value mapping */
  111974. /* explicitly populated value mapping */
  111975. if(!c->quantlist){
  111976. /* no quantlist? error */
  111977. return(-1);
  111978. }
  111979. /* values that define the dequantization */
  111980. oggpack_write(opb,c->q_min,32);
  111981. oggpack_write(opb,c->q_delta,32);
  111982. oggpack_write(opb,c->q_quant-1,4);
  111983. oggpack_write(opb,c->q_sequencep,1);
  111984. {
  111985. int quantvals;
  111986. switch(c->maptype){
  111987. case 1:
  111988. /* a single column of (c->entries/c->dim) quantized values for
  111989. building a full value list algorithmically (square lattice) */
  111990. quantvals=_book_maptype1_quantvals(c);
  111991. break;
  111992. case 2:
  111993. /* every value (c->entries*c->dim total) specified explicitly */
  111994. quantvals=c->entries*c->dim;
  111995. break;
  111996. default: /* NOT_REACHABLE */
  111997. quantvals=-1;
  111998. }
  111999. /* quantized values */
  112000. for(i=0;i<quantvals;i++)
  112001. oggpack_write(opb,labs(c->quantlist[i]),c->q_quant);
  112002. }
  112003. break;
  112004. default:
  112005. /* error case; we don't have any other map types now */
  112006. return(-1);
  112007. }
  112008. return(0);
  112009. }
  112010. /* unpacks a codebook from the packet buffer into the codebook struct,
  112011. readies the codebook auxiliary structures for decode *************/
  112012. int vorbis_staticbook_unpack(oggpack_buffer *opb,static_codebook *s){
  112013. long i,j;
  112014. memset(s,0,sizeof(*s));
  112015. s->allocedp=1;
  112016. /* make sure alignment is correct */
  112017. if(oggpack_read(opb,24)!=0x564342)goto _eofout;
  112018. /* first the basic parameters */
  112019. s->dim=oggpack_read(opb,16);
  112020. s->entries=oggpack_read(opb,24);
  112021. if(s->entries==-1)goto _eofout;
  112022. /* codeword ordering.... length ordered or unordered? */
  112023. switch((int)oggpack_read(opb,1)){
  112024. case 0:
  112025. /* unordered */
  112026. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  112027. /* allocated but unused entries? */
  112028. if(oggpack_read(opb,1)){
  112029. /* yes, unused entries */
  112030. for(i=0;i<s->entries;i++){
  112031. if(oggpack_read(opb,1)){
  112032. long num=oggpack_read(opb,5);
  112033. if(num==-1)goto _eofout;
  112034. s->lengthlist[i]=num+1;
  112035. }else
  112036. s->lengthlist[i]=0;
  112037. }
  112038. }else{
  112039. /* all entries used; no tagging */
  112040. for(i=0;i<s->entries;i++){
  112041. long num=oggpack_read(opb,5);
  112042. if(num==-1)goto _eofout;
  112043. s->lengthlist[i]=num+1;
  112044. }
  112045. }
  112046. break;
  112047. case 1:
  112048. /* ordered */
  112049. {
  112050. long length=oggpack_read(opb,5)+1;
  112051. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  112052. for(i=0;i<s->entries;){
  112053. long num=oggpack_read(opb,_ilog(s->entries-i));
  112054. if(num==-1)goto _eofout;
  112055. for(j=0;j<num && i<s->entries;j++,i++)
  112056. s->lengthlist[i]=length;
  112057. length++;
  112058. }
  112059. }
  112060. break;
  112061. default:
  112062. /* EOF */
  112063. return(-1);
  112064. }
  112065. /* Do we have a mapping to unpack? */
  112066. switch((s->maptype=oggpack_read(opb,4))){
  112067. case 0:
  112068. /* no mapping */
  112069. break;
  112070. case 1: case 2:
  112071. /* implicitly populated value mapping */
  112072. /* explicitly populated value mapping */
  112073. s->q_min=oggpack_read(opb,32);
  112074. s->q_delta=oggpack_read(opb,32);
  112075. s->q_quant=oggpack_read(opb,4)+1;
  112076. s->q_sequencep=oggpack_read(opb,1);
  112077. {
  112078. int quantvals=0;
  112079. switch(s->maptype){
  112080. case 1:
  112081. quantvals=_book_maptype1_quantvals(s);
  112082. break;
  112083. case 2:
  112084. quantvals=s->entries*s->dim;
  112085. break;
  112086. }
  112087. /* quantized values */
  112088. s->quantlist=(long*)_ogg_malloc(sizeof(*s->quantlist)*quantvals);
  112089. for(i=0;i<quantvals;i++)
  112090. s->quantlist[i]=oggpack_read(opb,s->q_quant);
  112091. if(quantvals&&s->quantlist[quantvals-1]==-1)goto _eofout;
  112092. }
  112093. break;
  112094. default:
  112095. goto _errout;
  112096. }
  112097. /* all set */
  112098. return(0);
  112099. _errout:
  112100. _eofout:
  112101. vorbis_staticbook_clear(s);
  112102. return(-1);
  112103. }
  112104. /* returns the number of bits ************************************************/
  112105. int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b){
  112106. oggpack_write(b,book->codelist[a],book->c->lengthlist[a]);
  112107. return(book->c->lengthlist[a]);
  112108. }
  112109. /* One the encode side, our vector writers are each designed for a
  112110. specific purpose, and the encoder is not flexible without modification:
  112111. The LSP vector coder uses a single stage nearest-match with no
  112112. interleave, so no step and no error return. This is specced by floor0
  112113. and doesn't change.
  112114. Residue0 encoding interleaves, uses multiple stages, and each stage
  112115. peels of a specific amount of resolution from a lattice (thus we want
  112116. to match by threshold, not nearest match). Residue doesn't *have* to
  112117. be encoded that way, but to change it, one will need to add more
  112118. infrastructure on the encode side (decode side is specced and simpler) */
  112119. /* floor0 LSP (single stage, non interleaved, nearest match) */
  112120. /* returns entry number and *modifies a* to the quantization value *****/
  112121. int vorbis_book_errorv(codebook *book,float *a){
  112122. int dim=book->dim,k;
  112123. int best=_best(book,a,1);
  112124. for(k=0;k<dim;k++)
  112125. a[k]=(book->valuelist+best*dim)[k];
  112126. return(best);
  112127. }
  112128. /* returns the number of bits and *modifies a* to the quantization value *****/
  112129. int vorbis_book_encodev(codebook *book,int best,float *a,oggpack_buffer *b){
  112130. int k,dim=book->dim;
  112131. for(k=0;k<dim;k++)
  112132. a[k]=(book->valuelist+best*dim)[k];
  112133. return(vorbis_book_encode(book,best,b));
  112134. }
  112135. /* the 'eliminate the decode tree' optimization actually requires the
  112136. codewords to be MSb first, not LSb. This is an annoying inelegancy
  112137. (and one of the first places where carefully thought out design
  112138. turned out to be wrong; Vorbis II and future Ogg codecs should go
  112139. to an MSb bitpacker), but not actually the huge hit it appears to
  112140. be. The first-stage decode table catches most words so that
  112141. bitreverse is not in the main execution path. */
  112142. STIN long decode_packed_entry_number(codebook *book, oggpack_buffer *b){
  112143. int read=book->dec_maxlength;
  112144. long lo,hi;
  112145. long lok = oggpack_look(b,book->dec_firsttablen);
  112146. if (lok >= 0) {
  112147. long entry = book->dec_firsttable[lok];
  112148. if(entry&0x80000000UL){
  112149. lo=(entry>>15)&0x7fff;
  112150. hi=book->used_entries-(entry&0x7fff);
  112151. }else{
  112152. oggpack_adv(b, book->dec_codelengths[entry-1]);
  112153. return(entry-1);
  112154. }
  112155. }else{
  112156. lo=0;
  112157. hi=book->used_entries;
  112158. }
  112159. lok = oggpack_look(b, read);
  112160. while(lok<0 && read>1)
  112161. lok = oggpack_look(b, --read);
  112162. if(lok<0)return -1;
  112163. /* bisect search for the codeword in the ordered list */
  112164. {
  112165. ogg_uint32_t testword=ogg_bitreverse((ogg_uint32_t)lok);
  112166. while(hi-lo>1){
  112167. long p=(hi-lo)>>1;
  112168. long test=book->codelist[lo+p]>testword;
  112169. lo+=p&(test-1);
  112170. hi-=p&(-test);
  112171. }
  112172. if(book->dec_codelengths[lo]<=read){
  112173. oggpack_adv(b, book->dec_codelengths[lo]);
  112174. return(lo);
  112175. }
  112176. }
  112177. oggpack_adv(b, read);
  112178. return(-1);
  112179. }
  112180. /* Decode side is specced and easier, because we don't need to find
  112181. matches using different criteria; we simply read and map. There are
  112182. two things we need to do 'depending':
  112183. We may need to support interleave. We don't really, but it's
  112184. convenient to do it here rather than rebuild the vector later.
  112185. Cascades may be additive or multiplicitive; this is not inherent in
  112186. the codebook, but set in the code using the codebook. Like
  112187. interleaving, it's easiest to do it here.
  112188. addmul==0 -> declarative (set the value)
  112189. addmul==1 -> additive
  112190. addmul==2 -> multiplicitive */
  112191. /* returns the [original, not compacted] entry number or -1 on eof *********/
  112192. long vorbis_book_decode(codebook *book, oggpack_buffer *b){
  112193. long packed_entry=decode_packed_entry_number(book,b);
  112194. if(packed_entry>=0)
  112195. return(book->dec_index[packed_entry]);
  112196. /* if there's no dec_index, the codebook unpacking isn't collapsed */
  112197. return(packed_entry);
  112198. }
  112199. /* returns 0 on OK or -1 on eof *************************************/
  112200. long vorbis_book_decodevs_add(codebook *book,float *a,oggpack_buffer *b,int n){
  112201. int step=n/book->dim;
  112202. long *entry = (long*)alloca(sizeof(*entry)*step);
  112203. float **t = (float**)alloca(sizeof(*t)*step);
  112204. int i,j,o;
  112205. for (i = 0; i < step; i++) {
  112206. entry[i]=decode_packed_entry_number(book,b);
  112207. if(entry[i]==-1)return(-1);
  112208. t[i] = book->valuelist+entry[i]*book->dim;
  112209. }
  112210. for(i=0,o=0;i<book->dim;i++,o+=step)
  112211. for (j=0;j<step;j++)
  112212. a[o+j]+=t[j][i];
  112213. return(0);
  112214. }
  112215. long vorbis_book_decodev_add(codebook *book,float *a,oggpack_buffer *b,int n){
  112216. int i,j,entry;
  112217. float *t;
  112218. if(book->dim>8){
  112219. for(i=0;i<n;){
  112220. entry = decode_packed_entry_number(book,b);
  112221. if(entry==-1)return(-1);
  112222. t = book->valuelist+entry*book->dim;
  112223. for (j=0;j<book->dim;)
  112224. a[i++]+=t[j++];
  112225. }
  112226. }else{
  112227. for(i=0;i<n;){
  112228. entry = decode_packed_entry_number(book,b);
  112229. if(entry==-1)return(-1);
  112230. t = book->valuelist+entry*book->dim;
  112231. j=0;
  112232. switch((int)book->dim){
  112233. case 8:
  112234. a[i++]+=t[j++];
  112235. case 7:
  112236. a[i++]+=t[j++];
  112237. case 6:
  112238. a[i++]+=t[j++];
  112239. case 5:
  112240. a[i++]+=t[j++];
  112241. case 4:
  112242. a[i++]+=t[j++];
  112243. case 3:
  112244. a[i++]+=t[j++];
  112245. case 2:
  112246. a[i++]+=t[j++];
  112247. case 1:
  112248. a[i++]+=t[j++];
  112249. case 0:
  112250. break;
  112251. }
  112252. }
  112253. }
  112254. return(0);
  112255. }
  112256. long vorbis_book_decodev_set(codebook *book,float *a,oggpack_buffer *b,int n){
  112257. int i,j,entry;
  112258. float *t;
  112259. for(i=0;i<n;){
  112260. entry = decode_packed_entry_number(book,b);
  112261. if(entry==-1)return(-1);
  112262. t = book->valuelist+entry*book->dim;
  112263. for (j=0;j<book->dim;)
  112264. a[i++]=t[j++];
  112265. }
  112266. return(0);
  112267. }
  112268. long vorbis_book_decodevv_add(codebook *book,float **a,long offset,int ch,
  112269. oggpack_buffer *b,int n){
  112270. long i,j,entry;
  112271. int chptr=0;
  112272. for(i=offset/ch;i<(offset+n)/ch;){
  112273. entry = decode_packed_entry_number(book,b);
  112274. if(entry==-1)return(-1);
  112275. {
  112276. const float *t = book->valuelist+entry*book->dim;
  112277. for (j=0;j<book->dim;j++){
  112278. a[chptr++][i]+=t[j];
  112279. if(chptr==ch){
  112280. chptr=0;
  112281. i++;
  112282. }
  112283. }
  112284. }
  112285. }
  112286. return(0);
  112287. }
  112288. #ifdef _V_SELFTEST
  112289. /* Simple enough; pack a few candidate codebooks, unpack them. Code a
  112290. number of vectors through (keeping track of the quantized values),
  112291. and decode using the unpacked book. quantized version of in should
  112292. exactly equal out */
  112293. #include <stdio.h>
  112294. #include "vorbis/book/lsp20_0.vqh"
  112295. #include "vorbis/book/res0a_13.vqh"
  112296. #define TESTSIZE 40
  112297. float test1[TESTSIZE]={
  112298. 0.105939f,
  112299. 0.215373f,
  112300. 0.429117f,
  112301. 0.587974f,
  112302. 0.181173f,
  112303. 0.296583f,
  112304. 0.515707f,
  112305. 0.715261f,
  112306. 0.162327f,
  112307. 0.263834f,
  112308. 0.342876f,
  112309. 0.406025f,
  112310. 0.103571f,
  112311. 0.223561f,
  112312. 0.368513f,
  112313. 0.540313f,
  112314. 0.136672f,
  112315. 0.395882f,
  112316. 0.587183f,
  112317. 0.652476f,
  112318. 0.114338f,
  112319. 0.417300f,
  112320. 0.525486f,
  112321. 0.698679f,
  112322. 0.147492f,
  112323. 0.324481f,
  112324. 0.643089f,
  112325. 0.757582f,
  112326. 0.139556f,
  112327. 0.215795f,
  112328. 0.324559f,
  112329. 0.399387f,
  112330. 0.120236f,
  112331. 0.267420f,
  112332. 0.446940f,
  112333. 0.608760f,
  112334. 0.115587f,
  112335. 0.287234f,
  112336. 0.571081f,
  112337. 0.708603f,
  112338. };
  112339. float test3[TESTSIZE]={
  112340. 0,1,-2,3,4,-5,6,7,8,9,
  112341. 8,-2,7,-1,4,6,8,3,1,-9,
  112342. 10,11,12,13,14,15,26,17,18,19,
  112343. 30,-25,-30,-1,-5,-32,4,3,-2,0};
  112344. static_codebook *testlist[]={&_vq_book_lsp20_0,
  112345. &_vq_book_res0a_13,NULL};
  112346. float *testvec[]={test1,test3};
  112347. int main(){
  112348. oggpack_buffer write;
  112349. oggpack_buffer read;
  112350. long ptr=0,i;
  112351. oggpack_writeinit(&write);
  112352. fprintf(stderr,"Testing codebook abstraction...:\n");
  112353. while(testlist[ptr]){
  112354. codebook c;
  112355. static_codebook s;
  112356. float *qv=alloca(sizeof(*qv)*TESTSIZE);
  112357. float *iv=alloca(sizeof(*iv)*TESTSIZE);
  112358. memcpy(qv,testvec[ptr],sizeof(*qv)*TESTSIZE);
  112359. memset(iv,0,sizeof(*iv)*TESTSIZE);
  112360. fprintf(stderr,"\tpacking/coding %ld... ",ptr);
  112361. /* pack the codebook, write the testvector */
  112362. oggpack_reset(&write);
  112363. vorbis_book_init_encode(&c,testlist[ptr]); /* get it into memory
  112364. we can write */
  112365. vorbis_staticbook_pack(testlist[ptr],&write);
  112366. fprintf(stderr,"Codebook size %ld bytes... ",oggpack_bytes(&write));
  112367. for(i=0;i<TESTSIZE;i+=c.dim){
  112368. int best=_best(&c,qv+i,1);
  112369. vorbis_book_encodev(&c,best,qv+i,&write);
  112370. }
  112371. vorbis_book_clear(&c);
  112372. fprintf(stderr,"OK.\n");
  112373. fprintf(stderr,"\tunpacking/decoding %ld... ",ptr);
  112374. /* transfer the write data to a read buffer and unpack/read */
  112375. oggpack_readinit(&read,oggpack_get_buffer(&write),oggpack_bytes(&write));
  112376. if(vorbis_staticbook_unpack(&read,&s)){
  112377. fprintf(stderr,"Error unpacking codebook.\n");
  112378. exit(1);
  112379. }
  112380. if(vorbis_book_init_decode(&c,&s)){
  112381. fprintf(stderr,"Error initializing codebook.\n");
  112382. exit(1);
  112383. }
  112384. for(i=0;i<TESTSIZE;i+=c.dim)
  112385. if(vorbis_book_decodev_set(&c,iv+i,&read,c.dim)==-1){
  112386. fprintf(stderr,"Error reading codebook test data (EOP).\n");
  112387. exit(1);
  112388. }
  112389. for(i=0;i<TESTSIZE;i++)
  112390. if(fabs(qv[i]-iv[i])>.000001){
  112391. fprintf(stderr,"read (%g) != written (%g) at position (%ld)\n",
  112392. iv[i],qv[i],i);
  112393. exit(1);
  112394. }
  112395. fprintf(stderr,"OK\n");
  112396. ptr++;
  112397. }
  112398. /* The above is the trivial stuff; now try unquantizing a log scale codebook */
  112399. exit(0);
  112400. }
  112401. #endif
  112402. #endif
  112403. /*** End of inlined file: codebook.c ***/
  112404. /*** Start of inlined file: envelope.c ***/
  112405. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112406. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112407. // tasks..
  112408. #if JUCE_MSVC
  112409. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112410. #endif
  112411. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112412. #if JUCE_USE_OGGVORBIS
  112413. #include <stdlib.h>
  112414. #include <string.h>
  112415. #include <stdio.h>
  112416. #include <math.h>
  112417. void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi){
  112418. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112419. vorbis_info_psy_global *gi=&ci->psy_g_param;
  112420. int ch=vi->channels;
  112421. int i,j;
  112422. int n=e->winlength=128;
  112423. e->searchstep=64; /* not random */
  112424. e->minenergy=gi->preecho_minenergy;
  112425. e->ch=ch;
  112426. e->storage=128;
  112427. e->cursor=ci->blocksizes[1]/2;
  112428. e->mdct_win=(float*)_ogg_calloc(n,sizeof(*e->mdct_win));
  112429. mdct_init(&e->mdct,n);
  112430. for(i=0;i<n;i++){
  112431. e->mdct_win[i]=sin(i/(n-1.)*M_PI);
  112432. e->mdct_win[i]*=e->mdct_win[i];
  112433. }
  112434. /* magic follows */
  112435. e->band[0].begin=2; e->band[0].end=4;
  112436. e->band[1].begin=4; e->band[1].end=5;
  112437. e->band[2].begin=6; e->band[2].end=6;
  112438. e->band[3].begin=9; e->band[3].end=8;
  112439. e->band[4].begin=13; e->band[4].end=8;
  112440. e->band[5].begin=17; e->band[5].end=8;
  112441. e->band[6].begin=22; e->band[6].end=8;
  112442. for(j=0;j<VE_BANDS;j++){
  112443. n=e->band[j].end;
  112444. e->band[j].window=(float*)_ogg_malloc(n*sizeof(*e->band[0].window));
  112445. for(i=0;i<n;i++){
  112446. e->band[j].window[i]=sin((i+.5)/n*M_PI);
  112447. e->band[j].total+=e->band[j].window[i];
  112448. }
  112449. e->band[j].total=1./e->band[j].total;
  112450. }
  112451. e->filter=(envelope_filter_state*)_ogg_calloc(VE_BANDS*ch,sizeof(*e->filter));
  112452. e->mark=(int*)_ogg_calloc(e->storage,sizeof(*e->mark));
  112453. }
  112454. void _ve_envelope_clear(envelope_lookup *e){
  112455. int i;
  112456. mdct_clear(&e->mdct);
  112457. for(i=0;i<VE_BANDS;i++)
  112458. _ogg_free(e->band[i].window);
  112459. _ogg_free(e->mdct_win);
  112460. _ogg_free(e->filter);
  112461. _ogg_free(e->mark);
  112462. memset(e,0,sizeof(*e));
  112463. }
  112464. /* fairly straight threshhold-by-band based until we find something
  112465. that works better and isn't patented. */
  112466. static int _ve_amp(envelope_lookup *ve,
  112467. vorbis_info_psy_global *gi,
  112468. float *data,
  112469. envelope_band *bands,
  112470. envelope_filter_state *filters,
  112471. long pos){
  112472. long n=ve->winlength;
  112473. int ret=0;
  112474. long i,j;
  112475. float decay;
  112476. /* we want to have a 'minimum bar' for energy, else we're just
  112477. basing blocks on quantization noise that outweighs the signal
  112478. itself (for low power signals) */
  112479. float minV=ve->minenergy;
  112480. float *vec=(float*) alloca(n*sizeof(*vec));
  112481. /* stretch is used to gradually lengthen the number of windows
  112482. considered prevoius-to-potential-trigger */
  112483. int stretch=max(VE_MINSTRETCH,ve->stretch/2);
  112484. float penalty=gi->stretch_penalty-(ve->stretch/2-VE_MINSTRETCH);
  112485. if(penalty<0.f)penalty=0.f;
  112486. if(penalty>gi->stretch_penalty)penalty=gi->stretch_penalty;
  112487. /*_analysis_output_always("lpcm",seq2,data,n,0,0,
  112488. totalshift+pos*ve->searchstep);*/
  112489. /* window and transform */
  112490. for(i=0;i<n;i++)
  112491. vec[i]=data[i]*ve->mdct_win[i];
  112492. mdct_forward(&ve->mdct,vec,vec);
  112493. /*_analysis_output_always("mdct",seq2,vec,n/2,0,1,0); */
  112494. /* near-DC spreading function; this has nothing to do with
  112495. psychoacoustics, just sidelobe leakage and window size */
  112496. {
  112497. float temp=vec[0]*vec[0]+.7*vec[1]*vec[1]+.2*vec[2]*vec[2];
  112498. int ptr=filters->nearptr;
  112499. /* the accumulation is regularly refreshed from scratch to avoid
  112500. floating point creep */
  112501. if(ptr==0){
  112502. decay=filters->nearDC_acc=filters->nearDC_partialacc+temp;
  112503. filters->nearDC_partialacc=temp;
  112504. }else{
  112505. decay=filters->nearDC_acc+=temp;
  112506. filters->nearDC_partialacc+=temp;
  112507. }
  112508. filters->nearDC_acc-=filters->nearDC[ptr];
  112509. filters->nearDC[ptr]=temp;
  112510. decay*=(1./(VE_NEARDC+1));
  112511. filters->nearptr++;
  112512. if(filters->nearptr>=VE_NEARDC)filters->nearptr=0;
  112513. decay=todB(&decay)*.5-15.f;
  112514. }
  112515. /* perform spreading and limiting, also smooth the spectrum. yes,
  112516. the MDCT results in all real coefficients, but it still *behaves*
  112517. like real/imaginary pairs */
  112518. for(i=0;i<n/2;i+=2){
  112519. float val=vec[i]*vec[i]+vec[i+1]*vec[i+1];
  112520. val=todB(&val)*.5f;
  112521. if(val<decay)val=decay;
  112522. if(val<minV)val=minV;
  112523. vec[i>>1]=val;
  112524. decay-=8.;
  112525. }
  112526. /*_analysis_output_always("spread",seq2++,vec,n/4,0,0,0);*/
  112527. /* perform preecho/postecho triggering by band */
  112528. for(j=0;j<VE_BANDS;j++){
  112529. float acc=0.;
  112530. float valmax,valmin;
  112531. /* accumulate amplitude */
  112532. for(i=0;i<bands[j].end;i++)
  112533. acc+=vec[i+bands[j].begin]*bands[j].window[i];
  112534. acc*=bands[j].total;
  112535. /* convert amplitude to delta */
  112536. {
  112537. int p,thisx=filters[j].ampptr;
  112538. float postmax,postmin,premax=-99999.f,premin=99999.f;
  112539. p=thisx;
  112540. p--;
  112541. if(p<0)p+=VE_AMP;
  112542. postmax=max(acc,filters[j].ampbuf[p]);
  112543. postmin=min(acc,filters[j].ampbuf[p]);
  112544. for(i=0;i<stretch;i++){
  112545. p--;
  112546. if(p<0)p+=VE_AMP;
  112547. premax=max(premax,filters[j].ampbuf[p]);
  112548. premin=min(premin,filters[j].ampbuf[p]);
  112549. }
  112550. valmin=postmin-premin;
  112551. valmax=postmax-premax;
  112552. /*filters[j].markers[pos]=valmax;*/
  112553. filters[j].ampbuf[thisx]=acc;
  112554. filters[j].ampptr++;
  112555. if(filters[j].ampptr>=VE_AMP)filters[j].ampptr=0;
  112556. }
  112557. /* look at min/max, decide trigger */
  112558. if(valmax>gi->preecho_thresh[j]+penalty){
  112559. ret|=1;
  112560. ret|=4;
  112561. }
  112562. if(valmin<gi->postecho_thresh[j]-penalty)ret|=2;
  112563. }
  112564. return(ret);
  112565. }
  112566. #if 0
  112567. static int seq=0;
  112568. static ogg_int64_t totalshift=-1024;
  112569. #endif
  112570. long _ve_envelope_search(vorbis_dsp_state *v){
  112571. vorbis_info *vi=v->vi;
  112572. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  112573. vorbis_info_psy_global *gi=&ci->psy_g_param;
  112574. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  112575. long i,j;
  112576. int first=ve->current/ve->searchstep;
  112577. int last=v->pcm_current/ve->searchstep-VE_WIN;
  112578. if(first<0)first=0;
  112579. /* make sure we have enough storage to match the PCM */
  112580. if(last+VE_WIN+VE_POST>ve->storage){
  112581. ve->storage=last+VE_WIN+VE_POST; /* be sure */
  112582. ve->mark=(int*)_ogg_realloc(ve->mark,ve->storage*sizeof(*ve->mark));
  112583. }
  112584. for(j=first;j<last;j++){
  112585. int ret=0;
  112586. ve->stretch++;
  112587. if(ve->stretch>VE_MAXSTRETCH*2)
  112588. ve->stretch=VE_MAXSTRETCH*2;
  112589. for(i=0;i<ve->ch;i++){
  112590. float *pcm=v->pcm[i]+ve->searchstep*(j);
  112591. ret|=_ve_amp(ve,gi,pcm,ve->band,ve->filter+i*VE_BANDS,j);
  112592. }
  112593. ve->mark[j+VE_POST]=0;
  112594. if(ret&1){
  112595. ve->mark[j]=1;
  112596. ve->mark[j+1]=1;
  112597. }
  112598. if(ret&2){
  112599. ve->mark[j]=1;
  112600. if(j>0)ve->mark[j-1]=1;
  112601. }
  112602. if(ret&4)ve->stretch=-1;
  112603. }
  112604. ve->current=last*ve->searchstep;
  112605. {
  112606. long centerW=v->centerW;
  112607. long testW=
  112608. centerW+
  112609. ci->blocksizes[v->W]/4+
  112610. ci->blocksizes[1]/2+
  112611. ci->blocksizes[0]/4;
  112612. j=ve->cursor;
  112613. while(j<ve->current-(ve->searchstep)){/* account for postecho
  112614. working back one window */
  112615. if(j>=testW)return(1);
  112616. ve->cursor=j;
  112617. if(ve->mark[j/ve->searchstep]){
  112618. if(j>centerW){
  112619. #if 0
  112620. if(j>ve->curmark){
  112621. float *marker=alloca(v->pcm_current*sizeof(*marker));
  112622. int l,m;
  112623. memset(marker,0,sizeof(*marker)*v->pcm_current);
  112624. fprintf(stderr,"mark! seq=%d, cursor:%fs time:%fs\n",
  112625. seq,
  112626. (totalshift+ve->cursor)/44100.,
  112627. (totalshift+j)/44100.);
  112628. _analysis_output_always("pcmL",seq,v->pcm[0],v->pcm_current,0,0,totalshift);
  112629. _analysis_output_always("pcmR",seq,v->pcm[1],v->pcm_current,0,0,totalshift);
  112630. _analysis_output_always("markL",seq,v->pcm[0],j,0,0,totalshift);
  112631. _analysis_output_always("markR",seq,v->pcm[1],j,0,0,totalshift);
  112632. for(m=0;m<VE_BANDS;m++){
  112633. char buf[80];
  112634. sprintf(buf,"delL%d",m);
  112635. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m].markers[l]*.1;
  112636. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  112637. }
  112638. for(m=0;m<VE_BANDS;m++){
  112639. char buf[80];
  112640. sprintf(buf,"delR%d",m);
  112641. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m+VE_BANDS].markers[l]*.1;
  112642. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  112643. }
  112644. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->mark[l]*.4;
  112645. _analysis_output_always("mark",seq,marker,v->pcm_current,0,0,totalshift);
  112646. seq++;
  112647. }
  112648. #endif
  112649. ve->curmark=j;
  112650. if(j>=testW)return(1);
  112651. return(0);
  112652. }
  112653. }
  112654. j+=ve->searchstep;
  112655. }
  112656. }
  112657. return(-1);
  112658. }
  112659. int _ve_envelope_mark(vorbis_dsp_state *v){
  112660. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  112661. vorbis_info *vi=v->vi;
  112662. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112663. long centerW=v->centerW;
  112664. long beginW=centerW-ci->blocksizes[v->W]/4;
  112665. long endW=centerW+ci->blocksizes[v->W]/4;
  112666. if(v->W){
  112667. beginW-=ci->blocksizes[v->lW]/4;
  112668. endW+=ci->blocksizes[v->nW]/4;
  112669. }else{
  112670. beginW-=ci->blocksizes[0]/4;
  112671. endW+=ci->blocksizes[0]/4;
  112672. }
  112673. if(ve->curmark>=beginW && ve->curmark<endW)return(1);
  112674. {
  112675. long first=beginW/ve->searchstep;
  112676. long last=endW/ve->searchstep;
  112677. long i;
  112678. for(i=first;i<last;i++)
  112679. if(ve->mark[i])return(1);
  112680. }
  112681. return(0);
  112682. }
  112683. void _ve_envelope_shift(envelope_lookup *e,long shift){
  112684. int smallsize=e->current/e->searchstep+VE_POST; /* adjust for placing marks
  112685. ahead of ve->current */
  112686. int smallshift=shift/e->searchstep;
  112687. memmove(e->mark,e->mark+smallshift,(smallsize-smallshift)*sizeof(*e->mark));
  112688. #if 0
  112689. for(i=0;i<VE_BANDS*e->ch;i++)
  112690. memmove(e->filter[i].markers,
  112691. e->filter[i].markers+smallshift,
  112692. (1024-smallshift)*sizeof(*(*e->filter).markers));
  112693. totalshift+=shift;
  112694. #endif
  112695. e->current-=shift;
  112696. if(e->curmark>=0)
  112697. e->curmark-=shift;
  112698. e->cursor-=shift;
  112699. }
  112700. #endif
  112701. /*** End of inlined file: envelope.c ***/
  112702. /*** Start of inlined file: floor0.c ***/
  112703. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112704. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112705. // tasks..
  112706. #if JUCE_MSVC
  112707. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112708. #endif
  112709. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112710. #if JUCE_USE_OGGVORBIS
  112711. #include <stdlib.h>
  112712. #include <string.h>
  112713. #include <math.h>
  112714. /*** Start of inlined file: lsp.h ***/
  112715. #ifndef _V_LSP_H_
  112716. #define _V_LSP_H_
  112717. extern int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m);
  112718. extern void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,
  112719. float *lsp,int m,
  112720. float amp,float ampoffset);
  112721. #endif
  112722. /*** End of inlined file: lsp.h ***/
  112723. #include <stdio.h>
  112724. typedef struct {
  112725. int ln;
  112726. int m;
  112727. int **linearmap;
  112728. int n[2];
  112729. vorbis_info_floor0 *vi;
  112730. long bits;
  112731. long frames;
  112732. } vorbis_look_floor0;
  112733. /***********************************************/
  112734. static void floor0_free_info(vorbis_info_floor *i){
  112735. vorbis_info_floor0 *info=(vorbis_info_floor0 *)i;
  112736. if(info){
  112737. memset(info,0,sizeof(*info));
  112738. _ogg_free(info);
  112739. }
  112740. }
  112741. static void floor0_free_look(vorbis_look_floor *i){
  112742. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112743. if(look){
  112744. if(look->linearmap){
  112745. if(look->linearmap[0])_ogg_free(look->linearmap[0]);
  112746. if(look->linearmap[1])_ogg_free(look->linearmap[1]);
  112747. _ogg_free(look->linearmap);
  112748. }
  112749. memset(look,0,sizeof(*look));
  112750. _ogg_free(look);
  112751. }
  112752. }
  112753. static vorbis_info_floor *floor0_unpack (vorbis_info *vi,oggpack_buffer *opb){
  112754. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112755. int j;
  112756. vorbis_info_floor0 *info=(vorbis_info_floor0*)_ogg_malloc(sizeof(*info));
  112757. info->order=oggpack_read(opb,8);
  112758. info->rate=oggpack_read(opb,16);
  112759. info->barkmap=oggpack_read(opb,16);
  112760. info->ampbits=oggpack_read(opb,6);
  112761. info->ampdB=oggpack_read(opb,8);
  112762. info->numbooks=oggpack_read(opb,4)+1;
  112763. if(info->order<1)goto err_out;
  112764. if(info->rate<1)goto err_out;
  112765. if(info->barkmap<1)goto err_out;
  112766. if(info->numbooks<1)goto err_out;
  112767. for(j=0;j<info->numbooks;j++){
  112768. info->books[j]=oggpack_read(opb,8);
  112769. if(info->books[j]<0 || info->books[j]>=ci->books)goto err_out;
  112770. }
  112771. return(info);
  112772. err_out:
  112773. floor0_free_info(info);
  112774. return(NULL);
  112775. }
  112776. /* initialize Bark scale and normalization lookups. We could do this
  112777. with static tables, but Vorbis allows a number of possible
  112778. combinations, so it's best to do it computationally.
  112779. The below is authoritative in terms of defining scale mapping.
  112780. Note that the scale depends on the sampling rate as well as the
  112781. linear block and mapping sizes */
  112782. static void floor0_map_lazy_init(vorbis_block *vb,
  112783. vorbis_info_floor *infoX,
  112784. vorbis_look_floor0 *look){
  112785. if(!look->linearmap[vb->W]){
  112786. vorbis_dsp_state *vd=vb->vd;
  112787. vorbis_info *vi=vd->vi;
  112788. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112789. vorbis_info_floor0 *info=(vorbis_info_floor0 *)infoX;
  112790. int W=vb->W;
  112791. int n=ci->blocksizes[W]/2,j;
  112792. /* we choose a scaling constant so that:
  112793. floor(bark(rate/2-1)*C)=mapped-1
  112794. floor(bark(rate/2)*C)=mapped */
  112795. float scale=look->ln/toBARK(info->rate/2.f);
  112796. /* the mapping from a linear scale to a smaller bark scale is
  112797. straightforward. We do *not* make sure that the linear mapping
  112798. does not skip bark-scale bins; the decoder simply skips them and
  112799. the encoder may do what it wishes in filling them. They're
  112800. necessary in some mapping combinations to keep the scale spacing
  112801. accurate */
  112802. look->linearmap[W]=(int*)_ogg_malloc((n+1)*sizeof(**look->linearmap));
  112803. for(j=0;j<n;j++){
  112804. int val=floor( toBARK((info->rate/2.f)/n*j)
  112805. *scale); /* bark numbers represent band edges */
  112806. if(val>=look->ln)val=look->ln-1; /* guard against the approximation */
  112807. look->linearmap[W][j]=val;
  112808. }
  112809. look->linearmap[W][j]=-1;
  112810. look->n[W]=n;
  112811. }
  112812. }
  112813. static vorbis_look_floor *floor0_look(vorbis_dsp_state *vd,
  112814. vorbis_info_floor *i){
  112815. vorbis_info_floor0 *info=(vorbis_info_floor0*)i;
  112816. vorbis_look_floor0 *look=(vorbis_look_floor0*)_ogg_calloc(1,sizeof(*look));
  112817. look->m=info->order;
  112818. look->ln=info->barkmap;
  112819. look->vi=info;
  112820. look->linearmap=(int**)_ogg_calloc(2,sizeof(*look->linearmap));
  112821. return look;
  112822. }
  112823. static void *floor0_inverse1(vorbis_block *vb,vorbis_look_floor *i){
  112824. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112825. vorbis_info_floor0 *info=look->vi;
  112826. int j,k;
  112827. int ampraw=oggpack_read(&vb->opb,info->ampbits);
  112828. if(ampraw>0){ /* also handles the -1 out of data case */
  112829. long maxval=(1<<info->ampbits)-1;
  112830. float amp=(float)ampraw/maxval*info->ampdB;
  112831. int booknum=oggpack_read(&vb->opb,_ilog(info->numbooks));
  112832. if(booknum!=-1 && booknum<info->numbooks){ /* be paranoid */
  112833. codec_setup_info *ci=(codec_setup_info *)vb->vd->vi->codec_setup;
  112834. codebook *b=ci->fullbooks+info->books[booknum];
  112835. float last=0.f;
  112836. /* the additional b->dim is a guard against any possible stack
  112837. smash; b->dim is provably more than we can overflow the
  112838. vector */
  112839. float *lsp=(float*)_vorbis_block_alloc(vb,sizeof(*lsp)*(look->m+b->dim+1));
  112840. for(j=0;j<look->m;j+=b->dim)
  112841. if(vorbis_book_decodev_set(b,lsp+j,&vb->opb,b->dim)==-1)goto eop;
  112842. for(j=0;j<look->m;){
  112843. for(k=0;k<b->dim;k++,j++)lsp[j]+=last;
  112844. last=lsp[j-1];
  112845. }
  112846. lsp[look->m]=amp;
  112847. return(lsp);
  112848. }
  112849. }
  112850. eop:
  112851. return(NULL);
  112852. }
  112853. static int floor0_inverse2(vorbis_block *vb,vorbis_look_floor *i,
  112854. void *memo,float *out){
  112855. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112856. vorbis_info_floor0 *info=look->vi;
  112857. floor0_map_lazy_init(vb,info,look);
  112858. if(memo){
  112859. float *lsp=(float *)memo;
  112860. float amp=lsp[look->m];
  112861. /* take the coefficients back to a spectral envelope curve */
  112862. vorbis_lsp_to_curve(out,
  112863. look->linearmap[vb->W],
  112864. look->n[vb->W],
  112865. look->ln,
  112866. lsp,look->m,amp,(float)info->ampdB);
  112867. return(1);
  112868. }
  112869. memset(out,0,sizeof(*out)*look->n[vb->W]);
  112870. return(0);
  112871. }
  112872. /* export hooks */
  112873. vorbis_func_floor floor0_exportbundle={
  112874. NULL,&floor0_unpack,&floor0_look,&floor0_free_info,
  112875. &floor0_free_look,&floor0_inverse1,&floor0_inverse2
  112876. };
  112877. #endif
  112878. /*** End of inlined file: floor0.c ***/
  112879. /*** Start of inlined file: floor1.c ***/
  112880. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112881. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112882. // tasks..
  112883. #if JUCE_MSVC
  112884. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112885. #endif
  112886. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112887. #if JUCE_USE_OGGVORBIS
  112888. #include <stdlib.h>
  112889. #include <string.h>
  112890. #include <math.h>
  112891. #include <stdio.h>
  112892. #define floor1_rangedB 140 /* floor 1 fixed at -140dB to 0dB range */
  112893. typedef struct {
  112894. int sorted_index[VIF_POSIT+2];
  112895. int forward_index[VIF_POSIT+2];
  112896. int reverse_index[VIF_POSIT+2];
  112897. int hineighbor[VIF_POSIT];
  112898. int loneighbor[VIF_POSIT];
  112899. int posts;
  112900. int n;
  112901. int quant_q;
  112902. vorbis_info_floor1 *vi;
  112903. long phrasebits;
  112904. long postbits;
  112905. long frames;
  112906. } vorbis_look_floor1;
  112907. typedef struct lsfit_acc{
  112908. long x0;
  112909. long x1;
  112910. long xa;
  112911. long ya;
  112912. long x2a;
  112913. long y2a;
  112914. long xya;
  112915. long an;
  112916. } lsfit_acc;
  112917. /***********************************************/
  112918. static void floor1_free_info(vorbis_info_floor *i){
  112919. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  112920. if(info){
  112921. memset(info,0,sizeof(*info));
  112922. _ogg_free(info);
  112923. }
  112924. }
  112925. static void floor1_free_look(vorbis_look_floor *i){
  112926. vorbis_look_floor1 *look=(vorbis_look_floor1 *)i;
  112927. if(look){
  112928. /*fprintf(stderr,"floor 1 bit usage %f:%f (%f total)\n",
  112929. (float)look->phrasebits/look->frames,
  112930. (float)look->postbits/look->frames,
  112931. (float)(look->postbits+look->phrasebits)/look->frames);*/
  112932. memset(look,0,sizeof(*look));
  112933. _ogg_free(look);
  112934. }
  112935. }
  112936. static void floor1_pack (vorbis_info_floor *i,oggpack_buffer *opb){
  112937. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  112938. int j,k;
  112939. int count=0;
  112940. int rangebits;
  112941. int maxposit=info->postlist[1];
  112942. int maxclass=-1;
  112943. /* save out partitions */
  112944. oggpack_write(opb,info->partitions,5); /* only 0 to 31 legal */
  112945. for(j=0;j<info->partitions;j++){
  112946. oggpack_write(opb,info->partitionclass[j],4); /* only 0 to 15 legal */
  112947. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  112948. }
  112949. /* save out partition classes */
  112950. for(j=0;j<maxclass+1;j++){
  112951. oggpack_write(opb,info->class_dim[j]-1,3); /* 1 to 8 */
  112952. oggpack_write(opb,info->class_subs[j],2); /* 0 to 3 */
  112953. if(info->class_subs[j])oggpack_write(opb,info->class_book[j],8);
  112954. for(k=0;k<(1<<info->class_subs[j]);k++)
  112955. oggpack_write(opb,info->class_subbook[j][k]+1,8);
  112956. }
  112957. /* save out the post list */
  112958. oggpack_write(opb,info->mult-1,2); /* only 1,2,3,4 legal now */
  112959. oggpack_write(opb,ilog2(maxposit),4);
  112960. rangebits=ilog2(maxposit);
  112961. for(j=0,k=0;j<info->partitions;j++){
  112962. count+=info->class_dim[info->partitionclass[j]];
  112963. for(;k<count;k++)
  112964. oggpack_write(opb,info->postlist[k+2],rangebits);
  112965. }
  112966. }
  112967. static vorbis_info_floor *floor1_unpack (vorbis_info *vi,oggpack_buffer *opb){
  112968. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112969. int j,k,count=0,maxclass=-1,rangebits;
  112970. vorbis_info_floor1 *info=(vorbis_info_floor1*)_ogg_calloc(1,sizeof(*info));
  112971. /* read partitions */
  112972. info->partitions=oggpack_read(opb,5); /* only 0 to 31 legal */
  112973. for(j=0;j<info->partitions;j++){
  112974. info->partitionclass[j]=oggpack_read(opb,4); /* only 0 to 15 legal */
  112975. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  112976. }
  112977. /* read partition classes */
  112978. for(j=0;j<maxclass+1;j++){
  112979. info->class_dim[j]=oggpack_read(opb,3)+1; /* 1 to 8 */
  112980. info->class_subs[j]=oggpack_read(opb,2); /* 0,1,2,3 bits */
  112981. if(info->class_subs[j]<0)
  112982. goto err_out;
  112983. if(info->class_subs[j])info->class_book[j]=oggpack_read(opb,8);
  112984. if(info->class_book[j]<0 || info->class_book[j]>=ci->books)
  112985. goto err_out;
  112986. for(k=0;k<(1<<info->class_subs[j]);k++){
  112987. info->class_subbook[j][k]=oggpack_read(opb,8)-1;
  112988. if(info->class_subbook[j][k]<-1 || info->class_subbook[j][k]>=ci->books)
  112989. goto err_out;
  112990. }
  112991. }
  112992. /* read the post list */
  112993. info->mult=oggpack_read(opb,2)+1; /* only 1,2,3,4 legal now */
  112994. rangebits=oggpack_read(opb,4);
  112995. for(j=0,k=0;j<info->partitions;j++){
  112996. count+=info->class_dim[info->partitionclass[j]];
  112997. for(;k<count;k++){
  112998. int t=info->postlist[k+2]=oggpack_read(opb,rangebits);
  112999. if(t<0 || t>=(1<<rangebits))
  113000. goto err_out;
  113001. }
  113002. }
  113003. info->postlist[0]=0;
  113004. info->postlist[1]=1<<rangebits;
  113005. return(info);
  113006. err_out:
  113007. floor1_free_info(info);
  113008. return(NULL);
  113009. }
  113010. static int JUCE_CDECL icomp(const void *a,const void *b){
  113011. return(**(int **)a-**(int **)b);
  113012. }
  113013. static vorbis_look_floor *floor1_look(vorbis_dsp_state *vd,
  113014. vorbis_info_floor *in){
  113015. int *sortpointer[VIF_POSIT+2];
  113016. vorbis_info_floor1 *info=(vorbis_info_floor1*)in;
  113017. vorbis_look_floor1 *look=(vorbis_look_floor1*)_ogg_calloc(1,sizeof(*look));
  113018. int i,j,n=0;
  113019. look->vi=info;
  113020. look->n=info->postlist[1];
  113021. /* we drop each position value in-between already decoded values,
  113022. and use linear interpolation to predict each new value past the
  113023. edges. The positions are read in the order of the position
  113024. list... we precompute the bounding positions in the lookup. Of
  113025. course, the neighbors can change (if a position is declined), but
  113026. this is an initial mapping */
  113027. for(i=0;i<info->partitions;i++)n+=info->class_dim[info->partitionclass[i]];
  113028. n+=2;
  113029. look->posts=n;
  113030. /* also store a sorted position index */
  113031. for(i=0;i<n;i++)sortpointer[i]=info->postlist+i;
  113032. qsort(sortpointer,n,sizeof(*sortpointer),icomp);
  113033. /* points from sort order back to range number */
  113034. for(i=0;i<n;i++)look->forward_index[i]=sortpointer[i]-info->postlist;
  113035. /* points from range order to sorted position */
  113036. for(i=0;i<n;i++)look->reverse_index[look->forward_index[i]]=i;
  113037. /* we actually need the post values too */
  113038. for(i=0;i<n;i++)look->sorted_index[i]=info->postlist[look->forward_index[i]];
  113039. /* quantize values to multiplier spec */
  113040. switch(info->mult){
  113041. case 1: /* 1024 -> 256 */
  113042. look->quant_q=256;
  113043. break;
  113044. case 2: /* 1024 -> 128 */
  113045. look->quant_q=128;
  113046. break;
  113047. case 3: /* 1024 -> 86 */
  113048. look->quant_q=86;
  113049. break;
  113050. case 4: /* 1024 -> 64 */
  113051. look->quant_q=64;
  113052. break;
  113053. }
  113054. /* discover our neighbors for decode where we don't use fit flags
  113055. (that would push the neighbors outward) */
  113056. for(i=0;i<n-2;i++){
  113057. int lo=0;
  113058. int hi=1;
  113059. int lx=0;
  113060. int hx=look->n;
  113061. int currentx=info->postlist[i+2];
  113062. for(j=0;j<i+2;j++){
  113063. int x=info->postlist[j];
  113064. if(x>lx && x<currentx){
  113065. lo=j;
  113066. lx=x;
  113067. }
  113068. if(x<hx && x>currentx){
  113069. hi=j;
  113070. hx=x;
  113071. }
  113072. }
  113073. look->loneighbor[i]=lo;
  113074. look->hineighbor[i]=hi;
  113075. }
  113076. return(look);
  113077. }
  113078. static int render_point(int x0,int x1,int y0,int y1,int x){
  113079. y0&=0x7fff; /* mask off flag */
  113080. y1&=0x7fff;
  113081. {
  113082. int dy=y1-y0;
  113083. int adx=x1-x0;
  113084. int ady=abs(dy);
  113085. int err=ady*(x-x0);
  113086. int off=err/adx;
  113087. if(dy<0)return(y0-off);
  113088. return(y0+off);
  113089. }
  113090. }
  113091. static int vorbis_dBquant(const float *x){
  113092. int i= *x*7.3142857f+1023.5f;
  113093. if(i>1023)return(1023);
  113094. if(i<0)return(0);
  113095. return i;
  113096. }
  113097. static float FLOOR1_fromdB_LOOKUP[256]={
  113098. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  113099. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  113100. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  113101. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  113102. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  113103. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  113104. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  113105. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  113106. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  113107. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  113108. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  113109. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  113110. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  113111. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  113112. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  113113. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  113114. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  113115. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  113116. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  113117. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  113118. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  113119. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  113120. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  113121. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  113122. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  113123. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  113124. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  113125. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  113126. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  113127. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  113128. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  113129. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  113130. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  113131. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  113132. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  113133. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  113134. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  113135. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  113136. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  113137. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  113138. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  113139. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  113140. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  113141. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  113142. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  113143. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  113144. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  113145. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  113146. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  113147. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  113148. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  113149. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  113150. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  113151. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  113152. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  113153. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  113154. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  113155. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  113156. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  113157. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  113158. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  113159. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  113160. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  113161. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  113162. };
  113163. static void render_line(int x0,int x1,int y0,int y1,float *d){
  113164. int dy=y1-y0;
  113165. int adx=x1-x0;
  113166. int ady=abs(dy);
  113167. int base=dy/adx;
  113168. int sy=(dy<0?base-1:base+1);
  113169. int x=x0;
  113170. int y=y0;
  113171. int err=0;
  113172. ady-=abs(base*adx);
  113173. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  113174. while(++x<x1){
  113175. err=err+ady;
  113176. if(err>=adx){
  113177. err-=adx;
  113178. y+=sy;
  113179. }else{
  113180. y+=base;
  113181. }
  113182. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  113183. }
  113184. }
  113185. static void render_line0(int x0,int x1,int y0,int y1,int *d){
  113186. int dy=y1-y0;
  113187. int adx=x1-x0;
  113188. int ady=abs(dy);
  113189. int base=dy/adx;
  113190. int sy=(dy<0?base-1:base+1);
  113191. int x=x0;
  113192. int y=y0;
  113193. int err=0;
  113194. ady-=abs(base*adx);
  113195. d[x]=y;
  113196. while(++x<x1){
  113197. err=err+ady;
  113198. if(err>=adx){
  113199. err-=adx;
  113200. y+=sy;
  113201. }else{
  113202. y+=base;
  113203. }
  113204. d[x]=y;
  113205. }
  113206. }
  113207. /* the floor has already been filtered to only include relevant sections */
  113208. static int accumulate_fit(const float *flr,const float *mdct,
  113209. int x0, int x1,lsfit_acc *a,
  113210. int n,vorbis_info_floor1 *info){
  113211. long i;
  113212. 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;
  113213. memset(a,0,sizeof(*a));
  113214. a->x0=x0;
  113215. a->x1=x1;
  113216. if(x1>=n)x1=n-1;
  113217. for(i=x0;i<=x1;i++){
  113218. int quantized=vorbis_dBquant(flr+i);
  113219. if(quantized){
  113220. if(mdct[i]+info->twofitatten>=flr[i]){
  113221. xa += i;
  113222. ya += quantized;
  113223. x2a += i*i;
  113224. y2a += quantized*quantized;
  113225. xya += i*quantized;
  113226. na++;
  113227. }else{
  113228. xb += i;
  113229. yb += quantized;
  113230. x2b += i*i;
  113231. y2b += quantized*quantized;
  113232. xyb += i*quantized;
  113233. nb++;
  113234. }
  113235. }
  113236. }
  113237. xb+=xa;
  113238. yb+=ya;
  113239. x2b+=x2a;
  113240. y2b+=y2a;
  113241. xyb+=xya;
  113242. nb+=na;
  113243. /* weight toward the actually used frequencies if we meet the threshhold */
  113244. {
  113245. int weight=nb*info->twofitweight/(na+1);
  113246. a->xa=xa*weight+xb;
  113247. a->ya=ya*weight+yb;
  113248. a->x2a=x2a*weight+x2b;
  113249. a->y2a=y2a*weight+y2b;
  113250. a->xya=xya*weight+xyb;
  113251. a->an=na*weight+nb;
  113252. }
  113253. return(na);
  113254. }
  113255. static void fit_line(lsfit_acc *a,int fits,int *y0,int *y1){
  113256. long x=0,y=0,x2=0,y2=0,xy=0,an=0,i;
  113257. long x0=a[0].x0;
  113258. long x1=a[fits-1].x1;
  113259. for(i=0;i<fits;i++){
  113260. x+=a[i].xa;
  113261. y+=a[i].ya;
  113262. x2+=a[i].x2a;
  113263. y2+=a[i].y2a;
  113264. xy+=a[i].xya;
  113265. an+=a[i].an;
  113266. }
  113267. if(*y0>=0){
  113268. x+= x0;
  113269. y+= *y0;
  113270. x2+= x0 * x0;
  113271. y2+= *y0 * *y0;
  113272. xy+= *y0 * x0;
  113273. an++;
  113274. }
  113275. if(*y1>=0){
  113276. x+= x1;
  113277. y+= *y1;
  113278. x2+= x1 * x1;
  113279. y2+= *y1 * *y1;
  113280. xy+= *y1 * x1;
  113281. an++;
  113282. }
  113283. if(an){
  113284. /* need 64 bit multiplies, which C doesn't give portably as int */
  113285. double fx=x;
  113286. double fy=y;
  113287. double fx2=x2;
  113288. double fxy=xy;
  113289. double denom=1./(an*fx2-fx*fx);
  113290. double a=(fy*fx2-fxy*fx)*denom;
  113291. double b=(an*fxy-fx*fy)*denom;
  113292. *y0=rint(a+b*x0);
  113293. *y1=rint(a+b*x1);
  113294. /* limit to our range! */
  113295. if(*y0>1023)*y0=1023;
  113296. if(*y1>1023)*y1=1023;
  113297. if(*y0<0)*y0=0;
  113298. if(*y1<0)*y1=0;
  113299. }else{
  113300. *y0=0;
  113301. *y1=0;
  113302. }
  113303. }
  113304. /*static void fit_line_point(lsfit_acc *a,int fits,int *y0,int *y1){
  113305. long y=0;
  113306. int i;
  113307. for(i=0;i<fits && y==0;i++)
  113308. y+=a[i].ya;
  113309. *y0=*y1=y;
  113310. }*/
  113311. static int inspect_error(int x0,int x1,int y0,int y1,const float *mask,
  113312. const float *mdct,
  113313. vorbis_info_floor1 *info){
  113314. int dy=y1-y0;
  113315. int adx=x1-x0;
  113316. int ady=abs(dy);
  113317. int base=dy/adx;
  113318. int sy=(dy<0?base-1:base+1);
  113319. int x=x0;
  113320. int y=y0;
  113321. int err=0;
  113322. int val=vorbis_dBquant(mask+x);
  113323. int mse=0;
  113324. int n=0;
  113325. ady-=abs(base*adx);
  113326. mse=(y-val);
  113327. mse*=mse;
  113328. n++;
  113329. if(mdct[x]+info->twofitatten>=mask[x]){
  113330. if(y+info->maxover<val)return(1);
  113331. if(y-info->maxunder>val)return(1);
  113332. }
  113333. while(++x<x1){
  113334. err=err+ady;
  113335. if(err>=adx){
  113336. err-=adx;
  113337. y+=sy;
  113338. }else{
  113339. y+=base;
  113340. }
  113341. val=vorbis_dBquant(mask+x);
  113342. mse+=((y-val)*(y-val));
  113343. n++;
  113344. if(mdct[x]+info->twofitatten>=mask[x]){
  113345. if(val){
  113346. if(y+info->maxover<val)return(1);
  113347. if(y-info->maxunder>val)return(1);
  113348. }
  113349. }
  113350. }
  113351. if(info->maxover*info->maxover/n>info->maxerr)return(0);
  113352. if(info->maxunder*info->maxunder/n>info->maxerr)return(0);
  113353. if(mse/n>info->maxerr)return(1);
  113354. return(0);
  113355. }
  113356. static int post_Y(int *A,int *B,int pos){
  113357. if(A[pos]<0)
  113358. return B[pos];
  113359. if(B[pos]<0)
  113360. return A[pos];
  113361. return (A[pos]+B[pos])>>1;
  113362. }
  113363. int *floor1_fit(vorbis_block *vb,void *look_,
  113364. const float *logmdct, /* in */
  113365. const float *logmask){
  113366. long i,j;
  113367. vorbis_look_floor1 *look = (vorbis_look_floor1*) look_;
  113368. vorbis_info_floor1 *info=look->vi;
  113369. long n=look->n;
  113370. long posts=look->posts;
  113371. long nonzero=0;
  113372. lsfit_acc fits[VIF_POSIT+1];
  113373. int fit_valueA[VIF_POSIT+2]; /* index by range list position */
  113374. int fit_valueB[VIF_POSIT+2]; /* index by range list position */
  113375. int loneighbor[VIF_POSIT+2]; /* sorted index of range list position (+2) */
  113376. int hineighbor[VIF_POSIT+2];
  113377. int *output=NULL;
  113378. int memo[VIF_POSIT+2];
  113379. for(i=0;i<posts;i++)fit_valueA[i]=-200; /* mark all unused */
  113380. for(i=0;i<posts;i++)fit_valueB[i]=-200; /* mark all unused */
  113381. for(i=0;i<posts;i++)loneighbor[i]=0; /* 0 for the implicit 0 post */
  113382. for(i=0;i<posts;i++)hineighbor[i]=1; /* 1 for the implicit post at n */
  113383. for(i=0;i<posts;i++)memo[i]=-1; /* no neighbor yet */
  113384. /* quantize the relevant floor points and collect them into line fit
  113385. structures (one per minimal division) at the same time */
  113386. if(posts==0){
  113387. nonzero+=accumulate_fit(logmask,logmdct,0,n,fits,n,info);
  113388. }else{
  113389. for(i=0;i<posts-1;i++)
  113390. nonzero+=accumulate_fit(logmask,logmdct,look->sorted_index[i],
  113391. look->sorted_index[i+1],fits+i,
  113392. n,info);
  113393. }
  113394. if(nonzero){
  113395. /* start by fitting the implicit base case.... */
  113396. int y0=-200;
  113397. int y1=-200;
  113398. fit_line(fits,posts-1,&y0,&y1);
  113399. fit_valueA[0]=y0;
  113400. fit_valueB[0]=y0;
  113401. fit_valueB[1]=y1;
  113402. fit_valueA[1]=y1;
  113403. /* Non degenerate case */
  113404. /* start progressive splitting. This is a greedy, non-optimal
  113405. algorithm, but simple and close enough to the best
  113406. answer. */
  113407. for(i=2;i<posts;i++){
  113408. int sortpos=look->reverse_index[i];
  113409. int ln=loneighbor[sortpos];
  113410. int hn=hineighbor[sortpos];
  113411. /* eliminate repeat searches of a particular range with a memo */
  113412. if(memo[ln]!=hn){
  113413. /* haven't performed this error search yet */
  113414. int lsortpos=look->reverse_index[ln];
  113415. int hsortpos=look->reverse_index[hn];
  113416. memo[ln]=hn;
  113417. {
  113418. /* A note: we want to bound/minimize *local*, not global, error */
  113419. int lx=info->postlist[ln];
  113420. int hx=info->postlist[hn];
  113421. int ly=post_Y(fit_valueA,fit_valueB,ln);
  113422. int hy=post_Y(fit_valueA,fit_valueB,hn);
  113423. if(ly==-1 || hy==-1){
  113424. exit(1);
  113425. }
  113426. if(inspect_error(lx,hx,ly,hy,logmask,logmdct,info)){
  113427. /* outside error bounds/begin search area. Split it. */
  113428. int ly0=-200;
  113429. int ly1=-200;
  113430. int hy0=-200;
  113431. int hy1=-200;
  113432. fit_line(fits+lsortpos,sortpos-lsortpos,&ly0,&ly1);
  113433. fit_line(fits+sortpos,hsortpos-sortpos,&hy0,&hy1);
  113434. /* store new edge values */
  113435. fit_valueB[ln]=ly0;
  113436. if(ln==0)fit_valueA[ln]=ly0;
  113437. fit_valueA[i]=ly1;
  113438. fit_valueB[i]=hy0;
  113439. fit_valueA[hn]=hy1;
  113440. if(hn==1)fit_valueB[hn]=hy1;
  113441. if(ly1>=0 || hy0>=0){
  113442. /* store new neighbor values */
  113443. for(j=sortpos-1;j>=0;j--)
  113444. if(hineighbor[j]==hn)
  113445. hineighbor[j]=i;
  113446. else
  113447. break;
  113448. for(j=sortpos+1;j<posts;j++)
  113449. if(loneighbor[j]==ln)
  113450. loneighbor[j]=i;
  113451. else
  113452. break;
  113453. }
  113454. }else{
  113455. fit_valueA[i]=-200;
  113456. fit_valueB[i]=-200;
  113457. }
  113458. }
  113459. }
  113460. }
  113461. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  113462. output[0]=post_Y(fit_valueA,fit_valueB,0);
  113463. output[1]=post_Y(fit_valueA,fit_valueB,1);
  113464. /* fill in posts marked as not using a fit; we will zero
  113465. back out to 'unused' when encoding them so long as curve
  113466. interpolation doesn't force them into use */
  113467. for(i=2;i<posts;i++){
  113468. int ln=look->loneighbor[i-2];
  113469. int hn=look->hineighbor[i-2];
  113470. int x0=info->postlist[ln];
  113471. int x1=info->postlist[hn];
  113472. int y0=output[ln];
  113473. int y1=output[hn];
  113474. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  113475. int vx=post_Y(fit_valueA,fit_valueB,i);
  113476. if(vx>=0 && predicted!=vx){
  113477. output[i]=vx;
  113478. }else{
  113479. output[i]= predicted|0x8000;
  113480. }
  113481. }
  113482. }
  113483. return(output);
  113484. }
  113485. int *floor1_interpolate_fit(vorbis_block *vb,void *look_,
  113486. int *A,int *B,
  113487. int del){
  113488. long i;
  113489. vorbis_look_floor1* look = (vorbis_look_floor1*) look_;
  113490. long posts=look->posts;
  113491. int *output=NULL;
  113492. if(A && B){
  113493. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  113494. for(i=0;i<posts;i++){
  113495. output[i]=((65536-del)*(A[i]&0x7fff)+del*(B[i]&0x7fff)+32768)>>16;
  113496. if(A[i]&0x8000 && B[i]&0x8000)output[i]|=0x8000;
  113497. }
  113498. }
  113499. return(output);
  113500. }
  113501. int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  113502. void*look_,
  113503. int *post,int *ilogmask){
  113504. long i,j;
  113505. vorbis_look_floor1 *look = (vorbis_look_floor1 *) look_;
  113506. vorbis_info_floor1 *info=look->vi;
  113507. long posts=look->posts;
  113508. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113509. int out[VIF_POSIT+2];
  113510. static_codebook **sbooks=ci->book_param;
  113511. codebook *books=ci->fullbooks;
  113512. static long seq=0;
  113513. /* quantize values to multiplier spec */
  113514. if(post){
  113515. for(i=0;i<posts;i++){
  113516. int val=post[i]&0x7fff;
  113517. switch(info->mult){
  113518. case 1: /* 1024 -> 256 */
  113519. val>>=2;
  113520. break;
  113521. case 2: /* 1024 -> 128 */
  113522. val>>=3;
  113523. break;
  113524. case 3: /* 1024 -> 86 */
  113525. val/=12;
  113526. break;
  113527. case 4: /* 1024 -> 64 */
  113528. val>>=4;
  113529. break;
  113530. }
  113531. post[i]=val | (post[i]&0x8000);
  113532. }
  113533. out[0]=post[0];
  113534. out[1]=post[1];
  113535. /* find prediction values for each post and subtract them */
  113536. for(i=2;i<posts;i++){
  113537. int ln=look->loneighbor[i-2];
  113538. int hn=look->hineighbor[i-2];
  113539. int x0=info->postlist[ln];
  113540. int x1=info->postlist[hn];
  113541. int y0=post[ln];
  113542. int y1=post[hn];
  113543. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  113544. if((post[i]&0x8000) || (predicted==post[i])){
  113545. post[i]=predicted|0x8000; /* in case there was roundoff jitter
  113546. in interpolation */
  113547. out[i]=0;
  113548. }else{
  113549. int headroom=(look->quant_q-predicted<predicted?
  113550. look->quant_q-predicted:predicted);
  113551. int val=post[i]-predicted;
  113552. /* at this point the 'deviation' value is in the range +/- max
  113553. range, but the real, unique range can always be mapped to
  113554. only [0-maxrange). So we want to wrap the deviation into
  113555. this limited range, but do it in the way that least screws
  113556. an essentially gaussian probability distribution. */
  113557. if(val<0)
  113558. if(val<-headroom)
  113559. val=headroom-val-1;
  113560. else
  113561. val=-1-(val<<1);
  113562. else
  113563. if(val>=headroom)
  113564. val= val+headroom;
  113565. else
  113566. val<<=1;
  113567. out[i]=val;
  113568. post[ln]&=0x7fff;
  113569. post[hn]&=0x7fff;
  113570. }
  113571. }
  113572. /* we have everything we need. pack it out */
  113573. /* mark nontrivial floor */
  113574. oggpack_write(opb,1,1);
  113575. /* beginning/end post */
  113576. look->frames++;
  113577. look->postbits+=ilog(look->quant_q-1)*2;
  113578. oggpack_write(opb,out[0],ilog(look->quant_q-1));
  113579. oggpack_write(opb,out[1],ilog(look->quant_q-1));
  113580. /* partition by partition */
  113581. for(i=0,j=2;i<info->partitions;i++){
  113582. int classx=info->partitionclass[i];
  113583. int cdim=info->class_dim[classx];
  113584. int csubbits=info->class_subs[classx];
  113585. int csub=1<<csubbits;
  113586. int bookas[8]={0,0,0,0,0,0,0,0};
  113587. int cval=0;
  113588. int cshift=0;
  113589. int k,l;
  113590. /* generate the partition's first stage cascade value */
  113591. if(csubbits){
  113592. int maxval[8];
  113593. for(k=0;k<csub;k++){
  113594. int booknum=info->class_subbook[classx][k];
  113595. if(booknum<0){
  113596. maxval[k]=1;
  113597. }else{
  113598. maxval[k]=sbooks[info->class_subbook[classx][k]]->entries;
  113599. }
  113600. }
  113601. for(k=0;k<cdim;k++){
  113602. for(l=0;l<csub;l++){
  113603. int val=out[j+k];
  113604. if(val<maxval[l]){
  113605. bookas[k]=l;
  113606. break;
  113607. }
  113608. }
  113609. cval|= bookas[k]<<cshift;
  113610. cshift+=csubbits;
  113611. }
  113612. /* write it */
  113613. look->phrasebits+=
  113614. vorbis_book_encode(books+info->class_book[classx],cval,opb);
  113615. #ifdef TRAIN_FLOOR1
  113616. {
  113617. FILE *of;
  113618. char buffer[80];
  113619. sprintf(buffer,"line_%dx%ld_class%d.vqd",
  113620. vb->pcmend/2,posts-2,class);
  113621. of=fopen(buffer,"a");
  113622. fprintf(of,"%d\n",cval);
  113623. fclose(of);
  113624. }
  113625. #endif
  113626. }
  113627. /* write post values */
  113628. for(k=0;k<cdim;k++){
  113629. int book=info->class_subbook[classx][bookas[k]];
  113630. if(book>=0){
  113631. /* hack to allow training with 'bad' books */
  113632. if(out[j+k]<(books+book)->entries)
  113633. look->postbits+=vorbis_book_encode(books+book,
  113634. out[j+k],opb);
  113635. /*else
  113636. fprintf(stderr,"+!");*/
  113637. #ifdef TRAIN_FLOOR1
  113638. {
  113639. FILE *of;
  113640. char buffer[80];
  113641. sprintf(buffer,"line_%dx%ld_%dsub%d.vqd",
  113642. vb->pcmend/2,posts-2,class,bookas[k]);
  113643. of=fopen(buffer,"a");
  113644. fprintf(of,"%d\n",out[j+k]);
  113645. fclose(of);
  113646. }
  113647. #endif
  113648. }
  113649. }
  113650. j+=cdim;
  113651. }
  113652. {
  113653. /* generate quantized floor equivalent to what we'd unpack in decode */
  113654. /* render the lines */
  113655. int hx=0;
  113656. int lx=0;
  113657. int ly=post[0]*info->mult;
  113658. for(j=1;j<look->posts;j++){
  113659. int current=look->forward_index[j];
  113660. int hy=post[current]&0x7fff;
  113661. if(hy==post[current]){
  113662. hy*=info->mult;
  113663. hx=info->postlist[current];
  113664. render_line0(lx,hx,ly,hy,ilogmask);
  113665. lx=hx;
  113666. ly=hy;
  113667. }
  113668. }
  113669. for(j=hx;j<vb->pcmend/2;j++)ilogmask[j]=ly; /* be certain */
  113670. seq++;
  113671. return(1);
  113672. }
  113673. }else{
  113674. oggpack_write(opb,0,1);
  113675. memset(ilogmask,0,vb->pcmend/2*sizeof(*ilogmask));
  113676. seq++;
  113677. return(0);
  113678. }
  113679. }
  113680. static void *floor1_inverse1(vorbis_block *vb,vorbis_look_floor *in){
  113681. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  113682. vorbis_info_floor1 *info=look->vi;
  113683. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113684. int i,j,k;
  113685. codebook *books=ci->fullbooks;
  113686. /* unpack wrapped/predicted values from stream */
  113687. if(oggpack_read(&vb->opb,1)==1){
  113688. int *fit_value=(int*)_vorbis_block_alloc(vb,(look->posts)*sizeof(*fit_value));
  113689. fit_value[0]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  113690. fit_value[1]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  113691. /* partition by partition */
  113692. for(i=0,j=2;i<info->partitions;i++){
  113693. int classx=info->partitionclass[i];
  113694. int cdim=info->class_dim[classx];
  113695. int csubbits=info->class_subs[classx];
  113696. int csub=1<<csubbits;
  113697. int cval=0;
  113698. /* decode the partition's first stage cascade value */
  113699. if(csubbits){
  113700. cval=vorbis_book_decode(books+info->class_book[classx],&vb->opb);
  113701. if(cval==-1)goto eop;
  113702. }
  113703. for(k=0;k<cdim;k++){
  113704. int book=info->class_subbook[classx][cval&(csub-1)];
  113705. cval>>=csubbits;
  113706. if(book>=0){
  113707. if((fit_value[j+k]=vorbis_book_decode(books+book,&vb->opb))==-1)
  113708. goto eop;
  113709. }else{
  113710. fit_value[j+k]=0;
  113711. }
  113712. }
  113713. j+=cdim;
  113714. }
  113715. /* unwrap positive values and reconsitute via linear interpolation */
  113716. for(i=2;i<look->posts;i++){
  113717. int predicted=render_point(info->postlist[look->loneighbor[i-2]],
  113718. info->postlist[look->hineighbor[i-2]],
  113719. fit_value[look->loneighbor[i-2]],
  113720. fit_value[look->hineighbor[i-2]],
  113721. info->postlist[i]);
  113722. int hiroom=look->quant_q-predicted;
  113723. int loroom=predicted;
  113724. int room=(hiroom<loroom?hiroom:loroom)<<1;
  113725. int val=fit_value[i];
  113726. if(val){
  113727. if(val>=room){
  113728. if(hiroom>loroom){
  113729. val = val-loroom;
  113730. }else{
  113731. val = -1-(val-hiroom);
  113732. }
  113733. }else{
  113734. if(val&1){
  113735. val= -((val+1)>>1);
  113736. }else{
  113737. val>>=1;
  113738. }
  113739. }
  113740. fit_value[i]=val+predicted;
  113741. fit_value[look->loneighbor[i-2]]&=0x7fff;
  113742. fit_value[look->hineighbor[i-2]]&=0x7fff;
  113743. }else{
  113744. fit_value[i]=predicted|0x8000;
  113745. }
  113746. }
  113747. return(fit_value);
  113748. }
  113749. eop:
  113750. return(NULL);
  113751. }
  113752. static int floor1_inverse2(vorbis_block *vb,vorbis_look_floor *in,void *memo,
  113753. float *out){
  113754. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  113755. vorbis_info_floor1 *info=look->vi;
  113756. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113757. int n=ci->blocksizes[vb->W]/2;
  113758. int j;
  113759. if(memo){
  113760. /* render the lines */
  113761. int *fit_value=(int *)memo;
  113762. int hx=0;
  113763. int lx=0;
  113764. int ly=fit_value[0]*info->mult;
  113765. for(j=1;j<look->posts;j++){
  113766. int current=look->forward_index[j];
  113767. int hy=fit_value[current]&0x7fff;
  113768. if(hy==fit_value[current]){
  113769. hy*=info->mult;
  113770. hx=info->postlist[current];
  113771. render_line(lx,hx,ly,hy,out);
  113772. lx=hx;
  113773. ly=hy;
  113774. }
  113775. }
  113776. for(j=hx;j<n;j++)out[j]*=FLOOR1_fromdB_LOOKUP[ly]; /* be certain */
  113777. return(1);
  113778. }
  113779. memset(out,0,sizeof(*out)*n);
  113780. return(0);
  113781. }
  113782. /* export hooks */
  113783. vorbis_func_floor floor1_exportbundle={
  113784. &floor1_pack,&floor1_unpack,&floor1_look,&floor1_free_info,
  113785. &floor1_free_look,&floor1_inverse1,&floor1_inverse2
  113786. };
  113787. #endif
  113788. /*** End of inlined file: floor1.c ***/
  113789. /*** Start of inlined file: info.c ***/
  113790. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  113791. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113792. // tasks..
  113793. #if JUCE_MSVC
  113794. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113795. #endif
  113796. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  113797. #if JUCE_USE_OGGVORBIS
  113798. /* general handling of the header and the vorbis_info structure (and
  113799. substructures) */
  113800. #include <stdlib.h>
  113801. #include <string.h>
  113802. #include <ctype.h>
  113803. static void _v_writestring(oggpack_buffer *o, const char *s, int bytes){
  113804. while(bytes--){
  113805. oggpack_write(o,*s++,8);
  113806. }
  113807. }
  113808. static void _v_readstring(oggpack_buffer *o,char *buf,int bytes){
  113809. while(bytes--){
  113810. *buf++=oggpack_read(o,8);
  113811. }
  113812. }
  113813. void vorbis_comment_init(vorbis_comment *vc){
  113814. memset(vc,0,sizeof(*vc));
  113815. }
  113816. void vorbis_comment_add(vorbis_comment *vc,char *comment){
  113817. vc->user_comments=(char**)_ogg_realloc(vc->user_comments,
  113818. (vc->comments+2)*sizeof(*vc->user_comments));
  113819. vc->comment_lengths=(int*)_ogg_realloc(vc->comment_lengths,
  113820. (vc->comments+2)*sizeof(*vc->comment_lengths));
  113821. vc->comment_lengths[vc->comments]=strlen(comment);
  113822. vc->user_comments[vc->comments]=(char*)_ogg_malloc(vc->comment_lengths[vc->comments]+1);
  113823. strcpy(vc->user_comments[vc->comments], comment);
  113824. vc->comments++;
  113825. vc->user_comments[vc->comments]=NULL;
  113826. }
  113827. void vorbis_comment_add_tag(vorbis_comment *vc, const char *tag, char *contents){
  113828. char *comment=(char*)alloca(strlen(tag)+strlen(contents)+2); /* +2 for = and \0 */
  113829. strcpy(comment, tag);
  113830. strcat(comment, "=");
  113831. strcat(comment, contents);
  113832. vorbis_comment_add(vc, comment);
  113833. }
  113834. /* This is more or less the same as strncasecmp - but that doesn't exist
  113835. * everywhere, and this is a fairly trivial function, so we include it */
  113836. static int tagcompare(const char *s1, const char *s2, int n){
  113837. int c=0;
  113838. while(c < n){
  113839. if(toupper(s1[c]) != toupper(s2[c]))
  113840. return !0;
  113841. c++;
  113842. }
  113843. return 0;
  113844. }
  113845. char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count){
  113846. long i;
  113847. int found = 0;
  113848. int taglen = strlen(tag)+1; /* +1 for the = we append */
  113849. char *fulltag = (char*)alloca(taglen+ 1);
  113850. strcpy(fulltag, tag);
  113851. strcat(fulltag, "=");
  113852. for(i=0;i<vc->comments;i++){
  113853. if(!tagcompare(vc->user_comments[i], fulltag, taglen)){
  113854. if(count == found)
  113855. /* We return a pointer to the data, not a copy */
  113856. return vc->user_comments[i] + taglen;
  113857. else
  113858. found++;
  113859. }
  113860. }
  113861. return NULL; /* didn't find anything */
  113862. }
  113863. int vorbis_comment_query_count(vorbis_comment *vc, char *tag){
  113864. int i,count=0;
  113865. int taglen = strlen(tag)+1; /* +1 for the = we append */
  113866. char *fulltag = (char*)alloca(taglen+1);
  113867. strcpy(fulltag,tag);
  113868. strcat(fulltag, "=");
  113869. for(i=0;i<vc->comments;i++){
  113870. if(!tagcompare(vc->user_comments[i], fulltag, taglen))
  113871. count++;
  113872. }
  113873. return count;
  113874. }
  113875. void vorbis_comment_clear(vorbis_comment *vc){
  113876. if(vc){
  113877. long i;
  113878. for(i=0;i<vc->comments;i++)
  113879. if(vc->user_comments[i])_ogg_free(vc->user_comments[i]);
  113880. if(vc->user_comments)_ogg_free(vc->user_comments);
  113881. if(vc->comment_lengths)_ogg_free(vc->comment_lengths);
  113882. if(vc->vendor)_ogg_free(vc->vendor);
  113883. }
  113884. memset(vc,0,sizeof(*vc));
  113885. }
  113886. /* blocksize 0 is guaranteed to be short, 1 is guarantted to be long.
  113887. They may be equal, but short will never ge greater than long */
  113888. int vorbis_info_blocksize(vorbis_info *vi,int zo){
  113889. codec_setup_info *ci = (codec_setup_info*)vi->codec_setup;
  113890. return ci ? ci->blocksizes[zo] : -1;
  113891. }
  113892. /* used by synthesis, which has a full, alloced vi */
  113893. void vorbis_info_init(vorbis_info *vi){
  113894. memset(vi,0,sizeof(*vi));
  113895. vi->codec_setup=_ogg_calloc(1,sizeof(codec_setup_info));
  113896. }
  113897. void vorbis_info_clear(vorbis_info *vi){
  113898. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113899. int i;
  113900. if(ci){
  113901. for(i=0;i<ci->modes;i++)
  113902. if(ci->mode_param[i])_ogg_free(ci->mode_param[i]);
  113903. for(i=0;i<ci->maps;i++) /* unpack does the range checking */
  113904. _mapping_P[ci->map_type[i]]->free_info(ci->map_param[i]);
  113905. for(i=0;i<ci->floors;i++) /* unpack does the range checking */
  113906. _floor_P[ci->floor_type[i]]->free_info(ci->floor_param[i]);
  113907. for(i=0;i<ci->residues;i++) /* unpack does the range checking */
  113908. _residue_P[ci->residue_type[i]]->free_info(ci->residue_param[i]);
  113909. for(i=0;i<ci->books;i++){
  113910. if(ci->book_param[i]){
  113911. /* knows if the book was not alloced */
  113912. vorbis_staticbook_destroy(ci->book_param[i]);
  113913. }
  113914. if(ci->fullbooks)
  113915. vorbis_book_clear(ci->fullbooks+i);
  113916. }
  113917. if(ci->fullbooks)
  113918. _ogg_free(ci->fullbooks);
  113919. for(i=0;i<ci->psys;i++)
  113920. _vi_psy_free(ci->psy_param[i]);
  113921. _ogg_free(ci);
  113922. }
  113923. memset(vi,0,sizeof(*vi));
  113924. }
  113925. /* Header packing/unpacking ********************************************/
  113926. static int _vorbis_unpack_info(vorbis_info *vi,oggpack_buffer *opb){
  113927. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113928. if(!ci)return(OV_EFAULT);
  113929. vi->version=oggpack_read(opb,32);
  113930. if(vi->version!=0)return(OV_EVERSION);
  113931. vi->channels=oggpack_read(opb,8);
  113932. vi->rate=oggpack_read(opb,32);
  113933. vi->bitrate_upper=oggpack_read(opb,32);
  113934. vi->bitrate_nominal=oggpack_read(opb,32);
  113935. vi->bitrate_lower=oggpack_read(opb,32);
  113936. ci->blocksizes[0]=1<<oggpack_read(opb,4);
  113937. ci->blocksizes[1]=1<<oggpack_read(opb,4);
  113938. if(vi->rate<1)goto err_out;
  113939. if(vi->channels<1)goto err_out;
  113940. if(ci->blocksizes[0]<8)goto err_out;
  113941. if(ci->blocksizes[1]<ci->blocksizes[0])goto err_out;
  113942. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  113943. return(0);
  113944. err_out:
  113945. vorbis_info_clear(vi);
  113946. return(OV_EBADHEADER);
  113947. }
  113948. static int _vorbis_unpack_comment(vorbis_comment *vc,oggpack_buffer *opb){
  113949. int i;
  113950. int vendorlen=oggpack_read(opb,32);
  113951. if(vendorlen<0)goto err_out;
  113952. vc->vendor=(char*)_ogg_calloc(vendorlen+1,1);
  113953. _v_readstring(opb,vc->vendor,vendorlen);
  113954. vc->comments=oggpack_read(opb,32);
  113955. if(vc->comments<0)goto err_out;
  113956. vc->user_comments=(char**)_ogg_calloc(vc->comments+1,sizeof(*vc->user_comments));
  113957. vc->comment_lengths=(int*)_ogg_calloc(vc->comments+1, sizeof(*vc->comment_lengths));
  113958. for(i=0;i<vc->comments;i++){
  113959. int len=oggpack_read(opb,32);
  113960. if(len<0)goto err_out;
  113961. vc->comment_lengths[i]=len;
  113962. vc->user_comments[i]=(char*)_ogg_calloc(len+1,1);
  113963. _v_readstring(opb,vc->user_comments[i],len);
  113964. }
  113965. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  113966. return(0);
  113967. err_out:
  113968. vorbis_comment_clear(vc);
  113969. return(OV_EBADHEADER);
  113970. }
  113971. /* all of the real encoding details are here. The modes, books,
  113972. everything */
  113973. static int _vorbis_unpack_books(vorbis_info *vi,oggpack_buffer *opb){
  113974. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113975. int i;
  113976. if(!ci)return(OV_EFAULT);
  113977. /* codebooks */
  113978. ci->books=oggpack_read(opb,8)+1;
  113979. /*ci->book_param=_ogg_calloc(ci->books,sizeof(*ci->book_param));*/
  113980. for(i=0;i<ci->books;i++){
  113981. ci->book_param[i]=(static_codebook*)_ogg_calloc(1,sizeof(*ci->book_param[i]));
  113982. if(vorbis_staticbook_unpack(opb,ci->book_param[i]))goto err_out;
  113983. }
  113984. /* time backend settings; hooks are unused */
  113985. {
  113986. int times=oggpack_read(opb,6)+1;
  113987. for(i=0;i<times;i++){
  113988. int test=oggpack_read(opb,16);
  113989. if(test<0 || test>=VI_TIMEB)goto err_out;
  113990. }
  113991. }
  113992. /* floor backend settings */
  113993. ci->floors=oggpack_read(opb,6)+1;
  113994. /*ci->floor_type=_ogg_malloc(ci->floors*sizeof(*ci->floor_type));*/
  113995. /*ci->floor_param=_ogg_calloc(ci->floors,sizeof(void *));*/
  113996. for(i=0;i<ci->floors;i++){
  113997. ci->floor_type[i]=oggpack_read(opb,16);
  113998. if(ci->floor_type[i]<0 || ci->floor_type[i]>=VI_FLOORB)goto err_out;
  113999. ci->floor_param[i]=_floor_P[ci->floor_type[i]]->unpack(vi,opb);
  114000. if(!ci->floor_param[i])goto err_out;
  114001. }
  114002. /* residue backend settings */
  114003. ci->residues=oggpack_read(opb,6)+1;
  114004. /*ci->residue_type=_ogg_malloc(ci->residues*sizeof(*ci->residue_type));*/
  114005. /*ci->residue_param=_ogg_calloc(ci->residues,sizeof(void *));*/
  114006. for(i=0;i<ci->residues;i++){
  114007. ci->residue_type[i]=oggpack_read(opb,16);
  114008. if(ci->residue_type[i]<0 || ci->residue_type[i]>=VI_RESB)goto err_out;
  114009. ci->residue_param[i]=_residue_P[ci->residue_type[i]]->unpack(vi,opb);
  114010. if(!ci->residue_param[i])goto err_out;
  114011. }
  114012. /* map backend settings */
  114013. ci->maps=oggpack_read(opb,6)+1;
  114014. /*ci->map_type=_ogg_malloc(ci->maps*sizeof(*ci->map_type));*/
  114015. /*ci->map_param=_ogg_calloc(ci->maps,sizeof(void *));*/
  114016. for(i=0;i<ci->maps;i++){
  114017. ci->map_type[i]=oggpack_read(opb,16);
  114018. if(ci->map_type[i]<0 || ci->map_type[i]>=VI_MAPB)goto err_out;
  114019. ci->map_param[i]=_mapping_P[ci->map_type[i]]->unpack(vi,opb);
  114020. if(!ci->map_param[i])goto err_out;
  114021. }
  114022. /* mode settings */
  114023. ci->modes=oggpack_read(opb,6)+1;
  114024. /*vi->mode_param=_ogg_calloc(vi->modes,sizeof(void *));*/
  114025. for(i=0;i<ci->modes;i++){
  114026. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*ci->mode_param[i]));
  114027. ci->mode_param[i]->blockflag=oggpack_read(opb,1);
  114028. ci->mode_param[i]->windowtype=oggpack_read(opb,16);
  114029. ci->mode_param[i]->transformtype=oggpack_read(opb,16);
  114030. ci->mode_param[i]->mapping=oggpack_read(opb,8);
  114031. if(ci->mode_param[i]->windowtype>=VI_WINDOWB)goto err_out;
  114032. if(ci->mode_param[i]->transformtype>=VI_WINDOWB)goto err_out;
  114033. if(ci->mode_param[i]->mapping>=ci->maps)goto err_out;
  114034. }
  114035. if(oggpack_read(opb,1)!=1)goto err_out; /* top level EOP check */
  114036. return(0);
  114037. err_out:
  114038. vorbis_info_clear(vi);
  114039. return(OV_EBADHEADER);
  114040. }
  114041. /* The Vorbis header is in three packets; the initial small packet in
  114042. the first page that identifies basic parameters, a second packet
  114043. with bitstream comments and a third packet that holds the
  114044. codebook. */
  114045. int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,ogg_packet *op){
  114046. oggpack_buffer opb;
  114047. if(op){
  114048. oggpack_readinit(&opb,op->packet,op->bytes);
  114049. /* Which of the three types of header is this? */
  114050. /* Also verify header-ness, vorbis */
  114051. {
  114052. char buffer[6];
  114053. int packtype=oggpack_read(&opb,8);
  114054. memset(buffer,0,6);
  114055. _v_readstring(&opb,buffer,6);
  114056. if(memcmp(buffer,"vorbis",6)){
  114057. /* not a vorbis header */
  114058. return(OV_ENOTVORBIS);
  114059. }
  114060. switch(packtype){
  114061. case 0x01: /* least significant *bit* is read first */
  114062. if(!op->b_o_s){
  114063. /* Not the initial packet */
  114064. return(OV_EBADHEADER);
  114065. }
  114066. if(vi->rate!=0){
  114067. /* previously initialized info header */
  114068. return(OV_EBADHEADER);
  114069. }
  114070. return(_vorbis_unpack_info(vi,&opb));
  114071. case 0x03: /* least significant *bit* is read first */
  114072. if(vi->rate==0){
  114073. /* um... we didn't get the initial header */
  114074. return(OV_EBADHEADER);
  114075. }
  114076. return(_vorbis_unpack_comment(vc,&opb));
  114077. case 0x05: /* least significant *bit* is read first */
  114078. if(vi->rate==0 || vc->vendor==NULL){
  114079. /* um... we didn;t get the initial header or comments yet */
  114080. return(OV_EBADHEADER);
  114081. }
  114082. return(_vorbis_unpack_books(vi,&opb));
  114083. default:
  114084. /* Not a valid vorbis header type */
  114085. return(OV_EBADHEADER);
  114086. break;
  114087. }
  114088. }
  114089. }
  114090. return(OV_EBADHEADER);
  114091. }
  114092. /* pack side **********************************************************/
  114093. static int _vorbis_pack_info(oggpack_buffer *opb,vorbis_info *vi){
  114094. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114095. if(!ci)return(OV_EFAULT);
  114096. /* preamble */
  114097. oggpack_write(opb,0x01,8);
  114098. _v_writestring(opb,"vorbis", 6);
  114099. /* basic information about the stream */
  114100. oggpack_write(opb,0x00,32);
  114101. oggpack_write(opb,vi->channels,8);
  114102. oggpack_write(opb,vi->rate,32);
  114103. oggpack_write(opb,vi->bitrate_upper,32);
  114104. oggpack_write(opb,vi->bitrate_nominal,32);
  114105. oggpack_write(opb,vi->bitrate_lower,32);
  114106. oggpack_write(opb,ilog2(ci->blocksizes[0]),4);
  114107. oggpack_write(opb,ilog2(ci->blocksizes[1]),4);
  114108. oggpack_write(opb,1,1);
  114109. return(0);
  114110. }
  114111. static int _vorbis_pack_comment(oggpack_buffer *opb,vorbis_comment *vc){
  114112. char temp[]="Xiph.Org libVorbis I 20050304";
  114113. int bytes = strlen(temp);
  114114. /* preamble */
  114115. oggpack_write(opb,0x03,8);
  114116. _v_writestring(opb,"vorbis", 6);
  114117. /* vendor */
  114118. oggpack_write(opb,bytes,32);
  114119. _v_writestring(opb,temp, bytes);
  114120. /* comments */
  114121. oggpack_write(opb,vc->comments,32);
  114122. if(vc->comments){
  114123. int i;
  114124. for(i=0;i<vc->comments;i++){
  114125. if(vc->user_comments[i]){
  114126. oggpack_write(opb,vc->comment_lengths[i],32);
  114127. _v_writestring(opb,vc->user_comments[i], vc->comment_lengths[i]);
  114128. }else{
  114129. oggpack_write(opb,0,32);
  114130. }
  114131. }
  114132. }
  114133. oggpack_write(opb,1,1);
  114134. return(0);
  114135. }
  114136. static int _vorbis_pack_books(oggpack_buffer *opb,vorbis_info *vi){
  114137. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114138. int i;
  114139. if(!ci)return(OV_EFAULT);
  114140. oggpack_write(opb,0x05,8);
  114141. _v_writestring(opb,"vorbis", 6);
  114142. /* books */
  114143. oggpack_write(opb,ci->books-1,8);
  114144. for(i=0;i<ci->books;i++)
  114145. if(vorbis_staticbook_pack(ci->book_param[i],opb))goto err_out;
  114146. /* times; hook placeholders */
  114147. oggpack_write(opb,0,6);
  114148. oggpack_write(opb,0,16);
  114149. /* floors */
  114150. oggpack_write(opb,ci->floors-1,6);
  114151. for(i=0;i<ci->floors;i++){
  114152. oggpack_write(opb,ci->floor_type[i],16);
  114153. if(_floor_P[ci->floor_type[i]]->pack)
  114154. _floor_P[ci->floor_type[i]]->pack(ci->floor_param[i],opb);
  114155. else
  114156. goto err_out;
  114157. }
  114158. /* residues */
  114159. oggpack_write(opb,ci->residues-1,6);
  114160. for(i=0;i<ci->residues;i++){
  114161. oggpack_write(opb,ci->residue_type[i],16);
  114162. _residue_P[ci->residue_type[i]]->pack(ci->residue_param[i],opb);
  114163. }
  114164. /* maps */
  114165. oggpack_write(opb,ci->maps-1,6);
  114166. for(i=0;i<ci->maps;i++){
  114167. oggpack_write(opb,ci->map_type[i],16);
  114168. _mapping_P[ci->map_type[i]]->pack(vi,ci->map_param[i],opb);
  114169. }
  114170. /* modes */
  114171. oggpack_write(opb,ci->modes-1,6);
  114172. for(i=0;i<ci->modes;i++){
  114173. oggpack_write(opb,ci->mode_param[i]->blockflag,1);
  114174. oggpack_write(opb,ci->mode_param[i]->windowtype,16);
  114175. oggpack_write(opb,ci->mode_param[i]->transformtype,16);
  114176. oggpack_write(opb,ci->mode_param[i]->mapping,8);
  114177. }
  114178. oggpack_write(opb,1,1);
  114179. return(0);
  114180. err_out:
  114181. return(-1);
  114182. }
  114183. int vorbis_commentheader_out(vorbis_comment *vc,
  114184. ogg_packet *op){
  114185. oggpack_buffer opb;
  114186. oggpack_writeinit(&opb);
  114187. if(_vorbis_pack_comment(&opb,vc)) return OV_EIMPL;
  114188. op->packet = (unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114189. memcpy(op->packet, opb.buffer, oggpack_bytes(&opb));
  114190. op->bytes=oggpack_bytes(&opb);
  114191. op->b_o_s=0;
  114192. op->e_o_s=0;
  114193. op->granulepos=0;
  114194. op->packetno=1;
  114195. return 0;
  114196. }
  114197. int vorbis_analysis_headerout(vorbis_dsp_state *v,
  114198. vorbis_comment *vc,
  114199. ogg_packet *op,
  114200. ogg_packet *op_comm,
  114201. ogg_packet *op_code){
  114202. int ret=OV_EIMPL;
  114203. vorbis_info *vi=v->vi;
  114204. oggpack_buffer opb;
  114205. private_state *b=(private_state*)v->backend_state;
  114206. if(!b){
  114207. ret=OV_EFAULT;
  114208. goto err_out;
  114209. }
  114210. /* first header packet **********************************************/
  114211. oggpack_writeinit(&opb);
  114212. if(_vorbis_pack_info(&opb,vi))goto err_out;
  114213. /* build the packet */
  114214. if(b->header)_ogg_free(b->header);
  114215. b->header=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114216. memcpy(b->header,opb.buffer,oggpack_bytes(&opb));
  114217. op->packet=b->header;
  114218. op->bytes=oggpack_bytes(&opb);
  114219. op->b_o_s=1;
  114220. op->e_o_s=0;
  114221. op->granulepos=0;
  114222. op->packetno=0;
  114223. /* second header packet (comments) **********************************/
  114224. oggpack_reset(&opb);
  114225. if(_vorbis_pack_comment(&opb,vc))goto err_out;
  114226. if(b->header1)_ogg_free(b->header1);
  114227. b->header1=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114228. memcpy(b->header1,opb.buffer,oggpack_bytes(&opb));
  114229. op_comm->packet=b->header1;
  114230. op_comm->bytes=oggpack_bytes(&opb);
  114231. op_comm->b_o_s=0;
  114232. op_comm->e_o_s=0;
  114233. op_comm->granulepos=0;
  114234. op_comm->packetno=1;
  114235. /* third header packet (modes/codebooks) ****************************/
  114236. oggpack_reset(&opb);
  114237. if(_vorbis_pack_books(&opb,vi))goto err_out;
  114238. if(b->header2)_ogg_free(b->header2);
  114239. b->header2=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114240. memcpy(b->header2,opb.buffer,oggpack_bytes(&opb));
  114241. op_code->packet=b->header2;
  114242. op_code->bytes=oggpack_bytes(&opb);
  114243. op_code->b_o_s=0;
  114244. op_code->e_o_s=0;
  114245. op_code->granulepos=0;
  114246. op_code->packetno=2;
  114247. oggpack_writeclear(&opb);
  114248. return(0);
  114249. err_out:
  114250. oggpack_writeclear(&opb);
  114251. memset(op,0,sizeof(*op));
  114252. memset(op_comm,0,sizeof(*op_comm));
  114253. memset(op_code,0,sizeof(*op_code));
  114254. if(b->header)_ogg_free(b->header);
  114255. if(b->header1)_ogg_free(b->header1);
  114256. if(b->header2)_ogg_free(b->header2);
  114257. b->header=NULL;
  114258. b->header1=NULL;
  114259. b->header2=NULL;
  114260. return(ret);
  114261. }
  114262. double vorbis_granule_time(vorbis_dsp_state *v,ogg_int64_t granulepos){
  114263. if(granulepos>=0)
  114264. return((double)granulepos/v->vi->rate);
  114265. return(-1);
  114266. }
  114267. #endif
  114268. /*** End of inlined file: info.c ***/
  114269. /*** Start of inlined file: lpc.c ***/
  114270. /* Some of these routines (autocorrelator, LPC coefficient estimator)
  114271. are derived from code written by Jutta Degener and Carsten Bormann;
  114272. thus we include their copyright below. The entirety of this file
  114273. is freely redistributable on the condition that both of these
  114274. copyright notices are preserved without modification. */
  114275. /* Preserved Copyright: *********************************************/
  114276. /* Copyright 1992, 1993, 1994 by Jutta Degener and Carsten Bormann,
  114277. Technische Universita"t Berlin
  114278. Any use of this software is permitted provided that this notice is not
  114279. removed and that neither the authors nor the Technische Universita"t
  114280. Berlin are deemed to have made any representations as to the
  114281. suitability of this software for any purpose nor are held responsible
  114282. for any defects of this software. THERE IS ABSOLUTELY NO WARRANTY FOR
  114283. THIS SOFTWARE.
  114284. As a matter of courtesy, the authors request to be informed about uses
  114285. this software has found, about bugs in this software, and about any
  114286. improvements that may be of general interest.
  114287. Berlin, 28.11.1994
  114288. Jutta Degener
  114289. Carsten Bormann
  114290. *********************************************************************/
  114291. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114292. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114293. // tasks..
  114294. #if JUCE_MSVC
  114295. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114296. #endif
  114297. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114298. #if JUCE_USE_OGGVORBIS
  114299. #include <stdlib.h>
  114300. #include <string.h>
  114301. #include <math.h>
  114302. /* Autocorrelation LPC coeff generation algorithm invented by
  114303. N. Levinson in 1947, modified by J. Durbin in 1959. */
  114304. /* Input : n elements of time doamin data
  114305. Output: m lpc coefficients, excitation energy */
  114306. float vorbis_lpc_from_data(float *data,float *lpci,int n,int m){
  114307. double *aut=(double*)alloca(sizeof(*aut)*(m+1));
  114308. double *lpc=(double*)alloca(sizeof(*lpc)*(m));
  114309. double error;
  114310. int i,j;
  114311. /* autocorrelation, p+1 lag coefficients */
  114312. j=m+1;
  114313. while(j--){
  114314. double d=0; /* double needed for accumulator depth */
  114315. for(i=j;i<n;i++)d+=(double)data[i]*data[i-j];
  114316. aut[j]=d;
  114317. }
  114318. /* Generate lpc coefficients from autocorr values */
  114319. error=aut[0];
  114320. for(i=0;i<m;i++){
  114321. double r= -aut[i+1];
  114322. if(error==0){
  114323. memset(lpci,0,m*sizeof(*lpci));
  114324. return 0;
  114325. }
  114326. /* Sum up this iteration's reflection coefficient; note that in
  114327. Vorbis we don't save it. If anyone wants to recycle this code
  114328. and needs reflection coefficients, save the results of 'r' from
  114329. each iteration. */
  114330. for(j=0;j<i;j++)r-=lpc[j]*aut[i-j];
  114331. r/=error;
  114332. /* Update LPC coefficients and total error */
  114333. lpc[i]=r;
  114334. for(j=0;j<i/2;j++){
  114335. double tmp=lpc[j];
  114336. lpc[j]+=r*lpc[i-1-j];
  114337. lpc[i-1-j]+=r*tmp;
  114338. }
  114339. if(i%2)lpc[j]+=lpc[j]*r;
  114340. error*=1.f-r*r;
  114341. }
  114342. for(j=0;j<m;j++)lpci[j]=(float)lpc[j];
  114343. /* we need the error value to know how big an impulse to hit the
  114344. filter with later */
  114345. return error;
  114346. }
  114347. void vorbis_lpc_predict(float *coeff,float *prime,int m,
  114348. float *data,long n){
  114349. /* in: coeff[0...m-1] LPC coefficients
  114350. prime[0...m-1] initial values (allocated size of n+m-1)
  114351. out: data[0...n-1] data samples */
  114352. long i,j,o,p;
  114353. float y;
  114354. float *work=(float*)alloca(sizeof(*work)*(m+n));
  114355. if(!prime)
  114356. for(i=0;i<m;i++)
  114357. work[i]=0.f;
  114358. else
  114359. for(i=0;i<m;i++)
  114360. work[i]=prime[i];
  114361. for(i=0;i<n;i++){
  114362. y=0;
  114363. o=i;
  114364. p=m;
  114365. for(j=0;j<m;j++)
  114366. y-=work[o++]*coeff[--p];
  114367. data[i]=work[o]=y;
  114368. }
  114369. }
  114370. #endif
  114371. /*** End of inlined file: lpc.c ***/
  114372. /*** Start of inlined file: lsp.c ***/
  114373. /* Note that the lpc-lsp conversion finds the roots of polynomial with
  114374. an iterative root polisher (CACM algorithm 283). It *is* possible
  114375. to confuse this algorithm into not converging; that should only
  114376. happen with absurdly closely spaced roots (very sharp peaks in the
  114377. LPC f response) which in turn should be impossible in our use of
  114378. the code. If this *does* happen anyway, it's a bug in the floor
  114379. finder; find the cause of the confusion (probably a single bin
  114380. spike or accidental near-float-limit resolution problems) and
  114381. correct it. */
  114382. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114383. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114384. // tasks..
  114385. #if JUCE_MSVC
  114386. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114387. #endif
  114388. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114389. #if JUCE_USE_OGGVORBIS
  114390. #include <math.h>
  114391. #include <string.h>
  114392. #include <stdlib.h>
  114393. /*** Start of inlined file: lookup.h ***/
  114394. #ifndef _V_LOOKUP_H_
  114395. #ifdef FLOAT_LOOKUP
  114396. extern float vorbis_coslook(float a);
  114397. extern float vorbis_invsqlook(float a);
  114398. extern float vorbis_invsq2explook(int a);
  114399. extern float vorbis_fromdBlook(float a);
  114400. #endif
  114401. #ifdef INT_LOOKUP
  114402. extern long vorbis_invsqlook_i(long a,long e);
  114403. extern long vorbis_coslook_i(long a);
  114404. extern float vorbis_fromdBlook_i(long a);
  114405. #endif
  114406. #endif
  114407. /*** End of inlined file: lookup.h ***/
  114408. /* three possible LSP to f curve functions; the exact computation
  114409. (float), a lookup based float implementation, and an integer
  114410. implementation. The float lookup is likely the optimal choice on
  114411. any machine with an FPU. The integer implementation is *not* fixed
  114412. point (due to the need for a large dynamic range and thus a
  114413. seperately tracked exponent) and thus much more complex than the
  114414. relatively simple float implementations. It's mostly for future
  114415. work on a fully fixed point implementation for processors like the
  114416. ARM family. */
  114417. /* undefine both for the 'old' but more precise implementation */
  114418. #define FLOAT_LOOKUP
  114419. #undef INT_LOOKUP
  114420. #ifdef FLOAT_LOOKUP
  114421. /*** Start of inlined file: lookup.c ***/
  114422. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114423. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114424. // tasks..
  114425. #if JUCE_MSVC
  114426. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114427. #endif
  114428. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114429. #if JUCE_USE_OGGVORBIS
  114430. #include <math.h>
  114431. /*** Start of inlined file: lookup.h ***/
  114432. #ifndef _V_LOOKUP_H_
  114433. #ifdef FLOAT_LOOKUP
  114434. extern float vorbis_coslook(float a);
  114435. extern float vorbis_invsqlook(float a);
  114436. extern float vorbis_invsq2explook(int a);
  114437. extern float vorbis_fromdBlook(float a);
  114438. #endif
  114439. #ifdef INT_LOOKUP
  114440. extern long vorbis_invsqlook_i(long a,long e);
  114441. extern long vorbis_coslook_i(long a);
  114442. extern float vorbis_fromdBlook_i(long a);
  114443. #endif
  114444. #endif
  114445. /*** End of inlined file: lookup.h ***/
  114446. /*** Start of inlined file: lookup_data.h ***/
  114447. #ifndef _V_LOOKUP_DATA_H_
  114448. #ifdef FLOAT_LOOKUP
  114449. #define COS_LOOKUP_SZ 128
  114450. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  114451. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  114452. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  114453. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  114454. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  114455. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  114456. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  114457. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  114458. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  114459. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  114460. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  114461. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  114462. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  114463. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  114464. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  114465. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  114466. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  114467. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  114468. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  114469. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  114470. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  114471. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  114472. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  114473. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  114474. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  114475. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  114476. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  114477. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  114478. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  114479. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  114480. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  114481. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  114482. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  114483. -1.0000000000000f,
  114484. };
  114485. #define INVSQ_LOOKUP_SZ 32
  114486. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  114487. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  114488. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  114489. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  114490. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  114491. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  114492. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  114493. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  114494. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  114495. 1.000000000000f,
  114496. };
  114497. #define INVSQ2EXP_LOOKUP_MIN (-32)
  114498. #define INVSQ2EXP_LOOKUP_MAX 32
  114499. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  114500. INVSQ2EXP_LOOKUP_MIN+1]={
  114501. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  114502. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  114503. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  114504. 1024.f, 724.0773439f, 512.f, 362.038672f,
  114505. 256.f, 181.019336f, 128.f, 90.50966799f,
  114506. 64.f, 45.254834f, 32.f, 22.627417f,
  114507. 16.f, 11.3137085f, 8.f, 5.656854249f,
  114508. 4.f, 2.828427125f, 2.f, 1.414213562f,
  114509. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  114510. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  114511. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  114512. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  114513. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  114514. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  114515. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  114516. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  114517. 1.525878906e-05f,
  114518. };
  114519. #endif
  114520. #define FROMdB_LOOKUP_SZ 35
  114521. #define FROMdB2_LOOKUP_SZ 32
  114522. #define FROMdB_SHIFT 5
  114523. #define FROMdB2_SHIFT 3
  114524. #define FROMdB2_MASK 31
  114525. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  114526. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  114527. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  114528. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  114529. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  114530. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  114531. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  114532. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  114533. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  114534. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  114535. };
  114536. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  114537. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  114538. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  114539. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  114540. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  114541. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  114542. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  114543. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  114544. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  114545. };
  114546. #ifdef INT_LOOKUP
  114547. #define INVSQ_LOOKUP_I_SHIFT 10
  114548. #define INVSQ_LOOKUP_I_MASK 1023
  114549. static long INVSQ_LOOKUP_I[64+1]={
  114550. 92682l, 91966l, 91267l, 90583l,
  114551. 89915l, 89261l, 88621l, 87995l,
  114552. 87381l, 86781l, 86192l, 85616l,
  114553. 85051l, 84497l, 83953l, 83420l,
  114554. 82897l, 82384l, 81880l, 81385l,
  114555. 80899l, 80422l, 79953l, 79492l,
  114556. 79039l, 78594l, 78156l, 77726l,
  114557. 77302l, 76885l, 76475l, 76072l,
  114558. 75674l, 75283l, 74898l, 74519l,
  114559. 74146l, 73778l, 73415l, 73058l,
  114560. 72706l, 72359l, 72016l, 71679l,
  114561. 71347l, 71019l, 70695l, 70376l,
  114562. 70061l, 69750l, 69444l, 69141l,
  114563. 68842l, 68548l, 68256l, 67969l,
  114564. 67685l, 67405l, 67128l, 66855l,
  114565. 66585l, 66318l, 66054l, 65794l,
  114566. 65536l,
  114567. };
  114568. #define COS_LOOKUP_I_SHIFT 9
  114569. #define COS_LOOKUP_I_MASK 511
  114570. #define COS_LOOKUP_I_SZ 128
  114571. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  114572. 16384l, 16379l, 16364l, 16340l,
  114573. 16305l, 16261l, 16207l, 16143l,
  114574. 16069l, 15986l, 15893l, 15791l,
  114575. 15679l, 15557l, 15426l, 15286l,
  114576. 15137l, 14978l, 14811l, 14635l,
  114577. 14449l, 14256l, 14053l, 13842l,
  114578. 13623l, 13395l, 13160l, 12916l,
  114579. 12665l, 12406l, 12140l, 11866l,
  114580. 11585l, 11297l, 11003l, 10702l,
  114581. 10394l, 10080l, 9760l, 9434l,
  114582. 9102l, 8765l, 8423l, 8076l,
  114583. 7723l, 7366l, 7005l, 6639l,
  114584. 6270l, 5897l, 5520l, 5139l,
  114585. 4756l, 4370l, 3981l, 3590l,
  114586. 3196l, 2801l, 2404l, 2006l,
  114587. 1606l, 1205l, 804l, 402l,
  114588. 0l, -401l, -803l, -1204l,
  114589. -1605l, -2005l, -2403l, -2800l,
  114590. -3195l, -3589l, -3980l, -4369l,
  114591. -4755l, -5138l, -5519l, -5896l,
  114592. -6269l, -6638l, -7004l, -7365l,
  114593. -7722l, -8075l, -8422l, -8764l,
  114594. -9101l, -9433l, -9759l, -10079l,
  114595. -10393l, -10701l, -11002l, -11296l,
  114596. -11584l, -11865l, -12139l, -12405l,
  114597. -12664l, -12915l, -13159l, -13394l,
  114598. -13622l, -13841l, -14052l, -14255l,
  114599. -14448l, -14634l, -14810l, -14977l,
  114600. -15136l, -15285l, -15425l, -15556l,
  114601. -15678l, -15790l, -15892l, -15985l,
  114602. -16068l, -16142l, -16206l, -16260l,
  114603. -16304l, -16339l, -16363l, -16378l,
  114604. -16383l,
  114605. };
  114606. #endif
  114607. #endif
  114608. /*** End of inlined file: lookup_data.h ***/
  114609. #ifdef FLOAT_LOOKUP
  114610. /* interpolated lookup based cos function, domain 0 to PI only */
  114611. float vorbis_coslook(float a){
  114612. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  114613. int i=vorbis_ftoi(d-.5);
  114614. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  114615. }
  114616. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114617. float vorbis_invsqlook(float a){
  114618. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  114619. int i=vorbis_ftoi(d-.5f);
  114620. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  114621. }
  114622. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114623. float vorbis_invsq2explook(int a){
  114624. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  114625. }
  114626. #include <stdio.h>
  114627. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114628. float vorbis_fromdBlook(float a){
  114629. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  114630. return (i<0)?1.f:
  114631. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114632. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114633. }
  114634. #endif
  114635. #ifdef INT_LOOKUP
  114636. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  114637. 16.16 format
  114638. returns in m.8 format */
  114639. long vorbis_invsqlook_i(long a,long e){
  114640. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  114641. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  114642. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  114643. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  114644. d)>>16); /* result 1.16 */
  114645. e+=32;
  114646. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  114647. e=(e>>1)-8;
  114648. return(val>>e);
  114649. }
  114650. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114651. /* a is in n.12 format */
  114652. float vorbis_fromdBlook_i(long a){
  114653. int i=(-a)>>(12-FROMdB2_SHIFT);
  114654. return (i<0)?1.f:
  114655. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114656. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114657. }
  114658. /* interpolated lookup based cos function, domain 0 to PI only */
  114659. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  114660. long vorbis_coslook_i(long a){
  114661. int i=a>>COS_LOOKUP_I_SHIFT;
  114662. int d=a&COS_LOOKUP_I_MASK;
  114663. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  114664. COS_LOOKUP_I_SHIFT);
  114665. }
  114666. #endif
  114667. #endif
  114668. /*** End of inlined file: lookup.c ***/
  114669. /* catch this in the build system; we #include for
  114670. compilers (like gcc) that can't inline across
  114671. modules */
  114672. /* side effect: changes *lsp to cosines of lsp */
  114673. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  114674. float amp,float ampoffset){
  114675. int i;
  114676. float wdel=M_PI/ln;
  114677. vorbis_fpu_control fpu;
  114678. (void) fpu; // to avoid an unused variable warning
  114679. vorbis_fpu_setround(&fpu);
  114680. for(i=0;i<m;i++)lsp[i]=vorbis_coslook(lsp[i]);
  114681. i=0;
  114682. while(i<n){
  114683. int k=map[i];
  114684. int qexp;
  114685. float p=.7071067812f;
  114686. float q=.7071067812f;
  114687. float w=vorbis_coslook(wdel*k);
  114688. float *ftmp=lsp;
  114689. int c=m>>1;
  114690. do{
  114691. q*=ftmp[0]-w;
  114692. p*=ftmp[1]-w;
  114693. ftmp+=2;
  114694. }while(--c);
  114695. if(m&1){
  114696. /* odd order filter; slightly assymetric */
  114697. /* the last coefficient */
  114698. q*=ftmp[0]-w;
  114699. q*=q;
  114700. p*=p*(1.f-w*w);
  114701. }else{
  114702. /* even order filter; still symmetric */
  114703. q*=q*(1.f+w);
  114704. p*=p*(1.f-w);
  114705. }
  114706. q=frexp(p+q,&qexp);
  114707. q=vorbis_fromdBlook(amp*
  114708. vorbis_invsqlook(q)*
  114709. vorbis_invsq2explook(qexp+m)-
  114710. ampoffset);
  114711. do{
  114712. curve[i++]*=q;
  114713. }while(map[i]==k);
  114714. }
  114715. vorbis_fpu_restore(fpu);
  114716. }
  114717. #else
  114718. #ifdef INT_LOOKUP
  114719. /*** Start of inlined file: lookup.c ***/
  114720. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114721. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114722. // tasks..
  114723. #if JUCE_MSVC
  114724. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114725. #endif
  114726. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114727. #if JUCE_USE_OGGVORBIS
  114728. #include <math.h>
  114729. /*** Start of inlined file: lookup.h ***/
  114730. #ifndef _V_LOOKUP_H_
  114731. #ifdef FLOAT_LOOKUP
  114732. extern float vorbis_coslook(float a);
  114733. extern float vorbis_invsqlook(float a);
  114734. extern float vorbis_invsq2explook(int a);
  114735. extern float vorbis_fromdBlook(float a);
  114736. #endif
  114737. #ifdef INT_LOOKUP
  114738. extern long vorbis_invsqlook_i(long a,long e);
  114739. extern long vorbis_coslook_i(long a);
  114740. extern float vorbis_fromdBlook_i(long a);
  114741. #endif
  114742. #endif
  114743. /*** End of inlined file: lookup.h ***/
  114744. /*** Start of inlined file: lookup_data.h ***/
  114745. #ifndef _V_LOOKUP_DATA_H_
  114746. #ifdef FLOAT_LOOKUP
  114747. #define COS_LOOKUP_SZ 128
  114748. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  114749. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  114750. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  114751. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  114752. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  114753. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  114754. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  114755. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  114756. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  114757. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  114758. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  114759. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  114760. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  114761. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  114762. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  114763. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  114764. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  114765. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  114766. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  114767. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  114768. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  114769. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  114770. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  114771. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  114772. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  114773. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  114774. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  114775. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  114776. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  114777. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  114778. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  114779. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  114780. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  114781. -1.0000000000000f,
  114782. };
  114783. #define INVSQ_LOOKUP_SZ 32
  114784. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  114785. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  114786. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  114787. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  114788. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  114789. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  114790. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  114791. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  114792. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  114793. 1.000000000000f,
  114794. };
  114795. #define INVSQ2EXP_LOOKUP_MIN (-32)
  114796. #define INVSQ2EXP_LOOKUP_MAX 32
  114797. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  114798. INVSQ2EXP_LOOKUP_MIN+1]={
  114799. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  114800. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  114801. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  114802. 1024.f, 724.0773439f, 512.f, 362.038672f,
  114803. 256.f, 181.019336f, 128.f, 90.50966799f,
  114804. 64.f, 45.254834f, 32.f, 22.627417f,
  114805. 16.f, 11.3137085f, 8.f, 5.656854249f,
  114806. 4.f, 2.828427125f, 2.f, 1.414213562f,
  114807. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  114808. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  114809. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  114810. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  114811. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  114812. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  114813. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  114814. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  114815. 1.525878906e-05f,
  114816. };
  114817. #endif
  114818. #define FROMdB_LOOKUP_SZ 35
  114819. #define FROMdB2_LOOKUP_SZ 32
  114820. #define FROMdB_SHIFT 5
  114821. #define FROMdB2_SHIFT 3
  114822. #define FROMdB2_MASK 31
  114823. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  114824. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  114825. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  114826. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  114827. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  114828. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  114829. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  114830. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  114831. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  114832. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  114833. };
  114834. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  114835. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  114836. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  114837. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  114838. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  114839. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  114840. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  114841. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  114842. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  114843. };
  114844. #ifdef INT_LOOKUP
  114845. #define INVSQ_LOOKUP_I_SHIFT 10
  114846. #define INVSQ_LOOKUP_I_MASK 1023
  114847. static long INVSQ_LOOKUP_I[64+1]={
  114848. 92682l, 91966l, 91267l, 90583l,
  114849. 89915l, 89261l, 88621l, 87995l,
  114850. 87381l, 86781l, 86192l, 85616l,
  114851. 85051l, 84497l, 83953l, 83420l,
  114852. 82897l, 82384l, 81880l, 81385l,
  114853. 80899l, 80422l, 79953l, 79492l,
  114854. 79039l, 78594l, 78156l, 77726l,
  114855. 77302l, 76885l, 76475l, 76072l,
  114856. 75674l, 75283l, 74898l, 74519l,
  114857. 74146l, 73778l, 73415l, 73058l,
  114858. 72706l, 72359l, 72016l, 71679l,
  114859. 71347l, 71019l, 70695l, 70376l,
  114860. 70061l, 69750l, 69444l, 69141l,
  114861. 68842l, 68548l, 68256l, 67969l,
  114862. 67685l, 67405l, 67128l, 66855l,
  114863. 66585l, 66318l, 66054l, 65794l,
  114864. 65536l,
  114865. };
  114866. #define COS_LOOKUP_I_SHIFT 9
  114867. #define COS_LOOKUP_I_MASK 511
  114868. #define COS_LOOKUP_I_SZ 128
  114869. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  114870. 16384l, 16379l, 16364l, 16340l,
  114871. 16305l, 16261l, 16207l, 16143l,
  114872. 16069l, 15986l, 15893l, 15791l,
  114873. 15679l, 15557l, 15426l, 15286l,
  114874. 15137l, 14978l, 14811l, 14635l,
  114875. 14449l, 14256l, 14053l, 13842l,
  114876. 13623l, 13395l, 13160l, 12916l,
  114877. 12665l, 12406l, 12140l, 11866l,
  114878. 11585l, 11297l, 11003l, 10702l,
  114879. 10394l, 10080l, 9760l, 9434l,
  114880. 9102l, 8765l, 8423l, 8076l,
  114881. 7723l, 7366l, 7005l, 6639l,
  114882. 6270l, 5897l, 5520l, 5139l,
  114883. 4756l, 4370l, 3981l, 3590l,
  114884. 3196l, 2801l, 2404l, 2006l,
  114885. 1606l, 1205l, 804l, 402l,
  114886. 0l, -401l, -803l, -1204l,
  114887. -1605l, -2005l, -2403l, -2800l,
  114888. -3195l, -3589l, -3980l, -4369l,
  114889. -4755l, -5138l, -5519l, -5896l,
  114890. -6269l, -6638l, -7004l, -7365l,
  114891. -7722l, -8075l, -8422l, -8764l,
  114892. -9101l, -9433l, -9759l, -10079l,
  114893. -10393l, -10701l, -11002l, -11296l,
  114894. -11584l, -11865l, -12139l, -12405l,
  114895. -12664l, -12915l, -13159l, -13394l,
  114896. -13622l, -13841l, -14052l, -14255l,
  114897. -14448l, -14634l, -14810l, -14977l,
  114898. -15136l, -15285l, -15425l, -15556l,
  114899. -15678l, -15790l, -15892l, -15985l,
  114900. -16068l, -16142l, -16206l, -16260l,
  114901. -16304l, -16339l, -16363l, -16378l,
  114902. -16383l,
  114903. };
  114904. #endif
  114905. #endif
  114906. /*** End of inlined file: lookup_data.h ***/
  114907. #ifdef FLOAT_LOOKUP
  114908. /* interpolated lookup based cos function, domain 0 to PI only */
  114909. float vorbis_coslook(float a){
  114910. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  114911. int i=vorbis_ftoi(d-.5);
  114912. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  114913. }
  114914. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114915. float vorbis_invsqlook(float a){
  114916. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  114917. int i=vorbis_ftoi(d-.5f);
  114918. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  114919. }
  114920. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114921. float vorbis_invsq2explook(int a){
  114922. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  114923. }
  114924. #include <stdio.h>
  114925. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114926. float vorbis_fromdBlook(float a){
  114927. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  114928. return (i<0)?1.f:
  114929. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114930. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114931. }
  114932. #endif
  114933. #ifdef INT_LOOKUP
  114934. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  114935. 16.16 format
  114936. returns in m.8 format */
  114937. long vorbis_invsqlook_i(long a,long e){
  114938. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  114939. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  114940. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  114941. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  114942. d)>>16); /* result 1.16 */
  114943. e+=32;
  114944. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  114945. e=(e>>1)-8;
  114946. return(val>>e);
  114947. }
  114948. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114949. /* a is in n.12 format */
  114950. float vorbis_fromdBlook_i(long a){
  114951. int i=(-a)>>(12-FROMdB2_SHIFT);
  114952. return (i<0)?1.f:
  114953. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114954. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114955. }
  114956. /* interpolated lookup based cos function, domain 0 to PI only */
  114957. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  114958. long vorbis_coslook_i(long a){
  114959. int i=a>>COS_LOOKUP_I_SHIFT;
  114960. int d=a&COS_LOOKUP_I_MASK;
  114961. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  114962. COS_LOOKUP_I_SHIFT);
  114963. }
  114964. #endif
  114965. #endif
  114966. /*** End of inlined file: lookup.c ***/
  114967. /* catch this in the build system; we #include for
  114968. compilers (like gcc) that can't inline across
  114969. modules */
  114970. static int MLOOP_1[64]={
  114971. 0,10,11,11, 12,12,12,12, 13,13,13,13, 13,13,13,13,
  114972. 14,14,14,14, 14,14,14,14, 14,14,14,14, 14,14,14,14,
  114973. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  114974. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  114975. };
  114976. static int MLOOP_2[64]={
  114977. 0,4,5,5, 6,6,6,6, 7,7,7,7, 7,7,7,7,
  114978. 8,8,8,8, 8,8,8,8, 8,8,8,8, 8,8,8,8,
  114979. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  114980. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  114981. };
  114982. static int MLOOP_3[8]={0,1,2,2,3,3,3,3};
  114983. /* side effect: changes *lsp to cosines of lsp */
  114984. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  114985. float amp,float ampoffset){
  114986. /* 0 <= m < 256 */
  114987. /* set up for using all int later */
  114988. int i;
  114989. int ampoffseti=rint(ampoffset*4096.f);
  114990. int ampi=rint(amp*16.f);
  114991. long *ilsp=alloca(m*sizeof(*ilsp));
  114992. for(i=0;i<m;i++)ilsp[i]=vorbis_coslook_i(lsp[i]/M_PI*65536.f+.5f);
  114993. i=0;
  114994. while(i<n){
  114995. int j,k=map[i];
  114996. unsigned long pi=46341; /* 2**-.5 in 0.16 */
  114997. unsigned long qi=46341;
  114998. int qexp=0,shift;
  114999. long wi=vorbis_coslook_i(k*65536/ln);
  115000. qi*=labs(ilsp[0]-wi);
  115001. pi*=labs(ilsp[1]-wi);
  115002. for(j=3;j<m;j+=2){
  115003. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  115004. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  115005. shift=MLOOP_3[(pi|qi)>>16];
  115006. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  115007. pi=(pi>>shift)*labs(ilsp[j]-wi);
  115008. qexp+=shift;
  115009. }
  115010. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  115011. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  115012. shift=MLOOP_3[(pi|qi)>>16];
  115013. /* pi,qi normalized collectively, both tracked using qexp */
  115014. if(m&1){
  115015. /* odd order filter; slightly assymetric */
  115016. /* the last coefficient */
  115017. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  115018. pi=(pi>>shift)<<14;
  115019. qexp+=shift;
  115020. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  115021. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  115022. shift=MLOOP_3[(pi|qi)>>16];
  115023. pi>>=shift;
  115024. qi>>=shift;
  115025. qexp+=shift-14*((m+1)>>1);
  115026. pi=((pi*pi)>>16);
  115027. qi=((qi*qi)>>16);
  115028. qexp=qexp*2+m;
  115029. pi*=(1<<14)-((wi*wi)>>14);
  115030. qi+=pi>>14;
  115031. }else{
  115032. /* even order filter; still symmetric */
  115033. /* p*=p(1-w), q*=q(1+w), let normalization drift because it isn't
  115034. worth tracking step by step */
  115035. pi>>=shift;
  115036. qi>>=shift;
  115037. qexp+=shift-7*m;
  115038. pi=((pi*pi)>>16);
  115039. qi=((qi*qi)>>16);
  115040. qexp=qexp*2+m;
  115041. pi*=(1<<14)-wi;
  115042. qi*=(1<<14)+wi;
  115043. qi=(qi+pi)>>14;
  115044. }
  115045. /* we've let the normalization drift because it wasn't important;
  115046. however, for the lookup, things must be normalized again. We
  115047. need at most one right shift or a number of left shifts */
  115048. if(qi&0xffff0000){ /* checks for 1.xxxxxxxxxxxxxxxx */
  115049. qi>>=1; qexp++;
  115050. }else
  115051. while(qi && !(qi&0x8000)){ /* checks for 0.0xxxxxxxxxxxxxxx or less*/
  115052. qi<<=1; qexp--;
  115053. }
  115054. amp=vorbis_fromdBlook_i(ampi* /* n.4 */
  115055. vorbis_invsqlook_i(qi,qexp)-
  115056. /* m.8, m+n<=8 */
  115057. ampoffseti); /* 8.12[0] */
  115058. curve[i]*=amp;
  115059. while(map[++i]==k)curve[i]*=amp;
  115060. }
  115061. }
  115062. #else
  115063. /* old, nonoptimized but simple version for any poor sap who needs to
  115064. figure out what the hell this code does, or wants the other
  115065. fraction of a dB precision */
  115066. /* side effect: changes *lsp to cosines of lsp */
  115067. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  115068. float amp,float ampoffset){
  115069. int i;
  115070. float wdel=M_PI/ln;
  115071. for(i=0;i<m;i++)lsp[i]=2.f*cos(lsp[i]);
  115072. i=0;
  115073. while(i<n){
  115074. int j,k=map[i];
  115075. float p=.5f;
  115076. float q=.5f;
  115077. float w=2.f*cos(wdel*k);
  115078. for(j=1;j<m;j+=2){
  115079. q *= w-lsp[j-1];
  115080. p *= w-lsp[j];
  115081. }
  115082. if(j==m){
  115083. /* odd order filter; slightly assymetric */
  115084. /* the last coefficient */
  115085. q*=w-lsp[j-1];
  115086. p*=p*(4.f-w*w);
  115087. q*=q;
  115088. }else{
  115089. /* even order filter; still symmetric */
  115090. p*=p*(2.f-w);
  115091. q*=q*(2.f+w);
  115092. }
  115093. q=fromdB(amp/sqrt(p+q)-ampoffset);
  115094. curve[i]*=q;
  115095. while(map[++i]==k)curve[i]*=q;
  115096. }
  115097. }
  115098. #endif
  115099. #endif
  115100. static void cheby(float *g, int ord) {
  115101. int i, j;
  115102. g[0] *= .5f;
  115103. for(i=2; i<= ord; i++) {
  115104. for(j=ord; j >= i; j--) {
  115105. g[j-2] -= g[j];
  115106. g[j] += g[j];
  115107. }
  115108. }
  115109. }
  115110. static int JUCE_CDECL comp(const void *a,const void *b){
  115111. return (*(float *)a<*(float *)b)-(*(float *)a>*(float *)b);
  115112. }
  115113. /* Newton-Raphson-Maehly actually functioned as a decent root finder,
  115114. but there are root sets for which it gets into limit cycles
  115115. (exacerbated by zero suppression) and fails. We can't afford to
  115116. fail, even if the failure is 1 in 100,000,000, so we now use
  115117. Laguerre and later polish with Newton-Raphson (which can then
  115118. afford to fail) */
  115119. #define EPSILON 10e-7
  115120. static int Laguerre_With_Deflation(float *a,int ord,float *r){
  115121. int i,m;
  115122. double lastdelta=0.f;
  115123. double *defl=(double*)alloca(sizeof(*defl)*(ord+1));
  115124. for(i=0;i<=ord;i++)defl[i]=a[i];
  115125. for(m=ord;m>0;m--){
  115126. double newx=0.f,delta;
  115127. /* iterate a root */
  115128. while(1){
  115129. double p=defl[m],pp=0.f,ppp=0.f,denom;
  115130. /* eval the polynomial and its first two derivatives */
  115131. for(i=m;i>0;i--){
  115132. ppp = newx*ppp + pp;
  115133. pp = newx*pp + p;
  115134. p = newx*p + defl[i-1];
  115135. }
  115136. /* Laguerre's method */
  115137. denom=(m-1) * ((m-1)*pp*pp - m*p*ppp);
  115138. if(denom<0)
  115139. return(-1); /* complex root! The LPC generator handed us a bad filter */
  115140. if(pp>0){
  115141. denom = pp + sqrt(denom);
  115142. if(denom<EPSILON)denom=EPSILON;
  115143. }else{
  115144. denom = pp - sqrt(denom);
  115145. if(denom>-(EPSILON))denom=-(EPSILON);
  115146. }
  115147. delta = m*p/denom;
  115148. newx -= delta;
  115149. if(delta<0.f)delta*=-1;
  115150. if(fabs(delta/newx)<10e-12)break;
  115151. lastdelta=delta;
  115152. }
  115153. r[m-1]=newx;
  115154. /* forward deflation */
  115155. for(i=m;i>0;i--)
  115156. defl[i-1]+=newx*defl[i];
  115157. defl++;
  115158. }
  115159. return(0);
  115160. }
  115161. /* for spit-and-polish only */
  115162. static int Newton_Raphson(float *a,int ord,float *r){
  115163. int i, k, count=0;
  115164. double error=1.f;
  115165. double *root=(double*)alloca(ord*sizeof(*root));
  115166. for(i=0; i<ord;i++) root[i] = r[i];
  115167. while(error>1e-20){
  115168. error=0;
  115169. for(i=0; i<ord; i++) { /* Update each point. */
  115170. double pp=0.,delta;
  115171. double rooti=root[i];
  115172. double p=a[ord];
  115173. for(k=ord-1; k>= 0; k--) {
  115174. pp= pp* rooti + p;
  115175. p = p * rooti + a[k];
  115176. }
  115177. delta = p/pp;
  115178. root[i] -= delta;
  115179. error+= delta*delta;
  115180. }
  115181. if(count>40)return(-1);
  115182. count++;
  115183. }
  115184. /* Replaced the original bubble sort with a real sort. With your
  115185. help, we can eliminate the bubble sort in our lifetime. --Monty */
  115186. for(i=0; i<ord;i++) r[i] = root[i];
  115187. return(0);
  115188. }
  115189. /* Convert lpc coefficients to lsp coefficients */
  115190. int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m){
  115191. int order2=(m+1)>>1;
  115192. int g1_order,g2_order;
  115193. float *g1=(float*)alloca(sizeof(*g1)*(order2+1));
  115194. float *g2=(float*)alloca(sizeof(*g2)*(order2+1));
  115195. float *g1r=(float*)alloca(sizeof(*g1r)*(order2+1));
  115196. float *g2r=(float*)alloca(sizeof(*g2r)*(order2+1));
  115197. int i;
  115198. /* even and odd are slightly different base cases */
  115199. g1_order=(m+1)>>1;
  115200. g2_order=(m) >>1;
  115201. /* Compute the lengths of the x polynomials. */
  115202. /* Compute the first half of K & R F1 & F2 polynomials. */
  115203. /* Compute half of the symmetric and antisymmetric polynomials. */
  115204. /* Remove the roots at +1 and -1. */
  115205. g1[g1_order] = 1.f;
  115206. for(i=1;i<=g1_order;i++) g1[g1_order-i] = lpc[i-1]+lpc[m-i];
  115207. g2[g2_order] = 1.f;
  115208. for(i=1;i<=g2_order;i++) g2[g2_order-i] = lpc[i-1]-lpc[m-i];
  115209. if(g1_order>g2_order){
  115210. for(i=2; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+2];
  115211. }else{
  115212. for(i=1; i<=g1_order;i++) g1[g1_order-i] -= g1[g1_order-i+1];
  115213. for(i=1; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+1];
  115214. }
  115215. /* Convert into polynomials in cos(alpha) */
  115216. cheby(g1,g1_order);
  115217. cheby(g2,g2_order);
  115218. /* Find the roots of the 2 even polynomials.*/
  115219. if(Laguerre_With_Deflation(g1,g1_order,g1r) ||
  115220. Laguerre_With_Deflation(g2,g2_order,g2r))
  115221. return(-1);
  115222. Newton_Raphson(g1,g1_order,g1r); /* if it fails, it leaves g1r alone */
  115223. Newton_Raphson(g2,g2_order,g2r); /* if it fails, it leaves g2r alone */
  115224. qsort(g1r,g1_order,sizeof(*g1r),comp);
  115225. qsort(g2r,g2_order,sizeof(*g2r),comp);
  115226. for(i=0;i<g1_order;i++)
  115227. lsp[i*2] = acos(g1r[i]);
  115228. for(i=0;i<g2_order;i++)
  115229. lsp[i*2+1] = acos(g2r[i]);
  115230. return(0);
  115231. }
  115232. #endif
  115233. /*** End of inlined file: lsp.c ***/
  115234. /*** Start of inlined file: mapping0.c ***/
  115235. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  115236. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  115237. // tasks..
  115238. #if JUCE_MSVC
  115239. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  115240. #endif
  115241. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  115242. #if JUCE_USE_OGGVORBIS
  115243. #include <stdlib.h>
  115244. #include <stdio.h>
  115245. #include <string.h>
  115246. #include <math.h>
  115247. /* simplistic, wasteful way of doing this (unique lookup for each
  115248. mode/submapping); there should be a central repository for
  115249. identical lookups. That will require minor work, so I'm putting it
  115250. off as low priority.
  115251. Why a lookup for each backend in a given mode? Because the
  115252. blocksize is set by the mode, and low backend lookups may require
  115253. parameters from other areas of the mode/mapping */
  115254. static void mapping0_free_info(vorbis_info_mapping *i){
  115255. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)i;
  115256. if(info){
  115257. memset(info,0,sizeof(*info));
  115258. _ogg_free(info);
  115259. }
  115260. }
  115261. static int ilog3(unsigned int v){
  115262. int ret=0;
  115263. if(v)--v;
  115264. while(v){
  115265. ret++;
  115266. v>>=1;
  115267. }
  115268. return(ret);
  115269. }
  115270. static void mapping0_pack(vorbis_info *vi,vorbis_info_mapping *vm,
  115271. oggpack_buffer *opb){
  115272. int i;
  115273. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)vm;
  115274. /* another 'we meant to do it this way' hack... up to beta 4, we
  115275. packed 4 binary zeros here to signify one submapping in use. We
  115276. now redefine that to mean four bitflags that indicate use of
  115277. deeper features; bit0:submappings, bit1:coupling,
  115278. bit2,3:reserved. This is backward compatable with all actual uses
  115279. of the beta code. */
  115280. if(info->submaps>1){
  115281. oggpack_write(opb,1,1);
  115282. oggpack_write(opb,info->submaps-1,4);
  115283. }else
  115284. oggpack_write(opb,0,1);
  115285. if(info->coupling_steps>0){
  115286. oggpack_write(opb,1,1);
  115287. oggpack_write(opb,info->coupling_steps-1,8);
  115288. for(i=0;i<info->coupling_steps;i++){
  115289. oggpack_write(opb,info->coupling_mag[i],ilog3(vi->channels));
  115290. oggpack_write(opb,info->coupling_ang[i],ilog3(vi->channels));
  115291. }
  115292. }else
  115293. oggpack_write(opb,0,1);
  115294. oggpack_write(opb,0,2); /* 2,3:reserved */
  115295. /* we don't write the channel submappings if we only have one... */
  115296. if(info->submaps>1){
  115297. for(i=0;i<vi->channels;i++)
  115298. oggpack_write(opb,info->chmuxlist[i],4);
  115299. }
  115300. for(i=0;i<info->submaps;i++){
  115301. oggpack_write(opb,0,8); /* time submap unused */
  115302. oggpack_write(opb,info->floorsubmap[i],8);
  115303. oggpack_write(opb,info->residuesubmap[i],8);
  115304. }
  115305. }
  115306. /* also responsible for range checking */
  115307. static vorbis_info_mapping *mapping0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  115308. int i;
  115309. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)_ogg_calloc(1,sizeof(*info));
  115310. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  115311. memset(info,0,sizeof(*info));
  115312. if(oggpack_read(opb,1))
  115313. info->submaps=oggpack_read(opb,4)+1;
  115314. else
  115315. info->submaps=1;
  115316. if(oggpack_read(opb,1)){
  115317. info->coupling_steps=oggpack_read(opb,8)+1;
  115318. for(i=0;i<info->coupling_steps;i++){
  115319. int testM=info->coupling_mag[i]=oggpack_read(opb,ilog3(vi->channels));
  115320. int testA=info->coupling_ang[i]=oggpack_read(opb,ilog3(vi->channels));
  115321. if(testM<0 ||
  115322. testA<0 ||
  115323. testM==testA ||
  115324. testM>=vi->channels ||
  115325. testA>=vi->channels) goto err_out;
  115326. }
  115327. }
  115328. if(oggpack_read(opb,2)>0)goto err_out; /* 2,3:reserved */
  115329. if(info->submaps>1){
  115330. for(i=0;i<vi->channels;i++){
  115331. info->chmuxlist[i]=oggpack_read(opb,4);
  115332. if(info->chmuxlist[i]>=info->submaps)goto err_out;
  115333. }
  115334. }
  115335. for(i=0;i<info->submaps;i++){
  115336. oggpack_read(opb,8); /* time submap unused */
  115337. info->floorsubmap[i]=oggpack_read(opb,8);
  115338. if(info->floorsubmap[i]>=ci->floors)goto err_out;
  115339. info->residuesubmap[i]=oggpack_read(opb,8);
  115340. if(info->residuesubmap[i]>=ci->residues)goto err_out;
  115341. }
  115342. return info;
  115343. err_out:
  115344. mapping0_free_info(info);
  115345. return(NULL);
  115346. }
  115347. #if 0
  115348. static long seq=0;
  115349. static ogg_int64_t total=0;
  115350. static float FLOOR1_fromdB_LOOKUP[256]={
  115351. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  115352. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  115353. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  115354. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  115355. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  115356. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  115357. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  115358. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  115359. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  115360. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  115361. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  115362. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  115363. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  115364. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  115365. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  115366. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  115367. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  115368. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  115369. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  115370. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  115371. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  115372. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  115373. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  115374. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  115375. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  115376. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  115377. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  115378. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  115379. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  115380. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  115381. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  115382. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  115383. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  115384. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  115385. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  115386. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  115387. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  115388. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  115389. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  115390. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  115391. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  115392. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  115393. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  115394. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  115395. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  115396. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  115397. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  115398. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  115399. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  115400. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  115401. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  115402. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  115403. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  115404. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  115405. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  115406. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  115407. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  115408. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  115409. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  115410. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  115411. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  115412. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  115413. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  115414. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  115415. };
  115416. #endif
  115417. extern int *floor1_fit(vorbis_block *vb,void *look,
  115418. const float *logmdct, /* in */
  115419. const float *logmask);
  115420. extern int *floor1_interpolate_fit(vorbis_block *vb,void *look,
  115421. int *A,int *B,
  115422. int del);
  115423. extern int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  115424. void*look,
  115425. int *post,int *ilogmask);
  115426. static int mapping0_forward(vorbis_block *vb){
  115427. vorbis_dsp_state *vd=vb->vd;
  115428. vorbis_info *vi=vd->vi;
  115429. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  115430. private_state *b=(private_state*)vb->vd->backend_state;
  115431. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  115432. int n=vb->pcmend;
  115433. int i,j,k;
  115434. int *nonzero = (int*) alloca(sizeof(*nonzero)*vi->channels);
  115435. float **gmdct = (float**) _vorbis_block_alloc(vb,vi->channels*sizeof(*gmdct));
  115436. int **ilogmaskch= (int**) _vorbis_block_alloc(vb,vi->channels*sizeof(*ilogmaskch));
  115437. int ***floor_posts = (int***) _vorbis_block_alloc(vb,vi->channels*sizeof(*floor_posts));
  115438. float global_ampmax=vbi->ampmax;
  115439. float *local_ampmax=(float*)alloca(sizeof(*local_ampmax)*vi->channels);
  115440. int blocktype=vbi->blocktype;
  115441. int modenumber=vb->W;
  115442. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)ci->map_param[modenumber];
  115443. vorbis_look_psy *psy_look=
  115444. b->psy+blocktype+(vb->W?2:0);
  115445. vb->mode=modenumber;
  115446. for(i=0;i<vi->channels;i++){
  115447. float scale=4.f/n;
  115448. float scale_dB;
  115449. float *pcm =vb->pcm[i];
  115450. float *logfft =pcm;
  115451. gmdct[i]=(float*)_vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  115452. scale_dB=todB(&scale) + .345; /* + .345 is a hack; the original
  115453. todB estimation used on IEEE 754
  115454. compliant machines had a bug that
  115455. returned dB values about a third
  115456. of a decibel too high. The bug
  115457. was harmless because tunings
  115458. implicitly took that into
  115459. account. However, fixing the bug
  115460. in the estimator requires
  115461. changing all the tunings as well.
  115462. For now, it's easier to sync
  115463. things back up here, and
  115464. recalibrate the tunings in the
  115465. next major model upgrade. */
  115466. #if 0
  115467. if(vi->channels==2)
  115468. if(i==0)
  115469. _analysis_output("pcmL",seq,pcm,n,0,0,total-n/2);
  115470. else
  115471. _analysis_output("pcmR",seq,pcm,n,0,0,total-n/2);
  115472. #endif
  115473. /* window the PCM data */
  115474. _vorbis_apply_window(pcm,b->window,ci->blocksizes,vb->lW,vb->W,vb->nW);
  115475. #if 0
  115476. if(vi->channels==2)
  115477. if(i==0)
  115478. _analysis_output("windowedL",seq,pcm,n,0,0,total-n/2);
  115479. else
  115480. _analysis_output("windowedR",seq,pcm,n,0,0,total-n/2);
  115481. #endif
  115482. /* transform the PCM data */
  115483. /* only MDCT right now.... */
  115484. mdct_forward((mdct_lookup*) b->transform[vb->W][0],pcm,gmdct[i]);
  115485. /* FFT yields more accurate tonal estimation (not phase sensitive) */
  115486. drft_forward(&b->fft_look[vb->W],pcm);
  115487. logfft[0]=scale_dB+todB(pcm) + .345; /* + .345 is a hack; the
  115488. original todB estimation used on
  115489. IEEE 754 compliant machines had a
  115490. bug that returned dB values about
  115491. a third of a decibel too high.
  115492. The bug was harmless because
  115493. tunings implicitly took that into
  115494. account. However, fixing the bug
  115495. in the estimator requires
  115496. changing all the tunings as well.
  115497. For now, it's easier to sync
  115498. things back up here, and
  115499. recalibrate the tunings in the
  115500. next major model upgrade. */
  115501. local_ampmax[i]=logfft[0];
  115502. for(j=1;j<n-1;j+=2){
  115503. float temp=pcm[j]*pcm[j]+pcm[j+1]*pcm[j+1];
  115504. temp=logfft[(j+1)>>1]=scale_dB+.5f*todB(&temp) + .345; /* +
  115505. .345 is a hack; the original todB
  115506. estimation used on IEEE 754
  115507. compliant machines had a bug that
  115508. returned dB values about a third
  115509. of a decibel too high. The bug
  115510. was harmless because tunings
  115511. implicitly took that into
  115512. account. However, fixing the bug
  115513. in the estimator requires
  115514. changing all the tunings as well.
  115515. For now, it's easier to sync
  115516. things back up here, and
  115517. recalibrate the tunings in the
  115518. next major model upgrade. */
  115519. if(temp>local_ampmax[i])local_ampmax[i]=temp;
  115520. }
  115521. if(local_ampmax[i]>0.f)local_ampmax[i]=0.f;
  115522. if(local_ampmax[i]>global_ampmax)global_ampmax=local_ampmax[i];
  115523. #if 0
  115524. if(vi->channels==2){
  115525. if(i==0){
  115526. _analysis_output("fftL",seq,logfft,n/2,1,0,0);
  115527. }else{
  115528. _analysis_output("fftR",seq,logfft,n/2,1,0,0);
  115529. }
  115530. }
  115531. #endif
  115532. }
  115533. {
  115534. float *noise = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*noise));
  115535. float *tone = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*tone));
  115536. for(i=0;i<vi->channels;i++){
  115537. /* the encoder setup assumes that all the modes used by any
  115538. specific bitrate tweaking use the same floor */
  115539. int submap=info->chmuxlist[i];
  115540. /* the following makes things clearer to *me* anyway */
  115541. float *mdct =gmdct[i];
  115542. float *logfft =vb->pcm[i];
  115543. float *logmdct =logfft+n/2;
  115544. float *logmask =logfft;
  115545. vb->mode=modenumber;
  115546. floor_posts[i]=(int**) _vorbis_block_alloc(vb,PACKETBLOBS*sizeof(**floor_posts));
  115547. memset(floor_posts[i],0,sizeof(**floor_posts)*PACKETBLOBS);
  115548. for(j=0;j<n/2;j++)
  115549. logmdct[j]=todB(mdct+j) + .345; /* + .345 is a hack; the original
  115550. todB estimation used on IEEE 754
  115551. compliant machines had a bug that
  115552. returned dB values about a third
  115553. of a decibel too high. The bug
  115554. was harmless because tunings
  115555. implicitly took that into
  115556. account. However, fixing the bug
  115557. in the estimator requires
  115558. changing all the tunings as well.
  115559. For now, it's easier to sync
  115560. things back up here, and
  115561. recalibrate the tunings in the
  115562. next major model upgrade. */
  115563. #if 0
  115564. if(vi->channels==2){
  115565. if(i==0)
  115566. _analysis_output("mdctL",seq,logmdct,n/2,1,0,0);
  115567. else
  115568. _analysis_output("mdctR",seq,logmdct,n/2,1,0,0);
  115569. }else{
  115570. _analysis_output("mdct",seq,logmdct,n/2,1,0,0);
  115571. }
  115572. #endif
  115573. /* first step; noise masking. Not only does 'noise masking'
  115574. give us curves from which we can decide how much resolution
  115575. to give noise parts of the spectrum, it also implicitly hands
  115576. us a tonality estimate (the larger the value in the
  115577. 'noise_depth' vector, the more tonal that area is) */
  115578. _vp_noisemask(psy_look,
  115579. logmdct,
  115580. noise); /* noise does not have by-frequency offset
  115581. bias applied yet */
  115582. #if 0
  115583. if(vi->channels==2){
  115584. if(i==0)
  115585. _analysis_output("noiseL",seq,noise,n/2,1,0,0);
  115586. else
  115587. _analysis_output("noiseR",seq,noise,n/2,1,0,0);
  115588. }
  115589. #endif
  115590. /* second step: 'all the other crap'; all the stuff that isn't
  115591. computed/fit for bitrate management goes in the second psy
  115592. vector. This includes tone masking, peak limiting and ATH */
  115593. _vp_tonemask(psy_look,
  115594. logfft,
  115595. tone,
  115596. global_ampmax,
  115597. local_ampmax[i]);
  115598. #if 0
  115599. if(vi->channels==2){
  115600. if(i==0)
  115601. _analysis_output("toneL",seq,tone,n/2,1,0,0);
  115602. else
  115603. _analysis_output("toneR",seq,tone,n/2,1,0,0);
  115604. }
  115605. #endif
  115606. /* third step; we offset the noise vectors, overlay tone
  115607. masking. We then do a floor1-specific line fit. If we're
  115608. performing bitrate management, the line fit is performed
  115609. multiple times for up/down tweakage on demand. */
  115610. #if 0
  115611. {
  115612. float aotuv[psy_look->n];
  115613. #endif
  115614. _vp_offset_and_mix(psy_look,
  115615. noise,
  115616. tone,
  115617. 1,
  115618. logmask,
  115619. mdct,
  115620. logmdct);
  115621. #if 0
  115622. if(vi->channels==2){
  115623. if(i==0)
  115624. _analysis_output("aotuvM1_L",seq,aotuv,psy_look->n,1,1,0);
  115625. else
  115626. _analysis_output("aotuvM1_R",seq,aotuv,psy_look->n,1,1,0);
  115627. }
  115628. }
  115629. #endif
  115630. #if 0
  115631. if(vi->channels==2){
  115632. if(i==0)
  115633. _analysis_output("mask1L",seq,logmask,n/2,1,0,0);
  115634. else
  115635. _analysis_output("mask1R",seq,logmask,n/2,1,0,0);
  115636. }
  115637. #endif
  115638. /* this algorithm is hardwired to floor 1 for now; abort out if
  115639. we're *not* floor1. This won't happen unless someone has
  115640. broken the encode setup lib. Guard it anyway. */
  115641. if(ci->floor_type[info->floorsubmap[submap]]!=1)return(-1);
  115642. floor_posts[i][PACKETBLOBS/2]=
  115643. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115644. logmdct,
  115645. logmask);
  115646. /* are we managing bitrate? If so, perform two more fits for
  115647. later rate tweaking (fits represent hi/lo) */
  115648. if(vorbis_bitrate_managed(vb) && floor_posts[i][PACKETBLOBS/2]){
  115649. /* higher rate by way of lower noise curve */
  115650. _vp_offset_and_mix(psy_look,
  115651. noise,
  115652. tone,
  115653. 2,
  115654. logmask,
  115655. mdct,
  115656. logmdct);
  115657. #if 0
  115658. if(vi->channels==2){
  115659. if(i==0)
  115660. _analysis_output("mask2L",seq,logmask,n/2,1,0,0);
  115661. else
  115662. _analysis_output("mask2R",seq,logmask,n/2,1,0,0);
  115663. }
  115664. #endif
  115665. floor_posts[i][PACKETBLOBS-1]=
  115666. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115667. logmdct,
  115668. logmask);
  115669. /* lower rate by way of higher noise curve */
  115670. _vp_offset_and_mix(psy_look,
  115671. noise,
  115672. tone,
  115673. 0,
  115674. logmask,
  115675. mdct,
  115676. logmdct);
  115677. #if 0
  115678. if(vi->channels==2)
  115679. if(i==0)
  115680. _analysis_output("mask0L",seq,logmask,n/2,1,0,0);
  115681. else
  115682. _analysis_output("mask0R",seq,logmask,n/2,1,0,0);
  115683. #endif
  115684. floor_posts[i][0]=
  115685. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115686. logmdct,
  115687. logmask);
  115688. /* we also interpolate a range of intermediate curves for
  115689. intermediate rates */
  115690. for(k=1;k<PACKETBLOBS/2;k++)
  115691. floor_posts[i][k]=
  115692. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  115693. floor_posts[i][0],
  115694. floor_posts[i][PACKETBLOBS/2],
  115695. k*65536/(PACKETBLOBS/2));
  115696. for(k=PACKETBLOBS/2+1;k<PACKETBLOBS-1;k++)
  115697. floor_posts[i][k]=
  115698. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  115699. floor_posts[i][PACKETBLOBS/2],
  115700. floor_posts[i][PACKETBLOBS-1],
  115701. (k-PACKETBLOBS/2)*65536/(PACKETBLOBS/2));
  115702. }
  115703. }
  115704. }
  115705. vbi->ampmax=global_ampmax;
  115706. /*
  115707. the next phases are performed once for vbr-only and PACKETBLOB
  115708. times for bitrate managed modes.
  115709. 1) encode actual mode being used
  115710. 2) encode the floor for each channel, compute coded mask curve/res
  115711. 3) normalize and couple.
  115712. 4) encode residue
  115713. 5) save packet bytes to the packetblob vector
  115714. */
  115715. /* iterate over the many masking curve fits we've created */
  115716. {
  115717. float **res_bundle=(float**) alloca(sizeof(*res_bundle)*vi->channels);
  115718. float **couple_bundle=(float**) alloca(sizeof(*couple_bundle)*vi->channels);
  115719. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  115720. int **sortindex=(int**) alloca(sizeof(*sortindex)*vi->channels);
  115721. float **mag_memo;
  115722. int **mag_sort;
  115723. if(info->coupling_steps){
  115724. mag_memo=_vp_quantize_couple_memo(vb,
  115725. &ci->psy_g_param,
  115726. psy_look,
  115727. info,
  115728. gmdct);
  115729. mag_sort=_vp_quantize_couple_sort(vb,
  115730. psy_look,
  115731. info,
  115732. mag_memo);
  115733. hf_reduction(&ci->psy_g_param,
  115734. psy_look,
  115735. info,
  115736. mag_memo);
  115737. }
  115738. memset(sortindex,0,sizeof(*sortindex)*vi->channels);
  115739. if(psy_look->vi->normal_channel_p){
  115740. for(i=0;i<vi->channels;i++){
  115741. float *mdct =gmdct[i];
  115742. sortindex[i]=(int*) alloca(sizeof(**sortindex)*n/2);
  115743. _vp_noise_normalize_sort(psy_look,mdct,sortindex[i]);
  115744. }
  115745. }
  115746. for(k=(vorbis_bitrate_managed(vb)?0:PACKETBLOBS/2);
  115747. k<=(vorbis_bitrate_managed(vb)?PACKETBLOBS-1:PACKETBLOBS/2);
  115748. k++){
  115749. oggpack_buffer *opb=vbi->packetblob[k];
  115750. /* start out our new packet blob with packet type and mode */
  115751. /* Encode the packet type */
  115752. oggpack_write(opb,0,1);
  115753. /* Encode the modenumber */
  115754. /* Encode frame mode, pre,post windowsize, then dispatch */
  115755. oggpack_write(opb,modenumber,b->modebits);
  115756. if(vb->W){
  115757. oggpack_write(opb,vb->lW,1);
  115758. oggpack_write(opb,vb->nW,1);
  115759. }
  115760. /* encode floor, compute masking curve, sep out residue */
  115761. for(i=0;i<vi->channels;i++){
  115762. int submap=info->chmuxlist[i];
  115763. float *mdct =gmdct[i];
  115764. float *res =vb->pcm[i];
  115765. int *ilogmask=ilogmaskch[i]=
  115766. (int*) _vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  115767. nonzero[i]=floor1_encode(opb,vb,b->flr[info->floorsubmap[submap]],
  115768. floor_posts[i][k],
  115769. ilogmask);
  115770. #if 0
  115771. {
  115772. char buf[80];
  115773. sprintf(buf,"maskI%c%d",i?'R':'L',k);
  115774. float work[n/2];
  115775. for(j=0;j<n/2;j++)
  115776. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]];
  115777. _analysis_output(buf,seq,work,n/2,1,1,0);
  115778. }
  115779. #endif
  115780. _vp_remove_floor(psy_look,
  115781. mdct,
  115782. ilogmask,
  115783. res,
  115784. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  115785. _vp_noise_normalize(psy_look,res,res+n/2,sortindex[i]);
  115786. #if 0
  115787. {
  115788. char buf[80];
  115789. float work[n/2];
  115790. for(j=0;j<n/2;j++)
  115791. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]]*(res+n/2)[j];
  115792. sprintf(buf,"resI%c%d",i?'R':'L',k);
  115793. _analysis_output(buf,seq,work,n/2,1,1,0);
  115794. }
  115795. #endif
  115796. }
  115797. /* our iteration is now based on masking curve, not prequant and
  115798. coupling. Only one prequant/coupling step */
  115799. /* quantize/couple */
  115800. /* incomplete implementation that assumes the tree is all depth
  115801. one, or no tree at all */
  115802. if(info->coupling_steps){
  115803. _vp_couple(k,
  115804. &ci->psy_g_param,
  115805. psy_look,
  115806. info,
  115807. vb->pcm,
  115808. mag_memo,
  115809. mag_sort,
  115810. ilogmaskch,
  115811. nonzero,
  115812. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  115813. }
  115814. /* classify and encode by submap */
  115815. for(i=0;i<info->submaps;i++){
  115816. int ch_in_bundle=0;
  115817. long **classifications;
  115818. int resnum=info->residuesubmap[i];
  115819. for(j=0;j<vi->channels;j++){
  115820. if(info->chmuxlist[j]==i){
  115821. zerobundle[ch_in_bundle]=0;
  115822. if(nonzero[j])zerobundle[ch_in_bundle]=1;
  115823. res_bundle[ch_in_bundle]=vb->pcm[j];
  115824. couple_bundle[ch_in_bundle++]=vb->pcm[j]+n/2;
  115825. }
  115826. }
  115827. classifications=_residue_P[ci->residue_type[resnum]]->
  115828. classx(vb,b->residue[resnum],couple_bundle,zerobundle,ch_in_bundle);
  115829. _residue_P[ci->residue_type[resnum]]->
  115830. forward(opb,vb,b->residue[resnum],
  115831. couple_bundle,NULL,zerobundle,ch_in_bundle,classifications);
  115832. }
  115833. /* ok, done encoding. Next protopacket. */
  115834. }
  115835. }
  115836. #if 0
  115837. seq++;
  115838. total+=ci->blocksizes[vb->W]/4+ci->blocksizes[vb->nW]/4;
  115839. #endif
  115840. return(0);
  115841. }
  115842. static int mapping0_inverse(vorbis_block *vb,vorbis_info_mapping *l){
  115843. vorbis_dsp_state *vd=vb->vd;
  115844. vorbis_info *vi=vd->vi;
  115845. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  115846. private_state *b=(private_state*)vd->backend_state;
  115847. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)l;
  115848. int i,j;
  115849. long n=vb->pcmend=ci->blocksizes[vb->W];
  115850. float **pcmbundle=(float**) alloca(sizeof(*pcmbundle)*vi->channels);
  115851. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  115852. int *nonzero =(int*) alloca(sizeof(*nonzero)*vi->channels);
  115853. void **floormemo=(void**) alloca(sizeof(*floormemo)*vi->channels);
  115854. /* recover the spectral envelope; store it in the PCM vector for now */
  115855. for(i=0;i<vi->channels;i++){
  115856. int submap=info->chmuxlist[i];
  115857. floormemo[i]=_floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  115858. inverse1(vb,b->flr[info->floorsubmap[submap]]);
  115859. if(floormemo[i])
  115860. nonzero[i]=1;
  115861. else
  115862. nonzero[i]=0;
  115863. memset(vb->pcm[i],0,sizeof(*vb->pcm[i])*n/2);
  115864. }
  115865. /* channel coupling can 'dirty' the nonzero listing */
  115866. for(i=0;i<info->coupling_steps;i++){
  115867. if(nonzero[info->coupling_mag[i]] ||
  115868. nonzero[info->coupling_ang[i]]){
  115869. nonzero[info->coupling_mag[i]]=1;
  115870. nonzero[info->coupling_ang[i]]=1;
  115871. }
  115872. }
  115873. /* recover the residue into our working vectors */
  115874. for(i=0;i<info->submaps;i++){
  115875. int ch_in_bundle=0;
  115876. for(j=0;j<vi->channels;j++){
  115877. if(info->chmuxlist[j]==i){
  115878. if(nonzero[j])
  115879. zerobundle[ch_in_bundle]=1;
  115880. else
  115881. zerobundle[ch_in_bundle]=0;
  115882. pcmbundle[ch_in_bundle++]=vb->pcm[j];
  115883. }
  115884. }
  115885. _residue_P[ci->residue_type[info->residuesubmap[i]]]->
  115886. inverse(vb,b->residue[info->residuesubmap[i]],
  115887. pcmbundle,zerobundle,ch_in_bundle);
  115888. }
  115889. /* channel coupling */
  115890. for(i=info->coupling_steps-1;i>=0;i--){
  115891. float *pcmM=vb->pcm[info->coupling_mag[i]];
  115892. float *pcmA=vb->pcm[info->coupling_ang[i]];
  115893. for(j=0;j<n/2;j++){
  115894. float mag=pcmM[j];
  115895. float ang=pcmA[j];
  115896. if(mag>0)
  115897. if(ang>0){
  115898. pcmM[j]=mag;
  115899. pcmA[j]=mag-ang;
  115900. }else{
  115901. pcmA[j]=mag;
  115902. pcmM[j]=mag+ang;
  115903. }
  115904. else
  115905. if(ang>0){
  115906. pcmM[j]=mag;
  115907. pcmA[j]=mag+ang;
  115908. }else{
  115909. pcmA[j]=mag;
  115910. pcmM[j]=mag-ang;
  115911. }
  115912. }
  115913. }
  115914. /* compute and apply spectral envelope */
  115915. for(i=0;i<vi->channels;i++){
  115916. float *pcm=vb->pcm[i];
  115917. int submap=info->chmuxlist[i];
  115918. _floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  115919. inverse2(vb,b->flr[info->floorsubmap[submap]],
  115920. floormemo[i],pcm);
  115921. }
  115922. /* transform the PCM data; takes PCM vector, vb; modifies PCM vector */
  115923. /* only MDCT right now.... */
  115924. for(i=0;i<vi->channels;i++){
  115925. float *pcm=vb->pcm[i];
  115926. mdct_backward((mdct_lookup*) b->transform[vb->W][0],pcm,pcm);
  115927. }
  115928. /* all done! */
  115929. return(0);
  115930. }
  115931. /* export hooks */
  115932. vorbis_func_mapping mapping0_exportbundle={
  115933. &mapping0_pack,
  115934. &mapping0_unpack,
  115935. &mapping0_free_info,
  115936. &mapping0_forward,
  115937. &mapping0_inverse
  115938. };
  115939. #endif
  115940. /*** End of inlined file: mapping0.c ***/
  115941. /*** Start of inlined file: mdct.c ***/
  115942. /* this can also be run as an integer transform by uncommenting a
  115943. define in mdct.h; the integerization is a first pass and although
  115944. it's likely stable for Vorbis, the dynamic range is constrained and
  115945. roundoff isn't done (so it's noisy). Consider it functional, but
  115946. only a starting point. There's no point on a machine with an FPU */
  115947. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  115948. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  115949. // tasks..
  115950. #if JUCE_MSVC
  115951. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  115952. #endif
  115953. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  115954. #if JUCE_USE_OGGVORBIS
  115955. #include <stdio.h>
  115956. #include <stdlib.h>
  115957. #include <string.h>
  115958. #include <math.h>
  115959. /* build lookups for trig functions; also pre-figure scaling and
  115960. some window function algebra. */
  115961. void mdct_init(mdct_lookup *lookup,int n){
  115962. int *bitrev=(int*) _ogg_malloc(sizeof(*bitrev)*(n/4));
  115963. DATA_TYPE *T=(DATA_TYPE*) _ogg_malloc(sizeof(*T)*(n+n/4));
  115964. int i;
  115965. int n2=n>>1;
  115966. int log2n=lookup->log2n=rint(log((float)n)/log(2.f));
  115967. lookup->n=n;
  115968. lookup->trig=T;
  115969. lookup->bitrev=bitrev;
  115970. /* trig lookups... */
  115971. for(i=0;i<n/4;i++){
  115972. T[i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i)));
  115973. T[i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i)));
  115974. T[n2+i*2]=FLOAT_CONV(cos((M_PI/(2*n))*(2*i+1)));
  115975. T[n2+i*2+1]=FLOAT_CONV(sin((M_PI/(2*n))*(2*i+1)));
  115976. }
  115977. for(i=0;i<n/8;i++){
  115978. T[n+i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i+2))*.5);
  115979. T[n+i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i+2))*.5);
  115980. }
  115981. /* bitreverse lookup... */
  115982. {
  115983. int mask=(1<<(log2n-1))-1,i,j;
  115984. int msb=1<<(log2n-2);
  115985. for(i=0;i<n/8;i++){
  115986. int acc=0;
  115987. for(j=0;msb>>j;j++)
  115988. if((msb>>j)&i)acc|=1<<j;
  115989. bitrev[i*2]=((~acc)&mask)-1;
  115990. bitrev[i*2+1]=acc;
  115991. }
  115992. }
  115993. lookup->scale=FLOAT_CONV(4.f/n);
  115994. }
  115995. /* 8 point butterfly (in place, 4 register) */
  115996. STIN void mdct_butterfly_8(DATA_TYPE *x){
  115997. REG_TYPE r0 = x[6] + x[2];
  115998. REG_TYPE r1 = x[6] - x[2];
  115999. REG_TYPE r2 = x[4] + x[0];
  116000. REG_TYPE r3 = x[4] - x[0];
  116001. x[6] = r0 + r2;
  116002. x[4] = r0 - r2;
  116003. r0 = x[5] - x[1];
  116004. r2 = x[7] - x[3];
  116005. x[0] = r1 + r0;
  116006. x[2] = r1 - r0;
  116007. r0 = x[5] + x[1];
  116008. r1 = x[7] + x[3];
  116009. x[3] = r2 + r3;
  116010. x[1] = r2 - r3;
  116011. x[7] = r1 + r0;
  116012. x[5] = r1 - r0;
  116013. }
  116014. /* 16 point butterfly (in place, 4 register) */
  116015. STIN void mdct_butterfly_16(DATA_TYPE *x){
  116016. REG_TYPE r0 = x[1] - x[9];
  116017. REG_TYPE r1 = x[0] - x[8];
  116018. x[8] += x[0];
  116019. x[9] += x[1];
  116020. x[0] = MULT_NORM((r0 + r1) * cPI2_8);
  116021. x[1] = MULT_NORM((r0 - r1) * cPI2_8);
  116022. r0 = x[3] - x[11];
  116023. r1 = x[10] - x[2];
  116024. x[10] += x[2];
  116025. x[11] += x[3];
  116026. x[2] = r0;
  116027. x[3] = r1;
  116028. r0 = x[12] - x[4];
  116029. r1 = x[13] - x[5];
  116030. x[12] += x[4];
  116031. x[13] += x[5];
  116032. x[4] = MULT_NORM((r0 - r1) * cPI2_8);
  116033. x[5] = MULT_NORM((r0 + r1) * cPI2_8);
  116034. r0 = x[14] - x[6];
  116035. r1 = x[15] - x[7];
  116036. x[14] += x[6];
  116037. x[15] += x[7];
  116038. x[6] = r0;
  116039. x[7] = r1;
  116040. mdct_butterfly_8(x);
  116041. mdct_butterfly_8(x+8);
  116042. }
  116043. /* 32 point butterfly (in place, 4 register) */
  116044. STIN void mdct_butterfly_32(DATA_TYPE *x){
  116045. REG_TYPE r0 = x[30] - x[14];
  116046. REG_TYPE r1 = x[31] - x[15];
  116047. x[30] += x[14];
  116048. x[31] += x[15];
  116049. x[14] = r0;
  116050. x[15] = r1;
  116051. r0 = x[28] - x[12];
  116052. r1 = x[29] - x[13];
  116053. x[28] += x[12];
  116054. x[29] += x[13];
  116055. x[12] = MULT_NORM( r0 * cPI1_8 - r1 * cPI3_8 );
  116056. x[13] = MULT_NORM( r0 * cPI3_8 + r1 * cPI1_8 );
  116057. r0 = x[26] - x[10];
  116058. r1 = x[27] - x[11];
  116059. x[26] += x[10];
  116060. x[27] += x[11];
  116061. x[10] = MULT_NORM(( r0 - r1 ) * cPI2_8);
  116062. x[11] = MULT_NORM(( r0 + r1 ) * cPI2_8);
  116063. r0 = x[24] - x[8];
  116064. r1 = x[25] - x[9];
  116065. x[24] += x[8];
  116066. x[25] += x[9];
  116067. x[8] = MULT_NORM( r0 * cPI3_8 - r1 * cPI1_8 );
  116068. x[9] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  116069. r0 = x[22] - x[6];
  116070. r1 = x[7] - x[23];
  116071. x[22] += x[6];
  116072. x[23] += x[7];
  116073. x[6] = r1;
  116074. x[7] = r0;
  116075. r0 = x[4] - x[20];
  116076. r1 = x[5] - x[21];
  116077. x[20] += x[4];
  116078. x[21] += x[5];
  116079. x[4] = MULT_NORM( r1 * cPI1_8 + r0 * cPI3_8 );
  116080. x[5] = MULT_NORM( r1 * cPI3_8 - r0 * cPI1_8 );
  116081. r0 = x[2] - x[18];
  116082. r1 = x[3] - x[19];
  116083. x[18] += x[2];
  116084. x[19] += x[3];
  116085. x[2] = MULT_NORM(( r1 + r0 ) * cPI2_8);
  116086. x[3] = MULT_NORM(( r1 - r0 ) * cPI2_8);
  116087. r0 = x[0] - x[16];
  116088. r1 = x[1] - x[17];
  116089. x[16] += x[0];
  116090. x[17] += x[1];
  116091. x[0] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  116092. x[1] = MULT_NORM( r1 * cPI1_8 - r0 * cPI3_8 );
  116093. mdct_butterfly_16(x);
  116094. mdct_butterfly_16(x+16);
  116095. }
  116096. /* N point first stage butterfly (in place, 2 register) */
  116097. STIN void mdct_butterfly_first(DATA_TYPE *T,
  116098. DATA_TYPE *x,
  116099. int points){
  116100. DATA_TYPE *x1 = x + points - 8;
  116101. DATA_TYPE *x2 = x + (points>>1) - 8;
  116102. REG_TYPE r0;
  116103. REG_TYPE r1;
  116104. do{
  116105. r0 = x1[6] - x2[6];
  116106. r1 = x1[7] - x2[7];
  116107. x1[6] += x2[6];
  116108. x1[7] += x2[7];
  116109. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116110. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116111. r0 = x1[4] - x2[4];
  116112. r1 = x1[5] - x2[5];
  116113. x1[4] += x2[4];
  116114. x1[5] += x2[5];
  116115. x2[4] = MULT_NORM(r1 * T[5] + r0 * T[4]);
  116116. x2[5] = MULT_NORM(r1 * T[4] - r0 * T[5]);
  116117. r0 = x1[2] - x2[2];
  116118. r1 = x1[3] - x2[3];
  116119. x1[2] += x2[2];
  116120. x1[3] += x2[3];
  116121. x2[2] = MULT_NORM(r1 * T[9] + r0 * T[8]);
  116122. x2[3] = MULT_NORM(r1 * T[8] - r0 * T[9]);
  116123. r0 = x1[0] - x2[0];
  116124. r1 = x1[1] - x2[1];
  116125. x1[0] += x2[0];
  116126. x1[1] += x2[1];
  116127. x2[0] = MULT_NORM(r1 * T[13] + r0 * T[12]);
  116128. x2[1] = MULT_NORM(r1 * T[12] - r0 * T[13]);
  116129. x1-=8;
  116130. x2-=8;
  116131. T+=16;
  116132. }while(x2>=x);
  116133. }
  116134. /* N/stage point generic N stage butterfly (in place, 2 register) */
  116135. STIN void mdct_butterfly_generic(DATA_TYPE *T,
  116136. DATA_TYPE *x,
  116137. int points,
  116138. int trigint){
  116139. DATA_TYPE *x1 = x + points - 8;
  116140. DATA_TYPE *x2 = x + (points>>1) - 8;
  116141. REG_TYPE r0;
  116142. REG_TYPE r1;
  116143. do{
  116144. r0 = x1[6] - x2[6];
  116145. r1 = x1[7] - x2[7];
  116146. x1[6] += x2[6];
  116147. x1[7] += x2[7];
  116148. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116149. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116150. T+=trigint;
  116151. r0 = x1[4] - x2[4];
  116152. r1 = x1[5] - x2[5];
  116153. x1[4] += x2[4];
  116154. x1[5] += x2[5];
  116155. x2[4] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116156. x2[5] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116157. T+=trigint;
  116158. r0 = x1[2] - x2[2];
  116159. r1 = x1[3] - x2[3];
  116160. x1[2] += x2[2];
  116161. x1[3] += x2[3];
  116162. x2[2] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116163. x2[3] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116164. T+=trigint;
  116165. r0 = x1[0] - x2[0];
  116166. r1 = x1[1] - x2[1];
  116167. x1[0] += x2[0];
  116168. x1[1] += x2[1];
  116169. x2[0] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116170. x2[1] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116171. T+=trigint;
  116172. x1-=8;
  116173. x2-=8;
  116174. }while(x2>=x);
  116175. }
  116176. STIN void mdct_butterflies(mdct_lookup *init,
  116177. DATA_TYPE *x,
  116178. int points){
  116179. DATA_TYPE *T=init->trig;
  116180. int stages=init->log2n-5;
  116181. int i,j;
  116182. if(--stages>0){
  116183. mdct_butterfly_first(T,x,points);
  116184. }
  116185. for(i=1;--stages>0;i++){
  116186. for(j=0;j<(1<<i);j++)
  116187. mdct_butterfly_generic(T,x+(points>>i)*j,points>>i,4<<i);
  116188. }
  116189. for(j=0;j<points;j+=32)
  116190. mdct_butterfly_32(x+j);
  116191. }
  116192. void mdct_clear(mdct_lookup *l){
  116193. if(l){
  116194. if(l->trig)_ogg_free(l->trig);
  116195. if(l->bitrev)_ogg_free(l->bitrev);
  116196. memset(l,0,sizeof(*l));
  116197. }
  116198. }
  116199. STIN void mdct_bitreverse(mdct_lookup *init,
  116200. DATA_TYPE *x){
  116201. int n = init->n;
  116202. int *bit = init->bitrev;
  116203. DATA_TYPE *w0 = x;
  116204. DATA_TYPE *w1 = x = w0+(n>>1);
  116205. DATA_TYPE *T = init->trig+n;
  116206. do{
  116207. DATA_TYPE *x0 = x+bit[0];
  116208. DATA_TYPE *x1 = x+bit[1];
  116209. REG_TYPE r0 = x0[1] - x1[1];
  116210. REG_TYPE r1 = x0[0] + x1[0];
  116211. REG_TYPE r2 = MULT_NORM(r1 * T[0] + r0 * T[1]);
  116212. REG_TYPE r3 = MULT_NORM(r1 * T[1] - r0 * T[0]);
  116213. w1 -= 4;
  116214. r0 = HALVE(x0[1] + x1[1]);
  116215. r1 = HALVE(x0[0] - x1[0]);
  116216. w0[0] = r0 + r2;
  116217. w1[2] = r0 - r2;
  116218. w0[1] = r1 + r3;
  116219. w1[3] = r3 - r1;
  116220. x0 = x+bit[2];
  116221. x1 = x+bit[3];
  116222. r0 = x0[1] - x1[1];
  116223. r1 = x0[0] + x1[0];
  116224. r2 = MULT_NORM(r1 * T[2] + r0 * T[3]);
  116225. r3 = MULT_NORM(r1 * T[3] - r0 * T[2]);
  116226. r0 = HALVE(x0[1] + x1[1]);
  116227. r1 = HALVE(x0[0] - x1[0]);
  116228. w0[2] = r0 + r2;
  116229. w1[0] = r0 - r2;
  116230. w0[3] = r1 + r3;
  116231. w1[1] = r3 - r1;
  116232. T += 4;
  116233. bit += 4;
  116234. w0 += 4;
  116235. }while(w0<w1);
  116236. }
  116237. void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  116238. int n=init->n;
  116239. int n2=n>>1;
  116240. int n4=n>>2;
  116241. /* rotate */
  116242. DATA_TYPE *iX = in+n2-7;
  116243. DATA_TYPE *oX = out+n2+n4;
  116244. DATA_TYPE *T = init->trig+n4;
  116245. do{
  116246. oX -= 4;
  116247. oX[0] = MULT_NORM(-iX[2] * T[3] - iX[0] * T[2]);
  116248. oX[1] = MULT_NORM (iX[0] * T[3] - iX[2] * T[2]);
  116249. oX[2] = MULT_NORM(-iX[6] * T[1] - iX[4] * T[0]);
  116250. oX[3] = MULT_NORM (iX[4] * T[1] - iX[6] * T[0]);
  116251. iX -= 8;
  116252. T += 4;
  116253. }while(iX>=in);
  116254. iX = in+n2-8;
  116255. oX = out+n2+n4;
  116256. T = init->trig+n4;
  116257. do{
  116258. T -= 4;
  116259. oX[0] = MULT_NORM (iX[4] * T[3] + iX[6] * T[2]);
  116260. oX[1] = MULT_NORM (iX[4] * T[2] - iX[6] * T[3]);
  116261. oX[2] = MULT_NORM (iX[0] * T[1] + iX[2] * T[0]);
  116262. oX[3] = MULT_NORM (iX[0] * T[0] - iX[2] * T[1]);
  116263. iX -= 8;
  116264. oX += 4;
  116265. }while(iX>=in);
  116266. mdct_butterflies(init,out+n2,n2);
  116267. mdct_bitreverse(init,out);
  116268. /* roatate + window */
  116269. {
  116270. DATA_TYPE *oX1=out+n2+n4;
  116271. DATA_TYPE *oX2=out+n2+n4;
  116272. DATA_TYPE *iX =out;
  116273. T =init->trig+n2;
  116274. do{
  116275. oX1-=4;
  116276. oX1[3] = MULT_NORM (iX[0] * T[1] - iX[1] * T[0]);
  116277. oX2[0] = -MULT_NORM (iX[0] * T[0] + iX[1] * T[1]);
  116278. oX1[2] = MULT_NORM (iX[2] * T[3] - iX[3] * T[2]);
  116279. oX2[1] = -MULT_NORM (iX[2] * T[2] + iX[3] * T[3]);
  116280. oX1[1] = MULT_NORM (iX[4] * T[5] - iX[5] * T[4]);
  116281. oX2[2] = -MULT_NORM (iX[4] * T[4] + iX[5] * T[5]);
  116282. oX1[0] = MULT_NORM (iX[6] * T[7] - iX[7] * T[6]);
  116283. oX2[3] = -MULT_NORM (iX[6] * T[6] + iX[7] * T[7]);
  116284. oX2+=4;
  116285. iX += 8;
  116286. T += 8;
  116287. }while(iX<oX1);
  116288. iX=out+n2+n4;
  116289. oX1=out+n4;
  116290. oX2=oX1;
  116291. do{
  116292. oX1-=4;
  116293. iX-=4;
  116294. oX2[0] = -(oX1[3] = iX[3]);
  116295. oX2[1] = -(oX1[2] = iX[2]);
  116296. oX2[2] = -(oX1[1] = iX[1]);
  116297. oX2[3] = -(oX1[0] = iX[0]);
  116298. oX2+=4;
  116299. }while(oX2<iX);
  116300. iX=out+n2+n4;
  116301. oX1=out+n2+n4;
  116302. oX2=out+n2;
  116303. do{
  116304. oX1-=4;
  116305. oX1[0]= iX[3];
  116306. oX1[1]= iX[2];
  116307. oX1[2]= iX[1];
  116308. oX1[3]= iX[0];
  116309. iX+=4;
  116310. }while(oX1>oX2);
  116311. }
  116312. }
  116313. void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  116314. int n=init->n;
  116315. int n2=n>>1;
  116316. int n4=n>>2;
  116317. int n8=n>>3;
  116318. DATA_TYPE *w=(DATA_TYPE*) alloca(n*sizeof(*w)); /* forward needs working space */
  116319. DATA_TYPE *w2=w+n2;
  116320. /* rotate */
  116321. /* window + rotate + step 1 */
  116322. REG_TYPE r0;
  116323. REG_TYPE r1;
  116324. DATA_TYPE *x0=in+n2+n4;
  116325. DATA_TYPE *x1=x0+1;
  116326. DATA_TYPE *T=init->trig+n2;
  116327. int i=0;
  116328. for(i=0;i<n8;i+=2){
  116329. x0 -=4;
  116330. T-=2;
  116331. r0= x0[2] + x1[0];
  116332. r1= x0[0] + x1[2];
  116333. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  116334. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  116335. x1 +=4;
  116336. }
  116337. x1=in+1;
  116338. for(;i<n2-n8;i+=2){
  116339. T-=2;
  116340. x0 -=4;
  116341. r0= x0[2] - x1[0];
  116342. r1= x0[0] - x1[2];
  116343. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  116344. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  116345. x1 +=4;
  116346. }
  116347. x0=in+n;
  116348. for(;i<n2;i+=2){
  116349. T-=2;
  116350. x0 -=4;
  116351. r0= -x0[2] - x1[0];
  116352. r1= -x0[0] - x1[2];
  116353. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  116354. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  116355. x1 +=4;
  116356. }
  116357. mdct_butterflies(init,w+n2,n2);
  116358. mdct_bitreverse(init,w);
  116359. /* roatate + window */
  116360. T=init->trig+n2;
  116361. x0=out+n2;
  116362. for(i=0;i<n4;i++){
  116363. x0--;
  116364. out[i] =MULT_NORM((w[0]*T[0]+w[1]*T[1])*init->scale);
  116365. x0[0] =MULT_NORM((w[0]*T[1]-w[1]*T[0])*init->scale);
  116366. w+=2;
  116367. T+=2;
  116368. }
  116369. }
  116370. #endif
  116371. /*** End of inlined file: mdct.c ***/
  116372. /*** Start of inlined file: psy.c ***/
  116373. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  116374. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  116375. // tasks..
  116376. #if JUCE_MSVC
  116377. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  116378. #endif
  116379. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  116380. #if JUCE_USE_OGGVORBIS
  116381. #include <stdlib.h>
  116382. #include <math.h>
  116383. #include <string.h>
  116384. /*** Start of inlined file: masking.h ***/
  116385. #ifndef _V_MASKING_H_
  116386. #define _V_MASKING_H_
  116387. /* more detailed ATH; the bass if flat to save stressing the floor
  116388. overly for only a bin or two of savings. */
  116389. #define MAX_ATH 88
  116390. static float ATH[]={
  116391. /*15*/ -51, -52, -53, -54, -55, -56, -57, -58,
  116392. /*31*/ -59, -60, -61, -62, -63, -64, -65, -66,
  116393. /*63*/ -67, -68, -69, -70, -71, -72, -73, -74,
  116394. /*125*/ -75, -76, -77, -78, -80, -81, -82, -83,
  116395. /*250*/ -84, -85, -86, -87, -88, -88, -89, -89,
  116396. /*500*/ -90, -91, -91, -92, -93, -94, -95, -96,
  116397. /*1k*/ -96, -97, -98, -98, -99, -99,-100,-100,
  116398. /*2k*/ -101,-102,-103,-104,-106,-107,-107,-107,
  116399. /*4k*/ -107,-105,-103,-102,-101, -99, -98, -96,
  116400. /*8k*/ -95, -95, -96, -97, -96, -95, -93, -90,
  116401. /*16k*/ -80, -70, -50, -40, -30, -30, -30, -30
  116402. };
  116403. /* The tone masking curves from Ehmer's and Fielder's papers have been
  116404. replaced by an empirically collected data set. The previously
  116405. published values were, far too often, simply on crack. */
  116406. #define EHMER_OFFSET 16
  116407. #define EHMER_MAX 56
  116408. /* masking tones from -50 to 0dB, 62.5 through 16kHz at half octaves
  116409. test tones from -2 octaves to +5 octaves sampled at eighth octaves */
  116410. /* (Vorbis 0dB, the loudest possible tone, is assumed to be ~100dB SPL
  116411. for collection of these curves) */
  116412. static float tonemasks[P_BANDS][6][EHMER_MAX]={
  116413. /* 62.5 Hz */
  116414. {{ -60, -60, -60, -60, -60, -60, -60, -60,
  116415. -60, -60, -60, -60, -62, -62, -65, -73,
  116416. -69, -68, -68, -67, -70, -70, -72, -74,
  116417. -75, -79, -79, -80, -83, -88, -93, -100,
  116418. -110, -999, -999, -999, -999, -999, -999, -999,
  116419. -999, -999, -999, -999, -999, -999, -999, -999,
  116420. -999, -999, -999, -999, -999, -999, -999, -999},
  116421. { -48, -48, -48, -48, -48, -48, -48, -48,
  116422. -48, -48, -48, -48, -48, -53, -61, -66,
  116423. -66, -68, -67, -70, -76, -76, -72, -73,
  116424. -75, -76, -78, -79, -83, -88, -93, -100,
  116425. -110, -999, -999, -999, -999, -999, -999, -999,
  116426. -999, -999, -999, -999, -999, -999, -999, -999,
  116427. -999, -999, -999, -999, -999, -999, -999, -999},
  116428. { -37, -37, -37, -37, -37, -37, -37, -37,
  116429. -38, -40, -42, -46, -48, -53, -55, -62,
  116430. -65, -58, -56, -56, -61, -60, -65, -67,
  116431. -69, -71, -77, -77, -78, -80, -82, -84,
  116432. -88, -93, -98, -106, -112, -999, -999, -999,
  116433. -999, -999, -999, -999, -999, -999, -999, -999,
  116434. -999, -999, -999, -999, -999, -999, -999, -999},
  116435. { -25, -25, -25, -25, -25, -25, -25, -25,
  116436. -25, -26, -27, -29, -32, -38, -48, -52,
  116437. -52, -50, -48, -48, -51, -52, -54, -60,
  116438. -67, -67, -66, -68, -69, -73, -73, -76,
  116439. -80, -81, -81, -85, -85, -86, -88, -93,
  116440. -100, -110, -999, -999, -999, -999, -999, -999,
  116441. -999, -999, -999, -999, -999, -999, -999, -999},
  116442. { -16, -16, -16, -16, -16, -16, -16, -16,
  116443. -17, -19, -20, -22, -26, -28, -31, -40,
  116444. -47, -39, -39, -40, -42, -43, -47, -51,
  116445. -57, -52, -55, -55, -60, -58, -62, -63,
  116446. -70, -67, -69, -72, -73, -77, -80, -82,
  116447. -83, -87, -90, -94, -98, -104, -115, -999,
  116448. -999, -999, -999, -999, -999, -999, -999, -999},
  116449. { -8, -8, -8, -8, -8, -8, -8, -8,
  116450. -8, -8, -10, -11, -15, -19, -25, -30,
  116451. -34, -31, -30, -31, -29, -32, -35, -42,
  116452. -48, -42, -44, -46, -50, -50, -51, -52,
  116453. -59, -54, -55, -55, -58, -62, -63, -66,
  116454. -72, -73, -76, -75, -78, -80, -80, -81,
  116455. -84, -88, -90, -94, -98, -101, -106, -110}},
  116456. /* 88Hz */
  116457. {{ -66, -66, -66, -66, -66, -66, -66, -66,
  116458. -66, -66, -66, -66, -66, -67, -67, -67,
  116459. -76, -72, -71, -74, -76, -76, -75, -78,
  116460. -79, -79, -81, -83, -86, -89, -93, -97,
  116461. -100, -105, -110, -999, -999, -999, -999, -999,
  116462. -999, -999, -999, -999, -999, -999, -999, -999,
  116463. -999, -999, -999, -999, -999, -999, -999, -999},
  116464. { -47, -47, -47, -47, -47, -47, -47, -47,
  116465. -47, -47, -47, -48, -51, -55, -59, -66,
  116466. -66, -66, -67, -66, -68, -69, -70, -74,
  116467. -79, -77, -77, -78, -80, -81, -82, -84,
  116468. -86, -88, -91, -95, -100, -108, -116, -999,
  116469. -999, -999, -999, -999, -999, -999, -999, -999,
  116470. -999, -999, -999, -999, -999, -999, -999, -999},
  116471. { -36, -36, -36, -36, -36, -36, -36, -36,
  116472. -36, -37, -37, -41, -44, -48, -51, -58,
  116473. -62, -60, -57, -59, -59, -60, -63, -65,
  116474. -72, -71, -70, -72, -74, -77, -76, -78,
  116475. -81, -81, -80, -83, -86, -91, -96, -100,
  116476. -105, -110, -999, -999, -999, -999, -999, -999,
  116477. -999, -999, -999, -999, -999, -999, -999, -999},
  116478. { -28, -28, -28, -28, -28, -28, -28, -28,
  116479. -28, -30, -32, -32, -33, -35, -41, -49,
  116480. -50, -49, -47, -48, -48, -52, -51, -57,
  116481. -65, -61, -59, -61, -64, -69, -70, -74,
  116482. -77, -77, -78, -81, -84, -85, -87, -90,
  116483. -92, -96, -100, -107, -112, -999, -999, -999,
  116484. -999, -999, -999, -999, -999, -999, -999, -999},
  116485. { -19, -19, -19, -19, -19, -19, -19, -19,
  116486. -20, -21, -23, -27, -30, -35, -36, -41,
  116487. -46, -44, -42, -40, -41, -41, -43, -48,
  116488. -55, -53, -52, -53, -56, -59, -58, -60,
  116489. -67, -66, -69, -71, -72, -75, -79, -81,
  116490. -84, -87, -90, -93, -97, -101, -107, -114,
  116491. -999, -999, -999, -999, -999, -999, -999, -999},
  116492. { -9, -9, -9, -9, -9, -9, -9, -9,
  116493. -11, -12, -12, -15, -16, -20, -23, -30,
  116494. -37, -34, -33, -34, -31, -32, -32, -38,
  116495. -47, -44, -41, -40, -47, -49, -46, -46,
  116496. -58, -50, -50, -54, -58, -62, -64, -67,
  116497. -67, -70, -72, -76, -79, -83, -87, -91,
  116498. -96, -100, -104, -110, -999, -999, -999, -999}},
  116499. /* 125 Hz */
  116500. {{ -62, -62, -62, -62, -62, -62, -62, -62,
  116501. -62, -62, -63, -64, -66, -67, -66, -68,
  116502. -75, -72, -76, -75, -76, -78, -79, -82,
  116503. -84, -85, -90, -94, -101, -110, -999, -999,
  116504. -999, -999, -999, -999, -999, -999, -999, -999,
  116505. -999, -999, -999, -999, -999, -999, -999, -999,
  116506. -999, -999, -999, -999, -999, -999, -999, -999},
  116507. { -59, -59, -59, -59, -59, -59, -59, -59,
  116508. -59, -59, -59, -60, -60, -61, -63, -66,
  116509. -71, -68, -70, -70, -71, -72, -72, -75,
  116510. -81, -78, -79, -82, -83, -86, -90, -97,
  116511. -103, -113, -999, -999, -999, -999, -999, -999,
  116512. -999, -999, -999, -999, -999, -999, -999, -999,
  116513. -999, -999, -999, -999, -999, -999, -999, -999},
  116514. { -53, -53, -53, -53, -53, -53, -53, -53,
  116515. -53, -54, -55, -57, -56, -57, -55, -61,
  116516. -65, -60, -60, -62, -63, -63, -66, -68,
  116517. -74, -73, -75, -75, -78, -80, -80, -82,
  116518. -85, -90, -96, -101, -108, -999, -999, -999,
  116519. -999, -999, -999, -999, -999, -999, -999, -999,
  116520. -999, -999, -999, -999, -999, -999, -999, -999},
  116521. { -46, -46, -46, -46, -46, -46, -46, -46,
  116522. -46, -46, -47, -47, -47, -47, -48, -51,
  116523. -57, -51, -49, -50, -51, -53, -54, -59,
  116524. -66, -60, -62, -67, -67, -70, -72, -75,
  116525. -76, -78, -81, -85, -88, -94, -97, -104,
  116526. -112, -999, -999, -999, -999, -999, -999, -999,
  116527. -999, -999, -999, -999, -999, -999, -999, -999},
  116528. { -36, -36, -36, -36, -36, -36, -36, -36,
  116529. -39, -41, -42, -42, -39, -38, -41, -43,
  116530. -52, -44, -40, -39, -37, -37, -40, -47,
  116531. -54, -50, -48, -50, -55, -61, -59, -62,
  116532. -66, -66, -66, -69, -69, -73, -74, -74,
  116533. -75, -77, -79, -82, -87, -91, -95, -100,
  116534. -108, -115, -999, -999, -999, -999, -999, -999},
  116535. { -28, -26, -24, -22, -20, -20, -23, -29,
  116536. -30, -31, -28, -27, -28, -28, -28, -35,
  116537. -40, -33, -32, -29, -30, -30, -30, -37,
  116538. -45, -41, -37, -38, -45, -47, -47, -48,
  116539. -53, -49, -48, -50, -49, -49, -51, -52,
  116540. -58, -56, -57, -56, -60, -61, -62, -70,
  116541. -72, -74, -78, -83, -88, -93, -100, -106}},
  116542. /* 177 Hz */
  116543. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116544. -999, -110, -105, -100, -95, -91, -87, -83,
  116545. -80, -78, -76, -78, -78, -81, -83, -85,
  116546. -86, -85, -86, -87, -90, -97, -107, -999,
  116547. -999, -999, -999, -999, -999, -999, -999, -999,
  116548. -999, -999, -999, -999, -999, -999, -999, -999,
  116549. -999, -999, -999, -999, -999, -999, -999, -999},
  116550. {-999, -999, -999, -110, -105, -100, -95, -90,
  116551. -85, -81, -77, -73, -70, -67, -67, -68,
  116552. -75, -73, -70, -69, -70, -72, -75, -79,
  116553. -84, -83, -84, -86, -88, -89, -89, -93,
  116554. -98, -105, -112, -999, -999, -999, -999, -999,
  116555. -999, -999, -999, -999, -999, -999, -999, -999,
  116556. -999, -999, -999, -999, -999, -999, -999, -999},
  116557. {-105, -100, -95, -90, -85, -80, -76, -71,
  116558. -68, -68, -65, -63, -63, -62, -62, -64,
  116559. -65, -64, -61, -62, -63, -64, -66, -68,
  116560. -73, -73, -74, -75, -76, -81, -83, -85,
  116561. -88, -89, -92, -95, -100, -108, -999, -999,
  116562. -999, -999, -999, -999, -999, -999, -999, -999,
  116563. -999, -999, -999, -999, -999, -999, -999, -999},
  116564. { -80, -75, -71, -68, -65, -63, -62, -61,
  116565. -61, -61, -61, -59, -56, -57, -53, -50,
  116566. -58, -52, -50, -50, -52, -53, -54, -58,
  116567. -67, -63, -67, -68, -72, -75, -78, -80,
  116568. -81, -81, -82, -85, -89, -90, -93, -97,
  116569. -101, -107, -114, -999, -999, -999, -999, -999,
  116570. -999, -999, -999, -999, -999, -999, -999, -999},
  116571. { -65, -61, -59, -57, -56, -55, -55, -56,
  116572. -56, -57, -55, -53, -52, -47, -44, -44,
  116573. -50, -44, -41, -39, -39, -42, -40, -46,
  116574. -51, -49, -50, -53, -54, -63, -60, -61,
  116575. -62, -66, -66, -66, -70, -73, -74, -75,
  116576. -76, -75, -79, -85, -89, -91, -96, -102,
  116577. -110, -999, -999, -999, -999, -999, -999, -999},
  116578. { -52, -50, -49, -49, -48, -48, -48, -49,
  116579. -50, -50, -49, -46, -43, -39, -35, -33,
  116580. -38, -36, -32, -29, -32, -32, -32, -35,
  116581. -44, -39, -38, -38, -46, -50, -45, -46,
  116582. -53, -50, -50, -50, -54, -54, -53, -53,
  116583. -56, -57, -59, -66, -70, -72, -74, -79,
  116584. -83, -85, -90, -97, -114, -999, -999, -999}},
  116585. /* 250 Hz */
  116586. {{-999, -999, -999, -999, -999, -999, -110, -105,
  116587. -100, -95, -90, -86, -80, -75, -75, -79,
  116588. -80, -79, -80, -81, -82, -88, -95, -103,
  116589. -110, -999, -999, -999, -999, -999, -999, -999,
  116590. -999, -999, -999, -999, -999, -999, -999, -999,
  116591. -999, -999, -999, -999, -999, -999, -999, -999,
  116592. -999, -999, -999, -999, -999, -999, -999, -999},
  116593. {-999, -999, -999, -999, -108, -103, -98, -93,
  116594. -88, -83, -79, -78, -75, -71, -67, -68,
  116595. -73, -73, -72, -73, -75, -77, -80, -82,
  116596. -88, -93, -100, -107, -114, -999, -999, -999,
  116597. -999, -999, -999, -999, -999, -999, -999, -999,
  116598. -999, -999, -999, -999, -999, -999, -999, -999,
  116599. -999, -999, -999, -999, -999, -999, -999, -999},
  116600. {-999, -999, -999, -110, -105, -101, -96, -90,
  116601. -86, -81, -77, -73, -69, -66, -61, -62,
  116602. -66, -64, -62, -65, -66, -70, -72, -76,
  116603. -81, -80, -84, -90, -95, -102, -110, -999,
  116604. -999, -999, -999, -999, -999, -999, -999, -999,
  116605. -999, -999, -999, -999, -999, -999, -999, -999,
  116606. -999, -999, -999, -999, -999, -999, -999, -999},
  116607. {-999, -999, -999, -107, -103, -97, -92, -88,
  116608. -83, -79, -74, -70, -66, -59, -53, -58,
  116609. -62, -55, -54, -54, -54, -58, -61, -62,
  116610. -72, -70, -72, -75, -78, -80, -81, -80,
  116611. -83, -83, -88, -93, -100, -107, -115, -999,
  116612. -999, -999, -999, -999, -999, -999, -999, -999,
  116613. -999, -999, -999, -999, -999, -999, -999, -999},
  116614. {-999, -999, -999, -105, -100, -95, -90, -85,
  116615. -80, -75, -70, -66, -62, -56, -48, -44,
  116616. -48, -46, -46, -43, -46, -48, -48, -51,
  116617. -58, -58, -59, -60, -62, -62, -61, -61,
  116618. -65, -64, -65, -68, -70, -74, -75, -78,
  116619. -81, -86, -95, -110, -999, -999, -999, -999,
  116620. -999, -999, -999, -999, -999, -999, -999, -999},
  116621. {-999, -999, -105, -100, -95, -90, -85, -80,
  116622. -75, -70, -65, -61, -55, -49, -39, -33,
  116623. -40, -35, -32, -38, -40, -33, -35, -37,
  116624. -46, -41, -45, -44, -46, -42, -45, -46,
  116625. -52, -50, -50, -50, -54, -54, -55, -57,
  116626. -62, -64, -66, -68, -70, -76, -81, -90,
  116627. -100, -110, -999, -999, -999, -999, -999, -999}},
  116628. /* 354 hz */
  116629. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116630. -105, -98, -90, -85, -82, -83, -80, -78,
  116631. -84, -79, -80, -83, -87, -89, -91, -93,
  116632. -99, -106, -117, -999, -999, -999, -999, -999,
  116633. -999, -999, -999, -999, -999, -999, -999, -999,
  116634. -999, -999, -999, -999, -999, -999, -999, -999,
  116635. -999, -999, -999, -999, -999, -999, -999, -999},
  116636. {-999, -999, -999, -999, -999, -999, -999, -999,
  116637. -105, -98, -90, -85, -80, -75, -70, -68,
  116638. -74, -72, -74, -77, -80, -82, -85, -87,
  116639. -92, -89, -91, -95, -100, -106, -112, -999,
  116640. -999, -999, -999, -999, -999, -999, -999, -999,
  116641. -999, -999, -999, -999, -999, -999, -999, -999,
  116642. -999, -999, -999, -999, -999, -999, -999, -999},
  116643. {-999, -999, -999, -999, -999, -999, -999, -999,
  116644. -105, -98, -90, -83, -75, -71, -63, -64,
  116645. -67, -62, -64, -67, -70, -73, -77, -81,
  116646. -84, -83, -85, -89, -90, -93, -98, -104,
  116647. -109, -114, -999, -999, -999, -999, -999, -999,
  116648. -999, -999, -999, -999, -999, -999, -999, -999,
  116649. -999, -999, -999, -999, -999, -999, -999, -999},
  116650. {-999, -999, -999, -999, -999, -999, -999, -999,
  116651. -103, -96, -88, -81, -75, -68, -58, -54,
  116652. -56, -54, -56, -56, -58, -60, -63, -66,
  116653. -74, -69, -72, -72, -75, -74, -77, -81,
  116654. -81, -82, -84, -87, -93, -96, -99, -104,
  116655. -110, -999, -999, -999, -999, -999, -999, -999,
  116656. -999, -999, -999, -999, -999, -999, -999, -999},
  116657. {-999, -999, -999, -999, -999, -108, -102, -96,
  116658. -91, -85, -80, -74, -68, -60, -51, -46,
  116659. -48, -46, -43, -45, -47, -47, -49, -48,
  116660. -56, -53, -55, -58, -57, -63, -58, -60,
  116661. -66, -64, -67, -70, -70, -74, -77, -84,
  116662. -86, -89, -91, -93, -94, -101, -109, -118,
  116663. -999, -999, -999, -999, -999, -999, -999, -999},
  116664. {-999, -999, -999, -108, -103, -98, -93, -88,
  116665. -83, -78, -73, -68, -60, -53, -44, -35,
  116666. -38, -38, -34, -34, -36, -40, -41, -44,
  116667. -51, -45, -46, -47, -46, -54, -50, -49,
  116668. -50, -50, -50, -51, -54, -57, -58, -60,
  116669. -66, -66, -66, -64, -65, -68, -77, -82,
  116670. -87, -95, -110, -999, -999, -999, -999, -999}},
  116671. /* 500 Hz */
  116672. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116673. -107, -102, -97, -92, -87, -83, -78, -75,
  116674. -82, -79, -83, -85, -89, -92, -95, -98,
  116675. -101, -105, -109, -113, -999, -999, -999, -999,
  116676. -999, -999, -999, -999, -999, -999, -999, -999,
  116677. -999, -999, -999, -999, -999, -999, -999, -999,
  116678. -999, -999, -999, -999, -999, -999, -999, -999},
  116679. {-999, -999, -999, -999, -999, -999, -999, -106,
  116680. -100, -95, -90, -86, -81, -78, -74, -69,
  116681. -74, -74, -76, -79, -83, -84, -86, -89,
  116682. -92, -97, -93, -100, -103, -107, -110, -999,
  116683. -999, -999, -999, -999, -999, -999, -999, -999,
  116684. -999, -999, -999, -999, -999, -999, -999, -999,
  116685. -999, -999, -999, -999, -999, -999, -999, -999},
  116686. {-999, -999, -999, -999, -999, -999, -106, -100,
  116687. -95, -90, -87, -83, -80, -75, -69, -60,
  116688. -66, -66, -68, -70, -74, -78, -79, -81,
  116689. -81, -83, -84, -87, -93, -96, -99, -103,
  116690. -107, -110, -999, -999, -999, -999, -999, -999,
  116691. -999, -999, -999, -999, -999, -999, -999, -999,
  116692. -999, -999, -999, -999, -999, -999, -999, -999},
  116693. {-999, -999, -999, -999, -999, -108, -103, -98,
  116694. -93, -89, -85, -82, -78, -71, -62, -55,
  116695. -58, -58, -54, -54, -55, -59, -61, -62,
  116696. -70, -66, -66, -67, -70, -72, -75, -78,
  116697. -84, -84, -84, -88, -91, -90, -95, -98,
  116698. -102, -103, -106, -110, -999, -999, -999, -999,
  116699. -999, -999, -999, -999, -999, -999, -999, -999},
  116700. {-999, -999, -999, -999, -108, -103, -98, -94,
  116701. -90, -87, -82, -79, -73, -67, -58, -47,
  116702. -50, -45, -41, -45, -48, -44, -44, -49,
  116703. -54, -51, -48, -47, -49, -50, -51, -57,
  116704. -58, -60, -63, -69, -70, -69, -71, -74,
  116705. -78, -82, -90, -95, -101, -105, -110, -999,
  116706. -999, -999, -999, -999, -999, -999, -999, -999},
  116707. {-999, -999, -999, -105, -101, -97, -93, -90,
  116708. -85, -80, -77, -72, -65, -56, -48, -37,
  116709. -40, -36, -34, -40, -50, -47, -38, -41,
  116710. -47, -38, -35, -39, -38, -43, -40, -45,
  116711. -50, -45, -44, -47, -50, -55, -48, -48,
  116712. -52, -66, -70, -76, -82, -90, -97, -105,
  116713. -110, -999, -999, -999, -999, -999, -999, -999}},
  116714. /* 707 Hz */
  116715. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116716. -999, -108, -103, -98, -93, -86, -79, -76,
  116717. -83, -81, -85, -87, -89, -93, -98, -102,
  116718. -107, -112, -999, -999, -999, -999, -999, -999,
  116719. -999, -999, -999, -999, -999, -999, -999, -999,
  116720. -999, -999, -999, -999, -999, -999, -999, -999,
  116721. -999, -999, -999, -999, -999, -999, -999, -999},
  116722. {-999, -999, -999, -999, -999, -999, -999, -999,
  116723. -999, -108, -103, -98, -93, -86, -79, -71,
  116724. -77, -74, -77, -79, -81, -84, -85, -90,
  116725. -92, -93, -92, -98, -101, -108, -112, -999,
  116726. -999, -999, -999, -999, -999, -999, -999, -999,
  116727. -999, -999, -999, -999, -999, -999, -999, -999,
  116728. -999, -999, -999, -999, -999, -999, -999, -999},
  116729. {-999, -999, -999, -999, -999, -999, -999, -999,
  116730. -108, -103, -98, -93, -87, -78, -68, -65,
  116731. -66, -62, -65, -67, -70, -73, -75, -78,
  116732. -82, -82, -83, -84, -91, -93, -98, -102,
  116733. -106, -110, -999, -999, -999, -999, -999, -999,
  116734. -999, -999, -999, -999, -999, -999, -999, -999,
  116735. -999, -999, -999, -999, -999, -999, -999, -999},
  116736. {-999, -999, -999, -999, -999, -999, -999, -999,
  116737. -105, -100, -95, -90, -82, -74, -62, -57,
  116738. -58, -56, -51, -52, -52, -54, -54, -58,
  116739. -66, -59, -60, -63, -66, -69, -73, -79,
  116740. -83, -84, -80, -81, -81, -82, -88, -92,
  116741. -98, -105, -113, -999, -999, -999, -999, -999,
  116742. -999, -999, -999, -999, -999, -999, -999, -999},
  116743. {-999, -999, -999, -999, -999, -999, -999, -107,
  116744. -102, -97, -92, -84, -79, -69, -57, -47,
  116745. -52, -47, -44, -45, -50, -52, -42, -42,
  116746. -53, -43, -43, -48, -51, -56, -55, -52,
  116747. -57, -59, -61, -62, -67, -71, -78, -83,
  116748. -86, -94, -98, -103, -110, -999, -999, -999,
  116749. -999, -999, -999, -999, -999, -999, -999, -999},
  116750. {-999, -999, -999, -999, -999, -999, -105, -100,
  116751. -95, -90, -84, -78, -70, -61, -51, -41,
  116752. -40, -38, -40, -46, -52, -51, -41, -40,
  116753. -46, -40, -38, -38, -41, -46, -41, -46,
  116754. -47, -43, -43, -45, -41, -45, -56, -67,
  116755. -68, -83, -87, -90, -95, -102, -107, -113,
  116756. -999, -999, -999, -999, -999, -999, -999, -999}},
  116757. /* 1000 Hz */
  116758. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116759. -999, -109, -105, -101, -96, -91, -84, -77,
  116760. -82, -82, -85, -89, -94, -100, -106, -110,
  116761. -999, -999, -999, -999, -999, -999, -999, -999,
  116762. -999, -999, -999, -999, -999, -999, -999, -999,
  116763. -999, -999, -999, -999, -999, -999, -999, -999,
  116764. -999, -999, -999, -999, -999, -999, -999, -999},
  116765. {-999, -999, -999, -999, -999, -999, -999, -999,
  116766. -999, -106, -103, -98, -92, -85, -80, -71,
  116767. -75, -72, -76, -80, -84, -86, -89, -93,
  116768. -100, -107, -113, -999, -999, -999, -999, -999,
  116769. -999, -999, -999, -999, -999, -999, -999, -999,
  116770. -999, -999, -999, -999, -999, -999, -999, -999,
  116771. -999, -999, -999, -999, -999, -999, -999, -999},
  116772. {-999, -999, -999, -999, -999, -999, -999, -107,
  116773. -104, -101, -97, -92, -88, -84, -80, -64,
  116774. -66, -63, -64, -66, -69, -73, -77, -83,
  116775. -83, -86, -91, -98, -104, -111, -999, -999,
  116776. -999, -999, -999, -999, -999, -999, -999, -999,
  116777. -999, -999, -999, -999, -999, -999, -999, -999,
  116778. -999, -999, -999, -999, -999, -999, -999, -999},
  116779. {-999, -999, -999, -999, -999, -999, -999, -107,
  116780. -104, -101, -97, -92, -90, -84, -74, -57,
  116781. -58, -52, -55, -54, -50, -52, -50, -52,
  116782. -63, -62, -69, -76, -77, -78, -78, -79,
  116783. -82, -88, -94, -100, -106, -111, -999, -999,
  116784. -999, -999, -999, -999, -999, -999, -999, -999,
  116785. -999, -999, -999, -999, -999, -999, -999, -999},
  116786. {-999, -999, -999, -999, -999, -999, -106, -102,
  116787. -98, -95, -90, -85, -83, -78, -70, -50,
  116788. -50, -41, -44, -49, -47, -50, -50, -44,
  116789. -55, -46, -47, -48, -48, -54, -49, -49,
  116790. -58, -62, -71, -81, -87, -92, -97, -102,
  116791. -108, -114, -999, -999, -999, -999, -999, -999,
  116792. -999, -999, -999, -999, -999, -999, -999, -999},
  116793. {-999, -999, -999, -999, -999, -999, -106, -102,
  116794. -98, -95, -90, -85, -83, -78, -70, -45,
  116795. -43, -41, -47, -50, -51, -50, -49, -45,
  116796. -47, -41, -44, -41, -39, -43, -38, -37,
  116797. -40, -41, -44, -50, -58, -65, -73, -79,
  116798. -85, -92, -97, -101, -105, -109, -113, -999,
  116799. -999, -999, -999, -999, -999, -999, -999, -999}},
  116800. /* 1414 Hz */
  116801. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116802. -999, -999, -999, -107, -100, -95, -87, -81,
  116803. -85, -83, -88, -93, -100, -107, -114, -999,
  116804. -999, -999, -999, -999, -999, -999, -999, -999,
  116805. -999, -999, -999, -999, -999, -999, -999, -999,
  116806. -999, -999, -999, -999, -999, -999, -999, -999,
  116807. -999, -999, -999, -999, -999, -999, -999, -999},
  116808. {-999, -999, -999, -999, -999, -999, -999, -999,
  116809. -999, -999, -107, -101, -95, -88, -83, -76,
  116810. -73, -72, -79, -84, -90, -95, -100, -105,
  116811. -110, -115, -999, -999, -999, -999, -999, -999,
  116812. -999, -999, -999, -999, -999, -999, -999, -999,
  116813. -999, -999, -999, -999, -999, -999, -999, -999,
  116814. -999, -999, -999, -999, -999, -999, -999, -999},
  116815. {-999, -999, -999, -999, -999, -999, -999, -999,
  116816. -999, -999, -104, -98, -92, -87, -81, -70,
  116817. -65, -62, -67, -71, -74, -80, -85, -91,
  116818. -95, -99, -103, -108, -111, -114, -999, -999,
  116819. -999, -999, -999, -999, -999, -999, -999, -999,
  116820. -999, -999, -999, -999, -999, -999, -999, -999,
  116821. -999, -999, -999, -999, -999, -999, -999, -999},
  116822. {-999, -999, -999, -999, -999, -999, -999, -999,
  116823. -999, -999, -103, -97, -90, -85, -76, -60,
  116824. -56, -54, -60, -62, -61, -56, -63, -65,
  116825. -73, -74, -77, -75, -78, -81, -86, -87,
  116826. -88, -91, -94, -98, -103, -110, -999, -999,
  116827. -999, -999, -999, -999, -999, -999, -999, -999,
  116828. -999, -999, -999, -999, -999, -999, -999, -999},
  116829. {-999, -999, -999, -999, -999, -999, -999, -105,
  116830. -100, -97, -92, -86, -81, -79, -70, -57,
  116831. -51, -47, -51, -58, -60, -56, -53, -50,
  116832. -58, -52, -50, -50, -53, -55, -64, -69,
  116833. -71, -85, -82, -78, -81, -85, -95, -102,
  116834. -112, -999, -999, -999, -999, -999, -999, -999,
  116835. -999, -999, -999, -999, -999, -999, -999, -999},
  116836. {-999, -999, -999, -999, -999, -999, -999, -105,
  116837. -100, -97, -92, -85, -83, -79, -72, -49,
  116838. -40, -43, -43, -54, -56, -51, -50, -40,
  116839. -43, -38, -36, -35, -37, -38, -37, -44,
  116840. -54, -60, -57, -60, -70, -75, -84, -92,
  116841. -103, -112, -999, -999, -999, -999, -999, -999,
  116842. -999, -999, -999, -999, -999, -999, -999, -999}},
  116843. /* 2000 Hz */
  116844. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116845. -999, -999, -999, -110, -102, -95, -89, -82,
  116846. -83, -84, -90, -92, -99, -107, -113, -999,
  116847. -999, -999, -999, -999, -999, -999, -999, -999,
  116848. -999, -999, -999, -999, -999, -999, -999, -999,
  116849. -999, -999, -999, -999, -999, -999, -999, -999,
  116850. -999, -999, -999, -999, -999, -999, -999, -999},
  116851. {-999, -999, -999, -999, -999, -999, -999, -999,
  116852. -999, -999, -107, -101, -95, -89, -83, -72,
  116853. -74, -78, -85, -88, -88, -90, -92, -98,
  116854. -105, -111, -999, -999, -999, -999, -999, -999,
  116855. -999, -999, -999, -999, -999, -999, -999, -999,
  116856. -999, -999, -999, -999, -999, -999, -999, -999,
  116857. -999, -999, -999, -999, -999, -999, -999, -999},
  116858. {-999, -999, -999, -999, -999, -999, -999, -999,
  116859. -999, -109, -103, -97, -93, -87, -81, -70,
  116860. -70, -67, -75, -73, -76, -79, -81, -83,
  116861. -88, -89, -97, -103, -110, -999, -999, -999,
  116862. -999, -999, -999, -999, -999, -999, -999, -999,
  116863. -999, -999, -999, -999, -999, -999, -999, -999,
  116864. -999, -999, -999, -999, -999, -999, -999, -999},
  116865. {-999, -999, -999, -999, -999, -999, -999, -999,
  116866. -999, -107, -100, -94, -88, -83, -75, -63,
  116867. -59, -59, -63, -66, -60, -62, -67, -67,
  116868. -77, -76, -81, -88, -86, -92, -96, -102,
  116869. -109, -116, -999, -999, -999, -999, -999, -999,
  116870. -999, -999, -999, -999, -999, -999, -999, -999,
  116871. -999, -999, -999, -999, -999, -999, -999, -999},
  116872. {-999, -999, -999, -999, -999, -999, -999, -999,
  116873. -999, -105, -98, -92, -86, -81, -73, -56,
  116874. -52, -47, -55, -60, -58, -52, -51, -45,
  116875. -49, -50, -53, -54, -61, -71, -70, -69,
  116876. -78, -79, -87, -90, -96, -104, -112, -999,
  116877. -999, -999, -999, -999, -999, -999, -999, -999,
  116878. -999, -999, -999, -999, -999, -999, -999, -999},
  116879. {-999, -999, -999, -999, -999, -999, -999, -999,
  116880. -999, -103, -96, -90, -86, -78, -70, -51,
  116881. -42, -47, -48, -55, -54, -54, -53, -42,
  116882. -35, -28, -33, -38, -37, -44, -47, -49,
  116883. -54, -63, -68, -78, -82, -89, -94, -99,
  116884. -104, -109, -114, -999, -999, -999, -999, -999,
  116885. -999, -999, -999, -999, -999, -999, -999, -999}},
  116886. /* 2828 Hz */
  116887. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116888. -999, -999, -999, -999, -110, -100, -90, -79,
  116889. -85, -81, -82, -82, -89, -94, -99, -103,
  116890. -109, -115, -999, -999, -999, -999, -999, -999,
  116891. -999, -999, -999, -999, -999, -999, -999, -999,
  116892. -999, -999, -999, -999, -999, -999, -999, -999,
  116893. -999, -999, -999, -999, -999, -999, -999, -999},
  116894. {-999, -999, -999, -999, -999, -999, -999, -999,
  116895. -999, -999, -999, -999, -105, -97, -85, -72,
  116896. -74, -70, -70, -70, -76, -85, -91, -93,
  116897. -97, -103, -109, -115, -999, -999, -999, -999,
  116898. -999, -999, -999, -999, -999, -999, -999, -999,
  116899. -999, -999, -999, -999, -999, -999, -999, -999,
  116900. -999, -999, -999, -999, -999, -999, -999, -999},
  116901. {-999, -999, -999, -999, -999, -999, -999, -999,
  116902. -999, -999, -999, -999, -112, -93, -81, -68,
  116903. -62, -60, -60, -57, -63, -70, -77, -82,
  116904. -90, -93, -98, -104, -109, -113, -999, -999,
  116905. -999, -999, -999, -999, -999, -999, -999, -999,
  116906. -999, -999, -999, -999, -999, -999, -999, -999,
  116907. -999, -999, -999, -999, -999, -999, -999, -999},
  116908. {-999, -999, -999, -999, -999, -999, -999, -999,
  116909. -999, -999, -999, -113, -100, -93, -84, -63,
  116910. -58, -48, -53, -54, -52, -52, -57, -64,
  116911. -66, -76, -83, -81, -85, -85, -90, -95,
  116912. -98, -101, -103, -106, -108, -111, -999, -999,
  116913. -999, -999, -999, -999, -999, -999, -999, -999,
  116914. -999, -999, -999, -999, -999, -999, -999, -999},
  116915. {-999, -999, -999, -999, -999, -999, -999, -999,
  116916. -999, -999, -999, -105, -95, -86, -74, -53,
  116917. -50, -38, -43, -49, -43, -42, -39, -39,
  116918. -46, -52, -57, -56, -72, -69, -74, -81,
  116919. -87, -92, -94, -97, -99, -102, -105, -108,
  116920. -999, -999, -999, -999, -999, -999, -999, -999,
  116921. -999, -999, -999, -999, -999, -999, -999, -999},
  116922. {-999, -999, -999, -999, -999, -999, -999, -999,
  116923. -999, -999, -108, -99, -90, -76, -66, -45,
  116924. -43, -41, -44, -47, -43, -47, -40, -30,
  116925. -31, -31, -39, -33, -40, -41, -43, -53,
  116926. -59, -70, -73, -77, -79, -82, -84, -87,
  116927. -999, -999, -999, -999, -999, -999, -999, -999,
  116928. -999, -999, -999, -999, -999, -999, -999, -999}},
  116929. /* 4000 Hz */
  116930. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116931. -999, -999, -999, -999, -999, -110, -91, -76,
  116932. -75, -85, -93, -98, -104, -110, -999, -999,
  116933. -999, -999, -999, -999, -999, -999, -999, -999,
  116934. -999, -999, -999, -999, -999, -999, -999, -999,
  116935. -999, -999, -999, -999, -999, -999, -999, -999,
  116936. -999, -999, -999, -999, -999, -999, -999, -999},
  116937. {-999, -999, -999, -999, -999, -999, -999, -999,
  116938. -999, -999, -999, -999, -999, -110, -91, -70,
  116939. -70, -75, -86, -89, -94, -98, -101, -106,
  116940. -110, -999, -999, -999, -999, -999, -999, -999,
  116941. -999, -999, -999, -999, -999, -999, -999, -999,
  116942. -999, -999, -999, -999, -999, -999, -999, -999,
  116943. -999, -999, -999, -999, -999, -999, -999, -999},
  116944. {-999, -999, -999, -999, -999, -999, -999, -999,
  116945. -999, -999, -999, -999, -110, -95, -80, -60,
  116946. -65, -64, -74, -83, -88, -91, -95, -99,
  116947. -103, -107, -110, -999, -999, -999, -999, -999,
  116948. -999, -999, -999, -999, -999, -999, -999, -999,
  116949. -999, -999, -999, -999, -999, -999, -999, -999,
  116950. -999, -999, -999, -999, -999, -999, -999, -999},
  116951. {-999, -999, -999, -999, -999, -999, -999, -999,
  116952. -999, -999, -999, -999, -110, -95, -80, -58,
  116953. -55, -49, -66, -68, -71, -78, -78, -80,
  116954. -88, -85, -89, -97, -100, -105, -110, -999,
  116955. -999, -999, -999, -999, -999, -999, -999, -999,
  116956. -999, -999, -999, -999, -999, -999, -999, -999,
  116957. -999, -999, -999, -999, -999, -999, -999, -999},
  116958. {-999, -999, -999, -999, -999, -999, -999, -999,
  116959. -999, -999, -999, -999, -110, -95, -80, -53,
  116960. -52, -41, -59, -59, -49, -58, -56, -63,
  116961. -86, -79, -90, -93, -98, -103, -107, -112,
  116962. -999, -999, -999, -999, -999, -999, -999, -999,
  116963. -999, -999, -999, -999, -999, -999, -999, -999,
  116964. -999, -999, -999, -999, -999, -999, -999, -999},
  116965. {-999, -999, -999, -999, -999, -999, -999, -999,
  116966. -999, -999, -999, -110, -97, -91, -73, -45,
  116967. -40, -33, -53, -61, -49, -54, -50, -50,
  116968. -60, -52, -67, -74, -81, -92, -96, -100,
  116969. -105, -110, -999, -999, -999, -999, -999, -999,
  116970. -999, -999, -999, -999, -999, -999, -999, -999,
  116971. -999, -999, -999, -999, -999, -999, -999, -999}},
  116972. /* 5657 Hz */
  116973. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116974. -999, -999, -999, -113, -106, -99, -92, -77,
  116975. -80, -88, -97, -106, -115, -999, -999, -999,
  116976. -999, -999, -999, -999, -999, -999, -999, -999,
  116977. -999, -999, -999, -999, -999, -999, -999, -999,
  116978. -999, -999, -999, -999, -999, -999, -999, -999,
  116979. -999, -999, -999, -999, -999, -999, -999, -999},
  116980. {-999, -999, -999, -999, -999, -999, -999, -999,
  116981. -999, -999, -116, -109, -102, -95, -89, -74,
  116982. -72, -88, -87, -95, -102, -109, -116, -999,
  116983. -999, -999, -999, -999, -999, -999, -999, -999,
  116984. -999, -999, -999, -999, -999, -999, -999, -999,
  116985. -999, -999, -999, -999, -999, -999, -999, -999,
  116986. -999, -999, -999, -999, -999, -999, -999, -999},
  116987. {-999, -999, -999, -999, -999, -999, -999, -999,
  116988. -999, -999, -116, -109, -102, -95, -89, -75,
  116989. -66, -74, -77, -78, -86, -87, -90, -96,
  116990. -105, -115, -999, -999, -999, -999, -999, -999,
  116991. -999, -999, -999, -999, -999, -999, -999, -999,
  116992. -999, -999, -999, -999, -999, -999, -999, -999,
  116993. -999, -999, -999, -999, -999, -999, -999, -999},
  116994. {-999, -999, -999, -999, -999, -999, -999, -999,
  116995. -999, -999, -115, -108, -101, -94, -88, -66,
  116996. -56, -61, -70, -65, -78, -72, -83, -84,
  116997. -93, -98, -105, -110, -999, -999, -999, -999,
  116998. -999, -999, -999, -999, -999, -999, -999, -999,
  116999. -999, -999, -999, -999, -999, -999, -999, -999,
  117000. -999, -999, -999, -999, -999, -999, -999, -999},
  117001. {-999, -999, -999, -999, -999, -999, -999, -999,
  117002. -999, -999, -110, -105, -95, -89, -82, -57,
  117003. -52, -52, -59, -56, -59, -58, -69, -67,
  117004. -88, -82, -82, -89, -94, -100, -108, -999,
  117005. -999, -999, -999, -999, -999, -999, -999, -999,
  117006. -999, -999, -999, -999, -999, -999, -999, -999,
  117007. -999, -999, -999, -999, -999, -999, -999, -999},
  117008. {-999, -999, -999, -999, -999, -999, -999, -999,
  117009. -999, -110, -101, -96, -90, -83, -77, -54,
  117010. -43, -38, -50, -48, -52, -48, -42, -42,
  117011. -51, -52, -53, -59, -65, -71, -78, -85,
  117012. -95, -999, -999, -999, -999, -999, -999, -999,
  117013. -999, -999, -999, -999, -999, -999, -999, -999,
  117014. -999, -999, -999, -999, -999, -999, -999, -999}},
  117015. /* 8000 Hz */
  117016. {{-999, -999, -999, -999, -999, -999, -999, -999,
  117017. -999, -999, -999, -999, -120, -105, -86, -68,
  117018. -78, -79, -90, -100, -110, -999, -999, -999,
  117019. -999, -999, -999, -999, -999, -999, -999, -999,
  117020. -999, -999, -999, -999, -999, -999, -999, -999,
  117021. -999, -999, -999, -999, -999, -999, -999, -999,
  117022. -999, -999, -999, -999, -999, -999, -999, -999},
  117023. {-999, -999, -999, -999, -999, -999, -999, -999,
  117024. -999, -999, -999, -999, -120, -105, -86, -66,
  117025. -73, -77, -88, -96, -105, -115, -999, -999,
  117026. -999, -999, -999, -999, -999, -999, -999, -999,
  117027. -999, -999, -999, -999, -999, -999, -999, -999,
  117028. -999, -999, -999, -999, -999, -999, -999, -999,
  117029. -999, -999, -999, -999, -999, -999, -999, -999},
  117030. {-999, -999, -999, -999, -999, -999, -999, -999,
  117031. -999, -999, -999, -120, -105, -92, -80, -61,
  117032. -64, -68, -80, -87, -92, -100, -110, -999,
  117033. -999, -999, -999, -999, -999, -999, -999, -999,
  117034. -999, -999, -999, -999, -999, -999, -999, -999,
  117035. -999, -999, -999, -999, -999, -999, -999, -999,
  117036. -999, -999, -999, -999, -999, -999, -999, -999},
  117037. {-999, -999, -999, -999, -999, -999, -999, -999,
  117038. -999, -999, -999, -120, -104, -91, -79, -52,
  117039. -60, -54, -64, -69, -77, -80, -82, -84,
  117040. -85, -87, -88, -90, -999, -999, -999, -999,
  117041. -999, -999, -999, -999, -999, -999, -999, -999,
  117042. -999, -999, -999, -999, -999, -999, -999, -999,
  117043. -999, -999, -999, -999, -999, -999, -999, -999},
  117044. {-999, -999, -999, -999, -999, -999, -999, -999,
  117045. -999, -999, -999, -118, -100, -87, -77, -49,
  117046. -50, -44, -58, -61, -61, -67, -65, -62,
  117047. -62, -62, -65, -68, -999, -999, -999, -999,
  117048. -999, -999, -999, -999, -999, -999, -999, -999,
  117049. -999, -999, -999, -999, -999, -999, -999, -999,
  117050. -999, -999, -999, -999, -999, -999, -999, -999},
  117051. {-999, -999, -999, -999, -999, -999, -999, -999,
  117052. -999, -999, -999, -115, -98, -84, -62, -49,
  117053. -44, -38, -46, -49, -49, -46, -39, -37,
  117054. -39, -40, -42, -43, -999, -999, -999, -999,
  117055. -999, -999, -999, -999, -999, -999, -999, -999,
  117056. -999, -999, -999, -999, -999, -999, -999, -999,
  117057. -999, -999, -999, -999, -999, -999, -999, -999}},
  117058. /* 11314 Hz */
  117059. {{-999, -999, -999, -999, -999, -999, -999, -999,
  117060. -999, -999, -999, -999, -999, -110, -88, -74,
  117061. -77, -82, -82, -85, -90, -94, -99, -104,
  117062. -999, -999, -999, -999, -999, -999, -999, -999,
  117063. -999, -999, -999, -999, -999, -999, -999, -999,
  117064. -999, -999, -999, -999, -999, -999, -999, -999,
  117065. -999, -999, -999, -999, -999, -999, -999, -999},
  117066. {-999, -999, -999, -999, -999, -999, -999, -999,
  117067. -999, -999, -999, -999, -999, -110, -88, -66,
  117068. -70, -81, -80, -81, -84, -88, -91, -93,
  117069. -999, -999, -999, -999, -999, -999, -999, -999,
  117070. -999, -999, -999, -999, -999, -999, -999, -999,
  117071. -999, -999, -999, -999, -999, -999, -999, -999,
  117072. -999, -999, -999, -999, -999, -999, -999, -999},
  117073. {-999, -999, -999, -999, -999, -999, -999, -999,
  117074. -999, -999, -999, -999, -999, -110, -88, -61,
  117075. -63, -70, -71, -74, -77, -80, -83, -85,
  117076. -999, -999, -999, -999, -999, -999, -999, -999,
  117077. -999, -999, -999, -999, -999, -999, -999, -999,
  117078. -999, -999, -999, -999, -999, -999, -999, -999,
  117079. -999, -999, -999, -999, -999, -999, -999, -999},
  117080. {-999, -999, -999, -999, -999, -999, -999, -999,
  117081. -999, -999, -999, -999, -999, -110, -86, -62,
  117082. -63, -62, -62, -58, -52, -50, -50, -52,
  117083. -54, -999, -999, -999, -999, -999, -999, -999,
  117084. -999, -999, -999, -999, -999, -999, -999, -999,
  117085. -999, -999, -999, -999, -999, -999, -999, -999,
  117086. -999, -999, -999, -999, -999, -999, -999, -999},
  117087. {-999, -999, -999, -999, -999, -999, -999, -999,
  117088. -999, -999, -999, -999, -118, -108, -84, -53,
  117089. -50, -50, -50, -55, -47, -45, -40, -40,
  117090. -40, -999, -999, -999, -999, -999, -999, -999,
  117091. -999, -999, -999, -999, -999, -999, -999, -999,
  117092. -999, -999, -999, -999, -999, -999, -999, -999,
  117093. -999, -999, -999, -999, -999, -999, -999, -999},
  117094. {-999, -999, -999, -999, -999, -999, -999, -999,
  117095. -999, -999, -999, -999, -118, -100, -73, -43,
  117096. -37, -42, -43, -53, -38, -37, -35, -35,
  117097. -38, -999, -999, -999, -999, -999, -999, -999,
  117098. -999, -999, -999, -999, -999, -999, -999, -999,
  117099. -999, -999, -999, -999, -999, -999, -999, -999,
  117100. -999, -999, -999, -999, -999, -999, -999, -999}},
  117101. /* 16000 Hz */
  117102. {{-999, -999, -999, -999, -999, -999, -999, -999,
  117103. -999, -999, -999, -110, -100, -91, -84, -74,
  117104. -80, -80, -80, -80, -80, -999, -999, -999,
  117105. -999, -999, -999, -999, -999, -999, -999, -999,
  117106. -999, -999, -999, -999, -999, -999, -999, -999,
  117107. -999, -999, -999, -999, -999, -999, -999, -999,
  117108. -999, -999, -999, -999, -999, -999, -999, -999},
  117109. {-999, -999, -999, -999, -999, -999, -999, -999,
  117110. -999, -999, -999, -110, -100, -91, -84, -74,
  117111. -68, -68, -68, -68, -68, -999, -999, -999,
  117112. -999, -999, -999, -999, -999, -999, -999, -999,
  117113. -999, -999, -999, -999, -999, -999, -999, -999,
  117114. -999, -999, -999, -999, -999, -999, -999, -999,
  117115. -999, -999, -999, -999, -999, -999, -999, -999},
  117116. {-999, -999, -999, -999, -999, -999, -999, -999,
  117117. -999, -999, -999, -110, -100, -86, -78, -70,
  117118. -60, -45, -30, -21, -999, -999, -999, -999,
  117119. -999, -999, -999, -999, -999, -999, -999, -999,
  117120. -999, -999, -999, -999, -999, -999, -999, -999,
  117121. -999, -999, -999, -999, -999, -999, -999, -999,
  117122. -999, -999, -999, -999, -999, -999, -999, -999},
  117123. {-999, -999, -999, -999, -999, -999, -999, -999,
  117124. -999, -999, -999, -110, -100, -87, -78, -67,
  117125. -48, -38, -29, -21, -999, -999, -999, -999,
  117126. -999, -999, -999, -999, -999, -999, -999, -999,
  117127. -999, -999, -999, -999, -999, -999, -999, -999,
  117128. -999, -999, -999, -999, -999, -999, -999, -999,
  117129. -999, -999, -999, -999, -999, -999, -999, -999},
  117130. {-999, -999, -999, -999, -999, -999, -999, -999,
  117131. -999, -999, -999, -110, -100, -86, -69, -56,
  117132. -45, -35, -33, -29, -999, -999, -999, -999,
  117133. -999, -999, -999, -999, -999, -999, -999, -999,
  117134. -999, -999, -999, -999, -999, -999, -999, -999,
  117135. -999, -999, -999, -999, -999, -999, -999, -999,
  117136. -999, -999, -999, -999, -999, -999, -999, -999},
  117137. {-999, -999, -999, -999, -999, -999, -999, -999,
  117138. -999, -999, -999, -110, -100, -83, -71, -48,
  117139. -27, -38, -37, -34, -999, -999, -999, -999,
  117140. -999, -999, -999, -999, -999, -999, -999, -999,
  117141. -999, -999, -999, -999, -999, -999, -999, -999,
  117142. -999, -999, -999, -999, -999, -999, -999, -999,
  117143. -999, -999, -999, -999, -999, -999, -999, -999}}
  117144. };
  117145. #endif
  117146. /*** End of inlined file: masking.h ***/
  117147. #define NEGINF -9999.f
  117148. static double stereo_threshholds[]={0.0, .5, 1.0, 1.5, 2.5, 4.5, 8.5, 16.5, 9e10};
  117149. static double stereo_threshholds_limited[]={0.0, .5, 1.0, 1.5, 2.0, 2.5, 4.5, 8.5, 9e10};
  117150. vorbis_look_psy_global *_vp_global_look(vorbis_info *vi){
  117151. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  117152. vorbis_info_psy_global *gi=&ci->psy_g_param;
  117153. vorbis_look_psy_global *look=(vorbis_look_psy_global*)_ogg_calloc(1,sizeof(*look));
  117154. look->channels=vi->channels;
  117155. look->ampmax=-9999.;
  117156. look->gi=gi;
  117157. return(look);
  117158. }
  117159. void _vp_global_free(vorbis_look_psy_global *look){
  117160. if(look){
  117161. memset(look,0,sizeof(*look));
  117162. _ogg_free(look);
  117163. }
  117164. }
  117165. void _vi_gpsy_free(vorbis_info_psy_global *i){
  117166. if(i){
  117167. memset(i,0,sizeof(*i));
  117168. _ogg_free(i);
  117169. }
  117170. }
  117171. void _vi_psy_free(vorbis_info_psy *i){
  117172. if(i){
  117173. memset(i,0,sizeof(*i));
  117174. _ogg_free(i);
  117175. }
  117176. }
  117177. static void min_curve(float *c,
  117178. float *c2){
  117179. int i;
  117180. for(i=0;i<EHMER_MAX;i++)if(c2[i]<c[i])c[i]=c2[i];
  117181. }
  117182. static void max_curve(float *c,
  117183. float *c2){
  117184. int i;
  117185. for(i=0;i<EHMER_MAX;i++)if(c2[i]>c[i])c[i]=c2[i];
  117186. }
  117187. static void attenuate_curve(float *c,float att){
  117188. int i;
  117189. for(i=0;i<EHMER_MAX;i++)
  117190. c[i]+=att;
  117191. }
  117192. static float ***setup_tone_curves(float curveatt_dB[P_BANDS],float binHz,int n,
  117193. float center_boost, float center_decay_rate){
  117194. int i,j,k,m;
  117195. float ath[EHMER_MAX];
  117196. float workc[P_BANDS][P_LEVELS][EHMER_MAX];
  117197. float athc[P_LEVELS][EHMER_MAX];
  117198. float *brute_buffer=(float*) alloca(n*sizeof(*brute_buffer));
  117199. float ***ret=(float***) _ogg_malloc(sizeof(*ret)*P_BANDS);
  117200. memset(workc,0,sizeof(workc));
  117201. for(i=0;i<P_BANDS;i++){
  117202. /* we add back in the ATH to avoid low level curves falling off to
  117203. -infinity and unnecessarily cutting off high level curves in the
  117204. curve limiting (last step). */
  117205. /* A half-band's settings must be valid over the whole band, and
  117206. it's better to mask too little than too much */
  117207. int ath_offset=i*4;
  117208. for(j=0;j<EHMER_MAX;j++){
  117209. float min=999.;
  117210. for(k=0;k<4;k++)
  117211. if(j+k+ath_offset<MAX_ATH){
  117212. if(min>ATH[j+k+ath_offset])min=ATH[j+k+ath_offset];
  117213. }else{
  117214. if(min>ATH[MAX_ATH-1])min=ATH[MAX_ATH-1];
  117215. }
  117216. ath[j]=min;
  117217. }
  117218. /* copy curves into working space, replicate the 50dB curve to 30
  117219. and 40, replicate the 100dB curve to 110 */
  117220. for(j=0;j<6;j++)
  117221. memcpy(workc[i][j+2],tonemasks[i][j],EHMER_MAX*sizeof(*tonemasks[i][j]));
  117222. memcpy(workc[i][0],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  117223. memcpy(workc[i][1],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  117224. /* apply centered curve boost/decay */
  117225. for(j=0;j<P_LEVELS;j++){
  117226. for(k=0;k<EHMER_MAX;k++){
  117227. float adj=center_boost+abs(EHMER_OFFSET-k)*center_decay_rate;
  117228. if(adj<0. && center_boost>0)adj=0.;
  117229. if(adj>0. && center_boost<0)adj=0.;
  117230. workc[i][j][k]+=adj;
  117231. }
  117232. }
  117233. /* normalize curves so the driving amplitude is 0dB */
  117234. /* make temp curves with the ATH overlayed */
  117235. for(j=0;j<P_LEVELS;j++){
  117236. attenuate_curve(workc[i][j],curveatt_dB[i]+100.-(j<2?2:j)*10.-P_LEVEL_0);
  117237. memcpy(athc[j],ath,EHMER_MAX*sizeof(**athc));
  117238. attenuate_curve(athc[j],+100.-j*10.f-P_LEVEL_0);
  117239. max_curve(athc[j],workc[i][j]);
  117240. }
  117241. /* Now limit the louder curves.
  117242. the idea is this: We don't know what the playback attenuation
  117243. will be; 0dB SL moves every time the user twiddles the volume
  117244. knob. So that means we have to use a single 'most pessimal' curve
  117245. for all masking amplitudes, right? Wrong. The *loudest* sound
  117246. can be in (we assume) a range of ...+100dB] SL. However, sounds
  117247. 20dB down will be in a range ...+80], 40dB down is from ...+60],
  117248. etc... */
  117249. for(j=1;j<P_LEVELS;j++){
  117250. min_curve(athc[j],athc[j-1]);
  117251. min_curve(workc[i][j],athc[j]);
  117252. }
  117253. }
  117254. for(i=0;i<P_BANDS;i++){
  117255. int hi_curve,lo_curve,bin;
  117256. ret[i]=(float**)_ogg_malloc(sizeof(**ret)*P_LEVELS);
  117257. /* low frequency curves are measured with greater resolution than
  117258. the MDCT/FFT will actually give us; we want the curve applied
  117259. to the tone data to be pessimistic and thus apply the minimum
  117260. masking possible for a given bin. That means that a single bin
  117261. could span more than one octave and that the curve will be a
  117262. composite of multiple octaves. It also may mean that a single
  117263. bin may span > an eighth of an octave and that the eighth
  117264. octave values may also be composited. */
  117265. /* which octave curves will we be compositing? */
  117266. bin=floor(fromOC(i*.5)/binHz);
  117267. lo_curve= ceil(toOC(bin*binHz+1)*2);
  117268. hi_curve= floor(toOC((bin+1)*binHz)*2);
  117269. if(lo_curve>i)lo_curve=i;
  117270. if(lo_curve<0)lo_curve=0;
  117271. if(hi_curve>=P_BANDS)hi_curve=P_BANDS-1;
  117272. for(m=0;m<P_LEVELS;m++){
  117273. ret[i][m]=(float*)_ogg_malloc(sizeof(***ret)*(EHMER_MAX+2));
  117274. for(j=0;j<n;j++)brute_buffer[j]=999.;
  117275. /* render the curve into bins, then pull values back into curve.
  117276. The point is that any inherent subsampling aliasing results in
  117277. a safe minimum */
  117278. for(k=lo_curve;k<=hi_curve;k++){
  117279. int l=0;
  117280. for(j=0;j<EHMER_MAX;j++){
  117281. int lo_bin= fromOC(j*.125+k*.5-2.0625)/binHz;
  117282. int hi_bin= fromOC(j*.125+k*.5-1.9375)/binHz+1;
  117283. if(lo_bin<0)lo_bin=0;
  117284. if(lo_bin>n)lo_bin=n;
  117285. if(lo_bin<l)l=lo_bin;
  117286. if(hi_bin<0)hi_bin=0;
  117287. if(hi_bin>n)hi_bin=n;
  117288. for(;l<hi_bin && l<n;l++)
  117289. if(brute_buffer[l]>workc[k][m][j])
  117290. brute_buffer[l]=workc[k][m][j];
  117291. }
  117292. for(;l<n;l++)
  117293. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  117294. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  117295. }
  117296. /* be equally paranoid about being valid up to next half ocatve */
  117297. if(i+1<P_BANDS){
  117298. int l=0;
  117299. k=i+1;
  117300. for(j=0;j<EHMER_MAX;j++){
  117301. int lo_bin= fromOC(j*.125+i*.5-2.0625)/binHz;
  117302. int hi_bin= fromOC(j*.125+i*.5-1.9375)/binHz+1;
  117303. if(lo_bin<0)lo_bin=0;
  117304. if(lo_bin>n)lo_bin=n;
  117305. if(lo_bin<l)l=lo_bin;
  117306. if(hi_bin<0)hi_bin=0;
  117307. if(hi_bin>n)hi_bin=n;
  117308. for(;l<hi_bin && l<n;l++)
  117309. if(brute_buffer[l]>workc[k][m][j])
  117310. brute_buffer[l]=workc[k][m][j];
  117311. }
  117312. for(;l<n;l++)
  117313. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  117314. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  117315. }
  117316. for(j=0;j<EHMER_MAX;j++){
  117317. int bin=fromOC(j*.125+i*.5-2.)/binHz;
  117318. if(bin<0){
  117319. ret[i][m][j+2]=-999.;
  117320. }else{
  117321. if(bin>=n){
  117322. ret[i][m][j+2]=-999.;
  117323. }else{
  117324. ret[i][m][j+2]=brute_buffer[bin];
  117325. }
  117326. }
  117327. }
  117328. /* add fenceposts */
  117329. for(j=0;j<EHMER_OFFSET;j++)
  117330. if(ret[i][m][j+2]>-200.f)break;
  117331. ret[i][m][0]=j;
  117332. for(j=EHMER_MAX-1;j>EHMER_OFFSET+1;j--)
  117333. if(ret[i][m][j+2]>-200.f)
  117334. break;
  117335. ret[i][m][1]=j;
  117336. }
  117337. }
  117338. return(ret);
  117339. }
  117340. void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  117341. vorbis_info_psy_global *gi,int n,long rate){
  117342. long i,j,lo=-99,hi=1;
  117343. long maxoc;
  117344. memset(p,0,sizeof(*p));
  117345. p->eighth_octave_lines=gi->eighth_octave_lines;
  117346. p->shiftoc=rint(log(gi->eighth_octave_lines*8.f)/log(2.f))-1;
  117347. p->firstoc=toOC(.25f*rate*.5/n)*(1<<(p->shiftoc+1))-gi->eighth_octave_lines;
  117348. maxoc=toOC((n+.25f)*rate*.5/n)*(1<<(p->shiftoc+1))+.5f;
  117349. p->total_octave_lines=maxoc-p->firstoc+1;
  117350. p->ath=(float*)_ogg_malloc(n*sizeof(*p->ath));
  117351. p->octave=(long*)_ogg_malloc(n*sizeof(*p->octave));
  117352. p->bark=(long*)_ogg_malloc(n*sizeof(*p->bark));
  117353. p->vi=vi;
  117354. p->n=n;
  117355. p->rate=rate;
  117356. /* AoTuV HF weighting */
  117357. p->m_val = 1.;
  117358. if(rate < 26000) p->m_val = 0;
  117359. else if(rate < 38000) p->m_val = .94; /* 32kHz */
  117360. else if(rate > 46000) p->m_val = 1.275; /* 48kHz */
  117361. /* set up the lookups for a given blocksize and sample rate */
  117362. for(i=0,j=0;i<MAX_ATH-1;i++){
  117363. int endpos=rint(fromOC((i+1)*.125-2.)*2*n/rate);
  117364. float base=ATH[i];
  117365. if(j<endpos){
  117366. float delta=(ATH[i+1]-base)/(endpos-j);
  117367. for(;j<endpos && j<n;j++){
  117368. p->ath[j]=base+100.;
  117369. base+=delta;
  117370. }
  117371. }
  117372. }
  117373. for(i=0;i<n;i++){
  117374. float bark=toBARK(rate/(2*n)*i);
  117375. for(;lo+vi->noisewindowlomin<i &&
  117376. toBARK(rate/(2*n)*lo)<(bark-vi->noisewindowlo);lo++);
  117377. for(;hi<=n && (hi<i+vi->noisewindowhimin ||
  117378. toBARK(rate/(2*n)*hi)<(bark+vi->noisewindowhi));hi++);
  117379. p->bark[i]=((lo-1)<<16)+(hi-1);
  117380. }
  117381. for(i=0;i<n;i++)
  117382. p->octave[i]=toOC((i+.25f)*.5*rate/n)*(1<<(p->shiftoc+1))+.5f;
  117383. p->tonecurves=setup_tone_curves(vi->toneatt,rate*.5/n,n,
  117384. vi->tone_centerboost,vi->tone_decay);
  117385. /* set up rolling noise median */
  117386. p->noiseoffset=(float**)_ogg_malloc(P_NOISECURVES*sizeof(*p->noiseoffset));
  117387. for(i=0;i<P_NOISECURVES;i++)
  117388. p->noiseoffset[i]=(float*)_ogg_malloc(n*sizeof(**p->noiseoffset));
  117389. for(i=0;i<n;i++){
  117390. float halfoc=toOC((i+.5)*rate/(2.*n))*2.;
  117391. int inthalfoc;
  117392. float del;
  117393. if(halfoc<0)halfoc=0;
  117394. if(halfoc>=P_BANDS-1)halfoc=P_BANDS-1;
  117395. inthalfoc=(int)halfoc;
  117396. del=halfoc-inthalfoc;
  117397. for(j=0;j<P_NOISECURVES;j++)
  117398. p->noiseoffset[j][i]=
  117399. p->vi->noiseoff[j][inthalfoc]*(1.-del) +
  117400. p->vi->noiseoff[j][inthalfoc+1]*del;
  117401. }
  117402. #if 0
  117403. {
  117404. static int ls=0;
  117405. _analysis_output_always("noiseoff0",ls,p->noiseoffset[0],n,1,0,0);
  117406. _analysis_output_always("noiseoff1",ls,p->noiseoffset[1],n,1,0,0);
  117407. _analysis_output_always("noiseoff2",ls++,p->noiseoffset[2],n,1,0,0);
  117408. }
  117409. #endif
  117410. }
  117411. void _vp_psy_clear(vorbis_look_psy *p){
  117412. int i,j;
  117413. if(p){
  117414. if(p->ath)_ogg_free(p->ath);
  117415. if(p->octave)_ogg_free(p->octave);
  117416. if(p->bark)_ogg_free(p->bark);
  117417. if(p->tonecurves){
  117418. for(i=0;i<P_BANDS;i++){
  117419. for(j=0;j<P_LEVELS;j++){
  117420. _ogg_free(p->tonecurves[i][j]);
  117421. }
  117422. _ogg_free(p->tonecurves[i]);
  117423. }
  117424. _ogg_free(p->tonecurves);
  117425. }
  117426. if(p->noiseoffset){
  117427. for(i=0;i<P_NOISECURVES;i++){
  117428. _ogg_free(p->noiseoffset[i]);
  117429. }
  117430. _ogg_free(p->noiseoffset);
  117431. }
  117432. memset(p,0,sizeof(*p));
  117433. }
  117434. }
  117435. /* octave/(8*eighth_octave_lines) x scale and dB y scale */
  117436. static void seed_curve(float *seed,
  117437. const float **curves,
  117438. float amp,
  117439. int oc, int n,
  117440. int linesper,float dBoffset){
  117441. int i,post1;
  117442. int seedptr;
  117443. const float *posts,*curve;
  117444. int choice=(int)((amp+dBoffset-P_LEVEL_0)*.1f);
  117445. choice=max(choice,0);
  117446. choice=min(choice,P_LEVELS-1);
  117447. posts=curves[choice];
  117448. curve=posts+2;
  117449. post1=(int)posts[1];
  117450. seedptr=oc+(posts[0]-EHMER_OFFSET)*linesper-(linesper>>1);
  117451. for(i=posts[0];i<post1;i++){
  117452. if(seedptr>0){
  117453. float lin=amp+curve[i];
  117454. if(seed[seedptr]<lin)seed[seedptr]=lin;
  117455. }
  117456. seedptr+=linesper;
  117457. if(seedptr>=n)break;
  117458. }
  117459. }
  117460. static void seed_loop(vorbis_look_psy *p,
  117461. const float ***curves,
  117462. const float *f,
  117463. const float *flr,
  117464. float *seed,
  117465. float specmax){
  117466. vorbis_info_psy *vi=p->vi;
  117467. long n=p->n,i;
  117468. float dBoffset=vi->max_curve_dB-specmax;
  117469. /* prime the working vector with peak values */
  117470. for(i=0;i<n;i++){
  117471. float max=f[i];
  117472. long oc=p->octave[i];
  117473. while(i+1<n && p->octave[i+1]==oc){
  117474. i++;
  117475. if(f[i]>max)max=f[i];
  117476. }
  117477. if(max+6.f>flr[i]){
  117478. oc=oc>>p->shiftoc;
  117479. if(oc>=P_BANDS)oc=P_BANDS-1;
  117480. if(oc<0)oc=0;
  117481. seed_curve(seed,
  117482. curves[oc],
  117483. max,
  117484. p->octave[i]-p->firstoc,
  117485. p->total_octave_lines,
  117486. p->eighth_octave_lines,
  117487. dBoffset);
  117488. }
  117489. }
  117490. }
  117491. static void seed_chase(float *seeds, int linesper, long n){
  117492. long *posstack=(long*)alloca(n*sizeof(*posstack));
  117493. float *ampstack=(float*)alloca(n*sizeof(*ampstack));
  117494. long stack=0;
  117495. long pos=0;
  117496. long i;
  117497. for(i=0;i<n;i++){
  117498. if(stack<2){
  117499. posstack[stack]=i;
  117500. ampstack[stack++]=seeds[i];
  117501. }else{
  117502. while(1){
  117503. if(seeds[i]<ampstack[stack-1]){
  117504. posstack[stack]=i;
  117505. ampstack[stack++]=seeds[i];
  117506. break;
  117507. }else{
  117508. if(i<posstack[stack-1]+linesper){
  117509. if(stack>1 && ampstack[stack-1]<=ampstack[stack-2] &&
  117510. i<posstack[stack-2]+linesper){
  117511. /* we completely overlap, making stack-1 irrelevant. pop it */
  117512. stack--;
  117513. continue;
  117514. }
  117515. }
  117516. posstack[stack]=i;
  117517. ampstack[stack++]=seeds[i];
  117518. break;
  117519. }
  117520. }
  117521. }
  117522. }
  117523. /* the stack now contains only the positions that are relevant. Scan
  117524. 'em straight through */
  117525. for(i=0;i<stack;i++){
  117526. long endpos;
  117527. if(i<stack-1 && ampstack[i+1]>ampstack[i]){
  117528. endpos=posstack[i+1];
  117529. }else{
  117530. endpos=posstack[i]+linesper+1; /* +1 is important, else bin 0 is
  117531. discarded in short frames */
  117532. }
  117533. if(endpos>n)endpos=n;
  117534. for(;pos<endpos;pos++)
  117535. seeds[pos]=ampstack[i];
  117536. }
  117537. /* there. Linear time. I now remember this was on a problem set I
  117538. had in Grad Skool... I didn't solve it at the time ;-) */
  117539. }
  117540. /* bleaugh, this is more complicated than it needs to be */
  117541. #include<stdio.h>
  117542. static void max_seeds(vorbis_look_psy *p,
  117543. float *seed,
  117544. float *flr){
  117545. long n=p->total_octave_lines;
  117546. int linesper=p->eighth_octave_lines;
  117547. long linpos=0;
  117548. long pos;
  117549. seed_chase(seed,linesper,n); /* for masking */
  117550. pos=p->octave[0]-p->firstoc-(linesper>>1);
  117551. while(linpos+1<p->n){
  117552. float minV=seed[pos];
  117553. long end=((p->octave[linpos]+p->octave[linpos+1])>>1)-p->firstoc;
  117554. if(minV>p->vi->tone_abs_limit)minV=p->vi->tone_abs_limit;
  117555. while(pos+1<=end){
  117556. pos++;
  117557. if((seed[pos]>NEGINF && seed[pos]<minV) || minV==NEGINF)
  117558. minV=seed[pos];
  117559. }
  117560. end=pos+p->firstoc;
  117561. for(;linpos<p->n && p->octave[linpos]<=end;linpos++)
  117562. if(flr[linpos]<minV)flr[linpos]=minV;
  117563. }
  117564. {
  117565. float minV=seed[p->total_octave_lines-1];
  117566. for(;linpos<p->n;linpos++)
  117567. if(flr[linpos]<minV)flr[linpos]=minV;
  117568. }
  117569. }
  117570. static void bark_noise_hybridmp(int n,const long *b,
  117571. const float *f,
  117572. float *noise,
  117573. const float offset,
  117574. const int fixed){
  117575. float *N=(float*) alloca(n*sizeof(*N));
  117576. float *X=(float*) alloca(n*sizeof(*N));
  117577. float *XX=(float*) alloca(n*sizeof(*N));
  117578. float *Y=(float*) alloca(n*sizeof(*N));
  117579. float *XY=(float*) alloca(n*sizeof(*N));
  117580. float tN, tX, tXX, tY, tXY;
  117581. int i;
  117582. int lo, hi;
  117583. float R, A, B, D;
  117584. float w, x, y;
  117585. tN = tX = tXX = tY = tXY = 0.f;
  117586. y = f[0] + offset;
  117587. if (y < 1.f) y = 1.f;
  117588. w = y * y * .5;
  117589. tN += w;
  117590. tX += w;
  117591. tY += w * y;
  117592. N[0] = tN;
  117593. X[0] = tX;
  117594. XX[0] = tXX;
  117595. Y[0] = tY;
  117596. XY[0] = tXY;
  117597. for (i = 1, x = 1.f; i < n; i++, x += 1.f) {
  117598. y = f[i] + offset;
  117599. if (y < 1.f) y = 1.f;
  117600. w = y * y;
  117601. tN += w;
  117602. tX += w * x;
  117603. tXX += w * x * x;
  117604. tY += w * y;
  117605. tXY += w * x * y;
  117606. N[i] = tN;
  117607. X[i] = tX;
  117608. XX[i] = tXX;
  117609. Y[i] = tY;
  117610. XY[i] = tXY;
  117611. }
  117612. for (i = 0, x = 0.f;; i++, x += 1.f) {
  117613. lo = b[i] >> 16;
  117614. if( lo>=0 ) break;
  117615. hi = b[i] & 0xffff;
  117616. tN = N[hi] + N[-lo];
  117617. tX = X[hi] - X[-lo];
  117618. tXX = XX[hi] + XX[-lo];
  117619. tY = Y[hi] + Y[-lo];
  117620. tXY = XY[hi] - XY[-lo];
  117621. A = tY * tXX - tX * tXY;
  117622. B = tN * tXY - tX * tY;
  117623. D = tN * tXX - tX * tX;
  117624. R = (A + x * B) / D;
  117625. if (R < 0.f)
  117626. R = 0.f;
  117627. noise[i] = R - offset;
  117628. }
  117629. for ( ;; i++, x += 1.f) {
  117630. lo = b[i] >> 16;
  117631. hi = b[i] & 0xffff;
  117632. if(hi>=n)break;
  117633. tN = N[hi] - N[lo];
  117634. tX = X[hi] - X[lo];
  117635. tXX = XX[hi] - XX[lo];
  117636. tY = Y[hi] - Y[lo];
  117637. tXY = XY[hi] - XY[lo];
  117638. A = tY * tXX - tX * tXY;
  117639. B = tN * tXY - tX * tY;
  117640. D = tN * tXX - tX * tX;
  117641. R = (A + x * B) / D;
  117642. if (R < 0.f) R = 0.f;
  117643. noise[i] = R - offset;
  117644. }
  117645. for ( ; i < n; i++, x += 1.f) {
  117646. R = (A + x * B) / D;
  117647. if (R < 0.f) R = 0.f;
  117648. noise[i] = R - offset;
  117649. }
  117650. if (fixed <= 0) return;
  117651. for (i = 0, x = 0.f;; i++, x += 1.f) {
  117652. hi = i + fixed / 2;
  117653. lo = hi - fixed;
  117654. if(lo>=0)break;
  117655. tN = N[hi] + N[-lo];
  117656. tX = X[hi] - X[-lo];
  117657. tXX = XX[hi] + XX[-lo];
  117658. tY = Y[hi] + Y[-lo];
  117659. tXY = XY[hi] - XY[-lo];
  117660. A = tY * tXX - tX * tXY;
  117661. B = tN * tXY - tX * tY;
  117662. D = tN * tXX - tX * tX;
  117663. R = (A + x * B) / D;
  117664. if (R - offset < noise[i]) noise[i] = R - offset;
  117665. }
  117666. for ( ;; i++, x += 1.f) {
  117667. hi = i + fixed / 2;
  117668. lo = hi - fixed;
  117669. if(hi>=n)break;
  117670. tN = N[hi] - N[lo];
  117671. tX = X[hi] - X[lo];
  117672. tXX = XX[hi] - XX[lo];
  117673. tY = Y[hi] - Y[lo];
  117674. tXY = XY[hi] - XY[lo];
  117675. A = tY * tXX - tX * tXY;
  117676. B = tN * tXY - tX * tY;
  117677. D = tN * tXX - tX * tX;
  117678. R = (A + x * B) / D;
  117679. if (R - offset < noise[i]) noise[i] = R - offset;
  117680. }
  117681. for ( ; i < n; i++, x += 1.f) {
  117682. R = (A + x * B) / D;
  117683. if (R - offset < noise[i]) noise[i] = R - offset;
  117684. }
  117685. }
  117686. static float FLOOR1_fromdB_INV_LOOKUP[256]={
  117687. 0.F, 8.81683e+06F, 8.27882e+06F, 7.77365e+06F,
  117688. 7.29930e+06F, 6.85389e+06F, 6.43567e+06F, 6.04296e+06F,
  117689. 5.67422e+06F, 5.32798e+06F, 5.00286e+06F, 4.69759e+06F,
  117690. 4.41094e+06F, 4.14178e+06F, 3.88905e+06F, 3.65174e+06F,
  117691. 3.42891e+06F, 3.21968e+06F, 3.02321e+06F, 2.83873e+06F,
  117692. 2.66551e+06F, 2.50286e+06F, 2.35014e+06F, 2.20673e+06F,
  117693. 2.07208e+06F, 1.94564e+06F, 1.82692e+06F, 1.71544e+06F,
  117694. 1.61076e+06F, 1.51247e+06F, 1.42018e+06F, 1.33352e+06F,
  117695. 1.25215e+06F, 1.17574e+06F, 1.10400e+06F, 1.03663e+06F,
  117696. 973377.F, 913981.F, 858210.F, 805842.F,
  117697. 756669.F, 710497.F, 667142.F, 626433.F,
  117698. 588208.F, 552316.F, 518613.F, 486967.F,
  117699. 457252.F, 429351.F, 403152.F, 378551.F,
  117700. 355452.F, 333762.F, 313396.F, 294273.F,
  117701. 276316.F, 259455.F, 243623.F, 228757.F,
  117702. 214798.F, 201691.F, 189384.F, 177828.F,
  117703. 166977.F, 156788.F, 147221.F, 138237.F,
  117704. 129802.F, 121881.F, 114444.F, 107461.F,
  117705. 100903.F, 94746.3F, 88964.9F, 83536.2F,
  117706. 78438.8F, 73652.5F, 69158.2F, 64938.1F,
  117707. 60975.6F, 57254.9F, 53761.2F, 50480.6F,
  117708. 47400.3F, 44507.9F, 41792.0F, 39241.9F,
  117709. 36847.3F, 34598.9F, 32487.7F, 30505.3F,
  117710. 28643.8F, 26896.0F, 25254.8F, 23713.7F,
  117711. 22266.7F, 20908.0F, 19632.2F, 18434.2F,
  117712. 17309.4F, 16253.1F, 15261.4F, 14330.1F,
  117713. 13455.7F, 12634.6F, 11863.7F, 11139.7F,
  117714. 10460.0F, 9821.72F, 9222.39F, 8659.64F,
  117715. 8131.23F, 7635.06F, 7169.17F, 6731.70F,
  117716. 6320.93F, 5935.23F, 5573.06F, 5232.99F,
  117717. 4913.67F, 4613.84F, 4332.30F, 4067.94F,
  117718. 3819.72F, 3586.64F, 3367.78F, 3162.28F,
  117719. 2969.31F, 2788.13F, 2617.99F, 2458.24F,
  117720. 2308.24F, 2167.39F, 2035.14F, 1910.95F,
  117721. 1794.35F, 1684.85F, 1582.04F, 1485.51F,
  117722. 1394.86F, 1309.75F, 1229.83F, 1154.78F,
  117723. 1084.32F, 1018.15F, 956.024F, 897.687F,
  117724. 842.910F, 791.475F, 743.179F, 697.830F,
  117725. 655.249F, 615.265F, 577.722F, 542.469F,
  117726. 509.367F, 478.286F, 449.101F, 421.696F,
  117727. 395.964F, 371.803F, 349.115F, 327.812F,
  117728. 307.809F, 289.026F, 271.390F, 254.830F,
  117729. 239.280F, 224.679F, 210.969F, 198.096F,
  117730. 186.008F, 174.658F, 164.000F, 153.993F,
  117731. 144.596F, 135.773F, 127.488F, 119.708F,
  117732. 112.404F, 105.545F, 99.1046F, 93.0572F,
  117733. 87.3788F, 82.0469F, 77.0404F, 72.3394F,
  117734. 67.9252F, 63.7804F, 59.8885F, 56.2341F,
  117735. 52.8027F, 49.5807F, 46.5553F, 43.7144F,
  117736. 41.0470F, 38.5423F, 36.1904F, 33.9821F,
  117737. 31.9085F, 29.9614F, 28.1332F, 26.4165F,
  117738. 24.8045F, 23.2910F, 21.8697F, 20.5352F,
  117739. 19.2822F, 18.1056F, 17.0008F, 15.9634F,
  117740. 14.9893F, 14.0746F, 13.2158F, 12.4094F,
  117741. 11.6522F, 10.9411F, 10.2735F, 9.64662F,
  117742. 9.05798F, 8.50526F, 7.98626F, 7.49894F,
  117743. 7.04135F, 6.61169F, 6.20824F, 5.82941F,
  117744. 5.47370F, 5.13970F, 4.82607F, 4.53158F,
  117745. 4.25507F, 3.99542F, 3.75162F, 3.52269F,
  117746. 3.30774F, 3.10590F, 2.91638F, 2.73842F,
  117747. 2.57132F, 2.41442F, 2.26709F, 2.12875F,
  117748. 1.99885F, 1.87688F, 1.76236F, 1.65482F,
  117749. 1.55384F, 1.45902F, 1.36999F, 1.28640F,
  117750. 1.20790F, 1.13419F, 1.06499F, 1.F
  117751. };
  117752. void _vp_remove_floor(vorbis_look_psy *p,
  117753. float *mdct,
  117754. int *codedflr,
  117755. float *residue,
  117756. int sliding_lowpass){
  117757. int i,n=p->n;
  117758. if(sliding_lowpass>n)sliding_lowpass=n;
  117759. for(i=0;i<sliding_lowpass;i++){
  117760. residue[i]=
  117761. mdct[i]*FLOOR1_fromdB_INV_LOOKUP[codedflr[i]];
  117762. }
  117763. for(;i<n;i++)
  117764. residue[i]=0.;
  117765. }
  117766. void _vp_noisemask(vorbis_look_psy *p,
  117767. float *logmdct,
  117768. float *logmask){
  117769. int i,n=p->n;
  117770. float *work=(float*) alloca(n*sizeof(*work));
  117771. bark_noise_hybridmp(n,p->bark,logmdct,logmask,
  117772. 140.,-1);
  117773. for(i=0;i<n;i++)work[i]=logmdct[i]-logmask[i];
  117774. bark_noise_hybridmp(n,p->bark,work,logmask,0.,
  117775. p->vi->noisewindowfixed);
  117776. for(i=0;i<n;i++)work[i]=logmdct[i]-work[i];
  117777. #if 0
  117778. {
  117779. static int seq=0;
  117780. float work2[n];
  117781. for(i=0;i<n;i++){
  117782. work2[i]=logmask[i]+work[i];
  117783. }
  117784. if(seq&1)
  117785. _analysis_output("median2R",seq/2,work,n,1,0,0);
  117786. else
  117787. _analysis_output("median2L",seq/2,work,n,1,0,0);
  117788. if(seq&1)
  117789. _analysis_output("envelope2R",seq/2,work2,n,1,0,0);
  117790. else
  117791. _analysis_output("envelope2L",seq/2,work2,n,1,0,0);
  117792. seq++;
  117793. }
  117794. #endif
  117795. for(i=0;i<n;i++){
  117796. int dB=logmask[i]+.5;
  117797. if(dB>=NOISE_COMPAND_LEVELS)dB=NOISE_COMPAND_LEVELS-1;
  117798. if(dB<0)dB=0;
  117799. logmask[i]= work[i]+p->vi->noisecompand[dB];
  117800. }
  117801. }
  117802. void _vp_tonemask(vorbis_look_psy *p,
  117803. float *logfft,
  117804. float *logmask,
  117805. float global_specmax,
  117806. float local_specmax){
  117807. int i,n=p->n;
  117808. float *seed=(float*) alloca(sizeof(*seed)*p->total_octave_lines);
  117809. float att=local_specmax+p->vi->ath_adjatt;
  117810. for(i=0;i<p->total_octave_lines;i++)seed[i]=NEGINF;
  117811. /* set the ATH (floating below localmax, not global max by a
  117812. specified att) */
  117813. if(att<p->vi->ath_maxatt)att=p->vi->ath_maxatt;
  117814. for(i=0;i<n;i++)
  117815. logmask[i]=p->ath[i]+att;
  117816. /* tone masking */
  117817. seed_loop(p,(const float ***)p->tonecurves,logfft,logmask,seed,global_specmax);
  117818. max_seeds(p,seed,logmask);
  117819. }
  117820. void _vp_offset_and_mix(vorbis_look_psy *p,
  117821. float *noise,
  117822. float *tone,
  117823. int offset_select,
  117824. float *logmask,
  117825. float *mdct,
  117826. float *logmdct){
  117827. int i,n=p->n;
  117828. float de, coeffi, cx;/* AoTuV */
  117829. float toneatt=p->vi->tone_masteratt[offset_select];
  117830. cx = p->m_val;
  117831. for(i=0;i<n;i++){
  117832. float val= noise[i]+p->noiseoffset[offset_select][i];
  117833. if(val>p->vi->noisemaxsupp)val=p->vi->noisemaxsupp;
  117834. logmask[i]=max(val,tone[i]+toneatt);
  117835. /* AoTuV */
  117836. /** @ M1 **
  117837. The following codes improve a noise problem.
  117838. A fundamental idea uses the value of masking and carries out
  117839. the relative compensation of the MDCT.
  117840. However, this code is not perfect and all noise problems cannot be solved.
  117841. by Aoyumi @ 2004/04/18
  117842. */
  117843. if(offset_select == 1) {
  117844. coeffi = -17.2; /* coeffi is a -17.2dB threshold */
  117845. val = val - logmdct[i]; /* val == mdct line value relative to floor in dB */
  117846. if(val > coeffi){
  117847. /* mdct value is > -17.2 dB below floor */
  117848. de = 1.0-((val-coeffi)*0.005*cx);
  117849. /* pro-rated attenuation:
  117850. -0.00 dB boost if mdct value is -17.2dB (relative to floor)
  117851. -0.77 dB boost if mdct value is 0dB (relative to floor)
  117852. -1.64 dB boost if mdct value is +17.2dB (relative to floor)
  117853. etc... */
  117854. if(de < 0) de = 0.0001;
  117855. }else
  117856. /* mdct value is <= -17.2 dB below floor */
  117857. de = 1.0-((val-coeffi)*0.0003*cx);
  117858. /* pro-rated attenuation:
  117859. +0.00 dB atten if mdct value is -17.2dB (relative to floor)
  117860. +0.45 dB atten if mdct value is -34.4dB (relative to floor)
  117861. etc... */
  117862. mdct[i] *= de;
  117863. }
  117864. }
  117865. }
  117866. float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd){
  117867. vorbis_info *vi=vd->vi;
  117868. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  117869. vorbis_info_psy_global *gi=&ci->psy_g_param;
  117870. int n=ci->blocksizes[vd->W]/2;
  117871. float secs=(float)n/vi->rate;
  117872. amp+=secs*gi->ampmax_att_per_sec;
  117873. if(amp<-9999)amp=-9999;
  117874. return(amp);
  117875. }
  117876. static void couple_lossless(float A, float B,
  117877. float *qA, float *qB){
  117878. int test1=fabs(*qA)>fabs(*qB);
  117879. test1-= fabs(*qA)<fabs(*qB);
  117880. if(!test1)test1=((fabs(A)>fabs(B))<<1)-1;
  117881. if(test1==1){
  117882. *qB=(*qA>0.f?*qA-*qB:*qB-*qA);
  117883. }else{
  117884. float temp=*qB;
  117885. *qB=(*qB>0.f?*qA-*qB:*qB-*qA);
  117886. *qA=temp;
  117887. }
  117888. if(*qB>fabs(*qA)*1.9999f){
  117889. *qB= -fabs(*qA)*2.f;
  117890. *qA= -*qA;
  117891. }
  117892. }
  117893. static float hypot_lookup[32]={
  117894. -0.009935, -0.011245, -0.012726, -0.014397,
  117895. -0.016282, -0.018407, -0.020800, -0.023494,
  117896. -0.026522, -0.029923, -0.033737, -0.038010,
  117897. -0.042787, -0.048121, -0.054064, -0.060671,
  117898. -0.068000, -0.076109, -0.085054, -0.094892,
  117899. -0.105675, -0.117451, -0.130260, -0.144134,
  117900. -0.159093, -0.175146, -0.192286, -0.210490,
  117901. -0.229718, -0.249913, -0.271001, -0.292893};
  117902. static void precomputed_couple_point(float premag,
  117903. int floorA,int floorB,
  117904. float *mag, float *ang){
  117905. int test=(floorA>floorB)-1;
  117906. int offset=31-abs(floorA-floorB);
  117907. float floormag=hypot_lookup[((offset<0)-1)&offset]+1.f;
  117908. floormag*=FLOOR1_fromdB_INV_LOOKUP[(floorB&test)|(floorA&(~test))];
  117909. *mag=premag*floormag;
  117910. *ang=0.f;
  117911. }
  117912. /* just like below, this is currently set up to only do
  117913. single-step-depth coupling. Otherwise, we'd have to do more
  117914. copying (which will be inevitable later) */
  117915. /* doing the real circular magnitude calculation is audibly superior
  117916. to (A+B)/sqrt(2) */
  117917. static float dipole_hypot(float a, float b){
  117918. if(a>0.){
  117919. if(b>0.)return sqrt(a*a+b*b);
  117920. if(a>-b)return sqrt(a*a-b*b);
  117921. return -sqrt(b*b-a*a);
  117922. }
  117923. if(b<0.)return -sqrt(a*a+b*b);
  117924. if(-a>b)return -sqrt(a*a-b*b);
  117925. return sqrt(b*b-a*a);
  117926. }
  117927. static float round_hypot(float a, float b){
  117928. if(a>0.){
  117929. if(b>0.)return sqrt(a*a+b*b);
  117930. if(a>-b)return sqrt(a*a+b*b);
  117931. return -sqrt(b*b+a*a);
  117932. }
  117933. if(b<0.)return -sqrt(a*a+b*b);
  117934. if(-a>b)return -sqrt(a*a+b*b);
  117935. return sqrt(b*b+a*a);
  117936. }
  117937. /* revert to round hypot for now */
  117938. float **_vp_quantize_couple_memo(vorbis_block *vb,
  117939. vorbis_info_psy_global *g,
  117940. vorbis_look_psy *p,
  117941. vorbis_info_mapping0 *vi,
  117942. float **mdct){
  117943. int i,j,n=p->n;
  117944. float **ret=(float**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  117945. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  117946. for(i=0;i<vi->coupling_steps;i++){
  117947. float *mdctM=mdct[vi->coupling_mag[i]];
  117948. float *mdctA=mdct[vi->coupling_ang[i]];
  117949. ret[i]=(float*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  117950. for(j=0;j<limit;j++)
  117951. ret[i][j]=dipole_hypot(mdctM[j],mdctA[j]);
  117952. for(;j<n;j++)
  117953. ret[i][j]=round_hypot(mdctM[j],mdctA[j]);
  117954. }
  117955. return(ret);
  117956. }
  117957. /* this is for per-channel noise normalization */
  117958. static int JUCE_CDECL apsort(const void *a, const void *b){
  117959. float f1=fabs(**(float**)a);
  117960. float f2=fabs(**(float**)b);
  117961. return (f1<f2)-(f1>f2);
  117962. }
  117963. int **_vp_quantize_couple_sort(vorbis_block *vb,
  117964. vorbis_look_psy *p,
  117965. vorbis_info_mapping0 *vi,
  117966. float **mags){
  117967. if(p->vi->normal_point_p){
  117968. int i,j,k,n=p->n;
  117969. int **ret=(int**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  117970. int partition=p->vi->normal_partition;
  117971. float **work=(float**) alloca(sizeof(*work)*partition);
  117972. for(i=0;i<vi->coupling_steps;i++){
  117973. ret[i]=(int*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  117974. for(j=0;j<n;j+=partition){
  117975. for(k=0;k<partition;k++)work[k]=mags[i]+k+j;
  117976. qsort(work,partition,sizeof(*work),apsort);
  117977. for(k=0;k<partition;k++)ret[i][k+j]=work[k]-mags[i];
  117978. }
  117979. }
  117980. return(ret);
  117981. }
  117982. return(NULL);
  117983. }
  117984. void _vp_noise_normalize_sort(vorbis_look_psy *p,
  117985. float *magnitudes,int *sortedindex){
  117986. int i,j,n=p->n;
  117987. vorbis_info_psy *vi=p->vi;
  117988. int partition=vi->normal_partition;
  117989. float **work=(float**) alloca(sizeof(*work)*partition);
  117990. int start=vi->normal_start;
  117991. for(j=start;j<n;j+=partition){
  117992. if(j+partition>n)partition=n-j;
  117993. for(i=0;i<partition;i++)work[i]=magnitudes+i+j;
  117994. qsort(work,partition,sizeof(*work),apsort);
  117995. for(i=0;i<partition;i++){
  117996. sortedindex[i+j-start]=work[i]-magnitudes;
  117997. }
  117998. }
  117999. }
  118000. void _vp_noise_normalize(vorbis_look_psy *p,
  118001. float *in,float *out,int *sortedindex){
  118002. int flag=0,i,j=0,n=p->n;
  118003. vorbis_info_psy *vi=p->vi;
  118004. int partition=vi->normal_partition;
  118005. int start=vi->normal_start;
  118006. if(start>n)start=n;
  118007. if(vi->normal_channel_p){
  118008. for(;j<start;j++)
  118009. out[j]=rint(in[j]);
  118010. for(;j+partition<=n;j+=partition){
  118011. float acc=0.;
  118012. int k;
  118013. for(i=j;i<j+partition;i++)
  118014. acc+=in[i]*in[i];
  118015. for(i=0;i<partition;i++){
  118016. k=sortedindex[i+j-start];
  118017. if(in[k]*in[k]>=.25f){
  118018. out[k]=rint(in[k]);
  118019. acc-=in[k]*in[k];
  118020. flag=1;
  118021. }else{
  118022. if(acc<vi->normal_thresh)break;
  118023. out[k]=unitnorm(in[k]);
  118024. acc-=1.;
  118025. }
  118026. }
  118027. for(;i<partition;i++){
  118028. k=sortedindex[i+j-start];
  118029. out[k]=0.;
  118030. }
  118031. }
  118032. }
  118033. for(;j<n;j++)
  118034. out[j]=rint(in[j]);
  118035. }
  118036. void _vp_couple(int blobno,
  118037. vorbis_info_psy_global *g,
  118038. vorbis_look_psy *p,
  118039. vorbis_info_mapping0 *vi,
  118040. float **res,
  118041. float **mag_memo,
  118042. int **mag_sort,
  118043. int **ifloor,
  118044. int *nonzero,
  118045. int sliding_lowpass){
  118046. int i,j,k,n=p->n;
  118047. /* perform any requested channel coupling */
  118048. /* point stereo can only be used in a first stage (in this encoder)
  118049. because of the dependency on floor lookups */
  118050. for(i=0;i<vi->coupling_steps;i++){
  118051. /* once we're doing multistage coupling in which a channel goes
  118052. through more than one coupling step, the floor vector
  118053. magnitudes will also have to be recalculated an propogated
  118054. along with PCM. Right now, we're not (that will wait until 5.1
  118055. most likely), so the code isn't here yet. The memory management
  118056. here is all assuming single depth couplings anyway. */
  118057. /* make sure coupling a zero and a nonzero channel results in two
  118058. nonzero channels. */
  118059. if(nonzero[vi->coupling_mag[i]] ||
  118060. nonzero[vi->coupling_ang[i]]){
  118061. float *rM=res[vi->coupling_mag[i]];
  118062. float *rA=res[vi->coupling_ang[i]];
  118063. float *qM=rM+n;
  118064. float *qA=rA+n;
  118065. int *floorM=ifloor[vi->coupling_mag[i]];
  118066. int *floorA=ifloor[vi->coupling_ang[i]];
  118067. float prepoint=stereo_threshholds[g->coupling_prepointamp[blobno]];
  118068. float postpoint=stereo_threshholds[g->coupling_postpointamp[blobno]];
  118069. int partition=(p->vi->normal_point_p?p->vi->normal_partition:p->n);
  118070. int limit=g->coupling_pointlimit[p->vi->blockflag][blobno];
  118071. int pointlimit=limit;
  118072. nonzero[vi->coupling_mag[i]]=1;
  118073. nonzero[vi->coupling_ang[i]]=1;
  118074. /* The threshold of a stereo is changed with the size of n */
  118075. if(n > 1000)
  118076. postpoint=stereo_threshholds_limited[g->coupling_postpointamp[blobno]];
  118077. for(j=0;j<p->n;j+=partition){
  118078. float acc=0.f;
  118079. for(k=0;k<partition;k++){
  118080. int l=k+j;
  118081. if(l<sliding_lowpass){
  118082. if((l>=limit && fabs(rM[l])<postpoint && fabs(rA[l])<postpoint) ||
  118083. (fabs(rM[l])<prepoint && fabs(rA[l])<prepoint)){
  118084. precomputed_couple_point(mag_memo[i][l],
  118085. floorM[l],floorA[l],
  118086. qM+l,qA+l);
  118087. if(rint(qM[l])==0.f)acc+=qM[l]*qM[l];
  118088. }else{
  118089. couple_lossless(rM[l],rA[l],qM+l,qA+l);
  118090. }
  118091. }else{
  118092. qM[l]=0.;
  118093. qA[l]=0.;
  118094. }
  118095. }
  118096. if(p->vi->normal_point_p){
  118097. for(k=0;k<partition && acc>=p->vi->normal_thresh;k++){
  118098. int l=mag_sort[i][j+k];
  118099. if(l<sliding_lowpass && l>=pointlimit && rint(qM[l])==0.f){
  118100. qM[l]=unitnorm(qM[l]);
  118101. acc-=1.f;
  118102. }
  118103. }
  118104. }
  118105. }
  118106. }
  118107. }
  118108. }
  118109. /* AoTuV */
  118110. /** @ M2 **
  118111. The boost problem by the combination of noise normalization and point stereo is eased.
  118112. However, this is a temporary patch.
  118113. by Aoyumi @ 2004/04/18
  118114. */
  118115. void hf_reduction(vorbis_info_psy_global *g,
  118116. vorbis_look_psy *p,
  118117. vorbis_info_mapping0 *vi,
  118118. float **mdct){
  118119. int i,j,n=p->n, de=0.3*p->m_val;
  118120. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  118121. for(i=0; i<vi->coupling_steps; i++){
  118122. /* for(j=start; j<limit; j++){} // ???*/
  118123. for(j=limit; j<n; j++)
  118124. mdct[i][j] *= (1.0 - de*((float)(j-limit) / (float)(n-limit)));
  118125. }
  118126. }
  118127. #endif
  118128. /*** End of inlined file: psy.c ***/
  118129. /*** Start of inlined file: registry.c ***/
  118130. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  118131. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  118132. // tasks..
  118133. #if JUCE_MSVC
  118134. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  118135. #endif
  118136. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  118137. #if JUCE_USE_OGGVORBIS
  118138. /* seems like major overkill now; the backend numbers will grow into
  118139. the infrastructure soon enough */
  118140. extern vorbis_func_floor floor0_exportbundle;
  118141. extern vorbis_func_floor floor1_exportbundle;
  118142. extern vorbis_func_residue residue0_exportbundle;
  118143. extern vorbis_func_residue residue1_exportbundle;
  118144. extern vorbis_func_residue residue2_exportbundle;
  118145. extern vorbis_func_mapping mapping0_exportbundle;
  118146. vorbis_func_floor *_floor_P[]={
  118147. &floor0_exportbundle,
  118148. &floor1_exportbundle,
  118149. };
  118150. vorbis_func_residue *_residue_P[]={
  118151. &residue0_exportbundle,
  118152. &residue1_exportbundle,
  118153. &residue2_exportbundle,
  118154. };
  118155. vorbis_func_mapping *_mapping_P[]={
  118156. &mapping0_exportbundle,
  118157. };
  118158. #endif
  118159. /*** End of inlined file: registry.c ***/
  118160. /*** Start of inlined file: res0.c ***/
  118161. /* Slow, slow, slow, simpleminded and did I mention it was slow? The
  118162. encode/decode loops are coded for clarity and performance is not
  118163. yet even a nagging little idea lurking in the shadows. Oh and BTW,
  118164. it's slow. */
  118165. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  118166. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  118167. // tasks..
  118168. #if JUCE_MSVC
  118169. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  118170. #endif
  118171. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  118172. #if JUCE_USE_OGGVORBIS
  118173. #include <stdlib.h>
  118174. #include <string.h>
  118175. #include <math.h>
  118176. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  118177. #include <stdio.h>
  118178. #endif
  118179. typedef struct {
  118180. vorbis_info_residue0 *info;
  118181. int parts;
  118182. int stages;
  118183. codebook *fullbooks;
  118184. codebook *phrasebook;
  118185. codebook ***partbooks;
  118186. int partvals;
  118187. int **decodemap;
  118188. long postbits;
  118189. long phrasebits;
  118190. long frames;
  118191. #if defined(TRAIN_RES) || defined(TRAIN_RESAUX)
  118192. int train_seq;
  118193. long *training_data[8][64];
  118194. float training_max[8][64];
  118195. float training_min[8][64];
  118196. float tmin;
  118197. float tmax;
  118198. #endif
  118199. } vorbis_look_residue0;
  118200. void res0_free_info(vorbis_info_residue *i){
  118201. vorbis_info_residue0 *info=(vorbis_info_residue0 *)i;
  118202. if(info){
  118203. memset(info,0,sizeof(*info));
  118204. _ogg_free(info);
  118205. }
  118206. }
  118207. void res0_free_look(vorbis_look_residue *i){
  118208. int j;
  118209. if(i){
  118210. vorbis_look_residue0 *look=(vorbis_look_residue0 *)i;
  118211. #ifdef TRAIN_RES
  118212. {
  118213. int j,k,l;
  118214. for(j=0;j<look->parts;j++){
  118215. /*fprintf(stderr,"partition %d: ",j);*/
  118216. for(k=0;k<8;k++)
  118217. if(look->training_data[k][j]){
  118218. char buffer[80];
  118219. FILE *of;
  118220. codebook *statebook=look->partbooks[j][k];
  118221. /* long and short into the same bucket by current convention */
  118222. sprintf(buffer,"res_part%d_pass%d.vqd",j,k);
  118223. of=fopen(buffer,"a");
  118224. for(l=0;l<statebook->entries;l++)
  118225. fprintf(of,"%d:%ld\n",l,look->training_data[k][j][l]);
  118226. fclose(of);
  118227. /*fprintf(stderr,"%d(%.2f|%.2f) ",k,
  118228. look->training_min[k][j],look->training_max[k][j]);*/
  118229. _ogg_free(look->training_data[k][j]);
  118230. look->training_data[k][j]=NULL;
  118231. }
  118232. /*fprintf(stderr,"\n");*/
  118233. }
  118234. }
  118235. fprintf(stderr,"min/max residue: %g::%g\n",look->tmin,look->tmax);
  118236. /*fprintf(stderr,"residue bit usage %f:%f (%f total)\n",
  118237. (float)look->phrasebits/look->frames,
  118238. (float)look->postbits/look->frames,
  118239. (float)(look->postbits+look->phrasebits)/look->frames);*/
  118240. #endif
  118241. /*vorbis_info_residue0 *info=look->info;
  118242. fprintf(stderr,
  118243. "%ld frames encoded in %ld phrasebits and %ld residue bits "
  118244. "(%g/frame) \n",look->frames,look->phrasebits,
  118245. look->resbitsflat,
  118246. (look->phrasebits+look->resbitsflat)/(float)look->frames);
  118247. for(j=0;j<look->parts;j++){
  118248. long acc=0;
  118249. fprintf(stderr,"\t[%d] == ",j);
  118250. for(k=0;k<look->stages;k++)
  118251. if((info->secondstages[j]>>k)&1){
  118252. fprintf(stderr,"%ld,",look->resbits[j][k]);
  118253. acc+=look->resbits[j][k];
  118254. }
  118255. fprintf(stderr,":: (%ld vals) %1.2fbits/sample\n",look->resvals[j],
  118256. acc?(float)acc/(look->resvals[j]*info->grouping):0);
  118257. }
  118258. fprintf(stderr,"\n");*/
  118259. for(j=0;j<look->parts;j++)
  118260. if(look->partbooks[j])_ogg_free(look->partbooks[j]);
  118261. _ogg_free(look->partbooks);
  118262. for(j=0;j<look->partvals;j++)
  118263. _ogg_free(look->decodemap[j]);
  118264. _ogg_free(look->decodemap);
  118265. memset(look,0,sizeof(*look));
  118266. _ogg_free(look);
  118267. }
  118268. }
  118269. static int icount(unsigned int v){
  118270. int ret=0;
  118271. while(v){
  118272. ret+=v&1;
  118273. v>>=1;
  118274. }
  118275. return(ret);
  118276. }
  118277. void res0_pack(vorbis_info_residue *vr,oggpack_buffer *opb){
  118278. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  118279. int j,acc=0;
  118280. oggpack_write(opb,info->begin,24);
  118281. oggpack_write(opb,info->end,24);
  118282. oggpack_write(opb,info->grouping-1,24); /* residue vectors to group and
  118283. code with a partitioned book */
  118284. oggpack_write(opb,info->partitions-1,6); /* possible partition choices */
  118285. oggpack_write(opb,info->groupbook,8); /* group huffman book */
  118286. /* secondstages is a bitmask; as encoding progresses pass by pass, a
  118287. bitmask of one indicates this partition class has bits to write
  118288. this pass */
  118289. for(j=0;j<info->partitions;j++){
  118290. if(ilog(info->secondstages[j])>3){
  118291. /* yes, this is a minor hack due to not thinking ahead */
  118292. oggpack_write(opb,info->secondstages[j],3);
  118293. oggpack_write(opb,1,1);
  118294. oggpack_write(opb,info->secondstages[j]>>3,5);
  118295. }else
  118296. oggpack_write(opb,info->secondstages[j],4); /* trailing zero */
  118297. acc+=icount(info->secondstages[j]);
  118298. }
  118299. for(j=0;j<acc;j++)
  118300. oggpack_write(opb,info->booklist[j],8);
  118301. }
  118302. /* vorbis_info is for range checking */
  118303. vorbis_info_residue *res0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  118304. int j,acc=0;
  118305. vorbis_info_residue0 *info=(vorbis_info_residue0*) _ogg_calloc(1,sizeof(*info));
  118306. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  118307. info->begin=oggpack_read(opb,24);
  118308. info->end=oggpack_read(opb,24);
  118309. info->grouping=oggpack_read(opb,24)+1;
  118310. info->partitions=oggpack_read(opb,6)+1;
  118311. info->groupbook=oggpack_read(opb,8);
  118312. for(j=0;j<info->partitions;j++){
  118313. int cascade=oggpack_read(opb,3);
  118314. if(oggpack_read(opb,1))
  118315. cascade|=(oggpack_read(opb,5)<<3);
  118316. info->secondstages[j]=cascade;
  118317. acc+=icount(cascade);
  118318. }
  118319. for(j=0;j<acc;j++)
  118320. info->booklist[j]=oggpack_read(opb,8);
  118321. if(info->groupbook>=ci->books)goto errout;
  118322. for(j=0;j<acc;j++)
  118323. if(info->booklist[j]>=ci->books)goto errout;
  118324. return(info);
  118325. errout:
  118326. res0_free_info(info);
  118327. return(NULL);
  118328. }
  118329. vorbis_look_residue *res0_look(vorbis_dsp_state *vd,
  118330. vorbis_info_residue *vr){
  118331. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  118332. vorbis_look_residue0 *look=(vorbis_look_residue0 *)_ogg_calloc(1,sizeof(*look));
  118333. codec_setup_info *ci=(codec_setup_info*)vd->vi->codec_setup;
  118334. int j,k,acc=0;
  118335. int dim;
  118336. int maxstage=0;
  118337. look->info=info;
  118338. look->parts=info->partitions;
  118339. look->fullbooks=ci->fullbooks;
  118340. look->phrasebook=ci->fullbooks+info->groupbook;
  118341. dim=look->phrasebook->dim;
  118342. look->partbooks=(codebook***)_ogg_calloc(look->parts,sizeof(*look->partbooks));
  118343. for(j=0;j<look->parts;j++){
  118344. int stages=ilog(info->secondstages[j]);
  118345. if(stages){
  118346. if(stages>maxstage)maxstage=stages;
  118347. look->partbooks[j]=(codebook**) _ogg_calloc(stages,sizeof(*look->partbooks[j]));
  118348. for(k=0;k<stages;k++)
  118349. if(info->secondstages[j]&(1<<k)){
  118350. look->partbooks[j][k]=ci->fullbooks+info->booklist[acc++];
  118351. #ifdef TRAIN_RES
  118352. look->training_data[k][j]=_ogg_calloc(look->partbooks[j][k]->entries,
  118353. sizeof(***look->training_data));
  118354. #endif
  118355. }
  118356. }
  118357. }
  118358. look->partvals=rint(pow((float)look->parts,(float)dim));
  118359. look->stages=maxstage;
  118360. look->decodemap=(int**)_ogg_malloc(look->partvals*sizeof(*look->decodemap));
  118361. for(j=0;j<look->partvals;j++){
  118362. long val=j;
  118363. long mult=look->partvals/look->parts;
  118364. look->decodemap[j]=(int*)_ogg_malloc(dim*sizeof(*look->decodemap[j]));
  118365. for(k=0;k<dim;k++){
  118366. long deco=val/mult;
  118367. val-=deco*mult;
  118368. mult/=look->parts;
  118369. look->decodemap[j][k]=deco;
  118370. }
  118371. }
  118372. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  118373. {
  118374. static int train_seq=0;
  118375. look->train_seq=train_seq++;
  118376. }
  118377. #endif
  118378. return(look);
  118379. }
  118380. /* break an abstraction and copy some code for performance purposes */
  118381. static int local_book_besterror(codebook *book,float *a){
  118382. int dim=book->dim,i,k,o;
  118383. int best=0;
  118384. encode_aux_threshmatch *tt=book->c->thresh_tree;
  118385. /* find the quant val of each scalar */
  118386. for(k=0,o=dim;k<dim;++k){
  118387. float val=a[--o];
  118388. i=tt->threshvals>>1;
  118389. if(val<tt->quantthresh[i]){
  118390. if(val<tt->quantthresh[i-1]){
  118391. for(--i;i>0;--i)
  118392. if(val>=tt->quantthresh[i-1])
  118393. break;
  118394. }
  118395. }else{
  118396. for(++i;i<tt->threshvals-1;++i)
  118397. if(val<tt->quantthresh[i])break;
  118398. }
  118399. best=(best*tt->quantvals)+tt->quantmap[i];
  118400. }
  118401. /* regular lattices are easy :-) */
  118402. if(book->c->lengthlist[best]<=0){
  118403. const static_codebook *c=book->c;
  118404. int i,j;
  118405. float bestf=0.f;
  118406. float *e=book->valuelist;
  118407. best=-1;
  118408. for(i=0;i<book->entries;i++){
  118409. if(c->lengthlist[i]>0){
  118410. float thisx=0.f;
  118411. for(j=0;j<dim;j++){
  118412. float val=(e[j]-a[j]);
  118413. thisx+=val*val;
  118414. }
  118415. if(best==-1 || thisx<bestf){
  118416. bestf=thisx;
  118417. best=i;
  118418. }
  118419. }
  118420. e+=dim;
  118421. }
  118422. }
  118423. {
  118424. float *ptr=book->valuelist+best*dim;
  118425. for(i=0;i<dim;i++)
  118426. *a++ -= *ptr++;
  118427. }
  118428. return(best);
  118429. }
  118430. static int _encodepart(oggpack_buffer *opb,float *vec, int n,
  118431. codebook *book,long *acc){
  118432. int i,bits=0;
  118433. int dim=book->dim;
  118434. int step=n/dim;
  118435. for(i=0;i<step;i++){
  118436. int entry=local_book_besterror(book,vec+i*dim);
  118437. #ifdef TRAIN_RES
  118438. acc[entry]++;
  118439. #endif
  118440. bits+=vorbis_book_encode(book,entry,opb);
  118441. }
  118442. return(bits);
  118443. }
  118444. static long **_01class(vorbis_block *vb,vorbis_look_residue *vl,
  118445. float **in,int ch){
  118446. long i,j,k;
  118447. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118448. vorbis_info_residue0 *info=look->info;
  118449. /* move all this setup out later */
  118450. int samples_per_partition=info->grouping;
  118451. int possible_partitions=info->partitions;
  118452. int n=info->end-info->begin;
  118453. int partvals=n/samples_per_partition;
  118454. long **partword=(long**)_vorbis_block_alloc(vb,ch*sizeof(*partword));
  118455. float scale=100./samples_per_partition;
  118456. /* we find the partition type for each partition of each
  118457. channel. We'll go back and do the interleaved encoding in a
  118458. bit. For now, clarity */
  118459. for(i=0;i<ch;i++){
  118460. partword[i]=(long*)_vorbis_block_alloc(vb,n/samples_per_partition*sizeof(*partword[i]));
  118461. memset(partword[i],0,n/samples_per_partition*sizeof(*partword[i]));
  118462. }
  118463. for(i=0;i<partvals;i++){
  118464. int offset=i*samples_per_partition+info->begin;
  118465. for(j=0;j<ch;j++){
  118466. float max=0.;
  118467. float ent=0.;
  118468. for(k=0;k<samples_per_partition;k++){
  118469. if(fabs(in[j][offset+k])>max)max=fabs(in[j][offset+k]);
  118470. ent+=fabs(rint(in[j][offset+k]));
  118471. }
  118472. ent*=scale;
  118473. for(k=0;k<possible_partitions-1;k++)
  118474. if(max<=info->classmetric1[k] &&
  118475. (info->classmetric2[k]<0 || (int)ent<info->classmetric2[k]))
  118476. break;
  118477. partword[j][i]=k;
  118478. }
  118479. }
  118480. #ifdef TRAIN_RESAUX
  118481. {
  118482. FILE *of;
  118483. char buffer[80];
  118484. for(i=0;i<ch;i++){
  118485. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  118486. of=fopen(buffer,"a");
  118487. for(j=0;j<partvals;j++)
  118488. fprintf(of,"%ld, ",partword[i][j]);
  118489. fprintf(of,"\n");
  118490. fclose(of);
  118491. }
  118492. }
  118493. #endif
  118494. look->frames++;
  118495. return(partword);
  118496. }
  118497. /* designed for stereo or other modes where the partition size is an
  118498. integer multiple of the number of channels encoded in the current
  118499. submap */
  118500. static long **_2class(vorbis_block *vb,vorbis_look_residue *vl,float **in,
  118501. int ch){
  118502. long i,j,k,l;
  118503. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118504. vorbis_info_residue0 *info=look->info;
  118505. /* move all this setup out later */
  118506. int samples_per_partition=info->grouping;
  118507. int possible_partitions=info->partitions;
  118508. int n=info->end-info->begin;
  118509. int partvals=n/samples_per_partition;
  118510. long **partword=(long**)_vorbis_block_alloc(vb,sizeof(*partword));
  118511. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  118512. FILE *of;
  118513. char buffer[80];
  118514. #endif
  118515. partword[0]=(long*)_vorbis_block_alloc(vb,n*ch/samples_per_partition*sizeof(*partword[0]));
  118516. memset(partword[0],0,n*ch/samples_per_partition*sizeof(*partword[0]));
  118517. for(i=0,l=info->begin/ch;i<partvals;i++){
  118518. float magmax=0.f;
  118519. float angmax=0.f;
  118520. for(j=0;j<samples_per_partition;j+=ch){
  118521. if(fabs(in[0][l])>magmax)magmax=fabs(in[0][l]);
  118522. for(k=1;k<ch;k++)
  118523. if(fabs(in[k][l])>angmax)angmax=fabs(in[k][l]);
  118524. l++;
  118525. }
  118526. for(j=0;j<possible_partitions-1;j++)
  118527. if(magmax<=info->classmetric1[j] &&
  118528. angmax<=info->classmetric2[j])
  118529. break;
  118530. partword[0][i]=j;
  118531. }
  118532. #ifdef TRAIN_RESAUX
  118533. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  118534. of=fopen(buffer,"a");
  118535. for(i=0;i<partvals;i++)
  118536. fprintf(of,"%ld, ",partword[0][i]);
  118537. fprintf(of,"\n");
  118538. fclose(of);
  118539. #endif
  118540. look->frames++;
  118541. return(partword);
  118542. }
  118543. static int _01forward(oggpack_buffer *opb,
  118544. vorbis_block *vb,vorbis_look_residue *vl,
  118545. float **in,int ch,
  118546. long **partword,
  118547. int (*encode)(oggpack_buffer *,float *,int,
  118548. codebook *,long *)){
  118549. long i,j,k,s;
  118550. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118551. vorbis_info_residue0 *info=look->info;
  118552. /* move all this setup out later */
  118553. int samples_per_partition=info->grouping;
  118554. int possible_partitions=info->partitions;
  118555. int partitions_per_word=look->phrasebook->dim;
  118556. int n=info->end-info->begin;
  118557. int partvals=n/samples_per_partition;
  118558. long resbits[128];
  118559. long resvals[128];
  118560. #ifdef TRAIN_RES
  118561. for(i=0;i<ch;i++)
  118562. for(j=info->begin;j<info->end;j++){
  118563. if(in[i][j]>look->tmax)look->tmax=in[i][j];
  118564. if(in[i][j]<look->tmin)look->tmin=in[i][j];
  118565. }
  118566. #endif
  118567. memset(resbits,0,sizeof(resbits));
  118568. memset(resvals,0,sizeof(resvals));
  118569. /* we code the partition words for each channel, then the residual
  118570. words for a partition per channel until we've written all the
  118571. residual words for that partition word. Then write the next
  118572. partition channel words... */
  118573. for(s=0;s<look->stages;s++){
  118574. for(i=0;i<partvals;){
  118575. /* first we encode a partition codeword for each channel */
  118576. if(s==0){
  118577. for(j=0;j<ch;j++){
  118578. long val=partword[j][i];
  118579. for(k=1;k<partitions_per_word;k++){
  118580. val*=possible_partitions;
  118581. if(i+k<partvals)
  118582. val+=partword[j][i+k];
  118583. }
  118584. /* training hack */
  118585. if(val<look->phrasebook->entries)
  118586. look->phrasebits+=vorbis_book_encode(look->phrasebook,val,opb);
  118587. #if 0 /*def TRAIN_RES*/
  118588. else
  118589. fprintf(stderr,"!");
  118590. #endif
  118591. }
  118592. }
  118593. /* now we encode interleaved residual values for the partitions */
  118594. for(k=0;k<partitions_per_word && i<partvals;k++,i++){
  118595. long offset=i*samples_per_partition+info->begin;
  118596. for(j=0;j<ch;j++){
  118597. if(s==0)resvals[partword[j][i]]+=samples_per_partition;
  118598. if(info->secondstages[partword[j][i]]&(1<<s)){
  118599. codebook *statebook=look->partbooks[partword[j][i]][s];
  118600. if(statebook){
  118601. int ret;
  118602. long *accumulator=NULL;
  118603. #ifdef TRAIN_RES
  118604. accumulator=look->training_data[s][partword[j][i]];
  118605. {
  118606. int l;
  118607. float *samples=in[j]+offset;
  118608. for(l=0;l<samples_per_partition;l++){
  118609. if(samples[l]<look->training_min[s][partword[j][i]])
  118610. look->training_min[s][partword[j][i]]=samples[l];
  118611. if(samples[l]>look->training_max[s][partword[j][i]])
  118612. look->training_max[s][partword[j][i]]=samples[l];
  118613. }
  118614. }
  118615. #endif
  118616. ret=encode(opb,in[j]+offset,samples_per_partition,
  118617. statebook,accumulator);
  118618. look->postbits+=ret;
  118619. resbits[partword[j][i]]+=ret;
  118620. }
  118621. }
  118622. }
  118623. }
  118624. }
  118625. }
  118626. /*{
  118627. long total=0;
  118628. long totalbits=0;
  118629. fprintf(stderr,"%d :: ",vb->mode);
  118630. for(k=0;k<possible_partitions;k++){
  118631. fprintf(stderr,"%ld/%1.2g, ",resvals[k],(float)resbits[k]/resvals[k]);
  118632. total+=resvals[k];
  118633. totalbits+=resbits[k];
  118634. }
  118635. fprintf(stderr,":: %ld:%1.2g\n",total,(double)totalbits/total);
  118636. }*/
  118637. return(0);
  118638. }
  118639. /* a truncated packet here just means 'stop working'; it's not an error */
  118640. static int _01inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118641. float **in,int ch,
  118642. long (*decodepart)(codebook *, float *,
  118643. oggpack_buffer *,int)){
  118644. long i,j,k,l,s;
  118645. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118646. vorbis_info_residue0 *info=look->info;
  118647. /* move all this setup out later */
  118648. int samples_per_partition=info->grouping;
  118649. int partitions_per_word=look->phrasebook->dim;
  118650. int n=info->end-info->begin;
  118651. int partvals=n/samples_per_partition;
  118652. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  118653. int ***partword=(int***)alloca(ch*sizeof(*partword));
  118654. for(j=0;j<ch;j++)
  118655. partword[j]=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword[j]));
  118656. for(s=0;s<look->stages;s++){
  118657. /* each loop decodes on partition codeword containing
  118658. partitions_pre_word partitions */
  118659. for(i=0,l=0;i<partvals;l++){
  118660. if(s==0){
  118661. /* fetch the partition word for each channel */
  118662. for(j=0;j<ch;j++){
  118663. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  118664. if(temp==-1)goto eopbreak;
  118665. partword[j][l]=look->decodemap[temp];
  118666. if(partword[j][l]==NULL)goto errout;
  118667. }
  118668. }
  118669. /* now we decode residual values for the partitions */
  118670. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  118671. for(j=0;j<ch;j++){
  118672. long offset=info->begin+i*samples_per_partition;
  118673. if(info->secondstages[partword[j][l][k]]&(1<<s)){
  118674. codebook *stagebook=look->partbooks[partword[j][l][k]][s];
  118675. if(stagebook){
  118676. if(decodepart(stagebook,in[j]+offset,&vb->opb,
  118677. samples_per_partition)==-1)goto eopbreak;
  118678. }
  118679. }
  118680. }
  118681. }
  118682. }
  118683. errout:
  118684. eopbreak:
  118685. return(0);
  118686. }
  118687. #if 0
  118688. /* residue 0 and 1 are just slight variants of one another. 0 is
  118689. interleaved, 1 is not */
  118690. long **res0_class(vorbis_block *vb,vorbis_look_residue *vl,
  118691. float **in,int *nonzero,int ch){
  118692. /* we encode only the nonzero parts of a bundle */
  118693. int i,used=0;
  118694. for(i=0;i<ch;i++)
  118695. if(nonzero[i])
  118696. in[used++]=in[i];
  118697. if(used)
  118698. /*return(_01class(vb,vl,in,used,_interleaved_testhack));*/
  118699. return(_01class(vb,vl,in,used));
  118700. else
  118701. return(0);
  118702. }
  118703. int res0_forward(vorbis_block *vb,vorbis_look_residue *vl,
  118704. float **in,float **out,int *nonzero,int ch,
  118705. long **partword){
  118706. /* we encode only the nonzero parts of a bundle */
  118707. int i,j,used=0,n=vb->pcmend/2;
  118708. for(i=0;i<ch;i++)
  118709. if(nonzero[i]){
  118710. if(out)
  118711. for(j=0;j<n;j++)
  118712. out[i][j]+=in[i][j];
  118713. in[used++]=in[i];
  118714. }
  118715. if(used){
  118716. int ret=_01forward(vb,vl,in,used,partword,
  118717. _interleaved_encodepart);
  118718. if(out){
  118719. used=0;
  118720. for(i=0;i<ch;i++)
  118721. if(nonzero[i]){
  118722. for(j=0;j<n;j++)
  118723. out[i][j]-=in[used][j];
  118724. used++;
  118725. }
  118726. }
  118727. return(ret);
  118728. }else{
  118729. return(0);
  118730. }
  118731. }
  118732. #endif
  118733. int res0_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118734. float **in,int *nonzero,int ch){
  118735. int i,used=0;
  118736. for(i=0;i<ch;i++)
  118737. if(nonzero[i])
  118738. in[used++]=in[i];
  118739. if(used)
  118740. return(_01inverse(vb,vl,in,used,vorbis_book_decodevs_add));
  118741. else
  118742. return(0);
  118743. }
  118744. int res1_forward(oggpack_buffer *opb,vorbis_block *vb,vorbis_look_residue *vl,
  118745. float **in,float **out,int *nonzero,int ch,
  118746. long **partword){
  118747. int i,j,used=0,n=vb->pcmend/2;
  118748. for(i=0;i<ch;i++)
  118749. if(nonzero[i]){
  118750. if(out)
  118751. for(j=0;j<n;j++)
  118752. out[i][j]+=in[i][j];
  118753. in[used++]=in[i];
  118754. }
  118755. if(used){
  118756. int ret=_01forward(opb,vb,vl,in,used,partword,_encodepart);
  118757. if(out){
  118758. used=0;
  118759. for(i=0;i<ch;i++)
  118760. if(nonzero[i]){
  118761. for(j=0;j<n;j++)
  118762. out[i][j]-=in[used][j];
  118763. used++;
  118764. }
  118765. }
  118766. return(ret);
  118767. }else{
  118768. return(0);
  118769. }
  118770. }
  118771. long **res1_class(vorbis_block *vb,vorbis_look_residue *vl,
  118772. float **in,int *nonzero,int ch){
  118773. int i,used=0;
  118774. for(i=0;i<ch;i++)
  118775. if(nonzero[i])
  118776. in[used++]=in[i];
  118777. if(used)
  118778. return(_01class(vb,vl,in,used));
  118779. else
  118780. return(0);
  118781. }
  118782. int res1_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118783. float **in,int *nonzero,int ch){
  118784. int i,used=0;
  118785. for(i=0;i<ch;i++)
  118786. if(nonzero[i])
  118787. in[used++]=in[i];
  118788. if(used)
  118789. return(_01inverse(vb,vl,in,used,vorbis_book_decodev_add));
  118790. else
  118791. return(0);
  118792. }
  118793. long **res2_class(vorbis_block *vb,vorbis_look_residue *vl,
  118794. float **in,int *nonzero,int ch){
  118795. int i,used=0;
  118796. for(i=0;i<ch;i++)
  118797. if(nonzero[i])used++;
  118798. if(used)
  118799. return(_2class(vb,vl,in,ch));
  118800. else
  118801. return(0);
  118802. }
  118803. /* res2 is slightly more different; all the channels are interleaved
  118804. into a single vector and encoded. */
  118805. int res2_forward(oggpack_buffer *opb,
  118806. vorbis_block *vb,vorbis_look_residue *vl,
  118807. float **in,float **out,int *nonzero,int ch,
  118808. long **partword){
  118809. long i,j,k,n=vb->pcmend/2,used=0;
  118810. /* don't duplicate the code; use a working vector hack for now and
  118811. reshape ourselves into a single channel res1 */
  118812. /* ugly; reallocs for each coupling pass :-( */
  118813. float *work=(float*)_vorbis_block_alloc(vb,ch*n*sizeof(*work));
  118814. for(i=0;i<ch;i++){
  118815. float *pcm=in[i];
  118816. if(nonzero[i])used++;
  118817. for(j=0,k=i;j<n;j++,k+=ch)
  118818. work[k]=pcm[j];
  118819. }
  118820. if(used){
  118821. int ret=_01forward(opb,vb,vl,&work,1,partword,_encodepart);
  118822. /* update the sofar vector */
  118823. if(out){
  118824. for(i=0;i<ch;i++){
  118825. float *pcm=in[i];
  118826. float *sofar=out[i];
  118827. for(j=0,k=i;j<n;j++,k+=ch)
  118828. sofar[j]+=pcm[j]-work[k];
  118829. }
  118830. }
  118831. return(ret);
  118832. }else{
  118833. return(0);
  118834. }
  118835. }
  118836. /* duplicate code here as speed is somewhat more important */
  118837. int res2_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118838. float **in,int *nonzero,int ch){
  118839. long i,k,l,s;
  118840. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118841. vorbis_info_residue0 *info=look->info;
  118842. /* move all this setup out later */
  118843. int samples_per_partition=info->grouping;
  118844. int partitions_per_word=look->phrasebook->dim;
  118845. int n=info->end-info->begin;
  118846. int partvals=n/samples_per_partition;
  118847. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  118848. int **partword=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword));
  118849. for(i=0;i<ch;i++)if(nonzero[i])break;
  118850. if(i==ch)return(0); /* no nonzero vectors */
  118851. for(s=0;s<look->stages;s++){
  118852. for(i=0,l=0;i<partvals;l++){
  118853. if(s==0){
  118854. /* fetch the partition word */
  118855. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  118856. if(temp==-1)goto eopbreak;
  118857. partword[l]=look->decodemap[temp];
  118858. if(partword[l]==NULL)goto errout;
  118859. }
  118860. /* now we decode residual values for the partitions */
  118861. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  118862. if(info->secondstages[partword[l][k]]&(1<<s)){
  118863. codebook *stagebook=look->partbooks[partword[l][k]][s];
  118864. if(stagebook){
  118865. if(vorbis_book_decodevv_add(stagebook,in,
  118866. i*samples_per_partition+info->begin,ch,
  118867. &vb->opb,samples_per_partition)==-1)
  118868. goto eopbreak;
  118869. }
  118870. }
  118871. }
  118872. }
  118873. errout:
  118874. eopbreak:
  118875. return(0);
  118876. }
  118877. vorbis_func_residue residue0_exportbundle={
  118878. NULL,
  118879. &res0_unpack,
  118880. &res0_look,
  118881. &res0_free_info,
  118882. &res0_free_look,
  118883. NULL,
  118884. NULL,
  118885. &res0_inverse
  118886. };
  118887. vorbis_func_residue residue1_exportbundle={
  118888. &res0_pack,
  118889. &res0_unpack,
  118890. &res0_look,
  118891. &res0_free_info,
  118892. &res0_free_look,
  118893. &res1_class,
  118894. &res1_forward,
  118895. &res1_inverse
  118896. };
  118897. vorbis_func_residue residue2_exportbundle={
  118898. &res0_pack,
  118899. &res0_unpack,
  118900. &res0_look,
  118901. &res0_free_info,
  118902. &res0_free_look,
  118903. &res2_class,
  118904. &res2_forward,
  118905. &res2_inverse
  118906. };
  118907. #endif
  118908. /*** End of inlined file: res0.c ***/
  118909. /*** Start of inlined file: sharedbook.c ***/
  118910. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  118911. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  118912. // tasks..
  118913. #if JUCE_MSVC
  118914. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  118915. #endif
  118916. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  118917. #if JUCE_USE_OGGVORBIS
  118918. #include <stdlib.h>
  118919. #include <math.h>
  118920. #include <string.h>
  118921. /**** pack/unpack helpers ******************************************/
  118922. int _ilog(unsigned int v){
  118923. int ret=0;
  118924. while(v){
  118925. ret++;
  118926. v>>=1;
  118927. }
  118928. return(ret);
  118929. }
  118930. /* 32 bit float (not IEEE; nonnormalized mantissa +
  118931. biased exponent) : neeeeeee eeemmmmm mmmmmmmm mmmmmmmm
  118932. Why not IEEE? It's just not that important here. */
  118933. #define VQ_FEXP 10
  118934. #define VQ_FMAN 21
  118935. #define VQ_FEXP_BIAS 768 /* bias toward values smaller than 1. */
  118936. /* doesn't currently guard under/overflow */
  118937. long _float32_pack(float val){
  118938. int sign=0;
  118939. long exp;
  118940. long mant;
  118941. if(val<0){
  118942. sign=0x80000000;
  118943. val= -val;
  118944. }
  118945. exp= floor(log(val)/log(2.f));
  118946. mant=rint(ldexp(val,(VQ_FMAN-1)-exp));
  118947. exp=(exp+VQ_FEXP_BIAS)<<VQ_FMAN;
  118948. return(sign|exp|mant);
  118949. }
  118950. float _float32_unpack(long val){
  118951. double mant=val&0x1fffff;
  118952. int sign=val&0x80000000;
  118953. long exp =(val&0x7fe00000L)>>VQ_FMAN;
  118954. if(sign)mant= -mant;
  118955. return(ldexp(mant,exp-(VQ_FMAN-1)-VQ_FEXP_BIAS));
  118956. }
  118957. /* given a list of word lengths, generate a list of codewords. Works
  118958. for length ordered or unordered, always assigns the lowest valued
  118959. codewords first. Extended to handle unused entries (length 0) */
  118960. ogg_uint32_t *_make_words(long *l,long n,long sparsecount){
  118961. long i,j,count=0;
  118962. ogg_uint32_t marker[33];
  118963. ogg_uint32_t *r=(ogg_uint32_t*)_ogg_malloc((sparsecount?sparsecount:n)*sizeof(*r));
  118964. memset(marker,0,sizeof(marker));
  118965. for(i=0;i<n;i++){
  118966. long length=l[i];
  118967. if(length>0){
  118968. ogg_uint32_t entry=marker[length];
  118969. /* when we claim a node for an entry, we also claim the nodes
  118970. below it (pruning off the imagined tree that may have dangled
  118971. from it) as well as blocking the use of any nodes directly
  118972. above for leaves */
  118973. /* update ourself */
  118974. if(length<32 && (entry>>length)){
  118975. /* error condition; the lengths must specify an overpopulated tree */
  118976. _ogg_free(r);
  118977. return(NULL);
  118978. }
  118979. r[count++]=entry;
  118980. /* Look to see if the next shorter marker points to the node
  118981. above. if so, update it and repeat. */
  118982. {
  118983. for(j=length;j>0;j--){
  118984. if(marker[j]&1){
  118985. /* have to jump branches */
  118986. if(j==1)
  118987. marker[1]++;
  118988. else
  118989. marker[j]=marker[j-1]<<1;
  118990. break; /* invariant says next upper marker would already
  118991. have been moved if it was on the same path */
  118992. }
  118993. marker[j]++;
  118994. }
  118995. }
  118996. /* prune the tree; the implicit invariant says all the longer
  118997. markers were dangling from our just-taken node. Dangle them
  118998. from our *new* node. */
  118999. for(j=length+1;j<33;j++)
  119000. if((marker[j]>>1) == entry){
  119001. entry=marker[j];
  119002. marker[j]=marker[j-1]<<1;
  119003. }else
  119004. break;
  119005. }else
  119006. if(sparsecount==0)count++;
  119007. }
  119008. /* bitreverse the words because our bitwise packer/unpacker is LSb
  119009. endian */
  119010. for(i=0,count=0;i<n;i++){
  119011. ogg_uint32_t temp=0;
  119012. for(j=0;j<l[i];j++){
  119013. temp<<=1;
  119014. temp|=(r[count]>>j)&1;
  119015. }
  119016. if(sparsecount){
  119017. if(l[i])
  119018. r[count++]=temp;
  119019. }else
  119020. r[count++]=temp;
  119021. }
  119022. return(r);
  119023. }
  119024. /* there might be a straightforward one-line way to do the below
  119025. that's portable and totally safe against roundoff, but I haven't
  119026. thought of it. Therefore, we opt on the side of caution */
  119027. long _book_maptype1_quantvals(const static_codebook *b){
  119028. long vals=floor(pow((float)b->entries,1.f/b->dim));
  119029. /* the above *should* be reliable, but we'll not assume that FP is
  119030. ever reliable when bitstream sync is at stake; verify via integer
  119031. means that vals really is the greatest value of dim for which
  119032. vals^b->bim <= b->entries */
  119033. /* treat the above as an initial guess */
  119034. while(1){
  119035. long acc=1;
  119036. long acc1=1;
  119037. int i;
  119038. for(i=0;i<b->dim;i++){
  119039. acc*=vals;
  119040. acc1*=vals+1;
  119041. }
  119042. if(acc<=b->entries && acc1>b->entries){
  119043. return(vals);
  119044. }else{
  119045. if(acc>b->entries){
  119046. vals--;
  119047. }else{
  119048. vals++;
  119049. }
  119050. }
  119051. }
  119052. }
  119053. /* unpack the quantized list of values for encode/decode ***********/
  119054. /* we need to deal with two map types: in map type 1, the values are
  119055. generated algorithmically (each column of the vector counts through
  119056. the values in the quant vector). in map type 2, all the values came
  119057. in in an explicit list. Both value lists must be unpacked */
  119058. float *_book_unquantize(const static_codebook *b,int n,int *sparsemap){
  119059. long j,k,count=0;
  119060. if(b->maptype==1 || b->maptype==2){
  119061. int quantvals;
  119062. float mindel=_float32_unpack(b->q_min);
  119063. float delta=_float32_unpack(b->q_delta);
  119064. float *r=(float*)_ogg_calloc(n*b->dim,sizeof(*r));
  119065. /* maptype 1 and 2 both use a quantized value vector, but
  119066. different sizes */
  119067. switch(b->maptype){
  119068. case 1:
  119069. /* most of the time, entries%dimensions == 0, but we need to be
  119070. well defined. We define that the possible vales at each
  119071. scalar is values == entries/dim. If entries%dim != 0, we'll
  119072. have 'too few' values (values*dim<entries), which means that
  119073. we'll have 'left over' entries; left over entries use zeroed
  119074. values (and are wasted). So don't generate codebooks like
  119075. that */
  119076. quantvals=_book_maptype1_quantvals(b);
  119077. for(j=0;j<b->entries;j++){
  119078. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  119079. float last=0.f;
  119080. int indexdiv=1;
  119081. for(k=0;k<b->dim;k++){
  119082. int index= (j/indexdiv)%quantvals;
  119083. float val=b->quantlist[index];
  119084. val=fabs(val)*delta+mindel+last;
  119085. if(b->q_sequencep)last=val;
  119086. if(sparsemap)
  119087. r[sparsemap[count]*b->dim+k]=val;
  119088. else
  119089. r[count*b->dim+k]=val;
  119090. indexdiv*=quantvals;
  119091. }
  119092. count++;
  119093. }
  119094. }
  119095. break;
  119096. case 2:
  119097. for(j=0;j<b->entries;j++){
  119098. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  119099. float last=0.f;
  119100. for(k=0;k<b->dim;k++){
  119101. float val=b->quantlist[j*b->dim+k];
  119102. val=fabs(val)*delta+mindel+last;
  119103. if(b->q_sequencep)last=val;
  119104. if(sparsemap)
  119105. r[sparsemap[count]*b->dim+k]=val;
  119106. else
  119107. r[count*b->dim+k]=val;
  119108. }
  119109. count++;
  119110. }
  119111. }
  119112. break;
  119113. }
  119114. return(r);
  119115. }
  119116. return(NULL);
  119117. }
  119118. void vorbis_staticbook_clear(static_codebook *b){
  119119. if(b->allocedp){
  119120. if(b->quantlist)_ogg_free(b->quantlist);
  119121. if(b->lengthlist)_ogg_free(b->lengthlist);
  119122. if(b->nearest_tree){
  119123. _ogg_free(b->nearest_tree->ptr0);
  119124. _ogg_free(b->nearest_tree->ptr1);
  119125. _ogg_free(b->nearest_tree->p);
  119126. _ogg_free(b->nearest_tree->q);
  119127. memset(b->nearest_tree,0,sizeof(*b->nearest_tree));
  119128. _ogg_free(b->nearest_tree);
  119129. }
  119130. if(b->thresh_tree){
  119131. _ogg_free(b->thresh_tree->quantthresh);
  119132. _ogg_free(b->thresh_tree->quantmap);
  119133. memset(b->thresh_tree,0,sizeof(*b->thresh_tree));
  119134. _ogg_free(b->thresh_tree);
  119135. }
  119136. memset(b,0,sizeof(*b));
  119137. }
  119138. }
  119139. void vorbis_staticbook_destroy(static_codebook *b){
  119140. if(b->allocedp){
  119141. vorbis_staticbook_clear(b);
  119142. _ogg_free(b);
  119143. }
  119144. }
  119145. void vorbis_book_clear(codebook *b){
  119146. /* static book is not cleared; we're likely called on the lookup and
  119147. the static codebook belongs to the info struct */
  119148. if(b->valuelist)_ogg_free(b->valuelist);
  119149. if(b->codelist)_ogg_free(b->codelist);
  119150. if(b->dec_index)_ogg_free(b->dec_index);
  119151. if(b->dec_codelengths)_ogg_free(b->dec_codelengths);
  119152. if(b->dec_firsttable)_ogg_free(b->dec_firsttable);
  119153. memset(b,0,sizeof(*b));
  119154. }
  119155. int vorbis_book_init_encode(codebook *c,const static_codebook *s){
  119156. memset(c,0,sizeof(*c));
  119157. c->c=s;
  119158. c->entries=s->entries;
  119159. c->used_entries=s->entries;
  119160. c->dim=s->dim;
  119161. c->codelist=_make_words(s->lengthlist,s->entries,0);
  119162. c->valuelist=_book_unquantize(s,s->entries,NULL);
  119163. return(0);
  119164. }
  119165. static int JUCE_CDECL sort32a(const void *a,const void *b){
  119166. return ( **(ogg_uint32_t **)a>**(ogg_uint32_t **)b)-
  119167. ( **(ogg_uint32_t **)a<**(ogg_uint32_t **)b);
  119168. }
  119169. /* decode codebook arrangement is more heavily optimized than encode */
  119170. int vorbis_book_init_decode(codebook *c,const static_codebook *s){
  119171. int i,j,n=0,tabn;
  119172. int *sortindex;
  119173. memset(c,0,sizeof(*c));
  119174. /* count actually used entries */
  119175. for(i=0;i<s->entries;i++)
  119176. if(s->lengthlist[i]>0)
  119177. n++;
  119178. c->entries=s->entries;
  119179. c->used_entries=n;
  119180. c->dim=s->dim;
  119181. /* two different remappings go on here.
  119182. First, we collapse the likely sparse codebook down only to
  119183. actually represented values/words. This collapsing needs to be
  119184. indexed as map-valueless books are used to encode original entry
  119185. positions as integers.
  119186. Second, we reorder all vectors, including the entry index above,
  119187. by sorted bitreversed codeword to allow treeless decode. */
  119188. {
  119189. /* perform sort */
  119190. ogg_uint32_t *codes=_make_words(s->lengthlist,s->entries,c->used_entries);
  119191. ogg_uint32_t **codep=(ogg_uint32_t**)alloca(sizeof(*codep)*n);
  119192. if(codes==NULL)goto err_out;
  119193. for(i=0;i<n;i++){
  119194. codes[i]=ogg_bitreverse(codes[i]);
  119195. codep[i]=codes+i;
  119196. }
  119197. qsort(codep,n,sizeof(*codep),sort32a);
  119198. sortindex=(int*)alloca(n*sizeof(*sortindex));
  119199. c->codelist=(ogg_uint32_t*)_ogg_malloc(n*sizeof(*c->codelist));
  119200. /* the index is a reverse index */
  119201. for(i=0;i<n;i++){
  119202. int position=codep[i]-codes;
  119203. sortindex[position]=i;
  119204. }
  119205. for(i=0;i<n;i++)
  119206. c->codelist[sortindex[i]]=codes[i];
  119207. _ogg_free(codes);
  119208. }
  119209. c->valuelist=_book_unquantize(s,n,sortindex);
  119210. c->dec_index=(int*)_ogg_malloc(n*sizeof(*c->dec_index));
  119211. for(n=0,i=0;i<s->entries;i++)
  119212. if(s->lengthlist[i]>0)
  119213. c->dec_index[sortindex[n++]]=i;
  119214. c->dec_codelengths=(char*)_ogg_malloc(n*sizeof(*c->dec_codelengths));
  119215. for(n=0,i=0;i<s->entries;i++)
  119216. if(s->lengthlist[i]>0)
  119217. c->dec_codelengths[sortindex[n++]]=s->lengthlist[i];
  119218. c->dec_firsttablen=_ilog(c->used_entries)-4; /* this is magic */
  119219. if(c->dec_firsttablen<5)c->dec_firsttablen=5;
  119220. if(c->dec_firsttablen>8)c->dec_firsttablen=8;
  119221. tabn=1<<c->dec_firsttablen;
  119222. c->dec_firsttable=(ogg_uint32_t*)_ogg_calloc(tabn,sizeof(*c->dec_firsttable));
  119223. c->dec_maxlength=0;
  119224. for(i=0;i<n;i++){
  119225. if(c->dec_maxlength<c->dec_codelengths[i])
  119226. c->dec_maxlength=c->dec_codelengths[i];
  119227. if(c->dec_codelengths[i]<=c->dec_firsttablen){
  119228. ogg_uint32_t orig=ogg_bitreverse(c->codelist[i]);
  119229. for(j=0;j<(1<<(c->dec_firsttablen-c->dec_codelengths[i]));j++)
  119230. c->dec_firsttable[orig|(j<<c->dec_codelengths[i])]=i+1;
  119231. }
  119232. }
  119233. /* now fill in 'unused' entries in the firsttable with hi/lo search
  119234. hints for the non-direct-hits */
  119235. {
  119236. ogg_uint32_t mask=0xfffffffeUL<<(31-c->dec_firsttablen);
  119237. long lo=0,hi=0;
  119238. for(i=0;i<tabn;i++){
  119239. ogg_uint32_t word=i<<(32-c->dec_firsttablen);
  119240. if(c->dec_firsttable[ogg_bitreverse(word)]==0){
  119241. while((lo+1)<n && c->codelist[lo+1]<=word)lo++;
  119242. while( hi<n && word>=(c->codelist[hi]&mask))hi++;
  119243. /* we only actually have 15 bits per hint to play with here.
  119244. In order to overflow gracefully (nothing breaks, efficiency
  119245. just drops), encode as the difference from the extremes. */
  119246. {
  119247. unsigned long loval=lo;
  119248. unsigned long hival=n-hi;
  119249. if(loval>0x7fff)loval=0x7fff;
  119250. if(hival>0x7fff)hival=0x7fff;
  119251. c->dec_firsttable[ogg_bitreverse(word)]=
  119252. 0x80000000UL | (loval<<15) | hival;
  119253. }
  119254. }
  119255. }
  119256. }
  119257. return(0);
  119258. err_out:
  119259. vorbis_book_clear(c);
  119260. return(-1);
  119261. }
  119262. static float _dist(int el,float *ref, float *b,int step){
  119263. int i;
  119264. float acc=0.f;
  119265. for(i=0;i<el;i++){
  119266. float val=(ref[i]-b[i*step]);
  119267. acc+=val*val;
  119268. }
  119269. return(acc);
  119270. }
  119271. int _best(codebook *book, float *a, int step){
  119272. encode_aux_threshmatch *tt=book->c->thresh_tree;
  119273. #if 0
  119274. encode_aux_nearestmatch *nt=book->c->nearest_tree;
  119275. encode_aux_pigeonhole *pt=book->c->pigeon_tree;
  119276. #endif
  119277. int dim=book->dim;
  119278. int k,o;
  119279. /*int savebest=-1;
  119280. float saverr;*/
  119281. /* do we have a threshhold encode hint? */
  119282. if(tt){
  119283. int index=0,i;
  119284. /* find the quant val of each scalar */
  119285. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  119286. i=tt->threshvals>>1;
  119287. if(a[o]<tt->quantthresh[i]){
  119288. for(;i>0;i--)
  119289. if(a[o]>=tt->quantthresh[i-1])
  119290. break;
  119291. }else{
  119292. for(i++;i<tt->threshvals-1;i++)
  119293. if(a[o]<tt->quantthresh[i])break;
  119294. }
  119295. index=(index*tt->quantvals)+tt->quantmap[i];
  119296. }
  119297. /* regular lattices are easy :-) */
  119298. if(book->c->lengthlist[index]>0) /* is this unused? If so, we'll
  119299. use a decision tree after all
  119300. and fall through*/
  119301. return(index);
  119302. }
  119303. #if 0
  119304. /* do we have a pigeonhole encode hint? */
  119305. if(pt){
  119306. const static_codebook *c=book->c;
  119307. int i,besti=-1;
  119308. float best=0.f;
  119309. int entry=0;
  119310. /* dealing with sequentialness is a pain in the ass */
  119311. if(c->q_sequencep){
  119312. int pv;
  119313. long mul=1;
  119314. float qlast=0;
  119315. for(k=0,o=0;k<dim;k++,o+=step){
  119316. pv=(int)((a[o]-qlast-pt->min)/pt->del);
  119317. if(pv<0 || pv>=pt->mapentries)break;
  119318. entry+=pt->pigeonmap[pv]*mul;
  119319. mul*=pt->quantvals;
  119320. qlast+=pv*pt->del+pt->min;
  119321. }
  119322. }else{
  119323. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  119324. int pv=(int)((a[o]-pt->min)/pt->del);
  119325. if(pv<0 || pv>=pt->mapentries)break;
  119326. entry=entry*pt->quantvals+pt->pigeonmap[pv];
  119327. }
  119328. }
  119329. /* must be within the pigeonholable range; if we quant outside (or
  119330. in an entry that we define no list for), brute force it */
  119331. if(k==dim && pt->fitlength[entry]){
  119332. /* search the abbreviated list */
  119333. long *list=pt->fitlist+pt->fitmap[entry];
  119334. for(i=0;i<pt->fitlength[entry];i++){
  119335. float this=_dist(dim,book->valuelist+list[i]*dim,a,step);
  119336. if(besti==-1 || this<best){
  119337. best=this;
  119338. besti=list[i];
  119339. }
  119340. }
  119341. return(besti);
  119342. }
  119343. }
  119344. if(nt){
  119345. /* optimized using the decision tree */
  119346. while(1){
  119347. float c=0.f;
  119348. float *p=book->valuelist+nt->p[ptr];
  119349. float *q=book->valuelist+nt->q[ptr];
  119350. for(k=0,o=0;k<dim;k++,o+=step)
  119351. c+=(p[k]-q[k])*(a[o]-(p[k]+q[k])*.5);
  119352. if(c>0.f) /* in A */
  119353. ptr= -nt->ptr0[ptr];
  119354. else /* in B */
  119355. ptr= -nt->ptr1[ptr];
  119356. if(ptr<=0)break;
  119357. }
  119358. return(-ptr);
  119359. }
  119360. #endif
  119361. /* brute force it! */
  119362. {
  119363. const static_codebook *c=book->c;
  119364. int i,besti=-1;
  119365. float best=0.f;
  119366. float *e=book->valuelist;
  119367. for(i=0;i<book->entries;i++){
  119368. if(c->lengthlist[i]>0){
  119369. float thisx=_dist(dim,e,a,step);
  119370. if(besti==-1 || thisx<best){
  119371. best=thisx;
  119372. besti=i;
  119373. }
  119374. }
  119375. e+=dim;
  119376. }
  119377. /*if(savebest!=-1 && savebest!=besti){
  119378. fprintf(stderr,"brute force/pigeonhole disagreement:\n"
  119379. "original:");
  119380. for(i=0;i<dim*step;i+=step)fprintf(stderr,"%g,",a[i]);
  119381. fprintf(stderr,"\n"
  119382. "pigeonhole (entry %d, err %g):",savebest,saverr);
  119383. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  119384. (book->valuelist+savebest*dim)[i]);
  119385. fprintf(stderr,"\n"
  119386. "bruteforce (entry %d, err %g):",besti,best);
  119387. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  119388. (book->valuelist+besti*dim)[i]);
  119389. fprintf(stderr,"\n");
  119390. }*/
  119391. return(besti);
  119392. }
  119393. }
  119394. long vorbis_book_codeword(codebook *book,int entry){
  119395. if(book->c) /* only use with encode; decode optimizations are
  119396. allowed to break this */
  119397. return book->codelist[entry];
  119398. return -1;
  119399. }
  119400. long vorbis_book_codelen(codebook *book,int entry){
  119401. if(book->c) /* only use with encode; decode optimizations are
  119402. allowed to break this */
  119403. return book->c->lengthlist[entry];
  119404. return -1;
  119405. }
  119406. #ifdef _V_SELFTEST
  119407. /* Unit tests of the dequantizer; this stuff will be OK
  119408. cross-platform, I simply want to be sure that special mapping cases
  119409. actually work properly; a bug could go unnoticed for a while */
  119410. #include <stdio.h>
  119411. /* cases:
  119412. no mapping
  119413. full, explicit mapping
  119414. algorithmic mapping
  119415. nonsequential
  119416. sequential
  119417. */
  119418. static long full_quantlist1[]={0,1,2,3, 4,5,6,7, 8,3,6,1};
  119419. static long partial_quantlist1[]={0,7,2};
  119420. /* no mapping */
  119421. static_codebook test1={
  119422. 4,16,
  119423. NULL,
  119424. 0,
  119425. 0,0,0,0,
  119426. NULL,
  119427. NULL,NULL
  119428. };
  119429. static float *test1_result=NULL;
  119430. /* linear, full mapping, nonsequential */
  119431. static_codebook test2={
  119432. 4,3,
  119433. NULL,
  119434. 2,
  119435. -533200896,1611661312,4,0,
  119436. full_quantlist1,
  119437. NULL,NULL
  119438. };
  119439. static float test2_result[]={-3,-2,-1,0, 1,2,3,4, 5,0,3,-2};
  119440. /* linear, full mapping, sequential */
  119441. static_codebook test3={
  119442. 4,3,
  119443. NULL,
  119444. 2,
  119445. -533200896,1611661312,4,1,
  119446. full_quantlist1,
  119447. NULL,NULL
  119448. };
  119449. static float test3_result[]={-3,-5,-6,-6, 1,3,6,10, 5,5,8,6};
  119450. /* linear, algorithmic mapping, nonsequential */
  119451. static_codebook test4={
  119452. 3,27,
  119453. NULL,
  119454. 1,
  119455. -533200896,1611661312,4,0,
  119456. partial_quantlist1,
  119457. NULL,NULL
  119458. };
  119459. static float test4_result[]={-3,-3,-3, 4,-3,-3, -1,-3,-3,
  119460. -3, 4,-3, 4, 4,-3, -1, 4,-3,
  119461. -3,-1,-3, 4,-1,-3, -1,-1,-3,
  119462. -3,-3, 4, 4,-3, 4, -1,-3, 4,
  119463. -3, 4, 4, 4, 4, 4, -1, 4, 4,
  119464. -3,-1, 4, 4,-1, 4, -1,-1, 4,
  119465. -3,-3,-1, 4,-3,-1, -1,-3,-1,
  119466. -3, 4,-1, 4, 4,-1, -1, 4,-1,
  119467. -3,-1,-1, 4,-1,-1, -1,-1,-1};
  119468. /* linear, algorithmic mapping, sequential */
  119469. static_codebook test5={
  119470. 3,27,
  119471. NULL,
  119472. 1,
  119473. -533200896,1611661312,4,1,
  119474. partial_quantlist1,
  119475. NULL,NULL
  119476. };
  119477. static float test5_result[]={-3,-6,-9, 4, 1,-2, -1,-4,-7,
  119478. -3, 1,-2, 4, 8, 5, -1, 3, 0,
  119479. -3,-4,-7, 4, 3, 0, -1,-2,-5,
  119480. -3,-6,-2, 4, 1, 5, -1,-4, 0,
  119481. -3, 1, 5, 4, 8,12, -1, 3, 7,
  119482. -3,-4, 0, 4, 3, 7, -1,-2, 2,
  119483. -3,-6,-7, 4, 1, 0, -1,-4,-5,
  119484. -3, 1, 0, 4, 8, 7, -1, 3, 2,
  119485. -3,-4,-5, 4, 3, 2, -1,-2,-3};
  119486. void run_test(static_codebook *b,float *comp){
  119487. float *out=_book_unquantize(b,b->entries,NULL);
  119488. int i;
  119489. if(comp){
  119490. if(!out){
  119491. fprintf(stderr,"_book_unquantize incorrectly returned NULL\n");
  119492. exit(1);
  119493. }
  119494. for(i=0;i<b->entries*b->dim;i++)
  119495. if(fabs(out[i]-comp[i])>.0001){
  119496. fprintf(stderr,"disagreement in unquantized and reference data:\n"
  119497. "position %d, %g != %g\n",i,out[i],comp[i]);
  119498. exit(1);
  119499. }
  119500. }else{
  119501. if(out){
  119502. fprintf(stderr,"_book_unquantize returned a value array: \n"
  119503. " correct result should have been NULL\n");
  119504. exit(1);
  119505. }
  119506. }
  119507. }
  119508. int main(){
  119509. /* run the nine dequant tests, and compare to the hand-rolled results */
  119510. fprintf(stderr,"Dequant test 1... ");
  119511. run_test(&test1,test1_result);
  119512. fprintf(stderr,"OK\nDequant test 2... ");
  119513. run_test(&test2,test2_result);
  119514. fprintf(stderr,"OK\nDequant test 3... ");
  119515. run_test(&test3,test3_result);
  119516. fprintf(stderr,"OK\nDequant test 4... ");
  119517. run_test(&test4,test4_result);
  119518. fprintf(stderr,"OK\nDequant test 5... ");
  119519. run_test(&test5,test5_result);
  119520. fprintf(stderr,"OK\n\n");
  119521. return(0);
  119522. }
  119523. #endif
  119524. #endif
  119525. /*** End of inlined file: sharedbook.c ***/
  119526. /*** Start of inlined file: smallft.c ***/
  119527. /* FFT implementation from OggSquish, minus cosine transforms,
  119528. * minus all but radix 2/4 case. In Vorbis we only need this
  119529. * cut-down version.
  119530. *
  119531. * To do more than just power-of-two sized vectors, see the full
  119532. * version I wrote for NetLib.
  119533. *
  119534. * Note that the packing is a little strange; rather than the FFT r/i
  119535. * packing following R_0, I_n, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1,
  119536. * it follows R_0, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1, I_n like the
  119537. * FORTRAN version
  119538. */
  119539. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  119540. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  119541. // tasks..
  119542. #if JUCE_MSVC
  119543. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  119544. #endif
  119545. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  119546. #if JUCE_USE_OGGVORBIS
  119547. #include <stdlib.h>
  119548. #include <string.h>
  119549. #include <math.h>
  119550. static void drfti1(int n, float *wa, int *ifac){
  119551. static int ntryh[4] = { 4,2,3,5 };
  119552. static float tpi = 6.28318530717958648f;
  119553. float arg,argh,argld,fi;
  119554. int ntry=0,i,j=-1;
  119555. int k1, l1, l2, ib;
  119556. int ld, ii, ip, is, nq, nr;
  119557. int ido, ipm, nfm1;
  119558. int nl=n;
  119559. int nf=0;
  119560. L101:
  119561. j++;
  119562. if (j < 4)
  119563. ntry=ntryh[j];
  119564. else
  119565. ntry+=2;
  119566. L104:
  119567. nq=nl/ntry;
  119568. nr=nl-ntry*nq;
  119569. if (nr!=0) goto L101;
  119570. nf++;
  119571. ifac[nf+1]=ntry;
  119572. nl=nq;
  119573. if(ntry!=2)goto L107;
  119574. if(nf==1)goto L107;
  119575. for (i=1;i<nf;i++){
  119576. ib=nf-i+1;
  119577. ifac[ib+1]=ifac[ib];
  119578. }
  119579. ifac[2] = 2;
  119580. L107:
  119581. if(nl!=1)goto L104;
  119582. ifac[0]=n;
  119583. ifac[1]=nf;
  119584. argh=tpi/n;
  119585. is=0;
  119586. nfm1=nf-1;
  119587. l1=1;
  119588. if(nfm1==0)return;
  119589. for (k1=0;k1<nfm1;k1++){
  119590. ip=ifac[k1+2];
  119591. ld=0;
  119592. l2=l1*ip;
  119593. ido=n/l2;
  119594. ipm=ip-1;
  119595. for (j=0;j<ipm;j++){
  119596. ld+=l1;
  119597. i=is;
  119598. argld=(float)ld*argh;
  119599. fi=0.f;
  119600. for (ii=2;ii<ido;ii+=2){
  119601. fi+=1.f;
  119602. arg=fi*argld;
  119603. wa[i++]=cos(arg);
  119604. wa[i++]=sin(arg);
  119605. }
  119606. is+=ido;
  119607. }
  119608. l1=l2;
  119609. }
  119610. }
  119611. static void fdrffti(int n, float *wsave, int *ifac){
  119612. if (n == 1) return;
  119613. drfti1(n, wsave+n, ifac);
  119614. }
  119615. static void dradf2(int ido,int l1,float *cc,float *ch,float *wa1){
  119616. int i,k;
  119617. float ti2,tr2;
  119618. int t0,t1,t2,t3,t4,t5,t6;
  119619. t1=0;
  119620. t0=(t2=l1*ido);
  119621. t3=ido<<1;
  119622. for(k=0;k<l1;k++){
  119623. ch[t1<<1]=cc[t1]+cc[t2];
  119624. ch[(t1<<1)+t3-1]=cc[t1]-cc[t2];
  119625. t1+=ido;
  119626. t2+=ido;
  119627. }
  119628. if(ido<2)return;
  119629. if(ido==2)goto L105;
  119630. t1=0;
  119631. t2=t0;
  119632. for(k=0;k<l1;k++){
  119633. t3=t2;
  119634. t4=(t1<<1)+(ido<<1);
  119635. t5=t1;
  119636. t6=t1+t1;
  119637. for(i=2;i<ido;i+=2){
  119638. t3+=2;
  119639. t4-=2;
  119640. t5+=2;
  119641. t6+=2;
  119642. tr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  119643. ti2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  119644. ch[t6]=cc[t5]+ti2;
  119645. ch[t4]=ti2-cc[t5];
  119646. ch[t6-1]=cc[t5-1]+tr2;
  119647. ch[t4-1]=cc[t5-1]-tr2;
  119648. }
  119649. t1+=ido;
  119650. t2+=ido;
  119651. }
  119652. if(ido%2==1)return;
  119653. L105:
  119654. t3=(t2=(t1=ido)-1);
  119655. t2+=t0;
  119656. for(k=0;k<l1;k++){
  119657. ch[t1]=-cc[t2];
  119658. ch[t1-1]=cc[t3];
  119659. t1+=ido<<1;
  119660. t2+=ido;
  119661. t3+=ido;
  119662. }
  119663. }
  119664. static void dradf4(int ido,int l1,float *cc,float *ch,float *wa1,
  119665. float *wa2,float *wa3){
  119666. static float hsqt2 = .70710678118654752f;
  119667. int i,k,t0,t1,t2,t3,t4,t5,t6;
  119668. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  119669. t0=l1*ido;
  119670. t1=t0;
  119671. t4=t1<<1;
  119672. t2=t1+(t1<<1);
  119673. t3=0;
  119674. for(k=0;k<l1;k++){
  119675. tr1=cc[t1]+cc[t2];
  119676. tr2=cc[t3]+cc[t4];
  119677. ch[t5=t3<<2]=tr1+tr2;
  119678. ch[(ido<<2)+t5-1]=tr2-tr1;
  119679. ch[(t5+=(ido<<1))-1]=cc[t3]-cc[t4];
  119680. ch[t5]=cc[t2]-cc[t1];
  119681. t1+=ido;
  119682. t2+=ido;
  119683. t3+=ido;
  119684. t4+=ido;
  119685. }
  119686. if(ido<2)return;
  119687. if(ido==2)goto L105;
  119688. t1=0;
  119689. for(k=0;k<l1;k++){
  119690. t2=t1;
  119691. t4=t1<<2;
  119692. t5=(t6=ido<<1)+t4;
  119693. for(i=2;i<ido;i+=2){
  119694. t3=(t2+=2);
  119695. t4+=2;
  119696. t5-=2;
  119697. t3+=t0;
  119698. cr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  119699. ci2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  119700. t3+=t0;
  119701. cr3=wa2[i-2]*cc[t3-1]+wa2[i-1]*cc[t3];
  119702. ci3=wa2[i-2]*cc[t3]-wa2[i-1]*cc[t3-1];
  119703. t3+=t0;
  119704. cr4=wa3[i-2]*cc[t3-1]+wa3[i-1]*cc[t3];
  119705. ci4=wa3[i-2]*cc[t3]-wa3[i-1]*cc[t3-1];
  119706. tr1=cr2+cr4;
  119707. tr4=cr4-cr2;
  119708. ti1=ci2+ci4;
  119709. ti4=ci2-ci4;
  119710. ti2=cc[t2]+ci3;
  119711. ti3=cc[t2]-ci3;
  119712. tr2=cc[t2-1]+cr3;
  119713. tr3=cc[t2-1]-cr3;
  119714. ch[t4-1]=tr1+tr2;
  119715. ch[t4]=ti1+ti2;
  119716. ch[t5-1]=tr3-ti4;
  119717. ch[t5]=tr4-ti3;
  119718. ch[t4+t6-1]=ti4+tr3;
  119719. ch[t4+t6]=tr4+ti3;
  119720. ch[t5+t6-1]=tr2-tr1;
  119721. ch[t5+t6]=ti1-ti2;
  119722. }
  119723. t1+=ido;
  119724. }
  119725. if(ido&1)return;
  119726. L105:
  119727. t2=(t1=t0+ido-1)+(t0<<1);
  119728. t3=ido<<2;
  119729. t4=ido;
  119730. t5=ido<<1;
  119731. t6=ido;
  119732. for(k=0;k<l1;k++){
  119733. ti1=-hsqt2*(cc[t1]+cc[t2]);
  119734. tr1=hsqt2*(cc[t1]-cc[t2]);
  119735. ch[t4-1]=tr1+cc[t6-1];
  119736. ch[t4+t5-1]=cc[t6-1]-tr1;
  119737. ch[t4]=ti1-cc[t1+t0];
  119738. ch[t4+t5]=ti1+cc[t1+t0];
  119739. t1+=ido;
  119740. t2+=ido;
  119741. t4+=t3;
  119742. t6+=ido;
  119743. }
  119744. }
  119745. static void dradfg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  119746. float *c2,float *ch,float *ch2,float *wa){
  119747. static float tpi=6.283185307179586f;
  119748. int idij,ipph,i,j,k,l,ic,ik,is;
  119749. int t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  119750. float dc2,ai1,ai2,ar1,ar2,ds2;
  119751. int nbd;
  119752. float dcp,arg,dsp,ar1h,ar2h;
  119753. int idp2,ipp2;
  119754. arg=tpi/(float)ip;
  119755. dcp=cos(arg);
  119756. dsp=sin(arg);
  119757. ipph=(ip+1)>>1;
  119758. ipp2=ip;
  119759. idp2=ido;
  119760. nbd=(ido-1)>>1;
  119761. t0=l1*ido;
  119762. t10=ip*ido;
  119763. if(ido==1)goto L119;
  119764. for(ik=0;ik<idl1;ik++)ch2[ik]=c2[ik];
  119765. t1=0;
  119766. for(j=1;j<ip;j++){
  119767. t1+=t0;
  119768. t2=t1;
  119769. for(k=0;k<l1;k++){
  119770. ch[t2]=c1[t2];
  119771. t2+=ido;
  119772. }
  119773. }
  119774. is=-ido;
  119775. t1=0;
  119776. if(nbd>l1){
  119777. for(j=1;j<ip;j++){
  119778. t1+=t0;
  119779. is+=ido;
  119780. t2= -ido+t1;
  119781. for(k=0;k<l1;k++){
  119782. idij=is-1;
  119783. t2+=ido;
  119784. t3=t2;
  119785. for(i=2;i<ido;i+=2){
  119786. idij+=2;
  119787. t3+=2;
  119788. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  119789. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  119790. }
  119791. }
  119792. }
  119793. }else{
  119794. for(j=1;j<ip;j++){
  119795. is+=ido;
  119796. idij=is-1;
  119797. t1+=t0;
  119798. t2=t1;
  119799. for(i=2;i<ido;i+=2){
  119800. idij+=2;
  119801. t2+=2;
  119802. t3=t2;
  119803. for(k=0;k<l1;k++){
  119804. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  119805. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  119806. t3+=ido;
  119807. }
  119808. }
  119809. }
  119810. }
  119811. t1=0;
  119812. t2=ipp2*t0;
  119813. if(nbd<l1){
  119814. for(j=1;j<ipph;j++){
  119815. t1+=t0;
  119816. t2-=t0;
  119817. t3=t1;
  119818. t4=t2;
  119819. for(i=2;i<ido;i+=2){
  119820. t3+=2;
  119821. t4+=2;
  119822. t5=t3-ido;
  119823. t6=t4-ido;
  119824. for(k=0;k<l1;k++){
  119825. t5+=ido;
  119826. t6+=ido;
  119827. c1[t5-1]=ch[t5-1]+ch[t6-1];
  119828. c1[t6-1]=ch[t5]-ch[t6];
  119829. c1[t5]=ch[t5]+ch[t6];
  119830. c1[t6]=ch[t6-1]-ch[t5-1];
  119831. }
  119832. }
  119833. }
  119834. }else{
  119835. for(j=1;j<ipph;j++){
  119836. t1+=t0;
  119837. t2-=t0;
  119838. t3=t1;
  119839. t4=t2;
  119840. for(k=0;k<l1;k++){
  119841. t5=t3;
  119842. t6=t4;
  119843. for(i=2;i<ido;i+=2){
  119844. t5+=2;
  119845. t6+=2;
  119846. c1[t5-1]=ch[t5-1]+ch[t6-1];
  119847. c1[t6-1]=ch[t5]-ch[t6];
  119848. c1[t5]=ch[t5]+ch[t6];
  119849. c1[t6]=ch[t6-1]-ch[t5-1];
  119850. }
  119851. t3+=ido;
  119852. t4+=ido;
  119853. }
  119854. }
  119855. }
  119856. L119:
  119857. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  119858. t1=0;
  119859. t2=ipp2*idl1;
  119860. for(j=1;j<ipph;j++){
  119861. t1+=t0;
  119862. t2-=t0;
  119863. t3=t1-ido;
  119864. t4=t2-ido;
  119865. for(k=0;k<l1;k++){
  119866. t3+=ido;
  119867. t4+=ido;
  119868. c1[t3]=ch[t3]+ch[t4];
  119869. c1[t4]=ch[t4]-ch[t3];
  119870. }
  119871. }
  119872. ar1=1.f;
  119873. ai1=0.f;
  119874. t1=0;
  119875. t2=ipp2*idl1;
  119876. t3=(ip-1)*idl1;
  119877. for(l=1;l<ipph;l++){
  119878. t1+=idl1;
  119879. t2-=idl1;
  119880. ar1h=dcp*ar1-dsp*ai1;
  119881. ai1=dcp*ai1+dsp*ar1;
  119882. ar1=ar1h;
  119883. t4=t1;
  119884. t5=t2;
  119885. t6=t3;
  119886. t7=idl1;
  119887. for(ik=0;ik<idl1;ik++){
  119888. ch2[t4++]=c2[ik]+ar1*c2[t7++];
  119889. ch2[t5++]=ai1*c2[t6++];
  119890. }
  119891. dc2=ar1;
  119892. ds2=ai1;
  119893. ar2=ar1;
  119894. ai2=ai1;
  119895. t4=idl1;
  119896. t5=(ipp2-1)*idl1;
  119897. for(j=2;j<ipph;j++){
  119898. t4+=idl1;
  119899. t5-=idl1;
  119900. ar2h=dc2*ar2-ds2*ai2;
  119901. ai2=dc2*ai2+ds2*ar2;
  119902. ar2=ar2h;
  119903. t6=t1;
  119904. t7=t2;
  119905. t8=t4;
  119906. t9=t5;
  119907. for(ik=0;ik<idl1;ik++){
  119908. ch2[t6++]+=ar2*c2[t8++];
  119909. ch2[t7++]+=ai2*c2[t9++];
  119910. }
  119911. }
  119912. }
  119913. t1=0;
  119914. for(j=1;j<ipph;j++){
  119915. t1+=idl1;
  119916. t2=t1;
  119917. for(ik=0;ik<idl1;ik++)ch2[ik]+=c2[t2++];
  119918. }
  119919. if(ido<l1)goto L132;
  119920. t1=0;
  119921. t2=0;
  119922. for(k=0;k<l1;k++){
  119923. t3=t1;
  119924. t4=t2;
  119925. for(i=0;i<ido;i++)cc[t4++]=ch[t3++];
  119926. t1+=ido;
  119927. t2+=t10;
  119928. }
  119929. goto L135;
  119930. L132:
  119931. for(i=0;i<ido;i++){
  119932. t1=i;
  119933. t2=i;
  119934. for(k=0;k<l1;k++){
  119935. cc[t2]=ch[t1];
  119936. t1+=ido;
  119937. t2+=t10;
  119938. }
  119939. }
  119940. L135:
  119941. t1=0;
  119942. t2=ido<<1;
  119943. t3=0;
  119944. t4=ipp2*t0;
  119945. for(j=1;j<ipph;j++){
  119946. t1+=t2;
  119947. t3+=t0;
  119948. t4-=t0;
  119949. t5=t1;
  119950. t6=t3;
  119951. t7=t4;
  119952. for(k=0;k<l1;k++){
  119953. cc[t5-1]=ch[t6];
  119954. cc[t5]=ch[t7];
  119955. t5+=t10;
  119956. t6+=ido;
  119957. t7+=ido;
  119958. }
  119959. }
  119960. if(ido==1)return;
  119961. if(nbd<l1)goto L141;
  119962. t1=-ido;
  119963. t3=0;
  119964. t4=0;
  119965. t5=ipp2*t0;
  119966. for(j=1;j<ipph;j++){
  119967. t1+=t2;
  119968. t3+=t2;
  119969. t4+=t0;
  119970. t5-=t0;
  119971. t6=t1;
  119972. t7=t3;
  119973. t8=t4;
  119974. t9=t5;
  119975. for(k=0;k<l1;k++){
  119976. for(i=2;i<ido;i+=2){
  119977. ic=idp2-i;
  119978. cc[i+t7-1]=ch[i+t8-1]+ch[i+t9-1];
  119979. cc[ic+t6-1]=ch[i+t8-1]-ch[i+t9-1];
  119980. cc[i+t7]=ch[i+t8]+ch[i+t9];
  119981. cc[ic+t6]=ch[i+t9]-ch[i+t8];
  119982. }
  119983. t6+=t10;
  119984. t7+=t10;
  119985. t8+=ido;
  119986. t9+=ido;
  119987. }
  119988. }
  119989. return;
  119990. L141:
  119991. t1=-ido;
  119992. t3=0;
  119993. t4=0;
  119994. t5=ipp2*t0;
  119995. for(j=1;j<ipph;j++){
  119996. t1+=t2;
  119997. t3+=t2;
  119998. t4+=t0;
  119999. t5-=t0;
  120000. for(i=2;i<ido;i+=2){
  120001. t6=idp2+t1-i;
  120002. t7=i+t3;
  120003. t8=i+t4;
  120004. t9=i+t5;
  120005. for(k=0;k<l1;k++){
  120006. cc[t7-1]=ch[t8-1]+ch[t9-1];
  120007. cc[t6-1]=ch[t8-1]-ch[t9-1];
  120008. cc[t7]=ch[t8]+ch[t9];
  120009. cc[t6]=ch[t9]-ch[t8];
  120010. t6+=t10;
  120011. t7+=t10;
  120012. t8+=ido;
  120013. t9+=ido;
  120014. }
  120015. }
  120016. }
  120017. }
  120018. static void drftf1(int n,float *c,float *ch,float *wa,int *ifac){
  120019. int i,k1,l1,l2;
  120020. int na,kh,nf;
  120021. int ip,iw,ido,idl1,ix2,ix3;
  120022. nf=ifac[1];
  120023. na=1;
  120024. l2=n;
  120025. iw=n;
  120026. for(k1=0;k1<nf;k1++){
  120027. kh=nf-k1;
  120028. ip=ifac[kh+1];
  120029. l1=l2/ip;
  120030. ido=n/l2;
  120031. idl1=ido*l1;
  120032. iw-=(ip-1)*ido;
  120033. na=1-na;
  120034. if(ip!=4)goto L102;
  120035. ix2=iw+ido;
  120036. ix3=ix2+ido;
  120037. if(na!=0)
  120038. dradf4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  120039. else
  120040. dradf4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  120041. goto L110;
  120042. L102:
  120043. if(ip!=2)goto L104;
  120044. if(na!=0)goto L103;
  120045. dradf2(ido,l1,c,ch,wa+iw-1);
  120046. goto L110;
  120047. L103:
  120048. dradf2(ido,l1,ch,c,wa+iw-1);
  120049. goto L110;
  120050. L104:
  120051. if(ido==1)na=1-na;
  120052. if(na!=0)goto L109;
  120053. dradfg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  120054. na=1;
  120055. goto L110;
  120056. L109:
  120057. dradfg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  120058. na=0;
  120059. L110:
  120060. l2=l1;
  120061. }
  120062. if(na==1)return;
  120063. for(i=0;i<n;i++)c[i]=ch[i];
  120064. }
  120065. static void dradb2(int ido,int l1,float *cc,float *ch,float *wa1){
  120066. int i,k,t0,t1,t2,t3,t4,t5,t6;
  120067. float ti2,tr2;
  120068. t0=l1*ido;
  120069. t1=0;
  120070. t2=0;
  120071. t3=(ido<<1)-1;
  120072. for(k=0;k<l1;k++){
  120073. ch[t1]=cc[t2]+cc[t3+t2];
  120074. ch[t1+t0]=cc[t2]-cc[t3+t2];
  120075. t2=(t1+=ido)<<1;
  120076. }
  120077. if(ido<2)return;
  120078. if(ido==2)goto L105;
  120079. t1=0;
  120080. t2=0;
  120081. for(k=0;k<l1;k++){
  120082. t3=t1;
  120083. t5=(t4=t2)+(ido<<1);
  120084. t6=t0+t1;
  120085. for(i=2;i<ido;i+=2){
  120086. t3+=2;
  120087. t4+=2;
  120088. t5-=2;
  120089. t6+=2;
  120090. ch[t3-1]=cc[t4-1]+cc[t5-1];
  120091. tr2=cc[t4-1]-cc[t5-1];
  120092. ch[t3]=cc[t4]-cc[t5];
  120093. ti2=cc[t4]+cc[t5];
  120094. ch[t6-1]=wa1[i-2]*tr2-wa1[i-1]*ti2;
  120095. ch[t6]=wa1[i-2]*ti2+wa1[i-1]*tr2;
  120096. }
  120097. t2=(t1+=ido)<<1;
  120098. }
  120099. if(ido%2==1)return;
  120100. L105:
  120101. t1=ido-1;
  120102. t2=ido-1;
  120103. for(k=0;k<l1;k++){
  120104. ch[t1]=cc[t2]+cc[t2];
  120105. ch[t1+t0]=-(cc[t2+1]+cc[t2+1]);
  120106. t1+=ido;
  120107. t2+=ido<<1;
  120108. }
  120109. }
  120110. static void dradb3(int ido,int l1,float *cc,float *ch,float *wa1,
  120111. float *wa2){
  120112. static float taur = -.5f;
  120113. static float taui = .8660254037844386f;
  120114. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  120115. float ci2,ci3,di2,di3,cr2,cr3,dr2,dr3,ti2,tr2;
  120116. t0=l1*ido;
  120117. t1=0;
  120118. t2=t0<<1;
  120119. t3=ido<<1;
  120120. t4=ido+(ido<<1);
  120121. t5=0;
  120122. for(k=0;k<l1;k++){
  120123. tr2=cc[t3-1]+cc[t3-1];
  120124. cr2=cc[t5]+(taur*tr2);
  120125. ch[t1]=cc[t5]+tr2;
  120126. ci3=taui*(cc[t3]+cc[t3]);
  120127. ch[t1+t0]=cr2-ci3;
  120128. ch[t1+t2]=cr2+ci3;
  120129. t1+=ido;
  120130. t3+=t4;
  120131. t5+=t4;
  120132. }
  120133. if(ido==1)return;
  120134. t1=0;
  120135. t3=ido<<1;
  120136. for(k=0;k<l1;k++){
  120137. t7=t1+(t1<<1);
  120138. t6=(t5=t7+t3);
  120139. t8=t1;
  120140. t10=(t9=t1+t0)+t0;
  120141. for(i=2;i<ido;i+=2){
  120142. t5+=2;
  120143. t6-=2;
  120144. t7+=2;
  120145. t8+=2;
  120146. t9+=2;
  120147. t10+=2;
  120148. tr2=cc[t5-1]+cc[t6-1];
  120149. cr2=cc[t7-1]+(taur*tr2);
  120150. ch[t8-1]=cc[t7-1]+tr2;
  120151. ti2=cc[t5]-cc[t6];
  120152. ci2=cc[t7]+(taur*ti2);
  120153. ch[t8]=cc[t7]+ti2;
  120154. cr3=taui*(cc[t5-1]-cc[t6-1]);
  120155. ci3=taui*(cc[t5]+cc[t6]);
  120156. dr2=cr2-ci3;
  120157. dr3=cr2+ci3;
  120158. di2=ci2+cr3;
  120159. di3=ci2-cr3;
  120160. ch[t9-1]=wa1[i-2]*dr2-wa1[i-1]*di2;
  120161. ch[t9]=wa1[i-2]*di2+wa1[i-1]*dr2;
  120162. ch[t10-1]=wa2[i-2]*dr3-wa2[i-1]*di3;
  120163. ch[t10]=wa2[i-2]*di3+wa2[i-1]*dr3;
  120164. }
  120165. t1+=ido;
  120166. }
  120167. }
  120168. static void dradb4(int ido,int l1,float *cc,float *ch,float *wa1,
  120169. float *wa2,float *wa3){
  120170. static float sqrt2=1.414213562373095f;
  120171. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8;
  120172. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  120173. t0=l1*ido;
  120174. t1=0;
  120175. t2=ido<<2;
  120176. t3=0;
  120177. t6=ido<<1;
  120178. for(k=0;k<l1;k++){
  120179. t4=t3+t6;
  120180. t5=t1;
  120181. tr3=cc[t4-1]+cc[t4-1];
  120182. tr4=cc[t4]+cc[t4];
  120183. tr1=cc[t3]-cc[(t4+=t6)-1];
  120184. tr2=cc[t3]+cc[t4-1];
  120185. ch[t5]=tr2+tr3;
  120186. ch[t5+=t0]=tr1-tr4;
  120187. ch[t5+=t0]=tr2-tr3;
  120188. ch[t5+=t0]=tr1+tr4;
  120189. t1+=ido;
  120190. t3+=t2;
  120191. }
  120192. if(ido<2)return;
  120193. if(ido==2)goto L105;
  120194. t1=0;
  120195. for(k=0;k<l1;k++){
  120196. t5=(t4=(t3=(t2=t1<<2)+t6))+t6;
  120197. t7=t1;
  120198. for(i=2;i<ido;i+=2){
  120199. t2+=2;
  120200. t3+=2;
  120201. t4-=2;
  120202. t5-=2;
  120203. t7+=2;
  120204. ti1=cc[t2]+cc[t5];
  120205. ti2=cc[t2]-cc[t5];
  120206. ti3=cc[t3]-cc[t4];
  120207. tr4=cc[t3]+cc[t4];
  120208. tr1=cc[t2-1]-cc[t5-1];
  120209. tr2=cc[t2-1]+cc[t5-1];
  120210. ti4=cc[t3-1]-cc[t4-1];
  120211. tr3=cc[t3-1]+cc[t4-1];
  120212. ch[t7-1]=tr2+tr3;
  120213. cr3=tr2-tr3;
  120214. ch[t7]=ti2+ti3;
  120215. ci3=ti2-ti3;
  120216. cr2=tr1-tr4;
  120217. cr4=tr1+tr4;
  120218. ci2=ti1+ti4;
  120219. ci4=ti1-ti4;
  120220. ch[(t8=t7+t0)-1]=wa1[i-2]*cr2-wa1[i-1]*ci2;
  120221. ch[t8]=wa1[i-2]*ci2+wa1[i-1]*cr2;
  120222. ch[(t8+=t0)-1]=wa2[i-2]*cr3-wa2[i-1]*ci3;
  120223. ch[t8]=wa2[i-2]*ci3+wa2[i-1]*cr3;
  120224. ch[(t8+=t0)-1]=wa3[i-2]*cr4-wa3[i-1]*ci4;
  120225. ch[t8]=wa3[i-2]*ci4+wa3[i-1]*cr4;
  120226. }
  120227. t1+=ido;
  120228. }
  120229. if(ido%2 == 1)return;
  120230. L105:
  120231. t1=ido;
  120232. t2=ido<<2;
  120233. t3=ido-1;
  120234. t4=ido+(ido<<1);
  120235. for(k=0;k<l1;k++){
  120236. t5=t3;
  120237. ti1=cc[t1]+cc[t4];
  120238. ti2=cc[t4]-cc[t1];
  120239. tr1=cc[t1-1]-cc[t4-1];
  120240. tr2=cc[t1-1]+cc[t4-1];
  120241. ch[t5]=tr2+tr2;
  120242. ch[t5+=t0]=sqrt2*(tr1-ti1);
  120243. ch[t5+=t0]=ti2+ti2;
  120244. ch[t5+=t0]=-sqrt2*(tr1+ti1);
  120245. t3+=ido;
  120246. t1+=t2;
  120247. t4+=t2;
  120248. }
  120249. }
  120250. static void dradbg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  120251. float *c2,float *ch,float *ch2,float *wa){
  120252. static float tpi=6.283185307179586f;
  120253. int idij,ipph,i,j,k,l,ik,is,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,
  120254. t11,t12;
  120255. float dc2,ai1,ai2,ar1,ar2,ds2;
  120256. int nbd;
  120257. float dcp,arg,dsp,ar1h,ar2h;
  120258. int ipp2;
  120259. t10=ip*ido;
  120260. t0=l1*ido;
  120261. arg=tpi/(float)ip;
  120262. dcp=cos(arg);
  120263. dsp=sin(arg);
  120264. nbd=(ido-1)>>1;
  120265. ipp2=ip;
  120266. ipph=(ip+1)>>1;
  120267. if(ido<l1)goto L103;
  120268. t1=0;
  120269. t2=0;
  120270. for(k=0;k<l1;k++){
  120271. t3=t1;
  120272. t4=t2;
  120273. for(i=0;i<ido;i++){
  120274. ch[t3]=cc[t4];
  120275. t3++;
  120276. t4++;
  120277. }
  120278. t1+=ido;
  120279. t2+=t10;
  120280. }
  120281. goto L106;
  120282. L103:
  120283. t1=0;
  120284. for(i=0;i<ido;i++){
  120285. t2=t1;
  120286. t3=t1;
  120287. for(k=0;k<l1;k++){
  120288. ch[t2]=cc[t3];
  120289. t2+=ido;
  120290. t3+=t10;
  120291. }
  120292. t1++;
  120293. }
  120294. L106:
  120295. t1=0;
  120296. t2=ipp2*t0;
  120297. t7=(t5=ido<<1);
  120298. for(j=1;j<ipph;j++){
  120299. t1+=t0;
  120300. t2-=t0;
  120301. t3=t1;
  120302. t4=t2;
  120303. t6=t5;
  120304. for(k=0;k<l1;k++){
  120305. ch[t3]=cc[t6-1]+cc[t6-1];
  120306. ch[t4]=cc[t6]+cc[t6];
  120307. t3+=ido;
  120308. t4+=ido;
  120309. t6+=t10;
  120310. }
  120311. t5+=t7;
  120312. }
  120313. if (ido == 1)goto L116;
  120314. if(nbd<l1)goto L112;
  120315. t1=0;
  120316. t2=ipp2*t0;
  120317. t7=0;
  120318. for(j=1;j<ipph;j++){
  120319. t1+=t0;
  120320. t2-=t0;
  120321. t3=t1;
  120322. t4=t2;
  120323. t7+=(ido<<1);
  120324. t8=t7;
  120325. for(k=0;k<l1;k++){
  120326. t5=t3;
  120327. t6=t4;
  120328. t9=t8;
  120329. t11=t8;
  120330. for(i=2;i<ido;i+=2){
  120331. t5+=2;
  120332. t6+=2;
  120333. t9+=2;
  120334. t11-=2;
  120335. ch[t5-1]=cc[t9-1]+cc[t11-1];
  120336. ch[t6-1]=cc[t9-1]-cc[t11-1];
  120337. ch[t5]=cc[t9]-cc[t11];
  120338. ch[t6]=cc[t9]+cc[t11];
  120339. }
  120340. t3+=ido;
  120341. t4+=ido;
  120342. t8+=t10;
  120343. }
  120344. }
  120345. goto L116;
  120346. L112:
  120347. t1=0;
  120348. t2=ipp2*t0;
  120349. t7=0;
  120350. for(j=1;j<ipph;j++){
  120351. t1+=t0;
  120352. t2-=t0;
  120353. t3=t1;
  120354. t4=t2;
  120355. t7+=(ido<<1);
  120356. t8=t7;
  120357. t9=t7;
  120358. for(i=2;i<ido;i+=2){
  120359. t3+=2;
  120360. t4+=2;
  120361. t8+=2;
  120362. t9-=2;
  120363. t5=t3;
  120364. t6=t4;
  120365. t11=t8;
  120366. t12=t9;
  120367. for(k=0;k<l1;k++){
  120368. ch[t5-1]=cc[t11-1]+cc[t12-1];
  120369. ch[t6-1]=cc[t11-1]-cc[t12-1];
  120370. ch[t5]=cc[t11]-cc[t12];
  120371. ch[t6]=cc[t11]+cc[t12];
  120372. t5+=ido;
  120373. t6+=ido;
  120374. t11+=t10;
  120375. t12+=t10;
  120376. }
  120377. }
  120378. }
  120379. L116:
  120380. ar1=1.f;
  120381. ai1=0.f;
  120382. t1=0;
  120383. t9=(t2=ipp2*idl1);
  120384. t3=(ip-1)*idl1;
  120385. for(l=1;l<ipph;l++){
  120386. t1+=idl1;
  120387. t2-=idl1;
  120388. ar1h=dcp*ar1-dsp*ai1;
  120389. ai1=dcp*ai1+dsp*ar1;
  120390. ar1=ar1h;
  120391. t4=t1;
  120392. t5=t2;
  120393. t6=0;
  120394. t7=idl1;
  120395. t8=t3;
  120396. for(ik=0;ik<idl1;ik++){
  120397. c2[t4++]=ch2[t6++]+ar1*ch2[t7++];
  120398. c2[t5++]=ai1*ch2[t8++];
  120399. }
  120400. dc2=ar1;
  120401. ds2=ai1;
  120402. ar2=ar1;
  120403. ai2=ai1;
  120404. t6=idl1;
  120405. t7=t9-idl1;
  120406. for(j=2;j<ipph;j++){
  120407. t6+=idl1;
  120408. t7-=idl1;
  120409. ar2h=dc2*ar2-ds2*ai2;
  120410. ai2=dc2*ai2+ds2*ar2;
  120411. ar2=ar2h;
  120412. t4=t1;
  120413. t5=t2;
  120414. t11=t6;
  120415. t12=t7;
  120416. for(ik=0;ik<idl1;ik++){
  120417. c2[t4++]+=ar2*ch2[t11++];
  120418. c2[t5++]+=ai2*ch2[t12++];
  120419. }
  120420. }
  120421. }
  120422. t1=0;
  120423. for(j=1;j<ipph;j++){
  120424. t1+=idl1;
  120425. t2=t1;
  120426. for(ik=0;ik<idl1;ik++)ch2[ik]+=ch2[t2++];
  120427. }
  120428. t1=0;
  120429. t2=ipp2*t0;
  120430. for(j=1;j<ipph;j++){
  120431. t1+=t0;
  120432. t2-=t0;
  120433. t3=t1;
  120434. t4=t2;
  120435. for(k=0;k<l1;k++){
  120436. ch[t3]=c1[t3]-c1[t4];
  120437. ch[t4]=c1[t3]+c1[t4];
  120438. t3+=ido;
  120439. t4+=ido;
  120440. }
  120441. }
  120442. if(ido==1)goto L132;
  120443. if(nbd<l1)goto L128;
  120444. t1=0;
  120445. t2=ipp2*t0;
  120446. for(j=1;j<ipph;j++){
  120447. t1+=t0;
  120448. t2-=t0;
  120449. t3=t1;
  120450. t4=t2;
  120451. for(k=0;k<l1;k++){
  120452. t5=t3;
  120453. t6=t4;
  120454. for(i=2;i<ido;i+=2){
  120455. t5+=2;
  120456. t6+=2;
  120457. ch[t5-1]=c1[t5-1]-c1[t6];
  120458. ch[t6-1]=c1[t5-1]+c1[t6];
  120459. ch[t5]=c1[t5]+c1[t6-1];
  120460. ch[t6]=c1[t5]-c1[t6-1];
  120461. }
  120462. t3+=ido;
  120463. t4+=ido;
  120464. }
  120465. }
  120466. goto L132;
  120467. L128:
  120468. t1=0;
  120469. t2=ipp2*t0;
  120470. for(j=1;j<ipph;j++){
  120471. t1+=t0;
  120472. t2-=t0;
  120473. t3=t1;
  120474. t4=t2;
  120475. for(i=2;i<ido;i+=2){
  120476. t3+=2;
  120477. t4+=2;
  120478. t5=t3;
  120479. t6=t4;
  120480. for(k=0;k<l1;k++){
  120481. ch[t5-1]=c1[t5-1]-c1[t6];
  120482. ch[t6-1]=c1[t5-1]+c1[t6];
  120483. ch[t5]=c1[t5]+c1[t6-1];
  120484. ch[t6]=c1[t5]-c1[t6-1];
  120485. t5+=ido;
  120486. t6+=ido;
  120487. }
  120488. }
  120489. }
  120490. L132:
  120491. if(ido==1)return;
  120492. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  120493. t1=0;
  120494. for(j=1;j<ip;j++){
  120495. t2=(t1+=t0);
  120496. for(k=0;k<l1;k++){
  120497. c1[t2]=ch[t2];
  120498. t2+=ido;
  120499. }
  120500. }
  120501. if(nbd>l1)goto L139;
  120502. is= -ido-1;
  120503. t1=0;
  120504. for(j=1;j<ip;j++){
  120505. is+=ido;
  120506. t1+=t0;
  120507. idij=is;
  120508. t2=t1;
  120509. for(i=2;i<ido;i+=2){
  120510. t2+=2;
  120511. idij+=2;
  120512. t3=t2;
  120513. for(k=0;k<l1;k++){
  120514. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  120515. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  120516. t3+=ido;
  120517. }
  120518. }
  120519. }
  120520. return;
  120521. L139:
  120522. is= -ido-1;
  120523. t1=0;
  120524. for(j=1;j<ip;j++){
  120525. is+=ido;
  120526. t1+=t0;
  120527. t2=t1;
  120528. for(k=0;k<l1;k++){
  120529. idij=is;
  120530. t3=t2;
  120531. for(i=2;i<ido;i+=2){
  120532. idij+=2;
  120533. t3+=2;
  120534. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  120535. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  120536. }
  120537. t2+=ido;
  120538. }
  120539. }
  120540. }
  120541. static void drftb1(int n, float *c, float *ch, float *wa, int *ifac){
  120542. int i,k1,l1,l2;
  120543. int na;
  120544. int nf,ip,iw,ix2,ix3,ido,idl1;
  120545. nf=ifac[1];
  120546. na=0;
  120547. l1=1;
  120548. iw=1;
  120549. for(k1=0;k1<nf;k1++){
  120550. ip=ifac[k1 + 2];
  120551. l2=ip*l1;
  120552. ido=n/l2;
  120553. idl1=ido*l1;
  120554. if(ip!=4)goto L103;
  120555. ix2=iw+ido;
  120556. ix3=ix2+ido;
  120557. if(na!=0)
  120558. dradb4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  120559. else
  120560. dradb4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  120561. na=1-na;
  120562. goto L115;
  120563. L103:
  120564. if(ip!=2)goto L106;
  120565. if(na!=0)
  120566. dradb2(ido,l1,ch,c,wa+iw-1);
  120567. else
  120568. dradb2(ido,l1,c,ch,wa+iw-1);
  120569. na=1-na;
  120570. goto L115;
  120571. L106:
  120572. if(ip!=3)goto L109;
  120573. ix2=iw+ido;
  120574. if(na!=0)
  120575. dradb3(ido,l1,ch,c,wa+iw-1,wa+ix2-1);
  120576. else
  120577. dradb3(ido,l1,c,ch,wa+iw-1,wa+ix2-1);
  120578. na=1-na;
  120579. goto L115;
  120580. L109:
  120581. /* The radix five case can be translated later..... */
  120582. /* if(ip!=5)goto L112;
  120583. ix2=iw+ido;
  120584. ix3=ix2+ido;
  120585. ix4=ix3+ido;
  120586. if(na!=0)
  120587. dradb5(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  120588. else
  120589. dradb5(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  120590. na=1-na;
  120591. goto L115;
  120592. L112:*/
  120593. if(na!=0)
  120594. dradbg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  120595. else
  120596. dradbg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  120597. if(ido==1)na=1-na;
  120598. L115:
  120599. l1=l2;
  120600. iw+=(ip-1)*ido;
  120601. }
  120602. if(na==0)return;
  120603. for(i=0;i<n;i++)c[i]=ch[i];
  120604. }
  120605. void drft_forward(drft_lookup *l,float *data){
  120606. if(l->n==1)return;
  120607. drftf1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  120608. }
  120609. void drft_backward(drft_lookup *l,float *data){
  120610. if (l->n==1)return;
  120611. drftb1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  120612. }
  120613. void drft_init(drft_lookup *l,int n){
  120614. l->n=n;
  120615. l->trigcache=(float*)_ogg_calloc(3*n,sizeof(*l->trigcache));
  120616. l->splitcache=(int*)_ogg_calloc(32,sizeof(*l->splitcache));
  120617. fdrffti(n, l->trigcache, l->splitcache);
  120618. }
  120619. void drft_clear(drft_lookup *l){
  120620. if(l){
  120621. if(l->trigcache)_ogg_free(l->trigcache);
  120622. if(l->splitcache)_ogg_free(l->splitcache);
  120623. memset(l,0,sizeof(*l));
  120624. }
  120625. }
  120626. #endif
  120627. /*** End of inlined file: smallft.c ***/
  120628. /*** Start of inlined file: synthesis.c ***/
  120629. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  120630. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  120631. // tasks..
  120632. #if JUCE_MSVC
  120633. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  120634. #endif
  120635. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  120636. #if JUCE_USE_OGGVORBIS
  120637. #include <stdio.h>
  120638. int vorbis_synthesis(vorbis_block *vb,ogg_packet *op){
  120639. vorbis_dsp_state *vd=vb->vd;
  120640. private_state *b=(private_state*)vd->backend_state;
  120641. vorbis_info *vi=vd->vi;
  120642. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  120643. oggpack_buffer *opb=&vb->opb;
  120644. int type,mode,i;
  120645. /* first things first. Make sure decode is ready */
  120646. _vorbis_block_ripcord(vb);
  120647. oggpack_readinit(opb,op->packet,op->bytes);
  120648. /* Check the packet type */
  120649. if(oggpack_read(opb,1)!=0){
  120650. /* Oops. This is not an audio data packet */
  120651. return(OV_ENOTAUDIO);
  120652. }
  120653. /* read our mode and pre/post windowsize */
  120654. mode=oggpack_read(opb,b->modebits);
  120655. if(mode==-1)return(OV_EBADPACKET);
  120656. vb->mode=mode;
  120657. vb->W=ci->mode_param[mode]->blockflag;
  120658. if(vb->W){
  120659. /* this doesn;t get mapped through mode selection as it's used
  120660. only for window selection */
  120661. vb->lW=oggpack_read(opb,1);
  120662. vb->nW=oggpack_read(opb,1);
  120663. if(vb->nW==-1) return(OV_EBADPACKET);
  120664. }else{
  120665. vb->lW=0;
  120666. vb->nW=0;
  120667. }
  120668. /* more setup */
  120669. vb->granulepos=op->granulepos;
  120670. vb->sequence=op->packetno;
  120671. vb->eofflag=op->e_o_s;
  120672. /* alloc pcm passback storage */
  120673. vb->pcmend=ci->blocksizes[vb->W];
  120674. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  120675. for(i=0;i<vi->channels;i++)
  120676. vb->pcm[i]=(float*)_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  120677. /* unpack_header enforces range checking */
  120678. type=ci->map_type[ci->mode_param[mode]->mapping];
  120679. return(_mapping_P[type]->inverse(vb,ci->map_param[ci->mode_param[mode]->
  120680. mapping]));
  120681. }
  120682. /* used to track pcm position without actually performing decode.
  120683. Useful for sequential 'fast forward' */
  120684. int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op){
  120685. vorbis_dsp_state *vd=vb->vd;
  120686. private_state *b=(private_state*)vd->backend_state;
  120687. vorbis_info *vi=vd->vi;
  120688. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120689. oggpack_buffer *opb=&vb->opb;
  120690. int mode;
  120691. /* first things first. Make sure decode is ready */
  120692. _vorbis_block_ripcord(vb);
  120693. oggpack_readinit(opb,op->packet,op->bytes);
  120694. /* Check the packet type */
  120695. if(oggpack_read(opb,1)!=0){
  120696. /* Oops. This is not an audio data packet */
  120697. return(OV_ENOTAUDIO);
  120698. }
  120699. /* read our mode and pre/post windowsize */
  120700. mode=oggpack_read(opb,b->modebits);
  120701. if(mode==-1)return(OV_EBADPACKET);
  120702. vb->mode=mode;
  120703. vb->W=ci->mode_param[mode]->blockflag;
  120704. if(vb->W){
  120705. vb->lW=oggpack_read(opb,1);
  120706. vb->nW=oggpack_read(opb,1);
  120707. if(vb->nW==-1) return(OV_EBADPACKET);
  120708. }else{
  120709. vb->lW=0;
  120710. vb->nW=0;
  120711. }
  120712. /* more setup */
  120713. vb->granulepos=op->granulepos;
  120714. vb->sequence=op->packetno;
  120715. vb->eofflag=op->e_o_s;
  120716. /* no pcm */
  120717. vb->pcmend=0;
  120718. vb->pcm=NULL;
  120719. return(0);
  120720. }
  120721. long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op){
  120722. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120723. oggpack_buffer opb;
  120724. int mode;
  120725. oggpack_readinit(&opb,op->packet,op->bytes);
  120726. /* Check the packet type */
  120727. if(oggpack_read(&opb,1)!=0){
  120728. /* Oops. This is not an audio data packet */
  120729. return(OV_ENOTAUDIO);
  120730. }
  120731. {
  120732. int modebits=0;
  120733. int v=ci->modes;
  120734. while(v>1){
  120735. modebits++;
  120736. v>>=1;
  120737. }
  120738. /* read our mode and pre/post windowsize */
  120739. mode=oggpack_read(&opb,modebits);
  120740. }
  120741. if(mode==-1)return(OV_EBADPACKET);
  120742. return(ci->blocksizes[ci->mode_param[mode]->blockflag]);
  120743. }
  120744. int vorbis_synthesis_halfrate(vorbis_info *vi,int flag){
  120745. /* set / clear half-sample-rate mode */
  120746. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120747. /* right now, our MDCT can't handle < 64 sample windows. */
  120748. if(ci->blocksizes[0]<=64 && flag)return -1;
  120749. ci->halfrate_flag=(flag?1:0);
  120750. return 0;
  120751. }
  120752. int vorbis_synthesis_halfrate_p(vorbis_info *vi){
  120753. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120754. return ci->halfrate_flag;
  120755. }
  120756. #endif
  120757. /*** End of inlined file: synthesis.c ***/
  120758. /*** Start of inlined file: vorbisenc.c ***/
  120759. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  120760. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  120761. // tasks..
  120762. #if JUCE_MSVC
  120763. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  120764. #endif
  120765. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  120766. #if JUCE_USE_OGGVORBIS
  120767. #include <stdlib.h>
  120768. #include <string.h>
  120769. #include <math.h>
  120770. /* careful with this; it's using static array sizing to make managing
  120771. all the modes a little less annoying. If we use a residue backend
  120772. with > 12 partition types, or a different division of iteration,
  120773. this needs to be updated. */
  120774. typedef struct {
  120775. static_codebook *books[12][3];
  120776. } static_bookblock;
  120777. typedef struct {
  120778. int res_type;
  120779. int limit_type; /* 0 lowpass limited, 1 point stereo limited */
  120780. vorbis_info_residue0 *res;
  120781. static_codebook *book_aux;
  120782. static_codebook *book_aux_managed;
  120783. static_bookblock *books_base;
  120784. static_bookblock *books_base_managed;
  120785. } vorbis_residue_template;
  120786. typedef struct {
  120787. vorbis_info_mapping0 *map;
  120788. vorbis_residue_template *res;
  120789. } vorbis_mapping_template;
  120790. typedef struct vp_adjblock{
  120791. int block[P_BANDS];
  120792. } vp_adjblock;
  120793. typedef struct {
  120794. int data[NOISE_COMPAND_LEVELS];
  120795. } compandblock;
  120796. /* high level configuration information for setting things up
  120797. step-by-step with the detailed vorbis_encode_ctl interface.
  120798. There's a fair amount of redundancy such that interactive setup
  120799. does not directly deal with any vorbis_info or codec_setup_info
  120800. initialization; it's all stored (until full init) in this highlevel
  120801. setup, then flushed out to the real codec setup structs later. */
  120802. typedef struct {
  120803. int att[P_NOISECURVES];
  120804. float boost;
  120805. float decay;
  120806. } att3;
  120807. typedef struct { int data[P_NOISECURVES]; } adj3;
  120808. typedef struct {
  120809. int pre[PACKETBLOBS];
  120810. int post[PACKETBLOBS];
  120811. float kHz[PACKETBLOBS];
  120812. float lowpasskHz[PACKETBLOBS];
  120813. } adj_stereo;
  120814. typedef struct {
  120815. int lo;
  120816. int hi;
  120817. int fixed;
  120818. } noiseguard;
  120819. typedef struct {
  120820. int data[P_NOISECURVES][17];
  120821. } noise3;
  120822. typedef struct {
  120823. int mappings;
  120824. double *rate_mapping;
  120825. double *quality_mapping;
  120826. int coupling_restriction;
  120827. long samplerate_min_restriction;
  120828. long samplerate_max_restriction;
  120829. int *blocksize_short;
  120830. int *blocksize_long;
  120831. att3 *psy_tone_masteratt;
  120832. int *psy_tone_0dB;
  120833. int *psy_tone_dBsuppress;
  120834. vp_adjblock *psy_tone_adj_impulse;
  120835. vp_adjblock *psy_tone_adj_long;
  120836. vp_adjblock *psy_tone_adj_other;
  120837. noiseguard *psy_noiseguards;
  120838. noise3 *psy_noise_bias_impulse;
  120839. noise3 *psy_noise_bias_padding;
  120840. noise3 *psy_noise_bias_trans;
  120841. noise3 *psy_noise_bias_long;
  120842. int *psy_noise_dBsuppress;
  120843. compandblock *psy_noise_compand;
  120844. double *psy_noise_compand_short_mapping;
  120845. double *psy_noise_compand_long_mapping;
  120846. int *psy_noise_normal_start[2];
  120847. int *psy_noise_normal_partition[2];
  120848. double *psy_noise_normal_thresh;
  120849. int *psy_ath_float;
  120850. int *psy_ath_abs;
  120851. double *psy_lowpass;
  120852. vorbis_info_psy_global *global_params;
  120853. double *global_mapping;
  120854. adj_stereo *stereo_modes;
  120855. static_codebook ***floor_books;
  120856. vorbis_info_floor1 *floor_params;
  120857. int *floor_short_mapping;
  120858. int *floor_long_mapping;
  120859. vorbis_mapping_template *maps;
  120860. } ve_setup_data_template;
  120861. /* a few static coder conventions */
  120862. static vorbis_info_mode _mode_template[2]={
  120863. {0,0,0,0},
  120864. {1,0,0,1}
  120865. };
  120866. static vorbis_info_mapping0 _map_nominal[2]={
  120867. {1, {0,0}, {0}, {0}, 1,{0},{1}},
  120868. {1, {0,0}, {1}, {1}, 1,{0},{1}}
  120869. };
  120870. /*** Start of inlined file: setup_44.h ***/
  120871. /*** Start of inlined file: floor_all.h ***/
  120872. /*** Start of inlined file: floor_books.h ***/
  120873. static long _huff_lengthlist_line_256x7_0sub1[] = {
  120874. 0, 2, 3, 3, 3, 3, 4, 3, 4,
  120875. };
  120876. static static_codebook _huff_book_line_256x7_0sub1 = {
  120877. 1, 9,
  120878. _huff_lengthlist_line_256x7_0sub1,
  120879. 0, 0, 0, 0, 0,
  120880. NULL,
  120881. NULL,
  120882. NULL,
  120883. NULL,
  120884. 0
  120885. };
  120886. static long _huff_lengthlist_line_256x7_0sub2[] = {
  120887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 4, 3, 5, 3,
  120888. 6, 3, 6, 4, 6, 4, 7, 5, 7,
  120889. };
  120890. static static_codebook _huff_book_line_256x7_0sub2 = {
  120891. 1, 25,
  120892. _huff_lengthlist_line_256x7_0sub2,
  120893. 0, 0, 0, 0, 0,
  120894. NULL,
  120895. NULL,
  120896. NULL,
  120897. NULL,
  120898. 0
  120899. };
  120900. static long _huff_lengthlist_line_256x7_0sub3[] = {
  120901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 2, 5, 3, 5, 3,
  120903. 6, 3, 6, 4, 7, 6, 7, 8, 7, 9, 8, 9, 9, 9,10, 9,
  120904. 11,13,11,13,10,10,13,13,13,13,13,13,12,12,12,12,
  120905. };
  120906. static static_codebook _huff_book_line_256x7_0sub3 = {
  120907. 1, 64,
  120908. _huff_lengthlist_line_256x7_0sub3,
  120909. 0, 0, 0, 0, 0,
  120910. NULL,
  120911. NULL,
  120912. NULL,
  120913. NULL,
  120914. 0
  120915. };
  120916. static long _huff_lengthlist_line_256x7_1sub1[] = {
  120917. 0, 3, 3, 3, 3, 2, 4, 3, 4,
  120918. };
  120919. static static_codebook _huff_book_line_256x7_1sub1 = {
  120920. 1, 9,
  120921. _huff_lengthlist_line_256x7_1sub1,
  120922. 0, 0, 0, 0, 0,
  120923. NULL,
  120924. NULL,
  120925. NULL,
  120926. NULL,
  120927. 0
  120928. };
  120929. static long _huff_lengthlist_line_256x7_1sub2[] = {
  120930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 3, 4, 3, 4, 4,
  120931. 5, 4, 6, 5, 6, 7, 6, 8, 8,
  120932. };
  120933. static static_codebook _huff_book_line_256x7_1sub2 = {
  120934. 1, 25,
  120935. _huff_lengthlist_line_256x7_1sub2,
  120936. 0, 0, 0, 0, 0,
  120937. NULL,
  120938. NULL,
  120939. NULL,
  120940. NULL,
  120941. 0
  120942. };
  120943. static long _huff_lengthlist_line_256x7_1sub3[] = {
  120944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 4, 3, 6, 3, 7,
  120946. 3, 8, 5, 8, 6, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  120947. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7,
  120948. };
  120949. static static_codebook _huff_book_line_256x7_1sub3 = {
  120950. 1, 64,
  120951. _huff_lengthlist_line_256x7_1sub3,
  120952. 0, 0, 0, 0, 0,
  120953. NULL,
  120954. NULL,
  120955. NULL,
  120956. NULL,
  120957. 0
  120958. };
  120959. static long _huff_lengthlist_line_256x7_class0[] = {
  120960. 7, 5, 5, 9, 9, 6, 6, 9,12, 8, 7, 8,11, 8, 9,15,
  120961. 6, 3, 3, 7, 7, 4, 3, 6, 9, 6, 5, 6, 8, 6, 8,15,
  120962. 8, 5, 5, 9, 8, 5, 4, 6,10, 7, 5, 5,11, 8, 7,15,
  120963. 14,15,13,13,13,13, 8,11,15,10, 7, 6,11, 9,10,15,
  120964. };
  120965. static static_codebook _huff_book_line_256x7_class0 = {
  120966. 1, 64,
  120967. _huff_lengthlist_line_256x7_class0,
  120968. 0, 0, 0, 0, 0,
  120969. NULL,
  120970. NULL,
  120971. NULL,
  120972. NULL,
  120973. 0
  120974. };
  120975. static long _huff_lengthlist_line_256x7_class1[] = {
  120976. 5, 6, 8,15, 6, 9,10,15,10,11,12,15,15,15,15,15,
  120977. 4, 6, 7,15, 6, 7, 8,15, 9, 8, 9,15,15,15,15,15,
  120978. 6, 8, 9,15, 7, 7, 8,15,10, 9,10,15,15,15,15,15,
  120979. 15,13,15,15,15,10,11,15,15,13,13,15,15,15,15,15,
  120980. 4, 6, 7,15, 6, 8, 9,15,10,10,12,15,15,15,15,15,
  120981. 2, 5, 6,15, 5, 6, 7,15, 8, 6, 7,15,15,15,15,15,
  120982. 5, 6, 8,15, 5, 6, 7,15, 9, 6, 7,15,15,15,15,15,
  120983. 14,12,13,15,12,10,11,15,15,15,15,15,15,15,15,15,
  120984. 7, 8, 9,15, 9,10,10,15,15,14,14,15,15,15,15,15,
  120985. 5, 6, 7,15, 7, 8, 9,15,12, 9,10,15,15,15,15,15,
  120986. 7, 7, 9,15, 7, 7, 8,15,12, 8, 9,15,15,15,15,15,
  120987. 13,13,14,15,12,11,12,15,15,15,15,15,15,15,15,15,
  120988. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  120989. 13,13,13,15,15,15,15,15,15,15,15,15,15,15,15,15,
  120990. 15,12,13,15,15,12,13,15,15,14,15,15,15,15,15,15,
  120991. 15,15,15,15,15,15,13,15,15,15,15,15,15,15,15,15,
  120992. };
  120993. static static_codebook _huff_book_line_256x7_class1 = {
  120994. 1, 256,
  120995. _huff_lengthlist_line_256x7_class1,
  120996. 0, 0, 0, 0, 0,
  120997. NULL,
  120998. NULL,
  120999. NULL,
  121000. NULL,
  121001. 0
  121002. };
  121003. static long _huff_lengthlist_line_512x17_0sub0[] = {
  121004. 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  121005. 5, 6, 5, 6, 6, 6, 6, 5, 6, 6, 7, 6, 7, 6, 7, 6,
  121006. 7, 6, 8, 7, 8, 7, 8, 7, 8, 7, 8, 7, 9, 7, 9, 7,
  121007. 9, 7, 9, 8, 9, 8,10, 8,10, 8,10, 7,10, 6,10, 8,
  121008. 10, 8,11, 7,10, 7,11, 8,11,11,12,12,11,11,12,11,
  121009. 13,11,13,11,13,12,15,12,13,13,14,14,14,14,14,15,
  121010. 15,15,16,14,17,19,19,18,18,18,18,18,18,18,18,18,
  121011. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  121012. };
  121013. static static_codebook _huff_book_line_512x17_0sub0 = {
  121014. 1, 128,
  121015. _huff_lengthlist_line_512x17_0sub0,
  121016. 0, 0, 0, 0, 0,
  121017. NULL,
  121018. NULL,
  121019. NULL,
  121020. NULL,
  121021. 0
  121022. };
  121023. static long _huff_lengthlist_line_512x17_1sub0[] = {
  121024. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  121025. 6, 5, 6, 6, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 8, 7,
  121026. };
  121027. static static_codebook _huff_book_line_512x17_1sub0 = {
  121028. 1, 32,
  121029. _huff_lengthlist_line_512x17_1sub0,
  121030. 0, 0, 0, 0, 0,
  121031. NULL,
  121032. NULL,
  121033. NULL,
  121034. NULL,
  121035. 0
  121036. };
  121037. static long _huff_lengthlist_line_512x17_1sub1[] = {
  121038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121040. 4, 3, 5, 3, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 6, 5,
  121041. 6, 5, 7, 5, 8, 6, 8, 6, 8, 6, 8, 6, 8, 7, 9, 7,
  121042. 9, 7,11, 9,11,11,12,11,14,12,14,16,14,16,13,16,
  121043. 14,16,12,15,13,16,14,16,13,14,12,15,13,15,13,13,
  121044. 13,15,12,14,14,15,13,15,12,15,15,15,15,15,15,15,
  121045. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  121046. };
  121047. static static_codebook _huff_book_line_512x17_1sub1 = {
  121048. 1, 128,
  121049. _huff_lengthlist_line_512x17_1sub1,
  121050. 0, 0, 0, 0, 0,
  121051. NULL,
  121052. NULL,
  121053. NULL,
  121054. NULL,
  121055. 0
  121056. };
  121057. static long _huff_lengthlist_line_512x17_2sub1[] = {
  121058. 0, 4, 5, 4, 4, 4, 5, 4, 4, 4, 5, 4, 5, 4, 5, 3,
  121059. 5, 3,
  121060. };
  121061. static static_codebook _huff_book_line_512x17_2sub1 = {
  121062. 1, 18,
  121063. _huff_lengthlist_line_512x17_2sub1,
  121064. 0, 0, 0, 0, 0,
  121065. NULL,
  121066. NULL,
  121067. NULL,
  121068. NULL,
  121069. 0
  121070. };
  121071. static long _huff_lengthlist_line_512x17_2sub2[] = {
  121072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121073. 0, 0, 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 6, 4, 6, 5,
  121074. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 7, 8, 7, 9, 7,
  121075. 9, 8,
  121076. };
  121077. static static_codebook _huff_book_line_512x17_2sub2 = {
  121078. 1, 50,
  121079. _huff_lengthlist_line_512x17_2sub2,
  121080. 0, 0, 0, 0, 0,
  121081. NULL,
  121082. NULL,
  121083. NULL,
  121084. NULL,
  121085. 0
  121086. };
  121087. static long _huff_lengthlist_line_512x17_2sub3[] = {
  121088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121091. 0, 0, 3, 3, 3, 3, 4, 3, 4, 4, 5, 5, 6, 6, 7, 7,
  121092. 7, 8, 8,11, 8, 9, 9, 9,10,11,11,11, 9,10,10,11,
  121093. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121094. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121095. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121096. };
  121097. static static_codebook _huff_book_line_512x17_2sub3 = {
  121098. 1, 128,
  121099. _huff_lengthlist_line_512x17_2sub3,
  121100. 0, 0, 0, 0, 0,
  121101. NULL,
  121102. NULL,
  121103. NULL,
  121104. NULL,
  121105. 0
  121106. };
  121107. static long _huff_lengthlist_line_512x17_3sub1[] = {
  121108. 0, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, 4, 4, 5, 4, 5,
  121109. 5, 5,
  121110. };
  121111. static static_codebook _huff_book_line_512x17_3sub1 = {
  121112. 1, 18,
  121113. _huff_lengthlist_line_512x17_3sub1,
  121114. 0, 0, 0, 0, 0,
  121115. NULL,
  121116. NULL,
  121117. NULL,
  121118. NULL,
  121119. 0
  121120. };
  121121. static long _huff_lengthlist_line_512x17_3sub2[] = {
  121122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121123. 0, 0, 2, 3, 3, 4, 3, 5, 4, 6, 4, 6, 5, 7, 6, 7,
  121124. 6, 8, 6, 8, 7, 9, 8,10, 8,12, 9,13,10,15,10,15,
  121125. 11,14,
  121126. };
  121127. static static_codebook _huff_book_line_512x17_3sub2 = {
  121128. 1, 50,
  121129. _huff_lengthlist_line_512x17_3sub2,
  121130. 0, 0, 0, 0, 0,
  121131. NULL,
  121132. NULL,
  121133. NULL,
  121134. NULL,
  121135. 0
  121136. };
  121137. static long _huff_lengthlist_line_512x17_3sub3[] = {
  121138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121141. 0, 0, 4, 8, 4, 8, 4, 8, 4, 8, 5, 8, 5, 8, 6, 8,
  121142. 4, 8, 4, 8, 5, 8, 5, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121143. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121144. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121145. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121146. };
  121147. static static_codebook _huff_book_line_512x17_3sub3 = {
  121148. 1, 128,
  121149. _huff_lengthlist_line_512x17_3sub3,
  121150. 0, 0, 0, 0, 0,
  121151. NULL,
  121152. NULL,
  121153. NULL,
  121154. NULL,
  121155. 0
  121156. };
  121157. static long _huff_lengthlist_line_512x17_class1[] = {
  121158. 1, 2, 3, 6, 5, 4, 7, 7,
  121159. };
  121160. static static_codebook _huff_book_line_512x17_class1 = {
  121161. 1, 8,
  121162. _huff_lengthlist_line_512x17_class1,
  121163. 0, 0, 0, 0, 0,
  121164. NULL,
  121165. NULL,
  121166. NULL,
  121167. NULL,
  121168. 0
  121169. };
  121170. static long _huff_lengthlist_line_512x17_class2[] = {
  121171. 3, 3, 3,14, 5, 4, 4,11, 8, 6, 6,10,17,12,11,17,
  121172. 6, 5, 5,15, 5, 3, 4,11, 8, 5, 5, 8,16, 9,10,14,
  121173. 10, 8, 9,17, 8, 6, 6,13,10, 7, 7,10,16,11,13,14,
  121174. 17,17,17,17,17,16,16,16,16,15,16,16,16,16,16,16,
  121175. };
  121176. static static_codebook _huff_book_line_512x17_class2 = {
  121177. 1, 64,
  121178. _huff_lengthlist_line_512x17_class2,
  121179. 0, 0, 0, 0, 0,
  121180. NULL,
  121181. NULL,
  121182. NULL,
  121183. NULL,
  121184. 0
  121185. };
  121186. static long _huff_lengthlist_line_512x17_class3[] = {
  121187. 2, 4, 6,17, 4, 5, 7,17, 8, 7,10,17,17,17,17,17,
  121188. 3, 4, 6,15, 3, 3, 6,15, 7, 6, 9,17,17,17,17,17,
  121189. 6, 8,10,17, 6, 6, 8,16, 9, 8,10,17,17,15,16,17,
  121190. 17,17,17,17,12,15,15,16,12,15,15,16,16,16,16,16,
  121191. };
  121192. static static_codebook _huff_book_line_512x17_class3 = {
  121193. 1, 64,
  121194. _huff_lengthlist_line_512x17_class3,
  121195. 0, 0, 0, 0, 0,
  121196. NULL,
  121197. NULL,
  121198. NULL,
  121199. NULL,
  121200. 0
  121201. };
  121202. static long _huff_lengthlist_line_128x4_class0[] = {
  121203. 7, 7, 7,11, 6, 6, 7,11, 7, 6, 6,10,12,10,10,13,
  121204. 7, 7, 8,11, 7, 7, 7,11, 7, 6, 7,10,11,10,10,13,
  121205. 10,10, 9,12, 9, 9, 9,11, 8, 8, 8,11,13,11,10,14,
  121206. 15,15,14,15,15,14,13,14,15,12,12,17,17,17,17,17,
  121207. 7, 7, 6, 9, 6, 6, 6, 9, 7, 6, 6, 8,11,11,10,12,
  121208. 7, 7, 7, 9, 7, 6, 6, 9, 7, 6, 6, 9,13,10,10,11,
  121209. 10, 9, 8,10, 9, 8, 8,10, 8, 8, 7, 9,13,12,10,11,
  121210. 17,14,14,13,15,14,12,13,17,13,12,15,17,17,14,17,
  121211. 7, 6, 6, 7, 6, 6, 5, 7, 6, 6, 6, 6,11, 9, 9, 9,
  121212. 7, 7, 6, 7, 7, 6, 6, 7, 6, 6, 6, 6,10, 9, 8, 9,
  121213. 10, 9, 8, 8, 9, 8, 7, 8, 8, 7, 6, 8,11,10, 9,10,
  121214. 17,17,12,15,15,15,12,14,14,14,10,12,15,13,12,13,
  121215. 11,10, 8,10,11,10, 8, 8,10, 9, 7, 7,10, 9, 9,11,
  121216. 11,11, 9,10,11,10, 8, 9,10, 8, 6, 8,10, 9, 9,11,
  121217. 14,13,10,12,12,11,10,10, 8, 7, 8,10,10,11,11,12,
  121218. 17,17,15,17,17,17,17,17,17,13,12,17,17,17,14,17,
  121219. };
  121220. static static_codebook _huff_book_line_128x4_class0 = {
  121221. 1, 256,
  121222. _huff_lengthlist_line_128x4_class0,
  121223. 0, 0, 0, 0, 0,
  121224. NULL,
  121225. NULL,
  121226. NULL,
  121227. NULL,
  121228. 0
  121229. };
  121230. static long _huff_lengthlist_line_128x4_0sub0[] = {
  121231. 2, 2, 2, 2,
  121232. };
  121233. static static_codebook _huff_book_line_128x4_0sub0 = {
  121234. 1, 4,
  121235. _huff_lengthlist_line_128x4_0sub0,
  121236. 0, 0, 0, 0, 0,
  121237. NULL,
  121238. NULL,
  121239. NULL,
  121240. NULL,
  121241. 0
  121242. };
  121243. static long _huff_lengthlist_line_128x4_0sub1[] = {
  121244. 0, 0, 0, 0, 3, 2, 3, 2, 3, 3,
  121245. };
  121246. static static_codebook _huff_book_line_128x4_0sub1 = {
  121247. 1, 10,
  121248. _huff_lengthlist_line_128x4_0sub1,
  121249. 0, 0, 0, 0, 0,
  121250. NULL,
  121251. NULL,
  121252. NULL,
  121253. NULL,
  121254. 0
  121255. };
  121256. static long _huff_lengthlist_line_128x4_0sub2[] = {
  121257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 4, 3, 4, 3,
  121258. 4, 4, 5, 4, 5, 4, 6, 5, 6,
  121259. };
  121260. static static_codebook _huff_book_line_128x4_0sub2 = {
  121261. 1, 25,
  121262. _huff_lengthlist_line_128x4_0sub2,
  121263. 0, 0, 0, 0, 0,
  121264. NULL,
  121265. NULL,
  121266. NULL,
  121267. NULL,
  121268. 0
  121269. };
  121270. static long _huff_lengthlist_line_128x4_0sub3[] = {
  121271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  121273. 5, 4, 6, 5, 6, 5, 7, 6, 6, 7, 7, 9, 9,11,11,16,
  121274. 11,14,10,11,11,13,16,15,15,15,15,15,15,15,15,15,
  121275. };
  121276. static static_codebook _huff_book_line_128x4_0sub3 = {
  121277. 1, 64,
  121278. _huff_lengthlist_line_128x4_0sub3,
  121279. 0, 0, 0, 0, 0,
  121280. NULL,
  121281. NULL,
  121282. NULL,
  121283. NULL,
  121284. 0
  121285. };
  121286. static long _huff_lengthlist_line_256x4_class0[] = {
  121287. 6, 7, 7,12, 6, 6, 7,12, 7, 6, 6,10,15,12,11,13,
  121288. 7, 7, 8,13, 7, 7, 8,12, 7, 7, 7,11,12,12,11,13,
  121289. 10, 9, 9,11, 9, 9, 9,10,10, 8, 8,12,14,12,12,14,
  121290. 11,11,12,14,11,12,11,15,15,12,13,15,15,15,15,15,
  121291. 6, 6, 7,10, 6, 6, 6,11, 7, 6, 6, 9,14,12,11,13,
  121292. 7, 7, 7,10, 6, 6, 7, 9, 7, 7, 6,10,13,12,10,12,
  121293. 9, 9, 9,11, 9, 9, 8, 9, 9, 8, 8,10,13,12,10,12,
  121294. 12,12,11,13,12,12,11,12,15,13,12,15,15,15,14,14,
  121295. 6, 6, 6, 8, 6, 6, 5, 6, 7, 7, 6, 5,11,10, 9, 8,
  121296. 7, 6, 6, 7, 6, 6, 5, 6, 7, 7, 6, 6,11,10, 9, 8,
  121297. 8, 8, 8, 9, 8, 8, 7, 8, 8, 8, 6, 7,11,10, 9, 9,
  121298. 14,11,10,14,14,11,10,15,13,11, 9,11,15,12,12,11,
  121299. 11, 9, 8, 8,10, 9, 8, 9,11,10, 9, 8,12,11,12,11,
  121300. 13,10, 8, 9,11,10, 8, 9,10, 9, 8, 9,10, 8,12,12,
  121301. 15,11,10,10,13,11,10,10, 8, 8, 7,12,10, 9,11,12,
  121302. 15,12,11,15,13,11,11,15,12,14,11,13,15,15,13,13,
  121303. };
  121304. static static_codebook _huff_book_line_256x4_class0 = {
  121305. 1, 256,
  121306. _huff_lengthlist_line_256x4_class0,
  121307. 0, 0, 0, 0, 0,
  121308. NULL,
  121309. NULL,
  121310. NULL,
  121311. NULL,
  121312. 0
  121313. };
  121314. static long _huff_lengthlist_line_256x4_0sub0[] = {
  121315. 2, 2, 2, 2,
  121316. };
  121317. static static_codebook _huff_book_line_256x4_0sub0 = {
  121318. 1, 4,
  121319. _huff_lengthlist_line_256x4_0sub0,
  121320. 0, 0, 0, 0, 0,
  121321. NULL,
  121322. NULL,
  121323. NULL,
  121324. NULL,
  121325. 0
  121326. };
  121327. static long _huff_lengthlist_line_256x4_0sub1[] = {
  121328. 0, 0, 0, 0, 2, 2, 3, 3, 3, 3,
  121329. };
  121330. static static_codebook _huff_book_line_256x4_0sub1 = {
  121331. 1, 10,
  121332. _huff_lengthlist_line_256x4_0sub1,
  121333. 0, 0, 0, 0, 0,
  121334. NULL,
  121335. NULL,
  121336. NULL,
  121337. NULL,
  121338. 0
  121339. };
  121340. static long _huff_lengthlist_line_256x4_0sub2[] = {
  121341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 3, 4, 3, 4, 3,
  121342. 5, 3, 5, 4, 5, 4, 6, 4, 6,
  121343. };
  121344. static static_codebook _huff_book_line_256x4_0sub2 = {
  121345. 1, 25,
  121346. _huff_lengthlist_line_256x4_0sub2,
  121347. 0, 0, 0, 0, 0,
  121348. NULL,
  121349. NULL,
  121350. NULL,
  121351. NULL,
  121352. 0
  121353. };
  121354. static long _huff_lengthlist_line_256x4_0sub3[] = {
  121355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  121357. 6, 4, 7, 4, 7, 5, 7, 6, 7, 6, 7, 8,10,13,13,13,
  121358. 13,13,13,13,13,13,13,13,13,13,13,12,12,12,12,12,
  121359. };
  121360. static static_codebook _huff_book_line_256x4_0sub3 = {
  121361. 1, 64,
  121362. _huff_lengthlist_line_256x4_0sub3,
  121363. 0, 0, 0, 0, 0,
  121364. NULL,
  121365. NULL,
  121366. NULL,
  121367. NULL,
  121368. 0
  121369. };
  121370. static long _huff_lengthlist_line_128x7_class0[] = {
  121371. 10, 7, 8,13, 9, 6, 7,11,10, 8, 8,12,17,17,17,17,
  121372. 7, 5, 5, 9, 6, 4, 4, 8, 8, 5, 5, 8,16,14,13,16,
  121373. 7, 5, 5, 7, 6, 3, 3, 5, 8, 5, 4, 7,14,12,12,15,
  121374. 10, 7, 8, 9, 7, 5, 5, 6, 9, 6, 5, 5,15,12, 9,10,
  121375. };
  121376. static static_codebook _huff_book_line_128x7_class0 = {
  121377. 1, 64,
  121378. _huff_lengthlist_line_128x7_class0,
  121379. 0, 0, 0, 0, 0,
  121380. NULL,
  121381. NULL,
  121382. NULL,
  121383. NULL,
  121384. 0
  121385. };
  121386. static long _huff_lengthlist_line_128x7_class1[] = {
  121387. 8,13,17,17, 8,11,17,17,11,13,17,17,17,17,17,17,
  121388. 6,10,16,17, 6,10,15,17, 8,10,16,17,17,17,17,17,
  121389. 9,13,15,17, 8,11,17,17,10,12,17,17,17,17,17,17,
  121390. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  121391. 6,11,15,17, 7,10,15,17, 8,10,17,17,17,15,17,17,
  121392. 4, 8,13,17, 4, 7,13,17, 6, 8,15,17,16,15,17,17,
  121393. 6,11,15,17, 6, 9,13,17, 8,10,17,17,15,17,17,17,
  121394. 16,17,17,17,12,14,15,17,13,14,15,17,17,17,17,17,
  121395. 5,10,14,17, 5, 9,14,17, 7, 9,15,17,15,15,17,17,
  121396. 3, 7,12,17, 3, 6,11,17, 5, 7,13,17,12,12,17,17,
  121397. 5, 9,14,17, 3, 7,11,17, 5, 8,13,17,13,11,16,17,
  121398. 12,17,17,17, 9,14,15,17,10,11,14,17,16,14,17,17,
  121399. 8,12,17,17, 8,12,17,17,10,12,17,17,17,17,17,17,
  121400. 5,10,17,17, 5, 9,15,17, 7, 9,17,17,13,13,17,17,
  121401. 7,11,17,17, 6,10,15,17, 7, 9,15,17,12,11,17,17,
  121402. 12,15,17,17,11,14,17,17,11,10,15,17,17,16,17,17,
  121403. };
  121404. static static_codebook _huff_book_line_128x7_class1 = {
  121405. 1, 256,
  121406. _huff_lengthlist_line_128x7_class1,
  121407. 0, 0, 0, 0, 0,
  121408. NULL,
  121409. NULL,
  121410. NULL,
  121411. NULL,
  121412. 0
  121413. };
  121414. static long _huff_lengthlist_line_128x7_0sub1[] = {
  121415. 0, 3, 3, 3, 3, 3, 3, 3, 3,
  121416. };
  121417. static static_codebook _huff_book_line_128x7_0sub1 = {
  121418. 1, 9,
  121419. _huff_lengthlist_line_128x7_0sub1,
  121420. 0, 0, 0, 0, 0,
  121421. NULL,
  121422. NULL,
  121423. NULL,
  121424. NULL,
  121425. 0
  121426. };
  121427. static long _huff_lengthlist_line_128x7_0sub2[] = {
  121428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 4, 4, 4,
  121429. 5, 4, 5, 4, 5, 4, 6, 4, 6,
  121430. };
  121431. static static_codebook _huff_book_line_128x7_0sub2 = {
  121432. 1, 25,
  121433. _huff_lengthlist_line_128x7_0sub2,
  121434. 0, 0, 0, 0, 0,
  121435. NULL,
  121436. NULL,
  121437. NULL,
  121438. NULL,
  121439. 0
  121440. };
  121441. static long _huff_lengthlist_line_128x7_0sub3[] = {
  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, 3, 5, 3, 5, 3, 5, 4,
  121444. 5, 4, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121445. 7, 8, 9,11,13,13,13,13,13,13,13,13,13,13,13,13,
  121446. };
  121447. static static_codebook _huff_book_line_128x7_0sub3 = {
  121448. 1, 64,
  121449. _huff_lengthlist_line_128x7_0sub3,
  121450. 0, 0, 0, 0, 0,
  121451. NULL,
  121452. NULL,
  121453. NULL,
  121454. NULL,
  121455. 0
  121456. };
  121457. static long _huff_lengthlist_line_128x7_1sub1[] = {
  121458. 0, 3, 3, 2, 3, 3, 4, 3, 4,
  121459. };
  121460. static static_codebook _huff_book_line_128x7_1sub1 = {
  121461. 1, 9,
  121462. _huff_lengthlist_line_128x7_1sub1,
  121463. 0, 0, 0, 0, 0,
  121464. NULL,
  121465. NULL,
  121466. NULL,
  121467. NULL,
  121468. 0
  121469. };
  121470. static long _huff_lengthlist_line_128x7_1sub2[] = {
  121471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 6, 3, 6, 3,
  121472. 6, 3, 7, 3, 8, 4, 9, 4, 9,
  121473. };
  121474. static static_codebook _huff_book_line_128x7_1sub2 = {
  121475. 1, 25,
  121476. _huff_lengthlist_line_128x7_1sub2,
  121477. 0, 0, 0, 0, 0,
  121478. NULL,
  121479. NULL,
  121480. NULL,
  121481. NULL,
  121482. 0
  121483. };
  121484. static long _huff_lengthlist_line_128x7_1sub3[] = {
  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, 1, 7, 2, 7, 3, 8, 4,
  121487. 9, 5, 9, 8,10,11,11,12,14,14,14,14,14,14,14,14,
  121488. 14,14,14,14,14,14,14,14,14,14,14,14,13,13,13,13,
  121489. };
  121490. static static_codebook _huff_book_line_128x7_1sub3 = {
  121491. 1, 64,
  121492. _huff_lengthlist_line_128x7_1sub3,
  121493. 0, 0, 0, 0, 0,
  121494. NULL,
  121495. NULL,
  121496. NULL,
  121497. NULL,
  121498. 0
  121499. };
  121500. static long _huff_lengthlist_line_128x11_class1[] = {
  121501. 1, 6, 3, 7, 2, 4, 5, 7,
  121502. };
  121503. static static_codebook _huff_book_line_128x11_class1 = {
  121504. 1, 8,
  121505. _huff_lengthlist_line_128x11_class1,
  121506. 0, 0, 0, 0, 0,
  121507. NULL,
  121508. NULL,
  121509. NULL,
  121510. NULL,
  121511. 0
  121512. };
  121513. static long _huff_lengthlist_line_128x11_class2[] = {
  121514. 1, 6,12,16, 4,12,15,16, 9,15,16,16,16,16,16,16,
  121515. 2, 5,11,16, 5,11,13,16, 9,13,16,16,16,16,16,16,
  121516. 4, 8,12,16, 5, 9,12,16, 9,13,15,16,16,16,16,16,
  121517. 15,16,16,16,11,14,13,16,12,15,16,16,16,16,16,15,
  121518. };
  121519. static static_codebook _huff_book_line_128x11_class2 = {
  121520. 1, 64,
  121521. _huff_lengthlist_line_128x11_class2,
  121522. 0, 0, 0, 0, 0,
  121523. NULL,
  121524. NULL,
  121525. NULL,
  121526. NULL,
  121527. 0
  121528. };
  121529. static long _huff_lengthlist_line_128x11_class3[] = {
  121530. 7, 6, 9,17, 7, 6, 8,17,12, 9,11,16,16,16,16,16,
  121531. 5, 4, 7,16, 5, 3, 6,14, 9, 6, 8,15,16,16,16,16,
  121532. 5, 4, 6,13, 3, 2, 4,11, 7, 4, 6,13,16,11,10,14,
  121533. 12,12,12,16, 9, 7,10,15,12, 9,11,16,16,15,15,16,
  121534. };
  121535. static static_codebook _huff_book_line_128x11_class3 = {
  121536. 1, 64,
  121537. _huff_lengthlist_line_128x11_class3,
  121538. 0, 0, 0, 0, 0,
  121539. NULL,
  121540. NULL,
  121541. NULL,
  121542. NULL,
  121543. 0
  121544. };
  121545. static long _huff_lengthlist_line_128x11_0sub0[] = {
  121546. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121547. 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 6, 6, 6, 7, 6,
  121548. 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6, 8, 7,
  121549. 8, 7, 8, 7, 8, 7, 9, 7, 9, 8, 9, 8, 9, 8,10, 8,
  121550. 10, 9,10, 9,10, 9,11, 9,11, 9,10,10,11,10,11,10,
  121551. 11,11,11,11,11,11,12,13,14,14,14,15,15,16,16,16,
  121552. 17,15,16,15,16,16,17,17,16,17,17,17,17,17,17,17,
  121553. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  121554. };
  121555. static static_codebook _huff_book_line_128x11_0sub0 = {
  121556. 1, 128,
  121557. _huff_lengthlist_line_128x11_0sub0,
  121558. 0, 0, 0, 0, 0,
  121559. NULL,
  121560. NULL,
  121561. NULL,
  121562. NULL,
  121563. 0
  121564. };
  121565. static long _huff_lengthlist_line_128x11_1sub0[] = {
  121566. 2, 5, 5, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  121567. 6, 5, 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6,
  121568. };
  121569. static static_codebook _huff_book_line_128x11_1sub0 = {
  121570. 1, 32,
  121571. _huff_lengthlist_line_128x11_1sub0,
  121572. 0, 0, 0, 0, 0,
  121573. NULL,
  121574. NULL,
  121575. NULL,
  121576. NULL,
  121577. 0
  121578. };
  121579. static long _huff_lengthlist_line_128x11_1sub1[] = {
  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. 5, 3, 5, 3, 6, 4, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  121583. 8, 4, 9, 5, 9, 5, 9, 5, 9, 6,10, 6,10, 6,11, 7,
  121584. 10, 7,10, 8,11, 9,11, 9,11,10,11,11,12,11,11,12,
  121585. 15,15,12,14,11,14,12,14,11,14,13,14,12,14,11,14,
  121586. 11,14,12,14,11,14,11,14,13,13,14,14,14,14,14,14,
  121587. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  121588. };
  121589. static static_codebook _huff_book_line_128x11_1sub1 = {
  121590. 1, 128,
  121591. _huff_lengthlist_line_128x11_1sub1,
  121592. 0, 0, 0, 0, 0,
  121593. NULL,
  121594. NULL,
  121595. NULL,
  121596. NULL,
  121597. 0
  121598. };
  121599. static long _huff_lengthlist_line_128x11_2sub1[] = {
  121600. 0, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4,
  121601. 5, 5,
  121602. };
  121603. static static_codebook _huff_book_line_128x11_2sub1 = {
  121604. 1, 18,
  121605. _huff_lengthlist_line_128x11_2sub1,
  121606. 0, 0, 0, 0, 0,
  121607. NULL,
  121608. NULL,
  121609. NULL,
  121610. NULL,
  121611. 0
  121612. };
  121613. static long _huff_lengthlist_line_128x11_2sub2[] = {
  121614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121615. 0, 0, 3, 3, 3, 4, 4, 4, 4, 5, 4, 5, 4, 6, 5, 7,
  121616. 5, 7, 6, 8, 6, 8, 6, 9, 7, 9, 7,10, 7, 9, 8,11,
  121617. 8,11,
  121618. };
  121619. static static_codebook _huff_book_line_128x11_2sub2 = {
  121620. 1, 50,
  121621. _huff_lengthlist_line_128x11_2sub2,
  121622. 0, 0, 0, 0, 0,
  121623. NULL,
  121624. NULL,
  121625. NULL,
  121626. NULL,
  121627. 0
  121628. };
  121629. static long _huff_lengthlist_line_128x11_2sub3[] = {
  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, 4, 8, 3, 8, 4, 8, 4, 8, 6, 8, 5, 8, 4, 8,
  121634. 4, 8, 6, 8, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121635. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121636. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121637. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121638. };
  121639. static static_codebook _huff_book_line_128x11_2sub3 = {
  121640. 1, 128,
  121641. _huff_lengthlist_line_128x11_2sub3,
  121642. 0, 0, 0, 0, 0,
  121643. NULL,
  121644. NULL,
  121645. NULL,
  121646. NULL,
  121647. 0
  121648. };
  121649. static long _huff_lengthlist_line_128x11_3sub1[] = {
  121650. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4,
  121651. 5, 4,
  121652. };
  121653. static static_codebook _huff_book_line_128x11_3sub1 = {
  121654. 1, 18,
  121655. _huff_lengthlist_line_128x11_3sub1,
  121656. 0, 0, 0, 0, 0,
  121657. NULL,
  121658. NULL,
  121659. NULL,
  121660. NULL,
  121661. 0
  121662. };
  121663. static long _huff_lengthlist_line_128x11_3sub2[] = {
  121664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121665. 0, 0, 5, 3, 5, 4, 6, 4, 6, 4, 7, 4, 7, 4, 8, 4,
  121666. 8, 4, 9, 4, 9, 4,10, 4,10, 5,10, 5,11, 5,12, 6,
  121667. 12, 6,
  121668. };
  121669. static static_codebook _huff_book_line_128x11_3sub2 = {
  121670. 1, 50,
  121671. _huff_lengthlist_line_128x11_3sub2,
  121672. 0, 0, 0, 0, 0,
  121673. NULL,
  121674. NULL,
  121675. NULL,
  121676. NULL,
  121677. 0
  121678. };
  121679. static long _huff_lengthlist_line_128x11_3sub3[] = {
  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, 7, 1, 6, 3, 7, 3, 8, 4, 8, 5, 8, 8, 8, 9,
  121684. 7, 8, 8, 7, 7, 7, 8, 9,10, 9, 9,10,10,10,10,10,
  121685. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121686. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121687. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  121688. };
  121689. static static_codebook _huff_book_line_128x11_3sub3 = {
  121690. 1, 128,
  121691. _huff_lengthlist_line_128x11_3sub3,
  121692. 0, 0, 0, 0, 0,
  121693. NULL,
  121694. NULL,
  121695. NULL,
  121696. NULL,
  121697. 0
  121698. };
  121699. static long _huff_lengthlist_line_128x17_class1[] = {
  121700. 1, 3, 4, 7, 2, 5, 6, 7,
  121701. };
  121702. static static_codebook _huff_book_line_128x17_class1 = {
  121703. 1, 8,
  121704. _huff_lengthlist_line_128x17_class1,
  121705. 0, 0, 0, 0, 0,
  121706. NULL,
  121707. NULL,
  121708. NULL,
  121709. NULL,
  121710. 0
  121711. };
  121712. static long _huff_lengthlist_line_128x17_class2[] = {
  121713. 1, 4,10,19, 3, 8,13,19, 7,12,19,19,19,19,19,19,
  121714. 2, 6,11,19, 8,13,19,19, 9,11,19,19,19,19,19,19,
  121715. 6, 7,13,19, 9,13,19,19,10,13,18,18,18,18,18,18,
  121716. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  121717. };
  121718. static static_codebook _huff_book_line_128x17_class2 = {
  121719. 1, 64,
  121720. _huff_lengthlist_line_128x17_class2,
  121721. 0, 0, 0, 0, 0,
  121722. NULL,
  121723. NULL,
  121724. NULL,
  121725. NULL,
  121726. 0
  121727. };
  121728. static long _huff_lengthlist_line_128x17_class3[] = {
  121729. 3, 6,10,17, 4, 8,11,20, 8,10,11,20,20,20,20,20,
  121730. 2, 4, 8,18, 4, 6, 8,17, 7, 8,10,20,20,17,20,20,
  121731. 3, 5, 8,17, 3, 4, 6,17, 8, 8,10,17,17,12,16,20,
  121732. 13,13,15,20,10,10,12,20,15,14,15,20,20,20,19,19,
  121733. };
  121734. static static_codebook _huff_book_line_128x17_class3 = {
  121735. 1, 64,
  121736. _huff_lengthlist_line_128x17_class3,
  121737. 0, 0, 0, 0, 0,
  121738. NULL,
  121739. NULL,
  121740. NULL,
  121741. NULL,
  121742. 0
  121743. };
  121744. static long _huff_lengthlist_line_128x17_0sub0[] = {
  121745. 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121746. 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5,
  121747. 8, 5, 8, 5, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6, 9, 6,
  121748. 9, 6, 9, 7, 9, 7, 9, 7, 9, 7,10, 7,10, 8,10, 8,
  121749. 10, 8,10, 8,10, 8,11, 8,11, 8,11, 8,11, 8,11, 9,
  121750. 12, 9,12, 9,12, 9,12, 9,12,10,12,10,13,11,13,11,
  121751. 14,12,14,13,15,14,16,14,17,15,18,16,20,20,20,20,
  121752. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  121753. };
  121754. static static_codebook _huff_book_line_128x17_0sub0 = {
  121755. 1, 128,
  121756. _huff_lengthlist_line_128x17_0sub0,
  121757. 0, 0, 0, 0, 0,
  121758. NULL,
  121759. NULL,
  121760. NULL,
  121761. NULL,
  121762. 0
  121763. };
  121764. static long _huff_lengthlist_line_128x17_1sub0[] = {
  121765. 2, 5, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  121766. 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7,
  121767. };
  121768. static static_codebook _huff_book_line_128x17_1sub0 = {
  121769. 1, 32,
  121770. _huff_lengthlist_line_128x17_1sub0,
  121771. 0, 0, 0, 0, 0,
  121772. NULL,
  121773. NULL,
  121774. NULL,
  121775. NULL,
  121776. 0
  121777. };
  121778. static long _huff_lengthlist_line_128x17_1sub1[] = {
  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. 4, 3, 5, 3, 5, 3, 6, 3, 6, 4, 6, 4, 7, 4, 7, 5,
  121782. 8, 5, 8, 6, 9, 7, 9, 7, 9, 8,10, 9,10, 9,11,10,
  121783. 11,11,11,11,11,11,12,12,12,13,12,13,12,14,12,15,
  121784. 12,14,12,16,13,17,13,17,14,17,14,16,13,17,14,17,
  121785. 14,17,15,17,15,15,16,17,17,17,17,17,17,17,17,17,
  121786. 17,17,17,17,17,17,16,16,16,16,16,16,16,16,16,16,
  121787. };
  121788. static static_codebook _huff_book_line_128x17_1sub1 = {
  121789. 1, 128,
  121790. _huff_lengthlist_line_128x17_1sub1,
  121791. 0, 0, 0, 0, 0,
  121792. NULL,
  121793. NULL,
  121794. NULL,
  121795. NULL,
  121796. 0
  121797. };
  121798. static long _huff_lengthlist_line_128x17_2sub1[] = {
  121799. 0, 4, 5, 4, 6, 4, 8, 3, 9, 3, 9, 2, 9, 3, 8, 4,
  121800. 9, 4,
  121801. };
  121802. static static_codebook _huff_book_line_128x17_2sub1 = {
  121803. 1, 18,
  121804. _huff_lengthlist_line_128x17_2sub1,
  121805. 0, 0, 0, 0, 0,
  121806. NULL,
  121807. NULL,
  121808. NULL,
  121809. NULL,
  121810. 0
  121811. };
  121812. static long _huff_lengthlist_line_128x17_2sub2[] = {
  121813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121814. 0, 0, 5, 1, 5, 3, 5, 3, 5, 4, 7, 5,10, 7,10, 7,
  121815. 12,10,14,10,14, 9,14,11,14,14,14,13,13,13,13,13,
  121816. 13,13,
  121817. };
  121818. static static_codebook _huff_book_line_128x17_2sub2 = {
  121819. 1, 50,
  121820. _huff_lengthlist_line_128x17_2sub2,
  121821. 0, 0, 0, 0, 0,
  121822. NULL,
  121823. NULL,
  121824. NULL,
  121825. NULL,
  121826. 0
  121827. };
  121828. static long _huff_lengthlist_line_128x17_2sub3[] = {
  121829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121832. 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121833. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6,
  121834. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121835. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121836. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121837. };
  121838. static static_codebook _huff_book_line_128x17_2sub3 = {
  121839. 1, 128,
  121840. _huff_lengthlist_line_128x17_2sub3,
  121841. 0, 0, 0, 0, 0,
  121842. NULL,
  121843. NULL,
  121844. NULL,
  121845. NULL,
  121846. 0
  121847. };
  121848. static long _huff_lengthlist_line_128x17_3sub1[] = {
  121849. 0, 4, 4, 4, 4, 4, 4, 4, 5, 3, 5, 3, 5, 4, 6, 4,
  121850. 6, 4,
  121851. };
  121852. static static_codebook _huff_book_line_128x17_3sub1 = {
  121853. 1, 18,
  121854. _huff_lengthlist_line_128x17_3sub1,
  121855. 0, 0, 0, 0, 0,
  121856. NULL,
  121857. NULL,
  121858. NULL,
  121859. NULL,
  121860. 0
  121861. };
  121862. static long _huff_lengthlist_line_128x17_3sub2[] = {
  121863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121864. 0, 0, 5, 3, 6, 3, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  121865. 8, 4, 8, 4, 8, 4, 9, 4, 9, 5,10, 5,10, 7,10, 8,
  121866. 10, 8,
  121867. };
  121868. static static_codebook _huff_book_line_128x17_3sub2 = {
  121869. 1, 50,
  121870. _huff_lengthlist_line_128x17_3sub2,
  121871. 0, 0, 0, 0, 0,
  121872. NULL,
  121873. NULL,
  121874. NULL,
  121875. NULL,
  121876. 0
  121877. };
  121878. static long _huff_lengthlist_line_128x17_3sub3[] = {
  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, 3, 2, 4, 3, 4, 4, 4, 5, 4, 7, 5, 8, 5,11,
  121883. 6,10, 6,12, 7,12, 7,12, 8,12, 8,12,10,12,12,12,
  121884. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121885. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121886. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121887. };
  121888. static static_codebook _huff_book_line_128x17_3sub3 = {
  121889. 1, 128,
  121890. _huff_lengthlist_line_128x17_3sub3,
  121891. 0, 0, 0, 0, 0,
  121892. NULL,
  121893. NULL,
  121894. NULL,
  121895. NULL,
  121896. 0
  121897. };
  121898. static long _huff_lengthlist_line_1024x27_class1[] = {
  121899. 2,10, 8,14, 7,12,11,14, 1, 5, 3, 7, 4, 9, 7,13,
  121900. };
  121901. static static_codebook _huff_book_line_1024x27_class1 = {
  121902. 1, 16,
  121903. _huff_lengthlist_line_1024x27_class1,
  121904. 0, 0, 0, 0, 0,
  121905. NULL,
  121906. NULL,
  121907. NULL,
  121908. NULL,
  121909. 0
  121910. };
  121911. static long _huff_lengthlist_line_1024x27_class2[] = {
  121912. 1, 4, 2, 6, 3, 7, 5, 7,
  121913. };
  121914. static static_codebook _huff_book_line_1024x27_class2 = {
  121915. 1, 8,
  121916. _huff_lengthlist_line_1024x27_class2,
  121917. 0, 0, 0, 0, 0,
  121918. NULL,
  121919. NULL,
  121920. NULL,
  121921. NULL,
  121922. 0
  121923. };
  121924. static long _huff_lengthlist_line_1024x27_class3[] = {
  121925. 1, 5, 7,21, 5, 8, 9,21,10, 9,12,20,20,16,20,20,
  121926. 4, 8, 9,20, 6, 8, 9,20,11,11,13,20,20,15,17,20,
  121927. 9,11,14,20, 8,10,15,20,11,13,15,20,20,20,20,20,
  121928. 20,20,20,20,13,20,20,20,18,18,20,20,20,20,20,20,
  121929. 3, 6, 8,20, 6, 7, 9,20,10, 9,12,20,20,20,20,20,
  121930. 5, 7, 9,20, 6, 6, 9,20,10, 9,12,20,20,20,20,20,
  121931. 8,10,13,20, 8, 9,12,20,11,10,12,20,20,20,20,20,
  121932. 18,20,20,20,15,17,18,20,18,17,18,20,20,20,20,20,
  121933. 7,10,12,20, 8, 9,11,20,14,13,14,20,20,20,20,20,
  121934. 6, 9,12,20, 7, 8,11,20,12,11,13,20,20,20,20,20,
  121935. 9,11,15,20, 8,10,14,20,12,11,14,20,20,20,20,20,
  121936. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  121937. 11,16,18,20,15,15,17,20,20,17,20,20,20,20,20,20,
  121938. 9,14,16,20,12,12,15,20,17,15,18,20,20,20,20,20,
  121939. 16,19,18,20,15,16,20,20,17,17,20,20,20,20,20,20,
  121940. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  121941. };
  121942. static static_codebook _huff_book_line_1024x27_class3 = {
  121943. 1, 256,
  121944. _huff_lengthlist_line_1024x27_class3,
  121945. 0, 0, 0, 0, 0,
  121946. NULL,
  121947. NULL,
  121948. NULL,
  121949. NULL,
  121950. 0
  121951. };
  121952. static long _huff_lengthlist_line_1024x27_class4[] = {
  121953. 2, 3, 7,13, 4, 4, 7,15, 8, 6, 9,17,21,16,15,21,
  121954. 2, 5, 7,11, 5, 5, 7,14, 9, 7,10,16,17,15,16,21,
  121955. 4, 7,10,17, 7, 7, 9,15,11, 9,11,16,21,18,15,21,
  121956. 18,21,21,21,15,17,17,19,21,19,18,20,21,21,21,20,
  121957. };
  121958. static static_codebook _huff_book_line_1024x27_class4 = {
  121959. 1, 64,
  121960. _huff_lengthlist_line_1024x27_class4,
  121961. 0, 0, 0, 0, 0,
  121962. NULL,
  121963. NULL,
  121964. NULL,
  121965. NULL,
  121966. 0
  121967. };
  121968. static long _huff_lengthlist_line_1024x27_0sub0[] = {
  121969. 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121970. 6, 5, 6, 5, 6, 5, 6, 5, 7, 5, 7, 5, 7, 5, 7, 5,
  121971. 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,10, 6,10, 6,11, 6,
  121972. 11, 7,11, 7,12, 7,12, 7,12, 7,12, 7,12, 7,12, 7,
  121973. 12, 7,12, 8,13, 8,12, 8,12, 8,13, 8,13, 9,13, 9,
  121974. 13, 9,13, 9,12,10,12,10,13,10,14,11,14,12,14,13,
  121975. 14,13,14,14,15,16,15,15,15,14,15,17,21,22,22,21,
  121976. 22,22,22,22,22,22,21,21,21,21,21,21,21,21,21,21,
  121977. };
  121978. static static_codebook _huff_book_line_1024x27_0sub0 = {
  121979. 1, 128,
  121980. _huff_lengthlist_line_1024x27_0sub0,
  121981. 0, 0, 0, 0, 0,
  121982. NULL,
  121983. NULL,
  121984. NULL,
  121985. NULL,
  121986. 0
  121987. };
  121988. static long _huff_lengthlist_line_1024x27_1sub0[] = {
  121989. 2, 5, 5, 4, 5, 4, 5, 4, 5, 4, 6, 5, 6, 5, 6, 5,
  121990. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,
  121991. };
  121992. static static_codebook _huff_book_line_1024x27_1sub0 = {
  121993. 1, 32,
  121994. _huff_lengthlist_line_1024x27_1sub0,
  121995. 0, 0, 0, 0, 0,
  121996. NULL,
  121997. NULL,
  121998. NULL,
  121999. NULL,
  122000. 0
  122001. };
  122002. static long _huff_lengthlist_line_1024x27_1sub1[] = {
  122003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122005. 8, 5, 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4,
  122006. 9, 4, 9, 4, 9, 4, 8, 4, 8, 4, 9, 5, 9, 5, 9, 5,
  122007. 9, 5, 9, 6,10, 6,10, 7,10, 8,11, 9,11,11,12,13,
  122008. 12,14,13,15,13,15,14,16,14,17,15,17,15,15,16,16,
  122009. 15,16,16,16,15,18,16,15,17,17,19,19,19,19,19,19,
  122010. 19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,
  122011. };
  122012. static static_codebook _huff_book_line_1024x27_1sub1 = {
  122013. 1, 128,
  122014. _huff_lengthlist_line_1024x27_1sub1,
  122015. 0, 0, 0, 0, 0,
  122016. NULL,
  122017. NULL,
  122018. NULL,
  122019. NULL,
  122020. 0
  122021. };
  122022. static long _huff_lengthlist_line_1024x27_2sub0[] = {
  122023. 1, 5, 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  122024. 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 9, 8,10, 9,10, 9,
  122025. };
  122026. static static_codebook _huff_book_line_1024x27_2sub0 = {
  122027. 1, 32,
  122028. _huff_lengthlist_line_1024x27_2sub0,
  122029. 0, 0, 0, 0, 0,
  122030. NULL,
  122031. NULL,
  122032. NULL,
  122033. NULL,
  122034. 0
  122035. };
  122036. static long _huff_lengthlist_line_1024x27_2sub1[] = {
  122037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122039. 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 5, 5, 6, 5, 6, 5,
  122040. 7, 5, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 9, 8, 9, 9,
  122041. 9, 9,10,10,10,11, 9,12, 9,12, 9,15,10,14, 9,13,
  122042. 10,13,10,12,10,12,10,13,10,12,11,13,11,14,12,13,
  122043. 13,14,14,13,14,15,14,16,13,13,14,16,16,16,16,16,
  122044. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,15,15,
  122045. };
  122046. static static_codebook _huff_book_line_1024x27_2sub1 = {
  122047. 1, 128,
  122048. _huff_lengthlist_line_1024x27_2sub1,
  122049. 0, 0, 0, 0, 0,
  122050. NULL,
  122051. NULL,
  122052. NULL,
  122053. NULL,
  122054. 0
  122055. };
  122056. static long _huff_lengthlist_line_1024x27_3sub1[] = {
  122057. 0, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4, 4, 5,
  122058. 5, 5,
  122059. };
  122060. static static_codebook _huff_book_line_1024x27_3sub1 = {
  122061. 1, 18,
  122062. _huff_lengthlist_line_1024x27_3sub1,
  122063. 0, 0, 0, 0, 0,
  122064. NULL,
  122065. NULL,
  122066. NULL,
  122067. NULL,
  122068. 0
  122069. };
  122070. static long _huff_lengthlist_line_1024x27_3sub2[] = {
  122071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122072. 0, 0, 3, 3, 4, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6,
  122073. 5, 7, 5, 8, 6, 8, 6, 9, 7,10, 7,10, 8,10, 8,11,
  122074. 9,11,
  122075. };
  122076. static static_codebook _huff_book_line_1024x27_3sub2 = {
  122077. 1, 50,
  122078. _huff_lengthlist_line_1024x27_3sub2,
  122079. 0, 0, 0, 0, 0,
  122080. NULL,
  122081. NULL,
  122082. NULL,
  122083. NULL,
  122084. 0
  122085. };
  122086. static long _huff_lengthlist_line_1024x27_3sub3[] = {
  122087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122090. 0, 0, 3, 7, 3, 8, 3,10, 3, 8, 3, 9, 3, 8, 4, 9,
  122091. 4, 9, 5, 9, 6,10, 6, 9, 7,11, 7,12, 9,13,10,13,
  122092. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  122093. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  122094. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  122095. };
  122096. static static_codebook _huff_book_line_1024x27_3sub3 = {
  122097. 1, 128,
  122098. _huff_lengthlist_line_1024x27_3sub3,
  122099. 0, 0, 0, 0, 0,
  122100. NULL,
  122101. NULL,
  122102. NULL,
  122103. NULL,
  122104. 0
  122105. };
  122106. static long _huff_lengthlist_line_1024x27_4sub1[] = {
  122107. 0, 4, 5, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4,
  122108. 5, 4,
  122109. };
  122110. static static_codebook _huff_book_line_1024x27_4sub1 = {
  122111. 1, 18,
  122112. _huff_lengthlist_line_1024x27_4sub1,
  122113. 0, 0, 0, 0, 0,
  122114. NULL,
  122115. NULL,
  122116. NULL,
  122117. NULL,
  122118. 0
  122119. };
  122120. static long _huff_lengthlist_line_1024x27_4sub2[] = {
  122121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122122. 0, 0, 4, 2, 4, 2, 5, 3, 5, 4, 6, 6, 6, 7, 7, 8,
  122123. 7, 8, 7, 8, 7, 9, 8, 9, 8, 9, 8,10, 8,11, 9,12,
  122124. 9,12,
  122125. };
  122126. static static_codebook _huff_book_line_1024x27_4sub2 = {
  122127. 1, 50,
  122128. _huff_lengthlist_line_1024x27_4sub2,
  122129. 0, 0, 0, 0, 0,
  122130. NULL,
  122131. NULL,
  122132. NULL,
  122133. NULL,
  122134. 0
  122135. };
  122136. static long _huff_lengthlist_line_1024x27_4sub3[] = {
  122137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122140. 0, 0, 2, 5, 2, 6, 3, 6, 4, 7, 4, 7, 5, 9, 5,11,
  122141. 6,11, 6,11, 7,11, 6,11, 6,11, 9,11, 8,11,11,11,
  122142. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122143. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122144. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  122145. };
  122146. static static_codebook _huff_book_line_1024x27_4sub3 = {
  122147. 1, 128,
  122148. _huff_lengthlist_line_1024x27_4sub3,
  122149. 0, 0, 0, 0, 0,
  122150. NULL,
  122151. NULL,
  122152. NULL,
  122153. NULL,
  122154. 0
  122155. };
  122156. static long _huff_lengthlist_line_2048x27_class1[] = {
  122157. 2, 6, 8, 9, 7,11,13,13, 1, 3, 5, 5, 6, 6,12,10,
  122158. };
  122159. static static_codebook _huff_book_line_2048x27_class1 = {
  122160. 1, 16,
  122161. _huff_lengthlist_line_2048x27_class1,
  122162. 0, 0, 0, 0, 0,
  122163. NULL,
  122164. NULL,
  122165. NULL,
  122166. NULL,
  122167. 0
  122168. };
  122169. static long _huff_lengthlist_line_2048x27_class2[] = {
  122170. 1, 2, 3, 6, 4, 7, 5, 7,
  122171. };
  122172. static static_codebook _huff_book_line_2048x27_class2 = {
  122173. 1, 8,
  122174. _huff_lengthlist_line_2048x27_class2,
  122175. 0, 0, 0, 0, 0,
  122176. NULL,
  122177. NULL,
  122178. NULL,
  122179. NULL,
  122180. 0
  122181. };
  122182. static long _huff_lengthlist_line_2048x27_class3[] = {
  122183. 3, 3, 6,16, 5, 5, 7,16, 9, 8,11,16,16,16,16,16,
  122184. 5, 5, 8,16, 5, 5, 7,16, 8, 7, 9,16,16,16,16,16,
  122185. 9, 9,12,16, 6, 8,11,16, 9,10,11,16,16,16,16,16,
  122186. 16,16,16,16,13,16,16,16,15,16,16,16,16,16,16,16,
  122187. 5, 4, 7,16, 6, 5, 8,16, 9, 8,10,16,16,16,16,16,
  122188. 5, 5, 7,15, 5, 4, 6,15, 7, 6, 8,16,16,16,16,16,
  122189. 9, 9,11,15, 7, 7, 9,16, 8, 8, 9,16,16,16,16,16,
  122190. 16,16,16,16,15,15,15,16,15,15,14,16,16,16,16,16,
  122191. 8, 8,11,16, 8, 9,10,16,11,10,14,16,16,16,16,16,
  122192. 6, 8,10,16, 6, 7,10,16, 8, 8,11,16,14,16,16,16,
  122193. 10,11,14,16, 9, 9,11,16,10,10,11,16,16,16,16,16,
  122194. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  122195. 16,16,16,16,15,16,16,16,16,16,16,16,16,16,16,16,
  122196. 12,16,15,16,12,14,16,16,16,16,16,16,16,16,16,16,
  122197. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  122198. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  122199. };
  122200. static static_codebook _huff_book_line_2048x27_class3 = {
  122201. 1, 256,
  122202. _huff_lengthlist_line_2048x27_class3,
  122203. 0, 0, 0, 0, 0,
  122204. NULL,
  122205. NULL,
  122206. NULL,
  122207. NULL,
  122208. 0
  122209. };
  122210. static long _huff_lengthlist_line_2048x27_class4[] = {
  122211. 2, 4, 7,13, 4, 5, 7,15, 8, 7,10,16,16,14,16,16,
  122212. 2, 4, 7,16, 3, 4, 7,14, 8, 8,10,16,16,16,15,16,
  122213. 6, 8,11,16, 7, 7, 9,16,11, 9,13,16,16,16,15,16,
  122214. 16,16,16,16,14,16,16,16,16,16,16,16,16,16,16,16,
  122215. };
  122216. static static_codebook _huff_book_line_2048x27_class4 = {
  122217. 1, 64,
  122218. _huff_lengthlist_line_2048x27_class4,
  122219. 0, 0, 0, 0, 0,
  122220. NULL,
  122221. NULL,
  122222. NULL,
  122223. NULL,
  122224. 0
  122225. };
  122226. static long _huff_lengthlist_line_2048x27_0sub0[] = {
  122227. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  122228. 6, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5, 8, 5, 9, 5,
  122229. 9, 6,10, 6,10, 6,11, 6,11, 6,11, 6,11, 6,11, 6,
  122230. 11, 6,11, 6,12, 7,11, 7,11, 7,11, 7,11, 7,10, 7,
  122231. 11, 7,11, 7,12, 7,11, 8,11, 8,11, 8,11, 8,13, 8,
  122232. 12, 9,11, 9,11, 9,11,10,12,10,12, 9,12,10,12,11,
  122233. 14,12,16,12,12,11,14,16,17,17,17,17,17,17,17,17,
  122234. 17,17,17,17,17,17,17,17,17,17,17,17,16,16,16,16,
  122235. };
  122236. static static_codebook _huff_book_line_2048x27_0sub0 = {
  122237. 1, 128,
  122238. _huff_lengthlist_line_2048x27_0sub0,
  122239. 0, 0, 0, 0, 0,
  122240. NULL,
  122241. NULL,
  122242. NULL,
  122243. NULL,
  122244. 0
  122245. };
  122246. static long _huff_lengthlist_line_2048x27_1sub0[] = {
  122247. 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  122248. 5, 5, 6, 6, 6, 6, 6, 6, 7, 6, 7, 6, 7, 6, 7, 6,
  122249. };
  122250. static static_codebook _huff_book_line_2048x27_1sub0 = {
  122251. 1, 32,
  122252. _huff_lengthlist_line_2048x27_1sub0,
  122253. 0, 0, 0, 0, 0,
  122254. NULL,
  122255. NULL,
  122256. NULL,
  122257. NULL,
  122258. 0
  122259. };
  122260. static long _huff_lengthlist_line_2048x27_1sub1[] = {
  122261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122263. 6, 5, 7, 5, 7, 4, 7, 4, 8, 4, 8, 4, 8, 4, 8, 3,
  122264. 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 5, 9, 5, 9, 6,
  122265. 9, 7, 9, 8, 9, 9, 9,10, 9,11, 9,14, 9,15,10,15,
  122266. 10,15,10,15,10,15,11,15,10,14,12,14,11,14,13,14,
  122267. 13,15,15,15,12,15,15,15,13,15,13,15,13,15,15,15,
  122268. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,14,
  122269. };
  122270. static static_codebook _huff_book_line_2048x27_1sub1 = {
  122271. 1, 128,
  122272. _huff_lengthlist_line_2048x27_1sub1,
  122273. 0, 0, 0, 0, 0,
  122274. NULL,
  122275. NULL,
  122276. NULL,
  122277. NULL,
  122278. 0
  122279. };
  122280. static long _huff_lengthlist_line_2048x27_2sub0[] = {
  122281. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  122282. 6, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  122283. };
  122284. static static_codebook _huff_book_line_2048x27_2sub0 = {
  122285. 1, 32,
  122286. _huff_lengthlist_line_2048x27_2sub0,
  122287. 0, 0, 0, 0, 0,
  122288. NULL,
  122289. NULL,
  122290. NULL,
  122291. NULL,
  122292. 0
  122293. };
  122294. static long _huff_lengthlist_line_2048x27_2sub1[] = {
  122295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122297. 3, 4, 3, 4, 3, 4, 4, 5, 4, 5, 5, 5, 6, 6, 6, 7,
  122298. 6, 8, 6, 8, 6, 9, 7,10, 7,10, 7,10, 7,12, 7,12,
  122299. 7,12, 9,12,11,12,10,12,10,12,11,12,12,12,10,12,
  122300. 10,12,10,12, 9,12,11,12,12,12,12,12,11,12,11,12,
  122301. 12,12,12,12,12,12,12,12,10,10,12,12,12,12,12,10,
  122302. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  122303. };
  122304. static static_codebook _huff_book_line_2048x27_2sub1 = {
  122305. 1, 128,
  122306. _huff_lengthlist_line_2048x27_2sub1,
  122307. 0, 0, 0, 0, 0,
  122308. NULL,
  122309. NULL,
  122310. NULL,
  122311. NULL,
  122312. 0
  122313. };
  122314. static long _huff_lengthlist_line_2048x27_3sub1[] = {
  122315. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  122316. 5, 5,
  122317. };
  122318. static static_codebook _huff_book_line_2048x27_3sub1 = {
  122319. 1, 18,
  122320. _huff_lengthlist_line_2048x27_3sub1,
  122321. 0, 0, 0, 0, 0,
  122322. NULL,
  122323. NULL,
  122324. NULL,
  122325. NULL,
  122326. 0
  122327. };
  122328. static long _huff_lengthlist_line_2048x27_3sub2[] = {
  122329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122330. 0, 0, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6,
  122331. 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7, 9, 9,11, 9,12,
  122332. 10,12,
  122333. };
  122334. static static_codebook _huff_book_line_2048x27_3sub2 = {
  122335. 1, 50,
  122336. _huff_lengthlist_line_2048x27_3sub2,
  122337. 0, 0, 0, 0, 0,
  122338. NULL,
  122339. NULL,
  122340. NULL,
  122341. NULL,
  122342. 0
  122343. };
  122344. static long _huff_lengthlist_line_2048x27_3sub3[] = {
  122345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122348. 0, 0, 3, 6, 3, 7, 3, 7, 5, 7, 7, 7, 7, 7, 6, 7,
  122349. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122350. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122351. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122352. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122353. };
  122354. static static_codebook _huff_book_line_2048x27_3sub3 = {
  122355. 1, 128,
  122356. _huff_lengthlist_line_2048x27_3sub3,
  122357. 0, 0, 0, 0, 0,
  122358. NULL,
  122359. NULL,
  122360. NULL,
  122361. NULL,
  122362. 0
  122363. };
  122364. static long _huff_lengthlist_line_2048x27_4sub1[] = {
  122365. 0, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4, 5, 4, 5, 4,
  122366. 4, 5,
  122367. };
  122368. static static_codebook _huff_book_line_2048x27_4sub1 = {
  122369. 1, 18,
  122370. _huff_lengthlist_line_2048x27_4sub1,
  122371. 0, 0, 0, 0, 0,
  122372. NULL,
  122373. NULL,
  122374. NULL,
  122375. NULL,
  122376. 0
  122377. };
  122378. static long _huff_lengthlist_line_2048x27_4sub2[] = {
  122379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122380. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 5, 6, 5, 6, 5, 7,
  122381. 6, 6, 6, 7, 7, 7, 8, 9, 9, 9,12,10,11,10,10,12,
  122382. 10,10,
  122383. };
  122384. static static_codebook _huff_book_line_2048x27_4sub2 = {
  122385. 1, 50,
  122386. _huff_lengthlist_line_2048x27_4sub2,
  122387. 0, 0, 0, 0, 0,
  122388. NULL,
  122389. NULL,
  122390. NULL,
  122391. NULL,
  122392. 0
  122393. };
  122394. static long _huff_lengthlist_line_2048x27_4sub3[] = {
  122395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122398. 0, 0, 3, 6, 5, 7, 5, 7, 7, 7, 7, 7, 5, 7, 5, 7,
  122399. 5, 7, 5, 7, 7, 7, 7, 7, 4, 7, 7, 7, 7, 7, 7, 7,
  122400. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122401. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122402. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  122403. };
  122404. static static_codebook _huff_book_line_2048x27_4sub3 = {
  122405. 1, 128,
  122406. _huff_lengthlist_line_2048x27_4sub3,
  122407. 0, 0, 0, 0, 0,
  122408. NULL,
  122409. NULL,
  122410. NULL,
  122411. NULL,
  122412. 0
  122413. };
  122414. static long _huff_lengthlist_line_256x4low_class0[] = {
  122415. 4, 5, 6,11, 5, 5, 6,10, 7, 7, 6, 6,14,13, 9, 9,
  122416. 6, 6, 6,10, 6, 6, 6, 9, 8, 7, 7, 9,14,12, 8,11,
  122417. 8, 7, 7,11, 8, 8, 7,11, 9, 9, 7, 9,13,11, 9,13,
  122418. 19,19,18,19,15,16,16,19,11,11,10,13,10,10, 9,15,
  122419. 5, 5, 6,13, 6, 6, 6,11, 8, 7, 6, 7,14,11,10,11,
  122420. 6, 6, 6,12, 7, 6, 6,11, 8, 7, 7,11,13,11, 9,11,
  122421. 9, 7, 6,12, 8, 7, 6,12, 9, 8, 8,11,13,10, 7,13,
  122422. 19,19,17,19,17,14,14,19,12,10, 8,12,13,10, 9,16,
  122423. 7, 8, 7,12, 7, 7, 7,11, 8, 7, 7, 8,12,12,11,11,
  122424. 8, 8, 7,12, 8, 7, 6,11, 8, 7, 7,10,10,11,10,11,
  122425. 9, 8, 8,13, 9, 8, 7,12,10, 9, 7,11, 9, 8, 7,11,
  122426. 18,18,15,18,18,16,17,18,15,11,10,18,11, 9, 9,18,
  122427. 16,16,13,16,12,11,10,16,12,11, 9, 6,15,12,11,13,
  122428. 16,16,14,14,13,11,12,16,12, 9, 9,13,13,10,10,12,
  122429. 17,18,17,17,14,15,14,16,14,12,14,15,12,10,11,12,
  122430. 18,18,18,18,18,18,18,18,18,12,13,18,16,11, 9,18,
  122431. };
  122432. static static_codebook _huff_book_line_256x4low_class0 = {
  122433. 1, 256,
  122434. _huff_lengthlist_line_256x4low_class0,
  122435. 0, 0, 0, 0, 0,
  122436. NULL,
  122437. NULL,
  122438. NULL,
  122439. NULL,
  122440. 0
  122441. };
  122442. static long _huff_lengthlist_line_256x4low_0sub0[] = {
  122443. 1, 3, 2, 3,
  122444. };
  122445. static static_codebook _huff_book_line_256x4low_0sub0 = {
  122446. 1, 4,
  122447. _huff_lengthlist_line_256x4low_0sub0,
  122448. 0, 0, 0, 0, 0,
  122449. NULL,
  122450. NULL,
  122451. NULL,
  122452. NULL,
  122453. 0
  122454. };
  122455. static long _huff_lengthlist_line_256x4low_0sub1[] = {
  122456. 0, 0, 0, 0, 2, 3, 2, 3, 3, 3,
  122457. };
  122458. static static_codebook _huff_book_line_256x4low_0sub1 = {
  122459. 1, 10,
  122460. _huff_lengthlist_line_256x4low_0sub1,
  122461. 0, 0, 0, 0, 0,
  122462. NULL,
  122463. NULL,
  122464. NULL,
  122465. NULL,
  122466. 0
  122467. };
  122468. static long _huff_lengthlist_line_256x4low_0sub2[] = {
  122469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 3, 4,
  122470. 4, 4, 4, 4, 5, 5, 5, 6, 6,
  122471. };
  122472. static static_codebook _huff_book_line_256x4low_0sub2 = {
  122473. 1, 25,
  122474. _huff_lengthlist_line_256x4low_0sub2,
  122475. 0, 0, 0, 0, 0,
  122476. NULL,
  122477. NULL,
  122478. NULL,
  122479. NULL,
  122480. 0
  122481. };
  122482. static long _huff_lengthlist_line_256x4low_0sub3[] = {
  122483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 2, 4, 3, 5, 4,
  122485. 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 7, 7, 8, 6, 9,
  122486. 7,12,11,16,13,16,12,15,13,15,12,14,12,15,15,15,
  122487. };
  122488. static static_codebook _huff_book_line_256x4low_0sub3 = {
  122489. 1, 64,
  122490. _huff_lengthlist_line_256x4low_0sub3,
  122491. 0, 0, 0, 0, 0,
  122492. NULL,
  122493. NULL,
  122494. NULL,
  122495. NULL,
  122496. 0
  122497. };
  122498. /*** End of inlined file: floor_books.h ***/
  122499. static static_codebook *_floor_128x4_books[]={
  122500. &_huff_book_line_128x4_class0,
  122501. &_huff_book_line_128x4_0sub0,
  122502. &_huff_book_line_128x4_0sub1,
  122503. &_huff_book_line_128x4_0sub2,
  122504. &_huff_book_line_128x4_0sub3,
  122505. };
  122506. static static_codebook *_floor_256x4_books[]={
  122507. &_huff_book_line_256x4_class0,
  122508. &_huff_book_line_256x4_0sub0,
  122509. &_huff_book_line_256x4_0sub1,
  122510. &_huff_book_line_256x4_0sub2,
  122511. &_huff_book_line_256x4_0sub3,
  122512. };
  122513. static static_codebook *_floor_128x7_books[]={
  122514. &_huff_book_line_128x7_class0,
  122515. &_huff_book_line_128x7_class1,
  122516. &_huff_book_line_128x7_0sub1,
  122517. &_huff_book_line_128x7_0sub2,
  122518. &_huff_book_line_128x7_0sub3,
  122519. &_huff_book_line_128x7_1sub1,
  122520. &_huff_book_line_128x7_1sub2,
  122521. &_huff_book_line_128x7_1sub3,
  122522. };
  122523. static static_codebook *_floor_256x7_books[]={
  122524. &_huff_book_line_256x7_class0,
  122525. &_huff_book_line_256x7_class1,
  122526. &_huff_book_line_256x7_0sub1,
  122527. &_huff_book_line_256x7_0sub2,
  122528. &_huff_book_line_256x7_0sub3,
  122529. &_huff_book_line_256x7_1sub1,
  122530. &_huff_book_line_256x7_1sub2,
  122531. &_huff_book_line_256x7_1sub3,
  122532. };
  122533. static static_codebook *_floor_128x11_books[]={
  122534. &_huff_book_line_128x11_class1,
  122535. &_huff_book_line_128x11_class2,
  122536. &_huff_book_line_128x11_class3,
  122537. &_huff_book_line_128x11_0sub0,
  122538. &_huff_book_line_128x11_1sub0,
  122539. &_huff_book_line_128x11_1sub1,
  122540. &_huff_book_line_128x11_2sub1,
  122541. &_huff_book_line_128x11_2sub2,
  122542. &_huff_book_line_128x11_2sub3,
  122543. &_huff_book_line_128x11_3sub1,
  122544. &_huff_book_line_128x11_3sub2,
  122545. &_huff_book_line_128x11_3sub3,
  122546. };
  122547. static static_codebook *_floor_128x17_books[]={
  122548. &_huff_book_line_128x17_class1,
  122549. &_huff_book_line_128x17_class2,
  122550. &_huff_book_line_128x17_class3,
  122551. &_huff_book_line_128x17_0sub0,
  122552. &_huff_book_line_128x17_1sub0,
  122553. &_huff_book_line_128x17_1sub1,
  122554. &_huff_book_line_128x17_2sub1,
  122555. &_huff_book_line_128x17_2sub2,
  122556. &_huff_book_line_128x17_2sub3,
  122557. &_huff_book_line_128x17_3sub1,
  122558. &_huff_book_line_128x17_3sub2,
  122559. &_huff_book_line_128x17_3sub3,
  122560. };
  122561. static static_codebook *_floor_256x4low_books[]={
  122562. &_huff_book_line_256x4low_class0,
  122563. &_huff_book_line_256x4low_0sub0,
  122564. &_huff_book_line_256x4low_0sub1,
  122565. &_huff_book_line_256x4low_0sub2,
  122566. &_huff_book_line_256x4low_0sub3,
  122567. };
  122568. static static_codebook *_floor_1024x27_books[]={
  122569. &_huff_book_line_1024x27_class1,
  122570. &_huff_book_line_1024x27_class2,
  122571. &_huff_book_line_1024x27_class3,
  122572. &_huff_book_line_1024x27_class4,
  122573. &_huff_book_line_1024x27_0sub0,
  122574. &_huff_book_line_1024x27_1sub0,
  122575. &_huff_book_line_1024x27_1sub1,
  122576. &_huff_book_line_1024x27_2sub0,
  122577. &_huff_book_line_1024x27_2sub1,
  122578. &_huff_book_line_1024x27_3sub1,
  122579. &_huff_book_line_1024x27_3sub2,
  122580. &_huff_book_line_1024x27_3sub3,
  122581. &_huff_book_line_1024x27_4sub1,
  122582. &_huff_book_line_1024x27_4sub2,
  122583. &_huff_book_line_1024x27_4sub3,
  122584. };
  122585. static static_codebook *_floor_2048x27_books[]={
  122586. &_huff_book_line_2048x27_class1,
  122587. &_huff_book_line_2048x27_class2,
  122588. &_huff_book_line_2048x27_class3,
  122589. &_huff_book_line_2048x27_class4,
  122590. &_huff_book_line_2048x27_0sub0,
  122591. &_huff_book_line_2048x27_1sub0,
  122592. &_huff_book_line_2048x27_1sub1,
  122593. &_huff_book_line_2048x27_2sub0,
  122594. &_huff_book_line_2048x27_2sub1,
  122595. &_huff_book_line_2048x27_3sub1,
  122596. &_huff_book_line_2048x27_3sub2,
  122597. &_huff_book_line_2048x27_3sub3,
  122598. &_huff_book_line_2048x27_4sub1,
  122599. &_huff_book_line_2048x27_4sub2,
  122600. &_huff_book_line_2048x27_4sub3,
  122601. };
  122602. static static_codebook *_floor_512x17_books[]={
  122603. &_huff_book_line_512x17_class1,
  122604. &_huff_book_line_512x17_class2,
  122605. &_huff_book_line_512x17_class3,
  122606. &_huff_book_line_512x17_0sub0,
  122607. &_huff_book_line_512x17_1sub0,
  122608. &_huff_book_line_512x17_1sub1,
  122609. &_huff_book_line_512x17_2sub1,
  122610. &_huff_book_line_512x17_2sub2,
  122611. &_huff_book_line_512x17_2sub3,
  122612. &_huff_book_line_512x17_3sub1,
  122613. &_huff_book_line_512x17_3sub2,
  122614. &_huff_book_line_512x17_3sub3,
  122615. };
  122616. static static_codebook **_floor_books[10]={
  122617. _floor_128x4_books,
  122618. _floor_256x4_books,
  122619. _floor_128x7_books,
  122620. _floor_256x7_books,
  122621. _floor_128x11_books,
  122622. _floor_128x17_books,
  122623. _floor_256x4low_books,
  122624. _floor_1024x27_books,
  122625. _floor_2048x27_books,
  122626. _floor_512x17_books,
  122627. };
  122628. static vorbis_info_floor1 _floor[10]={
  122629. /* 128 x 4 */
  122630. {
  122631. 1,{0},{4},{2},{0},
  122632. {{1,2,3,4}},
  122633. 4,{0,128, 33,8,16,70},
  122634. 60,30,500, 1.,18., -1
  122635. },
  122636. /* 256 x 4 */
  122637. {
  122638. 1,{0},{4},{2},{0},
  122639. {{1,2,3,4}},
  122640. 4,{0,256, 66,16,32,140},
  122641. 60,30,500, 1.,18., -1
  122642. },
  122643. /* 128 x 7 */
  122644. {
  122645. 2,{0,1},{3,4},{2,2},{0,1},
  122646. {{-1,2,3,4},{-1,5,6,7}},
  122647. 4,{0,128, 14,4,58, 2,8,28,90},
  122648. 60,30,500, 1.,18., -1
  122649. },
  122650. /* 256 x 7 */
  122651. {
  122652. 2,{0,1},{3,4},{2,2},{0,1},
  122653. {{-1,2,3,4},{-1,5,6,7}},
  122654. 4,{0,256, 28,8,116, 4,16,56,180},
  122655. 60,30,500, 1.,18., -1
  122656. },
  122657. /* 128 x 11 */
  122658. {
  122659. 4,{0,1,2,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122660. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122661. 2,{0,128, 8,33, 4,16,70, 2,6,12, 23,46,90},
  122662. 60,30,500, 1,18., -1
  122663. },
  122664. /* 128 x 17 */
  122665. {
  122666. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122667. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122668. 2,{0,128, 12,46, 4,8,16, 23,33,70, 2,6,10, 14,19,28, 39,58,90},
  122669. 60,30,500, 1,18., -1
  122670. },
  122671. /* 256 x 4 (low bitrate version) */
  122672. {
  122673. 1,{0},{4},{2},{0},
  122674. {{1,2,3,4}},
  122675. 4,{0,256, 66,16,32,140},
  122676. 60,30,500, 1.,18., -1
  122677. },
  122678. /* 1024 x 27 */
  122679. {
  122680. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  122681. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  122682. 2,{0,1024, 93,23,372, 6,46,186,750, 14,33,65, 130,260,556,
  122683. 3,10,18,28, 39,55,79,111, 158,220,312, 464,650,850},
  122684. 60,30,500, 3,18., -1 /* lowpass */
  122685. },
  122686. /* 2048 x 27 */
  122687. {
  122688. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  122689. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  122690. 2,{0,2048, 186,46,744, 12,92,372,1500, 28,66,130, 260,520,1112,
  122691. 6,20,36,56, 78,110,158,222, 316,440,624, 928,1300,1700},
  122692. 60,30,500, 3,18., -1 /* lowpass */
  122693. },
  122694. /* 512 x 17 */
  122695. {
  122696. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122697. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122698. 2,{0,512, 46,186, 16,33,65, 93,130,278,
  122699. 7,23,39, 55,79,110, 156,232,360},
  122700. 60,30,500, 1,18., -1 /* lowpass! */
  122701. },
  122702. };
  122703. /*** End of inlined file: floor_all.h ***/
  122704. /*** Start of inlined file: residue_44.h ***/
  122705. /*** Start of inlined file: res_books_stereo.h ***/
  122706. static long _vq_quantlist__16c0_s_p1_0[] = {
  122707. 1,
  122708. 0,
  122709. 2,
  122710. };
  122711. static long _vq_lengthlist__16c0_s_p1_0[] = {
  122712. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  122713. 0, 0, 5, 7, 7, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0,
  122718. 0, 0, 0, 7, 9,10, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  122723. 0, 0, 0, 0, 7, 9, 9, 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, 5, 8, 8, 0, 0, 0, 0,
  122758. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8,10,10, 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, 7,10,10, 0, 0, 0,
  122763. 0, 0, 0, 9, 9,12, 0, 0, 0, 0, 0, 0,10,12,11, 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, 7,10,10, 0, 0,
  122768. 0, 0, 0, 0, 9,12,10, 0, 0, 0, 0, 0, 0,10,11,12,
  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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  122804. 0, 0, 0, 0, 8,10,10, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  122809. 0, 0, 0, 0, 0, 9,10,12, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,12,
  122814. 0, 0, 0, 0, 0, 0, 9,12, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123122. 0,
  123123. };
  123124. static float _vq_quantthresh__16c0_s_p1_0[] = {
  123125. -0.5, 0.5,
  123126. };
  123127. static long _vq_quantmap__16c0_s_p1_0[] = {
  123128. 1, 0, 2,
  123129. };
  123130. static encode_aux_threshmatch _vq_auxt__16c0_s_p1_0 = {
  123131. _vq_quantthresh__16c0_s_p1_0,
  123132. _vq_quantmap__16c0_s_p1_0,
  123133. 3,
  123134. 3
  123135. };
  123136. static static_codebook _16c0_s_p1_0 = {
  123137. 8, 6561,
  123138. _vq_lengthlist__16c0_s_p1_0,
  123139. 1, -535822336, 1611661312, 2, 0,
  123140. _vq_quantlist__16c0_s_p1_0,
  123141. NULL,
  123142. &_vq_auxt__16c0_s_p1_0,
  123143. NULL,
  123144. 0
  123145. };
  123146. static long _vq_quantlist__16c0_s_p2_0[] = {
  123147. 2,
  123148. 1,
  123149. 3,
  123150. 0,
  123151. 4,
  123152. };
  123153. static long _vq_lengthlist__16c0_s_p2_0[] = {
  123154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123193. 0,
  123194. };
  123195. static float _vq_quantthresh__16c0_s_p2_0[] = {
  123196. -1.5, -0.5, 0.5, 1.5,
  123197. };
  123198. static long _vq_quantmap__16c0_s_p2_0[] = {
  123199. 3, 1, 0, 2, 4,
  123200. };
  123201. static encode_aux_threshmatch _vq_auxt__16c0_s_p2_0 = {
  123202. _vq_quantthresh__16c0_s_p2_0,
  123203. _vq_quantmap__16c0_s_p2_0,
  123204. 5,
  123205. 5
  123206. };
  123207. static static_codebook _16c0_s_p2_0 = {
  123208. 4, 625,
  123209. _vq_lengthlist__16c0_s_p2_0,
  123210. 1, -533725184, 1611661312, 3, 0,
  123211. _vq_quantlist__16c0_s_p2_0,
  123212. NULL,
  123213. &_vq_auxt__16c0_s_p2_0,
  123214. NULL,
  123215. 0
  123216. };
  123217. static long _vq_quantlist__16c0_s_p3_0[] = {
  123218. 2,
  123219. 1,
  123220. 3,
  123221. 0,
  123222. 4,
  123223. };
  123224. static long _vq_lengthlist__16c0_s_p3_0[] = {
  123225. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 7, 6, 0, 0,
  123227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123228. 0, 0, 4, 6, 6, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  123230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123231. 0, 0, 0, 0, 6, 6, 6, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  123232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123264. 0,
  123265. };
  123266. static float _vq_quantthresh__16c0_s_p3_0[] = {
  123267. -1.5, -0.5, 0.5, 1.5,
  123268. };
  123269. static long _vq_quantmap__16c0_s_p3_0[] = {
  123270. 3, 1, 0, 2, 4,
  123271. };
  123272. static encode_aux_threshmatch _vq_auxt__16c0_s_p3_0 = {
  123273. _vq_quantthresh__16c0_s_p3_0,
  123274. _vq_quantmap__16c0_s_p3_0,
  123275. 5,
  123276. 5
  123277. };
  123278. static static_codebook _16c0_s_p3_0 = {
  123279. 4, 625,
  123280. _vq_lengthlist__16c0_s_p3_0,
  123281. 1, -533725184, 1611661312, 3, 0,
  123282. _vq_quantlist__16c0_s_p3_0,
  123283. NULL,
  123284. &_vq_auxt__16c0_s_p3_0,
  123285. NULL,
  123286. 0
  123287. };
  123288. static long _vq_quantlist__16c0_s_p4_0[] = {
  123289. 4,
  123290. 3,
  123291. 5,
  123292. 2,
  123293. 6,
  123294. 1,
  123295. 7,
  123296. 0,
  123297. 8,
  123298. };
  123299. static long _vq_lengthlist__16c0_s_p4_0[] = {
  123300. 1, 3, 2, 7, 8, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  123301. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  123302. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  123303. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  123304. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123305. 0,
  123306. };
  123307. static float _vq_quantthresh__16c0_s_p4_0[] = {
  123308. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123309. };
  123310. static long _vq_quantmap__16c0_s_p4_0[] = {
  123311. 7, 5, 3, 1, 0, 2, 4, 6,
  123312. 8,
  123313. };
  123314. static encode_aux_threshmatch _vq_auxt__16c0_s_p4_0 = {
  123315. _vq_quantthresh__16c0_s_p4_0,
  123316. _vq_quantmap__16c0_s_p4_0,
  123317. 9,
  123318. 9
  123319. };
  123320. static static_codebook _16c0_s_p4_0 = {
  123321. 2, 81,
  123322. _vq_lengthlist__16c0_s_p4_0,
  123323. 1, -531628032, 1611661312, 4, 0,
  123324. _vq_quantlist__16c0_s_p4_0,
  123325. NULL,
  123326. &_vq_auxt__16c0_s_p4_0,
  123327. NULL,
  123328. 0
  123329. };
  123330. static long _vq_quantlist__16c0_s_p5_0[] = {
  123331. 4,
  123332. 3,
  123333. 5,
  123334. 2,
  123335. 6,
  123336. 1,
  123337. 7,
  123338. 0,
  123339. 8,
  123340. };
  123341. static long _vq_lengthlist__16c0_s_p5_0[] = {
  123342. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  123343. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 8, 0, 0, 0, 7, 7,
  123344. 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0, 0, 0,
  123345. 8, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  123346. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  123347. 10,
  123348. };
  123349. static float _vq_quantthresh__16c0_s_p5_0[] = {
  123350. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123351. };
  123352. static long _vq_quantmap__16c0_s_p5_0[] = {
  123353. 7, 5, 3, 1, 0, 2, 4, 6,
  123354. 8,
  123355. };
  123356. static encode_aux_threshmatch _vq_auxt__16c0_s_p5_0 = {
  123357. _vq_quantthresh__16c0_s_p5_0,
  123358. _vq_quantmap__16c0_s_p5_0,
  123359. 9,
  123360. 9
  123361. };
  123362. static static_codebook _16c0_s_p5_0 = {
  123363. 2, 81,
  123364. _vq_lengthlist__16c0_s_p5_0,
  123365. 1, -531628032, 1611661312, 4, 0,
  123366. _vq_quantlist__16c0_s_p5_0,
  123367. NULL,
  123368. &_vq_auxt__16c0_s_p5_0,
  123369. NULL,
  123370. 0
  123371. };
  123372. static long _vq_quantlist__16c0_s_p6_0[] = {
  123373. 8,
  123374. 7,
  123375. 9,
  123376. 6,
  123377. 10,
  123378. 5,
  123379. 11,
  123380. 4,
  123381. 12,
  123382. 3,
  123383. 13,
  123384. 2,
  123385. 14,
  123386. 1,
  123387. 15,
  123388. 0,
  123389. 16,
  123390. };
  123391. static long _vq_lengthlist__16c0_s_p6_0[] = {
  123392. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  123393. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  123394. 11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  123395. 11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  123396. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  123397. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  123398. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  123399. 10,11,11,12,12,12,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  123400. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10,10,10,
  123401. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  123402. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  123403. 9,10,10,11,11,12,12,13,13,13,14, 0, 0, 0, 0, 0,
  123404. 10,10,10,11,11,11,12,12,13,13,13,14, 0, 0, 0, 0,
  123405. 0, 0, 0,10,10,11,11,12,12,13,13,14,14, 0, 0, 0,
  123406. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  123407. 0, 0, 0, 0, 0,11,11,12,12,12,13,13,14,15,14, 0,
  123408. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,14,14,15,
  123409. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,13,14,
  123410. 14,
  123411. };
  123412. static float _vq_quantthresh__16c0_s_p6_0[] = {
  123413. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  123414. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  123415. };
  123416. static long _vq_quantmap__16c0_s_p6_0[] = {
  123417. 15, 13, 11, 9, 7, 5, 3, 1,
  123418. 0, 2, 4, 6, 8, 10, 12, 14,
  123419. 16,
  123420. };
  123421. static encode_aux_threshmatch _vq_auxt__16c0_s_p6_0 = {
  123422. _vq_quantthresh__16c0_s_p6_0,
  123423. _vq_quantmap__16c0_s_p6_0,
  123424. 17,
  123425. 17
  123426. };
  123427. static static_codebook _16c0_s_p6_0 = {
  123428. 2, 289,
  123429. _vq_lengthlist__16c0_s_p6_0,
  123430. 1, -529530880, 1611661312, 5, 0,
  123431. _vq_quantlist__16c0_s_p6_0,
  123432. NULL,
  123433. &_vq_auxt__16c0_s_p6_0,
  123434. NULL,
  123435. 0
  123436. };
  123437. static long _vq_quantlist__16c0_s_p7_0[] = {
  123438. 1,
  123439. 0,
  123440. 2,
  123441. };
  123442. static long _vq_lengthlist__16c0_s_p7_0[] = {
  123443. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,11,10,10,11,
  123444. 11,10, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  123445. 11,11,11,10, 6, 9, 9,11,12,12,11, 9, 9, 6, 9,10,
  123446. 11,12,12,11, 9,10, 7,11,11,11,11,11,12,13,12, 6,
  123447. 9,10,11,10,10,12,13,13, 6,10, 9,11,10,10,11,12,
  123448. 13,
  123449. };
  123450. static float _vq_quantthresh__16c0_s_p7_0[] = {
  123451. -5.5, 5.5,
  123452. };
  123453. static long _vq_quantmap__16c0_s_p7_0[] = {
  123454. 1, 0, 2,
  123455. };
  123456. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_0 = {
  123457. _vq_quantthresh__16c0_s_p7_0,
  123458. _vq_quantmap__16c0_s_p7_0,
  123459. 3,
  123460. 3
  123461. };
  123462. static static_codebook _16c0_s_p7_0 = {
  123463. 4, 81,
  123464. _vq_lengthlist__16c0_s_p7_0,
  123465. 1, -529137664, 1618345984, 2, 0,
  123466. _vq_quantlist__16c0_s_p7_0,
  123467. NULL,
  123468. &_vq_auxt__16c0_s_p7_0,
  123469. NULL,
  123470. 0
  123471. };
  123472. static long _vq_quantlist__16c0_s_p7_1[] = {
  123473. 5,
  123474. 4,
  123475. 6,
  123476. 3,
  123477. 7,
  123478. 2,
  123479. 8,
  123480. 1,
  123481. 9,
  123482. 0,
  123483. 10,
  123484. };
  123485. static long _vq_lengthlist__16c0_s_p7_1[] = {
  123486. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7,
  123487. 8, 8, 8, 9, 9, 9,10,10,10, 6, 7, 8, 8, 8, 8, 9,
  123488. 8,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10, 7,
  123489. 7, 8, 8, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9, 9,
  123490. 9, 9,11,11,11, 8, 8, 9, 9, 9, 9, 9,10,10,11,11,
  123491. 9, 9, 9, 9, 9, 9, 9,10,11,11,11,10,11, 9, 9, 9,
  123492. 9,10, 9,11,11,11,10,11,10,10, 9, 9,10,10,11,11,
  123493. 11,11,11, 9, 9, 9, 9,10,10,
  123494. };
  123495. static float _vq_quantthresh__16c0_s_p7_1[] = {
  123496. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  123497. 3.5, 4.5,
  123498. };
  123499. static long _vq_quantmap__16c0_s_p7_1[] = {
  123500. 9, 7, 5, 3, 1, 0, 2, 4,
  123501. 6, 8, 10,
  123502. };
  123503. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_1 = {
  123504. _vq_quantthresh__16c0_s_p7_1,
  123505. _vq_quantmap__16c0_s_p7_1,
  123506. 11,
  123507. 11
  123508. };
  123509. static static_codebook _16c0_s_p7_1 = {
  123510. 2, 121,
  123511. _vq_lengthlist__16c0_s_p7_1,
  123512. 1, -531365888, 1611661312, 4, 0,
  123513. _vq_quantlist__16c0_s_p7_1,
  123514. NULL,
  123515. &_vq_auxt__16c0_s_p7_1,
  123516. NULL,
  123517. 0
  123518. };
  123519. static long _vq_quantlist__16c0_s_p8_0[] = {
  123520. 6,
  123521. 5,
  123522. 7,
  123523. 4,
  123524. 8,
  123525. 3,
  123526. 9,
  123527. 2,
  123528. 10,
  123529. 1,
  123530. 11,
  123531. 0,
  123532. 12,
  123533. };
  123534. static long _vq_lengthlist__16c0_s_p8_0[] = {
  123535. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8,10,10, 6, 5, 6,
  123536. 8, 8, 8, 8, 8, 8, 8, 9,10,10, 7, 6, 6, 8, 8, 8,
  123537. 8, 8, 8, 8, 8,10,10, 0, 8, 8, 8, 8, 9, 8, 9, 9,
  123538. 9,10,10,10, 0, 9, 8, 8, 8, 9, 9, 8, 8, 9, 9,10,
  123539. 10, 0,12,11, 8, 8, 9, 9, 9, 9,10,10,11,10, 0,12,
  123540. 13, 8, 8, 9,10, 9, 9,11,11,11,12, 0, 0, 0, 8, 8,
  123541. 8, 8,10, 9,12,13,12,14, 0, 0, 0, 8, 8, 8, 9,10,
  123542. 10,12,12,13,14, 0, 0, 0,13,13, 9, 9,11,11, 0, 0,
  123543. 14, 0, 0, 0, 0,14,14,10,10,12,11,12,14,14,14, 0,
  123544. 0, 0, 0, 0,11,11,13,13,14,13,14,14, 0, 0, 0, 0,
  123545. 0,12,13,13,12,13,14,14,14,
  123546. };
  123547. static float _vq_quantthresh__16c0_s_p8_0[] = {
  123548. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  123549. 12.5, 17.5, 22.5, 27.5,
  123550. };
  123551. static long _vq_quantmap__16c0_s_p8_0[] = {
  123552. 11, 9, 7, 5, 3, 1, 0, 2,
  123553. 4, 6, 8, 10, 12,
  123554. };
  123555. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_0 = {
  123556. _vq_quantthresh__16c0_s_p8_0,
  123557. _vq_quantmap__16c0_s_p8_0,
  123558. 13,
  123559. 13
  123560. };
  123561. static static_codebook _16c0_s_p8_0 = {
  123562. 2, 169,
  123563. _vq_lengthlist__16c0_s_p8_0,
  123564. 1, -526516224, 1616117760, 4, 0,
  123565. _vq_quantlist__16c0_s_p8_0,
  123566. NULL,
  123567. &_vq_auxt__16c0_s_p8_0,
  123568. NULL,
  123569. 0
  123570. };
  123571. static long _vq_quantlist__16c0_s_p8_1[] = {
  123572. 2,
  123573. 1,
  123574. 3,
  123575. 0,
  123576. 4,
  123577. };
  123578. static long _vq_lengthlist__16c0_s_p8_1[] = {
  123579. 1, 4, 3, 5, 5, 7, 7, 7, 6, 6, 7, 7, 7, 5, 5, 7,
  123580. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  123581. };
  123582. static float _vq_quantthresh__16c0_s_p8_1[] = {
  123583. -1.5, -0.5, 0.5, 1.5,
  123584. };
  123585. static long _vq_quantmap__16c0_s_p8_1[] = {
  123586. 3, 1, 0, 2, 4,
  123587. };
  123588. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_1 = {
  123589. _vq_quantthresh__16c0_s_p8_1,
  123590. _vq_quantmap__16c0_s_p8_1,
  123591. 5,
  123592. 5
  123593. };
  123594. static static_codebook _16c0_s_p8_1 = {
  123595. 2, 25,
  123596. _vq_lengthlist__16c0_s_p8_1,
  123597. 1, -533725184, 1611661312, 3, 0,
  123598. _vq_quantlist__16c0_s_p8_1,
  123599. NULL,
  123600. &_vq_auxt__16c0_s_p8_1,
  123601. NULL,
  123602. 0
  123603. };
  123604. static long _vq_quantlist__16c0_s_p9_0[] = {
  123605. 1,
  123606. 0,
  123607. 2,
  123608. };
  123609. static long _vq_lengthlist__16c0_s_p9_0[] = {
  123610. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123611. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123612. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123613. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123614. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123615. 7,
  123616. };
  123617. static float _vq_quantthresh__16c0_s_p9_0[] = {
  123618. -157.5, 157.5,
  123619. };
  123620. static long _vq_quantmap__16c0_s_p9_0[] = {
  123621. 1, 0, 2,
  123622. };
  123623. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_0 = {
  123624. _vq_quantthresh__16c0_s_p9_0,
  123625. _vq_quantmap__16c0_s_p9_0,
  123626. 3,
  123627. 3
  123628. };
  123629. static static_codebook _16c0_s_p9_0 = {
  123630. 4, 81,
  123631. _vq_lengthlist__16c0_s_p9_0,
  123632. 1, -518803456, 1628680192, 2, 0,
  123633. _vq_quantlist__16c0_s_p9_0,
  123634. NULL,
  123635. &_vq_auxt__16c0_s_p9_0,
  123636. NULL,
  123637. 0
  123638. };
  123639. static long _vq_quantlist__16c0_s_p9_1[] = {
  123640. 7,
  123641. 6,
  123642. 8,
  123643. 5,
  123644. 9,
  123645. 4,
  123646. 10,
  123647. 3,
  123648. 11,
  123649. 2,
  123650. 12,
  123651. 1,
  123652. 13,
  123653. 0,
  123654. 14,
  123655. };
  123656. static long _vq_lengthlist__16c0_s_p9_1[] = {
  123657. 1, 5, 5, 5, 5, 9,11,11,10,10,10,10,10,10,10, 7,
  123658. 6, 6, 6, 6,10,10,10,10,10,10,10,10,10,10, 7, 6,
  123659. 6, 6, 6,10, 9,10,10,10,10,10,10,10,10,10, 7, 7,
  123660. 8, 9,10,10,10,10,10,10,10,10,10,10,10, 8, 7,10,
  123661. 10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123662. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123663. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123664. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123665. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123666. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123667. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123668. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123669. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123670. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123671. 10,
  123672. };
  123673. static float _vq_quantthresh__16c0_s_p9_1[] = {
  123674. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  123675. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  123676. };
  123677. static long _vq_quantmap__16c0_s_p9_1[] = {
  123678. 13, 11, 9, 7, 5, 3, 1, 0,
  123679. 2, 4, 6, 8, 10, 12, 14,
  123680. };
  123681. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_1 = {
  123682. _vq_quantthresh__16c0_s_p9_1,
  123683. _vq_quantmap__16c0_s_p9_1,
  123684. 15,
  123685. 15
  123686. };
  123687. static static_codebook _16c0_s_p9_1 = {
  123688. 2, 225,
  123689. _vq_lengthlist__16c0_s_p9_1,
  123690. 1, -520986624, 1620377600, 4, 0,
  123691. _vq_quantlist__16c0_s_p9_1,
  123692. NULL,
  123693. &_vq_auxt__16c0_s_p9_1,
  123694. NULL,
  123695. 0
  123696. };
  123697. static long _vq_quantlist__16c0_s_p9_2[] = {
  123698. 10,
  123699. 9,
  123700. 11,
  123701. 8,
  123702. 12,
  123703. 7,
  123704. 13,
  123705. 6,
  123706. 14,
  123707. 5,
  123708. 15,
  123709. 4,
  123710. 16,
  123711. 3,
  123712. 17,
  123713. 2,
  123714. 18,
  123715. 1,
  123716. 19,
  123717. 0,
  123718. 20,
  123719. };
  123720. static long _vq_lengthlist__16c0_s_p9_2[] = {
  123721. 1, 5, 5, 7, 8, 8, 7, 9, 9, 9,12,12,11,12,12,10,
  123722. 10,11,12,12,12,11,12,12, 8, 9, 8, 7, 9,10,10,11,
  123723. 11,10,11,12,10,12,10,12,12,12,11,12,11, 9, 8, 8,
  123724. 9,10, 9, 8, 9,10,12,12,11,11,12,11,10,11,12,11,
  123725. 12,12, 8, 9, 9, 9,10,11,12,11,12,11,11,11,11,12,
  123726. 12,11,11,12,12,11,11, 9, 9, 8, 9, 9,11, 9, 9,10,
  123727. 9,11,11,11,11,12,11,11,10,12,12,12, 9,12,11,10,
  123728. 11,11,11,11,12,12,12,11,11,11,12,10,12,12,12,10,
  123729. 10, 9,10, 9,10,10, 9, 9, 9,10,10,12,10,11,11, 9,
  123730. 11,11,10,11,11,11,10,10,10, 9, 9,10,10, 9, 9,10,
  123731. 11,11,10,11,10,11,10,11,11,10,11,11,11,10, 9,10,
  123732. 10, 9,10, 9, 9,11, 9, 9,11,10,10,11,11,10,10,11,
  123733. 10,11, 8, 9,11,11,10, 9,10,11,11,10,11,11,10,10,
  123734. 10,11,10, 9,10,10,11, 9,10,10, 9,11,10,10,10,10,
  123735. 11,10,11,11, 9,11,10,11,10,10,11,11,10,10,10, 9,
  123736. 10,10,11,11,11, 9,10,10,10,10,10,11,10,10,10, 9,
  123737. 10,10,11,10,10,10,10,10, 9,10,11,10,10,10,10,11,
  123738. 11,11,10,10,10,10,10,11,10,11,10,11,10,10,10, 9,
  123739. 11,11,10,10,10,11,11,10,10,10,10,10,10,10,10,11,
  123740. 11, 9,10,10,10,11,10,11,10,10,10,11, 9,10,11,10,
  123741. 11,10,10, 9,10,10,10,11,10,11,10,10,10,10,10,11,
  123742. 11,10,11,11,10,10,11,11,10, 9, 9,10,10,10,10,10,
  123743. 9,11, 9,10,10,10,11,11,10,10,10,10,11,11,11,10,
  123744. 9, 9,10,10,11,10,10,10,10,10,11,11,11,10,10,10,
  123745. 11,11,11, 9,10,10,10,10, 9,10, 9,10,11,10,11,10,
  123746. 10,11,11,10,11,11,11,11,11,10,11,10,10,10, 9,11,
  123747. 11,10,11,11,11,11,11,11,11,11,11,10,11,10,10,10,
  123748. 10,11,10,10,11, 9,10,10,10,
  123749. };
  123750. static float _vq_quantthresh__16c0_s_p9_2[] = {
  123751. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  123752. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  123753. 6.5, 7.5, 8.5, 9.5,
  123754. };
  123755. static long _vq_quantmap__16c0_s_p9_2[] = {
  123756. 19, 17, 15, 13, 11, 9, 7, 5,
  123757. 3, 1, 0, 2, 4, 6, 8, 10,
  123758. 12, 14, 16, 18, 20,
  123759. };
  123760. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_2 = {
  123761. _vq_quantthresh__16c0_s_p9_2,
  123762. _vq_quantmap__16c0_s_p9_2,
  123763. 21,
  123764. 21
  123765. };
  123766. static static_codebook _16c0_s_p9_2 = {
  123767. 2, 441,
  123768. _vq_lengthlist__16c0_s_p9_2,
  123769. 1, -529268736, 1611661312, 5, 0,
  123770. _vq_quantlist__16c0_s_p9_2,
  123771. NULL,
  123772. &_vq_auxt__16c0_s_p9_2,
  123773. NULL,
  123774. 0
  123775. };
  123776. static long _huff_lengthlist__16c0_s_single[] = {
  123777. 3, 4,19, 7, 9, 7, 8,11, 9,12, 4, 1,19, 6, 7, 7,
  123778. 8,10,11,13,18,18,18,18,18,18,18,18,18,18, 8, 6,
  123779. 18, 8, 9, 9,11,12,14,18, 9, 6,18, 9, 7, 8, 9,11,
  123780. 12,18, 7, 6,18, 8, 7, 7, 7, 9,11,17, 8, 8,18, 9,
  123781. 7, 6, 6, 8,11,17,10,10,18,12, 9, 8, 7, 9,12,18,
  123782. 13,15,18,15,13,11,10,11,15,18,14,18,18,18,18,18,
  123783. 16,16,18,18,
  123784. };
  123785. static static_codebook _huff_book__16c0_s_single = {
  123786. 2, 100,
  123787. _huff_lengthlist__16c0_s_single,
  123788. 0, 0, 0, 0, 0,
  123789. NULL,
  123790. NULL,
  123791. NULL,
  123792. NULL,
  123793. 0
  123794. };
  123795. static long _huff_lengthlist__16c1_s_long[] = {
  123796. 2, 5,20, 7,10, 7, 8,10,11,11, 4, 2,20, 5, 8, 6,
  123797. 7, 9,10,10,20,20,20,20,19,19,19,19,19,19, 7, 5,
  123798. 19, 6,10, 7, 9,11,13,17,11, 8,19,10, 7, 7, 8,10,
  123799. 11,15, 7, 5,19, 7, 7, 5, 6, 9,11,16, 7, 6,19, 8,
  123800. 7, 6, 6, 7, 9,13, 9, 9,19,11, 9, 8, 6, 7, 8,13,
  123801. 12,14,19,16,13,10, 9, 8, 9,13,14,17,19,18,18,17,
  123802. 12,11,11,13,
  123803. };
  123804. static static_codebook _huff_book__16c1_s_long = {
  123805. 2, 100,
  123806. _huff_lengthlist__16c1_s_long,
  123807. 0, 0, 0, 0, 0,
  123808. NULL,
  123809. NULL,
  123810. NULL,
  123811. NULL,
  123812. 0
  123813. };
  123814. static long _vq_quantlist__16c1_s_p1_0[] = {
  123815. 1,
  123816. 0,
  123817. 2,
  123818. };
  123819. static long _vq_lengthlist__16c1_s_p1_0[] = {
  123820. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  123821. 0, 0, 5, 7, 7, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  123826. 0, 0, 0, 7, 8, 9, 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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  123831. 0, 0, 0, 0, 7, 9, 9, 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, 5, 8, 7, 0, 0, 0, 0,
  123866. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  123871. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 9,11,10, 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, 7, 9, 9, 0, 0,
  123876. 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  123912. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  123917. 0, 0, 0, 0, 0, 8, 9,11, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  123922. 0, 0, 0, 0, 0, 0, 9,11, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124071. 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124079. 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124230. 0,
  124231. };
  124232. static float _vq_quantthresh__16c1_s_p1_0[] = {
  124233. -0.5, 0.5,
  124234. };
  124235. static long _vq_quantmap__16c1_s_p1_0[] = {
  124236. 1, 0, 2,
  124237. };
  124238. static encode_aux_threshmatch _vq_auxt__16c1_s_p1_0 = {
  124239. _vq_quantthresh__16c1_s_p1_0,
  124240. _vq_quantmap__16c1_s_p1_0,
  124241. 3,
  124242. 3
  124243. };
  124244. static static_codebook _16c1_s_p1_0 = {
  124245. 8, 6561,
  124246. _vq_lengthlist__16c1_s_p1_0,
  124247. 1, -535822336, 1611661312, 2, 0,
  124248. _vq_quantlist__16c1_s_p1_0,
  124249. NULL,
  124250. &_vq_auxt__16c1_s_p1_0,
  124251. NULL,
  124252. 0
  124253. };
  124254. static long _vq_quantlist__16c1_s_p2_0[] = {
  124255. 2,
  124256. 1,
  124257. 3,
  124258. 0,
  124259. 4,
  124260. };
  124261. static long _vq_lengthlist__16c1_s_p2_0[] = {
  124262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124301. 0,
  124302. };
  124303. static float _vq_quantthresh__16c1_s_p2_0[] = {
  124304. -1.5, -0.5, 0.5, 1.5,
  124305. };
  124306. static long _vq_quantmap__16c1_s_p2_0[] = {
  124307. 3, 1, 0, 2, 4,
  124308. };
  124309. static encode_aux_threshmatch _vq_auxt__16c1_s_p2_0 = {
  124310. _vq_quantthresh__16c1_s_p2_0,
  124311. _vq_quantmap__16c1_s_p2_0,
  124312. 5,
  124313. 5
  124314. };
  124315. static static_codebook _16c1_s_p2_0 = {
  124316. 4, 625,
  124317. _vq_lengthlist__16c1_s_p2_0,
  124318. 1, -533725184, 1611661312, 3, 0,
  124319. _vq_quantlist__16c1_s_p2_0,
  124320. NULL,
  124321. &_vq_auxt__16c1_s_p2_0,
  124322. NULL,
  124323. 0
  124324. };
  124325. static long _vq_quantlist__16c1_s_p3_0[] = {
  124326. 2,
  124327. 1,
  124328. 3,
  124329. 0,
  124330. 4,
  124331. };
  124332. static long _vq_lengthlist__16c1_s_p3_0[] = {
  124333. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  124335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124336. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 7, 9, 9,
  124338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124339. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  124340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124372. 0,
  124373. };
  124374. static float _vq_quantthresh__16c1_s_p3_0[] = {
  124375. -1.5, -0.5, 0.5, 1.5,
  124376. };
  124377. static long _vq_quantmap__16c1_s_p3_0[] = {
  124378. 3, 1, 0, 2, 4,
  124379. };
  124380. static encode_aux_threshmatch _vq_auxt__16c1_s_p3_0 = {
  124381. _vq_quantthresh__16c1_s_p3_0,
  124382. _vq_quantmap__16c1_s_p3_0,
  124383. 5,
  124384. 5
  124385. };
  124386. static static_codebook _16c1_s_p3_0 = {
  124387. 4, 625,
  124388. _vq_lengthlist__16c1_s_p3_0,
  124389. 1, -533725184, 1611661312, 3, 0,
  124390. _vq_quantlist__16c1_s_p3_0,
  124391. NULL,
  124392. &_vq_auxt__16c1_s_p3_0,
  124393. NULL,
  124394. 0
  124395. };
  124396. static long _vq_quantlist__16c1_s_p4_0[] = {
  124397. 4,
  124398. 3,
  124399. 5,
  124400. 2,
  124401. 6,
  124402. 1,
  124403. 7,
  124404. 0,
  124405. 8,
  124406. };
  124407. static long _vq_lengthlist__16c1_s_p4_0[] = {
  124408. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  124409. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  124410. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  124411. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 9, 0, 0, 0, 0, 0,
  124412. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124413. 0,
  124414. };
  124415. static float _vq_quantthresh__16c1_s_p4_0[] = {
  124416. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124417. };
  124418. static long _vq_quantmap__16c1_s_p4_0[] = {
  124419. 7, 5, 3, 1, 0, 2, 4, 6,
  124420. 8,
  124421. };
  124422. static encode_aux_threshmatch _vq_auxt__16c1_s_p4_0 = {
  124423. _vq_quantthresh__16c1_s_p4_0,
  124424. _vq_quantmap__16c1_s_p4_0,
  124425. 9,
  124426. 9
  124427. };
  124428. static static_codebook _16c1_s_p4_0 = {
  124429. 2, 81,
  124430. _vq_lengthlist__16c1_s_p4_0,
  124431. 1, -531628032, 1611661312, 4, 0,
  124432. _vq_quantlist__16c1_s_p4_0,
  124433. NULL,
  124434. &_vq_auxt__16c1_s_p4_0,
  124435. NULL,
  124436. 0
  124437. };
  124438. static long _vq_quantlist__16c1_s_p5_0[] = {
  124439. 4,
  124440. 3,
  124441. 5,
  124442. 2,
  124443. 6,
  124444. 1,
  124445. 7,
  124446. 0,
  124447. 8,
  124448. };
  124449. static long _vq_lengthlist__16c1_s_p5_0[] = {
  124450. 1, 3, 3, 5, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  124451. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 8, 8,
  124452. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  124453. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  124454. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  124455. 10,
  124456. };
  124457. static float _vq_quantthresh__16c1_s_p5_0[] = {
  124458. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124459. };
  124460. static long _vq_quantmap__16c1_s_p5_0[] = {
  124461. 7, 5, 3, 1, 0, 2, 4, 6,
  124462. 8,
  124463. };
  124464. static encode_aux_threshmatch _vq_auxt__16c1_s_p5_0 = {
  124465. _vq_quantthresh__16c1_s_p5_0,
  124466. _vq_quantmap__16c1_s_p5_0,
  124467. 9,
  124468. 9
  124469. };
  124470. static static_codebook _16c1_s_p5_0 = {
  124471. 2, 81,
  124472. _vq_lengthlist__16c1_s_p5_0,
  124473. 1, -531628032, 1611661312, 4, 0,
  124474. _vq_quantlist__16c1_s_p5_0,
  124475. NULL,
  124476. &_vq_auxt__16c1_s_p5_0,
  124477. NULL,
  124478. 0
  124479. };
  124480. static long _vq_quantlist__16c1_s_p6_0[] = {
  124481. 8,
  124482. 7,
  124483. 9,
  124484. 6,
  124485. 10,
  124486. 5,
  124487. 11,
  124488. 4,
  124489. 12,
  124490. 3,
  124491. 13,
  124492. 2,
  124493. 14,
  124494. 1,
  124495. 15,
  124496. 0,
  124497. 16,
  124498. };
  124499. static long _vq_lengthlist__16c1_s_p6_0[] = {
  124500. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,12,
  124501. 12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  124502. 12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  124503. 11,12,12, 0, 0, 0, 8, 8, 8, 9,10, 9,10,10,10,10,
  124504. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,11,
  124505. 11,11,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  124506. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  124507. 10,11,11,12,12,13,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  124508. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  124509. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  124510. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  124511. 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0,
  124512. 10,10,11,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0,
  124513. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  124514. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  124515. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0,
  124516. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  124517. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  124518. 14,
  124519. };
  124520. static float _vq_quantthresh__16c1_s_p6_0[] = {
  124521. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  124522. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  124523. };
  124524. static long _vq_quantmap__16c1_s_p6_0[] = {
  124525. 15, 13, 11, 9, 7, 5, 3, 1,
  124526. 0, 2, 4, 6, 8, 10, 12, 14,
  124527. 16,
  124528. };
  124529. static encode_aux_threshmatch _vq_auxt__16c1_s_p6_0 = {
  124530. _vq_quantthresh__16c1_s_p6_0,
  124531. _vq_quantmap__16c1_s_p6_0,
  124532. 17,
  124533. 17
  124534. };
  124535. static static_codebook _16c1_s_p6_0 = {
  124536. 2, 289,
  124537. _vq_lengthlist__16c1_s_p6_0,
  124538. 1, -529530880, 1611661312, 5, 0,
  124539. _vq_quantlist__16c1_s_p6_0,
  124540. NULL,
  124541. &_vq_auxt__16c1_s_p6_0,
  124542. NULL,
  124543. 0
  124544. };
  124545. static long _vq_quantlist__16c1_s_p7_0[] = {
  124546. 1,
  124547. 0,
  124548. 2,
  124549. };
  124550. static long _vq_lengthlist__16c1_s_p7_0[] = {
  124551. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9,10,10,
  124552. 10, 9, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  124553. 11,11,10,10, 6,10, 9,11,11,11,11,10,10, 6,10,10,
  124554. 11,11,11,11,10,10, 7,11,11,11,11,11,12,12,11, 6,
  124555. 10,10,11,10,10,11,11,11, 6,10,10,10,11,10,11,11,
  124556. 11,
  124557. };
  124558. static float _vq_quantthresh__16c1_s_p7_0[] = {
  124559. -5.5, 5.5,
  124560. };
  124561. static long _vq_quantmap__16c1_s_p7_0[] = {
  124562. 1, 0, 2,
  124563. };
  124564. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_0 = {
  124565. _vq_quantthresh__16c1_s_p7_0,
  124566. _vq_quantmap__16c1_s_p7_0,
  124567. 3,
  124568. 3
  124569. };
  124570. static static_codebook _16c1_s_p7_0 = {
  124571. 4, 81,
  124572. _vq_lengthlist__16c1_s_p7_0,
  124573. 1, -529137664, 1618345984, 2, 0,
  124574. _vq_quantlist__16c1_s_p7_0,
  124575. NULL,
  124576. &_vq_auxt__16c1_s_p7_0,
  124577. NULL,
  124578. 0
  124579. };
  124580. static long _vq_quantlist__16c1_s_p7_1[] = {
  124581. 5,
  124582. 4,
  124583. 6,
  124584. 3,
  124585. 7,
  124586. 2,
  124587. 8,
  124588. 1,
  124589. 9,
  124590. 0,
  124591. 10,
  124592. };
  124593. static long _vq_lengthlist__16c1_s_p7_1[] = {
  124594. 2, 3, 3, 5, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  124595. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  124596. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  124597. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  124598. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  124599. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  124600. 8, 9, 9,10,10,10,10,10, 9, 9, 8, 8, 9, 9,10,10,
  124601. 10,10,10, 8, 8, 8, 8, 9, 9,
  124602. };
  124603. static float _vq_quantthresh__16c1_s_p7_1[] = {
  124604. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  124605. 3.5, 4.5,
  124606. };
  124607. static long _vq_quantmap__16c1_s_p7_1[] = {
  124608. 9, 7, 5, 3, 1, 0, 2, 4,
  124609. 6, 8, 10,
  124610. };
  124611. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_1 = {
  124612. _vq_quantthresh__16c1_s_p7_1,
  124613. _vq_quantmap__16c1_s_p7_1,
  124614. 11,
  124615. 11
  124616. };
  124617. static static_codebook _16c1_s_p7_1 = {
  124618. 2, 121,
  124619. _vq_lengthlist__16c1_s_p7_1,
  124620. 1, -531365888, 1611661312, 4, 0,
  124621. _vq_quantlist__16c1_s_p7_1,
  124622. NULL,
  124623. &_vq_auxt__16c1_s_p7_1,
  124624. NULL,
  124625. 0
  124626. };
  124627. static long _vq_quantlist__16c1_s_p8_0[] = {
  124628. 6,
  124629. 5,
  124630. 7,
  124631. 4,
  124632. 8,
  124633. 3,
  124634. 9,
  124635. 2,
  124636. 10,
  124637. 1,
  124638. 11,
  124639. 0,
  124640. 12,
  124641. };
  124642. static long _vq_lengthlist__16c1_s_p8_0[] = {
  124643. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  124644. 7, 8, 8, 9, 8, 8, 9, 9,10,11, 6, 5, 5, 8, 8, 9,
  124645. 9, 8, 8, 9,10,10,11, 0, 8, 8, 8, 9, 9, 9, 9, 9,
  124646. 10,10,11,11, 0, 9, 9, 9, 8, 9, 9, 9, 9,10,10,11,
  124647. 11, 0,13,13, 9, 9,10,10,10,10,11,11,12,12, 0,14,
  124648. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  124649. 9, 9,11,11,12,12,13,12, 0, 0, 0,10,10, 9, 9,10,
  124650. 10,12,12,13,13, 0, 0, 0,13,14,11,10,11,11,12,12,
  124651. 13,14, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  124652. 0, 0, 0, 0,12,12,12,12,13,13,14,15, 0, 0, 0, 0,
  124653. 0,12,12,12,12,13,13,14,15,
  124654. };
  124655. static float _vq_quantthresh__16c1_s_p8_0[] = {
  124656. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  124657. 12.5, 17.5, 22.5, 27.5,
  124658. };
  124659. static long _vq_quantmap__16c1_s_p8_0[] = {
  124660. 11, 9, 7, 5, 3, 1, 0, 2,
  124661. 4, 6, 8, 10, 12,
  124662. };
  124663. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_0 = {
  124664. _vq_quantthresh__16c1_s_p8_0,
  124665. _vq_quantmap__16c1_s_p8_0,
  124666. 13,
  124667. 13
  124668. };
  124669. static static_codebook _16c1_s_p8_0 = {
  124670. 2, 169,
  124671. _vq_lengthlist__16c1_s_p8_0,
  124672. 1, -526516224, 1616117760, 4, 0,
  124673. _vq_quantlist__16c1_s_p8_0,
  124674. NULL,
  124675. &_vq_auxt__16c1_s_p8_0,
  124676. NULL,
  124677. 0
  124678. };
  124679. static long _vq_quantlist__16c1_s_p8_1[] = {
  124680. 2,
  124681. 1,
  124682. 3,
  124683. 0,
  124684. 4,
  124685. };
  124686. static long _vq_lengthlist__16c1_s_p8_1[] = {
  124687. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  124688. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  124689. };
  124690. static float _vq_quantthresh__16c1_s_p8_1[] = {
  124691. -1.5, -0.5, 0.5, 1.5,
  124692. };
  124693. static long _vq_quantmap__16c1_s_p8_1[] = {
  124694. 3, 1, 0, 2, 4,
  124695. };
  124696. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_1 = {
  124697. _vq_quantthresh__16c1_s_p8_1,
  124698. _vq_quantmap__16c1_s_p8_1,
  124699. 5,
  124700. 5
  124701. };
  124702. static static_codebook _16c1_s_p8_1 = {
  124703. 2, 25,
  124704. _vq_lengthlist__16c1_s_p8_1,
  124705. 1, -533725184, 1611661312, 3, 0,
  124706. _vq_quantlist__16c1_s_p8_1,
  124707. NULL,
  124708. &_vq_auxt__16c1_s_p8_1,
  124709. NULL,
  124710. 0
  124711. };
  124712. static long _vq_quantlist__16c1_s_p9_0[] = {
  124713. 6,
  124714. 5,
  124715. 7,
  124716. 4,
  124717. 8,
  124718. 3,
  124719. 9,
  124720. 2,
  124721. 10,
  124722. 1,
  124723. 11,
  124724. 0,
  124725. 12,
  124726. };
  124727. static long _vq_lengthlist__16c1_s_p9_0[] = {
  124728. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124729. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124730. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124731. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124732. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124733. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124734. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124735. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124736. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124737. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124738. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124739. };
  124740. static float _vq_quantthresh__16c1_s_p9_0[] = {
  124741. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  124742. 787.5, 1102.5, 1417.5, 1732.5,
  124743. };
  124744. static long _vq_quantmap__16c1_s_p9_0[] = {
  124745. 11, 9, 7, 5, 3, 1, 0, 2,
  124746. 4, 6, 8, 10, 12,
  124747. };
  124748. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_0 = {
  124749. _vq_quantthresh__16c1_s_p9_0,
  124750. _vq_quantmap__16c1_s_p9_0,
  124751. 13,
  124752. 13
  124753. };
  124754. static static_codebook _16c1_s_p9_0 = {
  124755. 2, 169,
  124756. _vq_lengthlist__16c1_s_p9_0,
  124757. 1, -513964032, 1628680192, 4, 0,
  124758. _vq_quantlist__16c1_s_p9_0,
  124759. NULL,
  124760. &_vq_auxt__16c1_s_p9_0,
  124761. NULL,
  124762. 0
  124763. };
  124764. static long _vq_quantlist__16c1_s_p9_1[] = {
  124765. 7,
  124766. 6,
  124767. 8,
  124768. 5,
  124769. 9,
  124770. 4,
  124771. 10,
  124772. 3,
  124773. 11,
  124774. 2,
  124775. 12,
  124776. 1,
  124777. 13,
  124778. 0,
  124779. 14,
  124780. };
  124781. static long _vq_lengthlist__16c1_s_p9_1[] = {
  124782. 1, 4, 4, 4, 4, 8, 8,12,13,14,14,14,14,14,14, 6,
  124783. 6, 6, 6, 6,10, 9,14,14,14,14,14,14,14,14, 7, 6,
  124784. 5, 6, 6,10, 9,12,13,13,13,13,13,13,13,13, 7, 7,
  124785. 9, 9,11,11,12,13,13,13,13,13,13,13,13, 7, 7, 8,
  124786. 8,11,12,13,13,13,13,13,13,13,13,13,12,12,10,10,
  124787. 13,12,13,13,13,13,13,13,13,13,13,12,12,10,10,13,
  124788. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,13,12,
  124789. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  124790. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124791. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  124792. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124793. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124794. 13,13,13,13,13,13,13,13,13,12,13,13,13,13,13,13,
  124795. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124796. 13,
  124797. };
  124798. static float _vq_quantthresh__16c1_s_p9_1[] = {
  124799. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  124800. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  124801. };
  124802. static long _vq_quantmap__16c1_s_p9_1[] = {
  124803. 13, 11, 9, 7, 5, 3, 1, 0,
  124804. 2, 4, 6, 8, 10, 12, 14,
  124805. };
  124806. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_1 = {
  124807. _vq_quantthresh__16c1_s_p9_1,
  124808. _vq_quantmap__16c1_s_p9_1,
  124809. 15,
  124810. 15
  124811. };
  124812. static static_codebook _16c1_s_p9_1 = {
  124813. 2, 225,
  124814. _vq_lengthlist__16c1_s_p9_1,
  124815. 1, -520986624, 1620377600, 4, 0,
  124816. _vq_quantlist__16c1_s_p9_1,
  124817. NULL,
  124818. &_vq_auxt__16c1_s_p9_1,
  124819. NULL,
  124820. 0
  124821. };
  124822. static long _vq_quantlist__16c1_s_p9_2[] = {
  124823. 10,
  124824. 9,
  124825. 11,
  124826. 8,
  124827. 12,
  124828. 7,
  124829. 13,
  124830. 6,
  124831. 14,
  124832. 5,
  124833. 15,
  124834. 4,
  124835. 16,
  124836. 3,
  124837. 17,
  124838. 2,
  124839. 18,
  124840. 1,
  124841. 19,
  124842. 0,
  124843. 20,
  124844. };
  124845. static long _vq_lengthlist__16c1_s_p9_2[] = {
  124846. 1, 4, 4, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9,10,
  124847. 10,10, 9,10,10,11,12,12, 8, 8, 8, 8, 9, 9, 9, 9,
  124848. 10,10,10,10,10,11,11,10,12,11,11,13,11, 7, 7, 8,
  124849. 8, 8, 8, 9, 9, 9,10,10,10,10, 9,10,10,11,11,12,
  124850. 11,11, 8, 8, 8, 8, 9, 9,10,10,10,10,11,11,11,11,
  124851. 11,11,11,12,11,12,12, 8, 8, 9, 9, 9, 9, 9,10,10,
  124852. 10,10,10,10,11,11,11,11,11,11,12,11, 9, 9, 9, 9,
  124853. 10,10,10,10,11,10,11,11,11,11,11,11,12,12,12,12,
  124854. 11, 9, 9, 9, 9,10,10,10,10,11,11,11,11,11,11,11,
  124855. 11,11,12,12,12,13, 9,10,10, 9,11,10,10,10,10,11,
  124856. 11,11,11,11,10,11,12,11,12,12,11,12,11,10, 9,10,
  124857. 10,11,10,11,11,11,11,11,11,11,11,11,12,12,11,12,
  124858. 12,12,10,10,10,11,10,11,11,11,11,11,11,11,11,11,
  124859. 11,11,12,13,12,12,11, 9,10,10,11,11,10,11,11,11,
  124860. 12,11,11,11,11,11,12,12,13,13,12,13,10,10,12,10,
  124861. 11,11,11,11,11,11,11,11,11,12,12,11,13,12,12,12,
  124862. 12,13,12,11,11,11,11,11,11,12,11,12,11,11,11,11,
  124863. 12,12,13,12,11,12,12,11,11,11,11,11,12,11,11,11,
  124864. 11,12,11,11,12,11,12,13,13,12,12,12,12,11,11,11,
  124865. 11,11,12,11,11,12,11,12,11,11,11,11,13,12,12,12,
  124866. 12,13,11,11,11,12,12,11,11,11,12,11,12,12,12,11,
  124867. 12,13,12,11,11,12,12,11,12,11,11,11,12,12,11,12,
  124868. 11,11,11,12,12,12,12,13,12,13,12,12,12,12,11,11,
  124869. 12,11,11,11,11,11,11,12,12,12,13,12,11,13,13,12,
  124870. 12,11,12,10,11,11,11,11,12,11,12,12,11,12,12,13,
  124871. 12,12,13,12,12,12,12,12,11,12,12,12,11,12,11,11,
  124872. 11,12,13,12,13,13,13,13,13,12,13,13,12,12,13,11,
  124873. 11,11,11,11,12,11,11,12,11,
  124874. };
  124875. static float _vq_quantthresh__16c1_s_p9_2[] = {
  124876. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  124877. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  124878. 6.5, 7.5, 8.5, 9.5,
  124879. };
  124880. static long _vq_quantmap__16c1_s_p9_2[] = {
  124881. 19, 17, 15, 13, 11, 9, 7, 5,
  124882. 3, 1, 0, 2, 4, 6, 8, 10,
  124883. 12, 14, 16, 18, 20,
  124884. };
  124885. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_2 = {
  124886. _vq_quantthresh__16c1_s_p9_2,
  124887. _vq_quantmap__16c1_s_p9_2,
  124888. 21,
  124889. 21
  124890. };
  124891. static static_codebook _16c1_s_p9_2 = {
  124892. 2, 441,
  124893. _vq_lengthlist__16c1_s_p9_2,
  124894. 1, -529268736, 1611661312, 5, 0,
  124895. _vq_quantlist__16c1_s_p9_2,
  124896. NULL,
  124897. &_vq_auxt__16c1_s_p9_2,
  124898. NULL,
  124899. 0
  124900. };
  124901. static long _huff_lengthlist__16c1_s_short[] = {
  124902. 5, 6,17, 8,12, 9,10,10,12,13, 5, 2,17, 4, 9, 5,
  124903. 7, 8,11,13,16,16,16,16,16,16,16,16,16,16, 6, 4,
  124904. 16, 5,10, 5, 7,10,14,16,13, 9,16,11, 8, 7, 8, 9,
  124905. 13,16, 7, 4,16, 5, 7, 4, 6, 8,11,13, 8, 6,16, 7,
  124906. 8, 5, 5, 7, 9,13, 9, 8,16, 9, 8, 6, 6, 7, 9,13,
  124907. 11,11,16,10,10, 7, 7, 7, 9,13,13,13,16,13,13, 9,
  124908. 9, 9,10,13,
  124909. };
  124910. static static_codebook _huff_book__16c1_s_short = {
  124911. 2, 100,
  124912. _huff_lengthlist__16c1_s_short,
  124913. 0, 0, 0, 0, 0,
  124914. NULL,
  124915. NULL,
  124916. NULL,
  124917. NULL,
  124918. 0
  124919. };
  124920. static long _huff_lengthlist__16c2_s_long[] = {
  124921. 4, 7, 9, 9, 9, 8, 9,10,15,19, 5, 4, 5, 6, 7, 7,
  124922. 8, 9,14,16, 6, 5, 4, 5, 6, 7, 8,10,12,19, 7, 6,
  124923. 5, 4, 5, 6, 7, 9,11,18, 8, 7, 6, 5, 5, 5, 7, 9,
  124924. 10,17, 8, 7, 7, 5, 5, 5, 6, 7,12,18, 8, 8, 8, 7,
  124925. 7, 5, 5, 7,12,18, 8, 9,10, 9, 9, 7, 6, 7,12,17,
  124926. 14,18,16,16,15,12,11,10,12,18,15,17,18,18,18,15,
  124927. 14,14,16,18,
  124928. };
  124929. static static_codebook _huff_book__16c2_s_long = {
  124930. 2, 100,
  124931. _huff_lengthlist__16c2_s_long,
  124932. 0, 0, 0, 0, 0,
  124933. NULL,
  124934. NULL,
  124935. NULL,
  124936. NULL,
  124937. 0
  124938. };
  124939. static long _vq_quantlist__16c2_s_p1_0[] = {
  124940. 1,
  124941. 0,
  124942. 2,
  124943. };
  124944. static long _vq_lengthlist__16c2_s_p1_0[] = {
  124945. 1, 3, 3, 0, 0, 0, 0, 0, 0, 4, 5, 5, 0, 0, 0, 0,
  124946. 0, 0, 4, 5, 5, 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,
  124951. };
  124952. static float _vq_quantthresh__16c2_s_p1_0[] = {
  124953. -0.5, 0.5,
  124954. };
  124955. static long _vq_quantmap__16c2_s_p1_0[] = {
  124956. 1, 0, 2,
  124957. };
  124958. static encode_aux_threshmatch _vq_auxt__16c2_s_p1_0 = {
  124959. _vq_quantthresh__16c2_s_p1_0,
  124960. _vq_quantmap__16c2_s_p1_0,
  124961. 3,
  124962. 3
  124963. };
  124964. static static_codebook _16c2_s_p1_0 = {
  124965. 4, 81,
  124966. _vq_lengthlist__16c2_s_p1_0,
  124967. 1, -535822336, 1611661312, 2, 0,
  124968. _vq_quantlist__16c2_s_p1_0,
  124969. NULL,
  124970. &_vq_auxt__16c2_s_p1_0,
  124971. NULL,
  124972. 0
  124973. };
  124974. static long _vq_quantlist__16c2_s_p2_0[] = {
  124975. 2,
  124976. 1,
  124977. 3,
  124978. 0,
  124979. 4,
  124980. };
  124981. static long _vq_lengthlist__16c2_s_p2_0[] = {
  124982. 2, 4, 3, 7, 7, 0, 0, 0, 7, 8, 0, 0, 0, 8, 8, 0,
  124983. 0, 0, 8, 8, 0, 0, 0, 8, 8, 4, 5, 4, 8, 8, 0, 0,
  124984. 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0,
  124985. 9, 9, 4, 4, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8,
  124986. 8, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 7, 8, 8,10,10,
  124987. 0, 0, 0,12,11, 0, 0, 0,11,11, 0, 0, 0,14,13, 0,
  124988. 0, 0,14,13, 7, 8, 8, 9,10, 0, 0, 0,11,12, 0, 0,
  124989. 0,11,11, 0, 0, 0,14,14, 0, 0, 0,13,14, 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, 8, 8, 8,11,11, 0, 0, 0,
  124995. 11,11, 0, 0, 0,12,11, 0, 0, 0,12,12, 0, 0, 0,13,
  124996. 13, 8, 8, 8,11,11, 0, 0, 0,11,11, 0, 0, 0,11,12,
  124997. 0, 0, 0,12,13, 0, 0, 0,13,13, 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, 8, 8, 8,12,11, 0, 0, 0,12,11, 0,
  125003. 0, 0,11,11, 0, 0, 0,13,13, 0, 0, 0,13,12, 8, 8,
  125004. 8,11,12, 0, 0, 0,11,12, 0, 0, 0,11,11, 0, 0, 0,
  125005. 13,13, 0, 0, 0,12,13, 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, 8, 9, 9,14,13, 0, 0, 0,13,12, 0, 0, 0,13,
  125011. 13, 0, 0, 0,13,12, 0, 0, 0,13,13, 8, 9, 9,13,14,
  125012. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,13, 0,
  125013. 0, 0,13,13, 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, 8,
  125018. 9, 9,14,13, 0, 0, 0,13,13, 0, 0, 0,13,12, 0, 0,
  125019. 0,13,13, 0, 0, 0,13,12, 8, 9, 9,14,14, 0, 0, 0,
  125020. 13,13, 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,
  125021. 13,
  125022. };
  125023. static float _vq_quantthresh__16c2_s_p2_0[] = {
  125024. -1.5, -0.5, 0.5, 1.5,
  125025. };
  125026. static long _vq_quantmap__16c2_s_p2_0[] = {
  125027. 3, 1, 0, 2, 4,
  125028. };
  125029. static encode_aux_threshmatch _vq_auxt__16c2_s_p2_0 = {
  125030. _vq_quantthresh__16c2_s_p2_0,
  125031. _vq_quantmap__16c2_s_p2_0,
  125032. 5,
  125033. 5
  125034. };
  125035. static static_codebook _16c2_s_p2_0 = {
  125036. 4, 625,
  125037. _vq_lengthlist__16c2_s_p2_0,
  125038. 1, -533725184, 1611661312, 3, 0,
  125039. _vq_quantlist__16c2_s_p2_0,
  125040. NULL,
  125041. &_vq_auxt__16c2_s_p2_0,
  125042. NULL,
  125043. 0
  125044. };
  125045. static long _vq_quantlist__16c2_s_p3_0[] = {
  125046. 4,
  125047. 3,
  125048. 5,
  125049. 2,
  125050. 6,
  125051. 1,
  125052. 7,
  125053. 0,
  125054. 8,
  125055. };
  125056. static long _vq_lengthlist__16c2_s_p3_0[] = {
  125057. 1, 3, 3, 6, 6, 7, 7, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  125058. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  125059. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  125060. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 9, 9,10,10, 0,
  125061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125062. 0,
  125063. };
  125064. static float _vq_quantthresh__16c2_s_p3_0[] = {
  125065. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  125066. };
  125067. static long _vq_quantmap__16c2_s_p3_0[] = {
  125068. 7, 5, 3, 1, 0, 2, 4, 6,
  125069. 8,
  125070. };
  125071. static encode_aux_threshmatch _vq_auxt__16c2_s_p3_0 = {
  125072. _vq_quantthresh__16c2_s_p3_0,
  125073. _vq_quantmap__16c2_s_p3_0,
  125074. 9,
  125075. 9
  125076. };
  125077. static static_codebook _16c2_s_p3_0 = {
  125078. 2, 81,
  125079. _vq_lengthlist__16c2_s_p3_0,
  125080. 1, -531628032, 1611661312, 4, 0,
  125081. _vq_quantlist__16c2_s_p3_0,
  125082. NULL,
  125083. &_vq_auxt__16c2_s_p3_0,
  125084. NULL,
  125085. 0
  125086. };
  125087. static long _vq_quantlist__16c2_s_p4_0[] = {
  125088. 8,
  125089. 7,
  125090. 9,
  125091. 6,
  125092. 10,
  125093. 5,
  125094. 11,
  125095. 4,
  125096. 12,
  125097. 3,
  125098. 13,
  125099. 2,
  125100. 14,
  125101. 1,
  125102. 15,
  125103. 0,
  125104. 16,
  125105. };
  125106. static long _vq_lengthlist__16c2_s_p4_0[] = {
  125107. 2, 3, 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,
  125108. 10, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  125109. 11,11, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  125110. 10,10,11, 0, 0, 0, 6, 6, 8, 8, 8, 8, 9, 9,10,10,
  125111. 10,11,11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,
  125112. 10,11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,
  125113. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9,
  125114. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  125115. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  125116. 9,10,10,11,11,12,12,12,12, 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,
  125126. };
  125127. static float _vq_quantthresh__16c2_s_p4_0[] = {
  125128. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  125129. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  125130. };
  125131. static long _vq_quantmap__16c2_s_p4_0[] = {
  125132. 15, 13, 11, 9, 7, 5, 3, 1,
  125133. 0, 2, 4, 6, 8, 10, 12, 14,
  125134. 16,
  125135. };
  125136. static encode_aux_threshmatch _vq_auxt__16c2_s_p4_0 = {
  125137. _vq_quantthresh__16c2_s_p4_0,
  125138. _vq_quantmap__16c2_s_p4_0,
  125139. 17,
  125140. 17
  125141. };
  125142. static static_codebook _16c2_s_p4_0 = {
  125143. 2, 289,
  125144. _vq_lengthlist__16c2_s_p4_0,
  125145. 1, -529530880, 1611661312, 5, 0,
  125146. _vq_quantlist__16c2_s_p4_0,
  125147. NULL,
  125148. &_vq_auxt__16c2_s_p4_0,
  125149. NULL,
  125150. 0
  125151. };
  125152. static long _vq_quantlist__16c2_s_p5_0[] = {
  125153. 1,
  125154. 0,
  125155. 2,
  125156. };
  125157. static long _vq_lengthlist__16c2_s_p5_0[] = {
  125158. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6,10,10,10,10,
  125159. 10,10, 4, 7, 6,10,10,10,10,10,10, 5, 9, 9, 9,12,
  125160. 11,10,11,12, 7,10,10,12,12,12,12,12,12, 7,10,10,
  125161. 11,12,12,12,12,13, 6,10,10,10,12,12,10,12,12, 7,
  125162. 10,10,11,13,12,12,12,12, 7,10,10,11,12,12,12,12,
  125163. 12,
  125164. };
  125165. static float _vq_quantthresh__16c2_s_p5_0[] = {
  125166. -5.5, 5.5,
  125167. };
  125168. static long _vq_quantmap__16c2_s_p5_0[] = {
  125169. 1, 0, 2,
  125170. };
  125171. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_0 = {
  125172. _vq_quantthresh__16c2_s_p5_0,
  125173. _vq_quantmap__16c2_s_p5_0,
  125174. 3,
  125175. 3
  125176. };
  125177. static static_codebook _16c2_s_p5_0 = {
  125178. 4, 81,
  125179. _vq_lengthlist__16c2_s_p5_0,
  125180. 1, -529137664, 1618345984, 2, 0,
  125181. _vq_quantlist__16c2_s_p5_0,
  125182. NULL,
  125183. &_vq_auxt__16c2_s_p5_0,
  125184. NULL,
  125185. 0
  125186. };
  125187. static long _vq_quantlist__16c2_s_p5_1[] = {
  125188. 5,
  125189. 4,
  125190. 6,
  125191. 3,
  125192. 7,
  125193. 2,
  125194. 8,
  125195. 1,
  125196. 9,
  125197. 0,
  125198. 10,
  125199. };
  125200. static long _vq_lengthlist__16c2_s_p5_1[] = {
  125201. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11, 6, 6,
  125202. 7, 7, 8, 8, 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8,
  125203. 8,11,11,11, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  125204. 6, 8, 8, 8, 8, 9, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  125205. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 9,11,11,11,
  125206. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,11,11, 8, 8, 8,
  125207. 8, 8, 8,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  125208. 11,11,11, 7, 7, 8, 8, 8, 8,
  125209. };
  125210. static float _vq_quantthresh__16c2_s_p5_1[] = {
  125211. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125212. 3.5, 4.5,
  125213. };
  125214. static long _vq_quantmap__16c2_s_p5_1[] = {
  125215. 9, 7, 5, 3, 1, 0, 2, 4,
  125216. 6, 8, 10,
  125217. };
  125218. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_1 = {
  125219. _vq_quantthresh__16c2_s_p5_1,
  125220. _vq_quantmap__16c2_s_p5_1,
  125221. 11,
  125222. 11
  125223. };
  125224. static static_codebook _16c2_s_p5_1 = {
  125225. 2, 121,
  125226. _vq_lengthlist__16c2_s_p5_1,
  125227. 1, -531365888, 1611661312, 4, 0,
  125228. _vq_quantlist__16c2_s_p5_1,
  125229. NULL,
  125230. &_vq_auxt__16c2_s_p5_1,
  125231. NULL,
  125232. 0
  125233. };
  125234. static long _vq_quantlist__16c2_s_p6_0[] = {
  125235. 6,
  125236. 5,
  125237. 7,
  125238. 4,
  125239. 8,
  125240. 3,
  125241. 9,
  125242. 2,
  125243. 10,
  125244. 1,
  125245. 11,
  125246. 0,
  125247. 12,
  125248. };
  125249. static long _vq_lengthlist__16c2_s_p6_0[] = {
  125250. 1, 4, 4, 7, 6, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  125251. 7, 7, 9, 9, 9, 9,11,11,12,12, 6, 5, 5, 7, 7, 9,
  125252. 9,10,10,11,11,12,12, 0, 6, 6, 7, 7, 9, 9,10,10,
  125253. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,12,12,
  125254. 12, 0,11,11, 8, 8,10,10,11,11,12,12,13,13, 0,11,
  125255. 12, 8, 8,10,10,11,11,12,12,13,13, 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,
  125261. };
  125262. static float _vq_quantthresh__16c2_s_p6_0[] = {
  125263. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  125264. 12.5, 17.5, 22.5, 27.5,
  125265. };
  125266. static long _vq_quantmap__16c2_s_p6_0[] = {
  125267. 11, 9, 7, 5, 3, 1, 0, 2,
  125268. 4, 6, 8, 10, 12,
  125269. };
  125270. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_0 = {
  125271. _vq_quantthresh__16c2_s_p6_0,
  125272. _vq_quantmap__16c2_s_p6_0,
  125273. 13,
  125274. 13
  125275. };
  125276. static static_codebook _16c2_s_p6_0 = {
  125277. 2, 169,
  125278. _vq_lengthlist__16c2_s_p6_0,
  125279. 1, -526516224, 1616117760, 4, 0,
  125280. _vq_quantlist__16c2_s_p6_0,
  125281. NULL,
  125282. &_vq_auxt__16c2_s_p6_0,
  125283. NULL,
  125284. 0
  125285. };
  125286. static long _vq_quantlist__16c2_s_p6_1[] = {
  125287. 2,
  125288. 1,
  125289. 3,
  125290. 0,
  125291. 4,
  125292. };
  125293. static long _vq_lengthlist__16c2_s_p6_1[] = {
  125294. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  125295. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  125296. };
  125297. static float _vq_quantthresh__16c2_s_p6_1[] = {
  125298. -1.5, -0.5, 0.5, 1.5,
  125299. };
  125300. static long _vq_quantmap__16c2_s_p6_1[] = {
  125301. 3, 1, 0, 2, 4,
  125302. };
  125303. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_1 = {
  125304. _vq_quantthresh__16c2_s_p6_1,
  125305. _vq_quantmap__16c2_s_p6_1,
  125306. 5,
  125307. 5
  125308. };
  125309. static static_codebook _16c2_s_p6_1 = {
  125310. 2, 25,
  125311. _vq_lengthlist__16c2_s_p6_1,
  125312. 1, -533725184, 1611661312, 3, 0,
  125313. _vq_quantlist__16c2_s_p6_1,
  125314. NULL,
  125315. &_vq_auxt__16c2_s_p6_1,
  125316. NULL,
  125317. 0
  125318. };
  125319. static long _vq_quantlist__16c2_s_p7_0[] = {
  125320. 6,
  125321. 5,
  125322. 7,
  125323. 4,
  125324. 8,
  125325. 3,
  125326. 9,
  125327. 2,
  125328. 10,
  125329. 1,
  125330. 11,
  125331. 0,
  125332. 12,
  125333. };
  125334. static long _vq_lengthlist__16c2_s_p7_0[] = {
  125335. 1, 4, 4, 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  125336. 8, 8, 9, 9,10,10,11,11,12,12, 6, 5, 5, 8, 8, 9,
  125337. 9,10,10,11,11,12,13,18, 6, 6, 7, 7, 9, 9,10,10,
  125338. 12,12,13,13,18, 6, 6, 7, 7, 9, 9,10,10,12,12,13,
  125339. 13,18,11,10, 8, 8,10,10,11,11,12,12,13,13,18,11,
  125340. 11, 8, 8,10,10,11,11,12,13,13,13,18,18,18,10,11,
  125341. 11,11,12,12,13,13,14,14,18,18,18,11,11,11,11,12,
  125342. 12,13,13,14,14,18,18,18,14,14,12,12,12,12,14,14,
  125343. 15,14,18,18,18,15,15,11,12,12,12,13,13,15,15,18,
  125344. 18,18,18,18,13,13,13,13,13,14,17,16,18,18,18,18,
  125345. 18,13,14,13,13,14,13,15,14,
  125346. };
  125347. static float _vq_quantthresh__16c2_s_p7_0[] = {
  125348. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  125349. 27.5, 38.5, 49.5, 60.5,
  125350. };
  125351. static long _vq_quantmap__16c2_s_p7_0[] = {
  125352. 11, 9, 7, 5, 3, 1, 0, 2,
  125353. 4, 6, 8, 10, 12,
  125354. };
  125355. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_0 = {
  125356. _vq_quantthresh__16c2_s_p7_0,
  125357. _vq_quantmap__16c2_s_p7_0,
  125358. 13,
  125359. 13
  125360. };
  125361. static static_codebook _16c2_s_p7_0 = {
  125362. 2, 169,
  125363. _vq_lengthlist__16c2_s_p7_0,
  125364. 1, -523206656, 1618345984, 4, 0,
  125365. _vq_quantlist__16c2_s_p7_0,
  125366. NULL,
  125367. &_vq_auxt__16c2_s_p7_0,
  125368. NULL,
  125369. 0
  125370. };
  125371. static long _vq_quantlist__16c2_s_p7_1[] = {
  125372. 5,
  125373. 4,
  125374. 6,
  125375. 3,
  125376. 7,
  125377. 2,
  125378. 8,
  125379. 1,
  125380. 9,
  125381. 0,
  125382. 10,
  125383. };
  125384. static long _vq_lengthlist__16c2_s_p7_1[] = {
  125385. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 9, 9, 6, 6,
  125386. 7, 7, 8, 8, 8, 8, 9, 9, 9, 6, 6, 7, 7, 8, 8, 8,
  125387. 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7,
  125388. 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  125389. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  125390. 7, 7, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 9, 7, 7, 7,
  125391. 7, 8, 8, 9, 9, 9, 9, 9, 8, 8, 7, 7, 8, 8, 9, 9,
  125392. 9, 9, 9, 7, 7, 7, 7, 8, 8,
  125393. };
  125394. static float _vq_quantthresh__16c2_s_p7_1[] = {
  125395. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125396. 3.5, 4.5,
  125397. };
  125398. static long _vq_quantmap__16c2_s_p7_1[] = {
  125399. 9, 7, 5, 3, 1, 0, 2, 4,
  125400. 6, 8, 10,
  125401. };
  125402. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_1 = {
  125403. _vq_quantthresh__16c2_s_p7_1,
  125404. _vq_quantmap__16c2_s_p7_1,
  125405. 11,
  125406. 11
  125407. };
  125408. static static_codebook _16c2_s_p7_1 = {
  125409. 2, 121,
  125410. _vq_lengthlist__16c2_s_p7_1,
  125411. 1, -531365888, 1611661312, 4, 0,
  125412. _vq_quantlist__16c2_s_p7_1,
  125413. NULL,
  125414. &_vq_auxt__16c2_s_p7_1,
  125415. NULL,
  125416. 0
  125417. };
  125418. static long _vq_quantlist__16c2_s_p8_0[] = {
  125419. 7,
  125420. 6,
  125421. 8,
  125422. 5,
  125423. 9,
  125424. 4,
  125425. 10,
  125426. 3,
  125427. 11,
  125428. 2,
  125429. 12,
  125430. 1,
  125431. 13,
  125432. 0,
  125433. 14,
  125434. };
  125435. static long _vq_lengthlist__16c2_s_p8_0[] = {
  125436. 1, 4, 4, 7, 6, 7, 7, 6, 6, 8, 8, 9, 9,10,10, 6,
  125437. 6, 6, 8, 8, 9, 8, 8, 8, 9, 9,11,10,11,11, 7, 6,
  125438. 6, 8, 8, 9, 8, 7, 7, 9, 9,10,10,12,11,14, 8, 8,
  125439. 8, 9, 9, 9, 9, 9,10, 9,10,10,11,13,14, 8, 8, 8,
  125440. 8, 9, 9, 8, 8, 9, 9,10,10,11,12,14,13,11, 9, 9,
  125441. 9, 9, 9, 9, 9,10,11,10,13,12,14,11,13, 8, 9, 9,
  125442. 9, 9, 9,10,10,11,10,13,12,14,14,14, 8, 9, 9, 9,
  125443. 11,11,11,11,11,12,13,13,14,14,14, 9, 8, 9, 9,10,
  125444. 10,12,10,11,12,12,14,14,14,14,11,12,10,10,12,12,
  125445. 12,12,13,14,12,12,14,14,14,12,12, 9,10,11,11,12,
  125446. 14,12,14,14,14,14,14,14,14,14,11,11,12,11,12,14,
  125447. 14,14,14,14,14,14,14,14,14,12,11,11,11,11,14,14,
  125448. 14,14,14,14,14,14,14,14,14,14,13,12,14,14,14,14,
  125449. 14,14,14,14,14,14,14,14,14,12,12,12,13,14,14,13,
  125450. 13,
  125451. };
  125452. static float _vq_quantthresh__16c2_s_p8_0[] = {
  125453. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  125454. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  125455. };
  125456. static long _vq_quantmap__16c2_s_p8_0[] = {
  125457. 13, 11, 9, 7, 5, 3, 1, 0,
  125458. 2, 4, 6, 8, 10, 12, 14,
  125459. };
  125460. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_0 = {
  125461. _vq_quantthresh__16c2_s_p8_0,
  125462. _vq_quantmap__16c2_s_p8_0,
  125463. 15,
  125464. 15
  125465. };
  125466. static static_codebook _16c2_s_p8_0 = {
  125467. 2, 225,
  125468. _vq_lengthlist__16c2_s_p8_0,
  125469. 1, -520986624, 1620377600, 4, 0,
  125470. _vq_quantlist__16c2_s_p8_0,
  125471. NULL,
  125472. &_vq_auxt__16c2_s_p8_0,
  125473. NULL,
  125474. 0
  125475. };
  125476. static long _vq_quantlist__16c2_s_p8_1[] = {
  125477. 10,
  125478. 9,
  125479. 11,
  125480. 8,
  125481. 12,
  125482. 7,
  125483. 13,
  125484. 6,
  125485. 14,
  125486. 5,
  125487. 15,
  125488. 4,
  125489. 16,
  125490. 3,
  125491. 17,
  125492. 2,
  125493. 18,
  125494. 1,
  125495. 19,
  125496. 0,
  125497. 20,
  125498. };
  125499. static long _vq_lengthlist__16c2_s_p8_1[] = {
  125500. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  125501. 8, 8, 8, 8, 8,11,12,11, 7, 7, 8, 8, 8, 8, 9, 9,
  125502. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,11,11,10, 7, 7, 8,
  125503. 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  125504. 11,11, 8, 7, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 9,10,
  125505. 10, 9,10,10,11,11,12, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  125506. 9, 9, 9,10, 9,10,10,10,10,11,11,11, 8, 8, 9, 9,
  125507. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  125508. 11, 8, 8, 9, 8, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,
  125509. 10, 9,10,11,11,11, 9, 9, 9, 9,10, 9, 9, 9,10,10,
  125510. 9,10, 9,10,10,10,10,10,11,12,11,11,11, 9, 9, 9,
  125511. 9, 9,10,10, 9,10,10,10,10,10,10,10,10,12,11,13,
  125512. 13,11, 9, 9, 9, 9,10,10, 9,10,10,10,10,11,10,10,
  125513. 10,10,11,12,11,12,11, 9, 9, 9,10,10, 9,10,10,10,
  125514. 10,10,10,10,10,10,10,11,11,11,12,11, 9,10,10,10,
  125515. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,12,12,
  125516. 11,11,11,10, 9,10,10,10,10,10,10,10,10,11,10,10,
  125517. 10,11,11,11,11,11,11,11,10,10,10,11,10,10,10,10,
  125518. 10,10,10,10,10,10,11,11,11,11,12,12,11,10,10,10,
  125519. 10,10,10,10,10,11,10,10,10,11,10,12,11,11,12,11,
  125520. 11,11,10,10,10,10,10,11,10,10,10,10,10,11,10,10,
  125521. 11,11,11,12,11,12,11,11,12,10,10,10,10,10,10,10,
  125522. 11,10,10,11,10,12,11,11,11,12,11,11,11,11,10,10,
  125523. 10,10,10,10,10,11,11,11,10,11,12,11,11,11,12,11,
  125524. 12,11,12,10,11,10,10,10,10,11,10,10,10,10,10,10,
  125525. 12,11,11,11,11,11,12,12,10,10,10,10,10,11,10,10,
  125526. 11,10,11,11,11,11,11,11,11,11,11,11,11,11,12,11,
  125527. 10,11,10,10,10,10,10,10,10,
  125528. };
  125529. static float _vq_quantthresh__16c2_s_p8_1[] = {
  125530. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  125531. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  125532. 6.5, 7.5, 8.5, 9.5,
  125533. };
  125534. static long _vq_quantmap__16c2_s_p8_1[] = {
  125535. 19, 17, 15, 13, 11, 9, 7, 5,
  125536. 3, 1, 0, 2, 4, 6, 8, 10,
  125537. 12, 14, 16, 18, 20,
  125538. };
  125539. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_1 = {
  125540. _vq_quantthresh__16c2_s_p8_1,
  125541. _vq_quantmap__16c2_s_p8_1,
  125542. 21,
  125543. 21
  125544. };
  125545. static static_codebook _16c2_s_p8_1 = {
  125546. 2, 441,
  125547. _vq_lengthlist__16c2_s_p8_1,
  125548. 1, -529268736, 1611661312, 5, 0,
  125549. _vq_quantlist__16c2_s_p8_1,
  125550. NULL,
  125551. &_vq_auxt__16c2_s_p8_1,
  125552. NULL,
  125553. 0
  125554. };
  125555. static long _vq_quantlist__16c2_s_p9_0[] = {
  125556. 6,
  125557. 5,
  125558. 7,
  125559. 4,
  125560. 8,
  125561. 3,
  125562. 9,
  125563. 2,
  125564. 10,
  125565. 1,
  125566. 11,
  125567. 0,
  125568. 12,
  125569. };
  125570. static long _vq_lengthlist__16c2_s_p9_0[] = {
  125571. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125572. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125573. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125574. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125575. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125576. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125577. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125578. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125579. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125580. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125581. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125582. };
  125583. static float _vq_quantthresh__16c2_s_p9_0[] = {
  125584. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5,
  125585. 2327.5, 3258.5, 4189.5, 5120.5,
  125586. };
  125587. static long _vq_quantmap__16c2_s_p9_0[] = {
  125588. 11, 9, 7, 5, 3, 1, 0, 2,
  125589. 4, 6, 8, 10, 12,
  125590. };
  125591. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_0 = {
  125592. _vq_quantthresh__16c2_s_p9_0,
  125593. _vq_quantmap__16c2_s_p9_0,
  125594. 13,
  125595. 13
  125596. };
  125597. static static_codebook _16c2_s_p9_0 = {
  125598. 2, 169,
  125599. _vq_lengthlist__16c2_s_p9_0,
  125600. 1, -510275072, 1631393792, 4, 0,
  125601. _vq_quantlist__16c2_s_p9_0,
  125602. NULL,
  125603. &_vq_auxt__16c2_s_p9_0,
  125604. NULL,
  125605. 0
  125606. };
  125607. static long _vq_quantlist__16c2_s_p9_1[] = {
  125608. 8,
  125609. 7,
  125610. 9,
  125611. 6,
  125612. 10,
  125613. 5,
  125614. 11,
  125615. 4,
  125616. 12,
  125617. 3,
  125618. 13,
  125619. 2,
  125620. 14,
  125621. 1,
  125622. 15,
  125623. 0,
  125624. 16,
  125625. };
  125626. static long _vq_lengthlist__16c2_s_p9_1[] = {
  125627. 1, 5, 5, 9, 8, 7, 7, 7, 6,10,11,11,11,11,11,11,
  125628. 11, 8, 7, 6, 8, 8,10, 9,10,10,10, 9,11,10,10,10,
  125629. 10,10, 8, 6, 6, 8, 8, 9, 8, 9, 8, 9,10,10,10,10,
  125630. 10,10,10,10, 8,10, 9, 9, 9, 9,10,10,10,10,10,10,
  125631. 10,10,10,10,10, 8, 9, 9, 9,10,10, 9,10,10,10,10,
  125632. 10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,10,10,10,
  125633. 10,10,10,10,10,10,10,10, 9, 8, 8, 9, 9,10,10,10,
  125634. 10,10,10,10,10,10,10,10,10,10, 9,10, 9, 9,10,10,
  125635. 10,10,10,10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,
  125636. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  125637. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125638. 8,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125639. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125640. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125641. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125642. 10,10,10,10, 9,10, 9,10,10,10,10,10,10,10,10,10,
  125643. 10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,
  125644. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125645. 10,
  125646. };
  125647. static float _vq_quantthresh__16c2_s_p9_1[] = {
  125648. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -24.5,
  125649. 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5, 367.5,
  125650. };
  125651. static long _vq_quantmap__16c2_s_p9_1[] = {
  125652. 15, 13, 11, 9, 7, 5, 3, 1,
  125653. 0, 2, 4, 6, 8, 10, 12, 14,
  125654. 16,
  125655. };
  125656. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_1 = {
  125657. _vq_quantthresh__16c2_s_p9_1,
  125658. _vq_quantmap__16c2_s_p9_1,
  125659. 17,
  125660. 17
  125661. };
  125662. static static_codebook _16c2_s_p9_1 = {
  125663. 2, 289,
  125664. _vq_lengthlist__16c2_s_p9_1,
  125665. 1, -518488064, 1622704128, 5, 0,
  125666. _vq_quantlist__16c2_s_p9_1,
  125667. NULL,
  125668. &_vq_auxt__16c2_s_p9_1,
  125669. NULL,
  125670. 0
  125671. };
  125672. static long _vq_quantlist__16c2_s_p9_2[] = {
  125673. 13,
  125674. 12,
  125675. 14,
  125676. 11,
  125677. 15,
  125678. 10,
  125679. 16,
  125680. 9,
  125681. 17,
  125682. 8,
  125683. 18,
  125684. 7,
  125685. 19,
  125686. 6,
  125687. 20,
  125688. 5,
  125689. 21,
  125690. 4,
  125691. 22,
  125692. 3,
  125693. 23,
  125694. 2,
  125695. 24,
  125696. 1,
  125697. 25,
  125698. 0,
  125699. 26,
  125700. };
  125701. static long _vq_lengthlist__16c2_s_p9_2[] = {
  125702. 1, 4, 4, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  125703. 7, 7, 7, 7, 8, 7, 8, 7, 7, 4, 4,
  125704. };
  125705. static float _vq_quantthresh__16c2_s_p9_2[] = {
  125706. -12.5, -11.5, -10.5, -9.5, -8.5, -7.5, -6.5, -5.5,
  125707. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125708. 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 10.5,
  125709. 11.5, 12.5,
  125710. };
  125711. static long _vq_quantmap__16c2_s_p9_2[] = {
  125712. 25, 23, 21, 19, 17, 15, 13, 11,
  125713. 9, 7, 5, 3, 1, 0, 2, 4,
  125714. 6, 8, 10, 12, 14, 16, 18, 20,
  125715. 22, 24, 26,
  125716. };
  125717. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_2 = {
  125718. _vq_quantthresh__16c2_s_p9_2,
  125719. _vq_quantmap__16c2_s_p9_2,
  125720. 27,
  125721. 27
  125722. };
  125723. static static_codebook _16c2_s_p9_2 = {
  125724. 1, 27,
  125725. _vq_lengthlist__16c2_s_p9_2,
  125726. 1, -528875520, 1611661312, 5, 0,
  125727. _vq_quantlist__16c2_s_p9_2,
  125728. NULL,
  125729. &_vq_auxt__16c2_s_p9_2,
  125730. NULL,
  125731. 0
  125732. };
  125733. static long _huff_lengthlist__16c2_s_short[] = {
  125734. 7,10,11,11,11,14,15,15,17,14, 8, 6, 7, 7, 8, 9,
  125735. 11,11,14,17, 9, 6, 6, 6, 7, 7,10,11,15,16, 9, 6,
  125736. 6, 4, 4, 5, 8, 9,12,16,10, 6, 6, 4, 4, 4, 6, 9,
  125737. 13,16,10, 7, 6, 5, 4, 3, 5, 7,13,16,11, 9, 8, 7,
  125738. 6, 5, 5, 6,12,15,10,10,10, 9, 7, 6, 6, 7,11,15,
  125739. 13,13,13,13,11,10,10, 9,12,16,16,16,16,14,16,15,
  125740. 15,12,14,14,
  125741. };
  125742. static static_codebook _huff_book__16c2_s_short = {
  125743. 2, 100,
  125744. _huff_lengthlist__16c2_s_short,
  125745. 0, 0, 0, 0, 0,
  125746. NULL,
  125747. NULL,
  125748. NULL,
  125749. NULL,
  125750. 0
  125751. };
  125752. static long _vq_quantlist__8c0_s_p1_0[] = {
  125753. 1,
  125754. 0,
  125755. 2,
  125756. };
  125757. static long _vq_lengthlist__8c0_s_p1_0[] = {
  125758. 1, 5, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  125759. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125763. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  125764. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125768. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  125769. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  125804. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  125805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0, 0,
  125809. 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  125810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9,10, 0, 0,
  125814. 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  125815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125849. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  125850. 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125854. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  125855. 0, 0, 0, 0, 0, 9,10,11, 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, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  125860. 0, 0, 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 0,
  125861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125890. 0, 0, 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, 0, 0, 0, 0, 0, 0,
  125892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125895. 0, 0, 0, 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, 0, 0, 0, 0, 0,
  125897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125900. 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126168. 0,
  126169. };
  126170. static float _vq_quantthresh__8c0_s_p1_0[] = {
  126171. -0.5, 0.5,
  126172. };
  126173. static long _vq_quantmap__8c0_s_p1_0[] = {
  126174. 1, 0, 2,
  126175. };
  126176. static encode_aux_threshmatch _vq_auxt__8c0_s_p1_0 = {
  126177. _vq_quantthresh__8c0_s_p1_0,
  126178. _vq_quantmap__8c0_s_p1_0,
  126179. 3,
  126180. 3
  126181. };
  126182. static static_codebook _8c0_s_p1_0 = {
  126183. 8, 6561,
  126184. _vq_lengthlist__8c0_s_p1_0,
  126185. 1, -535822336, 1611661312, 2, 0,
  126186. _vq_quantlist__8c0_s_p1_0,
  126187. NULL,
  126188. &_vq_auxt__8c0_s_p1_0,
  126189. NULL,
  126190. 0
  126191. };
  126192. static long _vq_quantlist__8c0_s_p2_0[] = {
  126193. 2,
  126194. 1,
  126195. 3,
  126196. 0,
  126197. 4,
  126198. };
  126199. static long _vq_lengthlist__8c0_s_p2_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,
  126240. };
  126241. static float _vq_quantthresh__8c0_s_p2_0[] = {
  126242. -1.5, -0.5, 0.5, 1.5,
  126243. };
  126244. static long _vq_quantmap__8c0_s_p2_0[] = {
  126245. 3, 1, 0, 2, 4,
  126246. };
  126247. static encode_aux_threshmatch _vq_auxt__8c0_s_p2_0 = {
  126248. _vq_quantthresh__8c0_s_p2_0,
  126249. _vq_quantmap__8c0_s_p2_0,
  126250. 5,
  126251. 5
  126252. };
  126253. static static_codebook _8c0_s_p2_0 = {
  126254. 4, 625,
  126255. _vq_lengthlist__8c0_s_p2_0,
  126256. 1, -533725184, 1611661312, 3, 0,
  126257. _vq_quantlist__8c0_s_p2_0,
  126258. NULL,
  126259. &_vq_auxt__8c0_s_p2_0,
  126260. NULL,
  126261. 0
  126262. };
  126263. static long _vq_quantlist__8c0_s_p3_0[] = {
  126264. 2,
  126265. 1,
  126266. 3,
  126267. 0,
  126268. 4,
  126269. };
  126270. static long _vq_lengthlist__8c0_s_p3_0[] = {
  126271. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 6, 7, 7, 0, 0,
  126273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126274. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 8, 8,
  126276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126277. 0, 0, 0, 0, 6, 7, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  126278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126287. 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126295. 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126310. 0,
  126311. };
  126312. static float _vq_quantthresh__8c0_s_p3_0[] = {
  126313. -1.5, -0.5, 0.5, 1.5,
  126314. };
  126315. static long _vq_quantmap__8c0_s_p3_0[] = {
  126316. 3, 1, 0, 2, 4,
  126317. };
  126318. static encode_aux_threshmatch _vq_auxt__8c0_s_p3_0 = {
  126319. _vq_quantthresh__8c0_s_p3_0,
  126320. _vq_quantmap__8c0_s_p3_0,
  126321. 5,
  126322. 5
  126323. };
  126324. static static_codebook _8c0_s_p3_0 = {
  126325. 4, 625,
  126326. _vq_lengthlist__8c0_s_p3_0,
  126327. 1, -533725184, 1611661312, 3, 0,
  126328. _vq_quantlist__8c0_s_p3_0,
  126329. NULL,
  126330. &_vq_auxt__8c0_s_p3_0,
  126331. NULL,
  126332. 0
  126333. };
  126334. static long _vq_quantlist__8c0_s_p4_0[] = {
  126335. 4,
  126336. 3,
  126337. 5,
  126338. 2,
  126339. 6,
  126340. 1,
  126341. 7,
  126342. 0,
  126343. 8,
  126344. };
  126345. static long _vq_lengthlist__8c0_s_p4_0[] = {
  126346. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  126347. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  126348. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  126349. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  126350. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126351. 0,
  126352. };
  126353. static float _vq_quantthresh__8c0_s_p4_0[] = {
  126354. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126355. };
  126356. static long _vq_quantmap__8c0_s_p4_0[] = {
  126357. 7, 5, 3, 1, 0, 2, 4, 6,
  126358. 8,
  126359. };
  126360. static encode_aux_threshmatch _vq_auxt__8c0_s_p4_0 = {
  126361. _vq_quantthresh__8c0_s_p4_0,
  126362. _vq_quantmap__8c0_s_p4_0,
  126363. 9,
  126364. 9
  126365. };
  126366. static static_codebook _8c0_s_p4_0 = {
  126367. 2, 81,
  126368. _vq_lengthlist__8c0_s_p4_0,
  126369. 1, -531628032, 1611661312, 4, 0,
  126370. _vq_quantlist__8c0_s_p4_0,
  126371. NULL,
  126372. &_vq_auxt__8c0_s_p4_0,
  126373. NULL,
  126374. 0
  126375. };
  126376. static long _vq_quantlist__8c0_s_p5_0[] = {
  126377. 4,
  126378. 3,
  126379. 5,
  126380. 2,
  126381. 6,
  126382. 1,
  126383. 7,
  126384. 0,
  126385. 8,
  126386. };
  126387. static long _vq_lengthlist__8c0_s_p5_0[] = {
  126388. 1, 3, 3, 5, 5, 7, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  126389. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 9, 0, 0, 0, 8, 8,
  126390. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8, 9, 9, 0, 0, 0,
  126391. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  126392. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  126393. 10,
  126394. };
  126395. static float _vq_quantthresh__8c0_s_p5_0[] = {
  126396. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126397. };
  126398. static long _vq_quantmap__8c0_s_p5_0[] = {
  126399. 7, 5, 3, 1, 0, 2, 4, 6,
  126400. 8,
  126401. };
  126402. static encode_aux_threshmatch _vq_auxt__8c0_s_p5_0 = {
  126403. _vq_quantthresh__8c0_s_p5_0,
  126404. _vq_quantmap__8c0_s_p5_0,
  126405. 9,
  126406. 9
  126407. };
  126408. static static_codebook _8c0_s_p5_0 = {
  126409. 2, 81,
  126410. _vq_lengthlist__8c0_s_p5_0,
  126411. 1, -531628032, 1611661312, 4, 0,
  126412. _vq_quantlist__8c0_s_p5_0,
  126413. NULL,
  126414. &_vq_auxt__8c0_s_p5_0,
  126415. NULL,
  126416. 0
  126417. };
  126418. static long _vq_quantlist__8c0_s_p6_0[] = {
  126419. 8,
  126420. 7,
  126421. 9,
  126422. 6,
  126423. 10,
  126424. 5,
  126425. 11,
  126426. 4,
  126427. 12,
  126428. 3,
  126429. 13,
  126430. 2,
  126431. 14,
  126432. 1,
  126433. 15,
  126434. 0,
  126435. 16,
  126436. };
  126437. static long _vq_lengthlist__8c0_s_p6_0[] = {
  126438. 1, 3, 3, 6, 6, 8, 8, 9, 9, 8, 8,10, 9,10,10,11,
  126439. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  126440. 11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  126441. 11,12,11, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,10,10,
  126442. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,11,
  126443. 10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,10,
  126444. 11,11,11,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,
  126445. 10,11,11,12,12,13,13, 0, 0, 0,10,10,10,10,11,11,
  126446. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10, 9,10,
  126447. 11,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  126448. 10, 9,10,11,12,12,13,13,14,13, 0, 0, 0, 0, 0, 9,
  126449. 9, 9,10,10,10,11,11,13,12,13,13, 0, 0, 0, 0, 0,
  126450. 10,10,10,10,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  126451. 0, 0, 0,10,10,11,11,12,12,13,13,13,14, 0, 0, 0,
  126452. 0, 0, 0, 0,11,11,11,11,12,12,13,14,14,14, 0, 0,
  126453. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,14,13, 0,
  126454. 0, 0, 0, 0, 0, 0,11,11,12,12,13,13,14,14,14,14,
  126455. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  126456. 14,
  126457. };
  126458. static float _vq_quantthresh__8c0_s_p6_0[] = {
  126459. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  126460. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  126461. };
  126462. static long _vq_quantmap__8c0_s_p6_0[] = {
  126463. 15, 13, 11, 9, 7, 5, 3, 1,
  126464. 0, 2, 4, 6, 8, 10, 12, 14,
  126465. 16,
  126466. };
  126467. static encode_aux_threshmatch _vq_auxt__8c0_s_p6_0 = {
  126468. _vq_quantthresh__8c0_s_p6_0,
  126469. _vq_quantmap__8c0_s_p6_0,
  126470. 17,
  126471. 17
  126472. };
  126473. static static_codebook _8c0_s_p6_0 = {
  126474. 2, 289,
  126475. _vq_lengthlist__8c0_s_p6_0,
  126476. 1, -529530880, 1611661312, 5, 0,
  126477. _vq_quantlist__8c0_s_p6_0,
  126478. NULL,
  126479. &_vq_auxt__8c0_s_p6_0,
  126480. NULL,
  126481. 0
  126482. };
  126483. static long _vq_quantlist__8c0_s_p7_0[] = {
  126484. 1,
  126485. 0,
  126486. 2,
  126487. };
  126488. static long _vq_lengthlist__8c0_s_p7_0[] = {
  126489. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,11, 9,10,12,
  126490. 9,10, 4, 7, 7,10,10,10,11, 9, 9, 6,11,10,11,11,
  126491. 12,11,11,11, 6,10,10,11,11,12,11,10,10, 6, 9,10,
  126492. 11,11,11,11,10,10, 7,10,11,12,11,11,12,11,12, 6,
  126493. 9, 9,10, 9, 9,11,10,10, 6, 9, 9,10,10,10,11,10,
  126494. 10,
  126495. };
  126496. static float _vq_quantthresh__8c0_s_p7_0[] = {
  126497. -5.5, 5.5,
  126498. };
  126499. static long _vq_quantmap__8c0_s_p7_0[] = {
  126500. 1, 0, 2,
  126501. };
  126502. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_0 = {
  126503. _vq_quantthresh__8c0_s_p7_0,
  126504. _vq_quantmap__8c0_s_p7_0,
  126505. 3,
  126506. 3
  126507. };
  126508. static static_codebook _8c0_s_p7_0 = {
  126509. 4, 81,
  126510. _vq_lengthlist__8c0_s_p7_0,
  126511. 1, -529137664, 1618345984, 2, 0,
  126512. _vq_quantlist__8c0_s_p7_0,
  126513. NULL,
  126514. &_vq_auxt__8c0_s_p7_0,
  126515. NULL,
  126516. 0
  126517. };
  126518. static long _vq_quantlist__8c0_s_p7_1[] = {
  126519. 5,
  126520. 4,
  126521. 6,
  126522. 3,
  126523. 7,
  126524. 2,
  126525. 8,
  126526. 1,
  126527. 9,
  126528. 0,
  126529. 10,
  126530. };
  126531. static long _vq_lengthlist__8c0_s_p7_1[] = {
  126532. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10, 7, 7,
  126533. 8, 8, 9, 9, 9, 9,10,10, 9, 7, 7, 8, 8, 9, 9, 9,
  126534. 9,10,10,10, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10, 8,
  126535. 8, 9, 9, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9,10,
  126536. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,11,10,11,
  126537. 9, 9, 9, 9,10,10,10,10,11,11,11,10,10, 9, 9,10,
  126538. 10,10, 9,11,10,10,10,10,10,10, 9, 9,10,10,11,11,
  126539. 10,10,10, 9, 9, 9,10,10,10,
  126540. };
  126541. static float _vq_quantthresh__8c0_s_p7_1[] = {
  126542. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  126543. 3.5, 4.5,
  126544. };
  126545. static long _vq_quantmap__8c0_s_p7_1[] = {
  126546. 9, 7, 5, 3, 1, 0, 2, 4,
  126547. 6, 8, 10,
  126548. };
  126549. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_1 = {
  126550. _vq_quantthresh__8c0_s_p7_1,
  126551. _vq_quantmap__8c0_s_p7_1,
  126552. 11,
  126553. 11
  126554. };
  126555. static static_codebook _8c0_s_p7_1 = {
  126556. 2, 121,
  126557. _vq_lengthlist__8c0_s_p7_1,
  126558. 1, -531365888, 1611661312, 4, 0,
  126559. _vq_quantlist__8c0_s_p7_1,
  126560. NULL,
  126561. &_vq_auxt__8c0_s_p7_1,
  126562. NULL,
  126563. 0
  126564. };
  126565. static long _vq_quantlist__8c0_s_p8_0[] = {
  126566. 6,
  126567. 5,
  126568. 7,
  126569. 4,
  126570. 8,
  126571. 3,
  126572. 9,
  126573. 2,
  126574. 10,
  126575. 1,
  126576. 11,
  126577. 0,
  126578. 12,
  126579. };
  126580. static long _vq_lengthlist__8c0_s_p8_0[] = {
  126581. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 6, 6,
  126582. 7, 7, 8, 8, 7, 7, 8, 9,10,10, 7, 6, 6, 7, 7, 8,
  126583. 7, 7, 7, 9, 9,10,12, 0, 8, 8, 8, 8, 8, 9, 8, 8,
  126584. 9, 9,10,10, 0, 8, 8, 8, 8, 8, 9, 8, 9, 9, 9,11,
  126585. 10, 0, 0,13, 9, 8, 9, 9, 9, 9,10,10,11,11, 0,13,
  126586. 0, 9, 9, 9, 9, 9, 9,11,10,11,11, 0, 0, 0, 8, 9,
  126587. 10, 9,10,10,13,11,12,12, 0, 0, 0, 8, 9, 9, 9,10,
  126588. 10,13,12,12,13, 0, 0, 0,12, 0,10,10,12,11,10,11,
  126589. 12,12, 0, 0, 0,13,13,10,10,10,11,12, 0,13, 0, 0,
  126590. 0, 0, 0, 0,13,11, 0,12,12,12,13,12, 0, 0, 0, 0,
  126591. 0, 0,13,13,11,13,13,11,12,
  126592. };
  126593. static float _vq_quantthresh__8c0_s_p8_0[] = {
  126594. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  126595. 12.5, 17.5, 22.5, 27.5,
  126596. };
  126597. static long _vq_quantmap__8c0_s_p8_0[] = {
  126598. 11, 9, 7, 5, 3, 1, 0, 2,
  126599. 4, 6, 8, 10, 12,
  126600. };
  126601. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_0 = {
  126602. _vq_quantthresh__8c0_s_p8_0,
  126603. _vq_quantmap__8c0_s_p8_0,
  126604. 13,
  126605. 13
  126606. };
  126607. static static_codebook _8c0_s_p8_0 = {
  126608. 2, 169,
  126609. _vq_lengthlist__8c0_s_p8_0,
  126610. 1, -526516224, 1616117760, 4, 0,
  126611. _vq_quantlist__8c0_s_p8_0,
  126612. NULL,
  126613. &_vq_auxt__8c0_s_p8_0,
  126614. NULL,
  126615. 0
  126616. };
  126617. static long _vq_quantlist__8c0_s_p8_1[] = {
  126618. 2,
  126619. 1,
  126620. 3,
  126621. 0,
  126622. 4,
  126623. };
  126624. static long _vq_lengthlist__8c0_s_p8_1[] = {
  126625. 1, 3, 4, 5, 5, 7, 6, 6, 6, 5, 7, 7, 7, 6, 6, 7,
  126626. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  126627. };
  126628. static float _vq_quantthresh__8c0_s_p8_1[] = {
  126629. -1.5, -0.5, 0.5, 1.5,
  126630. };
  126631. static long _vq_quantmap__8c0_s_p8_1[] = {
  126632. 3, 1, 0, 2, 4,
  126633. };
  126634. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_1 = {
  126635. _vq_quantthresh__8c0_s_p8_1,
  126636. _vq_quantmap__8c0_s_p8_1,
  126637. 5,
  126638. 5
  126639. };
  126640. static static_codebook _8c0_s_p8_1 = {
  126641. 2, 25,
  126642. _vq_lengthlist__8c0_s_p8_1,
  126643. 1, -533725184, 1611661312, 3, 0,
  126644. _vq_quantlist__8c0_s_p8_1,
  126645. NULL,
  126646. &_vq_auxt__8c0_s_p8_1,
  126647. NULL,
  126648. 0
  126649. };
  126650. static long _vq_quantlist__8c0_s_p9_0[] = {
  126651. 1,
  126652. 0,
  126653. 2,
  126654. };
  126655. static long _vq_lengthlist__8c0_s_p9_0[] = {
  126656. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  126657. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  126658. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126659. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126660. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126661. 7,
  126662. };
  126663. static float _vq_quantthresh__8c0_s_p9_0[] = {
  126664. -157.5, 157.5,
  126665. };
  126666. static long _vq_quantmap__8c0_s_p9_0[] = {
  126667. 1, 0, 2,
  126668. };
  126669. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_0 = {
  126670. _vq_quantthresh__8c0_s_p9_0,
  126671. _vq_quantmap__8c0_s_p9_0,
  126672. 3,
  126673. 3
  126674. };
  126675. static static_codebook _8c0_s_p9_0 = {
  126676. 4, 81,
  126677. _vq_lengthlist__8c0_s_p9_0,
  126678. 1, -518803456, 1628680192, 2, 0,
  126679. _vq_quantlist__8c0_s_p9_0,
  126680. NULL,
  126681. &_vq_auxt__8c0_s_p9_0,
  126682. NULL,
  126683. 0
  126684. };
  126685. static long _vq_quantlist__8c0_s_p9_1[] = {
  126686. 7,
  126687. 6,
  126688. 8,
  126689. 5,
  126690. 9,
  126691. 4,
  126692. 10,
  126693. 3,
  126694. 11,
  126695. 2,
  126696. 12,
  126697. 1,
  126698. 13,
  126699. 0,
  126700. 14,
  126701. };
  126702. static long _vq_lengthlist__8c0_s_p9_1[] = {
  126703. 1, 4, 4, 5, 5,10, 8,11,11,11,11,11,11,11,11, 6,
  126704. 6, 6, 7, 6,11,10,11,11,11,11,11,11,11,11, 7, 5,
  126705. 6, 6, 6, 8, 7,11,11,11,11,11,11,11,11,11, 7, 8,
  126706. 8, 8, 9, 9,11,11,11,11,11,11,11,11,11, 9, 8, 7,
  126707. 8, 9,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  126708. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  126709. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126710. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126711. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126712. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126713. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126714. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126715. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126716. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126717. 11,
  126718. };
  126719. static float _vq_quantthresh__8c0_s_p9_1[] = {
  126720. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  126721. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  126722. };
  126723. static long _vq_quantmap__8c0_s_p9_1[] = {
  126724. 13, 11, 9, 7, 5, 3, 1, 0,
  126725. 2, 4, 6, 8, 10, 12, 14,
  126726. };
  126727. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_1 = {
  126728. _vq_quantthresh__8c0_s_p9_1,
  126729. _vq_quantmap__8c0_s_p9_1,
  126730. 15,
  126731. 15
  126732. };
  126733. static static_codebook _8c0_s_p9_1 = {
  126734. 2, 225,
  126735. _vq_lengthlist__8c0_s_p9_1,
  126736. 1, -520986624, 1620377600, 4, 0,
  126737. _vq_quantlist__8c0_s_p9_1,
  126738. NULL,
  126739. &_vq_auxt__8c0_s_p9_1,
  126740. NULL,
  126741. 0
  126742. };
  126743. static long _vq_quantlist__8c0_s_p9_2[] = {
  126744. 10,
  126745. 9,
  126746. 11,
  126747. 8,
  126748. 12,
  126749. 7,
  126750. 13,
  126751. 6,
  126752. 14,
  126753. 5,
  126754. 15,
  126755. 4,
  126756. 16,
  126757. 3,
  126758. 17,
  126759. 2,
  126760. 18,
  126761. 1,
  126762. 19,
  126763. 0,
  126764. 20,
  126765. };
  126766. static long _vq_lengthlist__8c0_s_p9_2[] = {
  126767. 1, 5, 5, 7, 7, 8, 7, 8, 8,10,10, 9, 9,10,10,10,
  126768. 11,11,10,12,11,12,12,12, 9, 8, 8, 8, 8, 8, 9,10,
  126769. 10,10,10,11,11,11,10,11,11,12,12,11,12, 8, 8, 7,
  126770. 7, 8, 9,10,10,10, 9,10,10, 9,10,10,11,11,11,11,
  126771. 11,11, 9, 9, 9, 9, 8, 9,10,10,11,10,10,11,11,12,
  126772. 10,10,12,12,11,11,10, 9, 9,10, 8, 9,10,10,10, 9,
  126773. 10,10,11,11,10,11,10,10,10,12,12,12, 9,10, 9,10,
  126774. 9, 9,10,10,11,11,11,11,10,10,10,11,12,11,12,11,
  126775. 12,10,11,10,11, 9,10, 9,10, 9,10,10, 9,10,10,11,
  126776. 10,11,11,11,11,12,11, 9,10,10,10,10,11,11,11,11,
  126777. 11,10,11,11,11,11,10,12,10,12,12,11,12,10,10,11,
  126778. 10, 9,11,10,11, 9,10,11,10,10,10,11,11,11,11,12,
  126779. 12,10, 9, 9,11,10, 9,12,11,10,12,12,11,11,11,11,
  126780. 10,11,11,12,11,10,12, 9,11,10,11,10,10,11,10,11,
  126781. 9,10,10,10,11,12,11,11,12,11,10,10,11,11, 9,10,
  126782. 10,12,10,11,10,10,10, 9,10,10,10,10, 9,10,10,11,
  126783. 11,11,11,12,11,10,10,10,10,11,11,10,11,11, 9,11,
  126784. 10,12,10,12,11,10,11,10,10,10,11,10,10,11,11,10,
  126785. 11,10,10,10,10,11,11,12,10,10,10,11,10,11,12,11,
  126786. 10,11,10,10,11,11,10,12,10, 9,10,10,11,11,11,10,
  126787. 12,10,10,11,11,11,10,10,11,10,10,10,11,10,11,10,
  126788. 12,11,11,10,10,10,12,10,10,11, 9,10,11,11,11,10,
  126789. 10,11,10,10, 9,11,11,12,12,11,12,11,11,11,11,11,
  126790. 11, 9,10,11,10,12,10,10,10,10,11,10,10,11,10,10,
  126791. 12,10,10,10,10,10, 9,12,10,10,10,10,12, 9,11,10,
  126792. 10,11,10,12,12,10,12,12,12,10,10,10,10, 9,10,11,
  126793. 10,10,12,10,10,12,11,10,11,10,10,12,11,10,12,10,
  126794. 10,11, 9,11,10, 9,10, 9,10,
  126795. };
  126796. static float _vq_quantthresh__8c0_s_p9_2[] = {
  126797. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  126798. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  126799. 6.5, 7.5, 8.5, 9.5,
  126800. };
  126801. static long _vq_quantmap__8c0_s_p9_2[] = {
  126802. 19, 17, 15, 13, 11, 9, 7, 5,
  126803. 3, 1, 0, 2, 4, 6, 8, 10,
  126804. 12, 14, 16, 18, 20,
  126805. };
  126806. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_2 = {
  126807. _vq_quantthresh__8c0_s_p9_2,
  126808. _vq_quantmap__8c0_s_p9_2,
  126809. 21,
  126810. 21
  126811. };
  126812. static static_codebook _8c0_s_p9_2 = {
  126813. 2, 441,
  126814. _vq_lengthlist__8c0_s_p9_2,
  126815. 1, -529268736, 1611661312, 5, 0,
  126816. _vq_quantlist__8c0_s_p9_2,
  126817. NULL,
  126818. &_vq_auxt__8c0_s_p9_2,
  126819. NULL,
  126820. 0
  126821. };
  126822. static long _huff_lengthlist__8c0_s_single[] = {
  126823. 4, 5,18, 7,10, 6, 7, 8, 9,10, 5, 2,18, 5, 7, 5,
  126824. 6, 7, 8,11,17,17,17,17,17,17,17,17,17,17, 7, 4,
  126825. 17, 6, 9, 6, 8,10,12,15,11, 7,17, 9, 6, 6, 7, 9,
  126826. 11,15, 6, 4,17, 6, 6, 4, 5, 8,11,16, 6, 6,17, 8,
  126827. 6, 5, 6, 9,13,16, 8, 9,17,11, 9, 8, 8,11,13,17,
  126828. 9,12,17,15,14,13,12,13,14,17,12,15,17,17,17,17,
  126829. 17,16,17,17,
  126830. };
  126831. static static_codebook _huff_book__8c0_s_single = {
  126832. 2, 100,
  126833. _huff_lengthlist__8c0_s_single,
  126834. 0, 0, 0, 0, 0,
  126835. NULL,
  126836. NULL,
  126837. NULL,
  126838. NULL,
  126839. 0
  126840. };
  126841. static long _vq_quantlist__8c1_s_p1_0[] = {
  126842. 1,
  126843. 0,
  126844. 2,
  126845. };
  126846. static long _vq_lengthlist__8c1_s_p1_0[] = {
  126847. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  126848. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126852. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  126853. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126857. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  126858. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  126893. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  126894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  126898. 0, 0, 0, 8, 8,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  126899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  126903. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  126904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126938. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  126939. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126943. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  126944. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  126945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126948. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  126949. 0, 0, 0, 0, 0, 0, 8,10, 8, 0, 0, 0, 0, 0, 0, 0,
  126950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  127012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127015. 0, 0, 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, 0, 0, 0, 0, 0, 0,
  127017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127020. 0, 0, 0, 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, 0, 0, 0, 0, 0,
  127022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127025. 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127257. 0,
  127258. };
  127259. static float _vq_quantthresh__8c1_s_p1_0[] = {
  127260. -0.5, 0.5,
  127261. };
  127262. static long _vq_quantmap__8c1_s_p1_0[] = {
  127263. 1, 0, 2,
  127264. };
  127265. static encode_aux_threshmatch _vq_auxt__8c1_s_p1_0 = {
  127266. _vq_quantthresh__8c1_s_p1_0,
  127267. _vq_quantmap__8c1_s_p1_0,
  127268. 3,
  127269. 3
  127270. };
  127271. static static_codebook _8c1_s_p1_0 = {
  127272. 8, 6561,
  127273. _vq_lengthlist__8c1_s_p1_0,
  127274. 1, -535822336, 1611661312, 2, 0,
  127275. _vq_quantlist__8c1_s_p1_0,
  127276. NULL,
  127277. &_vq_auxt__8c1_s_p1_0,
  127278. NULL,
  127279. 0
  127280. };
  127281. static long _vq_quantlist__8c1_s_p2_0[] = {
  127282. 2,
  127283. 1,
  127284. 3,
  127285. 0,
  127286. 4,
  127287. };
  127288. static long _vq_lengthlist__8c1_s_p2_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,
  127329. };
  127330. static float _vq_quantthresh__8c1_s_p2_0[] = {
  127331. -1.5, -0.5, 0.5, 1.5,
  127332. };
  127333. static long _vq_quantmap__8c1_s_p2_0[] = {
  127334. 3, 1, 0, 2, 4,
  127335. };
  127336. static encode_aux_threshmatch _vq_auxt__8c1_s_p2_0 = {
  127337. _vq_quantthresh__8c1_s_p2_0,
  127338. _vq_quantmap__8c1_s_p2_0,
  127339. 5,
  127340. 5
  127341. };
  127342. static static_codebook _8c1_s_p2_0 = {
  127343. 4, 625,
  127344. _vq_lengthlist__8c1_s_p2_0,
  127345. 1, -533725184, 1611661312, 3, 0,
  127346. _vq_quantlist__8c1_s_p2_0,
  127347. NULL,
  127348. &_vq_auxt__8c1_s_p2_0,
  127349. NULL,
  127350. 0
  127351. };
  127352. static long _vq_quantlist__8c1_s_p3_0[] = {
  127353. 2,
  127354. 1,
  127355. 3,
  127356. 0,
  127357. 4,
  127358. };
  127359. static long _vq_lengthlist__8c1_s_p3_0[] = {
  127360. 2, 4, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  127362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127363. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 7, 7,
  127365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127366. 0, 0, 0, 0, 6, 6, 6, 7, 7, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127399. 0,
  127400. };
  127401. static float _vq_quantthresh__8c1_s_p3_0[] = {
  127402. -1.5, -0.5, 0.5, 1.5,
  127403. };
  127404. static long _vq_quantmap__8c1_s_p3_0[] = {
  127405. 3, 1, 0, 2, 4,
  127406. };
  127407. static encode_aux_threshmatch _vq_auxt__8c1_s_p3_0 = {
  127408. _vq_quantthresh__8c1_s_p3_0,
  127409. _vq_quantmap__8c1_s_p3_0,
  127410. 5,
  127411. 5
  127412. };
  127413. static static_codebook _8c1_s_p3_0 = {
  127414. 4, 625,
  127415. _vq_lengthlist__8c1_s_p3_0,
  127416. 1, -533725184, 1611661312, 3, 0,
  127417. _vq_quantlist__8c1_s_p3_0,
  127418. NULL,
  127419. &_vq_auxt__8c1_s_p3_0,
  127420. NULL,
  127421. 0
  127422. };
  127423. static long _vq_quantlist__8c1_s_p4_0[] = {
  127424. 4,
  127425. 3,
  127426. 5,
  127427. 2,
  127428. 6,
  127429. 1,
  127430. 7,
  127431. 0,
  127432. 8,
  127433. };
  127434. static long _vq_lengthlist__8c1_s_p4_0[] = {
  127435. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  127436. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  127437. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  127438. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  127439. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127440. 0,
  127441. };
  127442. static float _vq_quantthresh__8c1_s_p4_0[] = {
  127443. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127444. };
  127445. static long _vq_quantmap__8c1_s_p4_0[] = {
  127446. 7, 5, 3, 1, 0, 2, 4, 6,
  127447. 8,
  127448. };
  127449. static encode_aux_threshmatch _vq_auxt__8c1_s_p4_0 = {
  127450. _vq_quantthresh__8c1_s_p4_0,
  127451. _vq_quantmap__8c1_s_p4_0,
  127452. 9,
  127453. 9
  127454. };
  127455. static static_codebook _8c1_s_p4_0 = {
  127456. 2, 81,
  127457. _vq_lengthlist__8c1_s_p4_0,
  127458. 1, -531628032, 1611661312, 4, 0,
  127459. _vq_quantlist__8c1_s_p4_0,
  127460. NULL,
  127461. &_vq_auxt__8c1_s_p4_0,
  127462. NULL,
  127463. 0
  127464. };
  127465. static long _vq_quantlist__8c1_s_p5_0[] = {
  127466. 4,
  127467. 3,
  127468. 5,
  127469. 2,
  127470. 6,
  127471. 1,
  127472. 7,
  127473. 0,
  127474. 8,
  127475. };
  127476. static long _vq_lengthlist__8c1_s_p5_0[] = {
  127477. 1, 3, 3, 4, 5, 6, 6, 8, 8, 0, 0, 0, 8, 8, 7, 7,
  127478. 9, 9, 0, 0, 0, 8, 8, 7, 7, 9, 9, 0, 0, 0, 9,10,
  127479. 8, 8, 9, 9, 0, 0, 0,10,10, 8, 8, 9, 9, 0, 0, 0,
  127480. 11,10, 8, 8,10,10, 0, 0, 0,11,11, 8, 8,10,10, 0,
  127481. 0, 0,12,12, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  127482. 10,
  127483. };
  127484. static float _vq_quantthresh__8c1_s_p5_0[] = {
  127485. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127486. };
  127487. static long _vq_quantmap__8c1_s_p5_0[] = {
  127488. 7, 5, 3, 1, 0, 2, 4, 6,
  127489. 8,
  127490. };
  127491. static encode_aux_threshmatch _vq_auxt__8c1_s_p5_0 = {
  127492. _vq_quantthresh__8c1_s_p5_0,
  127493. _vq_quantmap__8c1_s_p5_0,
  127494. 9,
  127495. 9
  127496. };
  127497. static static_codebook _8c1_s_p5_0 = {
  127498. 2, 81,
  127499. _vq_lengthlist__8c1_s_p5_0,
  127500. 1, -531628032, 1611661312, 4, 0,
  127501. _vq_quantlist__8c1_s_p5_0,
  127502. NULL,
  127503. &_vq_auxt__8c1_s_p5_0,
  127504. NULL,
  127505. 0
  127506. };
  127507. static long _vq_quantlist__8c1_s_p6_0[] = {
  127508. 8,
  127509. 7,
  127510. 9,
  127511. 6,
  127512. 10,
  127513. 5,
  127514. 11,
  127515. 4,
  127516. 12,
  127517. 3,
  127518. 13,
  127519. 2,
  127520. 14,
  127521. 1,
  127522. 15,
  127523. 0,
  127524. 16,
  127525. };
  127526. static long _vq_lengthlist__8c1_s_p6_0[] = {
  127527. 1, 3, 3, 5, 5, 8, 8, 8, 8, 9, 9,10,10,11,11,11,
  127528. 11, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11,
  127529. 12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  127530. 11,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,11,
  127531. 12,12,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,
  127532. 11,12,12,12,12, 0, 0, 0,10,10, 9, 9,10,10,10,10,
  127533. 11,11,12,12,13,13, 0, 0, 0,10,10, 9, 9,10,10,10,
  127534. 10,11,11,12,12,13,13, 0, 0, 0,11,11, 9, 9,10,10,
  127535. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  127536. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  127537. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  127538. 9,10,10,11,11,12,11,12,12,13,13, 0, 0, 0, 0, 0,
  127539. 10,10,11,11,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  127540. 0, 0, 0,11,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  127541. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  127542. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,13, 0,
  127543. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  127544. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  127545. 14,
  127546. };
  127547. static float _vq_quantthresh__8c1_s_p6_0[] = {
  127548. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  127549. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  127550. };
  127551. static long _vq_quantmap__8c1_s_p6_0[] = {
  127552. 15, 13, 11, 9, 7, 5, 3, 1,
  127553. 0, 2, 4, 6, 8, 10, 12, 14,
  127554. 16,
  127555. };
  127556. static encode_aux_threshmatch _vq_auxt__8c1_s_p6_0 = {
  127557. _vq_quantthresh__8c1_s_p6_0,
  127558. _vq_quantmap__8c1_s_p6_0,
  127559. 17,
  127560. 17
  127561. };
  127562. static static_codebook _8c1_s_p6_0 = {
  127563. 2, 289,
  127564. _vq_lengthlist__8c1_s_p6_0,
  127565. 1, -529530880, 1611661312, 5, 0,
  127566. _vq_quantlist__8c1_s_p6_0,
  127567. NULL,
  127568. &_vq_auxt__8c1_s_p6_0,
  127569. NULL,
  127570. 0
  127571. };
  127572. static long _vq_quantlist__8c1_s_p7_0[] = {
  127573. 1,
  127574. 0,
  127575. 2,
  127576. };
  127577. static long _vq_lengthlist__8c1_s_p7_0[] = {
  127578. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  127579. 9, 9, 5, 7, 7,10, 9, 9,10, 9, 9, 6,10,10,10,10,
  127580. 10,11,10,10, 6, 9, 9,10, 9,10,11,10,10, 6, 9, 9,
  127581. 10, 9, 9,11, 9,10, 7,10,10,11,11,11,11,10,10, 6,
  127582. 9, 9,10,10,10,11, 9, 9, 6, 9, 9,10,10,10,10, 9,
  127583. 9,
  127584. };
  127585. static float _vq_quantthresh__8c1_s_p7_0[] = {
  127586. -5.5, 5.5,
  127587. };
  127588. static long _vq_quantmap__8c1_s_p7_0[] = {
  127589. 1, 0, 2,
  127590. };
  127591. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_0 = {
  127592. _vq_quantthresh__8c1_s_p7_0,
  127593. _vq_quantmap__8c1_s_p7_0,
  127594. 3,
  127595. 3
  127596. };
  127597. static static_codebook _8c1_s_p7_0 = {
  127598. 4, 81,
  127599. _vq_lengthlist__8c1_s_p7_0,
  127600. 1, -529137664, 1618345984, 2, 0,
  127601. _vq_quantlist__8c1_s_p7_0,
  127602. NULL,
  127603. &_vq_auxt__8c1_s_p7_0,
  127604. NULL,
  127605. 0
  127606. };
  127607. static long _vq_quantlist__8c1_s_p7_1[] = {
  127608. 5,
  127609. 4,
  127610. 6,
  127611. 3,
  127612. 7,
  127613. 2,
  127614. 8,
  127615. 1,
  127616. 9,
  127617. 0,
  127618. 10,
  127619. };
  127620. static long _vq_lengthlist__8c1_s_p7_1[] = {
  127621. 2, 3, 3, 5, 5, 7, 7, 7, 7, 7, 7,10,10, 9, 7, 7,
  127622. 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8,
  127623. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  127624. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  127625. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  127626. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  127627. 8, 8, 8,10,10,10,10,10, 8, 8, 8, 8, 8, 8,10,10,
  127628. 10,10,10, 8, 8, 8, 8, 8, 8,
  127629. };
  127630. static float _vq_quantthresh__8c1_s_p7_1[] = {
  127631. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  127632. 3.5, 4.5,
  127633. };
  127634. static long _vq_quantmap__8c1_s_p7_1[] = {
  127635. 9, 7, 5, 3, 1, 0, 2, 4,
  127636. 6, 8, 10,
  127637. };
  127638. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_1 = {
  127639. _vq_quantthresh__8c1_s_p7_1,
  127640. _vq_quantmap__8c1_s_p7_1,
  127641. 11,
  127642. 11
  127643. };
  127644. static static_codebook _8c1_s_p7_1 = {
  127645. 2, 121,
  127646. _vq_lengthlist__8c1_s_p7_1,
  127647. 1, -531365888, 1611661312, 4, 0,
  127648. _vq_quantlist__8c1_s_p7_1,
  127649. NULL,
  127650. &_vq_auxt__8c1_s_p7_1,
  127651. NULL,
  127652. 0
  127653. };
  127654. static long _vq_quantlist__8c1_s_p8_0[] = {
  127655. 6,
  127656. 5,
  127657. 7,
  127658. 4,
  127659. 8,
  127660. 3,
  127661. 9,
  127662. 2,
  127663. 10,
  127664. 1,
  127665. 11,
  127666. 0,
  127667. 12,
  127668. };
  127669. static long _vq_lengthlist__8c1_s_p8_0[] = {
  127670. 1, 4, 4, 6, 6, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5,
  127671. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  127672. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  127673. 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  127674. 11, 0,12,12, 9, 9, 9, 9,10, 9,10,11,11,11, 0,13,
  127675. 12, 9, 8, 9, 9,10,10,11,11,12,11, 0, 0, 0, 9, 9,
  127676. 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10, 9, 9,10,
  127677. 10,11,11,12,12, 0, 0, 0,13,13,10,10,11,11,12,11,
  127678. 13,12, 0, 0, 0,14,14,10,10,11,10,11,11,12,12, 0,
  127679. 0, 0, 0, 0,12,12,11,11,12,12,13,13, 0, 0, 0, 0,
  127680. 0,12,12,11,10,12,11,13,12,
  127681. };
  127682. static float _vq_quantthresh__8c1_s_p8_0[] = {
  127683. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  127684. 12.5, 17.5, 22.5, 27.5,
  127685. };
  127686. static long _vq_quantmap__8c1_s_p8_0[] = {
  127687. 11, 9, 7, 5, 3, 1, 0, 2,
  127688. 4, 6, 8, 10, 12,
  127689. };
  127690. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_0 = {
  127691. _vq_quantthresh__8c1_s_p8_0,
  127692. _vq_quantmap__8c1_s_p8_0,
  127693. 13,
  127694. 13
  127695. };
  127696. static static_codebook _8c1_s_p8_0 = {
  127697. 2, 169,
  127698. _vq_lengthlist__8c1_s_p8_0,
  127699. 1, -526516224, 1616117760, 4, 0,
  127700. _vq_quantlist__8c1_s_p8_0,
  127701. NULL,
  127702. &_vq_auxt__8c1_s_p8_0,
  127703. NULL,
  127704. 0
  127705. };
  127706. static long _vq_quantlist__8c1_s_p8_1[] = {
  127707. 2,
  127708. 1,
  127709. 3,
  127710. 0,
  127711. 4,
  127712. };
  127713. static long _vq_lengthlist__8c1_s_p8_1[] = {
  127714. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  127715. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  127716. };
  127717. static float _vq_quantthresh__8c1_s_p8_1[] = {
  127718. -1.5, -0.5, 0.5, 1.5,
  127719. };
  127720. static long _vq_quantmap__8c1_s_p8_1[] = {
  127721. 3, 1, 0, 2, 4,
  127722. };
  127723. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_1 = {
  127724. _vq_quantthresh__8c1_s_p8_1,
  127725. _vq_quantmap__8c1_s_p8_1,
  127726. 5,
  127727. 5
  127728. };
  127729. static static_codebook _8c1_s_p8_1 = {
  127730. 2, 25,
  127731. _vq_lengthlist__8c1_s_p8_1,
  127732. 1, -533725184, 1611661312, 3, 0,
  127733. _vq_quantlist__8c1_s_p8_1,
  127734. NULL,
  127735. &_vq_auxt__8c1_s_p8_1,
  127736. NULL,
  127737. 0
  127738. };
  127739. static long _vq_quantlist__8c1_s_p9_0[] = {
  127740. 6,
  127741. 5,
  127742. 7,
  127743. 4,
  127744. 8,
  127745. 3,
  127746. 9,
  127747. 2,
  127748. 10,
  127749. 1,
  127750. 11,
  127751. 0,
  127752. 12,
  127753. };
  127754. static long _vq_lengthlist__8c1_s_p9_0[] = {
  127755. 1, 3, 3,10,10,10,10,10,10,10,10,10,10, 5, 6, 6,
  127756. 10,10,10,10,10,10,10,10,10,10, 6, 7, 8,10,10,10,
  127757. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127758. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127759. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127760. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127761. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127762. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127763. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127764. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127765. 10,10,10,10,10, 9, 9, 9, 9,
  127766. };
  127767. static float _vq_quantthresh__8c1_s_p9_0[] = {
  127768. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  127769. 787.5, 1102.5, 1417.5, 1732.5,
  127770. };
  127771. static long _vq_quantmap__8c1_s_p9_0[] = {
  127772. 11, 9, 7, 5, 3, 1, 0, 2,
  127773. 4, 6, 8, 10, 12,
  127774. };
  127775. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_0 = {
  127776. _vq_quantthresh__8c1_s_p9_0,
  127777. _vq_quantmap__8c1_s_p9_0,
  127778. 13,
  127779. 13
  127780. };
  127781. static static_codebook _8c1_s_p9_0 = {
  127782. 2, 169,
  127783. _vq_lengthlist__8c1_s_p9_0,
  127784. 1, -513964032, 1628680192, 4, 0,
  127785. _vq_quantlist__8c1_s_p9_0,
  127786. NULL,
  127787. &_vq_auxt__8c1_s_p9_0,
  127788. NULL,
  127789. 0
  127790. };
  127791. static long _vq_quantlist__8c1_s_p9_1[] = {
  127792. 7,
  127793. 6,
  127794. 8,
  127795. 5,
  127796. 9,
  127797. 4,
  127798. 10,
  127799. 3,
  127800. 11,
  127801. 2,
  127802. 12,
  127803. 1,
  127804. 13,
  127805. 0,
  127806. 14,
  127807. };
  127808. static long _vq_lengthlist__8c1_s_p9_1[] = {
  127809. 1, 4, 4, 5, 5, 7, 7, 9, 9,11,11,12,12,13,13, 6,
  127810. 5, 5, 6, 6, 9, 9,10,10,12,12,12,13,15,14, 6, 5,
  127811. 5, 7, 7, 9, 9,10,10,12,12,12,13,14,13,17, 7, 7,
  127812. 8, 8,10,10,11,11,12,13,13,13,13,13,17, 7, 7, 8,
  127813. 8,10,10,11,11,13,13,13,13,14,14,17,11,11, 9, 9,
  127814. 11,11,12,12,12,13,13,14,15,13,17,12,12, 9, 9,11,
  127815. 11,12,12,13,13,13,13,14,16,17,17,17,11,12,12,12,
  127816. 13,13,13,14,15,14,15,15,17,17,17,12,12,11,11,13,
  127817. 13,14,14,15,14,15,15,17,17,17,15,15,13,13,14,14,
  127818. 15,14,15,15,16,15,17,17,17,15,15,13,13,13,14,14,
  127819. 15,15,15,15,16,17,17,17,17,16,14,15,14,14,15,14,
  127820. 14,15,15,15,17,17,17,17,17,14,14,16,14,15,15,15,
  127821. 15,15,15,17,17,17,17,17,17,16,16,15,17,15,15,14,
  127822. 17,15,17,16,17,17,17,17,16,15,14,15,15,15,15,15,
  127823. 15,
  127824. };
  127825. static float _vq_quantthresh__8c1_s_p9_1[] = {
  127826. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  127827. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  127828. };
  127829. static long _vq_quantmap__8c1_s_p9_1[] = {
  127830. 13, 11, 9, 7, 5, 3, 1, 0,
  127831. 2, 4, 6, 8, 10, 12, 14,
  127832. };
  127833. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_1 = {
  127834. _vq_quantthresh__8c1_s_p9_1,
  127835. _vq_quantmap__8c1_s_p9_1,
  127836. 15,
  127837. 15
  127838. };
  127839. static static_codebook _8c1_s_p9_1 = {
  127840. 2, 225,
  127841. _vq_lengthlist__8c1_s_p9_1,
  127842. 1, -520986624, 1620377600, 4, 0,
  127843. _vq_quantlist__8c1_s_p9_1,
  127844. NULL,
  127845. &_vq_auxt__8c1_s_p9_1,
  127846. NULL,
  127847. 0
  127848. };
  127849. static long _vq_quantlist__8c1_s_p9_2[] = {
  127850. 10,
  127851. 9,
  127852. 11,
  127853. 8,
  127854. 12,
  127855. 7,
  127856. 13,
  127857. 6,
  127858. 14,
  127859. 5,
  127860. 15,
  127861. 4,
  127862. 16,
  127863. 3,
  127864. 17,
  127865. 2,
  127866. 18,
  127867. 1,
  127868. 19,
  127869. 0,
  127870. 20,
  127871. };
  127872. static long _vq_lengthlist__8c1_s_p9_2[] = {
  127873. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  127874. 9, 9, 9, 9, 9,11,11,12, 7, 7, 7, 7, 8, 8, 9, 9,
  127875. 9, 9,10,10,10,10,10,10,10,10,11,11,11, 7, 7, 7,
  127876. 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,11,
  127877. 11,12, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,
  127878. 10,10,10,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  127879. 9,10,10,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  127880. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,11,11,
  127881. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  127882. 10,10,10,11,12,11, 9, 9, 8, 9, 9, 9, 9, 9,10,10,
  127883. 10,10,10,10,10,10,10,10,11,11,11,11,11, 8, 8, 9,
  127884. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,11,12,11,
  127885. 12,11, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  127886. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  127887. 10,10,10,10,10,10,10,12,11,12,11,11, 9, 9, 9,10,
  127888. 10,10,10,10,10,10,10,10,10,10,10,10,12,11,11,11,
  127889. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127890. 11,11,11,12,11,11,12,11,10,10,10,10,10,10,10,10,
  127891. 10,10,10,10,11,10,11,11,11,11,11,11,11,10,10,10,
  127892. 10,10,10,10,10,10,10,10,10,10,10,11,11,12,11,12,
  127893. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127894. 11,11,12,11,12,11,11,11,11,10,10,10,10,10,10,10,
  127895. 10,10,10,10,10,11,11,12,11,11,12,11,11,12,10,10,
  127896. 11,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  127897. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,12,
  127898. 12,11,12,11,11,12,12,12,11,11,10,10,10,10,10,10,
  127899. 10,10,10,11,12,12,11,12,12,11,12,11,11,11,11,10,
  127900. 10,10,10,10,10,10,10,10,10,
  127901. };
  127902. static float _vq_quantthresh__8c1_s_p9_2[] = {
  127903. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  127904. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  127905. 6.5, 7.5, 8.5, 9.5,
  127906. };
  127907. static long _vq_quantmap__8c1_s_p9_2[] = {
  127908. 19, 17, 15, 13, 11, 9, 7, 5,
  127909. 3, 1, 0, 2, 4, 6, 8, 10,
  127910. 12, 14, 16, 18, 20,
  127911. };
  127912. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_2 = {
  127913. _vq_quantthresh__8c1_s_p9_2,
  127914. _vq_quantmap__8c1_s_p9_2,
  127915. 21,
  127916. 21
  127917. };
  127918. static static_codebook _8c1_s_p9_2 = {
  127919. 2, 441,
  127920. _vq_lengthlist__8c1_s_p9_2,
  127921. 1, -529268736, 1611661312, 5, 0,
  127922. _vq_quantlist__8c1_s_p9_2,
  127923. NULL,
  127924. &_vq_auxt__8c1_s_p9_2,
  127925. NULL,
  127926. 0
  127927. };
  127928. static long _huff_lengthlist__8c1_s_single[] = {
  127929. 4, 6,18, 8,11, 8, 8, 9, 9,10, 4, 4,18, 5, 9, 5,
  127930. 6, 7, 8,10,18,18,18,18,17,17,17,17,17,17, 7, 5,
  127931. 17, 6,11, 6, 7, 8, 9,12,12, 9,17,12, 8, 8, 9,10,
  127932. 10,13, 7, 5,17, 6, 8, 4, 5, 6, 8,10, 6, 5,17, 6,
  127933. 8, 5, 4, 5, 7, 9, 7, 7,17, 8, 9, 6, 5, 5, 6, 8,
  127934. 8, 8,17, 9,11, 8, 6, 6, 6, 7, 9,10,17,12,12,10,
  127935. 9, 7, 7, 8,
  127936. };
  127937. static static_codebook _huff_book__8c1_s_single = {
  127938. 2, 100,
  127939. _huff_lengthlist__8c1_s_single,
  127940. 0, 0, 0, 0, 0,
  127941. NULL,
  127942. NULL,
  127943. NULL,
  127944. NULL,
  127945. 0
  127946. };
  127947. static long _huff_lengthlist__44c2_s_long[] = {
  127948. 6, 6,12,10,10,10, 9,10,12,12, 6, 1,10, 5, 6, 6,
  127949. 7, 9,11,14,12, 9, 8,11, 7, 8, 9,11,13,15,10, 5,
  127950. 12, 7, 8, 7, 9,12,14,15,10, 6, 7, 8, 5, 6, 7, 9,
  127951. 12,14, 9, 6, 8, 7, 6, 6, 7, 9,12,12, 9, 7, 9, 9,
  127952. 7, 6, 6, 7,10,10,10, 9,10,11, 8, 7, 6, 6, 8,10,
  127953. 12,11,13,13,11,10, 8, 8, 8,10,11,13,15,15,14,13,
  127954. 10, 8, 8, 9,
  127955. };
  127956. static static_codebook _huff_book__44c2_s_long = {
  127957. 2, 100,
  127958. _huff_lengthlist__44c2_s_long,
  127959. 0, 0, 0, 0, 0,
  127960. NULL,
  127961. NULL,
  127962. NULL,
  127963. NULL,
  127964. 0
  127965. };
  127966. static long _vq_quantlist__44c2_s_p1_0[] = {
  127967. 1,
  127968. 0,
  127969. 2,
  127970. };
  127971. static long _vq_lengthlist__44c2_s_p1_0[] = {
  127972. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  127973. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127977. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  127978. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127982. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  127983. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  128018. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  128019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  128023. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  128024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  128028. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  128029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128063. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  128064. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128068. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  128069. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  128070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128073. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  128074. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  128075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128164. 0, 0, 0, 0, 0, 0, 0, 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. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128172. 0, 0, 0, 0, 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, 0,
  128177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128382. 0,
  128383. };
  128384. static float _vq_quantthresh__44c2_s_p1_0[] = {
  128385. -0.5, 0.5,
  128386. };
  128387. static long _vq_quantmap__44c2_s_p1_0[] = {
  128388. 1, 0, 2,
  128389. };
  128390. static encode_aux_threshmatch _vq_auxt__44c2_s_p1_0 = {
  128391. _vq_quantthresh__44c2_s_p1_0,
  128392. _vq_quantmap__44c2_s_p1_0,
  128393. 3,
  128394. 3
  128395. };
  128396. static static_codebook _44c2_s_p1_0 = {
  128397. 8, 6561,
  128398. _vq_lengthlist__44c2_s_p1_0,
  128399. 1, -535822336, 1611661312, 2, 0,
  128400. _vq_quantlist__44c2_s_p1_0,
  128401. NULL,
  128402. &_vq_auxt__44c2_s_p1_0,
  128403. NULL,
  128404. 0
  128405. };
  128406. static long _vq_quantlist__44c2_s_p2_0[] = {
  128407. 2,
  128408. 1,
  128409. 3,
  128410. 0,
  128411. 4,
  128412. };
  128413. static long _vq_lengthlist__44c2_s_p2_0[] = {
  128414. 1, 4, 4, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0,
  128415. 8, 8, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  128416. 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  128417. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0,
  128418. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128423. 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,11,11, 0, 0,
  128424. 0,11,11, 0, 0, 0,12,11, 0, 0, 0, 0, 0, 0, 0, 7,
  128425. 8, 8, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0, 0,11,
  128426. 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128431. 0, 0, 0, 6, 8, 8, 0, 0, 0,11,11, 0, 0, 0,11,11,
  128432. 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0,
  128433. 0, 0,10,11, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0,
  128434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128439. 8, 9, 9, 0, 0, 0,11,12, 0, 0, 0,11,12, 0, 0, 0,
  128440. 12,11, 0, 0, 0, 0, 0, 0, 0, 8,10, 9, 0, 0, 0,12,
  128441. 11, 0, 0, 0,12,11, 0, 0, 0,11,12, 0, 0, 0, 0, 0,
  128442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128453. 0,
  128454. };
  128455. static float _vq_quantthresh__44c2_s_p2_0[] = {
  128456. -1.5, -0.5, 0.5, 1.5,
  128457. };
  128458. static long _vq_quantmap__44c2_s_p2_0[] = {
  128459. 3, 1, 0, 2, 4,
  128460. };
  128461. static encode_aux_threshmatch _vq_auxt__44c2_s_p2_0 = {
  128462. _vq_quantthresh__44c2_s_p2_0,
  128463. _vq_quantmap__44c2_s_p2_0,
  128464. 5,
  128465. 5
  128466. };
  128467. static static_codebook _44c2_s_p2_0 = {
  128468. 4, 625,
  128469. _vq_lengthlist__44c2_s_p2_0,
  128470. 1, -533725184, 1611661312, 3, 0,
  128471. _vq_quantlist__44c2_s_p2_0,
  128472. NULL,
  128473. &_vq_auxt__44c2_s_p2_0,
  128474. NULL,
  128475. 0
  128476. };
  128477. static long _vq_quantlist__44c2_s_p3_0[] = {
  128478. 2,
  128479. 1,
  128480. 3,
  128481. 0,
  128482. 4,
  128483. };
  128484. static long _vq_lengthlist__44c2_s_p3_0[] = {
  128485. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  128487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128488. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  128490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128491. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  128492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128524. 0,
  128525. };
  128526. static float _vq_quantthresh__44c2_s_p3_0[] = {
  128527. -1.5, -0.5, 0.5, 1.5,
  128528. };
  128529. static long _vq_quantmap__44c2_s_p3_0[] = {
  128530. 3, 1, 0, 2, 4,
  128531. };
  128532. static encode_aux_threshmatch _vq_auxt__44c2_s_p3_0 = {
  128533. _vq_quantthresh__44c2_s_p3_0,
  128534. _vq_quantmap__44c2_s_p3_0,
  128535. 5,
  128536. 5
  128537. };
  128538. static static_codebook _44c2_s_p3_0 = {
  128539. 4, 625,
  128540. _vq_lengthlist__44c2_s_p3_0,
  128541. 1, -533725184, 1611661312, 3, 0,
  128542. _vq_quantlist__44c2_s_p3_0,
  128543. NULL,
  128544. &_vq_auxt__44c2_s_p3_0,
  128545. NULL,
  128546. 0
  128547. };
  128548. static long _vq_quantlist__44c2_s_p4_0[] = {
  128549. 4,
  128550. 3,
  128551. 5,
  128552. 2,
  128553. 6,
  128554. 1,
  128555. 7,
  128556. 0,
  128557. 8,
  128558. };
  128559. static long _vq_lengthlist__44c2_s_p4_0[] = {
  128560. 1, 3, 3, 6, 6, 0, 0, 0, 0, 0, 6, 6, 6, 6, 0, 0,
  128561. 0, 0, 0, 6, 6, 6, 6, 0, 0, 0, 0, 0, 7, 7, 6, 6,
  128562. 0, 0, 0, 0, 0, 0, 0, 6, 7, 0, 0, 0, 0, 0, 0, 0,
  128563. 7, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  128564. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128565. 0,
  128566. };
  128567. static float _vq_quantthresh__44c2_s_p4_0[] = {
  128568. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128569. };
  128570. static long _vq_quantmap__44c2_s_p4_0[] = {
  128571. 7, 5, 3, 1, 0, 2, 4, 6,
  128572. 8,
  128573. };
  128574. static encode_aux_threshmatch _vq_auxt__44c2_s_p4_0 = {
  128575. _vq_quantthresh__44c2_s_p4_0,
  128576. _vq_quantmap__44c2_s_p4_0,
  128577. 9,
  128578. 9
  128579. };
  128580. static static_codebook _44c2_s_p4_0 = {
  128581. 2, 81,
  128582. _vq_lengthlist__44c2_s_p4_0,
  128583. 1, -531628032, 1611661312, 4, 0,
  128584. _vq_quantlist__44c2_s_p4_0,
  128585. NULL,
  128586. &_vq_auxt__44c2_s_p4_0,
  128587. NULL,
  128588. 0
  128589. };
  128590. static long _vq_quantlist__44c2_s_p5_0[] = {
  128591. 4,
  128592. 3,
  128593. 5,
  128594. 2,
  128595. 6,
  128596. 1,
  128597. 7,
  128598. 0,
  128599. 8,
  128600. };
  128601. static long _vq_lengthlist__44c2_s_p5_0[] = {
  128602. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 7, 7, 7, 7, 7, 7,
  128603. 9, 9, 0, 7, 7, 7, 7, 7, 7, 9, 9, 0, 8, 8, 7, 7,
  128604. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  128605. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  128606. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  128607. 11,
  128608. };
  128609. static float _vq_quantthresh__44c2_s_p5_0[] = {
  128610. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128611. };
  128612. static long _vq_quantmap__44c2_s_p5_0[] = {
  128613. 7, 5, 3, 1, 0, 2, 4, 6,
  128614. 8,
  128615. };
  128616. static encode_aux_threshmatch _vq_auxt__44c2_s_p5_0 = {
  128617. _vq_quantthresh__44c2_s_p5_0,
  128618. _vq_quantmap__44c2_s_p5_0,
  128619. 9,
  128620. 9
  128621. };
  128622. static static_codebook _44c2_s_p5_0 = {
  128623. 2, 81,
  128624. _vq_lengthlist__44c2_s_p5_0,
  128625. 1, -531628032, 1611661312, 4, 0,
  128626. _vq_quantlist__44c2_s_p5_0,
  128627. NULL,
  128628. &_vq_auxt__44c2_s_p5_0,
  128629. NULL,
  128630. 0
  128631. };
  128632. static long _vq_quantlist__44c2_s_p6_0[] = {
  128633. 8,
  128634. 7,
  128635. 9,
  128636. 6,
  128637. 10,
  128638. 5,
  128639. 11,
  128640. 4,
  128641. 12,
  128642. 3,
  128643. 13,
  128644. 2,
  128645. 14,
  128646. 1,
  128647. 15,
  128648. 0,
  128649. 16,
  128650. };
  128651. static long _vq_lengthlist__44c2_s_p6_0[] = {
  128652. 1, 4, 3, 6, 6, 8, 8, 9, 9, 9, 9, 9, 9,10,10,11,
  128653. 11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  128654. 12,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  128655. 11,11,12, 0, 8, 8, 7, 7, 9, 9,10,10, 9, 9,10,10,
  128656. 11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10, 9,10,
  128657. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  128658. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  128659. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  128660. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  128661. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  128662. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  128663. 9,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  128664. 10,10,10,10,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  128665. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  128666. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  128667. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  128668. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  128669. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  128670. 14,
  128671. };
  128672. static float _vq_quantthresh__44c2_s_p6_0[] = {
  128673. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128674. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128675. };
  128676. static long _vq_quantmap__44c2_s_p6_0[] = {
  128677. 15, 13, 11, 9, 7, 5, 3, 1,
  128678. 0, 2, 4, 6, 8, 10, 12, 14,
  128679. 16,
  128680. };
  128681. static encode_aux_threshmatch _vq_auxt__44c2_s_p6_0 = {
  128682. _vq_quantthresh__44c2_s_p6_0,
  128683. _vq_quantmap__44c2_s_p6_0,
  128684. 17,
  128685. 17
  128686. };
  128687. static static_codebook _44c2_s_p6_0 = {
  128688. 2, 289,
  128689. _vq_lengthlist__44c2_s_p6_0,
  128690. 1, -529530880, 1611661312, 5, 0,
  128691. _vq_quantlist__44c2_s_p6_0,
  128692. NULL,
  128693. &_vq_auxt__44c2_s_p6_0,
  128694. NULL,
  128695. 0
  128696. };
  128697. static long _vq_quantlist__44c2_s_p7_0[] = {
  128698. 1,
  128699. 0,
  128700. 2,
  128701. };
  128702. static long _vq_lengthlist__44c2_s_p7_0[] = {
  128703. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  128704. 9, 9, 4, 7, 7,10, 9, 9,10, 9, 9, 7,10,10,11,10,
  128705. 11,11,10,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  128706. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 6,
  128707. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,12,10,
  128708. 11,
  128709. };
  128710. static float _vq_quantthresh__44c2_s_p7_0[] = {
  128711. -5.5, 5.5,
  128712. };
  128713. static long _vq_quantmap__44c2_s_p7_0[] = {
  128714. 1, 0, 2,
  128715. };
  128716. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_0 = {
  128717. _vq_quantthresh__44c2_s_p7_0,
  128718. _vq_quantmap__44c2_s_p7_0,
  128719. 3,
  128720. 3
  128721. };
  128722. static static_codebook _44c2_s_p7_0 = {
  128723. 4, 81,
  128724. _vq_lengthlist__44c2_s_p7_0,
  128725. 1, -529137664, 1618345984, 2, 0,
  128726. _vq_quantlist__44c2_s_p7_0,
  128727. NULL,
  128728. &_vq_auxt__44c2_s_p7_0,
  128729. NULL,
  128730. 0
  128731. };
  128732. static long _vq_quantlist__44c2_s_p7_1[] = {
  128733. 5,
  128734. 4,
  128735. 6,
  128736. 3,
  128737. 7,
  128738. 2,
  128739. 8,
  128740. 1,
  128741. 9,
  128742. 0,
  128743. 10,
  128744. };
  128745. static long _vq_lengthlist__44c2_s_p7_1[] = {
  128746. 2, 3, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 7, 7, 6, 6,
  128747. 7, 7, 8, 8, 8, 8, 9, 6, 6, 6, 6, 7, 7, 8, 8, 8,
  128748. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  128749. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  128750. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  128751. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  128752. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  128753. 10,10,10, 8, 8, 8, 8, 8, 8,
  128754. };
  128755. static float _vq_quantthresh__44c2_s_p7_1[] = {
  128756. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  128757. 3.5, 4.5,
  128758. };
  128759. static long _vq_quantmap__44c2_s_p7_1[] = {
  128760. 9, 7, 5, 3, 1, 0, 2, 4,
  128761. 6, 8, 10,
  128762. };
  128763. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_1 = {
  128764. _vq_quantthresh__44c2_s_p7_1,
  128765. _vq_quantmap__44c2_s_p7_1,
  128766. 11,
  128767. 11
  128768. };
  128769. static static_codebook _44c2_s_p7_1 = {
  128770. 2, 121,
  128771. _vq_lengthlist__44c2_s_p7_1,
  128772. 1, -531365888, 1611661312, 4, 0,
  128773. _vq_quantlist__44c2_s_p7_1,
  128774. NULL,
  128775. &_vq_auxt__44c2_s_p7_1,
  128776. NULL,
  128777. 0
  128778. };
  128779. static long _vq_quantlist__44c2_s_p8_0[] = {
  128780. 6,
  128781. 5,
  128782. 7,
  128783. 4,
  128784. 8,
  128785. 3,
  128786. 9,
  128787. 2,
  128788. 10,
  128789. 1,
  128790. 11,
  128791. 0,
  128792. 12,
  128793. };
  128794. static long _vq_lengthlist__44c2_s_p8_0[] = {
  128795. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  128796. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  128797. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  128798. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  128799. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  128800. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  128801. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  128802. 11,12,12,12,12, 0, 0, 0,14,14,10,11,11,11,12,12,
  128803. 13,13, 0, 0, 0,14,14,11,10,11,11,13,12,13,13, 0,
  128804. 0, 0, 0, 0,12,12,11,12,13,12,14,14, 0, 0, 0, 0,
  128805. 0,12,12,12,12,13,12,14,14,
  128806. };
  128807. static float _vq_quantthresh__44c2_s_p8_0[] = {
  128808. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  128809. 12.5, 17.5, 22.5, 27.5,
  128810. };
  128811. static long _vq_quantmap__44c2_s_p8_0[] = {
  128812. 11, 9, 7, 5, 3, 1, 0, 2,
  128813. 4, 6, 8, 10, 12,
  128814. };
  128815. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_0 = {
  128816. _vq_quantthresh__44c2_s_p8_0,
  128817. _vq_quantmap__44c2_s_p8_0,
  128818. 13,
  128819. 13
  128820. };
  128821. static static_codebook _44c2_s_p8_0 = {
  128822. 2, 169,
  128823. _vq_lengthlist__44c2_s_p8_0,
  128824. 1, -526516224, 1616117760, 4, 0,
  128825. _vq_quantlist__44c2_s_p8_0,
  128826. NULL,
  128827. &_vq_auxt__44c2_s_p8_0,
  128828. NULL,
  128829. 0
  128830. };
  128831. static long _vq_quantlist__44c2_s_p8_1[] = {
  128832. 2,
  128833. 1,
  128834. 3,
  128835. 0,
  128836. 4,
  128837. };
  128838. static long _vq_lengthlist__44c2_s_p8_1[] = {
  128839. 2, 4, 4, 5, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  128840. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  128841. };
  128842. static float _vq_quantthresh__44c2_s_p8_1[] = {
  128843. -1.5, -0.5, 0.5, 1.5,
  128844. };
  128845. static long _vq_quantmap__44c2_s_p8_1[] = {
  128846. 3, 1, 0, 2, 4,
  128847. };
  128848. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_1 = {
  128849. _vq_quantthresh__44c2_s_p8_1,
  128850. _vq_quantmap__44c2_s_p8_1,
  128851. 5,
  128852. 5
  128853. };
  128854. static static_codebook _44c2_s_p8_1 = {
  128855. 2, 25,
  128856. _vq_lengthlist__44c2_s_p8_1,
  128857. 1, -533725184, 1611661312, 3, 0,
  128858. _vq_quantlist__44c2_s_p8_1,
  128859. NULL,
  128860. &_vq_auxt__44c2_s_p8_1,
  128861. NULL,
  128862. 0
  128863. };
  128864. static long _vq_quantlist__44c2_s_p9_0[] = {
  128865. 6,
  128866. 5,
  128867. 7,
  128868. 4,
  128869. 8,
  128870. 3,
  128871. 9,
  128872. 2,
  128873. 10,
  128874. 1,
  128875. 11,
  128876. 0,
  128877. 12,
  128878. };
  128879. static long _vq_lengthlist__44c2_s_p9_0[] = {
  128880. 1, 5, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  128881. 11,11,11,11,11,11,11,11,11,11, 2, 8, 7,11,11,11,
  128882. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128883. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  128884. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128885. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128886. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128887. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128888. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128889. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128890. 11,11,11,11,11,11,11,11,11,
  128891. };
  128892. static float _vq_quantthresh__44c2_s_p9_0[] = {
  128893. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  128894. 552.5, 773.5, 994.5, 1215.5,
  128895. };
  128896. static long _vq_quantmap__44c2_s_p9_0[] = {
  128897. 11, 9, 7, 5, 3, 1, 0, 2,
  128898. 4, 6, 8, 10, 12,
  128899. };
  128900. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_0 = {
  128901. _vq_quantthresh__44c2_s_p9_0,
  128902. _vq_quantmap__44c2_s_p9_0,
  128903. 13,
  128904. 13
  128905. };
  128906. static static_codebook _44c2_s_p9_0 = {
  128907. 2, 169,
  128908. _vq_lengthlist__44c2_s_p9_0,
  128909. 1, -514541568, 1627103232, 4, 0,
  128910. _vq_quantlist__44c2_s_p9_0,
  128911. NULL,
  128912. &_vq_auxt__44c2_s_p9_0,
  128913. NULL,
  128914. 0
  128915. };
  128916. static long _vq_quantlist__44c2_s_p9_1[] = {
  128917. 6,
  128918. 5,
  128919. 7,
  128920. 4,
  128921. 8,
  128922. 3,
  128923. 9,
  128924. 2,
  128925. 10,
  128926. 1,
  128927. 11,
  128928. 0,
  128929. 12,
  128930. };
  128931. static long _vq_lengthlist__44c2_s_p9_1[] = {
  128932. 1, 4, 4, 6, 6, 7, 6, 8, 8,10, 9,10,10, 6, 5, 5,
  128933. 7, 7, 8, 7,10, 9,11,11,12,13, 6, 5, 5, 7, 7, 8,
  128934. 8,10,10,11,11,13,13,18, 8, 8, 8, 8, 9, 9,10,10,
  128935. 12,12,12,13,18, 8, 8, 8, 8, 9, 9,10,10,12,12,13,
  128936. 13,18,11,11, 8, 8,10,10,11,11,12,11,13,12,18,11,
  128937. 11, 9, 7,10,10,11,11,11,12,12,13,17,17,17,10,10,
  128938. 11,11,12,12,12,10,12,12,17,17,17,11,10,11,10,13,
  128939. 12,11,12,12,12,17,17,17,15,14,11,11,12,11,13,10,
  128940. 13,12,17,17,17,14,14,12,10,11,11,13,13,13,13,17,
  128941. 17,16,17,16,13,13,12,10,13,10,14,13,17,16,17,16,
  128942. 17,13,12,12,10,13,11,14,14,
  128943. };
  128944. static float _vq_quantthresh__44c2_s_p9_1[] = {
  128945. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  128946. 42.5, 59.5, 76.5, 93.5,
  128947. };
  128948. static long _vq_quantmap__44c2_s_p9_1[] = {
  128949. 11, 9, 7, 5, 3, 1, 0, 2,
  128950. 4, 6, 8, 10, 12,
  128951. };
  128952. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_1 = {
  128953. _vq_quantthresh__44c2_s_p9_1,
  128954. _vq_quantmap__44c2_s_p9_1,
  128955. 13,
  128956. 13
  128957. };
  128958. static static_codebook _44c2_s_p9_1 = {
  128959. 2, 169,
  128960. _vq_lengthlist__44c2_s_p9_1,
  128961. 1, -522616832, 1620115456, 4, 0,
  128962. _vq_quantlist__44c2_s_p9_1,
  128963. NULL,
  128964. &_vq_auxt__44c2_s_p9_1,
  128965. NULL,
  128966. 0
  128967. };
  128968. static long _vq_quantlist__44c2_s_p9_2[] = {
  128969. 8,
  128970. 7,
  128971. 9,
  128972. 6,
  128973. 10,
  128974. 5,
  128975. 11,
  128976. 4,
  128977. 12,
  128978. 3,
  128979. 13,
  128980. 2,
  128981. 14,
  128982. 1,
  128983. 15,
  128984. 0,
  128985. 16,
  128986. };
  128987. static long _vq_lengthlist__44c2_s_p9_2[] = {
  128988. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  128989. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  128990. 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  128991. 9, 9, 9,10, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  128992. 9, 9, 9, 9,10,10,10, 8, 7, 8, 8, 8, 8, 9, 9, 9,
  128993. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  128994. 9, 9,10, 9, 9, 9,10,11,10, 8, 8, 8, 8, 9, 9, 9,
  128995. 9, 9, 9, 9,10,10,10,10,11,10, 8, 8, 9, 9, 9, 9,
  128996. 9, 9,10, 9, 9,10, 9,10,11,10,11,11,11, 8, 8, 9,
  128997. 9, 9, 9, 9, 9, 9, 9,10,10,11,11,11,11,11, 9, 9,
  128998. 9, 9, 9, 9,10, 9, 9, 9,10,10,11,11,11,11,11, 9,
  128999. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,11,11,11,11,11,
  129000. 9, 9, 9, 9,10,10, 9, 9, 9,10,10,10,11,11,11,11,
  129001. 11,11,11, 9, 9, 9,10, 9, 9,10,10,10,10,11,11,10,
  129002. 11,11,11,11,10, 9,10,10, 9, 9, 9, 9,10,10,11,10,
  129003. 11,11,11,11,11, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  129004. 10,11,11,11,11,11,10,10, 9, 9,10, 9,10,10,10,10,
  129005. 10,10,10,11,11,11,11,11,11, 9, 9,10, 9,10, 9,10,
  129006. 10,
  129007. };
  129008. static float _vq_quantthresh__44c2_s_p9_2[] = {
  129009. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129010. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129011. };
  129012. static long _vq_quantmap__44c2_s_p9_2[] = {
  129013. 15, 13, 11, 9, 7, 5, 3, 1,
  129014. 0, 2, 4, 6, 8, 10, 12, 14,
  129015. 16,
  129016. };
  129017. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_2 = {
  129018. _vq_quantthresh__44c2_s_p9_2,
  129019. _vq_quantmap__44c2_s_p9_2,
  129020. 17,
  129021. 17
  129022. };
  129023. static static_codebook _44c2_s_p9_2 = {
  129024. 2, 289,
  129025. _vq_lengthlist__44c2_s_p9_2,
  129026. 1, -529530880, 1611661312, 5, 0,
  129027. _vq_quantlist__44c2_s_p9_2,
  129028. NULL,
  129029. &_vq_auxt__44c2_s_p9_2,
  129030. NULL,
  129031. 0
  129032. };
  129033. static long _huff_lengthlist__44c2_s_short[] = {
  129034. 11, 9,13,12,12,11,12,12,13,15, 8, 2,11, 4, 8, 5,
  129035. 7,10,12,15,13, 7,10, 9, 8, 8,10,13,17,17,11, 4,
  129036. 12, 5, 9, 5, 8,11,14,16,12, 6, 8, 7, 6, 6, 8,11,
  129037. 13,16,11, 4, 9, 5, 6, 4, 6,10,13,16,11, 6,11, 7,
  129038. 7, 6, 7,10,13,15,13, 9,12, 9, 8, 6, 8,10,12,14,
  129039. 14,10,10, 8, 6, 5, 6, 9,11,13,15,11,11, 9, 6, 5,
  129040. 6, 8, 9,12,
  129041. };
  129042. static static_codebook _huff_book__44c2_s_short = {
  129043. 2, 100,
  129044. _huff_lengthlist__44c2_s_short,
  129045. 0, 0, 0, 0, 0,
  129046. NULL,
  129047. NULL,
  129048. NULL,
  129049. NULL,
  129050. 0
  129051. };
  129052. static long _huff_lengthlist__44c3_s_long[] = {
  129053. 5, 6,11,11,11,11,10,10,12,11, 5, 2,11, 5, 6, 6,
  129054. 7, 9,11,13,13,10, 7,11, 6, 7, 8, 9,10,12,11, 5,
  129055. 11, 6, 8, 7, 9,11,14,15,11, 6, 6, 8, 4, 5, 7, 8,
  129056. 10,13,10, 5, 7, 7, 5, 5, 6, 8,10,11,10, 7, 7, 8,
  129057. 6, 5, 5, 7, 9, 9,11, 8, 8,11, 8, 7, 6, 6, 7, 9,
  129058. 12,11,10,13, 9, 9, 7, 7, 7, 9,11,13,12,15,12,11,
  129059. 9, 8, 8, 8,
  129060. };
  129061. static static_codebook _huff_book__44c3_s_long = {
  129062. 2, 100,
  129063. _huff_lengthlist__44c3_s_long,
  129064. 0, 0, 0, 0, 0,
  129065. NULL,
  129066. NULL,
  129067. NULL,
  129068. NULL,
  129069. 0
  129070. };
  129071. static long _vq_quantlist__44c3_s_p1_0[] = {
  129072. 1,
  129073. 0,
  129074. 2,
  129075. };
  129076. static long _vq_lengthlist__44c3_s_p1_0[] = {
  129077. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  129078. 0, 0, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129082. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  129083. 0, 0, 0, 6, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129087. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  129088. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  129123. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 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, 7, 8, 8, 0, 0, 0,
  129128. 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  129133. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  129134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129168. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  129169. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129173. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  129174. 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  129175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129178. 0, 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  129179. 0, 0, 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 0,
  129180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  129268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129487. 0,
  129488. };
  129489. static float _vq_quantthresh__44c3_s_p1_0[] = {
  129490. -0.5, 0.5,
  129491. };
  129492. static long _vq_quantmap__44c3_s_p1_0[] = {
  129493. 1, 0, 2,
  129494. };
  129495. static encode_aux_threshmatch _vq_auxt__44c3_s_p1_0 = {
  129496. _vq_quantthresh__44c3_s_p1_0,
  129497. _vq_quantmap__44c3_s_p1_0,
  129498. 3,
  129499. 3
  129500. };
  129501. static static_codebook _44c3_s_p1_0 = {
  129502. 8, 6561,
  129503. _vq_lengthlist__44c3_s_p1_0,
  129504. 1, -535822336, 1611661312, 2, 0,
  129505. _vq_quantlist__44c3_s_p1_0,
  129506. NULL,
  129507. &_vq_auxt__44c3_s_p1_0,
  129508. NULL,
  129509. 0
  129510. };
  129511. static long _vq_quantlist__44c3_s_p2_0[] = {
  129512. 2,
  129513. 1,
  129514. 3,
  129515. 0,
  129516. 4,
  129517. };
  129518. static long _vq_lengthlist__44c3_s_p2_0[] = {
  129519. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  129520. 7, 8, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  129521. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  129522. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  129523. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129528. 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0,
  129529. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  129530. 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  129531. 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129536. 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  129537. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  129538. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0,
  129539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129544. 8,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  129545. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  129546. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  129547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129558. 0,
  129559. };
  129560. static float _vq_quantthresh__44c3_s_p2_0[] = {
  129561. -1.5, -0.5, 0.5, 1.5,
  129562. };
  129563. static long _vq_quantmap__44c3_s_p2_0[] = {
  129564. 3, 1, 0, 2, 4,
  129565. };
  129566. static encode_aux_threshmatch _vq_auxt__44c3_s_p2_0 = {
  129567. _vq_quantthresh__44c3_s_p2_0,
  129568. _vq_quantmap__44c3_s_p2_0,
  129569. 5,
  129570. 5
  129571. };
  129572. static static_codebook _44c3_s_p2_0 = {
  129573. 4, 625,
  129574. _vq_lengthlist__44c3_s_p2_0,
  129575. 1, -533725184, 1611661312, 3, 0,
  129576. _vq_quantlist__44c3_s_p2_0,
  129577. NULL,
  129578. &_vq_auxt__44c3_s_p2_0,
  129579. NULL,
  129580. 0
  129581. };
  129582. static long _vq_quantlist__44c3_s_p3_0[] = {
  129583. 2,
  129584. 1,
  129585. 3,
  129586. 0,
  129587. 4,
  129588. };
  129589. static long _vq_lengthlist__44c3_s_p3_0[] = {
  129590. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  129592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129593. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  129595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129596. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  129597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129629. 0,
  129630. };
  129631. static float _vq_quantthresh__44c3_s_p3_0[] = {
  129632. -1.5, -0.5, 0.5, 1.5,
  129633. };
  129634. static long _vq_quantmap__44c3_s_p3_0[] = {
  129635. 3, 1, 0, 2, 4,
  129636. };
  129637. static encode_aux_threshmatch _vq_auxt__44c3_s_p3_0 = {
  129638. _vq_quantthresh__44c3_s_p3_0,
  129639. _vq_quantmap__44c3_s_p3_0,
  129640. 5,
  129641. 5
  129642. };
  129643. static static_codebook _44c3_s_p3_0 = {
  129644. 4, 625,
  129645. _vq_lengthlist__44c3_s_p3_0,
  129646. 1, -533725184, 1611661312, 3, 0,
  129647. _vq_quantlist__44c3_s_p3_0,
  129648. NULL,
  129649. &_vq_auxt__44c3_s_p3_0,
  129650. NULL,
  129651. 0
  129652. };
  129653. static long _vq_quantlist__44c3_s_p4_0[] = {
  129654. 4,
  129655. 3,
  129656. 5,
  129657. 2,
  129658. 6,
  129659. 1,
  129660. 7,
  129661. 0,
  129662. 8,
  129663. };
  129664. static long _vq_lengthlist__44c3_s_p4_0[] = {
  129665. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  129666. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  129667. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  129668. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  129669. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129670. 0,
  129671. };
  129672. static float _vq_quantthresh__44c3_s_p4_0[] = {
  129673. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129674. };
  129675. static long _vq_quantmap__44c3_s_p4_0[] = {
  129676. 7, 5, 3, 1, 0, 2, 4, 6,
  129677. 8,
  129678. };
  129679. static encode_aux_threshmatch _vq_auxt__44c3_s_p4_0 = {
  129680. _vq_quantthresh__44c3_s_p4_0,
  129681. _vq_quantmap__44c3_s_p4_0,
  129682. 9,
  129683. 9
  129684. };
  129685. static static_codebook _44c3_s_p4_0 = {
  129686. 2, 81,
  129687. _vq_lengthlist__44c3_s_p4_0,
  129688. 1, -531628032, 1611661312, 4, 0,
  129689. _vq_quantlist__44c3_s_p4_0,
  129690. NULL,
  129691. &_vq_auxt__44c3_s_p4_0,
  129692. NULL,
  129693. 0
  129694. };
  129695. static long _vq_quantlist__44c3_s_p5_0[] = {
  129696. 4,
  129697. 3,
  129698. 5,
  129699. 2,
  129700. 6,
  129701. 1,
  129702. 7,
  129703. 0,
  129704. 8,
  129705. };
  129706. static long _vq_lengthlist__44c3_s_p5_0[] = {
  129707. 1, 3, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 7, 8,
  129708. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  129709. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  129710. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  129711. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  129712. 11,
  129713. };
  129714. static float _vq_quantthresh__44c3_s_p5_0[] = {
  129715. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129716. };
  129717. static long _vq_quantmap__44c3_s_p5_0[] = {
  129718. 7, 5, 3, 1, 0, 2, 4, 6,
  129719. 8,
  129720. };
  129721. static encode_aux_threshmatch _vq_auxt__44c3_s_p5_0 = {
  129722. _vq_quantthresh__44c3_s_p5_0,
  129723. _vq_quantmap__44c3_s_p5_0,
  129724. 9,
  129725. 9
  129726. };
  129727. static static_codebook _44c3_s_p5_0 = {
  129728. 2, 81,
  129729. _vq_lengthlist__44c3_s_p5_0,
  129730. 1, -531628032, 1611661312, 4, 0,
  129731. _vq_quantlist__44c3_s_p5_0,
  129732. NULL,
  129733. &_vq_auxt__44c3_s_p5_0,
  129734. NULL,
  129735. 0
  129736. };
  129737. static long _vq_quantlist__44c3_s_p6_0[] = {
  129738. 8,
  129739. 7,
  129740. 9,
  129741. 6,
  129742. 10,
  129743. 5,
  129744. 11,
  129745. 4,
  129746. 12,
  129747. 3,
  129748. 13,
  129749. 2,
  129750. 14,
  129751. 1,
  129752. 15,
  129753. 0,
  129754. 16,
  129755. };
  129756. static long _vq_lengthlist__44c3_s_p6_0[] = {
  129757. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  129758. 10, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  129759. 11,11, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  129760. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  129761. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  129762. 10,11,11,11,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  129763. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  129764. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  129765. 10,10,11,10,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  129766. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 8,
  129767. 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8,
  129768. 8, 9, 9,10,10,11,11,12,11,12,12, 0, 0, 0, 0, 0,
  129769. 9,10,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0,
  129770. 0, 0, 0,10,10,10,10,11,11,12,12,13,13, 0, 0, 0,
  129771. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  129772. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  129773. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13,
  129774. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  129775. 13,
  129776. };
  129777. static float _vq_quantthresh__44c3_s_p6_0[] = {
  129778. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129779. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129780. };
  129781. static long _vq_quantmap__44c3_s_p6_0[] = {
  129782. 15, 13, 11, 9, 7, 5, 3, 1,
  129783. 0, 2, 4, 6, 8, 10, 12, 14,
  129784. 16,
  129785. };
  129786. static encode_aux_threshmatch _vq_auxt__44c3_s_p6_0 = {
  129787. _vq_quantthresh__44c3_s_p6_0,
  129788. _vq_quantmap__44c3_s_p6_0,
  129789. 17,
  129790. 17
  129791. };
  129792. static static_codebook _44c3_s_p6_0 = {
  129793. 2, 289,
  129794. _vq_lengthlist__44c3_s_p6_0,
  129795. 1, -529530880, 1611661312, 5, 0,
  129796. _vq_quantlist__44c3_s_p6_0,
  129797. NULL,
  129798. &_vq_auxt__44c3_s_p6_0,
  129799. NULL,
  129800. 0
  129801. };
  129802. static long _vq_quantlist__44c3_s_p7_0[] = {
  129803. 1,
  129804. 0,
  129805. 2,
  129806. };
  129807. static long _vq_lengthlist__44c3_s_p7_0[] = {
  129808. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  129809. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  129810. 10,12,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  129811. 11,10,10,11,10,10, 7,11,11,11,11,11,12,11,11, 6,
  129812. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  129813. 10,
  129814. };
  129815. static float _vq_quantthresh__44c3_s_p7_0[] = {
  129816. -5.5, 5.5,
  129817. };
  129818. static long _vq_quantmap__44c3_s_p7_0[] = {
  129819. 1, 0, 2,
  129820. };
  129821. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_0 = {
  129822. _vq_quantthresh__44c3_s_p7_0,
  129823. _vq_quantmap__44c3_s_p7_0,
  129824. 3,
  129825. 3
  129826. };
  129827. static static_codebook _44c3_s_p7_0 = {
  129828. 4, 81,
  129829. _vq_lengthlist__44c3_s_p7_0,
  129830. 1, -529137664, 1618345984, 2, 0,
  129831. _vq_quantlist__44c3_s_p7_0,
  129832. NULL,
  129833. &_vq_auxt__44c3_s_p7_0,
  129834. NULL,
  129835. 0
  129836. };
  129837. static long _vq_quantlist__44c3_s_p7_1[] = {
  129838. 5,
  129839. 4,
  129840. 6,
  129841. 3,
  129842. 7,
  129843. 2,
  129844. 8,
  129845. 1,
  129846. 9,
  129847. 0,
  129848. 10,
  129849. };
  129850. static long _vq_lengthlist__44c3_s_p7_1[] = {
  129851. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  129852. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  129853. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  129854. 7, 8, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  129855. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  129856. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  129857. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  129858. 10,10,10, 8, 8, 8, 8, 8, 8,
  129859. };
  129860. static float _vq_quantthresh__44c3_s_p7_1[] = {
  129861. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  129862. 3.5, 4.5,
  129863. };
  129864. static long _vq_quantmap__44c3_s_p7_1[] = {
  129865. 9, 7, 5, 3, 1, 0, 2, 4,
  129866. 6, 8, 10,
  129867. };
  129868. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_1 = {
  129869. _vq_quantthresh__44c3_s_p7_1,
  129870. _vq_quantmap__44c3_s_p7_1,
  129871. 11,
  129872. 11
  129873. };
  129874. static static_codebook _44c3_s_p7_1 = {
  129875. 2, 121,
  129876. _vq_lengthlist__44c3_s_p7_1,
  129877. 1, -531365888, 1611661312, 4, 0,
  129878. _vq_quantlist__44c3_s_p7_1,
  129879. NULL,
  129880. &_vq_auxt__44c3_s_p7_1,
  129881. NULL,
  129882. 0
  129883. };
  129884. static long _vq_quantlist__44c3_s_p8_0[] = {
  129885. 6,
  129886. 5,
  129887. 7,
  129888. 4,
  129889. 8,
  129890. 3,
  129891. 9,
  129892. 2,
  129893. 10,
  129894. 1,
  129895. 11,
  129896. 0,
  129897. 12,
  129898. };
  129899. static long _vq_lengthlist__44c3_s_p8_0[] = {
  129900. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  129901. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  129902. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  129903. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  129904. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,12, 0,13,
  129905. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  129906. 10,10,11,11,12,12,12,12, 0, 0, 0,10,10,10,10,11,
  129907. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  129908. 13,13, 0, 0, 0,14,14,11,11,11,11,12,12,13,13, 0,
  129909. 0, 0, 0, 0,12,12,12,12,13,13,14,13, 0, 0, 0, 0,
  129910. 0,13,13,12,12,13,12,14,13,
  129911. };
  129912. static float _vq_quantthresh__44c3_s_p8_0[] = {
  129913. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  129914. 12.5, 17.5, 22.5, 27.5,
  129915. };
  129916. static long _vq_quantmap__44c3_s_p8_0[] = {
  129917. 11, 9, 7, 5, 3, 1, 0, 2,
  129918. 4, 6, 8, 10, 12,
  129919. };
  129920. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_0 = {
  129921. _vq_quantthresh__44c3_s_p8_0,
  129922. _vq_quantmap__44c3_s_p8_0,
  129923. 13,
  129924. 13
  129925. };
  129926. static static_codebook _44c3_s_p8_0 = {
  129927. 2, 169,
  129928. _vq_lengthlist__44c3_s_p8_0,
  129929. 1, -526516224, 1616117760, 4, 0,
  129930. _vq_quantlist__44c3_s_p8_0,
  129931. NULL,
  129932. &_vq_auxt__44c3_s_p8_0,
  129933. NULL,
  129934. 0
  129935. };
  129936. static long _vq_quantlist__44c3_s_p8_1[] = {
  129937. 2,
  129938. 1,
  129939. 3,
  129940. 0,
  129941. 4,
  129942. };
  129943. static long _vq_lengthlist__44c3_s_p8_1[] = {
  129944. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  129945. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  129946. };
  129947. static float _vq_quantthresh__44c3_s_p8_1[] = {
  129948. -1.5, -0.5, 0.5, 1.5,
  129949. };
  129950. static long _vq_quantmap__44c3_s_p8_1[] = {
  129951. 3, 1, 0, 2, 4,
  129952. };
  129953. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_1 = {
  129954. _vq_quantthresh__44c3_s_p8_1,
  129955. _vq_quantmap__44c3_s_p8_1,
  129956. 5,
  129957. 5
  129958. };
  129959. static static_codebook _44c3_s_p8_1 = {
  129960. 2, 25,
  129961. _vq_lengthlist__44c3_s_p8_1,
  129962. 1, -533725184, 1611661312, 3, 0,
  129963. _vq_quantlist__44c3_s_p8_1,
  129964. NULL,
  129965. &_vq_auxt__44c3_s_p8_1,
  129966. NULL,
  129967. 0
  129968. };
  129969. static long _vq_quantlist__44c3_s_p9_0[] = {
  129970. 6,
  129971. 5,
  129972. 7,
  129973. 4,
  129974. 8,
  129975. 3,
  129976. 9,
  129977. 2,
  129978. 10,
  129979. 1,
  129980. 11,
  129981. 0,
  129982. 12,
  129983. };
  129984. static long _vq_lengthlist__44c3_s_p9_0[] = {
  129985. 1, 4, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  129986. 12,12,12,12,12,12,12,12,12,12, 2, 9, 7,12,12,12,
  129987. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129988. 12,12,12,12,12,12,11,12,12,12,12,12,12,12,12,12,
  129989. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129990. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129991. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129992. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129993. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  129994. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129995. 11,11,11,11,11,11,11,11,11,
  129996. };
  129997. static float _vq_quantthresh__44c3_s_p9_0[] = {
  129998. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  129999. 637.5, 892.5, 1147.5, 1402.5,
  130000. };
  130001. static long _vq_quantmap__44c3_s_p9_0[] = {
  130002. 11, 9, 7, 5, 3, 1, 0, 2,
  130003. 4, 6, 8, 10, 12,
  130004. };
  130005. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_0 = {
  130006. _vq_quantthresh__44c3_s_p9_0,
  130007. _vq_quantmap__44c3_s_p9_0,
  130008. 13,
  130009. 13
  130010. };
  130011. static static_codebook _44c3_s_p9_0 = {
  130012. 2, 169,
  130013. _vq_lengthlist__44c3_s_p9_0,
  130014. 1, -514332672, 1627381760, 4, 0,
  130015. _vq_quantlist__44c3_s_p9_0,
  130016. NULL,
  130017. &_vq_auxt__44c3_s_p9_0,
  130018. NULL,
  130019. 0
  130020. };
  130021. static long _vq_quantlist__44c3_s_p9_1[] = {
  130022. 7,
  130023. 6,
  130024. 8,
  130025. 5,
  130026. 9,
  130027. 4,
  130028. 10,
  130029. 3,
  130030. 11,
  130031. 2,
  130032. 12,
  130033. 1,
  130034. 13,
  130035. 0,
  130036. 14,
  130037. };
  130038. static long _vq_lengthlist__44c3_s_p9_1[] = {
  130039. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 9,10,10,10,10, 6,
  130040. 5, 5, 7, 7, 8, 8,10, 8,11,10,12,12,13,13, 6, 5,
  130041. 5, 7, 7, 8, 8,10, 9,11,11,12,12,13,12,18, 8, 8,
  130042. 8, 8, 9, 9,10, 9,11,10,12,12,13,13,18, 8, 8, 8,
  130043. 8, 9, 9,10,10,11,11,13,12,14,13,18,11,11, 9, 9,
  130044. 10,10,11,11,11,12,13,12,13,14,18,11,11, 9, 8,11,
  130045. 10,11,11,11,11,12,12,14,13,18,18,18,10,11,10,11,
  130046. 12,12,12,12,13,12,14,13,18,18,18,10,11,11, 9,12,
  130047. 11,12,12,12,13,13,13,18,18,17,14,14,11,11,12,12,
  130048. 13,12,14,12,14,13,18,18,18,14,14,11,10,12, 9,12,
  130049. 13,13,13,13,13,18,18,17,16,18,13,13,12,12,13,11,
  130050. 14,12,14,14,17,18,18,17,18,13,12,13,10,12,11,14,
  130051. 14,14,14,17,18,18,18,18,15,16,12,12,13,10,14,12,
  130052. 14,15,18,18,18,16,17,16,14,12,11,13,10,13,13,14,
  130053. 15,
  130054. };
  130055. static float _vq_quantthresh__44c3_s_p9_1[] = {
  130056. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  130057. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  130058. };
  130059. static long _vq_quantmap__44c3_s_p9_1[] = {
  130060. 13, 11, 9, 7, 5, 3, 1, 0,
  130061. 2, 4, 6, 8, 10, 12, 14,
  130062. };
  130063. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_1 = {
  130064. _vq_quantthresh__44c3_s_p9_1,
  130065. _vq_quantmap__44c3_s_p9_1,
  130066. 15,
  130067. 15
  130068. };
  130069. static static_codebook _44c3_s_p9_1 = {
  130070. 2, 225,
  130071. _vq_lengthlist__44c3_s_p9_1,
  130072. 1, -522338304, 1620115456, 4, 0,
  130073. _vq_quantlist__44c3_s_p9_1,
  130074. NULL,
  130075. &_vq_auxt__44c3_s_p9_1,
  130076. NULL,
  130077. 0
  130078. };
  130079. static long _vq_quantlist__44c3_s_p9_2[] = {
  130080. 8,
  130081. 7,
  130082. 9,
  130083. 6,
  130084. 10,
  130085. 5,
  130086. 11,
  130087. 4,
  130088. 12,
  130089. 3,
  130090. 13,
  130091. 2,
  130092. 14,
  130093. 1,
  130094. 15,
  130095. 0,
  130096. 16,
  130097. };
  130098. static long _vq_lengthlist__44c3_s_p9_2[] = {
  130099. 2, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  130100. 8,10, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 8, 9, 9, 9,
  130101. 9, 9,10, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  130102. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  130103. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  130104. 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  130105. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  130106. 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 9, 9, 9, 9, 9,
  130107. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 9, 9, 9,
  130108. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  130109. 9, 9, 9, 9,10,10, 9, 9,10, 9,11,10,11,11,11, 9,
  130110. 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,11,11,11,11,11,
  130111. 9, 9, 9, 9,10,10, 9, 9, 9, 9,10, 9,11,11,11,11,
  130112. 11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11,
  130113. 11,11,11,11,10, 9,10,10, 9,10, 9, 9,10, 9,11,10,
  130114. 10,11,11,11,11, 9,10, 9, 9, 9, 9,10,10,10,10,11,
  130115. 11,11,11,11,11,10,10,10, 9, 9,10, 9,10, 9,10,10,
  130116. 10,10,11,11,11,11,11,11,11, 9, 9, 9, 9, 9,10,10,
  130117. 10,
  130118. };
  130119. static float _vq_quantthresh__44c3_s_p9_2[] = {
  130120. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  130121. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  130122. };
  130123. static long _vq_quantmap__44c3_s_p9_2[] = {
  130124. 15, 13, 11, 9, 7, 5, 3, 1,
  130125. 0, 2, 4, 6, 8, 10, 12, 14,
  130126. 16,
  130127. };
  130128. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_2 = {
  130129. _vq_quantthresh__44c3_s_p9_2,
  130130. _vq_quantmap__44c3_s_p9_2,
  130131. 17,
  130132. 17
  130133. };
  130134. static static_codebook _44c3_s_p9_2 = {
  130135. 2, 289,
  130136. _vq_lengthlist__44c3_s_p9_2,
  130137. 1, -529530880, 1611661312, 5, 0,
  130138. _vq_quantlist__44c3_s_p9_2,
  130139. NULL,
  130140. &_vq_auxt__44c3_s_p9_2,
  130141. NULL,
  130142. 0
  130143. };
  130144. static long _huff_lengthlist__44c3_s_short[] = {
  130145. 10, 9,13,11,14,10,12,13,13,14, 7, 2,12, 5,10, 5,
  130146. 7,10,12,14,12, 6, 9, 8, 7, 7, 9,11,13,16,10, 4,
  130147. 12, 5,10, 6, 8,12,14,16,12, 6, 8, 7, 6, 5, 7,11,
  130148. 12,16,10, 4, 8, 5, 6, 4, 6, 9,13,16,10, 6,10, 7,
  130149. 7, 6, 7, 9,13,15,12, 9,11, 9, 8, 6, 7,10,12,14,
  130150. 14,11,10, 9, 6, 5, 6, 9,11,13,15,13,11,10, 6, 5,
  130151. 6, 8, 9,11,
  130152. };
  130153. static static_codebook _huff_book__44c3_s_short = {
  130154. 2, 100,
  130155. _huff_lengthlist__44c3_s_short,
  130156. 0, 0, 0, 0, 0,
  130157. NULL,
  130158. NULL,
  130159. NULL,
  130160. NULL,
  130161. 0
  130162. };
  130163. static long _huff_lengthlist__44c4_s_long[] = {
  130164. 4, 7,11,11,11,11,10,11,12,11, 5, 2,11, 5, 6, 6,
  130165. 7, 9,11,12,11, 9, 6,10, 6, 7, 8, 9,10,11,11, 5,
  130166. 11, 7, 8, 8, 9,11,13,14,11, 6, 5, 8, 4, 5, 7, 8,
  130167. 10,11,10, 6, 7, 7, 5, 5, 6, 8, 9,11,10, 7, 8, 9,
  130168. 6, 6, 6, 7, 8, 9,11, 9, 9,11, 7, 7, 6, 6, 7, 9,
  130169. 12,12,10,13, 9, 8, 7, 7, 7, 8,11,13,11,14,11,10,
  130170. 9, 8, 7, 7,
  130171. };
  130172. static static_codebook _huff_book__44c4_s_long = {
  130173. 2, 100,
  130174. _huff_lengthlist__44c4_s_long,
  130175. 0, 0, 0, 0, 0,
  130176. NULL,
  130177. NULL,
  130178. NULL,
  130179. NULL,
  130180. 0
  130181. };
  130182. static long _vq_quantlist__44c4_s_p1_0[] = {
  130183. 1,
  130184. 0,
  130185. 2,
  130186. };
  130187. static long _vq_lengthlist__44c4_s_p1_0[] = {
  130188. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  130189. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130193. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  130194. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130198. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  130199. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  130234. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  130235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  130239. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  130240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  130244. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  130245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130279. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  130280. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130284. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  130285. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  130286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130289. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  130290. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  130291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130598. 0,
  130599. };
  130600. static float _vq_quantthresh__44c4_s_p1_0[] = {
  130601. -0.5, 0.5,
  130602. };
  130603. static long _vq_quantmap__44c4_s_p1_0[] = {
  130604. 1, 0, 2,
  130605. };
  130606. static encode_aux_threshmatch _vq_auxt__44c4_s_p1_0 = {
  130607. _vq_quantthresh__44c4_s_p1_0,
  130608. _vq_quantmap__44c4_s_p1_0,
  130609. 3,
  130610. 3
  130611. };
  130612. static static_codebook _44c4_s_p1_0 = {
  130613. 8, 6561,
  130614. _vq_lengthlist__44c4_s_p1_0,
  130615. 1, -535822336, 1611661312, 2, 0,
  130616. _vq_quantlist__44c4_s_p1_0,
  130617. NULL,
  130618. &_vq_auxt__44c4_s_p1_0,
  130619. NULL,
  130620. 0
  130621. };
  130622. static long _vq_quantlist__44c4_s_p2_0[] = {
  130623. 2,
  130624. 1,
  130625. 3,
  130626. 0,
  130627. 4,
  130628. };
  130629. static long _vq_lengthlist__44c4_s_p2_0[] = {
  130630. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  130631. 7, 7, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  130632. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  130633. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  130634. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130639. 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 7, 7, 0, 0,
  130640. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  130641. 7, 8, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  130642. 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130647. 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  130648. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  130649. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0,
  130650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130655. 7,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  130656. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  130657. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  130658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130669. 0,
  130670. };
  130671. static float _vq_quantthresh__44c4_s_p2_0[] = {
  130672. -1.5, -0.5, 0.5, 1.5,
  130673. };
  130674. static long _vq_quantmap__44c4_s_p2_0[] = {
  130675. 3, 1, 0, 2, 4,
  130676. };
  130677. static encode_aux_threshmatch _vq_auxt__44c4_s_p2_0 = {
  130678. _vq_quantthresh__44c4_s_p2_0,
  130679. _vq_quantmap__44c4_s_p2_0,
  130680. 5,
  130681. 5
  130682. };
  130683. static static_codebook _44c4_s_p2_0 = {
  130684. 4, 625,
  130685. _vq_lengthlist__44c4_s_p2_0,
  130686. 1, -533725184, 1611661312, 3, 0,
  130687. _vq_quantlist__44c4_s_p2_0,
  130688. NULL,
  130689. &_vq_auxt__44c4_s_p2_0,
  130690. NULL,
  130691. 0
  130692. };
  130693. static long _vq_quantlist__44c4_s_p3_0[] = {
  130694. 2,
  130695. 1,
  130696. 3,
  130697. 0,
  130698. 4,
  130699. };
  130700. static long _vq_lengthlist__44c4_s_p3_0[] = {
  130701. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 4, 6, 6, 0, 0,
  130703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130704. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  130706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130707. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  130708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130740. 0,
  130741. };
  130742. static float _vq_quantthresh__44c4_s_p3_0[] = {
  130743. -1.5, -0.5, 0.5, 1.5,
  130744. };
  130745. static long _vq_quantmap__44c4_s_p3_0[] = {
  130746. 3, 1, 0, 2, 4,
  130747. };
  130748. static encode_aux_threshmatch _vq_auxt__44c4_s_p3_0 = {
  130749. _vq_quantthresh__44c4_s_p3_0,
  130750. _vq_quantmap__44c4_s_p3_0,
  130751. 5,
  130752. 5
  130753. };
  130754. static static_codebook _44c4_s_p3_0 = {
  130755. 4, 625,
  130756. _vq_lengthlist__44c4_s_p3_0,
  130757. 1, -533725184, 1611661312, 3, 0,
  130758. _vq_quantlist__44c4_s_p3_0,
  130759. NULL,
  130760. &_vq_auxt__44c4_s_p3_0,
  130761. NULL,
  130762. 0
  130763. };
  130764. static long _vq_quantlist__44c4_s_p4_0[] = {
  130765. 4,
  130766. 3,
  130767. 5,
  130768. 2,
  130769. 6,
  130770. 1,
  130771. 7,
  130772. 0,
  130773. 8,
  130774. };
  130775. static long _vq_lengthlist__44c4_s_p4_0[] = {
  130776. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  130777. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  130778. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  130779. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  130780. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130781. 0,
  130782. };
  130783. static float _vq_quantthresh__44c4_s_p4_0[] = {
  130784. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130785. };
  130786. static long _vq_quantmap__44c4_s_p4_0[] = {
  130787. 7, 5, 3, 1, 0, 2, 4, 6,
  130788. 8,
  130789. };
  130790. static encode_aux_threshmatch _vq_auxt__44c4_s_p4_0 = {
  130791. _vq_quantthresh__44c4_s_p4_0,
  130792. _vq_quantmap__44c4_s_p4_0,
  130793. 9,
  130794. 9
  130795. };
  130796. static static_codebook _44c4_s_p4_0 = {
  130797. 2, 81,
  130798. _vq_lengthlist__44c4_s_p4_0,
  130799. 1, -531628032, 1611661312, 4, 0,
  130800. _vq_quantlist__44c4_s_p4_0,
  130801. NULL,
  130802. &_vq_auxt__44c4_s_p4_0,
  130803. NULL,
  130804. 0
  130805. };
  130806. static long _vq_quantlist__44c4_s_p5_0[] = {
  130807. 4,
  130808. 3,
  130809. 5,
  130810. 2,
  130811. 6,
  130812. 1,
  130813. 7,
  130814. 0,
  130815. 8,
  130816. };
  130817. static long _vq_lengthlist__44c4_s_p5_0[] = {
  130818. 2, 3, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  130819. 9, 9, 0, 4, 5, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  130820. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10, 9, 0, 0, 0,
  130821. 9, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  130822. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,10,
  130823. 10,
  130824. };
  130825. static float _vq_quantthresh__44c4_s_p5_0[] = {
  130826. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130827. };
  130828. static long _vq_quantmap__44c4_s_p5_0[] = {
  130829. 7, 5, 3, 1, 0, 2, 4, 6,
  130830. 8,
  130831. };
  130832. static encode_aux_threshmatch _vq_auxt__44c4_s_p5_0 = {
  130833. _vq_quantthresh__44c4_s_p5_0,
  130834. _vq_quantmap__44c4_s_p5_0,
  130835. 9,
  130836. 9
  130837. };
  130838. static static_codebook _44c4_s_p5_0 = {
  130839. 2, 81,
  130840. _vq_lengthlist__44c4_s_p5_0,
  130841. 1, -531628032, 1611661312, 4, 0,
  130842. _vq_quantlist__44c4_s_p5_0,
  130843. NULL,
  130844. &_vq_auxt__44c4_s_p5_0,
  130845. NULL,
  130846. 0
  130847. };
  130848. static long _vq_quantlist__44c4_s_p6_0[] = {
  130849. 8,
  130850. 7,
  130851. 9,
  130852. 6,
  130853. 10,
  130854. 5,
  130855. 11,
  130856. 4,
  130857. 12,
  130858. 3,
  130859. 13,
  130860. 2,
  130861. 14,
  130862. 1,
  130863. 15,
  130864. 0,
  130865. 16,
  130866. };
  130867. static long _vq_lengthlist__44c4_s_p6_0[] = {
  130868. 2, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  130869. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  130870. 11,11, 0, 4, 4, 7, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  130871. 11,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  130872. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  130873. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  130874. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  130875. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  130876. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  130877. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  130878. 9,10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9,
  130879. 9, 9, 9,10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0,
  130880. 10,10,10,10,11,11,11,11,12,12,13,12, 0, 0, 0, 0,
  130881. 0, 0, 0,10,10,11,11,11,11,12,12,12,12, 0, 0, 0,
  130882. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  130883. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  130884. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,13,13,
  130885. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,
  130886. 13,
  130887. };
  130888. static float _vq_quantthresh__44c4_s_p6_0[] = {
  130889. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  130890. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  130891. };
  130892. static long _vq_quantmap__44c4_s_p6_0[] = {
  130893. 15, 13, 11, 9, 7, 5, 3, 1,
  130894. 0, 2, 4, 6, 8, 10, 12, 14,
  130895. 16,
  130896. };
  130897. static encode_aux_threshmatch _vq_auxt__44c4_s_p6_0 = {
  130898. _vq_quantthresh__44c4_s_p6_0,
  130899. _vq_quantmap__44c4_s_p6_0,
  130900. 17,
  130901. 17
  130902. };
  130903. static static_codebook _44c4_s_p6_0 = {
  130904. 2, 289,
  130905. _vq_lengthlist__44c4_s_p6_0,
  130906. 1, -529530880, 1611661312, 5, 0,
  130907. _vq_quantlist__44c4_s_p6_0,
  130908. NULL,
  130909. &_vq_auxt__44c4_s_p6_0,
  130910. NULL,
  130911. 0
  130912. };
  130913. static long _vq_quantlist__44c4_s_p7_0[] = {
  130914. 1,
  130915. 0,
  130916. 2,
  130917. };
  130918. static long _vq_lengthlist__44c4_s_p7_0[] = {
  130919. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  130920. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  130921. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  130922. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  130923. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  130924. 10,
  130925. };
  130926. static float _vq_quantthresh__44c4_s_p7_0[] = {
  130927. -5.5, 5.5,
  130928. };
  130929. static long _vq_quantmap__44c4_s_p7_0[] = {
  130930. 1, 0, 2,
  130931. };
  130932. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_0 = {
  130933. _vq_quantthresh__44c4_s_p7_0,
  130934. _vq_quantmap__44c4_s_p7_0,
  130935. 3,
  130936. 3
  130937. };
  130938. static static_codebook _44c4_s_p7_0 = {
  130939. 4, 81,
  130940. _vq_lengthlist__44c4_s_p7_0,
  130941. 1, -529137664, 1618345984, 2, 0,
  130942. _vq_quantlist__44c4_s_p7_0,
  130943. NULL,
  130944. &_vq_auxt__44c4_s_p7_0,
  130945. NULL,
  130946. 0
  130947. };
  130948. static long _vq_quantlist__44c4_s_p7_1[] = {
  130949. 5,
  130950. 4,
  130951. 6,
  130952. 3,
  130953. 7,
  130954. 2,
  130955. 8,
  130956. 1,
  130957. 9,
  130958. 0,
  130959. 10,
  130960. };
  130961. static long _vq_lengthlist__44c4_s_p7_1[] = {
  130962. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  130963. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  130964. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  130965. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  130966. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  130967. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  130968. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  130969. 10,10,10, 8, 8, 8, 8, 9, 9,
  130970. };
  130971. static float _vq_quantthresh__44c4_s_p7_1[] = {
  130972. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  130973. 3.5, 4.5,
  130974. };
  130975. static long _vq_quantmap__44c4_s_p7_1[] = {
  130976. 9, 7, 5, 3, 1, 0, 2, 4,
  130977. 6, 8, 10,
  130978. };
  130979. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_1 = {
  130980. _vq_quantthresh__44c4_s_p7_1,
  130981. _vq_quantmap__44c4_s_p7_1,
  130982. 11,
  130983. 11
  130984. };
  130985. static static_codebook _44c4_s_p7_1 = {
  130986. 2, 121,
  130987. _vq_lengthlist__44c4_s_p7_1,
  130988. 1, -531365888, 1611661312, 4, 0,
  130989. _vq_quantlist__44c4_s_p7_1,
  130990. NULL,
  130991. &_vq_auxt__44c4_s_p7_1,
  130992. NULL,
  130993. 0
  130994. };
  130995. static long _vq_quantlist__44c4_s_p8_0[] = {
  130996. 6,
  130997. 5,
  130998. 7,
  130999. 4,
  131000. 8,
  131001. 3,
  131002. 9,
  131003. 2,
  131004. 10,
  131005. 1,
  131006. 11,
  131007. 0,
  131008. 12,
  131009. };
  131010. static long _vq_lengthlist__44c4_s_p8_0[] = {
  131011. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  131012. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  131013. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  131014. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  131015. 11, 0,12,12, 9, 9, 9, 9,10,10,10,10,11,11, 0,13,
  131016. 13, 9, 9,10, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  131017. 10,10,10,10,11,11,12,12, 0, 0, 0,10,10,10,10,10,
  131018. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  131019. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,13, 0,
  131020. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  131021. 0,13,12,12,12,12,12,13,13,
  131022. };
  131023. static float _vq_quantthresh__44c4_s_p8_0[] = {
  131024. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  131025. 12.5, 17.5, 22.5, 27.5,
  131026. };
  131027. static long _vq_quantmap__44c4_s_p8_0[] = {
  131028. 11, 9, 7, 5, 3, 1, 0, 2,
  131029. 4, 6, 8, 10, 12,
  131030. };
  131031. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_0 = {
  131032. _vq_quantthresh__44c4_s_p8_0,
  131033. _vq_quantmap__44c4_s_p8_0,
  131034. 13,
  131035. 13
  131036. };
  131037. static static_codebook _44c4_s_p8_0 = {
  131038. 2, 169,
  131039. _vq_lengthlist__44c4_s_p8_0,
  131040. 1, -526516224, 1616117760, 4, 0,
  131041. _vq_quantlist__44c4_s_p8_0,
  131042. NULL,
  131043. &_vq_auxt__44c4_s_p8_0,
  131044. NULL,
  131045. 0
  131046. };
  131047. static long _vq_quantlist__44c4_s_p8_1[] = {
  131048. 2,
  131049. 1,
  131050. 3,
  131051. 0,
  131052. 4,
  131053. };
  131054. static long _vq_lengthlist__44c4_s_p8_1[] = {
  131055. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 5, 4, 5, 5, 6,
  131056. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  131057. };
  131058. static float _vq_quantthresh__44c4_s_p8_1[] = {
  131059. -1.5, -0.5, 0.5, 1.5,
  131060. };
  131061. static long _vq_quantmap__44c4_s_p8_1[] = {
  131062. 3, 1, 0, 2, 4,
  131063. };
  131064. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_1 = {
  131065. _vq_quantthresh__44c4_s_p8_1,
  131066. _vq_quantmap__44c4_s_p8_1,
  131067. 5,
  131068. 5
  131069. };
  131070. static static_codebook _44c4_s_p8_1 = {
  131071. 2, 25,
  131072. _vq_lengthlist__44c4_s_p8_1,
  131073. 1, -533725184, 1611661312, 3, 0,
  131074. _vq_quantlist__44c4_s_p8_1,
  131075. NULL,
  131076. &_vq_auxt__44c4_s_p8_1,
  131077. NULL,
  131078. 0
  131079. };
  131080. static long _vq_quantlist__44c4_s_p9_0[] = {
  131081. 6,
  131082. 5,
  131083. 7,
  131084. 4,
  131085. 8,
  131086. 3,
  131087. 9,
  131088. 2,
  131089. 10,
  131090. 1,
  131091. 11,
  131092. 0,
  131093. 12,
  131094. };
  131095. static long _vq_lengthlist__44c4_s_p9_0[] = {
  131096. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 4, 7, 7,
  131097. 12,12,12,12,12,12,12,12,12,12, 3, 8, 8,12,12,12,
  131098. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131099. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131100. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131101. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131102. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131103. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131104. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131105. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131106. 12,12,12,12,12,12,12,12,12,
  131107. };
  131108. static float _vq_quantthresh__44c4_s_p9_0[] = {
  131109. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  131110. 787.5, 1102.5, 1417.5, 1732.5,
  131111. };
  131112. static long _vq_quantmap__44c4_s_p9_0[] = {
  131113. 11, 9, 7, 5, 3, 1, 0, 2,
  131114. 4, 6, 8, 10, 12,
  131115. };
  131116. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_0 = {
  131117. _vq_quantthresh__44c4_s_p9_0,
  131118. _vq_quantmap__44c4_s_p9_0,
  131119. 13,
  131120. 13
  131121. };
  131122. static static_codebook _44c4_s_p9_0 = {
  131123. 2, 169,
  131124. _vq_lengthlist__44c4_s_p9_0,
  131125. 1, -513964032, 1628680192, 4, 0,
  131126. _vq_quantlist__44c4_s_p9_0,
  131127. NULL,
  131128. &_vq_auxt__44c4_s_p9_0,
  131129. NULL,
  131130. 0
  131131. };
  131132. static long _vq_quantlist__44c4_s_p9_1[] = {
  131133. 7,
  131134. 6,
  131135. 8,
  131136. 5,
  131137. 9,
  131138. 4,
  131139. 10,
  131140. 3,
  131141. 11,
  131142. 2,
  131143. 12,
  131144. 1,
  131145. 13,
  131146. 0,
  131147. 14,
  131148. };
  131149. static long _vq_lengthlist__44c4_s_p9_1[] = {
  131150. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,10,10, 6,
  131151. 5, 5, 7, 7, 9, 8,10, 9,11,10,12,12,13,13, 6, 5,
  131152. 5, 7, 7, 9, 9,10,10,11,11,12,12,12,13,19, 8, 8,
  131153. 8, 8, 9, 9,10,10,12,11,12,12,13,13,19, 8, 8, 8,
  131154. 8, 9, 9,11,11,12,12,13,13,13,13,19,12,12, 9, 9,
  131155. 11,11,11,11,12,11,13,12,13,13,18,12,12, 9, 9,11,
  131156. 10,11,11,12,12,12,13,13,14,19,18,18,11,11,11,11,
  131157. 12,12,13,12,13,13,14,14,16,18,18,11,11,11,10,12,
  131158. 11,13,13,13,13,13,14,17,18,18,14,15,11,12,12,13,
  131159. 13,13,13,14,14,14,18,18,18,15,15,12,10,13,10,13,
  131160. 13,13,13,13,14,18,17,18,17,18,12,13,12,13,13,13,
  131161. 14,14,16,14,18,17,18,18,17,13,12,13,10,12,12,14,
  131162. 14,14,14,17,18,18,18,18,14,15,12,12,13,12,14,14,
  131163. 15,15,18,18,18,17,18,15,14,12,11,12,12,14,14,14,
  131164. 15,
  131165. };
  131166. static float _vq_quantthresh__44c4_s_p9_1[] = {
  131167. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  131168. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  131169. };
  131170. static long _vq_quantmap__44c4_s_p9_1[] = {
  131171. 13, 11, 9, 7, 5, 3, 1, 0,
  131172. 2, 4, 6, 8, 10, 12, 14,
  131173. };
  131174. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_1 = {
  131175. _vq_quantthresh__44c4_s_p9_1,
  131176. _vq_quantmap__44c4_s_p9_1,
  131177. 15,
  131178. 15
  131179. };
  131180. static static_codebook _44c4_s_p9_1 = {
  131181. 2, 225,
  131182. _vq_lengthlist__44c4_s_p9_1,
  131183. 1, -520986624, 1620377600, 4, 0,
  131184. _vq_quantlist__44c4_s_p9_1,
  131185. NULL,
  131186. &_vq_auxt__44c4_s_p9_1,
  131187. NULL,
  131188. 0
  131189. };
  131190. static long _vq_quantlist__44c4_s_p9_2[] = {
  131191. 10,
  131192. 9,
  131193. 11,
  131194. 8,
  131195. 12,
  131196. 7,
  131197. 13,
  131198. 6,
  131199. 14,
  131200. 5,
  131201. 15,
  131202. 4,
  131203. 16,
  131204. 3,
  131205. 17,
  131206. 2,
  131207. 18,
  131208. 1,
  131209. 19,
  131210. 0,
  131211. 20,
  131212. };
  131213. static long _vq_lengthlist__44c4_s_p9_2[] = {
  131214. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  131215. 8, 9, 9, 9, 9,11, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  131216. 9, 9, 9, 9, 9, 9,10,10,10,10,11, 6, 6, 7, 7, 8,
  131217. 8, 8, 8, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  131218. 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  131219. 10,10,10,10,12,11,11, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  131220. 9,10,10,10,10,10,10,10,10,12,11,12, 8, 8, 8, 8,
  131221. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  131222. 11, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,
  131223. 10,10,10,11,11,12, 9, 9, 9, 9, 9, 9,10, 9,10,10,
  131224. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  131225. 9,10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,
  131226. 11,11, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  131227. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  131228. 10,10,10,10,10,10,10,11,11,11,12,12,10,10,10,10,
  131229. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,12,
  131230. 11,11,11, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  131231. 10,11,12,11,11,11,11,11,10,10,10,10,10,10,10,10,
  131232. 10,10,10,10,10,10,11,11,11,12,11,11,11,10,10,10,
  131233. 10,10,10,10,10,10,10,10,10,10,10,12,11,11,12,11,
  131234. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131235. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  131236. 10,10,10,10,10,11,11,11,11,12,12,11,11,11,11,11,
  131237. 11,11,10,10,10,10,10,10,10,10,12,12,12,11,11,11,
  131238. 12,11,11,11,10,10,10,10,10,10,10,10,10,10,10,12,
  131239. 11,12,12,12,12,12,11,12,11,11,10,10,10,10,10,10,
  131240. 10,10,10,10,12,12,12,12,11,11,11,11,11,11,11,10,
  131241. 10,10,10,10,10,10,10,10,10,
  131242. };
  131243. static float _vq_quantthresh__44c4_s_p9_2[] = {
  131244. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  131245. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  131246. 6.5, 7.5, 8.5, 9.5,
  131247. };
  131248. static long _vq_quantmap__44c4_s_p9_2[] = {
  131249. 19, 17, 15, 13, 11, 9, 7, 5,
  131250. 3, 1, 0, 2, 4, 6, 8, 10,
  131251. 12, 14, 16, 18, 20,
  131252. };
  131253. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_2 = {
  131254. _vq_quantthresh__44c4_s_p9_2,
  131255. _vq_quantmap__44c4_s_p9_2,
  131256. 21,
  131257. 21
  131258. };
  131259. static static_codebook _44c4_s_p9_2 = {
  131260. 2, 441,
  131261. _vq_lengthlist__44c4_s_p9_2,
  131262. 1, -529268736, 1611661312, 5, 0,
  131263. _vq_quantlist__44c4_s_p9_2,
  131264. NULL,
  131265. &_vq_auxt__44c4_s_p9_2,
  131266. NULL,
  131267. 0
  131268. };
  131269. static long _huff_lengthlist__44c4_s_short[] = {
  131270. 4, 7,14,10,15,10,12,15,16,15, 4, 2,11, 5,10, 6,
  131271. 8,11,14,14,14,10, 7,11, 6, 8,10,11,13,15, 9, 4,
  131272. 11, 5, 9, 6, 9,12,14,15,14, 9, 6, 9, 4, 5, 7,10,
  131273. 12,13, 9, 5, 7, 6, 5, 5, 7,10,13,13,10, 8, 9, 8,
  131274. 7, 6, 8,10,14,14,13,11,10,10, 7, 7, 8,11,14,15,
  131275. 13,12, 9, 9, 6, 5, 7,10,14,17,15,13,11,10, 6, 6,
  131276. 7, 9,12,17,
  131277. };
  131278. static static_codebook _huff_book__44c4_s_short = {
  131279. 2, 100,
  131280. _huff_lengthlist__44c4_s_short,
  131281. 0, 0, 0, 0, 0,
  131282. NULL,
  131283. NULL,
  131284. NULL,
  131285. NULL,
  131286. 0
  131287. };
  131288. static long _huff_lengthlist__44c5_s_long[] = {
  131289. 3, 8, 9,13,10,12,12,12,12,12, 6, 4, 6, 8, 6, 8,
  131290. 10,10,11,12, 8, 5, 4,10, 4, 7, 8, 9,10,11,13, 8,
  131291. 10, 8, 9, 9,11,12,13,14,10, 6, 4, 9, 3, 5, 6, 8,
  131292. 10,11,11, 8, 6, 9, 5, 5, 6, 7, 9,11,12, 9, 7,11,
  131293. 6, 6, 6, 7, 8,10,12,11, 9,12, 7, 7, 6, 6, 7, 9,
  131294. 13,12,10,13, 9, 8, 7, 7, 7, 8,11,15,11,15,11,10,
  131295. 9, 8, 7, 7,
  131296. };
  131297. static static_codebook _huff_book__44c5_s_long = {
  131298. 2, 100,
  131299. _huff_lengthlist__44c5_s_long,
  131300. 0, 0, 0, 0, 0,
  131301. NULL,
  131302. NULL,
  131303. NULL,
  131304. NULL,
  131305. 0
  131306. };
  131307. static long _vq_quantlist__44c5_s_p1_0[] = {
  131308. 1,
  131309. 0,
  131310. 2,
  131311. };
  131312. static long _vq_lengthlist__44c5_s_p1_0[] = {
  131313. 2, 4, 4, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  131314. 0, 0, 4, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131318. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  131319. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131323. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  131324. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  131359. 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  131360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  131364. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  131365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  131369. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  131370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131404. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  131405. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131409. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  131410. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  131411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131414. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  131415. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  131416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  131614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131617. 0, 0, 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, 0, 0, 0, 0, 0, 0,
  131619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131622. 0, 0, 0, 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, 0, 0, 0, 0, 0,
  131624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131627. 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131723. 0,
  131724. };
  131725. static float _vq_quantthresh__44c5_s_p1_0[] = {
  131726. -0.5, 0.5,
  131727. };
  131728. static long _vq_quantmap__44c5_s_p1_0[] = {
  131729. 1, 0, 2,
  131730. };
  131731. static encode_aux_threshmatch _vq_auxt__44c5_s_p1_0 = {
  131732. _vq_quantthresh__44c5_s_p1_0,
  131733. _vq_quantmap__44c5_s_p1_0,
  131734. 3,
  131735. 3
  131736. };
  131737. static static_codebook _44c5_s_p1_0 = {
  131738. 8, 6561,
  131739. _vq_lengthlist__44c5_s_p1_0,
  131740. 1, -535822336, 1611661312, 2, 0,
  131741. _vq_quantlist__44c5_s_p1_0,
  131742. NULL,
  131743. &_vq_auxt__44c5_s_p1_0,
  131744. NULL,
  131745. 0
  131746. };
  131747. static long _vq_quantlist__44c5_s_p2_0[] = {
  131748. 2,
  131749. 1,
  131750. 3,
  131751. 0,
  131752. 4,
  131753. };
  131754. static long _vq_lengthlist__44c5_s_p2_0[] = {
  131755. 2, 4, 4, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  131756. 8, 7, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  131757. 8, 0, 0, 0, 8, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  131758. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 7, 8, 0,
  131759. 0, 0,10,10, 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, 5, 8, 7, 0, 0, 0, 8, 8, 0, 0,
  131765. 0, 8, 8, 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5,
  131766. 7, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,
  131767. 10, 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, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8,
  131773. 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0,
  131774. 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,10, 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. 8,10,10, 0, 0, 0,10,10, 0, 0, 0, 9,10, 0, 0, 0,
  131781. 11,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0,10,
  131782. 10, 0, 0, 0,10,10, 0, 0, 0,10,11, 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,
  131795. };
  131796. static float _vq_quantthresh__44c5_s_p2_0[] = {
  131797. -1.5, -0.5, 0.5, 1.5,
  131798. };
  131799. static long _vq_quantmap__44c5_s_p2_0[] = {
  131800. 3, 1, 0, 2, 4,
  131801. };
  131802. static encode_aux_threshmatch _vq_auxt__44c5_s_p2_0 = {
  131803. _vq_quantthresh__44c5_s_p2_0,
  131804. _vq_quantmap__44c5_s_p2_0,
  131805. 5,
  131806. 5
  131807. };
  131808. static static_codebook _44c5_s_p2_0 = {
  131809. 4, 625,
  131810. _vq_lengthlist__44c5_s_p2_0,
  131811. 1, -533725184, 1611661312, 3, 0,
  131812. _vq_quantlist__44c5_s_p2_0,
  131813. NULL,
  131814. &_vq_auxt__44c5_s_p2_0,
  131815. NULL,
  131816. 0
  131817. };
  131818. static long _vq_quantlist__44c5_s_p3_0[] = {
  131819. 2,
  131820. 1,
  131821. 3,
  131822. 0,
  131823. 4,
  131824. };
  131825. static long _vq_lengthlist__44c5_s_p3_0[] = {
  131826. 2, 4, 3, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 6, 6, 0, 0,
  131828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131829. 0, 0, 3, 5, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  131831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131832. 0, 0, 0, 0, 5, 6, 6, 8, 8, 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,
  131866. };
  131867. static float _vq_quantthresh__44c5_s_p3_0[] = {
  131868. -1.5, -0.5, 0.5, 1.5,
  131869. };
  131870. static long _vq_quantmap__44c5_s_p3_0[] = {
  131871. 3, 1, 0, 2, 4,
  131872. };
  131873. static encode_aux_threshmatch _vq_auxt__44c5_s_p3_0 = {
  131874. _vq_quantthresh__44c5_s_p3_0,
  131875. _vq_quantmap__44c5_s_p3_0,
  131876. 5,
  131877. 5
  131878. };
  131879. static static_codebook _44c5_s_p3_0 = {
  131880. 4, 625,
  131881. _vq_lengthlist__44c5_s_p3_0,
  131882. 1, -533725184, 1611661312, 3, 0,
  131883. _vq_quantlist__44c5_s_p3_0,
  131884. NULL,
  131885. &_vq_auxt__44c5_s_p3_0,
  131886. NULL,
  131887. 0
  131888. };
  131889. static long _vq_quantlist__44c5_s_p4_0[] = {
  131890. 4,
  131891. 3,
  131892. 5,
  131893. 2,
  131894. 6,
  131895. 1,
  131896. 7,
  131897. 0,
  131898. 8,
  131899. };
  131900. static long _vq_lengthlist__44c5_s_p4_0[] = {
  131901. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  131902. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  131903. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  131904. 7, 7, 0, 0, 0, 0, 0, 0, 0, 8, 7, 0, 0, 0, 0, 0,
  131905. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131906. 0,
  131907. };
  131908. static float _vq_quantthresh__44c5_s_p4_0[] = {
  131909. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  131910. };
  131911. static long _vq_quantmap__44c5_s_p4_0[] = {
  131912. 7, 5, 3, 1, 0, 2, 4, 6,
  131913. 8,
  131914. };
  131915. static encode_aux_threshmatch _vq_auxt__44c5_s_p4_0 = {
  131916. _vq_quantthresh__44c5_s_p4_0,
  131917. _vq_quantmap__44c5_s_p4_0,
  131918. 9,
  131919. 9
  131920. };
  131921. static static_codebook _44c5_s_p4_0 = {
  131922. 2, 81,
  131923. _vq_lengthlist__44c5_s_p4_0,
  131924. 1, -531628032, 1611661312, 4, 0,
  131925. _vq_quantlist__44c5_s_p4_0,
  131926. NULL,
  131927. &_vq_auxt__44c5_s_p4_0,
  131928. NULL,
  131929. 0
  131930. };
  131931. static long _vq_quantlist__44c5_s_p5_0[] = {
  131932. 4,
  131933. 3,
  131934. 5,
  131935. 2,
  131936. 6,
  131937. 1,
  131938. 7,
  131939. 0,
  131940. 8,
  131941. };
  131942. static long _vq_lengthlist__44c5_s_p5_0[] = {
  131943. 2, 4, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  131944. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  131945. 7, 7, 9, 9, 0, 0, 0, 7, 6, 7, 7, 9, 9, 0, 0, 0,
  131946. 8, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  131947. 0, 0, 9, 9, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  131948. 10,
  131949. };
  131950. static float _vq_quantthresh__44c5_s_p5_0[] = {
  131951. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  131952. };
  131953. static long _vq_quantmap__44c5_s_p5_0[] = {
  131954. 7, 5, 3, 1, 0, 2, 4, 6,
  131955. 8,
  131956. };
  131957. static encode_aux_threshmatch _vq_auxt__44c5_s_p5_0 = {
  131958. _vq_quantthresh__44c5_s_p5_0,
  131959. _vq_quantmap__44c5_s_p5_0,
  131960. 9,
  131961. 9
  131962. };
  131963. static static_codebook _44c5_s_p5_0 = {
  131964. 2, 81,
  131965. _vq_lengthlist__44c5_s_p5_0,
  131966. 1, -531628032, 1611661312, 4, 0,
  131967. _vq_quantlist__44c5_s_p5_0,
  131968. NULL,
  131969. &_vq_auxt__44c5_s_p5_0,
  131970. NULL,
  131971. 0
  131972. };
  131973. static long _vq_quantlist__44c5_s_p6_0[] = {
  131974. 8,
  131975. 7,
  131976. 9,
  131977. 6,
  131978. 10,
  131979. 5,
  131980. 11,
  131981. 4,
  131982. 12,
  131983. 3,
  131984. 13,
  131985. 2,
  131986. 14,
  131987. 1,
  131988. 15,
  131989. 0,
  131990. 16,
  131991. };
  131992. static long _vq_lengthlist__44c5_s_p6_0[] = {
  131993. 2, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,11,
  131994. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  131995. 12,12, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  131996. 11,12,12, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  131997. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  131998. 10,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  131999. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 9,10,10,10,
  132000. 10,11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,
  132001. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  132002. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  132003. 10,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9,
  132004. 9, 9,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  132005. 10,10,10,10,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  132006. 0, 0, 0,10,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  132007. 0, 0, 0, 0,11,11,11,11,12,12,12,13,13,13, 0, 0,
  132008. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  132009. 0, 0, 0, 0, 0, 0,12,12,12,12,13,12,13,13,13,13,
  132010. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  132011. 13,
  132012. };
  132013. static float _vq_quantthresh__44c5_s_p6_0[] = {
  132014. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132015. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132016. };
  132017. static long _vq_quantmap__44c5_s_p6_0[] = {
  132018. 15, 13, 11, 9, 7, 5, 3, 1,
  132019. 0, 2, 4, 6, 8, 10, 12, 14,
  132020. 16,
  132021. };
  132022. static encode_aux_threshmatch _vq_auxt__44c5_s_p6_0 = {
  132023. _vq_quantthresh__44c5_s_p6_0,
  132024. _vq_quantmap__44c5_s_p6_0,
  132025. 17,
  132026. 17
  132027. };
  132028. static static_codebook _44c5_s_p6_0 = {
  132029. 2, 289,
  132030. _vq_lengthlist__44c5_s_p6_0,
  132031. 1, -529530880, 1611661312, 5, 0,
  132032. _vq_quantlist__44c5_s_p6_0,
  132033. NULL,
  132034. &_vq_auxt__44c5_s_p6_0,
  132035. NULL,
  132036. 0
  132037. };
  132038. static long _vq_quantlist__44c5_s_p7_0[] = {
  132039. 1,
  132040. 0,
  132041. 2,
  132042. };
  132043. static long _vq_lengthlist__44c5_s_p7_0[] = {
  132044. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  132045. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  132046. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  132047. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  132048. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  132049. 10,
  132050. };
  132051. static float _vq_quantthresh__44c5_s_p7_0[] = {
  132052. -5.5, 5.5,
  132053. };
  132054. static long _vq_quantmap__44c5_s_p7_0[] = {
  132055. 1, 0, 2,
  132056. };
  132057. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_0 = {
  132058. _vq_quantthresh__44c5_s_p7_0,
  132059. _vq_quantmap__44c5_s_p7_0,
  132060. 3,
  132061. 3
  132062. };
  132063. static static_codebook _44c5_s_p7_0 = {
  132064. 4, 81,
  132065. _vq_lengthlist__44c5_s_p7_0,
  132066. 1, -529137664, 1618345984, 2, 0,
  132067. _vq_quantlist__44c5_s_p7_0,
  132068. NULL,
  132069. &_vq_auxt__44c5_s_p7_0,
  132070. NULL,
  132071. 0
  132072. };
  132073. static long _vq_quantlist__44c5_s_p7_1[] = {
  132074. 5,
  132075. 4,
  132076. 6,
  132077. 3,
  132078. 7,
  132079. 2,
  132080. 8,
  132081. 1,
  132082. 9,
  132083. 0,
  132084. 10,
  132085. };
  132086. static long _vq_lengthlist__44c5_s_p7_1[] = {
  132087. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6,
  132088. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  132089. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  132090. 7, 8, 8, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  132091. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  132092. 8, 8, 8, 8, 8, 8, 8, 9,10,10,10,10,10, 8, 8, 8,
  132093. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  132094. 10,10,10, 8, 8, 8, 8, 8, 8,
  132095. };
  132096. static float _vq_quantthresh__44c5_s_p7_1[] = {
  132097. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132098. 3.5, 4.5,
  132099. };
  132100. static long _vq_quantmap__44c5_s_p7_1[] = {
  132101. 9, 7, 5, 3, 1, 0, 2, 4,
  132102. 6, 8, 10,
  132103. };
  132104. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_1 = {
  132105. _vq_quantthresh__44c5_s_p7_1,
  132106. _vq_quantmap__44c5_s_p7_1,
  132107. 11,
  132108. 11
  132109. };
  132110. static static_codebook _44c5_s_p7_1 = {
  132111. 2, 121,
  132112. _vq_lengthlist__44c5_s_p7_1,
  132113. 1, -531365888, 1611661312, 4, 0,
  132114. _vq_quantlist__44c5_s_p7_1,
  132115. NULL,
  132116. &_vq_auxt__44c5_s_p7_1,
  132117. NULL,
  132118. 0
  132119. };
  132120. static long _vq_quantlist__44c5_s_p8_0[] = {
  132121. 6,
  132122. 5,
  132123. 7,
  132124. 4,
  132125. 8,
  132126. 3,
  132127. 9,
  132128. 2,
  132129. 10,
  132130. 1,
  132131. 11,
  132132. 0,
  132133. 12,
  132134. };
  132135. static long _vq_lengthlist__44c5_s_p8_0[] = {
  132136. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  132137. 7, 7, 8, 8, 8, 9,10,10,10,10, 7, 5, 5, 7, 7, 8,
  132138. 8, 9, 9,10,10,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  132139. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  132140. 11, 0,12,12, 9, 9, 9,10,10,10,10,10,11,11, 0,13,
  132141. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  132142. 10,10,10,10,11,11,11,11, 0, 0, 0,10,10,10,10,10,
  132143. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  132144. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,12, 0,
  132145. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  132146. 0,12,12,12,12,12,12,13,13,
  132147. };
  132148. static float _vq_quantthresh__44c5_s_p8_0[] = {
  132149. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  132150. 12.5, 17.5, 22.5, 27.5,
  132151. };
  132152. static long _vq_quantmap__44c5_s_p8_0[] = {
  132153. 11, 9, 7, 5, 3, 1, 0, 2,
  132154. 4, 6, 8, 10, 12,
  132155. };
  132156. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_0 = {
  132157. _vq_quantthresh__44c5_s_p8_0,
  132158. _vq_quantmap__44c5_s_p8_0,
  132159. 13,
  132160. 13
  132161. };
  132162. static static_codebook _44c5_s_p8_0 = {
  132163. 2, 169,
  132164. _vq_lengthlist__44c5_s_p8_0,
  132165. 1, -526516224, 1616117760, 4, 0,
  132166. _vq_quantlist__44c5_s_p8_0,
  132167. NULL,
  132168. &_vq_auxt__44c5_s_p8_0,
  132169. NULL,
  132170. 0
  132171. };
  132172. static long _vq_quantlist__44c5_s_p8_1[] = {
  132173. 2,
  132174. 1,
  132175. 3,
  132176. 0,
  132177. 4,
  132178. };
  132179. static long _vq_lengthlist__44c5_s_p8_1[] = {
  132180. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  132181. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  132182. };
  132183. static float _vq_quantthresh__44c5_s_p8_1[] = {
  132184. -1.5, -0.5, 0.5, 1.5,
  132185. };
  132186. static long _vq_quantmap__44c5_s_p8_1[] = {
  132187. 3, 1, 0, 2, 4,
  132188. };
  132189. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_1 = {
  132190. _vq_quantthresh__44c5_s_p8_1,
  132191. _vq_quantmap__44c5_s_p8_1,
  132192. 5,
  132193. 5
  132194. };
  132195. static static_codebook _44c5_s_p8_1 = {
  132196. 2, 25,
  132197. _vq_lengthlist__44c5_s_p8_1,
  132198. 1, -533725184, 1611661312, 3, 0,
  132199. _vq_quantlist__44c5_s_p8_1,
  132200. NULL,
  132201. &_vq_auxt__44c5_s_p8_1,
  132202. NULL,
  132203. 0
  132204. };
  132205. static long _vq_quantlist__44c5_s_p9_0[] = {
  132206. 7,
  132207. 6,
  132208. 8,
  132209. 5,
  132210. 9,
  132211. 4,
  132212. 10,
  132213. 3,
  132214. 11,
  132215. 2,
  132216. 12,
  132217. 1,
  132218. 13,
  132219. 0,
  132220. 14,
  132221. };
  132222. static long _vq_lengthlist__44c5_s_p9_0[] = {
  132223. 1, 3, 3,13,13,13,13,13,13,13,13,13,13,13,13, 4,
  132224. 7, 7,13,13,13,13,13,13,13,13,13,13,13,13, 3, 8,
  132225. 6,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132226. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132227. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132228. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132229. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132230. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132231. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132232. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132233. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132234. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132235. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132236. 13,13,13,13,13,13,13,13,13,12,12,12,12,12,12,12,
  132237. 12,
  132238. };
  132239. static float _vq_quantthresh__44c5_s_p9_0[] = {
  132240. -2320.5, -1963.5, -1606.5, -1249.5, -892.5, -535.5, -178.5, 178.5,
  132241. 535.5, 892.5, 1249.5, 1606.5, 1963.5, 2320.5,
  132242. };
  132243. static long _vq_quantmap__44c5_s_p9_0[] = {
  132244. 13, 11, 9, 7, 5, 3, 1, 0,
  132245. 2, 4, 6, 8, 10, 12, 14,
  132246. };
  132247. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_0 = {
  132248. _vq_quantthresh__44c5_s_p9_0,
  132249. _vq_quantmap__44c5_s_p9_0,
  132250. 15,
  132251. 15
  132252. };
  132253. static static_codebook _44c5_s_p9_0 = {
  132254. 2, 225,
  132255. _vq_lengthlist__44c5_s_p9_0,
  132256. 1, -512522752, 1628852224, 4, 0,
  132257. _vq_quantlist__44c5_s_p9_0,
  132258. NULL,
  132259. &_vq_auxt__44c5_s_p9_0,
  132260. NULL,
  132261. 0
  132262. };
  132263. static long _vq_quantlist__44c5_s_p9_1[] = {
  132264. 8,
  132265. 7,
  132266. 9,
  132267. 6,
  132268. 10,
  132269. 5,
  132270. 11,
  132271. 4,
  132272. 12,
  132273. 3,
  132274. 13,
  132275. 2,
  132276. 14,
  132277. 1,
  132278. 15,
  132279. 0,
  132280. 16,
  132281. };
  132282. static long _vq_lengthlist__44c5_s_p9_1[] = {
  132283. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,11,10,11,
  132284. 11, 6, 5, 5, 7, 7, 8, 9,10,10,11,10,12,11,12,11,
  132285. 13,12, 6, 5, 5, 7, 7, 9, 9,10,10,11,11,12,12,13,
  132286. 12,13,13,18, 8, 8, 8, 8, 9, 9,10,11,11,11,12,11,
  132287. 13,11,13,12,18, 8, 8, 8, 8,10,10,11,11,12,12,13,
  132288. 13,13,13,13,14,18,12,12, 9, 9,11,11,11,11,12,12,
  132289. 13,12,13,12,13,13,20,13,12, 9, 9,11,11,11,11,12,
  132290. 12,13,13,13,14,14,13,20,18,19,11,12,11,11,12,12,
  132291. 13,13,13,13,13,13,14,13,18,19,19,12,11,11,11,12,
  132292. 12,13,12,13,13,13,14,14,13,18,17,19,14,15,12,12,
  132293. 12,13,13,13,14,14,14,14,14,14,19,19,19,16,15,12,
  132294. 11,13,12,14,14,14,13,13,14,14,14,19,18,19,18,19,
  132295. 13,13,13,13,14,14,14,13,14,14,14,14,18,17,19,19,
  132296. 19,13,13,13,11,13,11,13,14,14,14,14,14,19,17,17,
  132297. 18,18,16,16,13,13,13,13,14,13,15,15,14,14,19,19,
  132298. 17,17,18,16,16,13,11,14,10,13,12,14,14,14,14,19,
  132299. 19,19,19,19,18,17,13,14,13,11,14,13,14,14,15,15,
  132300. 19,19,19,17,19,18,18,14,13,12,11,14,11,15,15,15,
  132301. 15,
  132302. };
  132303. static float _vq_quantthresh__44c5_s_p9_1[] = {
  132304. -157.5, -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5,
  132305. 10.5, 31.5, 52.5, 73.5, 94.5, 115.5, 136.5, 157.5,
  132306. };
  132307. static long _vq_quantmap__44c5_s_p9_1[] = {
  132308. 15, 13, 11, 9, 7, 5, 3, 1,
  132309. 0, 2, 4, 6, 8, 10, 12, 14,
  132310. 16,
  132311. };
  132312. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_1 = {
  132313. _vq_quantthresh__44c5_s_p9_1,
  132314. _vq_quantmap__44c5_s_p9_1,
  132315. 17,
  132316. 17
  132317. };
  132318. static static_codebook _44c5_s_p9_1 = {
  132319. 2, 289,
  132320. _vq_lengthlist__44c5_s_p9_1,
  132321. 1, -520814592, 1620377600, 5, 0,
  132322. _vq_quantlist__44c5_s_p9_1,
  132323. NULL,
  132324. &_vq_auxt__44c5_s_p9_1,
  132325. NULL,
  132326. 0
  132327. };
  132328. static long _vq_quantlist__44c5_s_p9_2[] = {
  132329. 10,
  132330. 9,
  132331. 11,
  132332. 8,
  132333. 12,
  132334. 7,
  132335. 13,
  132336. 6,
  132337. 14,
  132338. 5,
  132339. 15,
  132340. 4,
  132341. 16,
  132342. 3,
  132343. 17,
  132344. 2,
  132345. 18,
  132346. 1,
  132347. 19,
  132348. 0,
  132349. 20,
  132350. };
  132351. static long _vq_lengthlist__44c5_s_p9_2[] = {
  132352. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  132353. 8, 8, 8, 8, 9,11, 5, 6, 7, 7, 8, 7, 8, 8, 8, 8,
  132354. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11, 5, 5, 7, 7, 7,
  132355. 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  132356. 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  132357. 9,10, 9,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  132358. 9, 9, 9,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  132359. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,11,11,
  132360. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  132361. 10,10,10,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132362. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  132363. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,11,11,11,
  132364. 11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,
  132365. 10,10,11,11,11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,
  132366. 10,10,10,10,10,10,10,11,11,11,11,11, 9, 9,10, 9,
  132367. 10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,
  132368. 11,11,11, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  132369. 10,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  132370. 10,10,10,10,10,10,11,11,11,11,11,11,11,10,10,10,
  132371. 10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,
  132372. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132373. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  132374. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  132375. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  132376. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,11,
  132377. 11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  132378. 10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,10,
  132379. 10,10,10,10,10,10,10,10,10,
  132380. };
  132381. static float _vq_quantthresh__44c5_s_p9_2[] = {
  132382. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  132383. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  132384. 6.5, 7.5, 8.5, 9.5,
  132385. };
  132386. static long _vq_quantmap__44c5_s_p9_2[] = {
  132387. 19, 17, 15, 13, 11, 9, 7, 5,
  132388. 3, 1, 0, 2, 4, 6, 8, 10,
  132389. 12, 14, 16, 18, 20,
  132390. };
  132391. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_2 = {
  132392. _vq_quantthresh__44c5_s_p9_2,
  132393. _vq_quantmap__44c5_s_p9_2,
  132394. 21,
  132395. 21
  132396. };
  132397. static static_codebook _44c5_s_p9_2 = {
  132398. 2, 441,
  132399. _vq_lengthlist__44c5_s_p9_2,
  132400. 1, -529268736, 1611661312, 5, 0,
  132401. _vq_quantlist__44c5_s_p9_2,
  132402. NULL,
  132403. &_vq_auxt__44c5_s_p9_2,
  132404. NULL,
  132405. 0
  132406. };
  132407. static long _huff_lengthlist__44c5_s_short[] = {
  132408. 5, 8,10,14,11,11,12,16,15,17, 5, 5, 7, 9, 7, 8,
  132409. 10,13,17,17, 7, 5, 5,10, 5, 7, 8,11,13,15,10, 8,
  132410. 10, 8, 8, 8,11,15,18,18, 8, 5, 5, 8, 3, 4, 6,10,
  132411. 14,16, 9, 7, 6, 7, 4, 3, 5, 9,14,18,10, 9, 8,10,
  132412. 6, 5, 6, 9,14,18,12,12,11,12, 8, 7, 8,11,14,18,
  132413. 14,13,12,10, 7, 5, 6, 9,14,18,14,14,13,10, 6, 5,
  132414. 6, 8,11,16,
  132415. };
  132416. static static_codebook _huff_book__44c5_s_short = {
  132417. 2, 100,
  132418. _huff_lengthlist__44c5_s_short,
  132419. 0, 0, 0, 0, 0,
  132420. NULL,
  132421. NULL,
  132422. NULL,
  132423. NULL,
  132424. 0
  132425. };
  132426. static long _huff_lengthlist__44c6_s_long[] = {
  132427. 3, 8,11,13,14,14,13,13,16,14, 6, 3, 4, 7, 9, 9,
  132428. 10,11,14,13,10, 4, 3, 5, 7, 7, 9,10,13,15,12, 7,
  132429. 4, 4, 6, 6, 8,10,13,15,12, 8, 6, 6, 6, 6, 8,10,
  132430. 13,14,11, 9, 7, 6, 6, 6, 7, 8,12,11,13,10, 9, 8,
  132431. 7, 6, 6, 7,11,11,13,11,10, 9, 9, 7, 7, 6,10,11,
  132432. 13,13,13,13,13,11, 9, 8,10,12,12,15,15,16,15,12,
  132433. 11,10,10,12,
  132434. };
  132435. static static_codebook _huff_book__44c6_s_long = {
  132436. 2, 100,
  132437. _huff_lengthlist__44c6_s_long,
  132438. 0, 0, 0, 0, 0,
  132439. NULL,
  132440. NULL,
  132441. NULL,
  132442. NULL,
  132443. 0
  132444. };
  132445. static long _vq_quantlist__44c6_s_p1_0[] = {
  132446. 1,
  132447. 0,
  132448. 2,
  132449. };
  132450. static long _vq_lengthlist__44c6_s_p1_0[] = {
  132451. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  132452. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  132453. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  132454. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  132455. 9, 9, 0, 8, 8, 0, 8, 8, 5, 9, 9, 0, 8, 8, 0, 8,
  132456. 8,
  132457. };
  132458. static float _vq_quantthresh__44c6_s_p1_0[] = {
  132459. -0.5, 0.5,
  132460. };
  132461. static long _vq_quantmap__44c6_s_p1_0[] = {
  132462. 1, 0, 2,
  132463. };
  132464. static encode_aux_threshmatch _vq_auxt__44c6_s_p1_0 = {
  132465. _vq_quantthresh__44c6_s_p1_0,
  132466. _vq_quantmap__44c6_s_p1_0,
  132467. 3,
  132468. 3
  132469. };
  132470. static static_codebook _44c6_s_p1_0 = {
  132471. 4, 81,
  132472. _vq_lengthlist__44c6_s_p1_0,
  132473. 1, -535822336, 1611661312, 2, 0,
  132474. _vq_quantlist__44c6_s_p1_0,
  132475. NULL,
  132476. &_vq_auxt__44c6_s_p1_0,
  132477. NULL,
  132478. 0
  132479. };
  132480. static long _vq_quantlist__44c6_s_p2_0[] = {
  132481. 2,
  132482. 1,
  132483. 3,
  132484. 0,
  132485. 4,
  132486. };
  132487. static long _vq_lengthlist__44c6_s_p2_0[] = {
  132488. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  132489. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  132490. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  132491. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  132492. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,11,
  132493. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  132494. 0, 0,14,13, 8, 9, 9,11,11, 0,11,11,12,12, 0,10,
  132495. 11,12,12, 0,14,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  132496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132497. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  132498. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  132499. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  132500. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  132501. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  132502. 13, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,12,12,
  132503. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  132504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132505. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  132506. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,11,
  132507. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,11,
  132508. 0, 0, 0,10,11, 8,10,10,12,12, 0,10,10,12,12, 0,
  132509. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,14,13, 8,10,
  132510. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  132511. 13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132513. 7,10,10,14,13, 0, 9, 9,13,12, 0, 9, 9,12,12, 0,
  132514. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  132515. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  132516. 12,12, 9,11,11,14,13, 0,11,10,14,13, 0,11,11,13,
  132517. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  132518. 0,10,11,13,14, 0,11,11,13,13, 0,12,12,13,13, 0,
  132519. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  132524. 11,11,14,14, 0,11,11,13,13, 0,11,10,13,13, 0,12,
  132525. 12,13,13, 0, 0, 0,13,13, 9,11,11,14,14, 0,11,11,
  132526. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  132527. 13,
  132528. };
  132529. static float _vq_quantthresh__44c6_s_p2_0[] = {
  132530. -1.5, -0.5, 0.5, 1.5,
  132531. };
  132532. static long _vq_quantmap__44c6_s_p2_0[] = {
  132533. 3, 1, 0, 2, 4,
  132534. };
  132535. static encode_aux_threshmatch _vq_auxt__44c6_s_p2_0 = {
  132536. _vq_quantthresh__44c6_s_p2_0,
  132537. _vq_quantmap__44c6_s_p2_0,
  132538. 5,
  132539. 5
  132540. };
  132541. static static_codebook _44c6_s_p2_0 = {
  132542. 4, 625,
  132543. _vq_lengthlist__44c6_s_p2_0,
  132544. 1, -533725184, 1611661312, 3, 0,
  132545. _vq_quantlist__44c6_s_p2_0,
  132546. NULL,
  132547. &_vq_auxt__44c6_s_p2_0,
  132548. NULL,
  132549. 0
  132550. };
  132551. static long _vq_quantlist__44c6_s_p3_0[] = {
  132552. 4,
  132553. 3,
  132554. 5,
  132555. 2,
  132556. 6,
  132557. 1,
  132558. 7,
  132559. 0,
  132560. 8,
  132561. };
  132562. static long _vq_lengthlist__44c6_s_p3_0[] = {
  132563. 2, 3, 4, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  132564. 9,10, 0, 4, 4, 6, 6, 7, 7,10, 9, 0, 5, 5, 7, 7,
  132565. 8, 8,10,10, 0, 0, 0, 7, 6, 8, 8,10,10, 0, 0, 0,
  132566. 7, 7, 9, 9,11,11, 0, 0, 0, 7, 7, 9, 9,11,11, 0,
  132567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132568. 0,
  132569. };
  132570. static float _vq_quantthresh__44c6_s_p3_0[] = {
  132571. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132572. };
  132573. static long _vq_quantmap__44c6_s_p3_0[] = {
  132574. 7, 5, 3, 1, 0, 2, 4, 6,
  132575. 8,
  132576. };
  132577. static encode_aux_threshmatch _vq_auxt__44c6_s_p3_0 = {
  132578. _vq_quantthresh__44c6_s_p3_0,
  132579. _vq_quantmap__44c6_s_p3_0,
  132580. 9,
  132581. 9
  132582. };
  132583. static static_codebook _44c6_s_p3_0 = {
  132584. 2, 81,
  132585. _vq_lengthlist__44c6_s_p3_0,
  132586. 1, -531628032, 1611661312, 4, 0,
  132587. _vq_quantlist__44c6_s_p3_0,
  132588. NULL,
  132589. &_vq_auxt__44c6_s_p3_0,
  132590. NULL,
  132591. 0
  132592. };
  132593. static long _vq_quantlist__44c6_s_p4_0[] = {
  132594. 8,
  132595. 7,
  132596. 9,
  132597. 6,
  132598. 10,
  132599. 5,
  132600. 11,
  132601. 4,
  132602. 12,
  132603. 3,
  132604. 13,
  132605. 2,
  132606. 14,
  132607. 1,
  132608. 15,
  132609. 0,
  132610. 16,
  132611. };
  132612. static long _vq_lengthlist__44c6_s_p4_0[] = {
  132613. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,10,10,
  132614. 10, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  132615. 11,11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  132616. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  132617. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  132618. 10,11,11,11,11, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  132619. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,
  132620. 10,11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  132621. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  132622. 9,10,10,11,11,12,12,12,12, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132631. 0,
  132632. };
  132633. static float _vq_quantthresh__44c6_s_p4_0[] = {
  132634. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132635. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132636. };
  132637. static long _vq_quantmap__44c6_s_p4_0[] = {
  132638. 15, 13, 11, 9, 7, 5, 3, 1,
  132639. 0, 2, 4, 6, 8, 10, 12, 14,
  132640. 16,
  132641. };
  132642. static encode_aux_threshmatch _vq_auxt__44c6_s_p4_0 = {
  132643. _vq_quantthresh__44c6_s_p4_0,
  132644. _vq_quantmap__44c6_s_p4_0,
  132645. 17,
  132646. 17
  132647. };
  132648. static static_codebook _44c6_s_p4_0 = {
  132649. 2, 289,
  132650. _vq_lengthlist__44c6_s_p4_0,
  132651. 1, -529530880, 1611661312, 5, 0,
  132652. _vq_quantlist__44c6_s_p4_0,
  132653. NULL,
  132654. &_vq_auxt__44c6_s_p4_0,
  132655. NULL,
  132656. 0
  132657. };
  132658. static long _vq_quantlist__44c6_s_p5_0[] = {
  132659. 1,
  132660. 0,
  132661. 2,
  132662. };
  132663. static long _vq_lengthlist__44c6_s_p5_0[] = {
  132664. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6, 9, 9,10,10,
  132665. 10, 9, 4, 6, 6, 9,10, 9,10, 9,10, 6, 9, 9,10,12,
  132666. 11,10,11,11, 7,10, 9,11,12,12,12,12,12, 7,10,10,
  132667. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  132668. 9,10,11,12,12,12,12,12, 7,10, 9,12,12,12,12,12,
  132669. 12,
  132670. };
  132671. static float _vq_quantthresh__44c6_s_p5_0[] = {
  132672. -5.5, 5.5,
  132673. };
  132674. static long _vq_quantmap__44c6_s_p5_0[] = {
  132675. 1, 0, 2,
  132676. };
  132677. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_0 = {
  132678. _vq_quantthresh__44c6_s_p5_0,
  132679. _vq_quantmap__44c6_s_p5_0,
  132680. 3,
  132681. 3
  132682. };
  132683. static static_codebook _44c6_s_p5_0 = {
  132684. 4, 81,
  132685. _vq_lengthlist__44c6_s_p5_0,
  132686. 1, -529137664, 1618345984, 2, 0,
  132687. _vq_quantlist__44c6_s_p5_0,
  132688. NULL,
  132689. &_vq_auxt__44c6_s_p5_0,
  132690. NULL,
  132691. 0
  132692. };
  132693. static long _vq_quantlist__44c6_s_p5_1[] = {
  132694. 5,
  132695. 4,
  132696. 6,
  132697. 3,
  132698. 7,
  132699. 2,
  132700. 8,
  132701. 1,
  132702. 9,
  132703. 0,
  132704. 10,
  132705. };
  132706. static long _vq_lengthlist__44c6_s_p5_1[] = {
  132707. 3, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  132708. 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6, 7, 7, 8, 8, 8,
  132709. 8,11, 6, 6, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  132710. 6, 7, 8, 8, 8, 8, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  132711. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 8,11,11,11,
  132712. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,10,10, 8, 8, 8,
  132713. 8, 8, 8,11,11,11,10,10, 8, 8, 8, 8, 8, 8,11,11,
  132714. 11,10,10, 7, 7, 8, 8, 8, 8,
  132715. };
  132716. static float _vq_quantthresh__44c6_s_p5_1[] = {
  132717. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132718. 3.5, 4.5,
  132719. };
  132720. static long _vq_quantmap__44c6_s_p5_1[] = {
  132721. 9, 7, 5, 3, 1, 0, 2, 4,
  132722. 6, 8, 10,
  132723. };
  132724. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_1 = {
  132725. _vq_quantthresh__44c6_s_p5_1,
  132726. _vq_quantmap__44c6_s_p5_1,
  132727. 11,
  132728. 11
  132729. };
  132730. static static_codebook _44c6_s_p5_1 = {
  132731. 2, 121,
  132732. _vq_lengthlist__44c6_s_p5_1,
  132733. 1, -531365888, 1611661312, 4, 0,
  132734. _vq_quantlist__44c6_s_p5_1,
  132735. NULL,
  132736. &_vq_auxt__44c6_s_p5_1,
  132737. NULL,
  132738. 0
  132739. };
  132740. static long _vq_quantlist__44c6_s_p6_0[] = {
  132741. 6,
  132742. 5,
  132743. 7,
  132744. 4,
  132745. 8,
  132746. 3,
  132747. 9,
  132748. 2,
  132749. 10,
  132750. 1,
  132751. 11,
  132752. 0,
  132753. 12,
  132754. };
  132755. static long _vq_lengthlist__44c6_s_p6_0[] = {
  132756. 1, 4, 4, 6, 6, 8, 8, 8, 8,10, 9,10,10, 6, 5, 5,
  132757. 7, 7, 9, 9, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 9,
  132758. 9,10, 9,11,10,11,11, 0, 6, 6, 7, 7, 9, 9,10,10,
  132759. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  132760. 12, 0,11,11, 8, 8,10,10,11,11,12,12,12,12, 0,11,
  132761. 12, 9, 8,10,10,11,11,12,12,13,13, 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,
  132767. };
  132768. static float _vq_quantthresh__44c6_s_p6_0[] = {
  132769. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  132770. 12.5, 17.5, 22.5, 27.5,
  132771. };
  132772. static long _vq_quantmap__44c6_s_p6_0[] = {
  132773. 11, 9, 7, 5, 3, 1, 0, 2,
  132774. 4, 6, 8, 10, 12,
  132775. };
  132776. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_0 = {
  132777. _vq_quantthresh__44c6_s_p6_0,
  132778. _vq_quantmap__44c6_s_p6_0,
  132779. 13,
  132780. 13
  132781. };
  132782. static static_codebook _44c6_s_p6_0 = {
  132783. 2, 169,
  132784. _vq_lengthlist__44c6_s_p6_0,
  132785. 1, -526516224, 1616117760, 4, 0,
  132786. _vq_quantlist__44c6_s_p6_0,
  132787. NULL,
  132788. &_vq_auxt__44c6_s_p6_0,
  132789. NULL,
  132790. 0
  132791. };
  132792. static long _vq_quantlist__44c6_s_p6_1[] = {
  132793. 2,
  132794. 1,
  132795. 3,
  132796. 0,
  132797. 4,
  132798. };
  132799. static long _vq_lengthlist__44c6_s_p6_1[] = {
  132800. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  132801. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  132802. };
  132803. static float _vq_quantthresh__44c6_s_p6_1[] = {
  132804. -1.5, -0.5, 0.5, 1.5,
  132805. };
  132806. static long _vq_quantmap__44c6_s_p6_1[] = {
  132807. 3, 1, 0, 2, 4,
  132808. };
  132809. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_1 = {
  132810. _vq_quantthresh__44c6_s_p6_1,
  132811. _vq_quantmap__44c6_s_p6_1,
  132812. 5,
  132813. 5
  132814. };
  132815. static static_codebook _44c6_s_p6_1 = {
  132816. 2, 25,
  132817. _vq_lengthlist__44c6_s_p6_1,
  132818. 1, -533725184, 1611661312, 3, 0,
  132819. _vq_quantlist__44c6_s_p6_1,
  132820. NULL,
  132821. &_vq_auxt__44c6_s_p6_1,
  132822. NULL,
  132823. 0
  132824. };
  132825. static long _vq_quantlist__44c6_s_p7_0[] = {
  132826. 6,
  132827. 5,
  132828. 7,
  132829. 4,
  132830. 8,
  132831. 3,
  132832. 9,
  132833. 2,
  132834. 10,
  132835. 1,
  132836. 11,
  132837. 0,
  132838. 12,
  132839. };
  132840. static long _vq_lengthlist__44c6_s_p7_0[] = {
  132841. 1, 4, 4, 6, 6, 8, 8, 8, 8,10,10,11,10, 6, 5, 5,
  132842. 7, 7, 8, 8, 9, 9,10,10,12,11, 6, 5, 5, 7, 7, 8,
  132843. 8, 9, 9,10,10,12,11,21, 7, 7, 7, 7, 9, 9,10,10,
  132844. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  132845. 12,21,12,12, 9, 9,10,10,11,11,11,11,12,12,21,12,
  132846. 12, 9, 9,10,10,11,11,12,12,12,12,21,21,21,11,11,
  132847. 10,10,11,12,12,12,13,13,21,21,21,11,11,10,10,12,
  132848. 12,12,12,13,13,21,21,21,15,15,11,11,12,12,13,13,
  132849. 13,13,21,21,21,15,16,11,11,12,12,13,13,14,14,21,
  132850. 21,21,21,20,13,13,13,13,13,13,14,14,20,20,20,20,
  132851. 20,13,13,13,13,13,13,14,14,
  132852. };
  132853. static float _vq_quantthresh__44c6_s_p7_0[] = {
  132854. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  132855. 27.5, 38.5, 49.5, 60.5,
  132856. };
  132857. static long _vq_quantmap__44c6_s_p7_0[] = {
  132858. 11, 9, 7, 5, 3, 1, 0, 2,
  132859. 4, 6, 8, 10, 12,
  132860. };
  132861. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_0 = {
  132862. _vq_quantthresh__44c6_s_p7_0,
  132863. _vq_quantmap__44c6_s_p7_0,
  132864. 13,
  132865. 13
  132866. };
  132867. static static_codebook _44c6_s_p7_0 = {
  132868. 2, 169,
  132869. _vq_lengthlist__44c6_s_p7_0,
  132870. 1, -523206656, 1618345984, 4, 0,
  132871. _vq_quantlist__44c6_s_p7_0,
  132872. NULL,
  132873. &_vq_auxt__44c6_s_p7_0,
  132874. NULL,
  132875. 0
  132876. };
  132877. static long _vq_quantlist__44c6_s_p7_1[] = {
  132878. 5,
  132879. 4,
  132880. 6,
  132881. 3,
  132882. 7,
  132883. 2,
  132884. 8,
  132885. 1,
  132886. 9,
  132887. 0,
  132888. 10,
  132889. };
  132890. static long _vq_lengthlist__44c6_s_p7_1[] = {
  132891. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 9, 5, 5, 6, 6,
  132892. 7, 7, 7, 7, 8, 7, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7,
  132893. 7, 9, 6, 6, 7, 7, 7, 7, 8, 7, 7, 8, 9, 9, 9, 7,
  132894. 7, 7, 7, 7, 7, 7, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  132895. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  132896. 8, 8, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 8, 8, 8, 7,
  132897. 7, 8, 8, 9, 9, 9, 8, 8, 8, 8, 7, 7, 8, 8, 9, 9,
  132898. 9, 8, 8, 7, 7, 7, 7, 8, 8,
  132899. };
  132900. static float _vq_quantthresh__44c6_s_p7_1[] = {
  132901. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132902. 3.5, 4.5,
  132903. };
  132904. static long _vq_quantmap__44c6_s_p7_1[] = {
  132905. 9, 7, 5, 3, 1, 0, 2, 4,
  132906. 6, 8, 10,
  132907. };
  132908. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_1 = {
  132909. _vq_quantthresh__44c6_s_p7_1,
  132910. _vq_quantmap__44c6_s_p7_1,
  132911. 11,
  132912. 11
  132913. };
  132914. static static_codebook _44c6_s_p7_1 = {
  132915. 2, 121,
  132916. _vq_lengthlist__44c6_s_p7_1,
  132917. 1, -531365888, 1611661312, 4, 0,
  132918. _vq_quantlist__44c6_s_p7_1,
  132919. NULL,
  132920. &_vq_auxt__44c6_s_p7_1,
  132921. NULL,
  132922. 0
  132923. };
  132924. static long _vq_quantlist__44c6_s_p8_0[] = {
  132925. 7,
  132926. 6,
  132927. 8,
  132928. 5,
  132929. 9,
  132930. 4,
  132931. 10,
  132932. 3,
  132933. 11,
  132934. 2,
  132935. 12,
  132936. 1,
  132937. 13,
  132938. 0,
  132939. 14,
  132940. };
  132941. static long _vq_lengthlist__44c6_s_p8_0[] = {
  132942. 1, 4, 4, 7, 7, 8, 8, 7, 7, 8, 7, 9, 8,10, 9, 6,
  132943. 5, 5, 8, 8, 9, 9, 8, 8, 9, 9,11,10,11,10, 6, 5,
  132944. 5, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,11,18, 8, 8,
  132945. 9, 8,10,10, 9, 9,10,10,10,10,11,10,18, 8, 8, 9,
  132946. 9,10,10, 9, 9,10,10,11,11,12,12,18,12,13, 9,10,
  132947. 10,10, 9,10,10,10,11,11,12,11,18,13,13, 9, 9,10,
  132948. 10,10,10,10,10,11,11,12,12,18,18,18,10,10, 9, 9,
  132949. 11,11,11,11,11,12,12,12,18,18,18,10, 9,10, 9,11,
  132950. 10,11,11,11,11,13,12,18,18,18,14,13,10,10,11,11,
  132951. 12,12,12,12,12,12,18,18,18,14,13,10,10,11,10,12,
  132952. 12,12,12,12,12,18,18,18,18,18,12,12,11,11,12,12,
  132953. 13,13,13,14,18,18,18,18,18,12,12,11,11,12,11,13,
  132954. 13,14,13,18,18,18,18,18,16,16,11,12,12,13,13,13,
  132955. 14,13,18,18,18,18,18,16,15,12,11,12,11,13,11,15,
  132956. 14,
  132957. };
  132958. static float _vq_quantthresh__44c6_s_p8_0[] = {
  132959. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  132960. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  132961. };
  132962. static long _vq_quantmap__44c6_s_p8_0[] = {
  132963. 13, 11, 9, 7, 5, 3, 1, 0,
  132964. 2, 4, 6, 8, 10, 12, 14,
  132965. };
  132966. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_0 = {
  132967. _vq_quantthresh__44c6_s_p8_0,
  132968. _vq_quantmap__44c6_s_p8_0,
  132969. 15,
  132970. 15
  132971. };
  132972. static static_codebook _44c6_s_p8_0 = {
  132973. 2, 225,
  132974. _vq_lengthlist__44c6_s_p8_0,
  132975. 1, -520986624, 1620377600, 4, 0,
  132976. _vq_quantlist__44c6_s_p8_0,
  132977. NULL,
  132978. &_vq_auxt__44c6_s_p8_0,
  132979. NULL,
  132980. 0
  132981. };
  132982. static long _vq_quantlist__44c6_s_p8_1[] = {
  132983. 10,
  132984. 9,
  132985. 11,
  132986. 8,
  132987. 12,
  132988. 7,
  132989. 13,
  132990. 6,
  132991. 14,
  132992. 5,
  132993. 15,
  132994. 4,
  132995. 16,
  132996. 3,
  132997. 17,
  132998. 2,
  132999. 18,
  133000. 1,
  133001. 19,
  133002. 0,
  133003. 20,
  133004. };
  133005. static long _vq_lengthlist__44c6_s_p8_1[] = {
  133006. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  133007. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,
  133008. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  133009. 8, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10,
  133010. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133011. 9, 9, 9, 9,10,11,11, 8, 7, 8, 8, 8, 9, 9, 9, 9,
  133012. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8,
  133013. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,
  133014. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133015. 9, 9, 9,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133016. 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9, 9,
  133017. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,
  133018. 11,11, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9,10, 9, 9,
  133019. 10, 9,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,10,10,
  133020. 10,10, 9,10,10, 9,10,11,11,11,11,11, 9, 9, 9, 9,
  133021. 10,10,10, 9,10,10,10,10, 9,10,10, 9,11,11,11,11,
  133022. 11,11,11, 9, 9, 9, 9,10,10,10,10, 9,10,10,10,10,
  133023. 10,11,11,11,11,11,11,11,10, 9,10,10,10,10,10,10,
  133024. 10, 9,10, 9,10,10,11,11,11,11,11,11,11,10, 9,10,
  133025. 9,10,10, 9,10,10,10,10,10,10,10,11,11,11,11,11,
  133026. 11,11,10,10,10,10,10,10,10, 9,10,10,10,10,10, 9,
  133027. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  133028. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  133029. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  133030. 11,11,11,10,10,10,10,10,10,10,10,10, 9,10,10,11,
  133031. 11,11,11,11,11,11,11,11,10,10,10, 9,10,10,10,10,
  133032. 10,10,10,10,10,11,11,11,11,11,11,11,11,10,11, 9,
  133033. 10,10,10,10,10,10,10,10,10,
  133034. };
  133035. static float _vq_quantthresh__44c6_s_p8_1[] = {
  133036. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  133037. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  133038. 6.5, 7.5, 8.5, 9.5,
  133039. };
  133040. static long _vq_quantmap__44c6_s_p8_1[] = {
  133041. 19, 17, 15, 13, 11, 9, 7, 5,
  133042. 3, 1, 0, 2, 4, 6, 8, 10,
  133043. 12, 14, 16, 18, 20,
  133044. };
  133045. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_1 = {
  133046. _vq_quantthresh__44c6_s_p8_1,
  133047. _vq_quantmap__44c6_s_p8_1,
  133048. 21,
  133049. 21
  133050. };
  133051. static static_codebook _44c6_s_p8_1 = {
  133052. 2, 441,
  133053. _vq_lengthlist__44c6_s_p8_1,
  133054. 1, -529268736, 1611661312, 5, 0,
  133055. _vq_quantlist__44c6_s_p8_1,
  133056. NULL,
  133057. &_vq_auxt__44c6_s_p8_1,
  133058. NULL,
  133059. 0
  133060. };
  133061. static long _vq_quantlist__44c6_s_p9_0[] = {
  133062. 6,
  133063. 5,
  133064. 7,
  133065. 4,
  133066. 8,
  133067. 3,
  133068. 9,
  133069. 2,
  133070. 10,
  133071. 1,
  133072. 11,
  133073. 0,
  133074. 12,
  133075. };
  133076. static long _vq_lengthlist__44c6_s_p9_0[] = {
  133077. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 7, 7,
  133078. 11,11,11,11,11,11,11,11,11,11, 5, 8, 9,11,11,11,
  133079. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133080. 11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,10,
  133081. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133082. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133083. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133084. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133085. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133086. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133087. 10,10,10,10,10,10,10,10,10,
  133088. };
  133089. static float _vq_quantthresh__44c6_s_p9_0[] = {
  133090. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  133091. 1592.5, 2229.5, 2866.5, 3503.5,
  133092. };
  133093. static long _vq_quantmap__44c6_s_p9_0[] = {
  133094. 11, 9, 7, 5, 3, 1, 0, 2,
  133095. 4, 6, 8, 10, 12,
  133096. };
  133097. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_0 = {
  133098. _vq_quantthresh__44c6_s_p9_0,
  133099. _vq_quantmap__44c6_s_p9_0,
  133100. 13,
  133101. 13
  133102. };
  133103. static static_codebook _44c6_s_p9_0 = {
  133104. 2, 169,
  133105. _vq_lengthlist__44c6_s_p9_0,
  133106. 1, -511845376, 1630791680, 4, 0,
  133107. _vq_quantlist__44c6_s_p9_0,
  133108. NULL,
  133109. &_vq_auxt__44c6_s_p9_0,
  133110. NULL,
  133111. 0
  133112. };
  133113. static long _vq_quantlist__44c6_s_p9_1[] = {
  133114. 6,
  133115. 5,
  133116. 7,
  133117. 4,
  133118. 8,
  133119. 3,
  133120. 9,
  133121. 2,
  133122. 10,
  133123. 1,
  133124. 11,
  133125. 0,
  133126. 12,
  133127. };
  133128. static long _vq_lengthlist__44c6_s_p9_1[] = {
  133129. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  133130. 8, 8, 8, 8, 8, 7, 9, 8,10,10, 5, 6, 6, 8, 8, 9,
  133131. 9, 8, 8,10,10,10,10,16, 9, 9, 9, 9, 9, 9, 9, 8,
  133132. 10, 9,11,11,16, 8, 9, 9, 9, 9, 9, 9, 9,10,10,11,
  133133. 11,16,13,13, 9, 9,10, 9, 9,10,11,11,11,12,16,13,
  133134. 14, 9, 8,10, 8, 9, 9,10,10,12,11,16,14,16, 9, 9,
  133135. 9, 9,11,11,12,11,12,11,16,16,16, 9, 7, 9, 6,11,
  133136. 11,11,10,11,11,16,16,16,11,12, 9,10,11,11,12,11,
  133137. 13,13,16,16,16,12,11,10, 7,12,10,12,12,12,12,16,
  133138. 16,15,16,16,10,11,10,11,13,13,14,12,16,16,16,15,
  133139. 15,12,10,11,11,13,11,12,13,
  133140. };
  133141. static float _vq_quantthresh__44c6_s_p9_1[] = {
  133142. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  133143. 122.5, 171.5, 220.5, 269.5,
  133144. };
  133145. static long _vq_quantmap__44c6_s_p9_1[] = {
  133146. 11, 9, 7, 5, 3, 1, 0, 2,
  133147. 4, 6, 8, 10, 12,
  133148. };
  133149. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_1 = {
  133150. _vq_quantthresh__44c6_s_p9_1,
  133151. _vq_quantmap__44c6_s_p9_1,
  133152. 13,
  133153. 13
  133154. };
  133155. static static_codebook _44c6_s_p9_1 = {
  133156. 2, 169,
  133157. _vq_lengthlist__44c6_s_p9_1,
  133158. 1, -518889472, 1622704128, 4, 0,
  133159. _vq_quantlist__44c6_s_p9_1,
  133160. NULL,
  133161. &_vq_auxt__44c6_s_p9_1,
  133162. NULL,
  133163. 0
  133164. };
  133165. static long _vq_quantlist__44c6_s_p9_2[] = {
  133166. 24,
  133167. 23,
  133168. 25,
  133169. 22,
  133170. 26,
  133171. 21,
  133172. 27,
  133173. 20,
  133174. 28,
  133175. 19,
  133176. 29,
  133177. 18,
  133178. 30,
  133179. 17,
  133180. 31,
  133181. 16,
  133182. 32,
  133183. 15,
  133184. 33,
  133185. 14,
  133186. 34,
  133187. 13,
  133188. 35,
  133189. 12,
  133190. 36,
  133191. 11,
  133192. 37,
  133193. 10,
  133194. 38,
  133195. 9,
  133196. 39,
  133197. 8,
  133198. 40,
  133199. 7,
  133200. 41,
  133201. 6,
  133202. 42,
  133203. 5,
  133204. 43,
  133205. 4,
  133206. 44,
  133207. 3,
  133208. 45,
  133209. 2,
  133210. 46,
  133211. 1,
  133212. 47,
  133213. 0,
  133214. 48,
  133215. };
  133216. static long _vq_lengthlist__44c6_s_p9_2[] = {
  133217. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  133218. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133219. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133220. 7,
  133221. };
  133222. static float _vq_quantthresh__44c6_s_p9_2[] = {
  133223. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  133224. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  133225. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133226. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133227. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  133228. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  133229. };
  133230. static long _vq_quantmap__44c6_s_p9_2[] = {
  133231. 47, 45, 43, 41, 39, 37, 35, 33,
  133232. 31, 29, 27, 25, 23, 21, 19, 17,
  133233. 15, 13, 11, 9, 7, 5, 3, 1,
  133234. 0, 2, 4, 6, 8, 10, 12, 14,
  133235. 16, 18, 20, 22, 24, 26, 28, 30,
  133236. 32, 34, 36, 38, 40, 42, 44, 46,
  133237. 48,
  133238. };
  133239. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_2 = {
  133240. _vq_quantthresh__44c6_s_p9_2,
  133241. _vq_quantmap__44c6_s_p9_2,
  133242. 49,
  133243. 49
  133244. };
  133245. static static_codebook _44c6_s_p9_2 = {
  133246. 1, 49,
  133247. _vq_lengthlist__44c6_s_p9_2,
  133248. 1, -526909440, 1611661312, 6, 0,
  133249. _vq_quantlist__44c6_s_p9_2,
  133250. NULL,
  133251. &_vq_auxt__44c6_s_p9_2,
  133252. NULL,
  133253. 0
  133254. };
  133255. static long _huff_lengthlist__44c6_s_short[] = {
  133256. 3, 9,11,11,13,14,19,17,17,19, 5, 4, 5, 8,10,10,
  133257. 13,16,18,19, 7, 4, 4, 5, 8, 9,12,14,17,19, 8, 6,
  133258. 5, 5, 7, 7,10,13,16,18,10, 8, 7, 6, 5, 5, 8,11,
  133259. 17,19,11, 9, 7, 7, 5, 4, 5, 8,17,19,13,11, 8, 7,
  133260. 7, 5, 5, 7,16,18,14,13, 8, 6, 6, 5, 5, 7,16,18,
  133261. 18,16,10, 8, 8, 7, 7, 9,16,18,18,18,12,10,10, 9,
  133262. 9,10,17,18,
  133263. };
  133264. static static_codebook _huff_book__44c6_s_short = {
  133265. 2, 100,
  133266. _huff_lengthlist__44c6_s_short,
  133267. 0, 0, 0, 0, 0,
  133268. NULL,
  133269. NULL,
  133270. NULL,
  133271. NULL,
  133272. 0
  133273. };
  133274. static long _huff_lengthlist__44c7_s_long[] = {
  133275. 3, 8,11,13,15,14,14,13,15,14, 6, 4, 5, 7, 9,10,
  133276. 11,11,14,13,10, 4, 3, 5, 7, 8, 9,10,13,13,12, 7,
  133277. 4, 4, 5, 6, 8, 9,12,14,13, 9, 6, 5, 5, 6, 8, 9,
  133278. 12,14,12, 9, 7, 6, 5, 5, 6, 8,11,11,12,11, 9, 8,
  133279. 7, 6, 6, 7,10,11,13,11,10, 9, 8, 7, 6, 6, 9,11,
  133280. 13,13,12,12,12,10, 9, 8, 9,11,12,14,15,15,14,12,
  133281. 11,10,10,12,
  133282. };
  133283. static static_codebook _huff_book__44c7_s_long = {
  133284. 2, 100,
  133285. _huff_lengthlist__44c7_s_long,
  133286. 0, 0, 0, 0, 0,
  133287. NULL,
  133288. NULL,
  133289. NULL,
  133290. NULL,
  133291. 0
  133292. };
  133293. static long _vq_quantlist__44c7_s_p1_0[] = {
  133294. 1,
  133295. 0,
  133296. 2,
  133297. };
  133298. static long _vq_lengthlist__44c7_s_p1_0[] = {
  133299. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  133300. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  133301. 0, 0, 0, 0, 5, 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  133302. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  133303. 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  133304. 8,
  133305. };
  133306. static float _vq_quantthresh__44c7_s_p1_0[] = {
  133307. -0.5, 0.5,
  133308. };
  133309. static long _vq_quantmap__44c7_s_p1_0[] = {
  133310. 1, 0, 2,
  133311. };
  133312. static encode_aux_threshmatch _vq_auxt__44c7_s_p1_0 = {
  133313. _vq_quantthresh__44c7_s_p1_0,
  133314. _vq_quantmap__44c7_s_p1_0,
  133315. 3,
  133316. 3
  133317. };
  133318. static static_codebook _44c7_s_p1_0 = {
  133319. 4, 81,
  133320. _vq_lengthlist__44c7_s_p1_0,
  133321. 1, -535822336, 1611661312, 2, 0,
  133322. _vq_quantlist__44c7_s_p1_0,
  133323. NULL,
  133324. &_vq_auxt__44c7_s_p1_0,
  133325. NULL,
  133326. 0
  133327. };
  133328. static long _vq_quantlist__44c7_s_p2_0[] = {
  133329. 2,
  133330. 1,
  133331. 3,
  133332. 0,
  133333. 4,
  133334. };
  133335. static long _vq_lengthlist__44c7_s_p2_0[] = {
  133336. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  133337. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  133338. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  133339. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  133340. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  133341. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  133342. 0, 0,14,13, 8, 9, 9,10,11, 0,11,11,12,12, 0,10,
  133343. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  133344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133345. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  133346. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  133347. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  133348. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  133349. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  133350. 13, 8, 9,10,12,12, 0,10,10,12,12, 0,10,10,11,12,
  133351. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  133352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133353. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  133354. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,10,
  133355. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,10,
  133356. 0, 0, 0,10,11, 9,10,10,12,12, 0,10,10,12,12, 0,
  133357. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,13,12, 9,10,
  133358. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  133359. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133361. 7,10,10,14,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  133362. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  133363. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  133364. 12,12, 9,11,11,14,13, 0,11,10,13,12, 0,11,11,13,
  133365. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  133366. 0,10,11,12,13, 0,11,11,13,13, 0,12,12,13,13, 0,
  133367. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  133372. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,12,
  133373. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  133374. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  133375. 13,
  133376. };
  133377. static float _vq_quantthresh__44c7_s_p2_0[] = {
  133378. -1.5, -0.5, 0.5, 1.5,
  133379. };
  133380. static long _vq_quantmap__44c7_s_p2_0[] = {
  133381. 3, 1, 0, 2, 4,
  133382. };
  133383. static encode_aux_threshmatch _vq_auxt__44c7_s_p2_0 = {
  133384. _vq_quantthresh__44c7_s_p2_0,
  133385. _vq_quantmap__44c7_s_p2_0,
  133386. 5,
  133387. 5
  133388. };
  133389. static static_codebook _44c7_s_p2_0 = {
  133390. 4, 625,
  133391. _vq_lengthlist__44c7_s_p2_0,
  133392. 1, -533725184, 1611661312, 3, 0,
  133393. _vq_quantlist__44c7_s_p2_0,
  133394. NULL,
  133395. &_vq_auxt__44c7_s_p2_0,
  133396. NULL,
  133397. 0
  133398. };
  133399. static long _vq_quantlist__44c7_s_p3_0[] = {
  133400. 4,
  133401. 3,
  133402. 5,
  133403. 2,
  133404. 6,
  133405. 1,
  133406. 7,
  133407. 0,
  133408. 8,
  133409. };
  133410. static long _vq_lengthlist__44c7_s_p3_0[] = {
  133411. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  133412. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  133413. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  133414. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  133415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133416. 0,
  133417. };
  133418. static float _vq_quantthresh__44c7_s_p3_0[] = {
  133419. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  133420. };
  133421. static long _vq_quantmap__44c7_s_p3_0[] = {
  133422. 7, 5, 3, 1, 0, 2, 4, 6,
  133423. 8,
  133424. };
  133425. static encode_aux_threshmatch _vq_auxt__44c7_s_p3_0 = {
  133426. _vq_quantthresh__44c7_s_p3_0,
  133427. _vq_quantmap__44c7_s_p3_0,
  133428. 9,
  133429. 9
  133430. };
  133431. static static_codebook _44c7_s_p3_0 = {
  133432. 2, 81,
  133433. _vq_lengthlist__44c7_s_p3_0,
  133434. 1, -531628032, 1611661312, 4, 0,
  133435. _vq_quantlist__44c7_s_p3_0,
  133436. NULL,
  133437. &_vq_auxt__44c7_s_p3_0,
  133438. NULL,
  133439. 0
  133440. };
  133441. static long _vq_quantlist__44c7_s_p4_0[] = {
  133442. 8,
  133443. 7,
  133444. 9,
  133445. 6,
  133446. 10,
  133447. 5,
  133448. 11,
  133449. 4,
  133450. 12,
  133451. 3,
  133452. 13,
  133453. 2,
  133454. 14,
  133455. 1,
  133456. 15,
  133457. 0,
  133458. 16,
  133459. };
  133460. static long _vq_lengthlist__44c7_s_p4_0[] = {
  133461. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  133462. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  133463. 12,12, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  133464. 11,12,12, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,
  133465. 11,12,12,12, 0, 0, 0, 6, 6, 8, 7, 9, 9, 9, 9,10,
  133466. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  133467. 11,11,12,12,13,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  133468. 10,11,11,12,12,12,13, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  133469. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  133470. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  133471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133479. 0,
  133480. };
  133481. static float _vq_quantthresh__44c7_s_p4_0[] = {
  133482. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133483. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133484. };
  133485. static long _vq_quantmap__44c7_s_p4_0[] = {
  133486. 15, 13, 11, 9, 7, 5, 3, 1,
  133487. 0, 2, 4, 6, 8, 10, 12, 14,
  133488. 16,
  133489. };
  133490. static encode_aux_threshmatch _vq_auxt__44c7_s_p4_0 = {
  133491. _vq_quantthresh__44c7_s_p4_0,
  133492. _vq_quantmap__44c7_s_p4_0,
  133493. 17,
  133494. 17
  133495. };
  133496. static static_codebook _44c7_s_p4_0 = {
  133497. 2, 289,
  133498. _vq_lengthlist__44c7_s_p4_0,
  133499. 1, -529530880, 1611661312, 5, 0,
  133500. _vq_quantlist__44c7_s_p4_0,
  133501. NULL,
  133502. &_vq_auxt__44c7_s_p4_0,
  133503. NULL,
  133504. 0
  133505. };
  133506. static long _vq_quantlist__44c7_s_p5_0[] = {
  133507. 1,
  133508. 0,
  133509. 2,
  133510. };
  133511. static long _vq_lengthlist__44c7_s_p5_0[] = {
  133512. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 7,10,10,10,10,
  133513. 10, 9, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  133514. 12,10,11,12, 7,10,10,11,12,12,12,12,12, 7,10,10,
  133515. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  133516. 10,10,12,12,12,12,11,12, 7,10,10,11,12,12,12,12,
  133517. 12,
  133518. };
  133519. static float _vq_quantthresh__44c7_s_p5_0[] = {
  133520. -5.5, 5.5,
  133521. };
  133522. static long _vq_quantmap__44c7_s_p5_0[] = {
  133523. 1, 0, 2,
  133524. };
  133525. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_0 = {
  133526. _vq_quantthresh__44c7_s_p5_0,
  133527. _vq_quantmap__44c7_s_p5_0,
  133528. 3,
  133529. 3
  133530. };
  133531. static static_codebook _44c7_s_p5_0 = {
  133532. 4, 81,
  133533. _vq_lengthlist__44c7_s_p5_0,
  133534. 1, -529137664, 1618345984, 2, 0,
  133535. _vq_quantlist__44c7_s_p5_0,
  133536. NULL,
  133537. &_vq_auxt__44c7_s_p5_0,
  133538. NULL,
  133539. 0
  133540. };
  133541. static long _vq_quantlist__44c7_s_p5_1[] = {
  133542. 5,
  133543. 4,
  133544. 6,
  133545. 3,
  133546. 7,
  133547. 2,
  133548. 8,
  133549. 1,
  133550. 9,
  133551. 0,
  133552. 10,
  133553. };
  133554. static long _vq_lengthlist__44c7_s_p5_1[] = {
  133555. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  133556. 7, 7, 8, 8, 9, 9,11, 4, 4, 6, 6, 7, 7, 8, 8, 9,
  133557. 9,12, 5, 5, 6, 6, 7, 7, 9, 9, 9, 9,12,12,12, 6,
  133558. 6, 7, 7, 9, 9, 9, 9,11,11,11, 7, 7, 7, 7, 8, 8,
  133559. 9, 9,11,11,11, 7, 7, 7, 7, 8, 8, 9, 9,11,11,11,
  133560. 7, 7, 8, 8, 8, 8, 9, 9,11,11,11,11,11, 8, 8, 8,
  133561. 8, 8, 9,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  133562. 11,11,11, 7, 7, 8, 8, 8, 8,
  133563. };
  133564. static float _vq_quantthresh__44c7_s_p5_1[] = {
  133565. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133566. 3.5, 4.5,
  133567. };
  133568. static long _vq_quantmap__44c7_s_p5_1[] = {
  133569. 9, 7, 5, 3, 1, 0, 2, 4,
  133570. 6, 8, 10,
  133571. };
  133572. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_1 = {
  133573. _vq_quantthresh__44c7_s_p5_1,
  133574. _vq_quantmap__44c7_s_p5_1,
  133575. 11,
  133576. 11
  133577. };
  133578. static static_codebook _44c7_s_p5_1 = {
  133579. 2, 121,
  133580. _vq_lengthlist__44c7_s_p5_1,
  133581. 1, -531365888, 1611661312, 4, 0,
  133582. _vq_quantlist__44c7_s_p5_1,
  133583. NULL,
  133584. &_vq_auxt__44c7_s_p5_1,
  133585. NULL,
  133586. 0
  133587. };
  133588. static long _vq_quantlist__44c7_s_p6_0[] = {
  133589. 6,
  133590. 5,
  133591. 7,
  133592. 4,
  133593. 8,
  133594. 3,
  133595. 9,
  133596. 2,
  133597. 10,
  133598. 1,
  133599. 11,
  133600. 0,
  133601. 12,
  133602. };
  133603. static long _vq_lengthlist__44c7_s_p6_0[] = {
  133604. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 8,10,10, 6, 5, 5,
  133605. 7, 7, 8, 8, 9, 9, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  133606. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 8, 9, 9,
  133607. 10,10,11,11, 0, 8, 8, 7, 7, 8, 9, 9, 9,10,10,11,
  133608. 11, 0,11,11, 9, 9,10,10,11,10,11,11,12,12, 0,12,
  133609. 12, 9, 9,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0,
  133610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133614. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133615. };
  133616. static float _vq_quantthresh__44c7_s_p6_0[] = {
  133617. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  133618. 12.5, 17.5, 22.5, 27.5,
  133619. };
  133620. static long _vq_quantmap__44c7_s_p6_0[] = {
  133621. 11, 9, 7, 5, 3, 1, 0, 2,
  133622. 4, 6, 8, 10, 12,
  133623. };
  133624. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_0 = {
  133625. _vq_quantthresh__44c7_s_p6_0,
  133626. _vq_quantmap__44c7_s_p6_0,
  133627. 13,
  133628. 13
  133629. };
  133630. static static_codebook _44c7_s_p6_0 = {
  133631. 2, 169,
  133632. _vq_lengthlist__44c7_s_p6_0,
  133633. 1, -526516224, 1616117760, 4, 0,
  133634. _vq_quantlist__44c7_s_p6_0,
  133635. NULL,
  133636. &_vq_auxt__44c7_s_p6_0,
  133637. NULL,
  133638. 0
  133639. };
  133640. static long _vq_quantlist__44c7_s_p6_1[] = {
  133641. 2,
  133642. 1,
  133643. 3,
  133644. 0,
  133645. 4,
  133646. };
  133647. static long _vq_lengthlist__44c7_s_p6_1[] = {
  133648. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  133649. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  133650. };
  133651. static float _vq_quantthresh__44c7_s_p6_1[] = {
  133652. -1.5, -0.5, 0.5, 1.5,
  133653. };
  133654. static long _vq_quantmap__44c7_s_p6_1[] = {
  133655. 3, 1, 0, 2, 4,
  133656. };
  133657. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_1 = {
  133658. _vq_quantthresh__44c7_s_p6_1,
  133659. _vq_quantmap__44c7_s_p6_1,
  133660. 5,
  133661. 5
  133662. };
  133663. static static_codebook _44c7_s_p6_1 = {
  133664. 2, 25,
  133665. _vq_lengthlist__44c7_s_p6_1,
  133666. 1, -533725184, 1611661312, 3, 0,
  133667. _vq_quantlist__44c7_s_p6_1,
  133668. NULL,
  133669. &_vq_auxt__44c7_s_p6_1,
  133670. NULL,
  133671. 0
  133672. };
  133673. static long _vq_quantlist__44c7_s_p7_0[] = {
  133674. 6,
  133675. 5,
  133676. 7,
  133677. 4,
  133678. 8,
  133679. 3,
  133680. 9,
  133681. 2,
  133682. 10,
  133683. 1,
  133684. 11,
  133685. 0,
  133686. 12,
  133687. };
  133688. static long _vq_lengthlist__44c7_s_p7_0[] = {
  133689. 1, 4, 4, 6, 6, 7, 8, 9, 9,10,10,12,11, 6, 5, 5,
  133690. 7, 7, 8, 8, 9,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  133691. 8,10,10,11,11,12,12,20, 7, 7, 7, 7, 8, 9,10,10,
  133692. 11,11,12,13,20, 7, 7, 7, 7, 9, 9,10,10,11,12,13,
  133693. 13,20,11,11, 8, 8, 9, 9,11,11,12,12,13,13,20,11,
  133694. 11, 8, 8, 9, 9,11,11,12,12,13,13,20,20,20,10,10,
  133695. 10,10,12,12,13,13,13,13,20,20,20,10,10,10,10,12,
  133696. 12,13,13,13,14,20,20,20,14,14,11,11,12,12,13,13,
  133697. 14,14,20,20,20,14,14,11,11,12,12,13,13,14,14,20,
  133698. 20,20,20,19,13,13,13,13,14,14,15,14,19,19,19,19,
  133699. 19,13,13,13,13,14,14,15,15,
  133700. };
  133701. static float _vq_quantthresh__44c7_s_p7_0[] = {
  133702. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  133703. 27.5, 38.5, 49.5, 60.5,
  133704. };
  133705. static long _vq_quantmap__44c7_s_p7_0[] = {
  133706. 11, 9, 7, 5, 3, 1, 0, 2,
  133707. 4, 6, 8, 10, 12,
  133708. };
  133709. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_0 = {
  133710. _vq_quantthresh__44c7_s_p7_0,
  133711. _vq_quantmap__44c7_s_p7_0,
  133712. 13,
  133713. 13
  133714. };
  133715. static static_codebook _44c7_s_p7_0 = {
  133716. 2, 169,
  133717. _vq_lengthlist__44c7_s_p7_0,
  133718. 1, -523206656, 1618345984, 4, 0,
  133719. _vq_quantlist__44c7_s_p7_0,
  133720. NULL,
  133721. &_vq_auxt__44c7_s_p7_0,
  133722. NULL,
  133723. 0
  133724. };
  133725. static long _vq_quantlist__44c7_s_p7_1[] = {
  133726. 5,
  133727. 4,
  133728. 6,
  133729. 3,
  133730. 7,
  133731. 2,
  133732. 8,
  133733. 1,
  133734. 9,
  133735. 0,
  133736. 10,
  133737. };
  133738. static long _vq_lengthlist__44c7_s_p7_1[] = {
  133739. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 7, 7,
  133740. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  133741. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  133742. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  133743. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  133744. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  133745. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  133746. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  133747. };
  133748. static float _vq_quantthresh__44c7_s_p7_1[] = {
  133749. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133750. 3.5, 4.5,
  133751. };
  133752. static long _vq_quantmap__44c7_s_p7_1[] = {
  133753. 9, 7, 5, 3, 1, 0, 2, 4,
  133754. 6, 8, 10,
  133755. };
  133756. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_1 = {
  133757. _vq_quantthresh__44c7_s_p7_1,
  133758. _vq_quantmap__44c7_s_p7_1,
  133759. 11,
  133760. 11
  133761. };
  133762. static static_codebook _44c7_s_p7_1 = {
  133763. 2, 121,
  133764. _vq_lengthlist__44c7_s_p7_1,
  133765. 1, -531365888, 1611661312, 4, 0,
  133766. _vq_quantlist__44c7_s_p7_1,
  133767. NULL,
  133768. &_vq_auxt__44c7_s_p7_1,
  133769. NULL,
  133770. 0
  133771. };
  133772. static long _vq_quantlist__44c7_s_p8_0[] = {
  133773. 7,
  133774. 6,
  133775. 8,
  133776. 5,
  133777. 9,
  133778. 4,
  133779. 10,
  133780. 3,
  133781. 11,
  133782. 2,
  133783. 12,
  133784. 1,
  133785. 13,
  133786. 0,
  133787. 14,
  133788. };
  133789. static long _vq_lengthlist__44c7_s_p8_0[] = {
  133790. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8, 9, 9,10,10, 6,
  133791. 5, 5, 7, 7, 9, 9, 8, 8,10, 9,11,10,12,11, 6, 5,
  133792. 5, 8, 7, 9, 9, 8, 8,10,10,11,11,12,11,19, 8, 8,
  133793. 8, 8,10,10, 9, 9,10,10,11,11,12,11,19, 8, 8, 8,
  133794. 8,10,10, 9, 9,10,10,11,11,12,12,19,12,12, 9, 9,
  133795. 10,10, 9,10,10,10,11,11,12,12,19,12,12, 9, 9,10,
  133796. 10,10,10,10,10,12,12,12,12,19,19,19, 9, 9, 9, 9,
  133797. 11,10,11,11,12,11,13,13,19,19,19, 9, 9, 9, 9,11,
  133798. 10,11,11,11,12,13,13,19,19,19,13,13,10,10,11,11,
  133799. 12,12,12,12,13,12,19,19,19,14,13,10,10,11,11,12,
  133800. 12,12,13,13,13,19,19,19,19,19,12,12,12,11,12,13,
  133801. 14,13,13,13,19,19,19,19,19,12,12,12,11,12,12,13,
  133802. 14,13,14,19,19,19,19,19,16,16,12,13,12,13,13,14,
  133803. 15,14,19,18,18,18,18,16,15,12,11,12,11,14,12,14,
  133804. 14,
  133805. };
  133806. static float _vq_quantthresh__44c7_s_p8_0[] = {
  133807. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  133808. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  133809. };
  133810. static long _vq_quantmap__44c7_s_p8_0[] = {
  133811. 13, 11, 9, 7, 5, 3, 1, 0,
  133812. 2, 4, 6, 8, 10, 12, 14,
  133813. };
  133814. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_0 = {
  133815. _vq_quantthresh__44c7_s_p8_0,
  133816. _vq_quantmap__44c7_s_p8_0,
  133817. 15,
  133818. 15
  133819. };
  133820. static static_codebook _44c7_s_p8_0 = {
  133821. 2, 225,
  133822. _vq_lengthlist__44c7_s_p8_0,
  133823. 1, -520986624, 1620377600, 4, 0,
  133824. _vq_quantlist__44c7_s_p8_0,
  133825. NULL,
  133826. &_vq_auxt__44c7_s_p8_0,
  133827. NULL,
  133828. 0
  133829. };
  133830. static long _vq_quantlist__44c7_s_p8_1[] = {
  133831. 10,
  133832. 9,
  133833. 11,
  133834. 8,
  133835. 12,
  133836. 7,
  133837. 13,
  133838. 6,
  133839. 14,
  133840. 5,
  133841. 15,
  133842. 4,
  133843. 16,
  133844. 3,
  133845. 17,
  133846. 2,
  133847. 18,
  133848. 1,
  133849. 19,
  133850. 0,
  133851. 20,
  133852. };
  133853. static long _vq_lengthlist__44c7_s_p8_1[] = {
  133854. 3, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  133855. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  133856. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  133857. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  133858. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133859. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  133860. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  133861. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  133862. 10, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133863. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133864. 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,10,10, 9, 9, 9,
  133865. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9, 9,10,11,10,
  133866. 11,10, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9, 9,
  133867. 9, 9,11,10,11,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,
  133868. 10, 9, 9,10, 9, 9,10,11,10,10,11,10, 9, 9, 9, 9,
  133869. 9,10,10, 9,10,10,10,10, 9,10,10,10,10,10,10,11,
  133870. 11,11,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  133871. 10,10,10,11,11,10,10,10,10,10,10,10,10,10,10,10,
  133872. 10, 9,10,10, 9,10,11,11,10,11,10,11,10, 9,10,10,
  133873. 9,10,10,10,10,10,10,10,10,10,10,11,11,11,11,10,
  133874. 11,11,10,10,10,10,10,10, 9,10, 9,10,10, 9,10, 9,
  133875. 10,10,10,11,10,11,10,11,11,10,10,10,10,10,10, 9,
  133876. 10,10,10,10,10,10,10,11,10,10,10,10,10,10,10,10,
  133877. 10,10,10,10,10,10,10,10,10,10,10,10,10,11,10,11,
  133878. 11,10,10,10,10, 9, 9,10,10, 9, 9,10, 9,10,10,10,
  133879. 10,11,11,10,10,10,10,10,10,10, 9, 9,10,10,10, 9,
  133880. 9,10,10,10,10,10,11,10,11,10,10,10,10,10,10, 9,
  133881. 10,10,10,10,10,10,10,10,10,
  133882. };
  133883. static float _vq_quantthresh__44c7_s_p8_1[] = {
  133884. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  133885. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  133886. 6.5, 7.5, 8.5, 9.5,
  133887. };
  133888. static long _vq_quantmap__44c7_s_p8_1[] = {
  133889. 19, 17, 15, 13, 11, 9, 7, 5,
  133890. 3, 1, 0, 2, 4, 6, 8, 10,
  133891. 12, 14, 16, 18, 20,
  133892. };
  133893. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_1 = {
  133894. _vq_quantthresh__44c7_s_p8_1,
  133895. _vq_quantmap__44c7_s_p8_1,
  133896. 21,
  133897. 21
  133898. };
  133899. static static_codebook _44c7_s_p8_1 = {
  133900. 2, 441,
  133901. _vq_lengthlist__44c7_s_p8_1,
  133902. 1, -529268736, 1611661312, 5, 0,
  133903. _vq_quantlist__44c7_s_p8_1,
  133904. NULL,
  133905. &_vq_auxt__44c7_s_p8_1,
  133906. NULL,
  133907. 0
  133908. };
  133909. static long _vq_quantlist__44c7_s_p9_0[] = {
  133910. 6,
  133911. 5,
  133912. 7,
  133913. 4,
  133914. 8,
  133915. 3,
  133916. 9,
  133917. 2,
  133918. 10,
  133919. 1,
  133920. 11,
  133921. 0,
  133922. 12,
  133923. };
  133924. static long _vq_lengthlist__44c7_s_p9_0[] = {
  133925. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 6, 6,
  133926. 11,11,11,11,11,11,11,11,11,11, 4, 7, 7,11,11,11,
  133927. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133928. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133929. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133930. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133931. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133932. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133933. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133934. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133935. 11,11,11,11,11,11,11,11,11,
  133936. };
  133937. static float _vq_quantthresh__44c7_s_p9_0[] = {
  133938. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  133939. 1592.5, 2229.5, 2866.5, 3503.5,
  133940. };
  133941. static long _vq_quantmap__44c7_s_p9_0[] = {
  133942. 11, 9, 7, 5, 3, 1, 0, 2,
  133943. 4, 6, 8, 10, 12,
  133944. };
  133945. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_0 = {
  133946. _vq_quantthresh__44c7_s_p9_0,
  133947. _vq_quantmap__44c7_s_p9_0,
  133948. 13,
  133949. 13
  133950. };
  133951. static static_codebook _44c7_s_p9_0 = {
  133952. 2, 169,
  133953. _vq_lengthlist__44c7_s_p9_0,
  133954. 1, -511845376, 1630791680, 4, 0,
  133955. _vq_quantlist__44c7_s_p9_0,
  133956. NULL,
  133957. &_vq_auxt__44c7_s_p9_0,
  133958. NULL,
  133959. 0
  133960. };
  133961. static long _vq_quantlist__44c7_s_p9_1[] = {
  133962. 6,
  133963. 5,
  133964. 7,
  133965. 4,
  133966. 8,
  133967. 3,
  133968. 9,
  133969. 2,
  133970. 10,
  133971. 1,
  133972. 11,
  133973. 0,
  133974. 12,
  133975. };
  133976. static long _vq_lengthlist__44c7_s_p9_1[] = {
  133977. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  133978. 8, 8, 9, 8, 8, 7, 9, 8,11,10, 5, 6, 6, 8, 8, 9,
  133979. 8, 8, 8,10, 9,11,11,16, 8, 8, 9, 8, 9, 9, 9, 8,
  133980. 10, 9,11,10,16, 8, 8, 9, 9,10,10, 9, 9,10,10,11,
  133981. 11,16,13,13, 9, 9,10,10, 9,10,11,11,12,11,16,13,
  133982. 13, 9, 8,10, 9,10,10,10,10,11,11,16,14,16, 8, 9,
  133983. 9, 9,11,10,11,11,12,11,16,16,16, 9, 7,10, 7,11,
  133984. 10,11,11,12,11,16,16,16,12,12, 9,10,11,11,12,11,
  133985. 12,12,16,16,16,12,10,10, 7,11, 8,12,11,12,12,16,
  133986. 16,15,16,16,11,12,10,10,12,11,12,12,16,16,16,15,
  133987. 15,11,11,10,10,12,12,12,12,
  133988. };
  133989. static float _vq_quantthresh__44c7_s_p9_1[] = {
  133990. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  133991. 122.5, 171.5, 220.5, 269.5,
  133992. };
  133993. static long _vq_quantmap__44c7_s_p9_1[] = {
  133994. 11, 9, 7, 5, 3, 1, 0, 2,
  133995. 4, 6, 8, 10, 12,
  133996. };
  133997. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_1 = {
  133998. _vq_quantthresh__44c7_s_p9_1,
  133999. _vq_quantmap__44c7_s_p9_1,
  134000. 13,
  134001. 13
  134002. };
  134003. static static_codebook _44c7_s_p9_1 = {
  134004. 2, 169,
  134005. _vq_lengthlist__44c7_s_p9_1,
  134006. 1, -518889472, 1622704128, 4, 0,
  134007. _vq_quantlist__44c7_s_p9_1,
  134008. NULL,
  134009. &_vq_auxt__44c7_s_p9_1,
  134010. NULL,
  134011. 0
  134012. };
  134013. static long _vq_quantlist__44c7_s_p9_2[] = {
  134014. 24,
  134015. 23,
  134016. 25,
  134017. 22,
  134018. 26,
  134019. 21,
  134020. 27,
  134021. 20,
  134022. 28,
  134023. 19,
  134024. 29,
  134025. 18,
  134026. 30,
  134027. 17,
  134028. 31,
  134029. 16,
  134030. 32,
  134031. 15,
  134032. 33,
  134033. 14,
  134034. 34,
  134035. 13,
  134036. 35,
  134037. 12,
  134038. 36,
  134039. 11,
  134040. 37,
  134041. 10,
  134042. 38,
  134043. 9,
  134044. 39,
  134045. 8,
  134046. 40,
  134047. 7,
  134048. 41,
  134049. 6,
  134050. 42,
  134051. 5,
  134052. 43,
  134053. 4,
  134054. 44,
  134055. 3,
  134056. 45,
  134057. 2,
  134058. 46,
  134059. 1,
  134060. 47,
  134061. 0,
  134062. 48,
  134063. };
  134064. static long _vq_lengthlist__44c7_s_p9_2[] = {
  134065. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  134066. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  134067. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  134068. 7,
  134069. };
  134070. static float _vq_quantthresh__44c7_s_p9_2[] = {
  134071. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  134072. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  134073. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134074. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134075. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  134076. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  134077. };
  134078. static long _vq_quantmap__44c7_s_p9_2[] = {
  134079. 47, 45, 43, 41, 39, 37, 35, 33,
  134080. 31, 29, 27, 25, 23, 21, 19, 17,
  134081. 15, 13, 11, 9, 7, 5, 3, 1,
  134082. 0, 2, 4, 6, 8, 10, 12, 14,
  134083. 16, 18, 20, 22, 24, 26, 28, 30,
  134084. 32, 34, 36, 38, 40, 42, 44, 46,
  134085. 48,
  134086. };
  134087. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_2 = {
  134088. _vq_quantthresh__44c7_s_p9_2,
  134089. _vq_quantmap__44c7_s_p9_2,
  134090. 49,
  134091. 49
  134092. };
  134093. static static_codebook _44c7_s_p9_2 = {
  134094. 1, 49,
  134095. _vq_lengthlist__44c7_s_p9_2,
  134096. 1, -526909440, 1611661312, 6, 0,
  134097. _vq_quantlist__44c7_s_p9_2,
  134098. NULL,
  134099. &_vq_auxt__44c7_s_p9_2,
  134100. NULL,
  134101. 0
  134102. };
  134103. static long _huff_lengthlist__44c7_s_short[] = {
  134104. 4,11,12,14,15,15,17,17,18,18, 5, 6, 6, 8, 9,10,
  134105. 13,17,18,19, 7, 5, 4, 6, 8, 9,11,15,19,19, 8, 6,
  134106. 5, 5, 6, 7,11,14,16,17, 9, 7, 7, 6, 7, 7,10,13,
  134107. 15,19,10, 8, 7, 6, 7, 6, 7, 9,14,16,12,10, 9, 7,
  134108. 7, 6, 4, 5,10,15,14,13,11, 7, 6, 6, 4, 2, 7,13,
  134109. 16,16,15, 9, 8, 8, 8, 6, 9,13,19,19,17,12,11,10,
  134110. 10, 9,11,14,
  134111. };
  134112. static static_codebook _huff_book__44c7_s_short = {
  134113. 2, 100,
  134114. _huff_lengthlist__44c7_s_short,
  134115. 0, 0, 0, 0, 0,
  134116. NULL,
  134117. NULL,
  134118. NULL,
  134119. NULL,
  134120. 0
  134121. };
  134122. static long _huff_lengthlist__44c8_s_long[] = {
  134123. 3, 8,12,13,14,14,14,13,14,14, 6, 4, 5, 8,10,10,
  134124. 11,11,14,13, 9, 5, 4, 5, 7, 8, 9,10,13,13,12, 7,
  134125. 5, 4, 5, 6, 8, 9,12,13,13, 9, 6, 5, 5, 5, 7, 9,
  134126. 11,14,12,10, 7, 6, 5, 4, 6, 7,10,11,12,11, 9, 8,
  134127. 7, 5, 5, 6,10,10,13,12,10, 9, 8, 6, 6, 5, 8,10,
  134128. 14,13,12,12,11,10, 9, 7, 8,10,12,13,14,14,13,12,
  134129. 11, 9, 9,10,
  134130. };
  134131. static static_codebook _huff_book__44c8_s_long = {
  134132. 2, 100,
  134133. _huff_lengthlist__44c8_s_long,
  134134. 0, 0, 0, 0, 0,
  134135. NULL,
  134136. NULL,
  134137. NULL,
  134138. NULL,
  134139. 0
  134140. };
  134141. static long _vq_quantlist__44c8_s_p1_0[] = {
  134142. 1,
  134143. 0,
  134144. 2,
  134145. };
  134146. static long _vq_lengthlist__44c8_s_p1_0[] = {
  134147. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 7, 7, 0, 9, 8, 0,
  134148. 9, 8, 6, 7, 7, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  134149. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  134150. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  134151. 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  134152. 8,
  134153. };
  134154. static float _vq_quantthresh__44c8_s_p1_0[] = {
  134155. -0.5, 0.5,
  134156. };
  134157. static long _vq_quantmap__44c8_s_p1_0[] = {
  134158. 1, 0, 2,
  134159. };
  134160. static encode_aux_threshmatch _vq_auxt__44c8_s_p1_0 = {
  134161. _vq_quantthresh__44c8_s_p1_0,
  134162. _vq_quantmap__44c8_s_p1_0,
  134163. 3,
  134164. 3
  134165. };
  134166. static static_codebook _44c8_s_p1_0 = {
  134167. 4, 81,
  134168. _vq_lengthlist__44c8_s_p1_0,
  134169. 1, -535822336, 1611661312, 2, 0,
  134170. _vq_quantlist__44c8_s_p1_0,
  134171. NULL,
  134172. &_vq_auxt__44c8_s_p1_0,
  134173. NULL,
  134174. 0
  134175. };
  134176. static long _vq_quantlist__44c8_s_p2_0[] = {
  134177. 2,
  134178. 1,
  134179. 3,
  134180. 0,
  134181. 4,
  134182. };
  134183. static long _vq_lengthlist__44c8_s_p2_0[] = {
  134184. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  134185. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  134186. 7,10, 9, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  134187. 11,11, 5, 7, 7, 9, 9, 0, 7, 8, 9,10, 0, 7, 8, 9,
  134188. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  134189. 0,11,10,12,11, 0,11,10,12,12, 0,13,13,14,14, 0,
  134190. 0, 0,14,13, 8, 9, 9,10,11, 0,10,11,12,12, 0,10,
  134191. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  134192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134193. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  134194. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,11,10, 5,
  134195. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  134196. 9,10,10, 0, 0, 0,10,10, 8,10, 9,12,12, 0,10,10,
  134197. 12,11, 0,10,10,12,12, 0,12,12,13,12, 0, 0, 0,13,
  134198. 12, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,11,12,
  134199. 0,12,12,13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0,
  134200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134201. 0, 0, 0, 6, 8, 7,11,10, 0, 7, 7,10,10, 0, 7, 7,
  134202. 10,10, 0, 9, 9,10,11, 0, 0, 0,10,10, 6, 7, 8,10,
  134203. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,10,10,
  134204. 0, 0, 0,10,10, 9,10, 9,12,12, 0,10,10,12,12, 0,
  134205. 10,10,12,11, 0,12,12,13,13, 0, 0, 0,13,12, 8, 9,
  134206. 10,12,12, 0,10,10,12,12, 0,10,10,11,12, 0,12,12,
  134207. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134209. 7,10,10,13,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  134210. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,13, 0, 9,
  134211. 9,12,12, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  134212. 12,12, 9,11,11,14,13, 0,10,10,13,12, 0,11,10,13,
  134213. 12, 0,12,12,13,12, 0, 0, 0,13,13, 9,11,11,13,14,
  134214. 0,10,11,12,13, 0,10,11,13,13, 0,12,12,12,13, 0,
  134215. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  134220. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,11,
  134221. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  134222. 13,13, 0,10,11,13,13, 0,12,12,13,13, 0, 0, 0,12,
  134223. 13,
  134224. };
  134225. static float _vq_quantthresh__44c8_s_p2_0[] = {
  134226. -1.5, -0.5, 0.5, 1.5,
  134227. };
  134228. static long _vq_quantmap__44c8_s_p2_0[] = {
  134229. 3, 1, 0, 2, 4,
  134230. };
  134231. static encode_aux_threshmatch _vq_auxt__44c8_s_p2_0 = {
  134232. _vq_quantthresh__44c8_s_p2_0,
  134233. _vq_quantmap__44c8_s_p2_0,
  134234. 5,
  134235. 5
  134236. };
  134237. static static_codebook _44c8_s_p2_0 = {
  134238. 4, 625,
  134239. _vq_lengthlist__44c8_s_p2_0,
  134240. 1, -533725184, 1611661312, 3, 0,
  134241. _vq_quantlist__44c8_s_p2_0,
  134242. NULL,
  134243. &_vq_auxt__44c8_s_p2_0,
  134244. NULL,
  134245. 0
  134246. };
  134247. static long _vq_quantlist__44c8_s_p3_0[] = {
  134248. 4,
  134249. 3,
  134250. 5,
  134251. 2,
  134252. 6,
  134253. 1,
  134254. 7,
  134255. 0,
  134256. 8,
  134257. };
  134258. static long _vq_lengthlist__44c8_s_p3_0[] = {
  134259. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  134260. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  134261. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  134262. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  134263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134264. 0,
  134265. };
  134266. static float _vq_quantthresh__44c8_s_p3_0[] = {
  134267. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  134268. };
  134269. static long _vq_quantmap__44c8_s_p3_0[] = {
  134270. 7, 5, 3, 1, 0, 2, 4, 6,
  134271. 8,
  134272. };
  134273. static encode_aux_threshmatch _vq_auxt__44c8_s_p3_0 = {
  134274. _vq_quantthresh__44c8_s_p3_0,
  134275. _vq_quantmap__44c8_s_p3_0,
  134276. 9,
  134277. 9
  134278. };
  134279. static static_codebook _44c8_s_p3_0 = {
  134280. 2, 81,
  134281. _vq_lengthlist__44c8_s_p3_0,
  134282. 1, -531628032, 1611661312, 4, 0,
  134283. _vq_quantlist__44c8_s_p3_0,
  134284. NULL,
  134285. &_vq_auxt__44c8_s_p3_0,
  134286. NULL,
  134287. 0
  134288. };
  134289. static long _vq_quantlist__44c8_s_p4_0[] = {
  134290. 8,
  134291. 7,
  134292. 9,
  134293. 6,
  134294. 10,
  134295. 5,
  134296. 11,
  134297. 4,
  134298. 12,
  134299. 3,
  134300. 13,
  134301. 2,
  134302. 14,
  134303. 1,
  134304. 15,
  134305. 0,
  134306. 16,
  134307. };
  134308. static long _vq_lengthlist__44c8_s_p4_0[] = {
  134309. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  134310. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 8,10,10,11,11,
  134311. 11,11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  134312. 11,11,11, 0, 6, 5, 6, 6, 7, 7, 9, 9, 9, 9,10,10,
  134313. 11,11,12,12, 0, 0, 0, 6, 6, 7, 7, 9, 9, 9, 9,10,
  134314. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  134315. 11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  134316. 10,11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  134317. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  134318. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  134319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134327. 0,
  134328. };
  134329. static float _vq_quantthresh__44c8_s_p4_0[] = {
  134330. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134331. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134332. };
  134333. static long _vq_quantmap__44c8_s_p4_0[] = {
  134334. 15, 13, 11, 9, 7, 5, 3, 1,
  134335. 0, 2, 4, 6, 8, 10, 12, 14,
  134336. 16,
  134337. };
  134338. static encode_aux_threshmatch _vq_auxt__44c8_s_p4_0 = {
  134339. _vq_quantthresh__44c8_s_p4_0,
  134340. _vq_quantmap__44c8_s_p4_0,
  134341. 17,
  134342. 17
  134343. };
  134344. static static_codebook _44c8_s_p4_0 = {
  134345. 2, 289,
  134346. _vq_lengthlist__44c8_s_p4_0,
  134347. 1, -529530880, 1611661312, 5, 0,
  134348. _vq_quantlist__44c8_s_p4_0,
  134349. NULL,
  134350. &_vq_auxt__44c8_s_p4_0,
  134351. NULL,
  134352. 0
  134353. };
  134354. static long _vq_quantlist__44c8_s_p5_0[] = {
  134355. 1,
  134356. 0,
  134357. 2,
  134358. };
  134359. static long _vq_lengthlist__44c8_s_p5_0[] = {
  134360. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6,10,10,10,10,
  134361. 10,10, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  134362. 11,10,11,11, 7,10,10,11,12,12,12,12,12, 7,10,10,
  134363. 11,12,12,12,12,12, 6,10,10,10,12,12,10,12,12, 7,
  134364. 10,10,11,12,12,12,12,12, 7,10,10,11,12,12,12,12,
  134365. 12,
  134366. };
  134367. static float _vq_quantthresh__44c8_s_p5_0[] = {
  134368. -5.5, 5.5,
  134369. };
  134370. static long _vq_quantmap__44c8_s_p5_0[] = {
  134371. 1, 0, 2,
  134372. };
  134373. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_0 = {
  134374. _vq_quantthresh__44c8_s_p5_0,
  134375. _vq_quantmap__44c8_s_p5_0,
  134376. 3,
  134377. 3
  134378. };
  134379. static static_codebook _44c8_s_p5_0 = {
  134380. 4, 81,
  134381. _vq_lengthlist__44c8_s_p5_0,
  134382. 1, -529137664, 1618345984, 2, 0,
  134383. _vq_quantlist__44c8_s_p5_0,
  134384. NULL,
  134385. &_vq_auxt__44c8_s_p5_0,
  134386. NULL,
  134387. 0
  134388. };
  134389. static long _vq_quantlist__44c8_s_p5_1[] = {
  134390. 5,
  134391. 4,
  134392. 6,
  134393. 3,
  134394. 7,
  134395. 2,
  134396. 8,
  134397. 1,
  134398. 9,
  134399. 0,
  134400. 10,
  134401. };
  134402. static long _vq_lengthlist__44c8_s_p5_1[] = {
  134403. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 5, 6, 6,
  134404. 7, 7, 8, 8, 8, 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  134405. 9,12, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,12,12,12, 6,
  134406. 6, 7, 7, 8, 8, 9, 9,11,11,11, 6, 6, 7, 7, 8, 8,
  134407. 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11,
  134408. 7, 7, 7, 8, 8, 8, 8, 8,11,11,11,11,11, 7, 7, 8,
  134409. 8, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 8, 8,11,11,
  134410. 11,11,11, 7, 7, 7, 7, 8, 8,
  134411. };
  134412. static float _vq_quantthresh__44c8_s_p5_1[] = {
  134413. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134414. 3.5, 4.5,
  134415. };
  134416. static long _vq_quantmap__44c8_s_p5_1[] = {
  134417. 9, 7, 5, 3, 1, 0, 2, 4,
  134418. 6, 8, 10,
  134419. };
  134420. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_1 = {
  134421. _vq_quantthresh__44c8_s_p5_1,
  134422. _vq_quantmap__44c8_s_p5_1,
  134423. 11,
  134424. 11
  134425. };
  134426. static static_codebook _44c8_s_p5_1 = {
  134427. 2, 121,
  134428. _vq_lengthlist__44c8_s_p5_1,
  134429. 1, -531365888, 1611661312, 4, 0,
  134430. _vq_quantlist__44c8_s_p5_1,
  134431. NULL,
  134432. &_vq_auxt__44c8_s_p5_1,
  134433. NULL,
  134434. 0
  134435. };
  134436. static long _vq_quantlist__44c8_s_p6_0[] = {
  134437. 6,
  134438. 5,
  134439. 7,
  134440. 4,
  134441. 8,
  134442. 3,
  134443. 9,
  134444. 2,
  134445. 10,
  134446. 1,
  134447. 11,
  134448. 0,
  134449. 12,
  134450. };
  134451. static long _vq_lengthlist__44c8_s_p6_0[] = {
  134452. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  134453. 7, 7, 8, 8, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 8,
  134454. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,
  134455. 10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,10,10,11,
  134456. 11, 0,11,11, 9, 9,10,10,11,11,11,11,12,12, 0,12,
  134457. 12, 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  134458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134462. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134463. };
  134464. static float _vq_quantthresh__44c8_s_p6_0[] = {
  134465. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  134466. 12.5, 17.5, 22.5, 27.5,
  134467. };
  134468. static long _vq_quantmap__44c8_s_p6_0[] = {
  134469. 11, 9, 7, 5, 3, 1, 0, 2,
  134470. 4, 6, 8, 10, 12,
  134471. };
  134472. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_0 = {
  134473. _vq_quantthresh__44c8_s_p6_0,
  134474. _vq_quantmap__44c8_s_p6_0,
  134475. 13,
  134476. 13
  134477. };
  134478. static static_codebook _44c8_s_p6_0 = {
  134479. 2, 169,
  134480. _vq_lengthlist__44c8_s_p6_0,
  134481. 1, -526516224, 1616117760, 4, 0,
  134482. _vq_quantlist__44c8_s_p6_0,
  134483. NULL,
  134484. &_vq_auxt__44c8_s_p6_0,
  134485. NULL,
  134486. 0
  134487. };
  134488. static long _vq_quantlist__44c8_s_p6_1[] = {
  134489. 2,
  134490. 1,
  134491. 3,
  134492. 0,
  134493. 4,
  134494. };
  134495. static long _vq_lengthlist__44c8_s_p6_1[] = {
  134496. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  134497. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  134498. };
  134499. static float _vq_quantthresh__44c8_s_p6_1[] = {
  134500. -1.5, -0.5, 0.5, 1.5,
  134501. };
  134502. static long _vq_quantmap__44c8_s_p6_1[] = {
  134503. 3, 1, 0, 2, 4,
  134504. };
  134505. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_1 = {
  134506. _vq_quantthresh__44c8_s_p6_1,
  134507. _vq_quantmap__44c8_s_p6_1,
  134508. 5,
  134509. 5
  134510. };
  134511. static static_codebook _44c8_s_p6_1 = {
  134512. 2, 25,
  134513. _vq_lengthlist__44c8_s_p6_1,
  134514. 1, -533725184, 1611661312, 3, 0,
  134515. _vq_quantlist__44c8_s_p6_1,
  134516. NULL,
  134517. &_vq_auxt__44c8_s_p6_1,
  134518. NULL,
  134519. 0
  134520. };
  134521. static long _vq_quantlist__44c8_s_p7_0[] = {
  134522. 6,
  134523. 5,
  134524. 7,
  134525. 4,
  134526. 8,
  134527. 3,
  134528. 9,
  134529. 2,
  134530. 10,
  134531. 1,
  134532. 11,
  134533. 0,
  134534. 12,
  134535. };
  134536. static long _vq_lengthlist__44c8_s_p7_0[] = {
  134537. 1, 4, 4, 6, 6, 8, 7, 9, 9,10,10,12,12, 6, 5, 5,
  134538. 7, 7, 8, 8,10,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  134539. 8,10,10,11,11,12,12,21, 7, 7, 7, 7, 8, 9,10,10,
  134540. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,12,12,13,
  134541. 13,21,11,11, 8, 8, 9, 9,11,11,12,12,13,13,21,11,
  134542. 11, 8, 8, 9, 9,11,11,12,12,13,13,21,21,21,10,10,
  134543. 10,10,11,11,12,13,13,13,21,21,21,10,10,10,10,11,
  134544. 11,13,13,14,13,21,21,21,13,13,11,11,12,12,13,13,
  134545. 14,14,21,21,21,14,14,11,11,12,12,13,13,14,14,21,
  134546. 21,21,21,20,13,13,13,12,14,14,16,15,20,20,20,20,
  134547. 20,13,13,13,13,14,13,15,15,
  134548. };
  134549. static float _vq_quantthresh__44c8_s_p7_0[] = {
  134550. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  134551. 27.5, 38.5, 49.5, 60.5,
  134552. };
  134553. static long _vq_quantmap__44c8_s_p7_0[] = {
  134554. 11, 9, 7, 5, 3, 1, 0, 2,
  134555. 4, 6, 8, 10, 12,
  134556. };
  134557. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_0 = {
  134558. _vq_quantthresh__44c8_s_p7_0,
  134559. _vq_quantmap__44c8_s_p7_0,
  134560. 13,
  134561. 13
  134562. };
  134563. static static_codebook _44c8_s_p7_0 = {
  134564. 2, 169,
  134565. _vq_lengthlist__44c8_s_p7_0,
  134566. 1, -523206656, 1618345984, 4, 0,
  134567. _vq_quantlist__44c8_s_p7_0,
  134568. NULL,
  134569. &_vq_auxt__44c8_s_p7_0,
  134570. NULL,
  134571. 0
  134572. };
  134573. static long _vq_quantlist__44c8_s_p7_1[] = {
  134574. 5,
  134575. 4,
  134576. 6,
  134577. 3,
  134578. 7,
  134579. 2,
  134580. 8,
  134581. 1,
  134582. 9,
  134583. 0,
  134584. 10,
  134585. };
  134586. static long _vq_lengthlist__44c8_s_p7_1[] = {
  134587. 4, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7,
  134588. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  134589. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  134590. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  134591. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  134592. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  134593. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  134594. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  134595. };
  134596. static float _vq_quantthresh__44c8_s_p7_1[] = {
  134597. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134598. 3.5, 4.5,
  134599. };
  134600. static long _vq_quantmap__44c8_s_p7_1[] = {
  134601. 9, 7, 5, 3, 1, 0, 2, 4,
  134602. 6, 8, 10,
  134603. };
  134604. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_1 = {
  134605. _vq_quantthresh__44c8_s_p7_1,
  134606. _vq_quantmap__44c8_s_p7_1,
  134607. 11,
  134608. 11
  134609. };
  134610. static static_codebook _44c8_s_p7_1 = {
  134611. 2, 121,
  134612. _vq_lengthlist__44c8_s_p7_1,
  134613. 1, -531365888, 1611661312, 4, 0,
  134614. _vq_quantlist__44c8_s_p7_1,
  134615. NULL,
  134616. &_vq_auxt__44c8_s_p7_1,
  134617. NULL,
  134618. 0
  134619. };
  134620. static long _vq_quantlist__44c8_s_p8_0[] = {
  134621. 7,
  134622. 6,
  134623. 8,
  134624. 5,
  134625. 9,
  134626. 4,
  134627. 10,
  134628. 3,
  134629. 11,
  134630. 2,
  134631. 12,
  134632. 1,
  134633. 13,
  134634. 0,
  134635. 14,
  134636. };
  134637. static long _vq_lengthlist__44c8_s_p8_0[] = {
  134638. 1, 4, 4, 7, 6, 8, 8, 8, 7, 9, 8,10,10,11,10, 6,
  134639. 5, 5, 7, 7, 9, 9, 8, 8,10,10,11,11,12,11, 6, 5,
  134640. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8,
  134641. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8, 8,
  134642. 8,10, 9, 9, 9,10,10,11,11,12,12,20,12,12, 9, 9,
  134643. 10,10,10,10,10,11,12,12,12,12,20,12,12, 9, 9,10,
  134644. 10,10,10,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,
  134645. 11,10,11,11,12,12,12,13,20,19,19, 9, 9, 9, 9,11,
  134646. 11,11,12,12,12,13,13,19,19,19,13,13,10,10,11,11,
  134647. 12,12,13,13,13,13,19,19,19,14,13,11,10,11,11,12,
  134648. 12,12,13,13,13,19,19,19,19,19,12,12,12,12,13,13,
  134649. 13,13,14,13,19,19,19,19,19,12,12,12,11,12,12,13,
  134650. 14,14,14,19,19,19,19,19,16,15,13,12,13,13,13,14,
  134651. 14,14,19,19,19,19,19,17,17,13,12,13,11,14,13,15,
  134652. 15,
  134653. };
  134654. static float _vq_quantthresh__44c8_s_p8_0[] = {
  134655. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  134656. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  134657. };
  134658. static long _vq_quantmap__44c8_s_p8_0[] = {
  134659. 13, 11, 9, 7, 5, 3, 1, 0,
  134660. 2, 4, 6, 8, 10, 12, 14,
  134661. };
  134662. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_0 = {
  134663. _vq_quantthresh__44c8_s_p8_0,
  134664. _vq_quantmap__44c8_s_p8_0,
  134665. 15,
  134666. 15
  134667. };
  134668. static static_codebook _44c8_s_p8_0 = {
  134669. 2, 225,
  134670. _vq_lengthlist__44c8_s_p8_0,
  134671. 1, -520986624, 1620377600, 4, 0,
  134672. _vq_quantlist__44c8_s_p8_0,
  134673. NULL,
  134674. &_vq_auxt__44c8_s_p8_0,
  134675. NULL,
  134676. 0
  134677. };
  134678. static long _vq_quantlist__44c8_s_p8_1[] = {
  134679. 10,
  134680. 9,
  134681. 11,
  134682. 8,
  134683. 12,
  134684. 7,
  134685. 13,
  134686. 6,
  134687. 14,
  134688. 5,
  134689. 15,
  134690. 4,
  134691. 16,
  134692. 3,
  134693. 17,
  134694. 2,
  134695. 18,
  134696. 1,
  134697. 19,
  134698. 0,
  134699. 20,
  134700. };
  134701. static long _vq_lengthlist__44c8_s_p8_1[] = {
  134702. 4, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  134703. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  134704. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  134705. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  134706. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134707. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  134708. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  134709. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  134710. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134711. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134712. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  134713. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  134714. 10,10, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9,
  134715. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134716. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  134717. 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,10,10,10,10,
  134718. 10,10,10, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  134719. 9,10,10,10,10,10,10,10, 9,10,10, 9,10,10,10,10,
  134720. 9,10, 9,10,10, 9,10,10,10,10,10,10,10, 9,10,10,
  134721. 10,10,10,10, 9, 9,10,10, 9,10,10,10,10,10,10,10,
  134722. 10,10,10,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9, 9,
  134723. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  134724. 10, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  134725. 10,10,10,10, 9, 9,10, 9, 9, 9,10,10,10,10,10,10,
  134726. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,10,10,
  134727. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10, 9,
  134728. 9,10, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  134729. 10, 9, 9,10,10, 9,10, 9, 9,
  134730. };
  134731. static float _vq_quantthresh__44c8_s_p8_1[] = {
  134732. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  134733. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  134734. 6.5, 7.5, 8.5, 9.5,
  134735. };
  134736. static long _vq_quantmap__44c8_s_p8_1[] = {
  134737. 19, 17, 15, 13, 11, 9, 7, 5,
  134738. 3, 1, 0, 2, 4, 6, 8, 10,
  134739. 12, 14, 16, 18, 20,
  134740. };
  134741. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_1 = {
  134742. _vq_quantthresh__44c8_s_p8_1,
  134743. _vq_quantmap__44c8_s_p8_1,
  134744. 21,
  134745. 21
  134746. };
  134747. static static_codebook _44c8_s_p8_1 = {
  134748. 2, 441,
  134749. _vq_lengthlist__44c8_s_p8_1,
  134750. 1, -529268736, 1611661312, 5, 0,
  134751. _vq_quantlist__44c8_s_p8_1,
  134752. NULL,
  134753. &_vq_auxt__44c8_s_p8_1,
  134754. NULL,
  134755. 0
  134756. };
  134757. static long _vq_quantlist__44c8_s_p9_0[] = {
  134758. 8,
  134759. 7,
  134760. 9,
  134761. 6,
  134762. 10,
  134763. 5,
  134764. 11,
  134765. 4,
  134766. 12,
  134767. 3,
  134768. 13,
  134769. 2,
  134770. 14,
  134771. 1,
  134772. 15,
  134773. 0,
  134774. 16,
  134775. };
  134776. static long _vq_lengthlist__44c8_s_p9_0[] = {
  134777. 1, 4, 3,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134778. 11, 4, 7, 7,11,11,11,11,11,11,11,11,11,11,11,11,
  134779. 11,11, 4, 8,11,11,11,11,11,11,11,11,11,11,11,11,
  134780. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134781. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134782. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134783. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134784. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134785. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134786. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134787. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134788. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134789. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134790. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134791. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134792. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134793. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134794. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134795. 10,
  134796. };
  134797. static float _vq_quantthresh__44c8_s_p9_0[] = {
  134798. -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5,
  134799. 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5, 6982.5,
  134800. };
  134801. static long _vq_quantmap__44c8_s_p9_0[] = {
  134802. 15, 13, 11, 9, 7, 5, 3, 1,
  134803. 0, 2, 4, 6, 8, 10, 12, 14,
  134804. 16,
  134805. };
  134806. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_0 = {
  134807. _vq_quantthresh__44c8_s_p9_0,
  134808. _vq_quantmap__44c8_s_p9_0,
  134809. 17,
  134810. 17
  134811. };
  134812. static static_codebook _44c8_s_p9_0 = {
  134813. 2, 289,
  134814. _vq_lengthlist__44c8_s_p9_0,
  134815. 1, -509798400, 1631393792, 5, 0,
  134816. _vq_quantlist__44c8_s_p9_0,
  134817. NULL,
  134818. &_vq_auxt__44c8_s_p9_0,
  134819. NULL,
  134820. 0
  134821. };
  134822. static long _vq_quantlist__44c8_s_p9_1[] = {
  134823. 9,
  134824. 8,
  134825. 10,
  134826. 7,
  134827. 11,
  134828. 6,
  134829. 12,
  134830. 5,
  134831. 13,
  134832. 4,
  134833. 14,
  134834. 3,
  134835. 15,
  134836. 2,
  134837. 16,
  134838. 1,
  134839. 17,
  134840. 0,
  134841. 18,
  134842. };
  134843. static long _vq_lengthlist__44c8_s_p9_1[] = {
  134844. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,10,10,
  134845. 10,11,11, 6, 6, 6, 8, 8, 9, 8, 8, 7,10, 8,11,10,
  134846. 12,11,12,12,13,13, 5, 5, 6, 8, 8, 9, 9, 8, 8,10,
  134847. 9,11,11,12,12,13,13,13,13,17, 8, 8, 9, 9, 9, 9,
  134848. 9, 9,10, 9,12,10,12,12,13,12,13,13,17, 9, 8, 9,
  134849. 9, 9, 9, 9, 9,10,10,12,12,12,12,13,13,13,13,17,
  134850. 13,13, 9, 9,10,10,10,10,11,11,12,11,13,12,13,13,
  134851. 14,15,17,13,13, 9, 8,10, 9,10,10,11,11,12,12,14,
  134852. 13,15,13,14,15,17,17,17, 9,10, 9,10,11,11,12,12,
  134853. 12,12,13,13,14,14,15,15,17,17,17, 9, 8, 9, 8,11,
  134854. 11,12,12,12,12,14,13,14,14,14,15,17,17,17,12,14,
  134855. 9,10,11,11,12,12,14,13,13,14,15,13,15,15,17,17,
  134856. 17,13,11,10, 8,11, 9,13,12,13,13,13,13,13,14,14,
  134857. 14,17,17,17,17,17,11,12,11,11,13,13,14,13,15,14,
  134858. 13,15,16,15,17,17,17,17,17,11,11,12, 8,13,12,14,
  134859. 13,17,14,15,14,15,14,17,17,17,17,17,15,15,12,12,
  134860. 12,12,13,14,14,14,15,14,17,14,17,17,17,17,17,16,
  134861. 17,12,12,13,12,13,13,14,14,14,14,14,14,17,17,17,
  134862. 17,17,17,17,14,14,13,12,13,13,15,15,14,13,15,17,
  134863. 17,17,17,17,17,17,17,13,14,13,13,13,13,14,15,15,
  134864. 15,14,15,17,17,17,17,17,17,17,16,15,13,14,13,13,
  134865. 14,14,15,14,14,16,17,17,17,17,17,17,17,16,16,13,
  134866. 14,13,13,14,14,15,14,15,14,
  134867. };
  134868. static float _vq_quantthresh__44c8_s_p9_1[] = {
  134869. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  134870. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  134871. 367.5, 416.5,
  134872. };
  134873. static long _vq_quantmap__44c8_s_p9_1[] = {
  134874. 17, 15, 13, 11, 9, 7, 5, 3,
  134875. 1, 0, 2, 4, 6, 8, 10, 12,
  134876. 14, 16, 18,
  134877. };
  134878. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_1 = {
  134879. _vq_quantthresh__44c8_s_p9_1,
  134880. _vq_quantmap__44c8_s_p9_1,
  134881. 19,
  134882. 19
  134883. };
  134884. static static_codebook _44c8_s_p9_1 = {
  134885. 2, 361,
  134886. _vq_lengthlist__44c8_s_p9_1,
  134887. 1, -518287360, 1622704128, 5, 0,
  134888. _vq_quantlist__44c8_s_p9_1,
  134889. NULL,
  134890. &_vq_auxt__44c8_s_p9_1,
  134891. NULL,
  134892. 0
  134893. };
  134894. static long _vq_quantlist__44c8_s_p9_2[] = {
  134895. 24,
  134896. 23,
  134897. 25,
  134898. 22,
  134899. 26,
  134900. 21,
  134901. 27,
  134902. 20,
  134903. 28,
  134904. 19,
  134905. 29,
  134906. 18,
  134907. 30,
  134908. 17,
  134909. 31,
  134910. 16,
  134911. 32,
  134912. 15,
  134913. 33,
  134914. 14,
  134915. 34,
  134916. 13,
  134917. 35,
  134918. 12,
  134919. 36,
  134920. 11,
  134921. 37,
  134922. 10,
  134923. 38,
  134924. 9,
  134925. 39,
  134926. 8,
  134927. 40,
  134928. 7,
  134929. 41,
  134930. 6,
  134931. 42,
  134932. 5,
  134933. 43,
  134934. 4,
  134935. 44,
  134936. 3,
  134937. 45,
  134938. 2,
  134939. 46,
  134940. 1,
  134941. 47,
  134942. 0,
  134943. 48,
  134944. };
  134945. static long _vq_lengthlist__44c8_s_p9_2[] = {
  134946. 2, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  134947. 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  134948. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  134949. 7,
  134950. };
  134951. static float _vq_quantthresh__44c8_s_p9_2[] = {
  134952. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  134953. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  134954. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134955. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134956. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  134957. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  134958. };
  134959. static long _vq_quantmap__44c8_s_p9_2[] = {
  134960. 47, 45, 43, 41, 39, 37, 35, 33,
  134961. 31, 29, 27, 25, 23, 21, 19, 17,
  134962. 15, 13, 11, 9, 7, 5, 3, 1,
  134963. 0, 2, 4, 6, 8, 10, 12, 14,
  134964. 16, 18, 20, 22, 24, 26, 28, 30,
  134965. 32, 34, 36, 38, 40, 42, 44, 46,
  134966. 48,
  134967. };
  134968. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_2 = {
  134969. _vq_quantthresh__44c8_s_p9_2,
  134970. _vq_quantmap__44c8_s_p9_2,
  134971. 49,
  134972. 49
  134973. };
  134974. static static_codebook _44c8_s_p9_2 = {
  134975. 1, 49,
  134976. _vq_lengthlist__44c8_s_p9_2,
  134977. 1, -526909440, 1611661312, 6, 0,
  134978. _vq_quantlist__44c8_s_p9_2,
  134979. NULL,
  134980. &_vq_auxt__44c8_s_p9_2,
  134981. NULL,
  134982. 0
  134983. };
  134984. static long _huff_lengthlist__44c8_s_short[] = {
  134985. 4,11,13,14,15,15,18,17,19,17, 5, 6, 8, 9,10,10,
  134986. 12,15,19,19, 6, 6, 6, 6, 8, 8,11,14,18,19, 8, 6,
  134987. 5, 4, 6, 7,10,13,16,17, 9, 7, 6, 5, 6, 7, 9,12,
  134988. 15,19,10, 8, 7, 6, 6, 6, 7, 9,13,15,12,10, 9, 8,
  134989. 7, 6, 4, 5,10,15,13,13,11, 8, 6, 6, 4, 2, 7,12,
  134990. 17,15,16,10, 8, 8, 7, 6, 9,12,19,18,17,13,11,10,
  134991. 10, 9,11,14,
  134992. };
  134993. static static_codebook _huff_book__44c8_s_short = {
  134994. 2, 100,
  134995. _huff_lengthlist__44c8_s_short,
  134996. 0, 0, 0, 0, 0,
  134997. NULL,
  134998. NULL,
  134999. NULL,
  135000. NULL,
  135001. 0
  135002. };
  135003. static long _huff_lengthlist__44c9_s_long[] = {
  135004. 3, 8,12,14,15,15,15,13,15,15, 6, 5, 8,10,12,12,
  135005. 13,12,14,13,10, 6, 5, 6, 8, 9,11,11,13,13,13, 8,
  135006. 5, 4, 5, 6, 8,10,11,13,14,10, 7, 5, 4, 5, 7, 9,
  135007. 11,12,13,11, 8, 6, 5, 4, 5, 7, 9,11,12,11,10, 8,
  135008. 7, 5, 4, 5, 9,10,13,13,11,10, 8, 6, 5, 4, 7, 9,
  135009. 15,14,13,12,10, 9, 8, 7, 8, 9,12,12,14,13,12,11,
  135010. 10, 9, 8, 9,
  135011. };
  135012. static static_codebook _huff_book__44c9_s_long = {
  135013. 2, 100,
  135014. _huff_lengthlist__44c9_s_long,
  135015. 0, 0, 0, 0, 0,
  135016. NULL,
  135017. NULL,
  135018. NULL,
  135019. NULL,
  135020. 0
  135021. };
  135022. static long _vq_quantlist__44c9_s_p1_0[] = {
  135023. 1,
  135024. 0,
  135025. 2,
  135026. };
  135027. static long _vq_lengthlist__44c9_s_p1_0[] = {
  135028. 1, 5, 5, 0, 5, 5, 0, 5, 5, 6, 8, 8, 0, 9, 8, 0,
  135029. 9, 8, 6, 8, 8, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  135030. 0, 0, 0, 0, 5, 8, 8, 0, 7, 7, 0, 8, 8, 5, 8, 8,
  135031. 0, 7, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  135032. 9, 8, 0, 8, 8, 0, 7, 7, 5, 8, 9, 0, 8, 8, 0, 7,
  135033. 7,
  135034. };
  135035. static float _vq_quantthresh__44c9_s_p1_0[] = {
  135036. -0.5, 0.5,
  135037. };
  135038. static long _vq_quantmap__44c9_s_p1_0[] = {
  135039. 1, 0, 2,
  135040. };
  135041. static encode_aux_threshmatch _vq_auxt__44c9_s_p1_0 = {
  135042. _vq_quantthresh__44c9_s_p1_0,
  135043. _vq_quantmap__44c9_s_p1_0,
  135044. 3,
  135045. 3
  135046. };
  135047. static static_codebook _44c9_s_p1_0 = {
  135048. 4, 81,
  135049. _vq_lengthlist__44c9_s_p1_0,
  135050. 1, -535822336, 1611661312, 2, 0,
  135051. _vq_quantlist__44c9_s_p1_0,
  135052. NULL,
  135053. &_vq_auxt__44c9_s_p1_0,
  135054. NULL,
  135055. 0
  135056. };
  135057. static long _vq_quantlist__44c9_s_p2_0[] = {
  135058. 2,
  135059. 1,
  135060. 3,
  135061. 0,
  135062. 4,
  135063. };
  135064. static long _vq_lengthlist__44c9_s_p2_0[] = {
  135065. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  135066. 7, 7, 9, 9, 0, 0, 0, 9, 9, 6, 7, 7, 9, 8, 0, 8,
  135067. 8, 9, 9, 0, 8, 7, 9, 9, 0, 9,10,10,10, 0, 0, 0,
  135068. 11,10, 6, 7, 7, 8, 9, 0, 8, 8, 9, 9, 0, 7, 8, 9,
  135069. 9, 0,10, 9,11,10, 0, 0, 0,10,10, 8, 9, 8,10,10,
  135070. 0,10,10,12,11, 0,10,10,11,11, 0,12,13,13,13, 0,
  135071. 0, 0,13,12, 8, 8, 9,10,10, 0,10,10,11,12, 0,10,
  135072. 10,11,11, 0,13,12,13,13, 0, 0, 0,13,13, 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, 6, 8, 7,10,10, 0, 7, 7,10, 9,
  135075. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,10,10, 6,
  135076. 7, 8,10,10, 0, 7, 7, 9,10, 0, 7, 7,10,10, 0, 9,
  135077. 9,10,10, 0, 0, 0,10,10, 8, 9, 9,11,11, 0,10,10,
  135078. 11,11, 0,10,10,11,11, 0,12,12,12,12, 0, 0, 0,12,
  135079. 12, 8, 9,10,11,11, 0, 9,10,11,11, 0,10,10,11,11,
  135080. 0,12,12,12,12, 0, 0, 0,12,12, 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, 5, 8, 7,10,10, 0, 7, 7,10,10, 0, 7, 7,
  135083. 10, 9, 0, 9, 9,10,10, 0, 0, 0,10,10, 6, 7, 8,10,
  135084. 10, 0, 7, 7,10,10, 0, 7, 7, 9,10, 0, 9, 9,10,10,
  135085. 0, 0, 0,10,10, 8,10, 9,12,11, 0,10,10,12,11, 0,
  135086. 10, 9,11,11, 0,11,12,12,12, 0, 0, 0,12,12, 8, 9,
  135087. 10,11,12, 0,10,10,11,11, 0, 9,10,11,11, 0,12,11,
  135088. 12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135090. 7,10, 9,12,12, 0, 9, 9,12,11, 0, 9, 9,11,11, 0,
  135091. 10,10,12,11, 0, 0, 0,11,12, 7, 9,10,12,12, 0, 9,
  135092. 9,11,12, 0, 9, 9,11,11, 0,10,10,11,12, 0, 0, 0,
  135093. 11,11, 9,11,10,13,12, 0,10,10,12,12, 0,10,10,12,
  135094. 12, 0,11,11,12,12, 0, 0, 0,13,12, 9,10,11,12,13,
  135095. 0,10,10,12,12, 0,10,10,12,12, 0,11,12,12,12, 0,
  135096. 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  135101. 11,10,13,13, 0,10,10,12,12, 0,10,10,12,12, 0,11,
  135102. 12,12,12, 0, 0, 0,12,12, 9,10,11,13,13, 0,10,10,
  135103. 12,12, 0,10,10,12,12, 0,12,11,13,12, 0, 0, 0,12,
  135104. 12,
  135105. };
  135106. static float _vq_quantthresh__44c9_s_p2_0[] = {
  135107. -1.5, -0.5, 0.5, 1.5,
  135108. };
  135109. static long _vq_quantmap__44c9_s_p2_0[] = {
  135110. 3, 1, 0, 2, 4,
  135111. };
  135112. static encode_aux_threshmatch _vq_auxt__44c9_s_p2_0 = {
  135113. _vq_quantthresh__44c9_s_p2_0,
  135114. _vq_quantmap__44c9_s_p2_0,
  135115. 5,
  135116. 5
  135117. };
  135118. static static_codebook _44c9_s_p2_0 = {
  135119. 4, 625,
  135120. _vq_lengthlist__44c9_s_p2_0,
  135121. 1, -533725184, 1611661312, 3, 0,
  135122. _vq_quantlist__44c9_s_p2_0,
  135123. NULL,
  135124. &_vq_auxt__44c9_s_p2_0,
  135125. NULL,
  135126. 0
  135127. };
  135128. static long _vq_quantlist__44c9_s_p3_0[] = {
  135129. 4,
  135130. 3,
  135131. 5,
  135132. 2,
  135133. 6,
  135134. 1,
  135135. 7,
  135136. 0,
  135137. 8,
  135138. };
  135139. static long _vq_lengthlist__44c9_s_p3_0[] = {
  135140. 3, 4, 4, 5, 5, 6, 6, 8, 8, 0, 4, 4, 5, 5, 6, 7,
  135141. 8, 8, 0, 4, 4, 5, 5, 7, 7, 8, 8, 0, 5, 5, 6, 6,
  135142. 7, 7, 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0,
  135143. 7, 7, 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0,
  135144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135145. 0,
  135146. };
  135147. static float _vq_quantthresh__44c9_s_p3_0[] = {
  135148. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  135149. };
  135150. static long _vq_quantmap__44c9_s_p3_0[] = {
  135151. 7, 5, 3, 1, 0, 2, 4, 6,
  135152. 8,
  135153. };
  135154. static encode_aux_threshmatch _vq_auxt__44c9_s_p3_0 = {
  135155. _vq_quantthresh__44c9_s_p3_0,
  135156. _vq_quantmap__44c9_s_p3_0,
  135157. 9,
  135158. 9
  135159. };
  135160. static static_codebook _44c9_s_p3_0 = {
  135161. 2, 81,
  135162. _vq_lengthlist__44c9_s_p3_0,
  135163. 1, -531628032, 1611661312, 4, 0,
  135164. _vq_quantlist__44c9_s_p3_0,
  135165. NULL,
  135166. &_vq_auxt__44c9_s_p3_0,
  135167. NULL,
  135168. 0
  135169. };
  135170. static long _vq_quantlist__44c9_s_p4_0[] = {
  135171. 8,
  135172. 7,
  135173. 9,
  135174. 6,
  135175. 10,
  135176. 5,
  135177. 11,
  135178. 4,
  135179. 12,
  135180. 3,
  135181. 13,
  135182. 2,
  135183. 14,
  135184. 1,
  135185. 15,
  135186. 0,
  135187. 16,
  135188. };
  135189. static long _vq_lengthlist__44c9_s_p4_0[] = {
  135190. 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,10,
  135191. 10, 0, 5, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  135192. 11,11, 0, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  135193. 10,11,11, 0, 6, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,
  135194. 11,11,11,12, 0, 0, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,
  135195. 10,11,11,12,12, 0, 0, 0, 7, 7, 7, 7, 9, 9, 9, 9,
  135196. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 7, 8, 9, 9, 9,
  135197. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  135198. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  135199. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  135200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135208. 0,
  135209. };
  135210. static float _vq_quantthresh__44c9_s_p4_0[] = {
  135211. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135212. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135213. };
  135214. static long _vq_quantmap__44c9_s_p4_0[] = {
  135215. 15, 13, 11, 9, 7, 5, 3, 1,
  135216. 0, 2, 4, 6, 8, 10, 12, 14,
  135217. 16,
  135218. };
  135219. static encode_aux_threshmatch _vq_auxt__44c9_s_p4_0 = {
  135220. _vq_quantthresh__44c9_s_p4_0,
  135221. _vq_quantmap__44c9_s_p4_0,
  135222. 17,
  135223. 17
  135224. };
  135225. static static_codebook _44c9_s_p4_0 = {
  135226. 2, 289,
  135227. _vq_lengthlist__44c9_s_p4_0,
  135228. 1, -529530880, 1611661312, 5, 0,
  135229. _vq_quantlist__44c9_s_p4_0,
  135230. NULL,
  135231. &_vq_auxt__44c9_s_p4_0,
  135232. NULL,
  135233. 0
  135234. };
  135235. static long _vq_quantlist__44c9_s_p5_0[] = {
  135236. 1,
  135237. 0,
  135238. 2,
  135239. };
  135240. static long _vq_lengthlist__44c9_s_p5_0[] = {
  135241. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6, 9,10,10,10,
  135242. 10, 9, 4, 6, 7, 9,10,10,10, 9,10, 5, 9, 9, 9,11,
  135243. 11,10,11,11, 7,10, 9,11,12,11,12,12,12, 7, 9,10,
  135244. 11,11,12,12,12,12, 6,10,10,10,12,12,10,12,11, 7,
  135245. 10,10,11,12,12,11,12,12, 7,10,10,11,12,12,12,12,
  135246. 12,
  135247. };
  135248. static float _vq_quantthresh__44c9_s_p5_0[] = {
  135249. -5.5, 5.5,
  135250. };
  135251. static long _vq_quantmap__44c9_s_p5_0[] = {
  135252. 1, 0, 2,
  135253. };
  135254. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_0 = {
  135255. _vq_quantthresh__44c9_s_p5_0,
  135256. _vq_quantmap__44c9_s_p5_0,
  135257. 3,
  135258. 3
  135259. };
  135260. static static_codebook _44c9_s_p5_0 = {
  135261. 4, 81,
  135262. _vq_lengthlist__44c9_s_p5_0,
  135263. 1, -529137664, 1618345984, 2, 0,
  135264. _vq_quantlist__44c9_s_p5_0,
  135265. NULL,
  135266. &_vq_auxt__44c9_s_p5_0,
  135267. NULL,
  135268. 0
  135269. };
  135270. static long _vq_quantlist__44c9_s_p5_1[] = {
  135271. 5,
  135272. 4,
  135273. 6,
  135274. 3,
  135275. 7,
  135276. 2,
  135277. 8,
  135278. 1,
  135279. 9,
  135280. 0,
  135281. 10,
  135282. };
  135283. static long _vq_lengthlist__44c9_s_p5_1[] = {
  135284. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7,11, 5, 5, 6, 6,
  135285. 7, 7, 7, 7, 8, 8,11, 5, 5, 6, 6, 7, 7, 7, 7, 8,
  135286. 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11, 6,
  135287. 6, 7, 7, 7, 8, 8, 8,11,11,11, 6, 6, 7, 7, 7, 8,
  135288. 8, 8,11,11,11, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11,
  135289. 7, 7, 7, 7, 7, 7, 8, 8,11,11,11,10,10, 7, 7, 7,
  135290. 7, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 7, 7,11,11,
  135291. 11,11,11, 7, 7, 7, 7, 7, 7,
  135292. };
  135293. static float _vq_quantthresh__44c9_s_p5_1[] = {
  135294. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  135295. 3.5, 4.5,
  135296. };
  135297. static long _vq_quantmap__44c9_s_p5_1[] = {
  135298. 9, 7, 5, 3, 1, 0, 2, 4,
  135299. 6, 8, 10,
  135300. };
  135301. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_1 = {
  135302. _vq_quantthresh__44c9_s_p5_1,
  135303. _vq_quantmap__44c9_s_p5_1,
  135304. 11,
  135305. 11
  135306. };
  135307. static static_codebook _44c9_s_p5_1 = {
  135308. 2, 121,
  135309. _vq_lengthlist__44c9_s_p5_1,
  135310. 1, -531365888, 1611661312, 4, 0,
  135311. _vq_quantlist__44c9_s_p5_1,
  135312. NULL,
  135313. &_vq_auxt__44c9_s_p5_1,
  135314. NULL,
  135315. 0
  135316. };
  135317. static long _vq_quantlist__44c9_s_p6_0[] = {
  135318. 6,
  135319. 5,
  135320. 7,
  135321. 4,
  135322. 8,
  135323. 3,
  135324. 9,
  135325. 2,
  135326. 10,
  135327. 1,
  135328. 11,
  135329. 0,
  135330. 12,
  135331. };
  135332. static long _vq_lengthlist__44c9_s_p6_0[] = {
  135333. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 5, 4, 4,
  135334. 6, 6, 8, 8, 9, 9, 9, 9,10,10, 6, 4, 4, 6, 6, 8,
  135335. 8, 9, 9, 9, 9,10,10, 0, 6, 6, 7, 7, 8, 8, 9, 9,
  135336. 10,10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  135337. 11, 0,10,10, 8, 8, 9, 9,10,10,11,11,12,12, 0,11,
  135338. 11, 8, 8, 9, 9,10,10,11,11,12,12, 0, 0, 0, 0, 0,
  135339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135343. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135344. };
  135345. static float _vq_quantthresh__44c9_s_p6_0[] = {
  135346. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  135347. 12.5, 17.5, 22.5, 27.5,
  135348. };
  135349. static long _vq_quantmap__44c9_s_p6_0[] = {
  135350. 11, 9, 7, 5, 3, 1, 0, 2,
  135351. 4, 6, 8, 10, 12,
  135352. };
  135353. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_0 = {
  135354. _vq_quantthresh__44c9_s_p6_0,
  135355. _vq_quantmap__44c9_s_p6_0,
  135356. 13,
  135357. 13
  135358. };
  135359. static static_codebook _44c9_s_p6_0 = {
  135360. 2, 169,
  135361. _vq_lengthlist__44c9_s_p6_0,
  135362. 1, -526516224, 1616117760, 4, 0,
  135363. _vq_quantlist__44c9_s_p6_0,
  135364. NULL,
  135365. &_vq_auxt__44c9_s_p6_0,
  135366. NULL,
  135367. 0
  135368. };
  135369. static long _vq_quantlist__44c9_s_p6_1[] = {
  135370. 2,
  135371. 1,
  135372. 3,
  135373. 0,
  135374. 4,
  135375. };
  135376. static long _vq_lengthlist__44c9_s_p6_1[] = {
  135377. 4, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5,
  135378. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  135379. };
  135380. static float _vq_quantthresh__44c9_s_p6_1[] = {
  135381. -1.5, -0.5, 0.5, 1.5,
  135382. };
  135383. static long _vq_quantmap__44c9_s_p6_1[] = {
  135384. 3, 1, 0, 2, 4,
  135385. };
  135386. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_1 = {
  135387. _vq_quantthresh__44c9_s_p6_1,
  135388. _vq_quantmap__44c9_s_p6_1,
  135389. 5,
  135390. 5
  135391. };
  135392. static static_codebook _44c9_s_p6_1 = {
  135393. 2, 25,
  135394. _vq_lengthlist__44c9_s_p6_1,
  135395. 1, -533725184, 1611661312, 3, 0,
  135396. _vq_quantlist__44c9_s_p6_1,
  135397. NULL,
  135398. &_vq_auxt__44c9_s_p6_1,
  135399. NULL,
  135400. 0
  135401. };
  135402. static long _vq_quantlist__44c9_s_p7_0[] = {
  135403. 6,
  135404. 5,
  135405. 7,
  135406. 4,
  135407. 8,
  135408. 3,
  135409. 9,
  135410. 2,
  135411. 10,
  135412. 1,
  135413. 11,
  135414. 0,
  135415. 12,
  135416. };
  135417. static long _vq_lengthlist__44c9_s_p7_0[] = {
  135418. 2, 4, 4, 6, 6, 7, 7, 8, 8,10,10,11,11, 6, 4, 4,
  135419. 6, 6, 8, 8, 9, 9,10,10,12,12, 6, 4, 5, 6, 6, 8,
  135420. 8, 9, 9,10,10,12,12,20, 6, 6, 6, 6, 8, 8, 9,10,
  135421. 11,11,12,12,20, 6, 6, 6, 6, 8, 8,10,10,11,11,12,
  135422. 12,20,10,10, 7, 7, 9, 9,10,10,11,11,12,12,20,11,
  135423. 11, 7, 7, 9, 9,10,10,11,11,12,12,20,20,20, 9, 9,
  135424. 9, 9,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,11,
  135425. 11,12,12,13,13,20,20,20,13,13,10,10,11,11,12,13,
  135426. 13,13,20,20,20,13,13,10,10,11,11,12,13,13,13,20,
  135427. 20,20,20,19,12,12,12,12,13,13,14,15,19,19,19,19,
  135428. 19,12,12,12,12,13,13,14,14,
  135429. };
  135430. static float _vq_quantthresh__44c9_s_p7_0[] = {
  135431. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  135432. 27.5, 38.5, 49.5, 60.5,
  135433. };
  135434. static long _vq_quantmap__44c9_s_p7_0[] = {
  135435. 11, 9, 7, 5, 3, 1, 0, 2,
  135436. 4, 6, 8, 10, 12,
  135437. };
  135438. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_0 = {
  135439. _vq_quantthresh__44c9_s_p7_0,
  135440. _vq_quantmap__44c9_s_p7_0,
  135441. 13,
  135442. 13
  135443. };
  135444. static static_codebook _44c9_s_p7_0 = {
  135445. 2, 169,
  135446. _vq_lengthlist__44c9_s_p7_0,
  135447. 1, -523206656, 1618345984, 4, 0,
  135448. _vq_quantlist__44c9_s_p7_0,
  135449. NULL,
  135450. &_vq_auxt__44c9_s_p7_0,
  135451. NULL,
  135452. 0
  135453. };
  135454. static long _vq_quantlist__44c9_s_p7_1[] = {
  135455. 5,
  135456. 4,
  135457. 6,
  135458. 3,
  135459. 7,
  135460. 2,
  135461. 8,
  135462. 1,
  135463. 9,
  135464. 0,
  135465. 10,
  135466. };
  135467. static long _vq_lengthlist__44c9_s_p7_1[] = {
  135468. 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6,
  135469. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  135470. 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 6,
  135471. 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  135472. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  135473. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  135474. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  135475. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  135476. };
  135477. static float _vq_quantthresh__44c9_s_p7_1[] = {
  135478. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  135479. 3.5, 4.5,
  135480. };
  135481. static long _vq_quantmap__44c9_s_p7_1[] = {
  135482. 9, 7, 5, 3, 1, 0, 2, 4,
  135483. 6, 8, 10,
  135484. };
  135485. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_1 = {
  135486. _vq_quantthresh__44c9_s_p7_1,
  135487. _vq_quantmap__44c9_s_p7_1,
  135488. 11,
  135489. 11
  135490. };
  135491. static static_codebook _44c9_s_p7_1 = {
  135492. 2, 121,
  135493. _vq_lengthlist__44c9_s_p7_1,
  135494. 1, -531365888, 1611661312, 4, 0,
  135495. _vq_quantlist__44c9_s_p7_1,
  135496. NULL,
  135497. &_vq_auxt__44c9_s_p7_1,
  135498. NULL,
  135499. 0
  135500. };
  135501. static long _vq_quantlist__44c9_s_p8_0[] = {
  135502. 7,
  135503. 6,
  135504. 8,
  135505. 5,
  135506. 9,
  135507. 4,
  135508. 10,
  135509. 3,
  135510. 11,
  135511. 2,
  135512. 12,
  135513. 1,
  135514. 13,
  135515. 0,
  135516. 14,
  135517. };
  135518. static long _vq_lengthlist__44c9_s_p8_0[] = {
  135519. 1, 4, 4, 7, 6, 8, 8, 8, 8, 9, 9,10,10,11,10, 6,
  135520. 5, 5, 7, 7, 9, 9, 8, 9,10,10,11,11,12,12, 6, 5,
  135521. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,21, 7, 8,
  135522. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,21, 8, 8, 8,
  135523. 8, 9, 9, 9, 9,10,10,11,11,12,12,21,11,12, 9, 9,
  135524. 10,10,10,10,10,11,11,12,12,12,21,12,12, 9, 8,10,
  135525. 10,10,10,11,11,12,12,13,13,21,21,21, 9, 9, 9, 9,
  135526. 11,11,11,11,12,12,12,13,21,20,20, 9, 9, 9, 9,10,
  135527. 11,11,11,12,12,13,13,20,20,20,13,13,10,10,11,11,
  135528. 12,12,13,13,13,13,20,20,20,13,13,10,10,11,11,12,
  135529. 12,13,13,13,13,20,20,20,20,20,12,12,12,12,12,12,
  135530. 13,13,14,14,20,20,20,20,20,12,12,12,11,13,12,13,
  135531. 13,14,14,20,20,20,20,20,15,16,13,12,13,13,14,13,
  135532. 14,14,20,20,20,20,20,16,15,12,12,13,12,14,13,14,
  135533. 14,
  135534. };
  135535. static float _vq_quantthresh__44c9_s_p8_0[] = {
  135536. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  135537. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  135538. };
  135539. static long _vq_quantmap__44c9_s_p8_0[] = {
  135540. 13, 11, 9, 7, 5, 3, 1, 0,
  135541. 2, 4, 6, 8, 10, 12, 14,
  135542. };
  135543. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_0 = {
  135544. _vq_quantthresh__44c9_s_p8_0,
  135545. _vq_quantmap__44c9_s_p8_0,
  135546. 15,
  135547. 15
  135548. };
  135549. static static_codebook _44c9_s_p8_0 = {
  135550. 2, 225,
  135551. _vq_lengthlist__44c9_s_p8_0,
  135552. 1, -520986624, 1620377600, 4, 0,
  135553. _vq_quantlist__44c9_s_p8_0,
  135554. NULL,
  135555. &_vq_auxt__44c9_s_p8_0,
  135556. NULL,
  135557. 0
  135558. };
  135559. static long _vq_quantlist__44c9_s_p8_1[] = {
  135560. 10,
  135561. 9,
  135562. 11,
  135563. 8,
  135564. 12,
  135565. 7,
  135566. 13,
  135567. 6,
  135568. 14,
  135569. 5,
  135570. 15,
  135571. 4,
  135572. 16,
  135573. 3,
  135574. 17,
  135575. 2,
  135576. 18,
  135577. 1,
  135578. 19,
  135579. 0,
  135580. 20,
  135581. };
  135582. static long _vq_lengthlist__44c9_s_p8_1[] = {
  135583. 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  135584. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  135585. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  135586. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  135587. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135588. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  135589. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8,
  135590. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  135591. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135592. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135593. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  135594. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  135595. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135596. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135597. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  135598. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,
  135599. 10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,
  135600. 9,10,10,10,10,10,10,10, 9, 9, 9,10,10,10,10,10,
  135601. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10, 9, 9,10,
  135602. 9,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  135603. 10,10,10,10, 9, 9,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  135604. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  135605. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  135606. 10,10, 9, 9,10, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  135607. 10,10,10,10,10, 9, 9,10,10, 9, 9,10, 9, 9, 9,10,
  135608. 10,10,10,10,10,10,10,10,10,10, 9, 9,10, 9, 9, 9,
  135609. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9,
  135610. 9, 9, 9,10, 9, 9, 9, 9, 9,
  135611. };
  135612. static float _vq_quantthresh__44c9_s_p8_1[] = {
  135613. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  135614. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  135615. 6.5, 7.5, 8.5, 9.5,
  135616. };
  135617. static long _vq_quantmap__44c9_s_p8_1[] = {
  135618. 19, 17, 15, 13, 11, 9, 7, 5,
  135619. 3, 1, 0, 2, 4, 6, 8, 10,
  135620. 12, 14, 16, 18, 20,
  135621. };
  135622. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_1 = {
  135623. _vq_quantthresh__44c9_s_p8_1,
  135624. _vq_quantmap__44c9_s_p8_1,
  135625. 21,
  135626. 21
  135627. };
  135628. static static_codebook _44c9_s_p8_1 = {
  135629. 2, 441,
  135630. _vq_lengthlist__44c9_s_p8_1,
  135631. 1, -529268736, 1611661312, 5, 0,
  135632. _vq_quantlist__44c9_s_p8_1,
  135633. NULL,
  135634. &_vq_auxt__44c9_s_p8_1,
  135635. NULL,
  135636. 0
  135637. };
  135638. static long _vq_quantlist__44c9_s_p9_0[] = {
  135639. 9,
  135640. 8,
  135641. 10,
  135642. 7,
  135643. 11,
  135644. 6,
  135645. 12,
  135646. 5,
  135647. 13,
  135648. 4,
  135649. 14,
  135650. 3,
  135651. 15,
  135652. 2,
  135653. 16,
  135654. 1,
  135655. 17,
  135656. 0,
  135657. 18,
  135658. };
  135659. static long _vq_lengthlist__44c9_s_p9_0[] = {
  135660. 1, 4, 3,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135661. 12,12,12, 4, 5, 6,12,12,12,12,12,12,12,12,12,12,
  135662. 12,12,12,12,12,12, 4, 6, 6,12,12,12,12,12,12,12,
  135663. 12,12,12,12,12,12,12,12,12,12,12,11,12,12,12,12,
  135664. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135665. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135666. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135667. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135668. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135669. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135670. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135671. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135672. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135673. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135674. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135675. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135676. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  135677. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135678. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135679. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135680. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135681. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135682. 11,11,11,11,11,11,11,11,11,
  135683. };
  135684. static float _vq_quantthresh__44c9_s_p9_0[] = {
  135685. -7913.5, -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5,
  135686. -465.5, 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  135687. 6982.5, 7913.5,
  135688. };
  135689. static long _vq_quantmap__44c9_s_p9_0[] = {
  135690. 17, 15, 13, 11, 9, 7, 5, 3,
  135691. 1, 0, 2, 4, 6, 8, 10, 12,
  135692. 14, 16, 18,
  135693. };
  135694. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_0 = {
  135695. _vq_quantthresh__44c9_s_p9_0,
  135696. _vq_quantmap__44c9_s_p9_0,
  135697. 19,
  135698. 19
  135699. };
  135700. static static_codebook _44c9_s_p9_0 = {
  135701. 2, 361,
  135702. _vq_lengthlist__44c9_s_p9_0,
  135703. 1, -508535424, 1631393792, 5, 0,
  135704. _vq_quantlist__44c9_s_p9_0,
  135705. NULL,
  135706. &_vq_auxt__44c9_s_p9_0,
  135707. NULL,
  135708. 0
  135709. };
  135710. static long _vq_quantlist__44c9_s_p9_1[] = {
  135711. 9,
  135712. 8,
  135713. 10,
  135714. 7,
  135715. 11,
  135716. 6,
  135717. 12,
  135718. 5,
  135719. 13,
  135720. 4,
  135721. 14,
  135722. 3,
  135723. 15,
  135724. 2,
  135725. 16,
  135726. 1,
  135727. 17,
  135728. 0,
  135729. 18,
  135730. };
  135731. static long _vq_lengthlist__44c9_s_p9_1[] = {
  135732. 1, 4, 4, 7, 7, 7, 7, 8, 7, 9, 8, 9, 9,10,10,11,
  135733. 11,11,11, 6, 5, 5, 8, 8, 9, 9, 9, 8,10, 9,11,10,
  135734. 12,12,13,12,13,13, 5, 5, 5, 8, 8, 9, 9, 9, 9,10,
  135735. 10,11,11,12,12,13,12,13,13,17, 8, 8, 9, 9, 9, 9,
  135736. 9, 9,10,10,12,11,13,12,13,13,13,13,18, 8, 8, 9,
  135737. 9, 9, 9, 9, 9,11,11,12,12,13,13,13,13,13,13,17,
  135738. 13,12, 9, 9,10,10,10,10,11,11,12,12,12,13,13,13,
  135739. 14,14,18,13,12, 9, 9,10,10,10,10,11,11,12,12,13,
  135740. 13,13,14,14,14,17,18,18,10,10,10,10,11,11,11,12,
  135741. 12,12,14,13,14,13,13,14,18,18,18,10, 9,10, 9,11,
  135742. 11,12,12,12,12,13,13,15,14,14,14,18,18,16,13,14,
  135743. 10,11,11,11,12,13,13,13,13,14,13,13,14,14,18,18,
  135744. 18,14,12,11, 9,11,10,13,12,13,13,13,14,14,14,13,
  135745. 14,18,18,17,18,18,11,12,12,12,13,13,14,13,14,14,
  135746. 13,14,14,14,18,18,18,18,17,12,10,12, 9,13,11,13,
  135747. 14,14,14,14,14,15,14,18,18,17,17,18,14,15,12,13,
  135748. 13,13,14,13,14,14,15,14,15,14,18,17,18,18,18,15,
  135749. 15,12,10,14,10,14,14,13,13,14,14,14,14,18,16,18,
  135750. 18,18,18,17,14,14,13,14,14,13,13,14,14,14,15,15,
  135751. 18,18,18,18,17,17,17,14,14,14,12,14,13,14,14,15,
  135752. 14,15,14,18,18,18,18,18,18,18,17,16,13,13,13,14,
  135753. 14,14,14,15,16,15,18,18,18,18,18,18,18,17,17,13,
  135754. 13,13,13,14,13,14,15,15,15,
  135755. };
  135756. static float _vq_quantthresh__44c9_s_p9_1[] = {
  135757. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  135758. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  135759. 367.5, 416.5,
  135760. };
  135761. static long _vq_quantmap__44c9_s_p9_1[] = {
  135762. 17, 15, 13, 11, 9, 7, 5, 3,
  135763. 1, 0, 2, 4, 6, 8, 10, 12,
  135764. 14, 16, 18,
  135765. };
  135766. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_1 = {
  135767. _vq_quantthresh__44c9_s_p9_1,
  135768. _vq_quantmap__44c9_s_p9_1,
  135769. 19,
  135770. 19
  135771. };
  135772. static static_codebook _44c9_s_p9_1 = {
  135773. 2, 361,
  135774. _vq_lengthlist__44c9_s_p9_1,
  135775. 1, -518287360, 1622704128, 5, 0,
  135776. _vq_quantlist__44c9_s_p9_1,
  135777. NULL,
  135778. &_vq_auxt__44c9_s_p9_1,
  135779. NULL,
  135780. 0
  135781. };
  135782. static long _vq_quantlist__44c9_s_p9_2[] = {
  135783. 24,
  135784. 23,
  135785. 25,
  135786. 22,
  135787. 26,
  135788. 21,
  135789. 27,
  135790. 20,
  135791. 28,
  135792. 19,
  135793. 29,
  135794. 18,
  135795. 30,
  135796. 17,
  135797. 31,
  135798. 16,
  135799. 32,
  135800. 15,
  135801. 33,
  135802. 14,
  135803. 34,
  135804. 13,
  135805. 35,
  135806. 12,
  135807. 36,
  135808. 11,
  135809. 37,
  135810. 10,
  135811. 38,
  135812. 9,
  135813. 39,
  135814. 8,
  135815. 40,
  135816. 7,
  135817. 41,
  135818. 6,
  135819. 42,
  135820. 5,
  135821. 43,
  135822. 4,
  135823. 44,
  135824. 3,
  135825. 45,
  135826. 2,
  135827. 46,
  135828. 1,
  135829. 47,
  135830. 0,
  135831. 48,
  135832. };
  135833. static long _vq_lengthlist__44c9_s_p9_2[] = {
  135834. 2, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  135835. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  135836. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  135837. 7,
  135838. };
  135839. static float _vq_quantthresh__44c9_s_p9_2[] = {
  135840. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  135841. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  135842. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135843. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135844. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  135845. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  135846. };
  135847. static long _vq_quantmap__44c9_s_p9_2[] = {
  135848. 47, 45, 43, 41, 39, 37, 35, 33,
  135849. 31, 29, 27, 25, 23, 21, 19, 17,
  135850. 15, 13, 11, 9, 7, 5, 3, 1,
  135851. 0, 2, 4, 6, 8, 10, 12, 14,
  135852. 16, 18, 20, 22, 24, 26, 28, 30,
  135853. 32, 34, 36, 38, 40, 42, 44, 46,
  135854. 48,
  135855. };
  135856. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_2 = {
  135857. _vq_quantthresh__44c9_s_p9_2,
  135858. _vq_quantmap__44c9_s_p9_2,
  135859. 49,
  135860. 49
  135861. };
  135862. static static_codebook _44c9_s_p9_2 = {
  135863. 1, 49,
  135864. _vq_lengthlist__44c9_s_p9_2,
  135865. 1, -526909440, 1611661312, 6, 0,
  135866. _vq_quantlist__44c9_s_p9_2,
  135867. NULL,
  135868. &_vq_auxt__44c9_s_p9_2,
  135869. NULL,
  135870. 0
  135871. };
  135872. static long _huff_lengthlist__44c9_s_short[] = {
  135873. 5,13,18,16,17,17,19,18,19,19, 5, 7,10,11,12,12,
  135874. 13,16,17,18, 6, 6, 7, 7, 9, 9,10,14,17,19, 8, 7,
  135875. 6, 5, 6, 7, 9,12,19,17, 8, 7, 7, 6, 5, 6, 8,11,
  135876. 15,19, 9, 8, 7, 6, 5, 5, 6, 8,13,15,11,10, 8, 8,
  135877. 7, 5, 4, 4,10,14,12,13,11, 9, 7, 6, 4, 2, 6,12,
  135878. 18,16,16,13, 8, 7, 7, 5, 8,13,16,17,18,15,11, 9,
  135879. 9, 8,10,13,
  135880. };
  135881. static static_codebook _huff_book__44c9_s_short = {
  135882. 2, 100,
  135883. _huff_lengthlist__44c9_s_short,
  135884. 0, 0, 0, 0, 0,
  135885. NULL,
  135886. NULL,
  135887. NULL,
  135888. NULL,
  135889. 0
  135890. };
  135891. static long _huff_lengthlist__44c0_s_long[] = {
  135892. 5, 4, 8, 9, 8, 9,10,12,15, 4, 1, 5, 5, 6, 8,11,
  135893. 12,12, 8, 5, 8, 9, 9,11,13,12,12, 9, 5, 8, 5, 7,
  135894. 9,12,13,13, 8, 6, 8, 7, 7, 9,11,11,11, 9, 7, 9,
  135895. 7, 7, 7, 7,10,12,10,10,11, 9, 8, 7, 7, 9,11,11,
  135896. 12,13,12,11, 9, 8, 9,11,13,16,16,15,15,12,10,11,
  135897. 12,
  135898. };
  135899. static static_codebook _huff_book__44c0_s_long = {
  135900. 2, 81,
  135901. _huff_lengthlist__44c0_s_long,
  135902. 0, 0, 0, 0, 0,
  135903. NULL,
  135904. NULL,
  135905. NULL,
  135906. NULL,
  135907. 0
  135908. };
  135909. static long _vq_quantlist__44c0_s_p1_0[] = {
  135910. 1,
  135911. 0,
  135912. 2,
  135913. };
  135914. static long _vq_lengthlist__44c0_s_p1_0[] = {
  135915. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  135916. 0, 0, 5, 7, 7, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  135921. 0, 0, 0, 7, 9, 9, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135926. 0, 0, 0, 0, 7, 9, 9, 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, 5, 7, 7, 0, 0, 0, 0,
  135961. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  135966. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,11,10, 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, 7, 9, 9, 0, 0,
  135971. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  136007. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  136012. 0, 0, 0, 0, 0, 9, 9,11, 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, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,11,
  136017. 0, 0, 0, 0, 0, 0, 9,11,10, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136325. 0,
  136326. };
  136327. static float _vq_quantthresh__44c0_s_p1_0[] = {
  136328. -0.5, 0.5,
  136329. };
  136330. static long _vq_quantmap__44c0_s_p1_0[] = {
  136331. 1, 0, 2,
  136332. };
  136333. static encode_aux_threshmatch _vq_auxt__44c0_s_p1_0 = {
  136334. _vq_quantthresh__44c0_s_p1_0,
  136335. _vq_quantmap__44c0_s_p1_0,
  136336. 3,
  136337. 3
  136338. };
  136339. static static_codebook _44c0_s_p1_0 = {
  136340. 8, 6561,
  136341. _vq_lengthlist__44c0_s_p1_0,
  136342. 1, -535822336, 1611661312, 2, 0,
  136343. _vq_quantlist__44c0_s_p1_0,
  136344. NULL,
  136345. &_vq_auxt__44c0_s_p1_0,
  136346. NULL,
  136347. 0
  136348. };
  136349. static long _vq_quantlist__44c0_s_p2_0[] = {
  136350. 2,
  136351. 1,
  136352. 3,
  136353. 0,
  136354. 4,
  136355. };
  136356. static long _vq_lengthlist__44c0_s_p2_0[] = {
  136357. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 6, 0, 0,
  136359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136360. 0, 0, 4, 5, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  136362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136363. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  136364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136396. 0,
  136397. };
  136398. static float _vq_quantthresh__44c0_s_p2_0[] = {
  136399. -1.5, -0.5, 0.5, 1.5,
  136400. };
  136401. static long _vq_quantmap__44c0_s_p2_0[] = {
  136402. 3, 1, 0, 2, 4,
  136403. };
  136404. static encode_aux_threshmatch _vq_auxt__44c0_s_p2_0 = {
  136405. _vq_quantthresh__44c0_s_p2_0,
  136406. _vq_quantmap__44c0_s_p2_0,
  136407. 5,
  136408. 5
  136409. };
  136410. static static_codebook _44c0_s_p2_0 = {
  136411. 4, 625,
  136412. _vq_lengthlist__44c0_s_p2_0,
  136413. 1, -533725184, 1611661312, 3, 0,
  136414. _vq_quantlist__44c0_s_p2_0,
  136415. NULL,
  136416. &_vq_auxt__44c0_s_p2_0,
  136417. NULL,
  136418. 0
  136419. };
  136420. static long _vq_quantlist__44c0_s_p3_0[] = {
  136421. 4,
  136422. 3,
  136423. 5,
  136424. 2,
  136425. 6,
  136426. 1,
  136427. 7,
  136428. 0,
  136429. 8,
  136430. };
  136431. static long _vq_lengthlist__44c0_s_p3_0[] = {
  136432. 1, 3, 2, 8, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  136433. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  136434. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  136435. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  136436. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136437. 0,
  136438. };
  136439. static float _vq_quantthresh__44c0_s_p3_0[] = {
  136440. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136441. };
  136442. static long _vq_quantmap__44c0_s_p3_0[] = {
  136443. 7, 5, 3, 1, 0, 2, 4, 6,
  136444. 8,
  136445. };
  136446. static encode_aux_threshmatch _vq_auxt__44c0_s_p3_0 = {
  136447. _vq_quantthresh__44c0_s_p3_0,
  136448. _vq_quantmap__44c0_s_p3_0,
  136449. 9,
  136450. 9
  136451. };
  136452. static static_codebook _44c0_s_p3_0 = {
  136453. 2, 81,
  136454. _vq_lengthlist__44c0_s_p3_0,
  136455. 1, -531628032, 1611661312, 4, 0,
  136456. _vq_quantlist__44c0_s_p3_0,
  136457. NULL,
  136458. &_vq_auxt__44c0_s_p3_0,
  136459. NULL,
  136460. 0
  136461. };
  136462. static long _vq_quantlist__44c0_s_p4_0[] = {
  136463. 4,
  136464. 3,
  136465. 5,
  136466. 2,
  136467. 6,
  136468. 1,
  136469. 7,
  136470. 0,
  136471. 8,
  136472. };
  136473. static long _vq_lengthlist__44c0_s_p4_0[] = {
  136474. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  136475. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  136476. 7, 8, 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0,
  136477. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 9, 8, 8,10,10, 0,
  136478. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  136479. 10,
  136480. };
  136481. static float _vq_quantthresh__44c0_s_p4_0[] = {
  136482. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136483. };
  136484. static long _vq_quantmap__44c0_s_p4_0[] = {
  136485. 7, 5, 3, 1, 0, 2, 4, 6,
  136486. 8,
  136487. };
  136488. static encode_aux_threshmatch _vq_auxt__44c0_s_p4_0 = {
  136489. _vq_quantthresh__44c0_s_p4_0,
  136490. _vq_quantmap__44c0_s_p4_0,
  136491. 9,
  136492. 9
  136493. };
  136494. static static_codebook _44c0_s_p4_0 = {
  136495. 2, 81,
  136496. _vq_lengthlist__44c0_s_p4_0,
  136497. 1, -531628032, 1611661312, 4, 0,
  136498. _vq_quantlist__44c0_s_p4_0,
  136499. NULL,
  136500. &_vq_auxt__44c0_s_p4_0,
  136501. NULL,
  136502. 0
  136503. };
  136504. static long _vq_quantlist__44c0_s_p5_0[] = {
  136505. 8,
  136506. 7,
  136507. 9,
  136508. 6,
  136509. 10,
  136510. 5,
  136511. 11,
  136512. 4,
  136513. 12,
  136514. 3,
  136515. 13,
  136516. 2,
  136517. 14,
  136518. 1,
  136519. 15,
  136520. 0,
  136521. 16,
  136522. };
  136523. static long _vq_lengthlist__44c0_s_p5_0[] = {
  136524. 1, 4, 3, 6, 6, 8, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  136525. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9, 9,10,10,10,
  136526. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  136527. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  136528. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  136529. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  136530. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  136531. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  136532. 10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  136533. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  136534. 10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  136535. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  136536. 10,10,11,11,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  136537. 0, 0, 0,11,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  136538. 0, 0, 0, 0,11,11,12,11,12,12,12,12,13,13, 0, 0,
  136539. 0, 0, 0, 0, 0,11,11,11,12,12,12,12,13,13,13, 0,
  136540. 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,13,14,14,
  136541. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  136542. 14,
  136543. };
  136544. static float _vq_quantthresh__44c0_s_p5_0[] = {
  136545. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136546. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136547. };
  136548. static long _vq_quantmap__44c0_s_p5_0[] = {
  136549. 15, 13, 11, 9, 7, 5, 3, 1,
  136550. 0, 2, 4, 6, 8, 10, 12, 14,
  136551. 16,
  136552. };
  136553. static encode_aux_threshmatch _vq_auxt__44c0_s_p5_0 = {
  136554. _vq_quantthresh__44c0_s_p5_0,
  136555. _vq_quantmap__44c0_s_p5_0,
  136556. 17,
  136557. 17
  136558. };
  136559. static static_codebook _44c0_s_p5_0 = {
  136560. 2, 289,
  136561. _vq_lengthlist__44c0_s_p5_0,
  136562. 1, -529530880, 1611661312, 5, 0,
  136563. _vq_quantlist__44c0_s_p5_0,
  136564. NULL,
  136565. &_vq_auxt__44c0_s_p5_0,
  136566. NULL,
  136567. 0
  136568. };
  136569. static long _vq_quantlist__44c0_s_p6_0[] = {
  136570. 1,
  136571. 0,
  136572. 2,
  136573. };
  136574. static long _vq_lengthlist__44c0_s_p6_0[] = {
  136575. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  136576. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  136577. 11,12,10,11, 6, 9, 9,11,10,11,11,10,10, 6, 9, 9,
  136578. 11,10,11,11,10,10, 7,11,10,12,11,11,11,11,11, 7,
  136579. 9, 9,10,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  136580. 10,
  136581. };
  136582. static float _vq_quantthresh__44c0_s_p6_0[] = {
  136583. -5.5, 5.5,
  136584. };
  136585. static long _vq_quantmap__44c0_s_p6_0[] = {
  136586. 1, 0, 2,
  136587. };
  136588. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_0 = {
  136589. _vq_quantthresh__44c0_s_p6_0,
  136590. _vq_quantmap__44c0_s_p6_0,
  136591. 3,
  136592. 3
  136593. };
  136594. static static_codebook _44c0_s_p6_0 = {
  136595. 4, 81,
  136596. _vq_lengthlist__44c0_s_p6_0,
  136597. 1, -529137664, 1618345984, 2, 0,
  136598. _vq_quantlist__44c0_s_p6_0,
  136599. NULL,
  136600. &_vq_auxt__44c0_s_p6_0,
  136601. NULL,
  136602. 0
  136603. };
  136604. static long _vq_quantlist__44c0_s_p6_1[] = {
  136605. 5,
  136606. 4,
  136607. 6,
  136608. 3,
  136609. 7,
  136610. 2,
  136611. 8,
  136612. 1,
  136613. 9,
  136614. 0,
  136615. 10,
  136616. };
  136617. static long _vq_lengthlist__44c0_s_p6_1[] = {
  136618. 2, 3, 3, 6, 6, 7, 7, 7, 7, 7, 8,10,10,10, 6, 6,
  136619. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  136620. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  136621. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  136622. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  136623. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  136624. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  136625. 10,10,10, 8, 8, 8, 8, 8, 8,
  136626. };
  136627. static float _vq_quantthresh__44c0_s_p6_1[] = {
  136628. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  136629. 3.5, 4.5,
  136630. };
  136631. static long _vq_quantmap__44c0_s_p6_1[] = {
  136632. 9, 7, 5, 3, 1, 0, 2, 4,
  136633. 6, 8, 10,
  136634. };
  136635. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_1 = {
  136636. _vq_quantthresh__44c0_s_p6_1,
  136637. _vq_quantmap__44c0_s_p6_1,
  136638. 11,
  136639. 11
  136640. };
  136641. static static_codebook _44c0_s_p6_1 = {
  136642. 2, 121,
  136643. _vq_lengthlist__44c0_s_p6_1,
  136644. 1, -531365888, 1611661312, 4, 0,
  136645. _vq_quantlist__44c0_s_p6_1,
  136646. NULL,
  136647. &_vq_auxt__44c0_s_p6_1,
  136648. NULL,
  136649. 0
  136650. };
  136651. static long _vq_quantlist__44c0_s_p7_0[] = {
  136652. 6,
  136653. 5,
  136654. 7,
  136655. 4,
  136656. 8,
  136657. 3,
  136658. 9,
  136659. 2,
  136660. 10,
  136661. 1,
  136662. 11,
  136663. 0,
  136664. 12,
  136665. };
  136666. static long _vq_lengthlist__44c0_s_p7_0[] = {
  136667. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  136668. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  136669. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  136670. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  136671. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  136672. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  136673. 10,10,11,11,11,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  136674. 11,11,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  136675. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  136676. 0, 0, 0, 0,11,11,11,11,13,12,13,13, 0, 0, 0, 0,
  136677. 0,12,12,11,11,12,12,13,13,
  136678. };
  136679. static float _vq_quantthresh__44c0_s_p7_0[] = {
  136680. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  136681. 12.5, 17.5, 22.5, 27.5,
  136682. };
  136683. static long _vq_quantmap__44c0_s_p7_0[] = {
  136684. 11, 9, 7, 5, 3, 1, 0, 2,
  136685. 4, 6, 8, 10, 12,
  136686. };
  136687. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_0 = {
  136688. _vq_quantthresh__44c0_s_p7_0,
  136689. _vq_quantmap__44c0_s_p7_0,
  136690. 13,
  136691. 13
  136692. };
  136693. static static_codebook _44c0_s_p7_0 = {
  136694. 2, 169,
  136695. _vq_lengthlist__44c0_s_p7_0,
  136696. 1, -526516224, 1616117760, 4, 0,
  136697. _vq_quantlist__44c0_s_p7_0,
  136698. NULL,
  136699. &_vq_auxt__44c0_s_p7_0,
  136700. NULL,
  136701. 0
  136702. };
  136703. static long _vq_quantlist__44c0_s_p7_1[] = {
  136704. 2,
  136705. 1,
  136706. 3,
  136707. 0,
  136708. 4,
  136709. };
  136710. static long _vq_lengthlist__44c0_s_p7_1[] = {
  136711. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  136712. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  136713. };
  136714. static float _vq_quantthresh__44c0_s_p7_1[] = {
  136715. -1.5, -0.5, 0.5, 1.5,
  136716. };
  136717. static long _vq_quantmap__44c0_s_p7_1[] = {
  136718. 3, 1, 0, 2, 4,
  136719. };
  136720. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_1 = {
  136721. _vq_quantthresh__44c0_s_p7_1,
  136722. _vq_quantmap__44c0_s_p7_1,
  136723. 5,
  136724. 5
  136725. };
  136726. static static_codebook _44c0_s_p7_1 = {
  136727. 2, 25,
  136728. _vq_lengthlist__44c0_s_p7_1,
  136729. 1, -533725184, 1611661312, 3, 0,
  136730. _vq_quantlist__44c0_s_p7_1,
  136731. NULL,
  136732. &_vq_auxt__44c0_s_p7_1,
  136733. NULL,
  136734. 0
  136735. };
  136736. static long _vq_quantlist__44c0_s_p8_0[] = {
  136737. 2,
  136738. 1,
  136739. 3,
  136740. 0,
  136741. 4,
  136742. };
  136743. static long _vq_lengthlist__44c0_s_p8_0[] = {
  136744. 1, 5, 5,10,10, 6, 9, 8,10,10, 6,10, 9,10,10,10,
  136745. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136746. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136747. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136748. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136749. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136750. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136751. 10,10,10,10,10,10,10,10,10,10,10,10,10, 8,10,10,
  136752. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136753. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136754. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136755. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136756. 10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,
  136757. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136758. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136759. 11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,
  136760. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136761. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136762. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136763. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136764. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136765. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136766. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136767. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136768. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136769. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136770. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136771. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136772. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136773. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136774. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136775. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136776. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136777. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136778. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136779. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136780. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136781. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136782. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136783. 11,
  136784. };
  136785. static float _vq_quantthresh__44c0_s_p8_0[] = {
  136786. -331.5, -110.5, 110.5, 331.5,
  136787. };
  136788. static long _vq_quantmap__44c0_s_p8_0[] = {
  136789. 3, 1, 0, 2, 4,
  136790. };
  136791. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_0 = {
  136792. _vq_quantthresh__44c0_s_p8_0,
  136793. _vq_quantmap__44c0_s_p8_0,
  136794. 5,
  136795. 5
  136796. };
  136797. static static_codebook _44c0_s_p8_0 = {
  136798. 4, 625,
  136799. _vq_lengthlist__44c0_s_p8_0,
  136800. 1, -518283264, 1627103232, 3, 0,
  136801. _vq_quantlist__44c0_s_p8_0,
  136802. NULL,
  136803. &_vq_auxt__44c0_s_p8_0,
  136804. NULL,
  136805. 0
  136806. };
  136807. static long _vq_quantlist__44c0_s_p8_1[] = {
  136808. 6,
  136809. 5,
  136810. 7,
  136811. 4,
  136812. 8,
  136813. 3,
  136814. 9,
  136815. 2,
  136816. 10,
  136817. 1,
  136818. 11,
  136819. 0,
  136820. 12,
  136821. };
  136822. static long _vq_lengthlist__44c0_s_p8_1[] = {
  136823. 1, 4, 4, 6, 6, 7, 7, 9, 9,11,12,13,12, 6, 5, 5,
  136824. 7, 7, 8, 8,10, 9,12,12,12,12, 6, 5, 5, 7, 7, 8,
  136825. 8,10, 9,12,11,11,13,16, 7, 7, 8, 8, 9, 9,10,10,
  136826. 12,12,13,12,16, 7, 7, 8, 7, 9, 9,10,10,11,12,12,
  136827. 13,16,10,10, 8, 8,10,10,11,12,12,12,13,13,16,11,
  136828. 10, 8, 7,11,10,11,11,12,11,13,13,16,16,16,10,10,
  136829. 10,10,11,11,13,12,13,13,16,16,16,11, 9,11, 9,15,
  136830. 13,12,13,13,13,16,16,16,15,13,11,11,12,13,12,12,
  136831. 14,13,16,16,16,14,13,11,11,13,12,14,13,13,13,16,
  136832. 16,16,16,16,13,13,13,12,14,13,14,14,16,16,16,16,
  136833. 16,13,13,12,12,14,14,15,13,
  136834. };
  136835. static float _vq_quantthresh__44c0_s_p8_1[] = {
  136836. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  136837. 42.5, 59.5, 76.5, 93.5,
  136838. };
  136839. static long _vq_quantmap__44c0_s_p8_1[] = {
  136840. 11, 9, 7, 5, 3, 1, 0, 2,
  136841. 4, 6, 8, 10, 12,
  136842. };
  136843. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_1 = {
  136844. _vq_quantthresh__44c0_s_p8_1,
  136845. _vq_quantmap__44c0_s_p8_1,
  136846. 13,
  136847. 13
  136848. };
  136849. static static_codebook _44c0_s_p8_1 = {
  136850. 2, 169,
  136851. _vq_lengthlist__44c0_s_p8_1,
  136852. 1, -522616832, 1620115456, 4, 0,
  136853. _vq_quantlist__44c0_s_p8_1,
  136854. NULL,
  136855. &_vq_auxt__44c0_s_p8_1,
  136856. NULL,
  136857. 0
  136858. };
  136859. static long _vq_quantlist__44c0_s_p8_2[] = {
  136860. 8,
  136861. 7,
  136862. 9,
  136863. 6,
  136864. 10,
  136865. 5,
  136866. 11,
  136867. 4,
  136868. 12,
  136869. 3,
  136870. 13,
  136871. 2,
  136872. 14,
  136873. 1,
  136874. 15,
  136875. 0,
  136876. 16,
  136877. };
  136878. static long _vq_lengthlist__44c0_s_p8_2[] = {
  136879. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  136880. 8,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  136881. 9, 9,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  136882. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  136883. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  136884. 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 8, 9, 9,
  136885. 9, 9, 9,10, 9,10,10,10,10, 7, 7, 8, 8, 9, 9, 9,
  136886. 9, 9, 9,10, 9,10,10,10,10,10, 8, 8, 8, 9, 9, 9,
  136887. 9, 9, 9, 9,10,10,10, 9,11,10,10,10,10, 8, 8, 9,
  136888. 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,11,11, 9, 9,
  136889. 9, 9, 9, 9, 9, 9,10, 9, 9,10,11,10,10,11,11, 9,
  136890. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  136891. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,10,11,
  136892. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  136893. 11,11,11,11, 9,10, 9,10, 9, 9, 9, 9,10, 9,10,11,
  136894. 10,11,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9,10,11,
  136895. 11,10,11,11,10,11,10,10,10, 9, 9, 9, 9,10, 9, 9,
  136896. 10,11,10,11,11,11,11,10,11,10,10, 9,10, 9, 9, 9,
  136897. 10,
  136898. };
  136899. static float _vq_quantthresh__44c0_s_p8_2[] = {
  136900. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136901. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136902. };
  136903. static long _vq_quantmap__44c0_s_p8_2[] = {
  136904. 15, 13, 11, 9, 7, 5, 3, 1,
  136905. 0, 2, 4, 6, 8, 10, 12, 14,
  136906. 16,
  136907. };
  136908. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_2 = {
  136909. _vq_quantthresh__44c0_s_p8_2,
  136910. _vq_quantmap__44c0_s_p8_2,
  136911. 17,
  136912. 17
  136913. };
  136914. static static_codebook _44c0_s_p8_2 = {
  136915. 2, 289,
  136916. _vq_lengthlist__44c0_s_p8_2,
  136917. 1, -529530880, 1611661312, 5, 0,
  136918. _vq_quantlist__44c0_s_p8_2,
  136919. NULL,
  136920. &_vq_auxt__44c0_s_p8_2,
  136921. NULL,
  136922. 0
  136923. };
  136924. static long _huff_lengthlist__44c0_s_short[] = {
  136925. 9, 8,12,11,12,13,14,14,16, 6, 1, 5, 6, 6, 9,12,
  136926. 14,17, 9, 4, 5, 9, 7, 9,13,15,16, 8, 5, 8, 6, 8,
  136927. 10,13,17,17, 9, 6, 7, 7, 8, 9,13,15,17,11, 8, 9,
  136928. 9, 9,10,12,16,16,13, 7, 8, 7, 7, 9,12,14,15,13,
  136929. 6, 7, 5, 5, 7,10,13,13,14, 7, 8, 5, 6, 7, 9,10,
  136930. 12,
  136931. };
  136932. static static_codebook _huff_book__44c0_s_short = {
  136933. 2, 81,
  136934. _huff_lengthlist__44c0_s_short,
  136935. 0, 0, 0, 0, 0,
  136936. NULL,
  136937. NULL,
  136938. NULL,
  136939. NULL,
  136940. 0
  136941. };
  136942. static long _huff_lengthlist__44c0_sm_long[] = {
  136943. 5, 4, 9,10, 9,10,11,12,13, 4, 1, 5, 7, 7, 9,11,
  136944. 12,14, 8, 5, 7, 9, 8,10,13,13,13,10, 7, 9, 4, 6,
  136945. 7,10,12,14, 9, 6, 7, 6, 6, 7,10,12,12, 9, 8, 9,
  136946. 7, 6, 7, 8,11,12,11,11,11, 9, 8, 7, 8,10,12,12,
  136947. 13,14,12,11, 9, 9, 9,12,12,17,17,15,16,12,10,11,
  136948. 13,
  136949. };
  136950. static static_codebook _huff_book__44c0_sm_long = {
  136951. 2, 81,
  136952. _huff_lengthlist__44c0_sm_long,
  136953. 0, 0, 0, 0, 0,
  136954. NULL,
  136955. NULL,
  136956. NULL,
  136957. NULL,
  136958. 0
  136959. };
  136960. static long _vq_quantlist__44c0_sm_p1_0[] = {
  136961. 1,
  136962. 0,
  136963. 2,
  136964. };
  136965. static long _vq_lengthlist__44c0_sm_p1_0[] = {
  136966. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  136967. 0, 0, 5, 7, 7, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  136972. 0, 0, 0, 7, 8, 9, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  136977. 0, 0, 0, 0, 7, 9, 9, 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, 5, 8, 7, 0, 0, 0, 0,
  137012. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  137017. 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  137022. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  137058. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  137063. 0, 0, 0, 0, 0, 9, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  137068. 0, 0, 0, 0, 0, 0, 9,10,10, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137376. 0,
  137377. };
  137378. static float _vq_quantthresh__44c0_sm_p1_0[] = {
  137379. -0.5, 0.5,
  137380. };
  137381. static long _vq_quantmap__44c0_sm_p1_0[] = {
  137382. 1, 0, 2,
  137383. };
  137384. static encode_aux_threshmatch _vq_auxt__44c0_sm_p1_0 = {
  137385. _vq_quantthresh__44c0_sm_p1_0,
  137386. _vq_quantmap__44c0_sm_p1_0,
  137387. 3,
  137388. 3
  137389. };
  137390. static static_codebook _44c0_sm_p1_0 = {
  137391. 8, 6561,
  137392. _vq_lengthlist__44c0_sm_p1_0,
  137393. 1, -535822336, 1611661312, 2, 0,
  137394. _vq_quantlist__44c0_sm_p1_0,
  137395. NULL,
  137396. &_vq_auxt__44c0_sm_p1_0,
  137397. NULL,
  137398. 0
  137399. };
  137400. static long _vq_quantlist__44c0_sm_p2_0[] = {
  137401. 2,
  137402. 1,
  137403. 3,
  137404. 0,
  137405. 4,
  137406. };
  137407. static long _vq_lengthlist__44c0_sm_p2_0[] = {
  137408. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  137410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137411. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  137413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137414. 0, 0, 0, 0, 7, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  137415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137447. 0,
  137448. };
  137449. static float _vq_quantthresh__44c0_sm_p2_0[] = {
  137450. -1.5, -0.5, 0.5, 1.5,
  137451. };
  137452. static long _vq_quantmap__44c0_sm_p2_0[] = {
  137453. 3, 1, 0, 2, 4,
  137454. };
  137455. static encode_aux_threshmatch _vq_auxt__44c0_sm_p2_0 = {
  137456. _vq_quantthresh__44c0_sm_p2_0,
  137457. _vq_quantmap__44c0_sm_p2_0,
  137458. 5,
  137459. 5
  137460. };
  137461. static static_codebook _44c0_sm_p2_0 = {
  137462. 4, 625,
  137463. _vq_lengthlist__44c0_sm_p2_0,
  137464. 1, -533725184, 1611661312, 3, 0,
  137465. _vq_quantlist__44c0_sm_p2_0,
  137466. NULL,
  137467. &_vq_auxt__44c0_sm_p2_0,
  137468. NULL,
  137469. 0
  137470. };
  137471. static long _vq_quantlist__44c0_sm_p3_0[] = {
  137472. 4,
  137473. 3,
  137474. 5,
  137475. 2,
  137476. 6,
  137477. 1,
  137478. 7,
  137479. 0,
  137480. 8,
  137481. };
  137482. static long _vq_lengthlist__44c0_sm_p3_0[] = {
  137483. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 4, 7, 7, 0, 0,
  137484. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  137485. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  137486. 9,10, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  137487. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137488. 0,
  137489. };
  137490. static float _vq_quantthresh__44c0_sm_p3_0[] = {
  137491. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137492. };
  137493. static long _vq_quantmap__44c0_sm_p3_0[] = {
  137494. 7, 5, 3, 1, 0, 2, 4, 6,
  137495. 8,
  137496. };
  137497. static encode_aux_threshmatch _vq_auxt__44c0_sm_p3_0 = {
  137498. _vq_quantthresh__44c0_sm_p3_0,
  137499. _vq_quantmap__44c0_sm_p3_0,
  137500. 9,
  137501. 9
  137502. };
  137503. static static_codebook _44c0_sm_p3_0 = {
  137504. 2, 81,
  137505. _vq_lengthlist__44c0_sm_p3_0,
  137506. 1, -531628032, 1611661312, 4, 0,
  137507. _vq_quantlist__44c0_sm_p3_0,
  137508. NULL,
  137509. &_vq_auxt__44c0_sm_p3_0,
  137510. NULL,
  137511. 0
  137512. };
  137513. static long _vq_quantlist__44c0_sm_p4_0[] = {
  137514. 4,
  137515. 3,
  137516. 5,
  137517. 2,
  137518. 6,
  137519. 1,
  137520. 7,
  137521. 0,
  137522. 8,
  137523. };
  137524. static long _vq_lengthlist__44c0_sm_p4_0[] = {
  137525. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  137526. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  137527. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  137528. 9, 9, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  137529. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  137530. 11,
  137531. };
  137532. static float _vq_quantthresh__44c0_sm_p4_0[] = {
  137533. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137534. };
  137535. static long _vq_quantmap__44c0_sm_p4_0[] = {
  137536. 7, 5, 3, 1, 0, 2, 4, 6,
  137537. 8,
  137538. };
  137539. static encode_aux_threshmatch _vq_auxt__44c0_sm_p4_0 = {
  137540. _vq_quantthresh__44c0_sm_p4_0,
  137541. _vq_quantmap__44c0_sm_p4_0,
  137542. 9,
  137543. 9
  137544. };
  137545. static static_codebook _44c0_sm_p4_0 = {
  137546. 2, 81,
  137547. _vq_lengthlist__44c0_sm_p4_0,
  137548. 1, -531628032, 1611661312, 4, 0,
  137549. _vq_quantlist__44c0_sm_p4_0,
  137550. NULL,
  137551. &_vq_auxt__44c0_sm_p4_0,
  137552. NULL,
  137553. 0
  137554. };
  137555. static long _vq_quantlist__44c0_sm_p5_0[] = {
  137556. 8,
  137557. 7,
  137558. 9,
  137559. 6,
  137560. 10,
  137561. 5,
  137562. 11,
  137563. 4,
  137564. 12,
  137565. 3,
  137566. 13,
  137567. 2,
  137568. 14,
  137569. 1,
  137570. 15,
  137571. 0,
  137572. 16,
  137573. };
  137574. static long _vq_lengthlist__44c0_sm_p5_0[] = {
  137575. 1, 4, 4, 6, 6, 8, 8, 8, 8, 8, 8, 9, 9,10,10,11,
  137576. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  137577. 11,11, 0, 5, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  137578. 11,11,11, 0, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  137579. 11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,
  137580. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  137581. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  137582. 10,11,11,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  137583. 10,10,11,11,12,12,12,13, 0, 0, 0, 0, 0, 9, 9,10,
  137584. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  137585. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  137586. 9,10,10,11,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  137587. 10,10,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0,
  137588. 0, 0, 0,10,10,11,11,12,12,12,13,13,13, 0, 0, 0,
  137589. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  137590. 0, 0, 0, 0, 0,11,11,12,11,12,12,13,13,13,13, 0,
  137591. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  137592. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  137593. 14,
  137594. };
  137595. static float _vq_quantthresh__44c0_sm_p5_0[] = {
  137596. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137597. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137598. };
  137599. static long _vq_quantmap__44c0_sm_p5_0[] = {
  137600. 15, 13, 11, 9, 7, 5, 3, 1,
  137601. 0, 2, 4, 6, 8, 10, 12, 14,
  137602. 16,
  137603. };
  137604. static encode_aux_threshmatch _vq_auxt__44c0_sm_p5_0 = {
  137605. _vq_quantthresh__44c0_sm_p5_0,
  137606. _vq_quantmap__44c0_sm_p5_0,
  137607. 17,
  137608. 17
  137609. };
  137610. static static_codebook _44c0_sm_p5_0 = {
  137611. 2, 289,
  137612. _vq_lengthlist__44c0_sm_p5_0,
  137613. 1, -529530880, 1611661312, 5, 0,
  137614. _vq_quantlist__44c0_sm_p5_0,
  137615. NULL,
  137616. &_vq_auxt__44c0_sm_p5_0,
  137617. NULL,
  137618. 0
  137619. };
  137620. static long _vq_quantlist__44c0_sm_p6_0[] = {
  137621. 1,
  137622. 0,
  137623. 2,
  137624. };
  137625. static long _vq_lengthlist__44c0_sm_p6_0[] = {
  137626. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  137627. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  137628. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  137629. 11,10,11,11,10,10, 7,11,10,11,11,11,11,11,11, 6,
  137630. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  137631. 11,
  137632. };
  137633. static float _vq_quantthresh__44c0_sm_p6_0[] = {
  137634. -5.5, 5.5,
  137635. };
  137636. static long _vq_quantmap__44c0_sm_p6_0[] = {
  137637. 1, 0, 2,
  137638. };
  137639. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_0 = {
  137640. _vq_quantthresh__44c0_sm_p6_0,
  137641. _vq_quantmap__44c0_sm_p6_0,
  137642. 3,
  137643. 3
  137644. };
  137645. static static_codebook _44c0_sm_p6_0 = {
  137646. 4, 81,
  137647. _vq_lengthlist__44c0_sm_p6_0,
  137648. 1, -529137664, 1618345984, 2, 0,
  137649. _vq_quantlist__44c0_sm_p6_0,
  137650. NULL,
  137651. &_vq_auxt__44c0_sm_p6_0,
  137652. NULL,
  137653. 0
  137654. };
  137655. static long _vq_quantlist__44c0_sm_p6_1[] = {
  137656. 5,
  137657. 4,
  137658. 6,
  137659. 3,
  137660. 7,
  137661. 2,
  137662. 8,
  137663. 1,
  137664. 9,
  137665. 0,
  137666. 10,
  137667. };
  137668. static long _vq_lengthlist__44c0_sm_p6_1[] = {
  137669. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 8, 9, 5, 5, 6, 6,
  137670. 7, 7, 8, 8, 8, 8, 9, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  137671. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  137672. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  137673. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  137674. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  137675. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  137676. 10,10,10, 8, 8, 8, 8, 8, 8,
  137677. };
  137678. static float _vq_quantthresh__44c0_sm_p6_1[] = {
  137679. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  137680. 3.5, 4.5,
  137681. };
  137682. static long _vq_quantmap__44c0_sm_p6_1[] = {
  137683. 9, 7, 5, 3, 1, 0, 2, 4,
  137684. 6, 8, 10,
  137685. };
  137686. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_1 = {
  137687. _vq_quantthresh__44c0_sm_p6_1,
  137688. _vq_quantmap__44c0_sm_p6_1,
  137689. 11,
  137690. 11
  137691. };
  137692. static static_codebook _44c0_sm_p6_1 = {
  137693. 2, 121,
  137694. _vq_lengthlist__44c0_sm_p6_1,
  137695. 1, -531365888, 1611661312, 4, 0,
  137696. _vq_quantlist__44c0_sm_p6_1,
  137697. NULL,
  137698. &_vq_auxt__44c0_sm_p6_1,
  137699. NULL,
  137700. 0
  137701. };
  137702. static long _vq_quantlist__44c0_sm_p7_0[] = {
  137703. 6,
  137704. 5,
  137705. 7,
  137706. 4,
  137707. 8,
  137708. 3,
  137709. 9,
  137710. 2,
  137711. 10,
  137712. 1,
  137713. 11,
  137714. 0,
  137715. 12,
  137716. };
  137717. static long _vq_lengthlist__44c0_sm_p7_0[] = {
  137718. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  137719. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  137720. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  137721. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  137722. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  137723. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0, 9,10,
  137724. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  137725. 11,12,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  137726. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  137727. 0, 0, 0, 0,11,12,11,11,13,12,13,13, 0, 0, 0, 0,
  137728. 0,12,12,11,11,13,12,14,14,
  137729. };
  137730. static float _vq_quantthresh__44c0_sm_p7_0[] = {
  137731. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  137732. 12.5, 17.5, 22.5, 27.5,
  137733. };
  137734. static long _vq_quantmap__44c0_sm_p7_0[] = {
  137735. 11, 9, 7, 5, 3, 1, 0, 2,
  137736. 4, 6, 8, 10, 12,
  137737. };
  137738. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_0 = {
  137739. _vq_quantthresh__44c0_sm_p7_0,
  137740. _vq_quantmap__44c0_sm_p7_0,
  137741. 13,
  137742. 13
  137743. };
  137744. static static_codebook _44c0_sm_p7_0 = {
  137745. 2, 169,
  137746. _vq_lengthlist__44c0_sm_p7_0,
  137747. 1, -526516224, 1616117760, 4, 0,
  137748. _vq_quantlist__44c0_sm_p7_0,
  137749. NULL,
  137750. &_vq_auxt__44c0_sm_p7_0,
  137751. NULL,
  137752. 0
  137753. };
  137754. static long _vq_quantlist__44c0_sm_p7_1[] = {
  137755. 2,
  137756. 1,
  137757. 3,
  137758. 0,
  137759. 4,
  137760. };
  137761. static long _vq_lengthlist__44c0_sm_p7_1[] = {
  137762. 2, 4, 4, 4, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  137763. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  137764. };
  137765. static float _vq_quantthresh__44c0_sm_p7_1[] = {
  137766. -1.5, -0.5, 0.5, 1.5,
  137767. };
  137768. static long _vq_quantmap__44c0_sm_p7_1[] = {
  137769. 3, 1, 0, 2, 4,
  137770. };
  137771. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_1 = {
  137772. _vq_quantthresh__44c0_sm_p7_1,
  137773. _vq_quantmap__44c0_sm_p7_1,
  137774. 5,
  137775. 5
  137776. };
  137777. static static_codebook _44c0_sm_p7_1 = {
  137778. 2, 25,
  137779. _vq_lengthlist__44c0_sm_p7_1,
  137780. 1, -533725184, 1611661312, 3, 0,
  137781. _vq_quantlist__44c0_sm_p7_1,
  137782. NULL,
  137783. &_vq_auxt__44c0_sm_p7_1,
  137784. NULL,
  137785. 0
  137786. };
  137787. static long _vq_quantlist__44c0_sm_p8_0[] = {
  137788. 4,
  137789. 3,
  137790. 5,
  137791. 2,
  137792. 6,
  137793. 1,
  137794. 7,
  137795. 0,
  137796. 8,
  137797. };
  137798. static long _vq_lengthlist__44c0_sm_p8_0[] = {
  137799. 1, 3, 3,11,11,11,11,11,11, 3, 7, 6,11,11,11,11,
  137800. 11,11, 4, 8, 7,11,11,11,11,11,11,11,11,11,11,11,
  137801. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137802. 11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137803. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137804. 12,
  137805. };
  137806. static float _vq_quantthresh__44c0_sm_p8_0[] = {
  137807. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  137808. };
  137809. static long _vq_quantmap__44c0_sm_p8_0[] = {
  137810. 7, 5, 3, 1, 0, 2, 4, 6,
  137811. 8,
  137812. };
  137813. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_0 = {
  137814. _vq_quantthresh__44c0_sm_p8_0,
  137815. _vq_quantmap__44c0_sm_p8_0,
  137816. 9,
  137817. 9
  137818. };
  137819. static static_codebook _44c0_sm_p8_0 = {
  137820. 2, 81,
  137821. _vq_lengthlist__44c0_sm_p8_0,
  137822. 1, -516186112, 1627103232, 4, 0,
  137823. _vq_quantlist__44c0_sm_p8_0,
  137824. NULL,
  137825. &_vq_auxt__44c0_sm_p8_0,
  137826. NULL,
  137827. 0
  137828. };
  137829. static long _vq_quantlist__44c0_sm_p8_1[] = {
  137830. 6,
  137831. 5,
  137832. 7,
  137833. 4,
  137834. 8,
  137835. 3,
  137836. 9,
  137837. 2,
  137838. 10,
  137839. 1,
  137840. 11,
  137841. 0,
  137842. 12,
  137843. };
  137844. static long _vq_lengthlist__44c0_sm_p8_1[] = {
  137845. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  137846. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  137847. 8,10,10,12,11,12,12,17, 7, 7, 8, 8, 9, 9,10,10,
  137848. 12,12,13,13,18, 7, 7, 8, 7, 9, 9,10,10,12,12,12,
  137849. 13,19,10,10, 8, 8,10,10,11,11,12,12,13,14,19,11,
  137850. 10, 8, 7,10,10,11,11,12,12,13,12,19,19,19,10,10,
  137851. 10,10,11,11,12,12,13,13,19,19,19,11, 9,11, 9,14,
  137852. 12,13,12,13,13,19,20,18,13,14,11,11,12,12,13,13,
  137853. 14,13,20,20,20,15,13,11,10,13,11,13,13,14,13,20,
  137854. 20,20,20,20,13,14,12,12,13,13,13,13,20,20,20,20,
  137855. 20,13,13,12,12,16,13,15,13,
  137856. };
  137857. static float _vq_quantthresh__44c0_sm_p8_1[] = {
  137858. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  137859. 42.5, 59.5, 76.5, 93.5,
  137860. };
  137861. static long _vq_quantmap__44c0_sm_p8_1[] = {
  137862. 11, 9, 7, 5, 3, 1, 0, 2,
  137863. 4, 6, 8, 10, 12,
  137864. };
  137865. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_1 = {
  137866. _vq_quantthresh__44c0_sm_p8_1,
  137867. _vq_quantmap__44c0_sm_p8_1,
  137868. 13,
  137869. 13
  137870. };
  137871. static static_codebook _44c0_sm_p8_1 = {
  137872. 2, 169,
  137873. _vq_lengthlist__44c0_sm_p8_1,
  137874. 1, -522616832, 1620115456, 4, 0,
  137875. _vq_quantlist__44c0_sm_p8_1,
  137876. NULL,
  137877. &_vq_auxt__44c0_sm_p8_1,
  137878. NULL,
  137879. 0
  137880. };
  137881. static long _vq_quantlist__44c0_sm_p8_2[] = {
  137882. 8,
  137883. 7,
  137884. 9,
  137885. 6,
  137886. 10,
  137887. 5,
  137888. 11,
  137889. 4,
  137890. 12,
  137891. 3,
  137892. 13,
  137893. 2,
  137894. 14,
  137895. 1,
  137896. 15,
  137897. 0,
  137898. 16,
  137899. };
  137900. static long _vq_lengthlist__44c0_sm_p8_2[] = {
  137901. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  137902. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  137903. 9, 9,10, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  137904. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  137905. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  137906. 9,10, 9, 9,10,10,10,11, 8, 8, 8, 8, 9, 9, 9, 9,
  137907. 9, 9, 9,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  137908. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  137909. 9, 9, 9, 9, 9, 9,10,10,10,10,10,11,11, 8, 8, 9,
  137910. 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,11,11,11, 9, 9,
  137911. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,10,11,11, 9,
  137912. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  137913. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,11,11,
  137914. 11,11,11, 9, 9,10, 9, 9, 9, 9, 9, 9, 9,10,11,10,
  137915. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  137916. 11,11,11,11,11, 9,10, 9, 9, 9, 9, 9, 9, 9, 9,11,
  137917. 11,10,11,11,11,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  137918. 10,11,10,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  137919. 9,
  137920. };
  137921. static float _vq_quantthresh__44c0_sm_p8_2[] = {
  137922. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137923. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137924. };
  137925. static long _vq_quantmap__44c0_sm_p8_2[] = {
  137926. 15, 13, 11, 9, 7, 5, 3, 1,
  137927. 0, 2, 4, 6, 8, 10, 12, 14,
  137928. 16,
  137929. };
  137930. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_2 = {
  137931. _vq_quantthresh__44c0_sm_p8_2,
  137932. _vq_quantmap__44c0_sm_p8_2,
  137933. 17,
  137934. 17
  137935. };
  137936. static static_codebook _44c0_sm_p8_2 = {
  137937. 2, 289,
  137938. _vq_lengthlist__44c0_sm_p8_2,
  137939. 1, -529530880, 1611661312, 5, 0,
  137940. _vq_quantlist__44c0_sm_p8_2,
  137941. NULL,
  137942. &_vq_auxt__44c0_sm_p8_2,
  137943. NULL,
  137944. 0
  137945. };
  137946. static long _huff_lengthlist__44c0_sm_short[] = {
  137947. 6, 6,12,13,13,14,16,17,17, 4, 2, 5, 8, 7, 9,12,
  137948. 15,15, 9, 4, 5, 9, 7, 9,12,16,18,11, 6, 7, 4, 6,
  137949. 8,11,14,18,10, 5, 6, 5, 5, 7,10,14,17,10, 5, 7,
  137950. 7, 6, 7,10,13,16,11, 5, 7, 7, 7, 8,10,12,15,13,
  137951. 6, 7, 5, 5, 7, 9,12,13,16, 8, 9, 6, 6, 7, 9,10,
  137952. 12,
  137953. };
  137954. static static_codebook _huff_book__44c0_sm_short = {
  137955. 2, 81,
  137956. _huff_lengthlist__44c0_sm_short,
  137957. 0, 0, 0, 0, 0,
  137958. NULL,
  137959. NULL,
  137960. NULL,
  137961. NULL,
  137962. 0
  137963. };
  137964. static long _huff_lengthlist__44c1_s_long[] = {
  137965. 5, 5, 9,10, 9, 9,10,11,12, 5, 1, 5, 6, 6, 7,10,
  137966. 12,14, 9, 5, 6, 8, 8,10,12,14,14,10, 5, 8, 5, 6,
  137967. 8,11,13,14, 9, 5, 7, 6, 6, 8,10,12,11, 9, 7, 9,
  137968. 7, 6, 6, 7,10,10,10, 9,12, 9, 8, 7, 7,10,12,11,
  137969. 11,13,12,10, 9, 8, 9,11,11,14,15,15,13,11, 9, 9,
  137970. 11,
  137971. };
  137972. static static_codebook _huff_book__44c1_s_long = {
  137973. 2, 81,
  137974. _huff_lengthlist__44c1_s_long,
  137975. 0, 0, 0, 0, 0,
  137976. NULL,
  137977. NULL,
  137978. NULL,
  137979. NULL,
  137980. 0
  137981. };
  137982. static long _vq_quantlist__44c1_s_p1_0[] = {
  137983. 1,
  137984. 0,
  137985. 2,
  137986. };
  137987. static long _vq_lengthlist__44c1_s_p1_0[] = {
  137988. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 6, 0, 0, 0, 0,
  137989. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137993. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  137994. 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137998. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  137999. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  138034. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  138035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  138039. 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  138040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  138044. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  138045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138079. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  138080. 0, 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138084. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8,10, 9, 0,
  138085. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  138086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138089. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  138090. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  138091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138398. 0,
  138399. };
  138400. static float _vq_quantthresh__44c1_s_p1_0[] = {
  138401. -0.5, 0.5,
  138402. };
  138403. static long _vq_quantmap__44c1_s_p1_0[] = {
  138404. 1, 0, 2,
  138405. };
  138406. static encode_aux_threshmatch _vq_auxt__44c1_s_p1_0 = {
  138407. _vq_quantthresh__44c1_s_p1_0,
  138408. _vq_quantmap__44c1_s_p1_0,
  138409. 3,
  138410. 3
  138411. };
  138412. static static_codebook _44c1_s_p1_0 = {
  138413. 8, 6561,
  138414. _vq_lengthlist__44c1_s_p1_0,
  138415. 1, -535822336, 1611661312, 2, 0,
  138416. _vq_quantlist__44c1_s_p1_0,
  138417. NULL,
  138418. &_vq_auxt__44c1_s_p1_0,
  138419. NULL,
  138420. 0
  138421. };
  138422. static long _vq_quantlist__44c1_s_p2_0[] = {
  138423. 2,
  138424. 1,
  138425. 3,
  138426. 0,
  138427. 4,
  138428. };
  138429. static long _vq_lengthlist__44c1_s_p2_0[] = {
  138430. 2, 3, 4, 6, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  138432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138433. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  138435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138436. 0, 0, 0, 0, 6, 6, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  138437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138469. 0,
  138470. };
  138471. static float _vq_quantthresh__44c1_s_p2_0[] = {
  138472. -1.5, -0.5, 0.5, 1.5,
  138473. };
  138474. static long _vq_quantmap__44c1_s_p2_0[] = {
  138475. 3, 1, 0, 2, 4,
  138476. };
  138477. static encode_aux_threshmatch _vq_auxt__44c1_s_p2_0 = {
  138478. _vq_quantthresh__44c1_s_p2_0,
  138479. _vq_quantmap__44c1_s_p2_0,
  138480. 5,
  138481. 5
  138482. };
  138483. static static_codebook _44c1_s_p2_0 = {
  138484. 4, 625,
  138485. _vq_lengthlist__44c1_s_p2_0,
  138486. 1, -533725184, 1611661312, 3, 0,
  138487. _vq_quantlist__44c1_s_p2_0,
  138488. NULL,
  138489. &_vq_auxt__44c1_s_p2_0,
  138490. NULL,
  138491. 0
  138492. };
  138493. static long _vq_quantlist__44c1_s_p3_0[] = {
  138494. 4,
  138495. 3,
  138496. 5,
  138497. 2,
  138498. 6,
  138499. 1,
  138500. 7,
  138501. 0,
  138502. 8,
  138503. };
  138504. static long _vq_lengthlist__44c1_s_p3_0[] = {
  138505. 1, 3, 2, 7, 7, 0, 0, 0, 0, 0,13,13, 6, 6, 0, 0,
  138506. 0, 0, 0,12, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  138507. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  138508. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  138509. 0, 0,11,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138510. 0,
  138511. };
  138512. static float _vq_quantthresh__44c1_s_p3_0[] = {
  138513. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138514. };
  138515. static long _vq_quantmap__44c1_s_p3_0[] = {
  138516. 7, 5, 3, 1, 0, 2, 4, 6,
  138517. 8,
  138518. };
  138519. static encode_aux_threshmatch _vq_auxt__44c1_s_p3_0 = {
  138520. _vq_quantthresh__44c1_s_p3_0,
  138521. _vq_quantmap__44c1_s_p3_0,
  138522. 9,
  138523. 9
  138524. };
  138525. static static_codebook _44c1_s_p3_0 = {
  138526. 2, 81,
  138527. _vq_lengthlist__44c1_s_p3_0,
  138528. 1, -531628032, 1611661312, 4, 0,
  138529. _vq_quantlist__44c1_s_p3_0,
  138530. NULL,
  138531. &_vq_auxt__44c1_s_p3_0,
  138532. NULL,
  138533. 0
  138534. };
  138535. static long _vq_quantlist__44c1_s_p4_0[] = {
  138536. 4,
  138537. 3,
  138538. 5,
  138539. 2,
  138540. 6,
  138541. 1,
  138542. 7,
  138543. 0,
  138544. 8,
  138545. };
  138546. static long _vq_lengthlist__44c1_s_p4_0[] = {
  138547. 1, 3, 3, 6, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  138548. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  138549. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  138550. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  138551. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  138552. 11,
  138553. };
  138554. static float _vq_quantthresh__44c1_s_p4_0[] = {
  138555. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138556. };
  138557. static long _vq_quantmap__44c1_s_p4_0[] = {
  138558. 7, 5, 3, 1, 0, 2, 4, 6,
  138559. 8,
  138560. };
  138561. static encode_aux_threshmatch _vq_auxt__44c1_s_p4_0 = {
  138562. _vq_quantthresh__44c1_s_p4_0,
  138563. _vq_quantmap__44c1_s_p4_0,
  138564. 9,
  138565. 9
  138566. };
  138567. static static_codebook _44c1_s_p4_0 = {
  138568. 2, 81,
  138569. _vq_lengthlist__44c1_s_p4_0,
  138570. 1, -531628032, 1611661312, 4, 0,
  138571. _vq_quantlist__44c1_s_p4_0,
  138572. NULL,
  138573. &_vq_auxt__44c1_s_p4_0,
  138574. NULL,
  138575. 0
  138576. };
  138577. static long _vq_quantlist__44c1_s_p5_0[] = {
  138578. 8,
  138579. 7,
  138580. 9,
  138581. 6,
  138582. 10,
  138583. 5,
  138584. 11,
  138585. 4,
  138586. 12,
  138587. 3,
  138588. 13,
  138589. 2,
  138590. 14,
  138591. 1,
  138592. 15,
  138593. 0,
  138594. 16,
  138595. };
  138596. static long _vq_lengthlist__44c1_s_p5_0[] = {
  138597. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  138598. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  138599. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  138600. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  138601. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  138602. 10,11,11,12,11, 0, 0, 0, 8, 8, 9, 9, 9,10,10,10,
  138603. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10, 9,10,
  138604. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  138605. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  138606. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  138607. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  138608. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  138609. 10,10,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  138610. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  138611. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13, 0, 0,
  138612. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  138613. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,14,14,
  138614. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  138615. 14,
  138616. };
  138617. static float _vq_quantthresh__44c1_s_p5_0[] = {
  138618. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138619. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138620. };
  138621. static long _vq_quantmap__44c1_s_p5_0[] = {
  138622. 15, 13, 11, 9, 7, 5, 3, 1,
  138623. 0, 2, 4, 6, 8, 10, 12, 14,
  138624. 16,
  138625. };
  138626. static encode_aux_threshmatch _vq_auxt__44c1_s_p5_0 = {
  138627. _vq_quantthresh__44c1_s_p5_0,
  138628. _vq_quantmap__44c1_s_p5_0,
  138629. 17,
  138630. 17
  138631. };
  138632. static static_codebook _44c1_s_p5_0 = {
  138633. 2, 289,
  138634. _vq_lengthlist__44c1_s_p5_0,
  138635. 1, -529530880, 1611661312, 5, 0,
  138636. _vq_quantlist__44c1_s_p5_0,
  138637. NULL,
  138638. &_vq_auxt__44c1_s_p5_0,
  138639. NULL,
  138640. 0
  138641. };
  138642. static long _vq_quantlist__44c1_s_p6_0[] = {
  138643. 1,
  138644. 0,
  138645. 2,
  138646. };
  138647. static long _vq_lengthlist__44c1_s_p6_0[] = {
  138648. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  138649. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 6,10,10,11,11,
  138650. 11,11,10,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  138651. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 7,
  138652. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,12,10,
  138653. 11,
  138654. };
  138655. static float _vq_quantthresh__44c1_s_p6_0[] = {
  138656. -5.5, 5.5,
  138657. };
  138658. static long _vq_quantmap__44c1_s_p6_0[] = {
  138659. 1, 0, 2,
  138660. };
  138661. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_0 = {
  138662. _vq_quantthresh__44c1_s_p6_0,
  138663. _vq_quantmap__44c1_s_p6_0,
  138664. 3,
  138665. 3
  138666. };
  138667. static static_codebook _44c1_s_p6_0 = {
  138668. 4, 81,
  138669. _vq_lengthlist__44c1_s_p6_0,
  138670. 1, -529137664, 1618345984, 2, 0,
  138671. _vq_quantlist__44c1_s_p6_0,
  138672. NULL,
  138673. &_vq_auxt__44c1_s_p6_0,
  138674. NULL,
  138675. 0
  138676. };
  138677. static long _vq_quantlist__44c1_s_p6_1[] = {
  138678. 5,
  138679. 4,
  138680. 6,
  138681. 3,
  138682. 7,
  138683. 2,
  138684. 8,
  138685. 1,
  138686. 9,
  138687. 0,
  138688. 10,
  138689. };
  138690. static long _vq_lengthlist__44c1_s_p6_1[] = {
  138691. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  138692. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  138693. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  138694. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  138695. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  138696. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  138697. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  138698. 10,10,10, 8, 8, 8, 8, 8, 8,
  138699. };
  138700. static float _vq_quantthresh__44c1_s_p6_1[] = {
  138701. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  138702. 3.5, 4.5,
  138703. };
  138704. static long _vq_quantmap__44c1_s_p6_1[] = {
  138705. 9, 7, 5, 3, 1, 0, 2, 4,
  138706. 6, 8, 10,
  138707. };
  138708. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_1 = {
  138709. _vq_quantthresh__44c1_s_p6_1,
  138710. _vq_quantmap__44c1_s_p6_1,
  138711. 11,
  138712. 11
  138713. };
  138714. static static_codebook _44c1_s_p6_1 = {
  138715. 2, 121,
  138716. _vq_lengthlist__44c1_s_p6_1,
  138717. 1, -531365888, 1611661312, 4, 0,
  138718. _vq_quantlist__44c1_s_p6_1,
  138719. NULL,
  138720. &_vq_auxt__44c1_s_p6_1,
  138721. NULL,
  138722. 0
  138723. };
  138724. static long _vq_quantlist__44c1_s_p7_0[] = {
  138725. 6,
  138726. 5,
  138727. 7,
  138728. 4,
  138729. 8,
  138730. 3,
  138731. 9,
  138732. 2,
  138733. 10,
  138734. 1,
  138735. 11,
  138736. 0,
  138737. 12,
  138738. };
  138739. static long _vq_lengthlist__44c1_s_p7_0[] = {
  138740. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 9, 7, 5, 6,
  138741. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  138742. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  138743. 10,10,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  138744. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,11, 0,13,
  138745. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  138746. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10,10, 9,11,
  138747. 11,12,11,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  138748. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  138749. 0, 0, 0, 0,11,12,11,11,12,12,14,13, 0, 0, 0, 0,
  138750. 0,12,11,11,11,13,10,14,13,
  138751. };
  138752. static float _vq_quantthresh__44c1_s_p7_0[] = {
  138753. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  138754. 12.5, 17.5, 22.5, 27.5,
  138755. };
  138756. static long _vq_quantmap__44c1_s_p7_0[] = {
  138757. 11, 9, 7, 5, 3, 1, 0, 2,
  138758. 4, 6, 8, 10, 12,
  138759. };
  138760. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_0 = {
  138761. _vq_quantthresh__44c1_s_p7_0,
  138762. _vq_quantmap__44c1_s_p7_0,
  138763. 13,
  138764. 13
  138765. };
  138766. static static_codebook _44c1_s_p7_0 = {
  138767. 2, 169,
  138768. _vq_lengthlist__44c1_s_p7_0,
  138769. 1, -526516224, 1616117760, 4, 0,
  138770. _vq_quantlist__44c1_s_p7_0,
  138771. NULL,
  138772. &_vq_auxt__44c1_s_p7_0,
  138773. NULL,
  138774. 0
  138775. };
  138776. static long _vq_quantlist__44c1_s_p7_1[] = {
  138777. 2,
  138778. 1,
  138779. 3,
  138780. 0,
  138781. 4,
  138782. };
  138783. static long _vq_lengthlist__44c1_s_p7_1[] = {
  138784. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  138785. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  138786. };
  138787. static float _vq_quantthresh__44c1_s_p7_1[] = {
  138788. -1.5, -0.5, 0.5, 1.5,
  138789. };
  138790. static long _vq_quantmap__44c1_s_p7_1[] = {
  138791. 3, 1, 0, 2, 4,
  138792. };
  138793. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_1 = {
  138794. _vq_quantthresh__44c1_s_p7_1,
  138795. _vq_quantmap__44c1_s_p7_1,
  138796. 5,
  138797. 5
  138798. };
  138799. static static_codebook _44c1_s_p7_1 = {
  138800. 2, 25,
  138801. _vq_lengthlist__44c1_s_p7_1,
  138802. 1, -533725184, 1611661312, 3, 0,
  138803. _vq_quantlist__44c1_s_p7_1,
  138804. NULL,
  138805. &_vq_auxt__44c1_s_p7_1,
  138806. NULL,
  138807. 0
  138808. };
  138809. static long _vq_quantlist__44c1_s_p8_0[] = {
  138810. 6,
  138811. 5,
  138812. 7,
  138813. 4,
  138814. 8,
  138815. 3,
  138816. 9,
  138817. 2,
  138818. 10,
  138819. 1,
  138820. 11,
  138821. 0,
  138822. 12,
  138823. };
  138824. static long _vq_lengthlist__44c1_s_p8_0[] = {
  138825. 1, 4, 3,10,10,10,10,10,10,10,10,10,10, 4, 8, 6,
  138826. 10,10,10,10,10,10,10,10,10,10, 4, 8, 7,10,10,10,
  138827. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138828. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138829. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138830. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138831. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138832. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138833. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138834. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138835. 10,10,10,10,10,10,10,10,10,
  138836. };
  138837. static float _vq_quantthresh__44c1_s_p8_0[] = {
  138838. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  138839. 552.5, 773.5, 994.5, 1215.5,
  138840. };
  138841. static long _vq_quantmap__44c1_s_p8_0[] = {
  138842. 11, 9, 7, 5, 3, 1, 0, 2,
  138843. 4, 6, 8, 10, 12,
  138844. };
  138845. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_0 = {
  138846. _vq_quantthresh__44c1_s_p8_0,
  138847. _vq_quantmap__44c1_s_p8_0,
  138848. 13,
  138849. 13
  138850. };
  138851. static static_codebook _44c1_s_p8_0 = {
  138852. 2, 169,
  138853. _vq_lengthlist__44c1_s_p8_0,
  138854. 1, -514541568, 1627103232, 4, 0,
  138855. _vq_quantlist__44c1_s_p8_0,
  138856. NULL,
  138857. &_vq_auxt__44c1_s_p8_0,
  138858. NULL,
  138859. 0
  138860. };
  138861. static long _vq_quantlist__44c1_s_p8_1[] = {
  138862. 6,
  138863. 5,
  138864. 7,
  138865. 4,
  138866. 8,
  138867. 3,
  138868. 9,
  138869. 2,
  138870. 10,
  138871. 1,
  138872. 11,
  138873. 0,
  138874. 12,
  138875. };
  138876. static long _vq_lengthlist__44c1_s_p8_1[] = {
  138877. 1, 4, 4, 6, 5, 7, 7, 9, 9,10,10,12,12, 6, 5, 5,
  138878. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  138879. 8,10,10,11,11,12,12,15, 7, 7, 8, 8, 9, 9,11,11,
  138880. 12,12,13,12,15, 8, 8, 8, 7, 9, 9,10,10,12,12,13,
  138881. 13,16,11,10, 8, 8,10,10,11,11,12,12,13,13,16,11,
  138882. 11, 9, 8,11,10,11,11,12,12,13,12,16,16,16,10,11,
  138883. 10,11,12,12,12,12,13,13,16,16,16,11, 9,11, 9,14,
  138884. 12,12,12,13,13,16,16,16,12,14,11,12,12,12,13,13,
  138885. 14,13,16,16,16,15,13,12,10,13,10,13,14,13,13,16,
  138886. 16,16,16,16,13,14,12,13,13,12,13,13,16,16,16,16,
  138887. 16,13,12,12,11,14,12,15,13,
  138888. };
  138889. static float _vq_quantthresh__44c1_s_p8_1[] = {
  138890. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  138891. 42.5, 59.5, 76.5, 93.5,
  138892. };
  138893. static long _vq_quantmap__44c1_s_p8_1[] = {
  138894. 11, 9, 7, 5, 3, 1, 0, 2,
  138895. 4, 6, 8, 10, 12,
  138896. };
  138897. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_1 = {
  138898. _vq_quantthresh__44c1_s_p8_1,
  138899. _vq_quantmap__44c1_s_p8_1,
  138900. 13,
  138901. 13
  138902. };
  138903. static static_codebook _44c1_s_p8_1 = {
  138904. 2, 169,
  138905. _vq_lengthlist__44c1_s_p8_1,
  138906. 1, -522616832, 1620115456, 4, 0,
  138907. _vq_quantlist__44c1_s_p8_1,
  138908. NULL,
  138909. &_vq_auxt__44c1_s_p8_1,
  138910. NULL,
  138911. 0
  138912. };
  138913. static long _vq_quantlist__44c1_s_p8_2[] = {
  138914. 8,
  138915. 7,
  138916. 9,
  138917. 6,
  138918. 10,
  138919. 5,
  138920. 11,
  138921. 4,
  138922. 12,
  138923. 3,
  138924. 13,
  138925. 2,
  138926. 14,
  138927. 1,
  138928. 15,
  138929. 0,
  138930. 16,
  138931. };
  138932. static long _vq_lengthlist__44c1_s_p8_2[] = {
  138933. 2, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  138934. 8,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  138935. 9, 9,10,10,10, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  138936. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  138937. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  138938. 9,10, 9, 9,10,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  138939. 9, 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  138940. 9, 9, 9, 9, 9,10,10,11,11,11, 8, 8, 9, 9, 9, 9,
  138941. 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11, 8, 8, 9,
  138942. 9, 9, 9,10, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  138943. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 9,
  138944. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  138945. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10,11,11,
  138946. 11,11,11, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,10,11,11,
  138947. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  138948. 11,11,11,11,11, 9,10, 9, 9, 9, 9,10, 9, 9, 9,11,
  138949. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  138950. 11,11,10,11,11,11,11,10,11, 9, 9, 9, 9, 9, 9, 9,
  138951. 9,
  138952. };
  138953. static float _vq_quantthresh__44c1_s_p8_2[] = {
  138954. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138955. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138956. };
  138957. static long _vq_quantmap__44c1_s_p8_2[] = {
  138958. 15, 13, 11, 9, 7, 5, 3, 1,
  138959. 0, 2, 4, 6, 8, 10, 12, 14,
  138960. 16,
  138961. };
  138962. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_2 = {
  138963. _vq_quantthresh__44c1_s_p8_2,
  138964. _vq_quantmap__44c1_s_p8_2,
  138965. 17,
  138966. 17
  138967. };
  138968. static static_codebook _44c1_s_p8_2 = {
  138969. 2, 289,
  138970. _vq_lengthlist__44c1_s_p8_2,
  138971. 1, -529530880, 1611661312, 5, 0,
  138972. _vq_quantlist__44c1_s_p8_2,
  138973. NULL,
  138974. &_vq_auxt__44c1_s_p8_2,
  138975. NULL,
  138976. 0
  138977. };
  138978. static long _huff_lengthlist__44c1_s_short[] = {
  138979. 6, 8,13,12,13,14,15,16,16, 4, 2, 4, 7, 6, 8,11,
  138980. 13,15,10, 4, 4, 8, 6, 8,11,14,17,11, 5, 6, 5, 6,
  138981. 8,12,14,17,11, 5, 5, 6, 5, 7,10,13,16,12, 6, 7,
  138982. 8, 7, 8,10,13,15,13, 8, 8, 7, 7, 8,10,12,15,15,
  138983. 7, 7, 5, 5, 7, 9,12,14,15, 8, 8, 6, 6, 7, 8,10,
  138984. 11,
  138985. };
  138986. static static_codebook _huff_book__44c1_s_short = {
  138987. 2, 81,
  138988. _huff_lengthlist__44c1_s_short,
  138989. 0, 0, 0, 0, 0,
  138990. NULL,
  138991. NULL,
  138992. NULL,
  138993. NULL,
  138994. 0
  138995. };
  138996. static long _huff_lengthlist__44c1_sm_long[] = {
  138997. 5, 4, 8,10, 9, 9,10,11,12, 4, 2, 5, 6, 6, 8,10,
  138998. 11,13, 8, 4, 6, 8, 7, 9,12,12,14,10, 6, 8, 4, 5,
  138999. 6, 9,11,12, 9, 5, 6, 5, 5, 6, 9,11,11, 9, 7, 9,
  139000. 6, 5, 5, 7,10,10,10, 9,11, 8, 7, 6, 7, 9,11,11,
  139001. 12,13,10,10, 9, 8, 9,11,11,15,15,12,13,11, 9,10,
  139002. 11,
  139003. };
  139004. static static_codebook _huff_book__44c1_sm_long = {
  139005. 2, 81,
  139006. _huff_lengthlist__44c1_sm_long,
  139007. 0, 0, 0, 0, 0,
  139008. NULL,
  139009. NULL,
  139010. NULL,
  139011. NULL,
  139012. 0
  139013. };
  139014. static long _vq_quantlist__44c1_sm_p1_0[] = {
  139015. 1,
  139016. 0,
  139017. 2,
  139018. };
  139019. static long _vq_lengthlist__44c1_sm_p1_0[] = {
  139020. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  139021. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139025. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  139026. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139030. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  139031. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  139066. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  139067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  139071. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  139072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  139076. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  139077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139111. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  139112. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139116. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  139117. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  139118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139121. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  139122. 0, 0, 0, 0, 0, 0, 9,10, 9, 0, 0, 0, 0, 0, 0, 0,
  139123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139430. 0,
  139431. };
  139432. static float _vq_quantthresh__44c1_sm_p1_0[] = {
  139433. -0.5, 0.5,
  139434. };
  139435. static long _vq_quantmap__44c1_sm_p1_0[] = {
  139436. 1, 0, 2,
  139437. };
  139438. static encode_aux_threshmatch _vq_auxt__44c1_sm_p1_0 = {
  139439. _vq_quantthresh__44c1_sm_p1_0,
  139440. _vq_quantmap__44c1_sm_p1_0,
  139441. 3,
  139442. 3
  139443. };
  139444. static static_codebook _44c1_sm_p1_0 = {
  139445. 8, 6561,
  139446. _vq_lengthlist__44c1_sm_p1_0,
  139447. 1, -535822336, 1611661312, 2, 0,
  139448. _vq_quantlist__44c1_sm_p1_0,
  139449. NULL,
  139450. &_vq_auxt__44c1_sm_p1_0,
  139451. NULL,
  139452. 0
  139453. };
  139454. static long _vq_quantlist__44c1_sm_p2_0[] = {
  139455. 2,
  139456. 1,
  139457. 3,
  139458. 0,
  139459. 4,
  139460. };
  139461. static long _vq_lengthlist__44c1_sm_p2_0[] = {
  139462. 2, 3, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  139464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139465. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  139467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139468. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  139469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139501. 0,
  139502. };
  139503. static float _vq_quantthresh__44c1_sm_p2_0[] = {
  139504. -1.5, -0.5, 0.5, 1.5,
  139505. };
  139506. static long _vq_quantmap__44c1_sm_p2_0[] = {
  139507. 3, 1, 0, 2, 4,
  139508. };
  139509. static encode_aux_threshmatch _vq_auxt__44c1_sm_p2_0 = {
  139510. _vq_quantthresh__44c1_sm_p2_0,
  139511. _vq_quantmap__44c1_sm_p2_0,
  139512. 5,
  139513. 5
  139514. };
  139515. static static_codebook _44c1_sm_p2_0 = {
  139516. 4, 625,
  139517. _vq_lengthlist__44c1_sm_p2_0,
  139518. 1, -533725184, 1611661312, 3, 0,
  139519. _vq_quantlist__44c1_sm_p2_0,
  139520. NULL,
  139521. &_vq_auxt__44c1_sm_p2_0,
  139522. NULL,
  139523. 0
  139524. };
  139525. static long _vq_quantlist__44c1_sm_p3_0[] = {
  139526. 4,
  139527. 3,
  139528. 5,
  139529. 2,
  139530. 6,
  139531. 1,
  139532. 7,
  139533. 0,
  139534. 8,
  139535. };
  139536. static long _vq_lengthlist__44c1_sm_p3_0[] = {
  139537. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 5, 6, 6, 0, 0,
  139538. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 7, 7, 7, 7,
  139539. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  139540. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  139541. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139542. 0,
  139543. };
  139544. static float _vq_quantthresh__44c1_sm_p3_0[] = {
  139545. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139546. };
  139547. static long _vq_quantmap__44c1_sm_p3_0[] = {
  139548. 7, 5, 3, 1, 0, 2, 4, 6,
  139549. 8,
  139550. };
  139551. static encode_aux_threshmatch _vq_auxt__44c1_sm_p3_0 = {
  139552. _vq_quantthresh__44c1_sm_p3_0,
  139553. _vq_quantmap__44c1_sm_p3_0,
  139554. 9,
  139555. 9
  139556. };
  139557. static static_codebook _44c1_sm_p3_0 = {
  139558. 2, 81,
  139559. _vq_lengthlist__44c1_sm_p3_0,
  139560. 1, -531628032, 1611661312, 4, 0,
  139561. _vq_quantlist__44c1_sm_p3_0,
  139562. NULL,
  139563. &_vq_auxt__44c1_sm_p3_0,
  139564. NULL,
  139565. 0
  139566. };
  139567. static long _vq_quantlist__44c1_sm_p4_0[] = {
  139568. 4,
  139569. 3,
  139570. 5,
  139571. 2,
  139572. 6,
  139573. 1,
  139574. 7,
  139575. 0,
  139576. 8,
  139577. };
  139578. static long _vq_lengthlist__44c1_sm_p4_0[] = {
  139579. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7, 8, 8,
  139580. 9, 9, 0, 6, 6, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  139581. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  139582. 8, 8, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  139583. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  139584. 11,
  139585. };
  139586. static float _vq_quantthresh__44c1_sm_p4_0[] = {
  139587. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139588. };
  139589. static long _vq_quantmap__44c1_sm_p4_0[] = {
  139590. 7, 5, 3, 1, 0, 2, 4, 6,
  139591. 8,
  139592. };
  139593. static encode_aux_threshmatch _vq_auxt__44c1_sm_p4_0 = {
  139594. _vq_quantthresh__44c1_sm_p4_0,
  139595. _vq_quantmap__44c1_sm_p4_0,
  139596. 9,
  139597. 9
  139598. };
  139599. static static_codebook _44c1_sm_p4_0 = {
  139600. 2, 81,
  139601. _vq_lengthlist__44c1_sm_p4_0,
  139602. 1, -531628032, 1611661312, 4, 0,
  139603. _vq_quantlist__44c1_sm_p4_0,
  139604. NULL,
  139605. &_vq_auxt__44c1_sm_p4_0,
  139606. NULL,
  139607. 0
  139608. };
  139609. static long _vq_quantlist__44c1_sm_p5_0[] = {
  139610. 8,
  139611. 7,
  139612. 9,
  139613. 6,
  139614. 10,
  139615. 5,
  139616. 11,
  139617. 4,
  139618. 12,
  139619. 3,
  139620. 13,
  139621. 2,
  139622. 14,
  139623. 1,
  139624. 15,
  139625. 0,
  139626. 16,
  139627. };
  139628. static long _vq_lengthlist__44c1_sm_p5_0[] = {
  139629. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  139630. 11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  139631. 11,11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  139632. 10,11,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  139633. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  139634. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,10,
  139635. 10,11,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,
  139636. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  139637. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  139638. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  139639. 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  139640. 9, 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  139641. 9, 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  139642. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  139643. 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0, 0,
  139644. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  139645. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14,
  139646. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  139647. 14,
  139648. };
  139649. static float _vq_quantthresh__44c1_sm_p5_0[] = {
  139650. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139651. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139652. };
  139653. static long _vq_quantmap__44c1_sm_p5_0[] = {
  139654. 15, 13, 11, 9, 7, 5, 3, 1,
  139655. 0, 2, 4, 6, 8, 10, 12, 14,
  139656. 16,
  139657. };
  139658. static encode_aux_threshmatch _vq_auxt__44c1_sm_p5_0 = {
  139659. _vq_quantthresh__44c1_sm_p5_0,
  139660. _vq_quantmap__44c1_sm_p5_0,
  139661. 17,
  139662. 17
  139663. };
  139664. static static_codebook _44c1_sm_p5_0 = {
  139665. 2, 289,
  139666. _vq_lengthlist__44c1_sm_p5_0,
  139667. 1, -529530880, 1611661312, 5, 0,
  139668. _vq_quantlist__44c1_sm_p5_0,
  139669. NULL,
  139670. &_vq_auxt__44c1_sm_p5_0,
  139671. NULL,
  139672. 0
  139673. };
  139674. static long _vq_quantlist__44c1_sm_p6_0[] = {
  139675. 1,
  139676. 0,
  139677. 2,
  139678. };
  139679. static long _vq_lengthlist__44c1_sm_p6_0[] = {
  139680. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  139681. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  139682. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  139683. 11,10,11,11,10,10, 7,11,11,11,11,11,11,11,11, 6,
  139684. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,11,10,
  139685. 11,
  139686. };
  139687. static float _vq_quantthresh__44c1_sm_p6_0[] = {
  139688. -5.5, 5.5,
  139689. };
  139690. static long _vq_quantmap__44c1_sm_p6_0[] = {
  139691. 1, 0, 2,
  139692. };
  139693. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_0 = {
  139694. _vq_quantthresh__44c1_sm_p6_0,
  139695. _vq_quantmap__44c1_sm_p6_0,
  139696. 3,
  139697. 3
  139698. };
  139699. static static_codebook _44c1_sm_p6_0 = {
  139700. 4, 81,
  139701. _vq_lengthlist__44c1_sm_p6_0,
  139702. 1, -529137664, 1618345984, 2, 0,
  139703. _vq_quantlist__44c1_sm_p6_0,
  139704. NULL,
  139705. &_vq_auxt__44c1_sm_p6_0,
  139706. NULL,
  139707. 0
  139708. };
  139709. static long _vq_quantlist__44c1_sm_p6_1[] = {
  139710. 5,
  139711. 4,
  139712. 6,
  139713. 3,
  139714. 7,
  139715. 2,
  139716. 8,
  139717. 1,
  139718. 9,
  139719. 0,
  139720. 10,
  139721. };
  139722. static long _vq_lengthlist__44c1_sm_p6_1[] = {
  139723. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  139724. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  139725. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  139726. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  139727. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  139728. 8, 8, 8, 8, 8, 8, 9, 8,10,10,10,10,10, 8, 8, 8,
  139729. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  139730. 10,10,10, 8, 8, 8, 8, 8, 8,
  139731. };
  139732. static float _vq_quantthresh__44c1_sm_p6_1[] = {
  139733. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  139734. 3.5, 4.5,
  139735. };
  139736. static long _vq_quantmap__44c1_sm_p6_1[] = {
  139737. 9, 7, 5, 3, 1, 0, 2, 4,
  139738. 6, 8, 10,
  139739. };
  139740. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_1 = {
  139741. _vq_quantthresh__44c1_sm_p6_1,
  139742. _vq_quantmap__44c1_sm_p6_1,
  139743. 11,
  139744. 11
  139745. };
  139746. static static_codebook _44c1_sm_p6_1 = {
  139747. 2, 121,
  139748. _vq_lengthlist__44c1_sm_p6_1,
  139749. 1, -531365888, 1611661312, 4, 0,
  139750. _vq_quantlist__44c1_sm_p6_1,
  139751. NULL,
  139752. &_vq_auxt__44c1_sm_p6_1,
  139753. NULL,
  139754. 0
  139755. };
  139756. static long _vq_quantlist__44c1_sm_p7_0[] = {
  139757. 6,
  139758. 5,
  139759. 7,
  139760. 4,
  139761. 8,
  139762. 3,
  139763. 9,
  139764. 2,
  139765. 10,
  139766. 1,
  139767. 11,
  139768. 0,
  139769. 12,
  139770. };
  139771. static long _vq_lengthlist__44c1_sm_p7_0[] = {
  139772. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  139773. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  139774. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  139775. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  139776. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  139777. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0, 9,10,
  139778. 9,10,11,11,12,11,13,12, 0, 0, 0,10,10, 9, 9,11,
  139779. 11,12,12,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  139780. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  139781. 0, 0, 0, 0,11,12,11,11,12,13,14,13, 0, 0, 0, 0,
  139782. 0,12,12,11,11,13,12,14,13,
  139783. };
  139784. static float _vq_quantthresh__44c1_sm_p7_0[] = {
  139785. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  139786. 12.5, 17.5, 22.5, 27.5,
  139787. };
  139788. static long _vq_quantmap__44c1_sm_p7_0[] = {
  139789. 11, 9, 7, 5, 3, 1, 0, 2,
  139790. 4, 6, 8, 10, 12,
  139791. };
  139792. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_0 = {
  139793. _vq_quantthresh__44c1_sm_p7_0,
  139794. _vq_quantmap__44c1_sm_p7_0,
  139795. 13,
  139796. 13
  139797. };
  139798. static static_codebook _44c1_sm_p7_0 = {
  139799. 2, 169,
  139800. _vq_lengthlist__44c1_sm_p7_0,
  139801. 1, -526516224, 1616117760, 4, 0,
  139802. _vq_quantlist__44c1_sm_p7_0,
  139803. NULL,
  139804. &_vq_auxt__44c1_sm_p7_0,
  139805. NULL,
  139806. 0
  139807. };
  139808. static long _vq_quantlist__44c1_sm_p7_1[] = {
  139809. 2,
  139810. 1,
  139811. 3,
  139812. 0,
  139813. 4,
  139814. };
  139815. static long _vq_lengthlist__44c1_sm_p7_1[] = {
  139816. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  139817. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  139818. };
  139819. static float _vq_quantthresh__44c1_sm_p7_1[] = {
  139820. -1.5, -0.5, 0.5, 1.5,
  139821. };
  139822. static long _vq_quantmap__44c1_sm_p7_1[] = {
  139823. 3, 1, 0, 2, 4,
  139824. };
  139825. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_1 = {
  139826. _vq_quantthresh__44c1_sm_p7_1,
  139827. _vq_quantmap__44c1_sm_p7_1,
  139828. 5,
  139829. 5
  139830. };
  139831. static static_codebook _44c1_sm_p7_1 = {
  139832. 2, 25,
  139833. _vq_lengthlist__44c1_sm_p7_1,
  139834. 1, -533725184, 1611661312, 3, 0,
  139835. _vq_quantlist__44c1_sm_p7_1,
  139836. NULL,
  139837. &_vq_auxt__44c1_sm_p7_1,
  139838. NULL,
  139839. 0
  139840. };
  139841. static long _vq_quantlist__44c1_sm_p8_0[] = {
  139842. 6,
  139843. 5,
  139844. 7,
  139845. 4,
  139846. 8,
  139847. 3,
  139848. 9,
  139849. 2,
  139850. 10,
  139851. 1,
  139852. 11,
  139853. 0,
  139854. 12,
  139855. };
  139856. static long _vq_lengthlist__44c1_sm_p8_0[] = {
  139857. 1, 3, 3,13,13,13,13,13,13,13,13,13,13, 3, 6, 6,
  139858. 13,13,13,13,13,13,13,13,13,13, 4, 8, 7,13,13,13,
  139859. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139860. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139861. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139862. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139863. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139864. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139865. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139866. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139867. 13,13,13,13,13,13,13,13,13,
  139868. };
  139869. static float _vq_quantthresh__44c1_sm_p8_0[] = {
  139870. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  139871. 552.5, 773.5, 994.5, 1215.5,
  139872. };
  139873. static long _vq_quantmap__44c1_sm_p8_0[] = {
  139874. 11, 9, 7, 5, 3, 1, 0, 2,
  139875. 4, 6, 8, 10, 12,
  139876. };
  139877. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_0 = {
  139878. _vq_quantthresh__44c1_sm_p8_0,
  139879. _vq_quantmap__44c1_sm_p8_0,
  139880. 13,
  139881. 13
  139882. };
  139883. static static_codebook _44c1_sm_p8_0 = {
  139884. 2, 169,
  139885. _vq_lengthlist__44c1_sm_p8_0,
  139886. 1, -514541568, 1627103232, 4, 0,
  139887. _vq_quantlist__44c1_sm_p8_0,
  139888. NULL,
  139889. &_vq_auxt__44c1_sm_p8_0,
  139890. NULL,
  139891. 0
  139892. };
  139893. static long _vq_quantlist__44c1_sm_p8_1[] = {
  139894. 6,
  139895. 5,
  139896. 7,
  139897. 4,
  139898. 8,
  139899. 3,
  139900. 9,
  139901. 2,
  139902. 10,
  139903. 1,
  139904. 11,
  139905. 0,
  139906. 12,
  139907. };
  139908. static long _vq_lengthlist__44c1_sm_p8_1[] = {
  139909. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  139910. 7, 7, 8, 7,10,10,11,11,12,12, 6, 5, 5, 7, 7, 8,
  139911. 8,10,10,11,11,12,12,16, 7, 7, 8, 8, 9, 9,11,11,
  139912. 12,12,13,13,17, 7, 7, 8, 7, 9, 9,11,10,12,12,13,
  139913. 13,19,11,10, 8, 8,10,10,11,11,12,12,13,13,19,11,
  139914. 11, 9, 7,11,10,11,11,12,12,13,12,19,19,19,10,10,
  139915. 10,10,11,12,12,12,13,14,18,19,19,11, 9,11, 9,13,
  139916. 12,12,12,13,13,19,20,19,13,15,11,11,12,12,13,13,
  139917. 14,13,18,19,20,15,13,12,10,13,10,13,13,13,14,20,
  139918. 20,20,20,20,13,14,12,12,13,12,13,13,20,20,20,20,
  139919. 20,13,12,12,12,14,12,14,13,
  139920. };
  139921. static float _vq_quantthresh__44c1_sm_p8_1[] = {
  139922. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  139923. 42.5, 59.5, 76.5, 93.5,
  139924. };
  139925. static long _vq_quantmap__44c1_sm_p8_1[] = {
  139926. 11, 9, 7, 5, 3, 1, 0, 2,
  139927. 4, 6, 8, 10, 12,
  139928. };
  139929. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_1 = {
  139930. _vq_quantthresh__44c1_sm_p8_1,
  139931. _vq_quantmap__44c1_sm_p8_1,
  139932. 13,
  139933. 13
  139934. };
  139935. static static_codebook _44c1_sm_p8_1 = {
  139936. 2, 169,
  139937. _vq_lengthlist__44c1_sm_p8_1,
  139938. 1, -522616832, 1620115456, 4, 0,
  139939. _vq_quantlist__44c1_sm_p8_1,
  139940. NULL,
  139941. &_vq_auxt__44c1_sm_p8_1,
  139942. NULL,
  139943. 0
  139944. };
  139945. static long _vq_quantlist__44c1_sm_p8_2[] = {
  139946. 8,
  139947. 7,
  139948. 9,
  139949. 6,
  139950. 10,
  139951. 5,
  139952. 11,
  139953. 4,
  139954. 12,
  139955. 3,
  139956. 13,
  139957. 2,
  139958. 14,
  139959. 1,
  139960. 15,
  139961. 0,
  139962. 16,
  139963. };
  139964. static long _vq_lengthlist__44c1_sm_p8_2[] = {
  139965. 2, 5, 5, 6, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  139966. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  139967. 9, 9,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  139968. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  139969. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  139970. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  139971. 9, 9,10,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  139972. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  139973. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 8, 8, 9,
  139974. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  139975. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,11,11,11, 9,
  139976. 8, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,10,11,11,
  139977. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,11,
  139978. 11,11,11, 9, 9,10, 9, 9, 9, 9,10, 9,10,10,11,10,
  139979. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  139980. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,
  139981. 11,10,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  139982. 10,11,10,11,11,11,11,11,11, 9, 9,10, 9, 9, 9, 9,
  139983. 9,
  139984. };
  139985. static float _vq_quantthresh__44c1_sm_p8_2[] = {
  139986. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139987. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139988. };
  139989. static long _vq_quantmap__44c1_sm_p8_2[] = {
  139990. 15, 13, 11, 9, 7, 5, 3, 1,
  139991. 0, 2, 4, 6, 8, 10, 12, 14,
  139992. 16,
  139993. };
  139994. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_2 = {
  139995. _vq_quantthresh__44c1_sm_p8_2,
  139996. _vq_quantmap__44c1_sm_p8_2,
  139997. 17,
  139998. 17
  139999. };
  140000. static static_codebook _44c1_sm_p8_2 = {
  140001. 2, 289,
  140002. _vq_lengthlist__44c1_sm_p8_2,
  140003. 1, -529530880, 1611661312, 5, 0,
  140004. _vq_quantlist__44c1_sm_p8_2,
  140005. NULL,
  140006. &_vq_auxt__44c1_sm_p8_2,
  140007. NULL,
  140008. 0
  140009. };
  140010. static long _huff_lengthlist__44c1_sm_short[] = {
  140011. 4, 7,13,14,14,15,16,18,18, 4, 2, 5, 8, 7, 9,12,
  140012. 15,15,10, 4, 5,10, 6, 8,11,15,17,12, 5, 7, 5, 6,
  140013. 8,11,14,17,11, 5, 6, 6, 5, 6, 9,13,17,12, 6, 7,
  140014. 6, 5, 6, 8,12,14,14, 7, 8, 6, 6, 7, 9,11,14,14,
  140015. 8, 9, 6, 5, 6, 9,11,13,16,10,10, 7, 6, 7, 8,10,
  140016. 11,
  140017. };
  140018. static static_codebook _huff_book__44c1_sm_short = {
  140019. 2, 81,
  140020. _huff_lengthlist__44c1_sm_short,
  140021. 0, 0, 0, 0, 0,
  140022. NULL,
  140023. NULL,
  140024. NULL,
  140025. NULL,
  140026. 0
  140027. };
  140028. static long _huff_lengthlist__44cn1_s_long[] = {
  140029. 4, 4, 7, 8, 7, 8,10,12,17, 3, 1, 6, 6, 7, 8,10,
  140030. 12,15, 7, 6, 9, 9, 9,11,12,14,17, 8, 6, 9, 6, 7,
  140031. 9,11,13,17, 7, 6, 9, 7, 7, 8, 9,12,15, 8, 8,10,
  140032. 8, 7, 7, 7,10,14, 9,10,12,10, 8, 8, 8,10,14,11,
  140033. 13,15,13,12,11,11,12,16,17,18,18,19,20,18,16,16,
  140034. 20,
  140035. };
  140036. static static_codebook _huff_book__44cn1_s_long = {
  140037. 2, 81,
  140038. _huff_lengthlist__44cn1_s_long,
  140039. 0, 0, 0, 0, 0,
  140040. NULL,
  140041. NULL,
  140042. NULL,
  140043. NULL,
  140044. 0
  140045. };
  140046. static long _vq_quantlist__44cn1_s_p1_0[] = {
  140047. 1,
  140048. 0,
  140049. 2,
  140050. };
  140051. static long _vq_lengthlist__44cn1_s_p1_0[] = {
  140052. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  140053. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140057. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  140058. 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140062. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0,
  140063. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  140098. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0,
  140099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0, 0,
  140103. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  140104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0,
  140108. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0,10,11,11,
  140109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140143. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  140144. 0, 0, 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140148. 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  140149. 0, 0, 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  140150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140153. 0, 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11,
  140154. 0, 0, 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 0,
  140155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140462. 0,
  140463. };
  140464. static float _vq_quantthresh__44cn1_s_p1_0[] = {
  140465. -0.5, 0.5,
  140466. };
  140467. static long _vq_quantmap__44cn1_s_p1_0[] = {
  140468. 1, 0, 2,
  140469. };
  140470. static encode_aux_threshmatch _vq_auxt__44cn1_s_p1_0 = {
  140471. _vq_quantthresh__44cn1_s_p1_0,
  140472. _vq_quantmap__44cn1_s_p1_0,
  140473. 3,
  140474. 3
  140475. };
  140476. static static_codebook _44cn1_s_p1_0 = {
  140477. 8, 6561,
  140478. _vq_lengthlist__44cn1_s_p1_0,
  140479. 1, -535822336, 1611661312, 2, 0,
  140480. _vq_quantlist__44cn1_s_p1_0,
  140481. NULL,
  140482. &_vq_auxt__44cn1_s_p1_0,
  140483. NULL,
  140484. 0
  140485. };
  140486. static long _vq_quantlist__44cn1_s_p2_0[] = {
  140487. 2,
  140488. 1,
  140489. 3,
  140490. 0,
  140491. 4,
  140492. };
  140493. static long _vq_lengthlist__44cn1_s_p2_0[] = {
  140494. 1, 4, 4, 7, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  140496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140497. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  140499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140500. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  140501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140533. 0,
  140534. };
  140535. static float _vq_quantthresh__44cn1_s_p2_0[] = {
  140536. -1.5, -0.5, 0.5, 1.5,
  140537. };
  140538. static long _vq_quantmap__44cn1_s_p2_0[] = {
  140539. 3, 1, 0, 2, 4,
  140540. };
  140541. static encode_aux_threshmatch _vq_auxt__44cn1_s_p2_0 = {
  140542. _vq_quantthresh__44cn1_s_p2_0,
  140543. _vq_quantmap__44cn1_s_p2_0,
  140544. 5,
  140545. 5
  140546. };
  140547. static static_codebook _44cn1_s_p2_0 = {
  140548. 4, 625,
  140549. _vq_lengthlist__44cn1_s_p2_0,
  140550. 1, -533725184, 1611661312, 3, 0,
  140551. _vq_quantlist__44cn1_s_p2_0,
  140552. NULL,
  140553. &_vq_auxt__44cn1_s_p2_0,
  140554. NULL,
  140555. 0
  140556. };
  140557. static long _vq_quantlist__44cn1_s_p3_0[] = {
  140558. 4,
  140559. 3,
  140560. 5,
  140561. 2,
  140562. 6,
  140563. 1,
  140564. 7,
  140565. 0,
  140566. 8,
  140567. };
  140568. static long _vq_lengthlist__44cn1_s_p3_0[] = {
  140569. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  140570. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  140571. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  140572. 9, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  140573. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140574. 0,
  140575. };
  140576. static float _vq_quantthresh__44cn1_s_p3_0[] = {
  140577. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140578. };
  140579. static long _vq_quantmap__44cn1_s_p3_0[] = {
  140580. 7, 5, 3, 1, 0, 2, 4, 6,
  140581. 8,
  140582. };
  140583. static encode_aux_threshmatch _vq_auxt__44cn1_s_p3_0 = {
  140584. _vq_quantthresh__44cn1_s_p3_0,
  140585. _vq_quantmap__44cn1_s_p3_0,
  140586. 9,
  140587. 9
  140588. };
  140589. static static_codebook _44cn1_s_p3_0 = {
  140590. 2, 81,
  140591. _vq_lengthlist__44cn1_s_p3_0,
  140592. 1, -531628032, 1611661312, 4, 0,
  140593. _vq_quantlist__44cn1_s_p3_0,
  140594. NULL,
  140595. &_vq_auxt__44cn1_s_p3_0,
  140596. NULL,
  140597. 0
  140598. };
  140599. static long _vq_quantlist__44cn1_s_p4_0[] = {
  140600. 4,
  140601. 3,
  140602. 5,
  140603. 2,
  140604. 6,
  140605. 1,
  140606. 7,
  140607. 0,
  140608. 8,
  140609. };
  140610. static long _vq_lengthlist__44cn1_s_p4_0[] = {
  140611. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  140612. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  140613. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  140614. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  140615. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  140616. 11,
  140617. };
  140618. static float _vq_quantthresh__44cn1_s_p4_0[] = {
  140619. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140620. };
  140621. static long _vq_quantmap__44cn1_s_p4_0[] = {
  140622. 7, 5, 3, 1, 0, 2, 4, 6,
  140623. 8,
  140624. };
  140625. static encode_aux_threshmatch _vq_auxt__44cn1_s_p4_0 = {
  140626. _vq_quantthresh__44cn1_s_p4_0,
  140627. _vq_quantmap__44cn1_s_p4_0,
  140628. 9,
  140629. 9
  140630. };
  140631. static static_codebook _44cn1_s_p4_0 = {
  140632. 2, 81,
  140633. _vq_lengthlist__44cn1_s_p4_0,
  140634. 1, -531628032, 1611661312, 4, 0,
  140635. _vq_quantlist__44cn1_s_p4_0,
  140636. NULL,
  140637. &_vq_auxt__44cn1_s_p4_0,
  140638. NULL,
  140639. 0
  140640. };
  140641. static long _vq_quantlist__44cn1_s_p5_0[] = {
  140642. 8,
  140643. 7,
  140644. 9,
  140645. 6,
  140646. 10,
  140647. 5,
  140648. 11,
  140649. 4,
  140650. 12,
  140651. 3,
  140652. 13,
  140653. 2,
  140654. 14,
  140655. 1,
  140656. 15,
  140657. 0,
  140658. 16,
  140659. };
  140660. static long _vq_lengthlist__44cn1_s_p5_0[] = {
  140661. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  140662. 10, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  140663. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  140664. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  140665. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  140666. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  140667. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  140668. 10,10,11,11,11,12,12, 0, 0, 0, 9, 9,10, 9,10,10,
  140669. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  140670. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  140671. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  140672. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  140673. 10,10,11,10,11,11,11,12,13,12,13,13, 0, 0, 0, 0,
  140674. 0, 0, 0,11,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  140675. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  140676. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  140677. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,13,13,14,14,
  140678. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,12,13,13,14,
  140679. 14,
  140680. };
  140681. static float _vq_quantthresh__44cn1_s_p5_0[] = {
  140682. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140683. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140684. };
  140685. static long _vq_quantmap__44cn1_s_p5_0[] = {
  140686. 15, 13, 11, 9, 7, 5, 3, 1,
  140687. 0, 2, 4, 6, 8, 10, 12, 14,
  140688. 16,
  140689. };
  140690. static encode_aux_threshmatch _vq_auxt__44cn1_s_p5_0 = {
  140691. _vq_quantthresh__44cn1_s_p5_0,
  140692. _vq_quantmap__44cn1_s_p5_0,
  140693. 17,
  140694. 17
  140695. };
  140696. static static_codebook _44cn1_s_p5_0 = {
  140697. 2, 289,
  140698. _vq_lengthlist__44cn1_s_p5_0,
  140699. 1, -529530880, 1611661312, 5, 0,
  140700. _vq_quantlist__44cn1_s_p5_0,
  140701. NULL,
  140702. &_vq_auxt__44cn1_s_p5_0,
  140703. NULL,
  140704. 0
  140705. };
  140706. static long _vq_quantlist__44cn1_s_p6_0[] = {
  140707. 1,
  140708. 0,
  140709. 2,
  140710. };
  140711. static long _vq_lengthlist__44cn1_s_p6_0[] = {
  140712. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 6, 6,10, 9, 9,11,
  140713. 9, 9, 4, 6, 6,10, 9, 9,10, 9, 9, 7,10,10,11,11,
  140714. 11,12,11,11, 7, 9, 9,11,11,10,11,10,10, 7, 9, 9,
  140715. 11,10,11,11,10,10, 7,10,10,11,11,11,12,11,11, 7,
  140716. 9, 9,11,10,10,11,10,10, 7, 9, 9,11,10,10,11,10,
  140717. 10,
  140718. };
  140719. static float _vq_quantthresh__44cn1_s_p6_0[] = {
  140720. -5.5, 5.5,
  140721. };
  140722. static long _vq_quantmap__44cn1_s_p6_0[] = {
  140723. 1, 0, 2,
  140724. };
  140725. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_0 = {
  140726. _vq_quantthresh__44cn1_s_p6_0,
  140727. _vq_quantmap__44cn1_s_p6_0,
  140728. 3,
  140729. 3
  140730. };
  140731. static static_codebook _44cn1_s_p6_0 = {
  140732. 4, 81,
  140733. _vq_lengthlist__44cn1_s_p6_0,
  140734. 1, -529137664, 1618345984, 2, 0,
  140735. _vq_quantlist__44cn1_s_p6_0,
  140736. NULL,
  140737. &_vq_auxt__44cn1_s_p6_0,
  140738. NULL,
  140739. 0
  140740. };
  140741. static long _vq_quantlist__44cn1_s_p6_1[] = {
  140742. 5,
  140743. 4,
  140744. 6,
  140745. 3,
  140746. 7,
  140747. 2,
  140748. 8,
  140749. 1,
  140750. 9,
  140751. 0,
  140752. 10,
  140753. };
  140754. static long _vq_lengthlist__44cn1_s_p6_1[] = {
  140755. 1, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 6,
  140756. 8, 8, 8, 8, 8, 8,10,10,10, 7, 6, 7, 7, 8, 8, 8,
  140757. 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  140758. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 9, 9,
  140759. 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,
  140760. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  140761. 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,
  140762. 10,10,10, 9, 9, 9, 9, 9, 9,
  140763. };
  140764. static float _vq_quantthresh__44cn1_s_p6_1[] = {
  140765. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  140766. 3.5, 4.5,
  140767. };
  140768. static long _vq_quantmap__44cn1_s_p6_1[] = {
  140769. 9, 7, 5, 3, 1, 0, 2, 4,
  140770. 6, 8, 10,
  140771. };
  140772. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_1 = {
  140773. _vq_quantthresh__44cn1_s_p6_1,
  140774. _vq_quantmap__44cn1_s_p6_1,
  140775. 11,
  140776. 11
  140777. };
  140778. static static_codebook _44cn1_s_p6_1 = {
  140779. 2, 121,
  140780. _vq_lengthlist__44cn1_s_p6_1,
  140781. 1, -531365888, 1611661312, 4, 0,
  140782. _vq_quantlist__44cn1_s_p6_1,
  140783. NULL,
  140784. &_vq_auxt__44cn1_s_p6_1,
  140785. NULL,
  140786. 0
  140787. };
  140788. static long _vq_quantlist__44cn1_s_p7_0[] = {
  140789. 6,
  140790. 5,
  140791. 7,
  140792. 4,
  140793. 8,
  140794. 3,
  140795. 9,
  140796. 2,
  140797. 10,
  140798. 1,
  140799. 11,
  140800. 0,
  140801. 12,
  140802. };
  140803. static long _vq_lengthlist__44cn1_s_p7_0[] = {
  140804. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  140805. 7, 7, 8, 8, 8, 8, 9, 9,11,11, 7, 5, 5, 7, 7, 8,
  140806. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  140807. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  140808. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,12, 0,13,
  140809. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  140810. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  140811. 11,12,12,13,12, 0, 0, 0,14,14,11,10,11,12,12,13,
  140812. 13,14, 0, 0, 0,15,15,11,11,12,11,12,12,14,13, 0,
  140813. 0, 0, 0, 0,12,12,12,12,13,13,14,14, 0, 0, 0, 0,
  140814. 0,13,13,12,12,13,13,13,14,
  140815. };
  140816. static float _vq_quantthresh__44cn1_s_p7_0[] = {
  140817. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  140818. 12.5, 17.5, 22.5, 27.5,
  140819. };
  140820. static long _vq_quantmap__44cn1_s_p7_0[] = {
  140821. 11, 9, 7, 5, 3, 1, 0, 2,
  140822. 4, 6, 8, 10, 12,
  140823. };
  140824. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_0 = {
  140825. _vq_quantthresh__44cn1_s_p7_0,
  140826. _vq_quantmap__44cn1_s_p7_0,
  140827. 13,
  140828. 13
  140829. };
  140830. static static_codebook _44cn1_s_p7_0 = {
  140831. 2, 169,
  140832. _vq_lengthlist__44cn1_s_p7_0,
  140833. 1, -526516224, 1616117760, 4, 0,
  140834. _vq_quantlist__44cn1_s_p7_0,
  140835. NULL,
  140836. &_vq_auxt__44cn1_s_p7_0,
  140837. NULL,
  140838. 0
  140839. };
  140840. static long _vq_quantlist__44cn1_s_p7_1[] = {
  140841. 2,
  140842. 1,
  140843. 3,
  140844. 0,
  140845. 4,
  140846. };
  140847. static long _vq_lengthlist__44cn1_s_p7_1[] = {
  140848. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  140849. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  140850. };
  140851. static float _vq_quantthresh__44cn1_s_p7_1[] = {
  140852. -1.5, -0.5, 0.5, 1.5,
  140853. };
  140854. static long _vq_quantmap__44cn1_s_p7_1[] = {
  140855. 3, 1, 0, 2, 4,
  140856. };
  140857. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_1 = {
  140858. _vq_quantthresh__44cn1_s_p7_1,
  140859. _vq_quantmap__44cn1_s_p7_1,
  140860. 5,
  140861. 5
  140862. };
  140863. static static_codebook _44cn1_s_p7_1 = {
  140864. 2, 25,
  140865. _vq_lengthlist__44cn1_s_p7_1,
  140866. 1, -533725184, 1611661312, 3, 0,
  140867. _vq_quantlist__44cn1_s_p7_1,
  140868. NULL,
  140869. &_vq_auxt__44cn1_s_p7_1,
  140870. NULL,
  140871. 0
  140872. };
  140873. static long _vq_quantlist__44cn1_s_p8_0[] = {
  140874. 2,
  140875. 1,
  140876. 3,
  140877. 0,
  140878. 4,
  140879. };
  140880. static long _vq_lengthlist__44cn1_s_p8_0[] = {
  140881. 1, 7, 7,11,11, 8,11,11,11,11, 4,11, 3,11,11,11,
  140882. 11,11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,
  140883. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140884. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  140885. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140886. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140887. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140888. 11,11,11,11,11,11,11,11,11,11,11,11,11, 7,11,11,
  140889. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140890. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  140891. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  140892. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140893. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140894. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140895. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140896. 11,11,11,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  140897. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140898. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140899. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140900. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140901. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140902. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140903. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140904. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140905. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140906. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140907. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140908. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140909. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140910. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140911. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140912. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140913. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140914. 11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,
  140915. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140916. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140917. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140918. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140919. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140920. 12,
  140921. };
  140922. static float _vq_quantthresh__44cn1_s_p8_0[] = {
  140923. -331.5, -110.5, 110.5, 331.5,
  140924. };
  140925. static long _vq_quantmap__44cn1_s_p8_0[] = {
  140926. 3, 1, 0, 2, 4,
  140927. };
  140928. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_0 = {
  140929. _vq_quantthresh__44cn1_s_p8_0,
  140930. _vq_quantmap__44cn1_s_p8_0,
  140931. 5,
  140932. 5
  140933. };
  140934. static static_codebook _44cn1_s_p8_0 = {
  140935. 4, 625,
  140936. _vq_lengthlist__44cn1_s_p8_0,
  140937. 1, -518283264, 1627103232, 3, 0,
  140938. _vq_quantlist__44cn1_s_p8_0,
  140939. NULL,
  140940. &_vq_auxt__44cn1_s_p8_0,
  140941. NULL,
  140942. 0
  140943. };
  140944. static long _vq_quantlist__44cn1_s_p8_1[] = {
  140945. 6,
  140946. 5,
  140947. 7,
  140948. 4,
  140949. 8,
  140950. 3,
  140951. 9,
  140952. 2,
  140953. 10,
  140954. 1,
  140955. 11,
  140956. 0,
  140957. 12,
  140958. };
  140959. static long _vq_lengthlist__44cn1_s_p8_1[] = {
  140960. 1, 4, 4, 6, 6, 8, 8, 9,10,10,11,11,11, 6, 5, 5,
  140961. 7, 7, 8, 8, 9,10, 9,11,11,12, 5, 5, 5, 7, 7, 8,
  140962. 9,10,10,12,12,14,13,15, 7, 7, 8, 8, 9,10,11,11,
  140963. 10,12,10,11,15, 7, 8, 8, 8, 9, 9,11,11,13,12,12,
  140964. 13,15,10,10, 8, 8,10,10,12,12,11,14,10,10,15,11,
  140965. 11, 8, 8,10,10,12,13,13,14,15,13,15,15,15,10,10,
  140966. 10,10,12,12,13,12,13,10,15,15,15,10,10,11,10,13,
  140967. 11,13,13,15,13,15,15,15,13,13,10,11,11,11,12,10,
  140968. 14,11,15,15,14,14,13,10,10,12,11,13,13,14,14,15,
  140969. 15,15,15,15,11,11,11,11,12,11,15,12,15,15,15,15,
  140970. 15,12,12,11,11,14,12,13,14,
  140971. };
  140972. static float _vq_quantthresh__44cn1_s_p8_1[] = {
  140973. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  140974. 42.5, 59.5, 76.5, 93.5,
  140975. };
  140976. static long _vq_quantmap__44cn1_s_p8_1[] = {
  140977. 11, 9, 7, 5, 3, 1, 0, 2,
  140978. 4, 6, 8, 10, 12,
  140979. };
  140980. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_1 = {
  140981. _vq_quantthresh__44cn1_s_p8_1,
  140982. _vq_quantmap__44cn1_s_p8_1,
  140983. 13,
  140984. 13
  140985. };
  140986. static static_codebook _44cn1_s_p8_1 = {
  140987. 2, 169,
  140988. _vq_lengthlist__44cn1_s_p8_1,
  140989. 1, -522616832, 1620115456, 4, 0,
  140990. _vq_quantlist__44cn1_s_p8_1,
  140991. NULL,
  140992. &_vq_auxt__44cn1_s_p8_1,
  140993. NULL,
  140994. 0
  140995. };
  140996. static long _vq_quantlist__44cn1_s_p8_2[] = {
  140997. 8,
  140998. 7,
  140999. 9,
  141000. 6,
  141001. 10,
  141002. 5,
  141003. 11,
  141004. 4,
  141005. 12,
  141006. 3,
  141007. 13,
  141008. 2,
  141009. 14,
  141010. 1,
  141011. 15,
  141012. 0,
  141013. 16,
  141014. };
  141015. static long _vq_lengthlist__44cn1_s_p8_2[] = {
  141016. 3, 4, 3, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  141017. 9,10,11,11, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  141018. 9, 9,10,10,10, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  141019. 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  141020. 9, 9,10, 9,10,11,10, 7, 6, 7, 7, 8, 8, 9, 9, 9,
  141021. 9, 9, 9, 9,10,10,10,11, 7, 7, 8, 8, 8, 8, 9, 9,
  141022. 9, 9, 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9,
  141023. 9, 9, 9, 9, 9, 9,10,11,11,11, 8, 8, 8, 8, 8, 8,
  141024. 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 8, 8, 8,
  141025. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,11, 9, 9,
  141026. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,10,11,11, 9,
  141027. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  141028. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,
  141029. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11,
  141030. 10,11,11,11, 9,10,10, 9, 9, 9, 9, 9, 9, 9,10,11,
  141031. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  141032. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  141033. 11,11,11,10,11,11,11,11,11, 9, 9, 9,10, 9, 9, 9,
  141034. 9,
  141035. };
  141036. static float _vq_quantthresh__44cn1_s_p8_2[] = {
  141037. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  141038. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  141039. };
  141040. static long _vq_quantmap__44cn1_s_p8_2[] = {
  141041. 15, 13, 11, 9, 7, 5, 3, 1,
  141042. 0, 2, 4, 6, 8, 10, 12, 14,
  141043. 16,
  141044. };
  141045. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_2 = {
  141046. _vq_quantthresh__44cn1_s_p8_2,
  141047. _vq_quantmap__44cn1_s_p8_2,
  141048. 17,
  141049. 17
  141050. };
  141051. static static_codebook _44cn1_s_p8_2 = {
  141052. 2, 289,
  141053. _vq_lengthlist__44cn1_s_p8_2,
  141054. 1, -529530880, 1611661312, 5, 0,
  141055. _vq_quantlist__44cn1_s_p8_2,
  141056. NULL,
  141057. &_vq_auxt__44cn1_s_p8_2,
  141058. NULL,
  141059. 0
  141060. };
  141061. static long _huff_lengthlist__44cn1_s_short[] = {
  141062. 10, 9,12,15,12,13,16,14,16, 7, 1, 5,14, 7,10,13,
  141063. 16,16, 9, 4, 6,16, 8,11,16,16,16,14, 4, 7,16, 9,
  141064. 12,14,16,16,10, 5, 7,14, 9,12,14,15,15,13, 8, 9,
  141065. 14,10,12,13,14,15,13, 9, 9, 7, 6, 8,11,12,12,14,
  141066. 8, 8, 5, 4, 5, 8,11,12,16,10,10, 6, 5, 6, 8, 9,
  141067. 10,
  141068. };
  141069. static static_codebook _huff_book__44cn1_s_short = {
  141070. 2, 81,
  141071. _huff_lengthlist__44cn1_s_short,
  141072. 0, 0, 0, 0, 0,
  141073. NULL,
  141074. NULL,
  141075. NULL,
  141076. NULL,
  141077. 0
  141078. };
  141079. static long _huff_lengthlist__44cn1_sm_long[] = {
  141080. 3, 3, 8, 8, 8, 8,10,12,14, 3, 2, 6, 7, 7, 8,10,
  141081. 12,16, 7, 6, 7, 9, 8,10,12,14,16, 8, 6, 8, 4, 5,
  141082. 7, 9,11,13, 7, 6, 8, 5, 6, 7, 9,11,14, 8, 8,10,
  141083. 7, 7, 6, 8,10,13, 9,11,12, 9, 9, 7, 8,10,12,10,
  141084. 13,15,11,11,10, 9,10,13,13,16,17,14,15,14,13,14,
  141085. 17,
  141086. };
  141087. static static_codebook _huff_book__44cn1_sm_long = {
  141088. 2, 81,
  141089. _huff_lengthlist__44cn1_sm_long,
  141090. 0, 0, 0, 0, 0,
  141091. NULL,
  141092. NULL,
  141093. NULL,
  141094. NULL,
  141095. 0
  141096. };
  141097. static long _vq_quantlist__44cn1_sm_p1_0[] = {
  141098. 1,
  141099. 0,
  141100. 2,
  141101. };
  141102. static long _vq_lengthlist__44cn1_sm_p1_0[] = {
  141103. 1, 4, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  141104. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141108. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  141109. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141113. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  141114. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  141149. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  141150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0, 0,
  141154. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  141155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  141159. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  141160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141194. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  141195. 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141199. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  141200. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  141201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141204. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10,
  141205. 0, 0, 0, 0, 0, 0, 9,10, 9, 0, 0, 0, 0, 0, 0, 0,
  141206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141513. 0,
  141514. };
  141515. static float _vq_quantthresh__44cn1_sm_p1_0[] = {
  141516. -0.5, 0.5,
  141517. };
  141518. static long _vq_quantmap__44cn1_sm_p1_0[] = {
  141519. 1, 0, 2,
  141520. };
  141521. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p1_0 = {
  141522. _vq_quantthresh__44cn1_sm_p1_0,
  141523. _vq_quantmap__44cn1_sm_p1_0,
  141524. 3,
  141525. 3
  141526. };
  141527. static static_codebook _44cn1_sm_p1_0 = {
  141528. 8, 6561,
  141529. _vq_lengthlist__44cn1_sm_p1_0,
  141530. 1, -535822336, 1611661312, 2, 0,
  141531. _vq_quantlist__44cn1_sm_p1_0,
  141532. NULL,
  141533. &_vq_auxt__44cn1_sm_p1_0,
  141534. NULL,
  141535. 0
  141536. };
  141537. static long _vq_quantlist__44cn1_sm_p2_0[] = {
  141538. 2,
  141539. 1,
  141540. 3,
  141541. 0,
  141542. 4,
  141543. };
  141544. static long _vq_lengthlist__44cn1_sm_p2_0[] = {
  141545. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  141547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141548. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  141550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141551. 0, 0, 0, 0, 7, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  141552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141584. 0,
  141585. };
  141586. static float _vq_quantthresh__44cn1_sm_p2_0[] = {
  141587. -1.5, -0.5, 0.5, 1.5,
  141588. };
  141589. static long _vq_quantmap__44cn1_sm_p2_0[] = {
  141590. 3, 1, 0, 2, 4,
  141591. };
  141592. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p2_0 = {
  141593. _vq_quantthresh__44cn1_sm_p2_0,
  141594. _vq_quantmap__44cn1_sm_p2_0,
  141595. 5,
  141596. 5
  141597. };
  141598. static static_codebook _44cn1_sm_p2_0 = {
  141599. 4, 625,
  141600. _vq_lengthlist__44cn1_sm_p2_0,
  141601. 1, -533725184, 1611661312, 3, 0,
  141602. _vq_quantlist__44cn1_sm_p2_0,
  141603. NULL,
  141604. &_vq_auxt__44cn1_sm_p2_0,
  141605. NULL,
  141606. 0
  141607. };
  141608. static long _vq_quantlist__44cn1_sm_p3_0[] = {
  141609. 4,
  141610. 3,
  141611. 5,
  141612. 2,
  141613. 6,
  141614. 1,
  141615. 7,
  141616. 0,
  141617. 8,
  141618. };
  141619. static long _vq_lengthlist__44cn1_sm_p3_0[] = {
  141620. 1, 3, 4, 7, 7, 0, 0, 0, 0, 0, 4, 4, 7, 7, 0, 0,
  141621. 0, 0, 0, 4, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  141622. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  141623. 9, 9, 0, 0, 0, 0, 0, 0, 0,10, 9, 0, 0, 0, 0, 0,
  141624. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141625. 0,
  141626. };
  141627. static float _vq_quantthresh__44cn1_sm_p3_0[] = {
  141628. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141629. };
  141630. static long _vq_quantmap__44cn1_sm_p3_0[] = {
  141631. 7, 5, 3, 1, 0, 2, 4, 6,
  141632. 8,
  141633. };
  141634. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p3_0 = {
  141635. _vq_quantthresh__44cn1_sm_p3_0,
  141636. _vq_quantmap__44cn1_sm_p3_0,
  141637. 9,
  141638. 9
  141639. };
  141640. static static_codebook _44cn1_sm_p3_0 = {
  141641. 2, 81,
  141642. _vq_lengthlist__44cn1_sm_p3_0,
  141643. 1, -531628032, 1611661312, 4, 0,
  141644. _vq_quantlist__44cn1_sm_p3_0,
  141645. NULL,
  141646. &_vq_auxt__44cn1_sm_p3_0,
  141647. NULL,
  141648. 0
  141649. };
  141650. static long _vq_quantlist__44cn1_sm_p4_0[] = {
  141651. 4,
  141652. 3,
  141653. 5,
  141654. 2,
  141655. 6,
  141656. 1,
  141657. 7,
  141658. 0,
  141659. 8,
  141660. };
  141661. static long _vq_lengthlist__44cn1_sm_p4_0[] = {
  141662. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  141663. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  141664. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  141665. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  141666. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  141667. 11,
  141668. };
  141669. static float _vq_quantthresh__44cn1_sm_p4_0[] = {
  141670. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141671. };
  141672. static long _vq_quantmap__44cn1_sm_p4_0[] = {
  141673. 7, 5, 3, 1, 0, 2, 4, 6,
  141674. 8,
  141675. };
  141676. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p4_0 = {
  141677. _vq_quantthresh__44cn1_sm_p4_0,
  141678. _vq_quantmap__44cn1_sm_p4_0,
  141679. 9,
  141680. 9
  141681. };
  141682. static static_codebook _44cn1_sm_p4_0 = {
  141683. 2, 81,
  141684. _vq_lengthlist__44cn1_sm_p4_0,
  141685. 1, -531628032, 1611661312, 4, 0,
  141686. _vq_quantlist__44cn1_sm_p4_0,
  141687. NULL,
  141688. &_vq_auxt__44cn1_sm_p4_0,
  141689. NULL,
  141690. 0
  141691. };
  141692. static long _vq_quantlist__44cn1_sm_p5_0[] = {
  141693. 8,
  141694. 7,
  141695. 9,
  141696. 6,
  141697. 10,
  141698. 5,
  141699. 11,
  141700. 4,
  141701. 12,
  141702. 3,
  141703. 13,
  141704. 2,
  141705. 14,
  141706. 1,
  141707. 15,
  141708. 0,
  141709. 16,
  141710. };
  141711. static long _vq_lengthlist__44cn1_sm_p5_0[] = {
  141712. 1, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  141713. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  141714. 12,12, 0, 6, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  141715. 11,12,12, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  141716. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,11,
  141717. 11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  141718. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  141719. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  141720. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  141721. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  141722. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  141723. 9,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0, 0,
  141724. 10,10,11,11,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  141725. 0, 0, 0,11,11,11,11,12,12,13,13,14,14, 0, 0, 0,
  141726. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  141727. 0, 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0,
  141728. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,14,14,14,14,
  141729. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,14,14,
  141730. 14,
  141731. };
  141732. static float _vq_quantthresh__44cn1_sm_p5_0[] = {
  141733. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  141734. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  141735. };
  141736. static long _vq_quantmap__44cn1_sm_p5_0[] = {
  141737. 15, 13, 11, 9, 7, 5, 3, 1,
  141738. 0, 2, 4, 6, 8, 10, 12, 14,
  141739. 16,
  141740. };
  141741. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p5_0 = {
  141742. _vq_quantthresh__44cn1_sm_p5_0,
  141743. _vq_quantmap__44cn1_sm_p5_0,
  141744. 17,
  141745. 17
  141746. };
  141747. static static_codebook _44cn1_sm_p5_0 = {
  141748. 2, 289,
  141749. _vq_lengthlist__44cn1_sm_p5_0,
  141750. 1, -529530880, 1611661312, 5, 0,
  141751. _vq_quantlist__44cn1_sm_p5_0,
  141752. NULL,
  141753. &_vq_auxt__44cn1_sm_p5_0,
  141754. NULL,
  141755. 0
  141756. };
  141757. static long _vq_quantlist__44cn1_sm_p6_0[] = {
  141758. 1,
  141759. 0,
  141760. 2,
  141761. };
  141762. static long _vq_lengthlist__44cn1_sm_p6_0[] = {
  141763. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 6,10, 9, 9,11,
  141764. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  141765. 11,11,11,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  141766. 11,10,11,11,10,10, 7,11,11,11,11,11,12,11,11, 7,
  141767. 9, 9,11,10,10,12,10,10, 7, 9, 9,11,10,10,11,10,
  141768. 10,
  141769. };
  141770. static float _vq_quantthresh__44cn1_sm_p6_0[] = {
  141771. -5.5, 5.5,
  141772. };
  141773. static long _vq_quantmap__44cn1_sm_p6_0[] = {
  141774. 1, 0, 2,
  141775. };
  141776. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_0 = {
  141777. _vq_quantthresh__44cn1_sm_p6_0,
  141778. _vq_quantmap__44cn1_sm_p6_0,
  141779. 3,
  141780. 3
  141781. };
  141782. static static_codebook _44cn1_sm_p6_0 = {
  141783. 4, 81,
  141784. _vq_lengthlist__44cn1_sm_p6_0,
  141785. 1, -529137664, 1618345984, 2, 0,
  141786. _vq_quantlist__44cn1_sm_p6_0,
  141787. NULL,
  141788. &_vq_auxt__44cn1_sm_p6_0,
  141789. NULL,
  141790. 0
  141791. };
  141792. static long _vq_quantlist__44cn1_sm_p6_1[] = {
  141793. 5,
  141794. 4,
  141795. 6,
  141796. 3,
  141797. 7,
  141798. 2,
  141799. 8,
  141800. 1,
  141801. 9,
  141802. 0,
  141803. 10,
  141804. };
  141805. static long _vq_lengthlist__44cn1_sm_p6_1[] = {
  141806. 2, 4, 4, 5, 5, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  141807. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  141808. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  141809. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  141810. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  141811. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  141812. 8, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 8, 9,10,10,
  141813. 10,10,10, 8, 9, 8, 8, 9, 8,
  141814. };
  141815. static float _vq_quantthresh__44cn1_sm_p6_1[] = {
  141816. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  141817. 3.5, 4.5,
  141818. };
  141819. static long _vq_quantmap__44cn1_sm_p6_1[] = {
  141820. 9, 7, 5, 3, 1, 0, 2, 4,
  141821. 6, 8, 10,
  141822. };
  141823. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_1 = {
  141824. _vq_quantthresh__44cn1_sm_p6_1,
  141825. _vq_quantmap__44cn1_sm_p6_1,
  141826. 11,
  141827. 11
  141828. };
  141829. static static_codebook _44cn1_sm_p6_1 = {
  141830. 2, 121,
  141831. _vq_lengthlist__44cn1_sm_p6_1,
  141832. 1, -531365888, 1611661312, 4, 0,
  141833. _vq_quantlist__44cn1_sm_p6_1,
  141834. NULL,
  141835. &_vq_auxt__44cn1_sm_p6_1,
  141836. NULL,
  141837. 0
  141838. };
  141839. static long _vq_quantlist__44cn1_sm_p7_0[] = {
  141840. 6,
  141841. 5,
  141842. 7,
  141843. 4,
  141844. 8,
  141845. 3,
  141846. 9,
  141847. 2,
  141848. 10,
  141849. 1,
  141850. 11,
  141851. 0,
  141852. 12,
  141853. };
  141854. static long _vq_lengthlist__44cn1_sm_p7_0[] = {
  141855. 1, 4, 4, 6, 6, 7, 7, 7, 7, 9, 9,10,10, 7, 5, 5,
  141856. 7, 7, 8, 8, 8, 8,10, 9,11,10, 7, 5, 5, 7, 7, 8,
  141857. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  141858. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  141859. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,12,12, 0,13,
  141860. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10,
  141861. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  141862. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,13,
  141863. 13,13, 0, 0, 0,14,14,11,10,11,11,12,12,13,13, 0,
  141864. 0, 0, 0, 0,12,12,12,12,13,13,13,14, 0, 0, 0, 0,
  141865. 0,13,12,12,12,13,13,13,14,
  141866. };
  141867. static float _vq_quantthresh__44cn1_sm_p7_0[] = {
  141868. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  141869. 12.5, 17.5, 22.5, 27.5,
  141870. };
  141871. static long _vq_quantmap__44cn1_sm_p7_0[] = {
  141872. 11, 9, 7, 5, 3, 1, 0, 2,
  141873. 4, 6, 8, 10, 12,
  141874. };
  141875. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_0 = {
  141876. _vq_quantthresh__44cn1_sm_p7_0,
  141877. _vq_quantmap__44cn1_sm_p7_0,
  141878. 13,
  141879. 13
  141880. };
  141881. static static_codebook _44cn1_sm_p7_0 = {
  141882. 2, 169,
  141883. _vq_lengthlist__44cn1_sm_p7_0,
  141884. 1, -526516224, 1616117760, 4, 0,
  141885. _vq_quantlist__44cn1_sm_p7_0,
  141886. NULL,
  141887. &_vq_auxt__44cn1_sm_p7_0,
  141888. NULL,
  141889. 0
  141890. };
  141891. static long _vq_quantlist__44cn1_sm_p7_1[] = {
  141892. 2,
  141893. 1,
  141894. 3,
  141895. 0,
  141896. 4,
  141897. };
  141898. static long _vq_lengthlist__44cn1_sm_p7_1[] = {
  141899. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  141900. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  141901. };
  141902. static float _vq_quantthresh__44cn1_sm_p7_1[] = {
  141903. -1.5, -0.5, 0.5, 1.5,
  141904. };
  141905. static long _vq_quantmap__44cn1_sm_p7_1[] = {
  141906. 3, 1, 0, 2, 4,
  141907. };
  141908. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_1 = {
  141909. _vq_quantthresh__44cn1_sm_p7_1,
  141910. _vq_quantmap__44cn1_sm_p7_1,
  141911. 5,
  141912. 5
  141913. };
  141914. static static_codebook _44cn1_sm_p7_1 = {
  141915. 2, 25,
  141916. _vq_lengthlist__44cn1_sm_p7_1,
  141917. 1, -533725184, 1611661312, 3, 0,
  141918. _vq_quantlist__44cn1_sm_p7_1,
  141919. NULL,
  141920. &_vq_auxt__44cn1_sm_p7_1,
  141921. NULL,
  141922. 0
  141923. };
  141924. static long _vq_quantlist__44cn1_sm_p8_0[] = {
  141925. 4,
  141926. 3,
  141927. 5,
  141928. 2,
  141929. 6,
  141930. 1,
  141931. 7,
  141932. 0,
  141933. 8,
  141934. };
  141935. static long _vq_lengthlist__44cn1_sm_p8_0[] = {
  141936. 1, 4, 4,12,11,13,13,14,14, 4, 7, 7,11,13,14,14,
  141937. 14,14, 3, 8, 3,14,14,14,14,14,14,14,10,12,14,14,
  141938. 14,14,14,14,14,14, 5,14, 8,14,14,14,14,14,12,14,
  141939. 13,14,14,14,14,14,14,14,13,14,10,14,14,14,14,14,
  141940. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  141941. 14,
  141942. };
  141943. static float _vq_quantthresh__44cn1_sm_p8_0[] = {
  141944. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  141945. };
  141946. static long _vq_quantmap__44cn1_sm_p8_0[] = {
  141947. 7, 5, 3, 1, 0, 2, 4, 6,
  141948. 8,
  141949. };
  141950. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_0 = {
  141951. _vq_quantthresh__44cn1_sm_p8_0,
  141952. _vq_quantmap__44cn1_sm_p8_0,
  141953. 9,
  141954. 9
  141955. };
  141956. static static_codebook _44cn1_sm_p8_0 = {
  141957. 2, 81,
  141958. _vq_lengthlist__44cn1_sm_p8_0,
  141959. 1, -516186112, 1627103232, 4, 0,
  141960. _vq_quantlist__44cn1_sm_p8_0,
  141961. NULL,
  141962. &_vq_auxt__44cn1_sm_p8_0,
  141963. NULL,
  141964. 0
  141965. };
  141966. static long _vq_quantlist__44cn1_sm_p8_1[] = {
  141967. 6,
  141968. 5,
  141969. 7,
  141970. 4,
  141971. 8,
  141972. 3,
  141973. 9,
  141974. 2,
  141975. 10,
  141976. 1,
  141977. 11,
  141978. 0,
  141979. 12,
  141980. };
  141981. static long _vq_lengthlist__44cn1_sm_p8_1[] = {
  141982. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,11,11, 6, 5, 5,
  141983. 7, 7, 8, 8,10,10,10,11,11,11, 6, 5, 5, 7, 7, 8,
  141984. 8,10,10,11,12,12,12,14, 7, 7, 7, 8, 9, 9,11,11,
  141985. 11,12,11,12,17, 7, 7, 8, 7, 9, 9,11,11,12,12,12,
  141986. 12,14,11,11, 8, 8,10,10,11,12,12,13,11,12,14,11,
  141987. 11, 8, 8,10,10,11,12,12,13,13,12,14,15,14,10,10,
  141988. 10,10,11,12,12,12,12,11,14,13,16,10,10,10, 9,12,
  141989. 11,12,12,13,14,14,15,14,14,13,10,10,11,11,12,11,
  141990. 13,11,14,12,15,13,14,11,10,12,10,12,12,13,13,13,
  141991. 13,14,15,15,12,12,11,11,12,11,13,12,14,14,14,14,
  141992. 17,12,12,11,10,13,11,13,13,
  141993. };
  141994. static float _vq_quantthresh__44cn1_sm_p8_1[] = {
  141995. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  141996. 42.5, 59.5, 76.5, 93.5,
  141997. };
  141998. static long _vq_quantmap__44cn1_sm_p8_1[] = {
  141999. 11, 9, 7, 5, 3, 1, 0, 2,
  142000. 4, 6, 8, 10, 12,
  142001. };
  142002. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_1 = {
  142003. _vq_quantthresh__44cn1_sm_p8_1,
  142004. _vq_quantmap__44cn1_sm_p8_1,
  142005. 13,
  142006. 13
  142007. };
  142008. static static_codebook _44cn1_sm_p8_1 = {
  142009. 2, 169,
  142010. _vq_lengthlist__44cn1_sm_p8_1,
  142011. 1, -522616832, 1620115456, 4, 0,
  142012. _vq_quantlist__44cn1_sm_p8_1,
  142013. NULL,
  142014. &_vq_auxt__44cn1_sm_p8_1,
  142015. NULL,
  142016. 0
  142017. };
  142018. static long _vq_quantlist__44cn1_sm_p8_2[] = {
  142019. 8,
  142020. 7,
  142021. 9,
  142022. 6,
  142023. 10,
  142024. 5,
  142025. 11,
  142026. 4,
  142027. 12,
  142028. 3,
  142029. 13,
  142030. 2,
  142031. 14,
  142032. 1,
  142033. 15,
  142034. 0,
  142035. 16,
  142036. };
  142037. static long _vq_lengthlist__44cn1_sm_p8_2[] = {
  142038. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  142039. 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  142040. 9, 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  142041. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  142042. 9, 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,
  142043. 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9, 9,
  142044. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9,
  142045. 9, 9, 9, 9, 9, 9, 9,11,10,11, 8, 8, 8, 8, 8, 8,
  142046. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11, 8, 8, 8,
  142047. 8, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  142048. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,11,11, 9,
  142049. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,10,11,11,
  142050. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,
  142051. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,
  142052. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,11,10,
  142053. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  142054. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  142055. 10,11,11,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  142056. 9,
  142057. };
  142058. static float _vq_quantthresh__44cn1_sm_p8_2[] = {
  142059. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  142060. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  142061. };
  142062. static long _vq_quantmap__44cn1_sm_p8_2[] = {
  142063. 15, 13, 11, 9, 7, 5, 3, 1,
  142064. 0, 2, 4, 6, 8, 10, 12, 14,
  142065. 16,
  142066. };
  142067. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_2 = {
  142068. _vq_quantthresh__44cn1_sm_p8_2,
  142069. _vq_quantmap__44cn1_sm_p8_2,
  142070. 17,
  142071. 17
  142072. };
  142073. static static_codebook _44cn1_sm_p8_2 = {
  142074. 2, 289,
  142075. _vq_lengthlist__44cn1_sm_p8_2,
  142076. 1, -529530880, 1611661312, 5, 0,
  142077. _vq_quantlist__44cn1_sm_p8_2,
  142078. NULL,
  142079. &_vq_auxt__44cn1_sm_p8_2,
  142080. NULL,
  142081. 0
  142082. };
  142083. static long _huff_lengthlist__44cn1_sm_short[] = {
  142084. 5, 6,12,14,12,14,16,17,18, 4, 2, 5,11, 7,10,12,
  142085. 14,15, 9, 4, 5,11, 7,10,13,15,18,15, 6, 7, 5, 6,
  142086. 8,11,13,16,11, 5, 6, 5, 5, 6, 9,13,15,12, 5, 7,
  142087. 6, 5, 6, 9,12,14,12, 6, 7, 8, 6, 7, 9,12,13,14,
  142088. 8, 8, 7, 5, 5, 8,10,12,16, 9, 9, 8, 6, 6, 7, 9,
  142089. 9,
  142090. };
  142091. static static_codebook _huff_book__44cn1_sm_short = {
  142092. 2, 81,
  142093. _huff_lengthlist__44cn1_sm_short,
  142094. 0, 0, 0, 0, 0,
  142095. NULL,
  142096. NULL,
  142097. NULL,
  142098. NULL,
  142099. 0
  142100. };
  142101. /*** End of inlined file: res_books_stereo.h ***/
  142102. /***** residue backends *********************************************/
  142103. static vorbis_info_residue0 _residue_44_low={
  142104. 0,-1, -1, 9,-1,
  142105. /* 0 1 2 3 4 5 6 7 */
  142106. {0},
  142107. {-1},
  142108. { .5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  142109. { .5, .5, .5, 999., 4.5, 8.5, 16.5, 32.5},
  142110. };
  142111. static vorbis_info_residue0 _residue_44_mid={
  142112. 0,-1, -1, 10,-1,
  142113. /* 0 1 2 3 4 5 6 7 8 */
  142114. {0},
  142115. {-1},
  142116. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  142117. { .5, .5, 999., .5, 999., 4.5, 8.5, 16.5, 32.5},
  142118. };
  142119. static vorbis_info_residue0 _residue_44_high={
  142120. 0,-1, -1, 10,-1,
  142121. /* 0 1 2 3 4 5 6 7 8 */
  142122. {0},
  142123. {-1},
  142124. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  142125. { .5, 1.5, 2.5, 3.5, 4.5, 8.5, 16.5, 71.5,157.5},
  142126. };
  142127. static static_bookblock _resbook_44s_n1={
  142128. {
  142129. {0},{0,0,&_44cn1_s_p1_0},{0,0,&_44cn1_s_p2_0},
  142130. {0,0,&_44cn1_s_p3_0},{0,0,&_44cn1_s_p4_0},{0,0,&_44cn1_s_p5_0},
  142131. {&_44cn1_s_p6_0,&_44cn1_s_p6_1},{&_44cn1_s_p7_0,&_44cn1_s_p7_1},
  142132. {&_44cn1_s_p8_0,&_44cn1_s_p8_1,&_44cn1_s_p8_2}
  142133. }
  142134. };
  142135. static static_bookblock _resbook_44sm_n1={
  142136. {
  142137. {0},{0,0,&_44cn1_sm_p1_0},{0,0,&_44cn1_sm_p2_0},
  142138. {0,0,&_44cn1_sm_p3_0},{0,0,&_44cn1_sm_p4_0},{0,0,&_44cn1_sm_p5_0},
  142139. {&_44cn1_sm_p6_0,&_44cn1_sm_p6_1},{&_44cn1_sm_p7_0,&_44cn1_sm_p7_1},
  142140. {&_44cn1_sm_p8_0,&_44cn1_sm_p8_1,&_44cn1_sm_p8_2}
  142141. }
  142142. };
  142143. static static_bookblock _resbook_44s_0={
  142144. {
  142145. {0},{0,0,&_44c0_s_p1_0},{0,0,&_44c0_s_p2_0},
  142146. {0,0,&_44c0_s_p3_0},{0,0,&_44c0_s_p4_0},{0,0,&_44c0_s_p5_0},
  142147. {&_44c0_s_p6_0,&_44c0_s_p6_1},{&_44c0_s_p7_0,&_44c0_s_p7_1},
  142148. {&_44c0_s_p8_0,&_44c0_s_p8_1,&_44c0_s_p8_2}
  142149. }
  142150. };
  142151. static static_bookblock _resbook_44sm_0={
  142152. {
  142153. {0},{0,0,&_44c0_sm_p1_0},{0,0,&_44c0_sm_p2_0},
  142154. {0,0,&_44c0_sm_p3_0},{0,0,&_44c0_sm_p4_0},{0,0,&_44c0_sm_p5_0},
  142155. {&_44c0_sm_p6_0,&_44c0_sm_p6_1},{&_44c0_sm_p7_0,&_44c0_sm_p7_1},
  142156. {&_44c0_sm_p8_0,&_44c0_sm_p8_1,&_44c0_sm_p8_2}
  142157. }
  142158. };
  142159. static static_bookblock _resbook_44s_1={
  142160. {
  142161. {0},{0,0,&_44c1_s_p1_0},{0,0,&_44c1_s_p2_0},
  142162. {0,0,&_44c1_s_p3_0},{0,0,&_44c1_s_p4_0},{0,0,&_44c1_s_p5_0},
  142163. {&_44c1_s_p6_0,&_44c1_s_p6_1},{&_44c1_s_p7_0,&_44c1_s_p7_1},
  142164. {&_44c1_s_p8_0,&_44c1_s_p8_1,&_44c1_s_p8_2}
  142165. }
  142166. };
  142167. static static_bookblock _resbook_44sm_1={
  142168. {
  142169. {0},{0,0,&_44c1_sm_p1_0},{0,0,&_44c1_sm_p2_0},
  142170. {0,0,&_44c1_sm_p3_0},{0,0,&_44c1_sm_p4_0},{0,0,&_44c1_sm_p5_0},
  142171. {&_44c1_sm_p6_0,&_44c1_sm_p6_1},{&_44c1_sm_p7_0,&_44c1_sm_p7_1},
  142172. {&_44c1_sm_p8_0,&_44c1_sm_p8_1,&_44c1_sm_p8_2}
  142173. }
  142174. };
  142175. static static_bookblock _resbook_44s_2={
  142176. {
  142177. {0},{0,0,&_44c2_s_p1_0},{0,0,&_44c2_s_p2_0},{0,0,&_44c2_s_p3_0},
  142178. {0,0,&_44c2_s_p4_0},{0,0,&_44c2_s_p5_0},{0,0,&_44c2_s_p6_0},
  142179. {&_44c2_s_p7_0,&_44c2_s_p7_1},{&_44c2_s_p8_0,&_44c2_s_p8_1},
  142180. {&_44c2_s_p9_0,&_44c2_s_p9_1,&_44c2_s_p9_2}
  142181. }
  142182. };
  142183. static static_bookblock _resbook_44s_3={
  142184. {
  142185. {0},{0,0,&_44c3_s_p1_0},{0,0,&_44c3_s_p2_0},{0,0,&_44c3_s_p3_0},
  142186. {0,0,&_44c3_s_p4_0},{0,0,&_44c3_s_p5_0},{0,0,&_44c3_s_p6_0},
  142187. {&_44c3_s_p7_0,&_44c3_s_p7_1},{&_44c3_s_p8_0,&_44c3_s_p8_1},
  142188. {&_44c3_s_p9_0,&_44c3_s_p9_1,&_44c3_s_p9_2}
  142189. }
  142190. };
  142191. static static_bookblock _resbook_44s_4={
  142192. {
  142193. {0},{0,0,&_44c4_s_p1_0},{0,0,&_44c4_s_p2_0},{0,0,&_44c4_s_p3_0},
  142194. {0,0,&_44c4_s_p4_0},{0,0,&_44c4_s_p5_0},{0,0,&_44c4_s_p6_0},
  142195. {&_44c4_s_p7_0,&_44c4_s_p7_1},{&_44c4_s_p8_0,&_44c4_s_p8_1},
  142196. {&_44c4_s_p9_0,&_44c4_s_p9_1,&_44c4_s_p9_2}
  142197. }
  142198. };
  142199. static static_bookblock _resbook_44s_5={
  142200. {
  142201. {0},{0,0,&_44c5_s_p1_0},{0,0,&_44c5_s_p2_0},{0,0,&_44c5_s_p3_0},
  142202. {0,0,&_44c5_s_p4_0},{0,0,&_44c5_s_p5_0},{0,0,&_44c5_s_p6_0},
  142203. {&_44c5_s_p7_0,&_44c5_s_p7_1},{&_44c5_s_p8_0,&_44c5_s_p8_1},
  142204. {&_44c5_s_p9_0,&_44c5_s_p9_1,&_44c5_s_p9_2}
  142205. }
  142206. };
  142207. static static_bookblock _resbook_44s_6={
  142208. {
  142209. {0},{0,0,&_44c6_s_p1_0},{0,0,&_44c6_s_p2_0},{0,0,&_44c6_s_p3_0},
  142210. {0,0,&_44c6_s_p4_0},
  142211. {&_44c6_s_p5_0,&_44c6_s_p5_1},
  142212. {&_44c6_s_p6_0,&_44c6_s_p6_1},
  142213. {&_44c6_s_p7_0,&_44c6_s_p7_1},
  142214. {&_44c6_s_p8_0,&_44c6_s_p8_1},
  142215. {&_44c6_s_p9_0,&_44c6_s_p9_1,&_44c6_s_p9_2}
  142216. }
  142217. };
  142218. static static_bookblock _resbook_44s_7={
  142219. {
  142220. {0},{0,0,&_44c7_s_p1_0},{0,0,&_44c7_s_p2_0},{0,0,&_44c7_s_p3_0},
  142221. {0,0,&_44c7_s_p4_0},
  142222. {&_44c7_s_p5_0,&_44c7_s_p5_1},
  142223. {&_44c7_s_p6_0,&_44c7_s_p6_1},
  142224. {&_44c7_s_p7_0,&_44c7_s_p7_1},
  142225. {&_44c7_s_p8_0,&_44c7_s_p8_1},
  142226. {&_44c7_s_p9_0,&_44c7_s_p9_1,&_44c7_s_p9_2}
  142227. }
  142228. };
  142229. static static_bookblock _resbook_44s_8={
  142230. {
  142231. {0},{0,0,&_44c8_s_p1_0},{0,0,&_44c8_s_p2_0},{0,0,&_44c8_s_p3_0},
  142232. {0,0,&_44c8_s_p4_0},
  142233. {&_44c8_s_p5_0,&_44c8_s_p5_1},
  142234. {&_44c8_s_p6_0,&_44c8_s_p6_1},
  142235. {&_44c8_s_p7_0,&_44c8_s_p7_1},
  142236. {&_44c8_s_p8_0,&_44c8_s_p8_1},
  142237. {&_44c8_s_p9_0,&_44c8_s_p9_1,&_44c8_s_p9_2}
  142238. }
  142239. };
  142240. static static_bookblock _resbook_44s_9={
  142241. {
  142242. {0},{0,0,&_44c9_s_p1_0},{0,0,&_44c9_s_p2_0},{0,0,&_44c9_s_p3_0},
  142243. {0,0,&_44c9_s_p4_0},
  142244. {&_44c9_s_p5_0,&_44c9_s_p5_1},
  142245. {&_44c9_s_p6_0,&_44c9_s_p6_1},
  142246. {&_44c9_s_p7_0,&_44c9_s_p7_1},
  142247. {&_44c9_s_p8_0,&_44c9_s_p8_1},
  142248. {&_44c9_s_p9_0,&_44c9_s_p9_1,&_44c9_s_p9_2}
  142249. }
  142250. };
  142251. static vorbis_residue_template _res_44s_n1[]={
  142252. {2,0, &_residue_44_low,
  142253. &_huff_book__44cn1_s_short,&_huff_book__44cn1_sm_short,
  142254. &_resbook_44s_n1,&_resbook_44sm_n1},
  142255. {2,0, &_residue_44_low,
  142256. &_huff_book__44cn1_s_long,&_huff_book__44cn1_sm_long,
  142257. &_resbook_44s_n1,&_resbook_44sm_n1}
  142258. };
  142259. static vorbis_residue_template _res_44s_0[]={
  142260. {2,0, &_residue_44_low,
  142261. &_huff_book__44c0_s_short,&_huff_book__44c0_sm_short,
  142262. &_resbook_44s_0,&_resbook_44sm_0},
  142263. {2,0, &_residue_44_low,
  142264. &_huff_book__44c0_s_long,&_huff_book__44c0_sm_long,
  142265. &_resbook_44s_0,&_resbook_44sm_0}
  142266. };
  142267. static vorbis_residue_template _res_44s_1[]={
  142268. {2,0, &_residue_44_low,
  142269. &_huff_book__44c1_s_short,&_huff_book__44c1_sm_short,
  142270. &_resbook_44s_1,&_resbook_44sm_1},
  142271. {2,0, &_residue_44_low,
  142272. &_huff_book__44c1_s_long,&_huff_book__44c1_sm_long,
  142273. &_resbook_44s_1,&_resbook_44sm_1}
  142274. };
  142275. static vorbis_residue_template _res_44s_2[]={
  142276. {2,0, &_residue_44_mid,
  142277. &_huff_book__44c2_s_short,&_huff_book__44c2_s_short,
  142278. &_resbook_44s_2,&_resbook_44s_2},
  142279. {2,0, &_residue_44_mid,
  142280. &_huff_book__44c2_s_long,&_huff_book__44c2_s_long,
  142281. &_resbook_44s_2,&_resbook_44s_2}
  142282. };
  142283. static vorbis_residue_template _res_44s_3[]={
  142284. {2,0, &_residue_44_mid,
  142285. &_huff_book__44c3_s_short,&_huff_book__44c3_s_short,
  142286. &_resbook_44s_3,&_resbook_44s_3},
  142287. {2,0, &_residue_44_mid,
  142288. &_huff_book__44c3_s_long,&_huff_book__44c3_s_long,
  142289. &_resbook_44s_3,&_resbook_44s_3}
  142290. };
  142291. static vorbis_residue_template _res_44s_4[]={
  142292. {2,0, &_residue_44_mid,
  142293. &_huff_book__44c4_s_short,&_huff_book__44c4_s_short,
  142294. &_resbook_44s_4,&_resbook_44s_4},
  142295. {2,0, &_residue_44_mid,
  142296. &_huff_book__44c4_s_long,&_huff_book__44c4_s_long,
  142297. &_resbook_44s_4,&_resbook_44s_4}
  142298. };
  142299. static vorbis_residue_template _res_44s_5[]={
  142300. {2,0, &_residue_44_mid,
  142301. &_huff_book__44c5_s_short,&_huff_book__44c5_s_short,
  142302. &_resbook_44s_5,&_resbook_44s_5},
  142303. {2,0, &_residue_44_mid,
  142304. &_huff_book__44c5_s_long,&_huff_book__44c5_s_long,
  142305. &_resbook_44s_5,&_resbook_44s_5}
  142306. };
  142307. static vorbis_residue_template _res_44s_6[]={
  142308. {2,0, &_residue_44_high,
  142309. &_huff_book__44c6_s_short,&_huff_book__44c6_s_short,
  142310. &_resbook_44s_6,&_resbook_44s_6},
  142311. {2,0, &_residue_44_high,
  142312. &_huff_book__44c6_s_long,&_huff_book__44c6_s_long,
  142313. &_resbook_44s_6,&_resbook_44s_6}
  142314. };
  142315. static vorbis_residue_template _res_44s_7[]={
  142316. {2,0, &_residue_44_high,
  142317. &_huff_book__44c7_s_short,&_huff_book__44c7_s_short,
  142318. &_resbook_44s_7,&_resbook_44s_7},
  142319. {2,0, &_residue_44_high,
  142320. &_huff_book__44c7_s_long,&_huff_book__44c7_s_long,
  142321. &_resbook_44s_7,&_resbook_44s_7}
  142322. };
  142323. static vorbis_residue_template _res_44s_8[]={
  142324. {2,0, &_residue_44_high,
  142325. &_huff_book__44c8_s_short,&_huff_book__44c8_s_short,
  142326. &_resbook_44s_8,&_resbook_44s_8},
  142327. {2,0, &_residue_44_high,
  142328. &_huff_book__44c8_s_long,&_huff_book__44c8_s_long,
  142329. &_resbook_44s_8,&_resbook_44s_8}
  142330. };
  142331. static vorbis_residue_template _res_44s_9[]={
  142332. {2,0, &_residue_44_high,
  142333. &_huff_book__44c9_s_short,&_huff_book__44c9_s_short,
  142334. &_resbook_44s_9,&_resbook_44s_9},
  142335. {2,0, &_residue_44_high,
  142336. &_huff_book__44c9_s_long,&_huff_book__44c9_s_long,
  142337. &_resbook_44s_9,&_resbook_44s_9}
  142338. };
  142339. static vorbis_mapping_template _mapres_template_44_stereo[]={
  142340. { _map_nominal, _res_44s_n1 }, /* -1 */
  142341. { _map_nominal, _res_44s_0 }, /* 0 */
  142342. { _map_nominal, _res_44s_1 }, /* 1 */
  142343. { _map_nominal, _res_44s_2 }, /* 2 */
  142344. { _map_nominal, _res_44s_3 }, /* 3 */
  142345. { _map_nominal, _res_44s_4 }, /* 4 */
  142346. { _map_nominal, _res_44s_5 }, /* 5 */
  142347. { _map_nominal, _res_44s_6 }, /* 6 */
  142348. { _map_nominal, _res_44s_7 }, /* 7 */
  142349. { _map_nominal, _res_44s_8 }, /* 8 */
  142350. { _map_nominal, _res_44s_9 }, /* 9 */
  142351. };
  142352. /*** End of inlined file: residue_44.h ***/
  142353. /*** Start of inlined file: psych_44.h ***/
  142354. /* preecho trigger settings *****************************************/
  142355. static vorbis_info_psy_global _psy_global_44[5]={
  142356. {8, /* lines per eighth octave */
  142357. {20.f,14.f,12.f,12.f,12.f,12.f,12.f},
  142358. {-60.f,-30.f,-40.f,-40.f,-40.f,-40.f,-40.f}, 2,-75.f,
  142359. -6.f,
  142360. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142361. },
  142362. {8, /* lines per eighth octave */
  142363. {14.f,10.f,10.f,10.f,10.f,10.f,10.f},
  142364. {-40.f,-30.f,-25.f,-25.f,-25.f,-25.f,-25.f}, 2,-80.f,
  142365. -6.f,
  142366. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142367. },
  142368. {8, /* lines per eighth octave */
  142369. {12.f,10.f,10.f,10.f,10.f,10.f,10.f},
  142370. {-20.f,-20.f,-15.f,-15.f,-15.f,-15.f,-15.f}, 0,-80.f,
  142371. -6.f,
  142372. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142373. },
  142374. {8, /* lines per eighth octave */
  142375. {10.f,8.f,8.f,8.f,8.f,8.f,8.f},
  142376. {-20.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-80.f,
  142377. -6.f,
  142378. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142379. },
  142380. {8, /* lines per eighth octave */
  142381. {10.f,6.f,6.f,6.f,6.f,6.f,6.f},
  142382. {-15.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-85.f,
  142383. -6.f,
  142384. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142385. },
  142386. };
  142387. /* noise compander lookups * low, mid, high quality ****************/
  142388. static compandblock _psy_compand_44[6]={
  142389. /* sub-mode Z short */
  142390. {{
  142391. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142392. 8, 9,10,11,12,13,14, 15, /* 15dB */
  142393. 16,17,18,19,20,21,22, 23, /* 23dB */
  142394. 24,25,26,27,28,29,30, 31, /* 31dB */
  142395. 32,33,34,35,36,37,38, 39, /* 39dB */
  142396. }},
  142397. /* mode_Z nominal short */
  142398. {{
  142399. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  142400. 7, 7, 7, 7, 6, 6, 6, 7, /* 15dB */
  142401. 7, 8, 9,10,11,12,13, 14, /* 23dB */
  142402. 15,16,17,17,17,18,18, 19, /* 31dB */
  142403. 19,19,20,21,22,23,24, 25, /* 39dB */
  142404. }},
  142405. /* mode A short */
  142406. {{
  142407. 0, 1, 2, 3, 4, 5, 5, 5, /* 7dB */
  142408. 6, 6, 6, 5, 4, 4, 4, 4, /* 15dB */
  142409. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  142410. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  142411. 11,12,13,14,15,16,17, 18, /* 39dB */
  142412. }},
  142413. /* sub-mode Z long */
  142414. {{
  142415. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142416. 8, 9,10,11,12,13,14, 15, /* 15dB */
  142417. 16,17,18,19,20,21,22, 23, /* 23dB */
  142418. 24,25,26,27,28,29,30, 31, /* 31dB */
  142419. 32,33,34,35,36,37,38, 39, /* 39dB */
  142420. }},
  142421. /* mode_Z nominal long */
  142422. {{
  142423. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142424. 8, 9,10,11,12,12,13, 13, /* 15dB */
  142425. 13,14,14,14,15,15,15, 15, /* 23dB */
  142426. 16,16,17,17,17,18,18, 19, /* 31dB */
  142427. 19,19,20,21,22,23,24, 25, /* 39dB */
  142428. }},
  142429. /* mode A long */
  142430. {{
  142431. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142432. 8, 8, 7, 6, 5, 4, 4, 4, /* 15dB */
  142433. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  142434. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  142435. 11,12,13,14,15,16,17, 18, /* 39dB */
  142436. }}
  142437. };
  142438. /* tonal masking curve level adjustments *************************/
  142439. static vp_adjblock _vp_tonemask_adj_longblock[12]={
  142440. /* 63 125 250 500 1 2 4 8 16 */
  142441. {{ -3, -8,-13,-15,-10,-10,-10,-10,-10,-10,-10, 0, 0, 0, 0, 0, 0}}, /* -1 */
  142442. /* {{-15,-15,-15,-15,-10, -8, -4, -2, 0, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  142443. {{ -4,-10,-14,-16,-15,-14,-13,-12,-12,-12,-11, -1, -1, -1, -1, -1, 0}}, /* 0 */
  142444. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  142445. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, -1, -1, 0}}, /* 1 */
  142446. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  142447. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -6, -3, -1, -1, -1, 0}}, /* 2 */
  142448. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  142449. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, -1, -1, 0}}, /* 3 */
  142450. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, *//* 4 */
  142451. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  142452. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  142453. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  142454. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  142455. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  142456. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  142457. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  142458. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  142459. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  142460. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  142461. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  142462. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  142463. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  142464. };
  142465. static vp_adjblock _vp_tonemask_adj_otherblock[12]={
  142466. /* 63 125 250 500 1 2 4 8 16 */
  142467. {{ -3, -8,-13,-15,-10,-10, -9, -9, -9, -9, -9, 1, 1, 1, 1, 1, 1}}, /* -1 */
  142468. /* {{-20,-20,-20,-20,-14,-12,-10, -8, -4, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  142469. {{ -4,-10,-14,-16,-14,-13,-12,-12,-11,-11,-10, 0, 0, 0, 0, 0, 0}}, /* 0 */
  142470. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  142471. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, 0, 0, 0}}, /* 1 */
  142472. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  142473. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -5, -2, -1, 0, 0, 0}}, /* 2 */
  142474. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  142475. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, 0, 0, 0}}, /* 3 */
  142476. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 4 */
  142477. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  142478. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  142479. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  142480. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  142481. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  142482. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  142483. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  142484. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  142485. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  142486. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  142487. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  142488. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  142489. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  142490. };
  142491. /* noise bias (transition block) */
  142492. static noise3 _psy_noisebias_trans[12]={
  142493. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142494. /* -1 */
  142495. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142496. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142497. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142498. /* 0
  142499. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142500. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 4, 10},
  142501. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  142502. {{{-15,-15,-15,-15,-15,-12, -6, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142503. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 3, 6},
  142504. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},
  142505. /* 1
  142506. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142507. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  142508. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  142509. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142510. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  142511. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  142512. /* 2
  142513. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142514. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  142515. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}}, */
  142516. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142517. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  142518. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -7, -4}}},
  142519. /* 3
  142520. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142521. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  142522. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142523. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142524. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  142525. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  142526. /* 4
  142527. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142528. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  142529. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142530. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142531. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  142532. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  142533. /* 5
  142534. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142535. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  142536. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}}, */
  142537. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142538. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  142539. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},
  142540. /* 6
  142541. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142542. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  142543. {-34,-34,-34,-34,-30,-26,-24,-18,-17,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  142544. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142545. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  142546. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},
  142547. /* 7
  142548. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142549. {-32,-32,-32,-32,-28,-24,-24,-18,-14,-12,-10, -8, -8, -8, -6, -4, 0},
  142550. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},*/
  142551. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142552. {-32,-32,-32,-32,-28,-24,-24,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  142553. {-34,-34,-34,-34,-30,-26,-26,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  142554. /* 8
  142555. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  142556. {-36,-36,-36,-36,-30,-30,-30,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  142557. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  142558. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  142559. {-36,-36,-36,-36,-30,-30,-30,-24,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  142560. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142561. /* 9
  142562. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142563. {-36,-36,-36,-36,-34,-32,-32,-28,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  142564. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  142565. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142566. {-38,-38,-38,-38,-36,-34,-34,-30,-24,-20,-20,-20,-20,-18,-16,-12,-10},
  142567. {-40,-40,-40,-40,-40,-40,-40,-38,-35,-35,-35,-35,-35,-35,-35,-35,-30}}},
  142568. /* 10 */
  142569. {{{-30,-30,-30,-30,-30,-30,-30,-28,-20,-14,-14,-14,-14,-14,-14,-12,-10},
  142570. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-20},
  142571. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142572. };
  142573. /* noise bias (long block) */
  142574. static noise3 _psy_noisebias_long[12]={
  142575. /*63 125 250 500 1k 2k 4k 8k 16k*/
  142576. /* -1 */
  142577. {{{-10,-10,-10,-10,-10, -4, 0, 0, 0, 6, 6, 6, 6, 10, 10, 12, 20},
  142578. {-20,-20,-20,-20,-20,-20,-10, -2, 0, 0, 0, 0, 0, 2, 4, 6, 15},
  142579. {-20,-20,-20,-20,-20,-20,-20,-10, -6, -6, -6, -6, -6, -4, -4, -4, -2}}},
  142580. /* 0 */
  142581. /* {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  142582. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 4, 10},
  142583. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  142584. {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  142585. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 3, 6},
  142586. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},
  142587. /* 1 */
  142588. /* {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142589. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  142590. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  142591. {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142592. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  142593. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  142594. /* 2 */
  142595. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142596. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  142597. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142598. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142599. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  142600. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  142601. /* 3 */
  142602. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142603. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  142604. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142605. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142606. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  142607. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -5}}},
  142608. /* 4 */
  142609. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142610. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  142611. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142612. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142613. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  142614. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -7}}},
  142615. /* 5 */
  142616. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142617. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  142618. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},*/
  142619. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142620. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  142621. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -8}}},
  142622. /* 6 */
  142623. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142624. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  142625. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  142626. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142627. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  142628. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12,-10}}},
  142629. /* 7 */
  142630. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142631. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-10, -8, -8, -8, -8, -6, -4, 0},
  142632. {-26,-26,-26,-26,-26,-26,-26,-22,-20,-19,-19,-19,-19,-18,-17,-16,-12}}},
  142633. /* 8 */
  142634. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 0, 0, 0, 0, 1, 2, 3, 7},
  142635. {-26,-26,-26,-26,-26,-26,-26,-20,-16,-12,-10,-10,-10,-10, -8, -6, -2},
  142636. {-28,-28,-28,-28,-28,-28,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  142637. /* 9 */
  142638. {{{-22,-22,-22,-22,-22,-22,-22,-18,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142639. {-26,-26,-26,-26,-26,-26,-26,-22,-18,-16,-16,-16,-16,-14,-12,-10, -7},
  142640. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142641. /* 10 */
  142642. {{{-24,-24,-24,-24,-24,-24,-24,-24,-24,-18,-14,-14,-14,-14,-14,-12,-10},
  142643. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-20},
  142644. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142645. };
  142646. /* noise bias (impulse block) */
  142647. static noise3 _psy_noisebias_impulse[12]={
  142648. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142649. /* -1 */
  142650. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142651. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142652. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142653. /* 0 */
  142654. /* {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  142655. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 4, 10},
  142656. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},*/
  142657. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  142658. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 3, 6},
  142659. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142660. /* 1 */
  142661. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  142662. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -4, -4, -2, -2, -2, -2, 2},
  142663. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8,-10,-10, -8, -8, -8, -6, -4}}},
  142664. /* 2 */
  142665. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142666. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142667. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142668. /* 3 */
  142669. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  142670. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142671. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142672. /* 4 */
  142673. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  142674. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142675. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142676. /* 5 */
  142677. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142678. {-32,-32,-32,-32,-28,-24,-22,-16,-10, -6, -8, -8, -6, -6, -6, -4, -2},
  142679. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-12,-12,-12,-12,-12,-10, -9, -5}}},
  142680. /* 6
  142681. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142682. {-34,-34,-34,-34,-30,-30,-24,-20,-12,-12,-14,-14,-10, -9, -8, -6, -4},
  142683. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-15,-15,-15,-15,-15,-13,-12, -8}}},*/
  142684. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142685. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-16,-16,-16,-16,-16,-14,-14,-12},
  142686. {-36,-36,-36,-36,-36,-34,-28,-24,-20,-20,-20,-20,-20,-20,-20,-18,-16}}},
  142687. /* 7 */
  142688. /* {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  142689. {-34,-34,-34,-34,-30,-30,-24,-20,-14,-14,-16,-16,-14,-12,-10,-10,-10},
  142690. {-34,-34,-34,-34,-32,-32,-30,-24,-20,-19,-19,-19,-19,-19,-17,-16,-12}}},*/
  142691. {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  142692. {-34,-34,-34,-34,-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-24,-22},
  142693. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  142694. /* 8 */
  142695. /* {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  142696. {-34,-34,-34,-34,-30,-30,-30,-24,-20,-20,-20,-20,-20,-18,-16,-16,-14},
  142697. {-36,-36,-36,-36,-36,-34,-28,-24,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  142698. {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  142699. {-34,-34,-34,-34,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-24},
  142700. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  142701. /* 9 */
  142702. /* {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142703. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-22,-20,-20,-18},
  142704. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  142705. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142706. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26},
  142707. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142708. /* 10 */
  142709. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-16,-16,-16,-16,-16,-14,-12},
  142710. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-26},
  142711. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142712. };
  142713. /* noise bias (padding block) */
  142714. static noise3 _psy_noisebias_padding[12]={
  142715. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142716. /* -1 */
  142717. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142718. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142719. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142720. /* 0 */
  142721. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142722. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, 2, 3, 6, 6, 8, 10},
  142723. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -4, -4, -4, -4, -2, 0, 2}}},
  142724. /* 1 */
  142725. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  142726. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  142727. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -6, -4, -2, 0}}},
  142728. /* 2 */
  142729. /* {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142730. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  142731. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},*/
  142732. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142733. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  142734. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142735. /* 3 */
  142736. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  142737. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  142738. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142739. /* 4 */
  142740. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  142741. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, -1, 0, 2, 6},
  142742. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142743. /* 5 */
  142744. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142745. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -3, -3, -3, -3, -2, 0, 4},
  142746. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-10,-10,-10,-10,-10, -8, -5, -3}}},
  142747. /* 6 */
  142748. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142749. {-34,-34,-34,-34,-30,-30,-24,-20,-14, -8, -4, -4, -4, -4, -3, -1, 4},
  142750. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-13,-13,-13,-13,-13,-11, -8, -6}}},
  142751. /* 7 */
  142752. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142753. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-10, -8, -6, -6, -6, -5, -3, 1},
  142754. {-34,-34,-34,-34,-32,-32,-28,-22,-18,-16,-16,-16,-16,-16,-14,-12,-10}}},
  142755. /* 8 */
  142756. {{{-22,-22,-22,-22,-22,-20,-14,-10, -4, 0, 0, 0, 0, 3, 5, 5, 11},
  142757. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-12,-10, -8, -8, -8, -7, -5, -2},
  142758. {-36,-36,-36,-36,-36,-34,-28,-22,-20,-20,-20,-20,-20,-20,-20,-16,-14}}},
  142759. /* 9 */
  142760. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -2, -2, -2, -2, 0, 2, 6},
  142761. {-36,-36,-36,-36,-34,-32,-32,-24,-16,-12,-12,-12,-12,-12,-10, -8, -5},
  142762. {-40,-40,-40,-40,-40,-40,-40,-32,-26,-24,-24,-24,-24,-24,-24,-20,-18}}},
  142763. /* 10 */
  142764. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-12,-12,-12,-12,-12,-10, -8},
  142765. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-25,-25,-25,-25,-25,-25,-15},
  142766. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142767. };
  142768. static noiseguard _psy_noiseguards_44[4]={
  142769. {3,3,15},
  142770. {3,3,15},
  142771. {10,10,100},
  142772. {10,10,100},
  142773. };
  142774. static int _psy_tone_suppress[12]={
  142775. -20,-20,-20,-20,-20,-24,-30,-40,-40,-45,-45,-45,
  142776. };
  142777. static int _psy_tone_0dB[12]={
  142778. 90,90,95,95,95,95,105,105,105,105,105,105,
  142779. };
  142780. static int _psy_noise_suppress[12]={
  142781. -20,-20,-24,-24,-24,-24,-30,-40,-40,-45,-45,-45,
  142782. };
  142783. static vorbis_info_psy _psy_info_template={
  142784. /* blockflag */
  142785. -1,
  142786. /* ath_adjatt, ath_maxatt */
  142787. -140.,-140.,
  142788. /* tonemask att boost/decay,suppr,curves */
  142789. {0.f,0.f,0.f}, 0.,0., -40.f, {0.},
  142790. /*noisemaskp,supp, low/high window, low/hi guard, minimum */
  142791. 1, -0.f, .5f, .5f, 0,0,0,
  142792. /* noiseoffset*3, noisecompand, max_curve_dB */
  142793. {{-1},{-1},{-1}},{-1},105.f,
  142794. /* noise normalization - channel_p, point_p, start, partition, thresh. */
  142795. 0,0,-1,-1,0.,
  142796. };
  142797. /* ath ****************/
  142798. static int _psy_ath_floater[12]={
  142799. -100,-100,-100,-100,-100,-100,-105,-105,-105,-105,-110,-120,
  142800. };
  142801. static int _psy_ath_abs[12]={
  142802. -130,-130,-130,-130,-140,-140,-140,-140,-140,-140,-140,-150,
  142803. };
  142804. /* stereo setup. These don't map directly to quality level, there's
  142805. an additional indirection as several of the below may be used in a
  142806. single bitmanaged stream
  142807. ****************/
  142808. /* various stereo possibilities */
  142809. /* stereo mode by base quality level */
  142810. static adj_stereo _psy_stereo_modes_44[12]={
  142811. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 -1 */
  142812. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  142813. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  142814. { 1, 2, 3, 4, 4, 4, 4, 4, 4, 5, 6, 7, 8, 8, 8},
  142815. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  142816. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 0 */
  142817. /*{{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  142818. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  142819. { 1, 2, 3, 4, 5, 5, 6, 6, 6, 6, 6, 7, 8, 8, 8},
  142820. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142821. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 1, 0, 0, 0, 0, 0},
  142822. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  142823. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142824. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  142825. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 */
  142826. {{ 3, 3, 3, 3, 3, 3, 3, 3, 2, 1, 0, 0, 0, 0, 0},
  142827. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  142828. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142829. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142830. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 2 */
  142831. /* {{ 3, 3, 3, 3, 3, 3, 2, 2, 2, 1, 0, 0, 0, 0, 0},
  142832. { 8, 8, 8, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3, 2, 1},
  142833. { 3, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142834. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  142835. {{ 3, 3, 3, 3, 3, 3, 3, 2, 1, 1, 0, 0, 0, 0, 0},
  142836. { 8, 8, 6, 6, 5, 5, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  142837. { 3, 4, 4, 5, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142838. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142839. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 3 */
  142840. {{ 2, 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0},
  142841. { 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  142842. { 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 10, 10, 10, 10, 10},
  142843. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142844. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 4 */
  142845. {{ 2, 2, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142846. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 2, 1, 0},
  142847. { 6, 6, 6, 8, 8, 8, 8, 8, 8, 8, 10, 10, 10, 10, 10},
  142848. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142849. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 5 */
  142850. /* {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142851. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  142852. { 6, 6, 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142853. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142854. {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142855. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  142856. { 6, 7, 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12},
  142857. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142858. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 6 */
  142859. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142860. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142861. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142862. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  142863. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142864. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142865. { 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142866. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142867. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 7 */
  142868. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142869. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142870. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142871. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142872. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142873. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142874. { 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142875. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142876. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 8 */
  142877. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142878. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142879. { 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142880. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142881. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142882. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142883. { 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142884. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142885. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 9 */
  142886. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142887. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142888. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  142889. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142890. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 10 */
  142891. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142892. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142893. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  142894. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142895. };
  142896. /* tone master attenuation by base quality mode and bitrate tweak */
  142897. static att3 _psy_tone_masteratt_44[12]={
  142898. {{ 35, 21, 9}, 0, 0}, /* -1 */
  142899. {{ 30, 20, 8}, -2, 1.25}, /* 0 */
  142900. /* {{ 25, 14, 4}, 0, 0}, *//* 1 */
  142901. {{ 25, 12, 2}, 0, 0}, /* 1 */
  142902. /* {{ 20, 10, -2}, 0, 0}, *//* 2 */
  142903. {{ 20, 9, -3}, 0, 0}, /* 2 */
  142904. {{ 20, 9, -4}, 0, 0}, /* 3 */
  142905. {{ 20, 9, -4}, 0, 0}, /* 4 */
  142906. {{ 20, 6, -6}, 0, 0}, /* 5 */
  142907. {{ 20, 3, -10}, 0, 0}, /* 6 */
  142908. {{ 18, 1, -14}, 0, 0}, /* 7 */
  142909. {{ 18, 0, -16}, 0, 0}, /* 8 */
  142910. {{ 18, -2, -16}, 0, 0}, /* 9 */
  142911. {{ 12, -2, -20}, 0, 0}, /* 10 */
  142912. };
  142913. /* lowpass by mode **************/
  142914. static double _psy_lowpass_44[12]={
  142915. /* 15.1,15.8,16.5,17.9,20.5,48.,999.,999.,999.,999.,999. */
  142916. 13.9,15.1,15.8,16.5,17.2,18.9,20.1,48.,999.,999.,999.,999.
  142917. };
  142918. /* noise normalization **********/
  142919. static int _noise_start_short_44[11]={
  142920. /* 16,16,16,16,32,32,9999,9999,9999,9999 */
  142921. 32,16,16,16,32,9999,9999,9999,9999,9999,9999
  142922. };
  142923. static int _noise_start_long_44[11]={
  142924. /* 128,128,128,256,512,512,9999,9999,9999,9999 */
  142925. 256,128,128,256,512,9999,9999,9999,9999,9999,9999
  142926. };
  142927. static int _noise_part_short_44[11]={
  142928. 8,8,8,8,8,8,8,8,8,8,8
  142929. };
  142930. static int _noise_part_long_44[11]={
  142931. 32,32,32,32,32,32,32,32,32,32,32
  142932. };
  142933. static double _noise_thresh_44[11]={
  142934. /* .2,.2,.3,.4,.5,.5,9999.,9999.,9999.,9999., */
  142935. .2,.2,.2,.4,.6,9999.,9999.,9999.,9999.,9999.,9999.,
  142936. };
  142937. static double _noise_thresh_5only[2]={
  142938. .5,.5,
  142939. };
  142940. /*** End of inlined file: psych_44.h ***/
  142941. static double rate_mapping_44_stereo[12]={
  142942. 22500.,32000.,40000.,48000.,56000.,64000.,
  142943. 80000.,96000.,112000.,128000.,160000.,250001.
  142944. };
  142945. static double quality_mapping_44[12]={
  142946. -.1,.0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1.0
  142947. };
  142948. static int blocksize_short_44[11]={
  142949. 512,256,256,256,256,256,256,256,256,256,256
  142950. };
  142951. static int blocksize_long_44[11]={
  142952. 4096,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048
  142953. };
  142954. static double _psy_compand_short_mapping[12]={
  142955. 0.5, 1., 1., 1.3, 1.6, 2., 2., 2., 2., 2., 2., 2.
  142956. };
  142957. static double _psy_compand_long_mapping[12]={
  142958. 3.5, 4., 4., 4.3, 4.6, 5., 5., 5., 5., 5., 5., 5.
  142959. };
  142960. static double _global_mapping_44[12]={
  142961. /* 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.5, 4., 4. */
  142962. 0., 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.7, 4., 4.
  142963. };
  142964. static int _floor_short_mapping_44[11]={
  142965. 1,0,0,2,2,4,5,5,5,5,5
  142966. };
  142967. static int _floor_long_mapping_44[11]={
  142968. 8,7,7,7,7,7,7,7,7,7,7
  142969. };
  142970. ve_setup_data_template ve_setup_44_stereo={
  142971. 11,
  142972. rate_mapping_44_stereo,
  142973. quality_mapping_44,
  142974. 2,
  142975. 40000,
  142976. 50000,
  142977. blocksize_short_44,
  142978. blocksize_long_44,
  142979. _psy_tone_masteratt_44,
  142980. _psy_tone_0dB,
  142981. _psy_tone_suppress,
  142982. _vp_tonemask_adj_otherblock,
  142983. _vp_tonemask_adj_longblock,
  142984. _vp_tonemask_adj_otherblock,
  142985. _psy_noiseguards_44,
  142986. _psy_noisebias_impulse,
  142987. _psy_noisebias_padding,
  142988. _psy_noisebias_trans,
  142989. _psy_noisebias_long,
  142990. _psy_noise_suppress,
  142991. _psy_compand_44,
  142992. _psy_compand_short_mapping,
  142993. _psy_compand_long_mapping,
  142994. {_noise_start_short_44,_noise_start_long_44},
  142995. {_noise_part_short_44,_noise_part_long_44},
  142996. _noise_thresh_44,
  142997. _psy_ath_floater,
  142998. _psy_ath_abs,
  142999. _psy_lowpass_44,
  143000. _psy_global_44,
  143001. _global_mapping_44,
  143002. _psy_stereo_modes_44,
  143003. _floor_books,
  143004. _floor,
  143005. _floor_short_mapping_44,
  143006. _floor_long_mapping_44,
  143007. _mapres_template_44_stereo
  143008. };
  143009. /*** End of inlined file: setup_44.h ***/
  143010. /*** Start of inlined file: setup_44u.h ***/
  143011. /*** Start of inlined file: residue_44u.h ***/
  143012. /*** Start of inlined file: res_books_uncoupled.h ***/
  143013. static long _vq_quantlist__16u0__p1_0[] = {
  143014. 1,
  143015. 0,
  143016. 2,
  143017. };
  143018. static long _vq_lengthlist__16u0__p1_0[] = {
  143019. 1, 4, 4, 5, 7, 7, 5, 7, 8, 5, 8, 8, 8,10,10, 8,
  143020. 10,11, 5, 8, 8, 8,10,10, 8,10,10, 4, 9, 9, 9,12,
  143021. 11, 8,11,11, 8,12,11,10,12,14,10,13,13, 7,11,11,
  143022. 10,14,12,11,14,14, 4, 9, 9, 8,11,11, 9,11,12, 7,
  143023. 11,11,10,13,14,10,12,14, 8,11,12,10,14,14,10,13,
  143024. 12,
  143025. };
  143026. static float _vq_quantthresh__16u0__p1_0[] = {
  143027. -0.5, 0.5,
  143028. };
  143029. static long _vq_quantmap__16u0__p1_0[] = {
  143030. 1, 0, 2,
  143031. };
  143032. static encode_aux_threshmatch _vq_auxt__16u0__p1_0 = {
  143033. _vq_quantthresh__16u0__p1_0,
  143034. _vq_quantmap__16u0__p1_0,
  143035. 3,
  143036. 3
  143037. };
  143038. static static_codebook _16u0__p1_0 = {
  143039. 4, 81,
  143040. _vq_lengthlist__16u0__p1_0,
  143041. 1, -535822336, 1611661312, 2, 0,
  143042. _vq_quantlist__16u0__p1_0,
  143043. NULL,
  143044. &_vq_auxt__16u0__p1_0,
  143045. NULL,
  143046. 0
  143047. };
  143048. static long _vq_quantlist__16u0__p2_0[] = {
  143049. 1,
  143050. 0,
  143051. 2,
  143052. };
  143053. static long _vq_lengthlist__16u0__p2_0[] = {
  143054. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 9, 7,
  143055. 8, 9, 5, 7, 7, 7, 9, 8, 7, 9, 7, 4, 7, 7, 7, 9,
  143056. 9, 7, 8, 8, 6, 9, 8, 7, 8,11, 9,11,10, 6, 8, 9,
  143057. 8,11, 8, 9,10,11, 4, 7, 7, 7, 8, 8, 7, 9, 9, 6,
  143058. 9, 8, 9,11,10, 8, 8,11, 6, 8, 9, 9,10,11, 8,11,
  143059. 8,
  143060. };
  143061. static float _vq_quantthresh__16u0__p2_0[] = {
  143062. -0.5, 0.5,
  143063. };
  143064. static long _vq_quantmap__16u0__p2_0[] = {
  143065. 1, 0, 2,
  143066. };
  143067. static encode_aux_threshmatch _vq_auxt__16u0__p2_0 = {
  143068. _vq_quantthresh__16u0__p2_0,
  143069. _vq_quantmap__16u0__p2_0,
  143070. 3,
  143071. 3
  143072. };
  143073. static static_codebook _16u0__p2_0 = {
  143074. 4, 81,
  143075. _vq_lengthlist__16u0__p2_0,
  143076. 1, -535822336, 1611661312, 2, 0,
  143077. _vq_quantlist__16u0__p2_0,
  143078. NULL,
  143079. &_vq_auxt__16u0__p2_0,
  143080. NULL,
  143081. 0
  143082. };
  143083. static long _vq_quantlist__16u0__p3_0[] = {
  143084. 2,
  143085. 1,
  143086. 3,
  143087. 0,
  143088. 4,
  143089. };
  143090. static long _vq_lengthlist__16u0__p3_0[] = {
  143091. 1, 5, 5, 7, 7, 6, 7, 7, 8, 8, 6, 7, 8, 8, 8, 8,
  143092. 9, 9,11,11, 8, 9, 9,11,11, 6, 9, 8,10,10, 8,10,
  143093. 10,11,11, 8,10,10,11,11,10,11,10,13,12, 9,11,10,
  143094. 13,13, 6, 8, 9,10,10, 8,10,10,11,11, 8,10,10,11,
  143095. 11, 9,10,11,13,12,10,10,11,12,12, 8,11,11,14,13,
  143096. 10,12,11,15,13, 9,12,11,15,14,12,14,13,16,14,12,
  143097. 13,13,17,14, 8,11,11,13,14, 9,11,12,14,15,10,11,
  143098. 12,13,15,11,13,13,14,16,12,13,14,14,16, 5, 9, 9,
  143099. 11,11, 9,11,11,12,12, 8,11,11,12,12,11,12,12,15,
  143100. 14,10,12,12,15,15, 8,11,11,13,12,10,12,12,13,13,
  143101. 10,12,12,14,13,12,12,13,14,15,11,13,13,17,16, 7,
  143102. 11,11,13,13,10,12,12,14,13,10,12,12,13,14,12,13,
  143103. 12,15,14,11,13,13,15,14, 9,12,12,16,15,11,13,13,
  143104. 17,16,10,13,13,16,16,13,14,15,15,16,13,15,14,19,
  143105. 17, 9,12,12,14,16,11,13,13,15,16,10,13,13,17,16,
  143106. 13,14,13,17,15,12,15,15,16,17, 5, 9, 9,11,11, 8,
  143107. 11,11,13,12, 9,11,11,12,12,10,12,12,14,15,11,12,
  143108. 12,14,14, 7,11,10,13,12,10,12,12,14,13,10,11,12,
  143109. 13,13,11,13,13,15,16,12,12,13,15,15, 7,11,11,13,
  143110. 13,10,13,13,14,14,10,12,12,13,13,11,13,13,16,15,
  143111. 12,13,13,15,14, 9,12,12,15,15,10,13,13,17,16,11,
  143112. 12,13,15,15,12,15,14,18,18,13,14,14,16,17, 9,12,
  143113. 12,15,16,10,13,13,15,16,11,13,13,15,16,13,15,15,
  143114. 17,17,13,15,14,16,15, 7,11,11,15,16,10,13,12,16,
  143115. 17,10,12,13,15,17,15,16,16,18,17,13,15,15,17,18,
  143116. 8,12,12,16,16,11,13,14,17,18,11,13,13,18,16,15,
  143117. 17,16,17,19,14,15,15,17,16, 8,12,12,16,15,11,14,
  143118. 13,18,17,11,13,14,18,17,15,16,16,18,17,13,16,16,
  143119. 18,18,11,15,14,18,17,13,14,15,18, 0,12,15,15, 0,
  143120. 17,17,16,17,17,18,14,16,18,18, 0,11,14,14,17, 0,
  143121. 12,15,14,17,19,12,15,14,18, 0,15,18,16, 0,17,14,
  143122. 18,16,18, 0, 7,11,11,16,15,10,12,12,18,16,10,13,
  143123. 13,16,15,13,15,14,17,17,14,16,16,19,18, 8,12,12,
  143124. 16,16,11,13,13,18,16,11,13,14,17,16,14,15,15,19,
  143125. 18,15,16,16, 0,19, 8,12,12,16,17,11,13,13,17,17,
  143126. 11,14,13,17,17,13,15,15,17,19,15,17,17,19, 0,11,
  143127. 14,15,19,17,12,15,16,18,18,12,14,15,19,17,14,16,
  143128. 17, 0,18,16,16,19,17, 0,11,14,14,18,19,12,15,14,
  143129. 17,17,13,16,14,17,16,14,17,16,18,18,15,18,15, 0,
  143130. 18,
  143131. };
  143132. static float _vq_quantthresh__16u0__p3_0[] = {
  143133. -1.5, -0.5, 0.5, 1.5,
  143134. };
  143135. static long _vq_quantmap__16u0__p3_0[] = {
  143136. 3, 1, 0, 2, 4,
  143137. };
  143138. static encode_aux_threshmatch _vq_auxt__16u0__p3_0 = {
  143139. _vq_quantthresh__16u0__p3_0,
  143140. _vq_quantmap__16u0__p3_0,
  143141. 5,
  143142. 5
  143143. };
  143144. static static_codebook _16u0__p3_0 = {
  143145. 4, 625,
  143146. _vq_lengthlist__16u0__p3_0,
  143147. 1, -533725184, 1611661312, 3, 0,
  143148. _vq_quantlist__16u0__p3_0,
  143149. NULL,
  143150. &_vq_auxt__16u0__p3_0,
  143151. NULL,
  143152. 0
  143153. };
  143154. static long _vq_quantlist__16u0__p4_0[] = {
  143155. 2,
  143156. 1,
  143157. 3,
  143158. 0,
  143159. 4,
  143160. };
  143161. static long _vq_lengthlist__16u0__p4_0[] = {
  143162. 3, 5, 5, 8, 8, 6, 6, 6, 9, 9, 6, 6, 6, 9, 9, 9,
  143163. 10, 9,11,11, 9, 9, 9,11,11, 6, 7, 7,10,10, 7, 7,
  143164. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  143165. 11,12, 6, 7, 7,10,10, 7, 8, 7,10,10, 7, 8, 7,10,
  143166. 10,10,11,10,12,11,10,10,10,13,10, 9,10,10,12,12,
  143167. 10,11,10,14,12, 9,11,11,13,13,11,12,13,13,13,11,
  143168. 12,12,15,13, 9,10,10,12,13, 9,11,10,12,13,10,10,
  143169. 11,12,13,11,12,12,12,13,11,12,12,13,13, 5, 7, 7,
  143170. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  143171. 13,10,10,11,12,12, 6, 8, 8,11,10, 7, 8, 9,10,12,
  143172. 8, 9, 9,11,11,11,10,11,11,12,10,11,11,13,12, 7,
  143173. 8, 8,10,11, 8, 9, 8,11,10, 8, 9, 9,11,11,10,12,
  143174. 10,13,11,10,11,11,13,13,10,11,10,14,13,10,10,11,
  143175. 13,13,10,12,11,14,13,12,11,13,12,13,13,12,13,14,
  143176. 14,10,11,11,13,13,10,11,10,12,13,10,12,12,12,14,
  143177. 12,12,12,14,12,12,13,12,17,15, 5, 7, 7,10,10, 7,
  143178. 8, 8,10,10, 7, 8, 8,11,10,10,10,11,12,12,10,11,
  143179. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  143180. 10,11,11,11,11,12,12,10,10,11,12,13, 6, 8, 8,10,
  143181. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,12,12,13,13,
  143182. 11,11,10,13,11, 9,11,10,14,13,11,11,11,15,13,10,
  143183. 10,11,13,13,12,13,13,14,14,12,11,12,12,13,10,11,
  143184. 11,12,13,10,11,12,13,13,10,11,10,13,12,12,12,13,
  143185. 14, 0,12,13,11,13,11, 8,10,10,13,13,10,11,11,14,
  143186. 13,10,11,11,13,12,13,14,14,14,15,12,12,12,15,14,
  143187. 9,11,10,13,12,10,10,11,13,14,11,11,11,15,12,13,
  143188. 12,14,15,16,13,13,13,14,13, 9,11,11,12,12,10,12,
  143189. 11,13,13,10,11,11,13,14,13,13,13,15,15,13,13,14,
  143190. 17,15,11,12,12,14,14,10,11,12,13,15,12,13,13, 0,
  143191. 15,13,11,14,12,16,14,16,14, 0,15,11,12,12,14,16,
  143192. 11,13,12,16,15,12,13,13,14,15,12,14,12,15,13,15,
  143193. 14,14,16,16, 8,10,10,13,13,10,11,10,13,14,10,11,
  143194. 11,13,13,13,13,12,14,14,14,13,13,16,17, 9,10,10,
  143195. 12,14,10,12,11,14,13,10,11,12,13,14,12,12,12,15,
  143196. 15,13,13,13,14,14, 9,10,10,13,13,10,11,12,12,14,
  143197. 10,11,10,13,13,13,13,13,14,16,13,13,13,14,14,11,
  143198. 12,13,15,13,12,14,13,14,16,12,12,13,13,14,13,14,
  143199. 14,17,15,13,12,17,13,16,11,12,13,14,15,12,13,14,
  143200. 14,17,11,12,11,14,14,13,16,14,16, 0,14,15,11,15,
  143201. 11,
  143202. };
  143203. static float _vq_quantthresh__16u0__p4_0[] = {
  143204. -1.5, -0.5, 0.5, 1.5,
  143205. };
  143206. static long _vq_quantmap__16u0__p4_0[] = {
  143207. 3, 1, 0, 2, 4,
  143208. };
  143209. static encode_aux_threshmatch _vq_auxt__16u0__p4_0 = {
  143210. _vq_quantthresh__16u0__p4_0,
  143211. _vq_quantmap__16u0__p4_0,
  143212. 5,
  143213. 5
  143214. };
  143215. static static_codebook _16u0__p4_0 = {
  143216. 4, 625,
  143217. _vq_lengthlist__16u0__p4_0,
  143218. 1, -533725184, 1611661312, 3, 0,
  143219. _vq_quantlist__16u0__p4_0,
  143220. NULL,
  143221. &_vq_auxt__16u0__p4_0,
  143222. NULL,
  143223. 0
  143224. };
  143225. static long _vq_quantlist__16u0__p5_0[] = {
  143226. 4,
  143227. 3,
  143228. 5,
  143229. 2,
  143230. 6,
  143231. 1,
  143232. 7,
  143233. 0,
  143234. 8,
  143235. };
  143236. static long _vq_lengthlist__16u0__p5_0[] = {
  143237. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  143238. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  143239. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 7, 8, 8,
  143240. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  143241. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,10,11,11,12,
  143242. 12,
  143243. };
  143244. static float _vq_quantthresh__16u0__p5_0[] = {
  143245. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143246. };
  143247. static long _vq_quantmap__16u0__p5_0[] = {
  143248. 7, 5, 3, 1, 0, 2, 4, 6,
  143249. 8,
  143250. };
  143251. static encode_aux_threshmatch _vq_auxt__16u0__p5_0 = {
  143252. _vq_quantthresh__16u0__p5_0,
  143253. _vq_quantmap__16u0__p5_0,
  143254. 9,
  143255. 9
  143256. };
  143257. static static_codebook _16u0__p5_0 = {
  143258. 2, 81,
  143259. _vq_lengthlist__16u0__p5_0,
  143260. 1, -531628032, 1611661312, 4, 0,
  143261. _vq_quantlist__16u0__p5_0,
  143262. NULL,
  143263. &_vq_auxt__16u0__p5_0,
  143264. NULL,
  143265. 0
  143266. };
  143267. static long _vq_quantlist__16u0__p6_0[] = {
  143268. 6,
  143269. 5,
  143270. 7,
  143271. 4,
  143272. 8,
  143273. 3,
  143274. 9,
  143275. 2,
  143276. 10,
  143277. 1,
  143278. 11,
  143279. 0,
  143280. 12,
  143281. };
  143282. static long _vq_lengthlist__16u0__p6_0[] = {
  143283. 1, 4, 4, 7, 7,10,10,12,12,13,13,18,17, 3, 6, 6,
  143284. 9, 9,11,11,13,13,14,14,18,17, 3, 6, 6, 9, 9,11,
  143285. 11,13,13,14,14,17,18, 7, 9, 9,11,11,13,13,14,14,
  143286. 15,15, 0, 0, 7, 9, 9,11,11,13,13,14,14,15,16,19,
  143287. 18,10,11,11,13,13,14,14,16,15,17,18, 0, 0,10,11,
  143288. 11,13,13,14,14,15,15,16,18, 0, 0,11,13,13,14,14,
  143289. 15,15,17,17, 0,19, 0, 0,11,13,13,14,14,14,15,16,
  143290. 18, 0,19, 0, 0,13,14,14,15,15,18,17,18,18, 0,19,
  143291. 0, 0,13,14,14,15,16,16,16,18,18,19, 0, 0, 0,16,
  143292. 17,17, 0,17,19,19, 0,19, 0, 0, 0, 0,16,19,16,17,
  143293. 18, 0,19, 0, 0, 0, 0, 0, 0,
  143294. };
  143295. static float _vq_quantthresh__16u0__p6_0[] = {
  143296. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  143297. 12.5, 17.5, 22.5, 27.5,
  143298. };
  143299. static long _vq_quantmap__16u0__p6_0[] = {
  143300. 11, 9, 7, 5, 3, 1, 0, 2,
  143301. 4, 6, 8, 10, 12,
  143302. };
  143303. static encode_aux_threshmatch _vq_auxt__16u0__p6_0 = {
  143304. _vq_quantthresh__16u0__p6_0,
  143305. _vq_quantmap__16u0__p6_0,
  143306. 13,
  143307. 13
  143308. };
  143309. static static_codebook _16u0__p6_0 = {
  143310. 2, 169,
  143311. _vq_lengthlist__16u0__p6_0,
  143312. 1, -526516224, 1616117760, 4, 0,
  143313. _vq_quantlist__16u0__p6_0,
  143314. NULL,
  143315. &_vq_auxt__16u0__p6_0,
  143316. NULL,
  143317. 0
  143318. };
  143319. static long _vq_quantlist__16u0__p6_1[] = {
  143320. 2,
  143321. 1,
  143322. 3,
  143323. 0,
  143324. 4,
  143325. };
  143326. static long _vq_lengthlist__16u0__p6_1[] = {
  143327. 1, 4, 5, 6, 6, 4, 6, 6, 6, 6, 4, 6, 6, 6, 6, 6,
  143328. 6, 6, 7, 7, 6, 6, 6, 7, 7,
  143329. };
  143330. static float _vq_quantthresh__16u0__p6_1[] = {
  143331. -1.5, -0.5, 0.5, 1.5,
  143332. };
  143333. static long _vq_quantmap__16u0__p6_1[] = {
  143334. 3, 1, 0, 2, 4,
  143335. };
  143336. static encode_aux_threshmatch _vq_auxt__16u0__p6_1 = {
  143337. _vq_quantthresh__16u0__p6_1,
  143338. _vq_quantmap__16u0__p6_1,
  143339. 5,
  143340. 5
  143341. };
  143342. static static_codebook _16u0__p6_1 = {
  143343. 2, 25,
  143344. _vq_lengthlist__16u0__p6_1,
  143345. 1, -533725184, 1611661312, 3, 0,
  143346. _vq_quantlist__16u0__p6_1,
  143347. NULL,
  143348. &_vq_auxt__16u0__p6_1,
  143349. NULL,
  143350. 0
  143351. };
  143352. static long _vq_quantlist__16u0__p7_0[] = {
  143353. 1,
  143354. 0,
  143355. 2,
  143356. };
  143357. static long _vq_lengthlist__16u0__p7_0[] = {
  143358. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143359. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143360. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  143361. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  143362. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  143363. 7,
  143364. };
  143365. static float _vq_quantthresh__16u0__p7_0[] = {
  143366. -157.5, 157.5,
  143367. };
  143368. static long _vq_quantmap__16u0__p7_0[] = {
  143369. 1, 0, 2,
  143370. };
  143371. static encode_aux_threshmatch _vq_auxt__16u0__p7_0 = {
  143372. _vq_quantthresh__16u0__p7_0,
  143373. _vq_quantmap__16u0__p7_0,
  143374. 3,
  143375. 3
  143376. };
  143377. static static_codebook _16u0__p7_0 = {
  143378. 4, 81,
  143379. _vq_lengthlist__16u0__p7_0,
  143380. 1, -518803456, 1628680192, 2, 0,
  143381. _vq_quantlist__16u0__p7_0,
  143382. NULL,
  143383. &_vq_auxt__16u0__p7_0,
  143384. NULL,
  143385. 0
  143386. };
  143387. static long _vq_quantlist__16u0__p7_1[] = {
  143388. 7,
  143389. 6,
  143390. 8,
  143391. 5,
  143392. 9,
  143393. 4,
  143394. 10,
  143395. 3,
  143396. 11,
  143397. 2,
  143398. 12,
  143399. 1,
  143400. 13,
  143401. 0,
  143402. 14,
  143403. };
  143404. static long _vq_lengthlist__16u0__p7_1[] = {
  143405. 1, 5, 5, 6, 5, 9,10,11,11,10,10,10,10,10,10, 5,
  143406. 8, 8, 8,10,10,10,10,10,10,10,10,10,10,10, 5, 8,
  143407. 9, 9, 9,10,10,10,10,10,10,10,10,10,10, 5,10, 8,
  143408. 10,10,10,10,10,10,10,10,10,10,10,10, 4, 8, 9,10,
  143409. 10,10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,
  143410. 10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,
  143411. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143412. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143413. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143414. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143415. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143416. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143417. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143418. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143419. 10,
  143420. };
  143421. static float _vq_quantthresh__16u0__p7_1[] = {
  143422. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  143423. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  143424. };
  143425. static long _vq_quantmap__16u0__p7_1[] = {
  143426. 13, 11, 9, 7, 5, 3, 1, 0,
  143427. 2, 4, 6, 8, 10, 12, 14,
  143428. };
  143429. static encode_aux_threshmatch _vq_auxt__16u0__p7_1 = {
  143430. _vq_quantthresh__16u0__p7_1,
  143431. _vq_quantmap__16u0__p7_1,
  143432. 15,
  143433. 15
  143434. };
  143435. static static_codebook _16u0__p7_1 = {
  143436. 2, 225,
  143437. _vq_lengthlist__16u0__p7_1,
  143438. 1, -520986624, 1620377600, 4, 0,
  143439. _vq_quantlist__16u0__p7_1,
  143440. NULL,
  143441. &_vq_auxt__16u0__p7_1,
  143442. NULL,
  143443. 0
  143444. };
  143445. static long _vq_quantlist__16u0__p7_2[] = {
  143446. 10,
  143447. 9,
  143448. 11,
  143449. 8,
  143450. 12,
  143451. 7,
  143452. 13,
  143453. 6,
  143454. 14,
  143455. 5,
  143456. 15,
  143457. 4,
  143458. 16,
  143459. 3,
  143460. 17,
  143461. 2,
  143462. 18,
  143463. 1,
  143464. 19,
  143465. 0,
  143466. 20,
  143467. };
  143468. static long _vq_lengthlist__16u0__p7_2[] = {
  143469. 1, 6, 6, 7, 8, 7, 7,10, 9,10, 9,11,10, 9,11,10,
  143470. 9, 9, 9, 9,10, 6, 8, 7, 9, 9, 8, 8,10,10, 9,11,
  143471. 11,12,12,10, 9,11, 9,12,10, 9, 6, 9, 8, 9,12, 8,
  143472. 8,11, 9,11,11,12,11,12,12,10,11,11,10,10,11, 7,
  143473. 10, 9, 9, 9, 9, 9,10, 9,10, 9,10,10,12,10,10,10,
  143474. 11,12,10,10, 7, 9, 9, 9,10, 9, 9,10,10, 9, 9, 9,
  143475. 11,11,10,10,10,10, 9, 9,12, 7, 9,10, 9,11, 9,10,
  143476. 9,10,11,11,11,10,11,12, 9,12,11,10,10,10, 7, 9,
  143477. 9, 9, 9,10,12,10, 9,11,12,10,11,12,12,11, 9,10,
  143478. 11,10,11, 7, 9,10,10,11,10, 9,10,11,11,11,10,12,
  143479. 12,12,11,11,10,11,11,12, 8, 9,10,12,11,10,10,12,
  143480. 12,12,12,12,10,11,11, 9,11,10,12,11,11, 8, 9,10,
  143481. 10,11,12,11,11,10,10,10,12,12,12, 9,10,12,12,12,
  143482. 12,12, 8,10,11,10,10,12, 9,11,12,12,11,12,12,12,
  143483. 12,10,12,10,10,10,10, 8,12,11,11,11,10,10,11,12,
  143484. 12,12,12,11,12,12,12,11,11,11,12,10, 9,10,10,12,
  143485. 10,12,10,12,12,10,10,10,11,12,12,12,11,12,12,12,
  143486. 11,10,11,12,12,12,11,12,12,11,12,12,11,12,12,12,
  143487. 12,11,12,12,10,10,10,10,11,11,12,11,12,12,12,12,
  143488. 12,12,12,11,12,11,10,11,11,12,11,11, 9,10,10,10,
  143489. 12,10,10,11, 9,11,12,11,12,11,12,12,10,11,10,12,
  143490. 9, 9, 9,12,11,10,11,10,12,10,12,10,12,12,12,11,
  143491. 11,11,11,11,10, 9,10,10,11,10,11,11,12,11,10,11,
  143492. 12,12,12,11,11, 9,12,10,12, 9,10,12,10,10,11,10,
  143493. 11,11,12,11,10,11,10,11,11,11,11,12,11,11,10, 9,
  143494. 10,10,10, 9,11,11,10, 9,12,10,11,12,11,12,12,11,
  143495. 12,11,12,11,10,11,10,12,11,12,11,12,11,12,10,11,
  143496. 10,10,12,11,10,11,11,11,10,
  143497. };
  143498. static float _vq_quantthresh__16u0__p7_2[] = {
  143499. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  143500. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  143501. 6.5, 7.5, 8.5, 9.5,
  143502. };
  143503. static long _vq_quantmap__16u0__p7_2[] = {
  143504. 19, 17, 15, 13, 11, 9, 7, 5,
  143505. 3, 1, 0, 2, 4, 6, 8, 10,
  143506. 12, 14, 16, 18, 20,
  143507. };
  143508. static encode_aux_threshmatch _vq_auxt__16u0__p7_2 = {
  143509. _vq_quantthresh__16u0__p7_2,
  143510. _vq_quantmap__16u0__p7_2,
  143511. 21,
  143512. 21
  143513. };
  143514. static static_codebook _16u0__p7_2 = {
  143515. 2, 441,
  143516. _vq_lengthlist__16u0__p7_2,
  143517. 1, -529268736, 1611661312, 5, 0,
  143518. _vq_quantlist__16u0__p7_2,
  143519. NULL,
  143520. &_vq_auxt__16u0__p7_2,
  143521. NULL,
  143522. 0
  143523. };
  143524. static long _huff_lengthlist__16u0__single[] = {
  143525. 3, 5, 8, 7,14, 8, 9,19, 5, 2, 5, 5, 9, 6, 9,19,
  143526. 8, 4, 5, 7, 8, 9,13,19, 7, 4, 6, 5, 9, 6, 9,19,
  143527. 12, 8, 7, 9,10,11,13,19, 8, 5, 8, 6, 9, 6, 7,19,
  143528. 8, 8,10, 7, 7, 4, 5,19,12,17,19,15,18,13,11,18,
  143529. };
  143530. static static_codebook _huff_book__16u0__single = {
  143531. 2, 64,
  143532. _huff_lengthlist__16u0__single,
  143533. 0, 0, 0, 0, 0,
  143534. NULL,
  143535. NULL,
  143536. NULL,
  143537. NULL,
  143538. 0
  143539. };
  143540. static long _huff_lengthlist__16u1__long[] = {
  143541. 3, 6,10, 8,12, 8,14, 8,14,19, 5, 3, 5, 5, 7, 6,
  143542. 11, 7,16,19, 7, 5, 6, 7, 7, 9,11,12,19,19, 6, 4,
  143543. 7, 5, 7, 6,10, 7,18,18, 8, 6, 7, 7, 7, 7, 8, 9,
  143544. 18,18, 7, 5, 8, 5, 7, 5, 8, 6,18,18,12, 9,10, 9,
  143545. 9, 9, 8, 9,18,18, 8, 7,10, 6, 8, 5, 6, 4,11,18,
  143546. 11,15,16,12,11, 8, 8, 6, 9,18,14,18,18,18,16,16,
  143547. 16,13,16,18,
  143548. };
  143549. static static_codebook _huff_book__16u1__long = {
  143550. 2, 100,
  143551. _huff_lengthlist__16u1__long,
  143552. 0, 0, 0, 0, 0,
  143553. NULL,
  143554. NULL,
  143555. NULL,
  143556. NULL,
  143557. 0
  143558. };
  143559. static long _vq_quantlist__16u1__p1_0[] = {
  143560. 1,
  143561. 0,
  143562. 2,
  143563. };
  143564. static long _vq_lengthlist__16u1__p1_0[] = {
  143565. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 7, 7,10,10, 7,
  143566. 9,10, 5, 7, 8, 7,10, 9, 7,10,10, 5, 8, 8, 8,10,
  143567. 10, 8,10,10, 7,10,10,10,11,12,10,12,13, 7,10,10,
  143568. 9,13,11,10,12,13, 5, 8, 8, 8,10,10, 8,10,10, 7,
  143569. 10,10,10,12,12, 9,11,12, 7,10,11,10,12,12,10,13,
  143570. 11,
  143571. };
  143572. static float _vq_quantthresh__16u1__p1_0[] = {
  143573. -0.5, 0.5,
  143574. };
  143575. static long _vq_quantmap__16u1__p1_0[] = {
  143576. 1, 0, 2,
  143577. };
  143578. static encode_aux_threshmatch _vq_auxt__16u1__p1_0 = {
  143579. _vq_quantthresh__16u1__p1_0,
  143580. _vq_quantmap__16u1__p1_0,
  143581. 3,
  143582. 3
  143583. };
  143584. static static_codebook _16u1__p1_0 = {
  143585. 4, 81,
  143586. _vq_lengthlist__16u1__p1_0,
  143587. 1, -535822336, 1611661312, 2, 0,
  143588. _vq_quantlist__16u1__p1_0,
  143589. NULL,
  143590. &_vq_auxt__16u1__p1_0,
  143591. NULL,
  143592. 0
  143593. };
  143594. static long _vq_quantlist__16u1__p2_0[] = {
  143595. 1,
  143596. 0,
  143597. 2,
  143598. };
  143599. static long _vq_lengthlist__16u1__p2_0[] = {
  143600. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 7, 8, 6,
  143601. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 6, 8,
  143602. 8, 6, 8, 8, 6, 8, 8, 7, 7,10, 8, 9, 9, 6, 8, 8,
  143603. 7, 9, 8, 8, 9,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  143604. 8, 8, 8,10, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 7,10,
  143605. 8,
  143606. };
  143607. static float _vq_quantthresh__16u1__p2_0[] = {
  143608. -0.5, 0.5,
  143609. };
  143610. static long _vq_quantmap__16u1__p2_0[] = {
  143611. 1, 0, 2,
  143612. };
  143613. static encode_aux_threshmatch _vq_auxt__16u1__p2_0 = {
  143614. _vq_quantthresh__16u1__p2_0,
  143615. _vq_quantmap__16u1__p2_0,
  143616. 3,
  143617. 3
  143618. };
  143619. static static_codebook _16u1__p2_0 = {
  143620. 4, 81,
  143621. _vq_lengthlist__16u1__p2_0,
  143622. 1, -535822336, 1611661312, 2, 0,
  143623. _vq_quantlist__16u1__p2_0,
  143624. NULL,
  143625. &_vq_auxt__16u1__p2_0,
  143626. NULL,
  143627. 0
  143628. };
  143629. static long _vq_quantlist__16u1__p3_0[] = {
  143630. 2,
  143631. 1,
  143632. 3,
  143633. 0,
  143634. 4,
  143635. };
  143636. static long _vq_lengthlist__16u1__p3_0[] = {
  143637. 1, 5, 5, 8, 8, 6, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  143638. 10, 9,11,11, 9, 9,10,11,11, 6, 8, 8,10,10, 8, 9,
  143639. 10,11,11, 8, 9,10,11,11,10,11,11,12,13,10,11,11,
  143640. 13,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  143641. 11,10,11,11,13,13,10,11,11,13,12, 9,11,11,14,13,
  143642. 10,12,12,15,14,10,12,11,14,13,12,13,13,15,15,12,
  143643. 13,13,16,14, 9,11,11,13,14,10,11,12,14,14,10,12,
  143644. 12,14,15,12,13,13,14,15,12,13,14,15,16, 5, 8, 8,
  143645. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  143646. 14,11,12,12,14,14, 8,10,10,12,12, 9,11,12,12,13,
  143647. 10,12,12,13,13,12,12,13,14,15,11,13,13,15,15, 7,
  143648. 10,10,12,12, 9,12,11,13,12,10,11,12,13,13,12,13,
  143649. 12,15,14,11,12,13,15,15,10,12,12,15,14,11,13,13,
  143650. 16,15,11,13,13,16,15,14,13,14,15,16,13,15,15,17,
  143651. 17,10,12,12,14,15,11,12,12,15,15,11,13,13,15,16,
  143652. 13,15,13,16,15,13,15,15,16,17, 5, 8, 8,11,11, 8,
  143653. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  143654. 12,14,14, 7,10,10,12,12,10,12,12,14,13, 9,11,12,
  143655. 12,13,12,13,13,15,15,12,12,13,13,15, 7,10,10,12,
  143656. 13,10,11,12,13,13,10,12,11,13,13,11,13,13,15,15,
  143657. 12,13,12,15,14, 9,12,12,15,14,11,13,13,15,15,11,
  143658. 12,13,15,15,13,14,14,17,19,13,13,14,16,16,10,12,
  143659. 12,14,15,11,13,13,15,16,11,13,12,16,15,13,15,15,
  143660. 17,18,14,15,13,16,15, 8,11,11,15,14,10,12,12,16,
  143661. 15,10,12,12,16,16,14,15,15,18,17,13,14,15,16,18,
  143662. 9,12,12,15,15,11,12,14,16,17,11,13,13,16,15,15,
  143663. 15,15,17,18,14,15,16,17,17, 9,12,12,15,15,11,14,
  143664. 13,16,16,11,13,13,16,16,15,16,15,17,18,14,16,15,
  143665. 17,16,12,14,14,17,16,12,14,15,18,17,13,15,15,17,
  143666. 17,15,15,18,16,20,15,16,17,18,18,11,14,14,16,17,
  143667. 13,15,14,18,17,13,15,15,17,17,15,17,15,18,17,15,
  143668. 17,16,19,18, 8,11,11,14,15,10,12,12,15,15,10,12,
  143669. 12,16,16,13,14,14,17,16,14,15,15,17,17, 9,12,12,
  143670. 15,16,11,13,13,16,16,11,12,13,16,16,14,16,15,20,
  143671. 17,14,16,16,17,17, 9,12,12,15,16,11,13,13,16,17,
  143672. 11,13,13,17,16,14,15,15,17,18,15,15,15,18,18,11,
  143673. 14,14,17,16,13,15,15,17,17,13,14,14,18,17,15,16,
  143674. 16,18,19,15,15,17,17,19,11,14,14,16,17,13,15,14,
  143675. 17,19,13,15,14,18,17,15,17,16,18,18,15,17,15,18,
  143676. 16,
  143677. };
  143678. static float _vq_quantthresh__16u1__p3_0[] = {
  143679. -1.5, -0.5, 0.5, 1.5,
  143680. };
  143681. static long _vq_quantmap__16u1__p3_0[] = {
  143682. 3, 1, 0, 2, 4,
  143683. };
  143684. static encode_aux_threshmatch _vq_auxt__16u1__p3_0 = {
  143685. _vq_quantthresh__16u1__p3_0,
  143686. _vq_quantmap__16u1__p3_0,
  143687. 5,
  143688. 5
  143689. };
  143690. static static_codebook _16u1__p3_0 = {
  143691. 4, 625,
  143692. _vq_lengthlist__16u1__p3_0,
  143693. 1, -533725184, 1611661312, 3, 0,
  143694. _vq_quantlist__16u1__p3_0,
  143695. NULL,
  143696. &_vq_auxt__16u1__p3_0,
  143697. NULL,
  143698. 0
  143699. };
  143700. static long _vq_quantlist__16u1__p4_0[] = {
  143701. 2,
  143702. 1,
  143703. 3,
  143704. 0,
  143705. 4,
  143706. };
  143707. static long _vq_lengthlist__16u1__p4_0[] = {
  143708. 4, 5, 5, 8, 8, 6, 6, 7, 9, 9, 6, 6, 6, 9, 9, 9,
  143709. 10, 9,11,11, 9, 9,10,11,11, 6, 7, 7,10, 9, 7, 7,
  143710. 8, 9,10, 7, 7, 8,10,10,10,10,10,10,12, 9, 9,10,
  143711. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 7,10,
  143712. 10, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  143713. 10,10,10,12,12, 9,10,10,12,12,12,11,12,13,13,11,
  143714. 11,12,12,13, 9,10,10,11,12, 9,10,10,12,12,10,10,
  143715. 10,12,12,11,12,11,14,13,11,12,12,14,13, 5, 7, 7,
  143716. 10,10, 7, 8, 8,10,10, 7, 8, 7,10,10,10,10,10,12,
  143717. 12,10,10,10,12,12, 6, 8, 7,10,10, 7, 7, 9,10,11,
  143718. 8, 9, 9,11,10,10,10,11,11,13,10,10,11,12,13, 6,
  143719. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,10,11,10,11,
  143720. 10,13,11,10,11,10,12,12,10,11,10,12,11,10,10,10,
  143721. 12,13,10,11,11,13,12,11,11,13,11,14,12,12,13,14,
  143722. 14, 9,10,10,12,13,10,11,10,13,12,10,11,11,12,13,
  143723. 11,12,11,14,12,12,13,13,15,14, 5, 7, 7,10,10, 7,
  143724. 7, 8,10,10, 7, 8, 8,10,10,10,10,10,11,12,10,10,
  143725. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  143726. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 7, 8,10,
  143727. 10, 8, 8, 9,10,11, 7, 9, 7,11,10,10,11,11,13,12,
  143728. 11,11,10,13,11, 9,10,10,12,12,10,11,11,13,12,10,
  143729. 10,11,12,12,12,13,13,14,14,11,11,12,12,14,10,10,
  143730. 11,12,12,10,11,11,12,13,10,10,10,13,12,12,13,13,
  143731. 15,14,12,13,10,14,11, 8,10,10,12,12,10,11,10,13,
  143732. 13, 9,10,10,12,12,12,13,13,15,14,11,12,12,13,13,
  143733. 9,10,10,13,12,10,10,11,13,13,10,11,10,13,12,12,
  143734. 12,13,14,15,12,13,12,15,13, 9,10,10,12,13,10,11,
  143735. 10,13,12,10,10,11,12,13,12,14,12,15,13,12,12,13,
  143736. 14,15,11,12,11,14,13,11,11,12,14,15,12,13,12,15,
  143737. 14,13,11,15,11,16,13,14,14,16,15,11,12,12,14,14,
  143738. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,12,14,
  143739. 14,14,15,15, 8,10,10,12,12, 9,10,10,12,12,10,10,
  143740. 11,13,13,11,12,12,13,13,12,13,13,14,15, 9,10,10,
  143741. 13,12,10,11,11,13,12,10,10,11,13,13,12,13,12,15,
  143742. 14,12,12,13,13,16, 9, 9,10,12,13,10,10,11,12,13,
  143743. 10,11,10,13,13,12,12,13,13,15,13,13,12,15,13,11,
  143744. 12,12,14,14,12,13,12,15,14,11,11,12,13,14,14,14,
  143745. 14,16,15,13,12,15,12,16,11,11,12,13,14,12,13,13,
  143746. 14,15,10,12,11,14,13,14,15,14,16,16,13,14,11,15,
  143747. 11,
  143748. };
  143749. static float _vq_quantthresh__16u1__p4_0[] = {
  143750. -1.5, -0.5, 0.5, 1.5,
  143751. };
  143752. static long _vq_quantmap__16u1__p4_0[] = {
  143753. 3, 1, 0, 2, 4,
  143754. };
  143755. static encode_aux_threshmatch _vq_auxt__16u1__p4_0 = {
  143756. _vq_quantthresh__16u1__p4_0,
  143757. _vq_quantmap__16u1__p4_0,
  143758. 5,
  143759. 5
  143760. };
  143761. static static_codebook _16u1__p4_0 = {
  143762. 4, 625,
  143763. _vq_lengthlist__16u1__p4_0,
  143764. 1, -533725184, 1611661312, 3, 0,
  143765. _vq_quantlist__16u1__p4_0,
  143766. NULL,
  143767. &_vq_auxt__16u1__p4_0,
  143768. NULL,
  143769. 0
  143770. };
  143771. static long _vq_quantlist__16u1__p5_0[] = {
  143772. 4,
  143773. 3,
  143774. 5,
  143775. 2,
  143776. 6,
  143777. 1,
  143778. 7,
  143779. 0,
  143780. 8,
  143781. };
  143782. static long _vq_lengthlist__16u1__p5_0[] = {
  143783. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  143784. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  143785. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  143786. 10, 9,11,11,12,11, 7, 8, 8, 9, 9,11,11,12,12, 9,
  143787. 10,10,11,11,12,12,13,12, 9,10,10,11,11,12,12,12,
  143788. 13,
  143789. };
  143790. static float _vq_quantthresh__16u1__p5_0[] = {
  143791. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143792. };
  143793. static long _vq_quantmap__16u1__p5_0[] = {
  143794. 7, 5, 3, 1, 0, 2, 4, 6,
  143795. 8,
  143796. };
  143797. static encode_aux_threshmatch _vq_auxt__16u1__p5_0 = {
  143798. _vq_quantthresh__16u1__p5_0,
  143799. _vq_quantmap__16u1__p5_0,
  143800. 9,
  143801. 9
  143802. };
  143803. static static_codebook _16u1__p5_0 = {
  143804. 2, 81,
  143805. _vq_lengthlist__16u1__p5_0,
  143806. 1, -531628032, 1611661312, 4, 0,
  143807. _vq_quantlist__16u1__p5_0,
  143808. NULL,
  143809. &_vq_auxt__16u1__p5_0,
  143810. NULL,
  143811. 0
  143812. };
  143813. static long _vq_quantlist__16u1__p6_0[] = {
  143814. 4,
  143815. 3,
  143816. 5,
  143817. 2,
  143818. 6,
  143819. 1,
  143820. 7,
  143821. 0,
  143822. 8,
  143823. };
  143824. static long _vq_lengthlist__16u1__p6_0[] = {
  143825. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 4, 6, 6, 8, 8,
  143826. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  143827. 8, 8,10, 9, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  143828. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  143829. 9, 9,10,10,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  143830. 11,
  143831. };
  143832. static float _vq_quantthresh__16u1__p6_0[] = {
  143833. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143834. };
  143835. static long _vq_quantmap__16u1__p6_0[] = {
  143836. 7, 5, 3, 1, 0, 2, 4, 6,
  143837. 8,
  143838. };
  143839. static encode_aux_threshmatch _vq_auxt__16u1__p6_0 = {
  143840. _vq_quantthresh__16u1__p6_0,
  143841. _vq_quantmap__16u1__p6_0,
  143842. 9,
  143843. 9
  143844. };
  143845. static static_codebook _16u1__p6_0 = {
  143846. 2, 81,
  143847. _vq_lengthlist__16u1__p6_0,
  143848. 1, -531628032, 1611661312, 4, 0,
  143849. _vq_quantlist__16u1__p6_0,
  143850. NULL,
  143851. &_vq_auxt__16u1__p6_0,
  143852. NULL,
  143853. 0
  143854. };
  143855. static long _vq_quantlist__16u1__p7_0[] = {
  143856. 1,
  143857. 0,
  143858. 2,
  143859. };
  143860. static long _vq_lengthlist__16u1__p7_0[] = {
  143861. 1, 4, 4, 4, 8, 8, 4, 8, 8, 5,11, 9, 8,12,11, 8,
  143862. 12,11, 5,10,11, 8,11,12, 8,11,12, 4,11,11,11,14,
  143863. 13,10,13,13, 8,14,13,12,14,16,12,16,15, 8,14,14,
  143864. 13,16,14,12,15,16, 4,11,11,10,14,13,11,14,14, 8,
  143865. 15,14,12,15,15,12,14,16, 8,14,14,11,16,15,12,15,
  143866. 13,
  143867. };
  143868. static float _vq_quantthresh__16u1__p7_0[] = {
  143869. -5.5, 5.5,
  143870. };
  143871. static long _vq_quantmap__16u1__p7_0[] = {
  143872. 1, 0, 2,
  143873. };
  143874. static encode_aux_threshmatch _vq_auxt__16u1__p7_0 = {
  143875. _vq_quantthresh__16u1__p7_0,
  143876. _vq_quantmap__16u1__p7_0,
  143877. 3,
  143878. 3
  143879. };
  143880. static static_codebook _16u1__p7_0 = {
  143881. 4, 81,
  143882. _vq_lengthlist__16u1__p7_0,
  143883. 1, -529137664, 1618345984, 2, 0,
  143884. _vq_quantlist__16u1__p7_0,
  143885. NULL,
  143886. &_vq_auxt__16u1__p7_0,
  143887. NULL,
  143888. 0
  143889. };
  143890. static long _vq_quantlist__16u1__p7_1[] = {
  143891. 5,
  143892. 4,
  143893. 6,
  143894. 3,
  143895. 7,
  143896. 2,
  143897. 8,
  143898. 1,
  143899. 9,
  143900. 0,
  143901. 10,
  143902. };
  143903. static long _vq_lengthlist__16u1__p7_1[] = {
  143904. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 5, 7, 7,
  143905. 8, 8, 8, 8, 8, 8, 4, 5, 6, 7, 7, 8, 8, 8, 8, 8,
  143906. 8, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  143907. 8, 8, 8, 9, 9, 9, 9, 7, 8, 8, 8, 8, 9, 9, 9,10,
  143908. 9,10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10, 9, 8, 8, 8,
  143909. 9, 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,10,
  143910. 10,10,10, 8, 8, 8, 9, 9, 9,10,10,10,10,10, 8, 8,
  143911. 8, 9, 9,10,10,10,10,10,10,
  143912. };
  143913. static float _vq_quantthresh__16u1__p7_1[] = {
  143914. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  143915. 3.5, 4.5,
  143916. };
  143917. static long _vq_quantmap__16u1__p7_1[] = {
  143918. 9, 7, 5, 3, 1, 0, 2, 4,
  143919. 6, 8, 10,
  143920. };
  143921. static encode_aux_threshmatch _vq_auxt__16u1__p7_1 = {
  143922. _vq_quantthresh__16u1__p7_1,
  143923. _vq_quantmap__16u1__p7_1,
  143924. 11,
  143925. 11
  143926. };
  143927. static static_codebook _16u1__p7_1 = {
  143928. 2, 121,
  143929. _vq_lengthlist__16u1__p7_1,
  143930. 1, -531365888, 1611661312, 4, 0,
  143931. _vq_quantlist__16u1__p7_1,
  143932. NULL,
  143933. &_vq_auxt__16u1__p7_1,
  143934. NULL,
  143935. 0
  143936. };
  143937. static long _vq_quantlist__16u1__p8_0[] = {
  143938. 5,
  143939. 4,
  143940. 6,
  143941. 3,
  143942. 7,
  143943. 2,
  143944. 8,
  143945. 1,
  143946. 9,
  143947. 0,
  143948. 10,
  143949. };
  143950. static long _vq_lengthlist__16u1__p8_0[] = {
  143951. 1, 4, 4, 5, 5, 8, 8,10,10,12,12, 4, 7, 7, 8, 8,
  143952. 9, 9,12,11,14,13, 4, 7, 7, 7, 8, 9,10,11,11,13,
  143953. 12, 5, 8, 8, 9, 9,11,11,12,13,15,14, 5, 7, 8, 9,
  143954. 9,11,11,13,13,17,15, 8, 9,10,11,11,12,13,17,14,
  143955. 17,16, 8,10, 9,11,11,12,12,13,15,15,17,10,11,11,
  143956. 12,13,14,15,15,16,16,17, 9,11,11,12,12,14,15,17,
  143957. 15,15,16,11,14,12,14,15,16,15,16,16,16,15,11,13,
  143958. 13,14,14,15,15,16,16,15,16,
  143959. };
  143960. static float _vq_quantthresh__16u1__p8_0[] = {
  143961. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  143962. 38.5, 49.5,
  143963. };
  143964. static long _vq_quantmap__16u1__p8_0[] = {
  143965. 9, 7, 5, 3, 1, 0, 2, 4,
  143966. 6, 8, 10,
  143967. };
  143968. static encode_aux_threshmatch _vq_auxt__16u1__p8_0 = {
  143969. _vq_quantthresh__16u1__p8_0,
  143970. _vq_quantmap__16u1__p8_0,
  143971. 11,
  143972. 11
  143973. };
  143974. static static_codebook _16u1__p8_0 = {
  143975. 2, 121,
  143976. _vq_lengthlist__16u1__p8_0,
  143977. 1, -524582912, 1618345984, 4, 0,
  143978. _vq_quantlist__16u1__p8_0,
  143979. NULL,
  143980. &_vq_auxt__16u1__p8_0,
  143981. NULL,
  143982. 0
  143983. };
  143984. static long _vq_quantlist__16u1__p8_1[] = {
  143985. 5,
  143986. 4,
  143987. 6,
  143988. 3,
  143989. 7,
  143990. 2,
  143991. 8,
  143992. 1,
  143993. 9,
  143994. 0,
  143995. 10,
  143996. };
  143997. static long _vq_lengthlist__16u1__p8_1[] = {
  143998. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7,
  143999. 8, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  144000. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 6, 7, 7, 7,
  144001. 7, 8, 8, 8, 8, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  144002. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  144003. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  144004. 9, 9, 9, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  144005. 8, 9, 9, 9, 9, 9, 9, 9, 9,
  144006. };
  144007. static float _vq_quantthresh__16u1__p8_1[] = {
  144008. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144009. 3.5, 4.5,
  144010. };
  144011. static long _vq_quantmap__16u1__p8_1[] = {
  144012. 9, 7, 5, 3, 1, 0, 2, 4,
  144013. 6, 8, 10,
  144014. };
  144015. static encode_aux_threshmatch _vq_auxt__16u1__p8_1 = {
  144016. _vq_quantthresh__16u1__p8_1,
  144017. _vq_quantmap__16u1__p8_1,
  144018. 11,
  144019. 11
  144020. };
  144021. static static_codebook _16u1__p8_1 = {
  144022. 2, 121,
  144023. _vq_lengthlist__16u1__p8_1,
  144024. 1, -531365888, 1611661312, 4, 0,
  144025. _vq_quantlist__16u1__p8_1,
  144026. NULL,
  144027. &_vq_auxt__16u1__p8_1,
  144028. NULL,
  144029. 0
  144030. };
  144031. static long _vq_quantlist__16u1__p9_0[] = {
  144032. 7,
  144033. 6,
  144034. 8,
  144035. 5,
  144036. 9,
  144037. 4,
  144038. 10,
  144039. 3,
  144040. 11,
  144041. 2,
  144042. 12,
  144043. 1,
  144044. 13,
  144045. 0,
  144046. 14,
  144047. };
  144048. static long _vq_lengthlist__16u1__p9_0[] = {
  144049. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144050. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144051. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144052. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144053. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144054. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144055. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144056. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144057. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144058. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144059. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144060. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144061. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144062. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144063. 8,
  144064. };
  144065. static float _vq_quantthresh__16u1__p9_0[] = {
  144066. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  144067. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  144068. };
  144069. static long _vq_quantmap__16u1__p9_0[] = {
  144070. 13, 11, 9, 7, 5, 3, 1, 0,
  144071. 2, 4, 6, 8, 10, 12, 14,
  144072. };
  144073. static encode_aux_threshmatch _vq_auxt__16u1__p9_0 = {
  144074. _vq_quantthresh__16u1__p9_0,
  144075. _vq_quantmap__16u1__p9_0,
  144076. 15,
  144077. 15
  144078. };
  144079. static static_codebook _16u1__p9_0 = {
  144080. 2, 225,
  144081. _vq_lengthlist__16u1__p9_0,
  144082. 1, -514071552, 1627381760, 4, 0,
  144083. _vq_quantlist__16u1__p9_0,
  144084. NULL,
  144085. &_vq_auxt__16u1__p9_0,
  144086. NULL,
  144087. 0
  144088. };
  144089. static long _vq_quantlist__16u1__p9_1[] = {
  144090. 7,
  144091. 6,
  144092. 8,
  144093. 5,
  144094. 9,
  144095. 4,
  144096. 10,
  144097. 3,
  144098. 11,
  144099. 2,
  144100. 12,
  144101. 1,
  144102. 13,
  144103. 0,
  144104. 14,
  144105. };
  144106. static long _vq_lengthlist__16u1__p9_1[] = {
  144107. 1, 6, 5, 9, 9,10,10, 6, 7, 9, 9,10,10,10,10, 5,
  144108. 10, 8,10, 8,10,10, 8, 8,10, 9,10,10,10,10, 5, 8,
  144109. 9,10,10,10,10, 8,10,10,10,10,10,10,10, 9,10,10,
  144110. 10,10,10,10, 9, 9,10,10,10,10,10,10, 9, 9, 8, 9,
  144111. 10,10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  144112. 10,10,10,10,10,10,10,10,10,10,10, 8,10,10,10,10,
  144113. 10,10,10,10,10,10,10,10,10, 6, 8, 8,10,10,10, 8,
  144114. 10,10,10,10,10,10,10,10, 5, 8, 8,10,10,10, 9, 9,
  144115. 10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,10,
  144116. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144117. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  144118. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144119. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144120. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144121. 9,
  144122. };
  144123. static float _vq_quantthresh__16u1__p9_1[] = {
  144124. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  144125. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  144126. };
  144127. static long _vq_quantmap__16u1__p9_1[] = {
  144128. 13, 11, 9, 7, 5, 3, 1, 0,
  144129. 2, 4, 6, 8, 10, 12, 14,
  144130. };
  144131. static encode_aux_threshmatch _vq_auxt__16u1__p9_1 = {
  144132. _vq_quantthresh__16u1__p9_1,
  144133. _vq_quantmap__16u1__p9_1,
  144134. 15,
  144135. 15
  144136. };
  144137. static static_codebook _16u1__p9_1 = {
  144138. 2, 225,
  144139. _vq_lengthlist__16u1__p9_1,
  144140. 1, -522338304, 1620115456, 4, 0,
  144141. _vq_quantlist__16u1__p9_1,
  144142. NULL,
  144143. &_vq_auxt__16u1__p9_1,
  144144. NULL,
  144145. 0
  144146. };
  144147. static long _vq_quantlist__16u1__p9_2[] = {
  144148. 8,
  144149. 7,
  144150. 9,
  144151. 6,
  144152. 10,
  144153. 5,
  144154. 11,
  144155. 4,
  144156. 12,
  144157. 3,
  144158. 13,
  144159. 2,
  144160. 14,
  144161. 1,
  144162. 15,
  144163. 0,
  144164. 16,
  144165. };
  144166. static long _vq_lengthlist__16u1__p9_2[] = {
  144167. 1, 6, 6, 7, 8, 8,11,10, 9, 9,11, 9,10, 9,11,11,
  144168. 9, 6, 7, 6,11, 8,11, 9,10,10,11, 9,11,10,10,10,
  144169. 11, 9, 5, 7, 7, 8, 8,10,11, 8, 8,11, 9, 9,10,11,
  144170. 9,10,11, 8, 9, 6, 8, 8, 9, 9,10,10,11,11,11, 9,
  144171. 11,10, 9,11, 8, 8, 8, 9, 8, 9,10,11, 9, 9,11,11,
  144172. 10, 9, 9,11,10, 8,11, 8, 9, 8,11, 9,10, 9,10,11,
  144173. 11,10,10, 9,10,10, 8, 8, 9,10,10,10, 9,11, 9,10,
  144174. 11,11,11,11,10, 9,11, 9, 9,11,11,10, 8,11,11,11,
  144175. 9,10,10,11,10,11,11, 9,11,10, 9,11,10,10,10,10,
  144176. 9,11,10,11,10, 9, 9,10,11, 9, 8,10,11,11,10,10,
  144177. 11, 9,11,10,11,11,10,11, 9, 9, 8,10, 8, 9,11, 9,
  144178. 8,10,10, 9,11,10,11,10,11, 9,11, 8,10,11,11,11,
  144179. 11,10,10,11,11,11,11,10,11,11,10, 9, 8,10,10, 9,
  144180. 11,10,11,11,11, 9, 9, 9,11,11,11,10,10, 9, 9,10,
  144181. 9,11,11,11,11, 8,10,11,10,11,11,10,11,11, 9, 9,
  144182. 9,10, 9,11, 9,11,11,11,11,11,10,11,11,10,11,10,
  144183. 11,11, 9,11,10,11,10, 9,10, 9,10,10,11,11,11,11,
  144184. 9,10, 9,10,11,11,10,11,11,11,11,11,11,10,11,11,
  144185. 10,
  144186. };
  144187. static float _vq_quantthresh__16u1__p9_2[] = {
  144188. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144189. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144190. };
  144191. static long _vq_quantmap__16u1__p9_2[] = {
  144192. 15, 13, 11, 9, 7, 5, 3, 1,
  144193. 0, 2, 4, 6, 8, 10, 12, 14,
  144194. 16,
  144195. };
  144196. static encode_aux_threshmatch _vq_auxt__16u1__p9_2 = {
  144197. _vq_quantthresh__16u1__p9_2,
  144198. _vq_quantmap__16u1__p9_2,
  144199. 17,
  144200. 17
  144201. };
  144202. static static_codebook _16u1__p9_2 = {
  144203. 2, 289,
  144204. _vq_lengthlist__16u1__p9_2,
  144205. 1, -529530880, 1611661312, 5, 0,
  144206. _vq_quantlist__16u1__p9_2,
  144207. NULL,
  144208. &_vq_auxt__16u1__p9_2,
  144209. NULL,
  144210. 0
  144211. };
  144212. static long _huff_lengthlist__16u1__short[] = {
  144213. 5, 7,10, 9,11,10,15,11,13,16, 6, 4, 6, 6, 7, 7,
  144214. 10, 9,12,16,10, 6, 5, 6, 6, 7,10,11,16,16, 9, 6,
  144215. 7, 6, 7, 7,10, 8,14,16,11, 6, 5, 4, 5, 6, 8, 9,
  144216. 15,16, 9, 6, 6, 5, 6, 6, 9, 8,14,16,12, 7, 6, 6,
  144217. 5, 6, 6, 7,13,16, 8, 6, 7, 6, 5, 5, 4, 4,11,16,
  144218. 9, 8, 9, 9, 7, 7, 6, 5,13,16,14,14,16,15,16,15,
  144219. 16,16,16,16,
  144220. };
  144221. static static_codebook _huff_book__16u1__short = {
  144222. 2, 100,
  144223. _huff_lengthlist__16u1__short,
  144224. 0, 0, 0, 0, 0,
  144225. NULL,
  144226. NULL,
  144227. NULL,
  144228. NULL,
  144229. 0
  144230. };
  144231. static long _huff_lengthlist__16u2__long[] = {
  144232. 5, 7,10,10,10,11,11,13,18,19, 6, 5, 5, 6, 7, 8,
  144233. 9,12,19,19, 8, 5, 4, 4, 6, 7, 9,13,19,19, 8, 5,
  144234. 4, 4, 5, 6, 8,12,17,19, 7, 5, 5, 4, 4, 5, 7,12,
  144235. 18,18, 8, 7, 7, 6, 5, 5, 6,10,18,18, 9, 9, 9, 8,
  144236. 6, 5, 6, 9,18,18,11,13,13,13, 8, 7, 7, 9,16,18,
  144237. 13,17,18,16,11, 9, 9, 9,17,18,15,18,18,18,15,13,
  144238. 13,14,18,18,
  144239. };
  144240. static static_codebook _huff_book__16u2__long = {
  144241. 2, 100,
  144242. _huff_lengthlist__16u2__long,
  144243. 0, 0, 0, 0, 0,
  144244. NULL,
  144245. NULL,
  144246. NULL,
  144247. NULL,
  144248. 0
  144249. };
  144250. static long _huff_lengthlist__16u2__short[] = {
  144251. 8,11,12,12,14,15,16,16,16,16, 9, 7, 7, 8, 9,11,
  144252. 13,14,16,16,13, 7, 6, 6, 7, 9,12,13,15,16,15, 7,
  144253. 6, 5, 4, 6,10,11,14,16,12, 8, 7, 4, 2, 4, 7,10,
  144254. 14,16,11, 9, 7, 5, 3, 4, 6, 9,14,16,11,10, 9, 7,
  144255. 5, 5, 6, 9,16,16,10,10, 9, 8, 6, 6, 7,10,16,16,
  144256. 11,11,11,10,10,10,11,14,16,16,16,14,14,13,14,16,
  144257. 16,16,16,16,
  144258. };
  144259. static static_codebook _huff_book__16u2__short = {
  144260. 2, 100,
  144261. _huff_lengthlist__16u2__short,
  144262. 0, 0, 0, 0, 0,
  144263. NULL,
  144264. NULL,
  144265. NULL,
  144266. NULL,
  144267. 0
  144268. };
  144269. static long _vq_quantlist__16u2_p1_0[] = {
  144270. 1,
  144271. 0,
  144272. 2,
  144273. };
  144274. static long _vq_lengthlist__16u2_p1_0[] = {
  144275. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  144276. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 8, 9,
  144277. 9, 7, 9, 9, 7, 9, 9, 9,10,10, 9,10,10, 7, 9, 9,
  144278. 9,10,10, 9,10,11, 5, 7, 8, 8, 9, 9, 8, 9, 9, 7,
  144279. 9, 9, 9,10,10, 9, 9,10, 7, 9, 9, 9,10,10, 9,11,
  144280. 10,
  144281. };
  144282. static float _vq_quantthresh__16u2_p1_0[] = {
  144283. -0.5, 0.5,
  144284. };
  144285. static long _vq_quantmap__16u2_p1_0[] = {
  144286. 1, 0, 2,
  144287. };
  144288. static encode_aux_threshmatch _vq_auxt__16u2_p1_0 = {
  144289. _vq_quantthresh__16u2_p1_0,
  144290. _vq_quantmap__16u2_p1_0,
  144291. 3,
  144292. 3
  144293. };
  144294. static static_codebook _16u2_p1_0 = {
  144295. 4, 81,
  144296. _vq_lengthlist__16u2_p1_0,
  144297. 1, -535822336, 1611661312, 2, 0,
  144298. _vq_quantlist__16u2_p1_0,
  144299. NULL,
  144300. &_vq_auxt__16u2_p1_0,
  144301. NULL,
  144302. 0
  144303. };
  144304. static long _vq_quantlist__16u2_p2_0[] = {
  144305. 2,
  144306. 1,
  144307. 3,
  144308. 0,
  144309. 4,
  144310. };
  144311. static long _vq_lengthlist__16u2_p2_0[] = {
  144312. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  144313. 10, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  144314. 8,10,10, 7, 8, 8,10,10,10,10,10,12,12, 9,10,10,
  144315. 11,12, 5, 7, 7, 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,
  144316. 10, 9,10,10,12,11,10,10,10,12,12, 9,10,10,12,12,
  144317. 10,11,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  144318. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,12,10,10,
  144319. 10,12,12,11,12,12,14,13,12,13,12,14,14, 5, 7, 7,
  144320. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  144321. 12,10,10,11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  144322. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,12,13, 7,
  144323. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  144324. 10,13,12,10,11,11,13,13, 9,11,10,13,13,10,11,11,
  144325. 13,13,10,11,11,13,13,12,12,13,13,15,12,12,13,14,
  144326. 15, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  144327. 11,13,11,14,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  144328. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  144329. 11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  144330. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  144331. 11, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,12,
  144332. 11,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  144333. 10,11,12,13,12,13,13,15,14,11,11,13,12,14,10,10,
  144334. 11,13,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  144335. 14,14,12,13,12,14,13, 8,10, 9,12,12, 9,11,10,13,
  144336. 13, 9,10,10,12,13,12,13,13,14,14,12,12,13,14,14,
  144337. 9,11,10,13,13,10,11,11,13,13,10,11,11,13,13,12,
  144338. 13,13,15,15,13,13,13,14,15, 9,10,10,12,13,10,11,
  144339. 10,13,12,10,11,11,13,13,12,13,12,15,14,13,13,13,
  144340. 14,15,11,12,12,15,14,12,12,13,15,15,12,13,13,15,
  144341. 14,14,13,15,14,16,13,14,15,16,16,11,12,12,14,14,
  144342. 11,12,12,15,14,12,13,13,15,15,13,14,13,16,14,14,
  144343. 14,14,16,16, 8, 9, 9,12,12, 9,10,10,13,12, 9,10,
  144344. 10,13,13,12,12,12,14,14,12,12,13,15,15, 9,10,10,
  144345. 13,12,10,11,11,13,13,10,10,11,13,14,12,13,13,15,
  144346. 15,12,12,13,14,15, 9,10,10,13,13,10,11,11,13,13,
  144347. 10,11,11,13,13,12,13,13,14,14,13,14,13,15,14,11,
  144348. 12,12,14,14,12,13,13,15,14,11,12,12,14,15,14,14,
  144349. 14,16,15,13,12,14,14,16,11,12,13,14,15,12,13,13,
  144350. 14,16,12,13,12,15,14,13,15,14,16,16,14,15,13,16,
  144351. 13,
  144352. };
  144353. static float _vq_quantthresh__16u2_p2_0[] = {
  144354. -1.5, -0.5, 0.5, 1.5,
  144355. };
  144356. static long _vq_quantmap__16u2_p2_0[] = {
  144357. 3, 1, 0, 2, 4,
  144358. };
  144359. static encode_aux_threshmatch _vq_auxt__16u2_p2_0 = {
  144360. _vq_quantthresh__16u2_p2_0,
  144361. _vq_quantmap__16u2_p2_0,
  144362. 5,
  144363. 5
  144364. };
  144365. static static_codebook _16u2_p2_0 = {
  144366. 4, 625,
  144367. _vq_lengthlist__16u2_p2_0,
  144368. 1, -533725184, 1611661312, 3, 0,
  144369. _vq_quantlist__16u2_p2_0,
  144370. NULL,
  144371. &_vq_auxt__16u2_p2_0,
  144372. NULL,
  144373. 0
  144374. };
  144375. static long _vq_quantlist__16u2_p3_0[] = {
  144376. 4,
  144377. 3,
  144378. 5,
  144379. 2,
  144380. 6,
  144381. 1,
  144382. 7,
  144383. 0,
  144384. 8,
  144385. };
  144386. static long _vq_lengthlist__16u2_p3_0[] = {
  144387. 2, 4, 4, 6, 6, 7, 7, 9, 9, 4, 5, 5, 6, 6, 8, 7,
  144388. 9, 9, 4, 5, 5, 6, 6, 7, 8, 9, 9, 6, 6, 6, 7, 7,
  144389. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  144390. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  144391. 9, 9,10, 9,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  144392. 11,
  144393. };
  144394. static float _vq_quantthresh__16u2_p3_0[] = {
  144395. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144396. };
  144397. static long _vq_quantmap__16u2_p3_0[] = {
  144398. 7, 5, 3, 1, 0, 2, 4, 6,
  144399. 8,
  144400. };
  144401. static encode_aux_threshmatch _vq_auxt__16u2_p3_0 = {
  144402. _vq_quantthresh__16u2_p3_0,
  144403. _vq_quantmap__16u2_p3_0,
  144404. 9,
  144405. 9
  144406. };
  144407. static static_codebook _16u2_p3_0 = {
  144408. 2, 81,
  144409. _vq_lengthlist__16u2_p3_0,
  144410. 1, -531628032, 1611661312, 4, 0,
  144411. _vq_quantlist__16u2_p3_0,
  144412. NULL,
  144413. &_vq_auxt__16u2_p3_0,
  144414. NULL,
  144415. 0
  144416. };
  144417. static long _vq_quantlist__16u2_p4_0[] = {
  144418. 8,
  144419. 7,
  144420. 9,
  144421. 6,
  144422. 10,
  144423. 5,
  144424. 11,
  144425. 4,
  144426. 12,
  144427. 3,
  144428. 13,
  144429. 2,
  144430. 14,
  144431. 1,
  144432. 15,
  144433. 0,
  144434. 16,
  144435. };
  144436. static long _vq_lengthlist__16u2_p4_0[] = {
  144437. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,11,
  144438. 11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  144439. 12,11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  144440. 11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  144441. 11,11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,
  144442. 10,11,11,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  144443. 11,11,12,12,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  144444. 10,11,11,11,12,12,12, 9, 9, 9, 9, 9, 9,10,10,10,
  144445. 10,10,11,11,12,12,13,13, 8, 9, 9, 9, 9,10, 9,10,
  144446. 10,10,10,11,11,12,12,13,13, 9, 9, 9, 9, 9,10,10,
  144447. 10,10,11,11,11,12,12,12,13,13, 9, 9, 9, 9, 9,10,
  144448. 10,10,10,11,11,12,11,12,12,13,13,10,10,10,10,10,
  144449. 11,11,11,11,11,12,12,12,12,13,13,14,10,10,10,10,
  144450. 10,11,11,11,11,12,11,12,12,13,12,13,13,11,11,11,
  144451. 11,11,12,12,12,12,12,12,13,13,13,13,14,14,11,11,
  144452. 11,11,11,12,12,12,12,12,12,13,12,13,13,14,14,11,
  144453. 12,12,12,12,12,12,13,13,13,13,13,13,14,14,14,14,
  144454. 11,12,12,12,12,12,12,13,13,13,13,14,13,14,14,14,
  144455. 14,
  144456. };
  144457. static float _vq_quantthresh__16u2_p4_0[] = {
  144458. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144459. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144460. };
  144461. static long _vq_quantmap__16u2_p4_0[] = {
  144462. 15, 13, 11, 9, 7, 5, 3, 1,
  144463. 0, 2, 4, 6, 8, 10, 12, 14,
  144464. 16,
  144465. };
  144466. static encode_aux_threshmatch _vq_auxt__16u2_p4_0 = {
  144467. _vq_quantthresh__16u2_p4_0,
  144468. _vq_quantmap__16u2_p4_0,
  144469. 17,
  144470. 17
  144471. };
  144472. static static_codebook _16u2_p4_0 = {
  144473. 2, 289,
  144474. _vq_lengthlist__16u2_p4_0,
  144475. 1, -529530880, 1611661312, 5, 0,
  144476. _vq_quantlist__16u2_p4_0,
  144477. NULL,
  144478. &_vq_auxt__16u2_p4_0,
  144479. NULL,
  144480. 0
  144481. };
  144482. static long _vq_quantlist__16u2_p5_0[] = {
  144483. 1,
  144484. 0,
  144485. 2,
  144486. };
  144487. static long _vq_lengthlist__16u2_p5_0[] = {
  144488. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10, 9, 7,
  144489. 10, 9, 5, 8, 9, 7, 9,10, 7, 9,10, 4, 9, 9, 9,11,
  144490. 11, 8,11,11, 7,11,11,10,10,13,10,14,13, 7,11,11,
  144491. 10,13,11,10,13,14, 5, 9, 9, 8,11,11, 9,11,11, 7,
  144492. 11,11,10,14,13,10,12,14, 7,11,11,10,13,13,10,13,
  144493. 10,
  144494. };
  144495. static float _vq_quantthresh__16u2_p5_0[] = {
  144496. -5.5, 5.5,
  144497. };
  144498. static long _vq_quantmap__16u2_p5_0[] = {
  144499. 1, 0, 2,
  144500. };
  144501. static encode_aux_threshmatch _vq_auxt__16u2_p5_0 = {
  144502. _vq_quantthresh__16u2_p5_0,
  144503. _vq_quantmap__16u2_p5_0,
  144504. 3,
  144505. 3
  144506. };
  144507. static static_codebook _16u2_p5_0 = {
  144508. 4, 81,
  144509. _vq_lengthlist__16u2_p5_0,
  144510. 1, -529137664, 1618345984, 2, 0,
  144511. _vq_quantlist__16u2_p5_0,
  144512. NULL,
  144513. &_vq_auxt__16u2_p5_0,
  144514. NULL,
  144515. 0
  144516. };
  144517. static long _vq_quantlist__16u2_p5_1[] = {
  144518. 5,
  144519. 4,
  144520. 6,
  144521. 3,
  144522. 7,
  144523. 2,
  144524. 8,
  144525. 1,
  144526. 9,
  144527. 0,
  144528. 10,
  144529. };
  144530. static long _vq_lengthlist__16u2_p5_1[] = {
  144531. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 5, 5, 5, 7, 7,
  144532. 7, 7, 8, 8, 8, 8, 5, 5, 6, 7, 7, 7, 7, 8, 8, 8,
  144533. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  144534. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  144535. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  144536. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  144537. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  144538. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  144539. };
  144540. static float _vq_quantthresh__16u2_p5_1[] = {
  144541. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144542. 3.5, 4.5,
  144543. };
  144544. static long _vq_quantmap__16u2_p5_1[] = {
  144545. 9, 7, 5, 3, 1, 0, 2, 4,
  144546. 6, 8, 10,
  144547. };
  144548. static encode_aux_threshmatch _vq_auxt__16u2_p5_1 = {
  144549. _vq_quantthresh__16u2_p5_1,
  144550. _vq_quantmap__16u2_p5_1,
  144551. 11,
  144552. 11
  144553. };
  144554. static static_codebook _16u2_p5_1 = {
  144555. 2, 121,
  144556. _vq_lengthlist__16u2_p5_1,
  144557. 1, -531365888, 1611661312, 4, 0,
  144558. _vq_quantlist__16u2_p5_1,
  144559. NULL,
  144560. &_vq_auxt__16u2_p5_1,
  144561. NULL,
  144562. 0
  144563. };
  144564. static long _vq_quantlist__16u2_p6_0[] = {
  144565. 6,
  144566. 5,
  144567. 7,
  144568. 4,
  144569. 8,
  144570. 3,
  144571. 9,
  144572. 2,
  144573. 10,
  144574. 1,
  144575. 11,
  144576. 0,
  144577. 12,
  144578. };
  144579. static long _vq_lengthlist__16u2_p6_0[] = {
  144580. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6,
  144581. 8, 8, 9, 9, 9, 9,10,10,12,11, 4, 6, 6, 8, 8, 9,
  144582. 9, 9, 9,10,10,11,12, 7, 8, 8, 9, 9,10,10,10,10,
  144583. 12,12,13,12, 7, 8, 8, 9, 9,10,10,10,10,11,12,12,
  144584. 12, 8, 9, 9,10,10,11,11,11,11,12,12,13,13, 8, 9,
  144585. 9,10,10,11,11,11,11,12,13,13,13, 8, 9, 9,10,10,
  144586. 11,11,12,12,13,13,14,14, 8, 9, 9,10,10,11,11,12,
  144587. 12,13,13,14,14, 9,10,10,11,12,13,12,13,14,14,14,
  144588. 14,14, 9,10,10,11,12,12,13,13,13,14,14,14,14,10,
  144589. 11,11,12,12,13,13,14,14,15,15,15,15,10,11,11,12,
  144590. 12,13,13,14,14,14,14,15,15,
  144591. };
  144592. static float _vq_quantthresh__16u2_p6_0[] = {
  144593. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  144594. 12.5, 17.5, 22.5, 27.5,
  144595. };
  144596. static long _vq_quantmap__16u2_p6_0[] = {
  144597. 11, 9, 7, 5, 3, 1, 0, 2,
  144598. 4, 6, 8, 10, 12,
  144599. };
  144600. static encode_aux_threshmatch _vq_auxt__16u2_p6_0 = {
  144601. _vq_quantthresh__16u2_p6_0,
  144602. _vq_quantmap__16u2_p6_0,
  144603. 13,
  144604. 13
  144605. };
  144606. static static_codebook _16u2_p6_0 = {
  144607. 2, 169,
  144608. _vq_lengthlist__16u2_p6_0,
  144609. 1, -526516224, 1616117760, 4, 0,
  144610. _vq_quantlist__16u2_p6_0,
  144611. NULL,
  144612. &_vq_auxt__16u2_p6_0,
  144613. NULL,
  144614. 0
  144615. };
  144616. static long _vq_quantlist__16u2_p6_1[] = {
  144617. 2,
  144618. 1,
  144619. 3,
  144620. 0,
  144621. 4,
  144622. };
  144623. static long _vq_lengthlist__16u2_p6_1[] = {
  144624. 2, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  144625. 5, 5, 6, 6, 5, 5, 5, 6, 6,
  144626. };
  144627. static float _vq_quantthresh__16u2_p6_1[] = {
  144628. -1.5, -0.5, 0.5, 1.5,
  144629. };
  144630. static long _vq_quantmap__16u2_p6_1[] = {
  144631. 3, 1, 0, 2, 4,
  144632. };
  144633. static encode_aux_threshmatch _vq_auxt__16u2_p6_1 = {
  144634. _vq_quantthresh__16u2_p6_1,
  144635. _vq_quantmap__16u2_p6_1,
  144636. 5,
  144637. 5
  144638. };
  144639. static static_codebook _16u2_p6_1 = {
  144640. 2, 25,
  144641. _vq_lengthlist__16u2_p6_1,
  144642. 1, -533725184, 1611661312, 3, 0,
  144643. _vq_quantlist__16u2_p6_1,
  144644. NULL,
  144645. &_vq_auxt__16u2_p6_1,
  144646. NULL,
  144647. 0
  144648. };
  144649. static long _vq_quantlist__16u2_p7_0[] = {
  144650. 6,
  144651. 5,
  144652. 7,
  144653. 4,
  144654. 8,
  144655. 3,
  144656. 9,
  144657. 2,
  144658. 10,
  144659. 1,
  144660. 11,
  144661. 0,
  144662. 12,
  144663. };
  144664. static long _vq_lengthlist__16u2_p7_0[] = {
  144665. 1, 4, 4, 7, 7, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 6,
  144666. 9, 9, 9, 9, 9, 9,10,10,11,11, 4, 6, 6, 8, 9, 9,
  144667. 9, 9, 9,10,11,12,11, 7, 8, 9,10,10,10,10,11,10,
  144668. 11,12,12,13, 7, 9, 9,10,10,10,10,10,10,11,12,13,
  144669. 13, 7, 9, 8,10,10,11,11,11,12,12,13,13,14, 7, 9,
  144670. 9,10,10,11,11,11,12,13,13,13,13, 8, 9, 9,10,11,
  144671. 11,12,12,12,13,13,13,13, 8, 9, 9,10,11,11,11,12,
  144672. 12,13,13,14,14, 9,10,10,12,11,12,13,13,13,14,13,
  144673. 13,13, 9,10,10,11,11,12,12,13,14,13,13,14,13,10,
  144674. 11,11,12,13,14,14,14,15,14,14,14,14,10,11,11,12,
  144675. 12,13,13,13,14,14,14,15,14,
  144676. };
  144677. static float _vq_quantthresh__16u2_p7_0[] = {
  144678. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  144679. 27.5, 38.5, 49.5, 60.5,
  144680. };
  144681. static long _vq_quantmap__16u2_p7_0[] = {
  144682. 11, 9, 7, 5, 3, 1, 0, 2,
  144683. 4, 6, 8, 10, 12,
  144684. };
  144685. static encode_aux_threshmatch _vq_auxt__16u2_p7_0 = {
  144686. _vq_quantthresh__16u2_p7_0,
  144687. _vq_quantmap__16u2_p7_0,
  144688. 13,
  144689. 13
  144690. };
  144691. static static_codebook _16u2_p7_0 = {
  144692. 2, 169,
  144693. _vq_lengthlist__16u2_p7_0,
  144694. 1, -523206656, 1618345984, 4, 0,
  144695. _vq_quantlist__16u2_p7_0,
  144696. NULL,
  144697. &_vq_auxt__16u2_p7_0,
  144698. NULL,
  144699. 0
  144700. };
  144701. static long _vq_quantlist__16u2_p7_1[] = {
  144702. 5,
  144703. 4,
  144704. 6,
  144705. 3,
  144706. 7,
  144707. 2,
  144708. 8,
  144709. 1,
  144710. 9,
  144711. 0,
  144712. 10,
  144713. };
  144714. static long _vq_lengthlist__16u2_p7_1[] = {
  144715. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  144716. 7, 7, 7, 7, 8, 8, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8,
  144717. 8, 6, 6, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 7, 7, 7,
  144718. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  144719. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  144720. 8, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8,
  144721. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  144722. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144723. };
  144724. static float _vq_quantthresh__16u2_p7_1[] = {
  144725. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144726. 3.5, 4.5,
  144727. };
  144728. static long _vq_quantmap__16u2_p7_1[] = {
  144729. 9, 7, 5, 3, 1, 0, 2, 4,
  144730. 6, 8, 10,
  144731. };
  144732. static encode_aux_threshmatch _vq_auxt__16u2_p7_1 = {
  144733. _vq_quantthresh__16u2_p7_1,
  144734. _vq_quantmap__16u2_p7_1,
  144735. 11,
  144736. 11
  144737. };
  144738. static static_codebook _16u2_p7_1 = {
  144739. 2, 121,
  144740. _vq_lengthlist__16u2_p7_1,
  144741. 1, -531365888, 1611661312, 4, 0,
  144742. _vq_quantlist__16u2_p7_1,
  144743. NULL,
  144744. &_vq_auxt__16u2_p7_1,
  144745. NULL,
  144746. 0
  144747. };
  144748. static long _vq_quantlist__16u2_p8_0[] = {
  144749. 7,
  144750. 6,
  144751. 8,
  144752. 5,
  144753. 9,
  144754. 4,
  144755. 10,
  144756. 3,
  144757. 11,
  144758. 2,
  144759. 12,
  144760. 1,
  144761. 13,
  144762. 0,
  144763. 14,
  144764. };
  144765. static long _vq_lengthlist__16u2_p8_0[] = {
  144766. 1, 5, 5, 7, 7, 8, 8, 7, 7, 8, 8,10, 9,11,11, 4,
  144767. 6, 6, 8, 8,10, 9, 9, 8, 9, 9,10,10,12,14, 4, 6,
  144768. 7, 8, 9, 9,10, 9, 8, 9, 9,10,12,12,11, 7, 8, 8,
  144769. 10,10,10,10, 9, 9,10,10,11,13,13,12, 7, 8, 8, 9,
  144770. 11,11,10, 9, 9,11,10,12,11,11,14, 8, 9, 9,11,10,
  144771. 11,11,10,10,11,11,13,12,14,12, 8, 9, 9,11,12,11,
  144772. 11,10,10,12,11,12,12,12,14, 7, 8, 8, 9, 9,10,10,
  144773. 10,11,12,11,13,13,14,12, 7, 8, 9, 9, 9,10,10,11,
  144774. 11,11,12,12,14,14,14, 8,10, 9,10,11,11,11,11,14,
  144775. 12,12,13,14,14,13, 9, 9, 9,10,11,11,11,12,12,12,
  144776. 14,12,14,13,14,10,10,10,12,11,12,11,14,13,14,13,
  144777. 14,14,13,14, 9,10,10,11,12,11,13,12,13,13,14,14,
  144778. 14,13,14,10,13,13,12,12,11,12,14,13,14,13,14,12,
  144779. 14,13,10,11,11,12,11,12,12,14,14,14,13,14,14,14,
  144780. 14,
  144781. };
  144782. static float _vq_quantthresh__16u2_p8_0[] = {
  144783. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  144784. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  144785. };
  144786. static long _vq_quantmap__16u2_p8_0[] = {
  144787. 13, 11, 9, 7, 5, 3, 1, 0,
  144788. 2, 4, 6, 8, 10, 12, 14,
  144789. };
  144790. static encode_aux_threshmatch _vq_auxt__16u2_p8_0 = {
  144791. _vq_quantthresh__16u2_p8_0,
  144792. _vq_quantmap__16u2_p8_0,
  144793. 15,
  144794. 15
  144795. };
  144796. static static_codebook _16u2_p8_0 = {
  144797. 2, 225,
  144798. _vq_lengthlist__16u2_p8_0,
  144799. 1, -520986624, 1620377600, 4, 0,
  144800. _vq_quantlist__16u2_p8_0,
  144801. NULL,
  144802. &_vq_auxt__16u2_p8_0,
  144803. NULL,
  144804. 0
  144805. };
  144806. static long _vq_quantlist__16u2_p8_1[] = {
  144807. 10,
  144808. 9,
  144809. 11,
  144810. 8,
  144811. 12,
  144812. 7,
  144813. 13,
  144814. 6,
  144815. 14,
  144816. 5,
  144817. 15,
  144818. 4,
  144819. 16,
  144820. 3,
  144821. 17,
  144822. 2,
  144823. 18,
  144824. 1,
  144825. 19,
  144826. 0,
  144827. 20,
  144828. };
  144829. static long _vq_lengthlist__16u2_p8_1[] = {
  144830. 2, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,10, 9, 9,
  144831. 9,10,10,10,10, 5, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,
  144832. 10, 9,10,10,10,10,10,10,11,10, 5, 6, 6, 7, 7, 8,
  144833. 8, 8, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 7,
  144834. 7, 7, 8, 8, 9, 8, 9, 9,10, 9,10,10,10,10,10,10,
  144835. 11,10,11,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,10, 9,10,
  144836. 10,10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,
  144837. 10, 9,10,10,10,10,10,10,10,11,10,10,11,10, 8, 8,
  144838. 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,
  144839. 11,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  144840. 11,10,11,10,11,10,11,10, 8, 9, 9, 9, 9, 9,10,10,
  144841. 10,10,10,10,10,10,10,10,11,11,10,10,10, 9,10, 9,
  144842. 9,10,10,10,11,10,10,10,10,10,10,10,10,11,11,11,
  144843. 11,11, 9, 9, 9,10, 9,10,10,10,10,10,10,11,10,11,
  144844. 10,11,11,11,11,10,10, 9,10, 9,10,10,10,10,11,10,
  144845. 10,10,10,10,11,10,11,10,11,10,10,11, 9,10,10,10,
  144846. 10,10,10,10,10,10,11,10,10,11,11,10,11,11,11,11,
  144847. 11, 9, 9,10,10,10,10,10,11,10,10,11,10,10,11,10,
  144848. 10,11,11,11,11,11, 9,10,10,10,10,10,10,10,11,10,
  144849. 11,10,11,10,11,11,11,11,11,10,11,10,10,10,10,10,
  144850. 10,10,10,10,11,11,11,11,11,11,11,11,11,10,11,11,
  144851. 10,10,10,10,10,11,10,10,10,11,10,11,11,11,11,10,
  144852. 12,11,11,11,10,10,10,10,10,10,11,10,10,10,11,11,
  144853. 12,11,11,11,11,11,11,11,11,11,10,10,10,11,10,11,
  144854. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  144855. 10,10,11,10,11,10,10,11,11,11,11,11,11,11,11,11,
  144856. 11,11,11,10,10,10,10,10,10,10,11,11,10,11,11,10,
  144857. 11,11,10,11,11,11,10,11,11,
  144858. };
  144859. static float _vq_quantthresh__16u2_p8_1[] = {
  144860. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  144861. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  144862. 6.5, 7.5, 8.5, 9.5,
  144863. };
  144864. static long _vq_quantmap__16u2_p8_1[] = {
  144865. 19, 17, 15, 13, 11, 9, 7, 5,
  144866. 3, 1, 0, 2, 4, 6, 8, 10,
  144867. 12, 14, 16, 18, 20,
  144868. };
  144869. static encode_aux_threshmatch _vq_auxt__16u2_p8_1 = {
  144870. _vq_quantthresh__16u2_p8_1,
  144871. _vq_quantmap__16u2_p8_1,
  144872. 21,
  144873. 21
  144874. };
  144875. static static_codebook _16u2_p8_1 = {
  144876. 2, 441,
  144877. _vq_lengthlist__16u2_p8_1,
  144878. 1, -529268736, 1611661312, 5, 0,
  144879. _vq_quantlist__16u2_p8_1,
  144880. NULL,
  144881. &_vq_auxt__16u2_p8_1,
  144882. NULL,
  144883. 0
  144884. };
  144885. static long _vq_quantlist__16u2_p9_0[] = {
  144886. 5586,
  144887. 4655,
  144888. 6517,
  144889. 3724,
  144890. 7448,
  144891. 2793,
  144892. 8379,
  144893. 1862,
  144894. 9310,
  144895. 931,
  144896. 10241,
  144897. 0,
  144898. 11172,
  144899. 5521,
  144900. 5651,
  144901. };
  144902. static long _vq_lengthlist__16u2_p9_0[] = {
  144903. 1,10,10,10,10,10,10,10,10,10,10,10,10, 5, 4,10,
  144904. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144905. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144906. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144907. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144908. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144909. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144910. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144911. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144912. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144913. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144914. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144915. 10,10,10, 4,10,10,10,10,10,10,10,10,10,10,10,10,
  144916. 6, 6, 5,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 5,
  144917. 5,
  144918. };
  144919. static float _vq_quantthresh__16u2_p9_0[] = {
  144920. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -498, -32.5, 32.5,
  144921. 498, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5,
  144922. };
  144923. static long _vq_quantmap__16u2_p9_0[] = {
  144924. 11, 9, 7, 5, 3, 1, 13, 0,
  144925. 14, 2, 4, 6, 8, 10, 12,
  144926. };
  144927. static encode_aux_threshmatch _vq_auxt__16u2_p9_0 = {
  144928. _vq_quantthresh__16u2_p9_0,
  144929. _vq_quantmap__16u2_p9_0,
  144930. 15,
  144931. 15
  144932. };
  144933. static static_codebook _16u2_p9_0 = {
  144934. 2, 225,
  144935. _vq_lengthlist__16u2_p9_0,
  144936. 1, -510275072, 1611661312, 14, 0,
  144937. _vq_quantlist__16u2_p9_0,
  144938. NULL,
  144939. &_vq_auxt__16u2_p9_0,
  144940. NULL,
  144941. 0
  144942. };
  144943. static long _vq_quantlist__16u2_p9_1[] = {
  144944. 392,
  144945. 343,
  144946. 441,
  144947. 294,
  144948. 490,
  144949. 245,
  144950. 539,
  144951. 196,
  144952. 588,
  144953. 147,
  144954. 637,
  144955. 98,
  144956. 686,
  144957. 49,
  144958. 735,
  144959. 0,
  144960. 784,
  144961. 388,
  144962. 396,
  144963. };
  144964. static long _vq_lengthlist__16u2_p9_1[] = {
  144965. 1,12,10,12,10,12,10,12,11,12,12,12,12,12,12,12,
  144966. 12, 5, 5, 9,10,12,11,11,12,12,12,12,12,12,12,12,
  144967. 12,12,12,12,10, 9, 9,11, 9,11,11,12,11,12,12,12,
  144968. 12,12,12,12,12,12,12, 8, 8,10,11, 9,12,11,12,12,
  144969. 12,12,12,12,12,12,12,12,12,12, 9, 8,10,11,12,11,
  144970. 12,11,12,12,12,12,12,12,12,12,12,12,12, 8, 9,11,
  144971. 11,10,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144972. 9,10,11,12,11,12,11,12,12,12,12,12,12,12,12,12,
  144973. 12,12,12, 9, 9,11,12,12,12,12,12,12,12,12,12,12,
  144974. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144975. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144976. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144977. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144978. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144979. 12,12,12,12,11,11,11,11,11,11,11,11,11,11,11,11,
  144980. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144981. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144982. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144983. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144984. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144985. 11,11,11, 5, 8, 9, 9, 8,11, 9,11,11,11,11,11,11,
  144986. 11,11,11,11, 5, 5, 4, 8, 8, 8, 8,10, 9,10,10,11,
  144987. 11,11,11,11,11,11,11, 5, 4,
  144988. };
  144989. static float _vq_quantthresh__16u2_p9_1[] = {
  144990. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -26.5,
  144991. -2, 2, 26.5, 73.5, 122.5, 171.5, 220.5, 269.5,
  144992. 318.5, 367.5,
  144993. };
  144994. static long _vq_quantmap__16u2_p9_1[] = {
  144995. 15, 13, 11, 9, 7, 5, 3, 1,
  144996. 17, 0, 18, 2, 4, 6, 8, 10,
  144997. 12, 14, 16,
  144998. };
  144999. static encode_aux_threshmatch _vq_auxt__16u2_p9_1 = {
  145000. _vq_quantthresh__16u2_p9_1,
  145001. _vq_quantmap__16u2_p9_1,
  145002. 19,
  145003. 19
  145004. };
  145005. static static_codebook _16u2_p9_1 = {
  145006. 2, 361,
  145007. _vq_lengthlist__16u2_p9_1,
  145008. 1, -518488064, 1611661312, 10, 0,
  145009. _vq_quantlist__16u2_p9_1,
  145010. NULL,
  145011. &_vq_auxt__16u2_p9_1,
  145012. NULL,
  145013. 0
  145014. };
  145015. static long _vq_quantlist__16u2_p9_2[] = {
  145016. 24,
  145017. 23,
  145018. 25,
  145019. 22,
  145020. 26,
  145021. 21,
  145022. 27,
  145023. 20,
  145024. 28,
  145025. 19,
  145026. 29,
  145027. 18,
  145028. 30,
  145029. 17,
  145030. 31,
  145031. 16,
  145032. 32,
  145033. 15,
  145034. 33,
  145035. 14,
  145036. 34,
  145037. 13,
  145038. 35,
  145039. 12,
  145040. 36,
  145041. 11,
  145042. 37,
  145043. 10,
  145044. 38,
  145045. 9,
  145046. 39,
  145047. 8,
  145048. 40,
  145049. 7,
  145050. 41,
  145051. 6,
  145052. 42,
  145053. 5,
  145054. 43,
  145055. 4,
  145056. 44,
  145057. 3,
  145058. 45,
  145059. 2,
  145060. 46,
  145061. 1,
  145062. 47,
  145063. 0,
  145064. 48,
  145065. };
  145066. static long _vq_lengthlist__16u2_p9_2[] = {
  145067. 1, 3, 3, 4, 7, 7, 7, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  145068. 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 9, 9, 8, 9, 9,
  145069. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,12,12,10,
  145070. 11,
  145071. };
  145072. static float _vq_quantthresh__16u2_p9_2[] = {
  145073. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  145074. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  145075. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  145076. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  145077. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  145078. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  145079. };
  145080. static long _vq_quantmap__16u2_p9_2[] = {
  145081. 47, 45, 43, 41, 39, 37, 35, 33,
  145082. 31, 29, 27, 25, 23, 21, 19, 17,
  145083. 15, 13, 11, 9, 7, 5, 3, 1,
  145084. 0, 2, 4, 6, 8, 10, 12, 14,
  145085. 16, 18, 20, 22, 24, 26, 28, 30,
  145086. 32, 34, 36, 38, 40, 42, 44, 46,
  145087. 48,
  145088. };
  145089. static encode_aux_threshmatch _vq_auxt__16u2_p9_2 = {
  145090. _vq_quantthresh__16u2_p9_2,
  145091. _vq_quantmap__16u2_p9_2,
  145092. 49,
  145093. 49
  145094. };
  145095. static static_codebook _16u2_p9_2 = {
  145096. 1, 49,
  145097. _vq_lengthlist__16u2_p9_2,
  145098. 1, -526909440, 1611661312, 6, 0,
  145099. _vq_quantlist__16u2_p9_2,
  145100. NULL,
  145101. &_vq_auxt__16u2_p9_2,
  145102. NULL,
  145103. 0
  145104. };
  145105. static long _vq_quantlist__8u0__p1_0[] = {
  145106. 1,
  145107. 0,
  145108. 2,
  145109. };
  145110. static long _vq_lengthlist__8u0__p1_0[] = {
  145111. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  145112. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 4, 9, 8, 8,11,
  145113. 11, 8,11,11, 7,11,11,10,11,13,10,13,13, 7,11,11,
  145114. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 8,11,11, 7,
  145115. 11,11, 9,13,13,10,12,13, 7,11,11,10,13,13,10,13,
  145116. 11,
  145117. };
  145118. static float _vq_quantthresh__8u0__p1_0[] = {
  145119. -0.5, 0.5,
  145120. };
  145121. static long _vq_quantmap__8u0__p1_0[] = {
  145122. 1, 0, 2,
  145123. };
  145124. static encode_aux_threshmatch _vq_auxt__8u0__p1_0 = {
  145125. _vq_quantthresh__8u0__p1_0,
  145126. _vq_quantmap__8u0__p1_0,
  145127. 3,
  145128. 3
  145129. };
  145130. static static_codebook _8u0__p1_0 = {
  145131. 4, 81,
  145132. _vq_lengthlist__8u0__p1_0,
  145133. 1, -535822336, 1611661312, 2, 0,
  145134. _vq_quantlist__8u0__p1_0,
  145135. NULL,
  145136. &_vq_auxt__8u0__p1_0,
  145137. NULL,
  145138. 0
  145139. };
  145140. static long _vq_quantlist__8u0__p2_0[] = {
  145141. 1,
  145142. 0,
  145143. 2,
  145144. };
  145145. static long _vq_lengthlist__8u0__p2_0[] = {
  145146. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 6, 7, 8, 6,
  145147. 7, 8, 5, 7, 7, 6, 8, 8, 7, 9, 7, 5, 7, 7, 7, 9,
  145148. 9, 7, 8, 8, 6, 9, 8, 7, 7,10, 8,10,10, 6, 8, 8,
  145149. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  145150. 8, 8, 8,10,10, 8, 8,10, 6, 8, 9, 8,10,10, 7,10,
  145151. 8,
  145152. };
  145153. static float _vq_quantthresh__8u0__p2_0[] = {
  145154. -0.5, 0.5,
  145155. };
  145156. static long _vq_quantmap__8u0__p2_0[] = {
  145157. 1, 0, 2,
  145158. };
  145159. static encode_aux_threshmatch _vq_auxt__8u0__p2_0 = {
  145160. _vq_quantthresh__8u0__p2_0,
  145161. _vq_quantmap__8u0__p2_0,
  145162. 3,
  145163. 3
  145164. };
  145165. static static_codebook _8u0__p2_0 = {
  145166. 4, 81,
  145167. _vq_lengthlist__8u0__p2_0,
  145168. 1, -535822336, 1611661312, 2, 0,
  145169. _vq_quantlist__8u0__p2_0,
  145170. NULL,
  145171. &_vq_auxt__8u0__p2_0,
  145172. NULL,
  145173. 0
  145174. };
  145175. static long _vq_quantlist__8u0__p3_0[] = {
  145176. 2,
  145177. 1,
  145178. 3,
  145179. 0,
  145180. 4,
  145181. };
  145182. static long _vq_lengthlist__8u0__p3_0[] = {
  145183. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  145184. 10, 9,11,11, 8, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  145185. 10,11,11, 8,10,10,11,11,10,11,11,12,12,10,11,11,
  145186. 12,13, 6, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  145187. 11, 9,10,11,12,12,10,11,11,12,12, 8,11,11,14,13,
  145188. 10,12,11,15,13,10,12,11,14,14,12,13,12,16,14,12,
  145189. 14,12,16,15, 8,11,11,13,14,10,11,12,13,15,10,11,
  145190. 12,13,15,11,12,13,14,15,12,12,14,14,16, 5, 8, 8,
  145191. 11,11, 9,11,11,12,12, 8,10,11,12,12,11,12,12,15,
  145192. 14,11,12,12,14,14, 7,11,10,13,12,10,11,12,13,14,
  145193. 10,12,12,14,13,12,13,13,14,15,12,13,13,15,15, 7,
  145194. 10,11,12,13,10,12,11,14,13,10,12,13,13,15,12,13,
  145195. 12,14,14,11,13,13,15,16, 9,12,12,15,14,11,13,13,
  145196. 15,16,11,13,13,16,16,13,14,15,15,15,12,14,15,17,
  145197. 16, 9,12,12,14,15,11,13,13,15,16,11,13,13,16,18,
  145198. 13,14,14,17,16,13,15,15,17,18, 5, 8, 9,11,11, 8,
  145199. 11,11,12,12, 8,10,11,12,12,11,12,12,14,14,11,12,
  145200. 12,14,15, 7,11,10,12,13,10,12,12,14,13,10,11,12,
  145201. 13,14,11,13,13,15,14,12,13,13,14,15, 7,10,11,13,
  145202. 13,10,12,12,13,14,10,12,12,13,13,11,13,13,16,16,
  145203. 12,13,13,15,14, 9,12,12,16,15,10,13,13,15,15,11,
  145204. 13,13,17,15,12,15,15,18,17,13,14,14,15,16, 9,12,
  145205. 12,15,15,11,13,13,15,16,11,13,13,15,15,12,15,15,
  145206. 16,16,13,15,14,17,15, 7,11,11,15,15,10,13,13,16,
  145207. 15,10,13,13,15,16,14,15,15,17,19,13,15,14,15,18,
  145208. 9,12,12,16,16,11,13,14,17,16,11,13,13,17,16,15,
  145209. 15,16,17,19,13,15,16, 0,18, 9,12,12,16,15,11,14,
  145210. 13,17,17,11,13,14,16,16,15,16,16,19,18,13,15,15,
  145211. 17,19,11,14,14,19,16,12,14,15, 0,18,12,16,15,18,
  145212. 17,15,15,18,16,19,14,15,17,19,19,11,14,14,18,19,
  145213. 13,15,14,19,19,12,16,15,18,17,15,17,15, 0,16,14,
  145214. 17,16,19, 0, 7,11,11,14,14,10,12,12,15,15,10,13,
  145215. 13,16,15,13,15,15,17, 0,14,15,15,16,19, 9,12,12,
  145216. 16,16,11,14,14,16,16,11,13,13,16,16,14,17,16,19,
  145217. 0,14,18,17,17,19, 9,12,12,15,16,11,13,13,15,17,
  145218. 12,14,13,19,16,13,15,15,17,19,15,17,16,17,19,11,
  145219. 14,14,19,16,12,15,15,19,17,13,14,15,17,19,14,16,
  145220. 17,19,19,16,15,16,17,19,11,15,14,16,16,12,15,15,
  145221. 19, 0,12,14,15,19,19,14,16,16, 0,18,15,19,14,18,
  145222. 16,
  145223. };
  145224. static float _vq_quantthresh__8u0__p3_0[] = {
  145225. -1.5, -0.5, 0.5, 1.5,
  145226. };
  145227. static long _vq_quantmap__8u0__p3_0[] = {
  145228. 3, 1, 0, 2, 4,
  145229. };
  145230. static encode_aux_threshmatch _vq_auxt__8u0__p3_0 = {
  145231. _vq_quantthresh__8u0__p3_0,
  145232. _vq_quantmap__8u0__p3_0,
  145233. 5,
  145234. 5
  145235. };
  145236. static static_codebook _8u0__p3_0 = {
  145237. 4, 625,
  145238. _vq_lengthlist__8u0__p3_0,
  145239. 1, -533725184, 1611661312, 3, 0,
  145240. _vq_quantlist__8u0__p3_0,
  145241. NULL,
  145242. &_vq_auxt__8u0__p3_0,
  145243. NULL,
  145244. 0
  145245. };
  145246. static long _vq_quantlist__8u0__p4_0[] = {
  145247. 2,
  145248. 1,
  145249. 3,
  145250. 0,
  145251. 4,
  145252. };
  145253. static long _vq_lengthlist__8u0__p4_0[] = {
  145254. 3, 5, 5, 8, 8, 5, 6, 7, 9, 9, 6, 7, 6, 9, 9, 9,
  145255. 9, 9,10,11, 9, 9, 9,11,10, 6, 7, 7,10,10, 7, 7,
  145256. 8,10,10, 7, 8, 8,10,10,10,10,10,10,11, 9,10,10,
  145257. 11,12, 6, 7, 7,10,10, 7, 8, 8,10,10, 7, 8, 7,10,
  145258. 10, 9,10,10,12,11,10,10,10,11,10, 9,10,10,12,11,
  145259. 10,10,10,13,11, 9,10,10,12,12,11,11,12,12,13,11,
  145260. 11,11,12,13, 9,10,10,12,12,10,10,11,12,12,10,10,
  145261. 11,12,12,11,11,11,13,13,11,12,12,13,13, 5, 7, 7,
  145262. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,11,12,
  145263. 12,10,11,10,12,12, 7, 8, 8,11,11, 7, 8, 9,10,11,
  145264. 8, 9, 9,11,11,11,10,11,10,12,10,11,11,12,13, 7,
  145265. 8, 8,10,11, 8, 9, 8,12,10, 8, 9, 9,11,12,10,11,
  145266. 10,13,11,10,11,11,13,12, 9,11,10,13,12,10,10,11,
  145267. 12,12,10,11,11,13,13,12,10,13,11,14,11,12,12,15,
  145268. 13, 9,11,11,13,13,10,11,11,13,12,10,11,11,12,14,
  145269. 12,13,11,14,12,12,12,12,14,14, 5, 7, 7,10,10, 7,
  145270. 8, 8,10,10, 7, 8, 8,11,10,10,11,11,12,12,10,11,
  145271. 10,12,12, 7, 8, 8,10,11, 8, 9, 9,12,11, 8, 8, 9,
  145272. 10,11,10,11,11,12,13,11,10,11,11,13, 6, 8, 8,10,
  145273. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,11,11,12,12,
  145274. 10,11,10,13,10, 9,11,10,13,12,10,12,11,13,13,10,
  145275. 10,11,12,13,11,12,13,15,14,11,11,13,12,13, 9,10,
  145276. 11,12,13,10,11,11,12,13,10,11,10,13,12,12,13,13,
  145277. 13,14,12,12,11,14,11, 8,10,10,12,13,10,11,11,13,
  145278. 13,10,11,10,13,13,12,13,14,15,14,12,12,12,14,13,
  145279. 9,10,10,13,12,10,10,12,13,13,10,11,11,15,12,12,
  145280. 12,13,15,14,12,13,13,15,13, 9,10,11,12,13,10,12,
  145281. 10,13,12,10,11,11,12,13,12,14,12,15,13,12,12,12,
  145282. 15,14,11,12,11,14,13,11,11,12,14,14,12,13,13,14,
  145283. 13,13,11,15,11,15,14,14,14,16,15,11,12,12,13,14,
  145284. 11,13,11,14,14,12,12,13,14,15,12,14,12,15,12,13,
  145285. 15,14,16,15, 8,10,10,12,12,10,10,10,12,13,10,11,
  145286. 11,13,13,12,12,12,13,14,13,13,13,15,15, 9,10,10,
  145287. 12,12,10,11,11,13,12,10,10,11,13,13,12,12,12,14,
  145288. 14,12,12,13,15,14, 9,10,10,13,12,10,10,12,12,13,
  145289. 10,11,10,13,13,12,13,13,14,14,12,13,12,14,13,11,
  145290. 12,12,14,13,12,13,12,14,14,10,12,12,14,14,14,14,
  145291. 14,16,14,13,12,14,12,15,10,12,12,14,15,12,13,13,
  145292. 14,16,11,12,11,15,14,13,14,14,14,15,13,14,11,14,
  145293. 12,
  145294. };
  145295. static float _vq_quantthresh__8u0__p4_0[] = {
  145296. -1.5, -0.5, 0.5, 1.5,
  145297. };
  145298. static long _vq_quantmap__8u0__p4_0[] = {
  145299. 3, 1, 0, 2, 4,
  145300. };
  145301. static encode_aux_threshmatch _vq_auxt__8u0__p4_0 = {
  145302. _vq_quantthresh__8u0__p4_0,
  145303. _vq_quantmap__8u0__p4_0,
  145304. 5,
  145305. 5
  145306. };
  145307. static static_codebook _8u0__p4_0 = {
  145308. 4, 625,
  145309. _vq_lengthlist__8u0__p4_0,
  145310. 1, -533725184, 1611661312, 3, 0,
  145311. _vq_quantlist__8u0__p4_0,
  145312. NULL,
  145313. &_vq_auxt__8u0__p4_0,
  145314. NULL,
  145315. 0
  145316. };
  145317. static long _vq_quantlist__8u0__p5_0[] = {
  145318. 4,
  145319. 3,
  145320. 5,
  145321. 2,
  145322. 6,
  145323. 1,
  145324. 7,
  145325. 0,
  145326. 8,
  145327. };
  145328. static long _vq_lengthlist__8u0__p5_0[] = {
  145329. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 7, 8, 8,
  145330. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 6, 8, 8, 9, 9,
  145331. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  145332. 9, 9,10,10,12,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  145333. 10,10,11,11,11,12,12,12, 9,10,10,11,11,12,12,12,
  145334. 12,
  145335. };
  145336. static float _vq_quantthresh__8u0__p5_0[] = {
  145337. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145338. };
  145339. static long _vq_quantmap__8u0__p5_0[] = {
  145340. 7, 5, 3, 1, 0, 2, 4, 6,
  145341. 8,
  145342. };
  145343. static encode_aux_threshmatch _vq_auxt__8u0__p5_0 = {
  145344. _vq_quantthresh__8u0__p5_0,
  145345. _vq_quantmap__8u0__p5_0,
  145346. 9,
  145347. 9
  145348. };
  145349. static static_codebook _8u0__p5_0 = {
  145350. 2, 81,
  145351. _vq_lengthlist__8u0__p5_0,
  145352. 1, -531628032, 1611661312, 4, 0,
  145353. _vq_quantlist__8u0__p5_0,
  145354. NULL,
  145355. &_vq_auxt__8u0__p5_0,
  145356. NULL,
  145357. 0
  145358. };
  145359. static long _vq_quantlist__8u0__p6_0[] = {
  145360. 6,
  145361. 5,
  145362. 7,
  145363. 4,
  145364. 8,
  145365. 3,
  145366. 9,
  145367. 2,
  145368. 10,
  145369. 1,
  145370. 11,
  145371. 0,
  145372. 12,
  145373. };
  145374. static long _vq_lengthlist__8u0__p6_0[] = {
  145375. 1, 4, 4, 7, 7, 9, 9,11,11,12,12,16,16, 3, 6, 6,
  145376. 9, 9,11,11,12,12,13,14,18,16, 3, 6, 7, 9, 9,11,
  145377. 11,13,12,14,14,17,16, 7, 9, 9,11,11,12,12,14,14,
  145378. 14,14,17,16, 7, 9, 9,11,11,13,12,13,13,14,14,17,
  145379. 0, 9,11,11,12,13,14,14,14,13,15,14,17,17, 9,11,
  145380. 11,12,12,14,14,13,14,14,15, 0, 0,11,12,12,15,14,
  145381. 15,14,15,14,15,16,17, 0,11,12,13,13,13,14,14,15,
  145382. 14,15,15, 0, 0,12,14,14,15,15,14,16,15,15,17,16,
  145383. 0,18,13,14,14,15,14,15,14,15,16,17,16, 0, 0,17,
  145384. 17,18, 0,16,18,16, 0, 0, 0,17, 0, 0,16, 0, 0,16,
  145385. 16, 0,15, 0,17, 0, 0, 0, 0,
  145386. };
  145387. static float _vq_quantthresh__8u0__p6_0[] = {
  145388. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  145389. 12.5, 17.5, 22.5, 27.5,
  145390. };
  145391. static long _vq_quantmap__8u0__p6_0[] = {
  145392. 11, 9, 7, 5, 3, 1, 0, 2,
  145393. 4, 6, 8, 10, 12,
  145394. };
  145395. static encode_aux_threshmatch _vq_auxt__8u0__p6_0 = {
  145396. _vq_quantthresh__8u0__p6_0,
  145397. _vq_quantmap__8u0__p6_0,
  145398. 13,
  145399. 13
  145400. };
  145401. static static_codebook _8u0__p6_0 = {
  145402. 2, 169,
  145403. _vq_lengthlist__8u0__p6_0,
  145404. 1, -526516224, 1616117760, 4, 0,
  145405. _vq_quantlist__8u0__p6_0,
  145406. NULL,
  145407. &_vq_auxt__8u0__p6_0,
  145408. NULL,
  145409. 0
  145410. };
  145411. static long _vq_quantlist__8u0__p6_1[] = {
  145412. 2,
  145413. 1,
  145414. 3,
  145415. 0,
  145416. 4,
  145417. };
  145418. static long _vq_lengthlist__8u0__p6_1[] = {
  145419. 1, 4, 4, 6, 6, 4, 6, 5, 7, 7, 4, 5, 6, 7, 7, 6,
  145420. 7, 7, 7, 7, 6, 7, 7, 7, 7,
  145421. };
  145422. static float _vq_quantthresh__8u0__p6_1[] = {
  145423. -1.5, -0.5, 0.5, 1.5,
  145424. };
  145425. static long _vq_quantmap__8u0__p6_1[] = {
  145426. 3, 1, 0, 2, 4,
  145427. };
  145428. static encode_aux_threshmatch _vq_auxt__8u0__p6_1 = {
  145429. _vq_quantthresh__8u0__p6_1,
  145430. _vq_quantmap__8u0__p6_1,
  145431. 5,
  145432. 5
  145433. };
  145434. static static_codebook _8u0__p6_1 = {
  145435. 2, 25,
  145436. _vq_lengthlist__8u0__p6_1,
  145437. 1, -533725184, 1611661312, 3, 0,
  145438. _vq_quantlist__8u0__p6_1,
  145439. NULL,
  145440. &_vq_auxt__8u0__p6_1,
  145441. NULL,
  145442. 0
  145443. };
  145444. static long _vq_quantlist__8u0__p7_0[] = {
  145445. 1,
  145446. 0,
  145447. 2,
  145448. };
  145449. static long _vq_lengthlist__8u0__p7_0[] = {
  145450. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145451. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145452. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145453. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145454. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145455. 7,
  145456. };
  145457. static float _vq_quantthresh__8u0__p7_0[] = {
  145458. -157.5, 157.5,
  145459. };
  145460. static long _vq_quantmap__8u0__p7_0[] = {
  145461. 1, 0, 2,
  145462. };
  145463. static encode_aux_threshmatch _vq_auxt__8u0__p7_0 = {
  145464. _vq_quantthresh__8u0__p7_0,
  145465. _vq_quantmap__8u0__p7_0,
  145466. 3,
  145467. 3
  145468. };
  145469. static static_codebook _8u0__p7_0 = {
  145470. 4, 81,
  145471. _vq_lengthlist__8u0__p7_0,
  145472. 1, -518803456, 1628680192, 2, 0,
  145473. _vq_quantlist__8u0__p7_0,
  145474. NULL,
  145475. &_vq_auxt__8u0__p7_0,
  145476. NULL,
  145477. 0
  145478. };
  145479. static long _vq_quantlist__8u0__p7_1[] = {
  145480. 7,
  145481. 6,
  145482. 8,
  145483. 5,
  145484. 9,
  145485. 4,
  145486. 10,
  145487. 3,
  145488. 11,
  145489. 2,
  145490. 12,
  145491. 1,
  145492. 13,
  145493. 0,
  145494. 14,
  145495. };
  145496. static long _vq_lengthlist__8u0__p7_1[] = {
  145497. 1, 5, 5, 5, 5,10,10,11,11,11,11,11,11,11,11, 5,
  145498. 7, 6, 8, 8, 9,10,11,11,11,11,11,11,11,11, 6, 6,
  145499. 7, 9, 7,11,10,11,11,11,11,11,11,11,11, 5, 6, 6,
  145500. 11, 8,11,11,11,11,11,11,11,11,11,11, 5, 6, 6, 9,
  145501. 10,11,10,11,11,11,11,11,11,11,11, 7,10,10,11,11,
  145502. 11,11,11,11,11,11,11,11,11,11, 7,11, 8,11,11,11,
  145503. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145504. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145505. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145506. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145507. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145508. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145509. 11,11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,
  145510. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145511. 10,
  145512. };
  145513. static float _vq_quantthresh__8u0__p7_1[] = {
  145514. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  145515. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  145516. };
  145517. static long _vq_quantmap__8u0__p7_1[] = {
  145518. 13, 11, 9, 7, 5, 3, 1, 0,
  145519. 2, 4, 6, 8, 10, 12, 14,
  145520. };
  145521. static encode_aux_threshmatch _vq_auxt__8u0__p7_1 = {
  145522. _vq_quantthresh__8u0__p7_1,
  145523. _vq_quantmap__8u0__p7_1,
  145524. 15,
  145525. 15
  145526. };
  145527. static static_codebook _8u0__p7_1 = {
  145528. 2, 225,
  145529. _vq_lengthlist__8u0__p7_1,
  145530. 1, -520986624, 1620377600, 4, 0,
  145531. _vq_quantlist__8u0__p7_1,
  145532. NULL,
  145533. &_vq_auxt__8u0__p7_1,
  145534. NULL,
  145535. 0
  145536. };
  145537. static long _vq_quantlist__8u0__p7_2[] = {
  145538. 10,
  145539. 9,
  145540. 11,
  145541. 8,
  145542. 12,
  145543. 7,
  145544. 13,
  145545. 6,
  145546. 14,
  145547. 5,
  145548. 15,
  145549. 4,
  145550. 16,
  145551. 3,
  145552. 17,
  145553. 2,
  145554. 18,
  145555. 1,
  145556. 19,
  145557. 0,
  145558. 20,
  145559. };
  145560. static long _vq_lengthlist__8u0__p7_2[] = {
  145561. 1, 6, 5, 7, 7, 9, 9, 9, 9,10,12,12,10,11,11,10,
  145562. 11,11,11,10,11, 6, 8, 8, 9, 9,10,10, 9,10,11,11,
  145563. 10,11,11,11,11,10,11,11,11,11, 6, 7, 8, 9, 9, 9,
  145564. 10,11,10,11,12,11,10,11,11,11,11,11,11,12,10, 8,
  145565. 9, 9,10, 9,10,10, 9,10,10,10,10,10, 9,10,10,10,
  145566. 10, 9,10,10, 9, 9, 9, 9,10,10, 9, 9,10,10,11,10,
  145567. 9,12,10,11,10, 9,10,10,10, 8, 9, 9,10, 9,10, 9,
  145568. 9,10,10, 9,10, 9,11,10,10,10,10,10, 9,10, 8, 8,
  145569. 9, 9,10, 9,11, 9, 8, 9, 9,10,11,10,10,10,11,12,
  145570. 9, 9,11, 8, 9, 8,11,10,11,10,10, 9,11,10,10,10,
  145571. 10,10,10,10,11,11,11,11, 8, 9, 9, 9,10,10,10,11,
  145572. 11,12,11,12,11,10,10,10,12,11,11,11,10, 8,10, 9,
  145573. 11,10,10,11,12,10,11,12,11,11,12,11,12,12,10,11,
  145574. 11,10, 9, 9,10,11,12,10,10,10,11,10,11,11,10,12,
  145575. 12,10,11,10,11,12,10, 9,10,10,11,10,11,11,11,11,
  145576. 11,12,11,11,11, 9,11,10,11,10,11,10, 9, 9,10,11,
  145577. 11,11,10,10,11,12,12,11,12,11,11,11,12,12,12,12,
  145578. 11, 9,11,11,12,10,11,11,11,11,11,11,12,11,11,12,
  145579. 11,11,11,10,11,11, 9,11,10,11,11,11,10,10,10,11,
  145580. 11,11,12,10,11,10,11,11,11,11,12, 9,11,10,11,11,
  145581. 10,10,11,11, 9,11,11,12,10,10,10,10,10,11,11,10,
  145582. 9,10,11,11,12,11,10,10,12,11,11,12,11,12,11,11,
  145583. 10,10,11,11,10,12,11,10,11,10,11,10,10,10,11,11,
  145584. 10,10,11,11,11,11,10,10,10,12,11,11,11,11,10, 9,
  145585. 10,11,11,11,12,11,11,11,12,10,11,11,11, 9,10,11,
  145586. 11,11,11,11,11,10,10,11,11,12,11,10,11,12,11,10,
  145587. 10,11, 9,10,11,11,11,11,11,10,11,11,10,12,11,11,
  145588. 11,12,11,11,11,10,10,11,11,
  145589. };
  145590. static float _vq_quantthresh__8u0__p7_2[] = {
  145591. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  145592. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  145593. 6.5, 7.5, 8.5, 9.5,
  145594. };
  145595. static long _vq_quantmap__8u0__p7_2[] = {
  145596. 19, 17, 15, 13, 11, 9, 7, 5,
  145597. 3, 1, 0, 2, 4, 6, 8, 10,
  145598. 12, 14, 16, 18, 20,
  145599. };
  145600. static encode_aux_threshmatch _vq_auxt__8u0__p7_2 = {
  145601. _vq_quantthresh__8u0__p7_2,
  145602. _vq_quantmap__8u0__p7_2,
  145603. 21,
  145604. 21
  145605. };
  145606. static static_codebook _8u0__p7_2 = {
  145607. 2, 441,
  145608. _vq_lengthlist__8u0__p7_2,
  145609. 1, -529268736, 1611661312, 5, 0,
  145610. _vq_quantlist__8u0__p7_2,
  145611. NULL,
  145612. &_vq_auxt__8u0__p7_2,
  145613. NULL,
  145614. 0
  145615. };
  145616. static long _huff_lengthlist__8u0__single[] = {
  145617. 4, 7,11, 9,12, 8, 7,10, 6, 4, 5, 5, 7, 5, 6,16,
  145618. 9, 5, 5, 6, 7, 7, 9,16, 7, 4, 6, 5, 7, 5, 7,17,
  145619. 10, 7, 7, 8, 7, 7, 8,18, 7, 5, 6, 4, 5, 4, 5,15,
  145620. 7, 6, 7, 5, 6, 4, 5,15,12,13,18,12,17,11, 9,17,
  145621. };
  145622. static static_codebook _huff_book__8u0__single = {
  145623. 2, 64,
  145624. _huff_lengthlist__8u0__single,
  145625. 0, 0, 0, 0, 0,
  145626. NULL,
  145627. NULL,
  145628. NULL,
  145629. NULL,
  145630. 0
  145631. };
  145632. static long _vq_quantlist__8u1__p1_0[] = {
  145633. 1,
  145634. 0,
  145635. 2,
  145636. };
  145637. static long _vq_lengthlist__8u1__p1_0[] = {
  145638. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 7, 9,10, 7,
  145639. 9, 9, 5, 8, 8, 7,10, 9, 7, 9, 9, 5, 8, 8, 8,10,
  145640. 10, 8,10,10, 7,10,10, 9,10,12,10,12,12, 7,10,10,
  145641. 9,12,11,10,12,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  145642. 10,10,10,12,12, 9,11,12, 7,10,10,10,12,12, 9,12,
  145643. 10,
  145644. };
  145645. static float _vq_quantthresh__8u1__p1_0[] = {
  145646. -0.5, 0.5,
  145647. };
  145648. static long _vq_quantmap__8u1__p1_0[] = {
  145649. 1, 0, 2,
  145650. };
  145651. static encode_aux_threshmatch _vq_auxt__8u1__p1_0 = {
  145652. _vq_quantthresh__8u1__p1_0,
  145653. _vq_quantmap__8u1__p1_0,
  145654. 3,
  145655. 3
  145656. };
  145657. static static_codebook _8u1__p1_0 = {
  145658. 4, 81,
  145659. _vq_lengthlist__8u1__p1_0,
  145660. 1, -535822336, 1611661312, 2, 0,
  145661. _vq_quantlist__8u1__p1_0,
  145662. NULL,
  145663. &_vq_auxt__8u1__p1_0,
  145664. NULL,
  145665. 0
  145666. };
  145667. static long _vq_quantlist__8u1__p2_0[] = {
  145668. 1,
  145669. 0,
  145670. 2,
  145671. };
  145672. static long _vq_lengthlist__8u1__p2_0[] = {
  145673. 3, 4, 5, 5, 6, 6, 5, 6, 6, 5, 7, 6, 6, 7, 8, 6,
  145674. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 7, 8,
  145675. 8, 6, 7, 7, 6, 8, 7, 7, 7, 9, 8, 9, 9, 6, 7, 8,
  145676. 7, 9, 7, 8, 9, 9, 5, 6, 6, 6, 7, 7, 7, 8, 8, 6,
  145677. 8, 7, 8, 9, 9, 7, 7, 9, 6, 7, 8, 8, 9, 9, 7, 9,
  145678. 7,
  145679. };
  145680. static float _vq_quantthresh__8u1__p2_0[] = {
  145681. -0.5, 0.5,
  145682. };
  145683. static long _vq_quantmap__8u1__p2_0[] = {
  145684. 1, 0, 2,
  145685. };
  145686. static encode_aux_threshmatch _vq_auxt__8u1__p2_0 = {
  145687. _vq_quantthresh__8u1__p2_0,
  145688. _vq_quantmap__8u1__p2_0,
  145689. 3,
  145690. 3
  145691. };
  145692. static static_codebook _8u1__p2_0 = {
  145693. 4, 81,
  145694. _vq_lengthlist__8u1__p2_0,
  145695. 1, -535822336, 1611661312, 2, 0,
  145696. _vq_quantlist__8u1__p2_0,
  145697. NULL,
  145698. &_vq_auxt__8u1__p2_0,
  145699. NULL,
  145700. 0
  145701. };
  145702. static long _vq_quantlist__8u1__p3_0[] = {
  145703. 2,
  145704. 1,
  145705. 3,
  145706. 0,
  145707. 4,
  145708. };
  145709. static long _vq_lengthlist__8u1__p3_0[] = {
  145710. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  145711. 10, 9,11,11, 9, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  145712. 10,11,11, 8, 9,10,11,11,10,11,11,12,12,10,11,11,
  145713. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  145714. 11,10,11,11,12,12,10,11,11,12,12, 9,11,11,14,13,
  145715. 10,12,11,14,14,10,12,11,14,13,12,13,13,15,14,12,
  145716. 13,13,15,14, 8,11,11,13,14,10,11,12,13,15,10,11,
  145717. 12,14,14,12,13,13,14,15,12,13,13,14,15, 5, 8, 8,
  145718. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  145719. 13,11,12,12,13,14, 8,10,10,12,12, 9,11,12,13,14,
  145720. 10,12,12,13,13,12,12,13,14,14,11,13,13,15,15, 7,
  145721. 10,10,12,12, 9,12,11,14,12,10,11,12,13,14,12,13,
  145722. 12,14,14,12,13,13,15,16,10,12,12,15,14,11,12,13,
  145723. 15,15,11,13,13,15,16,14,14,15,15,16,13,14,15,17,
  145724. 15, 9,12,12,14,15,11,13,12,15,15,11,13,13,15,15,
  145725. 13,14,13,15,14,13,14,14,17, 0, 5, 8, 8,11,11, 8,
  145726. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  145727. 12,14,14, 7,10,10,12,12,10,12,12,13,13, 9,11,12,
  145728. 12,13,11,12,13,15,15,11,12,13,14,15, 8,10,10,12,
  145729. 12,10,12,11,13,13,10,12,11,13,13,11,13,13,15,14,
  145730. 12,13,12,15,13, 9,12,12,14,14,11,13,13,16,15,11,
  145731. 12,13,16,15,13,14,15,16,16,13,13,15,15,16,10,12,
  145732. 12,15,14,11,13,13,14,16,11,13,13,15,16,13,15,15,
  145733. 16,17,13,15,14,16,15, 8,11,11,14,15,10,12,12,15,
  145734. 15,10,12,12,15,16,14,15,15,16,17,13,14,14,16,16,
  145735. 9,12,12,15,15,11,13,14,15,17,11,13,13,15,16,14,
  145736. 15,16,19,17,13,15,15, 0,17, 9,12,12,15,15,11,14,
  145737. 13,16,15,11,13,13,15,16,15,15,15,18,17,13,15,15,
  145738. 17,17,11,15,14,18,16,12,14,15,17,17,12,15,15,18,
  145739. 18,15,15,16,15,19,14,16,16, 0, 0,11,14,14,16,17,
  145740. 12,15,14,18,17,12,15,15,18,18,15,17,15,18,16,14,
  145741. 16,16,18,18, 7,11,11,14,14,10,12,12,15,15,10,12,
  145742. 13,15,15,13,14,15,16,16,14,15,15,18,18, 9,12,12,
  145743. 15,15,11,13,13,16,15,11,12,13,16,16,14,15,15,17,
  145744. 16,15,16,16,17,17, 9,12,12,15,15,11,13,13,15,17,
  145745. 11,14,13,16,15,13,15,15,17,17,15,15,15,18,17,11,
  145746. 14,14,17,15,12,14,15,17,18,13,13,15,17,17,14,16,
  145747. 16,19,18,16,15,17,17, 0,11,14,14,17,17,12,15,15,
  145748. 18, 0,12,15,14,18,16,14,17,17,19, 0,16,18,15, 0,
  145749. 16,
  145750. };
  145751. static float _vq_quantthresh__8u1__p3_0[] = {
  145752. -1.5, -0.5, 0.5, 1.5,
  145753. };
  145754. static long _vq_quantmap__8u1__p3_0[] = {
  145755. 3, 1, 0, 2, 4,
  145756. };
  145757. static encode_aux_threshmatch _vq_auxt__8u1__p3_0 = {
  145758. _vq_quantthresh__8u1__p3_0,
  145759. _vq_quantmap__8u1__p3_0,
  145760. 5,
  145761. 5
  145762. };
  145763. static static_codebook _8u1__p3_0 = {
  145764. 4, 625,
  145765. _vq_lengthlist__8u1__p3_0,
  145766. 1, -533725184, 1611661312, 3, 0,
  145767. _vq_quantlist__8u1__p3_0,
  145768. NULL,
  145769. &_vq_auxt__8u1__p3_0,
  145770. NULL,
  145771. 0
  145772. };
  145773. static long _vq_quantlist__8u1__p4_0[] = {
  145774. 2,
  145775. 1,
  145776. 3,
  145777. 0,
  145778. 4,
  145779. };
  145780. static long _vq_lengthlist__8u1__p4_0[] = {
  145781. 4, 5, 5, 9, 9, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 9,
  145782. 9, 9,11,11, 9, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 7,
  145783. 8, 9,10, 7, 7, 8, 9,10, 9, 9,10,10,11, 9, 9,10,
  145784. 10,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 7,10,
  145785. 9, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  145786. 9,10,10,12,11, 9,10,10,12,12,11,11,12,12,13,11,
  145787. 11,12,12,13, 9, 9,10,12,11, 9,10,10,12,12,10,10,
  145788. 10,12,12,11,12,11,13,12,11,12,11,13,12, 6, 7, 7,
  145789. 9, 9, 7, 8, 8,10,10, 7, 8, 7,10, 9,10,10,10,12,
  145790. 12,10,10,10,12,11, 7, 8, 7,10,10, 7, 7, 9,10,11,
  145791. 8, 9, 9,11,10,10,10,11,10,12,10,10,11,12,12, 7,
  145792. 8, 8,10,10, 7, 9, 8,11,10, 8, 8, 9,11,11,10,11,
  145793. 10,12,11,10,11,11,12,12, 9,10,10,12,12, 9,10,10,
  145794. 12,12,10,11,11,13,12,11,10,12,10,14,12,12,12,13,
  145795. 14, 9,10,10,12,12, 9,11,10,12,12,10,11,11,12,12,
  145796. 11,12,11,14,12,12,12,12,14,14, 5, 7, 7, 9, 9, 7,
  145797. 7, 7, 9,10, 7, 8, 8,10,10,10,10,10,11,11,10,10,
  145798. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  145799. 10,11,10,10,10,11,12,10,10,11,11,13, 6, 7, 8,10,
  145800. 10, 8, 9, 9,10,10, 7, 9, 7,11,10,10,11,10,12,12,
  145801. 10,11,10,12,10, 9,10,10,12,12,10,11,11,13,12, 9,
  145802. 10,10,12,12,12,12,12,14,13,11,11,12,11,14, 9,10,
  145803. 10,11,12,10,11,11,12,13, 9,10,10,12,12,12,12,12,
  145804. 14,13,11,12,10,14,11, 9, 9,10,11,12, 9,10,10,12,
  145805. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,13,12,
  145806. 9,10, 9,12,12, 9,10,11,12,13,10,11,10,13,11,12,
  145807. 12,13,13,14,12,12,12,13,13, 9,10,10,12,12,10,11,
  145808. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,12,
  145809. 13,14,11,12,11,14,13,10,10,11,13,13,12,12,12,14,
  145810. 13,12,10,14,10,15,13,14,14,14,14,11,11,12,13,14,
  145811. 10,12,11,13,13,12,12,12,13,15,12,13,11,15,12,13,
  145812. 13,14,14,14, 9,10, 9,12,12, 9,10,10,12,12,10,10,
  145813. 10,12,12,11,11,12,12,13,12,12,12,14,14, 9,10,10,
  145814. 12,12,10,11,10,13,12,10,10,11,12,13,12,12,12,14,
  145815. 13,12,12,13,13,14, 9,10,10,12,13,10,10,11,11,12,
  145816. 9,11,10,13,12,12,12,12,13,14,12,13,12,14,13,11,
  145817. 12,11,13,13,12,13,12,14,13,10,11,12,13,13,13,13,
  145818. 13,14,15,12,11,14,12,14,11,11,12,12,13,12,12,12,
  145819. 13,14,10,12,10,14,13,13,13,13,14,15,12,14,11,15,
  145820. 10,
  145821. };
  145822. static float _vq_quantthresh__8u1__p4_0[] = {
  145823. -1.5, -0.5, 0.5, 1.5,
  145824. };
  145825. static long _vq_quantmap__8u1__p4_0[] = {
  145826. 3, 1, 0, 2, 4,
  145827. };
  145828. static encode_aux_threshmatch _vq_auxt__8u1__p4_0 = {
  145829. _vq_quantthresh__8u1__p4_0,
  145830. _vq_quantmap__8u1__p4_0,
  145831. 5,
  145832. 5
  145833. };
  145834. static static_codebook _8u1__p4_0 = {
  145835. 4, 625,
  145836. _vq_lengthlist__8u1__p4_0,
  145837. 1, -533725184, 1611661312, 3, 0,
  145838. _vq_quantlist__8u1__p4_0,
  145839. NULL,
  145840. &_vq_auxt__8u1__p4_0,
  145841. NULL,
  145842. 0
  145843. };
  145844. static long _vq_quantlist__8u1__p5_0[] = {
  145845. 4,
  145846. 3,
  145847. 5,
  145848. 2,
  145849. 6,
  145850. 1,
  145851. 7,
  145852. 0,
  145853. 8,
  145854. };
  145855. static long _vq_lengthlist__8u1__p5_0[] = {
  145856. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  145857. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  145858. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  145859. 9, 9,10,10,12,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  145860. 10,10,11,11,11,11,13,12, 9,10,10,11,11,12,12,12,
  145861. 13,
  145862. };
  145863. static float _vq_quantthresh__8u1__p5_0[] = {
  145864. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145865. };
  145866. static long _vq_quantmap__8u1__p5_0[] = {
  145867. 7, 5, 3, 1, 0, 2, 4, 6,
  145868. 8,
  145869. };
  145870. static encode_aux_threshmatch _vq_auxt__8u1__p5_0 = {
  145871. _vq_quantthresh__8u1__p5_0,
  145872. _vq_quantmap__8u1__p5_0,
  145873. 9,
  145874. 9
  145875. };
  145876. static static_codebook _8u1__p5_0 = {
  145877. 2, 81,
  145878. _vq_lengthlist__8u1__p5_0,
  145879. 1, -531628032, 1611661312, 4, 0,
  145880. _vq_quantlist__8u1__p5_0,
  145881. NULL,
  145882. &_vq_auxt__8u1__p5_0,
  145883. NULL,
  145884. 0
  145885. };
  145886. static long _vq_quantlist__8u1__p6_0[] = {
  145887. 4,
  145888. 3,
  145889. 5,
  145890. 2,
  145891. 6,
  145892. 1,
  145893. 7,
  145894. 0,
  145895. 8,
  145896. };
  145897. static long _vq_lengthlist__8u1__p6_0[] = {
  145898. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 5, 6, 6, 7, 7,
  145899. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  145900. 8, 8, 9, 9, 6, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  145901. 8, 8, 8, 9,10,10, 7, 7, 7, 8, 8, 9, 8,10,10, 9,
  145902. 9, 9, 9, 9,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  145903. 10,
  145904. };
  145905. static float _vq_quantthresh__8u1__p6_0[] = {
  145906. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145907. };
  145908. static long _vq_quantmap__8u1__p6_0[] = {
  145909. 7, 5, 3, 1, 0, 2, 4, 6,
  145910. 8,
  145911. };
  145912. static encode_aux_threshmatch _vq_auxt__8u1__p6_0 = {
  145913. _vq_quantthresh__8u1__p6_0,
  145914. _vq_quantmap__8u1__p6_0,
  145915. 9,
  145916. 9
  145917. };
  145918. static static_codebook _8u1__p6_0 = {
  145919. 2, 81,
  145920. _vq_lengthlist__8u1__p6_0,
  145921. 1, -531628032, 1611661312, 4, 0,
  145922. _vq_quantlist__8u1__p6_0,
  145923. NULL,
  145924. &_vq_auxt__8u1__p6_0,
  145925. NULL,
  145926. 0
  145927. };
  145928. static long _vq_quantlist__8u1__p7_0[] = {
  145929. 1,
  145930. 0,
  145931. 2,
  145932. };
  145933. static long _vq_lengthlist__8u1__p7_0[] = {
  145934. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,10,10, 8,
  145935. 10,10, 5, 9, 9, 7,10,10, 8,10,10, 4,10,10, 9,12,
  145936. 12, 9,11,11, 7,12,11,10,11,13,10,13,13, 7,12,12,
  145937. 10,13,12,10,13,13, 4,10,10, 9,12,12, 9,12,12, 7,
  145938. 12,12,10,13,13,10,12,13, 7,11,12,10,13,13,10,13,
  145939. 11,
  145940. };
  145941. static float _vq_quantthresh__8u1__p7_0[] = {
  145942. -5.5, 5.5,
  145943. };
  145944. static long _vq_quantmap__8u1__p7_0[] = {
  145945. 1, 0, 2,
  145946. };
  145947. static encode_aux_threshmatch _vq_auxt__8u1__p7_0 = {
  145948. _vq_quantthresh__8u1__p7_0,
  145949. _vq_quantmap__8u1__p7_0,
  145950. 3,
  145951. 3
  145952. };
  145953. static static_codebook _8u1__p7_0 = {
  145954. 4, 81,
  145955. _vq_lengthlist__8u1__p7_0,
  145956. 1, -529137664, 1618345984, 2, 0,
  145957. _vq_quantlist__8u1__p7_0,
  145958. NULL,
  145959. &_vq_auxt__8u1__p7_0,
  145960. NULL,
  145961. 0
  145962. };
  145963. static long _vq_quantlist__8u1__p7_1[] = {
  145964. 5,
  145965. 4,
  145966. 6,
  145967. 3,
  145968. 7,
  145969. 2,
  145970. 8,
  145971. 1,
  145972. 9,
  145973. 0,
  145974. 10,
  145975. };
  145976. static long _vq_lengthlist__8u1__p7_1[] = {
  145977. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  145978. 8, 8, 9, 9, 9, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 9,
  145979. 9, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  145980. 8, 8, 8, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  145981. 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  145982. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  145983. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  145984. 9, 9, 9, 9, 9,10,10,10,10,
  145985. };
  145986. static float _vq_quantthresh__8u1__p7_1[] = {
  145987. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  145988. 3.5, 4.5,
  145989. };
  145990. static long _vq_quantmap__8u1__p7_1[] = {
  145991. 9, 7, 5, 3, 1, 0, 2, 4,
  145992. 6, 8, 10,
  145993. };
  145994. static encode_aux_threshmatch _vq_auxt__8u1__p7_1 = {
  145995. _vq_quantthresh__8u1__p7_1,
  145996. _vq_quantmap__8u1__p7_1,
  145997. 11,
  145998. 11
  145999. };
  146000. static static_codebook _8u1__p7_1 = {
  146001. 2, 121,
  146002. _vq_lengthlist__8u1__p7_1,
  146003. 1, -531365888, 1611661312, 4, 0,
  146004. _vq_quantlist__8u1__p7_1,
  146005. NULL,
  146006. &_vq_auxt__8u1__p7_1,
  146007. NULL,
  146008. 0
  146009. };
  146010. static long _vq_quantlist__8u1__p8_0[] = {
  146011. 5,
  146012. 4,
  146013. 6,
  146014. 3,
  146015. 7,
  146016. 2,
  146017. 8,
  146018. 1,
  146019. 9,
  146020. 0,
  146021. 10,
  146022. };
  146023. static long _vq_lengthlist__8u1__p8_0[] = {
  146024. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  146025. 9, 9,11,11,13,12, 4, 6, 6, 7, 7, 9, 9,11,11,12,
  146026. 12, 6, 7, 7, 9, 9,11,11,12,12,13,13, 6, 7, 7, 9,
  146027. 9,11,11,12,12,13,13, 8, 9, 9,11,11,12,12,13,13,
  146028. 14,14, 8, 9, 9,11,11,12,12,13,13,14,14, 9,11,11,
  146029. 12,12,13,13,14,14,15,15, 9,11,11,12,12,13,13,14,
  146030. 14,15,14,11,12,12,13,13,14,14,15,15,16,16,11,12,
  146031. 12,13,13,14,14,15,15,15,15,
  146032. };
  146033. static float _vq_quantthresh__8u1__p8_0[] = {
  146034. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  146035. 38.5, 49.5,
  146036. };
  146037. static long _vq_quantmap__8u1__p8_0[] = {
  146038. 9, 7, 5, 3, 1, 0, 2, 4,
  146039. 6, 8, 10,
  146040. };
  146041. static encode_aux_threshmatch _vq_auxt__8u1__p8_0 = {
  146042. _vq_quantthresh__8u1__p8_0,
  146043. _vq_quantmap__8u1__p8_0,
  146044. 11,
  146045. 11
  146046. };
  146047. static static_codebook _8u1__p8_0 = {
  146048. 2, 121,
  146049. _vq_lengthlist__8u1__p8_0,
  146050. 1, -524582912, 1618345984, 4, 0,
  146051. _vq_quantlist__8u1__p8_0,
  146052. NULL,
  146053. &_vq_auxt__8u1__p8_0,
  146054. NULL,
  146055. 0
  146056. };
  146057. static long _vq_quantlist__8u1__p8_1[] = {
  146058. 5,
  146059. 4,
  146060. 6,
  146061. 3,
  146062. 7,
  146063. 2,
  146064. 8,
  146065. 1,
  146066. 9,
  146067. 0,
  146068. 10,
  146069. };
  146070. static long _vq_lengthlist__8u1__p8_1[] = {
  146071. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 6, 6, 7, 7,
  146072. 7, 7, 8, 8, 8, 8, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  146073. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  146074. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  146075. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  146076. 8, 8, 8, 8, 9, 8, 9, 9, 7, 8, 8, 8, 8, 8, 8, 9,
  146077. 8, 9, 9, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8,
  146078. 8, 8, 8, 8, 8, 9, 9, 9, 9,
  146079. };
  146080. static float _vq_quantthresh__8u1__p8_1[] = {
  146081. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  146082. 3.5, 4.5,
  146083. };
  146084. static long _vq_quantmap__8u1__p8_1[] = {
  146085. 9, 7, 5, 3, 1, 0, 2, 4,
  146086. 6, 8, 10,
  146087. };
  146088. static encode_aux_threshmatch _vq_auxt__8u1__p8_1 = {
  146089. _vq_quantthresh__8u1__p8_1,
  146090. _vq_quantmap__8u1__p8_1,
  146091. 11,
  146092. 11
  146093. };
  146094. static static_codebook _8u1__p8_1 = {
  146095. 2, 121,
  146096. _vq_lengthlist__8u1__p8_1,
  146097. 1, -531365888, 1611661312, 4, 0,
  146098. _vq_quantlist__8u1__p8_1,
  146099. NULL,
  146100. &_vq_auxt__8u1__p8_1,
  146101. NULL,
  146102. 0
  146103. };
  146104. static long _vq_quantlist__8u1__p9_0[] = {
  146105. 7,
  146106. 6,
  146107. 8,
  146108. 5,
  146109. 9,
  146110. 4,
  146111. 10,
  146112. 3,
  146113. 11,
  146114. 2,
  146115. 12,
  146116. 1,
  146117. 13,
  146118. 0,
  146119. 14,
  146120. };
  146121. static long _vq_lengthlist__8u1__p9_0[] = {
  146122. 1, 4, 4,11,11,11,11,11,11,11,11,11,11,11,11, 3,
  146123. 11, 8,11,11,11,11,11,11,11,11,11,11,11,11, 3, 9,
  146124. 9,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146125. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146126. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146127. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146128. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146129. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146130. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146131. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146132. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146133. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146134. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  146135. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146136. 10,
  146137. };
  146138. static float _vq_quantthresh__8u1__p9_0[] = {
  146139. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  146140. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  146141. };
  146142. static long _vq_quantmap__8u1__p9_0[] = {
  146143. 13, 11, 9, 7, 5, 3, 1, 0,
  146144. 2, 4, 6, 8, 10, 12, 14,
  146145. };
  146146. static encode_aux_threshmatch _vq_auxt__8u1__p9_0 = {
  146147. _vq_quantthresh__8u1__p9_0,
  146148. _vq_quantmap__8u1__p9_0,
  146149. 15,
  146150. 15
  146151. };
  146152. static static_codebook _8u1__p9_0 = {
  146153. 2, 225,
  146154. _vq_lengthlist__8u1__p9_0,
  146155. 1, -514071552, 1627381760, 4, 0,
  146156. _vq_quantlist__8u1__p9_0,
  146157. NULL,
  146158. &_vq_auxt__8u1__p9_0,
  146159. NULL,
  146160. 0
  146161. };
  146162. static long _vq_quantlist__8u1__p9_1[] = {
  146163. 7,
  146164. 6,
  146165. 8,
  146166. 5,
  146167. 9,
  146168. 4,
  146169. 10,
  146170. 3,
  146171. 11,
  146172. 2,
  146173. 12,
  146174. 1,
  146175. 13,
  146176. 0,
  146177. 14,
  146178. };
  146179. static long _vq_lengthlist__8u1__p9_1[] = {
  146180. 1, 4, 4, 7, 7, 9, 9, 7, 7, 8, 8,10,10,11,11, 4,
  146181. 7, 7, 9, 9,10,10, 8, 8,10,10,10,11,10,11, 4, 7,
  146182. 7, 9, 9,10,10, 8, 8,10, 9,11,11,11,11, 7, 9, 9,
  146183. 12,12,11,12,10,10,11,10,12,11,11,11, 7, 9, 9,11,
  146184. 11,13,12, 9, 9,11,10,11,11,12,11, 9,10,10,12,12,
  146185. 14,14,10,10,11,12,12,11,11,11, 9,10,11,11,13,14,
  146186. 13,10,11,11,11,12,11,12,12, 7, 8, 8,10, 9,11,10,
  146187. 11,12,12,11,12,14,12,13, 7, 8, 8, 9,10,10,11,12,
  146188. 12,12,11,12,12,12,13, 9, 9, 9,11,11,13,12,12,12,
  146189. 12,11,12,12,13,12, 8,10,10,11,10,11,12,12,12,12,
  146190. 12,12,14,12,12, 9,11,11,11,12,12,12,12,13,13,12,
  146191. 12,13,13,12,10,11,11,12,11,12,12,12,11,12,13,12,
  146192. 12,12,13,11,11,12,12,12,13,12,12,11,12,13,13,12,
  146193. 12,13,12,11,12,12,13,13,12,13,12,13,13,13,13,14,
  146194. 13,
  146195. };
  146196. static float _vq_quantthresh__8u1__p9_1[] = {
  146197. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  146198. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  146199. };
  146200. static long _vq_quantmap__8u1__p9_1[] = {
  146201. 13, 11, 9, 7, 5, 3, 1, 0,
  146202. 2, 4, 6, 8, 10, 12, 14,
  146203. };
  146204. static encode_aux_threshmatch _vq_auxt__8u1__p9_1 = {
  146205. _vq_quantthresh__8u1__p9_1,
  146206. _vq_quantmap__8u1__p9_1,
  146207. 15,
  146208. 15
  146209. };
  146210. static static_codebook _8u1__p9_1 = {
  146211. 2, 225,
  146212. _vq_lengthlist__8u1__p9_1,
  146213. 1, -522338304, 1620115456, 4, 0,
  146214. _vq_quantlist__8u1__p9_1,
  146215. NULL,
  146216. &_vq_auxt__8u1__p9_1,
  146217. NULL,
  146218. 0
  146219. };
  146220. static long _vq_quantlist__8u1__p9_2[] = {
  146221. 8,
  146222. 7,
  146223. 9,
  146224. 6,
  146225. 10,
  146226. 5,
  146227. 11,
  146228. 4,
  146229. 12,
  146230. 3,
  146231. 13,
  146232. 2,
  146233. 14,
  146234. 1,
  146235. 15,
  146236. 0,
  146237. 16,
  146238. };
  146239. static long _vq_lengthlist__8u1__p9_2[] = {
  146240. 2, 5, 4, 6, 6, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  146241. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  146242. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  146243. 9, 9, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  146244. 9,10,10, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  146245. 9, 9, 9,10,10, 8, 8, 8, 9, 9, 9, 9,10,10,10, 9,
  146246. 10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  146247. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,
  146248. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  146249. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  146250. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  146251. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  146252. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  146253. 9,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  146254. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10,
  146255. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  146256. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146257. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146258. 10,
  146259. };
  146260. static float _vq_quantthresh__8u1__p9_2[] = {
  146261. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  146262. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  146263. };
  146264. static long _vq_quantmap__8u1__p9_2[] = {
  146265. 15, 13, 11, 9, 7, 5, 3, 1,
  146266. 0, 2, 4, 6, 8, 10, 12, 14,
  146267. 16,
  146268. };
  146269. static encode_aux_threshmatch _vq_auxt__8u1__p9_2 = {
  146270. _vq_quantthresh__8u1__p9_2,
  146271. _vq_quantmap__8u1__p9_2,
  146272. 17,
  146273. 17
  146274. };
  146275. static static_codebook _8u1__p9_2 = {
  146276. 2, 289,
  146277. _vq_lengthlist__8u1__p9_2,
  146278. 1, -529530880, 1611661312, 5, 0,
  146279. _vq_quantlist__8u1__p9_2,
  146280. NULL,
  146281. &_vq_auxt__8u1__p9_2,
  146282. NULL,
  146283. 0
  146284. };
  146285. static long _huff_lengthlist__8u1__single[] = {
  146286. 4, 7,13, 9,15, 9,16, 8,10,13, 7, 5, 8, 6, 9, 7,
  146287. 10, 7,10,11,11, 6, 7, 8, 8, 9, 9, 9,12,16, 8, 5,
  146288. 8, 6, 8, 6, 9, 7,10,12,11, 7, 7, 7, 6, 7, 7, 7,
  146289. 11,15, 7, 5, 8, 6, 7, 5, 7, 6, 9,13,13, 9, 9, 8,
  146290. 6, 6, 5, 5, 9,14, 8, 6, 8, 6, 6, 4, 5, 3, 5,13,
  146291. 9, 9,11, 8,10, 7, 8, 4, 5,12,11,16,17,15,17,12,
  146292. 13, 8, 8,15,
  146293. };
  146294. static static_codebook _huff_book__8u1__single = {
  146295. 2, 100,
  146296. _huff_lengthlist__8u1__single,
  146297. 0, 0, 0, 0, 0,
  146298. NULL,
  146299. NULL,
  146300. NULL,
  146301. NULL,
  146302. 0
  146303. };
  146304. static long _huff_lengthlist__44u0__long[] = {
  146305. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  146306. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  146307. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  146308. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  146309. };
  146310. static static_codebook _huff_book__44u0__long = {
  146311. 2, 64,
  146312. _huff_lengthlist__44u0__long,
  146313. 0, 0, 0, 0, 0,
  146314. NULL,
  146315. NULL,
  146316. NULL,
  146317. NULL,
  146318. 0
  146319. };
  146320. static long _vq_quantlist__44u0__p1_0[] = {
  146321. 1,
  146322. 0,
  146323. 2,
  146324. };
  146325. static long _vq_lengthlist__44u0__p1_0[] = {
  146326. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  146327. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  146328. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  146329. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  146330. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  146331. 13,
  146332. };
  146333. static float _vq_quantthresh__44u0__p1_0[] = {
  146334. -0.5, 0.5,
  146335. };
  146336. static long _vq_quantmap__44u0__p1_0[] = {
  146337. 1, 0, 2,
  146338. };
  146339. static encode_aux_threshmatch _vq_auxt__44u0__p1_0 = {
  146340. _vq_quantthresh__44u0__p1_0,
  146341. _vq_quantmap__44u0__p1_0,
  146342. 3,
  146343. 3
  146344. };
  146345. static static_codebook _44u0__p1_0 = {
  146346. 4, 81,
  146347. _vq_lengthlist__44u0__p1_0,
  146348. 1, -535822336, 1611661312, 2, 0,
  146349. _vq_quantlist__44u0__p1_0,
  146350. NULL,
  146351. &_vq_auxt__44u0__p1_0,
  146352. NULL,
  146353. 0
  146354. };
  146355. static long _vq_quantlist__44u0__p2_0[] = {
  146356. 1,
  146357. 0,
  146358. 2,
  146359. };
  146360. static long _vq_lengthlist__44u0__p2_0[] = {
  146361. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  146362. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  146363. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  146364. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  146365. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  146366. 9,
  146367. };
  146368. static float _vq_quantthresh__44u0__p2_0[] = {
  146369. -0.5, 0.5,
  146370. };
  146371. static long _vq_quantmap__44u0__p2_0[] = {
  146372. 1, 0, 2,
  146373. };
  146374. static encode_aux_threshmatch _vq_auxt__44u0__p2_0 = {
  146375. _vq_quantthresh__44u0__p2_0,
  146376. _vq_quantmap__44u0__p2_0,
  146377. 3,
  146378. 3
  146379. };
  146380. static static_codebook _44u0__p2_0 = {
  146381. 4, 81,
  146382. _vq_lengthlist__44u0__p2_0,
  146383. 1, -535822336, 1611661312, 2, 0,
  146384. _vq_quantlist__44u0__p2_0,
  146385. NULL,
  146386. &_vq_auxt__44u0__p2_0,
  146387. NULL,
  146388. 0
  146389. };
  146390. static long _vq_quantlist__44u0__p3_0[] = {
  146391. 2,
  146392. 1,
  146393. 3,
  146394. 0,
  146395. 4,
  146396. };
  146397. static long _vq_lengthlist__44u0__p3_0[] = {
  146398. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  146399. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  146400. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  146401. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  146402. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  146403. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  146404. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  146405. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  146406. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  146407. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  146408. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  146409. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  146410. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  146411. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  146412. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  146413. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  146414. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  146415. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  146416. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  146417. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  146418. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  146419. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  146420. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  146421. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  146422. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  146423. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  146424. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  146425. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  146426. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  146427. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  146428. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  146429. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  146430. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  146431. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  146432. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  146433. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  146434. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  146435. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  146436. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  146437. 19,
  146438. };
  146439. static float _vq_quantthresh__44u0__p3_0[] = {
  146440. -1.5, -0.5, 0.5, 1.5,
  146441. };
  146442. static long _vq_quantmap__44u0__p3_0[] = {
  146443. 3, 1, 0, 2, 4,
  146444. };
  146445. static encode_aux_threshmatch _vq_auxt__44u0__p3_0 = {
  146446. _vq_quantthresh__44u0__p3_0,
  146447. _vq_quantmap__44u0__p3_0,
  146448. 5,
  146449. 5
  146450. };
  146451. static static_codebook _44u0__p3_0 = {
  146452. 4, 625,
  146453. _vq_lengthlist__44u0__p3_0,
  146454. 1, -533725184, 1611661312, 3, 0,
  146455. _vq_quantlist__44u0__p3_0,
  146456. NULL,
  146457. &_vq_auxt__44u0__p3_0,
  146458. NULL,
  146459. 0
  146460. };
  146461. static long _vq_quantlist__44u0__p4_0[] = {
  146462. 2,
  146463. 1,
  146464. 3,
  146465. 0,
  146466. 4,
  146467. };
  146468. static long _vq_lengthlist__44u0__p4_0[] = {
  146469. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  146470. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  146471. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  146472. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  146473. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  146474. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  146475. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  146476. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  146477. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  146478. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  146479. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  146480. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  146481. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  146482. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  146483. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  146484. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  146485. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  146486. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  146487. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  146488. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  146489. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  146490. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  146491. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  146492. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  146493. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  146494. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  146495. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  146496. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  146497. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  146498. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  146499. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  146500. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  146501. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  146502. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  146503. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  146504. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  146505. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  146506. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  146507. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  146508. 12,
  146509. };
  146510. static float _vq_quantthresh__44u0__p4_0[] = {
  146511. -1.5, -0.5, 0.5, 1.5,
  146512. };
  146513. static long _vq_quantmap__44u0__p4_0[] = {
  146514. 3, 1, 0, 2, 4,
  146515. };
  146516. static encode_aux_threshmatch _vq_auxt__44u0__p4_0 = {
  146517. _vq_quantthresh__44u0__p4_0,
  146518. _vq_quantmap__44u0__p4_0,
  146519. 5,
  146520. 5
  146521. };
  146522. static static_codebook _44u0__p4_0 = {
  146523. 4, 625,
  146524. _vq_lengthlist__44u0__p4_0,
  146525. 1, -533725184, 1611661312, 3, 0,
  146526. _vq_quantlist__44u0__p4_0,
  146527. NULL,
  146528. &_vq_auxt__44u0__p4_0,
  146529. NULL,
  146530. 0
  146531. };
  146532. static long _vq_quantlist__44u0__p5_0[] = {
  146533. 4,
  146534. 3,
  146535. 5,
  146536. 2,
  146537. 6,
  146538. 1,
  146539. 7,
  146540. 0,
  146541. 8,
  146542. };
  146543. static long _vq_lengthlist__44u0__p5_0[] = {
  146544. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  146545. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  146546. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  146547. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  146548. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  146549. 12,
  146550. };
  146551. static float _vq_quantthresh__44u0__p5_0[] = {
  146552. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146553. };
  146554. static long _vq_quantmap__44u0__p5_0[] = {
  146555. 7, 5, 3, 1, 0, 2, 4, 6,
  146556. 8,
  146557. };
  146558. static encode_aux_threshmatch _vq_auxt__44u0__p5_0 = {
  146559. _vq_quantthresh__44u0__p5_0,
  146560. _vq_quantmap__44u0__p5_0,
  146561. 9,
  146562. 9
  146563. };
  146564. static static_codebook _44u0__p5_0 = {
  146565. 2, 81,
  146566. _vq_lengthlist__44u0__p5_0,
  146567. 1, -531628032, 1611661312, 4, 0,
  146568. _vq_quantlist__44u0__p5_0,
  146569. NULL,
  146570. &_vq_auxt__44u0__p5_0,
  146571. NULL,
  146572. 0
  146573. };
  146574. static long _vq_quantlist__44u0__p6_0[] = {
  146575. 6,
  146576. 5,
  146577. 7,
  146578. 4,
  146579. 8,
  146580. 3,
  146581. 9,
  146582. 2,
  146583. 10,
  146584. 1,
  146585. 11,
  146586. 0,
  146587. 12,
  146588. };
  146589. static long _vq_lengthlist__44u0__p6_0[] = {
  146590. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  146591. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  146592. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  146593. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  146594. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  146595. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  146596. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  146597. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  146598. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  146599. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  146600. 15,17,16,17,18,17,17,18, 0,
  146601. };
  146602. static float _vq_quantthresh__44u0__p6_0[] = {
  146603. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  146604. 12.5, 17.5, 22.5, 27.5,
  146605. };
  146606. static long _vq_quantmap__44u0__p6_0[] = {
  146607. 11, 9, 7, 5, 3, 1, 0, 2,
  146608. 4, 6, 8, 10, 12,
  146609. };
  146610. static encode_aux_threshmatch _vq_auxt__44u0__p6_0 = {
  146611. _vq_quantthresh__44u0__p6_0,
  146612. _vq_quantmap__44u0__p6_0,
  146613. 13,
  146614. 13
  146615. };
  146616. static static_codebook _44u0__p6_0 = {
  146617. 2, 169,
  146618. _vq_lengthlist__44u0__p6_0,
  146619. 1, -526516224, 1616117760, 4, 0,
  146620. _vq_quantlist__44u0__p6_0,
  146621. NULL,
  146622. &_vq_auxt__44u0__p6_0,
  146623. NULL,
  146624. 0
  146625. };
  146626. static long _vq_quantlist__44u0__p6_1[] = {
  146627. 2,
  146628. 1,
  146629. 3,
  146630. 0,
  146631. 4,
  146632. };
  146633. static long _vq_lengthlist__44u0__p6_1[] = {
  146634. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  146635. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  146636. };
  146637. static float _vq_quantthresh__44u0__p6_1[] = {
  146638. -1.5, -0.5, 0.5, 1.5,
  146639. };
  146640. static long _vq_quantmap__44u0__p6_1[] = {
  146641. 3, 1, 0, 2, 4,
  146642. };
  146643. static encode_aux_threshmatch _vq_auxt__44u0__p6_1 = {
  146644. _vq_quantthresh__44u0__p6_1,
  146645. _vq_quantmap__44u0__p6_1,
  146646. 5,
  146647. 5
  146648. };
  146649. static static_codebook _44u0__p6_1 = {
  146650. 2, 25,
  146651. _vq_lengthlist__44u0__p6_1,
  146652. 1, -533725184, 1611661312, 3, 0,
  146653. _vq_quantlist__44u0__p6_1,
  146654. NULL,
  146655. &_vq_auxt__44u0__p6_1,
  146656. NULL,
  146657. 0
  146658. };
  146659. static long _vq_quantlist__44u0__p7_0[] = {
  146660. 2,
  146661. 1,
  146662. 3,
  146663. 0,
  146664. 4,
  146665. };
  146666. static long _vq_lengthlist__44u0__p7_0[] = {
  146667. 1, 4, 4,11,11, 9,11,11,11,11,11,11,11,11,11,11,
  146668. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146669. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146670. 11,11, 9,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146671. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146672. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146673. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146674. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  146675. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146676. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146677. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146678. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146679. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146680. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146681. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146682. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146683. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146684. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146685. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146686. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146687. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146688. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146689. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146690. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146691. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146692. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146693. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146694. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146695. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146696. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146697. 11,11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,
  146698. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146699. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146700. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146701. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146702. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146703. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146704. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146705. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146706. 10,
  146707. };
  146708. static float _vq_quantthresh__44u0__p7_0[] = {
  146709. -253.5, -84.5, 84.5, 253.5,
  146710. };
  146711. static long _vq_quantmap__44u0__p7_0[] = {
  146712. 3, 1, 0, 2, 4,
  146713. };
  146714. static encode_aux_threshmatch _vq_auxt__44u0__p7_0 = {
  146715. _vq_quantthresh__44u0__p7_0,
  146716. _vq_quantmap__44u0__p7_0,
  146717. 5,
  146718. 5
  146719. };
  146720. static static_codebook _44u0__p7_0 = {
  146721. 4, 625,
  146722. _vq_lengthlist__44u0__p7_0,
  146723. 1, -518709248, 1626677248, 3, 0,
  146724. _vq_quantlist__44u0__p7_0,
  146725. NULL,
  146726. &_vq_auxt__44u0__p7_0,
  146727. NULL,
  146728. 0
  146729. };
  146730. static long _vq_quantlist__44u0__p7_1[] = {
  146731. 6,
  146732. 5,
  146733. 7,
  146734. 4,
  146735. 8,
  146736. 3,
  146737. 9,
  146738. 2,
  146739. 10,
  146740. 1,
  146741. 11,
  146742. 0,
  146743. 12,
  146744. };
  146745. static long _vq_lengthlist__44u0__p7_1[] = {
  146746. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  146747. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  146748. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  146749. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  146750. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  146751. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  146752. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  146753. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  146754. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  146755. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  146756. 15,15,15,15,15,15,15,15,15,
  146757. };
  146758. static float _vq_quantthresh__44u0__p7_1[] = {
  146759. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  146760. 32.5, 45.5, 58.5, 71.5,
  146761. };
  146762. static long _vq_quantmap__44u0__p7_1[] = {
  146763. 11, 9, 7, 5, 3, 1, 0, 2,
  146764. 4, 6, 8, 10, 12,
  146765. };
  146766. static encode_aux_threshmatch _vq_auxt__44u0__p7_1 = {
  146767. _vq_quantthresh__44u0__p7_1,
  146768. _vq_quantmap__44u0__p7_1,
  146769. 13,
  146770. 13
  146771. };
  146772. static static_codebook _44u0__p7_1 = {
  146773. 2, 169,
  146774. _vq_lengthlist__44u0__p7_1,
  146775. 1, -523010048, 1618608128, 4, 0,
  146776. _vq_quantlist__44u0__p7_1,
  146777. NULL,
  146778. &_vq_auxt__44u0__p7_1,
  146779. NULL,
  146780. 0
  146781. };
  146782. static long _vq_quantlist__44u0__p7_2[] = {
  146783. 6,
  146784. 5,
  146785. 7,
  146786. 4,
  146787. 8,
  146788. 3,
  146789. 9,
  146790. 2,
  146791. 10,
  146792. 1,
  146793. 11,
  146794. 0,
  146795. 12,
  146796. };
  146797. static long _vq_lengthlist__44u0__p7_2[] = {
  146798. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  146799. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  146800. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  146801. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  146802. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  146803. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  146804. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  146805. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146806. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146807. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  146808. 9, 9, 9,10, 9, 9,10,10, 9,
  146809. };
  146810. static float _vq_quantthresh__44u0__p7_2[] = {
  146811. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  146812. 2.5, 3.5, 4.5, 5.5,
  146813. };
  146814. static long _vq_quantmap__44u0__p7_2[] = {
  146815. 11, 9, 7, 5, 3, 1, 0, 2,
  146816. 4, 6, 8, 10, 12,
  146817. };
  146818. static encode_aux_threshmatch _vq_auxt__44u0__p7_2 = {
  146819. _vq_quantthresh__44u0__p7_2,
  146820. _vq_quantmap__44u0__p7_2,
  146821. 13,
  146822. 13
  146823. };
  146824. static static_codebook _44u0__p7_2 = {
  146825. 2, 169,
  146826. _vq_lengthlist__44u0__p7_2,
  146827. 1, -531103744, 1611661312, 4, 0,
  146828. _vq_quantlist__44u0__p7_2,
  146829. NULL,
  146830. &_vq_auxt__44u0__p7_2,
  146831. NULL,
  146832. 0
  146833. };
  146834. static long _huff_lengthlist__44u0__short[] = {
  146835. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  146836. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  146837. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  146838. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  146839. };
  146840. static static_codebook _huff_book__44u0__short = {
  146841. 2, 64,
  146842. _huff_lengthlist__44u0__short,
  146843. 0, 0, 0, 0, 0,
  146844. NULL,
  146845. NULL,
  146846. NULL,
  146847. NULL,
  146848. 0
  146849. };
  146850. static long _huff_lengthlist__44u1__long[] = {
  146851. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  146852. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  146853. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  146854. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  146855. };
  146856. static static_codebook _huff_book__44u1__long = {
  146857. 2, 64,
  146858. _huff_lengthlist__44u1__long,
  146859. 0, 0, 0, 0, 0,
  146860. NULL,
  146861. NULL,
  146862. NULL,
  146863. NULL,
  146864. 0
  146865. };
  146866. static long _vq_quantlist__44u1__p1_0[] = {
  146867. 1,
  146868. 0,
  146869. 2,
  146870. };
  146871. static long _vq_lengthlist__44u1__p1_0[] = {
  146872. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  146873. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  146874. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  146875. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  146876. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  146877. 13,
  146878. };
  146879. static float _vq_quantthresh__44u1__p1_0[] = {
  146880. -0.5, 0.5,
  146881. };
  146882. static long _vq_quantmap__44u1__p1_0[] = {
  146883. 1, 0, 2,
  146884. };
  146885. static encode_aux_threshmatch _vq_auxt__44u1__p1_0 = {
  146886. _vq_quantthresh__44u1__p1_0,
  146887. _vq_quantmap__44u1__p1_0,
  146888. 3,
  146889. 3
  146890. };
  146891. static static_codebook _44u1__p1_0 = {
  146892. 4, 81,
  146893. _vq_lengthlist__44u1__p1_0,
  146894. 1, -535822336, 1611661312, 2, 0,
  146895. _vq_quantlist__44u1__p1_0,
  146896. NULL,
  146897. &_vq_auxt__44u1__p1_0,
  146898. NULL,
  146899. 0
  146900. };
  146901. static long _vq_quantlist__44u1__p2_0[] = {
  146902. 1,
  146903. 0,
  146904. 2,
  146905. };
  146906. static long _vq_lengthlist__44u1__p2_0[] = {
  146907. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  146908. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  146909. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  146910. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  146911. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  146912. 9,
  146913. };
  146914. static float _vq_quantthresh__44u1__p2_0[] = {
  146915. -0.5, 0.5,
  146916. };
  146917. static long _vq_quantmap__44u1__p2_0[] = {
  146918. 1, 0, 2,
  146919. };
  146920. static encode_aux_threshmatch _vq_auxt__44u1__p2_0 = {
  146921. _vq_quantthresh__44u1__p2_0,
  146922. _vq_quantmap__44u1__p2_0,
  146923. 3,
  146924. 3
  146925. };
  146926. static static_codebook _44u1__p2_0 = {
  146927. 4, 81,
  146928. _vq_lengthlist__44u1__p2_0,
  146929. 1, -535822336, 1611661312, 2, 0,
  146930. _vq_quantlist__44u1__p2_0,
  146931. NULL,
  146932. &_vq_auxt__44u1__p2_0,
  146933. NULL,
  146934. 0
  146935. };
  146936. static long _vq_quantlist__44u1__p3_0[] = {
  146937. 2,
  146938. 1,
  146939. 3,
  146940. 0,
  146941. 4,
  146942. };
  146943. static long _vq_lengthlist__44u1__p3_0[] = {
  146944. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  146945. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  146946. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  146947. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  146948. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  146949. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  146950. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  146951. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  146952. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  146953. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  146954. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  146955. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  146956. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  146957. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  146958. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  146959. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  146960. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  146961. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  146962. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  146963. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  146964. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  146965. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  146966. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  146967. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  146968. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  146969. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  146970. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  146971. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  146972. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  146973. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  146974. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  146975. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  146976. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  146977. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  146978. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  146979. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  146980. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  146981. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  146982. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  146983. 19,
  146984. };
  146985. static float _vq_quantthresh__44u1__p3_0[] = {
  146986. -1.5, -0.5, 0.5, 1.5,
  146987. };
  146988. static long _vq_quantmap__44u1__p3_0[] = {
  146989. 3, 1, 0, 2, 4,
  146990. };
  146991. static encode_aux_threshmatch _vq_auxt__44u1__p3_0 = {
  146992. _vq_quantthresh__44u1__p3_0,
  146993. _vq_quantmap__44u1__p3_0,
  146994. 5,
  146995. 5
  146996. };
  146997. static static_codebook _44u1__p3_0 = {
  146998. 4, 625,
  146999. _vq_lengthlist__44u1__p3_0,
  147000. 1, -533725184, 1611661312, 3, 0,
  147001. _vq_quantlist__44u1__p3_0,
  147002. NULL,
  147003. &_vq_auxt__44u1__p3_0,
  147004. NULL,
  147005. 0
  147006. };
  147007. static long _vq_quantlist__44u1__p4_0[] = {
  147008. 2,
  147009. 1,
  147010. 3,
  147011. 0,
  147012. 4,
  147013. };
  147014. static long _vq_lengthlist__44u1__p4_0[] = {
  147015. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  147016. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  147017. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  147018. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  147019. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  147020. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  147021. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  147022. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  147023. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  147024. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  147025. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  147026. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  147027. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  147028. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  147029. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  147030. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  147031. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  147032. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  147033. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  147034. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  147035. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  147036. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  147037. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  147038. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  147039. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  147040. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  147041. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  147042. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  147043. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  147044. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  147045. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  147046. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  147047. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  147048. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  147049. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  147050. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  147051. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  147052. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  147053. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  147054. 12,
  147055. };
  147056. static float _vq_quantthresh__44u1__p4_0[] = {
  147057. -1.5, -0.5, 0.5, 1.5,
  147058. };
  147059. static long _vq_quantmap__44u1__p4_0[] = {
  147060. 3, 1, 0, 2, 4,
  147061. };
  147062. static encode_aux_threshmatch _vq_auxt__44u1__p4_0 = {
  147063. _vq_quantthresh__44u1__p4_0,
  147064. _vq_quantmap__44u1__p4_0,
  147065. 5,
  147066. 5
  147067. };
  147068. static static_codebook _44u1__p4_0 = {
  147069. 4, 625,
  147070. _vq_lengthlist__44u1__p4_0,
  147071. 1, -533725184, 1611661312, 3, 0,
  147072. _vq_quantlist__44u1__p4_0,
  147073. NULL,
  147074. &_vq_auxt__44u1__p4_0,
  147075. NULL,
  147076. 0
  147077. };
  147078. static long _vq_quantlist__44u1__p5_0[] = {
  147079. 4,
  147080. 3,
  147081. 5,
  147082. 2,
  147083. 6,
  147084. 1,
  147085. 7,
  147086. 0,
  147087. 8,
  147088. };
  147089. static long _vq_lengthlist__44u1__p5_0[] = {
  147090. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  147091. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  147092. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  147093. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  147094. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  147095. 12,
  147096. };
  147097. static float _vq_quantthresh__44u1__p5_0[] = {
  147098. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147099. };
  147100. static long _vq_quantmap__44u1__p5_0[] = {
  147101. 7, 5, 3, 1, 0, 2, 4, 6,
  147102. 8,
  147103. };
  147104. static encode_aux_threshmatch _vq_auxt__44u1__p5_0 = {
  147105. _vq_quantthresh__44u1__p5_0,
  147106. _vq_quantmap__44u1__p5_0,
  147107. 9,
  147108. 9
  147109. };
  147110. static static_codebook _44u1__p5_0 = {
  147111. 2, 81,
  147112. _vq_lengthlist__44u1__p5_0,
  147113. 1, -531628032, 1611661312, 4, 0,
  147114. _vq_quantlist__44u1__p5_0,
  147115. NULL,
  147116. &_vq_auxt__44u1__p5_0,
  147117. NULL,
  147118. 0
  147119. };
  147120. static long _vq_quantlist__44u1__p6_0[] = {
  147121. 6,
  147122. 5,
  147123. 7,
  147124. 4,
  147125. 8,
  147126. 3,
  147127. 9,
  147128. 2,
  147129. 10,
  147130. 1,
  147131. 11,
  147132. 0,
  147133. 12,
  147134. };
  147135. static long _vq_lengthlist__44u1__p6_0[] = {
  147136. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  147137. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  147138. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  147139. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  147140. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  147141. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  147142. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  147143. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  147144. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  147145. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  147146. 15,17,16,17,18,17,17,18, 0,
  147147. };
  147148. static float _vq_quantthresh__44u1__p6_0[] = {
  147149. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147150. 12.5, 17.5, 22.5, 27.5,
  147151. };
  147152. static long _vq_quantmap__44u1__p6_0[] = {
  147153. 11, 9, 7, 5, 3, 1, 0, 2,
  147154. 4, 6, 8, 10, 12,
  147155. };
  147156. static encode_aux_threshmatch _vq_auxt__44u1__p6_0 = {
  147157. _vq_quantthresh__44u1__p6_0,
  147158. _vq_quantmap__44u1__p6_0,
  147159. 13,
  147160. 13
  147161. };
  147162. static static_codebook _44u1__p6_0 = {
  147163. 2, 169,
  147164. _vq_lengthlist__44u1__p6_0,
  147165. 1, -526516224, 1616117760, 4, 0,
  147166. _vq_quantlist__44u1__p6_0,
  147167. NULL,
  147168. &_vq_auxt__44u1__p6_0,
  147169. NULL,
  147170. 0
  147171. };
  147172. static long _vq_quantlist__44u1__p6_1[] = {
  147173. 2,
  147174. 1,
  147175. 3,
  147176. 0,
  147177. 4,
  147178. };
  147179. static long _vq_lengthlist__44u1__p6_1[] = {
  147180. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  147181. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  147182. };
  147183. static float _vq_quantthresh__44u1__p6_1[] = {
  147184. -1.5, -0.5, 0.5, 1.5,
  147185. };
  147186. static long _vq_quantmap__44u1__p6_1[] = {
  147187. 3, 1, 0, 2, 4,
  147188. };
  147189. static encode_aux_threshmatch _vq_auxt__44u1__p6_1 = {
  147190. _vq_quantthresh__44u1__p6_1,
  147191. _vq_quantmap__44u1__p6_1,
  147192. 5,
  147193. 5
  147194. };
  147195. static static_codebook _44u1__p6_1 = {
  147196. 2, 25,
  147197. _vq_lengthlist__44u1__p6_1,
  147198. 1, -533725184, 1611661312, 3, 0,
  147199. _vq_quantlist__44u1__p6_1,
  147200. NULL,
  147201. &_vq_auxt__44u1__p6_1,
  147202. NULL,
  147203. 0
  147204. };
  147205. static long _vq_quantlist__44u1__p7_0[] = {
  147206. 3,
  147207. 2,
  147208. 4,
  147209. 1,
  147210. 5,
  147211. 0,
  147212. 6,
  147213. };
  147214. static long _vq_lengthlist__44u1__p7_0[] = {
  147215. 1, 3, 2, 9, 9, 7, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147216. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147217. 9, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  147218. 8,
  147219. };
  147220. static float _vq_quantthresh__44u1__p7_0[] = {
  147221. -422.5, -253.5, -84.5, 84.5, 253.5, 422.5,
  147222. };
  147223. static long _vq_quantmap__44u1__p7_0[] = {
  147224. 5, 3, 1, 0, 2, 4, 6,
  147225. };
  147226. static encode_aux_threshmatch _vq_auxt__44u1__p7_0 = {
  147227. _vq_quantthresh__44u1__p7_0,
  147228. _vq_quantmap__44u1__p7_0,
  147229. 7,
  147230. 7
  147231. };
  147232. static static_codebook _44u1__p7_0 = {
  147233. 2, 49,
  147234. _vq_lengthlist__44u1__p7_0,
  147235. 1, -518017024, 1626677248, 3, 0,
  147236. _vq_quantlist__44u1__p7_0,
  147237. NULL,
  147238. &_vq_auxt__44u1__p7_0,
  147239. NULL,
  147240. 0
  147241. };
  147242. static long _vq_quantlist__44u1__p7_1[] = {
  147243. 6,
  147244. 5,
  147245. 7,
  147246. 4,
  147247. 8,
  147248. 3,
  147249. 9,
  147250. 2,
  147251. 10,
  147252. 1,
  147253. 11,
  147254. 0,
  147255. 12,
  147256. };
  147257. static long _vq_lengthlist__44u1__p7_1[] = {
  147258. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  147259. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  147260. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  147261. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  147262. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  147263. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  147264. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  147265. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  147266. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  147267. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  147268. 15,15,15,15,15,15,15,15,15,
  147269. };
  147270. static float _vq_quantthresh__44u1__p7_1[] = {
  147271. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  147272. 32.5, 45.5, 58.5, 71.5,
  147273. };
  147274. static long _vq_quantmap__44u1__p7_1[] = {
  147275. 11, 9, 7, 5, 3, 1, 0, 2,
  147276. 4, 6, 8, 10, 12,
  147277. };
  147278. static encode_aux_threshmatch _vq_auxt__44u1__p7_1 = {
  147279. _vq_quantthresh__44u1__p7_1,
  147280. _vq_quantmap__44u1__p7_1,
  147281. 13,
  147282. 13
  147283. };
  147284. static static_codebook _44u1__p7_1 = {
  147285. 2, 169,
  147286. _vq_lengthlist__44u1__p7_1,
  147287. 1, -523010048, 1618608128, 4, 0,
  147288. _vq_quantlist__44u1__p7_1,
  147289. NULL,
  147290. &_vq_auxt__44u1__p7_1,
  147291. NULL,
  147292. 0
  147293. };
  147294. static long _vq_quantlist__44u1__p7_2[] = {
  147295. 6,
  147296. 5,
  147297. 7,
  147298. 4,
  147299. 8,
  147300. 3,
  147301. 9,
  147302. 2,
  147303. 10,
  147304. 1,
  147305. 11,
  147306. 0,
  147307. 12,
  147308. };
  147309. static long _vq_lengthlist__44u1__p7_2[] = {
  147310. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  147311. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  147312. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  147313. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  147314. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  147315. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  147316. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  147317. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147318. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147319. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  147320. 9, 9, 9,10, 9, 9,10,10, 9,
  147321. };
  147322. static float _vq_quantthresh__44u1__p7_2[] = {
  147323. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  147324. 2.5, 3.5, 4.5, 5.5,
  147325. };
  147326. static long _vq_quantmap__44u1__p7_2[] = {
  147327. 11, 9, 7, 5, 3, 1, 0, 2,
  147328. 4, 6, 8, 10, 12,
  147329. };
  147330. static encode_aux_threshmatch _vq_auxt__44u1__p7_2 = {
  147331. _vq_quantthresh__44u1__p7_2,
  147332. _vq_quantmap__44u1__p7_2,
  147333. 13,
  147334. 13
  147335. };
  147336. static static_codebook _44u1__p7_2 = {
  147337. 2, 169,
  147338. _vq_lengthlist__44u1__p7_2,
  147339. 1, -531103744, 1611661312, 4, 0,
  147340. _vq_quantlist__44u1__p7_2,
  147341. NULL,
  147342. &_vq_auxt__44u1__p7_2,
  147343. NULL,
  147344. 0
  147345. };
  147346. static long _huff_lengthlist__44u1__short[] = {
  147347. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  147348. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  147349. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  147350. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  147351. };
  147352. static static_codebook _huff_book__44u1__short = {
  147353. 2, 64,
  147354. _huff_lengthlist__44u1__short,
  147355. 0, 0, 0, 0, 0,
  147356. NULL,
  147357. NULL,
  147358. NULL,
  147359. NULL,
  147360. 0
  147361. };
  147362. static long _huff_lengthlist__44u2__long[] = {
  147363. 5, 9,14,12,15,13,10,13, 7, 4, 5, 6, 8, 7, 8,12,
  147364. 13, 4, 3, 5, 5, 6, 9,15,12, 6, 5, 6, 6, 6, 7,14,
  147365. 14, 7, 4, 6, 4, 6, 8,15,12, 6, 6, 5, 5, 5, 6,14,
  147366. 9, 7, 8, 6, 7, 5, 4,10,10,13,14,14,15,10, 6, 8,
  147367. };
  147368. static static_codebook _huff_book__44u2__long = {
  147369. 2, 64,
  147370. _huff_lengthlist__44u2__long,
  147371. 0, 0, 0, 0, 0,
  147372. NULL,
  147373. NULL,
  147374. NULL,
  147375. NULL,
  147376. 0
  147377. };
  147378. static long _vq_quantlist__44u2__p1_0[] = {
  147379. 1,
  147380. 0,
  147381. 2,
  147382. };
  147383. static long _vq_lengthlist__44u2__p1_0[] = {
  147384. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  147385. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  147386. 11, 8,11,11, 8,11,11,11,13,14,11,13,13, 7,11,11,
  147387. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 8,
  147388. 11,11,11,14,13,10,12,13, 8,11,11,11,13,13,11,13,
  147389. 13,
  147390. };
  147391. static float _vq_quantthresh__44u2__p1_0[] = {
  147392. -0.5, 0.5,
  147393. };
  147394. static long _vq_quantmap__44u2__p1_0[] = {
  147395. 1, 0, 2,
  147396. };
  147397. static encode_aux_threshmatch _vq_auxt__44u2__p1_0 = {
  147398. _vq_quantthresh__44u2__p1_0,
  147399. _vq_quantmap__44u2__p1_0,
  147400. 3,
  147401. 3
  147402. };
  147403. static static_codebook _44u2__p1_0 = {
  147404. 4, 81,
  147405. _vq_lengthlist__44u2__p1_0,
  147406. 1, -535822336, 1611661312, 2, 0,
  147407. _vq_quantlist__44u2__p1_0,
  147408. NULL,
  147409. &_vq_auxt__44u2__p1_0,
  147410. NULL,
  147411. 0
  147412. };
  147413. static long _vq_quantlist__44u2__p2_0[] = {
  147414. 1,
  147415. 0,
  147416. 2,
  147417. };
  147418. static long _vq_lengthlist__44u2__p2_0[] = {
  147419. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  147420. 8, 8, 5, 6, 6, 6, 8, 7, 7, 8, 8, 5, 6, 6, 7, 8,
  147421. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  147422. 7,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  147423. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  147424. 9,
  147425. };
  147426. static float _vq_quantthresh__44u2__p2_0[] = {
  147427. -0.5, 0.5,
  147428. };
  147429. static long _vq_quantmap__44u2__p2_0[] = {
  147430. 1, 0, 2,
  147431. };
  147432. static encode_aux_threshmatch _vq_auxt__44u2__p2_0 = {
  147433. _vq_quantthresh__44u2__p2_0,
  147434. _vq_quantmap__44u2__p2_0,
  147435. 3,
  147436. 3
  147437. };
  147438. static static_codebook _44u2__p2_0 = {
  147439. 4, 81,
  147440. _vq_lengthlist__44u2__p2_0,
  147441. 1, -535822336, 1611661312, 2, 0,
  147442. _vq_quantlist__44u2__p2_0,
  147443. NULL,
  147444. &_vq_auxt__44u2__p2_0,
  147445. NULL,
  147446. 0
  147447. };
  147448. static long _vq_quantlist__44u2__p3_0[] = {
  147449. 2,
  147450. 1,
  147451. 3,
  147452. 0,
  147453. 4,
  147454. };
  147455. static long _vq_lengthlist__44u2__p3_0[] = {
  147456. 2, 4, 4, 7, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  147457. 9, 9,12,11, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  147458. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  147459. 12,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  147460. 11, 9,11,10,13,13,10,11,11,13,13, 8,10,10,14,13,
  147461. 10,11,11,15,14, 9,11,11,15,14,13,14,13,16,14,12,
  147462. 13,13,15,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  147463. 11,14,15,12,13,13,15,15,12,13,14,15,16, 5, 7, 7,
  147464. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  147465. 13,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  147466. 9,11,11,13,13,12,13,12,14,14,11,12,13,15,15, 7,
  147467. 9, 9,12,12, 8,11,10,13,12, 9,11,11,13,13,11,13,
  147468. 12,15,13,11,13,13,15,16, 9,12,11,15,15,11,12,12,
  147469. 16,15,11,12,13,16,16,13,14,15,16,15,13,15,15,17,
  147470. 17, 9,11,11,14,15,10,12,12,15,15,11,13,12,15,16,
  147471. 13,15,14,16,16,13,15,15,17,19, 5, 7, 7,10,10, 7,
  147472. 9, 9,12,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  147473. 11,13,14, 7, 9, 9,12,12, 9,11,11,13,13, 9,10,11,
  147474. 12,13,11,13,12,16,15,11,12,12,14,15, 7, 9, 9,12,
  147475. 12, 9,11,11,13,13, 9,11,11,13,12,11,13,12,15,16,
  147476. 12,13,13,15,14, 9,11,11,15,14,11,13,12,16,15,10,
  147477. 11,12,15,15,13,14,14,18,17,13,14,14,15,17,10,11,
  147478. 11,14,15,11,13,12,15,17,11,13,12,15,16,13,15,14,
  147479. 18,17,14,15,15,16,18, 7,10,10,14,14,10,12,12,15,
  147480. 15,10,12,12,15,15,14,15,15,18,17,13,15,15,16,16,
  147481. 9,11,11,16,15,11,13,13,16,18,11,13,13,16,16,15,
  147482. 16,16, 0, 0,14,15,16,18,17, 9,11,11,15,15,10,13,
  147483. 12,17,16,11,12,13,16,17,14,15,16,19,19,14,15,15,
  147484. 0,20,12,14,14, 0, 0,13,14,16,19,18,13,15,16,20,
  147485. 17,16,18, 0, 0, 0,15,16,17,18,19,11,14,14, 0,19,
  147486. 12,15,14,17,17,13,15,15, 0, 0,16,17,15,20,19,15,
  147487. 17,16,19, 0, 8,10,10,14,15,10,12,11,15,15,10,11,
  147488. 12,16,15,13,14,14,19,17,14,15,15, 0, 0, 9,11,11,
  147489. 16,15,11,13,13,17,16,10,12,13,16,17,14,15,15,18,
  147490. 18,14,15,16,20,19, 9,12,12, 0,15,11,13,13,16,17,
  147491. 11,13,13,19,17,14,16,16,18,17,15,16,16,17,19,11,
  147492. 14,14,18,18,13,14,15, 0, 0,12,14,15,19,18,15,16,
  147493. 19, 0,19,15,16,19,19,17,12,14,14,16,19,13,15,15,
  147494. 0,17,13,15,14,18,18,15,16,15, 0,18,16,17,17, 0,
  147495. 0,
  147496. };
  147497. static float _vq_quantthresh__44u2__p3_0[] = {
  147498. -1.5, -0.5, 0.5, 1.5,
  147499. };
  147500. static long _vq_quantmap__44u2__p3_0[] = {
  147501. 3, 1, 0, 2, 4,
  147502. };
  147503. static encode_aux_threshmatch _vq_auxt__44u2__p3_0 = {
  147504. _vq_quantthresh__44u2__p3_0,
  147505. _vq_quantmap__44u2__p3_0,
  147506. 5,
  147507. 5
  147508. };
  147509. static static_codebook _44u2__p3_0 = {
  147510. 4, 625,
  147511. _vq_lengthlist__44u2__p3_0,
  147512. 1, -533725184, 1611661312, 3, 0,
  147513. _vq_quantlist__44u2__p3_0,
  147514. NULL,
  147515. &_vq_auxt__44u2__p3_0,
  147516. NULL,
  147517. 0
  147518. };
  147519. static long _vq_quantlist__44u2__p4_0[] = {
  147520. 2,
  147521. 1,
  147522. 3,
  147523. 0,
  147524. 4,
  147525. };
  147526. static long _vq_lengthlist__44u2__p4_0[] = {
  147527. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  147528. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  147529. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  147530. 11,12, 5, 7, 7, 9, 9, 6, 8, 7,10,10, 7, 8, 8,10,
  147531. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10,10,12,12,
  147532. 10,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  147533. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,13,10,10,
  147534. 10,12,13,11,12,12,14,13,12,12,12,14,13, 5, 7, 7,
  147535. 10, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  147536. 12,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  147537. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,13,13, 6,
  147538. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  147539. 10,13,11,10,11,11,13,13, 9,10,10,13,13,10,11,11,
  147540. 13,13,10,11,11,14,13,12,11,13,12,15,12,13,13,15,
  147541. 15, 9,10,10,12,13,10,11,10,13,13,10,11,11,13,13,
  147542. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9,10, 7,
  147543. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  147544. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  147545. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  147546. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  147547. 10,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  147548. 10,11,13,13,12,13,13,15,15,12,11,13,12,14, 9,10,
  147549. 10,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  147550. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  147551. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  147552. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,12,13,
  147553. 13,14,14,16,12,13,13,15,14, 9,10,10,13,13,10,11,
  147554. 10,14,13,10,11,11,13,14,12,14,13,16,14,13,13,13,
  147555. 14,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  147556. 15,14,12,15,12,16,14,15,15,17,16,11,12,12,14,15,
  147557. 11,13,11,15,14,12,13,13,15,16,13,15,12,17,13,14,
  147558. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,13,13, 9,10,
  147559. 10,13,13,12,13,12,14,14,12,13,13,15,15, 9,10,10,
  147560. 13,13,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  147561. 14,12,12,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  147562. 10,11,11,14,13,13,13,13,15,15,13,14,13,16,14,11,
  147563. 12,12,14,14,12,13,13,16,15,11,12,13,14,15,14,15,
  147564. 15,16,16,14,13,15,13,17,11,12,12,14,15,12,13,13,
  147565. 15,16,11,13,12,15,15,14,15,14,16,16,14,15,12,17,
  147566. 13,
  147567. };
  147568. static float _vq_quantthresh__44u2__p4_0[] = {
  147569. -1.5, -0.5, 0.5, 1.5,
  147570. };
  147571. static long _vq_quantmap__44u2__p4_0[] = {
  147572. 3, 1, 0, 2, 4,
  147573. };
  147574. static encode_aux_threshmatch _vq_auxt__44u2__p4_0 = {
  147575. _vq_quantthresh__44u2__p4_0,
  147576. _vq_quantmap__44u2__p4_0,
  147577. 5,
  147578. 5
  147579. };
  147580. static static_codebook _44u2__p4_0 = {
  147581. 4, 625,
  147582. _vq_lengthlist__44u2__p4_0,
  147583. 1, -533725184, 1611661312, 3, 0,
  147584. _vq_quantlist__44u2__p4_0,
  147585. NULL,
  147586. &_vq_auxt__44u2__p4_0,
  147587. NULL,
  147588. 0
  147589. };
  147590. static long _vq_quantlist__44u2__p5_0[] = {
  147591. 4,
  147592. 3,
  147593. 5,
  147594. 2,
  147595. 6,
  147596. 1,
  147597. 7,
  147598. 0,
  147599. 8,
  147600. };
  147601. static long _vq_lengthlist__44u2__p5_0[] = {
  147602. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 8, 8, 8,
  147603. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  147604. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  147605. 9, 9,10,11,12,12, 8, 8, 8, 9, 9,10,10,12,12,10,
  147606. 10,10,11,11,12,12,13,13,10,10,10,11,11,12,12,13,
  147607. 13,
  147608. };
  147609. static float _vq_quantthresh__44u2__p5_0[] = {
  147610. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147611. };
  147612. static long _vq_quantmap__44u2__p5_0[] = {
  147613. 7, 5, 3, 1, 0, 2, 4, 6,
  147614. 8,
  147615. };
  147616. static encode_aux_threshmatch _vq_auxt__44u2__p5_0 = {
  147617. _vq_quantthresh__44u2__p5_0,
  147618. _vq_quantmap__44u2__p5_0,
  147619. 9,
  147620. 9
  147621. };
  147622. static static_codebook _44u2__p5_0 = {
  147623. 2, 81,
  147624. _vq_lengthlist__44u2__p5_0,
  147625. 1, -531628032, 1611661312, 4, 0,
  147626. _vq_quantlist__44u2__p5_0,
  147627. NULL,
  147628. &_vq_auxt__44u2__p5_0,
  147629. NULL,
  147630. 0
  147631. };
  147632. static long _vq_quantlist__44u2__p6_0[] = {
  147633. 6,
  147634. 5,
  147635. 7,
  147636. 4,
  147637. 8,
  147638. 3,
  147639. 9,
  147640. 2,
  147641. 10,
  147642. 1,
  147643. 11,
  147644. 0,
  147645. 12,
  147646. };
  147647. static long _vq_lengthlist__44u2__p6_0[] = {
  147648. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,14,13, 4, 6, 5,
  147649. 8, 8, 9, 9,11,10,12,11,15,14, 4, 5, 6, 8, 8, 9,
  147650. 9,11,11,11,11,14,14, 6, 8, 8,10, 9,11,11,11,11,
  147651. 12,12,15,15, 6, 8, 8, 9, 9,11,11,11,12,12,12,15,
  147652. 15, 8,10,10,11,11,11,11,12,12,13,13,15,16, 8,10,
  147653. 10,11,11,11,11,12,12,13,13,16,16,10,11,11,12,12,
  147654. 12,12,13,13,13,13,17,16,10,11,11,12,12,12,12,13,
  147655. 13,13,14,16,17,11,12,12,13,13,13,13,14,14,15,14,
  147656. 18,17,11,12,12,13,13,13,13,14,14,14,15,19,18,14,
  147657. 15,15,15,15,16,16,18,19,18,18, 0, 0,14,15,15,16,
  147658. 15,17,17,16,18,17,18, 0, 0,
  147659. };
  147660. static float _vq_quantthresh__44u2__p6_0[] = {
  147661. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147662. 12.5, 17.5, 22.5, 27.5,
  147663. };
  147664. static long _vq_quantmap__44u2__p6_0[] = {
  147665. 11, 9, 7, 5, 3, 1, 0, 2,
  147666. 4, 6, 8, 10, 12,
  147667. };
  147668. static encode_aux_threshmatch _vq_auxt__44u2__p6_0 = {
  147669. _vq_quantthresh__44u2__p6_0,
  147670. _vq_quantmap__44u2__p6_0,
  147671. 13,
  147672. 13
  147673. };
  147674. static static_codebook _44u2__p6_0 = {
  147675. 2, 169,
  147676. _vq_lengthlist__44u2__p6_0,
  147677. 1, -526516224, 1616117760, 4, 0,
  147678. _vq_quantlist__44u2__p6_0,
  147679. NULL,
  147680. &_vq_auxt__44u2__p6_0,
  147681. NULL,
  147682. 0
  147683. };
  147684. static long _vq_quantlist__44u2__p6_1[] = {
  147685. 2,
  147686. 1,
  147687. 3,
  147688. 0,
  147689. 4,
  147690. };
  147691. static long _vq_lengthlist__44u2__p6_1[] = {
  147692. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  147693. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  147694. };
  147695. static float _vq_quantthresh__44u2__p6_1[] = {
  147696. -1.5, -0.5, 0.5, 1.5,
  147697. };
  147698. static long _vq_quantmap__44u2__p6_1[] = {
  147699. 3, 1, 0, 2, 4,
  147700. };
  147701. static encode_aux_threshmatch _vq_auxt__44u2__p6_1 = {
  147702. _vq_quantthresh__44u2__p6_1,
  147703. _vq_quantmap__44u2__p6_1,
  147704. 5,
  147705. 5
  147706. };
  147707. static static_codebook _44u2__p6_1 = {
  147708. 2, 25,
  147709. _vq_lengthlist__44u2__p6_1,
  147710. 1, -533725184, 1611661312, 3, 0,
  147711. _vq_quantlist__44u2__p6_1,
  147712. NULL,
  147713. &_vq_auxt__44u2__p6_1,
  147714. NULL,
  147715. 0
  147716. };
  147717. static long _vq_quantlist__44u2__p7_0[] = {
  147718. 4,
  147719. 3,
  147720. 5,
  147721. 2,
  147722. 6,
  147723. 1,
  147724. 7,
  147725. 0,
  147726. 8,
  147727. };
  147728. static long _vq_lengthlist__44u2__p7_0[] = {
  147729. 1, 3, 2,12,12,12,12,12,12, 4,12,12,12,12,12,12,
  147730. 12,12, 5,12,12,12,12,12,12,12,12,12,12,11,11,11,
  147731. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147732. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147733. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147734. 11,
  147735. };
  147736. static float _vq_quantthresh__44u2__p7_0[] = {
  147737. -591.5, -422.5, -253.5, -84.5, 84.5, 253.5, 422.5, 591.5,
  147738. };
  147739. static long _vq_quantmap__44u2__p7_0[] = {
  147740. 7, 5, 3, 1, 0, 2, 4, 6,
  147741. 8,
  147742. };
  147743. static encode_aux_threshmatch _vq_auxt__44u2__p7_0 = {
  147744. _vq_quantthresh__44u2__p7_0,
  147745. _vq_quantmap__44u2__p7_0,
  147746. 9,
  147747. 9
  147748. };
  147749. static static_codebook _44u2__p7_0 = {
  147750. 2, 81,
  147751. _vq_lengthlist__44u2__p7_0,
  147752. 1, -516612096, 1626677248, 4, 0,
  147753. _vq_quantlist__44u2__p7_0,
  147754. NULL,
  147755. &_vq_auxt__44u2__p7_0,
  147756. NULL,
  147757. 0
  147758. };
  147759. static long _vq_quantlist__44u2__p7_1[] = {
  147760. 6,
  147761. 5,
  147762. 7,
  147763. 4,
  147764. 8,
  147765. 3,
  147766. 9,
  147767. 2,
  147768. 10,
  147769. 1,
  147770. 11,
  147771. 0,
  147772. 12,
  147773. };
  147774. static long _vq_lengthlist__44u2__p7_1[] = {
  147775. 1, 4, 4, 7, 6, 7, 6, 8, 7, 9, 7, 9, 8, 4, 7, 6,
  147776. 8, 8, 9, 8,10, 9,10,10,11,11, 4, 7, 7, 8, 8, 8,
  147777. 8, 9,10,11,11,11,11, 6, 8, 8,10,10,10,10,11,11,
  147778. 12,12,12,12, 7, 8, 8,10,10,10,10,11,11,12,12,13,
  147779. 13, 7, 9, 9,11,10,12,12,13,13,14,13,14,14, 7, 9,
  147780. 9,10,11,11,12,13,13,13,13,16,14, 9,10,10,12,12,
  147781. 13,13,14,14,15,16,15,16, 9,10,10,12,12,12,13,14,
  147782. 14,14,15,16,15,10,12,12,13,13,15,13,16,16,15,17,
  147783. 17,17,10,11,11,12,14,14,14,15,15,17,17,15,17,11,
  147784. 12,12,14,14,14,15,15,15,17,16,17,17,10,12,12,13,
  147785. 14,14,14,17,15,17,17,17,17,
  147786. };
  147787. static float _vq_quantthresh__44u2__p7_1[] = {
  147788. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  147789. 32.5, 45.5, 58.5, 71.5,
  147790. };
  147791. static long _vq_quantmap__44u2__p7_1[] = {
  147792. 11, 9, 7, 5, 3, 1, 0, 2,
  147793. 4, 6, 8, 10, 12,
  147794. };
  147795. static encode_aux_threshmatch _vq_auxt__44u2__p7_1 = {
  147796. _vq_quantthresh__44u2__p7_1,
  147797. _vq_quantmap__44u2__p7_1,
  147798. 13,
  147799. 13
  147800. };
  147801. static static_codebook _44u2__p7_1 = {
  147802. 2, 169,
  147803. _vq_lengthlist__44u2__p7_1,
  147804. 1, -523010048, 1618608128, 4, 0,
  147805. _vq_quantlist__44u2__p7_1,
  147806. NULL,
  147807. &_vq_auxt__44u2__p7_1,
  147808. NULL,
  147809. 0
  147810. };
  147811. static long _vq_quantlist__44u2__p7_2[] = {
  147812. 6,
  147813. 5,
  147814. 7,
  147815. 4,
  147816. 8,
  147817. 3,
  147818. 9,
  147819. 2,
  147820. 10,
  147821. 1,
  147822. 11,
  147823. 0,
  147824. 12,
  147825. };
  147826. static long _vq_lengthlist__44u2__p7_2[] = {
  147827. 2, 5, 5, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 5, 6, 6,
  147828. 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 5, 6, 6, 7, 7, 8,
  147829. 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7, 8, 8, 8, 8, 8,
  147830. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  147831. 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 7, 8,
  147832. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 9,
  147833. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  147834. 9, 9, 9, 9, 9, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147835. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8,
  147836. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9,
  147837. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147838. };
  147839. static float _vq_quantthresh__44u2__p7_2[] = {
  147840. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  147841. 2.5, 3.5, 4.5, 5.5,
  147842. };
  147843. static long _vq_quantmap__44u2__p7_2[] = {
  147844. 11, 9, 7, 5, 3, 1, 0, 2,
  147845. 4, 6, 8, 10, 12,
  147846. };
  147847. static encode_aux_threshmatch _vq_auxt__44u2__p7_2 = {
  147848. _vq_quantthresh__44u2__p7_2,
  147849. _vq_quantmap__44u2__p7_2,
  147850. 13,
  147851. 13
  147852. };
  147853. static static_codebook _44u2__p7_2 = {
  147854. 2, 169,
  147855. _vq_lengthlist__44u2__p7_2,
  147856. 1, -531103744, 1611661312, 4, 0,
  147857. _vq_quantlist__44u2__p7_2,
  147858. NULL,
  147859. &_vq_auxt__44u2__p7_2,
  147860. NULL,
  147861. 0
  147862. };
  147863. static long _huff_lengthlist__44u2__short[] = {
  147864. 13,15,17,17,15,15,12,17,11, 9, 7,10,10, 9,12,17,
  147865. 10, 6, 3, 6, 5, 7,10,17,15,10, 6, 9, 8, 9,11,17,
  147866. 15, 8, 4, 7, 3, 5, 9,16,16,10, 5, 8, 4, 5, 8,16,
  147867. 13,11, 5, 8, 3, 3, 5,14,13,12, 7,10, 5, 5, 7,14,
  147868. };
  147869. static static_codebook _huff_book__44u2__short = {
  147870. 2, 64,
  147871. _huff_lengthlist__44u2__short,
  147872. 0, 0, 0, 0, 0,
  147873. NULL,
  147874. NULL,
  147875. NULL,
  147876. NULL,
  147877. 0
  147878. };
  147879. static long _huff_lengthlist__44u3__long[] = {
  147880. 6, 9,13,12,14,11,10,13, 8, 4, 5, 7, 8, 7, 8,12,
  147881. 11, 4, 3, 5, 5, 7, 9,14,11, 6, 5, 6, 6, 6, 7,13,
  147882. 13, 7, 5, 6, 4, 5, 7,14,11, 7, 6, 6, 5, 5, 6,13,
  147883. 9, 7, 8, 6, 7, 5, 3, 9, 9,12,13,12,14,10, 6, 7,
  147884. };
  147885. static static_codebook _huff_book__44u3__long = {
  147886. 2, 64,
  147887. _huff_lengthlist__44u3__long,
  147888. 0, 0, 0, 0, 0,
  147889. NULL,
  147890. NULL,
  147891. NULL,
  147892. NULL,
  147893. 0
  147894. };
  147895. static long _vq_quantlist__44u3__p1_0[] = {
  147896. 1,
  147897. 0,
  147898. 2,
  147899. };
  147900. static long _vq_lengthlist__44u3__p1_0[] = {
  147901. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  147902. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  147903. 11, 8,11,11, 8,11,11,11,13,14,11,14,14, 8,11,11,
  147904. 10,14,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  147905. 11,11,11,14,14,10,12,14, 8,11,11,11,14,14,11,14,
  147906. 13,
  147907. };
  147908. static float _vq_quantthresh__44u3__p1_0[] = {
  147909. -0.5, 0.5,
  147910. };
  147911. static long _vq_quantmap__44u3__p1_0[] = {
  147912. 1, 0, 2,
  147913. };
  147914. static encode_aux_threshmatch _vq_auxt__44u3__p1_0 = {
  147915. _vq_quantthresh__44u3__p1_0,
  147916. _vq_quantmap__44u3__p1_0,
  147917. 3,
  147918. 3
  147919. };
  147920. static static_codebook _44u3__p1_0 = {
  147921. 4, 81,
  147922. _vq_lengthlist__44u3__p1_0,
  147923. 1, -535822336, 1611661312, 2, 0,
  147924. _vq_quantlist__44u3__p1_0,
  147925. NULL,
  147926. &_vq_auxt__44u3__p1_0,
  147927. NULL,
  147928. 0
  147929. };
  147930. static long _vq_quantlist__44u3__p2_0[] = {
  147931. 1,
  147932. 0,
  147933. 2,
  147934. };
  147935. static long _vq_lengthlist__44u3__p2_0[] = {
  147936. 2, 5, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  147937. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 7, 8,
  147938. 8, 6, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  147939. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  147940. 8, 8, 8,10,10, 8, 8,10, 7, 8, 8, 8,10,10, 8,10,
  147941. 9,
  147942. };
  147943. static float _vq_quantthresh__44u3__p2_0[] = {
  147944. -0.5, 0.5,
  147945. };
  147946. static long _vq_quantmap__44u3__p2_0[] = {
  147947. 1, 0, 2,
  147948. };
  147949. static encode_aux_threshmatch _vq_auxt__44u3__p2_0 = {
  147950. _vq_quantthresh__44u3__p2_0,
  147951. _vq_quantmap__44u3__p2_0,
  147952. 3,
  147953. 3
  147954. };
  147955. static static_codebook _44u3__p2_0 = {
  147956. 4, 81,
  147957. _vq_lengthlist__44u3__p2_0,
  147958. 1, -535822336, 1611661312, 2, 0,
  147959. _vq_quantlist__44u3__p2_0,
  147960. NULL,
  147961. &_vq_auxt__44u3__p2_0,
  147962. NULL,
  147963. 0
  147964. };
  147965. static long _vq_quantlist__44u3__p3_0[] = {
  147966. 2,
  147967. 1,
  147968. 3,
  147969. 0,
  147970. 4,
  147971. };
  147972. static long _vq_lengthlist__44u3__p3_0[] = {
  147973. 2, 4, 4, 7, 7, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  147974. 9, 9,12,12, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  147975. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  147976. 13,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  147977. 11, 9,11,10,13,13,10,11,11,14,13, 8,10,10,14,13,
  147978. 10,11,11,15,14, 9,11,11,14,14,13,14,13,16,16,12,
  147979. 13,13,15,15, 8,10,10,13,14, 9,11,11,14,14,10,11,
  147980. 11,14,15,12,13,13,15,15,13,14,14,15,16, 5, 7, 7,
  147981. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  147982. 14,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  147983. 9,11,11,13,13,12,12,13,15,15,11,12,13,15,16, 7,
  147984. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  147985. 12,15,13,11,13,13,15,16, 9,12,11,15,14,11,12,13,
  147986. 16,15,11,13,13,15,16,14,14,15,17,16,13,15,16, 0,
  147987. 17, 9,11,11,15,15,10,13,12,15,15,11,13,13,15,16,
  147988. 13,15,13,16,15,14,16,15, 0,19, 5, 7, 7,10,10, 7,
  147989. 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,14,10,11,
  147990. 12,14,14, 7, 9, 9,12,12, 9,11,11,14,13, 9,10,11,
  147991. 12,13,11,13,13,16,16,11,12,13,13,16, 7, 9, 9,12,
  147992. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,15,
  147993. 12,13,12,15,14, 9,11,11,15,14,11,13,12,16,16,10,
  147994. 12,12,15,15,13,15,15,17,19,13,14,15,16,17,10,12,
  147995. 12,15,15,11,13,13,16,16,11,13,13,15,16,13,15,15,
  147996. 0, 0,14,15,15,16,16, 8,10,10,14,14,10,12,12,15,
  147997. 15,10,12,11,15,16,14,15,15,19,20,13,14,14,18,16,
  147998. 9,11,11,15,15,11,13,13,17,16,11,13,13,16,16,15,
  147999. 17,17,20,20,14,15,16,17,20, 9,11,11,15,15,10,13,
  148000. 12,16,15,11,13,13,15,17,14,16,15,18, 0,14,16,15,
  148001. 18,20,12,14,14, 0, 0,14,14,16, 0, 0,13,16,15, 0,
  148002. 0,17,17,18, 0, 0,16,17,19,19, 0,12,14,14,18, 0,
  148003. 12,16,14, 0,17,13,15,15,18, 0,16,18,17, 0,17,16,
  148004. 18,17, 0, 0, 7,10,10,14,14,10,12,11,15,15,10,12,
  148005. 12,16,15,13,15,15,18, 0,14,15,15,17, 0, 9,11,11,
  148006. 15,15,11,13,13,16,16,11,12,13,16,16,14,15,16,17,
  148007. 17,14,16,16,16,18, 9,11,12,16,16,11,13,13,17,17,
  148008. 11,14,13,20,17,15,16,16,19, 0,15,16,17, 0,19,11,
  148009. 13,14,17,16,14,15,15,20,18,13,14,15,17,19,16,18,
  148010. 18, 0,20,16,16,19,17, 0,12,15,14,17, 0,14,15,15,
  148011. 18,19,13,16,15,19,20,15,18,18, 0,20,17, 0,16, 0,
  148012. 0,
  148013. };
  148014. static float _vq_quantthresh__44u3__p3_0[] = {
  148015. -1.5, -0.5, 0.5, 1.5,
  148016. };
  148017. static long _vq_quantmap__44u3__p3_0[] = {
  148018. 3, 1, 0, 2, 4,
  148019. };
  148020. static encode_aux_threshmatch _vq_auxt__44u3__p3_0 = {
  148021. _vq_quantthresh__44u3__p3_0,
  148022. _vq_quantmap__44u3__p3_0,
  148023. 5,
  148024. 5
  148025. };
  148026. static static_codebook _44u3__p3_0 = {
  148027. 4, 625,
  148028. _vq_lengthlist__44u3__p3_0,
  148029. 1, -533725184, 1611661312, 3, 0,
  148030. _vq_quantlist__44u3__p3_0,
  148031. NULL,
  148032. &_vq_auxt__44u3__p3_0,
  148033. NULL,
  148034. 0
  148035. };
  148036. static long _vq_quantlist__44u3__p4_0[] = {
  148037. 2,
  148038. 1,
  148039. 3,
  148040. 0,
  148041. 4,
  148042. };
  148043. static long _vq_lengthlist__44u3__p4_0[] = {
  148044. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  148045. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  148046. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  148047. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  148048. 10, 9,10, 9,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  148049. 9,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  148050. 12,12,13,14, 9, 9,10,12,12, 9,10,10,12,12, 9,10,
  148051. 10,12,13,11,12,11,14,13,12,12,12,14,13, 5, 7, 7,
  148052. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  148053. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  148054. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  148055. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  148056. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  148057. 13,13,10,11,11,13,13,12,12,13,12,15,12,13,13,15,
  148058. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  148059. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  148060. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  148061. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  148062. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  148063. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  148064. 11,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  148065. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  148066. 11,12,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  148067. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  148068. 13, 9,10,10,13,13,12,13,13,15,14,12,12,12,14,13,
  148069. 9,10,10,13,12,10,11,11,13,13,10,11,11,14,12,13,
  148070. 13,14,14,16,12,13,13,15,15, 9,10,10,13,13,10,11,
  148071. 10,14,13,10,11,11,13,14,12,14,13,15,14,13,13,13,
  148072. 15,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  148073. 14,14,12,15,12,16,14,15,15,17,15,11,12,12,14,14,
  148074. 11,13,11,15,14,12,13,13,15,15,13,15,12,17,13,14,
  148075. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  148076. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  148077. 13,12,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  148078. 15,12,12,13,14,16, 9,10,10,13,13,10,11,11,13,14,
  148079. 10,11,11,14,13,12,13,13,14,15,13,14,13,16,14,11,
  148080. 12,12,14,14,12,13,13,15,14,11,12,13,14,15,14,15,
  148081. 15,16,16,13,13,15,13,16,11,12,12,14,15,12,13,13,
  148082. 14,15,11,13,12,15,14,14,15,15,16,16,14,15,12,16,
  148083. 13,
  148084. };
  148085. static float _vq_quantthresh__44u3__p4_0[] = {
  148086. -1.5, -0.5, 0.5, 1.5,
  148087. };
  148088. static long _vq_quantmap__44u3__p4_0[] = {
  148089. 3, 1, 0, 2, 4,
  148090. };
  148091. static encode_aux_threshmatch _vq_auxt__44u3__p4_0 = {
  148092. _vq_quantthresh__44u3__p4_0,
  148093. _vq_quantmap__44u3__p4_0,
  148094. 5,
  148095. 5
  148096. };
  148097. static static_codebook _44u3__p4_0 = {
  148098. 4, 625,
  148099. _vq_lengthlist__44u3__p4_0,
  148100. 1, -533725184, 1611661312, 3, 0,
  148101. _vq_quantlist__44u3__p4_0,
  148102. NULL,
  148103. &_vq_auxt__44u3__p4_0,
  148104. NULL,
  148105. 0
  148106. };
  148107. static long _vq_quantlist__44u3__p5_0[] = {
  148108. 4,
  148109. 3,
  148110. 5,
  148111. 2,
  148112. 6,
  148113. 1,
  148114. 7,
  148115. 0,
  148116. 8,
  148117. };
  148118. static long _vq_lengthlist__44u3__p5_0[] = {
  148119. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  148120. 10,10, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  148121. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,10, 7, 8, 8,
  148122. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  148123. 10,10,11,10,11,11,12,12, 9,10,10,10,10,11,11,12,
  148124. 12,
  148125. };
  148126. static float _vq_quantthresh__44u3__p5_0[] = {
  148127. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148128. };
  148129. static long _vq_quantmap__44u3__p5_0[] = {
  148130. 7, 5, 3, 1, 0, 2, 4, 6,
  148131. 8,
  148132. };
  148133. static encode_aux_threshmatch _vq_auxt__44u3__p5_0 = {
  148134. _vq_quantthresh__44u3__p5_0,
  148135. _vq_quantmap__44u3__p5_0,
  148136. 9,
  148137. 9
  148138. };
  148139. static static_codebook _44u3__p5_0 = {
  148140. 2, 81,
  148141. _vq_lengthlist__44u3__p5_0,
  148142. 1, -531628032, 1611661312, 4, 0,
  148143. _vq_quantlist__44u3__p5_0,
  148144. NULL,
  148145. &_vq_auxt__44u3__p5_0,
  148146. NULL,
  148147. 0
  148148. };
  148149. static long _vq_quantlist__44u3__p6_0[] = {
  148150. 6,
  148151. 5,
  148152. 7,
  148153. 4,
  148154. 8,
  148155. 3,
  148156. 9,
  148157. 2,
  148158. 10,
  148159. 1,
  148160. 11,
  148161. 0,
  148162. 12,
  148163. };
  148164. static long _vq_lengthlist__44u3__p6_0[] = {
  148165. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,13,14, 4, 6, 5,
  148166. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  148167. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  148168. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  148169. 15, 8, 9, 9,11,10,11,11,12,12,13,13,15,16, 8, 9,
  148170. 9,10,11,11,11,12,12,13,13,16,16,10,10,11,11,11,
  148171. 12,12,13,13,13,14,17,16, 9,10,11,12,11,12,12,13,
  148172. 13,13,13,16,18,11,12,11,12,12,13,13,13,14,15,14,
  148173. 17,17,11,11,12,12,12,13,13,13,14,14,15,18,17,14,
  148174. 15,15,15,15,16,16,17,17,19,18, 0,20,14,15,14,15,
  148175. 15,16,16,16,17,18,16,20,18,
  148176. };
  148177. static float _vq_quantthresh__44u3__p6_0[] = {
  148178. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  148179. 12.5, 17.5, 22.5, 27.5,
  148180. };
  148181. static long _vq_quantmap__44u3__p6_0[] = {
  148182. 11, 9, 7, 5, 3, 1, 0, 2,
  148183. 4, 6, 8, 10, 12,
  148184. };
  148185. static encode_aux_threshmatch _vq_auxt__44u3__p6_0 = {
  148186. _vq_quantthresh__44u3__p6_0,
  148187. _vq_quantmap__44u3__p6_0,
  148188. 13,
  148189. 13
  148190. };
  148191. static static_codebook _44u3__p6_0 = {
  148192. 2, 169,
  148193. _vq_lengthlist__44u3__p6_0,
  148194. 1, -526516224, 1616117760, 4, 0,
  148195. _vq_quantlist__44u3__p6_0,
  148196. NULL,
  148197. &_vq_auxt__44u3__p6_0,
  148198. NULL,
  148199. 0
  148200. };
  148201. static long _vq_quantlist__44u3__p6_1[] = {
  148202. 2,
  148203. 1,
  148204. 3,
  148205. 0,
  148206. 4,
  148207. };
  148208. static long _vq_lengthlist__44u3__p6_1[] = {
  148209. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  148210. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  148211. };
  148212. static float _vq_quantthresh__44u3__p6_1[] = {
  148213. -1.5, -0.5, 0.5, 1.5,
  148214. };
  148215. static long _vq_quantmap__44u3__p6_1[] = {
  148216. 3, 1, 0, 2, 4,
  148217. };
  148218. static encode_aux_threshmatch _vq_auxt__44u3__p6_1 = {
  148219. _vq_quantthresh__44u3__p6_1,
  148220. _vq_quantmap__44u3__p6_1,
  148221. 5,
  148222. 5
  148223. };
  148224. static static_codebook _44u3__p6_1 = {
  148225. 2, 25,
  148226. _vq_lengthlist__44u3__p6_1,
  148227. 1, -533725184, 1611661312, 3, 0,
  148228. _vq_quantlist__44u3__p6_1,
  148229. NULL,
  148230. &_vq_auxt__44u3__p6_1,
  148231. NULL,
  148232. 0
  148233. };
  148234. static long _vq_quantlist__44u3__p7_0[] = {
  148235. 4,
  148236. 3,
  148237. 5,
  148238. 2,
  148239. 6,
  148240. 1,
  148241. 7,
  148242. 0,
  148243. 8,
  148244. };
  148245. static long _vq_lengthlist__44u3__p7_0[] = {
  148246. 1, 3, 3,10,10,10,10,10,10, 4,10,10,10,10,10,10,
  148247. 10,10, 4,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  148248. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148249. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148250. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148251. 9,
  148252. };
  148253. static float _vq_quantthresh__44u3__p7_0[] = {
  148254. -892.5, -637.5, -382.5, -127.5, 127.5, 382.5, 637.5, 892.5,
  148255. };
  148256. static long _vq_quantmap__44u3__p7_0[] = {
  148257. 7, 5, 3, 1, 0, 2, 4, 6,
  148258. 8,
  148259. };
  148260. static encode_aux_threshmatch _vq_auxt__44u3__p7_0 = {
  148261. _vq_quantthresh__44u3__p7_0,
  148262. _vq_quantmap__44u3__p7_0,
  148263. 9,
  148264. 9
  148265. };
  148266. static static_codebook _44u3__p7_0 = {
  148267. 2, 81,
  148268. _vq_lengthlist__44u3__p7_0,
  148269. 1, -515907584, 1627381760, 4, 0,
  148270. _vq_quantlist__44u3__p7_0,
  148271. NULL,
  148272. &_vq_auxt__44u3__p7_0,
  148273. NULL,
  148274. 0
  148275. };
  148276. static long _vq_quantlist__44u3__p7_1[] = {
  148277. 7,
  148278. 6,
  148279. 8,
  148280. 5,
  148281. 9,
  148282. 4,
  148283. 10,
  148284. 3,
  148285. 11,
  148286. 2,
  148287. 12,
  148288. 1,
  148289. 13,
  148290. 0,
  148291. 14,
  148292. };
  148293. static long _vq_lengthlist__44u3__p7_1[] = {
  148294. 1, 4, 4, 6, 6, 7, 6, 8, 7, 9, 8,10, 9,11,11, 4,
  148295. 7, 7, 8, 7, 9, 9,10,10,11,11,11,11,12,12, 4, 7,
  148296. 7, 7, 7, 9, 9,10,10,11,11,12,12,12,11, 6, 8, 8,
  148297. 9, 9,10,10,11,11,12,12,13,12,13,13, 6, 8, 8, 9,
  148298. 9,10,11,11,11,12,12,13,14,13,13, 8, 9, 9,11,11,
  148299. 12,12,12,13,14,13,14,14,14,15, 8, 9, 9,11,11,11,
  148300. 12,13,14,13,14,15,17,14,15, 9,10,10,12,12,13,13,
  148301. 13,14,15,15,15,16,16,16, 9,11,11,12,12,13,13,14,
  148302. 14,14,15,16,16,16,16,10,12,12,13,13,14,14,15,15,
  148303. 15,16,17,17,17,17,10,12,11,13,13,15,14,15,14,16,
  148304. 17,16,16,16,16,11,13,12,14,14,14,14,15,16,17,16,
  148305. 17,17,17,17,11,13,12,14,14,14,15,17,16,17,17,17,
  148306. 17,17,17,12,13,13,15,16,15,16,17,17,16,16,17,17,
  148307. 17,17,12,13,13,15,15,15,16,17,17,17,16,17,16,17,
  148308. 17,
  148309. };
  148310. static float _vq_quantthresh__44u3__p7_1[] = {
  148311. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  148312. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  148313. };
  148314. static long _vq_quantmap__44u3__p7_1[] = {
  148315. 13, 11, 9, 7, 5, 3, 1, 0,
  148316. 2, 4, 6, 8, 10, 12, 14,
  148317. };
  148318. static encode_aux_threshmatch _vq_auxt__44u3__p7_1 = {
  148319. _vq_quantthresh__44u3__p7_1,
  148320. _vq_quantmap__44u3__p7_1,
  148321. 15,
  148322. 15
  148323. };
  148324. static static_codebook _44u3__p7_1 = {
  148325. 2, 225,
  148326. _vq_lengthlist__44u3__p7_1,
  148327. 1, -522338304, 1620115456, 4, 0,
  148328. _vq_quantlist__44u3__p7_1,
  148329. NULL,
  148330. &_vq_auxt__44u3__p7_1,
  148331. NULL,
  148332. 0
  148333. };
  148334. static long _vq_quantlist__44u3__p7_2[] = {
  148335. 8,
  148336. 7,
  148337. 9,
  148338. 6,
  148339. 10,
  148340. 5,
  148341. 11,
  148342. 4,
  148343. 12,
  148344. 3,
  148345. 13,
  148346. 2,
  148347. 14,
  148348. 1,
  148349. 15,
  148350. 0,
  148351. 16,
  148352. };
  148353. static long _vq_lengthlist__44u3__p7_2[] = {
  148354. 2, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148355. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148356. 10,10, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  148357. 9,10, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148358. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  148359. 9,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148360. 10,10,10,10,10,10, 7, 8, 8, 9, 8, 9, 9, 9, 9,10,
  148361. 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148362. 9,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9,10,
  148363. 9,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  148364. 9,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  148365. 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,
  148366. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10,
  148367. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  148368. 10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,10,
  148369. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,
  148370. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148371. 9,10,10,10,10,10,10,10,10,10,10,10,11,11,11,10,
  148372. 11,
  148373. };
  148374. static float _vq_quantthresh__44u3__p7_2[] = {
  148375. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  148376. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  148377. };
  148378. static long _vq_quantmap__44u3__p7_2[] = {
  148379. 15, 13, 11, 9, 7, 5, 3, 1,
  148380. 0, 2, 4, 6, 8, 10, 12, 14,
  148381. 16,
  148382. };
  148383. static encode_aux_threshmatch _vq_auxt__44u3__p7_2 = {
  148384. _vq_quantthresh__44u3__p7_2,
  148385. _vq_quantmap__44u3__p7_2,
  148386. 17,
  148387. 17
  148388. };
  148389. static static_codebook _44u3__p7_2 = {
  148390. 2, 289,
  148391. _vq_lengthlist__44u3__p7_2,
  148392. 1, -529530880, 1611661312, 5, 0,
  148393. _vq_quantlist__44u3__p7_2,
  148394. NULL,
  148395. &_vq_auxt__44u3__p7_2,
  148396. NULL,
  148397. 0
  148398. };
  148399. static long _huff_lengthlist__44u3__short[] = {
  148400. 14,14,14,15,13,15,12,16,10, 8, 7, 9, 9, 8,12,16,
  148401. 10, 5, 4, 6, 5, 6, 9,16,14, 8, 6, 8, 7, 8,10,16,
  148402. 14, 7, 4, 6, 3, 5, 8,16,15, 9, 5, 7, 4, 4, 7,16,
  148403. 13,10, 6, 7, 4, 3, 4,13,13,12, 7, 9, 5, 5, 6,12,
  148404. };
  148405. static static_codebook _huff_book__44u3__short = {
  148406. 2, 64,
  148407. _huff_lengthlist__44u3__short,
  148408. 0, 0, 0, 0, 0,
  148409. NULL,
  148410. NULL,
  148411. NULL,
  148412. NULL,
  148413. 0
  148414. };
  148415. static long _huff_lengthlist__44u4__long[] = {
  148416. 3, 8,12,12,13,12,11,13, 5, 4, 6, 7, 8, 8, 9,13,
  148417. 9, 5, 4, 5, 5, 7, 9,13, 9, 6, 5, 6, 6, 7, 8,12,
  148418. 12, 7, 5, 6, 4, 5, 8,13,11, 7, 6, 6, 5, 5, 6,12,
  148419. 10, 8, 8, 7, 7, 5, 3, 8,10,12,13,12,12, 9, 6, 7,
  148420. };
  148421. static static_codebook _huff_book__44u4__long = {
  148422. 2, 64,
  148423. _huff_lengthlist__44u4__long,
  148424. 0, 0, 0, 0, 0,
  148425. NULL,
  148426. NULL,
  148427. NULL,
  148428. NULL,
  148429. 0
  148430. };
  148431. static long _vq_quantlist__44u4__p1_0[] = {
  148432. 1,
  148433. 0,
  148434. 2,
  148435. };
  148436. static long _vq_lengthlist__44u4__p1_0[] = {
  148437. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  148438. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  148439. 11, 8,11,11, 8,11,11,11,13,14,11,15,14, 8,11,11,
  148440. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  148441. 11,11,11,15,14,10,12,14, 8,11,11,11,14,14,11,14,
  148442. 13,
  148443. };
  148444. static float _vq_quantthresh__44u4__p1_0[] = {
  148445. -0.5, 0.5,
  148446. };
  148447. static long _vq_quantmap__44u4__p1_0[] = {
  148448. 1, 0, 2,
  148449. };
  148450. static encode_aux_threshmatch _vq_auxt__44u4__p1_0 = {
  148451. _vq_quantthresh__44u4__p1_0,
  148452. _vq_quantmap__44u4__p1_0,
  148453. 3,
  148454. 3
  148455. };
  148456. static static_codebook _44u4__p1_0 = {
  148457. 4, 81,
  148458. _vq_lengthlist__44u4__p1_0,
  148459. 1, -535822336, 1611661312, 2, 0,
  148460. _vq_quantlist__44u4__p1_0,
  148461. NULL,
  148462. &_vq_auxt__44u4__p1_0,
  148463. NULL,
  148464. 0
  148465. };
  148466. static long _vq_quantlist__44u4__p2_0[] = {
  148467. 1,
  148468. 0,
  148469. 2,
  148470. };
  148471. static long _vq_lengthlist__44u4__p2_0[] = {
  148472. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  148473. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 6, 8,
  148474. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  148475. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 6, 8, 8, 6,
  148476. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  148477. 9,
  148478. };
  148479. static float _vq_quantthresh__44u4__p2_0[] = {
  148480. -0.5, 0.5,
  148481. };
  148482. static long _vq_quantmap__44u4__p2_0[] = {
  148483. 1, 0, 2,
  148484. };
  148485. static encode_aux_threshmatch _vq_auxt__44u4__p2_0 = {
  148486. _vq_quantthresh__44u4__p2_0,
  148487. _vq_quantmap__44u4__p2_0,
  148488. 3,
  148489. 3
  148490. };
  148491. static static_codebook _44u4__p2_0 = {
  148492. 4, 81,
  148493. _vq_lengthlist__44u4__p2_0,
  148494. 1, -535822336, 1611661312, 2, 0,
  148495. _vq_quantlist__44u4__p2_0,
  148496. NULL,
  148497. &_vq_auxt__44u4__p2_0,
  148498. NULL,
  148499. 0
  148500. };
  148501. static long _vq_quantlist__44u4__p3_0[] = {
  148502. 2,
  148503. 1,
  148504. 3,
  148505. 0,
  148506. 4,
  148507. };
  148508. static long _vq_lengthlist__44u4__p3_0[] = {
  148509. 2, 4, 4, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  148510. 10, 9,12,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  148511. 9,11,11, 7, 9, 9,11,11,10,12,11,14,14, 9,10,11,
  148512. 13,14, 5, 7, 7,10,10, 7, 9, 9,11,11, 7, 9, 9,11,
  148513. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  148514. 10,12,12,15,14, 9,11,11,15,14,13,14,14,17,17,12,
  148515. 14,14,16,16, 8,10,10,14,14, 9,11,11,14,15,10,12,
  148516. 12,14,15,12,14,13,16,16,13,14,15,15,18, 4, 7, 7,
  148517. 10,10, 7, 9, 9,12,11, 7, 9, 9,11,12,10,12,11,15,
  148518. 14,10,11,12,14,15, 7, 9, 9,12,12, 9,11,12,13,13,
  148519. 9,11,12,13,13,12,13,13,15,16,11,13,13,15,16, 7,
  148520. 9, 9,12,12, 9,11,10,13,12, 9,11,12,13,14,11,13,
  148521. 12,16,14,12,13,13,15,16,10,12,12,16,15,11,13,13,
  148522. 17,16,11,13,13,17,16,14,15,15,17,17,14,16,16,18,
  148523. 20, 9,11,11,15,16,11,13,12,16,16,11,13,13,16,17,
  148524. 14,15,14,18,16,14,16,16,17,20, 5, 7, 7,10,10, 7,
  148525. 9, 9,12,11, 7, 9,10,11,12,10,12,11,15,15,10,12,
  148526. 12,14,14, 7, 9, 9,12,12, 9,12,11,14,13, 9,10,11,
  148527. 12,13,12,13,14,16,16,11,12,13,14,16, 7, 9, 9,12,
  148528. 12, 9,12,11,13,13, 9,12,11,13,13,11,13,13,16,16,
  148529. 12,13,13,16,15, 9,11,11,16,14,11,13,13,16,16,11,
  148530. 12,13,16,16,14,16,16,17,17,13,14,15,16,17,10,12,
  148531. 12,15,15,11,13,13,16,17,11,13,13,16,16,14,16,15,
  148532. 19,19,14,15,15,17,18, 8,10,10,14,14,10,12,12,15,
  148533. 15,10,12,12,16,16,14,16,15,20,19,13,15,15,17,16,
  148534. 9,12,12,16,16,11,13,13,16,18,11,14,13,16,17,16,
  148535. 17,16,20, 0,15,16,18,18,20, 9,11,11,15,15,11,14,
  148536. 12,17,16,11,13,13,17,17,15,17,15,20,20,14,16,16,
  148537. 17, 0,13,15,14,18,16,14,15,16, 0,18,14,16,16, 0,
  148538. 0,18,16, 0, 0,20,16,18,18, 0, 0,12,14,14,17,18,
  148539. 13,15,14,20,18,14,16,15,19,19,16,20,16, 0,18,16,
  148540. 19,17,19, 0, 8,10,10,14,14,10,12,12,16,15,10,12,
  148541. 12,16,16,13,15,15,18,17,14,16,16,19, 0, 9,11,11,
  148542. 16,15,11,14,13,18,17,11,12,13,17,18,14,17,16,18,
  148543. 18,15,16,17,18,18, 9,12,12,16,16,11,13,13,16,18,
  148544. 11,14,13,17,17,15,16,16,18,20,16,17,17,20,20,12,
  148545. 14,14,18,17,14,16,16, 0,19,13,14,15,18, 0,16, 0,
  148546. 0, 0, 0,16,16, 0,19,20,13,15,14, 0, 0,14,16,16,
  148547. 18,19,14,16,15, 0,20,16,20,18, 0,20,17,20,17, 0,
  148548. 0,
  148549. };
  148550. static float _vq_quantthresh__44u4__p3_0[] = {
  148551. -1.5, -0.5, 0.5, 1.5,
  148552. };
  148553. static long _vq_quantmap__44u4__p3_0[] = {
  148554. 3, 1, 0, 2, 4,
  148555. };
  148556. static encode_aux_threshmatch _vq_auxt__44u4__p3_0 = {
  148557. _vq_quantthresh__44u4__p3_0,
  148558. _vq_quantmap__44u4__p3_0,
  148559. 5,
  148560. 5
  148561. };
  148562. static static_codebook _44u4__p3_0 = {
  148563. 4, 625,
  148564. _vq_lengthlist__44u4__p3_0,
  148565. 1, -533725184, 1611661312, 3, 0,
  148566. _vq_quantlist__44u4__p3_0,
  148567. NULL,
  148568. &_vq_auxt__44u4__p3_0,
  148569. NULL,
  148570. 0
  148571. };
  148572. static long _vq_quantlist__44u4__p4_0[] = {
  148573. 2,
  148574. 1,
  148575. 3,
  148576. 0,
  148577. 4,
  148578. };
  148579. static long _vq_lengthlist__44u4__p4_0[] = {
  148580. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  148581. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  148582. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  148583. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  148584. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  148585. 9,10,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  148586. 12,12,13,14, 9, 9,10,12,12, 9,10,10,13,13, 9,10,
  148587. 10,12,13,11,12,12,14,13,11,12,12,14,14, 5, 7, 7,
  148588. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  148589. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  148590. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  148591. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  148592. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  148593. 13,14,10,11,11,14,13,12,12,13,12,15,12,13,13,15,
  148594. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  148595. 12,13,11,15,13,13,13,13,15,15, 5, 7, 7, 9, 9, 7,
  148596. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  148597. 11,12,13, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  148598. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  148599. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  148600. 11,12,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  148601. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  148602. 11,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  148603. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  148604. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  148605. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,13,13,
  148606. 13,14,14,16,13,13,13,15,15, 9,10,10,13,13,10,11,
  148607. 10,14,13,10,11,11,13,14,12,14,13,16,14,12,13,13,
  148608. 14,15,11,12,12,15,14,11,12,13,14,15,12,13,13,16,
  148609. 15,14,12,15,12,16,14,15,15,16,16,11,12,12,14,14,
  148610. 11,13,12,15,14,12,13,13,15,16,13,15,13,17,13,14,
  148611. 15,15,16,17, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  148612. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  148613. 13,12,10,11,11,14,13,10,10,11,13,14,13,13,13,15,
  148614. 15,12,13,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  148615. 10,11,11,14,14,13,13,13,15,15,13,14,13,16,14,11,
  148616. 12,12,15,14,12,13,13,16,15,11,12,13,14,15,14,15,
  148617. 15,17,16,13,13,15,13,16,11,12,13,14,15,13,13,13,
  148618. 15,16,11,13,12,15,14,14,15,15,16,16,14,15,12,17,
  148619. 13,
  148620. };
  148621. static float _vq_quantthresh__44u4__p4_0[] = {
  148622. -1.5, -0.5, 0.5, 1.5,
  148623. };
  148624. static long _vq_quantmap__44u4__p4_0[] = {
  148625. 3, 1, 0, 2, 4,
  148626. };
  148627. static encode_aux_threshmatch _vq_auxt__44u4__p4_0 = {
  148628. _vq_quantthresh__44u4__p4_0,
  148629. _vq_quantmap__44u4__p4_0,
  148630. 5,
  148631. 5
  148632. };
  148633. static static_codebook _44u4__p4_0 = {
  148634. 4, 625,
  148635. _vq_lengthlist__44u4__p4_0,
  148636. 1, -533725184, 1611661312, 3, 0,
  148637. _vq_quantlist__44u4__p4_0,
  148638. NULL,
  148639. &_vq_auxt__44u4__p4_0,
  148640. NULL,
  148641. 0
  148642. };
  148643. static long _vq_quantlist__44u4__p5_0[] = {
  148644. 4,
  148645. 3,
  148646. 5,
  148647. 2,
  148648. 6,
  148649. 1,
  148650. 7,
  148651. 0,
  148652. 8,
  148653. };
  148654. static long _vq_lengthlist__44u4__p5_0[] = {
  148655. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  148656. 10, 9, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  148657. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,11, 7, 8, 8,
  148658. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  148659. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  148660. 12,
  148661. };
  148662. static float _vq_quantthresh__44u4__p5_0[] = {
  148663. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148664. };
  148665. static long _vq_quantmap__44u4__p5_0[] = {
  148666. 7, 5, 3, 1, 0, 2, 4, 6,
  148667. 8,
  148668. };
  148669. static encode_aux_threshmatch _vq_auxt__44u4__p5_0 = {
  148670. _vq_quantthresh__44u4__p5_0,
  148671. _vq_quantmap__44u4__p5_0,
  148672. 9,
  148673. 9
  148674. };
  148675. static static_codebook _44u4__p5_0 = {
  148676. 2, 81,
  148677. _vq_lengthlist__44u4__p5_0,
  148678. 1, -531628032, 1611661312, 4, 0,
  148679. _vq_quantlist__44u4__p5_0,
  148680. NULL,
  148681. &_vq_auxt__44u4__p5_0,
  148682. NULL,
  148683. 0
  148684. };
  148685. static long _vq_quantlist__44u4__p6_0[] = {
  148686. 6,
  148687. 5,
  148688. 7,
  148689. 4,
  148690. 8,
  148691. 3,
  148692. 9,
  148693. 2,
  148694. 10,
  148695. 1,
  148696. 11,
  148697. 0,
  148698. 12,
  148699. };
  148700. static long _vq_lengthlist__44u4__p6_0[] = {
  148701. 1, 4, 4, 6, 6, 8, 8, 9, 9,11,10,13,13, 4, 6, 5,
  148702. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  148703. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  148704. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  148705. 15, 8, 9, 9,11,10,11,11,12,12,13,13,16,16, 8, 9,
  148706. 9,10,10,11,11,12,12,13,13,16,16,10,10,10,12,11,
  148707. 12,12,13,13,14,14,16,16,10,10,10,11,12,12,12,13,
  148708. 13,13,14,16,17,11,12,11,12,12,13,13,14,14,15,14,
  148709. 18,17,11,11,12,12,12,13,13,14,14,14,15,19,18,14,
  148710. 15,14,15,15,17,16,17,17,17,17,21, 0,14,15,15,16,
  148711. 16,16,16,17,17,18,17,20,21,
  148712. };
  148713. static float _vq_quantthresh__44u4__p6_0[] = {
  148714. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  148715. 12.5, 17.5, 22.5, 27.5,
  148716. };
  148717. static long _vq_quantmap__44u4__p6_0[] = {
  148718. 11, 9, 7, 5, 3, 1, 0, 2,
  148719. 4, 6, 8, 10, 12,
  148720. };
  148721. static encode_aux_threshmatch _vq_auxt__44u4__p6_0 = {
  148722. _vq_quantthresh__44u4__p6_0,
  148723. _vq_quantmap__44u4__p6_0,
  148724. 13,
  148725. 13
  148726. };
  148727. static static_codebook _44u4__p6_0 = {
  148728. 2, 169,
  148729. _vq_lengthlist__44u4__p6_0,
  148730. 1, -526516224, 1616117760, 4, 0,
  148731. _vq_quantlist__44u4__p6_0,
  148732. NULL,
  148733. &_vq_auxt__44u4__p6_0,
  148734. NULL,
  148735. 0
  148736. };
  148737. static long _vq_quantlist__44u4__p6_1[] = {
  148738. 2,
  148739. 1,
  148740. 3,
  148741. 0,
  148742. 4,
  148743. };
  148744. static long _vq_lengthlist__44u4__p6_1[] = {
  148745. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  148746. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  148747. };
  148748. static float _vq_quantthresh__44u4__p6_1[] = {
  148749. -1.5, -0.5, 0.5, 1.5,
  148750. };
  148751. static long _vq_quantmap__44u4__p6_1[] = {
  148752. 3, 1, 0, 2, 4,
  148753. };
  148754. static encode_aux_threshmatch _vq_auxt__44u4__p6_1 = {
  148755. _vq_quantthresh__44u4__p6_1,
  148756. _vq_quantmap__44u4__p6_1,
  148757. 5,
  148758. 5
  148759. };
  148760. static static_codebook _44u4__p6_1 = {
  148761. 2, 25,
  148762. _vq_lengthlist__44u4__p6_1,
  148763. 1, -533725184, 1611661312, 3, 0,
  148764. _vq_quantlist__44u4__p6_1,
  148765. NULL,
  148766. &_vq_auxt__44u4__p6_1,
  148767. NULL,
  148768. 0
  148769. };
  148770. static long _vq_quantlist__44u4__p7_0[] = {
  148771. 6,
  148772. 5,
  148773. 7,
  148774. 4,
  148775. 8,
  148776. 3,
  148777. 9,
  148778. 2,
  148779. 10,
  148780. 1,
  148781. 11,
  148782. 0,
  148783. 12,
  148784. };
  148785. static long _vq_lengthlist__44u4__p7_0[] = {
  148786. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 3,12,11,
  148787. 12,12,12,12,12,12,12,12,12,12, 4,11,10,12,12,12,
  148788. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148789. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148790. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148791. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,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,11,
  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,
  148797. };
  148798. static float _vq_quantthresh__44u4__p7_0[] = {
  148799. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  148800. 637.5, 892.5, 1147.5, 1402.5,
  148801. };
  148802. static long _vq_quantmap__44u4__p7_0[] = {
  148803. 11, 9, 7, 5, 3, 1, 0, 2,
  148804. 4, 6, 8, 10, 12,
  148805. };
  148806. static encode_aux_threshmatch _vq_auxt__44u4__p7_0 = {
  148807. _vq_quantthresh__44u4__p7_0,
  148808. _vq_quantmap__44u4__p7_0,
  148809. 13,
  148810. 13
  148811. };
  148812. static static_codebook _44u4__p7_0 = {
  148813. 2, 169,
  148814. _vq_lengthlist__44u4__p7_0,
  148815. 1, -514332672, 1627381760, 4, 0,
  148816. _vq_quantlist__44u4__p7_0,
  148817. NULL,
  148818. &_vq_auxt__44u4__p7_0,
  148819. NULL,
  148820. 0
  148821. };
  148822. static long _vq_quantlist__44u4__p7_1[] = {
  148823. 7,
  148824. 6,
  148825. 8,
  148826. 5,
  148827. 9,
  148828. 4,
  148829. 10,
  148830. 3,
  148831. 11,
  148832. 2,
  148833. 12,
  148834. 1,
  148835. 13,
  148836. 0,
  148837. 14,
  148838. };
  148839. static long _vq_lengthlist__44u4__p7_1[] = {
  148840. 1, 4, 4, 6, 6, 7, 7, 9, 8,10, 8,10, 9,11,11, 4,
  148841. 7, 6, 8, 7, 9, 9,10,10,11,10,11,10,12,10, 4, 6,
  148842. 7, 8, 8, 9, 9,10,10,11,11,11,11,12,12, 6, 8, 8,
  148843. 10, 9,11,10,12,11,12,12,12,12,13,13, 6, 8, 8,10,
  148844. 10,10,11,11,11,12,12,13,12,13,13, 8, 9, 9,11,11,
  148845. 12,11,12,12,13,13,13,13,13,13, 8, 9, 9,11,11,11,
  148846. 12,12,12,13,13,13,13,13,13, 9,10,10,12,11,13,13,
  148847. 13,13,14,13,13,14,14,14, 9,10,11,11,12,12,13,13,
  148848. 13,13,13,14,15,14,14,10,11,11,12,12,13,13,14,14,
  148849. 14,14,14,15,16,16,10,11,11,12,13,13,13,13,15,14,
  148850. 14,15,16,15,16,10,12,12,13,13,14,14,14,15,15,15,
  148851. 15,15,15,16,11,12,12,13,13,14,14,14,15,15,15,16,
  148852. 15,17,16,11,12,12,13,13,13,15,15,14,16,16,16,16,
  148853. 16,17,11,12,12,13,13,14,14,15,14,15,15,17,17,16,
  148854. 16,
  148855. };
  148856. static float _vq_quantthresh__44u4__p7_1[] = {
  148857. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  148858. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  148859. };
  148860. static long _vq_quantmap__44u4__p7_1[] = {
  148861. 13, 11, 9, 7, 5, 3, 1, 0,
  148862. 2, 4, 6, 8, 10, 12, 14,
  148863. };
  148864. static encode_aux_threshmatch _vq_auxt__44u4__p7_1 = {
  148865. _vq_quantthresh__44u4__p7_1,
  148866. _vq_quantmap__44u4__p7_1,
  148867. 15,
  148868. 15
  148869. };
  148870. static static_codebook _44u4__p7_1 = {
  148871. 2, 225,
  148872. _vq_lengthlist__44u4__p7_1,
  148873. 1, -522338304, 1620115456, 4, 0,
  148874. _vq_quantlist__44u4__p7_1,
  148875. NULL,
  148876. &_vq_auxt__44u4__p7_1,
  148877. NULL,
  148878. 0
  148879. };
  148880. static long _vq_quantlist__44u4__p7_2[] = {
  148881. 8,
  148882. 7,
  148883. 9,
  148884. 6,
  148885. 10,
  148886. 5,
  148887. 11,
  148888. 4,
  148889. 12,
  148890. 3,
  148891. 13,
  148892. 2,
  148893. 14,
  148894. 1,
  148895. 15,
  148896. 0,
  148897. 16,
  148898. };
  148899. static long _vq_lengthlist__44u4__p7_2[] = {
  148900. 2, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148901. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148902. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148903. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148904. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  148905. 9,10, 9,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148906. 10,10,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148907. 9,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  148908. 10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  148909. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,
  148910. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  148911. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  148912. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  148913. 10,10,10,10,10,10,10,10,10,11,10,10,10, 9, 9, 9,
  148914. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  148915. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  148916. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148917. 9,10, 9,10,10,10,10,10,10,10,10,10,10,11,10,10,
  148918. 10,
  148919. };
  148920. static float _vq_quantthresh__44u4__p7_2[] = {
  148921. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  148922. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  148923. };
  148924. static long _vq_quantmap__44u4__p7_2[] = {
  148925. 15, 13, 11, 9, 7, 5, 3, 1,
  148926. 0, 2, 4, 6, 8, 10, 12, 14,
  148927. 16,
  148928. };
  148929. static encode_aux_threshmatch _vq_auxt__44u4__p7_2 = {
  148930. _vq_quantthresh__44u4__p7_2,
  148931. _vq_quantmap__44u4__p7_2,
  148932. 17,
  148933. 17
  148934. };
  148935. static static_codebook _44u4__p7_2 = {
  148936. 2, 289,
  148937. _vq_lengthlist__44u4__p7_2,
  148938. 1, -529530880, 1611661312, 5, 0,
  148939. _vq_quantlist__44u4__p7_2,
  148940. NULL,
  148941. &_vq_auxt__44u4__p7_2,
  148942. NULL,
  148943. 0
  148944. };
  148945. static long _huff_lengthlist__44u4__short[] = {
  148946. 14,17,15,17,16,14,13,16,10, 7, 7,10,13,10,15,16,
  148947. 9, 4, 4, 6, 5, 7, 9,16,12, 8, 7, 8, 8, 8,11,16,
  148948. 14, 7, 4, 6, 3, 5, 8,15,13, 8, 5, 7, 4, 5, 7,16,
  148949. 12, 9, 6, 8, 3, 3, 5,16,14,13, 7,10, 5, 5, 7,15,
  148950. };
  148951. static static_codebook _huff_book__44u4__short = {
  148952. 2, 64,
  148953. _huff_lengthlist__44u4__short,
  148954. 0, 0, 0, 0, 0,
  148955. NULL,
  148956. NULL,
  148957. NULL,
  148958. NULL,
  148959. 0
  148960. };
  148961. static long _huff_lengthlist__44u5__long[] = {
  148962. 3, 8,13,12,14,12,16,11,13,14, 5, 4, 5, 6, 7, 8,
  148963. 10, 9,12,15,10, 5, 5, 5, 6, 8, 9, 9,13,15,10, 5,
  148964. 5, 6, 6, 7, 8, 8,11,13,12, 7, 5, 6, 4, 6, 7, 7,
  148965. 11,14,11, 7, 7, 6, 6, 6, 7, 6,10,14,14, 9, 8, 8,
  148966. 6, 7, 7, 7,11,16,11, 8, 8, 7, 6, 6, 7, 4, 7,12,
  148967. 10,10,12,10,10, 9,10, 5, 6, 9,10,12,15,13,14,14,
  148968. 14, 8, 7, 8,
  148969. };
  148970. static static_codebook _huff_book__44u5__long = {
  148971. 2, 100,
  148972. _huff_lengthlist__44u5__long,
  148973. 0, 0, 0, 0, 0,
  148974. NULL,
  148975. NULL,
  148976. NULL,
  148977. NULL,
  148978. 0
  148979. };
  148980. static long _vq_quantlist__44u5__p1_0[] = {
  148981. 1,
  148982. 0,
  148983. 2,
  148984. };
  148985. static long _vq_lengthlist__44u5__p1_0[] = {
  148986. 1, 4, 4, 5, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  148987. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  148988. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  148989. 10,13,11,10,13,13, 4, 8, 8, 8,11,10, 8,10,10, 7,
  148990. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  148991. 12,
  148992. };
  148993. static float _vq_quantthresh__44u5__p1_0[] = {
  148994. -0.5, 0.5,
  148995. };
  148996. static long _vq_quantmap__44u5__p1_0[] = {
  148997. 1, 0, 2,
  148998. };
  148999. static encode_aux_threshmatch _vq_auxt__44u5__p1_0 = {
  149000. _vq_quantthresh__44u5__p1_0,
  149001. _vq_quantmap__44u5__p1_0,
  149002. 3,
  149003. 3
  149004. };
  149005. static static_codebook _44u5__p1_0 = {
  149006. 4, 81,
  149007. _vq_lengthlist__44u5__p1_0,
  149008. 1, -535822336, 1611661312, 2, 0,
  149009. _vq_quantlist__44u5__p1_0,
  149010. NULL,
  149011. &_vq_auxt__44u5__p1_0,
  149012. NULL,
  149013. 0
  149014. };
  149015. static long _vq_quantlist__44u5__p2_0[] = {
  149016. 1,
  149017. 0,
  149018. 2,
  149019. };
  149020. static long _vq_lengthlist__44u5__p2_0[] = {
  149021. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  149022. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  149023. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  149024. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  149025. 8, 7, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  149026. 9,
  149027. };
  149028. static float _vq_quantthresh__44u5__p2_0[] = {
  149029. -0.5, 0.5,
  149030. };
  149031. static long _vq_quantmap__44u5__p2_0[] = {
  149032. 1, 0, 2,
  149033. };
  149034. static encode_aux_threshmatch _vq_auxt__44u5__p2_0 = {
  149035. _vq_quantthresh__44u5__p2_0,
  149036. _vq_quantmap__44u5__p2_0,
  149037. 3,
  149038. 3
  149039. };
  149040. static static_codebook _44u5__p2_0 = {
  149041. 4, 81,
  149042. _vq_lengthlist__44u5__p2_0,
  149043. 1, -535822336, 1611661312, 2, 0,
  149044. _vq_quantlist__44u5__p2_0,
  149045. NULL,
  149046. &_vq_auxt__44u5__p2_0,
  149047. NULL,
  149048. 0
  149049. };
  149050. static long _vq_quantlist__44u5__p3_0[] = {
  149051. 2,
  149052. 1,
  149053. 3,
  149054. 0,
  149055. 4,
  149056. };
  149057. static long _vq_lengthlist__44u5__p3_0[] = {
  149058. 2, 4, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  149059. 10, 9,13,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  149060. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  149061. 13,14, 5, 7, 7, 9,10, 7, 9, 8,11,11, 7, 9, 9,11,
  149062. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,13,13,
  149063. 10,11,11,15,14, 9,11,11,14,14,13,14,14,17,16,12,
  149064. 13,13,15,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  149065. 11,14,15,12,14,13,16,16,13,15,14,15,17, 5, 7, 7,
  149066. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,
  149067. 14,10,11,12,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  149068. 9,11,11,13,13,12,13,13,15,16,11,12,13,15,16, 6,
  149069. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,14,11,13,
  149070. 12,16,14,11,13,13,16,17,10,12,11,15,15,11,13,13,
  149071. 16,16,11,13,13,17,16,14,15,15,17,17,14,16,16,17,
  149072. 18, 9,11,11,14,15,10,12,12,15,15,11,13,13,16,17,
  149073. 13,15,13,17,15,14,15,16,18, 0, 5, 7, 7,10,10, 7,
  149074. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  149075. 12,14,15, 6, 9, 9,12,11, 9,11,11,13,13, 8,10,11,
  149076. 12,13,11,13,13,16,15,11,12,13,14,15, 7, 9, 9,11,
  149077. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,16,
  149078. 11,13,13,15,14, 9,11,11,15,14,11,13,13,17,15,10,
  149079. 12,12,15,15,14,16,16,17,17,13,13,15,15,17,10,11,
  149080. 12,15,15,11,13,13,16,16,11,13,13,15,15,14,15,15,
  149081. 18,18,14,15,15,17,17, 8,10,10,13,13,10,12,11,15,
  149082. 15,10,11,12,15,15,14,15,15,18,18,13,14,14,18,18,
  149083. 9,11,11,15,16,11,13,13,17,17,11,13,13,16,16,15,
  149084. 15,16,17, 0,14,15,17, 0, 0, 9,11,11,15,15,10,13,
  149085. 12,18,16,11,13,13,15,16,14,16,15,20,20,14,15,16,
  149086. 17, 0,13,14,14,20,16,14,15,16,19,18,14,15,15,19,
  149087. 0,18,16, 0,20,20,16,18,18, 0, 0,12,14,14,18,18,
  149088. 13,15,14,18,16,14,15,16,18,20,16,19,16, 0,17,17,
  149089. 18,18,19, 0, 8,10,10,14,14,10,11,11,14,15,10,11,
  149090. 12,15,15,13,15,14,19,17,13,15,15,17, 0, 9,11,11,
  149091. 16,15,11,13,13,16,16,10,12,13,15,17,14,16,16,18,
  149092. 18,14,15,15,18, 0, 9,11,11,15,15,11,13,13,16,17,
  149093. 11,13,13,18,17,14,18,16,18,18,15,17,17,18, 0,12,
  149094. 14,14,18,18,14,15,15,20, 0,13,14,15,17, 0,16,18,
  149095. 17, 0, 0,16,16, 0,17,20,12,14,14,18,18,14,16,15,
  149096. 0,18,14,16,15,18, 0,16,19,17, 0, 0,17,18,16, 0,
  149097. 0,
  149098. };
  149099. static float _vq_quantthresh__44u5__p3_0[] = {
  149100. -1.5, -0.5, 0.5, 1.5,
  149101. };
  149102. static long _vq_quantmap__44u5__p3_0[] = {
  149103. 3, 1, 0, 2, 4,
  149104. };
  149105. static encode_aux_threshmatch _vq_auxt__44u5__p3_0 = {
  149106. _vq_quantthresh__44u5__p3_0,
  149107. _vq_quantmap__44u5__p3_0,
  149108. 5,
  149109. 5
  149110. };
  149111. static static_codebook _44u5__p3_0 = {
  149112. 4, 625,
  149113. _vq_lengthlist__44u5__p3_0,
  149114. 1, -533725184, 1611661312, 3, 0,
  149115. _vq_quantlist__44u5__p3_0,
  149116. NULL,
  149117. &_vq_auxt__44u5__p3_0,
  149118. NULL,
  149119. 0
  149120. };
  149121. static long _vq_quantlist__44u5__p4_0[] = {
  149122. 2,
  149123. 1,
  149124. 3,
  149125. 0,
  149126. 4,
  149127. };
  149128. static long _vq_lengthlist__44u5__p4_0[] = {
  149129. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  149130. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  149131. 8,10,10, 6, 7, 8, 9,10, 9,10,10,11,12, 9, 9,10,
  149132. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  149133. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,12,11,
  149134. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  149135. 11,12,13,14, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  149136. 10,12,12,11,12,11,14,13,11,12,12,13,13, 5, 7, 7,
  149137. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  149138. 12, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,10,11,
  149139. 8, 9, 9,11,11,10,10,11,11,13,10,11,11,12,13, 6,
  149140. 7, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  149141. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  149142. 12,13,10,11,11,13,13,12,11,13,12,15,12,13,13,14,
  149143. 15, 9,10,10,12,12, 9,11,10,13,12,10,11,11,13,13,
  149144. 11,13,11,14,12,12,13,13,14,15, 5, 7, 7, 9, 9, 7,
  149145. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  149146. 10,12,12, 6, 8, 7,10,10, 8, 9, 9,11,11, 7, 8, 9,
  149147. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  149148. 10, 8, 9, 9,11,11, 8, 9, 8,11,10,10,11,11,13,12,
  149149. 10,11,10,13,11, 9,10,10,12,12,10,11,11,13,12, 9,
  149150. 10,10,12,13,12,13,13,14,15,11,11,13,12,14, 9,10,
  149151. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,13,13,
  149152. 14,14,12,13,11,14,12, 8, 9, 9,12,12, 9,10,10,12,
  149153. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,14,13,
  149154. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  149155. 12,13,14,15,12,13,13,15,14, 9,10,10,12,12,10,11,
  149156. 10,13,12,10,11,11,12,13,12,13,12,15,13,12,13,13,
  149157. 14,15,11,12,12,14,13,11,12,12,14,15,12,13,13,15,
  149158. 14,13,12,14,12,16,13,14,14,15,15,11,11,12,14,14,
  149159. 11,12,11,14,13,12,13,13,14,15,13,14,12,16,12,14,
  149160. 14,15,16,16, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  149161. 10,12,13,11,12,12,13,13,12,12,13,14,14, 9,10,10,
  149162. 12,12,10,11,10,13,12,10,10,11,12,13,12,13,13,15,
  149163. 14,12,12,13,13,15, 9,10,10,12,13,10,11,11,12,13,
  149164. 10,11,11,13,13,12,13,13,14,15,12,13,12,15,14,11,
  149165. 12,11,14,13,12,13,13,15,14,11,11,12,13,14,14,15,
  149166. 14,16,15,13,12,14,13,16,11,12,12,13,14,12,13,13,
  149167. 14,15,11,12,11,14,14,14,14,14,15,16,13,15,12,16,
  149168. 12,
  149169. };
  149170. static float _vq_quantthresh__44u5__p4_0[] = {
  149171. -1.5, -0.5, 0.5, 1.5,
  149172. };
  149173. static long _vq_quantmap__44u5__p4_0[] = {
  149174. 3, 1, 0, 2, 4,
  149175. };
  149176. static encode_aux_threshmatch _vq_auxt__44u5__p4_0 = {
  149177. _vq_quantthresh__44u5__p4_0,
  149178. _vq_quantmap__44u5__p4_0,
  149179. 5,
  149180. 5
  149181. };
  149182. static static_codebook _44u5__p4_0 = {
  149183. 4, 625,
  149184. _vq_lengthlist__44u5__p4_0,
  149185. 1, -533725184, 1611661312, 3, 0,
  149186. _vq_quantlist__44u5__p4_0,
  149187. NULL,
  149188. &_vq_auxt__44u5__p4_0,
  149189. NULL,
  149190. 0
  149191. };
  149192. static long _vq_quantlist__44u5__p5_0[] = {
  149193. 4,
  149194. 3,
  149195. 5,
  149196. 2,
  149197. 6,
  149198. 1,
  149199. 7,
  149200. 0,
  149201. 8,
  149202. };
  149203. static long _vq_lengthlist__44u5__p5_0[] = {
  149204. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  149205. 11,10, 3, 5, 5, 7, 8, 8, 8,10,11, 6, 8, 7,10, 9,
  149206. 10,10,11,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  149207. 10,10,11,11,13,12, 8, 8, 9, 9,10,11,11,12,13,10,
  149208. 11,10,12,11,13,12,14,14,10,10,11,11,12,12,13,14,
  149209. 14,
  149210. };
  149211. static float _vq_quantthresh__44u5__p5_0[] = {
  149212. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149213. };
  149214. static long _vq_quantmap__44u5__p5_0[] = {
  149215. 7, 5, 3, 1, 0, 2, 4, 6,
  149216. 8,
  149217. };
  149218. static encode_aux_threshmatch _vq_auxt__44u5__p5_0 = {
  149219. _vq_quantthresh__44u5__p5_0,
  149220. _vq_quantmap__44u5__p5_0,
  149221. 9,
  149222. 9
  149223. };
  149224. static static_codebook _44u5__p5_0 = {
  149225. 2, 81,
  149226. _vq_lengthlist__44u5__p5_0,
  149227. 1, -531628032, 1611661312, 4, 0,
  149228. _vq_quantlist__44u5__p5_0,
  149229. NULL,
  149230. &_vq_auxt__44u5__p5_0,
  149231. NULL,
  149232. 0
  149233. };
  149234. static long _vq_quantlist__44u5__p6_0[] = {
  149235. 4,
  149236. 3,
  149237. 5,
  149238. 2,
  149239. 6,
  149240. 1,
  149241. 7,
  149242. 0,
  149243. 8,
  149244. };
  149245. static long _vq_lengthlist__44u5__p6_0[] = {
  149246. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  149247. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  149248. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  149249. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  149250. 9, 9,10,10,11,10,11,11, 9, 9, 9,10,10,11,10,11,
  149251. 11,
  149252. };
  149253. static float _vq_quantthresh__44u5__p6_0[] = {
  149254. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149255. };
  149256. static long _vq_quantmap__44u5__p6_0[] = {
  149257. 7, 5, 3, 1, 0, 2, 4, 6,
  149258. 8,
  149259. };
  149260. static encode_aux_threshmatch _vq_auxt__44u5__p6_0 = {
  149261. _vq_quantthresh__44u5__p6_0,
  149262. _vq_quantmap__44u5__p6_0,
  149263. 9,
  149264. 9
  149265. };
  149266. static static_codebook _44u5__p6_0 = {
  149267. 2, 81,
  149268. _vq_lengthlist__44u5__p6_0,
  149269. 1, -531628032, 1611661312, 4, 0,
  149270. _vq_quantlist__44u5__p6_0,
  149271. NULL,
  149272. &_vq_auxt__44u5__p6_0,
  149273. NULL,
  149274. 0
  149275. };
  149276. static long _vq_quantlist__44u5__p7_0[] = {
  149277. 1,
  149278. 0,
  149279. 2,
  149280. };
  149281. static long _vq_lengthlist__44u5__p7_0[] = {
  149282. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,11,10, 7,
  149283. 11,10, 5, 9, 9, 7,10,10, 8,10,11, 4, 9, 9, 9,12,
  149284. 12, 9,12,12, 8,12,12,11,12,12,10,12,13, 7,12,12,
  149285. 11,12,12,10,12,13, 4, 9, 9, 9,12,12, 9,12,12, 7,
  149286. 12,11,10,13,13,11,12,12, 7,12,12,10,13,13,11,12,
  149287. 12,
  149288. };
  149289. static float _vq_quantthresh__44u5__p7_0[] = {
  149290. -5.5, 5.5,
  149291. };
  149292. static long _vq_quantmap__44u5__p7_0[] = {
  149293. 1, 0, 2,
  149294. };
  149295. static encode_aux_threshmatch _vq_auxt__44u5__p7_0 = {
  149296. _vq_quantthresh__44u5__p7_0,
  149297. _vq_quantmap__44u5__p7_0,
  149298. 3,
  149299. 3
  149300. };
  149301. static static_codebook _44u5__p7_0 = {
  149302. 4, 81,
  149303. _vq_lengthlist__44u5__p7_0,
  149304. 1, -529137664, 1618345984, 2, 0,
  149305. _vq_quantlist__44u5__p7_0,
  149306. NULL,
  149307. &_vq_auxt__44u5__p7_0,
  149308. NULL,
  149309. 0
  149310. };
  149311. static long _vq_quantlist__44u5__p7_1[] = {
  149312. 5,
  149313. 4,
  149314. 6,
  149315. 3,
  149316. 7,
  149317. 2,
  149318. 8,
  149319. 1,
  149320. 9,
  149321. 0,
  149322. 10,
  149323. };
  149324. static long _vq_lengthlist__44u5__p7_1[] = {
  149325. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  149326. 8, 8, 9, 8, 8, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 8,
  149327. 9, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  149328. 8, 9, 9, 9, 9, 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  149329. 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  149330. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  149331. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  149332. 9, 9, 9, 9, 9,10,10,10,10,
  149333. };
  149334. static float _vq_quantthresh__44u5__p7_1[] = {
  149335. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149336. 3.5, 4.5,
  149337. };
  149338. static long _vq_quantmap__44u5__p7_1[] = {
  149339. 9, 7, 5, 3, 1, 0, 2, 4,
  149340. 6, 8, 10,
  149341. };
  149342. static encode_aux_threshmatch _vq_auxt__44u5__p7_1 = {
  149343. _vq_quantthresh__44u5__p7_1,
  149344. _vq_quantmap__44u5__p7_1,
  149345. 11,
  149346. 11
  149347. };
  149348. static static_codebook _44u5__p7_1 = {
  149349. 2, 121,
  149350. _vq_lengthlist__44u5__p7_1,
  149351. 1, -531365888, 1611661312, 4, 0,
  149352. _vq_quantlist__44u5__p7_1,
  149353. NULL,
  149354. &_vq_auxt__44u5__p7_1,
  149355. NULL,
  149356. 0
  149357. };
  149358. static long _vq_quantlist__44u5__p8_0[] = {
  149359. 5,
  149360. 4,
  149361. 6,
  149362. 3,
  149363. 7,
  149364. 2,
  149365. 8,
  149366. 1,
  149367. 9,
  149368. 0,
  149369. 10,
  149370. };
  149371. static long _vq_lengthlist__44u5__p8_0[] = {
  149372. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  149373. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  149374. 11, 6, 8, 7, 9, 9,10,10,11,11,13,12, 6, 8, 8, 9,
  149375. 9,10,10,11,11,12,13, 8, 9, 9,10,10,12,12,13,12,
  149376. 14,13, 8, 9, 9,10,10,12,12,13,13,14,14, 9,11,11,
  149377. 12,12,13,13,14,14,15,14, 9,11,11,12,12,13,13,14,
  149378. 14,15,14,11,12,12,13,13,14,14,15,14,15,14,11,11,
  149379. 12,13,13,14,14,14,14,15,15,
  149380. };
  149381. static float _vq_quantthresh__44u5__p8_0[] = {
  149382. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  149383. 38.5, 49.5,
  149384. };
  149385. static long _vq_quantmap__44u5__p8_0[] = {
  149386. 9, 7, 5, 3, 1, 0, 2, 4,
  149387. 6, 8, 10,
  149388. };
  149389. static encode_aux_threshmatch _vq_auxt__44u5__p8_0 = {
  149390. _vq_quantthresh__44u5__p8_0,
  149391. _vq_quantmap__44u5__p8_0,
  149392. 11,
  149393. 11
  149394. };
  149395. static static_codebook _44u5__p8_0 = {
  149396. 2, 121,
  149397. _vq_lengthlist__44u5__p8_0,
  149398. 1, -524582912, 1618345984, 4, 0,
  149399. _vq_quantlist__44u5__p8_0,
  149400. NULL,
  149401. &_vq_auxt__44u5__p8_0,
  149402. NULL,
  149403. 0
  149404. };
  149405. static long _vq_quantlist__44u5__p8_1[] = {
  149406. 5,
  149407. 4,
  149408. 6,
  149409. 3,
  149410. 7,
  149411. 2,
  149412. 8,
  149413. 1,
  149414. 9,
  149415. 0,
  149416. 10,
  149417. };
  149418. static long _vq_lengthlist__44u5__p8_1[] = {
  149419. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 6,
  149420. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  149421. 8, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 6, 6, 7, 7,
  149422. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  149423. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8,
  149424. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  149425. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  149426. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  149427. };
  149428. static float _vq_quantthresh__44u5__p8_1[] = {
  149429. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149430. 3.5, 4.5,
  149431. };
  149432. static long _vq_quantmap__44u5__p8_1[] = {
  149433. 9, 7, 5, 3, 1, 0, 2, 4,
  149434. 6, 8, 10,
  149435. };
  149436. static encode_aux_threshmatch _vq_auxt__44u5__p8_1 = {
  149437. _vq_quantthresh__44u5__p8_1,
  149438. _vq_quantmap__44u5__p8_1,
  149439. 11,
  149440. 11
  149441. };
  149442. static static_codebook _44u5__p8_1 = {
  149443. 2, 121,
  149444. _vq_lengthlist__44u5__p8_1,
  149445. 1, -531365888, 1611661312, 4, 0,
  149446. _vq_quantlist__44u5__p8_1,
  149447. NULL,
  149448. &_vq_auxt__44u5__p8_1,
  149449. NULL,
  149450. 0
  149451. };
  149452. static long _vq_quantlist__44u5__p9_0[] = {
  149453. 6,
  149454. 5,
  149455. 7,
  149456. 4,
  149457. 8,
  149458. 3,
  149459. 9,
  149460. 2,
  149461. 10,
  149462. 1,
  149463. 11,
  149464. 0,
  149465. 12,
  149466. };
  149467. static long _vq_lengthlist__44u5__p9_0[] = {
  149468. 1, 3, 2,12,10,13,13,13,13,13,13,13,13, 4, 9, 9,
  149469. 13,13,13,13,13,13,13,13,13,13, 5,10, 9,13,13,13,
  149470. 13,13,13,13,13,13,13,12,13,13,13,13,13,13,13,13,
  149471. 13,13,13,13,11,13,13,13,13,13,13,13,13,13,13,13,
  149472. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149473. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149474. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149475. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149476. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,12,12,
  149477. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  149478. 12,12,12,12,12,12,12,12,12,
  149479. };
  149480. static float _vq_quantthresh__44u5__p9_0[] = {
  149481. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  149482. 637.5, 892.5, 1147.5, 1402.5,
  149483. };
  149484. static long _vq_quantmap__44u5__p9_0[] = {
  149485. 11, 9, 7, 5, 3, 1, 0, 2,
  149486. 4, 6, 8, 10, 12,
  149487. };
  149488. static encode_aux_threshmatch _vq_auxt__44u5__p9_0 = {
  149489. _vq_quantthresh__44u5__p9_0,
  149490. _vq_quantmap__44u5__p9_0,
  149491. 13,
  149492. 13
  149493. };
  149494. static static_codebook _44u5__p9_0 = {
  149495. 2, 169,
  149496. _vq_lengthlist__44u5__p9_0,
  149497. 1, -514332672, 1627381760, 4, 0,
  149498. _vq_quantlist__44u5__p9_0,
  149499. NULL,
  149500. &_vq_auxt__44u5__p9_0,
  149501. NULL,
  149502. 0
  149503. };
  149504. static long _vq_quantlist__44u5__p9_1[] = {
  149505. 7,
  149506. 6,
  149507. 8,
  149508. 5,
  149509. 9,
  149510. 4,
  149511. 10,
  149512. 3,
  149513. 11,
  149514. 2,
  149515. 12,
  149516. 1,
  149517. 13,
  149518. 0,
  149519. 14,
  149520. };
  149521. static long _vq_lengthlist__44u5__p9_1[] = {
  149522. 1, 4, 4, 7, 7, 8, 8, 8, 7, 8, 7, 9, 8, 9, 9, 4,
  149523. 7, 6, 9, 8,10,10, 9, 8, 9, 9, 9, 9, 9, 8, 5, 6,
  149524. 6, 8, 9,10,10, 9, 9, 9,10,10,10,10,11, 7, 8, 8,
  149525. 10,10,11,11,10,10,11,11,11,12,11,11, 7, 8, 8,10,
  149526. 10,11,11,10,10,11,11,12,11,11,11, 8, 9, 9,11,11,
  149527. 12,12,11,11,12,11,12,12,12,12, 8, 9,10,11,11,12,
  149528. 12,11,11,12,12,12,12,12,12, 8, 9, 9,10,10,12,11,
  149529. 12,12,12,12,12,12,12,13, 8, 9, 9,11,11,11,11,12,
  149530. 12,12,12,13,12,13,13, 9,10,10,11,11,12,12,12,13,
  149531. 12,13,13,13,14,13, 9,10,10,11,11,12,12,12,13,13,
  149532. 12,13,13,14,13, 9,11,10,12,11,13,12,12,13,13,13,
  149533. 13,13,13,14, 9,10,10,12,12,12,12,12,13,13,13,13,
  149534. 13,14,14,10,11,11,12,12,12,13,13,13,14,14,13,14,
  149535. 14,14,10,11,11,12,12,12,12,13,12,13,14,13,14,14,
  149536. 14,
  149537. };
  149538. static float _vq_quantthresh__44u5__p9_1[] = {
  149539. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  149540. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  149541. };
  149542. static long _vq_quantmap__44u5__p9_1[] = {
  149543. 13, 11, 9, 7, 5, 3, 1, 0,
  149544. 2, 4, 6, 8, 10, 12, 14,
  149545. };
  149546. static encode_aux_threshmatch _vq_auxt__44u5__p9_1 = {
  149547. _vq_quantthresh__44u5__p9_1,
  149548. _vq_quantmap__44u5__p9_1,
  149549. 15,
  149550. 15
  149551. };
  149552. static static_codebook _44u5__p9_1 = {
  149553. 2, 225,
  149554. _vq_lengthlist__44u5__p9_1,
  149555. 1, -522338304, 1620115456, 4, 0,
  149556. _vq_quantlist__44u5__p9_1,
  149557. NULL,
  149558. &_vq_auxt__44u5__p9_1,
  149559. NULL,
  149560. 0
  149561. };
  149562. static long _vq_quantlist__44u5__p9_2[] = {
  149563. 8,
  149564. 7,
  149565. 9,
  149566. 6,
  149567. 10,
  149568. 5,
  149569. 11,
  149570. 4,
  149571. 12,
  149572. 3,
  149573. 13,
  149574. 2,
  149575. 14,
  149576. 1,
  149577. 15,
  149578. 0,
  149579. 16,
  149580. };
  149581. static long _vq_lengthlist__44u5__p9_2[] = {
  149582. 2, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149583. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  149584. 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  149585. 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  149586. 9, 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  149587. 9, 9, 9, 9, 9, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  149588. 9,10, 9,10,10,10, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  149589. 9, 9,10, 9,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  149590. 9,10, 9,10,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  149591. 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,10, 9,
  149592. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,
  149593. 9,10, 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  149594. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  149595. 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  149596. 9,10,10, 9,10,10,10,10,10,10,10,10,10,10, 9, 9,
  149597. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  149598. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  149599. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,
  149600. 10,
  149601. };
  149602. static float _vq_quantthresh__44u5__p9_2[] = {
  149603. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  149604. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  149605. };
  149606. static long _vq_quantmap__44u5__p9_2[] = {
  149607. 15, 13, 11, 9, 7, 5, 3, 1,
  149608. 0, 2, 4, 6, 8, 10, 12, 14,
  149609. 16,
  149610. };
  149611. static encode_aux_threshmatch _vq_auxt__44u5__p9_2 = {
  149612. _vq_quantthresh__44u5__p9_2,
  149613. _vq_quantmap__44u5__p9_2,
  149614. 17,
  149615. 17
  149616. };
  149617. static static_codebook _44u5__p9_2 = {
  149618. 2, 289,
  149619. _vq_lengthlist__44u5__p9_2,
  149620. 1, -529530880, 1611661312, 5, 0,
  149621. _vq_quantlist__44u5__p9_2,
  149622. NULL,
  149623. &_vq_auxt__44u5__p9_2,
  149624. NULL,
  149625. 0
  149626. };
  149627. static long _huff_lengthlist__44u5__short[] = {
  149628. 4,10,17,13,17,13,17,17,17,17, 3, 6, 8, 9,11, 9,
  149629. 15,12,16,17, 6, 5, 5, 7, 7, 8,10,11,17,17, 7, 8,
  149630. 7, 9, 9,10,13,13,17,17, 8, 6, 5, 7, 4, 7, 5, 8,
  149631. 14,17, 9, 9, 8, 9, 7, 9, 8,10,16,17,12,10, 7, 8,
  149632. 4, 7, 4, 7,16,17,12,11, 9,10, 6, 9, 5, 7,14,17,
  149633. 14,13,10,15, 4, 8, 3, 5,14,17,17,14,11,15, 6,10,
  149634. 6, 8,15,17,
  149635. };
  149636. static static_codebook _huff_book__44u5__short = {
  149637. 2, 100,
  149638. _huff_lengthlist__44u5__short,
  149639. 0, 0, 0, 0, 0,
  149640. NULL,
  149641. NULL,
  149642. NULL,
  149643. NULL,
  149644. 0
  149645. };
  149646. static long _huff_lengthlist__44u6__long[] = {
  149647. 3, 9,14,13,14,13,16,12,13,14, 5, 4, 6, 6, 8, 9,
  149648. 11,10,12,15,10, 5, 5, 6, 6, 8,10,10,13,16,10, 6,
  149649. 6, 6, 6, 8, 9, 9,12,14,13, 7, 6, 6, 4, 6, 6, 7,
  149650. 11,14,10, 7, 7, 7, 6, 6, 6, 7,10,13,15,10, 9, 8,
  149651. 5, 6, 5, 6,10,14,10, 9, 8, 8, 6, 6, 5, 4, 6,11,
  149652. 11,11,12,11,10, 9, 9, 5, 5, 9,10,12,15,13,13,13,
  149653. 13, 8, 7, 7,
  149654. };
  149655. static static_codebook _huff_book__44u6__long = {
  149656. 2, 100,
  149657. _huff_lengthlist__44u6__long,
  149658. 0, 0, 0, 0, 0,
  149659. NULL,
  149660. NULL,
  149661. NULL,
  149662. NULL,
  149663. 0
  149664. };
  149665. static long _vq_quantlist__44u6__p1_0[] = {
  149666. 1,
  149667. 0,
  149668. 2,
  149669. };
  149670. static long _vq_lengthlist__44u6__p1_0[] = {
  149671. 1, 4, 4, 4, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  149672. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  149673. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  149674. 10,13,11,10,13,13, 5, 8, 8, 8,11,10, 8,10,10, 7,
  149675. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  149676. 12,
  149677. };
  149678. static float _vq_quantthresh__44u6__p1_0[] = {
  149679. -0.5, 0.5,
  149680. };
  149681. static long _vq_quantmap__44u6__p1_0[] = {
  149682. 1, 0, 2,
  149683. };
  149684. static encode_aux_threshmatch _vq_auxt__44u6__p1_0 = {
  149685. _vq_quantthresh__44u6__p1_0,
  149686. _vq_quantmap__44u6__p1_0,
  149687. 3,
  149688. 3
  149689. };
  149690. static static_codebook _44u6__p1_0 = {
  149691. 4, 81,
  149692. _vq_lengthlist__44u6__p1_0,
  149693. 1, -535822336, 1611661312, 2, 0,
  149694. _vq_quantlist__44u6__p1_0,
  149695. NULL,
  149696. &_vq_auxt__44u6__p1_0,
  149697. NULL,
  149698. 0
  149699. };
  149700. static long _vq_quantlist__44u6__p2_0[] = {
  149701. 1,
  149702. 0,
  149703. 2,
  149704. };
  149705. static long _vq_lengthlist__44u6__p2_0[] = {
  149706. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  149707. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  149708. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 7, 7,
  149709. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  149710. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  149711. 9,
  149712. };
  149713. static float _vq_quantthresh__44u6__p2_0[] = {
  149714. -0.5, 0.5,
  149715. };
  149716. static long _vq_quantmap__44u6__p2_0[] = {
  149717. 1, 0, 2,
  149718. };
  149719. static encode_aux_threshmatch _vq_auxt__44u6__p2_0 = {
  149720. _vq_quantthresh__44u6__p2_0,
  149721. _vq_quantmap__44u6__p2_0,
  149722. 3,
  149723. 3
  149724. };
  149725. static static_codebook _44u6__p2_0 = {
  149726. 4, 81,
  149727. _vq_lengthlist__44u6__p2_0,
  149728. 1, -535822336, 1611661312, 2, 0,
  149729. _vq_quantlist__44u6__p2_0,
  149730. NULL,
  149731. &_vq_auxt__44u6__p2_0,
  149732. NULL,
  149733. 0
  149734. };
  149735. static long _vq_quantlist__44u6__p3_0[] = {
  149736. 2,
  149737. 1,
  149738. 3,
  149739. 0,
  149740. 4,
  149741. };
  149742. static long _vq_lengthlist__44u6__p3_0[] = {
  149743. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  149744. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  149745. 9,11,11, 7, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  149746. 13,14, 5, 7, 7, 9,10, 6, 9, 8,11,11, 7, 9, 9,11,
  149747. 11, 9,11,10,14,13,10,11,11,14,13, 8,10,10,13,13,
  149748. 10,11,11,15,15, 9,11,11,14,14,13,14,14,17,16,12,
  149749. 13,14,16,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  149750. 12,14,15,12,14,13,16,15,13,14,14,15,17, 5, 7, 7,
  149751. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,
  149752. 14,10,11,11,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  149753. 9,11,11,13,13,11,13,13,14,15,11,12,13,15,16, 6,
  149754. 9, 9,11,12, 8,11,10,13,12, 9,11,11,13,14,11,13,
  149755. 12,16,14,11,13,13,15,16,10,12,11,14,15,11,13,13,
  149756. 15,17,11,13,13,17,16,15,15,16,17,16,14,15,16,18,
  149757. 0, 9,11,11,14,15,10,12,12,16,15,11,13,13,16,16,
  149758. 13,15,14,18,15,14,16,16, 0, 0, 5, 7, 7,10,10, 7,
  149759. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  149760. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  149761. 12,13,11,13,13,16,15,11,12,13,14,16, 7, 9, 9,11,
  149762. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,16,15,
  149763. 11,13,12,15,15, 9,11,11,15,14,11,13,13,17,16,10,
  149764. 12,13,15,16,14,16,16, 0,18,14,14,15,15,17,10,11,
  149765. 12,15,15,11,13,13,16,16,11,13,13,16,16,14,16,16,
  149766. 19,17,14,15,15,17,17, 8,10,10,14,14,10,12,11,15,
  149767. 15,10,11,12,16,15,14,15,15,18,20,13,14,16,17,18,
  149768. 9,11,11,15,16,11,13,13,17,17,11,13,13,17,16,15,
  149769. 16,16, 0, 0,15,16,16, 0, 0, 9,11,11,15,15,10,13,
  149770. 12,17,15,11,13,13,17,16,15,17,15,20,19,15,16,16,
  149771. 19, 0,13,15,14, 0,17,14,15,16, 0,20,15,16,16, 0,
  149772. 19,17,18, 0, 0, 0,16,17,18, 0, 0,12,14,14,19,18,
  149773. 13,15,14, 0,17,14,15,16,19,19,16,18,16, 0,19,19,
  149774. 20,17,20, 0, 8,10,10,13,14,10,11,11,15,15,10,12,
  149775. 12,15,16,14,15,14,19,16,14,15,15, 0,18, 9,11,11,
  149776. 16,15,11,13,13, 0,16,11,12,13,16,17,14,16,17, 0,
  149777. 19,15,16,16,18, 0, 9,11,11,15,16,11,13,13,16,16,
  149778. 11,14,13,18,17,15,16,16,18,20,15,17,19, 0, 0,12,
  149779. 14,14,17,17,14,16,15, 0, 0,13,14,15,19, 0,16,18,
  149780. 20, 0, 0,16,16,18,18, 0,12,14,14,17,20,14,16,16,
  149781. 19, 0,14,16,14, 0,20,16,20,17, 0, 0,17, 0,15, 0,
  149782. 19,
  149783. };
  149784. static float _vq_quantthresh__44u6__p3_0[] = {
  149785. -1.5, -0.5, 0.5, 1.5,
  149786. };
  149787. static long _vq_quantmap__44u6__p3_0[] = {
  149788. 3, 1, 0, 2, 4,
  149789. };
  149790. static encode_aux_threshmatch _vq_auxt__44u6__p3_0 = {
  149791. _vq_quantthresh__44u6__p3_0,
  149792. _vq_quantmap__44u6__p3_0,
  149793. 5,
  149794. 5
  149795. };
  149796. static static_codebook _44u6__p3_0 = {
  149797. 4, 625,
  149798. _vq_lengthlist__44u6__p3_0,
  149799. 1, -533725184, 1611661312, 3, 0,
  149800. _vq_quantlist__44u6__p3_0,
  149801. NULL,
  149802. &_vq_auxt__44u6__p3_0,
  149803. NULL,
  149804. 0
  149805. };
  149806. static long _vq_quantlist__44u6__p4_0[] = {
  149807. 2,
  149808. 1,
  149809. 3,
  149810. 0,
  149811. 4,
  149812. };
  149813. static long _vq_lengthlist__44u6__p4_0[] = {
  149814. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  149815. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  149816. 8,10,10, 7, 7, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  149817. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 8,10,
  149818. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  149819. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,13,11,
  149820. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  149821. 10,12,12,11,12,11,13,12,11,12,12,13,13, 5, 7, 7,
  149822. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  149823. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  149824. 8, 9, 9,11,11,10,10,11,12,13,10,10,11,12,12, 6,
  149825. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  149826. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  149827. 13,13,10,11,11,12,13,12,12,12,13,14,12,12,13,14,
  149828. 14, 9,10,10,12,12, 9,10,10,13,12,10,11,11,13,13,
  149829. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  149830. 8, 7,10,10, 7, 8, 8,10,10, 9,10,10,12,11, 9,10,
  149831. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  149832. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  149833. 10, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,10,13,12,
  149834. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,12, 9,
  149835. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  149836. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,12,12,
  149837. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  149838. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,14,
  149839. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  149840. 12,13,14,15,12,12,13,14,14, 9,10,10,12,12, 9,11,
  149841. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,13,
  149842. 14,15,11,12,12,14,13,11,12,12,14,14,12,13,13,14,
  149843. 14,13,13,14,14,16,13,14,14,15,15,11,12,11,13,13,
  149844. 11,12,11,14,13,12,12,13,14,15,12,14,12,15,12,13,
  149845. 14,15,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  149846. 10,12,12,11,12,12,14,13,11,12,12,13,13, 9,10,10,
  149847. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  149848. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  149849. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  149850. 11,11,13,13,12,13,12,14,14,11,11,12,13,14,14,14,
  149851. 14,16,15,12,12,14,12,15,11,12,12,13,14,12,13,13,
  149852. 14,15,11,12,12,14,14,13,14,14,16,16,13,14,13,16,
  149853. 13,
  149854. };
  149855. static float _vq_quantthresh__44u6__p4_0[] = {
  149856. -1.5, -0.5, 0.5, 1.5,
  149857. };
  149858. static long _vq_quantmap__44u6__p4_0[] = {
  149859. 3, 1, 0, 2, 4,
  149860. };
  149861. static encode_aux_threshmatch _vq_auxt__44u6__p4_0 = {
  149862. _vq_quantthresh__44u6__p4_0,
  149863. _vq_quantmap__44u6__p4_0,
  149864. 5,
  149865. 5
  149866. };
  149867. static static_codebook _44u6__p4_0 = {
  149868. 4, 625,
  149869. _vq_lengthlist__44u6__p4_0,
  149870. 1, -533725184, 1611661312, 3, 0,
  149871. _vq_quantlist__44u6__p4_0,
  149872. NULL,
  149873. &_vq_auxt__44u6__p4_0,
  149874. NULL,
  149875. 0
  149876. };
  149877. static long _vq_quantlist__44u6__p5_0[] = {
  149878. 4,
  149879. 3,
  149880. 5,
  149881. 2,
  149882. 6,
  149883. 1,
  149884. 7,
  149885. 0,
  149886. 8,
  149887. };
  149888. static long _vq_lengthlist__44u6__p5_0[] = {
  149889. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  149890. 11,11, 3, 5, 5, 7, 8, 8, 8,11,11, 6, 8, 7, 9, 9,
  149891. 10, 9,12,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  149892. 10, 9,12,11,13,13, 8, 8, 9, 9,10,11,12,13,13,10,
  149893. 11,11,12,12,13,13,14,14,10,10,11,11,12,13,13,14,
  149894. 14,
  149895. };
  149896. static float _vq_quantthresh__44u6__p5_0[] = {
  149897. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149898. };
  149899. static long _vq_quantmap__44u6__p5_0[] = {
  149900. 7, 5, 3, 1, 0, 2, 4, 6,
  149901. 8,
  149902. };
  149903. static encode_aux_threshmatch _vq_auxt__44u6__p5_0 = {
  149904. _vq_quantthresh__44u6__p5_0,
  149905. _vq_quantmap__44u6__p5_0,
  149906. 9,
  149907. 9
  149908. };
  149909. static static_codebook _44u6__p5_0 = {
  149910. 2, 81,
  149911. _vq_lengthlist__44u6__p5_0,
  149912. 1, -531628032, 1611661312, 4, 0,
  149913. _vq_quantlist__44u6__p5_0,
  149914. NULL,
  149915. &_vq_auxt__44u6__p5_0,
  149916. NULL,
  149917. 0
  149918. };
  149919. static long _vq_quantlist__44u6__p6_0[] = {
  149920. 4,
  149921. 3,
  149922. 5,
  149923. 2,
  149924. 6,
  149925. 1,
  149926. 7,
  149927. 0,
  149928. 8,
  149929. };
  149930. static long _vq_lengthlist__44u6__p6_0[] = {
  149931. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  149932. 9, 9, 4, 4, 5, 6, 6, 7, 8, 9, 9, 5, 6, 6, 7, 7,
  149933. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  149934. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,10,11, 9,
  149935. 9, 9,10,10,11,11,12,11, 9, 9, 9,10,10,11,11,11,
  149936. 12,
  149937. };
  149938. static float _vq_quantthresh__44u6__p6_0[] = {
  149939. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149940. };
  149941. static long _vq_quantmap__44u6__p6_0[] = {
  149942. 7, 5, 3, 1, 0, 2, 4, 6,
  149943. 8,
  149944. };
  149945. static encode_aux_threshmatch _vq_auxt__44u6__p6_0 = {
  149946. _vq_quantthresh__44u6__p6_0,
  149947. _vq_quantmap__44u6__p6_0,
  149948. 9,
  149949. 9
  149950. };
  149951. static static_codebook _44u6__p6_0 = {
  149952. 2, 81,
  149953. _vq_lengthlist__44u6__p6_0,
  149954. 1, -531628032, 1611661312, 4, 0,
  149955. _vq_quantlist__44u6__p6_0,
  149956. NULL,
  149957. &_vq_auxt__44u6__p6_0,
  149958. NULL,
  149959. 0
  149960. };
  149961. static long _vq_quantlist__44u6__p7_0[] = {
  149962. 1,
  149963. 0,
  149964. 2,
  149965. };
  149966. static long _vq_lengthlist__44u6__p7_0[] = {
  149967. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10,10, 8,
  149968. 10,10, 5, 8, 9, 7,10,10, 7,10, 9, 4, 8, 8, 9,11,
  149969. 11, 8,11,11, 7,11,11,10,10,13,10,13,13, 7,11,11,
  149970. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 9,11,11, 7,
  149971. 11,11,10,13,13,10,12,13, 7,11,11,10,13,13, 9,13,
  149972. 10,
  149973. };
  149974. static float _vq_quantthresh__44u6__p7_0[] = {
  149975. -5.5, 5.5,
  149976. };
  149977. static long _vq_quantmap__44u6__p7_0[] = {
  149978. 1, 0, 2,
  149979. };
  149980. static encode_aux_threshmatch _vq_auxt__44u6__p7_0 = {
  149981. _vq_quantthresh__44u6__p7_0,
  149982. _vq_quantmap__44u6__p7_0,
  149983. 3,
  149984. 3
  149985. };
  149986. static static_codebook _44u6__p7_0 = {
  149987. 4, 81,
  149988. _vq_lengthlist__44u6__p7_0,
  149989. 1, -529137664, 1618345984, 2, 0,
  149990. _vq_quantlist__44u6__p7_0,
  149991. NULL,
  149992. &_vq_auxt__44u6__p7_0,
  149993. NULL,
  149994. 0
  149995. };
  149996. static long _vq_quantlist__44u6__p7_1[] = {
  149997. 5,
  149998. 4,
  149999. 6,
  150000. 3,
  150001. 7,
  150002. 2,
  150003. 8,
  150004. 1,
  150005. 9,
  150006. 0,
  150007. 10,
  150008. };
  150009. static long _vq_lengthlist__44u6__p7_1[] = {
  150010. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 6,
  150011. 8, 8, 8, 8, 8, 8, 4, 5, 5, 6, 7, 8, 8, 8, 8, 8,
  150012. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  150013. 7, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 9, 9,
  150014. 9, 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  150015. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  150016. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  150017. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  150018. };
  150019. static float _vq_quantthresh__44u6__p7_1[] = {
  150020. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150021. 3.5, 4.5,
  150022. };
  150023. static long _vq_quantmap__44u6__p7_1[] = {
  150024. 9, 7, 5, 3, 1, 0, 2, 4,
  150025. 6, 8, 10,
  150026. };
  150027. static encode_aux_threshmatch _vq_auxt__44u6__p7_1 = {
  150028. _vq_quantthresh__44u6__p7_1,
  150029. _vq_quantmap__44u6__p7_1,
  150030. 11,
  150031. 11
  150032. };
  150033. static static_codebook _44u6__p7_1 = {
  150034. 2, 121,
  150035. _vq_lengthlist__44u6__p7_1,
  150036. 1, -531365888, 1611661312, 4, 0,
  150037. _vq_quantlist__44u6__p7_1,
  150038. NULL,
  150039. &_vq_auxt__44u6__p7_1,
  150040. NULL,
  150041. 0
  150042. };
  150043. static long _vq_quantlist__44u6__p8_0[] = {
  150044. 5,
  150045. 4,
  150046. 6,
  150047. 3,
  150048. 7,
  150049. 2,
  150050. 8,
  150051. 1,
  150052. 9,
  150053. 0,
  150054. 10,
  150055. };
  150056. static long _vq_lengthlist__44u6__p8_0[] = {
  150057. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  150058. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  150059. 11, 6, 8, 8, 9, 9,10,10,11,11,12,12, 6, 8, 8, 9,
  150060. 9,10,10,11,11,12,12, 8, 9, 9,10,10,11,11,12,12,
  150061. 13,13, 8, 9, 9,10,10,11,11,12,12,13,13,10,10,10,
  150062. 11,11,13,13,13,13,15,14, 9,10,10,12,11,12,13,13,
  150063. 13,14,15,11,12,12,13,13,13,13,15,14,15,15,11,11,
  150064. 12,13,13,14,14,14,15,15,15,
  150065. };
  150066. static float _vq_quantthresh__44u6__p8_0[] = {
  150067. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  150068. 38.5, 49.5,
  150069. };
  150070. static long _vq_quantmap__44u6__p8_0[] = {
  150071. 9, 7, 5, 3, 1, 0, 2, 4,
  150072. 6, 8, 10,
  150073. };
  150074. static encode_aux_threshmatch _vq_auxt__44u6__p8_0 = {
  150075. _vq_quantthresh__44u6__p8_0,
  150076. _vq_quantmap__44u6__p8_0,
  150077. 11,
  150078. 11
  150079. };
  150080. static static_codebook _44u6__p8_0 = {
  150081. 2, 121,
  150082. _vq_lengthlist__44u6__p8_0,
  150083. 1, -524582912, 1618345984, 4, 0,
  150084. _vq_quantlist__44u6__p8_0,
  150085. NULL,
  150086. &_vq_auxt__44u6__p8_0,
  150087. NULL,
  150088. 0
  150089. };
  150090. static long _vq_quantlist__44u6__p8_1[] = {
  150091. 5,
  150092. 4,
  150093. 6,
  150094. 3,
  150095. 7,
  150096. 2,
  150097. 8,
  150098. 1,
  150099. 9,
  150100. 0,
  150101. 10,
  150102. };
  150103. static long _vq_lengthlist__44u6__p8_1[] = {
  150104. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 7,
  150105. 7, 7, 8, 7, 8, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7, 8,
  150106. 8, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 6, 7, 7,
  150107. 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  150108. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  150109. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  150110. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  150111. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  150112. };
  150113. static float _vq_quantthresh__44u6__p8_1[] = {
  150114. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150115. 3.5, 4.5,
  150116. };
  150117. static long _vq_quantmap__44u6__p8_1[] = {
  150118. 9, 7, 5, 3, 1, 0, 2, 4,
  150119. 6, 8, 10,
  150120. };
  150121. static encode_aux_threshmatch _vq_auxt__44u6__p8_1 = {
  150122. _vq_quantthresh__44u6__p8_1,
  150123. _vq_quantmap__44u6__p8_1,
  150124. 11,
  150125. 11
  150126. };
  150127. static static_codebook _44u6__p8_1 = {
  150128. 2, 121,
  150129. _vq_lengthlist__44u6__p8_1,
  150130. 1, -531365888, 1611661312, 4, 0,
  150131. _vq_quantlist__44u6__p8_1,
  150132. NULL,
  150133. &_vq_auxt__44u6__p8_1,
  150134. NULL,
  150135. 0
  150136. };
  150137. static long _vq_quantlist__44u6__p9_0[] = {
  150138. 7,
  150139. 6,
  150140. 8,
  150141. 5,
  150142. 9,
  150143. 4,
  150144. 10,
  150145. 3,
  150146. 11,
  150147. 2,
  150148. 12,
  150149. 1,
  150150. 13,
  150151. 0,
  150152. 14,
  150153. };
  150154. static long _vq_lengthlist__44u6__p9_0[] = {
  150155. 1, 3, 2, 9, 8,15,15,15,15,15,15,15,15,15,15, 4,
  150156. 8, 9,13,14,14,14,14,14,14,14,14,14,14,14, 5, 8,
  150157. 9,14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,
  150158. 14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,14,
  150159. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150160. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150161. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150162. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150163. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150164. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150165. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150166. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150167. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150168. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150169. 14,
  150170. };
  150171. static float _vq_quantthresh__44u6__p9_0[] = {
  150172. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  150173. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  150174. };
  150175. static long _vq_quantmap__44u6__p9_0[] = {
  150176. 13, 11, 9, 7, 5, 3, 1, 0,
  150177. 2, 4, 6, 8, 10, 12, 14,
  150178. };
  150179. static encode_aux_threshmatch _vq_auxt__44u6__p9_0 = {
  150180. _vq_quantthresh__44u6__p9_0,
  150181. _vq_quantmap__44u6__p9_0,
  150182. 15,
  150183. 15
  150184. };
  150185. static static_codebook _44u6__p9_0 = {
  150186. 2, 225,
  150187. _vq_lengthlist__44u6__p9_0,
  150188. 1, -514071552, 1627381760, 4, 0,
  150189. _vq_quantlist__44u6__p9_0,
  150190. NULL,
  150191. &_vq_auxt__44u6__p9_0,
  150192. NULL,
  150193. 0
  150194. };
  150195. static long _vq_quantlist__44u6__p9_1[] = {
  150196. 7,
  150197. 6,
  150198. 8,
  150199. 5,
  150200. 9,
  150201. 4,
  150202. 10,
  150203. 3,
  150204. 11,
  150205. 2,
  150206. 12,
  150207. 1,
  150208. 13,
  150209. 0,
  150210. 14,
  150211. };
  150212. static long _vq_lengthlist__44u6__p9_1[] = {
  150213. 1, 4, 4, 7, 7, 8, 9, 8, 8, 9, 8, 9, 8, 9, 9, 4,
  150214. 7, 6, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 4, 7,
  150215. 6, 9, 9,10,10, 9, 9,10,10,10,10,11,11, 7, 9, 8,
  150216. 10,10,11,11,10,10,11,11,11,11,11,11, 7, 8, 9,10,
  150217. 10,11,11,10,10,11,11,11,11,11,12, 8,10,10,11,11,
  150218. 12,12,11,11,12,12,12,12,13,12, 8,10,10,11,11,12,
  150219. 11,11,11,11,12,12,12,12,13, 8, 9, 9,11,10,11,11,
  150220. 12,12,12,12,13,12,13,12, 8, 9, 9,11,11,11,11,12,
  150221. 12,12,12,12,13,13,13, 9,10,10,11,12,12,12,12,12,
  150222. 13,13,13,13,13,13, 9,10,10,11,11,12,12,12,12,13,
  150223. 13,13,13,14,13,10,10,10,12,11,12,12,13,13,13,13,
  150224. 13,13,13,13,10,10,11,11,11,12,12,13,13,13,13,13,
  150225. 13,13,13,10,11,11,12,12,13,12,12,13,13,13,13,13,
  150226. 13,14,10,11,11,12,12,13,12,13,13,13,14,13,13,14,
  150227. 13,
  150228. };
  150229. static float _vq_quantthresh__44u6__p9_1[] = {
  150230. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  150231. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  150232. };
  150233. static long _vq_quantmap__44u6__p9_1[] = {
  150234. 13, 11, 9, 7, 5, 3, 1, 0,
  150235. 2, 4, 6, 8, 10, 12, 14,
  150236. };
  150237. static encode_aux_threshmatch _vq_auxt__44u6__p9_1 = {
  150238. _vq_quantthresh__44u6__p9_1,
  150239. _vq_quantmap__44u6__p9_1,
  150240. 15,
  150241. 15
  150242. };
  150243. static static_codebook _44u6__p9_1 = {
  150244. 2, 225,
  150245. _vq_lengthlist__44u6__p9_1,
  150246. 1, -522338304, 1620115456, 4, 0,
  150247. _vq_quantlist__44u6__p9_1,
  150248. NULL,
  150249. &_vq_auxt__44u6__p9_1,
  150250. NULL,
  150251. 0
  150252. };
  150253. static long _vq_quantlist__44u6__p9_2[] = {
  150254. 8,
  150255. 7,
  150256. 9,
  150257. 6,
  150258. 10,
  150259. 5,
  150260. 11,
  150261. 4,
  150262. 12,
  150263. 3,
  150264. 13,
  150265. 2,
  150266. 14,
  150267. 1,
  150268. 15,
  150269. 0,
  150270. 16,
  150271. };
  150272. static long _vq_lengthlist__44u6__p9_2[] = {
  150273. 3, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 8, 8, 9, 9,
  150274. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  150275. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  150276. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  150277. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  150278. 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  150279. 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  150280. 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  150281. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  150282. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9, 9, 9, 9,
  150283. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 8, 9, 9, 9, 9, 9,
  150284. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  150285. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9, 9, 9, 9, 9,
  150286. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,
  150287. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9, 9,
  150288. 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9,10, 9,
  150289. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9,10,10,
  150290. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10, 9, 9,
  150291. 10,
  150292. };
  150293. static float _vq_quantthresh__44u6__p9_2[] = {
  150294. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  150295. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  150296. };
  150297. static long _vq_quantmap__44u6__p9_2[] = {
  150298. 15, 13, 11, 9, 7, 5, 3, 1,
  150299. 0, 2, 4, 6, 8, 10, 12, 14,
  150300. 16,
  150301. };
  150302. static encode_aux_threshmatch _vq_auxt__44u6__p9_2 = {
  150303. _vq_quantthresh__44u6__p9_2,
  150304. _vq_quantmap__44u6__p9_2,
  150305. 17,
  150306. 17
  150307. };
  150308. static static_codebook _44u6__p9_2 = {
  150309. 2, 289,
  150310. _vq_lengthlist__44u6__p9_2,
  150311. 1, -529530880, 1611661312, 5, 0,
  150312. _vq_quantlist__44u6__p9_2,
  150313. NULL,
  150314. &_vq_auxt__44u6__p9_2,
  150315. NULL,
  150316. 0
  150317. };
  150318. static long _huff_lengthlist__44u6__short[] = {
  150319. 4,11,16,13,17,13,17,16,17,17, 4, 7, 9, 9,13,10,
  150320. 16,12,16,17, 7, 6, 5, 7, 8, 9,12,12,16,17, 6, 9,
  150321. 7, 9,10,10,15,15,17,17, 6, 7, 5, 7, 5, 7, 7,10,
  150322. 16,17, 7, 9, 8, 9, 8,10,11,11,15,17, 7, 7, 7, 8,
  150323. 5, 8, 8, 9,15,17, 8, 7, 9, 9, 7, 8, 7, 2, 7,15,
  150324. 14,13,13,15, 5,10, 4, 3, 6,17,17,15,13,17, 7,11,
  150325. 7, 6, 9,16,
  150326. };
  150327. static static_codebook _huff_book__44u6__short = {
  150328. 2, 100,
  150329. _huff_lengthlist__44u6__short,
  150330. 0, 0, 0, 0, 0,
  150331. NULL,
  150332. NULL,
  150333. NULL,
  150334. NULL,
  150335. 0
  150336. };
  150337. static long _huff_lengthlist__44u7__long[] = {
  150338. 3, 9,14,13,15,14,16,13,13,14, 5, 5, 7, 7, 8, 9,
  150339. 11,10,12,15,10, 6, 5, 6, 6, 9,10,10,13,16,10, 6,
  150340. 6, 6, 6, 8, 9, 9,12,15,14, 7, 6, 6, 5, 6, 6, 8,
  150341. 12,15,10, 8, 7, 7, 6, 7, 7, 7,11,13,14,10, 9, 8,
  150342. 5, 6, 4, 5, 9,12,10, 9, 9, 8, 6, 6, 5, 3, 6,11,
  150343. 12,11,12,12,10, 9, 8, 5, 5, 8,10,11,15,13,13,13,
  150344. 12, 8, 6, 7,
  150345. };
  150346. static static_codebook _huff_book__44u7__long = {
  150347. 2, 100,
  150348. _huff_lengthlist__44u7__long,
  150349. 0, 0, 0, 0, 0,
  150350. NULL,
  150351. NULL,
  150352. NULL,
  150353. NULL,
  150354. 0
  150355. };
  150356. static long _vq_quantlist__44u7__p1_0[] = {
  150357. 1,
  150358. 0,
  150359. 2,
  150360. };
  150361. static long _vq_lengthlist__44u7__p1_0[] = {
  150362. 1, 4, 4, 4, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  150363. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 5, 8, 8, 8,11,
  150364. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  150365. 10,13,12,10,13,13, 5, 8, 8, 8,11,10, 8,10,11, 7,
  150366. 10,10,10,13,13,10,12,13, 8,11,11,10,13,13,10,13,
  150367. 12,
  150368. };
  150369. static float _vq_quantthresh__44u7__p1_0[] = {
  150370. -0.5, 0.5,
  150371. };
  150372. static long _vq_quantmap__44u7__p1_0[] = {
  150373. 1, 0, 2,
  150374. };
  150375. static encode_aux_threshmatch _vq_auxt__44u7__p1_0 = {
  150376. _vq_quantthresh__44u7__p1_0,
  150377. _vq_quantmap__44u7__p1_0,
  150378. 3,
  150379. 3
  150380. };
  150381. static static_codebook _44u7__p1_0 = {
  150382. 4, 81,
  150383. _vq_lengthlist__44u7__p1_0,
  150384. 1, -535822336, 1611661312, 2, 0,
  150385. _vq_quantlist__44u7__p1_0,
  150386. NULL,
  150387. &_vq_auxt__44u7__p1_0,
  150388. NULL,
  150389. 0
  150390. };
  150391. static long _vq_quantlist__44u7__p2_0[] = {
  150392. 1,
  150393. 0,
  150394. 2,
  150395. };
  150396. static long _vq_lengthlist__44u7__p2_0[] = {
  150397. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  150398. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  150399. 7, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  150400. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  150401. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  150402. 9,
  150403. };
  150404. static float _vq_quantthresh__44u7__p2_0[] = {
  150405. -0.5, 0.5,
  150406. };
  150407. static long _vq_quantmap__44u7__p2_0[] = {
  150408. 1, 0, 2,
  150409. };
  150410. static encode_aux_threshmatch _vq_auxt__44u7__p2_0 = {
  150411. _vq_quantthresh__44u7__p2_0,
  150412. _vq_quantmap__44u7__p2_0,
  150413. 3,
  150414. 3
  150415. };
  150416. static static_codebook _44u7__p2_0 = {
  150417. 4, 81,
  150418. _vq_lengthlist__44u7__p2_0,
  150419. 1, -535822336, 1611661312, 2, 0,
  150420. _vq_quantlist__44u7__p2_0,
  150421. NULL,
  150422. &_vq_auxt__44u7__p2_0,
  150423. NULL,
  150424. 0
  150425. };
  150426. static long _vq_quantlist__44u7__p3_0[] = {
  150427. 2,
  150428. 1,
  150429. 3,
  150430. 0,
  150431. 4,
  150432. };
  150433. static long _vq_lengthlist__44u7__p3_0[] = {
  150434. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  150435. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  150436. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  150437. 13,14, 5, 7, 7, 9, 9, 7, 9, 8,11,11, 7, 9, 9,11,
  150438. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  150439. 10,11,12,15,14, 9,11,11,15,14,13,14,14,16,16,12,
  150440. 13,14,17,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  150441. 12,14,15,12,14,13,16,16,13,14,15,15,17, 5, 7, 7,
  150442. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,15,
  150443. 14,10,11,12,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  150444. 9,11,11,13,13,11,13,13,14,17,11,13,13,15,16, 6,
  150445. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  150446. 12,16,14,11,13,13,16,16,10,12,12,15,15,11,13,13,
  150447. 16,16,11,13,13,16,15,14,16,17,17,19,14,16,16,18,
  150448. 0, 9,11,11,14,15,10,13,12,16,15,11,13,13,16,16,
  150449. 14,15,14, 0,16,14,16,16,18, 0, 5, 7, 7,10,10, 7,
  150450. 9, 9,12,11, 7, 9, 9,11,12,10,11,11,15,14,10,11,
  150451. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  150452. 12,13,11,13,13,17,15,11,12,13,14,15, 7, 9, 9,11,
  150453. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,12,16,16,
  150454. 11,13,13,15,14, 9,11,11,14,15,11,13,13,16,15,10,
  150455. 12,13,16,16,15,16,16, 0, 0,14,13,15,16,18,10,11,
  150456. 11,15,15,11,13,14,16,18,11,13,13,16,15,15,16,16,
  150457. 19, 0,14,15,15,16,16, 8,10,10,13,13,10,12,11,16,
  150458. 15,10,11,11,16,15,13,15,16,18, 0,13,14,15,17,17,
  150459. 9,11,11,15,15,11,13,13,16,18,11,13,13,16,17,15,
  150460. 16,16, 0, 0,15,18,16, 0,17, 9,11,11,15,15,11,13,
  150461. 12,17,15,11,13,14,16,17,15,18,15, 0,17,15,16,16,
  150462. 18,19,13,15,14, 0,18,14,16,16,19,18,14,16,15,19,
  150463. 19,16,18,19, 0, 0,16,17, 0, 0, 0,12,14,14,17,17,
  150464. 13,16,14, 0,18,14,16,15,18, 0,16,18,16,19,17,18,
  150465. 19,17, 0, 0, 8,10,10,14,14, 9,12,11,15,15,10,11,
  150466. 12,15,17,13,15,15,18,16,14,16,15,18,17, 9,11,11,
  150467. 16,15,11,13,13, 0,16,11,12,13,16,15,15,16,16, 0,
  150468. 17,15,15,16,18,17, 9,12,11,15,17,11,13,13,16,16,
  150469. 11,14,13,16,16,15,15,16,18,19,16,18,16, 0, 0,12,
  150470. 14,14, 0,16,14,16,16, 0,18,13,14,15,16, 0,17,16,
  150471. 18, 0, 0,16,16,17,19, 0,13,14,14,17, 0,14,17,16,
  150472. 0,19,14,15,15,18,19,17,16,18, 0, 0,15,19,16, 0,
  150473. 0,
  150474. };
  150475. static float _vq_quantthresh__44u7__p3_0[] = {
  150476. -1.5, -0.5, 0.5, 1.5,
  150477. };
  150478. static long _vq_quantmap__44u7__p3_0[] = {
  150479. 3, 1, 0, 2, 4,
  150480. };
  150481. static encode_aux_threshmatch _vq_auxt__44u7__p3_0 = {
  150482. _vq_quantthresh__44u7__p3_0,
  150483. _vq_quantmap__44u7__p3_0,
  150484. 5,
  150485. 5
  150486. };
  150487. static static_codebook _44u7__p3_0 = {
  150488. 4, 625,
  150489. _vq_lengthlist__44u7__p3_0,
  150490. 1, -533725184, 1611661312, 3, 0,
  150491. _vq_quantlist__44u7__p3_0,
  150492. NULL,
  150493. &_vq_auxt__44u7__p3_0,
  150494. NULL,
  150495. 0
  150496. };
  150497. static long _vq_quantlist__44u7__p4_0[] = {
  150498. 2,
  150499. 1,
  150500. 3,
  150501. 0,
  150502. 4,
  150503. };
  150504. static long _vq_lengthlist__44u7__p4_0[] = {
  150505. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  150506. 9, 9,11,11, 8, 9, 9,10,11, 6, 7, 7, 9, 9, 7, 8,
  150507. 8,10,10, 6, 7, 8, 9,10, 9,10,10,12,12, 9, 9,10,
  150508. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  150509. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  150510. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  150511. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,11, 9,10,
  150512. 10,12,12,11,12,11,13,13,11,12,12,13,13, 6, 7, 7,
  150513. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  150514. 11, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  150515. 8, 9, 9,11,11,10,11,11,12,12,10,10,11,12,13, 6,
  150516. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  150517. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  150518. 13,13,10,11,11,13,12,12,12,13,13,14,12,12,13,14,
  150519. 14, 9,10,10,12,12, 9,10,10,12,12,10,11,11,13,13,
  150520. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  150521. 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,11, 9,10,
  150522. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  150523. 10,11,10,11,11,13,12,10,10,11,11,13, 7, 8, 8,10,
  150524. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,10,13,12,
  150525. 10,11,11,12,12, 9,10,10,12,12,10,11,11,13,12, 9,
  150526. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  150527. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,12,
  150528. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  150529. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,13,
  150530. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  150531. 13,13,14,14,12,12,13,14,14, 9,10,10,12,12, 9,11,
  150532. 10,13,12,10,10,11,12,13,11,13,12,14,13,12,12,13,
  150533. 14,14,11,12,12,13,13,11,12,13,14,14,12,13,13,14,
  150534. 14,13,13,14,14,16,13,14,14,16,16,11,11,11,13,13,
  150535. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,13,14,
  150536. 14,14,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  150537. 10,12,12,11,12,12,14,13,11,12,12,13,14, 9,10,10,
  150538. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  150539. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,12,13,
  150540. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  150541. 12,12,13,13,12,13,12,14,14,11,11,12,13,14,13,15,
  150542. 14,16,15,13,12,14,13,16,11,12,12,13,13,12,13,13,
  150543. 14,14,12,12,12,14,14,13,14,14,15,15,13,14,13,16,
  150544. 14,
  150545. };
  150546. static float _vq_quantthresh__44u7__p4_0[] = {
  150547. -1.5, -0.5, 0.5, 1.5,
  150548. };
  150549. static long _vq_quantmap__44u7__p4_0[] = {
  150550. 3, 1, 0, 2, 4,
  150551. };
  150552. static encode_aux_threshmatch _vq_auxt__44u7__p4_0 = {
  150553. _vq_quantthresh__44u7__p4_0,
  150554. _vq_quantmap__44u7__p4_0,
  150555. 5,
  150556. 5
  150557. };
  150558. static static_codebook _44u7__p4_0 = {
  150559. 4, 625,
  150560. _vq_lengthlist__44u7__p4_0,
  150561. 1, -533725184, 1611661312, 3, 0,
  150562. _vq_quantlist__44u7__p4_0,
  150563. NULL,
  150564. &_vq_auxt__44u7__p4_0,
  150565. NULL,
  150566. 0
  150567. };
  150568. static long _vq_quantlist__44u7__p5_0[] = {
  150569. 4,
  150570. 3,
  150571. 5,
  150572. 2,
  150573. 6,
  150574. 1,
  150575. 7,
  150576. 0,
  150577. 8,
  150578. };
  150579. static long _vq_lengthlist__44u7__p5_0[] = {
  150580. 2, 3, 3, 6, 6, 7, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  150581. 11,11, 3, 5, 5, 7, 7, 8, 9,11,11, 6, 8, 7, 9, 9,
  150582. 10,10,12,12, 6, 7, 8, 9,10,10,10,12,12, 8, 8, 8,
  150583. 10,10,12,11,13,13, 8, 8, 9,10,10,11,11,13,13,10,
  150584. 11,11,12,12,13,13,14,14,10,11,11,12,12,13,13,14,
  150585. 14,
  150586. };
  150587. static float _vq_quantthresh__44u7__p5_0[] = {
  150588. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150589. };
  150590. static long _vq_quantmap__44u7__p5_0[] = {
  150591. 7, 5, 3, 1, 0, 2, 4, 6,
  150592. 8,
  150593. };
  150594. static encode_aux_threshmatch _vq_auxt__44u7__p5_0 = {
  150595. _vq_quantthresh__44u7__p5_0,
  150596. _vq_quantmap__44u7__p5_0,
  150597. 9,
  150598. 9
  150599. };
  150600. static static_codebook _44u7__p5_0 = {
  150601. 2, 81,
  150602. _vq_lengthlist__44u7__p5_0,
  150603. 1, -531628032, 1611661312, 4, 0,
  150604. _vq_quantlist__44u7__p5_0,
  150605. NULL,
  150606. &_vq_auxt__44u7__p5_0,
  150607. NULL,
  150608. 0
  150609. };
  150610. static long _vq_quantlist__44u7__p6_0[] = {
  150611. 4,
  150612. 3,
  150613. 5,
  150614. 2,
  150615. 6,
  150616. 1,
  150617. 7,
  150618. 0,
  150619. 8,
  150620. };
  150621. static long _vq_lengthlist__44u7__p6_0[] = {
  150622. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 8, 7,
  150623. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  150624. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  150625. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,11,11, 9,
  150626. 9, 9,10,10,11,10,12,11, 9, 9, 9,10,10,11,11,11,
  150627. 12,
  150628. };
  150629. static float _vq_quantthresh__44u7__p6_0[] = {
  150630. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150631. };
  150632. static long _vq_quantmap__44u7__p6_0[] = {
  150633. 7, 5, 3, 1, 0, 2, 4, 6,
  150634. 8,
  150635. };
  150636. static encode_aux_threshmatch _vq_auxt__44u7__p6_0 = {
  150637. _vq_quantthresh__44u7__p6_0,
  150638. _vq_quantmap__44u7__p6_0,
  150639. 9,
  150640. 9
  150641. };
  150642. static static_codebook _44u7__p6_0 = {
  150643. 2, 81,
  150644. _vq_lengthlist__44u7__p6_0,
  150645. 1, -531628032, 1611661312, 4, 0,
  150646. _vq_quantlist__44u7__p6_0,
  150647. NULL,
  150648. &_vq_auxt__44u7__p6_0,
  150649. NULL,
  150650. 0
  150651. };
  150652. static long _vq_quantlist__44u7__p7_0[] = {
  150653. 1,
  150654. 0,
  150655. 2,
  150656. };
  150657. static long _vq_lengthlist__44u7__p7_0[] = {
  150658. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 8, 9, 9, 7,
  150659. 10,10, 5, 8, 9, 7, 9,10, 8, 9, 9, 4, 9, 9, 9,11,
  150660. 10, 8,10,10, 7,11,10,10,10,12,10,12,12, 7,10,10,
  150661. 10,12,11,10,12,12, 5, 9, 9, 8,10,10, 9,11,11, 7,
  150662. 11,10,10,12,12,10,11,12, 7,10,11,10,12,12,10,12,
  150663. 10,
  150664. };
  150665. static float _vq_quantthresh__44u7__p7_0[] = {
  150666. -5.5, 5.5,
  150667. };
  150668. static long _vq_quantmap__44u7__p7_0[] = {
  150669. 1, 0, 2,
  150670. };
  150671. static encode_aux_threshmatch _vq_auxt__44u7__p7_0 = {
  150672. _vq_quantthresh__44u7__p7_0,
  150673. _vq_quantmap__44u7__p7_0,
  150674. 3,
  150675. 3
  150676. };
  150677. static static_codebook _44u7__p7_0 = {
  150678. 4, 81,
  150679. _vq_lengthlist__44u7__p7_0,
  150680. 1, -529137664, 1618345984, 2, 0,
  150681. _vq_quantlist__44u7__p7_0,
  150682. NULL,
  150683. &_vq_auxt__44u7__p7_0,
  150684. NULL,
  150685. 0
  150686. };
  150687. static long _vq_quantlist__44u7__p7_1[] = {
  150688. 5,
  150689. 4,
  150690. 6,
  150691. 3,
  150692. 7,
  150693. 2,
  150694. 8,
  150695. 1,
  150696. 9,
  150697. 0,
  150698. 10,
  150699. };
  150700. static long _vq_lengthlist__44u7__p7_1[] = {
  150701. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6,
  150702. 8, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6, 7, 8, 8, 8, 8,
  150703. 8, 6, 7, 6, 7, 7, 8, 8, 9, 9, 9, 9, 6, 6, 7, 7,
  150704. 7, 8, 8, 9, 9, 9, 9, 7, 8, 7, 8, 8, 9, 9, 9, 9,
  150705. 9, 9, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  150706. 9, 9, 9, 9,10, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  150707. 9, 9,10, 8, 8, 8, 9, 9, 9, 9,10, 9,10,10, 8, 8,
  150708. 8, 9, 9, 9, 9, 9,10,10,10,
  150709. };
  150710. static float _vq_quantthresh__44u7__p7_1[] = {
  150711. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150712. 3.5, 4.5,
  150713. };
  150714. static long _vq_quantmap__44u7__p7_1[] = {
  150715. 9, 7, 5, 3, 1, 0, 2, 4,
  150716. 6, 8, 10,
  150717. };
  150718. static encode_aux_threshmatch _vq_auxt__44u7__p7_1 = {
  150719. _vq_quantthresh__44u7__p7_1,
  150720. _vq_quantmap__44u7__p7_1,
  150721. 11,
  150722. 11
  150723. };
  150724. static static_codebook _44u7__p7_1 = {
  150725. 2, 121,
  150726. _vq_lengthlist__44u7__p7_1,
  150727. 1, -531365888, 1611661312, 4, 0,
  150728. _vq_quantlist__44u7__p7_1,
  150729. NULL,
  150730. &_vq_auxt__44u7__p7_1,
  150731. NULL,
  150732. 0
  150733. };
  150734. static long _vq_quantlist__44u7__p8_0[] = {
  150735. 5,
  150736. 4,
  150737. 6,
  150738. 3,
  150739. 7,
  150740. 2,
  150741. 8,
  150742. 1,
  150743. 9,
  150744. 0,
  150745. 10,
  150746. };
  150747. static long _vq_lengthlist__44u7__p8_0[] = {
  150748. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  150749. 9, 9,11,10,12,12, 5, 6, 5, 7, 7, 9, 9,10,11,12,
  150750. 12, 6, 7, 7, 8, 8,10,10,11,11,13,13, 6, 7, 7, 8,
  150751. 8,10,10,11,12,13,13, 8, 9, 9,10,10,11,11,12,12,
  150752. 14,14, 8, 9, 9,10,10,11,11,12,12,14,14,10,10,10,
  150753. 11,11,13,12,14,14,15,15,10,10,10,12,12,13,13,14,
  150754. 14,15,15,11,12,12,13,13,14,14,15,14,16,15,11,12,
  150755. 12,13,13,14,14,15,15,15,16,
  150756. };
  150757. static float _vq_quantthresh__44u7__p8_0[] = {
  150758. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  150759. 38.5, 49.5,
  150760. };
  150761. static long _vq_quantmap__44u7__p8_0[] = {
  150762. 9, 7, 5, 3, 1, 0, 2, 4,
  150763. 6, 8, 10,
  150764. };
  150765. static encode_aux_threshmatch _vq_auxt__44u7__p8_0 = {
  150766. _vq_quantthresh__44u7__p8_0,
  150767. _vq_quantmap__44u7__p8_0,
  150768. 11,
  150769. 11
  150770. };
  150771. static static_codebook _44u7__p8_0 = {
  150772. 2, 121,
  150773. _vq_lengthlist__44u7__p8_0,
  150774. 1, -524582912, 1618345984, 4, 0,
  150775. _vq_quantlist__44u7__p8_0,
  150776. NULL,
  150777. &_vq_auxt__44u7__p8_0,
  150778. NULL,
  150779. 0
  150780. };
  150781. static long _vq_quantlist__44u7__p8_1[] = {
  150782. 5,
  150783. 4,
  150784. 6,
  150785. 3,
  150786. 7,
  150787. 2,
  150788. 8,
  150789. 1,
  150790. 9,
  150791. 0,
  150792. 10,
  150793. };
  150794. static long _vq_lengthlist__44u7__p8_1[] = {
  150795. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  150796. 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  150797. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  150798. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  150799. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  150800. 7, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  150801. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  150802. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  150803. };
  150804. static float _vq_quantthresh__44u7__p8_1[] = {
  150805. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150806. 3.5, 4.5,
  150807. };
  150808. static long _vq_quantmap__44u7__p8_1[] = {
  150809. 9, 7, 5, 3, 1, 0, 2, 4,
  150810. 6, 8, 10,
  150811. };
  150812. static encode_aux_threshmatch _vq_auxt__44u7__p8_1 = {
  150813. _vq_quantthresh__44u7__p8_1,
  150814. _vq_quantmap__44u7__p8_1,
  150815. 11,
  150816. 11
  150817. };
  150818. static static_codebook _44u7__p8_1 = {
  150819. 2, 121,
  150820. _vq_lengthlist__44u7__p8_1,
  150821. 1, -531365888, 1611661312, 4, 0,
  150822. _vq_quantlist__44u7__p8_1,
  150823. NULL,
  150824. &_vq_auxt__44u7__p8_1,
  150825. NULL,
  150826. 0
  150827. };
  150828. static long _vq_quantlist__44u7__p9_0[] = {
  150829. 5,
  150830. 4,
  150831. 6,
  150832. 3,
  150833. 7,
  150834. 2,
  150835. 8,
  150836. 1,
  150837. 9,
  150838. 0,
  150839. 10,
  150840. };
  150841. static long _vq_lengthlist__44u7__p9_0[] = {
  150842. 1, 3, 3,10,10,10,10,10,10,10,10, 4,10,10,10,10,
  150843. 10,10,10,10,10,10, 4,10,10,10,10,10,10,10,10,10,
  150844. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150845. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150846. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150847. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150848. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  150849. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  150850. };
  150851. static float _vq_quantthresh__44u7__p9_0[] = {
  150852. -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5, 1592.5,
  150853. 2229.5, 2866.5,
  150854. };
  150855. static long _vq_quantmap__44u7__p9_0[] = {
  150856. 9, 7, 5, 3, 1, 0, 2, 4,
  150857. 6, 8, 10,
  150858. };
  150859. static encode_aux_threshmatch _vq_auxt__44u7__p9_0 = {
  150860. _vq_quantthresh__44u7__p9_0,
  150861. _vq_quantmap__44u7__p9_0,
  150862. 11,
  150863. 11
  150864. };
  150865. static static_codebook _44u7__p9_0 = {
  150866. 2, 121,
  150867. _vq_lengthlist__44u7__p9_0,
  150868. 1, -512171520, 1630791680, 4, 0,
  150869. _vq_quantlist__44u7__p9_0,
  150870. NULL,
  150871. &_vq_auxt__44u7__p9_0,
  150872. NULL,
  150873. 0
  150874. };
  150875. static long _vq_quantlist__44u7__p9_1[] = {
  150876. 6,
  150877. 5,
  150878. 7,
  150879. 4,
  150880. 8,
  150881. 3,
  150882. 9,
  150883. 2,
  150884. 10,
  150885. 1,
  150886. 11,
  150887. 0,
  150888. 12,
  150889. };
  150890. static long _vq_lengthlist__44u7__p9_1[] = {
  150891. 1, 4, 4, 6, 5, 8, 6, 9, 8,10, 9,11,10, 4, 6, 6,
  150892. 8, 8, 9, 9,11,10,11,11,11,11, 4, 6, 6, 8, 8,10,
  150893. 9,11,11,11,11,11,12, 6, 8, 8,10,10,11,11,12,12,
  150894. 13,12,13,13, 6, 8, 8,10,10,11,11,12,12,12,13,14,
  150895. 13, 8,10,10,11,11,12,13,14,14,14,14,15,15, 8,10,
  150896. 10,11,12,12,13,13,14,14,14,14,15, 9,11,11,13,13,
  150897. 14,14,15,14,16,15,17,15, 9,11,11,12,13,14,14,15,
  150898. 14,15,15,15,16,10,12,12,13,14,15,15,15,15,16,17,
  150899. 16,17,10,13,12,13,14,14,16,16,16,16,15,16,17,11,
  150900. 13,13,14,15,14,17,15,16,17,17,17,17,11,13,13,14,
  150901. 15,15,15,15,17,17,16,17,16,
  150902. };
  150903. static float _vq_quantthresh__44u7__p9_1[] = {
  150904. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  150905. 122.5, 171.5, 220.5, 269.5,
  150906. };
  150907. static long _vq_quantmap__44u7__p9_1[] = {
  150908. 11, 9, 7, 5, 3, 1, 0, 2,
  150909. 4, 6, 8, 10, 12,
  150910. };
  150911. static encode_aux_threshmatch _vq_auxt__44u7__p9_1 = {
  150912. _vq_quantthresh__44u7__p9_1,
  150913. _vq_quantmap__44u7__p9_1,
  150914. 13,
  150915. 13
  150916. };
  150917. static static_codebook _44u7__p9_1 = {
  150918. 2, 169,
  150919. _vq_lengthlist__44u7__p9_1,
  150920. 1, -518889472, 1622704128, 4, 0,
  150921. _vq_quantlist__44u7__p9_1,
  150922. NULL,
  150923. &_vq_auxt__44u7__p9_1,
  150924. NULL,
  150925. 0
  150926. };
  150927. static long _vq_quantlist__44u7__p9_2[] = {
  150928. 24,
  150929. 23,
  150930. 25,
  150931. 22,
  150932. 26,
  150933. 21,
  150934. 27,
  150935. 20,
  150936. 28,
  150937. 19,
  150938. 29,
  150939. 18,
  150940. 30,
  150941. 17,
  150942. 31,
  150943. 16,
  150944. 32,
  150945. 15,
  150946. 33,
  150947. 14,
  150948. 34,
  150949. 13,
  150950. 35,
  150951. 12,
  150952. 36,
  150953. 11,
  150954. 37,
  150955. 10,
  150956. 38,
  150957. 9,
  150958. 39,
  150959. 8,
  150960. 40,
  150961. 7,
  150962. 41,
  150963. 6,
  150964. 42,
  150965. 5,
  150966. 43,
  150967. 4,
  150968. 44,
  150969. 3,
  150970. 45,
  150971. 2,
  150972. 46,
  150973. 1,
  150974. 47,
  150975. 0,
  150976. 48,
  150977. };
  150978. static long _vq_lengthlist__44u7__p9_2[] = {
  150979. 2, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  150980. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  150981. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  150982. 8,
  150983. };
  150984. static float _vq_quantthresh__44u7__p9_2[] = {
  150985. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  150986. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  150987. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  150988. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  150989. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  150990. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  150991. };
  150992. static long _vq_quantmap__44u7__p9_2[] = {
  150993. 47, 45, 43, 41, 39, 37, 35, 33,
  150994. 31, 29, 27, 25, 23, 21, 19, 17,
  150995. 15, 13, 11, 9, 7, 5, 3, 1,
  150996. 0, 2, 4, 6, 8, 10, 12, 14,
  150997. 16, 18, 20, 22, 24, 26, 28, 30,
  150998. 32, 34, 36, 38, 40, 42, 44, 46,
  150999. 48,
  151000. };
  151001. static encode_aux_threshmatch _vq_auxt__44u7__p9_2 = {
  151002. _vq_quantthresh__44u7__p9_2,
  151003. _vq_quantmap__44u7__p9_2,
  151004. 49,
  151005. 49
  151006. };
  151007. static static_codebook _44u7__p9_2 = {
  151008. 1, 49,
  151009. _vq_lengthlist__44u7__p9_2,
  151010. 1, -526909440, 1611661312, 6, 0,
  151011. _vq_quantlist__44u7__p9_2,
  151012. NULL,
  151013. &_vq_auxt__44u7__p9_2,
  151014. NULL,
  151015. 0
  151016. };
  151017. static long _huff_lengthlist__44u7__short[] = {
  151018. 5,12,17,16,16,17,17,17,17,17, 4, 7,11,11,12, 9,
  151019. 17,10,17,17, 7, 7, 8, 9, 7, 9,11,10,15,17, 7, 9,
  151020. 10,11,10,12,14,12,16,17, 7, 8, 5, 7, 4, 7, 7, 8,
  151021. 16,16, 6,10, 9,10, 7,10,11,11,16,17, 6, 8, 8, 9,
  151022. 5, 7, 5, 8,16,17, 5, 5, 8, 7, 6, 7, 7, 6, 6,14,
  151023. 12,10,12,11, 7,11, 4, 4, 2, 7,17,15,15,15, 8,15,
  151024. 6, 8, 5, 9,
  151025. };
  151026. static static_codebook _huff_book__44u7__short = {
  151027. 2, 100,
  151028. _huff_lengthlist__44u7__short,
  151029. 0, 0, 0, 0, 0,
  151030. NULL,
  151031. NULL,
  151032. NULL,
  151033. NULL,
  151034. 0
  151035. };
  151036. static long _huff_lengthlist__44u8__long[] = {
  151037. 3, 9,13,14,14,15,14,14,15,15, 5, 4, 6, 8,10,12,
  151038. 12,14,15,15, 9, 5, 4, 5, 8,10,11,13,16,16,10, 7,
  151039. 4, 3, 5, 7, 9,11,13,13,10, 9, 7, 4, 4, 6, 8,10,
  151040. 12,14,13,11, 9, 6, 5, 5, 6, 8,12,14,13,11,10, 8,
  151041. 7, 6, 6, 7,10,14,13,11,12,10, 8, 7, 6, 6, 9,13,
  151042. 12,11,14,12,11, 9, 8, 7, 9,11,11,12,14,13,14,11,
  151043. 10, 8, 8, 9,
  151044. };
  151045. static static_codebook _huff_book__44u8__long = {
  151046. 2, 100,
  151047. _huff_lengthlist__44u8__long,
  151048. 0, 0, 0, 0, 0,
  151049. NULL,
  151050. NULL,
  151051. NULL,
  151052. NULL,
  151053. 0
  151054. };
  151055. static long _huff_lengthlist__44u8__short[] = {
  151056. 6,14,18,18,17,17,17,17,17,17, 4, 7, 9, 9,10,13,
  151057. 15,17,17,17, 6, 7, 5, 6, 8,11,16,17,16,17, 5, 7,
  151058. 5, 4, 6,10,14,17,17,17, 6, 6, 6, 5, 7,10,13,16,
  151059. 17,17, 7, 6, 7, 7, 7, 8, 7,10,15,16,12, 9, 9, 6,
  151060. 6, 5, 3, 5,11,15,14,14,13, 5, 5, 7, 3, 4, 8,15,
  151061. 17,17,13, 7, 7,10, 6, 6,10,15,17,17,16,10,11,14,
  151062. 10,10,15,17,
  151063. };
  151064. static static_codebook _huff_book__44u8__short = {
  151065. 2, 100,
  151066. _huff_lengthlist__44u8__short,
  151067. 0, 0, 0, 0, 0,
  151068. NULL,
  151069. NULL,
  151070. NULL,
  151071. NULL,
  151072. 0
  151073. };
  151074. static long _vq_quantlist__44u8_p1_0[] = {
  151075. 1,
  151076. 0,
  151077. 2,
  151078. };
  151079. static long _vq_lengthlist__44u8_p1_0[] = {
  151080. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 8, 9, 9, 7,
  151081. 9, 9, 5, 7, 7, 7, 9, 9, 8, 9, 9, 5, 7, 7, 7, 9,
  151082. 9, 7, 9, 9, 7, 9, 9, 9,10,11, 9,11,10, 7, 9, 9,
  151083. 9,11,10, 9,10,11, 5, 7, 7, 7, 9, 9, 7, 9, 9, 7,
  151084. 9, 9, 9,11,10, 9,10,10, 8, 9, 9, 9,11,11, 9,11,
  151085. 10,
  151086. };
  151087. static float _vq_quantthresh__44u8_p1_0[] = {
  151088. -0.5, 0.5,
  151089. };
  151090. static long _vq_quantmap__44u8_p1_0[] = {
  151091. 1, 0, 2,
  151092. };
  151093. static encode_aux_threshmatch _vq_auxt__44u8_p1_0 = {
  151094. _vq_quantthresh__44u8_p1_0,
  151095. _vq_quantmap__44u8_p1_0,
  151096. 3,
  151097. 3
  151098. };
  151099. static static_codebook _44u8_p1_0 = {
  151100. 4, 81,
  151101. _vq_lengthlist__44u8_p1_0,
  151102. 1, -535822336, 1611661312, 2, 0,
  151103. _vq_quantlist__44u8_p1_0,
  151104. NULL,
  151105. &_vq_auxt__44u8_p1_0,
  151106. NULL,
  151107. 0
  151108. };
  151109. static long _vq_quantlist__44u8_p2_0[] = {
  151110. 2,
  151111. 1,
  151112. 3,
  151113. 0,
  151114. 4,
  151115. };
  151116. static long _vq_lengthlist__44u8_p2_0[] = {
  151117. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  151118. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  151119. 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,10,
  151120. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  151121. 10, 9,10, 9,12,11, 9,10,10,12,12, 8, 9, 9,12,11,
  151122. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,14,11,
  151123. 11,12,13,14, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  151124. 10,12,12,11,12,11,13,13,11,12,12,14,14, 5, 7, 7,
  151125. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  151126. 12, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  151127. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,12,13, 6,
  151128. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  151129. 10,13,12,10,11,11,13,13, 9,10,10,12,12,10,11,11,
  151130. 13,13,10,11,11,13,13,12,12,13,13,14,12,13,13,14,
  151131. 14, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  151132. 11,13,12,14,13,12,13,13,14,14, 5, 7, 7, 9, 9, 7,
  151133. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  151134. 10,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  151135. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  151136. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  151137. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  151138. 10,11,12,13,12,13,13,14,14,12,12,13,13,14, 9,10,
  151139. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,13,
  151140. 15,14,12,13,13,14,13, 8, 9, 9,11,11, 9,10,10,12,
  151141. 12, 9,10,10,12,12,12,12,12,14,13,11,12,12,14,14,
  151142. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  151143. 13,13,14,15,12,13,13,14,15, 9,10,10,12,12,10,11,
  151144. 10,13,12,10,11,11,13,13,12,13,12,15,14,12,13,13,
  151145. 14,15,11,12,12,14,14,12,13,13,14,14,12,13,13,15,
  151146. 14,14,14,14,14,16,14,14,15,16,16,11,12,12,14,14,
  151147. 11,12,12,14,14,12,13,13,14,15,13,14,13,16,14,14,
  151148. 14,14,16,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  151149. 10,12,12,11,12,12,14,13,11,12,12,14,14, 9,10,10,
  151150. 12,12,10,11,11,13,13,10,10,11,12,13,12,13,13,15,
  151151. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  151152. 10,11,11,13,13,12,13,13,14,14,12,13,13,15,14,11,
  151153. 12,12,14,13,12,13,13,15,14,11,12,12,13,14,14,15,
  151154. 14,16,15,13,13,14,13,16,11,12,12,14,14,12,13,13,
  151155. 14,15,12,13,12,15,14,14,14,14,16,15,14,15,13,16,
  151156. 14,
  151157. };
  151158. static float _vq_quantthresh__44u8_p2_0[] = {
  151159. -1.5, -0.5, 0.5, 1.5,
  151160. };
  151161. static long _vq_quantmap__44u8_p2_0[] = {
  151162. 3, 1, 0, 2, 4,
  151163. };
  151164. static encode_aux_threshmatch _vq_auxt__44u8_p2_0 = {
  151165. _vq_quantthresh__44u8_p2_0,
  151166. _vq_quantmap__44u8_p2_0,
  151167. 5,
  151168. 5
  151169. };
  151170. static static_codebook _44u8_p2_0 = {
  151171. 4, 625,
  151172. _vq_lengthlist__44u8_p2_0,
  151173. 1, -533725184, 1611661312, 3, 0,
  151174. _vq_quantlist__44u8_p2_0,
  151175. NULL,
  151176. &_vq_auxt__44u8_p2_0,
  151177. NULL,
  151178. 0
  151179. };
  151180. static long _vq_quantlist__44u8_p3_0[] = {
  151181. 4,
  151182. 3,
  151183. 5,
  151184. 2,
  151185. 6,
  151186. 1,
  151187. 7,
  151188. 0,
  151189. 8,
  151190. };
  151191. static long _vq_lengthlist__44u8_p3_0[] = {
  151192. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  151193. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  151194. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  151195. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  151196. 9, 9,10,10,11,10,12,11, 9, 9, 9, 9,10,11,11,11,
  151197. 12,
  151198. };
  151199. static float _vq_quantthresh__44u8_p3_0[] = {
  151200. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  151201. };
  151202. static long _vq_quantmap__44u8_p3_0[] = {
  151203. 7, 5, 3, 1, 0, 2, 4, 6,
  151204. 8,
  151205. };
  151206. static encode_aux_threshmatch _vq_auxt__44u8_p3_0 = {
  151207. _vq_quantthresh__44u8_p3_0,
  151208. _vq_quantmap__44u8_p3_0,
  151209. 9,
  151210. 9
  151211. };
  151212. static static_codebook _44u8_p3_0 = {
  151213. 2, 81,
  151214. _vq_lengthlist__44u8_p3_0,
  151215. 1, -531628032, 1611661312, 4, 0,
  151216. _vq_quantlist__44u8_p3_0,
  151217. NULL,
  151218. &_vq_auxt__44u8_p3_0,
  151219. NULL,
  151220. 0
  151221. };
  151222. static long _vq_quantlist__44u8_p4_0[] = {
  151223. 8,
  151224. 7,
  151225. 9,
  151226. 6,
  151227. 10,
  151228. 5,
  151229. 11,
  151230. 4,
  151231. 12,
  151232. 3,
  151233. 13,
  151234. 2,
  151235. 14,
  151236. 1,
  151237. 15,
  151238. 0,
  151239. 16,
  151240. };
  151241. static long _vq_lengthlist__44u8_p4_0[] = {
  151242. 4, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,11,11,11,
  151243. 11, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  151244. 12,12, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  151245. 11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  151246. 11,11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,
  151247. 10,11,11,12,12, 7, 7, 7, 8, 8, 9, 8,10, 9,10, 9,
  151248. 11,10,12,11,13,12, 7, 7, 7, 8, 8, 8, 9, 9,10, 9,
  151249. 10,10,11,11,12,12,13, 8, 8, 8, 9, 9, 9, 9,10,10,
  151250. 11,10,11,11,12,12,13,13, 8, 8, 8, 9, 9, 9,10,10,
  151251. 10,10,11,11,11,12,12,12,13, 8, 9, 9, 9, 9,10, 9,
  151252. 11,10,11,11,12,11,13,12,13,13, 8, 9, 9, 9, 9, 9,
  151253. 10,10,11,11,11,11,12,12,13,13,13,10,10,10,10,10,
  151254. 11,10,11,11,12,11,13,12,13,13,14,13,10,10,10,10,
  151255. 10,10,11,11,11,11,12,12,13,13,13,13,14,11,11,11,
  151256. 11,11,12,11,12,12,13,12,13,13,14,13,14,14,11,11,
  151257. 11,11,11,11,12,12,12,12,13,13,13,13,14,14,14,11,
  151258. 12,12,12,12,13,12,13,12,13,13,14,13,14,14,14,14,
  151259. 11,12,12,12,12,12,12,13,13,13,13,13,14,14,14,14,
  151260. 14,
  151261. };
  151262. static float _vq_quantthresh__44u8_p4_0[] = {
  151263. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151264. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151265. };
  151266. static long _vq_quantmap__44u8_p4_0[] = {
  151267. 15, 13, 11, 9, 7, 5, 3, 1,
  151268. 0, 2, 4, 6, 8, 10, 12, 14,
  151269. 16,
  151270. };
  151271. static encode_aux_threshmatch _vq_auxt__44u8_p4_0 = {
  151272. _vq_quantthresh__44u8_p4_0,
  151273. _vq_quantmap__44u8_p4_0,
  151274. 17,
  151275. 17
  151276. };
  151277. static static_codebook _44u8_p4_0 = {
  151278. 2, 289,
  151279. _vq_lengthlist__44u8_p4_0,
  151280. 1, -529530880, 1611661312, 5, 0,
  151281. _vq_quantlist__44u8_p4_0,
  151282. NULL,
  151283. &_vq_auxt__44u8_p4_0,
  151284. NULL,
  151285. 0
  151286. };
  151287. static long _vq_quantlist__44u8_p5_0[] = {
  151288. 1,
  151289. 0,
  151290. 2,
  151291. };
  151292. static long _vq_lengthlist__44u8_p5_0[] = {
  151293. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  151294. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  151295. 10, 8,10,10, 7,10,10, 9,10,12, 9,12,11, 7,10,10,
  151296. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  151297. 10,10, 9,11,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  151298. 10,
  151299. };
  151300. static float _vq_quantthresh__44u8_p5_0[] = {
  151301. -5.5, 5.5,
  151302. };
  151303. static long _vq_quantmap__44u8_p5_0[] = {
  151304. 1, 0, 2,
  151305. };
  151306. static encode_aux_threshmatch _vq_auxt__44u8_p5_0 = {
  151307. _vq_quantthresh__44u8_p5_0,
  151308. _vq_quantmap__44u8_p5_0,
  151309. 3,
  151310. 3
  151311. };
  151312. static static_codebook _44u8_p5_0 = {
  151313. 4, 81,
  151314. _vq_lengthlist__44u8_p5_0,
  151315. 1, -529137664, 1618345984, 2, 0,
  151316. _vq_quantlist__44u8_p5_0,
  151317. NULL,
  151318. &_vq_auxt__44u8_p5_0,
  151319. NULL,
  151320. 0
  151321. };
  151322. static long _vq_quantlist__44u8_p5_1[] = {
  151323. 5,
  151324. 4,
  151325. 6,
  151326. 3,
  151327. 7,
  151328. 2,
  151329. 8,
  151330. 1,
  151331. 9,
  151332. 0,
  151333. 10,
  151334. };
  151335. static long _vq_lengthlist__44u8_p5_1[] = {
  151336. 4, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 5, 5, 6, 6,
  151337. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 7, 8, 8,
  151338. 8, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 6, 6, 6, 7,
  151339. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  151340. 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 7, 8, 7,
  151341. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  151342. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 8, 8,
  151343. 8, 8, 8, 8, 8, 8, 8, 9, 9,
  151344. };
  151345. static float _vq_quantthresh__44u8_p5_1[] = {
  151346. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  151347. 3.5, 4.5,
  151348. };
  151349. static long _vq_quantmap__44u8_p5_1[] = {
  151350. 9, 7, 5, 3, 1, 0, 2, 4,
  151351. 6, 8, 10,
  151352. };
  151353. static encode_aux_threshmatch _vq_auxt__44u8_p5_1 = {
  151354. _vq_quantthresh__44u8_p5_1,
  151355. _vq_quantmap__44u8_p5_1,
  151356. 11,
  151357. 11
  151358. };
  151359. static static_codebook _44u8_p5_1 = {
  151360. 2, 121,
  151361. _vq_lengthlist__44u8_p5_1,
  151362. 1, -531365888, 1611661312, 4, 0,
  151363. _vq_quantlist__44u8_p5_1,
  151364. NULL,
  151365. &_vq_auxt__44u8_p5_1,
  151366. NULL,
  151367. 0
  151368. };
  151369. static long _vq_quantlist__44u8_p6_0[] = {
  151370. 6,
  151371. 5,
  151372. 7,
  151373. 4,
  151374. 8,
  151375. 3,
  151376. 9,
  151377. 2,
  151378. 10,
  151379. 1,
  151380. 11,
  151381. 0,
  151382. 12,
  151383. };
  151384. static long _vq_lengthlist__44u8_p6_0[] = {
  151385. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  151386. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7, 8,
  151387. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 7, 8, 8, 8, 8, 9,
  151388. 9,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 8,10, 9,11,
  151389. 10, 7, 8, 8, 8, 8, 8, 9, 9, 9,10,10,11,11, 7, 8,
  151390. 8, 8, 8, 9, 8, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  151391. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  151392. 9,10,10,11,11, 9, 9, 9, 9,10,10,10,10,10,10,11,
  151393. 11,12, 9, 9, 9,10, 9,10,10,10,10,11,10,12,11,10,
  151394. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  151395. 11,11,11,11,11,12,11,12,12,
  151396. };
  151397. static float _vq_quantthresh__44u8_p6_0[] = {
  151398. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  151399. 12.5, 17.5, 22.5, 27.5,
  151400. };
  151401. static long _vq_quantmap__44u8_p6_0[] = {
  151402. 11, 9, 7, 5, 3, 1, 0, 2,
  151403. 4, 6, 8, 10, 12,
  151404. };
  151405. static encode_aux_threshmatch _vq_auxt__44u8_p6_0 = {
  151406. _vq_quantthresh__44u8_p6_0,
  151407. _vq_quantmap__44u8_p6_0,
  151408. 13,
  151409. 13
  151410. };
  151411. static static_codebook _44u8_p6_0 = {
  151412. 2, 169,
  151413. _vq_lengthlist__44u8_p6_0,
  151414. 1, -526516224, 1616117760, 4, 0,
  151415. _vq_quantlist__44u8_p6_0,
  151416. NULL,
  151417. &_vq_auxt__44u8_p6_0,
  151418. NULL,
  151419. 0
  151420. };
  151421. static long _vq_quantlist__44u8_p6_1[] = {
  151422. 2,
  151423. 1,
  151424. 3,
  151425. 0,
  151426. 4,
  151427. };
  151428. static long _vq_lengthlist__44u8_p6_1[] = {
  151429. 3, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  151430. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  151431. };
  151432. static float _vq_quantthresh__44u8_p6_1[] = {
  151433. -1.5, -0.5, 0.5, 1.5,
  151434. };
  151435. static long _vq_quantmap__44u8_p6_1[] = {
  151436. 3, 1, 0, 2, 4,
  151437. };
  151438. static encode_aux_threshmatch _vq_auxt__44u8_p6_1 = {
  151439. _vq_quantthresh__44u8_p6_1,
  151440. _vq_quantmap__44u8_p6_1,
  151441. 5,
  151442. 5
  151443. };
  151444. static static_codebook _44u8_p6_1 = {
  151445. 2, 25,
  151446. _vq_lengthlist__44u8_p6_1,
  151447. 1, -533725184, 1611661312, 3, 0,
  151448. _vq_quantlist__44u8_p6_1,
  151449. NULL,
  151450. &_vq_auxt__44u8_p6_1,
  151451. NULL,
  151452. 0
  151453. };
  151454. static long _vq_quantlist__44u8_p7_0[] = {
  151455. 6,
  151456. 5,
  151457. 7,
  151458. 4,
  151459. 8,
  151460. 3,
  151461. 9,
  151462. 2,
  151463. 10,
  151464. 1,
  151465. 11,
  151466. 0,
  151467. 12,
  151468. };
  151469. static long _vq_lengthlist__44u8_p7_0[] = {
  151470. 1, 4, 5, 6, 6, 7, 7, 8, 8,10,10,11,11, 5, 6, 6,
  151471. 7, 7, 8, 8, 9, 9,11,10,12,11, 5, 6, 6, 7, 7, 8,
  151472. 8, 9, 9,10,11,11,12, 6, 7, 7, 8, 8, 9, 9,10,10,
  151473. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,12,13,
  151474. 12, 7, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  151475. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  151476. 11,11,12,12,13,13,14,14, 9, 9, 9,10,10,11,11,12,
  151477. 12,13,13,14,14,10,11,11,12,11,13,12,13,13,14,14,
  151478. 15,15,10,11,11,11,12,12,13,13,14,14,14,15,15,11,
  151479. 12,12,13,13,14,13,15,14,15,15,16,15,11,11,12,13,
  151480. 13,13,14,14,14,15,15,15,16,
  151481. };
  151482. static float _vq_quantthresh__44u8_p7_0[] = {
  151483. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  151484. 27.5, 38.5, 49.5, 60.5,
  151485. };
  151486. static long _vq_quantmap__44u8_p7_0[] = {
  151487. 11, 9, 7, 5, 3, 1, 0, 2,
  151488. 4, 6, 8, 10, 12,
  151489. };
  151490. static encode_aux_threshmatch _vq_auxt__44u8_p7_0 = {
  151491. _vq_quantthresh__44u8_p7_0,
  151492. _vq_quantmap__44u8_p7_0,
  151493. 13,
  151494. 13
  151495. };
  151496. static static_codebook _44u8_p7_0 = {
  151497. 2, 169,
  151498. _vq_lengthlist__44u8_p7_0,
  151499. 1, -523206656, 1618345984, 4, 0,
  151500. _vq_quantlist__44u8_p7_0,
  151501. NULL,
  151502. &_vq_auxt__44u8_p7_0,
  151503. NULL,
  151504. 0
  151505. };
  151506. static long _vq_quantlist__44u8_p7_1[] = {
  151507. 5,
  151508. 4,
  151509. 6,
  151510. 3,
  151511. 7,
  151512. 2,
  151513. 8,
  151514. 1,
  151515. 9,
  151516. 0,
  151517. 10,
  151518. };
  151519. static long _vq_lengthlist__44u8_p7_1[] = {
  151520. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  151521. 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  151522. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  151523. 7, 7, 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8,
  151524. 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 7, 7, 7,
  151525. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  151526. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  151527. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  151528. };
  151529. static float _vq_quantthresh__44u8_p7_1[] = {
  151530. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  151531. 3.5, 4.5,
  151532. };
  151533. static long _vq_quantmap__44u8_p7_1[] = {
  151534. 9, 7, 5, 3, 1, 0, 2, 4,
  151535. 6, 8, 10,
  151536. };
  151537. static encode_aux_threshmatch _vq_auxt__44u8_p7_1 = {
  151538. _vq_quantthresh__44u8_p7_1,
  151539. _vq_quantmap__44u8_p7_1,
  151540. 11,
  151541. 11
  151542. };
  151543. static static_codebook _44u8_p7_1 = {
  151544. 2, 121,
  151545. _vq_lengthlist__44u8_p7_1,
  151546. 1, -531365888, 1611661312, 4, 0,
  151547. _vq_quantlist__44u8_p7_1,
  151548. NULL,
  151549. &_vq_auxt__44u8_p7_1,
  151550. NULL,
  151551. 0
  151552. };
  151553. static long _vq_quantlist__44u8_p8_0[] = {
  151554. 7,
  151555. 6,
  151556. 8,
  151557. 5,
  151558. 9,
  151559. 4,
  151560. 10,
  151561. 3,
  151562. 11,
  151563. 2,
  151564. 12,
  151565. 1,
  151566. 13,
  151567. 0,
  151568. 14,
  151569. };
  151570. static long _vq_lengthlist__44u8_p8_0[] = {
  151571. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8,10, 9,11,10, 4,
  151572. 6, 6, 8, 8,10, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  151573. 6, 8, 8,10,10, 9, 9,10,10,11,11,11,12, 7, 8, 8,
  151574. 10,10,11,11,11,10,12,11,12,12,13,11, 7, 8, 8,10,
  151575. 10,11,11,10,10,11,11,12,12,13,13, 8,10,10,11,11,
  151576. 12,11,12,11,13,12,13,12,14,13, 8,10, 9,11,11,12,
  151577. 12,12,12,12,12,13,13,14,13, 8, 9, 9,11,10,12,11,
  151578. 13,12,13,13,14,13,14,13, 8, 9, 9,10,11,12,12,12,
  151579. 12,13,13,14,15,14,14, 9,10,10,12,11,13,12,13,13,
  151580. 14,13,14,14,14,14, 9,10,10,12,12,12,12,13,13,14,
  151581. 14,14,15,14,14,10,11,11,13,12,13,12,14,14,14,14,
  151582. 14,14,15,15,10,11,11,12,12,13,13,14,14,14,15,15,
  151583. 14,16,15,11,12,12,13,12,14,14,14,13,15,14,15,15,
  151584. 15,17,11,12,12,13,13,14,14,14,15,15,14,15,15,14,
  151585. 17,
  151586. };
  151587. static float _vq_quantthresh__44u8_p8_0[] = {
  151588. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  151589. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  151590. };
  151591. static long _vq_quantmap__44u8_p8_0[] = {
  151592. 13, 11, 9, 7, 5, 3, 1, 0,
  151593. 2, 4, 6, 8, 10, 12, 14,
  151594. };
  151595. static encode_aux_threshmatch _vq_auxt__44u8_p8_0 = {
  151596. _vq_quantthresh__44u8_p8_0,
  151597. _vq_quantmap__44u8_p8_0,
  151598. 15,
  151599. 15
  151600. };
  151601. static static_codebook _44u8_p8_0 = {
  151602. 2, 225,
  151603. _vq_lengthlist__44u8_p8_0,
  151604. 1, -520986624, 1620377600, 4, 0,
  151605. _vq_quantlist__44u8_p8_0,
  151606. NULL,
  151607. &_vq_auxt__44u8_p8_0,
  151608. NULL,
  151609. 0
  151610. };
  151611. static long _vq_quantlist__44u8_p8_1[] = {
  151612. 10,
  151613. 9,
  151614. 11,
  151615. 8,
  151616. 12,
  151617. 7,
  151618. 13,
  151619. 6,
  151620. 14,
  151621. 5,
  151622. 15,
  151623. 4,
  151624. 16,
  151625. 3,
  151626. 17,
  151627. 2,
  151628. 18,
  151629. 1,
  151630. 19,
  151631. 0,
  151632. 20,
  151633. };
  151634. static long _vq_lengthlist__44u8_p8_1[] = {
  151635. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  151636. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  151637. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 5, 6, 6, 7, 7, 8,
  151638. 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  151639. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151640. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  151641. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  151642. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10, 8, 8,
  151643. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  151644. 10, 9,10, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,
  151645. 10,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9,
  151646. 9, 9, 9, 9, 9, 9,10,10,10,10, 9,10,10, 9, 9, 9,
  151647. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  151648. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  151649. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,
  151650. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  151651. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  151652. 10, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  151653. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  151654. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  151655. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  151656. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  151657. 10,10,10,10,10, 9, 9, 9,10, 9,10,10,10,10,10,10,
  151658. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  151659. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  151660. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  151661. 10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,10,
  151662. 10,10,10,10,10,10,10,10,10,
  151663. };
  151664. static float _vq_quantthresh__44u8_p8_1[] = {
  151665. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  151666. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  151667. 6.5, 7.5, 8.5, 9.5,
  151668. };
  151669. static long _vq_quantmap__44u8_p8_1[] = {
  151670. 19, 17, 15, 13, 11, 9, 7, 5,
  151671. 3, 1, 0, 2, 4, 6, 8, 10,
  151672. 12, 14, 16, 18, 20,
  151673. };
  151674. static encode_aux_threshmatch _vq_auxt__44u8_p8_1 = {
  151675. _vq_quantthresh__44u8_p8_1,
  151676. _vq_quantmap__44u8_p8_1,
  151677. 21,
  151678. 21
  151679. };
  151680. static static_codebook _44u8_p8_1 = {
  151681. 2, 441,
  151682. _vq_lengthlist__44u8_p8_1,
  151683. 1, -529268736, 1611661312, 5, 0,
  151684. _vq_quantlist__44u8_p8_1,
  151685. NULL,
  151686. &_vq_auxt__44u8_p8_1,
  151687. NULL,
  151688. 0
  151689. };
  151690. static long _vq_quantlist__44u8_p9_0[] = {
  151691. 4,
  151692. 3,
  151693. 5,
  151694. 2,
  151695. 6,
  151696. 1,
  151697. 7,
  151698. 0,
  151699. 8,
  151700. };
  151701. static long _vq_lengthlist__44u8_p9_0[] = {
  151702. 1, 3, 3, 9, 9, 9, 9, 9, 9, 4, 9, 9, 9, 9, 9, 9,
  151703. 9, 9, 5, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151704. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151705. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151706. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  151707. 8,
  151708. };
  151709. static float _vq_quantthresh__44u8_p9_0[] = {
  151710. -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5, 2327.5, 3258.5,
  151711. };
  151712. static long _vq_quantmap__44u8_p9_0[] = {
  151713. 7, 5, 3, 1, 0, 2, 4, 6,
  151714. 8,
  151715. };
  151716. static encode_aux_threshmatch _vq_auxt__44u8_p9_0 = {
  151717. _vq_quantthresh__44u8_p9_0,
  151718. _vq_quantmap__44u8_p9_0,
  151719. 9,
  151720. 9
  151721. };
  151722. static static_codebook _44u8_p9_0 = {
  151723. 2, 81,
  151724. _vq_lengthlist__44u8_p9_0,
  151725. 1, -511895552, 1631393792, 4, 0,
  151726. _vq_quantlist__44u8_p9_0,
  151727. NULL,
  151728. &_vq_auxt__44u8_p9_0,
  151729. NULL,
  151730. 0
  151731. };
  151732. static long _vq_quantlist__44u8_p9_1[] = {
  151733. 9,
  151734. 8,
  151735. 10,
  151736. 7,
  151737. 11,
  151738. 6,
  151739. 12,
  151740. 5,
  151741. 13,
  151742. 4,
  151743. 14,
  151744. 3,
  151745. 15,
  151746. 2,
  151747. 16,
  151748. 1,
  151749. 17,
  151750. 0,
  151751. 18,
  151752. };
  151753. static long _vq_lengthlist__44u8_p9_1[] = {
  151754. 1, 4, 4, 7, 7, 8, 7, 8, 6, 9, 7,10, 8,11,10,11,
  151755. 11,11,11, 4, 7, 6, 9, 9,10, 9, 9, 9,10,10,11,10,
  151756. 11,10,11,11,13,11, 4, 7, 7, 9, 9, 9, 9, 9, 9,10,
  151757. 10,11,10,11,11,11,12,11,12, 7, 9, 8,11,11,11,11,
  151758. 10,10,11,11,12,12,12,12,12,12,14,13, 7, 8, 9,10,
  151759. 11,11,11,10,10,11,11,11,11,12,12,14,12,13,14, 8,
  151760. 9, 9,11,11,11,11,11,11,12,12,14,12,15,14,14,14,
  151761. 15,14, 8, 9, 9,11,11,11,11,12,11,12,12,13,13,13,
  151762. 13,13,13,14,14, 8, 9, 9,11,10,12,11,12,12,13,13,
  151763. 13,13,15,14,14,14,16,16, 8, 9, 9,10,11,11,12,12,
  151764. 12,13,13,13,14,14,14,15,16,15,15, 9,10,10,11,12,
  151765. 12,13,13,13,14,14,16,14,14,16,16,16,16,15, 9,10,
  151766. 10,11,11,12,13,13,14,15,14,16,14,15,16,16,16,16,
  151767. 15,10,11,11,12,13,13,14,15,15,15,15,15,16,15,16,
  151768. 15,16,15,15,10,11,11,13,13,14,13,13,15,14,15,15,
  151769. 16,15,15,15,16,15,16,10,12,12,14,14,14,14,14,16,
  151770. 16,15,15,15,16,16,16,16,16,16,11,12,12,14,14,14,
  151771. 14,15,15,16,15,16,15,16,15,16,16,16,16,12,12,13,
  151772. 14,14,15,16,16,16,16,16,16,15,16,16,16,16,16,16,
  151773. 12,13,13,14,14,14,14,15,16,15,16,16,16,16,16,16,
  151774. 16,16,16,12,13,14,14,14,16,15,16,15,16,16,16,16,
  151775. 16,16,16,16,16,16,12,14,13,14,15,15,15,16,15,16,
  151776. 16,15,16,16,16,16,16,16,16,
  151777. };
  151778. static float _vq_quantthresh__44u8_p9_1[] = {
  151779. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  151780. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  151781. 367.5, 416.5,
  151782. };
  151783. static long _vq_quantmap__44u8_p9_1[] = {
  151784. 17, 15, 13, 11, 9, 7, 5, 3,
  151785. 1, 0, 2, 4, 6, 8, 10, 12,
  151786. 14, 16, 18,
  151787. };
  151788. static encode_aux_threshmatch _vq_auxt__44u8_p9_1 = {
  151789. _vq_quantthresh__44u8_p9_1,
  151790. _vq_quantmap__44u8_p9_1,
  151791. 19,
  151792. 19
  151793. };
  151794. static static_codebook _44u8_p9_1 = {
  151795. 2, 361,
  151796. _vq_lengthlist__44u8_p9_1,
  151797. 1, -518287360, 1622704128, 5, 0,
  151798. _vq_quantlist__44u8_p9_1,
  151799. NULL,
  151800. &_vq_auxt__44u8_p9_1,
  151801. NULL,
  151802. 0
  151803. };
  151804. static long _vq_quantlist__44u8_p9_2[] = {
  151805. 24,
  151806. 23,
  151807. 25,
  151808. 22,
  151809. 26,
  151810. 21,
  151811. 27,
  151812. 20,
  151813. 28,
  151814. 19,
  151815. 29,
  151816. 18,
  151817. 30,
  151818. 17,
  151819. 31,
  151820. 16,
  151821. 32,
  151822. 15,
  151823. 33,
  151824. 14,
  151825. 34,
  151826. 13,
  151827. 35,
  151828. 12,
  151829. 36,
  151830. 11,
  151831. 37,
  151832. 10,
  151833. 38,
  151834. 9,
  151835. 39,
  151836. 8,
  151837. 40,
  151838. 7,
  151839. 41,
  151840. 6,
  151841. 42,
  151842. 5,
  151843. 43,
  151844. 4,
  151845. 44,
  151846. 3,
  151847. 45,
  151848. 2,
  151849. 46,
  151850. 1,
  151851. 47,
  151852. 0,
  151853. 48,
  151854. };
  151855. static long _vq_lengthlist__44u8_p9_2[] = {
  151856. 2, 3, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  151857. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151858. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151859. 7,
  151860. };
  151861. static float _vq_quantthresh__44u8_p9_2[] = {
  151862. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  151863. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  151864. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151865. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151866. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  151867. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  151868. };
  151869. static long _vq_quantmap__44u8_p9_2[] = {
  151870. 47, 45, 43, 41, 39, 37, 35, 33,
  151871. 31, 29, 27, 25, 23, 21, 19, 17,
  151872. 15, 13, 11, 9, 7, 5, 3, 1,
  151873. 0, 2, 4, 6, 8, 10, 12, 14,
  151874. 16, 18, 20, 22, 24, 26, 28, 30,
  151875. 32, 34, 36, 38, 40, 42, 44, 46,
  151876. 48,
  151877. };
  151878. static encode_aux_threshmatch _vq_auxt__44u8_p9_2 = {
  151879. _vq_quantthresh__44u8_p9_2,
  151880. _vq_quantmap__44u8_p9_2,
  151881. 49,
  151882. 49
  151883. };
  151884. static static_codebook _44u8_p9_2 = {
  151885. 1, 49,
  151886. _vq_lengthlist__44u8_p9_2,
  151887. 1, -526909440, 1611661312, 6, 0,
  151888. _vq_quantlist__44u8_p9_2,
  151889. NULL,
  151890. &_vq_auxt__44u8_p9_2,
  151891. NULL,
  151892. 0
  151893. };
  151894. static long _huff_lengthlist__44u9__long[] = {
  151895. 3, 9,13,13,14,15,14,14,15,15, 5, 5, 9,10,12,12,
  151896. 13,14,16,15,10, 6, 6, 6, 8,11,12,13,16,15,11, 7,
  151897. 5, 3, 5, 8,10,12,15,15,10,10, 7, 4, 3, 5, 8,10,
  151898. 12,12,12,12, 9, 7, 5, 4, 6, 8,10,13,13,12,11, 9,
  151899. 7, 5, 5, 6, 9,12,14,12,12,10, 8, 6, 6, 6, 7,11,
  151900. 13,12,14,13,10, 8, 7, 7, 7,10,11,11,12,13,12,11,
  151901. 10, 8, 8, 9,
  151902. };
  151903. static static_codebook _huff_book__44u9__long = {
  151904. 2, 100,
  151905. _huff_lengthlist__44u9__long,
  151906. 0, 0, 0, 0, 0,
  151907. NULL,
  151908. NULL,
  151909. NULL,
  151910. NULL,
  151911. 0
  151912. };
  151913. static long _huff_lengthlist__44u9__short[] = {
  151914. 9,16,18,18,17,17,17,17,17,17, 5, 8,11,12,11,12,
  151915. 17,17,16,16, 6, 6, 8, 8, 9,10,14,15,16,16, 6, 7,
  151916. 7, 4, 6, 9,13,16,16,16, 6, 6, 7, 4, 5, 8,11,15,
  151917. 17,16, 7, 6, 7, 6, 6, 8, 9,10,14,16,11, 8, 8, 7,
  151918. 6, 6, 3, 4,10,15,14,12,12,10, 5, 6, 3, 3, 8,13,
  151919. 15,17,15,11, 6, 8, 6, 6, 9,14,17,15,15,12, 8,10,
  151920. 9, 9,12,15,
  151921. };
  151922. static static_codebook _huff_book__44u9__short = {
  151923. 2, 100,
  151924. _huff_lengthlist__44u9__short,
  151925. 0, 0, 0, 0, 0,
  151926. NULL,
  151927. NULL,
  151928. NULL,
  151929. NULL,
  151930. 0
  151931. };
  151932. static long _vq_quantlist__44u9_p1_0[] = {
  151933. 1,
  151934. 0,
  151935. 2,
  151936. };
  151937. static long _vq_lengthlist__44u9_p1_0[] = {
  151938. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  151939. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 7, 9,
  151940. 9, 7, 9, 9, 8, 9, 9, 9,10,11, 9,11,11, 7, 9, 9,
  151941. 9,11,10, 9,11,11, 5, 7, 7, 7, 9, 9, 8, 9,10, 7,
  151942. 9, 9, 9,11,11, 9,10,11, 7, 9,10, 9,11,11, 9,11,
  151943. 10,
  151944. };
  151945. static float _vq_quantthresh__44u9_p1_0[] = {
  151946. -0.5, 0.5,
  151947. };
  151948. static long _vq_quantmap__44u9_p1_0[] = {
  151949. 1, 0, 2,
  151950. };
  151951. static encode_aux_threshmatch _vq_auxt__44u9_p1_0 = {
  151952. _vq_quantthresh__44u9_p1_0,
  151953. _vq_quantmap__44u9_p1_0,
  151954. 3,
  151955. 3
  151956. };
  151957. static static_codebook _44u9_p1_0 = {
  151958. 4, 81,
  151959. _vq_lengthlist__44u9_p1_0,
  151960. 1, -535822336, 1611661312, 2, 0,
  151961. _vq_quantlist__44u9_p1_0,
  151962. NULL,
  151963. &_vq_auxt__44u9_p1_0,
  151964. NULL,
  151965. 0
  151966. };
  151967. static long _vq_quantlist__44u9_p2_0[] = {
  151968. 2,
  151969. 1,
  151970. 3,
  151971. 0,
  151972. 4,
  151973. };
  151974. static long _vq_lengthlist__44u9_p2_0[] = {
  151975. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  151976. 9, 9,11,10, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  151977. 8,10,10, 7, 8, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  151978. 11,11, 6, 7, 7, 9, 9, 7, 8, 8,10, 9, 7, 8, 8,10,
  151979. 10, 9,10, 9,11,11, 9,10,10,11,11, 8, 9, 9,11,11,
  151980. 9,10,10,12,11, 9,10,10,11,12,11,11,11,13,13,11,
  151981. 11,11,12,13, 8, 9, 9,11,11, 9,10,10,11,11, 9,10,
  151982. 10,12,11,11,12,11,13,12,11,11,12,13,13, 6, 7, 7,
  151983. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  151984. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  151985. 8, 9, 9,10,10,10,11,11,12,12,10,10,11,12,12, 7,
  151986. 8, 8,10,10, 8, 9, 8,10,10, 8, 9, 9,10,10,10,11,
  151987. 10,12,11,10,10,11,12,12, 9,10,10,11,12,10,11,11,
  151988. 12,12,10,11,10,12,12,12,12,12,13,13,11,12,12,13,
  151989. 13, 9,10,10,11,11, 9,10,10,12,12,10,11,11,12,13,
  151990. 11,12,11,13,12,12,12,12,13,14, 6, 7, 7, 9, 9, 7,
  151991. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,11,11, 9,10,
  151992. 10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,10, 8, 8, 9,
  151993. 10,10,10,11,10,12,12,10,10,11,11,12, 7, 8, 8,10,
  151994. 10, 8, 9, 9,10,10, 8, 9, 9,10,10,10,11,10,12,12,
  151995. 10,11,10,12,12, 9,10,10,12,11,10,11,11,12,12, 9,
  151996. 10,10,12,12,12,12,12,13,13,11,11,12,12,14, 9,10,
  151997. 10,11,12,10,11,11,12,12,10,11,11,12,12,11,12,12,
  151998. 14,14,12,12,12,13,13, 8, 9, 9,11,11, 9,10,10,12,
  151999. 11, 9,10,10,12,12,11,12,11,13,13,11,11,12,13,13,
  152000. 9,10,10,12,12,10,11,11,12,12,10,11,11,12,12,12,
  152001. 12,12,14,14,12,12,12,13,13, 9,10,10,12,11,10,11,
  152002. 10,12,12,10,11,11,12,12,11,12,12,14,13,12,12,12,
  152003. 13,14,11,12,11,13,13,11,12,12,13,13,12,12,12,14,
  152004. 14,13,13,13,13,15,13,13,14,15,15,11,11,11,13,13,
  152005. 11,12,11,13,13,11,12,12,13,13,12,13,12,15,13,13,
  152006. 13,14,14,15, 8, 9, 9,11,11, 9,10,10,11,12, 9,10,
  152007. 10,11,12,11,12,11,13,13,11,12,12,13,13, 9,10,10,
  152008. 11,12,10,11,10,12,12,10,10,11,12,13,12,12,12,14,
  152009. 13,11,12,12,13,14, 9,10,10,12,12,10,11,11,12,12,
  152010. 10,11,11,12,12,12,12,12,14,13,12,12,12,14,13,11,
  152011. 11,11,13,13,11,12,12,14,13,11,11,12,13,13,13,13,
  152012. 13,15,14,12,12,13,13,15,11,12,12,13,13,12,12,12,
  152013. 13,14,11,12,12,13,13,13,13,14,14,15,13,13,13,14,
  152014. 14,
  152015. };
  152016. static float _vq_quantthresh__44u9_p2_0[] = {
  152017. -1.5, -0.5, 0.5, 1.5,
  152018. };
  152019. static long _vq_quantmap__44u9_p2_0[] = {
  152020. 3, 1, 0, 2, 4,
  152021. };
  152022. static encode_aux_threshmatch _vq_auxt__44u9_p2_0 = {
  152023. _vq_quantthresh__44u9_p2_0,
  152024. _vq_quantmap__44u9_p2_0,
  152025. 5,
  152026. 5
  152027. };
  152028. static static_codebook _44u9_p2_0 = {
  152029. 4, 625,
  152030. _vq_lengthlist__44u9_p2_0,
  152031. 1, -533725184, 1611661312, 3, 0,
  152032. _vq_quantlist__44u9_p2_0,
  152033. NULL,
  152034. &_vq_auxt__44u9_p2_0,
  152035. NULL,
  152036. 0
  152037. };
  152038. static long _vq_quantlist__44u9_p3_0[] = {
  152039. 4,
  152040. 3,
  152041. 5,
  152042. 2,
  152043. 6,
  152044. 1,
  152045. 7,
  152046. 0,
  152047. 8,
  152048. };
  152049. static long _vq_lengthlist__44u9_p3_0[] = {
  152050. 3, 4, 4, 5, 5, 7, 7, 8, 8, 4, 5, 5, 6, 6, 7, 7,
  152051. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  152052. 8, 8, 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  152053. 8, 8, 9, 9,10,10, 7, 7, 7, 8, 8, 9, 9,10,10, 8,
  152054. 9, 9,10, 9,10,10,11,11, 8, 9, 9, 9,10,10,10,11,
  152055. 11,
  152056. };
  152057. static float _vq_quantthresh__44u9_p3_0[] = {
  152058. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  152059. };
  152060. static long _vq_quantmap__44u9_p3_0[] = {
  152061. 7, 5, 3, 1, 0, 2, 4, 6,
  152062. 8,
  152063. };
  152064. static encode_aux_threshmatch _vq_auxt__44u9_p3_0 = {
  152065. _vq_quantthresh__44u9_p3_0,
  152066. _vq_quantmap__44u9_p3_0,
  152067. 9,
  152068. 9
  152069. };
  152070. static static_codebook _44u9_p3_0 = {
  152071. 2, 81,
  152072. _vq_lengthlist__44u9_p3_0,
  152073. 1, -531628032, 1611661312, 4, 0,
  152074. _vq_quantlist__44u9_p3_0,
  152075. NULL,
  152076. &_vq_auxt__44u9_p3_0,
  152077. NULL,
  152078. 0
  152079. };
  152080. static long _vq_quantlist__44u9_p4_0[] = {
  152081. 8,
  152082. 7,
  152083. 9,
  152084. 6,
  152085. 10,
  152086. 5,
  152087. 11,
  152088. 4,
  152089. 12,
  152090. 3,
  152091. 13,
  152092. 2,
  152093. 14,
  152094. 1,
  152095. 15,
  152096. 0,
  152097. 16,
  152098. };
  152099. static long _vq_lengthlist__44u9_p4_0[] = {
  152100. 4, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  152101. 11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  152102. 11,11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  152103. 10,11,11, 6, 6, 6, 7, 6, 7, 7, 8, 8, 9, 9,10,10,
  152104. 11,11,12,11, 6, 6, 6, 6, 7, 7, 7, 8, 8, 9, 9,10,
  152105. 10,11,11,11,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,
  152106. 10,10,11,11,12,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  152107. 9,10,10,11,11,12,12, 8, 8, 8, 8, 8, 9, 8,10, 9,
  152108. 10,10,11,10,12,11,13,12, 8, 8, 8, 8, 8, 9, 9, 9,
  152109. 10,10,10,10,11,11,12,12,12, 8, 8, 8, 9, 9, 9, 9,
  152110. 10,10,11,10,12,11,12,12,13,12, 8, 8, 8, 9, 9, 9,
  152111. 9,10,10,10,11,11,11,12,12,12,13, 9, 9, 9,10,10,
  152112. 10,10,11,10,11,11,12,11,13,12,13,13, 9, 9,10,10,
  152113. 10,10,10,10,11,11,11,11,12,12,13,13,13,10,11,10,
  152114. 11,11,11,11,12,11,12,12,13,12,13,13,14,13,10,10,
  152115. 10,11,11,11,11,11,12,12,12,12,13,13,13,13,14,11,
  152116. 11,11,12,11,12,12,12,12,13,13,13,13,14,13,14,14,
  152117. 11,11,11,11,12,12,12,12,12,12,13,13,13,13,14,14,
  152118. 14,
  152119. };
  152120. static float _vq_quantthresh__44u9_p4_0[] = {
  152121. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  152122. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  152123. };
  152124. static long _vq_quantmap__44u9_p4_0[] = {
  152125. 15, 13, 11, 9, 7, 5, 3, 1,
  152126. 0, 2, 4, 6, 8, 10, 12, 14,
  152127. 16,
  152128. };
  152129. static encode_aux_threshmatch _vq_auxt__44u9_p4_0 = {
  152130. _vq_quantthresh__44u9_p4_0,
  152131. _vq_quantmap__44u9_p4_0,
  152132. 17,
  152133. 17
  152134. };
  152135. static static_codebook _44u9_p4_0 = {
  152136. 2, 289,
  152137. _vq_lengthlist__44u9_p4_0,
  152138. 1, -529530880, 1611661312, 5, 0,
  152139. _vq_quantlist__44u9_p4_0,
  152140. NULL,
  152141. &_vq_auxt__44u9_p4_0,
  152142. NULL,
  152143. 0
  152144. };
  152145. static long _vq_quantlist__44u9_p5_0[] = {
  152146. 1,
  152147. 0,
  152148. 2,
  152149. };
  152150. static long _vq_lengthlist__44u9_p5_0[] = {
  152151. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  152152. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  152153. 10, 8,10,10, 7,10,10, 9,10,12, 9,11,11, 7,10,10,
  152154. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  152155. 10,10, 9,12,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  152156. 10,
  152157. };
  152158. static float _vq_quantthresh__44u9_p5_0[] = {
  152159. -5.5, 5.5,
  152160. };
  152161. static long _vq_quantmap__44u9_p5_0[] = {
  152162. 1, 0, 2,
  152163. };
  152164. static encode_aux_threshmatch _vq_auxt__44u9_p5_0 = {
  152165. _vq_quantthresh__44u9_p5_0,
  152166. _vq_quantmap__44u9_p5_0,
  152167. 3,
  152168. 3
  152169. };
  152170. static static_codebook _44u9_p5_0 = {
  152171. 4, 81,
  152172. _vq_lengthlist__44u9_p5_0,
  152173. 1, -529137664, 1618345984, 2, 0,
  152174. _vq_quantlist__44u9_p5_0,
  152175. NULL,
  152176. &_vq_auxt__44u9_p5_0,
  152177. NULL,
  152178. 0
  152179. };
  152180. static long _vq_quantlist__44u9_p5_1[] = {
  152181. 5,
  152182. 4,
  152183. 6,
  152184. 3,
  152185. 7,
  152186. 2,
  152187. 8,
  152188. 1,
  152189. 9,
  152190. 0,
  152191. 10,
  152192. };
  152193. static long _vq_lengthlist__44u9_p5_1[] = {
  152194. 5, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 6,
  152195. 7, 7, 7, 7, 8, 7, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  152196. 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 6, 6, 6, 7,
  152197. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  152198. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  152199. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  152200. 8, 8, 8, 7, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  152201. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  152202. };
  152203. static float _vq_quantthresh__44u9_p5_1[] = {
  152204. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  152205. 3.5, 4.5,
  152206. };
  152207. static long _vq_quantmap__44u9_p5_1[] = {
  152208. 9, 7, 5, 3, 1, 0, 2, 4,
  152209. 6, 8, 10,
  152210. };
  152211. static encode_aux_threshmatch _vq_auxt__44u9_p5_1 = {
  152212. _vq_quantthresh__44u9_p5_1,
  152213. _vq_quantmap__44u9_p5_1,
  152214. 11,
  152215. 11
  152216. };
  152217. static static_codebook _44u9_p5_1 = {
  152218. 2, 121,
  152219. _vq_lengthlist__44u9_p5_1,
  152220. 1, -531365888, 1611661312, 4, 0,
  152221. _vq_quantlist__44u9_p5_1,
  152222. NULL,
  152223. &_vq_auxt__44u9_p5_1,
  152224. NULL,
  152225. 0
  152226. };
  152227. static long _vq_quantlist__44u9_p6_0[] = {
  152228. 6,
  152229. 5,
  152230. 7,
  152231. 4,
  152232. 8,
  152233. 3,
  152234. 9,
  152235. 2,
  152236. 10,
  152237. 1,
  152238. 11,
  152239. 0,
  152240. 12,
  152241. };
  152242. static long _vq_lengthlist__44u9_p6_0[] = {
  152243. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  152244. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 5, 6, 7, 7, 8,
  152245. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  152246. 10,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  152247. 10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 7, 8,
  152248. 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  152249. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  152250. 9,10,10,11,11, 9, 9, 9,10,10,10,10,10,11,11,11,
  152251. 11,12, 9, 9, 9,10,10,10,10,10,10,11,10,12,11,10,
  152252. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  152253. 10,11,11,11,11,12,11,12,12,
  152254. };
  152255. static float _vq_quantthresh__44u9_p6_0[] = {
  152256. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  152257. 12.5, 17.5, 22.5, 27.5,
  152258. };
  152259. static long _vq_quantmap__44u9_p6_0[] = {
  152260. 11, 9, 7, 5, 3, 1, 0, 2,
  152261. 4, 6, 8, 10, 12,
  152262. };
  152263. static encode_aux_threshmatch _vq_auxt__44u9_p6_0 = {
  152264. _vq_quantthresh__44u9_p6_0,
  152265. _vq_quantmap__44u9_p6_0,
  152266. 13,
  152267. 13
  152268. };
  152269. static static_codebook _44u9_p6_0 = {
  152270. 2, 169,
  152271. _vq_lengthlist__44u9_p6_0,
  152272. 1, -526516224, 1616117760, 4, 0,
  152273. _vq_quantlist__44u9_p6_0,
  152274. NULL,
  152275. &_vq_auxt__44u9_p6_0,
  152276. NULL,
  152277. 0
  152278. };
  152279. static long _vq_quantlist__44u9_p6_1[] = {
  152280. 2,
  152281. 1,
  152282. 3,
  152283. 0,
  152284. 4,
  152285. };
  152286. static long _vq_lengthlist__44u9_p6_1[] = {
  152287. 4, 4, 4, 5, 5, 4, 5, 4, 5, 5, 4, 4, 5, 5, 5, 5,
  152288. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  152289. };
  152290. static float _vq_quantthresh__44u9_p6_1[] = {
  152291. -1.5, -0.5, 0.5, 1.5,
  152292. };
  152293. static long _vq_quantmap__44u9_p6_1[] = {
  152294. 3, 1, 0, 2, 4,
  152295. };
  152296. static encode_aux_threshmatch _vq_auxt__44u9_p6_1 = {
  152297. _vq_quantthresh__44u9_p6_1,
  152298. _vq_quantmap__44u9_p6_1,
  152299. 5,
  152300. 5
  152301. };
  152302. static static_codebook _44u9_p6_1 = {
  152303. 2, 25,
  152304. _vq_lengthlist__44u9_p6_1,
  152305. 1, -533725184, 1611661312, 3, 0,
  152306. _vq_quantlist__44u9_p6_1,
  152307. NULL,
  152308. &_vq_auxt__44u9_p6_1,
  152309. NULL,
  152310. 0
  152311. };
  152312. static long _vq_quantlist__44u9_p7_0[] = {
  152313. 6,
  152314. 5,
  152315. 7,
  152316. 4,
  152317. 8,
  152318. 3,
  152319. 9,
  152320. 2,
  152321. 10,
  152322. 1,
  152323. 11,
  152324. 0,
  152325. 12,
  152326. };
  152327. static long _vq_lengthlist__44u9_p7_0[] = {
  152328. 1, 4, 5, 6, 6, 7, 7, 8, 9,10,10,11,11, 5, 6, 6,
  152329. 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 6, 6, 7, 7, 8,
  152330. 8, 9, 9,10,10,11,11, 6, 7, 7, 8, 8, 9, 9,10,10,
  152331. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,12,
  152332. 12, 8, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  152333. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  152334. 11,11,12,12,13,13,13,13, 9, 9, 9,10,10,11,11,12,
  152335. 12,13,13,14,14,10,10,10,11,11,12,12,13,13,14,13,
  152336. 15,14,10,10,10,11,11,12,12,13,13,14,14,14,14,11,
  152337. 11,12,12,12,13,13,14,14,14,14,15,15,11,11,12,12,
  152338. 12,13,13,14,14,14,15,15,15,
  152339. };
  152340. static float _vq_quantthresh__44u9_p7_0[] = {
  152341. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  152342. 27.5, 38.5, 49.5, 60.5,
  152343. };
  152344. static long _vq_quantmap__44u9_p7_0[] = {
  152345. 11, 9, 7, 5, 3, 1, 0, 2,
  152346. 4, 6, 8, 10, 12,
  152347. };
  152348. static encode_aux_threshmatch _vq_auxt__44u9_p7_0 = {
  152349. _vq_quantthresh__44u9_p7_0,
  152350. _vq_quantmap__44u9_p7_0,
  152351. 13,
  152352. 13
  152353. };
  152354. static static_codebook _44u9_p7_0 = {
  152355. 2, 169,
  152356. _vq_lengthlist__44u9_p7_0,
  152357. 1, -523206656, 1618345984, 4, 0,
  152358. _vq_quantlist__44u9_p7_0,
  152359. NULL,
  152360. &_vq_auxt__44u9_p7_0,
  152361. NULL,
  152362. 0
  152363. };
  152364. static long _vq_quantlist__44u9_p7_1[] = {
  152365. 5,
  152366. 4,
  152367. 6,
  152368. 3,
  152369. 7,
  152370. 2,
  152371. 8,
  152372. 1,
  152373. 9,
  152374. 0,
  152375. 10,
  152376. };
  152377. static long _vq_lengthlist__44u9_p7_1[] = {
  152378. 5, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7,
  152379. 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  152380. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 7, 7, 7,
  152381. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152382. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152383. 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152384. 7, 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 7, 8, 8, 7, 7,
  152385. 7, 7, 7, 7, 7, 8, 8, 8, 8,
  152386. };
  152387. static float _vq_quantthresh__44u9_p7_1[] = {
  152388. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  152389. 3.5, 4.5,
  152390. };
  152391. static long _vq_quantmap__44u9_p7_1[] = {
  152392. 9, 7, 5, 3, 1, 0, 2, 4,
  152393. 6, 8, 10,
  152394. };
  152395. static encode_aux_threshmatch _vq_auxt__44u9_p7_1 = {
  152396. _vq_quantthresh__44u9_p7_1,
  152397. _vq_quantmap__44u9_p7_1,
  152398. 11,
  152399. 11
  152400. };
  152401. static static_codebook _44u9_p7_1 = {
  152402. 2, 121,
  152403. _vq_lengthlist__44u9_p7_1,
  152404. 1, -531365888, 1611661312, 4, 0,
  152405. _vq_quantlist__44u9_p7_1,
  152406. NULL,
  152407. &_vq_auxt__44u9_p7_1,
  152408. NULL,
  152409. 0
  152410. };
  152411. static long _vq_quantlist__44u9_p8_0[] = {
  152412. 7,
  152413. 6,
  152414. 8,
  152415. 5,
  152416. 9,
  152417. 4,
  152418. 10,
  152419. 3,
  152420. 11,
  152421. 2,
  152422. 12,
  152423. 1,
  152424. 13,
  152425. 0,
  152426. 14,
  152427. };
  152428. static long _vq_lengthlist__44u9_p8_0[] = {
  152429. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,11,10, 4,
  152430. 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  152431. 6, 8, 8, 9,10, 9, 9,10,10,11,11,12,12, 7, 8, 8,
  152432. 10,10,11,11,10,10,11,11,12,12,13,12, 7, 8, 8,10,
  152433. 10,11,11,10,10,11,11,12,12,12,13, 8,10, 9,11,11,
  152434. 12,12,11,11,12,12,13,13,14,13, 8, 9, 9,11,11,12,
  152435. 12,11,12,12,12,13,13,14,13, 8, 9, 9,10,10,12,11,
  152436. 13,12,13,13,14,13,15,14, 8, 9, 9,10,10,11,12,12,
  152437. 12,13,13,13,14,14,14, 9,10,10,12,11,13,12,13,13,
  152438. 14,13,14,14,14,15, 9,10,10,11,12,12,12,13,13,14,
  152439. 14,14,15,15,15,10,11,11,12,12,13,13,14,14,14,14,
  152440. 15,14,16,15,10,11,11,12,12,13,13,13,14,14,14,14,
  152441. 14,15,16,11,12,12,13,13,14,13,14,14,15,14,15,16,
  152442. 16,16,11,12,12,13,13,14,13,14,14,15,15,15,16,15,
  152443. 15,
  152444. };
  152445. static float _vq_quantthresh__44u9_p8_0[] = {
  152446. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  152447. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  152448. };
  152449. static long _vq_quantmap__44u9_p8_0[] = {
  152450. 13, 11, 9, 7, 5, 3, 1, 0,
  152451. 2, 4, 6, 8, 10, 12, 14,
  152452. };
  152453. static encode_aux_threshmatch _vq_auxt__44u9_p8_0 = {
  152454. _vq_quantthresh__44u9_p8_0,
  152455. _vq_quantmap__44u9_p8_0,
  152456. 15,
  152457. 15
  152458. };
  152459. static static_codebook _44u9_p8_0 = {
  152460. 2, 225,
  152461. _vq_lengthlist__44u9_p8_0,
  152462. 1, -520986624, 1620377600, 4, 0,
  152463. _vq_quantlist__44u9_p8_0,
  152464. NULL,
  152465. &_vq_auxt__44u9_p8_0,
  152466. NULL,
  152467. 0
  152468. };
  152469. static long _vq_quantlist__44u9_p8_1[] = {
  152470. 10,
  152471. 9,
  152472. 11,
  152473. 8,
  152474. 12,
  152475. 7,
  152476. 13,
  152477. 6,
  152478. 14,
  152479. 5,
  152480. 15,
  152481. 4,
  152482. 16,
  152483. 3,
  152484. 17,
  152485. 2,
  152486. 18,
  152487. 1,
  152488. 19,
  152489. 0,
  152490. 20,
  152491. };
  152492. static long _vq_lengthlist__44u9_p8_1[] = {
  152493. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  152494. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  152495. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8,
  152496. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  152497. 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  152498. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  152499. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  152500. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10, 8, 8,
  152501. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152502. 9,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152503. 10, 9,10, 9,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  152504. 9, 9, 9, 9, 9,10,10, 9,10,10,10,10,10, 9, 9, 9,
  152505. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  152506. 10,10, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  152507. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152508. 9, 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  152509. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  152510. 10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  152511. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  152512. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  152513. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152514. 9, 9, 9, 9,10, 9, 9,10,10,10,10,10,10,10,10,10,
  152515. 10,10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,
  152516. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,10,
  152517. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  152518. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  152519. 10,10,10,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  152520. 10,10,10,10,10,10,10,10,10,
  152521. };
  152522. static float _vq_quantthresh__44u9_p8_1[] = {
  152523. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  152524. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  152525. 6.5, 7.5, 8.5, 9.5,
  152526. };
  152527. static long _vq_quantmap__44u9_p8_1[] = {
  152528. 19, 17, 15, 13, 11, 9, 7, 5,
  152529. 3, 1, 0, 2, 4, 6, 8, 10,
  152530. 12, 14, 16, 18, 20,
  152531. };
  152532. static encode_aux_threshmatch _vq_auxt__44u9_p8_1 = {
  152533. _vq_quantthresh__44u9_p8_1,
  152534. _vq_quantmap__44u9_p8_1,
  152535. 21,
  152536. 21
  152537. };
  152538. static static_codebook _44u9_p8_1 = {
  152539. 2, 441,
  152540. _vq_lengthlist__44u9_p8_1,
  152541. 1, -529268736, 1611661312, 5, 0,
  152542. _vq_quantlist__44u9_p8_1,
  152543. NULL,
  152544. &_vq_auxt__44u9_p8_1,
  152545. NULL,
  152546. 0
  152547. };
  152548. static long _vq_quantlist__44u9_p9_0[] = {
  152549. 7,
  152550. 6,
  152551. 8,
  152552. 5,
  152553. 9,
  152554. 4,
  152555. 10,
  152556. 3,
  152557. 11,
  152558. 2,
  152559. 12,
  152560. 1,
  152561. 13,
  152562. 0,
  152563. 14,
  152564. };
  152565. static long _vq_lengthlist__44u9_p9_0[] = {
  152566. 1, 3, 3,11,11,11,11,11,11,11,11,11,11,11,11, 4,
  152567. 10,11,11,11,11,11,11,11,11,11,11,11,11,11, 4,10,
  152568. 10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152569. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152570. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152571. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152572. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152573. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152574. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152575. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152576. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152577. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152578. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152579. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152580. 10,
  152581. };
  152582. static float _vq_quantthresh__44u9_p9_0[] = {
  152583. -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5,
  152584. 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  152585. };
  152586. static long _vq_quantmap__44u9_p9_0[] = {
  152587. 13, 11, 9, 7, 5, 3, 1, 0,
  152588. 2, 4, 6, 8, 10, 12, 14,
  152589. };
  152590. static encode_aux_threshmatch _vq_auxt__44u9_p9_0 = {
  152591. _vq_quantthresh__44u9_p9_0,
  152592. _vq_quantmap__44u9_p9_0,
  152593. 15,
  152594. 15
  152595. };
  152596. static static_codebook _44u9_p9_0 = {
  152597. 2, 225,
  152598. _vq_lengthlist__44u9_p9_0,
  152599. 1, -510036736, 1631393792, 4, 0,
  152600. _vq_quantlist__44u9_p9_0,
  152601. NULL,
  152602. &_vq_auxt__44u9_p9_0,
  152603. NULL,
  152604. 0
  152605. };
  152606. static long _vq_quantlist__44u9_p9_1[] = {
  152607. 9,
  152608. 8,
  152609. 10,
  152610. 7,
  152611. 11,
  152612. 6,
  152613. 12,
  152614. 5,
  152615. 13,
  152616. 4,
  152617. 14,
  152618. 3,
  152619. 15,
  152620. 2,
  152621. 16,
  152622. 1,
  152623. 17,
  152624. 0,
  152625. 18,
  152626. };
  152627. static long _vq_lengthlist__44u9_p9_1[] = {
  152628. 1, 4, 4, 7, 7, 8, 7, 8, 7, 9, 8,10, 9,10,10,11,
  152629. 11,12,12, 4, 7, 6, 9, 9,10, 9, 9, 8,10,10,11,10,
  152630. 12,10,13,12,13,12, 4, 6, 6, 9, 9, 9, 9, 9, 9,10,
  152631. 10,11,11,11,12,12,12,12,12, 7, 9, 8,11,10,10,10,
  152632. 11,10,11,11,12,12,13,12,13,13,13,13, 7, 8, 9,10,
  152633. 10,11,11,10,10,11,11,11,12,13,13,13,13,14,14, 8,
  152634. 9, 9,11,11,12,11,12,12,13,12,12,13,13,14,15,14,
  152635. 14,14, 8, 9, 9,10,11,11,11,12,12,13,12,13,13,14,
  152636. 14,14,15,14,16, 8, 9, 9,11,10,12,12,12,12,15,13,
  152637. 13,13,17,14,15,15,15,14, 8, 9, 9,10,11,11,12,13,
  152638. 12,13,13,13,14,15,14,14,14,16,15, 9,11,10,12,12,
  152639. 13,13,13,13,14,14,16,15,14,14,14,15,15,17, 9,10,
  152640. 10,11,11,13,13,13,14,14,13,15,14,15,14,15,16,15,
  152641. 16,10,11,11,12,12,13,14,15,14,15,14,14,15,17,16,
  152642. 15,15,17,17,10,12,11,13,12,14,14,13,14,15,15,15,
  152643. 15,16,17,17,15,17,16,11,12,12,14,13,15,14,15,16,
  152644. 17,15,17,15,17,15,15,16,17,15,11,11,12,14,14,14,
  152645. 14,14,15,15,16,15,17,17,17,16,17,16,15,12,12,13,
  152646. 14,14,14,15,14,15,15,16,16,17,16,17,15,17,17,16,
  152647. 12,14,12,14,14,15,15,15,14,14,16,16,16,15,16,16,
  152648. 15,17,15,12,13,13,14,15,14,15,17,15,17,16,17,17,
  152649. 17,16,17,16,17,17,12,13,13,14,16,15,15,15,16,15,
  152650. 17,17,15,17,15,17,16,16,17,
  152651. };
  152652. static float _vq_quantthresh__44u9_p9_1[] = {
  152653. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  152654. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  152655. 367.5, 416.5,
  152656. };
  152657. static long _vq_quantmap__44u9_p9_1[] = {
  152658. 17, 15, 13, 11, 9, 7, 5, 3,
  152659. 1, 0, 2, 4, 6, 8, 10, 12,
  152660. 14, 16, 18,
  152661. };
  152662. static encode_aux_threshmatch _vq_auxt__44u9_p9_1 = {
  152663. _vq_quantthresh__44u9_p9_1,
  152664. _vq_quantmap__44u9_p9_1,
  152665. 19,
  152666. 19
  152667. };
  152668. static static_codebook _44u9_p9_1 = {
  152669. 2, 361,
  152670. _vq_lengthlist__44u9_p9_1,
  152671. 1, -518287360, 1622704128, 5, 0,
  152672. _vq_quantlist__44u9_p9_1,
  152673. NULL,
  152674. &_vq_auxt__44u9_p9_1,
  152675. NULL,
  152676. 0
  152677. };
  152678. static long _vq_quantlist__44u9_p9_2[] = {
  152679. 24,
  152680. 23,
  152681. 25,
  152682. 22,
  152683. 26,
  152684. 21,
  152685. 27,
  152686. 20,
  152687. 28,
  152688. 19,
  152689. 29,
  152690. 18,
  152691. 30,
  152692. 17,
  152693. 31,
  152694. 16,
  152695. 32,
  152696. 15,
  152697. 33,
  152698. 14,
  152699. 34,
  152700. 13,
  152701. 35,
  152702. 12,
  152703. 36,
  152704. 11,
  152705. 37,
  152706. 10,
  152707. 38,
  152708. 9,
  152709. 39,
  152710. 8,
  152711. 40,
  152712. 7,
  152713. 41,
  152714. 6,
  152715. 42,
  152716. 5,
  152717. 43,
  152718. 4,
  152719. 44,
  152720. 3,
  152721. 45,
  152722. 2,
  152723. 46,
  152724. 1,
  152725. 47,
  152726. 0,
  152727. 48,
  152728. };
  152729. static long _vq_lengthlist__44u9_p9_2[] = {
  152730. 2, 4, 4, 5, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  152731. 6, 6, 6, 7, 6, 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152732. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152733. 7,
  152734. };
  152735. static float _vq_quantthresh__44u9_p9_2[] = {
  152736. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  152737. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  152738. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  152739. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  152740. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  152741. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  152742. };
  152743. static long _vq_quantmap__44u9_p9_2[] = {
  152744. 47, 45, 43, 41, 39, 37, 35, 33,
  152745. 31, 29, 27, 25, 23, 21, 19, 17,
  152746. 15, 13, 11, 9, 7, 5, 3, 1,
  152747. 0, 2, 4, 6, 8, 10, 12, 14,
  152748. 16, 18, 20, 22, 24, 26, 28, 30,
  152749. 32, 34, 36, 38, 40, 42, 44, 46,
  152750. 48,
  152751. };
  152752. static encode_aux_threshmatch _vq_auxt__44u9_p9_2 = {
  152753. _vq_quantthresh__44u9_p9_2,
  152754. _vq_quantmap__44u9_p9_2,
  152755. 49,
  152756. 49
  152757. };
  152758. static static_codebook _44u9_p9_2 = {
  152759. 1, 49,
  152760. _vq_lengthlist__44u9_p9_2,
  152761. 1, -526909440, 1611661312, 6, 0,
  152762. _vq_quantlist__44u9_p9_2,
  152763. NULL,
  152764. &_vq_auxt__44u9_p9_2,
  152765. NULL,
  152766. 0
  152767. };
  152768. static long _huff_lengthlist__44un1__long[] = {
  152769. 5, 6,12, 9,14, 9, 9,19, 6, 1, 5, 5, 8, 7, 9,19,
  152770. 12, 4, 4, 7, 7, 9,11,18, 9, 5, 6, 6, 8, 7, 8,17,
  152771. 14, 8, 7, 8, 8,10,12,18, 9, 6, 8, 6, 8, 6, 8,18,
  152772. 9, 8,11, 8,11, 7, 5,15,16,18,18,18,17,15,11,18,
  152773. };
  152774. static static_codebook _huff_book__44un1__long = {
  152775. 2, 64,
  152776. _huff_lengthlist__44un1__long,
  152777. 0, 0, 0, 0, 0,
  152778. NULL,
  152779. NULL,
  152780. NULL,
  152781. NULL,
  152782. 0
  152783. };
  152784. static long _vq_quantlist__44un1__p1_0[] = {
  152785. 1,
  152786. 0,
  152787. 2,
  152788. };
  152789. static long _vq_lengthlist__44un1__p1_0[] = {
  152790. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  152791. 10,11, 5, 8, 8, 8,11,10, 8,11,10, 4, 9, 9, 8,11,
  152792. 11, 8,11,11, 8,12,11,10,12,14,11,13,13, 7,11,11,
  152793. 10,13,11,11,13,14, 4, 8, 9, 8,11,11, 8,11,12, 7,
  152794. 11,11,11,14,13,10,11,13, 8,11,12,11,13,13,10,14,
  152795. 12,
  152796. };
  152797. static float _vq_quantthresh__44un1__p1_0[] = {
  152798. -0.5, 0.5,
  152799. };
  152800. static long _vq_quantmap__44un1__p1_0[] = {
  152801. 1, 0, 2,
  152802. };
  152803. static encode_aux_threshmatch _vq_auxt__44un1__p1_0 = {
  152804. _vq_quantthresh__44un1__p1_0,
  152805. _vq_quantmap__44un1__p1_0,
  152806. 3,
  152807. 3
  152808. };
  152809. static static_codebook _44un1__p1_0 = {
  152810. 4, 81,
  152811. _vq_lengthlist__44un1__p1_0,
  152812. 1, -535822336, 1611661312, 2, 0,
  152813. _vq_quantlist__44un1__p1_0,
  152814. NULL,
  152815. &_vq_auxt__44un1__p1_0,
  152816. NULL,
  152817. 0
  152818. };
  152819. static long _vq_quantlist__44un1__p2_0[] = {
  152820. 1,
  152821. 0,
  152822. 2,
  152823. };
  152824. static long _vq_lengthlist__44un1__p2_0[] = {
  152825. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  152826. 7, 9, 5, 7, 7, 6, 8, 7, 7, 9, 8, 4, 7, 7, 7, 9,
  152827. 8, 7, 8, 8, 7, 9, 8, 8, 8,10, 9,10,10, 6, 8, 8,
  152828. 7,10, 8, 9,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  152829. 8, 8, 9,10,10, 7, 8,10, 6, 8, 9, 9,10,10, 8,10,
  152830. 8,
  152831. };
  152832. static float _vq_quantthresh__44un1__p2_0[] = {
  152833. -0.5, 0.5,
  152834. };
  152835. static long _vq_quantmap__44un1__p2_0[] = {
  152836. 1, 0, 2,
  152837. };
  152838. static encode_aux_threshmatch _vq_auxt__44un1__p2_0 = {
  152839. _vq_quantthresh__44un1__p2_0,
  152840. _vq_quantmap__44un1__p2_0,
  152841. 3,
  152842. 3
  152843. };
  152844. static static_codebook _44un1__p2_0 = {
  152845. 4, 81,
  152846. _vq_lengthlist__44un1__p2_0,
  152847. 1, -535822336, 1611661312, 2, 0,
  152848. _vq_quantlist__44un1__p2_0,
  152849. NULL,
  152850. &_vq_auxt__44un1__p2_0,
  152851. NULL,
  152852. 0
  152853. };
  152854. static long _vq_quantlist__44un1__p3_0[] = {
  152855. 2,
  152856. 1,
  152857. 3,
  152858. 0,
  152859. 4,
  152860. };
  152861. static long _vq_lengthlist__44un1__p3_0[] = {
  152862. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  152863. 10, 9,12,12, 9, 9,10,11,12, 6, 8, 8,10,10, 8,10,
  152864. 10,11,11, 8, 9,10,11,11,10,11,11,13,13,10,11,11,
  152865. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10,10,11,
  152866. 11,10,11,11,13,12,10,11,11,13,12, 9,11,11,15,13,
  152867. 10,12,11,15,13,10,11,11,15,14,12,14,13,16,15,12,
  152868. 13,13,17,16, 9,11,11,13,15,10,11,12,14,15,10,11,
  152869. 12,14,15,12,13,13,15,16,12,13,13,16,16, 5, 8, 8,
  152870. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  152871. 14,11,12,12,14,14, 8,11,10,13,12,10,11,12,12,13,
  152872. 10,12,12,13,13,12,12,13,13,15,11,12,13,15,14, 7,
  152873. 10,10,12,12, 9,12,11,13,12,10,12,12,13,14,12,13,
  152874. 12,15,13,11,13,12,14,15,10,12,12,16,14,11,12,12,
  152875. 16,15,11,13,12,17,16,13,13,15,15,17,13,15,15,20,
  152876. 17,10,12,12,14,16,11,12,12,15,15,11,13,13,15,18,
  152877. 13,14,13,15,15,13,15,14,16,16, 5, 8, 8,11,11, 8,
  152878. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  152879. 12,14,15, 7,10,10,13,12,10,12,12,14,13, 9,10,12,
  152880. 12,13,11,13,13,15,15,11,12,13,13,15, 8,10,10,12,
  152881. 13,10,12,12,13,13,10,12,11,13,13,11,13,12,15,15,
  152882. 12,13,12,15,13,10,12,12,16,14,11,12,12,16,15,10,
  152883. 12,12,16,14,14,15,14,18,16,13,13,14,15,16,10,12,
  152884. 12,14,16,11,13,13,16,16,11,13,12,14,16,13,15,15,
  152885. 18,18,13,15,13,16,14, 8,11,11,16,16,10,13,13,17,
  152886. 16,10,12,12,16,15,14,16,15,20,17,13,14,14,17,17,
  152887. 9,12,12,16,16,11,13,14,16,17,11,13,13,16,16,15,
  152888. 15,19,18, 0,14,15,15,18,18, 9,12,12,17,16,11,13,
  152889. 12,17,16,11,12,13,15,17,15,16,15, 0,19,14,15,14,
  152890. 19,18,12,14,14, 0,16,13,14,14,19,18,13,15,16,17,
  152891. 16,15,15,17,18, 0,14,16,16,19, 0,12,14,14,16,18,
  152892. 13,15,13,17,18,13,15,14,17,18,15,18,14,18,18,16,
  152893. 17,16, 0,17, 8,11,11,15,15,10,12,12,16,16,10,13,
  152894. 13,16,16,13,15,14,17,17,14,15,17,17,18, 9,12,12,
  152895. 16,15,11,13,13,16,16,11,12,13,17,17,14,14,15,17,
  152896. 17,14,15,16, 0,18, 9,12,12,16,17,11,13,13,16,17,
  152897. 11,14,13,18,17,14,16,14,17,17,15,17,17,18,18,12,
  152898. 14,14, 0,16,13,15,15,19, 0,12,13,15, 0, 0,14,17,
  152899. 16,19, 0,16,15,18,18, 0,12,14,14,17, 0,13,14,14,
  152900. 17, 0,13,15,14, 0,18,15,16,16, 0,18,15,18,15, 0,
  152901. 17,
  152902. };
  152903. static float _vq_quantthresh__44un1__p3_0[] = {
  152904. -1.5, -0.5, 0.5, 1.5,
  152905. };
  152906. static long _vq_quantmap__44un1__p3_0[] = {
  152907. 3, 1, 0, 2, 4,
  152908. };
  152909. static encode_aux_threshmatch _vq_auxt__44un1__p3_0 = {
  152910. _vq_quantthresh__44un1__p3_0,
  152911. _vq_quantmap__44un1__p3_0,
  152912. 5,
  152913. 5
  152914. };
  152915. static static_codebook _44un1__p3_0 = {
  152916. 4, 625,
  152917. _vq_lengthlist__44un1__p3_0,
  152918. 1, -533725184, 1611661312, 3, 0,
  152919. _vq_quantlist__44un1__p3_0,
  152920. NULL,
  152921. &_vq_auxt__44un1__p3_0,
  152922. NULL,
  152923. 0
  152924. };
  152925. static long _vq_quantlist__44un1__p4_0[] = {
  152926. 2,
  152927. 1,
  152928. 3,
  152929. 0,
  152930. 4,
  152931. };
  152932. static long _vq_lengthlist__44un1__p4_0[] = {
  152933. 3, 5, 5, 9, 9, 5, 6, 6,10, 9, 5, 6, 6, 9,10,10,
  152934. 10,10,12,11, 9,10,10,12,12, 5, 7, 7,10,10, 7, 7,
  152935. 8,10,11, 7, 7, 8,10,11,10,10,11,11,13,10,10,11,
  152936. 11,13, 6, 7, 7,10,10, 7, 8, 7,11,10, 7, 8, 7,10,
  152937. 10,10,11, 9,13,11,10,11,10,13,11,10,10,10,14,13,
  152938. 10,11,11,14,13,10,10,11,13,14,12,12,13,15,15,12,
  152939. 12,13,13,14,10,10,10,12,13,10,11,10,13,13,10,11,
  152940. 11,13,13,12,13,12,14,13,12,13,13,14,13, 5, 7, 7,
  152941. 10,10, 7, 8, 8,11,10, 7, 8, 8,10,10,11,11,11,13,
  152942. 13,10,11,11,12,12, 7, 8, 8,11,11, 7, 8, 9,10,12,
  152943. 8, 9, 9,11,11,11,10,12,11,14,11,11,12,13,13, 6,
  152944. 8, 8,10,11, 7, 9, 7,12,10, 8, 9,10,11,12,10,12,
  152945. 10,14,11,11,12,11,13,13,10,11,11,14,14,10,10,11,
  152946. 13,14,11,12,12,15,13,12,11,14,12,16,12,13,14,15,
  152947. 16,10,10,11,13,14,10,11,10,14,12,11,12,12,13,14,
  152948. 12,13,11,15,12,14,14,14,15,15, 5, 7, 7,10,10, 7,
  152949. 8, 8,10,10, 7, 8, 8,10,11,10,11,10,12,12,10,11,
  152950. 11,12,13, 6, 8, 8,11,11, 8, 9, 9,12,11, 7, 7, 9,
  152951. 10,12,11,11,11,12,13,11,10,12,11,15, 7, 8, 8,11,
  152952. 11, 8, 9, 9,11,11, 7, 9, 8,12,10,11,12,11,13,12,
  152953. 11,12,10,15,11,10,11,10,14,12,11,12,11,14,13,10,
  152954. 10,11,13,14,13,13,13,17,15,12,11,14,12,15,10,10,
  152955. 11,13,14,11,12,12,14,14,10,11,10,14,13,13,14,13,
  152956. 16,17,12,14,11,16,12, 9,10,10,14,13,10,11,10,14,
  152957. 14,10,11,11,13,13,13,14,14,16,15,12,13,13,14,14,
  152958. 9,11,10,14,13,10,10,12,13,14,11,12,11,14,13,13,
  152959. 14,14,14,15,13,14,14,15,15, 9,10,11,13,14,10,11,
  152960. 10,15,13,11,11,12,12,15,13,14,12,15,14,13,13,14,
  152961. 14,15,12,13,12,16,14,11,11,12,15,14,13,15,13,16,
  152962. 14,13,12,15,12,17,15,16,15,16,16,12,12,13,13,15,
  152963. 11,13,11,15,14,13,13,14,15,17,13,14,12, 0,13,14,
  152964. 15,14,15, 0, 9,10,10,13,13,10,11,11,13,13,10,11,
  152965. 11,13,13,12,13,12,14,14,13,14,14,15,17, 9,10,10,
  152966. 13,13,11,12,11,15,12,10,10,11,13,16,13,14,13,15,
  152967. 14,13,13,14,15,16,10,10,11,13,14,11,11,12,13,14,
  152968. 10,12,11,14,14,13,13,13,14,15,13,15,13,16,15,12,
  152969. 13,12,15,13,12,15,13,15,15,11,11,13,14,15,15,15,
  152970. 15,15,17,13,12,14,13,17,12,12,14,14,15,13,13,14,
  152971. 14,16,11,13,11,16,15,14,16,16,17, 0,14,13,11,16,
  152972. 12,
  152973. };
  152974. static float _vq_quantthresh__44un1__p4_0[] = {
  152975. -1.5, -0.5, 0.5, 1.5,
  152976. };
  152977. static long _vq_quantmap__44un1__p4_0[] = {
  152978. 3, 1, 0, 2, 4,
  152979. };
  152980. static encode_aux_threshmatch _vq_auxt__44un1__p4_0 = {
  152981. _vq_quantthresh__44un1__p4_0,
  152982. _vq_quantmap__44un1__p4_0,
  152983. 5,
  152984. 5
  152985. };
  152986. static static_codebook _44un1__p4_0 = {
  152987. 4, 625,
  152988. _vq_lengthlist__44un1__p4_0,
  152989. 1, -533725184, 1611661312, 3, 0,
  152990. _vq_quantlist__44un1__p4_0,
  152991. NULL,
  152992. &_vq_auxt__44un1__p4_0,
  152993. NULL,
  152994. 0
  152995. };
  152996. static long _vq_quantlist__44un1__p5_0[] = {
  152997. 4,
  152998. 3,
  152999. 5,
  153000. 2,
  153001. 6,
  153002. 1,
  153003. 7,
  153004. 0,
  153005. 8,
  153006. };
  153007. static long _vq_lengthlist__44un1__p5_0[] = {
  153008. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  153009. 10, 9, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 7, 9, 9,
  153010. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 8, 8, 8,
  153011. 9, 9,10,10,11,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  153012. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  153013. 12,
  153014. };
  153015. static float _vq_quantthresh__44un1__p5_0[] = {
  153016. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  153017. };
  153018. static long _vq_quantmap__44un1__p5_0[] = {
  153019. 7, 5, 3, 1, 0, 2, 4, 6,
  153020. 8,
  153021. };
  153022. static encode_aux_threshmatch _vq_auxt__44un1__p5_0 = {
  153023. _vq_quantthresh__44un1__p5_0,
  153024. _vq_quantmap__44un1__p5_0,
  153025. 9,
  153026. 9
  153027. };
  153028. static static_codebook _44un1__p5_0 = {
  153029. 2, 81,
  153030. _vq_lengthlist__44un1__p5_0,
  153031. 1, -531628032, 1611661312, 4, 0,
  153032. _vq_quantlist__44un1__p5_0,
  153033. NULL,
  153034. &_vq_auxt__44un1__p5_0,
  153035. NULL,
  153036. 0
  153037. };
  153038. static long _vq_quantlist__44un1__p6_0[] = {
  153039. 6,
  153040. 5,
  153041. 7,
  153042. 4,
  153043. 8,
  153044. 3,
  153045. 9,
  153046. 2,
  153047. 10,
  153048. 1,
  153049. 11,
  153050. 0,
  153051. 12,
  153052. };
  153053. static long _vq_lengthlist__44un1__p6_0[] = {
  153054. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,15,15, 4, 5, 5,
  153055. 8, 8, 9, 9,11,11,12,12,16,16, 4, 5, 6, 8, 8, 9,
  153056. 9,11,11,12,12,14,14, 7, 8, 8, 9, 9,10,10,11,12,
  153057. 13,13,16,17, 7, 8, 8, 9, 9,10,10,12,12,12,13,15,
  153058. 15, 9,10,10,10,10,11,11,12,12,13,13,15,16, 9, 9,
  153059. 9,10,10,11,11,13,12,13,13,17,17,10,11,11,11,12,
  153060. 12,12,13,13,14,15, 0,18,10,11,11,12,12,12,13,14,
  153061. 13,14,14,17,16,11,12,12,13,13,14,14,14,14,15,16,
  153062. 17,16,11,12,12,13,13,14,14,14,14,15,15,17,17,14,
  153063. 15,15,16,16,16,17,17,16, 0,17, 0,18,14,15,15,16,
  153064. 16, 0,15,18,18, 0,16, 0, 0,
  153065. };
  153066. static float _vq_quantthresh__44un1__p6_0[] = {
  153067. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  153068. 12.5, 17.5, 22.5, 27.5,
  153069. };
  153070. static long _vq_quantmap__44un1__p6_0[] = {
  153071. 11, 9, 7, 5, 3, 1, 0, 2,
  153072. 4, 6, 8, 10, 12,
  153073. };
  153074. static encode_aux_threshmatch _vq_auxt__44un1__p6_0 = {
  153075. _vq_quantthresh__44un1__p6_0,
  153076. _vq_quantmap__44un1__p6_0,
  153077. 13,
  153078. 13
  153079. };
  153080. static static_codebook _44un1__p6_0 = {
  153081. 2, 169,
  153082. _vq_lengthlist__44un1__p6_0,
  153083. 1, -526516224, 1616117760, 4, 0,
  153084. _vq_quantlist__44un1__p6_0,
  153085. NULL,
  153086. &_vq_auxt__44un1__p6_0,
  153087. NULL,
  153088. 0
  153089. };
  153090. static long _vq_quantlist__44un1__p6_1[] = {
  153091. 2,
  153092. 1,
  153093. 3,
  153094. 0,
  153095. 4,
  153096. };
  153097. static long _vq_lengthlist__44un1__p6_1[] = {
  153098. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 6, 5, 5,
  153099. 6, 5, 6, 6, 5, 6, 6, 6, 6,
  153100. };
  153101. static float _vq_quantthresh__44un1__p6_1[] = {
  153102. -1.5, -0.5, 0.5, 1.5,
  153103. };
  153104. static long _vq_quantmap__44un1__p6_1[] = {
  153105. 3, 1, 0, 2, 4,
  153106. };
  153107. static encode_aux_threshmatch _vq_auxt__44un1__p6_1 = {
  153108. _vq_quantthresh__44un1__p6_1,
  153109. _vq_quantmap__44un1__p6_1,
  153110. 5,
  153111. 5
  153112. };
  153113. static static_codebook _44un1__p6_1 = {
  153114. 2, 25,
  153115. _vq_lengthlist__44un1__p6_1,
  153116. 1, -533725184, 1611661312, 3, 0,
  153117. _vq_quantlist__44un1__p6_1,
  153118. NULL,
  153119. &_vq_auxt__44un1__p6_1,
  153120. NULL,
  153121. 0
  153122. };
  153123. static long _vq_quantlist__44un1__p7_0[] = {
  153124. 2,
  153125. 1,
  153126. 3,
  153127. 0,
  153128. 4,
  153129. };
  153130. static long _vq_lengthlist__44un1__p7_0[] = {
  153131. 1, 5, 3,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  153132. 11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,11,
  153133. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153134. 11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153135. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153136. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153137. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153138. 11,11,11,11,11,11,11,11,11,11,11,11,11, 8,11,11,
  153139. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153140. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153141. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  153142. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153143. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153144. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153145. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153146. 11,11,11,11,11,11,11,11,11,11, 7,11,11,11,11,11,
  153147. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153148. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  153149. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153150. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153151. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153152. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153153. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153154. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153155. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153156. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153157. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153158. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153159. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153160. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153161. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153162. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153163. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153164. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153165. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153166. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153167. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  153168. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  153169. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  153170. 10,
  153171. };
  153172. static float _vq_quantthresh__44un1__p7_0[] = {
  153173. -253.5, -84.5, 84.5, 253.5,
  153174. };
  153175. static long _vq_quantmap__44un1__p7_0[] = {
  153176. 3, 1, 0, 2, 4,
  153177. };
  153178. static encode_aux_threshmatch _vq_auxt__44un1__p7_0 = {
  153179. _vq_quantthresh__44un1__p7_0,
  153180. _vq_quantmap__44un1__p7_0,
  153181. 5,
  153182. 5
  153183. };
  153184. static static_codebook _44un1__p7_0 = {
  153185. 4, 625,
  153186. _vq_lengthlist__44un1__p7_0,
  153187. 1, -518709248, 1626677248, 3, 0,
  153188. _vq_quantlist__44un1__p7_0,
  153189. NULL,
  153190. &_vq_auxt__44un1__p7_0,
  153191. NULL,
  153192. 0
  153193. };
  153194. static long _vq_quantlist__44un1__p7_1[] = {
  153195. 6,
  153196. 5,
  153197. 7,
  153198. 4,
  153199. 8,
  153200. 3,
  153201. 9,
  153202. 2,
  153203. 10,
  153204. 1,
  153205. 11,
  153206. 0,
  153207. 12,
  153208. };
  153209. static long _vq_lengthlist__44un1__p7_1[] = {
  153210. 1, 4, 4, 6, 6, 6, 6, 9, 8, 9, 8, 8, 8, 5, 7, 7,
  153211. 7, 7, 8, 8, 8,10, 8,10, 8, 9, 5, 7, 7, 8, 7, 7,
  153212. 8,10,10,11,10,12,11, 7, 8, 8, 9, 9, 9,10,11,11,
  153213. 11,11,11,11, 7, 8, 8, 8, 9, 9, 9,10,10,10,11,11,
  153214. 12, 7, 8, 8, 9, 9,10,11,11,12,11,12,11,11, 7, 8,
  153215. 8, 9, 9,10,10,11,11,11,12,12,11, 8,10,10,10,10,
  153216. 11,11,14,11,12,12,12,13, 9,10,10,10,10,12,11,14,
  153217. 11,14,11,12,13,10,11,11,11,11,13,11,14,14,13,13,
  153218. 13,14,11,11,11,12,11,12,12,12,13,14,14,13,14,12,
  153219. 11,12,12,12,12,13,13,13,14,13,14,14,11,12,12,14,
  153220. 12,13,13,12,13,13,14,14,14,
  153221. };
  153222. static float _vq_quantthresh__44un1__p7_1[] = {
  153223. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  153224. 32.5, 45.5, 58.5, 71.5,
  153225. };
  153226. static long _vq_quantmap__44un1__p7_1[] = {
  153227. 11, 9, 7, 5, 3, 1, 0, 2,
  153228. 4, 6, 8, 10, 12,
  153229. };
  153230. static encode_aux_threshmatch _vq_auxt__44un1__p7_1 = {
  153231. _vq_quantthresh__44un1__p7_1,
  153232. _vq_quantmap__44un1__p7_1,
  153233. 13,
  153234. 13
  153235. };
  153236. static static_codebook _44un1__p7_1 = {
  153237. 2, 169,
  153238. _vq_lengthlist__44un1__p7_1,
  153239. 1, -523010048, 1618608128, 4, 0,
  153240. _vq_quantlist__44un1__p7_1,
  153241. NULL,
  153242. &_vq_auxt__44un1__p7_1,
  153243. NULL,
  153244. 0
  153245. };
  153246. static long _vq_quantlist__44un1__p7_2[] = {
  153247. 6,
  153248. 5,
  153249. 7,
  153250. 4,
  153251. 8,
  153252. 3,
  153253. 9,
  153254. 2,
  153255. 10,
  153256. 1,
  153257. 11,
  153258. 0,
  153259. 12,
  153260. };
  153261. static long _vq_lengthlist__44un1__p7_2[] = {
  153262. 3, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9, 9, 8, 4, 5, 5,
  153263. 6, 6, 8, 8, 9, 8, 9, 9, 9, 9, 4, 5, 5, 7, 6, 8,
  153264. 8, 8, 8, 9, 8, 9, 8, 6, 7, 7, 7, 8, 8, 8, 9, 9,
  153265. 9, 9, 9, 9, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  153266. 9, 7, 8, 8, 8, 8, 9, 8, 9, 9,10, 9, 9,10, 7, 8,
  153267. 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 8, 9, 9, 9, 9,
  153268. 9, 9, 9, 9,10,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9,
  153269. 9, 9, 9,10,10, 9, 9, 9,10, 9, 9,10, 9, 9,10,10,
  153270. 10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10, 9,
  153271. 9, 9,10, 9, 9,10,10, 9,10,10,10,10, 9, 9, 9,10,
  153272. 9, 9, 9,10,10,10,10,10,10,
  153273. };
  153274. static float _vq_quantthresh__44un1__p7_2[] = {
  153275. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  153276. 2.5, 3.5, 4.5, 5.5,
  153277. };
  153278. static long _vq_quantmap__44un1__p7_2[] = {
  153279. 11, 9, 7, 5, 3, 1, 0, 2,
  153280. 4, 6, 8, 10, 12,
  153281. };
  153282. static encode_aux_threshmatch _vq_auxt__44un1__p7_2 = {
  153283. _vq_quantthresh__44un1__p7_2,
  153284. _vq_quantmap__44un1__p7_2,
  153285. 13,
  153286. 13
  153287. };
  153288. static static_codebook _44un1__p7_2 = {
  153289. 2, 169,
  153290. _vq_lengthlist__44un1__p7_2,
  153291. 1, -531103744, 1611661312, 4, 0,
  153292. _vq_quantlist__44un1__p7_2,
  153293. NULL,
  153294. &_vq_auxt__44un1__p7_2,
  153295. NULL,
  153296. 0
  153297. };
  153298. static long _huff_lengthlist__44un1__short[] = {
  153299. 12,12,14,12,14,14,14,14,12, 6, 6, 8, 9, 9,11,14,
  153300. 12, 4, 2, 6, 6, 7,11,14,13, 6, 5, 7, 8, 9,11,14,
  153301. 13, 8, 5, 8, 6, 8,12,14,12, 7, 7, 8, 8, 8,10,14,
  153302. 12, 6, 3, 4, 4, 4, 7,14,11, 7, 4, 6, 6, 6, 8,14,
  153303. };
  153304. static static_codebook _huff_book__44un1__short = {
  153305. 2, 64,
  153306. _huff_lengthlist__44un1__short,
  153307. 0, 0, 0, 0, 0,
  153308. NULL,
  153309. NULL,
  153310. NULL,
  153311. NULL,
  153312. 0
  153313. };
  153314. /*** End of inlined file: res_books_uncoupled.h ***/
  153315. /***** residue backends *********************************************/
  153316. static vorbis_info_residue0 _residue_44_low_un={
  153317. 0,-1, -1, 8,-1,
  153318. {0},
  153319. {-1},
  153320. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 28.5},
  153321. { -1, 25, -1, 45, -1, -1, -1}
  153322. };
  153323. static vorbis_info_residue0 _residue_44_mid_un={
  153324. 0,-1, -1, 10,-1,
  153325. /* 0 1 2 3 4 5 6 7 8 9 */
  153326. {0},
  153327. {-1},
  153328. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 4.5, 16.5, 60.5},
  153329. { -1, 30, -1, 50, -1, 80, -1, -1, -1}
  153330. };
  153331. static vorbis_info_residue0 _residue_44_hi_un={
  153332. 0,-1, -1, 10,-1,
  153333. /* 0 1 2 3 4 5 6 7 8 9 */
  153334. {0},
  153335. {-1},
  153336. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  153337. { -1, -1, -1, -1, -1, -1, -1, -1, -1}
  153338. };
  153339. /* mapping conventions:
  153340. only one submap (this would change for efficient 5.1 support for example)*/
  153341. /* Four psychoacoustic profiles are used, one for each blocktype */
  153342. static vorbis_info_mapping0 _map_nominal_u[2]={
  153343. {1, {0,0}, {0}, {0}, 0,{0},{0}},
  153344. {1, {0,0}, {1}, {1}, 0,{0},{0}}
  153345. };
  153346. static static_bookblock _resbook_44u_n1={
  153347. {
  153348. {0},
  153349. {0,0,&_44un1__p1_0},
  153350. {0,0,&_44un1__p2_0},
  153351. {0,0,&_44un1__p3_0},
  153352. {0,0,&_44un1__p4_0},
  153353. {0,0,&_44un1__p5_0},
  153354. {&_44un1__p6_0,&_44un1__p6_1},
  153355. {&_44un1__p7_0,&_44un1__p7_1,&_44un1__p7_2}
  153356. }
  153357. };
  153358. static static_bookblock _resbook_44u_0={
  153359. {
  153360. {0},
  153361. {0,0,&_44u0__p1_0},
  153362. {0,0,&_44u0__p2_0},
  153363. {0,0,&_44u0__p3_0},
  153364. {0,0,&_44u0__p4_0},
  153365. {0,0,&_44u0__p5_0},
  153366. {&_44u0__p6_0,&_44u0__p6_1},
  153367. {&_44u0__p7_0,&_44u0__p7_1,&_44u0__p7_2}
  153368. }
  153369. };
  153370. static static_bookblock _resbook_44u_1={
  153371. {
  153372. {0},
  153373. {0,0,&_44u1__p1_0},
  153374. {0,0,&_44u1__p2_0},
  153375. {0,0,&_44u1__p3_0},
  153376. {0,0,&_44u1__p4_0},
  153377. {0,0,&_44u1__p5_0},
  153378. {&_44u1__p6_0,&_44u1__p6_1},
  153379. {&_44u1__p7_0,&_44u1__p7_1,&_44u1__p7_2}
  153380. }
  153381. };
  153382. static static_bookblock _resbook_44u_2={
  153383. {
  153384. {0},
  153385. {0,0,&_44u2__p1_0},
  153386. {0,0,&_44u2__p2_0},
  153387. {0,0,&_44u2__p3_0},
  153388. {0,0,&_44u2__p4_0},
  153389. {0,0,&_44u2__p5_0},
  153390. {&_44u2__p6_0,&_44u2__p6_1},
  153391. {&_44u2__p7_0,&_44u2__p7_1,&_44u2__p7_2}
  153392. }
  153393. };
  153394. static static_bookblock _resbook_44u_3={
  153395. {
  153396. {0},
  153397. {0,0,&_44u3__p1_0},
  153398. {0,0,&_44u3__p2_0},
  153399. {0,0,&_44u3__p3_0},
  153400. {0,0,&_44u3__p4_0},
  153401. {0,0,&_44u3__p5_0},
  153402. {&_44u3__p6_0,&_44u3__p6_1},
  153403. {&_44u3__p7_0,&_44u3__p7_1,&_44u3__p7_2}
  153404. }
  153405. };
  153406. static static_bookblock _resbook_44u_4={
  153407. {
  153408. {0},
  153409. {0,0,&_44u4__p1_0},
  153410. {0,0,&_44u4__p2_0},
  153411. {0,0,&_44u4__p3_0},
  153412. {0,0,&_44u4__p4_0},
  153413. {0,0,&_44u4__p5_0},
  153414. {&_44u4__p6_0,&_44u4__p6_1},
  153415. {&_44u4__p7_0,&_44u4__p7_1,&_44u4__p7_2}
  153416. }
  153417. };
  153418. static static_bookblock _resbook_44u_5={
  153419. {
  153420. {0},
  153421. {0,0,&_44u5__p1_0},
  153422. {0,0,&_44u5__p2_0},
  153423. {0,0,&_44u5__p3_0},
  153424. {0,0,&_44u5__p4_0},
  153425. {0,0,&_44u5__p5_0},
  153426. {0,0,&_44u5__p6_0},
  153427. {&_44u5__p7_0,&_44u5__p7_1},
  153428. {&_44u5__p8_0,&_44u5__p8_1},
  153429. {&_44u5__p9_0,&_44u5__p9_1,&_44u5__p9_2}
  153430. }
  153431. };
  153432. static static_bookblock _resbook_44u_6={
  153433. {
  153434. {0},
  153435. {0,0,&_44u6__p1_0},
  153436. {0,0,&_44u6__p2_0},
  153437. {0,0,&_44u6__p3_0},
  153438. {0,0,&_44u6__p4_0},
  153439. {0,0,&_44u6__p5_0},
  153440. {0,0,&_44u6__p6_0},
  153441. {&_44u6__p7_0,&_44u6__p7_1},
  153442. {&_44u6__p8_0,&_44u6__p8_1},
  153443. {&_44u6__p9_0,&_44u6__p9_1,&_44u6__p9_2}
  153444. }
  153445. };
  153446. static static_bookblock _resbook_44u_7={
  153447. {
  153448. {0},
  153449. {0,0,&_44u7__p1_0},
  153450. {0,0,&_44u7__p2_0},
  153451. {0,0,&_44u7__p3_0},
  153452. {0,0,&_44u7__p4_0},
  153453. {0,0,&_44u7__p5_0},
  153454. {0,0,&_44u7__p6_0},
  153455. {&_44u7__p7_0,&_44u7__p7_1},
  153456. {&_44u7__p8_0,&_44u7__p8_1},
  153457. {&_44u7__p9_0,&_44u7__p9_1,&_44u7__p9_2}
  153458. }
  153459. };
  153460. static static_bookblock _resbook_44u_8={
  153461. {
  153462. {0},
  153463. {0,0,&_44u8_p1_0},
  153464. {0,0,&_44u8_p2_0},
  153465. {0,0,&_44u8_p3_0},
  153466. {0,0,&_44u8_p4_0},
  153467. {&_44u8_p5_0,&_44u8_p5_1},
  153468. {&_44u8_p6_0,&_44u8_p6_1},
  153469. {&_44u8_p7_0,&_44u8_p7_1},
  153470. {&_44u8_p8_0,&_44u8_p8_1},
  153471. {&_44u8_p9_0,&_44u8_p9_1,&_44u8_p9_2}
  153472. }
  153473. };
  153474. static static_bookblock _resbook_44u_9={
  153475. {
  153476. {0},
  153477. {0,0,&_44u9_p1_0},
  153478. {0,0,&_44u9_p2_0},
  153479. {0,0,&_44u9_p3_0},
  153480. {0,0,&_44u9_p4_0},
  153481. {&_44u9_p5_0,&_44u9_p5_1},
  153482. {&_44u9_p6_0,&_44u9_p6_1},
  153483. {&_44u9_p7_0,&_44u9_p7_1},
  153484. {&_44u9_p8_0,&_44u9_p8_1},
  153485. {&_44u9_p9_0,&_44u9_p9_1,&_44u9_p9_2}
  153486. }
  153487. };
  153488. static vorbis_residue_template _res_44u_n1[]={
  153489. {1,0, &_residue_44_low_un,
  153490. &_huff_book__44un1__short,&_huff_book__44un1__short,
  153491. &_resbook_44u_n1,&_resbook_44u_n1},
  153492. {1,0, &_residue_44_low_un,
  153493. &_huff_book__44un1__long,&_huff_book__44un1__long,
  153494. &_resbook_44u_n1,&_resbook_44u_n1}
  153495. };
  153496. static vorbis_residue_template _res_44u_0[]={
  153497. {1,0, &_residue_44_low_un,
  153498. &_huff_book__44u0__short,&_huff_book__44u0__short,
  153499. &_resbook_44u_0,&_resbook_44u_0},
  153500. {1,0, &_residue_44_low_un,
  153501. &_huff_book__44u0__long,&_huff_book__44u0__long,
  153502. &_resbook_44u_0,&_resbook_44u_0}
  153503. };
  153504. static vorbis_residue_template _res_44u_1[]={
  153505. {1,0, &_residue_44_low_un,
  153506. &_huff_book__44u1__short,&_huff_book__44u1__short,
  153507. &_resbook_44u_1,&_resbook_44u_1},
  153508. {1,0, &_residue_44_low_un,
  153509. &_huff_book__44u1__long,&_huff_book__44u1__long,
  153510. &_resbook_44u_1,&_resbook_44u_1}
  153511. };
  153512. static vorbis_residue_template _res_44u_2[]={
  153513. {1,0, &_residue_44_low_un,
  153514. &_huff_book__44u2__short,&_huff_book__44u2__short,
  153515. &_resbook_44u_2,&_resbook_44u_2},
  153516. {1,0, &_residue_44_low_un,
  153517. &_huff_book__44u2__long,&_huff_book__44u2__long,
  153518. &_resbook_44u_2,&_resbook_44u_2}
  153519. };
  153520. static vorbis_residue_template _res_44u_3[]={
  153521. {1,0, &_residue_44_low_un,
  153522. &_huff_book__44u3__short,&_huff_book__44u3__short,
  153523. &_resbook_44u_3,&_resbook_44u_3},
  153524. {1,0, &_residue_44_low_un,
  153525. &_huff_book__44u3__long,&_huff_book__44u3__long,
  153526. &_resbook_44u_3,&_resbook_44u_3}
  153527. };
  153528. static vorbis_residue_template _res_44u_4[]={
  153529. {1,0, &_residue_44_low_un,
  153530. &_huff_book__44u4__short,&_huff_book__44u4__short,
  153531. &_resbook_44u_4,&_resbook_44u_4},
  153532. {1,0, &_residue_44_low_un,
  153533. &_huff_book__44u4__long,&_huff_book__44u4__long,
  153534. &_resbook_44u_4,&_resbook_44u_4}
  153535. };
  153536. static vorbis_residue_template _res_44u_5[]={
  153537. {1,0, &_residue_44_mid_un,
  153538. &_huff_book__44u5__short,&_huff_book__44u5__short,
  153539. &_resbook_44u_5,&_resbook_44u_5},
  153540. {1,0, &_residue_44_mid_un,
  153541. &_huff_book__44u5__long,&_huff_book__44u5__long,
  153542. &_resbook_44u_5,&_resbook_44u_5}
  153543. };
  153544. static vorbis_residue_template _res_44u_6[]={
  153545. {1,0, &_residue_44_mid_un,
  153546. &_huff_book__44u6__short,&_huff_book__44u6__short,
  153547. &_resbook_44u_6,&_resbook_44u_6},
  153548. {1,0, &_residue_44_mid_un,
  153549. &_huff_book__44u6__long,&_huff_book__44u6__long,
  153550. &_resbook_44u_6,&_resbook_44u_6}
  153551. };
  153552. static vorbis_residue_template _res_44u_7[]={
  153553. {1,0, &_residue_44_mid_un,
  153554. &_huff_book__44u7__short,&_huff_book__44u7__short,
  153555. &_resbook_44u_7,&_resbook_44u_7},
  153556. {1,0, &_residue_44_mid_un,
  153557. &_huff_book__44u7__long,&_huff_book__44u7__long,
  153558. &_resbook_44u_7,&_resbook_44u_7}
  153559. };
  153560. static vorbis_residue_template _res_44u_8[]={
  153561. {1,0, &_residue_44_hi_un,
  153562. &_huff_book__44u8__short,&_huff_book__44u8__short,
  153563. &_resbook_44u_8,&_resbook_44u_8},
  153564. {1,0, &_residue_44_hi_un,
  153565. &_huff_book__44u8__long,&_huff_book__44u8__long,
  153566. &_resbook_44u_8,&_resbook_44u_8}
  153567. };
  153568. static vorbis_residue_template _res_44u_9[]={
  153569. {1,0, &_residue_44_hi_un,
  153570. &_huff_book__44u9__short,&_huff_book__44u9__short,
  153571. &_resbook_44u_9,&_resbook_44u_9},
  153572. {1,0, &_residue_44_hi_un,
  153573. &_huff_book__44u9__long,&_huff_book__44u9__long,
  153574. &_resbook_44u_9,&_resbook_44u_9}
  153575. };
  153576. static vorbis_mapping_template _mapres_template_44_uncoupled[]={
  153577. { _map_nominal_u, _res_44u_n1 }, /* -1 */
  153578. { _map_nominal_u, _res_44u_0 }, /* 0 */
  153579. { _map_nominal_u, _res_44u_1 }, /* 1 */
  153580. { _map_nominal_u, _res_44u_2 }, /* 2 */
  153581. { _map_nominal_u, _res_44u_3 }, /* 3 */
  153582. { _map_nominal_u, _res_44u_4 }, /* 4 */
  153583. { _map_nominal_u, _res_44u_5 }, /* 5 */
  153584. { _map_nominal_u, _res_44u_6 }, /* 6 */
  153585. { _map_nominal_u, _res_44u_7 }, /* 7 */
  153586. { _map_nominal_u, _res_44u_8 }, /* 8 */
  153587. { _map_nominal_u, _res_44u_9 }, /* 9 */
  153588. };
  153589. /*** End of inlined file: residue_44u.h ***/
  153590. static double rate_mapping_44_un[12]={
  153591. 32000.,48000.,60000.,70000.,80000.,86000.,
  153592. 96000.,110000.,120000.,140000.,160000.,240001.
  153593. };
  153594. ve_setup_data_template ve_setup_44_uncoupled={
  153595. 11,
  153596. rate_mapping_44_un,
  153597. quality_mapping_44,
  153598. -1,
  153599. 40000,
  153600. 50000,
  153601. blocksize_short_44,
  153602. blocksize_long_44,
  153603. _psy_tone_masteratt_44,
  153604. _psy_tone_0dB,
  153605. _psy_tone_suppress,
  153606. _vp_tonemask_adj_otherblock,
  153607. _vp_tonemask_adj_longblock,
  153608. _vp_tonemask_adj_otherblock,
  153609. _psy_noiseguards_44,
  153610. _psy_noisebias_impulse,
  153611. _psy_noisebias_padding,
  153612. _psy_noisebias_trans,
  153613. _psy_noisebias_long,
  153614. _psy_noise_suppress,
  153615. _psy_compand_44,
  153616. _psy_compand_short_mapping,
  153617. _psy_compand_long_mapping,
  153618. {_noise_start_short_44,_noise_start_long_44},
  153619. {_noise_part_short_44,_noise_part_long_44},
  153620. _noise_thresh_44,
  153621. _psy_ath_floater,
  153622. _psy_ath_abs,
  153623. _psy_lowpass_44,
  153624. _psy_global_44,
  153625. _global_mapping_44,
  153626. NULL,
  153627. _floor_books,
  153628. _floor,
  153629. _floor_short_mapping_44,
  153630. _floor_long_mapping_44,
  153631. _mapres_template_44_uncoupled
  153632. };
  153633. /*** End of inlined file: setup_44u.h ***/
  153634. /*** Start of inlined file: setup_32.h ***/
  153635. static double rate_mapping_32[12]={
  153636. 18000.,28000.,35000.,45000.,56000.,60000.,
  153637. 75000.,90000.,100000.,115000.,150000.,190000.,
  153638. };
  153639. static double rate_mapping_32_un[12]={
  153640. 30000.,42000.,52000.,64000.,72000.,78000.,
  153641. 86000.,92000.,110000.,120000.,140000.,190000.,
  153642. };
  153643. static double _psy_lowpass_32[12]={
  153644. 12.3,13.,13.,14.,15.,99.,99.,99.,99.,99.,99.,99.
  153645. };
  153646. ve_setup_data_template ve_setup_32_stereo={
  153647. 11,
  153648. rate_mapping_32,
  153649. quality_mapping_44,
  153650. 2,
  153651. 26000,
  153652. 40000,
  153653. blocksize_short_44,
  153654. blocksize_long_44,
  153655. _psy_tone_masteratt_44,
  153656. _psy_tone_0dB,
  153657. _psy_tone_suppress,
  153658. _vp_tonemask_adj_otherblock,
  153659. _vp_tonemask_adj_longblock,
  153660. _vp_tonemask_adj_otherblock,
  153661. _psy_noiseguards_44,
  153662. _psy_noisebias_impulse,
  153663. _psy_noisebias_padding,
  153664. _psy_noisebias_trans,
  153665. _psy_noisebias_long,
  153666. _psy_noise_suppress,
  153667. _psy_compand_44,
  153668. _psy_compand_short_mapping,
  153669. _psy_compand_long_mapping,
  153670. {_noise_start_short_44,_noise_start_long_44},
  153671. {_noise_part_short_44,_noise_part_long_44},
  153672. _noise_thresh_44,
  153673. _psy_ath_floater,
  153674. _psy_ath_abs,
  153675. _psy_lowpass_32,
  153676. _psy_global_44,
  153677. _global_mapping_44,
  153678. _psy_stereo_modes_44,
  153679. _floor_books,
  153680. _floor,
  153681. _floor_short_mapping_44,
  153682. _floor_long_mapping_44,
  153683. _mapres_template_44_stereo
  153684. };
  153685. ve_setup_data_template ve_setup_32_uncoupled={
  153686. 11,
  153687. rate_mapping_32_un,
  153688. quality_mapping_44,
  153689. -1,
  153690. 26000,
  153691. 40000,
  153692. blocksize_short_44,
  153693. blocksize_long_44,
  153694. _psy_tone_masteratt_44,
  153695. _psy_tone_0dB,
  153696. _psy_tone_suppress,
  153697. _vp_tonemask_adj_otherblock,
  153698. _vp_tonemask_adj_longblock,
  153699. _vp_tonemask_adj_otherblock,
  153700. _psy_noiseguards_44,
  153701. _psy_noisebias_impulse,
  153702. _psy_noisebias_padding,
  153703. _psy_noisebias_trans,
  153704. _psy_noisebias_long,
  153705. _psy_noise_suppress,
  153706. _psy_compand_44,
  153707. _psy_compand_short_mapping,
  153708. _psy_compand_long_mapping,
  153709. {_noise_start_short_44,_noise_start_long_44},
  153710. {_noise_part_short_44,_noise_part_long_44},
  153711. _noise_thresh_44,
  153712. _psy_ath_floater,
  153713. _psy_ath_abs,
  153714. _psy_lowpass_32,
  153715. _psy_global_44,
  153716. _global_mapping_44,
  153717. NULL,
  153718. _floor_books,
  153719. _floor,
  153720. _floor_short_mapping_44,
  153721. _floor_long_mapping_44,
  153722. _mapres_template_44_uncoupled
  153723. };
  153724. /*** End of inlined file: setup_32.h ***/
  153725. /*** Start of inlined file: setup_8.h ***/
  153726. /*** Start of inlined file: psych_8.h ***/
  153727. static att3 _psy_tone_masteratt_8[3]={
  153728. {{ 32, 25, 12}, 0, 0}, /* 0 */
  153729. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153730. {{ 20, 0, -14}, 0, 0}, /* 0 */
  153731. };
  153732. static vp_adjblock _vp_tonemask_adj_8[3]={
  153733. /* adjust for mode zero */
  153734. /* 63 125 250 500 1 2 4 8 16 */
  153735. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  153736. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  153737. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 1 */
  153738. };
  153739. static noise3 _psy_noisebias_8[3]={
  153740. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153741. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  153742. {-10,-10,-10,-10, -5, -5, -5, 0, 0, 4, 4, 4, 4, 4, 99, 99, 99},
  153743. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153744. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  153745. {-10,-10,-10,-10,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  153746. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153747. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  153748. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  153749. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  153750. };
  153751. /* stereo mode by base quality level */
  153752. static adj_stereo _psy_stereo_modes_8[3]={
  153753. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  153754. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153755. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153756. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153757. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153758. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153759. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153760. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153761. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153762. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153763. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153764. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153765. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153766. };
  153767. static noiseguard _psy_noiseguards_8[2]={
  153768. {10,10,-1},
  153769. {10,10,-1},
  153770. };
  153771. static compandblock _psy_compand_8[2]={
  153772. {{
  153773. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  153774. 8, 8, 9, 9,10,10,11, 11, /* 15dB */
  153775. 12,12,13,13,14,14,15, 15, /* 23dB */
  153776. 16,16,17,17,17,18,18, 19, /* 31dB */
  153777. 19,19,20,21,22,23,24, 25, /* 39dB */
  153778. }},
  153779. {{
  153780. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  153781. 7, 7, 6, 6, 5, 5, 4, 4, /* 15dB */
  153782. 3, 3, 3, 4, 5, 6, 7, 8, /* 23dB */
  153783. 9,10,11,12,13,14,15, 16, /* 31dB */
  153784. 17,18,19,20,21,22,23, 24, /* 39dB */
  153785. }},
  153786. };
  153787. static double _psy_lowpass_8[3]={3.,4.,4.};
  153788. static int _noise_start_8[2]={
  153789. 64,64,
  153790. };
  153791. static int _noise_part_8[2]={
  153792. 8,8,
  153793. };
  153794. static int _psy_ath_floater_8[3]={
  153795. -100,-100,-105,
  153796. };
  153797. static int _psy_ath_abs_8[3]={
  153798. -130,-130,-140,
  153799. };
  153800. /*** End of inlined file: psych_8.h ***/
  153801. /*** Start of inlined file: residue_8.h ***/
  153802. /***** residue backends *********************************************/
  153803. static static_bookblock _resbook_8s_0={
  153804. {
  153805. {0},{0,0,&_8c0_s_p1_0},{0,0,&_8c0_s_p2_0},{0,0,&_8c0_s_p3_0},
  153806. {0,0,&_8c0_s_p4_0},{0,0,&_8c0_s_p5_0},{0,0,&_8c0_s_p6_0},
  153807. {&_8c0_s_p7_0,&_8c0_s_p7_1},{&_8c0_s_p8_0,&_8c0_s_p8_1},
  153808. {&_8c0_s_p9_0,&_8c0_s_p9_1,&_8c0_s_p9_2}
  153809. }
  153810. };
  153811. static static_bookblock _resbook_8s_1={
  153812. {
  153813. {0},{0,0,&_8c1_s_p1_0},{0,0,&_8c1_s_p2_0},{0,0,&_8c1_s_p3_0},
  153814. {0,0,&_8c1_s_p4_0},{0,0,&_8c1_s_p5_0},{0,0,&_8c1_s_p6_0},
  153815. {&_8c1_s_p7_0,&_8c1_s_p7_1},{&_8c1_s_p8_0,&_8c1_s_p8_1},
  153816. {&_8c1_s_p9_0,&_8c1_s_p9_1,&_8c1_s_p9_2}
  153817. }
  153818. };
  153819. static vorbis_residue_template _res_8s_0[]={
  153820. {2,0, &_residue_44_mid,
  153821. &_huff_book__8c0_s_single,&_huff_book__8c0_s_single,
  153822. &_resbook_8s_0,&_resbook_8s_0},
  153823. };
  153824. static vorbis_residue_template _res_8s_1[]={
  153825. {2,0, &_residue_44_mid,
  153826. &_huff_book__8c1_s_single,&_huff_book__8c1_s_single,
  153827. &_resbook_8s_1,&_resbook_8s_1},
  153828. };
  153829. static vorbis_mapping_template _mapres_template_8_stereo[2]={
  153830. { _map_nominal, _res_8s_0 }, /* 0 */
  153831. { _map_nominal, _res_8s_1 }, /* 1 */
  153832. };
  153833. static static_bookblock _resbook_8u_0={
  153834. {
  153835. {0},
  153836. {0,0,&_8u0__p1_0},
  153837. {0,0,&_8u0__p2_0},
  153838. {0,0,&_8u0__p3_0},
  153839. {0,0,&_8u0__p4_0},
  153840. {0,0,&_8u0__p5_0},
  153841. {&_8u0__p6_0,&_8u0__p6_1},
  153842. {&_8u0__p7_0,&_8u0__p7_1,&_8u0__p7_2}
  153843. }
  153844. };
  153845. static static_bookblock _resbook_8u_1={
  153846. {
  153847. {0},
  153848. {0,0,&_8u1__p1_0},
  153849. {0,0,&_8u1__p2_0},
  153850. {0,0,&_8u1__p3_0},
  153851. {0,0,&_8u1__p4_0},
  153852. {0,0,&_8u1__p5_0},
  153853. {0,0,&_8u1__p6_0},
  153854. {&_8u1__p7_0,&_8u1__p7_1},
  153855. {&_8u1__p8_0,&_8u1__p8_1},
  153856. {&_8u1__p9_0,&_8u1__p9_1,&_8u1__p9_2}
  153857. }
  153858. };
  153859. static vorbis_residue_template _res_8u_0[]={
  153860. {1,0, &_residue_44_low_un,
  153861. &_huff_book__8u0__single,&_huff_book__8u0__single,
  153862. &_resbook_8u_0,&_resbook_8u_0},
  153863. };
  153864. static vorbis_residue_template _res_8u_1[]={
  153865. {1,0, &_residue_44_mid_un,
  153866. &_huff_book__8u1__single,&_huff_book__8u1__single,
  153867. &_resbook_8u_1,&_resbook_8u_1},
  153868. };
  153869. static vorbis_mapping_template _mapres_template_8_uncoupled[2]={
  153870. { _map_nominal_u, _res_8u_0 }, /* 0 */
  153871. { _map_nominal_u, _res_8u_1 }, /* 1 */
  153872. };
  153873. /*** End of inlined file: residue_8.h ***/
  153874. static int blocksize_8[2]={
  153875. 512,512
  153876. };
  153877. static int _floor_mapping_8[2]={
  153878. 6,6,
  153879. };
  153880. static double rate_mapping_8[3]={
  153881. 6000.,9000.,32000.,
  153882. };
  153883. static double rate_mapping_8_uncoupled[3]={
  153884. 8000.,14000.,42000.,
  153885. };
  153886. static double quality_mapping_8[3]={
  153887. -.1,.0,1.
  153888. };
  153889. static double _psy_compand_8_mapping[3]={ 0., 1., 1.};
  153890. static double _global_mapping_8[3]={ 1., 2., 3. };
  153891. ve_setup_data_template ve_setup_8_stereo={
  153892. 2,
  153893. rate_mapping_8,
  153894. quality_mapping_8,
  153895. 2,
  153896. 8000,
  153897. 9000,
  153898. blocksize_8,
  153899. blocksize_8,
  153900. _psy_tone_masteratt_8,
  153901. _psy_tone_0dB,
  153902. _psy_tone_suppress,
  153903. _vp_tonemask_adj_8,
  153904. NULL,
  153905. _vp_tonemask_adj_8,
  153906. _psy_noiseguards_8,
  153907. _psy_noisebias_8,
  153908. _psy_noisebias_8,
  153909. NULL,
  153910. NULL,
  153911. _psy_noise_suppress,
  153912. _psy_compand_8,
  153913. _psy_compand_8_mapping,
  153914. NULL,
  153915. {_noise_start_8,_noise_start_8},
  153916. {_noise_part_8,_noise_part_8},
  153917. _noise_thresh_5only,
  153918. _psy_ath_floater_8,
  153919. _psy_ath_abs_8,
  153920. _psy_lowpass_8,
  153921. _psy_global_44,
  153922. _global_mapping_8,
  153923. _psy_stereo_modes_8,
  153924. _floor_books,
  153925. _floor,
  153926. _floor_mapping_8,
  153927. NULL,
  153928. _mapres_template_8_stereo
  153929. };
  153930. ve_setup_data_template ve_setup_8_uncoupled={
  153931. 2,
  153932. rate_mapping_8_uncoupled,
  153933. quality_mapping_8,
  153934. -1,
  153935. 8000,
  153936. 9000,
  153937. blocksize_8,
  153938. blocksize_8,
  153939. _psy_tone_masteratt_8,
  153940. _psy_tone_0dB,
  153941. _psy_tone_suppress,
  153942. _vp_tonemask_adj_8,
  153943. NULL,
  153944. _vp_tonemask_adj_8,
  153945. _psy_noiseguards_8,
  153946. _psy_noisebias_8,
  153947. _psy_noisebias_8,
  153948. NULL,
  153949. NULL,
  153950. _psy_noise_suppress,
  153951. _psy_compand_8,
  153952. _psy_compand_8_mapping,
  153953. NULL,
  153954. {_noise_start_8,_noise_start_8},
  153955. {_noise_part_8,_noise_part_8},
  153956. _noise_thresh_5only,
  153957. _psy_ath_floater_8,
  153958. _psy_ath_abs_8,
  153959. _psy_lowpass_8,
  153960. _psy_global_44,
  153961. _global_mapping_8,
  153962. _psy_stereo_modes_8,
  153963. _floor_books,
  153964. _floor,
  153965. _floor_mapping_8,
  153966. NULL,
  153967. _mapres_template_8_uncoupled
  153968. };
  153969. /*** End of inlined file: setup_8.h ***/
  153970. /*** Start of inlined file: setup_11.h ***/
  153971. /*** Start of inlined file: psych_11.h ***/
  153972. static double _psy_lowpass_11[3]={4.5,5.5,30.,};
  153973. static att3 _psy_tone_masteratt_11[3]={
  153974. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153975. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153976. {{ 20, 0, -14}, 0, 0}, /* 0 */
  153977. };
  153978. static vp_adjblock _vp_tonemask_adj_11[3]={
  153979. /* adjust for mode zero */
  153980. /* 63 125 250 500 1 2 4 8 16 */
  153981. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 2, 0,99,99,99}}, /* 0 */
  153982. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 5, 0, 0,99,99,99}}, /* 1 */
  153983. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 2 */
  153984. };
  153985. static noise3 _psy_noisebias_11[3]={
  153986. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153987. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  153988. {-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 4, 5, 5, 10, 99, 99, 99},
  153989. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153990. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  153991. {-15,-15,-15,-15,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  153992. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153993. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  153994. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  153995. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  153996. };
  153997. static double _noise_thresh_11[3]={ .3,.5,.5 };
  153998. /*** End of inlined file: psych_11.h ***/
  153999. static int blocksize_11[2]={
  154000. 512,512
  154001. };
  154002. static int _floor_mapping_11[2]={
  154003. 6,6,
  154004. };
  154005. static double rate_mapping_11[3]={
  154006. 8000.,13000.,44000.,
  154007. };
  154008. static double rate_mapping_11_uncoupled[3]={
  154009. 12000.,20000.,50000.,
  154010. };
  154011. static double quality_mapping_11[3]={
  154012. -.1,.0,1.
  154013. };
  154014. ve_setup_data_template ve_setup_11_stereo={
  154015. 2,
  154016. rate_mapping_11,
  154017. quality_mapping_11,
  154018. 2,
  154019. 9000,
  154020. 15000,
  154021. blocksize_11,
  154022. blocksize_11,
  154023. _psy_tone_masteratt_11,
  154024. _psy_tone_0dB,
  154025. _psy_tone_suppress,
  154026. _vp_tonemask_adj_11,
  154027. NULL,
  154028. _vp_tonemask_adj_11,
  154029. _psy_noiseguards_8,
  154030. _psy_noisebias_11,
  154031. _psy_noisebias_11,
  154032. NULL,
  154033. NULL,
  154034. _psy_noise_suppress,
  154035. _psy_compand_8,
  154036. _psy_compand_8_mapping,
  154037. NULL,
  154038. {_noise_start_8,_noise_start_8},
  154039. {_noise_part_8,_noise_part_8},
  154040. _noise_thresh_11,
  154041. _psy_ath_floater_8,
  154042. _psy_ath_abs_8,
  154043. _psy_lowpass_11,
  154044. _psy_global_44,
  154045. _global_mapping_8,
  154046. _psy_stereo_modes_8,
  154047. _floor_books,
  154048. _floor,
  154049. _floor_mapping_11,
  154050. NULL,
  154051. _mapres_template_8_stereo
  154052. };
  154053. ve_setup_data_template ve_setup_11_uncoupled={
  154054. 2,
  154055. rate_mapping_11_uncoupled,
  154056. quality_mapping_11,
  154057. -1,
  154058. 9000,
  154059. 15000,
  154060. blocksize_11,
  154061. blocksize_11,
  154062. _psy_tone_masteratt_11,
  154063. _psy_tone_0dB,
  154064. _psy_tone_suppress,
  154065. _vp_tonemask_adj_11,
  154066. NULL,
  154067. _vp_tonemask_adj_11,
  154068. _psy_noiseguards_8,
  154069. _psy_noisebias_11,
  154070. _psy_noisebias_11,
  154071. NULL,
  154072. NULL,
  154073. _psy_noise_suppress,
  154074. _psy_compand_8,
  154075. _psy_compand_8_mapping,
  154076. NULL,
  154077. {_noise_start_8,_noise_start_8},
  154078. {_noise_part_8,_noise_part_8},
  154079. _noise_thresh_11,
  154080. _psy_ath_floater_8,
  154081. _psy_ath_abs_8,
  154082. _psy_lowpass_11,
  154083. _psy_global_44,
  154084. _global_mapping_8,
  154085. _psy_stereo_modes_8,
  154086. _floor_books,
  154087. _floor,
  154088. _floor_mapping_11,
  154089. NULL,
  154090. _mapres_template_8_uncoupled
  154091. };
  154092. /*** End of inlined file: setup_11.h ***/
  154093. /*** Start of inlined file: setup_16.h ***/
  154094. /*** Start of inlined file: psych_16.h ***/
  154095. /* stereo mode by base quality level */
  154096. static adj_stereo _psy_stereo_modes_16[4]={
  154097. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  154098. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  154099. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  154100. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 4, 4},
  154101. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  154102. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  154103. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  154104. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 4, 4, 4, 4, 4},
  154105. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  154106. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  154107. { 5, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  154108. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  154109. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  154110. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  154111. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  154112. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8},
  154113. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  154114. };
  154115. static double _psy_lowpass_16[4]={6.5,8,30.,99.};
  154116. static att3 _psy_tone_masteratt_16[4]={
  154117. {{ 30, 25, 12}, 0, 0}, /* 0 */
  154118. {{ 25, 22, 12}, 0, 0}, /* 0 */
  154119. {{ 20, 12, 0}, 0, 0}, /* 0 */
  154120. {{ 15, 0, -14}, 0, 0}, /* 0 */
  154121. };
  154122. static vp_adjblock _vp_tonemask_adj_16[4]={
  154123. /* adjust for mode zero */
  154124. /* 63 125 250 500 1 2 4 8 16 */
  154125. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 0 */
  154126. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 1 */
  154127. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  154128. {{-30,-30,-30,-30,-30,-26,-20,-10, -5, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  154129. };
  154130. static noise3 _psy_noisebias_16_short[4]={
  154131. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  154132. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  154133. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  154134. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  154135. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  154136. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 4, 5, 6, 8, 8, 15},
  154137. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  154138. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  154139. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10, -8, 0, 0, 0, 0, 2, 5},
  154140. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154141. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  154142. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  154143. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154144. };
  154145. static noise3 _psy_noisebias_16_impulse[4]={
  154146. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  154147. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  154148. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  154149. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  154150. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 4, 4, 4, 5, 5, 6, 8, 15},
  154151. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 0, 0, 0, 0, 4, 10},
  154152. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  154153. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 4, 10},
  154154. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10,-10,-10,-10,-10,-10, -7, -5},
  154155. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154156. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  154157. {-30,-30,-30,-30,-26,-22,-20,-18,-18,-18,-20,-20,-20,-20,-20,-20,-16},
  154158. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154159. };
  154160. static noise3 _psy_noisebias_16[4]={
  154161. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  154162. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 8, 8, 10, 10, 10, 14, 20},
  154163. {-10,-10,-10,-10,-10, -5, -2, -2, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  154164. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  154165. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  154166. {-15,-15,-15,-15,-15,-10, -5, -5, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  154167. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  154168. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  154169. {-20,-20,-20,-20,-16,-12,-20,-10, -5, -5, 0, 0, 0, 0, 0, 2, 5},
  154170. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154171. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  154172. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  154173. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154174. };
  154175. static double _noise_thresh_16[4]={ .3,.5,.5,.5 };
  154176. static int _noise_start_16[3]={ 256,256,9999 };
  154177. static int _noise_part_16[4]={ 8,8,8,8 };
  154178. static int _psy_ath_floater_16[4]={
  154179. -100,-100,-100,-105,
  154180. };
  154181. static int _psy_ath_abs_16[4]={
  154182. -130,-130,-130,-140,
  154183. };
  154184. /*** End of inlined file: psych_16.h ***/
  154185. /*** Start of inlined file: residue_16.h ***/
  154186. /***** residue backends *********************************************/
  154187. static static_bookblock _resbook_16s_0={
  154188. {
  154189. {0},
  154190. {0,0,&_16c0_s_p1_0},
  154191. {0,0,&_16c0_s_p2_0},
  154192. {0,0,&_16c0_s_p3_0},
  154193. {0,0,&_16c0_s_p4_0},
  154194. {0,0,&_16c0_s_p5_0},
  154195. {0,0,&_16c0_s_p6_0},
  154196. {&_16c0_s_p7_0,&_16c0_s_p7_1},
  154197. {&_16c0_s_p8_0,&_16c0_s_p8_1},
  154198. {&_16c0_s_p9_0,&_16c0_s_p9_1,&_16c0_s_p9_2}
  154199. }
  154200. };
  154201. static static_bookblock _resbook_16s_1={
  154202. {
  154203. {0},
  154204. {0,0,&_16c1_s_p1_0},
  154205. {0,0,&_16c1_s_p2_0},
  154206. {0,0,&_16c1_s_p3_0},
  154207. {0,0,&_16c1_s_p4_0},
  154208. {0,0,&_16c1_s_p5_0},
  154209. {0,0,&_16c1_s_p6_0},
  154210. {&_16c1_s_p7_0,&_16c1_s_p7_1},
  154211. {&_16c1_s_p8_0,&_16c1_s_p8_1},
  154212. {&_16c1_s_p9_0,&_16c1_s_p9_1,&_16c1_s_p9_2}
  154213. }
  154214. };
  154215. static static_bookblock _resbook_16s_2={
  154216. {
  154217. {0},
  154218. {0,0,&_16c2_s_p1_0},
  154219. {0,0,&_16c2_s_p2_0},
  154220. {0,0,&_16c2_s_p3_0},
  154221. {0,0,&_16c2_s_p4_0},
  154222. {&_16c2_s_p5_0,&_16c2_s_p5_1},
  154223. {&_16c2_s_p6_0,&_16c2_s_p6_1},
  154224. {&_16c2_s_p7_0,&_16c2_s_p7_1},
  154225. {&_16c2_s_p8_0,&_16c2_s_p8_1},
  154226. {&_16c2_s_p9_0,&_16c2_s_p9_1,&_16c2_s_p9_2}
  154227. }
  154228. };
  154229. static vorbis_residue_template _res_16s_0[]={
  154230. {2,0, &_residue_44_mid,
  154231. &_huff_book__16c0_s_single,&_huff_book__16c0_s_single,
  154232. &_resbook_16s_0,&_resbook_16s_0},
  154233. };
  154234. static vorbis_residue_template _res_16s_1[]={
  154235. {2,0, &_residue_44_mid,
  154236. &_huff_book__16c1_s_short,&_huff_book__16c1_s_short,
  154237. &_resbook_16s_1,&_resbook_16s_1},
  154238. {2,0, &_residue_44_mid,
  154239. &_huff_book__16c1_s_long,&_huff_book__16c1_s_long,
  154240. &_resbook_16s_1,&_resbook_16s_1}
  154241. };
  154242. static vorbis_residue_template _res_16s_2[]={
  154243. {2,0, &_residue_44_high,
  154244. &_huff_book__16c2_s_short,&_huff_book__16c2_s_short,
  154245. &_resbook_16s_2,&_resbook_16s_2},
  154246. {2,0, &_residue_44_high,
  154247. &_huff_book__16c2_s_long,&_huff_book__16c2_s_long,
  154248. &_resbook_16s_2,&_resbook_16s_2}
  154249. };
  154250. static vorbis_mapping_template _mapres_template_16_stereo[3]={
  154251. { _map_nominal, _res_16s_0 }, /* 0 */
  154252. { _map_nominal, _res_16s_1 }, /* 1 */
  154253. { _map_nominal, _res_16s_2 }, /* 2 */
  154254. };
  154255. static static_bookblock _resbook_16u_0={
  154256. {
  154257. {0},
  154258. {0,0,&_16u0__p1_0},
  154259. {0,0,&_16u0__p2_0},
  154260. {0,0,&_16u0__p3_0},
  154261. {0,0,&_16u0__p4_0},
  154262. {0,0,&_16u0__p5_0},
  154263. {&_16u0__p6_0,&_16u0__p6_1},
  154264. {&_16u0__p7_0,&_16u0__p7_1,&_16u0__p7_2}
  154265. }
  154266. };
  154267. static static_bookblock _resbook_16u_1={
  154268. {
  154269. {0},
  154270. {0,0,&_16u1__p1_0},
  154271. {0,0,&_16u1__p2_0},
  154272. {0,0,&_16u1__p3_0},
  154273. {0,0,&_16u1__p4_0},
  154274. {0,0,&_16u1__p5_0},
  154275. {0,0,&_16u1__p6_0},
  154276. {&_16u1__p7_0,&_16u1__p7_1},
  154277. {&_16u1__p8_0,&_16u1__p8_1},
  154278. {&_16u1__p9_0,&_16u1__p9_1,&_16u1__p9_2}
  154279. }
  154280. };
  154281. static static_bookblock _resbook_16u_2={
  154282. {
  154283. {0},
  154284. {0,0,&_16u2_p1_0},
  154285. {0,0,&_16u2_p2_0},
  154286. {0,0,&_16u2_p3_0},
  154287. {0,0,&_16u2_p4_0},
  154288. {&_16u2_p5_0,&_16u2_p5_1},
  154289. {&_16u2_p6_0,&_16u2_p6_1},
  154290. {&_16u2_p7_0,&_16u2_p7_1},
  154291. {&_16u2_p8_0,&_16u2_p8_1},
  154292. {&_16u2_p9_0,&_16u2_p9_1,&_16u2_p9_2}
  154293. }
  154294. };
  154295. static vorbis_residue_template _res_16u_0[]={
  154296. {1,0, &_residue_44_low_un,
  154297. &_huff_book__16u0__single,&_huff_book__16u0__single,
  154298. &_resbook_16u_0,&_resbook_16u_0},
  154299. };
  154300. static vorbis_residue_template _res_16u_1[]={
  154301. {1,0, &_residue_44_mid_un,
  154302. &_huff_book__16u1__short,&_huff_book__16u1__short,
  154303. &_resbook_16u_1,&_resbook_16u_1},
  154304. {1,0, &_residue_44_mid_un,
  154305. &_huff_book__16u1__long,&_huff_book__16u1__long,
  154306. &_resbook_16u_1,&_resbook_16u_1}
  154307. };
  154308. static vorbis_residue_template _res_16u_2[]={
  154309. {1,0, &_residue_44_hi_un,
  154310. &_huff_book__16u2__short,&_huff_book__16u2__short,
  154311. &_resbook_16u_2,&_resbook_16u_2},
  154312. {1,0, &_residue_44_hi_un,
  154313. &_huff_book__16u2__long,&_huff_book__16u2__long,
  154314. &_resbook_16u_2,&_resbook_16u_2}
  154315. };
  154316. static vorbis_mapping_template _mapres_template_16_uncoupled[3]={
  154317. { _map_nominal_u, _res_16u_0 }, /* 0 */
  154318. { _map_nominal_u, _res_16u_1 }, /* 1 */
  154319. { _map_nominal_u, _res_16u_2 }, /* 2 */
  154320. };
  154321. /*** End of inlined file: residue_16.h ***/
  154322. static int blocksize_16_short[3]={
  154323. 1024,512,512
  154324. };
  154325. static int blocksize_16_long[3]={
  154326. 1024,1024,1024
  154327. };
  154328. static int _floor_mapping_16_short[3]={
  154329. 9,3,3
  154330. };
  154331. static int _floor_mapping_16[3]={
  154332. 9,9,9
  154333. };
  154334. static double rate_mapping_16[4]={
  154335. 12000.,20000.,44000.,86000.
  154336. };
  154337. static double rate_mapping_16_uncoupled[4]={
  154338. 16000.,28000.,64000.,100000.
  154339. };
  154340. static double _global_mapping_16[4]={ 1., 2., 3., 4. };
  154341. static double quality_mapping_16[4]={ -.1,.05,.5,1. };
  154342. static double _psy_compand_16_mapping[4]={ 0., .8, 1., 1.};
  154343. ve_setup_data_template ve_setup_16_stereo={
  154344. 3,
  154345. rate_mapping_16,
  154346. quality_mapping_16,
  154347. 2,
  154348. 15000,
  154349. 19000,
  154350. blocksize_16_short,
  154351. blocksize_16_long,
  154352. _psy_tone_masteratt_16,
  154353. _psy_tone_0dB,
  154354. _psy_tone_suppress,
  154355. _vp_tonemask_adj_16,
  154356. _vp_tonemask_adj_16,
  154357. _vp_tonemask_adj_16,
  154358. _psy_noiseguards_8,
  154359. _psy_noisebias_16_impulse,
  154360. _psy_noisebias_16_short,
  154361. _psy_noisebias_16_short,
  154362. _psy_noisebias_16,
  154363. _psy_noise_suppress,
  154364. _psy_compand_8,
  154365. _psy_compand_16_mapping,
  154366. _psy_compand_16_mapping,
  154367. {_noise_start_16,_noise_start_16},
  154368. { _noise_part_16, _noise_part_16},
  154369. _noise_thresh_16,
  154370. _psy_ath_floater_16,
  154371. _psy_ath_abs_16,
  154372. _psy_lowpass_16,
  154373. _psy_global_44,
  154374. _global_mapping_16,
  154375. _psy_stereo_modes_16,
  154376. _floor_books,
  154377. _floor,
  154378. _floor_mapping_16_short,
  154379. _floor_mapping_16,
  154380. _mapres_template_16_stereo
  154381. };
  154382. ve_setup_data_template ve_setup_16_uncoupled={
  154383. 3,
  154384. rate_mapping_16_uncoupled,
  154385. quality_mapping_16,
  154386. -1,
  154387. 15000,
  154388. 19000,
  154389. blocksize_16_short,
  154390. blocksize_16_long,
  154391. _psy_tone_masteratt_16,
  154392. _psy_tone_0dB,
  154393. _psy_tone_suppress,
  154394. _vp_tonemask_adj_16,
  154395. _vp_tonemask_adj_16,
  154396. _vp_tonemask_adj_16,
  154397. _psy_noiseguards_8,
  154398. _psy_noisebias_16_impulse,
  154399. _psy_noisebias_16_short,
  154400. _psy_noisebias_16_short,
  154401. _psy_noisebias_16,
  154402. _psy_noise_suppress,
  154403. _psy_compand_8,
  154404. _psy_compand_16_mapping,
  154405. _psy_compand_16_mapping,
  154406. {_noise_start_16,_noise_start_16},
  154407. { _noise_part_16, _noise_part_16},
  154408. _noise_thresh_16,
  154409. _psy_ath_floater_16,
  154410. _psy_ath_abs_16,
  154411. _psy_lowpass_16,
  154412. _psy_global_44,
  154413. _global_mapping_16,
  154414. _psy_stereo_modes_16,
  154415. _floor_books,
  154416. _floor,
  154417. _floor_mapping_16_short,
  154418. _floor_mapping_16,
  154419. _mapres_template_16_uncoupled
  154420. };
  154421. /*** End of inlined file: setup_16.h ***/
  154422. /*** Start of inlined file: setup_22.h ***/
  154423. static double rate_mapping_22[4]={
  154424. 15000.,20000.,44000.,86000.
  154425. };
  154426. static double rate_mapping_22_uncoupled[4]={
  154427. 16000.,28000.,50000.,90000.
  154428. };
  154429. static double _psy_lowpass_22[4]={9.5,11.,30.,99.};
  154430. ve_setup_data_template ve_setup_22_stereo={
  154431. 3,
  154432. rate_mapping_22,
  154433. quality_mapping_16,
  154434. 2,
  154435. 19000,
  154436. 26000,
  154437. blocksize_16_short,
  154438. blocksize_16_long,
  154439. _psy_tone_masteratt_16,
  154440. _psy_tone_0dB,
  154441. _psy_tone_suppress,
  154442. _vp_tonemask_adj_16,
  154443. _vp_tonemask_adj_16,
  154444. _vp_tonemask_adj_16,
  154445. _psy_noiseguards_8,
  154446. _psy_noisebias_16_impulse,
  154447. _psy_noisebias_16_short,
  154448. _psy_noisebias_16_short,
  154449. _psy_noisebias_16,
  154450. _psy_noise_suppress,
  154451. _psy_compand_8,
  154452. _psy_compand_8_mapping,
  154453. _psy_compand_8_mapping,
  154454. {_noise_start_16,_noise_start_16},
  154455. { _noise_part_16, _noise_part_16},
  154456. _noise_thresh_16,
  154457. _psy_ath_floater_16,
  154458. _psy_ath_abs_16,
  154459. _psy_lowpass_22,
  154460. _psy_global_44,
  154461. _global_mapping_16,
  154462. _psy_stereo_modes_16,
  154463. _floor_books,
  154464. _floor,
  154465. _floor_mapping_16_short,
  154466. _floor_mapping_16,
  154467. _mapres_template_16_stereo
  154468. };
  154469. ve_setup_data_template ve_setup_22_uncoupled={
  154470. 3,
  154471. rate_mapping_22_uncoupled,
  154472. quality_mapping_16,
  154473. -1,
  154474. 19000,
  154475. 26000,
  154476. blocksize_16_short,
  154477. blocksize_16_long,
  154478. _psy_tone_masteratt_16,
  154479. _psy_tone_0dB,
  154480. _psy_tone_suppress,
  154481. _vp_tonemask_adj_16,
  154482. _vp_tonemask_adj_16,
  154483. _vp_tonemask_adj_16,
  154484. _psy_noiseguards_8,
  154485. _psy_noisebias_16_impulse,
  154486. _psy_noisebias_16_short,
  154487. _psy_noisebias_16_short,
  154488. _psy_noisebias_16,
  154489. _psy_noise_suppress,
  154490. _psy_compand_8,
  154491. _psy_compand_8_mapping,
  154492. _psy_compand_8_mapping,
  154493. {_noise_start_16,_noise_start_16},
  154494. { _noise_part_16, _noise_part_16},
  154495. _noise_thresh_16,
  154496. _psy_ath_floater_16,
  154497. _psy_ath_abs_16,
  154498. _psy_lowpass_22,
  154499. _psy_global_44,
  154500. _global_mapping_16,
  154501. _psy_stereo_modes_16,
  154502. _floor_books,
  154503. _floor,
  154504. _floor_mapping_16_short,
  154505. _floor_mapping_16,
  154506. _mapres_template_16_uncoupled
  154507. };
  154508. /*** End of inlined file: setup_22.h ***/
  154509. /*** Start of inlined file: setup_X.h ***/
  154510. static double rate_mapping_X[12]={
  154511. -1.,-1.,-1.,-1.,-1.,-1.,
  154512. -1.,-1.,-1.,-1.,-1.,-1.
  154513. };
  154514. ve_setup_data_template ve_setup_X_stereo={
  154515. 11,
  154516. rate_mapping_X,
  154517. quality_mapping_44,
  154518. 2,
  154519. 50000,
  154520. 200000,
  154521. blocksize_short_44,
  154522. blocksize_long_44,
  154523. _psy_tone_masteratt_44,
  154524. _psy_tone_0dB,
  154525. _psy_tone_suppress,
  154526. _vp_tonemask_adj_otherblock,
  154527. _vp_tonemask_adj_longblock,
  154528. _vp_tonemask_adj_otherblock,
  154529. _psy_noiseguards_44,
  154530. _psy_noisebias_impulse,
  154531. _psy_noisebias_padding,
  154532. _psy_noisebias_trans,
  154533. _psy_noisebias_long,
  154534. _psy_noise_suppress,
  154535. _psy_compand_44,
  154536. _psy_compand_short_mapping,
  154537. _psy_compand_long_mapping,
  154538. {_noise_start_short_44,_noise_start_long_44},
  154539. {_noise_part_short_44,_noise_part_long_44},
  154540. _noise_thresh_44,
  154541. _psy_ath_floater,
  154542. _psy_ath_abs,
  154543. _psy_lowpass_44,
  154544. _psy_global_44,
  154545. _global_mapping_44,
  154546. _psy_stereo_modes_44,
  154547. _floor_books,
  154548. _floor,
  154549. _floor_short_mapping_44,
  154550. _floor_long_mapping_44,
  154551. _mapres_template_44_stereo
  154552. };
  154553. ve_setup_data_template ve_setup_X_uncoupled={
  154554. 11,
  154555. rate_mapping_X,
  154556. quality_mapping_44,
  154557. -1,
  154558. 50000,
  154559. 200000,
  154560. blocksize_short_44,
  154561. blocksize_long_44,
  154562. _psy_tone_masteratt_44,
  154563. _psy_tone_0dB,
  154564. _psy_tone_suppress,
  154565. _vp_tonemask_adj_otherblock,
  154566. _vp_tonemask_adj_longblock,
  154567. _vp_tonemask_adj_otherblock,
  154568. _psy_noiseguards_44,
  154569. _psy_noisebias_impulse,
  154570. _psy_noisebias_padding,
  154571. _psy_noisebias_trans,
  154572. _psy_noisebias_long,
  154573. _psy_noise_suppress,
  154574. _psy_compand_44,
  154575. _psy_compand_short_mapping,
  154576. _psy_compand_long_mapping,
  154577. {_noise_start_short_44,_noise_start_long_44},
  154578. {_noise_part_short_44,_noise_part_long_44},
  154579. _noise_thresh_44,
  154580. _psy_ath_floater,
  154581. _psy_ath_abs,
  154582. _psy_lowpass_44,
  154583. _psy_global_44,
  154584. _global_mapping_44,
  154585. NULL,
  154586. _floor_books,
  154587. _floor,
  154588. _floor_short_mapping_44,
  154589. _floor_long_mapping_44,
  154590. _mapres_template_44_uncoupled
  154591. };
  154592. ve_setup_data_template ve_setup_XX_stereo={
  154593. 2,
  154594. rate_mapping_X,
  154595. quality_mapping_8,
  154596. 2,
  154597. 0,
  154598. 8000,
  154599. blocksize_8,
  154600. blocksize_8,
  154601. _psy_tone_masteratt_8,
  154602. _psy_tone_0dB,
  154603. _psy_tone_suppress,
  154604. _vp_tonemask_adj_8,
  154605. NULL,
  154606. _vp_tonemask_adj_8,
  154607. _psy_noiseguards_8,
  154608. _psy_noisebias_8,
  154609. _psy_noisebias_8,
  154610. NULL,
  154611. NULL,
  154612. _psy_noise_suppress,
  154613. _psy_compand_8,
  154614. _psy_compand_8_mapping,
  154615. NULL,
  154616. {_noise_start_8,_noise_start_8},
  154617. {_noise_part_8,_noise_part_8},
  154618. _noise_thresh_5only,
  154619. _psy_ath_floater_8,
  154620. _psy_ath_abs_8,
  154621. _psy_lowpass_8,
  154622. _psy_global_44,
  154623. _global_mapping_8,
  154624. _psy_stereo_modes_8,
  154625. _floor_books,
  154626. _floor,
  154627. _floor_mapping_8,
  154628. NULL,
  154629. _mapres_template_8_stereo
  154630. };
  154631. ve_setup_data_template ve_setup_XX_uncoupled={
  154632. 2,
  154633. rate_mapping_X,
  154634. quality_mapping_8,
  154635. -1,
  154636. 0,
  154637. 8000,
  154638. blocksize_8,
  154639. blocksize_8,
  154640. _psy_tone_masteratt_8,
  154641. _psy_tone_0dB,
  154642. _psy_tone_suppress,
  154643. _vp_tonemask_adj_8,
  154644. NULL,
  154645. _vp_tonemask_adj_8,
  154646. _psy_noiseguards_8,
  154647. _psy_noisebias_8,
  154648. _psy_noisebias_8,
  154649. NULL,
  154650. NULL,
  154651. _psy_noise_suppress,
  154652. _psy_compand_8,
  154653. _psy_compand_8_mapping,
  154654. NULL,
  154655. {_noise_start_8,_noise_start_8},
  154656. {_noise_part_8,_noise_part_8},
  154657. _noise_thresh_5only,
  154658. _psy_ath_floater_8,
  154659. _psy_ath_abs_8,
  154660. _psy_lowpass_8,
  154661. _psy_global_44,
  154662. _global_mapping_8,
  154663. _psy_stereo_modes_8,
  154664. _floor_books,
  154665. _floor,
  154666. _floor_mapping_8,
  154667. NULL,
  154668. _mapres_template_8_uncoupled
  154669. };
  154670. /*** End of inlined file: setup_X.h ***/
  154671. static ve_setup_data_template *setup_list[]={
  154672. &ve_setup_44_stereo,
  154673. &ve_setup_44_uncoupled,
  154674. &ve_setup_32_stereo,
  154675. &ve_setup_32_uncoupled,
  154676. &ve_setup_22_stereo,
  154677. &ve_setup_22_uncoupled,
  154678. &ve_setup_16_stereo,
  154679. &ve_setup_16_uncoupled,
  154680. &ve_setup_11_stereo,
  154681. &ve_setup_11_uncoupled,
  154682. &ve_setup_8_stereo,
  154683. &ve_setup_8_uncoupled,
  154684. &ve_setup_X_stereo,
  154685. &ve_setup_X_uncoupled,
  154686. &ve_setup_XX_stereo,
  154687. &ve_setup_XX_uncoupled,
  154688. 0
  154689. };
  154690. static int vorbis_encode_toplevel_setup(vorbis_info *vi,int ch,long rate){
  154691. if(vi && vi->codec_setup){
  154692. vi->version=0;
  154693. vi->channels=ch;
  154694. vi->rate=rate;
  154695. return(0);
  154696. }
  154697. return(OV_EINVAL);
  154698. }
  154699. static void vorbis_encode_floor_setup(vorbis_info *vi,double s,int block,
  154700. static_codebook ***books,
  154701. vorbis_info_floor1 *in,
  154702. int *x){
  154703. int i,k,is=s;
  154704. vorbis_info_floor1 *f=(vorbis_info_floor1*) _ogg_calloc(1,sizeof(*f));
  154705. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154706. memcpy(f,in+x[is],sizeof(*f));
  154707. /* fill in the lowpass field, even if it's temporary */
  154708. f->n=ci->blocksizes[block]>>1;
  154709. /* books */
  154710. {
  154711. int partitions=f->partitions;
  154712. int maxclass=-1;
  154713. int maxbook=-1;
  154714. for(i=0;i<partitions;i++)
  154715. if(f->partitionclass[i]>maxclass)maxclass=f->partitionclass[i];
  154716. for(i=0;i<=maxclass;i++){
  154717. if(f->class_book[i]>maxbook)maxbook=f->class_book[i];
  154718. f->class_book[i]+=ci->books;
  154719. for(k=0;k<(1<<f->class_subs[i]);k++){
  154720. if(f->class_subbook[i][k]>maxbook)maxbook=f->class_subbook[i][k];
  154721. if(f->class_subbook[i][k]>=0)f->class_subbook[i][k]+=ci->books;
  154722. }
  154723. }
  154724. for(i=0;i<=maxbook;i++)
  154725. ci->book_param[ci->books++]=books[x[is]][i];
  154726. }
  154727. /* for now, we're only using floor 1 */
  154728. ci->floor_type[ci->floors]=1;
  154729. ci->floor_param[ci->floors]=f;
  154730. ci->floors++;
  154731. return;
  154732. }
  154733. static void vorbis_encode_global_psych_setup(vorbis_info *vi,double s,
  154734. vorbis_info_psy_global *in,
  154735. double *x){
  154736. int i,is=s;
  154737. double ds=s-is;
  154738. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154739. vorbis_info_psy_global *g=&ci->psy_g_param;
  154740. memcpy(g,in+(int)x[is],sizeof(*g));
  154741. ds=x[is]*(1.-ds)+x[is+1]*ds;
  154742. is=(int)ds;
  154743. ds-=is;
  154744. if(ds==0 && is>0){
  154745. is--;
  154746. ds=1.;
  154747. }
  154748. /* interpolate the trigger threshholds */
  154749. for(i=0;i<4;i++){
  154750. g->preecho_thresh[i]=in[is].preecho_thresh[i]*(1.-ds)+in[is+1].preecho_thresh[i]*ds;
  154751. g->postecho_thresh[i]=in[is].postecho_thresh[i]*(1.-ds)+in[is+1].postecho_thresh[i]*ds;
  154752. }
  154753. g->ampmax_att_per_sec=ci->hi.amplitude_track_dBpersec;
  154754. return;
  154755. }
  154756. static void vorbis_encode_global_stereo(vorbis_info *vi,
  154757. highlevel_encode_setup *hi,
  154758. adj_stereo *p){
  154759. float s=hi->stereo_point_setting;
  154760. int i,is=s;
  154761. double ds=s-is;
  154762. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154763. vorbis_info_psy_global *g=&ci->psy_g_param;
  154764. if(p){
  154765. memcpy(g->coupling_prepointamp,p[is].pre,sizeof(*p[is].pre)*PACKETBLOBS);
  154766. memcpy(g->coupling_postpointamp,p[is].post,sizeof(*p[is].post)*PACKETBLOBS);
  154767. if(hi->managed){
  154768. /* interpolate the kHz threshholds */
  154769. for(i=0;i<PACKETBLOBS;i++){
  154770. float kHz=p[is].kHz[i]*(1.-ds)+p[is+1].kHz[i]*ds;
  154771. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154772. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154773. g->coupling_pkHz[i]=kHz;
  154774. kHz=p[is].lowpasskHz[i]*(1.-ds)+p[is+1].lowpasskHz[i]*ds;
  154775. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154776. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154777. }
  154778. }else{
  154779. float kHz=p[is].kHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].kHz[PACKETBLOBS/2]*ds;
  154780. for(i=0;i<PACKETBLOBS;i++){
  154781. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154782. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154783. g->coupling_pkHz[i]=kHz;
  154784. }
  154785. kHz=p[is].lowpasskHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].lowpasskHz[PACKETBLOBS/2]*ds;
  154786. for(i=0;i<PACKETBLOBS;i++){
  154787. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154788. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154789. }
  154790. }
  154791. }else{
  154792. for(i=0;i<PACKETBLOBS;i++){
  154793. g->sliding_lowpass[0][i]=ci->blocksizes[0];
  154794. g->sliding_lowpass[1][i]=ci->blocksizes[1];
  154795. }
  154796. }
  154797. return;
  154798. }
  154799. static void vorbis_encode_psyset_setup(vorbis_info *vi,double s,
  154800. int *nn_start,
  154801. int *nn_partition,
  154802. double *nn_thresh,
  154803. int block){
  154804. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154805. vorbis_info_psy *p=ci->psy_param[block];
  154806. highlevel_encode_setup *hi=&ci->hi;
  154807. int is=s;
  154808. if(block>=ci->psys)
  154809. ci->psys=block+1;
  154810. if(!p){
  154811. p=(vorbis_info_psy*)_ogg_calloc(1,sizeof(*p));
  154812. ci->psy_param[block]=p;
  154813. }
  154814. memcpy(p,&_psy_info_template,sizeof(*p));
  154815. p->blockflag=block>>1;
  154816. if(hi->noise_normalize_p){
  154817. p->normal_channel_p=1;
  154818. p->normal_point_p=1;
  154819. p->normal_start=nn_start[is];
  154820. p->normal_partition=nn_partition[is];
  154821. p->normal_thresh=nn_thresh[is];
  154822. }
  154823. return;
  154824. }
  154825. static void vorbis_encode_tonemask_setup(vorbis_info *vi,double s,int block,
  154826. att3 *att,
  154827. int *max,
  154828. vp_adjblock *in){
  154829. int i,is=s;
  154830. double ds=s-is;
  154831. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154832. vorbis_info_psy *p=ci->psy_param[block];
  154833. /* 0 and 2 are only used by bitmanagement, but there's no harm to always
  154834. filling the values in here */
  154835. p->tone_masteratt[0]=att[is].att[0]*(1.-ds)+att[is+1].att[0]*ds;
  154836. p->tone_masteratt[1]=att[is].att[1]*(1.-ds)+att[is+1].att[1]*ds;
  154837. p->tone_masteratt[2]=att[is].att[2]*(1.-ds)+att[is+1].att[2]*ds;
  154838. p->tone_centerboost=att[is].boost*(1.-ds)+att[is+1].boost*ds;
  154839. p->tone_decay=att[is].decay*(1.-ds)+att[is+1].decay*ds;
  154840. p->max_curve_dB=max[is]*(1.-ds)+max[is+1]*ds;
  154841. for(i=0;i<P_BANDS;i++)
  154842. p->toneatt[i]=in[is].block[i]*(1.-ds)+in[is+1].block[i]*ds;
  154843. return;
  154844. }
  154845. static void vorbis_encode_compand_setup(vorbis_info *vi,double s,int block,
  154846. compandblock *in, double *x){
  154847. int i,is=s;
  154848. double ds=s-is;
  154849. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154850. vorbis_info_psy *p=ci->psy_param[block];
  154851. ds=x[is]*(1.-ds)+x[is+1]*ds;
  154852. is=(int)ds;
  154853. ds-=is;
  154854. if(ds==0 && is>0){
  154855. is--;
  154856. ds=1.;
  154857. }
  154858. /* interpolate the compander settings */
  154859. for(i=0;i<NOISE_COMPAND_LEVELS;i++)
  154860. p->noisecompand[i]=in[is].data[i]*(1.-ds)+in[is+1].data[i]*ds;
  154861. return;
  154862. }
  154863. static void vorbis_encode_peak_setup(vorbis_info *vi,double s,int block,
  154864. int *suppress){
  154865. int is=s;
  154866. double ds=s-is;
  154867. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154868. vorbis_info_psy *p=ci->psy_param[block];
  154869. p->tone_abs_limit=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  154870. return;
  154871. }
  154872. static void vorbis_encode_noisebias_setup(vorbis_info *vi,double s,int block,
  154873. int *suppress,
  154874. noise3 *in,
  154875. noiseguard *guard,
  154876. double userbias){
  154877. int i,is=s,j;
  154878. double ds=s-is;
  154879. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154880. vorbis_info_psy *p=ci->psy_param[block];
  154881. p->noisemaxsupp=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  154882. p->noisewindowlomin=guard[block].lo;
  154883. p->noisewindowhimin=guard[block].hi;
  154884. p->noisewindowfixed=guard[block].fixed;
  154885. for(j=0;j<P_NOISECURVES;j++)
  154886. for(i=0;i<P_BANDS;i++)
  154887. p->noiseoff[j][i]=in[is].data[j][i]*(1.-ds)+in[is+1].data[j][i]*ds;
  154888. /* impulse blocks may take a user specified bias to boost the
  154889. nominal/high noise encoding depth */
  154890. for(j=0;j<P_NOISECURVES;j++){
  154891. float min=p->noiseoff[j][0]+6; /* the lowest it can go */
  154892. for(i=0;i<P_BANDS;i++){
  154893. p->noiseoff[j][i]+=userbias;
  154894. if(p->noiseoff[j][i]<min)p->noiseoff[j][i]=min;
  154895. }
  154896. }
  154897. return;
  154898. }
  154899. static void vorbis_encode_ath_setup(vorbis_info *vi,int block){
  154900. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154901. vorbis_info_psy *p=ci->psy_param[block];
  154902. p->ath_adjatt=ci->hi.ath_floating_dB;
  154903. p->ath_maxatt=ci->hi.ath_absolute_dB;
  154904. return;
  154905. }
  154906. static int book_dup_or_new(codec_setup_info *ci,static_codebook *book){
  154907. int i;
  154908. for(i=0;i<ci->books;i++)
  154909. if(ci->book_param[i]==book)return(i);
  154910. return(ci->books++);
  154911. }
  154912. static void vorbis_encode_blocksize_setup(vorbis_info *vi,double s,
  154913. int *shortb,int *longb){
  154914. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154915. int is=s;
  154916. int blockshort=shortb[is];
  154917. int blocklong=longb[is];
  154918. ci->blocksizes[0]=blockshort;
  154919. ci->blocksizes[1]=blocklong;
  154920. }
  154921. static void vorbis_encode_residue_setup(vorbis_info *vi,
  154922. int number, int block,
  154923. vorbis_residue_template *res){
  154924. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154925. int i,n;
  154926. vorbis_info_residue0 *r=(vorbis_info_residue0*)(ci->residue_param[number]=
  154927. (vorbis_info_residue0*)_ogg_malloc(sizeof(*r)));
  154928. memcpy(r,res->res,sizeof(*r));
  154929. if(ci->residues<=number)ci->residues=number+1;
  154930. switch(ci->blocksizes[block]){
  154931. case 64:case 128:case 256:
  154932. r->grouping=16;
  154933. break;
  154934. default:
  154935. r->grouping=32;
  154936. break;
  154937. }
  154938. ci->residue_type[number]=res->res_type;
  154939. /* to be adjusted by lowpass/pointlimit later */
  154940. n=r->end=ci->blocksizes[block]>>1;
  154941. if(res->res_type==2)
  154942. n=r->end*=vi->channels;
  154943. /* fill in all the books */
  154944. {
  154945. int booklist=0,k;
  154946. if(ci->hi.managed){
  154947. for(i=0;i<r->partitions;i++)
  154948. for(k=0;k<3;k++)
  154949. if(res->books_base_managed->books[i][k])
  154950. r->secondstages[i]|=(1<<k);
  154951. r->groupbook=book_dup_or_new(ci,res->book_aux_managed);
  154952. ci->book_param[r->groupbook]=res->book_aux_managed;
  154953. for(i=0;i<r->partitions;i++){
  154954. for(k=0;k<3;k++){
  154955. if(res->books_base_managed->books[i][k]){
  154956. int bookid=book_dup_or_new(ci,res->books_base_managed->books[i][k]);
  154957. r->booklist[booklist++]=bookid;
  154958. ci->book_param[bookid]=res->books_base_managed->books[i][k];
  154959. }
  154960. }
  154961. }
  154962. }else{
  154963. for(i=0;i<r->partitions;i++)
  154964. for(k=0;k<3;k++)
  154965. if(res->books_base->books[i][k])
  154966. r->secondstages[i]|=(1<<k);
  154967. r->groupbook=book_dup_or_new(ci,res->book_aux);
  154968. ci->book_param[r->groupbook]=res->book_aux;
  154969. for(i=0;i<r->partitions;i++){
  154970. for(k=0;k<3;k++){
  154971. if(res->books_base->books[i][k]){
  154972. int bookid=book_dup_or_new(ci,res->books_base->books[i][k]);
  154973. r->booklist[booklist++]=bookid;
  154974. ci->book_param[bookid]=res->books_base->books[i][k];
  154975. }
  154976. }
  154977. }
  154978. }
  154979. }
  154980. /* lowpass setup/pointlimit */
  154981. {
  154982. double freq=ci->hi.lowpass_kHz*1000.;
  154983. vorbis_info_floor1 *f=(vorbis_info_floor1*)ci->floor_param[block]; /* by convention */
  154984. double nyq=vi->rate/2.;
  154985. long blocksize=ci->blocksizes[block]>>1;
  154986. /* lowpass needs to be set in the floor and the residue. */
  154987. if(freq>nyq)freq=nyq;
  154988. /* in the floor, the granularity can be very fine; it doesn't alter
  154989. the encoding structure, only the samples used to fit the floor
  154990. approximation */
  154991. f->n=freq/nyq*blocksize;
  154992. /* this res may by limited by the maximum pointlimit of the mode,
  154993. not the lowpass. the floor is always lowpass limited. */
  154994. if(res->limit_type){
  154995. if(ci->hi.managed)
  154996. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS-1]*1000.;
  154997. else
  154998. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS/2]*1000.;
  154999. if(freq>nyq)freq=nyq;
  155000. }
  155001. /* in the residue, we're constrained, physically, by partition
  155002. boundaries. We still lowpass 'wherever', but we have to round up
  155003. here to next boundary, or the vorbis spec will round it *down* to
  155004. previous boundary in encode/decode */
  155005. if(ci->residue_type[block]==2)
  155006. r->end=(int)((freq/nyq*blocksize*2)/r->grouping+.9)* /* round up only if we're well past */
  155007. r->grouping;
  155008. else
  155009. r->end=(int)((freq/nyq*blocksize)/r->grouping+.9)* /* round up only if we're well past */
  155010. r->grouping;
  155011. }
  155012. }
  155013. /* we assume two maps in this encoder */
  155014. static void vorbis_encode_map_n_res_setup(vorbis_info *vi,double s,
  155015. vorbis_mapping_template *maps){
  155016. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155017. int i,j,is=s,modes=2;
  155018. vorbis_info_mapping0 *map=maps[is].map;
  155019. vorbis_info_mode *mode=_mode_template;
  155020. vorbis_residue_template *res=maps[is].res;
  155021. if(ci->blocksizes[0]==ci->blocksizes[1])modes=1;
  155022. for(i=0;i<modes;i++){
  155023. ci->map_param[i]=_ogg_calloc(1,sizeof(*map));
  155024. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*mode));
  155025. memcpy(ci->mode_param[i],mode+i,sizeof(*_mode_template));
  155026. if(i>=ci->modes)ci->modes=i+1;
  155027. ci->map_type[i]=0;
  155028. memcpy(ci->map_param[i],map+i,sizeof(*map));
  155029. if(i>=ci->maps)ci->maps=i+1;
  155030. for(j=0;j<map[i].submaps;j++)
  155031. vorbis_encode_residue_setup(vi,map[i].residuesubmap[j],i
  155032. ,res+map[i].residuesubmap[j]);
  155033. }
  155034. }
  155035. static double setting_to_approx_bitrate(vorbis_info *vi){
  155036. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155037. highlevel_encode_setup *hi=&ci->hi;
  155038. ve_setup_data_template *setup=(ve_setup_data_template *)hi->setup;
  155039. int is=hi->base_setting;
  155040. double ds=hi->base_setting-is;
  155041. int ch=vi->channels;
  155042. double *r=setup->rate_mapping;
  155043. if(r==NULL)
  155044. return(-1);
  155045. return((r[is]*(1.-ds)+r[is+1]*ds)*ch);
  155046. }
  155047. static void get_setup_template(vorbis_info *vi,
  155048. long ch,long srate,
  155049. double req,int q_or_bitrate){
  155050. int i=0,j;
  155051. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  155052. highlevel_encode_setup *hi=&ci->hi;
  155053. if(q_or_bitrate)req/=ch;
  155054. while(setup_list[i]){
  155055. if(setup_list[i]->coupling_restriction==-1 ||
  155056. setup_list[i]->coupling_restriction==ch){
  155057. if(srate>=setup_list[i]->samplerate_min_restriction &&
  155058. srate<=setup_list[i]->samplerate_max_restriction){
  155059. int mappings=setup_list[i]->mappings;
  155060. double *map=(q_or_bitrate?
  155061. setup_list[i]->rate_mapping:
  155062. setup_list[i]->quality_mapping);
  155063. /* the template matches. Does the requested quality mode
  155064. fall within this template's modes? */
  155065. if(req<map[0]){++i;continue;}
  155066. if(req>map[setup_list[i]->mappings]){++i;continue;}
  155067. for(j=0;j<mappings;j++)
  155068. if(req>=map[j] && req<map[j+1])break;
  155069. /* an all-points match */
  155070. hi->setup=setup_list[i];
  155071. if(j==mappings)
  155072. hi->base_setting=j-.001;
  155073. else{
  155074. float low=map[j];
  155075. float high=map[j+1];
  155076. float del=(req-low)/(high-low);
  155077. hi->base_setting=j+del;
  155078. }
  155079. return;
  155080. }
  155081. }
  155082. i++;
  155083. }
  155084. hi->setup=NULL;
  155085. }
  155086. /* encoders will need to use vorbis_info_init beforehand and call
  155087. vorbis_info clear when all done */
  155088. /* two interfaces; this, more detailed one, and later a convenience
  155089. layer on top */
  155090. /* the final setup call */
  155091. int vorbis_encode_setup_init(vorbis_info *vi){
  155092. int i0=0,singleblock=0;
  155093. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  155094. ve_setup_data_template *setup=NULL;
  155095. highlevel_encode_setup *hi=&ci->hi;
  155096. if(ci==NULL)return(OV_EINVAL);
  155097. if(!hi->impulse_block_p)i0=1;
  155098. /* too low/high an ATH floater is nonsensical, but doesn't break anything */
  155099. if(hi->ath_floating_dB>-80)hi->ath_floating_dB=-80;
  155100. if(hi->ath_floating_dB<-200)hi->ath_floating_dB=-200;
  155101. /* again, bound this to avoid the app shooting itself int he foot
  155102. too badly */
  155103. if(hi->amplitude_track_dBpersec>0.)hi->amplitude_track_dBpersec=0.;
  155104. if(hi->amplitude_track_dBpersec<-99999.)hi->amplitude_track_dBpersec=-99999.;
  155105. /* get the appropriate setup template; matches the fetch in previous
  155106. stages */
  155107. setup=(ve_setup_data_template *)hi->setup;
  155108. if(setup==NULL)return(OV_EINVAL);
  155109. hi->set_in_stone=1;
  155110. /* choose block sizes from configured sizes as well as paying
  155111. attention to long_block_p and short_block_p. If the configured
  155112. short and long blocks are the same length, we set long_block_p
  155113. and unset short_block_p */
  155114. vorbis_encode_blocksize_setup(vi,hi->base_setting,
  155115. setup->blocksize_short,
  155116. setup->blocksize_long);
  155117. if(ci->blocksizes[0]==ci->blocksizes[1])singleblock=1;
  155118. /* floor setup; choose proper floor params. Allocated on the floor
  155119. stack in order; if we alloc only long floor, it's 0 */
  155120. vorbis_encode_floor_setup(vi,hi->short_setting,0,
  155121. setup->floor_books,
  155122. setup->floor_params,
  155123. setup->floor_short_mapping);
  155124. if(!singleblock)
  155125. vorbis_encode_floor_setup(vi,hi->long_setting,1,
  155126. setup->floor_books,
  155127. setup->floor_params,
  155128. setup->floor_long_mapping);
  155129. /* setup of [mostly] short block detection and stereo*/
  155130. vorbis_encode_global_psych_setup(vi,hi->trigger_setting,
  155131. setup->global_params,
  155132. setup->global_mapping);
  155133. vorbis_encode_global_stereo(vi,hi,setup->stereo_modes);
  155134. /* basic psych setup and noise normalization */
  155135. vorbis_encode_psyset_setup(vi,hi->short_setting,
  155136. setup->psy_noise_normal_start[0],
  155137. setup->psy_noise_normal_partition[0],
  155138. setup->psy_noise_normal_thresh,
  155139. 0);
  155140. vorbis_encode_psyset_setup(vi,hi->short_setting,
  155141. setup->psy_noise_normal_start[0],
  155142. setup->psy_noise_normal_partition[0],
  155143. setup->psy_noise_normal_thresh,
  155144. 1);
  155145. if(!singleblock){
  155146. vorbis_encode_psyset_setup(vi,hi->long_setting,
  155147. setup->psy_noise_normal_start[1],
  155148. setup->psy_noise_normal_partition[1],
  155149. setup->psy_noise_normal_thresh,
  155150. 2);
  155151. vorbis_encode_psyset_setup(vi,hi->long_setting,
  155152. setup->psy_noise_normal_start[1],
  155153. setup->psy_noise_normal_partition[1],
  155154. setup->psy_noise_normal_thresh,
  155155. 3);
  155156. }
  155157. /* tone masking setup */
  155158. vorbis_encode_tonemask_setup(vi,hi->block[i0].tone_mask_setting,0,
  155159. setup->psy_tone_masteratt,
  155160. setup->psy_tone_0dB,
  155161. setup->psy_tone_adj_impulse);
  155162. vorbis_encode_tonemask_setup(vi,hi->block[1].tone_mask_setting,1,
  155163. setup->psy_tone_masteratt,
  155164. setup->psy_tone_0dB,
  155165. setup->psy_tone_adj_other);
  155166. if(!singleblock){
  155167. vorbis_encode_tonemask_setup(vi,hi->block[2].tone_mask_setting,2,
  155168. setup->psy_tone_masteratt,
  155169. setup->psy_tone_0dB,
  155170. setup->psy_tone_adj_other);
  155171. vorbis_encode_tonemask_setup(vi,hi->block[3].tone_mask_setting,3,
  155172. setup->psy_tone_masteratt,
  155173. setup->psy_tone_0dB,
  155174. setup->psy_tone_adj_long);
  155175. }
  155176. /* noise companding setup */
  155177. vorbis_encode_compand_setup(vi,hi->block[i0].noise_compand_setting,0,
  155178. setup->psy_noise_compand,
  155179. setup->psy_noise_compand_short_mapping);
  155180. vorbis_encode_compand_setup(vi,hi->block[1].noise_compand_setting,1,
  155181. setup->psy_noise_compand,
  155182. setup->psy_noise_compand_short_mapping);
  155183. if(!singleblock){
  155184. vorbis_encode_compand_setup(vi,hi->block[2].noise_compand_setting,2,
  155185. setup->psy_noise_compand,
  155186. setup->psy_noise_compand_long_mapping);
  155187. vorbis_encode_compand_setup(vi,hi->block[3].noise_compand_setting,3,
  155188. setup->psy_noise_compand,
  155189. setup->psy_noise_compand_long_mapping);
  155190. }
  155191. /* peak guarding setup */
  155192. vorbis_encode_peak_setup(vi,hi->block[i0].tone_peaklimit_setting,0,
  155193. setup->psy_tone_dBsuppress);
  155194. vorbis_encode_peak_setup(vi,hi->block[1].tone_peaklimit_setting,1,
  155195. setup->psy_tone_dBsuppress);
  155196. if(!singleblock){
  155197. vorbis_encode_peak_setup(vi,hi->block[2].tone_peaklimit_setting,2,
  155198. setup->psy_tone_dBsuppress);
  155199. vorbis_encode_peak_setup(vi,hi->block[3].tone_peaklimit_setting,3,
  155200. setup->psy_tone_dBsuppress);
  155201. }
  155202. /* noise bias setup */
  155203. vorbis_encode_noisebias_setup(vi,hi->block[i0].noise_bias_setting,0,
  155204. setup->psy_noise_dBsuppress,
  155205. setup->psy_noise_bias_impulse,
  155206. setup->psy_noiseguards,
  155207. (i0==0?hi->impulse_noisetune:0.));
  155208. vorbis_encode_noisebias_setup(vi,hi->block[1].noise_bias_setting,1,
  155209. setup->psy_noise_dBsuppress,
  155210. setup->psy_noise_bias_padding,
  155211. setup->psy_noiseguards,0.);
  155212. if(!singleblock){
  155213. vorbis_encode_noisebias_setup(vi,hi->block[2].noise_bias_setting,2,
  155214. setup->psy_noise_dBsuppress,
  155215. setup->psy_noise_bias_trans,
  155216. setup->psy_noiseguards,0.);
  155217. vorbis_encode_noisebias_setup(vi,hi->block[3].noise_bias_setting,3,
  155218. setup->psy_noise_dBsuppress,
  155219. setup->psy_noise_bias_long,
  155220. setup->psy_noiseguards,0.);
  155221. }
  155222. vorbis_encode_ath_setup(vi,0);
  155223. vorbis_encode_ath_setup(vi,1);
  155224. if(!singleblock){
  155225. vorbis_encode_ath_setup(vi,2);
  155226. vorbis_encode_ath_setup(vi,3);
  155227. }
  155228. vorbis_encode_map_n_res_setup(vi,hi->base_setting,setup->maps);
  155229. /* set bitrate readonlies and management */
  155230. if(hi->bitrate_av>0)
  155231. vi->bitrate_nominal=hi->bitrate_av;
  155232. else{
  155233. vi->bitrate_nominal=setting_to_approx_bitrate(vi);
  155234. }
  155235. vi->bitrate_lower=hi->bitrate_min;
  155236. vi->bitrate_upper=hi->bitrate_max;
  155237. if(hi->bitrate_av)
  155238. vi->bitrate_window=(double)hi->bitrate_reservoir/hi->bitrate_av;
  155239. else
  155240. vi->bitrate_window=0.;
  155241. if(hi->managed){
  155242. ci->bi.avg_rate=hi->bitrate_av;
  155243. ci->bi.min_rate=hi->bitrate_min;
  155244. ci->bi.max_rate=hi->bitrate_max;
  155245. ci->bi.reservoir_bits=hi->bitrate_reservoir;
  155246. ci->bi.reservoir_bias=
  155247. hi->bitrate_reservoir_bias;
  155248. ci->bi.slew_damp=hi->bitrate_av_damp;
  155249. }
  155250. return(0);
  155251. }
  155252. static int vorbis_encode_setup_setting(vorbis_info *vi,
  155253. long channels,
  155254. long rate){
  155255. int ret=0,i,is;
  155256. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155257. highlevel_encode_setup *hi=&ci->hi;
  155258. ve_setup_data_template *setup=(ve_setup_data_template*) hi->setup;
  155259. double ds;
  155260. ret=vorbis_encode_toplevel_setup(vi,channels,rate);
  155261. if(ret)return(ret);
  155262. is=hi->base_setting;
  155263. ds=hi->base_setting-is;
  155264. hi->short_setting=hi->base_setting;
  155265. hi->long_setting=hi->base_setting;
  155266. hi->managed=0;
  155267. hi->impulse_block_p=1;
  155268. hi->noise_normalize_p=1;
  155269. hi->stereo_point_setting=hi->base_setting;
  155270. hi->lowpass_kHz=
  155271. setup->psy_lowpass[is]*(1.-ds)+setup->psy_lowpass[is+1]*ds;
  155272. hi->ath_floating_dB=setup->psy_ath_float[is]*(1.-ds)+
  155273. setup->psy_ath_float[is+1]*ds;
  155274. hi->ath_absolute_dB=setup->psy_ath_abs[is]*(1.-ds)+
  155275. setup->psy_ath_abs[is+1]*ds;
  155276. hi->amplitude_track_dBpersec=-6.;
  155277. hi->trigger_setting=hi->base_setting;
  155278. for(i=0;i<4;i++){
  155279. hi->block[i].tone_mask_setting=hi->base_setting;
  155280. hi->block[i].tone_peaklimit_setting=hi->base_setting;
  155281. hi->block[i].noise_bias_setting=hi->base_setting;
  155282. hi->block[i].noise_compand_setting=hi->base_setting;
  155283. }
  155284. return(ret);
  155285. }
  155286. int vorbis_encode_setup_vbr(vorbis_info *vi,
  155287. long channels,
  155288. long rate,
  155289. float quality){
  155290. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  155291. highlevel_encode_setup *hi=&ci->hi;
  155292. quality+=.0000001;
  155293. if(quality>=1.)quality=.9999;
  155294. get_setup_template(vi,channels,rate,quality,0);
  155295. if(!hi->setup)return OV_EIMPL;
  155296. return vorbis_encode_setup_setting(vi,channels,rate);
  155297. }
  155298. int vorbis_encode_init_vbr(vorbis_info *vi,
  155299. long channels,
  155300. long rate,
  155301. float base_quality /* 0. to 1. */
  155302. ){
  155303. int ret=0;
  155304. ret=vorbis_encode_setup_vbr(vi,channels,rate,base_quality);
  155305. if(ret){
  155306. vorbis_info_clear(vi);
  155307. return ret;
  155308. }
  155309. ret=vorbis_encode_setup_init(vi);
  155310. if(ret)
  155311. vorbis_info_clear(vi);
  155312. return(ret);
  155313. }
  155314. int vorbis_encode_setup_managed(vorbis_info *vi,
  155315. long channels,
  155316. long rate,
  155317. long max_bitrate,
  155318. long nominal_bitrate,
  155319. long min_bitrate){
  155320. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155321. highlevel_encode_setup *hi=&ci->hi;
  155322. double tnominal=nominal_bitrate;
  155323. int ret=0;
  155324. if(nominal_bitrate<=0.){
  155325. if(max_bitrate>0.){
  155326. if(min_bitrate>0.)
  155327. nominal_bitrate=(max_bitrate+min_bitrate)*.5;
  155328. else
  155329. nominal_bitrate=max_bitrate*.875;
  155330. }else{
  155331. if(min_bitrate>0.){
  155332. nominal_bitrate=min_bitrate;
  155333. }else{
  155334. return(OV_EINVAL);
  155335. }
  155336. }
  155337. }
  155338. get_setup_template(vi,channels,rate,nominal_bitrate,1);
  155339. if(!hi->setup)return OV_EIMPL;
  155340. ret=vorbis_encode_setup_setting(vi,channels,rate);
  155341. if(ret){
  155342. vorbis_info_clear(vi);
  155343. return ret;
  155344. }
  155345. /* initialize management with sane defaults */
  155346. hi->managed=1;
  155347. hi->bitrate_min=min_bitrate;
  155348. hi->bitrate_max=max_bitrate;
  155349. hi->bitrate_av=tnominal;
  155350. hi->bitrate_av_damp=1.5f; /* full range in no less than 1.5 second */
  155351. hi->bitrate_reservoir=nominal_bitrate*2;
  155352. hi->bitrate_reservoir_bias=.1; /* bias toward hoarding bits */
  155353. return(ret);
  155354. }
  155355. int vorbis_encode_init(vorbis_info *vi,
  155356. long channels,
  155357. long rate,
  155358. long max_bitrate,
  155359. long nominal_bitrate,
  155360. long min_bitrate){
  155361. int ret=vorbis_encode_setup_managed(vi,channels,rate,
  155362. max_bitrate,
  155363. nominal_bitrate,
  155364. min_bitrate);
  155365. if(ret){
  155366. vorbis_info_clear(vi);
  155367. return(ret);
  155368. }
  155369. ret=vorbis_encode_setup_init(vi);
  155370. if(ret)
  155371. vorbis_info_clear(vi);
  155372. return(ret);
  155373. }
  155374. int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg){
  155375. if(vi){
  155376. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155377. highlevel_encode_setup *hi=&ci->hi;
  155378. int setp=(number&0xf); /* a read request has a low nibble of 0 */
  155379. if(setp && hi->set_in_stone)return(OV_EINVAL);
  155380. switch(number){
  155381. /* now deprecated *****************/
  155382. case OV_ECTL_RATEMANAGE_GET:
  155383. {
  155384. struct ovectl_ratemanage_arg *ai=
  155385. (struct ovectl_ratemanage_arg *)arg;
  155386. ai->management_active=hi->managed;
  155387. ai->bitrate_hard_window=ai->bitrate_av_window=
  155388. (double)hi->bitrate_reservoir/vi->rate;
  155389. ai->bitrate_av_window_center=1.;
  155390. ai->bitrate_hard_min=hi->bitrate_min;
  155391. ai->bitrate_hard_max=hi->bitrate_max;
  155392. ai->bitrate_av_lo=hi->bitrate_av;
  155393. ai->bitrate_av_hi=hi->bitrate_av;
  155394. }
  155395. return(0);
  155396. /* now deprecated *****************/
  155397. case OV_ECTL_RATEMANAGE_SET:
  155398. {
  155399. struct ovectl_ratemanage_arg *ai=
  155400. (struct ovectl_ratemanage_arg *)arg;
  155401. if(ai==NULL){
  155402. hi->managed=0;
  155403. }else{
  155404. hi->managed=ai->management_active;
  155405. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_AVG,arg);
  155406. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_HARD,arg);
  155407. }
  155408. }
  155409. return 0;
  155410. /* now deprecated *****************/
  155411. case OV_ECTL_RATEMANAGE_AVG:
  155412. {
  155413. struct ovectl_ratemanage_arg *ai=
  155414. (struct ovectl_ratemanage_arg *)arg;
  155415. if(ai==NULL){
  155416. hi->bitrate_av=0;
  155417. }else{
  155418. hi->bitrate_av=(ai->bitrate_av_lo+ai->bitrate_av_hi)*.5;
  155419. }
  155420. }
  155421. return(0);
  155422. /* now deprecated *****************/
  155423. case OV_ECTL_RATEMANAGE_HARD:
  155424. {
  155425. struct ovectl_ratemanage_arg *ai=
  155426. (struct ovectl_ratemanage_arg *)arg;
  155427. if(ai==NULL){
  155428. hi->bitrate_min=0;
  155429. hi->bitrate_max=0;
  155430. }else{
  155431. hi->bitrate_min=ai->bitrate_hard_min;
  155432. hi->bitrate_max=ai->bitrate_hard_max;
  155433. hi->bitrate_reservoir=ai->bitrate_hard_window*
  155434. (hi->bitrate_max+hi->bitrate_min)*.5;
  155435. }
  155436. if(hi->bitrate_reservoir<128.)
  155437. hi->bitrate_reservoir=128.;
  155438. }
  155439. return(0);
  155440. /* replacement ratemanage interface */
  155441. case OV_ECTL_RATEMANAGE2_GET:
  155442. {
  155443. struct ovectl_ratemanage2_arg *ai=
  155444. (struct ovectl_ratemanage2_arg *)arg;
  155445. if(ai==NULL)return OV_EINVAL;
  155446. ai->management_active=hi->managed;
  155447. ai->bitrate_limit_min_kbps=hi->bitrate_min/1000;
  155448. ai->bitrate_limit_max_kbps=hi->bitrate_max/1000;
  155449. ai->bitrate_average_kbps=hi->bitrate_av/1000;
  155450. ai->bitrate_average_damping=hi->bitrate_av_damp;
  155451. ai->bitrate_limit_reservoir_bits=hi->bitrate_reservoir;
  155452. ai->bitrate_limit_reservoir_bias=hi->bitrate_reservoir_bias;
  155453. }
  155454. return (0);
  155455. case OV_ECTL_RATEMANAGE2_SET:
  155456. {
  155457. struct ovectl_ratemanage2_arg *ai=
  155458. (struct ovectl_ratemanage2_arg *)arg;
  155459. if(ai==NULL){
  155460. hi->managed=0;
  155461. }else{
  155462. /* sanity check; only catch invariant violations */
  155463. if(ai->bitrate_limit_min_kbps>0 &&
  155464. ai->bitrate_average_kbps>0 &&
  155465. ai->bitrate_limit_min_kbps>ai->bitrate_average_kbps)
  155466. return OV_EINVAL;
  155467. if(ai->bitrate_limit_max_kbps>0 &&
  155468. ai->bitrate_average_kbps>0 &&
  155469. ai->bitrate_limit_max_kbps<ai->bitrate_average_kbps)
  155470. return OV_EINVAL;
  155471. if(ai->bitrate_limit_min_kbps>0 &&
  155472. ai->bitrate_limit_max_kbps>0 &&
  155473. ai->bitrate_limit_min_kbps>ai->bitrate_limit_max_kbps)
  155474. return OV_EINVAL;
  155475. if(ai->bitrate_average_damping <= 0.)
  155476. return OV_EINVAL;
  155477. if(ai->bitrate_limit_reservoir_bits < 0)
  155478. return OV_EINVAL;
  155479. if(ai->bitrate_limit_reservoir_bias < 0.)
  155480. return OV_EINVAL;
  155481. if(ai->bitrate_limit_reservoir_bias > 1.)
  155482. return OV_EINVAL;
  155483. hi->managed=ai->management_active;
  155484. hi->bitrate_min=ai->bitrate_limit_min_kbps * 1000;
  155485. hi->bitrate_max=ai->bitrate_limit_max_kbps * 1000;
  155486. hi->bitrate_av=ai->bitrate_average_kbps * 1000;
  155487. hi->bitrate_av_damp=ai->bitrate_average_damping;
  155488. hi->bitrate_reservoir=ai->bitrate_limit_reservoir_bits;
  155489. hi->bitrate_reservoir_bias=ai->bitrate_limit_reservoir_bias;
  155490. }
  155491. }
  155492. return 0;
  155493. case OV_ECTL_LOWPASS_GET:
  155494. {
  155495. double *farg=(double *)arg;
  155496. *farg=hi->lowpass_kHz;
  155497. }
  155498. return(0);
  155499. case OV_ECTL_LOWPASS_SET:
  155500. {
  155501. double *farg=(double *)arg;
  155502. hi->lowpass_kHz=*farg;
  155503. if(hi->lowpass_kHz<2.)hi->lowpass_kHz=2.;
  155504. if(hi->lowpass_kHz>99.)hi->lowpass_kHz=99.;
  155505. }
  155506. return(0);
  155507. case OV_ECTL_IBLOCK_GET:
  155508. {
  155509. double *farg=(double *)arg;
  155510. *farg=hi->impulse_noisetune;
  155511. }
  155512. return(0);
  155513. case OV_ECTL_IBLOCK_SET:
  155514. {
  155515. double *farg=(double *)arg;
  155516. hi->impulse_noisetune=*farg;
  155517. if(hi->impulse_noisetune>0.)hi->impulse_noisetune=0.;
  155518. if(hi->impulse_noisetune<-15.)hi->impulse_noisetune=-15.;
  155519. }
  155520. return(0);
  155521. }
  155522. return(OV_EIMPL);
  155523. }
  155524. return(OV_EINVAL);
  155525. }
  155526. #endif
  155527. /*** End of inlined file: vorbisenc.c ***/
  155528. /*** Start of inlined file: vorbisfile.c ***/
  155529. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  155530. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  155531. // tasks..
  155532. #if JUCE_MSVC
  155533. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  155534. #endif
  155535. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  155536. #if JUCE_USE_OGGVORBIS
  155537. #include <stdlib.h>
  155538. #include <stdio.h>
  155539. #include <errno.h>
  155540. #include <string.h>
  155541. #include <math.h>
  155542. /* A 'chained bitstream' is a Vorbis bitstream that contains more than
  155543. one logical bitstream arranged end to end (the only form of Ogg
  155544. multiplexing allowed in a Vorbis bitstream; grouping [parallel
  155545. multiplexing] is not allowed in Vorbis) */
  155546. /* A Vorbis file can be played beginning to end (streamed) without
  155547. worrying ahead of time about chaining (see decoder_example.c). If
  155548. we have the whole file, however, and want random access
  155549. (seeking/scrubbing) or desire to know the total length/time of a
  155550. file, we need to account for the possibility of chaining. */
  155551. /* We can handle things a number of ways; we can determine the entire
  155552. bitstream structure right off the bat, or find pieces on demand.
  155553. This example determines and caches structure for the entire
  155554. bitstream, but builds a virtual decoder on the fly when moving
  155555. between links in the chain. */
  155556. /* There are also different ways to implement seeking. Enough
  155557. information exists in an Ogg bitstream to seek to
  155558. sample-granularity positions in the output. Or, one can seek by
  155559. picking some portion of the stream roughly in the desired area if
  155560. we only want coarse navigation through the stream. */
  155561. /*************************************************************************
  155562. * Many, many internal helpers. The intention is not to be confusing;
  155563. * rampant duplication and monolithic function implementation would be
  155564. * harder to understand anyway. The high level functions are last. Begin
  155565. * grokking near the end of the file */
  155566. /* read a little more data from the file/pipe into the ogg_sync framer
  155567. */
  155568. #define CHUNKSIZE 8500 /* a shade over 8k; anyone using pages well
  155569. over 8k gets what they deserve */
  155570. static long _get_data(OggVorbis_File *vf){
  155571. errno=0;
  155572. if(vf->datasource){
  155573. char *buffer=ogg_sync_buffer(&vf->oy,CHUNKSIZE);
  155574. long bytes=(vf->callbacks.read_func)(buffer,1,CHUNKSIZE,vf->datasource);
  155575. if(bytes>0)ogg_sync_wrote(&vf->oy,bytes);
  155576. if(bytes==0 && errno)return(-1);
  155577. return(bytes);
  155578. }else
  155579. return(0);
  155580. }
  155581. /* save a tiny smidge of verbosity to make the code more readable */
  155582. static void _seek_helper(OggVorbis_File *vf,ogg_int64_t offset){
  155583. if(vf->datasource){
  155584. (vf->callbacks.seek_func)(vf->datasource, offset, SEEK_SET);
  155585. vf->offset=offset;
  155586. ogg_sync_reset(&vf->oy);
  155587. }else{
  155588. /* shouldn't happen unless someone writes a broken callback */
  155589. return;
  155590. }
  155591. }
  155592. /* The read/seek functions track absolute position within the stream */
  155593. /* from the head of the stream, get the next page. boundary specifies
  155594. if the function is allowed to fetch more data from the stream (and
  155595. how much) or only use internally buffered data.
  155596. boundary: -1) unbounded search
  155597. 0) read no additional data; use cached only
  155598. n) search for a new page beginning for n bytes
  155599. return: <0) did not find a page (OV_FALSE, OV_EOF, OV_EREAD)
  155600. n) found a page at absolute offset n */
  155601. static ogg_int64_t _get_next_page(OggVorbis_File *vf,ogg_page *og,
  155602. ogg_int64_t boundary){
  155603. if(boundary>0)boundary+=vf->offset;
  155604. while(1){
  155605. long more;
  155606. if(boundary>0 && vf->offset>=boundary)return(OV_FALSE);
  155607. more=ogg_sync_pageseek(&vf->oy,og);
  155608. if(more<0){
  155609. /* skipped n bytes */
  155610. vf->offset-=more;
  155611. }else{
  155612. if(more==0){
  155613. /* send more paramedics */
  155614. if(!boundary)return(OV_FALSE);
  155615. {
  155616. long ret=_get_data(vf);
  155617. if(ret==0)return(OV_EOF);
  155618. if(ret<0)return(OV_EREAD);
  155619. }
  155620. }else{
  155621. /* got a page. Return the offset at the page beginning,
  155622. advance the internal offset past the page end */
  155623. ogg_int64_t ret=vf->offset;
  155624. vf->offset+=more;
  155625. return(ret);
  155626. }
  155627. }
  155628. }
  155629. }
  155630. /* find the latest page beginning before the current stream cursor
  155631. position. Much dirtier than the above as Ogg doesn't have any
  155632. backward search linkage. no 'readp' as it will certainly have to
  155633. read. */
  155634. /* returns offset or OV_EREAD, OV_FAULT */
  155635. static ogg_int64_t _get_prev_page(OggVorbis_File *vf,ogg_page *og){
  155636. ogg_int64_t begin=vf->offset;
  155637. ogg_int64_t end=begin;
  155638. ogg_int64_t ret;
  155639. ogg_int64_t offset=-1;
  155640. while(offset==-1){
  155641. begin-=CHUNKSIZE;
  155642. if(begin<0)
  155643. begin=0;
  155644. _seek_helper(vf,begin);
  155645. while(vf->offset<end){
  155646. ret=_get_next_page(vf,og,end-vf->offset);
  155647. if(ret==OV_EREAD)return(OV_EREAD);
  155648. if(ret<0){
  155649. break;
  155650. }else{
  155651. offset=ret;
  155652. }
  155653. }
  155654. }
  155655. /* we have the offset. Actually snork and hold the page now */
  155656. _seek_helper(vf,offset);
  155657. ret=_get_next_page(vf,og,CHUNKSIZE);
  155658. if(ret<0)
  155659. /* this shouldn't be possible */
  155660. return(OV_EFAULT);
  155661. return(offset);
  155662. }
  155663. /* finds each bitstream link one at a time using a bisection search
  155664. (has to begin by knowing the offset of the lb's initial page).
  155665. Recurses for each link so it can alloc the link storage after
  155666. finding them all, then unroll and fill the cache at the same time */
  155667. static int _bisect_forward_serialno(OggVorbis_File *vf,
  155668. ogg_int64_t begin,
  155669. ogg_int64_t searched,
  155670. ogg_int64_t end,
  155671. long currentno,
  155672. long m){
  155673. ogg_int64_t endsearched=end;
  155674. ogg_int64_t next=end;
  155675. ogg_page og;
  155676. ogg_int64_t ret;
  155677. /* the below guards against garbage seperating the last and
  155678. first pages of two links. */
  155679. while(searched<endsearched){
  155680. ogg_int64_t bisect;
  155681. if(endsearched-searched<CHUNKSIZE){
  155682. bisect=searched;
  155683. }else{
  155684. bisect=(searched+endsearched)/2;
  155685. }
  155686. _seek_helper(vf,bisect);
  155687. ret=_get_next_page(vf,&og,-1);
  155688. if(ret==OV_EREAD)return(OV_EREAD);
  155689. if(ret<0 || ogg_page_serialno(&og)!=currentno){
  155690. endsearched=bisect;
  155691. if(ret>=0)next=ret;
  155692. }else{
  155693. searched=ret+og.header_len+og.body_len;
  155694. }
  155695. }
  155696. _seek_helper(vf,next);
  155697. ret=_get_next_page(vf,&og,-1);
  155698. if(ret==OV_EREAD)return(OV_EREAD);
  155699. if(searched>=end || ret<0){
  155700. vf->links=m+1;
  155701. vf->offsets=(ogg_int64_t*)_ogg_malloc((vf->links+1)*sizeof(*vf->offsets));
  155702. vf->serialnos=(long*)_ogg_malloc(vf->links*sizeof(*vf->serialnos));
  155703. vf->offsets[m+1]=searched;
  155704. }else{
  155705. ret=_bisect_forward_serialno(vf,next,vf->offset,
  155706. end,ogg_page_serialno(&og),m+1);
  155707. if(ret==OV_EREAD)return(OV_EREAD);
  155708. }
  155709. vf->offsets[m]=begin;
  155710. vf->serialnos[m]=currentno;
  155711. return(0);
  155712. }
  155713. /* uses the local ogg_stream storage in vf; this is important for
  155714. non-streaming input sources */
  155715. static int _fetch_headers(OggVorbis_File *vf,vorbis_info *vi,vorbis_comment *vc,
  155716. long *serialno,ogg_page *og_ptr){
  155717. ogg_page og;
  155718. ogg_packet op;
  155719. int i,ret;
  155720. if(!og_ptr){
  155721. ogg_int64_t llret=_get_next_page(vf,&og,CHUNKSIZE);
  155722. if(llret==OV_EREAD)return(OV_EREAD);
  155723. if(llret<0)return OV_ENOTVORBIS;
  155724. og_ptr=&og;
  155725. }
  155726. ogg_stream_reset_serialno(&vf->os,ogg_page_serialno(og_ptr));
  155727. if(serialno)*serialno=vf->os.serialno;
  155728. vf->ready_state=STREAMSET;
  155729. /* extract the initial header from the first page and verify that the
  155730. Ogg bitstream is in fact Vorbis data */
  155731. vorbis_info_init(vi);
  155732. vorbis_comment_init(vc);
  155733. i=0;
  155734. while(i<3){
  155735. ogg_stream_pagein(&vf->os,og_ptr);
  155736. while(i<3){
  155737. int result=ogg_stream_packetout(&vf->os,&op);
  155738. if(result==0)break;
  155739. if(result==-1){
  155740. ret=OV_EBADHEADER;
  155741. goto bail_header;
  155742. }
  155743. if((ret=vorbis_synthesis_headerin(vi,vc,&op))){
  155744. goto bail_header;
  155745. }
  155746. i++;
  155747. }
  155748. if(i<3)
  155749. if(_get_next_page(vf,og_ptr,CHUNKSIZE)<0){
  155750. ret=OV_EBADHEADER;
  155751. goto bail_header;
  155752. }
  155753. }
  155754. return 0;
  155755. bail_header:
  155756. vorbis_info_clear(vi);
  155757. vorbis_comment_clear(vc);
  155758. vf->ready_state=OPENED;
  155759. return ret;
  155760. }
  155761. /* last step of the OggVorbis_File initialization; get all the
  155762. vorbis_info structs and PCM positions. Only called by the seekable
  155763. initialization (local stream storage is hacked slightly; pay
  155764. attention to how that's done) */
  155765. /* this is void and does not propogate errors up because we want to be
  155766. able to open and use damaged bitstreams as well as we can. Just
  155767. watch out for missing information for links in the OggVorbis_File
  155768. struct */
  155769. static void _prefetch_all_headers(OggVorbis_File *vf, ogg_int64_t dataoffset){
  155770. ogg_page og;
  155771. int i;
  155772. ogg_int64_t ret;
  155773. vf->vi=(vorbis_info*) _ogg_realloc(vf->vi,vf->links*sizeof(*vf->vi));
  155774. vf->vc=(vorbis_comment*) _ogg_realloc(vf->vc,vf->links*sizeof(*vf->vc));
  155775. vf->dataoffsets=(ogg_int64_t*) _ogg_malloc(vf->links*sizeof(*vf->dataoffsets));
  155776. vf->pcmlengths=(ogg_int64_t*) _ogg_malloc(vf->links*2*sizeof(*vf->pcmlengths));
  155777. for(i=0;i<vf->links;i++){
  155778. if(i==0){
  155779. /* we already grabbed the initial header earlier. Just set the offset */
  155780. vf->dataoffsets[i]=dataoffset;
  155781. _seek_helper(vf,dataoffset);
  155782. }else{
  155783. /* seek to the location of the initial header */
  155784. _seek_helper(vf,vf->offsets[i]);
  155785. if(_fetch_headers(vf,vf->vi+i,vf->vc+i,NULL,NULL)<0){
  155786. vf->dataoffsets[i]=-1;
  155787. }else{
  155788. vf->dataoffsets[i]=vf->offset;
  155789. }
  155790. }
  155791. /* fetch beginning PCM offset */
  155792. if(vf->dataoffsets[i]!=-1){
  155793. ogg_int64_t accumulated=0;
  155794. long lastblock=-1;
  155795. int result;
  155796. ogg_stream_reset_serialno(&vf->os,vf->serialnos[i]);
  155797. while(1){
  155798. ogg_packet op;
  155799. ret=_get_next_page(vf,&og,-1);
  155800. if(ret<0)
  155801. /* this should not be possible unless the file is
  155802. truncated/mangled */
  155803. break;
  155804. if(ogg_page_serialno(&og)!=vf->serialnos[i])
  155805. break;
  155806. /* count blocksizes of all frames in the page */
  155807. ogg_stream_pagein(&vf->os,&og);
  155808. while((result=ogg_stream_packetout(&vf->os,&op))){
  155809. if(result>0){ /* ignore holes */
  155810. long thisblock=vorbis_packet_blocksize(vf->vi+i,&op);
  155811. if(lastblock!=-1)
  155812. accumulated+=(lastblock+thisblock)>>2;
  155813. lastblock=thisblock;
  155814. }
  155815. }
  155816. if(ogg_page_granulepos(&og)!=-1){
  155817. /* pcm offset of last packet on the first audio page */
  155818. accumulated= ogg_page_granulepos(&og)-accumulated;
  155819. break;
  155820. }
  155821. }
  155822. /* less than zero? This is a stream with samples trimmed off
  155823. the beginning, a normal occurrence; set the offset to zero */
  155824. if(accumulated<0)accumulated=0;
  155825. vf->pcmlengths[i*2]=accumulated;
  155826. }
  155827. /* get the PCM length of this link. To do this,
  155828. get the last page of the stream */
  155829. {
  155830. ogg_int64_t end=vf->offsets[i+1];
  155831. _seek_helper(vf,end);
  155832. while(1){
  155833. ret=_get_prev_page(vf,&og);
  155834. if(ret<0){
  155835. /* this should not be possible */
  155836. vorbis_info_clear(vf->vi+i);
  155837. vorbis_comment_clear(vf->vc+i);
  155838. break;
  155839. }
  155840. if(ogg_page_granulepos(&og)!=-1){
  155841. vf->pcmlengths[i*2+1]=ogg_page_granulepos(&og)-vf->pcmlengths[i*2];
  155842. break;
  155843. }
  155844. vf->offset=ret;
  155845. }
  155846. }
  155847. }
  155848. }
  155849. static int _make_decode_ready(OggVorbis_File *vf){
  155850. if(vf->ready_state>STREAMSET)return 0;
  155851. if(vf->ready_state<STREAMSET)return OV_EFAULT;
  155852. if(vf->seekable){
  155853. if(vorbis_synthesis_init(&vf->vd,vf->vi+vf->current_link))
  155854. return OV_EBADLINK;
  155855. }else{
  155856. if(vorbis_synthesis_init(&vf->vd,vf->vi))
  155857. return OV_EBADLINK;
  155858. }
  155859. vorbis_block_init(&vf->vd,&vf->vb);
  155860. vf->ready_state=INITSET;
  155861. vf->bittrack=0.f;
  155862. vf->samptrack=0.f;
  155863. return 0;
  155864. }
  155865. static int _open_seekable2(OggVorbis_File *vf){
  155866. long serialno=vf->current_serialno;
  155867. ogg_int64_t dataoffset=vf->offset, end;
  155868. ogg_page og;
  155869. /* we're partially open and have a first link header state in
  155870. storage in vf */
  155871. /* we can seek, so set out learning all about this file */
  155872. (vf->callbacks.seek_func)(vf->datasource,0,SEEK_END);
  155873. vf->offset=vf->end=(vf->callbacks.tell_func)(vf->datasource);
  155874. /* We get the offset for the last page of the physical bitstream.
  155875. Most OggVorbis files will contain a single logical bitstream */
  155876. end=_get_prev_page(vf,&og);
  155877. if(end<0)return(end);
  155878. /* more than one logical bitstream? */
  155879. if(ogg_page_serialno(&og)!=serialno){
  155880. /* Chained bitstream. Bisect-search each logical bitstream
  155881. section. Do so based on serial number only */
  155882. if(_bisect_forward_serialno(vf,0,0,end+1,serialno,0)<0)return(OV_EREAD);
  155883. }else{
  155884. /* Only one logical bitstream */
  155885. if(_bisect_forward_serialno(vf,0,end,end+1,serialno,0))return(OV_EREAD);
  155886. }
  155887. /* the initial header memory is referenced by vf after; don't free it */
  155888. _prefetch_all_headers(vf,dataoffset);
  155889. return(ov_raw_seek(vf,0));
  155890. }
  155891. /* clear out the current logical bitstream decoder */
  155892. static void _decode_clear(OggVorbis_File *vf){
  155893. vorbis_dsp_clear(&vf->vd);
  155894. vorbis_block_clear(&vf->vb);
  155895. vf->ready_state=OPENED;
  155896. }
  155897. /* fetch and process a packet. Handles the case where we're at a
  155898. bitstream boundary and dumps the decoding machine. If the decoding
  155899. machine is unloaded, it loads it. It also keeps pcm_offset up to
  155900. date (seek and read both use this. seek uses a special hack with
  155901. readp).
  155902. return: <0) error, OV_HOLE (lost packet) or OV_EOF
  155903. 0) need more data (only if readp==0)
  155904. 1) got a packet
  155905. */
  155906. static int _fetch_and_process_packet(OggVorbis_File *vf,
  155907. ogg_packet *op_in,
  155908. int readp,
  155909. int spanp){
  155910. ogg_page og;
  155911. /* handle one packet. Try to fetch it from current stream state */
  155912. /* extract packets from page */
  155913. while(1){
  155914. /* process a packet if we can. If the machine isn't loaded,
  155915. neither is a page */
  155916. if(vf->ready_state==INITSET){
  155917. while(1) {
  155918. ogg_packet op;
  155919. ogg_packet *op_ptr=(op_in?op_in:&op);
  155920. int result=ogg_stream_packetout(&vf->os,op_ptr);
  155921. ogg_int64_t granulepos;
  155922. op_in=NULL;
  155923. if(result==-1)return(OV_HOLE); /* hole in the data. */
  155924. if(result>0){
  155925. /* got a packet. process it */
  155926. granulepos=op_ptr->granulepos;
  155927. if(!vorbis_synthesis(&vf->vb,op_ptr)){ /* lazy check for lazy
  155928. header handling. The
  155929. header packets aren't
  155930. audio, so if/when we
  155931. submit them,
  155932. vorbis_synthesis will
  155933. reject them */
  155934. /* suck in the synthesis data and track bitrate */
  155935. {
  155936. int oldsamples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  155937. /* for proper use of libvorbis within libvorbisfile,
  155938. oldsamples will always be zero. */
  155939. if(oldsamples)return(OV_EFAULT);
  155940. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  155941. vf->samptrack+=vorbis_synthesis_pcmout(&vf->vd,NULL)-oldsamples;
  155942. vf->bittrack+=op_ptr->bytes*8;
  155943. }
  155944. /* update the pcm offset. */
  155945. if(granulepos!=-1 && !op_ptr->e_o_s){
  155946. int link=(vf->seekable?vf->current_link:0);
  155947. int i,samples;
  155948. /* this packet has a pcm_offset on it (the last packet
  155949. completed on a page carries the offset) After processing
  155950. (above), we know the pcm position of the *last* sample
  155951. ready to be returned. Find the offset of the *first*
  155952. As an aside, this trick is inaccurate if we begin
  155953. reading anew right at the last page; the end-of-stream
  155954. granulepos declares the last frame in the stream, and the
  155955. last packet of the last page may be a partial frame.
  155956. So, we need a previous granulepos from an in-sequence page
  155957. to have a reference point. Thus the !op_ptr->e_o_s clause
  155958. above */
  155959. if(vf->seekable && link>0)
  155960. granulepos-=vf->pcmlengths[link*2];
  155961. if(granulepos<0)granulepos=0; /* actually, this
  155962. shouldn't be possible
  155963. here unless the stream
  155964. is very broken */
  155965. samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  155966. granulepos-=samples;
  155967. for(i=0;i<link;i++)
  155968. granulepos+=vf->pcmlengths[i*2+1];
  155969. vf->pcm_offset=granulepos;
  155970. }
  155971. return(1);
  155972. }
  155973. }
  155974. else
  155975. break;
  155976. }
  155977. }
  155978. if(vf->ready_state>=OPENED){
  155979. ogg_int64_t ret;
  155980. if(!readp)return(0);
  155981. if((ret=_get_next_page(vf,&og,-1))<0){
  155982. return(OV_EOF); /* eof.
  155983. leave unitialized */
  155984. }
  155985. /* bitrate tracking; add the header's bytes here, the body bytes
  155986. are done by packet above */
  155987. vf->bittrack+=og.header_len*8;
  155988. /* has our decoding just traversed a bitstream boundary? */
  155989. if(vf->ready_state==INITSET){
  155990. if(vf->current_serialno!=ogg_page_serialno(&og)){
  155991. if(!spanp)
  155992. return(OV_EOF);
  155993. _decode_clear(vf);
  155994. if(!vf->seekable){
  155995. vorbis_info_clear(vf->vi);
  155996. vorbis_comment_clear(vf->vc);
  155997. }
  155998. }
  155999. }
  156000. }
  156001. /* Do we need to load a new machine before submitting the page? */
  156002. /* This is different in the seekable and non-seekable cases.
  156003. In the seekable case, we already have all the header
  156004. information loaded and cached; we just initialize the machine
  156005. with it and continue on our merry way.
  156006. In the non-seekable (streaming) case, we'll only be at a
  156007. boundary if we just left the previous logical bitstream and
  156008. we're now nominally at the header of the next bitstream
  156009. */
  156010. if(vf->ready_state!=INITSET){
  156011. int link;
  156012. if(vf->ready_state<STREAMSET){
  156013. if(vf->seekable){
  156014. vf->current_serialno=ogg_page_serialno(&og);
  156015. /* match the serialno to bitstream section. We use this rather than
  156016. offset positions to avoid problems near logical bitstream
  156017. boundaries */
  156018. for(link=0;link<vf->links;link++)
  156019. if(vf->serialnos[link]==vf->current_serialno)break;
  156020. if(link==vf->links)return(OV_EBADLINK); /* sign of a bogus
  156021. stream. error out,
  156022. leave machine
  156023. uninitialized */
  156024. vf->current_link=link;
  156025. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156026. vf->ready_state=STREAMSET;
  156027. }else{
  156028. /* we're streaming */
  156029. /* fetch the three header packets, build the info struct */
  156030. int ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,&og);
  156031. if(ret)return(ret);
  156032. vf->current_link++;
  156033. link=0;
  156034. }
  156035. }
  156036. {
  156037. int ret=_make_decode_ready(vf);
  156038. if(ret<0)return ret;
  156039. }
  156040. }
  156041. ogg_stream_pagein(&vf->os,&og);
  156042. }
  156043. }
  156044. /* if, eg, 64 bit stdio is configured by default, this will build with
  156045. fseek64 */
  156046. static int _fseek64_wrap(FILE *f,ogg_int64_t off,int whence){
  156047. if(f==NULL)return(-1);
  156048. return fseek(f,off,whence);
  156049. }
  156050. static int _ov_open1(void *f,OggVorbis_File *vf,char *initial,
  156051. long ibytes, ov_callbacks callbacks){
  156052. int offsettest=(f?callbacks.seek_func(f,0,SEEK_CUR):-1);
  156053. int ret;
  156054. memset(vf,0,sizeof(*vf));
  156055. vf->datasource=f;
  156056. vf->callbacks = callbacks;
  156057. /* init the framing state */
  156058. ogg_sync_init(&vf->oy);
  156059. /* perhaps some data was previously read into a buffer for testing
  156060. against other stream types. Allow initialization from this
  156061. previously read data (as we may be reading from a non-seekable
  156062. stream) */
  156063. if(initial){
  156064. char *buffer=ogg_sync_buffer(&vf->oy,ibytes);
  156065. memcpy(buffer,initial,ibytes);
  156066. ogg_sync_wrote(&vf->oy,ibytes);
  156067. }
  156068. /* can we seek? Stevens suggests the seek test was portable */
  156069. if(offsettest!=-1)vf->seekable=1;
  156070. /* No seeking yet; Set up a 'single' (current) logical bitstream
  156071. entry for partial open */
  156072. vf->links=1;
  156073. vf->vi=(vorbis_info*) _ogg_calloc(vf->links,sizeof(*vf->vi));
  156074. vf->vc=(vorbis_comment*) _ogg_calloc(vf->links,sizeof(*vf->vc));
  156075. ogg_stream_init(&vf->os,-1); /* fill in the serialno later */
  156076. /* Try to fetch the headers, maintaining all the storage */
  156077. if((ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,NULL))<0){
  156078. vf->datasource=NULL;
  156079. ov_clear(vf);
  156080. }else
  156081. vf->ready_state=PARTOPEN;
  156082. return(ret);
  156083. }
  156084. static int _ov_open2(OggVorbis_File *vf){
  156085. if(vf->ready_state != PARTOPEN) return OV_EINVAL;
  156086. vf->ready_state=OPENED;
  156087. if(vf->seekable){
  156088. int ret=_open_seekable2(vf);
  156089. if(ret){
  156090. vf->datasource=NULL;
  156091. ov_clear(vf);
  156092. }
  156093. return(ret);
  156094. }else
  156095. vf->ready_state=STREAMSET;
  156096. return 0;
  156097. }
  156098. /* clear out the OggVorbis_File struct */
  156099. int ov_clear(OggVorbis_File *vf){
  156100. if(vf){
  156101. vorbis_block_clear(&vf->vb);
  156102. vorbis_dsp_clear(&vf->vd);
  156103. ogg_stream_clear(&vf->os);
  156104. if(vf->vi && vf->links){
  156105. int i;
  156106. for(i=0;i<vf->links;i++){
  156107. vorbis_info_clear(vf->vi+i);
  156108. vorbis_comment_clear(vf->vc+i);
  156109. }
  156110. _ogg_free(vf->vi);
  156111. _ogg_free(vf->vc);
  156112. }
  156113. if(vf->dataoffsets)_ogg_free(vf->dataoffsets);
  156114. if(vf->pcmlengths)_ogg_free(vf->pcmlengths);
  156115. if(vf->serialnos)_ogg_free(vf->serialnos);
  156116. if(vf->offsets)_ogg_free(vf->offsets);
  156117. ogg_sync_clear(&vf->oy);
  156118. if(vf->datasource)(vf->callbacks.close_func)(vf->datasource);
  156119. memset(vf,0,sizeof(*vf));
  156120. }
  156121. #ifdef DEBUG_LEAKS
  156122. _VDBG_dump();
  156123. #endif
  156124. return(0);
  156125. }
  156126. /* inspects the OggVorbis file and finds/documents all the logical
  156127. bitstreams contained in it. Tries to be tolerant of logical
  156128. bitstream sections that are truncated/woogie.
  156129. return: -1) error
  156130. 0) OK
  156131. */
  156132. int ov_open_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  156133. ov_callbacks callbacks){
  156134. int ret=_ov_open1(f,vf,initial,ibytes,callbacks);
  156135. if(ret)return ret;
  156136. return _ov_open2(vf);
  156137. }
  156138. int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  156139. ov_callbacks callbacks = {
  156140. (size_t (*)(void *, size_t, size_t, void *)) fread,
  156141. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  156142. (int (*)(void *)) fclose,
  156143. (long (*)(void *)) ftell
  156144. };
  156145. return ov_open_callbacks((void *)f, vf, initial, ibytes, callbacks);
  156146. }
  156147. /* cheap hack for game usage where downsampling is desirable; there's
  156148. no need for SRC as we can just do it cheaply in libvorbis. */
  156149. int ov_halfrate(OggVorbis_File *vf,int flag){
  156150. int i;
  156151. if(vf->vi==NULL)return OV_EINVAL;
  156152. if(!vf->seekable)return OV_EINVAL;
  156153. if(vf->ready_state>=STREAMSET)
  156154. _decode_clear(vf); /* clear out stream state; later on libvorbis
  156155. will be able to swap this on the fly, but
  156156. for now dumping the decode machine is needed
  156157. to reinit the MDCT lookups. 1.1 libvorbis
  156158. is planned to be able to switch on the fly */
  156159. for(i=0;i<vf->links;i++){
  156160. if(vorbis_synthesis_halfrate(vf->vi+i,flag)){
  156161. ov_halfrate(vf,0);
  156162. return OV_EINVAL;
  156163. }
  156164. }
  156165. return 0;
  156166. }
  156167. int ov_halfrate_p(OggVorbis_File *vf){
  156168. if(vf->vi==NULL)return OV_EINVAL;
  156169. return vorbis_synthesis_halfrate_p(vf->vi);
  156170. }
  156171. /* Only partially open the vorbis file; test for Vorbisness, and load
  156172. the headers for the first chain. Do not seek (although test for
  156173. seekability). Use ov_test_open to finish opening the file, else
  156174. ov_clear to close/free it. Same return codes as open. */
  156175. int ov_test_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  156176. ov_callbacks callbacks)
  156177. {
  156178. return _ov_open1(f,vf,initial,ibytes,callbacks);
  156179. }
  156180. int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  156181. ov_callbacks callbacks = {
  156182. (size_t (*)(void *, size_t, size_t, void *)) fread,
  156183. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  156184. (int (*)(void *)) fclose,
  156185. (long (*)(void *)) ftell
  156186. };
  156187. return ov_test_callbacks((void *)f, vf, initial, ibytes, callbacks);
  156188. }
  156189. int ov_test_open(OggVorbis_File *vf){
  156190. if(vf->ready_state!=PARTOPEN)return(OV_EINVAL);
  156191. return _ov_open2(vf);
  156192. }
  156193. /* How many logical bitstreams in this physical bitstream? */
  156194. long ov_streams(OggVorbis_File *vf){
  156195. return vf->links;
  156196. }
  156197. /* Is the FILE * associated with vf seekable? */
  156198. long ov_seekable(OggVorbis_File *vf){
  156199. return vf->seekable;
  156200. }
  156201. /* returns the bitrate for a given logical bitstream or the entire
  156202. physical bitstream. If the file is open for random access, it will
  156203. find the *actual* average bitrate. If the file is streaming, it
  156204. returns the nominal bitrate (if set) else the average of the
  156205. upper/lower bounds (if set) else -1 (unset).
  156206. If you want the actual bitrate field settings, get them from the
  156207. vorbis_info structs */
  156208. long ov_bitrate(OggVorbis_File *vf,int i){
  156209. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156210. if(i>=vf->links)return(OV_EINVAL);
  156211. if(!vf->seekable && i!=0)return(ov_bitrate(vf,0));
  156212. if(i<0){
  156213. ogg_int64_t bits=0;
  156214. int i;
  156215. float br;
  156216. for(i=0;i<vf->links;i++)
  156217. bits+=(vf->offsets[i+1]-vf->dataoffsets[i])*8;
  156218. /* This once read: return(rint(bits/ov_time_total(vf,-1)));
  156219. * gcc 3.x on x86 miscompiled this at optimisation level 2 and above,
  156220. * so this is slightly transformed to make it work.
  156221. */
  156222. br = bits/ov_time_total(vf,-1);
  156223. return(rint(br));
  156224. }else{
  156225. if(vf->seekable){
  156226. /* return the actual bitrate */
  156227. return(rint((vf->offsets[i+1]-vf->dataoffsets[i])*8/ov_time_total(vf,i)));
  156228. }else{
  156229. /* return nominal if set */
  156230. if(vf->vi[i].bitrate_nominal>0){
  156231. return vf->vi[i].bitrate_nominal;
  156232. }else{
  156233. if(vf->vi[i].bitrate_upper>0){
  156234. if(vf->vi[i].bitrate_lower>0){
  156235. return (vf->vi[i].bitrate_upper+vf->vi[i].bitrate_lower)/2;
  156236. }else{
  156237. return vf->vi[i].bitrate_upper;
  156238. }
  156239. }
  156240. return(OV_FALSE);
  156241. }
  156242. }
  156243. }
  156244. }
  156245. /* returns the actual bitrate since last call. returns -1 if no
  156246. additional data to offer since last call (or at beginning of stream),
  156247. EINVAL if stream is only partially open
  156248. */
  156249. long ov_bitrate_instant(OggVorbis_File *vf){
  156250. int link=(vf->seekable?vf->current_link:0);
  156251. long ret;
  156252. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156253. if(vf->samptrack==0)return(OV_FALSE);
  156254. ret=vf->bittrack/vf->samptrack*vf->vi[link].rate+.5;
  156255. vf->bittrack=0.f;
  156256. vf->samptrack=0.f;
  156257. return(ret);
  156258. }
  156259. /* Guess */
  156260. long ov_serialnumber(OggVorbis_File *vf,int i){
  156261. if(i>=vf->links)return(ov_serialnumber(vf,vf->links-1));
  156262. if(!vf->seekable && i>=0)return(ov_serialnumber(vf,-1));
  156263. if(i<0){
  156264. return(vf->current_serialno);
  156265. }else{
  156266. return(vf->serialnos[i]);
  156267. }
  156268. }
  156269. /* returns: total raw (compressed) length of content if i==-1
  156270. raw (compressed) length of that logical bitstream for i==0 to n
  156271. OV_EINVAL if the stream is not seekable (we can't know the length)
  156272. or if stream is only partially open
  156273. */
  156274. ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i){
  156275. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156276. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  156277. if(i<0){
  156278. ogg_int64_t acc=0;
  156279. int i;
  156280. for(i=0;i<vf->links;i++)
  156281. acc+=ov_raw_total(vf,i);
  156282. return(acc);
  156283. }else{
  156284. return(vf->offsets[i+1]-vf->offsets[i]);
  156285. }
  156286. }
  156287. /* returns: total PCM length (samples) of content if i==-1 PCM length
  156288. (samples) of that logical bitstream for i==0 to n
  156289. OV_EINVAL if the stream is not seekable (we can't know the
  156290. length) or only partially open
  156291. */
  156292. ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i){
  156293. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156294. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  156295. if(i<0){
  156296. ogg_int64_t acc=0;
  156297. int i;
  156298. for(i=0;i<vf->links;i++)
  156299. acc+=ov_pcm_total(vf,i);
  156300. return(acc);
  156301. }else{
  156302. return(vf->pcmlengths[i*2+1]);
  156303. }
  156304. }
  156305. /* returns: total seconds of content if i==-1
  156306. seconds in that logical bitstream for i==0 to n
  156307. OV_EINVAL if the stream is not seekable (we can't know the
  156308. length) or only partially open
  156309. */
  156310. double ov_time_total(OggVorbis_File *vf,int i){
  156311. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156312. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  156313. if(i<0){
  156314. double acc=0;
  156315. int i;
  156316. for(i=0;i<vf->links;i++)
  156317. acc+=ov_time_total(vf,i);
  156318. return(acc);
  156319. }else{
  156320. return((double)(vf->pcmlengths[i*2+1])/vf->vi[i].rate);
  156321. }
  156322. }
  156323. /* seek to an offset relative to the *compressed* data. This also
  156324. scans packets to update the PCM cursor. It will cross a logical
  156325. bitstream boundary, but only if it can't get any packets out of the
  156326. tail of the bitstream we seek to (so no surprises).
  156327. returns zero on success, nonzero on failure */
  156328. int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos){
  156329. ogg_stream_state work_os;
  156330. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156331. if(!vf->seekable)
  156332. return(OV_ENOSEEK); /* don't dump machine if we can't seek */
  156333. if(pos<0 || pos>vf->end)return(OV_EINVAL);
  156334. /* don't yet clear out decoding machine (if it's initialized), in
  156335. the case we're in the same link. Restart the decode lapping, and
  156336. let _fetch_and_process_packet deal with a potential bitstream
  156337. boundary */
  156338. vf->pcm_offset=-1;
  156339. ogg_stream_reset_serialno(&vf->os,
  156340. vf->current_serialno); /* must set serialno */
  156341. vorbis_synthesis_restart(&vf->vd);
  156342. _seek_helper(vf,pos);
  156343. /* we need to make sure the pcm_offset is set, but we don't want to
  156344. advance the raw cursor past good packets just to get to the first
  156345. with a granulepos. That's not equivalent behavior to beginning
  156346. decoding as immediately after the seek position as possible.
  156347. So, a hack. We use two stream states; a local scratch state and
  156348. the shared vf->os stream state. We use the local state to
  156349. scan, and the shared state as a buffer for later decode.
  156350. Unfortuantely, on the last page we still advance to last packet
  156351. because the granulepos on the last page is not necessarily on a
  156352. packet boundary, and we need to make sure the granpos is
  156353. correct.
  156354. */
  156355. {
  156356. ogg_page og;
  156357. ogg_packet op;
  156358. int lastblock=0;
  156359. int accblock=0;
  156360. int thisblock;
  156361. int eosflag;
  156362. ogg_stream_init(&work_os,vf->current_serialno); /* get the memory ready */
  156363. ogg_stream_reset(&work_os); /* eliminate the spurious OV_HOLE
  156364. return from not necessarily
  156365. starting from the beginning */
  156366. while(1){
  156367. if(vf->ready_state>=STREAMSET){
  156368. /* snarf/scan a packet if we can */
  156369. int result=ogg_stream_packetout(&work_os,&op);
  156370. if(result>0){
  156371. if(vf->vi[vf->current_link].codec_setup){
  156372. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  156373. if(thisblock<0){
  156374. ogg_stream_packetout(&vf->os,NULL);
  156375. thisblock=0;
  156376. }else{
  156377. if(eosflag)
  156378. ogg_stream_packetout(&vf->os,NULL);
  156379. else
  156380. if(lastblock)accblock+=(lastblock+thisblock)>>2;
  156381. }
  156382. if(op.granulepos!=-1){
  156383. int i,link=vf->current_link;
  156384. ogg_int64_t granulepos=op.granulepos-vf->pcmlengths[link*2];
  156385. if(granulepos<0)granulepos=0;
  156386. for(i=0;i<link;i++)
  156387. granulepos+=vf->pcmlengths[i*2+1];
  156388. vf->pcm_offset=granulepos-accblock;
  156389. break;
  156390. }
  156391. lastblock=thisblock;
  156392. continue;
  156393. }else
  156394. ogg_stream_packetout(&vf->os,NULL);
  156395. }
  156396. }
  156397. if(!lastblock){
  156398. if(_get_next_page(vf,&og,-1)<0){
  156399. vf->pcm_offset=ov_pcm_total(vf,-1);
  156400. break;
  156401. }
  156402. }else{
  156403. /* huh? Bogus stream with packets but no granulepos */
  156404. vf->pcm_offset=-1;
  156405. break;
  156406. }
  156407. /* has our decoding just traversed a bitstream boundary? */
  156408. if(vf->ready_state>=STREAMSET)
  156409. if(vf->current_serialno!=ogg_page_serialno(&og)){
  156410. _decode_clear(vf); /* clear out stream state */
  156411. ogg_stream_clear(&work_os);
  156412. }
  156413. if(vf->ready_state<STREAMSET){
  156414. int link;
  156415. vf->current_serialno=ogg_page_serialno(&og);
  156416. for(link=0;link<vf->links;link++)
  156417. if(vf->serialnos[link]==vf->current_serialno)break;
  156418. if(link==vf->links)goto seek_error; /* sign of a bogus stream.
  156419. error out, leave
  156420. machine uninitialized */
  156421. vf->current_link=link;
  156422. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156423. ogg_stream_reset_serialno(&work_os,vf->current_serialno);
  156424. vf->ready_state=STREAMSET;
  156425. }
  156426. ogg_stream_pagein(&vf->os,&og);
  156427. ogg_stream_pagein(&work_os,&og);
  156428. eosflag=ogg_page_eos(&og);
  156429. }
  156430. }
  156431. ogg_stream_clear(&work_os);
  156432. vf->bittrack=0.f;
  156433. vf->samptrack=0.f;
  156434. return(0);
  156435. seek_error:
  156436. /* dump the machine so we're in a known state */
  156437. vf->pcm_offset=-1;
  156438. ogg_stream_clear(&work_os);
  156439. _decode_clear(vf);
  156440. return OV_EBADLINK;
  156441. }
  156442. /* Page granularity seek (faster than sample granularity because we
  156443. don't do the last bit of decode to find a specific sample).
  156444. Seek to the last [granule marked] page preceeding the specified pos
  156445. location, such that decoding past the returned point will quickly
  156446. arrive at the requested position. */
  156447. int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos){
  156448. int link=-1;
  156449. ogg_int64_t result=0;
  156450. ogg_int64_t total=ov_pcm_total(vf,-1);
  156451. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156452. if(!vf->seekable)return(OV_ENOSEEK);
  156453. if(pos<0 || pos>total)return(OV_EINVAL);
  156454. /* which bitstream section does this pcm offset occur in? */
  156455. for(link=vf->links-1;link>=0;link--){
  156456. total-=vf->pcmlengths[link*2+1];
  156457. if(pos>=total)break;
  156458. }
  156459. /* search within the logical bitstream for the page with the highest
  156460. pcm_pos preceeding (or equal to) pos. There is a danger here;
  156461. missing pages or incorrect frame number information in the
  156462. bitstream could make our task impossible. Account for that (it
  156463. would be an error condition) */
  156464. /* new search algorithm by HB (Nicholas Vinen) */
  156465. {
  156466. ogg_int64_t end=vf->offsets[link+1];
  156467. ogg_int64_t begin=vf->offsets[link];
  156468. ogg_int64_t begintime = vf->pcmlengths[link*2];
  156469. ogg_int64_t endtime = vf->pcmlengths[link*2+1]+begintime;
  156470. ogg_int64_t target=pos-total+begintime;
  156471. ogg_int64_t best=begin;
  156472. ogg_page og;
  156473. while(begin<end){
  156474. ogg_int64_t bisect;
  156475. if(end-begin<CHUNKSIZE){
  156476. bisect=begin;
  156477. }else{
  156478. /* take a (pretty decent) guess. */
  156479. bisect=begin +
  156480. (target-begintime)*(end-begin)/(endtime-begintime) - CHUNKSIZE;
  156481. if(bisect<=begin)
  156482. bisect=begin+1;
  156483. }
  156484. _seek_helper(vf,bisect);
  156485. while(begin<end){
  156486. result=_get_next_page(vf,&og,end-vf->offset);
  156487. if(result==OV_EREAD) goto seek_error;
  156488. if(result<0){
  156489. if(bisect<=begin+1)
  156490. end=begin; /* found it */
  156491. else{
  156492. if(bisect==0) goto seek_error;
  156493. bisect-=CHUNKSIZE;
  156494. if(bisect<=begin)bisect=begin+1;
  156495. _seek_helper(vf,bisect);
  156496. }
  156497. }else{
  156498. ogg_int64_t granulepos=ogg_page_granulepos(&og);
  156499. if(granulepos==-1)continue;
  156500. if(granulepos<target){
  156501. best=result; /* raw offset of packet with granulepos */
  156502. begin=vf->offset; /* raw offset of next page */
  156503. begintime=granulepos;
  156504. if(target-begintime>44100)break;
  156505. bisect=begin; /* *not* begin + 1 */
  156506. }else{
  156507. if(bisect<=begin+1)
  156508. end=begin; /* found it */
  156509. else{
  156510. if(end==vf->offset){ /* we're pretty close - we'd be stuck in */
  156511. end=result;
  156512. bisect-=CHUNKSIZE; /* an endless loop otherwise. */
  156513. if(bisect<=begin)bisect=begin+1;
  156514. _seek_helper(vf,bisect);
  156515. }else{
  156516. end=result;
  156517. endtime=granulepos;
  156518. break;
  156519. }
  156520. }
  156521. }
  156522. }
  156523. }
  156524. }
  156525. /* found our page. seek to it, update pcm offset. Easier case than
  156526. raw_seek, don't keep packets preceeding granulepos. */
  156527. {
  156528. ogg_page og;
  156529. ogg_packet op;
  156530. /* seek */
  156531. _seek_helper(vf,best);
  156532. vf->pcm_offset=-1;
  156533. if(_get_next_page(vf,&og,-1)<0)return(OV_EOF); /* shouldn't happen */
  156534. if(link!=vf->current_link){
  156535. /* Different link; dump entire decode machine */
  156536. _decode_clear(vf);
  156537. vf->current_link=link;
  156538. vf->current_serialno=ogg_page_serialno(&og);
  156539. vf->ready_state=STREAMSET;
  156540. }else{
  156541. vorbis_synthesis_restart(&vf->vd);
  156542. }
  156543. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156544. ogg_stream_pagein(&vf->os,&og);
  156545. /* pull out all but last packet; the one with granulepos */
  156546. while(1){
  156547. result=ogg_stream_packetpeek(&vf->os,&op);
  156548. if(result==0){
  156549. /* !!! the packet finishing this page originated on a
  156550. preceeding page. Keep fetching previous pages until we
  156551. get one with a granulepos or without the 'continued' flag
  156552. set. Then just use raw_seek for simplicity. */
  156553. _seek_helper(vf,best);
  156554. while(1){
  156555. result=_get_prev_page(vf,&og);
  156556. if(result<0) goto seek_error;
  156557. if(ogg_page_granulepos(&og)>-1 ||
  156558. !ogg_page_continued(&og)){
  156559. return ov_raw_seek(vf,result);
  156560. }
  156561. vf->offset=result;
  156562. }
  156563. }
  156564. if(result<0){
  156565. result = OV_EBADPACKET;
  156566. goto seek_error;
  156567. }
  156568. if(op.granulepos!=-1){
  156569. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  156570. if(vf->pcm_offset<0)vf->pcm_offset=0;
  156571. vf->pcm_offset+=total;
  156572. break;
  156573. }else
  156574. result=ogg_stream_packetout(&vf->os,NULL);
  156575. }
  156576. }
  156577. }
  156578. /* verify result */
  156579. if(vf->pcm_offset>pos || pos>ov_pcm_total(vf,-1)){
  156580. result=OV_EFAULT;
  156581. goto seek_error;
  156582. }
  156583. vf->bittrack=0.f;
  156584. vf->samptrack=0.f;
  156585. return(0);
  156586. seek_error:
  156587. /* dump machine so we're in a known state */
  156588. vf->pcm_offset=-1;
  156589. _decode_clear(vf);
  156590. return (int)result;
  156591. }
  156592. /* seek to a sample offset relative to the decompressed pcm stream
  156593. returns zero on success, nonzero on failure */
  156594. int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos){
  156595. int thisblock,lastblock=0;
  156596. int ret=ov_pcm_seek_page(vf,pos);
  156597. if(ret<0)return(ret);
  156598. if((ret=_make_decode_ready(vf)))return ret;
  156599. /* discard leading packets we don't need for the lapping of the
  156600. position we want; don't decode them */
  156601. while(1){
  156602. ogg_packet op;
  156603. ogg_page og;
  156604. int ret=ogg_stream_packetpeek(&vf->os,&op);
  156605. if(ret>0){
  156606. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  156607. if(thisblock<0){
  156608. ogg_stream_packetout(&vf->os,NULL);
  156609. continue; /* non audio packet */
  156610. }
  156611. if(lastblock)vf->pcm_offset+=(lastblock+thisblock)>>2;
  156612. if(vf->pcm_offset+((thisblock+
  156613. vorbis_info_blocksize(vf->vi,1))>>2)>=pos)break;
  156614. /* remove the packet from packet queue and track its granulepos */
  156615. ogg_stream_packetout(&vf->os,NULL);
  156616. vorbis_synthesis_trackonly(&vf->vb,&op); /* set up a vb with
  156617. only tracking, no
  156618. pcm_decode */
  156619. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  156620. /* end of logical stream case is hard, especially with exact
  156621. length positioning. */
  156622. if(op.granulepos>-1){
  156623. int i;
  156624. /* always believe the stream markers */
  156625. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  156626. if(vf->pcm_offset<0)vf->pcm_offset=0;
  156627. for(i=0;i<vf->current_link;i++)
  156628. vf->pcm_offset+=vf->pcmlengths[i*2+1];
  156629. }
  156630. lastblock=thisblock;
  156631. }else{
  156632. if(ret<0 && ret!=OV_HOLE)break;
  156633. /* suck in a new page */
  156634. if(_get_next_page(vf,&og,-1)<0)break;
  156635. if(vf->current_serialno!=ogg_page_serialno(&og))_decode_clear(vf);
  156636. if(vf->ready_state<STREAMSET){
  156637. int link;
  156638. vf->current_serialno=ogg_page_serialno(&og);
  156639. for(link=0;link<vf->links;link++)
  156640. if(vf->serialnos[link]==vf->current_serialno)break;
  156641. if(link==vf->links)return(OV_EBADLINK);
  156642. vf->current_link=link;
  156643. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156644. vf->ready_state=STREAMSET;
  156645. ret=_make_decode_ready(vf);
  156646. if(ret)return ret;
  156647. lastblock=0;
  156648. }
  156649. ogg_stream_pagein(&vf->os,&og);
  156650. }
  156651. }
  156652. vf->bittrack=0.f;
  156653. vf->samptrack=0.f;
  156654. /* discard samples until we reach the desired position. Crossing a
  156655. logical bitstream boundary with abandon is OK. */
  156656. while(vf->pcm_offset<pos){
  156657. ogg_int64_t target=pos-vf->pcm_offset;
  156658. long samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  156659. if(samples>target)samples=target;
  156660. vorbis_synthesis_read(&vf->vd,samples);
  156661. vf->pcm_offset+=samples;
  156662. if(samples<target)
  156663. if(_fetch_and_process_packet(vf,NULL,1,1)<=0)
  156664. vf->pcm_offset=ov_pcm_total(vf,-1); /* eof */
  156665. }
  156666. return 0;
  156667. }
  156668. /* seek to a playback time relative to the decompressed pcm stream
  156669. returns zero on success, nonzero on failure */
  156670. int ov_time_seek(OggVorbis_File *vf,double seconds){
  156671. /* translate time to PCM position and call ov_pcm_seek */
  156672. int link=-1;
  156673. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  156674. double time_total=ov_time_total(vf,-1);
  156675. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156676. if(!vf->seekable)return(OV_ENOSEEK);
  156677. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  156678. /* which bitstream section does this time offset occur in? */
  156679. for(link=vf->links-1;link>=0;link--){
  156680. pcm_total-=vf->pcmlengths[link*2+1];
  156681. time_total-=ov_time_total(vf,link);
  156682. if(seconds>=time_total)break;
  156683. }
  156684. /* enough information to convert time offset to pcm offset */
  156685. {
  156686. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  156687. return(ov_pcm_seek(vf,target));
  156688. }
  156689. }
  156690. /* page-granularity version of ov_time_seek
  156691. returns zero on success, nonzero on failure */
  156692. int ov_time_seek_page(OggVorbis_File *vf,double seconds){
  156693. /* translate time to PCM position and call ov_pcm_seek */
  156694. int link=-1;
  156695. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  156696. double time_total=ov_time_total(vf,-1);
  156697. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156698. if(!vf->seekable)return(OV_ENOSEEK);
  156699. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  156700. /* which bitstream section does this time offset occur in? */
  156701. for(link=vf->links-1;link>=0;link--){
  156702. pcm_total-=vf->pcmlengths[link*2+1];
  156703. time_total-=ov_time_total(vf,link);
  156704. if(seconds>=time_total)break;
  156705. }
  156706. /* enough information to convert time offset to pcm offset */
  156707. {
  156708. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  156709. return(ov_pcm_seek_page(vf,target));
  156710. }
  156711. }
  156712. /* tell the current stream offset cursor. Note that seek followed by
  156713. tell will likely not give the set offset due to caching */
  156714. ogg_int64_t ov_raw_tell(OggVorbis_File *vf){
  156715. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156716. return(vf->offset);
  156717. }
  156718. /* return PCM offset (sample) of next PCM sample to be read */
  156719. ogg_int64_t ov_pcm_tell(OggVorbis_File *vf){
  156720. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156721. return(vf->pcm_offset);
  156722. }
  156723. /* return time offset (seconds) of next PCM sample to be read */
  156724. double ov_time_tell(OggVorbis_File *vf){
  156725. int link=0;
  156726. ogg_int64_t pcm_total=0;
  156727. double time_total=0.f;
  156728. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156729. if(vf->seekable){
  156730. pcm_total=ov_pcm_total(vf,-1);
  156731. time_total=ov_time_total(vf,-1);
  156732. /* which bitstream section does this time offset occur in? */
  156733. for(link=vf->links-1;link>=0;link--){
  156734. pcm_total-=vf->pcmlengths[link*2+1];
  156735. time_total-=ov_time_total(vf,link);
  156736. if(vf->pcm_offset>=pcm_total)break;
  156737. }
  156738. }
  156739. return((double)time_total+(double)(vf->pcm_offset-pcm_total)/vf->vi[link].rate);
  156740. }
  156741. /* link: -1) return the vorbis_info struct for the bitstream section
  156742. currently being decoded
  156743. 0-n) to request information for a specific bitstream section
  156744. In the case of a non-seekable bitstream, any call returns the
  156745. current bitstream. NULL in the case that the machine is not
  156746. initialized */
  156747. vorbis_info *ov_info(OggVorbis_File *vf,int link){
  156748. if(vf->seekable){
  156749. if(link<0)
  156750. if(vf->ready_state>=STREAMSET)
  156751. return vf->vi+vf->current_link;
  156752. else
  156753. return vf->vi;
  156754. else
  156755. if(link>=vf->links)
  156756. return NULL;
  156757. else
  156758. return vf->vi+link;
  156759. }else{
  156760. return vf->vi;
  156761. }
  156762. }
  156763. /* grr, strong typing, grr, no templates/inheritence, grr */
  156764. vorbis_comment *ov_comment(OggVorbis_File *vf,int link){
  156765. if(vf->seekable){
  156766. if(link<0)
  156767. if(vf->ready_state>=STREAMSET)
  156768. return vf->vc+vf->current_link;
  156769. else
  156770. return vf->vc;
  156771. else
  156772. if(link>=vf->links)
  156773. return NULL;
  156774. else
  156775. return vf->vc+link;
  156776. }else{
  156777. return vf->vc;
  156778. }
  156779. }
  156780. static int host_is_big_endian() {
  156781. ogg_int32_t pattern = 0xfeedface; /* deadbeef */
  156782. unsigned char *bytewise = (unsigned char *)&pattern;
  156783. if (bytewise[0] == 0xfe) return 1;
  156784. return 0;
  156785. }
  156786. /* up to this point, everything could more or less hide the multiple
  156787. logical bitstream nature of chaining from the toplevel application
  156788. if the toplevel application didn't particularly care. However, at
  156789. the point that we actually read audio back, the multiple-section
  156790. nature must surface: Multiple bitstream sections do not necessarily
  156791. have to have the same number of channels or sampling rate.
  156792. ov_read returns the sequential logical bitstream number currently
  156793. being decoded along with the PCM data in order that the toplevel
  156794. application can take action on channel/sample rate changes. This
  156795. number will be incremented even for streamed (non-seekable) streams
  156796. (for seekable streams, it represents the actual logical bitstream
  156797. index within the physical bitstream. Note that the accessor
  156798. functions above are aware of this dichotomy).
  156799. input values: buffer) a buffer to hold packed PCM data for return
  156800. length) the byte length requested to be placed into buffer
  156801. bigendianp) should the data be packed LSB first (0) or
  156802. MSB first (1)
  156803. word) word size for output. currently 1 (byte) or
  156804. 2 (16 bit short)
  156805. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  156806. 0) EOF
  156807. n) number of bytes of PCM actually returned. The
  156808. below works on a packet-by-packet basis, so the
  156809. return length is not related to the 'length' passed
  156810. in, just guaranteed to fit.
  156811. *section) set to the logical bitstream number */
  156812. long ov_read(OggVorbis_File *vf,char *buffer,int length,
  156813. int bigendianp,int word,int sgned,int *bitstream){
  156814. int i,j;
  156815. int host_endian = host_is_big_endian();
  156816. float **pcm;
  156817. long samples;
  156818. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156819. while(1){
  156820. if(vf->ready_state==INITSET){
  156821. samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  156822. if(samples)break;
  156823. }
  156824. /* suck in another packet */
  156825. {
  156826. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  156827. if(ret==OV_EOF)
  156828. return(0);
  156829. if(ret<=0)
  156830. return(ret);
  156831. }
  156832. }
  156833. if(samples>0){
  156834. /* yay! proceed to pack data into the byte buffer */
  156835. long channels=ov_info(vf,-1)->channels;
  156836. long bytespersample=word * channels;
  156837. vorbis_fpu_control fpu;
  156838. (void) fpu; // (to avoid a warning about it being unused)
  156839. if(samples>length/bytespersample)samples=length/bytespersample;
  156840. if(samples <= 0)
  156841. return OV_EINVAL;
  156842. /* a tight loop to pack each size */
  156843. {
  156844. int val;
  156845. if(word==1){
  156846. int off=(sgned?0:128);
  156847. vorbis_fpu_setround(&fpu);
  156848. for(j=0;j<samples;j++)
  156849. for(i=0;i<channels;i++){
  156850. val=vorbis_ftoi(pcm[i][j]*128.f);
  156851. if(val>127)val=127;
  156852. else if(val<-128)val=-128;
  156853. *buffer++=val+off;
  156854. }
  156855. vorbis_fpu_restore(fpu);
  156856. }else{
  156857. int off=(sgned?0:32768);
  156858. if(host_endian==bigendianp){
  156859. if(sgned){
  156860. vorbis_fpu_setround(&fpu);
  156861. for(i=0;i<channels;i++) { /* It's faster in this order */
  156862. float *src=pcm[i];
  156863. short *dest=((short *)buffer)+i;
  156864. for(j=0;j<samples;j++) {
  156865. val=vorbis_ftoi(src[j]*32768.f);
  156866. if(val>32767)val=32767;
  156867. else if(val<-32768)val=-32768;
  156868. *dest=val;
  156869. dest+=channels;
  156870. }
  156871. }
  156872. vorbis_fpu_restore(fpu);
  156873. }else{
  156874. vorbis_fpu_setround(&fpu);
  156875. for(i=0;i<channels;i++) {
  156876. float *src=pcm[i];
  156877. short *dest=((short *)buffer)+i;
  156878. for(j=0;j<samples;j++) {
  156879. val=vorbis_ftoi(src[j]*32768.f);
  156880. if(val>32767)val=32767;
  156881. else if(val<-32768)val=-32768;
  156882. *dest=val+off;
  156883. dest+=channels;
  156884. }
  156885. }
  156886. vorbis_fpu_restore(fpu);
  156887. }
  156888. }else if(bigendianp){
  156889. vorbis_fpu_setround(&fpu);
  156890. for(j=0;j<samples;j++)
  156891. for(i=0;i<channels;i++){
  156892. val=vorbis_ftoi(pcm[i][j]*32768.f);
  156893. if(val>32767)val=32767;
  156894. else if(val<-32768)val=-32768;
  156895. val+=off;
  156896. *buffer++=(val>>8);
  156897. *buffer++=(val&0xff);
  156898. }
  156899. vorbis_fpu_restore(fpu);
  156900. }else{
  156901. int val;
  156902. vorbis_fpu_setround(&fpu);
  156903. for(j=0;j<samples;j++)
  156904. for(i=0;i<channels;i++){
  156905. val=vorbis_ftoi(pcm[i][j]*32768.f);
  156906. if(val>32767)val=32767;
  156907. else if(val<-32768)val=-32768;
  156908. val+=off;
  156909. *buffer++=(val&0xff);
  156910. *buffer++=(val>>8);
  156911. }
  156912. vorbis_fpu_restore(fpu);
  156913. }
  156914. }
  156915. }
  156916. vorbis_synthesis_read(&vf->vd,samples);
  156917. vf->pcm_offset+=samples;
  156918. if(bitstream)*bitstream=vf->current_link;
  156919. return(samples*bytespersample);
  156920. }else{
  156921. return(samples);
  156922. }
  156923. }
  156924. /* input values: pcm_channels) a float vector per channel of output
  156925. length) the sample length being read by the app
  156926. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  156927. 0) EOF
  156928. n) number of samples of PCM actually returned. The
  156929. below works on a packet-by-packet basis, so the
  156930. return length is not related to the 'length' passed
  156931. in, just guaranteed to fit.
  156932. *section) set to the logical bitstream number */
  156933. long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int length,
  156934. int *bitstream){
  156935. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156936. while(1){
  156937. if(vf->ready_state==INITSET){
  156938. float **pcm;
  156939. long samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  156940. if(samples){
  156941. if(pcm_channels)*pcm_channels=pcm;
  156942. if(samples>length)samples=length;
  156943. vorbis_synthesis_read(&vf->vd,samples);
  156944. vf->pcm_offset+=samples;
  156945. if(bitstream)*bitstream=vf->current_link;
  156946. return samples;
  156947. }
  156948. }
  156949. /* suck in another packet */
  156950. {
  156951. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  156952. if(ret==OV_EOF)return(0);
  156953. if(ret<=0)return(ret);
  156954. }
  156955. }
  156956. }
  156957. extern float *vorbis_window(vorbis_dsp_state *v,int W);
  156958. extern void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,
  156959. ogg_int64_t off);
  156960. static void _ov_splice(float **pcm,float **lappcm,
  156961. int n1, int n2,
  156962. int ch1, int ch2,
  156963. float *w1, float *w2){
  156964. int i,j;
  156965. float *w=w1;
  156966. int n=n1;
  156967. if(n1>n2){
  156968. n=n2;
  156969. w=w2;
  156970. }
  156971. /* splice */
  156972. for(j=0;j<ch1 && j<ch2;j++){
  156973. float *s=lappcm[j];
  156974. float *d=pcm[j];
  156975. for(i=0;i<n;i++){
  156976. float wd=w[i]*w[i];
  156977. float ws=1.-wd;
  156978. d[i]=d[i]*wd + s[i]*ws;
  156979. }
  156980. }
  156981. /* window from zero */
  156982. for(;j<ch2;j++){
  156983. float *d=pcm[j];
  156984. for(i=0;i<n;i++){
  156985. float wd=w[i]*w[i];
  156986. d[i]=d[i]*wd;
  156987. }
  156988. }
  156989. }
  156990. /* make sure vf is INITSET */
  156991. static int _ov_initset(OggVorbis_File *vf){
  156992. while(1){
  156993. if(vf->ready_state==INITSET)break;
  156994. /* suck in another packet */
  156995. {
  156996. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  156997. if(ret<0 && ret!=OV_HOLE)return(ret);
  156998. }
  156999. }
  157000. return 0;
  157001. }
  157002. /* make sure vf is INITSET and that we have a primed buffer; if
  157003. we're crosslapping at a stream section boundary, this also makes
  157004. sure we're sanity checking against the right stream information */
  157005. static int _ov_initprime(OggVorbis_File *vf){
  157006. vorbis_dsp_state *vd=&vf->vd;
  157007. while(1){
  157008. if(vf->ready_state==INITSET)
  157009. if(vorbis_synthesis_pcmout(vd,NULL))break;
  157010. /* suck in another packet */
  157011. {
  157012. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  157013. if(ret<0 && ret!=OV_HOLE)return(ret);
  157014. }
  157015. }
  157016. return 0;
  157017. }
  157018. /* grab enough data for lapping from vf; this may be in the form of
  157019. unreturned, already-decoded pcm, remaining PCM we will need to
  157020. decode, or synthetic postextrapolation from last packets. */
  157021. static void _ov_getlap(OggVorbis_File *vf,vorbis_info *vi,vorbis_dsp_state *vd,
  157022. float **lappcm,int lapsize){
  157023. int lapcount=0,i;
  157024. float **pcm;
  157025. /* try first to decode the lapping data */
  157026. while(lapcount<lapsize){
  157027. int samples=vorbis_synthesis_pcmout(vd,&pcm);
  157028. if(samples){
  157029. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  157030. for(i=0;i<vi->channels;i++)
  157031. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  157032. lapcount+=samples;
  157033. vorbis_synthesis_read(vd,samples);
  157034. }else{
  157035. /* suck in another packet */
  157036. int ret=_fetch_and_process_packet(vf,NULL,1,0); /* do *not* span */
  157037. if(ret==OV_EOF)break;
  157038. }
  157039. }
  157040. if(lapcount<lapsize){
  157041. /* failed to get lapping data from normal decode; pry it from the
  157042. postextrapolation buffering, or the second half of the MDCT
  157043. from the last packet */
  157044. int samples=vorbis_synthesis_lapout(&vf->vd,&pcm);
  157045. if(samples==0){
  157046. for(i=0;i<vi->channels;i++)
  157047. memset(lappcm[i]+lapcount,0,sizeof(**pcm)*lapsize-lapcount);
  157048. lapcount=lapsize;
  157049. }else{
  157050. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  157051. for(i=0;i<vi->channels;i++)
  157052. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  157053. lapcount+=samples;
  157054. }
  157055. }
  157056. }
  157057. /* this sets up crosslapping of a sample by using trailing data from
  157058. sample 1 and lapping it into the windowing buffer of sample 2 */
  157059. int ov_crosslap(OggVorbis_File *vf1, OggVorbis_File *vf2){
  157060. vorbis_info *vi1,*vi2;
  157061. float **lappcm;
  157062. float **pcm;
  157063. float *w1,*w2;
  157064. int n1,n2,i,ret,hs1,hs2;
  157065. if(vf1==vf2)return(0); /* degenerate case */
  157066. if(vf1->ready_state<OPENED)return(OV_EINVAL);
  157067. if(vf2->ready_state<OPENED)return(OV_EINVAL);
  157068. /* the relevant overlap buffers must be pre-checked and pre-primed
  157069. before looking at settings in the event that priming would cross
  157070. a bitstream boundary. So, do it now */
  157071. ret=_ov_initset(vf1);
  157072. if(ret)return(ret);
  157073. ret=_ov_initprime(vf2);
  157074. if(ret)return(ret);
  157075. vi1=ov_info(vf1,-1);
  157076. vi2=ov_info(vf2,-1);
  157077. hs1=ov_halfrate_p(vf1);
  157078. hs2=ov_halfrate_p(vf2);
  157079. lappcm=(float**) alloca(sizeof(*lappcm)*vi1->channels);
  157080. n1=vorbis_info_blocksize(vi1,0)>>(1+hs1);
  157081. n2=vorbis_info_blocksize(vi2,0)>>(1+hs2);
  157082. w1=vorbis_window(&vf1->vd,0);
  157083. w2=vorbis_window(&vf2->vd,0);
  157084. for(i=0;i<vi1->channels;i++)
  157085. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  157086. _ov_getlap(vf1,vi1,&vf1->vd,lappcm,n1);
  157087. /* have a lapping buffer from vf1; now to splice it into the lapping
  157088. buffer of vf2 */
  157089. /* consolidate and expose the buffer. */
  157090. vorbis_synthesis_lapout(&vf2->vd,&pcm);
  157091. _analysis_output_always("pcmL",0,pcm[0],n1*2,0,0,0);
  157092. _analysis_output_always("pcmR",0,pcm[1],n1*2,0,0,0);
  157093. /* splice */
  157094. _ov_splice(pcm,lappcm,n1,n2,vi1->channels,vi2->channels,w1,w2);
  157095. /* done */
  157096. return(0);
  157097. }
  157098. static int _ov_64_seek_lap(OggVorbis_File *vf,ogg_int64_t pos,
  157099. int (*localseek)(OggVorbis_File *,ogg_int64_t)){
  157100. vorbis_info *vi;
  157101. float **lappcm;
  157102. float **pcm;
  157103. float *w1,*w2;
  157104. int n1,n2,ch1,ch2,hs;
  157105. int i,ret;
  157106. if(vf->ready_state<OPENED)return(OV_EINVAL);
  157107. ret=_ov_initset(vf);
  157108. if(ret)return(ret);
  157109. vi=ov_info(vf,-1);
  157110. hs=ov_halfrate_p(vf);
  157111. ch1=vi->channels;
  157112. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  157113. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  157114. persistent; even if the decode state
  157115. from this link gets dumped, this
  157116. window array continues to exist */
  157117. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  157118. for(i=0;i<ch1;i++)
  157119. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  157120. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  157121. /* have lapping data; seek and prime the buffer */
  157122. ret=localseek(vf,pos);
  157123. if(ret)return ret;
  157124. ret=_ov_initprime(vf);
  157125. if(ret)return(ret);
  157126. /* Guard against cross-link changes; they're perfectly legal */
  157127. vi=ov_info(vf,-1);
  157128. ch2=vi->channels;
  157129. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  157130. w2=vorbis_window(&vf->vd,0);
  157131. /* consolidate and expose the buffer. */
  157132. vorbis_synthesis_lapout(&vf->vd,&pcm);
  157133. /* splice */
  157134. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  157135. /* done */
  157136. return(0);
  157137. }
  157138. int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  157139. return _ov_64_seek_lap(vf,pos,ov_raw_seek);
  157140. }
  157141. int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  157142. return _ov_64_seek_lap(vf,pos,ov_pcm_seek);
  157143. }
  157144. int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos){
  157145. return _ov_64_seek_lap(vf,pos,ov_pcm_seek_page);
  157146. }
  157147. static int _ov_d_seek_lap(OggVorbis_File *vf,double pos,
  157148. int (*localseek)(OggVorbis_File *,double)){
  157149. vorbis_info *vi;
  157150. float **lappcm;
  157151. float **pcm;
  157152. float *w1,*w2;
  157153. int n1,n2,ch1,ch2,hs;
  157154. int i,ret;
  157155. if(vf->ready_state<OPENED)return(OV_EINVAL);
  157156. ret=_ov_initset(vf);
  157157. if(ret)return(ret);
  157158. vi=ov_info(vf,-1);
  157159. hs=ov_halfrate_p(vf);
  157160. ch1=vi->channels;
  157161. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  157162. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  157163. persistent; even if the decode state
  157164. from this link gets dumped, this
  157165. window array continues to exist */
  157166. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  157167. for(i=0;i<ch1;i++)
  157168. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  157169. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  157170. /* have lapping data; seek and prime the buffer */
  157171. ret=localseek(vf,pos);
  157172. if(ret)return ret;
  157173. ret=_ov_initprime(vf);
  157174. if(ret)return(ret);
  157175. /* Guard against cross-link changes; they're perfectly legal */
  157176. vi=ov_info(vf,-1);
  157177. ch2=vi->channels;
  157178. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  157179. w2=vorbis_window(&vf->vd,0);
  157180. /* consolidate and expose the buffer. */
  157181. vorbis_synthesis_lapout(&vf->vd,&pcm);
  157182. /* splice */
  157183. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  157184. /* done */
  157185. return(0);
  157186. }
  157187. int ov_time_seek_lap(OggVorbis_File *vf,double pos){
  157188. return _ov_d_seek_lap(vf,pos,ov_time_seek);
  157189. }
  157190. int ov_time_seek_page_lap(OggVorbis_File *vf,double pos){
  157191. return _ov_d_seek_lap(vf,pos,ov_time_seek_page);
  157192. }
  157193. #endif
  157194. /*** End of inlined file: vorbisfile.c ***/
  157195. /*** Start of inlined file: window.c ***/
  157196. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  157197. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  157198. // tasks..
  157199. #if JUCE_MSVC
  157200. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  157201. #endif
  157202. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  157203. #if JUCE_USE_OGGVORBIS
  157204. #include <stdlib.h>
  157205. #include <math.h>
  157206. static float vwin64[32] = {
  157207. 0.0009460463F, 0.0085006468F, 0.0235352254F, 0.0458950567F,
  157208. 0.0753351908F, 0.1115073077F, 0.1539457973F, 0.2020557475F,
  157209. 0.2551056759F, 0.3122276645F, 0.3724270287F, 0.4346027792F,
  157210. 0.4975789974F, 0.5601459521F, 0.6211085051F, 0.6793382689F,
  157211. 0.7338252629F, 0.7837245849F, 0.8283939355F, 0.8674186656F,
  157212. 0.9006222429F, 0.9280614787F, 0.9500073081F, 0.9669131782F,
  157213. 0.9793740220F, 0.9880792941F, 0.9937636139F, 0.9971582668F,
  157214. 0.9989462667F, 0.9997230082F, 0.9999638688F, 0.9999995525F,
  157215. };
  157216. static float vwin128[64] = {
  157217. 0.0002365472F, 0.0021280687F, 0.0059065254F, 0.0115626550F,
  157218. 0.0190823442F, 0.0284463735F, 0.0396300935F, 0.0526030430F,
  157219. 0.0673285281F, 0.0837631763F, 0.1018564887F, 0.1215504095F,
  157220. 0.1427789367F, 0.1654677960F, 0.1895342001F, 0.2148867160F,
  157221. 0.2414252576F, 0.2690412240F, 0.2976177952F, 0.3270303960F,
  157222. 0.3571473350F, 0.3878306189F, 0.4189369387F, 0.4503188188F,
  157223. 0.4818259135F, 0.5133064334F, 0.5446086751F, 0.5755826278F,
  157224. 0.6060816248F, 0.6359640047F, 0.6650947483F, 0.6933470543F,
  157225. 0.7206038179F, 0.7467589810F, 0.7717187213F, 0.7954024542F,
  157226. 0.8177436264F, 0.8386902831F, 0.8582053981F, 0.8762669622F,
  157227. 0.8928678298F, 0.9080153310F, 0.9217306608F, 0.9340480615F,
  157228. 0.9450138200F, 0.9546851041F, 0.9631286621F, 0.9704194171F,
  157229. 0.9766389810F, 0.9818741197F, 0.9862151938F, 0.9897546035F,
  157230. 0.9925852598F, 0.9947991032F, 0.9964856900F, 0.9977308602F,
  157231. 0.9986155015F, 0.9992144193F, 0.9995953200F, 0.9998179155F,
  157232. 0.9999331503F, 0.9999825563F, 0.9999977357F, 0.9999999720F,
  157233. };
  157234. static float vwin256[128] = {
  157235. 0.0000591390F, 0.0005321979F, 0.0014780301F, 0.0028960636F,
  157236. 0.0047854363F, 0.0071449926F, 0.0099732775F, 0.0132685298F,
  157237. 0.0170286741F, 0.0212513119F, 0.0259337111F, 0.0310727950F,
  157238. 0.0366651302F, 0.0427069140F, 0.0491939614F, 0.0561216907F,
  157239. 0.0634851102F, 0.0712788035F, 0.0794969160F, 0.0881331402F,
  157240. 0.0971807028F, 0.1066323515F, 0.1164803426F, 0.1267164297F,
  157241. 0.1373318534F, 0.1483173323F, 0.1596630553F, 0.1713586755F,
  157242. 0.1833933062F, 0.1957555184F, 0.2084333404F, 0.2214142599F,
  157243. 0.2346852280F, 0.2482326664F, 0.2620424757F, 0.2761000481F,
  157244. 0.2903902813F, 0.3048975959F, 0.3196059553F, 0.3344988887F,
  157245. 0.3495595160F, 0.3647705766F, 0.3801144597F, 0.3955732382F,
  157246. 0.4111287047F, 0.4267624093F, 0.4424557009F, 0.4581897696F,
  157247. 0.4739456913F, 0.4897044744F, 0.5054471075F, 0.5211546088F,
  157248. 0.5368080763F, 0.5523887395F, 0.5678780103F, 0.5832575361F,
  157249. 0.5985092508F, 0.6136154277F, 0.6285587300F, 0.6433222619F,
  157250. 0.6578896175F, 0.6722449294F, 0.6863729144F, 0.7002589187F,
  157251. 0.7138889597F, 0.7272497662F, 0.7403288154F, 0.7531143679F,
  157252. 0.7655954985F, 0.7777621249F, 0.7896050322F, 0.8011158947F,
  157253. 0.8122872932F, 0.8231127294F, 0.8335866365F, 0.8437043850F,
  157254. 0.8534622861F, 0.8628575905F, 0.8718884835F, 0.8805540765F,
  157255. 0.8888543947F, 0.8967903616F, 0.9043637797F, 0.9115773078F,
  157256. 0.9184344360F, 0.9249394562F, 0.9310974312F, 0.9369141608F,
  157257. 0.9423961446F, 0.9475505439F, 0.9523851406F, 0.9569082947F,
  157258. 0.9611289005F, 0.9650563408F, 0.9687004405F, 0.9720714191F,
  157259. 0.9751798427F, 0.9780365753F, 0.9806527301F, 0.9830396204F,
  157260. 0.9852087111F, 0.9871715701F, 0.9889398207F, 0.9905250941F,
  157261. 0.9919389832F, 0.9931929973F, 0.9942985174F, 0.9952667537F,
  157262. 0.9961087037F, 0.9968351119F, 0.9974564312F, 0.9979827858F,
  157263. 0.9984239359F, 0.9987892441F, 0.9990876435F, 0.9993276081F,
  157264. 0.9995171241F, 0.9996636648F, 0.9997741654F, 0.9998550016F,
  157265. 0.9999119692F, 0.9999502656F, 0.9999744742F, 0.9999885497F,
  157266. 0.9999958064F, 0.9999989077F, 0.9999998584F, 0.9999999983F,
  157267. };
  157268. static float vwin512[256] = {
  157269. 0.0000147849F, 0.0001330607F, 0.0003695946F, 0.0007243509F,
  157270. 0.0011972759F, 0.0017882983F, 0.0024973285F, 0.0033242588F,
  157271. 0.0042689632F, 0.0053312973F, 0.0065110982F, 0.0078081841F,
  157272. 0.0092223540F, 0.0107533880F, 0.0124010466F, 0.0141650703F,
  157273. 0.0160451800F, 0.0180410758F, 0.0201524373F, 0.0223789233F,
  157274. 0.0247201710F, 0.0271757958F, 0.0297453914F, 0.0324285286F,
  157275. 0.0352247556F, 0.0381335972F, 0.0411545545F, 0.0442871045F,
  157276. 0.0475306997F, 0.0508847676F, 0.0543487103F, 0.0579219038F,
  157277. 0.0616036982F, 0.0653934164F, 0.0692903546F, 0.0732937809F,
  157278. 0.0774029356F, 0.0816170305F, 0.0859352485F, 0.0903567428F,
  157279. 0.0948806375F, 0.0995060259F, 0.1042319712F, 0.1090575056F,
  157280. 0.1139816300F, 0.1190033137F, 0.1241214941F, 0.1293350764F,
  157281. 0.1346429333F, 0.1400439046F, 0.1455367974F, 0.1511203852F,
  157282. 0.1567934083F, 0.1625545735F, 0.1684025537F, 0.1743359881F,
  157283. 0.1803534820F, 0.1864536069F, 0.1926349000F, 0.1988958650F,
  157284. 0.2052349715F, 0.2116506555F, 0.2181413191F, 0.2247053313F,
  157285. 0.2313410275F, 0.2380467105F, 0.2448206500F, 0.2516610835F,
  157286. 0.2585662164F, 0.2655342226F, 0.2725632448F, 0.2796513950F,
  157287. 0.2867967551F, 0.2939973773F, 0.3012512852F, 0.3085564739F,
  157288. 0.3159109111F, 0.3233125375F, 0.3307592680F, 0.3382489922F,
  157289. 0.3457795756F, 0.3533488602F, 0.3609546657F, 0.3685947904F,
  157290. 0.3762670121F, 0.3839690896F, 0.3916987634F, 0.3994537572F,
  157291. 0.4072317788F, 0.4150305215F, 0.4228476653F, 0.4306808783F,
  157292. 0.4385278181F, 0.4463861329F, 0.4542534630F, 0.4621274424F,
  157293. 0.4700057001F, 0.4778858615F, 0.4857655502F, 0.4936423891F,
  157294. 0.5015140023F, 0.5093780165F, 0.5172320626F, 0.5250737772F,
  157295. 0.5329008043F, 0.5407107971F, 0.5485014192F, 0.5562703465F,
  157296. 0.5640152688F, 0.5717338914F, 0.5794239366F, 0.5870831457F,
  157297. 0.5947092801F, 0.6023001235F, 0.6098534829F, 0.6173671907F,
  157298. 0.6248391059F, 0.6322671161F, 0.6396491384F, 0.6469831217F,
  157299. 0.6542670475F, 0.6614989319F, 0.6686768267F, 0.6757988210F,
  157300. 0.6828630426F, 0.6898676592F, 0.6968108799F, 0.7036909564F,
  157301. 0.7105061843F, 0.7172549043F, 0.7239355032F, 0.7305464154F,
  157302. 0.7370861235F, 0.7435531598F, 0.7499461068F, 0.7562635986F,
  157303. 0.7625043214F, 0.7686670148F, 0.7747504721F, 0.7807535410F,
  157304. 0.7866751247F, 0.7925141825F, 0.7982697296F, 0.8039408387F,
  157305. 0.8095266395F, 0.8150263196F, 0.8204391248F, 0.8257643590F,
  157306. 0.8310013848F, 0.8361496236F, 0.8412085555F, 0.8461777194F,
  157307. 0.8510567129F, 0.8558451924F, 0.8605428730F, 0.8651495278F,
  157308. 0.8696649882F, 0.8740891432F, 0.8784219392F, 0.8826633797F,
  157309. 0.8868135244F, 0.8908724888F, 0.8948404441F, 0.8987176157F,
  157310. 0.9025042831F, 0.9062007791F, 0.9098074886F, 0.9133248482F,
  157311. 0.9167533451F, 0.9200935163F, 0.9233459472F, 0.9265112712F,
  157312. 0.9295901680F, 0.9325833632F, 0.9354916263F, 0.9383157705F,
  157313. 0.9410566504F, 0.9437151618F, 0.9462922398F, 0.9487888576F,
  157314. 0.9512060252F, 0.9535447882F, 0.9558062262F, 0.9579914516F,
  157315. 0.9601016078F, 0.9621378683F, 0.9641014348F, 0.9659935361F,
  157316. 0.9678154261F, 0.9695683830F, 0.9712537071F, 0.9728727198F,
  157317. 0.9744267618F, 0.9759171916F, 0.9773453842F, 0.9787127293F,
  157318. 0.9800206298F, 0.9812705006F, 0.9824637665F, 0.9836018613F,
  157319. 0.9846862258F, 0.9857183066F, 0.9866995544F, 0.9876314227F,
  157320. 0.9885153662F, 0.9893528393F, 0.9901452948F, 0.9908941823F,
  157321. 0.9916009470F, 0.9922670279F, 0.9928938570F, 0.9934828574F,
  157322. 0.9940354423F, 0.9945530133F, 0.9950369595F, 0.9954886562F,
  157323. 0.9959094633F, 0.9963007242F, 0.9966637649F, 0.9969998925F,
  157324. 0.9973103939F, 0.9975965351F, 0.9978595598F, 0.9981006885F,
  157325. 0.9983211172F, 0.9985220166F, 0.9987045311F, 0.9988697776F,
  157326. 0.9990188449F, 0.9991527924F, 0.9992726499F, 0.9993794157F,
  157327. 0.9994740570F, 0.9995575079F, 0.9996306699F, 0.9996944099F,
  157328. 0.9997495605F, 0.9997969190F, 0.9998372465F, 0.9998712678F,
  157329. 0.9998996704F, 0.9999231041F, 0.9999421807F, 0.9999574732F,
  157330. 0.9999695157F, 0.9999788026F, 0.9999857885F, 0.9999908879F,
  157331. 0.9999944746F, 0.9999968817F, 0.9999984010F, 0.9999992833F,
  157332. 0.9999997377F, 0.9999999317F, 0.9999999911F, 0.9999999999F,
  157333. };
  157334. static float vwin1024[512] = {
  157335. 0.0000036962F, 0.0000332659F, 0.0000924041F, 0.0001811086F,
  157336. 0.0002993761F, 0.0004472021F, 0.0006245811F, 0.0008315063F,
  157337. 0.0010679699F, 0.0013339631F, 0.0016294757F, 0.0019544965F,
  157338. 0.0023090133F, 0.0026930125F, 0.0031064797F, 0.0035493989F,
  157339. 0.0040217533F, 0.0045235250F, 0.0050546946F, 0.0056152418F,
  157340. 0.0062051451F, 0.0068243817F, 0.0074729278F, 0.0081507582F,
  157341. 0.0088578466F, 0.0095941655F, 0.0103596863F, 0.0111543789F,
  157342. 0.0119782122F, 0.0128311538F, 0.0137131701F, 0.0146242260F,
  157343. 0.0155642855F, 0.0165333111F, 0.0175312640F, 0.0185581042F,
  157344. 0.0196137903F, 0.0206982797F, 0.0218115284F, 0.0229534910F,
  157345. 0.0241241208F, 0.0253233698F, 0.0265511886F, 0.0278075263F,
  157346. 0.0290923308F, 0.0304055484F, 0.0317471241F, 0.0331170013F,
  157347. 0.0345151222F, 0.0359414274F, 0.0373958560F, 0.0388783456F,
  157348. 0.0403888325F, 0.0419272511F, 0.0434935347F, 0.0450876148F,
  157349. 0.0467094213F, 0.0483588828F, 0.0500359261F, 0.0517404765F,
  157350. 0.0534724575F, 0.0552317913F, 0.0570183983F, 0.0588321971F,
  157351. 0.0606731048F, 0.0625410369F, 0.0644359070F, 0.0663576272F,
  157352. 0.0683061077F, 0.0702812571F, 0.0722829821F, 0.0743111878F,
  157353. 0.0763657775F, 0.0784466526F, 0.0805537129F, 0.0826868561F,
  157354. 0.0848459782F, 0.0870309736F, 0.0892417345F, 0.0914781514F,
  157355. 0.0937401128F, 0.0960275056F, 0.0983402145F, 0.1006781223F,
  157356. 0.1030411101F, 0.1054290568F, 0.1078418397F, 0.1102793336F,
  157357. 0.1127414119F, 0.1152279457F, 0.1177388042F, 0.1202738544F,
  157358. 0.1228329618F, 0.1254159892F, 0.1280227980F, 0.1306532471F,
  157359. 0.1333071937F, 0.1359844927F, 0.1386849970F, 0.1414085575F,
  157360. 0.1441550230F, 0.1469242403F, 0.1497160539F, 0.1525303063F,
  157361. 0.1553668381F, 0.1582254875F, 0.1611060909F, 0.1640084822F,
  157362. 0.1669324936F, 0.1698779549F, 0.1728446939F, 0.1758325362F,
  157363. 0.1788413055F, 0.1818708232F, 0.1849209084F, 0.1879913785F,
  157364. 0.1910820485F, 0.1941927312F, 0.1973232376F, 0.2004733764F,
  157365. 0.2036429541F, 0.2068317752F, 0.2100396421F, 0.2132663552F,
  157366. 0.2165117125F, 0.2197755102F, 0.2230575422F, 0.2263576007F,
  157367. 0.2296754753F, 0.2330109540F, 0.2363638225F, 0.2397338646F,
  157368. 0.2431208619F, 0.2465245941F, 0.2499448389F, 0.2533813719F,
  157369. 0.2568339669F, 0.2603023956F, 0.2637864277F, 0.2672858312F,
  157370. 0.2708003718F, 0.2743298135F, 0.2778739186F, 0.2814324472F,
  157371. 0.2850051576F, 0.2885918065F, 0.2921921485F, 0.2958059366F,
  157372. 0.2994329219F, 0.3030728538F, 0.3067254799F, 0.3103905462F,
  157373. 0.3140677969F, 0.3177569747F, 0.3214578205F, 0.3251700736F,
  157374. 0.3288934718F, 0.3326277513F, 0.3363726468F, 0.3401278914F,
  157375. 0.3438932168F, 0.3476683533F, 0.3514530297F, 0.3552469734F,
  157376. 0.3590499106F, 0.3628615659F, 0.3666816630F, 0.3705099239F,
  157377. 0.3743460698F, 0.3781898204F, 0.3820408945F, 0.3858990095F,
  157378. 0.3897638820F, 0.3936352274F, 0.3975127601F, 0.4013961936F,
  157379. 0.4052852405F, 0.4091796123F, 0.4130790198F, 0.4169831732F,
  157380. 0.4208917815F, 0.4248045534F, 0.4287211965F, 0.4326414181F,
  157381. 0.4365649248F, 0.4404914225F, 0.4444206167F, 0.4483522125F,
  157382. 0.4522859146F, 0.4562214270F, 0.4601584538F, 0.4640966984F,
  157383. 0.4680358644F, 0.4719756548F, 0.4759157726F, 0.4798559209F,
  157384. 0.4837958024F, 0.4877351199F, 0.4916735765F, 0.4956108751F,
  157385. 0.4995467188F, 0.5034808109F, 0.5074128550F, 0.5113425550F,
  157386. 0.5152696149F, 0.5191937395F, 0.5231146336F, 0.5270320028F,
  157387. 0.5309455530F, 0.5348549910F, 0.5387600239F, 0.5426603597F,
  157388. 0.5465557070F, 0.5504457754F, 0.5543302752F, 0.5582089175F,
  157389. 0.5620814145F, 0.5659474793F, 0.5698068262F, 0.5736591704F,
  157390. 0.5775042283F, 0.5813417176F, 0.5851713571F, 0.5889928670F,
  157391. 0.5928059689F, 0.5966103856F, 0.6004058415F, 0.6041920626F,
  157392. 0.6079687761F, 0.6117357113F, 0.6154925986F, 0.6192391705F,
  157393. 0.6229751612F, 0.6267003064F, 0.6304143441F, 0.6341170137F,
  157394. 0.6378080569F, 0.6414872173F, 0.6451542405F, 0.6488088741F,
  157395. 0.6524508681F, 0.6560799742F, 0.6596959469F, 0.6632985424F,
  157396. 0.6668875197F, 0.6704626398F, 0.6740236662F, 0.6775703649F,
  157397. 0.6811025043F, 0.6846198554F, 0.6881221916F, 0.6916092892F,
  157398. 0.6950809269F, 0.6985368861F, 0.7019769510F, 0.7054009085F,
  157399. 0.7088085484F, 0.7121996632F, 0.7155740484F, 0.7189315023F,
  157400. 0.7222718263F, 0.7255948245F, 0.7289003043F, 0.7321880760F,
  157401. 0.7354579530F, 0.7387097518F, 0.7419432921F, 0.7451583966F,
  157402. 0.7483548915F, 0.7515326059F, 0.7546913723F, 0.7578310265F,
  157403. 0.7609514077F, 0.7640523581F, 0.7671337237F, 0.7701953535F,
  157404. 0.7732371001F, 0.7762588195F, 0.7792603711F, 0.7822416178F,
  157405. 0.7852024259F, 0.7881426654F, 0.7910622097F, 0.7939609356F,
  157406. 0.7968387237F, 0.7996954579F, 0.8025310261F, 0.8053453193F,
  157407. 0.8081382324F, 0.8109096638F, 0.8136595156F, 0.8163876936F,
  157408. 0.8190941071F, 0.8217786690F, 0.8244412960F, 0.8270819086F,
  157409. 0.8297004305F, 0.8322967896F, 0.8348709171F, 0.8374227481F,
  157410. 0.8399522213F, 0.8424592789F, 0.8449438672F, 0.8474059356F,
  157411. 0.8498454378F, 0.8522623306F, 0.8546565748F, 0.8570281348F,
  157412. 0.8593769787F, 0.8617030779F, 0.8640064080F, 0.8662869477F,
  157413. 0.8685446796F, 0.8707795899F, 0.8729916682F, 0.8751809079F,
  157414. 0.8773473059F, 0.8794908626F, 0.8816115819F, 0.8837094713F,
  157415. 0.8857845418F, 0.8878368079F, 0.8898662874F, 0.8918730019F,
  157416. 0.8938569760F, 0.8958182380F, 0.8977568194F, 0.8996727552F,
  157417. 0.9015660837F, 0.9034368465F, 0.9052850885F, 0.9071108577F,
  157418. 0.9089142057F, 0.9106951869F, 0.9124538591F, 0.9141902832F,
  157419. 0.9159045233F, 0.9175966464F, 0.9192667228F, 0.9209148257F,
  157420. 0.9225410313F, 0.9241454187F, 0.9257280701F, 0.9272890704F,
  157421. 0.9288285075F, 0.9303464720F, 0.9318430576F, 0.9333183603F,
  157422. 0.9347724792F, 0.9362055158F, 0.9376175745F, 0.9390087622F,
  157423. 0.9403791881F, 0.9417289644F, 0.9430582055F, 0.9443670283F,
  157424. 0.9456555521F, 0.9469238986F, 0.9481721917F, 0.9494005577F,
  157425. 0.9506091252F, 0.9517980248F, 0.9529673894F, 0.9541173540F,
  157426. 0.9552480557F, 0.9563596334F, 0.9574522282F, 0.9585259830F,
  157427. 0.9595810428F, 0.9606175542F, 0.9616356656F, 0.9626355274F,
  157428. 0.9636172915F, 0.9645811114F, 0.9655271425F, 0.9664555414F,
  157429. 0.9673664664F, 0.9682600774F, 0.9691365355F, 0.9699960034F,
  157430. 0.9708386448F, 0.9716646250F, 0.9724741103F, 0.9732672685F,
  157431. 0.9740442683F, 0.9748052795F, 0.9755504729F, 0.9762800205F,
  157432. 0.9769940950F, 0.9776928703F, 0.9783765210F, 0.9790452223F,
  157433. 0.9796991504F, 0.9803384823F, 0.9809633954F, 0.9815740679F,
  157434. 0.9821706784F, 0.9827534063F, 0.9833224312F, 0.9838779332F,
  157435. 0.9844200928F, 0.9849490910F, 0.9854651087F, 0.9859683274F,
  157436. 0.9864589286F, 0.9869370940F, 0.9874030054F, 0.9878568447F,
  157437. 0.9882987937F, 0.9887290343F, 0.9891477481F, 0.9895551169F,
  157438. 0.9899513220F, 0.9903365446F, 0.9907109658F, 0.9910747662F,
  157439. 0.9914281260F, 0.9917712252F, 0.9921042433F, 0.9924273593F,
  157440. 0.9927407516F, 0.9930445982F, 0.9933390763F, 0.9936243626F,
  157441. 0.9939006331F, 0.9941680631F, 0.9944268269F, 0.9946770982F,
  157442. 0.9949190498F, 0.9951528537F, 0.9953786808F, 0.9955967011F,
  157443. 0.9958070836F, 0.9960099963F, 0.9962056061F, 0.9963940787F,
  157444. 0.9965755786F, 0.9967502693F, 0.9969183129F, 0.9970798704F,
  157445. 0.9972351013F, 0.9973841640F, 0.9975272151F, 0.9976644103F,
  157446. 0.9977959036F, 0.9979218476F, 0.9980423932F, 0.9981576901F,
  157447. 0.9982678862F, 0.9983731278F, 0.9984735596F, 0.9985693247F,
  157448. 0.9986605645F, 0.9987474186F, 0.9988300248F, 0.9989085193F,
  157449. 0.9989830364F, 0.9990537085F, 0.9991206662F, 0.9991840382F,
  157450. 0.9992439513F, 0.9993005303F, 0.9993538982F, 0.9994041757F,
  157451. 0.9994514817F, 0.9994959330F, 0.9995376444F, 0.9995767286F,
  157452. 0.9996132960F, 0.9996474550F, 0.9996793121F, 0.9997089710F,
  157453. 0.9997365339F, 0.9997621003F, 0.9997857677F, 0.9998076311F,
  157454. 0.9998277836F, 0.9998463156F, 0.9998633155F, 0.9998788692F,
  157455. 0.9998930603F, 0.9999059701F, 0.9999176774F, 0.9999282586F,
  157456. 0.9999377880F, 0.9999463370F, 0.9999539749F, 0.9999607685F,
  157457. 0.9999667820F, 0.9999720773F, 0.9999767136F, 0.9999807479F,
  157458. 0.9999842344F, 0.9999872249F, 0.9999897688F, 0.9999919127F,
  157459. 0.9999937009F, 0.9999951749F, 0.9999963738F, 0.9999973342F,
  157460. 0.9999980900F, 0.9999986724F, 0.9999991103F, 0.9999994297F,
  157461. 0.9999996543F, 0.9999998049F, 0.9999999000F, 0.9999999552F,
  157462. 0.9999999836F, 0.9999999957F, 0.9999999994F, 1.0000000000F,
  157463. };
  157464. static float vwin2048[1024] = {
  157465. 0.0000009241F, 0.0000083165F, 0.0000231014F, 0.0000452785F,
  157466. 0.0000748476F, 0.0001118085F, 0.0001561608F, 0.0002079041F,
  157467. 0.0002670379F, 0.0003335617F, 0.0004074748F, 0.0004887765F,
  157468. 0.0005774661F, 0.0006735427F, 0.0007770054F, 0.0008878533F,
  157469. 0.0010060853F, 0.0011317002F, 0.0012646969F, 0.0014050742F,
  157470. 0.0015528307F, 0.0017079650F, 0.0018704756F, 0.0020403610F,
  157471. 0.0022176196F, 0.0024022497F, 0.0025942495F, 0.0027936173F,
  157472. 0.0030003511F, 0.0032144490F, 0.0034359088F, 0.0036647286F,
  157473. 0.0039009061F, 0.0041444391F, 0.0043953253F, 0.0046535621F,
  157474. 0.0049191472F, 0.0051920781F, 0.0054723520F, 0.0057599664F,
  157475. 0.0060549184F, 0.0063572052F, 0.0066668239F, 0.0069837715F,
  157476. 0.0073080449F, 0.0076396410F, 0.0079785566F, 0.0083247884F,
  157477. 0.0086783330F, 0.0090391871F, 0.0094073470F, 0.0097828092F,
  157478. 0.0101655700F, 0.0105556258F, 0.0109529726F, 0.0113576065F,
  157479. 0.0117695237F, 0.0121887200F, 0.0126151913F, 0.0130489335F,
  157480. 0.0134899422F, 0.0139382130F, 0.0143937415F, 0.0148565233F,
  157481. 0.0153265536F, 0.0158038279F, 0.0162883413F, 0.0167800889F,
  157482. 0.0172790660F, 0.0177852675F, 0.0182986882F, 0.0188193231F,
  157483. 0.0193471668F, 0.0198822141F, 0.0204244594F, 0.0209738974F,
  157484. 0.0215305225F, 0.0220943289F, 0.0226653109F, 0.0232434627F,
  157485. 0.0238287784F, 0.0244212519F, 0.0250208772F, 0.0256276481F,
  157486. 0.0262415582F, 0.0268626014F, 0.0274907711F, 0.0281260608F,
  157487. 0.0287684638F, 0.0294179736F, 0.0300745833F, 0.0307382859F,
  157488. 0.0314090747F, 0.0320869424F, 0.0327718819F, 0.0334638860F,
  157489. 0.0341629474F, 0.0348690586F, 0.0355822122F, 0.0363024004F,
  157490. 0.0370296157F, 0.0377638502F, 0.0385050960F, 0.0392533451F,
  157491. 0.0400085896F, 0.0407708211F, 0.0415400315F, 0.0423162123F,
  157492. 0.0430993552F, 0.0438894515F, 0.0446864926F, 0.0454904698F,
  157493. 0.0463013742F, 0.0471191969F, 0.0479439288F, 0.0487755607F,
  157494. 0.0496140836F, 0.0504594879F, 0.0513117642F, 0.0521709031F,
  157495. 0.0530368949F, 0.0539097297F, 0.0547893979F, 0.0556758894F,
  157496. 0.0565691941F, 0.0574693019F, 0.0583762026F, 0.0592898858F,
  157497. 0.0602103410F, 0.0611375576F, 0.0620715250F, 0.0630122324F,
  157498. 0.0639596688F, 0.0649138234F, 0.0658746848F, 0.0668422421F,
  157499. 0.0678164838F, 0.0687973985F, 0.0697849746F, 0.0707792005F,
  157500. 0.0717800645F, 0.0727875547F, 0.0738016591F, 0.0748223656F,
  157501. 0.0758496620F, 0.0768835359F, 0.0779239751F, 0.0789709668F,
  157502. 0.0800244985F, 0.0810845574F, 0.0821511306F, 0.0832242052F,
  157503. 0.0843037679F, 0.0853898056F, 0.0864823050F, 0.0875812525F,
  157504. 0.0886866347F, 0.0897984378F, 0.0909166480F, 0.0920412513F,
  157505. 0.0931722338F, 0.0943095813F, 0.0954532795F, 0.0966033140F,
  157506. 0.0977596702F, 0.0989223336F, 0.1000912894F, 0.1012665227F,
  157507. 0.1024480185F, 0.1036357616F, 0.1048297369F, 0.1060299290F,
  157508. 0.1072363224F, 0.1084489014F, 0.1096676504F, 0.1108925534F,
  157509. 0.1121235946F, 0.1133607577F, 0.1146040267F, 0.1158533850F,
  157510. 0.1171088163F, 0.1183703040F, 0.1196378312F, 0.1209113812F,
  157511. 0.1221909370F, 0.1234764815F, 0.1247679974F, 0.1260654674F,
  157512. 0.1273688740F, 0.1286781995F, 0.1299934263F, 0.1313145365F,
  157513. 0.1326415121F, 0.1339743349F, 0.1353129866F, 0.1366574490F,
  157514. 0.1380077035F, 0.1393637315F, 0.1407255141F, 0.1420930325F,
  157515. 0.1434662677F, 0.1448452004F, 0.1462298115F, 0.1476200814F,
  157516. 0.1490159906F, 0.1504175195F, 0.1518246482F, 0.1532373569F,
  157517. 0.1546556253F, 0.1560794333F, 0.1575087606F, 0.1589435866F,
  157518. 0.1603838909F, 0.1618296526F, 0.1632808509F, 0.1647374648F,
  157519. 0.1661994731F, 0.1676668546F, 0.1691395880F, 0.1706176516F,
  157520. 0.1721010238F, 0.1735896829F, 0.1750836068F, 0.1765827736F,
  157521. 0.1780871610F, 0.1795967468F, 0.1811115084F, 0.1826314234F,
  157522. 0.1841564689F, 0.1856866221F, 0.1872218600F, 0.1887621595F,
  157523. 0.1903074974F, 0.1918578503F, 0.1934131947F, 0.1949735068F,
  157524. 0.1965387630F, 0.1981089393F, 0.1996840117F, 0.2012639560F,
  157525. 0.2028487479F, 0.2044383630F, 0.2060327766F, 0.2076319642F,
  157526. 0.2092359007F, 0.2108445614F, 0.2124579211F, 0.2140759545F,
  157527. 0.2156986364F, 0.2173259411F, 0.2189578432F, 0.2205943168F,
  157528. 0.2222353361F, 0.2238808751F, 0.2255309076F, 0.2271854073F,
  157529. 0.2288443480F, 0.2305077030F, 0.2321754457F, 0.2338475493F,
  157530. 0.2355239869F, 0.2372047315F, 0.2388897560F, 0.2405790329F,
  157531. 0.2422725350F, 0.2439702347F, 0.2456721043F, 0.2473781159F,
  157532. 0.2490882418F, 0.2508024539F, 0.2525207240F, 0.2542430237F,
  157533. 0.2559693248F, 0.2576995986F, 0.2594338166F, 0.2611719498F,
  157534. 0.2629139695F, 0.2646598466F, 0.2664095520F, 0.2681630564F,
  157535. 0.2699203304F, 0.2716813445F, 0.2734460691F, 0.2752144744F,
  157536. 0.2769865307F, 0.2787622079F, 0.2805414760F, 0.2823243047F,
  157537. 0.2841106637F, 0.2859005227F, 0.2876938509F, 0.2894906179F,
  157538. 0.2912907928F, 0.2930943447F, 0.2949012426F, 0.2967114554F,
  157539. 0.2985249520F, 0.3003417009F, 0.3021616708F, 0.3039848301F,
  157540. 0.3058111471F, 0.3076405901F, 0.3094731273F, 0.3113087266F,
  157541. 0.3131473560F, 0.3149889833F, 0.3168335762F, 0.3186811024F,
  157542. 0.3205315294F, 0.3223848245F, 0.3242409552F, 0.3260998886F,
  157543. 0.3279615918F, 0.3298260319F, 0.3316931758F, 0.3335629903F,
  157544. 0.3354354423F, 0.3373104982F, 0.3391881247F, 0.3410682882F,
  157545. 0.3429509551F, 0.3448360917F, 0.3467236642F, 0.3486136387F,
  157546. 0.3505059811F, 0.3524006575F, 0.3542976336F, 0.3561968753F,
  157547. 0.3580983482F, 0.3600020179F, 0.3619078499F, 0.3638158096F,
  157548. 0.3657258625F, 0.3676379737F, 0.3695521086F, 0.3714682321F,
  157549. 0.3733863094F, 0.3753063055F, 0.3772281852F, 0.3791519134F,
  157550. 0.3810774548F, 0.3830047742F, 0.3849338362F, 0.3868646053F,
  157551. 0.3887970459F, 0.3907311227F, 0.3926667998F, 0.3946040417F,
  157552. 0.3965428125F, 0.3984830765F, 0.4004247978F, 0.4023679403F,
  157553. 0.4043124683F, 0.4062583455F, 0.4082055359F, 0.4101540034F,
  157554. 0.4121037117F, 0.4140546246F, 0.4160067058F, 0.4179599190F,
  157555. 0.4199142277F, 0.4218695956F, 0.4238259861F, 0.4257833627F,
  157556. 0.4277416888F, 0.4297009279F, 0.4316610433F, 0.4336219983F,
  157557. 0.4355837562F, 0.4375462803F, 0.4395095337F, 0.4414734797F,
  157558. 0.4434380815F, 0.4454033021F, 0.4473691046F, 0.4493354521F,
  157559. 0.4513023078F, 0.4532696345F, 0.4552373954F, 0.4572055533F,
  157560. 0.4591740713F, 0.4611429123F, 0.4631120393F, 0.4650814151F,
  157561. 0.4670510028F, 0.4690207650F, 0.4709906649F, 0.4729606651F,
  157562. 0.4749307287F, 0.4769008185F, 0.4788708972F, 0.4808409279F,
  157563. 0.4828108732F, 0.4847806962F, 0.4867503597F, 0.4887198264F,
  157564. 0.4906890593F, 0.4926580213F, 0.4946266753F, 0.4965949840F,
  157565. 0.4985629105F, 0.5005304176F, 0.5024974683F, 0.5044640255F,
  157566. 0.5064300522F, 0.5083955114F, 0.5103603659F, 0.5123245790F,
  157567. 0.5142881136F, 0.5162509328F, 0.5182129997F, 0.5201742774F,
  157568. 0.5221347290F, 0.5240943178F, 0.5260530070F, 0.5280107598F,
  157569. 0.5299675395F, 0.5319233095F, 0.5338780330F, 0.5358316736F,
  157570. 0.5377841946F, 0.5397355596F, 0.5416857320F, 0.5436346755F,
  157571. 0.5455823538F, 0.5475287304F, 0.5494737691F, 0.5514174337F,
  157572. 0.5533596881F, 0.5553004962F, 0.5572398218F, 0.5591776291F,
  157573. 0.5611138821F, 0.5630485449F, 0.5649815818F, 0.5669129570F,
  157574. 0.5688426349F, 0.5707705799F, 0.5726967564F, 0.5746211290F,
  157575. 0.5765436624F, 0.5784643212F, 0.5803830702F, 0.5822998743F,
  157576. 0.5842146984F, 0.5861275076F, 0.5880382669F, 0.5899469416F,
  157577. 0.5918534968F, 0.5937578981F, 0.5956601107F, 0.5975601004F,
  157578. 0.5994578326F, 0.6013532732F, 0.6032463880F, 0.6051371429F,
  157579. 0.6070255039F, 0.6089114372F, 0.6107949090F, 0.6126758856F,
  157580. 0.6145543334F, 0.6164302191F, 0.6183035092F, 0.6201741706F,
  157581. 0.6220421700F, 0.6239074745F, 0.6257700513F, 0.6276298674F,
  157582. 0.6294868903F, 0.6313410873F, 0.6331924262F, 0.6350408745F,
  157583. 0.6368864001F, 0.6387289710F, 0.6405685552F, 0.6424051209F,
  157584. 0.6442386364F, 0.6460690702F, 0.6478963910F, 0.6497205673F,
  157585. 0.6515415682F, 0.6533593625F, 0.6551739194F, 0.6569852082F,
  157586. 0.6587931984F, 0.6605978593F, 0.6623991609F, 0.6641970728F,
  157587. 0.6659915652F, 0.6677826081F, 0.6695701718F, 0.6713542268F,
  157588. 0.6731347437F, 0.6749116932F, 0.6766850461F, 0.6784547736F,
  157589. 0.6802208469F, 0.6819832374F, 0.6837419164F, 0.6854968559F,
  157590. 0.6872480275F, 0.6889954034F, 0.6907389556F, 0.6924786566F,
  157591. 0.6942144788F, 0.6959463950F, 0.6976743780F, 0.6993984008F,
  157592. 0.7011184365F, 0.7028344587F, 0.7045464407F, 0.7062543564F,
  157593. 0.7079581796F, 0.7096578844F, 0.7113534450F, 0.7130448359F,
  157594. 0.7147320316F, 0.7164150070F, 0.7180937371F, 0.7197681970F,
  157595. 0.7214383620F, 0.7231042077F, 0.7247657098F, 0.7264228443F,
  157596. 0.7280755871F, 0.7297239147F, 0.7313678035F, 0.7330072301F,
  157597. 0.7346421715F, 0.7362726046F, 0.7378985069F, 0.7395198556F,
  157598. 0.7411366285F, 0.7427488034F, 0.7443563584F, 0.7459592717F,
  157599. 0.7475575218F, 0.7491510873F, 0.7507399471F, 0.7523240803F,
  157600. 0.7539034661F, 0.7554780839F, 0.7570479136F, 0.7586129349F,
  157601. 0.7601731279F, 0.7617284730F, 0.7632789506F, 0.7648245416F,
  157602. 0.7663652267F, 0.7679009872F, 0.7694318044F, 0.7709576599F,
  157603. 0.7724785354F, 0.7739944130F, 0.7755052749F, 0.7770111035F,
  157604. 0.7785118815F, 0.7800075916F, 0.7814982170F, 0.7829837410F,
  157605. 0.7844641472F, 0.7859394191F, 0.7874095408F, 0.7888744965F,
  157606. 0.7903342706F, 0.7917888476F, 0.7932382124F, 0.7946823501F,
  157607. 0.7961212460F, 0.7975548855F, 0.7989832544F, 0.8004063386F,
  157608. 0.8018241244F, 0.8032365981F, 0.8046437463F, 0.8060455560F,
  157609. 0.8074420141F, 0.8088331080F, 0.8102188253F, 0.8115991536F,
  157610. 0.8129740810F, 0.8143435957F, 0.8157076861F, 0.8170663409F,
  157611. 0.8184195489F, 0.8197672994F, 0.8211095817F, 0.8224463853F,
  157612. 0.8237777001F, 0.8251035161F, 0.8264238235F, 0.8277386129F,
  157613. 0.8290478750F, 0.8303516008F, 0.8316497814F, 0.8329424083F,
  157614. 0.8342294731F, 0.8355109677F, 0.8367868841F, 0.8380572148F,
  157615. 0.8393219523F, 0.8405810893F, 0.8418346190F, 0.8430825345F,
  157616. 0.8443248294F, 0.8455614974F, 0.8467925323F, 0.8480179285F,
  157617. 0.8492376802F, 0.8504517822F, 0.8516602292F, 0.8528630164F,
  157618. 0.8540601391F, 0.8552515928F, 0.8564373733F, 0.8576174766F,
  157619. 0.8587918990F, 0.8599606368F, 0.8611236868F, 0.8622810460F,
  157620. 0.8634327113F, 0.8645786802F, 0.8657189504F, 0.8668535195F,
  157621. 0.8679823857F, 0.8691055472F, 0.8702230025F, 0.8713347503F,
  157622. 0.8724407896F, 0.8735411194F, 0.8746357394F, 0.8757246489F,
  157623. 0.8768078479F, 0.8778853364F, 0.8789571146F, 0.8800231832F,
  157624. 0.8810835427F, 0.8821381942F, 0.8831871387F, 0.8842303777F,
  157625. 0.8852679127F, 0.8862997456F, 0.8873258784F, 0.8883463132F,
  157626. 0.8893610527F, 0.8903700994F, 0.8913734562F, 0.8923711263F,
  157627. 0.8933631129F, 0.8943494196F, 0.8953300500F, 0.8963050083F,
  157628. 0.8972742985F, 0.8982379249F, 0.8991958922F, 0.9001482052F,
  157629. 0.9010948688F, 0.9020358883F, 0.9029712690F, 0.9039010165F,
  157630. 0.9048251367F, 0.9057436357F, 0.9066565195F, 0.9075637946F,
  157631. 0.9084654678F, 0.9093615456F, 0.9102520353F, 0.9111369440F,
  157632. 0.9120162792F, 0.9128900484F, 0.9137582595F, 0.9146209204F,
  157633. 0.9154780394F, 0.9163296248F, 0.9171756853F, 0.9180162296F,
  157634. 0.9188512667F, 0.9196808057F, 0.9205048559F, 0.9213234270F,
  157635. 0.9221365285F, 0.9229441704F, 0.9237463629F, 0.9245431160F,
  157636. 0.9253344404F, 0.9261203465F, 0.9269008453F, 0.9276759477F,
  157637. 0.9284456648F, 0.9292100080F, 0.9299689889F, 0.9307226190F,
  157638. 0.9314709103F, 0.9322138747F, 0.9329515245F, 0.9336838721F,
  157639. 0.9344109300F, 0.9351327108F, 0.9358492275F, 0.9365604931F,
  157640. 0.9372665208F, 0.9379673239F, 0.9386629160F, 0.9393533107F,
  157641. 0.9400385220F, 0.9407185637F, 0.9413934501F, 0.9420631954F,
  157642. 0.9427278141F, 0.9433873208F, 0.9440417304F, 0.9446910576F,
  157643. 0.9453353176F, 0.9459745255F, 0.9466086968F, 0.9472378469F,
  157644. 0.9478619915F, 0.9484811463F, 0.9490953274F, 0.9497045506F,
  157645. 0.9503088323F, 0.9509081888F, 0.9515026365F, 0.9520921921F,
  157646. 0.9526768723F, 0.9532566940F, 0.9538316742F, 0.9544018300F,
  157647. 0.9549671786F, 0.9555277375F, 0.9560835241F, 0.9566345562F,
  157648. 0.9571808513F, 0.9577224275F, 0.9582593027F, 0.9587914949F,
  157649. 0.9593190225F, 0.9598419038F, 0.9603601571F, 0.9608738012F,
  157650. 0.9613828546F, 0.9618873361F, 0.9623872646F, 0.9628826591F,
  157651. 0.9633735388F, 0.9638599227F, 0.9643418303F, 0.9648192808F,
  157652. 0.9652922939F, 0.9657608890F, 0.9662250860F, 0.9666849046F,
  157653. 0.9671403646F, 0.9675914861F, 0.9680382891F, 0.9684807937F,
  157654. 0.9689190202F, 0.9693529890F, 0.9697827203F, 0.9702082347F,
  157655. 0.9706295529F, 0.9710466953F, 0.9714596828F, 0.9718685362F,
  157656. 0.9722732762F, 0.9726739240F, 0.9730705005F, 0.9734630267F,
  157657. 0.9738515239F, 0.9742360134F, 0.9746165163F, 0.9749930540F,
  157658. 0.9753656481F, 0.9757343198F, 0.9760990909F, 0.9764599829F,
  157659. 0.9768170175F, 0.9771702164F, 0.9775196013F, 0.9778651941F,
  157660. 0.9782070167F, 0.9785450909F, 0.9788794388F, 0.9792100824F,
  157661. 0.9795370437F, 0.9798603449F, 0.9801800080F, 0.9804960554F,
  157662. 0.9808085092F, 0.9811173916F, 0.9814227251F, 0.9817245318F,
  157663. 0.9820228343F, 0.9823176549F, 0.9826090160F, 0.9828969402F,
  157664. 0.9831814498F, 0.9834625674F, 0.9837403156F, 0.9840147169F,
  157665. 0.9842857939F, 0.9845535692F, 0.9848180654F, 0.9850793052F,
  157666. 0.9853373113F, 0.9855921062F, 0.9858437127F, 0.9860921535F,
  157667. 0.9863374512F, 0.9865796287F, 0.9868187085F, 0.9870547136F,
  157668. 0.9872876664F, 0.9875175899F, 0.9877445067F, 0.9879684396F,
  157669. 0.9881894112F, 0.9884074444F, 0.9886225619F, 0.9888347863F,
  157670. 0.9890441404F, 0.9892506468F, 0.9894543284F, 0.9896552077F,
  157671. 0.9898533074F, 0.9900486502F, 0.9902412587F, 0.9904311555F,
  157672. 0.9906183633F, 0.9908029045F, 0.9909848019F, 0.9911640779F,
  157673. 0.9913407550F, 0.9915148557F, 0.9916864025F, 0.9918554179F,
  157674. 0.9920219241F, 0.9921859437F, 0.9923474989F, 0.9925066120F,
  157675. 0.9926633054F, 0.9928176012F, 0.9929695218F, 0.9931190891F,
  157676. 0.9932663254F, 0.9934112527F, 0.9935538932F, 0.9936942686F,
  157677. 0.9938324012F, 0.9939683126F, 0.9941020248F, 0.9942335597F,
  157678. 0.9943629388F, 0.9944901841F, 0.9946153170F, 0.9947383593F,
  157679. 0.9948593325F, 0.9949782579F, 0.9950951572F, 0.9952100516F,
  157680. 0.9953229625F, 0.9954339111F, 0.9955429186F, 0.9956500062F,
  157681. 0.9957551948F, 0.9958585056F, 0.9959599593F, 0.9960595769F,
  157682. 0.9961573792F, 0.9962533869F, 0.9963476206F, 0.9964401009F,
  157683. 0.9965308483F, 0.9966198833F, 0.9967072261F, 0.9967928971F,
  157684. 0.9968769164F, 0.9969593041F, 0.9970400804F, 0.9971192651F,
  157685. 0.9971968781F, 0.9972729391F, 0.9973474680F, 0.9974204842F,
  157686. 0.9974920074F, 0.9975620569F, 0.9976306521F, 0.9976978122F,
  157687. 0.9977635565F, 0.9978279039F, 0.9978908736F, 0.9979524842F,
  157688. 0.9980127547F, 0.9980717037F, 0.9981293499F, 0.9981857116F,
  157689. 0.9982408073F, 0.9982946554F, 0.9983472739F, 0.9983986810F,
  157690. 0.9984488947F, 0.9984979328F, 0.9985458132F, 0.9985925534F,
  157691. 0.9986381711F, 0.9986826838F, 0.9987261086F, 0.9987684630F,
  157692. 0.9988097640F, 0.9988500286F, 0.9988892738F, 0.9989275163F,
  157693. 0.9989647727F, 0.9990010597F, 0.9990363938F, 0.9990707911F,
  157694. 0.9991042679F, 0.9991368404F, 0.9991685244F, 0.9991993358F,
  157695. 0.9992292905F, 0.9992584038F, 0.9992866914F, 0.9993141686F,
  157696. 0.9993408506F, 0.9993667526F, 0.9993918895F, 0.9994162761F,
  157697. 0.9994399273F, 0.9994628576F, 0.9994850815F, 0.9995066133F,
  157698. 0.9995274672F, 0.9995476574F, 0.9995671978F, 0.9995861021F,
  157699. 0.9996043841F, 0.9996220573F, 0.9996391352F, 0.9996556310F,
  157700. 0.9996715579F, 0.9996869288F, 0.9997017568F, 0.9997160543F,
  157701. 0.9997298342F, 0.9997431088F, 0.9997558905F, 0.9997681914F,
  157702. 0.9997800236F, 0.9997913990F, 0.9998023292F, 0.9998128261F,
  157703. 0.9998229009F, 0.9998325650F, 0.9998418296F, 0.9998507058F,
  157704. 0.9998592044F, 0.9998673362F, 0.9998751117F, 0.9998825415F,
  157705. 0.9998896358F, 0.9998964047F, 0.9999028584F, 0.9999090066F,
  157706. 0.9999148590F, 0.9999204253F, 0.9999257148F, 0.9999307368F,
  157707. 0.9999355003F, 0.9999400144F, 0.9999442878F, 0.9999483293F,
  157708. 0.9999521472F, 0.9999557499F, 0.9999591457F, 0.9999623426F,
  157709. 0.9999653483F, 0.9999681708F, 0.9999708175F, 0.9999732959F,
  157710. 0.9999756132F, 0.9999777765F, 0.9999797928F, 0.9999816688F,
  157711. 0.9999834113F, 0.9999850266F, 0.9999865211F, 0.9999879009F,
  157712. 0.9999891721F, 0.9999903405F, 0.9999914118F, 0.9999923914F,
  157713. 0.9999932849F, 0.9999940972F, 0.9999948336F, 0.9999954989F,
  157714. 0.9999960978F, 0.9999966349F, 0.9999971146F, 0.9999975411F,
  157715. 0.9999979185F, 0.9999982507F, 0.9999985414F, 0.9999987944F,
  157716. 0.9999990129F, 0.9999992003F, 0.9999993596F, 0.9999994939F,
  157717. 0.9999996059F, 0.9999996981F, 0.9999997732F, 0.9999998333F,
  157718. 0.9999998805F, 0.9999999170F, 0.9999999444F, 0.9999999643F,
  157719. 0.9999999784F, 0.9999999878F, 0.9999999937F, 0.9999999972F,
  157720. 0.9999999990F, 0.9999999997F, 1.0000000000F, 1.0000000000F,
  157721. };
  157722. static float vwin4096[2048] = {
  157723. 0.0000002310F, 0.0000020791F, 0.0000057754F, 0.0000113197F,
  157724. 0.0000187121F, 0.0000279526F, 0.0000390412F, 0.0000519777F,
  157725. 0.0000667623F, 0.0000833949F, 0.0001018753F, 0.0001222036F,
  157726. 0.0001443798F, 0.0001684037F, 0.0001942754F, 0.0002219947F,
  157727. 0.0002515616F, 0.0002829761F, 0.0003162380F, 0.0003513472F,
  157728. 0.0003883038F, 0.0004271076F, 0.0004677584F, 0.0005102563F,
  157729. 0.0005546011F, 0.0006007928F, 0.0006488311F, 0.0006987160F,
  157730. 0.0007504474F, 0.0008040251F, 0.0008594490F, 0.0009167191F,
  157731. 0.0009758351F, 0.0010367969F, 0.0010996044F, 0.0011642574F,
  157732. 0.0012307558F, 0.0012990994F, 0.0013692880F, 0.0014413216F,
  157733. 0.0015151998F, 0.0015909226F, 0.0016684898F, 0.0017479011F,
  157734. 0.0018291565F, 0.0019122556F, 0.0019971983F, 0.0020839845F,
  157735. 0.0021726138F, 0.0022630861F, 0.0023554012F, 0.0024495588F,
  157736. 0.0025455588F, 0.0026434008F, 0.0027430847F, 0.0028446103F,
  157737. 0.0029479772F, 0.0030531853F, 0.0031602342F, 0.0032691238F,
  157738. 0.0033798538F, 0.0034924239F, 0.0036068338F, 0.0037230833F,
  157739. 0.0038411721F, 0.0039610999F, 0.0040828664F, 0.0042064714F,
  157740. 0.0043319145F, 0.0044591954F, 0.0045883139F, 0.0047192696F,
  157741. 0.0048520622F, 0.0049866914F, 0.0051231569F, 0.0052614583F,
  157742. 0.0054015953F, 0.0055435676F, 0.0056873748F, 0.0058330166F,
  157743. 0.0059804926F, 0.0061298026F, 0.0062809460F, 0.0064339226F,
  157744. 0.0065887320F, 0.0067453738F, 0.0069038476F, 0.0070641531F,
  157745. 0.0072262899F, 0.0073902575F, 0.0075560556F, 0.0077236838F,
  157746. 0.0078931417F, 0.0080644288F, 0.0082375447F, 0.0084124891F,
  157747. 0.0085892615F, 0.0087678614F, 0.0089482885F, 0.0091305422F,
  157748. 0.0093146223F, 0.0095005281F, 0.0096882592F, 0.0098778153F,
  157749. 0.0100691958F, 0.0102624002F, 0.0104574281F, 0.0106542791F,
  157750. 0.0108529525F, 0.0110534480F, 0.0112557651F, 0.0114599032F,
  157751. 0.0116658618F, 0.0118736405F, 0.0120832387F, 0.0122946560F,
  157752. 0.0125078917F, 0.0127229454F, 0.0129398166F, 0.0131585046F,
  157753. 0.0133790090F, 0.0136013292F, 0.0138254647F, 0.0140514149F,
  157754. 0.0142791792F, 0.0145087572F, 0.0147401481F, 0.0149733515F,
  157755. 0.0152083667F, 0.0154451932F, 0.0156838304F, 0.0159242777F,
  157756. 0.0161665345F, 0.0164106001F, 0.0166564741F, 0.0169041557F,
  157757. 0.0171536443F, 0.0174049393F, 0.0176580401F, 0.0179129461F,
  157758. 0.0181696565F, 0.0184281708F, 0.0186884883F, 0.0189506084F,
  157759. 0.0192145303F, 0.0194802535F, 0.0197477772F, 0.0200171008F,
  157760. 0.0202882236F, 0.0205611449F, 0.0208358639F, 0.0211123801F,
  157761. 0.0213906927F, 0.0216708011F, 0.0219527043F, 0.0222364019F,
  157762. 0.0225218930F, 0.0228091769F, 0.0230982529F, 0.0233891203F,
  157763. 0.0236817782F, 0.0239762259F, 0.0242724628F, 0.0245704880F,
  157764. 0.0248703007F, 0.0251719002F, 0.0254752858F, 0.0257804565F,
  157765. 0.0260874117F, 0.0263961506F, 0.0267066722F, 0.0270189760F,
  157766. 0.0273330609F, 0.0276489263F, 0.0279665712F, 0.0282859949F,
  157767. 0.0286071966F, 0.0289301753F, 0.0292549303F, 0.0295814607F,
  157768. 0.0299097656F, 0.0302398442F, 0.0305716957F, 0.0309053191F,
  157769. 0.0312407135F, 0.0315778782F, 0.0319168122F, 0.0322575145F,
  157770. 0.0325999844F, 0.0329442209F, 0.0332902231F, 0.0336379900F,
  157771. 0.0339875208F, 0.0343388146F, 0.0346918703F, 0.0350466871F,
  157772. 0.0354032640F, 0.0357616000F, 0.0361216943F, 0.0364835458F,
  157773. 0.0368471535F, 0.0372125166F, 0.0375796339F, 0.0379485046F,
  157774. 0.0383191276F, 0.0386915020F, 0.0390656267F, 0.0394415008F,
  157775. 0.0398191231F, 0.0401984927F, 0.0405796086F, 0.0409624698F,
  157776. 0.0413470751F, 0.0417334235F, 0.0421215141F, 0.0425113457F,
  157777. 0.0429029172F, 0.0432962277F, 0.0436912760F, 0.0440880610F,
  157778. 0.0444865817F, 0.0448868370F, 0.0452888257F, 0.0456925468F,
  157779. 0.0460979992F, 0.0465051816F, 0.0469140931F, 0.0473247325F,
  157780. 0.0477370986F, 0.0481511902F, 0.0485670064F, 0.0489845458F,
  157781. 0.0494038074F, 0.0498247899F, 0.0502474922F, 0.0506719131F,
  157782. 0.0510980514F, 0.0515259060F, 0.0519554756F, 0.0523867590F,
  157783. 0.0528197550F, 0.0532544624F, 0.0536908800F, 0.0541290066F,
  157784. 0.0545688408F, 0.0550103815F, 0.0554536274F, 0.0558985772F,
  157785. 0.0563452297F, 0.0567935837F, 0.0572436377F, 0.0576953907F,
  157786. 0.0581488412F, 0.0586039880F, 0.0590608297F, 0.0595193651F,
  157787. 0.0599795929F, 0.0604415117F, 0.0609051202F, 0.0613704170F,
  157788. 0.0618374009F, 0.0623060704F, 0.0627764243F, 0.0632484611F,
  157789. 0.0637221795F, 0.0641975781F, 0.0646746555F, 0.0651534104F,
  157790. 0.0656338413F, 0.0661159469F, 0.0665997257F, 0.0670851763F,
  157791. 0.0675722973F, 0.0680610873F, 0.0685515448F, 0.0690436684F,
  157792. 0.0695374567F, 0.0700329081F, 0.0705300213F, 0.0710287947F,
  157793. 0.0715292269F, 0.0720313163F, 0.0725350616F, 0.0730404612F,
  157794. 0.0735475136F, 0.0740562172F, 0.0745665707F, 0.0750785723F,
  157795. 0.0755922207F, 0.0761075143F, 0.0766244515F, 0.0771430307F,
  157796. 0.0776632505F, 0.0781851092F, 0.0787086052F, 0.0792337371F,
  157797. 0.0797605032F, 0.0802889018F, 0.0808189315F, 0.0813505905F,
  157798. 0.0818838773F, 0.0824187903F, 0.0829553277F, 0.0834934881F,
  157799. 0.0840332697F, 0.0845746708F, 0.0851176899F, 0.0856623252F,
  157800. 0.0862085751F, 0.0867564379F, 0.0873059119F, 0.0878569954F,
  157801. 0.0884096867F, 0.0889639840F, 0.0895198858F, 0.0900773902F,
  157802. 0.0906364955F, 0.0911972000F, 0.0917595019F, 0.0923233995F,
  157803. 0.0928888909F, 0.0934559745F, 0.0940246485F, 0.0945949110F,
  157804. 0.0951667604F, 0.0957401946F, 0.0963152121F, 0.0968918109F,
  157805. 0.0974699893F, 0.0980497454F, 0.0986310773F, 0.0992139832F,
  157806. 0.0997984614F, 0.1003845098F, 0.1009721267F, 0.1015613101F,
  157807. 0.1021520582F, 0.1027443692F, 0.1033382410F, 0.1039336718F,
  157808. 0.1045306597F, 0.1051292027F, 0.1057292990F, 0.1063309466F,
  157809. 0.1069341435F, 0.1075388878F, 0.1081451776F, 0.1087530108F,
  157810. 0.1093623856F, 0.1099732998F, 0.1105857516F, 0.1111997389F,
  157811. 0.1118152597F, 0.1124323121F, 0.1130508939F, 0.1136710032F,
  157812. 0.1142926379F, 0.1149157960F, 0.1155404755F, 0.1161666742F,
  157813. 0.1167943901F, 0.1174236211F, 0.1180543652F, 0.1186866202F,
  157814. 0.1193203841F, 0.1199556548F, 0.1205924300F, 0.1212307078F,
  157815. 0.1218704860F, 0.1225117624F, 0.1231545349F, 0.1237988013F,
  157816. 0.1244445596F, 0.1250918074F, 0.1257405427F, 0.1263907632F,
  157817. 0.1270424667F, 0.1276956512F, 0.1283503142F, 0.1290064537F,
  157818. 0.1296640674F, 0.1303231530F, 0.1309837084F, 0.1316457312F,
  157819. 0.1323092193F, 0.1329741703F, 0.1336405820F, 0.1343084520F,
  157820. 0.1349777782F, 0.1356485582F, 0.1363207897F, 0.1369944704F,
  157821. 0.1376695979F, 0.1383461700F, 0.1390241842F, 0.1397036384F,
  157822. 0.1403845300F, 0.1410668567F, 0.1417506162F, 0.1424358061F,
  157823. 0.1431224240F, 0.1438104674F, 0.1444999341F, 0.1451908216F,
  157824. 0.1458831274F, 0.1465768492F, 0.1472719844F, 0.1479685308F,
  157825. 0.1486664857F, 0.1493658468F, 0.1500666115F, 0.1507687775F,
  157826. 0.1514723422F, 0.1521773031F, 0.1528836577F, 0.1535914035F,
  157827. 0.1543005380F, 0.1550110587F, 0.1557229631F, 0.1564362485F,
  157828. 0.1571509124F, 0.1578669524F, 0.1585843657F, 0.1593031499F,
  157829. 0.1600233024F, 0.1607448205F, 0.1614677017F, 0.1621919433F,
  157830. 0.1629175428F, 0.1636444975F, 0.1643728047F, 0.1651024619F,
  157831. 0.1658334665F, 0.1665658156F, 0.1672995067F, 0.1680345371F,
  157832. 0.1687709041F, 0.1695086050F, 0.1702476372F, 0.1709879978F,
  157833. 0.1717296843F, 0.1724726938F, 0.1732170237F, 0.1739626711F,
  157834. 0.1747096335F, 0.1754579079F, 0.1762074916F, 0.1769583819F,
  157835. 0.1777105760F, 0.1784640710F, 0.1792188642F, 0.1799749529F,
  157836. 0.1807323340F, 0.1814910049F, 0.1822509628F, 0.1830122046F,
  157837. 0.1837747277F, 0.1845385292F, 0.1853036062F, 0.1860699558F,
  157838. 0.1868375751F, 0.1876064613F, 0.1883766114F, 0.1891480226F,
  157839. 0.1899206919F, 0.1906946164F, 0.1914697932F, 0.1922462194F,
  157840. 0.1930238919F, 0.1938028079F, 0.1945829643F, 0.1953643583F,
  157841. 0.1961469868F, 0.1969308468F, 0.1977159353F, 0.1985022494F,
  157842. 0.1992897859F, 0.2000785420F, 0.2008685145F, 0.2016597005F,
  157843. 0.2024520968F, 0.2032457005F, 0.2040405084F, 0.2048365175F,
  157844. 0.2056337247F, 0.2064321269F, 0.2072317211F, 0.2080325041F,
  157845. 0.2088344727F, 0.2096376240F, 0.2104419547F, 0.2112474618F,
  157846. 0.2120541420F, 0.2128619923F, 0.2136710094F, 0.2144811902F,
  157847. 0.2152925315F, 0.2161050301F, 0.2169186829F, 0.2177334866F,
  157848. 0.2185494381F, 0.2193665340F, 0.2201847712F, 0.2210041465F,
  157849. 0.2218246565F, 0.2226462981F, 0.2234690680F, 0.2242929629F,
  157850. 0.2251179796F, 0.2259441147F, 0.2267713650F, 0.2275997272F,
  157851. 0.2284291979F, 0.2292597739F, 0.2300914518F, 0.2309242283F,
  157852. 0.2317581001F, 0.2325930638F, 0.2334291160F, 0.2342662534F,
  157853. 0.2351044727F, 0.2359437703F, 0.2367841431F, 0.2376255875F,
  157854. 0.2384681001F, 0.2393116776F, 0.2401563165F, 0.2410020134F,
  157855. 0.2418487649F, 0.2426965675F, 0.2435454178F, 0.2443953122F,
  157856. 0.2452462474F, 0.2460982199F, 0.2469512262F, 0.2478052628F,
  157857. 0.2486603262F, 0.2495164129F, 0.2503735194F, 0.2512316421F,
  157858. 0.2520907776F, 0.2529509222F, 0.2538120726F, 0.2546742250F,
  157859. 0.2555373760F, 0.2564015219F, 0.2572666593F, 0.2581327845F,
  157860. 0.2589998939F, 0.2598679840F, 0.2607370510F, 0.2616070916F,
  157861. 0.2624781019F, 0.2633500783F, 0.2642230173F, 0.2650969152F,
  157862. 0.2659717684F, 0.2668475731F, 0.2677243257F, 0.2686020226F,
  157863. 0.2694806601F, 0.2703602344F, 0.2712407419F, 0.2721221789F,
  157864. 0.2730045417F, 0.2738878265F, 0.2747720297F, 0.2756571474F,
  157865. 0.2765431760F, 0.2774301117F, 0.2783179508F, 0.2792066895F,
  157866. 0.2800963240F, 0.2809868505F, 0.2818782654F, 0.2827705647F,
  157867. 0.2836637447F, 0.2845578016F, 0.2854527315F, 0.2863485307F,
  157868. 0.2872451953F, 0.2881427215F, 0.2890411055F, 0.2899403433F,
  157869. 0.2908404312F, 0.2917413654F, 0.2926431418F, 0.2935457567F,
  157870. 0.2944492061F, 0.2953534863F, 0.2962585932F, 0.2971645230F,
  157871. 0.2980712717F, 0.2989788356F, 0.2998872105F, 0.3007963927F,
  157872. 0.3017063781F, 0.3026171629F, 0.3035287430F, 0.3044411145F,
  157873. 0.3053542736F, 0.3062682161F, 0.3071829381F, 0.3080984356F,
  157874. 0.3090147047F, 0.3099317413F, 0.3108495414F, 0.3117681011F,
  157875. 0.3126874163F, 0.3136074830F, 0.3145282972F, 0.3154498548F,
  157876. 0.3163721517F, 0.3172951841F, 0.3182189477F, 0.3191434385F,
  157877. 0.3200686525F, 0.3209945856F, 0.3219212336F, 0.3228485927F,
  157878. 0.3237766585F, 0.3247054271F, 0.3256348943F, 0.3265650560F,
  157879. 0.3274959081F, 0.3284274465F, 0.3293596671F, 0.3302925657F,
  157880. 0.3312261382F, 0.3321603804F, 0.3330952882F, 0.3340308574F,
  157881. 0.3349670838F, 0.3359039634F, 0.3368414919F, 0.3377796651F,
  157882. 0.3387184789F, 0.3396579290F, 0.3405980113F, 0.3415387216F,
  157883. 0.3424800556F, 0.3434220091F, 0.3443645779F, 0.3453077578F,
  157884. 0.3462515446F, 0.3471959340F, 0.3481409217F, 0.3490865036F,
  157885. 0.3500326754F, 0.3509794328F, 0.3519267715F, 0.3528746873F,
  157886. 0.3538231759F, 0.3547722330F, 0.3557218544F, 0.3566720357F,
  157887. 0.3576227727F, 0.3585740610F, 0.3595258964F, 0.3604782745F,
  157888. 0.3614311910F, 0.3623846417F, 0.3633386221F, 0.3642931280F,
  157889. 0.3652481549F, 0.3662036987F, 0.3671597548F, 0.3681163191F,
  157890. 0.3690733870F, 0.3700309544F, 0.3709890167F, 0.3719475696F,
  157891. 0.3729066089F, 0.3738661299F, 0.3748261285F, 0.3757866002F,
  157892. 0.3767475406F, 0.3777089453F, 0.3786708100F, 0.3796331302F,
  157893. 0.3805959014F, 0.3815591194F, 0.3825227796F, 0.3834868777F,
  157894. 0.3844514093F, 0.3854163698F, 0.3863817549F, 0.3873475601F,
  157895. 0.3883137810F, 0.3892804131F, 0.3902474521F, 0.3912148933F,
  157896. 0.3921827325F, 0.3931509650F, 0.3941195865F, 0.3950885925F,
  157897. 0.3960579785F, 0.3970277400F, 0.3979978725F, 0.3989683716F,
  157898. 0.3999392328F, 0.4009104516F, 0.4018820234F, 0.4028539438F,
  157899. 0.4038262084F, 0.4047988125F, 0.4057717516F, 0.4067450214F,
  157900. 0.4077186172F, 0.4086925345F, 0.4096667688F, 0.4106413155F,
  157901. 0.4116161703F, 0.4125913284F, 0.4135667854F, 0.4145425368F,
  157902. 0.4155185780F, 0.4164949044F, 0.4174715116F, 0.4184483949F,
  157903. 0.4194255498F, 0.4204029718F, 0.4213806563F, 0.4223585987F,
  157904. 0.4233367946F, 0.4243152392F, 0.4252939281F, 0.4262728566F,
  157905. 0.4272520202F, 0.4282314144F, 0.4292110345F, 0.4301908760F,
  157906. 0.4311709343F, 0.4321512047F, 0.4331316828F, 0.4341123639F,
  157907. 0.4350932435F, 0.4360743168F, 0.4370555794F, 0.4380370267F,
  157908. 0.4390186540F, 0.4400004567F, 0.4409824303F, 0.4419645701F,
  157909. 0.4429468716F, 0.4439293300F, 0.4449119409F, 0.4458946996F,
  157910. 0.4468776014F, 0.4478606418F, 0.4488438162F, 0.4498271199F,
  157911. 0.4508105483F, 0.4517940967F, 0.4527777607F, 0.4537615355F,
  157912. 0.4547454165F, 0.4557293991F, 0.4567134786F, 0.4576976505F,
  157913. 0.4586819101F, 0.4596662527F, 0.4606506738F, 0.4616351687F,
  157914. 0.4626197328F, 0.4636043614F, 0.4645890499F, 0.4655737936F,
  157915. 0.4665585880F, 0.4675434284F, 0.4685283101F, 0.4695132286F,
  157916. 0.4704981791F, 0.4714831570F, 0.4724681577F, 0.4734531766F,
  157917. 0.4744382089F, 0.4754232501F, 0.4764082956F, 0.4773933406F,
  157918. 0.4783783806F, 0.4793634108F, 0.4803484267F, 0.4813334237F,
  157919. 0.4823183969F, 0.4833033419F, 0.4842882540F, 0.4852731285F,
  157920. 0.4862579608F, 0.4872427462F, 0.4882274802F, 0.4892121580F,
  157921. 0.4901967751F, 0.4911813267F, 0.4921658083F, 0.4931502151F,
  157922. 0.4941345427F, 0.4951187863F, 0.4961029412F, 0.4970870029F,
  157923. 0.4980709667F, 0.4990548280F, 0.5000385822F, 0.5010222245F,
  157924. 0.5020057505F, 0.5029891553F, 0.5039724345F, 0.5049555834F,
  157925. 0.5059385973F, 0.5069214716F, 0.5079042018F, 0.5088867831F,
  157926. 0.5098692110F, 0.5108514808F, 0.5118335879F, 0.5128155277F,
  157927. 0.5137972956F, 0.5147788869F, 0.5157602971F, 0.5167415215F,
  157928. 0.5177225555F, 0.5187033945F, 0.5196840339F, 0.5206644692F,
  157929. 0.5216446956F, 0.5226247086F, 0.5236045035F, 0.5245840759F,
  157930. 0.5255634211F, 0.5265425344F, 0.5275214114F, 0.5285000474F,
  157931. 0.5294784378F, 0.5304565781F, 0.5314344637F, 0.5324120899F,
  157932. 0.5333894522F, 0.5343665461F, 0.5353433670F, 0.5363199102F,
  157933. 0.5372961713F, 0.5382721457F, 0.5392478287F, 0.5402232159F,
  157934. 0.5411983027F, 0.5421730845F, 0.5431475569F, 0.5441217151F,
  157935. 0.5450955548F, 0.5460690714F, 0.5470422602F, 0.5480151169F,
  157936. 0.5489876368F, 0.5499598155F, 0.5509316484F, 0.5519031310F,
  157937. 0.5528742587F, 0.5538450271F, 0.5548154317F, 0.5557854680F,
  157938. 0.5567551314F, 0.5577244174F, 0.5586933216F, 0.5596618395F,
  157939. 0.5606299665F, 0.5615976983F, 0.5625650302F, 0.5635319580F,
  157940. 0.5644984770F, 0.5654645828F, 0.5664302709F, 0.5673955370F,
  157941. 0.5683603765F, 0.5693247850F, 0.5702887580F, 0.5712522912F,
  157942. 0.5722153800F, 0.5731780200F, 0.5741402069F, 0.5751019362F,
  157943. 0.5760632034F, 0.5770240042F, 0.5779843341F, 0.5789441889F,
  157944. 0.5799035639F, 0.5808624549F, 0.5818208575F, 0.5827787673F,
  157945. 0.5837361800F, 0.5846930910F, 0.5856494961F, 0.5866053910F,
  157946. 0.5875607712F, 0.5885156324F, 0.5894699703F, 0.5904237804F,
  157947. 0.5913770586F, 0.5923298004F, 0.5932820016F, 0.5942336578F,
  157948. 0.5951847646F, 0.5961353179F, 0.5970853132F, 0.5980347464F,
  157949. 0.5989836131F, 0.5999319090F, 0.6008796298F, 0.6018267713F,
  157950. 0.6027733292F, 0.6037192993F, 0.6046646773F, 0.6056094589F,
  157951. 0.6065536400F, 0.6074972162F, 0.6084401833F, 0.6093825372F,
  157952. 0.6103242736F, 0.6112653884F, 0.6122058772F, 0.6131457359F,
  157953. 0.6140849604F, 0.6150235464F, 0.6159614897F, 0.6168987862F,
  157954. 0.6178354318F, 0.6187714223F, 0.6197067535F, 0.6206414213F,
  157955. 0.6215754215F, 0.6225087501F, 0.6234414028F, 0.6243733757F,
  157956. 0.6253046646F, 0.6262352654F, 0.6271651739F, 0.6280943862F,
  157957. 0.6290228982F, 0.6299507057F, 0.6308778048F, 0.6318041913F,
  157958. 0.6327298612F, 0.6336548105F, 0.6345790352F, 0.6355025312F,
  157959. 0.6364252945F, 0.6373473211F, 0.6382686070F, 0.6391891483F,
  157960. 0.6401089409F, 0.6410279808F, 0.6419462642F, 0.6428637869F,
  157961. 0.6437805452F, 0.6446965350F, 0.6456117524F, 0.6465261935F,
  157962. 0.6474398544F, 0.6483527311F, 0.6492648197F, 0.6501761165F,
  157963. 0.6510866174F, 0.6519963186F, 0.6529052162F, 0.6538133064F,
  157964. 0.6547205854F, 0.6556270492F, 0.6565326941F, 0.6574375162F,
  157965. 0.6583415117F, 0.6592446769F, 0.6601470079F, 0.6610485009F,
  157966. 0.6619491521F, 0.6628489578F, 0.6637479143F, 0.6646460177F,
  157967. 0.6655432643F, 0.6664396505F, 0.6673351724F, 0.6682298264F,
  157968. 0.6691236087F, 0.6700165157F, 0.6709085436F, 0.6717996889F,
  157969. 0.6726899478F, 0.6735793167F, 0.6744677918F, 0.6753553697F,
  157970. 0.6762420466F, 0.6771278190F, 0.6780126832F, 0.6788966357F,
  157971. 0.6797796728F, 0.6806617909F, 0.6815429866F, 0.6824232562F,
  157972. 0.6833025961F, 0.6841810030F, 0.6850584731F, 0.6859350031F,
  157973. 0.6868105894F, 0.6876852284F, 0.6885589168F, 0.6894316510F,
  157974. 0.6903034275F, 0.6911742430F, 0.6920440939F, 0.6929129769F,
  157975. 0.6937808884F, 0.6946478251F, 0.6955137837F, 0.6963787606F,
  157976. 0.6972427525F, 0.6981057560F, 0.6989677678F, 0.6998287845F,
  157977. 0.7006888028F, 0.7015478194F, 0.7024058309F, 0.7032628340F,
  157978. 0.7041188254F, 0.7049738019F, 0.7058277601F, 0.7066806969F,
  157979. 0.7075326089F, 0.7083834929F, 0.7092333457F, 0.7100821640F,
  157980. 0.7109299447F, 0.7117766846F, 0.7126223804F, 0.7134670291F,
  157981. 0.7143106273F, 0.7151531721F, 0.7159946602F, 0.7168350885F,
  157982. 0.7176744539F, 0.7185127534F, 0.7193499837F, 0.7201861418F,
  157983. 0.7210212247F, 0.7218552293F, 0.7226881526F, 0.7235199914F,
  157984. 0.7243507428F, 0.7251804039F, 0.7260089715F, 0.7268364426F,
  157985. 0.7276628144F, 0.7284880839F, 0.7293122481F, 0.7301353040F,
  157986. 0.7309572487F, 0.7317780794F, 0.7325977930F, 0.7334163868F,
  157987. 0.7342338579F, 0.7350502033F, 0.7358654202F, 0.7366795059F,
  157988. 0.7374924573F, 0.7383042718F, 0.7391149465F, 0.7399244787F,
  157989. 0.7407328655F, 0.7415401041F, 0.7423461920F, 0.7431511261F,
  157990. 0.7439549040F, 0.7447575227F, 0.7455589797F, 0.7463592723F,
  157991. 0.7471583976F, 0.7479563532F, 0.7487531363F, 0.7495487443F,
  157992. 0.7503431745F, 0.7511364244F, 0.7519284913F, 0.7527193726F,
  157993. 0.7535090658F, 0.7542975683F, 0.7550848776F, 0.7558709910F,
  157994. 0.7566559062F, 0.7574396205F, 0.7582221314F, 0.7590034366F,
  157995. 0.7597835334F, 0.7605624194F, 0.7613400923F, 0.7621165495F,
  157996. 0.7628917886F, 0.7636658072F, 0.7644386030F, 0.7652101735F,
  157997. 0.7659805164F, 0.7667496292F, 0.7675175098F, 0.7682841556F,
  157998. 0.7690495645F, 0.7698137341F, 0.7705766622F, 0.7713383463F,
  157999. 0.7720987844F, 0.7728579741F, 0.7736159132F, 0.7743725994F,
  158000. 0.7751280306F, 0.7758822046F, 0.7766351192F, 0.7773867722F,
  158001. 0.7781371614F, 0.7788862848F, 0.7796341401F, 0.7803807253F,
  158002. 0.7811260383F, 0.7818700769F, 0.7826128392F, 0.7833543230F,
  158003. 0.7840945263F, 0.7848334471F, 0.7855710833F, 0.7863074330F,
  158004. 0.7870424941F, 0.7877762647F, 0.7885087428F, 0.7892399264F,
  158005. 0.7899698137F, 0.7906984026F, 0.7914256914F, 0.7921516780F,
  158006. 0.7928763607F, 0.7935997375F, 0.7943218065F, 0.7950425661F,
  158007. 0.7957620142F, 0.7964801492F, 0.7971969692F, 0.7979124724F,
  158008. 0.7986266570F, 0.7993395214F, 0.8000510638F, 0.8007612823F,
  158009. 0.8014701754F, 0.8021777413F, 0.8028839784F, 0.8035888849F,
  158010. 0.8042924592F, 0.8049946997F, 0.8056956048F, 0.8063951727F,
  158011. 0.8070934020F, 0.8077902910F, 0.8084858381F, 0.8091800419F,
  158012. 0.8098729007F, 0.8105644130F, 0.8112545774F, 0.8119433922F,
  158013. 0.8126308561F, 0.8133169676F, 0.8140017251F, 0.8146851272F,
  158014. 0.8153671726F, 0.8160478598F, 0.8167271874F, 0.8174051539F,
  158015. 0.8180817582F, 0.8187569986F, 0.8194308741F, 0.8201033831F,
  158016. 0.8207745244F, 0.8214442966F, 0.8221126986F, 0.8227797290F,
  158017. 0.8234453865F, 0.8241096700F, 0.8247725781F, 0.8254341097F,
  158018. 0.8260942636F, 0.8267530385F, 0.8274104334F, 0.8280664470F,
  158019. 0.8287210782F, 0.8293743259F, 0.8300261889F, 0.8306766662F,
  158020. 0.8313257566F, 0.8319734591F, 0.8326197727F, 0.8332646963F,
  158021. 0.8339082288F, 0.8345503692F, 0.8351911167F, 0.8358304700F,
  158022. 0.8364684284F, 0.8371049907F, 0.8377401562F, 0.8383739238F,
  158023. 0.8390062927F, 0.8396372618F, 0.8402668305F, 0.8408949977F,
  158024. 0.8415217626F, 0.8421471245F, 0.8427710823F, 0.8433936354F,
  158025. 0.8440147830F, 0.8446345242F, 0.8452528582F, 0.8458697844F,
  158026. 0.8464853020F, 0.8470994102F, 0.8477121084F, 0.8483233958F,
  158027. 0.8489332718F, 0.8495417356F, 0.8501487866F, 0.8507544243F,
  158028. 0.8513586479F, 0.8519614568F, 0.8525628505F, 0.8531628283F,
  158029. 0.8537613897F, 0.8543585341F, 0.8549542611F, 0.8555485699F,
  158030. 0.8561414603F, 0.8567329315F, 0.8573229832F, 0.8579116149F,
  158031. 0.8584988262F, 0.8590846165F, 0.8596689855F, 0.8602519327F,
  158032. 0.8608334577F, 0.8614135603F, 0.8619922399F, 0.8625694962F,
  158033. 0.8631453289F, 0.8637197377F, 0.8642927222F, 0.8648642821F,
  158034. 0.8654344172F, 0.8660031272F, 0.8665704118F, 0.8671362708F,
  158035. 0.8677007039F, 0.8682637109F, 0.8688252917F, 0.8693854460F,
  158036. 0.8699441737F, 0.8705014745F, 0.8710573485F, 0.8716117953F,
  158037. 0.8721648150F, 0.8727164073F, 0.8732665723F, 0.8738153098F,
  158038. 0.8743626197F, 0.8749085021F, 0.8754529569F, 0.8759959840F,
  158039. 0.8765375835F, 0.8770777553F, 0.8776164996F, 0.8781538162F,
  158040. 0.8786897054F, 0.8792241670F, 0.8797572013F, 0.8802888082F,
  158041. 0.8808189880F, 0.8813477407F, 0.8818750664F, 0.8824009653F,
  158042. 0.8829254375F, 0.8834484833F, 0.8839701028F, 0.8844902961F,
  158043. 0.8850090636F, 0.8855264054F, 0.8860423218F, 0.8865568131F,
  158044. 0.8870698794F, 0.8875815212F, 0.8880917386F, 0.8886005319F,
  158045. 0.8891079016F, 0.8896138479F, 0.8901183712F, 0.8906214719F,
  158046. 0.8911231503F, 0.8916234067F, 0.8921222417F, 0.8926196556F,
  158047. 0.8931156489F, 0.8936102219F, 0.8941033752F, 0.8945951092F,
  158048. 0.8950854244F, 0.8955743212F, 0.8960618003F, 0.8965478621F,
  158049. 0.8970325071F, 0.8975157359F, 0.8979975490F, 0.8984779471F,
  158050. 0.8989569307F, 0.8994345004F, 0.8999106568F, 0.9003854005F,
  158051. 0.9008587323F, 0.9013306526F, 0.9018011623F, 0.9022702619F,
  158052. 0.9027379521F, 0.9032042337F, 0.9036691074F, 0.9041325739F,
  158053. 0.9045946339F, 0.9050552882F, 0.9055145376F, 0.9059723828F,
  158054. 0.9064288246F, 0.9068838638F, 0.9073375013F, 0.9077897379F,
  158055. 0.9082405743F, 0.9086900115F, 0.9091380503F, 0.9095846917F,
  158056. 0.9100299364F, 0.9104737854F, 0.9109162397F, 0.9113573001F,
  158057. 0.9117969675F, 0.9122352430F, 0.9126721275F, 0.9131076219F,
  158058. 0.9135417273F, 0.9139744447F, 0.9144057750F, 0.9148357194F,
  158059. 0.9152642787F, 0.9156914542F, 0.9161172468F, 0.9165416576F,
  158060. 0.9169646877F, 0.9173863382F, 0.9178066102F, 0.9182255048F,
  158061. 0.9186430232F, 0.9190591665F, 0.9194739359F, 0.9198873324F,
  158062. 0.9202993574F, 0.9207100120F, 0.9211192973F, 0.9215272147F,
  158063. 0.9219337653F, 0.9223389504F, 0.9227427713F, 0.9231452290F,
  158064. 0.9235463251F, 0.9239460607F, 0.9243444371F, 0.9247414557F,
  158065. 0.9251371177F, 0.9255314245F, 0.9259243774F, 0.9263159778F,
  158066. 0.9267062270F, 0.9270951264F, 0.9274826774F, 0.9278688814F,
  158067. 0.9282537398F, 0.9286372540F, 0.9290194254F, 0.9294002555F,
  158068. 0.9297797458F, 0.9301578976F, 0.9305347125F, 0.9309101919F,
  158069. 0.9312843373F, 0.9316571503F, 0.9320286323F, 0.9323987849F,
  158070. 0.9327676097F, 0.9331351080F, 0.9335012816F, 0.9338661320F,
  158071. 0.9342296607F, 0.9345918694F, 0.9349527596F, 0.9353123330F,
  158072. 0.9356705911F, 0.9360275357F, 0.9363831683F, 0.9367374905F,
  158073. 0.9370905042F, 0.9374422108F, 0.9377926122F, 0.9381417099F,
  158074. 0.9384895057F, 0.9388360014F, 0.9391811985F, 0.9395250989F,
  158075. 0.9398677043F, 0.9402090165F, 0.9405490371F, 0.9408877680F,
  158076. 0.9412252110F, 0.9415613678F, 0.9418962402F, 0.9422298301F,
  158077. 0.9425621392F, 0.9428931695F, 0.9432229226F, 0.9435514005F,
  158078. 0.9438786050F, 0.9442045381F, 0.9445292014F, 0.9448525971F,
  158079. 0.9451747268F, 0.9454955926F, 0.9458151963F, 0.9461335399F,
  158080. 0.9464506253F, 0.9467664545F, 0.9470810293F, 0.9473943517F,
  158081. 0.9477064238F, 0.9480172474F, 0.9483268246F, 0.9486351573F,
  158082. 0.9489422475F, 0.9492480973F, 0.9495527087F, 0.9498560837F,
  158083. 0.9501582243F, 0.9504591325F, 0.9507588105F, 0.9510572603F,
  158084. 0.9513544839F, 0.9516504834F, 0.9519452609F, 0.9522388186F,
  158085. 0.9525311584F, 0.9528222826F, 0.9531121932F, 0.9534008923F,
  158086. 0.9536883821F, 0.9539746647F, 0.9542597424F, 0.9545436171F,
  158087. 0.9548262912F, 0.9551077667F, 0.9553880459F, 0.9556671309F,
  158088. 0.9559450239F, 0.9562217272F, 0.9564972429F, 0.9567715733F,
  158089. 0.9570447206F, 0.9573166871F, 0.9575874749F, 0.9578570863F,
  158090. 0.9581255236F, 0.9583927890F, 0.9586588849F, 0.9589238134F,
  158091. 0.9591875769F, 0.9594501777F, 0.9597116180F, 0.9599719003F,
  158092. 0.9602310267F, 0.9604889995F, 0.9607458213F, 0.9610014942F,
  158093. 0.9612560206F, 0.9615094028F, 0.9617616433F, 0.9620127443F,
  158094. 0.9622627083F, 0.9625115376F, 0.9627592345F, 0.9630058016F,
  158095. 0.9632512411F, 0.9634955555F, 0.9637387471F, 0.9639808185F,
  158096. 0.9642217720F, 0.9644616100F, 0.9647003349F, 0.9649379493F,
  158097. 0.9651744556F, 0.9654098561F, 0.9656441534F, 0.9658773499F,
  158098. 0.9661094480F, 0.9663404504F, 0.9665703593F, 0.9667991774F,
  158099. 0.9670269071F, 0.9672535509F, 0.9674791114F, 0.9677035909F,
  158100. 0.9679269921F, 0.9681493174F, 0.9683705694F, 0.9685907506F,
  158101. 0.9688098636F, 0.9690279108F, 0.9692448948F, 0.9694608182F,
  158102. 0.9696756836F, 0.9698894934F, 0.9701022503F, 0.9703139569F,
  158103. 0.9705246156F, 0.9707342291F, 0.9709428000F, 0.9711503309F,
  158104. 0.9713568243F, 0.9715622829F, 0.9717667093F, 0.9719701060F,
  158105. 0.9721724757F, 0.9723738210F, 0.9725741446F, 0.9727734490F,
  158106. 0.9729717369F, 0.9731690109F, 0.9733652737F, 0.9735605279F,
  158107. 0.9737547762F, 0.9739480212F, 0.9741402656F, 0.9743315120F,
  158108. 0.9745217631F, 0.9747110216F, 0.9748992901F, 0.9750865714F,
  158109. 0.9752728681F, 0.9754581829F, 0.9756425184F, 0.9758258775F,
  158110. 0.9760082627F, 0.9761896768F, 0.9763701224F, 0.9765496024F,
  158111. 0.9767281193F, 0.9769056760F, 0.9770822751F, 0.9772579193F,
  158112. 0.9774326114F, 0.9776063542F, 0.9777791502F, 0.9779510023F,
  158113. 0.9781219133F, 0.9782918858F, 0.9784609226F, 0.9786290264F,
  158114. 0.9787962000F, 0.9789624461F, 0.9791277676F, 0.9792921671F,
  158115. 0.9794556474F, 0.9796182113F, 0.9797798615F, 0.9799406009F,
  158116. 0.9801004321F, 0.9802593580F, 0.9804173813F, 0.9805745049F,
  158117. 0.9807307314F, 0.9808860637F, 0.9810405046F, 0.9811940568F,
  158118. 0.9813467232F, 0.9814985065F, 0.9816494095F, 0.9817994351F,
  158119. 0.9819485860F, 0.9820968650F, 0.9822442750F, 0.9823908186F,
  158120. 0.9825364988F, 0.9826813184F, 0.9828252801F, 0.9829683868F,
  158121. 0.9831106413F, 0.9832520463F, 0.9833926048F, 0.9835323195F,
  158122. 0.9836711932F, 0.9838092288F, 0.9839464291F, 0.9840827969F,
  158123. 0.9842183351F, 0.9843530464F, 0.9844869337F, 0.9846199998F,
  158124. 0.9847522475F, 0.9848836798F, 0.9850142993F, 0.9851441090F,
  158125. 0.9852731117F, 0.9854013101F, 0.9855287073F, 0.9856553058F,
  158126. 0.9857811087F, 0.9859061188F, 0.9860303388F, 0.9861537717F,
  158127. 0.9862764202F, 0.9863982872F, 0.9865193756F, 0.9866396882F,
  158128. 0.9867592277F, 0.9868779972F, 0.9869959993F, 0.9871132370F,
  158129. 0.9872297131F, 0.9873454304F, 0.9874603918F, 0.9875746001F,
  158130. 0.9876880581F, 0.9878007688F, 0.9879127348F, 0.9880239592F,
  158131. 0.9881344447F, 0.9882441941F, 0.9883532104F, 0.9884614962F,
  158132. 0.9885690546F, 0.9886758883F, 0.9887820001F, 0.9888873930F,
  158133. 0.9889920697F, 0.9890960331F, 0.9891992859F, 0.9893018312F,
  158134. 0.9894036716F, 0.9895048100F, 0.9896052493F, 0.9897049923F,
  158135. 0.9898040418F, 0.9899024006F, 0.9900000717F, 0.9900970577F,
  158136. 0.9901933616F, 0.9902889862F, 0.9903839343F, 0.9904782087F,
  158137. 0.9905718122F, 0.9906647477F, 0.9907570180F, 0.9908486259F,
  158138. 0.9909395742F, 0.9910298658F, 0.9911195034F, 0.9912084899F,
  158139. 0.9912968281F, 0.9913845208F, 0.9914715708F, 0.9915579810F,
  158140. 0.9916437540F, 0.9917288928F, 0.9918134001F, 0.9918972788F,
  158141. 0.9919805316F, 0.9920631613F, 0.9921451707F, 0.9922265626F,
  158142. 0.9923073399F, 0.9923875052F, 0.9924670615F, 0.9925460114F,
  158143. 0.9926243577F, 0.9927021033F, 0.9927792508F, 0.9928558032F,
  158144. 0.9929317631F, 0.9930071333F, 0.9930819167F, 0.9931561158F,
  158145. 0.9932297337F, 0.9933027728F, 0.9933752362F, 0.9934471264F,
  158146. 0.9935184462F, 0.9935891985F, 0.9936593859F, 0.9937290112F,
  158147. 0.9937980771F, 0.9938665864F, 0.9939345418F, 0.9940019460F,
  158148. 0.9940688018F, 0.9941351118F, 0.9942008789F, 0.9942661057F,
  158149. 0.9943307950F, 0.9943949494F, 0.9944585717F, 0.9945216645F,
  158150. 0.9945842307F, 0.9946462728F, 0.9947077936F, 0.9947687957F,
  158151. 0.9948292820F, 0.9948892550F, 0.9949487174F, 0.9950076719F,
  158152. 0.9950661212F, 0.9951240679F, 0.9951815148F, 0.9952384645F,
  158153. 0.9952949196F, 0.9953508828F, 0.9954063568F, 0.9954613442F,
  158154. 0.9955158476F, 0.9955698697F, 0.9956234132F, 0.9956764806F,
  158155. 0.9957290746F, 0.9957811978F, 0.9958328528F, 0.9958840423F,
  158156. 0.9959347688F, 0.9959850351F, 0.9960348435F, 0.9960841969F,
  158157. 0.9961330977F, 0.9961815486F, 0.9962295521F, 0.9962771108F,
  158158. 0.9963242274F, 0.9963709043F, 0.9964171441F, 0.9964629494F,
  158159. 0.9965083228F, 0.9965532668F, 0.9965977840F, 0.9966418768F,
  158160. 0.9966855479F, 0.9967287998F, 0.9967716350F, 0.9968140559F,
  158161. 0.9968560653F, 0.9968976655F, 0.9969388591F, 0.9969796485F,
  158162. 0.9970200363F, 0.9970600250F, 0.9970996170F, 0.9971388149F,
  158163. 0.9971776211F, 0.9972160380F, 0.9972540683F, 0.9972917142F,
  158164. 0.9973289783F, 0.9973658631F, 0.9974023709F, 0.9974385042F,
  158165. 0.9974742655F, 0.9975096571F, 0.9975446816F, 0.9975793413F,
  158166. 0.9976136386F, 0.9976475759F, 0.9976811557F, 0.9977143803F,
  158167. 0.9977472521F, 0.9977797736F, 0.9978119470F, 0.9978437748F,
  158168. 0.9978752593F, 0.9979064029F, 0.9979372079F, 0.9979676768F,
  158169. 0.9979978117F, 0.9980276151F, 0.9980570893F, 0.9980862367F,
  158170. 0.9981150595F, 0.9981435600F, 0.9981717406F, 0.9981996035F,
  158171. 0.9982271511F, 0.9982543856F, 0.9982813093F, 0.9983079246F,
  158172. 0.9983342336F, 0.9983602386F, 0.9983859418F, 0.9984113456F,
  158173. 0.9984364522F, 0.9984612638F, 0.9984857825F, 0.9985100108F,
  158174. 0.9985339507F, 0.9985576044F, 0.9985809743F, 0.9986040624F,
  158175. 0.9986268710F, 0.9986494022F, 0.9986716583F, 0.9986936413F,
  158176. 0.9987153535F, 0.9987367969F, 0.9987579738F, 0.9987788864F,
  158177. 0.9987995366F, 0.9988199267F, 0.9988400587F, 0.9988599348F,
  158178. 0.9988795572F, 0.9988989278F, 0.9989180487F, 0.9989369222F,
  158179. 0.9989555501F, 0.9989739347F, 0.9989920780F, 0.9990099820F,
  158180. 0.9990276487F, 0.9990450803F, 0.9990622787F, 0.9990792460F,
  158181. 0.9990959841F, 0.9991124952F, 0.9991287812F, 0.9991448440F,
  158182. 0.9991606858F, 0.9991763084F, 0.9991917139F, 0.9992069042F,
  158183. 0.9992218813F, 0.9992366471F, 0.9992512035F, 0.9992655525F,
  158184. 0.9992796961F, 0.9992936361F, 0.9993073744F, 0.9993209131F,
  158185. 0.9993342538F, 0.9993473987F, 0.9993603494F, 0.9993731080F,
  158186. 0.9993856762F, 0.9993980559F, 0.9994102490F, 0.9994222573F,
  158187. 0.9994340827F, 0.9994457269F, 0.9994571918F, 0.9994684793F,
  158188. 0.9994795910F, 0.9994905288F, 0.9995012945F, 0.9995118898F,
  158189. 0.9995223165F, 0.9995325765F, 0.9995426713F, 0.9995526029F,
  158190. 0.9995623728F, 0.9995719829F, 0.9995814349F, 0.9995907304F,
  158191. 0.9995998712F, 0.9996088590F, 0.9996176954F, 0.9996263821F,
  158192. 0.9996349208F, 0.9996433132F, 0.9996515609F, 0.9996596656F,
  158193. 0.9996676288F, 0.9996754522F, 0.9996831375F, 0.9996906862F,
  158194. 0.9996981000F, 0.9997053804F, 0.9997125290F, 0.9997195474F,
  158195. 0.9997264371F, 0.9997331998F, 0.9997398369F, 0.9997463500F,
  158196. 0.9997527406F, 0.9997590103F, 0.9997651606F, 0.9997711930F,
  158197. 0.9997771089F, 0.9997829098F, 0.9997885973F, 0.9997941728F,
  158198. 0.9997996378F, 0.9998049936F, 0.9998102419F, 0.9998153839F,
  158199. 0.9998204211F, 0.9998253550F, 0.9998301868F, 0.9998349182F,
  158200. 0.9998395503F, 0.9998440847F, 0.9998485226F, 0.9998528654F,
  158201. 0.9998571146F, 0.9998612713F, 0.9998653370F, 0.9998693130F,
  158202. 0.9998732007F, 0.9998770012F, 0.9998807159F, 0.9998843461F,
  158203. 0.9998878931F, 0.9998913581F, 0.9998947424F, 0.9998980473F,
  158204. 0.9999012740F, 0.9999044237F, 0.9999074976F, 0.9999104971F,
  158205. 0.9999134231F, 0.9999162771F, 0.9999190601F, 0.9999217733F,
  158206. 0.9999244179F, 0.9999269950F, 0.9999295058F, 0.9999319515F,
  158207. 0.9999343332F, 0.9999366519F, 0.9999389088F, 0.9999411050F,
  158208. 0.9999432416F, 0.9999453196F, 0.9999473402F, 0.9999493044F,
  158209. 0.9999512132F, 0.9999530677F, 0.9999548690F, 0.9999566180F,
  158210. 0.9999583157F, 0.9999599633F, 0.9999615616F, 0.9999631116F,
  158211. 0.9999646144F, 0.9999660709F, 0.9999674820F, 0.9999688487F,
  158212. 0.9999701719F, 0.9999714526F, 0.9999726917F, 0.9999738900F,
  158213. 0.9999750486F, 0.9999761682F, 0.9999772497F, 0.9999782941F,
  158214. 0.9999793021F, 0.9999802747F, 0.9999812126F, 0.9999821167F,
  158215. 0.9999829878F, 0.9999838268F, 0.9999846343F, 0.9999854113F,
  158216. 0.9999861584F, 0.9999868765F, 0.9999875664F, 0.9999882287F,
  158217. 0.9999888642F, 0.9999894736F, 0.9999900577F, 0.9999906172F,
  158218. 0.9999911528F, 0.9999916651F, 0.9999921548F, 0.9999926227F,
  158219. 0.9999930693F, 0.9999934954F, 0.9999939015F, 0.9999942883F,
  158220. 0.9999946564F, 0.9999950064F, 0.9999953390F, 0.9999956547F,
  158221. 0.9999959541F, 0.9999962377F, 0.9999965062F, 0.9999967601F,
  158222. 0.9999969998F, 0.9999972260F, 0.9999974392F, 0.9999976399F,
  158223. 0.9999978285F, 0.9999980056F, 0.9999981716F, 0.9999983271F,
  158224. 0.9999984724F, 0.9999986081F, 0.9999987345F, 0.9999988521F,
  158225. 0.9999989613F, 0.9999990625F, 0.9999991562F, 0.9999992426F,
  158226. 0.9999993223F, 0.9999993954F, 0.9999994625F, 0.9999995239F,
  158227. 0.9999995798F, 0.9999996307F, 0.9999996768F, 0.9999997184F,
  158228. 0.9999997559F, 0.9999997895F, 0.9999998195F, 0.9999998462F,
  158229. 0.9999998698F, 0.9999998906F, 0.9999999088F, 0.9999999246F,
  158230. 0.9999999383F, 0.9999999500F, 0.9999999600F, 0.9999999684F,
  158231. 0.9999999754F, 0.9999999811F, 0.9999999858F, 0.9999999896F,
  158232. 0.9999999925F, 0.9999999948F, 0.9999999965F, 0.9999999978F,
  158233. 0.9999999986F, 0.9999999992F, 0.9999999996F, 0.9999999998F,
  158234. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  158235. };
  158236. static float vwin8192[4096] = {
  158237. 0.0000000578F, 0.0000005198F, 0.0000014438F, 0.0000028299F,
  158238. 0.0000046780F, 0.0000069882F, 0.0000097604F, 0.0000129945F,
  158239. 0.0000166908F, 0.0000208490F, 0.0000254692F, 0.0000305515F,
  158240. 0.0000360958F, 0.0000421021F, 0.0000485704F, 0.0000555006F,
  158241. 0.0000628929F, 0.0000707472F, 0.0000790635F, 0.0000878417F,
  158242. 0.0000970820F, 0.0001067842F, 0.0001169483F, 0.0001275744F,
  158243. 0.0001386625F, 0.0001502126F, 0.0001622245F, 0.0001746984F,
  158244. 0.0001876343F, 0.0002010320F, 0.0002148917F, 0.0002292132F,
  158245. 0.0002439967F, 0.0002592421F, 0.0002749493F, 0.0002911184F,
  158246. 0.0003077493F, 0.0003248421F, 0.0003423967F, 0.0003604132F,
  158247. 0.0003788915F, 0.0003978316F, 0.0004172335F, 0.0004370971F,
  158248. 0.0004574226F, 0.0004782098F, 0.0004994587F, 0.0005211694F,
  158249. 0.0005433418F, 0.0005659759F, 0.0005890717F, 0.0006126292F,
  158250. 0.0006366484F, 0.0006611292F, 0.0006860716F, 0.0007114757F,
  158251. 0.0007373414F, 0.0007636687F, 0.0007904576F, 0.0008177080F,
  158252. 0.0008454200F, 0.0008735935F, 0.0009022285F, 0.0009313250F,
  158253. 0.0009608830F, 0.0009909025F, 0.0010213834F, 0.0010523257F,
  158254. 0.0010837295F, 0.0011155946F, 0.0011479211F, 0.0011807090F,
  158255. 0.0012139582F, 0.0012476687F, 0.0012818405F, 0.0013164736F,
  158256. 0.0013515679F, 0.0013871235F, 0.0014231402F, 0.0014596182F,
  158257. 0.0014965573F, 0.0015339576F, 0.0015718190F, 0.0016101415F,
  158258. 0.0016489251F, 0.0016881698F, 0.0017278754F, 0.0017680421F,
  158259. 0.0018086698F, 0.0018497584F, 0.0018913080F, 0.0019333185F,
  158260. 0.0019757898F, 0.0020187221F, 0.0020621151F, 0.0021059690F,
  158261. 0.0021502837F, 0.0021950591F, 0.0022402953F, 0.0022859921F,
  158262. 0.0023321497F, 0.0023787679F, 0.0024258467F, 0.0024733861F,
  158263. 0.0025213861F, 0.0025698466F, 0.0026187676F, 0.0026681491F,
  158264. 0.0027179911F, 0.0027682935F, 0.0028190562F, 0.0028702794F,
  158265. 0.0029219628F, 0.0029741066F, 0.0030267107F, 0.0030797749F,
  158266. 0.0031332994F, 0.0031872841F, 0.0032417289F, 0.0032966338F,
  158267. 0.0033519988F, 0.0034078238F, 0.0034641089F, 0.0035208539F,
  158268. 0.0035780589F, 0.0036357237F, 0.0036938485F, 0.0037524331F,
  158269. 0.0038114775F, 0.0038709817F, 0.0039309456F, 0.0039913692F,
  158270. 0.0040522524F, 0.0041135953F, 0.0041753978F, 0.0042376599F,
  158271. 0.0043003814F, 0.0043635624F, 0.0044272029F, 0.0044913028F,
  158272. 0.0045558620F, 0.0046208806F, 0.0046863585F, 0.0047522955F,
  158273. 0.0048186919F, 0.0048855473F, 0.0049528619F, 0.0050206356F,
  158274. 0.0050888684F, 0.0051575601F, 0.0052267108F, 0.0052963204F,
  158275. 0.0053663890F, 0.0054369163F, 0.0055079025F, 0.0055793474F,
  158276. 0.0056512510F, 0.0057236133F, 0.0057964342F, 0.0058697137F,
  158277. 0.0059434517F, 0.0060176482F, 0.0060923032F, 0.0061674166F,
  158278. 0.0062429883F, 0.0063190183F, 0.0063955066F, 0.0064724532F,
  158279. 0.0065498579F, 0.0066277207F, 0.0067060416F, 0.0067848205F,
  158280. 0.0068640575F, 0.0069437523F, 0.0070239051F, 0.0071045157F,
  158281. 0.0071855840F, 0.0072671102F, 0.0073490940F, 0.0074315355F,
  158282. 0.0075144345F, 0.0075977911F, 0.0076816052F, 0.0077658768F,
  158283. 0.0078506057F, 0.0079357920F, 0.0080214355F, 0.0081075363F,
  158284. 0.0081940943F, 0.0082811094F, 0.0083685816F, 0.0084565108F,
  158285. 0.0085448970F, 0.0086337401F, 0.0087230401F, 0.0088127969F,
  158286. 0.0089030104F, 0.0089936807F, 0.0090848076F, 0.0091763911F,
  158287. 0.0092684311F, 0.0093609276F, 0.0094538805F, 0.0095472898F,
  158288. 0.0096411554F, 0.0097354772F, 0.0098302552F, 0.0099254894F,
  158289. 0.0100211796F, 0.0101173259F, 0.0102139281F, 0.0103109863F,
  158290. 0.0104085002F, 0.0105064700F, 0.0106048955F, 0.0107037766F,
  158291. 0.0108031133F, 0.0109029056F, 0.0110031534F, 0.0111038565F,
  158292. 0.0112050151F, 0.0113066289F, 0.0114086980F, 0.0115112222F,
  158293. 0.0116142015F, 0.0117176359F, 0.0118215252F, 0.0119258695F,
  158294. 0.0120306686F, 0.0121359225F, 0.0122416312F, 0.0123477944F,
  158295. 0.0124544123F, 0.0125614847F, 0.0126690116F, 0.0127769928F,
  158296. 0.0128854284F, 0.0129943182F, 0.0131036623F, 0.0132134604F,
  158297. 0.0133237126F, 0.0134344188F, 0.0135455790F, 0.0136571929F,
  158298. 0.0137692607F, 0.0138817821F, 0.0139947572F, 0.0141081859F,
  158299. 0.0142220681F, 0.0143364037F, 0.0144511927F, 0.0145664350F,
  158300. 0.0146821304F, 0.0147982791F, 0.0149148808F, 0.0150319355F,
  158301. 0.0151494431F, 0.0152674036F, 0.0153858168F, 0.0155046828F,
  158302. 0.0156240014F, 0.0157437726F, 0.0158639962F, 0.0159846723F,
  158303. 0.0161058007F, 0.0162273814F, 0.0163494142F, 0.0164718991F,
  158304. 0.0165948361F, 0.0167182250F, 0.0168420658F, 0.0169663584F,
  158305. 0.0170911027F, 0.0172162987F, 0.0173419462F, 0.0174680452F,
  158306. 0.0175945956F, 0.0177215974F, 0.0178490504F, 0.0179769545F,
  158307. 0.0181053098F, 0.0182341160F, 0.0183633732F, 0.0184930812F,
  158308. 0.0186232399F, 0.0187538494F, 0.0188849094F, 0.0190164200F,
  158309. 0.0191483809F, 0.0192807923F, 0.0194136539F, 0.0195469656F,
  158310. 0.0196807275F, 0.0198149394F, 0.0199496012F, 0.0200847128F,
  158311. 0.0202202742F, 0.0203562853F, 0.0204927460F, 0.0206296561F,
  158312. 0.0207670157F, 0.0209048245F, 0.0210430826F, 0.0211817899F,
  158313. 0.0213209462F, 0.0214605515F, 0.0216006057F, 0.0217411086F,
  158314. 0.0218820603F, 0.0220234605F, 0.0221653093F, 0.0223076066F,
  158315. 0.0224503521F, 0.0225935459F, 0.0227371879F, 0.0228812779F,
  158316. 0.0230258160F, 0.0231708018F, 0.0233162355F, 0.0234621169F,
  158317. 0.0236084459F, 0.0237552224F, 0.0239024462F, 0.0240501175F,
  158318. 0.0241982359F, 0.0243468015F, 0.0244958141F, 0.0246452736F,
  158319. 0.0247951800F, 0.0249455331F, 0.0250963329F, 0.0252475792F,
  158320. 0.0253992720F, 0.0255514111F, 0.0257039965F, 0.0258570281F,
  158321. 0.0260105057F, 0.0261644293F, 0.0263187987F, 0.0264736139F,
  158322. 0.0266288747F, 0.0267845811F, 0.0269407330F, 0.0270973302F,
  158323. 0.0272543727F, 0.0274118604F, 0.0275697930F, 0.0277281707F,
  158324. 0.0278869932F, 0.0280462604F, 0.0282059723F, 0.0283661287F,
  158325. 0.0285267295F, 0.0286877747F, 0.0288492641F, 0.0290111976F,
  158326. 0.0291735751F, 0.0293363965F, 0.0294996617F, 0.0296633706F,
  158327. 0.0298275231F, 0.0299921190F, 0.0301571583F, 0.0303226409F,
  158328. 0.0304885667F, 0.0306549354F, 0.0308217472F, 0.0309890017F,
  158329. 0.0311566989F, 0.0313248388F, 0.0314934211F, 0.0316624459F,
  158330. 0.0318319128F, 0.0320018220F, 0.0321721732F, 0.0323429663F,
  158331. 0.0325142013F, 0.0326858779F, 0.0328579962F, 0.0330305559F,
  158332. 0.0332035570F, 0.0333769994F, 0.0335508829F, 0.0337252074F,
  158333. 0.0338999728F, 0.0340751790F, 0.0342508259F, 0.0344269134F,
  158334. 0.0346034412F, 0.0347804094F, 0.0349578178F, 0.0351356663F,
  158335. 0.0353139548F, 0.0354926831F, 0.0356718511F, 0.0358514588F,
  158336. 0.0360315059F, 0.0362119924F, 0.0363929182F, 0.0365742831F,
  158337. 0.0367560870F, 0.0369383297F, 0.0371210113F, 0.0373041315F,
  158338. 0.0374876902F, 0.0376716873F, 0.0378561226F, 0.0380409961F,
  158339. 0.0382263077F, 0.0384120571F, 0.0385982443F, 0.0387848691F,
  158340. 0.0389719315F, 0.0391594313F, 0.0393473683F, 0.0395357425F,
  158341. 0.0397245537F, 0.0399138017F, 0.0401034866F, 0.0402936080F,
  158342. 0.0404841660F, 0.0406751603F, 0.0408665909F, 0.0410584576F,
  158343. 0.0412507603F, 0.0414434988F, 0.0416366731F, 0.0418302829F,
  158344. 0.0420243282F, 0.0422188088F, 0.0424137246F, 0.0426090755F,
  158345. 0.0428048613F, 0.0430010819F, 0.0431977371F, 0.0433948269F,
  158346. 0.0435923511F, 0.0437903095F, 0.0439887020F, 0.0441875285F,
  158347. 0.0443867889F, 0.0445864830F, 0.0447866106F, 0.0449871717F,
  158348. 0.0451881661F, 0.0453895936F, 0.0455914542F, 0.0457937477F,
  158349. 0.0459964738F, 0.0461996326F, 0.0464032239F, 0.0466072475F,
  158350. 0.0468117032F, 0.0470165910F, 0.0472219107F, 0.0474276622F,
  158351. 0.0476338452F, 0.0478404597F, 0.0480475056F, 0.0482549827F,
  158352. 0.0484628907F, 0.0486712297F, 0.0488799994F, 0.0490891998F,
  158353. 0.0492988306F, 0.0495088917F, 0.0497193830F, 0.0499303043F,
  158354. 0.0501416554F, 0.0503534363F, 0.0505656468F, 0.0507782867F,
  158355. 0.0509913559F, 0.0512048542F, 0.0514187815F, 0.0516331376F,
  158356. 0.0518479225F, 0.0520631358F, 0.0522787775F, 0.0524948475F,
  158357. 0.0527113455F, 0.0529282715F, 0.0531456252F, 0.0533634066F,
  158358. 0.0535816154F, 0.0538002515F, 0.0540193148F, 0.0542388051F,
  158359. 0.0544587222F, 0.0546790660F, 0.0548998364F, 0.0551210331F,
  158360. 0.0553426561F, 0.0555647051F, 0.0557871801F, 0.0560100807F,
  158361. 0.0562334070F, 0.0564571587F, 0.0566813357F, 0.0569059378F,
  158362. 0.0571309649F, 0.0573564168F, 0.0575822933F, 0.0578085942F,
  158363. 0.0580353195F, 0.0582624689F, 0.0584900423F, 0.0587180396F,
  158364. 0.0589464605F, 0.0591753049F, 0.0594045726F, 0.0596342635F,
  158365. 0.0598643774F, 0.0600949141F, 0.0603258735F, 0.0605572555F,
  158366. 0.0607890597F, 0.0610212862F, 0.0612539346F, 0.0614870049F,
  158367. 0.0617204968F, 0.0619544103F, 0.0621887451F, 0.0624235010F,
  158368. 0.0626586780F, 0.0628942758F, 0.0631302942F, 0.0633667331F,
  158369. 0.0636035923F, 0.0638408717F, 0.0640785710F, 0.0643166901F,
  158370. 0.0645552288F, 0.0647941870F, 0.0650335645F, 0.0652733610F,
  158371. 0.0655135765F, 0.0657542108F, 0.0659952636F, 0.0662367348F,
  158372. 0.0664786242F, 0.0667209316F, 0.0669636570F, 0.0672068000F,
  158373. 0.0674503605F, 0.0676943384F, 0.0679387334F, 0.0681835454F,
  158374. 0.0684287742F, 0.0686744196F, 0.0689204814F, 0.0691669595F,
  158375. 0.0694138536F, 0.0696611637F, 0.0699088894F, 0.0701570307F,
  158376. 0.0704055873F, 0.0706545590F, 0.0709039458F, 0.0711537473F,
  158377. 0.0714039634F, 0.0716545939F, 0.0719056387F, 0.0721570975F,
  158378. 0.0724089702F, 0.0726612565F, 0.0729139563F, 0.0731670694F,
  158379. 0.0734205956F, 0.0736745347F, 0.0739288866F, 0.0741836510F,
  158380. 0.0744388277F, 0.0746944166F, 0.0749504175F, 0.0752068301F,
  158381. 0.0754636543F, 0.0757208899F, 0.0759785367F, 0.0762365946F,
  158382. 0.0764950632F, 0.0767539424F, 0.0770132320F, 0.0772729319F,
  158383. 0.0775330418F, 0.0777935616F, 0.0780544909F, 0.0783158298F,
  158384. 0.0785775778F, 0.0788397349F, 0.0791023009F, 0.0793652755F,
  158385. 0.0796286585F, 0.0798924498F, 0.0801566492F, 0.0804212564F,
  158386. 0.0806862712F, 0.0809516935F, 0.0812175231F, 0.0814837597F,
  158387. 0.0817504031F, 0.0820174532F, 0.0822849097F, 0.0825527724F,
  158388. 0.0828210412F, 0.0830897158F, 0.0833587960F, 0.0836282816F,
  158389. 0.0838981724F, 0.0841684682F, 0.0844391688F, 0.0847102740F,
  158390. 0.0849817835F, 0.0852536973F, 0.0855260150F, 0.0857987364F,
  158391. 0.0860718614F, 0.0863453897F, 0.0866193211F, 0.0868936554F,
  158392. 0.0871683924F, 0.0874435319F, 0.0877190737F, 0.0879950175F,
  158393. 0.0882713632F, 0.0885481105F, 0.0888252592F, 0.0891028091F,
  158394. 0.0893807600F, 0.0896591117F, 0.0899378639F, 0.0902170165F,
  158395. 0.0904965692F, 0.0907765218F, 0.0910568740F, 0.0913376258F,
  158396. 0.0916187767F, 0.0919003268F, 0.0921822756F, 0.0924646230F,
  158397. 0.0927473687F, 0.0930305126F, 0.0933140545F, 0.0935979940F,
  158398. 0.0938823310F, 0.0941670653F, 0.0944521966F, 0.0947377247F,
  158399. 0.0950236494F, 0.0953099704F, 0.0955966876F, 0.0958838007F,
  158400. 0.0961713094F, 0.0964592136F, 0.0967475131F, 0.0970362075F,
  158401. 0.0973252967F, 0.0976147805F, 0.0979046585F, 0.0981949307F,
  158402. 0.0984855967F, 0.0987766563F, 0.0990681093F, 0.0993599555F,
  158403. 0.0996521945F, 0.0999448263F, 0.1002378506F, 0.1005312671F,
  158404. 0.1008250755F, 0.1011192757F, 0.1014138675F, 0.1017088505F,
  158405. 0.1020042246F, 0.1022999895F, 0.1025961450F, 0.1028926909F,
  158406. 0.1031896268F, 0.1034869526F, 0.1037846680F, 0.1040827729F,
  158407. 0.1043812668F, 0.1046801497F, 0.1049794213F, 0.1052790813F,
  158408. 0.1055791294F, 0.1058795656F, 0.1061803894F, 0.1064816006F,
  158409. 0.1067831991F, 0.1070851846F, 0.1073875568F, 0.1076903155F,
  158410. 0.1079934604F, 0.1082969913F, 0.1086009079F, 0.1089052101F,
  158411. 0.1092098975F, 0.1095149699F, 0.1098204270F, 0.1101262687F,
  158412. 0.1104324946F, 0.1107391045F, 0.1110460982F, 0.1113534754F,
  158413. 0.1116612359F, 0.1119693793F, 0.1122779055F, 0.1125868142F,
  158414. 0.1128961052F, 0.1132057781F, 0.1135158328F, 0.1138262690F,
  158415. 0.1141370863F, 0.1144482847F, 0.1147598638F, 0.1150718233F,
  158416. 0.1153841631F, 0.1156968828F, 0.1160099822F, 0.1163234610F,
  158417. 0.1166373190F, 0.1169515559F, 0.1172661714F, 0.1175811654F,
  158418. 0.1178965374F, 0.1182122874F, 0.1185284149F, 0.1188449198F,
  158419. 0.1191618018F, 0.1194790606F, 0.1197966960F, 0.1201147076F,
  158420. 0.1204330953F, 0.1207518587F, 0.1210709976F, 0.1213905118F,
  158421. 0.1217104009F, 0.1220306647F, 0.1223513029F, 0.1226723153F,
  158422. 0.1229937016F, 0.1233154615F, 0.1236375948F, 0.1239601011F,
  158423. 0.1242829803F, 0.1246062319F, 0.1249298559F, 0.1252538518F,
  158424. 0.1255782195F, 0.1259029586F, 0.1262280689F, 0.1265535501F,
  158425. 0.1268794019F, 0.1272056241F, 0.1275322163F, 0.1278591784F,
  158426. 0.1281865099F, 0.1285142108F, 0.1288422805F, 0.1291707190F,
  158427. 0.1294995259F, 0.1298287009F, 0.1301582437F, 0.1304881542F,
  158428. 0.1308184319F, 0.1311490766F, 0.1314800881F, 0.1318114660F,
  158429. 0.1321432100F, 0.1324753200F, 0.1328077955F, 0.1331406364F,
  158430. 0.1334738422F, 0.1338074129F, 0.1341413479F, 0.1344756472F,
  158431. 0.1348103103F, 0.1351453370F, 0.1354807270F, 0.1358164801F,
  158432. 0.1361525959F, 0.1364890741F, 0.1368259145F, 0.1371631167F,
  158433. 0.1375006805F, 0.1378386056F, 0.1381768917F, 0.1385155384F,
  158434. 0.1388545456F, 0.1391939129F, 0.1395336400F, 0.1398737266F,
  158435. 0.1402141724F, 0.1405549772F, 0.1408961406F, 0.1412376623F,
  158436. 0.1415795421F, 0.1419217797F, 0.1422643746F, 0.1426073268F,
  158437. 0.1429506358F, 0.1432943013F, 0.1436383231F, 0.1439827008F,
  158438. 0.1443274342F, 0.1446725229F, 0.1450179667F, 0.1453637652F,
  158439. 0.1457099181F, 0.1460564252F, 0.1464032861F, 0.1467505006F,
  158440. 0.1470980682F, 0.1474459888F, 0.1477942620F, 0.1481428875F,
  158441. 0.1484918651F, 0.1488411942F, 0.1491908748F, 0.1495409065F,
  158442. 0.1498912889F, 0.1502420218F, 0.1505931048F, 0.1509445376F,
  158443. 0.1512963200F, 0.1516484516F, 0.1520009321F, 0.1523537612F,
  158444. 0.1527069385F, 0.1530604638F, 0.1534143368F, 0.1537685571F,
  158445. 0.1541231244F, 0.1544780384F, 0.1548332987F, 0.1551889052F,
  158446. 0.1555448574F, 0.1559011550F, 0.1562577978F, 0.1566147853F,
  158447. 0.1569721173F, 0.1573297935F, 0.1576878135F, 0.1580461771F,
  158448. 0.1584048838F, 0.1587639334F, 0.1591233255F, 0.1594830599F,
  158449. 0.1598431361F, 0.1602035540F, 0.1605643131F, 0.1609254131F,
  158450. 0.1612868537F, 0.1616486346F, 0.1620107555F, 0.1623732160F,
  158451. 0.1627360158F, 0.1630991545F, 0.1634626319F, 0.1638264476F,
  158452. 0.1641906013F, 0.1645550926F, 0.1649199212F, 0.1652850869F,
  158453. 0.1656505892F, 0.1660164278F, 0.1663826024F, 0.1667491127F,
  158454. 0.1671159583F, 0.1674831388F, 0.1678506541F, 0.1682185036F,
  158455. 0.1685866872F, 0.1689552044F, 0.1693240549F, 0.1696932384F,
  158456. 0.1700627545F, 0.1704326029F, 0.1708027833F, 0.1711732952F,
  158457. 0.1715441385F, 0.1719153127F, 0.1722868175F, 0.1726586526F,
  158458. 0.1730308176F, 0.1734033121F, 0.1737761359F, 0.1741492886F,
  158459. 0.1745227698F, 0.1748965792F, 0.1752707164F, 0.1756451812F,
  158460. 0.1760199731F, 0.1763950918F, 0.1767705370F, 0.1771463083F,
  158461. 0.1775224054F, 0.1778988279F, 0.1782755754F, 0.1786526477F,
  158462. 0.1790300444F, 0.1794077651F, 0.1797858094F, 0.1801641771F,
  158463. 0.1805428677F, 0.1809218810F, 0.1813012165F, 0.1816808739F,
  158464. 0.1820608528F, 0.1824411530F, 0.1828217739F, 0.1832027154F,
  158465. 0.1835839770F, 0.1839655584F, 0.1843474592F, 0.1847296790F,
  158466. 0.1851122175F, 0.1854950744F, 0.1858782492F, 0.1862617417F,
  158467. 0.1866455514F, 0.1870296780F, 0.1874141211F, 0.1877988804F,
  158468. 0.1881839555F, 0.1885693461F, 0.1889550517F, 0.1893410721F,
  158469. 0.1897274068F, 0.1901140555F, 0.1905010178F, 0.1908882933F,
  158470. 0.1912758818F, 0.1916637828F, 0.1920519959F, 0.1924405208F,
  158471. 0.1928293571F, 0.1932185044F, 0.1936079625F, 0.1939977308F,
  158472. 0.1943878091F, 0.1947781969F, 0.1951688939F, 0.1955598998F,
  158473. 0.1959512141F, 0.1963428364F, 0.1967347665F, 0.1971270038F,
  158474. 0.1975195482F, 0.1979123990F, 0.1983055561F, 0.1986990190F,
  158475. 0.1990927873F, 0.1994868607F, 0.1998812388F, 0.2002759212F,
  158476. 0.2006709075F, 0.2010661974F, 0.2014617904F, 0.2018576862F,
  158477. 0.2022538844F, 0.2026503847F, 0.2030471865F, 0.2034442897F,
  158478. 0.2038416937F, 0.2042393982F, 0.2046374028F, 0.2050357071F,
  158479. 0.2054343107F, 0.2058332133F, 0.2062324145F, 0.2066319138F,
  158480. 0.2070317110F, 0.2074318055F, 0.2078321970F, 0.2082328852F,
  158481. 0.2086338696F, 0.2090351498F, 0.2094367255F, 0.2098385962F,
  158482. 0.2102407617F, 0.2106432213F, 0.2110459749F, 0.2114490220F,
  158483. 0.2118523621F, 0.2122559950F, 0.2126599202F, 0.2130641373F,
  158484. 0.2134686459F, 0.2138734456F, 0.2142785361F, 0.2146839168F,
  158485. 0.2150895875F, 0.2154955478F, 0.2159017972F, 0.2163083353F,
  158486. 0.2167151617F, 0.2171222761F, 0.2175296780F, 0.2179373670F,
  158487. 0.2183453428F, 0.2187536049F, 0.2191621529F, 0.2195709864F,
  158488. 0.2199801051F, 0.2203895085F, 0.2207991961F, 0.2212091677F,
  158489. 0.2216194228F, 0.2220299610F, 0.2224407818F, 0.2228518850F,
  158490. 0.2232632699F, 0.2236749364F, 0.2240868839F, 0.2244991121F,
  158491. 0.2249116204F, 0.2253244086F, 0.2257374763F, 0.2261508229F,
  158492. 0.2265644481F, 0.2269783514F, 0.2273925326F, 0.2278069911F,
  158493. 0.2282217265F, 0.2286367384F, 0.2290520265F, 0.2294675902F,
  158494. 0.2298834292F, 0.2302995431F, 0.2307159314F, 0.2311325937F,
  158495. 0.2315495297F, 0.2319667388F, 0.2323842207F, 0.2328019749F,
  158496. 0.2332200011F, 0.2336382988F, 0.2340568675F, 0.2344757070F,
  158497. 0.2348948166F, 0.2353141961F, 0.2357338450F, 0.2361537629F,
  158498. 0.2365739493F, 0.2369944038F, 0.2374151261F, 0.2378361156F,
  158499. 0.2382573720F, 0.2386788948F, 0.2391006836F, 0.2395227380F,
  158500. 0.2399450575F, 0.2403676417F, 0.2407904902F, 0.2412136026F,
  158501. 0.2416369783F, 0.2420606171F, 0.2424845185F, 0.2429086820F,
  158502. 0.2433331072F, 0.2437577936F, 0.2441827409F, 0.2446079486F,
  158503. 0.2450334163F, 0.2454591435F, 0.2458851298F, 0.2463113747F,
  158504. 0.2467378779F, 0.2471646389F, 0.2475916573F, 0.2480189325F,
  158505. 0.2484464643F, 0.2488742521F, 0.2493022955F, 0.2497305940F,
  158506. 0.2501591473F, 0.2505879549F, 0.2510170163F, 0.2514463311F,
  158507. 0.2518758989F, 0.2523057193F, 0.2527357916F, 0.2531661157F,
  158508. 0.2535966909F, 0.2540275169F, 0.2544585931F, 0.2548899193F,
  158509. 0.2553214948F, 0.2557533193F, 0.2561853924F, 0.2566177135F,
  158510. 0.2570502822F, 0.2574830981F, 0.2579161608F, 0.2583494697F,
  158511. 0.2587830245F, 0.2592168246F, 0.2596508697F, 0.2600851593F,
  158512. 0.2605196929F, 0.2609544701F, 0.2613894904F, 0.2618247534F,
  158513. 0.2622602586F, 0.2626960055F, 0.2631319938F, 0.2635682230F,
  158514. 0.2640046925F, 0.2644414021F, 0.2648783511F, 0.2653155391F,
  158515. 0.2657529657F, 0.2661906305F, 0.2666285329F, 0.2670666725F,
  158516. 0.2675050489F, 0.2679436616F, 0.2683825101F, 0.2688215940F,
  158517. 0.2692609127F, 0.2697004660F, 0.2701402532F, 0.2705802739F,
  158518. 0.2710205278F, 0.2714610142F, 0.2719017327F, 0.2723426830F,
  158519. 0.2727838644F, 0.2732252766F, 0.2736669191F, 0.2741087914F,
  158520. 0.2745508930F, 0.2749932235F, 0.2754357824F, 0.2758785693F,
  158521. 0.2763215837F, 0.2767648251F, 0.2772082930F, 0.2776519870F,
  158522. 0.2780959066F, 0.2785400513F, 0.2789844207F, 0.2794290143F,
  158523. 0.2798738316F, 0.2803188722F, 0.2807641355F, 0.2812096211F,
  158524. 0.2816553286F, 0.2821012574F, 0.2825474071F, 0.2829937773F,
  158525. 0.2834403673F, 0.2838871768F, 0.2843342053F, 0.2847814523F,
  158526. 0.2852289174F, 0.2856765999F, 0.2861244996F, 0.2865726159F,
  158527. 0.2870209482F, 0.2874694962F, 0.2879182594F, 0.2883672372F,
  158528. 0.2888164293F, 0.2892658350F, 0.2897154540F, 0.2901652858F,
  158529. 0.2906153298F, 0.2910655856F, 0.2915160527F, 0.2919667306F,
  158530. 0.2924176189F, 0.2928687171F, 0.2933200246F, 0.2937715409F,
  158531. 0.2942232657F, 0.2946751984F, 0.2951273386F, 0.2955796856F,
  158532. 0.2960322391F, 0.2964849986F, 0.2969379636F, 0.2973911335F,
  158533. 0.2978445080F, 0.2982980864F, 0.2987518684F, 0.2992058534F,
  158534. 0.2996600409F, 0.3001144305F, 0.3005690217F, 0.3010238139F,
  158535. 0.3014788067F, 0.3019339995F, 0.3023893920F, 0.3028449835F,
  158536. 0.3033007736F, 0.3037567618F, 0.3042129477F, 0.3046693306F,
  158537. 0.3051259102F, 0.3055826859F, 0.3060396572F, 0.3064968236F,
  158538. 0.3069541847F, 0.3074117399F, 0.3078694887F, 0.3083274307F,
  158539. 0.3087855653F, 0.3092438920F, 0.3097024104F, 0.3101611199F,
  158540. 0.3106200200F, 0.3110791103F, 0.3115383902F, 0.3119978592F,
  158541. 0.3124575169F, 0.3129173627F, 0.3133773961F, 0.3138376166F,
  158542. 0.3142980238F, 0.3147586170F, 0.3152193959F, 0.3156803598F,
  158543. 0.3161415084F, 0.3166028410F, 0.3170643573F, 0.3175260566F,
  158544. 0.3179879384F, 0.3184500023F, 0.3189122478F, 0.3193746743F,
  158545. 0.3198372814F, 0.3203000685F, 0.3207630351F, 0.3212261807F,
  158546. 0.3216895048F, 0.3221530069F, 0.3226166865F, 0.3230805430F,
  158547. 0.3235445760F, 0.3240087849F, 0.3244731693F, 0.3249377285F,
  158548. 0.3254024622F, 0.3258673698F, 0.3263324507F, 0.3267977045F,
  158549. 0.3272631306F, 0.3277287286F, 0.3281944978F, 0.3286604379F,
  158550. 0.3291265482F, 0.3295928284F, 0.3300592777F, 0.3305258958F,
  158551. 0.3309926821F, 0.3314596361F, 0.3319267573F, 0.3323940451F,
  158552. 0.3328614990F, 0.3333291186F, 0.3337969033F, 0.3342648525F,
  158553. 0.3347329658F, 0.3352012427F, 0.3356696825F, 0.3361382849F,
  158554. 0.3366070492F, 0.3370759749F, 0.3375450616F, 0.3380143087F,
  158555. 0.3384837156F, 0.3389532819F, 0.3394230071F, 0.3398928905F,
  158556. 0.3403629317F, 0.3408331302F, 0.3413034854F, 0.3417739967F,
  158557. 0.3422446638F, 0.3427154860F, 0.3431864628F, 0.3436575938F,
  158558. 0.3441288782F, 0.3446003158F, 0.3450719058F, 0.3455436478F,
  158559. 0.3460155412F, 0.3464875856F, 0.3469597804F, 0.3474321250F,
  158560. 0.3479046189F, 0.3483772617F, 0.3488500527F, 0.3493229914F,
  158561. 0.3497960774F, 0.3502693100F, 0.3507426887F, 0.3512162131F,
  158562. 0.3516898825F, 0.3521636965F, 0.3526376545F, 0.3531117559F,
  158563. 0.3535860003F, 0.3540603870F, 0.3545349157F, 0.3550095856F,
  158564. 0.3554843964F, 0.3559593474F, 0.3564344381F, 0.3569096680F,
  158565. 0.3573850366F, 0.3578605432F, 0.3583361875F, 0.3588119687F,
  158566. 0.3592878865F, 0.3597639402F, 0.3602401293F, 0.3607164533F,
  158567. 0.3611929117F, 0.3616695038F, 0.3621462292F, 0.3626230873F,
  158568. 0.3631000776F, 0.3635771995F, 0.3640544525F, 0.3645318360F,
  158569. 0.3650093496F, 0.3654869926F, 0.3659647645F, 0.3664426648F,
  158570. 0.3669206930F, 0.3673988484F, 0.3678771306F, 0.3683555390F,
  158571. 0.3688340731F, 0.3693127322F, 0.3697915160F, 0.3702704237F,
  158572. 0.3707494549F, 0.3712286091F, 0.3717078857F, 0.3721872840F,
  158573. 0.3726668037F, 0.3731464441F, 0.3736262047F, 0.3741060850F,
  158574. 0.3745860843F, 0.3750662023F, 0.3755464382F, 0.3760267915F,
  158575. 0.3765072618F, 0.3769878484F, 0.3774685509F, 0.3779493686F,
  158576. 0.3784303010F, 0.3789113475F, 0.3793925076F, 0.3798737809F,
  158577. 0.3803551666F, 0.3808366642F, 0.3813182733F, 0.3817999932F,
  158578. 0.3822818234F, 0.3827637633F, 0.3832458124F, 0.3837279702F,
  158579. 0.3842102360F, 0.3846926093F, 0.3851750897F, 0.3856576764F,
  158580. 0.3861403690F, 0.3866231670F, 0.3871060696F, 0.3875890765F,
  158581. 0.3880721870F, 0.3885554007F, 0.3890387168F, 0.3895221349F,
  158582. 0.3900056544F, 0.3904892748F, 0.3909729955F, 0.3914568160F,
  158583. 0.3919407356F, 0.3924247539F, 0.3929088702F, 0.3933930841F,
  158584. 0.3938773949F, 0.3943618021F, 0.3948463052F, 0.3953309035F,
  158585. 0.3958155966F, 0.3963003838F, 0.3967852646F, 0.3972702385F,
  158586. 0.3977553048F, 0.3982404631F, 0.3987257127F, 0.3992110531F,
  158587. 0.3996964838F, 0.4001820041F, 0.4006676136F, 0.4011533116F,
  158588. 0.4016390976F, 0.4021249710F, 0.4026109313F, 0.4030969779F,
  158589. 0.4035831102F, 0.4040693277F, 0.4045556299F, 0.4050420160F,
  158590. 0.4055284857F, 0.4060150383F, 0.4065016732F, 0.4069883899F,
  158591. 0.4074751879F, 0.4079620665F, 0.4084490252F, 0.4089360635F,
  158592. 0.4094231807F, 0.4099103763F, 0.4103976498F, 0.4108850005F,
  158593. 0.4113724280F, 0.4118599315F, 0.4123475107F, 0.4128351648F,
  158594. 0.4133228934F, 0.4138106959F, 0.4142985716F, 0.4147865201F,
  158595. 0.4152745408F, 0.4157626330F, 0.4162507963F, 0.4167390301F,
  158596. 0.4172273337F, 0.4177157067F, 0.4182041484F, 0.4186926583F,
  158597. 0.4191812359F, 0.4196698805F, 0.4201585915F, 0.4206473685F,
  158598. 0.4211362108F, 0.4216251179F, 0.4221140892F, 0.4226031241F,
  158599. 0.4230922221F, 0.4235813826F, 0.4240706050F, 0.4245598887F,
  158600. 0.4250492332F, 0.4255386379F, 0.4260281022F, 0.4265176256F,
  158601. 0.4270072075F, 0.4274968473F, 0.4279865445F, 0.4284762984F,
  158602. 0.4289661086F, 0.4294559743F, 0.4299458951F, 0.4304358704F,
  158603. 0.4309258996F, 0.4314159822F, 0.4319061175F, 0.4323963050F,
  158604. 0.4328865441F, 0.4333768342F, 0.4338671749F, 0.4343575654F,
  158605. 0.4348480052F, 0.4353384938F, 0.4358290306F, 0.4363196149F,
  158606. 0.4368102463F, 0.4373009241F, 0.4377916478F, 0.4382824168F,
  158607. 0.4387732305F, 0.4392640884F, 0.4397549899F, 0.4402459343F,
  158608. 0.4407369212F, 0.4412279499F, 0.4417190198F, 0.4422101305F,
  158609. 0.4427012813F, 0.4431924717F, 0.4436837010F, 0.4441749686F,
  158610. 0.4446662742F, 0.4451576169F, 0.4456489963F, 0.4461404118F,
  158611. 0.4466318628F, 0.4471233487F, 0.4476148690F, 0.4481064230F,
  158612. 0.4485980103F, 0.4490896302F, 0.4495812821F, 0.4500729654F,
  158613. 0.4505646797F, 0.4510564243F, 0.4515481986F, 0.4520400021F,
  158614. 0.4525318341F, 0.4530236942F, 0.4535155816F, 0.4540074959F,
  158615. 0.4544994365F, 0.4549914028F, 0.4554833941F, 0.4559754100F,
  158616. 0.4564674499F, 0.4569595131F, 0.4574515991F, 0.4579437074F,
  158617. 0.4584358372F, 0.4589279881F, 0.4594201595F, 0.4599123508F,
  158618. 0.4604045615F, 0.4608967908F, 0.4613890383F, 0.4618813034F,
  158619. 0.4623735855F, 0.4628658841F, 0.4633581984F, 0.4638505281F,
  158620. 0.4643428724F, 0.4648352308F, 0.4653276028F, 0.4658199877F,
  158621. 0.4663123849F, 0.4668047940F, 0.4672972143F, 0.4677896451F,
  158622. 0.4682820861F, 0.4687745365F, 0.4692669958F, 0.4697594634F,
  158623. 0.4702519387F, 0.4707444211F, 0.4712369102F, 0.4717294052F,
  158624. 0.4722219056F, 0.4727144109F, 0.4732069204F, 0.4736994336F,
  158625. 0.4741919498F, 0.4746844686F, 0.4751769893F, 0.4756695113F,
  158626. 0.4761620341F, 0.4766545571F, 0.4771470797F, 0.4776396013F,
  158627. 0.4781321213F, 0.4786246392F, 0.4791171544F, 0.4796096663F,
  158628. 0.4801021744F, 0.4805946779F, 0.4810871765F, 0.4815796694F,
  158629. 0.4820721561F, 0.4825646360F, 0.4830571086F, 0.4835495732F,
  158630. 0.4840420293F, 0.4845344763F, 0.4850269136F, 0.4855193407F,
  158631. 0.4860117569F, 0.4865041617F, 0.4869965545F, 0.4874889347F,
  158632. 0.4879813018F, 0.4884736551F, 0.4889659941F, 0.4894583182F,
  158633. 0.4899506268F, 0.4904429193F, 0.4909351952F, 0.4914274538F,
  158634. 0.4919196947F, 0.4924119172F, 0.4929041207F, 0.4933963046F,
  158635. 0.4938884685F, 0.4943806116F, 0.4948727335F, 0.4953648335F,
  158636. 0.4958569110F, 0.4963489656F, 0.4968409965F, 0.4973330032F,
  158637. 0.4978249852F, 0.4983169419F, 0.4988088726F, 0.4993007768F,
  158638. 0.4997926539F, 0.5002845034F, 0.5007763247F, 0.5012681171F,
  158639. 0.5017598801F, 0.5022516132F, 0.5027433157F, 0.5032349871F,
  158640. 0.5037266268F, 0.5042182341F, 0.5047098086F, 0.5052013497F,
  158641. 0.5056928567F, 0.5061843292F, 0.5066757664F, 0.5071671679F,
  158642. 0.5076585330F, 0.5081498613F, 0.5086411520F, 0.5091324047F,
  158643. 0.5096236187F, 0.5101147934F, 0.5106059284F, 0.5110970230F,
  158644. 0.5115880766F, 0.5120790887F, 0.5125700587F, 0.5130609860F,
  158645. 0.5135518700F, 0.5140427102F, 0.5145335059F, 0.5150242566F,
  158646. 0.5155149618F, 0.5160056208F, 0.5164962331F, 0.5169867980F,
  158647. 0.5174773151F, 0.5179677837F, 0.5184582033F, 0.5189485733F,
  158648. 0.5194388931F, 0.5199291621F, 0.5204193798F, 0.5209095455F,
  158649. 0.5213996588F, 0.5218897190F, 0.5223797256F, 0.5228696779F,
  158650. 0.5233595755F, 0.5238494177F, 0.5243392039F, 0.5248289337F,
  158651. 0.5253186063F, 0.5258082213F, 0.5262977781F, 0.5267872760F,
  158652. 0.5272767146F, 0.5277660932F, 0.5282554112F, 0.5287446682F,
  158653. 0.5292338635F, 0.5297229965F, 0.5302120667F, 0.5307010736F,
  158654. 0.5311900164F, 0.5316788947F, 0.5321677079F, 0.5326564554F,
  158655. 0.5331451366F, 0.5336337511F, 0.5341222981F, 0.5346107771F,
  158656. 0.5350991876F, 0.5355875290F, 0.5360758007F, 0.5365640021F,
  158657. 0.5370521327F, 0.5375401920F, 0.5380281792F, 0.5385160939F,
  158658. 0.5390039355F, 0.5394917034F, 0.5399793971F, 0.5404670159F,
  158659. 0.5409545594F, 0.5414420269F, 0.5419294179F, 0.5424167318F,
  158660. 0.5429039680F, 0.5433911261F, 0.5438782053F, 0.5443652051F,
  158661. 0.5448521250F, 0.5453389644F, 0.5458257228F, 0.5463123995F,
  158662. 0.5467989940F, 0.5472855057F, 0.5477719341F, 0.5482582786F,
  158663. 0.5487445387F, 0.5492307137F, 0.5497168031F, 0.5502028063F,
  158664. 0.5506887228F, 0.5511745520F, 0.5516602934F, 0.5521459463F,
  158665. 0.5526315103F, 0.5531169847F, 0.5536023690F, 0.5540876626F,
  158666. 0.5545728649F, 0.5550579755F, 0.5555429937F, 0.5560279189F,
  158667. 0.5565127507F, 0.5569974884F, 0.5574821315F, 0.5579666794F,
  158668. 0.5584511316F, 0.5589354875F, 0.5594197465F, 0.5599039080F,
  158669. 0.5603879716F, 0.5608719367F, 0.5613558026F, 0.5618395689F,
  158670. 0.5623232350F, 0.5628068002F, 0.5632902642F, 0.5637736262F,
  158671. 0.5642568858F, 0.5647400423F, 0.5652230953F, 0.5657060442F,
  158672. 0.5661888883F, 0.5666716272F, 0.5671542603F, 0.5676367870F,
  158673. 0.5681192069F, 0.5686015192F, 0.5690837235F, 0.5695658192F,
  158674. 0.5700478058F, 0.5705296827F, 0.5710114494F, 0.5714931052F,
  158675. 0.5719746497F, 0.5724560822F, 0.5729374023F, 0.5734186094F,
  158676. 0.5738997029F, 0.5743806823F, 0.5748615470F, 0.5753422965F,
  158677. 0.5758229301F, 0.5763034475F, 0.5767838480F, 0.5772641310F,
  158678. 0.5777442960F, 0.5782243426F, 0.5787042700F, 0.5791840778F,
  158679. 0.5796637654F, 0.5801433322F, 0.5806227778F, 0.5811021016F,
  158680. 0.5815813029F, 0.5820603814F, 0.5825393363F, 0.5830181673F,
  158681. 0.5834968737F, 0.5839754549F, 0.5844539105F, 0.5849322399F,
  158682. 0.5854104425F, 0.5858885179F, 0.5863664653F, 0.5868442844F,
  158683. 0.5873219746F, 0.5877995353F, 0.5882769660F, 0.5887542661F,
  158684. 0.5892314351F, 0.5897084724F, 0.5901853776F, 0.5906621500F,
  158685. 0.5911387892F, 0.5916152945F, 0.5920916655F, 0.5925679016F,
  158686. 0.5930440022F, 0.5935199669F, 0.5939957950F, 0.5944714861F,
  158687. 0.5949470396F, 0.5954224550F, 0.5958977317F, 0.5963728692F,
  158688. 0.5968478669F, 0.5973227244F, 0.5977974411F, 0.5982720163F,
  158689. 0.5987464497F, 0.5992207407F, 0.5996948887F, 0.6001688932F,
  158690. 0.6006427537F, 0.6011164696F, 0.6015900405F, 0.6020634657F,
  158691. 0.6025367447F, 0.6030098770F, 0.6034828621F, 0.6039556995F,
  158692. 0.6044283885F, 0.6049009288F, 0.6053733196F, 0.6058455606F,
  158693. 0.6063176512F, 0.6067895909F, 0.6072613790F, 0.6077330152F,
  158694. 0.6082044989F, 0.6086758295F, 0.6091470065F, 0.6096180294F,
  158695. 0.6100888977F, 0.6105596108F, 0.6110301682F, 0.6115005694F,
  158696. 0.6119708139F, 0.6124409011F, 0.6129108305F, 0.6133806017F,
  158697. 0.6138502139F, 0.6143196669F, 0.6147889599F, 0.6152580926F,
  158698. 0.6157270643F, 0.6161958746F, 0.6166645230F, 0.6171330088F,
  158699. 0.6176013317F, 0.6180694910F, 0.6185374863F, 0.6190053171F,
  158700. 0.6194729827F, 0.6199404828F, 0.6204078167F, 0.6208749841F,
  158701. 0.6213419842F, 0.6218088168F, 0.6222754811F, 0.6227419768F,
  158702. 0.6232083032F, 0.6236744600F, 0.6241404465F, 0.6246062622F,
  158703. 0.6250719067F, 0.6255373795F, 0.6260026799F, 0.6264678076F,
  158704. 0.6269327619F, 0.6273975425F, 0.6278621487F, 0.6283265800F,
  158705. 0.6287908361F, 0.6292549163F, 0.6297188201F, 0.6301825471F,
  158706. 0.6306460966F, 0.6311094683F, 0.6315726617F, 0.6320356761F,
  158707. 0.6324985111F, 0.6329611662F, 0.6334236410F, 0.6338859348F,
  158708. 0.6343480472F, 0.6348099777F, 0.6352717257F, 0.6357332909F,
  158709. 0.6361946726F, 0.6366558704F, 0.6371168837F, 0.6375777122F,
  158710. 0.6380383552F, 0.6384988123F, 0.6389590830F, 0.6394191668F,
  158711. 0.6398790631F, 0.6403387716F, 0.6407982916F, 0.6412576228F,
  158712. 0.6417167645F, 0.6421757163F, 0.6426344778F, 0.6430930483F,
  158713. 0.6435514275F, 0.6440096149F, 0.6444676098F, 0.6449254119F,
  158714. 0.6453830207F, 0.6458404356F, 0.6462976562F, 0.6467546820F,
  158715. 0.6472115125F, 0.6476681472F, 0.6481245856F, 0.6485808273F,
  158716. 0.6490368717F, 0.6494927183F, 0.6499483667F, 0.6504038164F,
  158717. 0.6508590670F, 0.6513141178F, 0.6517689684F, 0.6522236185F,
  158718. 0.6526780673F, 0.6531323146F, 0.6535863598F, 0.6540402024F,
  158719. 0.6544938419F, 0.6549472779F, 0.6554005099F, 0.6558535373F,
  158720. 0.6563063598F, 0.6567589769F, 0.6572113880F, 0.6576635927F,
  158721. 0.6581155906F, 0.6585673810F, 0.6590189637F, 0.6594703380F,
  158722. 0.6599215035F, 0.6603724598F, 0.6608232064F, 0.6612737427F,
  158723. 0.6617240684F, 0.6621741829F, 0.6626240859F, 0.6630737767F,
  158724. 0.6635232550F, 0.6639725202F, 0.6644215720F, 0.6648704098F,
  158725. 0.6653190332F, 0.6657674417F, 0.6662156348F, 0.6666636121F,
  158726. 0.6671113731F, 0.6675589174F, 0.6680062445F, 0.6684533538F,
  158727. 0.6689002450F, 0.6693469177F, 0.6697933712F, 0.6702396052F,
  158728. 0.6706856193F, 0.6711314129F, 0.6715769855F, 0.6720223369F,
  158729. 0.6724674664F, 0.6729123736F, 0.6733570581F, 0.6738015194F,
  158730. 0.6742457570F, 0.6746897706F, 0.6751335596F, 0.6755771236F,
  158731. 0.6760204621F, 0.6764635747F, 0.6769064609F, 0.6773491204F,
  158732. 0.6777915525F, 0.6782337570F, 0.6786757332F, 0.6791174809F,
  158733. 0.6795589995F, 0.6800002886F, 0.6804413477F, 0.6808821765F,
  158734. 0.6813227743F, 0.6817631409F, 0.6822032758F, 0.6826431785F,
  158735. 0.6830828485F, 0.6835222855F, 0.6839614890F, 0.6844004585F,
  158736. 0.6848391936F, 0.6852776939F, 0.6857159589F, 0.6861539883F,
  158737. 0.6865917815F, 0.6870293381F, 0.6874666576F, 0.6879037398F,
  158738. 0.6883405840F, 0.6887771899F, 0.6892135571F, 0.6896496850F,
  158739. 0.6900855733F, 0.6905212216F, 0.6909566294F, 0.6913917963F,
  158740. 0.6918267218F, 0.6922614055F, 0.6926958471F, 0.6931300459F,
  158741. 0.6935640018F, 0.6939977141F, 0.6944311825F, 0.6948644066F,
  158742. 0.6952973859F, 0.6957301200F, 0.6961626085F, 0.6965948510F,
  158743. 0.6970268470F, 0.6974585961F, 0.6978900980F, 0.6983213521F,
  158744. 0.6987523580F, 0.6991831154F, 0.6996136238F, 0.7000438828F,
  158745. 0.7004738921F, 0.7009036510F, 0.7013331594F, 0.7017624166F,
  158746. 0.7021914224F, 0.7026201763F, 0.7030486779F, 0.7034769268F,
  158747. 0.7039049226F, 0.7043326648F, 0.7047601531F, 0.7051873870F,
  158748. 0.7056143662F, 0.7060410902F, 0.7064675586F, 0.7068937711F,
  158749. 0.7073197271F, 0.7077454264F, 0.7081708684F, 0.7085960529F,
  158750. 0.7090209793F, 0.7094456474F, 0.7098700566F, 0.7102942066F,
  158751. 0.7107180970F, 0.7111417274F, 0.7115650974F, 0.7119882066F,
  158752. 0.7124110545F, 0.7128336409F, 0.7132559653F, 0.7136780272F,
  158753. 0.7140998264F, 0.7145213624F, 0.7149426348F, 0.7153636433F,
  158754. 0.7157843874F, 0.7162048668F, 0.7166250810F, 0.7170450296F,
  158755. 0.7174647124F, 0.7178841289F, 0.7183032786F, 0.7187221613F,
  158756. 0.7191407765F, 0.7195591239F, 0.7199772030F, 0.7203950135F,
  158757. 0.7208125550F, 0.7212298271F, 0.7216468294F, 0.7220635616F,
  158758. 0.7224800233F, 0.7228962140F, 0.7233121335F, 0.7237277813F,
  158759. 0.7241431571F, 0.7245582604F, 0.7249730910F, 0.7253876484F,
  158760. 0.7258019322F, 0.7262159422F, 0.7266296778F, 0.7270431388F,
  158761. 0.7274563247F, 0.7278692353F, 0.7282818700F, 0.7286942287F,
  158762. 0.7291063108F, 0.7295181160F, 0.7299296440F, 0.7303408944F,
  158763. 0.7307518669F, 0.7311625609F, 0.7315729763F, 0.7319831126F,
  158764. 0.7323929695F, 0.7328025466F, 0.7332118435F, 0.7336208600F,
  158765. 0.7340295955F, 0.7344380499F, 0.7348462226F, 0.7352541134F,
  158766. 0.7356617220F, 0.7360690478F, 0.7364760907F, 0.7368828502F,
  158767. 0.7372893259F, 0.7376955176F, 0.7381014249F, 0.7385070475F,
  158768. 0.7389123849F, 0.7393174368F, 0.7397222029F, 0.7401266829F,
  158769. 0.7405308763F, 0.7409347829F, 0.7413384023F, 0.7417417341F,
  158770. 0.7421447780F, 0.7425475338F, 0.7429500009F, 0.7433521791F,
  158771. 0.7437540681F, 0.7441556674F, 0.7445569769F, 0.7449579960F,
  158772. 0.7453587245F, 0.7457591621F, 0.7461593084F, 0.7465591631F,
  158773. 0.7469587259F, 0.7473579963F, 0.7477569741F, 0.7481556590F,
  158774. 0.7485540506F, 0.7489521486F, 0.7493499526F, 0.7497474623F,
  158775. 0.7501446775F, 0.7505415977F, 0.7509382227F, 0.7513345521F,
  158776. 0.7517305856F, 0.7521263229F, 0.7525217636F, 0.7529169074F,
  158777. 0.7533117541F, 0.7537063032F, 0.7541005545F, 0.7544945076F,
  158778. 0.7548881623F, 0.7552815182F, 0.7556745749F, 0.7560673323F,
  158779. 0.7564597899F, 0.7568519474F, 0.7572438046F, 0.7576353611F,
  158780. 0.7580266166F, 0.7584175708F, 0.7588082235F, 0.7591985741F,
  158781. 0.7595886226F, 0.7599783685F, 0.7603678116F, 0.7607569515F,
  158782. 0.7611457879F, 0.7615343206F, 0.7619225493F, 0.7623104735F,
  158783. 0.7626980931F, 0.7630854078F, 0.7634724171F, 0.7638591209F,
  158784. 0.7642455188F, 0.7646316106F, 0.7650173959F, 0.7654028744F,
  158785. 0.7657880459F, 0.7661729100F, 0.7665574664F, 0.7669417150F,
  158786. 0.7673256553F, 0.7677092871F, 0.7680926100F, 0.7684756239F,
  158787. 0.7688583284F, 0.7692407232F, 0.7696228080F, 0.7700045826F,
  158788. 0.7703860467F, 0.7707671999F, 0.7711480420F, 0.7715285728F,
  158789. 0.7719087918F, 0.7722886989F, 0.7726682938F, 0.7730475762F,
  158790. 0.7734265458F, 0.7738052023F, 0.7741835454F, 0.7745615750F,
  158791. 0.7749392906F, 0.7753166921F, 0.7756937791F, 0.7760705514F,
  158792. 0.7764470087F, 0.7768231508F, 0.7771989773F, 0.7775744880F,
  158793. 0.7779496827F, 0.7783245610F, 0.7786991227F, 0.7790733676F,
  158794. 0.7794472953F, 0.7798209056F, 0.7801941982F, 0.7805671729F,
  158795. 0.7809398294F, 0.7813121675F, 0.7816841869F, 0.7820558873F,
  158796. 0.7824272684F, 0.7827983301F, 0.7831690720F, 0.7835394940F,
  158797. 0.7839095957F, 0.7842793768F, 0.7846488373F, 0.7850179767F,
  158798. 0.7853867948F, 0.7857552914F, 0.7861234663F, 0.7864913191F,
  158799. 0.7868588497F, 0.7872260578F, 0.7875929431F, 0.7879595055F,
  158800. 0.7883257445F, 0.7886916601F, 0.7890572520F, 0.7894225198F,
  158801. 0.7897874635F, 0.7901520827F, 0.7905163772F, 0.7908803468F,
  158802. 0.7912439912F, 0.7916073102F, 0.7919703035F, 0.7923329710F,
  158803. 0.7926953124F, 0.7930573274F, 0.7934190158F, 0.7937803774F,
  158804. 0.7941414120F, 0.7945021193F, 0.7948624991F, 0.7952225511F,
  158805. 0.7955822752F, 0.7959416711F, 0.7963007387F, 0.7966594775F,
  158806. 0.7970178875F, 0.7973759685F, 0.7977337201F, 0.7980911422F,
  158807. 0.7984482346F, 0.7988049970F, 0.7991614292F, 0.7995175310F,
  158808. 0.7998733022F, 0.8002287426F, 0.8005838519F, 0.8009386299F,
  158809. 0.8012930765F, 0.8016471914F, 0.8020009744F, 0.8023544253F,
  158810. 0.8027075438F, 0.8030603298F, 0.8034127831F, 0.8037649035F,
  158811. 0.8041166906F, 0.8044681445F, 0.8048192647F, 0.8051700512F,
  158812. 0.8055205038F, 0.8058706222F, 0.8062204062F, 0.8065698556F,
  158813. 0.8069189702F, 0.8072677499F, 0.8076161944F, 0.8079643036F,
  158814. 0.8083120772F, 0.8086595151F, 0.8090066170F, 0.8093533827F,
  158815. 0.8096998122F, 0.8100459051F, 0.8103916613F, 0.8107370806F,
  158816. 0.8110821628F, 0.8114269077F, 0.8117713151F, 0.8121153849F,
  158817. 0.8124591169F, 0.8128025108F, 0.8131455666F, 0.8134882839F,
  158818. 0.8138306627F, 0.8141727027F, 0.8145144038F, 0.8148557658F,
  158819. 0.8151967886F, 0.8155374718F, 0.8158778154F, 0.8162178192F,
  158820. 0.8165574830F, 0.8168968067F, 0.8172357900F, 0.8175744328F,
  158821. 0.8179127349F, 0.8182506962F, 0.8185883164F, 0.8189255955F,
  158822. 0.8192625332F, 0.8195991295F, 0.8199353840F, 0.8202712967F,
  158823. 0.8206068673F, 0.8209420958F, 0.8212769820F, 0.8216115256F,
  158824. 0.8219457266F, 0.8222795848F, 0.8226131000F, 0.8229462721F,
  158825. 0.8232791009F, 0.8236115863F, 0.8239437280F, 0.8242755260F,
  158826. 0.8246069801F, 0.8249380901F, 0.8252688559F, 0.8255992774F,
  158827. 0.8259293544F, 0.8262590867F, 0.8265884741F, 0.8269175167F,
  158828. 0.8272462141F, 0.8275745663F, 0.8279025732F, 0.8282302344F,
  158829. 0.8285575501F, 0.8288845199F, 0.8292111437F, 0.8295374215F,
  158830. 0.8298633530F, 0.8301889382F, 0.8305141768F, 0.8308390688F,
  158831. 0.8311636141F, 0.8314878124F, 0.8318116637F, 0.8321351678F,
  158832. 0.8324583246F, 0.8327811340F, 0.8331035957F, 0.8334257098F,
  158833. 0.8337474761F, 0.8340688944F, 0.8343899647F, 0.8347106867F,
  158834. 0.8350310605F, 0.8353510857F, 0.8356707624F, 0.8359900904F,
  158835. 0.8363090696F, 0.8366276999F, 0.8369459811F, 0.8372639131F,
  158836. 0.8375814958F, 0.8378987292F, 0.8382156130F, 0.8385321472F,
  158837. 0.8388483316F, 0.8391641662F, 0.8394796508F, 0.8397947853F,
  158838. 0.8401095697F, 0.8404240037F, 0.8407380873F, 0.8410518204F,
  158839. 0.8413652029F, 0.8416782347F, 0.8419909156F, 0.8423032456F,
  158840. 0.8426152245F, 0.8429268523F, 0.8432381289F, 0.8435490541F,
  158841. 0.8438596279F, 0.8441698502F, 0.8444797208F, 0.8447892396F,
  158842. 0.8450984067F, 0.8454072218F, 0.8457156849F, 0.8460237959F,
  158843. 0.8463315547F, 0.8466389612F, 0.8469460154F, 0.8472527170F,
  158844. 0.8475590661F, 0.8478650625F, 0.8481707063F, 0.8484759971F,
  158845. 0.8487809351F, 0.8490855201F, 0.8493897521F, 0.8496936308F,
  158846. 0.8499971564F, 0.8503003286F, 0.8506031474F, 0.8509056128F,
  158847. 0.8512077246F, 0.8515094828F, 0.8518108872F, 0.8521119379F,
  158848. 0.8524126348F, 0.8527129777F, 0.8530129666F, 0.8533126015F,
  158849. 0.8536118822F, 0.8539108087F, 0.8542093809F, 0.8545075988F,
  158850. 0.8548054623F, 0.8551029712F, 0.8554001257F, 0.8556969255F,
  158851. 0.8559933707F, 0.8562894611F, 0.8565851968F, 0.8568805775F,
  158852. 0.8571756034F, 0.8574702743F, 0.8577645902F, 0.8580585509F,
  158853. 0.8583521566F, 0.8586454070F, 0.8589383021F, 0.8592308420F,
  158854. 0.8595230265F, 0.8598148556F, 0.8601063292F, 0.8603974473F,
  158855. 0.8606882098F, 0.8609786167F, 0.8612686680F, 0.8615583636F,
  158856. 0.8618477034F, 0.8621366874F, 0.8624253156F, 0.8627135878F,
  158857. 0.8630015042F, 0.8632890646F, 0.8635762690F, 0.8638631173F,
  158858. 0.8641496096F, 0.8644357457F, 0.8647215257F, 0.8650069495F,
  158859. 0.8652920171F, 0.8655767283F, 0.8658610833F, 0.8661450820F,
  158860. 0.8664287243F, 0.8667120102F, 0.8669949397F, 0.8672775127F,
  158861. 0.8675597293F, 0.8678415894F, 0.8681230929F, 0.8684042398F,
  158862. 0.8686850302F, 0.8689654640F, 0.8692455412F, 0.8695252617F,
  158863. 0.8698046255F, 0.8700836327F, 0.8703622831F, 0.8706405768F,
  158864. 0.8709185138F, 0.8711960940F, 0.8714733174F, 0.8717501840F,
  158865. 0.8720266939F, 0.8723028469F, 0.8725786430F, 0.8728540824F,
  158866. 0.8731291648F, 0.8734038905F, 0.8736782592F, 0.8739522711F,
  158867. 0.8742259261F, 0.8744992242F, 0.8747721653F, 0.8750447496F,
  158868. 0.8753169770F, 0.8755888475F, 0.8758603611F, 0.8761315177F,
  158869. 0.8764023175F, 0.8766727603F, 0.8769428462F, 0.8772125752F,
  158870. 0.8774819474F, 0.8777509626F, 0.8780196209F, 0.8782879224F,
  158871. 0.8785558669F, 0.8788234546F, 0.8790906854F, 0.8793575594F,
  158872. 0.8796240765F, 0.8798902368F, 0.8801560403F, 0.8804214870F,
  158873. 0.8806865768F, 0.8809513099F, 0.8812156863F, 0.8814797059F,
  158874. 0.8817433687F, 0.8820066749F, 0.8822696243F, 0.8825322171F,
  158875. 0.8827944532F, 0.8830563327F, 0.8833178556F, 0.8835790219F,
  158876. 0.8838398316F, 0.8841002848F, 0.8843603815F, 0.8846201217F,
  158877. 0.8848795054F, 0.8851385327F, 0.8853972036F, 0.8856555182F,
  158878. 0.8859134764F, 0.8861710783F, 0.8864283239F, 0.8866852133F,
  158879. 0.8869417464F, 0.8871979234F, 0.8874537443F, 0.8877092090F,
  158880. 0.8879643177F, 0.8882190704F, 0.8884734671F, 0.8887275078F,
  158881. 0.8889811927F, 0.8892345216F, 0.8894874948F, 0.8897401122F,
  158882. 0.8899923738F, 0.8902442798F, 0.8904958301F, 0.8907470248F,
  158883. 0.8909978640F, 0.8912483477F, 0.8914984759F, 0.8917482487F,
  158884. 0.8919976662F, 0.8922467284F, 0.8924954353F, 0.8927437871F,
  158885. 0.8929917837F, 0.8932394252F, 0.8934867118F, 0.8937336433F,
  158886. 0.8939802199F, 0.8942264417F, 0.8944723087F, 0.8947178210F,
  158887. 0.8949629785F, 0.8952077815F, 0.8954522299F, 0.8956963239F,
  158888. 0.8959400634F, 0.8961834486F, 0.8964264795F, 0.8966691561F,
  158889. 0.8969114786F, 0.8971534470F, 0.8973950614F, 0.8976363219F,
  158890. 0.8978772284F, 0.8981177812F, 0.8983579802F, 0.8985978256F,
  158891. 0.8988373174F, 0.8990764556F, 0.8993152405F, 0.8995536720F,
  158892. 0.8997917502F, 0.9000294751F, 0.9002668470F, 0.9005038658F,
  158893. 0.9007405317F, 0.9009768446F, 0.9012128048F, 0.9014484123F,
  158894. 0.9016836671F, 0.9019185693F, 0.9021531191F, 0.9023873165F,
  158895. 0.9026211616F, 0.9028546546F, 0.9030877954F, 0.9033205841F,
  158896. 0.9035530210F, 0.9037851059F, 0.9040168392F, 0.9042482207F,
  158897. 0.9044792507F, 0.9047099293F, 0.9049402564F, 0.9051702323F,
  158898. 0.9053998569F, 0.9056291305F, 0.9058580531F, 0.9060866248F,
  158899. 0.9063148457F, 0.9065427159F, 0.9067702355F, 0.9069974046F,
  158900. 0.9072242233F, 0.9074506917F, 0.9076768100F, 0.9079025782F,
  158901. 0.9081279964F, 0.9083530647F, 0.9085777833F, 0.9088021523F,
  158902. 0.9090261717F, 0.9092498417F, 0.9094731623F, 0.9096961338F,
  158903. 0.9099187561F, 0.9101410295F, 0.9103629540F, 0.9105845297F,
  158904. 0.9108057568F, 0.9110266354F, 0.9112471656F, 0.9114673475F,
  158905. 0.9116871812F, 0.9119066668F, 0.9121258046F, 0.9123445945F,
  158906. 0.9125630367F, 0.9127811314F, 0.9129988786F, 0.9132162785F,
  158907. 0.9134333312F, 0.9136500368F, 0.9138663954F, 0.9140824073F,
  158908. 0.9142980724F, 0.9145133910F, 0.9147283632F, 0.9149429890F,
  158909. 0.9151572687F, 0.9153712023F, 0.9155847900F, 0.9157980319F,
  158910. 0.9160109282F, 0.9162234790F, 0.9164356844F, 0.9166475445F,
  158911. 0.9168590595F, 0.9170702296F, 0.9172810548F, 0.9174915354F,
  158912. 0.9177016714F, 0.9179114629F, 0.9181209102F, 0.9183300134F,
  158913. 0.9185387726F, 0.9187471879F, 0.9189552595F, 0.9191629876F,
  158914. 0.9193703723F, 0.9195774136F, 0.9197841119F, 0.9199904672F,
  158915. 0.9201964797F, 0.9204021495F, 0.9206074767F, 0.9208124616F,
  158916. 0.9210171043F, 0.9212214049F, 0.9214253636F, 0.9216289805F,
  158917. 0.9218322558F, 0.9220351896F, 0.9222377821F, 0.9224400335F,
  158918. 0.9226419439F, 0.9228435134F, 0.9230447423F, 0.9232456307F,
  158919. 0.9234461787F, 0.9236463865F, 0.9238462543F, 0.9240457822F,
  158920. 0.9242449704F, 0.9244438190F, 0.9246423282F, 0.9248404983F,
  158921. 0.9250383293F, 0.9252358214F, 0.9254329747F, 0.9256297896F,
  158922. 0.9258262660F, 0.9260224042F, 0.9262182044F, 0.9264136667F,
  158923. 0.9266087913F, 0.9268035783F, 0.9269980280F, 0.9271921405F,
  158924. 0.9273859160F, 0.9275793546F, 0.9277724566F, 0.9279652221F,
  158925. 0.9281576513F, 0.9283497443F, 0.9285415014F, 0.9287329227F,
  158926. 0.9289240084F, 0.9291147586F, 0.9293051737F, 0.9294952536F,
  158927. 0.9296849987F, 0.9298744091F, 0.9300634850F, 0.9302522266F,
  158928. 0.9304406340F, 0.9306287074F, 0.9308164471F, 0.9310038532F,
  158929. 0.9311909259F, 0.9313776654F, 0.9315640719F, 0.9317501455F,
  158930. 0.9319358865F, 0.9321212951F, 0.9323063713F, 0.9324911155F,
  158931. 0.9326755279F, 0.9328596085F, 0.9330433577F, 0.9332267756F,
  158932. 0.9334098623F, 0.9335926182F, 0.9337750434F, 0.9339571380F,
  158933. 0.9341389023F, 0.9343203366F, 0.9345014409F, 0.9346822155F,
  158934. 0.9348626606F, 0.9350427763F, 0.9352225630F, 0.9354020207F,
  158935. 0.9355811498F, 0.9357599503F, 0.9359384226F, 0.9361165667F,
  158936. 0.9362943830F, 0.9364718716F, 0.9366490327F, 0.9368258666F,
  158937. 0.9370023733F, 0.9371785533F, 0.9373544066F, 0.9375299335F,
  158938. 0.9377051341F, 0.9378800087F, 0.9380545576F, 0.9382287809F,
  158939. 0.9384026787F, 0.9385762515F, 0.9387494993F, 0.9389224223F,
  158940. 0.9390950209F, 0.9392672951F, 0.9394392453F, 0.9396108716F,
  158941. 0.9397821743F, 0.9399531536F, 0.9401238096F, 0.9402941427F,
  158942. 0.9404641530F, 0.9406338407F, 0.9408032061F, 0.9409722495F,
  158943. 0.9411409709F, 0.9413093707F, 0.9414774491F, 0.9416452062F,
  158944. 0.9418126424F, 0.9419797579F, 0.9421465528F, 0.9423130274F,
  158945. 0.9424791819F, 0.9426450166F, 0.9428105317F, 0.9429757274F,
  158946. 0.9431406039F, 0.9433051616F, 0.9434694005F, 0.9436333209F,
  158947. 0.9437969232F, 0.9439602074F, 0.9441231739F, 0.9442858229F,
  158948. 0.9444481545F, 0.9446101691F, 0.9447718669F, 0.9449332481F,
  158949. 0.9450943129F, 0.9452550617F, 0.9454154945F, 0.9455756118F,
  158950. 0.9457354136F, 0.9458949003F, 0.9460540721F, 0.9462129292F,
  158951. 0.9463714719F, 0.9465297003F, 0.9466876149F, 0.9468452157F,
  158952. 0.9470025031F, 0.9471594772F, 0.9473161384F, 0.9474724869F,
  158953. 0.9476285229F, 0.9477842466F, 0.9479396584F, 0.9480947585F,
  158954. 0.9482495470F, 0.9484040243F, 0.9485581906F, 0.9487120462F,
  158955. 0.9488655913F, 0.9490188262F, 0.9491717511F, 0.9493243662F,
  158956. 0.9494766718F, 0.9496286683F, 0.9497803557F, 0.9499317345F,
  158957. 0.9500828047F, 0.9502335668F, 0.9503840209F, 0.9505341673F,
  158958. 0.9506840062F, 0.9508335380F, 0.9509827629F, 0.9511316810F,
  158959. 0.9512802928F, 0.9514285984F, 0.9515765982F, 0.9517242923F,
  158960. 0.9518716810F, 0.9520187646F, 0.9521655434F, 0.9523120176F,
  158961. 0.9524581875F, 0.9526040534F, 0.9527496154F, 0.9528948739F,
  158962. 0.9530398292F, 0.9531844814F, 0.9533288310F, 0.9534728780F,
  158963. 0.9536166229F, 0.9537600659F, 0.9539032071F, 0.9540460470F,
  158964. 0.9541885858F, 0.9543308237F, 0.9544727611F, 0.9546143981F,
  158965. 0.9547557351F, 0.9548967723F, 0.9550375100F, 0.9551779485F,
  158966. 0.9553180881F, 0.9554579290F, 0.9555974714F, 0.9557367158F,
  158967. 0.9558756623F, 0.9560143112F, 0.9561526628F, 0.9562907174F,
  158968. 0.9564284752F, 0.9565659366F, 0.9567031017F, 0.9568399710F,
  158969. 0.9569765446F, 0.9571128229F, 0.9572488061F, 0.9573844944F,
  158970. 0.9575198883F, 0.9576549879F, 0.9577897936F, 0.9579243056F,
  158971. 0.9580585242F, 0.9581924497F, 0.9583260824F, 0.9584594226F,
  158972. 0.9585924705F, 0.9587252264F, 0.9588576906F, 0.9589898634F,
  158973. 0.9591217452F, 0.9592533360F, 0.9593846364F, 0.9595156465F,
  158974. 0.9596463666F, 0.9597767971F, 0.9599069382F, 0.9600367901F,
  158975. 0.9601663533F, 0.9602956279F, 0.9604246143F, 0.9605533128F,
  158976. 0.9606817236F, 0.9608098471F, 0.9609376835F, 0.9610652332F,
  158977. 0.9611924963F, 0.9613194733F, 0.9614461644F, 0.9615725699F,
  158978. 0.9616986901F, 0.9618245253F, 0.9619500757F, 0.9620753418F,
  158979. 0.9622003238F, 0.9623250219F, 0.9624494365F, 0.9625735679F,
  158980. 0.9626974163F, 0.9628209821F, 0.9629442656F, 0.9630672671F,
  158981. 0.9631899868F, 0.9633124251F, 0.9634345822F, 0.9635564585F,
  158982. 0.9636780543F, 0.9637993699F, 0.9639204056F, 0.9640411616F,
  158983. 0.9641616383F, 0.9642818359F, 0.9644017549F, 0.9645213955F,
  158984. 0.9646407579F, 0.9647598426F, 0.9648786497F, 0.9649971797F,
  158985. 0.9651154328F, 0.9652334092F, 0.9653511095F, 0.9654685337F,
  158986. 0.9655856823F, 0.9657025556F, 0.9658191538F, 0.9659354773F,
  158987. 0.9660515263F, 0.9661673013F, 0.9662828024F, 0.9663980300F,
  158988. 0.9665129845F, 0.9666276660F, 0.9667420750F, 0.9668562118F,
  158989. 0.9669700766F, 0.9670836698F, 0.9671969917F, 0.9673100425F,
  158990. 0.9674228227F, 0.9675353325F, 0.9676475722F, 0.9677595422F,
  158991. 0.9678712428F, 0.9679826742F, 0.9680938368F, 0.9682047309F,
  158992. 0.9683153569F, 0.9684257150F, 0.9685358056F, 0.9686456289F,
  158993. 0.9687551853F, 0.9688644752F, 0.9689734987F, 0.9690822564F,
  158994. 0.9691907483F, 0.9692989750F, 0.9694069367F, 0.9695146337F,
  158995. 0.9696220663F, 0.9697292349F, 0.9698361398F, 0.9699427813F,
  158996. 0.9700491597F, 0.9701552754F, 0.9702611286F, 0.9703667197F,
  158997. 0.9704720490F, 0.9705771169F, 0.9706819236F, 0.9707864695F,
  158998. 0.9708907549F, 0.9709947802F, 0.9710985456F, 0.9712020514F,
  158999. 0.9713052981F, 0.9714082859F, 0.9715110151F, 0.9716134862F,
  159000. 0.9717156993F, 0.9718176549F, 0.9719193532F, 0.9720207946F,
  159001. 0.9721219794F, 0.9722229080F, 0.9723235806F, 0.9724239976F,
  159002. 0.9725241593F, 0.9726240661F, 0.9727237183F, 0.9728231161F,
  159003. 0.9729222601F, 0.9730211503F, 0.9731197873F, 0.9732181713F,
  159004. 0.9733163027F, 0.9734141817F, 0.9735118088F, 0.9736091842F,
  159005. 0.9737063083F, 0.9738031814F, 0.9738998039F, 0.9739961760F,
  159006. 0.9740922981F, 0.9741881706F, 0.9742837938F, 0.9743791680F,
  159007. 0.9744742935F, 0.9745691707F, 0.9746637999F, 0.9747581814F,
  159008. 0.9748523157F, 0.9749462029F, 0.9750398435F, 0.9751332378F,
  159009. 0.9752263861F, 0.9753192887F, 0.9754119461F, 0.9755043585F,
  159010. 0.9755965262F, 0.9756884496F, 0.9757801291F, 0.9758715650F,
  159011. 0.9759627575F, 0.9760537071F, 0.9761444141F, 0.9762348789F,
  159012. 0.9763251016F, 0.9764150828F, 0.9765048228F, 0.9765943218F,
  159013. 0.9766835802F, 0.9767725984F, 0.9768613767F, 0.9769499154F,
  159014. 0.9770382149F, 0.9771262755F, 0.9772140976F, 0.9773016815F,
  159015. 0.9773890275F, 0.9774761360F, 0.9775630073F, 0.9776496418F,
  159016. 0.9777360398F, 0.9778222016F, 0.9779081277F, 0.9779938182F,
  159017. 0.9780792736F, 0.9781644943F, 0.9782494805F, 0.9783342326F,
  159018. 0.9784187509F, 0.9785030359F, 0.9785870877F, 0.9786709069F,
  159019. 0.9787544936F, 0.9788378484F, 0.9789209714F, 0.9790038631F,
  159020. 0.9790865238F, 0.9791689538F, 0.9792511535F, 0.9793331232F,
  159021. 0.9794148633F, 0.9794963742F, 0.9795776561F, 0.9796587094F,
  159022. 0.9797395345F, 0.9798201316F, 0.9799005013F, 0.9799806437F,
  159023. 0.9800605593F, 0.9801402483F, 0.9802197112F, 0.9802989483F,
  159024. 0.9803779600F, 0.9804567465F, 0.9805353082F, 0.9806136455F,
  159025. 0.9806917587F, 0.9807696482F, 0.9808473143F, 0.9809247574F,
  159026. 0.9810019778F, 0.9810789759F, 0.9811557519F, 0.9812323064F,
  159027. 0.9813086395F, 0.9813847517F, 0.9814606433F, 0.9815363147F,
  159028. 0.9816117662F, 0.9816869981F, 0.9817620108F, 0.9818368047F,
  159029. 0.9819113801F, 0.9819857374F, 0.9820598769F, 0.9821337989F,
  159030. 0.9822075038F, 0.9822809920F, 0.9823542638F, 0.9824273195F,
  159031. 0.9825001596F, 0.9825727843F, 0.9826451940F, 0.9827173891F,
  159032. 0.9827893700F, 0.9828611368F, 0.9829326901F, 0.9830040302F,
  159033. 0.9830751574F, 0.9831460720F, 0.9832167745F, 0.9832872652F,
  159034. 0.9833575444F, 0.9834276124F, 0.9834974697F, 0.9835671166F,
  159035. 0.9836365535F, 0.9837057806F, 0.9837747983F, 0.9838436071F,
  159036. 0.9839122072F, 0.9839805990F, 0.9840487829F, 0.9841167591F,
  159037. 0.9841845282F, 0.9842520903F, 0.9843194459F, 0.9843865953F,
  159038. 0.9844535389F, 0.9845202771F, 0.9845868101F, 0.9846531383F,
  159039. 0.9847192622F, 0.9847851820F, 0.9848508980F, 0.9849164108F,
  159040. 0.9849817205F, 0.9850468276F, 0.9851117324F, 0.9851764352F,
  159041. 0.9852409365F, 0.9853052366F, 0.9853693358F, 0.9854332344F,
  159042. 0.9854969330F, 0.9855604317F, 0.9856237309F, 0.9856868310F,
  159043. 0.9857497325F, 0.9858124355F, 0.9858749404F, 0.9859372477F,
  159044. 0.9859993577F, 0.9860612707F, 0.9861229871F, 0.9861845072F,
  159045. 0.9862458315F, 0.9863069601F, 0.9863678936F, 0.9864286322F,
  159046. 0.9864891764F, 0.9865495264F, 0.9866096826F, 0.9866696454F,
  159047. 0.9867294152F, 0.9867889922F, 0.9868483769F, 0.9869075695F,
  159048. 0.9869665706F, 0.9870253803F, 0.9870839991F, 0.9871424273F,
  159049. 0.9872006653F, 0.9872587135F, 0.9873165721F, 0.9873742415F,
  159050. 0.9874317222F, 0.9874890144F, 0.9875461185F, 0.9876030348F,
  159051. 0.9876597638F, 0.9877163057F, 0.9877726610F, 0.9878288300F,
  159052. 0.9878848130F, 0.9879406104F, 0.9879962225F, 0.9880516497F,
  159053. 0.9881068924F, 0.9881619509F, 0.9882168256F, 0.9882715168F,
  159054. 0.9883260249F, 0.9883803502F, 0.9884344931F, 0.9884884539F,
  159055. 0.9885422331F, 0.9885958309F, 0.9886492477F, 0.9887024838F,
  159056. 0.9887555397F, 0.9888084157F, 0.9888611120F, 0.9889136292F,
  159057. 0.9889659675F, 0.9890181273F, 0.9890701089F, 0.9891219128F,
  159058. 0.9891735392F, 0.9892249885F, 0.9892762610F, 0.9893273572F,
  159059. 0.9893782774F, 0.9894290219F, 0.9894795911F, 0.9895299853F,
  159060. 0.9895802049F, 0.9896302502F, 0.9896801217F, 0.9897298196F,
  159061. 0.9897793443F, 0.9898286961F, 0.9898778755F, 0.9899268828F,
  159062. 0.9899757183F, 0.9900243823F, 0.9900728753F, 0.9901211976F,
  159063. 0.9901693495F, 0.9902173314F, 0.9902651436F, 0.9903127865F,
  159064. 0.9903602605F, 0.9904075659F, 0.9904547031F, 0.9905016723F,
  159065. 0.9905484740F, 0.9905951086F, 0.9906415763F, 0.9906878775F,
  159066. 0.9907340126F, 0.9907799819F, 0.9908257858F, 0.9908714247F,
  159067. 0.9909168988F, 0.9909622086F, 0.9910073543F, 0.9910523364F,
  159068. 0.9910971552F, 0.9911418110F, 0.9911863042F, 0.9912306351F,
  159069. 0.9912748042F, 0.9913188117F, 0.9913626580F, 0.9914063435F,
  159070. 0.9914498684F, 0.9914932333F, 0.9915364383F, 0.9915794839F,
  159071. 0.9916223703F, 0.9916650981F, 0.9917076674F, 0.9917500787F,
  159072. 0.9917923323F, 0.9918344286F, 0.9918763679F, 0.9919181505F,
  159073. 0.9919597769F, 0.9920012473F, 0.9920425621F, 0.9920837217F,
  159074. 0.9921247263F, 0.9921655765F, 0.9922062724F, 0.9922468145F,
  159075. 0.9922872030F, 0.9923274385F, 0.9923675211F, 0.9924074513F,
  159076. 0.9924472294F, 0.9924868557F, 0.9925263306F, 0.9925656544F,
  159077. 0.9926048275F, 0.9926438503F, 0.9926827230F, 0.9927214461F,
  159078. 0.9927600199F, 0.9927984446F, 0.9928367208F, 0.9928748486F,
  159079. 0.9929128285F, 0.9929506608F, 0.9929883459F, 0.9930258841F,
  159080. 0.9930632757F, 0.9931005211F, 0.9931376207F, 0.9931745747F,
  159081. 0.9932113836F, 0.9932480476F, 0.9932845671F, 0.9933209425F,
  159082. 0.9933571742F, 0.9933932623F, 0.9934292074F, 0.9934650097F,
  159083. 0.9935006696F, 0.9935361874F, 0.9935715635F, 0.9936067982F,
  159084. 0.9936418919F, 0.9936768448F, 0.9937116574F, 0.9937463300F,
  159085. 0.9937808629F, 0.9938152565F, 0.9938495111F, 0.9938836271F,
  159086. 0.9939176047F, 0.9939514444F, 0.9939851465F, 0.9940187112F,
  159087. 0.9940521391F, 0.9940854303F, 0.9941185853F, 0.9941516044F,
  159088. 0.9941844879F, 0.9942172361F, 0.9942498495F, 0.9942823283F,
  159089. 0.9943146729F, 0.9943468836F, 0.9943789608F, 0.9944109047F,
  159090. 0.9944427158F, 0.9944743944F, 0.9945059408F, 0.9945373553F,
  159091. 0.9945686384F, 0.9945997902F, 0.9946308112F, 0.9946617017F,
  159092. 0.9946924621F, 0.9947230926F, 0.9947535937F, 0.9947839656F,
  159093. 0.9948142086F, 0.9948443232F, 0.9948743097F, 0.9949041683F,
  159094. 0.9949338995F, 0.9949635035F, 0.9949929807F, 0.9950223315F,
  159095. 0.9950515561F, 0.9950806549F, 0.9951096282F, 0.9951384764F,
  159096. 0.9951671998F, 0.9951957987F, 0.9952242735F, 0.9952526245F,
  159097. 0.9952808520F, 0.9953089564F, 0.9953369380F, 0.9953647971F,
  159098. 0.9953925340F, 0.9954201491F, 0.9954476428F, 0.9954750153F,
  159099. 0.9955022670F, 0.9955293981F, 0.9955564092F, 0.9955833003F,
  159100. 0.9956100720F, 0.9956367245F, 0.9956632582F, 0.9956896733F,
  159101. 0.9957159703F, 0.9957421494F, 0.9957682110F, 0.9957941553F,
  159102. 0.9958199828F, 0.9958456937F, 0.9958712884F, 0.9958967672F,
  159103. 0.9959221305F, 0.9959473784F, 0.9959725115F, 0.9959975300F,
  159104. 0.9960224342F, 0.9960472244F, 0.9960719011F, 0.9960964644F,
  159105. 0.9961209148F, 0.9961452525F, 0.9961694779F, 0.9961935913F,
  159106. 0.9962175930F, 0.9962414834F, 0.9962652627F, 0.9962889313F,
  159107. 0.9963124895F, 0.9963359377F, 0.9963592761F, 0.9963825051F,
  159108. 0.9964056250F, 0.9964286361F, 0.9964515387F, 0.9964743332F,
  159109. 0.9964970198F, 0.9965195990F, 0.9965420709F, 0.9965644360F,
  159110. 0.9965866946F, 0.9966088469F, 0.9966308932F, 0.9966528340F,
  159111. 0.9966746695F, 0.9966964001F, 0.9967180260F, 0.9967395475F,
  159112. 0.9967609651F, 0.9967822789F, 0.9968034894F, 0.9968245968F,
  159113. 0.9968456014F, 0.9968665036F, 0.9968873037F, 0.9969080019F,
  159114. 0.9969285987F, 0.9969490942F, 0.9969694889F, 0.9969897830F,
  159115. 0.9970099769F, 0.9970300708F, 0.9970500651F, 0.9970699601F,
  159116. 0.9970897561F, 0.9971094533F, 0.9971290522F, 0.9971485531F,
  159117. 0.9971679561F, 0.9971872617F, 0.9972064702F, 0.9972255818F,
  159118. 0.9972445968F, 0.9972635157F, 0.9972823386F, 0.9973010659F,
  159119. 0.9973196980F, 0.9973382350F, 0.9973566773F, 0.9973750253F,
  159120. 0.9973932791F, 0.9974114392F, 0.9974295059F, 0.9974474793F,
  159121. 0.9974653599F, 0.9974831480F, 0.9975008438F, 0.9975184476F,
  159122. 0.9975359598F, 0.9975533806F, 0.9975707104F, 0.9975879495F,
  159123. 0.9976050981F, 0.9976221566F, 0.9976391252F, 0.9976560043F,
  159124. 0.9976727941F, 0.9976894950F, 0.9977061073F, 0.9977226312F,
  159125. 0.9977390671F, 0.9977554152F, 0.9977716759F, 0.9977878495F,
  159126. 0.9978039361F, 0.9978199363F, 0.9978358501F, 0.9978516780F,
  159127. 0.9978674202F, 0.9978830771F, 0.9978986488F, 0.9979141358F,
  159128. 0.9979295383F, 0.9979448566F, 0.9979600909F, 0.9979752417F,
  159129. 0.9979903091F, 0.9980052936F, 0.9980201952F, 0.9980350145F,
  159130. 0.9980497515F, 0.9980644067F, 0.9980789804F, 0.9980934727F,
  159131. 0.9981078841F, 0.9981222147F, 0.9981364649F, 0.9981506350F,
  159132. 0.9981647253F, 0.9981787360F, 0.9981926674F, 0.9982065199F,
  159133. 0.9982202936F, 0.9982339890F, 0.9982476062F, 0.9982611456F,
  159134. 0.9982746074F, 0.9982879920F, 0.9983012996F, 0.9983145304F,
  159135. 0.9983276849F, 0.9983407632F, 0.9983537657F, 0.9983666926F,
  159136. 0.9983795442F, 0.9983923208F, 0.9984050226F, 0.9984176501F,
  159137. 0.9984302033F, 0.9984426827F, 0.9984550884F, 0.9984674208F,
  159138. 0.9984796802F, 0.9984918667F, 0.9985039808F, 0.9985160227F,
  159139. 0.9985279926F, 0.9985398909F, 0.9985517177F, 0.9985634734F,
  159140. 0.9985751583F, 0.9985867727F, 0.9985983167F, 0.9986097907F,
  159141. 0.9986211949F, 0.9986325297F, 0.9986437953F, 0.9986549919F,
  159142. 0.9986661199F, 0.9986771795F, 0.9986881710F, 0.9986990946F,
  159143. 0.9987099507F, 0.9987207394F, 0.9987314611F, 0.9987421161F,
  159144. 0.9987527045F, 0.9987632267F, 0.9987736829F, 0.9987840734F,
  159145. 0.9987943985F, 0.9988046584F, 0.9988148534F, 0.9988249838F,
  159146. 0.9988350498F, 0.9988450516F, 0.9988549897F, 0.9988648641F,
  159147. 0.9988746753F, 0.9988844233F, 0.9988941086F, 0.9989037313F,
  159148. 0.9989132918F, 0.9989227902F, 0.9989322269F, 0.9989416021F,
  159149. 0.9989509160F, 0.9989601690F, 0.9989693613F, 0.9989784931F,
  159150. 0.9989875647F, 0.9989965763F, 0.9990055283F, 0.9990144208F,
  159151. 0.9990232541F, 0.9990320286F, 0.9990407443F, 0.9990494016F,
  159152. 0.9990580008F, 0.9990665421F, 0.9990750257F, 0.9990834519F,
  159153. 0.9990918209F, 0.9991001331F, 0.9991083886F, 0.9991165877F,
  159154. 0.9991247307F, 0.9991328177F, 0.9991408491F, 0.9991488251F,
  159155. 0.9991567460F, 0.9991646119F, 0.9991724232F, 0.9991801801F,
  159156. 0.9991878828F, 0.9991955316F, 0.9992031267F, 0.9992106684F,
  159157. 0.9992181569F, 0.9992255925F, 0.9992329753F, 0.9992403057F,
  159158. 0.9992475839F, 0.9992548101F, 0.9992619846F, 0.9992691076F,
  159159. 0.9992761793F, 0.9992832001F, 0.9992901701F, 0.9992970895F,
  159160. 0.9993039587F, 0.9993107777F, 0.9993175470F, 0.9993242667F,
  159161. 0.9993309371F, 0.9993375583F, 0.9993441307F, 0.9993506545F,
  159162. 0.9993571298F, 0.9993635570F, 0.9993699362F, 0.9993762678F,
  159163. 0.9993825519F, 0.9993887887F, 0.9993949785F, 0.9994011216F,
  159164. 0.9994072181F, 0.9994132683F, 0.9994192725F, 0.9994252307F,
  159165. 0.9994311434F, 0.9994370107F, 0.9994428327F, 0.9994486099F,
  159166. 0.9994543423F, 0.9994600303F, 0.9994656739F, 0.9994712736F,
  159167. 0.9994768294F, 0.9994823417F, 0.9994878105F, 0.9994932363F,
  159168. 0.9994986191F, 0.9995039592F, 0.9995092568F, 0.9995145122F,
  159169. 0.9995197256F, 0.9995248971F, 0.9995300270F, 0.9995351156F,
  159170. 0.9995401630F, 0.9995451695F, 0.9995501352F, 0.9995550604F,
  159171. 0.9995599454F, 0.9995647903F, 0.9995695953F, 0.9995743607F,
  159172. 0.9995790866F, 0.9995837734F, 0.9995884211F, 0.9995930300F,
  159173. 0.9995976004F, 0.9996021324F, 0.9996066263F, 0.9996110822F,
  159174. 0.9996155004F, 0.9996198810F, 0.9996242244F, 0.9996285306F,
  159175. 0.9996327999F, 0.9996370326F, 0.9996412287F, 0.9996453886F,
  159176. 0.9996495125F, 0.9996536004F, 0.9996576527F, 0.9996616696F,
  159177. 0.9996656512F, 0.9996695977F, 0.9996735094F, 0.9996773865F,
  159178. 0.9996812291F, 0.9996850374F, 0.9996888118F, 0.9996925523F,
  159179. 0.9996962591F, 0.9996999325F, 0.9997035727F, 0.9997071798F,
  159180. 0.9997107541F, 0.9997142957F, 0.9997178049F, 0.9997212818F,
  159181. 0.9997247266F, 0.9997281396F, 0.9997315209F, 0.9997348708F,
  159182. 0.9997381893F, 0.9997414767F, 0.9997447333F, 0.9997479591F,
  159183. 0.9997511544F, 0.9997543194F, 0.9997574542F, 0.9997605591F,
  159184. 0.9997636342F, 0.9997666797F, 0.9997696958F, 0.9997726828F,
  159185. 0.9997756407F, 0.9997785698F, 0.9997814703F, 0.9997843423F,
  159186. 0.9997871860F, 0.9997900016F, 0.9997927894F, 0.9997955494F,
  159187. 0.9997982818F, 0.9998009869F, 0.9998036648F, 0.9998063157F,
  159188. 0.9998089398F, 0.9998115373F, 0.9998141082F, 0.9998166529F,
  159189. 0.9998191715F, 0.9998216642F, 0.9998241311F, 0.9998265724F,
  159190. 0.9998289884F, 0.9998313790F, 0.9998337447F, 0.9998360854F,
  159191. 0.9998384015F, 0.9998406930F, 0.9998429602F, 0.9998452031F,
  159192. 0.9998474221F, 0.9998496171F, 0.9998517885F, 0.9998539364F,
  159193. 0.9998560610F, 0.9998581624F, 0.9998602407F, 0.9998622962F,
  159194. 0.9998643291F, 0.9998663394F, 0.9998683274F, 0.9998702932F,
  159195. 0.9998722370F, 0.9998741589F, 0.9998760591F, 0.9998779378F,
  159196. 0.9998797952F, 0.9998816313F, 0.9998834464F, 0.9998852406F,
  159197. 0.9998870141F, 0.9998887670F, 0.9998904995F, 0.9998922117F,
  159198. 0.9998939039F, 0.9998955761F, 0.9998972285F, 0.9998988613F,
  159199. 0.9999004746F, 0.9999020686F, 0.9999036434F, 0.9999051992F,
  159200. 0.9999067362F, 0.9999082544F, 0.9999097541F, 0.9999112354F,
  159201. 0.9999126984F, 0.9999141433F, 0.9999155703F, 0.9999169794F,
  159202. 0.9999183709F, 0.9999197449F, 0.9999211014F, 0.9999224408F,
  159203. 0.9999237631F, 0.9999250684F, 0.9999263570F, 0.9999276289F,
  159204. 0.9999288843F, 0.9999301233F, 0.9999313461F, 0.9999325529F,
  159205. 0.9999337437F, 0.9999349187F, 0.9999360780F, 0.9999372218F,
  159206. 0.9999383503F, 0.9999394635F, 0.9999405616F, 0.9999416447F,
  159207. 0.9999427129F, 0.9999437665F, 0.9999448055F, 0.9999458301F,
  159208. 0.9999468404F, 0.9999478365F, 0.9999488185F, 0.9999497867F,
  159209. 0.9999507411F, 0.9999516819F, 0.9999526091F, 0.9999535230F,
  159210. 0.9999544236F, 0.9999553111F, 0.9999561856F, 0.9999570472F,
  159211. 0.9999578960F, 0.9999587323F, 0.9999595560F, 0.9999603674F,
  159212. 0.9999611666F, 0.9999619536F, 0.9999627286F, 0.9999634917F,
  159213. 0.9999642431F, 0.9999649828F, 0.9999657110F, 0.9999664278F,
  159214. 0.9999671334F, 0.9999678278F, 0.9999685111F, 0.9999691835F,
  159215. 0.9999698451F, 0.9999704960F, 0.9999711364F, 0.9999717662F,
  159216. 0.9999723858F, 0.9999729950F, 0.9999735942F, 0.9999741834F,
  159217. 0.9999747626F, 0.9999753321F, 0.9999758919F, 0.9999764421F,
  159218. 0.9999769828F, 0.9999775143F, 0.9999780364F, 0.9999785495F,
  159219. 0.9999790535F, 0.9999795485F, 0.9999800348F, 0.9999805124F,
  159220. 0.9999809813F, 0.9999814417F, 0.9999818938F, 0.9999823375F,
  159221. 0.9999827731F, 0.9999832005F, 0.9999836200F, 0.9999840316F,
  159222. 0.9999844353F, 0.9999848314F, 0.9999852199F, 0.9999856008F,
  159223. 0.9999859744F, 0.9999863407F, 0.9999866997F, 0.9999870516F,
  159224. 0.9999873965F, 0.9999877345F, 0.9999880656F, 0.9999883900F,
  159225. 0.9999887078F, 0.9999890190F, 0.9999893237F, 0.9999896220F,
  159226. 0.9999899140F, 0.9999901999F, 0.9999904796F, 0.9999907533F,
  159227. 0.9999910211F, 0.9999912830F, 0.9999915391F, 0.9999917896F,
  159228. 0.9999920345F, 0.9999922738F, 0.9999925077F, 0.9999927363F,
  159229. 0.9999929596F, 0.9999931777F, 0.9999933907F, 0.9999935987F,
  159230. 0.9999938018F, 0.9999940000F, 0.9999941934F, 0.9999943820F,
  159231. 0.9999945661F, 0.9999947456F, 0.9999949206F, 0.9999950912F,
  159232. 0.9999952575F, 0.9999954195F, 0.9999955773F, 0.9999957311F,
  159233. 0.9999958807F, 0.9999960265F, 0.9999961683F, 0.9999963063F,
  159234. 0.9999964405F, 0.9999965710F, 0.9999966979F, 0.9999968213F,
  159235. 0.9999969412F, 0.9999970576F, 0.9999971707F, 0.9999972805F,
  159236. 0.9999973871F, 0.9999974905F, 0.9999975909F, 0.9999976881F,
  159237. 0.9999977824F, 0.9999978738F, 0.9999979624F, 0.9999980481F,
  159238. 0.9999981311F, 0.9999982115F, 0.9999982892F, 0.9999983644F,
  159239. 0.9999984370F, 0.9999985072F, 0.9999985750F, 0.9999986405F,
  159240. 0.9999987037F, 0.9999987647F, 0.9999988235F, 0.9999988802F,
  159241. 0.9999989348F, 0.9999989873F, 0.9999990379F, 0.9999990866F,
  159242. 0.9999991334F, 0.9999991784F, 0.9999992217F, 0.9999992632F,
  159243. 0.9999993030F, 0.9999993411F, 0.9999993777F, 0.9999994128F,
  159244. 0.9999994463F, 0.9999994784F, 0.9999995091F, 0.9999995384F,
  159245. 0.9999995663F, 0.9999995930F, 0.9999996184F, 0.9999996426F,
  159246. 0.9999996657F, 0.9999996876F, 0.9999997084F, 0.9999997282F,
  159247. 0.9999997469F, 0.9999997647F, 0.9999997815F, 0.9999997973F,
  159248. 0.9999998123F, 0.9999998265F, 0.9999998398F, 0.9999998524F,
  159249. 0.9999998642F, 0.9999998753F, 0.9999998857F, 0.9999998954F,
  159250. 0.9999999045F, 0.9999999130F, 0.9999999209F, 0.9999999282F,
  159251. 0.9999999351F, 0.9999999414F, 0.9999999472F, 0.9999999526F,
  159252. 0.9999999576F, 0.9999999622F, 0.9999999664F, 0.9999999702F,
  159253. 0.9999999737F, 0.9999999769F, 0.9999999798F, 0.9999999824F,
  159254. 0.9999999847F, 0.9999999868F, 0.9999999887F, 0.9999999904F,
  159255. 0.9999999919F, 0.9999999932F, 0.9999999943F, 0.9999999953F,
  159256. 0.9999999961F, 0.9999999969F, 0.9999999975F, 0.9999999980F,
  159257. 0.9999999985F, 0.9999999988F, 0.9999999991F, 0.9999999993F,
  159258. 0.9999999995F, 0.9999999997F, 0.9999999998F, 0.9999999999F,
  159259. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  159260. 1.0000000000F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  159261. };
  159262. static float *vwin[8] = {
  159263. vwin64,
  159264. vwin128,
  159265. vwin256,
  159266. vwin512,
  159267. vwin1024,
  159268. vwin2048,
  159269. vwin4096,
  159270. vwin8192,
  159271. };
  159272. float *_vorbis_window_get(int n){
  159273. return vwin[n];
  159274. }
  159275. void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  159276. int lW,int W,int nW){
  159277. lW=(W?lW:0);
  159278. nW=(W?nW:0);
  159279. {
  159280. float *windowLW=vwin[winno[lW]];
  159281. float *windowNW=vwin[winno[nW]];
  159282. long n=blocksizes[W];
  159283. long ln=blocksizes[lW];
  159284. long rn=blocksizes[nW];
  159285. long leftbegin=n/4-ln/4;
  159286. long leftend=leftbegin+ln/2;
  159287. long rightbegin=n/2+n/4-rn/4;
  159288. long rightend=rightbegin+rn/2;
  159289. int i,p;
  159290. for(i=0;i<leftbegin;i++)
  159291. d[i]=0.f;
  159292. for(p=0;i<leftend;i++,p++)
  159293. d[i]*=windowLW[p];
  159294. for(i=rightbegin,p=rn/2-1;i<rightend;i++,p--)
  159295. d[i]*=windowNW[p];
  159296. for(;i<n;i++)
  159297. d[i]=0.f;
  159298. }
  159299. }
  159300. #endif
  159301. /*** End of inlined file: window.c ***/
  159302. #else
  159303. #include <vorbis/vorbisenc.h>
  159304. #include <vorbis/codec.h>
  159305. #include <vorbis/vorbisfile.h>
  159306. #endif
  159307. }
  159308. #undef max
  159309. #undef min
  159310. BEGIN_JUCE_NAMESPACE
  159311. static const char* const oggFormatName = "Ogg-Vorbis file";
  159312. static const char* const oggExtensions[] = { ".ogg", 0 };
  159313. class OggReader : public AudioFormatReader
  159314. {
  159315. OggVorbisNamespace::OggVorbis_File ovFile;
  159316. OggVorbisNamespace::ov_callbacks callbacks;
  159317. AudioSampleBuffer reservoir;
  159318. int reservoirStart, samplesInReservoir;
  159319. public:
  159320. OggReader (InputStream* const inp)
  159321. : AudioFormatReader (inp, TRANS (oggFormatName)),
  159322. reservoir (2, 4096),
  159323. reservoirStart (0),
  159324. samplesInReservoir (0)
  159325. {
  159326. using namespace OggVorbisNamespace;
  159327. sampleRate = 0;
  159328. usesFloatingPointData = true;
  159329. callbacks.read_func = &oggReadCallback;
  159330. callbacks.seek_func = &oggSeekCallback;
  159331. callbacks.close_func = &oggCloseCallback;
  159332. callbacks.tell_func = &oggTellCallback;
  159333. const int err = ov_open_callbacks (input, &ovFile, 0, 0, callbacks);
  159334. if (err == 0)
  159335. {
  159336. vorbis_info* info = ov_info (&ovFile, -1);
  159337. lengthInSamples = (uint32) ov_pcm_total (&ovFile, -1);
  159338. numChannels = info->channels;
  159339. bitsPerSample = 16;
  159340. sampleRate = info->rate;
  159341. reservoir.setSize (numChannels,
  159342. (int) jmin (lengthInSamples, (int64) reservoir.getNumSamples()));
  159343. }
  159344. }
  159345. ~OggReader()
  159346. {
  159347. OggVorbisNamespace::ov_clear (&ovFile);
  159348. }
  159349. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  159350. int64 startSampleInFile, int numSamples)
  159351. {
  159352. while (numSamples > 0)
  159353. {
  159354. const int numAvailable = reservoirStart + samplesInReservoir - startSampleInFile;
  159355. if (startSampleInFile >= reservoirStart && numAvailable > 0)
  159356. {
  159357. // got a few samples overlapping, so use them before seeking..
  159358. const int numToUse = jmin (numSamples, numAvailable);
  159359. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  159360. if (destSamples[i] != 0)
  159361. memcpy (destSamples[i] + startOffsetInDestBuffer,
  159362. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  159363. sizeof (float) * numToUse);
  159364. startSampleInFile += numToUse;
  159365. numSamples -= numToUse;
  159366. startOffsetInDestBuffer += numToUse;
  159367. if (numSamples == 0)
  159368. break;
  159369. }
  159370. if (startSampleInFile < reservoirStart
  159371. || startSampleInFile + numSamples > reservoirStart + samplesInReservoir)
  159372. {
  159373. // buffer miss, so refill the reservoir
  159374. int bitStream = 0;
  159375. reservoirStart = jmax (0, (int) startSampleInFile);
  159376. samplesInReservoir = reservoir.getNumSamples();
  159377. if (reservoirStart != (int) OggVorbisNamespace::ov_pcm_tell (&ovFile))
  159378. OggVorbisNamespace::ov_pcm_seek (&ovFile, reservoirStart);
  159379. int offset = 0;
  159380. int numToRead = samplesInReservoir;
  159381. while (numToRead > 0)
  159382. {
  159383. float** dataIn = 0;
  159384. const int samps = OggVorbisNamespace::ov_read_float (&ovFile, &dataIn, numToRead, &bitStream);
  159385. if (samps <= 0)
  159386. break;
  159387. jassert (samps <= numToRead);
  159388. for (int i = jmin ((int) numChannels, reservoir.getNumChannels()); --i >= 0;)
  159389. {
  159390. memcpy (reservoir.getSampleData (i, offset),
  159391. dataIn[i],
  159392. sizeof (float) * samps);
  159393. }
  159394. numToRead -= samps;
  159395. offset += samps;
  159396. }
  159397. if (numToRead > 0)
  159398. reservoir.clear (offset, numToRead);
  159399. }
  159400. }
  159401. if (numSamples > 0)
  159402. {
  159403. for (int i = numDestChannels; --i >= 0;)
  159404. if (destSamples[i] != 0)
  159405. zeromem (destSamples[i] + startOffsetInDestBuffer,
  159406. sizeof (int) * numSamples);
  159407. }
  159408. return true;
  159409. }
  159410. static size_t oggReadCallback (void* ptr, size_t size, size_t nmemb, void* datasource)
  159411. {
  159412. return (size_t) (static_cast <InputStream*> (datasource)->read (ptr, (int) (size * nmemb)) / size);
  159413. }
  159414. static int oggSeekCallback (void* datasource, OggVorbisNamespace::ogg_int64_t offset, int whence)
  159415. {
  159416. InputStream* const in = static_cast <InputStream*> (datasource);
  159417. if (whence == SEEK_CUR)
  159418. offset += in->getPosition();
  159419. else if (whence == SEEK_END)
  159420. offset += in->getTotalLength();
  159421. in->setPosition (offset);
  159422. return 0;
  159423. }
  159424. static int oggCloseCallback (void*)
  159425. {
  159426. return 0;
  159427. }
  159428. static long oggTellCallback (void* datasource)
  159429. {
  159430. return (long) static_cast <InputStream*> (datasource)->getPosition();
  159431. }
  159432. juce_UseDebuggingNewOperator
  159433. };
  159434. class OggWriter : public AudioFormatWriter
  159435. {
  159436. OggVorbisNamespace::ogg_stream_state os;
  159437. OggVorbisNamespace::ogg_page og;
  159438. OggVorbisNamespace::ogg_packet op;
  159439. OggVorbisNamespace::vorbis_info vi;
  159440. OggVorbisNamespace::vorbis_comment vc;
  159441. OggVorbisNamespace::vorbis_dsp_state vd;
  159442. OggVorbisNamespace::vorbis_block vb;
  159443. public:
  159444. bool ok;
  159445. OggWriter (OutputStream* const out,
  159446. const double sampleRate,
  159447. const int numChannels,
  159448. const int bitsPerSample,
  159449. const int qualityIndex)
  159450. : AudioFormatWriter (out, TRANS (oggFormatName),
  159451. sampleRate,
  159452. numChannels,
  159453. bitsPerSample)
  159454. {
  159455. using namespace OggVorbisNamespace;
  159456. ok = false;
  159457. vorbis_info_init (&vi);
  159458. if (vorbis_encode_init_vbr (&vi,
  159459. numChannels,
  159460. (int) sampleRate,
  159461. jlimit (0.0f, 1.0f, qualityIndex * 0.5f)) == 0)
  159462. {
  159463. vorbis_comment_init (&vc);
  159464. if (JUCEApplication::getInstance() != 0)
  159465. vorbis_comment_add_tag (&vc, "ENCODER", const_cast <char*> (JUCEApplication::getInstance()->getApplicationName().toUTF8()));
  159466. vorbis_analysis_init (&vd, &vi);
  159467. vorbis_block_init (&vd, &vb);
  159468. ogg_stream_init (&os, Random::getSystemRandom().nextInt());
  159469. ogg_packet header;
  159470. ogg_packet header_comm;
  159471. ogg_packet header_code;
  159472. vorbis_analysis_headerout (&vd, &vc, &header, &header_comm, &header_code);
  159473. ogg_stream_packetin (&os, &header);
  159474. ogg_stream_packetin (&os, &header_comm);
  159475. ogg_stream_packetin (&os, &header_code);
  159476. for (;;)
  159477. {
  159478. if (ogg_stream_flush (&os, &og) == 0)
  159479. break;
  159480. output->write (og.header, og.header_len);
  159481. output->write (og.body, og.body_len);
  159482. }
  159483. ok = true;
  159484. }
  159485. }
  159486. ~OggWriter()
  159487. {
  159488. using namespace OggVorbisNamespace;
  159489. if (ok)
  159490. {
  159491. // write a zero-length packet to show ogg that we're finished..
  159492. write (0, 0);
  159493. ogg_stream_clear (&os);
  159494. vorbis_block_clear (&vb);
  159495. vorbis_dsp_clear (&vd);
  159496. vorbis_comment_clear (&vc);
  159497. vorbis_info_clear (&vi);
  159498. output->flush();
  159499. }
  159500. else
  159501. {
  159502. vorbis_info_clear (&vi);
  159503. output = 0; // to stop the base class deleting this, as it needs to be returned
  159504. // to the caller of createWriter()
  159505. }
  159506. }
  159507. bool write (const int** samplesToWrite, int numSamples)
  159508. {
  159509. using namespace OggVorbisNamespace;
  159510. if (! ok)
  159511. return false;
  159512. if (numSamples > 0)
  159513. {
  159514. const double gain = 1.0 / 0x80000000u;
  159515. float** const vorbisBuffer = vorbis_analysis_buffer (&vd, numSamples);
  159516. for (int i = numChannels; --i >= 0;)
  159517. {
  159518. float* const dst = vorbisBuffer[i];
  159519. const int* const src = samplesToWrite [i];
  159520. if (src != 0 && dst != 0)
  159521. {
  159522. for (int j = 0; j < numSamples; ++j)
  159523. dst[j] = (float) (src[j] * gain);
  159524. }
  159525. }
  159526. }
  159527. vorbis_analysis_wrote (&vd, numSamples);
  159528. while (vorbis_analysis_blockout (&vd, &vb) == 1)
  159529. {
  159530. vorbis_analysis (&vb, 0);
  159531. vorbis_bitrate_addblock (&vb);
  159532. while (vorbis_bitrate_flushpacket (&vd, &op))
  159533. {
  159534. ogg_stream_packetin (&os, &op);
  159535. for (;;)
  159536. {
  159537. if (ogg_stream_pageout (&os, &og) == 0)
  159538. break;
  159539. output->write (og.header, og.header_len);
  159540. output->write (og.body, og.body_len);
  159541. if (ogg_page_eos (&og))
  159542. break;
  159543. }
  159544. }
  159545. }
  159546. return true;
  159547. }
  159548. juce_UseDebuggingNewOperator
  159549. };
  159550. OggVorbisAudioFormat::OggVorbisAudioFormat()
  159551. : AudioFormat (TRANS (oggFormatName), StringArray (oggExtensions))
  159552. {
  159553. }
  159554. OggVorbisAudioFormat::~OggVorbisAudioFormat()
  159555. {
  159556. }
  159557. const Array <int> OggVorbisAudioFormat::getPossibleSampleRates()
  159558. {
  159559. const int rates[] = { 22050, 32000, 44100, 48000, 0 };
  159560. return Array <int> (rates);
  159561. }
  159562. const Array <int> OggVorbisAudioFormat::getPossibleBitDepths()
  159563. {
  159564. const int depths[] = { 32, 0 };
  159565. return Array <int> (depths);
  159566. }
  159567. bool OggVorbisAudioFormat::canDoStereo() { return true; }
  159568. bool OggVorbisAudioFormat::canDoMono() { return true; }
  159569. bool OggVorbisAudioFormat::isCompressed() { return true; }
  159570. AudioFormatReader* OggVorbisAudioFormat::createReaderFor (InputStream* in,
  159571. const bool deleteStreamIfOpeningFails)
  159572. {
  159573. ScopedPointer <OggReader> r (new OggReader (in));
  159574. if (r->sampleRate != 0)
  159575. return r.release();
  159576. if (! deleteStreamIfOpeningFails)
  159577. r->input = 0;
  159578. return 0;
  159579. }
  159580. AudioFormatWriter* OggVorbisAudioFormat::createWriterFor (OutputStream* out,
  159581. double sampleRate,
  159582. unsigned int numChannels,
  159583. int bitsPerSample,
  159584. const StringPairArray& /*metadataValues*/,
  159585. int qualityOptionIndex)
  159586. {
  159587. ScopedPointer <OggWriter> w (new OggWriter (out,
  159588. sampleRate,
  159589. numChannels,
  159590. bitsPerSample,
  159591. qualityOptionIndex));
  159592. return w->ok ? w.release() : 0;
  159593. }
  159594. const StringArray OggVorbisAudioFormat::getQualityOptions()
  159595. {
  159596. StringArray s;
  159597. s.add ("Low Quality");
  159598. s.add ("Medium Quality");
  159599. s.add ("High Quality");
  159600. return s;
  159601. }
  159602. int OggVorbisAudioFormat::estimateOggFileQuality (const File& source)
  159603. {
  159604. FileInputStream* const in = source.createInputStream();
  159605. if (in != 0)
  159606. {
  159607. ScopedPointer <AudioFormatReader> r (createReaderFor (in, true));
  159608. if (r != 0)
  159609. {
  159610. const int64 numSamps = r->lengthInSamples;
  159611. r = 0;
  159612. const int64 fileNumSamps = source.getSize() / 4;
  159613. const double ratio = numSamps / (double) fileNumSamps;
  159614. if (ratio > 12.0)
  159615. return 0;
  159616. else if (ratio > 6.0)
  159617. return 1;
  159618. else
  159619. return 2;
  159620. }
  159621. }
  159622. return 1;
  159623. }
  159624. END_JUCE_NAMESPACE
  159625. #endif
  159626. /*** End of inlined file: juce_OggVorbisAudioFormat.cpp ***/
  159627. #endif
  159628. #if JUCE_BUILD_CORE && ! JUCE_ONLY_BUILD_CORE_LIBRARY // do these in the core section to help balance the sizes
  159629. /*** Start of inlined file: juce_JPEGLoader.cpp ***/
  159630. #if JUCE_MSVC
  159631. #pragma warning (push)
  159632. #endif
  159633. namespace jpeglibNamespace
  159634. {
  159635. #if JUCE_INCLUDE_JPEGLIB_CODE
  159636. #if JUCE_MINGW
  159637. typedef unsigned char boolean;
  159638. #endif
  159639. #define JPEG_INTERNALS
  159640. #undef FAR
  159641. /*** Start of inlined file: jpeglib.h ***/
  159642. #ifndef JPEGLIB_H
  159643. #define JPEGLIB_H
  159644. /*
  159645. * First we include the configuration files that record how this
  159646. * installation of the JPEG library is set up. jconfig.h can be
  159647. * generated automatically for many systems. jmorecfg.h contains
  159648. * manual configuration options that most people need not worry about.
  159649. */
  159650. #ifndef JCONFIG_INCLUDED /* in case jinclude.h already did */
  159651. /*** Start of inlined file: jconfig.h ***/
  159652. /* see jconfig.doc for explanations */
  159653. // disable all the warnings under MSVC
  159654. #ifdef _MSC_VER
  159655. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  159656. #endif
  159657. #ifdef __BORLANDC__
  159658. #pragma warn -8057
  159659. #pragma warn -8019
  159660. #pragma warn -8004
  159661. #pragma warn -8008
  159662. #endif
  159663. #define HAVE_PROTOTYPES
  159664. #define HAVE_UNSIGNED_CHAR
  159665. #define HAVE_UNSIGNED_SHORT
  159666. /* #define void char */
  159667. /* #define const */
  159668. #undef CHAR_IS_UNSIGNED
  159669. #define HAVE_STDDEF_H
  159670. #define HAVE_STDLIB_H
  159671. #undef NEED_BSD_STRINGS
  159672. #undef NEED_SYS_TYPES_H
  159673. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  159674. #undef NEED_SHORT_EXTERNAL_NAMES
  159675. #undef INCOMPLETE_TYPES_BROKEN
  159676. /* Define "boolean" as unsigned char, not int, per Windows custom */
  159677. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  159678. typedef unsigned char boolean;
  159679. #endif
  159680. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  159681. #ifdef JPEG_INTERNALS
  159682. #undef RIGHT_SHIFT_IS_UNSIGNED
  159683. #endif /* JPEG_INTERNALS */
  159684. #ifdef JPEG_CJPEG_DJPEG
  159685. #define BMP_SUPPORTED /* BMP image file format */
  159686. #define GIF_SUPPORTED /* GIF image file format */
  159687. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  159688. #undef RLE_SUPPORTED /* Utah RLE image file format */
  159689. #define TARGA_SUPPORTED /* Targa image file format */
  159690. #define TWO_FILE_COMMANDLINE /* optional */
  159691. #define USE_SETMODE /* Microsoft has setmode() */
  159692. #undef NEED_SIGNAL_CATCHER
  159693. #undef DONT_USE_B_MODE
  159694. #undef PROGRESS_REPORT /* optional */
  159695. #endif /* JPEG_CJPEG_DJPEG */
  159696. /*** End of inlined file: jconfig.h ***/
  159697. /* widely used configuration options */
  159698. #endif
  159699. /*** Start of inlined file: jmorecfg.h ***/
  159700. /*
  159701. * Define BITS_IN_JSAMPLE as either
  159702. * 8 for 8-bit sample values (the usual setting)
  159703. * 12 for 12-bit sample values
  159704. * Only 8 and 12 are legal data precisions for lossy JPEG according to the
  159705. * JPEG standard, and the IJG code does not support anything else!
  159706. * We do not support run-time selection of data precision, sorry.
  159707. */
  159708. #define BITS_IN_JSAMPLE 8 /* use 8 or 12 */
  159709. /*
  159710. * Maximum number of components (color channels) allowed in JPEG image.
  159711. * To meet the letter of the JPEG spec, set this to 255. However, darn
  159712. * few applications need more than 4 channels (maybe 5 for CMYK + alpha
  159713. * mask). We recommend 10 as a reasonable compromise; use 4 if you are
  159714. * really short on memory. (Each allowed component costs a hundred or so
  159715. * bytes of storage, whether actually used in an image or not.)
  159716. */
  159717. #define MAX_COMPONENTS 10 /* maximum number of image components */
  159718. /*
  159719. * Basic data types.
  159720. * You may need to change these if you have a machine with unusual data
  159721. * type sizes; for example, "char" not 8 bits, "short" not 16 bits,
  159722. * or "long" not 32 bits. We don't care whether "int" is 16 or 32 bits,
  159723. * but it had better be at least 16.
  159724. */
  159725. /* Representation of a single sample (pixel element value).
  159726. * We frequently allocate large arrays of these, so it's important to keep
  159727. * them small. But if you have memory to burn and access to char or short
  159728. * arrays is very slow on your hardware, you might want to change these.
  159729. */
  159730. #if BITS_IN_JSAMPLE == 8
  159731. /* JSAMPLE should be the smallest type that will hold the values 0..255.
  159732. * You can use a signed char by having GETJSAMPLE mask it with 0xFF.
  159733. */
  159734. #ifdef HAVE_UNSIGNED_CHAR
  159735. typedef unsigned char JSAMPLE;
  159736. #define GETJSAMPLE(value) ((int) (value))
  159737. #else /* not HAVE_UNSIGNED_CHAR */
  159738. typedef char JSAMPLE;
  159739. #ifdef CHAR_IS_UNSIGNED
  159740. #define GETJSAMPLE(value) ((int) (value))
  159741. #else
  159742. #define GETJSAMPLE(value) ((int) (value) & 0xFF)
  159743. #endif /* CHAR_IS_UNSIGNED */
  159744. #endif /* HAVE_UNSIGNED_CHAR */
  159745. #define MAXJSAMPLE 255
  159746. #define CENTERJSAMPLE 128
  159747. #endif /* BITS_IN_JSAMPLE == 8 */
  159748. #if BITS_IN_JSAMPLE == 12
  159749. /* JSAMPLE should be the smallest type that will hold the values 0..4095.
  159750. * On nearly all machines "short" will do nicely.
  159751. */
  159752. typedef short JSAMPLE;
  159753. #define GETJSAMPLE(value) ((int) (value))
  159754. #define MAXJSAMPLE 4095
  159755. #define CENTERJSAMPLE 2048
  159756. #endif /* BITS_IN_JSAMPLE == 12 */
  159757. /* Representation of a DCT frequency coefficient.
  159758. * This should be a signed value of at least 16 bits; "short" is usually OK.
  159759. * Again, we allocate large arrays of these, but you can change to int
  159760. * if you have memory to burn and "short" is really slow.
  159761. */
  159762. typedef short JCOEF;
  159763. /* Compressed datastreams are represented as arrays of JOCTET.
  159764. * These must be EXACTLY 8 bits wide, at least once they are written to
  159765. * external storage. Note that when using the stdio data source/destination
  159766. * managers, this is also the data type passed to fread/fwrite.
  159767. */
  159768. #ifdef HAVE_UNSIGNED_CHAR
  159769. typedef unsigned char JOCTET;
  159770. #define GETJOCTET(value) (value)
  159771. #else /* not HAVE_UNSIGNED_CHAR */
  159772. typedef char JOCTET;
  159773. #ifdef CHAR_IS_UNSIGNED
  159774. #define GETJOCTET(value) (value)
  159775. #else
  159776. #define GETJOCTET(value) ((value) & 0xFF)
  159777. #endif /* CHAR_IS_UNSIGNED */
  159778. #endif /* HAVE_UNSIGNED_CHAR */
  159779. /* These typedefs are used for various table entries and so forth.
  159780. * They must be at least as wide as specified; but making them too big
  159781. * won't cost a huge amount of memory, so we don't provide special
  159782. * extraction code like we did for JSAMPLE. (In other words, these
  159783. * typedefs live at a different point on the speed/space tradeoff curve.)
  159784. */
  159785. /* UINT8 must hold at least the values 0..255. */
  159786. #ifdef HAVE_UNSIGNED_CHAR
  159787. typedef unsigned char UINT8;
  159788. #else /* not HAVE_UNSIGNED_CHAR */
  159789. #ifdef CHAR_IS_UNSIGNED
  159790. typedef char UINT8;
  159791. #else /* not CHAR_IS_UNSIGNED */
  159792. typedef short UINT8;
  159793. #endif /* CHAR_IS_UNSIGNED */
  159794. #endif /* HAVE_UNSIGNED_CHAR */
  159795. /* UINT16 must hold at least the values 0..65535. */
  159796. #ifdef HAVE_UNSIGNED_SHORT
  159797. typedef unsigned short UINT16;
  159798. #else /* not HAVE_UNSIGNED_SHORT */
  159799. typedef unsigned int UINT16;
  159800. #endif /* HAVE_UNSIGNED_SHORT */
  159801. /* INT16 must hold at least the values -32768..32767. */
  159802. #ifndef XMD_H /* X11/xmd.h correctly defines INT16 */
  159803. typedef short INT16;
  159804. #endif
  159805. /* INT32 must hold at least signed 32-bit values. */
  159806. #ifndef XMD_H /* X11/xmd.h correctly defines INT32 */
  159807. typedef long INT32;
  159808. #endif
  159809. /* Datatype used for image dimensions. The JPEG standard only supports
  159810. * images up to 64K*64K due to 16-bit fields in SOF markers. Therefore
  159811. * "unsigned int" is sufficient on all machines. However, if you need to
  159812. * handle larger images and you don't mind deviating from the spec, you
  159813. * can change this datatype.
  159814. */
  159815. typedef unsigned int JDIMENSION;
  159816. #define JPEG_MAX_DIMENSION 65500L /* a tad under 64K to prevent overflows */
  159817. /* These macros are used in all function definitions and extern declarations.
  159818. * You could modify them if you need to change function linkage conventions;
  159819. * in particular, you'll need to do that to make the library a Windows DLL.
  159820. * Another application is to make all functions global for use with debuggers
  159821. * or code profilers that require it.
  159822. */
  159823. /* a function called through method pointers: */
  159824. #define METHODDEF(type) static type
  159825. /* a function used only in its module: */
  159826. #define LOCAL(type) static type
  159827. /* a function referenced thru EXTERNs: */
  159828. #define GLOBAL(type) type
  159829. /* a reference to a GLOBAL function: */
  159830. #define EXTERN(type) extern type
  159831. /* This macro is used to declare a "method", that is, a function pointer.
  159832. * We want to supply prototype parameters if the compiler can cope.
  159833. * Note that the arglist parameter must be parenthesized!
  159834. * Again, you can customize this if you need special linkage keywords.
  159835. */
  159836. #ifdef HAVE_PROTOTYPES
  159837. #define JMETHOD(type,methodname,arglist) type (*methodname) arglist
  159838. #else
  159839. #define JMETHOD(type,methodname,arglist) type (*methodname) ()
  159840. #endif
  159841. /* Here is the pseudo-keyword for declaring pointers that must be "far"
  159842. * on 80x86 machines. Most of the specialized coding for 80x86 is handled
  159843. * by just saying "FAR *" where such a pointer is needed. In a few places
  159844. * explicit coding is needed; see uses of the NEED_FAR_POINTERS symbol.
  159845. */
  159846. #ifdef NEED_FAR_POINTERS
  159847. #define FAR far
  159848. #else
  159849. #define FAR
  159850. #endif
  159851. /*
  159852. * On a few systems, type boolean and/or its values FALSE, TRUE may appear
  159853. * in standard header files. Or you may have conflicts with application-
  159854. * specific header files that you want to include together with these files.
  159855. * Defining HAVE_BOOLEAN before including jpeglib.h should make it work.
  159856. */
  159857. #ifndef HAVE_BOOLEAN
  159858. typedef int boolean;
  159859. #endif
  159860. #ifndef FALSE /* in case these macros already exist */
  159861. #define FALSE 0 /* values of boolean */
  159862. #endif
  159863. #ifndef TRUE
  159864. #define TRUE 1
  159865. #endif
  159866. /*
  159867. * The remaining options affect code selection within the JPEG library,
  159868. * but they don't need to be visible to most applications using the library.
  159869. * To minimize application namespace pollution, the symbols won't be
  159870. * defined unless JPEG_INTERNALS or JPEG_INTERNAL_OPTIONS has been defined.
  159871. */
  159872. #ifdef JPEG_INTERNALS
  159873. #define JPEG_INTERNAL_OPTIONS
  159874. #endif
  159875. #ifdef JPEG_INTERNAL_OPTIONS
  159876. /*
  159877. * These defines indicate whether to include various optional functions.
  159878. * Undefining some of these symbols will produce a smaller but less capable
  159879. * library. Note that you can leave certain source files out of the
  159880. * compilation/linking process if you've #undef'd the corresponding symbols.
  159881. * (You may HAVE to do that if your compiler doesn't like null source files.)
  159882. */
  159883. /* Arithmetic coding is unsupported for legal reasons. Complaints to IBM. */
  159884. /* Capability options common to encoder and decoder: */
  159885. #define DCT_ISLOW_SUPPORTED /* slow but accurate integer algorithm */
  159886. #define DCT_IFAST_SUPPORTED /* faster, less accurate integer method */
  159887. #define DCT_FLOAT_SUPPORTED /* floating-point: accurate, fast on fast HW */
  159888. /* Encoder capability options: */
  159889. #undef C_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  159890. #define C_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  159891. #define C_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  159892. #define ENTROPY_OPT_SUPPORTED /* Optimization of entropy coding parms? */
  159893. /* Note: if you selected 12-bit data precision, it is dangerous to turn off
  159894. * ENTROPY_OPT_SUPPORTED. The standard Huffman tables are only good for 8-bit
  159895. * precision, so jchuff.c normally uses entropy optimization to compute
  159896. * usable tables for higher precision. If you don't want to do optimization,
  159897. * you'll have to supply different default Huffman tables.
  159898. * The exact same statements apply for progressive JPEG: the default tables
  159899. * don't work for progressive mode. (This may get fixed, however.)
  159900. */
  159901. #define INPUT_SMOOTHING_SUPPORTED /* Input image smoothing option? */
  159902. /* Decoder capability options: */
  159903. #undef D_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  159904. #define D_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  159905. #define D_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  159906. #define SAVE_MARKERS_SUPPORTED /* jpeg_save_markers() needed? */
  159907. #define BLOCK_SMOOTHING_SUPPORTED /* Block smoothing? (Progressive only) */
  159908. #define IDCT_SCALING_SUPPORTED /* Output rescaling via IDCT? */
  159909. #undef UPSAMPLE_SCALING_SUPPORTED /* Output rescaling at upsample stage? */
  159910. #define UPSAMPLE_MERGING_SUPPORTED /* Fast path for sloppy upsampling? */
  159911. #define QUANT_1PASS_SUPPORTED /* 1-pass color quantization? */
  159912. #define QUANT_2PASS_SUPPORTED /* 2-pass color quantization? */
  159913. /* more capability options later, no doubt */
  159914. /*
  159915. * Ordering of RGB data in scanlines passed to or from the application.
  159916. * If your application wants to deal with data in the order B,G,R, just
  159917. * change these macros. You can also deal with formats such as R,G,B,X
  159918. * (one extra byte per pixel) by changing RGB_PIXELSIZE. Note that changing
  159919. * the offsets will also change the order in which colormap data is organized.
  159920. * RESTRICTIONS:
  159921. * 1. The sample applications cjpeg,djpeg do NOT support modified RGB formats.
  159922. * 2. These macros only affect RGB<=>YCbCr color conversion, so they are not
  159923. * useful if you are using JPEG color spaces other than YCbCr or grayscale.
  159924. * 3. The color quantizer modules will not behave desirably if RGB_PIXELSIZE
  159925. * is not 3 (they don't understand about dummy color components!). So you
  159926. * can't use color quantization if you change that value.
  159927. */
  159928. #define RGB_RED 0 /* Offset of Red in an RGB scanline element */
  159929. #define RGB_GREEN 1 /* Offset of Green */
  159930. #define RGB_BLUE 2 /* Offset of Blue */
  159931. #define RGB_PIXELSIZE 3 /* JSAMPLEs per RGB scanline element */
  159932. /* Definitions for speed-related optimizations. */
  159933. /* If your compiler supports inline functions, define INLINE
  159934. * as the inline keyword; otherwise define it as empty.
  159935. */
  159936. #ifndef INLINE
  159937. #ifdef __GNUC__ /* for instance, GNU C knows about inline */
  159938. #define INLINE __inline__
  159939. #endif
  159940. #ifndef INLINE
  159941. #define INLINE /* default is to define it as empty */
  159942. #endif
  159943. #endif
  159944. /* On some machines (notably 68000 series) "int" is 32 bits, but multiplying
  159945. * two 16-bit shorts is faster than multiplying two ints. Define MULTIPLIER
  159946. * as short on such a machine. MULTIPLIER must be at least 16 bits wide.
  159947. */
  159948. #ifndef MULTIPLIER
  159949. #define MULTIPLIER int /* type for fastest integer multiply */
  159950. #endif
  159951. /* FAST_FLOAT should be either float or double, whichever is done faster
  159952. * by your compiler. (Note that this type is only used in the floating point
  159953. * DCT routines, so it only matters if you've defined DCT_FLOAT_SUPPORTED.)
  159954. * Typically, float is faster in ANSI C compilers, while double is faster in
  159955. * pre-ANSI compilers (because they insist on converting to double anyway).
  159956. * The code below therefore chooses float if we have ANSI-style prototypes.
  159957. */
  159958. #ifndef FAST_FLOAT
  159959. #ifdef HAVE_PROTOTYPES
  159960. #define FAST_FLOAT float
  159961. #else
  159962. #define FAST_FLOAT double
  159963. #endif
  159964. #endif
  159965. #endif /* JPEG_INTERNAL_OPTIONS */
  159966. /*** End of inlined file: jmorecfg.h ***/
  159967. /* seldom changed options */
  159968. /* Version ID for the JPEG library.
  159969. * Might be useful for tests like "#if JPEG_LIB_VERSION >= 60".
  159970. */
  159971. #define JPEG_LIB_VERSION 62 /* Version 6b */
  159972. /* Various constants determining the sizes of things.
  159973. * All of these are specified by the JPEG standard, so don't change them
  159974. * if you want to be compatible.
  159975. */
  159976. #define DCTSIZE 8 /* The basic DCT block is 8x8 samples */
  159977. #define DCTSIZE2 64 /* DCTSIZE squared; # of elements in a block */
  159978. #define NUM_QUANT_TBLS 4 /* Quantization tables are numbered 0..3 */
  159979. #define NUM_HUFF_TBLS 4 /* Huffman tables are numbered 0..3 */
  159980. #define NUM_ARITH_TBLS 16 /* Arith-coding tables are numbered 0..15 */
  159981. #define MAX_COMPS_IN_SCAN 4 /* JPEG limit on # of components in one scan */
  159982. #define MAX_SAMP_FACTOR 4 /* JPEG limit on sampling factors */
  159983. /* Unfortunately, some bozo at Adobe saw no reason to be bound by the standard;
  159984. * the PostScript DCT filter can emit files with many more than 10 blocks/MCU.
  159985. * If you happen to run across such a file, you can up D_MAX_BLOCKS_IN_MCU
  159986. * to handle it. We even let you do this from the jconfig.h file. However,
  159987. * we strongly discourage changing C_MAX_BLOCKS_IN_MCU; just because Adobe
  159988. * sometimes emits noncompliant files doesn't mean you should too.
  159989. */
  159990. #define C_MAX_BLOCKS_IN_MCU 10 /* compressor's limit on blocks per MCU */
  159991. #ifndef D_MAX_BLOCKS_IN_MCU
  159992. #define D_MAX_BLOCKS_IN_MCU 10 /* decompressor's limit on blocks per MCU */
  159993. #endif
  159994. /* Data structures for images (arrays of samples and of DCT coefficients).
  159995. * On 80x86 machines, the image arrays are too big for near pointers,
  159996. * but the pointer arrays can fit in near memory.
  159997. */
  159998. typedef JSAMPLE FAR *JSAMPROW; /* ptr to one image row of pixel samples. */
  159999. typedef JSAMPROW *JSAMPARRAY; /* ptr to some rows (a 2-D sample array) */
  160000. typedef JSAMPARRAY *JSAMPIMAGE; /* a 3-D sample array: top index is color */
  160001. typedef JCOEF JBLOCK[DCTSIZE2]; /* one block of coefficients */
  160002. typedef JBLOCK FAR *JBLOCKROW; /* pointer to one row of coefficient blocks */
  160003. typedef JBLOCKROW *JBLOCKARRAY; /* a 2-D array of coefficient blocks */
  160004. typedef JBLOCKARRAY *JBLOCKIMAGE; /* a 3-D array of coefficient blocks */
  160005. typedef JCOEF FAR *JCOEFPTR; /* useful in a couple of places */
  160006. /* Types for JPEG compression parameters and working tables. */
  160007. /* DCT coefficient quantization tables. */
  160008. typedef struct {
  160009. /* This array gives the coefficient quantizers in natural array order
  160010. * (not the zigzag order in which they are stored in a JPEG DQT marker).
  160011. * CAUTION: IJG versions prior to v6a kept this array in zigzag order.
  160012. */
  160013. UINT16 quantval[DCTSIZE2]; /* quantization step for each coefficient */
  160014. /* This field is used only during compression. It's initialized FALSE when
  160015. * the table is created, and set TRUE when it's been output to the file.
  160016. * You could suppress output of a table by setting this to TRUE.
  160017. * (See jpeg_suppress_tables for an example.)
  160018. */
  160019. boolean sent_table; /* TRUE when table has been output */
  160020. } JQUANT_TBL;
  160021. /* Huffman coding tables. */
  160022. typedef struct {
  160023. /* These two fields directly represent the contents of a JPEG DHT marker */
  160024. UINT8 bits[17]; /* bits[k] = # of symbols with codes of */
  160025. /* length k bits; bits[0] is unused */
  160026. UINT8 huffval[256]; /* The symbols, in order of incr code length */
  160027. /* This field is used only during compression. It's initialized FALSE when
  160028. * the table is created, and set TRUE when it's been output to the file.
  160029. * You could suppress output of a table by setting this to TRUE.
  160030. * (See jpeg_suppress_tables for an example.)
  160031. */
  160032. boolean sent_table; /* TRUE when table has been output */
  160033. } JHUFF_TBL;
  160034. /* Basic info about one component (color channel). */
  160035. typedef struct {
  160036. /* These values are fixed over the whole image. */
  160037. /* For compression, they must be supplied by parameter setup; */
  160038. /* for decompression, they are read from the SOF marker. */
  160039. int component_id; /* identifier for this component (0..255) */
  160040. int component_index; /* its index in SOF or cinfo->comp_info[] */
  160041. int h_samp_factor; /* horizontal sampling factor (1..4) */
  160042. int v_samp_factor; /* vertical sampling factor (1..4) */
  160043. int quant_tbl_no; /* quantization table selector (0..3) */
  160044. /* These values may vary between scans. */
  160045. /* For compression, they must be supplied by parameter setup; */
  160046. /* for decompression, they are read from the SOS marker. */
  160047. /* The decompressor output side may not use these variables. */
  160048. int dc_tbl_no; /* DC entropy table selector (0..3) */
  160049. int ac_tbl_no; /* AC entropy table selector (0..3) */
  160050. /* Remaining fields should be treated as private by applications. */
  160051. /* These values are computed during compression or decompression startup: */
  160052. /* Component's size in DCT blocks.
  160053. * Any dummy blocks added to complete an MCU are not counted; therefore
  160054. * these values do not depend on whether a scan is interleaved or not.
  160055. */
  160056. JDIMENSION width_in_blocks;
  160057. JDIMENSION height_in_blocks;
  160058. /* Size of a DCT block in samples. Always DCTSIZE for compression.
  160059. * For decompression this is the size of the output from one DCT block,
  160060. * reflecting any scaling we choose to apply during the IDCT step.
  160061. * Values of 1,2,4,8 are likely to be supported. Note that different
  160062. * components may receive different IDCT scalings.
  160063. */
  160064. int DCT_scaled_size;
  160065. /* The downsampled dimensions are the component's actual, unpadded number
  160066. * of samples at the main buffer (preprocessing/compression interface), thus
  160067. * downsampled_width = ceil(image_width * Hi/Hmax)
  160068. * and similarly for height. For decompression, IDCT scaling is included, so
  160069. * downsampled_width = ceil(image_width * Hi/Hmax * DCT_scaled_size/DCTSIZE)
  160070. */
  160071. JDIMENSION downsampled_width; /* actual width in samples */
  160072. JDIMENSION downsampled_height; /* actual height in samples */
  160073. /* This flag is used only for decompression. In cases where some of the
  160074. * components will be ignored (eg grayscale output from YCbCr image),
  160075. * we can skip most computations for the unused components.
  160076. */
  160077. boolean component_needed; /* do we need the value of this component? */
  160078. /* These values are computed before starting a scan of the component. */
  160079. /* The decompressor output side may not use these variables. */
  160080. int MCU_width; /* number of blocks per MCU, horizontally */
  160081. int MCU_height; /* number of blocks per MCU, vertically */
  160082. int MCU_blocks; /* MCU_width * MCU_height */
  160083. int MCU_sample_width; /* MCU width in samples, MCU_width*DCT_scaled_size */
  160084. int last_col_width; /* # of non-dummy blocks across in last MCU */
  160085. int last_row_height; /* # of non-dummy blocks down in last MCU */
  160086. /* Saved quantization table for component; NULL if none yet saved.
  160087. * See jdinput.c comments about the need for this information.
  160088. * This field is currently used only for decompression.
  160089. */
  160090. JQUANT_TBL * quant_table;
  160091. /* Private per-component storage for DCT or IDCT subsystem. */
  160092. void * dct_table;
  160093. } jpeg_component_info;
  160094. /* The script for encoding a multiple-scan file is an array of these: */
  160095. typedef struct {
  160096. int comps_in_scan; /* number of components encoded in this scan */
  160097. int component_index[MAX_COMPS_IN_SCAN]; /* their SOF/comp_info[] indexes */
  160098. int Ss, Se; /* progressive JPEG spectral selection parms */
  160099. int Ah, Al; /* progressive JPEG successive approx. parms */
  160100. } jpeg_scan_info;
  160101. /* The decompressor can save APPn and COM markers in a list of these: */
  160102. typedef struct jpeg_marker_struct FAR * jpeg_saved_marker_ptr;
  160103. struct jpeg_marker_struct {
  160104. jpeg_saved_marker_ptr next; /* next in list, or NULL */
  160105. UINT8 marker; /* marker code: JPEG_COM, or JPEG_APP0+n */
  160106. unsigned int original_length; /* # bytes of data in the file */
  160107. unsigned int data_length; /* # bytes of data saved at data[] */
  160108. JOCTET FAR * data; /* the data contained in the marker */
  160109. /* the marker length word is not counted in data_length or original_length */
  160110. };
  160111. /* Known color spaces. */
  160112. typedef enum {
  160113. JCS_UNKNOWN, /* error/unspecified */
  160114. JCS_GRAYSCALE, /* monochrome */
  160115. JCS_RGB, /* red/green/blue */
  160116. JCS_YCbCr, /* Y/Cb/Cr (also known as YUV) */
  160117. JCS_CMYK, /* C/M/Y/K */
  160118. JCS_YCCK /* Y/Cb/Cr/K */
  160119. } J_COLOR_SPACE;
  160120. /* DCT/IDCT algorithm options. */
  160121. typedef enum {
  160122. JDCT_ISLOW, /* slow but accurate integer algorithm */
  160123. JDCT_IFAST, /* faster, less accurate integer method */
  160124. JDCT_FLOAT /* floating-point: accurate, fast on fast HW */
  160125. } J_DCT_METHOD;
  160126. #ifndef JDCT_DEFAULT /* may be overridden in jconfig.h */
  160127. #define JDCT_DEFAULT JDCT_ISLOW
  160128. #endif
  160129. #ifndef JDCT_FASTEST /* may be overridden in jconfig.h */
  160130. #define JDCT_FASTEST JDCT_IFAST
  160131. #endif
  160132. /* Dithering options for decompression. */
  160133. typedef enum {
  160134. JDITHER_NONE, /* no dithering */
  160135. JDITHER_ORDERED, /* simple ordered dither */
  160136. JDITHER_FS /* Floyd-Steinberg error diffusion dither */
  160137. } J_DITHER_MODE;
  160138. /* Common fields between JPEG compression and decompression master structs. */
  160139. #define jpeg_common_fields \
  160140. struct jpeg_error_mgr * err; /* Error handler module */\
  160141. struct jpeg_memory_mgr * mem; /* Memory manager module */\
  160142. struct jpeg_progress_mgr * progress; /* Progress monitor, or NULL if none */\
  160143. void * client_data; /* Available for use by application */\
  160144. boolean is_decompressor; /* So common code can tell which is which */\
  160145. int global_state /* For checking call sequence validity */
  160146. /* Routines that are to be used by both halves of the library are declared
  160147. * to receive a pointer to this structure. There are no actual instances of
  160148. * jpeg_common_struct, only of jpeg_compress_struct and jpeg_decompress_struct.
  160149. */
  160150. struct jpeg_common_struct {
  160151. jpeg_common_fields; /* Fields common to both master struct types */
  160152. /* Additional fields follow in an actual jpeg_compress_struct or
  160153. * jpeg_decompress_struct. All three structs must agree on these
  160154. * initial fields! (This would be a lot cleaner in C++.)
  160155. */
  160156. };
  160157. typedef struct jpeg_common_struct * j_common_ptr;
  160158. typedef struct jpeg_compress_struct * j_compress_ptr;
  160159. typedef struct jpeg_decompress_struct * j_decompress_ptr;
  160160. /* Master record for a compression instance */
  160161. struct jpeg_compress_struct {
  160162. jpeg_common_fields; /* Fields shared with jpeg_decompress_struct */
  160163. /* Destination for compressed data */
  160164. struct jpeg_destination_mgr * dest;
  160165. /* Description of source image --- these fields must be filled in by
  160166. * outer application before starting compression. in_color_space must
  160167. * be correct before you can even call jpeg_set_defaults().
  160168. */
  160169. JDIMENSION image_width; /* input image width */
  160170. JDIMENSION image_height; /* input image height */
  160171. int input_components; /* # of color components in input image */
  160172. J_COLOR_SPACE in_color_space; /* colorspace of input image */
  160173. double input_gamma; /* image gamma of input image */
  160174. /* Compression parameters --- these fields must be set before calling
  160175. * jpeg_start_compress(). We recommend calling jpeg_set_defaults() to
  160176. * initialize everything to reasonable defaults, then changing anything
  160177. * the application specifically wants to change. That way you won't get
  160178. * burnt when new parameters are added. Also note that there are several
  160179. * helper routines to simplify changing parameters.
  160180. */
  160181. int data_precision; /* bits of precision in image data */
  160182. int num_components; /* # of color components in JPEG image */
  160183. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  160184. jpeg_component_info * comp_info;
  160185. /* comp_info[i] describes component that appears i'th in SOF */
  160186. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  160187. /* ptrs to coefficient quantization tables, or NULL if not defined */
  160188. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160189. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160190. /* ptrs to Huffman coding tables, or NULL if not defined */
  160191. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  160192. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  160193. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  160194. int num_scans; /* # of entries in scan_info array */
  160195. const jpeg_scan_info * scan_info; /* script for multi-scan file, or NULL */
  160196. /* The default value of scan_info is NULL, which causes a single-scan
  160197. * sequential JPEG file to be emitted. To create a multi-scan file,
  160198. * set num_scans and scan_info to point to an array of scan definitions.
  160199. */
  160200. boolean raw_data_in; /* TRUE=caller supplies downsampled data */
  160201. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  160202. boolean optimize_coding; /* TRUE=optimize entropy encoding parms */
  160203. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  160204. int smoothing_factor; /* 1..100, or 0 for no input smoothing */
  160205. J_DCT_METHOD dct_method; /* DCT algorithm selector */
  160206. /* The restart interval can be specified in absolute MCUs by setting
  160207. * restart_interval, or in MCU rows by setting restart_in_rows
  160208. * (in which case the correct restart_interval will be figured
  160209. * for each scan).
  160210. */
  160211. unsigned int restart_interval; /* MCUs per restart, or 0 for no restart */
  160212. int restart_in_rows; /* if > 0, MCU rows per restart interval */
  160213. /* Parameters controlling emission of special markers. */
  160214. boolean write_JFIF_header; /* should a JFIF marker be written? */
  160215. UINT8 JFIF_major_version; /* What to write for the JFIF version number */
  160216. UINT8 JFIF_minor_version;
  160217. /* These three values are not used by the JPEG code, merely copied */
  160218. /* into the JFIF APP0 marker. density_unit can be 0 for unknown, */
  160219. /* 1 for dots/inch, or 2 for dots/cm. Note that the pixel aspect */
  160220. /* ratio is defined by X_density/Y_density even when density_unit=0. */
  160221. UINT8 density_unit; /* JFIF code for pixel size units */
  160222. UINT16 X_density; /* Horizontal pixel density */
  160223. UINT16 Y_density; /* Vertical pixel density */
  160224. boolean write_Adobe_marker; /* should an Adobe marker be written? */
  160225. /* State variable: index of next scanline to be written to
  160226. * jpeg_write_scanlines(). Application may use this to control its
  160227. * processing loop, e.g., "while (next_scanline < image_height)".
  160228. */
  160229. JDIMENSION next_scanline; /* 0 .. image_height-1 */
  160230. /* Remaining fields are known throughout compressor, but generally
  160231. * should not be touched by a surrounding application.
  160232. */
  160233. /*
  160234. * These fields are computed during compression startup
  160235. */
  160236. boolean progressive_mode; /* TRUE if scan script uses progressive mode */
  160237. int max_h_samp_factor; /* largest h_samp_factor */
  160238. int max_v_samp_factor; /* largest v_samp_factor */
  160239. JDIMENSION total_iMCU_rows; /* # of iMCU rows to be input to coef ctlr */
  160240. /* The coefficient controller receives data in units of MCU rows as defined
  160241. * for fully interleaved scans (whether the JPEG file is interleaved or not).
  160242. * There are v_samp_factor * DCTSIZE sample rows of each component in an
  160243. * "iMCU" (interleaved MCU) row.
  160244. */
  160245. /*
  160246. * These fields are valid during any one scan.
  160247. * They describe the components and MCUs actually appearing in the scan.
  160248. */
  160249. int comps_in_scan; /* # of JPEG components in this scan */
  160250. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  160251. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  160252. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  160253. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  160254. int blocks_in_MCU; /* # of DCT blocks per MCU */
  160255. int MCU_membership[C_MAX_BLOCKS_IN_MCU];
  160256. /* MCU_membership[i] is index in cur_comp_info of component owning */
  160257. /* i'th block in an MCU */
  160258. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  160259. /*
  160260. * Links to compression subobjects (methods and private variables of modules)
  160261. */
  160262. struct jpeg_comp_master * master;
  160263. struct jpeg_c_main_controller * main;
  160264. struct jpeg_c_prep_controller * prep;
  160265. struct jpeg_c_coef_controller * coef;
  160266. struct jpeg_marker_writer * marker;
  160267. struct jpeg_color_converter * cconvert;
  160268. struct jpeg_downsampler * downsample;
  160269. struct jpeg_forward_dct * fdct;
  160270. struct jpeg_entropy_encoder * entropy;
  160271. jpeg_scan_info * script_space; /* workspace for jpeg_simple_progression */
  160272. int script_space_size;
  160273. };
  160274. /* Master record for a decompression instance */
  160275. struct jpeg_decompress_struct {
  160276. jpeg_common_fields; /* Fields shared with jpeg_compress_struct */
  160277. /* Source of compressed data */
  160278. struct jpeg_source_mgr * src;
  160279. /* Basic description of image --- filled in by jpeg_read_header(). */
  160280. /* Application may inspect these values to decide how to process image. */
  160281. JDIMENSION image_width; /* nominal image width (from SOF marker) */
  160282. JDIMENSION image_height; /* nominal image height */
  160283. int num_components; /* # of color components in JPEG image */
  160284. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  160285. /* Decompression processing parameters --- these fields must be set before
  160286. * calling jpeg_start_decompress(). Note that jpeg_read_header() initializes
  160287. * them to default values.
  160288. */
  160289. J_COLOR_SPACE out_color_space; /* colorspace for output */
  160290. unsigned int scale_num, scale_denom; /* fraction by which to scale image */
  160291. double output_gamma; /* image gamma wanted in output */
  160292. boolean buffered_image; /* TRUE=multiple output passes */
  160293. boolean raw_data_out; /* TRUE=downsampled data wanted */
  160294. J_DCT_METHOD dct_method; /* IDCT algorithm selector */
  160295. boolean do_fancy_upsampling; /* TRUE=apply fancy upsampling */
  160296. boolean do_block_smoothing; /* TRUE=apply interblock smoothing */
  160297. boolean quantize_colors; /* TRUE=colormapped output wanted */
  160298. /* the following are ignored if not quantize_colors: */
  160299. J_DITHER_MODE dither_mode; /* type of color dithering to use */
  160300. boolean two_pass_quantize; /* TRUE=use two-pass color quantization */
  160301. int desired_number_of_colors; /* max # colors to use in created colormap */
  160302. /* these are significant only in buffered-image mode: */
  160303. boolean enable_1pass_quant; /* enable future use of 1-pass quantizer */
  160304. boolean enable_external_quant;/* enable future use of external colormap */
  160305. boolean enable_2pass_quant; /* enable future use of 2-pass quantizer */
  160306. /* Description of actual output image that will be returned to application.
  160307. * These fields are computed by jpeg_start_decompress().
  160308. * You can also use jpeg_calc_output_dimensions() to determine these values
  160309. * in advance of calling jpeg_start_decompress().
  160310. */
  160311. JDIMENSION output_width; /* scaled image width */
  160312. JDIMENSION output_height; /* scaled image height */
  160313. int out_color_components; /* # of color components in out_color_space */
  160314. int output_components; /* # of color components returned */
  160315. /* output_components is 1 (a colormap index) when quantizing colors;
  160316. * otherwise it equals out_color_components.
  160317. */
  160318. int rec_outbuf_height; /* min recommended height of scanline buffer */
  160319. /* If the buffer passed to jpeg_read_scanlines() is less than this many rows
  160320. * high, space and time will be wasted due to unnecessary data copying.
  160321. * Usually rec_outbuf_height will be 1 or 2, at most 4.
  160322. */
  160323. /* When quantizing colors, the output colormap is described by these fields.
  160324. * The application can supply a colormap by setting colormap non-NULL before
  160325. * calling jpeg_start_decompress; otherwise a colormap is created during
  160326. * jpeg_start_decompress or jpeg_start_output.
  160327. * The map has out_color_components rows and actual_number_of_colors columns.
  160328. */
  160329. int actual_number_of_colors; /* number of entries in use */
  160330. JSAMPARRAY colormap; /* The color map as a 2-D pixel array */
  160331. /* State variables: these variables indicate the progress of decompression.
  160332. * The application may examine these but must not modify them.
  160333. */
  160334. /* Row index of next scanline to be read from jpeg_read_scanlines().
  160335. * Application may use this to control its processing loop, e.g.,
  160336. * "while (output_scanline < output_height)".
  160337. */
  160338. JDIMENSION output_scanline; /* 0 .. output_height-1 */
  160339. /* Current input scan number and number of iMCU rows completed in scan.
  160340. * These indicate the progress of the decompressor input side.
  160341. */
  160342. int input_scan_number; /* Number of SOS markers seen so far */
  160343. JDIMENSION input_iMCU_row; /* Number of iMCU rows completed */
  160344. /* The "output scan number" is the notional scan being displayed by the
  160345. * output side. The decompressor will not allow output scan/row number
  160346. * to get ahead of input scan/row, but it can fall arbitrarily far behind.
  160347. */
  160348. int output_scan_number; /* Nominal scan number being displayed */
  160349. JDIMENSION output_iMCU_row; /* Number of iMCU rows read */
  160350. /* Current progression status. coef_bits[c][i] indicates the precision
  160351. * with which component c's DCT coefficient i (in zigzag order) is known.
  160352. * It is -1 when no data has yet been received, otherwise it is the point
  160353. * transform (shift) value for the most recent scan of the coefficient
  160354. * (thus, 0 at completion of the progression).
  160355. * This pointer is NULL when reading a non-progressive file.
  160356. */
  160357. int (*coef_bits)[DCTSIZE2]; /* -1 or current Al value for each coef */
  160358. /* Internal JPEG parameters --- the application usually need not look at
  160359. * these fields. Note that the decompressor output side may not use
  160360. * any parameters that can change between scans.
  160361. */
  160362. /* Quantization and Huffman tables are carried forward across input
  160363. * datastreams when processing abbreviated JPEG datastreams.
  160364. */
  160365. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  160366. /* ptrs to coefficient quantization tables, or NULL if not defined */
  160367. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160368. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160369. /* ptrs to Huffman coding tables, or NULL if not defined */
  160370. /* These parameters are never carried across datastreams, since they
  160371. * are given in SOF/SOS markers or defined to be reset by SOI.
  160372. */
  160373. int data_precision; /* bits of precision in image data */
  160374. jpeg_component_info * comp_info;
  160375. /* comp_info[i] describes component that appears i'th in SOF */
  160376. boolean progressive_mode; /* TRUE if SOFn specifies progressive mode */
  160377. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  160378. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  160379. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  160380. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  160381. unsigned int restart_interval; /* MCUs per restart interval, or 0 for no restart */
  160382. /* These fields record data obtained from optional markers recognized by
  160383. * the JPEG library.
  160384. */
  160385. boolean saw_JFIF_marker; /* TRUE iff a JFIF APP0 marker was found */
  160386. /* Data copied from JFIF marker; only valid if saw_JFIF_marker is TRUE: */
  160387. UINT8 JFIF_major_version; /* JFIF version number */
  160388. UINT8 JFIF_minor_version;
  160389. UINT8 density_unit; /* JFIF code for pixel size units */
  160390. UINT16 X_density; /* Horizontal pixel density */
  160391. UINT16 Y_density; /* Vertical pixel density */
  160392. boolean saw_Adobe_marker; /* TRUE iff an Adobe APP14 marker was found */
  160393. UINT8 Adobe_transform; /* Color transform code from Adobe marker */
  160394. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  160395. /* Aside from the specific data retained from APPn markers known to the
  160396. * library, the uninterpreted contents of any or all APPn and COM markers
  160397. * can be saved in a list for examination by the application.
  160398. */
  160399. jpeg_saved_marker_ptr marker_list; /* Head of list of saved markers */
  160400. /* Remaining fields are known throughout decompressor, but generally
  160401. * should not be touched by a surrounding application.
  160402. */
  160403. /*
  160404. * These fields are computed during decompression startup
  160405. */
  160406. int max_h_samp_factor; /* largest h_samp_factor */
  160407. int max_v_samp_factor; /* largest v_samp_factor */
  160408. int min_DCT_scaled_size; /* smallest DCT_scaled_size of any component */
  160409. JDIMENSION total_iMCU_rows; /* # of iMCU rows in image */
  160410. /* The coefficient controller's input and output progress is measured in
  160411. * units of "iMCU" (interleaved MCU) rows. These are the same as MCU rows
  160412. * in fully interleaved JPEG scans, but are used whether the scan is
  160413. * interleaved or not. We define an iMCU row as v_samp_factor DCT block
  160414. * rows of each component. Therefore, the IDCT output contains
  160415. * v_samp_factor*DCT_scaled_size sample rows of a component per iMCU row.
  160416. */
  160417. JSAMPLE * sample_range_limit; /* table for fast range-limiting */
  160418. /*
  160419. * These fields are valid during any one scan.
  160420. * They describe the components and MCUs actually appearing in the scan.
  160421. * Note that the decompressor output side must not use these fields.
  160422. */
  160423. int comps_in_scan; /* # of JPEG components in this scan */
  160424. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  160425. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  160426. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  160427. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  160428. int blocks_in_MCU; /* # of DCT blocks per MCU */
  160429. int MCU_membership[D_MAX_BLOCKS_IN_MCU];
  160430. /* MCU_membership[i] is index in cur_comp_info of component owning */
  160431. /* i'th block in an MCU */
  160432. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  160433. /* This field is shared between entropy decoder and marker parser.
  160434. * It is either zero or the code of a JPEG marker that has been
  160435. * read from the data source, but has not yet been processed.
  160436. */
  160437. int unread_marker;
  160438. /*
  160439. * Links to decompression subobjects (methods, private variables of modules)
  160440. */
  160441. struct jpeg_decomp_master * master;
  160442. struct jpeg_d_main_controller * main;
  160443. struct jpeg_d_coef_controller * coef;
  160444. struct jpeg_d_post_controller * post;
  160445. struct jpeg_input_controller * inputctl;
  160446. struct jpeg_marker_reader * marker;
  160447. struct jpeg_entropy_decoder * entropy;
  160448. struct jpeg_inverse_dct * idct;
  160449. struct jpeg_upsampler * upsample;
  160450. struct jpeg_color_deconverter * cconvert;
  160451. struct jpeg_color_quantizer * cquantize;
  160452. };
  160453. /* "Object" declarations for JPEG modules that may be supplied or called
  160454. * directly by the surrounding application.
  160455. * As with all objects in the JPEG library, these structs only define the
  160456. * publicly visible methods and state variables of a module. Additional
  160457. * private fields may exist after the public ones.
  160458. */
  160459. /* Error handler object */
  160460. struct jpeg_error_mgr {
  160461. /* Error exit handler: does not return to caller */
  160462. JMETHOD(void, error_exit, (j_common_ptr cinfo));
  160463. /* Conditionally emit a trace or warning message */
  160464. JMETHOD(void, emit_message, (j_common_ptr cinfo, int msg_level));
  160465. /* Routine that actually outputs a trace or error message */
  160466. JMETHOD(void, output_message, (j_common_ptr cinfo));
  160467. /* Format a message string for the most recent JPEG error or message */
  160468. JMETHOD(void, format_message, (j_common_ptr cinfo, char * buffer));
  160469. #define JMSG_LENGTH_MAX 200 /* recommended size of format_message buffer */
  160470. /* Reset error state variables at start of a new image */
  160471. JMETHOD(void, reset_error_mgr, (j_common_ptr cinfo));
  160472. /* The message ID code and any parameters are saved here.
  160473. * A message can have one string parameter or up to 8 int parameters.
  160474. */
  160475. int msg_code;
  160476. #define JMSG_STR_PARM_MAX 80
  160477. union {
  160478. int i[8];
  160479. char s[JMSG_STR_PARM_MAX];
  160480. } msg_parm;
  160481. /* Standard state variables for error facility */
  160482. int trace_level; /* max msg_level that will be displayed */
  160483. /* For recoverable corrupt-data errors, we emit a warning message,
  160484. * but keep going unless emit_message chooses to abort. emit_message
  160485. * should count warnings in num_warnings. The surrounding application
  160486. * can check for bad data by seeing if num_warnings is nonzero at the
  160487. * end of processing.
  160488. */
  160489. long num_warnings; /* number of corrupt-data warnings */
  160490. /* These fields point to the table(s) of error message strings.
  160491. * An application can change the table pointer to switch to a different
  160492. * message list (typically, to change the language in which errors are
  160493. * reported). Some applications may wish to add additional error codes
  160494. * that will be handled by the JPEG library error mechanism; the second
  160495. * table pointer is used for this purpose.
  160496. *
  160497. * First table includes all errors generated by JPEG library itself.
  160498. * Error code 0 is reserved for a "no such error string" message.
  160499. */
  160500. const char * const * jpeg_message_table; /* Library errors */
  160501. int last_jpeg_message; /* Table contains strings 0..last_jpeg_message */
  160502. /* Second table can be added by application (see cjpeg/djpeg for example).
  160503. * It contains strings numbered first_addon_message..last_addon_message.
  160504. */
  160505. const char * const * addon_message_table; /* Non-library errors */
  160506. int first_addon_message; /* code for first string in addon table */
  160507. int last_addon_message; /* code for last string in addon table */
  160508. };
  160509. /* Progress monitor object */
  160510. struct jpeg_progress_mgr {
  160511. JMETHOD(void, progress_monitor, (j_common_ptr cinfo));
  160512. long pass_counter; /* work units completed in this pass */
  160513. long pass_limit; /* total number of work units in this pass */
  160514. int completed_passes; /* passes completed so far */
  160515. int total_passes; /* total number of passes expected */
  160516. };
  160517. /* Data destination object for compression */
  160518. struct jpeg_destination_mgr {
  160519. JOCTET * next_output_byte; /* => next byte to write in buffer */
  160520. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  160521. JMETHOD(void, init_destination, (j_compress_ptr cinfo));
  160522. JMETHOD(boolean, empty_output_buffer, (j_compress_ptr cinfo));
  160523. JMETHOD(void, term_destination, (j_compress_ptr cinfo));
  160524. };
  160525. /* Data source object for decompression */
  160526. struct jpeg_source_mgr {
  160527. const JOCTET * next_input_byte; /* => next byte to read from buffer */
  160528. size_t bytes_in_buffer; /* # of bytes remaining in buffer */
  160529. JMETHOD(void, init_source, (j_decompress_ptr cinfo));
  160530. JMETHOD(boolean, fill_input_buffer, (j_decompress_ptr cinfo));
  160531. JMETHOD(void, skip_input_data, (j_decompress_ptr cinfo, long num_bytes));
  160532. JMETHOD(boolean, resync_to_restart, (j_decompress_ptr cinfo, int desired));
  160533. JMETHOD(void, term_source, (j_decompress_ptr cinfo));
  160534. };
  160535. /* Memory manager object.
  160536. * Allocates "small" objects (a few K total), "large" objects (tens of K),
  160537. * and "really big" objects (virtual arrays with backing store if needed).
  160538. * The memory manager does not allow individual objects to be freed; rather,
  160539. * each created object is assigned to a pool, and whole pools can be freed
  160540. * at once. This is faster and more convenient than remembering exactly what
  160541. * to free, especially where malloc()/free() are not too speedy.
  160542. * NB: alloc routines never return NULL. They exit to error_exit if not
  160543. * successful.
  160544. */
  160545. #define JPOOL_PERMANENT 0 /* lasts until master record is destroyed */
  160546. #define JPOOL_IMAGE 1 /* lasts until done with image/datastream */
  160547. #define JPOOL_NUMPOOLS 2
  160548. typedef struct jvirt_sarray_control * jvirt_sarray_ptr;
  160549. typedef struct jvirt_barray_control * jvirt_barray_ptr;
  160550. struct jpeg_memory_mgr {
  160551. /* Method pointers */
  160552. JMETHOD(void *, alloc_small, (j_common_ptr cinfo, int pool_id,
  160553. size_t sizeofobject));
  160554. JMETHOD(void FAR *, alloc_large, (j_common_ptr cinfo, int pool_id,
  160555. size_t sizeofobject));
  160556. JMETHOD(JSAMPARRAY, alloc_sarray, (j_common_ptr cinfo, int pool_id,
  160557. JDIMENSION samplesperrow,
  160558. JDIMENSION numrows));
  160559. JMETHOD(JBLOCKARRAY, alloc_barray, (j_common_ptr cinfo, int pool_id,
  160560. JDIMENSION blocksperrow,
  160561. JDIMENSION numrows));
  160562. JMETHOD(jvirt_sarray_ptr, request_virt_sarray, (j_common_ptr cinfo,
  160563. int pool_id,
  160564. boolean pre_zero,
  160565. JDIMENSION samplesperrow,
  160566. JDIMENSION numrows,
  160567. JDIMENSION maxaccess));
  160568. JMETHOD(jvirt_barray_ptr, request_virt_barray, (j_common_ptr cinfo,
  160569. int pool_id,
  160570. boolean pre_zero,
  160571. JDIMENSION blocksperrow,
  160572. JDIMENSION numrows,
  160573. JDIMENSION maxaccess));
  160574. JMETHOD(void, realize_virt_arrays, (j_common_ptr cinfo));
  160575. JMETHOD(JSAMPARRAY, access_virt_sarray, (j_common_ptr cinfo,
  160576. jvirt_sarray_ptr ptr,
  160577. JDIMENSION start_row,
  160578. JDIMENSION num_rows,
  160579. boolean writable));
  160580. JMETHOD(JBLOCKARRAY, access_virt_barray, (j_common_ptr cinfo,
  160581. jvirt_barray_ptr ptr,
  160582. JDIMENSION start_row,
  160583. JDIMENSION num_rows,
  160584. boolean writable));
  160585. JMETHOD(void, free_pool, (j_common_ptr cinfo, int pool_id));
  160586. JMETHOD(void, self_destruct, (j_common_ptr cinfo));
  160587. /* Limit on memory allocation for this JPEG object. (Note that this is
  160588. * merely advisory, not a guaranteed maximum; it only affects the space
  160589. * used for virtual-array buffers.) May be changed by outer application
  160590. * after creating the JPEG object.
  160591. */
  160592. long max_memory_to_use;
  160593. /* Maximum allocation request accepted by alloc_large. */
  160594. long max_alloc_chunk;
  160595. };
  160596. /* Routine signature for application-supplied marker processing methods.
  160597. * Need not pass marker code since it is stored in cinfo->unread_marker.
  160598. */
  160599. typedef JMETHOD(boolean, jpeg_marker_parser_method, (j_decompress_ptr cinfo));
  160600. /* Declarations for routines called by application.
  160601. * The JPP macro hides prototype parameters from compilers that can't cope.
  160602. * Note JPP requires double parentheses.
  160603. */
  160604. #ifdef HAVE_PROTOTYPES
  160605. #define JPP(arglist) arglist
  160606. #else
  160607. #define JPP(arglist) ()
  160608. #endif
  160609. /* Short forms of external names for systems with brain-damaged linkers.
  160610. * We shorten external names to be unique in the first six letters, which
  160611. * is good enough for all known systems.
  160612. * (If your compiler itself needs names to be unique in less than 15
  160613. * characters, you are out of luck. Get a better compiler.)
  160614. */
  160615. #ifdef NEED_SHORT_EXTERNAL_NAMES
  160616. #define jpeg_std_error jStdError
  160617. #define jpeg_CreateCompress jCreaCompress
  160618. #define jpeg_CreateDecompress jCreaDecompress
  160619. #define jpeg_destroy_compress jDestCompress
  160620. #define jpeg_destroy_decompress jDestDecompress
  160621. #define jpeg_stdio_dest jStdDest
  160622. #define jpeg_stdio_src jStdSrc
  160623. #define jpeg_set_defaults jSetDefaults
  160624. #define jpeg_set_colorspace jSetColorspace
  160625. #define jpeg_default_colorspace jDefColorspace
  160626. #define jpeg_set_quality jSetQuality
  160627. #define jpeg_set_linear_quality jSetLQuality
  160628. #define jpeg_add_quant_table jAddQuantTable
  160629. #define jpeg_quality_scaling jQualityScaling
  160630. #define jpeg_simple_progression jSimProgress
  160631. #define jpeg_suppress_tables jSuppressTables
  160632. #define jpeg_alloc_quant_table jAlcQTable
  160633. #define jpeg_alloc_huff_table jAlcHTable
  160634. #define jpeg_start_compress jStrtCompress
  160635. #define jpeg_write_scanlines jWrtScanlines
  160636. #define jpeg_finish_compress jFinCompress
  160637. #define jpeg_write_raw_data jWrtRawData
  160638. #define jpeg_write_marker jWrtMarker
  160639. #define jpeg_write_m_header jWrtMHeader
  160640. #define jpeg_write_m_byte jWrtMByte
  160641. #define jpeg_write_tables jWrtTables
  160642. #define jpeg_read_header jReadHeader
  160643. #define jpeg_start_decompress jStrtDecompress
  160644. #define jpeg_read_scanlines jReadScanlines
  160645. #define jpeg_finish_decompress jFinDecompress
  160646. #define jpeg_read_raw_data jReadRawData
  160647. #define jpeg_has_multiple_scans jHasMultScn
  160648. #define jpeg_start_output jStrtOutput
  160649. #define jpeg_finish_output jFinOutput
  160650. #define jpeg_input_complete jInComplete
  160651. #define jpeg_new_colormap jNewCMap
  160652. #define jpeg_consume_input jConsumeInput
  160653. #define jpeg_calc_output_dimensions jCalcDimensions
  160654. #define jpeg_save_markers jSaveMarkers
  160655. #define jpeg_set_marker_processor jSetMarker
  160656. #define jpeg_read_coefficients jReadCoefs
  160657. #define jpeg_write_coefficients jWrtCoefs
  160658. #define jpeg_copy_critical_parameters jCopyCrit
  160659. #define jpeg_abort_compress jAbrtCompress
  160660. #define jpeg_abort_decompress jAbrtDecompress
  160661. #define jpeg_abort jAbort
  160662. #define jpeg_destroy jDestroy
  160663. #define jpeg_resync_to_restart jResyncRestart
  160664. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  160665. /* Default error-management setup */
  160666. EXTERN(struct jpeg_error_mgr *) jpeg_std_error
  160667. JPP((struct jpeg_error_mgr * err));
  160668. /* Initialization of JPEG compression objects.
  160669. * jpeg_create_compress() and jpeg_create_decompress() are the exported
  160670. * names that applications should call. These expand to calls on
  160671. * jpeg_CreateCompress and jpeg_CreateDecompress with additional information
  160672. * passed for version mismatch checking.
  160673. * NB: you must set up the error-manager BEFORE calling jpeg_create_xxx.
  160674. */
  160675. #define jpeg_create_compress(cinfo) \
  160676. jpeg_CreateCompress((cinfo), JPEG_LIB_VERSION, \
  160677. (size_t) sizeof(struct jpeg_compress_struct))
  160678. #define jpeg_create_decompress(cinfo) \
  160679. jpeg_CreateDecompress((cinfo), JPEG_LIB_VERSION, \
  160680. (size_t) sizeof(struct jpeg_decompress_struct))
  160681. EXTERN(void) jpeg_CreateCompress JPP((j_compress_ptr cinfo,
  160682. int version, size_t structsize));
  160683. EXTERN(void) jpeg_CreateDecompress JPP((j_decompress_ptr cinfo,
  160684. int version, size_t structsize));
  160685. /* Destruction of JPEG compression objects */
  160686. EXTERN(void) jpeg_destroy_compress JPP((j_compress_ptr cinfo));
  160687. EXTERN(void) jpeg_destroy_decompress JPP((j_decompress_ptr cinfo));
  160688. /* Standard data source and destination managers: stdio streams. */
  160689. /* Caller is responsible for opening the file before and closing after. */
  160690. EXTERN(void) jpeg_stdio_dest JPP((j_compress_ptr cinfo, FILE * outfile));
  160691. EXTERN(void) jpeg_stdio_src JPP((j_decompress_ptr cinfo, FILE * infile));
  160692. /* Default parameter setup for compression */
  160693. EXTERN(void) jpeg_set_defaults JPP((j_compress_ptr cinfo));
  160694. /* Compression parameter setup aids */
  160695. EXTERN(void) jpeg_set_colorspace JPP((j_compress_ptr cinfo,
  160696. J_COLOR_SPACE colorspace));
  160697. EXTERN(void) jpeg_default_colorspace JPP((j_compress_ptr cinfo));
  160698. EXTERN(void) jpeg_set_quality JPP((j_compress_ptr cinfo, int quality,
  160699. boolean force_baseline));
  160700. EXTERN(void) jpeg_set_linear_quality JPP((j_compress_ptr cinfo,
  160701. int scale_factor,
  160702. boolean force_baseline));
  160703. EXTERN(void) jpeg_add_quant_table JPP((j_compress_ptr cinfo, int which_tbl,
  160704. const unsigned int *basic_table,
  160705. int scale_factor,
  160706. boolean force_baseline));
  160707. EXTERN(int) jpeg_quality_scaling JPP((int quality));
  160708. EXTERN(void) jpeg_simple_progression JPP((j_compress_ptr cinfo));
  160709. EXTERN(void) jpeg_suppress_tables JPP((j_compress_ptr cinfo,
  160710. boolean suppress));
  160711. EXTERN(JQUANT_TBL *) jpeg_alloc_quant_table JPP((j_common_ptr cinfo));
  160712. EXTERN(JHUFF_TBL *) jpeg_alloc_huff_table JPP((j_common_ptr cinfo));
  160713. /* Main entry points for compression */
  160714. EXTERN(void) jpeg_start_compress JPP((j_compress_ptr cinfo,
  160715. boolean write_all_tables));
  160716. EXTERN(JDIMENSION) jpeg_write_scanlines JPP((j_compress_ptr cinfo,
  160717. JSAMPARRAY scanlines,
  160718. JDIMENSION num_lines));
  160719. EXTERN(void) jpeg_finish_compress JPP((j_compress_ptr cinfo));
  160720. /* Replaces jpeg_write_scanlines when writing raw downsampled data. */
  160721. EXTERN(JDIMENSION) jpeg_write_raw_data JPP((j_compress_ptr cinfo,
  160722. JSAMPIMAGE data,
  160723. JDIMENSION num_lines));
  160724. /* Write a special marker. See libjpeg.doc concerning safe usage. */
  160725. EXTERN(void) jpeg_write_marker
  160726. JPP((j_compress_ptr cinfo, int marker,
  160727. const JOCTET * dataptr, unsigned int datalen));
  160728. /* Same, but piecemeal. */
  160729. EXTERN(void) jpeg_write_m_header
  160730. JPP((j_compress_ptr cinfo, int marker, unsigned int datalen));
  160731. EXTERN(void) jpeg_write_m_byte
  160732. JPP((j_compress_ptr cinfo, int val));
  160733. /* Alternate compression function: just write an abbreviated table file */
  160734. EXTERN(void) jpeg_write_tables JPP((j_compress_ptr cinfo));
  160735. /* Decompression startup: read start of JPEG datastream to see what's there */
  160736. EXTERN(int) jpeg_read_header JPP((j_decompress_ptr cinfo,
  160737. boolean require_image));
  160738. /* Return value is one of: */
  160739. #define JPEG_SUSPENDED 0 /* Suspended due to lack of input data */
  160740. #define JPEG_HEADER_OK 1 /* Found valid image datastream */
  160741. #define JPEG_HEADER_TABLES_ONLY 2 /* Found valid table-specs-only datastream */
  160742. /* If you pass require_image = TRUE (normal case), you need not check for
  160743. * a TABLES_ONLY return code; an abbreviated file will cause an error exit.
  160744. * JPEG_SUSPENDED is only possible if you use a data source module that can
  160745. * give a suspension return (the stdio source module doesn't).
  160746. */
  160747. /* Main entry points for decompression */
  160748. EXTERN(boolean) jpeg_start_decompress JPP((j_decompress_ptr cinfo));
  160749. EXTERN(JDIMENSION) jpeg_read_scanlines JPP((j_decompress_ptr cinfo,
  160750. JSAMPARRAY scanlines,
  160751. JDIMENSION max_lines));
  160752. EXTERN(boolean) jpeg_finish_decompress JPP((j_decompress_ptr cinfo));
  160753. /* Replaces jpeg_read_scanlines when reading raw downsampled data. */
  160754. EXTERN(JDIMENSION) jpeg_read_raw_data JPP((j_decompress_ptr cinfo,
  160755. JSAMPIMAGE data,
  160756. JDIMENSION max_lines));
  160757. /* Additional entry points for buffered-image mode. */
  160758. EXTERN(boolean) jpeg_has_multiple_scans JPP((j_decompress_ptr cinfo));
  160759. EXTERN(boolean) jpeg_start_output JPP((j_decompress_ptr cinfo,
  160760. int scan_number));
  160761. EXTERN(boolean) jpeg_finish_output JPP((j_decompress_ptr cinfo));
  160762. EXTERN(boolean) jpeg_input_complete JPP((j_decompress_ptr cinfo));
  160763. EXTERN(void) jpeg_new_colormap JPP((j_decompress_ptr cinfo));
  160764. EXTERN(int) jpeg_consume_input JPP((j_decompress_ptr cinfo));
  160765. /* Return value is one of: */
  160766. /* #define JPEG_SUSPENDED 0 Suspended due to lack of input data */
  160767. #define JPEG_REACHED_SOS 1 /* Reached start of new scan */
  160768. #define JPEG_REACHED_EOI 2 /* Reached end of image */
  160769. #define JPEG_ROW_COMPLETED 3 /* Completed one iMCU row */
  160770. #define JPEG_SCAN_COMPLETED 4 /* Completed last iMCU row of a scan */
  160771. /* Precalculate output dimensions for current decompression parameters. */
  160772. EXTERN(void) jpeg_calc_output_dimensions JPP((j_decompress_ptr cinfo));
  160773. /* Control saving of COM and APPn markers into marker_list. */
  160774. EXTERN(void) jpeg_save_markers
  160775. JPP((j_decompress_ptr cinfo, int marker_code,
  160776. unsigned int length_limit));
  160777. /* Install a special processing method for COM or APPn markers. */
  160778. EXTERN(void) jpeg_set_marker_processor
  160779. JPP((j_decompress_ptr cinfo, int marker_code,
  160780. jpeg_marker_parser_method routine));
  160781. /* Read or write raw DCT coefficients --- useful for lossless transcoding. */
  160782. EXTERN(jvirt_barray_ptr *) jpeg_read_coefficients JPP((j_decompress_ptr cinfo));
  160783. EXTERN(void) jpeg_write_coefficients JPP((j_compress_ptr cinfo,
  160784. jvirt_barray_ptr * coef_arrays));
  160785. EXTERN(void) jpeg_copy_critical_parameters JPP((j_decompress_ptr srcinfo,
  160786. j_compress_ptr dstinfo));
  160787. /* If you choose to abort compression or decompression before completing
  160788. * jpeg_finish_(de)compress, then you need to clean up to release memory,
  160789. * temporary files, etc. You can just call jpeg_destroy_(de)compress
  160790. * if you're done with the JPEG object, but if you want to clean it up and
  160791. * reuse it, call this:
  160792. */
  160793. EXTERN(void) jpeg_abort_compress JPP((j_compress_ptr cinfo));
  160794. EXTERN(void) jpeg_abort_decompress JPP((j_decompress_ptr cinfo));
  160795. /* Generic versions of jpeg_abort and jpeg_destroy that work on either
  160796. * flavor of JPEG object. These may be more convenient in some places.
  160797. */
  160798. EXTERN(void) jpeg_abort JPP((j_common_ptr cinfo));
  160799. EXTERN(void) jpeg_destroy JPP((j_common_ptr cinfo));
  160800. /* Default restart-marker-resync procedure for use by data source modules */
  160801. EXTERN(boolean) jpeg_resync_to_restart JPP((j_decompress_ptr cinfo,
  160802. int desired));
  160803. /* These marker codes are exported since applications and data source modules
  160804. * are likely to want to use them.
  160805. */
  160806. #define JPEG_RST0 0xD0 /* RST0 marker code */
  160807. #define JPEG_EOI 0xD9 /* EOI marker code */
  160808. #define JPEG_APP0 0xE0 /* APP0 marker code */
  160809. #define JPEG_COM 0xFE /* COM marker code */
  160810. /* If we have a brain-damaged compiler that emits warnings (or worse, errors)
  160811. * for structure definitions that are never filled in, keep it quiet by
  160812. * supplying dummy definitions for the various substructures.
  160813. */
  160814. #ifdef INCOMPLETE_TYPES_BROKEN
  160815. #ifndef JPEG_INTERNALS /* will be defined in jpegint.h */
  160816. struct jvirt_sarray_control { long dummy; };
  160817. struct jvirt_barray_control { long dummy; };
  160818. struct jpeg_comp_master { long dummy; };
  160819. struct jpeg_c_main_controller { long dummy; };
  160820. struct jpeg_c_prep_controller { long dummy; };
  160821. struct jpeg_c_coef_controller { long dummy; };
  160822. struct jpeg_marker_writer { long dummy; };
  160823. struct jpeg_color_converter { long dummy; };
  160824. struct jpeg_downsampler { long dummy; };
  160825. struct jpeg_forward_dct { long dummy; };
  160826. struct jpeg_entropy_encoder { long dummy; };
  160827. struct jpeg_decomp_master { long dummy; };
  160828. struct jpeg_d_main_controller { long dummy; };
  160829. struct jpeg_d_coef_controller { long dummy; };
  160830. struct jpeg_d_post_controller { long dummy; };
  160831. struct jpeg_input_controller { long dummy; };
  160832. struct jpeg_marker_reader { long dummy; };
  160833. struct jpeg_entropy_decoder { long dummy; };
  160834. struct jpeg_inverse_dct { long dummy; };
  160835. struct jpeg_upsampler { long dummy; };
  160836. struct jpeg_color_deconverter { long dummy; };
  160837. struct jpeg_color_quantizer { long dummy; };
  160838. #endif /* JPEG_INTERNALS */
  160839. #endif /* INCOMPLETE_TYPES_BROKEN */
  160840. /*
  160841. * The JPEG library modules define JPEG_INTERNALS before including this file.
  160842. * The internal structure declarations are read only when that is true.
  160843. * Applications using the library should not include jpegint.h, but may wish
  160844. * to include jerror.h.
  160845. */
  160846. #ifdef JPEG_INTERNALS
  160847. /*** Start of inlined file: jpegint.h ***/
  160848. /* Declarations for both compression & decompression */
  160849. typedef enum { /* Operating modes for buffer controllers */
  160850. JBUF_PASS_THRU, /* Plain stripwise operation */
  160851. /* Remaining modes require a full-image buffer to have been created */
  160852. JBUF_SAVE_SOURCE, /* Run source subobject only, save output */
  160853. JBUF_CRANK_DEST, /* Run dest subobject only, using saved data */
  160854. JBUF_SAVE_AND_PASS /* Run both subobjects, save output */
  160855. } J_BUF_MODE;
  160856. /* Values of global_state field (jdapi.c has some dependencies on ordering!) */
  160857. #define CSTATE_START 100 /* after create_compress */
  160858. #define CSTATE_SCANNING 101 /* start_compress done, write_scanlines OK */
  160859. #define CSTATE_RAW_OK 102 /* start_compress done, write_raw_data OK */
  160860. #define CSTATE_WRCOEFS 103 /* jpeg_write_coefficients done */
  160861. #define DSTATE_START 200 /* after create_decompress */
  160862. #define DSTATE_INHEADER 201 /* reading header markers, no SOS yet */
  160863. #define DSTATE_READY 202 /* found SOS, ready for start_decompress */
  160864. #define DSTATE_PRELOAD 203 /* reading multiscan file in start_decompress*/
  160865. #define DSTATE_PRESCAN 204 /* performing dummy pass for 2-pass quant */
  160866. #define DSTATE_SCANNING 205 /* start_decompress done, read_scanlines OK */
  160867. #define DSTATE_RAW_OK 206 /* start_decompress done, read_raw_data OK */
  160868. #define DSTATE_BUFIMAGE 207 /* expecting jpeg_start_output */
  160869. #define DSTATE_BUFPOST 208 /* looking for SOS/EOI in jpeg_finish_output */
  160870. #define DSTATE_RDCOEFS 209 /* reading file in jpeg_read_coefficients */
  160871. #define DSTATE_STOPPING 210 /* looking for EOI in jpeg_finish_decompress */
  160872. /* Declarations for compression modules */
  160873. /* Master control module */
  160874. struct jpeg_comp_master {
  160875. JMETHOD(void, prepare_for_pass, (j_compress_ptr cinfo));
  160876. JMETHOD(void, pass_startup, (j_compress_ptr cinfo));
  160877. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  160878. /* State variables made visible to other modules */
  160879. boolean call_pass_startup; /* True if pass_startup must be called */
  160880. boolean is_last_pass; /* True during last pass */
  160881. };
  160882. /* Main buffer control (downsampled-data buffer) */
  160883. struct jpeg_c_main_controller {
  160884. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  160885. JMETHOD(void, process_data, (j_compress_ptr cinfo,
  160886. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  160887. JDIMENSION in_rows_avail));
  160888. };
  160889. /* Compression preprocessing (downsampling input buffer control) */
  160890. struct jpeg_c_prep_controller {
  160891. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  160892. JMETHOD(void, pre_process_data, (j_compress_ptr cinfo,
  160893. JSAMPARRAY input_buf,
  160894. JDIMENSION *in_row_ctr,
  160895. JDIMENSION in_rows_avail,
  160896. JSAMPIMAGE output_buf,
  160897. JDIMENSION *out_row_group_ctr,
  160898. JDIMENSION out_row_groups_avail));
  160899. };
  160900. /* Coefficient buffer control */
  160901. struct jpeg_c_coef_controller {
  160902. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  160903. JMETHOD(boolean, compress_data, (j_compress_ptr cinfo,
  160904. JSAMPIMAGE input_buf));
  160905. };
  160906. /* Colorspace conversion */
  160907. struct jpeg_color_converter {
  160908. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  160909. JMETHOD(void, color_convert, (j_compress_ptr cinfo,
  160910. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  160911. JDIMENSION output_row, int num_rows));
  160912. };
  160913. /* Downsampling */
  160914. struct jpeg_downsampler {
  160915. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  160916. JMETHOD(void, downsample, (j_compress_ptr cinfo,
  160917. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  160918. JSAMPIMAGE output_buf,
  160919. JDIMENSION out_row_group_index));
  160920. boolean need_context_rows; /* TRUE if need rows above & below */
  160921. };
  160922. /* Forward DCT (also controls coefficient quantization) */
  160923. struct jpeg_forward_dct {
  160924. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  160925. /* perhaps this should be an array??? */
  160926. JMETHOD(void, forward_DCT, (j_compress_ptr cinfo,
  160927. jpeg_component_info * compptr,
  160928. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  160929. JDIMENSION start_row, JDIMENSION start_col,
  160930. JDIMENSION num_blocks));
  160931. };
  160932. /* Entropy encoding */
  160933. struct jpeg_entropy_encoder {
  160934. JMETHOD(void, start_pass, (j_compress_ptr cinfo, boolean gather_statistics));
  160935. JMETHOD(boolean, encode_mcu, (j_compress_ptr cinfo, JBLOCKROW *MCU_data));
  160936. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  160937. };
  160938. /* Marker writing */
  160939. struct jpeg_marker_writer {
  160940. JMETHOD(void, write_file_header, (j_compress_ptr cinfo));
  160941. JMETHOD(void, write_frame_header, (j_compress_ptr cinfo));
  160942. JMETHOD(void, write_scan_header, (j_compress_ptr cinfo));
  160943. JMETHOD(void, write_file_trailer, (j_compress_ptr cinfo));
  160944. JMETHOD(void, write_tables_only, (j_compress_ptr cinfo));
  160945. /* These routines are exported to allow insertion of extra markers */
  160946. /* Probably only COM and APPn markers should be written this way */
  160947. JMETHOD(void, write_marker_header, (j_compress_ptr cinfo, int marker,
  160948. unsigned int datalen));
  160949. JMETHOD(void, write_marker_byte, (j_compress_ptr cinfo, int val));
  160950. };
  160951. /* Declarations for decompression modules */
  160952. /* Master control module */
  160953. struct jpeg_decomp_master {
  160954. JMETHOD(void, prepare_for_output_pass, (j_decompress_ptr cinfo));
  160955. JMETHOD(void, finish_output_pass, (j_decompress_ptr cinfo));
  160956. /* State variables made visible to other modules */
  160957. boolean is_dummy_pass; /* True during 1st pass for 2-pass quant */
  160958. };
  160959. /* Input control module */
  160960. struct jpeg_input_controller {
  160961. JMETHOD(int, consume_input, (j_decompress_ptr cinfo));
  160962. JMETHOD(void, reset_input_controller, (j_decompress_ptr cinfo));
  160963. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  160964. JMETHOD(void, finish_input_pass, (j_decompress_ptr cinfo));
  160965. /* State variables made visible to other modules */
  160966. boolean has_multiple_scans; /* True if file has multiple scans */
  160967. boolean eoi_reached; /* True when EOI has been consumed */
  160968. };
  160969. /* Main buffer control (downsampled-data buffer) */
  160970. struct jpeg_d_main_controller {
  160971. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  160972. JMETHOD(void, process_data, (j_decompress_ptr cinfo,
  160973. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  160974. JDIMENSION out_rows_avail));
  160975. };
  160976. /* Coefficient buffer control */
  160977. struct jpeg_d_coef_controller {
  160978. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  160979. JMETHOD(int, consume_data, (j_decompress_ptr cinfo));
  160980. JMETHOD(void, start_output_pass, (j_decompress_ptr cinfo));
  160981. JMETHOD(int, decompress_data, (j_decompress_ptr cinfo,
  160982. JSAMPIMAGE output_buf));
  160983. /* Pointer to array of coefficient virtual arrays, or NULL if none */
  160984. jvirt_barray_ptr *coef_arrays;
  160985. };
  160986. /* Decompression postprocessing (color quantization buffer control) */
  160987. struct jpeg_d_post_controller {
  160988. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  160989. JMETHOD(void, post_process_data, (j_decompress_ptr cinfo,
  160990. JSAMPIMAGE input_buf,
  160991. JDIMENSION *in_row_group_ctr,
  160992. JDIMENSION in_row_groups_avail,
  160993. JSAMPARRAY output_buf,
  160994. JDIMENSION *out_row_ctr,
  160995. JDIMENSION out_rows_avail));
  160996. };
  160997. /* Marker reading & parsing */
  160998. struct jpeg_marker_reader {
  160999. JMETHOD(void, reset_marker_reader, (j_decompress_ptr cinfo));
  161000. /* Read markers until SOS or EOI.
  161001. * Returns same codes as are defined for jpeg_consume_input:
  161002. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  161003. */
  161004. JMETHOD(int, read_markers, (j_decompress_ptr cinfo));
  161005. /* Read a restart marker --- exported for use by entropy decoder only */
  161006. jpeg_marker_parser_method read_restart_marker;
  161007. /* State of marker reader --- nominally internal, but applications
  161008. * supplying COM or APPn handlers might like to know the state.
  161009. */
  161010. boolean saw_SOI; /* found SOI? */
  161011. boolean saw_SOF; /* found SOF? */
  161012. int next_restart_num; /* next restart number expected (0-7) */
  161013. unsigned int discarded_bytes; /* # of bytes skipped looking for a marker */
  161014. };
  161015. /* Entropy decoding */
  161016. struct jpeg_entropy_decoder {
  161017. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  161018. JMETHOD(boolean, decode_mcu, (j_decompress_ptr cinfo,
  161019. JBLOCKROW *MCU_data));
  161020. /* This is here to share code between baseline and progressive decoders; */
  161021. /* other modules probably should not use it */
  161022. boolean insufficient_data; /* set TRUE after emitting warning */
  161023. };
  161024. /* Inverse DCT (also performs dequantization) */
  161025. typedef JMETHOD(void, inverse_DCT_method_ptr,
  161026. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  161027. JCOEFPTR coef_block,
  161028. JSAMPARRAY output_buf, JDIMENSION output_col));
  161029. struct jpeg_inverse_dct {
  161030. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  161031. /* It is useful to allow each component to have a separate IDCT method. */
  161032. inverse_DCT_method_ptr inverse_DCT[MAX_COMPONENTS];
  161033. };
  161034. /* Upsampling (note that upsampler must also call color converter) */
  161035. struct jpeg_upsampler {
  161036. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  161037. JMETHOD(void, upsample, (j_decompress_ptr cinfo,
  161038. JSAMPIMAGE input_buf,
  161039. JDIMENSION *in_row_group_ctr,
  161040. JDIMENSION in_row_groups_avail,
  161041. JSAMPARRAY output_buf,
  161042. JDIMENSION *out_row_ctr,
  161043. JDIMENSION out_rows_avail));
  161044. boolean need_context_rows; /* TRUE if need rows above & below */
  161045. };
  161046. /* Colorspace conversion */
  161047. struct jpeg_color_deconverter {
  161048. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  161049. JMETHOD(void, color_convert, (j_decompress_ptr cinfo,
  161050. JSAMPIMAGE input_buf, JDIMENSION input_row,
  161051. JSAMPARRAY output_buf, int num_rows));
  161052. };
  161053. /* Color quantization or color precision reduction */
  161054. struct jpeg_color_quantizer {
  161055. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, boolean is_pre_scan));
  161056. JMETHOD(void, color_quantize, (j_decompress_ptr cinfo,
  161057. JSAMPARRAY input_buf, JSAMPARRAY output_buf,
  161058. int num_rows));
  161059. JMETHOD(void, finish_pass, (j_decompress_ptr cinfo));
  161060. JMETHOD(void, new_color_map, (j_decompress_ptr cinfo));
  161061. };
  161062. /* Miscellaneous useful macros */
  161063. #undef MAX
  161064. #define MAX(a,b) ((a) > (b) ? (a) : (b))
  161065. #undef MIN
  161066. #define MIN(a,b) ((a) < (b) ? (a) : (b))
  161067. /* We assume that right shift corresponds to signed division by 2 with
  161068. * rounding towards minus infinity. This is correct for typical "arithmetic
  161069. * shift" instructions that shift in copies of the sign bit. But some
  161070. * C compilers implement >> with an unsigned shift. For these machines you
  161071. * must define RIGHT_SHIFT_IS_UNSIGNED.
  161072. * RIGHT_SHIFT provides a proper signed right shift of an INT32 quantity.
  161073. * It is only applied with constant shift counts. SHIFT_TEMPS must be
  161074. * included in the variables of any routine using RIGHT_SHIFT.
  161075. */
  161076. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  161077. #define SHIFT_TEMPS INT32 shift_temp;
  161078. #define RIGHT_SHIFT(x,shft) \
  161079. ((shift_temp = (x)) < 0 ? \
  161080. (shift_temp >> (shft)) | ((~((INT32) 0)) << (32-(shft))) : \
  161081. (shift_temp >> (shft)))
  161082. #else
  161083. #define SHIFT_TEMPS
  161084. #define RIGHT_SHIFT(x,shft) ((x) >> (shft))
  161085. #endif
  161086. /* Short forms of external names for systems with brain-damaged linkers. */
  161087. #ifdef NEED_SHORT_EXTERNAL_NAMES
  161088. #define jinit_compress_master jICompress
  161089. #define jinit_c_master_control jICMaster
  161090. #define jinit_c_main_controller jICMainC
  161091. #define jinit_c_prep_controller jICPrepC
  161092. #define jinit_c_coef_controller jICCoefC
  161093. #define jinit_color_converter jICColor
  161094. #define jinit_downsampler jIDownsampler
  161095. #define jinit_forward_dct jIFDCT
  161096. #define jinit_huff_encoder jIHEncoder
  161097. #define jinit_phuff_encoder jIPHEncoder
  161098. #define jinit_marker_writer jIMWriter
  161099. #define jinit_master_decompress jIDMaster
  161100. #define jinit_d_main_controller jIDMainC
  161101. #define jinit_d_coef_controller jIDCoefC
  161102. #define jinit_d_post_controller jIDPostC
  161103. #define jinit_input_controller jIInCtlr
  161104. #define jinit_marker_reader jIMReader
  161105. #define jinit_huff_decoder jIHDecoder
  161106. #define jinit_phuff_decoder jIPHDecoder
  161107. #define jinit_inverse_dct jIIDCT
  161108. #define jinit_upsampler jIUpsampler
  161109. #define jinit_color_deconverter jIDColor
  161110. #define jinit_1pass_quantizer jI1Quant
  161111. #define jinit_2pass_quantizer jI2Quant
  161112. #define jinit_merged_upsampler jIMUpsampler
  161113. #define jinit_memory_mgr jIMemMgr
  161114. #define jdiv_round_up jDivRound
  161115. #define jround_up jRound
  161116. #define jcopy_sample_rows jCopySamples
  161117. #define jcopy_block_row jCopyBlocks
  161118. #define jzero_far jZeroFar
  161119. #define jpeg_zigzag_order jZIGTable
  161120. #define jpeg_natural_order jZAGTable
  161121. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  161122. /* Compression module initialization routines */
  161123. EXTERN(void) jinit_compress_master JPP((j_compress_ptr cinfo));
  161124. EXTERN(void) jinit_c_master_control JPP((j_compress_ptr cinfo,
  161125. boolean transcode_only));
  161126. EXTERN(void) jinit_c_main_controller JPP((j_compress_ptr cinfo,
  161127. boolean need_full_buffer));
  161128. EXTERN(void) jinit_c_prep_controller JPP((j_compress_ptr cinfo,
  161129. boolean need_full_buffer));
  161130. EXTERN(void) jinit_c_coef_controller JPP((j_compress_ptr cinfo,
  161131. boolean need_full_buffer));
  161132. EXTERN(void) jinit_color_converter JPP((j_compress_ptr cinfo));
  161133. EXTERN(void) jinit_downsampler JPP((j_compress_ptr cinfo));
  161134. EXTERN(void) jinit_forward_dct JPP((j_compress_ptr cinfo));
  161135. EXTERN(void) jinit_huff_encoder JPP((j_compress_ptr cinfo));
  161136. EXTERN(void) jinit_phuff_encoder JPP((j_compress_ptr cinfo));
  161137. EXTERN(void) jinit_marker_writer JPP((j_compress_ptr cinfo));
  161138. /* Decompression module initialization routines */
  161139. EXTERN(void) jinit_master_decompress JPP((j_decompress_ptr cinfo));
  161140. EXTERN(void) jinit_d_main_controller JPP((j_decompress_ptr cinfo,
  161141. boolean need_full_buffer));
  161142. EXTERN(void) jinit_d_coef_controller JPP((j_decompress_ptr cinfo,
  161143. boolean need_full_buffer));
  161144. EXTERN(void) jinit_d_post_controller JPP((j_decompress_ptr cinfo,
  161145. boolean need_full_buffer));
  161146. EXTERN(void) jinit_input_controller JPP((j_decompress_ptr cinfo));
  161147. EXTERN(void) jinit_marker_reader JPP((j_decompress_ptr cinfo));
  161148. EXTERN(void) jinit_huff_decoder JPP((j_decompress_ptr cinfo));
  161149. EXTERN(void) jinit_phuff_decoder JPP((j_decompress_ptr cinfo));
  161150. EXTERN(void) jinit_inverse_dct JPP((j_decompress_ptr cinfo));
  161151. EXTERN(void) jinit_upsampler JPP((j_decompress_ptr cinfo));
  161152. EXTERN(void) jinit_color_deconverter JPP((j_decompress_ptr cinfo));
  161153. EXTERN(void) jinit_1pass_quantizer JPP((j_decompress_ptr cinfo));
  161154. EXTERN(void) jinit_2pass_quantizer JPP((j_decompress_ptr cinfo));
  161155. EXTERN(void) jinit_merged_upsampler JPP((j_decompress_ptr cinfo));
  161156. /* Memory manager initialization */
  161157. EXTERN(void) jinit_memory_mgr JPP((j_common_ptr cinfo));
  161158. /* Utility routines in jutils.c */
  161159. EXTERN(long) jdiv_round_up JPP((long a, long b));
  161160. EXTERN(long) jround_up JPP((long a, long b));
  161161. EXTERN(void) jcopy_sample_rows JPP((JSAMPARRAY input_array, int source_row,
  161162. JSAMPARRAY output_array, int dest_row,
  161163. int num_rows, JDIMENSION num_cols));
  161164. EXTERN(void) jcopy_block_row JPP((JBLOCKROW input_row, JBLOCKROW output_row,
  161165. JDIMENSION num_blocks));
  161166. EXTERN(void) jzero_far JPP((void FAR * target, size_t bytestozero));
  161167. /* Constant tables in jutils.c */
  161168. #if 0 /* This table is not actually needed in v6a */
  161169. extern const int jpeg_zigzag_order[]; /* natural coef order to zigzag order */
  161170. #endif
  161171. extern const int jpeg_natural_order[]; /* zigzag coef order to natural order */
  161172. /* Suppress undefined-structure complaints if necessary. */
  161173. #ifdef INCOMPLETE_TYPES_BROKEN
  161174. #ifndef AM_MEMORY_MANAGER /* only jmemmgr.c defines these */
  161175. struct jvirt_sarray_control { long dummy; };
  161176. struct jvirt_barray_control { long dummy; };
  161177. #endif
  161178. #endif /* INCOMPLETE_TYPES_BROKEN */
  161179. /*** End of inlined file: jpegint.h ***/
  161180. /* fetch private declarations */
  161181. /*** Start of inlined file: jerror.h ***/
  161182. /*
  161183. * To define the enum list of message codes, include this file without
  161184. * defining macro JMESSAGE. To create a message string table, include it
  161185. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  161186. */
  161187. #ifndef JMESSAGE
  161188. #ifndef JERROR_H
  161189. /* First time through, define the enum list */
  161190. #define JMAKE_ENUM_LIST
  161191. #else
  161192. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  161193. #define JMESSAGE(code,string)
  161194. #endif /* JERROR_H */
  161195. #endif /* JMESSAGE */
  161196. #ifdef JMAKE_ENUM_LIST
  161197. typedef enum {
  161198. #define JMESSAGE(code,string) code ,
  161199. #endif /* JMAKE_ENUM_LIST */
  161200. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  161201. /* For maintenance convenience, list is alphabetical by message code name */
  161202. JMESSAGE(JERR_ARITH_NOTIMPL,
  161203. "Sorry, there are legal restrictions on arithmetic coding")
  161204. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  161205. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  161206. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  161207. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  161208. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  161209. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  161210. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  161211. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  161212. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  161213. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  161214. JMESSAGE(JERR_BAD_LIB_VERSION,
  161215. "Wrong JPEG library version: library is %d, caller expects %d")
  161216. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  161217. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  161218. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  161219. JMESSAGE(JERR_BAD_PROGRESSION,
  161220. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  161221. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  161222. "Invalid progressive parameters at scan script entry %d")
  161223. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  161224. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  161225. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  161226. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  161227. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  161228. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  161229. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  161230. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  161231. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  161232. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  161233. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  161234. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  161235. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  161236. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  161237. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  161238. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  161239. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  161240. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  161241. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  161242. JMESSAGE(JERR_FILE_READ, "Input file read error")
  161243. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  161244. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  161245. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  161246. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  161247. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  161248. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  161249. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  161250. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  161251. "Cannot transcode due to multiple use of quantization table %d")
  161252. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  161253. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  161254. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  161255. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  161256. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  161257. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  161258. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  161259. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  161260. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  161261. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  161262. JMESSAGE(JERR_QUANT_COMPONENTS,
  161263. "Cannot quantize more than %d color components")
  161264. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  161265. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  161266. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  161267. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  161268. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  161269. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  161270. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  161271. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  161272. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  161273. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  161274. JMESSAGE(JERR_TFILE_WRITE,
  161275. "Write failed on temporary file --- out of disk space?")
  161276. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  161277. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  161278. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  161279. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  161280. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  161281. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  161282. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  161283. JMESSAGE(JMSG_VERSION, JVERSION)
  161284. JMESSAGE(JTRC_16BIT_TABLES,
  161285. "Caution: quantization tables are too coarse for baseline JPEG")
  161286. JMESSAGE(JTRC_ADOBE,
  161287. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  161288. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  161289. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  161290. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  161291. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  161292. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  161293. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  161294. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  161295. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  161296. JMESSAGE(JTRC_EOI, "End Of Image")
  161297. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  161298. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  161299. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  161300. "Warning: thumbnail image size does not match data length %u")
  161301. JMESSAGE(JTRC_JFIF_EXTENSION,
  161302. "JFIF extension marker: type 0x%02x, length %u")
  161303. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  161304. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  161305. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  161306. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  161307. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  161308. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  161309. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  161310. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  161311. JMESSAGE(JTRC_RST, "RST%d")
  161312. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  161313. "Smoothing not supported with nonstandard sampling ratios")
  161314. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  161315. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  161316. JMESSAGE(JTRC_SOI, "Start of Image")
  161317. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  161318. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  161319. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  161320. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  161321. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  161322. JMESSAGE(JTRC_THUMB_JPEG,
  161323. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  161324. JMESSAGE(JTRC_THUMB_PALETTE,
  161325. "JFIF extension marker: palette thumbnail image, length %u")
  161326. JMESSAGE(JTRC_THUMB_RGB,
  161327. "JFIF extension marker: RGB thumbnail image, length %u")
  161328. JMESSAGE(JTRC_UNKNOWN_IDS,
  161329. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  161330. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  161331. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  161332. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  161333. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  161334. "Inconsistent progression sequence for component %d coefficient %d")
  161335. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  161336. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  161337. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  161338. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  161339. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  161340. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  161341. JMESSAGE(JWRN_MUST_RESYNC,
  161342. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  161343. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  161344. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  161345. #ifdef JMAKE_ENUM_LIST
  161346. JMSG_LASTMSGCODE
  161347. } J_MESSAGE_CODE;
  161348. #undef JMAKE_ENUM_LIST
  161349. #endif /* JMAKE_ENUM_LIST */
  161350. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  161351. #undef JMESSAGE
  161352. #ifndef JERROR_H
  161353. #define JERROR_H
  161354. /* Macros to simplify using the error and trace message stuff */
  161355. /* The first parameter is either type of cinfo pointer */
  161356. /* Fatal errors (print message and exit) */
  161357. #define ERREXIT(cinfo,code) \
  161358. ((cinfo)->err->msg_code = (code), \
  161359. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161360. #define ERREXIT1(cinfo,code,p1) \
  161361. ((cinfo)->err->msg_code = (code), \
  161362. (cinfo)->err->msg_parm.i[0] = (p1), \
  161363. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161364. #define ERREXIT2(cinfo,code,p1,p2) \
  161365. ((cinfo)->err->msg_code = (code), \
  161366. (cinfo)->err->msg_parm.i[0] = (p1), \
  161367. (cinfo)->err->msg_parm.i[1] = (p2), \
  161368. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161369. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  161370. ((cinfo)->err->msg_code = (code), \
  161371. (cinfo)->err->msg_parm.i[0] = (p1), \
  161372. (cinfo)->err->msg_parm.i[1] = (p2), \
  161373. (cinfo)->err->msg_parm.i[2] = (p3), \
  161374. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161375. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  161376. ((cinfo)->err->msg_code = (code), \
  161377. (cinfo)->err->msg_parm.i[0] = (p1), \
  161378. (cinfo)->err->msg_parm.i[1] = (p2), \
  161379. (cinfo)->err->msg_parm.i[2] = (p3), \
  161380. (cinfo)->err->msg_parm.i[3] = (p4), \
  161381. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161382. #define ERREXITS(cinfo,code,str) \
  161383. ((cinfo)->err->msg_code = (code), \
  161384. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  161385. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161386. #define MAKESTMT(stuff) do { stuff } while (0)
  161387. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  161388. #define WARNMS(cinfo,code) \
  161389. ((cinfo)->err->msg_code = (code), \
  161390. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  161391. #define WARNMS1(cinfo,code,p1) \
  161392. ((cinfo)->err->msg_code = (code), \
  161393. (cinfo)->err->msg_parm.i[0] = (p1), \
  161394. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  161395. #define WARNMS2(cinfo,code,p1,p2) \
  161396. ((cinfo)->err->msg_code = (code), \
  161397. (cinfo)->err->msg_parm.i[0] = (p1), \
  161398. (cinfo)->err->msg_parm.i[1] = (p2), \
  161399. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  161400. /* Informational/debugging messages */
  161401. #define TRACEMS(cinfo,lvl,code) \
  161402. ((cinfo)->err->msg_code = (code), \
  161403. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161404. #define TRACEMS1(cinfo,lvl,code,p1) \
  161405. ((cinfo)->err->msg_code = (code), \
  161406. (cinfo)->err->msg_parm.i[0] = (p1), \
  161407. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161408. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  161409. ((cinfo)->err->msg_code = (code), \
  161410. (cinfo)->err->msg_parm.i[0] = (p1), \
  161411. (cinfo)->err->msg_parm.i[1] = (p2), \
  161412. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161413. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  161414. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161415. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  161416. (cinfo)->err->msg_code = (code); \
  161417. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161418. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  161419. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161420. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161421. (cinfo)->err->msg_code = (code); \
  161422. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161423. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  161424. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161425. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161426. _mp[4] = (p5); \
  161427. (cinfo)->err->msg_code = (code); \
  161428. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161429. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  161430. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161431. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161432. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  161433. (cinfo)->err->msg_code = (code); \
  161434. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161435. #define TRACEMSS(cinfo,lvl,code,str) \
  161436. ((cinfo)->err->msg_code = (code), \
  161437. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  161438. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161439. #endif /* JERROR_H */
  161440. /*** End of inlined file: jerror.h ***/
  161441. /* fetch error codes too */
  161442. #endif
  161443. #endif /* JPEGLIB_H */
  161444. /*** End of inlined file: jpeglib.h ***/
  161445. /*** Start of inlined file: jcapimin.c ***/
  161446. #define JPEG_INTERNALS
  161447. /*** Start of inlined file: jinclude.h ***/
  161448. /* Include auto-config file to find out which system include files we need. */
  161449. #ifndef __jinclude_h__
  161450. #define __jinclude_h__
  161451. /*** Start of inlined file: jconfig.h ***/
  161452. /* see jconfig.doc for explanations */
  161453. // disable all the warnings under MSVC
  161454. #ifdef _MSC_VER
  161455. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  161456. #endif
  161457. #ifdef __BORLANDC__
  161458. #pragma warn -8057
  161459. #pragma warn -8019
  161460. #pragma warn -8004
  161461. #pragma warn -8008
  161462. #endif
  161463. #define HAVE_PROTOTYPES
  161464. #define HAVE_UNSIGNED_CHAR
  161465. #define HAVE_UNSIGNED_SHORT
  161466. /* #define void char */
  161467. /* #define const */
  161468. #undef CHAR_IS_UNSIGNED
  161469. #define HAVE_STDDEF_H
  161470. #define HAVE_STDLIB_H
  161471. #undef NEED_BSD_STRINGS
  161472. #undef NEED_SYS_TYPES_H
  161473. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  161474. #undef NEED_SHORT_EXTERNAL_NAMES
  161475. #undef INCOMPLETE_TYPES_BROKEN
  161476. /* Define "boolean" as unsigned char, not int, per Windows custom */
  161477. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  161478. typedef unsigned char boolean;
  161479. #endif
  161480. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  161481. #ifdef JPEG_INTERNALS
  161482. #undef RIGHT_SHIFT_IS_UNSIGNED
  161483. #endif /* JPEG_INTERNALS */
  161484. #ifdef JPEG_CJPEG_DJPEG
  161485. #define BMP_SUPPORTED /* BMP image file format */
  161486. #define GIF_SUPPORTED /* GIF image file format */
  161487. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  161488. #undef RLE_SUPPORTED /* Utah RLE image file format */
  161489. #define TARGA_SUPPORTED /* Targa image file format */
  161490. #define TWO_FILE_COMMANDLINE /* optional */
  161491. #define USE_SETMODE /* Microsoft has setmode() */
  161492. #undef NEED_SIGNAL_CATCHER
  161493. #undef DONT_USE_B_MODE
  161494. #undef PROGRESS_REPORT /* optional */
  161495. #endif /* JPEG_CJPEG_DJPEG */
  161496. /*** End of inlined file: jconfig.h ***/
  161497. /* auto configuration options */
  161498. #define JCONFIG_INCLUDED /* so that jpeglib.h doesn't do it again */
  161499. /*
  161500. * We need the NULL macro and size_t typedef.
  161501. * On an ANSI-conforming system it is sufficient to include <stddef.h>.
  161502. * Otherwise, we get them from <stdlib.h> or <stdio.h>; we may have to
  161503. * pull in <sys/types.h> as well.
  161504. * Note that the core JPEG library does not require <stdio.h>;
  161505. * only the default error handler and data source/destination modules do.
  161506. * But we must pull it in because of the references to FILE in jpeglib.h.
  161507. * You can remove those references if you want to compile without <stdio.h>.
  161508. */
  161509. #ifdef HAVE_STDDEF_H
  161510. #include <stddef.h>
  161511. #endif
  161512. #ifdef HAVE_STDLIB_H
  161513. #include <stdlib.h>
  161514. #endif
  161515. #ifdef NEED_SYS_TYPES_H
  161516. #include <sys/types.h>
  161517. #endif
  161518. #include <stdio.h>
  161519. /*
  161520. * We need memory copying and zeroing functions, plus strncpy().
  161521. * ANSI and System V implementations declare these in <string.h>.
  161522. * BSD doesn't have the mem() functions, but it does have bcopy()/bzero().
  161523. * Some systems may declare memset and memcpy in <memory.h>.
  161524. *
  161525. * NOTE: we assume the size parameters to these functions are of type size_t.
  161526. * Change the casts in these macros if not!
  161527. */
  161528. #ifdef NEED_BSD_STRINGS
  161529. #include <strings.h>
  161530. #define MEMZERO(target,size) bzero((void *)(target), (size_t)(size))
  161531. #define MEMCOPY(dest,src,size) bcopy((const void *)(src), (void *)(dest), (size_t)(size))
  161532. #else /* not BSD, assume ANSI/SysV string lib */
  161533. #include <string.h>
  161534. #define MEMZERO(target,size) memset((void *)(target), 0, (size_t)(size))
  161535. #define MEMCOPY(dest,src,size) memcpy((void *)(dest), (const void *)(src), (size_t)(size))
  161536. #endif
  161537. /*
  161538. * In ANSI C, and indeed any rational implementation, size_t is also the
  161539. * type returned by sizeof(). However, it seems there are some irrational
  161540. * implementations out there, in which sizeof() returns an int even though
  161541. * size_t is defined as long or unsigned long. To ensure consistent results
  161542. * we always use this SIZEOF() macro in place of using sizeof() directly.
  161543. */
  161544. #define SIZEOF(object) ((size_t) sizeof(object))
  161545. /*
  161546. * The modules that use fread() and fwrite() always invoke them through
  161547. * these macros. On some systems you may need to twiddle the argument casts.
  161548. * CAUTION: argument order is different from underlying functions!
  161549. */
  161550. #define JFREAD(file,buf,sizeofbuf) \
  161551. ((size_t) fread((void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  161552. #define JFWRITE(file,buf,sizeofbuf) \
  161553. ((size_t) fwrite((const void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  161554. typedef enum { /* JPEG marker codes */
  161555. M_SOF0 = 0xc0,
  161556. M_SOF1 = 0xc1,
  161557. M_SOF2 = 0xc2,
  161558. M_SOF3 = 0xc3,
  161559. M_SOF5 = 0xc5,
  161560. M_SOF6 = 0xc6,
  161561. M_SOF7 = 0xc7,
  161562. M_JPG = 0xc8,
  161563. M_SOF9 = 0xc9,
  161564. M_SOF10 = 0xca,
  161565. M_SOF11 = 0xcb,
  161566. M_SOF13 = 0xcd,
  161567. M_SOF14 = 0xce,
  161568. M_SOF15 = 0xcf,
  161569. M_DHT = 0xc4,
  161570. M_DAC = 0xcc,
  161571. M_RST0 = 0xd0,
  161572. M_RST1 = 0xd1,
  161573. M_RST2 = 0xd2,
  161574. M_RST3 = 0xd3,
  161575. M_RST4 = 0xd4,
  161576. M_RST5 = 0xd5,
  161577. M_RST6 = 0xd6,
  161578. M_RST7 = 0xd7,
  161579. M_SOI = 0xd8,
  161580. M_EOI = 0xd9,
  161581. M_SOS = 0xda,
  161582. M_DQT = 0xdb,
  161583. M_DNL = 0xdc,
  161584. M_DRI = 0xdd,
  161585. M_DHP = 0xde,
  161586. M_EXP = 0xdf,
  161587. M_APP0 = 0xe0,
  161588. M_APP1 = 0xe1,
  161589. M_APP2 = 0xe2,
  161590. M_APP3 = 0xe3,
  161591. M_APP4 = 0xe4,
  161592. M_APP5 = 0xe5,
  161593. M_APP6 = 0xe6,
  161594. M_APP7 = 0xe7,
  161595. M_APP8 = 0xe8,
  161596. M_APP9 = 0xe9,
  161597. M_APP10 = 0xea,
  161598. M_APP11 = 0xeb,
  161599. M_APP12 = 0xec,
  161600. M_APP13 = 0xed,
  161601. M_APP14 = 0xee,
  161602. M_APP15 = 0xef,
  161603. M_JPG0 = 0xf0,
  161604. M_JPG13 = 0xfd,
  161605. M_COM = 0xfe,
  161606. M_TEM = 0x01,
  161607. M_ERROR = 0x100
  161608. } JPEG_MARKER;
  161609. /*
  161610. * Figure F.12: extend sign bit.
  161611. * On some machines, a shift and add will be faster than a table lookup.
  161612. */
  161613. #ifdef AVOID_TABLES
  161614. #define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
  161615. #else
  161616. #define HUFF_EXTEND(x,s) ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
  161617. static const int extend_test[16] = /* entry n is 2**(n-1) */
  161618. { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
  161619. 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
  161620. static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
  161621. { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
  161622. ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
  161623. ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
  161624. ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
  161625. #endif /* AVOID_TABLES */
  161626. #endif
  161627. /*** End of inlined file: jinclude.h ***/
  161628. /*
  161629. * Initialization of a JPEG compression object.
  161630. * The error manager must already be set up (in case memory manager fails).
  161631. */
  161632. GLOBAL(void)
  161633. jpeg_CreateCompress (j_compress_ptr cinfo, int version, size_t structsize)
  161634. {
  161635. int i;
  161636. /* Guard against version mismatches between library and caller. */
  161637. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  161638. if (version != JPEG_LIB_VERSION)
  161639. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  161640. if (structsize != SIZEOF(struct jpeg_compress_struct))
  161641. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  161642. (int) SIZEOF(struct jpeg_compress_struct), (int) structsize);
  161643. /* For debugging purposes, we zero the whole master structure.
  161644. * But the application has already set the err pointer, and may have set
  161645. * client_data, so we have to save and restore those fields.
  161646. * Note: if application hasn't set client_data, tools like Purify may
  161647. * complain here.
  161648. */
  161649. {
  161650. struct jpeg_error_mgr * err = cinfo->err;
  161651. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  161652. MEMZERO(cinfo, SIZEOF(struct jpeg_compress_struct));
  161653. cinfo->err = err;
  161654. cinfo->client_data = client_data;
  161655. }
  161656. cinfo->is_decompressor = FALSE;
  161657. /* Initialize a memory manager instance for this object */
  161658. jinit_memory_mgr((j_common_ptr) cinfo);
  161659. /* Zero out pointers to permanent structures. */
  161660. cinfo->progress = NULL;
  161661. cinfo->dest = NULL;
  161662. cinfo->comp_info = NULL;
  161663. for (i = 0; i < NUM_QUANT_TBLS; i++)
  161664. cinfo->quant_tbl_ptrs[i] = NULL;
  161665. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  161666. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  161667. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  161668. }
  161669. cinfo->script_space = NULL;
  161670. cinfo->input_gamma = 1.0; /* in case application forgets */
  161671. /* OK, I'm ready */
  161672. cinfo->global_state = CSTATE_START;
  161673. }
  161674. /*
  161675. * Destruction of a JPEG compression object
  161676. */
  161677. GLOBAL(void)
  161678. jpeg_destroy_compress (j_compress_ptr cinfo)
  161679. {
  161680. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  161681. }
  161682. /*
  161683. * Abort processing of a JPEG compression operation,
  161684. * but don't destroy the object itself.
  161685. */
  161686. GLOBAL(void)
  161687. jpeg_abort_compress (j_compress_ptr cinfo)
  161688. {
  161689. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  161690. }
  161691. /*
  161692. * Forcibly suppress or un-suppress all quantization and Huffman tables.
  161693. * Marks all currently defined tables as already written (if suppress)
  161694. * or not written (if !suppress). This will control whether they get emitted
  161695. * by a subsequent jpeg_start_compress call.
  161696. *
  161697. * This routine is exported for use by applications that want to produce
  161698. * abbreviated JPEG datastreams. It logically belongs in jcparam.c, but
  161699. * since it is called by jpeg_start_compress, we put it here --- otherwise
  161700. * jcparam.o would be linked whether the application used it or not.
  161701. */
  161702. GLOBAL(void)
  161703. jpeg_suppress_tables (j_compress_ptr cinfo, boolean suppress)
  161704. {
  161705. int i;
  161706. JQUANT_TBL * qtbl;
  161707. JHUFF_TBL * htbl;
  161708. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  161709. if ((qtbl = cinfo->quant_tbl_ptrs[i]) != NULL)
  161710. qtbl->sent_table = suppress;
  161711. }
  161712. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  161713. if ((htbl = cinfo->dc_huff_tbl_ptrs[i]) != NULL)
  161714. htbl->sent_table = suppress;
  161715. if ((htbl = cinfo->ac_huff_tbl_ptrs[i]) != NULL)
  161716. htbl->sent_table = suppress;
  161717. }
  161718. }
  161719. /*
  161720. * Finish JPEG compression.
  161721. *
  161722. * If a multipass operating mode was selected, this may do a great deal of
  161723. * work including most of the actual output.
  161724. */
  161725. GLOBAL(void)
  161726. jpeg_finish_compress (j_compress_ptr cinfo)
  161727. {
  161728. JDIMENSION iMCU_row;
  161729. if (cinfo->global_state == CSTATE_SCANNING ||
  161730. cinfo->global_state == CSTATE_RAW_OK) {
  161731. /* Terminate first pass */
  161732. if (cinfo->next_scanline < cinfo->image_height)
  161733. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  161734. (*cinfo->master->finish_pass) (cinfo);
  161735. } else if (cinfo->global_state != CSTATE_WRCOEFS)
  161736. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161737. /* Perform any remaining passes */
  161738. while (! cinfo->master->is_last_pass) {
  161739. (*cinfo->master->prepare_for_pass) (cinfo);
  161740. for (iMCU_row = 0; iMCU_row < cinfo->total_iMCU_rows; iMCU_row++) {
  161741. if (cinfo->progress != NULL) {
  161742. cinfo->progress->pass_counter = (long) iMCU_row;
  161743. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows;
  161744. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161745. }
  161746. /* We bypass the main controller and invoke coef controller directly;
  161747. * all work is being done from the coefficient buffer.
  161748. */
  161749. if (! (*cinfo->coef->compress_data) (cinfo, (JSAMPIMAGE) NULL))
  161750. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  161751. }
  161752. (*cinfo->master->finish_pass) (cinfo);
  161753. }
  161754. /* Write EOI, do final cleanup */
  161755. (*cinfo->marker->write_file_trailer) (cinfo);
  161756. (*cinfo->dest->term_destination) (cinfo);
  161757. /* We can use jpeg_abort to release memory and reset global_state */
  161758. jpeg_abort((j_common_ptr) cinfo);
  161759. }
  161760. /*
  161761. * Write a special marker.
  161762. * This is only recommended for writing COM or APPn markers.
  161763. * Must be called after jpeg_start_compress() and before
  161764. * first call to jpeg_write_scanlines() or jpeg_write_raw_data().
  161765. */
  161766. GLOBAL(void)
  161767. jpeg_write_marker (j_compress_ptr cinfo, int marker,
  161768. const JOCTET *dataptr, unsigned int datalen)
  161769. {
  161770. JMETHOD(void, write_marker_byte, (j_compress_ptr info, int val));
  161771. if (cinfo->next_scanline != 0 ||
  161772. (cinfo->global_state != CSTATE_SCANNING &&
  161773. cinfo->global_state != CSTATE_RAW_OK &&
  161774. cinfo->global_state != CSTATE_WRCOEFS))
  161775. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161776. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  161777. write_marker_byte = cinfo->marker->write_marker_byte; /* copy for speed */
  161778. while (datalen--) {
  161779. (*write_marker_byte) (cinfo, *dataptr);
  161780. dataptr++;
  161781. }
  161782. }
  161783. /* Same, but piecemeal. */
  161784. GLOBAL(void)
  161785. jpeg_write_m_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  161786. {
  161787. if (cinfo->next_scanline != 0 ||
  161788. (cinfo->global_state != CSTATE_SCANNING &&
  161789. cinfo->global_state != CSTATE_RAW_OK &&
  161790. cinfo->global_state != CSTATE_WRCOEFS))
  161791. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161792. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  161793. }
  161794. GLOBAL(void)
  161795. jpeg_write_m_byte (j_compress_ptr cinfo, int val)
  161796. {
  161797. (*cinfo->marker->write_marker_byte) (cinfo, val);
  161798. }
  161799. /*
  161800. * Alternate compression function: just write an abbreviated table file.
  161801. * Before calling this, all parameters and a data destination must be set up.
  161802. *
  161803. * To produce a pair of files containing abbreviated tables and abbreviated
  161804. * image data, one would proceed as follows:
  161805. *
  161806. * initialize JPEG object
  161807. * set JPEG parameters
  161808. * set destination to table file
  161809. * jpeg_write_tables(cinfo);
  161810. * set destination to image file
  161811. * jpeg_start_compress(cinfo, FALSE);
  161812. * write data...
  161813. * jpeg_finish_compress(cinfo);
  161814. *
  161815. * jpeg_write_tables has the side effect of marking all tables written
  161816. * (same as jpeg_suppress_tables(..., TRUE)). Thus a subsequent start_compress
  161817. * will not re-emit the tables unless it is passed write_all_tables=TRUE.
  161818. */
  161819. GLOBAL(void)
  161820. jpeg_write_tables (j_compress_ptr cinfo)
  161821. {
  161822. if (cinfo->global_state != CSTATE_START)
  161823. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161824. /* (Re)initialize error mgr and destination modules */
  161825. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  161826. (*cinfo->dest->init_destination) (cinfo);
  161827. /* Initialize the marker writer ... bit of a crock to do it here. */
  161828. jinit_marker_writer(cinfo);
  161829. /* Write them tables! */
  161830. (*cinfo->marker->write_tables_only) (cinfo);
  161831. /* And clean up. */
  161832. (*cinfo->dest->term_destination) (cinfo);
  161833. /*
  161834. * In library releases up through v6a, we called jpeg_abort() here to free
  161835. * any working memory allocated by the destination manager and marker
  161836. * writer. Some applications had a problem with that: they allocated space
  161837. * of their own from the library memory manager, and didn't want it to go
  161838. * away during write_tables. So now we do nothing. This will cause a
  161839. * memory leak if an app calls write_tables repeatedly without doing a full
  161840. * compression cycle or otherwise resetting the JPEG object. However, that
  161841. * seems less bad than unexpectedly freeing memory in the normal case.
  161842. * An app that prefers the old behavior can call jpeg_abort for itself after
  161843. * each call to jpeg_write_tables().
  161844. */
  161845. }
  161846. /*** End of inlined file: jcapimin.c ***/
  161847. /*** Start of inlined file: jcapistd.c ***/
  161848. #define JPEG_INTERNALS
  161849. /*
  161850. * Compression initialization.
  161851. * Before calling this, all parameters and a data destination must be set up.
  161852. *
  161853. * We require a write_all_tables parameter as a failsafe check when writing
  161854. * multiple datastreams from the same compression object. Since prior runs
  161855. * will have left all the tables marked sent_table=TRUE, a subsequent run
  161856. * would emit an abbreviated stream (no tables) by default. This may be what
  161857. * is wanted, but for safety's sake it should not be the default behavior:
  161858. * programmers should have to make a deliberate choice to emit abbreviated
  161859. * images. Therefore the documentation and examples should encourage people
  161860. * to pass write_all_tables=TRUE; then it will take active thought to do the
  161861. * wrong thing.
  161862. */
  161863. GLOBAL(void)
  161864. jpeg_start_compress (j_compress_ptr cinfo, boolean write_all_tables)
  161865. {
  161866. if (cinfo->global_state != CSTATE_START)
  161867. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161868. if (write_all_tables)
  161869. jpeg_suppress_tables(cinfo, FALSE); /* mark all tables to be written */
  161870. /* (Re)initialize error mgr and destination modules */
  161871. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  161872. (*cinfo->dest->init_destination) (cinfo);
  161873. /* Perform master selection of active modules */
  161874. jinit_compress_master(cinfo);
  161875. /* Set up for the first pass */
  161876. (*cinfo->master->prepare_for_pass) (cinfo);
  161877. /* Ready for application to drive first pass through jpeg_write_scanlines
  161878. * or jpeg_write_raw_data.
  161879. */
  161880. cinfo->next_scanline = 0;
  161881. cinfo->global_state = (cinfo->raw_data_in ? CSTATE_RAW_OK : CSTATE_SCANNING);
  161882. }
  161883. /*
  161884. * Write some scanlines of data to the JPEG compressor.
  161885. *
  161886. * The return value will be the number of lines actually written.
  161887. * This should be less than the supplied num_lines only in case that
  161888. * the data destination module has requested suspension of the compressor,
  161889. * or if more than image_height scanlines are passed in.
  161890. *
  161891. * Note: we warn about excess calls to jpeg_write_scanlines() since
  161892. * this likely signals an application programmer error. However,
  161893. * excess scanlines passed in the last valid call are *silently* ignored,
  161894. * so that the application need not adjust num_lines for end-of-image
  161895. * when using a multiple-scanline buffer.
  161896. */
  161897. GLOBAL(JDIMENSION)
  161898. jpeg_write_scanlines (j_compress_ptr cinfo, JSAMPARRAY scanlines,
  161899. JDIMENSION num_lines)
  161900. {
  161901. JDIMENSION row_ctr, rows_left;
  161902. if (cinfo->global_state != CSTATE_SCANNING)
  161903. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161904. if (cinfo->next_scanline >= cinfo->image_height)
  161905. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  161906. /* Call progress monitor hook if present */
  161907. if (cinfo->progress != NULL) {
  161908. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  161909. cinfo->progress->pass_limit = (long) cinfo->image_height;
  161910. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161911. }
  161912. /* Give master control module another chance if this is first call to
  161913. * jpeg_write_scanlines. This lets output of the frame/scan headers be
  161914. * delayed so that application can write COM, etc, markers between
  161915. * jpeg_start_compress and jpeg_write_scanlines.
  161916. */
  161917. if (cinfo->master->call_pass_startup)
  161918. (*cinfo->master->pass_startup) (cinfo);
  161919. /* Ignore any extra scanlines at bottom of image. */
  161920. rows_left = cinfo->image_height - cinfo->next_scanline;
  161921. if (num_lines > rows_left)
  161922. num_lines = rows_left;
  161923. row_ctr = 0;
  161924. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, num_lines);
  161925. cinfo->next_scanline += row_ctr;
  161926. return row_ctr;
  161927. }
  161928. /*
  161929. * Alternate entry point to write raw data.
  161930. * Processes exactly one iMCU row per call, unless suspended.
  161931. */
  161932. GLOBAL(JDIMENSION)
  161933. jpeg_write_raw_data (j_compress_ptr cinfo, JSAMPIMAGE data,
  161934. JDIMENSION num_lines)
  161935. {
  161936. JDIMENSION lines_per_iMCU_row;
  161937. if (cinfo->global_state != CSTATE_RAW_OK)
  161938. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161939. if (cinfo->next_scanline >= cinfo->image_height) {
  161940. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  161941. return 0;
  161942. }
  161943. /* Call progress monitor hook if present */
  161944. if (cinfo->progress != NULL) {
  161945. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  161946. cinfo->progress->pass_limit = (long) cinfo->image_height;
  161947. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161948. }
  161949. /* Give master control module another chance if this is first call to
  161950. * jpeg_write_raw_data. This lets output of the frame/scan headers be
  161951. * delayed so that application can write COM, etc, markers between
  161952. * jpeg_start_compress and jpeg_write_raw_data.
  161953. */
  161954. if (cinfo->master->call_pass_startup)
  161955. (*cinfo->master->pass_startup) (cinfo);
  161956. /* Verify that at least one iMCU row has been passed. */
  161957. lines_per_iMCU_row = cinfo->max_v_samp_factor * DCTSIZE;
  161958. if (num_lines < lines_per_iMCU_row)
  161959. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  161960. /* Directly compress the row. */
  161961. if (! (*cinfo->coef->compress_data) (cinfo, data)) {
  161962. /* If compressor did not consume the whole row, suspend processing. */
  161963. return 0;
  161964. }
  161965. /* OK, we processed one iMCU row. */
  161966. cinfo->next_scanline += lines_per_iMCU_row;
  161967. return lines_per_iMCU_row;
  161968. }
  161969. /*** End of inlined file: jcapistd.c ***/
  161970. /*** Start of inlined file: jccoefct.c ***/
  161971. #define JPEG_INTERNALS
  161972. /* We use a full-image coefficient buffer when doing Huffman optimization,
  161973. * and also for writing multiple-scan JPEG files. In all cases, the DCT
  161974. * step is run during the first pass, and subsequent passes need only read
  161975. * the buffered coefficients.
  161976. */
  161977. #ifdef ENTROPY_OPT_SUPPORTED
  161978. #define FULL_COEF_BUFFER_SUPPORTED
  161979. #else
  161980. #ifdef C_MULTISCAN_FILES_SUPPORTED
  161981. #define FULL_COEF_BUFFER_SUPPORTED
  161982. #endif
  161983. #endif
  161984. /* Private buffer controller object */
  161985. typedef struct {
  161986. struct jpeg_c_coef_controller pub; /* public fields */
  161987. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  161988. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  161989. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  161990. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  161991. /* For single-pass compression, it's sufficient to buffer just one MCU
  161992. * (although this may prove a bit slow in practice). We allocate a
  161993. * workspace of C_MAX_BLOCKS_IN_MCU coefficient blocks, and reuse it for each
  161994. * MCU constructed and sent. (On 80x86, the workspace is FAR even though
  161995. * it's not really very big; this is to keep the module interfaces unchanged
  161996. * when a large coefficient buffer is necessary.)
  161997. * In multi-pass modes, this array points to the current MCU's blocks
  161998. * within the virtual arrays.
  161999. */
  162000. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  162001. /* In multi-pass modes, we need a virtual block array for each component. */
  162002. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  162003. } my_coef_controller;
  162004. typedef my_coef_controller * my_coef_ptr;
  162005. /* Forward declarations */
  162006. METHODDEF(boolean) compress_data
  162007. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  162008. #ifdef FULL_COEF_BUFFER_SUPPORTED
  162009. METHODDEF(boolean) compress_first_pass
  162010. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  162011. METHODDEF(boolean) compress_output
  162012. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  162013. #endif
  162014. LOCAL(void)
  162015. start_iMCU_row (j_compress_ptr cinfo)
  162016. /* Reset within-iMCU-row counters for a new row */
  162017. {
  162018. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  162019. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  162020. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  162021. * But at the bottom of the image, process only what's left.
  162022. */
  162023. if (cinfo->comps_in_scan > 1) {
  162024. coef->MCU_rows_per_iMCU_row = 1;
  162025. } else {
  162026. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  162027. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  162028. else
  162029. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  162030. }
  162031. coef->mcu_ctr = 0;
  162032. coef->MCU_vert_offset = 0;
  162033. }
  162034. /*
  162035. * Initialize for a processing pass.
  162036. */
  162037. METHODDEF(void)
  162038. start_pass_coef (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  162039. {
  162040. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  162041. coef->iMCU_row_num = 0;
  162042. start_iMCU_row(cinfo);
  162043. switch (pass_mode) {
  162044. case JBUF_PASS_THRU:
  162045. if (coef->whole_image[0] != NULL)
  162046. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162047. coef->pub.compress_data = compress_data;
  162048. break;
  162049. #ifdef FULL_COEF_BUFFER_SUPPORTED
  162050. case JBUF_SAVE_AND_PASS:
  162051. if (coef->whole_image[0] == NULL)
  162052. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162053. coef->pub.compress_data = compress_first_pass;
  162054. break;
  162055. case JBUF_CRANK_DEST:
  162056. if (coef->whole_image[0] == NULL)
  162057. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162058. coef->pub.compress_data = compress_output;
  162059. break;
  162060. #endif
  162061. default:
  162062. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162063. break;
  162064. }
  162065. }
  162066. /*
  162067. * Process some data in the single-pass case.
  162068. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  162069. * per call, ie, v_samp_factor block rows for each component in the image.
  162070. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  162071. *
  162072. * NB: input_buf contains a plane for each component in image,
  162073. * which we index according to the component's SOF position.
  162074. */
  162075. METHODDEF(boolean)
  162076. compress_data (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  162077. {
  162078. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  162079. JDIMENSION MCU_col_num; /* index of current MCU within row */
  162080. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  162081. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  162082. int blkn, bi, ci, yindex, yoffset, blockcnt;
  162083. JDIMENSION ypos, xpos;
  162084. jpeg_component_info *compptr;
  162085. /* Loop to write as much as one whole iMCU row */
  162086. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  162087. yoffset++) {
  162088. for (MCU_col_num = coef->mcu_ctr; MCU_col_num <= last_MCU_col;
  162089. MCU_col_num++) {
  162090. /* Determine where data comes from in input_buf and do the DCT thing.
  162091. * Each call on forward_DCT processes a horizontal row of DCT blocks
  162092. * as wide as an MCU; we rely on having allocated the MCU_buffer[] blocks
  162093. * sequentially. Dummy blocks at the right or bottom edge are filled in
  162094. * specially. The data in them does not matter for image reconstruction,
  162095. * so we fill them with values that will encode to the smallest amount of
  162096. * data, viz: all zeroes in the AC entries, DC entries equal to previous
  162097. * block's DC value. (Thanks to Thomas Kinsman for this idea.)
  162098. */
  162099. blkn = 0;
  162100. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162101. compptr = cinfo->cur_comp_info[ci];
  162102. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  162103. : compptr->last_col_width;
  162104. xpos = MCU_col_num * compptr->MCU_sample_width;
  162105. ypos = yoffset * DCTSIZE; /* ypos == (yoffset+yindex) * DCTSIZE */
  162106. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  162107. if (coef->iMCU_row_num < last_iMCU_row ||
  162108. yoffset+yindex < compptr->last_row_height) {
  162109. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  162110. input_buf[compptr->component_index],
  162111. coef->MCU_buffer[blkn],
  162112. ypos, xpos, (JDIMENSION) blockcnt);
  162113. if (blockcnt < compptr->MCU_width) {
  162114. /* Create some dummy blocks at the right edge of the image. */
  162115. jzero_far((void FAR *) coef->MCU_buffer[blkn + blockcnt],
  162116. (compptr->MCU_width - blockcnt) * SIZEOF(JBLOCK));
  162117. for (bi = blockcnt; bi < compptr->MCU_width; bi++) {
  162118. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn+bi-1][0][0];
  162119. }
  162120. }
  162121. } else {
  162122. /* Create a row of dummy blocks at the bottom of the image. */
  162123. jzero_far((void FAR *) coef->MCU_buffer[blkn],
  162124. compptr->MCU_width * SIZEOF(JBLOCK));
  162125. for (bi = 0; bi < compptr->MCU_width; bi++) {
  162126. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn-1][0][0];
  162127. }
  162128. }
  162129. blkn += compptr->MCU_width;
  162130. ypos += DCTSIZE;
  162131. }
  162132. }
  162133. /* Try to write the MCU. In event of a suspension failure, we will
  162134. * re-DCT the MCU on restart (a bit inefficient, could be fixed...)
  162135. */
  162136. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  162137. /* Suspension forced; update state counters and exit */
  162138. coef->MCU_vert_offset = yoffset;
  162139. coef->mcu_ctr = MCU_col_num;
  162140. return FALSE;
  162141. }
  162142. }
  162143. /* Completed an MCU row, but perhaps not an iMCU row */
  162144. coef->mcu_ctr = 0;
  162145. }
  162146. /* Completed the iMCU row, advance counters for next one */
  162147. coef->iMCU_row_num++;
  162148. start_iMCU_row(cinfo);
  162149. return TRUE;
  162150. }
  162151. #ifdef FULL_COEF_BUFFER_SUPPORTED
  162152. /*
  162153. * Process some data in the first pass of a multi-pass case.
  162154. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  162155. * per call, ie, v_samp_factor block rows for each component in the image.
  162156. * This amount of data is read from the source buffer, DCT'd and quantized,
  162157. * and saved into the virtual arrays. We also generate suitable dummy blocks
  162158. * as needed at the right and lower edges. (The dummy blocks are constructed
  162159. * in the virtual arrays, which have been padded appropriately.) This makes
  162160. * it possible for subsequent passes not to worry about real vs. dummy blocks.
  162161. *
  162162. * We must also emit the data to the entropy encoder. This is conveniently
  162163. * done by calling compress_output() after we've loaded the current strip
  162164. * of the virtual arrays.
  162165. *
  162166. * NB: input_buf contains a plane for each component in image. All
  162167. * components are DCT'd and loaded into the virtual arrays in this pass.
  162168. * However, it may be that only a subset of the components are emitted to
  162169. * the entropy encoder during this first pass; be careful about looking
  162170. * at the scan-dependent variables (MCU dimensions, etc).
  162171. */
  162172. METHODDEF(boolean)
  162173. compress_first_pass (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  162174. {
  162175. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  162176. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  162177. JDIMENSION blocks_across, MCUs_across, MCUindex;
  162178. int bi, ci, h_samp_factor, block_row, block_rows, ndummy;
  162179. JCOEF lastDC;
  162180. jpeg_component_info *compptr;
  162181. JBLOCKARRAY buffer;
  162182. JBLOCKROW thisblockrow, lastblockrow;
  162183. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162184. ci++, compptr++) {
  162185. /* Align the virtual buffer for this component. */
  162186. buffer = (*cinfo->mem->access_virt_barray)
  162187. ((j_common_ptr) cinfo, coef->whole_image[ci],
  162188. coef->iMCU_row_num * compptr->v_samp_factor,
  162189. (JDIMENSION) compptr->v_samp_factor, TRUE);
  162190. /* Count non-dummy DCT block rows in this iMCU row. */
  162191. if (coef->iMCU_row_num < last_iMCU_row)
  162192. block_rows = compptr->v_samp_factor;
  162193. else {
  162194. /* NB: can't use last_row_height here, since may not be set! */
  162195. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  162196. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  162197. }
  162198. blocks_across = compptr->width_in_blocks;
  162199. h_samp_factor = compptr->h_samp_factor;
  162200. /* Count number of dummy blocks to be added at the right margin. */
  162201. ndummy = (int) (blocks_across % h_samp_factor);
  162202. if (ndummy > 0)
  162203. ndummy = h_samp_factor - ndummy;
  162204. /* Perform DCT for all non-dummy blocks in this iMCU row. Each call
  162205. * on forward_DCT processes a complete horizontal row of DCT blocks.
  162206. */
  162207. for (block_row = 0; block_row < block_rows; block_row++) {
  162208. thisblockrow = buffer[block_row];
  162209. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  162210. input_buf[ci], thisblockrow,
  162211. (JDIMENSION) (block_row * DCTSIZE),
  162212. (JDIMENSION) 0, blocks_across);
  162213. if (ndummy > 0) {
  162214. /* Create dummy blocks at the right edge of the image. */
  162215. thisblockrow += blocks_across; /* => first dummy block */
  162216. jzero_far((void FAR *) thisblockrow, ndummy * SIZEOF(JBLOCK));
  162217. lastDC = thisblockrow[-1][0];
  162218. for (bi = 0; bi < ndummy; bi++) {
  162219. thisblockrow[bi][0] = lastDC;
  162220. }
  162221. }
  162222. }
  162223. /* If at end of image, create dummy block rows as needed.
  162224. * The tricky part here is that within each MCU, we want the DC values
  162225. * of the dummy blocks to match the last real block's DC value.
  162226. * This squeezes a few more bytes out of the resulting file...
  162227. */
  162228. if (coef->iMCU_row_num == last_iMCU_row) {
  162229. blocks_across += ndummy; /* include lower right corner */
  162230. MCUs_across = blocks_across / h_samp_factor;
  162231. for (block_row = block_rows; block_row < compptr->v_samp_factor;
  162232. block_row++) {
  162233. thisblockrow = buffer[block_row];
  162234. lastblockrow = buffer[block_row-1];
  162235. jzero_far((void FAR *) thisblockrow,
  162236. (size_t) (blocks_across * SIZEOF(JBLOCK)));
  162237. for (MCUindex = 0; MCUindex < MCUs_across; MCUindex++) {
  162238. lastDC = lastblockrow[h_samp_factor-1][0];
  162239. for (bi = 0; bi < h_samp_factor; bi++) {
  162240. thisblockrow[bi][0] = lastDC;
  162241. }
  162242. thisblockrow += h_samp_factor; /* advance to next MCU in row */
  162243. lastblockrow += h_samp_factor;
  162244. }
  162245. }
  162246. }
  162247. }
  162248. /* NB: compress_output will increment iMCU_row_num if successful.
  162249. * A suspension return will result in redoing all the work above next time.
  162250. */
  162251. /* Emit data to the entropy encoder, sharing code with subsequent passes */
  162252. return compress_output(cinfo, input_buf);
  162253. }
  162254. /*
  162255. * Process some data in subsequent passes of a multi-pass case.
  162256. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  162257. * per call, ie, v_samp_factor block rows for each component in the scan.
  162258. * The data is obtained from the virtual arrays and fed to the entropy coder.
  162259. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  162260. *
  162261. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  162262. */
  162263. METHODDEF(boolean)
  162264. compress_output (j_compress_ptr cinfo, JSAMPIMAGE)
  162265. {
  162266. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  162267. JDIMENSION MCU_col_num; /* index of current MCU within row */
  162268. int blkn, ci, xindex, yindex, yoffset;
  162269. JDIMENSION start_col;
  162270. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  162271. JBLOCKROW buffer_ptr;
  162272. jpeg_component_info *compptr;
  162273. /* Align the virtual buffers for the components used in this scan.
  162274. * NB: during first pass, this is safe only because the buffers will
  162275. * already be aligned properly, so jmemmgr.c won't need to do any I/O.
  162276. */
  162277. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162278. compptr = cinfo->cur_comp_info[ci];
  162279. buffer[ci] = (*cinfo->mem->access_virt_barray)
  162280. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  162281. coef->iMCU_row_num * compptr->v_samp_factor,
  162282. (JDIMENSION) compptr->v_samp_factor, FALSE);
  162283. }
  162284. /* Loop to process one whole iMCU row */
  162285. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  162286. yoffset++) {
  162287. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  162288. MCU_col_num++) {
  162289. /* Construct list of pointers to DCT blocks belonging to this MCU */
  162290. blkn = 0; /* index of current DCT block within MCU */
  162291. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162292. compptr = cinfo->cur_comp_info[ci];
  162293. start_col = MCU_col_num * compptr->MCU_width;
  162294. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  162295. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  162296. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  162297. coef->MCU_buffer[blkn++] = buffer_ptr++;
  162298. }
  162299. }
  162300. }
  162301. /* Try to write the MCU. */
  162302. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  162303. /* Suspension forced; update state counters and exit */
  162304. coef->MCU_vert_offset = yoffset;
  162305. coef->mcu_ctr = MCU_col_num;
  162306. return FALSE;
  162307. }
  162308. }
  162309. /* Completed an MCU row, but perhaps not an iMCU row */
  162310. coef->mcu_ctr = 0;
  162311. }
  162312. /* Completed the iMCU row, advance counters for next one */
  162313. coef->iMCU_row_num++;
  162314. start_iMCU_row(cinfo);
  162315. return TRUE;
  162316. }
  162317. #endif /* FULL_COEF_BUFFER_SUPPORTED */
  162318. /*
  162319. * Initialize coefficient buffer controller.
  162320. */
  162321. GLOBAL(void)
  162322. jinit_c_coef_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  162323. {
  162324. my_coef_ptr coef;
  162325. coef = (my_coef_ptr)
  162326. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162327. SIZEOF(my_coef_controller));
  162328. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  162329. coef->pub.start_pass = start_pass_coef;
  162330. /* Create the coefficient buffer. */
  162331. if (need_full_buffer) {
  162332. #ifdef FULL_COEF_BUFFER_SUPPORTED
  162333. /* Allocate a full-image virtual array for each component, */
  162334. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  162335. int ci;
  162336. jpeg_component_info *compptr;
  162337. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162338. ci++, compptr++) {
  162339. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  162340. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  162341. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  162342. (long) compptr->h_samp_factor),
  162343. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  162344. (long) compptr->v_samp_factor),
  162345. (JDIMENSION) compptr->v_samp_factor);
  162346. }
  162347. #else
  162348. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162349. #endif
  162350. } else {
  162351. /* We only need a single-MCU buffer. */
  162352. JBLOCKROW buffer;
  162353. int i;
  162354. buffer = (JBLOCKROW)
  162355. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162356. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  162357. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  162358. coef->MCU_buffer[i] = buffer + i;
  162359. }
  162360. coef->whole_image[0] = NULL; /* flag for no virtual arrays */
  162361. }
  162362. }
  162363. /*** End of inlined file: jccoefct.c ***/
  162364. /*** Start of inlined file: jccolor.c ***/
  162365. #define JPEG_INTERNALS
  162366. /* Private subobject */
  162367. typedef struct {
  162368. struct jpeg_color_converter pub; /* public fields */
  162369. /* Private state for RGB->YCC conversion */
  162370. INT32 * rgb_ycc_tab; /* => table for RGB to YCbCr conversion */
  162371. } my_color_converter;
  162372. typedef my_color_converter * my_cconvert_ptr;
  162373. /**************** RGB -> YCbCr conversion: most common case **************/
  162374. /*
  162375. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  162376. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  162377. * The conversion equations to be implemented are therefore
  162378. * Y = 0.29900 * R + 0.58700 * G + 0.11400 * B
  162379. * Cb = -0.16874 * R - 0.33126 * G + 0.50000 * B + CENTERJSAMPLE
  162380. * Cr = 0.50000 * R - 0.41869 * G - 0.08131 * B + CENTERJSAMPLE
  162381. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  162382. * Note: older versions of the IJG code used a zero offset of MAXJSAMPLE/2,
  162383. * rather than CENTERJSAMPLE, for Cb and Cr. This gave equal positive and
  162384. * negative swings for Cb/Cr, but meant that grayscale values (Cb=Cr=0)
  162385. * were not represented exactly. Now we sacrifice exact representation of
  162386. * maximum red and maximum blue in order to get exact grayscales.
  162387. *
  162388. * To avoid floating-point arithmetic, we represent the fractional constants
  162389. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  162390. * the products by 2^16, with appropriate rounding, to get the correct answer.
  162391. *
  162392. * For even more speed, we avoid doing any multiplications in the inner loop
  162393. * by precalculating the constants times R,G,B for all possible values.
  162394. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  162395. * for 12-bit samples it is still acceptable. It's not very reasonable for
  162396. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  162397. * colorspace anyway.
  162398. * The CENTERJSAMPLE offsets and the rounding fudge-factor of 0.5 are included
  162399. * in the tables to save adding them separately in the inner loop.
  162400. */
  162401. #define SCALEBITS 16 /* speediest right-shift on some machines */
  162402. #define CBCR_OFFSET ((INT32) CENTERJSAMPLE << SCALEBITS)
  162403. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  162404. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  162405. /* We allocate one big table and divide it up into eight parts, instead of
  162406. * doing eight alloc_small requests. This lets us use a single table base
  162407. * address, which can be held in a register in the inner loops on many
  162408. * machines (more than can hold all eight addresses, anyway).
  162409. */
  162410. #define R_Y_OFF 0 /* offset to R => Y section */
  162411. #define G_Y_OFF (1*(MAXJSAMPLE+1)) /* offset to G => Y section */
  162412. #define B_Y_OFF (2*(MAXJSAMPLE+1)) /* etc. */
  162413. #define R_CB_OFF (3*(MAXJSAMPLE+1))
  162414. #define G_CB_OFF (4*(MAXJSAMPLE+1))
  162415. #define B_CB_OFF (5*(MAXJSAMPLE+1))
  162416. #define R_CR_OFF B_CB_OFF /* B=>Cb, R=>Cr are the same */
  162417. #define G_CR_OFF (6*(MAXJSAMPLE+1))
  162418. #define B_CR_OFF (7*(MAXJSAMPLE+1))
  162419. #define TABLE_SIZE (8*(MAXJSAMPLE+1))
  162420. /*
  162421. * Initialize for RGB->YCC colorspace conversion.
  162422. */
  162423. METHODDEF(void)
  162424. rgb_ycc_start (j_compress_ptr cinfo)
  162425. {
  162426. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162427. INT32 * rgb_ycc_tab;
  162428. INT32 i;
  162429. /* Allocate and fill in the conversion tables. */
  162430. cconvert->rgb_ycc_tab = rgb_ycc_tab = (INT32 *)
  162431. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162432. (TABLE_SIZE * SIZEOF(INT32)));
  162433. for (i = 0; i <= MAXJSAMPLE; i++) {
  162434. rgb_ycc_tab[i+R_Y_OFF] = FIX(0.29900) * i;
  162435. rgb_ycc_tab[i+G_Y_OFF] = FIX(0.58700) * i;
  162436. rgb_ycc_tab[i+B_Y_OFF] = FIX(0.11400) * i + ONE_HALF;
  162437. rgb_ycc_tab[i+R_CB_OFF] = (-FIX(0.16874)) * i;
  162438. rgb_ycc_tab[i+G_CB_OFF] = (-FIX(0.33126)) * i;
  162439. /* We use a rounding fudge-factor of 0.5-epsilon for Cb and Cr.
  162440. * This ensures that the maximum output will round to MAXJSAMPLE
  162441. * not MAXJSAMPLE+1, and thus that we don't have to range-limit.
  162442. */
  162443. rgb_ycc_tab[i+B_CB_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  162444. /* B=>Cb and R=>Cr tables are the same
  162445. rgb_ycc_tab[i+R_CR_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  162446. */
  162447. rgb_ycc_tab[i+G_CR_OFF] = (-FIX(0.41869)) * i;
  162448. rgb_ycc_tab[i+B_CR_OFF] = (-FIX(0.08131)) * i;
  162449. }
  162450. }
  162451. /*
  162452. * Convert some rows of samples to the JPEG colorspace.
  162453. *
  162454. * Note that we change from the application's interleaved-pixel format
  162455. * to our internal noninterleaved, one-plane-per-component format.
  162456. * The input buffer is therefore three times as wide as the output buffer.
  162457. *
  162458. * A starting row offset is provided only for the output buffer. The caller
  162459. * can easily adjust the passed input_buf value to accommodate any row
  162460. * offset required on that side.
  162461. */
  162462. METHODDEF(void)
  162463. rgb_ycc_convert (j_compress_ptr cinfo,
  162464. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162465. JDIMENSION output_row, int num_rows)
  162466. {
  162467. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162468. register int r, g, b;
  162469. register INT32 * ctab = cconvert->rgb_ycc_tab;
  162470. register JSAMPROW inptr;
  162471. register JSAMPROW outptr0, outptr1, outptr2;
  162472. register JDIMENSION col;
  162473. JDIMENSION num_cols = cinfo->image_width;
  162474. while (--num_rows >= 0) {
  162475. inptr = *input_buf++;
  162476. outptr0 = output_buf[0][output_row];
  162477. outptr1 = output_buf[1][output_row];
  162478. outptr2 = output_buf[2][output_row];
  162479. output_row++;
  162480. for (col = 0; col < num_cols; col++) {
  162481. r = GETJSAMPLE(inptr[RGB_RED]);
  162482. g = GETJSAMPLE(inptr[RGB_GREEN]);
  162483. b = GETJSAMPLE(inptr[RGB_BLUE]);
  162484. inptr += RGB_PIXELSIZE;
  162485. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  162486. * must be too; we do not need an explicit range-limiting operation.
  162487. * Hence the value being shifted is never negative, and we don't
  162488. * need the general RIGHT_SHIFT macro.
  162489. */
  162490. /* Y */
  162491. outptr0[col] = (JSAMPLE)
  162492. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  162493. >> SCALEBITS);
  162494. /* Cb */
  162495. outptr1[col] = (JSAMPLE)
  162496. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  162497. >> SCALEBITS);
  162498. /* Cr */
  162499. outptr2[col] = (JSAMPLE)
  162500. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  162501. >> SCALEBITS);
  162502. }
  162503. }
  162504. }
  162505. /**************** Cases other than RGB -> YCbCr **************/
  162506. /*
  162507. * Convert some rows of samples to the JPEG colorspace.
  162508. * This version handles RGB->grayscale conversion, which is the same
  162509. * as the RGB->Y portion of RGB->YCbCr.
  162510. * We assume rgb_ycc_start has been called (we only use the Y tables).
  162511. */
  162512. METHODDEF(void)
  162513. rgb_gray_convert (j_compress_ptr cinfo,
  162514. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162515. JDIMENSION output_row, int num_rows)
  162516. {
  162517. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162518. register int r, g, b;
  162519. register INT32 * ctab = cconvert->rgb_ycc_tab;
  162520. register JSAMPROW inptr;
  162521. register JSAMPROW outptr;
  162522. register JDIMENSION col;
  162523. JDIMENSION num_cols = cinfo->image_width;
  162524. while (--num_rows >= 0) {
  162525. inptr = *input_buf++;
  162526. outptr = output_buf[0][output_row];
  162527. output_row++;
  162528. for (col = 0; col < num_cols; col++) {
  162529. r = GETJSAMPLE(inptr[RGB_RED]);
  162530. g = GETJSAMPLE(inptr[RGB_GREEN]);
  162531. b = GETJSAMPLE(inptr[RGB_BLUE]);
  162532. inptr += RGB_PIXELSIZE;
  162533. /* Y */
  162534. outptr[col] = (JSAMPLE)
  162535. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  162536. >> SCALEBITS);
  162537. }
  162538. }
  162539. }
  162540. /*
  162541. * Convert some rows of samples to the JPEG colorspace.
  162542. * This version handles Adobe-style CMYK->YCCK conversion,
  162543. * where we convert R=1-C, G=1-M, and B=1-Y to YCbCr using the same
  162544. * conversion as above, while passing K (black) unchanged.
  162545. * We assume rgb_ycc_start has been called.
  162546. */
  162547. METHODDEF(void)
  162548. cmyk_ycck_convert (j_compress_ptr cinfo,
  162549. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162550. JDIMENSION output_row, int num_rows)
  162551. {
  162552. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162553. register int r, g, b;
  162554. register INT32 * ctab = cconvert->rgb_ycc_tab;
  162555. register JSAMPROW inptr;
  162556. register JSAMPROW outptr0, outptr1, outptr2, outptr3;
  162557. register JDIMENSION col;
  162558. JDIMENSION num_cols = cinfo->image_width;
  162559. while (--num_rows >= 0) {
  162560. inptr = *input_buf++;
  162561. outptr0 = output_buf[0][output_row];
  162562. outptr1 = output_buf[1][output_row];
  162563. outptr2 = output_buf[2][output_row];
  162564. outptr3 = output_buf[3][output_row];
  162565. output_row++;
  162566. for (col = 0; col < num_cols; col++) {
  162567. r = MAXJSAMPLE - GETJSAMPLE(inptr[0]);
  162568. g = MAXJSAMPLE - GETJSAMPLE(inptr[1]);
  162569. b = MAXJSAMPLE - GETJSAMPLE(inptr[2]);
  162570. /* K passes through as-is */
  162571. outptr3[col] = inptr[3]; /* don't need GETJSAMPLE here */
  162572. inptr += 4;
  162573. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  162574. * must be too; we do not need an explicit range-limiting operation.
  162575. * Hence the value being shifted is never negative, and we don't
  162576. * need the general RIGHT_SHIFT macro.
  162577. */
  162578. /* Y */
  162579. outptr0[col] = (JSAMPLE)
  162580. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  162581. >> SCALEBITS);
  162582. /* Cb */
  162583. outptr1[col] = (JSAMPLE)
  162584. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  162585. >> SCALEBITS);
  162586. /* Cr */
  162587. outptr2[col] = (JSAMPLE)
  162588. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  162589. >> SCALEBITS);
  162590. }
  162591. }
  162592. }
  162593. /*
  162594. * Convert some rows of samples to the JPEG colorspace.
  162595. * This version handles grayscale output with no conversion.
  162596. * The source can be either plain grayscale or YCbCr (since Y == gray).
  162597. */
  162598. METHODDEF(void)
  162599. grayscale_convert (j_compress_ptr cinfo,
  162600. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162601. JDIMENSION output_row, int num_rows)
  162602. {
  162603. register JSAMPROW inptr;
  162604. register JSAMPROW outptr;
  162605. register JDIMENSION col;
  162606. JDIMENSION num_cols = cinfo->image_width;
  162607. int instride = cinfo->input_components;
  162608. while (--num_rows >= 0) {
  162609. inptr = *input_buf++;
  162610. outptr = output_buf[0][output_row];
  162611. output_row++;
  162612. for (col = 0; col < num_cols; col++) {
  162613. outptr[col] = inptr[0]; /* don't need GETJSAMPLE() here */
  162614. inptr += instride;
  162615. }
  162616. }
  162617. }
  162618. /*
  162619. * Convert some rows of samples to the JPEG colorspace.
  162620. * This version handles multi-component colorspaces without conversion.
  162621. * We assume input_components == num_components.
  162622. */
  162623. METHODDEF(void)
  162624. null_convert (j_compress_ptr cinfo,
  162625. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162626. JDIMENSION output_row, int num_rows)
  162627. {
  162628. register JSAMPROW inptr;
  162629. register JSAMPROW outptr;
  162630. register JDIMENSION col;
  162631. register int ci;
  162632. int nc = cinfo->num_components;
  162633. JDIMENSION num_cols = cinfo->image_width;
  162634. while (--num_rows >= 0) {
  162635. /* It seems fastest to make a separate pass for each component. */
  162636. for (ci = 0; ci < nc; ci++) {
  162637. inptr = *input_buf;
  162638. outptr = output_buf[ci][output_row];
  162639. for (col = 0; col < num_cols; col++) {
  162640. outptr[col] = inptr[ci]; /* don't need GETJSAMPLE() here */
  162641. inptr += nc;
  162642. }
  162643. }
  162644. input_buf++;
  162645. output_row++;
  162646. }
  162647. }
  162648. /*
  162649. * Empty method for start_pass.
  162650. */
  162651. METHODDEF(void)
  162652. null_method (j_compress_ptr)
  162653. {
  162654. /* no work needed */
  162655. }
  162656. /*
  162657. * Module initialization routine for input colorspace conversion.
  162658. */
  162659. GLOBAL(void)
  162660. jinit_color_converter (j_compress_ptr cinfo)
  162661. {
  162662. my_cconvert_ptr cconvert;
  162663. cconvert = (my_cconvert_ptr)
  162664. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162665. SIZEOF(my_color_converter));
  162666. cinfo->cconvert = (struct jpeg_color_converter *) cconvert;
  162667. /* set start_pass to null method until we find out differently */
  162668. cconvert->pub.start_pass = null_method;
  162669. /* Make sure input_components agrees with in_color_space */
  162670. switch (cinfo->in_color_space) {
  162671. case JCS_GRAYSCALE:
  162672. if (cinfo->input_components != 1)
  162673. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162674. break;
  162675. case JCS_RGB:
  162676. #if RGB_PIXELSIZE != 3
  162677. if (cinfo->input_components != RGB_PIXELSIZE)
  162678. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162679. break;
  162680. #endif /* else share code with YCbCr */
  162681. case JCS_YCbCr:
  162682. if (cinfo->input_components != 3)
  162683. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162684. break;
  162685. case JCS_CMYK:
  162686. case JCS_YCCK:
  162687. if (cinfo->input_components != 4)
  162688. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162689. break;
  162690. default: /* JCS_UNKNOWN can be anything */
  162691. if (cinfo->input_components < 1)
  162692. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162693. break;
  162694. }
  162695. /* Check num_components, set conversion method based on requested space */
  162696. switch (cinfo->jpeg_color_space) {
  162697. case JCS_GRAYSCALE:
  162698. if (cinfo->num_components != 1)
  162699. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162700. if (cinfo->in_color_space == JCS_GRAYSCALE)
  162701. cconvert->pub.color_convert = grayscale_convert;
  162702. else if (cinfo->in_color_space == JCS_RGB) {
  162703. cconvert->pub.start_pass = rgb_ycc_start;
  162704. cconvert->pub.color_convert = rgb_gray_convert;
  162705. } else if (cinfo->in_color_space == JCS_YCbCr)
  162706. cconvert->pub.color_convert = grayscale_convert;
  162707. else
  162708. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162709. break;
  162710. case JCS_RGB:
  162711. if (cinfo->num_components != 3)
  162712. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162713. if (cinfo->in_color_space == JCS_RGB && RGB_PIXELSIZE == 3)
  162714. cconvert->pub.color_convert = null_convert;
  162715. else
  162716. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162717. break;
  162718. case JCS_YCbCr:
  162719. if (cinfo->num_components != 3)
  162720. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162721. if (cinfo->in_color_space == JCS_RGB) {
  162722. cconvert->pub.start_pass = rgb_ycc_start;
  162723. cconvert->pub.color_convert = rgb_ycc_convert;
  162724. } else if (cinfo->in_color_space == JCS_YCbCr)
  162725. cconvert->pub.color_convert = null_convert;
  162726. else
  162727. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162728. break;
  162729. case JCS_CMYK:
  162730. if (cinfo->num_components != 4)
  162731. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162732. if (cinfo->in_color_space == JCS_CMYK)
  162733. cconvert->pub.color_convert = null_convert;
  162734. else
  162735. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162736. break;
  162737. case JCS_YCCK:
  162738. if (cinfo->num_components != 4)
  162739. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162740. if (cinfo->in_color_space == JCS_CMYK) {
  162741. cconvert->pub.start_pass = rgb_ycc_start;
  162742. cconvert->pub.color_convert = cmyk_ycck_convert;
  162743. } else if (cinfo->in_color_space == JCS_YCCK)
  162744. cconvert->pub.color_convert = null_convert;
  162745. else
  162746. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162747. break;
  162748. default: /* allow null conversion of JCS_UNKNOWN */
  162749. if (cinfo->jpeg_color_space != cinfo->in_color_space ||
  162750. cinfo->num_components != cinfo->input_components)
  162751. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162752. cconvert->pub.color_convert = null_convert;
  162753. break;
  162754. }
  162755. }
  162756. /*** End of inlined file: jccolor.c ***/
  162757. #undef FIX
  162758. /*** Start of inlined file: jcdctmgr.c ***/
  162759. #define JPEG_INTERNALS
  162760. /*** Start of inlined file: jdct.h ***/
  162761. /*
  162762. * A forward DCT routine is given a pointer to a work area of type DCTELEM[];
  162763. * the DCT is to be performed in-place in that buffer. Type DCTELEM is int
  162764. * for 8-bit samples, INT32 for 12-bit samples. (NOTE: Floating-point DCT
  162765. * implementations use an array of type FAST_FLOAT, instead.)
  162766. * The DCT inputs are expected to be signed (range +-CENTERJSAMPLE).
  162767. * The DCT outputs are returned scaled up by a factor of 8; they therefore
  162768. * have a range of +-8K for 8-bit data, +-128K for 12-bit data. This
  162769. * convention improves accuracy in integer implementations and saves some
  162770. * work in floating-point ones.
  162771. * Quantization of the output coefficients is done by jcdctmgr.c.
  162772. */
  162773. #ifndef __jdct_h__
  162774. #define __jdct_h__
  162775. #if BITS_IN_JSAMPLE == 8
  162776. typedef int DCTELEM; /* 16 or 32 bits is fine */
  162777. #else
  162778. typedef INT32 DCTELEM; /* must have 32 bits */
  162779. #endif
  162780. typedef JMETHOD(void, forward_DCT_method_ptr, (DCTELEM * data));
  162781. typedef JMETHOD(void, float_DCT_method_ptr, (FAST_FLOAT * data));
  162782. /*
  162783. * An inverse DCT routine is given a pointer to the input JBLOCK and a pointer
  162784. * to an output sample array. The routine must dequantize the input data as
  162785. * well as perform the IDCT; for dequantization, it uses the multiplier table
  162786. * pointed to by compptr->dct_table. The output data is to be placed into the
  162787. * sample array starting at a specified column. (Any row offset needed will
  162788. * be applied to the array pointer before it is passed to the IDCT code.)
  162789. * Note that the number of samples emitted by the IDCT routine is
  162790. * DCT_scaled_size * DCT_scaled_size.
  162791. */
  162792. /* typedef inverse_DCT_method_ptr is declared in jpegint.h */
  162793. /*
  162794. * Each IDCT routine has its own ideas about the best dct_table element type.
  162795. */
  162796. typedef MULTIPLIER ISLOW_MULT_TYPE; /* short or int, whichever is faster */
  162797. #if BITS_IN_JSAMPLE == 8
  162798. typedef MULTIPLIER IFAST_MULT_TYPE; /* 16 bits is OK, use short if faster */
  162799. #define IFAST_SCALE_BITS 2 /* fractional bits in scale factors */
  162800. #else
  162801. typedef INT32 IFAST_MULT_TYPE; /* need 32 bits for scaled quantizers */
  162802. #define IFAST_SCALE_BITS 13 /* fractional bits in scale factors */
  162803. #endif
  162804. typedef FAST_FLOAT FLOAT_MULT_TYPE; /* preferred floating type */
  162805. /*
  162806. * Each IDCT routine is responsible for range-limiting its results and
  162807. * converting them to unsigned form (0..MAXJSAMPLE). The raw outputs could
  162808. * be quite far out of range if the input data is corrupt, so a bulletproof
  162809. * range-limiting step is required. We use a mask-and-table-lookup method
  162810. * to do the combined operations quickly. See the comments with
  162811. * prepare_range_limit_table (in jdmaster.c) for more info.
  162812. */
  162813. #define IDCT_range_limit(cinfo) ((cinfo)->sample_range_limit + CENTERJSAMPLE)
  162814. #define RANGE_MASK (MAXJSAMPLE * 4 + 3) /* 2 bits wider than legal samples */
  162815. /* Short forms of external names for systems with brain-damaged linkers. */
  162816. #ifdef NEED_SHORT_EXTERNAL_NAMES
  162817. #define jpeg_fdct_islow jFDislow
  162818. #define jpeg_fdct_ifast jFDifast
  162819. #define jpeg_fdct_float jFDfloat
  162820. #define jpeg_idct_islow jRDislow
  162821. #define jpeg_idct_ifast jRDifast
  162822. #define jpeg_idct_float jRDfloat
  162823. #define jpeg_idct_4x4 jRD4x4
  162824. #define jpeg_idct_2x2 jRD2x2
  162825. #define jpeg_idct_1x1 jRD1x1
  162826. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  162827. /* Extern declarations for the forward and inverse DCT routines. */
  162828. EXTERN(void) jpeg_fdct_islow JPP((DCTELEM * data));
  162829. EXTERN(void) jpeg_fdct_ifast JPP((DCTELEM * data));
  162830. EXTERN(void) jpeg_fdct_float JPP((FAST_FLOAT * data));
  162831. EXTERN(void) jpeg_idct_islow
  162832. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162833. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162834. EXTERN(void) jpeg_idct_ifast
  162835. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162836. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162837. EXTERN(void) jpeg_idct_float
  162838. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162839. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162840. EXTERN(void) jpeg_idct_4x4
  162841. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162842. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162843. EXTERN(void) jpeg_idct_2x2
  162844. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162845. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162846. EXTERN(void) jpeg_idct_1x1
  162847. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162848. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162849. /*
  162850. * Macros for handling fixed-point arithmetic; these are used by many
  162851. * but not all of the DCT/IDCT modules.
  162852. *
  162853. * All values are expected to be of type INT32.
  162854. * Fractional constants are scaled left by CONST_BITS bits.
  162855. * CONST_BITS is defined within each module using these macros,
  162856. * and may differ from one module to the next.
  162857. */
  162858. #define ONE ((INT32) 1)
  162859. #define CONST_SCALE (ONE << CONST_BITS)
  162860. /* Convert a positive real constant to an integer scaled by CONST_SCALE.
  162861. * Caution: some C compilers fail to reduce "FIX(constant)" at compile time,
  162862. * thus causing a lot of useless floating-point operations at run time.
  162863. */
  162864. #define FIX(x) ((INT32) ((x) * CONST_SCALE + 0.5))
  162865. /* Descale and correctly round an INT32 value that's scaled by N bits.
  162866. * We assume RIGHT_SHIFT rounds towards minus infinity, so adding
  162867. * the fudge factor is correct for either sign of X.
  162868. */
  162869. #define DESCALE(x,n) RIGHT_SHIFT((x) + (ONE << ((n)-1)), n)
  162870. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  162871. * This macro is used only when the two inputs will actually be no more than
  162872. * 16 bits wide, so that a 16x16->32 bit multiply can be used instead of a
  162873. * full 32x32 multiply. This provides a useful speedup on many machines.
  162874. * Unfortunately there is no way to specify a 16x16->32 multiply portably
  162875. * in C, but some C compilers will do the right thing if you provide the
  162876. * correct combination of casts.
  162877. */
  162878. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  162879. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT16) (const)))
  162880. #endif
  162881. #ifdef SHORTxLCONST_32 /* known to work with Microsoft C 6.0 */
  162882. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT32) (const)))
  162883. #endif
  162884. #ifndef MULTIPLY16C16 /* default definition */
  162885. #define MULTIPLY16C16(var,const) ((var) * (const))
  162886. #endif
  162887. /* Same except both inputs are variables. */
  162888. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  162889. #define MULTIPLY16V16(var1,var2) (((INT16) (var1)) * ((INT16) (var2)))
  162890. #endif
  162891. #ifndef MULTIPLY16V16 /* default definition */
  162892. #define MULTIPLY16V16(var1,var2) ((var1) * (var2))
  162893. #endif
  162894. #endif
  162895. /*** End of inlined file: jdct.h ***/
  162896. /* Private declarations for DCT subsystem */
  162897. /* Private subobject for this module */
  162898. typedef struct {
  162899. struct jpeg_forward_dct pub; /* public fields */
  162900. /* Pointer to the DCT routine actually in use */
  162901. forward_DCT_method_ptr do_dct;
  162902. /* The actual post-DCT divisors --- not identical to the quant table
  162903. * entries, because of scaling (especially for an unnormalized DCT).
  162904. * Each table is given in normal array order.
  162905. */
  162906. DCTELEM * divisors[NUM_QUANT_TBLS];
  162907. #ifdef DCT_FLOAT_SUPPORTED
  162908. /* Same as above for the floating-point case. */
  162909. float_DCT_method_ptr do_float_dct;
  162910. FAST_FLOAT * float_divisors[NUM_QUANT_TBLS];
  162911. #endif
  162912. } my_fdct_controller;
  162913. typedef my_fdct_controller * my_fdct_ptr;
  162914. /*
  162915. * Initialize for a processing pass.
  162916. * Verify that all referenced Q-tables are present, and set up
  162917. * the divisor table for each one.
  162918. * In the current implementation, DCT of all components is done during
  162919. * the first pass, even if only some components will be output in the
  162920. * first scan. Hence all components should be examined here.
  162921. */
  162922. METHODDEF(void)
  162923. start_pass_fdctmgr (j_compress_ptr cinfo)
  162924. {
  162925. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  162926. int ci, qtblno, i;
  162927. jpeg_component_info *compptr;
  162928. JQUANT_TBL * qtbl;
  162929. DCTELEM * dtbl;
  162930. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162931. ci++, compptr++) {
  162932. qtblno = compptr->quant_tbl_no;
  162933. /* Make sure specified quantization table is present */
  162934. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  162935. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  162936. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  162937. qtbl = cinfo->quant_tbl_ptrs[qtblno];
  162938. /* Compute divisors for this quant table */
  162939. /* We may do this more than once for same table, but it's not a big deal */
  162940. switch (cinfo->dct_method) {
  162941. #ifdef DCT_ISLOW_SUPPORTED
  162942. case JDCT_ISLOW:
  162943. /* For LL&M IDCT method, divisors are equal to raw quantization
  162944. * coefficients multiplied by 8 (to counteract scaling).
  162945. */
  162946. if (fdct->divisors[qtblno] == NULL) {
  162947. fdct->divisors[qtblno] = (DCTELEM *)
  162948. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162949. DCTSIZE2 * SIZEOF(DCTELEM));
  162950. }
  162951. dtbl = fdct->divisors[qtblno];
  162952. for (i = 0; i < DCTSIZE2; i++) {
  162953. dtbl[i] = ((DCTELEM) qtbl->quantval[i]) << 3;
  162954. }
  162955. break;
  162956. #endif
  162957. #ifdef DCT_IFAST_SUPPORTED
  162958. case JDCT_IFAST:
  162959. {
  162960. /* For AA&N IDCT method, divisors are equal to quantization
  162961. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  162962. * scalefactor[0] = 1
  162963. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  162964. * We apply a further scale factor of 8.
  162965. */
  162966. #define CONST_BITS 14
  162967. static const INT16 aanscales[DCTSIZE2] = {
  162968. /* precomputed values scaled up by 14 bits */
  162969. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  162970. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  162971. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  162972. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  162973. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  162974. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  162975. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  162976. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  162977. };
  162978. SHIFT_TEMPS
  162979. if (fdct->divisors[qtblno] == NULL) {
  162980. fdct->divisors[qtblno] = (DCTELEM *)
  162981. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162982. DCTSIZE2 * SIZEOF(DCTELEM));
  162983. }
  162984. dtbl = fdct->divisors[qtblno];
  162985. for (i = 0; i < DCTSIZE2; i++) {
  162986. dtbl[i] = (DCTELEM)
  162987. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  162988. (INT32) aanscales[i]),
  162989. CONST_BITS-3);
  162990. }
  162991. }
  162992. break;
  162993. #endif
  162994. #ifdef DCT_FLOAT_SUPPORTED
  162995. case JDCT_FLOAT:
  162996. {
  162997. /* For float AA&N IDCT method, divisors are equal to quantization
  162998. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  162999. * scalefactor[0] = 1
  163000. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  163001. * We apply a further scale factor of 8.
  163002. * What's actually stored is 1/divisor so that the inner loop can
  163003. * use a multiplication rather than a division.
  163004. */
  163005. FAST_FLOAT * fdtbl;
  163006. int row, col;
  163007. static const double aanscalefactor[DCTSIZE] = {
  163008. 1.0, 1.387039845, 1.306562965, 1.175875602,
  163009. 1.0, 0.785694958, 0.541196100, 0.275899379
  163010. };
  163011. if (fdct->float_divisors[qtblno] == NULL) {
  163012. fdct->float_divisors[qtblno] = (FAST_FLOAT *)
  163013. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163014. DCTSIZE2 * SIZEOF(FAST_FLOAT));
  163015. }
  163016. fdtbl = fdct->float_divisors[qtblno];
  163017. i = 0;
  163018. for (row = 0; row < DCTSIZE; row++) {
  163019. for (col = 0; col < DCTSIZE; col++) {
  163020. fdtbl[i] = (FAST_FLOAT)
  163021. (1.0 / (((double) qtbl->quantval[i] *
  163022. aanscalefactor[row] * aanscalefactor[col] * 8.0)));
  163023. i++;
  163024. }
  163025. }
  163026. }
  163027. break;
  163028. #endif
  163029. default:
  163030. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163031. break;
  163032. }
  163033. }
  163034. }
  163035. /*
  163036. * Perform forward DCT on one or more blocks of a component.
  163037. *
  163038. * The input samples are taken from the sample_data[] array starting at
  163039. * position start_row/start_col, and moving to the right for any additional
  163040. * blocks. The quantized coefficients are returned in coef_blocks[].
  163041. */
  163042. METHODDEF(void)
  163043. forward_DCT (j_compress_ptr cinfo, jpeg_component_info * compptr,
  163044. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  163045. JDIMENSION start_row, JDIMENSION start_col,
  163046. JDIMENSION num_blocks)
  163047. /* This version is used for integer DCT implementations. */
  163048. {
  163049. /* This routine is heavily used, so it's worth coding it tightly. */
  163050. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  163051. forward_DCT_method_ptr do_dct = fdct->do_dct;
  163052. DCTELEM * divisors = fdct->divisors[compptr->quant_tbl_no];
  163053. DCTELEM workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  163054. JDIMENSION bi;
  163055. sample_data += start_row; /* fold in the vertical offset once */
  163056. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  163057. /* Load data into workspace, applying unsigned->signed conversion */
  163058. { register DCTELEM *workspaceptr;
  163059. register JSAMPROW elemptr;
  163060. register int elemr;
  163061. workspaceptr = workspace;
  163062. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  163063. elemptr = sample_data[elemr] + start_col;
  163064. #if DCTSIZE == 8 /* unroll the inner loop */
  163065. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163066. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163067. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163068. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163069. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163070. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163071. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163072. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163073. #else
  163074. { register int elemc;
  163075. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  163076. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163077. }
  163078. }
  163079. #endif
  163080. }
  163081. }
  163082. /* Perform the DCT */
  163083. (*do_dct) (workspace);
  163084. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  163085. { register DCTELEM temp, qval;
  163086. register int i;
  163087. register JCOEFPTR output_ptr = coef_blocks[bi];
  163088. for (i = 0; i < DCTSIZE2; i++) {
  163089. qval = divisors[i];
  163090. temp = workspace[i];
  163091. /* Divide the coefficient value by qval, ensuring proper rounding.
  163092. * Since C does not specify the direction of rounding for negative
  163093. * quotients, we have to force the dividend positive for portability.
  163094. *
  163095. * In most files, at least half of the output values will be zero
  163096. * (at default quantization settings, more like three-quarters...)
  163097. * so we should ensure that this case is fast. On many machines,
  163098. * a comparison is enough cheaper than a divide to make a special test
  163099. * a win. Since both inputs will be nonnegative, we need only test
  163100. * for a < b to discover whether a/b is 0.
  163101. * If your machine's division is fast enough, define FAST_DIVIDE.
  163102. */
  163103. #ifdef FAST_DIVIDE
  163104. #define DIVIDE_BY(a,b) a /= b
  163105. #else
  163106. #define DIVIDE_BY(a,b) if (a >= b) a /= b; else a = 0
  163107. #endif
  163108. if (temp < 0) {
  163109. temp = -temp;
  163110. temp += qval>>1; /* for rounding */
  163111. DIVIDE_BY(temp, qval);
  163112. temp = -temp;
  163113. } else {
  163114. temp += qval>>1; /* for rounding */
  163115. DIVIDE_BY(temp, qval);
  163116. }
  163117. output_ptr[i] = (JCOEF) temp;
  163118. }
  163119. }
  163120. }
  163121. }
  163122. #ifdef DCT_FLOAT_SUPPORTED
  163123. METHODDEF(void)
  163124. forward_DCT_float (j_compress_ptr cinfo, jpeg_component_info * compptr,
  163125. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  163126. JDIMENSION start_row, JDIMENSION start_col,
  163127. JDIMENSION num_blocks)
  163128. /* This version is used for floating-point DCT implementations. */
  163129. {
  163130. /* This routine is heavily used, so it's worth coding it tightly. */
  163131. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  163132. float_DCT_method_ptr do_dct = fdct->do_float_dct;
  163133. FAST_FLOAT * divisors = fdct->float_divisors[compptr->quant_tbl_no];
  163134. FAST_FLOAT workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  163135. JDIMENSION bi;
  163136. sample_data += start_row; /* fold in the vertical offset once */
  163137. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  163138. /* Load data into workspace, applying unsigned->signed conversion */
  163139. { register FAST_FLOAT *workspaceptr;
  163140. register JSAMPROW elemptr;
  163141. register int elemr;
  163142. workspaceptr = workspace;
  163143. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  163144. elemptr = sample_data[elemr] + start_col;
  163145. #if DCTSIZE == 8 /* unroll the inner loop */
  163146. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163147. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163148. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163149. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163150. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163151. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163152. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163153. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163154. #else
  163155. { register int elemc;
  163156. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  163157. *workspaceptr++ = (FAST_FLOAT)
  163158. (GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163159. }
  163160. }
  163161. #endif
  163162. }
  163163. }
  163164. /* Perform the DCT */
  163165. (*do_dct) (workspace);
  163166. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  163167. { register FAST_FLOAT temp;
  163168. register int i;
  163169. register JCOEFPTR output_ptr = coef_blocks[bi];
  163170. for (i = 0; i < DCTSIZE2; i++) {
  163171. /* Apply the quantization and scaling factor */
  163172. temp = workspace[i] * divisors[i];
  163173. /* Round to nearest integer.
  163174. * Since C does not specify the direction of rounding for negative
  163175. * quotients, we have to force the dividend positive for portability.
  163176. * The maximum coefficient size is +-16K (for 12-bit data), so this
  163177. * code should work for either 16-bit or 32-bit ints.
  163178. */
  163179. output_ptr[i] = (JCOEF) ((int) (temp + (FAST_FLOAT) 16384.5) - 16384);
  163180. }
  163181. }
  163182. }
  163183. }
  163184. #endif /* DCT_FLOAT_SUPPORTED */
  163185. /*
  163186. * Initialize FDCT manager.
  163187. */
  163188. GLOBAL(void)
  163189. jinit_forward_dct (j_compress_ptr cinfo)
  163190. {
  163191. my_fdct_ptr fdct;
  163192. int i;
  163193. fdct = (my_fdct_ptr)
  163194. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163195. SIZEOF(my_fdct_controller));
  163196. cinfo->fdct = (struct jpeg_forward_dct *) fdct;
  163197. fdct->pub.start_pass = start_pass_fdctmgr;
  163198. switch (cinfo->dct_method) {
  163199. #ifdef DCT_ISLOW_SUPPORTED
  163200. case JDCT_ISLOW:
  163201. fdct->pub.forward_DCT = forward_DCT;
  163202. fdct->do_dct = jpeg_fdct_islow;
  163203. break;
  163204. #endif
  163205. #ifdef DCT_IFAST_SUPPORTED
  163206. case JDCT_IFAST:
  163207. fdct->pub.forward_DCT = forward_DCT;
  163208. fdct->do_dct = jpeg_fdct_ifast;
  163209. break;
  163210. #endif
  163211. #ifdef DCT_FLOAT_SUPPORTED
  163212. case JDCT_FLOAT:
  163213. fdct->pub.forward_DCT = forward_DCT_float;
  163214. fdct->do_float_dct = jpeg_fdct_float;
  163215. break;
  163216. #endif
  163217. default:
  163218. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163219. break;
  163220. }
  163221. /* Mark divisor tables unallocated */
  163222. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  163223. fdct->divisors[i] = NULL;
  163224. #ifdef DCT_FLOAT_SUPPORTED
  163225. fdct->float_divisors[i] = NULL;
  163226. #endif
  163227. }
  163228. }
  163229. /*** End of inlined file: jcdctmgr.c ***/
  163230. #undef CONST_BITS
  163231. /*** Start of inlined file: jchuff.c ***/
  163232. #define JPEG_INTERNALS
  163233. /*** Start of inlined file: jchuff.h ***/
  163234. /* The legal range of a DCT coefficient is
  163235. * -1024 .. +1023 for 8-bit data;
  163236. * -16384 .. +16383 for 12-bit data.
  163237. * Hence the magnitude should always fit in 10 or 14 bits respectively.
  163238. */
  163239. #ifndef _jchuff_h_
  163240. #define _jchuff_h_
  163241. #if BITS_IN_JSAMPLE == 8
  163242. #define MAX_COEF_BITS 10
  163243. #else
  163244. #define MAX_COEF_BITS 14
  163245. #endif
  163246. /* Derived data constructed for each Huffman table */
  163247. typedef struct {
  163248. unsigned int ehufco[256]; /* code for each symbol */
  163249. char ehufsi[256]; /* length of code for each symbol */
  163250. /* If no code has been allocated for a symbol S, ehufsi[S] contains 0 */
  163251. } c_derived_tbl;
  163252. /* Short forms of external names for systems with brain-damaged linkers. */
  163253. #ifdef NEED_SHORT_EXTERNAL_NAMES
  163254. #define jpeg_make_c_derived_tbl jMkCDerived
  163255. #define jpeg_gen_optimal_table jGenOptTbl
  163256. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  163257. /* Expand a Huffman table definition into the derived format */
  163258. EXTERN(void) jpeg_make_c_derived_tbl
  163259. JPP((j_compress_ptr cinfo, boolean isDC, int tblno,
  163260. c_derived_tbl ** pdtbl));
  163261. /* Generate an optimal table definition given the specified counts */
  163262. EXTERN(void) jpeg_gen_optimal_table
  163263. JPP((j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[]));
  163264. #endif
  163265. /*** End of inlined file: jchuff.h ***/
  163266. /* Declarations shared with jcphuff.c */
  163267. /* Expanded entropy encoder object for Huffman encoding.
  163268. *
  163269. * The savable_state subrecord contains fields that change within an MCU,
  163270. * but must not be updated permanently until we complete the MCU.
  163271. */
  163272. typedef struct {
  163273. INT32 put_buffer; /* current bit-accumulation buffer */
  163274. int put_bits; /* # of bits now in it */
  163275. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  163276. } savable_state;
  163277. /* This macro is to work around compilers with missing or broken
  163278. * structure assignment. You'll need to fix this code if you have
  163279. * such a compiler and you change MAX_COMPS_IN_SCAN.
  163280. */
  163281. #ifndef NO_STRUCT_ASSIGN
  163282. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  163283. #else
  163284. #if MAX_COMPS_IN_SCAN == 4
  163285. #define ASSIGN_STATE(dest,src) \
  163286. ((dest).put_buffer = (src).put_buffer, \
  163287. (dest).put_bits = (src).put_bits, \
  163288. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  163289. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  163290. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  163291. (dest).last_dc_val[3] = (src).last_dc_val[3])
  163292. #endif
  163293. #endif
  163294. typedef struct {
  163295. struct jpeg_entropy_encoder pub; /* public fields */
  163296. savable_state saved; /* Bit buffer & DC state at start of MCU */
  163297. /* These fields are NOT loaded into local working state. */
  163298. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  163299. int next_restart_num; /* next restart number to write (0-7) */
  163300. /* Pointers to derived tables (these workspaces have image lifespan) */
  163301. c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  163302. c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  163303. #ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */
  163304. long * dc_count_ptrs[NUM_HUFF_TBLS];
  163305. long * ac_count_ptrs[NUM_HUFF_TBLS];
  163306. #endif
  163307. } huff_entropy_encoder;
  163308. typedef huff_entropy_encoder * huff_entropy_ptr;
  163309. /* Working state while writing an MCU.
  163310. * This struct contains all the fields that are needed by subroutines.
  163311. */
  163312. typedef struct {
  163313. JOCTET * next_output_byte; /* => next byte to write in buffer */
  163314. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  163315. savable_state cur; /* Current bit buffer & DC state */
  163316. j_compress_ptr cinfo; /* dump_buffer needs access to this */
  163317. } working_state;
  163318. /* Forward declarations */
  163319. METHODDEF(boolean) encode_mcu_huff JPP((j_compress_ptr cinfo,
  163320. JBLOCKROW *MCU_data));
  163321. METHODDEF(void) finish_pass_huff JPP((j_compress_ptr cinfo));
  163322. #ifdef ENTROPY_OPT_SUPPORTED
  163323. METHODDEF(boolean) encode_mcu_gather JPP((j_compress_ptr cinfo,
  163324. JBLOCKROW *MCU_data));
  163325. METHODDEF(void) finish_pass_gather JPP((j_compress_ptr cinfo));
  163326. #endif
  163327. /*
  163328. * Initialize for a Huffman-compressed scan.
  163329. * If gather_statistics is TRUE, we do not output anything during the scan,
  163330. * just count the Huffman symbols used and generate Huffman code tables.
  163331. */
  163332. METHODDEF(void)
  163333. start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
  163334. {
  163335. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163336. int ci, dctbl, actbl;
  163337. jpeg_component_info * compptr;
  163338. if (gather_statistics) {
  163339. #ifdef ENTROPY_OPT_SUPPORTED
  163340. entropy->pub.encode_mcu = encode_mcu_gather;
  163341. entropy->pub.finish_pass = finish_pass_gather;
  163342. #else
  163343. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163344. #endif
  163345. } else {
  163346. entropy->pub.encode_mcu = encode_mcu_huff;
  163347. entropy->pub.finish_pass = finish_pass_huff;
  163348. }
  163349. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  163350. compptr = cinfo->cur_comp_info[ci];
  163351. dctbl = compptr->dc_tbl_no;
  163352. actbl = compptr->ac_tbl_no;
  163353. if (gather_statistics) {
  163354. #ifdef ENTROPY_OPT_SUPPORTED
  163355. /* Check for invalid table indexes */
  163356. /* (make_c_derived_tbl does this in the other path) */
  163357. if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS)
  163358. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
  163359. if (actbl < 0 || actbl >= NUM_HUFF_TBLS)
  163360. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
  163361. /* Allocate and zero the statistics tables */
  163362. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  163363. if (entropy->dc_count_ptrs[dctbl] == NULL)
  163364. entropy->dc_count_ptrs[dctbl] = (long *)
  163365. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163366. 257 * SIZEOF(long));
  163367. MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * SIZEOF(long));
  163368. if (entropy->ac_count_ptrs[actbl] == NULL)
  163369. entropy->ac_count_ptrs[actbl] = (long *)
  163370. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163371. 257 * SIZEOF(long));
  163372. MEMZERO(entropy->ac_count_ptrs[actbl], 257 * SIZEOF(long));
  163373. #endif
  163374. } else {
  163375. /* Compute derived values for Huffman tables */
  163376. /* We may do this more than once for a table, but it's not expensive */
  163377. jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl,
  163378. & entropy->dc_derived_tbls[dctbl]);
  163379. jpeg_make_c_derived_tbl(cinfo, FALSE, actbl,
  163380. & entropy->ac_derived_tbls[actbl]);
  163381. }
  163382. /* Initialize DC predictions to 0 */
  163383. entropy->saved.last_dc_val[ci] = 0;
  163384. }
  163385. /* Initialize bit buffer to empty */
  163386. entropy->saved.put_buffer = 0;
  163387. entropy->saved.put_bits = 0;
  163388. /* Initialize restart stuff */
  163389. entropy->restarts_to_go = cinfo->restart_interval;
  163390. entropy->next_restart_num = 0;
  163391. }
  163392. /*
  163393. * Compute the derived values for a Huffman table.
  163394. * This routine also performs some validation checks on the table.
  163395. *
  163396. * Note this is also used by jcphuff.c.
  163397. */
  163398. GLOBAL(void)
  163399. jpeg_make_c_derived_tbl (j_compress_ptr cinfo, boolean isDC, int tblno,
  163400. c_derived_tbl ** pdtbl)
  163401. {
  163402. JHUFF_TBL *htbl;
  163403. c_derived_tbl *dtbl;
  163404. int p, i, l, lastp, si, maxsymbol;
  163405. char huffsize[257];
  163406. unsigned int huffcode[257];
  163407. unsigned int code;
  163408. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  163409. * paralleling the order of the symbols themselves in htbl->huffval[].
  163410. */
  163411. /* Find the input Huffman table */
  163412. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  163413. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  163414. htbl =
  163415. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  163416. if (htbl == NULL)
  163417. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  163418. /* Allocate a workspace if we haven't already done so. */
  163419. if (*pdtbl == NULL)
  163420. *pdtbl = (c_derived_tbl *)
  163421. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163422. SIZEOF(c_derived_tbl));
  163423. dtbl = *pdtbl;
  163424. /* Figure C.1: make table of Huffman code length for each symbol */
  163425. p = 0;
  163426. for (l = 1; l <= 16; l++) {
  163427. i = (int) htbl->bits[l];
  163428. if (i < 0 || p + i > 256) /* protect against table overrun */
  163429. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163430. while (i--)
  163431. huffsize[p++] = (char) l;
  163432. }
  163433. huffsize[p] = 0;
  163434. lastp = p;
  163435. /* Figure C.2: generate the codes themselves */
  163436. /* We also validate that the counts represent a legal Huffman code tree. */
  163437. code = 0;
  163438. si = huffsize[0];
  163439. p = 0;
  163440. while (huffsize[p]) {
  163441. while (((int) huffsize[p]) == si) {
  163442. huffcode[p++] = code;
  163443. code++;
  163444. }
  163445. /* code is now 1 more than the last code used for codelength si; but
  163446. * it must still fit in si bits, since no code is allowed to be all ones.
  163447. */
  163448. if (((INT32) code) >= (((INT32) 1) << si))
  163449. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163450. code <<= 1;
  163451. si++;
  163452. }
  163453. /* Figure C.3: generate encoding tables */
  163454. /* These are code and size indexed by symbol value */
  163455. /* Set all codeless symbols to have code length 0;
  163456. * this lets us detect duplicate VAL entries here, and later
  163457. * allows emit_bits to detect any attempt to emit such symbols.
  163458. */
  163459. MEMZERO(dtbl->ehufsi, SIZEOF(dtbl->ehufsi));
  163460. /* This is also a convenient place to check for out-of-range
  163461. * and duplicated VAL entries. We allow 0..255 for AC symbols
  163462. * but only 0..15 for DC. (We could constrain them further
  163463. * based on data depth and mode, but this seems enough.)
  163464. */
  163465. maxsymbol = isDC ? 15 : 255;
  163466. for (p = 0; p < lastp; p++) {
  163467. i = htbl->huffval[p];
  163468. if (i < 0 || i > maxsymbol || dtbl->ehufsi[i])
  163469. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163470. dtbl->ehufco[i] = huffcode[p];
  163471. dtbl->ehufsi[i] = huffsize[p];
  163472. }
  163473. }
  163474. /* Outputting bytes to the file */
  163475. /* Emit a byte, taking 'action' if must suspend. */
  163476. #define emit_byte(state,val,action) \
  163477. { *(state)->next_output_byte++ = (JOCTET) (val); \
  163478. if (--(state)->free_in_buffer == 0) \
  163479. if (! dump_buffer(state)) \
  163480. { action; } }
  163481. LOCAL(boolean)
  163482. dump_buffer (working_state * state)
  163483. /* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
  163484. {
  163485. struct jpeg_destination_mgr * dest = state->cinfo->dest;
  163486. if (! (*dest->empty_output_buffer) (state->cinfo))
  163487. return FALSE;
  163488. /* After a successful buffer dump, must reset buffer pointers */
  163489. state->next_output_byte = dest->next_output_byte;
  163490. state->free_in_buffer = dest->free_in_buffer;
  163491. return TRUE;
  163492. }
  163493. /* Outputting bits to the file */
  163494. /* Only the right 24 bits of put_buffer are used; the valid bits are
  163495. * left-justified in this part. At most 16 bits can be passed to emit_bits
  163496. * in one call, and we never retain more than 7 bits in put_buffer
  163497. * between calls, so 24 bits are sufficient.
  163498. */
  163499. INLINE
  163500. LOCAL(boolean)
  163501. emit_bits (working_state * state, unsigned int code, int size)
  163502. /* Emit some bits; return TRUE if successful, FALSE if must suspend */
  163503. {
  163504. /* This routine is heavily used, so it's worth coding tightly. */
  163505. register INT32 put_buffer = (INT32) code;
  163506. register int put_bits = state->cur.put_bits;
  163507. /* if size is 0, caller used an invalid Huffman table entry */
  163508. if (size == 0)
  163509. ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE);
  163510. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  163511. put_bits += size; /* new number of bits in buffer */
  163512. put_buffer <<= 24 - put_bits; /* align incoming bits */
  163513. put_buffer |= state->cur.put_buffer; /* and merge with old buffer contents */
  163514. while (put_bits >= 8) {
  163515. int c = (int) ((put_buffer >> 16) & 0xFF);
  163516. emit_byte(state, c, return FALSE);
  163517. if (c == 0xFF) { /* need to stuff a zero byte? */
  163518. emit_byte(state, 0, return FALSE);
  163519. }
  163520. put_buffer <<= 8;
  163521. put_bits -= 8;
  163522. }
  163523. state->cur.put_buffer = put_buffer; /* update state variables */
  163524. state->cur.put_bits = put_bits;
  163525. return TRUE;
  163526. }
  163527. LOCAL(boolean)
  163528. flush_bits (working_state * state)
  163529. {
  163530. if (! emit_bits(state, 0x7F, 7)) /* fill any partial byte with ones */
  163531. return FALSE;
  163532. state->cur.put_buffer = 0; /* and reset bit-buffer to empty */
  163533. state->cur.put_bits = 0;
  163534. return TRUE;
  163535. }
  163536. /* Encode a single block's worth of coefficients */
  163537. LOCAL(boolean)
  163538. encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,
  163539. c_derived_tbl *dctbl, c_derived_tbl *actbl)
  163540. {
  163541. register int temp, temp2;
  163542. register int nbits;
  163543. register int k, r, i;
  163544. /* Encode the DC coefficient difference per section F.1.2.1 */
  163545. temp = temp2 = block[0] - last_dc_val;
  163546. if (temp < 0) {
  163547. temp = -temp; /* temp is abs value of input */
  163548. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  163549. /* This code assumes we are on a two's complement machine */
  163550. temp2--;
  163551. }
  163552. /* Find the number of bits needed for the magnitude of the coefficient */
  163553. nbits = 0;
  163554. while (temp) {
  163555. nbits++;
  163556. temp >>= 1;
  163557. }
  163558. /* Check for out-of-range coefficient values.
  163559. * Since we're encoding a difference, the range limit is twice as much.
  163560. */
  163561. if (nbits > MAX_COEF_BITS+1)
  163562. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  163563. /* Emit the Huffman-coded symbol for the number of bits */
  163564. if (! emit_bits(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits]))
  163565. return FALSE;
  163566. /* Emit that number of bits of the value, if positive, */
  163567. /* or the complement of its magnitude, if negative. */
  163568. if (nbits) /* emit_bits rejects calls with size 0 */
  163569. if (! emit_bits(state, (unsigned int) temp2, nbits))
  163570. return FALSE;
  163571. /* Encode the AC coefficients per section F.1.2.2 */
  163572. r = 0; /* r = run length of zeros */
  163573. for (k = 1; k < DCTSIZE2; k++) {
  163574. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  163575. r++;
  163576. } else {
  163577. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  163578. while (r > 15) {
  163579. if (! emit_bits(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0]))
  163580. return FALSE;
  163581. r -= 16;
  163582. }
  163583. temp2 = temp;
  163584. if (temp < 0) {
  163585. temp = -temp; /* temp is abs value of input */
  163586. /* This code assumes we are on a two's complement machine */
  163587. temp2--;
  163588. }
  163589. /* Find the number of bits needed for the magnitude of the coefficient */
  163590. nbits = 1; /* there must be at least one 1 bit */
  163591. while ((temp >>= 1))
  163592. nbits++;
  163593. /* Check for out-of-range coefficient values */
  163594. if (nbits > MAX_COEF_BITS)
  163595. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  163596. /* Emit Huffman symbol for run length / number of bits */
  163597. i = (r << 4) + nbits;
  163598. if (! emit_bits(state, actbl->ehufco[i], actbl->ehufsi[i]))
  163599. return FALSE;
  163600. /* Emit that number of bits of the value, if positive, */
  163601. /* or the complement of its magnitude, if negative. */
  163602. if (! emit_bits(state, (unsigned int) temp2, nbits))
  163603. return FALSE;
  163604. r = 0;
  163605. }
  163606. }
  163607. /* If the last coef(s) were zero, emit an end-of-block code */
  163608. if (r > 0)
  163609. if (! emit_bits(state, actbl->ehufco[0], actbl->ehufsi[0]))
  163610. return FALSE;
  163611. return TRUE;
  163612. }
  163613. /*
  163614. * Emit a restart marker & resynchronize predictions.
  163615. */
  163616. LOCAL(boolean)
  163617. emit_restart (working_state * state, int restart_num)
  163618. {
  163619. int ci;
  163620. if (! flush_bits(state))
  163621. return FALSE;
  163622. emit_byte(state, 0xFF, return FALSE);
  163623. emit_byte(state, JPEG_RST0 + restart_num, return FALSE);
  163624. /* Re-initialize DC predictions to 0 */
  163625. for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
  163626. state->cur.last_dc_val[ci] = 0;
  163627. /* The restart counter is not updated until we successfully write the MCU. */
  163628. return TRUE;
  163629. }
  163630. /*
  163631. * Encode and output one MCU's worth of Huffman-compressed coefficients.
  163632. */
  163633. METHODDEF(boolean)
  163634. encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  163635. {
  163636. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163637. working_state state;
  163638. int blkn, ci;
  163639. jpeg_component_info * compptr;
  163640. /* Load up working state */
  163641. state.next_output_byte = cinfo->dest->next_output_byte;
  163642. state.free_in_buffer = cinfo->dest->free_in_buffer;
  163643. ASSIGN_STATE(state.cur, entropy->saved);
  163644. state.cinfo = cinfo;
  163645. /* Emit restart marker if needed */
  163646. if (cinfo->restart_interval) {
  163647. if (entropy->restarts_to_go == 0)
  163648. if (! emit_restart(&state, entropy->next_restart_num))
  163649. return FALSE;
  163650. }
  163651. /* Encode the MCU data blocks */
  163652. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  163653. ci = cinfo->MCU_membership[blkn];
  163654. compptr = cinfo->cur_comp_info[ci];
  163655. if (! encode_one_block(&state,
  163656. MCU_data[blkn][0], state.cur.last_dc_val[ci],
  163657. entropy->dc_derived_tbls[compptr->dc_tbl_no],
  163658. entropy->ac_derived_tbls[compptr->ac_tbl_no]))
  163659. return FALSE;
  163660. /* Update last_dc_val */
  163661. state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
  163662. }
  163663. /* Completed MCU, so update state */
  163664. cinfo->dest->next_output_byte = state.next_output_byte;
  163665. cinfo->dest->free_in_buffer = state.free_in_buffer;
  163666. ASSIGN_STATE(entropy->saved, state.cur);
  163667. /* Update restart-interval state too */
  163668. if (cinfo->restart_interval) {
  163669. if (entropy->restarts_to_go == 0) {
  163670. entropy->restarts_to_go = cinfo->restart_interval;
  163671. entropy->next_restart_num++;
  163672. entropy->next_restart_num &= 7;
  163673. }
  163674. entropy->restarts_to_go--;
  163675. }
  163676. return TRUE;
  163677. }
  163678. /*
  163679. * Finish up at the end of a Huffman-compressed scan.
  163680. */
  163681. METHODDEF(void)
  163682. finish_pass_huff (j_compress_ptr cinfo)
  163683. {
  163684. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163685. working_state state;
  163686. /* Load up working state ... flush_bits needs it */
  163687. state.next_output_byte = cinfo->dest->next_output_byte;
  163688. state.free_in_buffer = cinfo->dest->free_in_buffer;
  163689. ASSIGN_STATE(state.cur, entropy->saved);
  163690. state.cinfo = cinfo;
  163691. /* Flush out the last data */
  163692. if (! flush_bits(&state))
  163693. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  163694. /* Update state */
  163695. cinfo->dest->next_output_byte = state.next_output_byte;
  163696. cinfo->dest->free_in_buffer = state.free_in_buffer;
  163697. ASSIGN_STATE(entropy->saved, state.cur);
  163698. }
  163699. /*
  163700. * Huffman coding optimization.
  163701. *
  163702. * We first scan the supplied data and count the number of uses of each symbol
  163703. * that is to be Huffman-coded. (This process MUST agree with the code above.)
  163704. * Then we build a Huffman coding tree for the observed counts.
  163705. * Symbols which are not needed at all for the particular image are not
  163706. * assigned any code, which saves space in the DHT marker as well as in
  163707. * the compressed data.
  163708. */
  163709. #ifdef ENTROPY_OPT_SUPPORTED
  163710. /* Process a single block's worth of coefficients */
  163711. LOCAL(void)
  163712. htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,
  163713. long dc_counts[], long ac_counts[])
  163714. {
  163715. register int temp;
  163716. register int nbits;
  163717. register int k, r;
  163718. /* Encode the DC coefficient difference per section F.1.2.1 */
  163719. temp = block[0] - last_dc_val;
  163720. if (temp < 0)
  163721. temp = -temp;
  163722. /* Find the number of bits needed for the magnitude of the coefficient */
  163723. nbits = 0;
  163724. while (temp) {
  163725. nbits++;
  163726. temp >>= 1;
  163727. }
  163728. /* Check for out-of-range coefficient values.
  163729. * Since we're encoding a difference, the range limit is twice as much.
  163730. */
  163731. if (nbits > MAX_COEF_BITS+1)
  163732. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  163733. /* Count the Huffman symbol for the number of bits */
  163734. dc_counts[nbits]++;
  163735. /* Encode the AC coefficients per section F.1.2.2 */
  163736. r = 0; /* r = run length of zeros */
  163737. for (k = 1; k < DCTSIZE2; k++) {
  163738. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  163739. r++;
  163740. } else {
  163741. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  163742. while (r > 15) {
  163743. ac_counts[0xF0]++;
  163744. r -= 16;
  163745. }
  163746. /* Find the number of bits needed for the magnitude of the coefficient */
  163747. if (temp < 0)
  163748. temp = -temp;
  163749. /* Find the number of bits needed for the magnitude of the coefficient */
  163750. nbits = 1; /* there must be at least one 1 bit */
  163751. while ((temp >>= 1))
  163752. nbits++;
  163753. /* Check for out-of-range coefficient values */
  163754. if (nbits > MAX_COEF_BITS)
  163755. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  163756. /* Count Huffman symbol for run length / number of bits */
  163757. ac_counts[(r << 4) + nbits]++;
  163758. r = 0;
  163759. }
  163760. }
  163761. /* If the last coef(s) were zero, emit an end-of-block code */
  163762. if (r > 0)
  163763. ac_counts[0]++;
  163764. }
  163765. /*
  163766. * Trial-encode one MCU's worth of Huffman-compressed coefficients.
  163767. * No data is actually output, so no suspension return is possible.
  163768. */
  163769. METHODDEF(boolean)
  163770. encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  163771. {
  163772. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163773. int blkn, ci;
  163774. jpeg_component_info * compptr;
  163775. /* Take care of restart intervals if needed */
  163776. if (cinfo->restart_interval) {
  163777. if (entropy->restarts_to_go == 0) {
  163778. /* Re-initialize DC predictions to 0 */
  163779. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  163780. entropy->saved.last_dc_val[ci] = 0;
  163781. /* Update restart state */
  163782. entropy->restarts_to_go = cinfo->restart_interval;
  163783. }
  163784. entropy->restarts_to_go--;
  163785. }
  163786. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  163787. ci = cinfo->MCU_membership[blkn];
  163788. compptr = cinfo->cur_comp_info[ci];
  163789. htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
  163790. entropy->dc_count_ptrs[compptr->dc_tbl_no],
  163791. entropy->ac_count_ptrs[compptr->ac_tbl_no]);
  163792. entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
  163793. }
  163794. return TRUE;
  163795. }
  163796. /*
  163797. * Generate the best Huffman code table for the given counts, fill htbl.
  163798. * Note this is also used by jcphuff.c.
  163799. *
  163800. * The JPEG standard requires that no symbol be assigned a codeword of all
  163801. * one bits (so that padding bits added at the end of a compressed segment
  163802. * can't look like a valid code). Because of the canonical ordering of
  163803. * codewords, this just means that there must be an unused slot in the
  163804. * longest codeword length category. Section K.2 of the JPEG spec suggests
  163805. * reserving such a slot by pretending that symbol 256 is a valid symbol
  163806. * with count 1. In theory that's not optimal; giving it count zero but
  163807. * including it in the symbol set anyway should give a better Huffman code.
  163808. * But the theoretically better code actually seems to come out worse in
  163809. * practice, because it produces more all-ones bytes (which incur stuffed
  163810. * zero bytes in the final file). In any case the difference is tiny.
  163811. *
  163812. * The JPEG standard requires Huffman codes to be no more than 16 bits long.
  163813. * If some symbols have a very small but nonzero probability, the Huffman tree
  163814. * must be adjusted to meet the code length restriction. We currently use
  163815. * the adjustment method suggested in JPEG section K.2. This method is *not*
  163816. * optimal; it may not choose the best possible limited-length code. But
  163817. * typically only very-low-frequency symbols will be given less-than-optimal
  163818. * lengths, so the code is almost optimal. Experimental comparisons against
  163819. * an optimal limited-length-code algorithm indicate that the difference is
  163820. * microscopic --- usually less than a hundredth of a percent of total size.
  163821. * So the extra complexity of an optimal algorithm doesn't seem worthwhile.
  163822. */
  163823. GLOBAL(void)
  163824. jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[])
  163825. {
  163826. #define MAX_CLEN 32 /* assumed maximum initial code length */
  163827. UINT8 bits[MAX_CLEN+1]; /* bits[k] = # of symbols with code length k */
  163828. int codesize[257]; /* codesize[k] = code length of symbol k */
  163829. int others[257]; /* next symbol in current branch of tree */
  163830. int c1, c2;
  163831. int p, i, j;
  163832. long v;
  163833. /* This algorithm is explained in section K.2 of the JPEG standard */
  163834. MEMZERO(bits, SIZEOF(bits));
  163835. MEMZERO(codesize, SIZEOF(codesize));
  163836. for (i = 0; i < 257; i++)
  163837. others[i] = -1; /* init links to empty */
  163838. freq[256] = 1; /* make sure 256 has a nonzero count */
  163839. /* Including the pseudo-symbol 256 in the Huffman procedure guarantees
  163840. * that no real symbol is given code-value of all ones, because 256
  163841. * will be placed last in the largest codeword category.
  163842. */
  163843. /* Huffman's basic algorithm to assign optimal code lengths to symbols */
  163844. for (;;) {
  163845. /* Find the smallest nonzero frequency, set c1 = its symbol */
  163846. /* In case of ties, take the larger symbol number */
  163847. c1 = -1;
  163848. v = 1000000000L;
  163849. for (i = 0; i <= 256; i++) {
  163850. if (freq[i] && freq[i] <= v) {
  163851. v = freq[i];
  163852. c1 = i;
  163853. }
  163854. }
  163855. /* Find the next smallest nonzero frequency, set c2 = its symbol */
  163856. /* In case of ties, take the larger symbol number */
  163857. c2 = -1;
  163858. v = 1000000000L;
  163859. for (i = 0; i <= 256; i++) {
  163860. if (freq[i] && freq[i] <= v && i != c1) {
  163861. v = freq[i];
  163862. c2 = i;
  163863. }
  163864. }
  163865. /* Done if we've merged everything into one frequency */
  163866. if (c2 < 0)
  163867. break;
  163868. /* Else merge the two counts/trees */
  163869. freq[c1] += freq[c2];
  163870. freq[c2] = 0;
  163871. /* Increment the codesize of everything in c1's tree branch */
  163872. codesize[c1]++;
  163873. while (others[c1] >= 0) {
  163874. c1 = others[c1];
  163875. codesize[c1]++;
  163876. }
  163877. others[c1] = c2; /* chain c2 onto c1's tree branch */
  163878. /* Increment the codesize of everything in c2's tree branch */
  163879. codesize[c2]++;
  163880. while (others[c2] >= 0) {
  163881. c2 = others[c2];
  163882. codesize[c2]++;
  163883. }
  163884. }
  163885. /* Now count the number of symbols of each code length */
  163886. for (i = 0; i <= 256; i++) {
  163887. if (codesize[i]) {
  163888. /* The JPEG standard seems to think that this can't happen, */
  163889. /* but I'm paranoid... */
  163890. if (codesize[i] > MAX_CLEN)
  163891. ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);
  163892. bits[codesize[i]]++;
  163893. }
  163894. }
  163895. /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
  163896. * Huffman procedure assigned any such lengths, we must adjust the coding.
  163897. * Here is what the JPEG spec says about how this next bit works:
  163898. * Since symbols are paired for the longest Huffman code, the symbols are
  163899. * removed from this length category two at a time. The prefix for the pair
  163900. * (which is one bit shorter) is allocated to one of the pair; then,
  163901. * skipping the BITS entry for that prefix length, a code word from the next
  163902. * shortest nonzero BITS entry is converted into a prefix for two code words
  163903. * one bit longer.
  163904. */
  163905. for (i = MAX_CLEN; i > 16; i--) {
  163906. while (bits[i] > 0) {
  163907. j = i - 2; /* find length of new prefix to be used */
  163908. while (bits[j] == 0)
  163909. j--;
  163910. bits[i] -= 2; /* remove two symbols */
  163911. bits[i-1]++; /* one goes in this length */
  163912. bits[j+1] += 2; /* two new symbols in this length */
  163913. bits[j]--; /* symbol of this length is now a prefix */
  163914. }
  163915. }
  163916. /* Remove the count for the pseudo-symbol 256 from the largest codelength */
  163917. while (bits[i] == 0) /* find largest codelength still in use */
  163918. i--;
  163919. bits[i]--;
  163920. /* Return final symbol counts (only for lengths 0..16) */
  163921. MEMCOPY(htbl->bits, bits, SIZEOF(htbl->bits));
  163922. /* Return a list of the symbols sorted by code length */
  163923. /* It's not real clear to me why we don't need to consider the codelength
  163924. * changes made above, but the JPEG spec seems to think this works.
  163925. */
  163926. p = 0;
  163927. for (i = 1; i <= MAX_CLEN; i++) {
  163928. for (j = 0; j <= 255; j++) {
  163929. if (codesize[j] == i) {
  163930. htbl->huffval[p] = (UINT8) j;
  163931. p++;
  163932. }
  163933. }
  163934. }
  163935. /* Set sent_table FALSE so updated table will be written to JPEG file. */
  163936. htbl->sent_table = FALSE;
  163937. }
  163938. /*
  163939. * Finish up a statistics-gathering pass and create the new Huffman tables.
  163940. */
  163941. METHODDEF(void)
  163942. finish_pass_gather (j_compress_ptr cinfo)
  163943. {
  163944. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163945. int ci, dctbl, actbl;
  163946. jpeg_component_info * compptr;
  163947. JHUFF_TBL **htblptr;
  163948. boolean did_dc[NUM_HUFF_TBLS];
  163949. boolean did_ac[NUM_HUFF_TBLS];
  163950. /* It's important not to apply jpeg_gen_optimal_table more than once
  163951. * per table, because it clobbers the input frequency counts!
  163952. */
  163953. MEMZERO(did_dc, SIZEOF(did_dc));
  163954. MEMZERO(did_ac, SIZEOF(did_ac));
  163955. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  163956. compptr = cinfo->cur_comp_info[ci];
  163957. dctbl = compptr->dc_tbl_no;
  163958. actbl = compptr->ac_tbl_no;
  163959. if (! did_dc[dctbl]) {
  163960. htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl];
  163961. if (*htblptr == NULL)
  163962. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  163963. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
  163964. did_dc[dctbl] = TRUE;
  163965. }
  163966. if (! did_ac[actbl]) {
  163967. htblptr = & cinfo->ac_huff_tbl_ptrs[actbl];
  163968. if (*htblptr == NULL)
  163969. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  163970. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
  163971. did_ac[actbl] = TRUE;
  163972. }
  163973. }
  163974. }
  163975. #endif /* ENTROPY_OPT_SUPPORTED */
  163976. /*
  163977. * Module initialization routine for Huffman entropy encoding.
  163978. */
  163979. GLOBAL(void)
  163980. jinit_huff_encoder (j_compress_ptr cinfo)
  163981. {
  163982. huff_entropy_ptr entropy;
  163983. int i;
  163984. entropy = (huff_entropy_ptr)
  163985. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163986. SIZEOF(huff_entropy_encoder));
  163987. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  163988. entropy->pub.start_pass = start_pass_huff;
  163989. /* Mark tables unallocated */
  163990. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  163991. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  163992. #ifdef ENTROPY_OPT_SUPPORTED
  163993. entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
  163994. #endif
  163995. }
  163996. }
  163997. /*** End of inlined file: jchuff.c ***/
  163998. #undef emit_byte
  163999. /*** Start of inlined file: jcinit.c ***/
  164000. #define JPEG_INTERNALS
  164001. /*
  164002. * Master selection of compression modules.
  164003. * This is done once at the start of processing an image. We determine
  164004. * which modules will be used and give them appropriate initialization calls.
  164005. */
  164006. GLOBAL(void)
  164007. jinit_compress_master (j_compress_ptr cinfo)
  164008. {
  164009. /* Initialize master control (includes parameter checking/processing) */
  164010. jinit_c_master_control(cinfo, FALSE /* full compression */);
  164011. /* Preprocessing */
  164012. if (! cinfo->raw_data_in) {
  164013. jinit_color_converter(cinfo);
  164014. jinit_downsampler(cinfo);
  164015. jinit_c_prep_controller(cinfo, FALSE /* never need full buffer here */);
  164016. }
  164017. /* Forward DCT */
  164018. jinit_forward_dct(cinfo);
  164019. /* Entropy encoding: either Huffman or arithmetic coding. */
  164020. if (cinfo->arith_code) {
  164021. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  164022. } else {
  164023. if (cinfo->progressive_mode) {
  164024. #ifdef C_PROGRESSIVE_SUPPORTED
  164025. jinit_phuff_encoder(cinfo);
  164026. #else
  164027. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164028. #endif
  164029. } else
  164030. jinit_huff_encoder(cinfo);
  164031. }
  164032. /* Need a full-image coefficient buffer in any multi-pass mode. */
  164033. jinit_c_coef_controller(cinfo,
  164034. (boolean) (cinfo->num_scans > 1 || cinfo->optimize_coding));
  164035. jinit_c_main_controller(cinfo, FALSE /* never need full buffer here */);
  164036. jinit_marker_writer(cinfo);
  164037. /* We can now tell the memory manager to allocate virtual arrays. */
  164038. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  164039. /* Write the datastream header (SOI) immediately.
  164040. * Frame and scan headers are postponed till later.
  164041. * This lets application insert special markers after the SOI.
  164042. */
  164043. (*cinfo->marker->write_file_header) (cinfo);
  164044. }
  164045. /*** End of inlined file: jcinit.c ***/
  164046. /*** Start of inlined file: jcmainct.c ***/
  164047. #define JPEG_INTERNALS
  164048. /* Note: currently, there is no operating mode in which a full-image buffer
  164049. * is needed at this step. If there were, that mode could not be used with
  164050. * "raw data" input, since this module is bypassed in that case. However,
  164051. * we've left the code here for possible use in special applications.
  164052. */
  164053. #undef FULL_MAIN_BUFFER_SUPPORTED
  164054. /* Private buffer controller object */
  164055. typedef struct {
  164056. struct jpeg_c_main_controller pub; /* public fields */
  164057. JDIMENSION cur_iMCU_row; /* number of current iMCU row */
  164058. JDIMENSION rowgroup_ctr; /* counts row groups received in iMCU row */
  164059. boolean suspended; /* remember if we suspended output */
  164060. J_BUF_MODE pass_mode; /* current operating mode */
  164061. /* If using just a strip buffer, this points to the entire set of buffers
  164062. * (we allocate one for each component). In the full-image case, this
  164063. * points to the currently accessible strips of the virtual arrays.
  164064. */
  164065. JSAMPARRAY buffer[MAX_COMPONENTS];
  164066. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164067. /* If using full-image storage, this array holds pointers to virtual-array
  164068. * control blocks for each component. Unused if not full-image storage.
  164069. */
  164070. jvirt_sarray_ptr whole_image[MAX_COMPONENTS];
  164071. #endif
  164072. } my_main_controller;
  164073. typedef my_main_controller * my_main_ptr;
  164074. /* Forward declarations */
  164075. METHODDEF(void) process_data_simple_main
  164076. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  164077. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  164078. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164079. METHODDEF(void) process_data_buffer_main
  164080. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  164081. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  164082. #endif
  164083. /*
  164084. * Initialize for a processing pass.
  164085. */
  164086. METHODDEF(void)
  164087. start_pass_main (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  164088. {
  164089. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  164090. /* Do nothing in raw-data mode. */
  164091. if (cinfo->raw_data_in)
  164092. return;
  164093. main_->cur_iMCU_row = 0; /* initialize counters */
  164094. main_->rowgroup_ctr = 0;
  164095. main_->suspended = FALSE;
  164096. main_->pass_mode = pass_mode; /* save mode for use by process_data */
  164097. switch (pass_mode) {
  164098. case JBUF_PASS_THRU:
  164099. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164100. if (main_->whole_image[0] != NULL)
  164101. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  164102. #endif
  164103. main_->pub.process_data = process_data_simple_main;
  164104. break;
  164105. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164106. case JBUF_SAVE_SOURCE:
  164107. case JBUF_CRANK_DEST:
  164108. case JBUF_SAVE_AND_PASS:
  164109. if (main_->whole_image[0] == NULL)
  164110. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  164111. main_->pub.process_data = process_data_buffer_main;
  164112. break;
  164113. #endif
  164114. default:
  164115. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  164116. break;
  164117. }
  164118. }
  164119. /*
  164120. * Process some data.
  164121. * This routine handles the simple pass-through mode,
  164122. * where we have only a strip buffer.
  164123. */
  164124. METHODDEF(void)
  164125. process_data_simple_main (j_compress_ptr cinfo,
  164126. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  164127. JDIMENSION in_rows_avail)
  164128. {
  164129. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  164130. while (main_->cur_iMCU_row < cinfo->total_iMCU_rows) {
  164131. /* Read input data if we haven't filled the main buffer yet */
  164132. if (main_->rowgroup_ctr < DCTSIZE)
  164133. (*cinfo->prep->pre_process_data) (cinfo,
  164134. input_buf, in_row_ctr, in_rows_avail,
  164135. main_->buffer, &main_->rowgroup_ctr,
  164136. (JDIMENSION) DCTSIZE);
  164137. /* If we don't have a full iMCU row buffered, return to application for
  164138. * more data. Note that preprocessor will always pad to fill the iMCU row
  164139. * at the bottom of the image.
  164140. */
  164141. if (main_->rowgroup_ctr != DCTSIZE)
  164142. return;
  164143. /* Send the completed row to the compressor */
  164144. if (! (*cinfo->coef->compress_data) (cinfo, main_->buffer)) {
  164145. /* If compressor did not consume the whole row, then we must need to
  164146. * suspend processing and return to the application. In this situation
  164147. * we pretend we didn't yet consume the last input row; otherwise, if
  164148. * it happened to be the last row of the image, the application would
  164149. * think we were done.
  164150. */
  164151. if (! main_->suspended) {
  164152. (*in_row_ctr)--;
  164153. main_->suspended = TRUE;
  164154. }
  164155. return;
  164156. }
  164157. /* We did finish the row. Undo our little suspension hack if a previous
  164158. * call suspended; then mark the main buffer empty.
  164159. */
  164160. if (main_->suspended) {
  164161. (*in_row_ctr)++;
  164162. main_->suspended = FALSE;
  164163. }
  164164. main_->rowgroup_ctr = 0;
  164165. main_->cur_iMCU_row++;
  164166. }
  164167. }
  164168. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164169. /*
  164170. * Process some data.
  164171. * This routine handles all of the modes that use a full-size buffer.
  164172. */
  164173. METHODDEF(void)
  164174. process_data_buffer_main (j_compress_ptr cinfo,
  164175. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  164176. JDIMENSION in_rows_avail)
  164177. {
  164178. my_main_ptr main = (my_main_ptr) cinfo->main;
  164179. int ci;
  164180. jpeg_component_info *compptr;
  164181. boolean writing = (main->pass_mode != JBUF_CRANK_DEST);
  164182. while (main->cur_iMCU_row < cinfo->total_iMCU_rows) {
  164183. /* Realign the virtual buffers if at the start of an iMCU row. */
  164184. if (main->rowgroup_ctr == 0) {
  164185. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164186. ci++, compptr++) {
  164187. main->buffer[ci] = (*cinfo->mem->access_virt_sarray)
  164188. ((j_common_ptr) cinfo, main->whole_image[ci],
  164189. main->cur_iMCU_row * (compptr->v_samp_factor * DCTSIZE),
  164190. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE), writing);
  164191. }
  164192. /* In a read pass, pretend we just read some source data. */
  164193. if (! writing) {
  164194. *in_row_ctr += cinfo->max_v_samp_factor * DCTSIZE;
  164195. main->rowgroup_ctr = DCTSIZE;
  164196. }
  164197. }
  164198. /* If a write pass, read input data until the current iMCU row is full. */
  164199. /* Note: preprocessor will pad if necessary to fill the last iMCU row. */
  164200. if (writing) {
  164201. (*cinfo->prep->pre_process_data) (cinfo,
  164202. input_buf, in_row_ctr, in_rows_avail,
  164203. main->buffer, &main->rowgroup_ctr,
  164204. (JDIMENSION) DCTSIZE);
  164205. /* Return to application if we need more data to fill the iMCU row. */
  164206. if (main->rowgroup_ctr < DCTSIZE)
  164207. return;
  164208. }
  164209. /* Emit data, unless this is a sink-only pass. */
  164210. if (main->pass_mode != JBUF_SAVE_SOURCE) {
  164211. if (! (*cinfo->coef->compress_data) (cinfo, main->buffer)) {
  164212. /* If compressor did not consume the whole row, then we must need to
  164213. * suspend processing and return to the application. In this situation
  164214. * we pretend we didn't yet consume the last input row; otherwise, if
  164215. * it happened to be the last row of the image, the application would
  164216. * think we were done.
  164217. */
  164218. if (! main->suspended) {
  164219. (*in_row_ctr)--;
  164220. main->suspended = TRUE;
  164221. }
  164222. return;
  164223. }
  164224. /* We did finish the row. Undo our little suspension hack if a previous
  164225. * call suspended; then mark the main buffer empty.
  164226. */
  164227. if (main->suspended) {
  164228. (*in_row_ctr)++;
  164229. main->suspended = FALSE;
  164230. }
  164231. }
  164232. /* If get here, we are done with this iMCU row. Mark buffer empty. */
  164233. main->rowgroup_ctr = 0;
  164234. main->cur_iMCU_row++;
  164235. }
  164236. }
  164237. #endif /* FULL_MAIN_BUFFER_SUPPORTED */
  164238. /*
  164239. * Initialize main buffer controller.
  164240. */
  164241. GLOBAL(void)
  164242. jinit_c_main_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  164243. {
  164244. my_main_ptr main_;
  164245. int ci;
  164246. jpeg_component_info *compptr;
  164247. main_ = (my_main_ptr)
  164248. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164249. SIZEOF(my_main_controller));
  164250. cinfo->main = (struct jpeg_c_main_controller *) main_;
  164251. main_->pub.start_pass = start_pass_main;
  164252. /* We don't need to create a buffer in raw-data mode. */
  164253. if (cinfo->raw_data_in)
  164254. return;
  164255. /* Create the buffer. It holds downsampled data, so each component
  164256. * may be of a different size.
  164257. */
  164258. if (need_full_buffer) {
  164259. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164260. /* Allocate a full-image virtual array for each component */
  164261. /* Note we pad the bottom to a multiple of the iMCU height */
  164262. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164263. ci++, compptr++) {
  164264. main->whole_image[ci] = (*cinfo->mem->request_virt_sarray)
  164265. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  164266. compptr->width_in_blocks * DCTSIZE,
  164267. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  164268. (long) compptr->v_samp_factor) * DCTSIZE,
  164269. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  164270. }
  164271. #else
  164272. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  164273. #endif
  164274. } else {
  164275. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164276. main_->whole_image[0] = NULL; /* flag for no virtual arrays */
  164277. #endif
  164278. /* Allocate a strip buffer for each component */
  164279. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164280. ci++, compptr++) {
  164281. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  164282. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164283. compptr->width_in_blocks * DCTSIZE,
  164284. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  164285. }
  164286. }
  164287. }
  164288. /*** End of inlined file: jcmainct.c ***/
  164289. /*** Start of inlined file: jcmarker.c ***/
  164290. #define JPEG_INTERNALS
  164291. /* Private state */
  164292. typedef struct {
  164293. struct jpeg_marker_writer pub; /* public fields */
  164294. unsigned int last_restart_interval; /* last DRI value emitted; 0 after SOI */
  164295. } my_marker_writer;
  164296. typedef my_marker_writer * my_marker_ptr;
  164297. /*
  164298. * Basic output routines.
  164299. *
  164300. * Note that we do not support suspension while writing a marker.
  164301. * Therefore, an application using suspension must ensure that there is
  164302. * enough buffer space for the initial markers (typ. 600-700 bytes) before
  164303. * calling jpeg_start_compress, and enough space to write the trailing EOI
  164304. * (a few bytes) before calling jpeg_finish_compress. Multipass compression
  164305. * modes are not supported at all with suspension, so those two are the only
  164306. * points where markers will be written.
  164307. */
  164308. LOCAL(void)
  164309. emit_byte (j_compress_ptr cinfo, int val)
  164310. /* Emit a byte */
  164311. {
  164312. struct jpeg_destination_mgr * dest = cinfo->dest;
  164313. *(dest->next_output_byte)++ = (JOCTET) val;
  164314. if (--dest->free_in_buffer == 0) {
  164315. if (! (*dest->empty_output_buffer) (cinfo))
  164316. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  164317. }
  164318. }
  164319. LOCAL(void)
  164320. emit_marker (j_compress_ptr cinfo, JPEG_MARKER mark)
  164321. /* Emit a marker code */
  164322. {
  164323. emit_byte(cinfo, 0xFF);
  164324. emit_byte(cinfo, (int) mark);
  164325. }
  164326. LOCAL(void)
  164327. emit_2bytes (j_compress_ptr cinfo, int value)
  164328. /* Emit a 2-byte integer; these are always MSB first in JPEG files */
  164329. {
  164330. emit_byte(cinfo, (value >> 8) & 0xFF);
  164331. emit_byte(cinfo, value & 0xFF);
  164332. }
  164333. /*
  164334. * Routines to write specific marker types.
  164335. */
  164336. LOCAL(int)
  164337. emit_dqt (j_compress_ptr cinfo, int index)
  164338. /* Emit a DQT marker */
  164339. /* Returns the precision used (0 = 8bits, 1 = 16bits) for baseline checking */
  164340. {
  164341. JQUANT_TBL * qtbl = cinfo->quant_tbl_ptrs[index];
  164342. int prec;
  164343. int i;
  164344. if (qtbl == NULL)
  164345. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, index);
  164346. prec = 0;
  164347. for (i = 0; i < DCTSIZE2; i++) {
  164348. if (qtbl->quantval[i] > 255)
  164349. prec = 1;
  164350. }
  164351. if (! qtbl->sent_table) {
  164352. emit_marker(cinfo, M_DQT);
  164353. emit_2bytes(cinfo, prec ? DCTSIZE2*2 + 1 + 2 : DCTSIZE2 + 1 + 2);
  164354. emit_byte(cinfo, index + (prec<<4));
  164355. for (i = 0; i < DCTSIZE2; i++) {
  164356. /* The table entries must be emitted in zigzag order. */
  164357. unsigned int qval = qtbl->quantval[jpeg_natural_order[i]];
  164358. if (prec)
  164359. emit_byte(cinfo, (int) (qval >> 8));
  164360. emit_byte(cinfo, (int) (qval & 0xFF));
  164361. }
  164362. qtbl->sent_table = TRUE;
  164363. }
  164364. return prec;
  164365. }
  164366. LOCAL(void)
  164367. emit_dht (j_compress_ptr cinfo, int index, boolean is_ac)
  164368. /* Emit a DHT marker */
  164369. {
  164370. JHUFF_TBL * htbl;
  164371. int length, i;
  164372. if (is_ac) {
  164373. htbl = cinfo->ac_huff_tbl_ptrs[index];
  164374. index += 0x10; /* output index has AC bit set */
  164375. } else {
  164376. htbl = cinfo->dc_huff_tbl_ptrs[index];
  164377. }
  164378. if (htbl == NULL)
  164379. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, index);
  164380. if (! htbl->sent_table) {
  164381. emit_marker(cinfo, M_DHT);
  164382. length = 0;
  164383. for (i = 1; i <= 16; i++)
  164384. length += htbl->bits[i];
  164385. emit_2bytes(cinfo, length + 2 + 1 + 16);
  164386. emit_byte(cinfo, index);
  164387. for (i = 1; i <= 16; i++)
  164388. emit_byte(cinfo, htbl->bits[i]);
  164389. for (i = 0; i < length; i++)
  164390. emit_byte(cinfo, htbl->huffval[i]);
  164391. htbl->sent_table = TRUE;
  164392. }
  164393. }
  164394. LOCAL(void)
  164395. emit_dac (j_compress_ptr)
  164396. /* Emit a DAC marker */
  164397. /* Since the useful info is so small, we want to emit all the tables in */
  164398. /* one DAC marker. Therefore this routine does its own scan of the table. */
  164399. {
  164400. #ifdef C_ARITH_CODING_SUPPORTED
  164401. char dc_in_use[NUM_ARITH_TBLS];
  164402. char ac_in_use[NUM_ARITH_TBLS];
  164403. int length, i;
  164404. jpeg_component_info *compptr;
  164405. for (i = 0; i < NUM_ARITH_TBLS; i++)
  164406. dc_in_use[i] = ac_in_use[i] = 0;
  164407. for (i = 0; i < cinfo->comps_in_scan; i++) {
  164408. compptr = cinfo->cur_comp_info[i];
  164409. dc_in_use[compptr->dc_tbl_no] = 1;
  164410. ac_in_use[compptr->ac_tbl_no] = 1;
  164411. }
  164412. length = 0;
  164413. for (i = 0; i < NUM_ARITH_TBLS; i++)
  164414. length += dc_in_use[i] + ac_in_use[i];
  164415. emit_marker(cinfo, M_DAC);
  164416. emit_2bytes(cinfo, length*2 + 2);
  164417. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  164418. if (dc_in_use[i]) {
  164419. emit_byte(cinfo, i);
  164420. emit_byte(cinfo, cinfo->arith_dc_L[i] + (cinfo->arith_dc_U[i]<<4));
  164421. }
  164422. if (ac_in_use[i]) {
  164423. emit_byte(cinfo, i + 0x10);
  164424. emit_byte(cinfo, cinfo->arith_ac_K[i]);
  164425. }
  164426. }
  164427. #endif /* C_ARITH_CODING_SUPPORTED */
  164428. }
  164429. LOCAL(void)
  164430. emit_dri (j_compress_ptr cinfo)
  164431. /* Emit a DRI marker */
  164432. {
  164433. emit_marker(cinfo, M_DRI);
  164434. emit_2bytes(cinfo, 4); /* fixed length */
  164435. emit_2bytes(cinfo, (int) cinfo->restart_interval);
  164436. }
  164437. LOCAL(void)
  164438. emit_sof (j_compress_ptr cinfo, JPEG_MARKER code)
  164439. /* Emit a SOF marker */
  164440. {
  164441. int ci;
  164442. jpeg_component_info *compptr;
  164443. emit_marker(cinfo, code);
  164444. emit_2bytes(cinfo, 3 * cinfo->num_components + 2 + 5 + 1); /* length */
  164445. /* Make sure image isn't bigger than SOF field can handle */
  164446. if ((long) cinfo->image_height > 65535L ||
  164447. (long) cinfo->image_width > 65535L)
  164448. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) 65535);
  164449. emit_byte(cinfo, cinfo->data_precision);
  164450. emit_2bytes(cinfo, (int) cinfo->image_height);
  164451. emit_2bytes(cinfo, (int) cinfo->image_width);
  164452. emit_byte(cinfo, cinfo->num_components);
  164453. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164454. ci++, compptr++) {
  164455. emit_byte(cinfo, compptr->component_id);
  164456. emit_byte(cinfo, (compptr->h_samp_factor << 4) + compptr->v_samp_factor);
  164457. emit_byte(cinfo, compptr->quant_tbl_no);
  164458. }
  164459. }
  164460. LOCAL(void)
  164461. emit_sos (j_compress_ptr cinfo)
  164462. /* Emit a SOS marker */
  164463. {
  164464. int i, td, ta;
  164465. jpeg_component_info *compptr;
  164466. emit_marker(cinfo, M_SOS);
  164467. emit_2bytes(cinfo, 2 * cinfo->comps_in_scan + 2 + 1 + 3); /* length */
  164468. emit_byte(cinfo, cinfo->comps_in_scan);
  164469. for (i = 0; i < cinfo->comps_in_scan; i++) {
  164470. compptr = cinfo->cur_comp_info[i];
  164471. emit_byte(cinfo, compptr->component_id);
  164472. td = compptr->dc_tbl_no;
  164473. ta = compptr->ac_tbl_no;
  164474. if (cinfo->progressive_mode) {
  164475. /* Progressive mode: only DC or only AC tables are used in one scan;
  164476. * furthermore, Huffman coding of DC refinement uses no table at all.
  164477. * We emit 0 for unused field(s); this is recommended by the P&M text
  164478. * but does not seem to be specified in the standard.
  164479. */
  164480. if (cinfo->Ss == 0) {
  164481. ta = 0; /* DC scan */
  164482. if (cinfo->Ah != 0 && !cinfo->arith_code)
  164483. td = 0; /* no DC table either */
  164484. } else {
  164485. td = 0; /* AC scan */
  164486. }
  164487. }
  164488. emit_byte(cinfo, (td << 4) + ta);
  164489. }
  164490. emit_byte(cinfo, cinfo->Ss);
  164491. emit_byte(cinfo, cinfo->Se);
  164492. emit_byte(cinfo, (cinfo->Ah << 4) + cinfo->Al);
  164493. }
  164494. LOCAL(void)
  164495. emit_jfif_app0 (j_compress_ptr cinfo)
  164496. /* Emit a JFIF-compliant APP0 marker */
  164497. {
  164498. /*
  164499. * Length of APP0 block (2 bytes)
  164500. * Block ID (4 bytes - ASCII "JFIF")
  164501. * Zero byte (1 byte to terminate the ID string)
  164502. * Version Major, Minor (2 bytes - major first)
  164503. * Units (1 byte - 0x00 = none, 0x01 = inch, 0x02 = cm)
  164504. * Xdpu (2 bytes - dots per unit horizontal)
  164505. * Ydpu (2 bytes - dots per unit vertical)
  164506. * Thumbnail X size (1 byte)
  164507. * Thumbnail Y size (1 byte)
  164508. */
  164509. emit_marker(cinfo, M_APP0);
  164510. emit_2bytes(cinfo, 2 + 4 + 1 + 2 + 1 + 2 + 2 + 1 + 1); /* length */
  164511. emit_byte(cinfo, 0x4A); /* Identifier: ASCII "JFIF" */
  164512. emit_byte(cinfo, 0x46);
  164513. emit_byte(cinfo, 0x49);
  164514. emit_byte(cinfo, 0x46);
  164515. emit_byte(cinfo, 0);
  164516. emit_byte(cinfo, cinfo->JFIF_major_version); /* Version fields */
  164517. emit_byte(cinfo, cinfo->JFIF_minor_version);
  164518. emit_byte(cinfo, cinfo->density_unit); /* Pixel size information */
  164519. emit_2bytes(cinfo, (int) cinfo->X_density);
  164520. emit_2bytes(cinfo, (int) cinfo->Y_density);
  164521. emit_byte(cinfo, 0); /* No thumbnail image */
  164522. emit_byte(cinfo, 0);
  164523. }
  164524. LOCAL(void)
  164525. emit_adobe_app14 (j_compress_ptr cinfo)
  164526. /* Emit an Adobe APP14 marker */
  164527. {
  164528. /*
  164529. * Length of APP14 block (2 bytes)
  164530. * Block ID (5 bytes - ASCII "Adobe")
  164531. * Version Number (2 bytes - currently 100)
  164532. * Flags0 (2 bytes - currently 0)
  164533. * Flags1 (2 bytes - currently 0)
  164534. * Color transform (1 byte)
  164535. *
  164536. * Although Adobe TN 5116 mentions Version = 101, all the Adobe files
  164537. * now in circulation seem to use Version = 100, so that's what we write.
  164538. *
  164539. * We write the color transform byte as 1 if the JPEG color space is
  164540. * YCbCr, 2 if it's YCCK, 0 otherwise. Adobe's definition has to do with
  164541. * whether the encoder performed a transformation, which is pretty useless.
  164542. */
  164543. emit_marker(cinfo, M_APP14);
  164544. emit_2bytes(cinfo, 2 + 5 + 2 + 2 + 2 + 1); /* length */
  164545. emit_byte(cinfo, 0x41); /* Identifier: ASCII "Adobe" */
  164546. emit_byte(cinfo, 0x64);
  164547. emit_byte(cinfo, 0x6F);
  164548. emit_byte(cinfo, 0x62);
  164549. emit_byte(cinfo, 0x65);
  164550. emit_2bytes(cinfo, 100); /* Version */
  164551. emit_2bytes(cinfo, 0); /* Flags0 */
  164552. emit_2bytes(cinfo, 0); /* Flags1 */
  164553. switch (cinfo->jpeg_color_space) {
  164554. case JCS_YCbCr:
  164555. emit_byte(cinfo, 1); /* Color transform = 1 */
  164556. break;
  164557. case JCS_YCCK:
  164558. emit_byte(cinfo, 2); /* Color transform = 2 */
  164559. break;
  164560. default:
  164561. emit_byte(cinfo, 0); /* Color transform = 0 */
  164562. break;
  164563. }
  164564. }
  164565. /*
  164566. * These routines allow writing an arbitrary marker with parameters.
  164567. * The only intended use is to emit COM or APPn markers after calling
  164568. * write_file_header and before calling write_frame_header.
  164569. * Other uses are not guaranteed to produce desirable results.
  164570. * Counting the parameter bytes properly is the caller's responsibility.
  164571. */
  164572. METHODDEF(void)
  164573. write_marker_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  164574. /* Emit an arbitrary marker header */
  164575. {
  164576. if (datalen > (unsigned int) 65533) /* safety check */
  164577. ERREXIT(cinfo, JERR_BAD_LENGTH);
  164578. emit_marker(cinfo, (JPEG_MARKER) marker);
  164579. emit_2bytes(cinfo, (int) (datalen + 2)); /* total length */
  164580. }
  164581. METHODDEF(void)
  164582. write_marker_byte (j_compress_ptr cinfo, int val)
  164583. /* Emit one byte of marker parameters following write_marker_header */
  164584. {
  164585. emit_byte(cinfo, val);
  164586. }
  164587. /*
  164588. * Write datastream header.
  164589. * This consists of an SOI and optional APPn markers.
  164590. * We recommend use of the JFIF marker, but not the Adobe marker,
  164591. * when using YCbCr or grayscale data. The JFIF marker should NOT
  164592. * be used for any other JPEG colorspace. The Adobe marker is helpful
  164593. * to distinguish RGB, CMYK, and YCCK colorspaces.
  164594. * Note that an application can write additional header markers after
  164595. * jpeg_start_compress returns.
  164596. */
  164597. METHODDEF(void)
  164598. write_file_header (j_compress_ptr cinfo)
  164599. {
  164600. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  164601. emit_marker(cinfo, M_SOI); /* first the SOI */
  164602. /* SOI is defined to reset restart interval to 0 */
  164603. marker->last_restart_interval = 0;
  164604. if (cinfo->write_JFIF_header) /* next an optional JFIF APP0 */
  164605. emit_jfif_app0(cinfo);
  164606. if (cinfo->write_Adobe_marker) /* next an optional Adobe APP14 */
  164607. emit_adobe_app14(cinfo);
  164608. }
  164609. /*
  164610. * Write frame header.
  164611. * This consists of DQT and SOFn markers.
  164612. * Note that we do not emit the SOF until we have emitted the DQT(s).
  164613. * This avoids compatibility problems with incorrect implementations that
  164614. * try to error-check the quant table numbers as soon as they see the SOF.
  164615. */
  164616. METHODDEF(void)
  164617. write_frame_header (j_compress_ptr cinfo)
  164618. {
  164619. int ci, prec;
  164620. boolean is_baseline;
  164621. jpeg_component_info *compptr;
  164622. /* Emit DQT for each quantization table.
  164623. * Note that emit_dqt() suppresses any duplicate tables.
  164624. */
  164625. prec = 0;
  164626. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164627. ci++, compptr++) {
  164628. prec += emit_dqt(cinfo, compptr->quant_tbl_no);
  164629. }
  164630. /* now prec is nonzero iff there are any 16-bit quant tables. */
  164631. /* Check for a non-baseline specification.
  164632. * Note we assume that Huffman table numbers won't be changed later.
  164633. */
  164634. if (cinfo->arith_code || cinfo->progressive_mode ||
  164635. cinfo->data_precision != 8) {
  164636. is_baseline = FALSE;
  164637. } else {
  164638. is_baseline = TRUE;
  164639. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164640. ci++, compptr++) {
  164641. if (compptr->dc_tbl_no > 1 || compptr->ac_tbl_no > 1)
  164642. is_baseline = FALSE;
  164643. }
  164644. if (prec && is_baseline) {
  164645. is_baseline = FALSE;
  164646. /* If it's baseline except for quantizer size, warn the user */
  164647. TRACEMS(cinfo, 0, JTRC_16BIT_TABLES);
  164648. }
  164649. }
  164650. /* Emit the proper SOF marker */
  164651. if (cinfo->arith_code) {
  164652. emit_sof(cinfo, M_SOF9); /* SOF code for arithmetic coding */
  164653. } else {
  164654. if (cinfo->progressive_mode)
  164655. emit_sof(cinfo, M_SOF2); /* SOF code for progressive Huffman */
  164656. else if (is_baseline)
  164657. emit_sof(cinfo, M_SOF0); /* SOF code for baseline implementation */
  164658. else
  164659. emit_sof(cinfo, M_SOF1); /* SOF code for non-baseline Huffman file */
  164660. }
  164661. }
  164662. /*
  164663. * Write scan header.
  164664. * This consists of DHT or DAC markers, optional DRI, and SOS.
  164665. * Compressed data will be written following the SOS.
  164666. */
  164667. METHODDEF(void)
  164668. write_scan_header (j_compress_ptr cinfo)
  164669. {
  164670. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  164671. int i;
  164672. jpeg_component_info *compptr;
  164673. if (cinfo->arith_code) {
  164674. /* Emit arith conditioning info. We may have some duplication
  164675. * if the file has multiple scans, but it's so small it's hardly
  164676. * worth worrying about.
  164677. */
  164678. emit_dac(cinfo);
  164679. } else {
  164680. /* Emit Huffman tables.
  164681. * Note that emit_dht() suppresses any duplicate tables.
  164682. */
  164683. for (i = 0; i < cinfo->comps_in_scan; i++) {
  164684. compptr = cinfo->cur_comp_info[i];
  164685. if (cinfo->progressive_mode) {
  164686. /* Progressive mode: only DC or only AC tables are used in one scan */
  164687. if (cinfo->Ss == 0) {
  164688. if (cinfo->Ah == 0) /* DC needs no table for refinement scan */
  164689. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  164690. } else {
  164691. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  164692. }
  164693. } else {
  164694. /* Sequential mode: need both DC and AC tables */
  164695. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  164696. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  164697. }
  164698. }
  164699. }
  164700. /* Emit DRI if required --- note that DRI value could change for each scan.
  164701. * We avoid wasting space with unnecessary DRIs, however.
  164702. */
  164703. if (cinfo->restart_interval != marker->last_restart_interval) {
  164704. emit_dri(cinfo);
  164705. marker->last_restart_interval = cinfo->restart_interval;
  164706. }
  164707. emit_sos(cinfo);
  164708. }
  164709. /*
  164710. * Write datastream trailer.
  164711. */
  164712. METHODDEF(void)
  164713. write_file_trailer (j_compress_ptr cinfo)
  164714. {
  164715. emit_marker(cinfo, M_EOI);
  164716. }
  164717. /*
  164718. * Write an abbreviated table-specification datastream.
  164719. * This consists of SOI, DQT and DHT tables, and EOI.
  164720. * Any table that is defined and not marked sent_table = TRUE will be
  164721. * emitted. Note that all tables will be marked sent_table = TRUE at exit.
  164722. */
  164723. METHODDEF(void)
  164724. write_tables_only (j_compress_ptr cinfo)
  164725. {
  164726. int i;
  164727. emit_marker(cinfo, M_SOI);
  164728. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  164729. if (cinfo->quant_tbl_ptrs[i] != NULL)
  164730. (void) emit_dqt(cinfo, i);
  164731. }
  164732. if (! cinfo->arith_code) {
  164733. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  164734. if (cinfo->dc_huff_tbl_ptrs[i] != NULL)
  164735. emit_dht(cinfo, i, FALSE);
  164736. if (cinfo->ac_huff_tbl_ptrs[i] != NULL)
  164737. emit_dht(cinfo, i, TRUE);
  164738. }
  164739. }
  164740. emit_marker(cinfo, M_EOI);
  164741. }
  164742. /*
  164743. * Initialize the marker writer module.
  164744. */
  164745. GLOBAL(void)
  164746. jinit_marker_writer (j_compress_ptr cinfo)
  164747. {
  164748. my_marker_ptr marker;
  164749. /* Create the subobject */
  164750. marker = (my_marker_ptr)
  164751. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164752. SIZEOF(my_marker_writer));
  164753. cinfo->marker = (struct jpeg_marker_writer *) marker;
  164754. /* Initialize method pointers */
  164755. marker->pub.write_file_header = write_file_header;
  164756. marker->pub.write_frame_header = write_frame_header;
  164757. marker->pub.write_scan_header = write_scan_header;
  164758. marker->pub.write_file_trailer = write_file_trailer;
  164759. marker->pub.write_tables_only = write_tables_only;
  164760. marker->pub.write_marker_header = write_marker_header;
  164761. marker->pub.write_marker_byte = write_marker_byte;
  164762. /* Initialize private state */
  164763. marker->last_restart_interval = 0;
  164764. }
  164765. /*** End of inlined file: jcmarker.c ***/
  164766. /*** Start of inlined file: jcmaster.c ***/
  164767. #define JPEG_INTERNALS
  164768. /* Private state */
  164769. typedef enum {
  164770. main_pass, /* input data, also do first output step */
  164771. huff_opt_pass, /* Huffman code optimization pass */
  164772. output_pass /* data output pass */
  164773. } c_pass_type;
  164774. typedef struct {
  164775. struct jpeg_comp_master pub; /* public fields */
  164776. c_pass_type pass_type; /* the type of the current pass */
  164777. int pass_number; /* # of passes completed */
  164778. int total_passes; /* total # of passes needed */
  164779. int scan_number; /* current index in scan_info[] */
  164780. } my_comp_master;
  164781. typedef my_comp_master * my_master_ptr;
  164782. /*
  164783. * Support routines that do various essential calculations.
  164784. */
  164785. LOCAL(void)
  164786. initial_setup (j_compress_ptr cinfo)
  164787. /* Do computations that are needed before master selection phase */
  164788. {
  164789. int ci;
  164790. jpeg_component_info *compptr;
  164791. long samplesperrow;
  164792. JDIMENSION jd_samplesperrow;
  164793. /* Sanity check on image dimensions */
  164794. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  164795. || cinfo->num_components <= 0 || cinfo->input_components <= 0)
  164796. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  164797. /* Make sure image isn't bigger than I can handle */
  164798. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  164799. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  164800. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  164801. /* Width of an input scanline must be representable as JDIMENSION. */
  164802. samplesperrow = (long) cinfo->image_width * (long) cinfo->input_components;
  164803. jd_samplesperrow = (JDIMENSION) samplesperrow;
  164804. if ((long) jd_samplesperrow != samplesperrow)
  164805. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  164806. /* For now, precision must match compiled-in value... */
  164807. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  164808. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  164809. /* Check that number of components won't exceed internal array sizes */
  164810. if (cinfo->num_components > MAX_COMPONENTS)
  164811. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  164812. MAX_COMPONENTS);
  164813. /* Compute maximum sampling factors; check factor validity */
  164814. cinfo->max_h_samp_factor = 1;
  164815. cinfo->max_v_samp_factor = 1;
  164816. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164817. ci++, compptr++) {
  164818. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  164819. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  164820. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  164821. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  164822. compptr->h_samp_factor);
  164823. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  164824. compptr->v_samp_factor);
  164825. }
  164826. /* Compute dimensions of components */
  164827. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164828. ci++, compptr++) {
  164829. /* Fill in the correct component_index value; don't rely on application */
  164830. compptr->component_index = ci;
  164831. /* For compression, we never do DCT scaling. */
  164832. compptr->DCT_scaled_size = DCTSIZE;
  164833. /* Size in DCT blocks */
  164834. compptr->width_in_blocks = (JDIMENSION)
  164835. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  164836. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  164837. compptr->height_in_blocks = (JDIMENSION)
  164838. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  164839. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  164840. /* Size in samples */
  164841. compptr->downsampled_width = (JDIMENSION)
  164842. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  164843. (long) cinfo->max_h_samp_factor);
  164844. compptr->downsampled_height = (JDIMENSION)
  164845. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  164846. (long) cinfo->max_v_samp_factor);
  164847. /* Mark component needed (this flag isn't actually used for compression) */
  164848. compptr->component_needed = TRUE;
  164849. }
  164850. /* Compute number of fully interleaved MCU rows (number of times that
  164851. * main controller will call coefficient controller).
  164852. */
  164853. cinfo->total_iMCU_rows = (JDIMENSION)
  164854. jdiv_round_up((long) cinfo->image_height,
  164855. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  164856. }
  164857. #ifdef C_MULTISCAN_FILES_SUPPORTED
  164858. LOCAL(void)
  164859. validate_script (j_compress_ptr cinfo)
  164860. /* Verify that the scan script in cinfo->scan_info[] is valid; also
  164861. * determine whether it uses progressive JPEG, and set cinfo->progressive_mode.
  164862. */
  164863. {
  164864. const jpeg_scan_info * scanptr;
  164865. int scanno, ncomps, ci, coefi, thisi;
  164866. int Ss, Se, Ah, Al;
  164867. boolean component_sent[MAX_COMPONENTS];
  164868. #ifdef C_PROGRESSIVE_SUPPORTED
  164869. int * last_bitpos_ptr;
  164870. int last_bitpos[MAX_COMPONENTS][DCTSIZE2];
  164871. /* -1 until that coefficient has been seen; then last Al for it */
  164872. #endif
  164873. if (cinfo->num_scans <= 0)
  164874. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, 0);
  164875. /* For sequential JPEG, all scans must have Ss=0, Se=DCTSIZE2-1;
  164876. * for progressive JPEG, no scan can have this.
  164877. */
  164878. scanptr = cinfo->scan_info;
  164879. if (scanptr->Ss != 0 || scanptr->Se != DCTSIZE2-1) {
  164880. #ifdef C_PROGRESSIVE_SUPPORTED
  164881. cinfo->progressive_mode = TRUE;
  164882. last_bitpos_ptr = & last_bitpos[0][0];
  164883. for (ci = 0; ci < cinfo->num_components; ci++)
  164884. for (coefi = 0; coefi < DCTSIZE2; coefi++)
  164885. *last_bitpos_ptr++ = -1;
  164886. #else
  164887. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164888. #endif
  164889. } else {
  164890. cinfo->progressive_mode = FALSE;
  164891. for (ci = 0; ci < cinfo->num_components; ci++)
  164892. component_sent[ci] = FALSE;
  164893. }
  164894. for (scanno = 1; scanno <= cinfo->num_scans; scanptr++, scanno++) {
  164895. /* Validate component indexes */
  164896. ncomps = scanptr->comps_in_scan;
  164897. if (ncomps <= 0 || ncomps > MAX_COMPS_IN_SCAN)
  164898. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, ncomps, MAX_COMPS_IN_SCAN);
  164899. for (ci = 0; ci < ncomps; ci++) {
  164900. thisi = scanptr->component_index[ci];
  164901. if (thisi < 0 || thisi >= cinfo->num_components)
  164902. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  164903. /* Components must appear in SOF order within each scan */
  164904. if (ci > 0 && thisi <= scanptr->component_index[ci-1])
  164905. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  164906. }
  164907. /* Validate progression parameters */
  164908. Ss = scanptr->Ss;
  164909. Se = scanptr->Se;
  164910. Ah = scanptr->Ah;
  164911. Al = scanptr->Al;
  164912. if (cinfo->progressive_mode) {
  164913. #ifdef C_PROGRESSIVE_SUPPORTED
  164914. /* The JPEG spec simply gives the ranges 0..13 for Ah and Al, but that
  164915. * seems wrong: the upper bound ought to depend on data precision.
  164916. * Perhaps they really meant 0..N+1 for N-bit precision.
  164917. * Here we allow 0..10 for 8-bit data; Al larger than 10 results in
  164918. * out-of-range reconstructed DC values during the first DC scan,
  164919. * which might cause problems for some decoders.
  164920. */
  164921. #if BITS_IN_JSAMPLE == 8
  164922. #define MAX_AH_AL 10
  164923. #else
  164924. #define MAX_AH_AL 13
  164925. #endif
  164926. if (Ss < 0 || Ss >= DCTSIZE2 || Se < Ss || Se >= DCTSIZE2 ||
  164927. Ah < 0 || Ah > MAX_AH_AL || Al < 0 || Al > MAX_AH_AL)
  164928. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164929. if (Ss == 0) {
  164930. if (Se != 0) /* DC and AC together not OK */
  164931. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164932. } else {
  164933. if (ncomps != 1) /* AC scans must be for only one component */
  164934. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164935. }
  164936. for (ci = 0; ci < ncomps; ci++) {
  164937. last_bitpos_ptr = & last_bitpos[scanptr->component_index[ci]][0];
  164938. if (Ss != 0 && last_bitpos_ptr[0] < 0) /* AC without prior DC scan */
  164939. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164940. for (coefi = Ss; coefi <= Se; coefi++) {
  164941. if (last_bitpos_ptr[coefi] < 0) {
  164942. /* first scan of this coefficient */
  164943. if (Ah != 0)
  164944. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164945. } else {
  164946. /* not first scan */
  164947. if (Ah != last_bitpos_ptr[coefi] || Al != Ah-1)
  164948. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164949. }
  164950. last_bitpos_ptr[coefi] = Al;
  164951. }
  164952. }
  164953. #endif
  164954. } else {
  164955. /* For sequential JPEG, all progression parameters must be these: */
  164956. if (Ss != 0 || Se != DCTSIZE2-1 || Ah != 0 || Al != 0)
  164957. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164958. /* Make sure components are not sent twice */
  164959. for (ci = 0; ci < ncomps; ci++) {
  164960. thisi = scanptr->component_index[ci];
  164961. if (component_sent[thisi])
  164962. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  164963. component_sent[thisi] = TRUE;
  164964. }
  164965. }
  164966. }
  164967. /* Now verify that everything got sent. */
  164968. if (cinfo->progressive_mode) {
  164969. #ifdef C_PROGRESSIVE_SUPPORTED
  164970. /* For progressive mode, we only check that at least some DC data
  164971. * got sent for each component; the spec does not require that all bits
  164972. * of all coefficients be transmitted. Would it be wiser to enforce
  164973. * transmission of all coefficient bits??
  164974. */
  164975. for (ci = 0; ci < cinfo->num_components; ci++) {
  164976. if (last_bitpos[ci][0] < 0)
  164977. ERREXIT(cinfo, JERR_MISSING_DATA);
  164978. }
  164979. #endif
  164980. } else {
  164981. for (ci = 0; ci < cinfo->num_components; ci++) {
  164982. if (! component_sent[ci])
  164983. ERREXIT(cinfo, JERR_MISSING_DATA);
  164984. }
  164985. }
  164986. }
  164987. #endif /* C_MULTISCAN_FILES_SUPPORTED */
  164988. LOCAL(void)
  164989. select_scan_parameters (j_compress_ptr cinfo)
  164990. /* Set up the scan parameters for the current scan */
  164991. {
  164992. int ci;
  164993. #ifdef C_MULTISCAN_FILES_SUPPORTED
  164994. if (cinfo->scan_info != NULL) {
  164995. /* Prepare for current scan --- the script is already validated */
  164996. my_master_ptr master = (my_master_ptr) cinfo->master;
  164997. const jpeg_scan_info * scanptr = cinfo->scan_info + master->scan_number;
  164998. cinfo->comps_in_scan = scanptr->comps_in_scan;
  164999. for (ci = 0; ci < scanptr->comps_in_scan; ci++) {
  165000. cinfo->cur_comp_info[ci] =
  165001. &cinfo->comp_info[scanptr->component_index[ci]];
  165002. }
  165003. cinfo->Ss = scanptr->Ss;
  165004. cinfo->Se = scanptr->Se;
  165005. cinfo->Ah = scanptr->Ah;
  165006. cinfo->Al = scanptr->Al;
  165007. }
  165008. else
  165009. #endif
  165010. {
  165011. /* Prepare for single sequential-JPEG scan containing all components */
  165012. if (cinfo->num_components > MAX_COMPS_IN_SCAN)
  165013. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  165014. MAX_COMPS_IN_SCAN);
  165015. cinfo->comps_in_scan = cinfo->num_components;
  165016. for (ci = 0; ci < cinfo->num_components; ci++) {
  165017. cinfo->cur_comp_info[ci] = &cinfo->comp_info[ci];
  165018. }
  165019. cinfo->Ss = 0;
  165020. cinfo->Se = DCTSIZE2-1;
  165021. cinfo->Ah = 0;
  165022. cinfo->Al = 0;
  165023. }
  165024. }
  165025. LOCAL(void)
  165026. per_scan_setup (j_compress_ptr cinfo)
  165027. /* Do computations that are needed before processing a JPEG scan */
  165028. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] are already set */
  165029. {
  165030. int ci, mcublks, tmp;
  165031. jpeg_component_info *compptr;
  165032. if (cinfo->comps_in_scan == 1) {
  165033. /* Noninterleaved (single-component) scan */
  165034. compptr = cinfo->cur_comp_info[0];
  165035. /* Overall image size in MCUs */
  165036. cinfo->MCUs_per_row = compptr->width_in_blocks;
  165037. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  165038. /* For noninterleaved scan, always one block per MCU */
  165039. compptr->MCU_width = 1;
  165040. compptr->MCU_height = 1;
  165041. compptr->MCU_blocks = 1;
  165042. compptr->MCU_sample_width = DCTSIZE;
  165043. compptr->last_col_width = 1;
  165044. /* For noninterleaved scans, it is convenient to define last_row_height
  165045. * as the number of block rows present in the last iMCU row.
  165046. */
  165047. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  165048. if (tmp == 0) tmp = compptr->v_samp_factor;
  165049. compptr->last_row_height = tmp;
  165050. /* Prepare array describing MCU composition */
  165051. cinfo->blocks_in_MCU = 1;
  165052. cinfo->MCU_membership[0] = 0;
  165053. } else {
  165054. /* Interleaved (multi-component) scan */
  165055. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  165056. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  165057. MAX_COMPS_IN_SCAN);
  165058. /* Overall image size in MCUs */
  165059. cinfo->MCUs_per_row = (JDIMENSION)
  165060. jdiv_round_up((long) cinfo->image_width,
  165061. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  165062. cinfo->MCU_rows_in_scan = (JDIMENSION)
  165063. jdiv_round_up((long) cinfo->image_height,
  165064. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  165065. cinfo->blocks_in_MCU = 0;
  165066. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  165067. compptr = cinfo->cur_comp_info[ci];
  165068. /* Sampling factors give # of blocks of component in each MCU */
  165069. compptr->MCU_width = compptr->h_samp_factor;
  165070. compptr->MCU_height = compptr->v_samp_factor;
  165071. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  165072. compptr->MCU_sample_width = compptr->MCU_width * DCTSIZE;
  165073. /* Figure number of non-dummy blocks in last MCU column & row */
  165074. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  165075. if (tmp == 0) tmp = compptr->MCU_width;
  165076. compptr->last_col_width = tmp;
  165077. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  165078. if (tmp == 0) tmp = compptr->MCU_height;
  165079. compptr->last_row_height = tmp;
  165080. /* Prepare array describing MCU composition */
  165081. mcublks = compptr->MCU_blocks;
  165082. if (cinfo->blocks_in_MCU + mcublks > C_MAX_BLOCKS_IN_MCU)
  165083. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  165084. while (mcublks-- > 0) {
  165085. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  165086. }
  165087. }
  165088. }
  165089. /* Convert restart specified in rows to actual MCU count. */
  165090. /* Note that count must fit in 16 bits, so we provide limiting. */
  165091. if (cinfo->restart_in_rows > 0) {
  165092. long nominal = (long) cinfo->restart_in_rows * (long) cinfo->MCUs_per_row;
  165093. cinfo->restart_interval = (unsigned int) MIN(nominal, 65535L);
  165094. }
  165095. }
  165096. /*
  165097. * Per-pass setup.
  165098. * This is called at the beginning of each pass. We determine which modules
  165099. * will be active during this pass and give them appropriate start_pass calls.
  165100. * We also set is_last_pass to indicate whether any more passes will be
  165101. * required.
  165102. */
  165103. METHODDEF(void)
  165104. prepare_for_pass (j_compress_ptr cinfo)
  165105. {
  165106. my_master_ptr master = (my_master_ptr) cinfo->master;
  165107. switch (master->pass_type) {
  165108. case main_pass:
  165109. /* Initial pass: will collect input data, and do either Huffman
  165110. * optimization or data output for the first scan.
  165111. */
  165112. select_scan_parameters(cinfo);
  165113. per_scan_setup(cinfo);
  165114. if (! cinfo->raw_data_in) {
  165115. (*cinfo->cconvert->start_pass) (cinfo);
  165116. (*cinfo->downsample->start_pass) (cinfo);
  165117. (*cinfo->prep->start_pass) (cinfo, JBUF_PASS_THRU);
  165118. }
  165119. (*cinfo->fdct->start_pass) (cinfo);
  165120. (*cinfo->entropy->start_pass) (cinfo, cinfo->optimize_coding);
  165121. (*cinfo->coef->start_pass) (cinfo,
  165122. (master->total_passes > 1 ?
  165123. JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  165124. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  165125. if (cinfo->optimize_coding) {
  165126. /* No immediate data output; postpone writing frame/scan headers */
  165127. master->pub.call_pass_startup = FALSE;
  165128. } else {
  165129. /* Will write frame/scan headers at first jpeg_write_scanlines call */
  165130. master->pub.call_pass_startup = TRUE;
  165131. }
  165132. break;
  165133. #ifdef ENTROPY_OPT_SUPPORTED
  165134. case huff_opt_pass:
  165135. /* Do Huffman optimization for a scan after the first one. */
  165136. select_scan_parameters(cinfo);
  165137. per_scan_setup(cinfo);
  165138. if (cinfo->Ss != 0 || cinfo->Ah == 0 || cinfo->arith_code) {
  165139. (*cinfo->entropy->start_pass) (cinfo, TRUE);
  165140. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  165141. master->pub.call_pass_startup = FALSE;
  165142. break;
  165143. }
  165144. /* Special case: Huffman DC refinement scans need no Huffman table
  165145. * and therefore we can skip the optimization pass for them.
  165146. */
  165147. master->pass_type = output_pass;
  165148. master->pass_number++;
  165149. /*FALLTHROUGH*/
  165150. #endif
  165151. case output_pass:
  165152. /* Do a data-output pass. */
  165153. /* We need not repeat per-scan setup if prior optimization pass did it. */
  165154. if (! cinfo->optimize_coding) {
  165155. select_scan_parameters(cinfo);
  165156. per_scan_setup(cinfo);
  165157. }
  165158. (*cinfo->entropy->start_pass) (cinfo, FALSE);
  165159. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  165160. /* We emit frame/scan headers now */
  165161. if (master->scan_number == 0)
  165162. (*cinfo->marker->write_frame_header) (cinfo);
  165163. (*cinfo->marker->write_scan_header) (cinfo);
  165164. master->pub.call_pass_startup = FALSE;
  165165. break;
  165166. default:
  165167. ERREXIT(cinfo, JERR_NOT_COMPILED);
  165168. }
  165169. master->pub.is_last_pass = (master->pass_number == master->total_passes-1);
  165170. /* Set up progress monitor's pass info if present */
  165171. if (cinfo->progress != NULL) {
  165172. cinfo->progress->completed_passes = master->pass_number;
  165173. cinfo->progress->total_passes = master->total_passes;
  165174. }
  165175. }
  165176. /*
  165177. * Special start-of-pass hook.
  165178. * This is called by jpeg_write_scanlines if call_pass_startup is TRUE.
  165179. * In single-pass processing, we need this hook because we don't want to
  165180. * write frame/scan headers during jpeg_start_compress; we want to let the
  165181. * application write COM markers etc. between jpeg_start_compress and the
  165182. * jpeg_write_scanlines loop.
  165183. * In multi-pass processing, this routine is not used.
  165184. */
  165185. METHODDEF(void)
  165186. pass_startup (j_compress_ptr cinfo)
  165187. {
  165188. cinfo->master->call_pass_startup = FALSE; /* reset flag so call only once */
  165189. (*cinfo->marker->write_frame_header) (cinfo);
  165190. (*cinfo->marker->write_scan_header) (cinfo);
  165191. }
  165192. /*
  165193. * Finish up at end of pass.
  165194. */
  165195. METHODDEF(void)
  165196. finish_pass_master (j_compress_ptr cinfo)
  165197. {
  165198. my_master_ptr master = (my_master_ptr) cinfo->master;
  165199. /* The entropy coder always needs an end-of-pass call,
  165200. * either to analyze statistics or to flush its output buffer.
  165201. */
  165202. (*cinfo->entropy->finish_pass) (cinfo);
  165203. /* Update state for next pass */
  165204. switch (master->pass_type) {
  165205. case main_pass:
  165206. /* next pass is either output of scan 0 (after optimization)
  165207. * or output of scan 1 (if no optimization).
  165208. */
  165209. master->pass_type = output_pass;
  165210. if (! cinfo->optimize_coding)
  165211. master->scan_number++;
  165212. break;
  165213. case huff_opt_pass:
  165214. /* next pass is always output of current scan */
  165215. master->pass_type = output_pass;
  165216. break;
  165217. case output_pass:
  165218. /* next pass is either optimization or output of next scan */
  165219. if (cinfo->optimize_coding)
  165220. master->pass_type = huff_opt_pass;
  165221. master->scan_number++;
  165222. break;
  165223. }
  165224. master->pass_number++;
  165225. }
  165226. /*
  165227. * Initialize master compression control.
  165228. */
  165229. GLOBAL(void)
  165230. jinit_c_master_control (j_compress_ptr cinfo, boolean transcode_only)
  165231. {
  165232. my_master_ptr master;
  165233. master = (my_master_ptr)
  165234. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165235. SIZEOF(my_comp_master));
  165236. cinfo->master = (struct jpeg_comp_master *) master;
  165237. master->pub.prepare_for_pass = prepare_for_pass;
  165238. master->pub.pass_startup = pass_startup;
  165239. master->pub.finish_pass = finish_pass_master;
  165240. master->pub.is_last_pass = FALSE;
  165241. /* Validate parameters, determine derived values */
  165242. initial_setup(cinfo);
  165243. if (cinfo->scan_info != NULL) {
  165244. #ifdef C_MULTISCAN_FILES_SUPPORTED
  165245. validate_script(cinfo);
  165246. #else
  165247. ERREXIT(cinfo, JERR_NOT_COMPILED);
  165248. #endif
  165249. } else {
  165250. cinfo->progressive_mode = FALSE;
  165251. cinfo->num_scans = 1;
  165252. }
  165253. if (cinfo->progressive_mode) /* TEMPORARY HACK ??? */
  165254. cinfo->optimize_coding = TRUE; /* assume default tables no good for progressive mode */
  165255. /* Initialize my private state */
  165256. if (transcode_only) {
  165257. /* no main pass in transcoding */
  165258. if (cinfo->optimize_coding)
  165259. master->pass_type = huff_opt_pass;
  165260. else
  165261. master->pass_type = output_pass;
  165262. } else {
  165263. /* for normal compression, first pass is always this type: */
  165264. master->pass_type = main_pass;
  165265. }
  165266. master->scan_number = 0;
  165267. master->pass_number = 0;
  165268. if (cinfo->optimize_coding)
  165269. master->total_passes = cinfo->num_scans * 2;
  165270. else
  165271. master->total_passes = cinfo->num_scans;
  165272. }
  165273. /*** End of inlined file: jcmaster.c ***/
  165274. /*** Start of inlined file: jcomapi.c ***/
  165275. #define JPEG_INTERNALS
  165276. /*
  165277. * Abort processing of a JPEG compression or decompression operation,
  165278. * but don't destroy the object itself.
  165279. *
  165280. * For this, we merely clean up all the nonpermanent memory pools.
  165281. * Note that temp files (virtual arrays) are not allowed to belong to
  165282. * the permanent pool, so we will be able to close all temp files here.
  165283. * Closing a data source or destination, if necessary, is the application's
  165284. * responsibility.
  165285. */
  165286. GLOBAL(void)
  165287. jpeg_abort (j_common_ptr cinfo)
  165288. {
  165289. int pool;
  165290. /* Do nothing if called on a not-initialized or destroyed JPEG object. */
  165291. if (cinfo->mem == NULL)
  165292. return;
  165293. /* Releasing pools in reverse order might help avoid fragmentation
  165294. * with some (brain-damaged) malloc libraries.
  165295. */
  165296. for (pool = JPOOL_NUMPOOLS-1; pool > JPOOL_PERMANENT; pool--) {
  165297. (*cinfo->mem->free_pool) (cinfo, pool);
  165298. }
  165299. /* Reset overall state for possible reuse of object */
  165300. if (cinfo->is_decompressor) {
  165301. cinfo->global_state = DSTATE_START;
  165302. /* Try to keep application from accessing now-deleted marker list.
  165303. * A bit kludgy to do it here, but this is the most central place.
  165304. */
  165305. ((j_decompress_ptr) cinfo)->marker_list = NULL;
  165306. } else {
  165307. cinfo->global_state = CSTATE_START;
  165308. }
  165309. }
  165310. /*
  165311. * Destruction of a JPEG object.
  165312. *
  165313. * Everything gets deallocated except the master jpeg_compress_struct itself
  165314. * and the error manager struct. Both of these are supplied by the application
  165315. * and must be freed, if necessary, by the application. (Often they are on
  165316. * the stack and so don't need to be freed anyway.)
  165317. * Closing a data source or destination, if necessary, is the application's
  165318. * responsibility.
  165319. */
  165320. GLOBAL(void)
  165321. jpeg_destroy (j_common_ptr cinfo)
  165322. {
  165323. /* We need only tell the memory manager to release everything. */
  165324. /* NB: mem pointer is NULL if memory mgr failed to initialize. */
  165325. if (cinfo->mem != NULL)
  165326. (*cinfo->mem->self_destruct) (cinfo);
  165327. cinfo->mem = NULL; /* be safe if jpeg_destroy is called twice */
  165328. cinfo->global_state = 0; /* mark it destroyed */
  165329. }
  165330. /*
  165331. * Convenience routines for allocating quantization and Huffman tables.
  165332. * (Would jutils.c be a more reasonable place to put these?)
  165333. */
  165334. GLOBAL(JQUANT_TBL *)
  165335. jpeg_alloc_quant_table (j_common_ptr cinfo)
  165336. {
  165337. JQUANT_TBL *tbl;
  165338. tbl = (JQUANT_TBL *)
  165339. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JQUANT_TBL));
  165340. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  165341. return tbl;
  165342. }
  165343. GLOBAL(JHUFF_TBL *)
  165344. jpeg_alloc_huff_table (j_common_ptr cinfo)
  165345. {
  165346. JHUFF_TBL *tbl;
  165347. tbl = (JHUFF_TBL *)
  165348. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JHUFF_TBL));
  165349. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  165350. return tbl;
  165351. }
  165352. /*** End of inlined file: jcomapi.c ***/
  165353. /*** Start of inlined file: jcparam.c ***/
  165354. #define JPEG_INTERNALS
  165355. /*
  165356. * Quantization table setup routines
  165357. */
  165358. GLOBAL(void)
  165359. jpeg_add_quant_table (j_compress_ptr cinfo, int which_tbl,
  165360. const unsigned int *basic_table,
  165361. int scale_factor, boolean force_baseline)
  165362. /* Define a quantization table equal to the basic_table times
  165363. * a scale factor (given as a percentage).
  165364. * If force_baseline is TRUE, the computed quantization table entries
  165365. * are limited to 1..255 for JPEG baseline compatibility.
  165366. */
  165367. {
  165368. JQUANT_TBL ** qtblptr;
  165369. int i;
  165370. long temp;
  165371. /* Safety check to ensure start_compress not called yet. */
  165372. if (cinfo->global_state != CSTATE_START)
  165373. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165374. if (which_tbl < 0 || which_tbl >= NUM_QUANT_TBLS)
  165375. ERREXIT1(cinfo, JERR_DQT_INDEX, which_tbl);
  165376. qtblptr = & cinfo->quant_tbl_ptrs[which_tbl];
  165377. if (*qtblptr == NULL)
  165378. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  165379. for (i = 0; i < DCTSIZE2; i++) {
  165380. temp = ((long) basic_table[i] * scale_factor + 50L) / 100L;
  165381. /* limit the values to the valid range */
  165382. if (temp <= 0L) temp = 1L;
  165383. if (temp > 32767L) temp = 32767L; /* max quantizer needed for 12 bits */
  165384. if (force_baseline && temp > 255L)
  165385. temp = 255L; /* limit to baseline range if requested */
  165386. (*qtblptr)->quantval[i] = (UINT16) temp;
  165387. }
  165388. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  165389. (*qtblptr)->sent_table = FALSE;
  165390. }
  165391. GLOBAL(void)
  165392. jpeg_set_linear_quality (j_compress_ptr cinfo, int scale_factor,
  165393. boolean force_baseline)
  165394. /* Set or change the 'quality' (quantization) setting, using default tables
  165395. * and a straight percentage-scaling quality scale. In most cases it's better
  165396. * to use jpeg_set_quality (below); this entry point is provided for
  165397. * applications that insist on a linear percentage scaling.
  165398. */
  165399. {
  165400. /* These are the sample quantization tables given in JPEG spec section K.1.
  165401. * The spec says that the values given produce "good" quality, and
  165402. * when divided by 2, "very good" quality.
  165403. */
  165404. static const unsigned int std_luminance_quant_tbl[DCTSIZE2] = {
  165405. 16, 11, 10, 16, 24, 40, 51, 61,
  165406. 12, 12, 14, 19, 26, 58, 60, 55,
  165407. 14, 13, 16, 24, 40, 57, 69, 56,
  165408. 14, 17, 22, 29, 51, 87, 80, 62,
  165409. 18, 22, 37, 56, 68, 109, 103, 77,
  165410. 24, 35, 55, 64, 81, 104, 113, 92,
  165411. 49, 64, 78, 87, 103, 121, 120, 101,
  165412. 72, 92, 95, 98, 112, 100, 103, 99
  165413. };
  165414. static const unsigned int std_chrominance_quant_tbl[DCTSIZE2] = {
  165415. 17, 18, 24, 47, 99, 99, 99, 99,
  165416. 18, 21, 26, 66, 99, 99, 99, 99,
  165417. 24, 26, 56, 99, 99, 99, 99, 99,
  165418. 47, 66, 99, 99, 99, 99, 99, 99,
  165419. 99, 99, 99, 99, 99, 99, 99, 99,
  165420. 99, 99, 99, 99, 99, 99, 99, 99,
  165421. 99, 99, 99, 99, 99, 99, 99, 99,
  165422. 99, 99, 99, 99, 99, 99, 99, 99
  165423. };
  165424. /* Set up two quantization tables using the specified scaling */
  165425. jpeg_add_quant_table(cinfo, 0, std_luminance_quant_tbl,
  165426. scale_factor, force_baseline);
  165427. jpeg_add_quant_table(cinfo, 1, std_chrominance_quant_tbl,
  165428. scale_factor, force_baseline);
  165429. }
  165430. GLOBAL(int)
  165431. jpeg_quality_scaling (int quality)
  165432. /* Convert a user-specified quality rating to a percentage scaling factor
  165433. * for an underlying quantization table, using our recommended scaling curve.
  165434. * The input 'quality' factor should be 0 (terrible) to 100 (very good).
  165435. */
  165436. {
  165437. /* Safety limit on quality factor. Convert 0 to 1 to avoid zero divide. */
  165438. if (quality <= 0) quality = 1;
  165439. if (quality > 100) quality = 100;
  165440. /* The basic table is used as-is (scaling 100) for a quality of 50.
  165441. * Qualities 50..100 are converted to scaling percentage 200 - 2*Q;
  165442. * note that at Q=100 the scaling is 0, which will cause jpeg_add_quant_table
  165443. * to make all the table entries 1 (hence, minimum quantization loss).
  165444. * Qualities 1..50 are converted to scaling percentage 5000/Q.
  165445. */
  165446. if (quality < 50)
  165447. quality = 5000 / quality;
  165448. else
  165449. quality = 200 - quality*2;
  165450. return quality;
  165451. }
  165452. GLOBAL(void)
  165453. jpeg_set_quality (j_compress_ptr cinfo, int quality, boolean force_baseline)
  165454. /* Set or change the 'quality' (quantization) setting, using default tables.
  165455. * This is the standard quality-adjusting entry point for typical user
  165456. * interfaces; only those who want detailed control over quantization tables
  165457. * would use the preceding three routines directly.
  165458. */
  165459. {
  165460. /* Convert user 0-100 rating to percentage scaling */
  165461. quality = jpeg_quality_scaling(quality);
  165462. /* Set up standard quality tables */
  165463. jpeg_set_linear_quality(cinfo, quality, force_baseline);
  165464. }
  165465. /*
  165466. * Huffman table setup routines
  165467. */
  165468. LOCAL(void)
  165469. add_huff_table (j_compress_ptr cinfo,
  165470. JHUFF_TBL **htblptr, const UINT8 *bits, const UINT8 *val)
  165471. /* Define a Huffman table */
  165472. {
  165473. int nsymbols, len;
  165474. if (*htblptr == NULL)
  165475. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  165476. /* Copy the number-of-symbols-of-each-code-length counts */
  165477. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  165478. /* Validate the counts. We do this here mainly so we can copy the right
  165479. * number of symbols from the val[] array, without risking marching off
  165480. * the end of memory. jchuff.c will do a more thorough test later.
  165481. */
  165482. nsymbols = 0;
  165483. for (len = 1; len <= 16; len++)
  165484. nsymbols += bits[len];
  165485. if (nsymbols < 1 || nsymbols > 256)
  165486. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  165487. MEMCOPY((*htblptr)->huffval, val, nsymbols * SIZEOF(UINT8));
  165488. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  165489. (*htblptr)->sent_table = FALSE;
  165490. }
  165491. LOCAL(void)
  165492. std_huff_tables (j_compress_ptr cinfo)
  165493. /* Set up the standard Huffman tables (cf. JPEG standard section K.3) */
  165494. /* IMPORTANT: these are only valid for 8-bit data precision! */
  165495. {
  165496. static const UINT8 bits_dc_luminance[17] =
  165497. { /* 0-base */ 0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 };
  165498. static const UINT8 val_dc_luminance[] =
  165499. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  165500. static const UINT8 bits_dc_chrominance[17] =
  165501. { /* 0-base */ 0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 };
  165502. static const UINT8 val_dc_chrominance[] =
  165503. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  165504. static const UINT8 bits_ac_luminance[17] =
  165505. { /* 0-base */ 0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d };
  165506. static const UINT8 val_ac_luminance[] =
  165507. { 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,
  165508. 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
  165509. 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08,
  165510. 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
  165511. 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16,
  165512. 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
  165513. 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
  165514. 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
  165515. 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
  165516. 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
  165517. 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
  165518. 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
  165519. 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
  165520. 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
  165521. 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
  165522. 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5,
  165523. 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4,
  165524. 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
  165525. 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea,
  165526. 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  165527. 0xf9, 0xfa };
  165528. static const UINT8 bits_ac_chrominance[17] =
  165529. { /* 0-base */ 0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77 };
  165530. static const UINT8 val_ac_chrominance[] =
  165531. { 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21,
  165532. 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
  165533. 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91,
  165534. 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
  165535. 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34,
  165536. 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
  165537. 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38,
  165538. 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
  165539. 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
  165540. 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
  165541. 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
  165542. 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
  165543. 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96,
  165544. 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5,
  165545. 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4,
  165546. 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3,
  165547. 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2,
  165548. 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
  165549. 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9,
  165550. 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  165551. 0xf9, 0xfa };
  165552. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[0],
  165553. bits_dc_luminance, val_dc_luminance);
  165554. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[0],
  165555. bits_ac_luminance, val_ac_luminance);
  165556. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[1],
  165557. bits_dc_chrominance, val_dc_chrominance);
  165558. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[1],
  165559. bits_ac_chrominance, val_ac_chrominance);
  165560. }
  165561. /*
  165562. * Default parameter setup for compression.
  165563. *
  165564. * Applications that don't choose to use this routine must do their
  165565. * own setup of all these parameters. Alternately, you can call this
  165566. * to establish defaults and then alter parameters selectively. This
  165567. * is the recommended approach since, if we add any new parameters,
  165568. * your code will still work (they'll be set to reasonable defaults).
  165569. */
  165570. GLOBAL(void)
  165571. jpeg_set_defaults (j_compress_ptr cinfo)
  165572. {
  165573. int i;
  165574. /* Safety check to ensure start_compress not called yet. */
  165575. if (cinfo->global_state != CSTATE_START)
  165576. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165577. /* Allocate comp_info array large enough for maximum component count.
  165578. * Array is made permanent in case application wants to compress
  165579. * multiple images at same param settings.
  165580. */
  165581. if (cinfo->comp_info == NULL)
  165582. cinfo->comp_info = (jpeg_component_info *)
  165583. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  165584. MAX_COMPONENTS * SIZEOF(jpeg_component_info));
  165585. /* Initialize everything not dependent on the color space */
  165586. cinfo->data_precision = BITS_IN_JSAMPLE;
  165587. /* Set up two quantization tables using default quality of 75 */
  165588. jpeg_set_quality(cinfo, 75, TRUE);
  165589. /* Set up two Huffman tables */
  165590. std_huff_tables(cinfo);
  165591. /* Initialize default arithmetic coding conditioning */
  165592. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  165593. cinfo->arith_dc_L[i] = 0;
  165594. cinfo->arith_dc_U[i] = 1;
  165595. cinfo->arith_ac_K[i] = 5;
  165596. }
  165597. /* Default is no multiple-scan output */
  165598. cinfo->scan_info = NULL;
  165599. cinfo->num_scans = 0;
  165600. /* Expect normal source image, not raw downsampled data */
  165601. cinfo->raw_data_in = FALSE;
  165602. /* Use Huffman coding, not arithmetic coding, by default */
  165603. cinfo->arith_code = FALSE;
  165604. /* By default, don't do extra passes to optimize entropy coding */
  165605. cinfo->optimize_coding = FALSE;
  165606. /* The standard Huffman tables are only valid for 8-bit data precision.
  165607. * If the precision is higher, force optimization on so that usable
  165608. * tables will be computed. This test can be removed if default tables
  165609. * are supplied that are valid for the desired precision.
  165610. */
  165611. if (cinfo->data_precision > 8)
  165612. cinfo->optimize_coding = TRUE;
  165613. /* By default, use the simpler non-cosited sampling alignment */
  165614. cinfo->CCIR601_sampling = FALSE;
  165615. /* No input smoothing */
  165616. cinfo->smoothing_factor = 0;
  165617. /* DCT algorithm preference */
  165618. cinfo->dct_method = JDCT_DEFAULT;
  165619. /* No restart markers */
  165620. cinfo->restart_interval = 0;
  165621. cinfo->restart_in_rows = 0;
  165622. /* Fill in default JFIF marker parameters. Note that whether the marker
  165623. * will actually be written is determined by jpeg_set_colorspace.
  165624. *
  165625. * By default, the library emits JFIF version code 1.01.
  165626. * An application that wants to emit JFIF 1.02 extension markers should set
  165627. * JFIF_minor_version to 2. We could probably get away with just defaulting
  165628. * to 1.02, but there may still be some decoders in use that will complain
  165629. * about that; saying 1.01 should minimize compatibility problems.
  165630. */
  165631. cinfo->JFIF_major_version = 1; /* Default JFIF version = 1.01 */
  165632. cinfo->JFIF_minor_version = 1;
  165633. cinfo->density_unit = 0; /* Pixel size is unknown by default */
  165634. cinfo->X_density = 1; /* Pixel aspect ratio is square by default */
  165635. cinfo->Y_density = 1;
  165636. /* Choose JPEG colorspace based on input space, set defaults accordingly */
  165637. jpeg_default_colorspace(cinfo);
  165638. }
  165639. /*
  165640. * Select an appropriate JPEG colorspace for in_color_space.
  165641. */
  165642. GLOBAL(void)
  165643. jpeg_default_colorspace (j_compress_ptr cinfo)
  165644. {
  165645. switch (cinfo->in_color_space) {
  165646. case JCS_GRAYSCALE:
  165647. jpeg_set_colorspace(cinfo, JCS_GRAYSCALE);
  165648. break;
  165649. case JCS_RGB:
  165650. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  165651. break;
  165652. case JCS_YCbCr:
  165653. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  165654. break;
  165655. case JCS_CMYK:
  165656. jpeg_set_colorspace(cinfo, JCS_CMYK); /* By default, no translation */
  165657. break;
  165658. case JCS_YCCK:
  165659. jpeg_set_colorspace(cinfo, JCS_YCCK);
  165660. break;
  165661. case JCS_UNKNOWN:
  165662. jpeg_set_colorspace(cinfo, JCS_UNKNOWN);
  165663. break;
  165664. default:
  165665. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  165666. }
  165667. }
  165668. /*
  165669. * Set the JPEG colorspace, and choose colorspace-dependent default values.
  165670. */
  165671. GLOBAL(void)
  165672. jpeg_set_colorspace (j_compress_ptr cinfo, J_COLOR_SPACE colorspace)
  165673. {
  165674. jpeg_component_info * compptr;
  165675. int ci;
  165676. #define SET_COMP(index,id,hsamp,vsamp,quant,dctbl,actbl) \
  165677. (compptr = &cinfo->comp_info[index], \
  165678. compptr->component_id = (id), \
  165679. compptr->h_samp_factor = (hsamp), \
  165680. compptr->v_samp_factor = (vsamp), \
  165681. compptr->quant_tbl_no = (quant), \
  165682. compptr->dc_tbl_no = (dctbl), \
  165683. compptr->ac_tbl_no = (actbl) )
  165684. /* Safety check to ensure start_compress not called yet. */
  165685. if (cinfo->global_state != CSTATE_START)
  165686. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165687. /* For all colorspaces, we use Q and Huff tables 0 for luminance components,
  165688. * tables 1 for chrominance components.
  165689. */
  165690. cinfo->jpeg_color_space = colorspace;
  165691. cinfo->write_JFIF_header = FALSE; /* No marker for non-JFIF colorspaces */
  165692. cinfo->write_Adobe_marker = FALSE; /* write no Adobe marker by default */
  165693. switch (colorspace) {
  165694. case JCS_GRAYSCALE:
  165695. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  165696. cinfo->num_components = 1;
  165697. /* JFIF specifies component ID 1 */
  165698. SET_COMP(0, 1, 1,1, 0, 0,0);
  165699. break;
  165700. case JCS_RGB:
  165701. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag RGB */
  165702. cinfo->num_components = 3;
  165703. SET_COMP(0, 0x52 /* 'R' */, 1,1, 0, 0,0);
  165704. SET_COMP(1, 0x47 /* 'G' */, 1,1, 0, 0,0);
  165705. SET_COMP(2, 0x42 /* 'B' */, 1,1, 0, 0,0);
  165706. break;
  165707. case JCS_YCbCr:
  165708. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  165709. cinfo->num_components = 3;
  165710. /* JFIF specifies component IDs 1,2,3 */
  165711. /* We default to 2x2 subsamples of chrominance */
  165712. SET_COMP(0, 1, 2,2, 0, 0,0);
  165713. SET_COMP(1, 2, 1,1, 1, 1,1);
  165714. SET_COMP(2, 3, 1,1, 1, 1,1);
  165715. break;
  165716. case JCS_CMYK:
  165717. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag CMYK */
  165718. cinfo->num_components = 4;
  165719. SET_COMP(0, 0x43 /* 'C' */, 1,1, 0, 0,0);
  165720. SET_COMP(1, 0x4D /* 'M' */, 1,1, 0, 0,0);
  165721. SET_COMP(2, 0x59 /* 'Y' */, 1,1, 0, 0,0);
  165722. SET_COMP(3, 0x4B /* 'K' */, 1,1, 0, 0,0);
  165723. break;
  165724. case JCS_YCCK:
  165725. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag YCCK */
  165726. cinfo->num_components = 4;
  165727. SET_COMP(0, 1, 2,2, 0, 0,0);
  165728. SET_COMP(1, 2, 1,1, 1, 1,1);
  165729. SET_COMP(2, 3, 1,1, 1, 1,1);
  165730. SET_COMP(3, 4, 2,2, 0, 0,0);
  165731. break;
  165732. case JCS_UNKNOWN:
  165733. cinfo->num_components = cinfo->input_components;
  165734. if (cinfo->num_components < 1 || cinfo->num_components > MAX_COMPONENTS)
  165735. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  165736. MAX_COMPONENTS);
  165737. for (ci = 0; ci < cinfo->num_components; ci++) {
  165738. SET_COMP(ci, ci, 1,1, 0, 0,0);
  165739. }
  165740. break;
  165741. default:
  165742. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  165743. }
  165744. }
  165745. #ifdef C_PROGRESSIVE_SUPPORTED
  165746. LOCAL(jpeg_scan_info *)
  165747. fill_a_scan (jpeg_scan_info * scanptr, int ci,
  165748. int Ss, int Se, int Ah, int Al)
  165749. /* Support routine: generate one scan for specified component */
  165750. {
  165751. scanptr->comps_in_scan = 1;
  165752. scanptr->component_index[0] = ci;
  165753. scanptr->Ss = Ss;
  165754. scanptr->Se = Se;
  165755. scanptr->Ah = Ah;
  165756. scanptr->Al = Al;
  165757. scanptr++;
  165758. return scanptr;
  165759. }
  165760. LOCAL(jpeg_scan_info *)
  165761. fill_scans (jpeg_scan_info * scanptr, int ncomps,
  165762. int Ss, int Se, int Ah, int Al)
  165763. /* Support routine: generate one scan for each component */
  165764. {
  165765. int ci;
  165766. for (ci = 0; ci < ncomps; ci++) {
  165767. scanptr->comps_in_scan = 1;
  165768. scanptr->component_index[0] = ci;
  165769. scanptr->Ss = Ss;
  165770. scanptr->Se = Se;
  165771. scanptr->Ah = Ah;
  165772. scanptr->Al = Al;
  165773. scanptr++;
  165774. }
  165775. return scanptr;
  165776. }
  165777. LOCAL(jpeg_scan_info *)
  165778. fill_dc_scans (jpeg_scan_info * scanptr, int ncomps, int Ah, int Al)
  165779. /* Support routine: generate interleaved DC scan if possible, else N scans */
  165780. {
  165781. int ci;
  165782. if (ncomps <= MAX_COMPS_IN_SCAN) {
  165783. /* Single interleaved DC scan */
  165784. scanptr->comps_in_scan = ncomps;
  165785. for (ci = 0; ci < ncomps; ci++)
  165786. scanptr->component_index[ci] = ci;
  165787. scanptr->Ss = scanptr->Se = 0;
  165788. scanptr->Ah = Ah;
  165789. scanptr->Al = Al;
  165790. scanptr++;
  165791. } else {
  165792. /* Noninterleaved DC scan for each component */
  165793. scanptr = fill_scans(scanptr, ncomps, 0, 0, Ah, Al);
  165794. }
  165795. return scanptr;
  165796. }
  165797. /*
  165798. * Create a recommended progressive-JPEG script.
  165799. * cinfo->num_components and cinfo->jpeg_color_space must be correct.
  165800. */
  165801. GLOBAL(void)
  165802. jpeg_simple_progression (j_compress_ptr cinfo)
  165803. {
  165804. int ncomps = cinfo->num_components;
  165805. int nscans;
  165806. jpeg_scan_info * scanptr;
  165807. /* Safety check to ensure start_compress not called yet. */
  165808. if (cinfo->global_state != CSTATE_START)
  165809. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165810. /* Figure space needed for script. Calculation must match code below! */
  165811. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  165812. /* Custom script for YCbCr color images. */
  165813. nscans = 10;
  165814. } else {
  165815. /* All-purpose script for other color spaces. */
  165816. if (ncomps > MAX_COMPS_IN_SCAN)
  165817. nscans = 6 * ncomps; /* 2 DC + 4 AC scans per component */
  165818. else
  165819. nscans = 2 + 4 * ncomps; /* 2 DC scans; 4 AC scans per component */
  165820. }
  165821. /* Allocate space for script.
  165822. * We need to put it in the permanent pool in case the application performs
  165823. * multiple compressions without changing the settings. To avoid a memory
  165824. * leak if jpeg_simple_progression is called repeatedly for the same JPEG
  165825. * object, we try to re-use previously allocated space, and we allocate
  165826. * enough space to handle YCbCr even if initially asked for grayscale.
  165827. */
  165828. if (cinfo->script_space == NULL || cinfo->script_space_size < nscans) {
  165829. cinfo->script_space_size = MAX(nscans, 10);
  165830. cinfo->script_space = (jpeg_scan_info *)
  165831. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  165832. cinfo->script_space_size * SIZEOF(jpeg_scan_info));
  165833. }
  165834. scanptr = cinfo->script_space;
  165835. cinfo->scan_info = scanptr;
  165836. cinfo->num_scans = nscans;
  165837. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  165838. /* Custom script for YCbCr color images. */
  165839. /* Initial DC scan */
  165840. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  165841. /* Initial AC scan: get some luma data out in a hurry */
  165842. scanptr = fill_a_scan(scanptr, 0, 1, 5, 0, 2);
  165843. /* Chroma data is too small to be worth expending many scans on */
  165844. scanptr = fill_a_scan(scanptr, 2, 1, 63, 0, 1);
  165845. scanptr = fill_a_scan(scanptr, 1, 1, 63, 0, 1);
  165846. /* Complete spectral selection for luma AC */
  165847. scanptr = fill_a_scan(scanptr, 0, 6, 63, 0, 2);
  165848. /* Refine next bit of luma AC */
  165849. scanptr = fill_a_scan(scanptr, 0, 1, 63, 2, 1);
  165850. /* Finish DC successive approximation */
  165851. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  165852. /* Finish AC successive approximation */
  165853. scanptr = fill_a_scan(scanptr, 2, 1, 63, 1, 0);
  165854. scanptr = fill_a_scan(scanptr, 1, 1, 63, 1, 0);
  165855. /* Luma bottom bit comes last since it's usually largest scan */
  165856. scanptr = fill_a_scan(scanptr, 0, 1, 63, 1, 0);
  165857. } else {
  165858. /* All-purpose script for other color spaces. */
  165859. /* Successive approximation first pass */
  165860. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  165861. scanptr = fill_scans(scanptr, ncomps, 1, 5, 0, 2);
  165862. scanptr = fill_scans(scanptr, ncomps, 6, 63, 0, 2);
  165863. /* Successive approximation second pass */
  165864. scanptr = fill_scans(scanptr, ncomps, 1, 63, 2, 1);
  165865. /* Successive approximation final pass */
  165866. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  165867. scanptr = fill_scans(scanptr, ncomps, 1, 63, 1, 0);
  165868. }
  165869. }
  165870. #endif /* C_PROGRESSIVE_SUPPORTED */
  165871. /*** End of inlined file: jcparam.c ***/
  165872. /*** Start of inlined file: jcphuff.c ***/
  165873. #define JPEG_INTERNALS
  165874. #ifdef C_PROGRESSIVE_SUPPORTED
  165875. /* Expanded entropy encoder object for progressive Huffman encoding. */
  165876. typedef struct {
  165877. struct jpeg_entropy_encoder pub; /* public fields */
  165878. /* Mode flag: TRUE for optimization, FALSE for actual data output */
  165879. boolean gather_statistics;
  165880. /* Bit-level coding status.
  165881. * next_output_byte/free_in_buffer are local copies of cinfo->dest fields.
  165882. */
  165883. JOCTET * next_output_byte; /* => next byte to write in buffer */
  165884. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  165885. INT32 put_buffer; /* current bit-accumulation buffer */
  165886. int put_bits; /* # of bits now in it */
  165887. j_compress_ptr cinfo; /* link to cinfo (needed for dump_buffer) */
  165888. /* Coding status for DC components */
  165889. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  165890. /* Coding status for AC components */
  165891. int ac_tbl_no; /* the table number of the single component */
  165892. unsigned int EOBRUN; /* run length of EOBs */
  165893. unsigned int BE; /* # of buffered correction bits before MCU */
  165894. char * bit_buffer; /* buffer for correction bits (1 per char) */
  165895. /* packing correction bits tightly would save some space but cost time... */
  165896. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  165897. int next_restart_num; /* next restart number to write (0-7) */
  165898. /* Pointers to derived tables (these workspaces have image lifespan).
  165899. * Since any one scan codes only DC or only AC, we only need one set
  165900. * of tables, not one for DC and one for AC.
  165901. */
  165902. c_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  165903. /* Statistics tables for optimization; again, one set is enough */
  165904. long * count_ptrs[NUM_HUFF_TBLS];
  165905. } phuff_entropy_encoder;
  165906. typedef phuff_entropy_encoder * phuff_entropy_ptr;
  165907. /* MAX_CORR_BITS is the number of bits the AC refinement correction-bit
  165908. * buffer can hold. Larger sizes may slightly improve compression, but
  165909. * 1000 is already well into the realm of overkill.
  165910. * The minimum safe size is 64 bits.
  165911. */
  165912. #define MAX_CORR_BITS 1000 /* Max # of correction bits I can buffer */
  165913. /* IRIGHT_SHIFT is like RIGHT_SHIFT, but works on int rather than INT32.
  165914. * We assume that int right shift is unsigned if INT32 right shift is,
  165915. * which should be safe.
  165916. */
  165917. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  165918. #define ISHIFT_TEMPS int ishift_temp;
  165919. #define IRIGHT_SHIFT(x,shft) \
  165920. ((ishift_temp = (x)) < 0 ? \
  165921. (ishift_temp >> (shft)) | ((~0) << (16-(shft))) : \
  165922. (ishift_temp >> (shft)))
  165923. #else
  165924. #define ISHIFT_TEMPS
  165925. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  165926. #endif
  165927. /* Forward declarations */
  165928. METHODDEF(boolean) encode_mcu_DC_first JPP((j_compress_ptr cinfo,
  165929. JBLOCKROW *MCU_data));
  165930. METHODDEF(boolean) encode_mcu_AC_first JPP((j_compress_ptr cinfo,
  165931. JBLOCKROW *MCU_data));
  165932. METHODDEF(boolean) encode_mcu_DC_refine JPP((j_compress_ptr cinfo,
  165933. JBLOCKROW *MCU_data));
  165934. METHODDEF(boolean) encode_mcu_AC_refine JPP((j_compress_ptr cinfo,
  165935. JBLOCKROW *MCU_data));
  165936. METHODDEF(void) finish_pass_phuff JPP((j_compress_ptr cinfo));
  165937. METHODDEF(void) finish_pass_gather_phuff JPP((j_compress_ptr cinfo));
  165938. /*
  165939. * Initialize for a Huffman-compressed scan using progressive JPEG.
  165940. */
  165941. METHODDEF(void)
  165942. start_pass_phuff (j_compress_ptr cinfo, boolean gather_statistics)
  165943. {
  165944. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165945. boolean is_DC_band;
  165946. int ci, tbl;
  165947. jpeg_component_info * compptr;
  165948. entropy->cinfo = cinfo;
  165949. entropy->gather_statistics = gather_statistics;
  165950. is_DC_band = (cinfo->Ss == 0);
  165951. /* We assume jcmaster.c already validated the scan parameters. */
  165952. /* Select execution routines */
  165953. if (cinfo->Ah == 0) {
  165954. if (is_DC_band)
  165955. entropy->pub.encode_mcu = encode_mcu_DC_first;
  165956. else
  165957. entropy->pub.encode_mcu = encode_mcu_AC_first;
  165958. } else {
  165959. if (is_DC_band)
  165960. entropy->pub.encode_mcu = encode_mcu_DC_refine;
  165961. else {
  165962. entropy->pub.encode_mcu = encode_mcu_AC_refine;
  165963. /* AC refinement needs a correction bit buffer */
  165964. if (entropy->bit_buffer == NULL)
  165965. entropy->bit_buffer = (char *)
  165966. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165967. MAX_CORR_BITS * SIZEOF(char));
  165968. }
  165969. }
  165970. if (gather_statistics)
  165971. entropy->pub.finish_pass = finish_pass_gather_phuff;
  165972. else
  165973. entropy->pub.finish_pass = finish_pass_phuff;
  165974. /* Only DC coefficients may be interleaved, so cinfo->comps_in_scan = 1
  165975. * for AC coefficients.
  165976. */
  165977. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  165978. compptr = cinfo->cur_comp_info[ci];
  165979. /* Initialize DC predictions to 0 */
  165980. entropy->last_dc_val[ci] = 0;
  165981. /* Get table index */
  165982. if (is_DC_band) {
  165983. if (cinfo->Ah != 0) /* DC refinement needs no table */
  165984. continue;
  165985. tbl = compptr->dc_tbl_no;
  165986. } else {
  165987. entropy->ac_tbl_no = tbl = compptr->ac_tbl_no;
  165988. }
  165989. if (gather_statistics) {
  165990. /* Check for invalid table index */
  165991. /* (make_c_derived_tbl does this in the other path) */
  165992. if (tbl < 0 || tbl >= NUM_HUFF_TBLS)
  165993. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);
  165994. /* Allocate and zero the statistics tables */
  165995. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  165996. if (entropy->count_ptrs[tbl] == NULL)
  165997. entropy->count_ptrs[tbl] = (long *)
  165998. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165999. 257 * SIZEOF(long));
  166000. MEMZERO(entropy->count_ptrs[tbl], 257 * SIZEOF(long));
  166001. } else {
  166002. /* Compute derived values for Huffman table */
  166003. /* We may do this more than once for a table, but it's not expensive */
  166004. jpeg_make_c_derived_tbl(cinfo, is_DC_band, tbl,
  166005. & entropy->derived_tbls[tbl]);
  166006. }
  166007. }
  166008. /* Initialize AC stuff */
  166009. entropy->EOBRUN = 0;
  166010. entropy->BE = 0;
  166011. /* Initialize bit buffer to empty */
  166012. entropy->put_buffer = 0;
  166013. entropy->put_bits = 0;
  166014. /* Initialize restart stuff */
  166015. entropy->restarts_to_go = cinfo->restart_interval;
  166016. entropy->next_restart_num = 0;
  166017. }
  166018. /* Outputting bytes to the file.
  166019. * NB: these must be called only when actually outputting,
  166020. * that is, entropy->gather_statistics == FALSE.
  166021. */
  166022. /* Emit a byte */
  166023. #define emit_byte(entropy,val) \
  166024. { *(entropy)->next_output_byte++ = (JOCTET) (val); \
  166025. if (--(entropy)->free_in_buffer == 0) \
  166026. dump_buffer_p(entropy); }
  166027. LOCAL(void)
  166028. dump_buffer_p (phuff_entropy_ptr entropy)
  166029. /* Empty the output buffer; we do not support suspension in this module. */
  166030. {
  166031. struct jpeg_destination_mgr * dest = entropy->cinfo->dest;
  166032. if (! (*dest->empty_output_buffer) (entropy->cinfo))
  166033. ERREXIT(entropy->cinfo, JERR_CANT_SUSPEND);
  166034. /* After a successful buffer dump, must reset buffer pointers */
  166035. entropy->next_output_byte = dest->next_output_byte;
  166036. entropy->free_in_buffer = dest->free_in_buffer;
  166037. }
  166038. /* Outputting bits to the file */
  166039. /* Only the right 24 bits of put_buffer are used; the valid bits are
  166040. * left-justified in this part. At most 16 bits can be passed to emit_bits
  166041. * in one call, and we never retain more than 7 bits in put_buffer
  166042. * between calls, so 24 bits are sufficient.
  166043. */
  166044. INLINE
  166045. LOCAL(void)
  166046. emit_bits_p (phuff_entropy_ptr entropy, unsigned int code, int size)
  166047. /* Emit some bits, unless we are in gather mode */
  166048. {
  166049. /* This routine is heavily used, so it's worth coding tightly. */
  166050. register INT32 put_buffer = (INT32) code;
  166051. register int put_bits = entropy->put_bits;
  166052. /* if size is 0, caller used an invalid Huffman table entry */
  166053. if (size == 0)
  166054. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  166055. if (entropy->gather_statistics)
  166056. return; /* do nothing if we're only getting stats */
  166057. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  166058. put_bits += size; /* new number of bits in buffer */
  166059. put_buffer <<= 24 - put_bits; /* align incoming bits */
  166060. put_buffer |= entropy->put_buffer; /* and merge with old buffer contents */
  166061. while (put_bits >= 8) {
  166062. int c = (int) ((put_buffer >> 16) & 0xFF);
  166063. emit_byte(entropy, c);
  166064. if (c == 0xFF) { /* need to stuff a zero byte? */
  166065. emit_byte(entropy, 0);
  166066. }
  166067. put_buffer <<= 8;
  166068. put_bits -= 8;
  166069. }
  166070. entropy->put_buffer = put_buffer; /* update variables */
  166071. entropy->put_bits = put_bits;
  166072. }
  166073. LOCAL(void)
  166074. flush_bits_p (phuff_entropy_ptr entropy)
  166075. {
  166076. emit_bits_p(entropy, 0x7F, 7); /* fill any partial byte with ones */
  166077. entropy->put_buffer = 0; /* and reset bit-buffer to empty */
  166078. entropy->put_bits = 0;
  166079. }
  166080. /*
  166081. * Emit (or just count) a Huffman symbol.
  166082. */
  166083. INLINE
  166084. LOCAL(void)
  166085. emit_symbol (phuff_entropy_ptr entropy, int tbl_no, int symbol)
  166086. {
  166087. if (entropy->gather_statistics)
  166088. entropy->count_ptrs[tbl_no][symbol]++;
  166089. else {
  166090. c_derived_tbl * tbl = entropy->derived_tbls[tbl_no];
  166091. emit_bits_p(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]);
  166092. }
  166093. }
  166094. /*
  166095. * Emit bits from a correction bit buffer.
  166096. */
  166097. LOCAL(void)
  166098. emit_buffered_bits (phuff_entropy_ptr entropy, char * bufstart,
  166099. unsigned int nbits)
  166100. {
  166101. if (entropy->gather_statistics)
  166102. return; /* no real work */
  166103. while (nbits > 0) {
  166104. emit_bits_p(entropy, (unsigned int) (*bufstart), 1);
  166105. bufstart++;
  166106. nbits--;
  166107. }
  166108. }
  166109. /*
  166110. * Emit any pending EOBRUN symbol.
  166111. */
  166112. LOCAL(void)
  166113. emit_eobrun (phuff_entropy_ptr entropy)
  166114. {
  166115. register int temp, nbits;
  166116. if (entropy->EOBRUN > 0) { /* if there is any pending EOBRUN */
  166117. temp = entropy->EOBRUN;
  166118. nbits = 0;
  166119. while ((temp >>= 1))
  166120. nbits++;
  166121. /* safety check: shouldn't happen given limited correction-bit buffer */
  166122. if (nbits > 14)
  166123. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  166124. emit_symbol(entropy, entropy->ac_tbl_no, nbits << 4);
  166125. if (nbits)
  166126. emit_bits_p(entropy, entropy->EOBRUN, nbits);
  166127. entropy->EOBRUN = 0;
  166128. /* Emit any buffered correction bits */
  166129. emit_buffered_bits(entropy, entropy->bit_buffer, entropy->BE);
  166130. entropy->BE = 0;
  166131. }
  166132. }
  166133. /*
  166134. * Emit a restart marker & resynchronize predictions.
  166135. */
  166136. LOCAL(void)
  166137. emit_restart_p (phuff_entropy_ptr entropy, int restart_num)
  166138. {
  166139. int ci;
  166140. emit_eobrun(entropy);
  166141. if (! entropy->gather_statistics) {
  166142. flush_bits_p(entropy);
  166143. emit_byte(entropy, 0xFF);
  166144. emit_byte(entropy, JPEG_RST0 + restart_num);
  166145. }
  166146. if (entropy->cinfo->Ss == 0) {
  166147. /* Re-initialize DC predictions to 0 */
  166148. for (ci = 0; ci < entropy->cinfo->comps_in_scan; ci++)
  166149. entropy->last_dc_val[ci] = 0;
  166150. } else {
  166151. /* Re-initialize all AC-related fields to 0 */
  166152. entropy->EOBRUN = 0;
  166153. entropy->BE = 0;
  166154. }
  166155. }
  166156. /*
  166157. * MCU encoding for DC initial scan (either spectral selection,
  166158. * or first pass of successive approximation).
  166159. */
  166160. METHODDEF(boolean)
  166161. encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166162. {
  166163. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166164. register int temp, temp2;
  166165. register int nbits;
  166166. int blkn, ci;
  166167. int Al = cinfo->Al;
  166168. JBLOCKROW block;
  166169. jpeg_component_info * compptr;
  166170. ISHIFT_TEMPS
  166171. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166172. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166173. /* Emit restart marker if needed */
  166174. if (cinfo->restart_interval)
  166175. if (entropy->restarts_to_go == 0)
  166176. emit_restart_p(entropy, entropy->next_restart_num);
  166177. /* Encode the MCU data blocks */
  166178. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  166179. block = MCU_data[blkn];
  166180. ci = cinfo->MCU_membership[blkn];
  166181. compptr = cinfo->cur_comp_info[ci];
  166182. /* Compute the DC value after the required point transform by Al.
  166183. * This is simply an arithmetic right shift.
  166184. */
  166185. temp2 = IRIGHT_SHIFT((int) ((*block)[0]), Al);
  166186. /* DC differences are figured on the point-transformed values. */
  166187. temp = temp2 - entropy->last_dc_val[ci];
  166188. entropy->last_dc_val[ci] = temp2;
  166189. /* Encode the DC coefficient difference per section G.1.2.1 */
  166190. temp2 = temp;
  166191. if (temp < 0) {
  166192. temp = -temp; /* temp is abs value of input */
  166193. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  166194. /* This code assumes we are on a two's complement machine */
  166195. temp2--;
  166196. }
  166197. /* Find the number of bits needed for the magnitude of the coefficient */
  166198. nbits = 0;
  166199. while (temp) {
  166200. nbits++;
  166201. temp >>= 1;
  166202. }
  166203. /* Check for out-of-range coefficient values.
  166204. * Since we're encoding a difference, the range limit is twice as much.
  166205. */
  166206. if (nbits > MAX_COEF_BITS+1)
  166207. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  166208. /* Count/emit the Huffman-coded symbol for the number of bits */
  166209. emit_symbol(entropy, compptr->dc_tbl_no, nbits);
  166210. /* Emit that number of bits of the value, if positive, */
  166211. /* or the complement of its magnitude, if negative. */
  166212. if (nbits) /* emit_bits rejects calls with size 0 */
  166213. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  166214. }
  166215. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166216. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166217. /* Update restart-interval state too */
  166218. if (cinfo->restart_interval) {
  166219. if (entropy->restarts_to_go == 0) {
  166220. entropy->restarts_to_go = cinfo->restart_interval;
  166221. entropy->next_restart_num++;
  166222. entropy->next_restart_num &= 7;
  166223. }
  166224. entropy->restarts_to_go--;
  166225. }
  166226. return TRUE;
  166227. }
  166228. /*
  166229. * MCU encoding for AC initial scan (either spectral selection,
  166230. * or first pass of successive approximation).
  166231. */
  166232. METHODDEF(boolean)
  166233. encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166234. {
  166235. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166236. register int temp, temp2;
  166237. register int nbits;
  166238. register int r, k;
  166239. int Se = cinfo->Se;
  166240. int Al = cinfo->Al;
  166241. JBLOCKROW block;
  166242. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166243. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166244. /* Emit restart marker if needed */
  166245. if (cinfo->restart_interval)
  166246. if (entropy->restarts_to_go == 0)
  166247. emit_restart_p(entropy, entropy->next_restart_num);
  166248. /* Encode the MCU data block */
  166249. block = MCU_data[0];
  166250. /* Encode the AC coefficients per section G.1.2.2, fig. G.3 */
  166251. r = 0; /* r = run length of zeros */
  166252. for (k = cinfo->Ss; k <= Se; k++) {
  166253. if ((temp = (*block)[jpeg_natural_order[k]]) == 0) {
  166254. r++;
  166255. continue;
  166256. }
  166257. /* We must apply the point transform by Al. For AC coefficients this
  166258. * is an integer division with rounding towards 0. To do this portably
  166259. * in C, we shift after obtaining the absolute value; so the code is
  166260. * interwoven with finding the abs value (temp) and output bits (temp2).
  166261. */
  166262. if (temp < 0) {
  166263. temp = -temp; /* temp is abs value of input */
  166264. temp >>= Al; /* apply the point transform */
  166265. /* For a negative coef, want temp2 = bitwise complement of abs(coef) */
  166266. temp2 = ~temp;
  166267. } else {
  166268. temp >>= Al; /* apply the point transform */
  166269. temp2 = temp;
  166270. }
  166271. /* Watch out for case that nonzero coef is zero after point transform */
  166272. if (temp == 0) {
  166273. r++;
  166274. continue;
  166275. }
  166276. /* Emit any pending EOBRUN */
  166277. if (entropy->EOBRUN > 0)
  166278. emit_eobrun(entropy);
  166279. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  166280. while (r > 15) {
  166281. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  166282. r -= 16;
  166283. }
  166284. /* Find the number of bits needed for the magnitude of the coefficient */
  166285. nbits = 1; /* there must be at least one 1 bit */
  166286. while ((temp >>= 1))
  166287. nbits++;
  166288. /* Check for out-of-range coefficient values */
  166289. if (nbits > MAX_COEF_BITS)
  166290. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  166291. /* Count/emit Huffman symbol for run length / number of bits */
  166292. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + nbits);
  166293. /* Emit that number of bits of the value, if positive, */
  166294. /* or the complement of its magnitude, if negative. */
  166295. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  166296. r = 0; /* reset zero run length */
  166297. }
  166298. if (r > 0) { /* If there are trailing zeroes, */
  166299. entropy->EOBRUN++; /* count an EOB */
  166300. if (entropy->EOBRUN == 0x7FFF)
  166301. emit_eobrun(entropy); /* force it out to avoid overflow */
  166302. }
  166303. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166304. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166305. /* Update restart-interval state too */
  166306. if (cinfo->restart_interval) {
  166307. if (entropy->restarts_to_go == 0) {
  166308. entropy->restarts_to_go = cinfo->restart_interval;
  166309. entropy->next_restart_num++;
  166310. entropy->next_restart_num &= 7;
  166311. }
  166312. entropy->restarts_to_go--;
  166313. }
  166314. return TRUE;
  166315. }
  166316. /*
  166317. * MCU encoding for DC successive approximation refinement scan.
  166318. * Note: we assume such scans can be multi-component, although the spec
  166319. * is not very clear on the point.
  166320. */
  166321. METHODDEF(boolean)
  166322. encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166323. {
  166324. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166325. register int temp;
  166326. int blkn;
  166327. int Al = cinfo->Al;
  166328. JBLOCKROW block;
  166329. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166330. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166331. /* Emit restart marker if needed */
  166332. if (cinfo->restart_interval)
  166333. if (entropy->restarts_to_go == 0)
  166334. emit_restart_p(entropy, entropy->next_restart_num);
  166335. /* Encode the MCU data blocks */
  166336. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  166337. block = MCU_data[blkn];
  166338. /* We simply emit the Al'th bit of the DC coefficient value. */
  166339. temp = (*block)[0];
  166340. emit_bits_p(entropy, (unsigned int) (temp >> Al), 1);
  166341. }
  166342. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166343. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166344. /* Update restart-interval state too */
  166345. if (cinfo->restart_interval) {
  166346. if (entropy->restarts_to_go == 0) {
  166347. entropy->restarts_to_go = cinfo->restart_interval;
  166348. entropy->next_restart_num++;
  166349. entropy->next_restart_num &= 7;
  166350. }
  166351. entropy->restarts_to_go--;
  166352. }
  166353. return TRUE;
  166354. }
  166355. /*
  166356. * MCU encoding for AC successive approximation refinement scan.
  166357. */
  166358. METHODDEF(boolean)
  166359. encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166360. {
  166361. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166362. register int temp;
  166363. register int r, k;
  166364. int EOB;
  166365. char *BR_buffer;
  166366. unsigned int BR;
  166367. int Se = cinfo->Se;
  166368. int Al = cinfo->Al;
  166369. JBLOCKROW block;
  166370. int absvalues[DCTSIZE2];
  166371. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166372. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166373. /* Emit restart marker if needed */
  166374. if (cinfo->restart_interval)
  166375. if (entropy->restarts_to_go == 0)
  166376. emit_restart_p(entropy, entropy->next_restart_num);
  166377. /* Encode the MCU data block */
  166378. block = MCU_data[0];
  166379. /* It is convenient to make a pre-pass to determine the transformed
  166380. * coefficients' absolute values and the EOB position.
  166381. */
  166382. EOB = 0;
  166383. for (k = cinfo->Ss; k <= Se; k++) {
  166384. temp = (*block)[jpeg_natural_order[k]];
  166385. /* We must apply the point transform by Al. For AC coefficients this
  166386. * is an integer division with rounding towards 0. To do this portably
  166387. * in C, we shift after obtaining the absolute value.
  166388. */
  166389. if (temp < 0)
  166390. temp = -temp; /* temp is abs value of input */
  166391. temp >>= Al; /* apply the point transform */
  166392. absvalues[k] = temp; /* save abs value for main pass */
  166393. if (temp == 1)
  166394. EOB = k; /* EOB = index of last newly-nonzero coef */
  166395. }
  166396. /* Encode the AC coefficients per section G.1.2.3, fig. G.7 */
  166397. r = 0; /* r = run length of zeros */
  166398. BR = 0; /* BR = count of buffered bits added now */
  166399. BR_buffer = entropy->bit_buffer + entropy->BE; /* Append bits to buffer */
  166400. for (k = cinfo->Ss; k <= Se; k++) {
  166401. if ((temp = absvalues[k]) == 0) {
  166402. r++;
  166403. continue;
  166404. }
  166405. /* Emit any required ZRLs, but not if they can be folded into EOB */
  166406. while (r > 15 && k <= EOB) {
  166407. /* emit any pending EOBRUN and the BE correction bits */
  166408. emit_eobrun(entropy);
  166409. /* Emit ZRL */
  166410. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  166411. r -= 16;
  166412. /* Emit buffered correction bits that must be associated with ZRL */
  166413. emit_buffered_bits(entropy, BR_buffer, BR);
  166414. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  166415. BR = 0;
  166416. }
  166417. /* If the coef was previously nonzero, it only needs a correction bit.
  166418. * NOTE: a straight translation of the spec's figure G.7 would suggest
  166419. * that we also need to test r > 15. But if r > 15, we can only get here
  166420. * if k > EOB, which implies that this coefficient is not 1.
  166421. */
  166422. if (temp > 1) {
  166423. /* The correction bit is the next bit of the absolute value. */
  166424. BR_buffer[BR++] = (char) (temp & 1);
  166425. continue;
  166426. }
  166427. /* Emit any pending EOBRUN and the BE correction bits */
  166428. emit_eobrun(entropy);
  166429. /* Count/emit Huffman symbol for run length / number of bits */
  166430. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + 1);
  166431. /* Emit output bit for newly-nonzero coef */
  166432. temp = ((*block)[jpeg_natural_order[k]] < 0) ? 0 : 1;
  166433. emit_bits_p(entropy, (unsigned int) temp, 1);
  166434. /* Emit buffered correction bits that must be associated with this code */
  166435. emit_buffered_bits(entropy, BR_buffer, BR);
  166436. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  166437. BR = 0;
  166438. r = 0; /* reset zero run length */
  166439. }
  166440. if (r > 0 || BR > 0) { /* If there are trailing zeroes, */
  166441. entropy->EOBRUN++; /* count an EOB */
  166442. entropy->BE += BR; /* concat my correction bits to older ones */
  166443. /* We force out the EOB if we risk either:
  166444. * 1. overflow of the EOB counter;
  166445. * 2. overflow of the correction bit buffer during the next MCU.
  166446. */
  166447. if (entropy->EOBRUN == 0x7FFF || entropy->BE > (MAX_CORR_BITS-DCTSIZE2+1))
  166448. emit_eobrun(entropy);
  166449. }
  166450. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166451. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166452. /* Update restart-interval state too */
  166453. if (cinfo->restart_interval) {
  166454. if (entropy->restarts_to_go == 0) {
  166455. entropy->restarts_to_go = cinfo->restart_interval;
  166456. entropy->next_restart_num++;
  166457. entropy->next_restart_num &= 7;
  166458. }
  166459. entropy->restarts_to_go--;
  166460. }
  166461. return TRUE;
  166462. }
  166463. /*
  166464. * Finish up at the end of a Huffman-compressed progressive scan.
  166465. */
  166466. METHODDEF(void)
  166467. finish_pass_phuff (j_compress_ptr cinfo)
  166468. {
  166469. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166470. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166471. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166472. /* Flush out any buffered data */
  166473. emit_eobrun(entropy);
  166474. flush_bits_p(entropy);
  166475. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166476. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166477. }
  166478. /*
  166479. * Finish up a statistics-gathering pass and create the new Huffman tables.
  166480. */
  166481. METHODDEF(void)
  166482. finish_pass_gather_phuff (j_compress_ptr cinfo)
  166483. {
  166484. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166485. boolean is_DC_band;
  166486. int ci, tbl;
  166487. jpeg_component_info * compptr;
  166488. JHUFF_TBL **htblptr;
  166489. boolean did[NUM_HUFF_TBLS];
  166490. /* Flush out buffered data (all we care about is counting the EOB symbol) */
  166491. emit_eobrun(entropy);
  166492. is_DC_band = (cinfo->Ss == 0);
  166493. /* It's important not to apply jpeg_gen_optimal_table more than once
  166494. * per table, because it clobbers the input frequency counts!
  166495. */
  166496. MEMZERO(did, SIZEOF(did));
  166497. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  166498. compptr = cinfo->cur_comp_info[ci];
  166499. if (is_DC_band) {
  166500. if (cinfo->Ah != 0) /* DC refinement needs no table */
  166501. continue;
  166502. tbl = compptr->dc_tbl_no;
  166503. } else {
  166504. tbl = compptr->ac_tbl_no;
  166505. }
  166506. if (! did[tbl]) {
  166507. if (is_DC_band)
  166508. htblptr = & cinfo->dc_huff_tbl_ptrs[tbl];
  166509. else
  166510. htblptr = & cinfo->ac_huff_tbl_ptrs[tbl];
  166511. if (*htblptr == NULL)
  166512. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  166513. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->count_ptrs[tbl]);
  166514. did[tbl] = TRUE;
  166515. }
  166516. }
  166517. }
  166518. /*
  166519. * Module initialization routine for progressive Huffman entropy encoding.
  166520. */
  166521. GLOBAL(void)
  166522. jinit_phuff_encoder (j_compress_ptr cinfo)
  166523. {
  166524. phuff_entropy_ptr entropy;
  166525. int i;
  166526. entropy = (phuff_entropy_ptr)
  166527. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166528. SIZEOF(phuff_entropy_encoder));
  166529. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  166530. entropy->pub.start_pass = start_pass_phuff;
  166531. /* Mark tables unallocated */
  166532. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  166533. entropy->derived_tbls[i] = NULL;
  166534. entropy->count_ptrs[i] = NULL;
  166535. }
  166536. entropy->bit_buffer = NULL; /* needed only in AC refinement scan */
  166537. }
  166538. #endif /* C_PROGRESSIVE_SUPPORTED */
  166539. /*** End of inlined file: jcphuff.c ***/
  166540. /*** Start of inlined file: jcprepct.c ***/
  166541. #define JPEG_INTERNALS
  166542. /* At present, jcsample.c can request context rows only for smoothing.
  166543. * In the future, we might also need context rows for CCIR601 sampling
  166544. * or other more-complex downsampling procedures. The code to support
  166545. * context rows should be compiled only if needed.
  166546. */
  166547. #ifdef INPUT_SMOOTHING_SUPPORTED
  166548. #define CONTEXT_ROWS_SUPPORTED
  166549. #endif
  166550. /*
  166551. * For the simple (no-context-row) case, we just need to buffer one
  166552. * row group's worth of pixels for the downsampling step. At the bottom of
  166553. * the image, we pad to a full row group by replicating the last pixel row.
  166554. * The downsampler's last output row is then replicated if needed to pad
  166555. * out to a full iMCU row.
  166556. *
  166557. * When providing context rows, we must buffer three row groups' worth of
  166558. * pixels. Three row groups are physically allocated, but the row pointer
  166559. * arrays are made five row groups high, with the extra pointers above and
  166560. * below "wrapping around" to point to the last and first real row groups.
  166561. * This allows the downsampler to access the proper context rows.
  166562. * At the top and bottom of the image, we create dummy context rows by
  166563. * copying the first or last real pixel row. This copying could be avoided
  166564. * by pointer hacking as is done in jdmainct.c, but it doesn't seem worth the
  166565. * trouble on the compression side.
  166566. */
  166567. /* Private buffer controller object */
  166568. typedef struct {
  166569. struct jpeg_c_prep_controller pub; /* public fields */
  166570. /* Downsampling input buffer. This buffer holds color-converted data
  166571. * until we have enough to do a downsample step.
  166572. */
  166573. JSAMPARRAY color_buf[MAX_COMPONENTS];
  166574. JDIMENSION rows_to_go; /* counts rows remaining in source image */
  166575. int next_buf_row; /* index of next row to store in color_buf */
  166576. #ifdef CONTEXT_ROWS_SUPPORTED /* only needed for context case */
  166577. int this_row_group; /* starting row index of group to process */
  166578. int next_buf_stop; /* downsample when we reach this index */
  166579. #endif
  166580. } my_prep_controller;
  166581. typedef my_prep_controller * my_prep_ptr;
  166582. /*
  166583. * Initialize for a processing pass.
  166584. */
  166585. METHODDEF(void)
  166586. start_pass_prep (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  166587. {
  166588. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166589. if (pass_mode != JBUF_PASS_THRU)
  166590. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166591. /* Initialize total-height counter for detecting bottom of image */
  166592. prep->rows_to_go = cinfo->image_height;
  166593. /* Mark the conversion buffer empty */
  166594. prep->next_buf_row = 0;
  166595. #ifdef CONTEXT_ROWS_SUPPORTED
  166596. /* Preset additional state variables for context mode.
  166597. * These aren't used in non-context mode, so we needn't test which mode.
  166598. */
  166599. prep->this_row_group = 0;
  166600. /* Set next_buf_stop to stop after two row groups have been read in. */
  166601. prep->next_buf_stop = 2 * cinfo->max_v_samp_factor;
  166602. #endif
  166603. }
  166604. /*
  166605. * Expand an image vertically from height input_rows to height output_rows,
  166606. * by duplicating the bottom row.
  166607. */
  166608. LOCAL(void)
  166609. expand_bottom_edge (JSAMPARRAY image_data, JDIMENSION num_cols,
  166610. int input_rows, int output_rows)
  166611. {
  166612. register int row;
  166613. for (row = input_rows; row < output_rows; row++) {
  166614. jcopy_sample_rows(image_data, input_rows-1, image_data, row,
  166615. 1, num_cols);
  166616. }
  166617. }
  166618. /*
  166619. * Process some data in the simple no-context case.
  166620. *
  166621. * Preprocessor output data is counted in "row groups". A row group
  166622. * is defined to be v_samp_factor sample rows of each component.
  166623. * Downsampling will produce this much data from each max_v_samp_factor
  166624. * input rows.
  166625. */
  166626. METHODDEF(void)
  166627. pre_process_data (j_compress_ptr cinfo,
  166628. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  166629. JDIMENSION in_rows_avail,
  166630. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  166631. JDIMENSION out_row_groups_avail)
  166632. {
  166633. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166634. int numrows, ci;
  166635. JDIMENSION inrows;
  166636. jpeg_component_info * compptr;
  166637. while (*in_row_ctr < in_rows_avail &&
  166638. *out_row_group_ctr < out_row_groups_avail) {
  166639. /* Do color conversion to fill the conversion buffer. */
  166640. inrows = in_rows_avail - *in_row_ctr;
  166641. numrows = cinfo->max_v_samp_factor - prep->next_buf_row;
  166642. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  166643. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  166644. prep->color_buf,
  166645. (JDIMENSION) prep->next_buf_row,
  166646. numrows);
  166647. *in_row_ctr += numrows;
  166648. prep->next_buf_row += numrows;
  166649. prep->rows_to_go -= numrows;
  166650. /* If at bottom of image, pad to fill the conversion buffer. */
  166651. if (prep->rows_to_go == 0 &&
  166652. prep->next_buf_row < cinfo->max_v_samp_factor) {
  166653. for (ci = 0; ci < cinfo->num_components; ci++) {
  166654. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  166655. prep->next_buf_row, cinfo->max_v_samp_factor);
  166656. }
  166657. prep->next_buf_row = cinfo->max_v_samp_factor;
  166658. }
  166659. /* If we've filled the conversion buffer, empty it. */
  166660. if (prep->next_buf_row == cinfo->max_v_samp_factor) {
  166661. (*cinfo->downsample->downsample) (cinfo,
  166662. prep->color_buf, (JDIMENSION) 0,
  166663. output_buf, *out_row_group_ctr);
  166664. prep->next_buf_row = 0;
  166665. (*out_row_group_ctr)++;
  166666. }
  166667. /* If at bottom of image, pad the output to a full iMCU height.
  166668. * Note we assume the caller is providing a one-iMCU-height output buffer!
  166669. */
  166670. if (prep->rows_to_go == 0 &&
  166671. *out_row_group_ctr < out_row_groups_avail) {
  166672. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166673. ci++, compptr++) {
  166674. expand_bottom_edge(output_buf[ci],
  166675. compptr->width_in_blocks * DCTSIZE,
  166676. (int) (*out_row_group_ctr * compptr->v_samp_factor),
  166677. (int) (out_row_groups_avail * compptr->v_samp_factor));
  166678. }
  166679. *out_row_group_ctr = out_row_groups_avail;
  166680. break; /* can exit outer loop without test */
  166681. }
  166682. }
  166683. }
  166684. #ifdef CONTEXT_ROWS_SUPPORTED
  166685. /*
  166686. * Process some data in the context case.
  166687. */
  166688. METHODDEF(void)
  166689. pre_process_context (j_compress_ptr cinfo,
  166690. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  166691. JDIMENSION in_rows_avail,
  166692. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  166693. JDIMENSION out_row_groups_avail)
  166694. {
  166695. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166696. int numrows, ci;
  166697. int buf_height = cinfo->max_v_samp_factor * 3;
  166698. JDIMENSION inrows;
  166699. while (*out_row_group_ctr < out_row_groups_avail) {
  166700. if (*in_row_ctr < in_rows_avail) {
  166701. /* Do color conversion to fill the conversion buffer. */
  166702. inrows = in_rows_avail - *in_row_ctr;
  166703. numrows = prep->next_buf_stop - prep->next_buf_row;
  166704. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  166705. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  166706. prep->color_buf,
  166707. (JDIMENSION) prep->next_buf_row,
  166708. numrows);
  166709. /* Pad at top of image, if first time through */
  166710. if (prep->rows_to_go == cinfo->image_height) {
  166711. for (ci = 0; ci < cinfo->num_components; ci++) {
  166712. int row;
  166713. for (row = 1; row <= cinfo->max_v_samp_factor; row++) {
  166714. jcopy_sample_rows(prep->color_buf[ci], 0,
  166715. prep->color_buf[ci], -row,
  166716. 1, cinfo->image_width);
  166717. }
  166718. }
  166719. }
  166720. *in_row_ctr += numrows;
  166721. prep->next_buf_row += numrows;
  166722. prep->rows_to_go -= numrows;
  166723. } else {
  166724. /* Return for more data, unless we are at the bottom of the image. */
  166725. if (prep->rows_to_go != 0)
  166726. break;
  166727. /* When at bottom of image, pad to fill the conversion buffer. */
  166728. if (prep->next_buf_row < prep->next_buf_stop) {
  166729. for (ci = 0; ci < cinfo->num_components; ci++) {
  166730. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  166731. prep->next_buf_row, prep->next_buf_stop);
  166732. }
  166733. prep->next_buf_row = prep->next_buf_stop;
  166734. }
  166735. }
  166736. /* If we've gotten enough data, downsample a row group. */
  166737. if (prep->next_buf_row == prep->next_buf_stop) {
  166738. (*cinfo->downsample->downsample) (cinfo,
  166739. prep->color_buf,
  166740. (JDIMENSION) prep->this_row_group,
  166741. output_buf, *out_row_group_ctr);
  166742. (*out_row_group_ctr)++;
  166743. /* Advance pointers with wraparound as necessary. */
  166744. prep->this_row_group += cinfo->max_v_samp_factor;
  166745. if (prep->this_row_group >= buf_height)
  166746. prep->this_row_group = 0;
  166747. if (prep->next_buf_row >= buf_height)
  166748. prep->next_buf_row = 0;
  166749. prep->next_buf_stop = prep->next_buf_row + cinfo->max_v_samp_factor;
  166750. }
  166751. }
  166752. }
  166753. /*
  166754. * Create the wrapped-around downsampling input buffer needed for context mode.
  166755. */
  166756. LOCAL(void)
  166757. create_context_buffer (j_compress_ptr cinfo)
  166758. {
  166759. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166760. int rgroup_height = cinfo->max_v_samp_factor;
  166761. int ci, i;
  166762. jpeg_component_info * compptr;
  166763. JSAMPARRAY true_buffer, fake_buffer;
  166764. /* Grab enough space for fake row pointers for all the components;
  166765. * we need five row groups' worth of pointers for each component.
  166766. */
  166767. fake_buffer = (JSAMPARRAY)
  166768. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166769. (cinfo->num_components * 5 * rgroup_height) *
  166770. SIZEOF(JSAMPROW));
  166771. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166772. ci++, compptr++) {
  166773. /* Allocate the actual buffer space (3 row groups) for this component.
  166774. * We make the buffer wide enough to allow the downsampler to edge-expand
  166775. * horizontally within the buffer, if it so chooses.
  166776. */
  166777. true_buffer = (*cinfo->mem->alloc_sarray)
  166778. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166779. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  166780. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  166781. (JDIMENSION) (3 * rgroup_height));
  166782. /* Copy true buffer row pointers into the middle of the fake row array */
  166783. MEMCOPY(fake_buffer + rgroup_height, true_buffer,
  166784. 3 * rgroup_height * SIZEOF(JSAMPROW));
  166785. /* Fill in the above and below wraparound pointers */
  166786. for (i = 0; i < rgroup_height; i++) {
  166787. fake_buffer[i] = true_buffer[2 * rgroup_height + i];
  166788. fake_buffer[4 * rgroup_height + i] = true_buffer[i];
  166789. }
  166790. prep->color_buf[ci] = fake_buffer + rgroup_height;
  166791. fake_buffer += 5 * rgroup_height; /* point to space for next component */
  166792. }
  166793. }
  166794. #endif /* CONTEXT_ROWS_SUPPORTED */
  166795. /*
  166796. * Initialize preprocessing controller.
  166797. */
  166798. GLOBAL(void)
  166799. jinit_c_prep_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  166800. {
  166801. my_prep_ptr prep;
  166802. int ci;
  166803. jpeg_component_info * compptr;
  166804. if (need_full_buffer) /* safety check */
  166805. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166806. prep = (my_prep_ptr)
  166807. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166808. SIZEOF(my_prep_controller));
  166809. cinfo->prep = (struct jpeg_c_prep_controller *) prep;
  166810. prep->pub.start_pass = start_pass_prep;
  166811. /* Allocate the color conversion buffer.
  166812. * We make the buffer wide enough to allow the downsampler to edge-expand
  166813. * horizontally within the buffer, if it so chooses.
  166814. */
  166815. if (cinfo->downsample->need_context_rows) {
  166816. /* Set up to provide context rows */
  166817. #ifdef CONTEXT_ROWS_SUPPORTED
  166818. prep->pub.pre_process_data = pre_process_context;
  166819. create_context_buffer(cinfo);
  166820. #else
  166821. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166822. #endif
  166823. } else {
  166824. /* No context, just make it tall enough for one row group */
  166825. prep->pub.pre_process_data = pre_process_data;
  166826. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166827. ci++, compptr++) {
  166828. prep->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  166829. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166830. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  166831. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  166832. (JDIMENSION) cinfo->max_v_samp_factor);
  166833. }
  166834. }
  166835. }
  166836. /*** End of inlined file: jcprepct.c ***/
  166837. /*** Start of inlined file: jcsample.c ***/
  166838. #define JPEG_INTERNALS
  166839. /* Pointer to routine to downsample a single component */
  166840. typedef JMETHOD(void, downsample1_ptr,
  166841. (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166842. JSAMPARRAY input_data, JSAMPARRAY output_data));
  166843. /* Private subobject */
  166844. typedef struct {
  166845. struct jpeg_downsampler pub; /* public fields */
  166846. /* Downsampling method pointers, one per component */
  166847. downsample1_ptr methods[MAX_COMPONENTS];
  166848. } my_downsampler;
  166849. typedef my_downsampler * my_downsample_ptr;
  166850. /*
  166851. * Initialize for a downsampling pass.
  166852. */
  166853. METHODDEF(void)
  166854. start_pass_downsample (j_compress_ptr)
  166855. {
  166856. /* no work for now */
  166857. }
  166858. /*
  166859. * Expand a component horizontally from width input_cols to width output_cols,
  166860. * by duplicating the rightmost samples.
  166861. */
  166862. LOCAL(void)
  166863. expand_right_edge (JSAMPARRAY image_data, int num_rows,
  166864. JDIMENSION input_cols, JDIMENSION output_cols)
  166865. {
  166866. register JSAMPROW ptr;
  166867. register JSAMPLE pixval;
  166868. register int count;
  166869. int row;
  166870. int numcols = (int) (output_cols - input_cols);
  166871. if (numcols > 0) {
  166872. for (row = 0; row < num_rows; row++) {
  166873. ptr = image_data[row] + input_cols;
  166874. pixval = ptr[-1]; /* don't need GETJSAMPLE() here */
  166875. for (count = numcols; count > 0; count--)
  166876. *ptr++ = pixval;
  166877. }
  166878. }
  166879. }
  166880. /*
  166881. * Do downsampling for a whole row group (all components).
  166882. *
  166883. * In this version we simply downsample each component independently.
  166884. */
  166885. METHODDEF(void)
  166886. sep_downsample (j_compress_ptr cinfo,
  166887. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  166888. JSAMPIMAGE output_buf, JDIMENSION out_row_group_index)
  166889. {
  166890. my_downsample_ptr downsample = (my_downsample_ptr) cinfo->downsample;
  166891. int ci;
  166892. jpeg_component_info * compptr;
  166893. JSAMPARRAY in_ptr, out_ptr;
  166894. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166895. ci++, compptr++) {
  166896. in_ptr = input_buf[ci] + in_row_index;
  166897. out_ptr = output_buf[ci] + (out_row_group_index * compptr->v_samp_factor);
  166898. (*downsample->methods[ci]) (cinfo, compptr, in_ptr, out_ptr);
  166899. }
  166900. }
  166901. /*
  166902. * Downsample pixel values of a single component.
  166903. * One row group is processed per call.
  166904. * This version handles arbitrary integral sampling ratios, without smoothing.
  166905. * Note that this version is not actually used for customary sampling ratios.
  166906. */
  166907. METHODDEF(void)
  166908. int_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166909. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166910. {
  166911. int inrow, outrow, h_expand, v_expand, numpix, numpix2, h, v;
  166912. JDIMENSION outcol, outcol_h; /* outcol_h == outcol*h_expand */
  166913. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166914. JSAMPROW inptr, outptr;
  166915. INT32 outvalue;
  166916. h_expand = cinfo->max_h_samp_factor / compptr->h_samp_factor;
  166917. v_expand = cinfo->max_v_samp_factor / compptr->v_samp_factor;
  166918. numpix = h_expand * v_expand;
  166919. numpix2 = numpix/2;
  166920. /* Expand input data enough to let all the output samples be generated
  166921. * by the standard loop. Special-casing padded output would be more
  166922. * efficient.
  166923. */
  166924. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  166925. cinfo->image_width, output_cols * h_expand);
  166926. inrow = 0;
  166927. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166928. outptr = output_data[outrow];
  166929. for (outcol = 0, outcol_h = 0; outcol < output_cols;
  166930. outcol++, outcol_h += h_expand) {
  166931. outvalue = 0;
  166932. for (v = 0; v < v_expand; v++) {
  166933. inptr = input_data[inrow+v] + outcol_h;
  166934. for (h = 0; h < h_expand; h++) {
  166935. outvalue += (INT32) GETJSAMPLE(*inptr++);
  166936. }
  166937. }
  166938. *outptr++ = (JSAMPLE) ((outvalue + numpix2) / numpix);
  166939. }
  166940. inrow += v_expand;
  166941. }
  166942. }
  166943. /*
  166944. * Downsample pixel values of a single component.
  166945. * This version handles the special case of a full-size component,
  166946. * without smoothing.
  166947. */
  166948. METHODDEF(void)
  166949. fullsize_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166950. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166951. {
  166952. /* Copy the data */
  166953. jcopy_sample_rows(input_data, 0, output_data, 0,
  166954. cinfo->max_v_samp_factor, cinfo->image_width);
  166955. /* Edge-expand */
  166956. expand_right_edge(output_data, cinfo->max_v_samp_factor,
  166957. cinfo->image_width, compptr->width_in_blocks * DCTSIZE);
  166958. }
  166959. /*
  166960. * Downsample pixel values of a single component.
  166961. * This version handles the common case of 2:1 horizontal and 1:1 vertical,
  166962. * without smoothing.
  166963. *
  166964. * A note about the "bias" calculations: when rounding fractional values to
  166965. * integer, we do not want to always round 0.5 up to the next integer.
  166966. * If we did that, we'd introduce a noticeable bias towards larger values.
  166967. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  166968. * alternate pixel locations (a simple ordered dither pattern).
  166969. */
  166970. METHODDEF(void)
  166971. h2v1_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166972. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166973. {
  166974. int outrow;
  166975. JDIMENSION outcol;
  166976. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166977. register JSAMPROW inptr, outptr;
  166978. register int bias;
  166979. /* Expand input data enough to let all the output samples be generated
  166980. * by the standard loop. Special-casing padded output would be more
  166981. * efficient.
  166982. */
  166983. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  166984. cinfo->image_width, output_cols * 2);
  166985. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166986. outptr = output_data[outrow];
  166987. inptr = input_data[outrow];
  166988. bias = 0; /* bias = 0,1,0,1,... for successive samples */
  166989. for (outcol = 0; outcol < output_cols; outcol++) {
  166990. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr) + GETJSAMPLE(inptr[1])
  166991. + bias) >> 1);
  166992. bias ^= 1; /* 0=>1, 1=>0 */
  166993. inptr += 2;
  166994. }
  166995. }
  166996. }
  166997. /*
  166998. * Downsample pixel values of a single component.
  166999. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  167000. * without smoothing.
  167001. */
  167002. METHODDEF(void)
  167003. h2v2_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  167004. JSAMPARRAY input_data, JSAMPARRAY output_data)
  167005. {
  167006. int inrow, outrow;
  167007. JDIMENSION outcol;
  167008. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  167009. register JSAMPROW inptr0, inptr1, outptr;
  167010. register int bias;
  167011. /* Expand input data enough to let all the output samples be generated
  167012. * by the standard loop. Special-casing padded output would be more
  167013. * efficient.
  167014. */
  167015. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  167016. cinfo->image_width, output_cols * 2);
  167017. inrow = 0;
  167018. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  167019. outptr = output_data[outrow];
  167020. inptr0 = input_data[inrow];
  167021. inptr1 = input_data[inrow+1];
  167022. bias = 1; /* bias = 1,2,1,2,... for successive samples */
  167023. for (outcol = 0; outcol < output_cols; outcol++) {
  167024. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  167025. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1])
  167026. + bias) >> 2);
  167027. bias ^= 3; /* 1=>2, 2=>1 */
  167028. inptr0 += 2; inptr1 += 2;
  167029. }
  167030. inrow += 2;
  167031. }
  167032. }
  167033. #ifdef INPUT_SMOOTHING_SUPPORTED
  167034. /*
  167035. * Downsample pixel values of a single component.
  167036. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  167037. * with smoothing. One row of context is required.
  167038. */
  167039. METHODDEF(void)
  167040. h2v2_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  167041. JSAMPARRAY input_data, JSAMPARRAY output_data)
  167042. {
  167043. int inrow, outrow;
  167044. JDIMENSION colctr;
  167045. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  167046. register JSAMPROW inptr0, inptr1, above_ptr, below_ptr, outptr;
  167047. INT32 membersum, neighsum, memberscale, neighscale;
  167048. /* Expand input data enough to let all the output samples be generated
  167049. * by the standard loop. Special-casing padded output would be more
  167050. * efficient.
  167051. */
  167052. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  167053. cinfo->image_width, output_cols * 2);
  167054. /* We don't bother to form the individual "smoothed" input pixel values;
  167055. * we can directly compute the output which is the average of the four
  167056. * smoothed values. Each of the four member pixels contributes a fraction
  167057. * (1-8*SF) to its own smoothed image and a fraction SF to each of the three
  167058. * other smoothed pixels, therefore a total fraction (1-5*SF)/4 to the final
  167059. * output. The four corner-adjacent neighbor pixels contribute a fraction
  167060. * SF to just one smoothed pixel, or SF/4 to the final output; while the
  167061. * eight edge-adjacent neighbors contribute SF to each of two smoothed
  167062. * pixels, or SF/2 overall. In order to use integer arithmetic, these
  167063. * factors are scaled by 2^16 = 65536.
  167064. * Also recall that SF = smoothing_factor / 1024.
  167065. */
  167066. memberscale = 16384 - cinfo->smoothing_factor * 80; /* scaled (1-5*SF)/4 */
  167067. neighscale = cinfo->smoothing_factor * 16; /* scaled SF/4 */
  167068. inrow = 0;
  167069. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  167070. outptr = output_data[outrow];
  167071. inptr0 = input_data[inrow];
  167072. inptr1 = input_data[inrow+1];
  167073. above_ptr = input_data[inrow-1];
  167074. below_ptr = input_data[inrow+2];
  167075. /* Special case for first column: pretend column -1 is same as column 0 */
  167076. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  167077. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  167078. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  167079. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  167080. GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[2]) +
  167081. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[2]);
  167082. neighsum += neighsum;
  167083. neighsum += GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[2]) +
  167084. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[2]);
  167085. membersum = membersum * memberscale + neighsum * neighscale;
  167086. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  167087. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  167088. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  167089. /* sum of pixels directly mapped to this output element */
  167090. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  167091. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  167092. /* sum of edge-neighbor pixels */
  167093. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  167094. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  167095. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[2]) +
  167096. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[2]);
  167097. /* The edge-neighbors count twice as much as corner-neighbors */
  167098. neighsum += neighsum;
  167099. /* Add in the corner-neighbors */
  167100. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[2]) +
  167101. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[2]);
  167102. /* form final output scaled up by 2^16 */
  167103. membersum = membersum * memberscale + neighsum * neighscale;
  167104. /* round, descale and output it */
  167105. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  167106. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  167107. }
  167108. /* Special case for last column */
  167109. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  167110. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  167111. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  167112. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  167113. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[1]) +
  167114. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[1]);
  167115. neighsum += neighsum;
  167116. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[1]) +
  167117. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[1]);
  167118. membersum = membersum * memberscale + neighsum * neighscale;
  167119. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  167120. inrow += 2;
  167121. }
  167122. }
  167123. /*
  167124. * Downsample pixel values of a single component.
  167125. * This version handles the special case of a full-size component,
  167126. * with smoothing. One row of context is required.
  167127. */
  167128. METHODDEF(void)
  167129. fullsize_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info *compptr,
  167130. JSAMPARRAY input_data, JSAMPARRAY output_data)
  167131. {
  167132. int outrow;
  167133. JDIMENSION colctr;
  167134. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  167135. register JSAMPROW inptr, above_ptr, below_ptr, outptr;
  167136. INT32 membersum, neighsum, memberscale, neighscale;
  167137. int colsum, lastcolsum, nextcolsum;
  167138. /* Expand input data enough to let all the output samples be generated
  167139. * by the standard loop. Special-casing padded output would be more
  167140. * efficient.
  167141. */
  167142. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  167143. cinfo->image_width, output_cols);
  167144. /* Each of the eight neighbor pixels contributes a fraction SF to the
  167145. * smoothed pixel, while the main pixel contributes (1-8*SF). In order
  167146. * to use integer arithmetic, these factors are multiplied by 2^16 = 65536.
  167147. * Also recall that SF = smoothing_factor / 1024.
  167148. */
  167149. memberscale = 65536L - cinfo->smoothing_factor * 512L; /* scaled 1-8*SF */
  167150. neighscale = cinfo->smoothing_factor * 64; /* scaled SF */
  167151. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  167152. outptr = output_data[outrow];
  167153. inptr = input_data[outrow];
  167154. above_ptr = input_data[outrow-1];
  167155. below_ptr = input_data[outrow+1];
  167156. /* Special case for first column */
  167157. colsum = GETJSAMPLE(*above_ptr++) + GETJSAMPLE(*below_ptr++) +
  167158. GETJSAMPLE(*inptr);
  167159. membersum = GETJSAMPLE(*inptr++);
  167160. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  167161. GETJSAMPLE(*inptr);
  167162. neighsum = colsum + (colsum - membersum) + nextcolsum;
  167163. membersum = membersum * memberscale + neighsum * neighscale;
  167164. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  167165. lastcolsum = colsum; colsum = nextcolsum;
  167166. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  167167. membersum = GETJSAMPLE(*inptr++);
  167168. above_ptr++; below_ptr++;
  167169. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  167170. GETJSAMPLE(*inptr);
  167171. neighsum = lastcolsum + (colsum - membersum) + nextcolsum;
  167172. membersum = membersum * memberscale + neighsum * neighscale;
  167173. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  167174. lastcolsum = colsum; colsum = nextcolsum;
  167175. }
  167176. /* Special case for last column */
  167177. membersum = GETJSAMPLE(*inptr);
  167178. neighsum = lastcolsum + (colsum - membersum) + colsum;
  167179. membersum = membersum * memberscale + neighsum * neighscale;
  167180. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  167181. }
  167182. }
  167183. #endif /* INPUT_SMOOTHING_SUPPORTED */
  167184. /*
  167185. * Module initialization routine for downsampling.
  167186. * Note that we must select a routine for each component.
  167187. */
  167188. GLOBAL(void)
  167189. jinit_downsampler (j_compress_ptr cinfo)
  167190. {
  167191. my_downsample_ptr downsample;
  167192. int ci;
  167193. jpeg_component_info * compptr;
  167194. boolean smoothok = TRUE;
  167195. downsample = (my_downsample_ptr)
  167196. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167197. SIZEOF(my_downsampler));
  167198. cinfo->downsample = (struct jpeg_downsampler *) downsample;
  167199. downsample->pub.start_pass = start_pass_downsample;
  167200. downsample->pub.downsample = sep_downsample;
  167201. downsample->pub.need_context_rows = FALSE;
  167202. if (cinfo->CCIR601_sampling)
  167203. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  167204. /* Verify we can handle the sampling factors, and set up method pointers */
  167205. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167206. ci++, compptr++) {
  167207. if (compptr->h_samp_factor == cinfo->max_h_samp_factor &&
  167208. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  167209. #ifdef INPUT_SMOOTHING_SUPPORTED
  167210. if (cinfo->smoothing_factor) {
  167211. downsample->methods[ci] = fullsize_smooth_downsample;
  167212. downsample->pub.need_context_rows = TRUE;
  167213. } else
  167214. #endif
  167215. downsample->methods[ci] = fullsize_downsample;
  167216. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  167217. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  167218. smoothok = FALSE;
  167219. downsample->methods[ci] = h2v1_downsample;
  167220. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  167221. compptr->v_samp_factor * 2 == cinfo->max_v_samp_factor) {
  167222. #ifdef INPUT_SMOOTHING_SUPPORTED
  167223. if (cinfo->smoothing_factor) {
  167224. downsample->methods[ci] = h2v2_smooth_downsample;
  167225. downsample->pub.need_context_rows = TRUE;
  167226. } else
  167227. #endif
  167228. downsample->methods[ci] = h2v2_downsample;
  167229. } else if ((cinfo->max_h_samp_factor % compptr->h_samp_factor) == 0 &&
  167230. (cinfo->max_v_samp_factor % compptr->v_samp_factor) == 0) {
  167231. smoothok = FALSE;
  167232. downsample->methods[ci] = int_downsample;
  167233. } else
  167234. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  167235. }
  167236. #ifdef INPUT_SMOOTHING_SUPPORTED
  167237. if (cinfo->smoothing_factor && !smoothok)
  167238. TRACEMS(cinfo, 0, JTRC_SMOOTH_NOTIMPL);
  167239. #endif
  167240. }
  167241. /*** End of inlined file: jcsample.c ***/
  167242. /*** Start of inlined file: jctrans.c ***/
  167243. #define JPEG_INTERNALS
  167244. /* Forward declarations */
  167245. LOCAL(void) transencode_master_selection
  167246. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  167247. LOCAL(void) transencode_coef_controller
  167248. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  167249. /*
  167250. * Compression initialization for writing raw-coefficient data.
  167251. * Before calling this, all parameters and a data destination must be set up.
  167252. * Call jpeg_finish_compress() to actually write the data.
  167253. *
  167254. * The number of passed virtual arrays must match cinfo->num_components.
  167255. * Note that the virtual arrays need not be filled or even realized at
  167256. * the time write_coefficients is called; indeed, if the virtual arrays
  167257. * were requested from this compression object's memory manager, they
  167258. * typically will be realized during this routine and filled afterwards.
  167259. */
  167260. GLOBAL(void)
  167261. jpeg_write_coefficients (j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays)
  167262. {
  167263. if (cinfo->global_state != CSTATE_START)
  167264. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167265. /* Mark all tables to be written */
  167266. jpeg_suppress_tables(cinfo, FALSE);
  167267. /* (Re)initialize error mgr and destination modules */
  167268. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  167269. (*cinfo->dest->init_destination) (cinfo);
  167270. /* Perform master selection of active modules */
  167271. transencode_master_selection(cinfo, coef_arrays);
  167272. /* Wait for jpeg_finish_compress() call */
  167273. cinfo->next_scanline = 0; /* so jpeg_write_marker works */
  167274. cinfo->global_state = CSTATE_WRCOEFS;
  167275. }
  167276. /*
  167277. * Initialize the compression object with default parameters,
  167278. * then copy from the source object all parameters needed for lossless
  167279. * transcoding. Parameters that can be varied without loss (such as
  167280. * scan script and Huffman optimization) are left in their default states.
  167281. */
  167282. GLOBAL(void)
  167283. jpeg_copy_critical_parameters (j_decompress_ptr srcinfo,
  167284. j_compress_ptr dstinfo)
  167285. {
  167286. JQUANT_TBL ** qtblptr;
  167287. jpeg_component_info *incomp, *outcomp;
  167288. JQUANT_TBL *c_quant, *slot_quant;
  167289. int tblno, ci, coefi;
  167290. /* Safety check to ensure start_compress not called yet. */
  167291. if (dstinfo->global_state != CSTATE_START)
  167292. ERREXIT1(dstinfo, JERR_BAD_STATE, dstinfo->global_state);
  167293. /* Copy fundamental image dimensions */
  167294. dstinfo->image_width = srcinfo->image_width;
  167295. dstinfo->image_height = srcinfo->image_height;
  167296. dstinfo->input_components = srcinfo->num_components;
  167297. dstinfo->in_color_space = srcinfo->jpeg_color_space;
  167298. /* Initialize all parameters to default values */
  167299. jpeg_set_defaults(dstinfo);
  167300. /* jpeg_set_defaults may choose wrong colorspace, eg YCbCr if input is RGB.
  167301. * Fix it to get the right header markers for the image colorspace.
  167302. */
  167303. jpeg_set_colorspace(dstinfo, srcinfo->jpeg_color_space);
  167304. dstinfo->data_precision = srcinfo->data_precision;
  167305. dstinfo->CCIR601_sampling = srcinfo->CCIR601_sampling;
  167306. /* Copy the source's quantization tables. */
  167307. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  167308. if (srcinfo->quant_tbl_ptrs[tblno] != NULL) {
  167309. qtblptr = & dstinfo->quant_tbl_ptrs[tblno];
  167310. if (*qtblptr == NULL)
  167311. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) dstinfo);
  167312. MEMCOPY((*qtblptr)->quantval,
  167313. srcinfo->quant_tbl_ptrs[tblno]->quantval,
  167314. SIZEOF((*qtblptr)->quantval));
  167315. (*qtblptr)->sent_table = FALSE;
  167316. }
  167317. }
  167318. /* Copy the source's per-component info.
  167319. * Note we assume jpeg_set_defaults has allocated the dest comp_info array.
  167320. */
  167321. dstinfo->num_components = srcinfo->num_components;
  167322. if (dstinfo->num_components < 1 || dstinfo->num_components > MAX_COMPONENTS)
  167323. ERREXIT2(dstinfo, JERR_COMPONENT_COUNT, dstinfo->num_components,
  167324. MAX_COMPONENTS);
  167325. for (ci = 0, incomp = srcinfo->comp_info, outcomp = dstinfo->comp_info;
  167326. ci < dstinfo->num_components; ci++, incomp++, outcomp++) {
  167327. outcomp->component_id = incomp->component_id;
  167328. outcomp->h_samp_factor = incomp->h_samp_factor;
  167329. outcomp->v_samp_factor = incomp->v_samp_factor;
  167330. outcomp->quant_tbl_no = incomp->quant_tbl_no;
  167331. /* Make sure saved quantization table for component matches the qtable
  167332. * slot. If not, the input file re-used this qtable slot.
  167333. * IJG encoder currently cannot duplicate this.
  167334. */
  167335. tblno = outcomp->quant_tbl_no;
  167336. if (tblno < 0 || tblno >= NUM_QUANT_TBLS ||
  167337. srcinfo->quant_tbl_ptrs[tblno] == NULL)
  167338. ERREXIT1(dstinfo, JERR_NO_QUANT_TABLE, tblno);
  167339. slot_quant = srcinfo->quant_tbl_ptrs[tblno];
  167340. c_quant = incomp->quant_table;
  167341. if (c_quant != NULL) {
  167342. for (coefi = 0; coefi < DCTSIZE2; coefi++) {
  167343. if (c_quant->quantval[coefi] != slot_quant->quantval[coefi])
  167344. ERREXIT1(dstinfo, JERR_MISMATCHED_QUANT_TABLE, tblno);
  167345. }
  167346. }
  167347. /* Note: we do not copy the source's Huffman table assignments;
  167348. * instead we rely on jpeg_set_colorspace to have made a suitable choice.
  167349. */
  167350. }
  167351. /* Also copy JFIF version and resolution information, if available.
  167352. * Strictly speaking this isn't "critical" info, but it's nearly
  167353. * always appropriate to copy it if available. In particular,
  167354. * if the application chooses to copy JFIF 1.02 extension markers from
  167355. * the source file, we need to copy the version to make sure we don't
  167356. * emit a file that has 1.02 extensions but a claimed version of 1.01.
  167357. * We will *not*, however, copy version info from mislabeled "2.01" files.
  167358. */
  167359. if (srcinfo->saw_JFIF_marker) {
  167360. if (srcinfo->JFIF_major_version == 1) {
  167361. dstinfo->JFIF_major_version = srcinfo->JFIF_major_version;
  167362. dstinfo->JFIF_minor_version = srcinfo->JFIF_minor_version;
  167363. }
  167364. dstinfo->density_unit = srcinfo->density_unit;
  167365. dstinfo->X_density = srcinfo->X_density;
  167366. dstinfo->Y_density = srcinfo->Y_density;
  167367. }
  167368. }
  167369. /*
  167370. * Master selection of compression modules for transcoding.
  167371. * This substitutes for jcinit.c's initialization of the full compressor.
  167372. */
  167373. LOCAL(void)
  167374. transencode_master_selection (j_compress_ptr cinfo,
  167375. jvirt_barray_ptr * coef_arrays)
  167376. {
  167377. /* Although we don't actually use input_components for transcoding,
  167378. * jcmaster.c's initial_setup will complain if input_components is 0.
  167379. */
  167380. cinfo->input_components = 1;
  167381. /* Initialize master control (includes parameter checking/processing) */
  167382. jinit_c_master_control(cinfo, TRUE /* transcode only */);
  167383. /* Entropy encoding: either Huffman or arithmetic coding. */
  167384. if (cinfo->arith_code) {
  167385. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  167386. } else {
  167387. if (cinfo->progressive_mode) {
  167388. #ifdef C_PROGRESSIVE_SUPPORTED
  167389. jinit_phuff_encoder(cinfo);
  167390. #else
  167391. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167392. #endif
  167393. } else
  167394. jinit_huff_encoder(cinfo);
  167395. }
  167396. /* We need a special coefficient buffer controller. */
  167397. transencode_coef_controller(cinfo, coef_arrays);
  167398. jinit_marker_writer(cinfo);
  167399. /* We can now tell the memory manager to allocate virtual arrays. */
  167400. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  167401. /* Write the datastream header (SOI, JFIF) immediately.
  167402. * Frame and scan headers are postponed till later.
  167403. * This lets application insert special markers after the SOI.
  167404. */
  167405. (*cinfo->marker->write_file_header) (cinfo);
  167406. }
  167407. /*
  167408. * The rest of this file is a special implementation of the coefficient
  167409. * buffer controller. This is similar to jccoefct.c, but it handles only
  167410. * output from presupplied virtual arrays. Furthermore, we generate any
  167411. * dummy padding blocks on-the-fly rather than expecting them to be present
  167412. * in the arrays.
  167413. */
  167414. /* Private buffer controller object */
  167415. typedef struct {
  167416. struct jpeg_c_coef_controller pub; /* public fields */
  167417. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  167418. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  167419. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  167420. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  167421. /* Virtual block array for each component. */
  167422. jvirt_barray_ptr * whole_image;
  167423. /* Workspace for constructing dummy blocks at right/bottom edges. */
  167424. JBLOCKROW dummy_buffer[C_MAX_BLOCKS_IN_MCU];
  167425. } my_coef_controller2;
  167426. typedef my_coef_controller2 * my_coef_ptr2;
  167427. LOCAL(void)
  167428. start_iMCU_row2 (j_compress_ptr cinfo)
  167429. /* Reset within-iMCU-row counters for a new row */
  167430. {
  167431. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  167432. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  167433. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  167434. * But at the bottom of the image, process only what's left.
  167435. */
  167436. if (cinfo->comps_in_scan > 1) {
  167437. coef->MCU_rows_per_iMCU_row = 1;
  167438. } else {
  167439. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  167440. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  167441. else
  167442. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  167443. }
  167444. coef->mcu_ctr = 0;
  167445. coef->MCU_vert_offset = 0;
  167446. }
  167447. /*
  167448. * Initialize for a processing pass.
  167449. */
  167450. METHODDEF(void)
  167451. start_pass_coef2 (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  167452. {
  167453. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  167454. if (pass_mode != JBUF_CRANK_DEST)
  167455. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  167456. coef->iMCU_row_num = 0;
  167457. start_iMCU_row2(cinfo);
  167458. }
  167459. /*
  167460. * Process some data.
  167461. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  167462. * per call, ie, v_samp_factor block rows for each component in the scan.
  167463. * The data is obtained from the virtual arrays and fed to the entropy coder.
  167464. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  167465. *
  167466. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  167467. */
  167468. METHODDEF(boolean)
  167469. compress_output2 (j_compress_ptr cinfo, JSAMPIMAGE)
  167470. {
  167471. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  167472. JDIMENSION MCU_col_num; /* index of current MCU within row */
  167473. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  167474. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  167475. int blkn, ci, xindex, yindex, yoffset, blockcnt;
  167476. JDIMENSION start_col;
  167477. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  167478. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  167479. JBLOCKROW buffer_ptr;
  167480. jpeg_component_info *compptr;
  167481. /* Align the virtual buffers for the components used in this scan. */
  167482. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167483. compptr = cinfo->cur_comp_info[ci];
  167484. buffer[ci] = (*cinfo->mem->access_virt_barray)
  167485. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  167486. coef->iMCU_row_num * compptr->v_samp_factor,
  167487. (JDIMENSION) compptr->v_samp_factor, FALSE);
  167488. }
  167489. /* Loop to process one whole iMCU row */
  167490. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  167491. yoffset++) {
  167492. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  167493. MCU_col_num++) {
  167494. /* Construct list of pointers to DCT blocks belonging to this MCU */
  167495. blkn = 0; /* index of current DCT block within MCU */
  167496. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167497. compptr = cinfo->cur_comp_info[ci];
  167498. start_col = MCU_col_num * compptr->MCU_width;
  167499. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  167500. : compptr->last_col_width;
  167501. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  167502. if (coef->iMCU_row_num < last_iMCU_row ||
  167503. yindex+yoffset < compptr->last_row_height) {
  167504. /* Fill in pointers to real blocks in this row */
  167505. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  167506. for (xindex = 0; xindex < blockcnt; xindex++)
  167507. MCU_buffer[blkn++] = buffer_ptr++;
  167508. } else {
  167509. /* At bottom of image, need a whole row of dummy blocks */
  167510. xindex = 0;
  167511. }
  167512. /* Fill in any dummy blocks needed in this row.
  167513. * Dummy blocks are filled in the same way as in jccoefct.c:
  167514. * all zeroes in the AC entries, DC entries equal to previous
  167515. * block's DC value. The init routine has already zeroed the
  167516. * AC entries, so we need only set the DC entries correctly.
  167517. */
  167518. for (; xindex < compptr->MCU_width; xindex++) {
  167519. MCU_buffer[blkn] = coef->dummy_buffer[blkn];
  167520. MCU_buffer[blkn][0][0] = MCU_buffer[blkn-1][0][0];
  167521. blkn++;
  167522. }
  167523. }
  167524. }
  167525. /* Try to write the MCU. */
  167526. if (! (*cinfo->entropy->encode_mcu) (cinfo, MCU_buffer)) {
  167527. /* Suspension forced; update state counters and exit */
  167528. coef->MCU_vert_offset = yoffset;
  167529. coef->mcu_ctr = MCU_col_num;
  167530. return FALSE;
  167531. }
  167532. }
  167533. /* Completed an MCU row, but perhaps not an iMCU row */
  167534. coef->mcu_ctr = 0;
  167535. }
  167536. /* Completed the iMCU row, advance counters for next one */
  167537. coef->iMCU_row_num++;
  167538. start_iMCU_row2(cinfo);
  167539. return TRUE;
  167540. }
  167541. /*
  167542. * Initialize coefficient buffer controller.
  167543. *
  167544. * Each passed coefficient array must be the right size for that
  167545. * coefficient: width_in_blocks wide and height_in_blocks high,
  167546. * with unitheight at least v_samp_factor.
  167547. */
  167548. LOCAL(void)
  167549. transencode_coef_controller (j_compress_ptr cinfo,
  167550. jvirt_barray_ptr * coef_arrays)
  167551. {
  167552. my_coef_ptr2 coef;
  167553. JBLOCKROW buffer;
  167554. int i;
  167555. coef = (my_coef_ptr2)
  167556. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167557. SIZEOF(my_coef_controller2));
  167558. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  167559. coef->pub.start_pass = start_pass_coef2;
  167560. coef->pub.compress_data = compress_output2;
  167561. /* Save pointer to virtual arrays */
  167562. coef->whole_image = coef_arrays;
  167563. /* Allocate and pre-zero space for dummy DCT blocks. */
  167564. buffer = (JBLOCKROW)
  167565. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167566. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  167567. jzero_far((void FAR *) buffer, C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  167568. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  167569. coef->dummy_buffer[i] = buffer + i;
  167570. }
  167571. }
  167572. /*** End of inlined file: jctrans.c ***/
  167573. /*** Start of inlined file: jdapistd.c ***/
  167574. #define JPEG_INTERNALS
  167575. /* Forward declarations */
  167576. LOCAL(boolean) output_pass_setup JPP((j_decompress_ptr cinfo));
  167577. /*
  167578. * Decompression initialization.
  167579. * jpeg_read_header must be completed before calling this.
  167580. *
  167581. * If a multipass operating mode was selected, this will do all but the
  167582. * last pass, and thus may take a great deal of time.
  167583. *
  167584. * Returns FALSE if suspended. The return value need be inspected only if
  167585. * a suspending data source is used.
  167586. */
  167587. GLOBAL(boolean)
  167588. jpeg_start_decompress (j_decompress_ptr cinfo)
  167589. {
  167590. if (cinfo->global_state == DSTATE_READY) {
  167591. /* First call: initialize master control, select active modules */
  167592. jinit_master_decompress(cinfo);
  167593. if (cinfo->buffered_image) {
  167594. /* No more work here; expecting jpeg_start_output next */
  167595. cinfo->global_state = DSTATE_BUFIMAGE;
  167596. return TRUE;
  167597. }
  167598. cinfo->global_state = DSTATE_PRELOAD;
  167599. }
  167600. if (cinfo->global_state == DSTATE_PRELOAD) {
  167601. /* If file has multiple scans, absorb them all into the coef buffer */
  167602. if (cinfo->inputctl->has_multiple_scans) {
  167603. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167604. for (;;) {
  167605. int retcode;
  167606. /* Call progress monitor hook if present */
  167607. if (cinfo->progress != NULL)
  167608. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167609. /* Absorb some more input */
  167610. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  167611. if (retcode == JPEG_SUSPENDED)
  167612. return FALSE;
  167613. if (retcode == JPEG_REACHED_EOI)
  167614. break;
  167615. /* Advance progress counter if appropriate */
  167616. if (cinfo->progress != NULL &&
  167617. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  167618. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  167619. /* jdmaster underestimated number of scans; ratchet up one scan */
  167620. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  167621. }
  167622. }
  167623. }
  167624. #else
  167625. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167626. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  167627. }
  167628. cinfo->output_scan_number = cinfo->input_scan_number;
  167629. } else if (cinfo->global_state != DSTATE_PRESCAN)
  167630. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167631. /* Perform any dummy output passes, and set up for the final pass */
  167632. return output_pass_setup(cinfo);
  167633. }
  167634. /*
  167635. * Set up for an output pass, and perform any dummy pass(es) needed.
  167636. * Common subroutine for jpeg_start_decompress and jpeg_start_output.
  167637. * Entry: global_state = DSTATE_PRESCAN only if previously suspended.
  167638. * Exit: If done, returns TRUE and sets global_state for proper output mode.
  167639. * If suspended, returns FALSE and sets global_state = DSTATE_PRESCAN.
  167640. */
  167641. LOCAL(boolean)
  167642. output_pass_setup (j_decompress_ptr cinfo)
  167643. {
  167644. if (cinfo->global_state != DSTATE_PRESCAN) {
  167645. /* First call: do pass setup */
  167646. (*cinfo->master->prepare_for_output_pass) (cinfo);
  167647. cinfo->output_scanline = 0;
  167648. cinfo->global_state = DSTATE_PRESCAN;
  167649. }
  167650. /* Loop over any required dummy passes */
  167651. while (cinfo->master->is_dummy_pass) {
  167652. #ifdef QUANT_2PASS_SUPPORTED
  167653. /* Crank through the dummy pass */
  167654. while (cinfo->output_scanline < cinfo->output_height) {
  167655. JDIMENSION last_scanline;
  167656. /* Call progress monitor hook if present */
  167657. if (cinfo->progress != NULL) {
  167658. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167659. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167660. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167661. }
  167662. /* Process some data */
  167663. last_scanline = cinfo->output_scanline;
  167664. (*cinfo->main->process_data) (cinfo, (JSAMPARRAY) NULL,
  167665. &cinfo->output_scanline, (JDIMENSION) 0);
  167666. if (cinfo->output_scanline == last_scanline)
  167667. return FALSE; /* No progress made, must suspend */
  167668. }
  167669. /* Finish up dummy pass, and set up for another one */
  167670. (*cinfo->master->finish_output_pass) (cinfo);
  167671. (*cinfo->master->prepare_for_output_pass) (cinfo);
  167672. cinfo->output_scanline = 0;
  167673. #else
  167674. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167675. #endif /* QUANT_2PASS_SUPPORTED */
  167676. }
  167677. /* Ready for application to drive output pass through
  167678. * jpeg_read_scanlines or jpeg_read_raw_data.
  167679. */
  167680. cinfo->global_state = cinfo->raw_data_out ? DSTATE_RAW_OK : DSTATE_SCANNING;
  167681. return TRUE;
  167682. }
  167683. /*
  167684. * Read some scanlines of data from the JPEG decompressor.
  167685. *
  167686. * The return value will be the number of lines actually read.
  167687. * This may be less than the number requested in several cases,
  167688. * including bottom of image, data source suspension, and operating
  167689. * modes that emit multiple scanlines at a time.
  167690. *
  167691. * Note: we warn about excess calls to jpeg_read_scanlines() since
  167692. * this likely signals an application programmer error. However,
  167693. * an oversize buffer (max_lines > scanlines remaining) is not an error.
  167694. */
  167695. GLOBAL(JDIMENSION)
  167696. jpeg_read_scanlines (j_decompress_ptr cinfo, JSAMPARRAY scanlines,
  167697. JDIMENSION max_lines)
  167698. {
  167699. JDIMENSION row_ctr;
  167700. if (cinfo->global_state != DSTATE_SCANNING)
  167701. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167702. if (cinfo->output_scanline >= cinfo->output_height) {
  167703. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  167704. return 0;
  167705. }
  167706. /* Call progress monitor hook if present */
  167707. if (cinfo->progress != NULL) {
  167708. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167709. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167710. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167711. }
  167712. /* Process some data */
  167713. row_ctr = 0;
  167714. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, max_lines);
  167715. cinfo->output_scanline += row_ctr;
  167716. return row_ctr;
  167717. }
  167718. /*
  167719. * Alternate entry point to read raw data.
  167720. * Processes exactly one iMCU row per call, unless suspended.
  167721. */
  167722. GLOBAL(JDIMENSION)
  167723. jpeg_read_raw_data (j_decompress_ptr cinfo, JSAMPIMAGE data,
  167724. JDIMENSION max_lines)
  167725. {
  167726. JDIMENSION lines_per_iMCU_row;
  167727. if (cinfo->global_state != DSTATE_RAW_OK)
  167728. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167729. if (cinfo->output_scanline >= cinfo->output_height) {
  167730. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  167731. return 0;
  167732. }
  167733. /* Call progress monitor hook if present */
  167734. if (cinfo->progress != NULL) {
  167735. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167736. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167737. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167738. }
  167739. /* Verify that at least one iMCU row can be returned. */
  167740. lines_per_iMCU_row = cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size;
  167741. if (max_lines < lines_per_iMCU_row)
  167742. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  167743. /* Decompress directly into user's buffer. */
  167744. if (! (*cinfo->coef->decompress_data) (cinfo, data))
  167745. return 0; /* suspension forced, can do nothing more */
  167746. /* OK, we processed one iMCU row. */
  167747. cinfo->output_scanline += lines_per_iMCU_row;
  167748. return lines_per_iMCU_row;
  167749. }
  167750. /* Additional entry points for buffered-image mode. */
  167751. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167752. /*
  167753. * Initialize for an output pass in buffered-image mode.
  167754. */
  167755. GLOBAL(boolean)
  167756. jpeg_start_output (j_decompress_ptr cinfo, int scan_number)
  167757. {
  167758. if (cinfo->global_state != DSTATE_BUFIMAGE &&
  167759. cinfo->global_state != DSTATE_PRESCAN)
  167760. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167761. /* Limit scan number to valid range */
  167762. if (scan_number <= 0)
  167763. scan_number = 1;
  167764. if (cinfo->inputctl->eoi_reached &&
  167765. scan_number > cinfo->input_scan_number)
  167766. scan_number = cinfo->input_scan_number;
  167767. cinfo->output_scan_number = scan_number;
  167768. /* Perform any dummy output passes, and set up for the real pass */
  167769. return output_pass_setup(cinfo);
  167770. }
  167771. /*
  167772. * Finish up after an output pass in buffered-image mode.
  167773. *
  167774. * Returns FALSE if suspended. The return value need be inspected only if
  167775. * a suspending data source is used.
  167776. */
  167777. GLOBAL(boolean)
  167778. jpeg_finish_output (j_decompress_ptr cinfo)
  167779. {
  167780. if ((cinfo->global_state == DSTATE_SCANNING ||
  167781. cinfo->global_state == DSTATE_RAW_OK) && cinfo->buffered_image) {
  167782. /* Terminate this pass. */
  167783. /* We do not require the whole pass to have been completed. */
  167784. (*cinfo->master->finish_output_pass) (cinfo);
  167785. cinfo->global_state = DSTATE_BUFPOST;
  167786. } else if (cinfo->global_state != DSTATE_BUFPOST) {
  167787. /* BUFPOST = repeat call after a suspension, anything else is error */
  167788. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167789. }
  167790. /* Read markers looking for SOS or EOI */
  167791. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  167792. ! cinfo->inputctl->eoi_reached) {
  167793. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  167794. return FALSE; /* Suspend, come back later */
  167795. }
  167796. cinfo->global_state = DSTATE_BUFIMAGE;
  167797. return TRUE;
  167798. }
  167799. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  167800. /*** End of inlined file: jdapistd.c ***/
  167801. /*** Start of inlined file: jdapimin.c ***/
  167802. #define JPEG_INTERNALS
  167803. /*
  167804. * Initialization of a JPEG decompression object.
  167805. * The error manager must already be set up (in case memory manager fails).
  167806. */
  167807. GLOBAL(void)
  167808. jpeg_CreateDecompress (j_decompress_ptr cinfo, int version, size_t structsize)
  167809. {
  167810. int i;
  167811. /* Guard against version mismatches between library and caller. */
  167812. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  167813. if (version != JPEG_LIB_VERSION)
  167814. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  167815. if (structsize != SIZEOF(struct jpeg_decompress_struct))
  167816. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  167817. (int) SIZEOF(struct jpeg_decompress_struct), (int) structsize);
  167818. /* For debugging purposes, we zero the whole master structure.
  167819. * But the application has already set the err pointer, and may have set
  167820. * client_data, so we have to save and restore those fields.
  167821. * Note: if application hasn't set client_data, tools like Purify may
  167822. * complain here.
  167823. */
  167824. {
  167825. struct jpeg_error_mgr * err = cinfo->err;
  167826. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  167827. MEMZERO(cinfo, SIZEOF(struct jpeg_decompress_struct));
  167828. cinfo->err = err;
  167829. cinfo->client_data = client_data;
  167830. }
  167831. cinfo->is_decompressor = TRUE;
  167832. /* Initialize a memory manager instance for this object */
  167833. jinit_memory_mgr((j_common_ptr) cinfo);
  167834. /* Zero out pointers to permanent structures. */
  167835. cinfo->progress = NULL;
  167836. cinfo->src = NULL;
  167837. for (i = 0; i < NUM_QUANT_TBLS; i++)
  167838. cinfo->quant_tbl_ptrs[i] = NULL;
  167839. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  167840. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  167841. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  167842. }
  167843. /* Initialize marker processor so application can override methods
  167844. * for COM, APPn markers before calling jpeg_read_header.
  167845. */
  167846. cinfo->marker_list = NULL;
  167847. jinit_marker_reader(cinfo);
  167848. /* And initialize the overall input controller. */
  167849. jinit_input_controller(cinfo);
  167850. /* OK, I'm ready */
  167851. cinfo->global_state = DSTATE_START;
  167852. }
  167853. /*
  167854. * Destruction of a JPEG decompression object
  167855. */
  167856. GLOBAL(void)
  167857. jpeg_destroy_decompress (j_decompress_ptr cinfo)
  167858. {
  167859. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  167860. }
  167861. /*
  167862. * Abort processing of a JPEG decompression operation,
  167863. * but don't destroy the object itself.
  167864. */
  167865. GLOBAL(void)
  167866. jpeg_abort_decompress (j_decompress_ptr cinfo)
  167867. {
  167868. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  167869. }
  167870. /*
  167871. * Set default decompression parameters.
  167872. */
  167873. LOCAL(void)
  167874. default_decompress_parms (j_decompress_ptr cinfo)
  167875. {
  167876. /* Guess the input colorspace, and set output colorspace accordingly. */
  167877. /* (Wish JPEG committee had provided a real way to specify this...) */
  167878. /* Note application may override our guesses. */
  167879. switch (cinfo->num_components) {
  167880. case 1:
  167881. cinfo->jpeg_color_space = JCS_GRAYSCALE;
  167882. cinfo->out_color_space = JCS_GRAYSCALE;
  167883. break;
  167884. case 3:
  167885. if (cinfo->saw_JFIF_marker) {
  167886. cinfo->jpeg_color_space = JCS_YCbCr; /* JFIF implies YCbCr */
  167887. } else if (cinfo->saw_Adobe_marker) {
  167888. switch (cinfo->Adobe_transform) {
  167889. case 0:
  167890. cinfo->jpeg_color_space = JCS_RGB;
  167891. break;
  167892. case 1:
  167893. cinfo->jpeg_color_space = JCS_YCbCr;
  167894. break;
  167895. default:
  167896. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  167897. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  167898. break;
  167899. }
  167900. } else {
  167901. /* Saw no special markers, try to guess from the component IDs */
  167902. int cid0 = cinfo->comp_info[0].component_id;
  167903. int cid1 = cinfo->comp_info[1].component_id;
  167904. int cid2 = cinfo->comp_info[2].component_id;
  167905. if (cid0 == 1 && cid1 == 2 && cid2 == 3)
  167906. cinfo->jpeg_color_space = JCS_YCbCr; /* assume JFIF w/out marker */
  167907. else if (cid0 == 82 && cid1 == 71 && cid2 == 66)
  167908. cinfo->jpeg_color_space = JCS_RGB; /* ASCII 'R', 'G', 'B' */
  167909. else {
  167910. TRACEMS3(cinfo, 1, JTRC_UNKNOWN_IDS, cid0, cid1, cid2);
  167911. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  167912. }
  167913. }
  167914. /* Always guess RGB is proper output colorspace. */
  167915. cinfo->out_color_space = JCS_RGB;
  167916. break;
  167917. case 4:
  167918. if (cinfo->saw_Adobe_marker) {
  167919. switch (cinfo->Adobe_transform) {
  167920. case 0:
  167921. cinfo->jpeg_color_space = JCS_CMYK;
  167922. break;
  167923. case 2:
  167924. cinfo->jpeg_color_space = JCS_YCCK;
  167925. break;
  167926. default:
  167927. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  167928. cinfo->jpeg_color_space = JCS_YCCK; /* assume it's YCCK */
  167929. break;
  167930. }
  167931. } else {
  167932. /* No special markers, assume straight CMYK. */
  167933. cinfo->jpeg_color_space = JCS_CMYK;
  167934. }
  167935. cinfo->out_color_space = JCS_CMYK;
  167936. break;
  167937. default:
  167938. cinfo->jpeg_color_space = JCS_UNKNOWN;
  167939. cinfo->out_color_space = JCS_UNKNOWN;
  167940. break;
  167941. }
  167942. /* Set defaults for other decompression parameters. */
  167943. cinfo->scale_num = 1; /* 1:1 scaling */
  167944. cinfo->scale_denom = 1;
  167945. cinfo->output_gamma = 1.0;
  167946. cinfo->buffered_image = FALSE;
  167947. cinfo->raw_data_out = FALSE;
  167948. cinfo->dct_method = JDCT_DEFAULT;
  167949. cinfo->do_fancy_upsampling = TRUE;
  167950. cinfo->do_block_smoothing = TRUE;
  167951. cinfo->quantize_colors = FALSE;
  167952. /* We set these in case application only sets quantize_colors. */
  167953. cinfo->dither_mode = JDITHER_FS;
  167954. #ifdef QUANT_2PASS_SUPPORTED
  167955. cinfo->two_pass_quantize = TRUE;
  167956. #else
  167957. cinfo->two_pass_quantize = FALSE;
  167958. #endif
  167959. cinfo->desired_number_of_colors = 256;
  167960. cinfo->colormap = NULL;
  167961. /* Initialize for no mode change in buffered-image mode. */
  167962. cinfo->enable_1pass_quant = FALSE;
  167963. cinfo->enable_external_quant = FALSE;
  167964. cinfo->enable_2pass_quant = FALSE;
  167965. }
  167966. /*
  167967. * Decompression startup: read start of JPEG datastream to see what's there.
  167968. * Need only initialize JPEG object and supply a data source before calling.
  167969. *
  167970. * This routine will read as far as the first SOS marker (ie, actual start of
  167971. * compressed data), and will save all tables and parameters in the JPEG
  167972. * object. It will also initialize the decompression parameters to default
  167973. * values, and finally return JPEG_HEADER_OK. On return, the application may
  167974. * adjust the decompression parameters and then call jpeg_start_decompress.
  167975. * (Or, if the application only wanted to determine the image parameters,
  167976. * the data need not be decompressed. In that case, call jpeg_abort or
  167977. * jpeg_destroy to release any temporary space.)
  167978. * If an abbreviated (tables only) datastream is presented, the routine will
  167979. * return JPEG_HEADER_TABLES_ONLY upon reaching EOI. The application may then
  167980. * re-use the JPEG object to read the abbreviated image datastream(s).
  167981. * It is unnecessary (but OK) to call jpeg_abort in this case.
  167982. * The JPEG_SUSPENDED return code only occurs if the data source module
  167983. * requests suspension of the decompressor. In this case the application
  167984. * should load more source data and then re-call jpeg_read_header to resume
  167985. * processing.
  167986. * If a non-suspending data source is used and require_image is TRUE, then the
  167987. * return code need not be inspected since only JPEG_HEADER_OK is possible.
  167988. *
  167989. * This routine is now just a front end to jpeg_consume_input, with some
  167990. * extra error checking.
  167991. */
  167992. GLOBAL(int)
  167993. jpeg_read_header (j_decompress_ptr cinfo, boolean require_image)
  167994. {
  167995. int retcode;
  167996. if (cinfo->global_state != DSTATE_START &&
  167997. cinfo->global_state != DSTATE_INHEADER)
  167998. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167999. retcode = jpeg_consume_input(cinfo);
  168000. switch (retcode) {
  168001. case JPEG_REACHED_SOS:
  168002. retcode = JPEG_HEADER_OK;
  168003. break;
  168004. case JPEG_REACHED_EOI:
  168005. if (require_image) /* Complain if application wanted an image */
  168006. ERREXIT(cinfo, JERR_NO_IMAGE);
  168007. /* Reset to start state; it would be safer to require the application to
  168008. * call jpeg_abort, but we can't change it now for compatibility reasons.
  168009. * A side effect is to free any temporary memory (there shouldn't be any).
  168010. */
  168011. jpeg_abort((j_common_ptr) cinfo); /* sets state = DSTATE_START */
  168012. retcode = JPEG_HEADER_TABLES_ONLY;
  168013. break;
  168014. case JPEG_SUSPENDED:
  168015. /* no work */
  168016. break;
  168017. }
  168018. return retcode;
  168019. }
  168020. /*
  168021. * Consume data in advance of what the decompressor requires.
  168022. * This can be called at any time once the decompressor object has
  168023. * been created and a data source has been set up.
  168024. *
  168025. * This routine is essentially a state machine that handles a couple
  168026. * of critical state-transition actions, namely initial setup and
  168027. * transition from header scanning to ready-for-start_decompress.
  168028. * All the actual input is done via the input controller's consume_input
  168029. * method.
  168030. */
  168031. GLOBAL(int)
  168032. jpeg_consume_input (j_decompress_ptr cinfo)
  168033. {
  168034. int retcode = JPEG_SUSPENDED;
  168035. /* NB: every possible DSTATE value should be listed in this switch */
  168036. switch (cinfo->global_state) {
  168037. case DSTATE_START:
  168038. /* Start-of-datastream actions: reset appropriate modules */
  168039. (*cinfo->inputctl->reset_input_controller) (cinfo);
  168040. /* Initialize application's data source module */
  168041. (*cinfo->src->init_source) (cinfo);
  168042. cinfo->global_state = DSTATE_INHEADER;
  168043. /*FALLTHROUGH*/
  168044. case DSTATE_INHEADER:
  168045. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  168046. if (retcode == JPEG_REACHED_SOS) { /* Found SOS, prepare to decompress */
  168047. /* Set up default parameters based on header data */
  168048. default_decompress_parms(cinfo);
  168049. /* Set global state: ready for start_decompress */
  168050. cinfo->global_state = DSTATE_READY;
  168051. }
  168052. break;
  168053. case DSTATE_READY:
  168054. /* Can't advance past first SOS until start_decompress is called */
  168055. retcode = JPEG_REACHED_SOS;
  168056. break;
  168057. case DSTATE_PRELOAD:
  168058. case DSTATE_PRESCAN:
  168059. case DSTATE_SCANNING:
  168060. case DSTATE_RAW_OK:
  168061. case DSTATE_BUFIMAGE:
  168062. case DSTATE_BUFPOST:
  168063. case DSTATE_STOPPING:
  168064. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  168065. break;
  168066. default:
  168067. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168068. }
  168069. return retcode;
  168070. }
  168071. /*
  168072. * Have we finished reading the input file?
  168073. */
  168074. GLOBAL(boolean)
  168075. jpeg_input_complete (j_decompress_ptr cinfo)
  168076. {
  168077. /* Check for valid jpeg object */
  168078. if (cinfo->global_state < DSTATE_START ||
  168079. cinfo->global_state > DSTATE_STOPPING)
  168080. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168081. return cinfo->inputctl->eoi_reached;
  168082. }
  168083. /*
  168084. * Is there more than one scan?
  168085. */
  168086. GLOBAL(boolean)
  168087. jpeg_has_multiple_scans (j_decompress_ptr cinfo)
  168088. {
  168089. /* Only valid after jpeg_read_header completes */
  168090. if (cinfo->global_state < DSTATE_READY ||
  168091. cinfo->global_state > DSTATE_STOPPING)
  168092. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168093. return cinfo->inputctl->has_multiple_scans;
  168094. }
  168095. /*
  168096. * Finish JPEG decompression.
  168097. *
  168098. * This will normally just verify the file trailer and release temp storage.
  168099. *
  168100. * Returns FALSE if suspended. The return value need be inspected only if
  168101. * a suspending data source is used.
  168102. */
  168103. GLOBAL(boolean)
  168104. jpeg_finish_decompress (j_decompress_ptr cinfo)
  168105. {
  168106. if ((cinfo->global_state == DSTATE_SCANNING ||
  168107. cinfo->global_state == DSTATE_RAW_OK) && ! cinfo->buffered_image) {
  168108. /* Terminate final pass of non-buffered mode */
  168109. if (cinfo->output_scanline < cinfo->output_height)
  168110. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  168111. (*cinfo->master->finish_output_pass) (cinfo);
  168112. cinfo->global_state = DSTATE_STOPPING;
  168113. } else if (cinfo->global_state == DSTATE_BUFIMAGE) {
  168114. /* Finishing after a buffered-image operation */
  168115. cinfo->global_state = DSTATE_STOPPING;
  168116. } else if (cinfo->global_state != DSTATE_STOPPING) {
  168117. /* STOPPING = repeat call after a suspension, anything else is error */
  168118. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168119. }
  168120. /* Read until EOI */
  168121. while (! cinfo->inputctl->eoi_reached) {
  168122. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  168123. return FALSE; /* Suspend, come back later */
  168124. }
  168125. /* Do final cleanup */
  168126. (*cinfo->src->term_source) (cinfo);
  168127. /* We can use jpeg_abort to release memory and reset global_state */
  168128. jpeg_abort((j_common_ptr) cinfo);
  168129. return TRUE;
  168130. }
  168131. /*** End of inlined file: jdapimin.c ***/
  168132. /*** Start of inlined file: jdatasrc.c ***/
  168133. /* this is not a core library module, so it doesn't define JPEG_INTERNALS */
  168134. /*** Start of inlined file: jerror.h ***/
  168135. /*
  168136. * To define the enum list of message codes, include this file without
  168137. * defining macro JMESSAGE. To create a message string table, include it
  168138. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  168139. */
  168140. #ifndef JMESSAGE
  168141. #ifndef JERROR_H
  168142. /* First time through, define the enum list */
  168143. #define JMAKE_ENUM_LIST
  168144. #else
  168145. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  168146. #define JMESSAGE(code,string)
  168147. #endif /* JERROR_H */
  168148. #endif /* JMESSAGE */
  168149. #ifdef JMAKE_ENUM_LIST
  168150. typedef enum {
  168151. #define JMESSAGE(code,string) code ,
  168152. #endif /* JMAKE_ENUM_LIST */
  168153. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  168154. /* For maintenance convenience, list is alphabetical by message code name */
  168155. JMESSAGE(JERR_ARITH_NOTIMPL,
  168156. "Sorry, there are legal restrictions on arithmetic coding")
  168157. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  168158. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  168159. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  168160. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  168161. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  168162. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  168163. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  168164. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  168165. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  168166. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  168167. JMESSAGE(JERR_BAD_LIB_VERSION,
  168168. "Wrong JPEG library version: library is %d, caller expects %d")
  168169. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  168170. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  168171. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  168172. JMESSAGE(JERR_BAD_PROGRESSION,
  168173. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  168174. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  168175. "Invalid progressive parameters at scan script entry %d")
  168176. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  168177. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  168178. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  168179. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  168180. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  168181. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  168182. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  168183. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  168184. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  168185. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  168186. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  168187. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  168188. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  168189. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  168190. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  168191. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  168192. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  168193. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  168194. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  168195. JMESSAGE(JERR_FILE_READ, "Input file read error")
  168196. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  168197. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  168198. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  168199. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  168200. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  168201. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  168202. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  168203. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  168204. "Cannot transcode due to multiple use of quantization table %d")
  168205. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  168206. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  168207. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  168208. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  168209. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  168210. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  168211. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  168212. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  168213. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  168214. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  168215. JMESSAGE(JERR_QUANT_COMPONENTS,
  168216. "Cannot quantize more than %d color components")
  168217. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  168218. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  168219. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  168220. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  168221. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  168222. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  168223. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  168224. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  168225. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  168226. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  168227. JMESSAGE(JERR_TFILE_WRITE,
  168228. "Write failed on temporary file --- out of disk space?")
  168229. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  168230. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  168231. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  168232. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  168233. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  168234. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  168235. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  168236. JMESSAGE(JMSG_VERSION, JVERSION)
  168237. JMESSAGE(JTRC_16BIT_TABLES,
  168238. "Caution: quantization tables are too coarse for baseline JPEG")
  168239. JMESSAGE(JTRC_ADOBE,
  168240. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  168241. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  168242. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  168243. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  168244. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  168245. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  168246. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  168247. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  168248. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  168249. JMESSAGE(JTRC_EOI, "End Of Image")
  168250. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  168251. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  168252. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  168253. "Warning: thumbnail image size does not match data length %u")
  168254. JMESSAGE(JTRC_JFIF_EXTENSION,
  168255. "JFIF extension marker: type 0x%02x, length %u")
  168256. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  168257. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  168258. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  168259. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  168260. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  168261. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  168262. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  168263. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  168264. JMESSAGE(JTRC_RST, "RST%d")
  168265. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  168266. "Smoothing not supported with nonstandard sampling ratios")
  168267. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  168268. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  168269. JMESSAGE(JTRC_SOI, "Start of Image")
  168270. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  168271. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  168272. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  168273. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  168274. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  168275. JMESSAGE(JTRC_THUMB_JPEG,
  168276. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  168277. JMESSAGE(JTRC_THUMB_PALETTE,
  168278. "JFIF extension marker: palette thumbnail image, length %u")
  168279. JMESSAGE(JTRC_THUMB_RGB,
  168280. "JFIF extension marker: RGB thumbnail image, length %u")
  168281. JMESSAGE(JTRC_UNKNOWN_IDS,
  168282. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  168283. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  168284. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  168285. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  168286. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  168287. "Inconsistent progression sequence for component %d coefficient %d")
  168288. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  168289. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  168290. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  168291. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  168292. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  168293. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  168294. JMESSAGE(JWRN_MUST_RESYNC,
  168295. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  168296. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  168297. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  168298. #ifdef JMAKE_ENUM_LIST
  168299. JMSG_LASTMSGCODE
  168300. } J_MESSAGE_CODE;
  168301. #undef JMAKE_ENUM_LIST
  168302. #endif /* JMAKE_ENUM_LIST */
  168303. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  168304. #undef JMESSAGE
  168305. #ifndef JERROR_H
  168306. #define JERROR_H
  168307. /* Macros to simplify using the error and trace message stuff */
  168308. /* The first parameter is either type of cinfo pointer */
  168309. /* Fatal errors (print message and exit) */
  168310. #define ERREXIT(cinfo,code) \
  168311. ((cinfo)->err->msg_code = (code), \
  168312. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168313. #define ERREXIT1(cinfo,code,p1) \
  168314. ((cinfo)->err->msg_code = (code), \
  168315. (cinfo)->err->msg_parm.i[0] = (p1), \
  168316. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168317. #define ERREXIT2(cinfo,code,p1,p2) \
  168318. ((cinfo)->err->msg_code = (code), \
  168319. (cinfo)->err->msg_parm.i[0] = (p1), \
  168320. (cinfo)->err->msg_parm.i[1] = (p2), \
  168321. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168322. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  168323. ((cinfo)->err->msg_code = (code), \
  168324. (cinfo)->err->msg_parm.i[0] = (p1), \
  168325. (cinfo)->err->msg_parm.i[1] = (p2), \
  168326. (cinfo)->err->msg_parm.i[2] = (p3), \
  168327. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168328. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  168329. ((cinfo)->err->msg_code = (code), \
  168330. (cinfo)->err->msg_parm.i[0] = (p1), \
  168331. (cinfo)->err->msg_parm.i[1] = (p2), \
  168332. (cinfo)->err->msg_parm.i[2] = (p3), \
  168333. (cinfo)->err->msg_parm.i[3] = (p4), \
  168334. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168335. #define ERREXITS(cinfo,code,str) \
  168336. ((cinfo)->err->msg_code = (code), \
  168337. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  168338. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168339. #define MAKESTMT(stuff) do { stuff } while (0)
  168340. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  168341. #define WARNMS(cinfo,code) \
  168342. ((cinfo)->err->msg_code = (code), \
  168343. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  168344. #define WARNMS1(cinfo,code,p1) \
  168345. ((cinfo)->err->msg_code = (code), \
  168346. (cinfo)->err->msg_parm.i[0] = (p1), \
  168347. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  168348. #define WARNMS2(cinfo,code,p1,p2) \
  168349. ((cinfo)->err->msg_code = (code), \
  168350. (cinfo)->err->msg_parm.i[0] = (p1), \
  168351. (cinfo)->err->msg_parm.i[1] = (p2), \
  168352. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  168353. /* Informational/debugging messages */
  168354. #define TRACEMS(cinfo,lvl,code) \
  168355. ((cinfo)->err->msg_code = (code), \
  168356. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168357. #define TRACEMS1(cinfo,lvl,code,p1) \
  168358. ((cinfo)->err->msg_code = (code), \
  168359. (cinfo)->err->msg_parm.i[0] = (p1), \
  168360. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168361. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  168362. ((cinfo)->err->msg_code = (code), \
  168363. (cinfo)->err->msg_parm.i[0] = (p1), \
  168364. (cinfo)->err->msg_parm.i[1] = (p2), \
  168365. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168366. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  168367. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168368. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  168369. (cinfo)->err->msg_code = (code); \
  168370. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168371. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  168372. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168373. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  168374. (cinfo)->err->msg_code = (code); \
  168375. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168376. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  168377. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168378. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  168379. _mp[4] = (p5); \
  168380. (cinfo)->err->msg_code = (code); \
  168381. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168382. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  168383. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168384. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  168385. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  168386. (cinfo)->err->msg_code = (code); \
  168387. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168388. #define TRACEMSS(cinfo,lvl,code,str) \
  168389. ((cinfo)->err->msg_code = (code), \
  168390. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  168391. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168392. #endif /* JERROR_H */
  168393. /*** End of inlined file: jerror.h ***/
  168394. /* Expanded data source object for stdio input */
  168395. typedef struct {
  168396. struct jpeg_source_mgr pub; /* public fields */
  168397. FILE * infile; /* source stream */
  168398. JOCTET * buffer; /* start of buffer */
  168399. boolean start_of_file; /* have we gotten any data yet? */
  168400. } my_source_mgr;
  168401. typedef my_source_mgr * my_src_ptr;
  168402. #define INPUT_BUF_SIZE 4096 /* choose an efficiently fread'able size */
  168403. /*
  168404. * Initialize source --- called by jpeg_read_header
  168405. * before any data is actually read.
  168406. */
  168407. METHODDEF(void)
  168408. init_source (j_decompress_ptr cinfo)
  168409. {
  168410. my_src_ptr src = (my_src_ptr) cinfo->src;
  168411. /* We reset the empty-input-file flag for each image,
  168412. * but we don't clear the input buffer.
  168413. * This is correct behavior for reading a series of images from one source.
  168414. */
  168415. src->start_of_file = TRUE;
  168416. }
  168417. /*
  168418. * Fill the input buffer --- called whenever buffer is emptied.
  168419. *
  168420. * In typical applications, this should read fresh data into the buffer
  168421. * (ignoring the current state of next_input_byte & bytes_in_buffer),
  168422. * reset the pointer & count to the start of the buffer, and return TRUE
  168423. * indicating that the buffer has been reloaded. It is not necessary to
  168424. * fill the buffer entirely, only to obtain at least one more byte.
  168425. *
  168426. * There is no such thing as an EOF return. If the end of the file has been
  168427. * reached, the routine has a choice of ERREXIT() or inserting fake data into
  168428. * the buffer. In most cases, generating a warning message and inserting a
  168429. * fake EOI marker is the best course of action --- this will allow the
  168430. * decompressor to output however much of the image is there. However,
  168431. * the resulting error message is misleading if the real problem is an empty
  168432. * input file, so we handle that case specially.
  168433. *
  168434. * In applications that need to be able to suspend compression due to input
  168435. * not being available yet, a FALSE return indicates that no more data can be
  168436. * obtained right now, but more may be forthcoming later. In this situation,
  168437. * the decompressor will return to its caller (with an indication of the
  168438. * number of scanlines it has read, if any). The application should resume
  168439. * decompression after it has loaded more data into the input buffer. Note
  168440. * that there are substantial restrictions on the use of suspension --- see
  168441. * the documentation.
  168442. *
  168443. * When suspending, the decompressor will back up to a convenient restart point
  168444. * (typically the start of the current MCU). next_input_byte & bytes_in_buffer
  168445. * indicate where the restart point will be if the current call returns FALSE.
  168446. * Data beyond this point must be rescanned after resumption, so move it to
  168447. * the front of the buffer rather than discarding it.
  168448. */
  168449. METHODDEF(boolean)
  168450. fill_input_buffer (j_decompress_ptr cinfo)
  168451. {
  168452. my_src_ptr src = (my_src_ptr) cinfo->src;
  168453. size_t nbytes;
  168454. nbytes = JFREAD(src->infile, src->buffer, INPUT_BUF_SIZE);
  168455. if (nbytes <= 0) {
  168456. if (src->start_of_file) /* Treat empty input file as fatal error */
  168457. ERREXIT(cinfo, JERR_INPUT_EMPTY);
  168458. WARNMS(cinfo, JWRN_JPEG_EOF);
  168459. /* Insert a fake EOI marker */
  168460. src->buffer[0] = (JOCTET) 0xFF;
  168461. src->buffer[1] = (JOCTET) JPEG_EOI;
  168462. nbytes = 2;
  168463. }
  168464. src->pub.next_input_byte = src->buffer;
  168465. src->pub.bytes_in_buffer = nbytes;
  168466. src->start_of_file = FALSE;
  168467. return TRUE;
  168468. }
  168469. /*
  168470. * Skip data --- used to skip over a potentially large amount of
  168471. * uninteresting data (such as an APPn marker).
  168472. *
  168473. * Writers of suspendable-input applications must note that skip_input_data
  168474. * is not granted the right to give a suspension return. If the skip extends
  168475. * beyond the data currently in the buffer, the buffer can be marked empty so
  168476. * that the next read will cause a fill_input_buffer call that can suspend.
  168477. * Arranging for additional bytes to be discarded before reloading the input
  168478. * buffer is the application writer's problem.
  168479. */
  168480. METHODDEF(void)
  168481. skip_input_data (j_decompress_ptr cinfo, long num_bytes)
  168482. {
  168483. my_src_ptr src = (my_src_ptr) cinfo->src;
  168484. /* Just a dumb implementation for now. Could use fseek() except
  168485. * it doesn't work on pipes. Not clear that being smart is worth
  168486. * any trouble anyway --- large skips are infrequent.
  168487. */
  168488. if (num_bytes > 0) {
  168489. while (num_bytes > (long) src->pub.bytes_in_buffer) {
  168490. num_bytes -= (long) src->pub.bytes_in_buffer;
  168491. (void) fill_input_buffer(cinfo);
  168492. /* note we assume that fill_input_buffer will never return FALSE,
  168493. * so suspension need not be handled.
  168494. */
  168495. }
  168496. src->pub.next_input_byte += (size_t) num_bytes;
  168497. src->pub.bytes_in_buffer -= (size_t) num_bytes;
  168498. }
  168499. }
  168500. /*
  168501. * An additional method that can be provided by data source modules is the
  168502. * resync_to_restart method for error recovery in the presence of RST markers.
  168503. * For the moment, this source module just uses the default resync method
  168504. * provided by the JPEG library. That method assumes that no backtracking
  168505. * is possible.
  168506. */
  168507. /*
  168508. * Terminate source --- called by jpeg_finish_decompress
  168509. * after all data has been read. Often a no-op.
  168510. *
  168511. * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
  168512. * application must deal with any cleanup that should happen even
  168513. * for error exit.
  168514. */
  168515. METHODDEF(void)
  168516. term_source (j_decompress_ptr)
  168517. {
  168518. /* no work necessary here */
  168519. }
  168520. /*
  168521. * Prepare for input from a stdio stream.
  168522. * The caller must have already opened the stream, and is responsible
  168523. * for closing it after finishing decompression.
  168524. */
  168525. GLOBAL(void)
  168526. jpeg_stdio_src (j_decompress_ptr cinfo, FILE * infile)
  168527. {
  168528. my_src_ptr src;
  168529. /* The source object and input buffer are made permanent so that a series
  168530. * of JPEG images can be read from the same file by calling jpeg_stdio_src
  168531. * only before the first one. (If we discarded the buffer at the end of
  168532. * one image, we'd likely lose the start of the next one.)
  168533. * This makes it unsafe to use this manager and a different source
  168534. * manager serially with the same JPEG object. Caveat programmer.
  168535. */
  168536. if (cinfo->src == NULL) { /* first time for this JPEG object? */
  168537. cinfo->src = (struct jpeg_source_mgr *)
  168538. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  168539. SIZEOF(my_source_mgr));
  168540. src = (my_src_ptr) cinfo->src;
  168541. src->buffer = (JOCTET *)
  168542. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  168543. INPUT_BUF_SIZE * SIZEOF(JOCTET));
  168544. }
  168545. src = (my_src_ptr) cinfo->src;
  168546. src->pub.init_source = init_source;
  168547. src->pub.fill_input_buffer = fill_input_buffer;
  168548. src->pub.skip_input_data = skip_input_data;
  168549. src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */
  168550. src->pub.term_source = term_source;
  168551. src->infile = infile;
  168552. src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */
  168553. src->pub.next_input_byte = NULL; /* until buffer loaded */
  168554. }
  168555. /*** End of inlined file: jdatasrc.c ***/
  168556. /*** Start of inlined file: jdcoefct.c ***/
  168557. #define JPEG_INTERNALS
  168558. /* Block smoothing is only applicable for progressive JPEG, so: */
  168559. #ifndef D_PROGRESSIVE_SUPPORTED
  168560. #undef BLOCK_SMOOTHING_SUPPORTED
  168561. #endif
  168562. /* Private buffer controller object */
  168563. typedef struct {
  168564. struct jpeg_d_coef_controller pub; /* public fields */
  168565. /* These variables keep track of the current location of the input side. */
  168566. /* cinfo->input_iMCU_row is also used for this. */
  168567. JDIMENSION MCU_ctr; /* counts MCUs processed in current row */
  168568. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  168569. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  168570. /* The output side's location is represented by cinfo->output_iMCU_row. */
  168571. /* In single-pass modes, it's sufficient to buffer just one MCU.
  168572. * We allocate a workspace of D_MAX_BLOCKS_IN_MCU coefficient blocks,
  168573. * and let the entropy decoder write into that workspace each time.
  168574. * (On 80x86, the workspace is FAR even though it's not really very big;
  168575. * this is to keep the module interfaces unchanged when a large coefficient
  168576. * buffer is necessary.)
  168577. * In multi-pass modes, this array points to the current MCU's blocks
  168578. * within the virtual arrays; it is used only by the input side.
  168579. */
  168580. JBLOCKROW MCU_buffer[D_MAX_BLOCKS_IN_MCU];
  168581. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168582. /* In multi-pass modes, we need a virtual block array for each component. */
  168583. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  168584. #endif
  168585. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168586. /* When doing block smoothing, we latch coefficient Al values here */
  168587. int * coef_bits_latch;
  168588. #define SAVED_COEFS 6 /* we save coef_bits[0..5] */
  168589. #endif
  168590. } my_coef_controller3;
  168591. typedef my_coef_controller3 * my_coef_ptr3;
  168592. /* Forward declarations */
  168593. METHODDEF(int) decompress_onepass
  168594. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  168595. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168596. METHODDEF(int) decompress_data
  168597. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  168598. #endif
  168599. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168600. LOCAL(boolean) smoothing_ok JPP((j_decompress_ptr cinfo));
  168601. METHODDEF(int) decompress_smooth_data
  168602. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  168603. #endif
  168604. LOCAL(void)
  168605. start_iMCU_row3 (j_decompress_ptr cinfo)
  168606. /* Reset within-iMCU-row counters for a new row (input side) */
  168607. {
  168608. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168609. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  168610. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  168611. * But at the bottom of the image, process only what's left.
  168612. */
  168613. if (cinfo->comps_in_scan > 1) {
  168614. coef->MCU_rows_per_iMCU_row = 1;
  168615. } else {
  168616. if (cinfo->input_iMCU_row < (cinfo->total_iMCU_rows-1))
  168617. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  168618. else
  168619. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  168620. }
  168621. coef->MCU_ctr = 0;
  168622. coef->MCU_vert_offset = 0;
  168623. }
  168624. /*
  168625. * Initialize for an input processing pass.
  168626. */
  168627. METHODDEF(void)
  168628. start_input_pass (j_decompress_ptr cinfo)
  168629. {
  168630. cinfo->input_iMCU_row = 0;
  168631. start_iMCU_row3(cinfo);
  168632. }
  168633. /*
  168634. * Initialize for an output processing pass.
  168635. */
  168636. METHODDEF(void)
  168637. start_output_pass (j_decompress_ptr cinfo)
  168638. {
  168639. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168640. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168641. /* If multipass, check to see whether to use block smoothing on this pass */
  168642. if (coef->pub.coef_arrays != NULL) {
  168643. if (cinfo->do_block_smoothing && smoothing_ok(cinfo))
  168644. coef->pub.decompress_data = decompress_smooth_data;
  168645. else
  168646. coef->pub.decompress_data = decompress_data;
  168647. }
  168648. #endif
  168649. cinfo->output_iMCU_row = 0;
  168650. }
  168651. /*
  168652. * Decompress and return some data in the single-pass case.
  168653. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  168654. * Input and output must run in lockstep since we have only a one-MCU buffer.
  168655. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168656. *
  168657. * NB: output_buf contains a plane for each component in image,
  168658. * which we index according to the component's SOF position.
  168659. */
  168660. METHODDEF(int)
  168661. decompress_onepass (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  168662. {
  168663. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168664. JDIMENSION MCU_col_num; /* index of current MCU within row */
  168665. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  168666. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168667. int blkn, ci, xindex, yindex, yoffset, useful_width;
  168668. JSAMPARRAY output_ptr;
  168669. JDIMENSION start_col, output_col;
  168670. jpeg_component_info *compptr;
  168671. inverse_DCT_method_ptr inverse_DCT;
  168672. /* Loop to process as much as one whole iMCU row */
  168673. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  168674. yoffset++) {
  168675. for (MCU_col_num = coef->MCU_ctr; MCU_col_num <= last_MCU_col;
  168676. MCU_col_num++) {
  168677. /* Try to fetch an MCU. Entropy decoder expects buffer to be zeroed. */
  168678. jzero_far((void FAR *) coef->MCU_buffer[0],
  168679. (size_t) (cinfo->blocks_in_MCU * SIZEOF(JBLOCK)));
  168680. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  168681. /* Suspension forced; update state counters and exit */
  168682. coef->MCU_vert_offset = yoffset;
  168683. coef->MCU_ctr = MCU_col_num;
  168684. return JPEG_SUSPENDED;
  168685. }
  168686. /* Determine where data should go in output_buf and do the IDCT thing.
  168687. * We skip dummy blocks at the right and bottom edges (but blkn gets
  168688. * incremented past them!). Note the inner loop relies on having
  168689. * allocated the MCU_buffer[] blocks sequentially.
  168690. */
  168691. blkn = 0; /* index of current DCT block within MCU */
  168692. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168693. compptr = cinfo->cur_comp_info[ci];
  168694. /* Don't bother to IDCT an uninteresting component. */
  168695. if (! compptr->component_needed) {
  168696. blkn += compptr->MCU_blocks;
  168697. continue;
  168698. }
  168699. inverse_DCT = cinfo->idct->inverse_DCT[compptr->component_index];
  168700. useful_width = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  168701. : compptr->last_col_width;
  168702. output_ptr = output_buf[compptr->component_index] +
  168703. yoffset * compptr->DCT_scaled_size;
  168704. start_col = MCU_col_num * compptr->MCU_sample_width;
  168705. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  168706. if (cinfo->input_iMCU_row < last_iMCU_row ||
  168707. yoffset+yindex < compptr->last_row_height) {
  168708. output_col = start_col;
  168709. for (xindex = 0; xindex < useful_width; xindex++) {
  168710. (*inverse_DCT) (cinfo, compptr,
  168711. (JCOEFPTR) coef->MCU_buffer[blkn+xindex],
  168712. output_ptr, output_col);
  168713. output_col += compptr->DCT_scaled_size;
  168714. }
  168715. }
  168716. blkn += compptr->MCU_width;
  168717. output_ptr += compptr->DCT_scaled_size;
  168718. }
  168719. }
  168720. }
  168721. /* Completed an MCU row, but perhaps not an iMCU row */
  168722. coef->MCU_ctr = 0;
  168723. }
  168724. /* Completed the iMCU row, advance counters for next one */
  168725. cinfo->output_iMCU_row++;
  168726. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  168727. start_iMCU_row3(cinfo);
  168728. return JPEG_ROW_COMPLETED;
  168729. }
  168730. /* Completed the scan */
  168731. (*cinfo->inputctl->finish_input_pass) (cinfo);
  168732. return JPEG_SCAN_COMPLETED;
  168733. }
  168734. /*
  168735. * Dummy consume-input routine for single-pass operation.
  168736. */
  168737. METHODDEF(int)
  168738. dummy_consume_data (j_decompress_ptr)
  168739. {
  168740. return JPEG_SUSPENDED; /* Always indicate nothing was done */
  168741. }
  168742. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168743. /*
  168744. * Consume input data and store it in the full-image coefficient buffer.
  168745. * We read as much as one fully interleaved MCU row ("iMCU" row) per call,
  168746. * ie, v_samp_factor block rows for each component in the scan.
  168747. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168748. */
  168749. METHODDEF(int)
  168750. consume_data (j_decompress_ptr cinfo)
  168751. {
  168752. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168753. JDIMENSION MCU_col_num; /* index of current MCU within row */
  168754. int blkn, ci, xindex, yindex, yoffset;
  168755. JDIMENSION start_col;
  168756. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  168757. JBLOCKROW buffer_ptr;
  168758. jpeg_component_info *compptr;
  168759. /* Align the virtual buffers for the components used in this scan. */
  168760. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168761. compptr = cinfo->cur_comp_info[ci];
  168762. buffer[ci] = (*cinfo->mem->access_virt_barray)
  168763. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  168764. cinfo->input_iMCU_row * compptr->v_samp_factor,
  168765. (JDIMENSION) compptr->v_samp_factor, TRUE);
  168766. /* Note: entropy decoder expects buffer to be zeroed,
  168767. * but this is handled automatically by the memory manager
  168768. * because we requested a pre-zeroed array.
  168769. */
  168770. }
  168771. /* Loop to process one whole iMCU row */
  168772. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  168773. yoffset++) {
  168774. for (MCU_col_num = coef->MCU_ctr; MCU_col_num < cinfo->MCUs_per_row;
  168775. MCU_col_num++) {
  168776. /* Construct list of pointers to DCT blocks belonging to this MCU */
  168777. blkn = 0; /* index of current DCT block within MCU */
  168778. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168779. compptr = cinfo->cur_comp_info[ci];
  168780. start_col = MCU_col_num * compptr->MCU_width;
  168781. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  168782. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  168783. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  168784. coef->MCU_buffer[blkn++] = buffer_ptr++;
  168785. }
  168786. }
  168787. }
  168788. /* Try to fetch the MCU. */
  168789. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  168790. /* Suspension forced; update state counters and exit */
  168791. coef->MCU_vert_offset = yoffset;
  168792. coef->MCU_ctr = MCU_col_num;
  168793. return JPEG_SUSPENDED;
  168794. }
  168795. }
  168796. /* Completed an MCU row, but perhaps not an iMCU row */
  168797. coef->MCU_ctr = 0;
  168798. }
  168799. /* Completed the iMCU row, advance counters for next one */
  168800. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  168801. start_iMCU_row3(cinfo);
  168802. return JPEG_ROW_COMPLETED;
  168803. }
  168804. /* Completed the scan */
  168805. (*cinfo->inputctl->finish_input_pass) (cinfo);
  168806. return JPEG_SCAN_COMPLETED;
  168807. }
  168808. /*
  168809. * Decompress and return some data in the multi-pass case.
  168810. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  168811. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168812. *
  168813. * NB: output_buf contains a plane for each component in image.
  168814. */
  168815. METHODDEF(int)
  168816. decompress_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  168817. {
  168818. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168819. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168820. JDIMENSION block_num;
  168821. int ci, block_row, block_rows;
  168822. JBLOCKARRAY buffer;
  168823. JBLOCKROW buffer_ptr;
  168824. JSAMPARRAY output_ptr;
  168825. JDIMENSION output_col;
  168826. jpeg_component_info *compptr;
  168827. inverse_DCT_method_ptr inverse_DCT;
  168828. /* Force some input to be done if we are getting ahead of the input. */
  168829. while (cinfo->input_scan_number < cinfo->output_scan_number ||
  168830. (cinfo->input_scan_number == cinfo->output_scan_number &&
  168831. cinfo->input_iMCU_row <= cinfo->output_iMCU_row)) {
  168832. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  168833. return JPEG_SUSPENDED;
  168834. }
  168835. /* OK, output from the virtual arrays. */
  168836. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168837. ci++, compptr++) {
  168838. /* Don't bother to IDCT an uninteresting component. */
  168839. if (! compptr->component_needed)
  168840. continue;
  168841. /* Align the virtual buffer for this component. */
  168842. buffer = (*cinfo->mem->access_virt_barray)
  168843. ((j_common_ptr) cinfo, coef->whole_image[ci],
  168844. cinfo->output_iMCU_row * compptr->v_samp_factor,
  168845. (JDIMENSION) compptr->v_samp_factor, FALSE);
  168846. /* Count non-dummy DCT block rows in this iMCU row. */
  168847. if (cinfo->output_iMCU_row < last_iMCU_row)
  168848. block_rows = compptr->v_samp_factor;
  168849. else {
  168850. /* NB: can't use last_row_height here; it is input-side-dependent! */
  168851. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  168852. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  168853. }
  168854. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  168855. output_ptr = output_buf[ci];
  168856. /* Loop over all DCT blocks to be processed. */
  168857. for (block_row = 0; block_row < block_rows; block_row++) {
  168858. buffer_ptr = buffer[block_row];
  168859. output_col = 0;
  168860. for (block_num = 0; block_num < compptr->width_in_blocks; block_num++) {
  168861. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) buffer_ptr,
  168862. output_ptr, output_col);
  168863. buffer_ptr++;
  168864. output_col += compptr->DCT_scaled_size;
  168865. }
  168866. output_ptr += compptr->DCT_scaled_size;
  168867. }
  168868. }
  168869. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  168870. return JPEG_ROW_COMPLETED;
  168871. return JPEG_SCAN_COMPLETED;
  168872. }
  168873. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  168874. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168875. /*
  168876. * This code applies interblock smoothing as described by section K.8
  168877. * of the JPEG standard: the first 5 AC coefficients are estimated from
  168878. * the DC values of a DCT block and its 8 neighboring blocks.
  168879. * We apply smoothing only for progressive JPEG decoding, and only if
  168880. * the coefficients it can estimate are not yet known to full precision.
  168881. */
  168882. /* Natural-order array positions of the first 5 zigzag-order coefficients */
  168883. #define Q01_POS 1
  168884. #define Q10_POS 8
  168885. #define Q20_POS 16
  168886. #define Q11_POS 9
  168887. #define Q02_POS 2
  168888. /*
  168889. * Determine whether block smoothing is applicable and safe.
  168890. * We also latch the current states of the coef_bits[] entries for the
  168891. * AC coefficients; otherwise, if the input side of the decompressor
  168892. * advances into a new scan, we might think the coefficients are known
  168893. * more accurately than they really are.
  168894. */
  168895. LOCAL(boolean)
  168896. smoothing_ok (j_decompress_ptr cinfo)
  168897. {
  168898. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168899. boolean smoothing_useful = FALSE;
  168900. int ci, coefi;
  168901. jpeg_component_info *compptr;
  168902. JQUANT_TBL * qtable;
  168903. int * coef_bits;
  168904. int * coef_bits_latch;
  168905. if (! cinfo->progressive_mode || cinfo->coef_bits == NULL)
  168906. return FALSE;
  168907. /* Allocate latch area if not already done */
  168908. if (coef->coef_bits_latch == NULL)
  168909. coef->coef_bits_latch = (int *)
  168910. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168911. cinfo->num_components *
  168912. (SAVED_COEFS * SIZEOF(int)));
  168913. coef_bits_latch = coef->coef_bits_latch;
  168914. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168915. ci++, compptr++) {
  168916. /* All components' quantization values must already be latched. */
  168917. if ((qtable = compptr->quant_table) == NULL)
  168918. return FALSE;
  168919. /* Verify DC & first 5 AC quantizers are nonzero to avoid zero-divide. */
  168920. if (qtable->quantval[0] == 0 ||
  168921. qtable->quantval[Q01_POS] == 0 ||
  168922. qtable->quantval[Q10_POS] == 0 ||
  168923. qtable->quantval[Q20_POS] == 0 ||
  168924. qtable->quantval[Q11_POS] == 0 ||
  168925. qtable->quantval[Q02_POS] == 0)
  168926. return FALSE;
  168927. /* DC values must be at least partly known for all components. */
  168928. coef_bits = cinfo->coef_bits[ci];
  168929. if (coef_bits[0] < 0)
  168930. return FALSE;
  168931. /* Block smoothing is helpful if some AC coefficients remain inaccurate. */
  168932. for (coefi = 1; coefi <= 5; coefi++) {
  168933. coef_bits_latch[coefi] = coef_bits[coefi];
  168934. if (coef_bits[coefi] != 0)
  168935. smoothing_useful = TRUE;
  168936. }
  168937. coef_bits_latch += SAVED_COEFS;
  168938. }
  168939. return smoothing_useful;
  168940. }
  168941. /*
  168942. * Variant of decompress_data for use when doing block smoothing.
  168943. */
  168944. METHODDEF(int)
  168945. decompress_smooth_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  168946. {
  168947. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168948. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168949. JDIMENSION block_num, last_block_column;
  168950. int ci, block_row, block_rows, access_rows;
  168951. JBLOCKARRAY buffer;
  168952. JBLOCKROW buffer_ptr, prev_block_row, next_block_row;
  168953. JSAMPARRAY output_ptr;
  168954. JDIMENSION output_col;
  168955. jpeg_component_info *compptr;
  168956. inverse_DCT_method_ptr inverse_DCT;
  168957. boolean first_row, last_row;
  168958. JBLOCK workspace;
  168959. int *coef_bits;
  168960. JQUANT_TBL *quanttbl;
  168961. INT32 Q00,Q01,Q02,Q10,Q11,Q20, num;
  168962. int DC1,DC2,DC3,DC4,DC5,DC6,DC7,DC8,DC9;
  168963. int Al, pred;
  168964. /* Force some input to be done if we are getting ahead of the input. */
  168965. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  168966. ! cinfo->inputctl->eoi_reached) {
  168967. if (cinfo->input_scan_number == cinfo->output_scan_number) {
  168968. /* If input is working on current scan, we ordinarily want it to
  168969. * have completed the current row. But if input scan is DC,
  168970. * we want it to keep one row ahead so that next block row's DC
  168971. * values are up to date.
  168972. */
  168973. JDIMENSION delta = (cinfo->Ss == 0) ? 1 : 0;
  168974. if (cinfo->input_iMCU_row > cinfo->output_iMCU_row+delta)
  168975. break;
  168976. }
  168977. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  168978. return JPEG_SUSPENDED;
  168979. }
  168980. /* OK, output from the virtual arrays. */
  168981. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168982. ci++, compptr++) {
  168983. /* Don't bother to IDCT an uninteresting component. */
  168984. if (! compptr->component_needed)
  168985. continue;
  168986. /* Count non-dummy DCT block rows in this iMCU row. */
  168987. if (cinfo->output_iMCU_row < last_iMCU_row) {
  168988. block_rows = compptr->v_samp_factor;
  168989. access_rows = block_rows * 2; /* this and next iMCU row */
  168990. last_row = FALSE;
  168991. } else {
  168992. /* NB: can't use last_row_height here; it is input-side-dependent! */
  168993. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  168994. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  168995. access_rows = block_rows; /* this iMCU row only */
  168996. last_row = TRUE;
  168997. }
  168998. /* Align the virtual buffer for this component. */
  168999. if (cinfo->output_iMCU_row > 0) {
  169000. access_rows += compptr->v_samp_factor; /* prior iMCU row too */
  169001. buffer = (*cinfo->mem->access_virt_barray)
  169002. ((j_common_ptr) cinfo, coef->whole_image[ci],
  169003. (cinfo->output_iMCU_row - 1) * compptr->v_samp_factor,
  169004. (JDIMENSION) access_rows, FALSE);
  169005. buffer += compptr->v_samp_factor; /* point to current iMCU row */
  169006. first_row = FALSE;
  169007. } else {
  169008. buffer = (*cinfo->mem->access_virt_barray)
  169009. ((j_common_ptr) cinfo, coef->whole_image[ci],
  169010. (JDIMENSION) 0, (JDIMENSION) access_rows, FALSE);
  169011. first_row = TRUE;
  169012. }
  169013. /* Fetch component-dependent info */
  169014. coef_bits = coef->coef_bits_latch + (ci * SAVED_COEFS);
  169015. quanttbl = compptr->quant_table;
  169016. Q00 = quanttbl->quantval[0];
  169017. Q01 = quanttbl->quantval[Q01_POS];
  169018. Q10 = quanttbl->quantval[Q10_POS];
  169019. Q20 = quanttbl->quantval[Q20_POS];
  169020. Q11 = quanttbl->quantval[Q11_POS];
  169021. Q02 = quanttbl->quantval[Q02_POS];
  169022. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  169023. output_ptr = output_buf[ci];
  169024. /* Loop over all DCT blocks to be processed. */
  169025. for (block_row = 0; block_row < block_rows; block_row++) {
  169026. buffer_ptr = buffer[block_row];
  169027. if (first_row && block_row == 0)
  169028. prev_block_row = buffer_ptr;
  169029. else
  169030. prev_block_row = buffer[block_row-1];
  169031. if (last_row && block_row == block_rows-1)
  169032. next_block_row = buffer_ptr;
  169033. else
  169034. next_block_row = buffer[block_row+1];
  169035. /* We fetch the surrounding DC values using a sliding-register approach.
  169036. * Initialize all nine here so as to do the right thing on narrow pics.
  169037. */
  169038. DC1 = DC2 = DC3 = (int) prev_block_row[0][0];
  169039. DC4 = DC5 = DC6 = (int) buffer_ptr[0][0];
  169040. DC7 = DC8 = DC9 = (int) next_block_row[0][0];
  169041. output_col = 0;
  169042. last_block_column = compptr->width_in_blocks - 1;
  169043. for (block_num = 0; block_num <= last_block_column; block_num++) {
  169044. /* Fetch current DCT block into workspace so we can modify it. */
  169045. jcopy_block_row(buffer_ptr, (JBLOCKROW) workspace, (JDIMENSION) 1);
  169046. /* Update DC values */
  169047. if (block_num < last_block_column) {
  169048. DC3 = (int) prev_block_row[1][0];
  169049. DC6 = (int) buffer_ptr[1][0];
  169050. DC9 = (int) next_block_row[1][0];
  169051. }
  169052. /* Compute coefficient estimates per K.8.
  169053. * An estimate is applied only if coefficient is still zero,
  169054. * and is not known to be fully accurate.
  169055. */
  169056. /* AC01 */
  169057. if ((Al=coef_bits[1]) != 0 && workspace[1] == 0) {
  169058. num = 36 * Q00 * (DC4 - DC6);
  169059. if (num >= 0) {
  169060. pred = (int) (((Q01<<7) + num) / (Q01<<8));
  169061. if (Al > 0 && pred >= (1<<Al))
  169062. pred = (1<<Al)-1;
  169063. } else {
  169064. pred = (int) (((Q01<<7) - num) / (Q01<<8));
  169065. if (Al > 0 && pred >= (1<<Al))
  169066. pred = (1<<Al)-1;
  169067. pred = -pred;
  169068. }
  169069. workspace[1] = (JCOEF) pred;
  169070. }
  169071. /* AC10 */
  169072. if ((Al=coef_bits[2]) != 0 && workspace[8] == 0) {
  169073. num = 36 * Q00 * (DC2 - DC8);
  169074. if (num >= 0) {
  169075. pred = (int) (((Q10<<7) + num) / (Q10<<8));
  169076. if (Al > 0 && pred >= (1<<Al))
  169077. pred = (1<<Al)-1;
  169078. } else {
  169079. pred = (int) (((Q10<<7) - num) / (Q10<<8));
  169080. if (Al > 0 && pred >= (1<<Al))
  169081. pred = (1<<Al)-1;
  169082. pred = -pred;
  169083. }
  169084. workspace[8] = (JCOEF) pred;
  169085. }
  169086. /* AC20 */
  169087. if ((Al=coef_bits[3]) != 0 && workspace[16] == 0) {
  169088. num = 9 * Q00 * (DC2 + DC8 - 2*DC5);
  169089. if (num >= 0) {
  169090. pred = (int) (((Q20<<7) + num) / (Q20<<8));
  169091. if (Al > 0 && pred >= (1<<Al))
  169092. pred = (1<<Al)-1;
  169093. } else {
  169094. pred = (int) (((Q20<<7) - num) / (Q20<<8));
  169095. if (Al > 0 && pred >= (1<<Al))
  169096. pred = (1<<Al)-1;
  169097. pred = -pred;
  169098. }
  169099. workspace[16] = (JCOEF) pred;
  169100. }
  169101. /* AC11 */
  169102. if ((Al=coef_bits[4]) != 0 && workspace[9] == 0) {
  169103. num = 5 * Q00 * (DC1 - DC3 - DC7 + DC9);
  169104. if (num >= 0) {
  169105. pred = (int) (((Q11<<7) + num) / (Q11<<8));
  169106. if (Al > 0 && pred >= (1<<Al))
  169107. pred = (1<<Al)-1;
  169108. } else {
  169109. pred = (int) (((Q11<<7) - num) / (Q11<<8));
  169110. if (Al > 0 && pred >= (1<<Al))
  169111. pred = (1<<Al)-1;
  169112. pred = -pred;
  169113. }
  169114. workspace[9] = (JCOEF) pred;
  169115. }
  169116. /* AC02 */
  169117. if ((Al=coef_bits[5]) != 0 && workspace[2] == 0) {
  169118. num = 9 * Q00 * (DC4 + DC6 - 2*DC5);
  169119. if (num >= 0) {
  169120. pred = (int) (((Q02<<7) + num) / (Q02<<8));
  169121. if (Al > 0 && pred >= (1<<Al))
  169122. pred = (1<<Al)-1;
  169123. } else {
  169124. pred = (int) (((Q02<<7) - num) / (Q02<<8));
  169125. if (Al > 0 && pred >= (1<<Al))
  169126. pred = (1<<Al)-1;
  169127. pred = -pred;
  169128. }
  169129. workspace[2] = (JCOEF) pred;
  169130. }
  169131. /* OK, do the IDCT */
  169132. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) workspace,
  169133. output_ptr, output_col);
  169134. /* Advance for next column */
  169135. DC1 = DC2; DC2 = DC3;
  169136. DC4 = DC5; DC5 = DC6;
  169137. DC7 = DC8; DC8 = DC9;
  169138. buffer_ptr++, prev_block_row++, next_block_row++;
  169139. output_col += compptr->DCT_scaled_size;
  169140. }
  169141. output_ptr += compptr->DCT_scaled_size;
  169142. }
  169143. }
  169144. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  169145. return JPEG_ROW_COMPLETED;
  169146. return JPEG_SCAN_COMPLETED;
  169147. }
  169148. #endif /* BLOCK_SMOOTHING_SUPPORTED */
  169149. /*
  169150. * Initialize coefficient buffer controller.
  169151. */
  169152. GLOBAL(void)
  169153. jinit_d_coef_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  169154. {
  169155. my_coef_ptr3 coef;
  169156. coef = (my_coef_ptr3)
  169157. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169158. SIZEOF(my_coef_controller3));
  169159. cinfo->coef = (struct jpeg_d_coef_controller *) coef;
  169160. coef->pub.start_input_pass = start_input_pass;
  169161. coef->pub.start_output_pass = start_output_pass;
  169162. #ifdef BLOCK_SMOOTHING_SUPPORTED
  169163. coef->coef_bits_latch = NULL;
  169164. #endif
  169165. /* Create the coefficient buffer. */
  169166. if (need_full_buffer) {
  169167. #ifdef D_MULTISCAN_FILES_SUPPORTED
  169168. /* Allocate a full-image virtual array for each component, */
  169169. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  169170. /* Note we ask for a pre-zeroed array. */
  169171. int ci, access_rows;
  169172. jpeg_component_info *compptr;
  169173. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169174. ci++, compptr++) {
  169175. access_rows = compptr->v_samp_factor;
  169176. #ifdef BLOCK_SMOOTHING_SUPPORTED
  169177. /* If block smoothing could be used, need a bigger window */
  169178. if (cinfo->progressive_mode)
  169179. access_rows *= 3;
  169180. #endif
  169181. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  169182. ((j_common_ptr) cinfo, JPOOL_IMAGE, TRUE,
  169183. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  169184. (long) compptr->h_samp_factor),
  169185. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  169186. (long) compptr->v_samp_factor),
  169187. (JDIMENSION) access_rows);
  169188. }
  169189. coef->pub.consume_data = consume_data;
  169190. coef->pub.decompress_data = decompress_data;
  169191. coef->pub.coef_arrays = coef->whole_image; /* link to virtual arrays */
  169192. #else
  169193. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169194. #endif
  169195. } else {
  169196. /* We only need a single-MCU buffer. */
  169197. JBLOCKROW buffer;
  169198. int i;
  169199. buffer = (JBLOCKROW)
  169200. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169201. D_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  169202. for (i = 0; i < D_MAX_BLOCKS_IN_MCU; i++) {
  169203. coef->MCU_buffer[i] = buffer + i;
  169204. }
  169205. coef->pub.consume_data = dummy_consume_data;
  169206. coef->pub.decompress_data = decompress_onepass;
  169207. coef->pub.coef_arrays = NULL; /* flag for no virtual arrays */
  169208. }
  169209. }
  169210. /*** End of inlined file: jdcoefct.c ***/
  169211. #undef FIX
  169212. /*** Start of inlined file: jdcolor.c ***/
  169213. #define JPEG_INTERNALS
  169214. /* Private subobject */
  169215. typedef struct {
  169216. struct jpeg_color_deconverter pub; /* public fields */
  169217. /* Private state for YCC->RGB conversion */
  169218. int * Cr_r_tab; /* => table for Cr to R conversion */
  169219. int * Cb_b_tab; /* => table for Cb to B conversion */
  169220. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  169221. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  169222. } my_color_deconverter2;
  169223. typedef my_color_deconverter2 * my_cconvert_ptr2;
  169224. /**************** YCbCr -> RGB conversion: most common case **************/
  169225. /*
  169226. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  169227. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  169228. * The conversion equations to be implemented are therefore
  169229. * R = Y + 1.40200 * Cr
  169230. * G = Y - 0.34414 * Cb - 0.71414 * Cr
  169231. * B = Y + 1.77200 * Cb
  169232. * where Cb and Cr represent the incoming values less CENTERJSAMPLE.
  169233. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  169234. *
  169235. * To avoid floating-point arithmetic, we represent the fractional constants
  169236. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  169237. * the products by 2^16, with appropriate rounding, to get the correct answer.
  169238. * Notice that Y, being an integral input, does not contribute any fraction
  169239. * so it need not participate in the rounding.
  169240. *
  169241. * For even more speed, we avoid doing any multiplications in the inner loop
  169242. * by precalculating the constants times Cb and Cr for all possible values.
  169243. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  169244. * for 12-bit samples it is still acceptable. It's not very reasonable for
  169245. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  169246. * colorspace anyway.
  169247. * The Cr=>R and Cb=>B values can be rounded to integers in advance; the
  169248. * values for the G calculation are left scaled up, since we must add them
  169249. * together before rounding.
  169250. */
  169251. #define SCALEBITS 16 /* speediest right-shift on some machines */
  169252. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  169253. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  169254. /*
  169255. * Initialize tables for YCC->RGB colorspace conversion.
  169256. */
  169257. LOCAL(void)
  169258. build_ycc_rgb_table (j_decompress_ptr cinfo)
  169259. {
  169260. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  169261. int i;
  169262. INT32 x;
  169263. SHIFT_TEMPS
  169264. cconvert->Cr_r_tab = (int *)
  169265. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169266. (MAXJSAMPLE+1) * SIZEOF(int));
  169267. cconvert->Cb_b_tab = (int *)
  169268. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169269. (MAXJSAMPLE+1) * SIZEOF(int));
  169270. cconvert->Cr_g_tab = (INT32 *)
  169271. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169272. (MAXJSAMPLE+1) * SIZEOF(INT32));
  169273. cconvert->Cb_g_tab = (INT32 *)
  169274. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169275. (MAXJSAMPLE+1) * SIZEOF(INT32));
  169276. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  169277. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  169278. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  169279. /* Cr=>R value is nearest int to 1.40200 * x */
  169280. cconvert->Cr_r_tab[i] = (int)
  169281. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  169282. /* Cb=>B value is nearest int to 1.77200 * x */
  169283. cconvert->Cb_b_tab[i] = (int)
  169284. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  169285. /* Cr=>G value is scaled-up -0.71414 * x */
  169286. cconvert->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  169287. /* Cb=>G value is scaled-up -0.34414 * x */
  169288. /* We also add in ONE_HALF so that need not do it in inner loop */
  169289. cconvert->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  169290. }
  169291. }
  169292. /*
  169293. * Convert some rows of samples to the output colorspace.
  169294. *
  169295. * Note that we change from noninterleaved, one-plane-per-component format
  169296. * to interleaved-pixel format. The output buffer is therefore three times
  169297. * as wide as the input buffer.
  169298. * A starting row offset is provided only for the input buffer. The caller
  169299. * can easily adjust the passed output_buf value to accommodate any row
  169300. * offset required on that side.
  169301. */
  169302. METHODDEF(void)
  169303. ycc_rgb_convert (j_decompress_ptr cinfo,
  169304. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169305. JSAMPARRAY output_buf, int num_rows)
  169306. {
  169307. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  169308. register int y, cb, cr;
  169309. register JSAMPROW outptr;
  169310. register JSAMPROW inptr0, inptr1, inptr2;
  169311. register JDIMENSION col;
  169312. JDIMENSION num_cols = cinfo->output_width;
  169313. /* copy these pointers into registers if possible */
  169314. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  169315. register int * Crrtab = cconvert->Cr_r_tab;
  169316. register int * Cbbtab = cconvert->Cb_b_tab;
  169317. register INT32 * Crgtab = cconvert->Cr_g_tab;
  169318. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  169319. SHIFT_TEMPS
  169320. while (--num_rows >= 0) {
  169321. inptr0 = input_buf[0][input_row];
  169322. inptr1 = input_buf[1][input_row];
  169323. inptr2 = input_buf[2][input_row];
  169324. input_row++;
  169325. outptr = *output_buf++;
  169326. for (col = 0; col < num_cols; col++) {
  169327. y = GETJSAMPLE(inptr0[col]);
  169328. cb = GETJSAMPLE(inptr1[col]);
  169329. cr = GETJSAMPLE(inptr2[col]);
  169330. /* Range-limiting is essential due to noise introduced by DCT losses. */
  169331. outptr[RGB_RED] = range_limit[y + Crrtab[cr]];
  169332. outptr[RGB_GREEN] = range_limit[y +
  169333. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  169334. SCALEBITS))];
  169335. outptr[RGB_BLUE] = range_limit[y + Cbbtab[cb]];
  169336. outptr += RGB_PIXELSIZE;
  169337. }
  169338. }
  169339. }
  169340. /**************** Cases other than YCbCr -> RGB **************/
  169341. /*
  169342. * Color conversion for no colorspace change: just copy the data,
  169343. * converting from separate-planes to interleaved representation.
  169344. */
  169345. METHODDEF(void)
  169346. null_convert2 (j_decompress_ptr cinfo,
  169347. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169348. JSAMPARRAY output_buf, int num_rows)
  169349. {
  169350. register JSAMPROW inptr, outptr;
  169351. register JDIMENSION count;
  169352. register int num_components = cinfo->num_components;
  169353. JDIMENSION num_cols = cinfo->output_width;
  169354. int ci;
  169355. while (--num_rows >= 0) {
  169356. for (ci = 0; ci < num_components; ci++) {
  169357. inptr = input_buf[ci][input_row];
  169358. outptr = output_buf[0] + ci;
  169359. for (count = num_cols; count > 0; count--) {
  169360. *outptr = *inptr++; /* needn't bother with GETJSAMPLE() here */
  169361. outptr += num_components;
  169362. }
  169363. }
  169364. input_row++;
  169365. output_buf++;
  169366. }
  169367. }
  169368. /*
  169369. * Color conversion for grayscale: just copy the data.
  169370. * This also works for YCbCr -> grayscale conversion, in which
  169371. * we just copy the Y (luminance) component and ignore chrominance.
  169372. */
  169373. METHODDEF(void)
  169374. grayscale_convert2 (j_decompress_ptr cinfo,
  169375. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169376. JSAMPARRAY output_buf, int num_rows)
  169377. {
  169378. jcopy_sample_rows(input_buf[0], (int) input_row, output_buf, 0,
  169379. num_rows, cinfo->output_width);
  169380. }
  169381. /*
  169382. * Convert grayscale to RGB: just duplicate the graylevel three times.
  169383. * This is provided to support applications that don't want to cope
  169384. * with grayscale as a separate case.
  169385. */
  169386. METHODDEF(void)
  169387. gray_rgb_convert (j_decompress_ptr cinfo,
  169388. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169389. JSAMPARRAY output_buf, int num_rows)
  169390. {
  169391. register JSAMPROW inptr, outptr;
  169392. register JDIMENSION col;
  169393. JDIMENSION num_cols = cinfo->output_width;
  169394. while (--num_rows >= 0) {
  169395. inptr = input_buf[0][input_row++];
  169396. outptr = *output_buf++;
  169397. for (col = 0; col < num_cols; col++) {
  169398. /* We can dispense with GETJSAMPLE() here */
  169399. outptr[RGB_RED] = outptr[RGB_GREEN] = outptr[RGB_BLUE] = inptr[col];
  169400. outptr += RGB_PIXELSIZE;
  169401. }
  169402. }
  169403. }
  169404. /*
  169405. * Adobe-style YCCK->CMYK conversion.
  169406. * We convert YCbCr to R=1-C, G=1-M, and B=1-Y using the same
  169407. * conversion as above, while passing K (black) unchanged.
  169408. * We assume build_ycc_rgb_table has been called.
  169409. */
  169410. METHODDEF(void)
  169411. ycck_cmyk_convert (j_decompress_ptr cinfo,
  169412. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169413. JSAMPARRAY output_buf, int num_rows)
  169414. {
  169415. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  169416. register int y, cb, cr;
  169417. register JSAMPROW outptr;
  169418. register JSAMPROW inptr0, inptr1, inptr2, inptr3;
  169419. register JDIMENSION col;
  169420. JDIMENSION num_cols = cinfo->output_width;
  169421. /* copy these pointers into registers if possible */
  169422. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  169423. register int * Crrtab = cconvert->Cr_r_tab;
  169424. register int * Cbbtab = cconvert->Cb_b_tab;
  169425. register INT32 * Crgtab = cconvert->Cr_g_tab;
  169426. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  169427. SHIFT_TEMPS
  169428. while (--num_rows >= 0) {
  169429. inptr0 = input_buf[0][input_row];
  169430. inptr1 = input_buf[1][input_row];
  169431. inptr2 = input_buf[2][input_row];
  169432. inptr3 = input_buf[3][input_row];
  169433. input_row++;
  169434. outptr = *output_buf++;
  169435. for (col = 0; col < num_cols; col++) {
  169436. y = GETJSAMPLE(inptr0[col]);
  169437. cb = GETJSAMPLE(inptr1[col]);
  169438. cr = GETJSAMPLE(inptr2[col]);
  169439. /* Range-limiting is essential due to noise introduced by DCT losses. */
  169440. outptr[0] = range_limit[MAXJSAMPLE - (y + Crrtab[cr])]; /* red */
  169441. outptr[1] = range_limit[MAXJSAMPLE - (y + /* green */
  169442. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  169443. SCALEBITS)))];
  169444. outptr[2] = range_limit[MAXJSAMPLE - (y + Cbbtab[cb])]; /* blue */
  169445. /* K passes through unchanged */
  169446. outptr[3] = inptr3[col]; /* don't need GETJSAMPLE here */
  169447. outptr += 4;
  169448. }
  169449. }
  169450. }
  169451. /*
  169452. * Empty method for start_pass.
  169453. */
  169454. METHODDEF(void)
  169455. start_pass_dcolor (j_decompress_ptr)
  169456. {
  169457. /* no work needed */
  169458. }
  169459. /*
  169460. * Module initialization routine for output colorspace conversion.
  169461. */
  169462. GLOBAL(void)
  169463. jinit_color_deconverter (j_decompress_ptr cinfo)
  169464. {
  169465. my_cconvert_ptr2 cconvert;
  169466. int ci;
  169467. cconvert = (my_cconvert_ptr2)
  169468. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169469. SIZEOF(my_color_deconverter2));
  169470. cinfo->cconvert = (struct jpeg_color_deconverter *) cconvert;
  169471. cconvert->pub.start_pass = start_pass_dcolor;
  169472. /* Make sure num_components agrees with jpeg_color_space */
  169473. switch (cinfo->jpeg_color_space) {
  169474. case JCS_GRAYSCALE:
  169475. if (cinfo->num_components != 1)
  169476. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169477. break;
  169478. case JCS_RGB:
  169479. case JCS_YCbCr:
  169480. if (cinfo->num_components != 3)
  169481. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169482. break;
  169483. case JCS_CMYK:
  169484. case JCS_YCCK:
  169485. if (cinfo->num_components != 4)
  169486. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169487. break;
  169488. default: /* JCS_UNKNOWN can be anything */
  169489. if (cinfo->num_components < 1)
  169490. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169491. break;
  169492. }
  169493. /* Set out_color_components and conversion method based on requested space.
  169494. * Also clear the component_needed flags for any unused components,
  169495. * so that earlier pipeline stages can avoid useless computation.
  169496. */
  169497. switch (cinfo->out_color_space) {
  169498. case JCS_GRAYSCALE:
  169499. cinfo->out_color_components = 1;
  169500. if (cinfo->jpeg_color_space == JCS_GRAYSCALE ||
  169501. cinfo->jpeg_color_space == JCS_YCbCr) {
  169502. cconvert->pub.color_convert = grayscale_convert2;
  169503. /* For color->grayscale conversion, only the Y (0) component is needed */
  169504. for (ci = 1; ci < cinfo->num_components; ci++)
  169505. cinfo->comp_info[ci].component_needed = FALSE;
  169506. } else
  169507. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169508. break;
  169509. case JCS_RGB:
  169510. cinfo->out_color_components = RGB_PIXELSIZE;
  169511. if (cinfo->jpeg_color_space == JCS_YCbCr) {
  169512. cconvert->pub.color_convert = ycc_rgb_convert;
  169513. build_ycc_rgb_table(cinfo);
  169514. } else if (cinfo->jpeg_color_space == JCS_GRAYSCALE) {
  169515. cconvert->pub.color_convert = gray_rgb_convert;
  169516. } else if (cinfo->jpeg_color_space == JCS_RGB && RGB_PIXELSIZE == 3) {
  169517. cconvert->pub.color_convert = null_convert2;
  169518. } else
  169519. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169520. break;
  169521. case JCS_CMYK:
  169522. cinfo->out_color_components = 4;
  169523. if (cinfo->jpeg_color_space == JCS_YCCK) {
  169524. cconvert->pub.color_convert = ycck_cmyk_convert;
  169525. build_ycc_rgb_table(cinfo);
  169526. } else if (cinfo->jpeg_color_space == JCS_CMYK) {
  169527. cconvert->pub.color_convert = null_convert2;
  169528. } else
  169529. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169530. break;
  169531. default:
  169532. /* Permit null conversion to same output space */
  169533. if (cinfo->out_color_space == cinfo->jpeg_color_space) {
  169534. cinfo->out_color_components = cinfo->num_components;
  169535. cconvert->pub.color_convert = null_convert2;
  169536. } else /* unsupported non-null conversion */
  169537. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169538. break;
  169539. }
  169540. if (cinfo->quantize_colors)
  169541. cinfo->output_components = 1; /* single colormapped output component */
  169542. else
  169543. cinfo->output_components = cinfo->out_color_components;
  169544. }
  169545. /*** End of inlined file: jdcolor.c ***/
  169546. #undef FIX
  169547. /*** Start of inlined file: jddctmgr.c ***/
  169548. #define JPEG_INTERNALS
  169549. /*
  169550. * The decompressor input side (jdinput.c) saves away the appropriate
  169551. * quantization table for each component at the start of the first scan
  169552. * involving that component. (This is necessary in order to correctly
  169553. * decode files that reuse Q-table slots.)
  169554. * When we are ready to make an output pass, the saved Q-table is converted
  169555. * to a multiplier table that will actually be used by the IDCT routine.
  169556. * The multiplier table contents are IDCT-method-dependent. To support
  169557. * application changes in IDCT method between scans, we can remake the
  169558. * multiplier tables if necessary.
  169559. * In buffered-image mode, the first output pass may occur before any data
  169560. * has been seen for some components, and thus before their Q-tables have
  169561. * been saved away. To handle this case, multiplier tables are preset
  169562. * to zeroes; the result of the IDCT will be a neutral gray level.
  169563. */
  169564. /* Private subobject for this module */
  169565. typedef struct {
  169566. struct jpeg_inverse_dct pub; /* public fields */
  169567. /* This array contains the IDCT method code that each multiplier table
  169568. * is currently set up for, or -1 if it's not yet set up.
  169569. * The actual multiplier tables are pointed to by dct_table in the
  169570. * per-component comp_info structures.
  169571. */
  169572. int cur_method[MAX_COMPONENTS];
  169573. } my_idct_controller;
  169574. typedef my_idct_controller * my_idct_ptr;
  169575. /* Allocated multiplier tables: big enough for any supported variant */
  169576. typedef union {
  169577. ISLOW_MULT_TYPE islow_array[DCTSIZE2];
  169578. #ifdef DCT_IFAST_SUPPORTED
  169579. IFAST_MULT_TYPE ifast_array[DCTSIZE2];
  169580. #endif
  169581. #ifdef DCT_FLOAT_SUPPORTED
  169582. FLOAT_MULT_TYPE float_array[DCTSIZE2];
  169583. #endif
  169584. } multiplier_table;
  169585. /* The current scaled-IDCT routines require ISLOW-style multiplier tables,
  169586. * so be sure to compile that code if either ISLOW or SCALING is requested.
  169587. */
  169588. #ifdef DCT_ISLOW_SUPPORTED
  169589. #define PROVIDE_ISLOW_TABLES
  169590. #else
  169591. #ifdef IDCT_SCALING_SUPPORTED
  169592. #define PROVIDE_ISLOW_TABLES
  169593. #endif
  169594. #endif
  169595. /*
  169596. * Prepare for an output pass.
  169597. * Here we select the proper IDCT routine for each component and build
  169598. * a matching multiplier table.
  169599. */
  169600. METHODDEF(void)
  169601. start_pass (j_decompress_ptr cinfo)
  169602. {
  169603. my_idct_ptr idct = (my_idct_ptr) cinfo->idct;
  169604. int ci, i;
  169605. jpeg_component_info *compptr;
  169606. int method = 0;
  169607. inverse_DCT_method_ptr method_ptr = NULL;
  169608. JQUANT_TBL * qtbl;
  169609. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169610. ci++, compptr++) {
  169611. /* Select the proper IDCT routine for this component's scaling */
  169612. switch (compptr->DCT_scaled_size) {
  169613. #ifdef IDCT_SCALING_SUPPORTED
  169614. case 1:
  169615. method_ptr = jpeg_idct_1x1;
  169616. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  169617. break;
  169618. case 2:
  169619. method_ptr = jpeg_idct_2x2;
  169620. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  169621. break;
  169622. case 4:
  169623. method_ptr = jpeg_idct_4x4;
  169624. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  169625. break;
  169626. #endif
  169627. case DCTSIZE:
  169628. switch (cinfo->dct_method) {
  169629. #ifdef DCT_ISLOW_SUPPORTED
  169630. case JDCT_ISLOW:
  169631. method_ptr = jpeg_idct_islow;
  169632. method = JDCT_ISLOW;
  169633. break;
  169634. #endif
  169635. #ifdef DCT_IFAST_SUPPORTED
  169636. case JDCT_IFAST:
  169637. method_ptr = jpeg_idct_ifast;
  169638. method = JDCT_IFAST;
  169639. break;
  169640. #endif
  169641. #ifdef DCT_FLOAT_SUPPORTED
  169642. case JDCT_FLOAT:
  169643. method_ptr = jpeg_idct_float;
  169644. method = JDCT_FLOAT;
  169645. break;
  169646. #endif
  169647. default:
  169648. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169649. break;
  169650. }
  169651. break;
  169652. default:
  169653. ERREXIT1(cinfo, JERR_BAD_DCTSIZE, compptr->DCT_scaled_size);
  169654. break;
  169655. }
  169656. idct->pub.inverse_DCT[ci] = method_ptr;
  169657. /* Create multiplier table from quant table.
  169658. * However, we can skip this if the component is uninteresting
  169659. * or if we already built the table. Also, if no quant table
  169660. * has yet been saved for the component, we leave the
  169661. * multiplier table all-zero; we'll be reading zeroes from the
  169662. * coefficient controller's buffer anyway.
  169663. */
  169664. if (! compptr->component_needed || idct->cur_method[ci] == method)
  169665. continue;
  169666. qtbl = compptr->quant_table;
  169667. if (qtbl == NULL) /* happens if no data yet for component */
  169668. continue;
  169669. idct->cur_method[ci] = method;
  169670. switch (method) {
  169671. #ifdef PROVIDE_ISLOW_TABLES
  169672. case JDCT_ISLOW:
  169673. {
  169674. /* For LL&M IDCT method, multipliers are equal to raw quantization
  169675. * coefficients, but are stored as ints to ensure access efficiency.
  169676. */
  169677. ISLOW_MULT_TYPE * ismtbl = (ISLOW_MULT_TYPE *) compptr->dct_table;
  169678. for (i = 0; i < DCTSIZE2; i++) {
  169679. ismtbl[i] = (ISLOW_MULT_TYPE) qtbl->quantval[i];
  169680. }
  169681. }
  169682. break;
  169683. #endif
  169684. #ifdef DCT_IFAST_SUPPORTED
  169685. case JDCT_IFAST:
  169686. {
  169687. /* For AA&N IDCT method, multipliers are equal to quantization
  169688. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  169689. * scalefactor[0] = 1
  169690. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  169691. * For integer operation, the multiplier table is to be scaled by
  169692. * IFAST_SCALE_BITS.
  169693. */
  169694. IFAST_MULT_TYPE * ifmtbl = (IFAST_MULT_TYPE *) compptr->dct_table;
  169695. #define CONST_BITS 14
  169696. static const INT16 aanscales[DCTSIZE2] = {
  169697. /* precomputed values scaled up by 14 bits */
  169698. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  169699. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  169700. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  169701. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  169702. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  169703. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  169704. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  169705. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  169706. };
  169707. SHIFT_TEMPS
  169708. for (i = 0; i < DCTSIZE2; i++) {
  169709. ifmtbl[i] = (IFAST_MULT_TYPE)
  169710. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  169711. (INT32) aanscales[i]),
  169712. CONST_BITS-IFAST_SCALE_BITS);
  169713. }
  169714. }
  169715. break;
  169716. #endif
  169717. #ifdef DCT_FLOAT_SUPPORTED
  169718. case JDCT_FLOAT:
  169719. {
  169720. /* For float AA&N IDCT method, multipliers are equal to quantization
  169721. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  169722. * scalefactor[0] = 1
  169723. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  169724. */
  169725. FLOAT_MULT_TYPE * fmtbl = (FLOAT_MULT_TYPE *) compptr->dct_table;
  169726. int row, col;
  169727. static const double aanscalefactor[DCTSIZE] = {
  169728. 1.0, 1.387039845, 1.306562965, 1.175875602,
  169729. 1.0, 0.785694958, 0.541196100, 0.275899379
  169730. };
  169731. i = 0;
  169732. for (row = 0; row < DCTSIZE; row++) {
  169733. for (col = 0; col < DCTSIZE; col++) {
  169734. fmtbl[i] = (FLOAT_MULT_TYPE)
  169735. ((double) qtbl->quantval[i] *
  169736. aanscalefactor[row] * aanscalefactor[col]);
  169737. i++;
  169738. }
  169739. }
  169740. }
  169741. break;
  169742. #endif
  169743. default:
  169744. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169745. break;
  169746. }
  169747. }
  169748. }
  169749. /*
  169750. * Initialize IDCT manager.
  169751. */
  169752. GLOBAL(void)
  169753. jinit_inverse_dct (j_decompress_ptr cinfo)
  169754. {
  169755. my_idct_ptr idct;
  169756. int ci;
  169757. jpeg_component_info *compptr;
  169758. idct = (my_idct_ptr)
  169759. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169760. SIZEOF(my_idct_controller));
  169761. cinfo->idct = (struct jpeg_inverse_dct *) idct;
  169762. idct->pub.start_pass = start_pass;
  169763. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169764. ci++, compptr++) {
  169765. /* Allocate and pre-zero a multiplier table for each component */
  169766. compptr->dct_table =
  169767. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169768. SIZEOF(multiplier_table));
  169769. MEMZERO(compptr->dct_table, SIZEOF(multiplier_table));
  169770. /* Mark multiplier table not yet set up for any method */
  169771. idct->cur_method[ci] = -1;
  169772. }
  169773. }
  169774. /*** End of inlined file: jddctmgr.c ***/
  169775. #undef CONST_BITS
  169776. #undef ASSIGN_STATE
  169777. /*** Start of inlined file: jdhuff.c ***/
  169778. #define JPEG_INTERNALS
  169779. /*** Start of inlined file: jdhuff.h ***/
  169780. /* Short forms of external names for systems with brain-damaged linkers. */
  169781. #ifndef __jdhuff_h__
  169782. #define __jdhuff_h__
  169783. #ifdef NEED_SHORT_EXTERNAL_NAMES
  169784. #define jpeg_make_d_derived_tbl jMkDDerived
  169785. #define jpeg_fill_bit_buffer jFilBitBuf
  169786. #define jpeg_huff_decode jHufDecode
  169787. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  169788. /* Derived data constructed for each Huffman table */
  169789. #define HUFF_LOOKAHEAD 8 /* # of bits of lookahead */
  169790. typedef struct {
  169791. /* Basic tables: (element [0] of each array is unused) */
  169792. INT32 maxcode[18]; /* largest code of length k (-1 if none) */
  169793. /* (maxcode[17] is a sentinel to ensure jpeg_huff_decode terminates) */
  169794. INT32 valoffset[17]; /* huffval[] offset for codes of length k */
  169795. /* valoffset[k] = huffval[] index of 1st symbol of code length k, less
  169796. * the smallest code of length k; so given a code of length k, the
  169797. * corresponding symbol is huffval[code + valoffset[k]]
  169798. */
  169799. /* Link to public Huffman table (needed only in jpeg_huff_decode) */
  169800. JHUFF_TBL *pub;
  169801. /* Lookahead tables: indexed by the next HUFF_LOOKAHEAD bits of
  169802. * the input data stream. If the next Huffman code is no more
  169803. * than HUFF_LOOKAHEAD bits long, we can obtain its length and
  169804. * the corresponding symbol directly from these tables.
  169805. */
  169806. int look_nbits[1<<HUFF_LOOKAHEAD]; /* # bits, or 0 if too long */
  169807. UINT8 look_sym[1<<HUFF_LOOKAHEAD]; /* symbol, or unused */
  169808. } d_derived_tbl;
  169809. /* Expand a Huffman table definition into the derived format */
  169810. EXTERN(void) jpeg_make_d_derived_tbl
  169811. JPP((j_decompress_ptr cinfo, boolean isDC, int tblno,
  169812. d_derived_tbl ** pdtbl));
  169813. /*
  169814. * Fetching the next N bits from the input stream is a time-critical operation
  169815. * for the Huffman decoders. We implement it with a combination of inline
  169816. * macros and out-of-line subroutines. Note that N (the number of bits
  169817. * demanded at one time) never exceeds 15 for JPEG use.
  169818. *
  169819. * We read source bytes into get_buffer and dole out bits as needed.
  169820. * If get_buffer already contains enough bits, they are fetched in-line
  169821. * by the macros CHECK_BIT_BUFFER and GET_BITS. When there aren't enough
  169822. * bits, jpeg_fill_bit_buffer is called; it will attempt to fill get_buffer
  169823. * as full as possible (not just to the number of bits needed; this
  169824. * prefetching reduces the overhead cost of calling jpeg_fill_bit_buffer).
  169825. * Note that jpeg_fill_bit_buffer may return FALSE to indicate suspension.
  169826. * On TRUE return, jpeg_fill_bit_buffer guarantees that get_buffer contains
  169827. * at least the requested number of bits --- dummy zeroes are inserted if
  169828. * necessary.
  169829. */
  169830. typedef INT32 bit_buf_type; /* type of bit-extraction buffer */
  169831. #define BIT_BUF_SIZE 32 /* size of buffer in bits */
  169832. /* If long is > 32 bits on your machine, and shifting/masking longs is
  169833. * reasonably fast, making bit_buf_type be long and setting BIT_BUF_SIZE
  169834. * appropriately should be a win. Unfortunately we can't define the size
  169835. * with something like #define BIT_BUF_SIZE (sizeof(bit_buf_type)*8)
  169836. * because not all machines measure sizeof in 8-bit bytes.
  169837. */
  169838. typedef struct { /* Bitreading state saved across MCUs */
  169839. bit_buf_type get_buffer; /* current bit-extraction buffer */
  169840. int bits_left; /* # of unused bits in it */
  169841. } bitread_perm_state;
  169842. typedef struct { /* Bitreading working state within an MCU */
  169843. /* Current data source location */
  169844. /* We need a copy, rather than munging the original, in case of suspension */
  169845. const JOCTET * next_input_byte; /* => next byte to read from source */
  169846. size_t bytes_in_buffer; /* # of bytes remaining in source buffer */
  169847. /* Bit input buffer --- note these values are kept in register variables,
  169848. * not in this struct, inside the inner loops.
  169849. */
  169850. bit_buf_type get_buffer; /* current bit-extraction buffer */
  169851. int bits_left; /* # of unused bits in it */
  169852. /* Pointer needed by jpeg_fill_bit_buffer. */
  169853. j_decompress_ptr cinfo; /* back link to decompress master record */
  169854. } bitread_working_state;
  169855. /* Macros to declare and load/save bitread local variables. */
  169856. #define BITREAD_STATE_VARS \
  169857. register bit_buf_type get_buffer; \
  169858. register int bits_left; \
  169859. bitread_working_state br_state
  169860. #define BITREAD_LOAD_STATE(cinfop,permstate) \
  169861. br_state.cinfo = cinfop; \
  169862. br_state.next_input_byte = cinfop->src->next_input_byte; \
  169863. br_state.bytes_in_buffer = cinfop->src->bytes_in_buffer; \
  169864. get_buffer = permstate.get_buffer; \
  169865. bits_left = permstate.bits_left;
  169866. #define BITREAD_SAVE_STATE(cinfop,permstate) \
  169867. cinfop->src->next_input_byte = br_state.next_input_byte; \
  169868. cinfop->src->bytes_in_buffer = br_state.bytes_in_buffer; \
  169869. permstate.get_buffer = get_buffer; \
  169870. permstate.bits_left = bits_left
  169871. /*
  169872. * These macros provide the in-line portion of bit fetching.
  169873. * Use CHECK_BIT_BUFFER to ensure there are N bits in get_buffer
  169874. * before using GET_BITS, PEEK_BITS, or DROP_BITS.
  169875. * The variables get_buffer and bits_left are assumed to be locals,
  169876. * but the state struct might not be (jpeg_huff_decode needs this).
  169877. * CHECK_BIT_BUFFER(state,n,action);
  169878. * Ensure there are N bits in get_buffer; if suspend, take action.
  169879. * val = GET_BITS(n);
  169880. * Fetch next N bits.
  169881. * val = PEEK_BITS(n);
  169882. * Fetch next N bits without removing them from the buffer.
  169883. * DROP_BITS(n);
  169884. * Discard next N bits.
  169885. * The value N should be a simple variable, not an expression, because it
  169886. * is evaluated multiple times.
  169887. */
  169888. #define CHECK_BIT_BUFFER(state,nbits,action) \
  169889. { if (bits_left < (nbits)) { \
  169890. if (! jpeg_fill_bit_buffer(&(state),get_buffer,bits_left,nbits)) \
  169891. { action; } \
  169892. get_buffer = (state).get_buffer; bits_left = (state).bits_left; } }
  169893. #define GET_BITS(nbits) \
  169894. (((int) (get_buffer >> (bits_left -= (nbits)))) & ((1<<(nbits))-1))
  169895. #define PEEK_BITS(nbits) \
  169896. (((int) (get_buffer >> (bits_left - (nbits)))) & ((1<<(nbits))-1))
  169897. #define DROP_BITS(nbits) \
  169898. (bits_left -= (nbits))
  169899. /* Load up the bit buffer to a depth of at least nbits */
  169900. EXTERN(boolean) jpeg_fill_bit_buffer
  169901. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  169902. register int bits_left, int nbits));
  169903. /*
  169904. * Code for extracting next Huffman-coded symbol from input bit stream.
  169905. * Again, this is time-critical and we make the main paths be macros.
  169906. *
  169907. * We use a lookahead table to process codes of up to HUFF_LOOKAHEAD bits
  169908. * without looping. Usually, more than 95% of the Huffman codes will be 8
  169909. * or fewer bits long. The few overlength codes are handled with a loop,
  169910. * which need not be inline code.
  169911. *
  169912. * Notes about the HUFF_DECODE macro:
  169913. * 1. Near the end of the data segment, we may fail to get enough bits
  169914. * for a lookahead. In that case, we do it the hard way.
  169915. * 2. If the lookahead table contains no entry, the next code must be
  169916. * more than HUFF_LOOKAHEAD bits long.
  169917. * 3. jpeg_huff_decode returns -1 if forced to suspend.
  169918. */
  169919. #define HUFF_DECODE(result,state,htbl,failaction,slowlabel) \
  169920. { register int nb, look; \
  169921. if (bits_left < HUFF_LOOKAHEAD) { \
  169922. if (! jpeg_fill_bit_buffer(&state,get_buffer,bits_left, 0)) {failaction;} \
  169923. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  169924. if (bits_left < HUFF_LOOKAHEAD) { \
  169925. nb = 1; goto slowlabel; \
  169926. } \
  169927. } \
  169928. look = PEEK_BITS(HUFF_LOOKAHEAD); \
  169929. if ((nb = htbl->look_nbits[look]) != 0) { \
  169930. DROP_BITS(nb); \
  169931. result = htbl->look_sym[look]; \
  169932. } else { \
  169933. nb = HUFF_LOOKAHEAD+1; \
  169934. slowlabel: \
  169935. if ((result=jpeg_huff_decode(&state,get_buffer,bits_left,htbl,nb)) < 0) \
  169936. { failaction; } \
  169937. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  169938. } \
  169939. }
  169940. /* Out-of-line case for Huffman code fetching */
  169941. EXTERN(int) jpeg_huff_decode
  169942. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  169943. register int bits_left, d_derived_tbl * htbl, int min_bits));
  169944. #endif
  169945. /*** End of inlined file: jdhuff.h ***/
  169946. /* Declarations shared with jdphuff.c */
  169947. /*
  169948. * Expanded entropy decoder object for Huffman decoding.
  169949. *
  169950. * The savable_state subrecord contains fields that change within an MCU,
  169951. * but must not be updated permanently until we complete the MCU.
  169952. */
  169953. typedef struct {
  169954. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  169955. } savable_state2;
  169956. /* This macro is to work around compilers with missing or broken
  169957. * structure assignment. You'll need to fix this code if you have
  169958. * such a compiler and you change MAX_COMPS_IN_SCAN.
  169959. */
  169960. #ifndef NO_STRUCT_ASSIGN
  169961. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  169962. #else
  169963. #if MAX_COMPS_IN_SCAN == 4
  169964. #define ASSIGN_STATE(dest,src) \
  169965. ((dest).last_dc_val[0] = (src).last_dc_val[0], \
  169966. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  169967. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  169968. (dest).last_dc_val[3] = (src).last_dc_val[3])
  169969. #endif
  169970. #endif
  169971. typedef struct {
  169972. struct jpeg_entropy_decoder pub; /* public fields */
  169973. /* These fields are loaded into local variables at start of each MCU.
  169974. * In case of suspension, we exit WITHOUT updating them.
  169975. */
  169976. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  169977. savable_state2 saved; /* Other state at start of MCU */
  169978. /* These fields are NOT loaded into local working state. */
  169979. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  169980. /* Pointers to derived tables (these workspaces have image lifespan) */
  169981. d_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  169982. d_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  169983. /* Precalculated info set up by start_pass for use in decode_mcu: */
  169984. /* Pointers to derived tables to be used for each block within an MCU */
  169985. d_derived_tbl * dc_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  169986. d_derived_tbl * ac_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  169987. /* Whether we care about the DC and AC coefficient values for each block */
  169988. boolean dc_needed[D_MAX_BLOCKS_IN_MCU];
  169989. boolean ac_needed[D_MAX_BLOCKS_IN_MCU];
  169990. } huff_entropy_decoder2;
  169991. typedef huff_entropy_decoder2 * huff_entropy_ptr2;
  169992. /*
  169993. * Initialize for a Huffman-compressed scan.
  169994. */
  169995. METHODDEF(void)
  169996. start_pass_huff_decoder (j_decompress_ptr cinfo)
  169997. {
  169998. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  169999. int ci, blkn, dctbl, actbl;
  170000. jpeg_component_info * compptr;
  170001. /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
  170002. * This ought to be an error condition, but we make it a warning because
  170003. * there are some baseline files out there with all zeroes in these bytes.
  170004. */
  170005. if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2-1 ||
  170006. cinfo->Ah != 0 || cinfo->Al != 0)
  170007. WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
  170008. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  170009. compptr = cinfo->cur_comp_info[ci];
  170010. dctbl = compptr->dc_tbl_no;
  170011. actbl = compptr->ac_tbl_no;
  170012. /* Compute derived values for Huffman tables */
  170013. /* We may do this more than once for a table, but it's not expensive */
  170014. jpeg_make_d_derived_tbl(cinfo, TRUE, dctbl,
  170015. & entropy->dc_derived_tbls[dctbl]);
  170016. jpeg_make_d_derived_tbl(cinfo, FALSE, actbl,
  170017. & entropy->ac_derived_tbls[actbl]);
  170018. /* Initialize DC predictions to 0 */
  170019. entropy->saved.last_dc_val[ci] = 0;
  170020. }
  170021. /* Precalculate decoding info for each block in an MCU of this scan */
  170022. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  170023. ci = cinfo->MCU_membership[blkn];
  170024. compptr = cinfo->cur_comp_info[ci];
  170025. /* Precalculate which table to use for each block */
  170026. entropy->dc_cur_tbls[blkn] = entropy->dc_derived_tbls[compptr->dc_tbl_no];
  170027. entropy->ac_cur_tbls[blkn] = entropy->ac_derived_tbls[compptr->ac_tbl_no];
  170028. /* Decide whether we really care about the coefficient values */
  170029. if (compptr->component_needed) {
  170030. entropy->dc_needed[blkn] = TRUE;
  170031. /* we don't need the ACs if producing a 1/8th-size image */
  170032. entropy->ac_needed[blkn] = (compptr->DCT_scaled_size > 1);
  170033. } else {
  170034. entropy->dc_needed[blkn] = entropy->ac_needed[blkn] = FALSE;
  170035. }
  170036. }
  170037. /* Initialize bitread state variables */
  170038. entropy->bitstate.bits_left = 0;
  170039. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  170040. entropy->pub.insufficient_data = FALSE;
  170041. /* Initialize restart counter */
  170042. entropy->restarts_to_go = cinfo->restart_interval;
  170043. }
  170044. /*
  170045. * Compute the derived values for a Huffman table.
  170046. * This routine also performs some validation checks on the table.
  170047. *
  170048. * Note this is also used by jdphuff.c.
  170049. */
  170050. GLOBAL(void)
  170051. jpeg_make_d_derived_tbl (j_decompress_ptr cinfo, boolean isDC, int tblno,
  170052. d_derived_tbl ** pdtbl)
  170053. {
  170054. JHUFF_TBL *htbl;
  170055. d_derived_tbl *dtbl;
  170056. int p, i, l, si, numsymbols;
  170057. int lookbits, ctr;
  170058. char huffsize[257];
  170059. unsigned int huffcode[257];
  170060. unsigned int code;
  170061. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  170062. * paralleling the order of the symbols themselves in htbl->huffval[].
  170063. */
  170064. /* Find the input Huffman table */
  170065. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  170066. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  170067. htbl =
  170068. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  170069. if (htbl == NULL)
  170070. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  170071. /* Allocate a workspace if we haven't already done so. */
  170072. if (*pdtbl == NULL)
  170073. *pdtbl = (d_derived_tbl *)
  170074. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170075. SIZEOF(d_derived_tbl));
  170076. dtbl = *pdtbl;
  170077. dtbl->pub = htbl; /* fill in back link */
  170078. /* Figure C.1: make table of Huffman code length for each symbol */
  170079. p = 0;
  170080. for (l = 1; l <= 16; l++) {
  170081. i = (int) htbl->bits[l];
  170082. if (i < 0 || p + i > 256) /* protect against table overrun */
  170083. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  170084. while (i--)
  170085. huffsize[p++] = (char) l;
  170086. }
  170087. huffsize[p] = 0;
  170088. numsymbols = p;
  170089. /* Figure C.2: generate the codes themselves */
  170090. /* We also validate that the counts represent a legal Huffman code tree. */
  170091. code = 0;
  170092. si = huffsize[0];
  170093. p = 0;
  170094. while (huffsize[p]) {
  170095. while (((int) huffsize[p]) == si) {
  170096. huffcode[p++] = code;
  170097. code++;
  170098. }
  170099. /* code is now 1 more than the last code used for codelength si; but
  170100. * it must still fit in si bits, since no code is allowed to be all ones.
  170101. */
  170102. if (((INT32) code) >= (((INT32) 1) << si))
  170103. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  170104. code <<= 1;
  170105. si++;
  170106. }
  170107. /* Figure F.15: generate decoding tables for bit-sequential decoding */
  170108. p = 0;
  170109. for (l = 1; l <= 16; l++) {
  170110. if (htbl->bits[l]) {
  170111. /* valoffset[l] = huffval[] index of 1st symbol of code length l,
  170112. * minus the minimum code of length l
  170113. */
  170114. dtbl->valoffset[l] = (INT32) p - (INT32) huffcode[p];
  170115. p += htbl->bits[l];
  170116. dtbl->maxcode[l] = huffcode[p-1]; /* maximum code of length l */
  170117. } else {
  170118. dtbl->maxcode[l] = -1; /* -1 if no codes of this length */
  170119. }
  170120. }
  170121. dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */
  170122. /* Compute lookahead tables to speed up decoding.
  170123. * First we set all the table entries to 0, indicating "too long";
  170124. * then we iterate through the Huffman codes that are short enough and
  170125. * fill in all the entries that correspond to bit sequences starting
  170126. * with that code.
  170127. */
  170128. MEMZERO(dtbl->look_nbits, SIZEOF(dtbl->look_nbits));
  170129. p = 0;
  170130. for (l = 1; l <= HUFF_LOOKAHEAD; l++) {
  170131. for (i = 1; i <= (int) htbl->bits[l]; i++, p++) {
  170132. /* l = current code's length, p = its index in huffcode[] & huffval[]. */
  170133. /* Generate left-justified code followed by all possible bit sequences */
  170134. lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l);
  170135. for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) {
  170136. dtbl->look_nbits[lookbits] = l;
  170137. dtbl->look_sym[lookbits] = htbl->huffval[p];
  170138. lookbits++;
  170139. }
  170140. }
  170141. }
  170142. /* Validate symbols as being reasonable.
  170143. * For AC tables, we make no check, but accept all byte values 0..255.
  170144. * For DC tables, we require the symbols to be in range 0..15.
  170145. * (Tighter bounds could be applied depending on the data depth and mode,
  170146. * but this is sufficient to ensure safe decoding.)
  170147. */
  170148. if (isDC) {
  170149. for (i = 0; i < numsymbols; i++) {
  170150. int sym = htbl->huffval[i];
  170151. if (sym < 0 || sym > 15)
  170152. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  170153. }
  170154. }
  170155. }
  170156. /*
  170157. * Out-of-line code for bit fetching (shared with jdphuff.c).
  170158. * See jdhuff.h for info about usage.
  170159. * Note: current values of get_buffer and bits_left are passed as parameters,
  170160. * but are returned in the corresponding fields of the state struct.
  170161. *
  170162. * On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width
  170163. * of get_buffer to be used. (On machines with wider words, an even larger
  170164. * buffer could be used.) However, on some machines 32-bit shifts are
  170165. * quite slow and take time proportional to the number of places shifted.
  170166. * (This is true with most PC compilers, for instance.) In this case it may
  170167. * be a win to set MIN_GET_BITS to the minimum value of 15. This reduces the
  170168. * average shift distance at the cost of more calls to jpeg_fill_bit_buffer.
  170169. */
  170170. #ifdef SLOW_SHIFT_32
  170171. #define MIN_GET_BITS 15 /* minimum allowable value */
  170172. #else
  170173. #define MIN_GET_BITS (BIT_BUF_SIZE-7)
  170174. #endif
  170175. GLOBAL(boolean)
  170176. jpeg_fill_bit_buffer (bitread_working_state * state,
  170177. register bit_buf_type get_buffer, register int bits_left,
  170178. int nbits)
  170179. /* Load up the bit buffer to a depth of at least nbits */
  170180. {
  170181. /* Copy heavily used state fields into locals (hopefully registers) */
  170182. register const JOCTET * next_input_byte = state->next_input_byte;
  170183. register size_t bytes_in_buffer = state->bytes_in_buffer;
  170184. j_decompress_ptr cinfo = state->cinfo;
  170185. /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */
  170186. /* (It is assumed that no request will be for more than that many bits.) */
  170187. /* We fail to do so only if we hit a marker or are forced to suspend. */
  170188. if (cinfo->unread_marker == 0) { /* cannot advance past a marker */
  170189. while (bits_left < MIN_GET_BITS) {
  170190. register int c;
  170191. /* Attempt to read a byte */
  170192. if (bytes_in_buffer == 0) {
  170193. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  170194. return FALSE;
  170195. next_input_byte = cinfo->src->next_input_byte;
  170196. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  170197. }
  170198. bytes_in_buffer--;
  170199. c = GETJOCTET(*next_input_byte++);
  170200. /* If it's 0xFF, check and discard stuffed zero byte */
  170201. if (c == 0xFF) {
  170202. /* Loop here to discard any padding FF's on terminating marker,
  170203. * so that we can save a valid unread_marker value. NOTE: we will
  170204. * accept multiple FF's followed by a 0 as meaning a single FF data
  170205. * byte. This data pattern is not valid according to the standard.
  170206. */
  170207. do {
  170208. if (bytes_in_buffer == 0) {
  170209. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  170210. return FALSE;
  170211. next_input_byte = cinfo->src->next_input_byte;
  170212. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  170213. }
  170214. bytes_in_buffer--;
  170215. c = GETJOCTET(*next_input_byte++);
  170216. } while (c == 0xFF);
  170217. if (c == 0) {
  170218. /* Found FF/00, which represents an FF data byte */
  170219. c = 0xFF;
  170220. } else {
  170221. /* Oops, it's actually a marker indicating end of compressed data.
  170222. * Save the marker code for later use.
  170223. * Fine point: it might appear that we should save the marker into
  170224. * bitread working state, not straight into permanent state. But
  170225. * once we have hit a marker, we cannot need to suspend within the
  170226. * current MCU, because we will read no more bytes from the data
  170227. * source. So it is OK to update permanent state right away.
  170228. */
  170229. cinfo->unread_marker = c;
  170230. /* See if we need to insert some fake zero bits. */
  170231. goto no_more_bytes;
  170232. }
  170233. }
  170234. /* OK, load c into get_buffer */
  170235. get_buffer = (get_buffer << 8) | c;
  170236. bits_left += 8;
  170237. } /* end while */
  170238. } else {
  170239. no_more_bytes:
  170240. /* We get here if we've read the marker that terminates the compressed
  170241. * data segment. There should be enough bits in the buffer register
  170242. * to satisfy the request; if so, no problem.
  170243. */
  170244. if (nbits > bits_left) {
  170245. /* Uh-oh. Report corrupted data to user and stuff zeroes into
  170246. * the data stream, so that we can produce some kind of image.
  170247. * We use a nonvolatile flag to ensure that only one warning message
  170248. * appears per data segment.
  170249. */
  170250. if (! cinfo->entropy->insufficient_data) {
  170251. WARNMS(cinfo, JWRN_HIT_MARKER);
  170252. cinfo->entropy->insufficient_data = TRUE;
  170253. }
  170254. /* Fill the buffer with zero bits */
  170255. get_buffer <<= MIN_GET_BITS - bits_left;
  170256. bits_left = MIN_GET_BITS;
  170257. }
  170258. }
  170259. /* Unload the local registers */
  170260. state->next_input_byte = next_input_byte;
  170261. state->bytes_in_buffer = bytes_in_buffer;
  170262. state->get_buffer = get_buffer;
  170263. state->bits_left = bits_left;
  170264. return TRUE;
  170265. }
  170266. /*
  170267. * Out-of-line code for Huffman code decoding.
  170268. * See jdhuff.h for info about usage.
  170269. */
  170270. GLOBAL(int)
  170271. jpeg_huff_decode (bitread_working_state * state,
  170272. register bit_buf_type get_buffer, register int bits_left,
  170273. d_derived_tbl * htbl, int min_bits)
  170274. {
  170275. register int l = min_bits;
  170276. register INT32 code;
  170277. /* HUFF_DECODE has determined that the code is at least min_bits */
  170278. /* bits long, so fetch that many bits in one swoop. */
  170279. CHECK_BIT_BUFFER(*state, l, return -1);
  170280. code = GET_BITS(l);
  170281. /* Collect the rest of the Huffman code one bit at a time. */
  170282. /* This is per Figure F.16 in the JPEG spec. */
  170283. while (code > htbl->maxcode[l]) {
  170284. code <<= 1;
  170285. CHECK_BIT_BUFFER(*state, 1, return -1);
  170286. code |= GET_BITS(1);
  170287. l++;
  170288. }
  170289. /* Unload the local registers */
  170290. state->get_buffer = get_buffer;
  170291. state->bits_left = bits_left;
  170292. /* With garbage input we may reach the sentinel value l = 17. */
  170293. if (l > 16) {
  170294. WARNMS(state->cinfo, JWRN_HUFF_BAD_CODE);
  170295. return 0; /* fake a zero as the safest result */
  170296. }
  170297. return htbl->pub->huffval[ (int) (code + htbl->valoffset[l]) ];
  170298. }
  170299. /*
  170300. * Check for a restart marker & resynchronize decoder.
  170301. * Returns FALSE if must suspend.
  170302. */
  170303. LOCAL(boolean)
  170304. process_restart (j_decompress_ptr cinfo)
  170305. {
  170306. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  170307. int ci;
  170308. /* Throw away any unused bits remaining in bit buffer; */
  170309. /* include any full bytes in next_marker's count of discarded bytes */
  170310. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  170311. entropy->bitstate.bits_left = 0;
  170312. /* Advance past the RSTn marker */
  170313. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  170314. return FALSE;
  170315. /* Re-initialize DC predictions to 0 */
  170316. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  170317. entropy->saved.last_dc_val[ci] = 0;
  170318. /* Reset restart counter */
  170319. entropy->restarts_to_go = cinfo->restart_interval;
  170320. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  170321. * against a marker. In that case we will end up treating the next data
  170322. * segment as empty, and we can avoid producing bogus output pixels by
  170323. * leaving the flag set.
  170324. */
  170325. if (cinfo->unread_marker == 0)
  170326. entropy->pub.insufficient_data = FALSE;
  170327. return TRUE;
  170328. }
  170329. /*
  170330. * Decode and return one MCU's worth of Huffman-compressed coefficients.
  170331. * The coefficients are reordered from zigzag order into natural array order,
  170332. * but are not dequantized.
  170333. *
  170334. * The i'th block of the MCU is stored into the block pointed to by
  170335. * MCU_data[i]. WE ASSUME THIS AREA HAS BEEN ZEROED BY THE CALLER.
  170336. * (Wholesale zeroing is usually a little faster than retail...)
  170337. *
  170338. * Returns FALSE if data source requested suspension. In that case no
  170339. * changes have been made to permanent state. (Exception: some output
  170340. * coefficients may already have been assigned. This is harmless for
  170341. * this module, since we'll just re-assign them on the next call.)
  170342. */
  170343. METHODDEF(boolean)
  170344. decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  170345. {
  170346. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  170347. int blkn;
  170348. BITREAD_STATE_VARS;
  170349. savable_state2 state;
  170350. /* Process restart marker if needed; may have to suspend */
  170351. if (cinfo->restart_interval) {
  170352. if (entropy->restarts_to_go == 0)
  170353. if (! process_restart(cinfo))
  170354. return FALSE;
  170355. }
  170356. /* If we've run out of data, just leave the MCU set to zeroes.
  170357. * This way, we return uniform gray for the remainder of the segment.
  170358. */
  170359. if (! entropy->pub.insufficient_data) {
  170360. /* Load up working state */
  170361. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  170362. ASSIGN_STATE(state, entropy->saved);
  170363. /* Outer loop handles each block in the MCU */
  170364. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  170365. JBLOCKROW block = MCU_data[blkn];
  170366. d_derived_tbl * dctbl = entropy->dc_cur_tbls[blkn];
  170367. d_derived_tbl * actbl = entropy->ac_cur_tbls[blkn];
  170368. register int s, k, r;
  170369. /* Decode a single block's worth of coefficients */
  170370. /* Section F.2.2.1: decode the DC coefficient difference */
  170371. HUFF_DECODE(s, br_state, dctbl, return FALSE, label1);
  170372. if (s) {
  170373. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  170374. r = GET_BITS(s);
  170375. s = HUFF_EXTEND(r, s);
  170376. }
  170377. if (entropy->dc_needed[blkn]) {
  170378. /* Convert DC difference to actual value, update last_dc_val */
  170379. int ci = cinfo->MCU_membership[blkn];
  170380. s += state.last_dc_val[ci];
  170381. state.last_dc_val[ci] = s;
  170382. /* Output the DC coefficient (assumes jpeg_natural_order[0] = 0) */
  170383. (*block)[0] = (JCOEF) s;
  170384. }
  170385. if (entropy->ac_needed[blkn]) {
  170386. /* Section F.2.2.2: decode the AC coefficients */
  170387. /* Since zeroes are skipped, output area must be cleared beforehand */
  170388. for (k = 1; k < DCTSIZE2; k++) {
  170389. HUFF_DECODE(s, br_state, actbl, return FALSE, label2);
  170390. r = s >> 4;
  170391. s &= 15;
  170392. if (s) {
  170393. k += r;
  170394. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  170395. r = GET_BITS(s);
  170396. s = HUFF_EXTEND(r, s);
  170397. /* Output coefficient in natural (dezigzagged) order.
  170398. * Note: the extra entries in jpeg_natural_order[] will save us
  170399. * if k >= DCTSIZE2, which could happen if the data is corrupted.
  170400. */
  170401. (*block)[jpeg_natural_order[k]] = (JCOEF) s;
  170402. } else {
  170403. if (r != 15)
  170404. break;
  170405. k += 15;
  170406. }
  170407. }
  170408. } else {
  170409. /* Section F.2.2.2: decode the AC coefficients */
  170410. /* In this path we just discard the values */
  170411. for (k = 1; k < DCTSIZE2; k++) {
  170412. HUFF_DECODE(s, br_state, actbl, return FALSE, label3);
  170413. r = s >> 4;
  170414. s &= 15;
  170415. if (s) {
  170416. k += r;
  170417. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  170418. DROP_BITS(s);
  170419. } else {
  170420. if (r != 15)
  170421. break;
  170422. k += 15;
  170423. }
  170424. }
  170425. }
  170426. }
  170427. /* Completed MCU, so update state */
  170428. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  170429. ASSIGN_STATE(entropy->saved, state);
  170430. }
  170431. /* Account for restart interval (no-op if not using restarts) */
  170432. entropy->restarts_to_go--;
  170433. return TRUE;
  170434. }
  170435. /*
  170436. * Module initialization routine for Huffman entropy decoding.
  170437. */
  170438. GLOBAL(void)
  170439. jinit_huff_decoder (j_decompress_ptr cinfo)
  170440. {
  170441. huff_entropy_ptr2 entropy;
  170442. int i;
  170443. entropy = (huff_entropy_ptr2)
  170444. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170445. SIZEOF(huff_entropy_decoder2));
  170446. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  170447. entropy->pub.start_pass = start_pass_huff_decoder;
  170448. entropy->pub.decode_mcu = decode_mcu;
  170449. /* Mark tables unallocated */
  170450. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  170451. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  170452. }
  170453. }
  170454. /*** End of inlined file: jdhuff.c ***/
  170455. /*** Start of inlined file: jdinput.c ***/
  170456. #define JPEG_INTERNALS
  170457. /* Private state */
  170458. typedef struct {
  170459. struct jpeg_input_controller pub; /* public fields */
  170460. boolean inheaders; /* TRUE until first SOS is reached */
  170461. } my_input_controller;
  170462. typedef my_input_controller * my_inputctl_ptr;
  170463. /* Forward declarations */
  170464. METHODDEF(int) consume_markers JPP((j_decompress_ptr cinfo));
  170465. /*
  170466. * Routines to calculate various quantities related to the size of the image.
  170467. */
  170468. LOCAL(void)
  170469. initial_setup2 (j_decompress_ptr cinfo)
  170470. /* Called once, when first SOS marker is reached */
  170471. {
  170472. int ci;
  170473. jpeg_component_info *compptr;
  170474. /* Make sure image isn't bigger than I can handle */
  170475. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  170476. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  170477. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  170478. /* For now, precision must match compiled-in value... */
  170479. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  170480. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  170481. /* Check that number of components won't exceed internal array sizes */
  170482. if (cinfo->num_components > MAX_COMPONENTS)
  170483. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  170484. MAX_COMPONENTS);
  170485. /* Compute maximum sampling factors; check factor validity */
  170486. cinfo->max_h_samp_factor = 1;
  170487. cinfo->max_v_samp_factor = 1;
  170488. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170489. ci++, compptr++) {
  170490. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  170491. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  170492. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  170493. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  170494. compptr->h_samp_factor);
  170495. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  170496. compptr->v_samp_factor);
  170497. }
  170498. /* We initialize DCT_scaled_size and min_DCT_scaled_size to DCTSIZE.
  170499. * In the full decompressor, this will be overridden by jdmaster.c;
  170500. * but in the transcoder, jdmaster.c is not used, so we must do it here.
  170501. */
  170502. cinfo->min_DCT_scaled_size = DCTSIZE;
  170503. /* Compute dimensions of components */
  170504. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170505. ci++, compptr++) {
  170506. compptr->DCT_scaled_size = DCTSIZE;
  170507. /* Size in DCT blocks */
  170508. compptr->width_in_blocks = (JDIMENSION)
  170509. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  170510. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  170511. compptr->height_in_blocks = (JDIMENSION)
  170512. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  170513. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  170514. /* downsampled_width and downsampled_height will also be overridden by
  170515. * jdmaster.c if we are doing full decompression. The transcoder library
  170516. * doesn't use these values, but the calling application might.
  170517. */
  170518. /* Size in samples */
  170519. compptr->downsampled_width = (JDIMENSION)
  170520. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  170521. (long) cinfo->max_h_samp_factor);
  170522. compptr->downsampled_height = (JDIMENSION)
  170523. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  170524. (long) cinfo->max_v_samp_factor);
  170525. /* Mark component needed, until color conversion says otherwise */
  170526. compptr->component_needed = TRUE;
  170527. /* Mark no quantization table yet saved for component */
  170528. compptr->quant_table = NULL;
  170529. }
  170530. /* Compute number of fully interleaved MCU rows. */
  170531. cinfo->total_iMCU_rows = (JDIMENSION)
  170532. jdiv_round_up((long) cinfo->image_height,
  170533. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  170534. /* Decide whether file contains multiple scans */
  170535. if (cinfo->comps_in_scan < cinfo->num_components || cinfo->progressive_mode)
  170536. cinfo->inputctl->has_multiple_scans = TRUE;
  170537. else
  170538. cinfo->inputctl->has_multiple_scans = FALSE;
  170539. }
  170540. LOCAL(void)
  170541. per_scan_setup2 (j_decompress_ptr cinfo)
  170542. /* Do computations that are needed before processing a JPEG scan */
  170543. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] were set from SOS marker */
  170544. {
  170545. int ci, mcublks, tmp;
  170546. jpeg_component_info *compptr;
  170547. if (cinfo->comps_in_scan == 1) {
  170548. /* Noninterleaved (single-component) scan */
  170549. compptr = cinfo->cur_comp_info[0];
  170550. /* Overall image size in MCUs */
  170551. cinfo->MCUs_per_row = compptr->width_in_blocks;
  170552. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  170553. /* For noninterleaved scan, always one block per MCU */
  170554. compptr->MCU_width = 1;
  170555. compptr->MCU_height = 1;
  170556. compptr->MCU_blocks = 1;
  170557. compptr->MCU_sample_width = compptr->DCT_scaled_size;
  170558. compptr->last_col_width = 1;
  170559. /* For noninterleaved scans, it is convenient to define last_row_height
  170560. * as the number of block rows present in the last iMCU row.
  170561. */
  170562. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  170563. if (tmp == 0) tmp = compptr->v_samp_factor;
  170564. compptr->last_row_height = tmp;
  170565. /* Prepare array describing MCU composition */
  170566. cinfo->blocks_in_MCU = 1;
  170567. cinfo->MCU_membership[0] = 0;
  170568. } else {
  170569. /* Interleaved (multi-component) scan */
  170570. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  170571. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  170572. MAX_COMPS_IN_SCAN);
  170573. /* Overall image size in MCUs */
  170574. cinfo->MCUs_per_row = (JDIMENSION)
  170575. jdiv_round_up((long) cinfo->image_width,
  170576. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  170577. cinfo->MCU_rows_in_scan = (JDIMENSION)
  170578. jdiv_round_up((long) cinfo->image_height,
  170579. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  170580. cinfo->blocks_in_MCU = 0;
  170581. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  170582. compptr = cinfo->cur_comp_info[ci];
  170583. /* Sampling factors give # of blocks of component in each MCU */
  170584. compptr->MCU_width = compptr->h_samp_factor;
  170585. compptr->MCU_height = compptr->v_samp_factor;
  170586. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  170587. compptr->MCU_sample_width = compptr->MCU_width * compptr->DCT_scaled_size;
  170588. /* Figure number of non-dummy blocks in last MCU column & row */
  170589. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  170590. if (tmp == 0) tmp = compptr->MCU_width;
  170591. compptr->last_col_width = tmp;
  170592. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  170593. if (tmp == 0) tmp = compptr->MCU_height;
  170594. compptr->last_row_height = tmp;
  170595. /* Prepare array describing MCU composition */
  170596. mcublks = compptr->MCU_blocks;
  170597. if (cinfo->blocks_in_MCU + mcublks > D_MAX_BLOCKS_IN_MCU)
  170598. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  170599. while (mcublks-- > 0) {
  170600. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  170601. }
  170602. }
  170603. }
  170604. }
  170605. /*
  170606. * Save away a copy of the Q-table referenced by each component present
  170607. * in the current scan, unless already saved during a prior scan.
  170608. *
  170609. * In a multiple-scan JPEG file, the encoder could assign different components
  170610. * the same Q-table slot number, but change table definitions between scans
  170611. * so that each component uses a different Q-table. (The IJG encoder is not
  170612. * currently capable of doing this, but other encoders might.) Since we want
  170613. * to be able to dequantize all the components at the end of the file, this
  170614. * means that we have to save away the table actually used for each component.
  170615. * We do this by copying the table at the start of the first scan containing
  170616. * the component.
  170617. * The JPEG spec prohibits the encoder from changing the contents of a Q-table
  170618. * slot between scans of a component using that slot. If the encoder does so
  170619. * anyway, this decoder will simply use the Q-table values that were current
  170620. * at the start of the first scan for the component.
  170621. *
  170622. * The decompressor output side looks only at the saved quant tables,
  170623. * not at the current Q-table slots.
  170624. */
  170625. LOCAL(void)
  170626. latch_quant_tables (j_decompress_ptr cinfo)
  170627. {
  170628. int ci, qtblno;
  170629. jpeg_component_info *compptr;
  170630. JQUANT_TBL * qtbl;
  170631. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  170632. compptr = cinfo->cur_comp_info[ci];
  170633. /* No work if we already saved Q-table for this component */
  170634. if (compptr->quant_table != NULL)
  170635. continue;
  170636. /* Make sure specified quantization table is present */
  170637. qtblno = compptr->quant_tbl_no;
  170638. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  170639. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  170640. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  170641. /* OK, save away the quantization table */
  170642. qtbl = (JQUANT_TBL *)
  170643. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170644. SIZEOF(JQUANT_TBL));
  170645. MEMCOPY(qtbl, cinfo->quant_tbl_ptrs[qtblno], SIZEOF(JQUANT_TBL));
  170646. compptr->quant_table = qtbl;
  170647. }
  170648. }
  170649. /*
  170650. * Initialize the input modules to read a scan of compressed data.
  170651. * The first call to this is done by jdmaster.c after initializing
  170652. * the entire decompressor (during jpeg_start_decompress).
  170653. * Subsequent calls come from consume_markers, below.
  170654. */
  170655. METHODDEF(void)
  170656. start_input_pass2 (j_decompress_ptr cinfo)
  170657. {
  170658. per_scan_setup2(cinfo);
  170659. latch_quant_tables(cinfo);
  170660. (*cinfo->entropy->start_pass) (cinfo);
  170661. (*cinfo->coef->start_input_pass) (cinfo);
  170662. cinfo->inputctl->consume_input = cinfo->coef->consume_data;
  170663. }
  170664. /*
  170665. * Finish up after inputting a compressed-data scan.
  170666. * This is called by the coefficient controller after it's read all
  170667. * the expected data of the scan.
  170668. */
  170669. METHODDEF(void)
  170670. finish_input_pass (j_decompress_ptr cinfo)
  170671. {
  170672. cinfo->inputctl->consume_input = consume_markers;
  170673. }
  170674. /*
  170675. * Read JPEG markers before, between, or after compressed-data scans.
  170676. * Change state as necessary when a new scan is reached.
  170677. * Return value is JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  170678. *
  170679. * The consume_input method pointer points either here or to the
  170680. * coefficient controller's consume_data routine, depending on whether
  170681. * we are reading a compressed data segment or inter-segment markers.
  170682. */
  170683. METHODDEF(int)
  170684. consume_markers (j_decompress_ptr cinfo)
  170685. {
  170686. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  170687. int val;
  170688. if (inputctl->pub.eoi_reached) /* After hitting EOI, read no further */
  170689. return JPEG_REACHED_EOI;
  170690. val = (*cinfo->marker->read_markers) (cinfo);
  170691. switch (val) {
  170692. case JPEG_REACHED_SOS: /* Found SOS */
  170693. if (inputctl->inheaders) { /* 1st SOS */
  170694. initial_setup2(cinfo);
  170695. inputctl->inheaders = FALSE;
  170696. /* Note: start_input_pass must be called by jdmaster.c
  170697. * before any more input can be consumed. jdapimin.c is
  170698. * responsible for enforcing this sequencing.
  170699. */
  170700. } else { /* 2nd or later SOS marker */
  170701. if (! inputctl->pub.has_multiple_scans)
  170702. ERREXIT(cinfo, JERR_EOI_EXPECTED); /* Oops, I wasn't expecting this! */
  170703. start_input_pass2(cinfo);
  170704. }
  170705. break;
  170706. case JPEG_REACHED_EOI: /* Found EOI */
  170707. inputctl->pub.eoi_reached = TRUE;
  170708. if (inputctl->inheaders) { /* Tables-only datastream, apparently */
  170709. if (cinfo->marker->saw_SOF)
  170710. ERREXIT(cinfo, JERR_SOF_NO_SOS);
  170711. } else {
  170712. /* Prevent infinite loop in coef ctlr's decompress_data routine
  170713. * if user set output_scan_number larger than number of scans.
  170714. */
  170715. if (cinfo->output_scan_number > cinfo->input_scan_number)
  170716. cinfo->output_scan_number = cinfo->input_scan_number;
  170717. }
  170718. break;
  170719. case JPEG_SUSPENDED:
  170720. break;
  170721. }
  170722. return val;
  170723. }
  170724. /*
  170725. * Reset state to begin a fresh datastream.
  170726. */
  170727. METHODDEF(void)
  170728. reset_input_controller (j_decompress_ptr cinfo)
  170729. {
  170730. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  170731. inputctl->pub.consume_input = consume_markers;
  170732. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  170733. inputctl->pub.eoi_reached = FALSE;
  170734. inputctl->inheaders = TRUE;
  170735. /* Reset other modules */
  170736. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  170737. (*cinfo->marker->reset_marker_reader) (cinfo);
  170738. /* Reset progression state -- would be cleaner if entropy decoder did this */
  170739. cinfo->coef_bits = NULL;
  170740. }
  170741. /*
  170742. * Initialize the input controller module.
  170743. * This is called only once, when the decompression object is created.
  170744. */
  170745. GLOBAL(void)
  170746. jinit_input_controller (j_decompress_ptr cinfo)
  170747. {
  170748. my_inputctl_ptr inputctl;
  170749. /* Create subobject in permanent pool */
  170750. inputctl = (my_inputctl_ptr)
  170751. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  170752. SIZEOF(my_input_controller));
  170753. cinfo->inputctl = (struct jpeg_input_controller *) inputctl;
  170754. /* Initialize method pointers */
  170755. inputctl->pub.consume_input = consume_markers;
  170756. inputctl->pub.reset_input_controller = reset_input_controller;
  170757. inputctl->pub.start_input_pass = start_input_pass2;
  170758. inputctl->pub.finish_input_pass = finish_input_pass;
  170759. /* Initialize state: can't use reset_input_controller since we don't
  170760. * want to try to reset other modules yet.
  170761. */
  170762. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  170763. inputctl->pub.eoi_reached = FALSE;
  170764. inputctl->inheaders = TRUE;
  170765. }
  170766. /*** End of inlined file: jdinput.c ***/
  170767. /*** Start of inlined file: jdmainct.c ***/
  170768. #define JPEG_INTERNALS
  170769. /*
  170770. * In the current system design, the main buffer need never be a full-image
  170771. * buffer; any full-height buffers will be found inside the coefficient or
  170772. * postprocessing controllers. Nonetheless, the main controller is not
  170773. * trivial. Its responsibility is to provide context rows for upsampling/
  170774. * rescaling, and doing this in an efficient fashion is a bit tricky.
  170775. *
  170776. * Postprocessor input data is counted in "row groups". A row group
  170777. * is defined to be (v_samp_factor * DCT_scaled_size / min_DCT_scaled_size)
  170778. * sample rows of each component. (We require DCT_scaled_size values to be
  170779. * chosen such that these numbers are integers. In practice DCT_scaled_size
  170780. * values will likely be powers of two, so we actually have the stronger
  170781. * condition that DCT_scaled_size / min_DCT_scaled_size is an integer.)
  170782. * Upsampling will typically produce max_v_samp_factor pixel rows from each
  170783. * row group (times any additional scale factor that the upsampler is
  170784. * applying).
  170785. *
  170786. * The coefficient controller will deliver data to us one iMCU row at a time;
  170787. * each iMCU row contains v_samp_factor * DCT_scaled_size sample rows, or
  170788. * exactly min_DCT_scaled_size row groups. (This amount of data corresponds
  170789. * to one row of MCUs when the image is fully interleaved.) Note that the
  170790. * number of sample rows varies across components, but the number of row
  170791. * groups does not. Some garbage sample rows may be included in the last iMCU
  170792. * row at the bottom of the image.
  170793. *
  170794. * Depending on the vertical scaling algorithm used, the upsampler may need
  170795. * access to the sample row(s) above and below its current input row group.
  170796. * The upsampler is required to set need_context_rows TRUE at global selection
  170797. * time if so. When need_context_rows is FALSE, this controller can simply
  170798. * obtain one iMCU row at a time from the coefficient controller and dole it
  170799. * out as row groups to the postprocessor.
  170800. *
  170801. * When need_context_rows is TRUE, this controller guarantees that the buffer
  170802. * passed to postprocessing contains at least one row group's worth of samples
  170803. * above and below the row group(s) being processed. Note that the context
  170804. * rows "above" the first passed row group appear at negative row offsets in
  170805. * the passed buffer. At the top and bottom of the image, the required
  170806. * context rows are manufactured by duplicating the first or last real sample
  170807. * row; this avoids having special cases in the upsampling inner loops.
  170808. *
  170809. * The amount of context is fixed at one row group just because that's a
  170810. * convenient number for this controller to work with. The existing
  170811. * upsamplers really only need one sample row of context. An upsampler
  170812. * supporting arbitrary output rescaling might wish for more than one row
  170813. * group of context when shrinking the image; tough, we don't handle that.
  170814. * (This is justified by the assumption that downsizing will be handled mostly
  170815. * by adjusting the DCT_scaled_size values, so that the actual scale factor at
  170816. * the upsample step needn't be much less than one.)
  170817. *
  170818. * To provide the desired context, we have to retain the last two row groups
  170819. * of one iMCU row while reading in the next iMCU row. (The last row group
  170820. * can't be processed until we have another row group for its below-context,
  170821. * and so we have to save the next-to-last group too for its above-context.)
  170822. * We could do this most simply by copying data around in our buffer, but
  170823. * that'd be very slow. We can avoid copying any data by creating a rather
  170824. * strange pointer structure. Here's how it works. We allocate a workspace
  170825. * consisting of M+2 row groups (where M = min_DCT_scaled_size is the number
  170826. * of row groups per iMCU row). We create two sets of redundant pointers to
  170827. * the workspace. Labeling the physical row groups 0 to M+1, the synthesized
  170828. * pointer lists look like this:
  170829. * M+1 M-1
  170830. * master pointer --> 0 master pointer --> 0
  170831. * 1 1
  170832. * ... ...
  170833. * M-3 M-3
  170834. * M-2 M
  170835. * M-1 M+1
  170836. * M M-2
  170837. * M+1 M-1
  170838. * 0 0
  170839. * We read alternate iMCU rows using each master pointer; thus the last two
  170840. * row groups of the previous iMCU row remain un-overwritten in the workspace.
  170841. * The pointer lists are set up so that the required context rows appear to
  170842. * be adjacent to the proper places when we pass the pointer lists to the
  170843. * upsampler.
  170844. *
  170845. * The above pictures describe the normal state of the pointer lists.
  170846. * At top and bottom of the image, we diddle the pointer lists to duplicate
  170847. * the first or last sample row as necessary (this is cheaper than copying
  170848. * sample rows around).
  170849. *
  170850. * This scheme breaks down if M < 2, ie, min_DCT_scaled_size is 1. In that
  170851. * situation each iMCU row provides only one row group so the buffering logic
  170852. * must be different (eg, we must read two iMCU rows before we can emit the
  170853. * first row group). For now, we simply do not support providing context
  170854. * rows when min_DCT_scaled_size is 1. That combination seems unlikely to
  170855. * be worth providing --- if someone wants a 1/8th-size preview, they probably
  170856. * want it quick and dirty, so a context-free upsampler is sufficient.
  170857. */
  170858. /* Private buffer controller object */
  170859. typedef struct {
  170860. struct jpeg_d_main_controller pub; /* public fields */
  170861. /* Pointer to allocated workspace (M or M+2 row groups). */
  170862. JSAMPARRAY buffer[MAX_COMPONENTS];
  170863. boolean buffer_full; /* Have we gotten an iMCU row from decoder? */
  170864. JDIMENSION rowgroup_ctr; /* counts row groups output to postprocessor */
  170865. /* Remaining fields are only used in the context case. */
  170866. /* These are the master pointers to the funny-order pointer lists. */
  170867. JSAMPIMAGE xbuffer[2]; /* pointers to weird pointer lists */
  170868. int whichptr; /* indicates which pointer set is now in use */
  170869. int context_state; /* process_data state machine status */
  170870. JDIMENSION rowgroups_avail; /* row groups available to postprocessor */
  170871. JDIMENSION iMCU_row_ctr; /* counts iMCU rows to detect image top/bot */
  170872. } my_main_controller4;
  170873. typedef my_main_controller4 * my_main_ptr4;
  170874. /* context_state values: */
  170875. #define CTX_PREPARE_FOR_IMCU 0 /* need to prepare for MCU row */
  170876. #define CTX_PROCESS_IMCU 1 /* feeding iMCU to postprocessor */
  170877. #define CTX_POSTPONED_ROW 2 /* feeding postponed row group */
  170878. /* Forward declarations */
  170879. METHODDEF(void) process_data_simple_main2
  170880. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  170881. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  170882. METHODDEF(void) process_data_context_main
  170883. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  170884. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  170885. #ifdef QUANT_2PASS_SUPPORTED
  170886. METHODDEF(void) process_data_crank_post
  170887. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  170888. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  170889. #endif
  170890. LOCAL(void)
  170891. alloc_funny_pointers (j_decompress_ptr cinfo)
  170892. /* Allocate space for the funny pointer lists.
  170893. * This is done only once, not once per pass.
  170894. */
  170895. {
  170896. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170897. int ci, rgroup;
  170898. int M = cinfo->min_DCT_scaled_size;
  170899. jpeg_component_info *compptr;
  170900. JSAMPARRAY xbuf;
  170901. /* Get top-level space for component array pointers.
  170902. * We alloc both arrays with one call to save a few cycles.
  170903. */
  170904. main_->xbuffer[0] = (JSAMPIMAGE)
  170905. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170906. cinfo->num_components * 2 * SIZEOF(JSAMPARRAY));
  170907. main_->xbuffer[1] = main_->xbuffer[0] + cinfo->num_components;
  170908. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170909. ci++, compptr++) {
  170910. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170911. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170912. /* Get space for pointer lists --- M+4 row groups in each list.
  170913. * We alloc both pointer lists with one call to save a few cycles.
  170914. */
  170915. xbuf = (JSAMPARRAY)
  170916. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170917. 2 * (rgroup * (M + 4)) * SIZEOF(JSAMPROW));
  170918. xbuf += rgroup; /* want one row group at negative offsets */
  170919. main_->xbuffer[0][ci] = xbuf;
  170920. xbuf += rgroup * (M + 4);
  170921. main_->xbuffer[1][ci] = xbuf;
  170922. }
  170923. }
  170924. LOCAL(void)
  170925. make_funny_pointers (j_decompress_ptr cinfo)
  170926. /* Create the funny pointer lists discussed in the comments above.
  170927. * The actual workspace is already allocated (in main->buffer),
  170928. * and the space for the pointer lists is allocated too.
  170929. * This routine just fills in the curiously ordered lists.
  170930. * This will be repeated at the beginning of each pass.
  170931. */
  170932. {
  170933. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170934. int ci, i, rgroup;
  170935. int M = cinfo->min_DCT_scaled_size;
  170936. jpeg_component_info *compptr;
  170937. JSAMPARRAY buf, xbuf0, xbuf1;
  170938. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170939. ci++, compptr++) {
  170940. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170941. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170942. xbuf0 = main_->xbuffer[0][ci];
  170943. xbuf1 = main_->xbuffer[1][ci];
  170944. /* First copy the workspace pointers as-is */
  170945. buf = main_->buffer[ci];
  170946. for (i = 0; i < rgroup * (M + 2); i++) {
  170947. xbuf0[i] = xbuf1[i] = buf[i];
  170948. }
  170949. /* In the second list, put the last four row groups in swapped order */
  170950. for (i = 0; i < rgroup * 2; i++) {
  170951. xbuf1[rgroup*(M-2) + i] = buf[rgroup*M + i];
  170952. xbuf1[rgroup*M + i] = buf[rgroup*(M-2) + i];
  170953. }
  170954. /* The wraparound pointers at top and bottom will be filled later
  170955. * (see set_wraparound_pointers, below). Initially we want the "above"
  170956. * pointers to duplicate the first actual data line. This only needs
  170957. * to happen in xbuffer[0].
  170958. */
  170959. for (i = 0; i < rgroup; i++) {
  170960. xbuf0[i - rgroup] = xbuf0[0];
  170961. }
  170962. }
  170963. }
  170964. LOCAL(void)
  170965. set_wraparound_pointers (j_decompress_ptr cinfo)
  170966. /* Set up the "wraparound" pointers at top and bottom of the pointer lists.
  170967. * This changes the pointer list state from top-of-image to the normal state.
  170968. */
  170969. {
  170970. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170971. int ci, i, rgroup;
  170972. int M = cinfo->min_DCT_scaled_size;
  170973. jpeg_component_info *compptr;
  170974. JSAMPARRAY xbuf0, xbuf1;
  170975. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170976. ci++, compptr++) {
  170977. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170978. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170979. xbuf0 = main_->xbuffer[0][ci];
  170980. xbuf1 = main_->xbuffer[1][ci];
  170981. for (i = 0; i < rgroup; i++) {
  170982. xbuf0[i - rgroup] = xbuf0[rgroup*(M+1) + i];
  170983. xbuf1[i - rgroup] = xbuf1[rgroup*(M+1) + i];
  170984. xbuf0[rgroup*(M+2) + i] = xbuf0[i];
  170985. xbuf1[rgroup*(M+2) + i] = xbuf1[i];
  170986. }
  170987. }
  170988. }
  170989. LOCAL(void)
  170990. set_bottom_pointers (j_decompress_ptr cinfo)
  170991. /* Change the pointer lists to duplicate the last sample row at the bottom
  170992. * of the image. whichptr indicates which xbuffer holds the final iMCU row.
  170993. * Also sets rowgroups_avail to indicate number of nondummy row groups in row.
  170994. */
  170995. {
  170996. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170997. int ci, i, rgroup, iMCUheight, rows_left;
  170998. jpeg_component_info *compptr;
  170999. JSAMPARRAY xbuf;
  171000. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171001. ci++, compptr++) {
  171002. /* Count sample rows in one iMCU row and in one row group */
  171003. iMCUheight = compptr->v_samp_factor * compptr->DCT_scaled_size;
  171004. rgroup = iMCUheight / cinfo->min_DCT_scaled_size;
  171005. /* Count nondummy sample rows remaining for this component */
  171006. rows_left = (int) (compptr->downsampled_height % (JDIMENSION) iMCUheight);
  171007. if (rows_left == 0) rows_left = iMCUheight;
  171008. /* Count nondummy row groups. Should get same answer for each component,
  171009. * so we need only do it once.
  171010. */
  171011. if (ci == 0) {
  171012. main_->rowgroups_avail = (JDIMENSION) ((rows_left-1) / rgroup + 1);
  171013. }
  171014. /* Duplicate the last real sample row rgroup*2 times; this pads out the
  171015. * last partial rowgroup and ensures at least one full rowgroup of context.
  171016. */
  171017. xbuf = main_->xbuffer[main_->whichptr][ci];
  171018. for (i = 0; i < rgroup * 2; i++) {
  171019. xbuf[rows_left + i] = xbuf[rows_left-1];
  171020. }
  171021. }
  171022. }
  171023. /*
  171024. * Initialize for a processing pass.
  171025. */
  171026. METHODDEF(void)
  171027. start_pass_main2 (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  171028. {
  171029. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  171030. switch (pass_mode) {
  171031. case JBUF_PASS_THRU:
  171032. if (cinfo->upsample->need_context_rows) {
  171033. main_->pub.process_data = process_data_context_main;
  171034. make_funny_pointers(cinfo); /* Create the xbuffer[] lists */
  171035. main_->whichptr = 0; /* Read first iMCU row into xbuffer[0] */
  171036. main_->context_state = CTX_PREPARE_FOR_IMCU;
  171037. main_->iMCU_row_ctr = 0;
  171038. } else {
  171039. /* Simple case with no context needed */
  171040. main_->pub.process_data = process_data_simple_main2;
  171041. }
  171042. main_->buffer_full = FALSE; /* Mark buffer empty */
  171043. main_->rowgroup_ctr = 0;
  171044. break;
  171045. #ifdef QUANT_2PASS_SUPPORTED
  171046. case JBUF_CRANK_DEST:
  171047. /* For last pass of 2-pass quantization, just crank the postprocessor */
  171048. main_->pub.process_data = process_data_crank_post;
  171049. break;
  171050. #endif
  171051. default:
  171052. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  171053. break;
  171054. }
  171055. }
  171056. /*
  171057. * Process some data.
  171058. * This handles the simple case where no context is required.
  171059. */
  171060. METHODDEF(void)
  171061. process_data_simple_main2 (j_decompress_ptr cinfo,
  171062. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  171063. JDIMENSION out_rows_avail)
  171064. {
  171065. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  171066. JDIMENSION rowgroups_avail;
  171067. /* Read input data if we haven't filled the main buffer yet */
  171068. if (! main_->buffer_full) {
  171069. if (! (*cinfo->coef->decompress_data) (cinfo, main_->buffer))
  171070. return; /* suspension forced, can do nothing more */
  171071. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  171072. }
  171073. /* There are always min_DCT_scaled_size row groups in an iMCU row. */
  171074. rowgroups_avail = (JDIMENSION) cinfo->min_DCT_scaled_size;
  171075. /* Note: at the bottom of the image, we may pass extra garbage row groups
  171076. * to the postprocessor. The postprocessor has to check for bottom
  171077. * of image anyway (at row resolution), so no point in us doing it too.
  171078. */
  171079. /* Feed the postprocessor */
  171080. (*cinfo->post->post_process_data) (cinfo, main_->buffer,
  171081. &main_->rowgroup_ctr, rowgroups_avail,
  171082. output_buf, out_row_ctr, out_rows_avail);
  171083. /* Has postprocessor consumed all the data yet? If so, mark buffer empty */
  171084. if (main_->rowgroup_ctr >= rowgroups_avail) {
  171085. main_->buffer_full = FALSE;
  171086. main_->rowgroup_ctr = 0;
  171087. }
  171088. }
  171089. /*
  171090. * Process some data.
  171091. * This handles the case where context rows must be provided.
  171092. */
  171093. METHODDEF(void)
  171094. process_data_context_main (j_decompress_ptr cinfo,
  171095. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  171096. JDIMENSION out_rows_avail)
  171097. {
  171098. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  171099. /* Read input data if we haven't filled the main buffer yet */
  171100. if (! main_->buffer_full) {
  171101. if (! (*cinfo->coef->decompress_data) (cinfo,
  171102. main_->xbuffer[main_->whichptr]))
  171103. return; /* suspension forced, can do nothing more */
  171104. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  171105. main_->iMCU_row_ctr++; /* count rows received */
  171106. }
  171107. /* Postprocessor typically will not swallow all the input data it is handed
  171108. * in one call (due to filling the output buffer first). Must be prepared
  171109. * to exit and restart. This switch lets us keep track of how far we got.
  171110. * Note that each case falls through to the next on successful completion.
  171111. */
  171112. switch (main_->context_state) {
  171113. case CTX_POSTPONED_ROW:
  171114. /* Call postprocessor using previously set pointers for postponed row */
  171115. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  171116. &main_->rowgroup_ctr, main_->rowgroups_avail,
  171117. output_buf, out_row_ctr, out_rows_avail);
  171118. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  171119. return; /* Need to suspend */
  171120. main_->context_state = CTX_PREPARE_FOR_IMCU;
  171121. if (*out_row_ctr >= out_rows_avail)
  171122. return; /* Postprocessor exactly filled output buf */
  171123. /*FALLTHROUGH*/
  171124. case CTX_PREPARE_FOR_IMCU:
  171125. /* Prepare to process first M-1 row groups of this iMCU row */
  171126. main_->rowgroup_ctr = 0;
  171127. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size - 1);
  171128. /* Check for bottom of image: if so, tweak pointers to "duplicate"
  171129. * the last sample row, and adjust rowgroups_avail to ignore padding rows.
  171130. */
  171131. if (main_->iMCU_row_ctr == cinfo->total_iMCU_rows)
  171132. set_bottom_pointers(cinfo);
  171133. main_->context_state = CTX_PROCESS_IMCU;
  171134. /*FALLTHROUGH*/
  171135. case CTX_PROCESS_IMCU:
  171136. /* Call postprocessor using previously set pointers */
  171137. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  171138. &main_->rowgroup_ctr, main_->rowgroups_avail,
  171139. output_buf, out_row_ctr, out_rows_avail);
  171140. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  171141. return; /* Need to suspend */
  171142. /* After the first iMCU, change wraparound pointers to normal state */
  171143. if (main_->iMCU_row_ctr == 1)
  171144. set_wraparound_pointers(cinfo);
  171145. /* Prepare to load new iMCU row using other xbuffer list */
  171146. main_->whichptr ^= 1; /* 0=>1 or 1=>0 */
  171147. main_->buffer_full = FALSE;
  171148. /* Still need to process last row group of this iMCU row, */
  171149. /* which is saved at index M+1 of the other xbuffer */
  171150. main_->rowgroup_ctr = (JDIMENSION) (cinfo->min_DCT_scaled_size + 1);
  171151. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size + 2);
  171152. main_->context_state = CTX_POSTPONED_ROW;
  171153. }
  171154. }
  171155. /*
  171156. * Process some data.
  171157. * Final pass of two-pass quantization: just call the postprocessor.
  171158. * Source data will be the postprocessor controller's internal buffer.
  171159. */
  171160. #ifdef QUANT_2PASS_SUPPORTED
  171161. METHODDEF(void)
  171162. process_data_crank_post (j_decompress_ptr cinfo,
  171163. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  171164. JDIMENSION out_rows_avail)
  171165. {
  171166. (*cinfo->post->post_process_data) (cinfo, (JSAMPIMAGE) NULL,
  171167. (JDIMENSION *) NULL, (JDIMENSION) 0,
  171168. output_buf, out_row_ctr, out_rows_avail);
  171169. }
  171170. #endif /* QUANT_2PASS_SUPPORTED */
  171171. /*
  171172. * Initialize main buffer controller.
  171173. */
  171174. GLOBAL(void)
  171175. jinit_d_main_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  171176. {
  171177. my_main_ptr4 main_;
  171178. int ci, rgroup, ngroups;
  171179. jpeg_component_info *compptr;
  171180. main_ = (my_main_ptr4)
  171181. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171182. SIZEOF(my_main_controller4));
  171183. cinfo->main = (struct jpeg_d_main_controller *) main_;
  171184. main_->pub.start_pass = start_pass_main2;
  171185. if (need_full_buffer) /* shouldn't happen */
  171186. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  171187. /* Allocate the workspace.
  171188. * ngroups is the number of row groups we need.
  171189. */
  171190. if (cinfo->upsample->need_context_rows) {
  171191. if (cinfo->min_DCT_scaled_size < 2) /* unsupported, see comments above */
  171192. ERREXIT(cinfo, JERR_NOTIMPL);
  171193. alloc_funny_pointers(cinfo); /* Alloc space for xbuffer[] lists */
  171194. ngroups = cinfo->min_DCT_scaled_size + 2;
  171195. } else {
  171196. ngroups = cinfo->min_DCT_scaled_size;
  171197. }
  171198. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171199. ci++, compptr++) {
  171200. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  171201. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  171202. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  171203. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171204. compptr->width_in_blocks * compptr->DCT_scaled_size,
  171205. (JDIMENSION) (rgroup * ngroups));
  171206. }
  171207. }
  171208. /*** End of inlined file: jdmainct.c ***/
  171209. /*** Start of inlined file: jdmarker.c ***/
  171210. #define JPEG_INTERNALS
  171211. /* Private state */
  171212. typedef struct {
  171213. struct jpeg_marker_reader pub; /* public fields */
  171214. /* Application-overridable marker processing methods */
  171215. jpeg_marker_parser_method process_COM;
  171216. jpeg_marker_parser_method process_APPn[16];
  171217. /* Limit on marker data length to save for each marker type */
  171218. unsigned int length_limit_COM;
  171219. unsigned int length_limit_APPn[16];
  171220. /* Status of COM/APPn marker saving */
  171221. jpeg_saved_marker_ptr cur_marker; /* NULL if not processing a marker */
  171222. unsigned int bytes_read; /* data bytes read so far in marker */
  171223. /* Note: cur_marker is not linked into marker_list until it's all read. */
  171224. } my_marker_reader;
  171225. typedef my_marker_reader * my_marker_ptr2;
  171226. /*
  171227. * Macros for fetching data from the data source module.
  171228. *
  171229. * At all times, cinfo->src->next_input_byte and ->bytes_in_buffer reflect
  171230. * the current restart point; we update them only when we have reached a
  171231. * suitable place to restart if a suspension occurs.
  171232. */
  171233. /* Declare and initialize local copies of input pointer/count */
  171234. #define INPUT_VARS(cinfo) \
  171235. struct jpeg_source_mgr * datasrc = (cinfo)->src; \
  171236. const JOCTET * next_input_byte = datasrc->next_input_byte; \
  171237. size_t bytes_in_buffer = datasrc->bytes_in_buffer
  171238. /* Unload the local copies --- do this only at a restart boundary */
  171239. #define INPUT_SYNC(cinfo) \
  171240. ( datasrc->next_input_byte = next_input_byte, \
  171241. datasrc->bytes_in_buffer = bytes_in_buffer )
  171242. /* Reload the local copies --- used only in MAKE_BYTE_AVAIL */
  171243. #define INPUT_RELOAD(cinfo) \
  171244. ( next_input_byte = datasrc->next_input_byte, \
  171245. bytes_in_buffer = datasrc->bytes_in_buffer )
  171246. /* Internal macro for INPUT_BYTE and INPUT_2BYTES: make a byte available.
  171247. * Note we do *not* do INPUT_SYNC before calling fill_input_buffer,
  171248. * but we must reload the local copies after a successful fill.
  171249. */
  171250. #define MAKE_BYTE_AVAIL(cinfo,action) \
  171251. if (bytes_in_buffer == 0) { \
  171252. if (! (*datasrc->fill_input_buffer) (cinfo)) \
  171253. { action; } \
  171254. INPUT_RELOAD(cinfo); \
  171255. }
  171256. /* Read a byte into variable V.
  171257. * If must suspend, take the specified action (typically "return FALSE").
  171258. */
  171259. #define INPUT_BYTE(cinfo,V,action) \
  171260. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  171261. bytes_in_buffer--; \
  171262. V = GETJOCTET(*next_input_byte++); )
  171263. /* As above, but read two bytes interpreted as an unsigned 16-bit integer.
  171264. * V should be declared unsigned int or perhaps INT32.
  171265. */
  171266. #define INPUT_2BYTES(cinfo,V,action) \
  171267. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  171268. bytes_in_buffer--; \
  171269. V = ((unsigned int) GETJOCTET(*next_input_byte++)) << 8; \
  171270. MAKE_BYTE_AVAIL(cinfo,action); \
  171271. bytes_in_buffer--; \
  171272. V += GETJOCTET(*next_input_byte++); )
  171273. /*
  171274. * Routines to process JPEG markers.
  171275. *
  171276. * Entry condition: JPEG marker itself has been read and its code saved
  171277. * in cinfo->unread_marker; input restart point is just after the marker.
  171278. *
  171279. * Exit: if return TRUE, have read and processed any parameters, and have
  171280. * updated the restart point to point after the parameters.
  171281. * If return FALSE, was forced to suspend before reaching end of
  171282. * marker parameters; restart point has not been moved. Same routine
  171283. * will be called again after application supplies more input data.
  171284. *
  171285. * This approach to suspension assumes that all of a marker's parameters
  171286. * can fit into a single input bufferload. This should hold for "normal"
  171287. * markers. Some COM/APPn markers might have large parameter segments
  171288. * that might not fit. If we are simply dropping such a marker, we use
  171289. * skip_input_data to get past it, and thereby put the problem on the
  171290. * source manager's shoulders. If we are saving the marker's contents
  171291. * into memory, we use a slightly different convention: when forced to
  171292. * suspend, the marker processor updates the restart point to the end of
  171293. * what it's consumed (ie, the end of the buffer) before returning FALSE.
  171294. * On resumption, cinfo->unread_marker still contains the marker code,
  171295. * but the data source will point to the next chunk of marker data.
  171296. * The marker processor must retain internal state to deal with this.
  171297. *
  171298. * Note that we don't bother to avoid duplicate trace messages if a
  171299. * suspension occurs within marker parameters. Other side effects
  171300. * require more care.
  171301. */
  171302. LOCAL(boolean)
  171303. get_soi (j_decompress_ptr cinfo)
  171304. /* Process an SOI marker */
  171305. {
  171306. int i;
  171307. TRACEMS(cinfo, 1, JTRC_SOI);
  171308. if (cinfo->marker->saw_SOI)
  171309. ERREXIT(cinfo, JERR_SOI_DUPLICATE);
  171310. /* Reset all parameters that are defined to be reset by SOI */
  171311. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  171312. cinfo->arith_dc_L[i] = 0;
  171313. cinfo->arith_dc_U[i] = 1;
  171314. cinfo->arith_ac_K[i] = 5;
  171315. }
  171316. cinfo->restart_interval = 0;
  171317. /* Set initial assumptions for colorspace etc */
  171318. cinfo->jpeg_color_space = JCS_UNKNOWN;
  171319. cinfo->CCIR601_sampling = FALSE; /* Assume non-CCIR sampling??? */
  171320. cinfo->saw_JFIF_marker = FALSE;
  171321. cinfo->JFIF_major_version = 1; /* set default JFIF APP0 values */
  171322. cinfo->JFIF_minor_version = 1;
  171323. cinfo->density_unit = 0;
  171324. cinfo->X_density = 1;
  171325. cinfo->Y_density = 1;
  171326. cinfo->saw_Adobe_marker = FALSE;
  171327. cinfo->Adobe_transform = 0;
  171328. cinfo->marker->saw_SOI = TRUE;
  171329. return TRUE;
  171330. }
  171331. LOCAL(boolean)
  171332. get_sof (j_decompress_ptr cinfo, boolean is_prog, boolean is_arith)
  171333. /* Process a SOFn marker */
  171334. {
  171335. INT32 length;
  171336. int c, ci;
  171337. jpeg_component_info * compptr;
  171338. INPUT_VARS(cinfo);
  171339. cinfo->progressive_mode = is_prog;
  171340. cinfo->arith_code = is_arith;
  171341. INPUT_2BYTES(cinfo, length, return FALSE);
  171342. INPUT_BYTE(cinfo, cinfo->data_precision, return FALSE);
  171343. INPUT_2BYTES(cinfo, cinfo->image_height, return FALSE);
  171344. INPUT_2BYTES(cinfo, cinfo->image_width, return FALSE);
  171345. INPUT_BYTE(cinfo, cinfo->num_components, return FALSE);
  171346. length -= 8;
  171347. TRACEMS4(cinfo, 1, JTRC_SOF, cinfo->unread_marker,
  171348. (int) cinfo->image_width, (int) cinfo->image_height,
  171349. cinfo->num_components);
  171350. if (cinfo->marker->saw_SOF)
  171351. ERREXIT(cinfo, JERR_SOF_DUPLICATE);
  171352. /* We don't support files in which the image height is initially specified */
  171353. /* as 0 and is later redefined by DNL. As long as we have to check that, */
  171354. /* might as well have a general sanity check. */
  171355. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  171356. || cinfo->num_components <= 0)
  171357. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  171358. if (length != (cinfo->num_components * 3))
  171359. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171360. if (cinfo->comp_info == NULL) /* do only once, even if suspend */
  171361. cinfo->comp_info = (jpeg_component_info *) (*cinfo->mem->alloc_small)
  171362. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171363. cinfo->num_components * SIZEOF(jpeg_component_info));
  171364. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171365. ci++, compptr++) {
  171366. compptr->component_index = ci;
  171367. INPUT_BYTE(cinfo, compptr->component_id, return FALSE);
  171368. INPUT_BYTE(cinfo, c, return FALSE);
  171369. compptr->h_samp_factor = (c >> 4) & 15;
  171370. compptr->v_samp_factor = (c ) & 15;
  171371. INPUT_BYTE(cinfo, compptr->quant_tbl_no, return FALSE);
  171372. TRACEMS4(cinfo, 1, JTRC_SOF_COMPONENT,
  171373. compptr->component_id, compptr->h_samp_factor,
  171374. compptr->v_samp_factor, compptr->quant_tbl_no);
  171375. }
  171376. cinfo->marker->saw_SOF = TRUE;
  171377. INPUT_SYNC(cinfo);
  171378. return TRUE;
  171379. }
  171380. LOCAL(boolean)
  171381. get_sos (j_decompress_ptr cinfo)
  171382. /* Process a SOS marker */
  171383. {
  171384. INT32 length;
  171385. int i, ci, n, c, cc;
  171386. jpeg_component_info * compptr;
  171387. INPUT_VARS(cinfo);
  171388. if (! cinfo->marker->saw_SOF)
  171389. ERREXIT(cinfo, JERR_SOS_NO_SOF);
  171390. INPUT_2BYTES(cinfo, length, return FALSE);
  171391. INPUT_BYTE(cinfo, n, return FALSE); /* Number of components */
  171392. TRACEMS1(cinfo, 1, JTRC_SOS, n);
  171393. if (length != (n * 2 + 6) || n < 1 || n > MAX_COMPS_IN_SCAN)
  171394. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171395. cinfo->comps_in_scan = n;
  171396. /* Collect the component-spec parameters */
  171397. for (i = 0; i < n; i++) {
  171398. INPUT_BYTE(cinfo, cc, return FALSE);
  171399. INPUT_BYTE(cinfo, c, return FALSE);
  171400. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171401. ci++, compptr++) {
  171402. if (cc == compptr->component_id)
  171403. goto id_found;
  171404. }
  171405. ERREXIT1(cinfo, JERR_BAD_COMPONENT_ID, cc);
  171406. id_found:
  171407. cinfo->cur_comp_info[i] = compptr;
  171408. compptr->dc_tbl_no = (c >> 4) & 15;
  171409. compptr->ac_tbl_no = (c ) & 15;
  171410. TRACEMS3(cinfo, 1, JTRC_SOS_COMPONENT, cc,
  171411. compptr->dc_tbl_no, compptr->ac_tbl_no);
  171412. }
  171413. /* Collect the additional scan parameters Ss, Se, Ah/Al. */
  171414. INPUT_BYTE(cinfo, c, return FALSE);
  171415. cinfo->Ss = c;
  171416. INPUT_BYTE(cinfo, c, return FALSE);
  171417. cinfo->Se = c;
  171418. INPUT_BYTE(cinfo, c, return FALSE);
  171419. cinfo->Ah = (c >> 4) & 15;
  171420. cinfo->Al = (c ) & 15;
  171421. TRACEMS4(cinfo, 1, JTRC_SOS_PARAMS, cinfo->Ss, cinfo->Se,
  171422. cinfo->Ah, cinfo->Al);
  171423. /* Prepare to scan data & restart markers */
  171424. cinfo->marker->next_restart_num = 0;
  171425. /* Count another SOS marker */
  171426. cinfo->input_scan_number++;
  171427. INPUT_SYNC(cinfo);
  171428. return TRUE;
  171429. }
  171430. #ifdef D_ARITH_CODING_SUPPORTED
  171431. LOCAL(boolean)
  171432. get_dac (j_decompress_ptr cinfo)
  171433. /* Process a DAC marker */
  171434. {
  171435. INT32 length;
  171436. int index, val;
  171437. INPUT_VARS(cinfo);
  171438. INPUT_2BYTES(cinfo, length, return FALSE);
  171439. length -= 2;
  171440. while (length > 0) {
  171441. INPUT_BYTE(cinfo, index, return FALSE);
  171442. INPUT_BYTE(cinfo, val, return FALSE);
  171443. length -= 2;
  171444. TRACEMS2(cinfo, 1, JTRC_DAC, index, val);
  171445. if (index < 0 || index >= (2*NUM_ARITH_TBLS))
  171446. ERREXIT1(cinfo, JERR_DAC_INDEX, index);
  171447. if (index >= NUM_ARITH_TBLS) { /* define AC table */
  171448. cinfo->arith_ac_K[index-NUM_ARITH_TBLS] = (UINT8) val;
  171449. } else { /* define DC table */
  171450. cinfo->arith_dc_L[index] = (UINT8) (val & 0x0F);
  171451. cinfo->arith_dc_U[index] = (UINT8) (val >> 4);
  171452. if (cinfo->arith_dc_L[index] > cinfo->arith_dc_U[index])
  171453. ERREXIT1(cinfo, JERR_DAC_VALUE, val);
  171454. }
  171455. }
  171456. if (length != 0)
  171457. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171458. INPUT_SYNC(cinfo);
  171459. return TRUE;
  171460. }
  171461. #else /* ! D_ARITH_CODING_SUPPORTED */
  171462. #define get_dac(cinfo) skip_variable(cinfo)
  171463. #endif /* D_ARITH_CODING_SUPPORTED */
  171464. LOCAL(boolean)
  171465. get_dht (j_decompress_ptr cinfo)
  171466. /* Process a DHT marker */
  171467. {
  171468. INT32 length;
  171469. UINT8 bits[17];
  171470. UINT8 huffval[256];
  171471. int i, index, count;
  171472. JHUFF_TBL **htblptr;
  171473. INPUT_VARS(cinfo);
  171474. INPUT_2BYTES(cinfo, length, return FALSE);
  171475. length -= 2;
  171476. while (length > 16) {
  171477. INPUT_BYTE(cinfo, index, return FALSE);
  171478. TRACEMS1(cinfo, 1, JTRC_DHT, index);
  171479. bits[0] = 0;
  171480. count = 0;
  171481. for (i = 1; i <= 16; i++) {
  171482. INPUT_BYTE(cinfo, bits[i], return FALSE);
  171483. count += bits[i];
  171484. }
  171485. length -= 1 + 16;
  171486. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  171487. bits[1], bits[2], bits[3], bits[4],
  171488. bits[5], bits[6], bits[7], bits[8]);
  171489. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  171490. bits[9], bits[10], bits[11], bits[12],
  171491. bits[13], bits[14], bits[15], bits[16]);
  171492. /* Here we just do minimal validation of the counts to avoid walking
  171493. * off the end of our table space. jdhuff.c will check more carefully.
  171494. */
  171495. if (count > 256 || ((INT32) count) > length)
  171496. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  171497. for (i = 0; i < count; i++)
  171498. INPUT_BYTE(cinfo, huffval[i], return FALSE);
  171499. length -= count;
  171500. if (index & 0x10) { /* AC table definition */
  171501. index -= 0x10;
  171502. htblptr = &cinfo->ac_huff_tbl_ptrs[index];
  171503. } else { /* DC table definition */
  171504. htblptr = &cinfo->dc_huff_tbl_ptrs[index];
  171505. }
  171506. if (index < 0 || index >= NUM_HUFF_TBLS)
  171507. ERREXIT1(cinfo, JERR_DHT_INDEX, index);
  171508. if (*htblptr == NULL)
  171509. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  171510. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  171511. MEMCOPY((*htblptr)->huffval, huffval, SIZEOF((*htblptr)->huffval));
  171512. }
  171513. if (length != 0)
  171514. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171515. INPUT_SYNC(cinfo);
  171516. return TRUE;
  171517. }
  171518. LOCAL(boolean)
  171519. get_dqt (j_decompress_ptr cinfo)
  171520. /* Process a DQT marker */
  171521. {
  171522. INT32 length;
  171523. int n, i, prec;
  171524. unsigned int tmp;
  171525. JQUANT_TBL *quant_ptr;
  171526. INPUT_VARS(cinfo);
  171527. INPUT_2BYTES(cinfo, length, return FALSE);
  171528. length -= 2;
  171529. while (length > 0) {
  171530. INPUT_BYTE(cinfo, n, return FALSE);
  171531. prec = n >> 4;
  171532. n &= 0x0F;
  171533. TRACEMS2(cinfo, 1, JTRC_DQT, n, prec);
  171534. if (n >= NUM_QUANT_TBLS)
  171535. ERREXIT1(cinfo, JERR_DQT_INDEX, n);
  171536. if (cinfo->quant_tbl_ptrs[n] == NULL)
  171537. cinfo->quant_tbl_ptrs[n] = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  171538. quant_ptr = cinfo->quant_tbl_ptrs[n];
  171539. for (i = 0; i < DCTSIZE2; i++) {
  171540. if (prec)
  171541. INPUT_2BYTES(cinfo, tmp, return FALSE);
  171542. else
  171543. INPUT_BYTE(cinfo, tmp, return FALSE);
  171544. /* We convert the zigzag-order table to natural array order. */
  171545. quant_ptr->quantval[jpeg_natural_order[i]] = (UINT16) tmp;
  171546. }
  171547. if (cinfo->err->trace_level >= 2) {
  171548. for (i = 0; i < DCTSIZE2; i += 8) {
  171549. TRACEMS8(cinfo, 2, JTRC_QUANTVALS,
  171550. quant_ptr->quantval[i], quant_ptr->quantval[i+1],
  171551. quant_ptr->quantval[i+2], quant_ptr->quantval[i+3],
  171552. quant_ptr->quantval[i+4], quant_ptr->quantval[i+5],
  171553. quant_ptr->quantval[i+6], quant_ptr->quantval[i+7]);
  171554. }
  171555. }
  171556. length -= DCTSIZE2+1;
  171557. if (prec) length -= DCTSIZE2;
  171558. }
  171559. if (length != 0)
  171560. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171561. INPUT_SYNC(cinfo);
  171562. return TRUE;
  171563. }
  171564. LOCAL(boolean)
  171565. get_dri (j_decompress_ptr cinfo)
  171566. /* Process a DRI marker */
  171567. {
  171568. INT32 length;
  171569. unsigned int tmp;
  171570. INPUT_VARS(cinfo);
  171571. INPUT_2BYTES(cinfo, length, return FALSE);
  171572. if (length != 4)
  171573. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171574. INPUT_2BYTES(cinfo, tmp, return FALSE);
  171575. TRACEMS1(cinfo, 1, JTRC_DRI, tmp);
  171576. cinfo->restart_interval = tmp;
  171577. INPUT_SYNC(cinfo);
  171578. return TRUE;
  171579. }
  171580. /*
  171581. * Routines for processing APPn and COM markers.
  171582. * These are either saved in memory or discarded, per application request.
  171583. * APP0 and APP14 are specially checked to see if they are
  171584. * JFIF and Adobe markers, respectively.
  171585. */
  171586. #define APP0_DATA_LEN 14 /* Length of interesting data in APP0 */
  171587. #define APP14_DATA_LEN 12 /* Length of interesting data in APP14 */
  171588. #define APPN_DATA_LEN 14 /* Must be the largest of the above!! */
  171589. LOCAL(void)
  171590. examine_app0 (j_decompress_ptr cinfo, JOCTET FAR * data,
  171591. unsigned int datalen, INT32 remaining)
  171592. /* Examine first few bytes from an APP0.
  171593. * Take appropriate action if it is a JFIF marker.
  171594. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  171595. */
  171596. {
  171597. INT32 totallen = (INT32) datalen + remaining;
  171598. if (datalen >= APP0_DATA_LEN &&
  171599. GETJOCTET(data[0]) == 0x4A &&
  171600. GETJOCTET(data[1]) == 0x46 &&
  171601. GETJOCTET(data[2]) == 0x49 &&
  171602. GETJOCTET(data[3]) == 0x46 &&
  171603. GETJOCTET(data[4]) == 0) {
  171604. /* Found JFIF APP0 marker: save info */
  171605. cinfo->saw_JFIF_marker = TRUE;
  171606. cinfo->JFIF_major_version = GETJOCTET(data[5]);
  171607. cinfo->JFIF_minor_version = GETJOCTET(data[6]);
  171608. cinfo->density_unit = GETJOCTET(data[7]);
  171609. cinfo->X_density = (GETJOCTET(data[8]) << 8) + GETJOCTET(data[9]);
  171610. cinfo->Y_density = (GETJOCTET(data[10]) << 8) + GETJOCTET(data[11]);
  171611. /* Check version.
  171612. * Major version must be 1, anything else signals an incompatible change.
  171613. * (We used to treat this as an error, but now it's a nonfatal warning,
  171614. * because some bozo at Hijaak couldn't read the spec.)
  171615. * Minor version should be 0..2, but process anyway if newer.
  171616. */
  171617. if (cinfo->JFIF_major_version != 1)
  171618. WARNMS2(cinfo, JWRN_JFIF_MAJOR,
  171619. cinfo->JFIF_major_version, cinfo->JFIF_minor_version);
  171620. /* Generate trace messages */
  171621. TRACEMS5(cinfo, 1, JTRC_JFIF,
  171622. cinfo->JFIF_major_version, cinfo->JFIF_minor_version,
  171623. cinfo->X_density, cinfo->Y_density, cinfo->density_unit);
  171624. /* Validate thumbnail dimensions and issue appropriate messages */
  171625. if (GETJOCTET(data[12]) | GETJOCTET(data[13]))
  171626. TRACEMS2(cinfo, 1, JTRC_JFIF_THUMBNAIL,
  171627. GETJOCTET(data[12]), GETJOCTET(data[13]));
  171628. totallen -= APP0_DATA_LEN;
  171629. if (totallen !=
  171630. ((INT32)GETJOCTET(data[12]) * (INT32)GETJOCTET(data[13]) * (INT32) 3))
  171631. TRACEMS1(cinfo, 1, JTRC_JFIF_BADTHUMBNAILSIZE, (int) totallen);
  171632. } else if (datalen >= 6 &&
  171633. GETJOCTET(data[0]) == 0x4A &&
  171634. GETJOCTET(data[1]) == 0x46 &&
  171635. GETJOCTET(data[2]) == 0x58 &&
  171636. GETJOCTET(data[3]) == 0x58 &&
  171637. GETJOCTET(data[4]) == 0) {
  171638. /* Found JFIF "JFXX" extension APP0 marker */
  171639. /* The library doesn't actually do anything with these,
  171640. * but we try to produce a helpful trace message.
  171641. */
  171642. switch (GETJOCTET(data[5])) {
  171643. case 0x10:
  171644. TRACEMS1(cinfo, 1, JTRC_THUMB_JPEG, (int) totallen);
  171645. break;
  171646. case 0x11:
  171647. TRACEMS1(cinfo, 1, JTRC_THUMB_PALETTE, (int) totallen);
  171648. break;
  171649. case 0x13:
  171650. TRACEMS1(cinfo, 1, JTRC_THUMB_RGB, (int) totallen);
  171651. break;
  171652. default:
  171653. TRACEMS2(cinfo, 1, JTRC_JFIF_EXTENSION,
  171654. GETJOCTET(data[5]), (int) totallen);
  171655. break;
  171656. }
  171657. } else {
  171658. /* Start of APP0 does not match "JFIF" or "JFXX", or too short */
  171659. TRACEMS1(cinfo, 1, JTRC_APP0, (int) totallen);
  171660. }
  171661. }
  171662. LOCAL(void)
  171663. examine_app14 (j_decompress_ptr cinfo, JOCTET FAR * data,
  171664. unsigned int datalen, INT32 remaining)
  171665. /* Examine first few bytes from an APP14.
  171666. * Take appropriate action if it is an Adobe marker.
  171667. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  171668. */
  171669. {
  171670. unsigned int version, flags0, flags1, transform;
  171671. if (datalen >= APP14_DATA_LEN &&
  171672. GETJOCTET(data[0]) == 0x41 &&
  171673. GETJOCTET(data[1]) == 0x64 &&
  171674. GETJOCTET(data[2]) == 0x6F &&
  171675. GETJOCTET(data[3]) == 0x62 &&
  171676. GETJOCTET(data[4]) == 0x65) {
  171677. /* Found Adobe APP14 marker */
  171678. version = (GETJOCTET(data[5]) << 8) + GETJOCTET(data[6]);
  171679. flags0 = (GETJOCTET(data[7]) << 8) + GETJOCTET(data[8]);
  171680. flags1 = (GETJOCTET(data[9]) << 8) + GETJOCTET(data[10]);
  171681. transform = GETJOCTET(data[11]);
  171682. TRACEMS4(cinfo, 1, JTRC_ADOBE, version, flags0, flags1, transform);
  171683. cinfo->saw_Adobe_marker = TRUE;
  171684. cinfo->Adobe_transform = (UINT8) transform;
  171685. } else {
  171686. /* Start of APP14 does not match "Adobe", or too short */
  171687. TRACEMS1(cinfo, 1, JTRC_APP14, (int) (datalen + remaining));
  171688. }
  171689. }
  171690. METHODDEF(boolean)
  171691. get_interesting_appn (j_decompress_ptr cinfo)
  171692. /* Process an APP0 or APP14 marker without saving it */
  171693. {
  171694. INT32 length;
  171695. JOCTET b[APPN_DATA_LEN];
  171696. unsigned int i, numtoread;
  171697. INPUT_VARS(cinfo);
  171698. INPUT_2BYTES(cinfo, length, return FALSE);
  171699. length -= 2;
  171700. /* get the interesting part of the marker data */
  171701. if (length >= APPN_DATA_LEN)
  171702. numtoread = APPN_DATA_LEN;
  171703. else if (length > 0)
  171704. numtoread = (unsigned int) length;
  171705. else
  171706. numtoread = 0;
  171707. for (i = 0; i < numtoread; i++)
  171708. INPUT_BYTE(cinfo, b[i], return FALSE);
  171709. length -= numtoread;
  171710. /* process it */
  171711. switch (cinfo->unread_marker) {
  171712. case M_APP0:
  171713. examine_app0(cinfo, (JOCTET FAR *) b, numtoread, length);
  171714. break;
  171715. case M_APP14:
  171716. examine_app14(cinfo, (JOCTET FAR *) b, numtoread, length);
  171717. break;
  171718. default:
  171719. /* can't get here unless jpeg_save_markers chooses wrong processor */
  171720. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  171721. break;
  171722. }
  171723. /* skip any remaining data -- could be lots */
  171724. INPUT_SYNC(cinfo);
  171725. if (length > 0)
  171726. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171727. return TRUE;
  171728. }
  171729. #ifdef SAVE_MARKERS_SUPPORTED
  171730. METHODDEF(boolean)
  171731. save_marker (j_decompress_ptr cinfo)
  171732. /* Save an APPn or COM marker into the marker list */
  171733. {
  171734. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  171735. jpeg_saved_marker_ptr cur_marker = marker->cur_marker;
  171736. unsigned int bytes_read, data_length;
  171737. JOCTET FAR * data;
  171738. INT32 length = 0;
  171739. INPUT_VARS(cinfo);
  171740. if (cur_marker == NULL) {
  171741. /* begin reading a marker */
  171742. INPUT_2BYTES(cinfo, length, return FALSE);
  171743. length -= 2;
  171744. if (length >= 0) { /* watch out for bogus length word */
  171745. /* figure out how much we want to save */
  171746. unsigned int limit;
  171747. if (cinfo->unread_marker == (int) M_COM)
  171748. limit = marker->length_limit_COM;
  171749. else
  171750. limit = marker->length_limit_APPn[cinfo->unread_marker - (int) M_APP0];
  171751. if ((unsigned int) length < limit)
  171752. limit = (unsigned int) length;
  171753. /* allocate and initialize the marker item */
  171754. cur_marker = (jpeg_saved_marker_ptr)
  171755. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171756. SIZEOF(struct jpeg_marker_struct) + limit);
  171757. cur_marker->next = NULL;
  171758. cur_marker->marker = (UINT8) cinfo->unread_marker;
  171759. cur_marker->original_length = (unsigned int) length;
  171760. cur_marker->data_length = limit;
  171761. /* data area is just beyond the jpeg_marker_struct */
  171762. data = cur_marker->data = (JOCTET FAR *) (cur_marker + 1);
  171763. marker->cur_marker = cur_marker;
  171764. marker->bytes_read = 0;
  171765. bytes_read = 0;
  171766. data_length = limit;
  171767. } else {
  171768. /* deal with bogus length word */
  171769. bytes_read = data_length = 0;
  171770. data = NULL;
  171771. }
  171772. } else {
  171773. /* resume reading a marker */
  171774. bytes_read = marker->bytes_read;
  171775. data_length = cur_marker->data_length;
  171776. data = cur_marker->data + bytes_read;
  171777. }
  171778. while (bytes_read < data_length) {
  171779. INPUT_SYNC(cinfo); /* move the restart point to here */
  171780. marker->bytes_read = bytes_read;
  171781. /* If there's not at least one byte in buffer, suspend */
  171782. MAKE_BYTE_AVAIL(cinfo, return FALSE);
  171783. /* Copy bytes with reasonable rapidity */
  171784. while (bytes_read < data_length && bytes_in_buffer > 0) {
  171785. *data++ = *next_input_byte++;
  171786. bytes_in_buffer--;
  171787. bytes_read++;
  171788. }
  171789. }
  171790. /* Done reading what we want to read */
  171791. if (cur_marker != NULL) { /* will be NULL if bogus length word */
  171792. /* Add new marker to end of list */
  171793. if (cinfo->marker_list == NULL) {
  171794. cinfo->marker_list = cur_marker;
  171795. } else {
  171796. jpeg_saved_marker_ptr prev = cinfo->marker_list;
  171797. while (prev->next != NULL)
  171798. prev = prev->next;
  171799. prev->next = cur_marker;
  171800. }
  171801. /* Reset pointer & calc remaining data length */
  171802. data = cur_marker->data;
  171803. length = cur_marker->original_length - data_length;
  171804. }
  171805. /* Reset to initial state for next marker */
  171806. marker->cur_marker = NULL;
  171807. /* Process the marker if interesting; else just make a generic trace msg */
  171808. switch (cinfo->unread_marker) {
  171809. case M_APP0:
  171810. examine_app0(cinfo, data, data_length, length);
  171811. break;
  171812. case M_APP14:
  171813. examine_app14(cinfo, data, data_length, length);
  171814. break;
  171815. default:
  171816. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker,
  171817. (int) (data_length + length));
  171818. break;
  171819. }
  171820. /* skip any remaining data -- could be lots */
  171821. INPUT_SYNC(cinfo); /* do before skip_input_data */
  171822. if (length > 0)
  171823. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171824. return TRUE;
  171825. }
  171826. #endif /* SAVE_MARKERS_SUPPORTED */
  171827. METHODDEF(boolean)
  171828. skip_variable (j_decompress_ptr cinfo)
  171829. /* Skip over an unknown or uninteresting variable-length marker */
  171830. {
  171831. INT32 length;
  171832. INPUT_VARS(cinfo);
  171833. INPUT_2BYTES(cinfo, length, return FALSE);
  171834. length -= 2;
  171835. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker, (int) length);
  171836. INPUT_SYNC(cinfo); /* do before skip_input_data */
  171837. if (length > 0)
  171838. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171839. return TRUE;
  171840. }
  171841. /*
  171842. * Find the next JPEG marker, save it in cinfo->unread_marker.
  171843. * Returns FALSE if had to suspend before reaching a marker;
  171844. * in that case cinfo->unread_marker is unchanged.
  171845. *
  171846. * Note that the result might not be a valid marker code,
  171847. * but it will never be 0 or FF.
  171848. */
  171849. LOCAL(boolean)
  171850. next_marker (j_decompress_ptr cinfo)
  171851. {
  171852. int c;
  171853. INPUT_VARS(cinfo);
  171854. for (;;) {
  171855. INPUT_BYTE(cinfo, c, return FALSE);
  171856. /* Skip any non-FF bytes.
  171857. * This may look a bit inefficient, but it will not occur in a valid file.
  171858. * We sync after each discarded byte so that a suspending data source
  171859. * can discard the byte from its buffer.
  171860. */
  171861. while (c != 0xFF) {
  171862. cinfo->marker->discarded_bytes++;
  171863. INPUT_SYNC(cinfo);
  171864. INPUT_BYTE(cinfo, c, return FALSE);
  171865. }
  171866. /* This loop swallows any duplicate FF bytes. Extra FFs are legal as
  171867. * pad bytes, so don't count them in discarded_bytes. We assume there
  171868. * will not be so many consecutive FF bytes as to overflow a suspending
  171869. * data source's input buffer.
  171870. */
  171871. do {
  171872. INPUT_BYTE(cinfo, c, return FALSE);
  171873. } while (c == 0xFF);
  171874. if (c != 0)
  171875. break; /* found a valid marker, exit loop */
  171876. /* Reach here if we found a stuffed-zero data sequence (FF/00).
  171877. * Discard it and loop back to try again.
  171878. */
  171879. cinfo->marker->discarded_bytes += 2;
  171880. INPUT_SYNC(cinfo);
  171881. }
  171882. if (cinfo->marker->discarded_bytes != 0) {
  171883. WARNMS2(cinfo, JWRN_EXTRANEOUS_DATA, cinfo->marker->discarded_bytes, c);
  171884. cinfo->marker->discarded_bytes = 0;
  171885. }
  171886. cinfo->unread_marker = c;
  171887. INPUT_SYNC(cinfo);
  171888. return TRUE;
  171889. }
  171890. LOCAL(boolean)
  171891. first_marker (j_decompress_ptr cinfo)
  171892. /* Like next_marker, but used to obtain the initial SOI marker. */
  171893. /* For this marker, we do not allow preceding garbage or fill; otherwise,
  171894. * we might well scan an entire input file before realizing it ain't JPEG.
  171895. * If an application wants to process non-JFIF files, it must seek to the
  171896. * SOI before calling the JPEG library.
  171897. */
  171898. {
  171899. int c, c2;
  171900. INPUT_VARS(cinfo);
  171901. INPUT_BYTE(cinfo, c, return FALSE);
  171902. INPUT_BYTE(cinfo, c2, return FALSE);
  171903. if (c != 0xFF || c2 != (int) M_SOI)
  171904. ERREXIT2(cinfo, JERR_NO_SOI, c, c2);
  171905. cinfo->unread_marker = c2;
  171906. INPUT_SYNC(cinfo);
  171907. return TRUE;
  171908. }
  171909. /*
  171910. * Read markers until SOS or EOI.
  171911. *
  171912. * Returns same codes as are defined for jpeg_consume_input:
  171913. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  171914. */
  171915. METHODDEF(int)
  171916. read_markers (j_decompress_ptr cinfo)
  171917. {
  171918. /* Outer loop repeats once for each marker. */
  171919. for (;;) {
  171920. /* Collect the marker proper, unless we already did. */
  171921. /* NB: first_marker() enforces the requirement that SOI appear first. */
  171922. if (cinfo->unread_marker == 0) {
  171923. if (! cinfo->marker->saw_SOI) {
  171924. if (! first_marker(cinfo))
  171925. return JPEG_SUSPENDED;
  171926. } else {
  171927. if (! next_marker(cinfo))
  171928. return JPEG_SUSPENDED;
  171929. }
  171930. }
  171931. /* At this point cinfo->unread_marker contains the marker code and the
  171932. * input point is just past the marker proper, but before any parameters.
  171933. * A suspension will cause us to return with this state still true.
  171934. */
  171935. switch (cinfo->unread_marker) {
  171936. case M_SOI:
  171937. if (! get_soi(cinfo))
  171938. return JPEG_SUSPENDED;
  171939. break;
  171940. case M_SOF0: /* Baseline */
  171941. case M_SOF1: /* Extended sequential, Huffman */
  171942. if (! get_sof(cinfo, FALSE, FALSE))
  171943. return JPEG_SUSPENDED;
  171944. break;
  171945. case M_SOF2: /* Progressive, Huffman */
  171946. if (! get_sof(cinfo, TRUE, FALSE))
  171947. return JPEG_SUSPENDED;
  171948. break;
  171949. case M_SOF9: /* Extended sequential, arithmetic */
  171950. if (! get_sof(cinfo, FALSE, TRUE))
  171951. return JPEG_SUSPENDED;
  171952. break;
  171953. case M_SOF10: /* Progressive, arithmetic */
  171954. if (! get_sof(cinfo, TRUE, TRUE))
  171955. return JPEG_SUSPENDED;
  171956. break;
  171957. /* Currently unsupported SOFn types */
  171958. case M_SOF3: /* Lossless, Huffman */
  171959. case M_SOF5: /* Differential sequential, Huffman */
  171960. case M_SOF6: /* Differential progressive, Huffman */
  171961. case M_SOF7: /* Differential lossless, Huffman */
  171962. case M_JPG: /* Reserved for JPEG extensions */
  171963. case M_SOF11: /* Lossless, arithmetic */
  171964. case M_SOF13: /* Differential sequential, arithmetic */
  171965. case M_SOF14: /* Differential progressive, arithmetic */
  171966. case M_SOF15: /* Differential lossless, arithmetic */
  171967. ERREXIT1(cinfo, JERR_SOF_UNSUPPORTED, cinfo->unread_marker);
  171968. break;
  171969. case M_SOS:
  171970. if (! get_sos(cinfo))
  171971. return JPEG_SUSPENDED;
  171972. cinfo->unread_marker = 0; /* processed the marker */
  171973. return JPEG_REACHED_SOS;
  171974. case M_EOI:
  171975. TRACEMS(cinfo, 1, JTRC_EOI);
  171976. cinfo->unread_marker = 0; /* processed the marker */
  171977. return JPEG_REACHED_EOI;
  171978. case M_DAC:
  171979. if (! get_dac(cinfo))
  171980. return JPEG_SUSPENDED;
  171981. break;
  171982. case M_DHT:
  171983. if (! get_dht(cinfo))
  171984. return JPEG_SUSPENDED;
  171985. break;
  171986. case M_DQT:
  171987. if (! get_dqt(cinfo))
  171988. return JPEG_SUSPENDED;
  171989. break;
  171990. case M_DRI:
  171991. if (! get_dri(cinfo))
  171992. return JPEG_SUSPENDED;
  171993. break;
  171994. case M_APP0:
  171995. case M_APP1:
  171996. case M_APP2:
  171997. case M_APP3:
  171998. case M_APP4:
  171999. case M_APP5:
  172000. case M_APP6:
  172001. case M_APP7:
  172002. case M_APP8:
  172003. case M_APP9:
  172004. case M_APP10:
  172005. case M_APP11:
  172006. case M_APP12:
  172007. case M_APP13:
  172008. case M_APP14:
  172009. case M_APP15:
  172010. if (! (*((my_marker_ptr2) cinfo->marker)->process_APPn[
  172011. cinfo->unread_marker - (int) M_APP0]) (cinfo))
  172012. return JPEG_SUSPENDED;
  172013. break;
  172014. case M_COM:
  172015. if (! (*((my_marker_ptr2) cinfo->marker)->process_COM) (cinfo))
  172016. return JPEG_SUSPENDED;
  172017. break;
  172018. case M_RST0: /* these are all parameterless */
  172019. case M_RST1:
  172020. case M_RST2:
  172021. case M_RST3:
  172022. case M_RST4:
  172023. case M_RST5:
  172024. case M_RST6:
  172025. case M_RST7:
  172026. case M_TEM:
  172027. TRACEMS1(cinfo, 1, JTRC_PARMLESS_MARKER, cinfo->unread_marker);
  172028. break;
  172029. case M_DNL: /* Ignore DNL ... perhaps the wrong thing */
  172030. if (! skip_variable(cinfo))
  172031. return JPEG_SUSPENDED;
  172032. break;
  172033. default: /* must be DHP, EXP, JPGn, or RESn */
  172034. /* For now, we treat the reserved markers as fatal errors since they are
  172035. * likely to be used to signal incompatible JPEG Part 3 extensions.
  172036. * Once the JPEG 3 version-number marker is well defined, this code
  172037. * ought to change!
  172038. */
  172039. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  172040. break;
  172041. }
  172042. /* Successfully processed marker, so reset state variable */
  172043. cinfo->unread_marker = 0;
  172044. } /* end loop */
  172045. }
  172046. /*
  172047. * Read a restart marker, which is expected to appear next in the datastream;
  172048. * if the marker is not there, take appropriate recovery action.
  172049. * Returns FALSE if suspension is required.
  172050. *
  172051. * This is called by the entropy decoder after it has read an appropriate
  172052. * number of MCUs. cinfo->unread_marker may be nonzero if the entropy decoder
  172053. * has already read a marker from the data source. Under normal conditions
  172054. * cinfo->unread_marker will be reset to 0 before returning; if not reset,
  172055. * it holds a marker which the decoder will be unable to read past.
  172056. */
  172057. METHODDEF(boolean)
  172058. read_restart_marker (j_decompress_ptr cinfo)
  172059. {
  172060. /* Obtain a marker unless we already did. */
  172061. /* Note that next_marker will complain if it skips any data. */
  172062. if (cinfo->unread_marker == 0) {
  172063. if (! next_marker(cinfo))
  172064. return FALSE;
  172065. }
  172066. if (cinfo->unread_marker ==
  172067. ((int) M_RST0 + cinfo->marker->next_restart_num)) {
  172068. /* Normal case --- swallow the marker and let entropy decoder continue */
  172069. TRACEMS1(cinfo, 3, JTRC_RST, cinfo->marker->next_restart_num);
  172070. cinfo->unread_marker = 0;
  172071. } else {
  172072. /* Uh-oh, the restart markers have been messed up. */
  172073. /* Let the data source manager determine how to resync. */
  172074. if (! (*cinfo->src->resync_to_restart) (cinfo,
  172075. cinfo->marker->next_restart_num))
  172076. return FALSE;
  172077. }
  172078. /* Update next-restart state */
  172079. cinfo->marker->next_restart_num = (cinfo->marker->next_restart_num + 1) & 7;
  172080. return TRUE;
  172081. }
  172082. /*
  172083. * This is the default resync_to_restart method for data source managers
  172084. * to use if they don't have any better approach. Some data source managers
  172085. * may be able to back up, or may have additional knowledge about the data
  172086. * which permits a more intelligent recovery strategy; such managers would
  172087. * presumably supply their own resync method.
  172088. *
  172089. * read_restart_marker calls resync_to_restart if it finds a marker other than
  172090. * the restart marker it was expecting. (This code is *not* used unless
  172091. * a nonzero restart interval has been declared.) cinfo->unread_marker is
  172092. * the marker code actually found (might be anything, except 0 or FF).
  172093. * The desired restart marker number (0..7) is passed as a parameter.
  172094. * This routine is supposed to apply whatever error recovery strategy seems
  172095. * appropriate in order to position the input stream to the next data segment.
  172096. * Note that cinfo->unread_marker is treated as a marker appearing before
  172097. * the current data-source input point; usually it should be reset to zero
  172098. * before returning.
  172099. * Returns FALSE if suspension is required.
  172100. *
  172101. * This implementation is substantially constrained by wanting to treat the
  172102. * input as a data stream; this means we can't back up. Therefore, we have
  172103. * only the following actions to work with:
  172104. * 1. Simply discard the marker and let the entropy decoder resume at next
  172105. * byte of file.
  172106. * 2. Read forward until we find another marker, discarding intervening
  172107. * data. (In theory we could look ahead within the current bufferload,
  172108. * without having to discard data if we don't find the desired marker.
  172109. * This idea is not implemented here, in part because it makes behavior
  172110. * dependent on buffer size and chance buffer-boundary positions.)
  172111. * 3. Leave the marker unread (by failing to zero cinfo->unread_marker).
  172112. * This will cause the entropy decoder to process an empty data segment,
  172113. * inserting dummy zeroes, and then we will reprocess the marker.
  172114. *
  172115. * #2 is appropriate if we think the desired marker lies ahead, while #3 is
  172116. * appropriate if the found marker is a future restart marker (indicating
  172117. * that we have missed the desired restart marker, probably because it got
  172118. * corrupted).
  172119. * We apply #2 or #3 if the found marker is a restart marker no more than
  172120. * two counts behind or ahead of the expected one. We also apply #2 if the
  172121. * found marker is not a legal JPEG marker code (it's certainly bogus data).
  172122. * If the found marker is a restart marker more than 2 counts away, we do #1
  172123. * (too much risk that the marker is erroneous; with luck we will be able to
  172124. * resync at some future point).
  172125. * For any valid non-restart JPEG marker, we apply #3. This keeps us from
  172126. * overrunning the end of a scan. An implementation limited to single-scan
  172127. * files might find it better to apply #2 for markers other than EOI, since
  172128. * any other marker would have to be bogus data in that case.
  172129. */
  172130. GLOBAL(boolean)
  172131. jpeg_resync_to_restart (j_decompress_ptr cinfo, int desired)
  172132. {
  172133. int marker = cinfo->unread_marker;
  172134. int action = 1;
  172135. /* Always put up a warning. */
  172136. WARNMS2(cinfo, JWRN_MUST_RESYNC, marker, desired);
  172137. /* Outer loop handles repeated decision after scanning forward. */
  172138. for (;;) {
  172139. if (marker < (int) M_SOF0)
  172140. action = 2; /* invalid marker */
  172141. else if (marker < (int) M_RST0 || marker > (int) M_RST7)
  172142. action = 3; /* valid non-restart marker */
  172143. else {
  172144. if (marker == ((int) M_RST0 + ((desired+1) & 7)) ||
  172145. marker == ((int) M_RST0 + ((desired+2) & 7)))
  172146. action = 3; /* one of the next two expected restarts */
  172147. else if (marker == ((int) M_RST0 + ((desired-1) & 7)) ||
  172148. marker == ((int) M_RST0 + ((desired-2) & 7)))
  172149. action = 2; /* a prior restart, so advance */
  172150. else
  172151. action = 1; /* desired restart or too far away */
  172152. }
  172153. TRACEMS2(cinfo, 4, JTRC_RECOVERY_ACTION, marker, action);
  172154. switch (action) {
  172155. case 1:
  172156. /* Discard marker and let entropy decoder resume processing. */
  172157. cinfo->unread_marker = 0;
  172158. return TRUE;
  172159. case 2:
  172160. /* Scan to the next marker, and repeat the decision loop. */
  172161. if (! next_marker(cinfo))
  172162. return FALSE;
  172163. marker = cinfo->unread_marker;
  172164. break;
  172165. case 3:
  172166. /* Return without advancing past this marker. */
  172167. /* Entropy decoder will be forced to process an empty segment. */
  172168. return TRUE;
  172169. }
  172170. } /* end loop */
  172171. }
  172172. /*
  172173. * Reset marker processing state to begin a fresh datastream.
  172174. */
  172175. METHODDEF(void)
  172176. reset_marker_reader (j_decompress_ptr cinfo)
  172177. {
  172178. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  172179. cinfo->comp_info = NULL; /* until allocated by get_sof */
  172180. cinfo->input_scan_number = 0; /* no SOS seen yet */
  172181. cinfo->unread_marker = 0; /* no pending marker */
  172182. marker->pub.saw_SOI = FALSE; /* set internal state too */
  172183. marker->pub.saw_SOF = FALSE;
  172184. marker->pub.discarded_bytes = 0;
  172185. marker->cur_marker = NULL;
  172186. }
  172187. /*
  172188. * Initialize the marker reader module.
  172189. * This is called only once, when the decompression object is created.
  172190. */
  172191. GLOBAL(void)
  172192. jinit_marker_reader (j_decompress_ptr cinfo)
  172193. {
  172194. my_marker_ptr2 marker;
  172195. int i;
  172196. /* Create subobject in permanent pool */
  172197. marker = (my_marker_ptr2)
  172198. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  172199. SIZEOF(my_marker_reader));
  172200. cinfo->marker = (struct jpeg_marker_reader *) marker;
  172201. /* Initialize public method pointers */
  172202. marker->pub.reset_marker_reader = reset_marker_reader;
  172203. marker->pub.read_markers = read_markers;
  172204. marker->pub.read_restart_marker = read_restart_marker;
  172205. /* Initialize COM/APPn processing.
  172206. * By default, we examine and then discard APP0 and APP14,
  172207. * but simply discard COM and all other APPn.
  172208. */
  172209. marker->process_COM = skip_variable;
  172210. marker->length_limit_COM = 0;
  172211. for (i = 0; i < 16; i++) {
  172212. marker->process_APPn[i] = skip_variable;
  172213. marker->length_limit_APPn[i] = 0;
  172214. }
  172215. marker->process_APPn[0] = get_interesting_appn;
  172216. marker->process_APPn[14] = get_interesting_appn;
  172217. /* Reset marker processing state */
  172218. reset_marker_reader(cinfo);
  172219. }
  172220. /*
  172221. * Control saving of COM and APPn markers into marker_list.
  172222. */
  172223. #ifdef SAVE_MARKERS_SUPPORTED
  172224. GLOBAL(void)
  172225. jpeg_save_markers (j_decompress_ptr cinfo, int marker_code,
  172226. unsigned int length_limit)
  172227. {
  172228. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  172229. long maxlength;
  172230. jpeg_marker_parser_method processor;
  172231. /* Length limit mustn't be larger than what we can allocate
  172232. * (should only be a concern in a 16-bit environment).
  172233. */
  172234. maxlength = cinfo->mem->max_alloc_chunk - SIZEOF(struct jpeg_marker_struct);
  172235. if (((long) length_limit) > maxlength)
  172236. length_limit = (unsigned int) maxlength;
  172237. /* Choose processor routine to use.
  172238. * APP0/APP14 have special requirements.
  172239. */
  172240. if (length_limit) {
  172241. processor = save_marker;
  172242. /* If saving APP0/APP14, save at least enough for our internal use. */
  172243. if (marker_code == (int) M_APP0 && length_limit < APP0_DATA_LEN)
  172244. length_limit = APP0_DATA_LEN;
  172245. else if (marker_code == (int) M_APP14 && length_limit < APP14_DATA_LEN)
  172246. length_limit = APP14_DATA_LEN;
  172247. } else {
  172248. processor = skip_variable;
  172249. /* If discarding APP0/APP14, use our regular on-the-fly processor. */
  172250. if (marker_code == (int) M_APP0 || marker_code == (int) M_APP14)
  172251. processor = get_interesting_appn;
  172252. }
  172253. if (marker_code == (int) M_COM) {
  172254. marker->process_COM = processor;
  172255. marker->length_limit_COM = length_limit;
  172256. } else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15) {
  172257. marker->process_APPn[marker_code - (int) M_APP0] = processor;
  172258. marker->length_limit_APPn[marker_code - (int) M_APP0] = length_limit;
  172259. } else
  172260. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  172261. }
  172262. #endif /* SAVE_MARKERS_SUPPORTED */
  172263. /*
  172264. * Install a special processing method for COM or APPn markers.
  172265. */
  172266. GLOBAL(void)
  172267. jpeg_set_marker_processor (j_decompress_ptr cinfo, int marker_code,
  172268. jpeg_marker_parser_method routine)
  172269. {
  172270. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  172271. if (marker_code == (int) M_COM)
  172272. marker->process_COM = routine;
  172273. else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15)
  172274. marker->process_APPn[marker_code - (int) M_APP0] = routine;
  172275. else
  172276. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  172277. }
  172278. /*** End of inlined file: jdmarker.c ***/
  172279. /*** Start of inlined file: jdmaster.c ***/
  172280. #define JPEG_INTERNALS
  172281. /* Private state */
  172282. typedef struct {
  172283. struct jpeg_decomp_master pub; /* public fields */
  172284. int pass_number; /* # of passes completed */
  172285. boolean using_merged_upsample; /* TRUE if using merged upsample/cconvert */
  172286. /* Saved references to initialized quantizer modules,
  172287. * in case we need to switch modes.
  172288. */
  172289. struct jpeg_color_quantizer * quantizer_1pass;
  172290. struct jpeg_color_quantizer * quantizer_2pass;
  172291. } my_decomp_master;
  172292. typedef my_decomp_master * my_master_ptr6;
  172293. /*
  172294. * Determine whether merged upsample/color conversion should be used.
  172295. * CRUCIAL: this must match the actual capabilities of jdmerge.c!
  172296. */
  172297. LOCAL(boolean)
  172298. use_merged_upsample (j_decompress_ptr cinfo)
  172299. {
  172300. #ifdef UPSAMPLE_MERGING_SUPPORTED
  172301. /* Merging is the equivalent of plain box-filter upsampling */
  172302. if (cinfo->do_fancy_upsampling || cinfo->CCIR601_sampling)
  172303. return FALSE;
  172304. /* jdmerge.c only supports YCC=>RGB color conversion */
  172305. if (cinfo->jpeg_color_space != JCS_YCbCr || cinfo->num_components != 3 ||
  172306. cinfo->out_color_space != JCS_RGB ||
  172307. cinfo->out_color_components != RGB_PIXELSIZE)
  172308. return FALSE;
  172309. /* and it only handles 2h1v or 2h2v sampling ratios */
  172310. if (cinfo->comp_info[0].h_samp_factor != 2 ||
  172311. cinfo->comp_info[1].h_samp_factor != 1 ||
  172312. cinfo->comp_info[2].h_samp_factor != 1 ||
  172313. cinfo->comp_info[0].v_samp_factor > 2 ||
  172314. cinfo->comp_info[1].v_samp_factor != 1 ||
  172315. cinfo->comp_info[2].v_samp_factor != 1)
  172316. return FALSE;
  172317. /* furthermore, it doesn't work if we've scaled the IDCTs differently */
  172318. if (cinfo->comp_info[0].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  172319. cinfo->comp_info[1].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  172320. cinfo->comp_info[2].DCT_scaled_size != cinfo->min_DCT_scaled_size)
  172321. return FALSE;
  172322. /* ??? also need to test for upsample-time rescaling, when & if supported */
  172323. return TRUE; /* by golly, it'll work... */
  172324. #else
  172325. return FALSE;
  172326. #endif
  172327. }
  172328. /*
  172329. * Compute output image dimensions and related values.
  172330. * NOTE: this is exported for possible use by application.
  172331. * Hence it mustn't do anything that can't be done twice.
  172332. * Also note that it may be called before the master module is initialized!
  172333. */
  172334. GLOBAL(void)
  172335. jpeg_calc_output_dimensions (j_decompress_ptr cinfo)
  172336. /* Do computations that are needed before master selection phase */
  172337. {
  172338. #ifdef IDCT_SCALING_SUPPORTED
  172339. int ci;
  172340. jpeg_component_info *compptr;
  172341. #endif
  172342. /* Prevent application from calling me at wrong times */
  172343. if (cinfo->global_state != DSTATE_READY)
  172344. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  172345. #ifdef IDCT_SCALING_SUPPORTED
  172346. /* Compute actual output image dimensions and DCT scaling choices. */
  172347. if (cinfo->scale_num * 8 <= cinfo->scale_denom) {
  172348. /* Provide 1/8 scaling */
  172349. cinfo->output_width = (JDIMENSION)
  172350. jdiv_round_up((long) cinfo->image_width, 8L);
  172351. cinfo->output_height = (JDIMENSION)
  172352. jdiv_round_up((long) cinfo->image_height, 8L);
  172353. cinfo->min_DCT_scaled_size = 1;
  172354. } else if (cinfo->scale_num * 4 <= cinfo->scale_denom) {
  172355. /* Provide 1/4 scaling */
  172356. cinfo->output_width = (JDIMENSION)
  172357. jdiv_round_up((long) cinfo->image_width, 4L);
  172358. cinfo->output_height = (JDIMENSION)
  172359. jdiv_round_up((long) cinfo->image_height, 4L);
  172360. cinfo->min_DCT_scaled_size = 2;
  172361. } else if (cinfo->scale_num * 2 <= cinfo->scale_denom) {
  172362. /* Provide 1/2 scaling */
  172363. cinfo->output_width = (JDIMENSION)
  172364. jdiv_round_up((long) cinfo->image_width, 2L);
  172365. cinfo->output_height = (JDIMENSION)
  172366. jdiv_round_up((long) cinfo->image_height, 2L);
  172367. cinfo->min_DCT_scaled_size = 4;
  172368. } else {
  172369. /* Provide 1/1 scaling */
  172370. cinfo->output_width = cinfo->image_width;
  172371. cinfo->output_height = cinfo->image_height;
  172372. cinfo->min_DCT_scaled_size = DCTSIZE;
  172373. }
  172374. /* In selecting the actual DCT scaling for each component, we try to
  172375. * scale up the chroma components via IDCT scaling rather than upsampling.
  172376. * This saves time if the upsampler gets to use 1:1 scaling.
  172377. * Note this code assumes that the supported DCT scalings are powers of 2.
  172378. */
  172379. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  172380. ci++, compptr++) {
  172381. int ssize = cinfo->min_DCT_scaled_size;
  172382. while (ssize < DCTSIZE &&
  172383. (compptr->h_samp_factor * ssize * 2 <=
  172384. cinfo->max_h_samp_factor * cinfo->min_DCT_scaled_size) &&
  172385. (compptr->v_samp_factor * ssize * 2 <=
  172386. cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size)) {
  172387. ssize = ssize * 2;
  172388. }
  172389. compptr->DCT_scaled_size = ssize;
  172390. }
  172391. /* Recompute downsampled dimensions of components;
  172392. * application needs to know these if using raw downsampled data.
  172393. */
  172394. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  172395. ci++, compptr++) {
  172396. /* Size in samples, after IDCT scaling */
  172397. compptr->downsampled_width = (JDIMENSION)
  172398. jdiv_round_up((long) cinfo->image_width *
  172399. (long) (compptr->h_samp_factor * compptr->DCT_scaled_size),
  172400. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  172401. compptr->downsampled_height = (JDIMENSION)
  172402. jdiv_round_up((long) cinfo->image_height *
  172403. (long) (compptr->v_samp_factor * compptr->DCT_scaled_size),
  172404. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  172405. }
  172406. #else /* !IDCT_SCALING_SUPPORTED */
  172407. /* Hardwire it to "no scaling" */
  172408. cinfo->output_width = cinfo->image_width;
  172409. cinfo->output_height = cinfo->image_height;
  172410. /* jdinput.c has already initialized DCT_scaled_size to DCTSIZE,
  172411. * and has computed unscaled downsampled_width and downsampled_height.
  172412. */
  172413. #endif /* IDCT_SCALING_SUPPORTED */
  172414. /* Report number of components in selected colorspace. */
  172415. /* Probably this should be in the color conversion module... */
  172416. switch (cinfo->out_color_space) {
  172417. case JCS_GRAYSCALE:
  172418. cinfo->out_color_components = 1;
  172419. break;
  172420. case JCS_RGB:
  172421. #if RGB_PIXELSIZE != 3
  172422. cinfo->out_color_components = RGB_PIXELSIZE;
  172423. break;
  172424. #endif /* else share code with YCbCr */
  172425. case JCS_YCbCr:
  172426. cinfo->out_color_components = 3;
  172427. break;
  172428. case JCS_CMYK:
  172429. case JCS_YCCK:
  172430. cinfo->out_color_components = 4;
  172431. break;
  172432. default: /* else must be same colorspace as in file */
  172433. cinfo->out_color_components = cinfo->num_components;
  172434. break;
  172435. }
  172436. cinfo->output_components = (cinfo->quantize_colors ? 1 :
  172437. cinfo->out_color_components);
  172438. /* See if upsampler will want to emit more than one row at a time */
  172439. if (use_merged_upsample(cinfo))
  172440. cinfo->rec_outbuf_height = cinfo->max_v_samp_factor;
  172441. else
  172442. cinfo->rec_outbuf_height = 1;
  172443. }
  172444. /*
  172445. * Several decompression processes need to range-limit values to the range
  172446. * 0..MAXJSAMPLE; the input value may fall somewhat outside this range
  172447. * due to noise introduced by quantization, roundoff error, etc. These
  172448. * processes are inner loops and need to be as fast as possible. On most
  172449. * machines, particularly CPUs with pipelines or instruction prefetch,
  172450. * a (subscript-check-less) C table lookup
  172451. * x = sample_range_limit[x];
  172452. * is faster than explicit tests
  172453. * if (x < 0) x = 0;
  172454. * else if (x > MAXJSAMPLE) x = MAXJSAMPLE;
  172455. * These processes all use a common table prepared by the routine below.
  172456. *
  172457. * For most steps we can mathematically guarantee that the initial value
  172458. * of x is within MAXJSAMPLE+1 of the legal range, so a table running from
  172459. * -(MAXJSAMPLE+1) to 2*MAXJSAMPLE+1 is sufficient. But for the initial
  172460. * limiting step (just after the IDCT), a wildly out-of-range value is
  172461. * possible if the input data is corrupt. To avoid any chance of indexing
  172462. * off the end of memory and getting a bad-pointer trap, we perform the
  172463. * post-IDCT limiting thus:
  172464. * x = range_limit[x & MASK];
  172465. * where MASK is 2 bits wider than legal sample data, ie 10 bits for 8-bit
  172466. * samples. Under normal circumstances this is more than enough range and
  172467. * a correct output will be generated; with bogus input data the mask will
  172468. * cause wraparound, and we will safely generate a bogus-but-in-range output.
  172469. * For the post-IDCT step, we want to convert the data from signed to unsigned
  172470. * representation by adding CENTERJSAMPLE at the same time that we limit it.
  172471. * So the post-IDCT limiting table ends up looking like this:
  172472. * CENTERJSAMPLE,CENTERJSAMPLE+1,...,MAXJSAMPLE,
  172473. * MAXJSAMPLE (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  172474. * 0 (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  172475. * 0,1,...,CENTERJSAMPLE-1
  172476. * Negative inputs select values from the upper half of the table after
  172477. * masking.
  172478. *
  172479. * We can save some space by overlapping the start of the post-IDCT table
  172480. * with the simpler range limiting table. The post-IDCT table begins at
  172481. * sample_range_limit + CENTERJSAMPLE.
  172482. *
  172483. * Note that the table is allocated in near data space on PCs; it's small
  172484. * enough and used often enough to justify this.
  172485. */
  172486. LOCAL(void)
  172487. prepare_range_limit_table (j_decompress_ptr cinfo)
  172488. /* Allocate and fill in the sample_range_limit table */
  172489. {
  172490. JSAMPLE * table;
  172491. int i;
  172492. table = (JSAMPLE *)
  172493. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172494. (5 * (MAXJSAMPLE+1) + CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  172495. table += (MAXJSAMPLE+1); /* allow negative subscripts of simple table */
  172496. cinfo->sample_range_limit = table;
  172497. /* First segment of "simple" table: limit[x] = 0 for x < 0 */
  172498. MEMZERO(table - (MAXJSAMPLE+1), (MAXJSAMPLE+1) * SIZEOF(JSAMPLE));
  172499. /* Main part of "simple" table: limit[x] = x */
  172500. for (i = 0; i <= MAXJSAMPLE; i++)
  172501. table[i] = (JSAMPLE) i;
  172502. table += CENTERJSAMPLE; /* Point to where post-IDCT table starts */
  172503. /* End of simple table, rest of first half of post-IDCT table */
  172504. for (i = CENTERJSAMPLE; i < 2*(MAXJSAMPLE+1); i++)
  172505. table[i] = MAXJSAMPLE;
  172506. /* Second half of post-IDCT table */
  172507. MEMZERO(table + (2 * (MAXJSAMPLE+1)),
  172508. (2 * (MAXJSAMPLE+1) - CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  172509. MEMCOPY(table + (4 * (MAXJSAMPLE+1) - CENTERJSAMPLE),
  172510. cinfo->sample_range_limit, CENTERJSAMPLE * SIZEOF(JSAMPLE));
  172511. }
  172512. /*
  172513. * Master selection of decompression modules.
  172514. * This is done once at jpeg_start_decompress time. We determine
  172515. * which modules will be used and give them appropriate initialization calls.
  172516. * We also initialize the decompressor input side to begin consuming data.
  172517. *
  172518. * Since jpeg_read_header has finished, we know what is in the SOF
  172519. * and (first) SOS markers. We also have all the application parameter
  172520. * settings.
  172521. */
  172522. LOCAL(void)
  172523. master_selection (j_decompress_ptr cinfo)
  172524. {
  172525. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172526. boolean use_c_buffer;
  172527. long samplesperrow;
  172528. JDIMENSION jd_samplesperrow;
  172529. /* Initialize dimensions and other stuff */
  172530. jpeg_calc_output_dimensions(cinfo);
  172531. prepare_range_limit_table(cinfo);
  172532. /* Width of an output scanline must be representable as JDIMENSION. */
  172533. samplesperrow = (long) cinfo->output_width * (long) cinfo->out_color_components;
  172534. jd_samplesperrow = (JDIMENSION) samplesperrow;
  172535. if ((long) jd_samplesperrow != samplesperrow)
  172536. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  172537. /* Initialize my private state */
  172538. master->pass_number = 0;
  172539. master->using_merged_upsample = use_merged_upsample(cinfo);
  172540. /* Color quantizer selection */
  172541. master->quantizer_1pass = NULL;
  172542. master->quantizer_2pass = NULL;
  172543. /* No mode changes if not using buffered-image mode. */
  172544. if (! cinfo->quantize_colors || ! cinfo->buffered_image) {
  172545. cinfo->enable_1pass_quant = FALSE;
  172546. cinfo->enable_external_quant = FALSE;
  172547. cinfo->enable_2pass_quant = FALSE;
  172548. }
  172549. if (cinfo->quantize_colors) {
  172550. if (cinfo->raw_data_out)
  172551. ERREXIT(cinfo, JERR_NOTIMPL);
  172552. /* 2-pass quantizer only works in 3-component color space. */
  172553. if (cinfo->out_color_components != 3) {
  172554. cinfo->enable_1pass_quant = TRUE;
  172555. cinfo->enable_external_quant = FALSE;
  172556. cinfo->enable_2pass_quant = FALSE;
  172557. cinfo->colormap = NULL;
  172558. } else if (cinfo->colormap != NULL) {
  172559. cinfo->enable_external_quant = TRUE;
  172560. } else if (cinfo->two_pass_quantize) {
  172561. cinfo->enable_2pass_quant = TRUE;
  172562. } else {
  172563. cinfo->enable_1pass_quant = TRUE;
  172564. }
  172565. if (cinfo->enable_1pass_quant) {
  172566. #ifdef QUANT_1PASS_SUPPORTED
  172567. jinit_1pass_quantizer(cinfo);
  172568. master->quantizer_1pass = cinfo->cquantize;
  172569. #else
  172570. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172571. #endif
  172572. }
  172573. /* We use the 2-pass code to map to external colormaps. */
  172574. if (cinfo->enable_2pass_quant || cinfo->enable_external_quant) {
  172575. #ifdef QUANT_2PASS_SUPPORTED
  172576. jinit_2pass_quantizer(cinfo);
  172577. master->quantizer_2pass = cinfo->cquantize;
  172578. #else
  172579. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172580. #endif
  172581. }
  172582. /* If both quantizers are initialized, the 2-pass one is left active;
  172583. * this is necessary for starting with quantization to an external map.
  172584. */
  172585. }
  172586. /* Post-processing: in particular, color conversion first */
  172587. if (! cinfo->raw_data_out) {
  172588. if (master->using_merged_upsample) {
  172589. #ifdef UPSAMPLE_MERGING_SUPPORTED
  172590. jinit_merged_upsampler(cinfo); /* does color conversion too */
  172591. #else
  172592. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172593. #endif
  172594. } else {
  172595. jinit_color_deconverter(cinfo);
  172596. jinit_upsampler(cinfo);
  172597. }
  172598. jinit_d_post_controller(cinfo, cinfo->enable_2pass_quant);
  172599. }
  172600. /* Inverse DCT */
  172601. jinit_inverse_dct(cinfo);
  172602. /* Entropy decoding: either Huffman or arithmetic coding. */
  172603. if (cinfo->arith_code) {
  172604. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  172605. } else {
  172606. if (cinfo->progressive_mode) {
  172607. #ifdef D_PROGRESSIVE_SUPPORTED
  172608. jinit_phuff_decoder(cinfo);
  172609. #else
  172610. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172611. #endif
  172612. } else
  172613. jinit_huff_decoder(cinfo);
  172614. }
  172615. /* Initialize principal buffer controllers. */
  172616. use_c_buffer = cinfo->inputctl->has_multiple_scans || cinfo->buffered_image;
  172617. jinit_d_coef_controller(cinfo, use_c_buffer);
  172618. if (! cinfo->raw_data_out)
  172619. jinit_d_main_controller(cinfo, FALSE /* never need full buffer here */);
  172620. /* We can now tell the memory manager to allocate virtual arrays. */
  172621. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  172622. /* Initialize input side of decompressor to consume first scan. */
  172623. (*cinfo->inputctl->start_input_pass) (cinfo);
  172624. #ifdef D_MULTISCAN_FILES_SUPPORTED
  172625. /* If jpeg_start_decompress will read the whole file, initialize
  172626. * progress monitoring appropriately. The input step is counted
  172627. * as one pass.
  172628. */
  172629. if (cinfo->progress != NULL && ! cinfo->buffered_image &&
  172630. cinfo->inputctl->has_multiple_scans) {
  172631. int nscans;
  172632. /* Estimate number of scans to set pass_limit. */
  172633. if (cinfo->progressive_mode) {
  172634. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  172635. nscans = 2 + 3 * cinfo->num_components;
  172636. } else {
  172637. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  172638. nscans = cinfo->num_components;
  172639. }
  172640. cinfo->progress->pass_counter = 0L;
  172641. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  172642. cinfo->progress->completed_passes = 0;
  172643. cinfo->progress->total_passes = (cinfo->enable_2pass_quant ? 3 : 2);
  172644. /* Count the input pass as done */
  172645. master->pass_number++;
  172646. }
  172647. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  172648. }
  172649. /*
  172650. * Per-pass setup.
  172651. * This is called at the beginning of each output pass. We determine which
  172652. * modules will be active during this pass and give them appropriate
  172653. * start_pass calls. We also set is_dummy_pass to indicate whether this
  172654. * is a "real" output pass or a dummy pass for color quantization.
  172655. * (In the latter case, jdapistd.c will crank the pass to completion.)
  172656. */
  172657. METHODDEF(void)
  172658. prepare_for_output_pass (j_decompress_ptr cinfo)
  172659. {
  172660. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172661. if (master->pub.is_dummy_pass) {
  172662. #ifdef QUANT_2PASS_SUPPORTED
  172663. /* Final pass of 2-pass quantization */
  172664. master->pub.is_dummy_pass = FALSE;
  172665. (*cinfo->cquantize->start_pass) (cinfo, FALSE);
  172666. (*cinfo->post->start_pass) (cinfo, JBUF_CRANK_DEST);
  172667. (*cinfo->main->start_pass) (cinfo, JBUF_CRANK_DEST);
  172668. #else
  172669. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172670. #endif /* QUANT_2PASS_SUPPORTED */
  172671. } else {
  172672. if (cinfo->quantize_colors && cinfo->colormap == NULL) {
  172673. /* Select new quantization method */
  172674. if (cinfo->two_pass_quantize && cinfo->enable_2pass_quant) {
  172675. cinfo->cquantize = master->quantizer_2pass;
  172676. master->pub.is_dummy_pass = TRUE;
  172677. } else if (cinfo->enable_1pass_quant) {
  172678. cinfo->cquantize = master->quantizer_1pass;
  172679. } else {
  172680. ERREXIT(cinfo, JERR_MODE_CHANGE);
  172681. }
  172682. }
  172683. (*cinfo->idct->start_pass) (cinfo);
  172684. (*cinfo->coef->start_output_pass) (cinfo);
  172685. if (! cinfo->raw_data_out) {
  172686. if (! master->using_merged_upsample)
  172687. (*cinfo->cconvert->start_pass) (cinfo);
  172688. (*cinfo->upsample->start_pass) (cinfo);
  172689. if (cinfo->quantize_colors)
  172690. (*cinfo->cquantize->start_pass) (cinfo, master->pub.is_dummy_pass);
  172691. (*cinfo->post->start_pass) (cinfo,
  172692. (master->pub.is_dummy_pass ? JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  172693. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  172694. }
  172695. }
  172696. /* Set up progress monitor's pass info if present */
  172697. if (cinfo->progress != NULL) {
  172698. cinfo->progress->completed_passes = master->pass_number;
  172699. cinfo->progress->total_passes = master->pass_number +
  172700. (master->pub.is_dummy_pass ? 2 : 1);
  172701. /* In buffered-image mode, we assume one more output pass if EOI not
  172702. * yet reached, but no more passes if EOI has been reached.
  172703. */
  172704. if (cinfo->buffered_image && ! cinfo->inputctl->eoi_reached) {
  172705. cinfo->progress->total_passes += (cinfo->enable_2pass_quant ? 2 : 1);
  172706. }
  172707. }
  172708. }
  172709. /*
  172710. * Finish up at end of an output pass.
  172711. */
  172712. METHODDEF(void)
  172713. finish_output_pass (j_decompress_ptr cinfo)
  172714. {
  172715. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172716. if (cinfo->quantize_colors)
  172717. (*cinfo->cquantize->finish_pass) (cinfo);
  172718. master->pass_number++;
  172719. }
  172720. #ifdef D_MULTISCAN_FILES_SUPPORTED
  172721. /*
  172722. * Switch to a new external colormap between output passes.
  172723. */
  172724. GLOBAL(void)
  172725. jpeg_new_colormap (j_decompress_ptr cinfo)
  172726. {
  172727. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172728. /* Prevent application from calling me at wrong times */
  172729. if (cinfo->global_state != DSTATE_BUFIMAGE)
  172730. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  172731. if (cinfo->quantize_colors && cinfo->enable_external_quant &&
  172732. cinfo->colormap != NULL) {
  172733. /* Select 2-pass quantizer for external colormap use */
  172734. cinfo->cquantize = master->quantizer_2pass;
  172735. /* Notify quantizer of colormap change */
  172736. (*cinfo->cquantize->new_color_map) (cinfo);
  172737. master->pub.is_dummy_pass = FALSE; /* just in case */
  172738. } else
  172739. ERREXIT(cinfo, JERR_MODE_CHANGE);
  172740. }
  172741. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  172742. /*
  172743. * Initialize master decompression control and select active modules.
  172744. * This is performed at the start of jpeg_start_decompress.
  172745. */
  172746. GLOBAL(void)
  172747. jinit_master_decompress (j_decompress_ptr cinfo)
  172748. {
  172749. my_master_ptr6 master;
  172750. master = (my_master_ptr6)
  172751. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172752. SIZEOF(my_decomp_master));
  172753. cinfo->master = (struct jpeg_decomp_master *) master;
  172754. master->pub.prepare_for_output_pass = prepare_for_output_pass;
  172755. master->pub.finish_output_pass = finish_output_pass;
  172756. master->pub.is_dummy_pass = FALSE;
  172757. master_selection(cinfo);
  172758. }
  172759. /*** End of inlined file: jdmaster.c ***/
  172760. #undef FIX
  172761. /*** Start of inlined file: jdmerge.c ***/
  172762. #define JPEG_INTERNALS
  172763. #ifdef UPSAMPLE_MERGING_SUPPORTED
  172764. /* Private subobject */
  172765. typedef struct {
  172766. struct jpeg_upsampler pub; /* public fields */
  172767. /* Pointer to routine to do actual upsampling/conversion of one row group */
  172768. JMETHOD(void, upmethod, (j_decompress_ptr cinfo,
  172769. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  172770. JSAMPARRAY output_buf));
  172771. /* Private state for YCC->RGB conversion */
  172772. int * Cr_r_tab; /* => table for Cr to R conversion */
  172773. int * Cb_b_tab; /* => table for Cb to B conversion */
  172774. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  172775. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  172776. /* For 2:1 vertical sampling, we produce two output rows at a time.
  172777. * We need a "spare" row buffer to hold the second output row if the
  172778. * application provides just a one-row buffer; we also use the spare
  172779. * to discard the dummy last row if the image height is odd.
  172780. */
  172781. JSAMPROW spare_row;
  172782. boolean spare_full; /* T if spare buffer is occupied */
  172783. JDIMENSION out_row_width; /* samples per output row */
  172784. JDIMENSION rows_to_go; /* counts rows remaining in image */
  172785. } my_upsampler;
  172786. typedef my_upsampler * my_upsample_ptr;
  172787. #define SCALEBITS 16 /* speediest right-shift on some machines */
  172788. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  172789. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  172790. /*
  172791. * Initialize tables for YCC->RGB colorspace conversion.
  172792. * This is taken directly from jdcolor.c; see that file for more info.
  172793. */
  172794. LOCAL(void)
  172795. build_ycc_rgb_table2 (j_decompress_ptr cinfo)
  172796. {
  172797. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172798. int i;
  172799. INT32 x;
  172800. SHIFT_TEMPS
  172801. upsample->Cr_r_tab = (int *)
  172802. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172803. (MAXJSAMPLE+1) * SIZEOF(int));
  172804. upsample->Cb_b_tab = (int *)
  172805. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172806. (MAXJSAMPLE+1) * SIZEOF(int));
  172807. upsample->Cr_g_tab = (INT32 *)
  172808. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172809. (MAXJSAMPLE+1) * SIZEOF(INT32));
  172810. upsample->Cb_g_tab = (INT32 *)
  172811. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172812. (MAXJSAMPLE+1) * SIZEOF(INT32));
  172813. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  172814. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  172815. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  172816. /* Cr=>R value is nearest int to 1.40200 * x */
  172817. upsample->Cr_r_tab[i] = (int)
  172818. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  172819. /* Cb=>B value is nearest int to 1.77200 * x */
  172820. upsample->Cb_b_tab[i] = (int)
  172821. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  172822. /* Cr=>G value is scaled-up -0.71414 * x */
  172823. upsample->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  172824. /* Cb=>G value is scaled-up -0.34414 * x */
  172825. /* We also add in ONE_HALF so that need not do it in inner loop */
  172826. upsample->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  172827. }
  172828. }
  172829. /*
  172830. * Initialize for an upsampling pass.
  172831. */
  172832. METHODDEF(void)
  172833. start_pass_merged_upsample (j_decompress_ptr cinfo)
  172834. {
  172835. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172836. /* Mark the spare buffer empty */
  172837. upsample->spare_full = FALSE;
  172838. /* Initialize total-height counter for detecting bottom of image */
  172839. upsample->rows_to_go = cinfo->output_height;
  172840. }
  172841. /*
  172842. * Control routine to do upsampling (and color conversion).
  172843. *
  172844. * The control routine just handles the row buffering considerations.
  172845. */
  172846. METHODDEF(void)
  172847. merged_2v_upsample (j_decompress_ptr cinfo,
  172848. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172849. JDIMENSION,
  172850. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172851. JDIMENSION out_rows_avail)
  172852. /* 2:1 vertical sampling case: may need a spare row. */
  172853. {
  172854. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172855. JSAMPROW work_ptrs[2];
  172856. JDIMENSION num_rows; /* number of rows returned to caller */
  172857. if (upsample->spare_full) {
  172858. /* If we have a spare row saved from a previous cycle, just return it. */
  172859. jcopy_sample_rows(& upsample->spare_row, 0, output_buf + *out_row_ctr, 0,
  172860. 1, upsample->out_row_width);
  172861. num_rows = 1;
  172862. upsample->spare_full = FALSE;
  172863. } else {
  172864. /* Figure number of rows to return to caller. */
  172865. num_rows = 2;
  172866. /* Not more than the distance to the end of the image. */
  172867. if (num_rows > upsample->rows_to_go)
  172868. num_rows = upsample->rows_to_go;
  172869. /* And not more than what the client can accept: */
  172870. out_rows_avail -= *out_row_ctr;
  172871. if (num_rows > out_rows_avail)
  172872. num_rows = out_rows_avail;
  172873. /* Create output pointer array for upsampler. */
  172874. work_ptrs[0] = output_buf[*out_row_ctr];
  172875. if (num_rows > 1) {
  172876. work_ptrs[1] = output_buf[*out_row_ctr + 1];
  172877. } else {
  172878. work_ptrs[1] = upsample->spare_row;
  172879. upsample->spare_full = TRUE;
  172880. }
  172881. /* Now do the upsampling. */
  172882. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr, work_ptrs);
  172883. }
  172884. /* Adjust counts */
  172885. *out_row_ctr += num_rows;
  172886. upsample->rows_to_go -= num_rows;
  172887. /* When the buffer is emptied, declare this input row group consumed */
  172888. if (! upsample->spare_full)
  172889. (*in_row_group_ctr)++;
  172890. }
  172891. METHODDEF(void)
  172892. merged_1v_upsample (j_decompress_ptr cinfo,
  172893. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172894. JDIMENSION,
  172895. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172896. JDIMENSION)
  172897. /* 1:1 vertical sampling case: much easier, never need a spare row. */
  172898. {
  172899. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172900. /* Just do the upsampling. */
  172901. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr,
  172902. output_buf + *out_row_ctr);
  172903. /* Adjust counts */
  172904. (*out_row_ctr)++;
  172905. (*in_row_group_ctr)++;
  172906. }
  172907. /*
  172908. * These are the routines invoked by the control routines to do
  172909. * the actual upsampling/conversion. One row group is processed per call.
  172910. *
  172911. * Note: since we may be writing directly into application-supplied buffers,
  172912. * we have to be honest about the output width; we can't assume the buffer
  172913. * has been rounded up to an even width.
  172914. */
  172915. /*
  172916. * Upsample and color convert for the case of 2:1 horizontal and 1:1 vertical.
  172917. */
  172918. METHODDEF(void)
  172919. h2v1_merged_upsample (j_decompress_ptr cinfo,
  172920. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  172921. JSAMPARRAY output_buf)
  172922. {
  172923. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172924. register int y, cred, cgreen, cblue;
  172925. int cb, cr;
  172926. register JSAMPROW outptr;
  172927. JSAMPROW inptr0, inptr1, inptr2;
  172928. JDIMENSION col;
  172929. /* copy these pointers into registers if possible */
  172930. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  172931. int * Crrtab = upsample->Cr_r_tab;
  172932. int * Cbbtab = upsample->Cb_b_tab;
  172933. INT32 * Crgtab = upsample->Cr_g_tab;
  172934. INT32 * Cbgtab = upsample->Cb_g_tab;
  172935. SHIFT_TEMPS
  172936. inptr0 = input_buf[0][in_row_group_ctr];
  172937. inptr1 = input_buf[1][in_row_group_ctr];
  172938. inptr2 = input_buf[2][in_row_group_ctr];
  172939. outptr = output_buf[0];
  172940. /* Loop for each pair of output pixels */
  172941. for (col = cinfo->output_width >> 1; col > 0; col--) {
  172942. /* Do the chroma part of the calculation */
  172943. cb = GETJSAMPLE(*inptr1++);
  172944. cr = GETJSAMPLE(*inptr2++);
  172945. cred = Crrtab[cr];
  172946. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172947. cblue = Cbbtab[cb];
  172948. /* Fetch 2 Y values and emit 2 pixels */
  172949. y = GETJSAMPLE(*inptr0++);
  172950. outptr[RGB_RED] = range_limit[y + cred];
  172951. outptr[RGB_GREEN] = range_limit[y + cgreen];
  172952. outptr[RGB_BLUE] = range_limit[y + cblue];
  172953. outptr += RGB_PIXELSIZE;
  172954. y = GETJSAMPLE(*inptr0++);
  172955. outptr[RGB_RED] = range_limit[y + cred];
  172956. outptr[RGB_GREEN] = range_limit[y + cgreen];
  172957. outptr[RGB_BLUE] = range_limit[y + cblue];
  172958. outptr += RGB_PIXELSIZE;
  172959. }
  172960. /* If image width is odd, do the last output column separately */
  172961. if (cinfo->output_width & 1) {
  172962. cb = GETJSAMPLE(*inptr1);
  172963. cr = GETJSAMPLE(*inptr2);
  172964. cred = Crrtab[cr];
  172965. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172966. cblue = Cbbtab[cb];
  172967. y = GETJSAMPLE(*inptr0);
  172968. outptr[RGB_RED] = range_limit[y + cred];
  172969. outptr[RGB_GREEN] = range_limit[y + cgreen];
  172970. outptr[RGB_BLUE] = range_limit[y + cblue];
  172971. }
  172972. }
  172973. /*
  172974. * Upsample and color convert for the case of 2:1 horizontal and 2:1 vertical.
  172975. */
  172976. METHODDEF(void)
  172977. h2v2_merged_upsample (j_decompress_ptr cinfo,
  172978. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  172979. JSAMPARRAY output_buf)
  172980. {
  172981. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172982. register int y, cred, cgreen, cblue;
  172983. int cb, cr;
  172984. register JSAMPROW outptr0, outptr1;
  172985. JSAMPROW inptr00, inptr01, inptr1, inptr2;
  172986. JDIMENSION col;
  172987. /* copy these pointers into registers if possible */
  172988. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  172989. int * Crrtab = upsample->Cr_r_tab;
  172990. int * Cbbtab = upsample->Cb_b_tab;
  172991. INT32 * Crgtab = upsample->Cr_g_tab;
  172992. INT32 * Cbgtab = upsample->Cb_g_tab;
  172993. SHIFT_TEMPS
  172994. inptr00 = input_buf[0][in_row_group_ctr*2];
  172995. inptr01 = input_buf[0][in_row_group_ctr*2 + 1];
  172996. inptr1 = input_buf[1][in_row_group_ctr];
  172997. inptr2 = input_buf[2][in_row_group_ctr];
  172998. outptr0 = output_buf[0];
  172999. outptr1 = output_buf[1];
  173000. /* Loop for each group of output pixels */
  173001. for (col = cinfo->output_width >> 1; col > 0; col--) {
  173002. /* Do the chroma part of the calculation */
  173003. cb = GETJSAMPLE(*inptr1++);
  173004. cr = GETJSAMPLE(*inptr2++);
  173005. cred = Crrtab[cr];
  173006. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  173007. cblue = Cbbtab[cb];
  173008. /* Fetch 4 Y values and emit 4 pixels */
  173009. y = GETJSAMPLE(*inptr00++);
  173010. outptr0[RGB_RED] = range_limit[y + cred];
  173011. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  173012. outptr0[RGB_BLUE] = range_limit[y + cblue];
  173013. outptr0 += RGB_PIXELSIZE;
  173014. y = GETJSAMPLE(*inptr00++);
  173015. outptr0[RGB_RED] = range_limit[y + cred];
  173016. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  173017. outptr0[RGB_BLUE] = range_limit[y + cblue];
  173018. outptr0 += RGB_PIXELSIZE;
  173019. y = GETJSAMPLE(*inptr01++);
  173020. outptr1[RGB_RED] = range_limit[y + cred];
  173021. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  173022. outptr1[RGB_BLUE] = range_limit[y + cblue];
  173023. outptr1 += RGB_PIXELSIZE;
  173024. y = GETJSAMPLE(*inptr01++);
  173025. outptr1[RGB_RED] = range_limit[y + cred];
  173026. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  173027. outptr1[RGB_BLUE] = range_limit[y + cblue];
  173028. outptr1 += RGB_PIXELSIZE;
  173029. }
  173030. /* If image width is odd, do the last output column separately */
  173031. if (cinfo->output_width & 1) {
  173032. cb = GETJSAMPLE(*inptr1);
  173033. cr = GETJSAMPLE(*inptr2);
  173034. cred = Crrtab[cr];
  173035. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  173036. cblue = Cbbtab[cb];
  173037. y = GETJSAMPLE(*inptr00);
  173038. outptr0[RGB_RED] = range_limit[y + cred];
  173039. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  173040. outptr0[RGB_BLUE] = range_limit[y + cblue];
  173041. y = GETJSAMPLE(*inptr01);
  173042. outptr1[RGB_RED] = range_limit[y + cred];
  173043. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  173044. outptr1[RGB_BLUE] = range_limit[y + cblue];
  173045. }
  173046. }
  173047. /*
  173048. * Module initialization routine for merged upsampling/color conversion.
  173049. *
  173050. * NB: this is called under the conditions determined by use_merged_upsample()
  173051. * in jdmaster.c. That routine MUST correspond to the actual capabilities
  173052. * of this module; no safety checks are made here.
  173053. */
  173054. GLOBAL(void)
  173055. jinit_merged_upsampler (j_decompress_ptr cinfo)
  173056. {
  173057. my_upsample_ptr upsample;
  173058. upsample = (my_upsample_ptr)
  173059. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173060. SIZEOF(my_upsampler));
  173061. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  173062. upsample->pub.start_pass = start_pass_merged_upsample;
  173063. upsample->pub.need_context_rows = FALSE;
  173064. upsample->out_row_width = cinfo->output_width * cinfo->out_color_components;
  173065. if (cinfo->max_v_samp_factor == 2) {
  173066. upsample->pub.upsample = merged_2v_upsample;
  173067. upsample->upmethod = h2v2_merged_upsample;
  173068. /* Allocate a spare row buffer */
  173069. upsample->spare_row = (JSAMPROW)
  173070. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173071. (size_t) (upsample->out_row_width * SIZEOF(JSAMPLE)));
  173072. } else {
  173073. upsample->pub.upsample = merged_1v_upsample;
  173074. upsample->upmethod = h2v1_merged_upsample;
  173075. /* No spare row needed */
  173076. upsample->spare_row = NULL;
  173077. }
  173078. build_ycc_rgb_table2(cinfo);
  173079. }
  173080. #endif /* UPSAMPLE_MERGING_SUPPORTED */
  173081. /*** End of inlined file: jdmerge.c ***/
  173082. #undef ASSIGN_STATE
  173083. /*** Start of inlined file: jdphuff.c ***/
  173084. #define JPEG_INTERNALS
  173085. #ifdef D_PROGRESSIVE_SUPPORTED
  173086. /*
  173087. * Expanded entropy decoder object for progressive Huffman decoding.
  173088. *
  173089. * The savable_state subrecord contains fields that change within an MCU,
  173090. * but must not be updated permanently until we complete the MCU.
  173091. */
  173092. typedef struct {
  173093. unsigned int EOBRUN; /* remaining EOBs in EOBRUN */
  173094. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  173095. } savable_state3;
  173096. /* This macro is to work around compilers with missing or broken
  173097. * structure assignment. You'll need to fix this code if you have
  173098. * such a compiler and you change MAX_COMPS_IN_SCAN.
  173099. */
  173100. #ifndef NO_STRUCT_ASSIGN
  173101. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  173102. #else
  173103. #if MAX_COMPS_IN_SCAN == 4
  173104. #define ASSIGN_STATE(dest,src) \
  173105. ((dest).EOBRUN = (src).EOBRUN, \
  173106. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  173107. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  173108. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  173109. (dest).last_dc_val[3] = (src).last_dc_val[3])
  173110. #endif
  173111. #endif
  173112. typedef struct {
  173113. struct jpeg_entropy_decoder pub; /* public fields */
  173114. /* These fields are loaded into local variables at start of each MCU.
  173115. * In case of suspension, we exit WITHOUT updating them.
  173116. */
  173117. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  173118. savable_state3 saved; /* Other state at start of MCU */
  173119. /* These fields are NOT loaded into local working state. */
  173120. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  173121. /* Pointers to derived tables (these workspaces have image lifespan) */
  173122. d_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  173123. d_derived_tbl * ac_derived_tbl; /* active table during an AC scan */
  173124. } phuff_entropy_decoder;
  173125. typedef phuff_entropy_decoder * phuff_entropy_ptr2;
  173126. /* Forward declarations */
  173127. METHODDEF(boolean) decode_mcu_DC_first JPP((j_decompress_ptr cinfo,
  173128. JBLOCKROW *MCU_data));
  173129. METHODDEF(boolean) decode_mcu_AC_first JPP((j_decompress_ptr cinfo,
  173130. JBLOCKROW *MCU_data));
  173131. METHODDEF(boolean) decode_mcu_DC_refine JPP((j_decompress_ptr cinfo,
  173132. JBLOCKROW *MCU_data));
  173133. METHODDEF(boolean) decode_mcu_AC_refine JPP((j_decompress_ptr cinfo,
  173134. JBLOCKROW *MCU_data));
  173135. /*
  173136. * Initialize for a Huffman-compressed scan.
  173137. */
  173138. METHODDEF(void)
  173139. start_pass_phuff_decoder (j_decompress_ptr cinfo)
  173140. {
  173141. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173142. boolean is_DC_band, bad;
  173143. int ci, coefi, tbl;
  173144. int *coef_bit_ptr;
  173145. jpeg_component_info * compptr;
  173146. is_DC_band = (cinfo->Ss == 0);
  173147. /* Validate scan parameters */
  173148. bad = FALSE;
  173149. if (is_DC_band) {
  173150. if (cinfo->Se != 0)
  173151. bad = TRUE;
  173152. } else {
  173153. /* need not check Ss/Se < 0 since they came from unsigned bytes */
  173154. if (cinfo->Ss > cinfo->Se || cinfo->Se >= DCTSIZE2)
  173155. bad = TRUE;
  173156. /* AC scans may have only one component */
  173157. if (cinfo->comps_in_scan != 1)
  173158. bad = TRUE;
  173159. }
  173160. if (cinfo->Ah != 0) {
  173161. /* Successive approximation refinement scan: must have Al = Ah-1. */
  173162. if (cinfo->Al != cinfo->Ah-1)
  173163. bad = TRUE;
  173164. }
  173165. if (cinfo->Al > 13) /* need not check for < 0 */
  173166. bad = TRUE;
  173167. /* Arguably the maximum Al value should be less than 13 for 8-bit precision,
  173168. * but the spec doesn't say so, and we try to be liberal about what we
  173169. * accept. Note: large Al values could result in out-of-range DC
  173170. * coefficients during early scans, leading to bizarre displays due to
  173171. * overflows in the IDCT math. But we won't crash.
  173172. */
  173173. if (bad)
  173174. ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
  173175. cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
  173176. /* Update progression status, and verify that scan order is legal.
  173177. * Note that inter-scan inconsistencies are treated as warnings
  173178. * not fatal errors ... not clear if this is right way to behave.
  173179. */
  173180. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  173181. int cindex = cinfo->cur_comp_info[ci]->component_index;
  173182. coef_bit_ptr = & cinfo->coef_bits[cindex][0];
  173183. if (!is_DC_band && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
  173184. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
  173185. for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
  173186. int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
  173187. if (cinfo->Ah != expected)
  173188. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
  173189. coef_bit_ptr[coefi] = cinfo->Al;
  173190. }
  173191. }
  173192. /* Select MCU decoding routine */
  173193. if (cinfo->Ah == 0) {
  173194. if (is_DC_band)
  173195. entropy->pub.decode_mcu = decode_mcu_DC_first;
  173196. else
  173197. entropy->pub.decode_mcu = decode_mcu_AC_first;
  173198. } else {
  173199. if (is_DC_band)
  173200. entropy->pub.decode_mcu = decode_mcu_DC_refine;
  173201. else
  173202. entropy->pub.decode_mcu = decode_mcu_AC_refine;
  173203. }
  173204. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  173205. compptr = cinfo->cur_comp_info[ci];
  173206. /* Make sure requested tables are present, and compute derived tables.
  173207. * We may build same derived table more than once, but it's not expensive.
  173208. */
  173209. if (is_DC_band) {
  173210. if (cinfo->Ah == 0) { /* DC refinement needs no table */
  173211. tbl = compptr->dc_tbl_no;
  173212. jpeg_make_d_derived_tbl(cinfo, TRUE, tbl,
  173213. & entropy->derived_tbls[tbl]);
  173214. }
  173215. } else {
  173216. tbl = compptr->ac_tbl_no;
  173217. jpeg_make_d_derived_tbl(cinfo, FALSE, tbl,
  173218. & entropy->derived_tbls[tbl]);
  173219. /* remember the single active table */
  173220. entropy->ac_derived_tbl = entropy->derived_tbls[tbl];
  173221. }
  173222. /* Initialize DC predictions to 0 */
  173223. entropy->saved.last_dc_val[ci] = 0;
  173224. }
  173225. /* Initialize bitread state variables */
  173226. entropy->bitstate.bits_left = 0;
  173227. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  173228. entropy->pub.insufficient_data = FALSE;
  173229. /* Initialize private state variables */
  173230. entropy->saved.EOBRUN = 0;
  173231. /* Initialize restart counter */
  173232. entropy->restarts_to_go = cinfo->restart_interval;
  173233. }
  173234. /*
  173235. * Check for a restart marker & resynchronize decoder.
  173236. * Returns FALSE if must suspend.
  173237. */
  173238. LOCAL(boolean)
  173239. process_restartp (j_decompress_ptr cinfo)
  173240. {
  173241. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173242. int ci;
  173243. /* Throw away any unused bits remaining in bit buffer; */
  173244. /* include any full bytes in next_marker's count of discarded bytes */
  173245. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  173246. entropy->bitstate.bits_left = 0;
  173247. /* Advance past the RSTn marker */
  173248. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  173249. return FALSE;
  173250. /* Re-initialize DC predictions to 0 */
  173251. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  173252. entropy->saved.last_dc_val[ci] = 0;
  173253. /* Re-init EOB run count, too */
  173254. entropy->saved.EOBRUN = 0;
  173255. /* Reset restart counter */
  173256. entropy->restarts_to_go = cinfo->restart_interval;
  173257. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  173258. * against a marker. In that case we will end up treating the next data
  173259. * segment as empty, and we can avoid producing bogus output pixels by
  173260. * leaving the flag set.
  173261. */
  173262. if (cinfo->unread_marker == 0)
  173263. entropy->pub.insufficient_data = FALSE;
  173264. return TRUE;
  173265. }
  173266. /*
  173267. * Huffman MCU decoding.
  173268. * Each of these routines decodes and returns one MCU's worth of
  173269. * Huffman-compressed coefficients.
  173270. * The coefficients are reordered from zigzag order into natural array order,
  173271. * but are not dequantized.
  173272. *
  173273. * The i'th block of the MCU is stored into the block pointed to by
  173274. * MCU_data[i]. WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
  173275. *
  173276. * We return FALSE if data source requested suspension. In that case no
  173277. * changes have been made to permanent state. (Exception: some output
  173278. * coefficients may already have been assigned. This is harmless for
  173279. * spectral selection, since we'll just re-assign them on the next call.
  173280. * Successive approximation AC refinement has to be more careful, however.)
  173281. */
  173282. /*
  173283. * MCU decoding for DC initial scan (either spectral selection,
  173284. * or first pass of successive approximation).
  173285. */
  173286. METHODDEF(boolean)
  173287. decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173288. {
  173289. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173290. int Al = cinfo->Al;
  173291. register int s, r;
  173292. int blkn, ci;
  173293. JBLOCKROW block;
  173294. BITREAD_STATE_VARS;
  173295. savable_state3 state;
  173296. d_derived_tbl * tbl;
  173297. jpeg_component_info * compptr;
  173298. /* Process restart marker if needed; may have to suspend */
  173299. if (cinfo->restart_interval) {
  173300. if (entropy->restarts_to_go == 0)
  173301. if (! process_restartp(cinfo))
  173302. return FALSE;
  173303. }
  173304. /* If we've run out of data, just leave the MCU set to zeroes.
  173305. * This way, we return uniform gray for the remainder of the segment.
  173306. */
  173307. if (! entropy->pub.insufficient_data) {
  173308. /* Load up working state */
  173309. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173310. ASSIGN_STATE(state, entropy->saved);
  173311. /* Outer loop handles each block in the MCU */
  173312. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  173313. block = MCU_data[blkn];
  173314. ci = cinfo->MCU_membership[blkn];
  173315. compptr = cinfo->cur_comp_info[ci];
  173316. tbl = entropy->derived_tbls[compptr->dc_tbl_no];
  173317. /* Decode a single block's worth of coefficients */
  173318. /* Section F.2.2.1: decode the DC coefficient difference */
  173319. HUFF_DECODE(s, br_state, tbl, return FALSE, label1);
  173320. if (s) {
  173321. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  173322. r = GET_BITS(s);
  173323. s = HUFF_EXTEND(r, s);
  173324. }
  173325. /* Convert DC difference to actual value, update last_dc_val */
  173326. s += state.last_dc_val[ci];
  173327. state.last_dc_val[ci] = s;
  173328. /* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */
  173329. (*block)[0] = (JCOEF) (s << Al);
  173330. }
  173331. /* Completed MCU, so update state */
  173332. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173333. ASSIGN_STATE(entropy->saved, state);
  173334. }
  173335. /* Account for restart interval (no-op if not using restarts) */
  173336. entropy->restarts_to_go--;
  173337. return TRUE;
  173338. }
  173339. /*
  173340. * MCU decoding for AC initial scan (either spectral selection,
  173341. * or first pass of successive approximation).
  173342. */
  173343. METHODDEF(boolean)
  173344. decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173345. {
  173346. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173347. int Se = cinfo->Se;
  173348. int Al = cinfo->Al;
  173349. register int s, k, r;
  173350. unsigned int EOBRUN;
  173351. JBLOCKROW block;
  173352. BITREAD_STATE_VARS;
  173353. d_derived_tbl * tbl;
  173354. /* Process restart marker if needed; may have to suspend */
  173355. if (cinfo->restart_interval) {
  173356. if (entropy->restarts_to_go == 0)
  173357. if (! process_restartp(cinfo))
  173358. return FALSE;
  173359. }
  173360. /* If we've run out of data, just leave the MCU set to zeroes.
  173361. * This way, we return uniform gray for the remainder of the segment.
  173362. */
  173363. if (! entropy->pub.insufficient_data) {
  173364. /* Load up working state.
  173365. * We can avoid loading/saving bitread state if in an EOB run.
  173366. */
  173367. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  173368. /* There is always only one block per MCU */
  173369. if (EOBRUN > 0) /* if it's a band of zeroes... */
  173370. EOBRUN--; /* ...process it now (we do nothing) */
  173371. else {
  173372. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173373. block = MCU_data[0];
  173374. tbl = entropy->ac_derived_tbl;
  173375. for (k = cinfo->Ss; k <= Se; k++) {
  173376. HUFF_DECODE(s, br_state, tbl, return FALSE, label2);
  173377. r = s >> 4;
  173378. s &= 15;
  173379. if (s) {
  173380. k += r;
  173381. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  173382. r = GET_BITS(s);
  173383. s = HUFF_EXTEND(r, s);
  173384. /* Scale and output coefficient in natural (dezigzagged) order */
  173385. (*block)[jpeg_natural_order[k]] = (JCOEF) (s << Al);
  173386. } else {
  173387. if (r == 15) { /* ZRL */
  173388. k += 15; /* skip 15 zeroes in band */
  173389. } else { /* EOBr, run length is 2^r + appended bits */
  173390. EOBRUN = 1 << r;
  173391. if (r) { /* EOBr, r > 0 */
  173392. CHECK_BIT_BUFFER(br_state, r, return FALSE);
  173393. r = GET_BITS(r);
  173394. EOBRUN += r;
  173395. }
  173396. EOBRUN--; /* this band is processed at this moment */
  173397. break; /* force end-of-band */
  173398. }
  173399. }
  173400. }
  173401. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173402. }
  173403. /* Completed MCU, so update state */
  173404. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  173405. }
  173406. /* Account for restart interval (no-op if not using restarts) */
  173407. entropy->restarts_to_go--;
  173408. return TRUE;
  173409. }
  173410. /*
  173411. * MCU decoding for DC successive approximation refinement scan.
  173412. * Note: we assume such scans can be multi-component, although the spec
  173413. * is not very clear on the point.
  173414. */
  173415. METHODDEF(boolean)
  173416. decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173417. {
  173418. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173419. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  173420. int blkn;
  173421. JBLOCKROW block;
  173422. BITREAD_STATE_VARS;
  173423. /* Process restart marker if needed; may have to suspend */
  173424. if (cinfo->restart_interval) {
  173425. if (entropy->restarts_to_go == 0)
  173426. if (! process_restartp(cinfo))
  173427. return FALSE;
  173428. }
  173429. /* Not worth the cycles to check insufficient_data here,
  173430. * since we will not change the data anyway if we read zeroes.
  173431. */
  173432. /* Load up working state */
  173433. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173434. /* Outer loop handles each block in the MCU */
  173435. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  173436. block = MCU_data[blkn];
  173437. /* Encoded data is simply the next bit of the two's-complement DC value */
  173438. CHECK_BIT_BUFFER(br_state, 1, return FALSE);
  173439. if (GET_BITS(1))
  173440. (*block)[0] |= p1;
  173441. /* Note: since we use |=, repeating the assignment later is safe */
  173442. }
  173443. /* Completed MCU, so update state */
  173444. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173445. /* Account for restart interval (no-op if not using restarts) */
  173446. entropy->restarts_to_go--;
  173447. return TRUE;
  173448. }
  173449. /*
  173450. * MCU decoding for AC successive approximation refinement scan.
  173451. */
  173452. METHODDEF(boolean)
  173453. decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173454. {
  173455. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173456. int Se = cinfo->Se;
  173457. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  173458. int m1 = (-1) << cinfo->Al; /* -1 in the bit position being coded */
  173459. register int s, k, r;
  173460. unsigned int EOBRUN;
  173461. JBLOCKROW block;
  173462. JCOEFPTR thiscoef;
  173463. BITREAD_STATE_VARS;
  173464. d_derived_tbl * tbl;
  173465. int num_newnz;
  173466. int newnz_pos[DCTSIZE2];
  173467. /* Process restart marker if needed; may have to suspend */
  173468. if (cinfo->restart_interval) {
  173469. if (entropy->restarts_to_go == 0)
  173470. if (! process_restartp(cinfo))
  173471. return FALSE;
  173472. }
  173473. /* If we've run out of data, don't modify the MCU.
  173474. */
  173475. if (! entropy->pub.insufficient_data) {
  173476. /* Load up working state */
  173477. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173478. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  173479. /* There is always only one block per MCU */
  173480. block = MCU_data[0];
  173481. tbl = entropy->ac_derived_tbl;
  173482. /* If we are forced to suspend, we must undo the assignments to any newly
  173483. * nonzero coefficients in the block, because otherwise we'd get confused
  173484. * next time about which coefficients were already nonzero.
  173485. * But we need not undo addition of bits to already-nonzero coefficients;
  173486. * instead, we can test the current bit to see if we already did it.
  173487. */
  173488. num_newnz = 0;
  173489. /* initialize coefficient loop counter to start of band */
  173490. k = cinfo->Ss;
  173491. if (EOBRUN == 0) {
  173492. for (; k <= Se; k++) {
  173493. HUFF_DECODE(s, br_state, tbl, goto undoit, label3);
  173494. r = s >> 4;
  173495. s &= 15;
  173496. if (s) {
  173497. if (s != 1) /* size of new coef should always be 1 */
  173498. WARNMS(cinfo, JWRN_HUFF_BAD_CODE);
  173499. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  173500. if (GET_BITS(1))
  173501. s = p1; /* newly nonzero coef is positive */
  173502. else
  173503. s = m1; /* newly nonzero coef is negative */
  173504. } else {
  173505. if (r != 15) {
  173506. EOBRUN = 1 << r; /* EOBr, run length is 2^r + appended bits */
  173507. if (r) {
  173508. CHECK_BIT_BUFFER(br_state, r, goto undoit);
  173509. r = GET_BITS(r);
  173510. EOBRUN += r;
  173511. }
  173512. break; /* rest of block is handled by EOB logic */
  173513. }
  173514. /* note s = 0 for processing ZRL */
  173515. }
  173516. /* Advance over already-nonzero coefs and r still-zero coefs,
  173517. * appending correction bits to the nonzeroes. A correction bit is 1
  173518. * if the absolute value of the coefficient must be increased.
  173519. */
  173520. do {
  173521. thiscoef = *block + jpeg_natural_order[k];
  173522. if (*thiscoef != 0) {
  173523. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  173524. if (GET_BITS(1)) {
  173525. if ((*thiscoef & p1) == 0) { /* do nothing if already set it */
  173526. if (*thiscoef >= 0)
  173527. *thiscoef += p1;
  173528. else
  173529. *thiscoef += m1;
  173530. }
  173531. }
  173532. } else {
  173533. if (--r < 0)
  173534. break; /* reached target zero coefficient */
  173535. }
  173536. k++;
  173537. } while (k <= Se);
  173538. if (s) {
  173539. int pos = jpeg_natural_order[k];
  173540. /* Output newly nonzero coefficient */
  173541. (*block)[pos] = (JCOEF) s;
  173542. /* Remember its position in case we have to suspend */
  173543. newnz_pos[num_newnz++] = pos;
  173544. }
  173545. }
  173546. }
  173547. if (EOBRUN > 0) {
  173548. /* Scan any remaining coefficient positions after the end-of-band
  173549. * (the last newly nonzero coefficient, if any). Append a correction
  173550. * bit to each already-nonzero coefficient. A correction bit is 1
  173551. * if the absolute value of the coefficient must be increased.
  173552. */
  173553. for (; k <= Se; k++) {
  173554. thiscoef = *block + jpeg_natural_order[k];
  173555. if (*thiscoef != 0) {
  173556. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  173557. if (GET_BITS(1)) {
  173558. if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
  173559. if (*thiscoef >= 0)
  173560. *thiscoef += p1;
  173561. else
  173562. *thiscoef += m1;
  173563. }
  173564. }
  173565. }
  173566. }
  173567. /* Count one block completed in EOB run */
  173568. EOBRUN--;
  173569. }
  173570. /* Completed MCU, so update state */
  173571. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173572. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  173573. }
  173574. /* Account for restart interval (no-op if not using restarts) */
  173575. entropy->restarts_to_go--;
  173576. return TRUE;
  173577. undoit:
  173578. /* Re-zero any output coefficients that we made newly nonzero */
  173579. while (num_newnz > 0)
  173580. (*block)[newnz_pos[--num_newnz]] = 0;
  173581. return FALSE;
  173582. }
  173583. /*
  173584. * Module initialization routine for progressive Huffman entropy decoding.
  173585. */
  173586. GLOBAL(void)
  173587. jinit_phuff_decoder (j_decompress_ptr cinfo)
  173588. {
  173589. phuff_entropy_ptr2 entropy;
  173590. int *coef_bit_ptr;
  173591. int ci, i;
  173592. entropy = (phuff_entropy_ptr2)
  173593. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173594. SIZEOF(phuff_entropy_decoder));
  173595. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  173596. entropy->pub.start_pass = start_pass_phuff_decoder;
  173597. /* Mark derived tables unallocated */
  173598. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  173599. entropy->derived_tbls[i] = NULL;
  173600. }
  173601. /* Create progression status table */
  173602. cinfo->coef_bits = (int (*)[DCTSIZE2])
  173603. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173604. cinfo->num_components*DCTSIZE2*SIZEOF(int));
  173605. coef_bit_ptr = & cinfo->coef_bits[0][0];
  173606. for (ci = 0; ci < cinfo->num_components; ci++)
  173607. for (i = 0; i < DCTSIZE2; i++)
  173608. *coef_bit_ptr++ = -1;
  173609. }
  173610. #endif /* D_PROGRESSIVE_SUPPORTED */
  173611. /*** End of inlined file: jdphuff.c ***/
  173612. /*** Start of inlined file: jdpostct.c ***/
  173613. #define JPEG_INTERNALS
  173614. /* Private buffer controller object */
  173615. typedef struct {
  173616. struct jpeg_d_post_controller pub; /* public fields */
  173617. /* Color quantization source buffer: this holds output data from
  173618. * the upsample/color conversion step to be passed to the quantizer.
  173619. * For two-pass color quantization, we need a full-image buffer;
  173620. * for one-pass operation, a strip buffer is sufficient.
  173621. */
  173622. jvirt_sarray_ptr whole_image; /* virtual array, or NULL if one-pass */
  173623. JSAMPARRAY buffer; /* strip buffer, or current strip of virtual */
  173624. JDIMENSION strip_height; /* buffer size in rows */
  173625. /* for two-pass mode only: */
  173626. JDIMENSION starting_row; /* row # of first row in current strip */
  173627. JDIMENSION next_row; /* index of next row to fill/empty in strip */
  173628. } my_post_controller;
  173629. typedef my_post_controller * my_post_ptr;
  173630. /* Forward declarations */
  173631. METHODDEF(void) post_process_1pass
  173632. JPP((j_decompress_ptr cinfo,
  173633. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173634. JDIMENSION in_row_groups_avail,
  173635. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173636. JDIMENSION out_rows_avail));
  173637. #ifdef QUANT_2PASS_SUPPORTED
  173638. METHODDEF(void) post_process_prepass
  173639. JPP((j_decompress_ptr cinfo,
  173640. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173641. JDIMENSION in_row_groups_avail,
  173642. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173643. JDIMENSION out_rows_avail));
  173644. METHODDEF(void) post_process_2pass
  173645. JPP((j_decompress_ptr cinfo,
  173646. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173647. JDIMENSION in_row_groups_avail,
  173648. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173649. JDIMENSION out_rows_avail));
  173650. #endif
  173651. /*
  173652. * Initialize for a processing pass.
  173653. */
  173654. METHODDEF(void)
  173655. start_pass_dpost (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  173656. {
  173657. my_post_ptr post = (my_post_ptr) cinfo->post;
  173658. switch (pass_mode) {
  173659. case JBUF_PASS_THRU:
  173660. if (cinfo->quantize_colors) {
  173661. /* Single-pass processing with color quantization. */
  173662. post->pub.post_process_data = post_process_1pass;
  173663. /* We could be doing buffered-image output before starting a 2-pass
  173664. * color quantization; in that case, jinit_d_post_controller did not
  173665. * allocate a strip buffer. Use the virtual-array buffer as workspace.
  173666. */
  173667. if (post->buffer == NULL) {
  173668. post->buffer = (*cinfo->mem->access_virt_sarray)
  173669. ((j_common_ptr) cinfo, post->whole_image,
  173670. (JDIMENSION) 0, post->strip_height, TRUE);
  173671. }
  173672. } else {
  173673. /* For single-pass processing without color quantization,
  173674. * I have no work to do; just call the upsampler directly.
  173675. */
  173676. post->pub.post_process_data = cinfo->upsample->upsample;
  173677. }
  173678. break;
  173679. #ifdef QUANT_2PASS_SUPPORTED
  173680. case JBUF_SAVE_AND_PASS:
  173681. /* First pass of 2-pass quantization */
  173682. if (post->whole_image == NULL)
  173683. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173684. post->pub.post_process_data = post_process_prepass;
  173685. break;
  173686. case JBUF_CRANK_DEST:
  173687. /* Second pass of 2-pass quantization */
  173688. if (post->whole_image == NULL)
  173689. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173690. post->pub.post_process_data = post_process_2pass;
  173691. break;
  173692. #endif /* QUANT_2PASS_SUPPORTED */
  173693. default:
  173694. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173695. break;
  173696. }
  173697. post->starting_row = post->next_row = 0;
  173698. }
  173699. /*
  173700. * Process some data in the one-pass (strip buffer) case.
  173701. * This is used for color precision reduction as well as one-pass quantization.
  173702. */
  173703. METHODDEF(void)
  173704. post_process_1pass (j_decompress_ptr cinfo,
  173705. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173706. JDIMENSION in_row_groups_avail,
  173707. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173708. JDIMENSION out_rows_avail)
  173709. {
  173710. my_post_ptr post = (my_post_ptr) cinfo->post;
  173711. JDIMENSION num_rows, max_rows;
  173712. /* Fill the buffer, but not more than what we can dump out in one go. */
  173713. /* Note we rely on the upsampler to detect bottom of image. */
  173714. max_rows = out_rows_avail - *out_row_ctr;
  173715. if (max_rows > post->strip_height)
  173716. max_rows = post->strip_height;
  173717. num_rows = 0;
  173718. (*cinfo->upsample->upsample) (cinfo,
  173719. input_buf, in_row_group_ctr, in_row_groups_avail,
  173720. post->buffer, &num_rows, max_rows);
  173721. /* Quantize and emit data. */
  173722. (*cinfo->cquantize->color_quantize) (cinfo,
  173723. post->buffer, output_buf + *out_row_ctr, (int) num_rows);
  173724. *out_row_ctr += num_rows;
  173725. }
  173726. #ifdef QUANT_2PASS_SUPPORTED
  173727. /*
  173728. * Process some data in the first pass of 2-pass quantization.
  173729. */
  173730. METHODDEF(void)
  173731. post_process_prepass (j_decompress_ptr cinfo,
  173732. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173733. JDIMENSION in_row_groups_avail,
  173734. JSAMPARRAY, JDIMENSION *out_row_ctr,
  173735. JDIMENSION)
  173736. {
  173737. my_post_ptr post = (my_post_ptr) cinfo->post;
  173738. JDIMENSION old_next_row, num_rows;
  173739. /* Reposition virtual buffer if at start of strip. */
  173740. if (post->next_row == 0) {
  173741. post->buffer = (*cinfo->mem->access_virt_sarray)
  173742. ((j_common_ptr) cinfo, post->whole_image,
  173743. post->starting_row, post->strip_height, TRUE);
  173744. }
  173745. /* Upsample some data (up to a strip height's worth). */
  173746. old_next_row = post->next_row;
  173747. (*cinfo->upsample->upsample) (cinfo,
  173748. input_buf, in_row_group_ctr, in_row_groups_avail,
  173749. post->buffer, &post->next_row, post->strip_height);
  173750. /* Allow quantizer to scan new data. No data is emitted, */
  173751. /* but we advance out_row_ctr so outer loop can tell when we're done. */
  173752. if (post->next_row > old_next_row) {
  173753. num_rows = post->next_row - old_next_row;
  173754. (*cinfo->cquantize->color_quantize) (cinfo, post->buffer + old_next_row,
  173755. (JSAMPARRAY) NULL, (int) num_rows);
  173756. *out_row_ctr += num_rows;
  173757. }
  173758. /* Advance if we filled the strip. */
  173759. if (post->next_row >= post->strip_height) {
  173760. post->starting_row += post->strip_height;
  173761. post->next_row = 0;
  173762. }
  173763. }
  173764. /*
  173765. * Process some data in the second pass of 2-pass quantization.
  173766. */
  173767. METHODDEF(void)
  173768. post_process_2pass (j_decompress_ptr cinfo,
  173769. JSAMPIMAGE, JDIMENSION *,
  173770. JDIMENSION,
  173771. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173772. JDIMENSION out_rows_avail)
  173773. {
  173774. my_post_ptr post = (my_post_ptr) cinfo->post;
  173775. JDIMENSION num_rows, max_rows;
  173776. /* Reposition virtual buffer if at start of strip. */
  173777. if (post->next_row == 0) {
  173778. post->buffer = (*cinfo->mem->access_virt_sarray)
  173779. ((j_common_ptr) cinfo, post->whole_image,
  173780. post->starting_row, post->strip_height, FALSE);
  173781. }
  173782. /* Determine number of rows to emit. */
  173783. num_rows = post->strip_height - post->next_row; /* available in strip */
  173784. max_rows = out_rows_avail - *out_row_ctr; /* available in output area */
  173785. if (num_rows > max_rows)
  173786. num_rows = max_rows;
  173787. /* We have to check bottom of image here, can't depend on upsampler. */
  173788. max_rows = cinfo->output_height - post->starting_row;
  173789. if (num_rows > max_rows)
  173790. num_rows = max_rows;
  173791. /* Quantize and emit data. */
  173792. (*cinfo->cquantize->color_quantize) (cinfo,
  173793. post->buffer + post->next_row, output_buf + *out_row_ctr,
  173794. (int) num_rows);
  173795. *out_row_ctr += num_rows;
  173796. /* Advance if we filled the strip. */
  173797. post->next_row += num_rows;
  173798. if (post->next_row >= post->strip_height) {
  173799. post->starting_row += post->strip_height;
  173800. post->next_row = 0;
  173801. }
  173802. }
  173803. #endif /* QUANT_2PASS_SUPPORTED */
  173804. /*
  173805. * Initialize postprocessing controller.
  173806. */
  173807. GLOBAL(void)
  173808. jinit_d_post_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  173809. {
  173810. my_post_ptr post;
  173811. post = (my_post_ptr)
  173812. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173813. SIZEOF(my_post_controller));
  173814. cinfo->post = (struct jpeg_d_post_controller *) post;
  173815. post->pub.start_pass = start_pass_dpost;
  173816. post->whole_image = NULL; /* flag for no virtual arrays */
  173817. post->buffer = NULL; /* flag for no strip buffer */
  173818. /* Create the quantization buffer, if needed */
  173819. if (cinfo->quantize_colors) {
  173820. /* The buffer strip height is max_v_samp_factor, which is typically
  173821. * an efficient number of rows for upsampling to return.
  173822. * (In the presence of output rescaling, we might want to be smarter?)
  173823. */
  173824. post->strip_height = (JDIMENSION) cinfo->max_v_samp_factor;
  173825. if (need_full_buffer) {
  173826. /* Two-pass color quantization: need full-image storage. */
  173827. /* We round up the number of rows to a multiple of the strip height. */
  173828. #ifdef QUANT_2PASS_SUPPORTED
  173829. post->whole_image = (*cinfo->mem->request_virt_sarray)
  173830. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  173831. cinfo->output_width * cinfo->out_color_components,
  173832. (JDIMENSION) jround_up((long) cinfo->output_height,
  173833. (long) post->strip_height),
  173834. post->strip_height);
  173835. #else
  173836. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173837. #endif /* QUANT_2PASS_SUPPORTED */
  173838. } else {
  173839. /* One-pass color quantization: just make a strip buffer. */
  173840. post->buffer = (*cinfo->mem->alloc_sarray)
  173841. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173842. cinfo->output_width * cinfo->out_color_components,
  173843. post->strip_height);
  173844. }
  173845. }
  173846. }
  173847. /*** End of inlined file: jdpostct.c ***/
  173848. #undef FIX
  173849. /*** Start of inlined file: jdsample.c ***/
  173850. #define JPEG_INTERNALS
  173851. /* Pointer to routine to upsample a single component */
  173852. typedef JMETHOD(void, upsample1_ptr,
  173853. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173854. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr));
  173855. /* Private subobject */
  173856. typedef struct {
  173857. struct jpeg_upsampler pub; /* public fields */
  173858. /* Color conversion buffer. When using separate upsampling and color
  173859. * conversion steps, this buffer holds one upsampled row group until it
  173860. * has been color converted and output.
  173861. * Note: we do not allocate any storage for component(s) which are full-size,
  173862. * ie do not need rescaling. The corresponding entry of color_buf[] is
  173863. * simply set to point to the input data array, thereby avoiding copying.
  173864. */
  173865. JSAMPARRAY color_buf[MAX_COMPONENTS];
  173866. /* Per-component upsampling method pointers */
  173867. upsample1_ptr methods[MAX_COMPONENTS];
  173868. int next_row_out; /* counts rows emitted from color_buf */
  173869. JDIMENSION rows_to_go; /* counts rows remaining in image */
  173870. /* Height of an input row group for each component. */
  173871. int rowgroup_height[MAX_COMPONENTS];
  173872. /* These arrays save pixel expansion factors so that int_expand need not
  173873. * recompute them each time. They are unused for other upsampling methods.
  173874. */
  173875. UINT8 h_expand[MAX_COMPONENTS];
  173876. UINT8 v_expand[MAX_COMPONENTS];
  173877. } my_upsampler2;
  173878. typedef my_upsampler2 * my_upsample_ptr2;
  173879. /*
  173880. * Initialize for an upsampling pass.
  173881. */
  173882. METHODDEF(void)
  173883. start_pass_upsample (j_decompress_ptr cinfo)
  173884. {
  173885. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  173886. /* Mark the conversion buffer empty */
  173887. upsample->next_row_out = cinfo->max_v_samp_factor;
  173888. /* Initialize total-height counter for detecting bottom of image */
  173889. upsample->rows_to_go = cinfo->output_height;
  173890. }
  173891. /*
  173892. * Control routine to do upsampling (and color conversion).
  173893. *
  173894. * In this version we upsample each component independently.
  173895. * We upsample one row group into the conversion buffer, then apply
  173896. * color conversion a row at a time.
  173897. */
  173898. METHODDEF(void)
  173899. sep_upsample (j_decompress_ptr cinfo,
  173900. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173901. JDIMENSION,
  173902. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173903. JDIMENSION out_rows_avail)
  173904. {
  173905. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  173906. int ci;
  173907. jpeg_component_info * compptr;
  173908. JDIMENSION num_rows;
  173909. /* Fill the conversion buffer, if it's empty */
  173910. if (upsample->next_row_out >= cinfo->max_v_samp_factor) {
  173911. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  173912. ci++, compptr++) {
  173913. /* Invoke per-component upsample method. Notice we pass a POINTER
  173914. * to color_buf[ci], so that fullsize_upsample can change it.
  173915. */
  173916. (*upsample->methods[ci]) (cinfo, compptr,
  173917. input_buf[ci] + (*in_row_group_ctr * upsample->rowgroup_height[ci]),
  173918. upsample->color_buf + ci);
  173919. }
  173920. upsample->next_row_out = 0;
  173921. }
  173922. /* Color-convert and emit rows */
  173923. /* How many we have in the buffer: */
  173924. num_rows = (JDIMENSION) (cinfo->max_v_samp_factor - upsample->next_row_out);
  173925. /* Not more than the distance to the end of the image. Need this test
  173926. * in case the image height is not a multiple of max_v_samp_factor:
  173927. */
  173928. if (num_rows > upsample->rows_to_go)
  173929. num_rows = upsample->rows_to_go;
  173930. /* And not more than what the client can accept: */
  173931. out_rows_avail -= *out_row_ctr;
  173932. if (num_rows > out_rows_avail)
  173933. num_rows = out_rows_avail;
  173934. (*cinfo->cconvert->color_convert) (cinfo, upsample->color_buf,
  173935. (JDIMENSION) upsample->next_row_out,
  173936. output_buf + *out_row_ctr,
  173937. (int) num_rows);
  173938. /* Adjust counts */
  173939. *out_row_ctr += num_rows;
  173940. upsample->rows_to_go -= num_rows;
  173941. upsample->next_row_out += num_rows;
  173942. /* When the buffer is emptied, declare this input row group consumed */
  173943. if (upsample->next_row_out >= cinfo->max_v_samp_factor)
  173944. (*in_row_group_ctr)++;
  173945. }
  173946. /*
  173947. * These are the routines invoked by sep_upsample to upsample pixel values
  173948. * of a single component. One row group is processed per call.
  173949. */
  173950. /*
  173951. * For full-size components, we just make color_buf[ci] point at the
  173952. * input buffer, and thus avoid copying any data. Note that this is
  173953. * safe only because sep_upsample doesn't declare the input row group
  173954. * "consumed" until we are done color converting and emitting it.
  173955. */
  173956. METHODDEF(void)
  173957. fullsize_upsample (j_decompress_ptr, jpeg_component_info *,
  173958. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173959. {
  173960. *output_data_ptr = input_data;
  173961. }
  173962. /*
  173963. * This is a no-op version used for "uninteresting" components.
  173964. * These components will not be referenced by color conversion.
  173965. */
  173966. METHODDEF(void)
  173967. noop_upsample (j_decompress_ptr, jpeg_component_info *,
  173968. JSAMPARRAY, JSAMPARRAY * output_data_ptr)
  173969. {
  173970. *output_data_ptr = NULL; /* safety check */
  173971. }
  173972. /*
  173973. * This version handles any integral sampling ratios.
  173974. * This is not used for typical JPEG files, so it need not be fast.
  173975. * Nor, for that matter, is it particularly accurate: the algorithm is
  173976. * simple replication of the input pixel onto the corresponding output
  173977. * pixels. The hi-falutin sampling literature refers to this as a
  173978. * "box filter". A box filter tends to introduce visible artifacts,
  173979. * so if you are actually going to use 3:1 or 4:1 sampling ratios
  173980. * you would be well advised to improve this code.
  173981. */
  173982. METHODDEF(void)
  173983. int_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173984. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173985. {
  173986. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  173987. JSAMPARRAY output_data = *output_data_ptr;
  173988. register JSAMPROW inptr, outptr;
  173989. register JSAMPLE invalue;
  173990. register int h;
  173991. JSAMPROW outend;
  173992. int h_expand, v_expand;
  173993. int inrow, outrow;
  173994. h_expand = upsample->h_expand[compptr->component_index];
  173995. v_expand = upsample->v_expand[compptr->component_index];
  173996. inrow = outrow = 0;
  173997. while (outrow < cinfo->max_v_samp_factor) {
  173998. /* Generate one output row with proper horizontal expansion */
  173999. inptr = input_data[inrow];
  174000. outptr = output_data[outrow];
  174001. outend = outptr + cinfo->output_width;
  174002. while (outptr < outend) {
  174003. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  174004. for (h = h_expand; h > 0; h--) {
  174005. *outptr++ = invalue;
  174006. }
  174007. }
  174008. /* Generate any additional output rows by duplicating the first one */
  174009. if (v_expand > 1) {
  174010. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  174011. v_expand-1, cinfo->output_width);
  174012. }
  174013. inrow++;
  174014. outrow += v_expand;
  174015. }
  174016. }
  174017. /*
  174018. * Fast processing for the common case of 2:1 horizontal and 1:1 vertical.
  174019. * It's still a box filter.
  174020. */
  174021. METHODDEF(void)
  174022. h2v1_upsample (j_decompress_ptr cinfo, jpeg_component_info *,
  174023. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  174024. {
  174025. JSAMPARRAY output_data = *output_data_ptr;
  174026. register JSAMPROW inptr, outptr;
  174027. register JSAMPLE invalue;
  174028. JSAMPROW outend;
  174029. int inrow;
  174030. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  174031. inptr = input_data[inrow];
  174032. outptr = output_data[inrow];
  174033. outend = outptr + cinfo->output_width;
  174034. while (outptr < outend) {
  174035. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  174036. *outptr++ = invalue;
  174037. *outptr++ = invalue;
  174038. }
  174039. }
  174040. }
  174041. /*
  174042. * Fast processing for the common case of 2:1 horizontal and 2:1 vertical.
  174043. * It's still a box filter.
  174044. */
  174045. METHODDEF(void)
  174046. h2v2_upsample (j_decompress_ptr cinfo, jpeg_component_info *,
  174047. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  174048. {
  174049. JSAMPARRAY output_data = *output_data_ptr;
  174050. register JSAMPROW inptr, outptr;
  174051. register JSAMPLE invalue;
  174052. JSAMPROW outend;
  174053. int inrow, outrow;
  174054. inrow = outrow = 0;
  174055. while (outrow < cinfo->max_v_samp_factor) {
  174056. inptr = input_data[inrow];
  174057. outptr = output_data[outrow];
  174058. outend = outptr + cinfo->output_width;
  174059. while (outptr < outend) {
  174060. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  174061. *outptr++ = invalue;
  174062. *outptr++ = invalue;
  174063. }
  174064. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  174065. 1, cinfo->output_width);
  174066. inrow++;
  174067. outrow += 2;
  174068. }
  174069. }
  174070. /*
  174071. * Fancy processing for the common case of 2:1 horizontal and 1:1 vertical.
  174072. *
  174073. * The upsampling algorithm is linear interpolation between pixel centers,
  174074. * also known as a "triangle filter". This is a good compromise between
  174075. * speed and visual quality. The centers of the output pixels are 1/4 and 3/4
  174076. * of the way between input pixel centers.
  174077. *
  174078. * A note about the "bias" calculations: when rounding fractional values to
  174079. * integer, we do not want to always round 0.5 up to the next integer.
  174080. * If we did that, we'd introduce a noticeable bias towards larger values.
  174081. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  174082. * alternate pixel locations (a simple ordered dither pattern).
  174083. */
  174084. METHODDEF(void)
  174085. h2v1_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174086. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  174087. {
  174088. JSAMPARRAY output_data = *output_data_ptr;
  174089. register JSAMPROW inptr, outptr;
  174090. register int invalue;
  174091. register JDIMENSION colctr;
  174092. int inrow;
  174093. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  174094. inptr = input_data[inrow];
  174095. outptr = output_data[inrow];
  174096. /* Special case for first column */
  174097. invalue = GETJSAMPLE(*inptr++);
  174098. *outptr++ = (JSAMPLE) invalue;
  174099. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(*inptr) + 2) >> 2);
  174100. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  174101. /* General case: 3/4 * nearer pixel + 1/4 * further pixel */
  174102. invalue = GETJSAMPLE(*inptr++) * 3;
  174103. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(inptr[-2]) + 1) >> 2);
  174104. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(*inptr) + 2) >> 2);
  174105. }
  174106. /* Special case for last column */
  174107. invalue = GETJSAMPLE(*inptr);
  174108. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(inptr[-1]) + 1) >> 2);
  174109. *outptr++ = (JSAMPLE) invalue;
  174110. }
  174111. }
  174112. /*
  174113. * Fancy processing for the common case of 2:1 horizontal and 2:1 vertical.
  174114. * Again a triangle filter; see comments for h2v1 case, above.
  174115. *
  174116. * It is OK for us to reference the adjacent input rows because we demanded
  174117. * context from the main buffer controller (see initialization code).
  174118. */
  174119. METHODDEF(void)
  174120. h2v2_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174121. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  174122. {
  174123. JSAMPARRAY output_data = *output_data_ptr;
  174124. register JSAMPROW inptr0, inptr1, outptr;
  174125. #if BITS_IN_JSAMPLE == 8
  174126. register int thiscolsum, lastcolsum, nextcolsum;
  174127. #else
  174128. register INT32 thiscolsum, lastcolsum, nextcolsum;
  174129. #endif
  174130. register JDIMENSION colctr;
  174131. int inrow, outrow, v;
  174132. inrow = outrow = 0;
  174133. while (outrow < cinfo->max_v_samp_factor) {
  174134. for (v = 0; v < 2; v++) {
  174135. /* inptr0 points to nearest input row, inptr1 points to next nearest */
  174136. inptr0 = input_data[inrow];
  174137. if (v == 0) /* next nearest is row above */
  174138. inptr1 = input_data[inrow-1];
  174139. else /* next nearest is row below */
  174140. inptr1 = input_data[inrow+1];
  174141. outptr = output_data[outrow++];
  174142. /* Special case for first column */
  174143. thiscolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  174144. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  174145. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 8) >> 4);
  174146. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  174147. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  174148. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  174149. /* General case: 3/4 * nearer pixel + 1/4 * further pixel in each */
  174150. /* dimension, thus 9/16, 3/16, 3/16, 1/16 overall */
  174151. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  174152. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  174153. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  174154. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  174155. }
  174156. /* Special case for last column */
  174157. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  174158. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 7) >> 4);
  174159. }
  174160. inrow++;
  174161. }
  174162. }
  174163. /*
  174164. * Module initialization routine for upsampling.
  174165. */
  174166. GLOBAL(void)
  174167. jinit_upsampler (j_decompress_ptr cinfo)
  174168. {
  174169. my_upsample_ptr2 upsample;
  174170. int ci;
  174171. jpeg_component_info * compptr;
  174172. boolean need_buffer, do_fancy;
  174173. int h_in_group, v_in_group, h_out_group, v_out_group;
  174174. upsample = (my_upsample_ptr2)
  174175. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  174176. SIZEOF(my_upsampler2));
  174177. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  174178. upsample->pub.start_pass = start_pass_upsample;
  174179. upsample->pub.upsample = sep_upsample;
  174180. upsample->pub.need_context_rows = FALSE; /* until we find out differently */
  174181. if (cinfo->CCIR601_sampling) /* this isn't supported */
  174182. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  174183. /* jdmainct.c doesn't support context rows when min_DCT_scaled_size = 1,
  174184. * so don't ask for it.
  174185. */
  174186. do_fancy = cinfo->do_fancy_upsampling && cinfo->min_DCT_scaled_size > 1;
  174187. /* Verify we can handle the sampling factors, select per-component methods,
  174188. * and create storage as needed.
  174189. */
  174190. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  174191. ci++, compptr++) {
  174192. /* Compute size of an "input group" after IDCT scaling. This many samples
  174193. * are to be converted to max_h_samp_factor * max_v_samp_factor pixels.
  174194. */
  174195. h_in_group = (compptr->h_samp_factor * compptr->DCT_scaled_size) /
  174196. cinfo->min_DCT_scaled_size;
  174197. v_in_group = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  174198. cinfo->min_DCT_scaled_size;
  174199. h_out_group = cinfo->max_h_samp_factor;
  174200. v_out_group = cinfo->max_v_samp_factor;
  174201. upsample->rowgroup_height[ci] = v_in_group; /* save for use later */
  174202. need_buffer = TRUE;
  174203. if (! compptr->component_needed) {
  174204. /* Don't bother to upsample an uninteresting component. */
  174205. upsample->methods[ci] = noop_upsample;
  174206. need_buffer = FALSE;
  174207. } else if (h_in_group == h_out_group && v_in_group == v_out_group) {
  174208. /* Fullsize components can be processed without any work. */
  174209. upsample->methods[ci] = fullsize_upsample;
  174210. need_buffer = FALSE;
  174211. } else if (h_in_group * 2 == h_out_group &&
  174212. v_in_group == v_out_group) {
  174213. /* Special cases for 2h1v upsampling */
  174214. if (do_fancy && compptr->downsampled_width > 2)
  174215. upsample->methods[ci] = h2v1_fancy_upsample;
  174216. else
  174217. upsample->methods[ci] = h2v1_upsample;
  174218. } else if (h_in_group * 2 == h_out_group &&
  174219. v_in_group * 2 == v_out_group) {
  174220. /* Special cases for 2h2v upsampling */
  174221. if (do_fancy && compptr->downsampled_width > 2) {
  174222. upsample->methods[ci] = h2v2_fancy_upsample;
  174223. upsample->pub.need_context_rows = TRUE;
  174224. } else
  174225. upsample->methods[ci] = h2v2_upsample;
  174226. } else if ((h_out_group % h_in_group) == 0 &&
  174227. (v_out_group % v_in_group) == 0) {
  174228. /* Generic integral-factors upsampling method */
  174229. upsample->methods[ci] = int_upsample;
  174230. upsample->h_expand[ci] = (UINT8) (h_out_group / h_in_group);
  174231. upsample->v_expand[ci] = (UINT8) (v_out_group / v_in_group);
  174232. } else
  174233. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  174234. if (need_buffer) {
  174235. upsample->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  174236. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  174237. (JDIMENSION) jround_up((long) cinfo->output_width,
  174238. (long) cinfo->max_h_samp_factor),
  174239. (JDIMENSION) cinfo->max_v_samp_factor);
  174240. }
  174241. }
  174242. }
  174243. /*** End of inlined file: jdsample.c ***/
  174244. /*** Start of inlined file: jdtrans.c ***/
  174245. #define JPEG_INTERNALS
  174246. /* Forward declarations */
  174247. LOCAL(void) transdecode_master_selection JPP((j_decompress_ptr cinfo));
  174248. /*
  174249. * Read the coefficient arrays from a JPEG file.
  174250. * jpeg_read_header must be completed before calling this.
  174251. *
  174252. * The entire image is read into a set of virtual coefficient-block arrays,
  174253. * one per component. The return value is a pointer to the array of
  174254. * virtual-array descriptors. These can be manipulated directly via the
  174255. * JPEG memory manager, or handed off to jpeg_write_coefficients().
  174256. * To release the memory occupied by the virtual arrays, call
  174257. * jpeg_finish_decompress() when done with the data.
  174258. *
  174259. * An alternative usage is to simply obtain access to the coefficient arrays
  174260. * during a buffered-image-mode decompression operation. This is allowed
  174261. * after any jpeg_finish_output() call. The arrays can be accessed until
  174262. * jpeg_finish_decompress() is called. (Note that any call to the library
  174263. * may reposition the arrays, so don't rely on access_virt_barray() results
  174264. * to stay valid across library calls.)
  174265. *
  174266. * Returns NULL if suspended. This case need be checked only if
  174267. * a suspending data source is used.
  174268. */
  174269. GLOBAL(jvirt_barray_ptr *)
  174270. jpeg_read_coefficients (j_decompress_ptr cinfo)
  174271. {
  174272. if (cinfo->global_state == DSTATE_READY) {
  174273. /* First call: initialize active modules */
  174274. transdecode_master_selection(cinfo);
  174275. cinfo->global_state = DSTATE_RDCOEFS;
  174276. }
  174277. if (cinfo->global_state == DSTATE_RDCOEFS) {
  174278. /* Absorb whole file into the coef buffer */
  174279. for (;;) {
  174280. int retcode;
  174281. /* Call progress monitor hook if present */
  174282. if (cinfo->progress != NULL)
  174283. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  174284. /* Absorb some more input */
  174285. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  174286. if (retcode == JPEG_SUSPENDED)
  174287. return NULL;
  174288. if (retcode == JPEG_REACHED_EOI)
  174289. break;
  174290. /* Advance progress counter if appropriate */
  174291. if (cinfo->progress != NULL &&
  174292. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  174293. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  174294. /* startup underestimated number of scans; ratchet up one scan */
  174295. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  174296. }
  174297. }
  174298. }
  174299. /* Set state so that jpeg_finish_decompress does the right thing */
  174300. cinfo->global_state = DSTATE_STOPPING;
  174301. }
  174302. /* At this point we should be in state DSTATE_STOPPING if being used
  174303. * standalone, or in state DSTATE_BUFIMAGE if being invoked to get access
  174304. * to the coefficients during a full buffered-image-mode decompression.
  174305. */
  174306. if ((cinfo->global_state == DSTATE_STOPPING ||
  174307. cinfo->global_state == DSTATE_BUFIMAGE) && cinfo->buffered_image) {
  174308. return cinfo->coef->coef_arrays;
  174309. }
  174310. /* Oops, improper usage */
  174311. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  174312. return NULL; /* keep compiler happy */
  174313. }
  174314. /*
  174315. * Master selection of decompression modules for transcoding.
  174316. * This substitutes for jdmaster.c's initialization of the full decompressor.
  174317. */
  174318. LOCAL(void)
  174319. transdecode_master_selection (j_decompress_ptr cinfo)
  174320. {
  174321. /* This is effectively a buffered-image operation. */
  174322. cinfo->buffered_image = TRUE;
  174323. /* Entropy decoding: either Huffman or arithmetic coding. */
  174324. if (cinfo->arith_code) {
  174325. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  174326. } else {
  174327. if (cinfo->progressive_mode) {
  174328. #ifdef D_PROGRESSIVE_SUPPORTED
  174329. jinit_phuff_decoder(cinfo);
  174330. #else
  174331. ERREXIT(cinfo, JERR_NOT_COMPILED);
  174332. #endif
  174333. } else
  174334. jinit_huff_decoder(cinfo);
  174335. }
  174336. /* Always get a full-image coefficient buffer. */
  174337. jinit_d_coef_controller(cinfo, TRUE);
  174338. /* We can now tell the memory manager to allocate virtual arrays. */
  174339. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  174340. /* Initialize input side of decompressor to consume first scan. */
  174341. (*cinfo->inputctl->start_input_pass) (cinfo);
  174342. /* Initialize progress monitoring. */
  174343. if (cinfo->progress != NULL) {
  174344. int nscans;
  174345. /* Estimate number of scans to set pass_limit. */
  174346. if (cinfo->progressive_mode) {
  174347. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  174348. nscans = 2 + 3 * cinfo->num_components;
  174349. } else if (cinfo->inputctl->has_multiple_scans) {
  174350. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  174351. nscans = cinfo->num_components;
  174352. } else {
  174353. nscans = 1;
  174354. }
  174355. cinfo->progress->pass_counter = 0L;
  174356. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  174357. cinfo->progress->completed_passes = 0;
  174358. cinfo->progress->total_passes = 1;
  174359. }
  174360. }
  174361. /*** End of inlined file: jdtrans.c ***/
  174362. /*** Start of inlined file: jfdctflt.c ***/
  174363. #define JPEG_INTERNALS
  174364. #ifdef DCT_FLOAT_SUPPORTED
  174365. /*
  174366. * This module is specialized to the case DCTSIZE = 8.
  174367. */
  174368. #if DCTSIZE != 8
  174369. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174370. #endif
  174371. /*
  174372. * Perform the forward DCT on one block of samples.
  174373. */
  174374. GLOBAL(void)
  174375. jpeg_fdct_float (FAST_FLOAT * data)
  174376. {
  174377. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174378. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  174379. FAST_FLOAT z1, z2, z3, z4, z5, z11, z13;
  174380. FAST_FLOAT *dataptr;
  174381. int ctr;
  174382. /* Pass 1: process rows. */
  174383. dataptr = data;
  174384. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174385. tmp0 = dataptr[0] + dataptr[7];
  174386. tmp7 = dataptr[0] - dataptr[7];
  174387. tmp1 = dataptr[1] + dataptr[6];
  174388. tmp6 = dataptr[1] - dataptr[6];
  174389. tmp2 = dataptr[2] + dataptr[5];
  174390. tmp5 = dataptr[2] - dataptr[5];
  174391. tmp3 = dataptr[3] + dataptr[4];
  174392. tmp4 = dataptr[3] - dataptr[4];
  174393. /* Even part */
  174394. tmp10 = tmp0 + tmp3; /* phase 2 */
  174395. tmp13 = tmp0 - tmp3;
  174396. tmp11 = tmp1 + tmp2;
  174397. tmp12 = tmp1 - tmp2;
  174398. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  174399. dataptr[4] = tmp10 - tmp11;
  174400. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  174401. dataptr[2] = tmp13 + z1; /* phase 5 */
  174402. dataptr[6] = tmp13 - z1;
  174403. /* Odd part */
  174404. tmp10 = tmp4 + tmp5; /* phase 2 */
  174405. tmp11 = tmp5 + tmp6;
  174406. tmp12 = tmp6 + tmp7;
  174407. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174408. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  174409. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  174410. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  174411. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  174412. z11 = tmp7 + z3; /* phase 5 */
  174413. z13 = tmp7 - z3;
  174414. dataptr[5] = z13 + z2; /* phase 6 */
  174415. dataptr[3] = z13 - z2;
  174416. dataptr[1] = z11 + z4;
  174417. dataptr[7] = z11 - z4;
  174418. dataptr += DCTSIZE; /* advance pointer to next row */
  174419. }
  174420. /* Pass 2: process columns. */
  174421. dataptr = data;
  174422. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174423. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174424. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174425. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174426. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174427. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174428. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174429. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174430. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174431. /* Even part */
  174432. tmp10 = tmp0 + tmp3; /* phase 2 */
  174433. tmp13 = tmp0 - tmp3;
  174434. tmp11 = tmp1 + tmp2;
  174435. tmp12 = tmp1 - tmp2;
  174436. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  174437. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  174438. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  174439. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  174440. dataptr[DCTSIZE*6] = tmp13 - z1;
  174441. /* Odd part */
  174442. tmp10 = tmp4 + tmp5; /* phase 2 */
  174443. tmp11 = tmp5 + tmp6;
  174444. tmp12 = tmp6 + tmp7;
  174445. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174446. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  174447. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  174448. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  174449. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  174450. z11 = tmp7 + z3; /* phase 5 */
  174451. z13 = tmp7 - z3;
  174452. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  174453. dataptr[DCTSIZE*3] = z13 - z2;
  174454. dataptr[DCTSIZE*1] = z11 + z4;
  174455. dataptr[DCTSIZE*7] = z11 - z4;
  174456. dataptr++; /* advance pointer to next column */
  174457. }
  174458. }
  174459. #endif /* DCT_FLOAT_SUPPORTED */
  174460. /*** End of inlined file: jfdctflt.c ***/
  174461. /*** Start of inlined file: jfdctint.c ***/
  174462. #define JPEG_INTERNALS
  174463. #ifdef DCT_ISLOW_SUPPORTED
  174464. /*
  174465. * This module is specialized to the case DCTSIZE = 8.
  174466. */
  174467. #if DCTSIZE != 8
  174468. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174469. #endif
  174470. /*
  174471. * The poop on this scaling stuff is as follows:
  174472. *
  174473. * Each 1-D DCT step produces outputs which are a factor of sqrt(N)
  174474. * larger than the true DCT outputs. The final outputs are therefore
  174475. * a factor of N larger than desired; since N=8 this can be cured by
  174476. * a simple right shift at the end of the algorithm. The advantage of
  174477. * this arrangement is that we save two multiplications per 1-D DCT,
  174478. * because the y0 and y4 outputs need not be divided by sqrt(N).
  174479. * In the IJG code, this factor of 8 is removed by the quantization step
  174480. * (in jcdctmgr.c), NOT in this module.
  174481. *
  174482. * We have to do addition and subtraction of the integer inputs, which
  174483. * is no problem, and multiplication by fractional constants, which is
  174484. * a problem to do in integer arithmetic. We multiply all the constants
  174485. * by CONST_SCALE and convert them to integer constants (thus retaining
  174486. * CONST_BITS bits of precision in the constants). After doing a
  174487. * multiplication we have to divide the product by CONST_SCALE, with proper
  174488. * rounding, to produce the correct output. This division can be done
  174489. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  174490. * as long as possible so that partial sums can be added together with
  174491. * full fractional precision.
  174492. *
  174493. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  174494. * they are represented to better-than-integral precision. These outputs
  174495. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  174496. * with the recommended scaling. (For 12-bit sample data, the intermediate
  174497. * array is INT32 anyway.)
  174498. *
  174499. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  174500. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  174501. * shows that the values given below are the most effective.
  174502. */
  174503. #if BITS_IN_JSAMPLE == 8
  174504. #define CONST_BITS 13
  174505. #define PASS1_BITS 2
  174506. #else
  174507. #define CONST_BITS 13
  174508. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  174509. #endif
  174510. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174511. * causing a lot of useless floating-point operations at run time.
  174512. * To get around this we use the following pre-calculated constants.
  174513. * If you change CONST_BITS you may want to add appropriate values.
  174514. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174515. */
  174516. #if CONST_BITS == 13
  174517. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  174518. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  174519. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  174520. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  174521. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  174522. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  174523. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  174524. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  174525. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  174526. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  174527. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  174528. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  174529. #else
  174530. #define FIX_0_298631336 FIX(0.298631336)
  174531. #define FIX_0_390180644 FIX(0.390180644)
  174532. #define FIX_0_541196100 FIX(0.541196100)
  174533. #define FIX_0_765366865 FIX(0.765366865)
  174534. #define FIX_0_899976223 FIX(0.899976223)
  174535. #define FIX_1_175875602 FIX(1.175875602)
  174536. #define FIX_1_501321110 FIX(1.501321110)
  174537. #define FIX_1_847759065 FIX(1.847759065)
  174538. #define FIX_1_961570560 FIX(1.961570560)
  174539. #define FIX_2_053119869 FIX(2.053119869)
  174540. #define FIX_2_562915447 FIX(2.562915447)
  174541. #define FIX_3_072711026 FIX(3.072711026)
  174542. #endif
  174543. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  174544. * For 8-bit samples with the recommended scaling, all the variable
  174545. * and constant values involved are no more than 16 bits wide, so a
  174546. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  174547. * For 12-bit samples, a full 32-bit multiplication will be needed.
  174548. */
  174549. #if BITS_IN_JSAMPLE == 8
  174550. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  174551. #else
  174552. #define MULTIPLY(var,const) ((var) * (const))
  174553. #endif
  174554. /*
  174555. * Perform the forward DCT on one block of samples.
  174556. */
  174557. GLOBAL(void)
  174558. jpeg_fdct_islow (DCTELEM * data)
  174559. {
  174560. INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174561. INT32 tmp10, tmp11, tmp12, tmp13;
  174562. INT32 z1, z2, z3, z4, z5;
  174563. DCTELEM *dataptr;
  174564. int ctr;
  174565. SHIFT_TEMPS
  174566. /* Pass 1: process rows. */
  174567. /* Note results are scaled up by sqrt(8) compared to a true DCT; */
  174568. /* furthermore, we scale the results by 2**PASS1_BITS. */
  174569. dataptr = data;
  174570. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174571. tmp0 = dataptr[0] + dataptr[7];
  174572. tmp7 = dataptr[0] - dataptr[7];
  174573. tmp1 = dataptr[1] + dataptr[6];
  174574. tmp6 = dataptr[1] - dataptr[6];
  174575. tmp2 = dataptr[2] + dataptr[5];
  174576. tmp5 = dataptr[2] - dataptr[5];
  174577. tmp3 = dataptr[3] + dataptr[4];
  174578. tmp4 = dataptr[3] - dataptr[4];
  174579. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  174580. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  174581. */
  174582. tmp10 = tmp0 + tmp3;
  174583. tmp13 = tmp0 - tmp3;
  174584. tmp11 = tmp1 + tmp2;
  174585. tmp12 = tmp1 - tmp2;
  174586. dataptr[0] = (DCTELEM) ((tmp10 + tmp11) << PASS1_BITS);
  174587. dataptr[4] = (DCTELEM) ((tmp10 - tmp11) << PASS1_BITS);
  174588. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  174589. dataptr[2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  174590. CONST_BITS-PASS1_BITS);
  174591. dataptr[6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  174592. CONST_BITS-PASS1_BITS);
  174593. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  174594. * cK represents cos(K*pi/16).
  174595. * i0..i3 in the paper are tmp4..tmp7 here.
  174596. */
  174597. z1 = tmp4 + tmp7;
  174598. z2 = tmp5 + tmp6;
  174599. z3 = tmp4 + tmp6;
  174600. z4 = tmp5 + tmp7;
  174601. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  174602. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  174603. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  174604. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  174605. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  174606. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  174607. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  174608. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  174609. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  174610. z3 += z5;
  174611. z4 += z5;
  174612. dataptr[7] = (DCTELEM) DESCALE(tmp4 + z1 + z3, CONST_BITS-PASS1_BITS);
  174613. dataptr[5] = (DCTELEM) DESCALE(tmp5 + z2 + z4, CONST_BITS-PASS1_BITS);
  174614. dataptr[3] = (DCTELEM) DESCALE(tmp6 + z2 + z3, CONST_BITS-PASS1_BITS);
  174615. dataptr[1] = (DCTELEM) DESCALE(tmp7 + z1 + z4, CONST_BITS-PASS1_BITS);
  174616. dataptr += DCTSIZE; /* advance pointer to next row */
  174617. }
  174618. /* Pass 2: process columns.
  174619. * We remove the PASS1_BITS scaling, but leave the results scaled up
  174620. * by an overall factor of 8.
  174621. */
  174622. dataptr = data;
  174623. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174624. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174625. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174626. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174627. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174628. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174629. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174630. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174631. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174632. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  174633. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  174634. */
  174635. tmp10 = tmp0 + tmp3;
  174636. tmp13 = tmp0 - tmp3;
  174637. tmp11 = tmp1 + tmp2;
  174638. tmp12 = tmp1 - tmp2;
  174639. dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(tmp10 + tmp11, PASS1_BITS);
  174640. dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(tmp10 - tmp11, PASS1_BITS);
  174641. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  174642. dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  174643. CONST_BITS+PASS1_BITS);
  174644. dataptr[DCTSIZE*6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  174645. CONST_BITS+PASS1_BITS);
  174646. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  174647. * cK represents cos(K*pi/16).
  174648. * i0..i3 in the paper are tmp4..tmp7 here.
  174649. */
  174650. z1 = tmp4 + tmp7;
  174651. z2 = tmp5 + tmp6;
  174652. z3 = tmp4 + tmp6;
  174653. z4 = tmp5 + tmp7;
  174654. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  174655. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  174656. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  174657. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  174658. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  174659. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  174660. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  174661. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  174662. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  174663. z3 += z5;
  174664. z4 += z5;
  174665. dataptr[DCTSIZE*7] = (DCTELEM) DESCALE(tmp4 + z1 + z3,
  174666. CONST_BITS+PASS1_BITS);
  174667. dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(tmp5 + z2 + z4,
  174668. CONST_BITS+PASS1_BITS);
  174669. dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(tmp6 + z2 + z3,
  174670. CONST_BITS+PASS1_BITS);
  174671. dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp7 + z1 + z4,
  174672. CONST_BITS+PASS1_BITS);
  174673. dataptr++; /* advance pointer to next column */
  174674. }
  174675. }
  174676. #endif /* DCT_ISLOW_SUPPORTED */
  174677. /*** End of inlined file: jfdctint.c ***/
  174678. #undef CONST_BITS
  174679. #undef MULTIPLY
  174680. #undef FIX_0_541196100
  174681. /*** Start of inlined file: jfdctfst.c ***/
  174682. #define JPEG_INTERNALS
  174683. #ifdef DCT_IFAST_SUPPORTED
  174684. /*
  174685. * This module is specialized to the case DCTSIZE = 8.
  174686. */
  174687. #if DCTSIZE != 8
  174688. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174689. #endif
  174690. /* Scaling decisions are generally the same as in the LL&M algorithm;
  174691. * see jfdctint.c for more details. However, we choose to descale
  174692. * (right shift) multiplication products as soon as they are formed,
  174693. * rather than carrying additional fractional bits into subsequent additions.
  174694. * This compromises accuracy slightly, but it lets us save a few shifts.
  174695. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  174696. * everywhere except in the multiplications proper; this saves a good deal
  174697. * of work on 16-bit-int machines.
  174698. *
  174699. * Again to save a few shifts, the intermediate results between pass 1 and
  174700. * pass 2 are not upscaled, but are represented only to integral precision.
  174701. *
  174702. * A final compromise is to represent the multiplicative constants to only
  174703. * 8 fractional bits, rather than 13. This saves some shifting work on some
  174704. * machines, and may also reduce the cost of multiplication (since there
  174705. * are fewer one-bits in the constants).
  174706. */
  174707. #define CONST_BITS 8
  174708. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174709. * causing a lot of useless floating-point operations at run time.
  174710. * To get around this we use the following pre-calculated constants.
  174711. * If you change CONST_BITS you may want to add appropriate values.
  174712. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174713. */
  174714. #if CONST_BITS == 8
  174715. #define FIX_0_382683433 ((INT32) 98) /* FIX(0.382683433) */
  174716. #define FIX_0_541196100 ((INT32) 139) /* FIX(0.541196100) */
  174717. #define FIX_0_707106781 ((INT32) 181) /* FIX(0.707106781) */
  174718. #define FIX_1_306562965 ((INT32) 334) /* FIX(1.306562965) */
  174719. #else
  174720. #define FIX_0_382683433 FIX(0.382683433)
  174721. #define FIX_0_541196100 FIX(0.541196100)
  174722. #define FIX_0_707106781 FIX(0.707106781)
  174723. #define FIX_1_306562965 FIX(1.306562965)
  174724. #endif
  174725. /* We can gain a little more speed, with a further compromise in accuracy,
  174726. * by omitting the addition in a descaling shift. This yields an incorrectly
  174727. * rounded result half the time...
  174728. */
  174729. #ifndef USE_ACCURATE_ROUNDING
  174730. #undef DESCALE
  174731. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  174732. #endif
  174733. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  174734. * descale to yield a DCTELEM result.
  174735. */
  174736. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  174737. /*
  174738. * Perform the forward DCT on one block of samples.
  174739. */
  174740. GLOBAL(void)
  174741. jpeg_fdct_ifast (DCTELEM * data)
  174742. {
  174743. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174744. DCTELEM tmp10, tmp11, tmp12, tmp13;
  174745. DCTELEM z1, z2, z3, z4, z5, z11, z13;
  174746. DCTELEM *dataptr;
  174747. int ctr;
  174748. SHIFT_TEMPS
  174749. /* Pass 1: process rows. */
  174750. dataptr = data;
  174751. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174752. tmp0 = dataptr[0] + dataptr[7];
  174753. tmp7 = dataptr[0] - dataptr[7];
  174754. tmp1 = dataptr[1] + dataptr[6];
  174755. tmp6 = dataptr[1] - dataptr[6];
  174756. tmp2 = dataptr[2] + dataptr[5];
  174757. tmp5 = dataptr[2] - dataptr[5];
  174758. tmp3 = dataptr[3] + dataptr[4];
  174759. tmp4 = dataptr[3] - dataptr[4];
  174760. /* Even part */
  174761. tmp10 = tmp0 + tmp3; /* phase 2 */
  174762. tmp13 = tmp0 - tmp3;
  174763. tmp11 = tmp1 + tmp2;
  174764. tmp12 = tmp1 - tmp2;
  174765. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  174766. dataptr[4] = tmp10 - tmp11;
  174767. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  174768. dataptr[2] = tmp13 + z1; /* phase 5 */
  174769. dataptr[6] = tmp13 - z1;
  174770. /* Odd part */
  174771. tmp10 = tmp4 + tmp5; /* phase 2 */
  174772. tmp11 = tmp5 + tmp6;
  174773. tmp12 = tmp6 + tmp7;
  174774. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174775. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  174776. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  174777. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  174778. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  174779. z11 = tmp7 + z3; /* phase 5 */
  174780. z13 = tmp7 - z3;
  174781. dataptr[5] = z13 + z2; /* phase 6 */
  174782. dataptr[3] = z13 - z2;
  174783. dataptr[1] = z11 + z4;
  174784. dataptr[7] = z11 - z4;
  174785. dataptr += DCTSIZE; /* advance pointer to next row */
  174786. }
  174787. /* Pass 2: process columns. */
  174788. dataptr = data;
  174789. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174790. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174791. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174792. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174793. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174794. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174795. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174796. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174797. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174798. /* Even part */
  174799. tmp10 = tmp0 + tmp3; /* phase 2 */
  174800. tmp13 = tmp0 - tmp3;
  174801. tmp11 = tmp1 + tmp2;
  174802. tmp12 = tmp1 - tmp2;
  174803. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  174804. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  174805. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  174806. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  174807. dataptr[DCTSIZE*6] = tmp13 - z1;
  174808. /* Odd part */
  174809. tmp10 = tmp4 + tmp5; /* phase 2 */
  174810. tmp11 = tmp5 + tmp6;
  174811. tmp12 = tmp6 + tmp7;
  174812. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174813. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  174814. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  174815. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  174816. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  174817. z11 = tmp7 + z3; /* phase 5 */
  174818. z13 = tmp7 - z3;
  174819. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  174820. dataptr[DCTSIZE*3] = z13 - z2;
  174821. dataptr[DCTSIZE*1] = z11 + z4;
  174822. dataptr[DCTSIZE*7] = z11 - z4;
  174823. dataptr++; /* advance pointer to next column */
  174824. }
  174825. }
  174826. #endif /* DCT_IFAST_SUPPORTED */
  174827. /*** End of inlined file: jfdctfst.c ***/
  174828. #undef FIX_0_541196100
  174829. /*** Start of inlined file: jidctflt.c ***/
  174830. #define JPEG_INTERNALS
  174831. #ifdef DCT_FLOAT_SUPPORTED
  174832. /*
  174833. * This module is specialized to the case DCTSIZE = 8.
  174834. */
  174835. #if DCTSIZE != 8
  174836. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174837. #endif
  174838. /* Dequantize a coefficient by multiplying it by the multiplier-table
  174839. * entry; produce a float result.
  174840. */
  174841. #define DEQUANTIZE(coef,quantval) (((FAST_FLOAT) (coef)) * (quantval))
  174842. /*
  174843. * Perform dequantization and inverse DCT on one block of coefficients.
  174844. */
  174845. GLOBAL(void)
  174846. jpeg_idct_float (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174847. JCOEFPTR coef_block,
  174848. JSAMPARRAY output_buf, JDIMENSION output_col)
  174849. {
  174850. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174851. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  174852. FAST_FLOAT z5, z10, z11, z12, z13;
  174853. JCOEFPTR inptr;
  174854. FLOAT_MULT_TYPE * quantptr;
  174855. FAST_FLOAT * wsptr;
  174856. JSAMPROW outptr;
  174857. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  174858. int ctr;
  174859. FAST_FLOAT workspace[DCTSIZE2]; /* buffers data between passes */
  174860. SHIFT_TEMPS
  174861. /* Pass 1: process columns from input, store into work array. */
  174862. inptr = coef_block;
  174863. quantptr = (FLOAT_MULT_TYPE *) compptr->dct_table;
  174864. wsptr = workspace;
  174865. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  174866. /* Due to quantization, we will usually find that many of the input
  174867. * coefficients are zero, especially the AC terms. We can exploit this
  174868. * by short-circuiting the IDCT calculation for any column in which all
  174869. * the AC terms are zero. In that case each output is equal to the
  174870. * DC coefficient (with scale factor as needed).
  174871. * With typical images and quantization tables, half or more of the
  174872. * column DCT calculations can be simplified this way.
  174873. */
  174874. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  174875. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  174876. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  174877. inptr[DCTSIZE*7] == 0) {
  174878. /* AC terms all zero */
  174879. FAST_FLOAT dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174880. wsptr[DCTSIZE*0] = dcval;
  174881. wsptr[DCTSIZE*1] = dcval;
  174882. wsptr[DCTSIZE*2] = dcval;
  174883. wsptr[DCTSIZE*3] = dcval;
  174884. wsptr[DCTSIZE*4] = dcval;
  174885. wsptr[DCTSIZE*5] = dcval;
  174886. wsptr[DCTSIZE*6] = dcval;
  174887. wsptr[DCTSIZE*7] = dcval;
  174888. inptr++; /* advance pointers to next column */
  174889. quantptr++;
  174890. wsptr++;
  174891. continue;
  174892. }
  174893. /* Even part */
  174894. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174895. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  174896. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  174897. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  174898. tmp10 = tmp0 + tmp2; /* phase 3 */
  174899. tmp11 = tmp0 - tmp2;
  174900. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  174901. tmp12 = (tmp1 - tmp3) * ((FAST_FLOAT) 1.414213562) - tmp13; /* 2*c4 */
  174902. tmp0 = tmp10 + tmp13; /* phase 2 */
  174903. tmp3 = tmp10 - tmp13;
  174904. tmp1 = tmp11 + tmp12;
  174905. tmp2 = tmp11 - tmp12;
  174906. /* Odd part */
  174907. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  174908. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  174909. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  174910. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  174911. z13 = tmp6 + tmp5; /* phase 6 */
  174912. z10 = tmp6 - tmp5;
  174913. z11 = tmp4 + tmp7;
  174914. z12 = tmp4 - tmp7;
  174915. tmp7 = z11 + z13; /* phase 5 */
  174916. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562); /* 2*c4 */
  174917. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  174918. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  174919. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  174920. tmp6 = tmp12 - tmp7; /* phase 2 */
  174921. tmp5 = tmp11 - tmp6;
  174922. tmp4 = tmp10 + tmp5;
  174923. wsptr[DCTSIZE*0] = tmp0 + tmp7;
  174924. wsptr[DCTSIZE*7] = tmp0 - tmp7;
  174925. wsptr[DCTSIZE*1] = tmp1 + tmp6;
  174926. wsptr[DCTSIZE*6] = tmp1 - tmp6;
  174927. wsptr[DCTSIZE*2] = tmp2 + tmp5;
  174928. wsptr[DCTSIZE*5] = tmp2 - tmp5;
  174929. wsptr[DCTSIZE*4] = tmp3 + tmp4;
  174930. wsptr[DCTSIZE*3] = tmp3 - tmp4;
  174931. inptr++; /* advance pointers to next column */
  174932. quantptr++;
  174933. wsptr++;
  174934. }
  174935. /* Pass 2: process rows from work array, store into output array. */
  174936. /* Note that we must descale the results by a factor of 8 == 2**3. */
  174937. wsptr = workspace;
  174938. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  174939. outptr = output_buf[ctr] + output_col;
  174940. /* Rows of zeroes can be exploited in the same way as we did with columns.
  174941. * However, the column calculation has created many nonzero AC terms, so
  174942. * the simplification applies less often (typically 5% to 10% of the time).
  174943. * And testing floats for zero is relatively expensive, so we don't bother.
  174944. */
  174945. /* Even part */
  174946. tmp10 = wsptr[0] + wsptr[4];
  174947. tmp11 = wsptr[0] - wsptr[4];
  174948. tmp13 = wsptr[2] + wsptr[6];
  174949. tmp12 = (wsptr[2] - wsptr[6]) * ((FAST_FLOAT) 1.414213562) - tmp13;
  174950. tmp0 = tmp10 + tmp13;
  174951. tmp3 = tmp10 - tmp13;
  174952. tmp1 = tmp11 + tmp12;
  174953. tmp2 = tmp11 - tmp12;
  174954. /* Odd part */
  174955. z13 = wsptr[5] + wsptr[3];
  174956. z10 = wsptr[5] - wsptr[3];
  174957. z11 = wsptr[1] + wsptr[7];
  174958. z12 = wsptr[1] - wsptr[7];
  174959. tmp7 = z11 + z13;
  174960. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562);
  174961. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  174962. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  174963. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  174964. tmp6 = tmp12 - tmp7;
  174965. tmp5 = tmp11 - tmp6;
  174966. tmp4 = tmp10 + tmp5;
  174967. /* Final output stage: scale down by a factor of 8 and range-limit */
  174968. outptr[0] = range_limit[(int) DESCALE((INT32) (tmp0 + tmp7), 3)
  174969. & RANGE_MASK];
  174970. outptr[7] = range_limit[(int) DESCALE((INT32) (tmp0 - tmp7), 3)
  174971. & RANGE_MASK];
  174972. outptr[1] = range_limit[(int) DESCALE((INT32) (tmp1 + tmp6), 3)
  174973. & RANGE_MASK];
  174974. outptr[6] = range_limit[(int) DESCALE((INT32) (tmp1 - tmp6), 3)
  174975. & RANGE_MASK];
  174976. outptr[2] = range_limit[(int) DESCALE((INT32) (tmp2 + tmp5), 3)
  174977. & RANGE_MASK];
  174978. outptr[5] = range_limit[(int) DESCALE((INT32) (tmp2 - tmp5), 3)
  174979. & RANGE_MASK];
  174980. outptr[4] = range_limit[(int) DESCALE((INT32) (tmp3 + tmp4), 3)
  174981. & RANGE_MASK];
  174982. outptr[3] = range_limit[(int) DESCALE((INT32) (tmp3 - tmp4), 3)
  174983. & RANGE_MASK];
  174984. wsptr += DCTSIZE; /* advance pointer to next row */
  174985. }
  174986. }
  174987. #endif /* DCT_FLOAT_SUPPORTED */
  174988. /*** End of inlined file: jidctflt.c ***/
  174989. #undef CONST_BITS
  174990. #undef FIX_1_847759065
  174991. #undef MULTIPLY
  174992. #undef DEQUANTIZE
  174993. #undef DESCALE
  174994. /*** Start of inlined file: jidctfst.c ***/
  174995. #define JPEG_INTERNALS
  174996. #ifdef DCT_IFAST_SUPPORTED
  174997. /*
  174998. * This module is specialized to the case DCTSIZE = 8.
  174999. */
  175000. #if DCTSIZE != 8
  175001. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  175002. #endif
  175003. /* Scaling decisions are generally the same as in the LL&M algorithm;
  175004. * see jidctint.c for more details. However, we choose to descale
  175005. * (right shift) multiplication products as soon as they are formed,
  175006. * rather than carrying additional fractional bits into subsequent additions.
  175007. * This compromises accuracy slightly, but it lets us save a few shifts.
  175008. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  175009. * everywhere except in the multiplications proper; this saves a good deal
  175010. * of work on 16-bit-int machines.
  175011. *
  175012. * The dequantized coefficients are not integers because the AA&N scaling
  175013. * factors have been incorporated. We represent them scaled up by PASS1_BITS,
  175014. * so that the first and second IDCT rounds have the same input scaling.
  175015. * For 8-bit JSAMPLEs, we choose IFAST_SCALE_BITS = PASS1_BITS so as to
  175016. * avoid a descaling shift; this compromises accuracy rather drastically
  175017. * for small quantization table entries, but it saves a lot of shifts.
  175018. * For 12-bit JSAMPLEs, there's no hope of using 16x16 multiplies anyway,
  175019. * so we use a much larger scaling factor to preserve accuracy.
  175020. *
  175021. * A final compromise is to represent the multiplicative constants to only
  175022. * 8 fractional bits, rather than 13. This saves some shifting work on some
  175023. * machines, and may also reduce the cost of multiplication (since there
  175024. * are fewer one-bits in the constants).
  175025. */
  175026. #if BITS_IN_JSAMPLE == 8
  175027. #define CONST_BITS 8
  175028. #define PASS1_BITS 2
  175029. #else
  175030. #define CONST_BITS 8
  175031. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  175032. #endif
  175033. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  175034. * causing a lot of useless floating-point operations at run time.
  175035. * To get around this we use the following pre-calculated constants.
  175036. * If you change CONST_BITS you may want to add appropriate values.
  175037. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  175038. */
  175039. #if CONST_BITS == 8
  175040. #define FIX_1_082392200 ((INT32) 277) /* FIX(1.082392200) */
  175041. #define FIX_1_414213562 ((INT32) 362) /* FIX(1.414213562) */
  175042. #define FIX_1_847759065 ((INT32) 473) /* FIX(1.847759065) */
  175043. #define FIX_2_613125930 ((INT32) 669) /* FIX(2.613125930) */
  175044. #else
  175045. #define FIX_1_082392200 FIX(1.082392200)
  175046. #define FIX_1_414213562 FIX(1.414213562)
  175047. #define FIX_1_847759065 FIX(1.847759065)
  175048. #define FIX_2_613125930 FIX(2.613125930)
  175049. #endif
  175050. /* We can gain a little more speed, with a further compromise in accuracy,
  175051. * by omitting the addition in a descaling shift. This yields an incorrectly
  175052. * rounded result half the time...
  175053. */
  175054. #ifndef USE_ACCURATE_ROUNDING
  175055. #undef DESCALE
  175056. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  175057. #endif
  175058. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  175059. * descale to yield a DCTELEM result.
  175060. */
  175061. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  175062. /* Dequantize a coefficient by multiplying it by the multiplier-table
  175063. * entry; produce a DCTELEM result. For 8-bit data a 16x16->16
  175064. * multiplication will do. For 12-bit data, the multiplier table is
  175065. * declared INT32, so a 32-bit multiply will be used.
  175066. */
  175067. #if BITS_IN_JSAMPLE == 8
  175068. #define DEQUANTIZE(coef,quantval) (((IFAST_MULT_TYPE) (coef)) * (quantval))
  175069. #else
  175070. #define DEQUANTIZE(coef,quantval) \
  175071. DESCALE((coef)*(quantval), IFAST_SCALE_BITS-PASS1_BITS)
  175072. #endif
  175073. /* Like DESCALE, but applies to a DCTELEM and produces an int.
  175074. * We assume that int right shift is unsigned if INT32 right shift is.
  175075. */
  175076. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  175077. #define ISHIFT_TEMPS DCTELEM ishift_temp;
  175078. #if BITS_IN_JSAMPLE == 8
  175079. #define DCTELEMBITS 16 /* DCTELEM may be 16 or 32 bits */
  175080. #else
  175081. #define DCTELEMBITS 32 /* DCTELEM must be 32 bits */
  175082. #endif
  175083. #define IRIGHT_SHIFT(x,shft) \
  175084. ((ishift_temp = (x)) < 0 ? \
  175085. (ishift_temp >> (shft)) | ((~((DCTELEM) 0)) << (DCTELEMBITS-(shft))) : \
  175086. (ishift_temp >> (shft)))
  175087. #else
  175088. #define ISHIFT_TEMPS
  175089. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  175090. #endif
  175091. #ifdef USE_ACCURATE_ROUNDING
  175092. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT((x) + (1 << ((n)-1)), n))
  175093. #else
  175094. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT(x, n))
  175095. #endif
  175096. /*
  175097. * Perform dequantization and inverse DCT on one block of coefficients.
  175098. */
  175099. GLOBAL(void)
  175100. jpeg_idct_ifast (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175101. JCOEFPTR coef_block,
  175102. JSAMPARRAY output_buf, JDIMENSION output_col)
  175103. {
  175104. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  175105. DCTELEM tmp10, tmp11, tmp12, tmp13;
  175106. DCTELEM z5, z10, z11, z12, z13;
  175107. JCOEFPTR inptr;
  175108. IFAST_MULT_TYPE * quantptr;
  175109. int * wsptr;
  175110. JSAMPROW outptr;
  175111. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175112. int ctr;
  175113. int workspace[DCTSIZE2]; /* buffers data between passes */
  175114. SHIFT_TEMPS /* for DESCALE */
  175115. ISHIFT_TEMPS /* for IDESCALE */
  175116. /* Pass 1: process columns from input, store into work array. */
  175117. inptr = coef_block;
  175118. quantptr = (IFAST_MULT_TYPE *) compptr->dct_table;
  175119. wsptr = workspace;
  175120. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  175121. /* Due to quantization, we will usually find that many of the input
  175122. * coefficients are zero, especially the AC terms. We can exploit this
  175123. * by short-circuiting the IDCT calculation for any column in which all
  175124. * the AC terms are zero. In that case each output is equal to the
  175125. * DC coefficient (with scale factor as needed).
  175126. * With typical images and quantization tables, half or more of the
  175127. * column DCT calculations can be simplified this way.
  175128. */
  175129. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  175130. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  175131. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  175132. inptr[DCTSIZE*7] == 0) {
  175133. /* AC terms all zero */
  175134. int dcval = (int) DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175135. wsptr[DCTSIZE*0] = dcval;
  175136. wsptr[DCTSIZE*1] = dcval;
  175137. wsptr[DCTSIZE*2] = dcval;
  175138. wsptr[DCTSIZE*3] = dcval;
  175139. wsptr[DCTSIZE*4] = dcval;
  175140. wsptr[DCTSIZE*5] = dcval;
  175141. wsptr[DCTSIZE*6] = dcval;
  175142. wsptr[DCTSIZE*7] = dcval;
  175143. inptr++; /* advance pointers to next column */
  175144. quantptr++;
  175145. wsptr++;
  175146. continue;
  175147. }
  175148. /* Even part */
  175149. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175150. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175151. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  175152. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175153. tmp10 = tmp0 + tmp2; /* phase 3 */
  175154. tmp11 = tmp0 - tmp2;
  175155. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  175156. tmp12 = MULTIPLY(tmp1 - tmp3, FIX_1_414213562) - tmp13; /* 2*c4 */
  175157. tmp0 = tmp10 + tmp13; /* phase 2 */
  175158. tmp3 = tmp10 - tmp13;
  175159. tmp1 = tmp11 + tmp12;
  175160. tmp2 = tmp11 - tmp12;
  175161. /* Odd part */
  175162. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175163. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175164. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175165. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175166. z13 = tmp6 + tmp5; /* phase 6 */
  175167. z10 = tmp6 - tmp5;
  175168. z11 = tmp4 + tmp7;
  175169. z12 = tmp4 - tmp7;
  175170. tmp7 = z11 + z13; /* phase 5 */
  175171. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  175172. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  175173. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  175174. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  175175. tmp6 = tmp12 - tmp7; /* phase 2 */
  175176. tmp5 = tmp11 - tmp6;
  175177. tmp4 = tmp10 + tmp5;
  175178. wsptr[DCTSIZE*0] = (int) (tmp0 + tmp7);
  175179. wsptr[DCTSIZE*7] = (int) (tmp0 - tmp7);
  175180. wsptr[DCTSIZE*1] = (int) (tmp1 + tmp6);
  175181. wsptr[DCTSIZE*6] = (int) (tmp1 - tmp6);
  175182. wsptr[DCTSIZE*2] = (int) (tmp2 + tmp5);
  175183. wsptr[DCTSIZE*5] = (int) (tmp2 - tmp5);
  175184. wsptr[DCTSIZE*4] = (int) (tmp3 + tmp4);
  175185. wsptr[DCTSIZE*3] = (int) (tmp3 - tmp4);
  175186. inptr++; /* advance pointers to next column */
  175187. quantptr++;
  175188. wsptr++;
  175189. }
  175190. /* Pass 2: process rows from work array, store into output array. */
  175191. /* Note that we must descale the results by a factor of 8 == 2**3, */
  175192. /* and also undo the PASS1_BITS scaling. */
  175193. wsptr = workspace;
  175194. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  175195. outptr = output_buf[ctr] + output_col;
  175196. /* Rows of zeroes can be exploited in the same way as we did with columns.
  175197. * However, the column calculation has created many nonzero AC terms, so
  175198. * the simplification applies less often (typically 5% to 10% of the time).
  175199. * On machines with very fast multiplication, it's possible that the
  175200. * test takes more time than it's worth. In that case this section
  175201. * may be commented out.
  175202. */
  175203. #ifndef NO_ZERO_ROW_TEST
  175204. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  175205. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  175206. /* AC terms all zero */
  175207. JSAMPLE dcval = range_limit[IDESCALE(wsptr[0], PASS1_BITS+3)
  175208. & RANGE_MASK];
  175209. outptr[0] = dcval;
  175210. outptr[1] = dcval;
  175211. outptr[2] = dcval;
  175212. outptr[3] = dcval;
  175213. outptr[4] = dcval;
  175214. outptr[5] = dcval;
  175215. outptr[6] = dcval;
  175216. outptr[7] = dcval;
  175217. wsptr += DCTSIZE; /* advance pointer to next row */
  175218. continue;
  175219. }
  175220. #endif
  175221. /* Even part */
  175222. tmp10 = ((DCTELEM) wsptr[0] + (DCTELEM) wsptr[4]);
  175223. tmp11 = ((DCTELEM) wsptr[0] - (DCTELEM) wsptr[4]);
  175224. tmp13 = ((DCTELEM) wsptr[2] + (DCTELEM) wsptr[6]);
  175225. tmp12 = MULTIPLY((DCTELEM) wsptr[2] - (DCTELEM) wsptr[6], FIX_1_414213562)
  175226. - tmp13;
  175227. tmp0 = tmp10 + tmp13;
  175228. tmp3 = tmp10 - tmp13;
  175229. tmp1 = tmp11 + tmp12;
  175230. tmp2 = tmp11 - tmp12;
  175231. /* Odd part */
  175232. z13 = (DCTELEM) wsptr[5] + (DCTELEM) wsptr[3];
  175233. z10 = (DCTELEM) wsptr[5] - (DCTELEM) wsptr[3];
  175234. z11 = (DCTELEM) wsptr[1] + (DCTELEM) wsptr[7];
  175235. z12 = (DCTELEM) wsptr[1] - (DCTELEM) wsptr[7];
  175236. tmp7 = z11 + z13; /* phase 5 */
  175237. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  175238. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  175239. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  175240. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  175241. tmp6 = tmp12 - tmp7; /* phase 2 */
  175242. tmp5 = tmp11 - tmp6;
  175243. tmp4 = tmp10 + tmp5;
  175244. /* Final output stage: scale down by a factor of 8 and range-limit */
  175245. outptr[0] = range_limit[IDESCALE(tmp0 + tmp7, PASS1_BITS+3)
  175246. & RANGE_MASK];
  175247. outptr[7] = range_limit[IDESCALE(tmp0 - tmp7, PASS1_BITS+3)
  175248. & RANGE_MASK];
  175249. outptr[1] = range_limit[IDESCALE(tmp1 + tmp6, PASS1_BITS+3)
  175250. & RANGE_MASK];
  175251. outptr[6] = range_limit[IDESCALE(tmp1 - tmp6, PASS1_BITS+3)
  175252. & RANGE_MASK];
  175253. outptr[2] = range_limit[IDESCALE(tmp2 + tmp5, PASS1_BITS+3)
  175254. & RANGE_MASK];
  175255. outptr[5] = range_limit[IDESCALE(tmp2 - tmp5, PASS1_BITS+3)
  175256. & RANGE_MASK];
  175257. outptr[4] = range_limit[IDESCALE(tmp3 + tmp4, PASS1_BITS+3)
  175258. & RANGE_MASK];
  175259. outptr[3] = range_limit[IDESCALE(tmp3 - tmp4, PASS1_BITS+3)
  175260. & RANGE_MASK];
  175261. wsptr += DCTSIZE; /* advance pointer to next row */
  175262. }
  175263. }
  175264. #endif /* DCT_IFAST_SUPPORTED */
  175265. /*** End of inlined file: jidctfst.c ***/
  175266. #undef CONST_BITS
  175267. #undef FIX_1_847759065
  175268. #undef MULTIPLY
  175269. #undef DEQUANTIZE
  175270. /*** Start of inlined file: jidctint.c ***/
  175271. #define JPEG_INTERNALS
  175272. #ifdef DCT_ISLOW_SUPPORTED
  175273. /*
  175274. * This module is specialized to the case DCTSIZE = 8.
  175275. */
  175276. #if DCTSIZE != 8
  175277. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  175278. #endif
  175279. /*
  175280. * The poop on this scaling stuff is as follows:
  175281. *
  175282. * Each 1-D IDCT step produces outputs which are a factor of sqrt(N)
  175283. * larger than the true IDCT outputs. The final outputs are therefore
  175284. * a factor of N larger than desired; since N=8 this can be cured by
  175285. * a simple right shift at the end of the algorithm. The advantage of
  175286. * this arrangement is that we save two multiplications per 1-D IDCT,
  175287. * because the y0 and y4 inputs need not be divided by sqrt(N).
  175288. *
  175289. * We have to do addition and subtraction of the integer inputs, which
  175290. * is no problem, and multiplication by fractional constants, which is
  175291. * a problem to do in integer arithmetic. We multiply all the constants
  175292. * by CONST_SCALE and convert them to integer constants (thus retaining
  175293. * CONST_BITS bits of precision in the constants). After doing a
  175294. * multiplication we have to divide the product by CONST_SCALE, with proper
  175295. * rounding, to produce the correct output. This division can be done
  175296. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  175297. * as long as possible so that partial sums can be added together with
  175298. * full fractional precision.
  175299. *
  175300. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  175301. * they are represented to better-than-integral precision. These outputs
  175302. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  175303. * with the recommended scaling. (To scale up 12-bit sample data further, an
  175304. * intermediate INT32 array would be needed.)
  175305. *
  175306. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  175307. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  175308. * shows that the values given below are the most effective.
  175309. */
  175310. #if BITS_IN_JSAMPLE == 8
  175311. #define CONST_BITS 13
  175312. #define PASS1_BITS 2
  175313. #else
  175314. #define CONST_BITS 13
  175315. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  175316. #endif
  175317. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  175318. * causing a lot of useless floating-point operations at run time.
  175319. * To get around this we use the following pre-calculated constants.
  175320. * If you change CONST_BITS you may want to add appropriate values.
  175321. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  175322. */
  175323. #if CONST_BITS == 13
  175324. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  175325. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  175326. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  175327. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  175328. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  175329. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  175330. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  175331. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  175332. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  175333. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  175334. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  175335. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  175336. #else
  175337. #define FIX_0_298631336 FIX(0.298631336)
  175338. #define FIX_0_390180644 FIX(0.390180644)
  175339. #define FIX_0_541196100 FIX(0.541196100)
  175340. #define FIX_0_765366865 FIX(0.765366865)
  175341. #define FIX_0_899976223 FIX(0.899976223)
  175342. #define FIX_1_175875602 FIX(1.175875602)
  175343. #define FIX_1_501321110 FIX(1.501321110)
  175344. #define FIX_1_847759065 FIX(1.847759065)
  175345. #define FIX_1_961570560 FIX(1.961570560)
  175346. #define FIX_2_053119869 FIX(2.053119869)
  175347. #define FIX_2_562915447 FIX(2.562915447)
  175348. #define FIX_3_072711026 FIX(3.072711026)
  175349. #endif
  175350. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  175351. * For 8-bit samples with the recommended scaling, all the variable
  175352. * and constant values involved are no more than 16 bits wide, so a
  175353. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  175354. * For 12-bit samples, a full 32-bit multiplication will be needed.
  175355. */
  175356. #if BITS_IN_JSAMPLE == 8
  175357. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  175358. #else
  175359. #define MULTIPLY(var,const) ((var) * (const))
  175360. #endif
  175361. /* Dequantize a coefficient by multiplying it by the multiplier-table
  175362. * entry; produce an int result. In this module, both inputs and result
  175363. * are 16 bits or less, so either int or short multiply will work.
  175364. */
  175365. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  175366. /*
  175367. * Perform dequantization and inverse DCT on one block of coefficients.
  175368. */
  175369. GLOBAL(void)
  175370. jpeg_idct_islow (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175371. JCOEFPTR coef_block,
  175372. JSAMPARRAY output_buf, JDIMENSION output_col)
  175373. {
  175374. INT32 tmp0, tmp1, tmp2, tmp3;
  175375. INT32 tmp10, tmp11, tmp12, tmp13;
  175376. INT32 z1, z2, z3, z4, z5;
  175377. JCOEFPTR inptr;
  175378. ISLOW_MULT_TYPE * quantptr;
  175379. int * wsptr;
  175380. JSAMPROW outptr;
  175381. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175382. int ctr;
  175383. int workspace[DCTSIZE2]; /* buffers data between passes */
  175384. SHIFT_TEMPS
  175385. /* Pass 1: process columns from input, store into work array. */
  175386. /* Note results are scaled up by sqrt(8) compared to a true IDCT; */
  175387. /* furthermore, we scale the results by 2**PASS1_BITS. */
  175388. inptr = coef_block;
  175389. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175390. wsptr = workspace;
  175391. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  175392. /* Due to quantization, we will usually find that many of the input
  175393. * coefficients are zero, especially the AC terms. We can exploit this
  175394. * by short-circuiting the IDCT calculation for any column in which all
  175395. * the AC terms are zero. In that case each output is equal to the
  175396. * DC coefficient (with scale factor as needed).
  175397. * With typical images and quantization tables, half or more of the
  175398. * column DCT calculations can be simplified this way.
  175399. */
  175400. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  175401. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  175402. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  175403. inptr[DCTSIZE*7] == 0) {
  175404. /* AC terms all zero */
  175405. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175406. wsptr[DCTSIZE*0] = dcval;
  175407. wsptr[DCTSIZE*1] = dcval;
  175408. wsptr[DCTSIZE*2] = dcval;
  175409. wsptr[DCTSIZE*3] = dcval;
  175410. wsptr[DCTSIZE*4] = dcval;
  175411. wsptr[DCTSIZE*5] = dcval;
  175412. wsptr[DCTSIZE*6] = dcval;
  175413. wsptr[DCTSIZE*7] = dcval;
  175414. inptr++; /* advance pointers to next column */
  175415. quantptr++;
  175416. wsptr++;
  175417. continue;
  175418. }
  175419. /* Even part: reverse the even part of the forward DCT. */
  175420. /* The rotator is sqrt(2)*c(-6). */
  175421. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175422. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175423. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  175424. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  175425. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  175426. z2 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175427. z3 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  175428. tmp0 = (z2 + z3) << CONST_BITS;
  175429. tmp1 = (z2 - z3) << CONST_BITS;
  175430. tmp10 = tmp0 + tmp3;
  175431. tmp13 = tmp0 - tmp3;
  175432. tmp11 = tmp1 + tmp2;
  175433. tmp12 = tmp1 - tmp2;
  175434. /* Odd part per figure 8; the matrix is unitary and hence its
  175435. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  175436. */
  175437. tmp0 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175438. tmp1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175439. tmp2 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175440. tmp3 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175441. z1 = tmp0 + tmp3;
  175442. z2 = tmp1 + tmp2;
  175443. z3 = tmp0 + tmp2;
  175444. z4 = tmp1 + tmp3;
  175445. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  175446. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  175447. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  175448. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  175449. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  175450. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  175451. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  175452. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  175453. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  175454. z3 += z5;
  175455. z4 += z5;
  175456. tmp0 += z1 + z3;
  175457. tmp1 += z2 + z4;
  175458. tmp2 += z2 + z3;
  175459. tmp3 += z1 + z4;
  175460. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  175461. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp3, CONST_BITS-PASS1_BITS);
  175462. wsptr[DCTSIZE*7] = (int) DESCALE(tmp10 - tmp3, CONST_BITS-PASS1_BITS);
  175463. wsptr[DCTSIZE*1] = (int) DESCALE(tmp11 + tmp2, CONST_BITS-PASS1_BITS);
  175464. wsptr[DCTSIZE*6] = (int) DESCALE(tmp11 - tmp2, CONST_BITS-PASS1_BITS);
  175465. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 + tmp1, CONST_BITS-PASS1_BITS);
  175466. wsptr[DCTSIZE*5] = (int) DESCALE(tmp12 - tmp1, CONST_BITS-PASS1_BITS);
  175467. wsptr[DCTSIZE*3] = (int) DESCALE(tmp13 + tmp0, CONST_BITS-PASS1_BITS);
  175468. wsptr[DCTSIZE*4] = (int) DESCALE(tmp13 - tmp0, CONST_BITS-PASS1_BITS);
  175469. inptr++; /* advance pointers to next column */
  175470. quantptr++;
  175471. wsptr++;
  175472. }
  175473. /* Pass 2: process rows from work array, store into output array. */
  175474. /* Note that we must descale the results by a factor of 8 == 2**3, */
  175475. /* and also undo the PASS1_BITS scaling. */
  175476. wsptr = workspace;
  175477. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  175478. outptr = output_buf[ctr] + output_col;
  175479. /* Rows of zeroes can be exploited in the same way as we did with columns.
  175480. * However, the column calculation has created many nonzero AC terms, so
  175481. * the simplification applies less often (typically 5% to 10% of the time).
  175482. * On machines with very fast multiplication, it's possible that the
  175483. * test takes more time than it's worth. In that case this section
  175484. * may be commented out.
  175485. */
  175486. #ifndef NO_ZERO_ROW_TEST
  175487. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  175488. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  175489. /* AC terms all zero */
  175490. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175491. & RANGE_MASK];
  175492. outptr[0] = dcval;
  175493. outptr[1] = dcval;
  175494. outptr[2] = dcval;
  175495. outptr[3] = dcval;
  175496. outptr[4] = dcval;
  175497. outptr[5] = dcval;
  175498. outptr[6] = dcval;
  175499. outptr[7] = dcval;
  175500. wsptr += DCTSIZE; /* advance pointer to next row */
  175501. continue;
  175502. }
  175503. #endif
  175504. /* Even part: reverse the even part of the forward DCT. */
  175505. /* The rotator is sqrt(2)*c(-6). */
  175506. z2 = (INT32) wsptr[2];
  175507. z3 = (INT32) wsptr[6];
  175508. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  175509. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  175510. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  175511. tmp0 = ((INT32) wsptr[0] + (INT32) wsptr[4]) << CONST_BITS;
  175512. tmp1 = ((INT32) wsptr[0] - (INT32) wsptr[4]) << CONST_BITS;
  175513. tmp10 = tmp0 + tmp3;
  175514. tmp13 = tmp0 - tmp3;
  175515. tmp11 = tmp1 + tmp2;
  175516. tmp12 = tmp1 - tmp2;
  175517. /* Odd part per figure 8; the matrix is unitary and hence its
  175518. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  175519. */
  175520. tmp0 = (INT32) wsptr[7];
  175521. tmp1 = (INT32) wsptr[5];
  175522. tmp2 = (INT32) wsptr[3];
  175523. tmp3 = (INT32) wsptr[1];
  175524. z1 = tmp0 + tmp3;
  175525. z2 = tmp1 + tmp2;
  175526. z3 = tmp0 + tmp2;
  175527. z4 = tmp1 + tmp3;
  175528. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  175529. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  175530. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  175531. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  175532. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  175533. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  175534. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  175535. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  175536. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  175537. z3 += z5;
  175538. z4 += z5;
  175539. tmp0 += z1 + z3;
  175540. tmp1 += z2 + z4;
  175541. tmp2 += z2 + z3;
  175542. tmp3 += z1 + z4;
  175543. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  175544. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp3,
  175545. CONST_BITS+PASS1_BITS+3)
  175546. & RANGE_MASK];
  175547. outptr[7] = range_limit[(int) DESCALE(tmp10 - tmp3,
  175548. CONST_BITS+PASS1_BITS+3)
  175549. & RANGE_MASK];
  175550. outptr[1] = range_limit[(int) DESCALE(tmp11 + tmp2,
  175551. CONST_BITS+PASS1_BITS+3)
  175552. & RANGE_MASK];
  175553. outptr[6] = range_limit[(int) DESCALE(tmp11 - tmp2,
  175554. CONST_BITS+PASS1_BITS+3)
  175555. & RANGE_MASK];
  175556. outptr[2] = range_limit[(int) DESCALE(tmp12 + tmp1,
  175557. CONST_BITS+PASS1_BITS+3)
  175558. & RANGE_MASK];
  175559. outptr[5] = range_limit[(int) DESCALE(tmp12 - tmp1,
  175560. CONST_BITS+PASS1_BITS+3)
  175561. & RANGE_MASK];
  175562. outptr[3] = range_limit[(int) DESCALE(tmp13 + tmp0,
  175563. CONST_BITS+PASS1_BITS+3)
  175564. & RANGE_MASK];
  175565. outptr[4] = range_limit[(int) DESCALE(tmp13 - tmp0,
  175566. CONST_BITS+PASS1_BITS+3)
  175567. & RANGE_MASK];
  175568. wsptr += DCTSIZE; /* advance pointer to next row */
  175569. }
  175570. }
  175571. #endif /* DCT_ISLOW_SUPPORTED */
  175572. /*** End of inlined file: jidctint.c ***/
  175573. /*** Start of inlined file: jidctred.c ***/
  175574. #define JPEG_INTERNALS
  175575. #ifdef IDCT_SCALING_SUPPORTED
  175576. /*
  175577. * This module is specialized to the case DCTSIZE = 8.
  175578. */
  175579. #if DCTSIZE != 8
  175580. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  175581. #endif
  175582. /* Scaling is the same as in jidctint.c. */
  175583. #if BITS_IN_JSAMPLE == 8
  175584. #define CONST_BITS 13
  175585. #define PASS1_BITS 2
  175586. #else
  175587. #define CONST_BITS 13
  175588. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  175589. #endif
  175590. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  175591. * causing a lot of useless floating-point operations at run time.
  175592. * To get around this we use the following pre-calculated constants.
  175593. * If you change CONST_BITS you may want to add appropriate values.
  175594. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  175595. */
  175596. #if CONST_BITS == 13
  175597. #define FIX_0_211164243 ((INT32) 1730) /* FIX(0.211164243) */
  175598. #define FIX_0_509795579 ((INT32) 4176) /* FIX(0.509795579) */
  175599. #define FIX_0_601344887 ((INT32) 4926) /* FIX(0.601344887) */
  175600. #define FIX_0_720959822 ((INT32) 5906) /* FIX(0.720959822) */
  175601. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  175602. #define FIX_0_850430095 ((INT32) 6967) /* FIX(0.850430095) */
  175603. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  175604. #define FIX_1_061594337 ((INT32) 8697) /* FIX(1.061594337) */
  175605. #define FIX_1_272758580 ((INT32) 10426) /* FIX(1.272758580) */
  175606. #define FIX_1_451774981 ((INT32) 11893) /* FIX(1.451774981) */
  175607. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  175608. #define FIX_2_172734803 ((INT32) 17799) /* FIX(2.172734803) */
  175609. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  175610. #define FIX_3_624509785 ((INT32) 29692) /* FIX(3.624509785) */
  175611. #else
  175612. #define FIX_0_211164243 FIX(0.211164243)
  175613. #define FIX_0_509795579 FIX(0.509795579)
  175614. #define FIX_0_601344887 FIX(0.601344887)
  175615. #define FIX_0_720959822 FIX(0.720959822)
  175616. #define FIX_0_765366865 FIX(0.765366865)
  175617. #define FIX_0_850430095 FIX(0.850430095)
  175618. #define FIX_0_899976223 FIX(0.899976223)
  175619. #define FIX_1_061594337 FIX(1.061594337)
  175620. #define FIX_1_272758580 FIX(1.272758580)
  175621. #define FIX_1_451774981 FIX(1.451774981)
  175622. #define FIX_1_847759065 FIX(1.847759065)
  175623. #define FIX_2_172734803 FIX(2.172734803)
  175624. #define FIX_2_562915447 FIX(2.562915447)
  175625. #define FIX_3_624509785 FIX(3.624509785)
  175626. #endif
  175627. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  175628. * For 8-bit samples with the recommended scaling, all the variable
  175629. * and constant values involved are no more than 16 bits wide, so a
  175630. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  175631. * For 12-bit samples, a full 32-bit multiplication will be needed.
  175632. */
  175633. #if BITS_IN_JSAMPLE == 8
  175634. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  175635. #else
  175636. #define MULTIPLY(var,const) ((var) * (const))
  175637. #endif
  175638. /* Dequantize a coefficient by multiplying it by the multiplier-table
  175639. * entry; produce an int result. In this module, both inputs and result
  175640. * are 16 bits or less, so either int or short multiply will work.
  175641. */
  175642. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  175643. /*
  175644. * Perform dequantization and inverse DCT on one block of coefficients,
  175645. * producing a reduced-size 4x4 output block.
  175646. */
  175647. GLOBAL(void)
  175648. jpeg_idct_4x4 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175649. JCOEFPTR coef_block,
  175650. JSAMPARRAY output_buf, JDIMENSION output_col)
  175651. {
  175652. INT32 tmp0, tmp2, tmp10, tmp12;
  175653. INT32 z1, z2, z3, z4;
  175654. JCOEFPTR inptr;
  175655. ISLOW_MULT_TYPE * quantptr;
  175656. int * wsptr;
  175657. JSAMPROW outptr;
  175658. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175659. int ctr;
  175660. int workspace[DCTSIZE*4]; /* buffers data between passes */
  175661. SHIFT_TEMPS
  175662. /* Pass 1: process columns from input, store into work array. */
  175663. inptr = coef_block;
  175664. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175665. wsptr = workspace;
  175666. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  175667. /* Don't bother to process column 4, because second pass won't use it */
  175668. if (ctr == DCTSIZE-4)
  175669. continue;
  175670. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  175671. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*5] == 0 &&
  175672. inptr[DCTSIZE*6] == 0 && inptr[DCTSIZE*7] == 0) {
  175673. /* AC terms all zero; we need not examine term 4 for 4x4 output */
  175674. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175675. wsptr[DCTSIZE*0] = dcval;
  175676. wsptr[DCTSIZE*1] = dcval;
  175677. wsptr[DCTSIZE*2] = dcval;
  175678. wsptr[DCTSIZE*3] = dcval;
  175679. continue;
  175680. }
  175681. /* Even part */
  175682. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175683. tmp0 <<= (CONST_BITS+1);
  175684. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175685. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175686. tmp2 = MULTIPLY(z2, FIX_1_847759065) + MULTIPLY(z3, - FIX_0_765366865);
  175687. tmp10 = tmp0 + tmp2;
  175688. tmp12 = tmp0 - tmp2;
  175689. /* Odd part */
  175690. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175691. z2 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175692. z3 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175693. z4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175694. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  175695. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  175696. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  175697. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  175698. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  175699. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  175700. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  175701. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  175702. /* Final output stage */
  175703. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp2, CONST_BITS-PASS1_BITS+1);
  175704. wsptr[DCTSIZE*3] = (int) DESCALE(tmp10 - tmp2, CONST_BITS-PASS1_BITS+1);
  175705. wsptr[DCTSIZE*1] = (int) DESCALE(tmp12 + tmp0, CONST_BITS-PASS1_BITS+1);
  175706. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 - tmp0, CONST_BITS-PASS1_BITS+1);
  175707. }
  175708. /* Pass 2: process 4 rows from work array, store into output array. */
  175709. wsptr = workspace;
  175710. for (ctr = 0; ctr < 4; ctr++) {
  175711. outptr = output_buf[ctr] + output_col;
  175712. /* It's not clear whether a zero row test is worthwhile here ... */
  175713. #ifndef NO_ZERO_ROW_TEST
  175714. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 &&
  175715. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  175716. /* AC terms all zero */
  175717. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175718. & RANGE_MASK];
  175719. outptr[0] = dcval;
  175720. outptr[1] = dcval;
  175721. outptr[2] = dcval;
  175722. outptr[3] = dcval;
  175723. wsptr += DCTSIZE; /* advance pointer to next row */
  175724. continue;
  175725. }
  175726. #endif
  175727. /* Even part */
  175728. tmp0 = ((INT32) wsptr[0]) << (CONST_BITS+1);
  175729. tmp2 = MULTIPLY((INT32) wsptr[2], FIX_1_847759065)
  175730. + MULTIPLY((INT32) wsptr[6], - FIX_0_765366865);
  175731. tmp10 = tmp0 + tmp2;
  175732. tmp12 = tmp0 - tmp2;
  175733. /* Odd part */
  175734. z1 = (INT32) wsptr[7];
  175735. z2 = (INT32) wsptr[5];
  175736. z3 = (INT32) wsptr[3];
  175737. z4 = (INT32) wsptr[1];
  175738. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  175739. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  175740. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  175741. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  175742. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  175743. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  175744. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  175745. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  175746. /* Final output stage */
  175747. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp2,
  175748. CONST_BITS+PASS1_BITS+3+1)
  175749. & RANGE_MASK];
  175750. outptr[3] = range_limit[(int) DESCALE(tmp10 - tmp2,
  175751. CONST_BITS+PASS1_BITS+3+1)
  175752. & RANGE_MASK];
  175753. outptr[1] = range_limit[(int) DESCALE(tmp12 + tmp0,
  175754. CONST_BITS+PASS1_BITS+3+1)
  175755. & RANGE_MASK];
  175756. outptr[2] = range_limit[(int) DESCALE(tmp12 - tmp0,
  175757. CONST_BITS+PASS1_BITS+3+1)
  175758. & RANGE_MASK];
  175759. wsptr += DCTSIZE; /* advance pointer to next row */
  175760. }
  175761. }
  175762. /*
  175763. * Perform dequantization and inverse DCT on one block of coefficients,
  175764. * producing a reduced-size 2x2 output block.
  175765. */
  175766. GLOBAL(void)
  175767. jpeg_idct_2x2 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175768. JCOEFPTR coef_block,
  175769. JSAMPARRAY output_buf, JDIMENSION output_col)
  175770. {
  175771. INT32 tmp0, tmp10, z1;
  175772. JCOEFPTR inptr;
  175773. ISLOW_MULT_TYPE * quantptr;
  175774. int * wsptr;
  175775. JSAMPROW outptr;
  175776. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175777. int ctr;
  175778. int workspace[DCTSIZE*2]; /* buffers data between passes */
  175779. SHIFT_TEMPS
  175780. /* Pass 1: process columns from input, store into work array. */
  175781. inptr = coef_block;
  175782. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175783. wsptr = workspace;
  175784. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  175785. /* Don't bother to process columns 2,4,6 */
  175786. if (ctr == DCTSIZE-2 || ctr == DCTSIZE-4 || ctr == DCTSIZE-6)
  175787. continue;
  175788. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*3] == 0 &&
  175789. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*7] == 0) {
  175790. /* AC terms all zero; we need not examine terms 2,4,6 for 2x2 output */
  175791. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175792. wsptr[DCTSIZE*0] = dcval;
  175793. wsptr[DCTSIZE*1] = dcval;
  175794. continue;
  175795. }
  175796. /* Even part */
  175797. z1 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175798. tmp10 = z1 << (CONST_BITS+2);
  175799. /* Odd part */
  175800. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175801. tmp0 = MULTIPLY(z1, - FIX_0_720959822); /* sqrt(2) * (c7-c5+c3-c1) */
  175802. z1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175803. tmp0 += MULTIPLY(z1, FIX_0_850430095); /* sqrt(2) * (-c1+c3+c5+c7) */
  175804. z1 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175805. tmp0 += MULTIPLY(z1, - FIX_1_272758580); /* sqrt(2) * (-c1+c3-c5-c7) */
  175806. z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175807. tmp0 += MULTIPLY(z1, FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  175808. /* Final output stage */
  175809. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp0, CONST_BITS-PASS1_BITS+2);
  175810. wsptr[DCTSIZE*1] = (int) DESCALE(tmp10 - tmp0, CONST_BITS-PASS1_BITS+2);
  175811. }
  175812. /* Pass 2: process 2 rows from work array, store into output array. */
  175813. wsptr = workspace;
  175814. for (ctr = 0; ctr < 2; ctr++) {
  175815. outptr = output_buf[ctr] + output_col;
  175816. /* It's not clear whether a zero row test is worthwhile here ... */
  175817. #ifndef NO_ZERO_ROW_TEST
  175818. if (wsptr[1] == 0 && wsptr[3] == 0 && wsptr[5] == 0 && wsptr[7] == 0) {
  175819. /* AC terms all zero */
  175820. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175821. & RANGE_MASK];
  175822. outptr[0] = dcval;
  175823. outptr[1] = dcval;
  175824. wsptr += DCTSIZE; /* advance pointer to next row */
  175825. continue;
  175826. }
  175827. #endif
  175828. /* Even part */
  175829. tmp10 = ((INT32) wsptr[0]) << (CONST_BITS+2);
  175830. /* Odd part */
  175831. tmp0 = MULTIPLY((INT32) wsptr[7], - FIX_0_720959822) /* sqrt(2) * (c7-c5+c3-c1) */
  175832. + MULTIPLY((INT32) wsptr[5], FIX_0_850430095) /* sqrt(2) * (-c1+c3+c5+c7) */
  175833. + MULTIPLY((INT32) wsptr[3], - FIX_1_272758580) /* sqrt(2) * (-c1+c3-c5-c7) */
  175834. + MULTIPLY((INT32) wsptr[1], FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  175835. /* Final output stage */
  175836. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp0,
  175837. CONST_BITS+PASS1_BITS+3+2)
  175838. & RANGE_MASK];
  175839. outptr[1] = range_limit[(int) DESCALE(tmp10 - tmp0,
  175840. CONST_BITS+PASS1_BITS+3+2)
  175841. & RANGE_MASK];
  175842. wsptr += DCTSIZE; /* advance pointer to next row */
  175843. }
  175844. }
  175845. /*
  175846. * Perform dequantization and inverse DCT on one block of coefficients,
  175847. * producing a reduced-size 1x1 output block.
  175848. */
  175849. GLOBAL(void)
  175850. jpeg_idct_1x1 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175851. JCOEFPTR coef_block,
  175852. JSAMPARRAY output_buf, JDIMENSION output_col)
  175853. {
  175854. int dcval;
  175855. ISLOW_MULT_TYPE * quantptr;
  175856. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175857. SHIFT_TEMPS
  175858. /* We hardly need an inverse DCT routine for this: just take the
  175859. * average pixel value, which is one-eighth of the DC coefficient.
  175860. */
  175861. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175862. dcval = DEQUANTIZE(coef_block[0], quantptr[0]);
  175863. dcval = (int) DESCALE((INT32) dcval, 3);
  175864. output_buf[0][output_col] = range_limit[dcval & RANGE_MASK];
  175865. }
  175866. #endif /* IDCT_SCALING_SUPPORTED */
  175867. /*** End of inlined file: jidctred.c ***/
  175868. /*** Start of inlined file: jmemmgr.c ***/
  175869. #define JPEG_INTERNALS
  175870. #define AM_MEMORY_MANAGER /* we define jvirt_Xarray_control structs */
  175871. /*** Start of inlined file: jmemsys.h ***/
  175872. #ifndef __jmemsys_h__
  175873. #define __jmemsys_h__
  175874. /* Short forms of external names for systems with brain-damaged linkers. */
  175875. #ifdef NEED_SHORT_EXTERNAL_NAMES
  175876. #define jpeg_get_small jGetSmall
  175877. #define jpeg_free_small jFreeSmall
  175878. #define jpeg_get_large jGetLarge
  175879. #define jpeg_free_large jFreeLarge
  175880. #define jpeg_mem_available jMemAvail
  175881. #define jpeg_open_backing_store jOpenBackStore
  175882. #define jpeg_mem_init jMemInit
  175883. #define jpeg_mem_term jMemTerm
  175884. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  175885. /*
  175886. * These two functions are used to allocate and release small chunks of
  175887. * memory. (Typically the total amount requested through jpeg_get_small is
  175888. * no more than 20K or so; this will be requested in chunks of a few K each.)
  175889. * Behavior should be the same as for the standard library functions malloc
  175890. * and free; in particular, jpeg_get_small must return NULL on failure.
  175891. * On most systems, these ARE malloc and free. jpeg_free_small is passed the
  175892. * size of the object being freed, just in case it's needed.
  175893. * On an 80x86 machine using small-data memory model, these manage near heap.
  175894. */
  175895. EXTERN(void *) jpeg_get_small JPP((j_common_ptr cinfo, size_t sizeofobject));
  175896. EXTERN(void) jpeg_free_small JPP((j_common_ptr cinfo, void * object,
  175897. size_t sizeofobject));
  175898. /*
  175899. * These two functions are used to allocate and release large chunks of
  175900. * memory (up to the total free space designated by jpeg_mem_available).
  175901. * The interface is the same as above, except that on an 80x86 machine,
  175902. * far pointers are used. On most other machines these are identical to
  175903. * the jpeg_get/free_small routines; but we keep them separate anyway,
  175904. * in case a different allocation strategy is desirable for large chunks.
  175905. */
  175906. EXTERN(void FAR *) jpeg_get_large JPP((j_common_ptr cinfo,
  175907. size_t sizeofobject));
  175908. EXTERN(void) jpeg_free_large JPP((j_common_ptr cinfo, void FAR * object,
  175909. size_t sizeofobject));
  175910. /*
  175911. * The macro MAX_ALLOC_CHUNK designates the maximum number of bytes that may
  175912. * be requested in a single call to jpeg_get_large (and jpeg_get_small for that
  175913. * matter, but that case should never come into play). This macro is needed
  175914. * to model the 64Kb-segment-size limit of far addressing on 80x86 machines.
  175915. * On those machines, we expect that jconfig.h will provide a proper value.
  175916. * On machines with 32-bit flat address spaces, any large constant may be used.
  175917. *
  175918. * NB: jmemmgr.c expects that MAX_ALLOC_CHUNK will be representable as type
  175919. * size_t and will be a multiple of sizeof(align_type).
  175920. */
  175921. #ifndef MAX_ALLOC_CHUNK /* may be overridden in jconfig.h */
  175922. #define MAX_ALLOC_CHUNK 1000000000L
  175923. #endif
  175924. /*
  175925. * This routine computes the total space still available for allocation by
  175926. * jpeg_get_large. If more space than this is needed, backing store will be
  175927. * used. NOTE: any memory already allocated must not be counted.
  175928. *
  175929. * There is a minimum space requirement, corresponding to the minimum
  175930. * feasible buffer sizes; jmemmgr.c will request that much space even if
  175931. * jpeg_mem_available returns zero. The maximum space needed, enough to hold
  175932. * all working storage in memory, is also passed in case it is useful.
  175933. * Finally, the total space already allocated is passed. If no better
  175934. * method is available, cinfo->mem->max_memory_to_use - already_allocated
  175935. * is often a suitable calculation.
  175936. *
  175937. * It is OK for jpeg_mem_available to underestimate the space available
  175938. * (that'll just lead to more backing-store access than is really necessary).
  175939. * However, an overestimate will lead to failure. Hence it's wise to subtract
  175940. * a slop factor from the true available space. 5% should be enough.
  175941. *
  175942. * On machines with lots of virtual memory, any large constant may be returned.
  175943. * Conversely, zero may be returned to always use the minimum amount of memory.
  175944. */
  175945. EXTERN(long) jpeg_mem_available JPP((j_common_ptr cinfo,
  175946. long min_bytes_needed,
  175947. long max_bytes_needed,
  175948. long already_allocated));
  175949. /*
  175950. * This structure holds whatever state is needed to access a single
  175951. * backing-store object. The read/write/close method pointers are called
  175952. * by jmemmgr.c to manipulate the backing-store object; all other fields
  175953. * are private to the system-dependent backing store routines.
  175954. */
  175955. #define TEMP_NAME_LENGTH 64 /* max length of a temporary file's name */
  175956. #ifdef USE_MSDOS_MEMMGR /* DOS-specific junk */
  175957. typedef unsigned short XMSH; /* type of extended-memory handles */
  175958. typedef unsigned short EMSH; /* type of expanded-memory handles */
  175959. typedef union {
  175960. short file_handle; /* DOS file handle if it's a temp file */
  175961. XMSH xms_handle; /* handle if it's a chunk of XMS */
  175962. EMSH ems_handle; /* handle if it's a chunk of EMS */
  175963. } handle_union;
  175964. #endif /* USE_MSDOS_MEMMGR */
  175965. #ifdef USE_MAC_MEMMGR /* Mac-specific junk */
  175966. #include <Files.h>
  175967. #endif /* USE_MAC_MEMMGR */
  175968. //typedef struct backing_store_struct * backing_store_ptr;
  175969. typedef struct backing_store_struct {
  175970. /* Methods for reading/writing/closing this backing-store object */
  175971. JMETHOD(void, read_backing_store, (j_common_ptr cinfo,
  175972. struct backing_store_struct *info,
  175973. void FAR * buffer_address,
  175974. long file_offset, long byte_count));
  175975. JMETHOD(void, write_backing_store, (j_common_ptr cinfo,
  175976. struct backing_store_struct *info,
  175977. void FAR * buffer_address,
  175978. long file_offset, long byte_count));
  175979. JMETHOD(void, close_backing_store, (j_common_ptr cinfo,
  175980. struct backing_store_struct *info));
  175981. /* Private fields for system-dependent backing-store management */
  175982. #ifdef USE_MSDOS_MEMMGR
  175983. /* For the MS-DOS manager (jmemdos.c), we need: */
  175984. handle_union handle; /* reference to backing-store storage object */
  175985. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  175986. #else
  175987. #ifdef USE_MAC_MEMMGR
  175988. /* For the Mac manager (jmemmac.c), we need: */
  175989. short temp_file; /* file reference number to temp file */
  175990. FSSpec tempSpec; /* the FSSpec for the temp file */
  175991. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  175992. #else
  175993. /* For a typical implementation with temp files, we need: */
  175994. FILE * temp_file; /* stdio reference to temp file */
  175995. char temp_name[TEMP_NAME_LENGTH]; /* name of temp file */
  175996. #endif
  175997. #endif
  175998. } backing_store_info;
  175999. /*
  176000. * Initial opening of a backing-store object. This must fill in the
  176001. * read/write/close pointers in the object. The read/write routines
  176002. * may take an error exit if the specified maximum file size is exceeded.
  176003. * (If jpeg_mem_available always returns a large value, this routine can
  176004. * just take an error exit.)
  176005. */
  176006. EXTERN(void) jpeg_open_backing_store JPP((j_common_ptr cinfo,
  176007. struct backing_store_struct *info,
  176008. long total_bytes_needed));
  176009. /*
  176010. * These routines take care of any system-dependent initialization and
  176011. * cleanup required. jpeg_mem_init will be called before anything is
  176012. * allocated (and, therefore, nothing in cinfo is of use except the error
  176013. * manager pointer). It should return a suitable default value for
  176014. * max_memory_to_use; this may subsequently be overridden by the surrounding
  176015. * application. (Note that max_memory_to_use is only important if
  176016. * jpeg_mem_available chooses to consult it ... no one else will.)
  176017. * jpeg_mem_term may assume that all requested memory has been freed and that
  176018. * all opened backing-store objects have been closed.
  176019. */
  176020. EXTERN(long) jpeg_mem_init JPP((j_common_ptr cinfo));
  176021. EXTERN(void) jpeg_mem_term JPP((j_common_ptr cinfo));
  176022. #endif
  176023. /*** End of inlined file: jmemsys.h ***/
  176024. /* import the system-dependent declarations */
  176025. #ifndef NO_GETENV
  176026. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare getenv() */
  176027. extern char * getenv JPP((const char * name));
  176028. #endif
  176029. #endif
  176030. /*
  176031. * Some important notes:
  176032. * The allocation routines provided here must never return NULL.
  176033. * They should exit to error_exit if unsuccessful.
  176034. *
  176035. * It's not a good idea to try to merge the sarray and barray routines,
  176036. * even though they are textually almost the same, because samples are
  176037. * usually stored as bytes while coefficients are shorts or ints. Thus,
  176038. * in machines where byte pointers have a different representation from
  176039. * word pointers, the resulting machine code could not be the same.
  176040. */
  176041. /*
  176042. * Many machines require storage alignment: longs must start on 4-byte
  176043. * boundaries, doubles on 8-byte boundaries, etc. On such machines, malloc()
  176044. * always returns pointers that are multiples of the worst-case alignment
  176045. * requirement, and we had better do so too.
  176046. * There isn't any really portable way to determine the worst-case alignment
  176047. * requirement. This module assumes that the alignment requirement is
  176048. * multiples of sizeof(ALIGN_TYPE).
  176049. * By default, we define ALIGN_TYPE as double. This is necessary on some
  176050. * workstations (where doubles really do need 8-byte alignment) and will work
  176051. * fine on nearly everything. If your machine has lesser alignment needs,
  176052. * you can save a few bytes by making ALIGN_TYPE smaller.
  176053. * The only place I know of where this will NOT work is certain Macintosh
  176054. * 680x0 compilers that define double as a 10-byte IEEE extended float.
  176055. * Doing 10-byte alignment is counterproductive because longwords won't be
  176056. * aligned well. Put "#define ALIGN_TYPE long" in jconfig.h if you have
  176057. * such a compiler.
  176058. */
  176059. #ifndef ALIGN_TYPE /* so can override from jconfig.h */
  176060. #define ALIGN_TYPE double
  176061. #endif
  176062. /*
  176063. * We allocate objects from "pools", where each pool is gotten with a single
  176064. * request to jpeg_get_small() or jpeg_get_large(). There is no per-object
  176065. * overhead within a pool, except for alignment padding. Each pool has a
  176066. * header with a link to the next pool of the same class.
  176067. * Small and large pool headers are identical except that the latter's
  176068. * link pointer must be FAR on 80x86 machines.
  176069. * Notice that the "real" header fields are union'ed with a dummy ALIGN_TYPE
  176070. * field. This forces the compiler to make SIZEOF(small_pool_hdr) a multiple
  176071. * of the alignment requirement of ALIGN_TYPE.
  176072. */
  176073. typedef union small_pool_struct * small_pool_ptr;
  176074. typedef union small_pool_struct {
  176075. struct {
  176076. small_pool_ptr next; /* next in list of pools */
  176077. size_t bytes_used; /* how many bytes already used within pool */
  176078. size_t bytes_left; /* bytes still available in this pool */
  176079. } hdr;
  176080. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  176081. } small_pool_hdr;
  176082. typedef union large_pool_struct FAR * large_pool_ptr;
  176083. typedef union large_pool_struct {
  176084. struct {
  176085. large_pool_ptr next; /* next in list of pools */
  176086. size_t bytes_used; /* how many bytes already used within pool */
  176087. size_t bytes_left; /* bytes still available in this pool */
  176088. } hdr;
  176089. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  176090. } large_pool_hdr;
  176091. /*
  176092. * Here is the full definition of a memory manager object.
  176093. */
  176094. typedef struct {
  176095. struct jpeg_memory_mgr pub; /* public fields */
  176096. /* Each pool identifier (lifetime class) names a linked list of pools. */
  176097. small_pool_ptr small_list[JPOOL_NUMPOOLS];
  176098. large_pool_ptr large_list[JPOOL_NUMPOOLS];
  176099. /* Since we only have one lifetime class of virtual arrays, only one
  176100. * linked list is necessary (for each datatype). Note that the virtual
  176101. * array control blocks being linked together are actually stored somewhere
  176102. * in the small-pool list.
  176103. */
  176104. jvirt_sarray_ptr virt_sarray_list;
  176105. jvirt_barray_ptr virt_barray_list;
  176106. /* This counts total space obtained from jpeg_get_small/large */
  176107. long total_space_allocated;
  176108. /* alloc_sarray and alloc_barray set this value for use by virtual
  176109. * array routines.
  176110. */
  176111. JDIMENSION last_rowsperchunk; /* from most recent alloc_sarray/barray */
  176112. } my_memory_mgr;
  176113. typedef my_memory_mgr * my_mem_ptr;
  176114. /*
  176115. * The control blocks for virtual arrays.
  176116. * Note that these blocks are allocated in the "small" pool area.
  176117. * System-dependent info for the associated backing store (if any) is hidden
  176118. * inside the backing_store_info struct.
  176119. */
  176120. struct jvirt_sarray_control {
  176121. JSAMPARRAY mem_buffer; /* => the in-memory buffer */
  176122. JDIMENSION rows_in_array; /* total virtual array height */
  176123. JDIMENSION samplesperrow; /* width of array (and of memory buffer) */
  176124. JDIMENSION maxaccess; /* max rows accessed by access_virt_sarray */
  176125. JDIMENSION rows_in_mem; /* height of memory buffer */
  176126. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  176127. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  176128. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  176129. boolean pre_zero; /* pre-zero mode requested? */
  176130. boolean dirty; /* do current buffer contents need written? */
  176131. boolean b_s_open; /* is backing-store data valid? */
  176132. jvirt_sarray_ptr next; /* link to next virtual sarray control block */
  176133. backing_store_info b_s_info; /* System-dependent control info */
  176134. };
  176135. struct jvirt_barray_control {
  176136. JBLOCKARRAY mem_buffer; /* => the in-memory buffer */
  176137. JDIMENSION rows_in_array; /* total virtual array height */
  176138. JDIMENSION blocksperrow; /* width of array (and of memory buffer) */
  176139. JDIMENSION maxaccess; /* max rows accessed by access_virt_barray */
  176140. JDIMENSION rows_in_mem; /* height of memory buffer */
  176141. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  176142. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  176143. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  176144. boolean pre_zero; /* pre-zero mode requested? */
  176145. boolean dirty; /* do current buffer contents need written? */
  176146. boolean b_s_open; /* is backing-store data valid? */
  176147. jvirt_barray_ptr next; /* link to next virtual barray control block */
  176148. backing_store_info b_s_info; /* System-dependent control info */
  176149. };
  176150. #ifdef MEM_STATS /* optional extra stuff for statistics */
  176151. LOCAL(void)
  176152. print_mem_stats (j_common_ptr cinfo, int pool_id)
  176153. {
  176154. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176155. small_pool_ptr shdr_ptr;
  176156. large_pool_ptr lhdr_ptr;
  176157. /* Since this is only a debugging stub, we can cheat a little by using
  176158. * fprintf directly rather than going through the trace message code.
  176159. * This is helpful because message parm array can't handle longs.
  176160. */
  176161. fprintf(stderr, "Freeing pool %d, total space = %ld\n",
  176162. pool_id, mem->total_space_allocated);
  176163. for (lhdr_ptr = mem->large_list[pool_id]; lhdr_ptr != NULL;
  176164. lhdr_ptr = lhdr_ptr->hdr.next) {
  176165. fprintf(stderr, " Large chunk used %ld\n",
  176166. (long) lhdr_ptr->hdr.bytes_used);
  176167. }
  176168. for (shdr_ptr = mem->small_list[pool_id]; shdr_ptr != NULL;
  176169. shdr_ptr = shdr_ptr->hdr.next) {
  176170. fprintf(stderr, " Small chunk used %ld free %ld\n",
  176171. (long) shdr_ptr->hdr.bytes_used,
  176172. (long) shdr_ptr->hdr.bytes_left);
  176173. }
  176174. }
  176175. #endif /* MEM_STATS */
  176176. LOCAL(void)
  176177. out_of_memory (j_common_ptr cinfo, int which)
  176178. /* Report an out-of-memory error and stop execution */
  176179. /* If we compiled MEM_STATS support, report alloc requests before dying */
  176180. {
  176181. #ifdef MEM_STATS
  176182. cinfo->err->trace_level = 2; /* force self_destruct to report stats */
  176183. #endif
  176184. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, which);
  176185. }
  176186. /*
  176187. * Allocation of "small" objects.
  176188. *
  176189. * For these, we use pooled storage. When a new pool must be created,
  176190. * we try to get enough space for the current request plus a "slop" factor,
  176191. * where the slop will be the amount of leftover space in the new pool.
  176192. * The speed vs. space tradeoff is largely determined by the slop values.
  176193. * A different slop value is provided for each pool class (lifetime),
  176194. * and we also distinguish the first pool of a class from later ones.
  176195. * NOTE: the values given work fairly well on both 16- and 32-bit-int
  176196. * machines, but may be too small if longs are 64 bits or more.
  176197. */
  176198. static const size_t first_pool_slop[JPOOL_NUMPOOLS] =
  176199. {
  176200. 1600, /* first PERMANENT pool */
  176201. 16000 /* first IMAGE pool */
  176202. };
  176203. static const size_t extra_pool_slop[JPOOL_NUMPOOLS] =
  176204. {
  176205. 0, /* additional PERMANENT pools */
  176206. 5000 /* additional IMAGE pools */
  176207. };
  176208. #define MIN_SLOP 50 /* greater than 0 to avoid futile looping */
  176209. METHODDEF(void *)
  176210. alloc_small (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  176211. /* Allocate a "small" object */
  176212. {
  176213. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176214. small_pool_ptr hdr_ptr, prev_hdr_ptr;
  176215. char * data_ptr;
  176216. size_t odd_bytes, min_request, slop;
  176217. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  176218. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(small_pool_hdr)))
  176219. out_of_memory(cinfo, 1); /* request exceeds malloc's ability */
  176220. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  176221. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  176222. if (odd_bytes > 0)
  176223. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  176224. /* See if space is available in any existing pool */
  176225. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  176226. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176227. prev_hdr_ptr = NULL;
  176228. hdr_ptr = mem->small_list[pool_id];
  176229. while (hdr_ptr != NULL) {
  176230. if (hdr_ptr->hdr.bytes_left >= sizeofobject)
  176231. break; /* found pool with enough space */
  176232. prev_hdr_ptr = hdr_ptr;
  176233. hdr_ptr = hdr_ptr->hdr.next;
  176234. }
  176235. /* Time to make a new pool? */
  176236. if (hdr_ptr == NULL) {
  176237. /* min_request is what we need now, slop is what will be leftover */
  176238. min_request = sizeofobject + SIZEOF(small_pool_hdr);
  176239. if (prev_hdr_ptr == NULL) /* first pool in class? */
  176240. slop = first_pool_slop[pool_id];
  176241. else
  176242. slop = extra_pool_slop[pool_id];
  176243. /* Don't ask for more than MAX_ALLOC_CHUNK */
  176244. if (slop > (size_t) (MAX_ALLOC_CHUNK-min_request))
  176245. slop = (size_t) (MAX_ALLOC_CHUNK-min_request);
  176246. /* Try to get space, if fail reduce slop and try again */
  176247. for (;;) {
  176248. hdr_ptr = (small_pool_ptr) jpeg_get_small(cinfo, min_request + slop);
  176249. if (hdr_ptr != NULL)
  176250. break;
  176251. slop /= 2;
  176252. if (slop < MIN_SLOP) /* give up when it gets real small */
  176253. out_of_memory(cinfo, 2); /* jpeg_get_small failed */
  176254. }
  176255. mem->total_space_allocated += min_request + slop;
  176256. /* Success, initialize the new pool header and add to end of list */
  176257. hdr_ptr->hdr.next = NULL;
  176258. hdr_ptr->hdr.bytes_used = 0;
  176259. hdr_ptr->hdr.bytes_left = sizeofobject + slop;
  176260. if (prev_hdr_ptr == NULL) /* first pool in class? */
  176261. mem->small_list[pool_id] = hdr_ptr;
  176262. else
  176263. prev_hdr_ptr->hdr.next = hdr_ptr;
  176264. }
  176265. /* OK, allocate the object from the current pool */
  176266. data_ptr = (char *) (hdr_ptr + 1); /* point to first data byte in pool */
  176267. data_ptr += hdr_ptr->hdr.bytes_used; /* point to place for object */
  176268. hdr_ptr->hdr.bytes_used += sizeofobject;
  176269. hdr_ptr->hdr.bytes_left -= sizeofobject;
  176270. return (void *) data_ptr;
  176271. }
  176272. /*
  176273. * Allocation of "large" objects.
  176274. *
  176275. * The external semantics of these are the same as "small" objects,
  176276. * except that FAR pointers are used on 80x86. However the pool
  176277. * management heuristics are quite different. We assume that each
  176278. * request is large enough that it may as well be passed directly to
  176279. * jpeg_get_large; the pool management just links everything together
  176280. * so that we can free it all on demand.
  176281. * Note: the major use of "large" objects is in JSAMPARRAY and JBLOCKARRAY
  176282. * structures. The routines that create these structures (see below)
  176283. * deliberately bunch rows together to ensure a large request size.
  176284. */
  176285. METHODDEF(void FAR *)
  176286. alloc_large (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  176287. /* Allocate a "large" object */
  176288. {
  176289. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176290. large_pool_ptr hdr_ptr;
  176291. size_t odd_bytes;
  176292. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  176293. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)))
  176294. out_of_memory(cinfo, 3); /* request exceeds malloc's ability */
  176295. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  176296. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  176297. if (odd_bytes > 0)
  176298. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  176299. /* Always make a new pool */
  176300. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  176301. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176302. hdr_ptr = (large_pool_ptr) jpeg_get_large(cinfo, sizeofobject +
  176303. SIZEOF(large_pool_hdr));
  176304. if (hdr_ptr == NULL)
  176305. out_of_memory(cinfo, 4); /* jpeg_get_large failed */
  176306. mem->total_space_allocated += sizeofobject + SIZEOF(large_pool_hdr);
  176307. /* Success, initialize the new pool header and add to list */
  176308. hdr_ptr->hdr.next = mem->large_list[pool_id];
  176309. /* We maintain space counts in each pool header for statistical purposes,
  176310. * even though they are not needed for allocation.
  176311. */
  176312. hdr_ptr->hdr.bytes_used = sizeofobject;
  176313. hdr_ptr->hdr.bytes_left = 0;
  176314. mem->large_list[pool_id] = hdr_ptr;
  176315. return (void FAR *) (hdr_ptr + 1); /* point to first data byte in pool */
  176316. }
  176317. /*
  176318. * Creation of 2-D sample arrays.
  176319. * The pointers are in near heap, the samples themselves in FAR heap.
  176320. *
  176321. * To minimize allocation overhead and to allow I/O of large contiguous
  176322. * blocks, we allocate the sample rows in groups of as many rows as possible
  176323. * without exceeding MAX_ALLOC_CHUNK total bytes per allocation request.
  176324. * NB: the virtual array control routines, later in this file, know about
  176325. * this chunking of rows. The rowsperchunk value is left in the mem manager
  176326. * object so that it can be saved away if this sarray is the workspace for
  176327. * a virtual array.
  176328. */
  176329. METHODDEF(JSAMPARRAY)
  176330. alloc_sarray (j_common_ptr cinfo, int pool_id,
  176331. JDIMENSION samplesperrow, JDIMENSION numrows)
  176332. /* Allocate a 2-D sample array */
  176333. {
  176334. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176335. JSAMPARRAY result;
  176336. JSAMPROW workspace;
  176337. JDIMENSION rowsperchunk, currow, i;
  176338. long ltemp;
  176339. /* Calculate max # of rows allowed in one allocation chunk */
  176340. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  176341. ((long) samplesperrow * SIZEOF(JSAMPLE));
  176342. if (ltemp <= 0)
  176343. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  176344. if (ltemp < (long) numrows)
  176345. rowsperchunk = (JDIMENSION) ltemp;
  176346. else
  176347. rowsperchunk = numrows;
  176348. mem->last_rowsperchunk = rowsperchunk;
  176349. /* Get space for row pointers (small object) */
  176350. result = (JSAMPARRAY) alloc_small(cinfo, pool_id,
  176351. (size_t) (numrows * SIZEOF(JSAMPROW)));
  176352. /* Get the rows themselves (large objects) */
  176353. currow = 0;
  176354. while (currow < numrows) {
  176355. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  176356. workspace = (JSAMPROW) alloc_large(cinfo, pool_id,
  176357. (size_t) ((size_t) rowsperchunk * (size_t) samplesperrow
  176358. * SIZEOF(JSAMPLE)));
  176359. for (i = rowsperchunk; i > 0; i--) {
  176360. result[currow++] = workspace;
  176361. workspace += samplesperrow;
  176362. }
  176363. }
  176364. return result;
  176365. }
  176366. /*
  176367. * Creation of 2-D coefficient-block arrays.
  176368. * This is essentially the same as the code for sample arrays, above.
  176369. */
  176370. METHODDEF(JBLOCKARRAY)
  176371. alloc_barray (j_common_ptr cinfo, int pool_id,
  176372. JDIMENSION blocksperrow, JDIMENSION numrows)
  176373. /* Allocate a 2-D coefficient-block array */
  176374. {
  176375. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176376. JBLOCKARRAY result;
  176377. JBLOCKROW workspace;
  176378. JDIMENSION rowsperchunk, currow, i;
  176379. long ltemp;
  176380. /* Calculate max # of rows allowed in one allocation chunk */
  176381. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  176382. ((long) blocksperrow * SIZEOF(JBLOCK));
  176383. if (ltemp <= 0)
  176384. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  176385. if (ltemp < (long) numrows)
  176386. rowsperchunk = (JDIMENSION) ltemp;
  176387. else
  176388. rowsperchunk = numrows;
  176389. mem->last_rowsperchunk = rowsperchunk;
  176390. /* Get space for row pointers (small object) */
  176391. result = (JBLOCKARRAY) alloc_small(cinfo, pool_id,
  176392. (size_t) (numrows * SIZEOF(JBLOCKROW)));
  176393. /* Get the rows themselves (large objects) */
  176394. currow = 0;
  176395. while (currow < numrows) {
  176396. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  176397. workspace = (JBLOCKROW) alloc_large(cinfo, pool_id,
  176398. (size_t) ((size_t) rowsperchunk * (size_t) blocksperrow
  176399. * SIZEOF(JBLOCK)));
  176400. for (i = rowsperchunk; i > 0; i--) {
  176401. result[currow++] = workspace;
  176402. workspace += blocksperrow;
  176403. }
  176404. }
  176405. return result;
  176406. }
  176407. /*
  176408. * About virtual array management:
  176409. *
  176410. * The above "normal" array routines are only used to allocate strip buffers
  176411. * (as wide as the image, but just a few rows high). Full-image-sized buffers
  176412. * are handled as "virtual" arrays. The array is still accessed a strip at a
  176413. * time, but the memory manager must save the whole array for repeated
  176414. * accesses. The intended implementation is that there is a strip buffer in
  176415. * memory (as high as is possible given the desired memory limit), plus a
  176416. * backing file that holds the rest of the array.
  176417. *
  176418. * The request_virt_array routines are told the total size of the image and
  176419. * the maximum number of rows that will be accessed at once. The in-memory
  176420. * buffer must be at least as large as the maxaccess value.
  176421. *
  176422. * The request routines create control blocks but not the in-memory buffers.
  176423. * That is postponed until realize_virt_arrays is called. At that time the
  176424. * total amount of space needed is known (approximately, anyway), so free
  176425. * memory can be divided up fairly.
  176426. *
  176427. * The access_virt_array routines are responsible for making a specific strip
  176428. * area accessible (after reading or writing the backing file, if necessary).
  176429. * Note that the access routines are told whether the caller intends to modify
  176430. * the accessed strip; during a read-only pass this saves having to rewrite
  176431. * data to disk. The access routines are also responsible for pre-zeroing
  176432. * any newly accessed rows, if pre-zeroing was requested.
  176433. *
  176434. * In current usage, the access requests are usually for nonoverlapping
  176435. * strips; that is, successive access start_row numbers differ by exactly
  176436. * num_rows = maxaccess. This means we can get good performance with simple
  176437. * buffer dump/reload logic, by making the in-memory buffer be a multiple
  176438. * of the access height; then there will never be accesses across bufferload
  176439. * boundaries. The code will still work with overlapping access requests,
  176440. * but it doesn't handle bufferload overlaps very efficiently.
  176441. */
  176442. METHODDEF(jvirt_sarray_ptr)
  176443. request_virt_sarray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  176444. JDIMENSION samplesperrow, JDIMENSION numrows,
  176445. JDIMENSION maxaccess)
  176446. /* Request a virtual 2-D sample array */
  176447. {
  176448. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176449. jvirt_sarray_ptr result;
  176450. /* Only IMAGE-lifetime virtual arrays are currently supported */
  176451. if (pool_id != JPOOL_IMAGE)
  176452. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176453. /* get control block */
  176454. result = (jvirt_sarray_ptr) alloc_small(cinfo, pool_id,
  176455. SIZEOF(struct jvirt_sarray_control));
  176456. result->mem_buffer = NULL; /* marks array not yet realized */
  176457. result->rows_in_array = numrows;
  176458. result->samplesperrow = samplesperrow;
  176459. result->maxaccess = maxaccess;
  176460. result->pre_zero = pre_zero;
  176461. result->b_s_open = FALSE; /* no associated backing-store object */
  176462. result->next = mem->virt_sarray_list; /* add to list of virtual arrays */
  176463. mem->virt_sarray_list = result;
  176464. return result;
  176465. }
  176466. METHODDEF(jvirt_barray_ptr)
  176467. request_virt_barray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  176468. JDIMENSION blocksperrow, JDIMENSION numrows,
  176469. JDIMENSION maxaccess)
  176470. /* Request a virtual 2-D coefficient-block array */
  176471. {
  176472. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176473. jvirt_barray_ptr result;
  176474. /* Only IMAGE-lifetime virtual arrays are currently supported */
  176475. if (pool_id != JPOOL_IMAGE)
  176476. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176477. /* get control block */
  176478. result = (jvirt_barray_ptr) alloc_small(cinfo, pool_id,
  176479. SIZEOF(struct jvirt_barray_control));
  176480. result->mem_buffer = NULL; /* marks array not yet realized */
  176481. result->rows_in_array = numrows;
  176482. result->blocksperrow = blocksperrow;
  176483. result->maxaccess = maxaccess;
  176484. result->pre_zero = pre_zero;
  176485. result->b_s_open = FALSE; /* no associated backing-store object */
  176486. result->next = mem->virt_barray_list; /* add to list of virtual arrays */
  176487. mem->virt_barray_list = result;
  176488. return result;
  176489. }
  176490. METHODDEF(void)
  176491. realize_virt_arrays (j_common_ptr cinfo)
  176492. /* Allocate the in-memory buffers for any unrealized virtual arrays */
  176493. {
  176494. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176495. long space_per_minheight, maximum_space, avail_mem;
  176496. long minheights, max_minheights;
  176497. jvirt_sarray_ptr sptr;
  176498. jvirt_barray_ptr bptr;
  176499. /* Compute the minimum space needed (maxaccess rows in each buffer)
  176500. * and the maximum space needed (full image height in each buffer).
  176501. * These may be of use to the system-dependent jpeg_mem_available routine.
  176502. */
  176503. space_per_minheight = 0;
  176504. maximum_space = 0;
  176505. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176506. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  176507. space_per_minheight += (long) sptr->maxaccess *
  176508. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  176509. maximum_space += (long) sptr->rows_in_array *
  176510. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  176511. }
  176512. }
  176513. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176514. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  176515. space_per_minheight += (long) bptr->maxaccess *
  176516. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  176517. maximum_space += (long) bptr->rows_in_array *
  176518. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  176519. }
  176520. }
  176521. if (space_per_minheight <= 0)
  176522. return; /* no unrealized arrays, no work */
  176523. /* Determine amount of memory to actually use; this is system-dependent. */
  176524. avail_mem = jpeg_mem_available(cinfo, space_per_minheight, maximum_space,
  176525. mem->total_space_allocated);
  176526. /* If the maximum space needed is available, make all the buffers full
  176527. * height; otherwise parcel it out with the same number of minheights
  176528. * in each buffer.
  176529. */
  176530. if (avail_mem >= maximum_space)
  176531. max_minheights = 1000000000L;
  176532. else {
  176533. max_minheights = avail_mem / space_per_minheight;
  176534. /* If there doesn't seem to be enough space, try to get the minimum
  176535. * anyway. This allows a "stub" implementation of jpeg_mem_available().
  176536. */
  176537. if (max_minheights <= 0)
  176538. max_minheights = 1;
  176539. }
  176540. /* Allocate the in-memory buffers and initialize backing store as needed. */
  176541. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176542. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  176543. minheights = ((long) sptr->rows_in_array - 1L) / sptr->maxaccess + 1L;
  176544. if (minheights <= max_minheights) {
  176545. /* This buffer fits in memory */
  176546. sptr->rows_in_mem = sptr->rows_in_array;
  176547. } else {
  176548. /* It doesn't fit in memory, create backing store. */
  176549. sptr->rows_in_mem = (JDIMENSION) (max_minheights * sptr->maxaccess);
  176550. jpeg_open_backing_store(cinfo, & sptr->b_s_info,
  176551. (long) sptr->rows_in_array *
  176552. (long) sptr->samplesperrow *
  176553. (long) SIZEOF(JSAMPLE));
  176554. sptr->b_s_open = TRUE;
  176555. }
  176556. sptr->mem_buffer = alloc_sarray(cinfo, JPOOL_IMAGE,
  176557. sptr->samplesperrow, sptr->rows_in_mem);
  176558. sptr->rowsperchunk = mem->last_rowsperchunk;
  176559. sptr->cur_start_row = 0;
  176560. sptr->first_undef_row = 0;
  176561. sptr->dirty = FALSE;
  176562. }
  176563. }
  176564. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176565. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  176566. minheights = ((long) bptr->rows_in_array - 1L) / bptr->maxaccess + 1L;
  176567. if (minheights <= max_minheights) {
  176568. /* This buffer fits in memory */
  176569. bptr->rows_in_mem = bptr->rows_in_array;
  176570. } else {
  176571. /* It doesn't fit in memory, create backing store. */
  176572. bptr->rows_in_mem = (JDIMENSION) (max_minheights * bptr->maxaccess);
  176573. jpeg_open_backing_store(cinfo, & bptr->b_s_info,
  176574. (long) bptr->rows_in_array *
  176575. (long) bptr->blocksperrow *
  176576. (long) SIZEOF(JBLOCK));
  176577. bptr->b_s_open = TRUE;
  176578. }
  176579. bptr->mem_buffer = alloc_barray(cinfo, JPOOL_IMAGE,
  176580. bptr->blocksperrow, bptr->rows_in_mem);
  176581. bptr->rowsperchunk = mem->last_rowsperchunk;
  176582. bptr->cur_start_row = 0;
  176583. bptr->first_undef_row = 0;
  176584. bptr->dirty = FALSE;
  176585. }
  176586. }
  176587. }
  176588. LOCAL(void)
  176589. do_sarray_io (j_common_ptr cinfo, jvirt_sarray_ptr ptr, boolean writing)
  176590. /* Do backing store read or write of a virtual sample array */
  176591. {
  176592. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  176593. bytesperrow = (long) ptr->samplesperrow * SIZEOF(JSAMPLE);
  176594. file_offset = ptr->cur_start_row * bytesperrow;
  176595. /* Loop to read or write each allocation chunk in mem_buffer */
  176596. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  176597. /* One chunk, but check for short chunk at end of buffer */
  176598. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  176599. /* Transfer no more than is currently defined */
  176600. thisrow = (long) ptr->cur_start_row + i;
  176601. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  176602. /* Transfer no more than fits in file */
  176603. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  176604. if (rows <= 0) /* this chunk might be past end of file! */
  176605. break;
  176606. byte_count = rows * bytesperrow;
  176607. if (writing)
  176608. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  176609. (void FAR *) ptr->mem_buffer[i],
  176610. file_offset, byte_count);
  176611. else
  176612. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  176613. (void FAR *) ptr->mem_buffer[i],
  176614. file_offset, byte_count);
  176615. file_offset += byte_count;
  176616. }
  176617. }
  176618. LOCAL(void)
  176619. do_barray_io (j_common_ptr cinfo, jvirt_barray_ptr ptr, boolean writing)
  176620. /* Do backing store read or write of a virtual coefficient-block array */
  176621. {
  176622. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  176623. bytesperrow = (long) ptr->blocksperrow * SIZEOF(JBLOCK);
  176624. file_offset = ptr->cur_start_row * bytesperrow;
  176625. /* Loop to read or write each allocation chunk in mem_buffer */
  176626. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  176627. /* One chunk, but check for short chunk at end of buffer */
  176628. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  176629. /* Transfer no more than is currently defined */
  176630. thisrow = (long) ptr->cur_start_row + i;
  176631. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  176632. /* Transfer no more than fits in file */
  176633. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  176634. if (rows <= 0) /* this chunk might be past end of file! */
  176635. break;
  176636. byte_count = rows * bytesperrow;
  176637. if (writing)
  176638. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  176639. (void FAR *) ptr->mem_buffer[i],
  176640. file_offset, byte_count);
  176641. else
  176642. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  176643. (void FAR *) ptr->mem_buffer[i],
  176644. file_offset, byte_count);
  176645. file_offset += byte_count;
  176646. }
  176647. }
  176648. METHODDEF(JSAMPARRAY)
  176649. access_virt_sarray (j_common_ptr cinfo, jvirt_sarray_ptr ptr,
  176650. JDIMENSION start_row, JDIMENSION num_rows,
  176651. boolean writable)
  176652. /* Access the part of a virtual sample array starting at start_row */
  176653. /* and extending for num_rows rows. writable is true if */
  176654. /* caller intends to modify the accessed area. */
  176655. {
  176656. JDIMENSION end_row = start_row + num_rows;
  176657. JDIMENSION undef_row;
  176658. /* debugging check */
  176659. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  176660. ptr->mem_buffer == NULL)
  176661. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176662. /* Make the desired part of the virtual array accessible */
  176663. if (start_row < ptr->cur_start_row ||
  176664. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  176665. if (! ptr->b_s_open)
  176666. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  176667. /* Flush old buffer contents if necessary */
  176668. if (ptr->dirty) {
  176669. do_sarray_io(cinfo, ptr, TRUE);
  176670. ptr->dirty = FALSE;
  176671. }
  176672. /* Decide what part of virtual array to access.
  176673. * Algorithm: if target address > current window, assume forward scan,
  176674. * load starting at target address. If target address < current window,
  176675. * assume backward scan, load so that target area is top of window.
  176676. * Note that when switching from forward write to forward read, will have
  176677. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  176678. */
  176679. if (start_row > ptr->cur_start_row) {
  176680. ptr->cur_start_row = start_row;
  176681. } else {
  176682. /* use long arithmetic here to avoid overflow & unsigned problems */
  176683. long ltemp;
  176684. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  176685. if (ltemp < 0)
  176686. ltemp = 0; /* don't fall off front end of file */
  176687. ptr->cur_start_row = (JDIMENSION) ltemp;
  176688. }
  176689. /* Read in the selected part of the array.
  176690. * During the initial write pass, we will do no actual read
  176691. * because the selected part is all undefined.
  176692. */
  176693. do_sarray_io(cinfo, ptr, FALSE);
  176694. }
  176695. /* Ensure the accessed part of the array is defined; prezero if needed.
  176696. * To improve locality of access, we only prezero the part of the array
  176697. * that the caller is about to access, not the entire in-memory array.
  176698. */
  176699. if (ptr->first_undef_row < end_row) {
  176700. if (ptr->first_undef_row < start_row) {
  176701. if (writable) /* writer skipped over a section of array */
  176702. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176703. undef_row = start_row; /* but reader is allowed to read ahead */
  176704. } else {
  176705. undef_row = ptr->first_undef_row;
  176706. }
  176707. if (writable)
  176708. ptr->first_undef_row = end_row;
  176709. if (ptr->pre_zero) {
  176710. size_t bytesperrow = (size_t) ptr->samplesperrow * SIZEOF(JSAMPLE);
  176711. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  176712. end_row -= ptr->cur_start_row;
  176713. while (undef_row < end_row) {
  176714. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  176715. undef_row++;
  176716. }
  176717. } else {
  176718. if (! writable) /* reader looking at undefined data */
  176719. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176720. }
  176721. }
  176722. /* Flag the buffer dirty if caller will write in it */
  176723. if (writable)
  176724. ptr->dirty = TRUE;
  176725. /* Return address of proper part of the buffer */
  176726. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  176727. }
  176728. METHODDEF(JBLOCKARRAY)
  176729. access_virt_barray (j_common_ptr cinfo, jvirt_barray_ptr ptr,
  176730. JDIMENSION start_row, JDIMENSION num_rows,
  176731. boolean writable)
  176732. /* Access the part of a virtual block array starting at start_row */
  176733. /* and extending for num_rows rows. writable is true if */
  176734. /* caller intends to modify the accessed area. */
  176735. {
  176736. JDIMENSION end_row = start_row + num_rows;
  176737. JDIMENSION undef_row;
  176738. /* debugging check */
  176739. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  176740. ptr->mem_buffer == NULL)
  176741. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176742. /* Make the desired part of the virtual array accessible */
  176743. if (start_row < ptr->cur_start_row ||
  176744. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  176745. if (! ptr->b_s_open)
  176746. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  176747. /* Flush old buffer contents if necessary */
  176748. if (ptr->dirty) {
  176749. do_barray_io(cinfo, ptr, TRUE);
  176750. ptr->dirty = FALSE;
  176751. }
  176752. /* Decide what part of virtual array to access.
  176753. * Algorithm: if target address > current window, assume forward scan,
  176754. * load starting at target address. If target address < current window,
  176755. * assume backward scan, load so that target area is top of window.
  176756. * Note that when switching from forward write to forward read, will have
  176757. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  176758. */
  176759. if (start_row > ptr->cur_start_row) {
  176760. ptr->cur_start_row = start_row;
  176761. } else {
  176762. /* use long arithmetic here to avoid overflow & unsigned problems */
  176763. long ltemp;
  176764. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  176765. if (ltemp < 0)
  176766. ltemp = 0; /* don't fall off front end of file */
  176767. ptr->cur_start_row = (JDIMENSION) ltemp;
  176768. }
  176769. /* Read in the selected part of the array.
  176770. * During the initial write pass, we will do no actual read
  176771. * because the selected part is all undefined.
  176772. */
  176773. do_barray_io(cinfo, ptr, FALSE);
  176774. }
  176775. /* Ensure the accessed part of the array is defined; prezero if needed.
  176776. * To improve locality of access, we only prezero the part of the array
  176777. * that the caller is about to access, not the entire in-memory array.
  176778. */
  176779. if (ptr->first_undef_row < end_row) {
  176780. if (ptr->first_undef_row < start_row) {
  176781. if (writable) /* writer skipped over a section of array */
  176782. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176783. undef_row = start_row; /* but reader is allowed to read ahead */
  176784. } else {
  176785. undef_row = ptr->first_undef_row;
  176786. }
  176787. if (writable)
  176788. ptr->first_undef_row = end_row;
  176789. if (ptr->pre_zero) {
  176790. size_t bytesperrow = (size_t) ptr->blocksperrow * SIZEOF(JBLOCK);
  176791. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  176792. end_row -= ptr->cur_start_row;
  176793. while (undef_row < end_row) {
  176794. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  176795. undef_row++;
  176796. }
  176797. } else {
  176798. if (! writable) /* reader looking at undefined data */
  176799. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176800. }
  176801. }
  176802. /* Flag the buffer dirty if caller will write in it */
  176803. if (writable)
  176804. ptr->dirty = TRUE;
  176805. /* Return address of proper part of the buffer */
  176806. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  176807. }
  176808. /*
  176809. * Release all objects belonging to a specified pool.
  176810. */
  176811. METHODDEF(void)
  176812. free_pool (j_common_ptr cinfo, int pool_id)
  176813. {
  176814. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176815. small_pool_ptr shdr_ptr;
  176816. large_pool_ptr lhdr_ptr;
  176817. size_t space_freed;
  176818. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  176819. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176820. #ifdef MEM_STATS
  176821. if (cinfo->err->trace_level > 1)
  176822. print_mem_stats(cinfo, pool_id); /* print pool's memory usage statistics */
  176823. #endif
  176824. /* If freeing IMAGE pool, close any virtual arrays first */
  176825. if (pool_id == JPOOL_IMAGE) {
  176826. jvirt_sarray_ptr sptr;
  176827. jvirt_barray_ptr bptr;
  176828. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176829. if (sptr->b_s_open) { /* there may be no backing store */
  176830. sptr->b_s_open = FALSE; /* prevent recursive close if error */
  176831. (*sptr->b_s_info.close_backing_store) (cinfo, & sptr->b_s_info);
  176832. }
  176833. }
  176834. mem->virt_sarray_list = NULL;
  176835. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176836. if (bptr->b_s_open) { /* there may be no backing store */
  176837. bptr->b_s_open = FALSE; /* prevent recursive close if error */
  176838. (*bptr->b_s_info.close_backing_store) (cinfo, & bptr->b_s_info);
  176839. }
  176840. }
  176841. mem->virt_barray_list = NULL;
  176842. }
  176843. /* Release large objects */
  176844. lhdr_ptr = mem->large_list[pool_id];
  176845. mem->large_list[pool_id] = NULL;
  176846. while (lhdr_ptr != NULL) {
  176847. large_pool_ptr next_lhdr_ptr = lhdr_ptr->hdr.next;
  176848. space_freed = lhdr_ptr->hdr.bytes_used +
  176849. lhdr_ptr->hdr.bytes_left +
  176850. SIZEOF(large_pool_hdr);
  176851. jpeg_free_large(cinfo, (void FAR *) lhdr_ptr, space_freed);
  176852. mem->total_space_allocated -= space_freed;
  176853. lhdr_ptr = next_lhdr_ptr;
  176854. }
  176855. /* Release small objects */
  176856. shdr_ptr = mem->small_list[pool_id];
  176857. mem->small_list[pool_id] = NULL;
  176858. while (shdr_ptr != NULL) {
  176859. small_pool_ptr next_shdr_ptr = shdr_ptr->hdr.next;
  176860. space_freed = shdr_ptr->hdr.bytes_used +
  176861. shdr_ptr->hdr.bytes_left +
  176862. SIZEOF(small_pool_hdr);
  176863. jpeg_free_small(cinfo, (void *) shdr_ptr, space_freed);
  176864. mem->total_space_allocated -= space_freed;
  176865. shdr_ptr = next_shdr_ptr;
  176866. }
  176867. }
  176868. /*
  176869. * Close up shop entirely.
  176870. * Note that this cannot be called unless cinfo->mem is non-NULL.
  176871. */
  176872. METHODDEF(void)
  176873. self_destruct (j_common_ptr cinfo)
  176874. {
  176875. int pool;
  176876. /* Close all backing store, release all memory.
  176877. * Releasing pools in reverse order might help avoid fragmentation
  176878. * with some (brain-damaged) malloc libraries.
  176879. */
  176880. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  176881. free_pool(cinfo, pool);
  176882. }
  176883. /* Release the memory manager control block too. */
  176884. jpeg_free_small(cinfo, (void *) cinfo->mem, SIZEOF(my_memory_mgr));
  176885. cinfo->mem = NULL; /* ensures I will be called only once */
  176886. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  176887. }
  176888. /*
  176889. * Memory manager initialization.
  176890. * When this is called, only the error manager pointer is valid in cinfo!
  176891. */
  176892. GLOBAL(void)
  176893. jinit_memory_mgr (j_common_ptr cinfo)
  176894. {
  176895. my_mem_ptr mem;
  176896. long max_to_use;
  176897. int pool;
  176898. size_t test_mac;
  176899. cinfo->mem = NULL; /* for safety if init fails */
  176900. /* Check for configuration errors.
  176901. * SIZEOF(ALIGN_TYPE) should be a power of 2; otherwise, it probably
  176902. * doesn't reflect any real hardware alignment requirement.
  176903. * The test is a little tricky: for X>0, X and X-1 have no one-bits
  176904. * in common if and only if X is a power of 2, ie has only one one-bit.
  176905. * Some compilers may give an "unreachable code" warning here; ignore it.
  176906. */
  176907. if ((SIZEOF(ALIGN_TYPE) & (SIZEOF(ALIGN_TYPE)-1)) != 0)
  176908. ERREXIT(cinfo, JERR_BAD_ALIGN_TYPE);
  176909. /* MAX_ALLOC_CHUNK must be representable as type size_t, and must be
  176910. * a multiple of SIZEOF(ALIGN_TYPE).
  176911. * Again, an "unreachable code" warning may be ignored here.
  176912. * But a "constant too large" warning means you need to fix MAX_ALLOC_CHUNK.
  176913. */
  176914. test_mac = (size_t) MAX_ALLOC_CHUNK;
  176915. if ((long) test_mac != MAX_ALLOC_CHUNK ||
  176916. (MAX_ALLOC_CHUNK % SIZEOF(ALIGN_TYPE)) != 0)
  176917. ERREXIT(cinfo, JERR_BAD_ALLOC_CHUNK);
  176918. max_to_use = jpeg_mem_init(cinfo); /* system-dependent initialization */
  176919. /* Attempt to allocate memory manager's control block */
  176920. mem = (my_mem_ptr) jpeg_get_small(cinfo, SIZEOF(my_memory_mgr));
  176921. if (mem == NULL) {
  176922. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  176923. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 0);
  176924. }
  176925. /* OK, fill in the method pointers */
  176926. mem->pub.alloc_small = alloc_small;
  176927. mem->pub.alloc_large = alloc_large;
  176928. mem->pub.alloc_sarray = alloc_sarray;
  176929. mem->pub.alloc_barray = alloc_barray;
  176930. mem->pub.request_virt_sarray = request_virt_sarray;
  176931. mem->pub.request_virt_barray = request_virt_barray;
  176932. mem->pub.realize_virt_arrays = realize_virt_arrays;
  176933. mem->pub.access_virt_sarray = access_virt_sarray;
  176934. mem->pub.access_virt_barray = access_virt_barray;
  176935. mem->pub.free_pool = free_pool;
  176936. mem->pub.self_destruct = self_destruct;
  176937. /* Make MAX_ALLOC_CHUNK accessible to other modules */
  176938. mem->pub.max_alloc_chunk = MAX_ALLOC_CHUNK;
  176939. /* Initialize working state */
  176940. mem->pub.max_memory_to_use = max_to_use;
  176941. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  176942. mem->small_list[pool] = NULL;
  176943. mem->large_list[pool] = NULL;
  176944. }
  176945. mem->virt_sarray_list = NULL;
  176946. mem->virt_barray_list = NULL;
  176947. mem->total_space_allocated = SIZEOF(my_memory_mgr);
  176948. /* Declare ourselves open for business */
  176949. cinfo->mem = & mem->pub;
  176950. /* Check for an environment variable JPEGMEM; if found, override the
  176951. * default max_memory setting from jpeg_mem_init. Note that the
  176952. * surrounding application may again override this value.
  176953. * If your system doesn't support getenv(), define NO_GETENV to disable
  176954. * this feature.
  176955. */
  176956. #ifndef NO_GETENV
  176957. { char * memenv;
  176958. if ((memenv = getenv("JPEGMEM")) != NULL) {
  176959. char ch = 'x';
  176960. if (sscanf(memenv, "%ld%c", &max_to_use, &ch) > 0) {
  176961. if (ch == 'm' || ch == 'M')
  176962. max_to_use *= 1000L;
  176963. mem->pub.max_memory_to_use = max_to_use * 1000L;
  176964. }
  176965. }
  176966. }
  176967. #endif
  176968. }
  176969. /*** End of inlined file: jmemmgr.c ***/
  176970. /*** Start of inlined file: jmemnobs.c ***/
  176971. #define JPEG_INTERNALS
  176972. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare malloc(),free() */
  176973. extern void * malloc JPP((size_t size));
  176974. extern void free JPP((void *ptr));
  176975. #endif
  176976. /*
  176977. * Memory allocation and freeing are controlled by the regular library
  176978. * routines malloc() and free().
  176979. */
  176980. GLOBAL(void *)
  176981. jpeg_get_small (j_common_ptr , size_t sizeofobject)
  176982. {
  176983. return (void *) malloc(sizeofobject);
  176984. }
  176985. GLOBAL(void)
  176986. jpeg_free_small (j_common_ptr , void * object, size_t)
  176987. {
  176988. free(object);
  176989. }
  176990. /*
  176991. * "Large" objects are treated the same as "small" ones.
  176992. * NB: although we include FAR keywords in the routine declarations,
  176993. * this file won't actually work in 80x86 small/medium model; at least,
  176994. * you probably won't be able to process useful-size images in only 64KB.
  176995. */
  176996. GLOBAL(void FAR *)
  176997. jpeg_get_large (j_common_ptr, size_t sizeofobject)
  176998. {
  176999. return (void FAR *) malloc(sizeofobject);
  177000. }
  177001. GLOBAL(void)
  177002. jpeg_free_large (j_common_ptr, void FAR * object, size_t)
  177003. {
  177004. free(object);
  177005. }
  177006. /*
  177007. * This routine computes the total memory space available for allocation.
  177008. * Here we always say, "we got all you want bud!"
  177009. */
  177010. GLOBAL(long)
  177011. jpeg_mem_available (j_common_ptr, long,
  177012. long max_bytes_needed, long)
  177013. {
  177014. return max_bytes_needed;
  177015. }
  177016. /*
  177017. * Backing store (temporary file) management.
  177018. * Since jpeg_mem_available always promised the moon,
  177019. * this should never be called and we can just error out.
  177020. */
  177021. GLOBAL(void)
  177022. jpeg_open_backing_store (j_common_ptr cinfo, struct backing_store_struct *,
  177023. long )
  177024. {
  177025. ERREXIT(cinfo, JERR_NO_BACKING_STORE);
  177026. }
  177027. /*
  177028. * These routines take care of any system-dependent initialization and
  177029. * cleanup required. Here, there isn't any.
  177030. */
  177031. GLOBAL(long)
  177032. jpeg_mem_init (j_common_ptr)
  177033. {
  177034. return 0; /* just set max_memory_to_use to 0 */
  177035. }
  177036. GLOBAL(void)
  177037. jpeg_mem_term (j_common_ptr)
  177038. {
  177039. /* no work */
  177040. }
  177041. /*** End of inlined file: jmemnobs.c ***/
  177042. /*** Start of inlined file: jquant1.c ***/
  177043. #define JPEG_INTERNALS
  177044. #ifdef QUANT_1PASS_SUPPORTED
  177045. /*
  177046. * The main purpose of 1-pass quantization is to provide a fast, if not very
  177047. * high quality, colormapped output capability. A 2-pass quantizer usually
  177048. * gives better visual quality; however, for quantized grayscale output this
  177049. * quantizer is perfectly adequate. Dithering is highly recommended with this
  177050. * quantizer, though you can turn it off if you really want to.
  177051. *
  177052. * In 1-pass quantization the colormap must be chosen in advance of seeing the
  177053. * image. We use a map consisting of all combinations of Ncolors[i] color
  177054. * values for the i'th component. The Ncolors[] values are chosen so that
  177055. * their product, the total number of colors, is no more than that requested.
  177056. * (In most cases, the product will be somewhat less.)
  177057. *
  177058. * Since the colormap is orthogonal, the representative value for each color
  177059. * component can be determined without considering the other components;
  177060. * then these indexes can be combined into a colormap index by a standard
  177061. * N-dimensional-array-subscript calculation. Most of the arithmetic involved
  177062. * can be precalculated and stored in the lookup table colorindex[].
  177063. * colorindex[i][j] maps pixel value j in component i to the nearest
  177064. * representative value (grid plane) for that component; this index is
  177065. * multiplied by the array stride for component i, so that the
  177066. * index of the colormap entry closest to a given pixel value is just
  177067. * sum( colorindex[component-number][pixel-component-value] )
  177068. * Aside from being fast, this scheme allows for variable spacing between
  177069. * representative values with no additional lookup cost.
  177070. *
  177071. * If gamma correction has been applied in color conversion, it might be wise
  177072. * to adjust the color grid spacing so that the representative colors are
  177073. * equidistant in linear space. At this writing, gamma correction is not
  177074. * implemented by jdcolor, so nothing is done here.
  177075. */
  177076. /* Declarations for ordered dithering.
  177077. *
  177078. * We use a standard 16x16 ordered dither array. The basic concept of ordered
  177079. * dithering is described in many references, for instance Dale Schumacher's
  177080. * chapter II.2 of Graphics Gems II (James Arvo, ed. Academic Press, 1991).
  177081. * In place of Schumacher's comparisons against a "threshold" value, we add a
  177082. * "dither" value to the input pixel and then round the result to the nearest
  177083. * output value. The dither value is equivalent to (0.5 - threshold) times
  177084. * the distance between output values. For ordered dithering, we assume that
  177085. * the output colors are equally spaced; if not, results will probably be
  177086. * worse, since the dither may be too much or too little at a given point.
  177087. *
  177088. * The normal calculation would be to form pixel value + dither, range-limit
  177089. * this to 0..MAXJSAMPLE, and then index into the colorindex table as usual.
  177090. * We can skip the separate range-limiting step by extending the colorindex
  177091. * table in both directions.
  177092. */
  177093. #define ODITHER_SIZE 16 /* dimension of dither matrix */
  177094. /* NB: if ODITHER_SIZE is not a power of 2, ODITHER_MASK uses will break */
  177095. #define ODITHER_CELLS (ODITHER_SIZE*ODITHER_SIZE) /* # cells in matrix */
  177096. #define ODITHER_MASK (ODITHER_SIZE-1) /* mask for wrapping around counters */
  177097. typedef int ODITHER_MATRIX[ODITHER_SIZE][ODITHER_SIZE];
  177098. typedef int (*ODITHER_MATRIX_PTR)[ODITHER_SIZE];
  177099. static const UINT8 base_dither_matrix[ODITHER_SIZE][ODITHER_SIZE] = {
  177100. /* Bayer's order-4 dither array. Generated by the code given in
  177101. * Stephen Hawley's article "Ordered Dithering" in Graphics Gems I.
  177102. * The values in this array must range from 0 to ODITHER_CELLS-1.
  177103. */
  177104. { 0,192, 48,240, 12,204, 60,252, 3,195, 51,243, 15,207, 63,255 },
  177105. { 128, 64,176,112,140, 76,188,124,131, 67,179,115,143, 79,191,127 },
  177106. { 32,224, 16,208, 44,236, 28,220, 35,227, 19,211, 47,239, 31,223 },
  177107. { 160, 96,144, 80,172,108,156, 92,163, 99,147, 83,175,111,159, 95 },
  177108. { 8,200, 56,248, 4,196, 52,244, 11,203, 59,251, 7,199, 55,247 },
  177109. { 136, 72,184,120,132, 68,180,116,139, 75,187,123,135, 71,183,119 },
  177110. { 40,232, 24,216, 36,228, 20,212, 43,235, 27,219, 39,231, 23,215 },
  177111. { 168,104,152, 88,164,100,148, 84,171,107,155, 91,167,103,151, 87 },
  177112. { 2,194, 50,242, 14,206, 62,254, 1,193, 49,241, 13,205, 61,253 },
  177113. { 130, 66,178,114,142, 78,190,126,129, 65,177,113,141, 77,189,125 },
  177114. { 34,226, 18,210, 46,238, 30,222, 33,225, 17,209, 45,237, 29,221 },
  177115. { 162, 98,146, 82,174,110,158, 94,161, 97,145, 81,173,109,157, 93 },
  177116. { 10,202, 58,250, 6,198, 54,246, 9,201, 57,249, 5,197, 53,245 },
  177117. { 138, 74,186,122,134, 70,182,118,137, 73,185,121,133, 69,181,117 },
  177118. { 42,234, 26,218, 38,230, 22,214, 41,233, 25,217, 37,229, 21,213 },
  177119. { 170,106,154, 90,166,102,150, 86,169,105,153, 89,165,101,149, 85 }
  177120. };
  177121. /* Declarations for Floyd-Steinberg dithering.
  177122. *
  177123. * Errors are accumulated into the array fserrors[], at a resolution of
  177124. * 1/16th of a pixel count. The error at a given pixel is propagated
  177125. * to its not-yet-processed neighbors using the standard F-S fractions,
  177126. * ... (here) 7/16
  177127. * 3/16 5/16 1/16
  177128. * We work left-to-right on even rows, right-to-left on odd rows.
  177129. *
  177130. * We can get away with a single array (holding one row's worth of errors)
  177131. * by using it to store the current row's errors at pixel columns not yet
  177132. * processed, but the next row's errors at columns already processed. We
  177133. * need only a few extra variables to hold the errors immediately around the
  177134. * current column. (If we are lucky, those variables are in registers, but
  177135. * even if not, they're probably cheaper to access than array elements are.)
  177136. *
  177137. * The fserrors[] array is indexed [component#][position].
  177138. * We provide (#columns + 2) entries per component; the extra entry at each
  177139. * end saves us from special-casing the first and last pixels.
  177140. *
  177141. * Note: on a wide image, we might not have enough room in a PC's near data
  177142. * segment to hold the error array; so it is allocated with alloc_large.
  177143. */
  177144. #if BITS_IN_JSAMPLE == 8
  177145. typedef INT16 FSERROR; /* 16 bits should be enough */
  177146. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  177147. #else
  177148. typedef INT32 FSERROR; /* may need more than 16 bits */
  177149. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  177150. #endif
  177151. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  177152. /* Private subobject */
  177153. #define MAX_Q_COMPS 4 /* max components I can handle */
  177154. typedef struct {
  177155. struct jpeg_color_quantizer pub; /* public fields */
  177156. /* Initially allocated colormap is saved here */
  177157. JSAMPARRAY sv_colormap; /* The color map as a 2-D pixel array */
  177158. int sv_actual; /* number of entries in use */
  177159. JSAMPARRAY colorindex; /* Precomputed mapping for speed */
  177160. /* colorindex[i][j] = index of color closest to pixel value j in component i,
  177161. * premultiplied as described above. Since colormap indexes must fit into
  177162. * JSAMPLEs, the entries of this array will too.
  177163. */
  177164. boolean is_padded; /* is the colorindex padded for odither? */
  177165. int Ncolors[MAX_Q_COMPS]; /* # of values alloced to each component */
  177166. /* Variables for ordered dithering */
  177167. int row_index; /* cur row's vertical index in dither matrix */
  177168. ODITHER_MATRIX_PTR odither[MAX_Q_COMPS]; /* one dither array per component */
  177169. /* Variables for Floyd-Steinberg dithering */
  177170. FSERRPTR fserrors[MAX_Q_COMPS]; /* accumulated errors */
  177171. boolean on_odd_row; /* flag to remember which row we are on */
  177172. } my_cquantizer;
  177173. typedef my_cquantizer * my_cquantize_ptr;
  177174. /*
  177175. * Policy-making subroutines for create_colormap and create_colorindex.
  177176. * These routines determine the colormap to be used. The rest of the module
  177177. * only assumes that the colormap is orthogonal.
  177178. *
  177179. * * select_ncolors decides how to divvy up the available colors
  177180. * among the components.
  177181. * * output_value defines the set of representative values for a component.
  177182. * * largest_input_value defines the mapping from input values to
  177183. * representative values for a component.
  177184. * Note that the latter two routines may impose different policies for
  177185. * different components, though this is not currently done.
  177186. */
  177187. LOCAL(int)
  177188. select_ncolors (j_decompress_ptr cinfo, int Ncolors[])
  177189. /* Determine allocation of desired colors to components, */
  177190. /* and fill in Ncolors[] array to indicate choice. */
  177191. /* Return value is total number of colors (product of Ncolors[] values). */
  177192. {
  177193. int nc = cinfo->out_color_components; /* number of color components */
  177194. int max_colors = cinfo->desired_number_of_colors;
  177195. int total_colors, iroot, i, j;
  177196. boolean changed;
  177197. long temp;
  177198. static const int RGB_order[3] = { RGB_GREEN, RGB_RED, RGB_BLUE };
  177199. /* We can allocate at least the nc'th root of max_colors per component. */
  177200. /* Compute floor(nc'th root of max_colors). */
  177201. iroot = 1;
  177202. do {
  177203. iroot++;
  177204. temp = iroot; /* set temp = iroot ** nc */
  177205. for (i = 1; i < nc; i++)
  177206. temp *= iroot;
  177207. } while (temp <= (long) max_colors); /* repeat till iroot exceeds root */
  177208. iroot--; /* now iroot = floor(root) */
  177209. /* Must have at least 2 color values per component */
  177210. if (iroot < 2)
  177211. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, (int) temp);
  177212. /* Initialize to iroot color values for each component */
  177213. total_colors = 1;
  177214. for (i = 0; i < nc; i++) {
  177215. Ncolors[i] = iroot;
  177216. total_colors *= iroot;
  177217. }
  177218. /* We may be able to increment the count for one or more components without
  177219. * exceeding max_colors, though we know not all can be incremented.
  177220. * Sometimes, the first component can be incremented more than once!
  177221. * (Example: for 16 colors, we start at 2*2*2, go to 3*2*2, then 4*2*2.)
  177222. * In RGB colorspace, try to increment G first, then R, then B.
  177223. */
  177224. do {
  177225. changed = FALSE;
  177226. for (i = 0; i < nc; i++) {
  177227. j = (cinfo->out_color_space == JCS_RGB ? RGB_order[i] : i);
  177228. /* calculate new total_colors if Ncolors[j] is incremented */
  177229. temp = total_colors / Ncolors[j];
  177230. temp *= Ncolors[j]+1; /* done in long arith to avoid oflo */
  177231. if (temp > (long) max_colors)
  177232. break; /* won't fit, done with this pass */
  177233. Ncolors[j]++; /* OK, apply the increment */
  177234. total_colors = (int) temp;
  177235. changed = TRUE;
  177236. }
  177237. } while (changed);
  177238. return total_colors;
  177239. }
  177240. LOCAL(int)
  177241. output_value (j_decompress_ptr, int, int j, int maxj)
  177242. /* Return j'th output value, where j will range from 0 to maxj */
  177243. /* The output values must fall in 0..MAXJSAMPLE in increasing order */
  177244. {
  177245. /* We always provide values 0 and MAXJSAMPLE for each component;
  177246. * any additional values are equally spaced between these limits.
  177247. * (Forcing the upper and lower values to the limits ensures that
  177248. * dithering can't produce a color outside the selected gamut.)
  177249. */
  177250. return (int) (((INT32) j * MAXJSAMPLE + maxj/2) / maxj);
  177251. }
  177252. LOCAL(int)
  177253. largest_input_value (j_decompress_ptr, int, int j, int maxj)
  177254. /* Return largest input value that should map to j'th output value */
  177255. /* Must have largest(j=0) >= 0, and largest(j=maxj) >= MAXJSAMPLE */
  177256. {
  177257. /* Breakpoints are halfway between values returned by output_value */
  177258. return (int) (((INT32) (2*j + 1) * MAXJSAMPLE + maxj) / (2*maxj));
  177259. }
  177260. /*
  177261. * Create the colormap.
  177262. */
  177263. LOCAL(void)
  177264. create_colormap (j_decompress_ptr cinfo)
  177265. {
  177266. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177267. JSAMPARRAY colormap; /* Created colormap */
  177268. int total_colors; /* Number of distinct output colors */
  177269. int i,j,k, nci, blksize, blkdist, ptr, val;
  177270. /* Select number of colors for each component */
  177271. total_colors = select_ncolors(cinfo, cquantize->Ncolors);
  177272. /* Report selected color counts */
  177273. if (cinfo->out_color_components == 3)
  177274. TRACEMS4(cinfo, 1, JTRC_QUANT_3_NCOLORS,
  177275. total_colors, cquantize->Ncolors[0],
  177276. cquantize->Ncolors[1], cquantize->Ncolors[2]);
  177277. else
  177278. TRACEMS1(cinfo, 1, JTRC_QUANT_NCOLORS, total_colors);
  177279. /* Allocate and fill in the colormap. */
  177280. /* The colors are ordered in the map in standard row-major order, */
  177281. /* i.e. rightmost (highest-indexed) color changes most rapidly. */
  177282. colormap = (*cinfo->mem->alloc_sarray)
  177283. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177284. (JDIMENSION) total_colors, (JDIMENSION) cinfo->out_color_components);
  177285. /* blksize is number of adjacent repeated entries for a component */
  177286. /* blkdist is distance between groups of identical entries for a component */
  177287. blkdist = total_colors;
  177288. for (i = 0; i < cinfo->out_color_components; i++) {
  177289. /* fill in colormap entries for i'th color component */
  177290. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  177291. blksize = blkdist / nci;
  177292. for (j = 0; j < nci; j++) {
  177293. /* Compute j'th output value (out of nci) for component */
  177294. val = output_value(cinfo, i, j, nci-1);
  177295. /* Fill in all colormap entries that have this value of this component */
  177296. for (ptr = j * blksize; ptr < total_colors; ptr += blkdist) {
  177297. /* fill in blksize entries beginning at ptr */
  177298. for (k = 0; k < blksize; k++)
  177299. colormap[i][ptr+k] = (JSAMPLE) val;
  177300. }
  177301. }
  177302. blkdist = blksize; /* blksize of this color is blkdist of next */
  177303. }
  177304. /* Save the colormap in private storage,
  177305. * where it will survive color quantization mode changes.
  177306. */
  177307. cquantize->sv_colormap = colormap;
  177308. cquantize->sv_actual = total_colors;
  177309. }
  177310. /*
  177311. * Create the color index table.
  177312. */
  177313. LOCAL(void)
  177314. create_colorindex (j_decompress_ptr cinfo)
  177315. {
  177316. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177317. JSAMPROW indexptr;
  177318. int i,j,k, nci, blksize, val, pad;
  177319. /* For ordered dither, we pad the color index tables by MAXJSAMPLE in
  177320. * each direction (input index values can be -MAXJSAMPLE .. 2*MAXJSAMPLE).
  177321. * This is not necessary in the other dithering modes. However, we
  177322. * flag whether it was done in case user changes dithering mode.
  177323. */
  177324. if (cinfo->dither_mode == JDITHER_ORDERED) {
  177325. pad = MAXJSAMPLE*2;
  177326. cquantize->is_padded = TRUE;
  177327. } else {
  177328. pad = 0;
  177329. cquantize->is_padded = FALSE;
  177330. }
  177331. cquantize->colorindex = (*cinfo->mem->alloc_sarray)
  177332. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177333. (JDIMENSION) (MAXJSAMPLE+1 + pad),
  177334. (JDIMENSION) cinfo->out_color_components);
  177335. /* blksize is number of adjacent repeated entries for a component */
  177336. blksize = cquantize->sv_actual;
  177337. for (i = 0; i < cinfo->out_color_components; i++) {
  177338. /* fill in colorindex entries for i'th color component */
  177339. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  177340. blksize = blksize / nci;
  177341. /* adjust colorindex pointers to provide padding at negative indexes. */
  177342. if (pad)
  177343. cquantize->colorindex[i] += MAXJSAMPLE;
  177344. /* in loop, val = index of current output value, */
  177345. /* and k = largest j that maps to current val */
  177346. indexptr = cquantize->colorindex[i];
  177347. val = 0;
  177348. k = largest_input_value(cinfo, i, 0, nci-1);
  177349. for (j = 0; j <= MAXJSAMPLE; j++) {
  177350. while (j > k) /* advance val if past boundary */
  177351. k = largest_input_value(cinfo, i, ++val, nci-1);
  177352. /* premultiply so that no multiplication needed in main processing */
  177353. indexptr[j] = (JSAMPLE) (val * blksize);
  177354. }
  177355. /* Pad at both ends if necessary */
  177356. if (pad)
  177357. for (j = 1; j <= MAXJSAMPLE; j++) {
  177358. indexptr[-j] = indexptr[0];
  177359. indexptr[MAXJSAMPLE+j] = indexptr[MAXJSAMPLE];
  177360. }
  177361. }
  177362. }
  177363. /*
  177364. * Create an ordered-dither array for a component having ncolors
  177365. * distinct output values.
  177366. */
  177367. LOCAL(ODITHER_MATRIX_PTR)
  177368. make_odither_array (j_decompress_ptr cinfo, int ncolors)
  177369. {
  177370. ODITHER_MATRIX_PTR odither;
  177371. int j,k;
  177372. INT32 num,den;
  177373. odither = (ODITHER_MATRIX_PTR)
  177374. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177375. SIZEOF(ODITHER_MATRIX));
  177376. /* The inter-value distance for this color is MAXJSAMPLE/(ncolors-1).
  177377. * Hence the dither value for the matrix cell with fill order f
  177378. * (f=0..N-1) should be (N-1-2*f)/(2*N) * MAXJSAMPLE/(ncolors-1).
  177379. * On 16-bit-int machine, be careful to avoid overflow.
  177380. */
  177381. den = 2 * ODITHER_CELLS * ((INT32) (ncolors - 1));
  177382. for (j = 0; j < ODITHER_SIZE; j++) {
  177383. for (k = 0; k < ODITHER_SIZE; k++) {
  177384. num = ((INT32) (ODITHER_CELLS-1 - 2*((int)base_dither_matrix[j][k])))
  177385. * MAXJSAMPLE;
  177386. /* Ensure round towards zero despite C's lack of consistency
  177387. * about rounding negative values in integer division...
  177388. */
  177389. odither[j][k] = (int) (num<0 ? -((-num)/den) : num/den);
  177390. }
  177391. }
  177392. return odither;
  177393. }
  177394. /*
  177395. * Create the ordered-dither tables.
  177396. * Components having the same number of representative colors may
  177397. * share a dither table.
  177398. */
  177399. LOCAL(void)
  177400. create_odither_tables (j_decompress_ptr cinfo)
  177401. {
  177402. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177403. ODITHER_MATRIX_PTR odither;
  177404. int i, j, nci;
  177405. for (i = 0; i < cinfo->out_color_components; i++) {
  177406. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  177407. odither = NULL; /* search for matching prior component */
  177408. for (j = 0; j < i; j++) {
  177409. if (nci == cquantize->Ncolors[j]) {
  177410. odither = cquantize->odither[j];
  177411. break;
  177412. }
  177413. }
  177414. if (odither == NULL) /* need a new table? */
  177415. odither = make_odither_array(cinfo, nci);
  177416. cquantize->odither[i] = odither;
  177417. }
  177418. }
  177419. /*
  177420. * Map some rows of pixels to the output colormapped representation.
  177421. */
  177422. METHODDEF(void)
  177423. color_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177424. JSAMPARRAY output_buf, int num_rows)
  177425. /* General case, no dithering */
  177426. {
  177427. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177428. JSAMPARRAY colorindex = cquantize->colorindex;
  177429. register int pixcode, ci;
  177430. register JSAMPROW ptrin, ptrout;
  177431. int row;
  177432. JDIMENSION col;
  177433. JDIMENSION width = cinfo->output_width;
  177434. register int nc = cinfo->out_color_components;
  177435. for (row = 0; row < num_rows; row++) {
  177436. ptrin = input_buf[row];
  177437. ptrout = output_buf[row];
  177438. for (col = width; col > 0; col--) {
  177439. pixcode = 0;
  177440. for (ci = 0; ci < nc; ci++) {
  177441. pixcode += GETJSAMPLE(colorindex[ci][GETJSAMPLE(*ptrin++)]);
  177442. }
  177443. *ptrout++ = (JSAMPLE) pixcode;
  177444. }
  177445. }
  177446. }
  177447. METHODDEF(void)
  177448. color_quantize3 (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177449. JSAMPARRAY output_buf, int num_rows)
  177450. /* Fast path for out_color_components==3, no dithering */
  177451. {
  177452. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177453. register int pixcode;
  177454. register JSAMPROW ptrin, ptrout;
  177455. JSAMPROW colorindex0 = cquantize->colorindex[0];
  177456. JSAMPROW colorindex1 = cquantize->colorindex[1];
  177457. JSAMPROW colorindex2 = cquantize->colorindex[2];
  177458. int row;
  177459. JDIMENSION col;
  177460. JDIMENSION width = cinfo->output_width;
  177461. for (row = 0; row < num_rows; row++) {
  177462. ptrin = input_buf[row];
  177463. ptrout = output_buf[row];
  177464. for (col = width; col > 0; col--) {
  177465. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*ptrin++)]);
  177466. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*ptrin++)]);
  177467. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*ptrin++)]);
  177468. *ptrout++ = (JSAMPLE) pixcode;
  177469. }
  177470. }
  177471. }
  177472. METHODDEF(void)
  177473. quantize_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177474. JSAMPARRAY output_buf, int num_rows)
  177475. /* General case, with ordered dithering */
  177476. {
  177477. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177478. register JSAMPROW input_ptr;
  177479. register JSAMPROW output_ptr;
  177480. JSAMPROW colorindex_ci;
  177481. int * dither; /* points to active row of dither matrix */
  177482. int row_index, col_index; /* current indexes into dither matrix */
  177483. int nc = cinfo->out_color_components;
  177484. int ci;
  177485. int row;
  177486. JDIMENSION col;
  177487. JDIMENSION width = cinfo->output_width;
  177488. for (row = 0; row < num_rows; row++) {
  177489. /* Initialize output values to 0 so can process components separately */
  177490. jzero_far((void FAR *) output_buf[row],
  177491. (size_t) (width * SIZEOF(JSAMPLE)));
  177492. row_index = cquantize->row_index;
  177493. for (ci = 0; ci < nc; ci++) {
  177494. input_ptr = input_buf[row] + ci;
  177495. output_ptr = output_buf[row];
  177496. colorindex_ci = cquantize->colorindex[ci];
  177497. dither = cquantize->odither[ci][row_index];
  177498. col_index = 0;
  177499. for (col = width; col > 0; col--) {
  177500. /* Form pixel value + dither, range-limit to 0..MAXJSAMPLE,
  177501. * select output value, accumulate into output code for this pixel.
  177502. * Range-limiting need not be done explicitly, as we have extended
  177503. * the colorindex table to produce the right answers for out-of-range
  177504. * inputs. The maximum dither is +- MAXJSAMPLE; this sets the
  177505. * required amount of padding.
  177506. */
  177507. *output_ptr += colorindex_ci[GETJSAMPLE(*input_ptr)+dither[col_index]];
  177508. input_ptr += nc;
  177509. output_ptr++;
  177510. col_index = (col_index + 1) & ODITHER_MASK;
  177511. }
  177512. }
  177513. /* Advance row index for next row */
  177514. row_index = (row_index + 1) & ODITHER_MASK;
  177515. cquantize->row_index = row_index;
  177516. }
  177517. }
  177518. METHODDEF(void)
  177519. quantize3_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177520. JSAMPARRAY output_buf, int num_rows)
  177521. /* Fast path for out_color_components==3, with ordered dithering */
  177522. {
  177523. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177524. register int pixcode;
  177525. register JSAMPROW input_ptr;
  177526. register JSAMPROW output_ptr;
  177527. JSAMPROW colorindex0 = cquantize->colorindex[0];
  177528. JSAMPROW colorindex1 = cquantize->colorindex[1];
  177529. JSAMPROW colorindex2 = cquantize->colorindex[2];
  177530. int * dither0; /* points to active row of dither matrix */
  177531. int * dither1;
  177532. int * dither2;
  177533. int row_index, col_index; /* current indexes into dither matrix */
  177534. int row;
  177535. JDIMENSION col;
  177536. JDIMENSION width = cinfo->output_width;
  177537. for (row = 0; row < num_rows; row++) {
  177538. row_index = cquantize->row_index;
  177539. input_ptr = input_buf[row];
  177540. output_ptr = output_buf[row];
  177541. dither0 = cquantize->odither[0][row_index];
  177542. dither1 = cquantize->odither[1][row_index];
  177543. dither2 = cquantize->odither[2][row_index];
  177544. col_index = 0;
  177545. for (col = width; col > 0; col--) {
  177546. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*input_ptr++) +
  177547. dither0[col_index]]);
  177548. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*input_ptr++) +
  177549. dither1[col_index]]);
  177550. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*input_ptr++) +
  177551. dither2[col_index]]);
  177552. *output_ptr++ = (JSAMPLE) pixcode;
  177553. col_index = (col_index + 1) & ODITHER_MASK;
  177554. }
  177555. row_index = (row_index + 1) & ODITHER_MASK;
  177556. cquantize->row_index = row_index;
  177557. }
  177558. }
  177559. METHODDEF(void)
  177560. quantize_fs_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177561. JSAMPARRAY output_buf, int num_rows)
  177562. /* General case, with Floyd-Steinberg dithering */
  177563. {
  177564. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177565. register LOCFSERROR cur; /* current error or pixel value */
  177566. LOCFSERROR belowerr; /* error for pixel below cur */
  177567. LOCFSERROR bpreverr; /* error for below/prev col */
  177568. LOCFSERROR bnexterr; /* error for below/next col */
  177569. LOCFSERROR delta;
  177570. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  177571. register JSAMPROW input_ptr;
  177572. register JSAMPROW output_ptr;
  177573. JSAMPROW colorindex_ci;
  177574. JSAMPROW colormap_ci;
  177575. int pixcode;
  177576. int nc = cinfo->out_color_components;
  177577. int dir; /* 1 for left-to-right, -1 for right-to-left */
  177578. int dirnc; /* dir * nc */
  177579. int ci;
  177580. int row;
  177581. JDIMENSION col;
  177582. JDIMENSION width = cinfo->output_width;
  177583. JSAMPLE *range_limit = cinfo->sample_range_limit;
  177584. SHIFT_TEMPS
  177585. for (row = 0; row < num_rows; row++) {
  177586. /* Initialize output values to 0 so can process components separately */
  177587. jzero_far((void FAR *) output_buf[row],
  177588. (size_t) (width * SIZEOF(JSAMPLE)));
  177589. for (ci = 0; ci < nc; ci++) {
  177590. input_ptr = input_buf[row] + ci;
  177591. output_ptr = output_buf[row];
  177592. if (cquantize->on_odd_row) {
  177593. /* work right to left in this row */
  177594. input_ptr += (width-1) * nc; /* so point to rightmost pixel */
  177595. output_ptr += width-1;
  177596. dir = -1;
  177597. dirnc = -nc;
  177598. errorptr = cquantize->fserrors[ci] + (width+1); /* => entry after last column */
  177599. } else {
  177600. /* work left to right in this row */
  177601. dir = 1;
  177602. dirnc = nc;
  177603. errorptr = cquantize->fserrors[ci]; /* => entry before first column */
  177604. }
  177605. colorindex_ci = cquantize->colorindex[ci];
  177606. colormap_ci = cquantize->sv_colormap[ci];
  177607. /* Preset error values: no error propagated to first pixel from left */
  177608. cur = 0;
  177609. /* and no error propagated to row below yet */
  177610. belowerr = bpreverr = 0;
  177611. for (col = width; col > 0; col--) {
  177612. /* cur holds the error propagated from the previous pixel on the
  177613. * current line. Add the error propagated from the previous line
  177614. * to form the complete error correction term for this pixel, and
  177615. * round the error term (which is expressed * 16) to an integer.
  177616. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  177617. * for either sign of the error value.
  177618. * Note: errorptr points to *previous* column's array entry.
  177619. */
  177620. cur = RIGHT_SHIFT(cur + errorptr[dir] + 8, 4);
  177621. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  177622. * The maximum error is +- MAXJSAMPLE; this sets the required size
  177623. * of the range_limit array.
  177624. */
  177625. cur += GETJSAMPLE(*input_ptr);
  177626. cur = GETJSAMPLE(range_limit[cur]);
  177627. /* Select output value, accumulate into output code for this pixel */
  177628. pixcode = GETJSAMPLE(colorindex_ci[cur]);
  177629. *output_ptr += (JSAMPLE) pixcode;
  177630. /* Compute actual representation error at this pixel */
  177631. /* Note: we can do this even though we don't have the final */
  177632. /* pixel code, because the colormap is orthogonal. */
  177633. cur -= GETJSAMPLE(colormap_ci[pixcode]);
  177634. /* Compute error fractions to be propagated to adjacent pixels.
  177635. * Add these into the running sums, and simultaneously shift the
  177636. * next-line error sums left by 1 column.
  177637. */
  177638. bnexterr = cur;
  177639. delta = cur * 2;
  177640. cur += delta; /* form error * 3 */
  177641. errorptr[0] = (FSERROR) (bpreverr + cur);
  177642. cur += delta; /* form error * 5 */
  177643. bpreverr = belowerr + cur;
  177644. belowerr = bnexterr;
  177645. cur += delta; /* form error * 7 */
  177646. /* At this point cur contains the 7/16 error value to be propagated
  177647. * to the next pixel on the current line, and all the errors for the
  177648. * next line have been shifted over. We are therefore ready to move on.
  177649. */
  177650. input_ptr += dirnc; /* advance input ptr to next column */
  177651. output_ptr += dir; /* advance output ptr to next column */
  177652. errorptr += dir; /* advance errorptr to current column */
  177653. }
  177654. /* Post-loop cleanup: we must unload the final error value into the
  177655. * final fserrors[] entry. Note we need not unload belowerr because
  177656. * it is for the dummy column before or after the actual array.
  177657. */
  177658. errorptr[0] = (FSERROR) bpreverr; /* unload prev err into array */
  177659. }
  177660. cquantize->on_odd_row = (cquantize->on_odd_row ? FALSE : TRUE);
  177661. }
  177662. }
  177663. /*
  177664. * Allocate workspace for Floyd-Steinberg errors.
  177665. */
  177666. LOCAL(void)
  177667. alloc_fs_workspace (j_decompress_ptr cinfo)
  177668. {
  177669. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177670. size_t arraysize;
  177671. int i;
  177672. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  177673. for (i = 0; i < cinfo->out_color_components; i++) {
  177674. cquantize->fserrors[i] = (FSERRPTR)
  177675. (*cinfo->mem->alloc_large)((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  177676. }
  177677. }
  177678. /*
  177679. * Initialize for one-pass color quantization.
  177680. */
  177681. METHODDEF(void)
  177682. start_pass_1_quant (j_decompress_ptr cinfo, boolean)
  177683. {
  177684. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177685. size_t arraysize;
  177686. int i;
  177687. /* Install my colormap. */
  177688. cinfo->colormap = cquantize->sv_colormap;
  177689. cinfo->actual_number_of_colors = cquantize->sv_actual;
  177690. /* Initialize for desired dithering mode. */
  177691. switch (cinfo->dither_mode) {
  177692. case JDITHER_NONE:
  177693. if (cinfo->out_color_components == 3)
  177694. cquantize->pub.color_quantize = color_quantize3;
  177695. else
  177696. cquantize->pub.color_quantize = color_quantize;
  177697. break;
  177698. case JDITHER_ORDERED:
  177699. if (cinfo->out_color_components == 3)
  177700. cquantize->pub.color_quantize = quantize3_ord_dither;
  177701. else
  177702. cquantize->pub.color_quantize = quantize_ord_dither;
  177703. cquantize->row_index = 0; /* initialize state for ordered dither */
  177704. /* If user changed to ordered dither from another mode,
  177705. * we must recreate the color index table with padding.
  177706. * This will cost extra space, but probably isn't very likely.
  177707. */
  177708. if (! cquantize->is_padded)
  177709. create_colorindex(cinfo);
  177710. /* Create ordered-dither tables if we didn't already. */
  177711. if (cquantize->odither[0] == NULL)
  177712. create_odither_tables(cinfo);
  177713. break;
  177714. case JDITHER_FS:
  177715. cquantize->pub.color_quantize = quantize_fs_dither;
  177716. cquantize->on_odd_row = FALSE; /* initialize state for F-S dither */
  177717. /* Allocate Floyd-Steinberg workspace if didn't already. */
  177718. if (cquantize->fserrors[0] == NULL)
  177719. alloc_fs_workspace(cinfo);
  177720. /* Initialize the propagated errors to zero. */
  177721. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  177722. for (i = 0; i < cinfo->out_color_components; i++)
  177723. jzero_far((void FAR *) cquantize->fserrors[i], arraysize);
  177724. break;
  177725. default:
  177726. ERREXIT(cinfo, JERR_NOT_COMPILED);
  177727. break;
  177728. }
  177729. }
  177730. /*
  177731. * Finish up at the end of the pass.
  177732. */
  177733. METHODDEF(void)
  177734. finish_pass_1_quant (j_decompress_ptr)
  177735. {
  177736. /* no work in 1-pass case */
  177737. }
  177738. /*
  177739. * Switch to a new external colormap between output passes.
  177740. * Shouldn't get to this module!
  177741. */
  177742. METHODDEF(void)
  177743. new_color_map_1_quant (j_decompress_ptr cinfo)
  177744. {
  177745. ERREXIT(cinfo, JERR_MODE_CHANGE);
  177746. }
  177747. /*
  177748. * Module initialization routine for 1-pass color quantization.
  177749. */
  177750. GLOBAL(void)
  177751. jinit_1pass_quantizer (j_decompress_ptr cinfo)
  177752. {
  177753. my_cquantize_ptr cquantize;
  177754. cquantize = (my_cquantize_ptr)
  177755. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177756. SIZEOF(my_cquantizer));
  177757. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  177758. cquantize->pub.start_pass = start_pass_1_quant;
  177759. cquantize->pub.finish_pass = finish_pass_1_quant;
  177760. cquantize->pub.new_color_map = new_color_map_1_quant;
  177761. cquantize->fserrors[0] = NULL; /* Flag FS workspace not allocated */
  177762. cquantize->odither[0] = NULL; /* Also flag odither arrays not allocated */
  177763. /* Make sure my internal arrays won't overflow */
  177764. if (cinfo->out_color_components > MAX_Q_COMPS)
  177765. ERREXIT1(cinfo, JERR_QUANT_COMPONENTS, MAX_Q_COMPS);
  177766. /* Make sure colormap indexes can be represented by JSAMPLEs */
  177767. if (cinfo->desired_number_of_colors > (MAXJSAMPLE+1))
  177768. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXJSAMPLE+1);
  177769. /* Create the colormap and color index table. */
  177770. create_colormap(cinfo);
  177771. create_colorindex(cinfo);
  177772. /* Allocate Floyd-Steinberg workspace now if requested.
  177773. * We do this now since it is FAR storage and may affect the memory
  177774. * manager's space calculations. If the user changes to FS dither
  177775. * mode in a later pass, we will allocate the space then, and will
  177776. * possibly overrun the max_memory_to_use setting.
  177777. */
  177778. if (cinfo->dither_mode == JDITHER_FS)
  177779. alloc_fs_workspace(cinfo);
  177780. }
  177781. #endif /* QUANT_1PASS_SUPPORTED */
  177782. /*** End of inlined file: jquant1.c ***/
  177783. /*** Start of inlined file: jquant2.c ***/
  177784. #define JPEG_INTERNALS
  177785. #ifdef QUANT_2PASS_SUPPORTED
  177786. /*
  177787. * This module implements the well-known Heckbert paradigm for color
  177788. * quantization. Most of the ideas used here can be traced back to
  177789. * Heckbert's seminal paper
  177790. * Heckbert, Paul. "Color Image Quantization for Frame Buffer Display",
  177791. * Proc. SIGGRAPH '82, Computer Graphics v.16 #3 (July 1982), pp 297-304.
  177792. *
  177793. * In the first pass over the image, we accumulate a histogram showing the
  177794. * usage count of each possible color. To keep the histogram to a reasonable
  177795. * size, we reduce the precision of the input; typical practice is to retain
  177796. * 5 or 6 bits per color, so that 8 or 4 different input values are counted
  177797. * in the same histogram cell.
  177798. *
  177799. * Next, the color-selection step begins with a box representing the whole
  177800. * color space, and repeatedly splits the "largest" remaining box until we
  177801. * have as many boxes as desired colors. Then the mean color in each
  177802. * remaining box becomes one of the possible output colors.
  177803. *
  177804. * The second pass over the image maps each input pixel to the closest output
  177805. * color (optionally after applying a Floyd-Steinberg dithering correction).
  177806. * This mapping is logically trivial, but making it go fast enough requires
  177807. * considerable care.
  177808. *
  177809. * Heckbert-style quantizers vary a good deal in their policies for choosing
  177810. * the "largest" box and deciding where to cut it. The particular policies
  177811. * used here have proved out well in experimental comparisons, but better ones
  177812. * may yet be found.
  177813. *
  177814. * In earlier versions of the IJG code, this module quantized in YCbCr color
  177815. * space, processing the raw upsampled data without a color conversion step.
  177816. * This allowed the color conversion math to be done only once per colormap
  177817. * entry, not once per pixel. However, that optimization precluded other
  177818. * useful optimizations (such as merging color conversion with upsampling)
  177819. * and it also interfered with desired capabilities such as quantizing to an
  177820. * externally-supplied colormap. We have therefore abandoned that approach.
  177821. * The present code works in the post-conversion color space, typically RGB.
  177822. *
  177823. * To improve the visual quality of the results, we actually work in scaled
  177824. * RGB space, giving G distances more weight than R, and R in turn more than
  177825. * B. To do everything in integer math, we must use integer scale factors.
  177826. * The 2/3/1 scale factors used here correspond loosely to the relative
  177827. * weights of the colors in the NTSC grayscale equation.
  177828. * If you want to use this code to quantize a non-RGB color space, you'll
  177829. * probably need to change these scale factors.
  177830. */
  177831. #define R_SCALE 2 /* scale R distances by this much */
  177832. #define G_SCALE 3 /* scale G distances by this much */
  177833. #define B_SCALE 1 /* and B by this much */
  177834. /* Relabel R/G/B as components 0/1/2, respecting the RGB ordering defined
  177835. * in jmorecfg.h. As the code stands, it will do the right thing for R,G,B
  177836. * and B,G,R orders. If you define some other weird order in jmorecfg.h,
  177837. * you'll get compile errors until you extend this logic. In that case
  177838. * you'll probably want to tweak the histogram sizes too.
  177839. */
  177840. #if RGB_RED == 0
  177841. #define C0_SCALE R_SCALE
  177842. #endif
  177843. #if RGB_BLUE == 0
  177844. #define C0_SCALE B_SCALE
  177845. #endif
  177846. #if RGB_GREEN == 1
  177847. #define C1_SCALE G_SCALE
  177848. #endif
  177849. #if RGB_RED == 2
  177850. #define C2_SCALE R_SCALE
  177851. #endif
  177852. #if RGB_BLUE == 2
  177853. #define C2_SCALE B_SCALE
  177854. #endif
  177855. /*
  177856. * First we have the histogram data structure and routines for creating it.
  177857. *
  177858. * The number of bits of precision can be adjusted by changing these symbols.
  177859. * We recommend keeping 6 bits for G and 5 each for R and B.
  177860. * If you have plenty of memory and cycles, 6 bits all around gives marginally
  177861. * better results; if you are short of memory, 5 bits all around will save
  177862. * some space but degrade the results.
  177863. * To maintain a fully accurate histogram, we'd need to allocate a "long"
  177864. * (preferably unsigned long) for each cell. In practice this is overkill;
  177865. * we can get by with 16 bits per cell. Few of the cell counts will overflow,
  177866. * and clamping those that do overflow to the maximum value will give close-
  177867. * enough results. This reduces the recommended histogram size from 256Kb
  177868. * to 128Kb, which is a useful savings on PC-class machines.
  177869. * (In the second pass the histogram space is re-used for pixel mapping data;
  177870. * in that capacity, each cell must be able to store zero to the number of
  177871. * desired colors. 16 bits/cell is plenty for that too.)
  177872. * Since the JPEG code is intended to run in small memory model on 80x86
  177873. * machines, we can't just allocate the histogram in one chunk. Instead
  177874. * of a true 3-D array, we use a row of pointers to 2-D arrays. Each
  177875. * pointer corresponds to a C0 value (typically 2^5 = 32 pointers) and
  177876. * each 2-D array has 2^6*2^5 = 2048 or 2^6*2^6 = 4096 entries. Note that
  177877. * on 80x86 machines, the pointer row is in near memory but the actual
  177878. * arrays are in far memory (same arrangement as we use for image arrays).
  177879. */
  177880. #define MAXNUMCOLORS (MAXJSAMPLE+1) /* maximum size of colormap */
  177881. /* These will do the right thing for either R,G,B or B,G,R color order,
  177882. * but you may not like the results for other color orders.
  177883. */
  177884. #define HIST_C0_BITS 5 /* bits of precision in R/B histogram */
  177885. #define HIST_C1_BITS 6 /* bits of precision in G histogram */
  177886. #define HIST_C2_BITS 5 /* bits of precision in B/R histogram */
  177887. /* Number of elements along histogram axes. */
  177888. #define HIST_C0_ELEMS (1<<HIST_C0_BITS)
  177889. #define HIST_C1_ELEMS (1<<HIST_C1_BITS)
  177890. #define HIST_C2_ELEMS (1<<HIST_C2_BITS)
  177891. /* These are the amounts to shift an input value to get a histogram index. */
  177892. #define C0_SHIFT (BITS_IN_JSAMPLE-HIST_C0_BITS)
  177893. #define C1_SHIFT (BITS_IN_JSAMPLE-HIST_C1_BITS)
  177894. #define C2_SHIFT (BITS_IN_JSAMPLE-HIST_C2_BITS)
  177895. typedef UINT16 histcell; /* histogram cell; prefer an unsigned type */
  177896. typedef histcell FAR * histptr; /* for pointers to histogram cells */
  177897. typedef histcell hist1d[HIST_C2_ELEMS]; /* typedefs for the array */
  177898. typedef hist1d FAR * hist2d; /* type for the 2nd-level pointers */
  177899. typedef hist2d * hist3d; /* type for top-level pointer */
  177900. /* Declarations for Floyd-Steinberg dithering.
  177901. *
  177902. * Errors are accumulated into the array fserrors[], at a resolution of
  177903. * 1/16th of a pixel count. The error at a given pixel is propagated
  177904. * to its not-yet-processed neighbors using the standard F-S fractions,
  177905. * ... (here) 7/16
  177906. * 3/16 5/16 1/16
  177907. * We work left-to-right on even rows, right-to-left on odd rows.
  177908. *
  177909. * We can get away with a single array (holding one row's worth of errors)
  177910. * by using it to store the current row's errors at pixel columns not yet
  177911. * processed, but the next row's errors at columns already processed. We
  177912. * need only a few extra variables to hold the errors immediately around the
  177913. * current column. (If we are lucky, those variables are in registers, but
  177914. * even if not, they're probably cheaper to access than array elements are.)
  177915. *
  177916. * The fserrors[] array has (#columns + 2) entries; the extra entry at
  177917. * each end saves us from special-casing the first and last pixels.
  177918. * Each entry is three values long, one value for each color component.
  177919. *
  177920. * Note: on a wide image, we might not have enough room in a PC's near data
  177921. * segment to hold the error array; so it is allocated with alloc_large.
  177922. */
  177923. #if BITS_IN_JSAMPLE == 8
  177924. typedef INT16 FSERROR; /* 16 bits should be enough */
  177925. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  177926. #else
  177927. typedef INT32 FSERROR; /* may need more than 16 bits */
  177928. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  177929. #endif
  177930. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  177931. /* Private subobject */
  177932. typedef struct {
  177933. struct jpeg_color_quantizer pub; /* public fields */
  177934. /* Space for the eventually created colormap is stashed here */
  177935. JSAMPARRAY sv_colormap; /* colormap allocated at init time */
  177936. int desired; /* desired # of colors = size of colormap */
  177937. /* Variables for accumulating image statistics */
  177938. hist3d histogram; /* pointer to the histogram */
  177939. boolean needs_zeroed; /* TRUE if next pass must zero histogram */
  177940. /* Variables for Floyd-Steinberg dithering */
  177941. FSERRPTR fserrors; /* accumulated errors */
  177942. boolean on_odd_row; /* flag to remember which row we are on */
  177943. int * error_limiter; /* table for clamping the applied error */
  177944. } my_cquantizer2;
  177945. typedef my_cquantizer2 * my_cquantize_ptr2;
  177946. /*
  177947. * Prescan some rows of pixels.
  177948. * In this module the prescan simply updates the histogram, which has been
  177949. * initialized to zeroes by start_pass.
  177950. * An output_buf parameter is required by the method signature, but no data
  177951. * is actually output (in fact the buffer controller is probably passing a
  177952. * NULL pointer).
  177953. */
  177954. METHODDEF(void)
  177955. prescan_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177956. JSAMPARRAY, int num_rows)
  177957. {
  177958. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177959. register JSAMPROW ptr;
  177960. register histptr histp;
  177961. register hist3d histogram = cquantize->histogram;
  177962. int row;
  177963. JDIMENSION col;
  177964. JDIMENSION width = cinfo->output_width;
  177965. for (row = 0; row < num_rows; row++) {
  177966. ptr = input_buf[row];
  177967. for (col = width; col > 0; col--) {
  177968. /* get pixel value and index into the histogram */
  177969. histp = & histogram[GETJSAMPLE(ptr[0]) >> C0_SHIFT]
  177970. [GETJSAMPLE(ptr[1]) >> C1_SHIFT]
  177971. [GETJSAMPLE(ptr[2]) >> C2_SHIFT];
  177972. /* increment, check for overflow and undo increment if so. */
  177973. if (++(*histp) <= 0)
  177974. (*histp)--;
  177975. ptr += 3;
  177976. }
  177977. }
  177978. }
  177979. /*
  177980. * Next we have the really interesting routines: selection of a colormap
  177981. * given the completed histogram.
  177982. * These routines work with a list of "boxes", each representing a rectangular
  177983. * subset of the input color space (to histogram precision).
  177984. */
  177985. typedef struct {
  177986. /* The bounds of the box (inclusive); expressed as histogram indexes */
  177987. int c0min, c0max;
  177988. int c1min, c1max;
  177989. int c2min, c2max;
  177990. /* The volume (actually 2-norm) of the box */
  177991. INT32 volume;
  177992. /* The number of nonzero histogram cells within this box */
  177993. long colorcount;
  177994. } box;
  177995. typedef box * boxptr;
  177996. LOCAL(boxptr)
  177997. find_biggest_color_pop (boxptr boxlist, int numboxes)
  177998. /* Find the splittable box with the largest color population */
  177999. /* Returns NULL if no splittable boxes remain */
  178000. {
  178001. register boxptr boxp;
  178002. register int i;
  178003. register long maxc = 0;
  178004. boxptr which = NULL;
  178005. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  178006. if (boxp->colorcount > maxc && boxp->volume > 0) {
  178007. which = boxp;
  178008. maxc = boxp->colorcount;
  178009. }
  178010. }
  178011. return which;
  178012. }
  178013. LOCAL(boxptr)
  178014. find_biggest_volume (boxptr boxlist, int numboxes)
  178015. /* Find the splittable box with the largest (scaled) volume */
  178016. /* Returns NULL if no splittable boxes remain */
  178017. {
  178018. register boxptr boxp;
  178019. register int i;
  178020. register INT32 maxv = 0;
  178021. boxptr which = NULL;
  178022. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  178023. if (boxp->volume > maxv) {
  178024. which = boxp;
  178025. maxv = boxp->volume;
  178026. }
  178027. }
  178028. return which;
  178029. }
  178030. LOCAL(void)
  178031. update_box (j_decompress_ptr cinfo, boxptr boxp)
  178032. /* Shrink the min/max bounds of a box to enclose only nonzero elements, */
  178033. /* and recompute its volume and population */
  178034. {
  178035. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178036. hist3d histogram = cquantize->histogram;
  178037. histptr histp;
  178038. int c0,c1,c2;
  178039. int c0min,c0max,c1min,c1max,c2min,c2max;
  178040. INT32 dist0,dist1,dist2;
  178041. long ccount;
  178042. c0min = boxp->c0min; c0max = boxp->c0max;
  178043. c1min = boxp->c1min; c1max = boxp->c1max;
  178044. c2min = boxp->c2min; c2max = boxp->c2max;
  178045. if (c0max > c0min)
  178046. for (c0 = c0min; c0 <= c0max; c0++)
  178047. for (c1 = c1min; c1 <= c1max; c1++) {
  178048. histp = & histogram[c0][c1][c2min];
  178049. for (c2 = c2min; c2 <= c2max; c2++)
  178050. if (*histp++ != 0) {
  178051. boxp->c0min = c0min = c0;
  178052. goto have_c0min;
  178053. }
  178054. }
  178055. have_c0min:
  178056. if (c0max > c0min)
  178057. for (c0 = c0max; c0 >= c0min; c0--)
  178058. for (c1 = c1min; c1 <= c1max; c1++) {
  178059. histp = & histogram[c0][c1][c2min];
  178060. for (c2 = c2min; c2 <= c2max; c2++)
  178061. if (*histp++ != 0) {
  178062. boxp->c0max = c0max = c0;
  178063. goto have_c0max;
  178064. }
  178065. }
  178066. have_c0max:
  178067. if (c1max > c1min)
  178068. for (c1 = c1min; c1 <= c1max; c1++)
  178069. for (c0 = c0min; c0 <= c0max; c0++) {
  178070. histp = & histogram[c0][c1][c2min];
  178071. for (c2 = c2min; c2 <= c2max; c2++)
  178072. if (*histp++ != 0) {
  178073. boxp->c1min = c1min = c1;
  178074. goto have_c1min;
  178075. }
  178076. }
  178077. have_c1min:
  178078. if (c1max > c1min)
  178079. for (c1 = c1max; c1 >= c1min; c1--)
  178080. for (c0 = c0min; c0 <= c0max; c0++) {
  178081. histp = & histogram[c0][c1][c2min];
  178082. for (c2 = c2min; c2 <= c2max; c2++)
  178083. if (*histp++ != 0) {
  178084. boxp->c1max = c1max = c1;
  178085. goto have_c1max;
  178086. }
  178087. }
  178088. have_c1max:
  178089. if (c2max > c2min)
  178090. for (c2 = c2min; c2 <= c2max; c2++)
  178091. for (c0 = c0min; c0 <= c0max; c0++) {
  178092. histp = & histogram[c0][c1min][c2];
  178093. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  178094. if (*histp != 0) {
  178095. boxp->c2min = c2min = c2;
  178096. goto have_c2min;
  178097. }
  178098. }
  178099. have_c2min:
  178100. if (c2max > c2min)
  178101. for (c2 = c2max; c2 >= c2min; c2--)
  178102. for (c0 = c0min; c0 <= c0max; c0++) {
  178103. histp = & histogram[c0][c1min][c2];
  178104. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  178105. if (*histp != 0) {
  178106. boxp->c2max = c2max = c2;
  178107. goto have_c2max;
  178108. }
  178109. }
  178110. have_c2max:
  178111. /* Update box volume.
  178112. * We use 2-norm rather than real volume here; this biases the method
  178113. * against making long narrow boxes, and it has the side benefit that
  178114. * a box is splittable iff norm > 0.
  178115. * Since the differences are expressed in histogram-cell units,
  178116. * we have to shift back to JSAMPLE units to get consistent distances;
  178117. * after which, we scale according to the selected distance scale factors.
  178118. */
  178119. dist0 = ((c0max - c0min) << C0_SHIFT) * C0_SCALE;
  178120. dist1 = ((c1max - c1min) << C1_SHIFT) * C1_SCALE;
  178121. dist2 = ((c2max - c2min) << C2_SHIFT) * C2_SCALE;
  178122. boxp->volume = dist0*dist0 + dist1*dist1 + dist2*dist2;
  178123. /* Now scan remaining volume of box and compute population */
  178124. ccount = 0;
  178125. for (c0 = c0min; c0 <= c0max; c0++)
  178126. for (c1 = c1min; c1 <= c1max; c1++) {
  178127. histp = & histogram[c0][c1][c2min];
  178128. for (c2 = c2min; c2 <= c2max; c2++, histp++)
  178129. if (*histp != 0) {
  178130. ccount++;
  178131. }
  178132. }
  178133. boxp->colorcount = ccount;
  178134. }
  178135. LOCAL(int)
  178136. median_cut (j_decompress_ptr cinfo, boxptr boxlist, int numboxes,
  178137. int desired_colors)
  178138. /* Repeatedly select and split the largest box until we have enough boxes */
  178139. {
  178140. int n,lb;
  178141. int c0,c1,c2,cmax;
  178142. register boxptr b1,b2;
  178143. while (numboxes < desired_colors) {
  178144. /* Select box to split.
  178145. * Current algorithm: by population for first half, then by volume.
  178146. */
  178147. if (numboxes*2 <= desired_colors) {
  178148. b1 = find_biggest_color_pop(boxlist, numboxes);
  178149. } else {
  178150. b1 = find_biggest_volume(boxlist, numboxes);
  178151. }
  178152. if (b1 == NULL) /* no splittable boxes left! */
  178153. break;
  178154. b2 = &boxlist[numboxes]; /* where new box will go */
  178155. /* Copy the color bounds to the new box. */
  178156. b2->c0max = b1->c0max; b2->c1max = b1->c1max; b2->c2max = b1->c2max;
  178157. b2->c0min = b1->c0min; b2->c1min = b1->c1min; b2->c2min = b1->c2min;
  178158. /* Choose which axis to split the box on.
  178159. * Current algorithm: longest scaled axis.
  178160. * See notes in update_box about scaling distances.
  178161. */
  178162. c0 = ((b1->c0max - b1->c0min) << C0_SHIFT) * C0_SCALE;
  178163. c1 = ((b1->c1max - b1->c1min) << C1_SHIFT) * C1_SCALE;
  178164. c2 = ((b1->c2max - b1->c2min) << C2_SHIFT) * C2_SCALE;
  178165. /* We want to break any ties in favor of green, then red, blue last.
  178166. * This code does the right thing for R,G,B or B,G,R color orders only.
  178167. */
  178168. #if RGB_RED == 0
  178169. cmax = c1; n = 1;
  178170. if (c0 > cmax) { cmax = c0; n = 0; }
  178171. if (c2 > cmax) { n = 2; }
  178172. #else
  178173. cmax = c1; n = 1;
  178174. if (c2 > cmax) { cmax = c2; n = 2; }
  178175. if (c0 > cmax) { n = 0; }
  178176. #endif
  178177. /* Choose split point along selected axis, and update box bounds.
  178178. * Current algorithm: split at halfway point.
  178179. * (Since the box has been shrunk to minimum volume,
  178180. * any split will produce two nonempty subboxes.)
  178181. * Note that lb value is max for lower box, so must be < old max.
  178182. */
  178183. switch (n) {
  178184. case 0:
  178185. lb = (b1->c0max + b1->c0min) / 2;
  178186. b1->c0max = lb;
  178187. b2->c0min = lb+1;
  178188. break;
  178189. case 1:
  178190. lb = (b1->c1max + b1->c1min) / 2;
  178191. b1->c1max = lb;
  178192. b2->c1min = lb+1;
  178193. break;
  178194. case 2:
  178195. lb = (b1->c2max + b1->c2min) / 2;
  178196. b1->c2max = lb;
  178197. b2->c2min = lb+1;
  178198. break;
  178199. }
  178200. /* Update stats for boxes */
  178201. update_box(cinfo, b1);
  178202. update_box(cinfo, b2);
  178203. numboxes++;
  178204. }
  178205. return numboxes;
  178206. }
  178207. LOCAL(void)
  178208. compute_color (j_decompress_ptr cinfo, boxptr boxp, int icolor)
  178209. /* Compute representative color for a box, put it in colormap[icolor] */
  178210. {
  178211. /* Current algorithm: mean weighted by pixels (not colors) */
  178212. /* Note it is important to get the rounding correct! */
  178213. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178214. hist3d histogram = cquantize->histogram;
  178215. histptr histp;
  178216. int c0,c1,c2;
  178217. int c0min,c0max,c1min,c1max,c2min,c2max;
  178218. long count;
  178219. long total = 0;
  178220. long c0total = 0;
  178221. long c1total = 0;
  178222. long c2total = 0;
  178223. c0min = boxp->c0min; c0max = boxp->c0max;
  178224. c1min = boxp->c1min; c1max = boxp->c1max;
  178225. c2min = boxp->c2min; c2max = boxp->c2max;
  178226. for (c0 = c0min; c0 <= c0max; c0++)
  178227. for (c1 = c1min; c1 <= c1max; c1++) {
  178228. histp = & histogram[c0][c1][c2min];
  178229. for (c2 = c2min; c2 <= c2max; c2++) {
  178230. if ((count = *histp++) != 0) {
  178231. total += count;
  178232. c0total += ((c0 << C0_SHIFT) + ((1<<C0_SHIFT)>>1)) * count;
  178233. c1total += ((c1 << C1_SHIFT) + ((1<<C1_SHIFT)>>1)) * count;
  178234. c2total += ((c2 << C2_SHIFT) + ((1<<C2_SHIFT)>>1)) * count;
  178235. }
  178236. }
  178237. }
  178238. cinfo->colormap[0][icolor] = (JSAMPLE) ((c0total + (total>>1)) / total);
  178239. cinfo->colormap[1][icolor] = (JSAMPLE) ((c1total + (total>>1)) / total);
  178240. cinfo->colormap[2][icolor] = (JSAMPLE) ((c2total + (total>>1)) / total);
  178241. }
  178242. LOCAL(void)
  178243. select_colors (j_decompress_ptr cinfo, int desired_colors)
  178244. /* Master routine for color selection */
  178245. {
  178246. boxptr boxlist;
  178247. int numboxes;
  178248. int i;
  178249. /* Allocate workspace for box list */
  178250. boxlist = (boxptr) (*cinfo->mem->alloc_small)
  178251. ((j_common_ptr) cinfo, JPOOL_IMAGE, desired_colors * SIZEOF(box));
  178252. /* Initialize one box containing whole space */
  178253. numboxes = 1;
  178254. boxlist[0].c0min = 0;
  178255. boxlist[0].c0max = MAXJSAMPLE >> C0_SHIFT;
  178256. boxlist[0].c1min = 0;
  178257. boxlist[0].c1max = MAXJSAMPLE >> C1_SHIFT;
  178258. boxlist[0].c2min = 0;
  178259. boxlist[0].c2max = MAXJSAMPLE >> C2_SHIFT;
  178260. /* Shrink it to actually-used volume and set its statistics */
  178261. update_box(cinfo, & boxlist[0]);
  178262. /* Perform median-cut to produce final box list */
  178263. numboxes = median_cut(cinfo, boxlist, numboxes, desired_colors);
  178264. /* Compute the representative color for each box, fill colormap */
  178265. for (i = 0; i < numboxes; i++)
  178266. compute_color(cinfo, & boxlist[i], i);
  178267. cinfo->actual_number_of_colors = numboxes;
  178268. TRACEMS1(cinfo, 1, JTRC_QUANT_SELECTED, numboxes);
  178269. }
  178270. /*
  178271. * These routines are concerned with the time-critical task of mapping input
  178272. * colors to the nearest color in the selected colormap.
  178273. *
  178274. * We re-use the histogram space as an "inverse color map", essentially a
  178275. * cache for the results of nearest-color searches. All colors within a
  178276. * histogram cell will be mapped to the same colormap entry, namely the one
  178277. * closest to the cell's center. This may not be quite the closest entry to
  178278. * the actual input color, but it's almost as good. A zero in the cache
  178279. * indicates we haven't found the nearest color for that cell yet; the array
  178280. * is cleared to zeroes before starting the mapping pass. When we find the
  178281. * nearest color for a cell, its colormap index plus one is recorded in the
  178282. * cache for future use. The pass2 scanning routines call fill_inverse_cmap
  178283. * when they need to use an unfilled entry in the cache.
  178284. *
  178285. * Our method of efficiently finding nearest colors is based on the "locally
  178286. * sorted search" idea described by Heckbert and on the incremental distance
  178287. * calculation described by Spencer W. Thomas in chapter III.1 of Graphics
  178288. * Gems II (James Arvo, ed. Academic Press, 1991). Thomas points out that
  178289. * the distances from a given colormap entry to each cell of the histogram can
  178290. * be computed quickly using an incremental method: the differences between
  178291. * distances to adjacent cells themselves differ by a constant. This allows a
  178292. * fairly fast implementation of the "brute force" approach of computing the
  178293. * distance from every colormap entry to every histogram cell. Unfortunately,
  178294. * it needs a work array to hold the best-distance-so-far for each histogram
  178295. * cell (because the inner loop has to be over cells, not colormap entries).
  178296. * The work array elements have to be INT32s, so the work array would need
  178297. * 256Kb at our recommended precision. This is not feasible in DOS machines.
  178298. *
  178299. * To get around these problems, we apply Thomas' method to compute the
  178300. * nearest colors for only the cells within a small subbox of the histogram.
  178301. * The work array need be only as big as the subbox, so the memory usage
  178302. * problem is solved. Furthermore, we need not fill subboxes that are never
  178303. * referenced in pass2; many images use only part of the color gamut, so a
  178304. * fair amount of work is saved. An additional advantage of this
  178305. * approach is that we can apply Heckbert's locality criterion to quickly
  178306. * eliminate colormap entries that are far away from the subbox; typically
  178307. * three-fourths of the colormap entries are rejected by Heckbert's criterion,
  178308. * and we need not compute their distances to individual cells in the subbox.
  178309. * The speed of this approach is heavily influenced by the subbox size: too
  178310. * small means too much overhead, too big loses because Heckbert's criterion
  178311. * can't eliminate as many colormap entries. Empirically the best subbox
  178312. * size seems to be about 1/512th of the histogram (1/8th in each direction).
  178313. *
  178314. * Thomas' article also describes a refined method which is asymptotically
  178315. * faster than the brute-force method, but it is also far more complex and
  178316. * cannot efficiently be applied to small subboxes. It is therefore not
  178317. * useful for programs intended to be portable to DOS machines. On machines
  178318. * with plenty of memory, filling the whole histogram in one shot with Thomas'
  178319. * refined method might be faster than the present code --- but then again,
  178320. * it might not be any faster, and it's certainly more complicated.
  178321. */
  178322. /* log2(histogram cells in update box) for each axis; this can be adjusted */
  178323. #define BOX_C0_LOG (HIST_C0_BITS-3)
  178324. #define BOX_C1_LOG (HIST_C1_BITS-3)
  178325. #define BOX_C2_LOG (HIST_C2_BITS-3)
  178326. #define BOX_C0_ELEMS (1<<BOX_C0_LOG) /* # of hist cells in update box */
  178327. #define BOX_C1_ELEMS (1<<BOX_C1_LOG)
  178328. #define BOX_C2_ELEMS (1<<BOX_C2_LOG)
  178329. #define BOX_C0_SHIFT (C0_SHIFT + BOX_C0_LOG)
  178330. #define BOX_C1_SHIFT (C1_SHIFT + BOX_C1_LOG)
  178331. #define BOX_C2_SHIFT (C2_SHIFT + BOX_C2_LOG)
  178332. /*
  178333. * The next three routines implement inverse colormap filling. They could
  178334. * all be folded into one big routine, but splitting them up this way saves
  178335. * some stack space (the mindist[] and bestdist[] arrays need not coexist)
  178336. * and may allow some compilers to produce better code by registerizing more
  178337. * inner-loop variables.
  178338. */
  178339. LOCAL(int)
  178340. find_nearby_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  178341. JSAMPLE colorlist[])
  178342. /* Locate the colormap entries close enough to an update box to be candidates
  178343. * for the nearest entry to some cell(s) in the update box. The update box
  178344. * is specified by the center coordinates of its first cell. The number of
  178345. * candidate colormap entries is returned, and their colormap indexes are
  178346. * placed in colorlist[].
  178347. * This routine uses Heckbert's "locally sorted search" criterion to select
  178348. * the colors that need further consideration.
  178349. */
  178350. {
  178351. int numcolors = cinfo->actual_number_of_colors;
  178352. int maxc0, maxc1, maxc2;
  178353. int centerc0, centerc1, centerc2;
  178354. int i, x, ncolors;
  178355. INT32 minmaxdist, min_dist, max_dist, tdist;
  178356. INT32 mindist[MAXNUMCOLORS]; /* min distance to colormap entry i */
  178357. /* Compute true coordinates of update box's upper corner and center.
  178358. * Actually we compute the coordinates of the center of the upper-corner
  178359. * histogram cell, which are the upper bounds of the volume we care about.
  178360. * Note that since ">>" rounds down, the "center" values may be closer to
  178361. * min than to max; hence comparisons to them must be "<=", not "<".
  178362. */
  178363. maxc0 = minc0 + ((1 << BOX_C0_SHIFT) - (1 << C0_SHIFT));
  178364. centerc0 = (minc0 + maxc0) >> 1;
  178365. maxc1 = minc1 + ((1 << BOX_C1_SHIFT) - (1 << C1_SHIFT));
  178366. centerc1 = (minc1 + maxc1) >> 1;
  178367. maxc2 = minc2 + ((1 << BOX_C2_SHIFT) - (1 << C2_SHIFT));
  178368. centerc2 = (minc2 + maxc2) >> 1;
  178369. /* For each color in colormap, find:
  178370. * 1. its minimum squared-distance to any point in the update box
  178371. * (zero if color is within update box);
  178372. * 2. its maximum squared-distance to any point in the update box.
  178373. * Both of these can be found by considering only the corners of the box.
  178374. * We save the minimum distance for each color in mindist[];
  178375. * only the smallest maximum distance is of interest.
  178376. */
  178377. minmaxdist = 0x7FFFFFFFL;
  178378. for (i = 0; i < numcolors; i++) {
  178379. /* We compute the squared-c0-distance term, then add in the other two. */
  178380. x = GETJSAMPLE(cinfo->colormap[0][i]);
  178381. if (x < minc0) {
  178382. tdist = (x - minc0) * C0_SCALE;
  178383. min_dist = tdist*tdist;
  178384. tdist = (x - maxc0) * C0_SCALE;
  178385. max_dist = tdist*tdist;
  178386. } else if (x > maxc0) {
  178387. tdist = (x - maxc0) * C0_SCALE;
  178388. min_dist = tdist*tdist;
  178389. tdist = (x - minc0) * C0_SCALE;
  178390. max_dist = tdist*tdist;
  178391. } else {
  178392. /* within cell range so no contribution to min_dist */
  178393. min_dist = 0;
  178394. if (x <= centerc0) {
  178395. tdist = (x - maxc0) * C0_SCALE;
  178396. max_dist = tdist*tdist;
  178397. } else {
  178398. tdist = (x - minc0) * C0_SCALE;
  178399. max_dist = tdist*tdist;
  178400. }
  178401. }
  178402. x = GETJSAMPLE(cinfo->colormap[1][i]);
  178403. if (x < minc1) {
  178404. tdist = (x - minc1) * C1_SCALE;
  178405. min_dist += tdist*tdist;
  178406. tdist = (x - maxc1) * C1_SCALE;
  178407. max_dist += tdist*tdist;
  178408. } else if (x > maxc1) {
  178409. tdist = (x - maxc1) * C1_SCALE;
  178410. min_dist += tdist*tdist;
  178411. tdist = (x - minc1) * C1_SCALE;
  178412. max_dist += tdist*tdist;
  178413. } else {
  178414. /* within cell range so no contribution to min_dist */
  178415. if (x <= centerc1) {
  178416. tdist = (x - maxc1) * C1_SCALE;
  178417. max_dist += tdist*tdist;
  178418. } else {
  178419. tdist = (x - minc1) * C1_SCALE;
  178420. max_dist += tdist*tdist;
  178421. }
  178422. }
  178423. x = GETJSAMPLE(cinfo->colormap[2][i]);
  178424. if (x < minc2) {
  178425. tdist = (x - minc2) * C2_SCALE;
  178426. min_dist += tdist*tdist;
  178427. tdist = (x - maxc2) * C2_SCALE;
  178428. max_dist += tdist*tdist;
  178429. } else if (x > maxc2) {
  178430. tdist = (x - maxc2) * C2_SCALE;
  178431. min_dist += tdist*tdist;
  178432. tdist = (x - minc2) * C2_SCALE;
  178433. max_dist += tdist*tdist;
  178434. } else {
  178435. /* within cell range so no contribution to min_dist */
  178436. if (x <= centerc2) {
  178437. tdist = (x - maxc2) * C2_SCALE;
  178438. max_dist += tdist*tdist;
  178439. } else {
  178440. tdist = (x - minc2) * C2_SCALE;
  178441. max_dist += tdist*tdist;
  178442. }
  178443. }
  178444. mindist[i] = min_dist; /* save away the results */
  178445. if (max_dist < minmaxdist)
  178446. minmaxdist = max_dist;
  178447. }
  178448. /* Now we know that no cell in the update box is more than minmaxdist
  178449. * away from some colormap entry. Therefore, only colors that are
  178450. * within minmaxdist of some part of the box need be considered.
  178451. */
  178452. ncolors = 0;
  178453. for (i = 0; i < numcolors; i++) {
  178454. if (mindist[i] <= minmaxdist)
  178455. colorlist[ncolors++] = (JSAMPLE) i;
  178456. }
  178457. return ncolors;
  178458. }
  178459. LOCAL(void)
  178460. find_best_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  178461. int numcolors, JSAMPLE colorlist[], JSAMPLE bestcolor[])
  178462. /* Find the closest colormap entry for each cell in the update box,
  178463. * given the list of candidate colors prepared by find_nearby_colors.
  178464. * Return the indexes of the closest entries in the bestcolor[] array.
  178465. * This routine uses Thomas' incremental distance calculation method to
  178466. * find the distance from a colormap entry to successive cells in the box.
  178467. */
  178468. {
  178469. int ic0, ic1, ic2;
  178470. int i, icolor;
  178471. register INT32 * bptr; /* pointer into bestdist[] array */
  178472. JSAMPLE * cptr; /* pointer into bestcolor[] array */
  178473. INT32 dist0, dist1; /* initial distance values */
  178474. register INT32 dist2; /* current distance in inner loop */
  178475. INT32 xx0, xx1; /* distance increments */
  178476. register INT32 xx2;
  178477. INT32 inc0, inc1, inc2; /* initial values for increments */
  178478. /* This array holds the distance to the nearest-so-far color for each cell */
  178479. INT32 bestdist[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  178480. /* Initialize best-distance for each cell of the update box */
  178481. bptr = bestdist;
  178482. for (i = BOX_C0_ELEMS*BOX_C1_ELEMS*BOX_C2_ELEMS-1; i >= 0; i--)
  178483. *bptr++ = 0x7FFFFFFFL;
  178484. /* For each color selected by find_nearby_colors,
  178485. * compute its distance to the center of each cell in the box.
  178486. * If that's less than best-so-far, update best distance and color number.
  178487. */
  178488. /* Nominal steps between cell centers ("x" in Thomas article) */
  178489. #define STEP_C0 ((1 << C0_SHIFT) * C0_SCALE)
  178490. #define STEP_C1 ((1 << C1_SHIFT) * C1_SCALE)
  178491. #define STEP_C2 ((1 << C2_SHIFT) * C2_SCALE)
  178492. for (i = 0; i < numcolors; i++) {
  178493. icolor = GETJSAMPLE(colorlist[i]);
  178494. /* Compute (square of) distance from minc0/c1/c2 to this color */
  178495. inc0 = (minc0 - GETJSAMPLE(cinfo->colormap[0][icolor])) * C0_SCALE;
  178496. dist0 = inc0*inc0;
  178497. inc1 = (minc1 - GETJSAMPLE(cinfo->colormap[1][icolor])) * C1_SCALE;
  178498. dist0 += inc1*inc1;
  178499. inc2 = (minc2 - GETJSAMPLE(cinfo->colormap[2][icolor])) * C2_SCALE;
  178500. dist0 += inc2*inc2;
  178501. /* Form the initial difference increments */
  178502. inc0 = inc0 * (2 * STEP_C0) + STEP_C0 * STEP_C0;
  178503. inc1 = inc1 * (2 * STEP_C1) + STEP_C1 * STEP_C1;
  178504. inc2 = inc2 * (2 * STEP_C2) + STEP_C2 * STEP_C2;
  178505. /* Now loop over all cells in box, updating distance per Thomas method */
  178506. bptr = bestdist;
  178507. cptr = bestcolor;
  178508. xx0 = inc0;
  178509. for (ic0 = BOX_C0_ELEMS-1; ic0 >= 0; ic0--) {
  178510. dist1 = dist0;
  178511. xx1 = inc1;
  178512. for (ic1 = BOX_C1_ELEMS-1; ic1 >= 0; ic1--) {
  178513. dist2 = dist1;
  178514. xx2 = inc2;
  178515. for (ic2 = BOX_C2_ELEMS-1; ic2 >= 0; ic2--) {
  178516. if (dist2 < *bptr) {
  178517. *bptr = dist2;
  178518. *cptr = (JSAMPLE) icolor;
  178519. }
  178520. dist2 += xx2;
  178521. xx2 += 2 * STEP_C2 * STEP_C2;
  178522. bptr++;
  178523. cptr++;
  178524. }
  178525. dist1 += xx1;
  178526. xx1 += 2 * STEP_C1 * STEP_C1;
  178527. }
  178528. dist0 += xx0;
  178529. xx0 += 2 * STEP_C0 * STEP_C0;
  178530. }
  178531. }
  178532. }
  178533. LOCAL(void)
  178534. fill_inverse_cmap (j_decompress_ptr cinfo, int c0, int c1, int c2)
  178535. /* Fill the inverse-colormap entries in the update box that contains */
  178536. /* histogram cell c0/c1/c2. (Only that one cell MUST be filled, but */
  178537. /* we can fill as many others as we wish.) */
  178538. {
  178539. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178540. hist3d histogram = cquantize->histogram;
  178541. int minc0, minc1, minc2; /* lower left corner of update box */
  178542. int ic0, ic1, ic2;
  178543. register JSAMPLE * cptr; /* pointer into bestcolor[] array */
  178544. register histptr cachep; /* pointer into main cache array */
  178545. /* This array lists the candidate colormap indexes. */
  178546. JSAMPLE colorlist[MAXNUMCOLORS];
  178547. int numcolors; /* number of candidate colors */
  178548. /* This array holds the actually closest colormap index for each cell. */
  178549. JSAMPLE bestcolor[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  178550. /* Convert cell coordinates to update box ID */
  178551. c0 >>= BOX_C0_LOG;
  178552. c1 >>= BOX_C1_LOG;
  178553. c2 >>= BOX_C2_LOG;
  178554. /* Compute true coordinates of update box's origin corner.
  178555. * Actually we compute the coordinates of the center of the corner
  178556. * histogram cell, which are the lower bounds of the volume we care about.
  178557. */
  178558. minc0 = (c0 << BOX_C0_SHIFT) + ((1 << C0_SHIFT) >> 1);
  178559. minc1 = (c1 << BOX_C1_SHIFT) + ((1 << C1_SHIFT) >> 1);
  178560. minc2 = (c2 << BOX_C2_SHIFT) + ((1 << C2_SHIFT) >> 1);
  178561. /* Determine which colormap entries are close enough to be candidates
  178562. * for the nearest entry to some cell in the update box.
  178563. */
  178564. numcolors = find_nearby_colors(cinfo, minc0, minc1, minc2, colorlist);
  178565. /* Determine the actually nearest colors. */
  178566. find_best_colors(cinfo, minc0, minc1, minc2, numcolors, colorlist,
  178567. bestcolor);
  178568. /* Save the best color numbers (plus 1) in the main cache array */
  178569. c0 <<= BOX_C0_LOG; /* convert ID back to base cell indexes */
  178570. c1 <<= BOX_C1_LOG;
  178571. c2 <<= BOX_C2_LOG;
  178572. cptr = bestcolor;
  178573. for (ic0 = 0; ic0 < BOX_C0_ELEMS; ic0++) {
  178574. for (ic1 = 0; ic1 < BOX_C1_ELEMS; ic1++) {
  178575. cachep = & histogram[c0+ic0][c1+ic1][c2];
  178576. for (ic2 = 0; ic2 < BOX_C2_ELEMS; ic2++) {
  178577. *cachep++ = (histcell) (GETJSAMPLE(*cptr++) + 1);
  178578. }
  178579. }
  178580. }
  178581. }
  178582. /*
  178583. * Map some rows of pixels to the output colormapped representation.
  178584. */
  178585. METHODDEF(void)
  178586. pass2_no_dither (j_decompress_ptr cinfo,
  178587. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  178588. /* This version performs no dithering */
  178589. {
  178590. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178591. hist3d histogram = cquantize->histogram;
  178592. register JSAMPROW inptr, outptr;
  178593. register histptr cachep;
  178594. register int c0, c1, c2;
  178595. int row;
  178596. JDIMENSION col;
  178597. JDIMENSION width = cinfo->output_width;
  178598. for (row = 0; row < num_rows; row++) {
  178599. inptr = input_buf[row];
  178600. outptr = output_buf[row];
  178601. for (col = width; col > 0; col--) {
  178602. /* get pixel value and index into the cache */
  178603. c0 = GETJSAMPLE(*inptr++) >> C0_SHIFT;
  178604. c1 = GETJSAMPLE(*inptr++) >> C1_SHIFT;
  178605. c2 = GETJSAMPLE(*inptr++) >> C2_SHIFT;
  178606. cachep = & histogram[c0][c1][c2];
  178607. /* If we have not seen this color before, find nearest colormap entry */
  178608. /* and update the cache */
  178609. if (*cachep == 0)
  178610. fill_inverse_cmap(cinfo, c0,c1,c2);
  178611. /* Now emit the colormap index for this cell */
  178612. *outptr++ = (JSAMPLE) (*cachep - 1);
  178613. }
  178614. }
  178615. }
  178616. METHODDEF(void)
  178617. pass2_fs_dither (j_decompress_ptr cinfo,
  178618. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  178619. /* This version performs Floyd-Steinberg dithering */
  178620. {
  178621. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178622. hist3d histogram = cquantize->histogram;
  178623. register LOCFSERROR cur0, cur1, cur2; /* current error or pixel value */
  178624. LOCFSERROR belowerr0, belowerr1, belowerr2; /* error for pixel below cur */
  178625. LOCFSERROR bpreverr0, bpreverr1, bpreverr2; /* error for below/prev col */
  178626. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  178627. JSAMPROW inptr; /* => current input pixel */
  178628. JSAMPROW outptr; /* => current output pixel */
  178629. histptr cachep;
  178630. int dir; /* +1 or -1 depending on direction */
  178631. int dir3; /* 3*dir, for advancing inptr & errorptr */
  178632. int row;
  178633. JDIMENSION col;
  178634. JDIMENSION width = cinfo->output_width;
  178635. JSAMPLE *range_limit = cinfo->sample_range_limit;
  178636. int *error_limit = cquantize->error_limiter;
  178637. JSAMPROW colormap0 = cinfo->colormap[0];
  178638. JSAMPROW colormap1 = cinfo->colormap[1];
  178639. JSAMPROW colormap2 = cinfo->colormap[2];
  178640. SHIFT_TEMPS
  178641. for (row = 0; row < num_rows; row++) {
  178642. inptr = input_buf[row];
  178643. outptr = output_buf[row];
  178644. if (cquantize->on_odd_row) {
  178645. /* work right to left in this row */
  178646. inptr += (width-1) * 3; /* so point to rightmost pixel */
  178647. outptr += width-1;
  178648. dir = -1;
  178649. dir3 = -3;
  178650. errorptr = cquantize->fserrors + (width+1)*3; /* => entry after last column */
  178651. cquantize->on_odd_row = FALSE; /* flip for next time */
  178652. } else {
  178653. /* work left to right in this row */
  178654. dir = 1;
  178655. dir3 = 3;
  178656. errorptr = cquantize->fserrors; /* => entry before first real column */
  178657. cquantize->on_odd_row = TRUE; /* flip for next time */
  178658. }
  178659. /* Preset error values: no error propagated to first pixel from left */
  178660. cur0 = cur1 = cur2 = 0;
  178661. /* and no error propagated to row below yet */
  178662. belowerr0 = belowerr1 = belowerr2 = 0;
  178663. bpreverr0 = bpreverr1 = bpreverr2 = 0;
  178664. for (col = width; col > 0; col--) {
  178665. /* curN holds the error propagated from the previous pixel on the
  178666. * current line. Add the error propagated from the previous line
  178667. * to form the complete error correction term for this pixel, and
  178668. * round the error term (which is expressed * 16) to an integer.
  178669. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  178670. * for either sign of the error value.
  178671. * Note: errorptr points to *previous* column's array entry.
  178672. */
  178673. cur0 = RIGHT_SHIFT(cur0 + errorptr[dir3+0] + 8, 4);
  178674. cur1 = RIGHT_SHIFT(cur1 + errorptr[dir3+1] + 8, 4);
  178675. cur2 = RIGHT_SHIFT(cur2 + errorptr[dir3+2] + 8, 4);
  178676. /* Limit the error using transfer function set by init_error_limit.
  178677. * See comments with init_error_limit for rationale.
  178678. */
  178679. cur0 = error_limit[cur0];
  178680. cur1 = error_limit[cur1];
  178681. cur2 = error_limit[cur2];
  178682. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  178683. * The maximum error is +- MAXJSAMPLE (or less with error limiting);
  178684. * this sets the required size of the range_limit array.
  178685. */
  178686. cur0 += GETJSAMPLE(inptr[0]);
  178687. cur1 += GETJSAMPLE(inptr[1]);
  178688. cur2 += GETJSAMPLE(inptr[2]);
  178689. cur0 = GETJSAMPLE(range_limit[cur0]);
  178690. cur1 = GETJSAMPLE(range_limit[cur1]);
  178691. cur2 = GETJSAMPLE(range_limit[cur2]);
  178692. /* Index into the cache with adjusted pixel value */
  178693. cachep = & histogram[cur0>>C0_SHIFT][cur1>>C1_SHIFT][cur2>>C2_SHIFT];
  178694. /* If we have not seen this color before, find nearest colormap */
  178695. /* entry and update the cache */
  178696. if (*cachep == 0)
  178697. fill_inverse_cmap(cinfo, cur0>>C0_SHIFT,cur1>>C1_SHIFT,cur2>>C2_SHIFT);
  178698. /* Now emit the colormap index for this cell */
  178699. { register int pixcode = *cachep - 1;
  178700. *outptr = (JSAMPLE) pixcode;
  178701. /* Compute representation error for this pixel */
  178702. cur0 -= GETJSAMPLE(colormap0[pixcode]);
  178703. cur1 -= GETJSAMPLE(colormap1[pixcode]);
  178704. cur2 -= GETJSAMPLE(colormap2[pixcode]);
  178705. }
  178706. /* Compute error fractions to be propagated to adjacent pixels.
  178707. * Add these into the running sums, and simultaneously shift the
  178708. * next-line error sums left by 1 column.
  178709. */
  178710. { register LOCFSERROR bnexterr, delta;
  178711. bnexterr = cur0; /* Process component 0 */
  178712. delta = cur0 * 2;
  178713. cur0 += delta; /* form error * 3 */
  178714. errorptr[0] = (FSERROR) (bpreverr0 + cur0);
  178715. cur0 += delta; /* form error * 5 */
  178716. bpreverr0 = belowerr0 + cur0;
  178717. belowerr0 = bnexterr;
  178718. cur0 += delta; /* form error * 7 */
  178719. bnexterr = cur1; /* Process component 1 */
  178720. delta = cur1 * 2;
  178721. cur1 += delta; /* form error * 3 */
  178722. errorptr[1] = (FSERROR) (bpreverr1 + cur1);
  178723. cur1 += delta; /* form error * 5 */
  178724. bpreverr1 = belowerr1 + cur1;
  178725. belowerr1 = bnexterr;
  178726. cur1 += delta; /* form error * 7 */
  178727. bnexterr = cur2; /* Process component 2 */
  178728. delta = cur2 * 2;
  178729. cur2 += delta; /* form error * 3 */
  178730. errorptr[2] = (FSERROR) (bpreverr2 + cur2);
  178731. cur2 += delta; /* form error * 5 */
  178732. bpreverr2 = belowerr2 + cur2;
  178733. belowerr2 = bnexterr;
  178734. cur2 += delta; /* form error * 7 */
  178735. }
  178736. /* At this point curN contains the 7/16 error value to be propagated
  178737. * to the next pixel on the current line, and all the errors for the
  178738. * next line have been shifted over. We are therefore ready to move on.
  178739. */
  178740. inptr += dir3; /* Advance pixel pointers to next column */
  178741. outptr += dir;
  178742. errorptr += dir3; /* advance errorptr to current column */
  178743. }
  178744. /* Post-loop cleanup: we must unload the final error values into the
  178745. * final fserrors[] entry. Note we need not unload belowerrN because
  178746. * it is for the dummy column before or after the actual array.
  178747. */
  178748. errorptr[0] = (FSERROR) bpreverr0; /* unload prev errs into array */
  178749. errorptr[1] = (FSERROR) bpreverr1;
  178750. errorptr[2] = (FSERROR) bpreverr2;
  178751. }
  178752. }
  178753. /*
  178754. * Initialize the error-limiting transfer function (lookup table).
  178755. * The raw F-S error computation can potentially compute error values of up to
  178756. * +- MAXJSAMPLE. But we want the maximum correction applied to a pixel to be
  178757. * much less, otherwise obviously wrong pixels will be created. (Typical
  178758. * effects include weird fringes at color-area boundaries, isolated bright
  178759. * pixels in a dark area, etc.) The standard advice for avoiding this problem
  178760. * is to ensure that the "corners" of the color cube are allocated as output
  178761. * colors; then repeated errors in the same direction cannot cause cascading
  178762. * error buildup. However, that only prevents the error from getting
  178763. * completely out of hand; Aaron Giles reports that error limiting improves
  178764. * the results even with corner colors allocated.
  178765. * A simple clamping of the error values to about +- MAXJSAMPLE/8 works pretty
  178766. * well, but the smoother transfer function used below is even better. Thanks
  178767. * to Aaron Giles for this idea.
  178768. */
  178769. LOCAL(void)
  178770. init_error_limit (j_decompress_ptr cinfo)
  178771. /* Allocate and fill in the error_limiter table */
  178772. {
  178773. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178774. int * table;
  178775. int in, out;
  178776. table = (int *) (*cinfo->mem->alloc_small)
  178777. ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE*2+1) * SIZEOF(int));
  178778. table += MAXJSAMPLE; /* so can index -MAXJSAMPLE .. +MAXJSAMPLE */
  178779. cquantize->error_limiter = table;
  178780. #define STEPSIZE ((MAXJSAMPLE+1)/16)
  178781. /* Map errors 1:1 up to +- MAXJSAMPLE/16 */
  178782. out = 0;
  178783. for (in = 0; in < STEPSIZE; in++, out++) {
  178784. table[in] = out; table[-in] = -out;
  178785. }
  178786. /* Map errors 1:2 up to +- 3*MAXJSAMPLE/16 */
  178787. for (; in < STEPSIZE*3; in++, out += (in&1) ? 0 : 1) {
  178788. table[in] = out; table[-in] = -out;
  178789. }
  178790. /* Clamp the rest to final out value (which is (MAXJSAMPLE+1)/8) */
  178791. for (; in <= MAXJSAMPLE; in++) {
  178792. table[in] = out; table[-in] = -out;
  178793. }
  178794. #undef STEPSIZE
  178795. }
  178796. /*
  178797. * Finish up at the end of each pass.
  178798. */
  178799. METHODDEF(void)
  178800. finish_pass1 (j_decompress_ptr cinfo)
  178801. {
  178802. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178803. /* Select the representative colors and fill in cinfo->colormap */
  178804. cinfo->colormap = cquantize->sv_colormap;
  178805. select_colors(cinfo, cquantize->desired);
  178806. /* Force next pass to zero the color index table */
  178807. cquantize->needs_zeroed = TRUE;
  178808. }
  178809. METHODDEF(void)
  178810. finish_pass2 (j_decompress_ptr)
  178811. {
  178812. /* no work */
  178813. }
  178814. /*
  178815. * Initialize for each processing pass.
  178816. */
  178817. METHODDEF(void)
  178818. start_pass_2_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
  178819. {
  178820. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178821. hist3d histogram = cquantize->histogram;
  178822. int i;
  178823. /* Only F-S dithering or no dithering is supported. */
  178824. /* If user asks for ordered dither, give him F-S. */
  178825. if (cinfo->dither_mode != JDITHER_NONE)
  178826. cinfo->dither_mode = JDITHER_FS;
  178827. if (is_pre_scan) {
  178828. /* Set up method pointers */
  178829. cquantize->pub.color_quantize = prescan_quantize;
  178830. cquantize->pub.finish_pass = finish_pass1;
  178831. cquantize->needs_zeroed = TRUE; /* Always zero histogram */
  178832. } else {
  178833. /* Set up method pointers */
  178834. if (cinfo->dither_mode == JDITHER_FS)
  178835. cquantize->pub.color_quantize = pass2_fs_dither;
  178836. else
  178837. cquantize->pub.color_quantize = pass2_no_dither;
  178838. cquantize->pub.finish_pass = finish_pass2;
  178839. /* Make sure color count is acceptable */
  178840. i = cinfo->actual_number_of_colors;
  178841. if (i < 1)
  178842. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 1);
  178843. if (i > MAXNUMCOLORS)
  178844. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  178845. if (cinfo->dither_mode == JDITHER_FS) {
  178846. size_t arraysize = (size_t) ((cinfo->output_width + 2) *
  178847. (3 * SIZEOF(FSERROR)));
  178848. /* Allocate Floyd-Steinberg workspace if we didn't already. */
  178849. if (cquantize->fserrors == NULL)
  178850. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  178851. ((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  178852. /* Initialize the propagated errors to zero. */
  178853. jzero_far((void FAR *) cquantize->fserrors, arraysize);
  178854. /* Make the error-limit table if we didn't already. */
  178855. if (cquantize->error_limiter == NULL)
  178856. init_error_limit(cinfo);
  178857. cquantize->on_odd_row = FALSE;
  178858. }
  178859. }
  178860. /* Zero the histogram or inverse color map, if necessary */
  178861. if (cquantize->needs_zeroed) {
  178862. for (i = 0; i < HIST_C0_ELEMS; i++) {
  178863. jzero_far((void FAR *) histogram[i],
  178864. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  178865. }
  178866. cquantize->needs_zeroed = FALSE;
  178867. }
  178868. }
  178869. /*
  178870. * Switch to a new external colormap between output passes.
  178871. */
  178872. METHODDEF(void)
  178873. new_color_map_2_quant (j_decompress_ptr cinfo)
  178874. {
  178875. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178876. /* Reset the inverse color map */
  178877. cquantize->needs_zeroed = TRUE;
  178878. }
  178879. /*
  178880. * Module initialization routine for 2-pass color quantization.
  178881. */
  178882. GLOBAL(void)
  178883. jinit_2pass_quantizer (j_decompress_ptr cinfo)
  178884. {
  178885. my_cquantize_ptr2 cquantize;
  178886. int i;
  178887. cquantize = (my_cquantize_ptr2)
  178888. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  178889. SIZEOF(my_cquantizer2));
  178890. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  178891. cquantize->pub.start_pass = start_pass_2_quant;
  178892. cquantize->pub.new_color_map = new_color_map_2_quant;
  178893. cquantize->fserrors = NULL; /* flag optional arrays not allocated */
  178894. cquantize->error_limiter = NULL;
  178895. /* Make sure jdmaster didn't give me a case I can't handle */
  178896. if (cinfo->out_color_components != 3)
  178897. ERREXIT(cinfo, JERR_NOTIMPL);
  178898. /* Allocate the histogram/inverse colormap storage */
  178899. cquantize->histogram = (hist3d) (*cinfo->mem->alloc_small)
  178900. ((j_common_ptr) cinfo, JPOOL_IMAGE, HIST_C0_ELEMS * SIZEOF(hist2d));
  178901. for (i = 0; i < HIST_C0_ELEMS; i++) {
  178902. cquantize->histogram[i] = (hist2d) (*cinfo->mem->alloc_large)
  178903. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  178904. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  178905. }
  178906. cquantize->needs_zeroed = TRUE; /* histogram is garbage now */
  178907. /* Allocate storage for the completed colormap, if required.
  178908. * We do this now since it is FAR storage and may affect
  178909. * the memory manager's space calculations.
  178910. */
  178911. if (cinfo->enable_2pass_quant) {
  178912. /* Make sure color count is acceptable */
  178913. int desired = cinfo->desired_number_of_colors;
  178914. /* Lower bound on # of colors ... somewhat arbitrary as long as > 0 */
  178915. if (desired < 8)
  178916. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 8);
  178917. /* Make sure colormap indexes can be represented by JSAMPLEs */
  178918. if (desired > MAXNUMCOLORS)
  178919. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  178920. cquantize->sv_colormap = (*cinfo->mem->alloc_sarray)
  178921. ((j_common_ptr) cinfo,JPOOL_IMAGE, (JDIMENSION) desired, (JDIMENSION) 3);
  178922. cquantize->desired = desired;
  178923. } else
  178924. cquantize->sv_colormap = NULL;
  178925. /* Only F-S dithering or no dithering is supported. */
  178926. /* If user asks for ordered dither, give him F-S. */
  178927. if (cinfo->dither_mode != JDITHER_NONE)
  178928. cinfo->dither_mode = JDITHER_FS;
  178929. /* Allocate Floyd-Steinberg workspace if necessary.
  178930. * This isn't really needed until pass 2, but again it is FAR storage.
  178931. * Although we will cope with a later change in dither_mode,
  178932. * we do not promise to honor max_memory_to_use if dither_mode changes.
  178933. */
  178934. if (cinfo->dither_mode == JDITHER_FS) {
  178935. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  178936. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  178937. (size_t) ((cinfo->output_width + 2) * (3 * SIZEOF(FSERROR))));
  178938. /* Might as well create the error-limiting table too. */
  178939. init_error_limit(cinfo);
  178940. }
  178941. }
  178942. #endif /* QUANT_2PASS_SUPPORTED */
  178943. /*** End of inlined file: jquant2.c ***/
  178944. /*** Start of inlined file: jutils.c ***/
  178945. #define JPEG_INTERNALS
  178946. /*
  178947. * jpeg_zigzag_order[i] is the zigzag-order position of the i'th element
  178948. * of a DCT block read in natural order (left to right, top to bottom).
  178949. */
  178950. #if 0 /* This table is not actually needed in v6a */
  178951. const int jpeg_zigzag_order[DCTSIZE2] = {
  178952. 0, 1, 5, 6, 14, 15, 27, 28,
  178953. 2, 4, 7, 13, 16, 26, 29, 42,
  178954. 3, 8, 12, 17, 25, 30, 41, 43,
  178955. 9, 11, 18, 24, 31, 40, 44, 53,
  178956. 10, 19, 23, 32, 39, 45, 52, 54,
  178957. 20, 22, 33, 38, 46, 51, 55, 60,
  178958. 21, 34, 37, 47, 50, 56, 59, 61,
  178959. 35, 36, 48, 49, 57, 58, 62, 63
  178960. };
  178961. #endif
  178962. /*
  178963. * jpeg_natural_order[i] is the natural-order position of the i'th element
  178964. * of zigzag order.
  178965. *
  178966. * When reading corrupted data, the Huffman decoders could attempt
  178967. * to reference an entry beyond the end of this array (if the decoded
  178968. * zero run length reaches past the end of the block). To prevent
  178969. * wild stores without adding an inner-loop test, we put some extra
  178970. * "63"s after the real entries. This will cause the extra coefficient
  178971. * to be stored in location 63 of the block, not somewhere random.
  178972. * The worst case would be a run-length of 15, which means we need 16
  178973. * fake entries.
  178974. */
  178975. const int jpeg_natural_order[DCTSIZE2+16] = {
  178976. 0, 1, 8, 16, 9, 2, 3, 10,
  178977. 17, 24, 32, 25, 18, 11, 4, 5,
  178978. 12, 19, 26, 33, 40, 48, 41, 34,
  178979. 27, 20, 13, 6, 7, 14, 21, 28,
  178980. 35, 42, 49, 56, 57, 50, 43, 36,
  178981. 29, 22, 15, 23, 30, 37, 44, 51,
  178982. 58, 59, 52, 45, 38, 31, 39, 46,
  178983. 53, 60, 61, 54, 47, 55, 62, 63,
  178984. 63, 63, 63, 63, 63, 63, 63, 63, /* extra entries for safety in decoder */
  178985. 63, 63, 63, 63, 63, 63, 63, 63
  178986. };
  178987. /*
  178988. * Arithmetic utilities
  178989. */
  178990. GLOBAL(long)
  178991. jdiv_round_up (long a, long b)
  178992. /* Compute a/b rounded up to next integer, ie, ceil(a/b) */
  178993. /* Assumes a >= 0, b > 0 */
  178994. {
  178995. return (a + b - 1L) / b;
  178996. }
  178997. GLOBAL(long)
  178998. jround_up (long a, long b)
  178999. /* Compute a rounded up to next multiple of b, ie, ceil(a/b)*b */
  179000. /* Assumes a >= 0, b > 0 */
  179001. {
  179002. a += b - 1L;
  179003. return a - (a % b);
  179004. }
  179005. /* On normal machines we can apply MEMCOPY() and MEMZERO() to sample arrays
  179006. * and coefficient-block arrays. This won't work on 80x86 because the arrays
  179007. * are FAR and we're assuming a small-pointer memory model. However, some
  179008. * DOS compilers provide far-pointer versions of memcpy() and memset() even
  179009. * in the small-model libraries. These will be used if USE_FMEM is defined.
  179010. * Otherwise, the routines below do it the hard way. (The performance cost
  179011. * is not all that great, because these routines aren't very heavily used.)
  179012. */
  179013. #ifndef NEED_FAR_POINTERS /* normal case, same as regular macros */
  179014. #define FMEMCOPY(dest,src,size) MEMCOPY(dest,src,size)
  179015. #define FMEMZERO(target,size) MEMZERO(target,size)
  179016. #else /* 80x86 case, define if we can */
  179017. #ifdef USE_FMEM
  179018. #define FMEMCOPY(dest,src,size) _fmemcpy((void FAR *)(dest), (const void FAR *)(src), (size_t)(size))
  179019. #define FMEMZERO(target,size) _fmemset((void FAR *)(target), 0, (size_t)(size))
  179020. #endif
  179021. #endif
  179022. GLOBAL(void)
  179023. jcopy_sample_rows (JSAMPARRAY input_array, int source_row,
  179024. JSAMPARRAY output_array, int dest_row,
  179025. int num_rows, JDIMENSION num_cols)
  179026. /* Copy some rows of samples from one place to another.
  179027. * num_rows rows are copied from input_array[source_row++]
  179028. * to output_array[dest_row++]; these areas may overlap for duplication.
  179029. * The source and destination arrays must be at least as wide as num_cols.
  179030. */
  179031. {
  179032. register JSAMPROW inptr, outptr;
  179033. #ifdef FMEMCOPY
  179034. register size_t count = (size_t) (num_cols * SIZEOF(JSAMPLE));
  179035. #else
  179036. register JDIMENSION count;
  179037. #endif
  179038. register int row;
  179039. input_array += source_row;
  179040. output_array += dest_row;
  179041. for (row = num_rows; row > 0; row--) {
  179042. inptr = *input_array++;
  179043. outptr = *output_array++;
  179044. #ifdef FMEMCOPY
  179045. FMEMCOPY(outptr, inptr, count);
  179046. #else
  179047. for (count = num_cols; count > 0; count--)
  179048. *outptr++ = *inptr++; /* needn't bother with GETJSAMPLE() here */
  179049. #endif
  179050. }
  179051. }
  179052. GLOBAL(void)
  179053. jcopy_block_row (JBLOCKROW input_row, JBLOCKROW output_row,
  179054. JDIMENSION num_blocks)
  179055. /* Copy a row of coefficient blocks from one place to another. */
  179056. {
  179057. #ifdef FMEMCOPY
  179058. FMEMCOPY(output_row, input_row, num_blocks * (DCTSIZE2 * SIZEOF(JCOEF)));
  179059. #else
  179060. register JCOEFPTR inptr, outptr;
  179061. register long count;
  179062. inptr = (JCOEFPTR) input_row;
  179063. outptr = (JCOEFPTR) output_row;
  179064. for (count = (long) num_blocks * DCTSIZE2; count > 0; count--) {
  179065. *outptr++ = *inptr++;
  179066. }
  179067. #endif
  179068. }
  179069. GLOBAL(void)
  179070. jzero_far (void FAR * target, size_t bytestozero)
  179071. /* Zero out a chunk of FAR memory. */
  179072. /* This might be sample-array data, block-array data, or alloc_large data. */
  179073. {
  179074. #ifdef FMEMZERO
  179075. FMEMZERO(target, bytestozero);
  179076. #else
  179077. register char FAR * ptr = (char FAR *) target;
  179078. register size_t count;
  179079. for (count = bytestozero; count > 0; count--) {
  179080. *ptr++ = 0;
  179081. }
  179082. #endif
  179083. }
  179084. /*** End of inlined file: jutils.c ***/
  179085. /*** Start of inlined file: transupp.c ***/
  179086. /* Although this file really shouldn't have access to the library internals,
  179087. * it's helpful to let it call jround_up() and jcopy_block_row().
  179088. */
  179089. #define JPEG_INTERNALS
  179090. /*** Start of inlined file: transupp.h ***/
  179091. /* If you happen not to want the image transform support, disable it here */
  179092. #ifndef TRANSFORMS_SUPPORTED
  179093. #define TRANSFORMS_SUPPORTED 1 /* 0 disables transform code */
  179094. #endif
  179095. /* Short forms of external names for systems with brain-damaged linkers. */
  179096. #ifdef NEED_SHORT_EXTERNAL_NAMES
  179097. #define jtransform_request_workspace jTrRequest
  179098. #define jtransform_adjust_parameters jTrAdjust
  179099. #define jtransform_execute_transformation jTrExec
  179100. #define jcopy_markers_setup jCMrkSetup
  179101. #define jcopy_markers_execute jCMrkExec
  179102. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  179103. /*
  179104. * Codes for supported types of image transformations.
  179105. */
  179106. typedef enum {
  179107. JXFORM_NONE, /* no transformation */
  179108. JXFORM_FLIP_H, /* horizontal flip */
  179109. JXFORM_FLIP_V, /* vertical flip */
  179110. JXFORM_TRANSPOSE, /* transpose across UL-to-LR axis */
  179111. JXFORM_TRANSVERSE, /* transpose across UR-to-LL axis */
  179112. JXFORM_ROT_90, /* 90-degree clockwise rotation */
  179113. JXFORM_ROT_180, /* 180-degree rotation */
  179114. JXFORM_ROT_270 /* 270-degree clockwise (or 90 ccw) */
  179115. } JXFORM_CODE;
  179116. /*
  179117. * Although rotating and flipping data expressed as DCT coefficients is not
  179118. * hard, there is an asymmetry in the JPEG format specification for images
  179119. * whose dimensions aren't multiples of the iMCU size. The right and bottom
  179120. * image edges are padded out to the next iMCU boundary with junk data; but
  179121. * no padding is possible at the top and left edges. If we were to flip
  179122. * the whole image including the pad data, then pad garbage would become
  179123. * visible at the top and/or left, and real pixels would disappear into the
  179124. * pad margins --- perhaps permanently, since encoders & decoders may not
  179125. * bother to preserve DCT blocks that appear to be completely outside the
  179126. * nominal image area. So, we have to exclude any partial iMCUs from the
  179127. * basic transformation.
  179128. *
  179129. * Transpose is the only transformation that can handle partial iMCUs at the
  179130. * right and bottom edges completely cleanly. flip_h can flip partial iMCUs
  179131. * at the bottom, but leaves any partial iMCUs at the right edge untouched.
  179132. * Similarly flip_v leaves any partial iMCUs at the bottom edge untouched.
  179133. * The other transforms are defined as combinations of these basic transforms
  179134. * and process edge blocks in a way that preserves the equivalence.
  179135. *
  179136. * The "trim" option causes untransformable partial iMCUs to be dropped;
  179137. * this is not strictly lossless, but it usually gives the best-looking
  179138. * result for odd-size images. Note that when this option is active,
  179139. * the expected mathematical equivalences between the transforms may not hold.
  179140. * (For example, -rot 270 -trim trims only the bottom edge, but -rot 90 -trim
  179141. * followed by -rot 180 -trim trims both edges.)
  179142. *
  179143. * We also offer a "force to grayscale" option, which simply discards the
  179144. * chrominance channels of a YCbCr image. This is lossless in the sense that
  179145. * the luminance channel is preserved exactly. It's not the same kind of
  179146. * thing as the rotate/flip transformations, but it's convenient to handle it
  179147. * as part of this package, mainly because the transformation routines have to
  179148. * be aware of the option to know how many components to work on.
  179149. */
  179150. typedef struct {
  179151. /* Options: set by caller */
  179152. JXFORM_CODE transform; /* image transform operator */
  179153. boolean trim; /* if TRUE, trim partial MCUs as needed */
  179154. boolean force_grayscale; /* if TRUE, convert color image to grayscale */
  179155. /* Internal workspace: caller should not touch these */
  179156. int num_components; /* # of components in workspace */
  179157. jvirt_barray_ptr * workspace_coef_arrays; /* workspace for transformations */
  179158. } jpeg_transform_info;
  179159. #if TRANSFORMS_SUPPORTED
  179160. /* Request any required workspace */
  179161. EXTERN(void) jtransform_request_workspace
  179162. JPP((j_decompress_ptr srcinfo, jpeg_transform_info *info));
  179163. /* Adjust output image parameters */
  179164. EXTERN(jvirt_barray_ptr *) jtransform_adjust_parameters
  179165. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179166. jvirt_barray_ptr *src_coef_arrays,
  179167. jpeg_transform_info *info));
  179168. /* Execute the actual transformation, if any */
  179169. EXTERN(void) jtransform_execute_transformation
  179170. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179171. jvirt_barray_ptr *src_coef_arrays,
  179172. jpeg_transform_info *info));
  179173. #endif /* TRANSFORMS_SUPPORTED */
  179174. /*
  179175. * Support for copying optional markers from source to destination file.
  179176. */
  179177. typedef enum {
  179178. JCOPYOPT_NONE, /* copy no optional markers */
  179179. JCOPYOPT_COMMENTS, /* copy only comment (COM) markers */
  179180. JCOPYOPT_ALL /* copy all optional markers */
  179181. } JCOPY_OPTION;
  179182. #define JCOPYOPT_DEFAULT JCOPYOPT_COMMENTS /* recommended default */
  179183. /* Setup decompression object to save desired markers in memory */
  179184. EXTERN(void) jcopy_markers_setup
  179185. JPP((j_decompress_ptr srcinfo, JCOPY_OPTION option));
  179186. /* Copy markers saved in the given source object to the destination object */
  179187. EXTERN(void) jcopy_markers_execute
  179188. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179189. JCOPY_OPTION option));
  179190. /*** End of inlined file: transupp.h ***/
  179191. /* My own external interface */
  179192. #if TRANSFORMS_SUPPORTED
  179193. /*
  179194. * Lossless image transformation routines. These routines work on DCT
  179195. * coefficient arrays and thus do not require any lossy decompression
  179196. * or recompression of the image.
  179197. * Thanks to Guido Vollbeding for the initial design and code of this feature.
  179198. *
  179199. * Horizontal flipping is done in-place, using a single top-to-bottom
  179200. * pass through the virtual source array. It will thus be much the
  179201. * fastest option for images larger than main memory.
  179202. *
  179203. * The other routines require a set of destination virtual arrays, so they
  179204. * need twice as much memory as jpegtran normally does. The destination
  179205. * arrays are always written in normal scan order (top to bottom) because
  179206. * the virtual array manager expects this. The source arrays will be scanned
  179207. * in the corresponding order, which means multiple passes through the source
  179208. * arrays for most of the transforms. That could result in much thrashing
  179209. * if the image is larger than main memory.
  179210. *
  179211. * Some notes about the operating environment of the individual transform
  179212. * routines:
  179213. * 1. Both the source and destination virtual arrays are allocated from the
  179214. * source JPEG object, and therefore should be manipulated by calling the
  179215. * source's memory manager.
  179216. * 2. The destination's component count should be used. It may be smaller
  179217. * than the source's when forcing to grayscale.
  179218. * 3. Likewise the destination's sampling factors should be used. When
  179219. * forcing to grayscale the destination's sampling factors will be all 1,
  179220. * and we may as well take that as the effective iMCU size.
  179221. * 4. When "trim" is in effect, the destination's dimensions will be the
  179222. * trimmed values but the source's will be untrimmed.
  179223. * 5. All the routines assume that the source and destination buffers are
  179224. * padded out to a full iMCU boundary. This is true, although for the
  179225. * source buffer it is an undocumented property of jdcoefct.c.
  179226. * Notes 2,3,4 boil down to this: generally we should use the destination's
  179227. * dimensions and ignore the source's.
  179228. */
  179229. LOCAL(void)
  179230. do_flip_h (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179231. jvirt_barray_ptr *src_coef_arrays)
  179232. /* Horizontal flip; done in-place, so no separate dest array is required */
  179233. {
  179234. JDIMENSION MCU_cols, comp_width, blk_x, blk_y;
  179235. int ci, k, offset_y;
  179236. JBLOCKARRAY buffer;
  179237. JCOEFPTR ptr1, ptr2;
  179238. JCOEF temp1, temp2;
  179239. jpeg_component_info *compptr;
  179240. /* Horizontal mirroring of DCT blocks is accomplished by swapping
  179241. * pairs of blocks in-place. Within a DCT block, we perform horizontal
  179242. * mirroring by changing the signs of odd-numbered columns.
  179243. * Partial iMCUs at the right edge are left untouched.
  179244. */
  179245. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179246. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179247. compptr = dstinfo->comp_info + ci;
  179248. comp_width = MCU_cols * compptr->h_samp_factor;
  179249. for (blk_y = 0; blk_y < compptr->height_in_blocks;
  179250. blk_y += compptr->v_samp_factor) {
  179251. buffer = (*srcinfo->mem->access_virt_barray)
  179252. ((j_common_ptr) srcinfo, src_coef_arrays[ci], blk_y,
  179253. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179254. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179255. for (blk_x = 0; blk_x * 2 < comp_width; blk_x++) {
  179256. ptr1 = buffer[offset_y][blk_x];
  179257. ptr2 = buffer[offset_y][comp_width - blk_x - 1];
  179258. /* this unrolled loop doesn't need to know which row it's on... */
  179259. for (k = 0; k < DCTSIZE2; k += 2) {
  179260. temp1 = *ptr1; /* swap even column */
  179261. temp2 = *ptr2;
  179262. *ptr1++ = temp2;
  179263. *ptr2++ = temp1;
  179264. temp1 = *ptr1; /* swap odd column with sign change */
  179265. temp2 = *ptr2;
  179266. *ptr1++ = -temp2;
  179267. *ptr2++ = -temp1;
  179268. }
  179269. }
  179270. }
  179271. }
  179272. }
  179273. }
  179274. LOCAL(void)
  179275. do_flip_v (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179276. jvirt_barray_ptr *src_coef_arrays,
  179277. jvirt_barray_ptr *dst_coef_arrays)
  179278. /* Vertical flip */
  179279. {
  179280. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  179281. int ci, i, j, offset_y;
  179282. JBLOCKARRAY src_buffer, dst_buffer;
  179283. JBLOCKROW src_row_ptr, dst_row_ptr;
  179284. JCOEFPTR src_ptr, dst_ptr;
  179285. jpeg_component_info *compptr;
  179286. /* We output into a separate array because we can't touch different
  179287. * rows of the source virtual array simultaneously. Otherwise, this
  179288. * is a pretty straightforward analog of horizontal flip.
  179289. * Within a DCT block, vertical mirroring is done by changing the signs
  179290. * of odd-numbered rows.
  179291. * Partial iMCUs at the bottom edge are copied verbatim.
  179292. */
  179293. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179294. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179295. compptr = dstinfo->comp_info + ci;
  179296. comp_height = MCU_rows * compptr->v_samp_factor;
  179297. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179298. dst_blk_y += compptr->v_samp_factor) {
  179299. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179300. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179301. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179302. if (dst_blk_y < comp_height) {
  179303. /* Row is within the mirrorable area. */
  179304. src_buffer = (*srcinfo->mem->access_virt_barray)
  179305. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  179306. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  179307. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179308. } else {
  179309. /* Bottom-edge blocks will be copied verbatim. */
  179310. src_buffer = (*srcinfo->mem->access_virt_barray)
  179311. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  179312. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179313. }
  179314. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179315. if (dst_blk_y < comp_height) {
  179316. /* Row is within the mirrorable area. */
  179317. dst_row_ptr = dst_buffer[offset_y];
  179318. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  179319. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179320. dst_blk_x++) {
  179321. dst_ptr = dst_row_ptr[dst_blk_x];
  179322. src_ptr = src_row_ptr[dst_blk_x];
  179323. for (i = 0; i < DCTSIZE; i += 2) {
  179324. /* copy even row */
  179325. for (j = 0; j < DCTSIZE; j++)
  179326. *dst_ptr++ = *src_ptr++;
  179327. /* copy odd row with sign change */
  179328. for (j = 0; j < DCTSIZE; j++)
  179329. *dst_ptr++ = - *src_ptr++;
  179330. }
  179331. }
  179332. } else {
  179333. /* Just copy row verbatim. */
  179334. jcopy_block_row(src_buffer[offset_y], dst_buffer[offset_y],
  179335. compptr->width_in_blocks);
  179336. }
  179337. }
  179338. }
  179339. }
  179340. }
  179341. LOCAL(void)
  179342. do_transpose (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179343. jvirt_barray_ptr *src_coef_arrays,
  179344. jvirt_barray_ptr *dst_coef_arrays)
  179345. /* Transpose source into destination */
  179346. {
  179347. JDIMENSION dst_blk_x, dst_blk_y;
  179348. int ci, i, j, offset_x, offset_y;
  179349. JBLOCKARRAY src_buffer, dst_buffer;
  179350. JCOEFPTR src_ptr, dst_ptr;
  179351. jpeg_component_info *compptr;
  179352. /* Transposing pixels within a block just requires transposing the
  179353. * DCT coefficients.
  179354. * Partial iMCUs at the edges require no special treatment; we simply
  179355. * process all the available DCT blocks for every component.
  179356. */
  179357. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179358. compptr = dstinfo->comp_info + ci;
  179359. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179360. dst_blk_y += compptr->v_samp_factor) {
  179361. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179362. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179363. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179364. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179365. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179366. dst_blk_x += compptr->h_samp_factor) {
  179367. src_buffer = (*srcinfo->mem->access_virt_barray)
  179368. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179369. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179370. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179371. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179372. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179373. for (i = 0; i < DCTSIZE; i++)
  179374. for (j = 0; j < DCTSIZE; j++)
  179375. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179376. }
  179377. }
  179378. }
  179379. }
  179380. }
  179381. }
  179382. LOCAL(void)
  179383. do_rot_90 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179384. jvirt_barray_ptr *src_coef_arrays,
  179385. jvirt_barray_ptr *dst_coef_arrays)
  179386. /* 90 degree rotation is equivalent to
  179387. * 1. Transposing the image;
  179388. * 2. Horizontal mirroring.
  179389. * These two steps are merged into a single processing routine.
  179390. */
  179391. {
  179392. JDIMENSION MCU_cols, comp_width, dst_blk_x, dst_blk_y;
  179393. int ci, i, j, offset_x, offset_y;
  179394. JBLOCKARRAY src_buffer, dst_buffer;
  179395. JCOEFPTR src_ptr, dst_ptr;
  179396. jpeg_component_info *compptr;
  179397. /* Because of the horizontal mirror step, we can't process partial iMCUs
  179398. * at the (output) right edge properly. They just get transposed and
  179399. * not mirrored.
  179400. */
  179401. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179402. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179403. compptr = dstinfo->comp_info + ci;
  179404. comp_width = MCU_cols * compptr->h_samp_factor;
  179405. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179406. dst_blk_y += compptr->v_samp_factor) {
  179407. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179408. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179409. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179410. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179411. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179412. dst_blk_x += compptr->h_samp_factor) {
  179413. src_buffer = (*srcinfo->mem->access_virt_barray)
  179414. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179415. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179416. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179417. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179418. if (dst_blk_x < comp_width) {
  179419. /* Block is within the mirrorable area. */
  179420. dst_ptr = dst_buffer[offset_y]
  179421. [comp_width - dst_blk_x - offset_x - 1];
  179422. for (i = 0; i < DCTSIZE; i++) {
  179423. for (j = 0; j < DCTSIZE; j++)
  179424. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179425. i++;
  179426. for (j = 0; j < DCTSIZE; j++)
  179427. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179428. }
  179429. } else {
  179430. /* Edge blocks are transposed but not mirrored. */
  179431. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179432. for (i = 0; i < DCTSIZE; i++)
  179433. for (j = 0; j < DCTSIZE; j++)
  179434. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179435. }
  179436. }
  179437. }
  179438. }
  179439. }
  179440. }
  179441. }
  179442. LOCAL(void)
  179443. do_rot_270 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179444. jvirt_barray_ptr *src_coef_arrays,
  179445. jvirt_barray_ptr *dst_coef_arrays)
  179446. /* 270 degree rotation is equivalent to
  179447. * 1. Horizontal mirroring;
  179448. * 2. Transposing the image.
  179449. * These two steps are merged into a single processing routine.
  179450. */
  179451. {
  179452. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  179453. int ci, i, j, offset_x, offset_y;
  179454. JBLOCKARRAY src_buffer, dst_buffer;
  179455. JCOEFPTR src_ptr, dst_ptr;
  179456. jpeg_component_info *compptr;
  179457. /* Because of the horizontal mirror step, we can't process partial iMCUs
  179458. * at the (output) bottom edge properly. They just get transposed and
  179459. * not mirrored.
  179460. */
  179461. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179462. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179463. compptr = dstinfo->comp_info + ci;
  179464. comp_height = MCU_rows * compptr->v_samp_factor;
  179465. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179466. dst_blk_y += compptr->v_samp_factor) {
  179467. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179468. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179469. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179470. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179471. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179472. dst_blk_x += compptr->h_samp_factor) {
  179473. src_buffer = (*srcinfo->mem->access_virt_barray)
  179474. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179475. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179476. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179477. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179478. if (dst_blk_y < comp_height) {
  179479. /* Block is within the mirrorable area. */
  179480. src_ptr = src_buffer[offset_x]
  179481. [comp_height - dst_blk_y - offset_y - 1];
  179482. for (i = 0; i < DCTSIZE; i++) {
  179483. for (j = 0; j < DCTSIZE; j++) {
  179484. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179485. j++;
  179486. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179487. }
  179488. }
  179489. } else {
  179490. /* Edge blocks are transposed but not mirrored. */
  179491. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179492. for (i = 0; i < DCTSIZE; i++)
  179493. for (j = 0; j < DCTSIZE; j++)
  179494. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179495. }
  179496. }
  179497. }
  179498. }
  179499. }
  179500. }
  179501. }
  179502. LOCAL(void)
  179503. do_rot_180 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179504. jvirt_barray_ptr *src_coef_arrays,
  179505. jvirt_barray_ptr *dst_coef_arrays)
  179506. /* 180 degree rotation is equivalent to
  179507. * 1. Vertical mirroring;
  179508. * 2. Horizontal mirroring.
  179509. * These two steps are merged into a single processing routine.
  179510. */
  179511. {
  179512. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  179513. int ci, i, j, offset_y;
  179514. JBLOCKARRAY src_buffer, dst_buffer;
  179515. JBLOCKROW src_row_ptr, dst_row_ptr;
  179516. JCOEFPTR src_ptr, dst_ptr;
  179517. jpeg_component_info *compptr;
  179518. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179519. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179520. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179521. compptr = dstinfo->comp_info + ci;
  179522. comp_width = MCU_cols * compptr->h_samp_factor;
  179523. comp_height = MCU_rows * compptr->v_samp_factor;
  179524. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179525. dst_blk_y += compptr->v_samp_factor) {
  179526. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179527. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179528. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179529. if (dst_blk_y < comp_height) {
  179530. /* Row is within the vertically mirrorable area. */
  179531. src_buffer = (*srcinfo->mem->access_virt_barray)
  179532. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  179533. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  179534. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179535. } else {
  179536. /* Bottom-edge rows are only mirrored horizontally. */
  179537. src_buffer = (*srcinfo->mem->access_virt_barray)
  179538. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  179539. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179540. }
  179541. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179542. if (dst_blk_y < comp_height) {
  179543. /* Row is within the mirrorable area. */
  179544. dst_row_ptr = dst_buffer[offset_y];
  179545. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  179546. /* Process the blocks that can be mirrored both ways. */
  179547. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  179548. dst_ptr = dst_row_ptr[dst_blk_x];
  179549. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  179550. for (i = 0; i < DCTSIZE; i += 2) {
  179551. /* For even row, negate every odd column. */
  179552. for (j = 0; j < DCTSIZE; j += 2) {
  179553. *dst_ptr++ = *src_ptr++;
  179554. *dst_ptr++ = - *src_ptr++;
  179555. }
  179556. /* For odd row, negate every even column. */
  179557. for (j = 0; j < DCTSIZE; j += 2) {
  179558. *dst_ptr++ = - *src_ptr++;
  179559. *dst_ptr++ = *src_ptr++;
  179560. }
  179561. }
  179562. }
  179563. /* Any remaining right-edge blocks are only mirrored vertically. */
  179564. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  179565. dst_ptr = dst_row_ptr[dst_blk_x];
  179566. src_ptr = src_row_ptr[dst_blk_x];
  179567. for (i = 0; i < DCTSIZE; i += 2) {
  179568. for (j = 0; j < DCTSIZE; j++)
  179569. *dst_ptr++ = *src_ptr++;
  179570. for (j = 0; j < DCTSIZE; j++)
  179571. *dst_ptr++ = - *src_ptr++;
  179572. }
  179573. }
  179574. } else {
  179575. /* Remaining rows are just mirrored horizontally. */
  179576. dst_row_ptr = dst_buffer[offset_y];
  179577. src_row_ptr = src_buffer[offset_y];
  179578. /* Process the blocks that can be mirrored. */
  179579. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  179580. dst_ptr = dst_row_ptr[dst_blk_x];
  179581. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  179582. for (i = 0; i < DCTSIZE2; i += 2) {
  179583. *dst_ptr++ = *src_ptr++;
  179584. *dst_ptr++ = - *src_ptr++;
  179585. }
  179586. }
  179587. /* Any remaining right-edge blocks are only copied. */
  179588. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  179589. dst_ptr = dst_row_ptr[dst_blk_x];
  179590. src_ptr = src_row_ptr[dst_blk_x];
  179591. for (i = 0; i < DCTSIZE2; i++)
  179592. *dst_ptr++ = *src_ptr++;
  179593. }
  179594. }
  179595. }
  179596. }
  179597. }
  179598. }
  179599. LOCAL(void)
  179600. do_transverse (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179601. jvirt_barray_ptr *src_coef_arrays,
  179602. jvirt_barray_ptr *dst_coef_arrays)
  179603. /* Transverse transpose is equivalent to
  179604. * 1. 180 degree rotation;
  179605. * 2. Transposition;
  179606. * or
  179607. * 1. Horizontal mirroring;
  179608. * 2. Transposition;
  179609. * 3. Horizontal mirroring.
  179610. * These steps are merged into a single processing routine.
  179611. */
  179612. {
  179613. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  179614. int ci, i, j, offset_x, offset_y;
  179615. JBLOCKARRAY src_buffer, dst_buffer;
  179616. JCOEFPTR src_ptr, dst_ptr;
  179617. jpeg_component_info *compptr;
  179618. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179619. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179620. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179621. compptr = dstinfo->comp_info + ci;
  179622. comp_width = MCU_cols * compptr->h_samp_factor;
  179623. comp_height = MCU_rows * compptr->v_samp_factor;
  179624. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179625. dst_blk_y += compptr->v_samp_factor) {
  179626. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179627. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179628. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179629. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179630. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179631. dst_blk_x += compptr->h_samp_factor) {
  179632. src_buffer = (*srcinfo->mem->access_virt_barray)
  179633. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179634. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179635. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179636. if (dst_blk_y < comp_height) {
  179637. src_ptr = src_buffer[offset_x]
  179638. [comp_height - dst_blk_y - offset_y - 1];
  179639. if (dst_blk_x < comp_width) {
  179640. /* Block is within the mirrorable area. */
  179641. dst_ptr = dst_buffer[offset_y]
  179642. [comp_width - dst_blk_x - offset_x - 1];
  179643. for (i = 0; i < DCTSIZE; i++) {
  179644. for (j = 0; j < DCTSIZE; j++) {
  179645. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179646. j++;
  179647. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179648. }
  179649. i++;
  179650. for (j = 0; j < DCTSIZE; j++) {
  179651. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179652. j++;
  179653. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179654. }
  179655. }
  179656. } else {
  179657. /* Right-edge blocks are mirrored in y only */
  179658. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179659. for (i = 0; i < DCTSIZE; i++) {
  179660. for (j = 0; j < DCTSIZE; j++) {
  179661. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179662. j++;
  179663. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179664. }
  179665. }
  179666. }
  179667. } else {
  179668. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179669. if (dst_blk_x < comp_width) {
  179670. /* Bottom-edge blocks are mirrored in x only */
  179671. dst_ptr = dst_buffer[offset_y]
  179672. [comp_width - dst_blk_x - offset_x - 1];
  179673. for (i = 0; i < DCTSIZE; i++) {
  179674. for (j = 0; j < DCTSIZE; j++)
  179675. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179676. i++;
  179677. for (j = 0; j < DCTSIZE; j++)
  179678. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179679. }
  179680. } else {
  179681. /* At lower right corner, just transpose, no mirroring */
  179682. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179683. for (i = 0; i < DCTSIZE; i++)
  179684. for (j = 0; j < DCTSIZE; j++)
  179685. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179686. }
  179687. }
  179688. }
  179689. }
  179690. }
  179691. }
  179692. }
  179693. }
  179694. /* Request any required workspace.
  179695. *
  179696. * We allocate the workspace virtual arrays from the source decompression
  179697. * object, so that all the arrays (both the original data and the workspace)
  179698. * will be taken into account while making memory management decisions.
  179699. * Hence, this routine must be called after jpeg_read_header (which reads
  179700. * the image dimensions) and before jpeg_read_coefficients (which realizes
  179701. * the source's virtual arrays).
  179702. */
  179703. GLOBAL(void)
  179704. jtransform_request_workspace (j_decompress_ptr srcinfo,
  179705. jpeg_transform_info *info)
  179706. {
  179707. jvirt_barray_ptr *coef_arrays = NULL;
  179708. jpeg_component_info *compptr;
  179709. int ci;
  179710. if (info->force_grayscale &&
  179711. srcinfo->jpeg_color_space == JCS_YCbCr &&
  179712. srcinfo->num_components == 3) {
  179713. /* We'll only process the first component */
  179714. info->num_components = 1;
  179715. } else {
  179716. /* Process all the components */
  179717. info->num_components = srcinfo->num_components;
  179718. }
  179719. switch (info->transform) {
  179720. case JXFORM_NONE:
  179721. case JXFORM_FLIP_H:
  179722. /* Don't need a workspace array */
  179723. break;
  179724. case JXFORM_FLIP_V:
  179725. case JXFORM_ROT_180:
  179726. /* Need workspace arrays having same dimensions as source image.
  179727. * Note that we allocate arrays padded out to the next iMCU boundary,
  179728. * so that transform routines need not worry about missing edge blocks.
  179729. */
  179730. coef_arrays = (jvirt_barray_ptr *)
  179731. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  179732. SIZEOF(jvirt_barray_ptr) * info->num_components);
  179733. for (ci = 0; ci < info->num_components; ci++) {
  179734. compptr = srcinfo->comp_info + ci;
  179735. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  179736. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  179737. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  179738. (long) compptr->h_samp_factor),
  179739. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  179740. (long) compptr->v_samp_factor),
  179741. (JDIMENSION) compptr->v_samp_factor);
  179742. }
  179743. break;
  179744. case JXFORM_TRANSPOSE:
  179745. case JXFORM_TRANSVERSE:
  179746. case JXFORM_ROT_90:
  179747. case JXFORM_ROT_270:
  179748. /* Need workspace arrays having transposed dimensions.
  179749. * Note that we allocate arrays padded out to the next iMCU boundary,
  179750. * so that transform routines need not worry about missing edge blocks.
  179751. */
  179752. coef_arrays = (jvirt_barray_ptr *)
  179753. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  179754. SIZEOF(jvirt_barray_ptr) * info->num_components);
  179755. for (ci = 0; ci < info->num_components; ci++) {
  179756. compptr = srcinfo->comp_info + ci;
  179757. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  179758. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  179759. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  179760. (long) compptr->v_samp_factor),
  179761. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  179762. (long) compptr->h_samp_factor),
  179763. (JDIMENSION) compptr->h_samp_factor);
  179764. }
  179765. break;
  179766. }
  179767. info->workspace_coef_arrays = coef_arrays;
  179768. }
  179769. /* Transpose destination image parameters */
  179770. LOCAL(void)
  179771. transpose_critical_parameters (j_compress_ptr dstinfo)
  179772. {
  179773. int tblno, i, j, ci, itemp;
  179774. jpeg_component_info *compptr;
  179775. JQUANT_TBL *qtblptr;
  179776. JDIMENSION dtemp;
  179777. UINT16 qtemp;
  179778. /* Transpose basic image dimensions */
  179779. dtemp = dstinfo->image_width;
  179780. dstinfo->image_width = dstinfo->image_height;
  179781. dstinfo->image_height = dtemp;
  179782. /* Transpose sampling factors */
  179783. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179784. compptr = dstinfo->comp_info + ci;
  179785. itemp = compptr->h_samp_factor;
  179786. compptr->h_samp_factor = compptr->v_samp_factor;
  179787. compptr->v_samp_factor = itemp;
  179788. }
  179789. /* Transpose quantization tables */
  179790. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  179791. qtblptr = dstinfo->quant_tbl_ptrs[tblno];
  179792. if (qtblptr != NULL) {
  179793. for (i = 0; i < DCTSIZE; i++) {
  179794. for (j = 0; j < i; j++) {
  179795. qtemp = qtblptr->quantval[i*DCTSIZE+j];
  179796. qtblptr->quantval[i*DCTSIZE+j] = qtblptr->quantval[j*DCTSIZE+i];
  179797. qtblptr->quantval[j*DCTSIZE+i] = qtemp;
  179798. }
  179799. }
  179800. }
  179801. }
  179802. }
  179803. /* Trim off any partial iMCUs on the indicated destination edge */
  179804. LOCAL(void)
  179805. trim_right_edge (j_compress_ptr dstinfo)
  179806. {
  179807. int ci, max_h_samp_factor;
  179808. JDIMENSION MCU_cols;
  179809. /* We have to compute max_h_samp_factor ourselves,
  179810. * because it hasn't been set yet in the destination
  179811. * (and we don't want to use the source's value).
  179812. */
  179813. max_h_samp_factor = 1;
  179814. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179815. int h_samp_factor = dstinfo->comp_info[ci].h_samp_factor;
  179816. max_h_samp_factor = MAX(max_h_samp_factor, h_samp_factor);
  179817. }
  179818. MCU_cols = dstinfo->image_width / (max_h_samp_factor * DCTSIZE);
  179819. if (MCU_cols > 0) /* can't trim to 0 pixels */
  179820. dstinfo->image_width = MCU_cols * (max_h_samp_factor * DCTSIZE);
  179821. }
  179822. LOCAL(void)
  179823. trim_bottom_edge (j_compress_ptr dstinfo)
  179824. {
  179825. int ci, max_v_samp_factor;
  179826. JDIMENSION MCU_rows;
  179827. /* We have to compute max_v_samp_factor ourselves,
  179828. * because it hasn't been set yet in the destination
  179829. * (and we don't want to use the source's value).
  179830. */
  179831. max_v_samp_factor = 1;
  179832. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179833. int v_samp_factor = dstinfo->comp_info[ci].v_samp_factor;
  179834. max_v_samp_factor = MAX(max_v_samp_factor, v_samp_factor);
  179835. }
  179836. MCU_rows = dstinfo->image_height / (max_v_samp_factor * DCTSIZE);
  179837. if (MCU_rows > 0) /* can't trim to 0 pixels */
  179838. dstinfo->image_height = MCU_rows * (max_v_samp_factor * DCTSIZE);
  179839. }
  179840. /* Adjust output image parameters as needed.
  179841. *
  179842. * This must be called after jpeg_copy_critical_parameters()
  179843. * and before jpeg_write_coefficients().
  179844. *
  179845. * The return value is the set of virtual coefficient arrays to be written
  179846. * (either the ones allocated by jtransform_request_workspace, or the
  179847. * original source data arrays). The caller will need to pass this value
  179848. * to jpeg_write_coefficients().
  179849. */
  179850. GLOBAL(jvirt_barray_ptr *)
  179851. jtransform_adjust_parameters (j_decompress_ptr,
  179852. j_compress_ptr dstinfo,
  179853. jvirt_barray_ptr *src_coef_arrays,
  179854. jpeg_transform_info *info)
  179855. {
  179856. /* If force-to-grayscale is requested, adjust destination parameters */
  179857. if (info->force_grayscale) {
  179858. /* We use jpeg_set_colorspace to make sure subsidiary settings get fixed
  179859. * properly. Among other things, the target h_samp_factor & v_samp_factor
  179860. * will get set to 1, which typically won't match the source.
  179861. * In fact we do this even if the source is already grayscale; that
  179862. * provides an easy way of coercing a grayscale JPEG with funny sampling
  179863. * factors to the customary 1,1. (Some decoders fail on other factors.)
  179864. */
  179865. if ((dstinfo->jpeg_color_space == JCS_YCbCr &&
  179866. dstinfo->num_components == 3) ||
  179867. (dstinfo->jpeg_color_space == JCS_GRAYSCALE &&
  179868. dstinfo->num_components == 1)) {
  179869. /* We have to preserve the source's quantization table number. */
  179870. int sv_quant_tbl_no = dstinfo->comp_info[0].quant_tbl_no;
  179871. jpeg_set_colorspace(dstinfo, JCS_GRAYSCALE);
  179872. dstinfo->comp_info[0].quant_tbl_no = sv_quant_tbl_no;
  179873. } else {
  179874. /* Sorry, can't do it */
  179875. ERREXIT(dstinfo, JERR_CONVERSION_NOTIMPL);
  179876. }
  179877. }
  179878. /* Correct the destination's image dimensions etc if necessary */
  179879. switch (info->transform) {
  179880. case JXFORM_NONE:
  179881. /* Nothing to do */
  179882. break;
  179883. case JXFORM_FLIP_H:
  179884. if (info->trim)
  179885. trim_right_edge(dstinfo);
  179886. break;
  179887. case JXFORM_FLIP_V:
  179888. if (info->trim)
  179889. trim_bottom_edge(dstinfo);
  179890. break;
  179891. case JXFORM_TRANSPOSE:
  179892. transpose_critical_parameters(dstinfo);
  179893. /* transpose does NOT have to trim anything */
  179894. break;
  179895. case JXFORM_TRANSVERSE:
  179896. transpose_critical_parameters(dstinfo);
  179897. if (info->trim) {
  179898. trim_right_edge(dstinfo);
  179899. trim_bottom_edge(dstinfo);
  179900. }
  179901. break;
  179902. case JXFORM_ROT_90:
  179903. transpose_critical_parameters(dstinfo);
  179904. if (info->trim)
  179905. trim_right_edge(dstinfo);
  179906. break;
  179907. case JXFORM_ROT_180:
  179908. if (info->trim) {
  179909. trim_right_edge(dstinfo);
  179910. trim_bottom_edge(dstinfo);
  179911. }
  179912. break;
  179913. case JXFORM_ROT_270:
  179914. transpose_critical_parameters(dstinfo);
  179915. if (info->trim)
  179916. trim_bottom_edge(dstinfo);
  179917. break;
  179918. }
  179919. /* Return the appropriate output data set */
  179920. if (info->workspace_coef_arrays != NULL)
  179921. return info->workspace_coef_arrays;
  179922. return src_coef_arrays;
  179923. }
  179924. /* Execute the actual transformation, if any.
  179925. *
  179926. * This must be called *after* jpeg_write_coefficients, because it depends
  179927. * on jpeg_write_coefficients to have computed subsidiary values such as
  179928. * the per-component width and height fields in the destination object.
  179929. *
  179930. * Note that some transformations will modify the source data arrays!
  179931. */
  179932. GLOBAL(void)
  179933. jtransform_execute_transformation (j_decompress_ptr srcinfo,
  179934. j_compress_ptr dstinfo,
  179935. jvirt_barray_ptr *src_coef_arrays,
  179936. jpeg_transform_info *info)
  179937. {
  179938. jvirt_barray_ptr *dst_coef_arrays = info->workspace_coef_arrays;
  179939. switch (info->transform) {
  179940. case JXFORM_NONE:
  179941. break;
  179942. case JXFORM_FLIP_H:
  179943. do_flip_h(srcinfo, dstinfo, src_coef_arrays);
  179944. break;
  179945. case JXFORM_FLIP_V:
  179946. do_flip_v(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179947. break;
  179948. case JXFORM_TRANSPOSE:
  179949. do_transpose(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179950. break;
  179951. case JXFORM_TRANSVERSE:
  179952. do_transverse(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179953. break;
  179954. case JXFORM_ROT_90:
  179955. do_rot_90(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179956. break;
  179957. case JXFORM_ROT_180:
  179958. do_rot_180(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179959. break;
  179960. case JXFORM_ROT_270:
  179961. do_rot_270(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179962. break;
  179963. }
  179964. }
  179965. #endif /* TRANSFORMS_SUPPORTED */
  179966. /* Setup decompression object to save desired markers in memory.
  179967. * This must be called before jpeg_read_header() to have the desired effect.
  179968. */
  179969. GLOBAL(void)
  179970. jcopy_markers_setup (j_decompress_ptr srcinfo, JCOPY_OPTION option)
  179971. {
  179972. #ifdef SAVE_MARKERS_SUPPORTED
  179973. int m;
  179974. /* Save comments except under NONE option */
  179975. if (option != JCOPYOPT_NONE) {
  179976. jpeg_save_markers(srcinfo, JPEG_COM, 0xFFFF);
  179977. }
  179978. /* Save all types of APPn markers iff ALL option */
  179979. if (option == JCOPYOPT_ALL) {
  179980. for (m = 0; m < 16; m++)
  179981. jpeg_save_markers(srcinfo, JPEG_APP0 + m, 0xFFFF);
  179982. }
  179983. #endif /* SAVE_MARKERS_SUPPORTED */
  179984. }
  179985. /* Copy markers saved in the given source object to the destination object.
  179986. * This should be called just after jpeg_start_compress() or
  179987. * jpeg_write_coefficients().
  179988. * Note that those routines will have written the SOI, and also the
  179989. * JFIF APP0 or Adobe APP14 markers if selected.
  179990. */
  179991. GLOBAL(void)
  179992. jcopy_markers_execute (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179993. JCOPY_OPTION)
  179994. {
  179995. jpeg_saved_marker_ptr marker;
  179996. /* In the current implementation, we don't actually need to examine the
  179997. * option flag here; we just copy everything that got saved.
  179998. * But to avoid confusion, we do not output JFIF and Adobe APP14 markers
  179999. * if the encoder library already wrote one.
  180000. */
  180001. for (marker = srcinfo->marker_list; marker != NULL; marker = marker->next) {
  180002. if (dstinfo->write_JFIF_header &&
  180003. marker->marker == JPEG_APP0 &&
  180004. marker->data_length >= 5 &&
  180005. GETJOCTET(marker->data[0]) == 0x4A &&
  180006. GETJOCTET(marker->data[1]) == 0x46 &&
  180007. GETJOCTET(marker->data[2]) == 0x49 &&
  180008. GETJOCTET(marker->data[3]) == 0x46 &&
  180009. GETJOCTET(marker->data[4]) == 0)
  180010. continue; /* reject duplicate JFIF */
  180011. if (dstinfo->write_Adobe_marker &&
  180012. marker->marker == JPEG_APP0+14 &&
  180013. marker->data_length >= 5 &&
  180014. GETJOCTET(marker->data[0]) == 0x41 &&
  180015. GETJOCTET(marker->data[1]) == 0x64 &&
  180016. GETJOCTET(marker->data[2]) == 0x6F &&
  180017. GETJOCTET(marker->data[3]) == 0x62 &&
  180018. GETJOCTET(marker->data[4]) == 0x65)
  180019. continue; /* reject duplicate Adobe */
  180020. #ifdef NEED_FAR_POINTERS
  180021. /* We could use jpeg_write_marker if the data weren't FAR... */
  180022. {
  180023. unsigned int i;
  180024. jpeg_write_m_header(dstinfo, marker->marker, marker->data_length);
  180025. for (i = 0; i < marker->data_length; i++)
  180026. jpeg_write_m_byte(dstinfo, marker->data[i]);
  180027. }
  180028. #else
  180029. jpeg_write_marker(dstinfo, marker->marker,
  180030. marker->data, marker->data_length);
  180031. #endif
  180032. }
  180033. }
  180034. /*** End of inlined file: transupp.c ***/
  180035. #else
  180036. #define JPEG_INTERNALS
  180037. #undef FAR
  180038. #include <jpeglib.h>
  180039. #endif
  180040. }
  180041. #undef max
  180042. #undef min
  180043. #if JUCE_MSVC
  180044. #pragma warning (pop)
  180045. #endif
  180046. BEGIN_JUCE_NAMESPACE
  180047. namespace JPEGHelpers
  180048. {
  180049. using namespace jpeglibNamespace;
  180050. #if ! JUCE_MSVC
  180051. using jpeglibNamespace::boolean;
  180052. #endif
  180053. struct JPEGDecodingFailure {};
  180054. static void fatalErrorHandler (j_common_ptr)
  180055. {
  180056. throw JPEGDecodingFailure();
  180057. }
  180058. static void silentErrorCallback1 (j_common_ptr) {}
  180059. static void silentErrorCallback2 (j_common_ptr, int) {}
  180060. static void silentErrorCallback3 (j_common_ptr, char*) {}
  180061. static void setupSilentErrorHandler (struct jpeg_error_mgr& err)
  180062. {
  180063. zerostruct (err);
  180064. err.error_exit = fatalErrorHandler;
  180065. err.emit_message = silentErrorCallback2;
  180066. err.output_message = silentErrorCallback1;
  180067. err.format_message = silentErrorCallback3;
  180068. err.reset_error_mgr = silentErrorCallback1;
  180069. }
  180070. static void dummyCallback1 (j_decompress_ptr)
  180071. {
  180072. }
  180073. static void jpegSkip (j_decompress_ptr decompStruct, long num)
  180074. {
  180075. decompStruct->src->next_input_byte += num;
  180076. num = jmin (num, (long) decompStruct->src->bytes_in_buffer);
  180077. decompStruct->src->bytes_in_buffer -= num;
  180078. }
  180079. static boolean jpegFill (j_decompress_ptr)
  180080. {
  180081. return 0;
  180082. }
  180083. static const int jpegBufferSize = 512;
  180084. struct JuceJpegDest : public jpeg_destination_mgr
  180085. {
  180086. OutputStream* output;
  180087. char* buffer;
  180088. };
  180089. static void jpegWriteInit (j_compress_ptr)
  180090. {
  180091. }
  180092. static void jpegWriteTerminate (j_compress_ptr cinfo)
  180093. {
  180094. JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest);
  180095. const size_t numToWrite = jpegBufferSize - dest->free_in_buffer;
  180096. dest->output->write (dest->buffer, (int) numToWrite);
  180097. }
  180098. static boolean jpegWriteFlush (j_compress_ptr cinfo)
  180099. {
  180100. JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest);
  180101. const int numToWrite = jpegBufferSize;
  180102. dest->next_output_byte = reinterpret_cast <JOCTET*> (dest->buffer);
  180103. dest->free_in_buffer = jpegBufferSize;
  180104. return dest->output->write (dest->buffer, numToWrite);
  180105. }
  180106. }
  180107. JPEGImageFormat::JPEGImageFormat()
  180108. : quality (-1.0f)
  180109. {
  180110. }
  180111. JPEGImageFormat::~JPEGImageFormat() {}
  180112. void JPEGImageFormat::setQuality (const float newQuality)
  180113. {
  180114. quality = newQuality;
  180115. }
  180116. const String JPEGImageFormat::getFormatName()
  180117. {
  180118. return "JPEG";
  180119. }
  180120. bool JPEGImageFormat::canUnderstand (InputStream& in)
  180121. {
  180122. const int bytesNeeded = 10;
  180123. uint8 header [bytesNeeded];
  180124. if (in.read (header, bytesNeeded) == bytesNeeded)
  180125. {
  180126. return header[0] == 0xff
  180127. && header[1] == 0xd8
  180128. && header[2] == 0xff
  180129. && (header[3] == 0xe0 || header[3] == 0xe1);
  180130. }
  180131. return false;
  180132. }
  180133. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  180134. const Image juce_loadWithCoreImage (InputStream& input);
  180135. #endif
  180136. const Image JPEGImageFormat::decodeImage (InputStream& in)
  180137. {
  180138. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  180139. return juce_loadWithCoreImage (in);
  180140. #else
  180141. using namespace jpeglibNamespace;
  180142. using namespace JPEGHelpers;
  180143. MemoryOutputStream mb;
  180144. mb.writeFromInputStream (in, -1);
  180145. Image image;
  180146. if (mb.getDataSize() > 16)
  180147. {
  180148. struct jpeg_decompress_struct jpegDecompStruct;
  180149. struct jpeg_error_mgr jerr;
  180150. setupSilentErrorHandler (jerr);
  180151. jpegDecompStruct.err = &jerr;
  180152. jpeg_create_decompress (&jpegDecompStruct);
  180153. jpegDecompStruct.src = (jpeg_source_mgr*)(jpegDecompStruct.mem->alloc_small)
  180154. ((j_common_ptr)(&jpegDecompStruct), JPOOL_PERMANENT, sizeof (jpeg_source_mgr));
  180155. jpegDecompStruct.src->init_source = dummyCallback1;
  180156. jpegDecompStruct.src->fill_input_buffer = jpegFill;
  180157. jpegDecompStruct.src->skip_input_data = jpegSkip;
  180158. jpegDecompStruct.src->resync_to_restart = jpeg_resync_to_restart;
  180159. jpegDecompStruct.src->term_source = dummyCallback1;
  180160. jpegDecompStruct.src->next_input_byte = static_cast <const unsigned char*> (mb.getData());
  180161. jpegDecompStruct.src->bytes_in_buffer = mb.getDataSize();
  180162. try
  180163. {
  180164. jpeg_read_header (&jpegDecompStruct, TRUE);
  180165. jpeg_calc_output_dimensions (&jpegDecompStruct);
  180166. const int width = jpegDecompStruct.output_width;
  180167. const int height = jpegDecompStruct.output_height;
  180168. jpegDecompStruct.out_color_space = JCS_RGB;
  180169. JSAMPARRAY buffer
  180170. = (*jpegDecompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegDecompStruct,
  180171. JPOOL_IMAGE,
  180172. width * 3, 1);
  180173. if (jpeg_start_decompress (&jpegDecompStruct))
  180174. {
  180175. image = Image (Image::RGB, width, height, false);
  180176. image.getProperties()->set ("originalImageHadAlpha", false);
  180177. const bool hasAlphaChan = image.hasAlphaChannel(); // (the native image creator may not give back what we expect)
  180178. const Image::BitmapData destData (image, true);
  180179. for (int y = 0; y < height; ++y)
  180180. {
  180181. jpeg_read_scanlines (&jpegDecompStruct, buffer, 1);
  180182. const uint8* src = *buffer;
  180183. uint8* dest = destData.getLinePointer (y);
  180184. if (hasAlphaChan)
  180185. {
  180186. for (int i = width; --i >= 0;)
  180187. {
  180188. ((PixelARGB*) dest)->setARGB (0xff, src[0], src[1], src[2]);
  180189. ((PixelARGB*) dest)->premultiply();
  180190. dest += destData.pixelStride;
  180191. src += 3;
  180192. }
  180193. }
  180194. else
  180195. {
  180196. for (int i = width; --i >= 0;)
  180197. {
  180198. ((PixelRGB*) dest)->setARGB (0xff, src[0], src[1], src[2]);
  180199. dest += destData.pixelStride;
  180200. src += 3;
  180201. }
  180202. }
  180203. }
  180204. jpeg_finish_decompress (&jpegDecompStruct);
  180205. in.setPosition (((char*) jpegDecompStruct.src->next_input_byte) - (char*) mb.getData());
  180206. }
  180207. jpeg_destroy_decompress (&jpegDecompStruct);
  180208. }
  180209. catch (...)
  180210. {}
  180211. }
  180212. return image;
  180213. #endif
  180214. }
  180215. bool JPEGImageFormat::writeImageToStream (const Image& image, OutputStream& out)
  180216. {
  180217. using namespace jpeglibNamespace;
  180218. using namespace JPEGHelpers;
  180219. if (image.hasAlphaChannel())
  180220. {
  180221. // this method could fill the background in white and still save the image..
  180222. jassertfalse;
  180223. return true;
  180224. }
  180225. struct jpeg_compress_struct jpegCompStruct;
  180226. struct jpeg_error_mgr jerr;
  180227. setupSilentErrorHandler (jerr);
  180228. jpegCompStruct.err = &jerr;
  180229. jpeg_create_compress (&jpegCompStruct);
  180230. JuceJpegDest dest;
  180231. jpegCompStruct.dest = &dest;
  180232. dest.output = &out;
  180233. HeapBlock <char> tempBuffer (jpegBufferSize);
  180234. dest.buffer = tempBuffer;
  180235. dest.next_output_byte = (JOCTET*) dest.buffer;
  180236. dest.free_in_buffer = jpegBufferSize;
  180237. dest.init_destination = jpegWriteInit;
  180238. dest.empty_output_buffer = jpegWriteFlush;
  180239. dest.term_destination = jpegWriteTerminate;
  180240. jpegCompStruct.image_width = image.getWidth();
  180241. jpegCompStruct.image_height = image.getHeight();
  180242. jpegCompStruct.input_components = 3;
  180243. jpegCompStruct.in_color_space = JCS_RGB;
  180244. jpegCompStruct.write_JFIF_header = 1;
  180245. jpegCompStruct.X_density = 72;
  180246. jpegCompStruct.Y_density = 72;
  180247. jpeg_set_defaults (&jpegCompStruct);
  180248. jpegCompStruct.dct_method = JDCT_FLOAT;
  180249. jpegCompStruct.optimize_coding = 1;
  180250. //jpegCompStruct.smoothing_factor = 10;
  180251. if (quality < 0.0f)
  180252. quality = 0.85f;
  180253. jpeg_set_quality (&jpegCompStruct, jlimit (0, 100, roundToInt (quality * 100.0f)), TRUE);
  180254. jpeg_start_compress (&jpegCompStruct, TRUE);
  180255. const int strideBytes = jpegCompStruct.image_width * jpegCompStruct.input_components;
  180256. JSAMPARRAY buffer = (*jpegCompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegCompStruct,
  180257. JPOOL_IMAGE, strideBytes, 1);
  180258. const Image::BitmapData srcData (image, false);
  180259. while (jpegCompStruct.next_scanline < jpegCompStruct.image_height)
  180260. {
  180261. const uint8* src = srcData.getLinePointer (jpegCompStruct.next_scanline);
  180262. uint8* dst = *buffer;
  180263. for (int i = jpegCompStruct.image_width; --i >= 0;)
  180264. {
  180265. *dst++ = ((const PixelRGB*) src)->getRed();
  180266. *dst++ = ((const PixelRGB*) src)->getGreen();
  180267. *dst++ = ((const PixelRGB*) src)->getBlue();
  180268. src += srcData.pixelStride;
  180269. }
  180270. jpeg_write_scanlines (&jpegCompStruct, buffer, 1);
  180271. }
  180272. jpeg_finish_compress (&jpegCompStruct);
  180273. jpeg_destroy_compress (&jpegCompStruct);
  180274. out.flush();
  180275. return true;
  180276. }
  180277. END_JUCE_NAMESPACE
  180278. /*** End of inlined file: juce_JPEGLoader.cpp ***/
  180279. /*** Start of inlined file: juce_PNGLoader.cpp ***/
  180280. #if JUCE_MSVC
  180281. #pragma warning (push)
  180282. #pragma warning (disable: 4390 4611)
  180283. #endif
  180284. namespace zlibNamespace
  180285. {
  180286. #if JUCE_INCLUDE_ZLIB_CODE
  180287. #undef OS_CODE
  180288. #undef fdopen
  180289. #undef OS_CODE
  180290. #else
  180291. #include <zlib.h>
  180292. #endif
  180293. }
  180294. namespace pnglibNamespace
  180295. {
  180296. using namespace zlibNamespace;
  180297. #if JUCE_INCLUDE_PNGLIB_CODE
  180298. #if _MSC_VER != 1310
  180299. using ::calloc; // (causes conflict in VS.NET 2003)
  180300. using ::malloc;
  180301. using ::free;
  180302. #endif
  180303. using ::abs;
  180304. #define PNG_INTERNAL
  180305. #define NO_DUMMY_DECL
  180306. #define PNG_SETJMP_NOT_SUPPORTED
  180307. /*** Start of inlined file: png.h ***/
  180308. /* png.h - header file for PNG reference library
  180309. *
  180310. * libpng version 1.2.21 - October 4, 2007
  180311. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  180312. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  180313. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  180314. *
  180315. * Authors and maintainers:
  180316. * libpng versions 0.71, May 1995, through 0.88, January 1996: Guy Schalnat
  180317. * libpng versions 0.89c, June 1996, through 0.96, May 1997: Andreas Dilger
  180318. * libpng versions 0.97, January 1998, through 1.2.21 - October 4, 2007: Glenn
  180319. * See also "Contributing Authors", below.
  180320. *
  180321. * Note about libpng version numbers:
  180322. *
  180323. * Due to various miscommunications, unforeseen code incompatibilities
  180324. * and occasional factors outside the authors' control, version numbering
  180325. * on the library has not always been consistent and straightforward.
  180326. * The following table summarizes matters since version 0.89c, which was
  180327. * the first widely used release:
  180328. *
  180329. * source png.h png.h shared-lib
  180330. * version string int version
  180331. * ------- ------ ----- ----------
  180332. * 0.89c "1.0 beta 3" 0.89 89 1.0.89
  180333. * 0.90 "1.0 beta 4" 0.90 90 0.90 [should have been 2.0.90]
  180334. * 0.95 "1.0 beta 5" 0.95 95 0.95 [should have been 2.0.95]
  180335. * 0.96 "1.0 beta 6" 0.96 96 0.96 [should have been 2.0.96]
  180336. * 0.97b "1.00.97 beta 7" 1.00.97 97 1.0.1 [should have been 2.0.97]
  180337. * 0.97c 0.97 97 2.0.97
  180338. * 0.98 0.98 98 2.0.98
  180339. * 0.99 0.99 98 2.0.99
  180340. * 0.99a-m 0.99 99 2.0.99
  180341. * 1.00 1.00 100 2.1.0 [100 should be 10000]
  180342. * 1.0.0 (from here on, the 100 2.1.0 [100 should be 10000]
  180343. * 1.0.1 png.h string is 10001 2.1.0
  180344. * 1.0.1a-e identical to the 10002 from here on, the shared library
  180345. * 1.0.2 source version) 10002 is 2.V where V is the source code
  180346. * 1.0.2a-b 10003 version, except as noted.
  180347. * 1.0.3 10003
  180348. * 1.0.3a-d 10004
  180349. * 1.0.4 10004
  180350. * 1.0.4a-f 10005
  180351. * 1.0.5 (+ 2 patches) 10005
  180352. * 1.0.5a-d 10006
  180353. * 1.0.5e-r 10100 (not source compatible)
  180354. * 1.0.5s-v 10006 (not binary compatible)
  180355. * 1.0.6 (+ 3 patches) 10006 (still binary incompatible)
  180356. * 1.0.6d-f 10007 (still binary incompatible)
  180357. * 1.0.6g 10007
  180358. * 1.0.6h 10007 10.6h (testing xy.z so-numbering)
  180359. * 1.0.6i 10007 10.6i
  180360. * 1.0.6j 10007 2.1.0.6j (incompatible with 1.0.0)
  180361. * 1.0.7beta11-14 DLLNUM 10007 2.1.0.7beta11-14 (binary compatible)
  180362. * 1.0.7beta15-18 1 10007 2.1.0.7beta15-18 (binary compatible)
  180363. * 1.0.7rc1-2 1 10007 2.1.0.7rc1-2 (binary compatible)
  180364. * 1.0.7 1 10007 (still compatible)
  180365. * 1.0.8beta1-4 1 10008 2.1.0.8beta1-4
  180366. * 1.0.8rc1 1 10008 2.1.0.8rc1
  180367. * 1.0.8 1 10008 2.1.0.8
  180368. * 1.0.9beta1-6 1 10009 2.1.0.9beta1-6
  180369. * 1.0.9rc1 1 10009 2.1.0.9rc1
  180370. * 1.0.9beta7-10 1 10009 2.1.0.9beta7-10
  180371. * 1.0.9rc2 1 10009 2.1.0.9rc2
  180372. * 1.0.9 1 10009 2.1.0.9
  180373. * 1.0.10beta1 1 10010 2.1.0.10beta1
  180374. * 1.0.10rc1 1 10010 2.1.0.10rc1
  180375. * 1.0.10 1 10010 2.1.0.10
  180376. * 1.0.11beta1-3 1 10011 2.1.0.11beta1-3
  180377. * 1.0.11rc1 1 10011 2.1.0.11rc1
  180378. * 1.0.11 1 10011 2.1.0.11
  180379. * 1.0.12beta1-2 2 10012 2.1.0.12beta1-2
  180380. * 1.0.12rc1 2 10012 2.1.0.12rc1
  180381. * 1.0.12 2 10012 2.1.0.12
  180382. * 1.1.0a-f - 10100 2.1.1.0a-f (branch abandoned)
  180383. * 1.2.0beta1-2 2 10200 2.1.2.0beta1-2
  180384. * 1.2.0beta3-5 3 10200 3.1.2.0beta3-5
  180385. * 1.2.0rc1 3 10200 3.1.2.0rc1
  180386. * 1.2.0 3 10200 3.1.2.0
  180387. * 1.2.1beta1-4 3 10201 3.1.2.1beta1-4
  180388. * 1.2.1rc1-2 3 10201 3.1.2.1rc1-2
  180389. * 1.2.1 3 10201 3.1.2.1
  180390. * 1.2.2beta1-6 12 10202 12.so.0.1.2.2beta1-6
  180391. * 1.0.13beta1 10 10013 10.so.0.1.0.13beta1
  180392. * 1.0.13rc1 10 10013 10.so.0.1.0.13rc1
  180393. * 1.2.2rc1 12 10202 12.so.0.1.2.2rc1
  180394. * 1.0.13 10 10013 10.so.0.1.0.13
  180395. * 1.2.2 12 10202 12.so.0.1.2.2
  180396. * 1.2.3rc1-6 12 10203 12.so.0.1.2.3rc1-6
  180397. * 1.2.3 12 10203 12.so.0.1.2.3
  180398. * 1.2.4beta1-3 13 10204 12.so.0.1.2.4beta1-3
  180399. * 1.0.14rc1 13 10014 10.so.0.1.0.14rc1
  180400. * 1.2.4rc1 13 10204 12.so.0.1.2.4rc1
  180401. * 1.0.14 10 10014 10.so.0.1.0.14
  180402. * 1.2.4 13 10204 12.so.0.1.2.4
  180403. * 1.2.5beta1-2 13 10205 12.so.0.1.2.5beta1-2
  180404. * 1.0.15rc1-3 10 10015 10.so.0.1.0.15rc1-3
  180405. * 1.2.5rc1-3 13 10205 12.so.0.1.2.5rc1-3
  180406. * 1.0.15 10 10015 10.so.0.1.0.15
  180407. * 1.2.5 13 10205 12.so.0.1.2.5
  180408. * 1.2.6beta1-4 13 10206 12.so.0.1.2.6beta1-4
  180409. * 1.0.16 10 10016 10.so.0.1.0.16
  180410. * 1.2.6 13 10206 12.so.0.1.2.6
  180411. * 1.2.7beta1-2 13 10207 12.so.0.1.2.7beta1-2
  180412. * 1.0.17rc1 10 10017 10.so.0.1.0.17rc1
  180413. * 1.2.7rc1 13 10207 12.so.0.1.2.7rc1
  180414. * 1.0.17 10 10017 10.so.0.1.0.17
  180415. * 1.2.7 13 10207 12.so.0.1.2.7
  180416. * 1.2.8beta1-5 13 10208 12.so.0.1.2.8beta1-5
  180417. * 1.0.18rc1-5 10 10018 10.so.0.1.0.18rc1-5
  180418. * 1.2.8rc1-5 13 10208 12.so.0.1.2.8rc1-5
  180419. * 1.0.18 10 10018 10.so.0.1.0.18
  180420. * 1.2.8 13 10208 12.so.0.1.2.8
  180421. * 1.2.9beta1-3 13 10209 12.so.0.1.2.9beta1-3
  180422. * 1.2.9beta4-11 13 10209 12.so.0.9[.0]
  180423. * 1.2.9rc1 13 10209 12.so.0.9[.0]
  180424. * 1.2.9 13 10209 12.so.0.9[.0]
  180425. * 1.2.10beta1-8 13 10210 12.so.0.10[.0]
  180426. * 1.2.10rc1-3 13 10210 12.so.0.10[.0]
  180427. * 1.2.10 13 10210 12.so.0.10[.0]
  180428. * 1.2.11beta1-4 13 10211 12.so.0.11[.0]
  180429. * 1.0.19rc1-5 10 10019 10.so.0.19[.0]
  180430. * 1.2.11rc1-5 13 10211 12.so.0.11[.0]
  180431. * 1.0.19 10 10019 10.so.0.19[.0]
  180432. * 1.2.11 13 10211 12.so.0.11[.0]
  180433. * 1.0.20 10 10020 10.so.0.20[.0]
  180434. * 1.2.12 13 10212 12.so.0.12[.0]
  180435. * 1.2.13beta1 13 10213 12.so.0.13[.0]
  180436. * 1.0.21 10 10021 10.so.0.21[.0]
  180437. * 1.2.13 13 10213 12.so.0.13[.0]
  180438. * 1.2.14beta1-2 13 10214 12.so.0.14[.0]
  180439. * 1.0.22rc1 10 10022 10.so.0.22[.0]
  180440. * 1.2.14rc1 13 10214 12.so.0.14[.0]
  180441. * 1.0.22 10 10022 10.so.0.22[.0]
  180442. * 1.2.14 13 10214 12.so.0.14[.0]
  180443. * 1.2.15beta1-6 13 10215 12.so.0.15[.0]
  180444. * 1.0.23rc1-5 10 10023 10.so.0.23[.0]
  180445. * 1.2.15rc1-5 13 10215 12.so.0.15[.0]
  180446. * 1.0.23 10 10023 10.so.0.23[.0]
  180447. * 1.2.15 13 10215 12.so.0.15[.0]
  180448. * 1.2.16beta1-2 13 10216 12.so.0.16[.0]
  180449. * 1.2.16rc1 13 10216 12.so.0.16[.0]
  180450. * 1.0.24 10 10024 10.so.0.24[.0]
  180451. * 1.2.16 13 10216 12.so.0.16[.0]
  180452. * 1.2.17beta1-2 13 10217 12.so.0.17[.0]
  180453. * 1.0.25rc1 10 10025 10.so.0.25[.0]
  180454. * 1.2.17rc1-3 13 10217 12.so.0.17[.0]
  180455. * 1.0.25 10 10025 10.so.0.25[.0]
  180456. * 1.2.17 13 10217 12.so.0.17[.0]
  180457. * 1.0.26 10 10026 10.so.0.26[.0]
  180458. * 1.2.18 13 10218 12.so.0.18[.0]
  180459. * 1.2.19beta1-31 13 10219 12.so.0.19[.0]
  180460. * 1.0.27rc1-6 10 10027 10.so.0.27[.0]
  180461. * 1.2.19rc1-6 13 10219 12.so.0.19[.0]
  180462. * 1.0.27 10 10027 10.so.0.27[.0]
  180463. * 1.2.19 13 10219 12.so.0.19[.0]
  180464. * 1.2.20beta01-04 13 10220 12.so.0.20[.0]
  180465. * 1.0.28rc1-6 10 10028 10.so.0.28[.0]
  180466. * 1.2.20rc1-6 13 10220 12.so.0.20[.0]
  180467. * 1.0.28 10 10028 10.so.0.28[.0]
  180468. * 1.2.20 13 10220 12.so.0.20[.0]
  180469. * 1.2.21beta1-2 13 10221 12.so.0.21[.0]
  180470. * 1.2.21rc1-3 13 10221 12.so.0.21[.0]
  180471. * 1.0.29 10 10029 10.so.0.29[.0]
  180472. * 1.2.21 13 10221 12.so.0.21[.0]
  180473. *
  180474. * Henceforth the source version will match the shared-library major
  180475. * and minor numbers; the shared-library major version number will be
  180476. * used for changes in backward compatibility, as it is intended. The
  180477. * PNG_LIBPNG_VER macro, which is not used within libpng but is available
  180478. * for applications, is an unsigned integer of the form xyyzz corresponding
  180479. * to the source version x.y.z (leading zeros in y and z). Beta versions
  180480. * were given the previous public release number plus a letter, until
  180481. * version 1.0.6j; from then on they were given the upcoming public
  180482. * release number plus "betaNN" or "rcN".
  180483. *
  180484. * Binary incompatibility exists only when applications make direct access
  180485. * to the info_ptr or png_ptr members through png.h, and the compiled
  180486. * application is loaded with a different version of the library.
  180487. *
  180488. * DLLNUM will change each time there are forward or backward changes
  180489. * in binary compatibility (e.g., when a new feature is added).
  180490. *
  180491. * See libpng.txt or libpng.3 for more information. The PNG specification
  180492. * is available as a W3C Recommendation and as an ISO Specification,
  180493. * <http://www.w3.org/TR/2003/REC-PNG-20031110/
  180494. */
  180495. /*
  180496. * COPYRIGHT NOTICE, DISCLAIMER, and LICENSE:
  180497. *
  180498. * If you modify libpng you may insert additional notices immediately following
  180499. * this sentence.
  180500. *
  180501. * libpng versions 1.2.6, August 15, 2004, through 1.2.21, October 4, 2007, are
  180502. * Copyright (c) 2004, 2006-2007 Glenn Randers-Pehrson, and are
  180503. * distributed according to the same disclaimer and license as libpng-1.2.5
  180504. * with the following individual added to the list of Contributing Authors:
  180505. *
  180506. * Cosmin Truta
  180507. *
  180508. * libpng versions 1.0.7, July 1, 2000, through 1.2.5, October 3, 2002, are
  180509. * Copyright (c) 2000-2002 Glenn Randers-Pehrson, and are
  180510. * distributed according to the same disclaimer and license as libpng-1.0.6
  180511. * with the following individuals added to the list of Contributing Authors:
  180512. *
  180513. * Simon-Pierre Cadieux
  180514. * Eric S. Raymond
  180515. * Gilles Vollant
  180516. *
  180517. * and with the following additions to the disclaimer:
  180518. *
  180519. * There is no warranty against interference with your enjoyment of the
  180520. * library or against infringement. There is no warranty that our
  180521. * efforts or the library will fulfill any of your particular purposes
  180522. * or needs. This library is provided with all faults, and the entire
  180523. * risk of satisfactory quality, performance, accuracy, and effort is with
  180524. * the user.
  180525. *
  180526. * libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are
  180527. * Copyright (c) 1998, 1999, 2000 Glenn Randers-Pehrson, and are
  180528. * distributed according to the same disclaimer and license as libpng-0.96,
  180529. * with the following individuals added to the list of Contributing Authors:
  180530. *
  180531. * Tom Lane
  180532. * Glenn Randers-Pehrson
  180533. * Willem van Schaik
  180534. *
  180535. * libpng versions 0.89, June 1996, through 0.96, May 1997, are
  180536. * Copyright (c) 1996, 1997 Andreas Dilger
  180537. * Distributed according to the same disclaimer and license as libpng-0.88,
  180538. * with the following individuals added to the list of Contributing Authors:
  180539. *
  180540. * John Bowler
  180541. * Kevin Bracey
  180542. * Sam Bushell
  180543. * Magnus Holmgren
  180544. * Greg Roelofs
  180545. * Tom Tanner
  180546. *
  180547. * libpng versions 0.5, May 1995, through 0.88, January 1996, are
  180548. * Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.
  180549. *
  180550. * For the purposes of this copyright and license, "Contributing Authors"
  180551. * is defined as the following set of individuals:
  180552. *
  180553. * Andreas Dilger
  180554. * Dave Martindale
  180555. * Guy Eric Schalnat
  180556. * Paul Schmidt
  180557. * Tim Wegner
  180558. *
  180559. * The PNG Reference Library is supplied "AS IS". The Contributing Authors
  180560. * and Group 42, Inc. disclaim all warranties, expressed or implied,
  180561. * including, without limitation, the warranties of merchantability and of
  180562. * fitness for any purpose. The Contributing Authors and Group 42, Inc.
  180563. * assume no liability for direct, indirect, incidental, special, exemplary,
  180564. * or consequential damages, which may result from the use of the PNG
  180565. * Reference Library, even if advised of the possibility of such damage.
  180566. *
  180567. * Permission is hereby granted to use, copy, modify, and distribute this
  180568. * source code, or portions hereof, for any purpose, without fee, subject
  180569. * to the following restrictions:
  180570. *
  180571. * 1. The origin of this source code must not be misrepresented.
  180572. *
  180573. * 2. Altered versions must be plainly marked as such and
  180574. * must not be misrepresented as being the original source.
  180575. *
  180576. * 3. This Copyright notice may not be removed or altered from
  180577. * any source or altered source distribution.
  180578. *
  180579. * The Contributing Authors and Group 42, Inc. specifically permit, without
  180580. * fee, and encourage the use of this source code as a component to
  180581. * supporting the PNG file format in commercial products. If you use this
  180582. * source code in a product, acknowledgment is not required but would be
  180583. * appreciated.
  180584. */
  180585. /*
  180586. * A "png_get_copyright" function is available, for convenient use in "about"
  180587. * boxes and the like:
  180588. *
  180589. * printf("%s",png_get_copyright(NULL));
  180590. *
  180591. * Also, the PNG logo (in PNG format, of course) is supplied in the
  180592. * files "pngbar.png" and "pngbar.jpg (88x31) and "pngnow.png" (98x31).
  180593. */
  180594. /*
  180595. * Libpng is OSI Certified Open Source Software. OSI Certified is a
  180596. * certification mark of the Open Source Initiative.
  180597. */
  180598. /*
  180599. * The contributing authors would like to thank all those who helped
  180600. * with testing, bug fixes, and patience. This wouldn't have been
  180601. * possible without all of you.
  180602. *
  180603. * Thanks to Frank J. T. Wojcik for helping with the documentation.
  180604. */
  180605. /*
  180606. * Y2K compliance in libpng:
  180607. * =========================
  180608. *
  180609. * October 4, 2007
  180610. *
  180611. * Since the PNG Development group is an ad-hoc body, we can't make
  180612. * an official declaration.
  180613. *
  180614. * This is your unofficial assurance that libpng from version 0.71 and
  180615. * upward through 1.2.21 are Y2K compliant. It is my belief that earlier
  180616. * versions were also Y2K compliant.
  180617. *
  180618. * Libpng only has three year fields. One is a 2-byte unsigned integer
  180619. * that will hold years up to 65535. The other two hold the date in text
  180620. * format, and will hold years up to 9999.
  180621. *
  180622. * The integer is
  180623. * "png_uint_16 year" in png_time_struct.
  180624. *
  180625. * The strings are
  180626. * "png_charp time_buffer" in png_struct and
  180627. * "near_time_buffer", which is a local character string in png.c.
  180628. *
  180629. * There are seven time-related functions:
  180630. * png.c: png_convert_to_rfc_1123() in png.c
  180631. * (formerly png_convert_to_rfc_1152() in error)
  180632. * png_convert_from_struct_tm() in pngwrite.c, called in pngwrite.c
  180633. * png_convert_from_time_t() in pngwrite.c
  180634. * png_get_tIME() in pngget.c
  180635. * png_handle_tIME() in pngrutil.c, called in pngread.c
  180636. * png_set_tIME() in pngset.c
  180637. * png_write_tIME() in pngwutil.c, called in pngwrite.c
  180638. *
  180639. * All handle dates properly in a Y2K environment. The
  180640. * png_convert_from_time_t() function calls gmtime() to convert from system
  180641. * clock time, which returns (year - 1900), which we properly convert to
  180642. * the full 4-digit year. There is a possibility that applications using
  180643. * libpng are not passing 4-digit years into the png_convert_to_rfc_1123()
  180644. * function, or that they are incorrectly passing only a 2-digit year
  180645. * instead of "year - 1900" into the png_convert_from_struct_tm() function,
  180646. * but this is not under our control. The libpng documentation has always
  180647. * stated that it works with 4-digit years, and the APIs have been
  180648. * documented as such.
  180649. *
  180650. * The tIME chunk itself is also Y2K compliant. It uses a 2-byte unsigned
  180651. * integer to hold the year, and can hold years as large as 65535.
  180652. *
  180653. * zlib, upon which libpng depends, is also Y2K compliant. It contains
  180654. * no date-related code.
  180655. *
  180656. * Glenn Randers-Pehrson
  180657. * libpng maintainer
  180658. * PNG Development Group
  180659. */
  180660. #ifndef PNG_H
  180661. #define PNG_H
  180662. /* This is not the place to learn how to use libpng. The file libpng.txt
  180663. * describes how to use libpng, and the file example.c summarizes it
  180664. * with some code on which to build. This file is useful for looking
  180665. * at the actual function definitions and structure components.
  180666. */
  180667. /* Version information for png.h - this should match the version in png.c */
  180668. #define PNG_LIBPNG_VER_STRING "1.2.21"
  180669. #define PNG_HEADER_VERSION_STRING \
  180670. " libpng version 1.2.21 - October 4, 2007\n"
  180671. #define PNG_LIBPNG_VER_SONUM 0
  180672. #define PNG_LIBPNG_VER_DLLNUM 13
  180673. /* These should match the first 3 components of PNG_LIBPNG_VER_STRING: */
  180674. #define PNG_LIBPNG_VER_MAJOR 1
  180675. #define PNG_LIBPNG_VER_MINOR 2
  180676. #define PNG_LIBPNG_VER_RELEASE 21
  180677. /* This should match the numeric part of the final component of
  180678. * PNG_LIBPNG_VER_STRING, omitting any leading zero: */
  180679. #define PNG_LIBPNG_VER_BUILD 0
  180680. /* Release Status */
  180681. #define PNG_LIBPNG_BUILD_ALPHA 1
  180682. #define PNG_LIBPNG_BUILD_BETA 2
  180683. #define PNG_LIBPNG_BUILD_RC 3
  180684. #define PNG_LIBPNG_BUILD_STABLE 4
  180685. #define PNG_LIBPNG_BUILD_RELEASE_STATUS_MASK 7
  180686. /* Release-Specific Flags */
  180687. #define PNG_LIBPNG_BUILD_PATCH 8 /* Can be OR'ed with
  180688. PNG_LIBPNG_BUILD_STABLE only */
  180689. #define PNG_LIBPNG_BUILD_PRIVATE 16 /* Cannot be OR'ed with
  180690. PNG_LIBPNG_BUILD_SPECIAL */
  180691. #define PNG_LIBPNG_BUILD_SPECIAL 32 /* Cannot be OR'ed with
  180692. PNG_LIBPNG_BUILD_PRIVATE */
  180693. #define PNG_LIBPNG_BUILD_BASE_TYPE PNG_LIBPNG_BUILD_STABLE
  180694. /* Careful here. At one time, Guy wanted to use 082, but that would be octal.
  180695. * We must not include leading zeros.
  180696. * Versions 0.7 through 1.0.0 were in the range 0 to 100 here (only
  180697. * version 1.0.0 was mis-numbered 100 instead of 10000). From
  180698. * version 1.0.1 it's xxyyzz, where x=major, y=minor, z=release */
  180699. #define PNG_LIBPNG_VER 10221 /* 1.2.21 */
  180700. #ifndef PNG_VERSION_INFO_ONLY
  180701. /* include the compression library's header */
  180702. #endif
  180703. /* include all user configurable info, including optional assembler routines */
  180704. /*** Start of inlined file: pngconf.h ***/
  180705. /* pngconf.h - machine configurable file for libpng
  180706. *
  180707. * libpng version 1.2.21 - October 4, 2007
  180708. * For conditions of distribution and use, see copyright notice in png.h
  180709. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  180710. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  180711. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  180712. */
  180713. /* Any machine specific code is near the front of this file, so if you
  180714. * are configuring libpng for a machine, you may want to read the section
  180715. * starting here down to where it starts to typedef png_color, png_text,
  180716. * and png_info.
  180717. */
  180718. #ifndef PNGCONF_H
  180719. #define PNGCONF_H
  180720. #define PNG_1_2_X
  180721. // These are some Juce config settings that should remove any unnecessary code bloat..
  180722. #define PNG_NO_STDIO 1
  180723. #define PNG_DEBUG 0
  180724. #define PNG_NO_WARNINGS 1
  180725. #define PNG_NO_ERROR_TEXT 1
  180726. #define PNG_NO_ERROR_NUMBERS 1
  180727. #define PNG_NO_USER_MEM 1
  180728. #define PNG_NO_READ_iCCP 1
  180729. #define PNG_NO_READ_UNKNOWN_CHUNKS 1
  180730. #define PNG_NO_READ_USER_CHUNKS 1
  180731. #define PNG_NO_READ_iTXt 1
  180732. #define PNG_NO_READ_sCAL 1
  180733. #define PNG_NO_READ_sPLT 1
  180734. #define png_error(a, b) png_err(a)
  180735. #define png_warning(a, b)
  180736. #define png_chunk_error(a, b) png_err(a)
  180737. #define png_chunk_warning(a, b)
  180738. /*
  180739. * PNG_USER_CONFIG has to be defined on the compiler command line. This
  180740. * includes the resource compiler for Windows DLL configurations.
  180741. */
  180742. #ifdef PNG_USER_CONFIG
  180743. # ifndef PNG_USER_PRIVATEBUILD
  180744. # define PNG_USER_PRIVATEBUILD
  180745. # endif
  180746. #include "pngusr.h"
  180747. #endif
  180748. /* PNG_CONFIGURE_LIBPNG is set by the "configure" script. */
  180749. #ifdef PNG_CONFIGURE_LIBPNG
  180750. #ifdef HAVE_CONFIG_H
  180751. #include "config.h"
  180752. #endif
  180753. #endif
  180754. /*
  180755. * Added at libpng-1.2.8
  180756. *
  180757. * If you create a private DLL you need to define in "pngusr.h" the followings:
  180758. * #define PNG_USER_PRIVATEBUILD <Describes by whom and why this version of
  180759. * the DLL was built>
  180760. * e.g. #define PNG_USER_PRIVATEBUILD "Build by MyCompany for xyz reasons."
  180761. * #define PNG_USER_DLLFNAME_POSTFIX <two-letter postfix that serve to
  180762. * distinguish your DLL from those of the official release. These
  180763. * correspond to the trailing letters that come after the version
  180764. * number and must match your private DLL name>
  180765. * e.g. // private DLL "libpng13gx.dll"
  180766. * #define PNG_USER_DLLFNAME_POSTFIX "gx"
  180767. *
  180768. * The following macros are also at your disposal if you want to complete the
  180769. * DLL VERSIONINFO structure.
  180770. * - PNG_USER_VERSIONINFO_COMMENTS
  180771. * - PNG_USER_VERSIONINFO_COMPANYNAME
  180772. * - PNG_USER_VERSIONINFO_LEGALTRADEMARKS
  180773. */
  180774. #ifdef __STDC__
  180775. #ifdef SPECIALBUILD
  180776. # pragma message("PNG_LIBPNG_SPECIALBUILD (and deprecated SPECIALBUILD)\
  180777. are now LIBPNG reserved macros. Use PNG_USER_PRIVATEBUILD instead.")
  180778. #endif
  180779. #ifdef PRIVATEBUILD
  180780. # pragma message("PRIVATEBUILD is deprecated.\
  180781. Use PNG_USER_PRIVATEBUILD instead.")
  180782. # define PNG_USER_PRIVATEBUILD PRIVATEBUILD
  180783. #endif
  180784. #endif /* __STDC__ */
  180785. #ifndef PNG_VERSION_INFO_ONLY
  180786. /* End of material added to libpng-1.2.8 */
  180787. /* Added at libpng-1.2.19, removed at libpng-1.2.20 because it caused trouble
  180788. Restored at libpng-1.2.21 */
  180789. # define PNG_WARN_UNINITIALIZED_ROW 1
  180790. /* End of material added at libpng-1.2.19/1.2.21 */
  180791. /* This is the size of the compression buffer, and thus the size of
  180792. * an IDAT chunk. Make this whatever size you feel is best for your
  180793. * machine. One of these will be allocated per png_struct. When this
  180794. * is full, it writes the data to the disk, and does some other
  180795. * calculations. Making this an extremely small size will slow
  180796. * the library down, but you may want to experiment to determine
  180797. * where it becomes significant, if you are concerned with memory
  180798. * usage. Note that zlib allocates at least 32Kb also. For readers,
  180799. * this describes the size of the buffer available to read the data in.
  180800. * Unless this gets smaller than the size of a row (compressed),
  180801. * it should not make much difference how big this is.
  180802. */
  180803. #ifndef PNG_ZBUF_SIZE
  180804. # define PNG_ZBUF_SIZE 8192
  180805. #endif
  180806. /* Enable if you want a write-only libpng */
  180807. #ifndef PNG_NO_READ_SUPPORTED
  180808. # define PNG_READ_SUPPORTED
  180809. #endif
  180810. /* Enable if you want a read-only libpng */
  180811. #ifndef PNG_NO_WRITE_SUPPORTED
  180812. # define PNG_WRITE_SUPPORTED
  180813. #endif
  180814. /* Enabled by default in 1.2.0. You can disable this if you don't need to
  180815. support PNGs that are embedded in MNG datastreams */
  180816. #if !defined(PNG_1_0_X) && !defined(PNG_NO_MNG_FEATURES)
  180817. # ifndef PNG_MNG_FEATURES_SUPPORTED
  180818. # define PNG_MNG_FEATURES_SUPPORTED
  180819. # endif
  180820. #endif
  180821. #ifndef PNG_NO_FLOATING_POINT_SUPPORTED
  180822. # ifndef PNG_FLOATING_POINT_SUPPORTED
  180823. # define PNG_FLOATING_POINT_SUPPORTED
  180824. # endif
  180825. #endif
  180826. /* If you are running on a machine where you cannot allocate more
  180827. * than 64K of memory at once, uncomment this. While libpng will not
  180828. * normally need that much memory in a chunk (unless you load up a very
  180829. * large file), zlib needs to know how big of a chunk it can use, and
  180830. * libpng thus makes sure to check any memory allocation to verify it
  180831. * will fit into memory.
  180832. #define PNG_MAX_MALLOC_64K
  180833. */
  180834. #if defined(MAXSEG_64K) && !defined(PNG_MAX_MALLOC_64K)
  180835. # define PNG_MAX_MALLOC_64K
  180836. #endif
  180837. /* Special munging to support doing things the 'cygwin' way:
  180838. * 'Normal' png-on-win32 defines/defaults:
  180839. * PNG_BUILD_DLL -- building dll
  180840. * PNG_USE_DLL -- building an application, linking to dll
  180841. * (no define) -- building static library, or building an
  180842. * application and linking to the static lib
  180843. * 'Cygwin' defines/defaults:
  180844. * PNG_BUILD_DLL -- (ignored) building the dll
  180845. * (no define) -- (ignored) building an application, linking to the dll
  180846. * PNG_STATIC -- (ignored) building the static lib, or building an
  180847. * application that links to the static lib.
  180848. * ALL_STATIC -- (ignored) building various static libs, or building an
  180849. * application that links to the static libs.
  180850. * Thus,
  180851. * a cygwin user should define either PNG_BUILD_DLL or PNG_STATIC, and
  180852. * this bit of #ifdefs will define the 'correct' config variables based on
  180853. * that. If a cygwin user *wants* to define 'PNG_USE_DLL' that's okay, but
  180854. * unnecessary.
  180855. *
  180856. * Also, the precedence order is:
  180857. * ALL_STATIC (since we can't #undef something outside our namespace)
  180858. * PNG_BUILD_DLL
  180859. * PNG_STATIC
  180860. * (nothing) == PNG_USE_DLL
  180861. *
  180862. * CYGWIN (2002-01-20): The preceding is now obsolete. With the advent
  180863. * of auto-import in binutils, we no longer need to worry about
  180864. * __declspec(dllexport) / __declspec(dllimport) and friends. Therefore,
  180865. * we don't need to worry about PNG_STATIC or ALL_STATIC when it comes
  180866. * to __declspec() stuff. However, we DO need to worry about
  180867. * PNG_BUILD_DLL and PNG_STATIC because those change some defaults
  180868. * such as CONSOLE_IO and whether GLOBAL_ARRAYS are allowed.
  180869. */
  180870. #if defined(__CYGWIN__)
  180871. # if defined(ALL_STATIC)
  180872. # if defined(PNG_BUILD_DLL)
  180873. # undef PNG_BUILD_DLL
  180874. # endif
  180875. # if defined(PNG_USE_DLL)
  180876. # undef PNG_USE_DLL
  180877. # endif
  180878. # if defined(PNG_DLL)
  180879. # undef PNG_DLL
  180880. # endif
  180881. # if !defined(PNG_STATIC)
  180882. # define PNG_STATIC
  180883. # endif
  180884. # else
  180885. # if defined (PNG_BUILD_DLL)
  180886. # if defined(PNG_STATIC)
  180887. # undef PNG_STATIC
  180888. # endif
  180889. # if defined(PNG_USE_DLL)
  180890. # undef PNG_USE_DLL
  180891. # endif
  180892. # if !defined(PNG_DLL)
  180893. # define PNG_DLL
  180894. # endif
  180895. # else
  180896. # if defined(PNG_STATIC)
  180897. # if defined(PNG_USE_DLL)
  180898. # undef PNG_USE_DLL
  180899. # endif
  180900. # if defined(PNG_DLL)
  180901. # undef PNG_DLL
  180902. # endif
  180903. # else
  180904. # if !defined(PNG_USE_DLL)
  180905. # define PNG_USE_DLL
  180906. # endif
  180907. # if !defined(PNG_DLL)
  180908. # define PNG_DLL
  180909. # endif
  180910. # endif
  180911. # endif
  180912. # endif
  180913. #endif
  180914. /* This protects us against compilers that run on a windowing system
  180915. * and thus don't have or would rather us not use the stdio types:
  180916. * stdin, stdout, and stderr. The only one currently used is stderr
  180917. * in png_error() and png_warning(). #defining PNG_NO_CONSOLE_IO will
  180918. * prevent these from being compiled and used. #defining PNG_NO_STDIO
  180919. * will also prevent these, plus will prevent the entire set of stdio
  180920. * macros and functions (FILE *, printf, etc.) from being compiled and used,
  180921. * unless (PNG_DEBUG > 0) has been #defined.
  180922. *
  180923. * #define PNG_NO_CONSOLE_IO
  180924. * #define PNG_NO_STDIO
  180925. */
  180926. #if defined(_WIN32_WCE)
  180927. # include <windows.h>
  180928. /* Console I/O functions are not supported on WindowsCE */
  180929. # define PNG_NO_CONSOLE_IO
  180930. # ifdef PNG_DEBUG
  180931. # undef PNG_DEBUG
  180932. # endif
  180933. #endif
  180934. #ifdef PNG_BUILD_DLL
  180935. # ifndef PNG_CONSOLE_IO_SUPPORTED
  180936. # ifndef PNG_NO_CONSOLE_IO
  180937. # define PNG_NO_CONSOLE_IO
  180938. # endif
  180939. # endif
  180940. #endif
  180941. # ifdef PNG_NO_STDIO
  180942. # ifndef PNG_NO_CONSOLE_IO
  180943. # define PNG_NO_CONSOLE_IO
  180944. # endif
  180945. # ifdef PNG_DEBUG
  180946. # if (PNG_DEBUG > 0)
  180947. # include <stdio.h>
  180948. # endif
  180949. # endif
  180950. # else
  180951. # if !defined(_WIN32_WCE)
  180952. /* "stdio.h" functions are not supported on WindowsCE */
  180953. # include <stdio.h>
  180954. # endif
  180955. # endif
  180956. /* This macro protects us against machines that don't have function
  180957. * prototypes (ie K&R style headers). If your compiler does not handle
  180958. * function prototypes, define this macro and use the included ansi2knr.
  180959. * I've always been able to use _NO_PROTO as the indicator, but you may
  180960. * need to drag the empty declaration out in front of here, or change the
  180961. * ifdef to suit your own needs.
  180962. */
  180963. #ifndef PNGARG
  180964. #ifdef OF /* zlib prototype munger */
  180965. # define PNGARG(arglist) OF(arglist)
  180966. #else
  180967. #ifdef _NO_PROTO
  180968. # define PNGARG(arglist) ()
  180969. # ifndef PNG_TYPECAST_NULL
  180970. # define PNG_TYPECAST_NULL
  180971. # endif
  180972. #else
  180973. # define PNGARG(arglist) arglist
  180974. #endif /* _NO_PROTO */
  180975. #endif /* OF */
  180976. #endif /* PNGARG */
  180977. /* Try to determine if we are compiling on a Mac. Note that testing for
  180978. * just __MWERKS__ is not good enough, because the Codewarrior is now used
  180979. * on non-Mac platforms.
  180980. */
  180981. #ifndef MACOS
  180982. # if (defined(__MWERKS__) && defined(macintosh)) || defined(applec) || \
  180983. defined(THINK_C) || defined(__SC__) || defined(TARGET_OS_MAC)
  180984. # define MACOS
  180985. # endif
  180986. #endif
  180987. /* enough people need this for various reasons to include it here */
  180988. #if !defined(MACOS) && !defined(RISCOS) && !defined(_WIN32_WCE)
  180989. # include <sys/types.h>
  180990. #endif
  180991. #if !defined(PNG_SETJMP_NOT_SUPPORTED) && !defined(PNG_NO_SETJMP_SUPPORTED)
  180992. # define PNG_SETJMP_SUPPORTED
  180993. #endif
  180994. #ifdef PNG_SETJMP_SUPPORTED
  180995. /* This is an attempt to force a single setjmp behaviour on Linux. If
  180996. * the X config stuff didn't define _BSD_SOURCE we wouldn't need this.
  180997. */
  180998. # ifdef __linux__
  180999. # ifdef _BSD_SOURCE
  181000. # define PNG_SAVE_BSD_SOURCE
  181001. # undef _BSD_SOURCE
  181002. # endif
  181003. # ifdef _SETJMP_H
  181004. /* If you encounter a compiler error here, see the explanation
  181005. * near the end of INSTALL.
  181006. */
  181007. __png.h__ already includes setjmp.h;
  181008. __dont__ include it again.;
  181009. # endif
  181010. # endif /* __linux__ */
  181011. /* include setjmp.h for error handling */
  181012. # include <setjmp.h>
  181013. # ifdef __linux__
  181014. # ifdef PNG_SAVE_BSD_SOURCE
  181015. # define _BSD_SOURCE
  181016. # undef PNG_SAVE_BSD_SOURCE
  181017. # endif
  181018. # endif /* __linux__ */
  181019. #endif /* PNG_SETJMP_SUPPORTED */
  181020. #ifdef BSD
  181021. #if ! JUCE_MAC
  181022. # include <strings.h>
  181023. #endif
  181024. #else
  181025. # include <string.h>
  181026. #endif
  181027. /* Other defines for things like memory and the like can go here. */
  181028. #ifdef PNG_INTERNAL
  181029. #include <stdlib.h>
  181030. /* The functions exported by PNG_EXTERN are PNG_INTERNAL functions, which
  181031. * aren't usually used outside the library (as far as I know), so it is
  181032. * debatable if they should be exported at all. In the future, when it is
  181033. * possible to have run-time registry of chunk-handling functions, some of
  181034. * these will be made available again.
  181035. #define PNG_EXTERN extern
  181036. */
  181037. #define PNG_EXTERN
  181038. /* Other defines specific to compilers can go here. Try to keep
  181039. * them inside an appropriate ifdef/endif pair for portability.
  181040. */
  181041. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  181042. # if defined(MACOS)
  181043. /* We need to check that <math.h> hasn't already been included earlier
  181044. * as it seems it doesn't agree with <fp.h>, yet we should really use
  181045. * <fp.h> if possible.
  181046. */
  181047. # if !defined(__MATH_H__) && !defined(__MATH_H) && !defined(__cmath__)
  181048. # include <fp.h>
  181049. # endif
  181050. # else
  181051. # include <math.h>
  181052. # endif
  181053. # if defined(_AMIGA) && defined(__SASC) && defined(_M68881)
  181054. /* Amiga SAS/C: We must include builtin FPU functions when compiling using
  181055. * MATH=68881
  181056. */
  181057. # include <m68881.h>
  181058. # endif
  181059. #endif
  181060. /* Codewarrior on NT has linking problems without this. */
  181061. #if (defined(__MWERKS__) && defined(WIN32)) || defined(__STDC__)
  181062. # define PNG_ALWAYS_EXTERN
  181063. #endif
  181064. /* This provides the non-ANSI (far) memory allocation routines. */
  181065. #if defined(__TURBOC__) && defined(__MSDOS__)
  181066. # include <mem.h>
  181067. # include <alloc.h>
  181068. #endif
  181069. /* I have no idea why is this necessary... */
  181070. #if defined(_MSC_VER) && (defined(WIN32) || defined(_Windows) || \
  181071. defined(_WINDOWS) || defined(_WIN32) || defined(__WIN32__))
  181072. # include <malloc.h>
  181073. #endif
  181074. /* This controls how fine the dithering gets. As this allocates
  181075. * a largish chunk of memory (32K), those who are not as concerned
  181076. * with dithering quality can decrease some or all of these.
  181077. */
  181078. #ifndef PNG_DITHER_RED_BITS
  181079. # define PNG_DITHER_RED_BITS 5
  181080. #endif
  181081. #ifndef PNG_DITHER_GREEN_BITS
  181082. # define PNG_DITHER_GREEN_BITS 5
  181083. #endif
  181084. #ifndef PNG_DITHER_BLUE_BITS
  181085. # define PNG_DITHER_BLUE_BITS 5
  181086. #endif
  181087. /* This controls how fine the gamma correction becomes when you
  181088. * are only interested in 8 bits anyway. Increasing this value
  181089. * results in more memory being used, and more pow() functions
  181090. * being called to fill in the gamma tables. Don't set this value
  181091. * less then 8, and even that may not work (I haven't tested it).
  181092. */
  181093. #ifndef PNG_MAX_GAMMA_8
  181094. # define PNG_MAX_GAMMA_8 11
  181095. #endif
  181096. /* This controls how much a difference in gamma we can tolerate before
  181097. * we actually start doing gamma conversion.
  181098. */
  181099. #ifndef PNG_GAMMA_THRESHOLD
  181100. # define PNG_GAMMA_THRESHOLD 0.05
  181101. #endif
  181102. #endif /* PNG_INTERNAL */
  181103. /* The following uses const char * instead of char * for error
  181104. * and warning message functions, so some compilers won't complain.
  181105. * If you do not want to use const, define PNG_NO_CONST here.
  181106. */
  181107. #ifndef PNG_NO_CONST
  181108. # define PNG_CONST const
  181109. #else
  181110. # define PNG_CONST
  181111. #endif
  181112. /* The following defines give you the ability to remove code from the
  181113. * library that you will not be using. I wish I could figure out how to
  181114. * automate this, but I can't do that without making it seriously hard
  181115. * on the users. So if you are not using an ability, change the #define
  181116. * to and #undef, and that part of the library will not be compiled. If
  181117. * your linker can't find a function, you may want to make sure the
  181118. * ability is defined here. Some of these depend upon some others being
  181119. * defined. I haven't figured out all the interactions here, so you may
  181120. * have to experiment awhile to get everything to compile. If you are
  181121. * creating or using a shared library, you probably shouldn't touch this,
  181122. * as it will affect the size of the structures, and this will cause bad
  181123. * things to happen if the library and/or application ever change.
  181124. */
  181125. /* Any features you will not be using can be undef'ed here */
  181126. /* GR-P, 0.96a: Set "*TRANSFORMS_SUPPORTED as default but allow user
  181127. * to turn it off with "*TRANSFORMS_NOT_SUPPORTED" or *PNG_NO_*_TRANSFORMS
  181128. * on the compile line, then pick and choose which ones to define without
  181129. * having to edit this file. It is safe to use the *TRANSFORMS_NOT_SUPPORTED
  181130. * if you only want to have a png-compliant reader/writer but don't need
  181131. * any of the extra transformations. This saves about 80 kbytes in a
  181132. * typical installation of the library. (PNG_NO_* form added in version
  181133. * 1.0.1c, for consistency)
  181134. */
  181135. /* The size of the png_text structure changed in libpng-1.0.6 when
  181136. * iTXt support was added. iTXt support was turned off by default through
  181137. * libpng-1.2.x, to support old apps that malloc the png_text structure
  181138. * instead of calling png_set_text() and letting libpng malloc it. It
  181139. * was turned on by default in libpng-1.3.0.
  181140. */
  181141. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  181142. # ifndef PNG_NO_iTXt_SUPPORTED
  181143. # define PNG_NO_iTXt_SUPPORTED
  181144. # endif
  181145. # ifndef PNG_NO_READ_iTXt
  181146. # define PNG_NO_READ_iTXt
  181147. # endif
  181148. # ifndef PNG_NO_WRITE_iTXt
  181149. # define PNG_NO_WRITE_iTXt
  181150. # endif
  181151. #endif
  181152. #if !defined(PNG_NO_iTXt_SUPPORTED)
  181153. # if !defined(PNG_READ_iTXt_SUPPORTED) && !defined(PNG_NO_READ_iTXt)
  181154. # define PNG_READ_iTXt
  181155. # endif
  181156. # if !defined(PNG_WRITE_iTXt_SUPPORTED) && !defined(PNG_NO_WRITE_iTXt)
  181157. # define PNG_WRITE_iTXt
  181158. # endif
  181159. #endif
  181160. /* The following support, added after version 1.0.0, can be turned off here en
  181161. * masse by defining PNG_LEGACY_SUPPORTED in case you need binary compatibility
  181162. * with old applications that require the length of png_struct and png_info
  181163. * to remain unchanged.
  181164. */
  181165. #ifdef PNG_LEGACY_SUPPORTED
  181166. # define PNG_NO_FREE_ME
  181167. # define PNG_NO_READ_UNKNOWN_CHUNKS
  181168. # define PNG_NO_WRITE_UNKNOWN_CHUNKS
  181169. # define PNG_NO_READ_USER_CHUNKS
  181170. # define PNG_NO_READ_iCCP
  181171. # define PNG_NO_WRITE_iCCP
  181172. # define PNG_NO_READ_iTXt
  181173. # define PNG_NO_WRITE_iTXt
  181174. # define PNG_NO_READ_sCAL
  181175. # define PNG_NO_WRITE_sCAL
  181176. # define PNG_NO_READ_sPLT
  181177. # define PNG_NO_WRITE_sPLT
  181178. # define PNG_NO_INFO_IMAGE
  181179. # define PNG_NO_READ_RGB_TO_GRAY
  181180. # define PNG_NO_READ_USER_TRANSFORM
  181181. # define PNG_NO_WRITE_USER_TRANSFORM
  181182. # define PNG_NO_USER_MEM
  181183. # define PNG_NO_READ_EMPTY_PLTE
  181184. # define PNG_NO_MNG_FEATURES
  181185. # define PNG_NO_FIXED_POINT_SUPPORTED
  181186. #endif
  181187. /* Ignore attempt to turn off both floating and fixed point support */
  181188. #if !defined(PNG_FLOATING_POINT_SUPPORTED) || \
  181189. !defined(PNG_NO_FIXED_POINT_SUPPORTED)
  181190. # define PNG_FIXED_POINT_SUPPORTED
  181191. #endif
  181192. #ifndef PNG_NO_FREE_ME
  181193. # define PNG_FREE_ME_SUPPORTED
  181194. #endif
  181195. #if defined(PNG_READ_SUPPORTED)
  181196. #if !defined(PNG_READ_TRANSFORMS_NOT_SUPPORTED) && \
  181197. !defined(PNG_NO_READ_TRANSFORMS)
  181198. # define PNG_READ_TRANSFORMS_SUPPORTED
  181199. #endif
  181200. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  181201. # ifndef PNG_NO_READ_EXPAND
  181202. # define PNG_READ_EXPAND_SUPPORTED
  181203. # endif
  181204. # ifndef PNG_NO_READ_SHIFT
  181205. # define PNG_READ_SHIFT_SUPPORTED
  181206. # endif
  181207. # ifndef PNG_NO_READ_PACK
  181208. # define PNG_READ_PACK_SUPPORTED
  181209. # endif
  181210. # ifndef PNG_NO_READ_BGR
  181211. # define PNG_READ_BGR_SUPPORTED
  181212. # endif
  181213. # ifndef PNG_NO_READ_SWAP
  181214. # define PNG_READ_SWAP_SUPPORTED
  181215. # endif
  181216. # ifndef PNG_NO_READ_PACKSWAP
  181217. # define PNG_READ_PACKSWAP_SUPPORTED
  181218. # endif
  181219. # ifndef PNG_NO_READ_INVERT
  181220. # define PNG_READ_INVERT_SUPPORTED
  181221. # endif
  181222. # ifndef PNG_NO_READ_DITHER
  181223. # define PNG_READ_DITHER_SUPPORTED
  181224. # endif
  181225. # ifndef PNG_NO_READ_BACKGROUND
  181226. # define PNG_READ_BACKGROUND_SUPPORTED
  181227. # endif
  181228. # ifndef PNG_NO_READ_16_TO_8
  181229. # define PNG_READ_16_TO_8_SUPPORTED
  181230. # endif
  181231. # ifndef PNG_NO_READ_FILLER
  181232. # define PNG_READ_FILLER_SUPPORTED
  181233. # endif
  181234. # ifndef PNG_NO_READ_GAMMA
  181235. # define PNG_READ_GAMMA_SUPPORTED
  181236. # endif
  181237. # ifndef PNG_NO_READ_GRAY_TO_RGB
  181238. # define PNG_READ_GRAY_TO_RGB_SUPPORTED
  181239. # endif
  181240. # ifndef PNG_NO_READ_SWAP_ALPHA
  181241. # define PNG_READ_SWAP_ALPHA_SUPPORTED
  181242. # endif
  181243. # ifndef PNG_NO_READ_INVERT_ALPHA
  181244. # define PNG_READ_INVERT_ALPHA_SUPPORTED
  181245. # endif
  181246. # ifndef PNG_NO_READ_STRIP_ALPHA
  181247. # define PNG_READ_STRIP_ALPHA_SUPPORTED
  181248. # endif
  181249. # ifndef PNG_NO_READ_USER_TRANSFORM
  181250. # define PNG_READ_USER_TRANSFORM_SUPPORTED
  181251. # endif
  181252. # ifndef PNG_NO_READ_RGB_TO_GRAY
  181253. # define PNG_READ_RGB_TO_GRAY_SUPPORTED
  181254. # endif
  181255. #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
  181256. #if !defined(PNG_NO_PROGRESSIVE_READ) && \
  181257. !defined(PNG_PROGRESSIVE_READ_SUPPORTED) /* if you don't do progressive */
  181258. # define PNG_PROGRESSIVE_READ_SUPPORTED /* reading. This is not talking */
  181259. #endif /* about interlacing capability! You'll */
  181260. /* still have interlacing unless you change the following line: */
  181261. #define PNG_READ_INTERLACING_SUPPORTED /* required in PNG-compliant decoders */
  181262. #ifndef PNG_NO_READ_COMPOSITE_NODIV
  181263. # ifndef PNG_NO_READ_COMPOSITED_NODIV /* libpng-1.0.x misspelling */
  181264. # define PNG_READ_COMPOSITE_NODIV_SUPPORTED /* well tested on Intel, SGI */
  181265. # endif
  181266. #endif
  181267. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  181268. /* Deprecated, will be removed from version 2.0.0.
  181269. Use PNG_MNG_FEATURES_SUPPORTED instead. */
  181270. #ifndef PNG_NO_READ_EMPTY_PLTE
  181271. # define PNG_READ_EMPTY_PLTE_SUPPORTED
  181272. #endif
  181273. #endif
  181274. #endif /* PNG_READ_SUPPORTED */
  181275. #if defined(PNG_WRITE_SUPPORTED)
  181276. # if !defined(PNG_WRITE_TRANSFORMS_NOT_SUPPORTED) && \
  181277. !defined(PNG_NO_WRITE_TRANSFORMS)
  181278. # define PNG_WRITE_TRANSFORMS_SUPPORTED
  181279. #endif
  181280. #ifdef PNG_WRITE_TRANSFORMS_SUPPORTED
  181281. # ifndef PNG_NO_WRITE_SHIFT
  181282. # define PNG_WRITE_SHIFT_SUPPORTED
  181283. # endif
  181284. # ifndef PNG_NO_WRITE_PACK
  181285. # define PNG_WRITE_PACK_SUPPORTED
  181286. # endif
  181287. # ifndef PNG_NO_WRITE_BGR
  181288. # define PNG_WRITE_BGR_SUPPORTED
  181289. # endif
  181290. # ifndef PNG_NO_WRITE_SWAP
  181291. # define PNG_WRITE_SWAP_SUPPORTED
  181292. # endif
  181293. # ifndef PNG_NO_WRITE_PACKSWAP
  181294. # define PNG_WRITE_PACKSWAP_SUPPORTED
  181295. # endif
  181296. # ifndef PNG_NO_WRITE_INVERT
  181297. # define PNG_WRITE_INVERT_SUPPORTED
  181298. # endif
  181299. # ifndef PNG_NO_WRITE_FILLER
  181300. # define PNG_WRITE_FILLER_SUPPORTED /* same as WRITE_STRIP_ALPHA */
  181301. # endif
  181302. # ifndef PNG_NO_WRITE_SWAP_ALPHA
  181303. # define PNG_WRITE_SWAP_ALPHA_SUPPORTED
  181304. # endif
  181305. # ifndef PNG_NO_WRITE_INVERT_ALPHA
  181306. # define PNG_WRITE_INVERT_ALPHA_SUPPORTED
  181307. # endif
  181308. # ifndef PNG_NO_WRITE_USER_TRANSFORM
  181309. # define PNG_WRITE_USER_TRANSFORM_SUPPORTED
  181310. # endif
  181311. #endif /* PNG_WRITE_TRANSFORMS_SUPPORTED */
  181312. #if !defined(PNG_NO_WRITE_INTERLACING_SUPPORTED) && \
  181313. !defined(PNG_WRITE_INTERLACING_SUPPORTED)
  181314. #define PNG_WRITE_INTERLACING_SUPPORTED /* not required for PNG-compliant
  181315. encoders, but can cause trouble
  181316. if left undefined */
  181317. #endif
  181318. #if !defined(PNG_NO_WRITE_WEIGHTED_FILTER) && \
  181319. !defined(PNG_WRITE_WEIGHTED_FILTER) && \
  181320. defined(PNG_FLOATING_POINT_SUPPORTED)
  181321. # define PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
  181322. #endif
  181323. #ifndef PNG_NO_WRITE_FLUSH
  181324. # define PNG_WRITE_FLUSH_SUPPORTED
  181325. #endif
  181326. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  181327. /* Deprecated, see PNG_MNG_FEATURES_SUPPORTED, above */
  181328. #ifndef PNG_NO_WRITE_EMPTY_PLTE
  181329. # define PNG_WRITE_EMPTY_PLTE_SUPPORTED
  181330. #endif
  181331. #endif
  181332. #endif /* PNG_WRITE_SUPPORTED */
  181333. #ifndef PNG_1_0_X
  181334. # ifndef PNG_NO_ERROR_NUMBERS
  181335. # define PNG_ERROR_NUMBERS_SUPPORTED
  181336. # endif
  181337. #endif /* PNG_1_0_X */
  181338. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  181339. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  181340. # ifndef PNG_NO_USER_TRANSFORM_PTR
  181341. # define PNG_USER_TRANSFORM_PTR_SUPPORTED
  181342. # endif
  181343. #endif
  181344. #ifndef PNG_NO_STDIO
  181345. # define PNG_TIME_RFC1123_SUPPORTED
  181346. #endif
  181347. /* This adds extra functions in pngget.c for accessing data from the
  181348. * info pointer (added in version 0.99)
  181349. * png_get_image_width()
  181350. * png_get_image_height()
  181351. * png_get_bit_depth()
  181352. * png_get_color_type()
  181353. * png_get_compression_type()
  181354. * png_get_filter_type()
  181355. * png_get_interlace_type()
  181356. * png_get_pixel_aspect_ratio()
  181357. * png_get_pixels_per_meter()
  181358. * png_get_x_offset_pixels()
  181359. * png_get_y_offset_pixels()
  181360. * png_get_x_offset_microns()
  181361. * png_get_y_offset_microns()
  181362. */
  181363. #if !defined(PNG_NO_EASY_ACCESS) && !defined(PNG_EASY_ACCESS_SUPPORTED)
  181364. # define PNG_EASY_ACCESS_SUPPORTED
  181365. #endif
  181366. /* PNG_ASSEMBLER_CODE was enabled by default in version 1.2.0
  181367. * and removed from version 1.2.20. The following will be removed
  181368. * from libpng-1.4.0
  181369. */
  181370. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_OPTIMIZED_CODE)
  181371. # ifndef PNG_OPTIMIZED_CODE_SUPPORTED
  181372. # define PNG_OPTIMIZED_CODE_SUPPORTED
  181373. # endif
  181374. #endif
  181375. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_ASSEMBLER_CODE)
  181376. # ifndef PNG_ASSEMBLER_CODE_SUPPORTED
  181377. # define PNG_ASSEMBLER_CODE_SUPPORTED
  181378. # endif
  181379. # if defined(__GNUC__) && defined(__x86_64__) && (__GNUC__ < 4)
  181380. /* work around 64-bit gcc compiler bugs in gcc-3.x */
  181381. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181382. # define PNG_NO_MMX_CODE
  181383. # endif
  181384. # endif
  181385. # if defined(__APPLE__)
  181386. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181387. # define PNG_NO_MMX_CODE
  181388. # endif
  181389. # endif
  181390. # if (defined(__MWERKS__) && ((__MWERKS__ < 0x0900) || macintosh))
  181391. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181392. # define PNG_NO_MMX_CODE
  181393. # endif
  181394. # endif
  181395. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181396. # define PNG_MMX_CODE_SUPPORTED
  181397. # endif
  181398. #endif
  181399. /* end of obsolete code to be removed from libpng-1.4.0 */
  181400. #if !defined(PNG_1_0_X)
  181401. #if !defined(PNG_NO_USER_MEM) && !defined(PNG_USER_MEM_SUPPORTED)
  181402. # define PNG_USER_MEM_SUPPORTED
  181403. #endif
  181404. #endif /* PNG_1_0_X */
  181405. /* Added at libpng-1.2.6 */
  181406. #if !defined(PNG_1_0_X)
  181407. #ifndef PNG_SET_USER_LIMITS_SUPPORTED
  181408. #if !defined(PNG_NO_SET_USER_LIMITS) && !defined(PNG_SET_USER_LIMITS_SUPPORTED)
  181409. # define PNG_SET_USER_LIMITS_SUPPORTED
  181410. #endif
  181411. #endif
  181412. #endif /* PNG_1_0_X */
  181413. /* Added at libpng-1.0.16 and 1.2.6. To accept all valid PNGS no matter
  181414. * how large, set these limits to 0x7fffffffL
  181415. */
  181416. #ifndef PNG_USER_WIDTH_MAX
  181417. # define PNG_USER_WIDTH_MAX 1000000L
  181418. #endif
  181419. #ifndef PNG_USER_HEIGHT_MAX
  181420. # define PNG_USER_HEIGHT_MAX 1000000L
  181421. #endif
  181422. /* These are currently experimental features, define them if you want */
  181423. /* very little testing */
  181424. /*
  181425. #ifdef PNG_READ_SUPPORTED
  181426. # ifndef PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  181427. # define PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  181428. # endif
  181429. #endif
  181430. */
  181431. /* This is only for PowerPC big-endian and 680x0 systems */
  181432. /* some testing */
  181433. /*
  181434. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  181435. # define PNG_READ_BIG_ENDIAN_SUPPORTED
  181436. #endif
  181437. */
  181438. /* Buggy compilers (e.g., gcc 2.7.2.2) need this */
  181439. /*
  181440. #define PNG_NO_POINTER_INDEXING
  181441. */
  181442. /* These functions are turned off by default, as they will be phased out. */
  181443. /*
  181444. #define PNG_USELESS_TESTS_SUPPORTED
  181445. #define PNG_CORRECT_PALETTE_SUPPORTED
  181446. */
  181447. /* Any chunks you are not interested in, you can undef here. The
  181448. * ones that allocate memory may be expecially important (hIST,
  181449. * tEXt, zTXt, tRNS, pCAL). Others will just save time and make png_info
  181450. * a bit smaller.
  181451. */
  181452. #if defined(PNG_READ_SUPPORTED) && \
  181453. !defined(PNG_READ_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  181454. !defined(PNG_NO_READ_ANCILLARY_CHUNKS)
  181455. # define PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  181456. #endif
  181457. #if defined(PNG_WRITE_SUPPORTED) && \
  181458. !defined(PNG_WRITE_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  181459. !defined(PNG_NO_WRITE_ANCILLARY_CHUNKS)
  181460. # define PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  181461. #endif
  181462. #ifdef PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  181463. #ifdef PNG_NO_READ_TEXT
  181464. # define PNG_NO_READ_iTXt
  181465. # define PNG_NO_READ_tEXt
  181466. # define PNG_NO_READ_zTXt
  181467. #endif
  181468. #ifndef PNG_NO_READ_bKGD
  181469. # define PNG_READ_bKGD_SUPPORTED
  181470. # define PNG_bKGD_SUPPORTED
  181471. #endif
  181472. #ifndef PNG_NO_READ_cHRM
  181473. # define PNG_READ_cHRM_SUPPORTED
  181474. # define PNG_cHRM_SUPPORTED
  181475. #endif
  181476. #ifndef PNG_NO_READ_gAMA
  181477. # define PNG_READ_gAMA_SUPPORTED
  181478. # define PNG_gAMA_SUPPORTED
  181479. #endif
  181480. #ifndef PNG_NO_READ_hIST
  181481. # define PNG_READ_hIST_SUPPORTED
  181482. # define PNG_hIST_SUPPORTED
  181483. #endif
  181484. #ifndef PNG_NO_READ_iCCP
  181485. # define PNG_READ_iCCP_SUPPORTED
  181486. # define PNG_iCCP_SUPPORTED
  181487. #endif
  181488. #ifndef PNG_NO_READ_iTXt
  181489. # ifndef PNG_READ_iTXt_SUPPORTED
  181490. # define PNG_READ_iTXt_SUPPORTED
  181491. # endif
  181492. # ifndef PNG_iTXt_SUPPORTED
  181493. # define PNG_iTXt_SUPPORTED
  181494. # endif
  181495. #endif
  181496. #ifndef PNG_NO_READ_oFFs
  181497. # define PNG_READ_oFFs_SUPPORTED
  181498. # define PNG_oFFs_SUPPORTED
  181499. #endif
  181500. #ifndef PNG_NO_READ_pCAL
  181501. # define PNG_READ_pCAL_SUPPORTED
  181502. # define PNG_pCAL_SUPPORTED
  181503. #endif
  181504. #ifndef PNG_NO_READ_sCAL
  181505. # define PNG_READ_sCAL_SUPPORTED
  181506. # define PNG_sCAL_SUPPORTED
  181507. #endif
  181508. #ifndef PNG_NO_READ_pHYs
  181509. # define PNG_READ_pHYs_SUPPORTED
  181510. # define PNG_pHYs_SUPPORTED
  181511. #endif
  181512. #ifndef PNG_NO_READ_sBIT
  181513. # define PNG_READ_sBIT_SUPPORTED
  181514. # define PNG_sBIT_SUPPORTED
  181515. #endif
  181516. #ifndef PNG_NO_READ_sPLT
  181517. # define PNG_READ_sPLT_SUPPORTED
  181518. # define PNG_sPLT_SUPPORTED
  181519. #endif
  181520. #ifndef PNG_NO_READ_sRGB
  181521. # define PNG_READ_sRGB_SUPPORTED
  181522. # define PNG_sRGB_SUPPORTED
  181523. #endif
  181524. #ifndef PNG_NO_READ_tEXt
  181525. # define PNG_READ_tEXt_SUPPORTED
  181526. # define PNG_tEXt_SUPPORTED
  181527. #endif
  181528. #ifndef PNG_NO_READ_tIME
  181529. # define PNG_READ_tIME_SUPPORTED
  181530. # define PNG_tIME_SUPPORTED
  181531. #endif
  181532. #ifndef PNG_NO_READ_tRNS
  181533. # define PNG_READ_tRNS_SUPPORTED
  181534. # define PNG_tRNS_SUPPORTED
  181535. #endif
  181536. #ifndef PNG_NO_READ_zTXt
  181537. # define PNG_READ_zTXt_SUPPORTED
  181538. # define PNG_zTXt_SUPPORTED
  181539. #endif
  181540. #ifndef PNG_NO_READ_UNKNOWN_CHUNKS
  181541. # define PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
  181542. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  181543. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  181544. # endif
  181545. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  181546. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181547. # endif
  181548. #endif
  181549. #if !defined(PNG_NO_READ_USER_CHUNKS) && \
  181550. defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  181551. # define PNG_READ_USER_CHUNKS_SUPPORTED
  181552. # define PNG_USER_CHUNKS_SUPPORTED
  181553. # ifdef PNG_NO_READ_UNKNOWN_CHUNKS
  181554. # undef PNG_NO_READ_UNKNOWN_CHUNKS
  181555. # endif
  181556. # ifdef PNG_NO_HANDLE_AS_UNKNOWN
  181557. # undef PNG_NO_HANDLE_AS_UNKNOWN
  181558. # endif
  181559. #endif
  181560. #ifndef PNG_NO_READ_OPT_PLTE
  181561. # define PNG_READ_OPT_PLTE_SUPPORTED /* only affects support of the */
  181562. #endif /* optional PLTE chunk in RGB and RGBA images */
  181563. #if defined(PNG_READ_iTXt_SUPPORTED) || defined(PNG_READ_tEXt_SUPPORTED) || \
  181564. defined(PNG_READ_zTXt_SUPPORTED)
  181565. # define PNG_READ_TEXT_SUPPORTED
  181566. # define PNG_TEXT_SUPPORTED
  181567. #endif
  181568. #endif /* PNG_READ_ANCILLARY_CHUNKS_SUPPORTED */
  181569. #ifdef PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  181570. #ifdef PNG_NO_WRITE_TEXT
  181571. # define PNG_NO_WRITE_iTXt
  181572. # define PNG_NO_WRITE_tEXt
  181573. # define PNG_NO_WRITE_zTXt
  181574. #endif
  181575. #ifndef PNG_NO_WRITE_bKGD
  181576. # define PNG_WRITE_bKGD_SUPPORTED
  181577. # ifndef PNG_bKGD_SUPPORTED
  181578. # define PNG_bKGD_SUPPORTED
  181579. # endif
  181580. #endif
  181581. #ifndef PNG_NO_WRITE_cHRM
  181582. # define PNG_WRITE_cHRM_SUPPORTED
  181583. # ifndef PNG_cHRM_SUPPORTED
  181584. # define PNG_cHRM_SUPPORTED
  181585. # endif
  181586. #endif
  181587. #ifndef PNG_NO_WRITE_gAMA
  181588. # define PNG_WRITE_gAMA_SUPPORTED
  181589. # ifndef PNG_gAMA_SUPPORTED
  181590. # define PNG_gAMA_SUPPORTED
  181591. # endif
  181592. #endif
  181593. #ifndef PNG_NO_WRITE_hIST
  181594. # define PNG_WRITE_hIST_SUPPORTED
  181595. # ifndef PNG_hIST_SUPPORTED
  181596. # define PNG_hIST_SUPPORTED
  181597. # endif
  181598. #endif
  181599. #ifndef PNG_NO_WRITE_iCCP
  181600. # define PNG_WRITE_iCCP_SUPPORTED
  181601. # ifndef PNG_iCCP_SUPPORTED
  181602. # define PNG_iCCP_SUPPORTED
  181603. # endif
  181604. #endif
  181605. #ifndef PNG_NO_WRITE_iTXt
  181606. # ifndef PNG_WRITE_iTXt_SUPPORTED
  181607. # define PNG_WRITE_iTXt_SUPPORTED
  181608. # endif
  181609. # ifndef PNG_iTXt_SUPPORTED
  181610. # define PNG_iTXt_SUPPORTED
  181611. # endif
  181612. #endif
  181613. #ifndef PNG_NO_WRITE_oFFs
  181614. # define PNG_WRITE_oFFs_SUPPORTED
  181615. # ifndef PNG_oFFs_SUPPORTED
  181616. # define PNG_oFFs_SUPPORTED
  181617. # endif
  181618. #endif
  181619. #ifndef PNG_NO_WRITE_pCAL
  181620. # define PNG_WRITE_pCAL_SUPPORTED
  181621. # ifndef PNG_pCAL_SUPPORTED
  181622. # define PNG_pCAL_SUPPORTED
  181623. # endif
  181624. #endif
  181625. #ifndef PNG_NO_WRITE_sCAL
  181626. # define PNG_WRITE_sCAL_SUPPORTED
  181627. # ifndef PNG_sCAL_SUPPORTED
  181628. # define PNG_sCAL_SUPPORTED
  181629. # endif
  181630. #endif
  181631. #ifndef PNG_NO_WRITE_pHYs
  181632. # define PNG_WRITE_pHYs_SUPPORTED
  181633. # ifndef PNG_pHYs_SUPPORTED
  181634. # define PNG_pHYs_SUPPORTED
  181635. # endif
  181636. #endif
  181637. #ifndef PNG_NO_WRITE_sBIT
  181638. # define PNG_WRITE_sBIT_SUPPORTED
  181639. # ifndef PNG_sBIT_SUPPORTED
  181640. # define PNG_sBIT_SUPPORTED
  181641. # endif
  181642. #endif
  181643. #ifndef PNG_NO_WRITE_sPLT
  181644. # define PNG_WRITE_sPLT_SUPPORTED
  181645. # ifndef PNG_sPLT_SUPPORTED
  181646. # define PNG_sPLT_SUPPORTED
  181647. # endif
  181648. #endif
  181649. #ifndef PNG_NO_WRITE_sRGB
  181650. # define PNG_WRITE_sRGB_SUPPORTED
  181651. # ifndef PNG_sRGB_SUPPORTED
  181652. # define PNG_sRGB_SUPPORTED
  181653. # endif
  181654. #endif
  181655. #ifndef PNG_NO_WRITE_tEXt
  181656. # define PNG_WRITE_tEXt_SUPPORTED
  181657. # ifndef PNG_tEXt_SUPPORTED
  181658. # define PNG_tEXt_SUPPORTED
  181659. # endif
  181660. #endif
  181661. #ifndef PNG_NO_WRITE_tIME
  181662. # define PNG_WRITE_tIME_SUPPORTED
  181663. # ifndef PNG_tIME_SUPPORTED
  181664. # define PNG_tIME_SUPPORTED
  181665. # endif
  181666. #endif
  181667. #ifndef PNG_NO_WRITE_tRNS
  181668. # define PNG_WRITE_tRNS_SUPPORTED
  181669. # ifndef PNG_tRNS_SUPPORTED
  181670. # define PNG_tRNS_SUPPORTED
  181671. # endif
  181672. #endif
  181673. #ifndef PNG_NO_WRITE_zTXt
  181674. # define PNG_WRITE_zTXt_SUPPORTED
  181675. # ifndef PNG_zTXt_SUPPORTED
  181676. # define PNG_zTXt_SUPPORTED
  181677. # endif
  181678. #endif
  181679. #ifndef PNG_NO_WRITE_UNKNOWN_CHUNKS
  181680. # define PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
  181681. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  181682. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  181683. # endif
  181684. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  181685. # ifndef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181686. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181687. # endif
  181688. # endif
  181689. #endif
  181690. #if defined(PNG_WRITE_iTXt_SUPPORTED) || defined(PNG_WRITE_tEXt_SUPPORTED) || \
  181691. defined(PNG_WRITE_zTXt_SUPPORTED)
  181692. # define PNG_WRITE_TEXT_SUPPORTED
  181693. # ifndef PNG_TEXT_SUPPORTED
  181694. # define PNG_TEXT_SUPPORTED
  181695. # endif
  181696. #endif
  181697. #endif /* PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED */
  181698. /* Turn this off to disable png_read_png() and
  181699. * png_write_png() and leave the row_pointers member
  181700. * out of the info structure.
  181701. */
  181702. #ifndef PNG_NO_INFO_IMAGE
  181703. # define PNG_INFO_IMAGE_SUPPORTED
  181704. #endif
  181705. /* need the time information for reading tIME chunks */
  181706. #if defined(PNG_tIME_SUPPORTED)
  181707. # if !defined(_WIN32_WCE)
  181708. /* "time.h" functions are not supported on WindowsCE */
  181709. # include <time.h>
  181710. # endif
  181711. #endif
  181712. /* Some typedefs to get us started. These should be safe on most of the
  181713. * common platforms. The typedefs should be at least as large as the
  181714. * numbers suggest (a png_uint_32 must be at least 32 bits long), but they
  181715. * don't have to be exactly that size. Some compilers dislike passing
  181716. * unsigned shorts as function parameters, so you may be better off using
  181717. * unsigned int for png_uint_16. Likewise, for 64-bit systems, you may
  181718. * want to have unsigned int for png_uint_32 instead of unsigned long.
  181719. */
  181720. typedef unsigned long png_uint_32;
  181721. typedef long png_int_32;
  181722. typedef unsigned short png_uint_16;
  181723. typedef short png_int_16;
  181724. typedef unsigned char png_byte;
  181725. /* This is usually size_t. It is typedef'ed just in case you need it to
  181726. change (I'm not sure if you will or not, so I thought I'd be safe) */
  181727. #ifdef PNG_SIZE_T
  181728. typedef PNG_SIZE_T png_size_t;
  181729. # define png_sizeof(x) png_convert_size(sizeof (x))
  181730. #else
  181731. typedef size_t png_size_t;
  181732. # define png_sizeof(x) sizeof (x)
  181733. #endif
  181734. /* The following is needed for medium model support. It cannot be in the
  181735. * PNG_INTERNAL section. Needs modification for other compilers besides
  181736. * MSC. Model independent support declares all arrays and pointers to be
  181737. * large using the far keyword. The zlib version used must also support
  181738. * model independent data. As of version zlib 1.0.4, the necessary changes
  181739. * have been made in zlib. The USE_FAR_KEYWORD define triggers other
  181740. * changes that are needed. (Tim Wegner)
  181741. */
  181742. /* Separate compiler dependencies (problem here is that zlib.h always
  181743. defines FAR. (SJT) */
  181744. #ifdef __BORLANDC__
  181745. # if defined(__LARGE__) || defined(__HUGE__) || defined(__COMPACT__)
  181746. # define LDATA 1
  181747. # else
  181748. # define LDATA 0
  181749. # endif
  181750. /* GRR: why is Cygwin in here? Cygwin is not Borland C... */
  181751. # if !defined(__WIN32__) && !defined(__FLAT__) && !defined(__CYGWIN__)
  181752. # define PNG_MAX_MALLOC_64K
  181753. # if (LDATA != 1)
  181754. # ifndef FAR
  181755. # define FAR __far
  181756. # endif
  181757. # define USE_FAR_KEYWORD
  181758. # endif /* LDATA != 1 */
  181759. /* Possibly useful for moving data out of default segment.
  181760. * Uncomment it if you want. Could also define FARDATA as
  181761. * const if your compiler supports it. (SJT)
  181762. # define FARDATA FAR
  181763. */
  181764. # endif /* __WIN32__, __FLAT__, __CYGWIN__ */
  181765. #endif /* __BORLANDC__ */
  181766. /* Suggest testing for specific compiler first before testing for
  181767. * FAR. The Watcom compiler defines both __MEDIUM__ and M_I86MM,
  181768. * making reliance oncertain keywords suspect. (SJT)
  181769. */
  181770. /* MSC Medium model */
  181771. #if defined(FAR)
  181772. # if defined(M_I86MM)
  181773. # define USE_FAR_KEYWORD
  181774. # define FARDATA FAR
  181775. # include <dos.h>
  181776. # endif
  181777. #endif
  181778. /* SJT: default case */
  181779. #ifndef FAR
  181780. # define FAR
  181781. #endif
  181782. /* At this point FAR is always defined */
  181783. #ifndef FARDATA
  181784. # define FARDATA
  181785. #endif
  181786. /* Typedef for floating-point numbers that are converted
  181787. to fixed-point with a multiple of 100,000, e.g., int_gamma */
  181788. typedef png_int_32 png_fixed_point;
  181789. /* Add typedefs for pointers */
  181790. typedef void FAR * png_voidp;
  181791. typedef png_byte FAR * png_bytep;
  181792. typedef png_uint_32 FAR * png_uint_32p;
  181793. typedef png_int_32 FAR * png_int_32p;
  181794. typedef png_uint_16 FAR * png_uint_16p;
  181795. typedef png_int_16 FAR * png_int_16p;
  181796. typedef PNG_CONST char FAR * png_const_charp;
  181797. typedef char FAR * png_charp;
  181798. typedef png_fixed_point FAR * png_fixed_point_p;
  181799. #ifndef PNG_NO_STDIO
  181800. #if defined(_WIN32_WCE)
  181801. typedef HANDLE png_FILE_p;
  181802. #else
  181803. typedef FILE * png_FILE_p;
  181804. #endif
  181805. #endif
  181806. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181807. typedef double FAR * png_doublep;
  181808. #endif
  181809. /* Pointers to pointers; i.e. arrays */
  181810. typedef png_byte FAR * FAR * png_bytepp;
  181811. typedef png_uint_32 FAR * FAR * png_uint_32pp;
  181812. typedef png_int_32 FAR * FAR * png_int_32pp;
  181813. typedef png_uint_16 FAR * FAR * png_uint_16pp;
  181814. typedef png_int_16 FAR * FAR * png_int_16pp;
  181815. typedef PNG_CONST char FAR * FAR * png_const_charpp;
  181816. typedef char FAR * FAR * png_charpp;
  181817. typedef png_fixed_point FAR * FAR * png_fixed_point_pp;
  181818. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181819. typedef double FAR * FAR * png_doublepp;
  181820. #endif
  181821. /* Pointers to pointers to pointers; i.e., pointer to array */
  181822. typedef char FAR * FAR * FAR * png_charppp;
  181823. #if 0
  181824. /* SPC - Is this stuff deprecated? */
  181825. /* It'll be removed as of libpng-1.3.0 - GR-P */
  181826. /* libpng typedefs for types in zlib. If zlib changes
  181827. * or another compression library is used, then change these.
  181828. * Eliminates need to change all the source files.
  181829. */
  181830. typedef charf * png_zcharp;
  181831. typedef charf * FAR * png_zcharpp;
  181832. typedef z_stream FAR * png_zstreamp;
  181833. #endif /* (PNG_1_0_X) || defined(PNG_1_2_X) */
  181834. /*
  181835. * Define PNG_BUILD_DLL if the module being built is a Windows
  181836. * LIBPNG DLL.
  181837. *
  181838. * Define PNG_USE_DLL if you want to *link* to the Windows LIBPNG DLL.
  181839. * It is equivalent to Microsoft predefined macro _DLL that is
  181840. * automatically defined when you compile using the share
  181841. * version of the CRT (C Run-Time library)
  181842. *
  181843. * The cygwin mods make this behavior a little different:
  181844. * Define PNG_BUILD_DLL if you are building a dll for use with cygwin
  181845. * Define PNG_STATIC if you are building a static library for use with cygwin,
  181846. * -or- if you are building an application that you want to link to the
  181847. * static library.
  181848. * PNG_USE_DLL is defined by default (no user action needed) unless one of
  181849. * the other flags is defined.
  181850. */
  181851. #if !defined(PNG_DLL) && (defined(PNG_BUILD_DLL) || defined(PNG_USE_DLL))
  181852. # define PNG_DLL
  181853. #endif
  181854. /* If CYGWIN, then disallow GLOBAL ARRAYS unless building a static lib.
  181855. * When building a static lib, default to no GLOBAL ARRAYS, but allow
  181856. * command-line override
  181857. */
  181858. #if defined(__CYGWIN__)
  181859. # if !defined(PNG_STATIC)
  181860. # if defined(PNG_USE_GLOBAL_ARRAYS)
  181861. # undef PNG_USE_GLOBAL_ARRAYS
  181862. # endif
  181863. # if !defined(PNG_USE_LOCAL_ARRAYS)
  181864. # define PNG_USE_LOCAL_ARRAYS
  181865. # endif
  181866. # else
  181867. # if defined(PNG_USE_LOCAL_ARRAYS) || defined(PNG_NO_GLOBAL_ARRAYS)
  181868. # if defined(PNG_USE_GLOBAL_ARRAYS)
  181869. # undef PNG_USE_GLOBAL_ARRAYS
  181870. # endif
  181871. # endif
  181872. # endif
  181873. # if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  181874. # define PNG_USE_LOCAL_ARRAYS
  181875. # endif
  181876. #endif
  181877. /* Do not use global arrays (helps with building DLL's)
  181878. * They are no longer used in libpng itself, since version 1.0.5c,
  181879. * but might be required for some pre-1.0.5c applications.
  181880. */
  181881. #if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  181882. # if defined(PNG_NO_GLOBAL_ARRAYS) || \
  181883. (defined(__GNUC__) && defined(PNG_DLL)) || defined(_MSC_VER)
  181884. # define PNG_USE_LOCAL_ARRAYS
  181885. # else
  181886. # define PNG_USE_GLOBAL_ARRAYS
  181887. # endif
  181888. #endif
  181889. #if defined(__CYGWIN__)
  181890. # undef PNGAPI
  181891. # define PNGAPI __cdecl
  181892. # undef PNG_IMPEXP
  181893. # define PNG_IMPEXP
  181894. #endif
  181895. /* If you define PNGAPI, e.g., with compiler option "-DPNGAPI=__stdcall",
  181896. * you may get warnings regarding the linkage of png_zalloc and png_zfree.
  181897. * Don't ignore those warnings; you must also reset the default calling
  181898. * convention in your compiler to match your PNGAPI, and you must build
  181899. * zlib and your applications the same way you build libpng.
  181900. */
  181901. #if defined(__MINGW32__) && !defined(PNG_MODULEDEF)
  181902. # ifndef PNG_NO_MODULEDEF
  181903. # define PNG_NO_MODULEDEF
  181904. # endif
  181905. #endif
  181906. #if !defined(PNG_IMPEXP) && defined(PNG_BUILD_DLL) && !defined(PNG_NO_MODULEDEF)
  181907. # define PNG_IMPEXP
  181908. #endif
  181909. #if defined(PNG_DLL) || defined(_DLL) || defined(__DLL__ ) || \
  181910. (( defined(_Windows) || defined(_WINDOWS) || \
  181911. defined(WIN32) || defined(_WIN32) || defined(__WIN32__) ))
  181912. # ifndef PNGAPI
  181913. # if defined(__GNUC__) || (defined (_MSC_VER) && (_MSC_VER >= 800))
  181914. # define PNGAPI __cdecl
  181915. # else
  181916. # define PNGAPI _cdecl
  181917. # endif
  181918. # endif
  181919. # if !defined(PNG_IMPEXP) && (!defined(PNG_DLL) || \
  181920. 0 /* WINCOMPILER_WITH_NO_SUPPORT_FOR_DECLIMPEXP */)
  181921. # define PNG_IMPEXP
  181922. # endif
  181923. # if !defined(PNG_IMPEXP)
  181924. # define PNG_EXPORT_TYPE1(type,symbol) PNG_IMPEXP type PNGAPI symbol
  181925. # define PNG_EXPORT_TYPE2(type,symbol) type PNG_IMPEXP PNGAPI symbol
  181926. /* Borland/Microsoft */
  181927. # if defined(_MSC_VER) || defined(__BORLANDC__)
  181928. # if (_MSC_VER >= 800) || (__BORLANDC__ >= 0x500)
  181929. # define PNG_EXPORT PNG_EXPORT_TYPE1
  181930. # else
  181931. # define PNG_EXPORT PNG_EXPORT_TYPE2
  181932. # if defined(PNG_BUILD_DLL)
  181933. # define PNG_IMPEXP __export
  181934. # else
  181935. # define PNG_IMPEXP /*__import */ /* doesn't exist AFAIK in
  181936. VC++ */
  181937. # endif /* Exists in Borland C++ for
  181938. C++ classes (== huge) */
  181939. # endif
  181940. # endif
  181941. # if !defined(PNG_IMPEXP)
  181942. # if defined(PNG_BUILD_DLL)
  181943. # define PNG_IMPEXP __declspec(dllexport)
  181944. # else
  181945. # define PNG_IMPEXP __declspec(dllimport)
  181946. # endif
  181947. # endif
  181948. # endif /* PNG_IMPEXP */
  181949. #else /* !(DLL || non-cygwin WINDOWS) */
  181950. # if (defined(__IBMC__) || defined(__IBMCPP__)) && defined(__OS2__)
  181951. # ifndef PNGAPI
  181952. # define PNGAPI _System
  181953. # endif
  181954. # else
  181955. # if 0 /* ... other platforms, with other meanings */
  181956. # endif
  181957. # endif
  181958. #endif
  181959. #ifndef PNGAPI
  181960. # define PNGAPI
  181961. #endif
  181962. #ifndef PNG_IMPEXP
  181963. # define PNG_IMPEXP
  181964. #endif
  181965. #ifdef PNG_BUILDSYMS
  181966. # ifndef PNG_EXPORT
  181967. # define PNG_EXPORT(type,symbol) PNG_FUNCTION_EXPORT symbol END
  181968. # endif
  181969. # ifdef PNG_USE_GLOBAL_ARRAYS
  181970. # ifndef PNG_EXPORT_VAR
  181971. # define PNG_EXPORT_VAR(type) PNG_DATA_EXPORT
  181972. # endif
  181973. # endif
  181974. #endif
  181975. #ifndef PNG_EXPORT
  181976. # define PNG_EXPORT(type,symbol) PNG_IMPEXP type PNGAPI symbol
  181977. #endif
  181978. #ifdef PNG_USE_GLOBAL_ARRAYS
  181979. # ifndef PNG_EXPORT_VAR
  181980. # define PNG_EXPORT_VAR(type) extern PNG_IMPEXP type
  181981. # endif
  181982. #endif
  181983. /* User may want to use these so they are not in PNG_INTERNAL. Any library
  181984. * functions that are passed far data must be model independent.
  181985. */
  181986. #ifndef PNG_ABORT
  181987. # define PNG_ABORT() abort()
  181988. #endif
  181989. #ifdef PNG_SETJMP_SUPPORTED
  181990. # define png_jmpbuf(png_ptr) ((png_ptr)->jmpbuf)
  181991. #else
  181992. # define png_jmpbuf(png_ptr) \
  181993. (LIBPNG_WAS_COMPILED_WITH__PNG_SETJMP_NOT_SUPPORTED)
  181994. #endif
  181995. #if defined(USE_FAR_KEYWORD) /* memory model independent fns */
  181996. /* use this to make far-to-near assignments */
  181997. # define CHECK 1
  181998. # define NOCHECK 0
  181999. # define CVT_PTR(ptr) (png_far_to_near(png_ptr,ptr,CHECK))
  182000. # define CVT_PTR_NOCHECK(ptr) (png_far_to_near(png_ptr,ptr,NOCHECK))
  182001. # define png_snprintf _fsnprintf /* Added to v 1.2.19 */
  182002. # define png_strcpy _fstrcpy
  182003. # define png_strncpy _fstrncpy /* Added to v 1.2.6 */
  182004. # define png_strlen _fstrlen
  182005. # define png_memcmp _fmemcmp /* SJT: added */
  182006. # define png_memcpy _fmemcpy
  182007. # define png_memset _fmemset
  182008. #else /* use the usual functions */
  182009. # define CVT_PTR(ptr) (ptr)
  182010. # define CVT_PTR_NOCHECK(ptr) (ptr)
  182011. # ifndef PNG_NO_SNPRINTF
  182012. # ifdef _MSC_VER
  182013. # define png_snprintf _snprintf /* Added to v 1.2.19 */
  182014. # define png_snprintf2 _snprintf
  182015. # define png_snprintf6 _snprintf
  182016. # else
  182017. # define png_snprintf snprintf /* Added to v 1.2.19 */
  182018. # define png_snprintf2 snprintf
  182019. # define png_snprintf6 snprintf
  182020. # endif
  182021. # else
  182022. /* You don't have or don't want to use snprintf(). Caution: Using
  182023. * sprintf instead of snprintf exposes your application to accidental
  182024. * or malevolent buffer overflows. If you don't have snprintf()
  182025. * as a general rule you should provide one (you can get one from
  182026. * Portable OpenSSH). */
  182027. # define png_snprintf(s1,n,fmt,x1) sprintf(s1,fmt,x1)
  182028. # define png_snprintf2(s1,n,fmt,x1,x2) sprintf(s1,fmt,x1,x2)
  182029. # define png_snprintf6(s1,n,fmt,x1,x2,x3,x4,x5,x6) \
  182030. sprintf(s1,fmt,x1,x2,x3,x4,x5,x6)
  182031. # endif
  182032. # define png_strcpy strcpy
  182033. # define png_strncpy strncpy /* Added to v 1.2.6 */
  182034. # define png_strlen strlen
  182035. # define png_memcmp memcmp /* SJT: added */
  182036. # define png_memcpy memcpy
  182037. # define png_memset memset
  182038. #endif
  182039. /* End of memory model independent support */
  182040. /* Just a little check that someone hasn't tried to define something
  182041. * contradictory.
  182042. */
  182043. #if (PNG_ZBUF_SIZE > 65536L) && defined(PNG_MAX_MALLOC_64K)
  182044. # undef PNG_ZBUF_SIZE
  182045. # define PNG_ZBUF_SIZE 65536L
  182046. #endif
  182047. /* Added at libpng-1.2.8 */
  182048. #endif /* PNG_VERSION_INFO_ONLY */
  182049. #endif /* PNGCONF_H */
  182050. /*** End of inlined file: pngconf.h ***/
  182051. #ifdef _MSC_VER
  182052. #pragma warning (disable: 4996 4100)
  182053. #endif
  182054. /*
  182055. * Added at libpng-1.2.8 */
  182056. /* Ref MSDN: Private as priority over Special
  182057. * VS_FF_PRIVATEBUILD File *was not* built using standard release
  182058. * procedures. If this value is given, the StringFileInfo block must
  182059. * contain a PrivateBuild string.
  182060. *
  182061. * VS_FF_SPECIALBUILD File *was* built by the original company using
  182062. * standard release procedures but is a variation of the standard
  182063. * file of the same version number. If this value is given, the
  182064. * StringFileInfo block must contain a SpecialBuild string.
  182065. */
  182066. #if defined(PNG_USER_PRIVATEBUILD)
  182067. # define PNG_LIBPNG_BUILD_TYPE \
  182068. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_PRIVATE)
  182069. #else
  182070. # if defined(PNG_LIBPNG_SPECIALBUILD)
  182071. # define PNG_LIBPNG_BUILD_TYPE \
  182072. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_SPECIAL)
  182073. # else
  182074. # define PNG_LIBPNG_BUILD_TYPE (PNG_LIBPNG_BUILD_BASE_TYPE)
  182075. # endif
  182076. #endif
  182077. #ifndef PNG_VERSION_INFO_ONLY
  182078. /* Inhibit C++ name-mangling for libpng functions but not for system calls. */
  182079. #ifdef __cplusplus
  182080. //extern "C" {
  182081. #endif /* __cplusplus */
  182082. /* This file is arranged in several sections. The first section contains
  182083. * structure and type definitions. The second section contains the external
  182084. * library functions, while the third has the internal library functions,
  182085. * which applications aren't expected to use directly.
  182086. */
  182087. #ifndef PNG_NO_TYPECAST_NULL
  182088. #define int_p_NULL (int *)NULL
  182089. #define png_bytep_NULL (png_bytep)NULL
  182090. #define png_bytepp_NULL (png_bytepp)NULL
  182091. #define png_doublep_NULL (png_doublep)NULL
  182092. #define png_error_ptr_NULL (png_error_ptr)NULL
  182093. #define png_flush_ptr_NULL (png_flush_ptr)NULL
  182094. #define png_free_ptr_NULL (png_free_ptr)NULL
  182095. #define png_infopp_NULL (png_infopp)NULL
  182096. #define png_malloc_ptr_NULL (png_malloc_ptr)NULL
  182097. #define png_read_status_ptr_NULL (png_read_status_ptr)NULL
  182098. #define png_rw_ptr_NULL (png_rw_ptr)NULL
  182099. #define png_structp_NULL (png_structp)NULL
  182100. #define png_uint_16p_NULL (png_uint_16p)NULL
  182101. #define png_voidp_NULL (png_voidp)NULL
  182102. #define png_write_status_ptr_NULL (png_write_status_ptr)NULL
  182103. #else
  182104. #define int_p_NULL NULL
  182105. #define png_bytep_NULL NULL
  182106. #define png_bytepp_NULL NULL
  182107. #define png_doublep_NULL NULL
  182108. #define png_error_ptr_NULL NULL
  182109. #define png_flush_ptr_NULL NULL
  182110. #define png_free_ptr_NULL NULL
  182111. #define png_infopp_NULL NULL
  182112. #define png_malloc_ptr_NULL NULL
  182113. #define png_read_status_ptr_NULL NULL
  182114. #define png_rw_ptr_NULL NULL
  182115. #define png_structp_NULL NULL
  182116. #define png_uint_16p_NULL NULL
  182117. #define png_voidp_NULL NULL
  182118. #define png_write_status_ptr_NULL NULL
  182119. #endif
  182120. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  182121. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  182122. /* Version information for C files, stored in png.c. This had better match
  182123. * the version above.
  182124. */
  182125. #ifdef PNG_USE_GLOBAL_ARRAYS
  182126. PNG_EXPORT_VAR (PNG_CONST char) png_libpng_ver[18];
  182127. /* need room for 99.99.99beta99z */
  182128. #else
  182129. #define png_libpng_ver png_get_header_ver(NULL)
  182130. #endif
  182131. #ifdef PNG_USE_GLOBAL_ARRAYS
  182132. /* This was removed in version 1.0.5c */
  182133. /* Structures to facilitate easy interlacing. See png.c for more details */
  182134. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_start[7];
  182135. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_inc[7];
  182136. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_ystart[7];
  182137. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_yinc[7];
  182138. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_mask[7];
  182139. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_dsp_mask[7];
  182140. /* This isn't currently used. If you need it, see png.c for more details.
  182141. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_height[7];
  182142. */
  182143. #endif
  182144. #endif /* PNG_NO_EXTERN */
  182145. /* Three color definitions. The order of the red, green, and blue, (and the
  182146. * exact size) is not important, although the size of the fields need to
  182147. * be png_byte or png_uint_16 (as defined below).
  182148. */
  182149. typedef struct png_color_struct
  182150. {
  182151. png_byte red;
  182152. png_byte green;
  182153. png_byte blue;
  182154. } png_color;
  182155. typedef png_color FAR * png_colorp;
  182156. typedef png_color FAR * FAR * png_colorpp;
  182157. typedef struct png_color_16_struct
  182158. {
  182159. png_byte index; /* used for palette files */
  182160. png_uint_16 red; /* for use in red green blue files */
  182161. png_uint_16 green;
  182162. png_uint_16 blue;
  182163. png_uint_16 gray; /* for use in grayscale files */
  182164. } png_color_16;
  182165. typedef png_color_16 FAR * png_color_16p;
  182166. typedef png_color_16 FAR * FAR * png_color_16pp;
  182167. typedef struct png_color_8_struct
  182168. {
  182169. png_byte red; /* for use in red green blue files */
  182170. png_byte green;
  182171. png_byte blue;
  182172. png_byte gray; /* for use in grayscale files */
  182173. png_byte alpha; /* for alpha channel files */
  182174. } png_color_8;
  182175. typedef png_color_8 FAR * png_color_8p;
  182176. typedef png_color_8 FAR * FAR * png_color_8pp;
  182177. /*
  182178. * The following two structures are used for the in-core representation
  182179. * of sPLT chunks.
  182180. */
  182181. typedef struct png_sPLT_entry_struct
  182182. {
  182183. png_uint_16 red;
  182184. png_uint_16 green;
  182185. png_uint_16 blue;
  182186. png_uint_16 alpha;
  182187. png_uint_16 frequency;
  182188. } png_sPLT_entry;
  182189. typedef png_sPLT_entry FAR * png_sPLT_entryp;
  182190. typedef png_sPLT_entry FAR * FAR * png_sPLT_entrypp;
  182191. /* When the depth of the sPLT palette is 8 bits, the color and alpha samples
  182192. * occupy the LSB of their respective members, and the MSB of each member
  182193. * is zero-filled. The frequency member always occupies the full 16 bits.
  182194. */
  182195. typedef struct png_sPLT_struct
  182196. {
  182197. png_charp name; /* palette name */
  182198. png_byte depth; /* depth of palette samples */
  182199. png_sPLT_entryp entries; /* palette entries */
  182200. png_int_32 nentries; /* number of palette entries */
  182201. } png_sPLT_t;
  182202. typedef png_sPLT_t FAR * png_sPLT_tp;
  182203. typedef png_sPLT_t FAR * FAR * png_sPLT_tpp;
  182204. #ifdef PNG_TEXT_SUPPORTED
  182205. /* png_text holds the contents of a text/ztxt/itxt chunk in a PNG file,
  182206. * and whether that contents is compressed or not. The "key" field
  182207. * points to a regular zero-terminated C string. The "text", "lang", and
  182208. * "lang_key" fields can be regular C strings, empty strings, or NULL pointers.
  182209. * However, the * structure returned by png_get_text() will always contain
  182210. * regular zero-terminated C strings (possibly empty), never NULL pointers,
  182211. * so they can be safely used in printf() and other string-handling functions.
  182212. */
  182213. typedef struct png_text_struct
  182214. {
  182215. int compression; /* compression value:
  182216. -1: tEXt, none
  182217. 0: zTXt, deflate
  182218. 1: iTXt, none
  182219. 2: iTXt, deflate */
  182220. png_charp key; /* keyword, 1-79 character description of "text" */
  182221. png_charp text; /* comment, may be an empty string (ie "")
  182222. or a NULL pointer */
  182223. png_size_t text_length; /* length of the text string */
  182224. #ifdef PNG_iTXt_SUPPORTED
  182225. png_size_t itxt_length; /* length of the itxt string */
  182226. png_charp lang; /* language code, 0-79 characters
  182227. or a NULL pointer */
  182228. png_charp lang_key; /* keyword translated UTF-8 string, 0 or more
  182229. chars or a NULL pointer */
  182230. #endif
  182231. } png_text;
  182232. typedef png_text FAR * png_textp;
  182233. typedef png_text FAR * FAR * png_textpp;
  182234. #endif
  182235. /* Supported compression types for text in PNG files (tEXt, and zTXt).
  182236. * The values of the PNG_TEXT_COMPRESSION_ defines should NOT be changed. */
  182237. #define PNG_TEXT_COMPRESSION_NONE_WR -3
  182238. #define PNG_TEXT_COMPRESSION_zTXt_WR -2
  182239. #define PNG_TEXT_COMPRESSION_NONE -1
  182240. #define PNG_TEXT_COMPRESSION_zTXt 0
  182241. #define PNG_ITXT_COMPRESSION_NONE 1
  182242. #define PNG_ITXT_COMPRESSION_zTXt 2
  182243. #define PNG_TEXT_COMPRESSION_LAST 3 /* Not a valid value */
  182244. /* png_time is a way to hold the time in an machine independent way.
  182245. * Two conversions are provided, both from time_t and struct tm. There
  182246. * is no portable way to convert to either of these structures, as far
  182247. * as I know. If you know of a portable way, send it to me. As a side
  182248. * note - PNG has always been Year 2000 compliant!
  182249. */
  182250. typedef struct png_time_struct
  182251. {
  182252. png_uint_16 year; /* full year, as in, 1995 */
  182253. png_byte month; /* month of year, 1 - 12 */
  182254. png_byte day; /* day of month, 1 - 31 */
  182255. png_byte hour; /* hour of day, 0 - 23 */
  182256. png_byte minute; /* minute of hour, 0 - 59 */
  182257. png_byte second; /* second of minute, 0 - 60 (for leap seconds) */
  182258. } png_time;
  182259. typedef png_time FAR * png_timep;
  182260. typedef png_time FAR * FAR * png_timepp;
  182261. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182262. /* png_unknown_chunk is a structure to hold queued chunks for which there is
  182263. * no specific support. The idea is that we can use this to queue
  182264. * up private chunks for output even though the library doesn't actually
  182265. * know about their semantics.
  182266. */
  182267. typedef struct png_unknown_chunk_t
  182268. {
  182269. png_byte name[5];
  182270. png_byte *data;
  182271. png_size_t size;
  182272. /* libpng-using applications should NOT directly modify this byte. */
  182273. png_byte location; /* mode of operation at read time */
  182274. }
  182275. png_unknown_chunk;
  182276. typedef png_unknown_chunk FAR * png_unknown_chunkp;
  182277. typedef png_unknown_chunk FAR * FAR * png_unknown_chunkpp;
  182278. #endif
  182279. /* png_info is a structure that holds the information in a PNG file so
  182280. * that the application can find out the characteristics of the image.
  182281. * If you are reading the file, this structure will tell you what is
  182282. * in the PNG file. If you are writing the file, fill in the information
  182283. * you want to put into the PNG file, then call png_write_info().
  182284. * The names chosen should be very close to the PNG specification, so
  182285. * consult that document for information about the meaning of each field.
  182286. *
  182287. * With libpng < 0.95, it was only possible to directly set and read the
  182288. * the values in the png_info_struct, which meant that the contents and
  182289. * order of the values had to remain fixed. With libpng 0.95 and later,
  182290. * however, there are now functions that abstract the contents of
  182291. * png_info_struct from the application, so this makes it easier to use
  182292. * libpng with dynamic libraries, and even makes it possible to use
  182293. * libraries that don't have all of the libpng ancillary chunk-handing
  182294. * functionality.
  182295. *
  182296. * In any case, the order of the parameters in png_info_struct should NOT
  182297. * be changed for as long as possible to keep compatibility with applications
  182298. * that use the old direct-access method with png_info_struct.
  182299. *
  182300. * The following members may have allocated storage attached that should be
  182301. * cleaned up before the structure is discarded: palette, trans, text,
  182302. * pcal_purpose, pcal_units, pcal_params, hist, iccp_name, iccp_profile,
  182303. * splt_palettes, scal_unit, row_pointers, and unknowns. By default, these
  182304. * are automatically freed when the info structure is deallocated, if they were
  182305. * allocated internally by libpng. This behavior can be changed by means
  182306. * of the png_data_freer() function.
  182307. *
  182308. * More allocation details: all the chunk-reading functions that
  182309. * change these members go through the corresponding png_set_*
  182310. * functions. A function to clear these members is available: see
  182311. * png_free_data(). The png_set_* functions do not depend on being
  182312. * able to point info structure members to any of the storage they are
  182313. * passed (they make their own copies), EXCEPT that the png_set_text
  182314. * functions use the same storage passed to them in the text_ptr or
  182315. * itxt_ptr structure argument, and the png_set_rows and png_set_unknowns
  182316. * functions do not make their own copies.
  182317. */
  182318. typedef struct png_info_struct
  182319. {
  182320. /* the following are necessary for every PNG file */
  182321. png_uint_32 width; /* width of image in pixels (from IHDR) */
  182322. png_uint_32 height; /* height of image in pixels (from IHDR) */
  182323. png_uint_32 valid; /* valid chunk data (see PNG_INFO_ below) */
  182324. png_uint_32 rowbytes; /* bytes needed to hold an untransformed row */
  182325. png_colorp palette; /* array of color values (valid & PNG_INFO_PLTE) */
  182326. png_uint_16 num_palette; /* number of color entries in "palette" (PLTE) */
  182327. png_uint_16 num_trans; /* number of transparent palette color (tRNS) */
  182328. png_byte bit_depth; /* 1, 2, 4, 8, or 16 bits/channel (from IHDR) */
  182329. png_byte color_type; /* see PNG_COLOR_TYPE_ below (from IHDR) */
  182330. /* The following three should have been named *_method not *_type */
  182331. png_byte compression_type; /* must be PNG_COMPRESSION_TYPE_BASE (IHDR) */
  182332. png_byte filter_type; /* must be PNG_FILTER_TYPE_BASE (from IHDR) */
  182333. png_byte interlace_type; /* One of PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  182334. /* The following is informational only on read, and not used on writes. */
  182335. png_byte channels; /* number of data channels per pixel (1, 2, 3, 4) */
  182336. png_byte pixel_depth; /* number of bits per pixel */
  182337. png_byte spare_byte; /* to align the data, and for future use */
  182338. png_byte signature[8]; /* magic bytes read by libpng from start of file */
  182339. /* The rest of the data is optional. If you are reading, check the
  182340. * valid field to see if the information in these are valid. If you
  182341. * are writing, set the valid field to those chunks you want written,
  182342. * and initialize the appropriate fields below.
  182343. */
  182344. #if defined(PNG_gAMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  182345. /* The gAMA chunk describes the gamma characteristics of the system
  182346. * on which the image was created, normally in the range [1.0, 2.5].
  182347. * Data is valid if (valid & PNG_INFO_gAMA) is non-zero.
  182348. */
  182349. float gamma; /* gamma value of image, if (valid & PNG_INFO_gAMA) */
  182350. #endif
  182351. #if defined(PNG_sRGB_SUPPORTED)
  182352. /* GR-P, 0.96a */
  182353. /* Data valid if (valid & PNG_INFO_sRGB) non-zero. */
  182354. png_byte srgb_intent; /* sRGB rendering intent [0, 1, 2, or 3] */
  182355. #endif
  182356. #if defined(PNG_TEXT_SUPPORTED)
  182357. /* The tEXt, and zTXt chunks contain human-readable textual data in
  182358. * uncompressed, compressed, and optionally compressed forms, respectively.
  182359. * The data in "text" is an array of pointers to uncompressed,
  182360. * null-terminated C strings. Each chunk has a keyword that describes the
  182361. * textual data contained in that chunk. Keywords are not required to be
  182362. * unique, and the text string may be empty. Any number of text chunks may
  182363. * be in an image.
  182364. */
  182365. int num_text; /* number of comments read/to write */
  182366. int max_text; /* current size of text array */
  182367. png_textp text; /* array of comments read/to write */
  182368. #endif /* PNG_TEXT_SUPPORTED */
  182369. #if defined(PNG_tIME_SUPPORTED)
  182370. /* The tIME chunk holds the last time the displayed image data was
  182371. * modified. See the png_time struct for the contents of this struct.
  182372. */
  182373. png_time mod_time;
  182374. #endif
  182375. #if defined(PNG_sBIT_SUPPORTED)
  182376. /* The sBIT chunk specifies the number of significant high-order bits
  182377. * in the pixel data. Values are in the range [1, bit_depth], and are
  182378. * only specified for the channels in the pixel data. The contents of
  182379. * the low-order bits is not specified. Data is valid if
  182380. * (valid & PNG_INFO_sBIT) is non-zero.
  182381. */
  182382. png_color_8 sig_bit; /* significant bits in color channels */
  182383. #endif
  182384. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_EXPAND_SUPPORTED) || \
  182385. defined(PNG_READ_BACKGROUND_SUPPORTED)
  182386. /* The tRNS chunk supplies transparency data for paletted images and
  182387. * other image types that don't need a full alpha channel. There are
  182388. * "num_trans" transparency values for a paletted image, stored in the
  182389. * same order as the palette colors, starting from index 0. Values
  182390. * for the data are in the range [0, 255], ranging from fully transparent
  182391. * to fully opaque, respectively. For non-paletted images, there is a
  182392. * single color specified that should be treated as fully transparent.
  182393. * Data is valid if (valid & PNG_INFO_tRNS) is non-zero.
  182394. */
  182395. png_bytep trans; /* transparent values for paletted image */
  182396. png_color_16 trans_values; /* transparent color for non-palette image */
  182397. #endif
  182398. #if defined(PNG_bKGD_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182399. /* The bKGD chunk gives the suggested image background color if the
  182400. * display program does not have its own background color and the image
  182401. * is needs to composited onto a background before display. The colors
  182402. * in "background" are normally in the same color space/depth as the
  182403. * pixel data. Data is valid if (valid & PNG_INFO_bKGD) is non-zero.
  182404. */
  182405. png_color_16 background;
  182406. #endif
  182407. #if defined(PNG_oFFs_SUPPORTED)
  182408. /* The oFFs chunk gives the offset in "offset_unit_type" units rightwards
  182409. * and downwards from the top-left corner of the display, page, or other
  182410. * application-specific co-ordinate space. See the PNG_OFFSET_ defines
  182411. * below for the unit types. Valid if (valid & PNG_INFO_oFFs) non-zero.
  182412. */
  182413. png_int_32 x_offset; /* x offset on page */
  182414. png_int_32 y_offset; /* y offset on page */
  182415. png_byte offset_unit_type; /* offset units type */
  182416. #endif
  182417. #if defined(PNG_pHYs_SUPPORTED)
  182418. /* The pHYs chunk gives the physical pixel density of the image for
  182419. * display or printing in "phys_unit_type" units (see PNG_RESOLUTION_
  182420. * defines below). Data is valid if (valid & PNG_INFO_pHYs) is non-zero.
  182421. */
  182422. png_uint_32 x_pixels_per_unit; /* horizontal pixel density */
  182423. png_uint_32 y_pixels_per_unit; /* vertical pixel density */
  182424. png_byte phys_unit_type; /* resolution type (see PNG_RESOLUTION_ below) */
  182425. #endif
  182426. #if defined(PNG_hIST_SUPPORTED)
  182427. /* The hIST chunk contains the relative frequency or importance of the
  182428. * various palette entries, so that a viewer can intelligently select a
  182429. * reduced-color palette, if required. Data is an array of "num_palette"
  182430. * values in the range [0,65535]. Data valid if (valid & PNG_INFO_hIST)
  182431. * is non-zero.
  182432. */
  182433. png_uint_16p hist;
  182434. #endif
  182435. #ifdef PNG_cHRM_SUPPORTED
  182436. /* The cHRM chunk describes the CIE color characteristics of the monitor
  182437. * on which the PNG was created. This data allows the viewer to do gamut
  182438. * mapping of the input image to ensure that the viewer sees the same
  182439. * colors in the image as the creator. Values are in the range
  182440. * [0.0, 0.8]. Data valid if (valid & PNG_INFO_cHRM) non-zero.
  182441. */
  182442. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182443. float x_white;
  182444. float y_white;
  182445. float x_red;
  182446. float y_red;
  182447. float x_green;
  182448. float y_green;
  182449. float x_blue;
  182450. float y_blue;
  182451. #endif
  182452. #endif
  182453. #if defined(PNG_pCAL_SUPPORTED)
  182454. /* The pCAL chunk describes a transformation between the stored pixel
  182455. * values and original physical data values used to create the image.
  182456. * The integer range [0, 2^bit_depth - 1] maps to the floating-point
  182457. * range given by [pcal_X0, pcal_X1], and are further transformed by a
  182458. * (possibly non-linear) transformation function given by "pcal_type"
  182459. * and "pcal_params" into "pcal_units". Please see the PNG_EQUATION_
  182460. * defines below, and the PNG-Group's PNG extensions document for a
  182461. * complete description of the transformations and how they should be
  182462. * implemented, and for a description of the ASCII parameter strings.
  182463. * Data values are valid if (valid & PNG_INFO_pCAL) non-zero.
  182464. */
  182465. png_charp pcal_purpose; /* pCAL chunk description string */
  182466. png_int_32 pcal_X0; /* minimum value */
  182467. png_int_32 pcal_X1; /* maximum value */
  182468. png_charp pcal_units; /* Latin-1 string giving physical units */
  182469. png_charpp pcal_params; /* ASCII strings containing parameter values */
  182470. png_byte pcal_type; /* equation type (see PNG_EQUATION_ below) */
  182471. png_byte pcal_nparams; /* number of parameters given in pcal_params */
  182472. #endif
  182473. /* New members added in libpng-1.0.6 */
  182474. #ifdef PNG_FREE_ME_SUPPORTED
  182475. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  182476. #endif
  182477. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182478. /* storage for unknown chunks that the library doesn't recognize. */
  182479. png_unknown_chunkp unknown_chunks;
  182480. png_size_t unknown_chunks_num;
  182481. #endif
  182482. #if defined(PNG_iCCP_SUPPORTED)
  182483. /* iCCP chunk data. */
  182484. png_charp iccp_name; /* profile name */
  182485. png_charp iccp_profile; /* International Color Consortium profile data */
  182486. /* Note to maintainer: should be png_bytep */
  182487. png_uint_32 iccp_proflen; /* ICC profile data length */
  182488. png_byte iccp_compression; /* Always zero */
  182489. #endif
  182490. #if defined(PNG_sPLT_SUPPORTED)
  182491. /* data on sPLT chunks (there may be more than one). */
  182492. png_sPLT_tp splt_palettes;
  182493. png_uint_32 splt_palettes_num;
  182494. #endif
  182495. #if defined(PNG_sCAL_SUPPORTED)
  182496. /* The sCAL chunk describes the actual physical dimensions of the
  182497. * subject matter of the graphic. The chunk contains a unit specification
  182498. * a byte value, and two ASCII strings representing floating-point
  182499. * values. The values are width and height corresponsing to one pixel
  182500. * in the image. This external representation is converted to double
  182501. * here. Data values are valid if (valid & PNG_INFO_sCAL) is non-zero.
  182502. */
  182503. png_byte scal_unit; /* unit of physical scale */
  182504. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182505. double scal_pixel_width; /* width of one pixel */
  182506. double scal_pixel_height; /* height of one pixel */
  182507. #endif
  182508. #ifdef PNG_FIXED_POINT_SUPPORTED
  182509. png_charp scal_s_width; /* string containing height */
  182510. png_charp scal_s_height; /* string containing width */
  182511. #endif
  182512. #endif
  182513. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  182514. /* Memory has been allocated if (valid & PNG_ALLOCATED_INFO_ROWS) non-zero */
  182515. /* Data valid if (valid & PNG_INFO_IDAT) non-zero */
  182516. png_bytepp row_pointers; /* the image bits */
  182517. #endif
  182518. #if defined(PNG_FIXED_POINT_SUPPORTED) && defined(PNG_gAMA_SUPPORTED)
  182519. png_fixed_point int_gamma; /* gamma of image, if (valid & PNG_INFO_gAMA) */
  182520. #endif
  182521. #if defined(PNG_cHRM_SUPPORTED) && defined(PNG_FIXED_POINT_SUPPORTED)
  182522. png_fixed_point int_x_white;
  182523. png_fixed_point int_y_white;
  182524. png_fixed_point int_x_red;
  182525. png_fixed_point int_y_red;
  182526. png_fixed_point int_x_green;
  182527. png_fixed_point int_y_green;
  182528. png_fixed_point int_x_blue;
  182529. png_fixed_point int_y_blue;
  182530. #endif
  182531. } png_info;
  182532. typedef png_info FAR * png_infop;
  182533. typedef png_info FAR * FAR * png_infopp;
  182534. /* Maximum positive integer used in PNG is (2^31)-1 */
  182535. #define PNG_UINT_31_MAX ((png_uint_32)0x7fffffffL)
  182536. #define PNG_UINT_32_MAX ((png_uint_32)(-1))
  182537. #define PNG_SIZE_MAX ((png_size_t)(-1))
  182538. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182539. /* PNG_MAX_UINT is deprecated; use PNG_UINT_31_MAX instead. */
  182540. #define PNG_MAX_UINT PNG_UINT_31_MAX
  182541. #endif
  182542. /* These describe the color_type field in png_info. */
  182543. /* color type masks */
  182544. #define PNG_COLOR_MASK_PALETTE 1
  182545. #define PNG_COLOR_MASK_COLOR 2
  182546. #define PNG_COLOR_MASK_ALPHA 4
  182547. /* color types. Note that not all combinations are legal */
  182548. #define PNG_COLOR_TYPE_GRAY 0
  182549. #define PNG_COLOR_TYPE_PALETTE (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_PALETTE)
  182550. #define PNG_COLOR_TYPE_RGB (PNG_COLOR_MASK_COLOR)
  182551. #define PNG_COLOR_TYPE_RGB_ALPHA (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_ALPHA)
  182552. #define PNG_COLOR_TYPE_GRAY_ALPHA (PNG_COLOR_MASK_ALPHA)
  182553. /* aliases */
  182554. #define PNG_COLOR_TYPE_RGBA PNG_COLOR_TYPE_RGB_ALPHA
  182555. #define PNG_COLOR_TYPE_GA PNG_COLOR_TYPE_GRAY_ALPHA
  182556. /* This is for compression type. PNG 1.0-1.2 only define the single type. */
  182557. #define PNG_COMPRESSION_TYPE_BASE 0 /* Deflate method 8, 32K window */
  182558. #define PNG_COMPRESSION_TYPE_DEFAULT PNG_COMPRESSION_TYPE_BASE
  182559. /* This is for filter type. PNG 1.0-1.2 only define the single type. */
  182560. #define PNG_FILTER_TYPE_BASE 0 /* Single row per-byte filtering */
  182561. #define PNG_INTRAPIXEL_DIFFERENCING 64 /* Used only in MNG datastreams */
  182562. #define PNG_FILTER_TYPE_DEFAULT PNG_FILTER_TYPE_BASE
  182563. /* These are for the interlacing type. These values should NOT be changed. */
  182564. #define PNG_INTERLACE_NONE 0 /* Non-interlaced image */
  182565. #define PNG_INTERLACE_ADAM7 1 /* Adam7 interlacing */
  182566. #define PNG_INTERLACE_LAST 2 /* Not a valid value */
  182567. /* These are for the oFFs chunk. These values should NOT be changed. */
  182568. #define PNG_OFFSET_PIXEL 0 /* Offset in pixels */
  182569. #define PNG_OFFSET_MICROMETER 1 /* Offset in micrometers (1/10^6 meter) */
  182570. #define PNG_OFFSET_LAST 2 /* Not a valid value */
  182571. /* These are for the pCAL chunk. These values should NOT be changed. */
  182572. #define PNG_EQUATION_LINEAR 0 /* Linear transformation */
  182573. #define PNG_EQUATION_BASE_E 1 /* Exponential base e transform */
  182574. #define PNG_EQUATION_ARBITRARY 2 /* Arbitrary base exponential transform */
  182575. #define PNG_EQUATION_HYPERBOLIC 3 /* Hyperbolic sine transformation */
  182576. #define PNG_EQUATION_LAST 4 /* Not a valid value */
  182577. /* These are for the sCAL chunk. These values should NOT be changed. */
  182578. #define PNG_SCALE_UNKNOWN 0 /* unknown unit (image scale) */
  182579. #define PNG_SCALE_METER 1 /* meters per pixel */
  182580. #define PNG_SCALE_RADIAN 2 /* radians per pixel */
  182581. #define PNG_SCALE_LAST 3 /* Not a valid value */
  182582. /* These are for the pHYs chunk. These values should NOT be changed. */
  182583. #define PNG_RESOLUTION_UNKNOWN 0 /* pixels/unknown unit (aspect ratio) */
  182584. #define PNG_RESOLUTION_METER 1 /* pixels/meter */
  182585. #define PNG_RESOLUTION_LAST 2 /* Not a valid value */
  182586. /* These are for the sRGB chunk. These values should NOT be changed. */
  182587. #define PNG_sRGB_INTENT_PERCEPTUAL 0
  182588. #define PNG_sRGB_INTENT_RELATIVE 1
  182589. #define PNG_sRGB_INTENT_SATURATION 2
  182590. #define PNG_sRGB_INTENT_ABSOLUTE 3
  182591. #define PNG_sRGB_INTENT_LAST 4 /* Not a valid value */
  182592. /* This is for text chunks */
  182593. #define PNG_KEYWORD_MAX_LENGTH 79
  182594. /* Maximum number of entries in PLTE/sPLT/tRNS arrays */
  182595. #define PNG_MAX_PALETTE_LENGTH 256
  182596. /* These determine if an ancillary chunk's data has been successfully read
  182597. * from the PNG header, or if the application has filled in the corresponding
  182598. * data in the info_struct to be written into the output file. The values
  182599. * of the PNG_INFO_<chunk> defines should NOT be changed.
  182600. */
  182601. #define PNG_INFO_gAMA 0x0001
  182602. #define PNG_INFO_sBIT 0x0002
  182603. #define PNG_INFO_cHRM 0x0004
  182604. #define PNG_INFO_PLTE 0x0008
  182605. #define PNG_INFO_tRNS 0x0010
  182606. #define PNG_INFO_bKGD 0x0020
  182607. #define PNG_INFO_hIST 0x0040
  182608. #define PNG_INFO_pHYs 0x0080
  182609. #define PNG_INFO_oFFs 0x0100
  182610. #define PNG_INFO_tIME 0x0200
  182611. #define PNG_INFO_pCAL 0x0400
  182612. #define PNG_INFO_sRGB 0x0800 /* GR-P, 0.96a */
  182613. #define PNG_INFO_iCCP 0x1000 /* ESR, 1.0.6 */
  182614. #define PNG_INFO_sPLT 0x2000 /* ESR, 1.0.6 */
  182615. #define PNG_INFO_sCAL 0x4000 /* ESR, 1.0.6 */
  182616. #define PNG_INFO_IDAT 0x8000L /* ESR, 1.0.6 */
  182617. /* This is used for the transformation routines, as some of them
  182618. * change these values for the row. It also should enable using
  182619. * the routines for other purposes.
  182620. */
  182621. typedef struct png_row_info_struct
  182622. {
  182623. png_uint_32 width; /* width of row */
  182624. png_uint_32 rowbytes; /* number of bytes in row */
  182625. png_byte color_type; /* color type of row */
  182626. png_byte bit_depth; /* bit depth of row */
  182627. png_byte channels; /* number of channels (1, 2, 3, or 4) */
  182628. png_byte pixel_depth; /* bits per pixel (depth * channels) */
  182629. } png_row_info;
  182630. typedef png_row_info FAR * png_row_infop;
  182631. typedef png_row_info FAR * FAR * png_row_infopp;
  182632. /* These are the function types for the I/O functions and for the functions
  182633. * that allow the user to override the default I/O functions with his or her
  182634. * own. The png_error_ptr type should match that of user-supplied warning
  182635. * and error functions, while the png_rw_ptr type should match that of the
  182636. * user read/write data functions.
  182637. */
  182638. typedef struct png_struct_def png_struct;
  182639. typedef png_struct FAR * png_structp;
  182640. typedef void (PNGAPI *png_error_ptr) PNGARG((png_structp, png_const_charp));
  182641. typedef void (PNGAPI *png_rw_ptr) PNGARG((png_structp, png_bytep, png_size_t));
  182642. typedef void (PNGAPI *png_flush_ptr) PNGARG((png_structp));
  182643. typedef void (PNGAPI *png_read_status_ptr) PNGARG((png_structp, png_uint_32,
  182644. int));
  182645. typedef void (PNGAPI *png_write_status_ptr) PNGARG((png_structp, png_uint_32,
  182646. int));
  182647. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  182648. typedef void (PNGAPI *png_progressive_info_ptr) PNGARG((png_structp, png_infop));
  182649. typedef void (PNGAPI *png_progressive_end_ptr) PNGARG((png_structp, png_infop));
  182650. typedef void (PNGAPI *png_progressive_row_ptr) PNGARG((png_structp, png_bytep,
  182651. png_uint_32, int));
  182652. #endif
  182653. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182654. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  182655. defined(PNG_LEGACY_SUPPORTED)
  182656. typedef void (PNGAPI *png_user_transform_ptr) PNGARG((png_structp,
  182657. png_row_infop, png_bytep));
  182658. #endif
  182659. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  182660. typedef int (PNGAPI *png_user_chunk_ptr) PNGARG((png_structp, png_unknown_chunkp));
  182661. #endif
  182662. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182663. typedef void (PNGAPI *png_unknown_chunk_ptr) PNGARG((png_structp));
  182664. #endif
  182665. /* Transform masks for the high-level interface */
  182666. #define PNG_TRANSFORM_IDENTITY 0x0000 /* read and write */
  182667. #define PNG_TRANSFORM_STRIP_16 0x0001 /* read only */
  182668. #define PNG_TRANSFORM_STRIP_ALPHA 0x0002 /* read only */
  182669. #define PNG_TRANSFORM_PACKING 0x0004 /* read and write */
  182670. #define PNG_TRANSFORM_PACKSWAP 0x0008 /* read and write */
  182671. #define PNG_TRANSFORM_EXPAND 0x0010 /* read only */
  182672. #define PNG_TRANSFORM_INVERT_MONO 0x0020 /* read and write */
  182673. #define PNG_TRANSFORM_SHIFT 0x0040 /* read and write */
  182674. #define PNG_TRANSFORM_BGR 0x0080 /* read and write */
  182675. #define PNG_TRANSFORM_SWAP_ALPHA 0x0100 /* read and write */
  182676. #define PNG_TRANSFORM_SWAP_ENDIAN 0x0200 /* read and write */
  182677. #define PNG_TRANSFORM_INVERT_ALPHA 0x0400 /* read and write */
  182678. #define PNG_TRANSFORM_STRIP_FILLER 0x0800 /* WRITE only */
  182679. /* Flags for MNG supported features */
  182680. #define PNG_FLAG_MNG_EMPTY_PLTE 0x01
  182681. #define PNG_FLAG_MNG_FILTER_64 0x04
  182682. #define PNG_ALL_MNG_FEATURES 0x05
  182683. typedef png_voidp (*png_malloc_ptr) PNGARG((png_structp, png_size_t));
  182684. typedef void (*png_free_ptr) PNGARG((png_structp, png_voidp));
  182685. /* The structure that holds the information to read and write PNG files.
  182686. * The only people who need to care about what is inside of this are the
  182687. * people who will be modifying the library for their own special needs.
  182688. * It should NOT be accessed directly by an application, except to store
  182689. * the jmp_buf.
  182690. */
  182691. struct png_struct_def
  182692. {
  182693. #ifdef PNG_SETJMP_SUPPORTED
  182694. jmp_buf jmpbuf; /* used in png_error */
  182695. #endif
  182696. png_error_ptr error_fn; /* function for printing errors and aborting */
  182697. png_error_ptr warning_fn; /* function for printing warnings */
  182698. png_voidp error_ptr; /* user supplied struct for error functions */
  182699. png_rw_ptr write_data_fn; /* function for writing output data */
  182700. png_rw_ptr read_data_fn; /* function for reading input data */
  182701. png_voidp io_ptr; /* ptr to application struct for I/O functions */
  182702. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  182703. png_user_transform_ptr read_user_transform_fn; /* user read transform */
  182704. #endif
  182705. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  182706. png_user_transform_ptr write_user_transform_fn; /* user write transform */
  182707. #endif
  182708. /* These were added in libpng-1.0.2 */
  182709. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  182710. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182711. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  182712. png_voidp user_transform_ptr; /* user supplied struct for user transform */
  182713. png_byte user_transform_depth; /* bit depth of user transformed pixels */
  182714. png_byte user_transform_channels; /* channels in user transformed pixels */
  182715. #endif
  182716. #endif
  182717. png_uint_32 mode; /* tells us where we are in the PNG file */
  182718. png_uint_32 flags; /* flags indicating various things to libpng */
  182719. png_uint_32 transformations; /* which transformations to perform */
  182720. z_stream zstream; /* pointer to decompression structure (below) */
  182721. png_bytep zbuf; /* buffer for zlib */
  182722. png_size_t zbuf_size; /* size of zbuf */
  182723. int zlib_level; /* holds zlib compression level */
  182724. int zlib_method; /* holds zlib compression method */
  182725. int zlib_window_bits; /* holds zlib compression window bits */
  182726. int zlib_mem_level; /* holds zlib compression memory level */
  182727. int zlib_strategy; /* holds zlib compression strategy */
  182728. png_uint_32 width; /* width of image in pixels */
  182729. png_uint_32 height; /* height of image in pixels */
  182730. png_uint_32 num_rows; /* number of rows in current pass */
  182731. png_uint_32 usr_width; /* width of row at start of write */
  182732. png_uint_32 rowbytes; /* size of row in bytes */
  182733. png_uint_32 irowbytes; /* size of current interlaced row in bytes */
  182734. png_uint_32 iwidth; /* width of current interlaced row in pixels */
  182735. png_uint_32 row_number; /* current row in interlace pass */
  182736. png_bytep prev_row; /* buffer to save previous (unfiltered) row */
  182737. png_bytep row_buf; /* buffer to save current (unfiltered) row */
  182738. png_bytep sub_row; /* buffer to save "sub" row when filtering */
  182739. png_bytep up_row; /* buffer to save "up" row when filtering */
  182740. png_bytep avg_row; /* buffer to save "avg" row when filtering */
  182741. png_bytep paeth_row; /* buffer to save "Paeth" row when filtering */
  182742. png_row_info row_info; /* used for transformation routines */
  182743. png_uint_32 idat_size; /* current IDAT size for read */
  182744. png_uint_32 crc; /* current chunk CRC value */
  182745. png_colorp palette; /* palette from the input file */
  182746. png_uint_16 num_palette; /* number of color entries in palette */
  182747. png_uint_16 num_trans; /* number of transparency values */
  182748. png_byte chunk_name[5]; /* null-terminated name of current chunk */
  182749. png_byte compression; /* file compression type (always 0) */
  182750. png_byte filter; /* file filter type (always 0) */
  182751. png_byte interlaced; /* PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  182752. png_byte pass; /* current interlace pass (0 - 6) */
  182753. png_byte do_filter; /* row filter flags (see PNG_FILTER_ below ) */
  182754. png_byte color_type; /* color type of file */
  182755. png_byte bit_depth; /* bit depth of file */
  182756. png_byte usr_bit_depth; /* bit depth of users row */
  182757. png_byte pixel_depth; /* number of bits per pixel */
  182758. png_byte channels; /* number of channels in file */
  182759. png_byte usr_channels; /* channels at start of write */
  182760. png_byte sig_bytes; /* magic bytes read/written from start of file */
  182761. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  182762. #ifdef PNG_LEGACY_SUPPORTED
  182763. png_byte filler; /* filler byte for pixel expansion */
  182764. #else
  182765. png_uint_16 filler; /* filler bytes for pixel expansion */
  182766. #endif
  182767. #endif
  182768. #if defined(PNG_bKGD_SUPPORTED)
  182769. png_byte background_gamma_type;
  182770. # ifdef PNG_FLOATING_POINT_SUPPORTED
  182771. float background_gamma;
  182772. # endif
  182773. png_color_16 background; /* background color in screen gamma space */
  182774. #if defined(PNG_READ_GAMMA_SUPPORTED)
  182775. png_color_16 background_1; /* background normalized to gamma 1.0 */
  182776. #endif
  182777. #endif /* PNG_bKGD_SUPPORTED */
  182778. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  182779. png_flush_ptr output_flush_fn;/* Function for flushing output */
  182780. png_uint_32 flush_dist; /* how many rows apart to flush, 0 - no flush */
  182781. png_uint_32 flush_rows; /* number of rows written since last flush */
  182782. #endif
  182783. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182784. int gamma_shift; /* number of "insignificant" bits 16-bit gamma */
  182785. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182786. float gamma; /* file gamma value */
  182787. float screen_gamma; /* screen gamma value (display_exponent) */
  182788. #endif
  182789. #endif
  182790. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182791. png_bytep gamma_table; /* gamma table for 8-bit depth files */
  182792. png_bytep gamma_from_1; /* converts from 1.0 to screen */
  182793. png_bytep gamma_to_1; /* converts from file to 1.0 */
  182794. png_uint_16pp gamma_16_table; /* gamma table for 16-bit depth files */
  182795. png_uint_16pp gamma_16_from_1; /* converts from 1.0 to screen */
  182796. png_uint_16pp gamma_16_to_1; /* converts from file to 1.0 */
  182797. #endif
  182798. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_sBIT_SUPPORTED)
  182799. png_color_8 sig_bit; /* significant bits in each available channel */
  182800. #endif
  182801. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  182802. png_color_8 shift; /* shift for significant bit tranformation */
  182803. #endif
  182804. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) \
  182805. || defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182806. png_bytep trans; /* transparency values for paletted files */
  182807. png_color_16 trans_values; /* transparency values for non-paletted files */
  182808. #endif
  182809. png_read_status_ptr read_row_fn; /* called after each row is decoded */
  182810. png_write_status_ptr write_row_fn; /* called after each row is encoded */
  182811. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  182812. png_progressive_info_ptr info_fn; /* called after header data fully read */
  182813. png_progressive_row_ptr row_fn; /* called after each prog. row is decoded */
  182814. png_progressive_end_ptr end_fn; /* called after image is complete */
  182815. png_bytep save_buffer_ptr; /* current location in save_buffer */
  182816. png_bytep save_buffer; /* buffer for previously read data */
  182817. png_bytep current_buffer_ptr; /* current location in current_buffer */
  182818. png_bytep current_buffer; /* buffer for recently used data */
  182819. png_uint_32 push_length; /* size of current input chunk */
  182820. png_uint_32 skip_length; /* bytes to skip in input data */
  182821. png_size_t save_buffer_size; /* amount of data now in save_buffer */
  182822. png_size_t save_buffer_max; /* total size of save_buffer */
  182823. png_size_t buffer_size; /* total amount of available input data */
  182824. png_size_t current_buffer_size; /* amount of data now in current_buffer */
  182825. int process_mode; /* what push library is currently doing */
  182826. int cur_palette; /* current push library palette index */
  182827. # if defined(PNG_TEXT_SUPPORTED)
  182828. png_size_t current_text_size; /* current size of text input data */
  182829. png_size_t current_text_left; /* how much text left to read in input */
  182830. png_charp current_text; /* current text chunk buffer */
  182831. png_charp current_text_ptr; /* current location in current_text */
  182832. # endif /* PNG_TEXT_SUPPORTED */
  182833. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  182834. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  182835. /* for the Borland special 64K segment handler */
  182836. png_bytepp offset_table_ptr;
  182837. png_bytep offset_table;
  182838. png_uint_16 offset_table_number;
  182839. png_uint_16 offset_table_count;
  182840. png_uint_16 offset_table_count_free;
  182841. #endif
  182842. #if defined(PNG_READ_DITHER_SUPPORTED)
  182843. png_bytep palette_lookup; /* lookup table for dithering */
  182844. png_bytep dither_index; /* index translation for palette files */
  182845. #endif
  182846. #if defined(PNG_READ_DITHER_SUPPORTED) || defined(PNG_hIST_SUPPORTED)
  182847. png_uint_16p hist; /* histogram */
  182848. #endif
  182849. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  182850. png_byte heuristic_method; /* heuristic for row filter selection */
  182851. png_byte num_prev_filters; /* number of weights for previous rows */
  182852. png_bytep prev_filters; /* filter type(s) of previous row(s) */
  182853. png_uint_16p filter_weights; /* weight(s) for previous line(s) */
  182854. png_uint_16p inv_filter_weights; /* 1/weight(s) for previous line(s) */
  182855. png_uint_16p filter_costs; /* relative filter calculation cost */
  182856. png_uint_16p inv_filter_costs; /* 1/relative filter calculation cost */
  182857. #endif
  182858. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  182859. png_charp time_buffer; /* String to hold RFC 1123 time text */
  182860. #endif
  182861. /* New members added in libpng-1.0.6 */
  182862. #ifdef PNG_FREE_ME_SUPPORTED
  182863. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  182864. #endif
  182865. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  182866. png_voidp user_chunk_ptr;
  182867. png_user_chunk_ptr read_user_chunk_fn; /* user read chunk handler */
  182868. #endif
  182869. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182870. int num_chunk_list;
  182871. png_bytep chunk_list;
  182872. #endif
  182873. /* New members added in libpng-1.0.3 */
  182874. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  182875. png_byte rgb_to_gray_status;
  182876. /* These were changed from png_byte in libpng-1.0.6 */
  182877. png_uint_16 rgb_to_gray_red_coeff;
  182878. png_uint_16 rgb_to_gray_green_coeff;
  182879. png_uint_16 rgb_to_gray_blue_coeff;
  182880. #endif
  182881. /* New member added in libpng-1.0.4 (renamed in 1.0.9) */
  182882. #if defined(PNG_MNG_FEATURES_SUPPORTED) || \
  182883. defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  182884. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  182885. /* changed from png_byte to png_uint_32 at version 1.2.0 */
  182886. #ifdef PNG_1_0_X
  182887. png_byte mng_features_permitted;
  182888. #else
  182889. png_uint_32 mng_features_permitted;
  182890. #endif /* PNG_1_0_X */
  182891. #endif
  182892. /* New member added in libpng-1.0.7 */
  182893. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182894. png_fixed_point int_gamma;
  182895. #endif
  182896. /* New member added in libpng-1.0.9, ifdef'ed out in 1.0.12, enabled in 1.2.0 */
  182897. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  182898. png_byte filter_type;
  182899. #endif
  182900. #if defined(PNG_1_0_X)
  182901. /* New member added in libpng-1.0.10, ifdef'ed out in 1.2.0 */
  182902. png_uint_32 row_buf_size;
  182903. #endif
  182904. /* New members added in libpng-1.2.0 */
  182905. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  182906. # if !defined(PNG_1_0_X)
  182907. # if defined(PNG_MMX_CODE_SUPPORTED)
  182908. png_byte mmx_bitdepth_threshold;
  182909. png_uint_32 mmx_rowbytes_threshold;
  182910. # endif
  182911. png_uint_32 asm_flags;
  182912. # endif
  182913. #endif
  182914. /* New members added in libpng-1.0.2 but first enabled by default in 1.2.0 */
  182915. #ifdef PNG_USER_MEM_SUPPORTED
  182916. png_voidp mem_ptr; /* user supplied struct for mem functions */
  182917. png_malloc_ptr malloc_fn; /* function for allocating memory */
  182918. png_free_ptr free_fn; /* function for freeing memory */
  182919. #endif
  182920. /* New member added in libpng-1.0.13 and 1.2.0 */
  182921. png_bytep big_row_buf; /* buffer to save current (unfiltered) row */
  182922. #if defined(PNG_READ_DITHER_SUPPORTED)
  182923. /* The following three members were added at version 1.0.14 and 1.2.4 */
  182924. png_bytep dither_sort; /* working sort array */
  182925. png_bytep index_to_palette; /* where the original index currently is */
  182926. /* in the palette */
  182927. png_bytep palette_to_index; /* which original index points to this */
  182928. /* palette color */
  182929. #endif
  182930. /* New members added in libpng-1.0.16 and 1.2.6 */
  182931. png_byte compression_type;
  182932. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  182933. png_uint_32 user_width_max;
  182934. png_uint_32 user_height_max;
  182935. #endif
  182936. /* New member added in libpng-1.0.25 and 1.2.17 */
  182937. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182938. /* storage for unknown chunk that the library doesn't recognize. */
  182939. png_unknown_chunk unknown_chunk;
  182940. #endif
  182941. };
  182942. /* This triggers a compiler error in png.c, if png.c and png.h
  182943. * do not agree upon the version number.
  182944. */
  182945. typedef png_structp version_1_2_21;
  182946. typedef png_struct FAR * FAR * png_structpp;
  182947. /* Here are the function definitions most commonly used. This is not
  182948. * the place to find out how to use libpng. See libpng.txt for the
  182949. * full explanation, see example.c for the summary. This just provides
  182950. * a simple one line description of the use of each function.
  182951. */
  182952. /* Returns the version number of the library */
  182953. extern PNG_EXPORT(png_uint_32,png_access_version_number) PNGARG((void));
  182954. /* Tell lib we have already handled the first <num_bytes> magic bytes.
  182955. * Handling more than 8 bytes from the beginning of the file is an error.
  182956. */
  182957. extern PNG_EXPORT(void,png_set_sig_bytes) PNGARG((png_structp png_ptr,
  182958. int num_bytes));
  182959. /* Check sig[start] through sig[start + num_to_check - 1] to see if it's a
  182960. * PNG file. Returns zero if the supplied bytes match the 8-byte PNG
  182961. * signature, and non-zero otherwise. Having num_to_check == 0 or
  182962. * start > 7 will always fail (ie return non-zero).
  182963. */
  182964. extern PNG_EXPORT(int,png_sig_cmp) PNGARG((png_bytep sig, png_size_t start,
  182965. png_size_t num_to_check));
  182966. /* Simple signature checking function. This is the same as calling
  182967. * png_check_sig(sig, n) := !png_sig_cmp(sig, 0, n).
  182968. */
  182969. extern PNG_EXPORT(int,png_check_sig) PNGARG((png_bytep sig, int num));
  182970. /* Allocate and initialize png_ptr struct for reading, and any other memory. */
  182971. extern PNG_EXPORT(png_structp,png_create_read_struct)
  182972. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182973. png_error_ptr error_fn, png_error_ptr warn_fn));
  182974. /* Allocate and initialize png_ptr struct for writing, and any other memory */
  182975. extern PNG_EXPORT(png_structp,png_create_write_struct)
  182976. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182977. png_error_ptr error_fn, png_error_ptr warn_fn));
  182978. #ifdef PNG_WRITE_SUPPORTED
  182979. extern PNG_EXPORT(png_uint_32,png_get_compression_buffer_size)
  182980. PNGARG((png_structp png_ptr));
  182981. #endif
  182982. #ifdef PNG_WRITE_SUPPORTED
  182983. extern PNG_EXPORT(void,png_set_compression_buffer_size)
  182984. PNGARG((png_structp png_ptr, png_uint_32 size));
  182985. #endif
  182986. /* Reset the compression stream */
  182987. extern PNG_EXPORT(int,png_reset_zstream) PNGARG((png_structp png_ptr));
  182988. /* New functions added in libpng-1.0.2 (not enabled by default until 1.2.0) */
  182989. #ifdef PNG_USER_MEM_SUPPORTED
  182990. extern PNG_EXPORT(png_structp,png_create_read_struct_2)
  182991. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182992. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  182993. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  182994. extern PNG_EXPORT(png_structp,png_create_write_struct_2)
  182995. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182996. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  182997. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  182998. #endif
  182999. /* Write a PNG chunk - size, type, (optional) data, CRC. */
  183000. extern PNG_EXPORT(void,png_write_chunk) PNGARG((png_structp png_ptr,
  183001. png_bytep chunk_name, png_bytep data, png_size_t length));
  183002. /* Write the start of a PNG chunk - length and chunk name. */
  183003. extern PNG_EXPORT(void,png_write_chunk_start) PNGARG((png_structp png_ptr,
  183004. png_bytep chunk_name, png_uint_32 length));
  183005. /* Write the data of a PNG chunk started with png_write_chunk_start(). */
  183006. extern PNG_EXPORT(void,png_write_chunk_data) PNGARG((png_structp png_ptr,
  183007. png_bytep data, png_size_t length));
  183008. /* Finish a chunk started with png_write_chunk_start() (includes CRC). */
  183009. extern PNG_EXPORT(void,png_write_chunk_end) PNGARG((png_structp png_ptr));
  183010. /* Allocate and initialize the info structure */
  183011. extern PNG_EXPORT(png_infop,png_create_info_struct)
  183012. PNGARG((png_structp png_ptr));
  183013. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183014. /* Initialize the info structure (old interface - DEPRECATED) */
  183015. extern PNG_EXPORT(void,png_info_init) PNGARG((png_infop info_ptr));
  183016. #undef png_info_init
  183017. #define png_info_init(info_ptr) png_info_init_3(&info_ptr,\
  183018. png_sizeof(png_info));
  183019. #endif
  183020. extern PNG_EXPORT(void,png_info_init_3) PNGARG((png_infopp info_ptr,
  183021. png_size_t png_info_struct_size));
  183022. /* Writes all the PNG information before the image. */
  183023. extern PNG_EXPORT(void,png_write_info_before_PLTE) PNGARG((png_structp png_ptr,
  183024. png_infop info_ptr));
  183025. extern PNG_EXPORT(void,png_write_info) PNGARG((png_structp png_ptr,
  183026. png_infop info_ptr));
  183027. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183028. /* read the information before the actual image data. */
  183029. extern PNG_EXPORT(void,png_read_info) PNGARG((png_structp png_ptr,
  183030. png_infop info_ptr));
  183031. #endif
  183032. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  183033. extern PNG_EXPORT(png_charp,png_convert_to_rfc1123)
  183034. PNGARG((png_structp png_ptr, png_timep ptime));
  183035. #endif
  183036. #if !defined(_WIN32_WCE)
  183037. /* "time.h" functions are not supported on WindowsCE */
  183038. #if defined(PNG_WRITE_tIME_SUPPORTED)
  183039. /* convert from a struct tm to png_time */
  183040. extern PNG_EXPORT(void,png_convert_from_struct_tm) PNGARG((png_timep ptime,
  183041. struct tm FAR * ttime));
  183042. /* convert from time_t to png_time. Uses gmtime() */
  183043. extern PNG_EXPORT(void,png_convert_from_time_t) PNGARG((png_timep ptime,
  183044. time_t ttime));
  183045. #endif /* PNG_WRITE_tIME_SUPPORTED */
  183046. #endif /* _WIN32_WCE */
  183047. #if defined(PNG_READ_EXPAND_SUPPORTED)
  183048. /* Expand data to 24-bit RGB, or 8-bit grayscale, with alpha if available. */
  183049. extern PNG_EXPORT(void,png_set_expand) PNGARG((png_structp png_ptr));
  183050. #if !defined(PNG_1_0_X)
  183051. extern PNG_EXPORT(void,png_set_expand_gray_1_2_4_to_8) PNGARG((png_structp
  183052. png_ptr));
  183053. #endif
  183054. extern PNG_EXPORT(void,png_set_palette_to_rgb) PNGARG((png_structp png_ptr));
  183055. extern PNG_EXPORT(void,png_set_tRNS_to_alpha) PNGARG((png_structp png_ptr));
  183056. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183057. /* Deprecated */
  183058. extern PNG_EXPORT(void,png_set_gray_1_2_4_to_8) PNGARG((png_structp png_ptr));
  183059. #endif
  183060. #endif
  183061. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  183062. /* Use blue, green, red order for pixels. */
  183063. extern PNG_EXPORT(void,png_set_bgr) PNGARG((png_structp png_ptr));
  183064. #endif
  183065. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  183066. /* Expand the grayscale to 24-bit RGB if necessary. */
  183067. extern PNG_EXPORT(void,png_set_gray_to_rgb) PNGARG((png_structp png_ptr));
  183068. #endif
  183069. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  183070. /* Reduce RGB to grayscale. */
  183071. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183072. extern PNG_EXPORT(void,png_set_rgb_to_gray) PNGARG((png_structp png_ptr,
  183073. int error_action, double red, double green ));
  183074. #endif
  183075. extern PNG_EXPORT(void,png_set_rgb_to_gray_fixed) PNGARG((png_structp png_ptr,
  183076. int error_action, png_fixed_point red, png_fixed_point green ));
  183077. extern PNG_EXPORT(png_byte,png_get_rgb_to_gray_status) PNGARG((png_structp
  183078. png_ptr));
  183079. #endif
  183080. extern PNG_EXPORT(void,png_build_grayscale_palette) PNGARG((int bit_depth,
  183081. png_colorp palette));
  183082. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  183083. extern PNG_EXPORT(void,png_set_strip_alpha) PNGARG((png_structp png_ptr));
  183084. #endif
  183085. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  183086. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  183087. extern PNG_EXPORT(void,png_set_swap_alpha) PNGARG((png_structp png_ptr));
  183088. #endif
  183089. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  183090. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  183091. extern PNG_EXPORT(void,png_set_invert_alpha) PNGARG((png_structp png_ptr));
  183092. #endif
  183093. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  183094. /* Add a filler byte to 8-bit Gray or 24-bit RGB images. */
  183095. extern PNG_EXPORT(void,png_set_filler) PNGARG((png_structp png_ptr,
  183096. png_uint_32 filler, int flags));
  183097. /* The values of the PNG_FILLER_ defines should NOT be changed */
  183098. #define PNG_FILLER_BEFORE 0
  183099. #define PNG_FILLER_AFTER 1
  183100. /* Add an alpha byte to 8-bit Gray or 24-bit RGB images. */
  183101. #if !defined(PNG_1_0_X)
  183102. extern PNG_EXPORT(void,png_set_add_alpha) PNGARG((png_structp png_ptr,
  183103. png_uint_32 filler, int flags));
  183104. #endif
  183105. #endif /* PNG_READ_FILLER_SUPPORTED || PNG_WRITE_FILLER_SUPPORTED */
  183106. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  183107. /* Swap bytes in 16-bit depth files. */
  183108. extern PNG_EXPORT(void,png_set_swap) PNGARG((png_structp png_ptr));
  183109. #endif
  183110. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  183111. /* Use 1 byte per pixel in 1, 2, or 4-bit depth files. */
  183112. extern PNG_EXPORT(void,png_set_packing) PNGARG((png_structp png_ptr));
  183113. #endif
  183114. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  183115. /* Swap packing order of pixels in bytes. */
  183116. extern PNG_EXPORT(void,png_set_packswap) PNGARG((png_structp png_ptr));
  183117. #endif
  183118. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  183119. /* Converts files to legal bit depths. */
  183120. extern PNG_EXPORT(void,png_set_shift) PNGARG((png_structp png_ptr,
  183121. png_color_8p true_bits));
  183122. #endif
  183123. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  183124. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  183125. /* Have the code handle the interlacing. Returns the number of passes. */
  183126. extern PNG_EXPORT(int,png_set_interlace_handling) PNGARG((png_structp png_ptr));
  183127. #endif
  183128. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  183129. /* Invert monochrome files */
  183130. extern PNG_EXPORT(void,png_set_invert_mono) PNGARG((png_structp png_ptr));
  183131. #endif
  183132. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  183133. /* Handle alpha and tRNS by replacing with a background color. */
  183134. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183135. extern PNG_EXPORT(void,png_set_background) PNGARG((png_structp png_ptr,
  183136. png_color_16p background_color, int background_gamma_code,
  183137. int need_expand, double background_gamma));
  183138. #endif
  183139. #define PNG_BACKGROUND_GAMMA_UNKNOWN 0
  183140. #define PNG_BACKGROUND_GAMMA_SCREEN 1
  183141. #define PNG_BACKGROUND_GAMMA_FILE 2
  183142. #define PNG_BACKGROUND_GAMMA_UNIQUE 3
  183143. #endif
  183144. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  183145. /* strip the second byte of information from a 16-bit depth file. */
  183146. extern PNG_EXPORT(void,png_set_strip_16) PNGARG((png_structp png_ptr));
  183147. #endif
  183148. #if defined(PNG_READ_DITHER_SUPPORTED)
  183149. /* Turn on dithering, and reduce the palette to the number of colors available. */
  183150. extern PNG_EXPORT(void,png_set_dither) PNGARG((png_structp png_ptr,
  183151. png_colorp palette, int num_palette, int maximum_colors,
  183152. png_uint_16p histogram, int full_dither));
  183153. #endif
  183154. #if defined(PNG_READ_GAMMA_SUPPORTED)
  183155. /* Handle gamma correction. Screen_gamma=(display_exponent) */
  183156. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183157. extern PNG_EXPORT(void,png_set_gamma) PNGARG((png_structp png_ptr,
  183158. double screen_gamma, double default_file_gamma));
  183159. #endif
  183160. #endif
  183161. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183162. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  183163. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  183164. /* Permit or disallow empty PLTE (0: not permitted, 1: permitted) */
  183165. /* Deprecated and will be removed. Use png_permit_mng_features() instead. */
  183166. extern PNG_EXPORT(void,png_permit_empty_plte) PNGARG((png_structp png_ptr,
  183167. int empty_plte_permitted));
  183168. #endif
  183169. #endif
  183170. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  183171. /* Set how many lines between output flushes - 0 for no flushing */
  183172. extern PNG_EXPORT(void,png_set_flush) PNGARG((png_structp png_ptr, int nrows));
  183173. /* Flush the current PNG output buffer */
  183174. extern PNG_EXPORT(void,png_write_flush) PNGARG((png_structp png_ptr));
  183175. #endif
  183176. /* optional update palette with requested transformations */
  183177. extern PNG_EXPORT(void,png_start_read_image) PNGARG((png_structp png_ptr));
  183178. /* optional call to update the users info structure */
  183179. extern PNG_EXPORT(void,png_read_update_info) PNGARG((png_structp png_ptr,
  183180. png_infop info_ptr));
  183181. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183182. /* read one or more rows of image data. */
  183183. extern PNG_EXPORT(void,png_read_rows) PNGARG((png_structp png_ptr,
  183184. png_bytepp row, png_bytepp display_row, png_uint_32 num_rows));
  183185. #endif
  183186. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183187. /* read a row of data. */
  183188. extern PNG_EXPORT(void,png_read_row) PNGARG((png_structp png_ptr,
  183189. png_bytep row,
  183190. png_bytep display_row));
  183191. #endif
  183192. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183193. /* read the whole image into memory at once. */
  183194. extern PNG_EXPORT(void,png_read_image) PNGARG((png_structp png_ptr,
  183195. png_bytepp image));
  183196. #endif
  183197. /* write a row of image data */
  183198. extern PNG_EXPORT(void,png_write_row) PNGARG((png_structp png_ptr,
  183199. png_bytep row));
  183200. /* write a few rows of image data */
  183201. extern PNG_EXPORT(void,png_write_rows) PNGARG((png_structp png_ptr,
  183202. png_bytepp row, png_uint_32 num_rows));
  183203. /* write the image data */
  183204. extern PNG_EXPORT(void,png_write_image) PNGARG((png_structp png_ptr,
  183205. png_bytepp image));
  183206. /* writes the end of the PNG file. */
  183207. extern PNG_EXPORT(void,png_write_end) PNGARG((png_structp png_ptr,
  183208. png_infop info_ptr));
  183209. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183210. /* read the end of the PNG file. */
  183211. extern PNG_EXPORT(void,png_read_end) PNGARG((png_structp png_ptr,
  183212. png_infop info_ptr));
  183213. #endif
  183214. /* free any memory associated with the png_info_struct */
  183215. extern PNG_EXPORT(void,png_destroy_info_struct) PNGARG((png_structp png_ptr,
  183216. png_infopp info_ptr_ptr));
  183217. /* free any memory associated with the png_struct and the png_info_structs */
  183218. extern PNG_EXPORT(void,png_destroy_read_struct) PNGARG((png_structpp
  183219. png_ptr_ptr, png_infopp info_ptr_ptr, png_infopp end_info_ptr_ptr));
  183220. /* free all memory used by the read (old method - NOT DLL EXPORTED) */
  183221. extern void png_read_destroy PNGARG((png_structp png_ptr, png_infop info_ptr,
  183222. png_infop end_info_ptr));
  183223. /* free any memory associated with the png_struct and the png_info_structs */
  183224. extern PNG_EXPORT(void,png_destroy_write_struct)
  183225. PNGARG((png_structpp png_ptr_ptr, png_infopp info_ptr_ptr));
  183226. /* free any memory used in png_ptr struct (old method - NOT DLL EXPORTED) */
  183227. extern void png_write_destroy PNGARG((png_structp png_ptr));
  183228. /* set the libpng method of handling chunk CRC errors */
  183229. extern PNG_EXPORT(void,png_set_crc_action) PNGARG((png_structp png_ptr,
  183230. int crit_action, int ancil_action));
  183231. /* Values for png_set_crc_action() to say how to handle CRC errors in
  183232. * ancillary and critical chunks, and whether to use the data contained
  183233. * therein. Note that it is impossible to "discard" data in a critical
  183234. * chunk. For versions prior to 0.90, the action was always error/quit,
  183235. * whereas in version 0.90 and later, the action for CRC errors in ancillary
  183236. * chunks is warn/discard. These values should NOT be changed.
  183237. *
  183238. * value action:critical action:ancillary
  183239. */
  183240. #define PNG_CRC_DEFAULT 0 /* error/quit warn/discard data */
  183241. #define PNG_CRC_ERROR_QUIT 1 /* error/quit error/quit */
  183242. #define PNG_CRC_WARN_DISCARD 2 /* (INVALID) warn/discard data */
  183243. #define PNG_CRC_WARN_USE 3 /* warn/use data warn/use data */
  183244. #define PNG_CRC_QUIET_USE 4 /* quiet/use data quiet/use data */
  183245. #define PNG_CRC_NO_CHANGE 5 /* use current value use current value */
  183246. /* These functions give the user control over the scan-line filtering in
  183247. * libpng and the compression methods used by zlib. These functions are
  183248. * mainly useful for testing, as the defaults should work with most users.
  183249. * Those users who are tight on memory or want faster performance at the
  183250. * expense of compression can modify them. See the compression library
  183251. * header file (zlib.h) for an explination of the compression functions.
  183252. */
  183253. /* set the filtering method(s) used by libpng. Currently, the only valid
  183254. * value for "method" is 0.
  183255. */
  183256. extern PNG_EXPORT(void,png_set_filter) PNGARG((png_structp png_ptr, int method,
  183257. int filters));
  183258. /* Flags for png_set_filter() to say which filters to use. The flags
  183259. * are chosen so that they don't conflict with real filter types
  183260. * below, in case they are supplied instead of the #defined constants.
  183261. * These values should NOT be changed.
  183262. */
  183263. #define PNG_NO_FILTERS 0x00
  183264. #define PNG_FILTER_NONE 0x08
  183265. #define PNG_FILTER_SUB 0x10
  183266. #define PNG_FILTER_UP 0x20
  183267. #define PNG_FILTER_AVG 0x40
  183268. #define PNG_FILTER_PAETH 0x80
  183269. #define PNG_ALL_FILTERS (PNG_FILTER_NONE | PNG_FILTER_SUB | PNG_FILTER_UP | \
  183270. PNG_FILTER_AVG | PNG_FILTER_PAETH)
  183271. /* Filter values (not flags) - used in pngwrite.c, pngwutil.c for now.
  183272. * These defines should NOT be changed.
  183273. */
  183274. #define PNG_FILTER_VALUE_NONE 0
  183275. #define PNG_FILTER_VALUE_SUB 1
  183276. #define PNG_FILTER_VALUE_UP 2
  183277. #define PNG_FILTER_VALUE_AVG 3
  183278. #define PNG_FILTER_VALUE_PAETH 4
  183279. #define PNG_FILTER_VALUE_LAST 5
  183280. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* EXPERIMENTAL */
  183281. /* The "heuristic_method" is given by one of the PNG_FILTER_HEURISTIC_
  183282. * defines, either the default (minimum-sum-of-absolute-differences), or
  183283. * the experimental method (weighted-minimum-sum-of-absolute-differences).
  183284. *
  183285. * Weights are factors >= 1.0, indicating how important it is to keep the
  183286. * filter type consistent between rows. Larger numbers mean the current
  183287. * filter is that many times as likely to be the same as the "num_weights"
  183288. * previous filters. This is cumulative for each previous row with a weight.
  183289. * There needs to be "num_weights" values in "filter_weights", or it can be
  183290. * NULL if the weights aren't being specified. Weights have no influence on
  183291. * the selection of the first row filter. Well chosen weights can (in theory)
  183292. * improve the compression for a given image.
  183293. *
  183294. * Costs are factors >= 1.0 indicating the relative decoding costs of a
  183295. * filter type. Higher costs indicate more decoding expense, and are
  183296. * therefore less likely to be selected over a filter with lower computational
  183297. * costs. There needs to be a value in "filter_costs" for each valid filter
  183298. * type (given by PNG_FILTER_VALUE_LAST), or it can be NULL if you aren't
  183299. * setting the costs. Costs try to improve the speed of decompression without
  183300. * unduly increasing the compressed image size.
  183301. *
  183302. * A negative weight or cost indicates the default value is to be used, and
  183303. * values in the range [0.0, 1.0) indicate the value is to remain unchanged.
  183304. * The default values for both weights and costs are currently 1.0, but may
  183305. * change if good general weighting/cost heuristics can be found. If both
  183306. * the weights and costs are set to 1.0, this degenerates the WEIGHTED method
  183307. * to the UNWEIGHTED method, but with added encoding time/computation.
  183308. */
  183309. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183310. extern PNG_EXPORT(void,png_set_filter_heuristics) PNGARG((png_structp png_ptr,
  183311. int heuristic_method, int num_weights, png_doublep filter_weights,
  183312. png_doublep filter_costs));
  183313. #endif
  183314. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  183315. /* Heuristic used for row filter selection. These defines should NOT be
  183316. * changed.
  183317. */
  183318. #define PNG_FILTER_HEURISTIC_DEFAULT 0 /* Currently "UNWEIGHTED" */
  183319. #define PNG_FILTER_HEURISTIC_UNWEIGHTED 1 /* Used by libpng < 0.95 */
  183320. #define PNG_FILTER_HEURISTIC_WEIGHTED 2 /* Experimental feature */
  183321. #define PNG_FILTER_HEURISTIC_LAST 3 /* Not a valid value */
  183322. /* Set the library compression level. Currently, valid values range from
  183323. * 0 - 9, corresponding directly to the zlib compression levels 0 - 9
  183324. * (0 - no compression, 9 - "maximal" compression). Note that tests have
  183325. * shown that zlib compression levels 3-6 usually perform as well as level 9
  183326. * for PNG images, and do considerably fewer caclulations. In the future,
  183327. * these values may not correspond directly to the zlib compression levels.
  183328. */
  183329. extern PNG_EXPORT(void,png_set_compression_level) PNGARG((png_structp png_ptr,
  183330. int level));
  183331. extern PNG_EXPORT(void,png_set_compression_mem_level)
  183332. PNGARG((png_structp png_ptr, int mem_level));
  183333. extern PNG_EXPORT(void,png_set_compression_strategy)
  183334. PNGARG((png_structp png_ptr, int strategy));
  183335. extern PNG_EXPORT(void,png_set_compression_window_bits)
  183336. PNGARG((png_structp png_ptr, int window_bits));
  183337. extern PNG_EXPORT(void,png_set_compression_method) PNGARG((png_structp png_ptr,
  183338. int method));
  183339. /* These next functions are called for input/output, memory, and error
  183340. * handling. They are in the file pngrio.c, pngwio.c, and pngerror.c,
  183341. * and call standard C I/O routines such as fread(), fwrite(), and
  183342. * fprintf(). These functions can be made to use other I/O routines
  183343. * at run time for those applications that need to handle I/O in a
  183344. * different manner by calling png_set_???_fn(). See libpng.txt for
  183345. * more information.
  183346. */
  183347. #if !defined(PNG_NO_STDIO)
  183348. /* Initialize the input/output for the PNG file to the default functions. */
  183349. extern PNG_EXPORT(void,png_init_io) PNGARG((png_structp png_ptr, png_FILE_p fp));
  183350. #endif
  183351. /* Replace the (error and abort), and warning functions with user
  183352. * supplied functions. If no messages are to be printed you must still
  183353. * write and use replacement functions. The replacement error_fn should
  183354. * still do a longjmp to the last setjmp location if you are using this
  183355. * method of error handling. If error_fn or warning_fn is NULL, the
  183356. * default function will be used.
  183357. */
  183358. extern PNG_EXPORT(void,png_set_error_fn) PNGARG((png_structp png_ptr,
  183359. png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warning_fn));
  183360. /* Return the user pointer associated with the error functions */
  183361. extern PNG_EXPORT(png_voidp,png_get_error_ptr) PNGARG((png_structp png_ptr));
  183362. /* Replace the default data output functions with a user supplied one(s).
  183363. * If buffered output is not used, then output_flush_fn can be set to NULL.
  183364. * If PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile time
  183365. * output_flush_fn will be ignored (and thus can be NULL).
  183366. */
  183367. extern PNG_EXPORT(void,png_set_write_fn) PNGARG((png_structp png_ptr,
  183368. png_voidp io_ptr, png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn));
  183369. /* Replace the default data input function with a user supplied one. */
  183370. extern PNG_EXPORT(void,png_set_read_fn) PNGARG((png_structp png_ptr,
  183371. png_voidp io_ptr, png_rw_ptr read_data_fn));
  183372. /* Return the user pointer associated with the I/O functions */
  183373. extern PNG_EXPORT(png_voidp,png_get_io_ptr) PNGARG((png_structp png_ptr));
  183374. extern PNG_EXPORT(void,png_set_read_status_fn) PNGARG((png_structp png_ptr,
  183375. png_read_status_ptr read_row_fn));
  183376. extern PNG_EXPORT(void,png_set_write_status_fn) PNGARG((png_structp png_ptr,
  183377. png_write_status_ptr write_row_fn));
  183378. #ifdef PNG_USER_MEM_SUPPORTED
  183379. /* Replace the default memory allocation functions with user supplied one(s). */
  183380. extern PNG_EXPORT(void,png_set_mem_fn) PNGARG((png_structp png_ptr,
  183381. png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  183382. /* Return the user pointer associated with the memory functions */
  183383. extern PNG_EXPORT(png_voidp,png_get_mem_ptr) PNGARG((png_structp png_ptr));
  183384. #endif
  183385. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  183386. defined(PNG_LEGACY_SUPPORTED)
  183387. extern PNG_EXPORT(void,png_set_read_user_transform_fn) PNGARG((png_structp
  183388. png_ptr, png_user_transform_ptr read_user_transform_fn));
  183389. #endif
  183390. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  183391. defined(PNG_LEGACY_SUPPORTED)
  183392. extern PNG_EXPORT(void,png_set_write_user_transform_fn) PNGARG((png_structp
  183393. png_ptr, png_user_transform_ptr write_user_transform_fn));
  183394. #endif
  183395. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  183396. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  183397. defined(PNG_LEGACY_SUPPORTED)
  183398. extern PNG_EXPORT(void,png_set_user_transform_info) PNGARG((png_structp
  183399. png_ptr, png_voidp user_transform_ptr, int user_transform_depth,
  183400. int user_transform_channels));
  183401. /* Return the user pointer associated with the user transform functions */
  183402. extern PNG_EXPORT(png_voidp,png_get_user_transform_ptr)
  183403. PNGARG((png_structp png_ptr));
  183404. #endif
  183405. #ifdef PNG_USER_CHUNKS_SUPPORTED
  183406. extern PNG_EXPORT(void,png_set_read_user_chunk_fn) PNGARG((png_structp png_ptr,
  183407. png_voidp user_chunk_ptr, png_user_chunk_ptr read_user_chunk_fn));
  183408. extern PNG_EXPORT(png_voidp,png_get_user_chunk_ptr) PNGARG((png_structp
  183409. png_ptr));
  183410. #endif
  183411. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  183412. /* Sets the function callbacks for the push reader, and a pointer to a
  183413. * user-defined structure available to the callback functions.
  183414. */
  183415. extern PNG_EXPORT(void,png_set_progressive_read_fn) PNGARG((png_structp png_ptr,
  183416. png_voidp progressive_ptr,
  183417. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  183418. png_progressive_end_ptr end_fn));
  183419. /* returns the user pointer associated with the push read functions */
  183420. extern PNG_EXPORT(png_voidp,png_get_progressive_ptr)
  183421. PNGARG((png_structp png_ptr));
  183422. /* function to be called when data becomes available */
  183423. extern PNG_EXPORT(void,png_process_data) PNGARG((png_structp png_ptr,
  183424. png_infop info_ptr, png_bytep buffer, png_size_t buffer_size));
  183425. /* function that combines rows. Not very much different than the
  183426. * png_combine_row() call. Is this even used?????
  183427. */
  183428. extern PNG_EXPORT(void,png_progressive_combine_row) PNGARG((png_structp png_ptr,
  183429. png_bytep old_row, png_bytep new_row));
  183430. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  183431. extern PNG_EXPORT(png_voidp,png_malloc) PNGARG((png_structp png_ptr,
  183432. png_uint_32 size));
  183433. #if defined(PNG_1_0_X)
  183434. # define png_malloc_warn png_malloc
  183435. #else
  183436. /* Added at libpng version 1.2.4 */
  183437. extern PNG_EXPORT(png_voidp,png_malloc_warn) PNGARG((png_structp png_ptr,
  183438. png_uint_32 size));
  183439. #endif
  183440. /* frees a pointer allocated by png_malloc() */
  183441. extern PNG_EXPORT(void,png_free) PNGARG((png_structp png_ptr, png_voidp ptr));
  183442. #if defined(PNG_1_0_X)
  183443. /* Function to allocate memory for zlib. */
  183444. extern PNG_EXPORT(voidpf,png_zalloc) PNGARG((voidpf png_ptr, uInt items,
  183445. uInt size));
  183446. /* Function to free memory for zlib */
  183447. extern PNG_EXPORT(void,png_zfree) PNGARG((voidpf png_ptr, voidpf ptr));
  183448. #endif
  183449. /* Free data that was allocated internally */
  183450. extern PNG_EXPORT(void,png_free_data) PNGARG((png_structp png_ptr,
  183451. png_infop info_ptr, png_uint_32 free_me, int num));
  183452. #ifdef PNG_FREE_ME_SUPPORTED
  183453. /* Reassign responsibility for freeing existing data, whether allocated
  183454. * by libpng or by the application */
  183455. extern PNG_EXPORT(void,png_data_freer) PNGARG((png_structp png_ptr,
  183456. png_infop info_ptr, int freer, png_uint_32 mask));
  183457. #endif
  183458. /* assignments for png_data_freer */
  183459. #define PNG_DESTROY_WILL_FREE_DATA 1
  183460. #define PNG_SET_WILL_FREE_DATA 1
  183461. #define PNG_USER_WILL_FREE_DATA 2
  183462. /* Flags for png_ptr->free_me and info_ptr->free_me */
  183463. #define PNG_FREE_HIST 0x0008
  183464. #define PNG_FREE_ICCP 0x0010
  183465. #define PNG_FREE_SPLT 0x0020
  183466. #define PNG_FREE_ROWS 0x0040
  183467. #define PNG_FREE_PCAL 0x0080
  183468. #define PNG_FREE_SCAL 0x0100
  183469. #define PNG_FREE_UNKN 0x0200
  183470. #define PNG_FREE_LIST 0x0400
  183471. #define PNG_FREE_PLTE 0x1000
  183472. #define PNG_FREE_TRNS 0x2000
  183473. #define PNG_FREE_TEXT 0x4000
  183474. #define PNG_FREE_ALL 0x7fff
  183475. #define PNG_FREE_MUL 0x4220 /* PNG_FREE_SPLT|PNG_FREE_TEXT|PNG_FREE_UNKN */
  183476. #ifdef PNG_USER_MEM_SUPPORTED
  183477. extern PNG_EXPORT(png_voidp,png_malloc_default) PNGARG((png_structp png_ptr,
  183478. png_uint_32 size));
  183479. extern PNG_EXPORT(void,png_free_default) PNGARG((png_structp png_ptr,
  183480. png_voidp ptr));
  183481. #endif
  183482. extern PNG_EXPORT(png_voidp,png_memcpy_check) PNGARG((png_structp png_ptr,
  183483. png_voidp s1, png_voidp s2, png_uint_32 size));
  183484. extern PNG_EXPORT(png_voidp,png_memset_check) PNGARG((png_structp png_ptr,
  183485. png_voidp s1, int value, png_uint_32 size));
  183486. #if defined(USE_FAR_KEYWORD) /* memory model conversion function */
  183487. extern void *png_far_to_near PNGARG((png_structp png_ptr,png_voidp ptr,
  183488. int check));
  183489. #endif /* USE_FAR_KEYWORD */
  183490. #ifndef PNG_NO_ERROR_TEXT
  183491. /* Fatal error in PNG image of libpng - can't continue */
  183492. extern PNG_EXPORT(void,png_error) PNGARG((png_structp png_ptr,
  183493. png_const_charp error_message));
  183494. /* The same, but the chunk name is prepended to the error string. */
  183495. extern PNG_EXPORT(void,png_chunk_error) PNGARG((png_structp png_ptr,
  183496. png_const_charp error_message));
  183497. #else
  183498. /* Fatal error in PNG image of libpng - can't continue */
  183499. extern PNG_EXPORT(void,png_err) PNGARG((png_structp png_ptr));
  183500. #endif
  183501. #ifndef PNG_NO_WARNINGS
  183502. /* Non-fatal error in libpng. Can continue, but may have a problem. */
  183503. extern PNG_EXPORT(void,png_warning) PNGARG((png_structp png_ptr,
  183504. png_const_charp warning_message));
  183505. #ifdef PNG_READ_SUPPORTED
  183506. /* Non-fatal error in libpng, chunk name is prepended to message. */
  183507. extern PNG_EXPORT(void,png_chunk_warning) PNGARG((png_structp png_ptr,
  183508. png_const_charp warning_message));
  183509. #endif /* PNG_READ_SUPPORTED */
  183510. #endif /* PNG_NO_WARNINGS */
  183511. /* The png_set_<chunk> functions are for storing values in the png_info_struct.
  183512. * Similarly, the png_get_<chunk> calls are used to read values from the
  183513. * png_info_struct, either storing the parameters in the passed variables, or
  183514. * setting pointers into the png_info_struct where the data is stored. The
  183515. * png_get_<chunk> functions return a non-zero value if the data was available
  183516. * in info_ptr, or return zero and do not change any of the parameters if the
  183517. * data was not available.
  183518. *
  183519. * These functions should be used instead of directly accessing png_info
  183520. * to avoid problems with future changes in the size and internal layout of
  183521. * png_info_struct.
  183522. */
  183523. /* Returns "flag" if chunk data is valid in info_ptr. */
  183524. extern PNG_EXPORT(png_uint_32,png_get_valid) PNGARG((png_structp png_ptr,
  183525. png_infop info_ptr, png_uint_32 flag));
  183526. /* Returns number of bytes needed to hold a transformed row. */
  183527. extern PNG_EXPORT(png_uint_32,png_get_rowbytes) PNGARG((png_structp png_ptr,
  183528. png_infop info_ptr));
  183529. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  183530. /* Returns row_pointers, which is an array of pointers to scanlines that was
  183531. returned from png_read_png(). */
  183532. extern PNG_EXPORT(png_bytepp,png_get_rows) PNGARG((png_structp png_ptr,
  183533. png_infop info_ptr));
  183534. /* Set row_pointers, which is an array of pointers to scanlines for use
  183535. by png_write_png(). */
  183536. extern PNG_EXPORT(void,png_set_rows) PNGARG((png_structp png_ptr,
  183537. png_infop info_ptr, png_bytepp row_pointers));
  183538. #endif
  183539. /* Returns number of color channels in image. */
  183540. extern PNG_EXPORT(png_byte,png_get_channels) PNGARG((png_structp png_ptr,
  183541. png_infop info_ptr));
  183542. #ifdef PNG_EASY_ACCESS_SUPPORTED
  183543. /* Returns image width in pixels. */
  183544. extern PNG_EXPORT(png_uint_32, png_get_image_width) PNGARG((png_structp
  183545. png_ptr, png_infop info_ptr));
  183546. /* Returns image height in pixels. */
  183547. extern PNG_EXPORT(png_uint_32, png_get_image_height) PNGARG((png_structp
  183548. png_ptr, png_infop info_ptr));
  183549. /* Returns image bit_depth. */
  183550. extern PNG_EXPORT(png_byte, png_get_bit_depth) PNGARG((png_structp
  183551. png_ptr, png_infop info_ptr));
  183552. /* Returns image color_type. */
  183553. extern PNG_EXPORT(png_byte, png_get_color_type) PNGARG((png_structp
  183554. png_ptr, png_infop info_ptr));
  183555. /* Returns image filter_type. */
  183556. extern PNG_EXPORT(png_byte, png_get_filter_type) PNGARG((png_structp
  183557. png_ptr, png_infop info_ptr));
  183558. /* Returns image interlace_type. */
  183559. extern PNG_EXPORT(png_byte, png_get_interlace_type) PNGARG((png_structp
  183560. png_ptr, png_infop info_ptr));
  183561. /* Returns image compression_type. */
  183562. extern PNG_EXPORT(png_byte, png_get_compression_type) PNGARG((png_structp
  183563. png_ptr, png_infop info_ptr));
  183564. /* Returns image resolution in pixels per meter, from pHYs chunk data. */
  183565. extern PNG_EXPORT(png_uint_32, png_get_pixels_per_meter) PNGARG((png_structp
  183566. png_ptr, png_infop info_ptr));
  183567. extern PNG_EXPORT(png_uint_32, png_get_x_pixels_per_meter) PNGARG((png_structp
  183568. png_ptr, png_infop info_ptr));
  183569. extern PNG_EXPORT(png_uint_32, png_get_y_pixels_per_meter) PNGARG((png_structp
  183570. png_ptr, png_infop info_ptr));
  183571. /* Returns pixel aspect ratio, computed from pHYs chunk data. */
  183572. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183573. extern PNG_EXPORT(float, png_get_pixel_aspect_ratio) PNGARG((png_structp
  183574. png_ptr, png_infop info_ptr));
  183575. #endif
  183576. /* Returns image x, y offset in pixels or microns, from oFFs chunk data. */
  183577. extern PNG_EXPORT(png_int_32, png_get_x_offset_pixels) PNGARG((png_structp
  183578. png_ptr, png_infop info_ptr));
  183579. extern PNG_EXPORT(png_int_32, png_get_y_offset_pixels) PNGARG((png_structp
  183580. png_ptr, png_infop info_ptr));
  183581. extern PNG_EXPORT(png_int_32, png_get_x_offset_microns) PNGARG((png_structp
  183582. png_ptr, png_infop info_ptr));
  183583. extern PNG_EXPORT(png_int_32, png_get_y_offset_microns) PNGARG((png_structp
  183584. png_ptr, png_infop info_ptr));
  183585. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  183586. /* Returns pointer to signature string read from PNG header */
  183587. extern PNG_EXPORT(png_bytep,png_get_signature) PNGARG((png_structp png_ptr,
  183588. png_infop info_ptr));
  183589. #if defined(PNG_bKGD_SUPPORTED)
  183590. extern PNG_EXPORT(png_uint_32,png_get_bKGD) PNGARG((png_structp png_ptr,
  183591. png_infop info_ptr, png_color_16p *background));
  183592. #endif
  183593. #if defined(PNG_bKGD_SUPPORTED)
  183594. extern PNG_EXPORT(void,png_set_bKGD) PNGARG((png_structp png_ptr,
  183595. png_infop info_ptr, png_color_16p background));
  183596. #endif
  183597. #if defined(PNG_cHRM_SUPPORTED)
  183598. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183599. extern PNG_EXPORT(png_uint_32,png_get_cHRM) PNGARG((png_structp png_ptr,
  183600. png_infop info_ptr, double *white_x, double *white_y, double *red_x,
  183601. double *red_y, double *green_x, double *green_y, double *blue_x,
  183602. double *blue_y));
  183603. #endif
  183604. #ifdef PNG_FIXED_POINT_SUPPORTED
  183605. extern PNG_EXPORT(png_uint_32,png_get_cHRM_fixed) PNGARG((png_structp png_ptr,
  183606. png_infop info_ptr, png_fixed_point *int_white_x, png_fixed_point
  183607. *int_white_y, png_fixed_point *int_red_x, png_fixed_point *int_red_y,
  183608. png_fixed_point *int_green_x, png_fixed_point *int_green_y, png_fixed_point
  183609. *int_blue_x, png_fixed_point *int_blue_y));
  183610. #endif
  183611. #endif
  183612. #if defined(PNG_cHRM_SUPPORTED)
  183613. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183614. extern PNG_EXPORT(void,png_set_cHRM) PNGARG((png_structp png_ptr,
  183615. png_infop info_ptr, double white_x, double white_y, double red_x,
  183616. double red_y, double green_x, double green_y, double blue_x, double blue_y));
  183617. #endif
  183618. #ifdef PNG_FIXED_POINT_SUPPORTED
  183619. extern PNG_EXPORT(void,png_set_cHRM_fixed) PNGARG((png_structp png_ptr,
  183620. png_infop info_ptr, png_fixed_point int_white_x, png_fixed_point int_white_y,
  183621. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  183622. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  183623. png_fixed_point int_blue_y));
  183624. #endif
  183625. #endif
  183626. #if defined(PNG_gAMA_SUPPORTED)
  183627. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183628. extern PNG_EXPORT(png_uint_32,png_get_gAMA) PNGARG((png_structp png_ptr,
  183629. png_infop info_ptr, double *file_gamma));
  183630. #endif
  183631. extern PNG_EXPORT(png_uint_32,png_get_gAMA_fixed) PNGARG((png_structp png_ptr,
  183632. png_infop info_ptr, png_fixed_point *int_file_gamma));
  183633. #endif
  183634. #if defined(PNG_gAMA_SUPPORTED)
  183635. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183636. extern PNG_EXPORT(void,png_set_gAMA) PNGARG((png_structp png_ptr,
  183637. png_infop info_ptr, double file_gamma));
  183638. #endif
  183639. extern PNG_EXPORT(void,png_set_gAMA_fixed) PNGARG((png_structp png_ptr,
  183640. png_infop info_ptr, png_fixed_point int_file_gamma));
  183641. #endif
  183642. #if defined(PNG_hIST_SUPPORTED)
  183643. extern PNG_EXPORT(png_uint_32,png_get_hIST) PNGARG((png_structp png_ptr,
  183644. png_infop info_ptr, png_uint_16p *hist));
  183645. #endif
  183646. #if defined(PNG_hIST_SUPPORTED)
  183647. extern PNG_EXPORT(void,png_set_hIST) PNGARG((png_structp png_ptr,
  183648. png_infop info_ptr, png_uint_16p hist));
  183649. #endif
  183650. extern PNG_EXPORT(png_uint_32,png_get_IHDR) PNGARG((png_structp png_ptr,
  183651. png_infop info_ptr, png_uint_32 *width, png_uint_32 *height,
  183652. int *bit_depth, int *color_type, int *interlace_method,
  183653. int *compression_method, int *filter_method));
  183654. extern PNG_EXPORT(void,png_set_IHDR) PNGARG((png_structp png_ptr,
  183655. png_infop info_ptr, png_uint_32 width, png_uint_32 height, int bit_depth,
  183656. int color_type, int interlace_method, int compression_method,
  183657. int filter_method));
  183658. #if defined(PNG_oFFs_SUPPORTED)
  183659. extern PNG_EXPORT(png_uint_32,png_get_oFFs) PNGARG((png_structp png_ptr,
  183660. png_infop info_ptr, png_int_32 *offset_x, png_int_32 *offset_y,
  183661. int *unit_type));
  183662. #endif
  183663. #if defined(PNG_oFFs_SUPPORTED)
  183664. extern PNG_EXPORT(void,png_set_oFFs) PNGARG((png_structp png_ptr,
  183665. png_infop info_ptr, png_int_32 offset_x, png_int_32 offset_y,
  183666. int unit_type));
  183667. #endif
  183668. #if defined(PNG_pCAL_SUPPORTED)
  183669. extern PNG_EXPORT(png_uint_32,png_get_pCAL) PNGARG((png_structp png_ptr,
  183670. png_infop info_ptr, png_charp *purpose, png_int_32 *X0, png_int_32 *X1,
  183671. int *type, int *nparams, png_charp *units, png_charpp *params));
  183672. #endif
  183673. #if defined(PNG_pCAL_SUPPORTED)
  183674. extern PNG_EXPORT(void,png_set_pCAL) PNGARG((png_structp png_ptr,
  183675. png_infop info_ptr, png_charp purpose, png_int_32 X0, png_int_32 X1,
  183676. int type, int nparams, png_charp units, png_charpp params));
  183677. #endif
  183678. #if defined(PNG_pHYs_SUPPORTED)
  183679. extern PNG_EXPORT(png_uint_32,png_get_pHYs) PNGARG((png_structp png_ptr,
  183680. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  183681. #endif
  183682. #if defined(PNG_pHYs_SUPPORTED)
  183683. extern PNG_EXPORT(void,png_set_pHYs) PNGARG((png_structp png_ptr,
  183684. png_infop info_ptr, png_uint_32 res_x, png_uint_32 res_y, int unit_type));
  183685. #endif
  183686. extern PNG_EXPORT(png_uint_32,png_get_PLTE) PNGARG((png_structp png_ptr,
  183687. png_infop info_ptr, png_colorp *palette, int *num_palette));
  183688. extern PNG_EXPORT(void,png_set_PLTE) PNGARG((png_structp png_ptr,
  183689. png_infop info_ptr, png_colorp palette, int num_palette));
  183690. #if defined(PNG_sBIT_SUPPORTED)
  183691. extern PNG_EXPORT(png_uint_32,png_get_sBIT) PNGARG((png_structp png_ptr,
  183692. png_infop info_ptr, png_color_8p *sig_bit));
  183693. #endif
  183694. #if defined(PNG_sBIT_SUPPORTED)
  183695. extern PNG_EXPORT(void,png_set_sBIT) PNGARG((png_structp png_ptr,
  183696. png_infop info_ptr, png_color_8p sig_bit));
  183697. #endif
  183698. #if defined(PNG_sRGB_SUPPORTED)
  183699. extern PNG_EXPORT(png_uint_32,png_get_sRGB) PNGARG((png_structp png_ptr,
  183700. png_infop info_ptr, int *intent));
  183701. #endif
  183702. #if defined(PNG_sRGB_SUPPORTED)
  183703. extern PNG_EXPORT(void,png_set_sRGB) PNGARG((png_structp png_ptr,
  183704. png_infop info_ptr, int intent));
  183705. extern PNG_EXPORT(void,png_set_sRGB_gAMA_and_cHRM) PNGARG((png_structp png_ptr,
  183706. png_infop info_ptr, int intent));
  183707. #endif
  183708. #if defined(PNG_iCCP_SUPPORTED)
  183709. extern PNG_EXPORT(png_uint_32,png_get_iCCP) PNGARG((png_structp png_ptr,
  183710. png_infop info_ptr, png_charpp name, int *compression_type,
  183711. png_charpp profile, png_uint_32 *proflen));
  183712. /* Note to maintainer: profile should be png_bytepp */
  183713. #endif
  183714. #if defined(PNG_iCCP_SUPPORTED)
  183715. extern PNG_EXPORT(void,png_set_iCCP) PNGARG((png_structp png_ptr,
  183716. png_infop info_ptr, png_charp name, int compression_type,
  183717. png_charp profile, png_uint_32 proflen));
  183718. /* Note to maintainer: profile should be png_bytep */
  183719. #endif
  183720. #if defined(PNG_sPLT_SUPPORTED)
  183721. extern PNG_EXPORT(png_uint_32,png_get_sPLT) PNGARG((png_structp png_ptr,
  183722. png_infop info_ptr, png_sPLT_tpp entries));
  183723. #endif
  183724. #if defined(PNG_sPLT_SUPPORTED)
  183725. extern PNG_EXPORT(void,png_set_sPLT) PNGARG((png_structp png_ptr,
  183726. png_infop info_ptr, png_sPLT_tp entries, int nentries));
  183727. #endif
  183728. #if defined(PNG_TEXT_SUPPORTED)
  183729. /* png_get_text also returns the number of text chunks in *num_text */
  183730. extern PNG_EXPORT(png_uint_32,png_get_text) PNGARG((png_structp png_ptr,
  183731. png_infop info_ptr, png_textp *text_ptr, int *num_text));
  183732. #endif
  183733. /*
  183734. * Note while png_set_text() will accept a structure whose text,
  183735. * language, and translated keywords are NULL pointers, the structure
  183736. * returned by png_get_text will always contain regular
  183737. * zero-terminated C strings. They might be empty strings but
  183738. * they will never be NULL pointers.
  183739. */
  183740. #if defined(PNG_TEXT_SUPPORTED)
  183741. extern PNG_EXPORT(void,png_set_text) PNGARG((png_structp png_ptr,
  183742. png_infop info_ptr, png_textp text_ptr, int num_text));
  183743. #endif
  183744. #if defined(PNG_tIME_SUPPORTED)
  183745. extern PNG_EXPORT(png_uint_32,png_get_tIME) PNGARG((png_structp png_ptr,
  183746. png_infop info_ptr, png_timep *mod_time));
  183747. #endif
  183748. #if defined(PNG_tIME_SUPPORTED)
  183749. extern PNG_EXPORT(void,png_set_tIME) PNGARG((png_structp png_ptr,
  183750. png_infop info_ptr, png_timep mod_time));
  183751. #endif
  183752. #if defined(PNG_tRNS_SUPPORTED)
  183753. extern PNG_EXPORT(png_uint_32,png_get_tRNS) PNGARG((png_structp png_ptr,
  183754. png_infop info_ptr, png_bytep *trans, int *num_trans,
  183755. png_color_16p *trans_values));
  183756. #endif
  183757. #if defined(PNG_tRNS_SUPPORTED)
  183758. extern PNG_EXPORT(void,png_set_tRNS) PNGARG((png_structp png_ptr,
  183759. png_infop info_ptr, png_bytep trans, int num_trans,
  183760. png_color_16p trans_values));
  183761. #endif
  183762. #if defined(PNG_tRNS_SUPPORTED)
  183763. #endif
  183764. #if defined(PNG_sCAL_SUPPORTED)
  183765. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183766. extern PNG_EXPORT(png_uint_32,png_get_sCAL) PNGARG((png_structp png_ptr,
  183767. png_infop info_ptr, int *unit, double *width, double *height));
  183768. #else
  183769. #ifdef PNG_FIXED_POINT_SUPPORTED
  183770. extern PNG_EXPORT(png_uint_32,png_get_sCAL_s) PNGARG((png_structp png_ptr,
  183771. png_infop info_ptr, int *unit, png_charpp swidth, png_charpp sheight));
  183772. #endif
  183773. #endif
  183774. #endif /* PNG_sCAL_SUPPORTED */
  183775. #if defined(PNG_sCAL_SUPPORTED)
  183776. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183777. extern PNG_EXPORT(void,png_set_sCAL) PNGARG((png_structp png_ptr,
  183778. png_infop info_ptr, int unit, double width, double height));
  183779. #else
  183780. #ifdef PNG_FIXED_POINT_SUPPORTED
  183781. extern PNG_EXPORT(void,png_set_sCAL_s) PNGARG((png_structp png_ptr,
  183782. png_infop info_ptr, int unit, png_charp swidth, png_charp sheight));
  183783. #endif
  183784. #endif
  183785. #endif /* PNG_sCAL_SUPPORTED || PNG_WRITE_sCAL_SUPPORTED */
  183786. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  183787. /* provide a list of chunks and how they are to be handled, if the built-in
  183788. handling or default unknown chunk handling is not desired. Any chunks not
  183789. listed will be handled in the default manner. The IHDR and IEND chunks
  183790. must not be listed.
  183791. keep = 0: follow default behaviour
  183792. = 1: do not keep
  183793. = 2: keep only if safe-to-copy
  183794. = 3: keep even if unsafe-to-copy
  183795. */
  183796. extern PNG_EXPORT(void, png_set_keep_unknown_chunks) PNGARG((png_structp
  183797. png_ptr, int keep, png_bytep chunk_list, int num_chunks));
  183798. extern PNG_EXPORT(void, png_set_unknown_chunks) PNGARG((png_structp png_ptr,
  183799. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns));
  183800. extern PNG_EXPORT(void, png_set_unknown_chunk_location)
  183801. PNGARG((png_structp png_ptr, png_infop info_ptr, int chunk, int location));
  183802. extern PNG_EXPORT(png_uint_32,png_get_unknown_chunks) PNGARG((png_structp
  183803. png_ptr, png_infop info_ptr, png_unknown_chunkpp entries));
  183804. #endif
  183805. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  183806. PNG_EXPORT(int,png_handle_as_unknown) PNGARG((png_structp png_ptr, png_bytep
  183807. chunk_name));
  183808. #endif
  183809. /* Png_free_data() will turn off the "valid" flag for anything it frees.
  183810. If you need to turn it off for a chunk that your application has freed,
  183811. you can use png_set_invalid(png_ptr, info_ptr, PNG_INFO_CHNK); */
  183812. extern PNG_EXPORT(void, png_set_invalid) PNGARG((png_structp png_ptr,
  183813. png_infop info_ptr, int mask));
  183814. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  183815. /* The "params" pointer is currently not used and is for future expansion. */
  183816. extern PNG_EXPORT(void, png_read_png) PNGARG((png_structp png_ptr,
  183817. png_infop info_ptr,
  183818. int transforms,
  183819. png_voidp params));
  183820. extern PNG_EXPORT(void, png_write_png) PNGARG((png_structp png_ptr,
  183821. png_infop info_ptr,
  183822. int transforms,
  183823. png_voidp params));
  183824. #endif
  183825. /* Define PNG_DEBUG at compile time for debugging information. Higher
  183826. * numbers for PNG_DEBUG mean more debugging information. This has
  183827. * only been added since version 0.95 so it is not implemented throughout
  183828. * libpng yet, but more support will be added as needed.
  183829. */
  183830. #ifdef PNG_DEBUG
  183831. #if (PNG_DEBUG > 0)
  183832. #if !defined(PNG_DEBUG_FILE) && defined(_MSC_VER)
  183833. #include <crtdbg.h>
  183834. #if (PNG_DEBUG > 1)
  183835. #define png_debug(l,m) _RPT0(_CRT_WARN,m)
  183836. #define png_debug1(l,m,p1) _RPT1(_CRT_WARN,m,p1)
  183837. #define png_debug2(l,m,p1,p2) _RPT2(_CRT_WARN,m,p1,p2)
  183838. #endif
  183839. #else /* PNG_DEBUG_FILE || !_MSC_VER */
  183840. #ifndef PNG_DEBUG_FILE
  183841. #define PNG_DEBUG_FILE stderr
  183842. #endif /* PNG_DEBUG_FILE */
  183843. #if (PNG_DEBUG > 1)
  183844. #define png_debug(l,m) \
  183845. { \
  183846. int num_tabs=l; \
  183847. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183848. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":"")))); \
  183849. }
  183850. #define png_debug1(l,m,p1) \
  183851. { \
  183852. int num_tabs=l; \
  183853. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183854. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1); \
  183855. }
  183856. #define png_debug2(l,m,p1,p2) \
  183857. { \
  183858. int num_tabs=l; \
  183859. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183860. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1,p2); \
  183861. }
  183862. #endif /* (PNG_DEBUG > 1) */
  183863. #endif /* _MSC_VER */
  183864. #endif /* (PNG_DEBUG > 0) */
  183865. #endif /* PNG_DEBUG */
  183866. #ifndef png_debug
  183867. #define png_debug(l, m)
  183868. #endif
  183869. #ifndef png_debug1
  183870. #define png_debug1(l, m, p1)
  183871. #endif
  183872. #ifndef png_debug2
  183873. #define png_debug2(l, m, p1, p2)
  183874. #endif
  183875. extern PNG_EXPORT(png_charp,png_get_copyright) PNGARG((png_structp png_ptr));
  183876. extern PNG_EXPORT(png_charp,png_get_header_ver) PNGARG((png_structp png_ptr));
  183877. extern PNG_EXPORT(png_charp,png_get_header_version) PNGARG((png_structp png_ptr));
  183878. extern PNG_EXPORT(png_charp,png_get_libpng_ver) PNGARG((png_structp png_ptr));
  183879. #ifdef PNG_MNG_FEATURES_SUPPORTED
  183880. extern PNG_EXPORT(png_uint_32,png_permit_mng_features) PNGARG((png_structp
  183881. png_ptr, png_uint_32 mng_features_permitted));
  183882. #endif
  183883. /* For use in png_set_keep_unknown, added to version 1.2.6 */
  183884. #define PNG_HANDLE_CHUNK_AS_DEFAULT 0
  183885. #define PNG_HANDLE_CHUNK_NEVER 1
  183886. #define PNG_HANDLE_CHUNK_IF_SAFE 2
  183887. #define PNG_HANDLE_CHUNK_ALWAYS 3
  183888. /* Added to version 1.2.0 */
  183889. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  183890. #if defined(PNG_MMX_CODE_SUPPORTED)
  183891. #define PNG_ASM_FLAG_MMX_SUPPORT_COMPILED 0x01 /* not user-settable */
  183892. #define PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU 0x02 /* not user-settable */
  183893. #define PNG_ASM_FLAG_MMX_READ_COMBINE_ROW 0x04
  183894. #define PNG_ASM_FLAG_MMX_READ_INTERLACE 0x08
  183895. #define PNG_ASM_FLAG_MMX_READ_FILTER_SUB 0x10
  183896. #define PNG_ASM_FLAG_MMX_READ_FILTER_UP 0x20
  183897. #define PNG_ASM_FLAG_MMX_READ_FILTER_AVG 0x40
  183898. #define PNG_ASM_FLAG_MMX_READ_FILTER_PAETH 0x80
  183899. #define PNG_ASM_FLAGS_INITIALIZED 0x80000000 /* not user-settable */
  183900. #define PNG_MMX_READ_FLAGS ( PNG_ASM_FLAG_MMX_READ_COMBINE_ROW \
  183901. | PNG_ASM_FLAG_MMX_READ_INTERLACE \
  183902. | PNG_ASM_FLAG_MMX_READ_FILTER_SUB \
  183903. | PNG_ASM_FLAG_MMX_READ_FILTER_UP \
  183904. | PNG_ASM_FLAG_MMX_READ_FILTER_AVG \
  183905. | PNG_ASM_FLAG_MMX_READ_FILTER_PAETH )
  183906. #define PNG_MMX_WRITE_FLAGS ( 0 )
  183907. #define PNG_MMX_FLAGS ( PNG_ASM_FLAG_MMX_SUPPORT_COMPILED \
  183908. | PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU \
  183909. | PNG_MMX_READ_FLAGS \
  183910. | PNG_MMX_WRITE_FLAGS )
  183911. #define PNG_SELECT_READ 1
  183912. #define PNG_SELECT_WRITE 2
  183913. #endif /* PNG_MMX_CODE_SUPPORTED */
  183914. #if !defined(PNG_1_0_X)
  183915. /* pngget.c */
  183916. extern PNG_EXPORT(png_uint_32,png_get_mmx_flagmask)
  183917. PNGARG((int flag_select, int *compilerID));
  183918. /* pngget.c */
  183919. extern PNG_EXPORT(png_uint_32,png_get_asm_flagmask)
  183920. PNGARG((int flag_select));
  183921. /* pngget.c */
  183922. extern PNG_EXPORT(png_uint_32,png_get_asm_flags)
  183923. PNGARG((png_structp png_ptr));
  183924. /* pngget.c */
  183925. extern PNG_EXPORT(png_byte,png_get_mmx_bitdepth_threshold)
  183926. PNGARG((png_structp png_ptr));
  183927. /* pngget.c */
  183928. extern PNG_EXPORT(png_uint_32,png_get_mmx_rowbytes_threshold)
  183929. PNGARG((png_structp png_ptr));
  183930. /* pngset.c */
  183931. extern PNG_EXPORT(void,png_set_asm_flags)
  183932. PNGARG((png_structp png_ptr, png_uint_32 asm_flags));
  183933. /* pngset.c */
  183934. extern PNG_EXPORT(void,png_set_mmx_thresholds)
  183935. PNGARG((png_structp png_ptr, png_byte mmx_bitdepth_threshold,
  183936. png_uint_32 mmx_rowbytes_threshold));
  183937. #endif /* PNG_1_0_X */
  183938. #if !defined(PNG_1_0_X)
  183939. /* png.c, pnggccrd.c, or pngvcrd.c */
  183940. extern PNG_EXPORT(int,png_mmx_support) PNGARG((void));
  183941. #endif /* PNG_ASSEMBLER_CODE_SUPPORTED */
  183942. /* Strip the prepended error numbers ("#nnn ") from error and warning
  183943. * messages before passing them to the error or warning handler. */
  183944. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  183945. extern PNG_EXPORT(void,png_set_strip_error_numbers) PNGARG((png_structp
  183946. png_ptr, png_uint_32 strip_mode));
  183947. #endif
  183948. #endif /* PNG_1_0_X */
  183949. /* Added at libpng-1.2.6 */
  183950. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  183951. extern PNG_EXPORT(void,png_set_user_limits) PNGARG((png_structp
  183952. png_ptr, png_uint_32 user_width_max, png_uint_32 user_height_max));
  183953. extern PNG_EXPORT(png_uint_32,png_get_user_width_max) PNGARG((png_structp
  183954. png_ptr));
  183955. extern PNG_EXPORT(png_uint_32,png_get_user_height_max) PNGARG((png_structp
  183956. png_ptr));
  183957. #endif
  183958. /* Maintainer: Put new public prototypes here ^, in libpng.3, and project defs */
  183959. #ifdef PNG_READ_COMPOSITE_NODIV_SUPPORTED
  183960. /* With these routines we avoid an integer divide, which will be slower on
  183961. * most machines. However, it does take more operations than the corresponding
  183962. * divide method, so it may be slower on a few RISC systems. There are two
  183963. * shifts (by 8 or 16 bits) and an addition, versus a single integer divide.
  183964. *
  183965. * Note that the rounding factors are NOT supposed to be the same! 128 and
  183966. * 32768 are correct for the NODIV code; 127 and 32767 are correct for the
  183967. * standard method.
  183968. *
  183969. * [Optimized code by Greg Roelofs and Mark Adler...blame us for bugs. :-) ]
  183970. */
  183971. /* fg and bg should be in `gamma 1.0' space; alpha is the opacity */
  183972. # define png_composite(composite, fg, alpha, bg) \
  183973. { png_uint_16 temp = (png_uint_16)((png_uint_16)(fg) * (png_uint_16)(alpha) \
  183974. + (png_uint_16)(bg)*(png_uint_16)(255 - \
  183975. (png_uint_16)(alpha)) + (png_uint_16)128); \
  183976. (composite) = (png_byte)((temp + (temp >> 8)) >> 8); }
  183977. # define png_composite_16(composite, fg, alpha, bg) \
  183978. { png_uint_32 temp = (png_uint_32)((png_uint_32)(fg) * (png_uint_32)(alpha) \
  183979. + (png_uint_32)(bg)*(png_uint_32)(65535L - \
  183980. (png_uint_32)(alpha)) + (png_uint_32)32768L); \
  183981. (composite) = (png_uint_16)((temp + (temp >> 16)) >> 16); }
  183982. #else /* standard method using integer division */
  183983. # define png_composite(composite, fg, alpha, bg) \
  183984. (composite) = (png_byte)(((png_uint_16)(fg) * (png_uint_16)(alpha) + \
  183985. (png_uint_16)(bg) * (png_uint_16)(255 - (png_uint_16)(alpha)) + \
  183986. (png_uint_16)127) / 255)
  183987. # define png_composite_16(composite, fg, alpha, bg) \
  183988. (composite) = (png_uint_16)(((png_uint_32)(fg) * (png_uint_32)(alpha) + \
  183989. (png_uint_32)(bg)*(png_uint_32)(65535L - (png_uint_32)(alpha)) + \
  183990. (png_uint_32)32767) / (png_uint_32)65535L)
  183991. #endif /* PNG_READ_COMPOSITE_NODIV_SUPPORTED */
  183992. /* Inline macros to do direct reads of bytes from the input buffer. These
  183993. * require that you are using an architecture that uses PNG byte ordering
  183994. * (MSB first) and supports unaligned data storage. I think that PowerPC
  183995. * in big-endian mode and 680x0 are the only ones that will support this.
  183996. * The x86 line of processors definitely do not. The png_get_int_32()
  183997. * routine also assumes we are using two's complement format for negative
  183998. * values, which is almost certainly true.
  183999. */
  184000. #if defined(PNG_READ_BIG_ENDIAN_SUPPORTED)
  184001. # define png_get_uint_32(buf) ( *((png_uint_32p) (buf)))
  184002. # define png_get_uint_16(buf) ( *((png_uint_16p) (buf)))
  184003. # define png_get_int_32(buf) ( *((png_int_32p) (buf)))
  184004. #else
  184005. extern PNG_EXPORT(png_uint_32,png_get_uint_32) PNGARG((png_bytep buf));
  184006. extern PNG_EXPORT(png_uint_16,png_get_uint_16) PNGARG((png_bytep buf));
  184007. extern PNG_EXPORT(png_int_32,png_get_int_32) PNGARG((png_bytep buf));
  184008. #endif /* !PNG_READ_BIG_ENDIAN_SUPPORTED */
  184009. extern PNG_EXPORT(png_uint_32,png_get_uint_31)
  184010. PNGARG((png_structp png_ptr, png_bytep buf));
  184011. /* No png_get_int_16 -- may be added if there's a real need for it. */
  184012. /* Place a 32-bit number into a buffer in PNG byte order (big-endian).
  184013. */
  184014. extern PNG_EXPORT(void,png_save_uint_32)
  184015. PNGARG((png_bytep buf, png_uint_32 i));
  184016. extern PNG_EXPORT(void,png_save_int_32)
  184017. PNGARG((png_bytep buf, png_int_32 i));
  184018. /* Place a 16-bit number into a buffer in PNG byte order.
  184019. * The parameter is declared unsigned int, not png_uint_16,
  184020. * just to avoid potential problems on pre-ANSI C compilers.
  184021. */
  184022. extern PNG_EXPORT(void,png_save_uint_16)
  184023. PNGARG((png_bytep buf, unsigned int i));
  184024. /* No png_save_int_16 -- may be added if there's a real need for it. */
  184025. /* ************************************************************************* */
  184026. /* These next functions are used internally in the code. They generally
  184027. * shouldn't be used unless you are writing code to add or replace some
  184028. * functionality in libpng. More information about most functions can
  184029. * be found in the files where the functions are located.
  184030. */
  184031. /* Various modes of operation, that are visible to applications because
  184032. * they are used for unknown chunk location.
  184033. */
  184034. #define PNG_HAVE_IHDR 0x01
  184035. #define PNG_HAVE_PLTE 0x02
  184036. #define PNG_HAVE_IDAT 0x04
  184037. #define PNG_AFTER_IDAT 0x08 /* Have complete zlib datastream */
  184038. #define PNG_HAVE_IEND 0x10
  184039. #if defined(PNG_INTERNAL)
  184040. /* More modes of operation. Note that after an init, mode is set to
  184041. * zero automatically when the structure is created.
  184042. */
  184043. #define PNG_HAVE_gAMA 0x20
  184044. #define PNG_HAVE_cHRM 0x40
  184045. #define PNG_HAVE_sRGB 0x80
  184046. #define PNG_HAVE_CHUNK_HEADER 0x100
  184047. #define PNG_WROTE_tIME 0x200
  184048. #define PNG_WROTE_INFO_BEFORE_PLTE 0x400
  184049. #define PNG_BACKGROUND_IS_GRAY 0x800
  184050. #define PNG_HAVE_PNG_SIGNATURE 0x1000
  184051. #define PNG_HAVE_CHUNK_AFTER_IDAT 0x2000 /* Have another chunk after IDAT */
  184052. /* flags for the transformations the PNG library does on the image data */
  184053. #define PNG_BGR 0x0001
  184054. #define PNG_INTERLACE 0x0002
  184055. #define PNG_PACK 0x0004
  184056. #define PNG_SHIFT 0x0008
  184057. #define PNG_SWAP_BYTES 0x0010
  184058. #define PNG_INVERT_MONO 0x0020
  184059. #define PNG_DITHER 0x0040
  184060. #define PNG_BACKGROUND 0x0080
  184061. #define PNG_BACKGROUND_EXPAND 0x0100
  184062. /* 0x0200 unused */
  184063. #define PNG_16_TO_8 0x0400
  184064. #define PNG_RGBA 0x0800
  184065. #define PNG_EXPAND 0x1000
  184066. #define PNG_GAMMA 0x2000
  184067. #define PNG_GRAY_TO_RGB 0x4000
  184068. #define PNG_FILLER 0x8000L
  184069. #define PNG_PACKSWAP 0x10000L
  184070. #define PNG_SWAP_ALPHA 0x20000L
  184071. #define PNG_STRIP_ALPHA 0x40000L
  184072. #define PNG_INVERT_ALPHA 0x80000L
  184073. #define PNG_USER_TRANSFORM 0x100000L
  184074. #define PNG_RGB_TO_GRAY_ERR 0x200000L
  184075. #define PNG_RGB_TO_GRAY_WARN 0x400000L
  184076. #define PNG_RGB_TO_GRAY 0x600000L /* two bits, RGB_TO_GRAY_ERR|WARN */
  184077. /* 0x800000L Unused */
  184078. #define PNG_ADD_ALPHA 0x1000000L /* Added to libpng-1.2.7 */
  184079. #define PNG_EXPAND_tRNS 0x2000000L /* Added to libpng-1.2.9 */
  184080. /* 0x4000000L unused */
  184081. /* 0x8000000L unused */
  184082. /* 0x10000000L unused */
  184083. /* 0x20000000L unused */
  184084. /* 0x40000000L unused */
  184085. /* flags for png_create_struct */
  184086. #define PNG_STRUCT_PNG 0x0001
  184087. #define PNG_STRUCT_INFO 0x0002
  184088. /* Scaling factor for filter heuristic weighting calculations */
  184089. #define PNG_WEIGHT_SHIFT 8
  184090. #define PNG_WEIGHT_FACTOR (1<<(PNG_WEIGHT_SHIFT))
  184091. #define PNG_COST_SHIFT 3
  184092. #define PNG_COST_FACTOR (1<<(PNG_COST_SHIFT))
  184093. /* flags for the png_ptr->flags rather than declaring a byte for each one */
  184094. #define PNG_FLAG_ZLIB_CUSTOM_STRATEGY 0x0001
  184095. #define PNG_FLAG_ZLIB_CUSTOM_LEVEL 0x0002
  184096. #define PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL 0x0004
  184097. #define PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS 0x0008
  184098. #define PNG_FLAG_ZLIB_CUSTOM_METHOD 0x0010
  184099. #define PNG_FLAG_ZLIB_FINISHED 0x0020
  184100. #define PNG_FLAG_ROW_INIT 0x0040
  184101. #define PNG_FLAG_FILLER_AFTER 0x0080
  184102. #define PNG_FLAG_CRC_ANCILLARY_USE 0x0100
  184103. #define PNG_FLAG_CRC_ANCILLARY_NOWARN 0x0200
  184104. #define PNG_FLAG_CRC_CRITICAL_USE 0x0400
  184105. #define PNG_FLAG_CRC_CRITICAL_IGNORE 0x0800
  184106. #define PNG_FLAG_FREE_PLTE 0x1000
  184107. #define PNG_FLAG_FREE_TRNS 0x2000
  184108. #define PNG_FLAG_FREE_HIST 0x4000
  184109. #define PNG_FLAG_KEEP_UNKNOWN_CHUNKS 0x8000L
  184110. #define PNG_FLAG_KEEP_UNSAFE_CHUNKS 0x10000L
  184111. #define PNG_FLAG_LIBRARY_MISMATCH 0x20000L
  184112. #define PNG_FLAG_STRIP_ERROR_NUMBERS 0x40000L
  184113. #define PNG_FLAG_STRIP_ERROR_TEXT 0x80000L
  184114. #define PNG_FLAG_MALLOC_NULL_MEM_OK 0x100000L
  184115. #define PNG_FLAG_ADD_ALPHA 0x200000L /* Added to libpng-1.2.8 */
  184116. #define PNG_FLAG_STRIP_ALPHA 0x400000L /* Added to libpng-1.2.8 */
  184117. /* 0x800000L unused */
  184118. /* 0x1000000L unused */
  184119. /* 0x2000000L unused */
  184120. /* 0x4000000L unused */
  184121. /* 0x8000000L unused */
  184122. /* 0x10000000L unused */
  184123. /* 0x20000000L unused */
  184124. /* 0x40000000L unused */
  184125. #define PNG_FLAG_CRC_ANCILLARY_MASK (PNG_FLAG_CRC_ANCILLARY_USE | \
  184126. PNG_FLAG_CRC_ANCILLARY_NOWARN)
  184127. #define PNG_FLAG_CRC_CRITICAL_MASK (PNG_FLAG_CRC_CRITICAL_USE | \
  184128. PNG_FLAG_CRC_CRITICAL_IGNORE)
  184129. #define PNG_FLAG_CRC_MASK (PNG_FLAG_CRC_ANCILLARY_MASK | \
  184130. PNG_FLAG_CRC_CRITICAL_MASK)
  184131. /* save typing and make code easier to understand */
  184132. #define PNG_COLOR_DIST(c1, c2) (abs((int)((c1).red) - (int)((c2).red)) + \
  184133. abs((int)((c1).green) - (int)((c2).green)) + \
  184134. abs((int)((c1).blue) - (int)((c2).blue)))
  184135. /* Added to libpng-1.2.6 JB */
  184136. #define PNG_ROWBYTES(pixel_bits, width) \
  184137. ((pixel_bits) >= 8 ? \
  184138. ((width) * (((png_uint_32)(pixel_bits)) >> 3)) : \
  184139. (( ((width) * ((png_uint_32)(pixel_bits))) + 7) >> 3) )
  184140. /* PNG_OUT_OF_RANGE returns true if value is outside the range
  184141. ideal-delta..ideal+delta. Each argument is evaluated twice.
  184142. "ideal" and "delta" should be constants, normally simple
  184143. integers, "value" a variable. Added to libpng-1.2.6 JB */
  184144. #define PNG_OUT_OF_RANGE(value, ideal, delta) \
  184145. ( (value) < (ideal)-(delta) || (value) > (ideal)+(delta) )
  184146. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  184147. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  184148. /* place to hold the signature string for a PNG file. */
  184149. #ifdef PNG_USE_GLOBAL_ARRAYS
  184150. PNG_EXPORT_VAR (PNG_CONST png_byte FARDATA) png_sig[8];
  184151. #else
  184152. #endif
  184153. #endif /* PNG_NO_EXTERN */
  184154. /* Constant strings for known chunk types. If you need to add a chunk,
  184155. * define the name here, and add an invocation of the macro in png.c and
  184156. * wherever it's needed.
  184157. */
  184158. #define PNG_IHDR png_byte png_IHDR[5] = { 73, 72, 68, 82, '\0'}
  184159. #define PNG_IDAT png_byte png_IDAT[5] = { 73, 68, 65, 84, '\0'}
  184160. #define PNG_IEND png_byte png_IEND[5] = { 73, 69, 78, 68, '\0'}
  184161. #define PNG_PLTE png_byte png_PLTE[5] = { 80, 76, 84, 69, '\0'}
  184162. #define PNG_bKGD png_byte png_bKGD[5] = { 98, 75, 71, 68, '\0'}
  184163. #define PNG_cHRM png_byte png_cHRM[5] = { 99, 72, 82, 77, '\0'}
  184164. #define PNG_gAMA png_byte png_gAMA[5] = {103, 65, 77, 65, '\0'}
  184165. #define PNG_hIST png_byte png_hIST[5] = {104, 73, 83, 84, '\0'}
  184166. #define PNG_iCCP png_byte png_iCCP[5] = {105, 67, 67, 80, '\0'}
  184167. #define PNG_iTXt png_byte png_iTXt[5] = {105, 84, 88, 116, '\0'}
  184168. #define PNG_oFFs png_byte png_oFFs[5] = {111, 70, 70, 115, '\0'}
  184169. #define PNG_pCAL png_byte png_pCAL[5] = {112, 67, 65, 76, '\0'}
  184170. #define PNG_sCAL png_byte png_sCAL[5] = {115, 67, 65, 76, '\0'}
  184171. #define PNG_pHYs png_byte png_pHYs[5] = {112, 72, 89, 115, '\0'}
  184172. #define PNG_sBIT png_byte png_sBIT[5] = {115, 66, 73, 84, '\0'}
  184173. #define PNG_sPLT png_byte png_sPLT[5] = {115, 80, 76, 84, '\0'}
  184174. #define PNG_sRGB png_byte png_sRGB[5] = {115, 82, 71, 66, '\0'}
  184175. #define PNG_tEXt png_byte png_tEXt[5] = {116, 69, 88, 116, '\0'}
  184176. #define PNG_tIME png_byte png_tIME[5] = {116, 73, 77, 69, '\0'}
  184177. #define PNG_tRNS png_byte png_tRNS[5] = {116, 82, 78, 83, '\0'}
  184178. #define PNG_zTXt png_byte png_zTXt[5] = {122, 84, 88, 116, '\0'}
  184179. #ifdef PNG_USE_GLOBAL_ARRAYS
  184180. PNG_EXPORT_VAR (png_byte FARDATA) png_IHDR[5];
  184181. PNG_EXPORT_VAR (png_byte FARDATA) png_IDAT[5];
  184182. PNG_EXPORT_VAR (png_byte FARDATA) png_IEND[5];
  184183. PNG_EXPORT_VAR (png_byte FARDATA) png_PLTE[5];
  184184. PNG_EXPORT_VAR (png_byte FARDATA) png_bKGD[5];
  184185. PNG_EXPORT_VAR (png_byte FARDATA) png_cHRM[5];
  184186. PNG_EXPORT_VAR (png_byte FARDATA) png_gAMA[5];
  184187. PNG_EXPORT_VAR (png_byte FARDATA) png_hIST[5];
  184188. PNG_EXPORT_VAR (png_byte FARDATA) png_iCCP[5];
  184189. PNG_EXPORT_VAR (png_byte FARDATA) png_iTXt[5];
  184190. PNG_EXPORT_VAR (png_byte FARDATA) png_oFFs[5];
  184191. PNG_EXPORT_VAR (png_byte FARDATA) png_pCAL[5];
  184192. PNG_EXPORT_VAR (png_byte FARDATA) png_sCAL[5];
  184193. PNG_EXPORT_VAR (png_byte FARDATA) png_pHYs[5];
  184194. PNG_EXPORT_VAR (png_byte FARDATA) png_sBIT[5];
  184195. PNG_EXPORT_VAR (png_byte FARDATA) png_sPLT[5];
  184196. PNG_EXPORT_VAR (png_byte FARDATA) png_sRGB[5];
  184197. PNG_EXPORT_VAR (png_byte FARDATA) png_tEXt[5];
  184198. PNG_EXPORT_VAR (png_byte FARDATA) png_tIME[5];
  184199. PNG_EXPORT_VAR (png_byte FARDATA) png_tRNS[5];
  184200. PNG_EXPORT_VAR (png_byte FARDATA) png_zTXt[5];
  184201. #endif /* PNG_USE_GLOBAL_ARRAYS */
  184202. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  184203. /* Initialize png_ptr struct for reading, and allocate any other memory.
  184204. * (old interface - DEPRECATED - use png_create_read_struct instead).
  184205. */
  184206. extern PNG_EXPORT(void,png_read_init) PNGARG((png_structp png_ptr));
  184207. #undef png_read_init
  184208. #define png_read_init(png_ptr) png_read_init_3(&png_ptr, \
  184209. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  184210. #endif
  184211. extern PNG_EXPORT(void,png_read_init_3) PNGARG((png_structpp ptr_ptr,
  184212. png_const_charp user_png_ver, png_size_t png_struct_size));
  184213. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  184214. extern PNG_EXPORT(void,png_read_init_2) PNGARG((png_structp png_ptr,
  184215. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  184216. png_info_size));
  184217. #endif
  184218. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  184219. /* Initialize png_ptr struct for writing, and allocate any other memory.
  184220. * (old interface - DEPRECATED - use png_create_write_struct instead).
  184221. */
  184222. extern PNG_EXPORT(void,png_write_init) PNGARG((png_structp png_ptr));
  184223. #undef png_write_init
  184224. #define png_write_init(png_ptr) png_write_init_3(&png_ptr, \
  184225. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  184226. #endif
  184227. extern PNG_EXPORT(void,png_write_init_3) PNGARG((png_structpp ptr_ptr,
  184228. png_const_charp user_png_ver, png_size_t png_struct_size));
  184229. extern PNG_EXPORT(void,png_write_init_2) PNGARG((png_structp png_ptr,
  184230. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  184231. png_info_size));
  184232. /* Allocate memory for an internal libpng struct */
  184233. PNG_EXTERN png_voidp png_create_struct PNGARG((int type));
  184234. /* Free memory from internal libpng struct */
  184235. PNG_EXTERN void png_destroy_struct PNGARG((png_voidp struct_ptr));
  184236. PNG_EXTERN png_voidp png_create_struct_2 PNGARG((int type, png_malloc_ptr
  184237. malloc_fn, png_voidp mem_ptr));
  184238. PNG_EXTERN void png_destroy_struct_2 PNGARG((png_voidp struct_ptr,
  184239. png_free_ptr free_fn, png_voidp mem_ptr));
  184240. /* Free any memory that info_ptr points to and reset struct. */
  184241. PNG_EXTERN void png_info_destroy PNGARG((png_structp png_ptr,
  184242. png_infop info_ptr));
  184243. #ifndef PNG_1_0_X
  184244. /* Function to allocate memory for zlib. */
  184245. PNG_EXTERN voidpf png_zalloc PNGARG((voidpf png_ptr, uInt items, uInt size));
  184246. /* Function to free memory for zlib */
  184247. PNG_EXTERN void png_zfree PNGARG((voidpf png_ptr, voidpf ptr));
  184248. #ifdef PNG_SIZE_T
  184249. /* Function to convert a sizeof an item to png_sizeof item */
  184250. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  184251. #endif
  184252. /* Next four functions are used internally as callbacks. PNGAPI is required
  184253. * but not PNG_EXPORT. PNGAPI added at libpng version 1.2.3. */
  184254. PNG_EXTERN void PNGAPI png_default_read_data PNGARG((png_structp png_ptr,
  184255. png_bytep data, png_size_t length));
  184256. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  184257. PNG_EXTERN void PNGAPI png_push_fill_buffer PNGARG((png_structp png_ptr,
  184258. png_bytep buffer, png_size_t length));
  184259. #endif
  184260. PNG_EXTERN void PNGAPI png_default_write_data PNGARG((png_structp png_ptr,
  184261. png_bytep data, png_size_t length));
  184262. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  184263. #if !defined(PNG_NO_STDIO)
  184264. PNG_EXTERN void PNGAPI png_default_flush PNGARG((png_structp png_ptr));
  184265. #endif
  184266. #endif
  184267. #else /* PNG_1_0_X */
  184268. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  184269. PNG_EXTERN void png_push_fill_buffer PNGARG((png_structp png_ptr,
  184270. png_bytep buffer, png_size_t length));
  184271. #endif
  184272. #endif /* PNG_1_0_X */
  184273. /* Reset the CRC variable */
  184274. PNG_EXTERN void png_reset_crc PNGARG((png_structp png_ptr));
  184275. /* Write the "data" buffer to whatever output you are using. */
  184276. PNG_EXTERN void png_write_data PNGARG((png_structp png_ptr, png_bytep data,
  184277. png_size_t length));
  184278. /* Read data from whatever input you are using into the "data" buffer */
  184279. PNG_EXTERN void png_read_data PNGARG((png_structp png_ptr, png_bytep data,
  184280. png_size_t length));
  184281. /* Read bytes into buf, and update png_ptr->crc */
  184282. PNG_EXTERN void png_crc_read PNGARG((png_structp png_ptr, png_bytep buf,
  184283. png_size_t length));
  184284. /* Decompress data in a chunk that uses compression */
  184285. #if defined(PNG_zTXt_SUPPORTED) || defined(PNG_iTXt_SUPPORTED) || \
  184286. defined(PNG_iCCP_SUPPORTED) || defined(PNG_sPLT_SUPPORTED)
  184287. PNG_EXTERN png_charp png_decompress_chunk PNGARG((png_structp png_ptr,
  184288. int comp_type, png_charp chunkdata, png_size_t chunklength,
  184289. png_size_t prefix_length, png_size_t *data_length));
  184290. #endif
  184291. /* Read "skip" bytes, read the file crc, and (optionally) verify png_ptr->crc */
  184292. PNG_EXTERN int png_crc_finish PNGARG((png_structp png_ptr, png_uint_32 skip));
  184293. /* Read the CRC from the file and compare it to the libpng calculated CRC */
  184294. PNG_EXTERN int png_crc_error PNGARG((png_structp png_ptr));
  184295. /* Calculate the CRC over a section of data. Note that we are only
  184296. * passing a maximum of 64K on systems that have this as a memory limit,
  184297. * since this is the maximum buffer size we can specify.
  184298. */
  184299. PNG_EXTERN void png_calculate_crc PNGARG((png_structp png_ptr, png_bytep ptr,
  184300. png_size_t length));
  184301. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  184302. PNG_EXTERN void png_flush PNGARG((png_structp png_ptr));
  184303. #endif
  184304. /* simple function to write the signature */
  184305. PNG_EXTERN void png_write_sig PNGARG((png_structp png_ptr));
  184306. /* write various chunks */
  184307. /* Write the IHDR chunk, and update the png_struct with the necessary
  184308. * information.
  184309. */
  184310. PNG_EXTERN void png_write_IHDR PNGARG((png_structp png_ptr, png_uint_32 width,
  184311. png_uint_32 height,
  184312. int bit_depth, int color_type, int compression_method, int filter_method,
  184313. int interlace_method));
  184314. PNG_EXTERN void png_write_PLTE PNGARG((png_structp png_ptr, png_colorp palette,
  184315. png_uint_32 num_pal));
  184316. PNG_EXTERN void png_write_IDAT PNGARG((png_structp png_ptr, png_bytep data,
  184317. png_size_t length));
  184318. PNG_EXTERN void png_write_IEND PNGARG((png_structp png_ptr));
  184319. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  184320. #ifdef PNG_FLOATING_POINT_SUPPORTED
  184321. PNG_EXTERN void png_write_gAMA PNGARG((png_structp png_ptr, double file_gamma));
  184322. #endif
  184323. #ifdef PNG_FIXED_POINT_SUPPORTED
  184324. PNG_EXTERN void png_write_gAMA_fixed PNGARG((png_structp png_ptr, png_fixed_point
  184325. file_gamma));
  184326. #endif
  184327. #endif
  184328. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  184329. PNG_EXTERN void png_write_sBIT PNGARG((png_structp png_ptr, png_color_8p sbit,
  184330. int color_type));
  184331. #endif
  184332. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  184333. #ifdef PNG_FLOATING_POINT_SUPPORTED
  184334. PNG_EXTERN void png_write_cHRM PNGARG((png_structp png_ptr,
  184335. double white_x, double white_y,
  184336. double red_x, double red_y, double green_x, double green_y,
  184337. double blue_x, double blue_y));
  184338. #endif
  184339. #ifdef PNG_FIXED_POINT_SUPPORTED
  184340. PNG_EXTERN void png_write_cHRM_fixed PNGARG((png_structp png_ptr,
  184341. png_fixed_point int_white_x, png_fixed_point int_white_y,
  184342. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  184343. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  184344. png_fixed_point int_blue_y));
  184345. #endif
  184346. #endif
  184347. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  184348. PNG_EXTERN void png_write_sRGB PNGARG((png_structp png_ptr,
  184349. int intent));
  184350. #endif
  184351. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  184352. PNG_EXTERN void png_write_iCCP PNGARG((png_structp png_ptr,
  184353. png_charp name, int compression_type,
  184354. png_charp profile, int proflen));
  184355. /* Note to maintainer: profile should be png_bytep */
  184356. #endif
  184357. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  184358. PNG_EXTERN void png_write_sPLT PNGARG((png_structp png_ptr,
  184359. png_sPLT_tp palette));
  184360. #endif
  184361. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  184362. PNG_EXTERN void png_write_tRNS PNGARG((png_structp png_ptr, png_bytep trans,
  184363. png_color_16p values, int number, int color_type));
  184364. #endif
  184365. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  184366. PNG_EXTERN void png_write_bKGD PNGARG((png_structp png_ptr,
  184367. png_color_16p values, int color_type));
  184368. #endif
  184369. #if defined(PNG_WRITE_hIST_SUPPORTED)
  184370. PNG_EXTERN void png_write_hIST PNGARG((png_structp png_ptr, png_uint_16p hist,
  184371. int num_hist));
  184372. #endif
  184373. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  184374. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  184375. PNG_EXTERN png_size_t png_check_keyword PNGARG((png_structp png_ptr,
  184376. png_charp key, png_charpp new_key));
  184377. #endif
  184378. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  184379. PNG_EXTERN void png_write_tEXt PNGARG((png_structp png_ptr, png_charp key,
  184380. png_charp text, png_size_t text_len));
  184381. #endif
  184382. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  184383. PNG_EXTERN void png_write_zTXt PNGARG((png_structp png_ptr, png_charp key,
  184384. png_charp text, png_size_t text_len, int compression));
  184385. #endif
  184386. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  184387. PNG_EXTERN void png_write_iTXt PNGARG((png_structp png_ptr,
  184388. int compression, png_charp key, png_charp lang, png_charp lang_key,
  184389. png_charp text));
  184390. #endif
  184391. #if defined(PNG_TEXT_SUPPORTED) /* Added at version 1.0.14 and 1.2.4 */
  184392. PNG_EXTERN int png_set_text_2 PNGARG((png_structp png_ptr,
  184393. png_infop info_ptr, png_textp text_ptr, int num_text));
  184394. #endif
  184395. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  184396. PNG_EXTERN void png_write_oFFs PNGARG((png_structp png_ptr,
  184397. png_int_32 x_offset, png_int_32 y_offset, int unit_type));
  184398. #endif
  184399. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  184400. PNG_EXTERN void png_write_pCAL PNGARG((png_structp png_ptr, png_charp purpose,
  184401. png_int_32 X0, png_int_32 X1, int type, int nparams,
  184402. png_charp units, png_charpp params));
  184403. #endif
  184404. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  184405. PNG_EXTERN void png_write_pHYs PNGARG((png_structp png_ptr,
  184406. png_uint_32 x_pixels_per_unit, png_uint_32 y_pixels_per_unit,
  184407. int unit_type));
  184408. #endif
  184409. #if defined(PNG_WRITE_tIME_SUPPORTED)
  184410. PNG_EXTERN void png_write_tIME PNGARG((png_structp png_ptr,
  184411. png_timep mod_time));
  184412. #endif
  184413. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  184414. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  184415. PNG_EXTERN void png_write_sCAL PNGARG((png_structp png_ptr,
  184416. int unit, double width, double height));
  184417. #else
  184418. #ifdef PNG_FIXED_POINT_SUPPORTED
  184419. PNG_EXTERN void png_write_sCAL_s PNGARG((png_structp png_ptr,
  184420. int unit, png_charp width, png_charp height));
  184421. #endif
  184422. #endif
  184423. #endif
  184424. /* Called when finished processing a row of data */
  184425. PNG_EXTERN void png_write_finish_row PNGARG((png_structp png_ptr));
  184426. /* Internal use only. Called before first row of data */
  184427. PNG_EXTERN void png_write_start_row PNGARG((png_structp png_ptr));
  184428. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184429. PNG_EXTERN void png_build_gamma_table PNGARG((png_structp png_ptr));
  184430. #endif
  184431. /* combine a row of data, dealing with alpha, etc. if requested */
  184432. PNG_EXTERN void png_combine_row PNGARG((png_structp png_ptr, png_bytep row,
  184433. int mask));
  184434. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  184435. /* expand an interlaced row */
  184436. /* OLD pre-1.0.9 interface:
  184437. PNG_EXTERN void png_do_read_interlace PNGARG((png_row_infop row_info,
  184438. png_bytep row, int pass, png_uint_32 transformations));
  184439. */
  184440. PNG_EXTERN void png_do_read_interlace PNGARG((png_structp png_ptr));
  184441. #endif
  184442. /* GRR TO DO (2.0 or whenever): simplify other internal calling interfaces */
  184443. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  184444. /* grab pixels out of a row for an interlaced pass */
  184445. PNG_EXTERN void png_do_write_interlace PNGARG((png_row_infop row_info,
  184446. png_bytep row, int pass));
  184447. #endif
  184448. /* unfilter a row */
  184449. PNG_EXTERN void png_read_filter_row PNGARG((png_structp png_ptr,
  184450. png_row_infop row_info, png_bytep row, png_bytep prev_row, int filter));
  184451. /* Choose the best filter to use and filter the row data */
  184452. PNG_EXTERN void png_write_find_filter PNGARG((png_structp png_ptr,
  184453. png_row_infop row_info));
  184454. /* Write out the filtered row. */
  184455. PNG_EXTERN void png_write_filtered_row PNGARG((png_structp png_ptr,
  184456. png_bytep filtered_row));
  184457. /* finish a row while reading, dealing with interlacing passes, etc. */
  184458. PNG_EXTERN void png_read_finish_row PNGARG((png_structp png_ptr));
  184459. /* initialize the row buffers, etc. */
  184460. PNG_EXTERN void png_read_start_row PNGARG((png_structp png_ptr));
  184461. /* optional call to update the users info structure */
  184462. PNG_EXTERN void png_read_transform_info PNGARG((png_structp png_ptr,
  184463. png_infop info_ptr));
  184464. /* these are the functions that do the transformations */
  184465. #if defined(PNG_READ_FILLER_SUPPORTED)
  184466. PNG_EXTERN void png_do_read_filler PNGARG((png_row_infop row_info,
  184467. png_bytep row, png_uint_32 filler, png_uint_32 flags));
  184468. #endif
  184469. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  184470. PNG_EXTERN void png_do_read_swap_alpha PNGARG((png_row_infop row_info,
  184471. png_bytep row));
  184472. #endif
  184473. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  184474. PNG_EXTERN void png_do_write_swap_alpha PNGARG((png_row_infop row_info,
  184475. png_bytep row));
  184476. #endif
  184477. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  184478. PNG_EXTERN void png_do_read_invert_alpha PNGARG((png_row_infop row_info,
  184479. png_bytep row));
  184480. #endif
  184481. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  184482. PNG_EXTERN void png_do_write_invert_alpha PNGARG((png_row_infop row_info,
  184483. png_bytep row));
  184484. #endif
  184485. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  184486. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  184487. PNG_EXTERN void png_do_strip_filler PNGARG((png_row_infop row_info,
  184488. png_bytep row, png_uint_32 flags));
  184489. #endif
  184490. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  184491. PNG_EXTERN void png_do_swap PNGARG((png_row_infop row_info, png_bytep row));
  184492. #endif
  184493. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  184494. PNG_EXTERN void png_do_packswap PNGARG((png_row_infop row_info, png_bytep row));
  184495. #endif
  184496. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  184497. PNG_EXTERN int png_do_rgb_to_gray PNGARG((png_structp png_ptr, png_row_infop
  184498. row_info, png_bytep row));
  184499. #endif
  184500. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  184501. PNG_EXTERN void png_do_gray_to_rgb PNGARG((png_row_infop row_info,
  184502. png_bytep row));
  184503. #endif
  184504. #if defined(PNG_READ_PACK_SUPPORTED)
  184505. PNG_EXTERN void png_do_unpack PNGARG((png_row_infop row_info, png_bytep row));
  184506. #endif
  184507. #if defined(PNG_READ_SHIFT_SUPPORTED)
  184508. PNG_EXTERN void png_do_unshift PNGARG((png_row_infop row_info, png_bytep row,
  184509. png_color_8p sig_bits));
  184510. #endif
  184511. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  184512. PNG_EXTERN void png_do_invert PNGARG((png_row_infop row_info, png_bytep row));
  184513. #endif
  184514. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  184515. PNG_EXTERN void png_do_chop PNGARG((png_row_infop row_info, png_bytep row));
  184516. #endif
  184517. #if defined(PNG_READ_DITHER_SUPPORTED)
  184518. PNG_EXTERN void png_do_dither PNGARG((png_row_infop row_info,
  184519. png_bytep row, png_bytep palette_lookup, png_bytep dither_lookup));
  184520. # if defined(PNG_CORRECT_PALETTE_SUPPORTED)
  184521. PNG_EXTERN void png_correct_palette PNGARG((png_structp png_ptr,
  184522. png_colorp palette, int num_palette));
  184523. # endif
  184524. #endif
  184525. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  184526. PNG_EXTERN void png_do_bgr PNGARG((png_row_infop row_info, png_bytep row));
  184527. #endif
  184528. #if defined(PNG_WRITE_PACK_SUPPORTED)
  184529. PNG_EXTERN void png_do_pack PNGARG((png_row_infop row_info,
  184530. png_bytep row, png_uint_32 bit_depth));
  184531. #endif
  184532. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  184533. PNG_EXTERN void png_do_shift PNGARG((png_row_infop row_info, png_bytep row,
  184534. png_color_8p bit_depth));
  184535. #endif
  184536. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  184537. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184538. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  184539. png_color_16p trans_values, png_color_16p background,
  184540. png_color_16p background_1,
  184541. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  184542. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  184543. png_uint_16pp gamma_16_to_1, int gamma_shift));
  184544. #else
  184545. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  184546. png_color_16p trans_values, png_color_16p background));
  184547. #endif
  184548. #endif
  184549. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184550. PNG_EXTERN void png_do_gamma PNGARG((png_row_infop row_info, png_bytep row,
  184551. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  184552. int gamma_shift));
  184553. #endif
  184554. #if defined(PNG_READ_EXPAND_SUPPORTED)
  184555. PNG_EXTERN void png_do_expand_palette PNGARG((png_row_infop row_info,
  184556. png_bytep row, png_colorp palette, png_bytep trans, int num_trans));
  184557. PNG_EXTERN void png_do_expand PNGARG((png_row_infop row_info,
  184558. png_bytep row, png_color_16p trans_value));
  184559. #endif
  184560. /* The following decodes the appropriate chunks, and does error correction,
  184561. * then calls the appropriate callback for the chunk if it is valid.
  184562. */
  184563. /* decode the IHDR chunk */
  184564. PNG_EXTERN void png_handle_IHDR PNGARG((png_structp png_ptr, png_infop info_ptr,
  184565. png_uint_32 length));
  184566. PNG_EXTERN void png_handle_PLTE PNGARG((png_structp png_ptr, png_infop info_ptr,
  184567. png_uint_32 length));
  184568. PNG_EXTERN void png_handle_IEND PNGARG((png_structp png_ptr, png_infop info_ptr,
  184569. png_uint_32 length));
  184570. #if defined(PNG_READ_bKGD_SUPPORTED)
  184571. PNG_EXTERN void png_handle_bKGD PNGARG((png_structp png_ptr, png_infop info_ptr,
  184572. png_uint_32 length));
  184573. #endif
  184574. #if defined(PNG_READ_cHRM_SUPPORTED)
  184575. PNG_EXTERN void png_handle_cHRM PNGARG((png_structp png_ptr, png_infop info_ptr,
  184576. png_uint_32 length));
  184577. #endif
  184578. #if defined(PNG_READ_gAMA_SUPPORTED)
  184579. PNG_EXTERN void png_handle_gAMA PNGARG((png_structp png_ptr, png_infop info_ptr,
  184580. png_uint_32 length));
  184581. #endif
  184582. #if defined(PNG_READ_hIST_SUPPORTED)
  184583. PNG_EXTERN void png_handle_hIST PNGARG((png_structp png_ptr, png_infop info_ptr,
  184584. png_uint_32 length));
  184585. #endif
  184586. #if defined(PNG_READ_iCCP_SUPPORTED)
  184587. extern void png_handle_iCCP PNGARG((png_structp png_ptr, png_infop info_ptr,
  184588. png_uint_32 length));
  184589. #endif /* PNG_READ_iCCP_SUPPORTED */
  184590. #if defined(PNG_READ_iTXt_SUPPORTED)
  184591. PNG_EXTERN void png_handle_iTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  184592. png_uint_32 length));
  184593. #endif
  184594. #if defined(PNG_READ_oFFs_SUPPORTED)
  184595. PNG_EXTERN void png_handle_oFFs PNGARG((png_structp png_ptr, png_infop info_ptr,
  184596. png_uint_32 length));
  184597. #endif
  184598. #if defined(PNG_READ_pCAL_SUPPORTED)
  184599. PNG_EXTERN void png_handle_pCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  184600. png_uint_32 length));
  184601. #endif
  184602. #if defined(PNG_READ_pHYs_SUPPORTED)
  184603. PNG_EXTERN void png_handle_pHYs PNGARG((png_structp png_ptr, png_infop info_ptr,
  184604. png_uint_32 length));
  184605. #endif
  184606. #if defined(PNG_READ_sBIT_SUPPORTED)
  184607. PNG_EXTERN void png_handle_sBIT PNGARG((png_structp png_ptr, png_infop info_ptr,
  184608. png_uint_32 length));
  184609. #endif
  184610. #if defined(PNG_READ_sCAL_SUPPORTED)
  184611. PNG_EXTERN void png_handle_sCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  184612. png_uint_32 length));
  184613. #endif
  184614. #if defined(PNG_READ_sPLT_SUPPORTED)
  184615. extern void png_handle_sPLT PNGARG((png_structp png_ptr, png_infop info_ptr,
  184616. png_uint_32 length));
  184617. #endif /* PNG_READ_sPLT_SUPPORTED */
  184618. #if defined(PNG_READ_sRGB_SUPPORTED)
  184619. PNG_EXTERN void png_handle_sRGB PNGARG((png_structp png_ptr, png_infop info_ptr,
  184620. png_uint_32 length));
  184621. #endif
  184622. #if defined(PNG_READ_tEXt_SUPPORTED)
  184623. PNG_EXTERN void png_handle_tEXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  184624. png_uint_32 length));
  184625. #endif
  184626. #if defined(PNG_READ_tIME_SUPPORTED)
  184627. PNG_EXTERN void png_handle_tIME PNGARG((png_structp png_ptr, png_infop info_ptr,
  184628. png_uint_32 length));
  184629. #endif
  184630. #if defined(PNG_READ_tRNS_SUPPORTED)
  184631. PNG_EXTERN void png_handle_tRNS PNGARG((png_structp png_ptr, png_infop info_ptr,
  184632. png_uint_32 length));
  184633. #endif
  184634. #if defined(PNG_READ_zTXt_SUPPORTED)
  184635. PNG_EXTERN void png_handle_zTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  184636. png_uint_32 length));
  184637. #endif
  184638. PNG_EXTERN void png_handle_unknown PNGARG((png_structp png_ptr,
  184639. png_infop info_ptr, png_uint_32 length));
  184640. PNG_EXTERN void png_check_chunk_name PNGARG((png_structp png_ptr,
  184641. png_bytep chunk_name));
  184642. /* handle the transformations for reading and writing */
  184643. PNG_EXTERN void png_do_read_transformations PNGARG((png_structp png_ptr));
  184644. PNG_EXTERN void png_do_write_transformations PNGARG((png_structp png_ptr));
  184645. PNG_EXTERN void png_init_read_transformations PNGARG((png_structp png_ptr));
  184646. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  184647. PNG_EXTERN void png_push_read_chunk PNGARG((png_structp png_ptr,
  184648. png_infop info_ptr));
  184649. PNG_EXTERN void png_push_read_sig PNGARG((png_structp png_ptr,
  184650. png_infop info_ptr));
  184651. PNG_EXTERN void png_push_check_crc PNGARG((png_structp png_ptr));
  184652. PNG_EXTERN void png_push_crc_skip PNGARG((png_structp png_ptr,
  184653. png_uint_32 length));
  184654. PNG_EXTERN void png_push_crc_finish PNGARG((png_structp png_ptr));
  184655. PNG_EXTERN void png_push_save_buffer PNGARG((png_structp png_ptr));
  184656. PNG_EXTERN void png_push_restore_buffer PNGARG((png_structp png_ptr,
  184657. png_bytep buffer, png_size_t buffer_length));
  184658. PNG_EXTERN void png_push_read_IDAT PNGARG((png_structp png_ptr));
  184659. PNG_EXTERN void png_process_IDAT_data PNGARG((png_structp png_ptr,
  184660. png_bytep buffer, png_size_t buffer_length));
  184661. PNG_EXTERN void png_push_process_row PNGARG((png_structp png_ptr));
  184662. PNG_EXTERN void png_push_handle_unknown PNGARG((png_structp png_ptr,
  184663. png_infop info_ptr, png_uint_32 length));
  184664. PNG_EXTERN void png_push_have_info PNGARG((png_structp png_ptr,
  184665. png_infop info_ptr));
  184666. PNG_EXTERN void png_push_have_end PNGARG((png_structp png_ptr,
  184667. png_infop info_ptr));
  184668. PNG_EXTERN void png_push_have_row PNGARG((png_structp png_ptr, png_bytep row));
  184669. PNG_EXTERN void png_push_read_end PNGARG((png_structp png_ptr,
  184670. png_infop info_ptr));
  184671. PNG_EXTERN void png_process_some_data PNGARG((png_structp png_ptr,
  184672. png_infop info_ptr));
  184673. PNG_EXTERN void png_read_push_finish_row PNGARG((png_structp png_ptr));
  184674. #if defined(PNG_READ_tEXt_SUPPORTED)
  184675. PNG_EXTERN void png_push_handle_tEXt PNGARG((png_structp png_ptr,
  184676. png_infop info_ptr, png_uint_32 length));
  184677. PNG_EXTERN void png_push_read_tEXt PNGARG((png_structp png_ptr,
  184678. png_infop info_ptr));
  184679. #endif
  184680. #if defined(PNG_READ_zTXt_SUPPORTED)
  184681. PNG_EXTERN void png_push_handle_zTXt PNGARG((png_structp png_ptr,
  184682. png_infop info_ptr, png_uint_32 length));
  184683. PNG_EXTERN void png_push_read_zTXt PNGARG((png_structp png_ptr,
  184684. png_infop info_ptr));
  184685. #endif
  184686. #if defined(PNG_READ_iTXt_SUPPORTED)
  184687. PNG_EXTERN void png_push_handle_iTXt PNGARG((png_structp png_ptr,
  184688. png_infop info_ptr, png_uint_32 length));
  184689. PNG_EXTERN void png_push_read_iTXt PNGARG((png_structp png_ptr,
  184690. png_infop info_ptr));
  184691. #endif
  184692. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  184693. #ifdef PNG_MNG_FEATURES_SUPPORTED
  184694. PNG_EXTERN void png_do_read_intrapixel PNGARG((png_row_infop row_info,
  184695. png_bytep row));
  184696. PNG_EXTERN void png_do_write_intrapixel PNGARG((png_row_infop row_info,
  184697. png_bytep row));
  184698. #endif
  184699. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  184700. #if defined(PNG_MMX_CODE_SUPPORTED)
  184701. /* png.c */ /* PRIVATE */
  184702. PNG_EXTERN void png_init_mmx_flags PNGARG((png_structp png_ptr));
  184703. #endif
  184704. #endif
  184705. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  184706. PNG_EXTERN png_uint_32 png_get_pixels_per_inch PNGARG((png_structp png_ptr,
  184707. png_infop info_ptr));
  184708. PNG_EXTERN png_uint_32 png_get_x_pixels_per_inch PNGARG((png_structp png_ptr,
  184709. png_infop info_ptr));
  184710. PNG_EXTERN png_uint_32 png_get_y_pixels_per_inch PNGARG((png_structp png_ptr,
  184711. png_infop info_ptr));
  184712. PNG_EXTERN float png_get_x_offset_inches PNGARG((png_structp png_ptr,
  184713. png_infop info_ptr));
  184714. PNG_EXTERN float png_get_y_offset_inches PNGARG((png_structp png_ptr,
  184715. png_infop info_ptr));
  184716. #if defined(PNG_pHYs_SUPPORTED)
  184717. PNG_EXTERN png_uint_32 png_get_pHYs_dpi PNGARG((png_structp png_ptr,
  184718. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  184719. #endif /* PNG_pHYs_SUPPORTED */
  184720. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  184721. /* Maintainer: Put new private prototypes here ^ and in libpngpf.3 */
  184722. #endif /* PNG_INTERNAL */
  184723. #ifdef __cplusplus
  184724. //}
  184725. #endif
  184726. #endif /* PNG_VERSION_INFO_ONLY */
  184727. /* do not put anything past this line */
  184728. #endif /* PNG_H */
  184729. /*** End of inlined file: png.h ***/
  184730. #define PNG_NO_EXTERN
  184731. /*** Start of inlined file: png.c ***/
  184732. /* png.c - location for general purpose libpng functions
  184733. *
  184734. * Last changed in libpng 1.2.21 [October 4, 2007]
  184735. * For conditions of distribution and use, see copyright notice in png.h
  184736. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  184737. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  184738. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  184739. */
  184740. #define PNG_INTERNAL
  184741. #define PNG_NO_EXTERN
  184742. /* Generate a compiler error if there is an old png.h in the search path. */
  184743. typedef version_1_2_21 Your_png_h_is_not_version_1_2_21;
  184744. /* Version information for C files. This had better match the version
  184745. * string defined in png.h. */
  184746. #ifdef PNG_USE_GLOBAL_ARRAYS
  184747. /* png_libpng_ver was changed to a function in version 1.0.5c */
  184748. PNG_CONST char png_libpng_ver[18] = PNG_LIBPNG_VER_STRING;
  184749. #ifdef PNG_READ_SUPPORTED
  184750. /* png_sig was changed to a function in version 1.0.5c */
  184751. /* Place to hold the signature string for a PNG file. */
  184752. PNG_CONST png_byte FARDATA png_sig[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  184753. #endif /* PNG_READ_SUPPORTED */
  184754. /* Invoke global declarations for constant strings for known chunk types */
  184755. PNG_IHDR;
  184756. PNG_IDAT;
  184757. PNG_IEND;
  184758. PNG_PLTE;
  184759. PNG_bKGD;
  184760. PNG_cHRM;
  184761. PNG_gAMA;
  184762. PNG_hIST;
  184763. PNG_iCCP;
  184764. PNG_iTXt;
  184765. PNG_oFFs;
  184766. PNG_pCAL;
  184767. PNG_sCAL;
  184768. PNG_pHYs;
  184769. PNG_sBIT;
  184770. PNG_sPLT;
  184771. PNG_sRGB;
  184772. PNG_tEXt;
  184773. PNG_tIME;
  184774. PNG_tRNS;
  184775. PNG_zTXt;
  184776. #ifdef PNG_READ_SUPPORTED
  184777. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  184778. /* start of interlace block */
  184779. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  184780. /* offset to next interlace block */
  184781. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  184782. /* start of interlace block in the y direction */
  184783. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  184784. /* offset to next interlace block in the y direction */
  184785. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  184786. /* Height of interlace block. This is not currently used - if you need
  184787. * it, uncomment it here and in png.h
  184788. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  184789. */
  184790. /* Mask to determine which pixels are valid in a pass */
  184791. PNG_CONST int FARDATA png_pass_mask[] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  184792. /* Mask to determine which pixels to overwrite while displaying */
  184793. PNG_CONST int FARDATA png_pass_dsp_mask[]
  184794. = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  184795. #endif /* PNG_READ_SUPPORTED */
  184796. #endif /* PNG_USE_GLOBAL_ARRAYS */
  184797. /* Tells libpng that we have already handled the first "num_bytes" bytes
  184798. * of the PNG file signature. If the PNG data is embedded into another
  184799. * stream we can set num_bytes = 8 so that libpng will not attempt to read
  184800. * or write any of the magic bytes before it starts on the IHDR.
  184801. */
  184802. #ifdef PNG_READ_SUPPORTED
  184803. void PNGAPI
  184804. png_set_sig_bytes(png_structp png_ptr, int num_bytes)
  184805. {
  184806. if(png_ptr == NULL) return;
  184807. png_debug(1, "in png_set_sig_bytes\n");
  184808. if (num_bytes > 8)
  184809. png_error(png_ptr, "Too many bytes for PNG signature.");
  184810. png_ptr->sig_bytes = (png_byte)(num_bytes < 0 ? 0 : num_bytes);
  184811. }
  184812. /* Checks whether the supplied bytes match the PNG signature. We allow
  184813. * checking less than the full 8-byte signature so that those apps that
  184814. * already read the first few bytes of a file to determine the file type
  184815. * can simply check the remaining bytes for extra assurance. Returns
  184816. * an integer less than, equal to, or greater than zero if sig is found,
  184817. * respectively, to be less than, to match, or be greater than the correct
  184818. * PNG signature (this is the same behaviour as strcmp, memcmp, etc).
  184819. */
  184820. int PNGAPI
  184821. png_sig_cmp(png_bytep sig, png_size_t start, png_size_t num_to_check)
  184822. {
  184823. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  184824. if (num_to_check > 8)
  184825. num_to_check = 8;
  184826. else if (num_to_check < 1)
  184827. return (-1);
  184828. if (start > 7)
  184829. return (-1);
  184830. if (start + num_to_check > 8)
  184831. num_to_check = 8 - start;
  184832. return ((int)(png_memcmp(&sig[start], &png_signature[start], num_to_check)));
  184833. }
  184834. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  184835. /* (Obsolete) function to check signature bytes. It does not allow one
  184836. * to check a partial signature. This function might be removed in the
  184837. * future - use png_sig_cmp(). Returns true (nonzero) if the file is PNG.
  184838. */
  184839. int PNGAPI
  184840. png_check_sig(png_bytep sig, int num)
  184841. {
  184842. return ((int)!png_sig_cmp(sig, (png_size_t)0, (png_size_t)num));
  184843. }
  184844. #endif
  184845. #endif /* PNG_READ_SUPPORTED */
  184846. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184847. /* Function to allocate memory for zlib and clear it to 0. */
  184848. #ifdef PNG_1_0_X
  184849. voidpf PNGAPI
  184850. #else
  184851. voidpf /* private */
  184852. #endif
  184853. png_zalloc(voidpf png_ptr, uInt items, uInt size)
  184854. {
  184855. png_voidp ptr;
  184856. png_structp p=(png_structp)png_ptr;
  184857. png_uint_32 save_flags=p->flags;
  184858. png_uint_32 num_bytes;
  184859. if(png_ptr == NULL) return (NULL);
  184860. if (items > PNG_UINT_32_MAX/size)
  184861. {
  184862. png_warning (p, "Potential overflow in png_zalloc()");
  184863. return (NULL);
  184864. }
  184865. num_bytes = (png_uint_32)items * size;
  184866. p->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  184867. ptr = (png_voidp)png_malloc((png_structp)png_ptr, num_bytes);
  184868. p->flags=save_flags;
  184869. #if defined(PNG_1_0_X) && !defined(PNG_NO_ZALLOC_ZERO)
  184870. if (ptr == NULL)
  184871. return ((voidpf)ptr);
  184872. if (num_bytes > (png_uint_32)0x8000L)
  184873. {
  184874. png_memset(ptr, 0, (png_size_t)0x8000L);
  184875. png_memset((png_bytep)ptr + (png_size_t)0x8000L, 0,
  184876. (png_size_t)(num_bytes - (png_uint_32)0x8000L));
  184877. }
  184878. else
  184879. {
  184880. png_memset(ptr, 0, (png_size_t)num_bytes);
  184881. }
  184882. #endif
  184883. return ((voidpf)ptr);
  184884. }
  184885. /* function to free memory for zlib */
  184886. #ifdef PNG_1_0_X
  184887. void PNGAPI
  184888. #else
  184889. void /* private */
  184890. #endif
  184891. png_zfree(voidpf png_ptr, voidpf ptr)
  184892. {
  184893. png_free((png_structp)png_ptr, (png_voidp)ptr);
  184894. }
  184895. /* Reset the CRC variable to 32 bits of 1's. Care must be taken
  184896. * in case CRC is > 32 bits to leave the top bits 0.
  184897. */
  184898. void /* PRIVATE */
  184899. png_reset_crc(png_structp png_ptr)
  184900. {
  184901. png_ptr->crc = crc32(0, Z_NULL, 0);
  184902. }
  184903. /* Calculate the CRC over a section of data. We can only pass as
  184904. * much data to this routine as the largest single buffer size. We
  184905. * also check that this data will actually be used before going to the
  184906. * trouble of calculating it.
  184907. */
  184908. void /* PRIVATE */
  184909. png_calculate_crc(png_structp png_ptr, png_bytep ptr, png_size_t length)
  184910. {
  184911. int need_crc = 1;
  184912. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  184913. {
  184914. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  184915. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  184916. need_crc = 0;
  184917. }
  184918. else /* critical */
  184919. {
  184920. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  184921. need_crc = 0;
  184922. }
  184923. if (need_crc)
  184924. png_ptr->crc = crc32(png_ptr->crc, ptr, (uInt)length);
  184925. }
  184926. /* Allocate the memory for an info_struct for the application. We don't
  184927. * really need the png_ptr, but it could potentially be useful in the
  184928. * future. This should be used in favour of malloc(png_sizeof(png_info))
  184929. * and png_info_init() so that applications that want to use a shared
  184930. * libpng don't have to be recompiled if png_info changes size.
  184931. */
  184932. png_infop PNGAPI
  184933. png_create_info_struct(png_structp png_ptr)
  184934. {
  184935. png_infop info_ptr;
  184936. png_debug(1, "in png_create_info_struct\n");
  184937. if(png_ptr == NULL) return (NULL);
  184938. #ifdef PNG_USER_MEM_SUPPORTED
  184939. info_ptr = (png_infop)png_create_struct_2(PNG_STRUCT_INFO,
  184940. png_ptr->malloc_fn, png_ptr->mem_ptr);
  184941. #else
  184942. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  184943. #endif
  184944. if (info_ptr != NULL)
  184945. png_info_init_3(&info_ptr, png_sizeof(png_info));
  184946. return (info_ptr);
  184947. }
  184948. /* This function frees the memory associated with a single info struct.
  184949. * Normally, one would use either png_destroy_read_struct() or
  184950. * png_destroy_write_struct() to free an info struct, but this may be
  184951. * useful for some applications.
  184952. */
  184953. void PNGAPI
  184954. png_destroy_info_struct(png_structp png_ptr, png_infopp info_ptr_ptr)
  184955. {
  184956. png_infop info_ptr = NULL;
  184957. if(png_ptr == NULL) return;
  184958. png_debug(1, "in png_destroy_info_struct\n");
  184959. if (info_ptr_ptr != NULL)
  184960. info_ptr = *info_ptr_ptr;
  184961. if (info_ptr != NULL)
  184962. {
  184963. png_info_destroy(png_ptr, info_ptr);
  184964. #ifdef PNG_USER_MEM_SUPPORTED
  184965. png_destroy_struct_2((png_voidp)info_ptr, png_ptr->free_fn,
  184966. png_ptr->mem_ptr);
  184967. #else
  184968. png_destroy_struct((png_voidp)info_ptr);
  184969. #endif
  184970. *info_ptr_ptr = NULL;
  184971. }
  184972. }
  184973. /* Initialize the info structure. This is now an internal function (0.89)
  184974. * and applications using it are urged to use png_create_info_struct()
  184975. * instead.
  184976. */
  184977. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  184978. #undef png_info_init
  184979. void PNGAPI
  184980. png_info_init(png_infop info_ptr)
  184981. {
  184982. /* We only come here via pre-1.0.12-compiled applications */
  184983. png_info_init_3(&info_ptr, 0);
  184984. }
  184985. #endif
  184986. void PNGAPI
  184987. png_info_init_3(png_infopp ptr_ptr, png_size_t png_info_struct_size)
  184988. {
  184989. png_infop info_ptr = *ptr_ptr;
  184990. if(info_ptr == NULL) return;
  184991. png_debug(1, "in png_info_init_3\n");
  184992. if(png_sizeof(png_info) > png_info_struct_size)
  184993. {
  184994. png_destroy_struct(info_ptr);
  184995. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  184996. *ptr_ptr = info_ptr;
  184997. }
  184998. /* set everything to 0 */
  184999. png_memset(info_ptr, 0, png_sizeof (png_info));
  185000. }
  185001. #ifdef PNG_FREE_ME_SUPPORTED
  185002. void PNGAPI
  185003. png_data_freer(png_structp png_ptr, png_infop info_ptr,
  185004. int freer, png_uint_32 mask)
  185005. {
  185006. png_debug(1, "in png_data_freer\n");
  185007. if (png_ptr == NULL || info_ptr == NULL)
  185008. return;
  185009. if(freer == PNG_DESTROY_WILL_FREE_DATA)
  185010. info_ptr->free_me |= mask;
  185011. else if(freer == PNG_USER_WILL_FREE_DATA)
  185012. info_ptr->free_me &= ~mask;
  185013. else
  185014. png_warning(png_ptr,
  185015. "Unknown freer parameter in png_data_freer.");
  185016. }
  185017. #endif
  185018. void PNGAPI
  185019. png_free_data(png_structp png_ptr, png_infop info_ptr, png_uint_32 mask,
  185020. int num)
  185021. {
  185022. png_debug(1, "in png_free_data\n");
  185023. if (png_ptr == NULL || info_ptr == NULL)
  185024. return;
  185025. #if defined(PNG_TEXT_SUPPORTED)
  185026. /* free text item num or (if num == -1) all text items */
  185027. #ifdef PNG_FREE_ME_SUPPORTED
  185028. if ((mask & PNG_FREE_TEXT) & info_ptr->free_me)
  185029. #else
  185030. if (mask & PNG_FREE_TEXT)
  185031. #endif
  185032. {
  185033. if (num != -1)
  185034. {
  185035. if (info_ptr->text && info_ptr->text[num].key)
  185036. {
  185037. png_free(png_ptr, info_ptr->text[num].key);
  185038. info_ptr->text[num].key = NULL;
  185039. }
  185040. }
  185041. else
  185042. {
  185043. int i;
  185044. for (i = 0; i < info_ptr->num_text; i++)
  185045. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, i);
  185046. png_free(png_ptr, info_ptr->text);
  185047. info_ptr->text = NULL;
  185048. info_ptr->num_text=0;
  185049. }
  185050. }
  185051. #endif
  185052. #if defined(PNG_tRNS_SUPPORTED)
  185053. /* free any tRNS entry */
  185054. #ifdef PNG_FREE_ME_SUPPORTED
  185055. if ((mask & PNG_FREE_TRNS) & info_ptr->free_me)
  185056. #else
  185057. if ((mask & PNG_FREE_TRNS) && (png_ptr->flags & PNG_FLAG_FREE_TRNS))
  185058. #endif
  185059. {
  185060. png_free(png_ptr, info_ptr->trans);
  185061. info_ptr->valid &= ~PNG_INFO_tRNS;
  185062. #ifndef PNG_FREE_ME_SUPPORTED
  185063. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  185064. #endif
  185065. info_ptr->trans = NULL;
  185066. }
  185067. #endif
  185068. #if defined(PNG_sCAL_SUPPORTED)
  185069. /* free any sCAL entry */
  185070. #ifdef PNG_FREE_ME_SUPPORTED
  185071. if ((mask & PNG_FREE_SCAL) & info_ptr->free_me)
  185072. #else
  185073. if (mask & PNG_FREE_SCAL)
  185074. #endif
  185075. {
  185076. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  185077. png_free(png_ptr, info_ptr->scal_s_width);
  185078. png_free(png_ptr, info_ptr->scal_s_height);
  185079. info_ptr->scal_s_width = NULL;
  185080. info_ptr->scal_s_height = NULL;
  185081. #endif
  185082. info_ptr->valid &= ~PNG_INFO_sCAL;
  185083. }
  185084. #endif
  185085. #if defined(PNG_pCAL_SUPPORTED)
  185086. /* free any pCAL entry */
  185087. #ifdef PNG_FREE_ME_SUPPORTED
  185088. if ((mask & PNG_FREE_PCAL) & info_ptr->free_me)
  185089. #else
  185090. if (mask & PNG_FREE_PCAL)
  185091. #endif
  185092. {
  185093. png_free(png_ptr, info_ptr->pcal_purpose);
  185094. png_free(png_ptr, info_ptr->pcal_units);
  185095. info_ptr->pcal_purpose = NULL;
  185096. info_ptr->pcal_units = NULL;
  185097. if (info_ptr->pcal_params != NULL)
  185098. {
  185099. int i;
  185100. for (i = 0; i < (int)info_ptr->pcal_nparams; i++)
  185101. {
  185102. png_free(png_ptr, info_ptr->pcal_params[i]);
  185103. info_ptr->pcal_params[i]=NULL;
  185104. }
  185105. png_free(png_ptr, info_ptr->pcal_params);
  185106. info_ptr->pcal_params = NULL;
  185107. }
  185108. info_ptr->valid &= ~PNG_INFO_pCAL;
  185109. }
  185110. #endif
  185111. #if defined(PNG_iCCP_SUPPORTED)
  185112. /* free any iCCP entry */
  185113. #ifdef PNG_FREE_ME_SUPPORTED
  185114. if ((mask & PNG_FREE_ICCP) & info_ptr->free_me)
  185115. #else
  185116. if (mask & PNG_FREE_ICCP)
  185117. #endif
  185118. {
  185119. png_free(png_ptr, info_ptr->iccp_name);
  185120. png_free(png_ptr, info_ptr->iccp_profile);
  185121. info_ptr->iccp_name = NULL;
  185122. info_ptr->iccp_profile = NULL;
  185123. info_ptr->valid &= ~PNG_INFO_iCCP;
  185124. }
  185125. #endif
  185126. #if defined(PNG_sPLT_SUPPORTED)
  185127. /* free a given sPLT entry, or (if num == -1) all sPLT entries */
  185128. #ifdef PNG_FREE_ME_SUPPORTED
  185129. if ((mask & PNG_FREE_SPLT) & info_ptr->free_me)
  185130. #else
  185131. if (mask & PNG_FREE_SPLT)
  185132. #endif
  185133. {
  185134. if (num != -1)
  185135. {
  185136. if(info_ptr->splt_palettes)
  185137. {
  185138. png_free(png_ptr, info_ptr->splt_palettes[num].name);
  185139. png_free(png_ptr, info_ptr->splt_palettes[num].entries);
  185140. info_ptr->splt_palettes[num].name = NULL;
  185141. info_ptr->splt_palettes[num].entries = NULL;
  185142. }
  185143. }
  185144. else
  185145. {
  185146. if(info_ptr->splt_palettes_num)
  185147. {
  185148. int i;
  185149. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  185150. png_free_data(png_ptr, info_ptr, PNG_FREE_SPLT, i);
  185151. png_free(png_ptr, info_ptr->splt_palettes);
  185152. info_ptr->splt_palettes = NULL;
  185153. info_ptr->splt_palettes_num = 0;
  185154. }
  185155. info_ptr->valid &= ~PNG_INFO_sPLT;
  185156. }
  185157. }
  185158. #endif
  185159. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  185160. if(png_ptr->unknown_chunk.data)
  185161. {
  185162. png_free(png_ptr, png_ptr->unknown_chunk.data);
  185163. png_ptr->unknown_chunk.data = NULL;
  185164. }
  185165. #ifdef PNG_FREE_ME_SUPPORTED
  185166. if ((mask & PNG_FREE_UNKN) & info_ptr->free_me)
  185167. #else
  185168. if (mask & PNG_FREE_UNKN)
  185169. #endif
  185170. {
  185171. if (num != -1)
  185172. {
  185173. if(info_ptr->unknown_chunks)
  185174. {
  185175. png_free(png_ptr, info_ptr->unknown_chunks[num].data);
  185176. info_ptr->unknown_chunks[num].data = NULL;
  185177. }
  185178. }
  185179. else
  185180. {
  185181. int i;
  185182. if(info_ptr->unknown_chunks_num)
  185183. {
  185184. for (i = 0; i < (int)info_ptr->unknown_chunks_num; i++)
  185185. png_free_data(png_ptr, info_ptr, PNG_FREE_UNKN, i);
  185186. png_free(png_ptr, info_ptr->unknown_chunks);
  185187. info_ptr->unknown_chunks = NULL;
  185188. info_ptr->unknown_chunks_num = 0;
  185189. }
  185190. }
  185191. }
  185192. #endif
  185193. #if defined(PNG_hIST_SUPPORTED)
  185194. /* free any hIST entry */
  185195. #ifdef PNG_FREE_ME_SUPPORTED
  185196. if ((mask & PNG_FREE_HIST) & info_ptr->free_me)
  185197. #else
  185198. if ((mask & PNG_FREE_HIST) && (png_ptr->flags & PNG_FLAG_FREE_HIST))
  185199. #endif
  185200. {
  185201. png_free(png_ptr, info_ptr->hist);
  185202. info_ptr->hist = NULL;
  185203. info_ptr->valid &= ~PNG_INFO_hIST;
  185204. #ifndef PNG_FREE_ME_SUPPORTED
  185205. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  185206. #endif
  185207. }
  185208. #endif
  185209. /* free any PLTE entry that was internally allocated */
  185210. #ifdef PNG_FREE_ME_SUPPORTED
  185211. if ((mask & PNG_FREE_PLTE) & info_ptr->free_me)
  185212. #else
  185213. if ((mask & PNG_FREE_PLTE) && (png_ptr->flags & PNG_FLAG_FREE_PLTE))
  185214. #endif
  185215. {
  185216. png_zfree(png_ptr, info_ptr->palette);
  185217. info_ptr->palette = NULL;
  185218. info_ptr->valid &= ~PNG_INFO_PLTE;
  185219. #ifndef PNG_FREE_ME_SUPPORTED
  185220. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  185221. #endif
  185222. info_ptr->num_palette = 0;
  185223. }
  185224. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  185225. /* free any image bits attached to the info structure */
  185226. #ifdef PNG_FREE_ME_SUPPORTED
  185227. if ((mask & PNG_FREE_ROWS) & info_ptr->free_me)
  185228. #else
  185229. if (mask & PNG_FREE_ROWS)
  185230. #endif
  185231. {
  185232. if(info_ptr->row_pointers)
  185233. {
  185234. int row;
  185235. for (row = 0; row < (int)info_ptr->height; row++)
  185236. {
  185237. png_free(png_ptr, info_ptr->row_pointers[row]);
  185238. info_ptr->row_pointers[row]=NULL;
  185239. }
  185240. png_free(png_ptr, info_ptr->row_pointers);
  185241. info_ptr->row_pointers=NULL;
  185242. }
  185243. info_ptr->valid &= ~PNG_INFO_IDAT;
  185244. }
  185245. #endif
  185246. #ifdef PNG_FREE_ME_SUPPORTED
  185247. if(num == -1)
  185248. info_ptr->free_me &= ~mask;
  185249. else
  185250. info_ptr->free_me &= ~(mask & ~PNG_FREE_MUL);
  185251. #endif
  185252. }
  185253. /* This is an internal routine to free any memory that the info struct is
  185254. * pointing to before re-using it or freeing the struct itself. Recall
  185255. * that png_free() checks for NULL pointers for us.
  185256. */
  185257. void /* PRIVATE */
  185258. png_info_destroy(png_structp png_ptr, png_infop info_ptr)
  185259. {
  185260. png_debug(1, "in png_info_destroy\n");
  185261. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  185262. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  185263. if (png_ptr->num_chunk_list)
  185264. {
  185265. png_free(png_ptr, png_ptr->chunk_list);
  185266. png_ptr->chunk_list=NULL;
  185267. png_ptr->num_chunk_list=0;
  185268. }
  185269. #endif
  185270. png_info_init_3(&info_ptr, png_sizeof(png_info));
  185271. }
  185272. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185273. /* This function returns a pointer to the io_ptr associated with the user
  185274. * functions. The application should free any memory associated with this
  185275. * pointer before png_write_destroy() or png_read_destroy() are called.
  185276. */
  185277. png_voidp PNGAPI
  185278. png_get_io_ptr(png_structp png_ptr)
  185279. {
  185280. if(png_ptr == NULL) return (NULL);
  185281. return (png_ptr->io_ptr);
  185282. }
  185283. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185284. #if !defined(PNG_NO_STDIO)
  185285. /* Initialize the default input/output functions for the PNG file. If you
  185286. * use your own read or write routines, you can call either png_set_read_fn()
  185287. * or png_set_write_fn() instead of png_init_io(). If you have defined
  185288. * PNG_NO_STDIO, you must use a function of your own because "FILE *" isn't
  185289. * necessarily available.
  185290. */
  185291. void PNGAPI
  185292. png_init_io(png_structp png_ptr, png_FILE_p fp)
  185293. {
  185294. png_debug(1, "in png_init_io\n");
  185295. if(png_ptr == NULL) return;
  185296. png_ptr->io_ptr = (png_voidp)fp;
  185297. }
  185298. #endif
  185299. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  185300. /* Convert the supplied time into an RFC 1123 string suitable for use in
  185301. * a "Creation Time" or other text-based time string.
  185302. */
  185303. png_charp PNGAPI
  185304. png_convert_to_rfc1123(png_structp png_ptr, png_timep ptime)
  185305. {
  185306. static PNG_CONST char short_months[12][4] =
  185307. {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
  185308. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
  185309. if(png_ptr == NULL) return (NULL);
  185310. if (png_ptr->time_buffer == NULL)
  185311. {
  185312. png_ptr->time_buffer = (png_charp)png_malloc(png_ptr, (png_uint_32)(29*
  185313. png_sizeof(char)));
  185314. }
  185315. #if defined(_WIN32_WCE)
  185316. {
  185317. wchar_t time_buf[29];
  185318. wsprintf(time_buf, TEXT("%d %S %d %02d:%02d:%02d +0000"),
  185319. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  185320. ptime->year, ptime->hour % 24, ptime->minute % 60,
  185321. ptime->second % 61);
  185322. WideCharToMultiByte(CP_ACP, 0, time_buf, -1, png_ptr->time_buffer, 29,
  185323. NULL, NULL);
  185324. }
  185325. #else
  185326. #ifdef USE_FAR_KEYWORD
  185327. {
  185328. char near_time_buf[29];
  185329. png_snprintf6(near_time_buf,29,"%d %s %d %02d:%02d:%02d +0000",
  185330. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  185331. ptime->year, ptime->hour % 24, ptime->minute % 60,
  185332. ptime->second % 61);
  185333. png_memcpy(png_ptr->time_buffer, near_time_buf,
  185334. 29*png_sizeof(char));
  185335. }
  185336. #else
  185337. png_snprintf6(png_ptr->time_buffer,29,"%d %s %d %02d:%02d:%02d +0000",
  185338. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  185339. ptime->year, ptime->hour % 24, ptime->minute % 60,
  185340. ptime->second % 61);
  185341. #endif
  185342. #endif /* _WIN32_WCE */
  185343. return ((png_charp)png_ptr->time_buffer);
  185344. }
  185345. #endif /* PNG_TIME_RFC1123_SUPPORTED */
  185346. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185347. png_charp PNGAPI
  185348. png_get_copyright(png_structp png_ptr)
  185349. {
  185350. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185351. return ((png_charp) "\n libpng version 1.2.21 - October 4, 2007\n\
  185352. Copyright (c) 1998-2007 Glenn Randers-Pehrson\n\
  185353. Copyright (c) 1996-1997 Andreas Dilger\n\
  185354. Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.\n");
  185355. }
  185356. /* The following return the library version as a short string in the
  185357. * format 1.0.0 through 99.99.99zz. To get the version of *.h files
  185358. * used with your application, print out PNG_LIBPNG_VER_STRING, which
  185359. * is defined in png.h.
  185360. * Note: now there is no difference between png_get_libpng_ver() and
  185361. * png_get_header_ver(). Due to the version_nn_nn_nn typedef guard,
  185362. * it is guaranteed that png.c uses the correct version of png.h.
  185363. */
  185364. png_charp PNGAPI
  185365. png_get_libpng_ver(png_structp png_ptr)
  185366. {
  185367. /* Version of *.c files used when building libpng */
  185368. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185369. return ((png_charp) PNG_LIBPNG_VER_STRING);
  185370. }
  185371. png_charp PNGAPI
  185372. png_get_header_ver(png_structp png_ptr)
  185373. {
  185374. /* Version of *.h files used when building libpng */
  185375. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185376. return ((png_charp) PNG_LIBPNG_VER_STRING);
  185377. }
  185378. png_charp PNGAPI
  185379. png_get_header_version(png_structp png_ptr)
  185380. {
  185381. /* Returns longer string containing both version and date */
  185382. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185383. return ((png_charp) PNG_HEADER_VERSION_STRING
  185384. #ifndef PNG_READ_SUPPORTED
  185385. " (NO READ SUPPORT)"
  185386. #endif
  185387. "\n");
  185388. }
  185389. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185390. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  185391. int PNGAPI
  185392. png_handle_as_unknown(png_structp png_ptr, png_bytep chunk_name)
  185393. {
  185394. /* check chunk_name and return "keep" value if it's on the list, else 0 */
  185395. int i;
  185396. png_bytep p;
  185397. if(png_ptr == NULL || chunk_name == NULL || png_ptr->num_chunk_list<=0)
  185398. return 0;
  185399. p=png_ptr->chunk_list+png_ptr->num_chunk_list*5-5;
  185400. for (i = png_ptr->num_chunk_list; i; i--, p-=5)
  185401. if (!png_memcmp(chunk_name, p, 4))
  185402. return ((int)*(p+4));
  185403. return 0;
  185404. }
  185405. #endif
  185406. /* This function, added to libpng-1.0.6g, is untested. */
  185407. int PNGAPI
  185408. png_reset_zstream(png_structp png_ptr)
  185409. {
  185410. if (png_ptr == NULL) return Z_STREAM_ERROR;
  185411. return (inflateReset(&png_ptr->zstream));
  185412. }
  185413. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185414. /* This function was added to libpng-1.0.7 */
  185415. png_uint_32 PNGAPI
  185416. png_access_version_number(void)
  185417. {
  185418. /* Version of *.c files used when building libpng */
  185419. return((png_uint_32) PNG_LIBPNG_VER);
  185420. }
  185421. #if defined(PNG_READ_SUPPORTED) && defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  185422. #if !defined(PNG_1_0_X)
  185423. /* this function was added to libpng 1.2.0 */
  185424. int PNGAPI
  185425. png_mmx_support(void)
  185426. {
  185427. /* obsolete, to be removed from libpng-1.4.0 */
  185428. return -1;
  185429. }
  185430. #endif /* PNG_1_0_X */
  185431. #endif /* PNG_READ_SUPPORTED && PNG_ASSEMBLER_CODE_SUPPORTED */
  185432. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185433. #ifdef PNG_SIZE_T
  185434. /* Added at libpng version 1.2.6 */
  185435. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  185436. png_size_t PNGAPI
  185437. png_convert_size(size_t size)
  185438. {
  185439. if (size > (png_size_t)-1)
  185440. PNG_ABORT(); /* We haven't got access to png_ptr, so no png_error() */
  185441. return ((png_size_t)size);
  185442. }
  185443. #endif /* PNG_SIZE_T */
  185444. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185445. /*** End of inlined file: png.c ***/
  185446. /*** Start of inlined file: pngerror.c ***/
  185447. /* pngerror.c - stub functions for i/o and memory allocation
  185448. *
  185449. * Last changed in libpng 1.2.20 October 4, 2007
  185450. * For conditions of distribution and use, see copyright notice in png.h
  185451. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  185452. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  185453. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  185454. *
  185455. * This file provides a location for all error handling. Users who
  185456. * need special error handling are expected to write replacement functions
  185457. * and use png_set_error_fn() to use those functions. See the instructions
  185458. * at each function.
  185459. */
  185460. #define PNG_INTERNAL
  185461. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185462. static void /* PRIVATE */
  185463. png_default_error PNGARG((png_structp png_ptr,
  185464. png_const_charp error_message));
  185465. #ifndef PNG_NO_WARNINGS
  185466. static void /* PRIVATE */
  185467. png_default_warning PNGARG((png_structp png_ptr,
  185468. png_const_charp warning_message));
  185469. #endif /* PNG_NO_WARNINGS */
  185470. /* This function is called whenever there is a fatal error. This function
  185471. * should not be changed. If there is a need to handle errors differently,
  185472. * you should supply a replacement error function and use png_set_error_fn()
  185473. * to replace the error function at run-time.
  185474. */
  185475. #ifndef PNG_NO_ERROR_TEXT
  185476. void PNGAPI
  185477. png_error(png_structp png_ptr, png_const_charp error_message)
  185478. {
  185479. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185480. char msg[16];
  185481. if (png_ptr != NULL)
  185482. {
  185483. if (png_ptr->flags&
  185484. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  185485. {
  185486. if (*error_message == '#')
  185487. {
  185488. int offset;
  185489. for (offset=1; offset<15; offset++)
  185490. if (*(error_message+offset) == ' ')
  185491. break;
  185492. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  185493. {
  185494. int i;
  185495. for (i=0; i<offset-1; i++)
  185496. msg[i]=error_message[i+1];
  185497. msg[i]='\0';
  185498. error_message=msg;
  185499. }
  185500. else
  185501. error_message+=offset;
  185502. }
  185503. else
  185504. {
  185505. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  185506. {
  185507. msg[0]='0';
  185508. msg[1]='\0';
  185509. error_message=msg;
  185510. }
  185511. }
  185512. }
  185513. }
  185514. #endif
  185515. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  185516. (*(png_ptr->error_fn))(png_ptr, error_message);
  185517. /* If the custom handler doesn't exist, or if it returns,
  185518. use the default handler, which will not return. */
  185519. png_default_error(png_ptr, error_message);
  185520. }
  185521. #else
  185522. void PNGAPI
  185523. png_err(png_structp png_ptr)
  185524. {
  185525. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  185526. (*(png_ptr->error_fn))(png_ptr, '\0');
  185527. /* If the custom handler doesn't exist, or if it returns,
  185528. use the default handler, which will not return. */
  185529. png_default_error(png_ptr, '\0');
  185530. }
  185531. #endif /* PNG_NO_ERROR_TEXT */
  185532. #ifndef PNG_NO_WARNINGS
  185533. /* This function is called whenever there is a non-fatal error. This function
  185534. * should not be changed. If there is a need to handle warnings differently,
  185535. * you should supply a replacement warning function and use
  185536. * png_set_error_fn() to replace the warning function at run-time.
  185537. */
  185538. void PNGAPI
  185539. png_warning(png_structp png_ptr, png_const_charp warning_message)
  185540. {
  185541. int offset = 0;
  185542. if (png_ptr != NULL)
  185543. {
  185544. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185545. if (png_ptr->flags&
  185546. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  185547. #endif
  185548. {
  185549. if (*warning_message == '#')
  185550. {
  185551. for (offset=1; offset<15; offset++)
  185552. if (*(warning_message+offset) == ' ')
  185553. break;
  185554. }
  185555. }
  185556. if (png_ptr != NULL && png_ptr->warning_fn != NULL)
  185557. (*(png_ptr->warning_fn))(png_ptr, warning_message+offset);
  185558. }
  185559. else
  185560. png_default_warning(png_ptr, warning_message+offset);
  185561. }
  185562. #endif /* PNG_NO_WARNINGS */
  185563. /* These utilities are used internally to build an error message that relates
  185564. * to the current chunk. The chunk name comes from png_ptr->chunk_name,
  185565. * this is used to prefix the message. The message is limited in length
  185566. * to 63 bytes, the name characters are output as hex digits wrapped in []
  185567. * if the character is invalid.
  185568. */
  185569. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  185570. /*static PNG_CONST char png_digit[16] = {
  185571. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  185572. 'A', 'B', 'C', 'D', 'E', 'F'
  185573. };*/
  185574. #if !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT)
  185575. static void /* PRIVATE */
  185576. png_format_buffer(png_structp png_ptr, png_charp buffer, png_const_charp
  185577. error_message)
  185578. {
  185579. int iout = 0, iin = 0;
  185580. while (iin < 4)
  185581. {
  185582. int c = png_ptr->chunk_name[iin++];
  185583. if (isnonalpha(c))
  185584. {
  185585. buffer[iout++] = '[';
  185586. buffer[iout++] = png_digit[(c & 0xf0) >> 4];
  185587. buffer[iout++] = png_digit[c & 0x0f];
  185588. buffer[iout++] = ']';
  185589. }
  185590. else
  185591. {
  185592. buffer[iout++] = (png_byte)c;
  185593. }
  185594. }
  185595. if (error_message == NULL)
  185596. buffer[iout] = 0;
  185597. else
  185598. {
  185599. buffer[iout++] = ':';
  185600. buffer[iout++] = ' ';
  185601. png_strncpy(buffer+iout, error_message, 63);
  185602. buffer[iout+63] = 0;
  185603. }
  185604. }
  185605. #ifdef PNG_READ_SUPPORTED
  185606. void PNGAPI
  185607. png_chunk_error(png_structp png_ptr, png_const_charp error_message)
  185608. {
  185609. char msg[18+64];
  185610. if (png_ptr == NULL)
  185611. png_error(png_ptr, error_message);
  185612. else
  185613. {
  185614. png_format_buffer(png_ptr, msg, error_message);
  185615. png_error(png_ptr, msg);
  185616. }
  185617. }
  185618. #endif /* PNG_READ_SUPPORTED */
  185619. #endif /* !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT) */
  185620. #ifndef PNG_NO_WARNINGS
  185621. void PNGAPI
  185622. png_chunk_warning(png_structp png_ptr, png_const_charp warning_message)
  185623. {
  185624. char msg[18+64];
  185625. if (png_ptr == NULL)
  185626. png_warning(png_ptr, warning_message);
  185627. else
  185628. {
  185629. png_format_buffer(png_ptr, msg, warning_message);
  185630. png_warning(png_ptr, msg);
  185631. }
  185632. }
  185633. #endif /* PNG_NO_WARNINGS */
  185634. /* This is the default error handling function. Note that replacements for
  185635. * this function MUST NOT RETURN, or the program will likely crash. This
  185636. * function is used by default, or if the program supplies NULL for the
  185637. * error function pointer in png_set_error_fn().
  185638. */
  185639. static void /* PRIVATE */
  185640. png_default_error(png_structp, png_const_charp error_message)
  185641. {
  185642. #ifndef PNG_NO_CONSOLE_IO
  185643. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185644. if (*error_message == '#')
  185645. {
  185646. int offset;
  185647. char error_number[16];
  185648. for (offset=0; offset<15; offset++)
  185649. {
  185650. error_number[offset] = *(error_message+offset+1);
  185651. if (*(error_message+offset) == ' ')
  185652. break;
  185653. }
  185654. if((offset > 1) && (offset < 15))
  185655. {
  185656. error_number[offset-1]='\0';
  185657. fprintf(stderr, "libpng error no. %s: %s\n", error_number,
  185658. error_message+offset);
  185659. }
  185660. else
  185661. fprintf(stderr, "libpng error: %s, offset=%d\n", error_message,offset);
  185662. }
  185663. else
  185664. #endif
  185665. fprintf(stderr, "libpng error: %s\n", error_message);
  185666. #endif
  185667. #ifdef PNG_SETJMP_SUPPORTED
  185668. if (png_ptr)
  185669. {
  185670. # ifdef USE_FAR_KEYWORD
  185671. {
  185672. jmp_buf jmpbuf;
  185673. png_memcpy(jmpbuf, png_ptr->jmpbuf, png_sizeof(jmp_buf));
  185674. longjmp(jmpbuf, 1);
  185675. }
  185676. # else
  185677. longjmp(png_ptr->jmpbuf, 1);
  185678. # endif
  185679. }
  185680. #else
  185681. PNG_ABORT();
  185682. #endif
  185683. #ifdef PNG_NO_CONSOLE_IO
  185684. error_message = error_message; /* make compiler happy */
  185685. #endif
  185686. }
  185687. #ifndef PNG_NO_WARNINGS
  185688. /* This function is called when there is a warning, but the library thinks
  185689. * it can continue anyway. Replacement functions don't have to do anything
  185690. * here if you don't want them to. In the default configuration, png_ptr is
  185691. * not used, but it is passed in case it may be useful.
  185692. */
  185693. static void /* PRIVATE */
  185694. png_default_warning(png_structp png_ptr, png_const_charp warning_message)
  185695. {
  185696. #ifndef PNG_NO_CONSOLE_IO
  185697. # ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185698. if (*warning_message == '#')
  185699. {
  185700. int offset;
  185701. char warning_number[16];
  185702. for (offset=0; offset<15; offset++)
  185703. {
  185704. warning_number[offset]=*(warning_message+offset+1);
  185705. if (*(warning_message+offset) == ' ')
  185706. break;
  185707. }
  185708. if((offset > 1) && (offset < 15))
  185709. {
  185710. warning_number[offset-1]='\0';
  185711. fprintf(stderr, "libpng warning no. %s: %s\n", warning_number,
  185712. warning_message+offset);
  185713. }
  185714. else
  185715. fprintf(stderr, "libpng warning: %s\n", warning_message);
  185716. }
  185717. else
  185718. # endif
  185719. fprintf(stderr, "libpng warning: %s\n", warning_message);
  185720. #else
  185721. warning_message = warning_message; /* make compiler happy */
  185722. #endif
  185723. png_ptr = png_ptr; /* make compiler happy */
  185724. }
  185725. #endif /* PNG_NO_WARNINGS */
  185726. /* This function is called when the application wants to use another method
  185727. * of handling errors and warnings. Note that the error function MUST NOT
  185728. * return to the calling routine or serious problems will occur. The return
  185729. * method used in the default routine calls longjmp(png_ptr->jmpbuf, 1)
  185730. */
  185731. void PNGAPI
  185732. png_set_error_fn(png_structp png_ptr, png_voidp error_ptr,
  185733. png_error_ptr error_fn, png_error_ptr warning_fn)
  185734. {
  185735. if (png_ptr == NULL)
  185736. return;
  185737. png_ptr->error_ptr = error_ptr;
  185738. png_ptr->error_fn = error_fn;
  185739. png_ptr->warning_fn = warning_fn;
  185740. }
  185741. /* This function returns a pointer to the error_ptr associated with the user
  185742. * functions. The application should free any memory associated with this
  185743. * pointer before png_write_destroy and png_read_destroy are called.
  185744. */
  185745. png_voidp PNGAPI
  185746. png_get_error_ptr(png_structp png_ptr)
  185747. {
  185748. if (png_ptr == NULL)
  185749. return NULL;
  185750. return ((png_voidp)png_ptr->error_ptr);
  185751. }
  185752. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185753. void PNGAPI
  185754. png_set_strip_error_numbers(png_structp png_ptr, png_uint_32 strip_mode)
  185755. {
  185756. if(png_ptr != NULL)
  185757. {
  185758. png_ptr->flags &=
  185759. ((~(PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))&strip_mode);
  185760. }
  185761. }
  185762. #endif
  185763. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  185764. /*** End of inlined file: pngerror.c ***/
  185765. /*** Start of inlined file: pngget.c ***/
  185766. /* pngget.c - retrieval of values from info struct
  185767. *
  185768. * Last changed in libpng 1.2.15 January 5, 2007
  185769. * For conditions of distribution and use, see copyright notice in png.h
  185770. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  185771. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  185772. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  185773. */
  185774. #define PNG_INTERNAL
  185775. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185776. png_uint_32 PNGAPI
  185777. png_get_valid(png_structp png_ptr, png_infop info_ptr, png_uint_32 flag)
  185778. {
  185779. if (png_ptr != NULL && info_ptr != NULL)
  185780. return(info_ptr->valid & flag);
  185781. else
  185782. return(0);
  185783. }
  185784. png_uint_32 PNGAPI
  185785. png_get_rowbytes(png_structp png_ptr, png_infop info_ptr)
  185786. {
  185787. if (png_ptr != NULL && info_ptr != NULL)
  185788. return(info_ptr->rowbytes);
  185789. else
  185790. return(0);
  185791. }
  185792. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  185793. png_bytepp PNGAPI
  185794. png_get_rows(png_structp png_ptr, png_infop info_ptr)
  185795. {
  185796. if (png_ptr != NULL && info_ptr != NULL)
  185797. return(info_ptr->row_pointers);
  185798. else
  185799. return(0);
  185800. }
  185801. #endif
  185802. #ifdef PNG_EASY_ACCESS_SUPPORTED
  185803. /* easy access to info, added in libpng-0.99 */
  185804. png_uint_32 PNGAPI
  185805. png_get_image_width(png_structp png_ptr, png_infop info_ptr)
  185806. {
  185807. if (png_ptr != NULL && info_ptr != NULL)
  185808. {
  185809. return info_ptr->width;
  185810. }
  185811. return (0);
  185812. }
  185813. png_uint_32 PNGAPI
  185814. png_get_image_height(png_structp png_ptr, png_infop info_ptr)
  185815. {
  185816. if (png_ptr != NULL && info_ptr != NULL)
  185817. {
  185818. return info_ptr->height;
  185819. }
  185820. return (0);
  185821. }
  185822. png_byte PNGAPI
  185823. png_get_bit_depth(png_structp png_ptr, png_infop info_ptr)
  185824. {
  185825. if (png_ptr != NULL && info_ptr != NULL)
  185826. {
  185827. return info_ptr->bit_depth;
  185828. }
  185829. return (0);
  185830. }
  185831. png_byte PNGAPI
  185832. png_get_color_type(png_structp png_ptr, png_infop info_ptr)
  185833. {
  185834. if (png_ptr != NULL && info_ptr != NULL)
  185835. {
  185836. return info_ptr->color_type;
  185837. }
  185838. return (0);
  185839. }
  185840. png_byte PNGAPI
  185841. png_get_filter_type(png_structp png_ptr, png_infop info_ptr)
  185842. {
  185843. if (png_ptr != NULL && info_ptr != NULL)
  185844. {
  185845. return info_ptr->filter_type;
  185846. }
  185847. return (0);
  185848. }
  185849. png_byte PNGAPI
  185850. png_get_interlace_type(png_structp png_ptr, png_infop info_ptr)
  185851. {
  185852. if (png_ptr != NULL && info_ptr != NULL)
  185853. {
  185854. return info_ptr->interlace_type;
  185855. }
  185856. return (0);
  185857. }
  185858. png_byte PNGAPI
  185859. png_get_compression_type(png_structp png_ptr, png_infop info_ptr)
  185860. {
  185861. if (png_ptr != NULL && info_ptr != NULL)
  185862. {
  185863. return info_ptr->compression_type;
  185864. }
  185865. return (0);
  185866. }
  185867. png_uint_32 PNGAPI
  185868. png_get_x_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  185869. {
  185870. if (png_ptr != NULL && info_ptr != NULL)
  185871. #if defined(PNG_pHYs_SUPPORTED)
  185872. if (info_ptr->valid & PNG_INFO_pHYs)
  185873. {
  185874. png_debug1(1, "in %s retrieval function\n", "png_get_x_pixels_per_meter");
  185875. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  185876. return (0);
  185877. else return (info_ptr->x_pixels_per_unit);
  185878. }
  185879. #else
  185880. return (0);
  185881. #endif
  185882. return (0);
  185883. }
  185884. png_uint_32 PNGAPI
  185885. png_get_y_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  185886. {
  185887. if (png_ptr != NULL && info_ptr != NULL)
  185888. #if defined(PNG_pHYs_SUPPORTED)
  185889. if (info_ptr->valid & PNG_INFO_pHYs)
  185890. {
  185891. png_debug1(1, "in %s retrieval function\n", "png_get_y_pixels_per_meter");
  185892. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  185893. return (0);
  185894. else return (info_ptr->y_pixels_per_unit);
  185895. }
  185896. #else
  185897. return (0);
  185898. #endif
  185899. return (0);
  185900. }
  185901. png_uint_32 PNGAPI
  185902. png_get_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  185903. {
  185904. if (png_ptr != NULL && info_ptr != NULL)
  185905. #if defined(PNG_pHYs_SUPPORTED)
  185906. if (info_ptr->valid & PNG_INFO_pHYs)
  185907. {
  185908. png_debug1(1, "in %s retrieval function\n", "png_get_pixels_per_meter");
  185909. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER ||
  185910. info_ptr->x_pixels_per_unit != info_ptr->y_pixels_per_unit)
  185911. return (0);
  185912. else return (info_ptr->x_pixels_per_unit);
  185913. }
  185914. #else
  185915. return (0);
  185916. #endif
  185917. return (0);
  185918. }
  185919. #ifdef PNG_FLOATING_POINT_SUPPORTED
  185920. float PNGAPI
  185921. png_get_pixel_aspect_ratio(png_structp png_ptr, png_infop info_ptr)
  185922. {
  185923. if (png_ptr != NULL && info_ptr != NULL)
  185924. #if defined(PNG_pHYs_SUPPORTED)
  185925. if (info_ptr->valid & PNG_INFO_pHYs)
  185926. {
  185927. png_debug1(1, "in %s retrieval function\n", "png_get_aspect_ratio");
  185928. if (info_ptr->x_pixels_per_unit == 0)
  185929. return ((float)0.0);
  185930. else
  185931. return ((float)((float)info_ptr->y_pixels_per_unit
  185932. /(float)info_ptr->x_pixels_per_unit));
  185933. }
  185934. #else
  185935. return (0.0);
  185936. #endif
  185937. return ((float)0.0);
  185938. }
  185939. #endif
  185940. png_int_32 PNGAPI
  185941. png_get_x_offset_microns(png_structp png_ptr, png_infop info_ptr)
  185942. {
  185943. if (png_ptr != NULL && info_ptr != NULL)
  185944. #if defined(PNG_oFFs_SUPPORTED)
  185945. if (info_ptr->valid & PNG_INFO_oFFs)
  185946. {
  185947. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  185948. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  185949. return (0);
  185950. else return (info_ptr->x_offset);
  185951. }
  185952. #else
  185953. return (0);
  185954. #endif
  185955. return (0);
  185956. }
  185957. png_int_32 PNGAPI
  185958. png_get_y_offset_microns(png_structp png_ptr, png_infop info_ptr)
  185959. {
  185960. if (png_ptr != NULL && info_ptr != NULL)
  185961. #if defined(PNG_oFFs_SUPPORTED)
  185962. if (info_ptr->valid & PNG_INFO_oFFs)
  185963. {
  185964. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  185965. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  185966. return (0);
  185967. else return (info_ptr->y_offset);
  185968. }
  185969. #else
  185970. return (0);
  185971. #endif
  185972. return (0);
  185973. }
  185974. png_int_32 PNGAPI
  185975. png_get_x_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  185976. {
  185977. if (png_ptr != NULL && info_ptr != NULL)
  185978. #if defined(PNG_oFFs_SUPPORTED)
  185979. if (info_ptr->valid & PNG_INFO_oFFs)
  185980. {
  185981. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  185982. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  185983. return (0);
  185984. else return (info_ptr->x_offset);
  185985. }
  185986. #else
  185987. return (0);
  185988. #endif
  185989. return (0);
  185990. }
  185991. png_int_32 PNGAPI
  185992. png_get_y_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  185993. {
  185994. if (png_ptr != NULL && info_ptr != NULL)
  185995. #if defined(PNG_oFFs_SUPPORTED)
  185996. if (info_ptr->valid & PNG_INFO_oFFs)
  185997. {
  185998. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  185999. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  186000. return (0);
  186001. else return (info_ptr->y_offset);
  186002. }
  186003. #else
  186004. return (0);
  186005. #endif
  186006. return (0);
  186007. }
  186008. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  186009. png_uint_32 PNGAPI
  186010. png_get_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  186011. {
  186012. return ((png_uint_32)((float)png_get_pixels_per_meter(png_ptr, info_ptr)
  186013. *.0254 +.5));
  186014. }
  186015. png_uint_32 PNGAPI
  186016. png_get_x_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  186017. {
  186018. return ((png_uint_32)((float)png_get_x_pixels_per_meter(png_ptr, info_ptr)
  186019. *.0254 +.5));
  186020. }
  186021. png_uint_32 PNGAPI
  186022. png_get_y_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  186023. {
  186024. return ((png_uint_32)((float)png_get_y_pixels_per_meter(png_ptr, info_ptr)
  186025. *.0254 +.5));
  186026. }
  186027. float PNGAPI
  186028. png_get_x_offset_inches(png_structp png_ptr, png_infop info_ptr)
  186029. {
  186030. return ((float)png_get_x_offset_microns(png_ptr, info_ptr)
  186031. *.00003937);
  186032. }
  186033. float PNGAPI
  186034. png_get_y_offset_inches(png_structp png_ptr, png_infop info_ptr)
  186035. {
  186036. return ((float)png_get_y_offset_microns(png_ptr, info_ptr)
  186037. *.00003937);
  186038. }
  186039. #if defined(PNG_pHYs_SUPPORTED)
  186040. png_uint_32 PNGAPI
  186041. png_get_pHYs_dpi(png_structp png_ptr, png_infop info_ptr,
  186042. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  186043. {
  186044. png_uint_32 retval = 0;
  186045. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  186046. {
  186047. png_debug1(1, "in %s retrieval function\n", "pHYs");
  186048. if (res_x != NULL)
  186049. {
  186050. *res_x = info_ptr->x_pixels_per_unit;
  186051. retval |= PNG_INFO_pHYs;
  186052. }
  186053. if (res_y != NULL)
  186054. {
  186055. *res_y = info_ptr->y_pixels_per_unit;
  186056. retval |= PNG_INFO_pHYs;
  186057. }
  186058. if (unit_type != NULL)
  186059. {
  186060. *unit_type = (int)info_ptr->phys_unit_type;
  186061. retval |= PNG_INFO_pHYs;
  186062. if(*unit_type == 1)
  186063. {
  186064. if (res_x != NULL) *res_x = (png_uint_32)(*res_x * .0254 + .50);
  186065. if (res_y != NULL) *res_y = (png_uint_32)(*res_y * .0254 + .50);
  186066. }
  186067. }
  186068. }
  186069. return (retval);
  186070. }
  186071. #endif /* PNG_pHYs_SUPPORTED */
  186072. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  186073. /* png_get_channels really belongs in here, too, but it's been around longer */
  186074. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  186075. png_byte PNGAPI
  186076. png_get_channels(png_structp png_ptr, png_infop info_ptr)
  186077. {
  186078. if (png_ptr != NULL && info_ptr != NULL)
  186079. return(info_ptr->channels);
  186080. else
  186081. return (0);
  186082. }
  186083. png_bytep PNGAPI
  186084. png_get_signature(png_structp png_ptr, png_infop info_ptr)
  186085. {
  186086. if (png_ptr != NULL && info_ptr != NULL)
  186087. return(info_ptr->signature);
  186088. else
  186089. return (NULL);
  186090. }
  186091. #if defined(PNG_bKGD_SUPPORTED)
  186092. png_uint_32 PNGAPI
  186093. png_get_bKGD(png_structp png_ptr, png_infop info_ptr,
  186094. png_color_16p *background)
  186095. {
  186096. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD)
  186097. && background != NULL)
  186098. {
  186099. png_debug1(1, "in %s retrieval function\n", "bKGD");
  186100. *background = &(info_ptr->background);
  186101. return (PNG_INFO_bKGD);
  186102. }
  186103. return (0);
  186104. }
  186105. #endif
  186106. #if defined(PNG_cHRM_SUPPORTED)
  186107. #ifdef PNG_FLOATING_POINT_SUPPORTED
  186108. png_uint_32 PNGAPI
  186109. png_get_cHRM(png_structp png_ptr, png_infop info_ptr,
  186110. double *white_x, double *white_y, double *red_x, double *red_y,
  186111. double *green_x, double *green_y, double *blue_x, double *blue_y)
  186112. {
  186113. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  186114. {
  186115. png_debug1(1, "in %s retrieval function\n", "cHRM");
  186116. if (white_x != NULL)
  186117. *white_x = (double)info_ptr->x_white;
  186118. if (white_y != NULL)
  186119. *white_y = (double)info_ptr->y_white;
  186120. if (red_x != NULL)
  186121. *red_x = (double)info_ptr->x_red;
  186122. if (red_y != NULL)
  186123. *red_y = (double)info_ptr->y_red;
  186124. if (green_x != NULL)
  186125. *green_x = (double)info_ptr->x_green;
  186126. if (green_y != NULL)
  186127. *green_y = (double)info_ptr->y_green;
  186128. if (blue_x != NULL)
  186129. *blue_x = (double)info_ptr->x_blue;
  186130. if (blue_y != NULL)
  186131. *blue_y = (double)info_ptr->y_blue;
  186132. return (PNG_INFO_cHRM);
  186133. }
  186134. return (0);
  186135. }
  186136. #endif
  186137. #ifdef PNG_FIXED_POINT_SUPPORTED
  186138. png_uint_32 PNGAPI
  186139. png_get_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  186140. png_fixed_point *white_x, png_fixed_point *white_y, png_fixed_point *red_x,
  186141. png_fixed_point *red_y, png_fixed_point *green_x, png_fixed_point *green_y,
  186142. png_fixed_point *blue_x, png_fixed_point *blue_y)
  186143. {
  186144. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  186145. {
  186146. png_debug1(1, "in %s retrieval function\n", "cHRM");
  186147. if (white_x != NULL)
  186148. *white_x = info_ptr->int_x_white;
  186149. if (white_y != NULL)
  186150. *white_y = info_ptr->int_y_white;
  186151. if (red_x != NULL)
  186152. *red_x = info_ptr->int_x_red;
  186153. if (red_y != NULL)
  186154. *red_y = info_ptr->int_y_red;
  186155. if (green_x != NULL)
  186156. *green_x = info_ptr->int_x_green;
  186157. if (green_y != NULL)
  186158. *green_y = info_ptr->int_y_green;
  186159. if (blue_x != NULL)
  186160. *blue_x = info_ptr->int_x_blue;
  186161. if (blue_y != NULL)
  186162. *blue_y = info_ptr->int_y_blue;
  186163. return (PNG_INFO_cHRM);
  186164. }
  186165. return (0);
  186166. }
  186167. #endif
  186168. #endif
  186169. #if defined(PNG_gAMA_SUPPORTED)
  186170. #ifdef PNG_FLOATING_POINT_SUPPORTED
  186171. png_uint_32 PNGAPI
  186172. png_get_gAMA(png_structp png_ptr, png_infop info_ptr, double *file_gamma)
  186173. {
  186174. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  186175. && file_gamma != NULL)
  186176. {
  186177. png_debug1(1, "in %s retrieval function\n", "gAMA");
  186178. *file_gamma = (double)info_ptr->gamma;
  186179. return (PNG_INFO_gAMA);
  186180. }
  186181. return (0);
  186182. }
  186183. #endif
  186184. #ifdef PNG_FIXED_POINT_SUPPORTED
  186185. png_uint_32 PNGAPI
  186186. png_get_gAMA_fixed(png_structp png_ptr, png_infop info_ptr,
  186187. png_fixed_point *int_file_gamma)
  186188. {
  186189. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  186190. && int_file_gamma != NULL)
  186191. {
  186192. png_debug1(1, "in %s retrieval function\n", "gAMA");
  186193. *int_file_gamma = info_ptr->int_gamma;
  186194. return (PNG_INFO_gAMA);
  186195. }
  186196. return (0);
  186197. }
  186198. #endif
  186199. #endif
  186200. #if defined(PNG_sRGB_SUPPORTED)
  186201. png_uint_32 PNGAPI
  186202. png_get_sRGB(png_structp png_ptr, png_infop info_ptr, int *file_srgb_intent)
  186203. {
  186204. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB)
  186205. && file_srgb_intent != NULL)
  186206. {
  186207. png_debug1(1, "in %s retrieval function\n", "sRGB");
  186208. *file_srgb_intent = (int)info_ptr->srgb_intent;
  186209. return (PNG_INFO_sRGB);
  186210. }
  186211. return (0);
  186212. }
  186213. #endif
  186214. #if defined(PNG_iCCP_SUPPORTED)
  186215. png_uint_32 PNGAPI
  186216. png_get_iCCP(png_structp png_ptr, png_infop info_ptr,
  186217. png_charpp name, int *compression_type,
  186218. png_charpp profile, png_uint_32 *proflen)
  186219. {
  186220. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP)
  186221. && name != NULL && profile != NULL && proflen != NULL)
  186222. {
  186223. png_debug1(1, "in %s retrieval function\n", "iCCP");
  186224. *name = info_ptr->iccp_name;
  186225. *profile = info_ptr->iccp_profile;
  186226. /* compression_type is a dummy so the API won't have to change
  186227. if we introduce multiple compression types later. */
  186228. *proflen = (int)info_ptr->iccp_proflen;
  186229. *compression_type = (int)info_ptr->iccp_compression;
  186230. return (PNG_INFO_iCCP);
  186231. }
  186232. return (0);
  186233. }
  186234. #endif
  186235. #if defined(PNG_sPLT_SUPPORTED)
  186236. png_uint_32 PNGAPI
  186237. png_get_sPLT(png_structp png_ptr, png_infop info_ptr,
  186238. png_sPLT_tpp spalettes)
  186239. {
  186240. if (png_ptr != NULL && info_ptr != NULL && spalettes != NULL)
  186241. {
  186242. *spalettes = info_ptr->splt_palettes;
  186243. return ((png_uint_32)info_ptr->splt_palettes_num);
  186244. }
  186245. return (0);
  186246. }
  186247. #endif
  186248. #if defined(PNG_hIST_SUPPORTED)
  186249. png_uint_32 PNGAPI
  186250. png_get_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p *hist)
  186251. {
  186252. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST)
  186253. && hist != NULL)
  186254. {
  186255. png_debug1(1, "in %s retrieval function\n", "hIST");
  186256. *hist = info_ptr->hist;
  186257. return (PNG_INFO_hIST);
  186258. }
  186259. return (0);
  186260. }
  186261. #endif
  186262. png_uint_32 PNGAPI
  186263. png_get_IHDR(png_structp png_ptr, png_infop info_ptr,
  186264. png_uint_32 *width, png_uint_32 *height, int *bit_depth,
  186265. int *color_type, int *interlace_type, int *compression_type,
  186266. int *filter_type)
  186267. {
  186268. if (png_ptr != NULL && info_ptr != NULL && width != NULL && height != NULL &&
  186269. bit_depth != NULL && color_type != NULL)
  186270. {
  186271. png_debug1(1, "in %s retrieval function\n", "IHDR");
  186272. *width = info_ptr->width;
  186273. *height = info_ptr->height;
  186274. *bit_depth = info_ptr->bit_depth;
  186275. if (info_ptr->bit_depth < 1 || info_ptr->bit_depth > 16)
  186276. png_error(png_ptr, "Invalid bit depth");
  186277. *color_type = info_ptr->color_type;
  186278. if (info_ptr->color_type > 6)
  186279. png_error(png_ptr, "Invalid color type");
  186280. if (compression_type != NULL)
  186281. *compression_type = info_ptr->compression_type;
  186282. if (filter_type != NULL)
  186283. *filter_type = info_ptr->filter_type;
  186284. if (interlace_type != NULL)
  186285. *interlace_type = info_ptr->interlace_type;
  186286. /* check for potential overflow of rowbytes */
  186287. if (*width == 0 || *width > PNG_UINT_31_MAX)
  186288. png_error(png_ptr, "Invalid image width");
  186289. if (*height == 0 || *height > PNG_UINT_31_MAX)
  186290. png_error(png_ptr, "Invalid image height");
  186291. if (info_ptr->width > (PNG_UINT_32_MAX
  186292. >> 3) /* 8-byte RGBA pixels */
  186293. - 64 /* bigrowbuf hack */
  186294. - 1 /* filter byte */
  186295. - 7*8 /* rounding of width to multiple of 8 pixels */
  186296. - 8) /* extra max_pixel_depth pad */
  186297. {
  186298. png_warning(png_ptr,
  186299. "Width too large for libpng to process image data.");
  186300. }
  186301. return (1);
  186302. }
  186303. return (0);
  186304. }
  186305. #if defined(PNG_oFFs_SUPPORTED)
  186306. png_uint_32 PNGAPI
  186307. png_get_oFFs(png_structp png_ptr, png_infop info_ptr,
  186308. png_int_32 *offset_x, png_int_32 *offset_y, int *unit_type)
  186309. {
  186310. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs)
  186311. && offset_x != NULL && offset_y != NULL && unit_type != NULL)
  186312. {
  186313. png_debug1(1, "in %s retrieval function\n", "oFFs");
  186314. *offset_x = info_ptr->x_offset;
  186315. *offset_y = info_ptr->y_offset;
  186316. *unit_type = (int)info_ptr->offset_unit_type;
  186317. return (PNG_INFO_oFFs);
  186318. }
  186319. return (0);
  186320. }
  186321. #endif
  186322. #if defined(PNG_pCAL_SUPPORTED)
  186323. png_uint_32 PNGAPI
  186324. png_get_pCAL(png_structp png_ptr, png_infop info_ptr,
  186325. png_charp *purpose, png_int_32 *X0, png_int_32 *X1, int *type, int *nparams,
  186326. png_charp *units, png_charpp *params)
  186327. {
  186328. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL)
  186329. && purpose != NULL && X0 != NULL && X1 != NULL && type != NULL &&
  186330. nparams != NULL && units != NULL && params != NULL)
  186331. {
  186332. png_debug1(1, "in %s retrieval function\n", "pCAL");
  186333. *purpose = info_ptr->pcal_purpose;
  186334. *X0 = info_ptr->pcal_X0;
  186335. *X1 = info_ptr->pcal_X1;
  186336. *type = (int)info_ptr->pcal_type;
  186337. *nparams = (int)info_ptr->pcal_nparams;
  186338. *units = info_ptr->pcal_units;
  186339. *params = info_ptr->pcal_params;
  186340. return (PNG_INFO_pCAL);
  186341. }
  186342. return (0);
  186343. }
  186344. #endif
  186345. #if defined(PNG_sCAL_SUPPORTED)
  186346. #ifdef PNG_FLOATING_POINT_SUPPORTED
  186347. png_uint_32 PNGAPI
  186348. png_get_sCAL(png_structp png_ptr, png_infop info_ptr,
  186349. int *unit, double *width, double *height)
  186350. {
  186351. if (png_ptr != NULL && info_ptr != NULL &&
  186352. (info_ptr->valid & PNG_INFO_sCAL))
  186353. {
  186354. *unit = info_ptr->scal_unit;
  186355. *width = info_ptr->scal_pixel_width;
  186356. *height = info_ptr->scal_pixel_height;
  186357. return (PNG_INFO_sCAL);
  186358. }
  186359. return(0);
  186360. }
  186361. #else
  186362. #ifdef PNG_FIXED_POINT_SUPPORTED
  186363. png_uint_32 PNGAPI
  186364. png_get_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  186365. int *unit, png_charpp width, png_charpp height)
  186366. {
  186367. if (png_ptr != NULL && info_ptr != NULL &&
  186368. (info_ptr->valid & PNG_INFO_sCAL))
  186369. {
  186370. *unit = info_ptr->scal_unit;
  186371. *width = info_ptr->scal_s_width;
  186372. *height = info_ptr->scal_s_height;
  186373. return (PNG_INFO_sCAL);
  186374. }
  186375. return(0);
  186376. }
  186377. #endif
  186378. #endif
  186379. #endif
  186380. #if defined(PNG_pHYs_SUPPORTED)
  186381. png_uint_32 PNGAPI
  186382. png_get_pHYs(png_structp png_ptr, png_infop info_ptr,
  186383. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  186384. {
  186385. png_uint_32 retval = 0;
  186386. if (png_ptr != NULL && info_ptr != NULL &&
  186387. (info_ptr->valid & PNG_INFO_pHYs))
  186388. {
  186389. png_debug1(1, "in %s retrieval function\n", "pHYs");
  186390. if (res_x != NULL)
  186391. {
  186392. *res_x = info_ptr->x_pixels_per_unit;
  186393. retval |= PNG_INFO_pHYs;
  186394. }
  186395. if (res_y != NULL)
  186396. {
  186397. *res_y = info_ptr->y_pixels_per_unit;
  186398. retval |= PNG_INFO_pHYs;
  186399. }
  186400. if (unit_type != NULL)
  186401. {
  186402. *unit_type = (int)info_ptr->phys_unit_type;
  186403. retval |= PNG_INFO_pHYs;
  186404. }
  186405. }
  186406. return (retval);
  186407. }
  186408. #endif
  186409. png_uint_32 PNGAPI
  186410. png_get_PLTE(png_structp png_ptr, png_infop info_ptr, png_colorp *palette,
  186411. int *num_palette)
  186412. {
  186413. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_PLTE)
  186414. && palette != NULL)
  186415. {
  186416. png_debug1(1, "in %s retrieval function\n", "PLTE");
  186417. *palette = info_ptr->palette;
  186418. *num_palette = info_ptr->num_palette;
  186419. png_debug1(3, "num_palette = %d\n", *num_palette);
  186420. return (PNG_INFO_PLTE);
  186421. }
  186422. return (0);
  186423. }
  186424. #if defined(PNG_sBIT_SUPPORTED)
  186425. png_uint_32 PNGAPI
  186426. png_get_sBIT(png_structp png_ptr, png_infop info_ptr, png_color_8p *sig_bit)
  186427. {
  186428. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT)
  186429. && sig_bit != NULL)
  186430. {
  186431. png_debug1(1, "in %s retrieval function\n", "sBIT");
  186432. *sig_bit = &(info_ptr->sig_bit);
  186433. return (PNG_INFO_sBIT);
  186434. }
  186435. return (0);
  186436. }
  186437. #endif
  186438. #if defined(PNG_TEXT_SUPPORTED)
  186439. png_uint_32 PNGAPI
  186440. png_get_text(png_structp png_ptr, png_infop info_ptr, png_textp *text_ptr,
  186441. int *num_text)
  186442. {
  186443. if (png_ptr != NULL && info_ptr != NULL && info_ptr->num_text > 0)
  186444. {
  186445. png_debug1(1, "in %s retrieval function\n",
  186446. (png_ptr->chunk_name[0] == '\0' ? "text"
  186447. : (png_const_charp)png_ptr->chunk_name));
  186448. if (text_ptr != NULL)
  186449. *text_ptr = info_ptr->text;
  186450. if (num_text != NULL)
  186451. *num_text = info_ptr->num_text;
  186452. return ((png_uint_32)info_ptr->num_text);
  186453. }
  186454. if (num_text != NULL)
  186455. *num_text = 0;
  186456. return(0);
  186457. }
  186458. #endif
  186459. #if defined(PNG_tIME_SUPPORTED)
  186460. png_uint_32 PNGAPI
  186461. png_get_tIME(png_structp png_ptr, png_infop info_ptr, png_timep *mod_time)
  186462. {
  186463. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME)
  186464. && mod_time != NULL)
  186465. {
  186466. png_debug1(1, "in %s retrieval function\n", "tIME");
  186467. *mod_time = &(info_ptr->mod_time);
  186468. return (PNG_INFO_tIME);
  186469. }
  186470. return (0);
  186471. }
  186472. #endif
  186473. #if defined(PNG_tRNS_SUPPORTED)
  186474. png_uint_32 PNGAPI
  186475. png_get_tRNS(png_structp png_ptr, png_infop info_ptr,
  186476. png_bytep *trans, int *num_trans, png_color_16p *trans_values)
  186477. {
  186478. png_uint_32 retval = 0;
  186479. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  186480. {
  186481. png_debug1(1, "in %s retrieval function\n", "tRNS");
  186482. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  186483. {
  186484. if (trans != NULL)
  186485. {
  186486. *trans = info_ptr->trans;
  186487. retval |= PNG_INFO_tRNS;
  186488. }
  186489. if (trans_values != NULL)
  186490. *trans_values = &(info_ptr->trans_values);
  186491. }
  186492. else /* if (info_ptr->color_type != PNG_COLOR_TYPE_PALETTE) */
  186493. {
  186494. if (trans_values != NULL)
  186495. {
  186496. *trans_values = &(info_ptr->trans_values);
  186497. retval |= PNG_INFO_tRNS;
  186498. }
  186499. if(trans != NULL)
  186500. *trans = NULL;
  186501. }
  186502. if(num_trans != NULL)
  186503. {
  186504. *num_trans = info_ptr->num_trans;
  186505. retval |= PNG_INFO_tRNS;
  186506. }
  186507. }
  186508. return (retval);
  186509. }
  186510. #endif
  186511. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  186512. png_uint_32 PNGAPI
  186513. png_get_unknown_chunks(png_structp png_ptr, png_infop info_ptr,
  186514. png_unknown_chunkpp unknowns)
  186515. {
  186516. if (png_ptr != NULL && info_ptr != NULL && unknowns != NULL)
  186517. {
  186518. *unknowns = info_ptr->unknown_chunks;
  186519. return ((png_uint_32)info_ptr->unknown_chunks_num);
  186520. }
  186521. return (0);
  186522. }
  186523. #endif
  186524. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  186525. png_byte PNGAPI
  186526. png_get_rgb_to_gray_status (png_structp png_ptr)
  186527. {
  186528. return (png_byte)(png_ptr? png_ptr->rgb_to_gray_status : 0);
  186529. }
  186530. #endif
  186531. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  186532. png_voidp PNGAPI
  186533. png_get_user_chunk_ptr(png_structp png_ptr)
  186534. {
  186535. return (png_ptr? png_ptr->user_chunk_ptr : NULL);
  186536. }
  186537. #endif
  186538. #ifdef PNG_WRITE_SUPPORTED
  186539. png_uint_32 PNGAPI
  186540. png_get_compression_buffer_size(png_structp png_ptr)
  186541. {
  186542. return (png_uint_32)(png_ptr? png_ptr->zbuf_size : 0L);
  186543. }
  186544. #endif
  186545. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  186546. #ifndef PNG_1_0_X
  186547. /* this function was added to libpng 1.2.0 and should exist by default */
  186548. png_uint_32 PNGAPI
  186549. png_get_asm_flags (png_structp png_ptr)
  186550. {
  186551. /* obsolete, to be removed from libpng-1.4.0 */
  186552. return (png_ptr? 0L: 0L);
  186553. }
  186554. /* this function was added to libpng 1.2.0 and should exist by default */
  186555. png_uint_32 PNGAPI
  186556. png_get_asm_flagmask (int flag_select)
  186557. {
  186558. /* obsolete, to be removed from libpng-1.4.0 */
  186559. flag_select=flag_select;
  186560. return 0L;
  186561. }
  186562. /* GRR: could add this: && defined(PNG_MMX_CODE_SUPPORTED) */
  186563. /* this function was added to libpng 1.2.0 */
  186564. png_uint_32 PNGAPI
  186565. png_get_mmx_flagmask (int flag_select, int *compilerID)
  186566. {
  186567. /* obsolete, to be removed from libpng-1.4.0 */
  186568. flag_select=flag_select;
  186569. *compilerID = -1; /* unknown (i.e., no asm/MMX code compiled) */
  186570. return 0L;
  186571. }
  186572. /* this function was added to libpng 1.2.0 */
  186573. png_byte PNGAPI
  186574. png_get_mmx_bitdepth_threshold (png_structp png_ptr)
  186575. {
  186576. /* obsolete, to be removed from libpng-1.4.0 */
  186577. return (png_ptr? 0: 0);
  186578. }
  186579. /* this function was added to libpng 1.2.0 */
  186580. png_uint_32 PNGAPI
  186581. png_get_mmx_rowbytes_threshold (png_structp png_ptr)
  186582. {
  186583. /* obsolete, to be removed from libpng-1.4.0 */
  186584. return (png_ptr? 0L: 0L);
  186585. }
  186586. #endif /* ?PNG_1_0_X */
  186587. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  186588. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  186589. /* these functions were added to libpng 1.2.6 */
  186590. png_uint_32 PNGAPI
  186591. png_get_user_width_max (png_structp png_ptr)
  186592. {
  186593. return (png_ptr? png_ptr->user_width_max : 0);
  186594. }
  186595. png_uint_32 PNGAPI
  186596. png_get_user_height_max (png_structp png_ptr)
  186597. {
  186598. return (png_ptr? png_ptr->user_height_max : 0);
  186599. }
  186600. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  186601. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  186602. /*** End of inlined file: pngget.c ***/
  186603. /*** Start of inlined file: pngmem.c ***/
  186604. /* pngmem.c - stub functions for memory allocation
  186605. *
  186606. * Last changed in libpng 1.2.13 November 13, 2006
  186607. * For conditions of distribution and use, see copyright notice in png.h
  186608. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  186609. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  186610. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  186611. *
  186612. * This file provides a location for all memory allocation. Users who
  186613. * need special memory handling are expected to supply replacement
  186614. * functions for png_malloc() and png_free(), and to use
  186615. * png_create_read_struct_2() and png_create_write_struct_2() to
  186616. * identify the replacement functions.
  186617. */
  186618. #define PNG_INTERNAL
  186619. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  186620. /* Borland DOS special memory handler */
  186621. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  186622. /* if you change this, be sure to change the one in png.h also */
  186623. /* Allocate memory for a png_struct. The malloc and memset can be replaced
  186624. by a single call to calloc() if this is thought to improve performance. */
  186625. png_voidp /* PRIVATE */
  186626. png_create_struct(int type)
  186627. {
  186628. #ifdef PNG_USER_MEM_SUPPORTED
  186629. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  186630. }
  186631. /* Alternate version of png_create_struct, for use with user-defined malloc. */
  186632. png_voidp /* PRIVATE */
  186633. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  186634. {
  186635. #endif /* PNG_USER_MEM_SUPPORTED */
  186636. png_size_t size;
  186637. png_voidp struct_ptr;
  186638. if (type == PNG_STRUCT_INFO)
  186639. size = png_sizeof(png_info);
  186640. else if (type == PNG_STRUCT_PNG)
  186641. size = png_sizeof(png_struct);
  186642. else
  186643. return (png_get_copyright(NULL));
  186644. #ifdef PNG_USER_MEM_SUPPORTED
  186645. if(malloc_fn != NULL)
  186646. {
  186647. png_struct dummy_struct;
  186648. png_structp png_ptr = &dummy_struct;
  186649. png_ptr->mem_ptr=mem_ptr;
  186650. struct_ptr = (*(malloc_fn))(png_ptr, (png_uint_32)size);
  186651. }
  186652. else
  186653. #endif /* PNG_USER_MEM_SUPPORTED */
  186654. struct_ptr = (png_voidp)farmalloc(size);
  186655. if (struct_ptr != NULL)
  186656. png_memset(struct_ptr, 0, size);
  186657. return (struct_ptr);
  186658. }
  186659. /* Free memory allocated by a png_create_struct() call */
  186660. void /* PRIVATE */
  186661. png_destroy_struct(png_voidp struct_ptr)
  186662. {
  186663. #ifdef PNG_USER_MEM_SUPPORTED
  186664. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  186665. }
  186666. /* Free memory allocated by a png_create_struct() call */
  186667. void /* PRIVATE */
  186668. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  186669. png_voidp mem_ptr)
  186670. {
  186671. #endif
  186672. if (struct_ptr != NULL)
  186673. {
  186674. #ifdef PNG_USER_MEM_SUPPORTED
  186675. if(free_fn != NULL)
  186676. {
  186677. png_struct dummy_struct;
  186678. png_structp png_ptr = &dummy_struct;
  186679. png_ptr->mem_ptr=mem_ptr;
  186680. (*(free_fn))(png_ptr, struct_ptr);
  186681. return;
  186682. }
  186683. #endif /* PNG_USER_MEM_SUPPORTED */
  186684. farfree (struct_ptr);
  186685. }
  186686. }
  186687. /* Allocate memory. For reasonable files, size should never exceed
  186688. * 64K. However, zlib may allocate more then 64K if you don't tell
  186689. * it not to. See zconf.h and png.h for more information. zlib does
  186690. * need to allocate exactly 64K, so whatever you call here must
  186691. * have the ability to do that.
  186692. *
  186693. * Borland seems to have a problem in DOS mode for exactly 64K.
  186694. * It gives you a segment with an offset of 8 (perhaps to store its
  186695. * memory stuff). zlib doesn't like this at all, so we have to
  186696. * detect and deal with it. This code should not be needed in
  186697. * Windows or OS/2 modes, and only in 16 bit mode. This code has
  186698. * been updated by Alexander Lehmann for version 0.89 to waste less
  186699. * memory.
  186700. *
  186701. * Note that we can't use png_size_t for the "size" declaration,
  186702. * since on some systems a png_size_t is a 16-bit quantity, and as a
  186703. * result, we would be truncating potentially larger memory requests
  186704. * (which should cause a fatal error) and introducing major problems.
  186705. */
  186706. png_voidp PNGAPI
  186707. png_malloc(png_structp png_ptr, png_uint_32 size)
  186708. {
  186709. png_voidp ret;
  186710. if (png_ptr == NULL || size == 0)
  186711. return (NULL);
  186712. #ifdef PNG_USER_MEM_SUPPORTED
  186713. if(png_ptr->malloc_fn != NULL)
  186714. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  186715. else
  186716. ret = (png_malloc_default(png_ptr, size));
  186717. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186718. png_error(png_ptr, "Out of memory!");
  186719. return (ret);
  186720. }
  186721. png_voidp PNGAPI
  186722. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  186723. {
  186724. png_voidp ret;
  186725. #endif /* PNG_USER_MEM_SUPPORTED */
  186726. if (png_ptr == NULL || size == 0)
  186727. return (NULL);
  186728. #ifdef PNG_MAX_MALLOC_64K
  186729. if (size > (png_uint_32)65536L)
  186730. {
  186731. png_warning(png_ptr, "Cannot Allocate > 64K");
  186732. ret = NULL;
  186733. }
  186734. else
  186735. #endif
  186736. if (size != (size_t)size)
  186737. ret = NULL;
  186738. else if (size == (png_uint_32)65536L)
  186739. {
  186740. if (png_ptr->offset_table == NULL)
  186741. {
  186742. /* try to see if we need to do any of this fancy stuff */
  186743. ret = farmalloc(size);
  186744. if (ret == NULL || ((png_size_t)ret & 0xffff))
  186745. {
  186746. int num_blocks;
  186747. png_uint_32 total_size;
  186748. png_bytep table;
  186749. int i;
  186750. png_byte huge * hptr;
  186751. if (ret != NULL)
  186752. {
  186753. farfree(ret);
  186754. ret = NULL;
  186755. }
  186756. if(png_ptr->zlib_window_bits > 14)
  186757. num_blocks = (int)(1 << (png_ptr->zlib_window_bits - 14));
  186758. else
  186759. num_blocks = 1;
  186760. if (png_ptr->zlib_mem_level >= 7)
  186761. num_blocks += (int)(1 << (png_ptr->zlib_mem_level - 7));
  186762. else
  186763. num_blocks++;
  186764. total_size = ((png_uint_32)65536L) * (png_uint_32)num_blocks+16;
  186765. table = farmalloc(total_size);
  186766. if (table == NULL)
  186767. {
  186768. #ifndef PNG_USER_MEM_SUPPORTED
  186769. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186770. png_error(png_ptr, "Out Of Memory."); /* Note "O" and "M" */
  186771. else
  186772. png_warning(png_ptr, "Out Of Memory.");
  186773. #endif
  186774. return (NULL);
  186775. }
  186776. if ((png_size_t)table & 0xfff0)
  186777. {
  186778. #ifndef PNG_USER_MEM_SUPPORTED
  186779. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186780. png_error(png_ptr,
  186781. "Farmalloc didn't return normalized pointer");
  186782. else
  186783. png_warning(png_ptr,
  186784. "Farmalloc didn't return normalized pointer");
  186785. #endif
  186786. return (NULL);
  186787. }
  186788. png_ptr->offset_table = table;
  186789. png_ptr->offset_table_ptr = farmalloc(num_blocks *
  186790. png_sizeof (png_bytep));
  186791. if (png_ptr->offset_table_ptr == NULL)
  186792. {
  186793. #ifndef PNG_USER_MEM_SUPPORTED
  186794. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186795. png_error(png_ptr, "Out Of memory."); /* Note "O" and "M" */
  186796. else
  186797. png_warning(png_ptr, "Out Of memory.");
  186798. #endif
  186799. return (NULL);
  186800. }
  186801. hptr = (png_byte huge *)table;
  186802. if ((png_size_t)hptr & 0xf)
  186803. {
  186804. hptr = (png_byte huge *)((long)(hptr) & 0xfffffff0L);
  186805. hptr = hptr + 16L; /* "hptr += 16L" fails on Turbo C++ 3.0 */
  186806. }
  186807. for (i = 0; i < num_blocks; i++)
  186808. {
  186809. png_ptr->offset_table_ptr[i] = (png_bytep)hptr;
  186810. hptr = hptr + (png_uint_32)65536L; /* "+=" fails on TC++3.0 */
  186811. }
  186812. png_ptr->offset_table_number = num_blocks;
  186813. png_ptr->offset_table_count = 0;
  186814. png_ptr->offset_table_count_free = 0;
  186815. }
  186816. }
  186817. if (png_ptr->offset_table_count >= png_ptr->offset_table_number)
  186818. {
  186819. #ifndef PNG_USER_MEM_SUPPORTED
  186820. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186821. png_error(png_ptr, "Out of Memory."); /* Note "o" and "M" */
  186822. else
  186823. png_warning(png_ptr, "Out of Memory.");
  186824. #endif
  186825. return (NULL);
  186826. }
  186827. ret = png_ptr->offset_table_ptr[png_ptr->offset_table_count++];
  186828. }
  186829. else
  186830. ret = farmalloc(size);
  186831. #ifndef PNG_USER_MEM_SUPPORTED
  186832. if (ret == NULL)
  186833. {
  186834. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186835. png_error(png_ptr, "Out of memory."); /* Note "o" and "m" */
  186836. else
  186837. png_warning(png_ptr, "Out of memory."); /* Note "o" and "m" */
  186838. }
  186839. #endif
  186840. return (ret);
  186841. }
  186842. /* free a pointer allocated by png_malloc(). In the default
  186843. configuration, png_ptr is not used, but is passed in case it
  186844. is needed. If ptr is NULL, return without taking any action. */
  186845. void PNGAPI
  186846. png_free(png_structp png_ptr, png_voidp ptr)
  186847. {
  186848. if (png_ptr == NULL || ptr == NULL)
  186849. return;
  186850. #ifdef PNG_USER_MEM_SUPPORTED
  186851. if (png_ptr->free_fn != NULL)
  186852. {
  186853. (*(png_ptr->free_fn))(png_ptr, ptr);
  186854. return;
  186855. }
  186856. else png_free_default(png_ptr, ptr);
  186857. }
  186858. void PNGAPI
  186859. png_free_default(png_structp png_ptr, png_voidp ptr)
  186860. {
  186861. #endif /* PNG_USER_MEM_SUPPORTED */
  186862. if(png_ptr == NULL) return;
  186863. if (png_ptr->offset_table != NULL)
  186864. {
  186865. int i;
  186866. for (i = 0; i < png_ptr->offset_table_count; i++)
  186867. {
  186868. if (ptr == png_ptr->offset_table_ptr[i])
  186869. {
  186870. ptr = NULL;
  186871. png_ptr->offset_table_count_free++;
  186872. break;
  186873. }
  186874. }
  186875. if (png_ptr->offset_table_count_free == png_ptr->offset_table_count)
  186876. {
  186877. farfree(png_ptr->offset_table);
  186878. farfree(png_ptr->offset_table_ptr);
  186879. png_ptr->offset_table = NULL;
  186880. png_ptr->offset_table_ptr = NULL;
  186881. }
  186882. }
  186883. if (ptr != NULL)
  186884. {
  186885. farfree(ptr);
  186886. }
  186887. }
  186888. #else /* Not the Borland DOS special memory handler */
  186889. /* Allocate memory for a png_struct or a png_info. The malloc and
  186890. memset can be replaced by a single call to calloc() if this is thought
  186891. to improve performance noticably. */
  186892. png_voidp /* PRIVATE */
  186893. png_create_struct(int type)
  186894. {
  186895. #ifdef PNG_USER_MEM_SUPPORTED
  186896. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  186897. }
  186898. /* Allocate memory for a png_struct or a png_info. The malloc and
  186899. memset can be replaced by a single call to calloc() if this is thought
  186900. to improve performance noticably. */
  186901. png_voidp /* PRIVATE */
  186902. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  186903. {
  186904. #endif /* PNG_USER_MEM_SUPPORTED */
  186905. png_size_t size;
  186906. png_voidp struct_ptr;
  186907. if (type == PNG_STRUCT_INFO)
  186908. size = png_sizeof(png_info);
  186909. else if (type == PNG_STRUCT_PNG)
  186910. size = png_sizeof(png_struct);
  186911. else
  186912. return (NULL);
  186913. #ifdef PNG_USER_MEM_SUPPORTED
  186914. if(malloc_fn != NULL)
  186915. {
  186916. png_struct dummy_struct;
  186917. png_structp png_ptr = &dummy_struct;
  186918. png_ptr->mem_ptr=mem_ptr;
  186919. struct_ptr = (*(malloc_fn))(png_ptr, size);
  186920. if (struct_ptr != NULL)
  186921. png_memset(struct_ptr, 0, size);
  186922. return (struct_ptr);
  186923. }
  186924. #endif /* PNG_USER_MEM_SUPPORTED */
  186925. #if defined(__TURBOC__) && !defined(__FLAT__)
  186926. struct_ptr = (png_voidp)farmalloc(size);
  186927. #else
  186928. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186929. struct_ptr = (png_voidp)halloc(size,1);
  186930. # else
  186931. struct_ptr = (png_voidp)malloc(size);
  186932. # endif
  186933. #endif
  186934. if (struct_ptr != NULL)
  186935. png_memset(struct_ptr, 0, size);
  186936. return (struct_ptr);
  186937. }
  186938. /* Free memory allocated by a png_create_struct() call */
  186939. void /* PRIVATE */
  186940. png_destroy_struct(png_voidp struct_ptr)
  186941. {
  186942. #ifdef PNG_USER_MEM_SUPPORTED
  186943. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  186944. }
  186945. /* Free memory allocated by a png_create_struct() call */
  186946. void /* PRIVATE */
  186947. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  186948. png_voidp mem_ptr)
  186949. {
  186950. #endif /* PNG_USER_MEM_SUPPORTED */
  186951. if (struct_ptr != NULL)
  186952. {
  186953. #ifdef PNG_USER_MEM_SUPPORTED
  186954. if(free_fn != NULL)
  186955. {
  186956. png_struct dummy_struct;
  186957. png_structp png_ptr = &dummy_struct;
  186958. png_ptr->mem_ptr=mem_ptr;
  186959. (*(free_fn))(png_ptr, struct_ptr);
  186960. return;
  186961. }
  186962. #endif /* PNG_USER_MEM_SUPPORTED */
  186963. #if defined(__TURBOC__) && !defined(__FLAT__)
  186964. farfree(struct_ptr);
  186965. #else
  186966. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186967. hfree(struct_ptr);
  186968. # else
  186969. free(struct_ptr);
  186970. # endif
  186971. #endif
  186972. }
  186973. }
  186974. /* Allocate memory. For reasonable files, size should never exceed
  186975. 64K. However, zlib may allocate more then 64K if you don't tell
  186976. it not to. See zconf.h and png.h for more information. zlib does
  186977. need to allocate exactly 64K, so whatever you call here must
  186978. have the ability to do that. */
  186979. png_voidp PNGAPI
  186980. png_malloc(png_structp png_ptr, png_uint_32 size)
  186981. {
  186982. png_voidp ret;
  186983. #ifdef PNG_USER_MEM_SUPPORTED
  186984. if (png_ptr == NULL || size == 0)
  186985. return (NULL);
  186986. if(png_ptr->malloc_fn != NULL)
  186987. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  186988. else
  186989. ret = (png_malloc_default(png_ptr, size));
  186990. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186991. png_error(png_ptr, "Out of Memory!");
  186992. return (ret);
  186993. }
  186994. png_voidp PNGAPI
  186995. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  186996. {
  186997. png_voidp ret;
  186998. #endif /* PNG_USER_MEM_SUPPORTED */
  186999. if (png_ptr == NULL || size == 0)
  187000. return (NULL);
  187001. #ifdef PNG_MAX_MALLOC_64K
  187002. if (size > (png_uint_32)65536L)
  187003. {
  187004. #ifndef PNG_USER_MEM_SUPPORTED
  187005. if(png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  187006. png_error(png_ptr, "Cannot Allocate > 64K");
  187007. else
  187008. #endif
  187009. return NULL;
  187010. }
  187011. #endif
  187012. /* Check for overflow */
  187013. #if defined(__TURBOC__) && !defined(__FLAT__)
  187014. if (size != (unsigned long)size)
  187015. ret = NULL;
  187016. else
  187017. ret = farmalloc(size);
  187018. #else
  187019. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  187020. if (size != (unsigned long)size)
  187021. ret = NULL;
  187022. else
  187023. ret = halloc(size, 1);
  187024. # else
  187025. if (size != (size_t)size)
  187026. ret = NULL;
  187027. else
  187028. ret = malloc((size_t)size);
  187029. # endif
  187030. #endif
  187031. #ifndef PNG_USER_MEM_SUPPORTED
  187032. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  187033. png_error(png_ptr, "Out of Memory");
  187034. #endif
  187035. return (ret);
  187036. }
  187037. /* Free a pointer allocated by png_malloc(). If ptr is NULL, return
  187038. without taking any action. */
  187039. void PNGAPI
  187040. png_free(png_structp png_ptr, png_voidp ptr)
  187041. {
  187042. if (png_ptr == NULL || ptr == NULL)
  187043. return;
  187044. #ifdef PNG_USER_MEM_SUPPORTED
  187045. if (png_ptr->free_fn != NULL)
  187046. {
  187047. (*(png_ptr->free_fn))(png_ptr, ptr);
  187048. return;
  187049. }
  187050. else png_free_default(png_ptr, ptr);
  187051. }
  187052. void PNGAPI
  187053. png_free_default(png_structp png_ptr, png_voidp ptr)
  187054. {
  187055. if (png_ptr == NULL || ptr == NULL)
  187056. return;
  187057. #endif /* PNG_USER_MEM_SUPPORTED */
  187058. #if defined(__TURBOC__) && !defined(__FLAT__)
  187059. farfree(ptr);
  187060. #else
  187061. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  187062. hfree(ptr);
  187063. # else
  187064. free(ptr);
  187065. # endif
  187066. #endif
  187067. }
  187068. #endif /* Not Borland DOS special memory handler */
  187069. #if defined(PNG_1_0_X)
  187070. # define png_malloc_warn png_malloc
  187071. #else
  187072. /* This function was added at libpng version 1.2.3. The png_malloc_warn()
  187073. * function will set up png_malloc() to issue a png_warning and return NULL
  187074. * instead of issuing a png_error, if it fails to allocate the requested
  187075. * memory.
  187076. */
  187077. png_voidp PNGAPI
  187078. png_malloc_warn(png_structp png_ptr, png_uint_32 size)
  187079. {
  187080. png_voidp ptr;
  187081. png_uint_32 save_flags;
  187082. if(png_ptr == NULL) return (NULL);
  187083. save_flags=png_ptr->flags;
  187084. png_ptr->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  187085. ptr = (png_voidp)png_malloc((png_structp)png_ptr, size);
  187086. png_ptr->flags=save_flags;
  187087. return(ptr);
  187088. }
  187089. #endif
  187090. png_voidp PNGAPI
  187091. png_memcpy_check (png_structp png_ptr, png_voidp s1, png_voidp s2,
  187092. png_uint_32 length)
  187093. {
  187094. png_size_t size;
  187095. size = (png_size_t)length;
  187096. if ((png_uint_32)size != length)
  187097. png_error(png_ptr,"Overflow in png_memcpy_check.");
  187098. return(png_memcpy (s1, s2, size));
  187099. }
  187100. png_voidp PNGAPI
  187101. png_memset_check (png_structp png_ptr, png_voidp s1, int value,
  187102. png_uint_32 length)
  187103. {
  187104. png_size_t size;
  187105. size = (png_size_t)length;
  187106. if ((png_uint_32)size != length)
  187107. png_error(png_ptr,"Overflow in png_memset_check.");
  187108. return (png_memset (s1, value, size));
  187109. }
  187110. #ifdef PNG_USER_MEM_SUPPORTED
  187111. /* This function is called when the application wants to use another method
  187112. * of allocating and freeing memory.
  187113. */
  187114. void PNGAPI
  187115. png_set_mem_fn(png_structp png_ptr, png_voidp mem_ptr, png_malloc_ptr
  187116. malloc_fn, png_free_ptr free_fn)
  187117. {
  187118. if(png_ptr != NULL) {
  187119. png_ptr->mem_ptr = mem_ptr;
  187120. png_ptr->malloc_fn = malloc_fn;
  187121. png_ptr->free_fn = free_fn;
  187122. }
  187123. }
  187124. /* This function returns a pointer to the mem_ptr associated with the user
  187125. * functions. The application should free any memory associated with this
  187126. * pointer before png_write_destroy and png_read_destroy are called.
  187127. */
  187128. png_voidp PNGAPI
  187129. png_get_mem_ptr(png_structp png_ptr)
  187130. {
  187131. if(png_ptr == NULL) return (NULL);
  187132. return ((png_voidp)png_ptr->mem_ptr);
  187133. }
  187134. #endif /* PNG_USER_MEM_SUPPORTED */
  187135. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  187136. /*** End of inlined file: pngmem.c ***/
  187137. /*** Start of inlined file: pngread.c ***/
  187138. /* pngread.c - read a PNG file
  187139. *
  187140. * Last changed in libpng 1.2.20 September 7, 2007
  187141. * For conditions of distribution and use, see copyright notice in png.h
  187142. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  187143. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  187144. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  187145. *
  187146. * This file contains routines that an application calls directly to
  187147. * read a PNG file or stream.
  187148. */
  187149. #define PNG_INTERNAL
  187150. #if defined(PNG_READ_SUPPORTED)
  187151. /* Create a PNG structure for reading, and allocate any memory needed. */
  187152. png_structp PNGAPI
  187153. png_create_read_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  187154. png_error_ptr error_fn, png_error_ptr warn_fn)
  187155. {
  187156. #ifdef PNG_USER_MEM_SUPPORTED
  187157. return (png_create_read_struct_2(user_png_ver, error_ptr, error_fn,
  187158. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  187159. }
  187160. /* Alternate create PNG structure for reading, and allocate any memory needed. */
  187161. png_structp PNGAPI
  187162. png_create_read_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  187163. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  187164. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  187165. {
  187166. #endif /* PNG_USER_MEM_SUPPORTED */
  187167. png_structp png_ptr;
  187168. #ifdef PNG_SETJMP_SUPPORTED
  187169. #ifdef USE_FAR_KEYWORD
  187170. jmp_buf jmpbuf;
  187171. #endif
  187172. #endif
  187173. int i;
  187174. png_debug(1, "in png_create_read_struct\n");
  187175. #ifdef PNG_USER_MEM_SUPPORTED
  187176. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  187177. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  187178. #else
  187179. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  187180. #endif
  187181. if (png_ptr == NULL)
  187182. return (NULL);
  187183. /* added at libpng-1.2.6 */
  187184. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  187185. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  187186. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  187187. #endif
  187188. #ifdef PNG_SETJMP_SUPPORTED
  187189. #ifdef USE_FAR_KEYWORD
  187190. if (setjmp(jmpbuf))
  187191. #else
  187192. if (setjmp(png_ptr->jmpbuf))
  187193. #endif
  187194. {
  187195. png_free(png_ptr, png_ptr->zbuf);
  187196. png_ptr->zbuf=NULL;
  187197. #ifdef PNG_USER_MEM_SUPPORTED
  187198. png_destroy_struct_2((png_voidp)png_ptr,
  187199. (png_free_ptr)free_fn, (png_voidp)mem_ptr);
  187200. #else
  187201. png_destroy_struct((png_voidp)png_ptr);
  187202. #endif
  187203. return (NULL);
  187204. }
  187205. #ifdef USE_FAR_KEYWORD
  187206. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  187207. #endif
  187208. #endif
  187209. #ifdef PNG_USER_MEM_SUPPORTED
  187210. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  187211. #endif
  187212. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  187213. i=0;
  187214. do
  187215. {
  187216. if(user_png_ver[i] != png_libpng_ver[i])
  187217. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  187218. } while (png_libpng_ver[i++]);
  187219. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  187220. {
  187221. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  187222. * we must recompile any applications that use any older library version.
  187223. * For versions after libpng 1.0, we will be compatible, so we need
  187224. * only check the first digit.
  187225. */
  187226. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  187227. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  187228. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  187229. {
  187230. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  187231. char msg[80];
  187232. if (user_png_ver)
  187233. {
  187234. png_snprintf(msg, 80,
  187235. "Application was compiled with png.h from libpng-%.20s",
  187236. user_png_ver);
  187237. png_warning(png_ptr, msg);
  187238. }
  187239. png_snprintf(msg, 80,
  187240. "Application is running with png.c from libpng-%.20s",
  187241. png_libpng_ver);
  187242. png_warning(png_ptr, msg);
  187243. #endif
  187244. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  187245. png_ptr->flags=0;
  187246. #endif
  187247. png_error(png_ptr,
  187248. "Incompatible libpng version in application and library");
  187249. }
  187250. }
  187251. /* initialize zbuf - compression buffer */
  187252. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  187253. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  187254. (png_uint_32)png_ptr->zbuf_size);
  187255. png_ptr->zstream.zalloc = png_zalloc;
  187256. png_ptr->zstream.zfree = png_zfree;
  187257. png_ptr->zstream.opaque = (voidpf)png_ptr;
  187258. switch (inflateInit(&png_ptr->zstream))
  187259. {
  187260. case Z_OK: /* Do nothing */ break;
  187261. case Z_MEM_ERROR:
  187262. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory error"); break;
  187263. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version error"); break;
  187264. default: png_error(png_ptr, "Unknown zlib error");
  187265. }
  187266. png_ptr->zstream.next_out = png_ptr->zbuf;
  187267. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  187268. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  187269. #ifdef PNG_SETJMP_SUPPORTED
  187270. /* Applications that neglect to set up their own setjmp() and then encounter
  187271. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  187272. abort instead of returning. */
  187273. #ifdef USE_FAR_KEYWORD
  187274. if (setjmp(jmpbuf))
  187275. PNG_ABORT();
  187276. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  187277. #else
  187278. if (setjmp(png_ptr->jmpbuf))
  187279. PNG_ABORT();
  187280. #endif
  187281. #endif
  187282. return (png_ptr);
  187283. }
  187284. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  187285. /* Initialize PNG structure for reading, and allocate any memory needed.
  187286. This interface is deprecated in favour of the png_create_read_struct(),
  187287. and it will disappear as of libpng-1.3.0. */
  187288. #undef png_read_init
  187289. void PNGAPI
  187290. png_read_init(png_structp png_ptr)
  187291. {
  187292. /* We only come here via pre-1.0.7-compiled applications */
  187293. png_read_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  187294. }
  187295. void PNGAPI
  187296. png_read_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  187297. png_size_t png_struct_size, png_size_t png_info_size)
  187298. {
  187299. /* We only come here via pre-1.0.12-compiled applications */
  187300. if(png_ptr == NULL) return;
  187301. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  187302. if(png_sizeof(png_struct) > png_struct_size ||
  187303. png_sizeof(png_info) > png_info_size)
  187304. {
  187305. char msg[80];
  187306. png_ptr->warning_fn=NULL;
  187307. if (user_png_ver)
  187308. {
  187309. png_snprintf(msg, 80,
  187310. "Application was compiled with png.h from libpng-%.20s",
  187311. user_png_ver);
  187312. png_warning(png_ptr, msg);
  187313. }
  187314. png_snprintf(msg, 80,
  187315. "Application is running with png.c from libpng-%.20s",
  187316. png_libpng_ver);
  187317. png_warning(png_ptr, msg);
  187318. }
  187319. #endif
  187320. if(png_sizeof(png_struct) > png_struct_size)
  187321. {
  187322. png_ptr->error_fn=NULL;
  187323. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  187324. png_ptr->flags=0;
  187325. #endif
  187326. png_error(png_ptr,
  187327. "The png struct allocated by the application for reading is too small.");
  187328. }
  187329. if(png_sizeof(png_info) > png_info_size)
  187330. {
  187331. png_ptr->error_fn=NULL;
  187332. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  187333. png_ptr->flags=0;
  187334. #endif
  187335. png_error(png_ptr,
  187336. "The info struct allocated by application for reading is too small.");
  187337. }
  187338. png_read_init_3(&png_ptr, user_png_ver, png_struct_size);
  187339. }
  187340. #endif /* PNG_1_0_X || PNG_1_2_X */
  187341. void PNGAPI
  187342. png_read_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  187343. png_size_t png_struct_size)
  187344. {
  187345. #ifdef PNG_SETJMP_SUPPORTED
  187346. jmp_buf tmp_jmp; /* to save current jump buffer */
  187347. #endif
  187348. int i=0;
  187349. png_structp png_ptr=*ptr_ptr;
  187350. if(png_ptr == NULL) return;
  187351. do
  187352. {
  187353. if(user_png_ver[i] != png_libpng_ver[i])
  187354. {
  187355. #ifdef PNG_LEGACY_SUPPORTED
  187356. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  187357. #else
  187358. png_ptr->warning_fn=NULL;
  187359. png_warning(png_ptr,
  187360. "Application uses deprecated png_read_init() and should be recompiled.");
  187361. break;
  187362. #endif
  187363. }
  187364. } while (png_libpng_ver[i++]);
  187365. png_debug(1, "in png_read_init_3\n");
  187366. #ifdef PNG_SETJMP_SUPPORTED
  187367. /* save jump buffer and error functions */
  187368. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  187369. #endif
  187370. if(png_sizeof(png_struct) > png_struct_size)
  187371. {
  187372. png_destroy_struct(png_ptr);
  187373. *ptr_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  187374. png_ptr = *ptr_ptr;
  187375. }
  187376. /* reset all variables to 0 */
  187377. png_memset(png_ptr, 0, png_sizeof (png_struct));
  187378. #ifdef PNG_SETJMP_SUPPORTED
  187379. /* restore jump buffer */
  187380. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  187381. #endif
  187382. /* added at libpng-1.2.6 */
  187383. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  187384. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  187385. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  187386. #endif
  187387. /* initialize zbuf - compression buffer */
  187388. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  187389. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  187390. (png_uint_32)png_ptr->zbuf_size);
  187391. png_ptr->zstream.zalloc = png_zalloc;
  187392. png_ptr->zstream.zfree = png_zfree;
  187393. png_ptr->zstream.opaque = (voidpf)png_ptr;
  187394. switch (inflateInit(&png_ptr->zstream))
  187395. {
  187396. case Z_OK: /* Do nothing */ break;
  187397. case Z_MEM_ERROR:
  187398. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory"); break;
  187399. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version"); break;
  187400. default: png_error(png_ptr, "Unknown zlib error");
  187401. }
  187402. png_ptr->zstream.next_out = png_ptr->zbuf;
  187403. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  187404. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  187405. }
  187406. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187407. /* Read the information before the actual image data. This has been
  187408. * changed in v0.90 to allow reading a file that already has the magic
  187409. * bytes read from the stream. You can tell libpng how many bytes have
  187410. * been read from the beginning of the stream (up to the maximum of 8)
  187411. * via png_set_sig_bytes(), and we will only check the remaining bytes
  187412. * here. The application can then have access to the signature bytes we
  187413. * read if it is determined that this isn't a valid PNG file.
  187414. */
  187415. void PNGAPI
  187416. png_read_info(png_structp png_ptr, png_infop info_ptr)
  187417. {
  187418. if(png_ptr == NULL) return;
  187419. png_debug(1, "in png_read_info\n");
  187420. /* If we haven't checked all of the PNG signature bytes, do so now. */
  187421. if (png_ptr->sig_bytes < 8)
  187422. {
  187423. png_size_t num_checked = png_ptr->sig_bytes,
  187424. num_to_check = 8 - num_checked;
  187425. png_read_data(png_ptr, &(info_ptr->signature[num_checked]), num_to_check);
  187426. png_ptr->sig_bytes = 8;
  187427. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  187428. {
  187429. if (num_checked < 4 &&
  187430. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  187431. png_error(png_ptr, "Not a PNG file");
  187432. else
  187433. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  187434. }
  187435. if (num_checked < 3)
  187436. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  187437. }
  187438. for(;;)
  187439. {
  187440. #ifdef PNG_USE_LOCAL_ARRAYS
  187441. PNG_CONST PNG_IHDR;
  187442. PNG_CONST PNG_IDAT;
  187443. PNG_CONST PNG_IEND;
  187444. PNG_CONST PNG_PLTE;
  187445. #if defined(PNG_READ_bKGD_SUPPORTED)
  187446. PNG_CONST PNG_bKGD;
  187447. #endif
  187448. #if defined(PNG_READ_cHRM_SUPPORTED)
  187449. PNG_CONST PNG_cHRM;
  187450. #endif
  187451. #if defined(PNG_READ_gAMA_SUPPORTED)
  187452. PNG_CONST PNG_gAMA;
  187453. #endif
  187454. #if defined(PNG_READ_hIST_SUPPORTED)
  187455. PNG_CONST PNG_hIST;
  187456. #endif
  187457. #if defined(PNG_READ_iCCP_SUPPORTED)
  187458. PNG_CONST PNG_iCCP;
  187459. #endif
  187460. #if defined(PNG_READ_iTXt_SUPPORTED)
  187461. PNG_CONST PNG_iTXt;
  187462. #endif
  187463. #if defined(PNG_READ_oFFs_SUPPORTED)
  187464. PNG_CONST PNG_oFFs;
  187465. #endif
  187466. #if defined(PNG_READ_pCAL_SUPPORTED)
  187467. PNG_CONST PNG_pCAL;
  187468. #endif
  187469. #if defined(PNG_READ_pHYs_SUPPORTED)
  187470. PNG_CONST PNG_pHYs;
  187471. #endif
  187472. #if defined(PNG_READ_sBIT_SUPPORTED)
  187473. PNG_CONST PNG_sBIT;
  187474. #endif
  187475. #if defined(PNG_READ_sCAL_SUPPORTED)
  187476. PNG_CONST PNG_sCAL;
  187477. #endif
  187478. #if defined(PNG_READ_sPLT_SUPPORTED)
  187479. PNG_CONST PNG_sPLT;
  187480. #endif
  187481. #if defined(PNG_READ_sRGB_SUPPORTED)
  187482. PNG_CONST PNG_sRGB;
  187483. #endif
  187484. #if defined(PNG_READ_tEXt_SUPPORTED)
  187485. PNG_CONST PNG_tEXt;
  187486. #endif
  187487. #if defined(PNG_READ_tIME_SUPPORTED)
  187488. PNG_CONST PNG_tIME;
  187489. #endif
  187490. #if defined(PNG_READ_tRNS_SUPPORTED)
  187491. PNG_CONST PNG_tRNS;
  187492. #endif
  187493. #if defined(PNG_READ_zTXt_SUPPORTED)
  187494. PNG_CONST PNG_zTXt;
  187495. #endif
  187496. #endif /* PNG_USE_LOCAL_ARRAYS */
  187497. png_byte chunk_length[4];
  187498. png_uint_32 length;
  187499. png_read_data(png_ptr, chunk_length, 4);
  187500. length = png_get_uint_31(png_ptr,chunk_length);
  187501. png_reset_crc(png_ptr);
  187502. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187503. png_debug2(0, "Reading %s chunk, length=%lu.\n", png_ptr->chunk_name,
  187504. length);
  187505. /* This should be a binary subdivision search or a hash for
  187506. * matching the chunk name rather than a linear search.
  187507. */
  187508. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187509. if(png_ptr->mode & PNG_AFTER_IDAT)
  187510. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  187511. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  187512. png_handle_IHDR(png_ptr, info_ptr, length);
  187513. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  187514. png_handle_IEND(png_ptr, info_ptr, length);
  187515. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  187516. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  187517. {
  187518. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187519. png_ptr->mode |= PNG_HAVE_IDAT;
  187520. png_handle_unknown(png_ptr, info_ptr, length);
  187521. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187522. png_ptr->mode |= PNG_HAVE_PLTE;
  187523. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187524. {
  187525. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  187526. png_error(png_ptr, "Missing IHDR before IDAT");
  187527. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  187528. !(png_ptr->mode & PNG_HAVE_PLTE))
  187529. png_error(png_ptr, "Missing PLTE before IDAT");
  187530. break;
  187531. }
  187532. }
  187533. #endif
  187534. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187535. png_handle_PLTE(png_ptr, info_ptr, length);
  187536. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187537. {
  187538. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  187539. png_error(png_ptr, "Missing IHDR before IDAT");
  187540. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  187541. !(png_ptr->mode & PNG_HAVE_PLTE))
  187542. png_error(png_ptr, "Missing PLTE before IDAT");
  187543. png_ptr->idat_size = length;
  187544. png_ptr->mode |= PNG_HAVE_IDAT;
  187545. break;
  187546. }
  187547. #if defined(PNG_READ_bKGD_SUPPORTED)
  187548. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  187549. png_handle_bKGD(png_ptr, info_ptr, length);
  187550. #endif
  187551. #if defined(PNG_READ_cHRM_SUPPORTED)
  187552. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  187553. png_handle_cHRM(png_ptr, info_ptr, length);
  187554. #endif
  187555. #if defined(PNG_READ_gAMA_SUPPORTED)
  187556. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  187557. png_handle_gAMA(png_ptr, info_ptr, length);
  187558. #endif
  187559. #if defined(PNG_READ_hIST_SUPPORTED)
  187560. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  187561. png_handle_hIST(png_ptr, info_ptr, length);
  187562. #endif
  187563. #if defined(PNG_READ_oFFs_SUPPORTED)
  187564. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  187565. png_handle_oFFs(png_ptr, info_ptr, length);
  187566. #endif
  187567. #if defined(PNG_READ_pCAL_SUPPORTED)
  187568. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  187569. png_handle_pCAL(png_ptr, info_ptr, length);
  187570. #endif
  187571. #if defined(PNG_READ_sCAL_SUPPORTED)
  187572. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  187573. png_handle_sCAL(png_ptr, info_ptr, length);
  187574. #endif
  187575. #if defined(PNG_READ_pHYs_SUPPORTED)
  187576. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  187577. png_handle_pHYs(png_ptr, info_ptr, length);
  187578. #endif
  187579. #if defined(PNG_READ_sBIT_SUPPORTED)
  187580. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  187581. png_handle_sBIT(png_ptr, info_ptr, length);
  187582. #endif
  187583. #if defined(PNG_READ_sRGB_SUPPORTED)
  187584. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  187585. png_handle_sRGB(png_ptr, info_ptr, length);
  187586. #endif
  187587. #if defined(PNG_READ_iCCP_SUPPORTED)
  187588. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  187589. png_handle_iCCP(png_ptr, info_ptr, length);
  187590. #endif
  187591. #if defined(PNG_READ_sPLT_SUPPORTED)
  187592. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  187593. png_handle_sPLT(png_ptr, info_ptr, length);
  187594. #endif
  187595. #if defined(PNG_READ_tEXt_SUPPORTED)
  187596. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  187597. png_handle_tEXt(png_ptr, info_ptr, length);
  187598. #endif
  187599. #if defined(PNG_READ_tIME_SUPPORTED)
  187600. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  187601. png_handle_tIME(png_ptr, info_ptr, length);
  187602. #endif
  187603. #if defined(PNG_READ_tRNS_SUPPORTED)
  187604. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  187605. png_handle_tRNS(png_ptr, info_ptr, length);
  187606. #endif
  187607. #if defined(PNG_READ_zTXt_SUPPORTED)
  187608. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  187609. png_handle_zTXt(png_ptr, info_ptr, length);
  187610. #endif
  187611. #if defined(PNG_READ_iTXt_SUPPORTED)
  187612. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  187613. png_handle_iTXt(png_ptr, info_ptr, length);
  187614. #endif
  187615. else
  187616. png_handle_unknown(png_ptr, info_ptr, length);
  187617. }
  187618. }
  187619. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187620. /* optional call to update the users info_ptr structure */
  187621. void PNGAPI
  187622. png_read_update_info(png_structp png_ptr, png_infop info_ptr)
  187623. {
  187624. png_debug(1, "in png_read_update_info\n");
  187625. if(png_ptr == NULL) return;
  187626. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187627. png_read_start_row(png_ptr);
  187628. else
  187629. png_warning(png_ptr,
  187630. "Ignoring extra png_read_update_info() call; row buffer not reallocated");
  187631. png_read_transform_info(png_ptr, info_ptr);
  187632. }
  187633. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187634. /* Initialize palette, background, etc, after transformations
  187635. * are set, but before any reading takes place. This allows
  187636. * the user to obtain a gamma-corrected palette, for example.
  187637. * If the user doesn't call this, we will do it ourselves.
  187638. */
  187639. void PNGAPI
  187640. png_start_read_image(png_structp png_ptr)
  187641. {
  187642. png_debug(1, "in png_start_read_image\n");
  187643. if(png_ptr == NULL) return;
  187644. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187645. png_read_start_row(png_ptr);
  187646. }
  187647. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187648. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187649. void PNGAPI
  187650. png_read_row(png_structp png_ptr, png_bytep row, png_bytep dsp_row)
  187651. {
  187652. #ifdef PNG_USE_LOCAL_ARRAYS
  187653. PNG_CONST PNG_IDAT;
  187654. PNG_CONST int png_pass_dsp_mask[7] = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55,
  187655. 0xff};
  187656. PNG_CONST int png_pass_mask[7] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  187657. #endif
  187658. int ret;
  187659. if(png_ptr == NULL) return;
  187660. png_debug2(1, "in png_read_row (row %lu, pass %d)\n",
  187661. png_ptr->row_number, png_ptr->pass);
  187662. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187663. png_read_start_row(png_ptr);
  187664. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  187665. {
  187666. /* check for transforms that have been set but were defined out */
  187667. #if defined(PNG_WRITE_INVERT_SUPPORTED) && !defined(PNG_READ_INVERT_SUPPORTED)
  187668. if (png_ptr->transformations & PNG_INVERT_MONO)
  187669. png_warning(png_ptr, "PNG_READ_INVERT_SUPPORTED is not defined.");
  187670. #endif
  187671. #if defined(PNG_WRITE_FILLER_SUPPORTED) && !defined(PNG_READ_FILLER_SUPPORTED)
  187672. if (png_ptr->transformations & PNG_FILLER)
  187673. png_warning(png_ptr, "PNG_READ_FILLER_SUPPORTED is not defined.");
  187674. #endif
  187675. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED) && !defined(PNG_READ_PACKSWAP_SUPPORTED)
  187676. if (png_ptr->transformations & PNG_PACKSWAP)
  187677. png_warning(png_ptr, "PNG_READ_PACKSWAP_SUPPORTED is not defined.");
  187678. #endif
  187679. #if defined(PNG_WRITE_PACK_SUPPORTED) && !defined(PNG_READ_PACK_SUPPORTED)
  187680. if (png_ptr->transformations & PNG_PACK)
  187681. png_warning(png_ptr, "PNG_READ_PACK_SUPPORTED is not defined.");
  187682. #endif
  187683. #if defined(PNG_WRITE_SHIFT_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED)
  187684. if (png_ptr->transformations & PNG_SHIFT)
  187685. png_warning(png_ptr, "PNG_READ_SHIFT_SUPPORTED is not defined.");
  187686. #endif
  187687. #if defined(PNG_WRITE_BGR_SUPPORTED) && !defined(PNG_READ_BGR_SUPPORTED)
  187688. if (png_ptr->transformations & PNG_BGR)
  187689. png_warning(png_ptr, "PNG_READ_BGR_SUPPORTED is not defined.");
  187690. #endif
  187691. #if defined(PNG_WRITE_SWAP_SUPPORTED) && !defined(PNG_READ_SWAP_SUPPORTED)
  187692. if (png_ptr->transformations & PNG_SWAP_BYTES)
  187693. png_warning(png_ptr, "PNG_READ_SWAP_SUPPORTED is not defined.");
  187694. #endif
  187695. }
  187696. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  187697. /* if interlaced and we do not need a new row, combine row and return */
  187698. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  187699. {
  187700. switch (png_ptr->pass)
  187701. {
  187702. case 0:
  187703. if (png_ptr->row_number & 0x07)
  187704. {
  187705. if (dsp_row != NULL)
  187706. png_combine_row(png_ptr, dsp_row,
  187707. png_pass_dsp_mask[png_ptr->pass]);
  187708. png_read_finish_row(png_ptr);
  187709. return;
  187710. }
  187711. break;
  187712. case 1:
  187713. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  187714. {
  187715. if (dsp_row != NULL)
  187716. png_combine_row(png_ptr, dsp_row,
  187717. png_pass_dsp_mask[png_ptr->pass]);
  187718. png_read_finish_row(png_ptr);
  187719. return;
  187720. }
  187721. break;
  187722. case 2:
  187723. if ((png_ptr->row_number & 0x07) != 4)
  187724. {
  187725. if (dsp_row != NULL && (png_ptr->row_number & 4))
  187726. png_combine_row(png_ptr, dsp_row,
  187727. png_pass_dsp_mask[png_ptr->pass]);
  187728. png_read_finish_row(png_ptr);
  187729. return;
  187730. }
  187731. break;
  187732. case 3:
  187733. if ((png_ptr->row_number & 3) || png_ptr->width < 3)
  187734. {
  187735. if (dsp_row != NULL)
  187736. png_combine_row(png_ptr, dsp_row,
  187737. png_pass_dsp_mask[png_ptr->pass]);
  187738. png_read_finish_row(png_ptr);
  187739. return;
  187740. }
  187741. break;
  187742. case 4:
  187743. if ((png_ptr->row_number & 3) != 2)
  187744. {
  187745. if (dsp_row != NULL && (png_ptr->row_number & 2))
  187746. png_combine_row(png_ptr, dsp_row,
  187747. png_pass_dsp_mask[png_ptr->pass]);
  187748. png_read_finish_row(png_ptr);
  187749. return;
  187750. }
  187751. break;
  187752. case 5:
  187753. if ((png_ptr->row_number & 1) || png_ptr->width < 2)
  187754. {
  187755. if (dsp_row != NULL)
  187756. png_combine_row(png_ptr, dsp_row,
  187757. png_pass_dsp_mask[png_ptr->pass]);
  187758. png_read_finish_row(png_ptr);
  187759. return;
  187760. }
  187761. break;
  187762. case 6:
  187763. if (!(png_ptr->row_number & 1))
  187764. {
  187765. png_read_finish_row(png_ptr);
  187766. return;
  187767. }
  187768. break;
  187769. }
  187770. }
  187771. #endif
  187772. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  187773. png_error(png_ptr, "Invalid attempt to read row data");
  187774. png_ptr->zstream.next_out = png_ptr->row_buf;
  187775. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  187776. do
  187777. {
  187778. if (!(png_ptr->zstream.avail_in))
  187779. {
  187780. while (!png_ptr->idat_size)
  187781. {
  187782. png_byte chunk_length[4];
  187783. png_crc_finish(png_ptr, 0);
  187784. png_read_data(png_ptr, chunk_length, 4);
  187785. png_ptr->idat_size = png_get_uint_31(png_ptr,chunk_length);
  187786. png_reset_crc(png_ptr);
  187787. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187788. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187789. png_error(png_ptr, "Not enough image data");
  187790. }
  187791. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  187792. png_ptr->zstream.next_in = png_ptr->zbuf;
  187793. if (png_ptr->zbuf_size > png_ptr->idat_size)
  187794. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  187795. png_crc_read(png_ptr, png_ptr->zbuf,
  187796. (png_size_t)png_ptr->zstream.avail_in);
  187797. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  187798. }
  187799. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  187800. if (ret == Z_STREAM_END)
  187801. {
  187802. if (png_ptr->zstream.avail_out || png_ptr->zstream.avail_in ||
  187803. png_ptr->idat_size)
  187804. png_error(png_ptr, "Extra compressed data");
  187805. png_ptr->mode |= PNG_AFTER_IDAT;
  187806. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  187807. break;
  187808. }
  187809. if (ret != Z_OK)
  187810. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  187811. "Decompression error");
  187812. } while (png_ptr->zstream.avail_out);
  187813. png_ptr->row_info.color_type = png_ptr->color_type;
  187814. png_ptr->row_info.width = png_ptr->iwidth;
  187815. png_ptr->row_info.channels = png_ptr->channels;
  187816. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  187817. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  187818. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  187819. png_ptr->row_info.width);
  187820. if(png_ptr->row_buf[0])
  187821. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  187822. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  187823. (int)(png_ptr->row_buf[0]));
  187824. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  187825. png_ptr->rowbytes + 1);
  187826. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  187827. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  187828. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  187829. {
  187830. /* Intrapixel differencing */
  187831. png_do_read_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  187832. }
  187833. #endif
  187834. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  187835. png_do_read_transformations(png_ptr);
  187836. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  187837. /* blow up interlaced rows to full size */
  187838. if (png_ptr->interlaced &&
  187839. (png_ptr->transformations & PNG_INTERLACE))
  187840. {
  187841. if (png_ptr->pass < 6)
  187842. /* old interface (pre-1.0.9):
  187843. png_do_read_interlace(&(png_ptr->row_info),
  187844. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  187845. */
  187846. png_do_read_interlace(png_ptr);
  187847. if (dsp_row != NULL)
  187848. png_combine_row(png_ptr, dsp_row,
  187849. png_pass_dsp_mask[png_ptr->pass]);
  187850. if (row != NULL)
  187851. png_combine_row(png_ptr, row,
  187852. png_pass_mask[png_ptr->pass]);
  187853. }
  187854. else
  187855. #endif
  187856. {
  187857. if (row != NULL)
  187858. png_combine_row(png_ptr, row, 0xff);
  187859. if (dsp_row != NULL)
  187860. png_combine_row(png_ptr, dsp_row, 0xff);
  187861. }
  187862. png_read_finish_row(png_ptr);
  187863. if (png_ptr->read_row_fn != NULL)
  187864. (*(png_ptr->read_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  187865. }
  187866. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187867. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187868. /* Read one or more rows of image data. If the image is interlaced,
  187869. * and png_set_interlace_handling() has been called, the rows need to
  187870. * contain the contents of the rows from the previous pass. If the
  187871. * image has alpha or transparency, and png_handle_alpha()[*] has been
  187872. * called, the rows contents must be initialized to the contents of the
  187873. * screen.
  187874. *
  187875. * "row" holds the actual image, and pixels are placed in it
  187876. * as they arrive. If the image is displayed after each pass, it will
  187877. * appear to "sparkle" in. "display_row" can be used to display a
  187878. * "chunky" progressive image, with finer detail added as it becomes
  187879. * available. If you do not want this "chunky" display, you may pass
  187880. * NULL for display_row. If you do not want the sparkle display, and
  187881. * you have not called png_handle_alpha(), you may pass NULL for rows.
  187882. * If you have called png_handle_alpha(), and the image has either an
  187883. * alpha channel or a transparency chunk, you must provide a buffer for
  187884. * rows. In this case, you do not have to provide a display_row buffer
  187885. * also, but you may. If the image is not interlaced, or if you have
  187886. * not called png_set_interlace_handling(), the display_row buffer will
  187887. * be ignored, so pass NULL to it.
  187888. *
  187889. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  187890. */
  187891. void PNGAPI
  187892. png_read_rows(png_structp png_ptr, png_bytepp row,
  187893. png_bytepp display_row, png_uint_32 num_rows)
  187894. {
  187895. png_uint_32 i;
  187896. png_bytepp rp;
  187897. png_bytepp dp;
  187898. png_debug(1, "in png_read_rows\n");
  187899. if(png_ptr == NULL) return;
  187900. rp = row;
  187901. dp = display_row;
  187902. if (rp != NULL && dp != NULL)
  187903. for (i = 0; i < num_rows; i++)
  187904. {
  187905. png_bytep rptr = *rp++;
  187906. png_bytep dptr = *dp++;
  187907. png_read_row(png_ptr, rptr, dptr);
  187908. }
  187909. else if(rp != NULL)
  187910. for (i = 0; i < num_rows; i++)
  187911. {
  187912. png_bytep rptr = *rp;
  187913. png_read_row(png_ptr, rptr, png_bytep_NULL);
  187914. rp++;
  187915. }
  187916. else if(dp != NULL)
  187917. for (i = 0; i < num_rows; i++)
  187918. {
  187919. png_bytep dptr = *dp;
  187920. png_read_row(png_ptr, png_bytep_NULL, dptr);
  187921. dp++;
  187922. }
  187923. }
  187924. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187925. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187926. /* Read the entire image. If the image has an alpha channel or a tRNS
  187927. * chunk, and you have called png_handle_alpha()[*], you will need to
  187928. * initialize the image to the current image that PNG will be overlaying.
  187929. * We set the num_rows again here, in case it was incorrectly set in
  187930. * png_read_start_row() by a call to png_read_update_info() or
  187931. * png_start_read_image() if png_set_interlace_handling() wasn't called
  187932. * prior to either of these functions like it should have been. You can
  187933. * only call this function once. If you desire to have an image for
  187934. * each pass of a interlaced image, use png_read_rows() instead.
  187935. *
  187936. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  187937. */
  187938. void PNGAPI
  187939. png_read_image(png_structp png_ptr, png_bytepp image)
  187940. {
  187941. png_uint_32 i,image_height;
  187942. int pass, j;
  187943. png_bytepp rp;
  187944. png_debug(1, "in png_read_image\n");
  187945. if(png_ptr == NULL) return;
  187946. #ifdef PNG_READ_INTERLACING_SUPPORTED
  187947. pass = png_set_interlace_handling(png_ptr);
  187948. #else
  187949. if (png_ptr->interlaced)
  187950. png_error(png_ptr,
  187951. "Cannot read interlaced image -- interlace handler disabled.");
  187952. pass = 1;
  187953. #endif
  187954. image_height=png_ptr->height;
  187955. png_ptr->num_rows = image_height; /* Make sure this is set correctly */
  187956. for (j = 0; j < pass; j++)
  187957. {
  187958. rp = image;
  187959. for (i = 0; i < image_height; i++)
  187960. {
  187961. png_read_row(png_ptr, *rp, png_bytep_NULL);
  187962. rp++;
  187963. }
  187964. }
  187965. }
  187966. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187967. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187968. /* Read the end of the PNG file. Will not read past the end of the
  187969. * file, will verify the end is accurate, and will read any comments
  187970. * or time information at the end of the file, if info is not NULL.
  187971. */
  187972. void PNGAPI
  187973. png_read_end(png_structp png_ptr, png_infop info_ptr)
  187974. {
  187975. png_byte chunk_length[4];
  187976. png_uint_32 length;
  187977. png_debug(1, "in png_read_end\n");
  187978. if(png_ptr == NULL) return;
  187979. png_crc_finish(png_ptr, 0); /* Finish off CRC from last IDAT chunk */
  187980. do
  187981. {
  187982. #ifdef PNG_USE_LOCAL_ARRAYS
  187983. PNG_CONST PNG_IHDR;
  187984. PNG_CONST PNG_IDAT;
  187985. PNG_CONST PNG_IEND;
  187986. PNG_CONST PNG_PLTE;
  187987. #if defined(PNG_READ_bKGD_SUPPORTED)
  187988. PNG_CONST PNG_bKGD;
  187989. #endif
  187990. #if defined(PNG_READ_cHRM_SUPPORTED)
  187991. PNG_CONST PNG_cHRM;
  187992. #endif
  187993. #if defined(PNG_READ_gAMA_SUPPORTED)
  187994. PNG_CONST PNG_gAMA;
  187995. #endif
  187996. #if defined(PNG_READ_hIST_SUPPORTED)
  187997. PNG_CONST PNG_hIST;
  187998. #endif
  187999. #if defined(PNG_READ_iCCP_SUPPORTED)
  188000. PNG_CONST PNG_iCCP;
  188001. #endif
  188002. #if defined(PNG_READ_iTXt_SUPPORTED)
  188003. PNG_CONST PNG_iTXt;
  188004. #endif
  188005. #if defined(PNG_READ_oFFs_SUPPORTED)
  188006. PNG_CONST PNG_oFFs;
  188007. #endif
  188008. #if defined(PNG_READ_pCAL_SUPPORTED)
  188009. PNG_CONST PNG_pCAL;
  188010. #endif
  188011. #if defined(PNG_READ_pHYs_SUPPORTED)
  188012. PNG_CONST PNG_pHYs;
  188013. #endif
  188014. #if defined(PNG_READ_sBIT_SUPPORTED)
  188015. PNG_CONST PNG_sBIT;
  188016. #endif
  188017. #if defined(PNG_READ_sCAL_SUPPORTED)
  188018. PNG_CONST PNG_sCAL;
  188019. #endif
  188020. #if defined(PNG_READ_sPLT_SUPPORTED)
  188021. PNG_CONST PNG_sPLT;
  188022. #endif
  188023. #if defined(PNG_READ_sRGB_SUPPORTED)
  188024. PNG_CONST PNG_sRGB;
  188025. #endif
  188026. #if defined(PNG_READ_tEXt_SUPPORTED)
  188027. PNG_CONST PNG_tEXt;
  188028. #endif
  188029. #if defined(PNG_READ_tIME_SUPPORTED)
  188030. PNG_CONST PNG_tIME;
  188031. #endif
  188032. #if defined(PNG_READ_tRNS_SUPPORTED)
  188033. PNG_CONST PNG_tRNS;
  188034. #endif
  188035. #if defined(PNG_READ_zTXt_SUPPORTED)
  188036. PNG_CONST PNG_zTXt;
  188037. #endif
  188038. #endif /* PNG_USE_LOCAL_ARRAYS */
  188039. png_read_data(png_ptr, chunk_length, 4);
  188040. length = png_get_uint_31(png_ptr,chunk_length);
  188041. png_reset_crc(png_ptr);
  188042. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  188043. png_debug1(0, "Reading %s chunk.\n", png_ptr->chunk_name);
  188044. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  188045. png_handle_IHDR(png_ptr, info_ptr, length);
  188046. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  188047. png_handle_IEND(png_ptr, info_ptr, length);
  188048. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  188049. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  188050. {
  188051. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188052. {
  188053. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  188054. png_error(png_ptr, "Too many IDAT's found");
  188055. }
  188056. png_handle_unknown(png_ptr, info_ptr, length);
  188057. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188058. png_ptr->mode |= PNG_HAVE_PLTE;
  188059. }
  188060. #endif
  188061. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188062. {
  188063. /* Zero length IDATs are legal after the last IDAT has been
  188064. * read, but not after other chunks have been read.
  188065. */
  188066. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  188067. png_error(png_ptr, "Too many IDAT's found");
  188068. png_crc_finish(png_ptr, length);
  188069. }
  188070. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188071. png_handle_PLTE(png_ptr, info_ptr, length);
  188072. #if defined(PNG_READ_bKGD_SUPPORTED)
  188073. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  188074. png_handle_bKGD(png_ptr, info_ptr, length);
  188075. #endif
  188076. #if defined(PNG_READ_cHRM_SUPPORTED)
  188077. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  188078. png_handle_cHRM(png_ptr, info_ptr, length);
  188079. #endif
  188080. #if defined(PNG_READ_gAMA_SUPPORTED)
  188081. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  188082. png_handle_gAMA(png_ptr, info_ptr, length);
  188083. #endif
  188084. #if defined(PNG_READ_hIST_SUPPORTED)
  188085. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  188086. png_handle_hIST(png_ptr, info_ptr, length);
  188087. #endif
  188088. #if defined(PNG_READ_oFFs_SUPPORTED)
  188089. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  188090. png_handle_oFFs(png_ptr, info_ptr, length);
  188091. #endif
  188092. #if defined(PNG_READ_pCAL_SUPPORTED)
  188093. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  188094. png_handle_pCAL(png_ptr, info_ptr, length);
  188095. #endif
  188096. #if defined(PNG_READ_sCAL_SUPPORTED)
  188097. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  188098. png_handle_sCAL(png_ptr, info_ptr, length);
  188099. #endif
  188100. #if defined(PNG_READ_pHYs_SUPPORTED)
  188101. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  188102. png_handle_pHYs(png_ptr, info_ptr, length);
  188103. #endif
  188104. #if defined(PNG_READ_sBIT_SUPPORTED)
  188105. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  188106. png_handle_sBIT(png_ptr, info_ptr, length);
  188107. #endif
  188108. #if defined(PNG_READ_sRGB_SUPPORTED)
  188109. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  188110. png_handle_sRGB(png_ptr, info_ptr, length);
  188111. #endif
  188112. #if defined(PNG_READ_iCCP_SUPPORTED)
  188113. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  188114. png_handle_iCCP(png_ptr, info_ptr, length);
  188115. #endif
  188116. #if defined(PNG_READ_sPLT_SUPPORTED)
  188117. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  188118. png_handle_sPLT(png_ptr, info_ptr, length);
  188119. #endif
  188120. #if defined(PNG_READ_tEXt_SUPPORTED)
  188121. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  188122. png_handle_tEXt(png_ptr, info_ptr, length);
  188123. #endif
  188124. #if defined(PNG_READ_tIME_SUPPORTED)
  188125. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  188126. png_handle_tIME(png_ptr, info_ptr, length);
  188127. #endif
  188128. #if defined(PNG_READ_tRNS_SUPPORTED)
  188129. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  188130. png_handle_tRNS(png_ptr, info_ptr, length);
  188131. #endif
  188132. #if defined(PNG_READ_zTXt_SUPPORTED)
  188133. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  188134. png_handle_zTXt(png_ptr, info_ptr, length);
  188135. #endif
  188136. #if defined(PNG_READ_iTXt_SUPPORTED)
  188137. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  188138. png_handle_iTXt(png_ptr, info_ptr, length);
  188139. #endif
  188140. else
  188141. png_handle_unknown(png_ptr, info_ptr, length);
  188142. } while (!(png_ptr->mode & PNG_HAVE_IEND));
  188143. }
  188144. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  188145. /* free all memory used by the read */
  188146. void PNGAPI
  188147. png_destroy_read_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr,
  188148. png_infopp end_info_ptr_ptr)
  188149. {
  188150. png_structp png_ptr = NULL;
  188151. png_infop info_ptr = NULL, end_info_ptr = NULL;
  188152. #ifdef PNG_USER_MEM_SUPPORTED
  188153. png_free_ptr free_fn;
  188154. png_voidp mem_ptr;
  188155. #endif
  188156. png_debug(1, "in png_destroy_read_struct\n");
  188157. if (png_ptr_ptr != NULL)
  188158. png_ptr = *png_ptr_ptr;
  188159. if (info_ptr_ptr != NULL)
  188160. info_ptr = *info_ptr_ptr;
  188161. if (end_info_ptr_ptr != NULL)
  188162. end_info_ptr = *end_info_ptr_ptr;
  188163. #ifdef PNG_USER_MEM_SUPPORTED
  188164. free_fn = png_ptr->free_fn;
  188165. mem_ptr = png_ptr->mem_ptr;
  188166. #endif
  188167. png_read_destroy(png_ptr, info_ptr, end_info_ptr);
  188168. if (info_ptr != NULL)
  188169. {
  188170. #if defined(PNG_TEXT_SUPPORTED)
  188171. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, -1);
  188172. #endif
  188173. #ifdef PNG_USER_MEM_SUPPORTED
  188174. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  188175. (png_voidp)mem_ptr);
  188176. #else
  188177. png_destroy_struct((png_voidp)info_ptr);
  188178. #endif
  188179. *info_ptr_ptr = NULL;
  188180. }
  188181. if (end_info_ptr != NULL)
  188182. {
  188183. #if defined(PNG_READ_TEXT_SUPPORTED)
  188184. png_free_data(png_ptr, end_info_ptr, PNG_FREE_TEXT, -1);
  188185. #endif
  188186. #ifdef PNG_USER_MEM_SUPPORTED
  188187. png_destroy_struct_2((png_voidp)end_info_ptr, (png_free_ptr)free_fn,
  188188. (png_voidp)mem_ptr);
  188189. #else
  188190. png_destroy_struct((png_voidp)end_info_ptr);
  188191. #endif
  188192. *end_info_ptr_ptr = NULL;
  188193. }
  188194. if (png_ptr != NULL)
  188195. {
  188196. #ifdef PNG_USER_MEM_SUPPORTED
  188197. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  188198. (png_voidp)mem_ptr);
  188199. #else
  188200. png_destroy_struct((png_voidp)png_ptr);
  188201. #endif
  188202. *png_ptr_ptr = NULL;
  188203. }
  188204. }
  188205. /* free all memory used by the read (old method) */
  188206. void /* PRIVATE */
  188207. png_read_destroy(png_structp png_ptr, png_infop info_ptr, png_infop end_info_ptr)
  188208. {
  188209. #ifdef PNG_SETJMP_SUPPORTED
  188210. jmp_buf tmp_jmp;
  188211. #endif
  188212. png_error_ptr error_fn;
  188213. png_error_ptr warning_fn;
  188214. png_voidp error_ptr;
  188215. #ifdef PNG_USER_MEM_SUPPORTED
  188216. png_free_ptr free_fn;
  188217. #endif
  188218. png_debug(1, "in png_read_destroy\n");
  188219. if (info_ptr != NULL)
  188220. png_info_destroy(png_ptr, info_ptr);
  188221. if (end_info_ptr != NULL)
  188222. png_info_destroy(png_ptr, end_info_ptr);
  188223. png_free(png_ptr, png_ptr->zbuf);
  188224. png_free(png_ptr, png_ptr->big_row_buf);
  188225. png_free(png_ptr, png_ptr->prev_row);
  188226. #if defined(PNG_READ_DITHER_SUPPORTED)
  188227. png_free(png_ptr, png_ptr->palette_lookup);
  188228. png_free(png_ptr, png_ptr->dither_index);
  188229. #endif
  188230. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188231. png_free(png_ptr, png_ptr->gamma_table);
  188232. #endif
  188233. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  188234. png_free(png_ptr, png_ptr->gamma_from_1);
  188235. png_free(png_ptr, png_ptr->gamma_to_1);
  188236. #endif
  188237. #ifdef PNG_FREE_ME_SUPPORTED
  188238. if (png_ptr->free_me & PNG_FREE_PLTE)
  188239. png_zfree(png_ptr, png_ptr->palette);
  188240. png_ptr->free_me &= ~PNG_FREE_PLTE;
  188241. #else
  188242. if (png_ptr->flags & PNG_FLAG_FREE_PLTE)
  188243. png_zfree(png_ptr, png_ptr->palette);
  188244. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  188245. #endif
  188246. #if defined(PNG_tRNS_SUPPORTED) || \
  188247. defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  188248. #ifdef PNG_FREE_ME_SUPPORTED
  188249. if (png_ptr->free_me & PNG_FREE_TRNS)
  188250. png_free(png_ptr, png_ptr->trans);
  188251. png_ptr->free_me &= ~PNG_FREE_TRNS;
  188252. #else
  188253. if (png_ptr->flags & PNG_FLAG_FREE_TRNS)
  188254. png_free(png_ptr, png_ptr->trans);
  188255. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  188256. #endif
  188257. #endif
  188258. #if defined(PNG_READ_hIST_SUPPORTED)
  188259. #ifdef PNG_FREE_ME_SUPPORTED
  188260. if (png_ptr->free_me & PNG_FREE_HIST)
  188261. png_free(png_ptr, png_ptr->hist);
  188262. png_ptr->free_me &= ~PNG_FREE_HIST;
  188263. #else
  188264. if (png_ptr->flags & PNG_FLAG_FREE_HIST)
  188265. png_free(png_ptr, png_ptr->hist);
  188266. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  188267. #endif
  188268. #endif
  188269. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188270. if (png_ptr->gamma_16_table != NULL)
  188271. {
  188272. int i;
  188273. int istop = (1 << (8 - png_ptr->gamma_shift));
  188274. for (i = 0; i < istop; i++)
  188275. {
  188276. png_free(png_ptr, png_ptr->gamma_16_table[i]);
  188277. }
  188278. png_free(png_ptr, png_ptr->gamma_16_table);
  188279. }
  188280. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  188281. if (png_ptr->gamma_16_from_1 != NULL)
  188282. {
  188283. int i;
  188284. int istop = (1 << (8 - png_ptr->gamma_shift));
  188285. for (i = 0; i < istop; i++)
  188286. {
  188287. png_free(png_ptr, png_ptr->gamma_16_from_1[i]);
  188288. }
  188289. png_free(png_ptr, png_ptr->gamma_16_from_1);
  188290. }
  188291. if (png_ptr->gamma_16_to_1 != NULL)
  188292. {
  188293. int i;
  188294. int istop = (1 << (8 - png_ptr->gamma_shift));
  188295. for (i = 0; i < istop; i++)
  188296. {
  188297. png_free(png_ptr, png_ptr->gamma_16_to_1[i]);
  188298. }
  188299. png_free(png_ptr, png_ptr->gamma_16_to_1);
  188300. }
  188301. #endif
  188302. #endif
  188303. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  188304. png_free(png_ptr, png_ptr->time_buffer);
  188305. #endif
  188306. inflateEnd(&png_ptr->zstream);
  188307. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  188308. png_free(png_ptr, png_ptr->save_buffer);
  188309. #endif
  188310. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  188311. #ifdef PNG_TEXT_SUPPORTED
  188312. png_free(png_ptr, png_ptr->current_text);
  188313. #endif /* PNG_TEXT_SUPPORTED */
  188314. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  188315. /* Save the important info out of the png_struct, in case it is
  188316. * being used again.
  188317. */
  188318. #ifdef PNG_SETJMP_SUPPORTED
  188319. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  188320. #endif
  188321. error_fn = png_ptr->error_fn;
  188322. warning_fn = png_ptr->warning_fn;
  188323. error_ptr = png_ptr->error_ptr;
  188324. #ifdef PNG_USER_MEM_SUPPORTED
  188325. free_fn = png_ptr->free_fn;
  188326. #endif
  188327. png_memset(png_ptr, 0, png_sizeof (png_struct));
  188328. png_ptr->error_fn = error_fn;
  188329. png_ptr->warning_fn = warning_fn;
  188330. png_ptr->error_ptr = error_ptr;
  188331. #ifdef PNG_USER_MEM_SUPPORTED
  188332. png_ptr->free_fn = free_fn;
  188333. #endif
  188334. #ifdef PNG_SETJMP_SUPPORTED
  188335. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  188336. #endif
  188337. }
  188338. void PNGAPI
  188339. png_set_read_status_fn(png_structp png_ptr, png_read_status_ptr read_row_fn)
  188340. {
  188341. if(png_ptr == NULL) return;
  188342. png_ptr->read_row_fn = read_row_fn;
  188343. }
  188344. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  188345. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  188346. void PNGAPI
  188347. png_read_png(png_structp png_ptr, png_infop info_ptr,
  188348. int transforms,
  188349. voidp params)
  188350. {
  188351. int row;
  188352. if(png_ptr == NULL) return;
  188353. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  188354. /* invert the alpha channel from opacity to transparency
  188355. */
  188356. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  188357. png_set_invert_alpha(png_ptr);
  188358. #endif
  188359. /* png_read_info() gives us all of the information from the
  188360. * PNG file before the first IDAT (image data chunk).
  188361. */
  188362. png_read_info(png_ptr, info_ptr);
  188363. if (info_ptr->height > PNG_UINT_32_MAX/png_sizeof(png_bytep))
  188364. png_error(png_ptr,"Image is too high to process with png_read_png()");
  188365. /* -------------- image transformations start here ------------------- */
  188366. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  188367. /* tell libpng to strip 16 bit/color files down to 8 bits per color
  188368. */
  188369. if (transforms & PNG_TRANSFORM_STRIP_16)
  188370. png_set_strip_16(png_ptr);
  188371. #endif
  188372. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  188373. /* Strip alpha bytes from the input data without combining with
  188374. * the background (not recommended).
  188375. */
  188376. if (transforms & PNG_TRANSFORM_STRIP_ALPHA)
  188377. png_set_strip_alpha(png_ptr);
  188378. #endif
  188379. #if defined(PNG_READ_PACK_SUPPORTED) && !defined(PNG_READ_EXPAND_SUPPORTED)
  188380. /* Extract multiple pixels with bit depths of 1, 2, or 4 from a single
  188381. * byte into separate bytes (useful for paletted and grayscale images).
  188382. */
  188383. if (transforms & PNG_TRANSFORM_PACKING)
  188384. png_set_packing(png_ptr);
  188385. #endif
  188386. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  188387. /* Change the order of packed pixels to least significant bit first
  188388. * (not useful if you are using png_set_packing).
  188389. */
  188390. if (transforms & PNG_TRANSFORM_PACKSWAP)
  188391. png_set_packswap(png_ptr);
  188392. #endif
  188393. #if defined(PNG_READ_EXPAND_SUPPORTED)
  188394. /* Expand paletted colors into true RGB triplets
  188395. * Expand grayscale images to full 8 bits from 1, 2, or 4 bits/pixel
  188396. * Expand paletted or RGB images with transparency to full alpha
  188397. * channels so the data will be available as RGBA quartets.
  188398. */
  188399. if (transforms & PNG_TRANSFORM_EXPAND)
  188400. if ((png_ptr->bit_depth < 8) ||
  188401. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) ||
  188402. (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)))
  188403. png_set_expand(png_ptr);
  188404. #endif
  188405. /* We don't handle background color or gamma transformation or dithering.
  188406. */
  188407. #if defined(PNG_READ_INVERT_SUPPORTED)
  188408. /* invert monochrome files to have 0 as white and 1 as black
  188409. */
  188410. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  188411. png_set_invert_mono(png_ptr);
  188412. #endif
  188413. #if defined(PNG_READ_SHIFT_SUPPORTED)
  188414. /* If you want to shift the pixel values from the range [0,255] or
  188415. * [0,65535] to the original [0,7] or [0,31], or whatever range the
  188416. * colors were originally in:
  188417. */
  188418. if ((transforms & PNG_TRANSFORM_SHIFT)
  188419. && png_get_valid(png_ptr, info_ptr, PNG_INFO_sBIT))
  188420. {
  188421. png_color_8p sig_bit;
  188422. png_get_sBIT(png_ptr, info_ptr, &sig_bit);
  188423. png_set_shift(png_ptr, sig_bit);
  188424. }
  188425. #endif
  188426. #if defined(PNG_READ_BGR_SUPPORTED)
  188427. /* flip the RGB pixels to BGR (or RGBA to BGRA)
  188428. */
  188429. if (transforms & PNG_TRANSFORM_BGR)
  188430. png_set_bgr(png_ptr);
  188431. #endif
  188432. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  188433. /* swap the RGBA or GA data to ARGB or AG (or BGRA to ABGR)
  188434. */
  188435. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  188436. png_set_swap_alpha(png_ptr);
  188437. #endif
  188438. #if defined(PNG_READ_SWAP_SUPPORTED)
  188439. /* swap bytes of 16 bit files to least significant byte first
  188440. */
  188441. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  188442. png_set_swap(png_ptr);
  188443. #endif
  188444. /* We don't handle adding filler bytes */
  188445. /* Optional call to gamma correct and add the background to the palette
  188446. * and update info structure. REQUIRED if you are expecting libpng to
  188447. * update the palette for you (i.e., you selected such a transform above).
  188448. */
  188449. png_read_update_info(png_ptr, info_ptr);
  188450. /* -------------- image transformations end here ------------------- */
  188451. #ifdef PNG_FREE_ME_SUPPORTED
  188452. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  188453. #endif
  188454. if(info_ptr->row_pointers == NULL)
  188455. {
  188456. info_ptr->row_pointers = (png_bytepp)png_malloc(png_ptr,
  188457. info_ptr->height * png_sizeof(png_bytep));
  188458. #ifdef PNG_FREE_ME_SUPPORTED
  188459. info_ptr->free_me |= PNG_FREE_ROWS;
  188460. #endif
  188461. for (row = 0; row < (int)info_ptr->height; row++)
  188462. {
  188463. info_ptr->row_pointers[row] = (png_bytep)png_malloc(png_ptr,
  188464. png_get_rowbytes(png_ptr, info_ptr));
  188465. }
  188466. }
  188467. png_read_image(png_ptr, info_ptr->row_pointers);
  188468. info_ptr->valid |= PNG_INFO_IDAT;
  188469. /* read rest of file, and get additional chunks in info_ptr - REQUIRED */
  188470. png_read_end(png_ptr, info_ptr);
  188471. transforms = transforms; /* quiet compiler warnings */
  188472. params = params;
  188473. }
  188474. #endif /* PNG_INFO_IMAGE_SUPPORTED */
  188475. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  188476. #endif /* PNG_READ_SUPPORTED */
  188477. /*** End of inlined file: pngread.c ***/
  188478. /*** Start of inlined file: pngpread.c ***/
  188479. /* pngpread.c - read a png file in push mode
  188480. *
  188481. * Last changed in libpng 1.2.21 October 4, 2007
  188482. * For conditions of distribution and use, see copyright notice in png.h
  188483. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  188484. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  188485. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  188486. */
  188487. #define PNG_INTERNAL
  188488. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  188489. /* push model modes */
  188490. #define PNG_READ_SIG_MODE 0
  188491. #define PNG_READ_CHUNK_MODE 1
  188492. #define PNG_READ_IDAT_MODE 2
  188493. #define PNG_SKIP_MODE 3
  188494. #define PNG_READ_tEXt_MODE 4
  188495. #define PNG_READ_zTXt_MODE 5
  188496. #define PNG_READ_DONE_MODE 6
  188497. #define PNG_READ_iTXt_MODE 7
  188498. #define PNG_ERROR_MODE 8
  188499. void PNGAPI
  188500. png_process_data(png_structp png_ptr, png_infop info_ptr,
  188501. png_bytep buffer, png_size_t buffer_size)
  188502. {
  188503. if(png_ptr == NULL) return;
  188504. png_push_restore_buffer(png_ptr, buffer, buffer_size);
  188505. while (png_ptr->buffer_size)
  188506. {
  188507. png_process_some_data(png_ptr, info_ptr);
  188508. }
  188509. }
  188510. /* What we do with the incoming data depends on what we were previously
  188511. * doing before we ran out of data...
  188512. */
  188513. void /* PRIVATE */
  188514. png_process_some_data(png_structp png_ptr, png_infop info_ptr)
  188515. {
  188516. if(png_ptr == NULL) return;
  188517. switch (png_ptr->process_mode)
  188518. {
  188519. case PNG_READ_SIG_MODE:
  188520. {
  188521. png_push_read_sig(png_ptr, info_ptr);
  188522. break;
  188523. }
  188524. case PNG_READ_CHUNK_MODE:
  188525. {
  188526. png_push_read_chunk(png_ptr, info_ptr);
  188527. break;
  188528. }
  188529. case PNG_READ_IDAT_MODE:
  188530. {
  188531. png_push_read_IDAT(png_ptr);
  188532. break;
  188533. }
  188534. #if defined(PNG_READ_tEXt_SUPPORTED)
  188535. case PNG_READ_tEXt_MODE:
  188536. {
  188537. png_push_read_tEXt(png_ptr, info_ptr);
  188538. break;
  188539. }
  188540. #endif
  188541. #if defined(PNG_READ_zTXt_SUPPORTED)
  188542. case PNG_READ_zTXt_MODE:
  188543. {
  188544. png_push_read_zTXt(png_ptr, info_ptr);
  188545. break;
  188546. }
  188547. #endif
  188548. #if defined(PNG_READ_iTXt_SUPPORTED)
  188549. case PNG_READ_iTXt_MODE:
  188550. {
  188551. png_push_read_iTXt(png_ptr, info_ptr);
  188552. break;
  188553. }
  188554. #endif
  188555. case PNG_SKIP_MODE:
  188556. {
  188557. png_push_crc_finish(png_ptr);
  188558. break;
  188559. }
  188560. default:
  188561. {
  188562. png_ptr->buffer_size = 0;
  188563. break;
  188564. }
  188565. }
  188566. }
  188567. /* Read any remaining signature bytes from the stream and compare them with
  188568. * the correct PNG signature. It is possible that this routine is called
  188569. * with bytes already read from the signature, either because they have been
  188570. * checked by the calling application, or because of multiple calls to this
  188571. * routine.
  188572. */
  188573. void /* PRIVATE */
  188574. png_push_read_sig(png_structp png_ptr, png_infop info_ptr)
  188575. {
  188576. png_size_t num_checked = png_ptr->sig_bytes,
  188577. num_to_check = 8 - num_checked;
  188578. if (png_ptr->buffer_size < num_to_check)
  188579. {
  188580. num_to_check = png_ptr->buffer_size;
  188581. }
  188582. png_push_fill_buffer(png_ptr, &(info_ptr->signature[num_checked]),
  188583. num_to_check);
  188584. png_ptr->sig_bytes = (png_byte)(png_ptr->sig_bytes+num_to_check);
  188585. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  188586. {
  188587. if (num_checked < 4 &&
  188588. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  188589. png_error(png_ptr, "Not a PNG file");
  188590. else
  188591. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  188592. }
  188593. else
  188594. {
  188595. if (png_ptr->sig_bytes >= 8)
  188596. {
  188597. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  188598. }
  188599. }
  188600. }
  188601. void /* PRIVATE */
  188602. png_push_read_chunk(png_structp png_ptr, png_infop info_ptr)
  188603. {
  188604. #ifdef PNG_USE_LOCAL_ARRAYS
  188605. PNG_CONST PNG_IHDR;
  188606. PNG_CONST PNG_IDAT;
  188607. PNG_CONST PNG_IEND;
  188608. PNG_CONST PNG_PLTE;
  188609. #if defined(PNG_READ_bKGD_SUPPORTED)
  188610. PNG_CONST PNG_bKGD;
  188611. #endif
  188612. #if defined(PNG_READ_cHRM_SUPPORTED)
  188613. PNG_CONST PNG_cHRM;
  188614. #endif
  188615. #if defined(PNG_READ_gAMA_SUPPORTED)
  188616. PNG_CONST PNG_gAMA;
  188617. #endif
  188618. #if defined(PNG_READ_hIST_SUPPORTED)
  188619. PNG_CONST PNG_hIST;
  188620. #endif
  188621. #if defined(PNG_READ_iCCP_SUPPORTED)
  188622. PNG_CONST PNG_iCCP;
  188623. #endif
  188624. #if defined(PNG_READ_iTXt_SUPPORTED)
  188625. PNG_CONST PNG_iTXt;
  188626. #endif
  188627. #if defined(PNG_READ_oFFs_SUPPORTED)
  188628. PNG_CONST PNG_oFFs;
  188629. #endif
  188630. #if defined(PNG_READ_pCAL_SUPPORTED)
  188631. PNG_CONST PNG_pCAL;
  188632. #endif
  188633. #if defined(PNG_READ_pHYs_SUPPORTED)
  188634. PNG_CONST PNG_pHYs;
  188635. #endif
  188636. #if defined(PNG_READ_sBIT_SUPPORTED)
  188637. PNG_CONST PNG_sBIT;
  188638. #endif
  188639. #if defined(PNG_READ_sCAL_SUPPORTED)
  188640. PNG_CONST PNG_sCAL;
  188641. #endif
  188642. #if defined(PNG_READ_sRGB_SUPPORTED)
  188643. PNG_CONST PNG_sRGB;
  188644. #endif
  188645. #if defined(PNG_READ_sPLT_SUPPORTED)
  188646. PNG_CONST PNG_sPLT;
  188647. #endif
  188648. #if defined(PNG_READ_tEXt_SUPPORTED)
  188649. PNG_CONST PNG_tEXt;
  188650. #endif
  188651. #if defined(PNG_READ_tIME_SUPPORTED)
  188652. PNG_CONST PNG_tIME;
  188653. #endif
  188654. #if defined(PNG_READ_tRNS_SUPPORTED)
  188655. PNG_CONST PNG_tRNS;
  188656. #endif
  188657. #if defined(PNG_READ_zTXt_SUPPORTED)
  188658. PNG_CONST PNG_zTXt;
  188659. #endif
  188660. #endif /* PNG_USE_LOCAL_ARRAYS */
  188661. /* First we make sure we have enough data for the 4 byte chunk name
  188662. * and the 4 byte chunk length before proceeding with decoding the
  188663. * chunk data. To fully decode each of these chunks, we also make
  188664. * sure we have enough data in the buffer for the 4 byte CRC at the
  188665. * end of every chunk (except IDAT, which is handled separately).
  188666. */
  188667. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  188668. {
  188669. png_byte chunk_length[4];
  188670. if (png_ptr->buffer_size < 8)
  188671. {
  188672. png_push_save_buffer(png_ptr);
  188673. return;
  188674. }
  188675. png_push_fill_buffer(png_ptr, chunk_length, 4);
  188676. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  188677. png_reset_crc(png_ptr);
  188678. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  188679. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  188680. }
  188681. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188682. if(png_ptr->mode & PNG_AFTER_IDAT)
  188683. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  188684. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  188685. {
  188686. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188687. {
  188688. png_push_save_buffer(png_ptr);
  188689. return;
  188690. }
  188691. png_handle_IHDR(png_ptr, info_ptr, png_ptr->push_length);
  188692. }
  188693. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  188694. {
  188695. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188696. {
  188697. png_push_save_buffer(png_ptr);
  188698. return;
  188699. }
  188700. png_handle_IEND(png_ptr, info_ptr, png_ptr->push_length);
  188701. png_ptr->process_mode = PNG_READ_DONE_MODE;
  188702. png_push_have_end(png_ptr, info_ptr);
  188703. }
  188704. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  188705. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  188706. {
  188707. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188708. {
  188709. png_push_save_buffer(png_ptr);
  188710. return;
  188711. }
  188712. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188713. png_ptr->mode |= PNG_HAVE_IDAT;
  188714. png_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  188715. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188716. png_ptr->mode |= PNG_HAVE_PLTE;
  188717. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188718. {
  188719. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188720. png_error(png_ptr, "Missing IHDR before IDAT");
  188721. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  188722. !(png_ptr->mode & PNG_HAVE_PLTE))
  188723. png_error(png_ptr, "Missing PLTE before IDAT");
  188724. }
  188725. }
  188726. #endif
  188727. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188728. {
  188729. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188730. {
  188731. png_push_save_buffer(png_ptr);
  188732. return;
  188733. }
  188734. png_handle_PLTE(png_ptr, info_ptr, png_ptr->push_length);
  188735. }
  188736. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188737. {
  188738. /* If we reach an IDAT chunk, this means we have read all of the
  188739. * header chunks, and we can start reading the image (or if this
  188740. * is called after the image has been read - we have an error).
  188741. */
  188742. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188743. png_error(png_ptr, "Missing IHDR before IDAT");
  188744. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  188745. !(png_ptr->mode & PNG_HAVE_PLTE))
  188746. png_error(png_ptr, "Missing PLTE before IDAT");
  188747. if (png_ptr->mode & PNG_HAVE_IDAT)
  188748. {
  188749. if (!(png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  188750. if (png_ptr->push_length == 0)
  188751. return;
  188752. if (png_ptr->mode & PNG_AFTER_IDAT)
  188753. png_error(png_ptr, "Too many IDAT's found");
  188754. }
  188755. png_ptr->idat_size = png_ptr->push_length;
  188756. png_ptr->mode |= PNG_HAVE_IDAT;
  188757. png_ptr->process_mode = PNG_READ_IDAT_MODE;
  188758. png_push_have_info(png_ptr, info_ptr);
  188759. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  188760. png_ptr->zstream.next_out = png_ptr->row_buf;
  188761. return;
  188762. }
  188763. #if defined(PNG_READ_gAMA_SUPPORTED)
  188764. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  188765. {
  188766. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188767. {
  188768. png_push_save_buffer(png_ptr);
  188769. return;
  188770. }
  188771. png_handle_gAMA(png_ptr, info_ptr, png_ptr->push_length);
  188772. }
  188773. #endif
  188774. #if defined(PNG_READ_sBIT_SUPPORTED)
  188775. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  188776. {
  188777. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188778. {
  188779. png_push_save_buffer(png_ptr);
  188780. return;
  188781. }
  188782. png_handle_sBIT(png_ptr, info_ptr, png_ptr->push_length);
  188783. }
  188784. #endif
  188785. #if defined(PNG_READ_cHRM_SUPPORTED)
  188786. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  188787. {
  188788. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188789. {
  188790. png_push_save_buffer(png_ptr);
  188791. return;
  188792. }
  188793. png_handle_cHRM(png_ptr, info_ptr, png_ptr->push_length);
  188794. }
  188795. #endif
  188796. #if defined(PNG_READ_sRGB_SUPPORTED)
  188797. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  188798. {
  188799. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188800. {
  188801. png_push_save_buffer(png_ptr);
  188802. return;
  188803. }
  188804. png_handle_sRGB(png_ptr, info_ptr, png_ptr->push_length);
  188805. }
  188806. #endif
  188807. #if defined(PNG_READ_iCCP_SUPPORTED)
  188808. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  188809. {
  188810. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188811. {
  188812. png_push_save_buffer(png_ptr);
  188813. return;
  188814. }
  188815. png_handle_iCCP(png_ptr, info_ptr, png_ptr->push_length);
  188816. }
  188817. #endif
  188818. #if defined(PNG_READ_sPLT_SUPPORTED)
  188819. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  188820. {
  188821. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188822. {
  188823. png_push_save_buffer(png_ptr);
  188824. return;
  188825. }
  188826. png_handle_sPLT(png_ptr, info_ptr, png_ptr->push_length);
  188827. }
  188828. #endif
  188829. #if defined(PNG_READ_tRNS_SUPPORTED)
  188830. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  188831. {
  188832. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188833. {
  188834. png_push_save_buffer(png_ptr);
  188835. return;
  188836. }
  188837. png_handle_tRNS(png_ptr, info_ptr, png_ptr->push_length);
  188838. }
  188839. #endif
  188840. #if defined(PNG_READ_bKGD_SUPPORTED)
  188841. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  188842. {
  188843. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188844. {
  188845. png_push_save_buffer(png_ptr);
  188846. return;
  188847. }
  188848. png_handle_bKGD(png_ptr, info_ptr, png_ptr->push_length);
  188849. }
  188850. #endif
  188851. #if defined(PNG_READ_hIST_SUPPORTED)
  188852. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  188853. {
  188854. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188855. {
  188856. png_push_save_buffer(png_ptr);
  188857. return;
  188858. }
  188859. png_handle_hIST(png_ptr, info_ptr, png_ptr->push_length);
  188860. }
  188861. #endif
  188862. #if defined(PNG_READ_pHYs_SUPPORTED)
  188863. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  188864. {
  188865. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188866. {
  188867. png_push_save_buffer(png_ptr);
  188868. return;
  188869. }
  188870. png_handle_pHYs(png_ptr, info_ptr, png_ptr->push_length);
  188871. }
  188872. #endif
  188873. #if defined(PNG_READ_oFFs_SUPPORTED)
  188874. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  188875. {
  188876. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188877. {
  188878. png_push_save_buffer(png_ptr);
  188879. return;
  188880. }
  188881. png_handle_oFFs(png_ptr, info_ptr, png_ptr->push_length);
  188882. }
  188883. #endif
  188884. #if defined(PNG_READ_pCAL_SUPPORTED)
  188885. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  188886. {
  188887. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188888. {
  188889. png_push_save_buffer(png_ptr);
  188890. return;
  188891. }
  188892. png_handle_pCAL(png_ptr, info_ptr, png_ptr->push_length);
  188893. }
  188894. #endif
  188895. #if defined(PNG_READ_sCAL_SUPPORTED)
  188896. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  188897. {
  188898. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188899. {
  188900. png_push_save_buffer(png_ptr);
  188901. return;
  188902. }
  188903. png_handle_sCAL(png_ptr, info_ptr, png_ptr->push_length);
  188904. }
  188905. #endif
  188906. #if defined(PNG_READ_tIME_SUPPORTED)
  188907. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  188908. {
  188909. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188910. {
  188911. png_push_save_buffer(png_ptr);
  188912. return;
  188913. }
  188914. png_handle_tIME(png_ptr, info_ptr, png_ptr->push_length);
  188915. }
  188916. #endif
  188917. #if defined(PNG_READ_tEXt_SUPPORTED)
  188918. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  188919. {
  188920. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188921. {
  188922. png_push_save_buffer(png_ptr);
  188923. return;
  188924. }
  188925. png_push_handle_tEXt(png_ptr, info_ptr, png_ptr->push_length);
  188926. }
  188927. #endif
  188928. #if defined(PNG_READ_zTXt_SUPPORTED)
  188929. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  188930. {
  188931. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188932. {
  188933. png_push_save_buffer(png_ptr);
  188934. return;
  188935. }
  188936. png_push_handle_zTXt(png_ptr, info_ptr, png_ptr->push_length);
  188937. }
  188938. #endif
  188939. #if defined(PNG_READ_iTXt_SUPPORTED)
  188940. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  188941. {
  188942. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188943. {
  188944. png_push_save_buffer(png_ptr);
  188945. return;
  188946. }
  188947. png_push_handle_iTXt(png_ptr, info_ptr, png_ptr->push_length);
  188948. }
  188949. #endif
  188950. else
  188951. {
  188952. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188953. {
  188954. png_push_save_buffer(png_ptr);
  188955. return;
  188956. }
  188957. png_push_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  188958. }
  188959. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  188960. }
  188961. void /* PRIVATE */
  188962. png_push_crc_skip(png_structp png_ptr, png_uint_32 skip)
  188963. {
  188964. png_ptr->process_mode = PNG_SKIP_MODE;
  188965. png_ptr->skip_length = skip;
  188966. }
  188967. void /* PRIVATE */
  188968. png_push_crc_finish(png_structp png_ptr)
  188969. {
  188970. if (png_ptr->skip_length && png_ptr->save_buffer_size)
  188971. {
  188972. png_size_t save_size;
  188973. if (png_ptr->skip_length < (png_uint_32)png_ptr->save_buffer_size)
  188974. save_size = (png_size_t)png_ptr->skip_length;
  188975. else
  188976. save_size = png_ptr->save_buffer_size;
  188977. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  188978. png_ptr->skip_length -= save_size;
  188979. png_ptr->buffer_size -= save_size;
  188980. png_ptr->save_buffer_size -= save_size;
  188981. png_ptr->save_buffer_ptr += save_size;
  188982. }
  188983. if (png_ptr->skip_length && png_ptr->current_buffer_size)
  188984. {
  188985. png_size_t save_size;
  188986. if (png_ptr->skip_length < (png_uint_32)png_ptr->current_buffer_size)
  188987. save_size = (png_size_t)png_ptr->skip_length;
  188988. else
  188989. save_size = png_ptr->current_buffer_size;
  188990. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  188991. png_ptr->skip_length -= save_size;
  188992. png_ptr->buffer_size -= save_size;
  188993. png_ptr->current_buffer_size -= save_size;
  188994. png_ptr->current_buffer_ptr += save_size;
  188995. }
  188996. if (!png_ptr->skip_length)
  188997. {
  188998. if (png_ptr->buffer_size < 4)
  188999. {
  189000. png_push_save_buffer(png_ptr);
  189001. return;
  189002. }
  189003. png_crc_finish(png_ptr, 0);
  189004. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  189005. }
  189006. }
  189007. void PNGAPI
  189008. png_push_fill_buffer(png_structp png_ptr, png_bytep buffer, png_size_t length)
  189009. {
  189010. png_bytep ptr;
  189011. if(png_ptr == NULL) return;
  189012. ptr = buffer;
  189013. if (png_ptr->save_buffer_size)
  189014. {
  189015. png_size_t save_size;
  189016. if (length < png_ptr->save_buffer_size)
  189017. save_size = length;
  189018. else
  189019. save_size = png_ptr->save_buffer_size;
  189020. png_memcpy(ptr, png_ptr->save_buffer_ptr, save_size);
  189021. length -= save_size;
  189022. ptr += save_size;
  189023. png_ptr->buffer_size -= save_size;
  189024. png_ptr->save_buffer_size -= save_size;
  189025. png_ptr->save_buffer_ptr += save_size;
  189026. }
  189027. if (length && png_ptr->current_buffer_size)
  189028. {
  189029. png_size_t save_size;
  189030. if (length < png_ptr->current_buffer_size)
  189031. save_size = length;
  189032. else
  189033. save_size = png_ptr->current_buffer_size;
  189034. png_memcpy(ptr, png_ptr->current_buffer_ptr, save_size);
  189035. png_ptr->buffer_size -= save_size;
  189036. png_ptr->current_buffer_size -= save_size;
  189037. png_ptr->current_buffer_ptr += save_size;
  189038. }
  189039. }
  189040. void /* PRIVATE */
  189041. png_push_save_buffer(png_structp png_ptr)
  189042. {
  189043. if (png_ptr->save_buffer_size)
  189044. {
  189045. if (png_ptr->save_buffer_ptr != png_ptr->save_buffer)
  189046. {
  189047. png_size_t i,istop;
  189048. png_bytep sp;
  189049. png_bytep dp;
  189050. istop = png_ptr->save_buffer_size;
  189051. for (i = 0, sp = png_ptr->save_buffer_ptr, dp = png_ptr->save_buffer;
  189052. i < istop; i++, sp++, dp++)
  189053. {
  189054. *dp = *sp;
  189055. }
  189056. }
  189057. }
  189058. if (png_ptr->save_buffer_size + png_ptr->current_buffer_size >
  189059. png_ptr->save_buffer_max)
  189060. {
  189061. png_size_t new_max;
  189062. png_bytep old_buffer;
  189063. if (png_ptr->save_buffer_size > PNG_SIZE_MAX -
  189064. (png_ptr->current_buffer_size + 256))
  189065. {
  189066. png_error(png_ptr, "Potential overflow of save_buffer");
  189067. }
  189068. new_max = png_ptr->save_buffer_size + png_ptr->current_buffer_size + 256;
  189069. old_buffer = png_ptr->save_buffer;
  189070. png_ptr->save_buffer = (png_bytep)png_malloc(png_ptr,
  189071. (png_uint_32)new_max);
  189072. png_memcpy(png_ptr->save_buffer, old_buffer, png_ptr->save_buffer_size);
  189073. png_free(png_ptr, old_buffer);
  189074. png_ptr->save_buffer_max = new_max;
  189075. }
  189076. if (png_ptr->current_buffer_size)
  189077. {
  189078. png_memcpy(png_ptr->save_buffer + png_ptr->save_buffer_size,
  189079. png_ptr->current_buffer_ptr, png_ptr->current_buffer_size);
  189080. png_ptr->save_buffer_size += png_ptr->current_buffer_size;
  189081. png_ptr->current_buffer_size = 0;
  189082. }
  189083. png_ptr->save_buffer_ptr = png_ptr->save_buffer;
  189084. png_ptr->buffer_size = 0;
  189085. }
  189086. void /* PRIVATE */
  189087. png_push_restore_buffer(png_structp png_ptr, png_bytep buffer,
  189088. png_size_t buffer_length)
  189089. {
  189090. png_ptr->current_buffer = buffer;
  189091. png_ptr->current_buffer_size = buffer_length;
  189092. png_ptr->buffer_size = buffer_length + png_ptr->save_buffer_size;
  189093. png_ptr->current_buffer_ptr = png_ptr->current_buffer;
  189094. }
  189095. void /* PRIVATE */
  189096. png_push_read_IDAT(png_structp png_ptr)
  189097. {
  189098. #ifdef PNG_USE_LOCAL_ARRAYS
  189099. PNG_CONST PNG_IDAT;
  189100. #endif
  189101. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  189102. {
  189103. png_byte chunk_length[4];
  189104. if (png_ptr->buffer_size < 8)
  189105. {
  189106. png_push_save_buffer(png_ptr);
  189107. return;
  189108. }
  189109. png_push_fill_buffer(png_ptr, chunk_length, 4);
  189110. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  189111. png_reset_crc(png_ptr);
  189112. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  189113. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  189114. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  189115. {
  189116. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  189117. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  189118. png_error(png_ptr, "Not enough compressed data");
  189119. return;
  189120. }
  189121. png_ptr->idat_size = png_ptr->push_length;
  189122. }
  189123. if (png_ptr->idat_size && png_ptr->save_buffer_size)
  189124. {
  189125. png_size_t save_size;
  189126. if (png_ptr->idat_size < (png_uint_32)png_ptr->save_buffer_size)
  189127. {
  189128. save_size = (png_size_t)png_ptr->idat_size;
  189129. /* check for overflow */
  189130. if((png_uint_32)save_size != png_ptr->idat_size)
  189131. png_error(png_ptr, "save_size overflowed in pngpread");
  189132. }
  189133. else
  189134. save_size = png_ptr->save_buffer_size;
  189135. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  189136. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  189137. png_process_IDAT_data(png_ptr, png_ptr->save_buffer_ptr, save_size);
  189138. png_ptr->idat_size -= save_size;
  189139. png_ptr->buffer_size -= save_size;
  189140. png_ptr->save_buffer_size -= save_size;
  189141. png_ptr->save_buffer_ptr += save_size;
  189142. }
  189143. if (png_ptr->idat_size && png_ptr->current_buffer_size)
  189144. {
  189145. png_size_t save_size;
  189146. if (png_ptr->idat_size < (png_uint_32)png_ptr->current_buffer_size)
  189147. {
  189148. save_size = (png_size_t)png_ptr->idat_size;
  189149. /* check for overflow */
  189150. if((png_uint_32)save_size != png_ptr->idat_size)
  189151. png_error(png_ptr, "save_size overflowed in pngpread");
  189152. }
  189153. else
  189154. save_size = png_ptr->current_buffer_size;
  189155. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  189156. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  189157. png_process_IDAT_data(png_ptr, png_ptr->current_buffer_ptr, save_size);
  189158. png_ptr->idat_size -= save_size;
  189159. png_ptr->buffer_size -= save_size;
  189160. png_ptr->current_buffer_size -= save_size;
  189161. png_ptr->current_buffer_ptr += save_size;
  189162. }
  189163. if (!png_ptr->idat_size)
  189164. {
  189165. if (png_ptr->buffer_size < 4)
  189166. {
  189167. png_push_save_buffer(png_ptr);
  189168. return;
  189169. }
  189170. png_crc_finish(png_ptr, 0);
  189171. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  189172. png_ptr->mode |= PNG_AFTER_IDAT;
  189173. }
  189174. }
  189175. void /* PRIVATE */
  189176. png_process_IDAT_data(png_structp png_ptr, png_bytep buffer,
  189177. png_size_t buffer_length)
  189178. {
  189179. int ret;
  189180. if ((png_ptr->flags & PNG_FLAG_ZLIB_FINISHED) && buffer_length)
  189181. png_error(png_ptr, "Extra compression data");
  189182. png_ptr->zstream.next_in = buffer;
  189183. png_ptr->zstream.avail_in = (uInt)buffer_length;
  189184. for(;;)
  189185. {
  189186. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  189187. if (ret != Z_OK)
  189188. {
  189189. if (ret == Z_STREAM_END)
  189190. {
  189191. if (png_ptr->zstream.avail_in)
  189192. png_error(png_ptr, "Extra compressed data");
  189193. if (!(png_ptr->zstream.avail_out))
  189194. {
  189195. png_push_process_row(png_ptr);
  189196. }
  189197. png_ptr->mode |= PNG_AFTER_IDAT;
  189198. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  189199. break;
  189200. }
  189201. else if (ret == Z_BUF_ERROR)
  189202. break;
  189203. else
  189204. png_error(png_ptr, "Decompression Error");
  189205. }
  189206. if (!(png_ptr->zstream.avail_out))
  189207. {
  189208. if ((
  189209. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  189210. png_ptr->interlaced && png_ptr->pass > 6) ||
  189211. (!png_ptr->interlaced &&
  189212. #endif
  189213. png_ptr->row_number == png_ptr->num_rows))
  189214. {
  189215. if (png_ptr->zstream.avail_in)
  189216. {
  189217. png_warning(png_ptr, "Too much data in IDAT chunks");
  189218. }
  189219. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  189220. break;
  189221. }
  189222. png_push_process_row(png_ptr);
  189223. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  189224. png_ptr->zstream.next_out = png_ptr->row_buf;
  189225. }
  189226. else
  189227. break;
  189228. }
  189229. }
  189230. void /* PRIVATE */
  189231. png_push_process_row(png_structp png_ptr)
  189232. {
  189233. png_ptr->row_info.color_type = png_ptr->color_type;
  189234. png_ptr->row_info.width = png_ptr->iwidth;
  189235. png_ptr->row_info.channels = png_ptr->channels;
  189236. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  189237. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  189238. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  189239. png_ptr->row_info.width);
  189240. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  189241. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  189242. (int)(png_ptr->row_buf[0]));
  189243. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  189244. png_ptr->rowbytes + 1);
  189245. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  189246. png_do_read_transformations(png_ptr);
  189247. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  189248. /* blow up interlaced rows to full size */
  189249. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  189250. {
  189251. if (png_ptr->pass < 6)
  189252. /* old interface (pre-1.0.9):
  189253. png_do_read_interlace(&(png_ptr->row_info),
  189254. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  189255. */
  189256. png_do_read_interlace(png_ptr);
  189257. switch (png_ptr->pass)
  189258. {
  189259. case 0:
  189260. {
  189261. int i;
  189262. for (i = 0; i < 8 && png_ptr->pass == 0; i++)
  189263. {
  189264. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189265. png_read_push_finish_row(png_ptr); /* updates png_ptr->pass */
  189266. }
  189267. if (png_ptr->pass == 2) /* pass 1 might be empty */
  189268. {
  189269. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189270. {
  189271. png_push_have_row(png_ptr, png_bytep_NULL);
  189272. png_read_push_finish_row(png_ptr);
  189273. }
  189274. }
  189275. if (png_ptr->pass == 4 && png_ptr->height <= 4)
  189276. {
  189277. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189278. {
  189279. png_push_have_row(png_ptr, png_bytep_NULL);
  189280. png_read_push_finish_row(png_ptr);
  189281. }
  189282. }
  189283. if (png_ptr->pass == 6 && png_ptr->height <= 4)
  189284. {
  189285. png_push_have_row(png_ptr, png_bytep_NULL);
  189286. png_read_push_finish_row(png_ptr);
  189287. }
  189288. break;
  189289. }
  189290. case 1:
  189291. {
  189292. int i;
  189293. for (i = 0; i < 8 && png_ptr->pass == 1; i++)
  189294. {
  189295. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189296. png_read_push_finish_row(png_ptr);
  189297. }
  189298. if (png_ptr->pass == 2) /* skip top 4 generated rows */
  189299. {
  189300. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189301. {
  189302. png_push_have_row(png_ptr, png_bytep_NULL);
  189303. png_read_push_finish_row(png_ptr);
  189304. }
  189305. }
  189306. break;
  189307. }
  189308. case 2:
  189309. {
  189310. int i;
  189311. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189312. {
  189313. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189314. png_read_push_finish_row(png_ptr);
  189315. }
  189316. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189317. {
  189318. png_push_have_row(png_ptr, png_bytep_NULL);
  189319. png_read_push_finish_row(png_ptr);
  189320. }
  189321. if (png_ptr->pass == 4) /* pass 3 might be empty */
  189322. {
  189323. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189324. {
  189325. png_push_have_row(png_ptr, png_bytep_NULL);
  189326. png_read_push_finish_row(png_ptr);
  189327. }
  189328. }
  189329. break;
  189330. }
  189331. case 3:
  189332. {
  189333. int i;
  189334. for (i = 0; i < 4 && png_ptr->pass == 3; i++)
  189335. {
  189336. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189337. png_read_push_finish_row(png_ptr);
  189338. }
  189339. if (png_ptr->pass == 4) /* skip top two generated rows */
  189340. {
  189341. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189342. {
  189343. png_push_have_row(png_ptr, png_bytep_NULL);
  189344. png_read_push_finish_row(png_ptr);
  189345. }
  189346. }
  189347. break;
  189348. }
  189349. case 4:
  189350. {
  189351. int i;
  189352. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189353. {
  189354. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189355. png_read_push_finish_row(png_ptr);
  189356. }
  189357. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189358. {
  189359. png_push_have_row(png_ptr, png_bytep_NULL);
  189360. png_read_push_finish_row(png_ptr);
  189361. }
  189362. if (png_ptr->pass == 6) /* pass 5 might be empty */
  189363. {
  189364. png_push_have_row(png_ptr, png_bytep_NULL);
  189365. png_read_push_finish_row(png_ptr);
  189366. }
  189367. break;
  189368. }
  189369. case 5:
  189370. {
  189371. int i;
  189372. for (i = 0; i < 2 && png_ptr->pass == 5; i++)
  189373. {
  189374. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189375. png_read_push_finish_row(png_ptr);
  189376. }
  189377. if (png_ptr->pass == 6) /* skip top generated row */
  189378. {
  189379. png_push_have_row(png_ptr, png_bytep_NULL);
  189380. png_read_push_finish_row(png_ptr);
  189381. }
  189382. break;
  189383. }
  189384. case 6:
  189385. {
  189386. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189387. png_read_push_finish_row(png_ptr);
  189388. if (png_ptr->pass != 6)
  189389. break;
  189390. png_push_have_row(png_ptr, png_bytep_NULL);
  189391. png_read_push_finish_row(png_ptr);
  189392. }
  189393. }
  189394. }
  189395. else
  189396. #endif
  189397. {
  189398. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189399. png_read_push_finish_row(png_ptr);
  189400. }
  189401. }
  189402. void /* PRIVATE */
  189403. png_read_push_finish_row(png_structp png_ptr)
  189404. {
  189405. #ifdef PNG_USE_LOCAL_ARRAYS
  189406. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  189407. /* start of interlace block */
  189408. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  189409. /* offset to next interlace block */
  189410. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  189411. /* start of interlace block in the y direction */
  189412. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  189413. /* offset to next interlace block in the y direction */
  189414. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  189415. /* Height of interlace block. This is not currently used - if you need
  189416. * it, uncomment it here and in png.h
  189417. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  189418. */
  189419. #endif
  189420. png_ptr->row_number++;
  189421. if (png_ptr->row_number < png_ptr->num_rows)
  189422. return;
  189423. if (png_ptr->interlaced)
  189424. {
  189425. png_ptr->row_number = 0;
  189426. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  189427. png_ptr->rowbytes + 1);
  189428. do
  189429. {
  189430. png_ptr->pass++;
  189431. if ((png_ptr->pass == 1 && png_ptr->width < 5) ||
  189432. (png_ptr->pass == 3 && png_ptr->width < 3) ||
  189433. (png_ptr->pass == 5 && png_ptr->width < 2))
  189434. png_ptr->pass++;
  189435. if (png_ptr->pass > 7)
  189436. png_ptr->pass--;
  189437. if (png_ptr->pass >= 7)
  189438. break;
  189439. png_ptr->iwidth = (png_ptr->width +
  189440. png_pass_inc[png_ptr->pass] - 1 -
  189441. png_pass_start[png_ptr->pass]) /
  189442. png_pass_inc[png_ptr->pass];
  189443. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  189444. png_ptr->iwidth) + 1;
  189445. if (png_ptr->transformations & PNG_INTERLACE)
  189446. break;
  189447. png_ptr->num_rows = (png_ptr->height +
  189448. png_pass_yinc[png_ptr->pass] - 1 -
  189449. png_pass_ystart[png_ptr->pass]) /
  189450. png_pass_yinc[png_ptr->pass];
  189451. } while (png_ptr->iwidth == 0 || png_ptr->num_rows == 0);
  189452. }
  189453. }
  189454. #if defined(PNG_READ_tEXt_SUPPORTED)
  189455. void /* PRIVATE */
  189456. png_push_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189457. length)
  189458. {
  189459. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189460. {
  189461. png_error(png_ptr, "Out of place tEXt");
  189462. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189463. }
  189464. #ifdef PNG_MAX_MALLOC_64K
  189465. png_ptr->skip_length = 0; /* This may not be necessary */
  189466. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  189467. {
  189468. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  189469. png_ptr->skip_length = length - (png_uint_32)65535L;
  189470. length = (png_uint_32)65535L;
  189471. }
  189472. #endif
  189473. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189474. (png_uint_32)(length+1));
  189475. png_ptr->current_text[length] = '\0';
  189476. png_ptr->current_text_ptr = png_ptr->current_text;
  189477. png_ptr->current_text_size = (png_size_t)length;
  189478. png_ptr->current_text_left = (png_size_t)length;
  189479. png_ptr->process_mode = PNG_READ_tEXt_MODE;
  189480. }
  189481. void /* PRIVATE */
  189482. png_push_read_tEXt(png_structp png_ptr, png_infop info_ptr)
  189483. {
  189484. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189485. {
  189486. png_size_t text_size;
  189487. if (png_ptr->buffer_size < png_ptr->current_text_left)
  189488. text_size = png_ptr->buffer_size;
  189489. else
  189490. text_size = png_ptr->current_text_left;
  189491. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189492. png_ptr->current_text_left -= text_size;
  189493. png_ptr->current_text_ptr += text_size;
  189494. }
  189495. if (!(png_ptr->current_text_left))
  189496. {
  189497. png_textp text_ptr;
  189498. png_charp text;
  189499. png_charp key;
  189500. int ret;
  189501. if (png_ptr->buffer_size < 4)
  189502. {
  189503. png_push_save_buffer(png_ptr);
  189504. return;
  189505. }
  189506. png_push_crc_finish(png_ptr);
  189507. #if defined(PNG_MAX_MALLOC_64K)
  189508. if (png_ptr->skip_length)
  189509. return;
  189510. #endif
  189511. key = png_ptr->current_text;
  189512. for (text = key; *text; text++)
  189513. /* empty loop */ ;
  189514. if (text < key + png_ptr->current_text_size)
  189515. text++;
  189516. text_ptr = (png_textp)png_malloc(png_ptr,
  189517. (png_uint_32)png_sizeof(png_text));
  189518. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  189519. text_ptr->key = key;
  189520. #ifdef PNG_iTXt_SUPPORTED
  189521. text_ptr->lang = NULL;
  189522. text_ptr->lang_key = NULL;
  189523. #endif
  189524. text_ptr->text = text;
  189525. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189526. png_free(png_ptr, key);
  189527. png_free(png_ptr, text_ptr);
  189528. png_ptr->current_text = NULL;
  189529. if (ret)
  189530. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  189531. }
  189532. }
  189533. #endif
  189534. #if defined(PNG_READ_zTXt_SUPPORTED)
  189535. void /* PRIVATE */
  189536. png_push_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189537. length)
  189538. {
  189539. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189540. {
  189541. png_error(png_ptr, "Out of place zTXt");
  189542. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189543. }
  189544. #ifdef PNG_MAX_MALLOC_64K
  189545. /* We can't handle zTXt chunks > 64K, since we don't have enough space
  189546. * to be able to store the uncompressed data. Actually, the threshold
  189547. * is probably around 32K, but it isn't as definite as 64K is.
  189548. */
  189549. if (length > (png_uint_32)65535L)
  189550. {
  189551. png_warning(png_ptr, "zTXt chunk too large to fit in memory");
  189552. png_push_crc_skip(png_ptr, length);
  189553. return;
  189554. }
  189555. #endif
  189556. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189557. (png_uint_32)(length+1));
  189558. png_ptr->current_text[length] = '\0';
  189559. png_ptr->current_text_ptr = png_ptr->current_text;
  189560. png_ptr->current_text_size = (png_size_t)length;
  189561. png_ptr->current_text_left = (png_size_t)length;
  189562. png_ptr->process_mode = PNG_READ_zTXt_MODE;
  189563. }
  189564. void /* PRIVATE */
  189565. png_push_read_zTXt(png_structp png_ptr, png_infop info_ptr)
  189566. {
  189567. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189568. {
  189569. png_size_t text_size;
  189570. if (png_ptr->buffer_size < (png_uint_32)png_ptr->current_text_left)
  189571. text_size = png_ptr->buffer_size;
  189572. else
  189573. text_size = png_ptr->current_text_left;
  189574. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189575. png_ptr->current_text_left -= text_size;
  189576. png_ptr->current_text_ptr += text_size;
  189577. }
  189578. if (!(png_ptr->current_text_left))
  189579. {
  189580. png_textp text_ptr;
  189581. png_charp text;
  189582. png_charp key;
  189583. int ret;
  189584. png_size_t text_size, key_size;
  189585. if (png_ptr->buffer_size < 4)
  189586. {
  189587. png_push_save_buffer(png_ptr);
  189588. return;
  189589. }
  189590. png_push_crc_finish(png_ptr);
  189591. key = png_ptr->current_text;
  189592. for (text = key; *text; text++)
  189593. /* empty loop */ ;
  189594. /* zTXt can't have zero text */
  189595. if (text >= key + png_ptr->current_text_size)
  189596. {
  189597. png_ptr->current_text = NULL;
  189598. png_free(png_ptr, key);
  189599. return;
  189600. }
  189601. text++;
  189602. if (*text != PNG_TEXT_COMPRESSION_zTXt) /* check compression byte */
  189603. {
  189604. png_ptr->current_text = NULL;
  189605. png_free(png_ptr, key);
  189606. return;
  189607. }
  189608. text++;
  189609. png_ptr->zstream.next_in = (png_bytep )text;
  189610. png_ptr->zstream.avail_in = (uInt)(png_ptr->current_text_size -
  189611. (text - key));
  189612. png_ptr->zstream.next_out = png_ptr->zbuf;
  189613. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  189614. key_size = text - key;
  189615. text_size = 0;
  189616. text = NULL;
  189617. ret = Z_STREAM_END;
  189618. while (png_ptr->zstream.avail_in)
  189619. {
  189620. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  189621. if (ret != Z_OK && ret != Z_STREAM_END)
  189622. {
  189623. inflateReset(&png_ptr->zstream);
  189624. png_ptr->zstream.avail_in = 0;
  189625. png_ptr->current_text = NULL;
  189626. png_free(png_ptr, key);
  189627. png_free(png_ptr, text);
  189628. return;
  189629. }
  189630. if (!(png_ptr->zstream.avail_out) || ret == Z_STREAM_END)
  189631. {
  189632. if (text == NULL)
  189633. {
  189634. text = (png_charp)png_malloc(png_ptr,
  189635. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  189636. + key_size + 1));
  189637. png_memcpy(text + key_size, png_ptr->zbuf,
  189638. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  189639. png_memcpy(text, key, key_size);
  189640. text_size = key_size + png_ptr->zbuf_size -
  189641. png_ptr->zstream.avail_out;
  189642. *(text + text_size) = '\0';
  189643. }
  189644. else
  189645. {
  189646. png_charp tmp;
  189647. tmp = text;
  189648. text = (png_charp)png_malloc(png_ptr, text_size +
  189649. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  189650. + 1));
  189651. png_memcpy(text, tmp, text_size);
  189652. png_free(png_ptr, tmp);
  189653. png_memcpy(text + text_size, png_ptr->zbuf,
  189654. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  189655. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  189656. *(text + text_size) = '\0';
  189657. }
  189658. if (ret != Z_STREAM_END)
  189659. {
  189660. png_ptr->zstream.next_out = png_ptr->zbuf;
  189661. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  189662. }
  189663. }
  189664. else
  189665. {
  189666. break;
  189667. }
  189668. if (ret == Z_STREAM_END)
  189669. break;
  189670. }
  189671. inflateReset(&png_ptr->zstream);
  189672. png_ptr->zstream.avail_in = 0;
  189673. if (ret != Z_STREAM_END)
  189674. {
  189675. png_ptr->current_text = NULL;
  189676. png_free(png_ptr, key);
  189677. png_free(png_ptr, text);
  189678. return;
  189679. }
  189680. png_ptr->current_text = NULL;
  189681. png_free(png_ptr, key);
  189682. key = text;
  189683. text += key_size;
  189684. text_ptr = (png_textp)png_malloc(png_ptr,
  189685. (png_uint_32)png_sizeof(png_text));
  189686. text_ptr->compression = PNG_TEXT_COMPRESSION_zTXt;
  189687. text_ptr->key = key;
  189688. #ifdef PNG_iTXt_SUPPORTED
  189689. text_ptr->lang = NULL;
  189690. text_ptr->lang_key = NULL;
  189691. #endif
  189692. text_ptr->text = text;
  189693. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189694. png_free(png_ptr, key);
  189695. png_free(png_ptr, text_ptr);
  189696. if (ret)
  189697. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  189698. }
  189699. }
  189700. #endif
  189701. #if defined(PNG_READ_iTXt_SUPPORTED)
  189702. void /* PRIVATE */
  189703. png_push_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189704. length)
  189705. {
  189706. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189707. {
  189708. png_error(png_ptr, "Out of place iTXt");
  189709. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189710. }
  189711. #ifdef PNG_MAX_MALLOC_64K
  189712. png_ptr->skip_length = 0; /* This may not be necessary */
  189713. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  189714. {
  189715. png_warning(png_ptr, "iTXt chunk too large to fit in memory");
  189716. png_ptr->skip_length = length - (png_uint_32)65535L;
  189717. length = (png_uint_32)65535L;
  189718. }
  189719. #endif
  189720. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189721. (png_uint_32)(length+1));
  189722. png_ptr->current_text[length] = '\0';
  189723. png_ptr->current_text_ptr = png_ptr->current_text;
  189724. png_ptr->current_text_size = (png_size_t)length;
  189725. png_ptr->current_text_left = (png_size_t)length;
  189726. png_ptr->process_mode = PNG_READ_iTXt_MODE;
  189727. }
  189728. void /* PRIVATE */
  189729. png_push_read_iTXt(png_structp png_ptr, png_infop info_ptr)
  189730. {
  189731. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189732. {
  189733. png_size_t text_size;
  189734. if (png_ptr->buffer_size < png_ptr->current_text_left)
  189735. text_size = png_ptr->buffer_size;
  189736. else
  189737. text_size = png_ptr->current_text_left;
  189738. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189739. png_ptr->current_text_left -= text_size;
  189740. png_ptr->current_text_ptr += text_size;
  189741. }
  189742. if (!(png_ptr->current_text_left))
  189743. {
  189744. png_textp text_ptr;
  189745. png_charp key;
  189746. int comp_flag;
  189747. png_charp lang;
  189748. png_charp lang_key;
  189749. png_charp text;
  189750. int ret;
  189751. if (png_ptr->buffer_size < 4)
  189752. {
  189753. png_push_save_buffer(png_ptr);
  189754. return;
  189755. }
  189756. png_push_crc_finish(png_ptr);
  189757. #if defined(PNG_MAX_MALLOC_64K)
  189758. if (png_ptr->skip_length)
  189759. return;
  189760. #endif
  189761. key = png_ptr->current_text;
  189762. for (lang = key; *lang; lang++)
  189763. /* empty loop */ ;
  189764. if (lang < key + png_ptr->current_text_size - 3)
  189765. lang++;
  189766. comp_flag = *lang++;
  189767. lang++; /* skip comp_type, always zero */
  189768. for (lang_key = lang; *lang_key; lang_key++)
  189769. /* empty loop */ ;
  189770. lang_key++; /* skip NUL separator */
  189771. text=lang_key;
  189772. if (lang_key < key + png_ptr->current_text_size - 1)
  189773. {
  189774. for (; *text; text++)
  189775. /* empty loop */ ;
  189776. }
  189777. if (text < key + png_ptr->current_text_size)
  189778. text++;
  189779. text_ptr = (png_textp)png_malloc(png_ptr,
  189780. (png_uint_32)png_sizeof(png_text));
  189781. text_ptr->compression = comp_flag + 2;
  189782. text_ptr->key = key;
  189783. text_ptr->lang = lang;
  189784. text_ptr->lang_key = lang_key;
  189785. text_ptr->text = text;
  189786. text_ptr->text_length = 0;
  189787. text_ptr->itxt_length = png_strlen(text);
  189788. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189789. png_ptr->current_text = NULL;
  189790. png_free(png_ptr, text_ptr);
  189791. if (ret)
  189792. png_warning(png_ptr, "Insufficient memory to store iTXt chunk.");
  189793. }
  189794. }
  189795. #endif
  189796. /* This function is called when we haven't found a handler for this
  189797. * chunk. If there isn't a problem with the chunk itself (ie a bad chunk
  189798. * name or a critical chunk), the chunk is (currently) silently ignored.
  189799. */
  189800. void /* PRIVATE */
  189801. png_push_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189802. length)
  189803. {
  189804. png_uint_32 skip=0;
  189805. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  189806. if (!(png_ptr->chunk_name[0] & 0x20))
  189807. {
  189808. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  189809. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  189810. PNG_HANDLE_CHUNK_ALWAYS
  189811. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  189812. && png_ptr->read_user_chunk_fn == NULL
  189813. #endif
  189814. )
  189815. #endif
  189816. png_chunk_error(png_ptr, "unknown critical chunk");
  189817. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189818. }
  189819. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  189820. if (png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS)
  189821. {
  189822. #ifdef PNG_MAX_MALLOC_64K
  189823. if (length > (png_uint_32)65535L)
  189824. {
  189825. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  189826. skip = length - (png_uint_32)65535L;
  189827. length = (png_uint_32)65535L;
  189828. }
  189829. #endif
  189830. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  189831. (png_charp)png_ptr->chunk_name, 5);
  189832. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  189833. png_ptr->unknown_chunk.size = (png_size_t)length;
  189834. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  189835. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  189836. if(png_ptr->read_user_chunk_fn != NULL)
  189837. {
  189838. /* callback to user unknown chunk handler */
  189839. int ret;
  189840. ret = (*(png_ptr->read_user_chunk_fn))
  189841. (png_ptr, &png_ptr->unknown_chunk);
  189842. if (ret < 0)
  189843. png_chunk_error(png_ptr, "error in user chunk");
  189844. if (ret == 0)
  189845. {
  189846. if (!(png_ptr->chunk_name[0] & 0x20))
  189847. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  189848. PNG_HANDLE_CHUNK_ALWAYS)
  189849. png_chunk_error(png_ptr, "unknown critical chunk");
  189850. png_set_unknown_chunks(png_ptr, info_ptr,
  189851. &png_ptr->unknown_chunk, 1);
  189852. }
  189853. }
  189854. #else
  189855. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  189856. #endif
  189857. png_free(png_ptr, png_ptr->unknown_chunk.data);
  189858. png_ptr->unknown_chunk.data = NULL;
  189859. }
  189860. else
  189861. #endif
  189862. skip=length;
  189863. png_push_crc_skip(png_ptr, skip);
  189864. }
  189865. void /* PRIVATE */
  189866. png_push_have_info(png_structp png_ptr, png_infop info_ptr)
  189867. {
  189868. if (png_ptr->info_fn != NULL)
  189869. (*(png_ptr->info_fn))(png_ptr, info_ptr);
  189870. }
  189871. void /* PRIVATE */
  189872. png_push_have_end(png_structp png_ptr, png_infop info_ptr)
  189873. {
  189874. if (png_ptr->end_fn != NULL)
  189875. (*(png_ptr->end_fn))(png_ptr, info_ptr);
  189876. }
  189877. void /* PRIVATE */
  189878. png_push_have_row(png_structp png_ptr, png_bytep row)
  189879. {
  189880. if (png_ptr->row_fn != NULL)
  189881. (*(png_ptr->row_fn))(png_ptr, row, png_ptr->row_number,
  189882. (int)png_ptr->pass);
  189883. }
  189884. void PNGAPI
  189885. png_progressive_combine_row (png_structp png_ptr,
  189886. png_bytep old_row, png_bytep new_row)
  189887. {
  189888. #ifdef PNG_USE_LOCAL_ARRAYS
  189889. PNG_CONST int FARDATA png_pass_dsp_mask[7] =
  189890. {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  189891. #endif
  189892. if(png_ptr == NULL) return;
  189893. if (new_row != NULL) /* new_row must == png_ptr->row_buf here. */
  189894. png_combine_row(png_ptr, old_row, png_pass_dsp_mask[png_ptr->pass]);
  189895. }
  189896. void PNGAPI
  189897. png_set_progressive_read_fn(png_structp png_ptr, png_voidp progressive_ptr,
  189898. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  189899. png_progressive_end_ptr end_fn)
  189900. {
  189901. if(png_ptr == NULL) return;
  189902. png_ptr->info_fn = info_fn;
  189903. png_ptr->row_fn = row_fn;
  189904. png_ptr->end_fn = end_fn;
  189905. png_set_read_fn(png_ptr, progressive_ptr, png_push_fill_buffer);
  189906. }
  189907. png_voidp PNGAPI
  189908. png_get_progressive_ptr(png_structp png_ptr)
  189909. {
  189910. if(png_ptr == NULL) return (NULL);
  189911. return png_ptr->io_ptr;
  189912. }
  189913. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  189914. /*** End of inlined file: pngpread.c ***/
  189915. /*** Start of inlined file: pngrio.c ***/
  189916. /* pngrio.c - functions for data input
  189917. *
  189918. * Last changed in libpng 1.2.13 November 13, 2006
  189919. * For conditions of distribution and use, see copyright notice in png.h
  189920. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  189921. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  189922. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  189923. *
  189924. * This file provides a location for all input. Users who need
  189925. * special handling are expected to write a function that has the same
  189926. * arguments as this and performs a similar function, but that possibly
  189927. * has a different input method. Note that you shouldn't change this
  189928. * function, but rather write a replacement function and then make
  189929. * libpng use it at run time with png_set_read_fn(...).
  189930. */
  189931. #define PNG_INTERNAL
  189932. #if defined(PNG_READ_SUPPORTED)
  189933. /* Read the data from whatever input you are using. The default routine
  189934. reads from a file pointer. Note that this routine sometimes gets called
  189935. with very small lengths, so you should implement some kind of simple
  189936. buffering if you are using unbuffered reads. This should never be asked
  189937. to read more then 64K on a 16 bit machine. */
  189938. void /* PRIVATE */
  189939. png_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  189940. {
  189941. png_debug1(4,"reading %d bytes\n", (int)length);
  189942. if (png_ptr->read_data_fn != NULL)
  189943. (*(png_ptr->read_data_fn))(png_ptr, data, length);
  189944. else
  189945. png_error(png_ptr, "Call to NULL read function");
  189946. }
  189947. #if !defined(PNG_NO_STDIO)
  189948. /* This is the function that does the actual reading of data. If you are
  189949. not reading from a standard C stream, you should create a replacement
  189950. read_data function and use it at run time with png_set_read_fn(), rather
  189951. than changing the library. */
  189952. #ifndef USE_FAR_KEYWORD
  189953. void PNGAPI
  189954. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  189955. {
  189956. png_size_t check;
  189957. if(png_ptr == NULL) return;
  189958. /* fread() returns 0 on error, so it is OK to store this in a png_size_t
  189959. * instead of an int, which is what fread() actually returns.
  189960. */
  189961. #if defined(_WIN32_WCE)
  189962. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  189963. check = 0;
  189964. #else
  189965. check = (png_size_t)fread(data, (png_size_t)1, length,
  189966. (png_FILE_p)png_ptr->io_ptr);
  189967. #endif
  189968. if (check != length)
  189969. png_error(png_ptr, "Read Error");
  189970. }
  189971. #else
  189972. /* this is the model-independent version. Since the standard I/O library
  189973. can't handle far buffers in the medium and small models, we have to copy
  189974. the data.
  189975. */
  189976. #define NEAR_BUF_SIZE 1024
  189977. #define MIN(a,b) (a <= b ? a : b)
  189978. static void PNGAPI
  189979. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  189980. {
  189981. int check;
  189982. png_byte *n_data;
  189983. png_FILE_p io_ptr;
  189984. if(png_ptr == NULL) return;
  189985. /* Check if data really is near. If so, use usual code. */
  189986. n_data = (png_byte *)CVT_PTR_NOCHECK(data);
  189987. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  189988. if ((png_bytep)n_data == data)
  189989. {
  189990. #if defined(_WIN32_WCE)
  189991. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  189992. check = 0;
  189993. #else
  189994. check = fread(n_data, 1, length, io_ptr);
  189995. #endif
  189996. }
  189997. else
  189998. {
  189999. png_byte buf[NEAR_BUF_SIZE];
  190000. png_size_t read, remaining, err;
  190001. check = 0;
  190002. remaining = length;
  190003. do
  190004. {
  190005. read = MIN(NEAR_BUF_SIZE, remaining);
  190006. #if defined(_WIN32_WCE)
  190007. if ( !ReadFile((HANDLE)(io_ptr), buf, read, &err, NULL) )
  190008. err = 0;
  190009. #else
  190010. err = fread(buf, (png_size_t)1, read, io_ptr);
  190011. #endif
  190012. png_memcpy(data, buf, read); /* copy far buffer to near buffer */
  190013. if(err != read)
  190014. break;
  190015. else
  190016. check += err;
  190017. data += read;
  190018. remaining -= read;
  190019. }
  190020. while (remaining != 0);
  190021. }
  190022. if ((png_uint_32)check != (png_uint_32)length)
  190023. png_error(png_ptr, "read Error");
  190024. }
  190025. #endif
  190026. #endif
  190027. /* This function allows the application to supply a new input function
  190028. for libpng if standard C streams aren't being used.
  190029. This function takes as its arguments:
  190030. png_ptr - pointer to a png input data structure
  190031. io_ptr - pointer to user supplied structure containing info about
  190032. the input functions. May be NULL.
  190033. read_data_fn - pointer to a new input function that takes as its
  190034. arguments a pointer to a png_struct, a pointer to
  190035. a location where input data can be stored, and a 32-bit
  190036. unsigned int that is the number of bytes to be read.
  190037. To exit and output any fatal error messages the new write
  190038. function should call png_error(png_ptr, "Error msg"). */
  190039. void PNGAPI
  190040. png_set_read_fn(png_structp png_ptr, png_voidp io_ptr,
  190041. png_rw_ptr read_data_fn)
  190042. {
  190043. if(png_ptr == NULL) return;
  190044. png_ptr->io_ptr = io_ptr;
  190045. #if !defined(PNG_NO_STDIO)
  190046. if (read_data_fn != NULL)
  190047. png_ptr->read_data_fn = read_data_fn;
  190048. else
  190049. png_ptr->read_data_fn = png_default_read_data;
  190050. #else
  190051. png_ptr->read_data_fn = read_data_fn;
  190052. #endif
  190053. /* It is an error to write to a read device */
  190054. if (png_ptr->write_data_fn != NULL)
  190055. {
  190056. png_ptr->write_data_fn = NULL;
  190057. png_warning(png_ptr,
  190058. "It's an error to set both read_data_fn and write_data_fn in the ");
  190059. png_warning(png_ptr,
  190060. "same structure. Resetting write_data_fn to NULL.");
  190061. }
  190062. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  190063. png_ptr->output_flush_fn = NULL;
  190064. #endif
  190065. }
  190066. #endif /* PNG_READ_SUPPORTED */
  190067. /*** End of inlined file: pngrio.c ***/
  190068. /*** Start of inlined file: pngrtran.c ***/
  190069. /* pngrtran.c - transforms the data in a row for PNG readers
  190070. *
  190071. * Last changed in libpng 1.2.21 [October 4, 2007]
  190072. * For conditions of distribution and use, see copyright notice in png.h
  190073. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  190074. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  190075. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  190076. *
  190077. * This file contains functions optionally called by an application
  190078. * in order to tell libpng how to handle data when reading a PNG.
  190079. * Transformations that are used in both reading and writing are
  190080. * in pngtrans.c.
  190081. */
  190082. #define PNG_INTERNAL
  190083. #if defined(PNG_READ_SUPPORTED)
  190084. /* Set the action on getting a CRC error for an ancillary or critical chunk. */
  190085. void PNGAPI
  190086. png_set_crc_action(png_structp png_ptr, int crit_action, int ancil_action)
  190087. {
  190088. png_debug(1, "in png_set_crc_action\n");
  190089. /* Tell libpng how we react to CRC errors in critical chunks */
  190090. if(png_ptr == NULL) return;
  190091. switch (crit_action)
  190092. {
  190093. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  190094. break;
  190095. case PNG_CRC_WARN_USE: /* warn/use data */
  190096. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  190097. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE;
  190098. break;
  190099. case PNG_CRC_QUIET_USE: /* quiet/use data */
  190100. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  190101. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE |
  190102. PNG_FLAG_CRC_CRITICAL_IGNORE;
  190103. break;
  190104. case PNG_CRC_WARN_DISCARD: /* not a valid action for critical data */
  190105. png_warning(png_ptr, "Can't discard critical data on CRC error.");
  190106. case PNG_CRC_ERROR_QUIT: /* error/quit */
  190107. case PNG_CRC_DEFAULT:
  190108. default:
  190109. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  190110. break;
  190111. }
  190112. switch (ancil_action)
  190113. {
  190114. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  190115. break;
  190116. case PNG_CRC_WARN_USE: /* warn/use data */
  190117. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  190118. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE;
  190119. break;
  190120. case PNG_CRC_QUIET_USE: /* quiet/use data */
  190121. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  190122. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE |
  190123. PNG_FLAG_CRC_ANCILLARY_NOWARN;
  190124. break;
  190125. case PNG_CRC_ERROR_QUIT: /* error/quit */
  190126. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  190127. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_NOWARN;
  190128. break;
  190129. case PNG_CRC_WARN_DISCARD: /* warn/discard data */
  190130. case PNG_CRC_DEFAULT:
  190131. default:
  190132. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  190133. break;
  190134. }
  190135. }
  190136. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  190137. defined(PNG_FLOATING_POINT_SUPPORTED)
  190138. /* handle alpha and tRNS via a background color */
  190139. void PNGAPI
  190140. png_set_background(png_structp png_ptr,
  190141. png_color_16p background_color, int background_gamma_code,
  190142. int need_expand, double background_gamma)
  190143. {
  190144. png_debug(1, "in png_set_background\n");
  190145. if(png_ptr == NULL) return;
  190146. if (background_gamma_code == PNG_BACKGROUND_GAMMA_UNKNOWN)
  190147. {
  190148. png_warning(png_ptr, "Application must supply a known background gamma");
  190149. return;
  190150. }
  190151. png_ptr->transformations |= PNG_BACKGROUND;
  190152. png_memcpy(&(png_ptr->background), background_color,
  190153. png_sizeof(png_color_16));
  190154. png_ptr->background_gamma = (float)background_gamma;
  190155. png_ptr->background_gamma_type = (png_byte)(background_gamma_code);
  190156. png_ptr->transformations |= (need_expand ? PNG_BACKGROUND_EXPAND : 0);
  190157. }
  190158. #endif
  190159. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  190160. /* strip 16 bit depth files to 8 bit depth */
  190161. void PNGAPI
  190162. png_set_strip_16(png_structp png_ptr)
  190163. {
  190164. png_debug(1, "in png_set_strip_16\n");
  190165. if(png_ptr == NULL) return;
  190166. png_ptr->transformations |= PNG_16_TO_8;
  190167. }
  190168. #endif
  190169. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  190170. void PNGAPI
  190171. png_set_strip_alpha(png_structp png_ptr)
  190172. {
  190173. png_debug(1, "in png_set_strip_alpha\n");
  190174. if(png_ptr == NULL) return;
  190175. png_ptr->flags |= PNG_FLAG_STRIP_ALPHA;
  190176. }
  190177. #endif
  190178. #if defined(PNG_READ_DITHER_SUPPORTED)
  190179. /* Dither file to 8 bit. Supply a palette, the current number
  190180. * of elements in the palette, the maximum number of elements
  190181. * allowed, and a histogram if possible. If the current number
  190182. * of colors is greater then the maximum number, the palette will be
  190183. * modified to fit in the maximum number. "full_dither" indicates
  190184. * whether we need a dithering cube set up for RGB images, or if we
  190185. * simply are reducing the number of colors in a paletted image.
  190186. */
  190187. typedef struct png_dsort_struct
  190188. {
  190189. struct png_dsort_struct FAR * next;
  190190. png_byte left;
  190191. png_byte right;
  190192. } png_dsort;
  190193. typedef png_dsort FAR * png_dsortp;
  190194. typedef png_dsort FAR * FAR * png_dsortpp;
  190195. void PNGAPI
  190196. png_set_dither(png_structp png_ptr, png_colorp palette,
  190197. int num_palette, int maximum_colors, png_uint_16p histogram,
  190198. int full_dither)
  190199. {
  190200. png_debug(1, "in png_set_dither\n");
  190201. if(png_ptr == NULL) return;
  190202. png_ptr->transformations |= PNG_DITHER;
  190203. if (!full_dither)
  190204. {
  190205. int i;
  190206. png_ptr->dither_index = (png_bytep)png_malloc(png_ptr,
  190207. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190208. for (i = 0; i < num_palette; i++)
  190209. png_ptr->dither_index[i] = (png_byte)i;
  190210. }
  190211. if (num_palette > maximum_colors)
  190212. {
  190213. if (histogram != NULL)
  190214. {
  190215. /* This is easy enough, just throw out the least used colors.
  190216. Perhaps not the best solution, but good enough. */
  190217. int i;
  190218. /* initialize an array to sort colors */
  190219. png_ptr->dither_sort = (png_bytep)png_malloc(png_ptr,
  190220. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190221. /* initialize the dither_sort array */
  190222. for (i = 0; i < num_palette; i++)
  190223. png_ptr->dither_sort[i] = (png_byte)i;
  190224. /* Find the least used palette entries by starting a
  190225. bubble sort, and running it until we have sorted
  190226. out enough colors. Note that we don't care about
  190227. sorting all the colors, just finding which are
  190228. least used. */
  190229. for (i = num_palette - 1; i >= maximum_colors; i--)
  190230. {
  190231. int done; /* to stop early if the list is pre-sorted */
  190232. int j;
  190233. done = 1;
  190234. for (j = 0; j < i; j++)
  190235. {
  190236. if (histogram[png_ptr->dither_sort[j]]
  190237. < histogram[png_ptr->dither_sort[j + 1]])
  190238. {
  190239. png_byte t;
  190240. t = png_ptr->dither_sort[j];
  190241. png_ptr->dither_sort[j] = png_ptr->dither_sort[j + 1];
  190242. png_ptr->dither_sort[j + 1] = t;
  190243. done = 0;
  190244. }
  190245. }
  190246. if (done)
  190247. break;
  190248. }
  190249. /* swap the palette around, and set up a table, if necessary */
  190250. if (full_dither)
  190251. {
  190252. int j = num_palette;
  190253. /* put all the useful colors within the max, but don't
  190254. move the others */
  190255. for (i = 0; i < maximum_colors; i++)
  190256. {
  190257. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  190258. {
  190259. do
  190260. j--;
  190261. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  190262. palette[i] = palette[j];
  190263. }
  190264. }
  190265. }
  190266. else
  190267. {
  190268. int j = num_palette;
  190269. /* move all the used colors inside the max limit, and
  190270. develop a translation table */
  190271. for (i = 0; i < maximum_colors; i++)
  190272. {
  190273. /* only move the colors we need to */
  190274. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  190275. {
  190276. png_color tmp_color;
  190277. do
  190278. j--;
  190279. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  190280. tmp_color = palette[j];
  190281. palette[j] = palette[i];
  190282. palette[i] = tmp_color;
  190283. /* indicate where the color went */
  190284. png_ptr->dither_index[j] = (png_byte)i;
  190285. png_ptr->dither_index[i] = (png_byte)j;
  190286. }
  190287. }
  190288. /* find closest color for those colors we are not using */
  190289. for (i = 0; i < num_palette; i++)
  190290. {
  190291. if ((int)png_ptr->dither_index[i] >= maximum_colors)
  190292. {
  190293. int min_d, k, min_k, d_index;
  190294. /* find the closest color to one we threw out */
  190295. d_index = png_ptr->dither_index[i];
  190296. min_d = PNG_COLOR_DIST(palette[d_index], palette[0]);
  190297. for (k = 1, min_k = 0; k < maximum_colors; k++)
  190298. {
  190299. int d;
  190300. d = PNG_COLOR_DIST(palette[d_index], palette[k]);
  190301. if (d < min_d)
  190302. {
  190303. min_d = d;
  190304. min_k = k;
  190305. }
  190306. }
  190307. /* point to closest color */
  190308. png_ptr->dither_index[i] = (png_byte)min_k;
  190309. }
  190310. }
  190311. }
  190312. png_free(png_ptr, png_ptr->dither_sort);
  190313. png_ptr->dither_sort=NULL;
  190314. }
  190315. else
  190316. {
  190317. /* This is much harder to do simply (and quickly). Perhaps
  190318. we need to go through a median cut routine, but those
  190319. don't always behave themselves with only a few colors
  190320. as input. So we will just find the closest two colors,
  190321. and throw out one of them (chosen somewhat randomly).
  190322. [We don't understand this at all, so if someone wants to
  190323. work on improving it, be our guest - AED, GRP]
  190324. */
  190325. int i;
  190326. int max_d;
  190327. int num_new_palette;
  190328. png_dsortp t;
  190329. png_dsortpp hash;
  190330. t=NULL;
  190331. /* initialize palette index arrays */
  190332. png_ptr->index_to_palette = (png_bytep)png_malloc(png_ptr,
  190333. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190334. png_ptr->palette_to_index = (png_bytep)png_malloc(png_ptr,
  190335. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190336. /* initialize the sort array */
  190337. for (i = 0; i < num_palette; i++)
  190338. {
  190339. png_ptr->index_to_palette[i] = (png_byte)i;
  190340. png_ptr->palette_to_index[i] = (png_byte)i;
  190341. }
  190342. hash = (png_dsortpp)png_malloc(png_ptr, (png_uint_32)(769 *
  190343. png_sizeof (png_dsortp)));
  190344. for (i = 0; i < 769; i++)
  190345. hash[i] = NULL;
  190346. /* png_memset(hash, 0, 769 * png_sizeof (png_dsortp)); */
  190347. num_new_palette = num_palette;
  190348. /* initial wild guess at how far apart the farthest pixel
  190349. pair we will be eliminating will be. Larger
  190350. numbers mean more areas will be allocated, Smaller
  190351. numbers run the risk of not saving enough data, and
  190352. having to do this all over again.
  190353. I have not done extensive checking on this number.
  190354. */
  190355. max_d = 96;
  190356. while (num_new_palette > maximum_colors)
  190357. {
  190358. for (i = 0; i < num_new_palette - 1; i++)
  190359. {
  190360. int j;
  190361. for (j = i + 1; j < num_new_palette; j++)
  190362. {
  190363. int d;
  190364. d = PNG_COLOR_DIST(palette[i], palette[j]);
  190365. if (d <= max_d)
  190366. {
  190367. t = (png_dsortp)png_malloc_warn(png_ptr,
  190368. (png_uint_32)(png_sizeof(png_dsort)));
  190369. if (t == NULL)
  190370. break;
  190371. t->next = hash[d];
  190372. t->left = (png_byte)i;
  190373. t->right = (png_byte)j;
  190374. hash[d] = t;
  190375. }
  190376. }
  190377. if (t == NULL)
  190378. break;
  190379. }
  190380. if (t != NULL)
  190381. for (i = 0; i <= max_d; i++)
  190382. {
  190383. if (hash[i] != NULL)
  190384. {
  190385. png_dsortp p;
  190386. for (p = hash[i]; p; p = p->next)
  190387. {
  190388. if ((int)png_ptr->index_to_palette[p->left]
  190389. < num_new_palette &&
  190390. (int)png_ptr->index_to_palette[p->right]
  190391. < num_new_palette)
  190392. {
  190393. int j, next_j;
  190394. if (num_new_palette & 0x01)
  190395. {
  190396. j = p->left;
  190397. next_j = p->right;
  190398. }
  190399. else
  190400. {
  190401. j = p->right;
  190402. next_j = p->left;
  190403. }
  190404. num_new_palette--;
  190405. palette[png_ptr->index_to_palette[j]]
  190406. = palette[num_new_palette];
  190407. if (!full_dither)
  190408. {
  190409. int k;
  190410. for (k = 0; k < num_palette; k++)
  190411. {
  190412. if (png_ptr->dither_index[k] ==
  190413. png_ptr->index_to_palette[j])
  190414. png_ptr->dither_index[k] =
  190415. png_ptr->index_to_palette[next_j];
  190416. if ((int)png_ptr->dither_index[k] ==
  190417. num_new_palette)
  190418. png_ptr->dither_index[k] =
  190419. png_ptr->index_to_palette[j];
  190420. }
  190421. }
  190422. png_ptr->index_to_palette[png_ptr->palette_to_index
  190423. [num_new_palette]] = png_ptr->index_to_palette[j];
  190424. png_ptr->palette_to_index[png_ptr->index_to_palette[j]]
  190425. = png_ptr->palette_to_index[num_new_palette];
  190426. png_ptr->index_to_palette[j] = (png_byte)num_new_palette;
  190427. png_ptr->palette_to_index[num_new_palette] = (png_byte)j;
  190428. }
  190429. if (num_new_palette <= maximum_colors)
  190430. break;
  190431. }
  190432. if (num_new_palette <= maximum_colors)
  190433. break;
  190434. }
  190435. }
  190436. for (i = 0; i < 769; i++)
  190437. {
  190438. if (hash[i] != NULL)
  190439. {
  190440. png_dsortp p = hash[i];
  190441. while (p)
  190442. {
  190443. t = p->next;
  190444. png_free(png_ptr, p);
  190445. p = t;
  190446. }
  190447. }
  190448. hash[i] = 0;
  190449. }
  190450. max_d += 96;
  190451. }
  190452. png_free(png_ptr, hash);
  190453. png_free(png_ptr, png_ptr->palette_to_index);
  190454. png_free(png_ptr, png_ptr->index_to_palette);
  190455. png_ptr->palette_to_index=NULL;
  190456. png_ptr->index_to_palette=NULL;
  190457. }
  190458. num_palette = maximum_colors;
  190459. }
  190460. if (png_ptr->palette == NULL)
  190461. {
  190462. png_ptr->palette = palette;
  190463. }
  190464. png_ptr->num_palette = (png_uint_16)num_palette;
  190465. if (full_dither)
  190466. {
  190467. int i;
  190468. png_bytep distance;
  190469. int total_bits = PNG_DITHER_RED_BITS + PNG_DITHER_GREEN_BITS +
  190470. PNG_DITHER_BLUE_BITS;
  190471. int num_red = (1 << PNG_DITHER_RED_BITS);
  190472. int num_green = (1 << PNG_DITHER_GREEN_BITS);
  190473. int num_blue = (1 << PNG_DITHER_BLUE_BITS);
  190474. png_size_t num_entries = ((png_size_t)1 << total_bits);
  190475. png_ptr->palette_lookup = (png_bytep )png_malloc(png_ptr,
  190476. (png_uint_32)(num_entries * png_sizeof (png_byte)));
  190477. png_memset(png_ptr->palette_lookup, 0, num_entries *
  190478. png_sizeof (png_byte));
  190479. distance = (png_bytep)png_malloc(png_ptr, (png_uint_32)(num_entries *
  190480. png_sizeof(png_byte)));
  190481. png_memset(distance, 0xff, num_entries * png_sizeof(png_byte));
  190482. for (i = 0; i < num_palette; i++)
  190483. {
  190484. int ir, ig, ib;
  190485. int r = (palette[i].red >> (8 - PNG_DITHER_RED_BITS));
  190486. int g = (palette[i].green >> (8 - PNG_DITHER_GREEN_BITS));
  190487. int b = (palette[i].blue >> (8 - PNG_DITHER_BLUE_BITS));
  190488. for (ir = 0; ir < num_red; ir++)
  190489. {
  190490. /* int dr = abs(ir - r); */
  190491. int dr = ((ir > r) ? ir - r : r - ir);
  190492. int index_r = (ir << (PNG_DITHER_BLUE_BITS + PNG_DITHER_GREEN_BITS));
  190493. for (ig = 0; ig < num_green; ig++)
  190494. {
  190495. /* int dg = abs(ig - g); */
  190496. int dg = ((ig > g) ? ig - g : g - ig);
  190497. int dt = dr + dg;
  190498. int dm = ((dr > dg) ? dr : dg);
  190499. int index_g = index_r | (ig << PNG_DITHER_BLUE_BITS);
  190500. for (ib = 0; ib < num_blue; ib++)
  190501. {
  190502. int d_index = index_g | ib;
  190503. /* int db = abs(ib - b); */
  190504. int db = ((ib > b) ? ib - b : b - ib);
  190505. int dmax = ((dm > db) ? dm : db);
  190506. int d = dmax + dt + db;
  190507. if (d < (int)distance[d_index])
  190508. {
  190509. distance[d_index] = (png_byte)d;
  190510. png_ptr->palette_lookup[d_index] = (png_byte)i;
  190511. }
  190512. }
  190513. }
  190514. }
  190515. }
  190516. png_free(png_ptr, distance);
  190517. }
  190518. }
  190519. #endif
  190520. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  190521. /* Transform the image from the file_gamma to the screen_gamma. We
  190522. * only do transformations on images where the file_gamma and screen_gamma
  190523. * are not close reciprocals, otherwise it slows things down slightly, and
  190524. * also needlessly introduces small errors.
  190525. *
  190526. * We will turn off gamma transformation later if no semitransparent entries
  190527. * are present in the tRNS array for palette images. We can't do it here
  190528. * because we don't necessarily have the tRNS chunk yet.
  190529. */
  190530. void PNGAPI
  190531. png_set_gamma(png_structp png_ptr, double scrn_gamma, double file_gamma)
  190532. {
  190533. png_debug(1, "in png_set_gamma\n");
  190534. if(png_ptr == NULL) return;
  190535. if ((fabs(scrn_gamma * file_gamma - 1.0) > PNG_GAMMA_THRESHOLD) ||
  190536. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA) ||
  190537. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE))
  190538. png_ptr->transformations |= PNG_GAMMA;
  190539. png_ptr->gamma = (float)file_gamma;
  190540. png_ptr->screen_gamma = (float)scrn_gamma;
  190541. }
  190542. #endif
  190543. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190544. /* Expand paletted images to RGB, expand grayscale images of
  190545. * less than 8-bit depth to 8-bit depth, and expand tRNS chunks
  190546. * to alpha channels.
  190547. */
  190548. void PNGAPI
  190549. png_set_expand(png_structp png_ptr)
  190550. {
  190551. png_debug(1, "in png_set_expand\n");
  190552. if(png_ptr == NULL) return;
  190553. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190554. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190555. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190556. #endif
  190557. }
  190558. /* GRR 19990627: the following three functions currently are identical
  190559. * to png_set_expand(). However, it is entirely reasonable that someone
  190560. * might wish to expand an indexed image to RGB but *not* expand a single,
  190561. * fully transparent palette entry to a full alpha channel--perhaps instead
  190562. * convert tRNS to the grayscale/RGB format (16-bit RGB value), or replace
  190563. * the transparent color with a particular RGB value, or drop tRNS entirely.
  190564. * IOW, a future version of the library may make the transformations flag
  190565. * a bit more fine-grained, with separate bits for each of these three
  190566. * functions.
  190567. *
  190568. * More to the point, these functions make it obvious what libpng will be
  190569. * doing, whereas "expand" can (and does) mean any number of things.
  190570. *
  190571. * GRP 20060307: In libpng-1.4.0, png_set_gray_1_2_4_to_8() was modified
  190572. * to expand only the sample depth but not to expand the tRNS to alpha.
  190573. */
  190574. /* Expand paletted images to RGB. */
  190575. void PNGAPI
  190576. png_set_palette_to_rgb(png_structp png_ptr)
  190577. {
  190578. png_debug(1, "in png_set_palette_to_rgb\n");
  190579. if(png_ptr == NULL) return;
  190580. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190581. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190582. png_ptr->flags &= !(PNG_FLAG_ROW_INIT);
  190583. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190584. #endif
  190585. }
  190586. #if !defined(PNG_1_0_X)
  190587. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  190588. void PNGAPI
  190589. png_set_expand_gray_1_2_4_to_8(png_structp png_ptr)
  190590. {
  190591. png_debug(1, "in png_set_expand_gray_1_2_4_to_8\n");
  190592. if(png_ptr == NULL) return;
  190593. png_ptr->transformations |= PNG_EXPAND;
  190594. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190595. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190596. #endif
  190597. }
  190598. #endif
  190599. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  190600. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  190601. /* Deprecated as of libpng-1.2.9 */
  190602. void PNGAPI
  190603. png_set_gray_1_2_4_to_8(png_structp png_ptr)
  190604. {
  190605. png_debug(1, "in png_set_gray_1_2_4_to_8\n");
  190606. if(png_ptr == NULL) return;
  190607. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190608. }
  190609. #endif
  190610. /* Expand tRNS chunks to alpha channels. */
  190611. void PNGAPI
  190612. png_set_tRNS_to_alpha(png_structp png_ptr)
  190613. {
  190614. png_debug(1, "in png_set_tRNS_to_alpha\n");
  190615. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190616. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190617. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190618. #endif
  190619. }
  190620. #endif /* defined(PNG_READ_EXPAND_SUPPORTED) */
  190621. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190622. void PNGAPI
  190623. png_set_gray_to_rgb(png_structp png_ptr)
  190624. {
  190625. png_debug(1, "in png_set_gray_to_rgb\n");
  190626. png_ptr->transformations |= PNG_GRAY_TO_RGB;
  190627. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190628. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190629. #endif
  190630. }
  190631. #endif
  190632. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  190633. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  190634. /* Convert a RGB image to a grayscale of the same width. This allows us,
  190635. * for example, to convert a 24 bpp RGB image into an 8 bpp grayscale image.
  190636. */
  190637. void PNGAPI
  190638. png_set_rgb_to_gray(png_structp png_ptr, int error_action, double red,
  190639. double green)
  190640. {
  190641. int red_fixed = (int)((float)red*100000.0 + 0.5);
  190642. int green_fixed = (int)((float)green*100000.0 + 0.5);
  190643. if(png_ptr == NULL) return;
  190644. png_set_rgb_to_gray_fixed(png_ptr, error_action, red_fixed, green_fixed);
  190645. }
  190646. #endif
  190647. void PNGAPI
  190648. png_set_rgb_to_gray_fixed(png_structp png_ptr, int error_action,
  190649. png_fixed_point red, png_fixed_point green)
  190650. {
  190651. png_debug(1, "in png_set_rgb_to_gray\n");
  190652. if(png_ptr == NULL) return;
  190653. switch(error_action)
  190654. {
  190655. case 1: png_ptr->transformations |= PNG_RGB_TO_GRAY;
  190656. break;
  190657. case 2: png_ptr->transformations |= PNG_RGB_TO_GRAY_WARN;
  190658. break;
  190659. case 3: png_ptr->transformations |= PNG_RGB_TO_GRAY_ERR;
  190660. }
  190661. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190662. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190663. png_ptr->transformations |= PNG_EXPAND;
  190664. #else
  190665. {
  190666. png_warning(png_ptr, "Cannot do RGB_TO_GRAY without EXPAND_SUPPORTED.");
  190667. png_ptr->transformations &= ~PNG_RGB_TO_GRAY;
  190668. }
  190669. #endif
  190670. {
  190671. png_uint_16 red_int, green_int;
  190672. if(red < 0 || green < 0)
  190673. {
  190674. red_int = 6968; /* .212671 * 32768 + .5 */
  190675. green_int = 23434; /* .715160 * 32768 + .5 */
  190676. }
  190677. else if(red + green < 100000L)
  190678. {
  190679. red_int = (png_uint_16)(((png_uint_32)red*32768L)/100000L);
  190680. green_int = (png_uint_16)(((png_uint_32)green*32768L)/100000L);
  190681. }
  190682. else
  190683. {
  190684. png_warning(png_ptr, "ignoring out of range rgb_to_gray coefficients");
  190685. red_int = 6968;
  190686. green_int = 23434;
  190687. }
  190688. png_ptr->rgb_to_gray_red_coeff = red_int;
  190689. png_ptr->rgb_to_gray_green_coeff = green_int;
  190690. png_ptr->rgb_to_gray_blue_coeff = (png_uint_16)(32768-red_int-green_int);
  190691. }
  190692. }
  190693. #endif
  190694. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  190695. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  190696. defined(PNG_LEGACY_SUPPORTED)
  190697. void PNGAPI
  190698. png_set_read_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  190699. read_user_transform_fn)
  190700. {
  190701. png_debug(1, "in png_set_read_user_transform_fn\n");
  190702. if(png_ptr == NULL) return;
  190703. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  190704. png_ptr->transformations |= PNG_USER_TRANSFORM;
  190705. png_ptr->read_user_transform_fn = read_user_transform_fn;
  190706. #endif
  190707. #ifdef PNG_LEGACY_SUPPORTED
  190708. if(read_user_transform_fn)
  190709. png_warning(png_ptr,
  190710. "This version of libpng does not support user transforms");
  190711. #endif
  190712. }
  190713. #endif
  190714. /* Initialize everything needed for the read. This includes modifying
  190715. * the palette.
  190716. */
  190717. void /* PRIVATE */
  190718. png_init_read_transformations(png_structp png_ptr)
  190719. {
  190720. png_debug(1, "in png_init_read_transformations\n");
  190721. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190722. if(png_ptr != NULL)
  190723. #endif
  190724. {
  190725. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || defined(PNG_READ_SHIFT_SUPPORTED) \
  190726. || defined(PNG_READ_GAMMA_SUPPORTED)
  190727. int color_type = png_ptr->color_type;
  190728. #endif
  190729. #if defined(PNG_READ_EXPAND_SUPPORTED) && defined(PNG_READ_BACKGROUND_SUPPORTED)
  190730. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190731. /* Detect gray background and attempt to enable optimization
  190732. * for gray --> RGB case */
  190733. /* Note: if PNG_BACKGROUND_EXPAND is set and color_type is either RGB or
  190734. * RGB_ALPHA (in which case need_expand is superfluous anyway), the
  190735. * background color might actually be gray yet not be flagged as such.
  190736. * This is not a problem for the current code, which uses
  190737. * PNG_BACKGROUND_IS_GRAY only to decide when to do the
  190738. * png_do_gray_to_rgb() transformation.
  190739. */
  190740. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190741. !(color_type & PNG_COLOR_MASK_COLOR))
  190742. {
  190743. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  190744. } else if ((png_ptr->transformations & PNG_BACKGROUND) &&
  190745. !(png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190746. (png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  190747. png_ptr->background.red == png_ptr->background.green &&
  190748. png_ptr->background.red == png_ptr->background.blue)
  190749. {
  190750. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  190751. png_ptr->background.gray = png_ptr->background.red;
  190752. }
  190753. #endif
  190754. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190755. (png_ptr->transformations & PNG_EXPAND))
  190756. {
  190757. if (!(color_type & PNG_COLOR_MASK_COLOR)) /* i.e., GRAY or GRAY_ALPHA */
  190758. {
  190759. /* expand background and tRNS chunks */
  190760. switch (png_ptr->bit_depth)
  190761. {
  190762. case 1:
  190763. png_ptr->background.gray *= (png_uint_16)0xff;
  190764. png_ptr->background.red = png_ptr->background.green
  190765. = png_ptr->background.blue = png_ptr->background.gray;
  190766. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190767. {
  190768. png_ptr->trans_values.gray *= (png_uint_16)0xff;
  190769. png_ptr->trans_values.red = png_ptr->trans_values.green
  190770. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190771. }
  190772. break;
  190773. case 2:
  190774. png_ptr->background.gray *= (png_uint_16)0x55;
  190775. png_ptr->background.red = png_ptr->background.green
  190776. = png_ptr->background.blue = png_ptr->background.gray;
  190777. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190778. {
  190779. png_ptr->trans_values.gray *= (png_uint_16)0x55;
  190780. png_ptr->trans_values.red = png_ptr->trans_values.green
  190781. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190782. }
  190783. break;
  190784. case 4:
  190785. png_ptr->background.gray *= (png_uint_16)0x11;
  190786. png_ptr->background.red = png_ptr->background.green
  190787. = png_ptr->background.blue = png_ptr->background.gray;
  190788. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190789. {
  190790. png_ptr->trans_values.gray *= (png_uint_16)0x11;
  190791. png_ptr->trans_values.red = png_ptr->trans_values.green
  190792. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190793. }
  190794. break;
  190795. case 8:
  190796. case 16:
  190797. png_ptr->background.red = png_ptr->background.green
  190798. = png_ptr->background.blue = png_ptr->background.gray;
  190799. break;
  190800. }
  190801. }
  190802. else if (color_type == PNG_COLOR_TYPE_PALETTE)
  190803. {
  190804. png_ptr->background.red =
  190805. png_ptr->palette[png_ptr->background.index].red;
  190806. png_ptr->background.green =
  190807. png_ptr->palette[png_ptr->background.index].green;
  190808. png_ptr->background.blue =
  190809. png_ptr->palette[png_ptr->background.index].blue;
  190810. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  190811. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  190812. {
  190813. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190814. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190815. #endif
  190816. {
  190817. /* invert the alpha channel (in tRNS) unless the pixels are
  190818. going to be expanded, in which case leave it for later */
  190819. int i,istop;
  190820. istop=(int)png_ptr->num_trans;
  190821. for (i=0; i<istop; i++)
  190822. png_ptr->trans[i] = (png_byte)(255 - png_ptr->trans[i]);
  190823. }
  190824. }
  190825. #endif
  190826. }
  190827. }
  190828. #endif
  190829. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  190830. png_ptr->background_1 = png_ptr->background;
  190831. #endif
  190832. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  190833. if ((color_type == PNG_COLOR_TYPE_PALETTE && png_ptr->num_trans != 0)
  190834. && (fabs(png_ptr->screen_gamma * png_ptr->gamma - 1.0)
  190835. < PNG_GAMMA_THRESHOLD))
  190836. {
  190837. int i,k;
  190838. k=0;
  190839. for (i=0; i<png_ptr->num_trans; i++)
  190840. {
  190841. if (png_ptr->trans[i] != 0 && png_ptr->trans[i] != 0xff)
  190842. k=1; /* partial transparency is present */
  190843. }
  190844. if (k == 0)
  190845. png_ptr->transformations &= (~PNG_GAMMA);
  190846. }
  190847. if ((png_ptr->transformations & (PNG_GAMMA | PNG_RGB_TO_GRAY)) &&
  190848. png_ptr->gamma != 0.0)
  190849. {
  190850. png_build_gamma_table(png_ptr);
  190851. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190852. if (png_ptr->transformations & PNG_BACKGROUND)
  190853. {
  190854. if (color_type == PNG_COLOR_TYPE_PALETTE)
  190855. {
  190856. /* could skip if no transparency and
  190857. */
  190858. png_color back, back_1;
  190859. png_colorp palette = png_ptr->palette;
  190860. int num_palette = png_ptr->num_palette;
  190861. int i;
  190862. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  190863. {
  190864. back.red = png_ptr->gamma_table[png_ptr->background.red];
  190865. back.green = png_ptr->gamma_table[png_ptr->background.green];
  190866. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  190867. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  190868. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  190869. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  190870. }
  190871. else
  190872. {
  190873. double g, gs;
  190874. switch (png_ptr->background_gamma_type)
  190875. {
  190876. case PNG_BACKGROUND_GAMMA_SCREEN:
  190877. g = (png_ptr->screen_gamma);
  190878. gs = 1.0;
  190879. break;
  190880. case PNG_BACKGROUND_GAMMA_FILE:
  190881. g = 1.0 / (png_ptr->gamma);
  190882. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  190883. break;
  190884. case PNG_BACKGROUND_GAMMA_UNIQUE:
  190885. g = 1.0 / (png_ptr->background_gamma);
  190886. gs = 1.0 / (png_ptr->background_gamma *
  190887. png_ptr->screen_gamma);
  190888. break;
  190889. default:
  190890. g = 1.0; /* back_1 */
  190891. gs = 1.0; /* back */
  190892. }
  190893. if ( fabs(gs - 1.0) < PNG_GAMMA_THRESHOLD)
  190894. {
  190895. back.red = (png_byte)png_ptr->background.red;
  190896. back.green = (png_byte)png_ptr->background.green;
  190897. back.blue = (png_byte)png_ptr->background.blue;
  190898. }
  190899. else
  190900. {
  190901. back.red = (png_byte)(pow(
  190902. (double)png_ptr->background.red/255, gs) * 255.0 + .5);
  190903. back.green = (png_byte)(pow(
  190904. (double)png_ptr->background.green/255, gs) * 255.0 + .5);
  190905. back.blue = (png_byte)(pow(
  190906. (double)png_ptr->background.blue/255, gs) * 255.0 + .5);
  190907. }
  190908. back_1.red = (png_byte)(pow(
  190909. (double)png_ptr->background.red/255, g) * 255.0 + .5);
  190910. back_1.green = (png_byte)(pow(
  190911. (double)png_ptr->background.green/255, g) * 255.0 + .5);
  190912. back_1.blue = (png_byte)(pow(
  190913. (double)png_ptr->background.blue/255, g) * 255.0 + .5);
  190914. }
  190915. for (i = 0; i < num_palette; i++)
  190916. {
  190917. if (i < (int)png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  190918. {
  190919. if (png_ptr->trans[i] == 0)
  190920. {
  190921. palette[i] = back;
  190922. }
  190923. else /* if (png_ptr->trans[i] != 0xff) */
  190924. {
  190925. png_byte v, w;
  190926. v = png_ptr->gamma_to_1[palette[i].red];
  190927. png_composite(w, v, png_ptr->trans[i], back_1.red);
  190928. palette[i].red = png_ptr->gamma_from_1[w];
  190929. v = png_ptr->gamma_to_1[palette[i].green];
  190930. png_composite(w, v, png_ptr->trans[i], back_1.green);
  190931. palette[i].green = png_ptr->gamma_from_1[w];
  190932. v = png_ptr->gamma_to_1[palette[i].blue];
  190933. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  190934. palette[i].blue = png_ptr->gamma_from_1[w];
  190935. }
  190936. }
  190937. else
  190938. {
  190939. palette[i].red = png_ptr->gamma_table[palette[i].red];
  190940. palette[i].green = png_ptr->gamma_table[palette[i].green];
  190941. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  190942. }
  190943. }
  190944. }
  190945. /* if (png_ptr->background_gamma_type!=PNG_BACKGROUND_GAMMA_UNKNOWN) */
  190946. else
  190947. /* color_type != PNG_COLOR_TYPE_PALETTE */
  190948. {
  190949. double m = (double)(((png_uint_32)1 << png_ptr->bit_depth) - 1);
  190950. double g = 1.0;
  190951. double gs = 1.0;
  190952. switch (png_ptr->background_gamma_type)
  190953. {
  190954. case PNG_BACKGROUND_GAMMA_SCREEN:
  190955. g = (png_ptr->screen_gamma);
  190956. gs = 1.0;
  190957. break;
  190958. case PNG_BACKGROUND_GAMMA_FILE:
  190959. g = 1.0 / (png_ptr->gamma);
  190960. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  190961. break;
  190962. case PNG_BACKGROUND_GAMMA_UNIQUE:
  190963. g = 1.0 / (png_ptr->background_gamma);
  190964. gs = 1.0 / (png_ptr->background_gamma *
  190965. png_ptr->screen_gamma);
  190966. break;
  190967. }
  190968. png_ptr->background_1.gray = (png_uint_16)(pow(
  190969. (double)png_ptr->background.gray / m, g) * m + .5);
  190970. png_ptr->background.gray = (png_uint_16)(pow(
  190971. (double)png_ptr->background.gray / m, gs) * m + .5);
  190972. if ((png_ptr->background.red != png_ptr->background.green) ||
  190973. (png_ptr->background.red != png_ptr->background.blue) ||
  190974. (png_ptr->background.red != png_ptr->background.gray))
  190975. {
  190976. /* RGB or RGBA with color background */
  190977. png_ptr->background_1.red = (png_uint_16)(pow(
  190978. (double)png_ptr->background.red / m, g) * m + .5);
  190979. png_ptr->background_1.green = (png_uint_16)(pow(
  190980. (double)png_ptr->background.green / m, g) * m + .5);
  190981. png_ptr->background_1.blue = (png_uint_16)(pow(
  190982. (double)png_ptr->background.blue / m, g) * m + .5);
  190983. png_ptr->background.red = (png_uint_16)(pow(
  190984. (double)png_ptr->background.red / m, gs) * m + .5);
  190985. png_ptr->background.green = (png_uint_16)(pow(
  190986. (double)png_ptr->background.green / m, gs) * m + .5);
  190987. png_ptr->background.blue = (png_uint_16)(pow(
  190988. (double)png_ptr->background.blue / m, gs) * m + .5);
  190989. }
  190990. else
  190991. {
  190992. /* GRAY, GRAY ALPHA, RGB, or RGBA with gray background */
  190993. png_ptr->background_1.red = png_ptr->background_1.green
  190994. = png_ptr->background_1.blue = png_ptr->background_1.gray;
  190995. png_ptr->background.red = png_ptr->background.green
  190996. = png_ptr->background.blue = png_ptr->background.gray;
  190997. }
  190998. }
  190999. }
  191000. else
  191001. /* transformation does not include PNG_BACKGROUND */
  191002. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  191003. if (color_type == PNG_COLOR_TYPE_PALETTE)
  191004. {
  191005. png_colorp palette = png_ptr->palette;
  191006. int num_palette = png_ptr->num_palette;
  191007. int i;
  191008. for (i = 0; i < num_palette; i++)
  191009. {
  191010. palette[i].red = png_ptr->gamma_table[palette[i].red];
  191011. palette[i].green = png_ptr->gamma_table[palette[i].green];
  191012. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  191013. }
  191014. }
  191015. }
  191016. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191017. else
  191018. #endif
  191019. #endif /* PNG_READ_GAMMA_SUPPORTED && PNG_FLOATING_POINT_SUPPORTED */
  191020. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191021. /* No GAMMA transformation */
  191022. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  191023. (color_type == PNG_COLOR_TYPE_PALETTE))
  191024. {
  191025. int i;
  191026. int istop = (int)png_ptr->num_trans;
  191027. png_color back;
  191028. png_colorp palette = png_ptr->palette;
  191029. back.red = (png_byte)png_ptr->background.red;
  191030. back.green = (png_byte)png_ptr->background.green;
  191031. back.blue = (png_byte)png_ptr->background.blue;
  191032. for (i = 0; i < istop; i++)
  191033. {
  191034. if (png_ptr->trans[i] == 0)
  191035. {
  191036. palette[i] = back;
  191037. }
  191038. else if (png_ptr->trans[i] != 0xff)
  191039. {
  191040. /* The png_composite() macro is defined in png.h */
  191041. png_composite(palette[i].red, palette[i].red,
  191042. png_ptr->trans[i], back.red);
  191043. png_composite(palette[i].green, palette[i].green,
  191044. png_ptr->trans[i], back.green);
  191045. png_composite(palette[i].blue, palette[i].blue,
  191046. png_ptr->trans[i], back.blue);
  191047. }
  191048. }
  191049. }
  191050. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  191051. #if defined(PNG_READ_SHIFT_SUPPORTED)
  191052. if ((png_ptr->transformations & PNG_SHIFT) &&
  191053. (color_type == PNG_COLOR_TYPE_PALETTE))
  191054. {
  191055. png_uint_16 i;
  191056. png_uint_16 istop = png_ptr->num_palette;
  191057. int sr = 8 - png_ptr->sig_bit.red;
  191058. int sg = 8 - png_ptr->sig_bit.green;
  191059. int sb = 8 - png_ptr->sig_bit.blue;
  191060. if (sr < 0 || sr > 8)
  191061. sr = 0;
  191062. if (sg < 0 || sg > 8)
  191063. sg = 0;
  191064. if (sb < 0 || sb > 8)
  191065. sb = 0;
  191066. for (i = 0; i < istop; i++)
  191067. {
  191068. png_ptr->palette[i].red >>= sr;
  191069. png_ptr->palette[i].green >>= sg;
  191070. png_ptr->palette[i].blue >>= sb;
  191071. }
  191072. }
  191073. #endif /* PNG_READ_SHIFT_SUPPORTED */
  191074. }
  191075. #if !defined(PNG_READ_GAMMA_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED) \
  191076. && !defined(PNG_READ_BACKGROUND_SUPPORTED)
  191077. if(png_ptr)
  191078. return;
  191079. #endif
  191080. }
  191081. /* Modify the info structure to reflect the transformations. The
  191082. * info should be updated so a PNG file could be written with it,
  191083. * assuming the transformations result in valid PNG data.
  191084. */
  191085. void /* PRIVATE */
  191086. png_read_transform_info(png_structp png_ptr, png_infop info_ptr)
  191087. {
  191088. png_debug(1, "in png_read_transform_info\n");
  191089. #if defined(PNG_READ_EXPAND_SUPPORTED)
  191090. if (png_ptr->transformations & PNG_EXPAND)
  191091. {
  191092. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  191093. {
  191094. if (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND_tRNS))
  191095. info_ptr->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  191096. else
  191097. info_ptr->color_type = PNG_COLOR_TYPE_RGB;
  191098. info_ptr->bit_depth = 8;
  191099. info_ptr->num_trans = 0;
  191100. }
  191101. else
  191102. {
  191103. if (png_ptr->num_trans)
  191104. {
  191105. if (png_ptr->transformations & PNG_EXPAND_tRNS)
  191106. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  191107. else
  191108. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  191109. }
  191110. if (info_ptr->bit_depth < 8)
  191111. info_ptr->bit_depth = 8;
  191112. info_ptr->num_trans = 0;
  191113. }
  191114. }
  191115. #endif
  191116. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191117. if (png_ptr->transformations & PNG_BACKGROUND)
  191118. {
  191119. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  191120. info_ptr->num_trans = 0;
  191121. info_ptr->background = png_ptr->background;
  191122. }
  191123. #endif
  191124. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191125. if (png_ptr->transformations & PNG_GAMMA)
  191126. {
  191127. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191128. info_ptr->gamma = png_ptr->gamma;
  191129. #endif
  191130. #ifdef PNG_FIXED_POINT_SUPPORTED
  191131. info_ptr->int_gamma = png_ptr->int_gamma;
  191132. #endif
  191133. }
  191134. #endif
  191135. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  191136. if ((png_ptr->transformations & PNG_16_TO_8) && (info_ptr->bit_depth == 16))
  191137. info_ptr->bit_depth = 8;
  191138. #endif
  191139. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191140. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  191141. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  191142. #endif
  191143. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  191144. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  191145. info_ptr->color_type &= ~PNG_COLOR_MASK_COLOR;
  191146. #endif
  191147. #if defined(PNG_READ_DITHER_SUPPORTED)
  191148. if (png_ptr->transformations & PNG_DITHER)
  191149. {
  191150. if (((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  191151. (info_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)) &&
  191152. png_ptr->palette_lookup && info_ptr->bit_depth == 8)
  191153. {
  191154. info_ptr->color_type = PNG_COLOR_TYPE_PALETTE;
  191155. }
  191156. }
  191157. #endif
  191158. #if defined(PNG_READ_PACK_SUPPORTED)
  191159. if ((png_ptr->transformations & PNG_PACK) && (info_ptr->bit_depth < 8))
  191160. info_ptr->bit_depth = 8;
  191161. #endif
  191162. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  191163. info_ptr->channels = 1;
  191164. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  191165. info_ptr->channels = 3;
  191166. else
  191167. info_ptr->channels = 1;
  191168. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  191169. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  191170. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  191171. #endif
  191172. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  191173. info_ptr->channels++;
  191174. #if defined(PNG_READ_FILLER_SUPPORTED)
  191175. /* STRIP_ALPHA and FILLER allowed: MASK_ALPHA bit stripped above */
  191176. if ((png_ptr->transformations & PNG_FILLER) &&
  191177. ((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  191178. (info_ptr->color_type == PNG_COLOR_TYPE_GRAY)))
  191179. {
  191180. info_ptr->channels++;
  191181. /* if adding a true alpha channel not just filler */
  191182. #if !defined(PNG_1_0_X)
  191183. if (png_ptr->transformations & PNG_ADD_ALPHA)
  191184. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  191185. #endif
  191186. }
  191187. #endif
  191188. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED) && \
  191189. defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  191190. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  191191. {
  191192. if(info_ptr->bit_depth < png_ptr->user_transform_depth)
  191193. info_ptr->bit_depth = png_ptr->user_transform_depth;
  191194. if(info_ptr->channels < png_ptr->user_transform_channels)
  191195. info_ptr->channels = png_ptr->user_transform_channels;
  191196. }
  191197. #endif
  191198. info_ptr->pixel_depth = (png_byte)(info_ptr->channels *
  191199. info_ptr->bit_depth);
  191200. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,info_ptr->width);
  191201. #if !defined(PNG_READ_EXPAND_SUPPORTED)
  191202. if(png_ptr)
  191203. return;
  191204. #endif
  191205. }
  191206. /* Transform the row. The order of transformations is significant,
  191207. * and is very touchy. If you add a transformation, take care to
  191208. * decide how it fits in with the other transformations here.
  191209. */
  191210. void /* PRIVATE */
  191211. png_do_read_transformations(png_structp png_ptr)
  191212. {
  191213. png_debug(1, "in png_do_read_transformations\n");
  191214. if (png_ptr->row_buf == NULL)
  191215. {
  191216. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  191217. char msg[50];
  191218. png_snprintf2(msg, 50,
  191219. "NULL row buffer for row %ld, pass %d", png_ptr->row_number,
  191220. png_ptr->pass);
  191221. png_error(png_ptr, msg);
  191222. #else
  191223. png_error(png_ptr, "NULL row buffer");
  191224. #endif
  191225. }
  191226. #ifdef PNG_WARN_UNINITIALIZED_ROW
  191227. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  191228. /* Application has failed to call either png_read_start_image()
  191229. * or png_read_update_info() after setting transforms that expand
  191230. * pixels. This check added to libpng-1.2.19 */
  191231. #if (PNG_WARN_UNINITIALIZED_ROW==1)
  191232. png_error(png_ptr, "Uninitialized row");
  191233. #else
  191234. png_warning(png_ptr, "Uninitialized row");
  191235. #endif
  191236. #endif
  191237. #if defined(PNG_READ_EXPAND_SUPPORTED)
  191238. if (png_ptr->transformations & PNG_EXPAND)
  191239. {
  191240. if (png_ptr->row_info.color_type == PNG_COLOR_TYPE_PALETTE)
  191241. {
  191242. png_do_expand_palette(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191243. png_ptr->palette, png_ptr->trans, png_ptr->num_trans);
  191244. }
  191245. else
  191246. {
  191247. if (png_ptr->num_trans &&
  191248. (png_ptr->transformations & PNG_EXPAND_tRNS))
  191249. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191250. &(png_ptr->trans_values));
  191251. else
  191252. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191253. NULL);
  191254. }
  191255. }
  191256. #endif
  191257. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  191258. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  191259. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191260. PNG_FLAG_FILLER_AFTER | (png_ptr->flags & PNG_FLAG_STRIP_ALPHA));
  191261. #endif
  191262. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  191263. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  191264. {
  191265. int rgb_error =
  191266. png_do_rgb_to_gray(png_ptr, &(png_ptr->row_info), png_ptr->row_buf + 1);
  191267. if(rgb_error)
  191268. {
  191269. png_ptr->rgb_to_gray_status=1;
  191270. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  191271. PNG_RGB_TO_GRAY_WARN)
  191272. png_warning(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  191273. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  191274. PNG_RGB_TO_GRAY_ERR)
  191275. png_error(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  191276. }
  191277. }
  191278. #endif
  191279. /*
  191280. From Andreas Dilger e-mail to png-implement, 26 March 1998:
  191281. In most cases, the "simple transparency" should be done prior to doing
  191282. gray-to-RGB, or you will have to test 3x as many bytes to check if a
  191283. pixel is transparent. You would also need to make sure that the
  191284. transparency information is upgraded to RGB.
  191285. To summarize, the current flow is:
  191286. - Gray + simple transparency -> compare 1 or 2 gray bytes and composite
  191287. with background "in place" if transparent,
  191288. convert to RGB if necessary
  191289. - Gray + alpha -> composite with gray background and remove alpha bytes,
  191290. convert to RGB if necessary
  191291. To support RGB backgrounds for gray images we need:
  191292. - Gray + simple transparency -> convert to RGB + simple transparency, compare
  191293. 3 or 6 bytes and composite with background
  191294. "in place" if transparent (3x compare/pixel
  191295. compared to doing composite with gray bkgrnd)
  191296. - Gray + alpha -> convert to RGB + alpha, composite with background and
  191297. remove alpha bytes (3x float operations/pixel
  191298. compared with composite on gray background)
  191299. Greg's change will do this. The reason it wasn't done before is for
  191300. performance, as this increases the per-pixel operations. If we would check
  191301. in advance if the background was gray or RGB, and position the gray-to-RGB
  191302. transform appropriately, then it would save a lot of work/time.
  191303. */
  191304. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191305. /* if gray -> RGB, do so now only if background is non-gray; else do later
  191306. * for performance reasons */
  191307. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  191308. !(png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  191309. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191310. #endif
  191311. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191312. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  191313. ((png_ptr->num_trans != 0 ) ||
  191314. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA)))
  191315. png_do_background(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191316. &(png_ptr->trans_values), &(png_ptr->background)
  191317. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191318. , &(png_ptr->background_1),
  191319. png_ptr->gamma_table, png_ptr->gamma_from_1,
  191320. png_ptr->gamma_to_1, png_ptr->gamma_16_table,
  191321. png_ptr->gamma_16_from_1, png_ptr->gamma_16_to_1,
  191322. png_ptr->gamma_shift
  191323. #endif
  191324. );
  191325. #endif
  191326. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191327. if ((png_ptr->transformations & PNG_GAMMA) &&
  191328. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191329. !((png_ptr->transformations & PNG_BACKGROUND) &&
  191330. ((png_ptr->num_trans != 0) ||
  191331. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA))) &&
  191332. #endif
  191333. (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE))
  191334. png_do_gamma(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191335. png_ptr->gamma_table, png_ptr->gamma_16_table,
  191336. png_ptr->gamma_shift);
  191337. #endif
  191338. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  191339. if (png_ptr->transformations & PNG_16_TO_8)
  191340. png_do_chop(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191341. #endif
  191342. #if defined(PNG_READ_DITHER_SUPPORTED)
  191343. if (png_ptr->transformations & PNG_DITHER)
  191344. {
  191345. png_do_dither((png_row_infop)&(png_ptr->row_info), png_ptr->row_buf + 1,
  191346. png_ptr->palette_lookup, png_ptr->dither_index);
  191347. if(png_ptr->row_info.rowbytes == (png_uint_32)0)
  191348. png_error(png_ptr, "png_do_dither returned rowbytes=0");
  191349. }
  191350. #endif
  191351. #if defined(PNG_READ_INVERT_SUPPORTED)
  191352. if (png_ptr->transformations & PNG_INVERT_MONO)
  191353. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191354. #endif
  191355. #if defined(PNG_READ_SHIFT_SUPPORTED)
  191356. if (png_ptr->transformations & PNG_SHIFT)
  191357. png_do_unshift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191358. &(png_ptr->shift));
  191359. #endif
  191360. #if defined(PNG_READ_PACK_SUPPORTED)
  191361. if (png_ptr->transformations & PNG_PACK)
  191362. png_do_unpack(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191363. #endif
  191364. #if defined(PNG_READ_BGR_SUPPORTED)
  191365. if (png_ptr->transformations & PNG_BGR)
  191366. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191367. #endif
  191368. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  191369. if (png_ptr->transformations & PNG_PACKSWAP)
  191370. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191371. #endif
  191372. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191373. /* if gray -> RGB, do so now only if we did not do so above */
  191374. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  191375. (png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  191376. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191377. #endif
  191378. #if defined(PNG_READ_FILLER_SUPPORTED)
  191379. if (png_ptr->transformations & PNG_FILLER)
  191380. png_do_read_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191381. (png_uint_32)png_ptr->filler, png_ptr->flags);
  191382. #endif
  191383. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  191384. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  191385. png_do_read_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191386. #endif
  191387. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  191388. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  191389. png_do_read_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191390. #endif
  191391. #if defined(PNG_READ_SWAP_SUPPORTED)
  191392. if (png_ptr->transformations & PNG_SWAP_BYTES)
  191393. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191394. #endif
  191395. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  191396. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  191397. {
  191398. if(png_ptr->read_user_transform_fn != NULL)
  191399. (*(png_ptr->read_user_transform_fn)) /* user read transform function */
  191400. (png_ptr, /* png_ptr */
  191401. &(png_ptr->row_info), /* row_info: */
  191402. /* png_uint_32 width; width of row */
  191403. /* png_uint_32 rowbytes; number of bytes in row */
  191404. /* png_byte color_type; color type of pixels */
  191405. /* png_byte bit_depth; bit depth of samples */
  191406. /* png_byte channels; number of channels (1-4) */
  191407. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  191408. png_ptr->row_buf + 1); /* start of pixel data for row */
  191409. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  191410. if(png_ptr->user_transform_depth)
  191411. png_ptr->row_info.bit_depth = png_ptr->user_transform_depth;
  191412. if(png_ptr->user_transform_channels)
  191413. png_ptr->row_info.channels = png_ptr->user_transform_channels;
  191414. #endif
  191415. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  191416. png_ptr->row_info.channels);
  191417. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  191418. png_ptr->row_info.width);
  191419. }
  191420. #endif
  191421. }
  191422. #if defined(PNG_READ_PACK_SUPPORTED)
  191423. /* Unpack pixels of 1, 2, or 4 bits per pixel into 1 byte per pixel,
  191424. * without changing the actual values. Thus, if you had a row with
  191425. * a bit depth of 1, you would end up with bytes that only contained
  191426. * the numbers 0 or 1. If you would rather they contain 0 and 255, use
  191427. * png_do_shift() after this.
  191428. */
  191429. void /* PRIVATE */
  191430. png_do_unpack(png_row_infop row_info, png_bytep row)
  191431. {
  191432. png_debug(1, "in png_do_unpack\n");
  191433. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191434. if (row != NULL && row_info != NULL && row_info->bit_depth < 8)
  191435. #else
  191436. if (row_info->bit_depth < 8)
  191437. #endif
  191438. {
  191439. png_uint_32 i;
  191440. png_uint_32 row_width=row_info->width;
  191441. switch (row_info->bit_depth)
  191442. {
  191443. case 1:
  191444. {
  191445. png_bytep sp = row + (png_size_t)((row_width - 1) >> 3);
  191446. png_bytep dp = row + (png_size_t)row_width - 1;
  191447. png_uint_32 shift = 7 - (int)((row_width + 7) & 0x07);
  191448. for (i = 0; i < row_width; i++)
  191449. {
  191450. *dp = (png_byte)((*sp >> shift) & 0x01);
  191451. if (shift == 7)
  191452. {
  191453. shift = 0;
  191454. sp--;
  191455. }
  191456. else
  191457. shift++;
  191458. dp--;
  191459. }
  191460. break;
  191461. }
  191462. case 2:
  191463. {
  191464. png_bytep sp = row + (png_size_t)((row_width - 1) >> 2);
  191465. png_bytep dp = row + (png_size_t)row_width - 1;
  191466. png_uint_32 shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  191467. for (i = 0; i < row_width; i++)
  191468. {
  191469. *dp = (png_byte)((*sp >> shift) & 0x03);
  191470. if (shift == 6)
  191471. {
  191472. shift = 0;
  191473. sp--;
  191474. }
  191475. else
  191476. shift += 2;
  191477. dp--;
  191478. }
  191479. break;
  191480. }
  191481. case 4:
  191482. {
  191483. png_bytep sp = row + (png_size_t)((row_width - 1) >> 1);
  191484. png_bytep dp = row + (png_size_t)row_width - 1;
  191485. png_uint_32 shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  191486. for (i = 0; i < row_width; i++)
  191487. {
  191488. *dp = (png_byte)((*sp >> shift) & 0x0f);
  191489. if (shift == 4)
  191490. {
  191491. shift = 0;
  191492. sp--;
  191493. }
  191494. else
  191495. shift = 4;
  191496. dp--;
  191497. }
  191498. break;
  191499. }
  191500. }
  191501. row_info->bit_depth = 8;
  191502. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  191503. row_info->rowbytes = row_width * row_info->channels;
  191504. }
  191505. }
  191506. #endif
  191507. #if defined(PNG_READ_SHIFT_SUPPORTED)
  191508. /* Reverse the effects of png_do_shift. This routine merely shifts the
  191509. * pixels back to their significant bits values. Thus, if you have
  191510. * a row of bit depth 8, but only 5 are significant, this will shift
  191511. * the values back to 0 through 31.
  191512. */
  191513. void /* PRIVATE */
  191514. png_do_unshift(png_row_infop row_info, png_bytep row, png_color_8p sig_bits)
  191515. {
  191516. png_debug(1, "in png_do_unshift\n");
  191517. if (
  191518. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191519. row != NULL && row_info != NULL && sig_bits != NULL &&
  191520. #endif
  191521. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  191522. {
  191523. int shift[4];
  191524. int channels = 0;
  191525. int c;
  191526. png_uint_16 value = 0;
  191527. png_uint_32 row_width = row_info->width;
  191528. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  191529. {
  191530. shift[channels++] = row_info->bit_depth - sig_bits->red;
  191531. shift[channels++] = row_info->bit_depth - sig_bits->green;
  191532. shift[channels++] = row_info->bit_depth - sig_bits->blue;
  191533. }
  191534. else
  191535. {
  191536. shift[channels++] = row_info->bit_depth - sig_bits->gray;
  191537. }
  191538. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  191539. {
  191540. shift[channels++] = row_info->bit_depth - sig_bits->alpha;
  191541. }
  191542. for (c = 0; c < channels; c++)
  191543. {
  191544. if (shift[c] <= 0)
  191545. shift[c] = 0;
  191546. else
  191547. value = 1;
  191548. }
  191549. if (!value)
  191550. return;
  191551. switch (row_info->bit_depth)
  191552. {
  191553. case 2:
  191554. {
  191555. png_bytep bp;
  191556. png_uint_32 i;
  191557. png_uint_32 istop = row_info->rowbytes;
  191558. for (bp = row, i = 0; i < istop; i++)
  191559. {
  191560. *bp >>= 1;
  191561. *bp++ &= 0x55;
  191562. }
  191563. break;
  191564. }
  191565. case 4:
  191566. {
  191567. png_bytep bp = row;
  191568. png_uint_32 i;
  191569. png_uint_32 istop = row_info->rowbytes;
  191570. png_byte mask = (png_byte)((((int)0xf0 >> shift[0]) & (int)0xf0) |
  191571. (png_byte)((int)0xf >> shift[0]));
  191572. for (i = 0; i < istop; i++)
  191573. {
  191574. *bp >>= shift[0];
  191575. *bp++ &= mask;
  191576. }
  191577. break;
  191578. }
  191579. case 8:
  191580. {
  191581. png_bytep bp = row;
  191582. png_uint_32 i;
  191583. png_uint_32 istop = row_width * channels;
  191584. for (i = 0; i < istop; i++)
  191585. {
  191586. *bp++ >>= shift[i%channels];
  191587. }
  191588. break;
  191589. }
  191590. case 16:
  191591. {
  191592. png_bytep bp = row;
  191593. png_uint_32 i;
  191594. png_uint_32 istop = channels * row_width;
  191595. for (i = 0; i < istop; i++)
  191596. {
  191597. value = (png_uint_16)((*bp << 8) + *(bp + 1));
  191598. value >>= shift[i%channels];
  191599. *bp++ = (png_byte)(value >> 8);
  191600. *bp++ = (png_byte)(value & 0xff);
  191601. }
  191602. break;
  191603. }
  191604. }
  191605. }
  191606. }
  191607. #endif
  191608. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  191609. /* chop rows of bit depth 16 down to 8 */
  191610. void /* PRIVATE */
  191611. png_do_chop(png_row_infop row_info, png_bytep row)
  191612. {
  191613. png_debug(1, "in png_do_chop\n");
  191614. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191615. if (row != NULL && row_info != NULL && row_info->bit_depth == 16)
  191616. #else
  191617. if (row_info->bit_depth == 16)
  191618. #endif
  191619. {
  191620. png_bytep sp = row;
  191621. png_bytep dp = row;
  191622. png_uint_32 i;
  191623. png_uint_32 istop = row_info->width * row_info->channels;
  191624. for (i = 0; i<istop; i++, sp += 2, dp++)
  191625. {
  191626. #if defined(PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED)
  191627. /* This does a more accurate scaling of the 16-bit color
  191628. * value, rather than a simple low-byte truncation.
  191629. *
  191630. * What the ideal calculation should be:
  191631. * *dp = (((((png_uint_32)(*sp) << 8) |
  191632. * (png_uint_32)(*(sp + 1))) * 255 + 127) / (png_uint_32)65535L;
  191633. *
  191634. * GRR: no, I think this is what it really should be:
  191635. * *dp = (((((png_uint_32)(*sp) << 8) |
  191636. * (png_uint_32)(*(sp + 1))) + 128L) / (png_uint_32)257L;
  191637. *
  191638. * GRR: here's the exact calculation with shifts:
  191639. * temp = (((png_uint_32)(*sp) << 8) | (png_uint_32)(*(sp + 1))) + 128L;
  191640. * *dp = (temp - (temp >> 8)) >> 8;
  191641. *
  191642. * Approximate calculation with shift/add instead of multiply/divide:
  191643. * *dp = ((((png_uint_32)(*sp) << 8) |
  191644. * (png_uint_32)((int)(*(sp + 1)) - *sp)) + 128) >> 8;
  191645. *
  191646. * What we actually do to avoid extra shifting and conversion:
  191647. */
  191648. *dp = *sp + ((((int)(*(sp + 1)) - *sp) > 128) ? 1 : 0);
  191649. #else
  191650. /* Simply discard the low order byte */
  191651. *dp = *sp;
  191652. #endif
  191653. }
  191654. row_info->bit_depth = 8;
  191655. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  191656. row_info->rowbytes = row_info->width * row_info->channels;
  191657. }
  191658. }
  191659. #endif
  191660. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  191661. void /* PRIVATE */
  191662. png_do_read_swap_alpha(png_row_infop row_info, png_bytep row)
  191663. {
  191664. png_debug(1, "in png_do_read_swap_alpha\n");
  191665. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191666. if (row != NULL && row_info != NULL)
  191667. #endif
  191668. {
  191669. png_uint_32 row_width = row_info->width;
  191670. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191671. {
  191672. /* This converts from RGBA to ARGB */
  191673. if (row_info->bit_depth == 8)
  191674. {
  191675. png_bytep sp = row + row_info->rowbytes;
  191676. png_bytep dp = sp;
  191677. png_byte save;
  191678. png_uint_32 i;
  191679. for (i = 0; i < row_width; i++)
  191680. {
  191681. save = *(--sp);
  191682. *(--dp) = *(--sp);
  191683. *(--dp) = *(--sp);
  191684. *(--dp) = *(--sp);
  191685. *(--dp) = save;
  191686. }
  191687. }
  191688. /* This converts from RRGGBBAA to AARRGGBB */
  191689. else
  191690. {
  191691. png_bytep sp = row + row_info->rowbytes;
  191692. png_bytep dp = sp;
  191693. png_byte save[2];
  191694. png_uint_32 i;
  191695. for (i = 0; i < row_width; i++)
  191696. {
  191697. save[0] = *(--sp);
  191698. save[1] = *(--sp);
  191699. *(--dp) = *(--sp);
  191700. *(--dp) = *(--sp);
  191701. *(--dp) = *(--sp);
  191702. *(--dp) = *(--sp);
  191703. *(--dp) = *(--sp);
  191704. *(--dp) = *(--sp);
  191705. *(--dp) = save[0];
  191706. *(--dp) = save[1];
  191707. }
  191708. }
  191709. }
  191710. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191711. {
  191712. /* This converts from GA to AG */
  191713. if (row_info->bit_depth == 8)
  191714. {
  191715. png_bytep sp = row + row_info->rowbytes;
  191716. png_bytep dp = sp;
  191717. png_byte save;
  191718. png_uint_32 i;
  191719. for (i = 0; i < row_width; i++)
  191720. {
  191721. save = *(--sp);
  191722. *(--dp) = *(--sp);
  191723. *(--dp) = save;
  191724. }
  191725. }
  191726. /* This converts from GGAA to AAGG */
  191727. else
  191728. {
  191729. png_bytep sp = row + row_info->rowbytes;
  191730. png_bytep dp = sp;
  191731. png_byte save[2];
  191732. png_uint_32 i;
  191733. for (i = 0; i < row_width; i++)
  191734. {
  191735. save[0] = *(--sp);
  191736. save[1] = *(--sp);
  191737. *(--dp) = *(--sp);
  191738. *(--dp) = *(--sp);
  191739. *(--dp) = save[0];
  191740. *(--dp) = save[1];
  191741. }
  191742. }
  191743. }
  191744. }
  191745. }
  191746. #endif
  191747. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  191748. void /* PRIVATE */
  191749. png_do_read_invert_alpha(png_row_infop row_info, png_bytep row)
  191750. {
  191751. png_debug(1, "in png_do_read_invert_alpha\n");
  191752. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191753. if (row != NULL && row_info != NULL)
  191754. #endif
  191755. {
  191756. png_uint_32 row_width = row_info->width;
  191757. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191758. {
  191759. /* This inverts the alpha channel in RGBA */
  191760. if (row_info->bit_depth == 8)
  191761. {
  191762. png_bytep sp = row + row_info->rowbytes;
  191763. png_bytep dp = sp;
  191764. png_uint_32 i;
  191765. for (i = 0; i < row_width; i++)
  191766. {
  191767. *(--dp) = (png_byte)(255 - *(--sp));
  191768. /* This does nothing:
  191769. *(--dp) = *(--sp);
  191770. *(--dp) = *(--sp);
  191771. *(--dp) = *(--sp);
  191772. We can replace it with:
  191773. */
  191774. sp-=3;
  191775. dp=sp;
  191776. }
  191777. }
  191778. /* This inverts the alpha channel in RRGGBBAA */
  191779. else
  191780. {
  191781. png_bytep sp = row + row_info->rowbytes;
  191782. png_bytep dp = sp;
  191783. png_uint_32 i;
  191784. for (i = 0; i < row_width; i++)
  191785. {
  191786. *(--dp) = (png_byte)(255 - *(--sp));
  191787. *(--dp) = (png_byte)(255 - *(--sp));
  191788. /* This does nothing:
  191789. *(--dp) = *(--sp);
  191790. *(--dp) = *(--sp);
  191791. *(--dp) = *(--sp);
  191792. *(--dp) = *(--sp);
  191793. *(--dp) = *(--sp);
  191794. *(--dp) = *(--sp);
  191795. We can replace it with:
  191796. */
  191797. sp-=6;
  191798. dp=sp;
  191799. }
  191800. }
  191801. }
  191802. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191803. {
  191804. /* This inverts the alpha channel in GA */
  191805. if (row_info->bit_depth == 8)
  191806. {
  191807. png_bytep sp = row + row_info->rowbytes;
  191808. png_bytep dp = sp;
  191809. png_uint_32 i;
  191810. for (i = 0; i < row_width; i++)
  191811. {
  191812. *(--dp) = (png_byte)(255 - *(--sp));
  191813. *(--dp) = *(--sp);
  191814. }
  191815. }
  191816. /* This inverts the alpha channel in GGAA */
  191817. else
  191818. {
  191819. png_bytep sp = row + row_info->rowbytes;
  191820. png_bytep dp = sp;
  191821. png_uint_32 i;
  191822. for (i = 0; i < row_width; i++)
  191823. {
  191824. *(--dp) = (png_byte)(255 - *(--sp));
  191825. *(--dp) = (png_byte)(255 - *(--sp));
  191826. /*
  191827. *(--dp) = *(--sp);
  191828. *(--dp) = *(--sp);
  191829. */
  191830. sp-=2;
  191831. dp=sp;
  191832. }
  191833. }
  191834. }
  191835. }
  191836. }
  191837. #endif
  191838. #if defined(PNG_READ_FILLER_SUPPORTED)
  191839. /* Add filler channel if we have RGB color */
  191840. void /* PRIVATE */
  191841. png_do_read_filler(png_row_infop row_info, png_bytep row,
  191842. png_uint_32 filler, png_uint_32 flags)
  191843. {
  191844. png_uint_32 i;
  191845. png_uint_32 row_width = row_info->width;
  191846. png_byte hi_filler = (png_byte)((filler>>8) & 0xff);
  191847. png_byte lo_filler = (png_byte)(filler & 0xff);
  191848. png_debug(1, "in png_do_read_filler\n");
  191849. if (
  191850. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191851. row != NULL && row_info != NULL &&
  191852. #endif
  191853. row_info->color_type == PNG_COLOR_TYPE_GRAY)
  191854. {
  191855. if(row_info->bit_depth == 8)
  191856. {
  191857. /* This changes the data from G to GX */
  191858. if (flags & PNG_FLAG_FILLER_AFTER)
  191859. {
  191860. png_bytep sp = row + (png_size_t)row_width;
  191861. png_bytep dp = sp + (png_size_t)row_width;
  191862. for (i = 1; i < row_width; i++)
  191863. {
  191864. *(--dp) = lo_filler;
  191865. *(--dp) = *(--sp);
  191866. }
  191867. *(--dp) = lo_filler;
  191868. row_info->channels = 2;
  191869. row_info->pixel_depth = 16;
  191870. row_info->rowbytes = row_width * 2;
  191871. }
  191872. /* This changes the data from G to XG */
  191873. else
  191874. {
  191875. png_bytep sp = row + (png_size_t)row_width;
  191876. png_bytep dp = sp + (png_size_t)row_width;
  191877. for (i = 0; i < row_width; i++)
  191878. {
  191879. *(--dp) = *(--sp);
  191880. *(--dp) = lo_filler;
  191881. }
  191882. row_info->channels = 2;
  191883. row_info->pixel_depth = 16;
  191884. row_info->rowbytes = row_width * 2;
  191885. }
  191886. }
  191887. else if(row_info->bit_depth == 16)
  191888. {
  191889. /* This changes the data from GG to GGXX */
  191890. if (flags & PNG_FLAG_FILLER_AFTER)
  191891. {
  191892. png_bytep sp = row + (png_size_t)row_width * 2;
  191893. png_bytep dp = sp + (png_size_t)row_width * 2;
  191894. for (i = 1; i < row_width; i++)
  191895. {
  191896. *(--dp) = hi_filler;
  191897. *(--dp) = lo_filler;
  191898. *(--dp) = *(--sp);
  191899. *(--dp) = *(--sp);
  191900. }
  191901. *(--dp) = hi_filler;
  191902. *(--dp) = lo_filler;
  191903. row_info->channels = 2;
  191904. row_info->pixel_depth = 32;
  191905. row_info->rowbytes = row_width * 4;
  191906. }
  191907. /* This changes the data from GG to XXGG */
  191908. else
  191909. {
  191910. png_bytep sp = row + (png_size_t)row_width * 2;
  191911. png_bytep dp = sp + (png_size_t)row_width * 2;
  191912. for (i = 0; i < row_width; i++)
  191913. {
  191914. *(--dp) = *(--sp);
  191915. *(--dp) = *(--sp);
  191916. *(--dp) = hi_filler;
  191917. *(--dp) = lo_filler;
  191918. }
  191919. row_info->channels = 2;
  191920. row_info->pixel_depth = 32;
  191921. row_info->rowbytes = row_width * 4;
  191922. }
  191923. }
  191924. } /* COLOR_TYPE == GRAY */
  191925. else if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  191926. {
  191927. if(row_info->bit_depth == 8)
  191928. {
  191929. /* This changes the data from RGB to RGBX */
  191930. if (flags & PNG_FLAG_FILLER_AFTER)
  191931. {
  191932. png_bytep sp = row + (png_size_t)row_width * 3;
  191933. png_bytep dp = sp + (png_size_t)row_width;
  191934. for (i = 1; i < row_width; i++)
  191935. {
  191936. *(--dp) = lo_filler;
  191937. *(--dp) = *(--sp);
  191938. *(--dp) = *(--sp);
  191939. *(--dp) = *(--sp);
  191940. }
  191941. *(--dp) = lo_filler;
  191942. row_info->channels = 4;
  191943. row_info->pixel_depth = 32;
  191944. row_info->rowbytes = row_width * 4;
  191945. }
  191946. /* This changes the data from RGB to XRGB */
  191947. else
  191948. {
  191949. png_bytep sp = row + (png_size_t)row_width * 3;
  191950. png_bytep dp = sp + (png_size_t)row_width;
  191951. for (i = 0; i < row_width; i++)
  191952. {
  191953. *(--dp) = *(--sp);
  191954. *(--dp) = *(--sp);
  191955. *(--dp) = *(--sp);
  191956. *(--dp) = lo_filler;
  191957. }
  191958. row_info->channels = 4;
  191959. row_info->pixel_depth = 32;
  191960. row_info->rowbytes = row_width * 4;
  191961. }
  191962. }
  191963. else if(row_info->bit_depth == 16)
  191964. {
  191965. /* This changes the data from RRGGBB to RRGGBBXX */
  191966. if (flags & PNG_FLAG_FILLER_AFTER)
  191967. {
  191968. png_bytep sp = row + (png_size_t)row_width * 6;
  191969. png_bytep dp = sp + (png_size_t)row_width * 2;
  191970. for (i = 1; i < row_width; i++)
  191971. {
  191972. *(--dp) = hi_filler;
  191973. *(--dp) = lo_filler;
  191974. *(--dp) = *(--sp);
  191975. *(--dp) = *(--sp);
  191976. *(--dp) = *(--sp);
  191977. *(--dp) = *(--sp);
  191978. *(--dp) = *(--sp);
  191979. *(--dp) = *(--sp);
  191980. }
  191981. *(--dp) = hi_filler;
  191982. *(--dp) = lo_filler;
  191983. row_info->channels = 4;
  191984. row_info->pixel_depth = 64;
  191985. row_info->rowbytes = row_width * 8;
  191986. }
  191987. /* This changes the data from RRGGBB to XXRRGGBB */
  191988. else
  191989. {
  191990. png_bytep sp = row + (png_size_t)row_width * 6;
  191991. png_bytep dp = sp + (png_size_t)row_width * 2;
  191992. for (i = 0; i < row_width; i++)
  191993. {
  191994. *(--dp) = *(--sp);
  191995. *(--dp) = *(--sp);
  191996. *(--dp) = *(--sp);
  191997. *(--dp) = *(--sp);
  191998. *(--dp) = *(--sp);
  191999. *(--dp) = *(--sp);
  192000. *(--dp) = hi_filler;
  192001. *(--dp) = lo_filler;
  192002. }
  192003. row_info->channels = 4;
  192004. row_info->pixel_depth = 64;
  192005. row_info->rowbytes = row_width * 8;
  192006. }
  192007. }
  192008. } /* COLOR_TYPE == RGB */
  192009. }
  192010. #endif
  192011. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  192012. /* expand grayscale files to RGB, with or without alpha */
  192013. void /* PRIVATE */
  192014. png_do_gray_to_rgb(png_row_infop row_info, png_bytep row)
  192015. {
  192016. png_uint_32 i;
  192017. png_uint_32 row_width = row_info->width;
  192018. png_debug(1, "in png_do_gray_to_rgb\n");
  192019. if (row_info->bit_depth >= 8 &&
  192020. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192021. row != NULL && row_info != NULL &&
  192022. #endif
  192023. !(row_info->color_type & PNG_COLOR_MASK_COLOR))
  192024. {
  192025. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  192026. {
  192027. if (row_info->bit_depth == 8)
  192028. {
  192029. png_bytep sp = row + (png_size_t)row_width - 1;
  192030. png_bytep dp = sp + (png_size_t)row_width * 2;
  192031. for (i = 0; i < row_width; i++)
  192032. {
  192033. *(dp--) = *sp;
  192034. *(dp--) = *sp;
  192035. *(dp--) = *(sp--);
  192036. }
  192037. }
  192038. else
  192039. {
  192040. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  192041. png_bytep dp = sp + (png_size_t)row_width * 4;
  192042. for (i = 0; i < row_width; i++)
  192043. {
  192044. *(dp--) = *sp;
  192045. *(dp--) = *(sp - 1);
  192046. *(dp--) = *sp;
  192047. *(dp--) = *(sp - 1);
  192048. *(dp--) = *(sp--);
  192049. *(dp--) = *(sp--);
  192050. }
  192051. }
  192052. }
  192053. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  192054. {
  192055. if (row_info->bit_depth == 8)
  192056. {
  192057. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  192058. png_bytep dp = sp + (png_size_t)row_width * 2;
  192059. for (i = 0; i < row_width; i++)
  192060. {
  192061. *(dp--) = *(sp--);
  192062. *(dp--) = *sp;
  192063. *(dp--) = *sp;
  192064. *(dp--) = *(sp--);
  192065. }
  192066. }
  192067. else
  192068. {
  192069. png_bytep sp = row + (png_size_t)row_width * 4 - 1;
  192070. png_bytep dp = sp + (png_size_t)row_width * 4;
  192071. for (i = 0; i < row_width; i++)
  192072. {
  192073. *(dp--) = *(sp--);
  192074. *(dp--) = *(sp--);
  192075. *(dp--) = *sp;
  192076. *(dp--) = *(sp - 1);
  192077. *(dp--) = *sp;
  192078. *(dp--) = *(sp - 1);
  192079. *(dp--) = *(sp--);
  192080. *(dp--) = *(sp--);
  192081. }
  192082. }
  192083. }
  192084. row_info->channels += (png_byte)2;
  192085. row_info->color_type |= PNG_COLOR_MASK_COLOR;
  192086. row_info->pixel_depth = (png_byte)(row_info->channels *
  192087. row_info->bit_depth);
  192088. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  192089. }
  192090. }
  192091. #endif
  192092. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  192093. /* reduce RGB files to grayscale, with or without alpha
  192094. * using the equation given in Poynton's ColorFAQ at
  192095. * <http://www.inforamp.net/~poynton/>
  192096. * Copyright (c) 1998-01-04 Charles Poynton poynton at inforamp.net
  192097. *
  192098. * Y = 0.212671 * R + 0.715160 * G + 0.072169 * B
  192099. *
  192100. * We approximate this with
  192101. *
  192102. * Y = 0.21268 * R + 0.7151 * G + 0.07217 * B
  192103. *
  192104. * which can be expressed with integers as
  192105. *
  192106. * Y = (6969 * R + 23434 * G + 2365 * B)/32768
  192107. *
  192108. * The calculation is to be done in a linear colorspace.
  192109. *
  192110. * Other integer coefficents can be used via png_set_rgb_to_gray().
  192111. */
  192112. int /* PRIVATE */
  192113. png_do_rgb_to_gray(png_structp png_ptr, png_row_infop row_info, png_bytep row)
  192114. {
  192115. png_uint_32 i;
  192116. png_uint_32 row_width = row_info->width;
  192117. int rgb_error = 0;
  192118. png_debug(1, "in png_do_rgb_to_gray\n");
  192119. if (
  192120. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192121. row != NULL && row_info != NULL &&
  192122. #endif
  192123. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  192124. {
  192125. png_uint_32 rc = png_ptr->rgb_to_gray_red_coeff;
  192126. png_uint_32 gc = png_ptr->rgb_to_gray_green_coeff;
  192127. png_uint_32 bc = png_ptr->rgb_to_gray_blue_coeff;
  192128. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  192129. {
  192130. if (row_info->bit_depth == 8)
  192131. {
  192132. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  192133. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  192134. {
  192135. png_bytep sp = row;
  192136. png_bytep dp = row;
  192137. for (i = 0; i < row_width; i++)
  192138. {
  192139. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  192140. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  192141. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  192142. if(red != green || red != blue)
  192143. {
  192144. rgb_error |= 1;
  192145. *(dp++) = png_ptr->gamma_from_1[
  192146. (rc*red+gc*green+bc*blue)>>15];
  192147. }
  192148. else
  192149. *(dp++) = *(sp-1);
  192150. }
  192151. }
  192152. else
  192153. #endif
  192154. {
  192155. png_bytep sp = row;
  192156. png_bytep dp = row;
  192157. for (i = 0; i < row_width; i++)
  192158. {
  192159. png_byte red = *(sp++);
  192160. png_byte green = *(sp++);
  192161. png_byte blue = *(sp++);
  192162. if(red != green || red != blue)
  192163. {
  192164. rgb_error |= 1;
  192165. *(dp++) = (png_byte)((rc*red+gc*green+bc*blue)>>15);
  192166. }
  192167. else
  192168. *(dp++) = *(sp-1);
  192169. }
  192170. }
  192171. }
  192172. else /* RGB bit_depth == 16 */
  192173. {
  192174. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  192175. if (png_ptr->gamma_16_to_1 != NULL &&
  192176. png_ptr->gamma_16_from_1 != NULL)
  192177. {
  192178. png_bytep sp = row;
  192179. png_bytep dp = row;
  192180. for (i = 0; i < row_width; i++)
  192181. {
  192182. png_uint_16 red, green, blue, w;
  192183. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192184. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192185. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192186. if(red == green && red == blue)
  192187. w = red;
  192188. else
  192189. {
  192190. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  192191. png_ptr->gamma_shift][red>>8];
  192192. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  192193. png_ptr->gamma_shift][green>>8];
  192194. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  192195. png_ptr->gamma_shift][blue>>8];
  192196. png_uint_16 gray16 = (png_uint_16)((rc*red_1 + gc*green_1
  192197. + bc*blue_1)>>15);
  192198. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  192199. png_ptr->gamma_shift][gray16 >> 8];
  192200. rgb_error |= 1;
  192201. }
  192202. *(dp++) = (png_byte)((w>>8) & 0xff);
  192203. *(dp++) = (png_byte)(w & 0xff);
  192204. }
  192205. }
  192206. else
  192207. #endif
  192208. {
  192209. png_bytep sp = row;
  192210. png_bytep dp = row;
  192211. for (i = 0; i < row_width; i++)
  192212. {
  192213. png_uint_16 red, green, blue, gray16;
  192214. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192215. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192216. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192217. if(red != green || red != blue)
  192218. rgb_error |= 1;
  192219. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  192220. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  192221. *(dp++) = (png_byte)(gray16 & 0xff);
  192222. }
  192223. }
  192224. }
  192225. }
  192226. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  192227. {
  192228. if (row_info->bit_depth == 8)
  192229. {
  192230. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  192231. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  192232. {
  192233. png_bytep sp = row;
  192234. png_bytep dp = row;
  192235. for (i = 0; i < row_width; i++)
  192236. {
  192237. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  192238. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  192239. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  192240. if(red != green || red != blue)
  192241. rgb_error |= 1;
  192242. *(dp++) = png_ptr->gamma_from_1
  192243. [(rc*red + gc*green + bc*blue)>>15];
  192244. *(dp++) = *(sp++); /* alpha */
  192245. }
  192246. }
  192247. else
  192248. #endif
  192249. {
  192250. png_bytep sp = row;
  192251. png_bytep dp = row;
  192252. for (i = 0; i < row_width; i++)
  192253. {
  192254. png_byte red = *(sp++);
  192255. png_byte green = *(sp++);
  192256. png_byte blue = *(sp++);
  192257. if(red != green || red != blue)
  192258. rgb_error |= 1;
  192259. *(dp++) = (png_byte)((rc*red + gc*green + bc*blue)>>15);
  192260. *(dp++) = *(sp++); /* alpha */
  192261. }
  192262. }
  192263. }
  192264. else /* RGBA bit_depth == 16 */
  192265. {
  192266. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  192267. if (png_ptr->gamma_16_to_1 != NULL &&
  192268. png_ptr->gamma_16_from_1 != NULL)
  192269. {
  192270. png_bytep sp = row;
  192271. png_bytep dp = row;
  192272. for (i = 0; i < row_width; i++)
  192273. {
  192274. png_uint_16 red, green, blue, w;
  192275. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192276. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192277. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192278. if(red == green && red == blue)
  192279. w = red;
  192280. else
  192281. {
  192282. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  192283. png_ptr->gamma_shift][red>>8];
  192284. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  192285. png_ptr->gamma_shift][green>>8];
  192286. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  192287. png_ptr->gamma_shift][blue>>8];
  192288. png_uint_16 gray16 = (png_uint_16)((rc * red_1
  192289. + gc * green_1 + bc * blue_1)>>15);
  192290. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  192291. png_ptr->gamma_shift][gray16 >> 8];
  192292. rgb_error |= 1;
  192293. }
  192294. *(dp++) = (png_byte)((w>>8) & 0xff);
  192295. *(dp++) = (png_byte)(w & 0xff);
  192296. *(dp++) = *(sp++); /* alpha */
  192297. *(dp++) = *(sp++);
  192298. }
  192299. }
  192300. else
  192301. #endif
  192302. {
  192303. png_bytep sp = row;
  192304. png_bytep dp = row;
  192305. for (i = 0; i < row_width; i++)
  192306. {
  192307. png_uint_16 red, green, blue, gray16;
  192308. red = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  192309. green = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  192310. blue = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  192311. if(red != green || red != blue)
  192312. rgb_error |= 1;
  192313. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  192314. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  192315. *(dp++) = (png_byte)(gray16 & 0xff);
  192316. *(dp++) = *(sp++); /* alpha */
  192317. *(dp++) = *(sp++);
  192318. }
  192319. }
  192320. }
  192321. }
  192322. row_info->channels -= (png_byte)2;
  192323. row_info->color_type &= ~PNG_COLOR_MASK_COLOR;
  192324. row_info->pixel_depth = (png_byte)(row_info->channels *
  192325. row_info->bit_depth);
  192326. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  192327. }
  192328. return rgb_error;
  192329. }
  192330. #endif
  192331. /* Build a grayscale palette. Palette is assumed to be 1 << bit_depth
  192332. * large of png_color. This lets grayscale images be treated as
  192333. * paletted. Most useful for gamma correction and simplification
  192334. * of code.
  192335. */
  192336. void PNGAPI
  192337. png_build_grayscale_palette(int bit_depth, png_colorp palette)
  192338. {
  192339. int num_palette;
  192340. int color_inc;
  192341. int i;
  192342. int v;
  192343. png_debug(1, "in png_do_build_grayscale_palette\n");
  192344. if (palette == NULL)
  192345. return;
  192346. switch (bit_depth)
  192347. {
  192348. case 1:
  192349. num_palette = 2;
  192350. color_inc = 0xff;
  192351. break;
  192352. case 2:
  192353. num_palette = 4;
  192354. color_inc = 0x55;
  192355. break;
  192356. case 4:
  192357. num_palette = 16;
  192358. color_inc = 0x11;
  192359. break;
  192360. case 8:
  192361. num_palette = 256;
  192362. color_inc = 1;
  192363. break;
  192364. default:
  192365. num_palette = 0;
  192366. color_inc = 0;
  192367. break;
  192368. }
  192369. for (i = 0, v = 0; i < num_palette; i++, v += color_inc)
  192370. {
  192371. palette[i].red = (png_byte)v;
  192372. palette[i].green = (png_byte)v;
  192373. palette[i].blue = (png_byte)v;
  192374. }
  192375. }
  192376. /* This function is currently unused. Do we really need it? */
  192377. #if defined(PNG_READ_DITHER_SUPPORTED) && defined(PNG_CORRECT_PALETTE_SUPPORTED)
  192378. void /* PRIVATE */
  192379. png_correct_palette(png_structp png_ptr, png_colorp palette,
  192380. int num_palette)
  192381. {
  192382. png_debug(1, "in png_correct_palette\n");
  192383. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  192384. defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  192385. if (png_ptr->transformations & (PNG_GAMMA | PNG_BACKGROUND))
  192386. {
  192387. png_color back, back_1;
  192388. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  192389. {
  192390. back.red = png_ptr->gamma_table[png_ptr->background.red];
  192391. back.green = png_ptr->gamma_table[png_ptr->background.green];
  192392. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  192393. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  192394. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  192395. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  192396. }
  192397. else
  192398. {
  192399. double g;
  192400. g = 1.0 / (png_ptr->background_gamma * png_ptr->screen_gamma);
  192401. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_SCREEN ||
  192402. fabs(g - 1.0) < PNG_GAMMA_THRESHOLD)
  192403. {
  192404. back.red = png_ptr->background.red;
  192405. back.green = png_ptr->background.green;
  192406. back.blue = png_ptr->background.blue;
  192407. }
  192408. else
  192409. {
  192410. back.red =
  192411. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  192412. 255.0 + 0.5);
  192413. back.green =
  192414. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  192415. 255.0 + 0.5);
  192416. back.blue =
  192417. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  192418. 255.0 + 0.5);
  192419. }
  192420. g = 1.0 / png_ptr->background_gamma;
  192421. back_1.red =
  192422. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  192423. 255.0 + 0.5);
  192424. back_1.green =
  192425. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  192426. 255.0 + 0.5);
  192427. back_1.blue =
  192428. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  192429. 255.0 + 0.5);
  192430. }
  192431. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192432. {
  192433. png_uint_32 i;
  192434. for (i = 0; i < (png_uint_32)num_palette; i++)
  192435. {
  192436. if (i < png_ptr->num_trans && png_ptr->trans[i] == 0)
  192437. {
  192438. palette[i] = back;
  192439. }
  192440. else if (i < png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  192441. {
  192442. png_byte v, w;
  192443. v = png_ptr->gamma_to_1[png_ptr->palette[i].red];
  192444. png_composite(w, v, png_ptr->trans[i], back_1.red);
  192445. palette[i].red = png_ptr->gamma_from_1[w];
  192446. v = png_ptr->gamma_to_1[png_ptr->palette[i].green];
  192447. png_composite(w, v, png_ptr->trans[i], back_1.green);
  192448. palette[i].green = png_ptr->gamma_from_1[w];
  192449. v = png_ptr->gamma_to_1[png_ptr->palette[i].blue];
  192450. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  192451. palette[i].blue = png_ptr->gamma_from_1[w];
  192452. }
  192453. else
  192454. {
  192455. palette[i].red = png_ptr->gamma_table[palette[i].red];
  192456. palette[i].green = png_ptr->gamma_table[palette[i].green];
  192457. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  192458. }
  192459. }
  192460. }
  192461. else
  192462. {
  192463. int i;
  192464. for (i = 0; i < num_palette; i++)
  192465. {
  192466. if (palette[i].red == (png_byte)png_ptr->trans_values.gray)
  192467. {
  192468. palette[i] = back;
  192469. }
  192470. else
  192471. {
  192472. palette[i].red = png_ptr->gamma_table[palette[i].red];
  192473. palette[i].green = png_ptr->gamma_table[palette[i].green];
  192474. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  192475. }
  192476. }
  192477. }
  192478. }
  192479. else
  192480. #endif
  192481. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192482. if (png_ptr->transformations & PNG_GAMMA)
  192483. {
  192484. int i;
  192485. for (i = 0; i < num_palette; i++)
  192486. {
  192487. palette[i].red = png_ptr->gamma_table[palette[i].red];
  192488. palette[i].green = png_ptr->gamma_table[palette[i].green];
  192489. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  192490. }
  192491. }
  192492. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192493. else
  192494. #endif
  192495. #endif
  192496. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192497. if (png_ptr->transformations & PNG_BACKGROUND)
  192498. {
  192499. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192500. {
  192501. png_color back;
  192502. back.red = (png_byte)png_ptr->background.red;
  192503. back.green = (png_byte)png_ptr->background.green;
  192504. back.blue = (png_byte)png_ptr->background.blue;
  192505. for (i = 0; i < (int)png_ptr->num_trans; i++)
  192506. {
  192507. if (png_ptr->trans[i] == 0)
  192508. {
  192509. palette[i].red = back.red;
  192510. palette[i].green = back.green;
  192511. palette[i].blue = back.blue;
  192512. }
  192513. else if (png_ptr->trans[i] != 0xff)
  192514. {
  192515. png_composite(palette[i].red, png_ptr->palette[i].red,
  192516. png_ptr->trans[i], back.red);
  192517. png_composite(palette[i].green, png_ptr->palette[i].green,
  192518. png_ptr->trans[i], back.green);
  192519. png_composite(palette[i].blue, png_ptr->palette[i].blue,
  192520. png_ptr->trans[i], back.blue);
  192521. }
  192522. }
  192523. }
  192524. else /* assume grayscale palette (what else could it be?) */
  192525. {
  192526. int i;
  192527. for (i = 0; i < num_palette; i++)
  192528. {
  192529. if (i == (png_byte)png_ptr->trans_values.gray)
  192530. {
  192531. palette[i].red = (png_byte)png_ptr->background.red;
  192532. palette[i].green = (png_byte)png_ptr->background.green;
  192533. palette[i].blue = (png_byte)png_ptr->background.blue;
  192534. }
  192535. }
  192536. }
  192537. }
  192538. #endif
  192539. }
  192540. #endif
  192541. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192542. /* Replace any alpha or transparency with the supplied background color.
  192543. * "background" is already in the screen gamma, while "background_1" is
  192544. * at a gamma of 1.0. Paletted files have already been taken care of.
  192545. */
  192546. void /* PRIVATE */
  192547. png_do_background(png_row_infop row_info, png_bytep row,
  192548. png_color_16p trans_values, png_color_16p background
  192549. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192550. , png_color_16p background_1,
  192551. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  192552. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  192553. png_uint_16pp gamma_16_to_1, int gamma_shift
  192554. #endif
  192555. )
  192556. {
  192557. png_bytep sp, dp;
  192558. png_uint_32 i;
  192559. png_uint_32 row_width=row_info->width;
  192560. int shift;
  192561. png_debug(1, "in png_do_background\n");
  192562. if (background != NULL &&
  192563. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192564. row != NULL && row_info != NULL &&
  192565. #endif
  192566. (!(row_info->color_type & PNG_COLOR_MASK_ALPHA) ||
  192567. (row_info->color_type != PNG_COLOR_TYPE_PALETTE && trans_values)))
  192568. {
  192569. switch (row_info->color_type)
  192570. {
  192571. case PNG_COLOR_TYPE_GRAY:
  192572. {
  192573. switch (row_info->bit_depth)
  192574. {
  192575. case 1:
  192576. {
  192577. sp = row;
  192578. shift = 7;
  192579. for (i = 0; i < row_width; i++)
  192580. {
  192581. if ((png_uint_16)((*sp >> shift) & 0x01)
  192582. == trans_values->gray)
  192583. {
  192584. *sp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  192585. *sp |= (png_byte)(background->gray << shift);
  192586. }
  192587. if (!shift)
  192588. {
  192589. shift = 7;
  192590. sp++;
  192591. }
  192592. else
  192593. shift--;
  192594. }
  192595. break;
  192596. }
  192597. case 2:
  192598. {
  192599. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192600. if (gamma_table != NULL)
  192601. {
  192602. sp = row;
  192603. shift = 6;
  192604. for (i = 0; i < row_width; i++)
  192605. {
  192606. if ((png_uint_16)((*sp >> shift) & 0x03)
  192607. == trans_values->gray)
  192608. {
  192609. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192610. *sp |= (png_byte)(background->gray << shift);
  192611. }
  192612. else
  192613. {
  192614. png_byte p = (png_byte)((*sp >> shift) & 0x03);
  192615. png_byte g = (png_byte)((gamma_table [p | (p << 2) |
  192616. (p << 4) | (p << 6)] >> 6) & 0x03);
  192617. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192618. *sp |= (png_byte)(g << shift);
  192619. }
  192620. if (!shift)
  192621. {
  192622. shift = 6;
  192623. sp++;
  192624. }
  192625. else
  192626. shift -= 2;
  192627. }
  192628. }
  192629. else
  192630. #endif
  192631. {
  192632. sp = row;
  192633. shift = 6;
  192634. for (i = 0; i < row_width; i++)
  192635. {
  192636. if ((png_uint_16)((*sp >> shift) & 0x03)
  192637. == trans_values->gray)
  192638. {
  192639. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192640. *sp |= (png_byte)(background->gray << shift);
  192641. }
  192642. if (!shift)
  192643. {
  192644. shift = 6;
  192645. sp++;
  192646. }
  192647. else
  192648. shift -= 2;
  192649. }
  192650. }
  192651. break;
  192652. }
  192653. case 4:
  192654. {
  192655. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192656. if (gamma_table != NULL)
  192657. {
  192658. sp = row;
  192659. shift = 4;
  192660. for (i = 0; i < row_width; i++)
  192661. {
  192662. if ((png_uint_16)((*sp >> shift) & 0x0f)
  192663. == trans_values->gray)
  192664. {
  192665. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192666. *sp |= (png_byte)(background->gray << shift);
  192667. }
  192668. else
  192669. {
  192670. png_byte p = (png_byte)((*sp >> shift) & 0x0f);
  192671. png_byte g = (png_byte)((gamma_table[p |
  192672. (p << 4)] >> 4) & 0x0f);
  192673. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192674. *sp |= (png_byte)(g << shift);
  192675. }
  192676. if (!shift)
  192677. {
  192678. shift = 4;
  192679. sp++;
  192680. }
  192681. else
  192682. shift -= 4;
  192683. }
  192684. }
  192685. else
  192686. #endif
  192687. {
  192688. sp = row;
  192689. shift = 4;
  192690. for (i = 0; i < row_width; i++)
  192691. {
  192692. if ((png_uint_16)((*sp >> shift) & 0x0f)
  192693. == trans_values->gray)
  192694. {
  192695. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192696. *sp |= (png_byte)(background->gray << shift);
  192697. }
  192698. if (!shift)
  192699. {
  192700. shift = 4;
  192701. sp++;
  192702. }
  192703. else
  192704. shift -= 4;
  192705. }
  192706. }
  192707. break;
  192708. }
  192709. case 8:
  192710. {
  192711. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192712. if (gamma_table != NULL)
  192713. {
  192714. sp = row;
  192715. for (i = 0; i < row_width; i++, sp++)
  192716. {
  192717. if (*sp == trans_values->gray)
  192718. {
  192719. *sp = (png_byte)background->gray;
  192720. }
  192721. else
  192722. {
  192723. *sp = gamma_table[*sp];
  192724. }
  192725. }
  192726. }
  192727. else
  192728. #endif
  192729. {
  192730. sp = row;
  192731. for (i = 0; i < row_width; i++, sp++)
  192732. {
  192733. if (*sp == trans_values->gray)
  192734. {
  192735. *sp = (png_byte)background->gray;
  192736. }
  192737. }
  192738. }
  192739. break;
  192740. }
  192741. case 16:
  192742. {
  192743. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192744. if (gamma_16 != NULL)
  192745. {
  192746. sp = row;
  192747. for (i = 0; i < row_width; i++, sp += 2)
  192748. {
  192749. png_uint_16 v;
  192750. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192751. if (v == trans_values->gray)
  192752. {
  192753. /* background is already in screen gamma */
  192754. *sp = (png_byte)((background->gray >> 8) & 0xff);
  192755. *(sp + 1) = (png_byte)(background->gray & 0xff);
  192756. }
  192757. else
  192758. {
  192759. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192760. *sp = (png_byte)((v >> 8) & 0xff);
  192761. *(sp + 1) = (png_byte)(v & 0xff);
  192762. }
  192763. }
  192764. }
  192765. else
  192766. #endif
  192767. {
  192768. sp = row;
  192769. for (i = 0; i < row_width; i++, sp += 2)
  192770. {
  192771. png_uint_16 v;
  192772. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192773. if (v == trans_values->gray)
  192774. {
  192775. *sp = (png_byte)((background->gray >> 8) & 0xff);
  192776. *(sp + 1) = (png_byte)(background->gray & 0xff);
  192777. }
  192778. }
  192779. }
  192780. break;
  192781. }
  192782. }
  192783. break;
  192784. }
  192785. case PNG_COLOR_TYPE_RGB:
  192786. {
  192787. if (row_info->bit_depth == 8)
  192788. {
  192789. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192790. if (gamma_table != NULL)
  192791. {
  192792. sp = row;
  192793. for (i = 0; i < row_width; i++, sp += 3)
  192794. {
  192795. if (*sp == trans_values->red &&
  192796. *(sp + 1) == trans_values->green &&
  192797. *(sp + 2) == trans_values->blue)
  192798. {
  192799. *sp = (png_byte)background->red;
  192800. *(sp + 1) = (png_byte)background->green;
  192801. *(sp + 2) = (png_byte)background->blue;
  192802. }
  192803. else
  192804. {
  192805. *sp = gamma_table[*sp];
  192806. *(sp + 1) = gamma_table[*(sp + 1)];
  192807. *(sp + 2) = gamma_table[*(sp + 2)];
  192808. }
  192809. }
  192810. }
  192811. else
  192812. #endif
  192813. {
  192814. sp = row;
  192815. for (i = 0; i < row_width; i++, sp += 3)
  192816. {
  192817. if (*sp == trans_values->red &&
  192818. *(sp + 1) == trans_values->green &&
  192819. *(sp + 2) == trans_values->blue)
  192820. {
  192821. *sp = (png_byte)background->red;
  192822. *(sp + 1) = (png_byte)background->green;
  192823. *(sp + 2) = (png_byte)background->blue;
  192824. }
  192825. }
  192826. }
  192827. }
  192828. else /* if (row_info->bit_depth == 16) */
  192829. {
  192830. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192831. if (gamma_16 != NULL)
  192832. {
  192833. sp = row;
  192834. for (i = 0; i < row_width; i++, sp += 6)
  192835. {
  192836. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192837. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192838. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  192839. if (r == trans_values->red && g == trans_values->green &&
  192840. b == trans_values->blue)
  192841. {
  192842. /* background is already in screen gamma */
  192843. *sp = (png_byte)((background->red >> 8) & 0xff);
  192844. *(sp + 1) = (png_byte)(background->red & 0xff);
  192845. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192846. *(sp + 3) = (png_byte)(background->green & 0xff);
  192847. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192848. *(sp + 5) = (png_byte)(background->blue & 0xff);
  192849. }
  192850. else
  192851. {
  192852. png_uint_16 v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192853. *sp = (png_byte)((v >> 8) & 0xff);
  192854. *(sp + 1) = (png_byte)(v & 0xff);
  192855. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  192856. *(sp + 2) = (png_byte)((v >> 8) & 0xff);
  192857. *(sp + 3) = (png_byte)(v & 0xff);
  192858. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  192859. *(sp + 4) = (png_byte)((v >> 8) & 0xff);
  192860. *(sp + 5) = (png_byte)(v & 0xff);
  192861. }
  192862. }
  192863. }
  192864. else
  192865. #endif
  192866. {
  192867. sp = row;
  192868. for (i = 0; i < row_width; i++, sp += 6)
  192869. {
  192870. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp+1));
  192871. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192872. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  192873. if (r == trans_values->red && g == trans_values->green &&
  192874. b == trans_values->blue)
  192875. {
  192876. *sp = (png_byte)((background->red >> 8) & 0xff);
  192877. *(sp + 1) = (png_byte)(background->red & 0xff);
  192878. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192879. *(sp + 3) = (png_byte)(background->green & 0xff);
  192880. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192881. *(sp + 5) = (png_byte)(background->blue & 0xff);
  192882. }
  192883. }
  192884. }
  192885. }
  192886. break;
  192887. }
  192888. case PNG_COLOR_TYPE_GRAY_ALPHA:
  192889. {
  192890. if (row_info->bit_depth == 8)
  192891. {
  192892. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192893. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  192894. gamma_table != NULL)
  192895. {
  192896. sp = row;
  192897. dp = row;
  192898. for (i = 0; i < row_width; i++, sp += 2, dp++)
  192899. {
  192900. png_uint_16 a = *(sp + 1);
  192901. if (a == 0xff)
  192902. {
  192903. *dp = gamma_table[*sp];
  192904. }
  192905. else if (a == 0)
  192906. {
  192907. /* background is already in screen gamma */
  192908. *dp = (png_byte)background->gray;
  192909. }
  192910. else
  192911. {
  192912. png_byte v, w;
  192913. v = gamma_to_1[*sp];
  192914. png_composite(w, v, a, background_1->gray);
  192915. *dp = gamma_from_1[w];
  192916. }
  192917. }
  192918. }
  192919. else
  192920. #endif
  192921. {
  192922. sp = row;
  192923. dp = row;
  192924. for (i = 0; i < row_width; i++, sp += 2, dp++)
  192925. {
  192926. png_byte a = *(sp + 1);
  192927. if (a == 0xff)
  192928. {
  192929. *dp = *sp;
  192930. }
  192931. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192932. else if (a == 0)
  192933. {
  192934. *dp = (png_byte)background->gray;
  192935. }
  192936. else
  192937. {
  192938. png_composite(*dp, *sp, a, background_1->gray);
  192939. }
  192940. #else
  192941. *dp = (png_byte)background->gray;
  192942. #endif
  192943. }
  192944. }
  192945. }
  192946. else /* if (png_ptr->bit_depth == 16) */
  192947. {
  192948. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192949. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  192950. gamma_16_to_1 != NULL)
  192951. {
  192952. sp = row;
  192953. dp = row;
  192954. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  192955. {
  192956. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192957. if (a == (png_uint_16)0xffff)
  192958. {
  192959. png_uint_16 v;
  192960. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192961. *dp = (png_byte)((v >> 8) & 0xff);
  192962. *(dp + 1) = (png_byte)(v & 0xff);
  192963. }
  192964. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192965. else if (a == 0)
  192966. #else
  192967. else
  192968. #endif
  192969. {
  192970. /* background is already in screen gamma */
  192971. *dp = (png_byte)((background->gray >> 8) & 0xff);
  192972. *(dp + 1) = (png_byte)(background->gray & 0xff);
  192973. }
  192974. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192975. else
  192976. {
  192977. png_uint_16 g, v, w;
  192978. g = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  192979. png_composite_16(v, g, a, background_1->gray);
  192980. w = gamma_16_from_1[(v&0xff) >> gamma_shift][v >> 8];
  192981. *dp = (png_byte)((w >> 8) & 0xff);
  192982. *(dp + 1) = (png_byte)(w & 0xff);
  192983. }
  192984. #endif
  192985. }
  192986. }
  192987. else
  192988. #endif
  192989. {
  192990. sp = row;
  192991. dp = row;
  192992. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  192993. {
  192994. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192995. if (a == (png_uint_16)0xffff)
  192996. {
  192997. png_memcpy(dp, sp, 2);
  192998. }
  192999. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193000. else if (a == 0)
  193001. #else
  193002. else
  193003. #endif
  193004. {
  193005. *dp = (png_byte)((background->gray >> 8) & 0xff);
  193006. *(dp + 1) = (png_byte)(background->gray & 0xff);
  193007. }
  193008. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193009. else
  193010. {
  193011. png_uint_16 g, v;
  193012. g = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  193013. png_composite_16(v, g, a, background_1->gray);
  193014. *dp = (png_byte)((v >> 8) & 0xff);
  193015. *(dp + 1) = (png_byte)(v & 0xff);
  193016. }
  193017. #endif
  193018. }
  193019. }
  193020. }
  193021. break;
  193022. }
  193023. case PNG_COLOR_TYPE_RGB_ALPHA:
  193024. {
  193025. if (row_info->bit_depth == 8)
  193026. {
  193027. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193028. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  193029. gamma_table != NULL)
  193030. {
  193031. sp = row;
  193032. dp = row;
  193033. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  193034. {
  193035. png_byte a = *(sp + 3);
  193036. if (a == 0xff)
  193037. {
  193038. *dp = gamma_table[*sp];
  193039. *(dp + 1) = gamma_table[*(sp + 1)];
  193040. *(dp + 2) = gamma_table[*(sp + 2)];
  193041. }
  193042. else if (a == 0)
  193043. {
  193044. /* background is already in screen gamma */
  193045. *dp = (png_byte)background->red;
  193046. *(dp + 1) = (png_byte)background->green;
  193047. *(dp + 2) = (png_byte)background->blue;
  193048. }
  193049. else
  193050. {
  193051. png_byte v, w;
  193052. v = gamma_to_1[*sp];
  193053. png_composite(w, v, a, background_1->red);
  193054. *dp = gamma_from_1[w];
  193055. v = gamma_to_1[*(sp + 1)];
  193056. png_composite(w, v, a, background_1->green);
  193057. *(dp + 1) = gamma_from_1[w];
  193058. v = gamma_to_1[*(sp + 2)];
  193059. png_composite(w, v, a, background_1->blue);
  193060. *(dp + 2) = gamma_from_1[w];
  193061. }
  193062. }
  193063. }
  193064. else
  193065. #endif
  193066. {
  193067. sp = row;
  193068. dp = row;
  193069. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  193070. {
  193071. png_byte a = *(sp + 3);
  193072. if (a == 0xff)
  193073. {
  193074. *dp = *sp;
  193075. *(dp + 1) = *(sp + 1);
  193076. *(dp + 2) = *(sp + 2);
  193077. }
  193078. else if (a == 0)
  193079. {
  193080. *dp = (png_byte)background->red;
  193081. *(dp + 1) = (png_byte)background->green;
  193082. *(dp + 2) = (png_byte)background->blue;
  193083. }
  193084. else
  193085. {
  193086. png_composite(*dp, *sp, a, background->red);
  193087. png_composite(*(dp + 1), *(sp + 1), a,
  193088. background->green);
  193089. png_composite(*(dp + 2), *(sp + 2), a,
  193090. background->blue);
  193091. }
  193092. }
  193093. }
  193094. }
  193095. else /* if (row_info->bit_depth == 16) */
  193096. {
  193097. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193098. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  193099. gamma_16_to_1 != NULL)
  193100. {
  193101. sp = row;
  193102. dp = row;
  193103. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  193104. {
  193105. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  193106. << 8) + (png_uint_16)(*(sp + 7)));
  193107. if (a == (png_uint_16)0xffff)
  193108. {
  193109. png_uint_16 v;
  193110. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  193111. *dp = (png_byte)((v >> 8) & 0xff);
  193112. *(dp + 1) = (png_byte)(v & 0xff);
  193113. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  193114. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  193115. *(dp + 3) = (png_byte)(v & 0xff);
  193116. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  193117. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  193118. *(dp + 5) = (png_byte)(v & 0xff);
  193119. }
  193120. else if (a == 0)
  193121. {
  193122. /* background is already in screen gamma */
  193123. *dp = (png_byte)((background->red >> 8) & 0xff);
  193124. *(dp + 1) = (png_byte)(background->red & 0xff);
  193125. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  193126. *(dp + 3) = (png_byte)(background->green & 0xff);
  193127. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  193128. *(dp + 5) = (png_byte)(background->blue & 0xff);
  193129. }
  193130. else
  193131. {
  193132. png_uint_16 v, w, x;
  193133. v = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  193134. png_composite_16(w, v, a, background_1->red);
  193135. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  193136. *dp = (png_byte)((x >> 8) & 0xff);
  193137. *(dp + 1) = (png_byte)(x & 0xff);
  193138. v = gamma_16_to_1[*(sp + 3) >> gamma_shift][*(sp + 2)];
  193139. png_composite_16(w, v, a, background_1->green);
  193140. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  193141. *(dp + 2) = (png_byte)((x >> 8) & 0xff);
  193142. *(dp + 3) = (png_byte)(x & 0xff);
  193143. v = gamma_16_to_1[*(sp + 5) >> gamma_shift][*(sp + 4)];
  193144. png_composite_16(w, v, a, background_1->blue);
  193145. x = gamma_16_from_1[(w & 0xff) >> gamma_shift][w >> 8];
  193146. *(dp + 4) = (png_byte)((x >> 8) & 0xff);
  193147. *(dp + 5) = (png_byte)(x & 0xff);
  193148. }
  193149. }
  193150. }
  193151. else
  193152. #endif
  193153. {
  193154. sp = row;
  193155. dp = row;
  193156. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  193157. {
  193158. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  193159. << 8) + (png_uint_16)(*(sp + 7)));
  193160. if (a == (png_uint_16)0xffff)
  193161. {
  193162. png_memcpy(dp, sp, 6);
  193163. }
  193164. else if (a == 0)
  193165. {
  193166. *dp = (png_byte)((background->red >> 8) & 0xff);
  193167. *(dp + 1) = (png_byte)(background->red & 0xff);
  193168. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  193169. *(dp + 3) = (png_byte)(background->green & 0xff);
  193170. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  193171. *(dp + 5) = (png_byte)(background->blue & 0xff);
  193172. }
  193173. else
  193174. {
  193175. png_uint_16 v;
  193176. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  193177. png_uint_16 g = (png_uint_16)(((*(sp + 2)) << 8)
  193178. + *(sp + 3));
  193179. png_uint_16 b = (png_uint_16)(((*(sp + 4)) << 8)
  193180. + *(sp + 5));
  193181. png_composite_16(v, r, a, background->red);
  193182. *dp = (png_byte)((v >> 8) & 0xff);
  193183. *(dp + 1) = (png_byte)(v & 0xff);
  193184. png_composite_16(v, g, a, background->green);
  193185. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  193186. *(dp + 3) = (png_byte)(v & 0xff);
  193187. png_composite_16(v, b, a, background->blue);
  193188. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  193189. *(dp + 5) = (png_byte)(v & 0xff);
  193190. }
  193191. }
  193192. }
  193193. }
  193194. break;
  193195. }
  193196. }
  193197. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  193198. {
  193199. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  193200. row_info->channels--;
  193201. row_info->pixel_depth = (png_byte)(row_info->channels *
  193202. row_info->bit_depth);
  193203. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193204. }
  193205. }
  193206. }
  193207. #endif
  193208. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193209. /* Gamma correct the image, avoiding the alpha channel. Make sure
  193210. * you do this after you deal with the transparency issue on grayscale
  193211. * or RGB images. If your bit depth is 8, use gamma_table, if it
  193212. * is 16, use gamma_16_table and gamma_shift. Build these with
  193213. * build_gamma_table().
  193214. */
  193215. void /* PRIVATE */
  193216. png_do_gamma(png_row_infop row_info, png_bytep row,
  193217. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  193218. int gamma_shift)
  193219. {
  193220. png_bytep sp;
  193221. png_uint_32 i;
  193222. png_uint_32 row_width=row_info->width;
  193223. png_debug(1, "in png_do_gamma\n");
  193224. if (
  193225. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193226. row != NULL && row_info != NULL &&
  193227. #endif
  193228. ((row_info->bit_depth <= 8 && gamma_table != NULL) ||
  193229. (row_info->bit_depth == 16 && gamma_16_table != NULL)))
  193230. {
  193231. switch (row_info->color_type)
  193232. {
  193233. case PNG_COLOR_TYPE_RGB:
  193234. {
  193235. if (row_info->bit_depth == 8)
  193236. {
  193237. sp = row;
  193238. for (i = 0; i < row_width; i++)
  193239. {
  193240. *sp = gamma_table[*sp];
  193241. sp++;
  193242. *sp = gamma_table[*sp];
  193243. sp++;
  193244. *sp = gamma_table[*sp];
  193245. sp++;
  193246. }
  193247. }
  193248. else /* if (row_info->bit_depth == 16) */
  193249. {
  193250. sp = row;
  193251. for (i = 0; i < row_width; i++)
  193252. {
  193253. png_uint_16 v;
  193254. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193255. *sp = (png_byte)((v >> 8) & 0xff);
  193256. *(sp + 1) = (png_byte)(v & 0xff);
  193257. sp += 2;
  193258. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193259. *sp = (png_byte)((v >> 8) & 0xff);
  193260. *(sp + 1) = (png_byte)(v & 0xff);
  193261. sp += 2;
  193262. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193263. *sp = (png_byte)((v >> 8) & 0xff);
  193264. *(sp + 1) = (png_byte)(v & 0xff);
  193265. sp += 2;
  193266. }
  193267. }
  193268. break;
  193269. }
  193270. case PNG_COLOR_TYPE_RGB_ALPHA:
  193271. {
  193272. if (row_info->bit_depth == 8)
  193273. {
  193274. sp = row;
  193275. for (i = 0; i < row_width; i++)
  193276. {
  193277. *sp = gamma_table[*sp];
  193278. sp++;
  193279. *sp = gamma_table[*sp];
  193280. sp++;
  193281. *sp = gamma_table[*sp];
  193282. sp++;
  193283. sp++;
  193284. }
  193285. }
  193286. else /* if (row_info->bit_depth == 16) */
  193287. {
  193288. sp = row;
  193289. for (i = 0; i < row_width; i++)
  193290. {
  193291. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193292. *sp = (png_byte)((v >> 8) & 0xff);
  193293. *(sp + 1) = (png_byte)(v & 0xff);
  193294. sp += 2;
  193295. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193296. *sp = (png_byte)((v >> 8) & 0xff);
  193297. *(sp + 1) = (png_byte)(v & 0xff);
  193298. sp += 2;
  193299. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193300. *sp = (png_byte)((v >> 8) & 0xff);
  193301. *(sp + 1) = (png_byte)(v & 0xff);
  193302. sp += 4;
  193303. }
  193304. }
  193305. break;
  193306. }
  193307. case PNG_COLOR_TYPE_GRAY_ALPHA:
  193308. {
  193309. if (row_info->bit_depth == 8)
  193310. {
  193311. sp = row;
  193312. for (i = 0; i < row_width; i++)
  193313. {
  193314. *sp = gamma_table[*sp];
  193315. sp += 2;
  193316. }
  193317. }
  193318. else /* if (row_info->bit_depth == 16) */
  193319. {
  193320. sp = row;
  193321. for (i = 0; i < row_width; i++)
  193322. {
  193323. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193324. *sp = (png_byte)((v >> 8) & 0xff);
  193325. *(sp + 1) = (png_byte)(v & 0xff);
  193326. sp += 4;
  193327. }
  193328. }
  193329. break;
  193330. }
  193331. case PNG_COLOR_TYPE_GRAY:
  193332. {
  193333. if (row_info->bit_depth == 2)
  193334. {
  193335. sp = row;
  193336. for (i = 0; i < row_width; i += 4)
  193337. {
  193338. int a = *sp & 0xc0;
  193339. int b = *sp & 0x30;
  193340. int c = *sp & 0x0c;
  193341. int d = *sp & 0x03;
  193342. *sp = (png_byte)(
  193343. ((((int)gamma_table[a|(a>>2)|(a>>4)|(a>>6)]) ) & 0xc0)|
  193344. ((((int)gamma_table[(b<<2)|b|(b>>2)|(b>>4)])>>2) & 0x30)|
  193345. ((((int)gamma_table[(c<<4)|(c<<2)|c|(c>>2)])>>4) & 0x0c)|
  193346. ((((int)gamma_table[(d<<6)|(d<<4)|(d<<2)|d])>>6) ));
  193347. sp++;
  193348. }
  193349. }
  193350. if (row_info->bit_depth == 4)
  193351. {
  193352. sp = row;
  193353. for (i = 0; i < row_width; i += 2)
  193354. {
  193355. int msb = *sp & 0xf0;
  193356. int lsb = *sp & 0x0f;
  193357. *sp = (png_byte)((((int)gamma_table[msb | (msb >> 4)]) & 0xf0)
  193358. | (((int)gamma_table[(lsb << 4) | lsb]) >> 4));
  193359. sp++;
  193360. }
  193361. }
  193362. else if (row_info->bit_depth == 8)
  193363. {
  193364. sp = row;
  193365. for (i = 0; i < row_width; i++)
  193366. {
  193367. *sp = gamma_table[*sp];
  193368. sp++;
  193369. }
  193370. }
  193371. else if (row_info->bit_depth == 16)
  193372. {
  193373. sp = row;
  193374. for (i = 0; i < row_width; i++)
  193375. {
  193376. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193377. *sp = (png_byte)((v >> 8) & 0xff);
  193378. *(sp + 1) = (png_byte)(v & 0xff);
  193379. sp += 2;
  193380. }
  193381. }
  193382. break;
  193383. }
  193384. }
  193385. }
  193386. }
  193387. #endif
  193388. #if defined(PNG_READ_EXPAND_SUPPORTED)
  193389. /* Expands a palette row to an RGB or RGBA row depending
  193390. * upon whether you supply trans and num_trans.
  193391. */
  193392. void /* PRIVATE */
  193393. png_do_expand_palette(png_row_infop row_info, png_bytep row,
  193394. png_colorp palette, png_bytep trans, int num_trans)
  193395. {
  193396. int shift, value;
  193397. png_bytep sp, dp;
  193398. png_uint_32 i;
  193399. png_uint_32 row_width=row_info->width;
  193400. png_debug(1, "in png_do_expand_palette\n");
  193401. if (
  193402. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193403. row != NULL && row_info != NULL &&
  193404. #endif
  193405. row_info->color_type == PNG_COLOR_TYPE_PALETTE)
  193406. {
  193407. if (row_info->bit_depth < 8)
  193408. {
  193409. switch (row_info->bit_depth)
  193410. {
  193411. case 1:
  193412. {
  193413. sp = row + (png_size_t)((row_width - 1) >> 3);
  193414. dp = row + (png_size_t)row_width - 1;
  193415. shift = 7 - (int)((row_width + 7) & 0x07);
  193416. for (i = 0; i < row_width; i++)
  193417. {
  193418. if ((*sp >> shift) & 0x01)
  193419. *dp = 1;
  193420. else
  193421. *dp = 0;
  193422. if (shift == 7)
  193423. {
  193424. shift = 0;
  193425. sp--;
  193426. }
  193427. else
  193428. shift++;
  193429. dp--;
  193430. }
  193431. break;
  193432. }
  193433. case 2:
  193434. {
  193435. sp = row + (png_size_t)((row_width - 1) >> 2);
  193436. dp = row + (png_size_t)row_width - 1;
  193437. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  193438. for (i = 0; i < row_width; i++)
  193439. {
  193440. value = (*sp >> shift) & 0x03;
  193441. *dp = (png_byte)value;
  193442. if (shift == 6)
  193443. {
  193444. shift = 0;
  193445. sp--;
  193446. }
  193447. else
  193448. shift += 2;
  193449. dp--;
  193450. }
  193451. break;
  193452. }
  193453. case 4:
  193454. {
  193455. sp = row + (png_size_t)((row_width - 1) >> 1);
  193456. dp = row + (png_size_t)row_width - 1;
  193457. shift = (int)((row_width & 0x01) << 2);
  193458. for (i = 0; i < row_width; i++)
  193459. {
  193460. value = (*sp >> shift) & 0x0f;
  193461. *dp = (png_byte)value;
  193462. if (shift == 4)
  193463. {
  193464. shift = 0;
  193465. sp--;
  193466. }
  193467. else
  193468. shift += 4;
  193469. dp--;
  193470. }
  193471. break;
  193472. }
  193473. }
  193474. row_info->bit_depth = 8;
  193475. row_info->pixel_depth = 8;
  193476. row_info->rowbytes = row_width;
  193477. }
  193478. switch (row_info->bit_depth)
  193479. {
  193480. case 8:
  193481. {
  193482. if (trans != NULL)
  193483. {
  193484. sp = row + (png_size_t)row_width - 1;
  193485. dp = row + (png_size_t)(row_width << 2) - 1;
  193486. for (i = 0; i < row_width; i++)
  193487. {
  193488. if ((int)(*sp) >= num_trans)
  193489. *dp-- = 0xff;
  193490. else
  193491. *dp-- = trans[*sp];
  193492. *dp-- = palette[*sp].blue;
  193493. *dp-- = palette[*sp].green;
  193494. *dp-- = palette[*sp].red;
  193495. sp--;
  193496. }
  193497. row_info->bit_depth = 8;
  193498. row_info->pixel_depth = 32;
  193499. row_info->rowbytes = row_width * 4;
  193500. row_info->color_type = 6;
  193501. row_info->channels = 4;
  193502. }
  193503. else
  193504. {
  193505. sp = row + (png_size_t)row_width - 1;
  193506. dp = row + (png_size_t)(row_width * 3) - 1;
  193507. for (i = 0; i < row_width; i++)
  193508. {
  193509. *dp-- = palette[*sp].blue;
  193510. *dp-- = palette[*sp].green;
  193511. *dp-- = palette[*sp].red;
  193512. sp--;
  193513. }
  193514. row_info->bit_depth = 8;
  193515. row_info->pixel_depth = 24;
  193516. row_info->rowbytes = row_width * 3;
  193517. row_info->color_type = 2;
  193518. row_info->channels = 3;
  193519. }
  193520. break;
  193521. }
  193522. }
  193523. }
  193524. }
  193525. /* If the bit depth < 8, it is expanded to 8. Also, if the already
  193526. * expanded transparency value is supplied, an alpha channel is built.
  193527. */
  193528. void /* PRIVATE */
  193529. png_do_expand(png_row_infop row_info, png_bytep row,
  193530. png_color_16p trans_value)
  193531. {
  193532. int shift, value;
  193533. png_bytep sp, dp;
  193534. png_uint_32 i;
  193535. png_uint_32 row_width=row_info->width;
  193536. png_debug(1, "in png_do_expand\n");
  193537. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193538. if (row != NULL && row_info != NULL)
  193539. #endif
  193540. {
  193541. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  193542. {
  193543. png_uint_16 gray = (png_uint_16)(trans_value ? trans_value->gray : 0);
  193544. if (row_info->bit_depth < 8)
  193545. {
  193546. switch (row_info->bit_depth)
  193547. {
  193548. case 1:
  193549. {
  193550. gray = (png_uint_16)((gray&0x01)*0xff);
  193551. sp = row + (png_size_t)((row_width - 1) >> 3);
  193552. dp = row + (png_size_t)row_width - 1;
  193553. shift = 7 - (int)((row_width + 7) & 0x07);
  193554. for (i = 0; i < row_width; i++)
  193555. {
  193556. if ((*sp >> shift) & 0x01)
  193557. *dp = 0xff;
  193558. else
  193559. *dp = 0;
  193560. if (shift == 7)
  193561. {
  193562. shift = 0;
  193563. sp--;
  193564. }
  193565. else
  193566. shift++;
  193567. dp--;
  193568. }
  193569. break;
  193570. }
  193571. case 2:
  193572. {
  193573. gray = (png_uint_16)((gray&0x03)*0x55);
  193574. sp = row + (png_size_t)((row_width - 1) >> 2);
  193575. dp = row + (png_size_t)row_width - 1;
  193576. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  193577. for (i = 0; i < row_width; i++)
  193578. {
  193579. value = (*sp >> shift) & 0x03;
  193580. *dp = (png_byte)(value | (value << 2) | (value << 4) |
  193581. (value << 6));
  193582. if (shift == 6)
  193583. {
  193584. shift = 0;
  193585. sp--;
  193586. }
  193587. else
  193588. shift += 2;
  193589. dp--;
  193590. }
  193591. break;
  193592. }
  193593. case 4:
  193594. {
  193595. gray = (png_uint_16)((gray&0x0f)*0x11);
  193596. sp = row + (png_size_t)((row_width - 1) >> 1);
  193597. dp = row + (png_size_t)row_width - 1;
  193598. shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  193599. for (i = 0; i < row_width; i++)
  193600. {
  193601. value = (*sp >> shift) & 0x0f;
  193602. *dp = (png_byte)(value | (value << 4));
  193603. if (shift == 4)
  193604. {
  193605. shift = 0;
  193606. sp--;
  193607. }
  193608. else
  193609. shift = 4;
  193610. dp--;
  193611. }
  193612. break;
  193613. }
  193614. }
  193615. row_info->bit_depth = 8;
  193616. row_info->pixel_depth = 8;
  193617. row_info->rowbytes = row_width;
  193618. }
  193619. if (trans_value != NULL)
  193620. {
  193621. if (row_info->bit_depth == 8)
  193622. {
  193623. gray = gray & 0xff;
  193624. sp = row + (png_size_t)row_width - 1;
  193625. dp = row + (png_size_t)(row_width << 1) - 1;
  193626. for (i = 0; i < row_width; i++)
  193627. {
  193628. if (*sp == gray)
  193629. *dp-- = 0;
  193630. else
  193631. *dp-- = 0xff;
  193632. *dp-- = *sp--;
  193633. }
  193634. }
  193635. else if (row_info->bit_depth == 16)
  193636. {
  193637. png_byte gray_high = (gray >> 8) & 0xff;
  193638. png_byte gray_low = gray & 0xff;
  193639. sp = row + row_info->rowbytes - 1;
  193640. dp = row + (row_info->rowbytes << 1) - 1;
  193641. for (i = 0; i < row_width; i++)
  193642. {
  193643. if (*(sp-1) == gray_high && *(sp) == gray_low)
  193644. {
  193645. *dp-- = 0;
  193646. *dp-- = 0;
  193647. }
  193648. else
  193649. {
  193650. *dp-- = 0xff;
  193651. *dp-- = 0xff;
  193652. }
  193653. *dp-- = *sp--;
  193654. *dp-- = *sp--;
  193655. }
  193656. }
  193657. row_info->color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
  193658. row_info->channels = 2;
  193659. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 1);
  193660. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  193661. row_width);
  193662. }
  193663. }
  193664. else if (row_info->color_type == PNG_COLOR_TYPE_RGB && trans_value)
  193665. {
  193666. if (row_info->bit_depth == 8)
  193667. {
  193668. png_byte red = trans_value->red & 0xff;
  193669. png_byte green = trans_value->green & 0xff;
  193670. png_byte blue = trans_value->blue & 0xff;
  193671. sp = row + (png_size_t)row_info->rowbytes - 1;
  193672. dp = row + (png_size_t)(row_width << 2) - 1;
  193673. for (i = 0; i < row_width; i++)
  193674. {
  193675. if (*(sp - 2) == red && *(sp - 1) == green && *(sp) == blue)
  193676. *dp-- = 0;
  193677. else
  193678. *dp-- = 0xff;
  193679. *dp-- = *sp--;
  193680. *dp-- = *sp--;
  193681. *dp-- = *sp--;
  193682. }
  193683. }
  193684. else if (row_info->bit_depth == 16)
  193685. {
  193686. png_byte red_high = (trans_value->red >> 8) & 0xff;
  193687. png_byte green_high = (trans_value->green >> 8) & 0xff;
  193688. png_byte blue_high = (trans_value->blue >> 8) & 0xff;
  193689. png_byte red_low = trans_value->red & 0xff;
  193690. png_byte green_low = trans_value->green & 0xff;
  193691. png_byte blue_low = trans_value->blue & 0xff;
  193692. sp = row + row_info->rowbytes - 1;
  193693. dp = row + (png_size_t)(row_width << 3) - 1;
  193694. for (i = 0; i < row_width; i++)
  193695. {
  193696. if (*(sp - 5) == red_high &&
  193697. *(sp - 4) == red_low &&
  193698. *(sp - 3) == green_high &&
  193699. *(sp - 2) == green_low &&
  193700. *(sp - 1) == blue_high &&
  193701. *(sp ) == blue_low)
  193702. {
  193703. *dp-- = 0;
  193704. *dp-- = 0;
  193705. }
  193706. else
  193707. {
  193708. *dp-- = 0xff;
  193709. *dp-- = 0xff;
  193710. }
  193711. *dp-- = *sp--;
  193712. *dp-- = *sp--;
  193713. *dp-- = *sp--;
  193714. *dp-- = *sp--;
  193715. *dp-- = *sp--;
  193716. *dp-- = *sp--;
  193717. }
  193718. }
  193719. row_info->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  193720. row_info->channels = 4;
  193721. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 2);
  193722. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193723. }
  193724. }
  193725. }
  193726. #endif
  193727. #if defined(PNG_READ_DITHER_SUPPORTED)
  193728. void /* PRIVATE */
  193729. png_do_dither(png_row_infop row_info, png_bytep row,
  193730. png_bytep palette_lookup, png_bytep dither_lookup)
  193731. {
  193732. png_bytep sp, dp;
  193733. png_uint_32 i;
  193734. png_uint_32 row_width=row_info->width;
  193735. png_debug(1, "in png_do_dither\n");
  193736. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193737. if (row != NULL && row_info != NULL)
  193738. #endif
  193739. {
  193740. if (row_info->color_type == PNG_COLOR_TYPE_RGB &&
  193741. palette_lookup && row_info->bit_depth == 8)
  193742. {
  193743. int r, g, b, p;
  193744. sp = row;
  193745. dp = row;
  193746. for (i = 0; i < row_width; i++)
  193747. {
  193748. r = *sp++;
  193749. g = *sp++;
  193750. b = *sp++;
  193751. /* this looks real messy, but the compiler will reduce
  193752. it down to a reasonable formula. For example, with
  193753. 5 bits per color, we get:
  193754. p = (((r >> 3) & 0x1f) << 10) |
  193755. (((g >> 3) & 0x1f) << 5) |
  193756. ((b >> 3) & 0x1f);
  193757. */
  193758. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  193759. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  193760. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  193761. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  193762. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  193763. (PNG_DITHER_BLUE_BITS)) |
  193764. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  193765. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  193766. *dp++ = palette_lookup[p];
  193767. }
  193768. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  193769. row_info->channels = 1;
  193770. row_info->pixel_depth = row_info->bit_depth;
  193771. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193772. }
  193773. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  193774. palette_lookup != NULL && row_info->bit_depth == 8)
  193775. {
  193776. int r, g, b, p;
  193777. sp = row;
  193778. dp = row;
  193779. for (i = 0; i < row_width; i++)
  193780. {
  193781. r = *sp++;
  193782. g = *sp++;
  193783. b = *sp++;
  193784. sp++;
  193785. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  193786. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  193787. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  193788. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  193789. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  193790. (PNG_DITHER_BLUE_BITS)) |
  193791. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  193792. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  193793. *dp++ = palette_lookup[p];
  193794. }
  193795. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  193796. row_info->channels = 1;
  193797. row_info->pixel_depth = row_info->bit_depth;
  193798. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193799. }
  193800. else if (row_info->color_type == PNG_COLOR_TYPE_PALETTE &&
  193801. dither_lookup && row_info->bit_depth == 8)
  193802. {
  193803. sp = row;
  193804. for (i = 0; i < row_width; i++, sp++)
  193805. {
  193806. *sp = dither_lookup[*sp];
  193807. }
  193808. }
  193809. }
  193810. }
  193811. #endif
  193812. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193813. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193814. static PNG_CONST int png_gamma_shift[] =
  193815. {0x10, 0x21, 0x42, 0x84, 0x110, 0x248, 0x550, 0xff0, 0x00};
  193816. /* We build the 8- or 16-bit gamma tables here. Note that for 16-bit
  193817. * tables, we don't make a full table if we are reducing to 8-bit in
  193818. * the future. Note also how the gamma_16 tables are segmented so that
  193819. * we don't need to allocate > 64K chunks for a full 16-bit table.
  193820. */
  193821. void /* PRIVATE */
  193822. png_build_gamma_table(png_structp png_ptr)
  193823. {
  193824. png_debug(1, "in png_build_gamma_table\n");
  193825. if (png_ptr->bit_depth <= 8)
  193826. {
  193827. int i;
  193828. double g;
  193829. if (png_ptr->screen_gamma > .000001)
  193830. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  193831. else
  193832. g = 1.0;
  193833. png_ptr->gamma_table = (png_bytep)png_malloc(png_ptr,
  193834. (png_uint_32)256);
  193835. for (i = 0; i < 256; i++)
  193836. {
  193837. png_ptr->gamma_table[i] = (png_byte)(pow((double)i / 255.0,
  193838. g) * 255.0 + .5);
  193839. }
  193840. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  193841. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  193842. if (png_ptr->transformations & ((PNG_BACKGROUND) | PNG_RGB_TO_GRAY))
  193843. {
  193844. g = 1.0 / (png_ptr->gamma);
  193845. png_ptr->gamma_to_1 = (png_bytep)png_malloc(png_ptr,
  193846. (png_uint_32)256);
  193847. for (i = 0; i < 256; i++)
  193848. {
  193849. png_ptr->gamma_to_1[i] = (png_byte)(pow((double)i / 255.0,
  193850. g) * 255.0 + .5);
  193851. }
  193852. png_ptr->gamma_from_1 = (png_bytep)png_malloc(png_ptr,
  193853. (png_uint_32)256);
  193854. if(png_ptr->screen_gamma > 0.000001)
  193855. g = 1.0 / png_ptr->screen_gamma;
  193856. else
  193857. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  193858. for (i = 0; i < 256; i++)
  193859. {
  193860. png_ptr->gamma_from_1[i] = (png_byte)(pow((double)i / 255.0,
  193861. g) * 255.0 + .5);
  193862. }
  193863. }
  193864. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  193865. }
  193866. else
  193867. {
  193868. double g;
  193869. int i, j, shift, num;
  193870. int sig_bit;
  193871. png_uint_32 ig;
  193872. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  193873. {
  193874. sig_bit = (int)png_ptr->sig_bit.red;
  193875. if ((int)png_ptr->sig_bit.green > sig_bit)
  193876. sig_bit = png_ptr->sig_bit.green;
  193877. if ((int)png_ptr->sig_bit.blue > sig_bit)
  193878. sig_bit = png_ptr->sig_bit.blue;
  193879. }
  193880. else
  193881. {
  193882. sig_bit = (int)png_ptr->sig_bit.gray;
  193883. }
  193884. if (sig_bit > 0)
  193885. shift = 16 - sig_bit;
  193886. else
  193887. shift = 0;
  193888. if (png_ptr->transformations & PNG_16_TO_8)
  193889. {
  193890. if (shift < (16 - PNG_MAX_GAMMA_8))
  193891. shift = (16 - PNG_MAX_GAMMA_8);
  193892. }
  193893. if (shift > 8)
  193894. shift = 8;
  193895. if (shift < 0)
  193896. shift = 0;
  193897. png_ptr->gamma_shift = (png_byte)shift;
  193898. num = (1 << (8 - shift));
  193899. if (png_ptr->screen_gamma > .000001)
  193900. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  193901. else
  193902. g = 1.0;
  193903. png_ptr->gamma_16_table = (png_uint_16pp)png_malloc(png_ptr,
  193904. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  193905. if (png_ptr->transformations & (PNG_16_TO_8 | PNG_BACKGROUND))
  193906. {
  193907. double fin, fout;
  193908. png_uint_32 last, max;
  193909. for (i = 0; i < num; i++)
  193910. {
  193911. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  193912. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193913. }
  193914. g = 1.0 / g;
  193915. last = 0;
  193916. for (i = 0; i < 256; i++)
  193917. {
  193918. fout = ((double)i + 0.5) / 256.0;
  193919. fin = pow(fout, g);
  193920. max = (png_uint_32)(fin * (double)((png_uint_32)num << 8));
  193921. while (last <= max)
  193922. {
  193923. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  193924. [(int)(last >> (8 - shift))] = (png_uint_16)(
  193925. (png_uint_16)i | ((png_uint_16)i << 8));
  193926. last++;
  193927. }
  193928. }
  193929. while (last < ((png_uint_32)num << 8))
  193930. {
  193931. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  193932. [(int)(last >> (8 - shift))] = (png_uint_16)65535L;
  193933. last++;
  193934. }
  193935. }
  193936. else
  193937. {
  193938. for (i = 0; i < num; i++)
  193939. {
  193940. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  193941. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193942. ig = (((png_uint_32)i * (png_uint_32)png_gamma_shift[shift]) >> 4);
  193943. for (j = 0; j < 256; j++)
  193944. {
  193945. png_ptr->gamma_16_table[i][j] =
  193946. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  193947. 65535.0, g) * 65535.0 + .5);
  193948. }
  193949. }
  193950. }
  193951. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  193952. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  193953. if (png_ptr->transformations & (PNG_BACKGROUND | PNG_RGB_TO_GRAY))
  193954. {
  193955. g = 1.0 / (png_ptr->gamma);
  193956. png_ptr->gamma_16_to_1 = (png_uint_16pp)png_malloc(png_ptr,
  193957. (png_uint_32)(num * png_sizeof (png_uint_16p )));
  193958. for (i = 0; i < num; i++)
  193959. {
  193960. png_ptr->gamma_16_to_1[i] = (png_uint_16p)png_malloc(png_ptr,
  193961. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193962. ig = (((png_uint_32)i *
  193963. (png_uint_32)png_gamma_shift[shift]) >> 4);
  193964. for (j = 0; j < 256; j++)
  193965. {
  193966. png_ptr->gamma_16_to_1[i][j] =
  193967. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  193968. 65535.0, g) * 65535.0 + .5);
  193969. }
  193970. }
  193971. if(png_ptr->screen_gamma > 0.000001)
  193972. g = 1.0 / png_ptr->screen_gamma;
  193973. else
  193974. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  193975. png_ptr->gamma_16_from_1 = (png_uint_16pp)png_malloc(png_ptr,
  193976. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  193977. for (i = 0; i < num; i++)
  193978. {
  193979. png_ptr->gamma_16_from_1[i] = (png_uint_16p)png_malloc(png_ptr,
  193980. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193981. ig = (((png_uint_32)i *
  193982. (png_uint_32)png_gamma_shift[shift]) >> 4);
  193983. for (j = 0; j < 256; j++)
  193984. {
  193985. png_ptr->gamma_16_from_1[i][j] =
  193986. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  193987. 65535.0, g) * 65535.0 + .5);
  193988. }
  193989. }
  193990. }
  193991. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  193992. }
  193993. }
  193994. #endif
  193995. /* To do: install integer version of png_build_gamma_table here */
  193996. #endif
  193997. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  193998. /* undoes intrapixel differencing */
  193999. void /* PRIVATE */
  194000. png_do_read_intrapixel(png_row_infop row_info, png_bytep row)
  194001. {
  194002. png_debug(1, "in png_do_read_intrapixel\n");
  194003. if (
  194004. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  194005. row != NULL && row_info != NULL &&
  194006. #endif
  194007. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  194008. {
  194009. int bytes_per_pixel;
  194010. png_uint_32 row_width = row_info->width;
  194011. if (row_info->bit_depth == 8)
  194012. {
  194013. png_bytep rp;
  194014. png_uint_32 i;
  194015. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  194016. bytes_per_pixel = 3;
  194017. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  194018. bytes_per_pixel = 4;
  194019. else
  194020. return;
  194021. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  194022. {
  194023. *(rp) = (png_byte)((256 + *rp + *(rp+1))&0xff);
  194024. *(rp+2) = (png_byte)((256 + *(rp+2) + *(rp+1))&0xff);
  194025. }
  194026. }
  194027. else if (row_info->bit_depth == 16)
  194028. {
  194029. png_bytep rp;
  194030. png_uint_32 i;
  194031. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  194032. bytes_per_pixel = 6;
  194033. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  194034. bytes_per_pixel = 8;
  194035. else
  194036. return;
  194037. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  194038. {
  194039. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  194040. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  194041. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  194042. png_uint_32 red = (png_uint_32)((s0+s1+65536L) & 0xffffL);
  194043. png_uint_32 blue = (png_uint_32)((s2+s1+65536L) & 0xffffL);
  194044. *(rp ) = (png_byte)((red >> 8) & 0xff);
  194045. *(rp+1) = (png_byte)(red & 0xff);
  194046. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  194047. *(rp+5) = (png_byte)(blue & 0xff);
  194048. }
  194049. }
  194050. }
  194051. }
  194052. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  194053. #endif /* PNG_READ_SUPPORTED */
  194054. /*** End of inlined file: pngrtran.c ***/
  194055. /*** Start of inlined file: pngrutil.c ***/
  194056. /* pngrutil.c - utilities to read a PNG file
  194057. *
  194058. * Last changed in libpng 1.2.21 [October 4, 2007]
  194059. * For conditions of distribution and use, see copyright notice in png.h
  194060. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  194061. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  194062. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  194063. *
  194064. * This file contains routines that are only called from within
  194065. * libpng itself during the course of reading an image.
  194066. */
  194067. #define PNG_INTERNAL
  194068. #if defined(PNG_READ_SUPPORTED)
  194069. #if defined(_WIN32_WCE) && (_WIN32_WCE<0x500)
  194070. # define WIN32_WCE_OLD
  194071. #endif
  194072. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194073. # if defined(WIN32_WCE_OLD)
  194074. /* strtod() function is not supported on WindowsCE */
  194075. __inline double png_strtod(png_structp png_ptr, PNG_CONST char *nptr, char **endptr)
  194076. {
  194077. double result = 0;
  194078. int len;
  194079. wchar_t *str, *end;
  194080. len = MultiByteToWideChar(CP_ACP, 0, nptr, -1, NULL, 0);
  194081. str = (wchar_t *)png_malloc(png_ptr, len * sizeof(wchar_t));
  194082. if ( NULL != str )
  194083. {
  194084. MultiByteToWideChar(CP_ACP, 0, nptr, -1, str, len);
  194085. result = wcstod(str, &end);
  194086. len = WideCharToMultiByte(CP_ACP, 0, end, -1, NULL, 0, NULL, NULL);
  194087. *endptr = (char *)nptr + (png_strlen(nptr) - len + 1);
  194088. png_free(png_ptr, str);
  194089. }
  194090. return result;
  194091. }
  194092. # else
  194093. # define png_strtod(p,a,b) strtod(a,b)
  194094. # endif
  194095. #endif
  194096. png_uint_32 PNGAPI
  194097. png_get_uint_31(png_structp png_ptr, png_bytep buf)
  194098. {
  194099. png_uint_32 i = png_get_uint_32(buf);
  194100. if (i > PNG_UINT_31_MAX)
  194101. png_error(png_ptr, "PNG unsigned integer out of range.");
  194102. return (i);
  194103. }
  194104. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  194105. /* Grab an unsigned 32-bit integer from a buffer in big-endian format. */
  194106. png_uint_32 PNGAPI
  194107. png_get_uint_32(png_bytep buf)
  194108. {
  194109. png_uint_32 i = ((png_uint_32)(*buf) << 24) +
  194110. ((png_uint_32)(*(buf + 1)) << 16) +
  194111. ((png_uint_32)(*(buf + 2)) << 8) +
  194112. (png_uint_32)(*(buf + 3));
  194113. return (i);
  194114. }
  194115. /* Grab a signed 32-bit integer from a buffer in big-endian format. The
  194116. * data is stored in the PNG file in two's complement format, and it is
  194117. * assumed that the machine format for signed integers is the same. */
  194118. png_int_32 PNGAPI
  194119. png_get_int_32(png_bytep buf)
  194120. {
  194121. png_int_32 i = ((png_int_32)(*buf) << 24) +
  194122. ((png_int_32)(*(buf + 1)) << 16) +
  194123. ((png_int_32)(*(buf + 2)) << 8) +
  194124. (png_int_32)(*(buf + 3));
  194125. return (i);
  194126. }
  194127. /* Grab an unsigned 16-bit integer from a buffer in big-endian format. */
  194128. png_uint_16 PNGAPI
  194129. png_get_uint_16(png_bytep buf)
  194130. {
  194131. png_uint_16 i = (png_uint_16)(((png_uint_16)(*buf) << 8) +
  194132. (png_uint_16)(*(buf + 1)));
  194133. return (i);
  194134. }
  194135. #endif /* PNG_READ_BIG_ENDIAN_SUPPORTED */
  194136. /* Read data, and (optionally) run it through the CRC. */
  194137. void /* PRIVATE */
  194138. png_crc_read(png_structp png_ptr, png_bytep buf, png_size_t length)
  194139. {
  194140. if(png_ptr == NULL) return;
  194141. png_read_data(png_ptr, buf, length);
  194142. png_calculate_crc(png_ptr, buf, length);
  194143. }
  194144. /* Optionally skip data and then check the CRC. Depending on whether we
  194145. are reading a ancillary or critical chunk, and how the program has set
  194146. things up, we may calculate the CRC on the data and print a message.
  194147. Returns '1' if there was a CRC error, '0' otherwise. */
  194148. int /* PRIVATE */
  194149. png_crc_finish(png_structp png_ptr, png_uint_32 skip)
  194150. {
  194151. png_size_t i;
  194152. png_size_t istop = png_ptr->zbuf_size;
  194153. for (i = (png_size_t)skip; i > istop; i -= istop)
  194154. {
  194155. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  194156. }
  194157. if (i)
  194158. {
  194159. png_crc_read(png_ptr, png_ptr->zbuf, i);
  194160. }
  194161. if (png_crc_error(png_ptr))
  194162. {
  194163. if (((png_ptr->chunk_name[0] & 0x20) && /* Ancillary */
  194164. !(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)) ||
  194165. (!(png_ptr->chunk_name[0] & 0x20) && /* Critical */
  194166. (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_USE)))
  194167. {
  194168. png_chunk_warning(png_ptr, "CRC error");
  194169. }
  194170. else
  194171. {
  194172. png_chunk_error(png_ptr, "CRC error");
  194173. }
  194174. return (1);
  194175. }
  194176. return (0);
  194177. }
  194178. /* Compare the CRC stored in the PNG file with that calculated by libpng from
  194179. the data it has read thus far. */
  194180. int /* PRIVATE */
  194181. png_crc_error(png_structp png_ptr)
  194182. {
  194183. png_byte crc_bytes[4];
  194184. png_uint_32 crc;
  194185. int need_crc = 1;
  194186. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  194187. {
  194188. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  194189. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  194190. need_crc = 0;
  194191. }
  194192. else /* critical */
  194193. {
  194194. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  194195. need_crc = 0;
  194196. }
  194197. png_read_data(png_ptr, crc_bytes, 4);
  194198. if (need_crc)
  194199. {
  194200. crc = png_get_uint_32(crc_bytes);
  194201. return ((int)(crc != png_ptr->crc));
  194202. }
  194203. else
  194204. return (0);
  194205. }
  194206. #if defined(PNG_READ_zTXt_SUPPORTED) || defined(PNG_READ_iTXt_SUPPORTED) || \
  194207. defined(PNG_READ_iCCP_SUPPORTED)
  194208. /*
  194209. * Decompress trailing data in a chunk. The assumption is that chunkdata
  194210. * points at an allocated area holding the contents of a chunk with a
  194211. * trailing compressed part. What we get back is an allocated area
  194212. * holding the original prefix part and an uncompressed version of the
  194213. * trailing part (the malloc area passed in is freed).
  194214. */
  194215. png_charp /* PRIVATE */
  194216. png_decompress_chunk(png_structp png_ptr, int comp_type,
  194217. png_charp chunkdata, png_size_t chunklength,
  194218. png_size_t prefix_size, png_size_t *newlength)
  194219. {
  194220. static PNG_CONST char msg[] = "Error decoding compressed text";
  194221. png_charp text;
  194222. png_size_t text_size;
  194223. if (comp_type == PNG_COMPRESSION_TYPE_BASE)
  194224. {
  194225. int ret = Z_OK;
  194226. png_ptr->zstream.next_in = (png_bytep)(chunkdata + prefix_size);
  194227. png_ptr->zstream.avail_in = (uInt)(chunklength - prefix_size);
  194228. png_ptr->zstream.next_out = png_ptr->zbuf;
  194229. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  194230. text_size = 0;
  194231. text = NULL;
  194232. while (png_ptr->zstream.avail_in)
  194233. {
  194234. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  194235. if (ret != Z_OK && ret != Z_STREAM_END)
  194236. {
  194237. if (png_ptr->zstream.msg != NULL)
  194238. png_warning(png_ptr, png_ptr->zstream.msg);
  194239. else
  194240. png_warning(png_ptr, msg);
  194241. inflateReset(&png_ptr->zstream);
  194242. png_ptr->zstream.avail_in = 0;
  194243. if (text == NULL)
  194244. {
  194245. text_size = prefix_size + png_sizeof(msg) + 1;
  194246. text = (png_charp)png_malloc_warn(png_ptr, text_size);
  194247. if (text == NULL)
  194248. {
  194249. png_free(png_ptr,chunkdata);
  194250. png_error(png_ptr,"Not enough memory to decompress chunk");
  194251. }
  194252. png_memcpy(text, chunkdata, prefix_size);
  194253. }
  194254. text[text_size - 1] = 0x00;
  194255. /* Copy what we can of the error message into the text chunk */
  194256. text_size = (png_size_t)(chunklength - (text - chunkdata) - 1);
  194257. text_size = png_sizeof(msg) > text_size ? text_size :
  194258. png_sizeof(msg);
  194259. png_memcpy(text + prefix_size, msg, text_size + 1);
  194260. break;
  194261. }
  194262. if (!png_ptr->zstream.avail_out || ret == Z_STREAM_END)
  194263. {
  194264. if (text == NULL)
  194265. {
  194266. text_size = prefix_size +
  194267. png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  194268. text = (png_charp)png_malloc_warn(png_ptr, text_size + 1);
  194269. if (text == NULL)
  194270. {
  194271. png_free(png_ptr,chunkdata);
  194272. png_error(png_ptr,"Not enough memory to decompress chunk.");
  194273. }
  194274. png_memcpy(text + prefix_size, png_ptr->zbuf,
  194275. text_size - prefix_size);
  194276. png_memcpy(text, chunkdata, prefix_size);
  194277. *(text + text_size) = 0x00;
  194278. }
  194279. else
  194280. {
  194281. png_charp tmp;
  194282. tmp = text;
  194283. text = (png_charp)png_malloc_warn(png_ptr,
  194284. (png_uint_32)(text_size +
  194285. png_ptr->zbuf_size - png_ptr->zstream.avail_out + 1));
  194286. if (text == NULL)
  194287. {
  194288. png_free(png_ptr, tmp);
  194289. png_free(png_ptr, chunkdata);
  194290. png_error(png_ptr,"Not enough memory to decompress chunk..");
  194291. }
  194292. png_memcpy(text, tmp, text_size);
  194293. png_free(png_ptr, tmp);
  194294. png_memcpy(text + text_size, png_ptr->zbuf,
  194295. (png_ptr->zbuf_size - png_ptr->zstream.avail_out));
  194296. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  194297. *(text + text_size) = 0x00;
  194298. }
  194299. if (ret == Z_STREAM_END)
  194300. break;
  194301. else
  194302. {
  194303. png_ptr->zstream.next_out = png_ptr->zbuf;
  194304. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  194305. }
  194306. }
  194307. }
  194308. if (ret != Z_STREAM_END)
  194309. {
  194310. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  194311. char umsg[52];
  194312. if (ret == Z_BUF_ERROR)
  194313. png_snprintf(umsg, 52,
  194314. "Buffer error in compressed datastream in %s chunk",
  194315. png_ptr->chunk_name);
  194316. else if (ret == Z_DATA_ERROR)
  194317. png_snprintf(umsg, 52,
  194318. "Data error in compressed datastream in %s chunk",
  194319. png_ptr->chunk_name);
  194320. else
  194321. png_snprintf(umsg, 52,
  194322. "Incomplete compressed datastream in %s chunk",
  194323. png_ptr->chunk_name);
  194324. png_warning(png_ptr, umsg);
  194325. #else
  194326. png_warning(png_ptr,
  194327. "Incomplete compressed datastream in chunk other than IDAT");
  194328. #endif
  194329. text_size=prefix_size;
  194330. if (text == NULL)
  194331. {
  194332. text = (png_charp)png_malloc_warn(png_ptr, text_size+1);
  194333. if (text == NULL)
  194334. {
  194335. png_free(png_ptr, chunkdata);
  194336. png_error(png_ptr,"Not enough memory for text.");
  194337. }
  194338. png_memcpy(text, chunkdata, prefix_size);
  194339. }
  194340. *(text + text_size) = 0x00;
  194341. }
  194342. inflateReset(&png_ptr->zstream);
  194343. png_ptr->zstream.avail_in = 0;
  194344. png_free(png_ptr, chunkdata);
  194345. chunkdata = text;
  194346. *newlength=text_size;
  194347. }
  194348. else /* if (comp_type != PNG_COMPRESSION_TYPE_BASE) */
  194349. {
  194350. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  194351. char umsg[50];
  194352. png_snprintf(umsg, 50,
  194353. "Unknown zTXt compression type %d", comp_type);
  194354. png_warning(png_ptr, umsg);
  194355. #else
  194356. png_warning(png_ptr, "Unknown zTXt compression type");
  194357. #endif
  194358. *(chunkdata + prefix_size) = 0x00;
  194359. *newlength=prefix_size;
  194360. }
  194361. return chunkdata;
  194362. }
  194363. #endif
  194364. /* read and check the IDHR chunk */
  194365. void /* PRIVATE */
  194366. png_handle_IHDR(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194367. {
  194368. png_byte buf[13];
  194369. png_uint_32 width, height;
  194370. int bit_depth, color_type, compression_type, filter_type;
  194371. int interlace_type;
  194372. png_debug(1, "in png_handle_IHDR\n");
  194373. if (png_ptr->mode & PNG_HAVE_IHDR)
  194374. png_error(png_ptr, "Out of place IHDR");
  194375. /* check the length */
  194376. if (length != 13)
  194377. png_error(png_ptr, "Invalid IHDR chunk");
  194378. png_ptr->mode |= PNG_HAVE_IHDR;
  194379. png_crc_read(png_ptr, buf, 13);
  194380. png_crc_finish(png_ptr, 0);
  194381. width = png_get_uint_31(png_ptr, buf);
  194382. height = png_get_uint_31(png_ptr, buf + 4);
  194383. bit_depth = buf[8];
  194384. color_type = buf[9];
  194385. compression_type = buf[10];
  194386. filter_type = buf[11];
  194387. interlace_type = buf[12];
  194388. /* set internal variables */
  194389. png_ptr->width = width;
  194390. png_ptr->height = height;
  194391. png_ptr->bit_depth = (png_byte)bit_depth;
  194392. png_ptr->interlaced = (png_byte)interlace_type;
  194393. png_ptr->color_type = (png_byte)color_type;
  194394. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  194395. png_ptr->filter_type = (png_byte)filter_type;
  194396. #endif
  194397. png_ptr->compression_type = (png_byte)compression_type;
  194398. /* find number of channels */
  194399. switch (png_ptr->color_type)
  194400. {
  194401. case PNG_COLOR_TYPE_GRAY:
  194402. case PNG_COLOR_TYPE_PALETTE:
  194403. png_ptr->channels = 1;
  194404. break;
  194405. case PNG_COLOR_TYPE_RGB:
  194406. png_ptr->channels = 3;
  194407. break;
  194408. case PNG_COLOR_TYPE_GRAY_ALPHA:
  194409. png_ptr->channels = 2;
  194410. break;
  194411. case PNG_COLOR_TYPE_RGB_ALPHA:
  194412. png_ptr->channels = 4;
  194413. break;
  194414. }
  194415. /* set up other useful info */
  194416. png_ptr->pixel_depth = (png_byte)(png_ptr->bit_depth *
  194417. png_ptr->channels);
  194418. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->width);
  194419. png_debug1(3,"bit_depth = %d\n", png_ptr->bit_depth);
  194420. png_debug1(3,"channels = %d\n", png_ptr->channels);
  194421. png_debug1(3,"rowbytes = %lu\n", png_ptr->rowbytes);
  194422. png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth,
  194423. color_type, interlace_type, compression_type, filter_type);
  194424. }
  194425. /* read and check the palette */
  194426. void /* PRIVATE */
  194427. png_handle_PLTE(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194428. {
  194429. png_color palette[PNG_MAX_PALETTE_LENGTH];
  194430. int num, i;
  194431. #ifndef PNG_NO_POINTER_INDEXING
  194432. png_colorp pal_ptr;
  194433. #endif
  194434. png_debug(1, "in png_handle_PLTE\n");
  194435. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194436. png_error(png_ptr, "Missing IHDR before PLTE");
  194437. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194438. {
  194439. png_warning(png_ptr, "Invalid PLTE after IDAT");
  194440. png_crc_finish(png_ptr, length);
  194441. return;
  194442. }
  194443. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194444. png_error(png_ptr, "Duplicate PLTE chunk");
  194445. png_ptr->mode |= PNG_HAVE_PLTE;
  194446. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  194447. {
  194448. png_warning(png_ptr,
  194449. "Ignoring PLTE chunk in grayscale PNG");
  194450. png_crc_finish(png_ptr, length);
  194451. return;
  194452. }
  194453. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  194454. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  194455. {
  194456. png_crc_finish(png_ptr, length);
  194457. return;
  194458. }
  194459. #endif
  194460. if (length > 3*PNG_MAX_PALETTE_LENGTH || length % 3)
  194461. {
  194462. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  194463. {
  194464. png_warning(png_ptr, "Invalid palette chunk");
  194465. png_crc_finish(png_ptr, length);
  194466. return;
  194467. }
  194468. else
  194469. {
  194470. png_error(png_ptr, "Invalid palette chunk");
  194471. }
  194472. }
  194473. num = (int)length / 3;
  194474. #ifndef PNG_NO_POINTER_INDEXING
  194475. for (i = 0, pal_ptr = palette; i < num; i++, pal_ptr++)
  194476. {
  194477. png_byte buf[3];
  194478. png_crc_read(png_ptr, buf, 3);
  194479. pal_ptr->red = buf[0];
  194480. pal_ptr->green = buf[1];
  194481. pal_ptr->blue = buf[2];
  194482. }
  194483. #else
  194484. for (i = 0; i < num; i++)
  194485. {
  194486. png_byte buf[3];
  194487. png_crc_read(png_ptr, buf, 3);
  194488. /* don't depend upon png_color being any order */
  194489. palette[i].red = buf[0];
  194490. palette[i].green = buf[1];
  194491. palette[i].blue = buf[2];
  194492. }
  194493. #endif
  194494. /* If we actually NEED the PLTE chunk (ie for a paletted image), we do
  194495. whatever the normal CRC configuration tells us. However, if we
  194496. have an RGB image, the PLTE can be considered ancillary, so
  194497. we will act as though it is. */
  194498. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  194499. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194500. #endif
  194501. {
  194502. png_crc_finish(png_ptr, 0);
  194503. }
  194504. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  194505. else if (png_crc_error(png_ptr)) /* Only if we have a CRC error */
  194506. {
  194507. /* If we don't want to use the data from an ancillary chunk,
  194508. we have two options: an error abort, or a warning and we
  194509. ignore the data in this chunk (which should be OK, since
  194510. it's considered ancillary for a RGB or RGBA image). */
  194511. if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_USE))
  194512. {
  194513. if (png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)
  194514. {
  194515. png_chunk_error(png_ptr, "CRC error");
  194516. }
  194517. else
  194518. {
  194519. png_chunk_warning(png_ptr, "CRC error");
  194520. return;
  194521. }
  194522. }
  194523. /* Otherwise, we (optionally) emit a warning and use the chunk. */
  194524. else if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN))
  194525. {
  194526. png_chunk_warning(png_ptr, "CRC error");
  194527. }
  194528. }
  194529. #endif
  194530. png_set_PLTE(png_ptr, info_ptr, palette, num);
  194531. #if defined(PNG_READ_tRNS_SUPPORTED)
  194532. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194533. {
  194534. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  194535. {
  194536. if (png_ptr->num_trans > (png_uint_16)num)
  194537. {
  194538. png_warning(png_ptr, "Truncating incorrect tRNS chunk length");
  194539. png_ptr->num_trans = (png_uint_16)num;
  194540. }
  194541. if (info_ptr->num_trans > (png_uint_16)num)
  194542. {
  194543. png_warning(png_ptr, "Truncating incorrect info tRNS chunk length");
  194544. info_ptr->num_trans = (png_uint_16)num;
  194545. }
  194546. }
  194547. }
  194548. #endif
  194549. }
  194550. void /* PRIVATE */
  194551. png_handle_IEND(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194552. {
  194553. png_debug(1, "in png_handle_IEND\n");
  194554. if (!(png_ptr->mode & PNG_HAVE_IHDR) || !(png_ptr->mode & PNG_HAVE_IDAT))
  194555. {
  194556. png_error(png_ptr, "No image in file");
  194557. }
  194558. png_ptr->mode |= (PNG_AFTER_IDAT | PNG_HAVE_IEND);
  194559. if (length != 0)
  194560. {
  194561. png_warning(png_ptr, "Incorrect IEND chunk length");
  194562. }
  194563. png_crc_finish(png_ptr, length);
  194564. info_ptr =info_ptr; /* quiet compiler warnings about unused info_ptr */
  194565. }
  194566. #if defined(PNG_READ_gAMA_SUPPORTED)
  194567. void /* PRIVATE */
  194568. png_handle_gAMA(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194569. {
  194570. png_fixed_point igamma;
  194571. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194572. float file_gamma;
  194573. #endif
  194574. png_byte buf[4];
  194575. png_debug(1, "in png_handle_gAMA\n");
  194576. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194577. png_error(png_ptr, "Missing IHDR before gAMA");
  194578. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194579. {
  194580. png_warning(png_ptr, "Invalid gAMA after IDAT");
  194581. png_crc_finish(png_ptr, length);
  194582. return;
  194583. }
  194584. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194585. /* Should be an error, but we can cope with it */
  194586. png_warning(png_ptr, "Out of place gAMA chunk");
  194587. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  194588. #if defined(PNG_READ_sRGB_SUPPORTED)
  194589. && !(info_ptr->valid & PNG_INFO_sRGB)
  194590. #endif
  194591. )
  194592. {
  194593. png_warning(png_ptr, "Duplicate gAMA chunk");
  194594. png_crc_finish(png_ptr, length);
  194595. return;
  194596. }
  194597. if (length != 4)
  194598. {
  194599. png_warning(png_ptr, "Incorrect gAMA chunk length");
  194600. png_crc_finish(png_ptr, length);
  194601. return;
  194602. }
  194603. png_crc_read(png_ptr, buf, 4);
  194604. if (png_crc_finish(png_ptr, 0))
  194605. return;
  194606. igamma = (png_fixed_point)png_get_uint_32(buf);
  194607. /* check for zero gamma */
  194608. if (igamma == 0)
  194609. {
  194610. png_warning(png_ptr,
  194611. "Ignoring gAMA chunk with gamma=0");
  194612. return;
  194613. }
  194614. #if defined(PNG_READ_sRGB_SUPPORTED)
  194615. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  194616. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  194617. {
  194618. png_warning(png_ptr,
  194619. "Ignoring incorrect gAMA value when sRGB is also present");
  194620. #ifndef PNG_NO_CONSOLE_IO
  194621. fprintf(stderr, "gamma = (%d/100000)\n", (int)igamma);
  194622. #endif
  194623. return;
  194624. }
  194625. #endif /* PNG_READ_sRGB_SUPPORTED */
  194626. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194627. file_gamma = (float)igamma / (float)100000.0;
  194628. # ifdef PNG_READ_GAMMA_SUPPORTED
  194629. png_ptr->gamma = file_gamma;
  194630. # endif
  194631. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  194632. #endif
  194633. #ifdef PNG_FIXED_POINT_SUPPORTED
  194634. png_set_gAMA_fixed(png_ptr, info_ptr, igamma);
  194635. #endif
  194636. }
  194637. #endif
  194638. #if defined(PNG_READ_sBIT_SUPPORTED)
  194639. void /* PRIVATE */
  194640. png_handle_sBIT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194641. {
  194642. png_size_t truelen;
  194643. png_byte buf[4];
  194644. png_debug(1, "in png_handle_sBIT\n");
  194645. buf[0] = buf[1] = buf[2] = buf[3] = 0;
  194646. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194647. png_error(png_ptr, "Missing IHDR before sBIT");
  194648. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194649. {
  194650. png_warning(png_ptr, "Invalid sBIT after IDAT");
  194651. png_crc_finish(png_ptr, length);
  194652. return;
  194653. }
  194654. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194655. {
  194656. /* Should be an error, but we can cope with it */
  194657. png_warning(png_ptr, "Out of place sBIT chunk");
  194658. }
  194659. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT))
  194660. {
  194661. png_warning(png_ptr, "Duplicate sBIT chunk");
  194662. png_crc_finish(png_ptr, length);
  194663. return;
  194664. }
  194665. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194666. truelen = 3;
  194667. else
  194668. truelen = (png_size_t)png_ptr->channels;
  194669. if (length != truelen || length > 4)
  194670. {
  194671. png_warning(png_ptr, "Incorrect sBIT chunk length");
  194672. png_crc_finish(png_ptr, length);
  194673. return;
  194674. }
  194675. png_crc_read(png_ptr, buf, truelen);
  194676. if (png_crc_finish(png_ptr, 0))
  194677. return;
  194678. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  194679. {
  194680. png_ptr->sig_bit.red = buf[0];
  194681. png_ptr->sig_bit.green = buf[1];
  194682. png_ptr->sig_bit.blue = buf[2];
  194683. png_ptr->sig_bit.alpha = buf[3];
  194684. }
  194685. else
  194686. {
  194687. png_ptr->sig_bit.gray = buf[0];
  194688. png_ptr->sig_bit.red = buf[0];
  194689. png_ptr->sig_bit.green = buf[0];
  194690. png_ptr->sig_bit.blue = buf[0];
  194691. png_ptr->sig_bit.alpha = buf[1];
  194692. }
  194693. png_set_sBIT(png_ptr, info_ptr, &(png_ptr->sig_bit));
  194694. }
  194695. #endif
  194696. #if defined(PNG_READ_cHRM_SUPPORTED)
  194697. void /* PRIVATE */
  194698. png_handle_cHRM(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194699. {
  194700. png_byte buf[4];
  194701. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194702. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  194703. #endif
  194704. png_fixed_point int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  194705. int_y_green, int_x_blue, int_y_blue;
  194706. png_uint_32 uint_x, uint_y;
  194707. png_debug(1, "in png_handle_cHRM\n");
  194708. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194709. png_error(png_ptr, "Missing IHDR before cHRM");
  194710. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194711. {
  194712. png_warning(png_ptr, "Invalid cHRM after IDAT");
  194713. png_crc_finish(png_ptr, length);
  194714. return;
  194715. }
  194716. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194717. /* Should be an error, but we can cope with it */
  194718. png_warning(png_ptr, "Missing PLTE before cHRM");
  194719. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM)
  194720. #if defined(PNG_READ_sRGB_SUPPORTED)
  194721. && !(info_ptr->valid & PNG_INFO_sRGB)
  194722. #endif
  194723. )
  194724. {
  194725. png_warning(png_ptr, "Duplicate cHRM chunk");
  194726. png_crc_finish(png_ptr, length);
  194727. return;
  194728. }
  194729. if (length != 32)
  194730. {
  194731. png_warning(png_ptr, "Incorrect cHRM chunk length");
  194732. png_crc_finish(png_ptr, length);
  194733. return;
  194734. }
  194735. png_crc_read(png_ptr, buf, 4);
  194736. uint_x = png_get_uint_32(buf);
  194737. png_crc_read(png_ptr, buf, 4);
  194738. uint_y = png_get_uint_32(buf);
  194739. if (uint_x > 80000L || uint_y > 80000L ||
  194740. uint_x + uint_y > 100000L)
  194741. {
  194742. png_warning(png_ptr, "Invalid cHRM white point");
  194743. png_crc_finish(png_ptr, 24);
  194744. return;
  194745. }
  194746. int_x_white = (png_fixed_point)uint_x;
  194747. int_y_white = (png_fixed_point)uint_y;
  194748. png_crc_read(png_ptr, buf, 4);
  194749. uint_x = png_get_uint_32(buf);
  194750. png_crc_read(png_ptr, buf, 4);
  194751. uint_y = png_get_uint_32(buf);
  194752. if (uint_x + uint_y > 100000L)
  194753. {
  194754. png_warning(png_ptr, "Invalid cHRM red point");
  194755. png_crc_finish(png_ptr, 16);
  194756. return;
  194757. }
  194758. int_x_red = (png_fixed_point)uint_x;
  194759. int_y_red = (png_fixed_point)uint_y;
  194760. png_crc_read(png_ptr, buf, 4);
  194761. uint_x = png_get_uint_32(buf);
  194762. png_crc_read(png_ptr, buf, 4);
  194763. uint_y = png_get_uint_32(buf);
  194764. if (uint_x + uint_y > 100000L)
  194765. {
  194766. png_warning(png_ptr, "Invalid cHRM green point");
  194767. png_crc_finish(png_ptr, 8);
  194768. return;
  194769. }
  194770. int_x_green = (png_fixed_point)uint_x;
  194771. int_y_green = (png_fixed_point)uint_y;
  194772. png_crc_read(png_ptr, buf, 4);
  194773. uint_x = png_get_uint_32(buf);
  194774. png_crc_read(png_ptr, buf, 4);
  194775. uint_y = png_get_uint_32(buf);
  194776. if (uint_x + uint_y > 100000L)
  194777. {
  194778. png_warning(png_ptr, "Invalid cHRM blue point");
  194779. png_crc_finish(png_ptr, 0);
  194780. return;
  194781. }
  194782. int_x_blue = (png_fixed_point)uint_x;
  194783. int_y_blue = (png_fixed_point)uint_y;
  194784. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194785. white_x = (float)int_x_white / (float)100000.0;
  194786. white_y = (float)int_y_white / (float)100000.0;
  194787. red_x = (float)int_x_red / (float)100000.0;
  194788. red_y = (float)int_y_red / (float)100000.0;
  194789. green_x = (float)int_x_green / (float)100000.0;
  194790. green_y = (float)int_y_green / (float)100000.0;
  194791. blue_x = (float)int_x_blue / (float)100000.0;
  194792. blue_y = (float)int_y_blue / (float)100000.0;
  194793. #endif
  194794. #if defined(PNG_READ_sRGB_SUPPORTED)
  194795. if ((info_ptr != NULL) && (info_ptr->valid & PNG_INFO_sRGB))
  194796. {
  194797. if (PNG_OUT_OF_RANGE(int_x_white, 31270, 1000) ||
  194798. PNG_OUT_OF_RANGE(int_y_white, 32900, 1000) ||
  194799. PNG_OUT_OF_RANGE(int_x_red, 64000L, 1000) ||
  194800. PNG_OUT_OF_RANGE(int_y_red, 33000, 1000) ||
  194801. PNG_OUT_OF_RANGE(int_x_green, 30000, 1000) ||
  194802. PNG_OUT_OF_RANGE(int_y_green, 60000L, 1000) ||
  194803. PNG_OUT_OF_RANGE(int_x_blue, 15000, 1000) ||
  194804. PNG_OUT_OF_RANGE(int_y_blue, 6000, 1000))
  194805. {
  194806. png_warning(png_ptr,
  194807. "Ignoring incorrect cHRM value when sRGB is also present");
  194808. #ifndef PNG_NO_CONSOLE_IO
  194809. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194810. fprintf(stderr,"wx=%f, wy=%f, rx=%f, ry=%f\n",
  194811. white_x, white_y, red_x, red_y);
  194812. fprintf(stderr,"gx=%f, gy=%f, bx=%f, by=%f\n",
  194813. green_x, green_y, blue_x, blue_y);
  194814. #else
  194815. fprintf(stderr,"wx=%ld, wy=%ld, rx=%ld, ry=%ld\n",
  194816. int_x_white, int_y_white, int_x_red, int_y_red);
  194817. fprintf(stderr,"gx=%ld, gy=%ld, bx=%ld, by=%ld\n",
  194818. int_x_green, int_y_green, int_x_blue, int_y_blue);
  194819. #endif
  194820. #endif /* PNG_NO_CONSOLE_IO */
  194821. }
  194822. png_crc_finish(png_ptr, 0);
  194823. return;
  194824. }
  194825. #endif /* PNG_READ_sRGB_SUPPORTED */
  194826. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194827. png_set_cHRM(png_ptr, info_ptr,
  194828. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  194829. #endif
  194830. #ifdef PNG_FIXED_POINT_SUPPORTED
  194831. png_set_cHRM_fixed(png_ptr, info_ptr,
  194832. int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  194833. int_y_green, int_x_blue, int_y_blue);
  194834. #endif
  194835. if (png_crc_finish(png_ptr, 0))
  194836. return;
  194837. }
  194838. #endif
  194839. #if defined(PNG_READ_sRGB_SUPPORTED)
  194840. void /* PRIVATE */
  194841. png_handle_sRGB(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194842. {
  194843. int intent;
  194844. png_byte buf[1];
  194845. png_debug(1, "in png_handle_sRGB\n");
  194846. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194847. png_error(png_ptr, "Missing IHDR before sRGB");
  194848. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194849. {
  194850. png_warning(png_ptr, "Invalid sRGB after IDAT");
  194851. png_crc_finish(png_ptr, length);
  194852. return;
  194853. }
  194854. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194855. /* Should be an error, but we can cope with it */
  194856. png_warning(png_ptr, "Out of place sRGB chunk");
  194857. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  194858. {
  194859. png_warning(png_ptr, "Duplicate sRGB chunk");
  194860. png_crc_finish(png_ptr, length);
  194861. return;
  194862. }
  194863. if (length != 1)
  194864. {
  194865. png_warning(png_ptr, "Incorrect sRGB chunk length");
  194866. png_crc_finish(png_ptr, length);
  194867. return;
  194868. }
  194869. png_crc_read(png_ptr, buf, 1);
  194870. if (png_crc_finish(png_ptr, 0))
  194871. return;
  194872. intent = buf[0];
  194873. /* check for bad intent */
  194874. if (intent >= PNG_sRGB_INTENT_LAST)
  194875. {
  194876. png_warning(png_ptr, "Unknown sRGB intent");
  194877. return;
  194878. }
  194879. #if defined(PNG_READ_gAMA_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  194880. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA))
  194881. {
  194882. png_fixed_point igamma;
  194883. #ifdef PNG_FIXED_POINT_SUPPORTED
  194884. igamma=info_ptr->int_gamma;
  194885. #else
  194886. # ifdef PNG_FLOATING_POINT_SUPPORTED
  194887. igamma=(png_fixed_point)(info_ptr->gamma * 100000.);
  194888. # endif
  194889. #endif
  194890. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  194891. {
  194892. png_warning(png_ptr,
  194893. "Ignoring incorrect gAMA value when sRGB is also present");
  194894. #ifndef PNG_NO_CONSOLE_IO
  194895. # ifdef PNG_FIXED_POINT_SUPPORTED
  194896. fprintf(stderr,"incorrect gamma=(%d/100000)\n",(int)png_ptr->int_gamma);
  194897. # else
  194898. # ifdef PNG_FLOATING_POINT_SUPPORTED
  194899. fprintf(stderr,"incorrect gamma=%f\n",png_ptr->gamma);
  194900. # endif
  194901. # endif
  194902. #endif
  194903. }
  194904. }
  194905. #endif /* PNG_READ_gAMA_SUPPORTED */
  194906. #ifdef PNG_READ_cHRM_SUPPORTED
  194907. #ifdef PNG_FIXED_POINT_SUPPORTED
  194908. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  194909. if (PNG_OUT_OF_RANGE(info_ptr->int_x_white, 31270, 1000) ||
  194910. PNG_OUT_OF_RANGE(info_ptr->int_y_white, 32900, 1000) ||
  194911. PNG_OUT_OF_RANGE(info_ptr->int_x_red, 64000L, 1000) ||
  194912. PNG_OUT_OF_RANGE(info_ptr->int_y_red, 33000, 1000) ||
  194913. PNG_OUT_OF_RANGE(info_ptr->int_x_green, 30000, 1000) ||
  194914. PNG_OUT_OF_RANGE(info_ptr->int_y_green, 60000L, 1000) ||
  194915. PNG_OUT_OF_RANGE(info_ptr->int_x_blue, 15000, 1000) ||
  194916. PNG_OUT_OF_RANGE(info_ptr->int_y_blue, 6000, 1000))
  194917. {
  194918. png_warning(png_ptr,
  194919. "Ignoring incorrect cHRM value when sRGB is also present");
  194920. }
  194921. #endif /* PNG_FIXED_POINT_SUPPORTED */
  194922. #endif /* PNG_READ_cHRM_SUPPORTED */
  194923. png_set_sRGB_gAMA_and_cHRM(png_ptr, info_ptr, intent);
  194924. }
  194925. #endif /* PNG_READ_sRGB_SUPPORTED */
  194926. #if defined(PNG_READ_iCCP_SUPPORTED)
  194927. void /* PRIVATE */
  194928. png_handle_iCCP(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194929. /* Note: this does not properly handle chunks that are > 64K under DOS */
  194930. {
  194931. png_charp chunkdata;
  194932. png_byte compression_type;
  194933. png_bytep pC;
  194934. png_charp profile;
  194935. png_uint_32 skip = 0;
  194936. png_uint_32 profile_size, profile_length;
  194937. png_size_t slength, prefix_length, data_length;
  194938. png_debug(1, "in png_handle_iCCP\n");
  194939. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194940. png_error(png_ptr, "Missing IHDR before iCCP");
  194941. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194942. {
  194943. png_warning(png_ptr, "Invalid iCCP after IDAT");
  194944. png_crc_finish(png_ptr, length);
  194945. return;
  194946. }
  194947. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194948. /* Should be an error, but we can cope with it */
  194949. png_warning(png_ptr, "Out of place iCCP chunk");
  194950. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP))
  194951. {
  194952. png_warning(png_ptr, "Duplicate iCCP chunk");
  194953. png_crc_finish(png_ptr, length);
  194954. return;
  194955. }
  194956. #ifdef PNG_MAX_MALLOC_64K
  194957. if (length > (png_uint_32)65535L)
  194958. {
  194959. png_warning(png_ptr, "iCCP chunk too large to fit in memory");
  194960. skip = length - (png_uint_32)65535L;
  194961. length = (png_uint_32)65535L;
  194962. }
  194963. #endif
  194964. chunkdata = (png_charp)png_malloc(png_ptr, length + 1);
  194965. slength = (png_size_t)length;
  194966. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  194967. if (png_crc_finish(png_ptr, skip))
  194968. {
  194969. png_free(png_ptr, chunkdata);
  194970. return;
  194971. }
  194972. chunkdata[slength] = 0x00;
  194973. for (profile = chunkdata; *profile; profile++)
  194974. /* empty loop to find end of name */ ;
  194975. ++profile;
  194976. /* there should be at least one zero (the compression type byte)
  194977. following the separator, and we should be on it */
  194978. if ( profile >= chunkdata + slength - 1)
  194979. {
  194980. png_free(png_ptr, chunkdata);
  194981. png_warning(png_ptr, "Malformed iCCP chunk");
  194982. return;
  194983. }
  194984. /* compression_type should always be zero */
  194985. compression_type = *profile++;
  194986. if (compression_type)
  194987. {
  194988. png_warning(png_ptr, "Ignoring nonzero compression type in iCCP chunk");
  194989. compression_type=0x00; /* Reset it to zero (libpng-1.0.6 through 1.0.8
  194990. wrote nonzero) */
  194991. }
  194992. prefix_length = profile - chunkdata;
  194993. chunkdata = png_decompress_chunk(png_ptr, compression_type, chunkdata,
  194994. slength, prefix_length, &data_length);
  194995. profile_length = data_length - prefix_length;
  194996. if ( prefix_length > data_length || profile_length < 4)
  194997. {
  194998. png_free(png_ptr, chunkdata);
  194999. png_warning(png_ptr, "Profile size field missing from iCCP chunk");
  195000. return;
  195001. }
  195002. /* Check the profile_size recorded in the first 32 bits of the ICC profile */
  195003. pC = (png_bytep)(chunkdata+prefix_length);
  195004. profile_size = ((*(pC ))<<24) |
  195005. ((*(pC+1))<<16) |
  195006. ((*(pC+2))<< 8) |
  195007. ((*(pC+3)) );
  195008. if(profile_size < profile_length)
  195009. profile_length = profile_size;
  195010. if(profile_size > profile_length)
  195011. {
  195012. png_free(png_ptr, chunkdata);
  195013. png_warning(png_ptr, "Ignoring truncated iCCP profile.");
  195014. return;
  195015. }
  195016. png_set_iCCP(png_ptr, info_ptr, chunkdata, compression_type,
  195017. chunkdata + prefix_length, profile_length);
  195018. png_free(png_ptr, chunkdata);
  195019. }
  195020. #endif /* PNG_READ_iCCP_SUPPORTED */
  195021. #if defined(PNG_READ_sPLT_SUPPORTED)
  195022. void /* PRIVATE */
  195023. png_handle_sPLT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195024. /* Note: this does not properly handle chunks that are > 64K under DOS */
  195025. {
  195026. png_bytep chunkdata;
  195027. png_bytep entry_start;
  195028. png_sPLT_t new_palette;
  195029. #ifdef PNG_NO_POINTER_INDEXING
  195030. png_sPLT_entryp pp;
  195031. #endif
  195032. int data_length, entry_size, i;
  195033. png_uint_32 skip = 0;
  195034. png_size_t slength;
  195035. png_debug(1, "in png_handle_sPLT\n");
  195036. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195037. png_error(png_ptr, "Missing IHDR before sPLT");
  195038. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195039. {
  195040. png_warning(png_ptr, "Invalid sPLT after IDAT");
  195041. png_crc_finish(png_ptr, length);
  195042. return;
  195043. }
  195044. #ifdef PNG_MAX_MALLOC_64K
  195045. if (length > (png_uint_32)65535L)
  195046. {
  195047. png_warning(png_ptr, "sPLT chunk too large to fit in memory");
  195048. skip = length - (png_uint_32)65535L;
  195049. length = (png_uint_32)65535L;
  195050. }
  195051. #endif
  195052. chunkdata = (png_bytep)png_malloc(png_ptr, length + 1);
  195053. slength = (png_size_t)length;
  195054. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  195055. if (png_crc_finish(png_ptr, skip))
  195056. {
  195057. png_free(png_ptr, chunkdata);
  195058. return;
  195059. }
  195060. chunkdata[slength] = 0x00;
  195061. for (entry_start = chunkdata; *entry_start; entry_start++)
  195062. /* empty loop to find end of name */ ;
  195063. ++entry_start;
  195064. /* a sample depth should follow the separator, and we should be on it */
  195065. if (entry_start > chunkdata + slength - 2)
  195066. {
  195067. png_free(png_ptr, chunkdata);
  195068. png_warning(png_ptr, "malformed sPLT chunk");
  195069. return;
  195070. }
  195071. new_palette.depth = *entry_start++;
  195072. entry_size = (new_palette.depth == 8 ? 6 : 10);
  195073. data_length = (slength - (entry_start - chunkdata));
  195074. /* integrity-check the data length */
  195075. if (data_length % entry_size)
  195076. {
  195077. png_free(png_ptr, chunkdata);
  195078. png_warning(png_ptr, "sPLT chunk has bad length");
  195079. return;
  195080. }
  195081. new_palette.nentries = (png_int_32) ( data_length / entry_size);
  195082. if ((png_uint_32) new_palette.nentries > (png_uint_32) (PNG_SIZE_MAX /
  195083. png_sizeof(png_sPLT_entry)))
  195084. {
  195085. png_warning(png_ptr, "sPLT chunk too long");
  195086. return;
  195087. }
  195088. new_palette.entries = (png_sPLT_entryp)png_malloc_warn(
  195089. png_ptr, new_palette.nentries * png_sizeof(png_sPLT_entry));
  195090. if (new_palette.entries == NULL)
  195091. {
  195092. png_warning(png_ptr, "sPLT chunk requires too much memory");
  195093. return;
  195094. }
  195095. #ifndef PNG_NO_POINTER_INDEXING
  195096. for (i = 0; i < new_palette.nentries; i++)
  195097. {
  195098. png_sPLT_entryp pp = new_palette.entries + i;
  195099. if (new_palette.depth == 8)
  195100. {
  195101. pp->red = *entry_start++;
  195102. pp->green = *entry_start++;
  195103. pp->blue = *entry_start++;
  195104. pp->alpha = *entry_start++;
  195105. }
  195106. else
  195107. {
  195108. pp->red = png_get_uint_16(entry_start); entry_start += 2;
  195109. pp->green = png_get_uint_16(entry_start); entry_start += 2;
  195110. pp->blue = png_get_uint_16(entry_start); entry_start += 2;
  195111. pp->alpha = png_get_uint_16(entry_start); entry_start += 2;
  195112. }
  195113. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  195114. }
  195115. #else
  195116. pp = new_palette.entries;
  195117. for (i = 0; i < new_palette.nentries; i++)
  195118. {
  195119. if (new_palette.depth == 8)
  195120. {
  195121. pp[i].red = *entry_start++;
  195122. pp[i].green = *entry_start++;
  195123. pp[i].blue = *entry_start++;
  195124. pp[i].alpha = *entry_start++;
  195125. }
  195126. else
  195127. {
  195128. pp[i].red = png_get_uint_16(entry_start); entry_start += 2;
  195129. pp[i].green = png_get_uint_16(entry_start); entry_start += 2;
  195130. pp[i].blue = png_get_uint_16(entry_start); entry_start += 2;
  195131. pp[i].alpha = png_get_uint_16(entry_start); entry_start += 2;
  195132. }
  195133. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  195134. }
  195135. #endif
  195136. /* discard all chunk data except the name and stash that */
  195137. new_palette.name = (png_charp)chunkdata;
  195138. png_set_sPLT(png_ptr, info_ptr, &new_palette, 1);
  195139. png_free(png_ptr, chunkdata);
  195140. png_free(png_ptr, new_palette.entries);
  195141. }
  195142. #endif /* PNG_READ_sPLT_SUPPORTED */
  195143. #if defined(PNG_READ_tRNS_SUPPORTED)
  195144. void /* PRIVATE */
  195145. png_handle_tRNS(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195146. {
  195147. png_byte readbuf[PNG_MAX_PALETTE_LENGTH];
  195148. int bit_mask;
  195149. png_debug(1, "in png_handle_tRNS\n");
  195150. /* For non-indexed color, mask off any bits in the tRNS value that
  195151. * exceed the bit depth. Some creators were writing extra bits there.
  195152. * This is not needed for indexed color. */
  195153. bit_mask = (1 << png_ptr->bit_depth) - 1;
  195154. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195155. png_error(png_ptr, "Missing IHDR before tRNS");
  195156. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195157. {
  195158. png_warning(png_ptr, "Invalid tRNS after IDAT");
  195159. png_crc_finish(png_ptr, length);
  195160. return;
  195161. }
  195162. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  195163. {
  195164. png_warning(png_ptr, "Duplicate tRNS chunk");
  195165. png_crc_finish(png_ptr, length);
  195166. return;
  195167. }
  195168. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  195169. {
  195170. png_byte buf[2];
  195171. if (length != 2)
  195172. {
  195173. png_warning(png_ptr, "Incorrect tRNS chunk length");
  195174. png_crc_finish(png_ptr, length);
  195175. return;
  195176. }
  195177. png_crc_read(png_ptr, buf, 2);
  195178. png_ptr->num_trans = 1;
  195179. png_ptr->trans_values.gray = png_get_uint_16(buf) & bit_mask;
  195180. }
  195181. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  195182. {
  195183. png_byte buf[6];
  195184. if (length != 6)
  195185. {
  195186. png_warning(png_ptr, "Incorrect tRNS chunk length");
  195187. png_crc_finish(png_ptr, length);
  195188. return;
  195189. }
  195190. png_crc_read(png_ptr, buf, (png_size_t)length);
  195191. png_ptr->num_trans = 1;
  195192. png_ptr->trans_values.red = png_get_uint_16(buf) & bit_mask;
  195193. png_ptr->trans_values.green = png_get_uint_16(buf + 2) & bit_mask;
  195194. png_ptr->trans_values.blue = png_get_uint_16(buf + 4) & bit_mask;
  195195. }
  195196. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195197. {
  195198. if (!(png_ptr->mode & PNG_HAVE_PLTE))
  195199. {
  195200. /* Should be an error, but we can cope with it. */
  195201. png_warning(png_ptr, "Missing PLTE before tRNS");
  195202. }
  195203. if (length > (png_uint_32)png_ptr->num_palette ||
  195204. length > PNG_MAX_PALETTE_LENGTH)
  195205. {
  195206. png_warning(png_ptr, "Incorrect tRNS chunk length");
  195207. png_crc_finish(png_ptr, length);
  195208. return;
  195209. }
  195210. if (length == 0)
  195211. {
  195212. png_warning(png_ptr, "Zero length tRNS chunk");
  195213. png_crc_finish(png_ptr, length);
  195214. return;
  195215. }
  195216. png_crc_read(png_ptr, readbuf, (png_size_t)length);
  195217. png_ptr->num_trans = (png_uint_16)length;
  195218. }
  195219. else
  195220. {
  195221. png_warning(png_ptr, "tRNS chunk not allowed with alpha channel");
  195222. png_crc_finish(png_ptr, length);
  195223. return;
  195224. }
  195225. if (png_crc_finish(png_ptr, 0))
  195226. {
  195227. png_ptr->num_trans = 0;
  195228. return;
  195229. }
  195230. png_set_tRNS(png_ptr, info_ptr, readbuf, png_ptr->num_trans,
  195231. &(png_ptr->trans_values));
  195232. }
  195233. #endif
  195234. #if defined(PNG_READ_bKGD_SUPPORTED)
  195235. void /* PRIVATE */
  195236. png_handle_bKGD(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195237. {
  195238. png_size_t truelen;
  195239. png_byte buf[6];
  195240. png_debug(1, "in png_handle_bKGD\n");
  195241. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195242. png_error(png_ptr, "Missing IHDR before bKGD");
  195243. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195244. {
  195245. png_warning(png_ptr, "Invalid bKGD after IDAT");
  195246. png_crc_finish(png_ptr, length);
  195247. return;
  195248. }
  195249. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  195250. !(png_ptr->mode & PNG_HAVE_PLTE))
  195251. {
  195252. png_warning(png_ptr, "Missing PLTE before bKGD");
  195253. png_crc_finish(png_ptr, length);
  195254. return;
  195255. }
  195256. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD))
  195257. {
  195258. png_warning(png_ptr, "Duplicate bKGD chunk");
  195259. png_crc_finish(png_ptr, length);
  195260. return;
  195261. }
  195262. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195263. truelen = 1;
  195264. else if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  195265. truelen = 6;
  195266. else
  195267. truelen = 2;
  195268. if (length != truelen)
  195269. {
  195270. png_warning(png_ptr, "Incorrect bKGD chunk length");
  195271. png_crc_finish(png_ptr, length);
  195272. return;
  195273. }
  195274. png_crc_read(png_ptr, buf, truelen);
  195275. if (png_crc_finish(png_ptr, 0))
  195276. return;
  195277. /* We convert the index value into RGB components so that we can allow
  195278. * arbitrary RGB values for background when we have transparency, and
  195279. * so it is easy to determine the RGB values of the background color
  195280. * from the info_ptr struct. */
  195281. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195282. {
  195283. png_ptr->background.index = buf[0];
  195284. if(info_ptr->num_palette)
  195285. {
  195286. if(buf[0] > info_ptr->num_palette)
  195287. {
  195288. png_warning(png_ptr, "Incorrect bKGD chunk index value");
  195289. return;
  195290. }
  195291. png_ptr->background.red =
  195292. (png_uint_16)png_ptr->palette[buf[0]].red;
  195293. png_ptr->background.green =
  195294. (png_uint_16)png_ptr->palette[buf[0]].green;
  195295. png_ptr->background.blue =
  195296. (png_uint_16)png_ptr->palette[buf[0]].blue;
  195297. }
  195298. }
  195299. else if (!(png_ptr->color_type & PNG_COLOR_MASK_COLOR)) /* GRAY */
  195300. {
  195301. png_ptr->background.red =
  195302. png_ptr->background.green =
  195303. png_ptr->background.blue =
  195304. png_ptr->background.gray = png_get_uint_16(buf);
  195305. }
  195306. else
  195307. {
  195308. png_ptr->background.red = png_get_uint_16(buf);
  195309. png_ptr->background.green = png_get_uint_16(buf + 2);
  195310. png_ptr->background.blue = png_get_uint_16(buf + 4);
  195311. }
  195312. png_set_bKGD(png_ptr, info_ptr, &(png_ptr->background));
  195313. }
  195314. #endif
  195315. #if defined(PNG_READ_hIST_SUPPORTED)
  195316. void /* PRIVATE */
  195317. png_handle_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195318. {
  195319. unsigned int num, i;
  195320. png_uint_16 readbuf[PNG_MAX_PALETTE_LENGTH];
  195321. png_debug(1, "in png_handle_hIST\n");
  195322. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195323. png_error(png_ptr, "Missing IHDR before hIST");
  195324. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195325. {
  195326. png_warning(png_ptr, "Invalid hIST after IDAT");
  195327. png_crc_finish(png_ptr, length);
  195328. return;
  195329. }
  195330. else if (!(png_ptr->mode & PNG_HAVE_PLTE))
  195331. {
  195332. png_warning(png_ptr, "Missing PLTE before hIST");
  195333. png_crc_finish(png_ptr, length);
  195334. return;
  195335. }
  195336. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST))
  195337. {
  195338. png_warning(png_ptr, "Duplicate hIST chunk");
  195339. png_crc_finish(png_ptr, length);
  195340. return;
  195341. }
  195342. num = length / 2 ;
  195343. if (num != (unsigned int) png_ptr->num_palette || num >
  195344. (unsigned int) PNG_MAX_PALETTE_LENGTH)
  195345. {
  195346. png_warning(png_ptr, "Incorrect hIST chunk length");
  195347. png_crc_finish(png_ptr, length);
  195348. return;
  195349. }
  195350. for (i = 0; i < num; i++)
  195351. {
  195352. png_byte buf[2];
  195353. png_crc_read(png_ptr, buf, 2);
  195354. readbuf[i] = png_get_uint_16(buf);
  195355. }
  195356. if (png_crc_finish(png_ptr, 0))
  195357. return;
  195358. png_set_hIST(png_ptr, info_ptr, readbuf);
  195359. }
  195360. #endif
  195361. #if defined(PNG_READ_pHYs_SUPPORTED)
  195362. void /* PRIVATE */
  195363. png_handle_pHYs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195364. {
  195365. png_byte buf[9];
  195366. png_uint_32 res_x, res_y;
  195367. int unit_type;
  195368. png_debug(1, "in png_handle_pHYs\n");
  195369. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195370. png_error(png_ptr, "Missing IHDR before pHYs");
  195371. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195372. {
  195373. png_warning(png_ptr, "Invalid pHYs after IDAT");
  195374. png_crc_finish(png_ptr, length);
  195375. return;
  195376. }
  195377. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  195378. {
  195379. png_warning(png_ptr, "Duplicate pHYs chunk");
  195380. png_crc_finish(png_ptr, length);
  195381. return;
  195382. }
  195383. if (length != 9)
  195384. {
  195385. png_warning(png_ptr, "Incorrect pHYs chunk length");
  195386. png_crc_finish(png_ptr, length);
  195387. return;
  195388. }
  195389. png_crc_read(png_ptr, buf, 9);
  195390. if (png_crc_finish(png_ptr, 0))
  195391. return;
  195392. res_x = png_get_uint_32(buf);
  195393. res_y = png_get_uint_32(buf + 4);
  195394. unit_type = buf[8];
  195395. png_set_pHYs(png_ptr, info_ptr, res_x, res_y, unit_type);
  195396. }
  195397. #endif
  195398. #if defined(PNG_READ_oFFs_SUPPORTED)
  195399. void /* PRIVATE */
  195400. png_handle_oFFs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195401. {
  195402. png_byte buf[9];
  195403. png_int_32 offset_x, offset_y;
  195404. int unit_type;
  195405. png_debug(1, "in png_handle_oFFs\n");
  195406. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195407. png_error(png_ptr, "Missing IHDR before oFFs");
  195408. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195409. {
  195410. png_warning(png_ptr, "Invalid oFFs after IDAT");
  195411. png_crc_finish(png_ptr, length);
  195412. return;
  195413. }
  195414. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs))
  195415. {
  195416. png_warning(png_ptr, "Duplicate oFFs chunk");
  195417. png_crc_finish(png_ptr, length);
  195418. return;
  195419. }
  195420. if (length != 9)
  195421. {
  195422. png_warning(png_ptr, "Incorrect oFFs chunk length");
  195423. png_crc_finish(png_ptr, length);
  195424. return;
  195425. }
  195426. png_crc_read(png_ptr, buf, 9);
  195427. if (png_crc_finish(png_ptr, 0))
  195428. return;
  195429. offset_x = png_get_int_32(buf);
  195430. offset_y = png_get_int_32(buf + 4);
  195431. unit_type = buf[8];
  195432. png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y, unit_type);
  195433. }
  195434. #endif
  195435. #if defined(PNG_READ_pCAL_SUPPORTED)
  195436. /* read the pCAL chunk (described in the PNG Extensions document) */
  195437. void /* PRIVATE */
  195438. png_handle_pCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195439. {
  195440. png_charp purpose;
  195441. png_int_32 X0, X1;
  195442. png_byte type, nparams;
  195443. png_charp buf, units, endptr;
  195444. png_charpp params;
  195445. png_size_t slength;
  195446. int i;
  195447. png_debug(1, "in png_handle_pCAL\n");
  195448. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195449. png_error(png_ptr, "Missing IHDR before pCAL");
  195450. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195451. {
  195452. png_warning(png_ptr, "Invalid pCAL after IDAT");
  195453. png_crc_finish(png_ptr, length);
  195454. return;
  195455. }
  195456. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL))
  195457. {
  195458. png_warning(png_ptr, "Duplicate pCAL chunk");
  195459. png_crc_finish(png_ptr, length);
  195460. return;
  195461. }
  195462. png_debug1(2, "Allocating and reading pCAL chunk data (%lu bytes)\n",
  195463. length + 1);
  195464. purpose = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195465. if (purpose == NULL)
  195466. {
  195467. png_warning(png_ptr, "No memory for pCAL purpose.");
  195468. return;
  195469. }
  195470. slength = (png_size_t)length;
  195471. png_crc_read(png_ptr, (png_bytep)purpose, slength);
  195472. if (png_crc_finish(png_ptr, 0))
  195473. {
  195474. png_free(png_ptr, purpose);
  195475. return;
  195476. }
  195477. purpose[slength] = 0x00; /* null terminate the last string */
  195478. png_debug(3, "Finding end of pCAL purpose string\n");
  195479. for (buf = purpose; *buf; buf++)
  195480. /* empty loop */ ;
  195481. endptr = purpose + slength;
  195482. /* We need to have at least 12 bytes after the purpose string
  195483. in order to get the parameter information. */
  195484. if (endptr <= buf + 12)
  195485. {
  195486. png_warning(png_ptr, "Invalid pCAL data");
  195487. png_free(png_ptr, purpose);
  195488. return;
  195489. }
  195490. png_debug(3, "Reading pCAL X0, X1, type, nparams, and units\n");
  195491. X0 = png_get_int_32((png_bytep)buf+1);
  195492. X1 = png_get_int_32((png_bytep)buf+5);
  195493. type = buf[9];
  195494. nparams = buf[10];
  195495. units = buf + 11;
  195496. png_debug(3, "Checking pCAL equation type and number of parameters\n");
  195497. /* Check that we have the right number of parameters for known
  195498. equation types. */
  195499. if ((type == PNG_EQUATION_LINEAR && nparams != 2) ||
  195500. (type == PNG_EQUATION_BASE_E && nparams != 3) ||
  195501. (type == PNG_EQUATION_ARBITRARY && nparams != 3) ||
  195502. (type == PNG_EQUATION_HYPERBOLIC && nparams != 4))
  195503. {
  195504. png_warning(png_ptr, "Invalid pCAL parameters for equation type");
  195505. png_free(png_ptr, purpose);
  195506. return;
  195507. }
  195508. else if (type >= PNG_EQUATION_LAST)
  195509. {
  195510. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  195511. }
  195512. for (buf = units; *buf; buf++)
  195513. /* Empty loop to move past the units string. */ ;
  195514. png_debug(3, "Allocating pCAL parameters array\n");
  195515. params = (png_charpp)png_malloc_warn(png_ptr, (png_uint_32)(nparams
  195516. *png_sizeof(png_charp))) ;
  195517. if (params == NULL)
  195518. {
  195519. png_free(png_ptr, purpose);
  195520. png_warning(png_ptr, "No memory for pCAL params.");
  195521. return;
  195522. }
  195523. /* Get pointers to the start of each parameter string. */
  195524. for (i = 0; i < (int)nparams; i++)
  195525. {
  195526. buf++; /* Skip the null string terminator from previous parameter. */
  195527. png_debug1(3, "Reading pCAL parameter %d\n", i);
  195528. for (params[i] = buf; buf <= endptr && *buf != 0x00; buf++)
  195529. /* Empty loop to move past each parameter string */ ;
  195530. /* Make sure we haven't run out of data yet */
  195531. if (buf > endptr)
  195532. {
  195533. png_warning(png_ptr, "Invalid pCAL data");
  195534. png_free(png_ptr, purpose);
  195535. png_free(png_ptr, params);
  195536. return;
  195537. }
  195538. }
  195539. png_set_pCAL(png_ptr, info_ptr, purpose, X0, X1, type, nparams,
  195540. units, params);
  195541. png_free(png_ptr, purpose);
  195542. png_free(png_ptr, params);
  195543. }
  195544. #endif
  195545. #if defined(PNG_READ_sCAL_SUPPORTED)
  195546. /* read the sCAL chunk */
  195547. void /* PRIVATE */
  195548. png_handle_sCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195549. {
  195550. png_charp buffer, ep;
  195551. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195552. double width, height;
  195553. png_charp vp;
  195554. #else
  195555. #ifdef PNG_FIXED_POINT_SUPPORTED
  195556. png_charp swidth, sheight;
  195557. #endif
  195558. #endif
  195559. png_size_t slength;
  195560. png_debug(1, "in png_handle_sCAL\n");
  195561. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195562. png_error(png_ptr, "Missing IHDR before sCAL");
  195563. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195564. {
  195565. png_warning(png_ptr, "Invalid sCAL after IDAT");
  195566. png_crc_finish(png_ptr, length);
  195567. return;
  195568. }
  195569. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sCAL))
  195570. {
  195571. png_warning(png_ptr, "Duplicate sCAL chunk");
  195572. png_crc_finish(png_ptr, length);
  195573. return;
  195574. }
  195575. png_debug1(2, "Allocating and reading sCAL chunk data (%lu bytes)\n",
  195576. length + 1);
  195577. buffer = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195578. if (buffer == NULL)
  195579. {
  195580. png_warning(png_ptr, "Out of memory while processing sCAL chunk");
  195581. return;
  195582. }
  195583. slength = (png_size_t)length;
  195584. png_crc_read(png_ptr, (png_bytep)buffer, slength);
  195585. if (png_crc_finish(png_ptr, 0))
  195586. {
  195587. png_free(png_ptr, buffer);
  195588. return;
  195589. }
  195590. buffer[slength] = 0x00; /* null terminate the last string */
  195591. ep = buffer + 1; /* skip unit byte */
  195592. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195593. width = png_strtod(png_ptr, ep, &vp);
  195594. if (*vp)
  195595. {
  195596. png_warning(png_ptr, "malformed width string in sCAL chunk");
  195597. return;
  195598. }
  195599. #else
  195600. #ifdef PNG_FIXED_POINT_SUPPORTED
  195601. swidth = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  195602. if (swidth == NULL)
  195603. {
  195604. png_warning(png_ptr, "Out of memory while processing sCAL chunk width");
  195605. return;
  195606. }
  195607. png_memcpy(swidth, ep, (png_size_t)png_strlen(ep));
  195608. #endif
  195609. #endif
  195610. for (ep = buffer; *ep; ep++)
  195611. /* empty loop */ ;
  195612. ep++;
  195613. if (buffer + slength < ep)
  195614. {
  195615. png_warning(png_ptr, "Truncated sCAL chunk");
  195616. #if defined(PNG_FIXED_POINT_SUPPORTED) && \
  195617. !defined(PNG_FLOATING_POINT_SUPPORTED)
  195618. png_free(png_ptr, swidth);
  195619. #endif
  195620. png_free(png_ptr, buffer);
  195621. return;
  195622. }
  195623. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195624. height = png_strtod(png_ptr, ep, &vp);
  195625. if (*vp)
  195626. {
  195627. png_warning(png_ptr, "malformed height string in sCAL chunk");
  195628. return;
  195629. }
  195630. #else
  195631. #ifdef PNG_FIXED_POINT_SUPPORTED
  195632. sheight = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  195633. if (swidth == NULL)
  195634. {
  195635. png_warning(png_ptr, "Out of memory while processing sCAL chunk height");
  195636. return;
  195637. }
  195638. png_memcpy(sheight, ep, (png_size_t)png_strlen(ep));
  195639. #endif
  195640. #endif
  195641. if (buffer + slength < ep
  195642. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195643. || width <= 0. || height <= 0.
  195644. #endif
  195645. )
  195646. {
  195647. png_warning(png_ptr, "Invalid sCAL data");
  195648. png_free(png_ptr, buffer);
  195649. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  195650. png_free(png_ptr, swidth);
  195651. png_free(png_ptr, sheight);
  195652. #endif
  195653. return;
  195654. }
  195655. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195656. png_set_sCAL(png_ptr, info_ptr, buffer[0], width, height);
  195657. #else
  195658. #ifdef PNG_FIXED_POINT_SUPPORTED
  195659. png_set_sCAL_s(png_ptr, info_ptr, buffer[0], swidth, sheight);
  195660. #endif
  195661. #endif
  195662. png_free(png_ptr, buffer);
  195663. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  195664. png_free(png_ptr, swidth);
  195665. png_free(png_ptr, sheight);
  195666. #endif
  195667. }
  195668. #endif
  195669. #if defined(PNG_READ_tIME_SUPPORTED)
  195670. void /* PRIVATE */
  195671. png_handle_tIME(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195672. {
  195673. png_byte buf[7];
  195674. png_time mod_time;
  195675. png_debug(1, "in png_handle_tIME\n");
  195676. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195677. png_error(png_ptr, "Out of place tIME chunk");
  195678. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME))
  195679. {
  195680. png_warning(png_ptr, "Duplicate tIME chunk");
  195681. png_crc_finish(png_ptr, length);
  195682. return;
  195683. }
  195684. if (png_ptr->mode & PNG_HAVE_IDAT)
  195685. png_ptr->mode |= PNG_AFTER_IDAT;
  195686. if (length != 7)
  195687. {
  195688. png_warning(png_ptr, "Incorrect tIME chunk length");
  195689. png_crc_finish(png_ptr, length);
  195690. return;
  195691. }
  195692. png_crc_read(png_ptr, buf, 7);
  195693. if (png_crc_finish(png_ptr, 0))
  195694. return;
  195695. mod_time.second = buf[6];
  195696. mod_time.minute = buf[5];
  195697. mod_time.hour = buf[4];
  195698. mod_time.day = buf[3];
  195699. mod_time.month = buf[2];
  195700. mod_time.year = png_get_uint_16(buf);
  195701. png_set_tIME(png_ptr, info_ptr, &mod_time);
  195702. }
  195703. #endif
  195704. #if defined(PNG_READ_tEXt_SUPPORTED)
  195705. /* Note: this does not properly handle chunks that are > 64K under DOS */
  195706. void /* PRIVATE */
  195707. png_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195708. {
  195709. png_textp text_ptr;
  195710. png_charp key;
  195711. png_charp text;
  195712. png_uint_32 skip = 0;
  195713. png_size_t slength;
  195714. int ret;
  195715. png_debug(1, "in png_handle_tEXt\n");
  195716. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195717. png_error(png_ptr, "Missing IHDR before tEXt");
  195718. if (png_ptr->mode & PNG_HAVE_IDAT)
  195719. png_ptr->mode |= PNG_AFTER_IDAT;
  195720. #ifdef PNG_MAX_MALLOC_64K
  195721. if (length > (png_uint_32)65535L)
  195722. {
  195723. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  195724. skip = length - (png_uint_32)65535L;
  195725. length = (png_uint_32)65535L;
  195726. }
  195727. #endif
  195728. key = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195729. if (key == NULL)
  195730. {
  195731. png_warning(png_ptr, "No memory to process text chunk.");
  195732. return;
  195733. }
  195734. slength = (png_size_t)length;
  195735. png_crc_read(png_ptr, (png_bytep)key, slength);
  195736. if (png_crc_finish(png_ptr, skip))
  195737. {
  195738. png_free(png_ptr, key);
  195739. return;
  195740. }
  195741. key[slength] = 0x00;
  195742. for (text = key; *text; text++)
  195743. /* empty loop to find end of key */ ;
  195744. if (text != key + slength)
  195745. text++;
  195746. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  195747. (png_uint_32)png_sizeof(png_text));
  195748. if (text_ptr == NULL)
  195749. {
  195750. png_warning(png_ptr, "Not enough memory to process text chunk.");
  195751. png_free(png_ptr, key);
  195752. return;
  195753. }
  195754. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  195755. text_ptr->key = key;
  195756. #ifdef PNG_iTXt_SUPPORTED
  195757. text_ptr->lang = NULL;
  195758. text_ptr->lang_key = NULL;
  195759. text_ptr->itxt_length = 0;
  195760. #endif
  195761. text_ptr->text = text;
  195762. text_ptr->text_length = png_strlen(text);
  195763. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195764. png_free(png_ptr, key);
  195765. png_free(png_ptr, text_ptr);
  195766. if (ret)
  195767. png_warning(png_ptr, "Insufficient memory to process text chunk.");
  195768. }
  195769. #endif
  195770. #if defined(PNG_READ_zTXt_SUPPORTED)
  195771. /* note: this does not correctly handle chunks that are > 64K under DOS */
  195772. void /* PRIVATE */
  195773. png_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195774. {
  195775. png_textp text_ptr;
  195776. png_charp chunkdata;
  195777. png_charp text;
  195778. int comp_type;
  195779. int ret;
  195780. png_size_t slength, prefix_len, data_len;
  195781. png_debug(1, "in png_handle_zTXt\n");
  195782. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195783. png_error(png_ptr, "Missing IHDR before zTXt");
  195784. if (png_ptr->mode & PNG_HAVE_IDAT)
  195785. png_ptr->mode |= PNG_AFTER_IDAT;
  195786. #ifdef PNG_MAX_MALLOC_64K
  195787. /* We will no doubt have problems with chunks even half this size, but
  195788. there is no hard and fast rule to tell us where to stop. */
  195789. if (length > (png_uint_32)65535L)
  195790. {
  195791. png_warning(png_ptr,"zTXt chunk too large to fit in memory");
  195792. png_crc_finish(png_ptr, length);
  195793. return;
  195794. }
  195795. #endif
  195796. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195797. if (chunkdata == NULL)
  195798. {
  195799. png_warning(png_ptr,"Out of memory processing zTXt chunk.");
  195800. return;
  195801. }
  195802. slength = (png_size_t)length;
  195803. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  195804. if (png_crc_finish(png_ptr, 0))
  195805. {
  195806. png_free(png_ptr, chunkdata);
  195807. return;
  195808. }
  195809. chunkdata[slength] = 0x00;
  195810. for (text = chunkdata; *text; text++)
  195811. /* empty loop */ ;
  195812. /* zTXt must have some text after the chunkdataword */
  195813. if (text >= chunkdata + slength - 2)
  195814. {
  195815. png_warning(png_ptr, "Truncated zTXt chunk");
  195816. png_free(png_ptr, chunkdata);
  195817. return;
  195818. }
  195819. else
  195820. {
  195821. comp_type = *(++text);
  195822. if (comp_type != PNG_TEXT_COMPRESSION_zTXt)
  195823. {
  195824. png_warning(png_ptr, "Unknown compression type in zTXt chunk");
  195825. comp_type = PNG_TEXT_COMPRESSION_zTXt;
  195826. }
  195827. text++; /* skip the compression_method byte */
  195828. }
  195829. prefix_len = text - chunkdata;
  195830. chunkdata = (png_charp)png_decompress_chunk(png_ptr, comp_type, chunkdata,
  195831. (png_size_t)length, prefix_len, &data_len);
  195832. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  195833. (png_uint_32)png_sizeof(png_text));
  195834. if (text_ptr == NULL)
  195835. {
  195836. png_warning(png_ptr,"Not enough memory to process zTXt chunk.");
  195837. png_free(png_ptr, chunkdata);
  195838. return;
  195839. }
  195840. text_ptr->compression = comp_type;
  195841. text_ptr->key = chunkdata;
  195842. #ifdef PNG_iTXt_SUPPORTED
  195843. text_ptr->lang = NULL;
  195844. text_ptr->lang_key = NULL;
  195845. text_ptr->itxt_length = 0;
  195846. #endif
  195847. text_ptr->text = chunkdata + prefix_len;
  195848. text_ptr->text_length = data_len;
  195849. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195850. png_free(png_ptr, text_ptr);
  195851. png_free(png_ptr, chunkdata);
  195852. if (ret)
  195853. png_error(png_ptr, "Insufficient memory to store zTXt chunk.");
  195854. }
  195855. #endif
  195856. #if defined(PNG_READ_iTXt_SUPPORTED)
  195857. /* note: this does not correctly handle chunks that are > 64K under DOS */
  195858. void /* PRIVATE */
  195859. png_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195860. {
  195861. png_textp text_ptr;
  195862. png_charp chunkdata;
  195863. png_charp key, lang, text, lang_key;
  195864. int comp_flag;
  195865. int comp_type = 0;
  195866. int ret;
  195867. png_size_t slength, prefix_len, data_len;
  195868. png_debug(1, "in png_handle_iTXt\n");
  195869. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195870. png_error(png_ptr, "Missing IHDR before iTXt");
  195871. if (png_ptr->mode & PNG_HAVE_IDAT)
  195872. png_ptr->mode |= PNG_AFTER_IDAT;
  195873. #ifdef PNG_MAX_MALLOC_64K
  195874. /* We will no doubt have problems with chunks even half this size, but
  195875. there is no hard and fast rule to tell us where to stop. */
  195876. if (length > (png_uint_32)65535L)
  195877. {
  195878. png_warning(png_ptr,"iTXt chunk too large to fit in memory");
  195879. png_crc_finish(png_ptr, length);
  195880. return;
  195881. }
  195882. #endif
  195883. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195884. if (chunkdata == NULL)
  195885. {
  195886. png_warning(png_ptr, "No memory to process iTXt chunk.");
  195887. return;
  195888. }
  195889. slength = (png_size_t)length;
  195890. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  195891. if (png_crc_finish(png_ptr, 0))
  195892. {
  195893. png_free(png_ptr, chunkdata);
  195894. return;
  195895. }
  195896. chunkdata[slength] = 0x00;
  195897. for (lang = chunkdata; *lang; lang++)
  195898. /* empty loop */ ;
  195899. lang++; /* skip NUL separator */
  195900. /* iTXt must have a language tag (possibly empty), two compression bytes,
  195901. translated keyword (possibly empty), and possibly some text after the
  195902. keyword */
  195903. if (lang >= chunkdata + slength - 3)
  195904. {
  195905. png_warning(png_ptr, "Truncated iTXt chunk");
  195906. png_free(png_ptr, chunkdata);
  195907. return;
  195908. }
  195909. else
  195910. {
  195911. comp_flag = *lang++;
  195912. comp_type = *lang++;
  195913. }
  195914. for (lang_key = lang; *lang_key; lang_key++)
  195915. /* empty loop */ ;
  195916. lang_key++; /* skip NUL separator */
  195917. if (lang_key >= chunkdata + slength)
  195918. {
  195919. png_warning(png_ptr, "Truncated iTXt chunk");
  195920. png_free(png_ptr, chunkdata);
  195921. return;
  195922. }
  195923. for (text = lang_key; *text; text++)
  195924. /* empty loop */ ;
  195925. text++; /* skip NUL separator */
  195926. if (text >= chunkdata + slength)
  195927. {
  195928. png_warning(png_ptr, "Malformed iTXt chunk");
  195929. png_free(png_ptr, chunkdata);
  195930. return;
  195931. }
  195932. prefix_len = text - chunkdata;
  195933. key=chunkdata;
  195934. if (comp_flag)
  195935. chunkdata = png_decompress_chunk(png_ptr, comp_type, chunkdata,
  195936. (size_t)length, prefix_len, &data_len);
  195937. else
  195938. data_len=png_strlen(chunkdata + prefix_len);
  195939. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  195940. (png_uint_32)png_sizeof(png_text));
  195941. if (text_ptr == NULL)
  195942. {
  195943. png_warning(png_ptr,"Not enough memory to process iTXt chunk.");
  195944. png_free(png_ptr, chunkdata);
  195945. return;
  195946. }
  195947. text_ptr->compression = (int)comp_flag + 1;
  195948. text_ptr->lang_key = chunkdata+(lang_key-key);
  195949. text_ptr->lang = chunkdata+(lang-key);
  195950. text_ptr->itxt_length = data_len;
  195951. text_ptr->text_length = 0;
  195952. text_ptr->key = chunkdata;
  195953. text_ptr->text = chunkdata + prefix_len;
  195954. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195955. png_free(png_ptr, text_ptr);
  195956. png_free(png_ptr, chunkdata);
  195957. if (ret)
  195958. png_error(png_ptr, "Insufficient memory to store iTXt chunk.");
  195959. }
  195960. #endif
  195961. /* This function is called when we haven't found a handler for a
  195962. chunk. If there isn't a problem with the chunk itself (ie bad
  195963. chunk name, CRC, or a critical chunk), the chunk is silently ignored
  195964. -- unless the PNG_FLAG_UNKNOWN_CHUNKS_SUPPORTED flag is on in which
  195965. case it will be saved away to be written out later. */
  195966. void /* PRIVATE */
  195967. png_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195968. {
  195969. png_uint_32 skip = 0;
  195970. png_debug(1, "in png_handle_unknown\n");
  195971. if (png_ptr->mode & PNG_HAVE_IDAT)
  195972. {
  195973. #ifdef PNG_USE_LOCAL_ARRAYS
  195974. PNG_CONST PNG_IDAT;
  195975. #endif
  195976. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4)) /* not an IDAT */
  195977. png_ptr->mode |= PNG_AFTER_IDAT;
  195978. }
  195979. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  195980. if (!(png_ptr->chunk_name[0] & 0x20))
  195981. {
  195982. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  195983. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  195984. PNG_HANDLE_CHUNK_ALWAYS
  195985. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  195986. && png_ptr->read_user_chunk_fn == NULL
  195987. #endif
  195988. )
  195989. #endif
  195990. png_chunk_error(png_ptr, "unknown critical chunk");
  195991. }
  195992. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  195993. if ((png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS) ||
  195994. (png_ptr->read_user_chunk_fn != NULL))
  195995. {
  195996. #ifdef PNG_MAX_MALLOC_64K
  195997. if (length > (png_uint_32)65535L)
  195998. {
  195999. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  196000. skip = length - (png_uint_32)65535L;
  196001. length = (png_uint_32)65535L;
  196002. }
  196003. #endif
  196004. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  196005. (png_charp)png_ptr->chunk_name, 5);
  196006. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  196007. png_ptr->unknown_chunk.size = (png_size_t)length;
  196008. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  196009. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  196010. if(png_ptr->read_user_chunk_fn != NULL)
  196011. {
  196012. /* callback to user unknown chunk handler */
  196013. int ret;
  196014. ret = (*(png_ptr->read_user_chunk_fn))
  196015. (png_ptr, &png_ptr->unknown_chunk);
  196016. if (ret < 0)
  196017. png_chunk_error(png_ptr, "error in user chunk");
  196018. if (ret == 0)
  196019. {
  196020. if (!(png_ptr->chunk_name[0] & 0x20))
  196021. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  196022. PNG_HANDLE_CHUNK_ALWAYS)
  196023. png_chunk_error(png_ptr, "unknown critical chunk");
  196024. png_set_unknown_chunks(png_ptr, info_ptr,
  196025. &png_ptr->unknown_chunk, 1);
  196026. }
  196027. }
  196028. #else
  196029. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  196030. #endif
  196031. png_free(png_ptr, png_ptr->unknown_chunk.data);
  196032. png_ptr->unknown_chunk.data = NULL;
  196033. }
  196034. else
  196035. #endif
  196036. skip = length;
  196037. png_crc_finish(png_ptr, skip);
  196038. #if !defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  196039. info_ptr = info_ptr; /* quiet compiler warnings about unused info_ptr */
  196040. #endif
  196041. }
  196042. /* This function is called to verify that a chunk name is valid.
  196043. This function can't have the "critical chunk check" incorporated
  196044. into it, since in the future we will need to be able to call user
  196045. functions to handle unknown critical chunks after we check that
  196046. the chunk name itself is valid. */
  196047. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  196048. void /* PRIVATE */
  196049. png_check_chunk_name(png_structp png_ptr, png_bytep chunk_name)
  196050. {
  196051. png_debug(1, "in png_check_chunk_name\n");
  196052. if (isnonalpha(chunk_name[0]) || isnonalpha(chunk_name[1]) ||
  196053. isnonalpha(chunk_name[2]) || isnonalpha(chunk_name[3]))
  196054. {
  196055. png_chunk_error(png_ptr, "invalid chunk type");
  196056. }
  196057. }
  196058. /* Combines the row recently read in with the existing pixels in the
  196059. row. This routine takes care of alpha and transparency if requested.
  196060. This routine also handles the two methods of progressive display
  196061. of interlaced images, depending on the mask value.
  196062. The mask value describes which pixels are to be combined with
  196063. the row. The pattern always repeats every 8 pixels, so just 8
  196064. bits are needed. A one indicates the pixel is to be combined,
  196065. a zero indicates the pixel is to be skipped. This is in addition
  196066. to any alpha or transparency value associated with the pixel. If
  196067. you want all pixels to be combined, pass 0xff (255) in mask. */
  196068. void /* PRIVATE */
  196069. png_combine_row(png_structp png_ptr, png_bytep row, int mask)
  196070. {
  196071. png_debug(1,"in png_combine_row\n");
  196072. if (mask == 0xff)
  196073. {
  196074. png_memcpy(row, png_ptr->row_buf + 1,
  196075. PNG_ROWBYTES(png_ptr->row_info.pixel_depth, png_ptr->width));
  196076. }
  196077. else
  196078. {
  196079. switch (png_ptr->row_info.pixel_depth)
  196080. {
  196081. case 1:
  196082. {
  196083. png_bytep sp = png_ptr->row_buf + 1;
  196084. png_bytep dp = row;
  196085. int s_inc, s_start, s_end;
  196086. int m = 0x80;
  196087. int shift;
  196088. png_uint_32 i;
  196089. png_uint_32 row_width = png_ptr->width;
  196090. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196091. if (png_ptr->transformations & PNG_PACKSWAP)
  196092. {
  196093. s_start = 0;
  196094. s_end = 7;
  196095. s_inc = 1;
  196096. }
  196097. else
  196098. #endif
  196099. {
  196100. s_start = 7;
  196101. s_end = 0;
  196102. s_inc = -1;
  196103. }
  196104. shift = s_start;
  196105. for (i = 0; i < row_width; i++)
  196106. {
  196107. if (m & mask)
  196108. {
  196109. int value;
  196110. value = (*sp >> shift) & 0x01;
  196111. *dp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  196112. *dp |= (png_byte)(value << shift);
  196113. }
  196114. if (shift == s_end)
  196115. {
  196116. shift = s_start;
  196117. sp++;
  196118. dp++;
  196119. }
  196120. else
  196121. shift += s_inc;
  196122. if (m == 1)
  196123. m = 0x80;
  196124. else
  196125. m >>= 1;
  196126. }
  196127. break;
  196128. }
  196129. case 2:
  196130. {
  196131. png_bytep sp = png_ptr->row_buf + 1;
  196132. png_bytep dp = row;
  196133. int s_start, s_end, s_inc;
  196134. int m = 0x80;
  196135. int shift;
  196136. png_uint_32 i;
  196137. png_uint_32 row_width = png_ptr->width;
  196138. int value;
  196139. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196140. if (png_ptr->transformations & PNG_PACKSWAP)
  196141. {
  196142. s_start = 0;
  196143. s_end = 6;
  196144. s_inc = 2;
  196145. }
  196146. else
  196147. #endif
  196148. {
  196149. s_start = 6;
  196150. s_end = 0;
  196151. s_inc = -2;
  196152. }
  196153. shift = s_start;
  196154. for (i = 0; i < row_width; i++)
  196155. {
  196156. if (m & mask)
  196157. {
  196158. value = (*sp >> shift) & 0x03;
  196159. *dp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  196160. *dp |= (png_byte)(value << shift);
  196161. }
  196162. if (shift == s_end)
  196163. {
  196164. shift = s_start;
  196165. sp++;
  196166. dp++;
  196167. }
  196168. else
  196169. shift += s_inc;
  196170. if (m == 1)
  196171. m = 0x80;
  196172. else
  196173. m >>= 1;
  196174. }
  196175. break;
  196176. }
  196177. case 4:
  196178. {
  196179. png_bytep sp = png_ptr->row_buf + 1;
  196180. png_bytep dp = row;
  196181. int s_start, s_end, s_inc;
  196182. int m = 0x80;
  196183. int shift;
  196184. png_uint_32 i;
  196185. png_uint_32 row_width = png_ptr->width;
  196186. int value;
  196187. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196188. if (png_ptr->transformations & PNG_PACKSWAP)
  196189. {
  196190. s_start = 0;
  196191. s_end = 4;
  196192. s_inc = 4;
  196193. }
  196194. else
  196195. #endif
  196196. {
  196197. s_start = 4;
  196198. s_end = 0;
  196199. s_inc = -4;
  196200. }
  196201. shift = s_start;
  196202. for (i = 0; i < row_width; i++)
  196203. {
  196204. if (m & mask)
  196205. {
  196206. value = (*sp >> shift) & 0xf;
  196207. *dp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  196208. *dp |= (png_byte)(value << shift);
  196209. }
  196210. if (shift == s_end)
  196211. {
  196212. shift = s_start;
  196213. sp++;
  196214. dp++;
  196215. }
  196216. else
  196217. shift += s_inc;
  196218. if (m == 1)
  196219. m = 0x80;
  196220. else
  196221. m >>= 1;
  196222. }
  196223. break;
  196224. }
  196225. default:
  196226. {
  196227. png_bytep sp = png_ptr->row_buf + 1;
  196228. png_bytep dp = row;
  196229. png_size_t pixel_bytes = (png_ptr->row_info.pixel_depth >> 3);
  196230. png_uint_32 i;
  196231. png_uint_32 row_width = png_ptr->width;
  196232. png_byte m = 0x80;
  196233. for (i = 0; i < row_width; i++)
  196234. {
  196235. if (m & mask)
  196236. {
  196237. png_memcpy(dp, sp, pixel_bytes);
  196238. }
  196239. sp += pixel_bytes;
  196240. dp += pixel_bytes;
  196241. if (m == 1)
  196242. m = 0x80;
  196243. else
  196244. m >>= 1;
  196245. }
  196246. break;
  196247. }
  196248. }
  196249. }
  196250. }
  196251. #ifdef PNG_READ_INTERLACING_SUPPORTED
  196252. /* OLD pre-1.0.9 interface:
  196253. void png_do_read_interlace(png_row_infop row_info, png_bytep row, int pass,
  196254. png_uint_32 transformations)
  196255. */
  196256. void /* PRIVATE */
  196257. png_do_read_interlace(png_structp png_ptr)
  196258. {
  196259. png_row_infop row_info = &(png_ptr->row_info);
  196260. png_bytep row = png_ptr->row_buf + 1;
  196261. int pass = png_ptr->pass;
  196262. png_uint_32 transformations = png_ptr->transformations;
  196263. #ifdef PNG_USE_LOCAL_ARRAYS
  196264. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196265. /* offset to next interlace block */
  196266. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196267. #endif
  196268. png_debug(1,"in png_do_read_interlace\n");
  196269. if (row != NULL && row_info != NULL)
  196270. {
  196271. png_uint_32 final_width;
  196272. final_width = row_info->width * png_pass_inc[pass];
  196273. switch (row_info->pixel_depth)
  196274. {
  196275. case 1:
  196276. {
  196277. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 3);
  196278. png_bytep dp = row + (png_size_t)((final_width - 1) >> 3);
  196279. int sshift, dshift;
  196280. int s_start, s_end, s_inc;
  196281. int jstop = png_pass_inc[pass];
  196282. png_byte v;
  196283. png_uint_32 i;
  196284. int j;
  196285. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196286. if (transformations & PNG_PACKSWAP)
  196287. {
  196288. sshift = (int)((row_info->width + 7) & 0x07);
  196289. dshift = (int)((final_width + 7) & 0x07);
  196290. s_start = 7;
  196291. s_end = 0;
  196292. s_inc = -1;
  196293. }
  196294. else
  196295. #endif
  196296. {
  196297. sshift = 7 - (int)((row_info->width + 7) & 0x07);
  196298. dshift = 7 - (int)((final_width + 7) & 0x07);
  196299. s_start = 0;
  196300. s_end = 7;
  196301. s_inc = 1;
  196302. }
  196303. for (i = 0; i < row_info->width; i++)
  196304. {
  196305. v = (png_byte)((*sp >> sshift) & 0x01);
  196306. for (j = 0; j < jstop; j++)
  196307. {
  196308. *dp &= (png_byte)((0x7f7f >> (7 - dshift)) & 0xff);
  196309. *dp |= (png_byte)(v << dshift);
  196310. if (dshift == s_end)
  196311. {
  196312. dshift = s_start;
  196313. dp--;
  196314. }
  196315. else
  196316. dshift += s_inc;
  196317. }
  196318. if (sshift == s_end)
  196319. {
  196320. sshift = s_start;
  196321. sp--;
  196322. }
  196323. else
  196324. sshift += s_inc;
  196325. }
  196326. break;
  196327. }
  196328. case 2:
  196329. {
  196330. png_bytep sp = row + (png_uint_32)((row_info->width - 1) >> 2);
  196331. png_bytep dp = row + (png_uint_32)((final_width - 1) >> 2);
  196332. int sshift, dshift;
  196333. int s_start, s_end, s_inc;
  196334. int jstop = png_pass_inc[pass];
  196335. png_uint_32 i;
  196336. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196337. if (transformations & PNG_PACKSWAP)
  196338. {
  196339. sshift = (int)(((row_info->width + 3) & 0x03) << 1);
  196340. dshift = (int)(((final_width + 3) & 0x03) << 1);
  196341. s_start = 6;
  196342. s_end = 0;
  196343. s_inc = -2;
  196344. }
  196345. else
  196346. #endif
  196347. {
  196348. sshift = (int)((3 - ((row_info->width + 3) & 0x03)) << 1);
  196349. dshift = (int)((3 - ((final_width + 3) & 0x03)) << 1);
  196350. s_start = 0;
  196351. s_end = 6;
  196352. s_inc = 2;
  196353. }
  196354. for (i = 0; i < row_info->width; i++)
  196355. {
  196356. png_byte v;
  196357. int j;
  196358. v = (png_byte)((*sp >> sshift) & 0x03);
  196359. for (j = 0; j < jstop; j++)
  196360. {
  196361. *dp &= (png_byte)((0x3f3f >> (6 - dshift)) & 0xff);
  196362. *dp |= (png_byte)(v << dshift);
  196363. if (dshift == s_end)
  196364. {
  196365. dshift = s_start;
  196366. dp--;
  196367. }
  196368. else
  196369. dshift += s_inc;
  196370. }
  196371. if (sshift == s_end)
  196372. {
  196373. sshift = s_start;
  196374. sp--;
  196375. }
  196376. else
  196377. sshift += s_inc;
  196378. }
  196379. break;
  196380. }
  196381. case 4:
  196382. {
  196383. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 1);
  196384. png_bytep dp = row + (png_size_t)((final_width - 1) >> 1);
  196385. int sshift, dshift;
  196386. int s_start, s_end, s_inc;
  196387. png_uint_32 i;
  196388. int jstop = png_pass_inc[pass];
  196389. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196390. if (transformations & PNG_PACKSWAP)
  196391. {
  196392. sshift = (int)(((row_info->width + 1) & 0x01) << 2);
  196393. dshift = (int)(((final_width + 1) & 0x01) << 2);
  196394. s_start = 4;
  196395. s_end = 0;
  196396. s_inc = -4;
  196397. }
  196398. else
  196399. #endif
  196400. {
  196401. sshift = (int)((1 - ((row_info->width + 1) & 0x01)) << 2);
  196402. dshift = (int)((1 - ((final_width + 1) & 0x01)) << 2);
  196403. s_start = 0;
  196404. s_end = 4;
  196405. s_inc = 4;
  196406. }
  196407. for (i = 0; i < row_info->width; i++)
  196408. {
  196409. png_byte v = (png_byte)((*sp >> sshift) & 0xf);
  196410. int j;
  196411. for (j = 0; j < jstop; j++)
  196412. {
  196413. *dp &= (png_byte)((0xf0f >> (4 - dshift)) & 0xff);
  196414. *dp |= (png_byte)(v << dshift);
  196415. if (dshift == s_end)
  196416. {
  196417. dshift = s_start;
  196418. dp--;
  196419. }
  196420. else
  196421. dshift += s_inc;
  196422. }
  196423. if (sshift == s_end)
  196424. {
  196425. sshift = s_start;
  196426. sp--;
  196427. }
  196428. else
  196429. sshift += s_inc;
  196430. }
  196431. break;
  196432. }
  196433. default:
  196434. {
  196435. png_size_t pixel_bytes = (row_info->pixel_depth >> 3);
  196436. png_bytep sp = row + (png_size_t)(row_info->width - 1) * pixel_bytes;
  196437. png_bytep dp = row + (png_size_t)(final_width - 1) * pixel_bytes;
  196438. int jstop = png_pass_inc[pass];
  196439. png_uint_32 i;
  196440. for (i = 0; i < row_info->width; i++)
  196441. {
  196442. png_byte v[8];
  196443. int j;
  196444. png_memcpy(v, sp, pixel_bytes);
  196445. for (j = 0; j < jstop; j++)
  196446. {
  196447. png_memcpy(dp, v, pixel_bytes);
  196448. dp -= pixel_bytes;
  196449. }
  196450. sp -= pixel_bytes;
  196451. }
  196452. break;
  196453. }
  196454. }
  196455. row_info->width = final_width;
  196456. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,final_width);
  196457. }
  196458. #if !defined(PNG_READ_PACKSWAP_SUPPORTED)
  196459. transformations = transformations; /* silence compiler warning */
  196460. #endif
  196461. }
  196462. #endif /* PNG_READ_INTERLACING_SUPPORTED */
  196463. void /* PRIVATE */
  196464. png_read_filter_row(png_structp, png_row_infop row_info, png_bytep row,
  196465. png_bytep prev_row, int filter)
  196466. {
  196467. png_debug(1, "in png_read_filter_row\n");
  196468. png_debug2(2,"row = %lu, filter = %d\n", png_ptr->row_number, filter);
  196469. switch (filter)
  196470. {
  196471. case PNG_FILTER_VALUE_NONE:
  196472. break;
  196473. case PNG_FILTER_VALUE_SUB:
  196474. {
  196475. png_uint_32 i;
  196476. png_uint_32 istop = row_info->rowbytes;
  196477. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  196478. png_bytep rp = row + bpp;
  196479. png_bytep lp = row;
  196480. for (i = bpp; i < istop; i++)
  196481. {
  196482. *rp = (png_byte)(((int)(*rp) + (int)(*lp++)) & 0xff);
  196483. rp++;
  196484. }
  196485. break;
  196486. }
  196487. case PNG_FILTER_VALUE_UP:
  196488. {
  196489. png_uint_32 i;
  196490. png_uint_32 istop = row_info->rowbytes;
  196491. png_bytep rp = row;
  196492. png_bytep pp = prev_row;
  196493. for (i = 0; i < istop; i++)
  196494. {
  196495. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  196496. rp++;
  196497. }
  196498. break;
  196499. }
  196500. case PNG_FILTER_VALUE_AVG:
  196501. {
  196502. png_uint_32 i;
  196503. png_bytep rp = row;
  196504. png_bytep pp = prev_row;
  196505. png_bytep lp = row;
  196506. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  196507. png_uint_32 istop = row_info->rowbytes - bpp;
  196508. for (i = 0; i < bpp; i++)
  196509. {
  196510. *rp = (png_byte)(((int)(*rp) +
  196511. ((int)(*pp++) / 2 )) & 0xff);
  196512. rp++;
  196513. }
  196514. for (i = 0; i < istop; i++)
  196515. {
  196516. *rp = (png_byte)(((int)(*rp) +
  196517. (int)(*pp++ + *lp++) / 2 ) & 0xff);
  196518. rp++;
  196519. }
  196520. break;
  196521. }
  196522. case PNG_FILTER_VALUE_PAETH:
  196523. {
  196524. png_uint_32 i;
  196525. png_bytep rp = row;
  196526. png_bytep pp = prev_row;
  196527. png_bytep lp = row;
  196528. png_bytep cp = prev_row;
  196529. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  196530. png_uint_32 istop=row_info->rowbytes - bpp;
  196531. for (i = 0; i < bpp; i++)
  196532. {
  196533. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  196534. rp++;
  196535. }
  196536. for (i = 0; i < istop; i++) /* use leftover rp,pp */
  196537. {
  196538. int a, b, c, pa, pb, pc, p;
  196539. a = *lp++;
  196540. b = *pp++;
  196541. c = *cp++;
  196542. p = b - c;
  196543. pc = a - c;
  196544. #ifdef PNG_USE_ABS
  196545. pa = abs(p);
  196546. pb = abs(pc);
  196547. pc = abs(p + pc);
  196548. #else
  196549. pa = p < 0 ? -p : p;
  196550. pb = pc < 0 ? -pc : pc;
  196551. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  196552. #endif
  196553. /*
  196554. if (pa <= pb && pa <= pc)
  196555. p = a;
  196556. else if (pb <= pc)
  196557. p = b;
  196558. else
  196559. p = c;
  196560. */
  196561. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  196562. *rp = (png_byte)(((int)(*rp) + p) & 0xff);
  196563. rp++;
  196564. }
  196565. break;
  196566. }
  196567. default:
  196568. png_warning(png_ptr, "Ignoring bad adaptive filter type");
  196569. *row=0;
  196570. break;
  196571. }
  196572. }
  196573. void /* PRIVATE */
  196574. png_read_finish_row(png_structp png_ptr)
  196575. {
  196576. #ifdef PNG_USE_LOCAL_ARRAYS
  196577. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196578. /* start of interlace block */
  196579. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  196580. /* offset to next interlace block */
  196581. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196582. /* start of interlace block in the y direction */
  196583. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  196584. /* offset to next interlace block in the y direction */
  196585. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  196586. #endif
  196587. png_debug(1, "in png_read_finish_row\n");
  196588. png_ptr->row_number++;
  196589. if (png_ptr->row_number < png_ptr->num_rows)
  196590. return;
  196591. if (png_ptr->interlaced)
  196592. {
  196593. png_ptr->row_number = 0;
  196594. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  196595. png_ptr->rowbytes + 1);
  196596. do
  196597. {
  196598. png_ptr->pass++;
  196599. if (png_ptr->pass >= 7)
  196600. break;
  196601. png_ptr->iwidth = (png_ptr->width +
  196602. png_pass_inc[png_ptr->pass] - 1 -
  196603. png_pass_start[png_ptr->pass]) /
  196604. png_pass_inc[png_ptr->pass];
  196605. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  196606. png_ptr->iwidth) + 1;
  196607. if (!(png_ptr->transformations & PNG_INTERLACE))
  196608. {
  196609. png_ptr->num_rows = (png_ptr->height +
  196610. png_pass_yinc[png_ptr->pass] - 1 -
  196611. png_pass_ystart[png_ptr->pass]) /
  196612. png_pass_yinc[png_ptr->pass];
  196613. if (!(png_ptr->num_rows))
  196614. continue;
  196615. }
  196616. else /* if (png_ptr->transformations & PNG_INTERLACE) */
  196617. break;
  196618. } while (png_ptr->iwidth == 0);
  196619. if (png_ptr->pass < 7)
  196620. return;
  196621. }
  196622. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  196623. {
  196624. #ifdef PNG_USE_LOCAL_ARRAYS
  196625. PNG_CONST PNG_IDAT;
  196626. #endif
  196627. char extra;
  196628. int ret;
  196629. png_ptr->zstream.next_out = (Bytef *)&extra;
  196630. png_ptr->zstream.avail_out = (uInt)1;
  196631. for(;;)
  196632. {
  196633. if (!(png_ptr->zstream.avail_in))
  196634. {
  196635. while (!png_ptr->idat_size)
  196636. {
  196637. png_byte chunk_length[4];
  196638. png_crc_finish(png_ptr, 0);
  196639. png_read_data(png_ptr, chunk_length, 4);
  196640. png_ptr->idat_size = png_get_uint_31(png_ptr, chunk_length);
  196641. png_reset_crc(png_ptr);
  196642. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  196643. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  196644. png_error(png_ptr, "Not enough image data");
  196645. }
  196646. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  196647. png_ptr->zstream.next_in = png_ptr->zbuf;
  196648. if (png_ptr->zbuf_size > png_ptr->idat_size)
  196649. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  196650. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zstream.avail_in);
  196651. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  196652. }
  196653. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  196654. if (ret == Z_STREAM_END)
  196655. {
  196656. if (!(png_ptr->zstream.avail_out) || png_ptr->zstream.avail_in ||
  196657. png_ptr->idat_size)
  196658. png_warning(png_ptr, "Extra compressed data");
  196659. png_ptr->mode |= PNG_AFTER_IDAT;
  196660. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  196661. break;
  196662. }
  196663. if (ret != Z_OK)
  196664. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  196665. "Decompression Error");
  196666. if (!(png_ptr->zstream.avail_out))
  196667. {
  196668. png_warning(png_ptr, "Extra compressed data.");
  196669. png_ptr->mode |= PNG_AFTER_IDAT;
  196670. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  196671. break;
  196672. }
  196673. }
  196674. png_ptr->zstream.avail_out = 0;
  196675. }
  196676. if (png_ptr->idat_size || png_ptr->zstream.avail_in)
  196677. png_warning(png_ptr, "Extra compression data");
  196678. inflateReset(&png_ptr->zstream);
  196679. png_ptr->mode |= PNG_AFTER_IDAT;
  196680. }
  196681. void /* PRIVATE */
  196682. png_read_start_row(png_structp png_ptr)
  196683. {
  196684. #ifdef PNG_USE_LOCAL_ARRAYS
  196685. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196686. /* start of interlace block */
  196687. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  196688. /* offset to next interlace block */
  196689. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196690. /* start of interlace block in the y direction */
  196691. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  196692. /* offset to next interlace block in the y direction */
  196693. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  196694. #endif
  196695. int max_pixel_depth;
  196696. png_uint_32 row_bytes;
  196697. png_debug(1, "in png_read_start_row\n");
  196698. png_ptr->zstream.avail_in = 0;
  196699. png_init_read_transformations(png_ptr);
  196700. if (png_ptr->interlaced)
  196701. {
  196702. if (!(png_ptr->transformations & PNG_INTERLACE))
  196703. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  196704. png_pass_ystart[0]) / png_pass_yinc[0];
  196705. else
  196706. png_ptr->num_rows = png_ptr->height;
  196707. png_ptr->iwidth = (png_ptr->width +
  196708. png_pass_inc[png_ptr->pass] - 1 -
  196709. png_pass_start[png_ptr->pass]) /
  196710. png_pass_inc[png_ptr->pass];
  196711. row_bytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->iwidth) + 1;
  196712. png_ptr->irowbytes = (png_size_t)row_bytes;
  196713. if((png_uint_32)png_ptr->irowbytes != row_bytes)
  196714. png_error(png_ptr, "Rowbytes overflow in png_read_start_row");
  196715. }
  196716. else
  196717. {
  196718. png_ptr->num_rows = png_ptr->height;
  196719. png_ptr->iwidth = png_ptr->width;
  196720. png_ptr->irowbytes = png_ptr->rowbytes + 1;
  196721. }
  196722. max_pixel_depth = png_ptr->pixel_depth;
  196723. #if defined(PNG_READ_PACK_SUPPORTED)
  196724. if ((png_ptr->transformations & PNG_PACK) && png_ptr->bit_depth < 8)
  196725. max_pixel_depth = 8;
  196726. #endif
  196727. #if defined(PNG_READ_EXPAND_SUPPORTED)
  196728. if (png_ptr->transformations & PNG_EXPAND)
  196729. {
  196730. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196731. {
  196732. if (png_ptr->num_trans)
  196733. max_pixel_depth = 32;
  196734. else
  196735. max_pixel_depth = 24;
  196736. }
  196737. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  196738. {
  196739. if (max_pixel_depth < 8)
  196740. max_pixel_depth = 8;
  196741. if (png_ptr->num_trans)
  196742. max_pixel_depth *= 2;
  196743. }
  196744. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  196745. {
  196746. if (png_ptr->num_trans)
  196747. {
  196748. max_pixel_depth *= 4;
  196749. max_pixel_depth /= 3;
  196750. }
  196751. }
  196752. }
  196753. #endif
  196754. #if defined(PNG_READ_FILLER_SUPPORTED)
  196755. if (png_ptr->transformations & (PNG_FILLER))
  196756. {
  196757. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196758. max_pixel_depth = 32;
  196759. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  196760. {
  196761. if (max_pixel_depth <= 8)
  196762. max_pixel_depth = 16;
  196763. else
  196764. max_pixel_depth = 32;
  196765. }
  196766. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  196767. {
  196768. if (max_pixel_depth <= 32)
  196769. max_pixel_depth = 32;
  196770. else
  196771. max_pixel_depth = 64;
  196772. }
  196773. }
  196774. #endif
  196775. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  196776. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  196777. {
  196778. if (
  196779. #if defined(PNG_READ_EXPAND_SUPPORTED)
  196780. (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND)) ||
  196781. #endif
  196782. #if defined(PNG_READ_FILLER_SUPPORTED)
  196783. (png_ptr->transformations & (PNG_FILLER)) ||
  196784. #endif
  196785. png_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  196786. {
  196787. if (max_pixel_depth <= 16)
  196788. max_pixel_depth = 32;
  196789. else
  196790. max_pixel_depth = 64;
  196791. }
  196792. else
  196793. {
  196794. if (max_pixel_depth <= 8)
  196795. {
  196796. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  196797. max_pixel_depth = 32;
  196798. else
  196799. max_pixel_depth = 24;
  196800. }
  196801. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  196802. max_pixel_depth = 64;
  196803. else
  196804. max_pixel_depth = 48;
  196805. }
  196806. }
  196807. #endif
  196808. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) && \
  196809. defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  196810. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  196811. {
  196812. int user_pixel_depth=png_ptr->user_transform_depth*
  196813. png_ptr->user_transform_channels;
  196814. if(user_pixel_depth > max_pixel_depth)
  196815. max_pixel_depth=user_pixel_depth;
  196816. }
  196817. #endif
  196818. /* align the width on the next larger 8 pixels. Mainly used
  196819. for interlacing */
  196820. row_bytes = ((png_ptr->width + 7) & ~((png_uint_32)7));
  196821. /* calculate the maximum bytes needed, adding a byte and a pixel
  196822. for safety's sake */
  196823. row_bytes = PNG_ROWBYTES(max_pixel_depth,row_bytes) +
  196824. 1 + ((max_pixel_depth + 7) >> 3);
  196825. #ifdef PNG_MAX_MALLOC_64K
  196826. if (row_bytes > (png_uint_32)65536L)
  196827. png_error(png_ptr, "This image requires a row greater than 64KB");
  196828. #endif
  196829. png_ptr->big_row_buf = (png_bytep)png_malloc(png_ptr, row_bytes+64);
  196830. png_ptr->row_buf = png_ptr->big_row_buf+32;
  196831. #ifdef PNG_MAX_MALLOC_64K
  196832. if ((png_uint_32)png_ptr->rowbytes + 1 > (png_uint_32)65536L)
  196833. png_error(png_ptr, "This image requires a row greater than 64KB");
  196834. #endif
  196835. if ((png_uint_32)png_ptr->rowbytes > (png_uint_32)(PNG_SIZE_MAX - 1))
  196836. png_error(png_ptr, "Row has too many bytes to allocate in memory.");
  196837. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)(
  196838. png_ptr->rowbytes + 1));
  196839. png_memset_check(png_ptr, png_ptr->prev_row, 0, png_ptr->rowbytes + 1);
  196840. png_debug1(3, "width = %lu,\n", png_ptr->width);
  196841. png_debug1(3, "height = %lu,\n", png_ptr->height);
  196842. png_debug1(3, "iwidth = %lu,\n", png_ptr->iwidth);
  196843. png_debug1(3, "num_rows = %lu\n", png_ptr->num_rows);
  196844. png_debug1(3, "rowbytes = %lu,\n", png_ptr->rowbytes);
  196845. png_debug1(3, "irowbytes = %lu,\n", png_ptr->irowbytes);
  196846. png_ptr->flags |= PNG_FLAG_ROW_INIT;
  196847. }
  196848. #endif /* PNG_READ_SUPPORTED */
  196849. /*** End of inlined file: pngrutil.c ***/
  196850. /*** Start of inlined file: pngset.c ***/
  196851. /* pngset.c - storage of image information into info struct
  196852. *
  196853. * Last changed in libpng 1.2.21 [October 4, 2007]
  196854. * For conditions of distribution and use, see copyright notice in png.h
  196855. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  196856. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  196857. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  196858. *
  196859. * The functions here are used during reads to store data from the file
  196860. * into the info struct, and during writes to store application data
  196861. * into the info struct for writing into the file. This abstracts the
  196862. * info struct and allows us to change the structure in the future.
  196863. */
  196864. #define PNG_INTERNAL
  196865. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  196866. #if defined(PNG_bKGD_SUPPORTED)
  196867. void PNGAPI
  196868. png_set_bKGD(png_structp png_ptr, png_infop info_ptr, png_color_16p background)
  196869. {
  196870. png_debug1(1, "in %s storage function\n", "bKGD");
  196871. if (png_ptr == NULL || info_ptr == NULL)
  196872. return;
  196873. png_memcpy(&(info_ptr->background), background, png_sizeof(png_color_16));
  196874. info_ptr->valid |= PNG_INFO_bKGD;
  196875. }
  196876. #endif
  196877. #if defined(PNG_cHRM_SUPPORTED)
  196878. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196879. void PNGAPI
  196880. png_set_cHRM(png_structp png_ptr, png_infop info_ptr,
  196881. double white_x, double white_y, double red_x, double red_y,
  196882. double green_x, double green_y, double blue_x, double blue_y)
  196883. {
  196884. png_debug1(1, "in %s storage function\n", "cHRM");
  196885. if (png_ptr == NULL || info_ptr == NULL)
  196886. return;
  196887. if (white_x < 0.0 || white_y < 0.0 ||
  196888. red_x < 0.0 || red_y < 0.0 ||
  196889. green_x < 0.0 || green_y < 0.0 ||
  196890. blue_x < 0.0 || blue_y < 0.0)
  196891. {
  196892. png_warning(png_ptr,
  196893. "Ignoring attempt to set negative chromaticity value");
  196894. return;
  196895. }
  196896. if (white_x > 21474.83 || white_y > 21474.83 ||
  196897. red_x > 21474.83 || red_y > 21474.83 ||
  196898. green_x > 21474.83 || green_y > 21474.83 ||
  196899. blue_x > 21474.83 || blue_y > 21474.83)
  196900. {
  196901. png_warning(png_ptr,
  196902. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  196903. return;
  196904. }
  196905. info_ptr->x_white = (float)white_x;
  196906. info_ptr->y_white = (float)white_y;
  196907. info_ptr->x_red = (float)red_x;
  196908. info_ptr->y_red = (float)red_y;
  196909. info_ptr->x_green = (float)green_x;
  196910. info_ptr->y_green = (float)green_y;
  196911. info_ptr->x_blue = (float)blue_x;
  196912. info_ptr->y_blue = (float)blue_y;
  196913. #ifdef PNG_FIXED_POINT_SUPPORTED
  196914. info_ptr->int_x_white = (png_fixed_point)(white_x*100000.+0.5);
  196915. info_ptr->int_y_white = (png_fixed_point)(white_y*100000.+0.5);
  196916. info_ptr->int_x_red = (png_fixed_point)( red_x*100000.+0.5);
  196917. info_ptr->int_y_red = (png_fixed_point)( red_y*100000.+0.5);
  196918. info_ptr->int_x_green = (png_fixed_point)(green_x*100000.+0.5);
  196919. info_ptr->int_y_green = (png_fixed_point)(green_y*100000.+0.5);
  196920. info_ptr->int_x_blue = (png_fixed_point)( blue_x*100000.+0.5);
  196921. info_ptr->int_y_blue = (png_fixed_point)( blue_y*100000.+0.5);
  196922. #endif
  196923. info_ptr->valid |= PNG_INFO_cHRM;
  196924. }
  196925. #endif
  196926. #ifdef PNG_FIXED_POINT_SUPPORTED
  196927. void PNGAPI
  196928. png_set_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  196929. png_fixed_point white_x, png_fixed_point white_y, png_fixed_point red_x,
  196930. png_fixed_point red_y, png_fixed_point green_x, png_fixed_point green_y,
  196931. png_fixed_point blue_x, png_fixed_point blue_y)
  196932. {
  196933. png_debug1(1, "in %s storage function\n", "cHRM");
  196934. if (png_ptr == NULL || info_ptr == NULL)
  196935. return;
  196936. if (white_x < 0 || white_y < 0 ||
  196937. red_x < 0 || red_y < 0 ||
  196938. green_x < 0 || green_y < 0 ||
  196939. blue_x < 0 || blue_y < 0)
  196940. {
  196941. png_warning(png_ptr,
  196942. "Ignoring attempt to set negative chromaticity value");
  196943. return;
  196944. }
  196945. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196946. if (white_x > (double) PNG_UINT_31_MAX ||
  196947. white_y > (double) PNG_UINT_31_MAX ||
  196948. red_x > (double) PNG_UINT_31_MAX ||
  196949. red_y > (double) PNG_UINT_31_MAX ||
  196950. green_x > (double) PNG_UINT_31_MAX ||
  196951. green_y > (double) PNG_UINT_31_MAX ||
  196952. blue_x > (double) PNG_UINT_31_MAX ||
  196953. blue_y > (double) PNG_UINT_31_MAX)
  196954. #else
  196955. if (white_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196956. white_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196957. red_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196958. red_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196959. green_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196960. green_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196961. blue_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196962. blue_y > (png_fixed_point) PNG_UINT_31_MAX/100000L)
  196963. #endif
  196964. {
  196965. png_warning(png_ptr,
  196966. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  196967. return;
  196968. }
  196969. info_ptr->int_x_white = white_x;
  196970. info_ptr->int_y_white = white_y;
  196971. info_ptr->int_x_red = red_x;
  196972. info_ptr->int_y_red = red_y;
  196973. info_ptr->int_x_green = green_x;
  196974. info_ptr->int_y_green = green_y;
  196975. info_ptr->int_x_blue = blue_x;
  196976. info_ptr->int_y_blue = blue_y;
  196977. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196978. info_ptr->x_white = (float)(white_x/100000.);
  196979. info_ptr->y_white = (float)(white_y/100000.);
  196980. info_ptr->x_red = (float)( red_x/100000.);
  196981. info_ptr->y_red = (float)( red_y/100000.);
  196982. info_ptr->x_green = (float)(green_x/100000.);
  196983. info_ptr->y_green = (float)(green_y/100000.);
  196984. info_ptr->x_blue = (float)( blue_x/100000.);
  196985. info_ptr->y_blue = (float)( blue_y/100000.);
  196986. #endif
  196987. info_ptr->valid |= PNG_INFO_cHRM;
  196988. }
  196989. #endif
  196990. #endif
  196991. #if defined(PNG_gAMA_SUPPORTED)
  196992. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196993. void PNGAPI
  196994. png_set_gAMA(png_structp png_ptr, png_infop info_ptr, double file_gamma)
  196995. {
  196996. double gamma;
  196997. png_debug1(1, "in %s storage function\n", "gAMA");
  196998. if (png_ptr == NULL || info_ptr == NULL)
  196999. return;
  197000. /* Check for overflow */
  197001. if (file_gamma > 21474.83)
  197002. {
  197003. png_warning(png_ptr, "Limiting gamma to 21474.83");
  197004. gamma=21474.83;
  197005. }
  197006. else
  197007. gamma=file_gamma;
  197008. info_ptr->gamma = (float)gamma;
  197009. #ifdef PNG_FIXED_POINT_SUPPORTED
  197010. info_ptr->int_gamma = (int)(gamma*100000.+.5);
  197011. #endif
  197012. info_ptr->valid |= PNG_INFO_gAMA;
  197013. if(gamma == 0.0)
  197014. png_warning(png_ptr, "Setting gamma=0");
  197015. }
  197016. #endif
  197017. void PNGAPI
  197018. png_set_gAMA_fixed(png_structp png_ptr, png_infop info_ptr, png_fixed_point
  197019. int_gamma)
  197020. {
  197021. png_fixed_point gamma;
  197022. png_debug1(1, "in %s storage function\n", "gAMA");
  197023. if (png_ptr == NULL || info_ptr == NULL)
  197024. return;
  197025. if (int_gamma > (png_fixed_point) PNG_UINT_31_MAX)
  197026. {
  197027. png_warning(png_ptr, "Limiting gamma to 21474.83");
  197028. gamma=PNG_UINT_31_MAX;
  197029. }
  197030. else
  197031. {
  197032. if (int_gamma < 0)
  197033. {
  197034. png_warning(png_ptr, "Setting negative gamma to zero");
  197035. gamma=0;
  197036. }
  197037. else
  197038. gamma=int_gamma;
  197039. }
  197040. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197041. info_ptr->gamma = (float)(gamma/100000.);
  197042. #endif
  197043. #ifdef PNG_FIXED_POINT_SUPPORTED
  197044. info_ptr->int_gamma = gamma;
  197045. #endif
  197046. info_ptr->valid |= PNG_INFO_gAMA;
  197047. if(gamma == 0)
  197048. png_warning(png_ptr, "Setting gamma=0");
  197049. }
  197050. #endif
  197051. #if defined(PNG_hIST_SUPPORTED)
  197052. void PNGAPI
  197053. png_set_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p hist)
  197054. {
  197055. int i;
  197056. png_debug1(1, "in %s storage function\n", "hIST");
  197057. if (png_ptr == NULL || info_ptr == NULL)
  197058. return;
  197059. if (info_ptr->num_palette == 0 || info_ptr->num_palette
  197060. > PNG_MAX_PALETTE_LENGTH)
  197061. {
  197062. png_warning(png_ptr,
  197063. "Invalid palette size, hIST allocation skipped.");
  197064. return;
  197065. }
  197066. #ifdef PNG_FREE_ME_SUPPORTED
  197067. png_free_data(png_ptr, info_ptr, PNG_FREE_HIST, 0);
  197068. #endif
  197069. /* Changed from info->num_palette to PNG_MAX_PALETTE_LENGTH in version
  197070. 1.2.1 */
  197071. png_ptr->hist = (png_uint_16p)png_malloc_warn(png_ptr,
  197072. (png_uint_32)(PNG_MAX_PALETTE_LENGTH * png_sizeof (png_uint_16)));
  197073. if (png_ptr->hist == NULL)
  197074. {
  197075. png_warning(png_ptr, "Insufficient memory for hIST chunk data.");
  197076. return;
  197077. }
  197078. for (i = 0; i < info_ptr->num_palette; i++)
  197079. png_ptr->hist[i] = hist[i];
  197080. info_ptr->hist = png_ptr->hist;
  197081. info_ptr->valid |= PNG_INFO_hIST;
  197082. #ifdef PNG_FREE_ME_SUPPORTED
  197083. info_ptr->free_me |= PNG_FREE_HIST;
  197084. #else
  197085. png_ptr->flags |= PNG_FLAG_FREE_HIST;
  197086. #endif
  197087. }
  197088. #endif
  197089. void PNGAPI
  197090. png_set_IHDR(png_structp png_ptr, png_infop info_ptr,
  197091. png_uint_32 width, png_uint_32 height, int bit_depth,
  197092. int color_type, int interlace_type, int compression_type,
  197093. int filter_type)
  197094. {
  197095. png_debug1(1, "in %s storage function\n", "IHDR");
  197096. if (png_ptr == NULL || info_ptr == NULL)
  197097. return;
  197098. /* check for width and height valid values */
  197099. if (width == 0 || height == 0)
  197100. png_error(png_ptr, "Image width or height is zero in IHDR");
  197101. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  197102. if (width > png_ptr->user_width_max || height > png_ptr->user_height_max)
  197103. png_error(png_ptr, "image size exceeds user limits in IHDR");
  197104. #else
  197105. if (width > PNG_USER_WIDTH_MAX || height > PNG_USER_HEIGHT_MAX)
  197106. png_error(png_ptr, "image size exceeds user limits in IHDR");
  197107. #endif
  197108. if (width > PNG_UINT_31_MAX || height > PNG_UINT_31_MAX)
  197109. png_error(png_ptr, "Invalid image size in IHDR");
  197110. if ( width > (PNG_UINT_32_MAX
  197111. >> 3) /* 8-byte RGBA pixels */
  197112. - 64 /* bigrowbuf hack */
  197113. - 1 /* filter byte */
  197114. - 7*8 /* rounding of width to multiple of 8 pixels */
  197115. - 8) /* extra max_pixel_depth pad */
  197116. png_warning(png_ptr, "Width is too large for libpng to process pixels");
  197117. /* check other values */
  197118. if (bit_depth != 1 && bit_depth != 2 && bit_depth != 4 &&
  197119. bit_depth != 8 && bit_depth != 16)
  197120. png_error(png_ptr, "Invalid bit depth in IHDR");
  197121. if (color_type < 0 || color_type == 1 ||
  197122. color_type == 5 || color_type > 6)
  197123. png_error(png_ptr, "Invalid color type in IHDR");
  197124. if (((color_type == PNG_COLOR_TYPE_PALETTE) && bit_depth > 8) ||
  197125. ((color_type == PNG_COLOR_TYPE_RGB ||
  197126. color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||
  197127. color_type == PNG_COLOR_TYPE_RGB_ALPHA) && bit_depth < 8))
  197128. png_error(png_ptr, "Invalid color type/bit depth combination in IHDR");
  197129. if (interlace_type >= PNG_INTERLACE_LAST)
  197130. png_error(png_ptr, "Unknown interlace method in IHDR");
  197131. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  197132. png_error(png_ptr, "Unknown compression method in IHDR");
  197133. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  197134. /* Accept filter_method 64 (intrapixel differencing) only if
  197135. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  197136. * 2. Libpng did not read a PNG signature (this filter_method is only
  197137. * used in PNG datastreams that are embedded in MNG datastreams) and
  197138. * 3. The application called png_permit_mng_features with a mask that
  197139. * included PNG_FLAG_MNG_FILTER_64 and
  197140. * 4. The filter_method is 64 and
  197141. * 5. The color_type is RGB or RGBA
  197142. */
  197143. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&png_ptr->mng_features_permitted)
  197144. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  197145. if(filter_type != PNG_FILTER_TYPE_BASE)
  197146. {
  197147. if(!((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  197148. (filter_type == PNG_INTRAPIXEL_DIFFERENCING) &&
  197149. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  197150. (color_type == PNG_COLOR_TYPE_RGB ||
  197151. color_type == PNG_COLOR_TYPE_RGB_ALPHA)))
  197152. png_error(png_ptr, "Unknown filter method in IHDR");
  197153. if(png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)
  197154. png_warning(png_ptr, "Invalid filter method in IHDR");
  197155. }
  197156. #else
  197157. if(filter_type != PNG_FILTER_TYPE_BASE)
  197158. png_error(png_ptr, "Unknown filter method in IHDR");
  197159. #endif
  197160. info_ptr->width = width;
  197161. info_ptr->height = height;
  197162. info_ptr->bit_depth = (png_byte)bit_depth;
  197163. info_ptr->color_type =(png_byte) color_type;
  197164. info_ptr->compression_type = (png_byte)compression_type;
  197165. info_ptr->filter_type = (png_byte)filter_type;
  197166. info_ptr->interlace_type = (png_byte)interlace_type;
  197167. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  197168. info_ptr->channels = 1;
  197169. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  197170. info_ptr->channels = 3;
  197171. else
  197172. info_ptr->channels = 1;
  197173. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  197174. info_ptr->channels++;
  197175. info_ptr->pixel_depth = (png_byte)(info_ptr->channels * info_ptr->bit_depth);
  197176. /* check for potential overflow */
  197177. if (width > (PNG_UINT_32_MAX
  197178. >> 3) /* 8-byte RGBA pixels */
  197179. - 64 /* bigrowbuf hack */
  197180. - 1 /* filter byte */
  197181. - 7*8 /* rounding of width to multiple of 8 pixels */
  197182. - 8) /* extra max_pixel_depth pad */
  197183. info_ptr->rowbytes = (png_size_t)0;
  197184. else
  197185. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,width);
  197186. }
  197187. #if defined(PNG_oFFs_SUPPORTED)
  197188. void PNGAPI
  197189. png_set_oFFs(png_structp png_ptr, png_infop info_ptr,
  197190. png_int_32 offset_x, png_int_32 offset_y, int unit_type)
  197191. {
  197192. png_debug1(1, "in %s storage function\n", "oFFs");
  197193. if (png_ptr == NULL || info_ptr == NULL)
  197194. return;
  197195. info_ptr->x_offset = offset_x;
  197196. info_ptr->y_offset = offset_y;
  197197. info_ptr->offset_unit_type = (png_byte)unit_type;
  197198. info_ptr->valid |= PNG_INFO_oFFs;
  197199. }
  197200. #endif
  197201. #if defined(PNG_pCAL_SUPPORTED)
  197202. void PNGAPI
  197203. png_set_pCAL(png_structp png_ptr, png_infop info_ptr,
  197204. png_charp purpose, png_int_32 X0, png_int_32 X1, int type, int nparams,
  197205. png_charp units, png_charpp params)
  197206. {
  197207. png_uint_32 length;
  197208. int i;
  197209. png_debug1(1, "in %s storage function\n", "pCAL");
  197210. if (png_ptr == NULL || info_ptr == NULL)
  197211. return;
  197212. length = png_strlen(purpose) + 1;
  197213. png_debug1(3, "allocating purpose for info (%lu bytes)\n", length);
  197214. info_ptr->pcal_purpose = (png_charp)png_malloc_warn(png_ptr, length);
  197215. if (info_ptr->pcal_purpose == NULL)
  197216. {
  197217. png_warning(png_ptr, "Insufficient memory for pCAL purpose.");
  197218. return;
  197219. }
  197220. png_memcpy(info_ptr->pcal_purpose, purpose, (png_size_t)length);
  197221. png_debug(3, "storing X0, X1, type, and nparams in info\n");
  197222. info_ptr->pcal_X0 = X0;
  197223. info_ptr->pcal_X1 = X1;
  197224. info_ptr->pcal_type = (png_byte)type;
  197225. info_ptr->pcal_nparams = (png_byte)nparams;
  197226. length = png_strlen(units) + 1;
  197227. png_debug1(3, "allocating units for info (%lu bytes)\n", length);
  197228. info_ptr->pcal_units = (png_charp)png_malloc_warn(png_ptr, length);
  197229. if (info_ptr->pcal_units == NULL)
  197230. {
  197231. png_warning(png_ptr, "Insufficient memory for pCAL units.");
  197232. return;
  197233. }
  197234. png_memcpy(info_ptr->pcal_units, units, (png_size_t)length);
  197235. info_ptr->pcal_params = (png_charpp)png_malloc_warn(png_ptr,
  197236. (png_uint_32)((nparams + 1) * png_sizeof(png_charp)));
  197237. if (info_ptr->pcal_params == NULL)
  197238. {
  197239. png_warning(png_ptr, "Insufficient memory for pCAL params.");
  197240. return;
  197241. }
  197242. info_ptr->pcal_params[nparams] = NULL;
  197243. for (i = 0; i < nparams; i++)
  197244. {
  197245. length = png_strlen(params[i]) + 1;
  197246. png_debug2(3, "allocating parameter %d for info (%lu bytes)\n", i, length);
  197247. info_ptr->pcal_params[i] = (png_charp)png_malloc_warn(png_ptr, length);
  197248. if (info_ptr->pcal_params[i] == NULL)
  197249. {
  197250. png_warning(png_ptr, "Insufficient memory for pCAL parameter.");
  197251. return;
  197252. }
  197253. png_memcpy(info_ptr->pcal_params[i], params[i], (png_size_t)length);
  197254. }
  197255. info_ptr->valid |= PNG_INFO_pCAL;
  197256. #ifdef PNG_FREE_ME_SUPPORTED
  197257. info_ptr->free_me |= PNG_FREE_PCAL;
  197258. #endif
  197259. }
  197260. #endif
  197261. #if defined(PNG_READ_sCAL_SUPPORTED) || defined(PNG_WRITE_sCAL_SUPPORTED)
  197262. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197263. void PNGAPI
  197264. png_set_sCAL(png_structp png_ptr, png_infop info_ptr,
  197265. int unit, double width, double height)
  197266. {
  197267. png_debug1(1, "in %s storage function\n", "sCAL");
  197268. if (png_ptr == NULL || info_ptr == NULL)
  197269. return;
  197270. info_ptr->scal_unit = (png_byte)unit;
  197271. info_ptr->scal_pixel_width = width;
  197272. info_ptr->scal_pixel_height = height;
  197273. info_ptr->valid |= PNG_INFO_sCAL;
  197274. }
  197275. #else
  197276. #ifdef PNG_FIXED_POINT_SUPPORTED
  197277. void PNGAPI
  197278. png_set_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  197279. int unit, png_charp swidth, png_charp sheight)
  197280. {
  197281. png_uint_32 length;
  197282. png_debug1(1, "in %s storage function\n", "sCAL");
  197283. if (png_ptr == NULL || info_ptr == NULL)
  197284. return;
  197285. info_ptr->scal_unit = (png_byte)unit;
  197286. length = png_strlen(swidth) + 1;
  197287. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  197288. info_ptr->scal_s_width = (png_charp)png_malloc_warn(png_ptr, length);
  197289. if (info_ptr->scal_s_width == NULL)
  197290. {
  197291. png_warning(png_ptr,
  197292. "Memory allocation failed while processing sCAL.");
  197293. }
  197294. png_memcpy(info_ptr->scal_s_width, swidth, (png_size_t)length);
  197295. length = png_strlen(sheight) + 1;
  197296. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  197297. info_ptr->scal_s_height = (png_charp)png_malloc_warn(png_ptr, length);
  197298. if (info_ptr->scal_s_height == NULL)
  197299. {
  197300. png_free (png_ptr, info_ptr->scal_s_width);
  197301. png_warning(png_ptr,
  197302. "Memory allocation failed while processing sCAL.");
  197303. }
  197304. png_memcpy(info_ptr->scal_s_height, sheight, (png_size_t)length);
  197305. info_ptr->valid |= PNG_INFO_sCAL;
  197306. #ifdef PNG_FREE_ME_SUPPORTED
  197307. info_ptr->free_me |= PNG_FREE_SCAL;
  197308. #endif
  197309. }
  197310. #endif
  197311. #endif
  197312. #endif
  197313. #if defined(PNG_pHYs_SUPPORTED)
  197314. void PNGAPI
  197315. png_set_pHYs(png_structp png_ptr, png_infop info_ptr,
  197316. png_uint_32 res_x, png_uint_32 res_y, int unit_type)
  197317. {
  197318. png_debug1(1, "in %s storage function\n", "pHYs");
  197319. if (png_ptr == NULL || info_ptr == NULL)
  197320. return;
  197321. info_ptr->x_pixels_per_unit = res_x;
  197322. info_ptr->y_pixels_per_unit = res_y;
  197323. info_ptr->phys_unit_type = (png_byte)unit_type;
  197324. info_ptr->valid |= PNG_INFO_pHYs;
  197325. }
  197326. #endif
  197327. void PNGAPI
  197328. png_set_PLTE(png_structp png_ptr, png_infop info_ptr,
  197329. png_colorp palette, int num_palette)
  197330. {
  197331. png_debug1(1, "in %s storage function\n", "PLTE");
  197332. if (png_ptr == NULL || info_ptr == NULL)
  197333. return;
  197334. if (num_palette < 0 || num_palette > PNG_MAX_PALETTE_LENGTH)
  197335. {
  197336. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  197337. png_error(png_ptr, "Invalid palette length");
  197338. else
  197339. {
  197340. png_warning(png_ptr, "Invalid palette length");
  197341. return;
  197342. }
  197343. }
  197344. /*
  197345. * It may not actually be necessary to set png_ptr->palette here;
  197346. * we do it for backward compatibility with the way the png_handle_tRNS
  197347. * function used to do the allocation.
  197348. */
  197349. #ifdef PNG_FREE_ME_SUPPORTED
  197350. png_free_data(png_ptr, info_ptr, PNG_FREE_PLTE, 0);
  197351. #endif
  197352. /* Changed in libpng-1.2.1 to allocate PNG_MAX_PALETTE_LENGTH instead
  197353. of num_palette entries,
  197354. in case of an invalid PNG file that has too-large sample values. */
  197355. png_ptr->palette = (png_colorp)png_malloc(png_ptr,
  197356. PNG_MAX_PALETTE_LENGTH * png_sizeof(png_color));
  197357. png_memset(png_ptr->palette, 0, PNG_MAX_PALETTE_LENGTH *
  197358. png_sizeof(png_color));
  197359. png_memcpy(png_ptr->palette, palette, num_palette * png_sizeof (png_color));
  197360. info_ptr->palette = png_ptr->palette;
  197361. info_ptr->num_palette = png_ptr->num_palette = (png_uint_16)num_palette;
  197362. #ifdef PNG_FREE_ME_SUPPORTED
  197363. info_ptr->free_me |= PNG_FREE_PLTE;
  197364. #else
  197365. png_ptr->flags |= PNG_FLAG_FREE_PLTE;
  197366. #endif
  197367. info_ptr->valid |= PNG_INFO_PLTE;
  197368. }
  197369. #if defined(PNG_sBIT_SUPPORTED)
  197370. void PNGAPI
  197371. png_set_sBIT(png_structp png_ptr, png_infop info_ptr,
  197372. png_color_8p sig_bit)
  197373. {
  197374. png_debug1(1, "in %s storage function\n", "sBIT");
  197375. if (png_ptr == NULL || info_ptr == NULL)
  197376. return;
  197377. png_memcpy(&(info_ptr->sig_bit), sig_bit, png_sizeof (png_color_8));
  197378. info_ptr->valid |= PNG_INFO_sBIT;
  197379. }
  197380. #endif
  197381. #if defined(PNG_sRGB_SUPPORTED)
  197382. void PNGAPI
  197383. png_set_sRGB(png_structp png_ptr, png_infop info_ptr, int intent)
  197384. {
  197385. png_debug1(1, "in %s storage function\n", "sRGB");
  197386. if (png_ptr == NULL || info_ptr == NULL)
  197387. return;
  197388. info_ptr->srgb_intent = (png_byte)intent;
  197389. info_ptr->valid |= PNG_INFO_sRGB;
  197390. }
  197391. void PNGAPI
  197392. png_set_sRGB_gAMA_and_cHRM(png_structp png_ptr, png_infop info_ptr,
  197393. int intent)
  197394. {
  197395. #if defined(PNG_gAMA_SUPPORTED)
  197396. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197397. float file_gamma;
  197398. #endif
  197399. #ifdef PNG_FIXED_POINT_SUPPORTED
  197400. png_fixed_point int_file_gamma;
  197401. #endif
  197402. #endif
  197403. #if defined(PNG_cHRM_SUPPORTED)
  197404. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197405. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  197406. #endif
  197407. #ifdef PNG_FIXED_POINT_SUPPORTED
  197408. png_fixed_point int_white_x, int_white_y, int_red_x, int_red_y, int_green_x,
  197409. int_green_y, int_blue_x, int_blue_y;
  197410. #endif
  197411. #endif
  197412. png_debug1(1, "in %s storage function\n", "sRGB_gAMA_and_cHRM");
  197413. if (png_ptr == NULL || info_ptr == NULL)
  197414. return;
  197415. png_set_sRGB(png_ptr, info_ptr, intent);
  197416. #if defined(PNG_gAMA_SUPPORTED)
  197417. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197418. file_gamma = (float).45455;
  197419. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  197420. #endif
  197421. #ifdef PNG_FIXED_POINT_SUPPORTED
  197422. int_file_gamma = 45455L;
  197423. png_set_gAMA_fixed(png_ptr, info_ptr, int_file_gamma);
  197424. #endif
  197425. #endif
  197426. #if defined(PNG_cHRM_SUPPORTED)
  197427. #ifdef PNG_FIXED_POINT_SUPPORTED
  197428. int_white_x = 31270L;
  197429. int_white_y = 32900L;
  197430. int_red_x = 64000L;
  197431. int_red_y = 33000L;
  197432. int_green_x = 30000L;
  197433. int_green_y = 60000L;
  197434. int_blue_x = 15000L;
  197435. int_blue_y = 6000L;
  197436. png_set_cHRM_fixed(png_ptr, info_ptr,
  197437. int_white_x, int_white_y, int_red_x, int_red_y, int_green_x, int_green_y,
  197438. int_blue_x, int_blue_y);
  197439. #endif
  197440. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197441. white_x = (float).3127;
  197442. white_y = (float).3290;
  197443. red_x = (float).64;
  197444. red_y = (float).33;
  197445. green_x = (float).30;
  197446. green_y = (float).60;
  197447. blue_x = (float).15;
  197448. blue_y = (float).06;
  197449. png_set_cHRM(png_ptr, info_ptr,
  197450. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  197451. #endif
  197452. #endif
  197453. }
  197454. #endif
  197455. #if defined(PNG_iCCP_SUPPORTED)
  197456. void PNGAPI
  197457. png_set_iCCP(png_structp png_ptr, png_infop info_ptr,
  197458. png_charp name, int compression_type,
  197459. png_charp profile, png_uint_32 proflen)
  197460. {
  197461. png_charp new_iccp_name;
  197462. png_charp new_iccp_profile;
  197463. png_debug1(1, "in %s storage function\n", "iCCP");
  197464. if (png_ptr == NULL || info_ptr == NULL || name == NULL || profile == NULL)
  197465. return;
  197466. new_iccp_name = (png_charp)png_malloc_warn(png_ptr, png_strlen(name)+1);
  197467. if (new_iccp_name == NULL)
  197468. {
  197469. png_warning(png_ptr, "Insufficient memory to process iCCP chunk.");
  197470. return;
  197471. }
  197472. png_strncpy(new_iccp_name, name, png_strlen(name)+1);
  197473. new_iccp_profile = (png_charp)png_malloc_warn(png_ptr, proflen);
  197474. if (new_iccp_profile == NULL)
  197475. {
  197476. png_free (png_ptr, new_iccp_name);
  197477. png_warning(png_ptr, "Insufficient memory to process iCCP profile.");
  197478. return;
  197479. }
  197480. png_memcpy(new_iccp_profile, profile, (png_size_t)proflen);
  197481. png_free_data(png_ptr, info_ptr, PNG_FREE_ICCP, 0);
  197482. info_ptr->iccp_proflen = proflen;
  197483. info_ptr->iccp_name = new_iccp_name;
  197484. info_ptr->iccp_profile = new_iccp_profile;
  197485. /* Compression is always zero but is here so the API and info structure
  197486. * does not have to change if we introduce multiple compression types */
  197487. info_ptr->iccp_compression = (png_byte)compression_type;
  197488. #ifdef PNG_FREE_ME_SUPPORTED
  197489. info_ptr->free_me |= PNG_FREE_ICCP;
  197490. #endif
  197491. info_ptr->valid |= PNG_INFO_iCCP;
  197492. }
  197493. #endif
  197494. #if defined(PNG_TEXT_SUPPORTED)
  197495. void PNGAPI
  197496. png_set_text(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  197497. int num_text)
  197498. {
  197499. int ret;
  197500. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, num_text);
  197501. if (ret)
  197502. png_error(png_ptr, "Insufficient memory to store text");
  197503. }
  197504. int /* PRIVATE */
  197505. png_set_text_2(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  197506. int num_text)
  197507. {
  197508. int i;
  197509. png_debug1(1, "in %s storage function\n", (png_ptr->chunk_name[0] == '\0' ?
  197510. "text" : (png_const_charp)png_ptr->chunk_name));
  197511. if (png_ptr == NULL || info_ptr == NULL || num_text == 0)
  197512. return(0);
  197513. /* Make sure we have enough space in the "text" array in info_struct
  197514. * to hold all of the incoming text_ptr objects.
  197515. */
  197516. if (info_ptr->num_text + num_text > info_ptr->max_text)
  197517. {
  197518. if (info_ptr->text != NULL)
  197519. {
  197520. png_textp old_text;
  197521. int old_max;
  197522. old_max = info_ptr->max_text;
  197523. info_ptr->max_text = info_ptr->num_text + num_text + 8;
  197524. old_text = info_ptr->text;
  197525. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  197526. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  197527. if (info_ptr->text == NULL)
  197528. {
  197529. png_free(png_ptr, old_text);
  197530. return(1);
  197531. }
  197532. png_memcpy(info_ptr->text, old_text, (png_size_t)(old_max *
  197533. png_sizeof(png_text)));
  197534. png_free(png_ptr, old_text);
  197535. }
  197536. else
  197537. {
  197538. info_ptr->max_text = num_text + 8;
  197539. info_ptr->num_text = 0;
  197540. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  197541. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  197542. if (info_ptr->text == NULL)
  197543. return(1);
  197544. #ifdef PNG_FREE_ME_SUPPORTED
  197545. info_ptr->free_me |= PNG_FREE_TEXT;
  197546. #endif
  197547. }
  197548. png_debug1(3, "allocated %d entries for info_ptr->text\n",
  197549. info_ptr->max_text);
  197550. }
  197551. for (i = 0; i < num_text; i++)
  197552. {
  197553. png_size_t text_length,key_len;
  197554. png_size_t lang_len,lang_key_len;
  197555. png_textp textp = &(info_ptr->text[info_ptr->num_text]);
  197556. if (text_ptr[i].key == NULL)
  197557. continue;
  197558. key_len = png_strlen(text_ptr[i].key);
  197559. if(text_ptr[i].compression <= 0)
  197560. {
  197561. lang_len = 0;
  197562. lang_key_len = 0;
  197563. }
  197564. else
  197565. #ifdef PNG_iTXt_SUPPORTED
  197566. {
  197567. /* set iTXt data */
  197568. if (text_ptr[i].lang != NULL)
  197569. lang_len = png_strlen(text_ptr[i].lang);
  197570. else
  197571. lang_len = 0;
  197572. if (text_ptr[i].lang_key != NULL)
  197573. lang_key_len = png_strlen(text_ptr[i].lang_key);
  197574. else
  197575. lang_key_len = 0;
  197576. }
  197577. #else
  197578. {
  197579. png_warning(png_ptr, "iTXt chunk not supported.");
  197580. continue;
  197581. }
  197582. #endif
  197583. if (text_ptr[i].text == NULL || text_ptr[i].text[0] == '\0')
  197584. {
  197585. text_length = 0;
  197586. #ifdef PNG_iTXt_SUPPORTED
  197587. if(text_ptr[i].compression > 0)
  197588. textp->compression = PNG_ITXT_COMPRESSION_NONE;
  197589. else
  197590. #endif
  197591. textp->compression = PNG_TEXT_COMPRESSION_NONE;
  197592. }
  197593. else
  197594. {
  197595. text_length = png_strlen(text_ptr[i].text);
  197596. textp->compression = text_ptr[i].compression;
  197597. }
  197598. textp->key = (png_charp)png_malloc_warn(png_ptr,
  197599. (png_uint_32)(key_len + text_length + lang_len + lang_key_len + 4));
  197600. if (textp->key == NULL)
  197601. return(1);
  197602. png_debug2(2, "Allocated %lu bytes at %x in png_set_text\n",
  197603. (png_uint_32)(key_len + lang_len + lang_key_len + text_length + 4),
  197604. (int)textp->key);
  197605. png_memcpy(textp->key, text_ptr[i].key,
  197606. (png_size_t)(key_len));
  197607. *(textp->key+key_len) = '\0';
  197608. #ifdef PNG_iTXt_SUPPORTED
  197609. if (text_ptr[i].compression > 0)
  197610. {
  197611. textp->lang=textp->key + key_len + 1;
  197612. png_memcpy(textp->lang, text_ptr[i].lang, lang_len);
  197613. *(textp->lang+lang_len) = '\0';
  197614. textp->lang_key=textp->lang + lang_len + 1;
  197615. png_memcpy(textp->lang_key, text_ptr[i].lang_key, lang_key_len);
  197616. *(textp->lang_key+lang_key_len) = '\0';
  197617. textp->text=textp->lang_key + lang_key_len + 1;
  197618. }
  197619. else
  197620. #endif
  197621. {
  197622. #ifdef PNG_iTXt_SUPPORTED
  197623. textp->lang=NULL;
  197624. textp->lang_key=NULL;
  197625. #endif
  197626. textp->text=textp->key + key_len + 1;
  197627. }
  197628. if(text_length)
  197629. png_memcpy(textp->text, text_ptr[i].text,
  197630. (png_size_t)(text_length));
  197631. *(textp->text+text_length) = '\0';
  197632. #ifdef PNG_iTXt_SUPPORTED
  197633. if(textp->compression > 0)
  197634. {
  197635. textp->text_length = 0;
  197636. textp->itxt_length = text_length;
  197637. }
  197638. else
  197639. #endif
  197640. {
  197641. textp->text_length = text_length;
  197642. #ifdef PNG_iTXt_SUPPORTED
  197643. textp->itxt_length = 0;
  197644. #endif
  197645. }
  197646. info_ptr->num_text++;
  197647. png_debug1(3, "transferred text chunk %d\n", info_ptr->num_text);
  197648. }
  197649. return(0);
  197650. }
  197651. #endif
  197652. #if defined(PNG_tIME_SUPPORTED)
  197653. void PNGAPI
  197654. png_set_tIME(png_structp png_ptr, png_infop info_ptr, png_timep mod_time)
  197655. {
  197656. png_debug1(1, "in %s storage function\n", "tIME");
  197657. if (png_ptr == NULL || info_ptr == NULL ||
  197658. (png_ptr->mode & PNG_WROTE_tIME))
  197659. return;
  197660. png_memcpy(&(info_ptr->mod_time), mod_time, png_sizeof (png_time));
  197661. info_ptr->valid |= PNG_INFO_tIME;
  197662. }
  197663. #endif
  197664. #if defined(PNG_tRNS_SUPPORTED)
  197665. void PNGAPI
  197666. png_set_tRNS(png_structp png_ptr, png_infop info_ptr,
  197667. png_bytep trans, int num_trans, png_color_16p trans_values)
  197668. {
  197669. png_debug1(1, "in %s storage function\n", "tRNS");
  197670. if (png_ptr == NULL || info_ptr == NULL)
  197671. return;
  197672. if (trans != NULL)
  197673. {
  197674. /*
  197675. * It may not actually be necessary to set png_ptr->trans here;
  197676. * we do it for backward compatibility with the way the png_handle_tRNS
  197677. * function used to do the allocation.
  197678. */
  197679. #ifdef PNG_FREE_ME_SUPPORTED
  197680. png_free_data(png_ptr, info_ptr, PNG_FREE_TRNS, 0);
  197681. #endif
  197682. /* Changed from num_trans to PNG_MAX_PALETTE_LENGTH in version 1.2.1 */
  197683. png_ptr->trans = info_ptr->trans = (png_bytep)png_malloc(png_ptr,
  197684. (png_uint_32)PNG_MAX_PALETTE_LENGTH);
  197685. if (num_trans <= PNG_MAX_PALETTE_LENGTH)
  197686. png_memcpy(info_ptr->trans, trans, (png_size_t)num_trans);
  197687. #ifdef PNG_FREE_ME_SUPPORTED
  197688. info_ptr->free_me |= PNG_FREE_TRNS;
  197689. #else
  197690. png_ptr->flags |= PNG_FLAG_FREE_TRNS;
  197691. #endif
  197692. }
  197693. if (trans_values != NULL)
  197694. {
  197695. png_memcpy(&(info_ptr->trans_values), trans_values,
  197696. png_sizeof(png_color_16));
  197697. if (num_trans == 0)
  197698. num_trans = 1;
  197699. }
  197700. info_ptr->num_trans = (png_uint_16)num_trans;
  197701. info_ptr->valid |= PNG_INFO_tRNS;
  197702. }
  197703. #endif
  197704. #if defined(PNG_sPLT_SUPPORTED)
  197705. void PNGAPI
  197706. png_set_sPLT(png_structp png_ptr,
  197707. png_infop info_ptr, png_sPLT_tp entries, int nentries)
  197708. {
  197709. png_sPLT_tp np;
  197710. int i;
  197711. if (png_ptr == NULL || info_ptr == NULL)
  197712. return;
  197713. np = (png_sPLT_tp)png_malloc_warn(png_ptr,
  197714. (info_ptr->splt_palettes_num + nentries) * png_sizeof(png_sPLT_t));
  197715. if (np == NULL)
  197716. {
  197717. png_warning(png_ptr, "No memory for sPLT palettes.");
  197718. return;
  197719. }
  197720. png_memcpy(np, info_ptr->splt_palettes,
  197721. info_ptr->splt_palettes_num * png_sizeof(png_sPLT_t));
  197722. png_free(png_ptr, info_ptr->splt_palettes);
  197723. info_ptr->splt_palettes=NULL;
  197724. for (i = 0; i < nentries; i++)
  197725. {
  197726. png_sPLT_tp to = np + info_ptr->splt_palettes_num + i;
  197727. png_sPLT_tp from = entries + i;
  197728. to->name = (png_charp)png_malloc_warn(png_ptr,
  197729. png_strlen(from->name) + 1);
  197730. if (to->name == NULL)
  197731. {
  197732. png_warning(png_ptr,
  197733. "Out of memory while processing sPLT chunk");
  197734. }
  197735. /* TODO: use png_malloc_warn */
  197736. png_strncpy(to->name, from->name, png_strlen(from->name)+1);
  197737. to->entries = (png_sPLT_entryp)png_malloc_warn(png_ptr,
  197738. from->nentries * png_sizeof(png_sPLT_entry));
  197739. /* TODO: use png_malloc_warn */
  197740. png_memcpy(to->entries, from->entries,
  197741. from->nentries * png_sizeof(png_sPLT_entry));
  197742. if (to->entries == NULL)
  197743. {
  197744. png_warning(png_ptr,
  197745. "Out of memory while processing sPLT chunk");
  197746. png_free(png_ptr,to->name);
  197747. to->name = NULL;
  197748. }
  197749. to->nentries = from->nentries;
  197750. to->depth = from->depth;
  197751. }
  197752. info_ptr->splt_palettes = np;
  197753. info_ptr->splt_palettes_num += nentries;
  197754. info_ptr->valid |= PNG_INFO_sPLT;
  197755. #ifdef PNG_FREE_ME_SUPPORTED
  197756. info_ptr->free_me |= PNG_FREE_SPLT;
  197757. #endif
  197758. }
  197759. #endif /* PNG_sPLT_SUPPORTED */
  197760. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  197761. void PNGAPI
  197762. png_set_unknown_chunks(png_structp png_ptr,
  197763. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns)
  197764. {
  197765. png_unknown_chunkp np;
  197766. int i;
  197767. if (png_ptr == NULL || info_ptr == NULL || num_unknowns == 0)
  197768. return;
  197769. np = (png_unknown_chunkp)png_malloc_warn(png_ptr,
  197770. (info_ptr->unknown_chunks_num + num_unknowns) *
  197771. png_sizeof(png_unknown_chunk));
  197772. if (np == NULL)
  197773. {
  197774. png_warning(png_ptr,
  197775. "Out of memory while processing unknown chunk.");
  197776. return;
  197777. }
  197778. png_memcpy(np, info_ptr->unknown_chunks,
  197779. info_ptr->unknown_chunks_num * png_sizeof(png_unknown_chunk));
  197780. png_free(png_ptr, info_ptr->unknown_chunks);
  197781. info_ptr->unknown_chunks=NULL;
  197782. for (i = 0; i < num_unknowns; i++)
  197783. {
  197784. png_unknown_chunkp to = np + info_ptr->unknown_chunks_num + i;
  197785. png_unknown_chunkp from = unknowns + i;
  197786. png_strncpy((png_charp)to->name, (png_charp)from->name, 5);
  197787. to->data = (png_bytep)png_malloc_warn(png_ptr, from->size);
  197788. if (to->data == NULL)
  197789. {
  197790. png_warning(png_ptr,
  197791. "Out of memory while processing unknown chunk.");
  197792. }
  197793. else
  197794. {
  197795. png_memcpy(to->data, from->data, from->size);
  197796. to->size = from->size;
  197797. /* note our location in the read or write sequence */
  197798. to->location = (png_byte)(png_ptr->mode & 0xff);
  197799. }
  197800. }
  197801. info_ptr->unknown_chunks = np;
  197802. info_ptr->unknown_chunks_num += num_unknowns;
  197803. #ifdef PNG_FREE_ME_SUPPORTED
  197804. info_ptr->free_me |= PNG_FREE_UNKN;
  197805. #endif
  197806. }
  197807. void PNGAPI
  197808. png_set_unknown_chunk_location(png_structp png_ptr, png_infop info_ptr,
  197809. int chunk, int location)
  197810. {
  197811. if(png_ptr != NULL && info_ptr != NULL && chunk >= 0 && chunk <
  197812. (int)info_ptr->unknown_chunks_num)
  197813. info_ptr->unknown_chunks[chunk].location = (png_byte)location;
  197814. }
  197815. #endif
  197816. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  197817. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  197818. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  197819. void PNGAPI
  197820. png_permit_empty_plte (png_structp png_ptr, int empty_plte_permitted)
  197821. {
  197822. /* This function is deprecated in favor of png_permit_mng_features()
  197823. and will be removed from libpng-1.3.0 */
  197824. png_debug(1, "in png_permit_empty_plte, DEPRECATED.\n");
  197825. if (png_ptr == NULL)
  197826. return;
  197827. png_ptr->mng_features_permitted = (png_byte)
  197828. ((png_ptr->mng_features_permitted & (~(PNG_FLAG_MNG_EMPTY_PLTE))) |
  197829. ((empty_plte_permitted & PNG_FLAG_MNG_EMPTY_PLTE)));
  197830. }
  197831. #endif
  197832. #endif
  197833. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  197834. png_uint_32 PNGAPI
  197835. png_permit_mng_features (png_structp png_ptr, png_uint_32 mng_features)
  197836. {
  197837. png_debug(1, "in png_permit_mng_features\n");
  197838. if (png_ptr == NULL)
  197839. return (png_uint_32)0;
  197840. png_ptr->mng_features_permitted =
  197841. (png_byte)(mng_features & PNG_ALL_MNG_FEATURES);
  197842. return (png_uint_32)png_ptr->mng_features_permitted;
  197843. }
  197844. #endif
  197845. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  197846. void PNGAPI
  197847. png_set_keep_unknown_chunks(png_structp png_ptr, int keep, png_bytep
  197848. chunk_list, int num_chunks)
  197849. {
  197850. png_bytep new_list, p;
  197851. int i, old_num_chunks;
  197852. if (png_ptr == NULL)
  197853. return;
  197854. if (num_chunks == 0)
  197855. {
  197856. if(keep == PNG_HANDLE_CHUNK_ALWAYS || keep == PNG_HANDLE_CHUNK_IF_SAFE)
  197857. png_ptr->flags |= PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  197858. else
  197859. png_ptr->flags &= ~PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  197860. if(keep == PNG_HANDLE_CHUNK_ALWAYS)
  197861. png_ptr->flags |= PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  197862. else
  197863. png_ptr->flags &= ~PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  197864. return;
  197865. }
  197866. if (chunk_list == NULL)
  197867. return;
  197868. old_num_chunks=png_ptr->num_chunk_list;
  197869. new_list=(png_bytep)png_malloc(png_ptr,
  197870. (png_uint_32)(5*(num_chunks+old_num_chunks)));
  197871. if(png_ptr->chunk_list != NULL)
  197872. {
  197873. png_memcpy(new_list, png_ptr->chunk_list,
  197874. (png_size_t)(5*old_num_chunks));
  197875. png_free(png_ptr, png_ptr->chunk_list);
  197876. png_ptr->chunk_list=NULL;
  197877. }
  197878. png_memcpy(new_list+5*old_num_chunks, chunk_list,
  197879. (png_size_t)(5*num_chunks));
  197880. for (p=new_list+5*old_num_chunks+4, i=0; i<num_chunks; i++, p+=5)
  197881. *p=(png_byte)keep;
  197882. png_ptr->num_chunk_list=old_num_chunks+num_chunks;
  197883. png_ptr->chunk_list=new_list;
  197884. #ifdef PNG_FREE_ME_SUPPORTED
  197885. png_ptr->free_me |= PNG_FREE_LIST;
  197886. #endif
  197887. }
  197888. #endif
  197889. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  197890. void PNGAPI
  197891. png_set_read_user_chunk_fn(png_structp png_ptr, png_voidp user_chunk_ptr,
  197892. png_user_chunk_ptr read_user_chunk_fn)
  197893. {
  197894. png_debug(1, "in png_set_read_user_chunk_fn\n");
  197895. if (png_ptr == NULL)
  197896. return;
  197897. png_ptr->read_user_chunk_fn = read_user_chunk_fn;
  197898. png_ptr->user_chunk_ptr = user_chunk_ptr;
  197899. }
  197900. #endif
  197901. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  197902. void PNGAPI
  197903. png_set_rows(png_structp png_ptr, png_infop info_ptr, png_bytepp row_pointers)
  197904. {
  197905. png_debug1(1, "in %s storage function\n", "rows");
  197906. if (png_ptr == NULL || info_ptr == NULL)
  197907. return;
  197908. if(info_ptr->row_pointers && (info_ptr->row_pointers != row_pointers))
  197909. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  197910. info_ptr->row_pointers = row_pointers;
  197911. if(row_pointers)
  197912. info_ptr->valid |= PNG_INFO_IDAT;
  197913. }
  197914. #endif
  197915. #ifdef PNG_WRITE_SUPPORTED
  197916. void PNGAPI
  197917. png_set_compression_buffer_size(png_structp png_ptr, png_uint_32 size)
  197918. {
  197919. if (png_ptr == NULL)
  197920. return;
  197921. if(png_ptr->zbuf)
  197922. png_free(png_ptr, png_ptr->zbuf);
  197923. png_ptr->zbuf_size = (png_size_t)size;
  197924. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr, size);
  197925. png_ptr->zstream.next_out = png_ptr->zbuf;
  197926. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  197927. }
  197928. #endif
  197929. void PNGAPI
  197930. png_set_invalid(png_structp png_ptr, png_infop info_ptr, int mask)
  197931. {
  197932. if (png_ptr && info_ptr)
  197933. info_ptr->valid &= ~(mask);
  197934. }
  197935. #ifndef PNG_1_0_X
  197936. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  197937. /* function was added to libpng 1.2.0 and should always exist by default */
  197938. void PNGAPI
  197939. png_set_asm_flags (png_structp png_ptr, png_uint_32)
  197940. {
  197941. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  197942. if (png_ptr != NULL)
  197943. png_ptr->asm_flags = 0;
  197944. }
  197945. /* this function was added to libpng 1.2.0 */
  197946. void PNGAPI
  197947. png_set_mmx_thresholds (png_structp png_ptr,
  197948. png_byte,
  197949. png_uint_32)
  197950. {
  197951. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  197952. if (png_ptr == NULL)
  197953. return;
  197954. }
  197955. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  197956. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  197957. /* this function was added to libpng 1.2.6 */
  197958. void PNGAPI
  197959. png_set_user_limits (png_structp png_ptr, png_uint_32 user_width_max,
  197960. png_uint_32 user_height_max)
  197961. {
  197962. /* Images with dimensions larger than these limits will be
  197963. * rejected by png_set_IHDR(). To accept any PNG datastream
  197964. * regardless of dimensions, set both limits to 0x7ffffffL.
  197965. */
  197966. if(png_ptr == NULL) return;
  197967. png_ptr->user_width_max = user_width_max;
  197968. png_ptr->user_height_max = user_height_max;
  197969. }
  197970. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  197971. #endif /* ?PNG_1_0_X */
  197972. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  197973. /*** End of inlined file: pngset.c ***/
  197974. /*** Start of inlined file: pngtrans.c ***/
  197975. /* pngtrans.c - transforms the data in a row (used by both readers and writers)
  197976. *
  197977. * Last changed in libpng 1.2.17 May 15, 2007
  197978. * For conditions of distribution and use, see copyright notice in png.h
  197979. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  197980. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  197981. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  197982. */
  197983. #define PNG_INTERNAL
  197984. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  197985. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  197986. /* turn on BGR-to-RGB mapping */
  197987. void PNGAPI
  197988. png_set_bgr(png_structp png_ptr)
  197989. {
  197990. png_debug(1, "in png_set_bgr\n");
  197991. if(png_ptr == NULL) return;
  197992. png_ptr->transformations |= PNG_BGR;
  197993. }
  197994. #endif
  197995. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  197996. /* turn on 16 bit byte swapping */
  197997. void PNGAPI
  197998. png_set_swap(png_structp png_ptr)
  197999. {
  198000. png_debug(1, "in png_set_swap\n");
  198001. if(png_ptr == NULL) return;
  198002. if (png_ptr->bit_depth == 16)
  198003. png_ptr->transformations |= PNG_SWAP_BYTES;
  198004. }
  198005. #endif
  198006. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  198007. /* turn on pixel packing */
  198008. void PNGAPI
  198009. png_set_packing(png_structp png_ptr)
  198010. {
  198011. png_debug(1, "in png_set_packing\n");
  198012. if(png_ptr == NULL) return;
  198013. if (png_ptr->bit_depth < 8)
  198014. {
  198015. png_ptr->transformations |= PNG_PACK;
  198016. png_ptr->usr_bit_depth = 8;
  198017. }
  198018. }
  198019. #endif
  198020. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  198021. /* turn on packed pixel swapping */
  198022. void PNGAPI
  198023. png_set_packswap(png_structp png_ptr)
  198024. {
  198025. png_debug(1, "in png_set_packswap\n");
  198026. if(png_ptr == NULL) return;
  198027. if (png_ptr->bit_depth < 8)
  198028. png_ptr->transformations |= PNG_PACKSWAP;
  198029. }
  198030. #endif
  198031. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  198032. void PNGAPI
  198033. png_set_shift(png_structp png_ptr, png_color_8p true_bits)
  198034. {
  198035. png_debug(1, "in png_set_shift\n");
  198036. if(png_ptr == NULL) return;
  198037. png_ptr->transformations |= PNG_SHIFT;
  198038. png_ptr->shift = *true_bits;
  198039. }
  198040. #endif
  198041. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  198042. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  198043. int PNGAPI
  198044. png_set_interlace_handling(png_structp png_ptr)
  198045. {
  198046. png_debug(1, "in png_set_interlace handling\n");
  198047. if (png_ptr && png_ptr->interlaced)
  198048. {
  198049. png_ptr->transformations |= PNG_INTERLACE;
  198050. return (7);
  198051. }
  198052. return (1);
  198053. }
  198054. #endif
  198055. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  198056. /* Add a filler byte on read, or remove a filler or alpha byte on write.
  198057. * The filler type has changed in v0.95 to allow future 2-byte fillers
  198058. * for 48-bit input data, as well as to avoid problems with some compilers
  198059. * that don't like bytes as parameters.
  198060. */
  198061. void PNGAPI
  198062. png_set_filler(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  198063. {
  198064. png_debug(1, "in png_set_filler\n");
  198065. if(png_ptr == NULL) return;
  198066. png_ptr->transformations |= PNG_FILLER;
  198067. png_ptr->filler = (png_byte)filler;
  198068. if (filler_loc == PNG_FILLER_AFTER)
  198069. png_ptr->flags |= PNG_FLAG_FILLER_AFTER;
  198070. else
  198071. png_ptr->flags &= ~PNG_FLAG_FILLER_AFTER;
  198072. /* This should probably go in the "do_read_filler" routine.
  198073. * I attempted to do that in libpng-1.0.1a but that caused problems
  198074. * so I restored it in libpng-1.0.2a
  198075. */
  198076. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  198077. {
  198078. png_ptr->usr_channels = 4;
  198079. }
  198080. /* Also I added this in libpng-1.0.2a (what happens when we expand
  198081. * a less-than-8-bit grayscale to GA? */
  198082. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY && png_ptr->bit_depth >= 8)
  198083. {
  198084. png_ptr->usr_channels = 2;
  198085. }
  198086. }
  198087. #if !defined(PNG_1_0_X)
  198088. /* Added to libpng-1.2.7 */
  198089. void PNGAPI
  198090. png_set_add_alpha(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  198091. {
  198092. png_debug(1, "in png_set_add_alpha\n");
  198093. if(png_ptr == NULL) return;
  198094. png_set_filler(png_ptr, filler, filler_loc);
  198095. png_ptr->transformations |= PNG_ADD_ALPHA;
  198096. }
  198097. #endif
  198098. #endif
  198099. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  198100. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  198101. void PNGAPI
  198102. png_set_swap_alpha(png_structp png_ptr)
  198103. {
  198104. png_debug(1, "in png_set_swap_alpha\n");
  198105. if(png_ptr == NULL) return;
  198106. png_ptr->transformations |= PNG_SWAP_ALPHA;
  198107. }
  198108. #endif
  198109. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  198110. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  198111. void PNGAPI
  198112. png_set_invert_alpha(png_structp png_ptr)
  198113. {
  198114. png_debug(1, "in png_set_invert_alpha\n");
  198115. if(png_ptr == NULL) return;
  198116. png_ptr->transformations |= PNG_INVERT_ALPHA;
  198117. }
  198118. #endif
  198119. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  198120. void PNGAPI
  198121. png_set_invert_mono(png_structp png_ptr)
  198122. {
  198123. png_debug(1, "in png_set_invert_mono\n");
  198124. if(png_ptr == NULL) return;
  198125. png_ptr->transformations |= PNG_INVERT_MONO;
  198126. }
  198127. /* invert monochrome grayscale data */
  198128. void /* PRIVATE */
  198129. png_do_invert(png_row_infop row_info, png_bytep row)
  198130. {
  198131. png_debug(1, "in png_do_invert\n");
  198132. /* This test removed from libpng version 1.0.13 and 1.2.0:
  198133. * if (row_info->bit_depth == 1 &&
  198134. */
  198135. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198136. if (row == NULL || row_info == NULL)
  198137. return;
  198138. #endif
  198139. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  198140. {
  198141. png_bytep rp = row;
  198142. png_uint_32 i;
  198143. png_uint_32 istop = row_info->rowbytes;
  198144. for (i = 0; i < istop; i++)
  198145. {
  198146. *rp = (png_byte)(~(*rp));
  198147. rp++;
  198148. }
  198149. }
  198150. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  198151. row_info->bit_depth == 8)
  198152. {
  198153. png_bytep rp = row;
  198154. png_uint_32 i;
  198155. png_uint_32 istop = row_info->rowbytes;
  198156. for (i = 0; i < istop; i+=2)
  198157. {
  198158. *rp = (png_byte)(~(*rp));
  198159. rp+=2;
  198160. }
  198161. }
  198162. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  198163. row_info->bit_depth == 16)
  198164. {
  198165. png_bytep rp = row;
  198166. png_uint_32 i;
  198167. png_uint_32 istop = row_info->rowbytes;
  198168. for (i = 0; i < istop; i+=4)
  198169. {
  198170. *rp = (png_byte)(~(*rp));
  198171. *(rp+1) = (png_byte)(~(*(rp+1)));
  198172. rp+=4;
  198173. }
  198174. }
  198175. }
  198176. #endif
  198177. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  198178. /* swaps byte order on 16 bit depth images */
  198179. void /* PRIVATE */
  198180. png_do_swap(png_row_infop row_info, png_bytep row)
  198181. {
  198182. png_debug(1, "in png_do_swap\n");
  198183. if (
  198184. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198185. row != NULL && row_info != NULL &&
  198186. #endif
  198187. row_info->bit_depth == 16)
  198188. {
  198189. png_bytep rp = row;
  198190. png_uint_32 i;
  198191. png_uint_32 istop= row_info->width * row_info->channels;
  198192. for (i = 0; i < istop; i++, rp += 2)
  198193. {
  198194. png_byte t = *rp;
  198195. *rp = *(rp + 1);
  198196. *(rp + 1) = t;
  198197. }
  198198. }
  198199. }
  198200. #endif
  198201. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  198202. static PNG_CONST png_byte onebppswaptable[256] = {
  198203. 0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0,
  198204. 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0,
  198205. 0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8,
  198206. 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8,
  198207. 0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4,
  198208. 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4,
  198209. 0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC,
  198210. 0x1C, 0x9C, 0x5C, 0xDC, 0x3C, 0xBC, 0x7C, 0xFC,
  198211. 0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2,
  198212. 0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2,
  198213. 0x0A, 0x8A, 0x4A, 0xCA, 0x2A, 0xAA, 0x6A, 0xEA,
  198214. 0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA,
  198215. 0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6,
  198216. 0x16, 0x96, 0x56, 0xD6, 0x36, 0xB6, 0x76, 0xF6,
  198217. 0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE,
  198218. 0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE,
  198219. 0x01, 0x81, 0x41, 0xC1, 0x21, 0xA1, 0x61, 0xE1,
  198220. 0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1,
  198221. 0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9,
  198222. 0x19, 0x99, 0x59, 0xD9, 0x39, 0xB9, 0x79, 0xF9,
  198223. 0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5,
  198224. 0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5,
  198225. 0x0D, 0x8D, 0x4D, 0xCD, 0x2D, 0xAD, 0x6D, 0xED,
  198226. 0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD,
  198227. 0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3,
  198228. 0x13, 0x93, 0x53, 0xD3, 0x33, 0xB3, 0x73, 0xF3,
  198229. 0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB,
  198230. 0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB,
  198231. 0x07, 0x87, 0x47, 0xC7, 0x27, 0xA7, 0x67, 0xE7,
  198232. 0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7,
  198233. 0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF,
  198234. 0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF
  198235. };
  198236. static PNG_CONST png_byte twobppswaptable[256] = {
  198237. 0x00, 0x40, 0x80, 0xC0, 0x10, 0x50, 0x90, 0xD0,
  198238. 0x20, 0x60, 0xA0, 0xE0, 0x30, 0x70, 0xB0, 0xF0,
  198239. 0x04, 0x44, 0x84, 0xC4, 0x14, 0x54, 0x94, 0xD4,
  198240. 0x24, 0x64, 0xA4, 0xE4, 0x34, 0x74, 0xB4, 0xF4,
  198241. 0x08, 0x48, 0x88, 0xC8, 0x18, 0x58, 0x98, 0xD8,
  198242. 0x28, 0x68, 0xA8, 0xE8, 0x38, 0x78, 0xB8, 0xF8,
  198243. 0x0C, 0x4C, 0x8C, 0xCC, 0x1C, 0x5C, 0x9C, 0xDC,
  198244. 0x2C, 0x6C, 0xAC, 0xEC, 0x3C, 0x7C, 0xBC, 0xFC,
  198245. 0x01, 0x41, 0x81, 0xC1, 0x11, 0x51, 0x91, 0xD1,
  198246. 0x21, 0x61, 0xA1, 0xE1, 0x31, 0x71, 0xB1, 0xF1,
  198247. 0x05, 0x45, 0x85, 0xC5, 0x15, 0x55, 0x95, 0xD5,
  198248. 0x25, 0x65, 0xA5, 0xE5, 0x35, 0x75, 0xB5, 0xF5,
  198249. 0x09, 0x49, 0x89, 0xC9, 0x19, 0x59, 0x99, 0xD9,
  198250. 0x29, 0x69, 0xA9, 0xE9, 0x39, 0x79, 0xB9, 0xF9,
  198251. 0x0D, 0x4D, 0x8D, 0xCD, 0x1D, 0x5D, 0x9D, 0xDD,
  198252. 0x2D, 0x6D, 0xAD, 0xED, 0x3D, 0x7D, 0xBD, 0xFD,
  198253. 0x02, 0x42, 0x82, 0xC2, 0x12, 0x52, 0x92, 0xD2,
  198254. 0x22, 0x62, 0xA2, 0xE2, 0x32, 0x72, 0xB2, 0xF2,
  198255. 0x06, 0x46, 0x86, 0xC6, 0x16, 0x56, 0x96, 0xD6,
  198256. 0x26, 0x66, 0xA6, 0xE6, 0x36, 0x76, 0xB6, 0xF6,
  198257. 0x0A, 0x4A, 0x8A, 0xCA, 0x1A, 0x5A, 0x9A, 0xDA,
  198258. 0x2A, 0x6A, 0xAA, 0xEA, 0x3A, 0x7A, 0xBA, 0xFA,
  198259. 0x0E, 0x4E, 0x8E, 0xCE, 0x1E, 0x5E, 0x9E, 0xDE,
  198260. 0x2E, 0x6E, 0xAE, 0xEE, 0x3E, 0x7E, 0xBE, 0xFE,
  198261. 0x03, 0x43, 0x83, 0xC3, 0x13, 0x53, 0x93, 0xD3,
  198262. 0x23, 0x63, 0xA3, 0xE3, 0x33, 0x73, 0xB3, 0xF3,
  198263. 0x07, 0x47, 0x87, 0xC7, 0x17, 0x57, 0x97, 0xD7,
  198264. 0x27, 0x67, 0xA7, 0xE7, 0x37, 0x77, 0xB7, 0xF7,
  198265. 0x0B, 0x4B, 0x8B, 0xCB, 0x1B, 0x5B, 0x9B, 0xDB,
  198266. 0x2B, 0x6B, 0xAB, 0xEB, 0x3B, 0x7B, 0xBB, 0xFB,
  198267. 0x0F, 0x4F, 0x8F, 0xCF, 0x1F, 0x5F, 0x9F, 0xDF,
  198268. 0x2F, 0x6F, 0xAF, 0xEF, 0x3F, 0x7F, 0xBF, 0xFF
  198269. };
  198270. static PNG_CONST png_byte fourbppswaptable[256] = {
  198271. 0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70,
  198272. 0x80, 0x90, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, 0xF0,
  198273. 0x01, 0x11, 0x21, 0x31, 0x41, 0x51, 0x61, 0x71,
  198274. 0x81, 0x91, 0xA1, 0xB1, 0xC1, 0xD1, 0xE1, 0xF1,
  198275. 0x02, 0x12, 0x22, 0x32, 0x42, 0x52, 0x62, 0x72,
  198276. 0x82, 0x92, 0xA2, 0xB2, 0xC2, 0xD2, 0xE2, 0xF2,
  198277. 0x03, 0x13, 0x23, 0x33, 0x43, 0x53, 0x63, 0x73,
  198278. 0x83, 0x93, 0xA3, 0xB3, 0xC3, 0xD3, 0xE3, 0xF3,
  198279. 0x04, 0x14, 0x24, 0x34, 0x44, 0x54, 0x64, 0x74,
  198280. 0x84, 0x94, 0xA4, 0xB4, 0xC4, 0xD4, 0xE4, 0xF4,
  198281. 0x05, 0x15, 0x25, 0x35, 0x45, 0x55, 0x65, 0x75,
  198282. 0x85, 0x95, 0xA5, 0xB5, 0xC5, 0xD5, 0xE5, 0xF5,
  198283. 0x06, 0x16, 0x26, 0x36, 0x46, 0x56, 0x66, 0x76,
  198284. 0x86, 0x96, 0xA6, 0xB6, 0xC6, 0xD6, 0xE6, 0xF6,
  198285. 0x07, 0x17, 0x27, 0x37, 0x47, 0x57, 0x67, 0x77,
  198286. 0x87, 0x97, 0xA7, 0xB7, 0xC7, 0xD7, 0xE7, 0xF7,
  198287. 0x08, 0x18, 0x28, 0x38, 0x48, 0x58, 0x68, 0x78,
  198288. 0x88, 0x98, 0xA8, 0xB8, 0xC8, 0xD8, 0xE8, 0xF8,
  198289. 0x09, 0x19, 0x29, 0x39, 0x49, 0x59, 0x69, 0x79,
  198290. 0x89, 0x99, 0xA9, 0xB9, 0xC9, 0xD9, 0xE9, 0xF9,
  198291. 0x0A, 0x1A, 0x2A, 0x3A, 0x4A, 0x5A, 0x6A, 0x7A,
  198292. 0x8A, 0x9A, 0xAA, 0xBA, 0xCA, 0xDA, 0xEA, 0xFA,
  198293. 0x0B, 0x1B, 0x2B, 0x3B, 0x4B, 0x5B, 0x6B, 0x7B,
  198294. 0x8B, 0x9B, 0xAB, 0xBB, 0xCB, 0xDB, 0xEB, 0xFB,
  198295. 0x0C, 0x1C, 0x2C, 0x3C, 0x4C, 0x5C, 0x6C, 0x7C,
  198296. 0x8C, 0x9C, 0xAC, 0xBC, 0xCC, 0xDC, 0xEC, 0xFC,
  198297. 0x0D, 0x1D, 0x2D, 0x3D, 0x4D, 0x5D, 0x6D, 0x7D,
  198298. 0x8D, 0x9D, 0xAD, 0xBD, 0xCD, 0xDD, 0xED, 0xFD,
  198299. 0x0E, 0x1E, 0x2E, 0x3E, 0x4E, 0x5E, 0x6E, 0x7E,
  198300. 0x8E, 0x9E, 0xAE, 0xBE, 0xCE, 0xDE, 0xEE, 0xFE,
  198301. 0x0F, 0x1F, 0x2F, 0x3F, 0x4F, 0x5F, 0x6F, 0x7F,
  198302. 0x8F, 0x9F, 0xAF, 0xBF, 0xCF, 0xDF, 0xEF, 0xFF
  198303. };
  198304. /* swaps pixel packing order within bytes */
  198305. void /* PRIVATE */
  198306. png_do_packswap(png_row_infop row_info, png_bytep row)
  198307. {
  198308. png_debug(1, "in png_do_packswap\n");
  198309. if (
  198310. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198311. row != NULL && row_info != NULL &&
  198312. #endif
  198313. row_info->bit_depth < 8)
  198314. {
  198315. png_bytep rp, end, table;
  198316. end = row + row_info->rowbytes;
  198317. if (row_info->bit_depth == 1)
  198318. table = (png_bytep)onebppswaptable;
  198319. else if (row_info->bit_depth == 2)
  198320. table = (png_bytep)twobppswaptable;
  198321. else if (row_info->bit_depth == 4)
  198322. table = (png_bytep)fourbppswaptable;
  198323. else
  198324. return;
  198325. for (rp = row; rp < end; rp++)
  198326. *rp = table[*rp];
  198327. }
  198328. }
  198329. #endif /* PNG_READ_PACKSWAP_SUPPORTED or PNG_WRITE_PACKSWAP_SUPPORTED */
  198330. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  198331. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  198332. /* remove filler or alpha byte(s) */
  198333. void /* PRIVATE */
  198334. png_do_strip_filler(png_row_infop row_info, png_bytep row, png_uint_32 flags)
  198335. {
  198336. png_debug(1, "in png_do_strip_filler\n");
  198337. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198338. if (row != NULL && row_info != NULL)
  198339. #endif
  198340. {
  198341. png_bytep sp=row;
  198342. png_bytep dp=row;
  198343. png_uint_32 row_width=row_info->width;
  198344. png_uint_32 i;
  198345. if ((row_info->color_type == PNG_COLOR_TYPE_RGB ||
  198346. (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  198347. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  198348. row_info->channels == 4)
  198349. {
  198350. if (row_info->bit_depth == 8)
  198351. {
  198352. /* This converts from RGBX or RGBA to RGB */
  198353. if (flags & PNG_FLAG_FILLER_AFTER)
  198354. {
  198355. dp+=3; sp+=4;
  198356. for (i = 1; i < row_width; i++)
  198357. {
  198358. *dp++ = *sp++;
  198359. *dp++ = *sp++;
  198360. *dp++ = *sp++;
  198361. sp++;
  198362. }
  198363. }
  198364. /* This converts from XRGB or ARGB to RGB */
  198365. else
  198366. {
  198367. for (i = 0; i < row_width; i++)
  198368. {
  198369. sp++;
  198370. *dp++ = *sp++;
  198371. *dp++ = *sp++;
  198372. *dp++ = *sp++;
  198373. }
  198374. }
  198375. row_info->pixel_depth = 24;
  198376. row_info->rowbytes = row_width * 3;
  198377. }
  198378. else /* if (row_info->bit_depth == 16) */
  198379. {
  198380. if (flags & PNG_FLAG_FILLER_AFTER)
  198381. {
  198382. /* This converts from RRGGBBXX or RRGGBBAA to RRGGBB */
  198383. sp += 8; dp += 6;
  198384. for (i = 1; i < row_width; i++)
  198385. {
  198386. /* This could be (although png_memcpy is probably slower):
  198387. png_memcpy(dp, sp, 6);
  198388. sp += 8;
  198389. dp += 6;
  198390. */
  198391. *dp++ = *sp++;
  198392. *dp++ = *sp++;
  198393. *dp++ = *sp++;
  198394. *dp++ = *sp++;
  198395. *dp++ = *sp++;
  198396. *dp++ = *sp++;
  198397. sp += 2;
  198398. }
  198399. }
  198400. else
  198401. {
  198402. /* This converts from XXRRGGBB or AARRGGBB to RRGGBB */
  198403. for (i = 0; i < row_width; i++)
  198404. {
  198405. /* This could be (although png_memcpy is probably slower):
  198406. png_memcpy(dp, sp, 6);
  198407. sp += 8;
  198408. dp += 6;
  198409. */
  198410. sp+=2;
  198411. *dp++ = *sp++;
  198412. *dp++ = *sp++;
  198413. *dp++ = *sp++;
  198414. *dp++ = *sp++;
  198415. *dp++ = *sp++;
  198416. *dp++ = *sp++;
  198417. }
  198418. }
  198419. row_info->pixel_depth = 48;
  198420. row_info->rowbytes = row_width * 6;
  198421. }
  198422. row_info->channels = 3;
  198423. }
  198424. else if ((row_info->color_type == PNG_COLOR_TYPE_GRAY ||
  198425. (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  198426. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  198427. row_info->channels == 2)
  198428. {
  198429. if (row_info->bit_depth == 8)
  198430. {
  198431. /* This converts from GX or GA to G */
  198432. if (flags & PNG_FLAG_FILLER_AFTER)
  198433. {
  198434. for (i = 0; i < row_width; i++)
  198435. {
  198436. *dp++ = *sp++;
  198437. sp++;
  198438. }
  198439. }
  198440. /* This converts from XG or AG to G */
  198441. else
  198442. {
  198443. for (i = 0; i < row_width; i++)
  198444. {
  198445. sp++;
  198446. *dp++ = *sp++;
  198447. }
  198448. }
  198449. row_info->pixel_depth = 8;
  198450. row_info->rowbytes = row_width;
  198451. }
  198452. else /* if (row_info->bit_depth == 16) */
  198453. {
  198454. if (flags & PNG_FLAG_FILLER_AFTER)
  198455. {
  198456. /* This converts from GGXX or GGAA to GG */
  198457. sp += 4; dp += 2;
  198458. for (i = 1; i < row_width; i++)
  198459. {
  198460. *dp++ = *sp++;
  198461. *dp++ = *sp++;
  198462. sp += 2;
  198463. }
  198464. }
  198465. else
  198466. {
  198467. /* This converts from XXGG or AAGG to GG */
  198468. for (i = 0; i < row_width; i++)
  198469. {
  198470. sp += 2;
  198471. *dp++ = *sp++;
  198472. *dp++ = *sp++;
  198473. }
  198474. }
  198475. row_info->pixel_depth = 16;
  198476. row_info->rowbytes = row_width * 2;
  198477. }
  198478. row_info->channels = 1;
  198479. }
  198480. if (flags & PNG_FLAG_STRIP_ALPHA)
  198481. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  198482. }
  198483. }
  198484. #endif
  198485. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  198486. /* swaps red and blue bytes within a pixel */
  198487. void /* PRIVATE */
  198488. png_do_bgr(png_row_infop row_info, png_bytep row)
  198489. {
  198490. png_debug(1, "in png_do_bgr\n");
  198491. if (
  198492. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198493. row != NULL && row_info != NULL &&
  198494. #endif
  198495. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  198496. {
  198497. png_uint_32 row_width = row_info->width;
  198498. if (row_info->bit_depth == 8)
  198499. {
  198500. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  198501. {
  198502. png_bytep rp;
  198503. png_uint_32 i;
  198504. for (i = 0, rp = row; i < row_width; i++, rp += 3)
  198505. {
  198506. png_byte save = *rp;
  198507. *rp = *(rp + 2);
  198508. *(rp + 2) = save;
  198509. }
  198510. }
  198511. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  198512. {
  198513. png_bytep rp;
  198514. png_uint_32 i;
  198515. for (i = 0, rp = row; i < row_width; i++, rp += 4)
  198516. {
  198517. png_byte save = *rp;
  198518. *rp = *(rp + 2);
  198519. *(rp + 2) = save;
  198520. }
  198521. }
  198522. }
  198523. else if (row_info->bit_depth == 16)
  198524. {
  198525. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  198526. {
  198527. png_bytep rp;
  198528. png_uint_32 i;
  198529. for (i = 0, rp = row; i < row_width; i++, rp += 6)
  198530. {
  198531. png_byte save = *rp;
  198532. *rp = *(rp + 4);
  198533. *(rp + 4) = save;
  198534. save = *(rp + 1);
  198535. *(rp + 1) = *(rp + 5);
  198536. *(rp + 5) = save;
  198537. }
  198538. }
  198539. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  198540. {
  198541. png_bytep rp;
  198542. png_uint_32 i;
  198543. for (i = 0, rp = row; i < row_width; i++, rp += 8)
  198544. {
  198545. png_byte save = *rp;
  198546. *rp = *(rp + 4);
  198547. *(rp + 4) = save;
  198548. save = *(rp + 1);
  198549. *(rp + 1) = *(rp + 5);
  198550. *(rp + 5) = save;
  198551. }
  198552. }
  198553. }
  198554. }
  198555. }
  198556. #endif /* PNG_READ_BGR_SUPPORTED or PNG_WRITE_BGR_SUPPORTED */
  198557. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  198558. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  198559. defined(PNG_LEGACY_SUPPORTED)
  198560. void PNGAPI
  198561. png_set_user_transform_info(png_structp png_ptr, png_voidp
  198562. user_transform_ptr, int user_transform_depth, int user_transform_channels)
  198563. {
  198564. png_debug(1, "in png_set_user_transform_info\n");
  198565. if(png_ptr == NULL) return;
  198566. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  198567. png_ptr->user_transform_ptr = user_transform_ptr;
  198568. png_ptr->user_transform_depth = (png_byte)user_transform_depth;
  198569. png_ptr->user_transform_channels = (png_byte)user_transform_channels;
  198570. #else
  198571. if(user_transform_ptr || user_transform_depth || user_transform_channels)
  198572. png_warning(png_ptr,
  198573. "This version of libpng does not support user transform info");
  198574. #endif
  198575. }
  198576. #endif
  198577. /* This function returns a pointer to the user_transform_ptr associated with
  198578. * the user transform functions. The application should free any memory
  198579. * associated with this pointer before png_write_destroy and png_read_destroy
  198580. * are called.
  198581. */
  198582. png_voidp PNGAPI
  198583. png_get_user_transform_ptr(png_structp png_ptr)
  198584. {
  198585. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  198586. if (png_ptr == NULL) return (NULL);
  198587. return ((png_voidp)png_ptr->user_transform_ptr);
  198588. #else
  198589. return (NULL);
  198590. #endif
  198591. }
  198592. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  198593. /*** End of inlined file: pngtrans.c ***/
  198594. /*** Start of inlined file: pngwio.c ***/
  198595. /* pngwio.c - functions for data output
  198596. *
  198597. * Last changed in libpng 1.2.13 November 13, 2006
  198598. * For conditions of distribution and use, see copyright notice in png.h
  198599. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  198600. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  198601. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  198602. *
  198603. * This file provides a location for all output. Users who need
  198604. * special handling are expected to write functions that have the same
  198605. * arguments as these and perform similar functions, but that possibly
  198606. * use different output methods. Note that you shouldn't change these
  198607. * functions, but rather write replacement functions and then change
  198608. * them at run time with png_set_write_fn(...).
  198609. */
  198610. #define PNG_INTERNAL
  198611. #ifdef PNG_WRITE_SUPPORTED
  198612. /* Write the data to whatever output you are using. The default routine
  198613. writes to a file pointer. Note that this routine sometimes gets called
  198614. with very small lengths, so you should implement some kind of simple
  198615. buffering if you are using unbuffered writes. This should never be asked
  198616. to write more than 64K on a 16 bit machine. */
  198617. void /* PRIVATE */
  198618. png_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198619. {
  198620. if (png_ptr->write_data_fn != NULL )
  198621. (*(png_ptr->write_data_fn))(png_ptr, data, length);
  198622. else
  198623. png_error(png_ptr, "Call to NULL write function");
  198624. }
  198625. #if !defined(PNG_NO_STDIO)
  198626. /* This is the function that does the actual writing of data. If you are
  198627. not writing to a standard C stream, you should create a replacement
  198628. write_data function and use it at run time with png_set_write_fn(), rather
  198629. than changing the library. */
  198630. #ifndef USE_FAR_KEYWORD
  198631. void PNGAPI
  198632. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198633. {
  198634. png_uint_32 check;
  198635. if(png_ptr == NULL) return;
  198636. #if defined(_WIN32_WCE)
  198637. if ( !WriteFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  198638. check = 0;
  198639. #else
  198640. check = fwrite(data, 1, length, (png_FILE_p)(png_ptr->io_ptr));
  198641. #endif
  198642. if (check != length)
  198643. png_error(png_ptr, "Write Error");
  198644. }
  198645. #else
  198646. /* this is the model-independent version. Since the standard I/O library
  198647. can't handle far buffers in the medium and small models, we have to copy
  198648. the data.
  198649. */
  198650. #define NEAR_BUF_SIZE 1024
  198651. #define MIN(a,b) (a <= b ? a : b)
  198652. void PNGAPI
  198653. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198654. {
  198655. png_uint_32 check;
  198656. png_byte *near_data; /* Needs to be "png_byte *" instead of "png_bytep" */
  198657. png_FILE_p io_ptr;
  198658. if(png_ptr == NULL) return;
  198659. /* Check if data really is near. If so, use usual code. */
  198660. near_data = (png_byte *)CVT_PTR_NOCHECK(data);
  198661. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  198662. if ((png_bytep)near_data == data)
  198663. {
  198664. #if defined(_WIN32_WCE)
  198665. if ( !WriteFile(io_ptr, near_data, length, &check, NULL) )
  198666. check = 0;
  198667. #else
  198668. check = fwrite(near_data, 1, length, io_ptr);
  198669. #endif
  198670. }
  198671. else
  198672. {
  198673. png_byte buf[NEAR_BUF_SIZE];
  198674. png_size_t written, remaining, err;
  198675. check = 0;
  198676. remaining = length;
  198677. do
  198678. {
  198679. written = MIN(NEAR_BUF_SIZE, remaining);
  198680. png_memcpy(buf, data, written); /* copy far buffer to near buffer */
  198681. #if defined(_WIN32_WCE)
  198682. if ( !WriteFile(io_ptr, buf, written, &err, NULL) )
  198683. err = 0;
  198684. #else
  198685. err = fwrite(buf, 1, written, io_ptr);
  198686. #endif
  198687. if (err != written)
  198688. break;
  198689. else
  198690. check += err;
  198691. data += written;
  198692. remaining -= written;
  198693. }
  198694. while (remaining != 0);
  198695. }
  198696. if (check != length)
  198697. png_error(png_ptr, "Write Error");
  198698. }
  198699. #endif
  198700. #endif
  198701. /* This function is called to output any data pending writing (normally
  198702. to disk). After png_flush is called, there should be no data pending
  198703. writing in any buffers. */
  198704. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  198705. void /* PRIVATE */
  198706. png_flush(png_structp png_ptr)
  198707. {
  198708. if (png_ptr->output_flush_fn != NULL)
  198709. (*(png_ptr->output_flush_fn))(png_ptr);
  198710. }
  198711. #if !defined(PNG_NO_STDIO)
  198712. void PNGAPI
  198713. png_default_flush(png_structp png_ptr)
  198714. {
  198715. #if !defined(_WIN32_WCE)
  198716. png_FILE_p io_ptr;
  198717. #endif
  198718. if(png_ptr == NULL) return;
  198719. #if !defined(_WIN32_WCE)
  198720. io_ptr = (png_FILE_p)CVT_PTR((png_ptr->io_ptr));
  198721. if (io_ptr != NULL)
  198722. fflush(io_ptr);
  198723. #endif
  198724. }
  198725. #endif
  198726. #endif
  198727. /* This function allows the application to supply new output functions for
  198728. libpng if standard C streams aren't being used.
  198729. This function takes as its arguments:
  198730. png_ptr - pointer to a png output data structure
  198731. io_ptr - pointer to user supplied structure containing info about
  198732. the output functions. May be NULL.
  198733. write_data_fn - pointer to a new output function that takes as its
  198734. arguments a pointer to a png_struct, a pointer to
  198735. data to be written, and a 32-bit unsigned int that is
  198736. the number of bytes to be written. The new write
  198737. function should call png_error(png_ptr, "Error msg")
  198738. to exit and output any fatal error messages.
  198739. flush_data_fn - pointer to a new flush function that takes as its
  198740. arguments a pointer to a png_struct. After a call to
  198741. the flush function, there should be no data in any buffers
  198742. or pending transmission. If the output method doesn't do
  198743. any buffering of ouput, a function prototype must still be
  198744. supplied although it doesn't have to do anything. If
  198745. PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile
  198746. time, output_flush_fn will be ignored, although it must be
  198747. supplied for compatibility. */
  198748. void PNGAPI
  198749. png_set_write_fn(png_structp png_ptr, png_voidp io_ptr,
  198750. png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn)
  198751. {
  198752. if(png_ptr == NULL) return;
  198753. png_ptr->io_ptr = io_ptr;
  198754. #if !defined(PNG_NO_STDIO)
  198755. if (write_data_fn != NULL)
  198756. png_ptr->write_data_fn = write_data_fn;
  198757. else
  198758. png_ptr->write_data_fn = png_default_write_data;
  198759. #else
  198760. png_ptr->write_data_fn = write_data_fn;
  198761. #endif
  198762. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  198763. #if !defined(PNG_NO_STDIO)
  198764. if (output_flush_fn != NULL)
  198765. png_ptr->output_flush_fn = output_flush_fn;
  198766. else
  198767. png_ptr->output_flush_fn = png_default_flush;
  198768. #else
  198769. png_ptr->output_flush_fn = output_flush_fn;
  198770. #endif
  198771. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  198772. /* It is an error to read while writing a png file */
  198773. if (png_ptr->read_data_fn != NULL)
  198774. {
  198775. png_ptr->read_data_fn = NULL;
  198776. png_warning(png_ptr,
  198777. "Attempted to set both read_data_fn and write_data_fn in");
  198778. png_warning(png_ptr,
  198779. "the same structure. Resetting read_data_fn to NULL.");
  198780. }
  198781. }
  198782. #if defined(USE_FAR_KEYWORD)
  198783. #if defined(_MSC_VER)
  198784. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  198785. {
  198786. void *near_ptr;
  198787. void FAR *far_ptr;
  198788. FP_OFF(near_ptr) = FP_OFF(ptr);
  198789. far_ptr = (void FAR *)near_ptr;
  198790. if(check != 0)
  198791. if(FP_SEG(ptr) != FP_SEG(far_ptr))
  198792. png_error(png_ptr,"segment lost in conversion");
  198793. return(near_ptr);
  198794. }
  198795. # else
  198796. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  198797. {
  198798. void *near_ptr;
  198799. void FAR *far_ptr;
  198800. near_ptr = (void FAR *)ptr;
  198801. far_ptr = (void FAR *)near_ptr;
  198802. if(check != 0)
  198803. if(far_ptr != ptr)
  198804. png_error(png_ptr,"segment lost in conversion");
  198805. return(near_ptr);
  198806. }
  198807. # endif
  198808. # endif
  198809. #endif /* PNG_WRITE_SUPPORTED */
  198810. /*** End of inlined file: pngwio.c ***/
  198811. /*** Start of inlined file: pngwrite.c ***/
  198812. /* pngwrite.c - general routines to write a PNG file
  198813. *
  198814. * Last changed in libpng 1.2.15 January 5, 2007
  198815. * For conditions of distribution and use, see copyright notice in png.h
  198816. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  198817. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  198818. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  198819. */
  198820. /* get internal access to png.h */
  198821. #define PNG_INTERNAL
  198822. #ifdef PNG_WRITE_SUPPORTED
  198823. /* Writes all the PNG information. This is the suggested way to use the
  198824. * library. If you have a new chunk to add, make a function to write it,
  198825. * and put it in the correct location here. If you want the chunk written
  198826. * after the image data, put it in png_write_end(). I strongly encourage
  198827. * you to supply a PNG_INFO_ flag, and check info_ptr->valid before writing
  198828. * the chunk, as that will keep the code from breaking if you want to just
  198829. * write a plain PNG file. If you have long comments, I suggest writing
  198830. * them in png_write_end(), and compressing them.
  198831. */
  198832. void PNGAPI
  198833. png_write_info_before_PLTE(png_structp png_ptr, png_infop info_ptr)
  198834. {
  198835. png_debug(1, "in png_write_info_before_PLTE\n");
  198836. if (png_ptr == NULL || info_ptr == NULL)
  198837. return;
  198838. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  198839. {
  198840. png_write_sig(png_ptr); /* write PNG signature */
  198841. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  198842. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&(png_ptr->mng_features_permitted))
  198843. {
  198844. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  198845. png_ptr->mng_features_permitted=0;
  198846. }
  198847. #endif
  198848. /* write IHDR information. */
  198849. png_write_IHDR(png_ptr, info_ptr->width, info_ptr->height,
  198850. info_ptr->bit_depth, info_ptr->color_type, info_ptr->compression_type,
  198851. info_ptr->filter_type,
  198852. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  198853. info_ptr->interlace_type);
  198854. #else
  198855. 0);
  198856. #endif
  198857. /* the rest of these check to see if the valid field has the appropriate
  198858. flag set, and if it does, writes the chunk. */
  198859. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  198860. if (info_ptr->valid & PNG_INFO_gAMA)
  198861. {
  198862. # ifdef PNG_FLOATING_POINT_SUPPORTED
  198863. png_write_gAMA(png_ptr, info_ptr->gamma);
  198864. #else
  198865. #ifdef PNG_FIXED_POINT_SUPPORTED
  198866. png_write_gAMA_fixed(png_ptr, info_ptr->int_gamma);
  198867. # endif
  198868. #endif
  198869. }
  198870. #endif
  198871. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  198872. if (info_ptr->valid & PNG_INFO_sRGB)
  198873. png_write_sRGB(png_ptr, (int)info_ptr->srgb_intent);
  198874. #endif
  198875. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  198876. if (info_ptr->valid & PNG_INFO_iCCP)
  198877. png_write_iCCP(png_ptr, info_ptr->iccp_name, PNG_COMPRESSION_TYPE_BASE,
  198878. info_ptr->iccp_profile, (int)info_ptr->iccp_proflen);
  198879. #endif
  198880. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  198881. if (info_ptr->valid & PNG_INFO_sBIT)
  198882. png_write_sBIT(png_ptr, &(info_ptr->sig_bit), info_ptr->color_type);
  198883. #endif
  198884. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  198885. if (info_ptr->valid & PNG_INFO_cHRM)
  198886. {
  198887. #ifdef PNG_FLOATING_POINT_SUPPORTED
  198888. png_write_cHRM(png_ptr,
  198889. info_ptr->x_white, info_ptr->y_white,
  198890. info_ptr->x_red, info_ptr->y_red,
  198891. info_ptr->x_green, info_ptr->y_green,
  198892. info_ptr->x_blue, info_ptr->y_blue);
  198893. #else
  198894. # ifdef PNG_FIXED_POINT_SUPPORTED
  198895. png_write_cHRM_fixed(png_ptr,
  198896. info_ptr->int_x_white, info_ptr->int_y_white,
  198897. info_ptr->int_x_red, info_ptr->int_y_red,
  198898. info_ptr->int_x_green, info_ptr->int_y_green,
  198899. info_ptr->int_x_blue, info_ptr->int_y_blue);
  198900. # endif
  198901. #endif
  198902. }
  198903. #endif
  198904. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  198905. if (info_ptr->unknown_chunks_num)
  198906. {
  198907. png_unknown_chunk *up;
  198908. png_debug(5, "writing extra chunks\n");
  198909. for (up = info_ptr->unknown_chunks;
  198910. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  198911. up++)
  198912. {
  198913. int keep=png_handle_as_unknown(png_ptr, up->name);
  198914. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  198915. up->location && !(up->location & PNG_HAVE_PLTE) &&
  198916. !(up->location & PNG_HAVE_IDAT) &&
  198917. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  198918. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  198919. {
  198920. png_write_chunk(png_ptr, up->name, up->data, up->size);
  198921. }
  198922. }
  198923. }
  198924. #endif
  198925. png_ptr->mode |= PNG_WROTE_INFO_BEFORE_PLTE;
  198926. }
  198927. }
  198928. void PNGAPI
  198929. png_write_info(png_structp png_ptr, png_infop info_ptr)
  198930. {
  198931. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  198932. int i;
  198933. #endif
  198934. png_debug(1, "in png_write_info\n");
  198935. if (png_ptr == NULL || info_ptr == NULL)
  198936. return;
  198937. png_write_info_before_PLTE(png_ptr, info_ptr);
  198938. if (info_ptr->valid & PNG_INFO_PLTE)
  198939. png_write_PLTE(png_ptr, info_ptr->palette,
  198940. (png_uint_32)info_ptr->num_palette);
  198941. else if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  198942. png_error(png_ptr, "Valid palette required for paletted images");
  198943. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  198944. if (info_ptr->valid & PNG_INFO_tRNS)
  198945. {
  198946. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  198947. /* invert the alpha channel (in tRNS) */
  198948. if ((png_ptr->transformations & PNG_INVERT_ALPHA) &&
  198949. info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  198950. {
  198951. int j;
  198952. for (j=0; j<(int)info_ptr->num_trans; j++)
  198953. info_ptr->trans[j] = (png_byte)(255 - info_ptr->trans[j]);
  198954. }
  198955. #endif
  198956. png_write_tRNS(png_ptr, info_ptr->trans, &(info_ptr->trans_values),
  198957. info_ptr->num_trans, info_ptr->color_type);
  198958. }
  198959. #endif
  198960. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  198961. if (info_ptr->valid & PNG_INFO_bKGD)
  198962. png_write_bKGD(png_ptr, &(info_ptr->background), info_ptr->color_type);
  198963. #endif
  198964. #if defined(PNG_WRITE_hIST_SUPPORTED)
  198965. if (info_ptr->valid & PNG_INFO_hIST)
  198966. png_write_hIST(png_ptr, info_ptr->hist, info_ptr->num_palette);
  198967. #endif
  198968. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  198969. if (info_ptr->valid & PNG_INFO_oFFs)
  198970. png_write_oFFs(png_ptr, info_ptr->x_offset, info_ptr->y_offset,
  198971. info_ptr->offset_unit_type);
  198972. #endif
  198973. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  198974. if (info_ptr->valid & PNG_INFO_pCAL)
  198975. png_write_pCAL(png_ptr, info_ptr->pcal_purpose, info_ptr->pcal_X0,
  198976. info_ptr->pcal_X1, info_ptr->pcal_type, info_ptr->pcal_nparams,
  198977. info_ptr->pcal_units, info_ptr->pcal_params);
  198978. #endif
  198979. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  198980. if (info_ptr->valid & PNG_INFO_sCAL)
  198981. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  198982. png_write_sCAL(png_ptr, (int)info_ptr->scal_unit,
  198983. info_ptr->scal_pixel_width, info_ptr->scal_pixel_height);
  198984. #else
  198985. #ifdef PNG_FIXED_POINT_SUPPORTED
  198986. png_write_sCAL_s(png_ptr, (int)info_ptr->scal_unit,
  198987. info_ptr->scal_s_width, info_ptr->scal_s_height);
  198988. #else
  198989. png_warning(png_ptr,
  198990. "png_write_sCAL not supported; sCAL chunk not written.");
  198991. #endif
  198992. #endif
  198993. #endif
  198994. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  198995. if (info_ptr->valid & PNG_INFO_pHYs)
  198996. png_write_pHYs(png_ptr, info_ptr->x_pixels_per_unit,
  198997. info_ptr->y_pixels_per_unit, info_ptr->phys_unit_type);
  198998. #endif
  198999. #if defined(PNG_WRITE_tIME_SUPPORTED)
  199000. if (info_ptr->valid & PNG_INFO_tIME)
  199001. {
  199002. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  199003. png_ptr->mode |= PNG_WROTE_tIME;
  199004. }
  199005. #endif
  199006. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  199007. if (info_ptr->valid & PNG_INFO_sPLT)
  199008. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  199009. png_write_sPLT(png_ptr, info_ptr->splt_palettes + i);
  199010. #endif
  199011. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  199012. /* Check to see if we need to write text chunks */
  199013. for (i = 0; i < info_ptr->num_text; i++)
  199014. {
  199015. png_debug2(2, "Writing header text chunk %d, type %d\n", i,
  199016. info_ptr->text[i].compression);
  199017. /* an internationalized chunk? */
  199018. if (info_ptr->text[i].compression > 0)
  199019. {
  199020. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  199021. /* write international chunk */
  199022. png_write_iTXt(png_ptr,
  199023. info_ptr->text[i].compression,
  199024. info_ptr->text[i].key,
  199025. info_ptr->text[i].lang,
  199026. info_ptr->text[i].lang_key,
  199027. info_ptr->text[i].text);
  199028. #else
  199029. png_warning(png_ptr, "Unable to write international text");
  199030. #endif
  199031. /* Mark this chunk as written */
  199032. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  199033. }
  199034. /* If we want a compressed text chunk */
  199035. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_zTXt)
  199036. {
  199037. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  199038. /* write compressed chunk */
  199039. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  199040. info_ptr->text[i].text, 0,
  199041. info_ptr->text[i].compression);
  199042. #else
  199043. png_warning(png_ptr, "Unable to write compressed text");
  199044. #endif
  199045. /* Mark this chunk as written */
  199046. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  199047. }
  199048. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  199049. {
  199050. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  199051. /* write uncompressed chunk */
  199052. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  199053. info_ptr->text[i].text,
  199054. 0);
  199055. #else
  199056. png_warning(png_ptr, "Unable to write uncompressed text");
  199057. #endif
  199058. /* Mark this chunk as written */
  199059. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  199060. }
  199061. }
  199062. #endif
  199063. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  199064. if (info_ptr->unknown_chunks_num)
  199065. {
  199066. png_unknown_chunk *up;
  199067. png_debug(5, "writing extra chunks\n");
  199068. for (up = info_ptr->unknown_chunks;
  199069. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  199070. up++)
  199071. {
  199072. int keep=png_handle_as_unknown(png_ptr, up->name);
  199073. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  199074. up->location && (up->location & PNG_HAVE_PLTE) &&
  199075. !(up->location & PNG_HAVE_IDAT) &&
  199076. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  199077. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  199078. {
  199079. png_write_chunk(png_ptr, up->name, up->data, up->size);
  199080. }
  199081. }
  199082. }
  199083. #endif
  199084. }
  199085. /* Writes the end of the PNG file. If you don't want to write comments or
  199086. * time information, you can pass NULL for info. If you already wrote these
  199087. * in png_write_info(), do not write them again here. If you have long
  199088. * comments, I suggest writing them here, and compressing them.
  199089. */
  199090. void PNGAPI
  199091. png_write_end(png_structp png_ptr, png_infop info_ptr)
  199092. {
  199093. png_debug(1, "in png_write_end\n");
  199094. if (png_ptr == NULL)
  199095. return;
  199096. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  199097. png_error(png_ptr, "No IDATs written into file");
  199098. /* see if user wants us to write information chunks */
  199099. if (info_ptr != NULL)
  199100. {
  199101. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  199102. int i; /* local index variable */
  199103. #endif
  199104. #if defined(PNG_WRITE_tIME_SUPPORTED)
  199105. /* check to see if user has supplied a time chunk */
  199106. if ((info_ptr->valid & PNG_INFO_tIME) &&
  199107. !(png_ptr->mode & PNG_WROTE_tIME))
  199108. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  199109. #endif
  199110. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  199111. /* loop through comment chunks */
  199112. for (i = 0; i < info_ptr->num_text; i++)
  199113. {
  199114. png_debug2(2, "Writing trailer text chunk %d, type %d\n", i,
  199115. info_ptr->text[i].compression);
  199116. /* an internationalized chunk? */
  199117. if (info_ptr->text[i].compression > 0)
  199118. {
  199119. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  199120. /* write international chunk */
  199121. png_write_iTXt(png_ptr,
  199122. info_ptr->text[i].compression,
  199123. info_ptr->text[i].key,
  199124. info_ptr->text[i].lang,
  199125. info_ptr->text[i].lang_key,
  199126. info_ptr->text[i].text);
  199127. #else
  199128. png_warning(png_ptr, "Unable to write international text");
  199129. #endif
  199130. /* Mark this chunk as written */
  199131. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  199132. }
  199133. else if (info_ptr->text[i].compression >= PNG_TEXT_COMPRESSION_zTXt)
  199134. {
  199135. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  199136. /* write compressed chunk */
  199137. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  199138. info_ptr->text[i].text, 0,
  199139. info_ptr->text[i].compression);
  199140. #else
  199141. png_warning(png_ptr, "Unable to write compressed text");
  199142. #endif
  199143. /* Mark this chunk as written */
  199144. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  199145. }
  199146. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  199147. {
  199148. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  199149. /* write uncompressed chunk */
  199150. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  199151. info_ptr->text[i].text, 0);
  199152. #else
  199153. png_warning(png_ptr, "Unable to write uncompressed text");
  199154. #endif
  199155. /* Mark this chunk as written */
  199156. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  199157. }
  199158. }
  199159. #endif
  199160. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  199161. if (info_ptr->unknown_chunks_num)
  199162. {
  199163. png_unknown_chunk *up;
  199164. png_debug(5, "writing extra chunks\n");
  199165. for (up = info_ptr->unknown_chunks;
  199166. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  199167. up++)
  199168. {
  199169. int keep=png_handle_as_unknown(png_ptr, up->name);
  199170. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  199171. up->location && (up->location & PNG_AFTER_IDAT) &&
  199172. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  199173. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  199174. {
  199175. png_write_chunk(png_ptr, up->name, up->data, up->size);
  199176. }
  199177. }
  199178. }
  199179. #endif
  199180. }
  199181. png_ptr->mode |= PNG_AFTER_IDAT;
  199182. /* write end of PNG file */
  199183. png_write_IEND(png_ptr);
  199184. }
  199185. #if defined(PNG_WRITE_tIME_SUPPORTED)
  199186. #if !defined(_WIN32_WCE)
  199187. /* "time.h" functions are not supported on WindowsCE */
  199188. void PNGAPI
  199189. png_convert_from_struct_tm(png_timep ptime, struct tm FAR * ttime)
  199190. {
  199191. png_debug(1, "in png_convert_from_struct_tm\n");
  199192. ptime->year = (png_uint_16)(1900 + ttime->tm_year);
  199193. ptime->month = (png_byte)(ttime->tm_mon + 1);
  199194. ptime->day = (png_byte)ttime->tm_mday;
  199195. ptime->hour = (png_byte)ttime->tm_hour;
  199196. ptime->minute = (png_byte)ttime->tm_min;
  199197. ptime->second = (png_byte)ttime->tm_sec;
  199198. }
  199199. void PNGAPI
  199200. png_convert_from_time_t(png_timep ptime, time_t ttime)
  199201. {
  199202. struct tm *tbuf;
  199203. png_debug(1, "in png_convert_from_time_t\n");
  199204. tbuf = gmtime(&ttime);
  199205. png_convert_from_struct_tm(ptime, tbuf);
  199206. }
  199207. #endif
  199208. #endif
  199209. /* Initialize png_ptr structure, and allocate any memory needed */
  199210. png_structp PNGAPI
  199211. png_create_write_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  199212. png_error_ptr error_fn, png_error_ptr warn_fn)
  199213. {
  199214. #ifdef PNG_USER_MEM_SUPPORTED
  199215. return (png_create_write_struct_2(user_png_ver, error_ptr, error_fn,
  199216. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  199217. }
  199218. /* Alternate initialize png_ptr structure, and allocate any memory needed */
  199219. png_structp PNGAPI
  199220. png_create_write_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  199221. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  199222. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  199223. {
  199224. #endif /* PNG_USER_MEM_SUPPORTED */
  199225. png_structp png_ptr;
  199226. #ifdef PNG_SETJMP_SUPPORTED
  199227. #ifdef USE_FAR_KEYWORD
  199228. jmp_buf jmpbuf;
  199229. #endif
  199230. #endif
  199231. int i;
  199232. png_debug(1, "in png_create_write_struct\n");
  199233. #ifdef PNG_USER_MEM_SUPPORTED
  199234. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  199235. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  199236. #else
  199237. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  199238. #endif /* PNG_USER_MEM_SUPPORTED */
  199239. if (png_ptr == NULL)
  199240. return (NULL);
  199241. /* added at libpng-1.2.6 */
  199242. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  199243. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  199244. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  199245. #endif
  199246. #ifdef PNG_SETJMP_SUPPORTED
  199247. #ifdef USE_FAR_KEYWORD
  199248. if (setjmp(jmpbuf))
  199249. #else
  199250. if (setjmp(png_ptr->jmpbuf))
  199251. #endif
  199252. {
  199253. png_free(png_ptr, png_ptr->zbuf);
  199254. png_ptr->zbuf=NULL;
  199255. png_destroy_struct(png_ptr);
  199256. return (NULL);
  199257. }
  199258. #ifdef USE_FAR_KEYWORD
  199259. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  199260. #endif
  199261. #endif
  199262. #ifdef PNG_USER_MEM_SUPPORTED
  199263. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  199264. #endif /* PNG_USER_MEM_SUPPORTED */
  199265. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  199266. i=0;
  199267. do
  199268. {
  199269. if(user_png_ver[i] != png_libpng_ver[i])
  199270. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  199271. } while (png_libpng_ver[i++]);
  199272. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  199273. {
  199274. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  199275. * we must recompile any applications that use any older library version.
  199276. * For versions after libpng 1.0, we will be compatible, so we need
  199277. * only check the first digit.
  199278. */
  199279. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  199280. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  199281. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  199282. {
  199283. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  199284. char msg[80];
  199285. if (user_png_ver)
  199286. {
  199287. png_snprintf(msg, 80,
  199288. "Application was compiled with png.h from libpng-%.20s",
  199289. user_png_ver);
  199290. png_warning(png_ptr, msg);
  199291. }
  199292. png_snprintf(msg, 80,
  199293. "Application is running with png.c from libpng-%.20s",
  199294. png_libpng_ver);
  199295. png_warning(png_ptr, msg);
  199296. #endif
  199297. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  199298. png_ptr->flags=0;
  199299. #endif
  199300. png_error(png_ptr,
  199301. "Incompatible libpng version in application and library");
  199302. }
  199303. }
  199304. /* initialize zbuf - compression buffer */
  199305. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  199306. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  199307. (png_uint_32)png_ptr->zbuf_size);
  199308. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  199309. png_flush_ptr_NULL);
  199310. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199311. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  199312. 1, png_doublep_NULL, png_doublep_NULL);
  199313. #endif
  199314. #ifdef PNG_SETJMP_SUPPORTED
  199315. /* Applications that neglect to set up their own setjmp() and then encounter
  199316. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  199317. abort instead of returning. */
  199318. #ifdef USE_FAR_KEYWORD
  199319. if (setjmp(jmpbuf))
  199320. PNG_ABORT();
  199321. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  199322. #else
  199323. if (setjmp(png_ptr->jmpbuf))
  199324. PNG_ABORT();
  199325. #endif
  199326. #endif
  199327. return (png_ptr);
  199328. }
  199329. /* Initialize png_ptr structure, and allocate any memory needed */
  199330. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  199331. /* Deprecated. */
  199332. #undef png_write_init
  199333. void PNGAPI
  199334. png_write_init(png_structp png_ptr)
  199335. {
  199336. /* We only come here via pre-1.0.7-compiled applications */
  199337. png_write_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  199338. }
  199339. void PNGAPI
  199340. png_write_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  199341. png_size_t png_struct_size, png_size_t png_info_size)
  199342. {
  199343. /* We only come here via pre-1.0.12-compiled applications */
  199344. if(png_ptr == NULL) return;
  199345. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  199346. if(png_sizeof(png_struct) > png_struct_size ||
  199347. png_sizeof(png_info) > png_info_size)
  199348. {
  199349. char msg[80];
  199350. png_ptr->warning_fn=NULL;
  199351. if (user_png_ver)
  199352. {
  199353. png_snprintf(msg, 80,
  199354. "Application was compiled with png.h from libpng-%.20s",
  199355. user_png_ver);
  199356. png_warning(png_ptr, msg);
  199357. }
  199358. png_snprintf(msg, 80,
  199359. "Application is running with png.c from libpng-%.20s",
  199360. png_libpng_ver);
  199361. png_warning(png_ptr, msg);
  199362. }
  199363. #endif
  199364. if(png_sizeof(png_struct) > png_struct_size)
  199365. {
  199366. png_ptr->error_fn=NULL;
  199367. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  199368. png_ptr->flags=0;
  199369. #endif
  199370. png_error(png_ptr,
  199371. "The png struct allocated by the application for writing is too small.");
  199372. }
  199373. if(png_sizeof(png_info) > png_info_size)
  199374. {
  199375. png_ptr->error_fn=NULL;
  199376. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  199377. png_ptr->flags=0;
  199378. #endif
  199379. png_error(png_ptr,
  199380. "The info struct allocated by the application for writing is too small.");
  199381. }
  199382. png_write_init_3(&png_ptr, user_png_ver, png_struct_size);
  199383. }
  199384. #endif /* PNG_1_0_X || PNG_1_2_X */
  199385. void PNGAPI
  199386. png_write_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  199387. png_size_t png_struct_size)
  199388. {
  199389. png_structp png_ptr=*ptr_ptr;
  199390. #ifdef PNG_SETJMP_SUPPORTED
  199391. jmp_buf tmp_jmp; /* to save current jump buffer */
  199392. #endif
  199393. int i = 0;
  199394. if (png_ptr == NULL)
  199395. return;
  199396. do
  199397. {
  199398. if (user_png_ver[i] != png_libpng_ver[i])
  199399. {
  199400. #ifdef PNG_LEGACY_SUPPORTED
  199401. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  199402. #else
  199403. png_ptr->warning_fn=NULL;
  199404. png_warning(png_ptr,
  199405. "Application uses deprecated png_write_init() and should be recompiled.");
  199406. break;
  199407. #endif
  199408. }
  199409. } while (png_libpng_ver[i++]);
  199410. png_debug(1, "in png_write_init_3\n");
  199411. #ifdef PNG_SETJMP_SUPPORTED
  199412. /* save jump buffer and error functions */
  199413. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  199414. #endif
  199415. if (png_sizeof(png_struct) > png_struct_size)
  199416. {
  199417. png_destroy_struct(png_ptr);
  199418. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  199419. *ptr_ptr = png_ptr;
  199420. }
  199421. /* reset all variables to 0 */
  199422. png_memset(png_ptr, 0, png_sizeof (png_struct));
  199423. /* added at libpng-1.2.6 */
  199424. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  199425. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  199426. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  199427. #endif
  199428. #ifdef PNG_SETJMP_SUPPORTED
  199429. /* restore jump buffer */
  199430. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  199431. #endif
  199432. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  199433. png_flush_ptr_NULL);
  199434. /* initialize zbuf - compression buffer */
  199435. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  199436. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  199437. (png_uint_32)png_ptr->zbuf_size);
  199438. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199439. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  199440. 1, png_doublep_NULL, png_doublep_NULL);
  199441. #endif
  199442. }
  199443. /* Write a few rows of image data. If the image is interlaced,
  199444. * either you will have to write the 7 sub images, or, if you
  199445. * have called png_set_interlace_handling(), you will have to
  199446. * "write" the image seven times.
  199447. */
  199448. void PNGAPI
  199449. png_write_rows(png_structp png_ptr, png_bytepp row,
  199450. png_uint_32 num_rows)
  199451. {
  199452. png_uint_32 i; /* row counter */
  199453. png_bytepp rp; /* row pointer */
  199454. png_debug(1, "in png_write_rows\n");
  199455. if (png_ptr == NULL)
  199456. return;
  199457. /* loop through the rows */
  199458. for (i = 0, rp = row; i < num_rows; i++, rp++)
  199459. {
  199460. png_write_row(png_ptr, *rp);
  199461. }
  199462. }
  199463. /* Write the image. You only need to call this function once, even
  199464. * if you are writing an interlaced image.
  199465. */
  199466. void PNGAPI
  199467. png_write_image(png_structp png_ptr, png_bytepp image)
  199468. {
  199469. png_uint_32 i; /* row index */
  199470. int pass, num_pass; /* pass variables */
  199471. png_bytepp rp; /* points to current row */
  199472. if (png_ptr == NULL)
  199473. return;
  199474. png_debug(1, "in png_write_image\n");
  199475. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199476. /* intialize interlace handling. If image is not interlaced,
  199477. this will set pass to 1 */
  199478. num_pass = png_set_interlace_handling(png_ptr);
  199479. #else
  199480. num_pass = 1;
  199481. #endif
  199482. /* loop through passes */
  199483. for (pass = 0; pass < num_pass; pass++)
  199484. {
  199485. /* loop through image */
  199486. for (i = 0, rp = image; i < png_ptr->height; i++, rp++)
  199487. {
  199488. png_write_row(png_ptr, *rp);
  199489. }
  199490. }
  199491. }
  199492. /* called by user to write a row of image data */
  199493. void PNGAPI
  199494. png_write_row(png_structp png_ptr, png_bytep row)
  199495. {
  199496. if (png_ptr == NULL)
  199497. return;
  199498. png_debug2(1, "in png_write_row (row %ld, pass %d)\n",
  199499. png_ptr->row_number, png_ptr->pass);
  199500. /* initialize transformations and other stuff if first time */
  199501. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  199502. {
  199503. /* make sure we wrote the header info */
  199504. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  199505. png_error(png_ptr,
  199506. "png_write_info was never called before png_write_row.");
  199507. /* check for transforms that have been set but were defined out */
  199508. #if !defined(PNG_WRITE_INVERT_SUPPORTED) && defined(PNG_READ_INVERT_SUPPORTED)
  199509. if (png_ptr->transformations & PNG_INVERT_MONO)
  199510. png_warning(png_ptr, "PNG_WRITE_INVERT_SUPPORTED is not defined.");
  199511. #endif
  199512. #if !defined(PNG_WRITE_FILLER_SUPPORTED) && defined(PNG_READ_FILLER_SUPPORTED)
  199513. if (png_ptr->transformations & PNG_FILLER)
  199514. png_warning(png_ptr, "PNG_WRITE_FILLER_SUPPORTED is not defined.");
  199515. #endif
  199516. #if !defined(PNG_WRITE_PACKSWAP_SUPPORTED) && defined(PNG_READ_PACKSWAP_SUPPORTED)
  199517. if (png_ptr->transformations & PNG_PACKSWAP)
  199518. png_warning(png_ptr, "PNG_WRITE_PACKSWAP_SUPPORTED is not defined.");
  199519. #endif
  199520. #if !defined(PNG_WRITE_PACK_SUPPORTED) && defined(PNG_READ_PACK_SUPPORTED)
  199521. if (png_ptr->transformations & PNG_PACK)
  199522. png_warning(png_ptr, "PNG_WRITE_PACK_SUPPORTED is not defined.");
  199523. #endif
  199524. #if !defined(PNG_WRITE_SHIFT_SUPPORTED) && defined(PNG_READ_SHIFT_SUPPORTED)
  199525. if (png_ptr->transformations & PNG_SHIFT)
  199526. png_warning(png_ptr, "PNG_WRITE_SHIFT_SUPPORTED is not defined.");
  199527. #endif
  199528. #if !defined(PNG_WRITE_BGR_SUPPORTED) && defined(PNG_READ_BGR_SUPPORTED)
  199529. if (png_ptr->transformations & PNG_BGR)
  199530. png_warning(png_ptr, "PNG_WRITE_BGR_SUPPORTED is not defined.");
  199531. #endif
  199532. #if !defined(PNG_WRITE_SWAP_SUPPORTED) && defined(PNG_READ_SWAP_SUPPORTED)
  199533. if (png_ptr->transformations & PNG_SWAP_BYTES)
  199534. png_warning(png_ptr, "PNG_WRITE_SWAP_SUPPORTED is not defined.");
  199535. #endif
  199536. png_write_start_row(png_ptr);
  199537. }
  199538. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199539. /* if interlaced and not interested in row, return */
  199540. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  199541. {
  199542. switch (png_ptr->pass)
  199543. {
  199544. case 0:
  199545. if (png_ptr->row_number & 0x07)
  199546. {
  199547. png_write_finish_row(png_ptr);
  199548. return;
  199549. }
  199550. break;
  199551. case 1:
  199552. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  199553. {
  199554. png_write_finish_row(png_ptr);
  199555. return;
  199556. }
  199557. break;
  199558. case 2:
  199559. if ((png_ptr->row_number & 0x07) != 4)
  199560. {
  199561. png_write_finish_row(png_ptr);
  199562. return;
  199563. }
  199564. break;
  199565. case 3:
  199566. if ((png_ptr->row_number & 0x03) || png_ptr->width < 3)
  199567. {
  199568. png_write_finish_row(png_ptr);
  199569. return;
  199570. }
  199571. break;
  199572. case 4:
  199573. if ((png_ptr->row_number & 0x03) != 2)
  199574. {
  199575. png_write_finish_row(png_ptr);
  199576. return;
  199577. }
  199578. break;
  199579. case 5:
  199580. if ((png_ptr->row_number & 0x01) || png_ptr->width < 2)
  199581. {
  199582. png_write_finish_row(png_ptr);
  199583. return;
  199584. }
  199585. break;
  199586. case 6:
  199587. if (!(png_ptr->row_number & 0x01))
  199588. {
  199589. png_write_finish_row(png_ptr);
  199590. return;
  199591. }
  199592. break;
  199593. }
  199594. }
  199595. #endif
  199596. /* set up row info for transformations */
  199597. png_ptr->row_info.color_type = png_ptr->color_type;
  199598. png_ptr->row_info.width = png_ptr->usr_width;
  199599. png_ptr->row_info.channels = png_ptr->usr_channels;
  199600. png_ptr->row_info.bit_depth = png_ptr->usr_bit_depth;
  199601. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  199602. png_ptr->row_info.channels);
  199603. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  199604. png_ptr->row_info.width);
  199605. png_debug1(3, "row_info->color_type = %d\n", png_ptr->row_info.color_type);
  199606. png_debug1(3, "row_info->width = %lu\n", png_ptr->row_info.width);
  199607. png_debug1(3, "row_info->channels = %d\n", png_ptr->row_info.channels);
  199608. png_debug1(3, "row_info->bit_depth = %d\n", png_ptr->row_info.bit_depth);
  199609. png_debug1(3, "row_info->pixel_depth = %d\n", png_ptr->row_info.pixel_depth);
  199610. png_debug1(3, "row_info->rowbytes = %lu\n", png_ptr->row_info.rowbytes);
  199611. /* Copy user's row into buffer, leaving room for filter byte. */
  199612. png_memcpy_check(png_ptr, png_ptr->row_buf + 1, row,
  199613. png_ptr->row_info.rowbytes);
  199614. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199615. /* handle interlacing */
  199616. if (png_ptr->interlaced && png_ptr->pass < 6 &&
  199617. (png_ptr->transformations & PNG_INTERLACE))
  199618. {
  199619. png_do_write_interlace(&(png_ptr->row_info),
  199620. png_ptr->row_buf + 1, png_ptr->pass);
  199621. /* this should always get caught above, but still ... */
  199622. if (!(png_ptr->row_info.width))
  199623. {
  199624. png_write_finish_row(png_ptr);
  199625. return;
  199626. }
  199627. }
  199628. #endif
  199629. /* handle other transformations */
  199630. if (png_ptr->transformations)
  199631. png_do_write_transformations(png_ptr);
  199632. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  199633. /* Write filter_method 64 (intrapixel differencing) only if
  199634. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  199635. * 2. Libpng did not write a PNG signature (this filter_method is only
  199636. * used in PNG datastreams that are embedded in MNG datastreams) and
  199637. * 3. The application called png_permit_mng_features with a mask that
  199638. * included PNG_FLAG_MNG_FILTER_64 and
  199639. * 4. The filter_method is 64 and
  199640. * 5. The color_type is RGB or RGBA
  199641. */
  199642. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  199643. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  199644. {
  199645. /* Intrapixel differencing */
  199646. png_do_write_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199647. }
  199648. #endif
  199649. /* Find a filter if necessary, filter the row and write it out. */
  199650. png_write_find_filter(png_ptr, &(png_ptr->row_info));
  199651. if (png_ptr->write_row_fn != NULL)
  199652. (*(png_ptr->write_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  199653. }
  199654. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  199655. /* Set the automatic flush interval or 0 to turn flushing off */
  199656. void PNGAPI
  199657. png_set_flush(png_structp png_ptr, int nrows)
  199658. {
  199659. png_debug(1, "in png_set_flush\n");
  199660. if (png_ptr == NULL)
  199661. return;
  199662. png_ptr->flush_dist = (nrows < 0 ? 0 : nrows);
  199663. }
  199664. /* flush the current output buffers now */
  199665. void PNGAPI
  199666. png_write_flush(png_structp png_ptr)
  199667. {
  199668. int wrote_IDAT;
  199669. png_debug(1, "in png_write_flush\n");
  199670. if (png_ptr == NULL)
  199671. return;
  199672. /* We have already written out all of the data */
  199673. if (png_ptr->row_number >= png_ptr->num_rows)
  199674. return;
  199675. do
  199676. {
  199677. int ret;
  199678. /* compress the data */
  199679. ret = deflate(&png_ptr->zstream, Z_SYNC_FLUSH);
  199680. wrote_IDAT = 0;
  199681. /* check for compression errors */
  199682. if (ret != Z_OK)
  199683. {
  199684. if (png_ptr->zstream.msg != NULL)
  199685. png_error(png_ptr, png_ptr->zstream.msg);
  199686. else
  199687. png_error(png_ptr, "zlib error");
  199688. }
  199689. if (!(png_ptr->zstream.avail_out))
  199690. {
  199691. /* write the IDAT and reset the zlib output buffer */
  199692. png_write_IDAT(png_ptr, png_ptr->zbuf,
  199693. png_ptr->zbuf_size);
  199694. png_ptr->zstream.next_out = png_ptr->zbuf;
  199695. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  199696. wrote_IDAT = 1;
  199697. }
  199698. } while(wrote_IDAT == 1);
  199699. /* If there is any data left to be output, write it into a new IDAT */
  199700. if (png_ptr->zbuf_size != png_ptr->zstream.avail_out)
  199701. {
  199702. /* write the IDAT and reset the zlib output buffer */
  199703. png_write_IDAT(png_ptr, png_ptr->zbuf,
  199704. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  199705. png_ptr->zstream.next_out = png_ptr->zbuf;
  199706. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  199707. }
  199708. png_ptr->flush_rows = 0;
  199709. png_flush(png_ptr);
  199710. }
  199711. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  199712. /* free all memory used by the write */
  199713. void PNGAPI
  199714. png_destroy_write_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr)
  199715. {
  199716. png_structp png_ptr = NULL;
  199717. png_infop info_ptr = NULL;
  199718. #ifdef PNG_USER_MEM_SUPPORTED
  199719. png_free_ptr free_fn = NULL;
  199720. png_voidp mem_ptr = NULL;
  199721. #endif
  199722. png_debug(1, "in png_destroy_write_struct\n");
  199723. if (png_ptr_ptr != NULL)
  199724. {
  199725. png_ptr = *png_ptr_ptr;
  199726. #ifdef PNG_USER_MEM_SUPPORTED
  199727. free_fn = png_ptr->free_fn;
  199728. mem_ptr = png_ptr->mem_ptr;
  199729. #endif
  199730. }
  199731. if (info_ptr_ptr != NULL)
  199732. info_ptr = *info_ptr_ptr;
  199733. if (info_ptr != NULL)
  199734. {
  199735. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  199736. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  199737. if (png_ptr->num_chunk_list)
  199738. {
  199739. png_free(png_ptr, png_ptr->chunk_list);
  199740. png_ptr->chunk_list=NULL;
  199741. png_ptr->num_chunk_list=0;
  199742. }
  199743. #endif
  199744. #ifdef PNG_USER_MEM_SUPPORTED
  199745. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  199746. (png_voidp)mem_ptr);
  199747. #else
  199748. png_destroy_struct((png_voidp)info_ptr);
  199749. #endif
  199750. *info_ptr_ptr = NULL;
  199751. }
  199752. if (png_ptr != NULL)
  199753. {
  199754. png_write_destroy(png_ptr);
  199755. #ifdef PNG_USER_MEM_SUPPORTED
  199756. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  199757. (png_voidp)mem_ptr);
  199758. #else
  199759. png_destroy_struct((png_voidp)png_ptr);
  199760. #endif
  199761. *png_ptr_ptr = NULL;
  199762. }
  199763. }
  199764. /* Free any memory used in png_ptr struct (old method) */
  199765. void /* PRIVATE */
  199766. png_write_destroy(png_structp png_ptr)
  199767. {
  199768. #ifdef PNG_SETJMP_SUPPORTED
  199769. jmp_buf tmp_jmp; /* save jump buffer */
  199770. #endif
  199771. png_error_ptr error_fn;
  199772. png_error_ptr warning_fn;
  199773. png_voidp error_ptr;
  199774. #ifdef PNG_USER_MEM_SUPPORTED
  199775. png_free_ptr free_fn;
  199776. #endif
  199777. png_debug(1, "in png_write_destroy\n");
  199778. /* free any memory zlib uses */
  199779. deflateEnd(&png_ptr->zstream);
  199780. /* free our memory. png_free checks NULL for us. */
  199781. png_free(png_ptr, png_ptr->zbuf);
  199782. png_free(png_ptr, png_ptr->row_buf);
  199783. png_free(png_ptr, png_ptr->prev_row);
  199784. png_free(png_ptr, png_ptr->sub_row);
  199785. png_free(png_ptr, png_ptr->up_row);
  199786. png_free(png_ptr, png_ptr->avg_row);
  199787. png_free(png_ptr, png_ptr->paeth_row);
  199788. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  199789. png_free(png_ptr, png_ptr->time_buffer);
  199790. #endif
  199791. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199792. png_free(png_ptr, png_ptr->prev_filters);
  199793. png_free(png_ptr, png_ptr->filter_weights);
  199794. png_free(png_ptr, png_ptr->inv_filter_weights);
  199795. png_free(png_ptr, png_ptr->filter_costs);
  199796. png_free(png_ptr, png_ptr->inv_filter_costs);
  199797. #endif
  199798. #ifdef PNG_SETJMP_SUPPORTED
  199799. /* reset structure */
  199800. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  199801. #endif
  199802. error_fn = png_ptr->error_fn;
  199803. warning_fn = png_ptr->warning_fn;
  199804. error_ptr = png_ptr->error_ptr;
  199805. #ifdef PNG_USER_MEM_SUPPORTED
  199806. free_fn = png_ptr->free_fn;
  199807. #endif
  199808. png_memset(png_ptr, 0, png_sizeof (png_struct));
  199809. png_ptr->error_fn = error_fn;
  199810. png_ptr->warning_fn = warning_fn;
  199811. png_ptr->error_ptr = error_ptr;
  199812. #ifdef PNG_USER_MEM_SUPPORTED
  199813. png_ptr->free_fn = free_fn;
  199814. #endif
  199815. #ifdef PNG_SETJMP_SUPPORTED
  199816. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  199817. #endif
  199818. }
  199819. /* Allow the application to select one or more row filters to use. */
  199820. void PNGAPI
  199821. png_set_filter(png_structp png_ptr, int method, int filters)
  199822. {
  199823. png_debug(1, "in png_set_filter\n");
  199824. if (png_ptr == NULL)
  199825. return;
  199826. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  199827. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  199828. (method == PNG_INTRAPIXEL_DIFFERENCING))
  199829. method = PNG_FILTER_TYPE_BASE;
  199830. #endif
  199831. if (method == PNG_FILTER_TYPE_BASE)
  199832. {
  199833. switch (filters & (PNG_ALL_FILTERS | 0x07))
  199834. {
  199835. #ifndef PNG_NO_WRITE_FILTER
  199836. case 5:
  199837. case 6:
  199838. case 7: png_warning(png_ptr, "Unknown row filter for method 0");
  199839. #endif /* PNG_NO_WRITE_FILTER */
  199840. case PNG_FILTER_VALUE_NONE:
  199841. png_ptr->do_filter=PNG_FILTER_NONE; break;
  199842. #ifndef PNG_NO_WRITE_FILTER
  199843. case PNG_FILTER_VALUE_SUB:
  199844. png_ptr->do_filter=PNG_FILTER_SUB; break;
  199845. case PNG_FILTER_VALUE_UP:
  199846. png_ptr->do_filter=PNG_FILTER_UP; break;
  199847. case PNG_FILTER_VALUE_AVG:
  199848. png_ptr->do_filter=PNG_FILTER_AVG; break;
  199849. case PNG_FILTER_VALUE_PAETH:
  199850. png_ptr->do_filter=PNG_FILTER_PAETH; break;
  199851. default: png_ptr->do_filter = (png_byte)filters; break;
  199852. #else
  199853. default: png_warning(png_ptr, "Unknown row filter for method 0");
  199854. #endif /* PNG_NO_WRITE_FILTER */
  199855. }
  199856. /* If we have allocated the row_buf, this means we have already started
  199857. * with the image and we should have allocated all of the filter buffers
  199858. * that have been selected. If prev_row isn't already allocated, then
  199859. * it is too late to start using the filters that need it, since we
  199860. * will be missing the data in the previous row. If an application
  199861. * wants to start and stop using particular filters during compression,
  199862. * it should start out with all of the filters, and then add and
  199863. * remove them after the start of compression.
  199864. */
  199865. if (png_ptr->row_buf != NULL)
  199866. {
  199867. #ifndef PNG_NO_WRITE_FILTER
  199868. if ((png_ptr->do_filter & PNG_FILTER_SUB) && png_ptr->sub_row == NULL)
  199869. {
  199870. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  199871. (png_ptr->rowbytes + 1));
  199872. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  199873. }
  199874. if ((png_ptr->do_filter & PNG_FILTER_UP) && png_ptr->up_row == NULL)
  199875. {
  199876. if (png_ptr->prev_row == NULL)
  199877. {
  199878. png_warning(png_ptr, "Can't add Up filter after starting");
  199879. png_ptr->do_filter &= ~PNG_FILTER_UP;
  199880. }
  199881. else
  199882. {
  199883. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  199884. (png_ptr->rowbytes + 1));
  199885. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  199886. }
  199887. }
  199888. if ((png_ptr->do_filter & PNG_FILTER_AVG) && png_ptr->avg_row == NULL)
  199889. {
  199890. if (png_ptr->prev_row == NULL)
  199891. {
  199892. png_warning(png_ptr, "Can't add Average filter after starting");
  199893. png_ptr->do_filter &= ~PNG_FILTER_AVG;
  199894. }
  199895. else
  199896. {
  199897. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  199898. (png_ptr->rowbytes + 1));
  199899. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  199900. }
  199901. }
  199902. if ((png_ptr->do_filter & PNG_FILTER_PAETH) &&
  199903. png_ptr->paeth_row == NULL)
  199904. {
  199905. if (png_ptr->prev_row == NULL)
  199906. {
  199907. png_warning(png_ptr, "Can't add Paeth filter after starting");
  199908. png_ptr->do_filter &= (png_byte)(~PNG_FILTER_PAETH);
  199909. }
  199910. else
  199911. {
  199912. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  199913. (png_ptr->rowbytes + 1));
  199914. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  199915. }
  199916. }
  199917. if (png_ptr->do_filter == PNG_NO_FILTERS)
  199918. #endif /* PNG_NO_WRITE_FILTER */
  199919. png_ptr->do_filter = PNG_FILTER_NONE;
  199920. }
  199921. }
  199922. else
  199923. png_error(png_ptr, "Unknown custom filter method");
  199924. }
  199925. /* This allows us to influence the way in which libpng chooses the "best"
  199926. * filter for the current scanline. While the "minimum-sum-of-absolute-
  199927. * differences metric is relatively fast and effective, there is some
  199928. * question as to whether it can be improved upon by trying to keep the
  199929. * filtered data going to zlib more consistent, hopefully resulting in
  199930. * better compression.
  199931. */
  199932. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* GRR 970116 */
  199933. void PNGAPI
  199934. png_set_filter_heuristics(png_structp png_ptr, int heuristic_method,
  199935. int num_weights, png_doublep filter_weights,
  199936. png_doublep filter_costs)
  199937. {
  199938. int i;
  199939. png_debug(1, "in png_set_filter_heuristics\n");
  199940. if (png_ptr == NULL)
  199941. return;
  199942. if (heuristic_method >= PNG_FILTER_HEURISTIC_LAST)
  199943. {
  199944. png_warning(png_ptr, "Unknown filter heuristic method");
  199945. return;
  199946. }
  199947. if (heuristic_method == PNG_FILTER_HEURISTIC_DEFAULT)
  199948. {
  199949. heuristic_method = PNG_FILTER_HEURISTIC_UNWEIGHTED;
  199950. }
  199951. if (num_weights < 0 || filter_weights == NULL ||
  199952. heuristic_method == PNG_FILTER_HEURISTIC_UNWEIGHTED)
  199953. {
  199954. num_weights = 0;
  199955. }
  199956. png_ptr->num_prev_filters = (png_byte)num_weights;
  199957. png_ptr->heuristic_method = (png_byte)heuristic_method;
  199958. if (num_weights > 0)
  199959. {
  199960. if (png_ptr->prev_filters == NULL)
  199961. {
  199962. png_ptr->prev_filters = (png_bytep)png_malloc(png_ptr,
  199963. (png_uint_32)(png_sizeof(png_byte) * num_weights));
  199964. /* To make sure that the weighting starts out fairly */
  199965. for (i = 0; i < num_weights; i++)
  199966. {
  199967. png_ptr->prev_filters[i] = 255;
  199968. }
  199969. }
  199970. if (png_ptr->filter_weights == NULL)
  199971. {
  199972. png_ptr->filter_weights = (png_uint_16p)png_malloc(png_ptr,
  199973. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  199974. png_ptr->inv_filter_weights = (png_uint_16p)png_malloc(png_ptr,
  199975. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  199976. for (i = 0; i < num_weights; i++)
  199977. {
  199978. png_ptr->inv_filter_weights[i] =
  199979. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  199980. }
  199981. }
  199982. for (i = 0; i < num_weights; i++)
  199983. {
  199984. if (filter_weights[i] < 0.0)
  199985. {
  199986. png_ptr->inv_filter_weights[i] =
  199987. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  199988. }
  199989. else
  199990. {
  199991. png_ptr->inv_filter_weights[i] =
  199992. (png_uint_16)((double)PNG_WEIGHT_FACTOR*filter_weights[i]+0.5);
  199993. png_ptr->filter_weights[i] =
  199994. (png_uint_16)((double)PNG_WEIGHT_FACTOR/filter_weights[i]+0.5);
  199995. }
  199996. }
  199997. }
  199998. /* If, in the future, there are other filter methods, this would
  199999. * need to be based on png_ptr->filter.
  200000. */
  200001. if (png_ptr->filter_costs == NULL)
  200002. {
  200003. png_ptr->filter_costs = (png_uint_16p)png_malloc(png_ptr,
  200004. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  200005. png_ptr->inv_filter_costs = (png_uint_16p)png_malloc(png_ptr,
  200006. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  200007. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  200008. {
  200009. png_ptr->inv_filter_costs[i] =
  200010. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  200011. }
  200012. }
  200013. /* Here is where we set the relative costs of the different filters. We
  200014. * should take the desired compression level into account when setting
  200015. * the costs, so that Paeth, for instance, has a high relative cost at low
  200016. * compression levels, while it has a lower relative cost at higher
  200017. * compression settings. The filter types are in order of increasing
  200018. * relative cost, so it would be possible to do this with an algorithm.
  200019. */
  200020. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  200021. {
  200022. if (filter_costs == NULL || filter_costs[i] < 0.0)
  200023. {
  200024. png_ptr->inv_filter_costs[i] =
  200025. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  200026. }
  200027. else if (filter_costs[i] >= 1.0)
  200028. {
  200029. png_ptr->inv_filter_costs[i] =
  200030. (png_uint_16)((double)PNG_COST_FACTOR / filter_costs[i] + 0.5);
  200031. png_ptr->filter_costs[i] =
  200032. (png_uint_16)((double)PNG_COST_FACTOR * filter_costs[i] + 0.5);
  200033. }
  200034. }
  200035. }
  200036. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  200037. void PNGAPI
  200038. png_set_compression_level(png_structp png_ptr, int level)
  200039. {
  200040. png_debug(1, "in png_set_compression_level\n");
  200041. if (png_ptr == NULL)
  200042. return;
  200043. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_LEVEL;
  200044. png_ptr->zlib_level = level;
  200045. }
  200046. void PNGAPI
  200047. png_set_compression_mem_level(png_structp png_ptr, int mem_level)
  200048. {
  200049. png_debug(1, "in png_set_compression_mem_level\n");
  200050. if (png_ptr == NULL)
  200051. return;
  200052. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL;
  200053. png_ptr->zlib_mem_level = mem_level;
  200054. }
  200055. void PNGAPI
  200056. png_set_compression_strategy(png_structp png_ptr, int strategy)
  200057. {
  200058. png_debug(1, "in png_set_compression_strategy\n");
  200059. if (png_ptr == NULL)
  200060. return;
  200061. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_STRATEGY;
  200062. png_ptr->zlib_strategy = strategy;
  200063. }
  200064. void PNGAPI
  200065. png_set_compression_window_bits(png_structp png_ptr, int window_bits)
  200066. {
  200067. if (png_ptr == NULL)
  200068. return;
  200069. if (window_bits > 15)
  200070. png_warning(png_ptr, "Only compression windows <= 32k supported by PNG");
  200071. else if (window_bits < 8)
  200072. png_warning(png_ptr, "Only compression windows >= 256 supported by PNG");
  200073. #ifndef WBITS_8_OK
  200074. /* avoid libpng bug with 256-byte windows */
  200075. if (window_bits == 8)
  200076. {
  200077. png_warning(png_ptr, "Compression window is being reset to 512");
  200078. window_bits=9;
  200079. }
  200080. #endif
  200081. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS;
  200082. png_ptr->zlib_window_bits = window_bits;
  200083. }
  200084. void PNGAPI
  200085. png_set_compression_method(png_structp png_ptr, int method)
  200086. {
  200087. png_debug(1, "in png_set_compression_method\n");
  200088. if (png_ptr == NULL)
  200089. return;
  200090. if (method != 8)
  200091. png_warning(png_ptr, "Only compression method 8 is supported by PNG");
  200092. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_METHOD;
  200093. png_ptr->zlib_method = method;
  200094. }
  200095. void PNGAPI
  200096. png_set_write_status_fn(png_structp png_ptr, png_write_status_ptr write_row_fn)
  200097. {
  200098. if (png_ptr == NULL)
  200099. return;
  200100. png_ptr->write_row_fn = write_row_fn;
  200101. }
  200102. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  200103. void PNGAPI
  200104. png_set_write_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  200105. write_user_transform_fn)
  200106. {
  200107. png_debug(1, "in png_set_write_user_transform_fn\n");
  200108. if (png_ptr == NULL)
  200109. return;
  200110. png_ptr->transformations |= PNG_USER_TRANSFORM;
  200111. png_ptr->write_user_transform_fn = write_user_transform_fn;
  200112. }
  200113. #endif
  200114. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  200115. void PNGAPI
  200116. png_write_png(png_structp png_ptr, png_infop info_ptr,
  200117. int transforms, voidp params)
  200118. {
  200119. if (png_ptr == NULL || info_ptr == NULL)
  200120. return;
  200121. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  200122. /* invert the alpha channel from opacity to transparency */
  200123. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  200124. png_set_invert_alpha(png_ptr);
  200125. #endif
  200126. /* Write the file header information. */
  200127. png_write_info(png_ptr, info_ptr);
  200128. /* ------ these transformations don't touch the info structure ------- */
  200129. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  200130. /* invert monochrome pixels */
  200131. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  200132. png_set_invert_mono(png_ptr);
  200133. #endif
  200134. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  200135. /* Shift the pixels up to a legal bit depth and fill in
  200136. * as appropriate to correctly scale the image.
  200137. */
  200138. if ((transforms & PNG_TRANSFORM_SHIFT)
  200139. && (info_ptr->valid & PNG_INFO_sBIT))
  200140. png_set_shift(png_ptr, &info_ptr->sig_bit);
  200141. #endif
  200142. #if defined(PNG_WRITE_PACK_SUPPORTED)
  200143. /* pack pixels into bytes */
  200144. if (transforms & PNG_TRANSFORM_PACKING)
  200145. png_set_packing(png_ptr);
  200146. #endif
  200147. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  200148. /* swap location of alpha bytes from ARGB to RGBA */
  200149. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  200150. png_set_swap_alpha(png_ptr);
  200151. #endif
  200152. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  200153. /* Get rid of filler (OR ALPHA) bytes, pack XRGB/RGBX/ARGB/RGBA into
  200154. * RGB (4 channels -> 3 channels). The second parameter is not used.
  200155. */
  200156. if (transforms & PNG_TRANSFORM_STRIP_FILLER)
  200157. png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
  200158. #endif
  200159. #if defined(PNG_WRITE_BGR_SUPPORTED)
  200160. /* flip BGR pixels to RGB */
  200161. if (transforms & PNG_TRANSFORM_BGR)
  200162. png_set_bgr(png_ptr);
  200163. #endif
  200164. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  200165. /* swap bytes of 16-bit files to most significant byte first */
  200166. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  200167. png_set_swap(png_ptr);
  200168. #endif
  200169. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  200170. /* swap bits of 1, 2, 4 bit packed pixel formats */
  200171. if (transforms & PNG_TRANSFORM_PACKSWAP)
  200172. png_set_packswap(png_ptr);
  200173. #endif
  200174. /* ----------------------- end of transformations ------------------- */
  200175. /* write the bits */
  200176. if (info_ptr->valid & PNG_INFO_IDAT)
  200177. png_write_image(png_ptr, info_ptr->row_pointers);
  200178. /* It is REQUIRED to call this to finish writing the rest of the file */
  200179. png_write_end(png_ptr, info_ptr);
  200180. transforms = transforms; /* quiet compiler warnings */
  200181. params = params;
  200182. }
  200183. #endif
  200184. #endif /* PNG_WRITE_SUPPORTED */
  200185. /*** End of inlined file: pngwrite.c ***/
  200186. /*** Start of inlined file: pngwtran.c ***/
  200187. /* pngwtran.c - transforms the data in a row for PNG writers
  200188. *
  200189. * Last changed in libpng 1.2.9 April 14, 2006
  200190. * For conditions of distribution and use, see copyright notice in png.h
  200191. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  200192. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  200193. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  200194. */
  200195. #define PNG_INTERNAL
  200196. #ifdef PNG_WRITE_SUPPORTED
  200197. /* Transform the data according to the user's wishes. The order of
  200198. * transformations is significant.
  200199. */
  200200. void /* PRIVATE */
  200201. png_do_write_transformations(png_structp png_ptr)
  200202. {
  200203. png_debug(1, "in png_do_write_transformations\n");
  200204. if (png_ptr == NULL)
  200205. return;
  200206. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  200207. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  200208. if(png_ptr->write_user_transform_fn != NULL)
  200209. (*(png_ptr->write_user_transform_fn)) /* user write transform function */
  200210. (png_ptr, /* png_ptr */
  200211. &(png_ptr->row_info), /* row_info: */
  200212. /* png_uint_32 width; width of row */
  200213. /* png_uint_32 rowbytes; number of bytes in row */
  200214. /* png_byte color_type; color type of pixels */
  200215. /* png_byte bit_depth; bit depth of samples */
  200216. /* png_byte channels; number of channels (1-4) */
  200217. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  200218. png_ptr->row_buf + 1); /* start of pixel data for row */
  200219. #endif
  200220. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  200221. if (png_ptr->transformations & PNG_FILLER)
  200222. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  200223. png_ptr->flags);
  200224. #endif
  200225. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  200226. if (png_ptr->transformations & PNG_PACKSWAP)
  200227. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200228. #endif
  200229. #if defined(PNG_WRITE_PACK_SUPPORTED)
  200230. if (png_ptr->transformations & PNG_PACK)
  200231. png_do_pack(&(png_ptr->row_info), png_ptr->row_buf + 1,
  200232. (png_uint_32)png_ptr->bit_depth);
  200233. #endif
  200234. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  200235. if (png_ptr->transformations & PNG_SWAP_BYTES)
  200236. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200237. #endif
  200238. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  200239. if (png_ptr->transformations & PNG_SHIFT)
  200240. png_do_shift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  200241. &(png_ptr->shift));
  200242. #endif
  200243. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  200244. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  200245. png_do_write_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200246. #endif
  200247. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  200248. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  200249. png_do_write_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200250. #endif
  200251. #if defined(PNG_WRITE_BGR_SUPPORTED)
  200252. if (png_ptr->transformations & PNG_BGR)
  200253. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200254. #endif
  200255. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  200256. if (png_ptr->transformations & PNG_INVERT_MONO)
  200257. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200258. #endif
  200259. }
  200260. #if defined(PNG_WRITE_PACK_SUPPORTED)
  200261. /* Pack pixels into bytes. Pass the true bit depth in bit_depth. The
  200262. * row_info bit depth should be 8 (one pixel per byte). The channels
  200263. * should be 1 (this only happens on grayscale and paletted images).
  200264. */
  200265. void /* PRIVATE */
  200266. png_do_pack(png_row_infop row_info, png_bytep row, png_uint_32 bit_depth)
  200267. {
  200268. png_debug(1, "in png_do_pack\n");
  200269. if (row_info->bit_depth == 8 &&
  200270. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200271. row != NULL && row_info != NULL &&
  200272. #endif
  200273. row_info->channels == 1)
  200274. {
  200275. switch ((int)bit_depth)
  200276. {
  200277. case 1:
  200278. {
  200279. png_bytep sp, dp;
  200280. int mask, v;
  200281. png_uint_32 i;
  200282. png_uint_32 row_width = row_info->width;
  200283. sp = row;
  200284. dp = row;
  200285. mask = 0x80;
  200286. v = 0;
  200287. for (i = 0; i < row_width; i++)
  200288. {
  200289. if (*sp != 0)
  200290. v |= mask;
  200291. sp++;
  200292. if (mask > 1)
  200293. mask >>= 1;
  200294. else
  200295. {
  200296. mask = 0x80;
  200297. *dp = (png_byte)v;
  200298. dp++;
  200299. v = 0;
  200300. }
  200301. }
  200302. if (mask != 0x80)
  200303. *dp = (png_byte)v;
  200304. break;
  200305. }
  200306. case 2:
  200307. {
  200308. png_bytep sp, dp;
  200309. int shift, v;
  200310. png_uint_32 i;
  200311. png_uint_32 row_width = row_info->width;
  200312. sp = row;
  200313. dp = row;
  200314. shift = 6;
  200315. v = 0;
  200316. for (i = 0; i < row_width; i++)
  200317. {
  200318. png_byte value;
  200319. value = (png_byte)(*sp & 0x03);
  200320. v |= (value << shift);
  200321. if (shift == 0)
  200322. {
  200323. shift = 6;
  200324. *dp = (png_byte)v;
  200325. dp++;
  200326. v = 0;
  200327. }
  200328. else
  200329. shift -= 2;
  200330. sp++;
  200331. }
  200332. if (shift != 6)
  200333. *dp = (png_byte)v;
  200334. break;
  200335. }
  200336. case 4:
  200337. {
  200338. png_bytep sp, dp;
  200339. int shift, v;
  200340. png_uint_32 i;
  200341. png_uint_32 row_width = row_info->width;
  200342. sp = row;
  200343. dp = row;
  200344. shift = 4;
  200345. v = 0;
  200346. for (i = 0; i < row_width; i++)
  200347. {
  200348. png_byte value;
  200349. value = (png_byte)(*sp & 0x0f);
  200350. v |= (value << shift);
  200351. if (shift == 0)
  200352. {
  200353. shift = 4;
  200354. *dp = (png_byte)v;
  200355. dp++;
  200356. v = 0;
  200357. }
  200358. else
  200359. shift -= 4;
  200360. sp++;
  200361. }
  200362. if (shift != 4)
  200363. *dp = (png_byte)v;
  200364. break;
  200365. }
  200366. }
  200367. row_info->bit_depth = (png_byte)bit_depth;
  200368. row_info->pixel_depth = (png_byte)(bit_depth * row_info->channels);
  200369. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  200370. row_info->width);
  200371. }
  200372. }
  200373. #endif
  200374. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  200375. /* Shift pixel values to take advantage of whole range. Pass the
  200376. * true number of bits in bit_depth. The row should be packed
  200377. * according to row_info->bit_depth. Thus, if you had a row of
  200378. * bit depth 4, but the pixels only had values from 0 to 7, you
  200379. * would pass 3 as bit_depth, and this routine would translate the
  200380. * data to 0 to 15.
  200381. */
  200382. void /* PRIVATE */
  200383. png_do_shift(png_row_infop row_info, png_bytep row, png_color_8p bit_depth)
  200384. {
  200385. png_debug(1, "in png_do_shift\n");
  200386. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200387. if (row != NULL && row_info != NULL &&
  200388. #else
  200389. if (
  200390. #endif
  200391. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  200392. {
  200393. int shift_start[4], shift_dec[4];
  200394. int channels = 0;
  200395. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  200396. {
  200397. shift_start[channels] = row_info->bit_depth - bit_depth->red;
  200398. shift_dec[channels] = bit_depth->red;
  200399. channels++;
  200400. shift_start[channels] = row_info->bit_depth - bit_depth->green;
  200401. shift_dec[channels] = bit_depth->green;
  200402. channels++;
  200403. shift_start[channels] = row_info->bit_depth - bit_depth->blue;
  200404. shift_dec[channels] = bit_depth->blue;
  200405. channels++;
  200406. }
  200407. else
  200408. {
  200409. shift_start[channels] = row_info->bit_depth - bit_depth->gray;
  200410. shift_dec[channels] = bit_depth->gray;
  200411. channels++;
  200412. }
  200413. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  200414. {
  200415. shift_start[channels] = row_info->bit_depth - bit_depth->alpha;
  200416. shift_dec[channels] = bit_depth->alpha;
  200417. channels++;
  200418. }
  200419. /* with low row depths, could only be grayscale, so one channel */
  200420. if (row_info->bit_depth < 8)
  200421. {
  200422. png_bytep bp = row;
  200423. png_uint_32 i;
  200424. png_byte mask;
  200425. png_uint_32 row_bytes = row_info->rowbytes;
  200426. if (bit_depth->gray == 1 && row_info->bit_depth == 2)
  200427. mask = 0x55;
  200428. else if (row_info->bit_depth == 4 && bit_depth->gray == 3)
  200429. mask = 0x11;
  200430. else
  200431. mask = 0xff;
  200432. for (i = 0; i < row_bytes; i++, bp++)
  200433. {
  200434. png_uint_16 v;
  200435. int j;
  200436. v = *bp;
  200437. *bp = 0;
  200438. for (j = shift_start[0]; j > -shift_dec[0]; j -= shift_dec[0])
  200439. {
  200440. if (j > 0)
  200441. *bp |= (png_byte)((v << j) & 0xff);
  200442. else
  200443. *bp |= (png_byte)((v >> (-j)) & mask);
  200444. }
  200445. }
  200446. }
  200447. else if (row_info->bit_depth == 8)
  200448. {
  200449. png_bytep bp = row;
  200450. png_uint_32 i;
  200451. png_uint_32 istop = channels * row_info->width;
  200452. for (i = 0; i < istop; i++, bp++)
  200453. {
  200454. png_uint_16 v;
  200455. int j;
  200456. int c = (int)(i%channels);
  200457. v = *bp;
  200458. *bp = 0;
  200459. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  200460. {
  200461. if (j > 0)
  200462. *bp |= (png_byte)((v << j) & 0xff);
  200463. else
  200464. *bp |= (png_byte)((v >> (-j)) & 0xff);
  200465. }
  200466. }
  200467. }
  200468. else
  200469. {
  200470. png_bytep bp;
  200471. png_uint_32 i;
  200472. png_uint_32 istop = channels * row_info->width;
  200473. for (bp = row, i = 0; i < istop; i++)
  200474. {
  200475. int c = (int)(i%channels);
  200476. png_uint_16 value, v;
  200477. int j;
  200478. v = (png_uint_16)(((png_uint_16)(*bp) << 8) + *(bp + 1));
  200479. value = 0;
  200480. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  200481. {
  200482. if (j > 0)
  200483. value |= (png_uint_16)((v << j) & (png_uint_16)0xffff);
  200484. else
  200485. value |= (png_uint_16)((v >> (-j)) & (png_uint_16)0xffff);
  200486. }
  200487. *bp++ = (png_byte)(value >> 8);
  200488. *bp++ = (png_byte)(value & 0xff);
  200489. }
  200490. }
  200491. }
  200492. }
  200493. #endif
  200494. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  200495. void /* PRIVATE */
  200496. png_do_write_swap_alpha(png_row_infop row_info, png_bytep row)
  200497. {
  200498. png_debug(1, "in png_do_write_swap_alpha\n");
  200499. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200500. if (row != NULL && row_info != NULL)
  200501. #endif
  200502. {
  200503. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200504. {
  200505. /* This converts from ARGB to RGBA */
  200506. if (row_info->bit_depth == 8)
  200507. {
  200508. png_bytep sp, dp;
  200509. png_uint_32 i;
  200510. png_uint_32 row_width = row_info->width;
  200511. for (i = 0, sp = dp = row; i < row_width; i++)
  200512. {
  200513. png_byte save = *(sp++);
  200514. *(dp++) = *(sp++);
  200515. *(dp++) = *(sp++);
  200516. *(dp++) = *(sp++);
  200517. *(dp++) = save;
  200518. }
  200519. }
  200520. /* This converts from AARRGGBB to RRGGBBAA */
  200521. else
  200522. {
  200523. png_bytep sp, dp;
  200524. png_uint_32 i;
  200525. png_uint_32 row_width = row_info->width;
  200526. for (i = 0, sp = dp = row; i < row_width; i++)
  200527. {
  200528. png_byte save[2];
  200529. save[0] = *(sp++);
  200530. save[1] = *(sp++);
  200531. *(dp++) = *(sp++);
  200532. *(dp++) = *(sp++);
  200533. *(dp++) = *(sp++);
  200534. *(dp++) = *(sp++);
  200535. *(dp++) = *(sp++);
  200536. *(dp++) = *(sp++);
  200537. *(dp++) = save[0];
  200538. *(dp++) = save[1];
  200539. }
  200540. }
  200541. }
  200542. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  200543. {
  200544. /* This converts from AG to GA */
  200545. if (row_info->bit_depth == 8)
  200546. {
  200547. png_bytep sp, dp;
  200548. png_uint_32 i;
  200549. png_uint_32 row_width = row_info->width;
  200550. for (i = 0, sp = dp = row; i < row_width; i++)
  200551. {
  200552. png_byte save = *(sp++);
  200553. *(dp++) = *(sp++);
  200554. *(dp++) = save;
  200555. }
  200556. }
  200557. /* This converts from AAGG to GGAA */
  200558. else
  200559. {
  200560. png_bytep sp, dp;
  200561. png_uint_32 i;
  200562. png_uint_32 row_width = row_info->width;
  200563. for (i = 0, sp = dp = row; i < row_width; i++)
  200564. {
  200565. png_byte save[2];
  200566. save[0] = *(sp++);
  200567. save[1] = *(sp++);
  200568. *(dp++) = *(sp++);
  200569. *(dp++) = *(sp++);
  200570. *(dp++) = save[0];
  200571. *(dp++) = save[1];
  200572. }
  200573. }
  200574. }
  200575. }
  200576. }
  200577. #endif
  200578. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  200579. void /* PRIVATE */
  200580. png_do_write_invert_alpha(png_row_infop row_info, png_bytep row)
  200581. {
  200582. png_debug(1, "in png_do_write_invert_alpha\n");
  200583. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200584. if (row != NULL && row_info != NULL)
  200585. #endif
  200586. {
  200587. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200588. {
  200589. /* This inverts the alpha channel in RGBA */
  200590. if (row_info->bit_depth == 8)
  200591. {
  200592. png_bytep sp, dp;
  200593. png_uint_32 i;
  200594. png_uint_32 row_width = row_info->width;
  200595. for (i = 0, sp = dp = row; i < row_width; i++)
  200596. {
  200597. /* does nothing
  200598. *(dp++) = *(sp++);
  200599. *(dp++) = *(sp++);
  200600. *(dp++) = *(sp++);
  200601. */
  200602. sp+=3; dp = sp;
  200603. *(dp++) = (png_byte)(255 - *(sp++));
  200604. }
  200605. }
  200606. /* This inverts the alpha channel in RRGGBBAA */
  200607. else
  200608. {
  200609. png_bytep sp, dp;
  200610. png_uint_32 i;
  200611. png_uint_32 row_width = row_info->width;
  200612. for (i = 0, sp = dp = row; i < row_width; i++)
  200613. {
  200614. /* does nothing
  200615. *(dp++) = *(sp++);
  200616. *(dp++) = *(sp++);
  200617. *(dp++) = *(sp++);
  200618. *(dp++) = *(sp++);
  200619. *(dp++) = *(sp++);
  200620. *(dp++) = *(sp++);
  200621. */
  200622. sp+=6; dp = sp;
  200623. *(dp++) = (png_byte)(255 - *(sp++));
  200624. *(dp++) = (png_byte)(255 - *(sp++));
  200625. }
  200626. }
  200627. }
  200628. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  200629. {
  200630. /* This inverts the alpha channel in GA */
  200631. if (row_info->bit_depth == 8)
  200632. {
  200633. png_bytep sp, dp;
  200634. png_uint_32 i;
  200635. png_uint_32 row_width = row_info->width;
  200636. for (i = 0, sp = dp = row; i < row_width; i++)
  200637. {
  200638. *(dp++) = *(sp++);
  200639. *(dp++) = (png_byte)(255 - *(sp++));
  200640. }
  200641. }
  200642. /* This inverts the alpha channel in GGAA */
  200643. else
  200644. {
  200645. png_bytep sp, dp;
  200646. png_uint_32 i;
  200647. png_uint_32 row_width = row_info->width;
  200648. for (i = 0, sp = dp = row; i < row_width; i++)
  200649. {
  200650. /* does nothing
  200651. *(dp++) = *(sp++);
  200652. *(dp++) = *(sp++);
  200653. */
  200654. sp+=2; dp = sp;
  200655. *(dp++) = (png_byte)(255 - *(sp++));
  200656. *(dp++) = (png_byte)(255 - *(sp++));
  200657. }
  200658. }
  200659. }
  200660. }
  200661. }
  200662. #endif
  200663. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200664. /* undoes intrapixel differencing */
  200665. void /* PRIVATE */
  200666. png_do_write_intrapixel(png_row_infop row_info, png_bytep row)
  200667. {
  200668. png_debug(1, "in png_do_write_intrapixel\n");
  200669. if (
  200670. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200671. row != NULL && row_info != NULL &&
  200672. #endif
  200673. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  200674. {
  200675. int bytes_per_pixel;
  200676. png_uint_32 row_width = row_info->width;
  200677. if (row_info->bit_depth == 8)
  200678. {
  200679. png_bytep rp;
  200680. png_uint_32 i;
  200681. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  200682. bytes_per_pixel = 3;
  200683. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200684. bytes_per_pixel = 4;
  200685. else
  200686. return;
  200687. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  200688. {
  200689. *(rp) = (png_byte)((*rp - *(rp+1))&0xff);
  200690. *(rp+2) = (png_byte)((*(rp+2) - *(rp+1))&0xff);
  200691. }
  200692. }
  200693. else if (row_info->bit_depth == 16)
  200694. {
  200695. png_bytep rp;
  200696. png_uint_32 i;
  200697. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  200698. bytes_per_pixel = 6;
  200699. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200700. bytes_per_pixel = 8;
  200701. else
  200702. return;
  200703. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  200704. {
  200705. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  200706. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  200707. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  200708. png_uint_32 red = (png_uint_32)((s0-s1) & 0xffffL);
  200709. png_uint_32 blue = (png_uint_32)((s2-s1) & 0xffffL);
  200710. *(rp ) = (png_byte)((red >> 8) & 0xff);
  200711. *(rp+1) = (png_byte)(red & 0xff);
  200712. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  200713. *(rp+5) = (png_byte)(blue & 0xff);
  200714. }
  200715. }
  200716. }
  200717. }
  200718. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  200719. #endif /* PNG_WRITE_SUPPORTED */
  200720. /*** End of inlined file: pngwtran.c ***/
  200721. /*** Start of inlined file: pngwutil.c ***/
  200722. /* pngwutil.c - utilities to write a PNG file
  200723. *
  200724. * Last changed in libpng 1.2.20 Septhember 3, 2007
  200725. * For conditions of distribution and use, see copyright notice in png.h
  200726. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  200727. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  200728. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  200729. */
  200730. #define PNG_INTERNAL
  200731. #ifdef PNG_WRITE_SUPPORTED
  200732. /* Place a 32-bit number into a buffer in PNG byte order. We work
  200733. * with unsigned numbers for convenience, although one supported
  200734. * ancillary chunk uses signed (two's complement) numbers.
  200735. */
  200736. void PNGAPI
  200737. png_save_uint_32(png_bytep buf, png_uint_32 i)
  200738. {
  200739. buf[0] = (png_byte)((i >> 24) & 0xff);
  200740. buf[1] = (png_byte)((i >> 16) & 0xff);
  200741. buf[2] = (png_byte)((i >> 8) & 0xff);
  200742. buf[3] = (png_byte)(i & 0xff);
  200743. }
  200744. /* The png_save_int_32 function assumes integers are stored in two's
  200745. * complement format. If this isn't the case, then this routine needs to
  200746. * be modified to write data in two's complement format.
  200747. */
  200748. void PNGAPI
  200749. png_save_int_32(png_bytep buf, png_int_32 i)
  200750. {
  200751. buf[0] = (png_byte)((i >> 24) & 0xff);
  200752. buf[1] = (png_byte)((i >> 16) & 0xff);
  200753. buf[2] = (png_byte)((i >> 8) & 0xff);
  200754. buf[3] = (png_byte)(i & 0xff);
  200755. }
  200756. /* Place a 16-bit number into a buffer in PNG byte order.
  200757. * The parameter is declared unsigned int, not png_uint_16,
  200758. * just to avoid potential problems on pre-ANSI C compilers.
  200759. */
  200760. void PNGAPI
  200761. png_save_uint_16(png_bytep buf, unsigned int i)
  200762. {
  200763. buf[0] = (png_byte)((i >> 8) & 0xff);
  200764. buf[1] = (png_byte)(i & 0xff);
  200765. }
  200766. /* Write a PNG chunk all at once. The type is an array of ASCII characters
  200767. * representing the chunk name. The array must be at least 4 bytes in
  200768. * length, and does not need to be null terminated. To be safe, pass the
  200769. * pre-defined chunk names here, and if you need a new one, define it
  200770. * where the others are defined. The length is the length of the data.
  200771. * All the data must be present. If that is not possible, use the
  200772. * png_write_chunk_start(), png_write_chunk_data(), and png_write_chunk_end()
  200773. * functions instead.
  200774. */
  200775. void PNGAPI
  200776. png_write_chunk(png_structp png_ptr, png_bytep chunk_name,
  200777. png_bytep data, png_size_t length)
  200778. {
  200779. if(png_ptr == NULL) return;
  200780. png_write_chunk_start(png_ptr, chunk_name, (png_uint_32)length);
  200781. png_write_chunk_data(png_ptr, data, length);
  200782. png_write_chunk_end(png_ptr);
  200783. }
  200784. /* Write the start of a PNG chunk. The type is the chunk type.
  200785. * The total_length is the sum of the lengths of all the data you will be
  200786. * passing in png_write_chunk_data().
  200787. */
  200788. void PNGAPI
  200789. png_write_chunk_start(png_structp png_ptr, png_bytep chunk_name,
  200790. png_uint_32 length)
  200791. {
  200792. png_byte buf[4];
  200793. png_debug2(0, "Writing %s chunk (%lu bytes)\n", chunk_name, length);
  200794. if(png_ptr == NULL) return;
  200795. /* write the length */
  200796. png_save_uint_32(buf, length);
  200797. png_write_data(png_ptr, buf, (png_size_t)4);
  200798. /* write the chunk name */
  200799. png_write_data(png_ptr, chunk_name, (png_size_t)4);
  200800. /* reset the crc and run it over the chunk name */
  200801. png_reset_crc(png_ptr);
  200802. png_calculate_crc(png_ptr, chunk_name, (png_size_t)4);
  200803. }
  200804. /* Write the data of a PNG chunk started with png_write_chunk_start().
  200805. * Note that multiple calls to this function are allowed, and that the
  200806. * sum of the lengths from these calls *must* add up to the total_length
  200807. * given to png_write_chunk_start().
  200808. */
  200809. void PNGAPI
  200810. png_write_chunk_data(png_structp png_ptr, png_bytep data, png_size_t length)
  200811. {
  200812. /* write the data, and run the CRC over it */
  200813. if(png_ptr == NULL) return;
  200814. if (data != NULL && length > 0)
  200815. {
  200816. png_calculate_crc(png_ptr, data, length);
  200817. png_write_data(png_ptr, data, length);
  200818. }
  200819. }
  200820. /* Finish a chunk started with png_write_chunk_start(). */
  200821. void PNGAPI
  200822. png_write_chunk_end(png_structp png_ptr)
  200823. {
  200824. png_byte buf[4];
  200825. if(png_ptr == NULL) return;
  200826. /* write the crc */
  200827. png_save_uint_32(buf, png_ptr->crc);
  200828. png_write_data(png_ptr, buf, (png_size_t)4);
  200829. }
  200830. /* Simple function to write the signature. If we have already written
  200831. * the magic bytes of the signature, or more likely, the PNG stream is
  200832. * being embedded into another stream and doesn't need its own signature,
  200833. * we should call png_set_sig_bytes() to tell libpng how many of the
  200834. * bytes have already been written.
  200835. */
  200836. void /* PRIVATE */
  200837. png_write_sig(png_structp png_ptr)
  200838. {
  200839. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  200840. /* write the rest of the 8 byte signature */
  200841. png_write_data(png_ptr, &png_signature[png_ptr->sig_bytes],
  200842. (png_size_t)8 - png_ptr->sig_bytes);
  200843. if(png_ptr->sig_bytes < 3)
  200844. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  200845. }
  200846. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_iCCP_SUPPORTED)
  200847. /*
  200848. * This pair of functions encapsulates the operation of (a) compressing a
  200849. * text string, and (b) issuing it later as a series of chunk data writes.
  200850. * The compression_state structure is shared context for these functions
  200851. * set up by the caller in order to make the whole mess thread-safe.
  200852. */
  200853. typedef struct
  200854. {
  200855. char *input; /* the uncompressed input data */
  200856. int input_len; /* its length */
  200857. int num_output_ptr; /* number of output pointers used */
  200858. int max_output_ptr; /* size of output_ptr */
  200859. png_charpp output_ptr; /* array of pointers to output */
  200860. } compression_state;
  200861. /* compress given text into storage in the png_ptr structure */
  200862. static int /* PRIVATE */
  200863. png_text_compress(png_structp png_ptr,
  200864. png_charp text, png_size_t text_len, int compression,
  200865. compression_state *comp)
  200866. {
  200867. int ret;
  200868. comp->num_output_ptr = 0;
  200869. comp->max_output_ptr = 0;
  200870. comp->output_ptr = NULL;
  200871. comp->input = NULL;
  200872. comp->input_len = 0;
  200873. /* we may just want to pass the text right through */
  200874. if (compression == PNG_TEXT_COMPRESSION_NONE)
  200875. {
  200876. comp->input = text;
  200877. comp->input_len = text_len;
  200878. return((int)text_len);
  200879. }
  200880. if (compression >= PNG_TEXT_COMPRESSION_LAST)
  200881. {
  200882. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  200883. char msg[50];
  200884. png_snprintf(msg, 50, "Unknown compression type %d", compression);
  200885. png_warning(png_ptr, msg);
  200886. #else
  200887. png_warning(png_ptr, "Unknown compression type");
  200888. #endif
  200889. }
  200890. /* We can't write the chunk until we find out how much data we have,
  200891. * which means we need to run the compressor first and save the
  200892. * output. This shouldn't be a problem, as the vast majority of
  200893. * comments should be reasonable, but we will set up an array of
  200894. * malloc'd pointers to be sure.
  200895. *
  200896. * If we knew the application was well behaved, we could simplify this
  200897. * greatly by assuming we can always malloc an output buffer large
  200898. * enough to hold the compressed text ((1001 * text_len / 1000) + 12)
  200899. * and malloc this directly. The only time this would be a bad idea is
  200900. * if we can't malloc more than 64K and we have 64K of random input
  200901. * data, or if the input string is incredibly large (although this
  200902. * wouldn't cause a failure, just a slowdown due to swapping).
  200903. */
  200904. /* set up the compression buffers */
  200905. png_ptr->zstream.avail_in = (uInt)text_len;
  200906. png_ptr->zstream.next_in = (Bytef *)text;
  200907. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200908. png_ptr->zstream.next_out = (Bytef *)png_ptr->zbuf;
  200909. /* this is the same compression loop as in png_write_row() */
  200910. do
  200911. {
  200912. /* compress the data */
  200913. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  200914. if (ret != Z_OK)
  200915. {
  200916. /* error */
  200917. if (png_ptr->zstream.msg != NULL)
  200918. png_error(png_ptr, png_ptr->zstream.msg);
  200919. else
  200920. png_error(png_ptr, "zlib error");
  200921. }
  200922. /* check to see if we need more room */
  200923. if (!(png_ptr->zstream.avail_out))
  200924. {
  200925. /* make sure the output array has room */
  200926. if (comp->num_output_ptr >= comp->max_output_ptr)
  200927. {
  200928. int old_max;
  200929. old_max = comp->max_output_ptr;
  200930. comp->max_output_ptr = comp->num_output_ptr + 4;
  200931. if (comp->output_ptr != NULL)
  200932. {
  200933. png_charpp old_ptr;
  200934. old_ptr = comp->output_ptr;
  200935. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200936. (png_uint_32)(comp->max_output_ptr *
  200937. png_sizeof (png_charpp)));
  200938. png_memcpy(comp->output_ptr, old_ptr, old_max
  200939. * png_sizeof (png_charp));
  200940. png_free(png_ptr, old_ptr);
  200941. }
  200942. else
  200943. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200944. (png_uint_32)(comp->max_output_ptr *
  200945. png_sizeof (png_charp)));
  200946. }
  200947. /* save the data */
  200948. comp->output_ptr[comp->num_output_ptr] = (png_charp)png_malloc(png_ptr,
  200949. (png_uint_32)png_ptr->zbuf_size);
  200950. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  200951. png_ptr->zbuf_size);
  200952. comp->num_output_ptr++;
  200953. /* and reset the buffer */
  200954. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200955. png_ptr->zstream.next_out = png_ptr->zbuf;
  200956. }
  200957. /* continue until we don't have any more to compress */
  200958. } while (png_ptr->zstream.avail_in);
  200959. /* finish the compression */
  200960. do
  200961. {
  200962. /* tell zlib we are finished */
  200963. ret = deflate(&png_ptr->zstream, Z_FINISH);
  200964. if (ret == Z_OK)
  200965. {
  200966. /* check to see if we need more room */
  200967. if (!(png_ptr->zstream.avail_out))
  200968. {
  200969. /* check to make sure our output array has room */
  200970. if (comp->num_output_ptr >= comp->max_output_ptr)
  200971. {
  200972. int old_max;
  200973. old_max = comp->max_output_ptr;
  200974. comp->max_output_ptr = comp->num_output_ptr + 4;
  200975. if (comp->output_ptr != NULL)
  200976. {
  200977. png_charpp old_ptr;
  200978. old_ptr = comp->output_ptr;
  200979. /* This could be optimized to realloc() */
  200980. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200981. (png_uint_32)(comp->max_output_ptr *
  200982. png_sizeof (png_charpp)));
  200983. png_memcpy(comp->output_ptr, old_ptr,
  200984. old_max * png_sizeof (png_charp));
  200985. png_free(png_ptr, old_ptr);
  200986. }
  200987. else
  200988. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200989. (png_uint_32)(comp->max_output_ptr *
  200990. png_sizeof (png_charp)));
  200991. }
  200992. /* save off the data */
  200993. comp->output_ptr[comp->num_output_ptr] =
  200994. (png_charp)png_malloc(png_ptr, (png_uint_32)png_ptr->zbuf_size);
  200995. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  200996. png_ptr->zbuf_size);
  200997. comp->num_output_ptr++;
  200998. /* and reset the buffer pointers */
  200999. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  201000. png_ptr->zstream.next_out = png_ptr->zbuf;
  201001. }
  201002. }
  201003. else if (ret != Z_STREAM_END)
  201004. {
  201005. /* we got an error */
  201006. if (png_ptr->zstream.msg != NULL)
  201007. png_error(png_ptr, png_ptr->zstream.msg);
  201008. else
  201009. png_error(png_ptr, "zlib error");
  201010. }
  201011. } while (ret != Z_STREAM_END);
  201012. /* text length is number of buffers plus last buffer */
  201013. text_len = png_ptr->zbuf_size * comp->num_output_ptr;
  201014. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  201015. text_len += png_ptr->zbuf_size - (png_size_t)png_ptr->zstream.avail_out;
  201016. return((int)text_len);
  201017. }
  201018. /* ship the compressed text out via chunk writes */
  201019. static void /* PRIVATE */
  201020. png_write_compressed_data_out(png_structp png_ptr, compression_state *comp)
  201021. {
  201022. int i;
  201023. /* handle the no-compression case */
  201024. if (comp->input)
  201025. {
  201026. png_write_chunk_data(png_ptr, (png_bytep)comp->input,
  201027. (png_size_t)comp->input_len);
  201028. return;
  201029. }
  201030. /* write saved output buffers, if any */
  201031. for (i = 0; i < comp->num_output_ptr; i++)
  201032. {
  201033. png_write_chunk_data(png_ptr,(png_bytep)comp->output_ptr[i],
  201034. png_ptr->zbuf_size);
  201035. png_free(png_ptr, comp->output_ptr[i]);
  201036. comp->output_ptr[i]=NULL;
  201037. }
  201038. if (comp->max_output_ptr != 0)
  201039. png_free(png_ptr, comp->output_ptr);
  201040. comp->output_ptr=NULL;
  201041. /* write anything left in zbuf */
  201042. if (png_ptr->zstream.avail_out < (png_uint_32)png_ptr->zbuf_size)
  201043. png_write_chunk_data(png_ptr, png_ptr->zbuf,
  201044. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  201045. /* reset zlib for another zTXt/iTXt or image data */
  201046. deflateReset(&png_ptr->zstream);
  201047. png_ptr->zstream.data_type = Z_BINARY;
  201048. }
  201049. #endif
  201050. /* Write the IHDR chunk, and update the png_struct with the necessary
  201051. * information. Note that the rest of this code depends upon this
  201052. * information being correct.
  201053. */
  201054. void /* PRIVATE */
  201055. png_write_IHDR(png_structp png_ptr, png_uint_32 width, png_uint_32 height,
  201056. int bit_depth, int color_type, int compression_type, int filter_type,
  201057. int interlace_type)
  201058. {
  201059. #ifdef PNG_USE_LOCAL_ARRAYS
  201060. PNG_IHDR;
  201061. #endif
  201062. png_byte buf[13]; /* buffer to store the IHDR info */
  201063. png_debug(1, "in png_write_IHDR\n");
  201064. /* Check that we have valid input data from the application info */
  201065. switch (color_type)
  201066. {
  201067. case PNG_COLOR_TYPE_GRAY:
  201068. switch (bit_depth)
  201069. {
  201070. case 1:
  201071. case 2:
  201072. case 4:
  201073. case 8:
  201074. case 16: png_ptr->channels = 1; break;
  201075. default: png_error(png_ptr,"Invalid bit depth for grayscale image");
  201076. }
  201077. break;
  201078. case PNG_COLOR_TYPE_RGB:
  201079. if (bit_depth != 8 && bit_depth != 16)
  201080. png_error(png_ptr, "Invalid bit depth for RGB image");
  201081. png_ptr->channels = 3;
  201082. break;
  201083. case PNG_COLOR_TYPE_PALETTE:
  201084. switch (bit_depth)
  201085. {
  201086. case 1:
  201087. case 2:
  201088. case 4:
  201089. case 8: png_ptr->channels = 1; break;
  201090. default: png_error(png_ptr, "Invalid bit depth for paletted image");
  201091. }
  201092. break;
  201093. case PNG_COLOR_TYPE_GRAY_ALPHA:
  201094. if (bit_depth != 8 && bit_depth != 16)
  201095. png_error(png_ptr, "Invalid bit depth for grayscale+alpha image");
  201096. png_ptr->channels = 2;
  201097. break;
  201098. case PNG_COLOR_TYPE_RGB_ALPHA:
  201099. if (bit_depth != 8 && bit_depth != 16)
  201100. png_error(png_ptr, "Invalid bit depth for RGBA image");
  201101. png_ptr->channels = 4;
  201102. break;
  201103. default:
  201104. png_error(png_ptr, "Invalid image color type specified");
  201105. }
  201106. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  201107. {
  201108. png_warning(png_ptr, "Invalid compression type specified");
  201109. compression_type = PNG_COMPRESSION_TYPE_BASE;
  201110. }
  201111. /* Write filter_method 64 (intrapixel differencing) only if
  201112. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  201113. * 2. Libpng did not write a PNG signature (this filter_method is only
  201114. * used in PNG datastreams that are embedded in MNG datastreams) and
  201115. * 3. The application called png_permit_mng_features with a mask that
  201116. * included PNG_FLAG_MNG_FILTER_64 and
  201117. * 4. The filter_method is 64 and
  201118. * 5. The color_type is RGB or RGBA
  201119. */
  201120. if (
  201121. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201122. !((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  201123. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  201124. (color_type == PNG_COLOR_TYPE_RGB ||
  201125. color_type == PNG_COLOR_TYPE_RGB_ALPHA) &&
  201126. (filter_type == PNG_INTRAPIXEL_DIFFERENCING)) &&
  201127. #endif
  201128. filter_type != PNG_FILTER_TYPE_BASE)
  201129. {
  201130. png_warning(png_ptr, "Invalid filter type specified");
  201131. filter_type = PNG_FILTER_TYPE_BASE;
  201132. }
  201133. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  201134. if (interlace_type != PNG_INTERLACE_NONE &&
  201135. interlace_type != PNG_INTERLACE_ADAM7)
  201136. {
  201137. png_warning(png_ptr, "Invalid interlace type specified");
  201138. interlace_type = PNG_INTERLACE_ADAM7;
  201139. }
  201140. #else
  201141. interlace_type=PNG_INTERLACE_NONE;
  201142. #endif
  201143. /* save off the relevent information */
  201144. png_ptr->bit_depth = (png_byte)bit_depth;
  201145. png_ptr->color_type = (png_byte)color_type;
  201146. png_ptr->interlaced = (png_byte)interlace_type;
  201147. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201148. png_ptr->filter_type = (png_byte)filter_type;
  201149. #endif
  201150. png_ptr->compression_type = (png_byte)compression_type;
  201151. png_ptr->width = width;
  201152. png_ptr->height = height;
  201153. png_ptr->pixel_depth = (png_byte)(bit_depth * png_ptr->channels);
  201154. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, width);
  201155. /* set the usr info, so any transformations can modify it */
  201156. png_ptr->usr_width = png_ptr->width;
  201157. png_ptr->usr_bit_depth = png_ptr->bit_depth;
  201158. png_ptr->usr_channels = png_ptr->channels;
  201159. /* pack the header information into the buffer */
  201160. png_save_uint_32(buf, width);
  201161. png_save_uint_32(buf + 4, height);
  201162. buf[8] = (png_byte)bit_depth;
  201163. buf[9] = (png_byte)color_type;
  201164. buf[10] = (png_byte)compression_type;
  201165. buf[11] = (png_byte)filter_type;
  201166. buf[12] = (png_byte)interlace_type;
  201167. /* write the chunk */
  201168. png_write_chunk(png_ptr, png_IHDR, buf, (png_size_t)13);
  201169. /* initialize zlib with PNG info */
  201170. png_ptr->zstream.zalloc = png_zalloc;
  201171. png_ptr->zstream.zfree = png_zfree;
  201172. png_ptr->zstream.opaque = (voidpf)png_ptr;
  201173. if (!(png_ptr->do_filter))
  201174. {
  201175. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE ||
  201176. png_ptr->bit_depth < 8)
  201177. png_ptr->do_filter = PNG_FILTER_NONE;
  201178. else
  201179. png_ptr->do_filter = PNG_ALL_FILTERS;
  201180. }
  201181. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_STRATEGY))
  201182. {
  201183. if (png_ptr->do_filter != PNG_FILTER_NONE)
  201184. png_ptr->zlib_strategy = Z_FILTERED;
  201185. else
  201186. png_ptr->zlib_strategy = Z_DEFAULT_STRATEGY;
  201187. }
  201188. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_LEVEL))
  201189. png_ptr->zlib_level = Z_DEFAULT_COMPRESSION;
  201190. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL))
  201191. png_ptr->zlib_mem_level = 8;
  201192. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS))
  201193. png_ptr->zlib_window_bits = 15;
  201194. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_METHOD))
  201195. png_ptr->zlib_method = 8;
  201196. if (deflateInit2(&png_ptr->zstream, png_ptr->zlib_level,
  201197. png_ptr->zlib_method, png_ptr->zlib_window_bits,
  201198. png_ptr->zlib_mem_level, png_ptr->zlib_strategy) != Z_OK)
  201199. png_error(png_ptr, "zlib failed to initialize compressor");
  201200. png_ptr->zstream.next_out = png_ptr->zbuf;
  201201. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  201202. /* libpng is not interested in zstream.data_type */
  201203. /* set it to a predefined value, to avoid its evaluation inside zlib */
  201204. png_ptr->zstream.data_type = Z_BINARY;
  201205. png_ptr->mode = PNG_HAVE_IHDR;
  201206. }
  201207. /* write the palette. We are careful not to trust png_color to be in the
  201208. * correct order for PNG, so people can redefine it to any convenient
  201209. * structure.
  201210. */
  201211. void /* PRIVATE */
  201212. png_write_PLTE(png_structp png_ptr, png_colorp palette, png_uint_32 num_pal)
  201213. {
  201214. #ifdef PNG_USE_LOCAL_ARRAYS
  201215. PNG_PLTE;
  201216. #endif
  201217. png_uint_32 i;
  201218. png_colorp pal_ptr;
  201219. png_byte buf[3];
  201220. png_debug(1, "in png_write_PLTE\n");
  201221. if ((
  201222. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201223. !(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) &&
  201224. #endif
  201225. num_pal == 0) || num_pal > 256)
  201226. {
  201227. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  201228. {
  201229. png_error(png_ptr, "Invalid number of colors in palette");
  201230. }
  201231. else
  201232. {
  201233. png_warning(png_ptr, "Invalid number of colors in palette");
  201234. return;
  201235. }
  201236. }
  201237. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  201238. {
  201239. png_warning(png_ptr,
  201240. "Ignoring request to write a PLTE chunk in grayscale PNG");
  201241. return;
  201242. }
  201243. png_ptr->num_palette = (png_uint_16)num_pal;
  201244. png_debug1(3, "num_palette = %d\n", png_ptr->num_palette);
  201245. png_write_chunk_start(png_ptr, png_PLTE, num_pal * 3);
  201246. #ifndef PNG_NO_POINTER_INDEXING
  201247. for (i = 0, pal_ptr = palette; i < num_pal; i++, pal_ptr++)
  201248. {
  201249. buf[0] = pal_ptr->red;
  201250. buf[1] = pal_ptr->green;
  201251. buf[2] = pal_ptr->blue;
  201252. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  201253. }
  201254. #else
  201255. /* This is a little slower but some buggy compilers need to do this instead */
  201256. pal_ptr=palette;
  201257. for (i = 0; i < num_pal; i++)
  201258. {
  201259. buf[0] = pal_ptr[i].red;
  201260. buf[1] = pal_ptr[i].green;
  201261. buf[2] = pal_ptr[i].blue;
  201262. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  201263. }
  201264. #endif
  201265. png_write_chunk_end(png_ptr);
  201266. png_ptr->mode |= PNG_HAVE_PLTE;
  201267. }
  201268. /* write an IDAT chunk */
  201269. void /* PRIVATE */
  201270. png_write_IDAT(png_structp png_ptr, png_bytep data, png_size_t length)
  201271. {
  201272. #ifdef PNG_USE_LOCAL_ARRAYS
  201273. PNG_IDAT;
  201274. #endif
  201275. png_debug(1, "in png_write_IDAT\n");
  201276. /* Optimize the CMF field in the zlib stream. */
  201277. /* This hack of the zlib stream is compliant to the stream specification. */
  201278. if (!(png_ptr->mode & PNG_HAVE_IDAT) &&
  201279. png_ptr->compression_type == PNG_COMPRESSION_TYPE_BASE)
  201280. {
  201281. unsigned int z_cmf = data[0]; /* zlib compression method and flags */
  201282. if ((z_cmf & 0x0f) == 8 && (z_cmf & 0xf0) <= 0x70)
  201283. {
  201284. /* Avoid memory underflows and multiplication overflows. */
  201285. /* The conditions below are practically always satisfied;
  201286. however, they still must be checked. */
  201287. if (length >= 2 &&
  201288. png_ptr->height < 16384 && png_ptr->width < 16384)
  201289. {
  201290. png_uint_32 uncompressed_idat_size = png_ptr->height *
  201291. ((png_ptr->width *
  201292. png_ptr->channels * png_ptr->bit_depth + 15) >> 3);
  201293. unsigned int z_cinfo = z_cmf >> 4;
  201294. unsigned int half_z_window_size = 1 << (z_cinfo + 7);
  201295. while (uncompressed_idat_size <= half_z_window_size &&
  201296. half_z_window_size >= 256)
  201297. {
  201298. z_cinfo--;
  201299. half_z_window_size >>= 1;
  201300. }
  201301. z_cmf = (z_cmf & 0x0f) | (z_cinfo << 4);
  201302. if (data[0] != (png_byte)z_cmf)
  201303. {
  201304. data[0] = (png_byte)z_cmf;
  201305. data[1] &= 0xe0;
  201306. data[1] += (png_byte)(0x1f - ((z_cmf << 8) + data[1]) % 0x1f);
  201307. }
  201308. }
  201309. }
  201310. else
  201311. png_error(png_ptr,
  201312. "Invalid zlib compression method or flags in IDAT");
  201313. }
  201314. png_write_chunk(png_ptr, png_IDAT, data, length);
  201315. png_ptr->mode |= PNG_HAVE_IDAT;
  201316. }
  201317. /* write an IEND chunk */
  201318. void /* PRIVATE */
  201319. png_write_IEND(png_structp png_ptr)
  201320. {
  201321. #ifdef PNG_USE_LOCAL_ARRAYS
  201322. PNG_IEND;
  201323. #endif
  201324. png_debug(1, "in png_write_IEND\n");
  201325. png_write_chunk(png_ptr, png_IEND, png_bytep_NULL,
  201326. (png_size_t)0);
  201327. png_ptr->mode |= PNG_HAVE_IEND;
  201328. }
  201329. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  201330. /* write a gAMA chunk */
  201331. #ifdef PNG_FLOATING_POINT_SUPPORTED
  201332. void /* PRIVATE */
  201333. png_write_gAMA(png_structp png_ptr, double file_gamma)
  201334. {
  201335. #ifdef PNG_USE_LOCAL_ARRAYS
  201336. PNG_gAMA;
  201337. #endif
  201338. png_uint_32 igamma;
  201339. png_byte buf[4];
  201340. png_debug(1, "in png_write_gAMA\n");
  201341. /* file_gamma is saved in 1/100,000ths */
  201342. igamma = (png_uint_32)(file_gamma * 100000.0 + 0.5);
  201343. png_save_uint_32(buf, igamma);
  201344. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  201345. }
  201346. #endif
  201347. #ifdef PNG_FIXED_POINT_SUPPORTED
  201348. void /* PRIVATE */
  201349. png_write_gAMA_fixed(png_structp png_ptr, png_fixed_point file_gamma)
  201350. {
  201351. #ifdef PNG_USE_LOCAL_ARRAYS
  201352. PNG_gAMA;
  201353. #endif
  201354. png_byte buf[4];
  201355. png_debug(1, "in png_write_gAMA\n");
  201356. /* file_gamma is saved in 1/100,000ths */
  201357. png_save_uint_32(buf, (png_uint_32)file_gamma);
  201358. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  201359. }
  201360. #endif
  201361. #endif
  201362. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  201363. /* write a sRGB chunk */
  201364. void /* PRIVATE */
  201365. png_write_sRGB(png_structp png_ptr, int srgb_intent)
  201366. {
  201367. #ifdef PNG_USE_LOCAL_ARRAYS
  201368. PNG_sRGB;
  201369. #endif
  201370. png_byte buf[1];
  201371. png_debug(1, "in png_write_sRGB\n");
  201372. if(srgb_intent >= PNG_sRGB_INTENT_LAST)
  201373. png_warning(png_ptr,
  201374. "Invalid sRGB rendering intent specified");
  201375. buf[0]=(png_byte)srgb_intent;
  201376. png_write_chunk(png_ptr, png_sRGB, buf, (png_size_t)1);
  201377. }
  201378. #endif
  201379. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  201380. /* write an iCCP chunk */
  201381. void /* PRIVATE */
  201382. png_write_iCCP(png_structp png_ptr, png_charp name, int compression_type,
  201383. png_charp profile, int profile_len)
  201384. {
  201385. #ifdef PNG_USE_LOCAL_ARRAYS
  201386. PNG_iCCP;
  201387. #endif
  201388. png_size_t name_len;
  201389. png_charp new_name;
  201390. compression_state comp;
  201391. int embedded_profile_len = 0;
  201392. png_debug(1, "in png_write_iCCP\n");
  201393. comp.num_output_ptr = 0;
  201394. comp.max_output_ptr = 0;
  201395. comp.output_ptr = NULL;
  201396. comp.input = NULL;
  201397. comp.input_len = 0;
  201398. if (name == NULL || (name_len = png_check_keyword(png_ptr, name,
  201399. &new_name)) == 0)
  201400. {
  201401. png_warning(png_ptr, "Empty keyword in iCCP chunk");
  201402. return;
  201403. }
  201404. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  201405. png_warning(png_ptr, "Unknown compression type in iCCP chunk");
  201406. if (profile == NULL)
  201407. profile_len = 0;
  201408. if (profile_len > 3)
  201409. embedded_profile_len =
  201410. ((*( (png_bytep)profile ))<<24) |
  201411. ((*( (png_bytep)profile+1))<<16) |
  201412. ((*( (png_bytep)profile+2))<< 8) |
  201413. ((*( (png_bytep)profile+3)) );
  201414. if (profile_len < embedded_profile_len)
  201415. {
  201416. png_warning(png_ptr,
  201417. "Embedded profile length too large in iCCP chunk");
  201418. return;
  201419. }
  201420. if (profile_len > embedded_profile_len)
  201421. {
  201422. png_warning(png_ptr,
  201423. "Truncating profile to actual length in iCCP chunk");
  201424. profile_len = embedded_profile_len;
  201425. }
  201426. if (profile_len)
  201427. profile_len = png_text_compress(png_ptr, profile, (png_size_t)profile_len,
  201428. PNG_COMPRESSION_TYPE_BASE, &comp);
  201429. /* make sure we include the NULL after the name and the compression type */
  201430. png_write_chunk_start(png_ptr, png_iCCP,
  201431. (png_uint_32)name_len+profile_len+2);
  201432. new_name[name_len+1]=0x00;
  201433. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 2);
  201434. if (profile_len)
  201435. png_write_compressed_data_out(png_ptr, &comp);
  201436. png_write_chunk_end(png_ptr);
  201437. png_free(png_ptr, new_name);
  201438. }
  201439. #endif
  201440. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  201441. /* write a sPLT chunk */
  201442. void /* PRIVATE */
  201443. png_write_sPLT(png_structp png_ptr, png_sPLT_tp spalette)
  201444. {
  201445. #ifdef PNG_USE_LOCAL_ARRAYS
  201446. PNG_sPLT;
  201447. #endif
  201448. png_size_t name_len;
  201449. png_charp new_name;
  201450. png_byte entrybuf[10];
  201451. int entry_size = (spalette->depth == 8 ? 6 : 10);
  201452. int palette_size = entry_size * spalette->nentries;
  201453. png_sPLT_entryp ep;
  201454. #ifdef PNG_NO_POINTER_INDEXING
  201455. int i;
  201456. #endif
  201457. png_debug(1, "in png_write_sPLT\n");
  201458. if (spalette->name == NULL || (name_len = png_check_keyword(png_ptr,
  201459. spalette->name, &new_name))==0)
  201460. {
  201461. png_warning(png_ptr, "Empty keyword in sPLT chunk");
  201462. return;
  201463. }
  201464. /* make sure we include the NULL after the name */
  201465. png_write_chunk_start(png_ptr, png_sPLT,
  201466. (png_uint_32)(name_len + 2 + palette_size));
  201467. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 1);
  201468. png_write_chunk_data(png_ptr, (png_bytep)&spalette->depth, 1);
  201469. /* loop through each palette entry, writing appropriately */
  201470. #ifndef PNG_NO_POINTER_INDEXING
  201471. for (ep = spalette->entries; ep<spalette->entries+spalette->nentries; ep++)
  201472. {
  201473. if (spalette->depth == 8)
  201474. {
  201475. entrybuf[0] = (png_byte)ep->red;
  201476. entrybuf[1] = (png_byte)ep->green;
  201477. entrybuf[2] = (png_byte)ep->blue;
  201478. entrybuf[3] = (png_byte)ep->alpha;
  201479. png_save_uint_16(entrybuf + 4, ep->frequency);
  201480. }
  201481. else
  201482. {
  201483. png_save_uint_16(entrybuf + 0, ep->red);
  201484. png_save_uint_16(entrybuf + 2, ep->green);
  201485. png_save_uint_16(entrybuf + 4, ep->blue);
  201486. png_save_uint_16(entrybuf + 6, ep->alpha);
  201487. png_save_uint_16(entrybuf + 8, ep->frequency);
  201488. }
  201489. png_write_chunk_data(png_ptr, entrybuf, (png_size_t)entry_size);
  201490. }
  201491. #else
  201492. ep=spalette->entries;
  201493. for (i=0; i>spalette->nentries; i++)
  201494. {
  201495. if (spalette->depth == 8)
  201496. {
  201497. entrybuf[0] = (png_byte)ep[i].red;
  201498. entrybuf[1] = (png_byte)ep[i].green;
  201499. entrybuf[2] = (png_byte)ep[i].blue;
  201500. entrybuf[3] = (png_byte)ep[i].alpha;
  201501. png_save_uint_16(entrybuf + 4, ep[i].frequency);
  201502. }
  201503. else
  201504. {
  201505. png_save_uint_16(entrybuf + 0, ep[i].red);
  201506. png_save_uint_16(entrybuf + 2, ep[i].green);
  201507. png_save_uint_16(entrybuf + 4, ep[i].blue);
  201508. png_save_uint_16(entrybuf + 6, ep[i].alpha);
  201509. png_save_uint_16(entrybuf + 8, ep[i].frequency);
  201510. }
  201511. png_write_chunk_data(png_ptr, entrybuf, entry_size);
  201512. }
  201513. #endif
  201514. png_write_chunk_end(png_ptr);
  201515. png_free(png_ptr, new_name);
  201516. }
  201517. #endif
  201518. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  201519. /* write the sBIT chunk */
  201520. void /* PRIVATE */
  201521. png_write_sBIT(png_structp png_ptr, png_color_8p sbit, int color_type)
  201522. {
  201523. #ifdef PNG_USE_LOCAL_ARRAYS
  201524. PNG_sBIT;
  201525. #endif
  201526. png_byte buf[4];
  201527. png_size_t size;
  201528. png_debug(1, "in png_write_sBIT\n");
  201529. /* make sure we don't depend upon the order of PNG_COLOR_8 */
  201530. if (color_type & PNG_COLOR_MASK_COLOR)
  201531. {
  201532. png_byte maxbits;
  201533. maxbits = (png_byte)(color_type==PNG_COLOR_TYPE_PALETTE ? 8 :
  201534. png_ptr->usr_bit_depth);
  201535. if (sbit->red == 0 || sbit->red > maxbits ||
  201536. sbit->green == 0 || sbit->green > maxbits ||
  201537. sbit->blue == 0 || sbit->blue > maxbits)
  201538. {
  201539. png_warning(png_ptr, "Invalid sBIT depth specified");
  201540. return;
  201541. }
  201542. buf[0] = sbit->red;
  201543. buf[1] = sbit->green;
  201544. buf[2] = sbit->blue;
  201545. size = 3;
  201546. }
  201547. else
  201548. {
  201549. if (sbit->gray == 0 || sbit->gray > png_ptr->usr_bit_depth)
  201550. {
  201551. png_warning(png_ptr, "Invalid sBIT depth specified");
  201552. return;
  201553. }
  201554. buf[0] = sbit->gray;
  201555. size = 1;
  201556. }
  201557. if (color_type & PNG_COLOR_MASK_ALPHA)
  201558. {
  201559. if (sbit->alpha == 0 || sbit->alpha > png_ptr->usr_bit_depth)
  201560. {
  201561. png_warning(png_ptr, "Invalid sBIT depth specified");
  201562. return;
  201563. }
  201564. buf[size++] = sbit->alpha;
  201565. }
  201566. png_write_chunk(png_ptr, png_sBIT, buf, size);
  201567. }
  201568. #endif
  201569. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  201570. /* write the cHRM chunk */
  201571. #ifdef PNG_FLOATING_POINT_SUPPORTED
  201572. void /* PRIVATE */
  201573. png_write_cHRM(png_structp png_ptr, double white_x, double white_y,
  201574. double red_x, double red_y, double green_x, double green_y,
  201575. double blue_x, double blue_y)
  201576. {
  201577. #ifdef PNG_USE_LOCAL_ARRAYS
  201578. PNG_cHRM;
  201579. #endif
  201580. png_byte buf[32];
  201581. png_uint_32 itemp;
  201582. png_debug(1, "in png_write_cHRM\n");
  201583. /* each value is saved in 1/100,000ths */
  201584. if (white_x < 0 || white_x > 0.8 || white_y < 0 || white_y > 0.8 ||
  201585. white_x + white_y > 1.0)
  201586. {
  201587. png_warning(png_ptr, "Invalid cHRM white point specified");
  201588. #if !defined(PNG_NO_CONSOLE_IO)
  201589. fprintf(stderr,"white_x=%f, white_y=%f\n",white_x, white_y);
  201590. #endif
  201591. return;
  201592. }
  201593. itemp = (png_uint_32)(white_x * 100000.0 + 0.5);
  201594. png_save_uint_32(buf, itemp);
  201595. itemp = (png_uint_32)(white_y * 100000.0 + 0.5);
  201596. png_save_uint_32(buf + 4, itemp);
  201597. if (red_x < 0 || red_y < 0 || red_x + red_y > 1.0)
  201598. {
  201599. png_warning(png_ptr, "Invalid cHRM red point specified");
  201600. return;
  201601. }
  201602. itemp = (png_uint_32)(red_x * 100000.0 + 0.5);
  201603. png_save_uint_32(buf + 8, itemp);
  201604. itemp = (png_uint_32)(red_y * 100000.0 + 0.5);
  201605. png_save_uint_32(buf + 12, itemp);
  201606. if (green_x < 0 || green_y < 0 || green_x + green_y > 1.0)
  201607. {
  201608. png_warning(png_ptr, "Invalid cHRM green point specified");
  201609. return;
  201610. }
  201611. itemp = (png_uint_32)(green_x * 100000.0 + 0.5);
  201612. png_save_uint_32(buf + 16, itemp);
  201613. itemp = (png_uint_32)(green_y * 100000.0 + 0.5);
  201614. png_save_uint_32(buf + 20, itemp);
  201615. if (blue_x < 0 || blue_y < 0 || blue_x + blue_y > 1.0)
  201616. {
  201617. png_warning(png_ptr, "Invalid cHRM blue point specified");
  201618. return;
  201619. }
  201620. itemp = (png_uint_32)(blue_x * 100000.0 + 0.5);
  201621. png_save_uint_32(buf + 24, itemp);
  201622. itemp = (png_uint_32)(blue_y * 100000.0 + 0.5);
  201623. png_save_uint_32(buf + 28, itemp);
  201624. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  201625. }
  201626. #endif
  201627. #ifdef PNG_FIXED_POINT_SUPPORTED
  201628. void /* PRIVATE */
  201629. png_write_cHRM_fixed(png_structp png_ptr, png_fixed_point white_x,
  201630. png_fixed_point white_y, png_fixed_point red_x, png_fixed_point red_y,
  201631. png_fixed_point green_x, png_fixed_point green_y, png_fixed_point blue_x,
  201632. png_fixed_point blue_y)
  201633. {
  201634. #ifdef PNG_USE_LOCAL_ARRAYS
  201635. PNG_cHRM;
  201636. #endif
  201637. png_byte buf[32];
  201638. png_debug(1, "in png_write_cHRM\n");
  201639. /* each value is saved in 1/100,000ths */
  201640. if (white_x > 80000L || white_y > 80000L || white_x + white_y > 100000L)
  201641. {
  201642. png_warning(png_ptr, "Invalid fixed cHRM white point specified");
  201643. #if !defined(PNG_NO_CONSOLE_IO)
  201644. fprintf(stderr,"white_x=%ld, white_y=%ld\n",white_x, white_y);
  201645. #endif
  201646. return;
  201647. }
  201648. png_save_uint_32(buf, (png_uint_32)white_x);
  201649. png_save_uint_32(buf + 4, (png_uint_32)white_y);
  201650. if (red_x + red_y > 100000L)
  201651. {
  201652. png_warning(png_ptr, "Invalid cHRM fixed red point specified");
  201653. return;
  201654. }
  201655. png_save_uint_32(buf + 8, (png_uint_32)red_x);
  201656. png_save_uint_32(buf + 12, (png_uint_32)red_y);
  201657. if (green_x + green_y > 100000L)
  201658. {
  201659. png_warning(png_ptr, "Invalid fixed cHRM green point specified");
  201660. return;
  201661. }
  201662. png_save_uint_32(buf + 16, (png_uint_32)green_x);
  201663. png_save_uint_32(buf + 20, (png_uint_32)green_y);
  201664. if (blue_x + blue_y > 100000L)
  201665. {
  201666. png_warning(png_ptr, "Invalid fixed cHRM blue point specified");
  201667. return;
  201668. }
  201669. png_save_uint_32(buf + 24, (png_uint_32)blue_x);
  201670. png_save_uint_32(buf + 28, (png_uint_32)blue_y);
  201671. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  201672. }
  201673. #endif
  201674. #endif
  201675. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  201676. /* write the tRNS chunk */
  201677. void /* PRIVATE */
  201678. png_write_tRNS(png_structp png_ptr, png_bytep trans, png_color_16p tran,
  201679. int num_trans, int color_type)
  201680. {
  201681. #ifdef PNG_USE_LOCAL_ARRAYS
  201682. PNG_tRNS;
  201683. #endif
  201684. png_byte buf[6];
  201685. png_debug(1, "in png_write_tRNS\n");
  201686. if (color_type == PNG_COLOR_TYPE_PALETTE)
  201687. {
  201688. if (num_trans <= 0 || num_trans > (int)png_ptr->num_palette)
  201689. {
  201690. png_warning(png_ptr,"Invalid number of transparent colors specified");
  201691. return;
  201692. }
  201693. /* write the chunk out as it is */
  201694. png_write_chunk(png_ptr, png_tRNS, trans, (png_size_t)num_trans);
  201695. }
  201696. else if (color_type == PNG_COLOR_TYPE_GRAY)
  201697. {
  201698. /* one 16 bit value */
  201699. if(tran->gray >= (1 << png_ptr->bit_depth))
  201700. {
  201701. png_warning(png_ptr,
  201702. "Ignoring attempt to write tRNS chunk out-of-range for bit_depth");
  201703. return;
  201704. }
  201705. png_save_uint_16(buf, tran->gray);
  201706. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)2);
  201707. }
  201708. else if (color_type == PNG_COLOR_TYPE_RGB)
  201709. {
  201710. /* three 16 bit values */
  201711. png_save_uint_16(buf, tran->red);
  201712. png_save_uint_16(buf + 2, tran->green);
  201713. png_save_uint_16(buf + 4, tran->blue);
  201714. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  201715. {
  201716. png_warning(png_ptr,
  201717. "Ignoring attempt to write 16-bit tRNS chunk when bit_depth is 8");
  201718. return;
  201719. }
  201720. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)6);
  201721. }
  201722. else
  201723. {
  201724. png_warning(png_ptr, "Can't write tRNS with an alpha channel");
  201725. }
  201726. }
  201727. #endif
  201728. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  201729. /* write the background chunk */
  201730. void /* PRIVATE */
  201731. png_write_bKGD(png_structp png_ptr, png_color_16p back, int color_type)
  201732. {
  201733. #ifdef PNG_USE_LOCAL_ARRAYS
  201734. PNG_bKGD;
  201735. #endif
  201736. png_byte buf[6];
  201737. png_debug(1, "in png_write_bKGD\n");
  201738. if (color_type == PNG_COLOR_TYPE_PALETTE)
  201739. {
  201740. if (
  201741. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201742. (png_ptr->num_palette ||
  201743. (!(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE))) &&
  201744. #endif
  201745. back->index > png_ptr->num_palette)
  201746. {
  201747. png_warning(png_ptr, "Invalid background palette index");
  201748. return;
  201749. }
  201750. buf[0] = back->index;
  201751. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)1);
  201752. }
  201753. else if (color_type & PNG_COLOR_MASK_COLOR)
  201754. {
  201755. png_save_uint_16(buf, back->red);
  201756. png_save_uint_16(buf + 2, back->green);
  201757. png_save_uint_16(buf + 4, back->blue);
  201758. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  201759. {
  201760. png_warning(png_ptr,
  201761. "Ignoring attempt to write 16-bit bKGD chunk when bit_depth is 8");
  201762. return;
  201763. }
  201764. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)6);
  201765. }
  201766. else
  201767. {
  201768. if(back->gray >= (1 << png_ptr->bit_depth))
  201769. {
  201770. png_warning(png_ptr,
  201771. "Ignoring attempt to write bKGD chunk out-of-range for bit_depth");
  201772. return;
  201773. }
  201774. png_save_uint_16(buf, back->gray);
  201775. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)2);
  201776. }
  201777. }
  201778. #endif
  201779. #if defined(PNG_WRITE_hIST_SUPPORTED)
  201780. /* write the histogram */
  201781. void /* PRIVATE */
  201782. png_write_hIST(png_structp png_ptr, png_uint_16p hist, int num_hist)
  201783. {
  201784. #ifdef PNG_USE_LOCAL_ARRAYS
  201785. PNG_hIST;
  201786. #endif
  201787. int i;
  201788. png_byte buf[3];
  201789. png_debug(1, "in png_write_hIST\n");
  201790. if (num_hist > (int)png_ptr->num_palette)
  201791. {
  201792. png_debug2(3, "num_hist = %d, num_palette = %d\n", num_hist,
  201793. png_ptr->num_palette);
  201794. png_warning(png_ptr, "Invalid number of histogram entries specified");
  201795. return;
  201796. }
  201797. png_write_chunk_start(png_ptr, png_hIST, (png_uint_32)(num_hist * 2));
  201798. for (i = 0; i < num_hist; i++)
  201799. {
  201800. png_save_uint_16(buf, hist[i]);
  201801. png_write_chunk_data(png_ptr, buf, (png_size_t)2);
  201802. }
  201803. png_write_chunk_end(png_ptr);
  201804. }
  201805. #endif
  201806. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  201807. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  201808. /* Check that the tEXt or zTXt keyword is valid per PNG 1.0 specification,
  201809. * and if invalid, correct the keyword rather than discarding the entire
  201810. * chunk. The PNG 1.0 specification requires keywords 1-79 characters in
  201811. * length, forbids leading or trailing whitespace, multiple internal spaces,
  201812. * and the non-break space (0x80) from ISO 8859-1. Returns keyword length.
  201813. *
  201814. * The new_key is allocated to hold the corrected keyword and must be freed
  201815. * by the calling routine. This avoids problems with trying to write to
  201816. * static keywords without having to have duplicate copies of the strings.
  201817. */
  201818. png_size_t /* PRIVATE */
  201819. png_check_keyword(png_structp png_ptr, png_charp key, png_charpp new_key)
  201820. {
  201821. png_size_t key_len;
  201822. png_charp kp, dp;
  201823. int kflag;
  201824. int kwarn=0;
  201825. png_debug(1, "in png_check_keyword\n");
  201826. *new_key = NULL;
  201827. if (key == NULL || (key_len = png_strlen(key)) == 0)
  201828. {
  201829. png_warning(png_ptr, "zero length keyword");
  201830. return ((png_size_t)0);
  201831. }
  201832. png_debug1(2, "Keyword to be checked is '%s'\n", key);
  201833. *new_key = (png_charp)png_malloc_warn(png_ptr, (png_uint_32)(key_len + 2));
  201834. if (*new_key == NULL)
  201835. {
  201836. png_warning(png_ptr, "Out of memory while procesing keyword");
  201837. return ((png_size_t)0);
  201838. }
  201839. /* Replace non-printing characters with a blank and print a warning */
  201840. for (kp = key, dp = *new_key; *kp != '\0'; kp++, dp++)
  201841. {
  201842. if ((png_byte)*kp < 0x20 ||
  201843. ((png_byte)*kp > 0x7E && (png_byte)*kp < 0xA1))
  201844. {
  201845. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  201846. char msg[40];
  201847. png_snprintf(msg, 40,
  201848. "invalid keyword character 0x%02X", (png_byte)*kp);
  201849. png_warning(png_ptr, msg);
  201850. #else
  201851. png_warning(png_ptr, "invalid character in keyword");
  201852. #endif
  201853. *dp = ' ';
  201854. }
  201855. else
  201856. {
  201857. *dp = *kp;
  201858. }
  201859. }
  201860. *dp = '\0';
  201861. /* Remove any trailing white space. */
  201862. kp = *new_key + key_len - 1;
  201863. if (*kp == ' ')
  201864. {
  201865. png_warning(png_ptr, "trailing spaces removed from keyword");
  201866. while (*kp == ' ')
  201867. {
  201868. *(kp--) = '\0';
  201869. key_len--;
  201870. }
  201871. }
  201872. /* Remove any leading white space. */
  201873. kp = *new_key;
  201874. if (*kp == ' ')
  201875. {
  201876. png_warning(png_ptr, "leading spaces removed from keyword");
  201877. while (*kp == ' ')
  201878. {
  201879. kp++;
  201880. key_len--;
  201881. }
  201882. }
  201883. png_debug1(2, "Checking for multiple internal spaces in '%s'\n", kp);
  201884. /* Remove multiple internal spaces. */
  201885. for (kflag = 0, dp = *new_key; *kp != '\0'; kp++)
  201886. {
  201887. if (*kp == ' ' && kflag == 0)
  201888. {
  201889. *(dp++) = *kp;
  201890. kflag = 1;
  201891. }
  201892. else if (*kp == ' ')
  201893. {
  201894. key_len--;
  201895. kwarn=1;
  201896. }
  201897. else
  201898. {
  201899. *(dp++) = *kp;
  201900. kflag = 0;
  201901. }
  201902. }
  201903. *dp = '\0';
  201904. if(kwarn)
  201905. png_warning(png_ptr, "extra interior spaces removed from keyword");
  201906. if (key_len == 0)
  201907. {
  201908. png_free(png_ptr, *new_key);
  201909. *new_key=NULL;
  201910. png_warning(png_ptr, "Zero length keyword");
  201911. }
  201912. if (key_len > 79)
  201913. {
  201914. png_warning(png_ptr, "keyword length must be 1 - 79 characters");
  201915. new_key[79] = '\0';
  201916. key_len = 79;
  201917. }
  201918. return (key_len);
  201919. }
  201920. #endif
  201921. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  201922. /* write a tEXt chunk */
  201923. void /* PRIVATE */
  201924. png_write_tEXt(png_structp png_ptr, png_charp key, png_charp text,
  201925. png_size_t text_len)
  201926. {
  201927. #ifdef PNG_USE_LOCAL_ARRAYS
  201928. PNG_tEXt;
  201929. #endif
  201930. png_size_t key_len;
  201931. png_charp new_key;
  201932. png_debug(1, "in png_write_tEXt\n");
  201933. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  201934. {
  201935. png_warning(png_ptr, "Empty keyword in tEXt chunk");
  201936. return;
  201937. }
  201938. if (text == NULL || *text == '\0')
  201939. text_len = 0;
  201940. else
  201941. text_len = png_strlen(text);
  201942. /* make sure we include the 0 after the key */
  201943. png_write_chunk_start(png_ptr, png_tEXt, (png_uint_32)key_len+text_len+1);
  201944. /*
  201945. * We leave it to the application to meet PNG-1.0 requirements on the
  201946. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  201947. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  201948. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  201949. */
  201950. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  201951. if (text_len)
  201952. png_write_chunk_data(png_ptr, (png_bytep)text, text_len);
  201953. png_write_chunk_end(png_ptr);
  201954. png_free(png_ptr, new_key);
  201955. }
  201956. #endif
  201957. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  201958. /* write a compressed text chunk */
  201959. void /* PRIVATE */
  201960. png_write_zTXt(png_structp png_ptr, png_charp key, png_charp text,
  201961. png_size_t text_len, int compression)
  201962. {
  201963. #ifdef PNG_USE_LOCAL_ARRAYS
  201964. PNG_zTXt;
  201965. #endif
  201966. png_size_t key_len;
  201967. char buf[1];
  201968. png_charp new_key;
  201969. compression_state comp;
  201970. png_debug(1, "in png_write_zTXt\n");
  201971. comp.num_output_ptr = 0;
  201972. comp.max_output_ptr = 0;
  201973. comp.output_ptr = NULL;
  201974. comp.input = NULL;
  201975. comp.input_len = 0;
  201976. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  201977. {
  201978. png_warning(png_ptr, "Empty keyword in zTXt chunk");
  201979. return;
  201980. }
  201981. if (text == NULL || *text == '\0' || compression==PNG_TEXT_COMPRESSION_NONE)
  201982. {
  201983. png_write_tEXt(png_ptr, new_key, text, (png_size_t)0);
  201984. png_free(png_ptr, new_key);
  201985. return;
  201986. }
  201987. text_len = png_strlen(text);
  201988. /* compute the compressed data; do it now for the length */
  201989. text_len = png_text_compress(png_ptr, text, text_len, compression,
  201990. &comp);
  201991. /* write start of chunk */
  201992. png_write_chunk_start(png_ptr, png_zTXt, (png_uint_32)
  201993. (key_len+text_len+2));
  201994. /* write key */
  201995. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  201996. png_free(png_ptr, new_key);
  201997. buf[0] = (png_byte)compression;
  201998. /* write compression */
  201999. png_write_chunk_data(png_ptr, (png_bytep)buf, (png_size_t)1);
  202000. /* write the compressed data */
  202001. png_write_compressed_data_out(png_ptr, &comp);
  202002. /* close the chunk */
  202003. png_write_chunk_end(png_ptr);
  202004. }
  202005. #endif
  202006. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  202007. /* write an iTXt chunk */
  202008. void /* PRIVATE */
  202009. png_write_iTXt(png_structp png_ptr, int compression, png_charp key,
  202010. png_charp lang, png_charp lang_key, png_charp text)
  202011. {
  202012. #ifdef PNG_USE_LOCAL_ARRAYS
  202013. PNG_iTXt;
  202014. #endif
  202015. png_size_t lang_len, key_len, lang_key_len, text_len;
  202016. png_charp new_lang, new_key;
  202017. png_byte cbuf[2];
  202018. compression_state comp;
  202019. png_debug(1, "in png_write_iTXt\n");
  202020. comp.num_output_ptr = 0;
  202021. comp.max_output_ptr = 0;
  202022. comp.output_ptr = NULL;
  202023. comp.input = NULL;
  202024. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  202025. {
  202026. png_warning(png_ptr, "Empty keyword in iTXt chunk");
  202027. return;
  202028. }
  202029. if (lang == NULL || (lang_len = png_check_keyword(png_ptr, lang, &new_lang))==0)
  202030. {
  202031. png_warning(png_ptr, "Empty language field in iTXt chunk");
  202032. new_lang = NULL;
  202033. lang_len = 0;
  202034. }
  202035. if (lang_key == NULL)
  202036. lang_key_len = 0;
  202037. else
  202038. lang_key_len = png_strlen(lang_key);
  202039. if (text == NULL)
  202040. text_len = 0;
  202041. else
  202042. text_len = png_strlen(text);
  202043. /* compute the compressed data; do it now for the length */
  202044. text_len = png_text_compress(png_ptr, text, text_len, compression-2,
  202045. &comp);
  202046. /* make sure we include the compression flag, the compression byte,
  202047. * and the NULs after the key, lang, and lang_key parts */
  202048. png_write_chunk_start(png_ptr, png_iTXt,
  202049. (png_uint_32)(
  202050. 5 /* comp byte, comp flag, terminators for key, lang and lang_key */
  202051. + key_len
  202052. + lang_len
  202053. + lang_key_len
  202054. + text_len));
  202055. /*
  202056. * We leave it to the application to meet PNG-1.0 requirements on the
  202057. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  202058. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  202059. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  202060. */
  202061. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  202062. /* set the compression flag */
  202063. if (compression == PNG_ITXT_COMPRESSION_NONE || \
  202064. compression == PNG_TEXT_COMPRESSION_NONE)
  202065. cbuf[0] = 0;
  202066. else /* compression == PNG_ITXT_COMPRESSION_zTXt */
  202067. cbuf[0] = 1;
  202068. /* set the compression method */
  202069. cbuf[1] = 0;
  202070. png_write_chunk_data(png_ptr, cbuf, 2);
  202071. cbuf[0] = 0;
  202072. png_write_chunk_data(png_ptr, (new_lang ? (png_bytep)new_lang : cbuf), lang_len + 1);
  202073. png_write_chunk_data(png_ptr, (lang_key ? (png_bytep)lang_key : cbuf), lang_key_len + 1);
  202074. png_write_compressed_data_out(png_ptr, &comp);
  202075. png_write_chunk_end(png_ptr);
  202076. png_free(png_ptr, new_key);
  202077. if (new_lang)
  202078. png_free(png_ptr, new_lang);
  202079. }
  202080. #endif
  202081. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  202082. /* write the oFFs chunk */
  202083. void /* PRIVATE */
  202084. png_write_oFFs(png_structp png_ptr, png_int_32 x_offset, png_int_32 y_offset,
  202085. int unit_type)
  202086. {
  202087. #ifdef PNG_USE_LOCAL_ARRAYS
  202088. PNG_oFFs;
  202089. #endif
  202090. png_byte buf[9];
  202091. png_debug(1, "in png_write_oFFs\n");
  202092. if (unit_type >= PNG_OFFSET_LAST)
  202093. png_warning(png_ptr, "Unrecognized unit type for oFFs chunk");
  202094. png_save_int_32(buf, x_offset);
  202095. png_save_int_32(buf + 4, y_offset);
  202096. buf[8] = (png_byte)unit_type;
  202097. png_write_chunk(png_ptr, png_oFFs, buf, (png_size_t)9);
  202098. }
  202099. #endif
  202100. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  202101. /* write the pCAL chunk (described in the PNG extensions document) */
  202102. void /* PRIVATE */
  202103. png_write_pCAL(png_structp png_ptr, png_charp purpose, png_int_32 X0,
  202104. png_int_32 X1, int type, int nparams, png_charp units, png_charpp params)
  202105. {
  202106. #ifdef PNG_USE_LOCAL_ARRAYS
  202107. PNG_pCAL;
  202108. #endif
  202109. png_size_t purpose_len, units_len, total_len;
  202110. png_uint_32p params_len;
  202111. png_byte buf[10];
  202112. png_charp new_purpose;
  202113. int i;
  202114. png_debug1(1, "in png_write_pCAL (%d parameters)\n", nparams);
  202115. if (type >= PNG_EQUATION_LAST)
  202116. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  202117. purpose_len = png_check_keyword(png_ptr, purpose, &new_purpose) + 1;
  202118. png_debug1(3, "pCAL purpose length = %d\n", (int)purpose_len);
  202119. units_len = png_strlen(units) + (nparams == 0 ? 0 : 1);
  202120. png_debug1(3, "pCAL units length = %d\n", (int)units_len);
  202121. total_len = purpose_len + units_len + 10;
  202122. params_len = (png_uint_32p)png_malloc(png_ptr, (png_uint_32)(nparams
  202123. *png_sizeof(png_uint_32)));
  202124. /* Find the length of each parameter, making sure we don't count the
  202125. null terminator for the last parameter. */
  202126. for (i = 0; i < nparams; i++)
  202127. {
  202128. params_len[i] = png_strlen(params[i]) + (i == nparams - 1 ? 0 : 1);
  202129. png_debug2(3, "pCAL parameter %d length = %lu\n", i, params_len[i]);
  202130. total_len += (png_size_t)params_len[i];
  202131. }
  202132. png_debug1(3, "pCAL total length = %d\n", (int)total_len);
  202133. png_write_chunk_start(png_ptr, png_pCAL, (png_uint_32)total_len);
  202134. png_write_chunk_data(png_ptr, (png_bytep)new_purpose, purpose_len);
  202135. png_save_int_32(buf, X0);
  202136. png_save_int_32(buf + 4, X1);
  202137. buf[8] = (png_byte)type;
  202138. buf[9] = (png_byte)nparams;
  202139. png_write_chunk_data(png_ptr, buf, (png_size_t)10);
  202140. png_write_chunk_data(png_ptr, (png_bytep)units, (png_size_t)units_len);
  202141. png_free(png_ptr, new_purpose);
  202142. for (i = 0; i < nparams; i++)
  202143. {
  202144. png_write_chunk_data(png_ptr, (png_bytep)params[i],
  202145. (png_size_t)params_len[i]);
  202146. }
  202147. png_free(png_ptr, params_len);
  202148. png_write_chunk_end(png_ptr);
  202149. }
  202150. #endif
  202151. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  202152. /* write the sCAL chunk */
  202153. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  202154. void /* PRIVATE */
  202155. png_write_sCAL(png_structp png_ptr, int unit, double width, double height)
  202156. {
  202157. #ifdef PNG_USE_LOCAL_ARRAYS
  202158. PNG_sCAL;
  202159. #endif
  202160. char buf[64];
  202161. png_size_t total_len;
  202162. png_debug(1, "in png_write_sCAL\n");
  202163. buf[0] = (char)unit;
  202164. #if defined(_WIN32_WCE)
  202165. /* sprintf() function is not supported on WindowsCE */
  202166. {
  202167. wchar_t wc_buf[32];
  202168. size_t wc_len;
  202169. swprintf(wc_buf, TEXT("%12.12e"), width);
  202170. wc_len = wcslen(wc_buf);
  202171. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + 1, wc_len, NULL, NULL);
  202172. total_len = wc_len + 2;
  202173. swprintf(wc_buf, TEXT("%12.12e"), height);
  202174. wc_len = wcslen(wc_buf);
  202175. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + total_len, wc_len,
  202176. NULL, NULL);
  202177. total_len += wc_len;
  202178. }
  202179. #else
  202180. png_snprintf(buf + 1, 63, "%12.12e", width);
  202181. total_len = 1 + png_strlen(buf + 1) + 1;
  202182. png_snprintf(buf + total_len, 64-total_len, "%12.12e", height);
  202183. total_len += png_strlen(buf + total_len);
  202184. #endif
  202185. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  202186. png_write_chunk(png_ptr, png_sCAL, (png_bytep)buf, total_len);
  202187. }
  202188. #else
  202189. #ifdef PNG_FIXED_POINT_SUPPORTED
  202190. void /* PRIVATE */
  202191. png_write_sCAL_s(png_structp png_ptr, int unit, png_charp width,
  202192. png_charp height)
  202193. {
  202194. #ifdef PNG_USE_LOCAL_ARRAYS
  202195. PNG_sCAL;
  202196. #endif
  202197. png_byte buf[64];
  202198. png_size_t wlen, hlen, total_len;
  202199. png_debug(1, "in png_write_sCAL_s\n");
  202200. wlen = png_strlen(width);
  202201. hlen = png_strlen(height);
  202202. total_len = wlen + hlen + 2;
  202203. if (total_len > 64)
  202204. {
  202205. png_warning(png_ptr, "Can't write sCAL (buffer too small)");
  202206. return;
  202207. }
  202208. buf[0] = (png_byte)unit;
  202209. png_memcpy(buf + 1, width, wlen + 1); /* append the '\0' here */
  202210. png_memcpy(buf + wlen + 2, height, hlen); /* do NOT append the '\0' here */
  202211. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  202212. png_write_chunk(png_ptr, png_sCAL, buf, total_len);
  202213. }
  202214. #endif
  202215. #endif
  202216. #endif
  202217. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  202218. /* write the pHYs chunk */
  202219. void /* PRIVATE */
  202220. png_write_pHYs(png_structp png_ptr, png_uint_32 x_pixels_per_unit,
  202221. png_uint_32 y_pixels_per_unit,
  202222. int unit_type)
  202223. {
  202224. #ifdef PNG_USE_LOCAL_ARRAYS
  202225. PNG_pHYs;
  202226. #endif
  202227. png_byte buf[9];
  202228. png_debug(1, "in png_write_pHYs\n");
  202229. if (unit_type >= PNG_RESOLUTION_LAST)
  202230. png_warning(png_ptr, "Unrecognized unit type for pHYs chunk");
  202231. png_save_uint_32(buf, x_pixels_per_unit);
  202232. png_save_uint_32(buf + 4, y_pixels_per_unit);
  202233. buf[8] = (png_byte)unit_type;
  202234. png_write_chunk(png_ptr, png_pHYs, buf, (png_size_t)9);
  202235. }
  202236. #endif
  202237. #if defined(PNG_WRITE_tIME_SUPPORTED)
  202238. /* Write the tIME chunk. Use either png_convert_from_struct_tm()
  202239. * or png_convert_from_time_t(), or fill in the structure yourself.
  202240. */
  202241. void /* PRIVATE */
  202242. png_write_tIME(png_structp png_ptr, png_timep mod_time)
  202243. {
  202244. #ifdef PNG_USE_LOCAL_ARRAYS
  202245. PNG_tIME;
  202246. #endif
  202247. png_byte buf[7];
  202248. png_debug(1, "in png_write_tIME\n");
  202249. if (mod_time->month > 12 || mod_time->month < 1 ||
  202250. mod_time->day > 31 || mod_time->day < 1 ||
  202251. mod_time->hour > 23 || mod_time->second > 60)
  202252. {
  202253. png_warning(png_ptr, "Invalid time specified for tIME chunk");
  202254. return;
  202255. }
  202256. png_save_uint_16(buf, mod_time->year);
  202257. buf[2] = mod_time->month;
  202258. buf[3] = mod_time->day;
  202259. buf[4] = mod_time->hour;
  202260. buf[5] = mod_time->minute;
  202261. buf[6] = mod_time->second;
  202262. png_write_chunk(png_ptr, png_tIME, buf, (png_size_t)7);
  202263. }
  202264. #endif
  202265. /* initializes the row writing capability of libpng */
  202266. void /* PRIVATE */
  202267. png_write_start_row(png_structp png_ptr)
  202268. {
  202269. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202270. #ifdef PNG_USE_LOCAL_ARRAYS
  202271. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  202272. /* start of interlace block */
  202273. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  202274. /* offset to next interlace block */
  202275. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  202276. /* start of interlace block in the y direction */
  202277. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  202278. /* offset to next interlace block in the y direction */
  202279. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  202280. #endif
  202281. #endif
  202282. png_size_t buf_size;
  202283. png_debug(1, "in png_write_start_row\n");
  202284. buf_size = (png_size_t)(PNG_ROWBYTES(
  202285. png_ptr->usr_channels*png_ptr->usr_bit_depth,png_ptr->width)+1);
  202286. /* set up row buffer */
  202287. png_ptr->row_buf = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  202288. png_ptr->row_buf[0] = PNG_FILTER_VALUE_NONE;
  202289. #ifndef PNG_NO_WRITE_FILTERING
  202290. /* set up filtering buffer, if using this filter */
  202291. if (png_ptr->do_filter & PNG_FILTER_SUB)
  202292. {
  202293. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  202294. (png_ptr->rowbytes + 1));
  202295. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  202296. }
  202297. /* We only need to keep the previous row if we are using one of these. */
  202298. if (png_ptr->do_filter & (PNG_FILTER_AVG | PNG_FILTER_UP | PNG_FILTER_PAETH))
  202299. {
  202300. /* set up previous row buffer */
  202301. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  202302. png_memset(png_ptr->prev_row, 0, buf_size);
  202303. if (png_ptr->do_filter & PNG_FILTER_UP)
  202304. {
  202305. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  202306. (png_ptr->rowbytes + 1));
  202307. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  202308. }
  202309. if (png_ptr->do_filter & PNG_FILTER_AVG)
  202310. {
  202311. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  202312. (png_ptr->rowbytes + 1));
  202313. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  202314. }
  202315. if (png_ptr->do_filter & PNG_FILTER_PAETH)
  202316. {
  202317. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  202318. (png_ptr->rowbytes + 1));
  202319. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  202320. }
  202321. #endif /* PNG_NO_WRITE_FILTERING */
  202322. }
  202323. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202324. /* if interlaced, we need to set up width and height of pass */
  202325. if (png_ptr->interlaced)
  202326. {
  202327. if (!(png_ptr->transformations & PNG_INTERLACE))
  202328. {
  202329. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  202330. png_pass_ystart[0]) / png_pass_yinc[0];
  202331. png_ptr->usr_width = (png_ptr->width + png_pass_inc[0] - 1 -
  202332. png_pass_start[0]) / png_pass_inc[0];
  202333. }
  202334. else
  202335. {
  202336. png_ptr->num_rows = png_ptr->height;
  202337. png_ptr->usr_width = png_ptr->width;
  202338. }
  202339. }
  202340. else
  202341. #endif
  202342. {
  202343. png_ptr->num_rows = png_ptr->height;
  202344. png_ptr->usr_width = png_ptr->width;
  202345. }
  202346. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  202347. png_ptr->zstream.next_out = png_ptr->zbuf;
  202348. }
  202349. /* Internal use only. Called when finished processing a row of data. */
  202350. void /* PRIVATE */
  202351. png_write_finish_row(png_structp png_ptr)
  202352. {
  202353. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202354. #ifdef PNG_USE_LOCAL_ARRAYS
  202355. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  202356. /* start of interlace block */
  202357. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  202358. /* offset to next interlace block */
  202359. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  202360. /* start of interlace block in the y direction */
  202361. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  202362. /* offset to next interlace block in the y direction */
  202363. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  202364. #endif
  202365. #endif
  202366. int ret;
  202367. png_debug(1, "in png_write_finish_row\n");
  202368. /* next row */
  202369. png_ptr->row_number++;
  202370. /* see if we are done */
  202371. if (png_ptr->row_number < png_ptr->num_rows)
  202372. return;
  202373. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202374. /* if interlaced, go to next pass */
  202375. if (png_ptr->interlaced)
  202376. {
  202377. png_ptr->row_number = 0;
  202378. if (png_ptr->transformations & PNG_INTERLACE)
  202379. {
  202380. png_ptr->pass++;
  202381. }
  202382. else
  202383. {
  202384. /* loop until we find a non-zero width or height pass */
  202385. do
  202386. {
  202387. png_ptr->pass++;
  202388. if (png_ptr->pass >= 7)
  202389. break;
  202390. png_ptr->usr_width = (png_ptr->width +
  202391. png_pass_inc[png_ptr->pass] - 1 -
  202392. png_pass_start[png_ptr->pass]) /
  202393. png_pass_inc[png_ptr->pass];
  202394. png_ptr->num_rows = (png_ptr->height +
  202395. png_pass_yinc[png_ptr->pass] - 1 -
  202396. png_pass_ystart[png_ptr->pass]) /
  202397. png_pass_yinc[png_ptr->pass];
  202398. if (png_ptr->transformations & PNG_INTERLACE)
  202399. break;
  202400. } while (png_ptr->usr_width == 0 || png_ptr->num_rows == 0);
  202401. }
  202402. /* reset the row above the image for the next pass */
  202403. if (png_ptr->pass < 7)
  202404. {
  202405. if (png_ptr->prev_row != NULL)
  202406. png_memset(png_ptr->prev_row, 0,
  202407. (png_size_t)(PNG_ROWBYTES(png_ptr->usr_channels*
  202408. png_ptr->usr_bit_depth,png_ptr->width))+1);
  202409. return;
  202410. }
  202411. }
  202412. #endif
  202413. /* if we get here, we've just written the last row, so we need
  202414. to flush the compressor */
  202415. do
  202416. {
  202417. /* tell the compressor we are done */
  202418. ret = deflate(&png_ptr->zstream, Z_FINISH);
  202419. /* check for an error */
  202420. if (ret == Z_OK)
  202421. {
  202422. /* check to see if we need more room */
  202423. if (!(png_ptr->zstream.avail_out))
  202424. {
  202425. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  202426. png_ptr->zstream.next_out = png_ptr->zbuf;
  202427. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  202428. }
  202429. }
  202430. else if (ret != Z_STREAM_END)
  202431. {
  202432. if (png_ptr->zstream.msg != NULL)
  202433. png_error(png_ptr, png_ptr->zstream.msg);
  202434. else
  202435. png_error(png_ptr, "zlib error");
  202436. }
  202437. } while (ret != Z_STREAM_END);
  202438. /* write any extra space */
  202439. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  202440. {
  202441. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size -
  202442. png_ptr->zstream.avail_out);
  202443. }
  202444. deflateReset(&png_ptr->zstream);
  202445. png_ptr->zstream.data_type = Z_BINARY;
  202446. }
  202447. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  202448. /* Pick out the correct pixels for the interlace pass.
  202449. * The basic idea here is to go through the row with a source
  202450. * pointer and a destination pointer (sp and dp), and copy the
  202451. * correct pixels for the pass. As the row gets compacted,
  202452. * sp will always be >= dp, so we should never overwrite anything.
  202453. * See the default: case for the easiest code to understand.
  202454. */
  202455. void /* PRIVATE */
  202456. png_do_write_interlace(png_row_infop row_info, png_bytep row, int pass)
  202457. {
  202458. #ifdef PNG_USE_LOCAL_ARRAYS
  202459. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  202460. /* start of interlace block */
  202461. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  202462. /* offset to next interlace block */
  202463. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  202464. #endif
  202465. png_debug(1, "in png_do_write_interlace\n");
  202466. /* we don't have to do anything on the last pass (6) */
  202467. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  202468. if (row != NULL && row_info != NULL && pass < 6)
  202469. #else
  202470. if (pass < 6)
  202471. #endif
  202472. {
  202473. /* each pixel depth is handled separately */
  202474. switch (row_info->pixel_depth)
  202475. {
  202476. case 1:
  202477. {
  202478. png_bytep sp;
  202479. png_bytep dp;
  202480. int shift;
  202481. int d;
  202482. int value;
  202483. png_uint_32 i;
  202484. png_uint_32 row_width = row_info->width;
  202485. dp = row;
  202486. d = 0;
  202487. shift = 7;
  202488. for (i = png_pass_start[pass]; i < row_width;
  202489. i += png_pass_inc[pass])
  202490. {
  202491. sp = row + (png_size_t)(i >> 3);
  202492. value = (int)(*sp >> (7 - (int)(i & 0x07))) & 0x01;
  202493. d |= (value << shift);
  202494. if (shift == 0)
  202495. {
  202496. shift = 7;
  202497. *dp++ = (png_byte)d;
  202498. d = 0;
  202499. }
  202500. else
  202501. shift--;
  202502. }
  202503. if (shift != 7)
  202504. *dp = (png_byte)d;
  202505. break;
  202506. }
  202507. case 2:
  202508. {
  202509. png_bytep sp;
  202510. png_bytep dp;
  202511. int shift;
  202512. int d;
  202513. int value;
  202514. png_uint_32 i;
  202515. png_uint_32 row_width = row_info->width;
  202516. dp = row;
  202517. shift = 6;
  202518. d = 0;
  202519. for (i = png_pass_start[pass]; i < row_width;
  202520. i += png_pass_inc[pass])
  202521. {
  202522. sp = row + (png_size_t)(i >> 2);
  202523. value = (*sp >> ((3 - (int)(i & 0x03)) << 1)) & 0x03;
  202524. d |= (value << shift);
  202525. if (shift == 0)
  202526. {
  202527. shift = 6;
  202528. *dp++ = (png_byte)d;
  202529. d = 0;
  202530. }
  202531. else
  202532. shift -= 2;
  202533. }
  202534. if (shift != 6)
  202535. *dp = (png_byte)d;
  202536. break;
  202537. }
  202538. case 4:
  202539. {
  202540. png_bytep sp;
  202541. png_bytep dp;
  202542. int shift;
  202543. int d;
  202544. int value;
  202545. png_uint_32 i;
  202546. png_uint_32 row_width = row_info->width;
  202547. dp = row;
  202548. shift = 4;
  202549. d = 0;
  202550. for (i = png_pass_start[pass]; i < row_width;
  202551. i += png_pass_inc[pass])
  202552. {
  202553. sp = row + (png_size_t)(i >> 1);
  202554. value = (*sp >> ((1 - (int)(i & 0x01)) << 2)) & 0x0f;
  202555. d |= (value << shift);
  202556. if (shift == 0)
  202557. {
  202558. shift = 4;
  202559. *dp++ = (png_byte)d;
  202560. d = 0;
  202561. }
  202562. else
  202563. shift -= 4;
  202564. }
  202565. if (shift != 4)
  202566. *dp = (png_byte)d;
  202567. break;
  202568. }
  202569. default:
  202570. {
  202571. png_bytep sp;
  202572. png_bytep dp;
  202573. png_uint_32 i;
  202574. png_uint_32 row_width = row_info->width;
  202575. png_size_t pixel_bytes;
  202576. /* start at the beginning */
  202577. dp = row;
  202578. /* find out how many bytes each pixel takes up */
  202579. pixel_bytes = (row_info->pixel_depth >> 3);
  202580. /* loop through the row, only looking at the pixels that
  202581. matter */
  202582. for (i = png_pass_start[pass]; i < row_width;
  202583. i += png_pass_inc[pass])
  202584. {
  202585. /* find out where the original pixel is */
  202586. sp = row + (png_size_t)i * pixel_bytes;
  202587. /* move the pixel */
  202588. if (dp != sp)
  202589. png_memcpy(dp, sp, pixel_bytes);
  202590. /* next pixel */
  202591. dp += pixel_bytes;
  202592. }
  202593. break;
  202594. }
  202595. }
  202596. /* set new row width */
  202597. row_info->width = (row_info->width +
  202598. png_pass_inc[pass] - 1 -
  202599. png_pass_start[pass]) /
  202600. png_pass_inc[pass];
  202601. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  202602. row_info->width);
  202603. }
  202604. }
  202605. #endif
  202606. /* This filters the row, chooses which filter to use, if it has not already
  202607. * been specified by the application, and then writes the row out with the
  202608. * chosen filter.
  202609. */
  202610. #define PNG_MAXSUM (((png_uint_32)(-1)) >> 1)
  202611. #define PNG_HISHIFT 10
  202612. #define PNG_LOMASK ((png_uint_32)0xffffL)
  202613. #define PNG_HIMASK ((png_uint_32)(~PNG_LOMASK >> PNG_HISHIFT))
  202614. void /* PRIVATE */
  202615. png_write_find_filter(png_structp png_ptr, png_row_infop row_info)
  202616. {
  202617. png_bytep best_row;
  202618. #ifndef PNG_NO_WRITE_FILTER
  202619. png_bytep prev_row, row_buf;
  202620. png_uint_32 mins, bpp;
  202621. png_byte filter_to_do = png_ptr->do_filter;
  202622. png_uint_32 row_bytes = row_info->rowbytes;
  202623. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202624. int num_p_filters = (int)png_ptr->num_prev_filters;
  202625. #endif
  202626. png_debug(1, "in png_write_find_filter\n");
  202627. /* find out how many bytes offset each pixel is */
  202628. bpp = (row_info->pixel_depth + 7) >> 3;
  202629. prev_row = png_ptr->prev_row;
  202630. #endif
  202631. best_row = png_ptr->row_buf;
  202632. #ifndef PNG_NO_WRITE_FILTER
  202633. row_buf = best_row;
  202634. mins = PNG_MAXSUM;
  202635. /* The prediction method we use is to find which method provides the
  202636. * smallest value when summing the absolute values of the distances
  202637. * from zero, using anything >= 128 as negative numbers. This is known
  202638. * as the "minimum sum of absolute differences" heuristic. Other
  202639. * heuristics are the "weighted minimum sum of absolute differences"
  202640. * (experimental and can in theory improve compression), and the "zlib
  202641. * predictive" method (not implemented yet), which does test compressions
  202642. * of lines using different filter methods, and then chooses the
  202643. * (series of) filter(s) that give minimum compressed data size (VERY
  202644. * computationally expensive).
  202645. *
  202646. * GRR 980525: consider also
  202647. * (1) minimum sum of absolute differences from running average (i.e.,
  202648. * keep running sum of non-absolute differences & count of bytes)
  202649. * [track dispersion, too? restart average if dispersion too large?]
  202650. * (1b) minimum sum of absolute differences from sliding average, probably
  202651. * with window size <= deflate window (usually 32K)
  202652. * (2) minimum sum of squared differences from zero or running average
  202653. * (i.e., ~ root-mean-square approach)
  202654. */
  202655. /* We don't need to test the 'no filter' case if this is the only filter
  202656. * that has been chosen, as it doesn't actually do anything to the data.
  202657. */
  202658. if ((filter_to_do & PNG_FILTER_NONE) &&
  202659. filter_to_do != PNG_FILTER_NONE)
  202660. {
  202661. png_bytep rp;
  202662. png_uint_32 sum = 0;
  202663. png_uint_32 i;
  202664. int v;
  202665. for (i = 0, rp = row_buf + 1; i < row_bytes; i++, rp++)
  202666. {
  202667. v = *rp;
  202668. sum += (v < 128) ? v : 256 - v;
  202669. }
  202670. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202671. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202672. {
  202673. png_uint_32 sumhi, sumlo;
  202674. int j;
  202675. sumlo = sum & PNG_LOMASK;
  202676. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK; /* Gives us some footroom */
  202677. /* Reduce the sum if we match any of the previous rows */
  202678. for (j = 0; j < num_p_filters; j++)
  202679. {
  202680. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  202681. {
  202682. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202683. PNG_WEIGHT_SHIFT;
  202684. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202685. PNG_WEIGHT_SHIFT;
  202686. }
  202687. }
  202688. /* Factor in the cost of this filter (this is here for completeness,
  202689. * but it makes no sense to have a "cost" for the NONE filter, as
  202690. * it has the minimum possible computational cost - none).
  202691. */
  202692. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  202693. PNG_COST_SHIFT;
  202694. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  202695. PNG_COST_SHIFT;
  202696. if (sumhi > PNG_HIMASK)
  202697. sum = PNG_MAXSUM;
  202698. else
  202699. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202700. }
  202701. #endif
  202702. mins = sum;
  202703. }
  202704. /* sub filter */
  202705. if (filter_to_do == PNG_FILTER_SUB)
  202706. /* it's the only filter so no testing is needed */
  202707. {
  202708. png_bytep rp, lp, dp;
  202709. png_uint_32 i;
  202710. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  202711. i++, rp++, dp++)
  202712. {
  202713. *dp = *rp;
  202714. }
  202715. for (lp = row_buf + 1; i < row_bytes;
  202716. i++, rp++, lp++, dp++)
  202717. {
  202718. *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  202719. }
  202720. best_row = png_ptr->sub_row;
  202721. }
  202722. else if (filter_to_do & PNG_FILTER_SUB)
  202723. {
  202724. png_bytep rp, dp, lp;
  202725. png_uint_32 sum = 0, lmins = mins;
  202726. png_uint_32 i;
  202727. int v;
  202728. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202729. /* We temporarily increase the "minimum sum" by the factor we
  202730. * would reduce the sum of this filter, so that we can do the
  202731. * early exit comparison without scaling the sum each time.
  202732. */
  202733. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202734. {
  202735. int j;
  202736. png_uint_32 lmhi, lmlo;
  202737. lmlo = lmins & PNG_LOMASK;
  202738. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202739. for (j = 0; j < num_p_filters; j++)
  202740. {
  202741. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  202742. {
  202743. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202744. PNG_WEIGHT_SHIFT;
  202745. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202746. PNG_WEIGHT_SHIFT;
  202747. }
  202748. }
  202749. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202750. PNG_COST_SHIFT;
  202751. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202752. PNG_COST_SHIFT;
  202753. if (lmhi > PNG_HIMASK)
  202754. lmins = PNG_MAXSUM;
  202755. else
  202756. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202757. }
  202758. #endif
  202759. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  202760. i++, rp++, dp++)
  202761. {
  202762. v = *dp = *rp;
  202763. sum += (v < 128) ? v : 256 - v;
  202764. }
  202765. for (lp = row_buf + 1; i < row_bytes;
  202766. i++, rp++, lp++, dp++)
  202767. {
  202768. v = *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  202769. sum += (v < 128) ? v : 256 - v;
  202770. if (sum > lmins) /* We are already worse, don't continue. */
  202771. break;
  202772. }
  202773. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202774. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202775. {
  202776. int j;
  202777. png_uint_32 sumhi, sumlo;
  202778. sumlo = sum & PNG_LOMASK;
  202779. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202780. for (j = 0; j < num_p_filters; j++)
  202781. {
  202782. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  202783. {
  202784. sumlo = (sumlo * png_ptr->inv_filter_weights[j]) >>
  202785. PNG_WEIGHT_SHIFT;
  202786. sumhi = (sumhi * png_ptr->inv_filter_weights[j]) >>
  202787. PNG_WEIGHT_SHIFT;
  202788. }
  202789. }
  202790. sumlo = (sumlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202791. PNG_COST_SHIFT;
  202792. sumhi = (sumhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202793. PNG_COST_SHIFT;
  202794. if (sumhi > PNG_HIMASK)
  202795. sum = PNG_MAXSUM;
  202796. else
  202797. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202798. }
  202799. #endif
  202800. if (sum < mins)
  202801. {
  202802. mins = sum;
  202803. best_row = png_ptr->sub_row;
  202804. }
  202805. }
  202806. /* up filter */
  202807. if (filter_to_do == PNG_FILTER_UP)
  202808. {
  202809. png_bytep rp, dp, pp;
  202810. png_uint_32 i;
  202811. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  202812. pp = prev_row + 1; i < row_bytes;
  202813. i++, rp++, pp++, dp++)
  202814. {
  202815. *dp = (png_byte)(((int)*rp - (int)*pp) & 0xff);
  202816. }
  202817. best_row = png_ptr->up_row;
  202818. }
  202819. else if (filter_to_do & PNG_FILTER_UP)
  202820. {
  202821. png_bytep rp, dp, pp;
  202822. png_uint_32 sum = 0, lmins = mins;
  202823. png_uint_32 i;
  202824. int v;
  202825. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202826. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202827. {
  202828. int j;
  202829. png_uint_32 lmhi, lmlo;
  202830. lmlo = lmins & PNG_LOMASK;
  202831. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202832. for (j = 0; j < num_p_filters; j++)
  202833. {
  202834. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  202835. {
  202836. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202837. PNG_WEIGHT_SHIFT;
  202838. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202839. PNG_WEIGHT_SHIFT;
  202840. }
  202841. }
  202842. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  202843. PNG_COST_SHIFT;
  202844. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  202845. PNG_COST_SHIFT;
  202846. if (lmhi > PNG_HIMASK)
  202847. lmins = PNG_MAXSUM;
  202848. else
  202849. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202850. }
  202851. #endif
  202852. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  202853. pp = prev_row + 1; i < row_bytes; i++)
  202854. {
  202855. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  202856. sum += (v < 128) ? v : 256 - v;
  202857. if (sum > lmins) /* We are already worse, don't continue. */
  202858. break;
  202859. }
  202860. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202861. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202862. {
  202863. int j;
  202864. png_uint_32 sumhi, sumlo;
  202865. sumlo = sum & PNG_LOMASK;
  202866. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202867. for (j = 0; j < num_p_filters; j++)
  202868. {
  202869. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  202870. {
  202871. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202872. PNG_WEIGHT_SHIFT;
  202873. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202874. PNG_WEIGHT_SHIFT;
  202875. }
  202876. }
  202877. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  202878. PNG_COST_SHIFT;
  202879. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  202880. PNG_COST_SHIFT;
  202881. if (sumhi > PNG_HIMASK)
  202882. sum = PNG_MAXSUM;
  202883. else
  202884. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202885. }
  202886. #endif
  202887. if (sum < mins)
  202888. {
  202889. mins = sum;
  202890. best_row = png_ptr->up_row;
  202891. }
  202892. }
  202893. /* avg filter */
  202894. if (filter_to_do == PNG_FILTER_AVG)
  202895. {
  202896. png_bytep rp, dp, pp, lp;
  202897. png_uint_32 i;
  202898. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  202899. pp = prev_row + 1; i < bpp; i++)
  202900. {
  202901. *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  202902. }
  202903. for (lp = row_buf + 1; i < row_bytes; i++)
  202904. {
  202905. *dp++ = (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2))
  202906. & 0xff);
  202907. }
  202908. best_row = png_ptr->avg_row;
  202909. }
  202910. else if (filter_to_do & PNG_FILTER_AVG)
  202911. {
  202912. png_bytep rp, dp, pp, lp;
  202913. png_uint_32 sum = 0, lmins = mins;
  202914. png_uint_32 i;
  202915. int v;
  202916. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202917. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202918. {
  202919. int j;
  202920. png_uint_32 lmhi, lmlo;
  202921. lmlo = lmins & PNG_LOMASK;
  202922. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202923. for (j = 0; j < num_p_filters; j++)
  202924. {
  202925. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_AVG)
  202926. {
  202927. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202928. PNG_WEIGHT_SHIFT;
  202929. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202930. PNG_WEIGHT_SHIFT;
  202931. }
  202932. }
  202933. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202934. PNG_COST_SHIFT;
  202935. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202936. PNG_COST_SHIFT;
  202937. if (lmhi > PNG_HIMASK)
  202938. lmins = PNG_MAXSUM;
  202939. else
  202940. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202941. }
  202942. #endif
  202943. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  202944. pp = prev_row + 1; i < bpp; i++)
  202945. {
  202946. v = *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  202947. sum += (v < 128) ? v : 256 - v;
  202948. }
  202949. for (lp = row_buf + 1; i < row_bytes; i++)
  202950. {
  202951. v = *dp++ =
  202952. (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2)) & 0xff);
  202953. sum += (v < 128) ? v : 256 - v;
  202954. if (sum > lmins) /* We are already worse, don't continue. */
  202955. break;
  202956. }
  202957. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202958. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202959. {
  202960. int j;
  202961. png_uint_32 sumhi, sumlo;
  202962. sumlo = sum & PNG_LOMASK;
  202963. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202964. for (j = 0; j < num_p_filters; j++)
  202965. {
  202966. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  202967. {
  202968. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202969. PNG_WEIGHT_SHIFT;
  202970. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202971. PNG_WEIGHT_SHIFT;
  202972. }
  202973. }
  202974. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202975. PNG_COST_SHIFT;
  202976. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202977. PNG_COST_SHIFT;
  202978. if (sumhi > PNG_HIMASK)
  202979. sum = PNG_MAXSUM;
  202980. else
  202981. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202982. }
  202983. #endif
  202984. if (sum < mins)
  202985. {
  202986. mins = sum;
  202987. best_row = png_ptr->avg_row;
  202988. }
  202989. }
  202990. /* Paeth filter */
  202991. if (filter_to_do == PNG_FILTER_PAETH)
  202992. {
  202993. png_bytep rp, dp, pp, cp, lp;
  202994. png_uint_32 i;
  202995. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  202996. pp = prev_row + 1; i < bpp; i++)
  202997. {
  202998. *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  202999. }
  203000. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  203001. {
  203002. int a, b, c, pa, pb, pc, p;
  203003. b = *pp++;
  203004. c = *cp++;
  203005. a = *lp++;
  203006. p = b - c;
  203007. pc = a - c;
  203008. #ifdef PNG_USE_ABS
  203009. pa = abs(p);
  203010. pb = abs(pc);
  203011. pc = abs(p + pc);
  203012. #else
  203013. pa = p < 0 ? -p : p;
  203014. pb = pc < 0 ? -pc : pc;
  203015. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  203016. #endif
  203017. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  203018. *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  203019. }
  203020. best_row = png_ptr->paeth_row;
  203021. }
  203022. else if (filter_to_do & PNG_FILTER_PAETH)
  203023. {
  203024. png_bytep rp, dp, pp, cp, lp;
  203025. png_uint_32 sum = 0, lmins = mins;
  203026. png_uint_32 i;
  203027. int v;
  203028. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  203029. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  203030. {
  203031. int j;
  203032. png_uint_32 lmhi, lmlo;
  203033. lmlo = lmins & PNG_LOMASK;
  203034. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  203035. for (j = 0; j < num_p_filters; j++)
  203036. {
  203037. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  203038. {
  203039. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  203040. PNG_WEIGHT_SHIFT;
  203041. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  203042. PNG_WEIGHT_SHIFT;
  203043. }
  203044. }
  203045. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  203046. PNG_COST_SHIFT;
  203047. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  203048. PNG_COST_SHIFT;
  203049. if (lmhi > PNG_HIMASK)
  203050. lmins = PNG_MAXSUM;
  203051. else
  203052. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  203053. }
  203054. #endif
  203055. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  203056. pp = prev_row + 1; i < bpp; i++)
  203057. {
  203058. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  203059. sum += (v < 128) ? v : 256 - v;
  203060. }
  203061. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  203062. {
  203063. int a, b, c, pa, pb, pc, p;
  203064. b = *pp++;
  203065. c = *cp++;
  203066. a = *lp++;
  203067. #ifndef PNG_SLOW_PAETH
  203068. p = b - c;
  203069. pc = a - c;
  203070. #ifdef PNG_USE_ABS
  203071. pa = abs(p);
  203072. pb = abs(pc);
  203073. pc = abs(p + pc);
  203074. #else
  203075. pa = p < 0 ? -p : p;
  203076. pb = pc < 0 ? -pc : pc;
  203077. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  203078. #endif
  203079. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  203080. #else /* PNG_SLOW_PAETH */
  203081. p = a + b - c;
  203082. pa = abs(p - a);
  203083. pb = abs(p - b);
  203084. pc = abs(p - c);
  203085. if (pa <= pb && pa <= pc)
  203086. p = a;
  203087. else if (pb <= pc)
  203088. p = b;
  203089. else
  203090. p = c;
  203091. #endif /* PNG_SLOW_PAETH */
  203092. v = *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  203093. sum += (v < 128) ? v : 256 - v;
  203094. if (sum > lmins) /* We are already worse, don't continue. */
  203095. break;
  203096. }
  203097. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  203098. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  203099. {
  203100. int j;
  203101. png_uint_32 sumhi, sumlo;
  203102. sumlo = sum & PNG_LOMASK;
  203103. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  203104. for (j = 0; j < num_p_filters; j++)
  203105. {
  203106. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  203107. {
  203108. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  203109. PNG_WEIGHT_SHIFT;
  203110. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  203111. PNG_WEIGHT_SHIFT;
  203112. }
  203113. }
  203114. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  203115. PNG_COST_SHIFT;
  203116. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  203117. PNG_COST_SHIFT;
  203118. if (sumhi > PNG_HIMASK)
  203119. sum = PNG_MAXSUM;
  203120. else
  203121. sum = (sumhi << PNG_HISHIFT) + sumlo;
  203122. }
  203123. #endif
  203124. if (sum < mins)
  203125. {
  203126. best_row = png_ptr->paeth_row;
  203127. }
  203128. }
  203129. #endif /* PNG_NO_WRITE_FILTER */
  203130. /* Do the actual writing of the filtered row data from the chosen filter. */
  203131. png_write_filtered_row(png_ptr, best_row);
  203132. #ifndef PNG_NO_WRITE_FILTER
  203133. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  203134. /* Save the type of filter we picked this time for future calculations */
  203135. if (png_ptr->num_prev_filters > 0)
  203136. {
  203137. int j;
  203138. for (j = 1; j < num_p_filters; j++)
  203139. {
  203140. png_ptr->prev_filters[j] = png_ptr->prev_filters[j - 1];
  203141. }
  203142. png_ptr->prev_filters[j] = best_row[0];
  203143. }
  203144. #endif
  203145. #endif /* PNG_NO_WRITE_FILTER */
  203146. }
  203147. /* Do the actual writing of a previously filtered row. */
  203148. void /* PRIVATE */
  203149. png_write_filtered_row(png_structp png_ptr, png_bytep filtered_row)
  203150. {
  203151. png_debug(1, "in png_write_filtered_row\n");
  203152. png_debug1(2, "filter = %d\n", filtered_row[0]);
  203153. /* set up the zlib input buffer */
  203154. png_ptr->zstream.next_in = filtered_row;
  203155. png_ptr->zstream.avail_in = (uInt)png_ptr->row_info.rowbytes + 1;
  203156. /* repeat until we have compressed all the data */
  203157. do
  203158. {
  203159. int ret; /* return of zlib */
  203160. /* compress the data */
  203161. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  203162. /* check for compression errors */
  203163. if (ret != Z_OK)
  203164. {
  203165. if (png_ptr->zstream.msg != NULL)
  203166. png_error(png_ptr, png_ptr->zstream.msg);
  203167. else
  203168. png_error(png_ptr, "zlib error");
  203169. }
  203170. /* see if it is time to write another IDAT */
  203171. if (!(png_ptr->zstream.avail_out))
  203172. {
  203173. /* write the IDAT and reset the zlib output buffer */
  203174. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  203175. png_ptr->zstream.next_out = png_ptr->zbuf;
  203176. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  203177. }
  203178. /* repeat until all data has been compressed */
  203179. } while (png_ptr->zstream.avail_in);
  203180. /* swap the current and previous rows */
  203181. if (png_ptr->prev_row != NULL)
  203182. {
  203183. png_bytep tptr;
  203184. tptr = png_ptr->prev_row;
  203185. png_ptr->prev_row = png_ptr->row_buf;
  203186. png_ptr->row_buf = tptr;
  203187. }
  203188. /* finish row - updates counters and flushes zlib if last row */
  203189. png_write_finish_row(png_ptr);
  203190. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  203191. png_ptr->flush_rows++;
  203192. if (png_ptr->flush_dist > 0 &&
  203193. png_ptr->flush_rows >= png_ptr->flush_dist)
  203194. {
  203195. png_write_flush(png_ptr);
  203196. }
  203197. #endif
  203198. }
  203199. #endif /* PNG_WRITE_SUPPORTED */
  203200. /*** End of inlined file: pngwutil.c ***/
  203201. #else
  203202. extern "C"
  203203. {
  203204. #include <png.h>
  203205. #include <pngconf.h>
  203206. }
  203207. #endif
  203208. }
  203209. #undef max
  203210. #undef min
  203211. #if JUCE_MSVC
  203212. #pragma warning (pop)
  203213. #endif
  203214. BEGIN_JUCE_NAMESPACE
  203215. using ::calloc;
  203216. using ::malloc;
  203217. using ::free;
  203218. namespace PNGHelpers
  203219. {
  203220. using namespace pnglibNamespace;
  203221. static void JUCE_CDECL readCallback (png_structp png, png_bytep data, png_size_t length)
  203222. {
  203223. static_cast<InputStream*> (png_get_io_ptr (png))->read (data, (int) length);
  203224. }
  203225. static void JUCE_CDECL writeDataCallback (png_structp png, png_bytep data, png_size_t length)
  203226. {
  203227. static_cast<OutputStream*> (png_get_io_ptr (png))->write (data, (int) length);
  203228. }
  203229. struct PNGErrorStruct {};
  203230. static void JUCE_CDECL errorCallback (png_structp, png_const_charp)
  203231. {
  203232. throw PNGErrorStruct();
  203233. }
  203234. }
  203235. PNGImageFormat::PNGImageFormat() {}
  203236. PNGImageFormat::~PNGImageFormat() {}
  203237. const String PNGImageFormat::getFormatName()
  203238. {
  203239. return "PNG";
  203240. }
  203241. bool PNGImageFormat::canUnderstand (InputStream& in)
  203242. {
  203243. const int bytesNeeded = 4;
  203244. char header [bytesNeeded];
  203245. return in.read (header, bytesNeeded) == bytesNeeded
  203246. && header[1] == 'P'
  203247. && header[2] == 'N'
  203248. && header[3] == 'G';
  203249. }
  203250. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  203251. const Image juce_loadWithCoreImage (InputStream& input);
  203252. #endif
  203253. const Image PNGImageFormat::decodeImage (InputStream& in)
  203254. {
  203255. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  203256. return juce_loadWithCoreImage (in);
  203257. #else
  203258. using namespace pnglibNamespace;
  203259. Image image;
  203260. png_structp pngReadStruct;
  203261. png_infop pngInfoStruct;
  203262. pngReadStruct = png_create_read_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  203263. if (pngReadStruct != 0)
  203264. {
  203265. pngInfoStruct = png_create_info_struct (pngReadStruct);
  203266. if (pngInfoStruct == 0)
  203267. {
  203268. png_destroy_read_struct (&pngReadStruct, 0, 0);
  203269. return Image::null;
  203270. }
  203271. png_set_error_fn (pngReadStruct, 0, PNGHelpers::errorCallback, PNGHelpers::errorCallback );
  203272. // read the header..
  203273. png_set_read_fn (pngReadStruct, &in, PNGHelpers::readCallback);
  203274. png_uint_32 width, height;
  203275. int bitDepth, colorType, interlaceType;
  203276. png_read_info (pngReadStruct, pngInfoStruct);
  203277. png_get_IHDR (pngReadStruct, pngInfoStruct,
  203278. &width, &height,
  203279. &bitDepth, &colorType,
  203280. &interlaceType, 0, 0);
  203281. if (bitDepth == 16)
  203282. png_set_strip_16 (pngReadStruct);
  203283. if (colorType == PNG_COLOR_TYPE_PALETTE)
  203284. png_set_expand (pngReadStruct);
  203285. if (bitDepth < 8)
  203286. png_set_expand (pngReadStruct);
  203287. if (png_get_valid (pngReadStruct, pngInfoStruct, PNG_INFO_tRNS))
  203288. png_set_expand (pngReadStruct);
  203289. if (colorType == PNG_COLOR_TYPE_GRAY || colorType == PNG_COLOR_TYPE_GRAY_ALPHA)
  203290. png_set_gray_to_rgb (pngReadStruct);
  203291. png_set_add_alpha (pngReadStruct, 0xff, PNG_FILLER_AFTER);
  203292. bool hasAlphaChan = (colorType & PNG_COLOR_MASK_ALPHA) != 0
  203293. || pngInfoStruct->num_trans > 0;
  203294. // Load the image into a temp buffer in the pnglib format..
  203295. HeapBlock <uint8> tempBuffer (height * (width << 2));
  203296. {
  203297. HeapBlock <png_bytep> rows (height);
  203298. for (int y = (int) height; --y >= 0;)
  203299. rows[y] = (png_bytep) (tempBuffer + (width << 2) * y);
  203300. png_read_image (pngReadStruct, rows);
  203301. png_read_end (pngReadStruct, pngInfoStruct);
  203302. }
  203303. png_destroy_read_struct (&pngReadStruct, &pngInfoStruct, 0);
  203304. // now convert the data to a juce image format..
  203305. image = Image (hasAlphaChan ? Image::ARGB : Image::RGB,
  203306. (int) width, (int) height, hasAlphaChan);
  203307. image.getProperties()->set ("originalImageHadAlpha", image.hasAlphaChannel());
  203308. hasAlphaChan = image.hasAlphaChannel(); // (the native image creator may not give back what we expect)
  203309. const Image::BitmapData destData (image, true);
  203310. uint8* srcRow = tempBuffer;
  203311. uint8* destRow = destData.data;
  203312. for (int y = 0; y < (int) height; ++y)
  203313. {
  203314. const uint8* src = srcRow;
  203315. srcRow += (width << 2);
  203316. uint8* dest = destRow;
  203317. destRow += destData.lineStride;
  203318. if (hasAlphaChan)
  203319. {
  203320. for (int i = (int) width; --i >= 0;)
  203321. {
  203322. ((PixelARGB*) dest)->setARGB (src[3], src[0], src[1], src[2]);
  203323. ((PixelARGB*) dest)->premultiply();
  203324. dest += destData.pixelStride;
  203325. src += 4;
  203326. }
  203327. }
  203328. else
  203329. {
  203330. for (int i = (int) width; --i >= 0;)
  203331. {
  203332. ((PixelRGB*) dest)->setARGB (0, src[0], src[1], src[2]);
  203333. dest += destData.pixelStride;
  203334. src += 4;
  203335. }
  203336. }
  203337. }
  203338. }
  203339. return image;
  203340. #endif
  203341. }
  203342. bool PNGImageFormat::writeImageToStream (const Image& image, OutputStream& out)
  203343. {
  203344. using namespace pnglibNamespace;
  203345. const int width = image.getWidth();
  203346. const int height = image.getHeight();
  203347. png_structp pngWriteStruct = png_create_write_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  203348. if (pngWriteStruct == 0)
  203349. return false;
  203350. png_infop pngInfoStruct = png_create_info_struct (pngWriteStruct);
  203351. if (pngInfoStruct == 0)
  203352. {
  203353. png_destroy_write_struct (&pngWriteStruct, (png_infopp) 0);
  203354. return false;
  203355. }
  203356. png_set_write_fn (pngWriteStruct, &out, PNGHelpers::writeDataCallback, 0);
  203357. png_set_IHDR (pngWriteStruct, pngInfoStruct, width, height, 8,
  203358. image.hasAlphaChannel() ? PNG_COLOR_TYPE_RGB_ALPHA
  203359. : PNG_COLOR_TYPE_RGB,
  203360. PNG_INTERLACE_NONE,
  203361. PNG_COMPRESSION_TYPE_BASE,
  203362. PNG_FILTER_TYPE_BASE);
  203363. HeapBlock <uint8> rowData (width * 4);
  203364. png_color_8 sig_bit;
  203365. sig_bit.red = 8;
  203366. sig_bit.green = 8;
  203367. sig_bit.blue = 8;
  203368. sig_bit.alpha = 8;
  203369. png_set_sBIT (pngWriteStruct, pngInfoStruct, &sig_bit);
  203370. png_write_info (pngWriteStruct, pngInfoStruct);
  203371. png_set_shift (pngWriteStruct, &sig_bit);
  203372. png_set_packing (pngWriteStruct);
  203373. const Image::BitmapData srcData (image, false);
  203374. for (int y = 0; y < height; ++y)
  203375. {
  203376. uint8* dst = rowData;
  203377. const uint8* src = srcData.getLinePointer (y);
  203378. if (image.hasAlphaChannel())
  203379. {
  203380. for (int i = width; --i >= 0;)
  203381. {
  203382. PixelARGB p (*(const PixelARGB*) src);
  203383. p.unpremultiply();
  203384. *dst++ = p.getRed();
  203385. *dst++ = p.getGreen();
  203386. *dst++ = p.getBlue();
  203387. *dst++ = p.getAlpha();
  203388. src += srcData.pixelStride;
  203389. }
  203390. }
  203391. else
  203392. {
  203393. for (int i = width; --i >= 0;)
  203394. {
  203395. *dst++ = ((const PixelRGB*) src)->getRed();
  203396. *dst++ = ((const PixelRGB*) src)->getGreen();
  203397. *dst++ = ((const PixelRGB*) src)->getBlue();
  203398. src += srcData.pixelStride;
  203399. }
  203400. }
  203401. png_bytep rowPtr = rowData;
  203402. png_write_rows (pngWriteStruct, &rowPtr, 1);
  203403. }
  203404. png_write_end (pngWriteStruct, pngInfoStruct);
  203405. png_destroy_write_struct (&pngWriteStruct, &pngInfoStruct);
  203406. out.flush();
  203407. return true;
  203408. }
  203409. END_JUCE_NAMESPACE
  203410. /*** End of inlined file: juce_PNGLoader.cpp ***/
  203411. #endif
  203412. //==============================================================================
  203413. #if JUCE_BUILD_NATIVE
  203414. // Non-public headers that are needed by more than one platform must be included
  203415. // before the platform-specific sections..
  203416. BEGIN_JUCE_NAMESPACE
  203417. /*** Start of inlined file: juce_MidiDataConcatenator.h ***/
  203418. #ifndef __JUCE_MIDIDATACONCATENATOR_JUCEHEADER__
  203419. #define __JUCE_MIDIDATACONCATENATOR_JUCEHEADER__
  203420. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  203421. /**
  203422. Helper class that takes chunks of incoming midi bytes, packages them into
  203423. messages, and dispatches them to a midi callback.
  203424. */
  203425. class MidiDataConcatenator
  203426. {
  203427. public:
  203428. MidiDataConcatenator (const int initialBufferSize)
  203429. : pendingData (initialBufferSize),
  203430. pendingBytes (0), pendingDataTime (0)
  203431. {
  203432. }
  203433. void reset()
  203434. {
  203435. pendingBytes = 0;
  203436. pendingDataTime = 0;
  203437. }
  203438. void pushMidiData (const void* data, int numBytes, double time,
  203439. MidiInput* input, MidiInputCallback& callback)
  203440. {
  203441. const uint8* d = static_cast <const uint8*> (data);
  203442. while (numBytes > 0)
  203443. {
  203444. if (pendingBytes > 0 || d[0] == 0xf0)
  203445. {
  203446. processSysex (d, numBytes, time, input, callback);
  203447. }
  203448. else
  203449. {
  203450. int used = 0;
  203451. const MidiMessage m (d, numBytes, used, 0, time);
  203452. if (used <= 0)
  203453. break; // malformed message..
  203454. callback.handleIncomingMidiMessage (input, m);
  203455. numBytes -= used;
  203456. d += used;
  203457. }
  203458. }
  203459. }
  203460. private:
  203461. void processSysex (const uint8*& d, int& numBytes, double time,
  203462. MidiInput* input, MidiInputCallback& callback)
  203463. {
  203464. if (*d == 0xf0)
  203465. {
  203466. pendingBytes = 0;
  203467. pendingDataTime = time;
  203468. }
  203469. pendingData.ensureSize (pendingBytes + numBytes, false);
  203470. uint8* totalMessage = static_cast<uint8*> (pendingData.getData());
  203471. uint8* dest = totalMessage + pendingBytes;
  203472. do
  203473. {
  203474. if (pendingBytes > 0 && *d >= 0x80)
  203475. {
  203476. if (*d >= 0xfa || *d == 0xf8)
  203477. {
  203478. callback.handleIncomingMidiMessage (input, MidiMessage (*d, time));
  203479. ++d;
  203480. --numBytes;
  203481. }
  203482. else
  203483. {
  203484. if (*d == 0xf7)
  203485. {
  203486. *dest++ = *d++;
  203487. pendingBytes++;
  203488. --numBytes;
  203489. }
  203490. break;
  203491. }
  203492. }
  203493. else
  203494. {
  203495. *dest++ = *d++;
  203496. pendingBytes++;
  203497. --numBytes;
  203498. }
  203499. }
  203500. while (numBytes > 0);
  203501. if (pendingBytes > 0)
  203502. {
  203503. if (totalMessage [pendingBytes - 1] == 0xf7)
  203504. {
  203505. callback.handleIncomingMidiMessage (input, MidiMessage (totalMessage, pendingBytes, pendingDataTime));
  203506. pendingBytes = 0;
  203507. }
  203508. else
  203509. {
  203510. callback.handlePartialSysexMessage (input, totalMessage, pendingBytes, pendingDataTime);
  203511. }
  203512. }
  203513. }
  203514. MemoryBlock pendingData;
  203515. int pendingBytes;
  203516. double pendingDataTime;
  203517. MidiDataConcatenator (const MidiDataConcatenator&);
  203518. MidiDataConcatenator& operator= (const MidiDataConcatenator&);
  203519. };
  203520. #endif
  203521. #endif // __JUCE_MIDIDATACONCATENATOR_JUCEHEADER__
  203522. /*** End of inlined file: juce_MidiDataConcatenator.h ***/
  203523. END_JUCE_NAMESPACE
  203524. #if JUCE_WINDOWS
  203525. /*** Start of inlined file: juce_win32_NativeCode.cpp ***/
  203526. /*
  203527. This file wraps together all the win32-specific code, so that
  203528. we can include all the native headers just once, and compile all our
  203529. platform-specific stuff in one big lump, keeping it out of the way of
  203530. the rest of the codebase.
  203531. */
  203532. #if JUCE_WINDOWS
  203533. BEGIN_JUCE_NAMESPACE
  203534. #define JUCE_INCLUDED_FILE 1
  203535. // Now include the actual code files..
  203536. /*** Start of inlined file: juce_win32_DynamicLibraryLoader.cpp ***/
  203537. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203538. // compiled on its own).
  203539. #if JUCE_INCLUDED_FILE
  203540. /*** Start of inlined file: juce_win32_DynamicLibraryLoader.h ***/
  203541. #ifndef __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  203542. #define __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  203543. #ifndef DOXYGEN
  203544. // use with DynamicLibraryLoader to simplify importing functions
  203545. //
  203546. // functionName: function to import
  203547. // localFunctionName: name you want to use to actually call it (must be different)
  203548. // returnType: the return type
  203549. // object: the DynamicLibraryLoader to use
  203550. // params: list of params (bracketed)
  203551. //
  203552. #define DynamicLibraryImport(functionName, localFunctionName, returnType, object, params) \
  203553. typedef returnType (WINAPI *type##localFunctionName) params; \
  203554. type##localFunctionName localFunctionName \
  203555. = (type##localFunctionName)object.findProcAddress (#functionName);
  203556. // loads and unloads a DLL automatically
  203557. class JUCE_API DynamicLibraryLoader
  203558. {
  203559. public:
  203560. DynamicLibraryLoader (const String& name);
  203561. ~DynamicLibraryLoader();
  203562. void* findProcAddress (const String& functionName);
  203563. private:
  203564. void* libHandle;
  203565. };
  203566. #endif
  203567. #endif // __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  203568. /*** End of inlined file: juce_win32_DynamicLibraryLoader.h ***/
  203569. DynamicLibraryLoader::DynamicLibraryLoader (const String& name)
  203570. {
  203571. libHandle = LoadLibrary (name);
  203572. }
  203573. DynamicLibraryLoader::~DynamicLibraryLoader()
  203574. {
  203575. FreeLibrary ((HMODULE) libHandle);
  203576. }
  203577. void* DynamicLibraryLoader::findProcAddress (const String& functionName)
  203578. {
  203579. return (void*) GetProcAddress ((HMODULE) libHandle, functionName.toCString()); // (void* cast is required for mingw)
  203580. }
  203581. #endif
  203582. /*** End of inlined file: juce_win32_DynamicLibraryLoader.cpp ***/
  203583. /*** Start of inlined file: juce_win32_SystemStats.cpp ***/
  203584. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203585. // compiled on its own).
  203586. #if JUCE_INCLUDED_FILE
  203587. extern void juce_initialiseThreadEvents();
  203588. void Logger::outputDebugString (const String& text)
  203589. {
  203590. OutputDebugString (text + "\n");
  203591. }
  203592. static int64 hiResTicksPerSecond;
  203593. static double hiResTicksScaleFactor;
  203594. #if JUCE_USE_INTRINSICS
  203595. // CPU info functions using intrinsics...
  203596. #pragma intrinsic (__cpuid)
  203597. #pragma intrinsic (__rdtsc)
  203598. const String SystemStats::getCpuVendor()
  203599. {
  203600. int info [4];
  203601. __cpuid (info, 0);
  203602. char v [12];
  203603. memcpy (v, info + 1, 4);
  203604. memcpy (v + 4, info + 3, 4);
  203605. memcpy (v + 8, info + 2, 4);
  203606. return String (v, 12);
  203607. }
  203608. #else
  203609. // CPU info functions using old fashioned inline asm...
  203610. static void juce_getCpuVendor (char* const v)
  203611. {
  203612. int vendor[4];
  203613. zeromem (vendor, 16);
  203614. #ifdef JUCE_64BIT
  203615. #else
  203616. #ifndef __MINGW32__
  203617. __try
  203618. #endif
  203619. {
  203620. #if JUCE_GCC
  203621. unsigned int dummy = 0;
  203622. __asm__ ("cpuid" : "=a" (dummy), "=b" (vendor[0]), "=c" (vendor[2]),"=d" (vendor[1]) : "a" (0));
  203623. #else
  203624. __asm
  203625. {
  203626. mov eax, 0
  203627. cpuid
  203628. mov [vendor], ebx
  203629. mov [vendor + 4], edx
  203630. mov [vendor + 8], ecx
  203631. }
  203632. #endif
  203633. }
  203634. #ifndef __MINGW32__
  203635. __except (EXCEPTION_EXECUTE_HANDLER)
  203636. {
  203637. *v = 0;
  203638. }
  203639. #endif
  203640. #endif
  203641. memcpy (v, vendor, 16);
  203642. }
  203643. const String SystemStats::getCpuVendor()
  203644. {
  203645. char v [16];
  203646. juce_getCpuVendor (v);
  203647. return String (v, 16);
  203648. }
  203649. #endif
  203650. void SystemStats::initialiseStats()
  203651. {
  203652. juce_initialiseThreadEvents();
  203653. cpuFlags.hasMMX = IsProcessorFeaturePresent (PF_MMX_INSTRUCTIONS_AVAILABLE) != 0;
  203654. cpuFlags.hasSSE = IsProcessorFeaturePresent (PF_XMMI_INSTRUCTIONS_AVAILABLE) != 0;
  203655. cpuFlags.hasSSE2 = IsProcessorFeaturePresent (PF_XMMI64_INSTRUCTIONS_AVAILABLE) != 0;
  203656. #ifdef PF_AMD3D_INSTRUCTIONS_AVAILABLE
  203657. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_AMD3D_INSTRUCTIONS_AVAILABLE) != 0;
  203658. #else
  203659. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_3DNOW_INSTRUCTIONS_AVAILABLE) != 0;
  203660. #endif
  203661. {
  203662. SYSTEM_INFO systemInfo;
  203663. GetSystemInfo (&systemInfo);
  203664. cpuFlags.numCpus = systemInfo.dwNumberOfProcessors;
  203665. }
  203666. LARGE_INTEGER f;
  203667. QueryPerformanceFrequency (&f);
  203668. hiResTicksPerSecond = f.QuadPart;
  203669. hiResTicksScaleFactor = 1000.0 / hiResTicksPerSecond;
  203670. String s (SystemStats::getJUCEVersion());
  203671. const MMRESULT res = timeBeginPeriod (1);
  203672. (void) res;
  203673. jassert (res == TIMERR_NOERROR);
  203674. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  203675. _CrtSetDbgFlag (_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
  203676. #endif
  203677. }
  203678. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  203679. {
  203680. OSVERSIONINFO info;
  203681. info.dwOSVersionInfoSize = sizeof (info);
  203682. GetVersionEx (&info);
  203683. if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
  203684. {
  203685. switch (info.dwMajorVersion)
  203686. {
  203687. case 5: return (info.dwMinorVersion == 0) ? Win2000 : WinXP;
  203688. case 6: return (info.dwMinorVersion == 0) ? WinVista : Windows7;
  203689. default: jassertfalse; break; // !! not a supported OS!
  203690. }
  203691. }
  203692. else if (info.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
  203693. {
  203694. jassert (info.dwMinorVersion != 0); // !! still running on Windows 95??
  203695. return Win98;
  203696. }
  203697. return UnknownOS;
  203698. }
  203699. const String SystemStats::getOperatingSystemName()
  203700. {
  203701. const char* name = "Unknown OS";
  203702. switch (getOperatingSystemType())
  203703. {
  203704. case Windows7: name = "Windows 7"; break;
  203705. case WinVista: name = "Windows Vista"; break;
  203706. case WinXP: name = "Windows XP"; break;
  203707. case Win2000: name = "Windows 2000"; break;
  203708. case Win98: name = "Windows 98"; break;
  203709. default: jassertfalse; break; // !! new type of OS?
  203710. }
  203711. return name;
  203712. }
  203713. bool SystemStats::isOperatingSystem64Bit()
  203714. {
  203715. #ifdef _WIN64
  203716. return true;
  203717. #else
  203718. typedef BOOL (WINAPI* LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
  203719. LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress (GetModuleHandle (L"kernel32"), "IsWow64Process");
  203720. BOOL isWow64 = FALSE;
  203721. return (fnIsWow64Process != 0)
  203722. && fnIsWow64Process (GetCurrentProcess(), &isWow64)
  203723. && (isWow64 != FALSE);
  203724. #endif
  203725. }
  203726. int SystemStats::getMemorySizeInMegabytes()
  203727. {
  203728. MEMORYSTATUSEX mem;
  203729. mem.dwLength = sizeof (mem);
  203730. GlobalMemoryStatusEx (&mem);
  203731. return (int) (mem.ullTotalPhys / (1024 * 1024)) + 1;
  203732. }
  203733. uint32 juce_millisecondsSinceStartup() throw()
  203734. {
  203735. return (uint32) timeGetTime();
  203736. }
  203737. int64 Time::getHighResolutionTicks() throw()
  203738. {
  203739. LARGE_INTEGER ticks;
  203740. QueryPerformanceCounter (&ticks);
  203741. const int64 mainCounterAsHiResTicks = (GetTickCount() * hiResTicksPerSecond) / 1000;
  203742. const int64 newOffset = mainCounterAsHiResTicks - ticks.QuadPart;
  203743. // fix for a very obscure PCI hardware bug that can make the counter
  203744. // sometimes jump forwards by a few seconds..
  203745. static int64 hiResTicksOffset = 0;
  203746. const int64 offsetDrift = abs64 (newOffset - hiResTicksOffset);
  203747. if (offsetDrift > (hiResTicksPerSecond >> 1))
  203748. hiResTicksOffset = newOffset;
  203749. return ticks.QuadPart + hiResTicksOffset;
  203750. }
  203751. double Time::getMillisecondCounterHiRes() throw()
  203752. {
  203753. return getHighResolutionTicks() * hiResTicksScaleFactor;
  203754. }
  203755. int64 Time::getHighResolutionTicksPerSecond() throw()
  203756. {
  203757. return hiResTicksPerSecond;
  203758. }
  203759. static int64 juce_getClockCycleCounter() throw()
  203760. {
  203761. #if JUCE_USE_INTRINSICS
  203762. // MS intrinsics version...
  203763. return __rdtsc();
  203764. #elif JUCE_GCC
  203765. // GNU inline asm version...
  203766. unsigned int hi = 0, lo = 0;
  203767. __asm__ __volatile__ (
  203768. "xor %%eax, %%eax \n\
  203769. xor %%edx, %%edx \n\
  203770. rdtsc \n\
  203771. movl %%eax, %[lo] \n\
  203772. movl %%edx, %[hi]"
  203773. :
  203774. : [hi] "m" (hi),
  203775. [lo] "m" (lo)
  203776. : "cc", "eax", "ebx", "ecx", "edx", "memory");
  203777. return (int64) ((((uint64) hi) << 32) | lo);
  203778. #else
  203779. // MSVC inline asm version...
  203780. unsigned int hi = 0, lo = 0;
  203781. __asm
  203782. {
  203783. xor eax, eax
  203784. xor edx, edx
  203785. rdtsc
  203786. mov lo, eax
  203787. mov hi, edx
  203788. }
  203789. return (int64) ((((uint64) hi) << 32) | lo);
  203790. #endif
  203791. }
  203792. int SystemStats::getCpuSpeedInMegaherz()
  203793. {
  203794. const int64 cycles = juce_getClockCycleCounter();
  203795. const uint32 millis = Time::getMillisecondCounter();
  203796. int lastResult = 0;
  203797. for (;;)
  203798. {
  203799. int n = 1000000;
  203800. while (--n > 0) {}
  203801. const uint32 millisElapsed = Time::getMillisecondCounter() - millis;
  203802. const int64 cyclesNow = juce_getClockCycleCounter();
  203803. if (millisElapsed > 80)
  203804. {
  203805. const int newResult = (int) (((cyclesNow - cycles) / millisElapsed) / 1000);
  203806. if (millisElapsed > 500 || (lastResult == newResult && newResult > 100))
  203807. return newResult;
  203808. lastResult = newResult;
  203809. }
  203810. }
  203811. }
  203812. bool Time::setSystemTimeToThisTime() const
  203813. {
  203814. SYSTEMTIME st;
  203815. st.wDayOfWeek = 0;
  203816. st.wYear = (WORD) getYear();
  203817. st.wMonth = (WORD) (getMonth() + 1);
  203818. st.wDay = (WORD) getDayOfMonth();
  203819. st.wHour = (WORD) getHours();
  203820. st.wMinute = (WORD) getMinutes();
  203821. st.wSecond = (WORD) getSeconds();
  203822. st.wMilliseconds = (WORD) (millisSinceEpoch % 1000);
  203823. // do this twice because of daylight saving conversion problems - the
  203824. // first one sets it up, the second one kicks it in.
  203825. return SetLocalTime (&st) != 0
  203826. && SetLocalTime (&st) != 0;
  203827. }
  203828. int SystemStats::getPageSize()
  203829. {
  203830. SYSTEM_INFO systemInfo;
  203831. GetSystemInfo (&systemInfo);
  203832. return systemInfo.dwPageSize;
  203833. }
  203834. const String SystemStats::getLogonName()
  203835. {
  203836. TCHAR text [256];
  203837. DWORD len = numElementsInArray (text) - 2;
  203838. zerostruct (text);
  203839. GetUserName (text, &len);
  203840. return String (text, len);
  203841. }
  203842. const String SystemStats::getFullUserName()
  203843. {
  203844. return getLogonName();
  203845. }
  203846. #endif
  203847. /*** End of inlined file: juce_win32_SystemStats.cpp ***/
  203848. /*** Start of inlined file: juce_win32_Threads.cpp ***/
  203849. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203850. // compiled on its own).
  203851. #if JUCE_INCLUDED_FILE
  203852. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  203853. extern HWND juce_messageWindowHandle;
  203854. #endif
  203855. #if ! JUCE_USE_INTRINSICS
  203856. // In newer compilers, the inline versions of these are used (in juce_Atomic.h), but in
  203857. // older ones we have to actually call the ops as win32 functions..
  203858. long juce_InterlockedExchange (volatile long* a, long b) throw() { return InterlockedExchange (a, b); }
  203859. long juce_InterlockedIncrement (volatile long* a) throw() { return InterlockedIncrement (a); }
  203860. long juce_InterlockedDecrement (volatile long* a) throw() { return InterlockedDecrement (a); }
  203861. long juce_InterlockedExchangeAdd (volatile long* a, long b) throw() { return InterlockedExchangeAdd (a, b); }
  203862. long juce_InterlockedCompareExchange (volatile long* a, long b, long c) throw() { return InterlockedCompareExchange (a, b, c); }
  203863. __int64 juce_InterlockedCompareExchange64 (volatile __int64* value, __int64 newValue, __int64 valueToCompare) throw()
  203864. {
  203865. jassertfalse; // This operation isn't available in old MS compiler versions!
  203866. __int64 oldValue = *value;
  203867. if (oldValue == valueToCompare)
  203868. *value = newValue;
  203869. return oldValue;
  203870. }
  203871. #endif
  203872. CriticalSection::CriticalSection() throw()
  203873. {
  203874. // (just to check the MS haven't changed this structure and broken things...)
  203875. #if _MSC_VER >= 1400
  203876. static_jassert (sizeof (CRITICAL_SECTION) <= sizeof (internal));
  203877. #else
  203878. static_jassert (sizeof (CRITICAL_SECTION) <= 24);
  203879. #endif
  203880. InitializeCriticalSection ((CRITICAL_SECTION*) internal);
  203881. }
  203882. CriticalSection::~CriticalSection() throw()
  203883. {
  203884. DeleteCriticalSection ((CRITICAL_SECTION*) internal);
  203885. }
  203886. void CriticalSection::enter() const throw()
  203887. {
  203888. EnterCriticalSection ((CRITICAL_SECTION*) internal);
  203889. }
  203890. bool CriticalSection::tryEnter() const throw()
  203891. {
  203892. return TryEnterCriticalSection ((CRITICAL_SECTION*) internal) != FALSE;
  203893. }
  203894. void CriticalSection::exit() const throw()
  203895. {
  203896. LeaveCriticalSection ((CRITICAL_SECTION*) internal);
  203897. }
  203898. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  203899. : internal (CreateEvent (0, manualReset ? TRUE : FALSE, FALSE, 0))
  203900. {
  203901. }
  203902. WaitableEvent::~WaitableEvent() throw()
  203903. {
  203904. CloseHandle (internal);
  203905. }
  203906. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  203907. {
  203908. return WaitForSingleObject (internal, timeOutMillisecs) == WAIT_OBJECT_0;
  203909. }
  203910. void WaitableEvent::signal() const throw()
  203911. {
  203912. SetEvent (internal);
  203913. }
  203914. void WaitableEvent::reset() const throw()
  203915. {
  203916. ResetEvent (internal);
  203917. }
  203918. void JUCE_API juce_threadEntryPoint (void*);
  203919. static unsigned int __stdcall threadEntryProc (void* userData)
  203920. {
  203921. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  203922. AttachThreadInput (GetWindowThreadProcessId (juce_messageWindowHandle, 0),
  203923. GetCurrentThreadId(), TRUE);
  203924. #endif
  203925. juce_threadEntryPoint (userData);
  203926. _endthreadex (0);
  203927. return 0;
  203928. }
  203929. void juce_CloseThreadHandle (void* handle)
  203930. {
  203931. CloseHandle ((HANDLE) handle);
  203932. }
  203933. void* juce_createThread (void* userData)
  203934. {
  203935. unsigned int threadId;
  203936. return (void*) _beginthreadex (0, 0, &threadEntryProc, userData, 0, &threadId);
  203937. }
  203938. void juce_killThread (void* handle)
  203939. {
  203940. if (handle != 0)
  203941. {
  203942. #if JUCE_DEBUG
  203943. OutputDebugString (_T("** Warning - Forced thread termination **\n"));
  203944. #endif
  203945. TerminateThread (handle, 0);
  203946. }
  203947. }
  203948. void juce_setCurrentThreadName (const String& name)
  203949. {
  203950. #if JUCE_DEBUG && JUCE_MSVC
  203951. struct
  203952. {
  203953. DWORD dwType;
  203954. LPCSTR szName;
  203955. DWORD dwThreadID;
  203956. DWORD dwFlags;
  203957. } info;
  203958. info.dwType = 0x1000;
  203959. info.szName = name.toCString();
  203960. info.dwThreadID = GetCurrentThreadId();
  203961. info.dwFlags = 0;
  203962. __try
  203963. {
  203964. RaiseException (0x406d1388 /*MS_VC_EXCEPTION*/, 0, sizeof (info) / sizeof (ULONG_PTR), (ULONG_PTR*) &info);
  203965. }
  203966. __except (EXCEPTION_CONTINUE_EXECUTION)
  203967. {}
  203968. #else
  203969. (void) name;
  203970. #endif
  203971. }
  203972. Thread::ThreadID Thread::getCurrentThreadId()
  203973. {
  203974. return (ThreadID) (pointer_sized_int) GetCurrentThreadId();
  203975. }
  203976. // priority 1 to 10 where 5=normal, 1=low
  203977. bool juce_setThreadPriority (void* threadHandle, int priority)
  203978. {
  203979. int pri = THREAD_PRIORITY_TIME_CRITICAL;
  203980. if (priority < 1) pri = THREAD_PRIORITY_IDLE;
  203981. else if (priority < 2) pri = THREAD_PRIORITY_LOWEST;
  203982. else if (priority < 5) pri = THREAD_PRIORITY_BELOW_NORMAL;
  203983. else if (priority < 7) pri = THREAD_PRIORITY_NORMAL;
  203984. else if (priority < 9) pri = THREAD_PRIORITY_ABOVE_NORMAL;
  203985. else if (priority < 10) pri = THREAD_PRIORITY_HIGHEST;
  203986. if (threadHandle == 0)
  203987. threadHandle = GetCurrentThread();
  203988. return SetThreadPriority (threadHandle, pri) != FALSE;
  203989. }
  203990. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  203991. {
  203992. SetThreadAffinityMask (GetCurrentThread(), affinityMask);
  203993. }
  203994. static HANDLE sleepEvent = 0;
  203995. void juce_initialiseThreadEvents()
  203996. {
  203997. if (sleepEvent == 0)
  203998. #if JUCE_DEBUG
  203999. sleepEvent = CreateEvent (0, 0, 0, _T("Juce Sleep Event"));
  204000. #else
  204001. sleepEvent = CreateEvent (0, 0, 0, 0);
  204002. #endif
  204003. }
  204004. void Thread::yield()
  204005. {
  204006. Sleep (0);
  204007. }
  204008. void JUCE_CALLTYPE Thread::sleep (const int millisecs)
  204009. {
  204010. if (millisecs >= 10)
  204011. {
  204012. Sleep (millisecs);
  204013. }
  204014. else
  204015. {
  204016. jassert (sleepEvent != 0);
  204017. // unlike Sleep() this is guaranteed to return to the current thread after
  204018. // the time expires, so we'll use this for short waits, which are more likely
  204019. // to need to be accurate
  204020. WaitForSingleObject (sleepEvent, millisecs);
  204021. }
  204022. }
  204023. static int lastProcessPriority = -1;
  204024. // called by WindowDriver because Windows does wierd things to process priority
  204025. // when you swap apps, and this forces an update when the app is brought to the front.
  204026. void juce_repeatLastProcessPriority()
  204027. {
  204028. if (lastProcessPriority >= 0) // (avoid changing this if it's not been explicitly set by the app..)
  204029. {
  204030. DWORD p;
  204031. switch (lastProcessPriority)
  204032. {
  204033. case Process::LowPriority: p = IDLE_PRIORITY_CLASS; break;
  204034. case Process::NormalPriority: p = NORMAL_PRIORITY_CLASS; break;
  204035. case Process::HighPriority: p = HIGH_PRIORITY_CLASS; break;
  204036. case Process::RealtimePriority: p = REALTIME_PRIORITY_CLASS; break;
  204037. default: jassertfalse; return; // bad priority value
  204038. }
  204039. SetPriorityClass (GetCurrentProcess(), p);
  204040. }
  204041. }
  204042. void Process::setPriority (ProcessPriority prior)
  204043. {
  204044. if (lastProcessPriority != (int) prior)
  204045. {
  204046. lastProcessPriority = (int) prior;
  204047. juce_repeatLastProcessPriority();
  204048. }
  204049. }
  204050. JUCE_API bool JUCE_CALLTYPE juce_isRunningUnderDebugger()
  204051. {
  204052. return IsDebuggerPresent() != FALSE;
  204053. }
  204054. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  204055. {
  204056. return juce_isRunningUnderDebugger();
  204057. }
  204058. void Process::raisePrivilege()
  204059. {
  204060. jassertfalse; // xxx not implemented
  204061. }
  204062. void Process::lowerPrivilege()
  204063. {
  204064. jassertfalse; // xxx not implemented
  204065. }
  204066. void Process::terminate()
  204067. {
  204068. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  204069. _CrtDumpMemoryLeaks();
  204070. #endif
  204071. // bullet in the head in case there's a problem shutting down..
  204072. ExitProcess (0);
  204073. }
  204074. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  204075. {
  204076. void* result = 0;
  204077. JUCE_TRY
  204078. {
  204079. result = LoadLibrary (name);
  204080. }
  204081. JUCE_CATCH_ALL
  204082. return result;
  204083. }
  204084. void PlatformUtilities::freeDynamicLibrary (void* h)
  204085. {
  204086. JUCE_TRY
  204087. {
  204088. if (h != 0)
  204089. FreeLibrary ((HMODULE) h);
  204090. }
  204091. JUCE_CATCH_ALL
  204092. }
  204093. void* PlatformUtilities::getProcedureEntryPoint (void* h, const String& name)
  204094. {
  204095. return (h != 0) ? (void*) GetProcAddress ((HMODULE) h, name.toCString()) : 0; // (void* cast is required for mingw)
  204096. }
  204097. class InterProcessLock::Pimpl
  204098. {
  204099. public:
  204100. Pimpl (const String& name, const int timeOutMillisecs)
  204101. : handle (0), refCount (1)
  204102. {
  204103. handle = CreateMutex (0, TRUE, "Global\\" + name.replaceCharacter ('\\','/'));
  204104. if (handle != 0 && GetLastError() == ERROR_ALREADY_EXISTS)
  204105. {
  204106. if (timeOutMillisecs == 0)
  204107. {
  204108. close();
  204109. return;
  204110. }
  204111. switch (WaitForSingleObject (handle, timeOutMillisecs < 0 ? INFINITE : timeOutMillisecs))
  204112. {
  204113. case WAIT_OBJECT_0:
  204114. case WAIT_ABANDONED:
  204115. break;
  204116. case WAIT_TIMEOUT:
  204117. default:
  204118. close();
  204119. break;
  204120. }
  204121. }
  204122. }
  204123. ~Pimpl()
  204124. {
  204125. close();
  204126. }
  204127. void close()
  204128. {
  204129. if (handle != 0)
  204130. {
  204131. ReleaseMutex (handle);
  204132. CloseHandle (handle);
  204133. handle = 0;
  204134. }
  204135. }
  204136. HANDLE handle;
  204137. int refCount;
  204138. };
  204139. InterProcessLock::InterProcessLock (const String& name_)
  204140. : name (name_)
  204141. {
  204142. }
  204143. InterProcessLock::~InterProcessLock()
  204144. {
  204145. }
  204146. bool InterProcessLock::enter (const int timeOutMillisecs)
  204147. {
  204148. const ScopedLock sl (lock);
  204149. if (pimpl == 0)
  204150. {
  204151. pimpl = new Pimpl (name, timeOutMillisecs);
  204152. if (pimpl->handle == 0)
  204153. pimpl = 0;
  204154. }
  204155. else
  204156. {
  204157. pimpl->refCount++;
  204158. }
  204159. return pimpl != 0;
  204160. }
  204161. void InterProcessLock::exit()
  204162. {
  204163. const ScopedLock sl (lock);
  204164. // Trying to release the lock too many times!
  204165. jassert (pimpl != 0);
  204166. if (pimpl != 0 && --(pimpl->refCount) == 0)
  204167. pimpl = 0;
  204168. }
  204169. #endif
  204170. /*** End of inlined file: juce_win32_Threads.cpp ***/
  204171. /*** Start of inlined file: juce_win32_Files.cpp ***/
  204172. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204173. // compiled on its own).
  204174. #if JUCE_INCLUDED_FILE
  204175. #ifndef CSIDL_MYMUSIC
  204176. #define CSIDL_MYMUSIC 0x000d
  204177. #endif
  204178. #ifndef CSIDL_MYVIDEO
  204179. #define CSIDL_MYVIDEO 0x000e
  204180. #endif
  204181. #ifndef INVALID_FILE_ATTRIBUTES
  204182. #define INVALID_FILE_ATTRIBUTES ((DWORD) -1)
  204183. #endif
  204184. namespace WindowsFileHelpers
  204185. {
  204186. int64 fileTimeToTime (const FILETIME* const ft)
  204187. {
  204188. static_jassert (sizeof (ULARGE_INTEGER) == sizeof (FILETIME)); // tell me if this fails!
  204189. return (reinterpret_cast<const ULARGE_INTEGER*> (ft)->QuadPart - literal64bit (116444736000000000)) / 10000;
  204190. }
  204191. void timeToFileTime (const int64 time, FILETIME* const ft)
  204192. {
  204193. reinterpret_cast<ULARGE_INTEGER*> (ft)->QuadPart = time * 10000 + literal64bit (116444736000000000);
  204194. }
  204195. const String getDriveFromPath (const String& path)
  204196. {
  204197. if (path.isNotEmpty() && path[1] == ':')
  204198. return path.substring (0, 2) + '\\';
  204199. return path;
  204200. }
  204201. int64 getDiskSpaceInfo (const String& path, const bool total)
  204202. {
  204203. ULARGE_INTEGER spc, tot, totFree;
  204204. if (GetDiskFreeSpaceEx (getDriveFromPath (path), &spc, &tot, &totFree))
  204205. return total ? (int64) tot.QuadPart
  204206. : (int64) spc.QuadPart;
  204207. return 0;
  204208. }
  204209. unsigned int getWindowsDriveType (const String& path)
  204210. {
  204211. return GetDriveType (getDriveFromPath (path));
  204212. }
  204213. const File getSpecialFolderPath (int type)
  204214. {
  204215. WCHAR path [MAX_PATH + 256];
  204216. if (SHGetSpecialFolderPath (0, path, type, FALSE))
  204217. return File (String (path));
  204218. return File::nonexistent;
  204219. }
  204220. }
  204221. const juce_wchar File::separator = '\\';
  204222. const String File::separatorString ("\\");
  204223. bool File::exists() const
  204224. {
  204225. return fullPath.isNotEmpty()
  204226. && GetFileAttributes (fullPath) != INVALID_FILE_ATTRIBUTES;
  204227. }
  204228. bool File::existsAsFile() const
  204229. {
  204230. return fullPath.isNotEmpty()
  204231. && (GetFileAttributes (fullPath) & FILE_ATTRIBUTE_DIRECTORY) == 0;
  204232. }
  204233. bool File::isDirectory() const
  204234. {
  204235. const DWORD attr = GetFileAttributes (fullPath);
  204236. return ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) && (attr != INVALID_FILE_ATTRIBUTES);
  204237. }
  204238. bool File::hasWriteAccess() const
  204239. {
  204240. if (exists())
  204241. return (GetFileAttributes (fullPath) & FILE_ATTRIBUTE_READONLY) == 0;
  204242. // on windows, it seems that even read-only directories can still be written into,
  204243. // so checking the parent directory's permissions would return the wrong result..
  204244. return true;
  204245. }
  204246. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  204247. {
  204248. DWORD attr = GetFileAttributes (fullPath);
  204249. if (attr == INVALID_FILE_ATTRIBUTES)
  204250. return false;
  204251. if (shouldBeReadOnly == ((attr & FILE_ATTRIBUTE_READONLY) != 0))
  204252. return true;
  204253. if (shouldBeReadOnly)
  204254. attr |= FILE_ATTRIBUTE_READONLY;
  204255. else
  204256. attr &= ~FILE_ATTRIBUTE_READONLY;
  204257. return SetFileAttributes (fullPath, attr) != FALSE;
  204258. }
  204259. bool File::isHidden() const
  204260. {
  204261. return (GetFileAttributes (getFullPathName()) & FILE_ATTRIBUTE_HIDDEN) != 0;
  204262. }
  204263. bool File::deleteFile() const
  204264. {
  204265. if (! exists())
  204266. return true;
  204267. else if (isDirectory())
  204268. return RemoveDirectory (fullPath) != 0;
  204269. else
  204270. return DeleteFile (fullPath) != 0;
  204271. }
  204272. bool File::moveToTrash() const
  204273. {
  204274. if (! exists())
  204275. return true;
  204276. SHFILEOPSTRUCT fos;
  204277. zerostruct (fos);
  204278. // The string we pass in must be double null terminated..
  204279. String doubleNullTermPath (getFullPathName() + " ");
  204280. TCHAR* const p = const_cast <TCHAR*> (static_cast <const TCHAR*> (doubleNullTermPath));
  204281. p [getFullPathName().length()] = 0;
  204282. fos.wFunc = FO_DELETE;
  204283. fos.pFrom = p;
  204284. fos.fFlags = FOF_ALLOWUNDO | FOF_NOERRORUI | FOF_SILENT | FOF_NOCONFIRMATION
  204285. | FOF_NOCONFIRMMKDIR | FOF_RENAMEONCOLLISION;
  204286. return SHFileOperation (&fos) == 0;
  204287. }
  204288. bool File::copyInternal (const File& dest) const
  204289. {
  204290. return CopyFile (fullPath, dest.getFullPathName(), false) != 0;
  204291. }
  204292. bool File::moveInternal (const File& dest) const
  204293. {
  204294. return MoveFile (fullPath, dest.getFullPathName()) != 0;
  204295. }
  204296. void File::createDirectoryInternal (const String& fileName) const
  204297. {
  204298. CreateDirectory (fileName, 0);
  204299. }
  204300. int64 juce_fileSetPosition (void* handle, int64 pos)
  204301. {
  204302. LARGE_INTEGER li;
  204303. li.QuadPart = pos;
  204304. li.LowPart = SetFilePointer ((HANDLE) handle, li.LowPart, &li.HighPart, FILE_BEGIN); // (returns -1 if it fails)
  204305. return li.QuadPart;
  204306. }
  204307. void FileInputStream::openHandle()
  204308. {
  204309. totalSize = file.getSize();
  204310. HANDLE h = CreateFile (file.getFullPathName(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
  204311. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, 0);
  204312. if (h != INVALID_HANDLE_VALUE)
  204313. fileHandle = (void*) h;
  204314. }
  204315. void FileInputStream::closeHandle()
  204316. {
  204317. CloseHandle ((HANDLE) fileHandle);
  204318. }
  204319. size_t FileInputStream::readInternal (void* buffer, size_t numBytes)
  204320. {
  204321. if (fileHandle != 0)
  204322. {
  204323. DWORD actualNum = 0;
  204324. ReadFile ((HANDLE) fileHandle, buffer, numBytes, &actualNum, 0);
  204325. return (size_t) actualNum;
  204326. }
  204327. return 0;
  204328. }
  204329. void FileOutputStream::openHandle()
  204330. {
  204331. HANDLE h = CreateFile (file.getFullPathName(), GENERIC_WRITE, FILE_SHARE_READ, 0,
  204332. OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  204333. if (h != INVALID_HANDLE_VALUE)
  204334. {
  204335. LARGE_INTEGER li;
  204336. li.QuadPart = 0;
  204337. li.LowPart = SetFilePointer (h, 0, &li.HighPart, FILE_END);
  204338. if (li.LowPart != INVALID_SET_FILE_POINTER)
  204339. {
  204340. fileHandle = (void*) h;
  204341. currentPosition = li.QuadPart;
  204342. }
  204343. }
  204344. }
  204345. void FileOutputStream::closeHandle()
  204346. {
  204347. CloseHandle ((HANDLE) fileHandle);
  204348. }
  204349. int FileOutputStream::writeInternal (const void* buffer, int numBytes)
  204350. {
  204351. if (fileHandle != 0)
  204352. {
  204353. DWORD actualNum = 0;
  204354. WriteFile ((HANDLE) fileHandle, buffer, numBytes, &actualNum, 0);
  204355. return (int) actualNum;
  204356. }
  204357. return 0;
  204358. }
  204359. void FileOutputStream::flushInternal()
  204360. {
  204361. if (fileHandle != 0)
  204362. FlushFileBuffers ((HANDLE) fileHandle);
  204363. }
  204364. int64 File::getSize() const
  204365. {
  204366. WIN32_FILE_ATTRIBUTE_DATA attributes;
  204367. if (GetFileAttributesEx (fullPath, GetFileExInfoStandard, &attributes))
  204368. return (((int64) attributes.nFileSizeHigh) << 32) | attributes.nFileSizeLow;
  204369. return 0;
  204370. }
  204371. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  204372. {
  204373. using namespace WindowsFileHelpers;
  204374. WIN32_FILE_ATTRIBUTE_DATA attributes;
  204375. if (GetFileAttributesEx (fullPath, GetFileExInfoStandard, &attributes))
  204376. {
  204377. modificationTime = fileTimeToTime (&attributes.ftLastWriteTime);
  204378. creationTime = fileTimeToTime (&attributes.ftCreationTime);
  204379. accessTime = fileTimeToTime (&attributes.ftLastAccessTime);
  204380. }
  204381. else
  204382. {
  204383. creationTime = accessTime = modificationTime = 0;
  204384. }
  204385. }
  204386. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 creationTime) const
  204387. {
  204388. using namespace WindowsFileHelpers;
  204389. bool ok = false;
  204390. HANDLE h = CreateFile (fullPath, GENERIC_WRITE, FILE_SHARE_READ, 0,
  204391. OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  204392. if (h != INVALID_HANDLE_VALUE)
  204393. {
  204394. FILETIME m, a, c;
  204395. timeToFileTime (modificationTime, &m);
  204396. timeToFileTime (accessTime, &a);
  204397. timeToFileTime (creationTime, &c);
  204398. ok = SetFileTime (h,
  204399. creationTime > 0 ? &c : 0,
  204400. accessTime > 0 ? &a : 0,
  204401. modificationTime > 0 ? &m : 0) != 0;
  204402. CloseHandle (h);
  204403. }
  204404. return ok;
  204405. }
  204406. void File::findFileSystemRoots (Array<File>& destArray)
  204407. {
  204408. TCHAR buffer [2048];
  204409. buffer[0] = 0;
  204410. buffer[1] = 0;
  204411. GetLogicalDriveStrings (2048, buffer);
  204412. const TCHAR* n = buffer;
  204413. StringArray roots;
  204414. while (*n != 0)
  204415. {
  204416. roots.add (String (n));
  204417. while (*n++ != 0)
  204418. {}
  204419. }
  204420. roots.sort (true);
  204421. for (int i = 0; i < roots.size(); ++i)
  204422. destArray.add (roots [i]);
  204423. }
  204424. const String File::getVolumeLabel() const
  204425. {
  204426. TCHAR dest[64];
  204427. if (! GetVolumeInformation (WindowsFileHelpers::getDriveFromPath (getFullPathName()), dest,
  204428. numElementsInArray (dest), 0, 0, 0, 0, 0))
  204429. dest[0] = 0;
  204430. return dest;
  204431. }
  204432. int File::getVolumeSerialNumber() const
  204433. {
  204434. TCHAR dest[64];
  204435. DWORD serialNum;
  204436. if (! GetVolumeInformation (WindowsFileHelpers::getDriveFromPath (getFullPathName()), dest,
  204437. numElementsInArray (dest), &serialNum, 0, 0, 0, 0))
  204438. return 0;
  204439. return (int) serialNum;
  204440. }
  204441. int64 File::getBytesFreeOnVolume() const
  204442. {
  204443. return WindowsFileHelpers::getDiskSpaceInfo (getFullPathName(), false);
  204444. }
  204445. int64 File::getVolumeTotalSize() const
  204446. {
  204447. return WindowsFileHelpers::getDiskSpaceInfo (getFullPathName(), true);
  204448. }
  204449. bool File::isOnCDRomDrive() const
  204450. {
  204451. return WindowsFileHelpers::getWindowsDriveType (getFullPathName()) == DRIVE_CDROM;
  204452. }
  204453. bool File::isOnHardDisk() const
  204454. {
  204455. if (fullPath.isEmpty())
  204456. return false;
  204457. const unsigned int n = WindowsFileHelpers::getWindowsDriveType (getFullPathName());
  204458. if (fullPath.toLowerCase()[0] <= 'b' && fullPath[1] == ':')
  204459. return n != DRIVE_REMOVABLE;
  204460. else
  204461. return n != DRIVE_CDROM && n != DRIVE_REMOTE;
  204462. }
  204463. bool File::isOnRemovableDrive() const
  204464. {
  204465. if (fullPath.isEmpty())
  204466. return false;
  204467. const unsigned int n = WindowsFileHelpers::getWindowsDriveType (getFullPathName());
  204468. return n == DRIVE_CDROM
  204469. || n == DRIVE_REMOTE
  204470. || n == DRIVE_REMOVABLE
  204471. || n == DRIVE_RAMDISK;
  204472. }
  204473. const File JUCE_CALLTYPE File::getSpecialLocation (const SpecialLocationType type)
  204474. {
  204475. int csidlType = 0;
  204476. switch (type)
  204477. {
  204478. case userHomeDirectory: csidlType = CSIDL_PROFILE; break;
  204479. case userDocumentsDirectory: csidlType = CSIDL_PERSONAL; break;
  204480. case userDesktopDirectory: csidlType = CSIDL_DESKTOP; break;
  204481. case userApplicationDataDirectory: csidlType = CSIDL_APPDATA; break;
  204482. case commonApplicationDataDirectory: csidlType = CSIDL_COMMON_APPDATA; break;
  204483. case globalApplicationsDirectory: csidlType = CSIDL_PROGRAM_FILES; break;
  204484. case userMusicDirectory: csidlType = CSIDL_MYMUSIC; break;
  204485. case userMoviesDirectory: csidlType = CSIDL_MYVIDEO; break;
  204486. case tempDirectory:
  204487. {
  204488. WCHAR dest [2048];
  204489. dest[0] = 0;
  204490. GetTempPath (numElementsInArray (dest), dest);
  204491. return File (String (dest));
  204492. }
  204493. case invokedExecutableFile:
  204494. case currentExecutableFile:
  204495. case currentApplicationFile:
  204496. {
  204497. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  204498. WCHAR dest [MAX_PATH + 256];
  204499. dest[0] = 0;
  204500. GetModuleFileName (moduleHandle, dest, numElementsInArray (dest));
  204501. return File (String (dest));
  204502. }
  204503. case hostApplicationPath:
  204504. {
  204505. WCHAR dest [MAX_PATH + 256];
  204506. dest[0] = 0;
  204507. GetModuleFileName (0, dest, numElementsInArray (dest));
  204508. return File (String (dest));
  204509. }
  204510. default:
  204511. jassertfalse; // unknown type?
  204512. return File::nonexistent;
  204513. }
  204514. return WindowsFileHelpers::getSpecialFolderPath (csidlType);
  204515. }
  204516. const File File::getCurrentWorkingDirectory()
  204517. {
  204518. WCHAR dest [MAX_PATH + 256];
  204519. dest[0] = 0;
  204520. GetCurrentDirectory (numElementsInArray (dest), dest);
  204521. return File (String (dest));
  204522. }
  204523. bool File::setAsCurrentWorkingDirectory() const
  204524. {
  204525. return SetCurrentDirectory (getFullPathName()) != FALSE;
  204526. }
  204527. const String File::getVersion() const
  204528. {
  204529. String result;
  204530. DWORD handle = 0;
  204531. DWORD bufferSize = GetFileVersionInfoSize (getFullPathName(), &handle);
  204532. HeapBlock<char> buffer;
  204533. buffer.calloc (bufferSize);
  204534. if (GetFileVersionInfo (getFullPathName(), 0, bufferSize, buffer))
  204535. {
  204536. VS_FIXEDFILEINFO* vffi;
  204537. UINT len = 0;
  204538. if (VerQueryValue (buffer, (LPTSTR) _T("\\"), (LPVOID*) &vffi, &len))
  204539. {
  204540. result << (int) HIWORD (vffi->dwFileVersionMS) << '.'
  204541. << (int) LOWORD (vffi->dwFileVersionMS) << '.'
  204542. << (int) HIWORD (vffi->dwFileVersionLS) << '.'
  204543. << (int) LOWORD (vffi->dwFileVersionLS);
  204544. }
  204545. }
  204546. return result;
  204547. }
  204548. const File File::getLinkedTarget() const
  204549. {
  204550. File result (*this);
  204551. String p (getFullPathName());
  204552. if (! exists())
  204553. p += ".lnk";
  204554. else if (getFileExtension() != ".lnk")
  204555. return result;
  204556. ComSmartPtr <IShellLink> shellLink;
  204557. if (SUCCEEDED (shellLink.CoCreateInstance (CLSID_ShellLink)))
  204558. {
  204559. ComSmartPtr <IPersistFile> persistFile;
  204560. if (SUCCEEDED (shellLink.QueryInterface (IID_IPersistFile, persistFile)))
  204561. {
  204562. if (SUCCEEDED (persistFile->Load ((const WCHAR*) p, STGM_READ))
  204563. && SUCCEEDED (shellLink->Resolve (0, SLR_ANY_MATCH | SLR_NO_UI)))
  204564. {
  204565. WIN32_FIND_DATA winFindData;
  204566. WCHAR resolvedPath [MAX_PATH];
  204567. if (SUCCEEDED (shellLink->GetPath (resolvedPath, MAX_PATH, &winFindData, SLGP_UNCPRIORITY)))
  204568. result = File (resolvedPath);
  204569. }
  204570. }
  204571. }
  204572. return result;
  204573. }
  204574. class DirectoryIterator::NativeIterator::Pimpl
  204575. {
  204576. public:
  204577. Pimpl (const File& directory, const String& wildCard)
  204578. : directoryWithWildCard (File::addTrailingSeparator (directory.getFullPathName()) + wildCard),
  204579. handle (INVALID_HANDLE_VALUE)
  204580. {
  204581. }
  204582. ~Pimpl()
  204583. {
  204584. if (handle != INVALID_HANDLE_VALUE)
  204585. FindClose (handle);
  204586. }
  204587. bool next (String& filenameFound,
  204588. bool* const isDir, bool* const isHidden, int64* const fileSize,
  204589. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  204590. {
  204591. using namespace WindowsFileHelpers;
  204592. WIN32_FIND_DATA findData;
  204593. if (handle == INVALID_HANDLE_VALUE)
  204594. {
  204595. handle = FindFirstFile (directoryWithWildCard, &findData);
  204596. if (handle == INVALID_HANDLE_VALUE)
  204597. return false;
  204598. }
  204599. else
  204600. {
  204601. if (FindNextFile (handle, &findData) == 0)
  204602. return false;
  204603. }
  204604. filenameFound = findData.cFileName;
  204605. if (isDir != 0) *isDir = ((findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
  204606. if (isHidden != 0) *isHidden = ((findData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) != 0);
  204607. if (fileSize != 0) *fileSize = findData.nFileSizeLow + (((int64) findData.nFileSizeHigh) << 32);
  204608. if (modTime != 0) *modTime = fileTimeToTime (&findData.ftLastWriteTime);
  204609. if (creationTime != 0) *creationTime = fileTimeToTime (&findData.ftCreationTime);
  204610. if (isReadOnly != 0) *isReadOnly = ((findData.dwFileAttributes & FILE_ATTRIBUTE_READONLY) != 0);
  204611. return true;
  204612. }
  204613. juce_UseDebuggingNewOperator
  204614. private:
  204615. const String directoryWithWildCard;
  204616. HANDLE handle;
  204617. Pimpl (const Pimpl&);
  204618. Pimpl& operator= (const Pimpl&);
  204619. };
  204620. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  204621. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  204622. {
  204623. }
  204624. DirectoryIterator::NativeIterator::~NativeIterator()
  204625. {
  204626. }
  204627. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  204628. bool* const isDir, bool* const isHidden, int64* const fileSize,
  204629. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  204630. {
  204631. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  204632. }
  204633. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  204634. {
  204635. HINSTANCE hInstance = 0;
  204636. JUCE_TRY
  204637. {
  204638. hInstance = ShellExecute (0, 0, fileName, parameters, 0, SW_SHOWDEFAULT);
  204639. }
  204640. JUCE_CATCH_ALL
  204641. return hInstance > (HINSTANCE) 32;
  204642. }
  204643. void File::revealToUser() const
  204644. {
  204645. if (isDirectory())
  204646. startAsProcess();
  204647. else if (getParentDirectory().exists())
  204648. getParentDirectory().startAsProcess();
  204649. }
  204650. class NamedPipeInternal
  204651. {
  204652. public:
  204653. NamedPipeInternal (const String& file, const bool isPipe_)
  204654. : pipeH (0),
  204655. cancelEvent (0),
  204656. connected (false),
  204657. isPipe (isPipe_)
  204658. {
  204659. cancelEvent = CreateEvent (0, FALSE, FALSE, 0);
  204660. pipeH = isPipe ? CreateNamedPipe (file, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, 0,
  204661. PIPE_UNLIMITED_INSTANCES, 4096, 4096, 0, 0)
  204662. : CreateFile (file, GENERIC_READ | GENERIC_WRITE, 0, 0,
  204663. OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
  204664. }
  204665. ~NamedPipeInternal()
  204666. {
  204667. disconnectPipe();
  204668. if (pipeH != 0)
  204669. CloseHandle (pipeH);
  204670. CloseHandle (cancelEvent);
  204671. }
  204672. bool connect (const int timeOutMs)
  204673. {
  204674. if (! isPipe)
  204675. return true;
  204676. if (! connected)
  204677. {
  204678. OVERLAPPED over;
  204679. zerostruct (over);
  204680. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204681. if (ConnectNamedPipe (pipeH, &over))
  204682. {
  204683. connected = false; // yes, you read that right. In overlapped mode it should always return 0.
  204684. }
  204685. else
  204686. {
  204687. const int err = GetLastError();
  204688. if (err == ERROR_IO_PENDING || err == ERROR_PIPE_LISTENING)
  204689. {
  204690. HANDLE handles[] = { over.hEvent, cancelEvent };
  204691. if (WaitForMultipleObjects (2, handles, FALSE,
  204692. timeOutMs >= 0 ? timeOutMs : INFINITE) == WAIT_OBJECT_0)
  204693. connected = true;
  204694. }
  204695. else if (err == ERROR_PIPE_CONNECTED)
  204696. {
  204697. connected = true;
  204698. }
  204699. }
  204700. CloseHandle (over.hEvent);
  204701. }
  204702. return connected;
  204703. }
  204704. void disconnectPipe()
  204705. {
  204706. if (connected)
  204707. {
  204708. DisconnectNamedPipe (pipeH);
  204709. connected = false;
  204710. }
  204711. }
  204712. HANDLE pipeH;
  204713. HANDLE cancelEvent;
  204714. bool connected, isPipe;
  204715. };
  204716. void NamedPipe::close()
  204717. {
  204718. cancelPendingReads();
  204719. const ScopedLock sl (lock);
  204720. delete static_cast<NamedPipeInternal*> (internal);
  204721. internal = 0;
  204722. }
  204723. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  204724. {
  204725. close();
  204726. ScopedPointer<NamedPipeInternal> intern (new NamedPipeInternal ("\\\\.\\pipe\\" + pipeName, createPipe));
  204727. if (intern->pipeH != INVALID_HANDLE_VALUE)
  204728. {
  204729. internal = intern.release();
  204730. return true;
  204731. }
  204732. return false;
  204733. }
  204734. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds)
  204735. {
  204736. const ScopedLock sl (lock);
  204737. int bytesRead = -1;
  204738. bool waitAgain = true;
  204739. while (waitAgain && internal != 0)
  204740. {
  204741. NamedPipeInternal* const intern = static_cast<NamedPipeInternal*> (internal);
  204742. waitAgain = false;
  204743. if (! intern->connect (timeOutMilliseconds))
  204744. break;
  204745. if (maxBytesToRead <= 0)
  204746. return 0;
  204747. OVERLAPPED over;
  204748. zerostruct (over);
  204749. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204750. unsigned long numRead;
  204751. if (ReadFile (intern->pipeH, destBuffer, maxBytesToRead, &numRead, &over))
  204752. {
  204753. bytesRead = (int) numRead;
  204754. }
  204755. else if (GetLastError() == ERROR_IO_PENDING)
  204756. {
  204757. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  204758. DWORD waitResult = WaitForMultipleObjects (2, handles, FALSE,
  204759. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  204760. : INFINITE);
  204761. if (waitResult != WAIT_OBJECT_0)
  204762. {
  204763. // if the operation timed out, let's cancel it...
  204764. CancelIo (intern->pipeH);
  204765. WaitForSingleObject (over.hEvent, INFINITE); // makes sure cancel is complete
  204766. }
  204767. if (GetOverlappedResult (intern->pipeH, &over, &numRead, FALSE))
  204768. {
  204769. bytesRead = (int) numRead;
  204770. }
  204771. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->isPipe)
  204772. {
  204773. intern->disconnectPipe();
  204774. waitAgain = true;
  204775. }
  204776. }
  204777. else
  204778. {
  204779. waitAgain = internal != 0;
  204780. Sleep (5);
  204781. }
  204782. CloseHandle (over.hEvent);
  204783. }
  204784. return bytesRead;
  204785. }
  204786. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  204787. {
  204788. int bytesWritten = -1;
  204789. NamedPipeInternal* const intern = static_cast<NamedPipeInternal*> (internal);
  204790. if (intern != 0 && intern->connect (timeOutMilliseconds))
  204791. {
  204792. if (numBytesToWrite <= 0)
  204793. return 0;
  204794. OVERLAPPED over;
  204795. zerostruct (over);
  204796. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204797. unsigned long numWritten;
  204798. if (WriteFile (intern->pipeH, sourceBuffer, numBytesToWrite, &numWritten, &over))
  204799. {
  204800. bytesWritten = (int) numWritten;
  204801. }
  204802. else if (GetLastError() == ERROR_IO_PENDING)
  204803. {
  204804. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  204805. DWORD waitResult;
  204806. waitResult = WaitForMultipleObjects (2, handles, FALSE,
  204807. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  204808. : INFINITE);
  204809. if (waitResult != WAIT_OBJECT_0)
  204810. {
  204811. CancelIo (intern->pipeH);
  204812. WaitForSingleObject (over.hEvent, INFINITE);
  204813. }
  204814. if (GetOverlappedResult (intern->pipeH, &over, &numWritten, FALSE))
  204815. {
  204816. bytesWritten = (int) numWritten;
  204817. }
  204818. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->isPipe)
  204819. {
  204820. intern->disconnectPipe();
  204821. }
  204822. }
  204823. CloseHandle (over.hEvent);
  204824. }
  204825. return bytesWritten;
  204826. }
  204827. void NamedPipe::cancelPendingReads()
  204828. {
  204829. if (internal != 0)
  204830. SetEvent (static_cast<NamedPipeInternal*> (internal)->cancelEvent);
  204831. }
  204832. #endif
  204833. /*** End of inlined file: juce_win32_Files.cpp ***/
  204834. /*** Start of inlined file: juce_win32_Network.cpp ***/
  204835. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204836. // compiled on its own).
  204837. #if JUCE_INCLUDED_FILE
  204838. #ifndef INTERNET_FLAG_NEED_FILE
  204839. #define INTERNET_FLAG_NEED_FILE 0x00000010
  204840. #endif
  204841. #ifndef INTERNET_OPTION_DISABLE_AUTODIAL
  204842. #define INTERNET_OPTION_DISABLE_AUTODIAL 70
  204843. #endif
  204844. struct ConnectionAndRequestStruct
  204845. {
  204846. HINTERNET connection, request;
  204847. };
  204848. static HINTERNET sessionHandle = 0;
  204849. #ifndef WORKAROUND_TIMEOUT_BUG
  204850. //#define WORKAROUND_TIMEOUT_BUG 1
  204851. #endif
  204852. #if WORKAROUND_TIMEOUT_BUG
  204853. // Required because of a Microsoft bug in setting a timeout
  204854. class InternetConnectThread : public Thread
  204855. {
  204856. public:
  204857. InternetConnectThread (URL_COMPONENTS& uc_, HINTERNET& connection_, const bool isFtp_)
  204858. : Thread ("Internet"), uc (uc_), connection (connection_), isFtp (isFtp_)
  204859. {
  204860. startThread();
  204861. }
  204862. ~InternetConnectThread()
  204863. {
  204864. stopThread (60000);
  204865. }
  204866. void run()
  204867. {
  204868. connection = InternetConnect (sessionHandle, uc.lpszHostName,
  204869. uc.nPort, _T(""), _T(""),
  204870. isFtp ? INTERNET_SERVICE_FTP
  204871. : INTERNET_SERVICE_HTTP,
  204872. 0, 0);
  204873. notify();
  204874. }
  204875. juce_UseDebuggingNewOperator
  204876. private:
  204877. URL_COMPONENTS& uc;
  204878. HINTERNET& connection;
  204879. const bool isFtp;
  204880. InternetConnectThread (const InternetConnectThread&);
  204881. InternetConnectThread& operator= (const InternetConnectThread&);
  204882. };
  204883. #endif
  204884. void* juce_openInternetFile (const String& url,
  204885. const String& headers,
  204886. const MemoryBlock& postData,
  204887. const bool isPost,
  204888. URL::OpenStreamProgressCallback* callback,
  204889. void* callbackContext,
  204890. int timeOutMs)
  204891. {
  204892. if (sessionHandle == 0)
  204893. sessionHandle = InternetOpen (_T("juce"),
  204894. INTERNET_OPEN_TYPE_PRECONFIG,
  204895. 0, 0, 0);
  204896. if (sessionHandle != 0)
  204897. {
  204898. // break up the url..
  204899. TCHAR file[1024], server[1024];
  204900. URL_COMPONENTS uc;
  204901. zerostruct (uc);
  204902. uc.dwStructSize = sizeof (uc);
  204903. uc.dwUrlPathLength = sizeof (file);
  204904. uc.dwHostNameLength = sizeof (server);
  204905. uc.lpszUrlPath = file;
  204906. uc.lpszHostName = server;
  204907. if (InternetCrackUrl (url, 0, 0, &uc))
  204908. {
  204909. int disable = 1;
  204910. InternetSetOption (sessionHandle, INTERNET_OPTION_DISABLE_AUTODIAL, &disable, sizeof (disable));
  204911. if (timeOutMs == 0)
  204912. timeOutMs = 30000;
  204913. else if (timeOutMs < 0)
  204914. timeOutMs = -1;
  204915. InternetSetOption (sessionHandle, INTERNET_OPTION_CONNECT_TIMEOUT, &timeOutMs, sizeof (timeOutMs));
  204916. const bool isFtp = url.startsWithIgnoreCase ("ftp:");
  204917. #if WORKAROUND_TIMEOUT_BUG
  204918. HINTERNET connection = 0;
  204919. {
  204920. InternetConnectThread connectThread (uc, connection, isFtp);
  204921. connectThread.wait (timeOutMs);
  204922. if (connection == 0)
  204923. {
  204924. InternetCloseHandle (sessionHandle);
  204925. sessionHandle = 0;
  204926. }
  204927. }
  204928. #else
  204929. HINTERNET connection = InternetConnect (sessionHandle,
  204930. uc.lpszHostName,
  204931. uc.nPort,
  204932. _T(""), _T(""),
  204933. isFtp ? INTERNET_SERVICE_FTP
  204934. : INTERNET_SERVICE_HTTP,
  204935. 0, 0);
  204936. #endif
  204937. if (connection != 0)
  204938. {
  204939. if (isFtp)
  204940. {
  204941. HINTERNET request = FtpOpenFile (connection,
  204942. uc.lpszUrlPath,
  204943. GENERIC_READ,
  204944. FTP_TRANSFER_TYPE_BINARY | INTERNET_FLAG_NEED_FILE,
  204945. 0);
  204946. ConnectionAndRequestStruct* const result = new ConnectionAndRequestStruct();
  204947. result->connection = connection;
  204948. result->request = request;
  204949. return result;
  204950. }
  204951. else
  204952. {
  204953. const TCHAR* mimeTypes[] = { _T("*/*"), 0 };
  204954. DWORD flags = INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_NO_COOKIES;
  204955. if (url.startsWithIgnoreCase ("https:"))
  204956. flags |= INTERNET_FLAG_SECURE; // (this flag only seems necessary if the OS is running IE6 -
  204957. // IE7 seems to automatically work out when it's https)
  204958. HINTERNET request = HttpOpenRequest (connection,
  204959. isPost ? _T("POST")
  204960. : _T("GET"),
  204961. uc.lpszUrlPath,
  204962. 0, 0, mimeTypes, flags, 0);
  204963. if (request != 0)
  204964. {
  204965. INTERNET_BUFFERS buffers;
  204966. zerostruct (buffers);
  204967. buffers.dwStructSize = sizeof (INTERNET_BUFFERS);
  204968. buffers.lpcszHeader = (LPCTSTR) headers;
  204969. buffers.dwHeadersLength = headers.length();
  204970. buffers.dwBufferTotal = (DWORD) postData.getSize();
  204971. ConnectionAndRequestStruct* result = 0;
  204972. if (HttpSendRequestEx (request, &buffers, 0, HSR_INITIATE, 0))
  204973. {
  204974. int bytesSent = 0;
  204975. for (;;)
  204976. {
  204977. const int bytesToDo = jmin (1024, (int) postData.getSize() - bytesSent);
  204978. DWORD bytesDone = 0;
  204979. if (bytesToDo > 0
  204980. && ! InternetWriteFile (request,
  204981. static_cast <const char*> (postData.getData()) + bytesSent,
  204982. bytesToDo, &bytesDone))
  204983. {
  204984. break;
  204985. }
  204986. if (bytesToDo == 0 || (int) bytesDone < bytesToDo)
  204987. {
  204988. result = new ConnectionAndRequestStruct();
  204989. result->connection = connection;
  204990. result->request = request;
  204991. if (! HttpEndRequest (request, 0, 0, 0))
  204992. break;
  204993. return result;
  204994. }
  204995. bytesSent += bytesDone;
  204996. if (callback != 0 && ! callback (callbackContext, bytesSent, postData.getSize()))
  204997. break;
  204998. }
  204999. }
  205000. InternetCloseHandle (request);
  205001. }
  205002. InternetCloseHandle (connection);
  205003. }
  205004. }
  205005. }
  205006. }
  205007. return 0;
  205008. }
  205009. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  205010. {
  205011. DWORD bytesRead = 0;
  205012. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  205013. if (crs != 0)
  205014. InternetReadFile (crs->request,
  205015. buffer, bytesToRead,
  205016. &bytesRead);
  205017. return bytesRead;
  205018. }
  205019. int juce_seekInInternetFile (void* handle, int newPosition)
  205020. {
  205021. if (handle != 0)
  205022. {
  205023. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  205024. return InternetSetFilePointer (crs->request, newPosition, 0, FILE_BEGIN, 0);
  205025. }
  205026. return -1;
  205027. }
  205028. int64 juce_getInternetFileContentLength (void* handle)
  205029. {
  205030. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  205031. if (crs != 0)
  205032. {
  205033. DWORD index = 0, result = 0, size = sizeof (result);
  205034. if (HttpQueryInfo (crs->request, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, &result, &size, &index))
  205035. return (int64) result;
  205036. }
  205037. return -1;
  205038. }
  205039. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers)
  205040. {
  205041. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  205042. if (crs != 0)
  205043. {
  205044. DWORD bufferSizeBytes = 4096;
  205045. for (;;)
  205046. {
  205047. HeapBlock<char> buffer ((size_t) bufferSizeBytes);
  205048. if (HttpQueryInfo (crs->request, HTTP_QUERY_RAW_HEADERS_CRLF, buffer.getData(), &bufferSizeBytes, 0))
  205049. {
  205050. StringArray headersArray;
  205051. headersArray.addLines (reinterpret_cast <const WCHAR*> (buffer.getData()));
  205052. for (int i = 0; i < headersArray.size(); ++i)
  205053. {
  205054. const String& header = headersArray[i];
  205055. const String key (header.upToFirstOccurrenceOf (": ", false, false));
  205056. const String value (header.fromFirstOccurrenceOf (": ", false, false));
  205057. const String previousValue (headers [key]);
  205058. headers.set (key, previousValue.isEmpty() ? value : (previousValue + "," + value));
  205059. }
  205060. break;
  205061. }
  205062. if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
  205063. break;
  205064. }
  205065. }
  205066. }
  205067. void juce_closeInternetFile (void* handle)
  205068. {
  205069. if (handle != 0)
  205070. {
  205071. ScopedPointer <ConnectionAndRequestStruct> crs (static_cast <ConnectionAndRequestStruct*> (handle));
  205072. InternetCloseHandle (crs->request);
  205073. InternetCloseHandle (crs->connection);
  205074. }
  205075. }
  205076. namespace MACAddressHelpers
  205077. {
  205078. void getViaGetAdaptersInfo (Array<MACAddress>& result)
  205079. {
  205080. DynamicLibraryLoader dll ("iphlpapi.dll");
  205081. DynamicLibraryImport (GetAdaptersInfo, getAdaptersInfo, DWORD, dll, (PIP_ADAPTER_INFO, PULONG))
  205082. if (getAdaptersInfo != 0)
  205083. {
  205084. ULONG len = sizeof (IP_ADAPTER_INFO);
  205085. MemoryBlock mb;
  205086. PIP_ADAPTER_INFO adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  205087. if (getAdaptersInfo (adapterInfo, &len) == ERROR_BUFFER_OVERFLOW)
  205088. {
  205089. mb.setSize (len);
  205090. adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  205091. }
  205092. if (getAdaptersInfo (adapterInfo, &len) == NO_ERROR)
  205093. {
  205094. for (PIP_ADAPTER_INFO adapter = adapterInfo; adapter != 0; adapter = adapter->Next)
  205095. {
  205096. if (adapter->AddressLength >= 6)
  205097. result.addIfNotAlreadyThere (MACAddress (adapter->Address));
  205098. }
  205099. }
  205100. }
  205101. }
  205102. void getViaNetBios (Array<MACAddress>& result)
  205103. {
  205104. DynamicLibraryLoader dll ("netapi32.dll");
  205105. DynamicLibraryImport (Netbios, NetbiosCall, UCHAR, dll, (PNCB))
  205106. if (NetbiosCall != 0)
  205107. {
  205108. NCB ncb;
  205109. zerostruct (ncb);
  205110. struct ASTAT
  205111. {
  205112. ADAPTER_STATUS adapt;
  205113. NAME_BUFFER NameBuff [30];
  205114. };
  205115. ASTAT astat;
  205116. zeromem (&astat, sizeof (astat)); // (can't use zerostruct here in VC6)
  205117. LANA_ENUM enums;
  205118. zerostruct (enums);
  205119. ncb.ncb_command = NCBENUM;
  205120. ncb.ncb_buffer = (unsigned char*) &enums;
  205121. ncb.ncb_length = sizeof (LANA_ENUM);
  205122. NetbiosCall (&ncb);
  205123. for (int i = 0; i < enums.length; ++i)
  205124. {
  205125. zerostruct (ncb);
  205126. ncb.ncb_command = NCBRESET;
  205127. ncb.ncb_lana_num = enums.lana[i];
  205128. if (NetbiosCall (&ncb) == 0)
  205129. {
  205130. zerostruct (ncb);
  205131. memcpy (ncb.ncb_callname, "* ", NCBNAMSZ);
  205132. ncb.ncb_command = NCBASTAT;
  205133. ncb.ncb_lana_num = enums.lana[i];
  205134. ncb.ncb_buffer = (unsigned char*) &astat;
  205135. ncb.ncb_length = sizeof (ASTAT);
  205136. if (NetbiosCall (&ncb) == 0 && astat.adapt.adapter_type == 0xfe)
  205137. result.addIfNotAlreadyThere (MACAddress (astat.adapt.adapter_address));
  205138. }
  205139. }
  205140. }
  205141. }
  205142. }
  205143. void MACAddress::findAllAddresses (Array<MACAddress>& result)
  205144. {
  205145. MACAddressHelpers::getViaGetAdaptersInfo (result);
  205146. MACAddressHelpers::getViaNetBios (result);
  205147. }
  205148. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  205149. const String& emailSubject,
  205150. const String& bodyText,
  205151. const StringArray& filesToAttach)
  205152. {
  205153. HMODULE h = LoadLibraryA ("MAPI32.dll");
  205154. typedef ULONG (WINAPI *MAPISendMailType) (LHANDLE, ULONG, lpMapiMessage, ::FLAGS, ULONG);
  205155. MAPISendMailType mapiSendMail = (MAPISendMailType) GetProcAddress (h, "MAPISendMail");
  205156. bool ok = false;
  205157. if (mapiSendMail != 0)
  205158. {
  205159. MapiMessage message;
  205160. zerostruct (message);
  205161. message.lpszSubject = (LPSTR) emailSubject.toCString();
  205162. message.lpszNoteText = (LPSTR) bodyText.toCString();
  205163. MapiRecipDesc recip;
  205164. zerostruct (recip);
  205165. recip.ulRecipClass = MAPI_TO;
  205166. String targetEmailAddress_ (targetEmailAddress);
  205167. if (targetEmailAddress_.isEmpty())
  205168. targetEmailAddress_ = " "; // (Windows Mail can't deal with a blank address)
  205169. recip.lpszName = (LPSTR) targetEmailAddress_.toCString();
  205170. message.nRecipCount = 1;
  205171. message.lpRecips = &recip;
  205172. HeapBlock <MapiFileDesc> files;
  205173. files.calloc (filesToAttach.size());
  205174. message.nFileCount = filesToAttach.size();
  205175. message.lpFiles = files;
  205176. for (int i = 0; i < filesToAttach.size(); ++i)
  205177. {
  205178. files[i].nPosition = (ULONG) -1;
  205179. files[i].lpszPathName = (LPSTR) filesToAttach[i].toCString();
  205180. }
  205181. ok = (mapiSendMail (0, 0, &message, MAPI_DIALOG | MAPI_LOGON_UI, 0) == SUCCESS_SUCCESS);
  205182. }
  205183. FreeLibrary (h);
  205184. return ok;
  205185. }
  205186. #endif
  205187. /*** End of inlined file: juce_win32_Network.cpp ***/
  205188. /*** Start of inlined file: juce_win32_PlatformUtils.cpp ***/
  205189. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205190. // compiled on its own).
  205191. #if JUCE_INCLUDED_FILE
  205192. namespace
  205193. {
  205194. HKEY findKeyForPath (String name, const bool createForWriting, String& valueName)
  205195. {
  205196. HKEY rootKey = 0;
  205197. if (name.startsWithIgnoreCase ("HKEY_CURRENT_USER\\"))
  205198. rootKey = HKEY_CURRENT_USER;
  205199. else if (name.startsWithIgnoreCase ("HKEY_LOCAL_MACHINE\\"))
  205200. rootKey = HKEY_LOCAL_MACHINE;
  205201. else if (name.startsWithIgnoreCase ("HKEY_CLASSES_ROOT\\"))
  205202. rootKey = HKEY_CLASSES_ROOT;
  205203. if (rootKey != 0)
  205204. {
  205205. name = name.substring (name.indexOfChar ('\\') + 1);
  205206. const int lastSlash = name.lastIndexOfChar ('\\');
  205207. valueName = name.substring (lastSlash + 1);
  205208. name = name.substring (0, lastSlash);
  205209. HKEY key;
  205210. DWORD result;
  205211. if (createForWriting)
  205212. {
  205213. if (RegCreateKeyEx (rootKey, name, 0, 0, REG_OPTION_NON_VOLATILE,
  205214. (KEY_WRITE | KEY_QUERY_VALUE), 0, &key, &result) == ERROR_SUCCESS)
  205215. return key;
  205216. }
  205217. else
  205218. {
  205219. if (RegOpenKeyEx (rootKey, name, 0, KEY_READ, &key) == ERROR_SUCCESS)
  205220. return key;
  205221. }
  205222. }
  205223. return 0;
  205224. }
  205225. }
  205226. const String PlatformUtilities::getRegistryValue (const String& regValuePath,
  205227. const String& defaultValue)
  205228. {
  205229. String valueName, result (defaultValue);
  205230. HKEY k = findKeyForPath (regValuePath, false, valueName);
  205231. if (k != 0)
  205232. {
  205233. WCHAR buffer [2048];
  205234. unsigned long bufferSize = sizeof (buffer);
  205235. DWORD type = REG_SZ;
  205236. if (RegQueryValueEx (k, valueName, 0, &type, (LPBYTE) buffer, &bufferSize) == ERROR_SUCCESS)
  205237. {
  205238. if (type == REG_SZ)
  205239. result = buffer;
  205240. else if (type == REG_DWORD)
  205241. result = String ((int) *(DWORD*) buffer);
  205242. }
  205243. RegCloseKey (k);
  205244. }
  205245. return result;
  205246. }
  205247. void PlatformUtilities::setRegistryValue (const String& regValuePath,
  205248. const String& value)
  205249. {
  205250. String valueName;
  205251. HKEY k = findKeyForPath (regValuePath, true, valueName);
  205252. if (k != 0)
  205253. {
  205254. RegSetValueEx (k, valueName, 0, REG_SZ,
  205255. (const BYTE*) (const WCHAR*) value,
  205256. sizeof (WCHAR) * (value.length() + 1));
  205257. RegCloseKey (k);
  205258. }
  205259. }
  205260. bool PlatformUtilities::registryValueExists (const String& regValuePath)
  205261. {
  205262. bool exists = false;
  205263. String valueName;
  205264. HKEY k = findKeyForPath (regValuePath, false, valueName);
  205265. if (k != 0)
  205266. {
  205267. unsigned char buffer [2048];
  205268. unsigned long bufferSize = sizeof (buffer);
  205269. DWORD type = 0;
  205270. if (RegQueryValueEx (k, valueName, 0, &type, buffer, &bufferSize) == ERROR_SUCCESS)
  205271. exists = true;
  205272. RegCloseKey (k);
  205273. }
  205274. return exists;
  205275. }
  205276. void PlatformUtilities::deleteRegistryValue (const String& regValuePath)
  205277. {
  205278. String valueName;
  205279. HKEY k = findKeyForPath (regValuePath, true, valueName);
  205280. if (k != 0)
  205281. {
  205282. RegDeleteValue (k, valueName);
  205283. RegCloseKey (k);
  205284. }
  205285. }
  205286. void PlatformUtilities::deleteRegistryKey (const String& regKeyPath)
  205287. {
  205288. String valueName;
  205289. HKEY k = findKeyForPath (regKeyPath, true, valueName);
  205290. if (k != 0)
  205291. {
  205292. RegDeleteKey (k, valueName);
  205293. RegCloseKey (k);
  205294. }
  205295. }
  205296. void PlatformUtilities::registerFileAssociation (const String& fileExtension,
  205297. const String& symbolicDescription,
  205298. const String& fullDescription,
  205299. const File& targetExecutable,
  205300. int iconResourceNumber)
  205301. {
  205302. setRegistryValue ("HKEY_CLASSES_ROOT\\" + fileExtension + "\\", symbolicDescription);
  205303. const String key ("HKEY_CLASSES_ROOT\\" + symbolicDescription);
  205304. if (iconResourceNumber != 0)
  205305. setRegistryValue (key + "\\DefaultIcon\\",
  205306. targetExecutable.getFullPathName() + "," + String (-iconResourceNumber));
  205307. setRegistryValue (key + "\\", fullDescription);
  205308. setRegistryValue (key + "\\shell\\open\\command\\",
  205309. targetExecutable.getFullPathName() + " %1");
  205310. }
  205311. bool juce_IsRunningInWine()
  205312. {
  205313. HKEY key;
  205314. if (RegOpenKeyEx (HKEY_CURRENT_USER, _T("Software\\Wine"), 0, KEY_READ, &key) == ERROR_SUCCESS)
  205315. {
  205316. RegCloseKey (key);
  205317. return true;
  205318. }
  205319. return false;
  205320. }
  205321. const String JUCE_CALLTYPE PlatformUtilities::getCurrentCommandLineParams()
  205322. {
  205323. String s (::GetCommandLineW());
  205324. StringArray tokens;
  205325. tokens.addTokens (s, true); // tokenise so that we can remove the initial filename argument
  205326. return tokens.joinIntoString (" ", 1);
  205327. }
  205328. static void* currentModuleHandle = 0;
  205329. void* PlatformUtilities::getCurrentModuleInstanceHandle() throw()
  205330. {
  205331. if (currentModuleHandle == 0)
  205332. currentModuleHandle = GetModuleHandle (0);
  205333. return currentModuleHandle;
  205334. }
  205335. void PlatformUtilities::setCurrentModuleInstanceHandle (void* const newHandle) throw()
  205336. {
  205337. currentModuleHandle = newHandle;
  205338. }
  205339. void PlatformUtilities::fpuReset()
  205340. {
  205341. #if JUCE_MSVC
  205342. _clearfp();
  205343. #endif
  205344. }
  205345. void PlatformUtilities::beep()
  205346. {
  205347. MessageBeep (MB_OK);
  205348. }
  205349. #endif
  205350. /*** End of inlined file: juce_win32_PlatformUtils.cpp ***/
  205351. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  205352. /*** Start of inlined file: juce_win32_Messaging.cpp ***/
  205353. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205354. // compiled on its own).
  205355. #if JUCE_INCLUDED_FILE
  205356. static const unsigned int specialId = WM_APP + 0x4400;
  205357. static const unsigned int broadcastId = WM_APP + 0x4403;
  205358. static const unsigned int specialCallbackId = WM_APP + 0x4402;
  205359. static const TCHAR* const messageWindowName = _T("JUCEWindow");
  205360. HWND juce_messageWindowHandle = 0;
  205361. extern long improbableWindowNumber; // defined in windowing.cpp
  205362. #ifndef WM_APPCOMMAND
  205363. #define WM_APPCOMMAND 0x0319
  205364. #endif
  205365. static LRESULT CALLBACK juce_MessageWndProc (HWND h,
  205366. const UINT message,
  205367. const WPARAM wParam,
  205368. const LPARAM lParam) throw()
  205369. {
  205370. JUCE_TRY
  205371. {
  205372. if (h == juce_messageWindowHandle)
  205373. {
  205374. if (message == specialCallbackId)
  205375. {
  205376. MessageCallbackFunction* const func = (MessageCallbackFunction*) wParam;
  205377. return (LRESULT) (*func) ((void*) lParam);
  205378. }
  205379. else if (message == specialId)
  205380. {
  205381. // these are trapped early in the dispatch call, but must also be checked
  205382. // here in case there are windows modal dialog boxes doing their own
  205383. // dispatch loop and not calling our version
  205384. MessageManager::getInstance()->deliverMessage ((Message*) lParam);
  205385. return 0;
  205386. }
  205387. else if (message == broadcastId)
  205388. {
  205389. const ScopedPointer <String> messageString ((String*) lParam);
  205390. MessageManager::getInstance()->deliverBroadcastMessage (*messageString);
  205391. return 0;
  205392. }
  205393. else if (message == WM_COPYDATA && ((const COPYDATASTRUCT*) lParam)->dwData == broadcastId)
  205394. {
  205395. const String messageString ((const juce_wchar*) ((const COPYDATASTRUCT*) lParam)->lpData,
  205396. ((const COPYDATASTRUCT*) lParam)->cbData / sizeof (juce_wchar));
  205397. PostMessage (juce_messageWindowHandle, broadcastId, 0, (LPARAM) new String (messageString));
  205398. return 0;
  205399. }
  205400. }
  205401. }
  205402. JUCE_CATCH_EXCEPTION
  205403. return DefWindowProc (h, message, wParam, lParam);
  205404. }
  205405. static bool isEventBlockedByModalComps (MSG& m)
  205406. {
  205407. if (Component::getNumCurrentlyModalComponents() == 0
  205408. || GetWindowLong (m.hwnd, GWLP_USERDATA) == improbableWindowNumber)
  205409. return false;
  205410. switch (m.message)
  205411. {
  205412. case WM_MOUSEMOVE:
  205413. case WM_NCMOUSEMOVE:
  205414. case 0x020A: /* WM_MOUSEWHEEL */
  205415. case 0x020E: /* WM_MOUSEHWHEEL */
  205416. case WM_KEYUP:
  205417. case WM_SYSKEYUP:
  205418. case WM_CHAR:
  205419. case WM_APPCOMMAND:
  205420. case WM_LBUTTONUP:
  205421. case WM_MBUTTONUP:
  205422. case WM_RBUTTONUP:
  205423. case WM_MOUSEACTIVATE:
  205424. case WM_NCMOUSEHOVER:
  205425. case WM_MOUSEHOVER:
  205426. return true;
  205427. case WM_NCLBUTTONDOWN:
  205428. case WM_NCLBUTTONDBLCLK:
  205429. case WM_NCRBUTTONDOWN:
  205430. case WM_NCRBUTTONDBLCLK:
  205431. case WM_NCMBUTTONDOWN:
  205432. case WM_NCMBUTTONDBLCLK:
  205433. case WM_LBUTTONDOWN:
  205434. case WM_LBUTTONDBLCLK:
  205435. case WM_MBUTTONDOWN:
  205436. case WM_MBUTTONDBLCLK:
  205437. case WM_RBUTTONDOWN:
  205438. case WM_RBUTTONDBLCLK:
  205439. case WM_KEYDOWN:
  205440. case WM_SYSKEYDOWN:
  205441. {
  205442. Component* const modal = Component::getCurrentlyModalComponent (0);
  205443. if (modal != 0)
  205444. modal->inputAttemptWhenModal();
  205445. return true;
  205446. }
  205447. default:
  205448. break;
  205449. }
  205450. return false;
  205451. }
  205452. bool juce_dispatchNextMessageOnSystemQueue (const bool returnIfNoPendingMessages)
  205453. {
  205454. MSG m;
  205455. if (returnIfNoPendingMessages && ! PeekMessage (&m, (HWND) 0, 0, 0, 0))
  205456. return false;
  205457. if (GetMessage (&m, (HWND) 0, 0, 0) >= 0)
  205458. {
  205459. if (m.message == specialId && m.hwnd == juce_messageWindowHandle)
  205460. {
  205461. MessageManager::getInstance()->deliverMessage ((Message*) (void*) m.lParam);
  205462. }
  205463. else if (m.message == WM_QUIT)
  205464. {
  205465. if (JUCEApplication::getInstance() != 0)
  205466. JUCEApplication::getInstance()->systemRequestedQuit();
  205467. }
  205468. else if (! isEventBlockedByModalComps (m))
  205469. {
  205470. if ((m.message == WM_LBUTTONDOWN || m.message == WM_RBUTTONDOWN)
  205471. && GetWindowLong (m.hwnd, GWLP_USERDATA) != improbableWindowNumber)
  205472. {
  205473. // if it's someone else's window being clicked on, and the focus is
  205474. // currently on a juce window, pass the kb focus over..
  205475. HWND currentFocus = GetFocus();
  205476. if (currentFocus == 0 || GetWindowLong (currentFocus, GWLP_USERDATA) == improbableWindowNumber)
  205477. SetFocus (m.hwnd);
  205478. }
  205479. TranslateMessage (&m);
  205480. DispatchMessage (&m);
  205481. }
  205482. }
  205483. return true;
  205484. }
  205485. bool juce_postMessageToSystemQueue (Message* message)
  205486. {
  205487. return PostMessage (juce_messageWindowHandle, specialId, 0, (LPARAM) message) != 0;
  205488. }
  205489. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  205490. void* userData)
  205491. {
  205492. if (MessageManager::getInstance()->isThisTheMessageThread())
  205493. {
  205494. return (*callback) (userData);
  205495. }
  205496. else
  205497. {
  205498. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  205499. // deadlock because the message manager is blocked from running, and can't
  205500. // call your function..
  205501. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  205502. return (void*) SendMessage (juce_messageWindowHandle,
  205503. specialCallbackId,
  205504. (WPARAM) callback,
  205505. (LPARAM) userData);
  205506. }
  205507. }
  205508. static BOOL CALLBACK BroadcastEnumWindowProc (HWND hwnd, LPARAM lParam)
  205509. {
  205510. if (hwnd != juce_messageWindowHandle)
  205511. reinterpret_cast <Array<void*>*> (lParam)->add ((void*) hwnd);
  205512. return TRUE;
  205513. }
  205514. void MessageManager::broadcastMessage (const String& value)
  205515. {
  205516. Array<void*> windows;
  205517. EnumWindows (&BroadcastEnumWindowProc, (LPARAM) &windows);
  205518. const String localCopy (value);
  205519. COPYDATASTRUCT data;
  205520. data.dwData = broadcastId;
  205521. data.cbData = (localCopy.length() + 1) * sizeof (juce_wchar);
  205522. data.lpData = (void*) static_cast <const juce_wchar*> (localCopy);
  205523. for (int i = windows.size(); --i >= 0;)
  205524. {
  205525. HWND hwnd = (HWND) windows.getUnchecked(i);
  205526. TCHAR windowName [64]; // no need to read longer strings than this
  205527. GetWindowText (hwnd, windowName, 64);
  205528. windowName [63] = 0;
  205529. if (String (windowName) == messageWindowName)
  205530. {
  205531. DWORD_PTR result;
  205532. SendMessageTimeout (hwnd, WM_COPYDATA,
  205533. (WPARAM) juce_messageWindowHandle,
  205534. (LPARAM) &data,
  205535. SMTO_BLOCK | SMTO_ABORTIFHUNG,
  205536. 8000,
  205537. &result);
  205538. }
  205539. }
  205540. }
  205541. static const String getMessageWindowClassName()
  205542. {
  205543. // this name has to be different for each app/dll instance because otherwise
  205544. // poor old Win32 can get a bit confused (even despite it not being a process-global
  205545. // window class).
  205546. static int number = 0;
  205547. if (number == 0)
  205548. number = 0x7fffffff & (int) Time::getHighResolutionTicks();
  205549. return "JUCEcs_" + String (number);
  205550. }
  205551. void MessageManager::doPlatformSpecificInitialisation()
  205552. {
  205553. OleInitialize (0);
  205554. const String className (getMessageWindowClassName());
  205555. HMODULE hmod = (HMODULE) PlatformUtilities::getCurrentModuleInstanceHandle();
  205556. WNDCLASSEX wc;
  205557. zerostruct (wc);
  205558. wc.cbSize = sizeof (wc);
  205559. wc.lpfnWndProc = (WNDPROC) juce_MessageWndProc;
  205560. wc.cbWndExtra = 4;
  205561. wc.hInstance = hmod;
  205562. wc.lpszClassName = className;
  205563. RegisterClassEx (&wc);
  205564. juce_messageWindowHandle = CreateWindow (wc.lpszClassName,
  205565. messageWindowName,
  205566. 0, 0, 0, 0, 0, 0, 0,
  205567. hmod, 0);
  205568. }
  205569. void MessageManager::doPlatformSpecificShutdown()
  205570. {
  205571. DestroyWindow (juce_messageWindowHandle);
  205572. UnregisterClass (getMessageWindowClassName(), 0);
  205573. OleUninitialize();
  205574. }
  205575. #endif
  205576. /*** End of inlined file: juce_win32_Messaging.cpp ***/
  205577. /*** Start of inlined file: juce_win32_Fonts.cpp ***/
  205578. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205579. // compiled on its own).
  205580. #if JUCE_INCLUDED_FILE
  205581. static int CALLBACK wfontEnum2 (ENUMLOGFONTEXW* lpelfe,
  205582. NEWTEXTMETRICEXW*,
  205583. int type,
  205584. LPARAM lParam)
  205585. {
  205586. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  205587. {
  205588. const String fontName (lpelfe->elfLogFont.lfFaceName);
  205589. ((StringArray*) lParam)->addIfNotAlreadyThere (fontName.removeCharacters ("@"));
  205590. }
  205591. return 1;
  205592. }
  205593. static int CALLBACK wfontEnum1 (ENUMLOGFONTEXW* lpelfe,
  205594. NEWTEXTMETRICEXW*,
  205595. int type,
  205596. LPARAM lParam)
  205597. {
  205598. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  205599. {
  205600. LOGFONTW lf;
  205601. zerostruct (lf);
  205602. lf.lfWeight = FW_DONTCARE;
  205603. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  205604. lf.lfQuality = DEFAULT_QUALITY;
  205605. lf.lfCharSet = DEFAULT_CHARSET;
  205606. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  205607. lf.lfPitchAndFamily = FF_DONTCARE;
  205608. const String fontName (lpelfe->elfLogFont.lfFaceName);
  205609. fontName.copyToUnicode (lf.lfFaceName, LF_FACESIZE - 1);
  205610. HDC dc = CreateCompatibleDC (0);
  205611. EnumFontFamiliesEx (dc, &lf,
  205612. (FONTENUMPROCW) &wfontEnum2,
  205613. lParam, 0);
  205614. DeleteDC (dc);
  205615. }
  205616. return 1;
  205617. }
  205618. const StringArray Font::findAllTypefaceNames()
  205619. {
  205620. StringArray results;
  205621. HDC dc = CreateCompatibleDC (0);
  205622. {
  205623. LOGFONTW lf;
  205624. zerostruct (lf);
  205625. lf.lfWeight = FW_DONTCARE;
  205626. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  205627. lf.lfQuality = DEFAULT_QUALITY;
  205628. lf.lfCharSet = DEFAULT_CHARSET;
  205629. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  205630. lf.lfPitchAndFamily = FF_DONTCARE;
  205631. lf.lfFaceName[0] = 0;
  205632. EnumFontFamiliesEx (dc, &lf,
  205633. (FONTENUMPROCW) &wfontEnum1,
  205634. (LPARAM) &results, 0);
  205635. }
  205636. DeleteDC (dc);
  205637. results.sort (true);
  205638. return results;
  205639. }
  205640. extern bool juce_IsRunningInWine();
  205641. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  205642. {
  205643. if (juce_IsRunningInWine())
  205644. {
  205645. // If we're running in Wine, then use fonts that might be available on Linux..
  205646. defaultSans = "Bitstream Vera Sans";
  205647. defaultSerif = "Bitstream Vera Serif";
  205648. defaultFixed = "Bitstream Vera Sans Mono";
  205649. }
  205650. else
  205651. {
  205652. defaultSans = "Verdana";
  205653. defaultSerif = "Times";
  205654. defaultFixed = "Lucida Console";
  205655. }
  205656. }
  205657. class FontDCHolder : private DeletedAtShutdown
  205658. {
  205659. public:
  205660. FontDCHolder()
  205661. : dc (0), numKPs (0), size (0),
  205662. bold (false), italic (false)
  205663. {
  205664. }
  205665. ~FontDCHolder()
  205666. {
  205667. if (dc != 0)
  205668. {
  205669. DeleteDC (dc);
  205670. DeleteObject (fontH);
  205671. }
  205672. clearSingletonInstance();
  205673. }
  205674. juce_DeclareSingleton_SingleThreaded_Minimal (FontDCHolder);
  205675. HDC loadFont (const String& fontName_, const bool bold_, const bool italic_, const int size_)
  205676. {
  205677. if (fontName != fontName_ || bold != bold_ || italic != italic_ || size != size_)
  205678. {
  205679. fontName = fontName_;
  205680. bold = bold_;
  205681. italic = italic_;
  205682. size = size_;
  205683. if (dc != 0)
  205684. {
  205685. DeleteDC (dc);
  205686. DeleteObject (fontH);
  205687. kps.free();
  205688. }
  205689. fontH = 0;
  205690. dc = CreateCompatibleDC (0);
  205691. SetMapperFlags (dc, 0);
  205692. SetMapMode (dc, MM_TEXT);
  205693. LOGFONTW lfw;
  205694. zerostruct (lfw);
  205695. lfw.lfCharSet = DEFAULT_CHARSET;
  205696. lfw.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  205697. lfw.lfOutPrecision = OUT_OUTLINE_PRECIS;
  205698. lfw.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
  205699. lfw.lfQuality = PROOF_QUALITY;
  205700. lfw.lfItalic = (BYTE) (italic ? TRUE : FALSE);
  205701. lfw.lfWeight = bold ? FW_BOLD : FW_NORMAL;
  205702. fontName.copyToUnicode (lfw.lfFaceName, LF_FACESIZE - 1);
  205703. lfw.lfHeight = size > 0 ? size : -256;
  205704. HFONT standardSizedFont = CreateFontIndirect (&lfw);
  205705. if (standardSizedFont != 0)
  205706. {
  205707. if (SelectObject (dc, standardSizedFont) != 0)
  205708. {
  205709. fontH = standardSizedFont;
  205710. if (size == 0)
  205711. {
  205712. OUTLINETEXTMETRIC otm;
  205713. if (GetOutlineTextMetrics (dc, sizeof (otm), &otm) != 0)
  205714. {
  205715. lfw.lfHeight = -(int) otm.otmEMSquare;
  205716. fontH = CreateFontIndirect (&lfw);
  205717. SelectObject (dc, fontH);
  205718. DeleteObject (standardSizedFont);
  205719. }
  205720. }
  205721. }
  205722. else
  205723. {
  205724. jassertfalse;
  205725. }
  205726. }
  205727. else
  205728. {
  205729. jassertfalse;
  205730. }
  205731. }
  205732. return dc;
  205733. }
  205734. KERNINGPAIR* getKerningPairs (int& numKPs_)
  205735. {
  205736. if (kps == 0)
  205737. {
  205738. numKPs = GetKerningPairs (dc, 0, 0);
  205739. kps.calloc (numKPs);
  205740. GetKerningPairs (dc, numKPs, kps);
  205741. }
  205742. numKPs_ = numKPs;
  205743. return kps;
  205744. }
  205745. private:
  205746. HFONT fontH;
  205747. HDC dc;
  205748. String fontName;
  205749. HeapBlock <KERNINGPAIR> kps;
  205750. int numKPs, size;
  205751. bool bold, italic;
  205752. FontDCHolder (const FontDCHolder&);
  205753. FontDCHolder& operator= (const FontDCHolder&);
  205754. };
  205755. juce_ImplementSingleton_SingleThreaded (FontDCHolder);
  205756. class WindowsTypeface : public CustomTypeface
  205757. {
  205758. public:
  205759. WindowsTypeface (const Font& font)
  205760. {
  205761. HDC dc = FontDCHolder::getInstance()->loadFont (font.getTypefaceName(),
  205762. font.isBold(), font.isItalic(), 0);
  205763. TEXTMETRIC tm;
  205764. tm.tmAscent = tm.tmHeight = 1;
  205765. tm.tmDefaultChar = 0;
  205766. GetTextMetrics (dc, &tm);
  205767. setCharacteristics (font.getTypefaceName(),
  205768. tm.tmAscent / (float) tm.tmHeight,
  205769. font.isBold(), font.isItalic(),
  205770. tm.tmDefaultChar);
  205771. }
  205772. bool loadGlyphIfPossible (juce_wchar character)
  205773. {
  205774. HDC dc = FontDCHolder::getInstance()->loadFont (name, isBold, isItalic, 0);
  205775. GLYPHMETRICS gm;
  205776. {
  205777. const WCHAR charToTest[] = { (WCHAR) character, 0 };
  205778. WORD index = 0;
  205779. if (GetGlyphIndices (dc, charToTest, 1, &index, GGI_MARK_NONEXISTING_GLYPHS) != GDI_ERROR
  205780. && index == 0xffff)
  205781. {
  205782. return false;
  205783. }
  205784. }
  205785. Path glyphPath;
  205786. TEXTMETRIC tm;
  205787. if (! GetTextMetrics (dc, &tm))
  205788. {
  205789. addGlyph (character, glyphPath, 0);
  205790. return true;
  205791. }
  205792. const float height = (float) tm.tmHeight;
  205793. static const MAT2 identityMatrix = { { 0, 1 }, { 0, 0 }, { 0, 0 }, { 0, 1 } };
  205794. const int bufSize = GetGlyphOutline (dc, character, GGO_NATIVE,
  205795. &gm, 0, 0, &identityMatrix);
  205796. if (bufSize > 0)
  205797. {
  205798. HeapBlock<char> data (bufSize);
  205799. GetGlyphOutline (dc, character, GGO_NATIVE, &gm,
  205800. bufSize, data, &identityMatrix);
  205801. const TTPOLYGONHEADER* pheader = reinterpret_cast<TTPOLYGONHEADER*> (data.getData());
  205802. const float scaleX = 1.0f / height;
  205803. const float scaleY = -1.0f / height;
  205804. while ((char*) pheader < data + bufSize)
  205805. {
  205806. float x = scaleX * pheader->pfxStart.x.value;
  205807. float y = scaleY * pheader->pfxStart.y.value;
  205808. glyphPath.startNewSubPath (x, y);
  205809. const TTPOLYCURVE* curve = (const TTPOLYCURVE*) ((const char*) pheader + sizeof (TTPOLYGONHEADER));
  205810. const char* const curveEnd = ((const char*) pheader) + pheader->cb;
  205811. while ((const char*) curve < curveEnd)
  205812. {
  205813. if (curve->wType == TT_PRIM_LINE)
  205814. {
  205815. for (int i = 0; i < curve->cpfx; ++i)
  205816. {
  205817. x = scaleX * curve->apfx[i].x.value;
  205818. y = scaleY * curve->apfx[i].y.value;
  205819. glyphPath.lineTo (x, y);
  205820. }
  205821. }
  205822. else if (curve->wType == TT_PRIM_QSPLINE)
  205823. {
  205824. for (int i = 0; i < curve->cpfx - 1; ++i)
  205825. {
  205826. const float x2 = scaleX * curve->apfx[i].x.value;
  205827. const float y2 = scaleY * curve->apfx[i].y.value;
  205828. float x3, y3;
  205829. if (i < curve->cpfx - 2)
  205830. {
  205831. x3 = 0.5f * (x2 + scaleX * curve->apfx[i + 1].x.value);
  205832. y3 = 0.5f * (y2 + scaleY * curve->apfx[i + 1].y.value);
  205833. }
  205834. else
  205835. {
  205836. x3 = scaleX * curve->apfx[i + 1].x.value;
  205837. y3 = scaleY * curve->apfx[i + 1].y.value;
  205838. }
  205839. glyphPath.quadraticTo (x2, y2, x3, y3);
  205840. x = x3;
  205841. y = y3;
  205842. }
  205843. }
  205844. curve = (const TTPOLYCURVE*) &(curve->apfx [curve->cpfx]);
  205845. }
  205846. pheader = (const TTPOLYGONHEADER*) curve;
  205847. glyphPath.closeSubPath();
  205848. }
  205849. }
  205850. addGlyph (character, glyphPath, gm.gmCellIncX / height);
  205851. int numKPs;
  205852. const KERNINGPAIR* const kps = FontDCHolder::getInstance()->getKerningPairs (numKPs);
  205853. for (int i = 0; i < numKPs; ++i)
  205854. {
  205855. if (kps[i].wFirst == character)
  205856. addKerningPair (kps[i].wFirst, kps[i].wSecond,
  205857. kps[i].iKernAmount / height);
  205858. }
  205859. return true;
  205860. }
  205861. juce_UseDebuggingNewOperator
  205862. };
  205863. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  205864. {
  205865. return new WindowsTypeface (font);
  205866. }
  205867. #endif
  205868. /*** End of inlined file: juce_win32_Fonts.cpp ***/
  205869. /*** Start of inlined file: juce_win32_Direct2DGraphicsContext.cpp ***/
  205870. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205871. // compiled on its own).
  205872. #if JUCE_INCLUDED_FILE && JUCE_DIRECT2D
  205873. class SharedD2DFactory : public DeletedAtShutdown
  205874. {
  205875. public:
  205876. SharedD2DFactory()
  205877. {
  205878. D2D1CreateFactory (D2D1_FACTORY_TYPE_SINGLE_THREADED, &d2dFactory);
  205879. DWriteCreateFactory (DWRITE_FACTORY_TYPE_SHARED, __uuidof (IDWriteFactory), (IUnknown**) &directWriteFactory);
  205880. if (directWriteFactory != 0)
  205881. directWriteFactory->GetSystemFontCollection (&systemFonts);
  205882. }
  205883. ~SharedD2DFactory()
  205884. {
  205885. clearSingletonInstance();
  205886. }
  205887. juce_DeclareSingleton (SharedD2DFactory, false);
  205888. ComSmartPtr <ID2D1Factory> d2dFactory;
  205889. ComSmartPtr <IDWriteFactory> directWriteFactory;
  205890. ComSmartPtr <IDWriteFontCollection> systemFonts;
  205891. };
  205892. juce_ImplementSingleton (SharedD2DFactory)
  205893. class Direct2DLowLevelGraphicsContext : public LowLevelGraphicsContext
  205894. {
  205895. public:
  205896. Direct2DLowLevelGraphicsContext (HWND hwnd_)
  205897. : hwnd (hwnd_),
  205898. currentState (0)
  205899. {
  205900. RECT windowRect;
  205901. GetClientRect (hwnd, &windowRect);
  205902. D2D1_SIZE_U size = { windowRect.right - windowRect.left, windowRect.bottom - windowRect.top };
  205903. bounds.setSize (size.width, size.height);
  205904. D2D1_RENDER_TARGET_PROPERTIES props = D2D1::RenderTargetProperties();
  205905. D2D1_HWND_RENDER_TARGET_PROPERTIES propsHwnd = D2D1::HwndRenderTargetProperties (hwnd, size);
  205906. HRESULT hr = SharedD2DFactory::getInstance()->d2dFactory->CreateHwndRenderTarget (props, propsHwnd, &renderingTarget);
  205907. // xxx check for error
  205908. hr = renderingTarget->CreateSolidColorBrush (D2D1::ColorF::ColorF (0.0f, 0.0f, 0.0f, 1.0f), &colourBrush);
  205909. }
  205910. ~Direct2DLowLevelGraphicsContext()
  205911. {
  205912. states.clear();
  205913. }
  205914. void resized()
  205915. {
  205916. RECT windowRect;
  205917. GetClientRect (hwnd, &windowRect);
  205918. D2D1_SIZE_U size = { windowRect.right - windowRect.left, windowRect.bottom - windowRect.top };
  205919. renderingTarget->Resize (size);
  205920. bounds.setSize (size.width, size.height);
  205921. }
  205922. void clear()
  205923. {
  205924. renderingTarget->Clear (D2D1::ColorF (D2D1::ColorF::White, 0.0f)); // xxx why white and not black?
  205925. }
  205926. void start()
  205927. {
  205928. renderingTarget->BeginDraw();
  205929. saveState();
  205930. }
  205931. void end()
  205932. {
  205933. states.clear();
  205934. currentState = 0;
  205935. renderingTarget->EndDraw();
  205936. renderingTarget->CheckWindowState();
  205937. }
  205938. bool isVectorDevice() const { return false; }
  205939. void setOrigin (int x, int y)
  205940. {
  205941. currentState->origin.addXY (x, y);
  205942. }
  205943. bool clipToRectangle (const Rectangle<int>& r)
  205944. {
  205945. currentState->clipToRectangle (r);
  205946. return ! isClipEmpty();
  205947. }
  205948. bool clipToRectangleList (const RectangleList& clipRegion)
  205949. {
  205950. currentState->clipToRectList (rectListToPathGeometry (clipRegion));
  205951. return ! isClipEmpty();
  205952. }
  205953. void excludeClipRectangle (const Rectangle<int>&)
  205954. {
  205955. //xxx
  205956. }
  205957. void clipToPath (const Path& path, const AffineTransform& transform)
  205958. {
  205959. currentState->clipToPath (pathToPathGeometry (path, transform, currentState->origin));
  205960. }
  205961. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  205962. {
  205963. currentState->clipToImage (sourceImage,transform);
  205964. }
  205965. bool clipRegionIntersects (const Rectangle<int>& r)
  205966. {
  205967. const Rectangle<int> r2 (r + currentState->origin);
  205968. return currentState->clipRect.intersects (r2);
  205969. }
  205970. const Rectangle<int> getClipBounds() const
  205971. {
  205972. // xxx could this take into account complex clip regions?
  205973. return currentState->clipRect - currentState->origin;
  205974. }
  205975. bool isClipEmpty() const
  205976. {
  205977. return currentState->clipRect.isEmpty();
  205978. }
  205979. void saveState()
  205980. {
  205981. states.add (new SavedState (*this));
  205982. currentState = states.getLast();
  205983. }
  205984. void restoreState()
  205985. {
  205986. jassert (states.size() > 1) //you should never pop the last state!
  205987. states.removeLast (1);
  205988. currentState = states.getLast();
  205989. }
  205990. void setFill (const FillType& fillType)
  205991. {
  205992. currentState->setFill (fillType);
  205993. }
  205994. void setOpacity (float newOpacity)
  205995. {
  205996. currentState->setOpacity (newOpacity);
  205997. }
  205998. void setInterpolationQuality (Graphics::ResamplingQuality /*quality*/)
  205999. {
  206000. }
  206001. void fillRect (const Rectangle<int>& r, bool replaceExistingContents)
  206002. {
  206003. currentState->createBrush();
  206004. renderingTarget->FillRectangle (rectangleToRectF (r + currentState->origin), currentState->currentBrush);
  206005. }
  206006. void fillPath (const Path& p, const AffineTransform& transform)
  206007. {
  206008. currentState->createBrush();
  206009. ComSmartPtr <ID2D1Geometry> geometry (pathToPathGeometry (p, transform, currentState->origin));
  206010. if (renderingTarget != 0)
  206011. renderingTarget->FillGeometry (geometry, currentState->currentBrush);
  206012. }
  206013. void drawImage (const Image& image, const AffineTransform& transform, bool fillEntireClipAsTiles)
  206014. {
  206015. const int x = currentState->origin.getX();
  206016. const int y = currentState->origin.getY();
  206017. renderingTarget->SetTransform (transfromToMatrix (transform) * D2D1::Matrix3x2F::Translation (x, y));
  206018. D2D1_SIZE_U size;
  206019. size.width = image.getWidth();
  206020. size.height = image.getHeight();
  206021. D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();
  206022. Image img (image.convertedToFormat (Image::ARGB));
  206023. Image::BitmapData bd (img, false);
  206024. bp.pixelFormat = renderingTarget->GetPixelFormat();
  206025. bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
  206026. {
  206027. ComSmartPtr <ID2D1Bitmap> tempBitmap;
  206028. renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, &tempBitmap);
  206029. if (tempBitmap != 0)
  206030. renderingTarget->DrawBitmap (tempBitmap);
  206031. }
  206032. renderingTarget->SetTransform (D2D1::IdentityMatrix());
  206033. }
  206034. void drawLine (const Line <float>& line)
  206035. {
  206036. // xxx doesn't seem to be correctly aligned, may need nudging by 0.5 to match the software renderer's behaviour
  206037. const Line<float> l (line.getStart() + currentState->origin.toFloat(),
  206038. line.getEnd() + currentState->origin.toFloat());
  206039. currentState->createBrush();
  206040. renderingTarget->DrawLine (D2D1::Point2F (l.getStartX(), l.getStartY()),
  206041. D2D1::Point2F (l.getEndX(), l.getEndY()),
  206042. currentState->currentBrush);
  206043. }
  206044. void drawVerticalLine (int x, float top, float bottom)
  206045. {
  206046. // xxx doesn't seem to be correctly aligned, may need nudging by 0.5 to match the software renderer's behaviour
  206047. currentState->createBrush();
  206048. x += currentState->origin.getX();
  206049. const int y = currentState->origin.getY();
  206050. renderingTarget->DrawLine (D2D1::Point2F (x, y + top),
  206051. D2D1::Point2F (x, y + bottom),
  206052. currentState->currentBrush);
  206053. }
  206054. void drawHorizontalLine (int y, float left, float right)
  206055. {
  206056. // xxx doesn't seem to be correctly aligned, may need nudging by 0.5 to match the software renderer's behaviour
  206057. currentState->createBrush();
  206058. y += currentState->origin.getY();
  206059. const int x = currentState->origin.getX();
  206060. renderingTarget->DrawLine (D2D1::Point2F (x + left, y),
  206061. D2D1::Point2F (x + right, y),
  206062. currentState->currentBrush);
  206063. }
  206064. void setFont (const Font& newFont)
  206065. {
  206066. currentState->setFont (newFont);
  206067. }
  206068. const Font getFont()
  206069. {
  206070. return currentState->font;
  206071. }
  206072. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  206073. {
  206074. const float x = currentState->origin.getX();
  206075. const float y = currentState->origin.getY();
  206076. currentState->createBrush();
  206077. currentState->createFont();
  206078. float kerning = currentState->font.getExtraKerningFactor(); // xxx why does removing this line mess up the kerning??
  206079. float hScale = currentState->font.getHorizontalScale();
  206080. renderingTarget->SetTransform (D2D1::Matrix3x2F::Scale (hScale, 1) * transfromToMatrix (transform) * D2D1::Matrix3x2F::Translation (x, y));
  206081. float dpiX = 0, dpiY = 0;
  206082. SharedD2DFactory::getInstance()->d2dFactory->GetDesktopDpi (&dpiX, &dpiY);
  206083. UINT32 glyphNum = glyphNumber;
  206084. UINT16 glyphNum1 = 0; // xxx needs a better name - what is this for?
  206085. currentState->currentFontFace->GetGlyphIndices (&glyphNum, 1, &glyphNum1);
  206086. DWRITE_GLYPH_OFFSET offset;
  206087. offset.advanceOffset = 0;
  206088. offset.ascenderOffset = 0;
  206089. float glyphAdvances = 0;
  206090. DWRITE_GLYPH_RUN glyph;
  206091. glyph.fontFace = currentState->currentFontFace;
  206092. glyph.glyphCount = 1;
  206093. glyph.glyphIndices = &glyphNum1;
  206094. glyph.isSideways = FALSE;
  206095. glyph.glyphAdvances = &glyphAdvances;
  206096. glyph.glyphOffsets = &offset;
  206097. glyph.fontEmSize = (float) currentState->font.getHeight() * dpiX / 96.0f * (1 + currentState->fontScaling) / 2;
  206098. renderingTarget->DrawGlyphRun (D2D1::Point2F (0, 0), &glyph, currentState->currentBrush);
  206099. renderingTarget->SetTransform (D2D1::IdentityMatrix());
  206100. }
  206101. class SavedState
  206102. {
  206103. public:
  206104. SavedState (Direct2DLowLevelGraphicsContext& owner_)
  206105. : owner (owner_), currentBrush (0),
  206106. fontScaling (1.0f), currentFontFace (0),
  206107. clipsRect (false), shouldClipRect (false),
  206108. clipsRectList (false), shouldClipRectList (false),
  206109. clipsComplex (false), shouldClipComplex (false),
  206110. clipsBitmap (false), shouldClipBitmap (false)
  206111. {
  206112. if (owner.currentState != 0)
  206113. {
  206114. // xxx seems like a very slow way to create one of these, and this is a performance
  206115. // bottleneck.. Can the same internal objects be shared by multiple state objects, maybe using copy-on-write?
  206116. setFill (owner.currentState->fillType);
  206117. currentBrush = owner.currentState->currentBrush;
  206118. origin = owner.currentState->origin;
  206119. clipRect = owner.currentState->clipRect;
  206120. font = owner.currentState->font;
  206121. currentFontFace = owner.currentState->currentFontFace;
  206122. }
  206123. else
  206124. {
  206125. const D2D1_SIZE_U size (owner.renderingTarget->GetPixelSize());
  206126. clipRect.setSize (size.width, size.height);
  206127. setFill (FillType (Colours::black));
  206128. }
  206129. }
  206130. ~SavedState()
  206131. {
  206132. clearClip();
  206133. clearFont();
  206134. clearFill();
  206135. clearPathClip();
  206136. clearImageClip();
  206137. complexClipLayer = 0;
  206138. bitmapMaskLayer = 0;
  206139. }
  206140. void clearClip()
  206141. {
  206142. popClips();
  206143. shouldClipRect = false;
  206144. }
  206145. void clipToRectangle (const Rectangle<int>& r)
  206146. {
  206147. clearClip();
  206148. clipRect = r + origin;
  206149. shouldClipRect = true;
  206150. pushClips();
  206151. }
  206152. void clearPathClip()
  206153. {
  206154. popClips();
  206155. if (shouldClipComplex)
  206156. {
  206157. complexClipGeometry = 0;
  206158. shouldClipComplex = false;
  206159. }
  206160. }
  206161. void clipToPath (ID2D1Geometry* geometry)
  206162. {
  206163. clearPathClip();
  206164. if (complexClipLayer == 0)
  206165. owner.renderingTarget->CreateLayer (&complexClipLayer);
  206166. complexClipGeometry = geometry;
  206167. shouldClipComplex = true;
  206168. pushClips();
  206169. }
  206170. void clearRectListClip()
  206171. {
  206172. popClips();
  206173. if (shouldClipRectList)
  206174. {
  206175. rectListGeometry = 0;
  206176. shouldClipRectList = false;
  206177. }
  206178. }
  206179. void clipToRectList (ID2D1Geometry* geometry)
  206180. {
  206181. clearRectListClip();
  206182. if (rectListLayer == 0)
  206183. owner.renderingTarget->CreateLayer (&rectListLayer);
  206184. rectListGeometry = geometry;
  206185. shouldClipRectList = true;
  206186. pushClips();
  206187. }
  206188. void clearImageClip()
  206189. {
  206190. popClips();
  206191. if (shouldClipBitmap)
  206192. {
  206193. maskBitmap = 0;
  206194. bitmapMaskBrush = 0;
  206195. shouldClipBitmap = false;
  206196. }
  206197. }
  206198. void clipToImage (const Image& image, const AffineTransform& transform)
  206199. {
  206200. clearImageClip();
  206201. if (bitmapMaskLayer == 0)
  206202. owner.renderingTarget->CreateLayer (&bitmapMaskLayer);
  206203. D2D1_BRUSH_PROPERTIES brushProps;
  206204. brushProps.opacity = 1;
  206205. brushProps.transform = transfromToMatrix (transform);
  206206. D2D1_BITMAP_BRUSH_PROPERTIES bmProps = D2D1::BitmapBrushProperties (D2D1_EXTEND_MODE_WRAP, D2D1_EXTEND_MODE_WRAP);
  206207. D2D1_SIZE_U size;
  206208. size.width = image.getWidth();
  206209. size.height = image.getHeight();
  206210. D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();
  206211. maskImage = image.convertedToFormat (Image::ARGB);
  206212. Image::BitmapData bd (this->image, false); // xxx should be maskImage?
  206213. bp.pixelFormat = owner.renderingTarget->GetPixelFormat();
  206214. bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
  206215. HRESULT hr = owner.renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, &maskBitmap);
  206216. hr = owner.renderingTarget->CreateBitmapBrush (maskBitmap, bmProps, brushProps, &bitmapMaskBrush);
  206217. imageMaskLayerParams = D2D1::LayerParameters();
  206218. imageMaskLayerParams.opacityBrush = bitmapMaskBrush;
  206219. shouldClipBitmap = true;
  206220. pushClips();
  206221. }
  206222. void popClips()
  206223. {
  206224. if (clipsBitmap)
  206225. {
  206226. owner.renderingTarget->PopLayer();
  206227. clipsBitmap = false;
  206228. }
  206229. if (clipsComplex)
  206230. {
  206231. owner.renderingTarget->PopLayer();
  206232. clipsComplex = false;
  206233. }
  206234. if (clipsRectList)
  206235. {
  206236. owner.renderingTarget->PopLayer();
  206237. clipsRectList = false;
  206238. }
  206239. if (clipsRect)
  206240. {
  206241. owner.renderingTarget->PopAxisAlignedClip();
  206242. clipsRect = false;
  206243. }
  206244. }
  206245. void pushClips()
  206246. {
  206247. if (shouldClipRect && ! clipsRect)
  206248. {
  206249. owner.renderingTarget->PushAxisAlignedClip (rectangleToRectF (clipRect), D2D1_ANTIALIAS_MODE_PER_PRIMITIVE);
  206250. clipsRect = true;
  206251. }
  206252. if (shouldClipRectList && ! clipsRectList)
  206253. {
  206254. D2D1_LAYER_PARAMETERS layerParams = D2D1::LayerParameters();
  206255. rectListGeometry->GetBounds (D2D1::IdentityMatrix(), &layerParams.contentBounds);
  206256. layerParams.geometricMask = rectListGeometry;
  206257. owner.renderingTarget->PushLayer (layerParams, rectListLayer);
  206258. clipsRectList = true;
  206259. }
  206260. if (shouldClipComplex && ! clipsComplex)
  206261. {
  206262. D2D1_LAYER_PARAMETERS layerParams = D2D1::LayerParameters();
  206263. complexClipGeometry->GetBounds (D2D1::IdentityMatrix(), &layerParams.contentBounds);
  206264. layerParams.geometricMask = complexClipGeometry;
  206265. owner.renderingTarget->PushLayer (layerParams, complexClipLayer);
  206266. clipsComplex = true;
  206267. }
  206268. if (shouldClipBitmap && ! clipsBitmap)
  206269. {
  206270. owner.renderingTarget->PushLayer (imageMaskLayerParams, bitmapMaskLayer);
  206271. clipsBitmap = true;
  206272. }
  206273. }
  206274. void setFill (const FillType& newFillType)
  206275. {
  206276. if (fillType != newFillType)
  206277. {
  206278. fillType = newFillType;
  206279. clearFill();
  206280. }
  206281. }
  206282. void clearFont()
  206283. {
  206284. currentFontFace = localFontFace = 0;
  206285. }
  206286. void setFont (const Font& newFont)
  206287. {
  206288. if (font != newFont)
  206289. {
  206290. font = newFont;
  206291. clearFont();
  206292. }
  206293. }
  206294. void createFont()
  206295. {
  206296. // xxx The font shouldn't be managed by the graphics context.
  206297. // The correct way to handle font lifetimes is to use a subclass of Typeface - see
  206298. // MacTypeface and WindowsTypeface classes. D2D support could probably just be added to the
  206299. // WindowsTypeface class.
  206300. if (currentFontFace == 0)
  206301. {
  206302. WindowsTypeface* systemType = dynamic_cast<WindowsTypeface*> (font.getTypeface());
  206303. fontScaling = systemType->getAscent();
  206304. BOOL fontFound;
  206305. uint32 fontIndex;
  206306. IDWriteFontCollection* fonts = SharedD2DFactory::getInstance()->systemFonts;
  206307. fonts->FindFamilyName (systemType->getName(), &fontIndex, &fontFound);
  206308. if (! fontFound)
  206309. fontIndex = 0;
  206310. ComSmartPtr <IDWriteFontFamily> fontFam;
  206311. fonts->GetFontFamily (fontIndex, &fontFam);
  206312. ComSmartPtr <IDWriteFont> font;
  206313. DWRITE_FONT_WEIGHT weight = this->font.isBold() ? DWRITE_FONT_WEIGHT_BOLD : DWRITE_FONT_WEIGHT_NORMAL;
  206314. DWRITE_FONT_STYLE style = this->font.isItalic() ? DWRITE_FONT_STYLE_ITALIC : DWRITE_FONT_STYLE_NORMAL;
  206315. fontFam->GetFirstMatchingFont (weight, DWRITE_FONT_STRETCH_NORMAL, style, &font);
  206316. font->CreateFontFace (&localFontFace);
  206317. currentFontFace = localFontFace;
  206318. }
  206319. }
  206320. void setOpacity (float newOpacity)
  206321. {
  206322. fillType.setOpacity (newOpacity);
  206323. if (currentBrush != 0)
  206324. currentBrush->SetOpacity (newOpacity);
  206325. }
  206326. void clearFill()
  206327. {
  206328. gradientStops = 0;
  206329. linearGradient = 0;
  206330. radialGradient = 0;
  206331. bitmap = 0;
  206332. bitmapBrush = 0;
  206333. currentBrush = 0;
  206334. }
  206335. void createBrush()
  206336. {
  206337. if (currentBrush == 0)
  206338. {
  206339. const int x = origin.getX();
  206340. const int y = origin.getY();
  206341. if (fillType.isColour())
  206342. {
  206343. D2D1_COLOR_F colour = colourToD2D (fillType.colour);
  206344. owner.colourBrush->SetColor (colour);
  206345. currentBrush = owner.colourBrush;
  206346. }
  206347. else if (fillType.isTiledImage())
  206348. {
  206349. D2D1_BRUSH_PROPERTIES brushProps;
  206350. brushProps.opacity = fillType.getOpacity();
  206351. brushProps.transform = transfromToMatrix (fillType.transform);
  206352. D2D1_BITMAP_BRUSH_PROPERTIES bmProps = D2D1::BitmapBrushProperties (D2D1_EXTEND_MODE_WRAP,D2D1_EXTEND_MODE_WRAP);
  206353. image = fillType.image;
  206354. D2D1_SIZE_U size;
  206355. size.width = image.getWidth();
  206356. size.height = image.getHeight();
  206357. D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();
  206358. this->image = image.convertedToFormat (Image::ARGB);
  206359. Image::BitmapData bd (this->image, false);
  206360. bp.pixelFormat = owner.renderingTarget->GetPixelFormat();
  206361. bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
  206362. HRESULT hr = owner.renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, &bitmap);
  206363. hr = owner.renderingTarget->CreateBitmapBrush (bitmap, bmProps, brushProps, &bitmapBrush);
  206364. currentBrush = bitmapBrush;
  206365. }
  206366. else if (fillType.isGradient())
  206367. {
  206368. gradientStops = 0;
  206369. D2D1_BRUSH_PROPERTIES brushProps;
  206370. brushProps.opacity = fillType.getOpacity();
  206371. brushProps.transform = transfromToMatrix (fillType.transform);
  206372. const int numColors = fillType.gradient->getNumColours();
  206373. HeapBlock<D2D1_GRADIENT_STOP> stops (numColors);
  206374. for (int i = fillType.gradient->getNumColours(); --i >= 0;)
  206375. {
  206376. stops[i].color = colourToD2D (fillType.gradient->getColour(i));
  206377. stops[i].position = fillType.gradient->getColourPosition(i);
  206378. }
  206379. owner.renderingTarget->CreateGradientStopCollection (stops.getData(), numColors, &gradientStops);
  206380. if (fillType.gradient->isRadial)
  206381. {
  206382. radialGradient = 0;
  206383. const Point<float>& p1 = fillType.gradient->point1;
  206384. const Point<float>& p2 = fillType.gradient->point2;
  206385. float r = p1.getDistanceFrom (p2);
  206386. D2D1_RADIAL_GRADIENT_BRUSH_PROPERTIES props =
  206387. D2D1::RadialGradientBrushProperties (D2D1::Point2F (p1.getX() + x, p1.getY() + y),
  206388. D2D1::Point2F (0, 0),
  206389. r, r);
  206390. owner.renderingTarget->CreateRadialGradientBrush (props, brushProps, gradientStops, &radialGradient);
  206391. currentBrush = radialGradient;
  206392. }
  206393. else
  206394. {
  206395. linearGradient = 0;
  206396. const Point<float>& p1 = fillType.gradient->point1;
  206397. const Point<float>& p2 = fillType.gradient->point2;
  206398. D2D1_LINEAR_GRADIENT_BRUSH_PROPERTIES props =
  206399. D2D1::LinearGradientBrushProperties (D2D1::Point2F (p1.getX() + x, p1.getY() + y),
  206400. D2D1::Point2F (p2.getX() + x, p2.getY() + y));
  206401. owner.renderingTarget->CreateLinearGradientBrush (props, brushProps, gradientStops, &linearGradient);
  206402. currentBrush = linearGradient;
  206403. }
  206404. }
  206405. }
  206406. }
  206407. juce_UseDebuggingNewOperator
  206408. //xxx most of these members should probably be private...
  206409. Direct2DLowLevelGraphicsContext& owner;
  206410. Point<int> origin;
  206411. Font font;
  206412. float fontScaling;
  206413. IDWriteFontFace* currentFontFace;
  206414. ComSmartPtr <IDWriteFontFace> localFontFace;
  206415. FillType fillType;
  206416. Image image;
  206417. ComSmartPtr <ID2D1Bitmap> bitmap; // xxx needs a better name - what is this for??
  206418. Rectangle<int> clipRect;
  206419. bool clipsRect, shouldClipRect;
  206420. ComSmartPtr <ID2D1Geometry> complexClipGeometry;
  206421. D2D1_LAYER_PARAMETERS complexClipLayerParams;
  206422. ComSmartPtr <ID2D1Layer> complexClipLayer;
  206423. bool clipsComplex, shouldClipComplex;
  206424. ComSmartPtr <ID2D1Geometry> rectListGeometry;
  206425. D2D1_LAYER_PARAMETERS rectListLayerParams;
  206426. ComSmartPtr <ID2D1Layer> rectListLayer;
  206427. bool clipsRectList, shouldClipRectList;
  206428. Image maskImage;
  206429. D2D1_LAYER_PARAMETERS imageMaskLayerParams;
  206430. ComSmartPtr <ID2D1Layer> bitmapMaskLayer;
  206431. ComSmartPtr <ID2D1Bitmap> maskBitmap;
  206432. ComSmartPtr <ID2D1BitmapBrush> bitmapMaskBrush;
  206433. bool clipsBitmap, shouldClipBitmap;
  206434. ID2D1Brush* currentBrush;
  206435. ComSmartPtr <ID2D1BitmapBrush> bitmapBrush;
  206436. ComSmartPtr <ID2D1LinearGradientBrush> linearGradient;
  206437. ComSmartPtr <ID2D1RadialGradientBrush> radialGradient;
  206438. ComSmartPtr <ID2D1GradientStopCollection> gradientStops;
  206439. private:
  206440. SavedState (const SavedState&);
  206441. SavedState& operator= (const SavedState& other);
  206442. };
  206443. juce_UseDebuggingNewOperator
  206444. private:
  206445. HWND hwnd;
  206446. ComSmartPtr <ID2D1HwndRenderTarget> renderingTarget;
  206447. ComSmartPtr <ID2D1SolidColorBrush> colourBrush;
  206448. Rectangle<int> bounds;
  206449. SavedState* currentState;
  206450. OwnedArray<SavedState> states;
  206451. static D2D1_RECT_F rectangleToRectF (const Rectangle<int>& r)
  206452. {
  206453. return D2D1::RectF ((float) r.getX(), (float) r.getY(), (float) r.getRight(), (float) r.getBottom());
  206454. }
  206455. static const D2D1_COLOR_F colourToD2D (const Colour& c)
  206456. {
  206457. return D2D1::ColorF::ColorF (c.getFloatRed(), c.getFloatGreen(), c.getFloatBlue(), c.getFloatAlpha());
  206458. }
  206459. static const D2D1_POINT_2F pointTransformed (int x, int y, const AffineTransform& transform = AffineTransform::identity)
  206460. {
  206461. transform.transformPoint (x, y);
  206462. return D2D1::Point2F (x, y);
  206463. }
  206464. static void rectToGeometrySink (const Rectangle<int>& rect, ID2D1GeometrySink* sink)
  206465. {
  206466. sink->BeginFigure (pointTransformed (rect.getX(), rect.getY()), D2D1_FIGURE_BEGIN_FILLED);
  206467. sink->AddLine (pointTransformed (rect.getRight(), rect.getY()));
  206468. sink->AddLine (pointTransformed (rect.getRight(), rect.getBottom()));
  206469. sink->AddLine (pointTransformed (rect.getX(), rect.getBottom()));
  206470. sink->EndFigure (D2D1_FIGURE_END_CLOSED);
  206471. }
  206472. static ID2D1PathGeometry* rectListToPathGeometry (const RectangleList& clipRegion)
  206473. {
  206474. ID2D1PathGeometry* p = 0;
  206475. SharedD2DFactory::getInstance()->d2dFactory->CreatePathGeometry (&p);
  206476. ComSmartPtr <ID2D1GeometrySink> sink;
  206477. HRESULT hr = p->Open (&sink); // xxx handle error
  206478. sink->SetFillMode (D2D1_FILL_MODE_WINDING);
  206479. for (int i = clipRegion.getNumRectangles(); --i >= 0;)
  206480. rectToGeometrySink (clipRegion.getRectangle(i), sink);
  206481. hr = sink->Close();
  206482. return p;
  206483. }
  206484. static void pathToGeometrySink (const Path& path, ID2D1GeometrySink* sink, const AffineTransform& transform, int x, int y)
  206485. {
  206486. Path::Iterator it (path);
  206487. while (it.next())
  206488. {
  206489. switch (it.elementType)
  206490. {
  206491. case Path::Iterator::cubicTo:
  206492. {
  206493. D2D1_BEZIER_SEGMENT seg;
  206494. transform.transformPoint (it.x1, it.y1);
  206495. seg.point1 = D2D1::Point2F (it.x1 + x, it.y1 + y);
  206496. transform.transformPoint (it.x2, it.y2);
  206497. seg.point2 = D2D1::Point2F (it.x2 + x, it.y2 + y);
  206498. transform.transformPoint(it.x3, it.y3);
  206499. seg.point3 = D2D1::Point2F (it.x3 + x, it.y3 + y);
  206500. sink->AddBezier (seg);
  206501. break;
  206502. }
  206503. case Path::Iterator::lineTo:
  206504. {
  206505. transform.transformPoint (it.x1, it.y1);
  206506. sink->AddLine (D2D1::Point2F (it.x1 + x, it.y1 + y));
  206507. break;
  206508. }
  206509. case Path::Iterator::quadraticTo:
  206510. {
  206511. D2D1_QUADRATIC_BEZIER_SEGMENT seg;
  206512. transform.transformPoint (it.x1, it.y1);
  206513. seg.point1 = D2D1::Point2F (it.x1 + x, it.y1 + y);
  206514. transform.transformPoint (it.x2, it.y2);
  206515. seg.point2 = D2D1::Point2F (it.x2 + x, it.y2 + y);
  206516. sink->AddQuadraticBezier (seg);
  206517. break;
  206518. }
  206519. case Path::Iterator::closePath:
  206520. {
  206521. sink->EndFigure (D2D1_FIGURE_END_CLOSED);
  206522. break;
  206523. }
  206524. case Path::Iterator::startNewSubPath:
  206525. {
  206526. transform.transformPoint (it.x1, it.y1);
  206527. sink->BeginFigure (D2D1::Point2F (it.x1 + x, it.y1 + y), D2D1_FIGURE_BEGIN_FILLED);
  206528. break;
  206529. }
  206530. }
  206531. }
  206532. }
  206533. static ID2D1PathGeometry* pathToPathGeometry (const Path& path, const AffineTransform& transform, const Point<int>& point)
  206534. {
  206535. ID2D1PathGeometry* p = 0;
  206536. SharedD2DFactory::getInstance()->d2dFactory->CreatePathGeometry (&p);
  206537. ComSmartPtr <ID2D1GeometrySink> sink;
  206538. HRESULT hr = p->Open (&sink);
  206539. sink->SetFillMode (D2D1_FILL_MODE_WINDING); // xxx need to check Path::isUsingNonZeroWinding()
  206540. pathToGeometrySink (path, sink, transform, point.getX(), point.getY());
  206541. hr = sink->Close();
  206542. return p;
  206543. }
  206544. static const D2D1::Matrix3x2F transfromToMatrix (const AffineTransform& transform)
  206545. {
  206546. D2D1::Matrix3x2F matrix;
  206547. matrix._11 = transform.mat00;
  206548. matrix._12 = transform.mat10;
  206549. matrix._21 = transform.mat01;
  206550. matrix._22 = transform.mat11;
  206551. matrix._31 = transform.mat02;
  206552. matrix._32 = transform.mat12;
  206553. return matrix;
  206554. }
  206555. };
  206556. #endif
  206557. /*** End of inlined file: juce_win32_Direct2DGraphicsContext.cpp ***/
  206558. /*** Start of inlined file: juce_win32_Windowing.cpp ***/
  206559. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  206560. // compiled on its own).
  206561. #if JUCE_INCLUDED_FILE
  206562. #undef GetSystemMetrics // multimon overrides this for some reason and causes a mess..
  206563. // these are in the windows SDK, but need to be repeated here for GCC..
  206564. #ifndef GET_APPCOMMAND_LPARAM
  206565. #define FAPPCOMMAND_MASK 0xF000
  206566. #define GET_APPCOMMAND_LPARAM(lParam) ((short) (HIWORD (lParam) & ~FAPPCOMMAND_MASK))
  206567. #define APPCOMMAND_MEDIA_NEXTTRACK 11
  206568. #define APPCOMMAND_MEDIA_PREVIOUSTRACK 12
  206569. #define APPCOMMAND_MEDIA_STOP 13
  206570. #define APPCOMMAND_MEDIA_PLAY_PAUSE 14
  206571. #define WM_APPCOMMAND 0x0319
  206572. #endif
  206573. extern void juce_repeatLastProcessPriority(); // in juce_win32_Threads.cpp
  206574. extern void juce_CheckCurrentlyFocusedTopLevelWindow(); // in juce_TopLevelWindow.cpp
  206575. extern bool juce_IsRunningInWine();
  206576. #ifndef ULW_ALPHA
  206577. #define ULW_ALPHA 0x00000002
  206578. #endif
  206579. #ifndef AC_SRC_ALPHA
  206580. #define AC_SRC_ALPHA 0x01
  206581. #endif
  206582. static HPALETTE palette = 0;
  206583. static bool createPaletteIfNeeded = true;
  206584. static bool shouldDeactivateTitleBar = true;
  206585. #define WM_TRAYNOTIFY WM_USER + 100
  206586. using ::abs;
  206587. typedef BOOL (WINAPI* UpdateLayeredWinFunc) (HWND, HDC, POINT*, SIZE*, HDC, POINT*, COLORREF, BLENDFUNCTION*, DWORD);
  206588. static UpdateLayeredWinFunc updateLayeredWindow = 0;
  206589. bool Desktop::canUseSemiTransparentWindows() throw()
  206590. {
  206591. if (updateLayeredWindow == 0)
  206592. {
  206593. if (! juce_IsRunningInWine())
  206594. {
  206595. HMODULE user32Mod = GetModuleHandle (_T("user32.dll"));
  206596. updateLayeredWindow = (UpdateLayeredWinFunc) GetProcAddress (user32Mod, "UpdateLayeredWindow");
  206597. }
  206598. }
  206599. return updateLayeredWindow != 0;
  206600. }
  206601. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  206602. {
  206603. return upright;
  206604. }
  206605. const int extendedKeyModifier = 0x10000;
  206606. const int KeyPress::spaceKey = VK_SPACE;
  206607. const int KeyPress::returnKey = VK_RETURN;
  206608. const int KeyPress::escapeKey = VK_ESCAPE;
  206609. const int KeyPress::backspaceKey = VK_BACK;
  206610. const int KeyPress::deleteKey = VK_DELETE | extendedKeyModifier;
  206611. const int KeyPress::insertKey = VK_INSERT | extendedKeyModifier;
  206612. const int KeyPress::tabKey = VK_TAB;
  206613. const int KeyPress::leftKey = VK_LEFT | extendedKeyModifier;
  206614. const int KeyPress::rightKey = VK_RIGHT | extendedKeyModifier;
  206615. const int KeyPress::upKey = VK_UP | extendedKeyModifier;
  206616. const int KeyPress::downKey = VK_DOWN | extendedKeyModifier;
  206617. const int KeyPress::homeKey = VK_HOME | extendedKeyModifier;
  206618. const int KeyPress::endKey = VK_END | extendedKeyModifier;
  206619. const int KeyPress::pageUpKey = VK_PRIOR | extendedKeyModifier;
  206620. const int KeyPress::pageDownKey = VK_NEXT | extendedKeyModifier;
  206621. const int KeyPress::F1Key = VK_F1 | extendedKeyModifier;
  206622. const int KeyPress::F2Key = VK_F2 | extendedKeyModifier;
  206623. const int KeyPress::F3Key = VK_F3 | extendedKeyModifier;
  206624. const int KeyPress::F4Key = VK_F4 | extendedKeyModifier;
  206625. const int KeyPress::F5Key = VK_F5 | extendedKeyModifier;
  206626. const int KeyPress::F6Key = VK_F6 | extendedKeyModifier;
  206627. const int KeyPress::F7Key = VK_F7 | extendedKeyModifier;
  206628. const int KeyPress::F8Key = VK_F8 | extendedKeyModifier;
  206629. const int KeyPress::F9Key = VK_F9 | extendedKeyModifier;
  206630. const int KeyPress::F10Key = VK_F10 | extendedKeyModifier;
  206631. const int KeyPress::F11Key = VK_F11 | extendedKeyModifier;
  206632. const int KeyPress::F12Key = VK_F12 | extendedKeyModifier;
  206633. const int KeyPress::F13Key = VK_F13 | extendedKeyModifier;
  206634. const int KeyPress::F14Key = VK_F14 | extendedKeyModifier;
  206635. const int KeyPress::F15Key = VK_F15 | extendedKeyModifier;
  206636. const int KeyPress::F16Key = VK_F16 | extendedKeyModifier;
  206637. const int KeyPress::numberPad0 = VK_NUMPAD0 | extendedKeyModifier;
  206638. const int KeyPress::numberPad1 = VK_NUMPAD1 | extendedKeyModifier;
  206639. const int KeyPress::numberPad2 = VK_NUMPAD2 | extendedKeyModifier;
  206640. const int KeyPress::numberPad3 = VK_NUMPAD3 | extendedKeyModifier;
  206641. const int KeyPress::numberPad4 = VK_NUMPAD4 | extendedKeyModifier;
  206642. const int KeyPress::numberPad5 = VK_NUMPAD5 | extendedKeyModifier;
  206643. const int KeyPress::numberPad6 = VK_NUMPAD6 | extendedKeyModifier;
  206644. const int KeyPress::numberPad7 = VK_NUMPAD7 | extendedKeyModifier;
  206645. const int KeyPress::numberPad8 = VK_NUMPAD8 | extendedKeyModifier;
  206646. const int KeyPress::numberPad9 = VK_NUMPAD9 | extendedKeyModifier;
  206647. const int KeyPress::numberPadAdd = VK_ADD | extendedKeyModifier;
  206648. const int KeyPress::numberPadSubtract = VK_SUBTRACT | extendedKeyModifier;
  206649. const int KeyPress::numberPadMultiply = VK_MULTIPLY | extendedKeyModifier;
  206650. const int KeyPress::numberPadDivide = VK_DIVIDE | extendedKeyModifier;
  206651. const int KeyPress::numberPadSeparator = VK_SEPARATOR | extendedKeyModifier;
  206652. const int KeyPress::numberPadDecimalPoint = VK_DECIMAL | extendedKeyModifier;
  206653. const int KeyPress::numberPadEquals = 0x92 /*VK_OEM_NEC_EQUAL*/ | extendedKeyModifier;
  206654. const int KeyPress::numberPadDelete = VK_DELETE | extendedKeyModifier;
  206655. const int KeyPress::playKey = 0x30000;
  206656. const int KeyPress::stopKey = 0x30001;
  206657. const int KeyPress::fastForwardKey = 0x30002;
  206658. const int KeyPress::rewindKey = 0x30003;
  206659. class WindowsBitmapImage : public Image::SharedImage
  206660. {
  206661. public:
  206662. HBITMAP hBitmap;
  206663. BITMAPV4HEADER bitmapInfo;
  206664. HDC hdc;
  206665. unsigned char* bitmapData;
  206666. WindowsBitmapImage (const Image::PixelFormat format_,
  206667. const int w, const int h, const bool clearImage)
  206668. : Image::SharedImage (format_, w, h)
  206669. {
  206670. jassert (format_ == Image::RGB || format_ == Image::ARGB);
  206671. pixelStride = (format_ == Image::RGB) ? 3 : 4;
  206672. zerostruct (bitmapInfo);
  206673. bitmapInfo.bV4Size = sizeof (BITMAPV4HEADER);
  206674. bitmapInfo.bV4Width = w;
  206675. bitmapInfo.bV4Height = h;
  206676. bitmapInfo.bV4Planes = 1;
  206677. bitmapInfo.bV4CSType = 1;
  206678. bitmapInfo.bV4BitCount = (unsigned short) (pixelStride * 8);
  206679. if (format_ == Image::ARGB)
  206680. {
  206681. bitmapInfo.bV4AlphaMask = 0xff000000;
  206682. bitmapInfo.bV4RedMask = 0xff0000;
  206683. bitmapInfo.bV4GreenMask = 0xff00;
  206684. bitmapInfo.bV4BlueMask = 0xff;
  206685. bitmapInfo.bV4V4Compression = BI_BITFIELDS;
  206686. }
  206687. else
  206688. {
  206689. bitmapInfo.bV4V4Compression = BI_RGB;
  206690. }
  206691. lineStride = -((w * pixelStride + 3) & ~3);
  206692. HDC dc = GetDC (0);
  206693. hdc = CreateCompatibleDC (dc);
  206694. ReleaseDC (0, dc);
  206695. SetMapMode (hdc, MM_TEXT);
  206696. hBitmap = CreateDIBSection (hdc,
  206697. (BITMAPINFO*) &(bitmapInfo),
  206698. DIB_RGB_COLORS,
  206699. (void**) &bitmapData,
  206700. 0, 0);
  206701. SelectObject (hdc, hBitmap);
  206702. if (format_ == Image::ARGB && clearImage)
  206703. zeromem (bitmapData, abs (h * lineStride));
  206704. imageData = bitmapData - (lineStride * (h - 1));
  206705. }
  206706. ~WindowsBitmapImage()
  206707. {
  206708. DeleteDC (hdc);
  206709. DeleteObject (hBitmap);
  206710. }
  206711. Image::ImageType getType() const { return Image::NativeImage; }
  206712. LowLevelGraphicsContext* createLowLevelContext()
  206713. {
  206714. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  206715. }
  206716. SharedImage* clone()
  206717. {
  206718. WindowsBitmapImage* im = new WindowsBitmapImage (format, width, height, false);
  206719. for (int i = 0; i < height; ++i)
  206720. memcpy (im->imageData + i * lineStride, imageData + i * lineStride, lineStride);
  206721. return im;
  206722. }
  206723. void blitToWindow (HWND hwnd, HDC dc, const bool transparent,
  206724. const int x, const int y,
  206725. const RectangleList& maskedRegion,
  206726. const uint8 updateLayeredWindowAlpha) throw()
  206727. {
  206728. static HDRAWDIB hdd = 0;
  206729. static bool needToCreateDrawDib = true;
  206730. if (needToCreateDrawDib)
  206731. {
  206732. needToCreateDrawDib = false;
  206733. HDC dc = GetDC (0);
  206734. const int n = GetDeviceCaps (dc, BITSPIXEL);
  206735. ReleaseDC (0, dc);
  206736. // only open if we're not palettised
  206737. if (n > 8)
  206738. hdd = DrawDibOpen();
  206739. }
  206740. if (createPaletteIfNeeded)
  206741. {
  206742. HDC dc = GetDC (0);
  206743. const int n = GetDeviceCaps (dc, BITSPIXEL);
  206744. ReleaseDC (0, dc);
  206745. if (n <= 8)
  206746. palette = CreateHalftonePalette (dc);
  206747. createPaletteIfNeeded = false;
  206748. }
  206749. if (palette != 0)
  206750. {
  206751. SelectPalette (dc, palette, FALSE);
  206752. RealizePalette (dc);
  206753. SetStretchBltMode (dc, HALFTONE);
  206754. }
  206755. SetMapMode (dc, MM_TEXT);
  206756. if (transparent)
  206757. {
  206758. POINT p, pos;
  206759. SIZE size;
  206760. RECT windowBounds;
  206761. GetWindowRect (hwnd, &windowBounds);
  206762. p.x = -x;
  206763. p.y = -y;
  206764. pos.x = windowBounds.left;
  206765. pos.y = windowBounds.top;
  206766. size.cx = windowBounds.right - windowBounds.left;
  206767. size.cy = windowBounds.bottom - windowBounds.top;
  206768. BLENDFUNCTION bf;
  206769. bf.AlphaFormat = AC_SRC_ALPHA;
  206770. bf.BlendFlags = 0;
  206771. bf.BlendOp = AC_SRC_OVER;
  206772. bf.SourceConstantAlpha = updateLayeredWindowAlpha;
  206773. if (! maskedRegion.isEmpty())
  206774. {
  206775. for (RectangleList::Iterator i (maskedRegion); i.next();)
  206776. {
  206777. const Rectangle<int>& r = *i.getRectangle();
  206778. ExcludeClipRect (hdc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  206779. }
  206780. }
  206781. updateLayeredWindow (hwnd, 0, &pos, &size, hdc, &p, 0, &bf, ULW_ALPHA);
  206782. }
  206783. else
  206784. {
  206785. int savedDC = 0;
  206786. if (! maskedRegion.isEmpty())
  206787. {
  206788. savedDC = SaveDC (dc);
  206789. for (RectangleList::Iterator i (maskedRegion); i.next();)
  206790. {
  206791. const Rectangle<int>& r = *i.getRectangle();
  206792. ExcludeClipRect (dc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  206793. }
  206794. }
  206795. if (hdd == 0)
  206796. {
  206797. StretchDIBits (dc,
  206798. x, y, width, height,
  206799. 0, 0, width, height,
  206800. bitmapData, (const BITMAPINFO*) &bitmapInfo,
  206801. DIB_RGB_COLORS, SRCCOPY);
  206802. }
  206803. else
  206804. {
  206805. DrawDibDraw (hdd, dc, x, y, -1, -1,
  206806. (BITMAPINFOHEADER*) &bitmapInfo, bitmapData,
  206807. 0, 0, width, height, 0);
  206808. }
  206809. if (! maskedRegion.isEmpty())
  206810. RestoreDC (dc, savedDC);
  206811. }
  206812. }
  206813. juce_UseDebuggingNewOperator
  206814. private:
  206815. WindowsBitmapImage (const WindowsBitmapImage&);
  206816. WindowsBitmapImage& operator= (const WindowsBitmapImage&);
  206817. };
  206818. namespace IconConverters
  206819. {
  206820. const Image createImageFromHBITMAP (HBITMAP bitmap)
  206821. {
  206822. Image im;
  206823. if (bitmap != 0)
  206824. {
  206825. BITMAP bm;
  206826. if (GetObject (bitmap, sizeof (BITMAP), &bm)
  206827. && bm.bmWidth > 0 && bm.bmHeight > 0)
  206828. {
  206829. HDC tempDC = GetDC (0);
  206830. HDC dc = CreateCompatibleDC (tempDC);
  206831. ReleaseDC (0, tempDC);
  206832. SelectObject (dc, bitmap);
  206833. im = Image (Image::ARGB, bm.bmWidth, bm.bmHeight, true);
  206834. Image::BitmapData imageData (im, true);
  206835. for (int y = bm.bmHeight; --y >= 0;)
  206836. {
  206837. for (int x = bm.bmWidth; --x >= 0;)
  206838. {
  206839. COLORREF col = GetPixel (dc, x, y);
  206840. imageData.setPixelColour (x, y, Colour ((uint8) GetRValue (col),
  206841. (uint8) GetGValue (col),
  206842. (uint8) GetBValue (col)));
  206843. }
  206844. }
  206845. DeleteDC (dc);
  206846. }
  206847. }
  206848. return im;
  206849. }
  206850. const Image createImageFromHICON (HICON icon)
  206851. {
  206852. ICONINFO info;
  206853. if (GetIconInfo (icon, &info))
  206854. {
  206855. Image mask (createImageFromHBITMAP (info.hbmMask));
  206856. Image image (createImageFromHBITMAP (info.hbmColor));
  206857. if (mask.isValid() && image.isValid())
  206858. {
  206859. for (int y = image.getHeight(); --y >= 0;)
  206860. {
  206861. for (int x = image.getWidth(); --x >= 0;)
  206862. {
  206863. const float brightness = mask.getPixelAt (x, y).getBrightness();
  206864. if (brightness > 0.0f)
  206865. image.multiplyAlphaAt (x, y, 1.0f - brightness);
  206866. }
  206867. }
  206868. return image;
  206869. }
  206870. }
  206871. return Image::null;
  206872. }
  206873. HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY)
  206874. {
  206875. WindowsBitmapImage* nativeBitmap = new WindowsBitmapImage (Image::ARGB, image.getWidth(), image.getHeight(), true);
  206876. Image bitmap (nativeBitmap);
  206877. {
  206878. Graphics g (bitmap);
  206879. g.drawImageAt (image, 0, 0);
  206880. }
  206881. HBITMAP mask = CreateBitmap (image.getWidth(), image.getHeight(), 1, 1, 0);
  206882. ICONINFO info;
  206883. info.fIcon = isIcon;
  206884. info.xHotspot = hotspotX;
  206885. info.yHotspot = hotspotY;
  206886. info.hbmMask = mask;
  206887. info.hbmColor = nativeBitmap->hBitmap;
  206888. HICON hi = CreateIconIndirect (&info);
  206889. DeleteObject (mask);
  206890. return hi;
  206891. }
  206892. }
  206893. long improbableWindowNumber = 0xf965aa01; // also referenced by messaging.cpp
  206894. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  206895. {
  206896. SHORT k = (SHORT) keyCode;
  206897. if ((keyCode & extendedKeyModifier) == 0
  206898. && (k >= (SHORT) 'a' && k <= (SHORT) 'z'))
  206899. k += (SHORT) 'A' - (SHORT) 'a';
  206900. const SHORT translatedValues[] = { (SHORT) ',', VK_OEM_COMMA,
  206901. (SHORT) '+', VK_OEM_PLUS,
  206902. (SHORT) '-', VK_OEM_MINUS,
  206903. (SHORT) '.', VK_OEM_PERIOD,
  206904. (SHORT) ';', VK_OEM_1,
  206905. (SHORT) ':', VK_OEM_1,
  206906. (SHORT) '/', VK_OEM_2,
  206907. (SHORT) '?', VK_OEM_2,
  206908. (SHORT) '[', VK_OEM_4,
  206909. (SHORT) ']', VK_OEM_6 };
  206910. for (int i = 0; i < numElementsInArray (translatedValues); i += 2)
  206911. if (k == translatedValues [i])
  206912. k = translatedValues [i + 1];
  206913. return (GetKeyState (k) & 0x8000) != 0;
  206914. }
  206915. class Win32ComponentPeer : public ComponentPeer
  206916. {
  206917. public:
  206918. enum RenderingEngineType
  206919. {
  206920. softwareRenderingEngine = 0,
  206921. direct2DRenderingEngine
  206922. };
  206923. Win32ComponentPeer (Component* const component,
  206924. const int windowStyleFlags,
  206925. HWND parentToAddTo_)
  206926. : ComponentPeer (component, windowStyleFlags),
  206927. dontRepaint (false),
  206928. #if JUCE_DIRECT2D
  206929. currentRenderingEngine (direct2DRenderingEngine),
  206930. #else
  206931. currentRenderingEngine (softwareRenderingEngine),
  206932. #endif
  206933. fullScreen (false),
  206934. isDragging (false),
  206935. isMouseOver (false),
  206936. hasCreatedCaret (false),
  206937. currentWindowIcon (0),
  206938. dropTarget (0),
  206939. updateLayeredWindowAlpha (255),
  206940. parentToAddTo (parentToAddTo_)
  206941. {
  206942. callFunctionIfNotLocked (&createWindowCallback, this);
  206943. setTitle (component->getName());
  206944. if ((windowStyleFlags & windowHasDropShadow) != 0
  206945. && Desktop::canUseSemiTransparentWindows())
  206946. {
  206947. shadower = component->getLookAndFeel().createDropShadowerForComponent (component);
  206948. if (shadower != 0)
  206949. shadower->setOwner (component);
  206950. }
  206951. }
  206952. ~Win32ComponentPeer()
  206953. {
  206954. setTaskBarIcon (Image());
  206955. shadower = 0;
  206956. // do this before the next bit to avoid messages arriving for this window
  206957. // before it's destroyed
  206958. SetWindowLongPtr (hwnd, GWLP_USERDATA, 0);
  206959. callFunctionIfNotLocked (&destroyWindowCallback, (void*) hwnd);
  206960. if (currentWindowIcon != 0)
  206961. DestroyIcon (currentWindowIcon);
  206962. if (dropTarget != 0)
  206963. {
  206964. dropTarget->Release();
  206965. dropTarget = 0;
  206966. }
  206967. #if JUCE_DIRECT2D
  206968. direct2DContext = 0;
  206969. #endif
  206970. }
  206971. void* getNativeHandle() const
  206972. {
  206973. return hwnd;
  206974. }
  206975. void setVisible (bool shouldBeVisible)
  206976. {
  206977. ShowWindow (hwnd, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  206978. if (shouldBeVisible)
  206979. InvalidateRect (hwnd, 0, 0);
  206980. else
  206981. lastPaintTime = 0;
  206982. }
  206983. void setTitle (const String& title)
  206984. {
  206985. SetWindowText (hwnd, title);
  206986. }
  206987. void setPosition (int x, int y)
  206988. {
  206989. offsetWithinParent (x, y);
  206990. SetWindowPos (hwnd, 0,
  206991. x - windowBorder.getLeft(),
  206992. y - windowBorder.getTop(),
  206993. 0, 0,
  206994. SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  206995. }
  206996. void repaintNowIfTransparent()
  206997. {
  206998. if (isUsingUpdateLayeredWindow() && lastPaintTime > 0 && Time::getMillisecondCounter() > lastPaintTime + 30)
  206999. handlePaintMessage();
  207000. }
  207001. void updateBorderSize()
  207002. {
  207003. WINDOWINFO info;
  207004. info.cbSize = sizeof (info);
  207005. if (GetWindowInfo (hwnd, &info))
  207006. {
  207007. windowBorder = BorderSize (info.rcClient.top - info.rcWindow.top,
  207008. info.rcClient.left - info.rcWindow.left,
  207009. info.rcWindow.bottom - info.rcClient.bottom,
  207010. info.rcWindow.right - info.rcClient.right);
  207011. }
  207012. #if JUCE_DIRECT2D
  207013. if (direct2DContext != 0)
  207014. direct2DContext->resized();
  207015. #endif
  207016. }
  207017. void setSize (int w, int h)
  207018. {
  207019. SetWindowPos (hwnd, 0, 0, 0,
  207020. w + windowBorder.getLeftAndRight(),
  207021. h + windowBorder.getTopAndBottom(),
  207022. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  207023. updateBorderSize();
  207024. repaintNowIfTransparent();
  207025. }
  207026. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  207027. {
  207028. fullScreen = isNowFullScreen;
  207029. offsetWithinParent (x, y);
  207030. SetWindowPos (hwnd, 0,
  207031. x - windowBorder.getLeft(),
  207032. y - windowBorder.getTop(),
  207033. w + windowBorder.getLeftAndRight(),
  207034. h + windowBorder.getTopAndBottom(),
  207035. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  207036. updateBorderSize();
  207037. repaintNowIfTransparent();
  207038. }
  207039. const Rectangle<int> getBounds() const
  207040. {
  207041. RECT r;
  207042. GetWindowRect (hwnd, &r);
  207043. Rectangle<int> bounds (r.left, r.top, r.right - r.left, r.bottom - r.top);
  207044. HWND parentH = GetParent (hwnd);
  207045. if (parentH != 0)
  207046. {
  207047. GetWindowRect (parentH, &r);
  207048. bounds.translate (-r.left, -r.top);
  207049. }
  207050. return windowBorder.subtractedFrom (bounds);
  207051. }
  207052. const Point<int> getScreenPosition() const
  207053. {
  207054. RECT r;
  207055. GetWindowRect (hwnd, &r);
  207056. return Point<int> (r.left + windowBorder.getLeft(),
  207057. r.top + windowBorder.getTop());
  207058. }
  207059. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition)
  207060. {
  207061. return relativePosition + getScreenPosition();
  207062. }
  207063. const Point<int> globalPositionToRelative (const Point<int>& screenPosition)
  207064. {
  207065. return screenPosition - getScreenPosition();
  207066. }
  207067. void setAlpha (float newAlpha)
  207068. {
  207069. const uint8 intAlpha = (uint8) jlimit (0, 255, (int) (newAlpha * 255.0f));
  207070. if (component->isOpaque())
  207071. {
  207072. if (newAlpha < 1.0f)
  207073. {
  207074. SetWindowLong (hwnd, GWL_EXSTYLE, GetWindowLong (hwnd, GWL_EXSTYLE) | WS_EX_LAYERED);
  207075. SetLayeredWindowAttributes (hwnd, RGB (0, 0, 0), intAlpha, LWA_ALPHA);
  207076. }
  207077. else
  207078. {
  207079. SetWindowLong (hwnd, GWL_EXSTYLE, GetWindowLong (hwnd, GWL_EXSTYLE) & ~WS_EX_LAYERED);
  207080. RedrawWindow (hwnd, 0, 0, RDW_ERASE | RDW_INVALIDATE | RDW_FRAME | RDW_ALLCHILDREN);
  207081. }
  207082. }
  207083. else
  207084. {
  207085. updateLayeredWindowAlpha = intAlpha;
  207086. component->repaint();
  207087. }
  207088. }
  207089. void setMinimised (bool shouldBeMinimised)
  207090. {
  207091. if (shouldBeMinimised != isMinimised())
  207092. ShowWindow (hwnd, shouldBeMinimised ? SW_MINIMIZE : SW_SHOWNORMAL);
  207093. }
  207094. bool isMinimised() const
  207095. {
  207096. WINDOWPLACEMENT wp;
  207097. wp.length = sizeof (WINDOWPLACEMENT);
  207098. GetWindowPlacement (hwnd, &wp);
  207099. return wp.showCmd == SW_SHOWMINIMIZED;
  207100. }
  207101. void setFullScreen (bool shouldBeFullScreen)
  207102. {
  207103. setMinimised (false);
  207104. if (fullScreen != shouldBeFullScreen)
  207105. {
  207106. fullScreen = shouldBeFullScreen;
  207107. const Component::SafePointer<Component> deletionChecker (component);
  207108. if (! fullScreen)
  207109. {
  207110. const Rectangle<int> boundsCopy (lastNonFullscreenBounds);
  207111. if (hasTitleBar())
  207112. ShowWindow (hwnd, SW_SHOWNORMAL);
  207113. if (! boundsCopy.isEmpty())
  207114. {
  207115. setBounds (boundsCopy.getX(),
  207116. boundsCopy.getY(),
  207117. boundsCopy.getWidth(),
  207118. boundsCopy.getHeight(),
  207119. false);
  207120. }
  207121. }
  207122. else
  207123. {
  207124. if (hasTitleBar())
  207125. ShowWindow (hwnd, SW_SHOWMAXIMIZED);
  207126. else
  207127. SendMessageW (hwnd, WM_SETTINGCHANGE, 0, 0);
  207128. }
  207129. if (deletionChecker != 0)
  207130. handleMovedOrResized();
  207131. }
  207132. }
  207133. bool isFullScreen() const
  207134. {
  207135. if (! hasTitleBar())
  207136. return fullScreen;
  207137. WINDOWPLACEMENT wp;
  207138. wp.length = sizeof (wp);
  207139. GetWindowPlacement (hwnd, &wp);
  207140. return wp.showCmd == SW_SHOWMAXIMIZED;
  207141. }
  207142. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  207143. {
  207144. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  207145. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  207146. return false;
  207147. RECT r;
  207148. GetWindowRect (hwnd, &r);
  207149. POINT p;
  207150. p.x = position.getX() + r.left + windowBorder.getLeft();
  207151. p.y = position.getY() + r.top + windowBorder.getTop();
  207152. HWND w = WindowFromPoint (p);
  207153. return w == hwnd || (trueIfInAChildWindow && (IsChild (hwnd, w) != 0));
  207154. }
  207155. const BorderSize getFrameSize() const
  207156. {
  207157. return windowBorder;
  207158. }
  207159. bool setAlwaysOnTop (bool alwaysOnTop)
  207160. {
  207161. const bool oldDeactivate = shouldDeactivateTitleBar;
  207162. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  207163. SetWindowPos (hwnd, alwaysOnTop ? HWND_TOPMOST : HWND_NOTOPMOST,
  207164. 0, 0, 0, 0,
  207165. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  207166. shouldDeactivateTitleBar = oldDeactivate;
  207167. if (shadower != 0)
  207168. shadower->componentBroughtToFront (*component);
  207169. return true;
  207170. }
  207171. void toFront (bool makeActive)
  207172. {
  207173. setMinimised (false);
  207174. const bool oldDeactivate = shouldDeactivateTitleBar;
  207175. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  207176. callFunctionIfNotLocked (makeActive ? &toFrontCallback1 : &toFrontCallback2, hwnd);
  207177. shouldDeactivateTitleBar = oldDeactivate;
  207178. if (! makeActive)
  207179. {
  207180. // in this case a broughttofront call won't have occured, so do it now..
  207181. handleBroughtToFront();
  207182. }
  207183. }
  207184. void toBehind (ComponentPeer* other)
  207185. {
  207186. Win32ComponentPeer* const otherPeer = dynamic_cast <Win32ComponentPeer*> (other);
  207187. jassert (otherPeer != 0); // wrong type of window?
  207188. if (otherPeer != 0)
  207189. {
  207190. setMinimised (false);
  207191. // must be careful not to try to put a topmost window behind a normal one, or win32
  207192. // promotes the normal one to be topmost!
  207193. if (getComponent()->isAlwaysOnTop() == otherPeer->getComponent()->isAlwaysOnTop())
  207194. SetWindowPos (hwnd, otherPeer->hwnd, 0, 0, 0, 0,
  207195. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  207196. else if (otherPeer->getComponent()->isAlwaysOnTop())
  207197. SetWindowPos (hwnd, HWND_TOP, 0, 0, 0, 0,
  207198. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  207199. }
  207200. }
  207201. bool isFocused() const
  207202. {
  207203. return callFunctionIfNotLocked (&getFocusCallback, 0) == (void*) hwnd;
  207204. }
  207205. void grabFocus()
  207206. {
  207207. const bool oldDeactivate = shouldDeactivateTitleBar;
  207208. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  207209. callFunctionIfNotLocked (&setFocusCallback, hwnd);
  207210. shouldDeactivateTitleBar = oldDeactivate;
  207211. }
  207212. void textInputRequired (const Point<int>&)
  207213. {
  207214. if (! hasCreatedCaret)
  207215. {
  207216. hasCreatedCaret = true;
  207217. CreateCaret (hwnd, (HBITMAP) 1, 0, 0);
  207218. }
  207219. ShowCaret (hwnd);
  207220. SetCaretPos (0, 0);
  207221. }
  207222. void repaint (const Rectangle<int>& area)
  207223. {
  207224. const RECT r = { area.getX(), area.getY(), area.getRight(), area.getBottom() };
  207225. InvalidateRect (hwnd, &r, FALSE);
  207226. }
  207227. void performAnyPendingRepaintsNow()
  207228. {
  207229. MSG m;
  207230. if (component->isVisible() && PeekMessage (&m, hwnd, WM_PAINT, WM_PAINT, PM_REMOVE))
  207231. DispatchMessage (&m);
  207232. }
  207233. static Win32ComponentPeer* getOwnerOfWindow (HWND h) throw()
  207234. {
  207235. if (h != 0 && GetWindowLongPtr (h, GWLP_USERDATA) == improbableWindowNumber)
  207236. return (Win32ComponentPeer*) (pointer_sized_int) GetWindowLongPtr (h, 8);
  207237. return 0;
  207238. }
  207239. void setTaskBarIcon (const Image& image)
  207240. {
  207241. if (image.isValid())
  207242. {
  207243. HICON hicon = IconConverters::createHICONFromImage (image, TRUE, 0, 0);
  207244. if (taskBarIcon == 0)
  207245. {
  207246. taskBarIcon = new NOTIFYICONDATA();
  207247. taskBarIcon->cbSize = sizeof (NOTIFYICONDATA);
  207248. taskBarIcon->hWnd = (HWND) hwnd;
  207249. taskBarIcon->uID = (int) (pointer_sized_int) hwnd;
  207250. taskBarIcon->uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  207251. taskBarIcon->uCallbackMessage = WM_TRAYNOTIFY;
  207252. taskBarIcon->hIcon = hicon;
  207253. taskBarIcon->szTip[0] = 0;
  207254. Shell_NotifyIcon (NIM_ADD, taskBarIcon);
  207255. }
  207256. else
  207257. {
  207258. HICON oldIcon = taskBarIcon->hIcon;
  207259. taskBarIcon->hIcon = hicon;
  207260. taskBarIcon->uFlags = NIF_ICON;
  207261. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  207262. DestroyIcon (oldIcon);
  207263. }
  207264. DestroyIcon (hicon);
  207265. }
  207266. else if (taskBarIcon != 0)
  207267. {
  207268. taskBarIcon->uFlags = 0;
  207269. Shell_NotifyIcon (NIM_DELETE, taskBarIcon);
  207270. DestroyIcon (taskBarIcon->hIcon);
  207271. taskBarIcon = 0;
  207272. }
  207273. }
  207274. void setTaskBarIconToolTip (const String& toolTip) const
  207275. {
  207276. if (taskBarIcon != 0)
  207277. {
  207278. taskBarIcon->uFlags = NIF_TIP;
  207279. toolTip.copyToUnicode (taskBarIcon->szTip, sizeof (taskBarIcon->szTip) - 1);
  207280. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  207281. }
  207282. }
  207283. bool isInside (HWND h) const
  207284. {
  207285. return GetAncestor (hwnd, GA_ROOT) == h;
  207286. }
  207287. static void updateKeyModifiers() throw()
  207288. {
  207289. int keyMods = 0;
  207290. if (GetKeyState (VK_SHIFT) & 0x8000) keyMods |= ModifierKeys::shiftModifier;
  207291. if (GetKeyState (VK_CONTROL) & 0x8000) keyMods |= ModifierKeys::ctrlModifier;
  207292. if (GetKeyState (VK_MENU) & 0x8000) keyMods |= ModifierKeys::altModifier;
  207293. if (GetKeyState (VK_RMENU) & 0x8000) keyMods &= ~(ModifierKeys::ctrlModifier | ModifierKeys::altModifier);
  207294. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  207295. }
  207296. static void updateModifiersFromWParam (const WPARAM wParam)
  207297. {
  207298. int mouseMods = 0;
  207299. if (wParam & MK_LBUTTON) mouseMods |= ModifierKeys::leftButtonModifier;
  207300. if (wParam & MK_RBUTTON) mouseMods |= ModifierKeys::rightButtonModifier;
  207301. if (wParam & MK_MBUTTON) mouseMods |= ModifierKeys::middleButtonModifier;
  207302. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  207303. updateKeyModifiers();
  207304. }
  207305. static int64 getMouseEventTime()
  207306. {
  207307. static int64 eventTimeOffset = 0;
  207308. static DWORD lastMessageTime = 0;
  207309. const DWORD thisMessageTime = GetMessageTime();
  207310. if (thisMessageTime < lastMessageTime || lastMessageTime == 0)
  207311. {
  207312. lastMessageTime = thisMessageTime;
  207313. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  207314. }
  207315. return eventTimeOffset + thisMessageTime;
  207316. }
  207317. juce_UseDebuggingNewOperator
  207318. bool dontRepaint;
  207319. static ModifierKeys currentModifiers;
  207320. static ModifierKeys modifiersAtLastCallback;
  207321. private:
  207322. HWND hwnd, parentToAddTo;
  207323. ScopedPointer<DropShadower> shadower;
  207324. RenderingEngineType currentRenderingEngine;
  207325. #if JUCE_DIRECT2D
  207326. ScopedPointer<Direct2DLowLevelGraphicsContext> direct2DContext;
  207327. #endif
  207328. bool fullScreen, isDragging, isMouseOver, hasCreatedCaret;
  207329. BorderSize windowBorder;
  207330. HICON currentWindowIcon;
  207331. ScopedPointer<NOTIFYICONDATA> taskBarIcon;
  207332. IDropTarget* dropTarget;
  207333. uint8 updateLayeredWindowAlpha;
  207334. class TemporaryImage : public Timer
  207335. {
  207336. public:
  207337. TemporaryImage() {}
  207338. ~TemporaryImage() {}
  207339. const Image& getImage (const bool transparent, const int w, const int h)
  207340. {
  207341. const Image::PixelFormat format = transparent ? Image::ARGB : Image::RGB;
  207342. if ((! image.isValid()) || image.getWidth() < w || image.getHeight() < h || image.getFormat() != format)
  207343. image = Image (new WindowsBitmapImage (format, (w + 31) & ~31, (h + 31) & ~31, false));
  207344. startTimer (3000);
  207345. return image;
  207346. }
  207347. void timerCallback()
  207348. {
  207349. stopTimer();
  207350. image = Image::null;
  207351. }
  207352. private:
  207353. Image image;
  207354. TemporaryImage (const TemporaryImage&);
  207355. TemporaryImage& operator= (const TemporaryImage&);
  207356. };
  207357. TemporaryImage offscreenImageGenerator;
  207358. class WindowClassHolder : public DeletedAtShutdown
  207359. {
  207360. public:
  207361. WindowClassHolder()
  207362. : windowClassName ("JUCE_")
  207363. {
  207364. // this name has to be different for each app/dll instance because otherwise
  207365. // poor old Win32 can get a bit confused (even despite it not being a process-global
  207366. // window class).
  207367. windowClassName << (int) (Time::currentTimeMillis() & 0x7fffffff);
  207368. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  207369. TCHAR moduleFile [1024];
  207370. moduleFile[0] = 0;
  207371. GetModuleFileName (moduleHandle, moduleFile, 1024);
  207372. WORD iconNum = 0;
  207373. WNDCLASSEX wcex;
  207374. wcex.cbSize = sizeof (wcex);
  207375. wcex.style = CS_OWNDC;
  207376. wcex.lpfnWndProc = (WNDPROC) windowProc;
  207377. wcex.lpszClassName = windowClassName;
  207378. wcex.cbClsExtra = 0;
  207379. wcex.cbWndExtra = 32;
  207380. wcex.hInstance = moduleHandle;
  207381. wcex.hIcon = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  207382. iconNum = 1;
  207383. wcex.hIconSm = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  207384. wcex.hCursor = 0;
  207385. wcex.hbrBackground = 0;
  207386. wcex.lpszMenuName = 0;
  207387. RegisterClassEx (&wcex);
  207388. }
  207389. ~WindowClassHolder()
  207390. {
  207391. if (ComponentPeer::getNumPeers() == 0)
  207392. UnregisterClass (windowClassName, (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle());
  207393. clearSingletonInstance();
  207394. }
  207395. String windowClassName;
  207396. juce_DeclareSingleton_SingleThreaded_Minimal (WindowClassHolder);
  207397. };
  207398. static void* createWindowCallback (void* userData)
  207399. {
  207400. static_cast <Win32ComponentPeer*> (userData)->createWindow();
  207401. return 0;
  207402. }
  207403. void createWindow()
  207404. {
  207405. DWORD exstyle = WS_EX_ACCEPTFILES;
  207406. DWORD type = WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
  207407. if (hasTitleBar())
  207408. {
  207409. type |= WS_OVERLAPPED;
  207410. if ((styleFlags & windowHasCloseButton) != 0)
  207411. {
  207412. type |= WS_SYSMENU;
  207413. }
  207414. else
  207415. {
  207416. // annoyingly, windows won't let you have a min/max button without a close button
  207417. jassert ((styleFlags & (windowHasMinimiseButton | windowHasMaximiseButton)) == 0);
  207418. }
  207419. if ((styleFlags & windowIsResizable) != 0)
  207420. type |= WS_THICKFRAME;
  207421. }
  207422. else if (parentToAddTo != 0)
  207423. {
  207424. type |= WS_CHILD;
  207425. }
  207426. else
  207427. {
  207428. type |= WS_POPUP | WS_SYSMENU;
  207429. }
  207430. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  207431. exstyle |= WS_EX_TOOLWINDOW;
  207432. else
  207433. exstyle |= WS_EX_APPWINDOW;
  207434. if ((styleFlags & windowHasMinimiseButton) != 0)
  207435. type |= WS_MINIMIZEBOX;
  207436. if ((styleFlags & windowHasMaximiseButton) != 0)
  207437. type |= WS_MAXIMIZEBOX;
  207438. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  207439. exstyle |= WS_EX_TRANSPARENT;
  207440. if ((styleFlags & windowIsSemiTransparent) != 0
  207441. && Desktop::canUseSemiTransparentWindows())
  207442. exstyle |= WS_EX_LAYERED;
  207443. hwnd = CreateWindowEx (exstyle, WindowClassHolder::getInstance()->windowClassName, L"", type, 0, 0, 0, 0,
  207444. parentToAddTo, 0, (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(), 0);
  207445. #if JUCE_DIRECT2D
  207446. updateDirect2DContext();
  207447. #endif
  207448. if (hwnd != 0)
  207449. {
  207450. SetWindowLongPtr (hwnd, 0, 0);
  207451. SetWindowLongPtr (hwnd, 8, (LONG_PTR) this);
  207452. SetWindowLongPtr (hwnd, GWLP_USERDATA, improbableWindowNumber);
  207453. if (dropTarget == 0)
  207454. dropTarget = new JuceDropTarget (this);
  207455. RegisterDragDrop (hwnd, dropTarget);
  207456. updateBorderSize();
  207457. // Calling this function here is (for some reason) necessary to make Windows
  207458. // correctly enable the menu items that we specify in the wm_initmenu message.
  207459. GetSystemMenu (hwnd, false);
  207460. const float alpha = component->getAlpha();
  207461. if (alpha < 1.0f)
  207462. setAlpha (alpha);
  207463. }
  207464. else
  207465. {
  207466. jassertfalse;
  207467. }
  207468. }
  207469. static void* destroyWindowCallback (void* handle)
  207470. {
  207471. RevokeDragDrop ((HWND) handle);
  207472. DestroyWindow ((HWND) handle);
  207473. return 0;
  207474. }
  207475. static void* toFrontCallback1 (void* h)
  207476. {
  207477. SetForegroundWindow ((HWND) h);
  207478. return 0;
  207479. }
  207480. static void* toFrontCallback2 (void* h)
  207481. {
  207482. SetWindowPos ((HWND) h, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  207483. return 0;
  207484. }
  207485. static void* setFocusCallback (void* h)
  207486. {
  207487. SetFocus ((HWND) h);
  207488. return 0;
  207489. }
  207490. static void* getFocusCallback (void*)
  207491. {
  207492. return GetFocus();
  207493. }
  207494. void offsetWithinParent (int& x, int& y) const
  207495. {
  207496. if (isUsingUpdateLayeredWindow())
  207497. {
  207498. HWND parentHwnd = GetParent (hwnd);
  207499. if (parentHwnd != 0)
  207500. {
  207501. RECT parentRect;
  207502. GetWindowRect (parentHwnd, &parentRect);
  207503. x += parentRect.left;
  207504. y += parentRect.top;
  207505. }
  207506. }
  207507. }
  207508. bool isUsingUpdateLayeredWindow() const
  207509. {
  207510. return ! component->isOpaque();
  207511. }
  207512. inline bool hasTitleBar() const throw() { return (styleFlags & windowHasTitleBar) != 0; }
  207513. void setIcon (const Image& newIcon)
  207514. {
  207515. HICON hicon = IconConverters::createHICONFromImage (newIcon, TRUE, 0, 0);
  207516. if (hicon != 0)
  207517. {
  207518. SendMessage (hwnd, WM_SETICON, ICON_BIG, (LPARAM) hicon);
  207519. SendMessage (hwnd, WM_SETICON, ICON_SMALL, (LPARAM) hicon);
  207520. if (currentWindowIcon != 0)
  207521. DestroyIcon (currentWindowIcon);
  207522. currentWindowIcon = hicon;
  207523. }
  207524. }
  207525. void handlePaintMessage()
  207526. {
  207527. #if JUCE_DIRECT2D
  207528. if (direct2DContext != 0)
  207529. {
  207530. RECT r;
  207531. if (GetUpdateRect (hwnd, &r, false))
  207532. {
  207533. direct2DContext->start();
  207534. direct2DContext->clipToRectangle (Rectangle<int> (r.left, r.top, r.right - r.left, r.bottom - r.top));
  207535. handlePaint (*direct2DContext);
  207536. direct2DContext->end();
  207537. }
  207538. }
  207539. else
  207540. #endif
  207541. {
  207542. HRGN rgn = CreateRectRgn (0, 0, 0, 0);
  207543. const int regionType = GetUpdateRgn (hwnd, rgn, false);
  207544. PAINTSTRUCT paintStruct;
  207545. HDC dc = BeginPaint (hwnd, &paintStruct); // Note this can immediately generate a WM_NCPAINT
  207546. // message and become re-entrant, but that's OK
  207547. // if something in a paint handler calls, e.g. a message box, this can become reentrant and
  207548. // corrupt the image it's using to paint into, so do a check here.
  207549. static bool reentrant = false;
  207550. if (reentrant)
  207551. {
  207552. DeleteObject (rgn);
  207553. EndPaint (hwnd, &paintStruct);
  207554. return;
  207555. }
  207556. reentrant = true;
  207557. // this is the rectangle to update..
  207558. int x = paintStruct.rcPaint.left;
  207559. int y = paintStruct.rcPaint.top;
  207560. int w = paintStruct.rcPaint.right - x;
  207561. int h = paintStruct.rcPaint.bottom - y;
  207562. const bool transparent = isUsingUpdateLayeredWindow();
  207563. if (transparent)
  207564. {
  207565. // it's not possible to have a transparent window with a title bar at the moment!
  207566. jassert (! hasTitleBar());
  207567. RECT r;
  207568. GetWindowRect (hwnd, &r);
  207569. x = y = 0;
  207570. w = r.right - r.left;
  207571. h = r.bottom - r.top;
  207572. }
  207573. if (w > 0 && h > 0)
  207574. {
  207575. clearMaskedRegion();
  207576. Image offscreenImage (offscreenImageGenerator.getImage (transparent, w, h));
  207577. RectangleList contextClip;
  207578. const Rectangle<int> clipBounds (0, 0, w, h);
  207579. bool needToPaintAll = true;
  207580. if (regionType == COMPLEXREGION && ! transparent)
  207581. {
  207582. HRGN clipRgn = CreateRectRgnIndirect (&paintStruct.rcPaint);
  207583. CombineRgn (rgn, rgn, clipRgn, RGN_AND);
  207584. DeleteObject (clipRgn);
  207585. char rgnData [8192];
  207586. const DWORD res = GetRegionData (rgn, sizeof (rgnData), (RGNDATA*) rgnData);
  207587. if (res > 0 && res <= sizeof (rgnData))
  207588. {
  207589. const RGNDATAHEADER* const hdr = &(((const RGNDATA*) rgnData)->rdh);
  207590. if (hdr->iType == RDH_RECTANGLES
  207591. && hdr->rcBound.right - hdr->rcBound.left >= w
  207592. && hdr->rcBound.bottom - hdr->rcBound.top >= h)
  207593. {
  207594. needToPaintAll = false;
  207595. const RECT* rects = (const RECT*) (rgnData + sizeof (RGNDATAHEADER));
  207596. int num = ((RGNDATA*) rgnData)->rdh.nCount;
  207597. while (--num >= 0)
  207598. {
  207599. if (rects->right <= x + w && rects->bottom <= y + h)
  207600. {
  207601. const int cx = jmax (x, (int) rects->left);
  207602. contextClip.addWithoutMerging (Rectangle<int> (cx - x, rects->top - y, rects->right - cx, rects->bottom - rects->top)
  207603. .getIntersection (clipBounds));
  207604. }
  207605. else
  207606. {
  207607. needToPaintAll = true;
  207608. break;
  207609. }
  207610. ++rects;
  207611. }
  207612. }
  207613. }
  207614. }
  207615. if (needToPaintAll)
  207616. {
  207617. contextClip.clear();
  207618. contextClip.addWithoutMerging (Rectangle<int> (w, h));
  207619. }
  207620. if (transparent)
  207621. {
  207622. RectangleList::Iterator i (contextClip);
  207623. while (i.next())
  207624. offscreenImage.clear (*i.getRectangle());
  207625. }
  207626. // if the component's not opaque, this won't draw properly unless the platform can support this
  207627. jassert (Desktop::canUseSemiTransparentWindows() || component->isOpaque());
  207628. updateCurrentModifiers();
  207629. LowLevelGraphicsSoftwareRenderer context (offscreenImage, -x, -y, contextClip);
  207630. handlePaint (context);
  207631. if (! dontRepaint)
  207632. static_cast <WindowsBitmapImage*> (offscreenImage.getSharedImage())
  207633. ->blitToWindow (hwnd, dc, transparent, x, y, maskedRegion, updateLayeredWindowAlpha);
  207634. }
  207635. DeleteObject (rgn);
  207636. EndPaint (hwnd, &paintStruct);
  207637. reentrant = false;
  207638. }
  207639. #ifndef JUCE_GCC //xxx should add this fn for gcc..
  207640. _fpreset(); // because some graphics cards can unmask FP exceptions
  207641. #endif
  207642. lastPaintTime = Time::getMillisecondCounter();
  207643. }
  207644. void doMouseEvent (const Point<int>& position)
  207645. {
  207646. handleMouseEvent (0, position, currentModifiers, getMouseEventTime());
  207647. }
  207648. const StringArray getAvailableRenderingEngines()
  207649. {
  207650. StringArray s (ComponentPeer::getAvailableRenderingEngines());
  207651. #if JUCE_DIRECT2D
  207652. // xxx is this correct? Seems to enable it on Vista too??
  207653. OSVERSIONINFO info;
  207654. zerostruct (info);
  207655. info.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
  207656. GetVersionEx (&info);
  207657. if (info.dwMajorVersion >= 6)
  207658. s.add ("Direct2D");
  207659. #endif
  207660. return s;
  207661. }
  207662. int getCurrentRenderingEngine() throw()
  207663. {
  207664. return currentRenderingEngine;
  207665. }
  207666. #if JUCE_DIRECT2D
  207667. void updateDirect2DContext()
  207668. {
  207669. if (currentRenderingEngine != direct2DRenderingEngine)
  207670. direct2DContext = 0;
  207671. else if (direct2DContext == 0)
  207672. direct2DContext = new Direct2DLowLevelGraphicsContext (hwnd);
  207673. }
  207674. #endif
  207675. void setCurrentRenderingEngine (int index)
  207676. {
  207677. (void) index;
  207678. #if JUCE_DIRECT2D
  207679. currentRenderingEngine = index == 1 ? direct2DRenderingEngine : softwareRenderingEngine;
  207680. updateDirect2DContext();
  207681. repaint (component->getLocalBounds());
  207682. #endif
  207683. }
  207684. void doMouseMove (const Point<int>& position)
  207685. {
  207686. if (! isMouseOver)
  207687. {
  207688. isMouseOver = true;
  207689. updateKeyModifiers();
  207690. TRACKMOUSEEVENT tme;
  207691. tme.cbSize = sizeof (tme);
  207692. tme.dwFlags = TME_LEAVE;
  207693. tme.hwndTrack = hwnd;
  207694. tme.dwHoverTime = 0;
  207695. if (! TrackMouseEvent (&tme))
  207696. jassertfalse;
  207697. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  207698. }
  207699. else if (! isDragging)
  207700. {
  207701. if (! contains (position, false))
  207702. return;
  207703. }
  207704. // (Throttling the incoming queue of mouse-events seems to still be required in XP..)
  207705. static uint32 lastMouseTime = 0;
  207706. const uint32 now = Time::getMillisecondCounter();
  207707. const int maxMouseMovesPerSecond = 60;
  207708. if (now > lastMouseTime + 1000 / maxMouseMovesPerSecond)
  207709. {
  207710. lastMouseTime = now;
  207711. doMouseEvent (position);
  207712. }
  207713. }
  207714. void doMouseDown (const Point<int>& position, const WPARAM wParam)
  207715. {
  207716. if (GetCapture() != hwnd)
  207717. SetCapture (hwnd);
  207718. doMouseMove (position);
  207719. updateModifiersFromWParam (wParam);
  207720. isDragging = true;
  207721. doMouseEvent (position);
  207722. }
  207723. void doMouseUp (const Point<int>& position, const WPARAM wParam)
  207724. {
  207725. updateModifiersFromWParam (wParam);
  207726. isDragging = false;
  207727. // release the mouse capture if the user has released all buttons
  207728. if ((wParam & (MK_LBUTTON | MK_RBUTTON | MK_MBUTTON)) == 0 && hwnd == GetCapture())
  207729. ReleaseCapture();
  207730. doMouseEvent (position);
  207731. }
  207732. void doCaptureChanged()
  207733. {
  207734. if (isDragging)
  207735. doMouseUp (getCurrentMousePos(), (WPARAM) 0);
  207736. }
  207737. void doMouseExit()
  207738. {
  207739. isMouseOver = false;
  207740. doMouseEvent (getCurrentMousePos());
  207741. }
  207742. void doMouseWheel (const Point<int>& position, const WPARAM wParam, const bool isVertical)
  207743. {
  207744. updateKeyModifiers();
  207745. const float amount = jlimit (-1000.0f, 1000.0f, 0.75f * (short) HIWORD (wParam));
  207746. handleMouseWheel (0, position, getMouseEventTime(),
  207747. isVertical ? 0.0f : amount,
  207748. isVertical ? amount : 0.0f);
  207749. }
  207750. void sendModifierKeyChangeIfNeeded()
  207751. {
  207752. if (modifiersAtLastCallback != currentModifiers)
  207753. {
  207754. modifiersAtLastCallback = currentModifiers;
  207755. handleModifierKeysChange();
  207756. }
  207757. }
  207758. bool doKeyUp (const WPARAM key)
  207759. {
  207760. updateKeyModifiers();
  207761. switch (key)
  207762. {
  207763. case VK_SHIFT:
  207764. case VK_CONTROL:
  207765. case VK_MENU:
  207766. case VK_CAPITAL:
  207767. case VK_LWIN:
  207768. case VK_RWIN:
  207769. case VK_APPS:
  207770. case VK_NUMLOCK:
  207771. case VK_SCROLL:
  207772. case VK_LSHIFT:
  207773. case VK_RSHIFT:
  207774. case VK_LCONTROL:
  207775. case VK_LMENU:
  207776. case VK_RCONTROL:
  207777. case VK_RMENU:
  207778. sendModifierKeyChangeIfNeeded();
  207779. }
  207780. return handleKeyUpOrDown (false)
  207781. || Component::getCurrentlyModalComponent() != 0;
  207782. }
  207783. bool doKeyDown (const WPARAM key)
  207784. {
  207785. updateKeyModifiers();
  207786. bool used = false;
  207787. switch (key)
  207788. {
  207789. case VK_SHIFT:
  207790. case VK_LSHIFT:
  207791. case VK_RSHIFT:
  207792. case VK_CONTROL:
  207793. case VK_LCONTROL:
  207794. case VK_RCONTROL:
  207795. case VK_MENU:
  207796. case VK_LMENU:
  207797. case VK_RMENU:
  207798. case VK_LWIN:
  207799. case VK_RWIN:
  207800. case VK_CAPITAL:
  207801. case VK_NUMLOCK:
  207802. case VK_SCROLL:
  207803. case VK_APPS:
  207804. sendModifierKeyChangeIfNeeded();
  207805. break;
  207806. case VK_LEFT:
  207807. case VK_RIGHT:
  207808. case VK_UP:
  207809. case VK_DOWN:
  207810. case VK_PRIOR:
  207811. case VK_NEXT:
  207812. case VK_HOME:
  207813. case VK_END:
  207814. case VK_DELETE:
  207815. case VK_INSERT:
  207816. case VK_F1:
  207817. case VK_F2:
  207818. case VK_F3:
  207819. case VK_F4:
  207820. case VK_F5:
  207821. case VK_F6:
  207822. case VK_F7:
  207823. case VK_F8:
  207824. case VK_F9:
  207825. case VK_F10:
  207826. case VK_F11:
  207827. case VK_F12:
  207828. case VK_F13:
  207829. case VK_F14:
  207830. case VK_F15:
  207831. case VK_F16:
  207832. used = handleKeyUpOrDown (true);
  207833. used = handleKeyPress (extendedKeyModifier | (int) key, 0) || used;
  207834. break;
  207835. case VK_ADD:
  207836. case VK_SUBTRACT:
  207837. case VK_MULTIPLY:
  207838. case VK_DIVIDE:
  207839. case VK_SEPARATOR:
  207840. case VK_DECIMAL:
  207841. used = handleKeyUpOrDown (true);
  207842. break;
  207843. default:
  207844. used = handleKeyUpOrDown (true);
  207845. {
  207846. MSG msg;
  207847. if (! PeekMessage (&msg, hwnd, WM_CHAR, WM_DEADCHAR, PM_NOREMOVE))
  207848. {
  207849. // if there isn't a WM_CHAR or WM_DEADCHAR message pending, we need to
  207850. // manually generate the key-press event that matches this key-down.
  207851. const UINT keyChar = MapVirtualKey (key, 2);
  207852. used = handleKeyPress ((int) LOWORD (keyChar), 0) || used;
  207853. }
  207854. }
  207855. break;
  207856. }
  207857. if (Component::getCurrentlyModalComponent() != 0)
  207858. used = true;
  207859. return used;
  207860. }
  207861. bool doKeyChar (int key, const LPARAM flags)
  207862. {
  207863. updateKeyModifiers();
  207864. juce_wchar textChar = (juce_wchar) key;
  207865. const int virtualScanCode = (flags >> 16) & 0xff;
  207866. if (key >= '0' && key <= '9')
  207867. {
  207868. switch (virtualScanCode) // check for a numeric keypad scan-code
  207869. {
  207870. case 0x52:
  207871. case 0x4f:
  207872. case 0x50:
  207873. case 0x51:
  207874. case 0x4b:
  207875. case 0x4c:
  207876. case 0x4d:
  207877. case 0x47:
  207878. case 0x48:
  207879. case 0x49:
  207880. key = (key - '0') + KeyPress::numberPad0;
  207881. break;
  207882. default:
  207883. break;
  207884. }
  207885. }
  207886. else
  207887. {
  207888. // convert the scan code to an unmodified character code..
  207889. const UINT virtualKey = MapVirtualKey (virtualScanCode, 1);
  207890. UINT keyChar = MapVirtualKey (virtualKey, 2);
  207891. keyChar = LOWORD (keyChar);
  207892. if (keyChar != 0)
  207893. key = (int) keyChar;
  207894. // avoid sending junk text characters for some control-key combinations
  207895. if (textChar < ' ' && currentModifiers.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::altModifier))
  207896. textChar = 0;
  207897. }
  207898. return handleKeyPress (key, textChar);
  207899. }
  207900. bool doAppCommand (const LPARAM lParam)
  207901. {
  207902. int key = 0;
  207903. switch (GET_APPCOMMAND_LPARAM (lParam))
  207904. {
  207905. case APPCOMMAND_MEDIA_PLAY_PAUSE:
  207906. key = KeyPress::playKey;
  207907. break;
  207908. case APPCOMMAND_MEDIA_STOP:
  207909. key = KeyPress::stopKey;
  207910. break;
  207911. case APPCOMMAND_MEDIA_NEXTTRACK:
  207912. key = KeyPress::fastForwardKey;
  207913. break;
  207914. case APPCOMMAND_MEDIA_PREVIOUSTRACK:
  207915. key = KeyPress::rewindKey;
  207916. break;
  207917. }
  207918. if (key != 0)
  207919. {
  207920. updateKeyModifiers();
  207921. if (hwnd == GetActiveWindow())
  207922. {
  207923. handleKeyPress (key, 0);
  207924. return true;
  207925. }
  207926. }
  207927. return false;
  207928. }
  207929. class JuceDropTarget : public ComBaseClassHelper <IDropTarget>
  207930. {
  207931. public:
  207932. JuceDropTarget (Win32ComponentPeer* const owner_)
  207933. : owner (owner_)
  207934. {
  207935. }
  207936. ~JuceDropTarget() {}
  207937. HRESULT __stdcall DragEnter (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  207938. {
  207939. updateFileList (pDataObject);
  207940. owner->handleFileDragMove (files, owner->globalPositionToRelative (Point<int> (mousePos.x, mousePos.y)));
  207941. *pdwEffect = DROPEFFECT_COPY;
  207942. return S_OK;
  207943. }
  207944. HRESULT __stdcall DragLeave()
  207945. {
  207946. owner->handleFileDragExit (files);
  207947. return S_OK;
  207948. }
  207949. HRESULT __stdcall DragOver (DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  207950. {
  207951. owner->handleFileDragMove (files, owner->globalPositionToRelative (Point<int> (mousePos.x, mousePos.y)));
  207952. *pdwEffect = DROPEFFECT_COPY;
  207953. return S_OK;
  207954. }
  207955. HRESULT __stdcall Drop (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  207956. {
  207957. updateFileList (pDataObject);
  207958. owner->handleFileDragDrop (files, owner->globalPositionToRelative (Point<int> (mousePos.x, mousePos.y)));
  207959. *pdwEffect = DROPEFFECT_COPY;
  207960. return S_OK;
  207961. }
  207962. private:
  207963. Win32ComponentPeer* const owner;
  207964. StringArray files;
  207965. void updateFileList (IDataObject* const pDataObject)
  207966. {
  207967. files.clear();
  207968. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  207969. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  207970. if (pDataObject->GetData (&format, &medium) == S_OK)
  207971. {
  207972. const SIZE_T totalLen = GlobalSize (medium.hGlobal);
  207973. const LPDROPFILES pDropFiles = (const LPDROPFILES) GlobalLock (medium.hGlobal);
  207974. unsigned int i = 0;
  207975. if (pDropFiles->fWide)
  207976. {
  207977. const WCHAR* const fname = (WCHAR*) (((const char*) pDropFiles) + sizeof (DROPFILES));
  207978. for (;;)
  207979. {
  207980. unsigned int len = 0;
  207981. while (i + len < totalLen && fname [i + len] != 0)
  207982. ++len;
  207983. if (len == 0)
  207984. break;
  207985. files.add (String (fname + i, len));
  207986. i += len + 1;
  207987. }
  207988. }
  207989. else
  207990. {
  207991. const char* const fname = ((const char*) pDropFiles) + sizeof (DROPFILES);
  207992. for (;;)
  207993. {
  207994. unsigned int len = 0;
  207995. while (i + len < totalLen && fname [i + len] != 0)
  207996. ++len;
  207997. if (len == 0)
  207998. break;
  207999. files.add (String (fname + i, len));
  208000. i += len + 1;
  208001. }
  208002. }
  208003. GlobalUnlock (medium.hGlobal);
  208004. }
  208005. }
  208006. JuceDropTarget (const JuceDropTarget&);
  208007. JuceDropTarget& operator= (const JuceDropTarget&);
  208008. };
  208009. void doSettingChange()
  208010. {
  208011. Desktop::getInstance().refreshMonitorSizes();
  208012. if (fullScreen && ! isMinimised())
  208013. {
  208014. const Rectangle<int> r (component->getParentMonitorArea());
  208015. SetWindowPos (hwnd, 0,
  208016. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  208017. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOSENDCHANGING);
  208018. }
  208019. }
  208020. public:
  208021. static LRESULT CALLBACK windowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  208022. {
  208023. Win32ComponentPeer* const peer = getOwnerOfWindow (h);
  208024. if (peer != 0)
  208025. return peer->peerWindowProc (h, message, wParam, lParam);
  208026. return DefWindowProcW (h, message, wParam, lParam);
  208027. }
  208028. private:
  208029. static void* callFunctionIfNotLocked (MessageCallbackFunction* callback, void* userData)
  208030. {
  208031. if (MessageManager::getInstance()->currentThreadHasLockedMessageManager())
  208032. return callback (userData);
  208033. else
  208034. return MessageManager::getInstance()->callFunctionOnMessageThread (callback, userData);
  208035. }
  208036. static const Point<int> getPointFromLParam (LPARAM lParam) throw()
  208037. {
  208038. return Point<int> (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam));
  208039. }
  208040. const Point<int> getCurrentMousePos() throw()
  208041. {
  208042. RECT wr;
  208043. GetWindowRect (hwnd, &wr);
  208044. const DWORD mp = GetMessagePos();
  208045. return Point<int> (GET_X_LPARAM (mp) - wr.left - windowBorder.getLeft(),
  208046. GET_Y_LPARAM (mp) - wr.top - windowBorder.getTop());
  208047. }
  208048. LRESULT peerWindowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  208049. {
  208050. if (isValidPeer (this))
  208051. {
  208052. switch (message)
  208053. {
  208054. case WM_NCHITTEST:
  208055. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  208056. return HTTRANSPARENT;
  208057. if (hasTitleBar())
  208058. break;
  208059. return HTCLIENT;
  208060. case WM_PAINT:
  208061. handlePaintMessage();
  208062. return 0;
  208063. case WM_NCPAINT:
  208064. if (wParam != 1)
  208065. handlePaintMessage();
  208066. if (hasTitleBar())
  208067. break;
  208068. return 0;
  208069. case WM_ERASEBKGND:
  208070. case WM_NCCALCSIZE:
  208071. if (hasTitleBar())
  208072. break;
  208073. return 1;
  208074. case WM_MOUSEMOVE:
  208075. doMouseMove (getPointFromLParam (lParam));
  208076. return 0;
  208077. case WM_MOUSELEAVE:
  208078. doMouseExit();
  208079. return 0;
  208080. case WM_LBUTTONDOWN:
  208081. case WM_MBUTTONDOWN:
  208082. case WM_RBUTTONDOWN:
  208083. doMouseDown (getPointFromLParam (lParam), wParam);
  208084. return 0;
  208085. case WM_LBUTTONUP:
  208086. case WM_MBUTTONUP:
  208087. case WM_RBUTTONUP:
  208088. doMouseUp (getPointFromLParam (lParam), wParam);
  208089. return 0;
  208090. case WM_CAPTURECHANGED:
  208091. doCaptureChanged();
  208092. return 0;
  208093. case WM_NCMOUSEMOVE:
  208094. if (hasTitleBar())
  208095. break;
  208096. return 0;
  208097. case 0x020A: /* WM_MOUSEWHEEL */
  208098. doMouseWheel (getCurrentMousePos(), wParam, true);
  208099. return 0;
  208100. case 0x020E: /* WM_MOUSEHWHEEL */
  208101. doMouseWheel (getCurrentMousePos(), wParam, false);
  208102. return 0;
  208103. case WM_SIZING:
  208104. if (constrainer != 0 && (styleFlags & (windowHasTitleBar | windowIsResizable)) == (windowHasTitleBar | windowIsResizable))
  208105. {
  208106. RECT* const r = (RECT*) lParam;
  208107. Rectangle<int> pos (r->left, r->top, r->right - r->left, r->bottom - r->top);
  208108. constrainer->checkBounds (pos, windowBorder.addedTo (component->getBounds()),
  208109. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  208110. wParam == WMSZ_TOP || wParam == WMSZ_TOPLEFT || wParam == WMSZ_TOPRIGHT,
  208111. wParam == WMSZ_LEFT || wParam == WMSZ_TOPLEFT || wParam == WMSZ_BOTTOMLEFT,
  208112. wParam == WMSZ_BOTTOM || wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_BOTTOMRIGHT,
  208113. wParam == WMSZ_RIGHT || wParam == WMSZ_TOPRIGHT || wParam == WMSZ_BOTTOMRIGHT);
  208114. r->left = pos.getX();
  208115. r->top = pos.getY();
  208116. r->right = pos.getRight();
  208117. r->bottom = pos.getBottom();
  208118. }
  208119. return TRUE;
  208120. case WM_WINDOWPOSCHANGING:
  208121. if (constrainer != 0 && (styleFlags & (windowHasTitleBar | windowIsResizable)) == (windowHasTitleBar | windowIsResizable))
  208122. {
  208123. WINDOWPOS* const wp = (WINDOWPOS*) lParam;
  208124. if ((wp->flags & (SWP_NOMOVE | SWP_NOSIZE)) != (SWP_NOMOVE | SWP_NOSIZE)
  208125. && ! Component::isMouseButtonDownAnywhere())
  208126. {
  208127. Rectangle<int> pos (wp->x, wp->y, wp->cx, wp->cy);
  208128. const Rectangle<int> current (windowBorder.addedTo (component->getBounds()));
  208129. constrainer->checkBounds (pos, current,
  208130. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  208131. pos.getY() != current.getY() && pos.getBottom() == current.getBottom(),
  208132. pos.getX() != current.getX() && pos.getRight() == current.getRight(),
  208133. pos.getY() == current.getY() && pos.getBottom() != current.getBottom(),
  208134. pos.getX() == current.getX() && pos.getRight() != current.getRight());
  208135. wp->x = pos.getX();
  208136. wp->y = pos.getY();
  208137. wp->cx = pos.getWidth();
  208138. wp->cy = pos.getHeight();
  208139. }
  208140. }
  208141. return 0;
  208142. case WM_WINDOWPOSCHANGED:
  208143. {
  208144. const Point<int> pos (getCurrentMousePos());
  208145. if (contains (pos, false))
  208146. doMouseEvent (pos);
  208147. }
  208148. handleMovedOrResized();
  208149. if (dontRepaint)
  208150. break; // needed for non-accelerated openGL windows to draw themselves correctly..
  208151. return 0;
  208152. case WM_KEYDOWN:
  208153. case WM_SYSKEYDOWN:
  208154. if (doKeyDown (wParam))
  208155. return 0;
  208156. break;
  208157. case WM_KEYUP:
  208158. case WM_SYSKEYUP:
  208159. if (doKeyUp (wParam))
  208160. return 0;
  208161. break;
  208162. case WM_CHAR:
  208163. if (doKeyChar ((int) wParam, lParam))
  208164. return 0;
  208165. break;
  208166. case WM_APPCOMMAND:
  208167. if (doAppCommand (lParam))
  208168. return TRUE;
  208169. break;
  208170. case WM_SETFOCUS:
  208171. updateKeyModifiers();
  208172. handleFocusGain();
  208173. break;
  208174. case WM_KILLFOCUS:
  208175. if (hasCreatedCaret)
  208176. {
  208177. hasCreatedCaret = false;
  208178. DestroyCaret();
  208179. }
  208180. handleFocusLoss();
  208181. break;
  208182. case WM_ACTIVATEAPP:
  208183. // Windows does weird things to process priority when you swap apps,
  208184. // so this forces an update when the app is brought to the front
  208185. if (wParam != FALSE)
  208186. juce_repeatLastProcessPriority();
  208187. else
  208188. Desktop::getInstance().setKioskModeComponent (0); // turn kiosk mode off if we lose focus
  208189. juce_CheckCurrentlyFocusedTopLevelWindow();
  208190. modifiersAtLastCallback = -1;
  208191. return 0;
  208192. case WM_ACTIVATE:
  208193. if (LOWORD (wParam) == WA_ACTIVE || LOWORD (wParam) == WA_CLICKACTIVE)
  208194. {
  208195. modifiersAtLastCallback = -1;
  208196. updateKeyModifiers();
  208197. if (isMinimised())
  208198. {
  208199. component->repaint();
  208200. handleMovedOrResized();
  208201. if (! ComponentPeer::isValidPeer (this))
  208202. return 0;
  208203. }
  208204. if (LOWORD (wParam) == WA_CLICKACTIVE
  208205. && component->isCurrentlyBlockedByAnotherModalComponent())
  208206. {
  208207. const Point<int> mousePos (component->getMouseXYRelative());
  208208. Component* const underMouse = component->getComponentAt (mousePos.getX(), mousePos.getY());
  208209. if (underMouse != 0 && underMouse->isCurrentlyBlockedByAnotherModalComponent())
  208210. Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  208211. return 0;
  208212. }
  208213. handleBroughtToFront();
  208214. if (component->isCurrentlyBlockedByAnotherModalComponent())
  208215. Component::getCurrentlyModalComponent()->toFront (true);
  208216. return 0;
  208217. }
  208218. break;
  208219. case WM_NCACTIVATE:
  208220. // while a temporary window is being shown, prevent Windows from deactivating the
  208221. // title bars of our main windows.
  208222. if (wParam == 0 && ! shouldDeactivateTitleBar)
  208223. wParam = TRUE; // change this and let it get passed to the DefWindowProc.
  208224. break;
  208225. case WM_MOUSEACTIVATE:
  208226. if (! component->getMouseClickGrabsKeyboardFocus())
  208227. return MA_NOACTIVATE;
  208228. break;
  208229. case WM_SHOWWINDOW:
  208230. if (wParam != 0)
  208231. handleBroughtToFront();
  208232. break;
  208233. case WM_CLOSE:
  208234. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  208235. handleUserClosingWindow();
  208236. return 0;
  208237. case WM_QUERYENDSESSION:
  208238. if (JUCEApplication::getInstance() != 0)
  208239. {
  208240. JUCEApplication::getInstance()->systemRequestedQuit();
  208241. return MessageManager::getInstance()->hasStopMessageBeenSent();
  208242. }
  208243. return TRUE;
  208244. case WM_TRAYNOTIFY:
  208245. if (component->isCurrentlyBlockedByAnotherModalComponent())
  208246. {
  208247. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN
  208248. || lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  208249. {
  208250. Component* const current = Component::getCurrentlyModalComponent();
  208251. if (current != 0)
  208252. current->inputAttemptWhenModal();
  208253. }
  208254. }
  208255. else
  208256. {
  208257. ModifierKeys eventMods (ModifierKeys::getCurrentModifiersRealtime());
  208258. if (lParam == WM_LBUTTONDOWN || lParam == WM_LBUTTONDBLCLK)
  208259. eventMods = eventMods.withFlags (ModifierKeys::leftButtonModifier);
  208260. else if (lParam == WM_RBUTTONDOWN || lParam == WM_RBUTTONDBLCLK)
  208261. eventMods = eventMods.withFlags (ModifierKeys::rightButtonModifier);
  208262. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  208263. eventMods = eventMods.withoutMouseButtons();
  208264. const MouseEvent e (Desktop::getInstance().getMainMouseSource(),
  208265. Point<int>(), eventMods, component, component, getMouseEventTime(),
  208266. Point<int>(), getMouseEventTime(), 1, false);
  208267. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN)
  208268. {
  208269. SetFocus (hwnd);
  208270. SetForegroundWindow (hwnd);
  208271. component->mouseDown (e);
  208272. }
  208273. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  208274. {
  208275. component->mouseUp (e);
  208276. }
  208277. else if (lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  208278. {
  208279. component->mouseDoubleClick (e);
  208280. }
  208281. else if (lParam == WM_MOUSEMOVE)
  208282. {
  208283. component->mouseMove (e);
  208284. }
  208285. }
  208286. break;
  208287. case WM_SYNCPAINT:
  208288. return 0;
  208289. case WM_PALETTECHANGED:
  208290. InvalidateRect (h, 0, 0);
  208291. break;
  208292. case WM_DISPLAYCHANGE:
  208293. InvalidateRect (h, 0, 0);
  208294. createPaletteIfNeeded = true;
  208295. // intentional fall-through...
  208296. case WM_SETTINGCHANGE: // note the fall-through in the previous case!
  208297. doSettingChange();
  208298. break;
  208299. case WM_INITMENU:
  208300. if (! hasTitleBar())
  208301. {
  208302. if (isFullScreen())
  208303. {
  208304. EnableMenuItem ((HMENU) wParam, SC_RESTORE, MF_BYCOMMAND | MF_ENABLED);
  208305. EnableMenuItem ((HMENU) wParam, SC_MOVE, MF_BYCOMMAND | MF_GRAYED);
  208306. }
  208307. else if (! isMinimised())
  208308. {
  208309. EnableMenuItem ((HMENU) wParam, SC_MAXIMIZE, MF_BYCOMMAND | MF_GRAYED);
  208310. }
  208311. }
  208312. break;
  208313. case WM_SYSCOMMAND:
  208314. switch (wParam & 0xfff0)
  208315. {
  208316. case SC_CLOSE:
  208317. if (sendInputAttemptWhenModalMessage())
  208318. return 0;
  208319. if (hasTitleBar())
  208320. {
  208321. PostMessage (h, WM_CLOSE, 0, 0);
  208322. return 0;
  208323. }
  208324. break;
  208325. case SC_KEYMENU:
  208326. // (NB mustn't call sendInputAttemptWhenModalMessage() here because of very
  208327. // obscure situations that can arise if a modal loop is started from an alt-key
  208328. // keypress).
  208329. if (hasTitleBar() && h == GetCapture())
  208330. ReleaseCapture();
  208331. break;
  208332. case SC_MAXIMIZE:
  208333. if (sendInputAttemptWhenModalMessage())
  208334. return 0;
  208335. setFullScreen (true);
  208336. return 0;
  208337. case SC_MINIMIZE:
  208338. if (sendInputAttemptWhenModalMessage())
  208339. return 0;
  208340. if (! hasTitleBar())
  208341. {
  208342. setMinimised (true);
  208343. return 0;
  208344. }
  208345. break;
  208346. case SC_RESTORE:
  208347. if (sendInputAttemptWhenModalMessage())
  208348. return 0;
  208349. if (hasTitleBar())
  208350. {
  208351. if (isFullScreen())
  208352. {
  208353. setFullScreen (false);
  208354. return 0;
  208355. }
  208356. }
  208357. else
  208358. {
  208359. if (isMinimised())
  208360. setMinimised (false);
  208361. else if (isFullScreen())
  208362. setFullScreen (false);
  208363. return 0;
  208364. }
  208365. break;
  208366. }
  208367. break;
  208368. case WM_NCLBUTTONDOWN:
  208369. case WM_NCRBUTTONDOWN:
  208370. case WM_NCMBUTTONDOWN:
  208371. sendInputAttemptWhenModalMessage();
  208372. break;
  208373. //case WM_IME_STARTCOMPOSITION;
  208374. // return 0;
  208375. case WM_GETDLGCODE:
  208376. return DLGC_WANTALLKEYS;
  208377. default:
  208378. break;
  208379. }
  208380. }
  208381. return DefWindowProcW (h, message, wParam, lParam);
  208382. }
  208383. bool sendInputAttemptWhenModalMessage()
  208384. {
  208385. if (component->isCurrentlyBlockedByAnotherModalComponent())
  208386. {
  208387. Component* const current = Component::getCurrentlyModalComponent();
  208388. if (current != 0)
  208389. current->inputAttemptWhenModal();
  208390. return true;
  208391. }
  208392. return false;
  208393. }
  208394. Win32ComponentPeer (const Win32ComponentPeer&);
  208395. Win32ComponentPeer& operator= (const Win32ComponentPeer&);
  208396. };
  208397. ModifierKeys Win32ComponentPeer::currentModifiers;
  208398. ModifierKeys Win32ComponentPeer::modifiersAtLastCallback;
  208399. ComponentPeer* Component::createNewPeer (int styleFlags, void* nativeWindowToAttachTo)
  208400. {
  208401. return new Win32ComponentPeer (this, styleFlags, (HWND) nativeWindowToAttachTo);
  208402. }
  208403. juce_ImplementSingleton_SingleThreaded (Win32ComponentPeer::WindowClassHolder);
  208404. void ModifierKeys::updateCurrentModifiers() throw()
  208405. {
  208406. currentModifiers = Win32ComponentPeer::currentModifiers;
  208407. }
  208408. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  208409. {
  208410. Win32ComponentPeer::updateKeyModifiers();
  208411. int mouseMods = 0;
  208412. if ((GetKeyState (VK_LBUTTON) & 0x8000) != 0) mouseMods |= ModifierKeys::leftButtonModifier;
  208413. if ((GetKeyState (VK_RBUTTON) & 0x8000) != 0) mouseMods |= ModifierKeys::rightButtonModifier;
  208414. if ((GetKeyState (VK_MBUTTON) & 0x8000) != 0) mouseMods |= ModifierKeys::middleButtonModifier;
  208415. Win32ComponentPeer::currentModifiers
  208416. = Win32ComponentPeer::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  208417. return Win32ComponentPeer::currentModifiers;
  208418. }
  208419. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  208420. {
  208421. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  208422. if (wp != 0)
  208423. wp->setTaskBarIcon (newImage);
  208424. }
  208425. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  208426. {
  208427. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  208428. if (wp != 0)
  208429. wp->setTaskBarIconToolTip (tooltip);
  208430. }
  208431. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw()
  208432. {
  208433. DWORD val = GetWindowLong (h, styleType);
  208434. if (bitIsSet)
  208435. val |= feature;
  208436. else
  208437. val &= ~feature;
  208438. SetWindowLongPtr (h, styleType, val);
  208439. SetWindowPos (h, 0, 0, 0, 0, 0,
  208440. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER
  208441. | SWP_NOOWNERZORDER | SWP_FRAMECHANGED | SWP_NOSENDCHANGING);
  208442. }
  208443. bool Process::isForegroundProcess()
  208444. {
  208445. HWND fg = GetForegroundWindow();
  208446. if (fg == 0)
  208447. return true;
  208448. // when running as a plugin in IE8, the browser UI runs in a different process to the plugin, so
  208449. // process ID isn't a reliable way to check if the foreground window belongs to us - instead, we
  208450. // have to see if any of our windows are children of the foreground window
  208451. fg = GetAncestor (fg, GA_ROOT);
  208452. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  208453. {
  208454. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (ComponentPeer::getPeer (i));
  208455. if (wp != 0 && wp->isInside (fg))
  208456. return true;
  208457. }
  208458. return false;
  208459. }
  208460. bool AlertWindow::showNativeDialogBox (const String& title,
  208461. const String& bodyText,
  208462. bool isOkCancel)
  208463. {
  208464. return MessageBox (0, bodyText, title,
  208465. MB_SETFOREGROUND | (isOkCancel ? MB_OKCANCEL
  208466. : MB_OK)) == IDOK;
  208467. }
  208468. void Desktop::createMouseInputSources()
  208469. {
  208470. mouseSources.add (new MouseInputSource (0, true));
  208471. }
  208472. const Point<int> Desktop::getMousePosition()
  208473. {
  208474. POINT mousePos;
  208475. GetCursorPos (&mousePos);
  208476. return Point<int> (mousePos.x, mousePos.y);
  208477. }
  208478. void Desktop::setMousePosition (const Point<int>& newPosition)
  208479. {
  208480. SetCursorPos (newPosition.getX(), newPosition.getY());
  208481. }
  208482. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  208483. {
  208484. return createSoftwareImage (format, width, height, clearImage);
  208485. }
  208486. class ScreenSaverDefeater : public Timer,
  208487. public DeletedAtShutdown
  208488. {
  208489. public:
  208490. ScreenSaverDefeater()
  208491. {
  208492. startTimer (10000);
  208493. timerCallback();
  208494. }
  208495. ~ScreenSaverDefeater() {}
  208496. void timerCallback()
  208497. {
  208498. if (Process::isForegroundProcess())
  208499. {
  208500. // simulate a shift key getting pressed..
  208501. INPUT input[2];
  208502. input[0].type = INPUT_KEYBOARD;
  208503. input[0].ki.wVk = VK_SHIFT;
  208504. input[0].ki.dwFlags = 0;
  208505. input[0].ki.dwExtraInfo = 0;
  208506. input[1].type = INPUT_KEYBOARD;
  208507. input[1].ki.wVk = VK_SHIFT;
  208508. input[1].ki.dwFlags = KEYEVENTF_KEYUP;
  208509. input[1].ki.dwExtraInfo = 0;
  208510. SendInput (2, input, sizeof (INPUT));
  208511. }
  208512. }
  208513. };
  208514. static ScreenSaverDefeater* screenSaverDefeater = 0;
  208515. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  208516. {
  208517. if (isEnabled)
  208518. deleteAndZero (screenSaverDefeater);
  208519. else if (screenSaverDefeater == 0)
  208520. screenSaverDefeater = new ScreenSaverDefeater();
  208521. }
  208522. bool Desktop::isScreenSaverEnabled()
  208523. {
  208524. return screenSaverDefeater == 0;
  208525. }
  208526. /* (The code below is the "correct" way to disable the screen saver, but it
  208527. completely fails on winXP when the saver is password-protected...)
  208528. static bool juce_screenSaverEnabled = true;
  208529. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  208530. {
  208531. juce_screenSaverEnabled = isEnabled;
  208532. SetThreadExecutionState (isEnabled ? ES_CONTINUOUS
  208533. : (ES_DISPLAY_REQUIRED | ES_CONTINUOUS));
  208534. }
  208535. bool Desktop::isScreenSaverEnabled() throw()
  208536. {
  208537. return juce_screenSaverEnabled;
  208538. }
  208539. */
  208540. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool /*allowMenusAndBars*/)
  208541. {
  208542. if (enableOrDisable)
  208543. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  208544. }
  208545. static BOOL CALLBACK enumMonitorsProc (HMONITOR, HDC, LPRECT r, LPARAM userInfo)
  208546. {
  208547. Array <Rectangle<int> >* const monitorCoords = (Array <Rectangle<int> >*) userInfo;
  208548. monitorCoords->add (Rectangle<int> (r->left, r->top, r->right - r->left, r->bottom - r->top));
  208549. return TRUE;
  208550. }
  208551. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  208552. {
  208553. EnumDisplayMonitors (0, 0, &enumMonitorsProc, (LPARAM) &monitorCoords);
  208554. // make sure the first in the list is the main monitor
  208555. for (int i = 1; i < monitorCoords.size(); ++i)
  208556. if (monitorCoords[i].getX() == 0 && monitorCoords[i].getY() == 0)
  208557. monitorCoords.swap (i, 0);
  208558. if (monitorCoords.size() == 0)
  208559. {
  208560. RECT r;
  208561. GetWindowRect (GetDesktopWindow(), &r);
  208562. monitorCoords.add (Rectangle<int> (r.left, r.top, r.right - r.left, r.bottom - r.top));
  208563. }
  208564. if (clipToWorkArea)
  208565. {
  208566. // clip the main monitor to the active non-taskbar area
  208567. RECT r;
  208568. SystemParametersInfo (SPI_GETWORKAREA, 0, &r, 0);
  208569. Rectangle<int>& screen = monitorCoords.getReference (0);
  208570. screen.setPosition (jmax (screen.getX(), (int) r.left),
  208571. jmax (screen.getY(), (int) r.top));
  208572. screen.setSize (jmin (screen.getRight(), (int) r.right) - screen.getX(),
  208573. jmin (screen.getBottom(), (int) r.bottom) - screen.getY());
  208574. }
  208575. }
  208576. const Image juce_createIconForFile (const File& file)
  208577. {
  208578. Image image;
  208579. WCHAR filename [1024];
  208580. file.getFullPathName().copyToUnicode (filename, 1023);
  208581. WORD iconNum = 0;
  208582. HICON icon = ExtractAssociatedIcon ((HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(),
  208583. filename, &iconNum);
  208584. if (icon != 0)
  208585. {
  208586. image = IconConverters::createImageFromHICON (icon);
  208587. DestroyIcon (icon);
  208588. }
  208589. return image;
  208590. }
  208591. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  208592. {
  208593. const int maxW = GetSystemMetrics (SM_CXCURSOR);
  208594. const int maxH = GetSystemMetrics (SM_CYCURSOR);
  208595. Image im (image);
  208596. if (im.getWidth() > maxW || im.getHeight() > maxH)
  208597. {
  208598. im = im.rescaled (maxW, maxH);
  208599. hotspotX = (hotspotX * maxW) / image.getWidth();
  208600. hotspotY = (hotspotY * maxH) / image.getHeight();
  208601. }
  208602. return IconConverters::createHICONFromImage (im, FALSE, hotspotX, hotspotY);
  208603. }
  208604. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard)
  208605. {
  208606. if (cursorHandle != 0 && ! isStandard)
  208607. DestroyCursor ((HCURSOR) cursorHandle);
  208608. }
  208609. void* MouseCursor::createStandardMouseCursor (const MouseCursor::StandardCursorType type)
  208610. {
  208611. LPCTSTR cursorName = IDC_ARROW;
  208612. switch (type)
  208613. {
  208614. case NormalCursor: break;
  208615. case NoCursor: return 0;
  208616. case WaitCursor: cursorName = IDC_WAIT; break;
  208617. case IBeamCursor: cursorName = IDC_IBEAM; break;
  208618. case PointingHandCursor: cursorName = MAKEINTRESOURCE(32649); break;
  208619. case CrosshairCursor: cursorName = IDC_CROSS; break;
  208620. case CopyingCursor: break; // can't seem to find one of these in the win32 list..
  208621. case LeftRightResizeCursor:
  208622. case LeftEdgeResizeCursor:
  208623. case RightEdgeResizeCursor: cursorName = IDC_SIZEWE; break;
  208624. case UpDownResizeCursor:
  208625. case TopEdgeResizeCursor:
  208626. case BottomEdgeResizeCursor: cursorName = IDC_SIZENS; break;
  208627. case TopLeftCornerResizeCursor:
  208628. case BottomRightCornerResizeCursor: cursorName = IDC_SIZENWSE; break;
  208629. case TopRightCornerResizeCursor:
  208630. case BottomLeftCornerResizeCursor: cursorName = IDC_SIZENESW; break;
  208631. case UpDownLeftRightResizeCursor: cursorName = IDC_SIZEALL; break;
  208632. case DraggingHandCursor:
  208633. {
  208634. static void* dragHandCursor = 0;
  208635. if (dragHandCursor == 0)
  208636. {
  208637. static const unsigned char dragHandData[] =
  208638. { 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,
  208639. 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,
  208640. 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 };
  208641. dragHandCursor = createMouseCursorFromImage (ImageFileFormat::loadFrom (dragHandData, sizeof (dragHandData)), 8, 7);
  208642. }
  208643. return dragHandCursor;
  208644. }
  208645. default:
  208646. jassertfalse; break;
  208647. }
  208648. HCURSOR cursorH = LoadCursor (0, cursorName);
  208649. if (cursorH == 0)
  208650. cursorH = LoadCursor (0, IDC_ARROW);
  208651. return cursorH;
  208652. }
  208653. void MouseCursor::showInWindow (ComponentPeer*) const
  208654. {
  208655. HCURSOR c = (HCURSOR) getHandle();
  208656. if (c == 0)
  208657. c = LoadCursor (0, IDC_ARROW);
  208658. SetCursor (c);
  208659. }
  208660. void MouseCursor::showInAllWindows() const
  208661. {
  208662. showInWindow (0);
  208663. }
  208664. class JuceDropSource : public ComBaseClassHelper <IDropSource>
  208665. {
  208666. public:
  208667. JuceDropSource() {}
  208668. ~JuceDropSource() {}
  208669. HRESULT __stdcall QueryContinueDrag (BOOL escapePressed, DWORD keys)
  208670. {
  208671. if (escapePressed)
  208672. return DRAGDROP_S_CANCEL;
  208673. if ((keys & (MK_LBUTTON | MK_RBUTTON)) == 0)
  208674. return DRAGDROP_S_DROP;
  208675. return S_OK;
  208676. }
  208677. HRESULT __stdcall GiveFeedback (DWORD)
  208678. {
  208679. return DRAGDROP_S_USEDEFAULTCURSORS;
  208680. }
  208681. };
  208682. class JuceEnumFormatEtc : public ComBaseClassHelper <IEnumFORMATETC>
  208683. {
  208684. public:
  208685. JuceEnumFormatEtc (const FORMATETC* const format_)
  208686. : format (format_),
  208687. index (0)
  208688. {
  208689. }
  208690. ~JuceEnumFormatEtc() {}
  208691. HRESULT __stdcall Clone (IEnumFORMATETC** result)
  208692. {
  208693. if (result == 0)
  208694. return E_POINTER;
  208695. JuceEnumFormatEtc* const newOne = new JuceEnumFormatEtc (format);
  208696. newOne->index = index;
  208697. *result = newOne;
  208698. return S_OK;
  208699. }
  208700. HRESULT __stdcall Next (ULONG celt, LPFORMATETC lpFormatEtc, ULONG* pceltFetched)
  208701. {
  208702. if (pceltFetched != 0)
  208703. *pceltFetched = 0;
  208704. else if (celt != 1)
  208705. return S_FALSE;
  208706. if (index == 0 && celt > 0 && lpFormatEtc != 0)
  208707. {
  208708. copyFormatEtc (lpFormatEtc [0], *format);
  208709. ++index;
  208710. if (pceltFetched != 0)
  208711. *pceltFetched = 1;
  208712. return S_OK;
  208713. }
  208714. return S_FALSE;
  208715. }
  208716. HRESULT __stdcall Skip (ULONG celt)
  208717. {
  208718. if (index + (int) celt >= 1)
  208719. return S_FALSE;
  208720. index += celt;
  208721. return S_OK;
  208722. }
  208723. HRESULT __stdcall Reset()
  208724. {
  208725. index = 0;
  208726. return S_OK;
  208727. }
  208728. private:
  208729. const FORMATETC* const format;
  208730. int index;
  208731. static void copyFormatEtc (FORMATETC& dest, const FORMATETC& source)
  208732. {
  208733. dest = source;
  208734. if (source.ptd != 0)
  208735. {
  208736. dest.ptd = (DVTARGETDEVICE*) CoTaskMemAlloc (sizeof (DVTARGETDEVICE));
  208737. *(dest.ptd) = *(source.ptd);
  208738. }
  208739. }
  208740. JuceEnumFormatEtc (const JuceEnumFormatEtc&);
  208741. JuceEnumFormatEtc& operator= (const JuceEnumFormatEtc&);
  208742. };
  208743. class JuceDataObject : public ComBaseClassHelper <IDataObject>
  208744. {
  208745. public:
  208746. JuceDataObject (JuceDropSource* const dropSource_,
  208747. const FORMATETC* const format_,
  208748. const STGMEDIUM* const medium_)
  208749. : dropSource (dropSource_),
  208750. format (format_),
  208751. medium (medium_)
  208752. {
  208753. }
  208754. ~JuceDataObject()
  208755. {
  208756. jassert (refCount == 0);
  208757. }
  208758. HRESULT __stdcall GetData (FORMATETC* pFormatEtc, STGMEDIUM* pMedium)
  208759. {
  208760. if ((pFormatEtc->tymed & format->tymed) != 0
  208761. && pFormatEtc->cfFormat == format->cfFormat
  208762. && pFormatEtc->dwAspect == format->dwAspect)
  208763. {
  208764. pMedium->tymed = format->tymed;
  208765. pMedium->pUnkForRelease = 0;
  208766. if (format->tymed == TYMED_HGLOBAL)
  208767. {
  208768. const SIZE_T len = GlobalSize (medium->hGlobal);
  208769. void* const src = GlobalLock (medium->hGlobal);
  208770. void* const dst = GlobalAlloc (GMEM_FIXED, len);
  208771. memcpy (dst, src, len);
  208772. GlobalUnlock (medium->hGlobal);
  208773. pMedium->hGlobal = dst;
  208774. return S_OK;
  208775. }
  208776. }
  208777. return DV_E_FORMATETC;
  208778. }
  208779. HRESULT __stdcall QueryGetData (FORMATETC* f)
  208780. {
  208781. if (f == 0)
  208782. return E_INVALIDARG;
  208783. if (f->tymed == format->tymed
  208784. && f->cfFormat == format->cfFormat
  208785. && f->dwAspect == format->dwAspect)
  208786. return S_OK;
  208787. return DV_E_FORMATETC;
  208788. }
  208789. HRESULT __stdcall GetCanonicalFormatEtc (FORMATETC*, FORMATETC* pFormatEtcOut)
  208790. {
  208791. pFormatEtcOut->ptd = 0;
  208792. return E_NOTIMPL;
  208793. }
  208794. HRESULT __stdcall EnumFormatEtc (DWORD direction, IEnumFORMATETC** result)
  208795. {
  208796. if (result == 0)
  208797. return E_POINTER;
  208798. if (direction == DATADIR_GET)
  208799. {
  208800. *result = new JuceEnumFormatEtc (format);
  208801. return S_OK;
  208802. }
  208803. *result = 0;
  208804. return E_NOTIMPL;
  208805. }
  208806. HRESULT __stdcall GetDataHere (FORMATETC*, STGMEDIUM*) { return DATA_E_FORMATETC; }
  208807. HRESULT __stdcall SetData (FORMATETC*, STGMEDIUM*, BOOL) { return E_NOTIMPL; }
  208808. HRESULT __stdcall DAdvise (FORMATETC*, DWORD, IAdviseSink*, DWORD*) { return OLE_E_ADVISENOTSUPPORTED; }
  208809. HRESULT __stdcall DUnadvise (DWORD) { return E_NOTIMPL; }
  208810. HRESULT __stdcall EnumDAdvise (IEnumSTATDATA**) { return OLE_E_ADVISENOTSUPPORTED; }
  208811. private:
  208812. JuceDropSource* const dropSource;
  208813. const FORMATETC* const format;
  208814. const STGMEDIUM* const medium;
  208815. JuceDataObject (const JuceDataObject&);
  208816. JuceDataObject& operator= (const JuceDataObject&);
  208817. };
  208818. static HDROP createHDrop (const StringArray& fileNames)
  208819. {
  208820. int totalChars = 0;
  208821. for (int i = fileNames.size(); --i >= 0;)
  208822. totalChars += fileNames[i].length() + 1;
  208823. HDROP hDrop = (HDROP) GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT,
  208824. sizeof (DROPFILES) + sizeof (WCHAR) * (totalChars + 2));
  208825. if (hDrop != 0)
  208826. {
  208827. LPDROPFILES pDropFiles = (LPDROPFILES) GlobalLock (hDrop);
  208828. pDropFiles->pFiles = sizeof (DROPFILES);
  208829. pDropFiles->fWide = true;
  208830. WCHAR* fname = reinterpret_cast<WCHAR*> (addBytesToPointer (pDropFiles, sizeof (DROPFILES)));
  208831. for (int i = 0; i < fileNames.size(); ++i)
  208832. {
  208833. fileNames[i].copyToUnicode (fname, 2048);
  208834. fname += fileNames[i].length() + 1;
  208835. }
  208836. *fname = 0;
  208837. GlobalUnlock (hDrop);
  208838. }
  208839. return hDrop;
  208840. }
  208841. static bool performDragDrop (FORMATETC* const format, STGMEDIUM* const medium, const DWORD whatToDo)
  208842. {
  208843. JuceDropSource* const source = new JuceDropSource();
  208844. JuceDataObject* const data = new JuceDataObject (source, format, medium);
  208845. DWORD effect;
  208846. const HRESULT res = DoDragDrop (data, source, whatToDo, &effect);
  208847. data->Release();
  208848. source->Release();
  208849. return res == DRAGDROP_S_DROP;
  208850. }
  208851. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMove)
  208852. {
  208853. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  208854. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  208855. medium.hGlobal = createHDrop (files);
  208856. return performDragDrop (&format, &medium, canMove ? (DROPEFFECT_COPY | DROPEFFECT_MOVE)
  208857. : DROPEFFECT_COPY);
  208858. }
  208859. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  208860. {
  208861. FORMATETC format = { CF_TEXT, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  208862. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  208863. const int numChars = text.length();
  208864. medium.hGlobal = GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT, (numChars + 2) * sizeof (WCHAR));
  208865. WCHAR* const data = static_cast <WCHAR*> (GlobalLock (medium.hGlobal));
  208866. text.copyToUnicode (data, numChars + 1);
  208867. format.cfFormat = CF_UNICODETEXT;
  208868. GlobalUnlock (medium.hGlobal);
  208869. return performDragDrop (&format, &medium, DROPEFFECT_COPY | DROPEFFECT_MOVE);
  208870. }
  208871. #endif
  208872. /*** End of inlined file: juce_win32_Windowing.cpp ***/
  208873. /*** Start of inlined file: juce_win32_FileChooser.cpp ***/
  208874. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  208875. // compiled on its own).
  208876. #if JUCE_INCLUDED_FILE
  208877. namespace FileChooserHelpers
  208878. {
  208879. static bool areThereAnyAlwaysOnTopWindows()
  208880. {
  208881. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  208882. {
  208883. Component* c = Desktop::getInstance().getComponent (i);
  208884. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  208885. return true;
  208886. }
  208887. return false;
  208888. }
  208889. struct FileChooserCallbackInfo
  208890. {
  208891. String initialPath;
  208892. String returnedString; // need this to get non-existent pathnames from the directory chooser
  208893. ScopedPointer<Component> customComponent;
  208894. };
  208895. static int CALLBACK browseCallbackProc (HWND hWnd, UINT msg, LPARAM lParam, LPARAM lpData)
  208896. {
  208897. FileChooserCallbackInfo* info = (FileChooserCallbackInfo*) lpData;
  208898. if (msg == BFFM_INITIALIZED)
  208899. SendMessage (hWnd, BFFM_SETSELECTIONW, TRUE, (LPARAM) static_cast <const WCHAR*> (info->initialPath));
  208900. else if (msg == BFFM_VALIDATEFAILEDW)
  208901. info->returnedString = (LPCWSTR) lParam;
  208902. else if (msg == BFFM_VALIDATEFAILEDA)
  208903. info->returnedString = (const char*) lParam;
  208904. return 0;
  208905. }
  208906. static UINT_PTR CALLBACK openCallback (HWND hdlg, UINT uiMsg, WPARAM /*wParam*/, LPARAM lParam)
  208907. {
  208908. if (uiMsg == WM_INITDIALOG)
  208909. {
  208910. Component* customComp = ((FileChooserCallbackInfo*) (((OPENFILENAMEW*) lParam)->lCustData))->customComponent;
  208911. HWND dialogH = GetParent (hdlg);
  208912. jassert (dialogH != 0);
  208913. if (dialogH == 0)
  208914. dialogH = hdlg;
  208915. RECT r, cr;
  208916. GetWindowRect (dialogH, &r);
  208917. GetClientRect (dialogH, &cr);
  208918. SetWindowPos (dialogH, 0,
  208919. r.left, r.top,
  208920. customComp->getWidth() + jmax (150, (int) (r.right - r.left)),
  208921. jmax (150, (int) (r.bottom - r.top)),
  208922. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  208923. customComp->setBounds (cr.right, cr.top, customComp->getWidth(), cr.bottom - cr.top);
  208924. customComp->addToDesktop (0, dialogH);
  208925. }
  208926. else if (uiMsg == WM_NOTIFY)
  208927. {
  208928. LPOFNOTIFY ofn = (LPOFNOTIFY) lParam;
  208929. if (ofn->hdr.code == CDN_SELCHANGE)
  208930. {
  208931. FileChooserCallbackInfo* info = (FileChooserCallbackInfo*) ofn->lpOFN->lCustData;
  208932. FilePreviewComponent* comp = static_cast<FilePreviewComponent*> (info->customComponent->getChildComponent(0));
  208933. if (comp != 0)
  208934. {
  208935. WCHAR path [MAX_PATH * 2];
  208936. zerostruct (path);
  208937. CommDlg_OpenSave_GetFilePath (GetParent (hdlg), (LPARAM) &path, MAX_PATH);
  208938. comp->selectedFileChanged (File (path));
  208939. }
  208940. }
  208941. }
  208942. return 0;
  208943. }
  208944. class CustomComponentHolder : public Component
  208945. {
  208946. public:
  208947. CustomComponentHolder (Component* customComp)
  208948. {
  208949. setVisible (true);
  208950. setOpaque (true);
  208951. addAndMakeVisible (customComp);
  208952. setSize (jlimit (20, 800, customComp->getWidth()), customComp->getHeight());
  208953. }
  208954. void paint (Graphics& g)
  208955. {
  208956. g.fillAll (Colours::lightgrey);
  208957. }
  208958. void resized()
  208959. {
  208960. if (getNumChildComponents() > 0)
  208961. getChildComponent(0)->setBounds (getLocalBounds());
  208962. }
  208963. juce_UseDebuggingNewOperator
  208964. private:
  208965. CustomComponentHolder (const CustomComponentHolder&);
  208966. CustomComponentHolder& operator= (const CustomComponentHolder&);
  208967. };
  208968. }
  208969. void FileChooser::showPlatformDialog (Array<File>& results, const String& title, const File& currentFileOrDirectory,
  208970. const String& filter, bool selectsDirectory, bool /*selectsFiles*/,
  208971. bool isSaveDialogue, bool warnAboutOverwritingExistingFiles,
  208972. bool selectMultipleFiles, FilePreviewComponent* extraInfoComponent)
  208973. {
  208974. using namespace FileChooserHelpers;
  208975. HeapBlock<WCHAR> files;
  208976. const int charsAvailableForResult = 32768;
  208977. files.calloc (charsAvailableForResult + 1);
  208978. int filenameOffset = 0;
  208979. FileChooserCallbackInfo info;
  208980. // use a modal window as the parent for this dialog box
  208981. // to block input from other app windows
  208982. Component parentWindow (String::empty);
  208983. const Rectangle<int> mainMon (Desktop::getInstance().getMainMonitorArea());
  208984. parentWindow.setBounds (mainMon.getX() + mainMon.getWidth() / 4,
  208985. mainMon.getY() + mainMon.getHeight() / 4,
  208986. 0, 0);
  208987. parentWindow.setOpaque (true);
  208988. parentWindow.setAlwaysOnTop (areThereAnyAlwaysOnTopWindows());
  208989. parentWindow.addToDesktop (0);
  208990. if (extraInfoComponent == 0)
  208991. parentWindow.enterModalState();
  208992. if (currentFileOrDirectory.isDirectory())
  208993. {
  208994. info.initialPath = currentFileOrDirectory.getFullPathName();
  208995. }
  208996. else
  208997. {
  208998. currentFileOrDirectory.getFileName().copyToUnicode (files, charsAvailableForResult);
  208999. info.initialPath = currentFileOrDirectory.getParentDirectory().getFullPathName();
  209000. }
  209001. if (selectsDirectory)
  209002. {
  209003. BROWSEINFO bi;
  209004. zerostruct (bi);
  209005. bi.hwndOwner = (HWND) parentWindow.getWindowHandle();
  209006. bi.pszDisplayName = files;
  209007. bi.lpszTitle = title;
  209008. bi.lParam = (LPARAM) &info;
  209009. bi.lpfn = browseCallbackProc;
  209010. #ifdef BIF_USENEWUI
  209011. bi.ulFlags = BIF_USENEWUI | BIF_VALIDATE;
  209012. #else
  209013. bi.ulFlags = 0x50;
  209014. #endif
  209015. LPITEMIDLIST list = SHBrowseForFolder (&bi);
  209016. if (! SHGetPathFromIDListW (list, files))
  209017. {
  209018. files[0] = 0;
  209019. info.returnedString = String::empty;
  209020. }
  209021. LPMALLOC al;
  209022. if (list != 0 && SUCCEEDED (SHGetMalloc (&al)))
  209023. al->Free (list);
  209024. if (info.returnedString.isNotEmpty())
  209025. {
  209026. results.add (File (String (files)).getSiblingFile (info.returnedString));
  209027. return;
  209028. }
  209029. }
  209030. else
  209031. {
  209032. DWORD flags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR | OFN_HIDEREADONLY;
  209033. if (warnAboutOverwritingExistingFiles)
  209034. flags |= OFN_OVERWRITEPROMPT;
  209035. if (selectMultipleFiles)
  209036. flags |= OFN_ALLOWMULTISELECT;
  209037. if (extraInfoComponent != 0)
  209038. {
  209039. flags |= OFN_ENABLEHOOK;
  209040. info.customComponent = new CustomComponentHolder (extraInfoComponent);
  209041. info.customComponent->enterModalState();
  209042. }
  209043. WCHAR filters [1024];
  209044. zerostruct (filters);
  209045. filter.copyToUnicode (filters, 1024);
  209046. filter.copyToUnicode (filters + filter.length() + 1, 1022 - filter.length());
  209047. OPENFILENAMEW of;
  209048. zerostruct (of);
  209049. #ifdef OPENFILENAME_SIZE_VERSION_400W
  209050. of.lStructSize = OPENFILENAME_SIZE_VERSION_400W;
  209051. #else
  209052. of.lStructSize = sizeof (of);
  209053. #endif
  209054. of.hwndOwner = (HWND) parentWindow.getWindowHandle();
  209055. of.lpstrFilter = filters;
  209056. of.nFilterIndex = 1;
  209057. of.lpstrFile = files;
  209058. of.nMaxFile = charsAvailableForResult;
  209059. of.lpstrInitialDir = info.initialPath;
  209060. of.lpstrTitle = title;
  209061. of.Flags = flags;
  209062. of.lCustData = (LPARAM) &info;
  209063. if (extraInfoComponent != 0)
  209064. of.lpfnHook = &openCallback;
  209065. if (! (isSaveDialogue ? GetSaveFileName (&of)
  209066. : GetOpenFileName (&of)))
  209067. return;
  209068. filenameOffset = of.nFileOffset;
  209069. }
  209070. if (selectMultipleFiles && filenameOffset > 0 && files [filenameOffset - 1] == 0)
  209071. {
  209072. const WCHAR* filename = files + filenameOffset;
  209073. while (*filename != 0)
  209074. {
  209075. results.add (File (String (files) + "\\" + String (filename)));
  209076. filename += CharacterFunctions::length (filename) + 1;
  209077. }
  209078. }
  209079. else if (files[0] != 0)
  209080. {
  209081. results.add (File (String (files)));
  209082. }
  209083. }
  209084. #endif
  209085. /*** End of inlined file: juce_win32_FileChooser.cpp ***/
  209086. /*** Start of inlined file: juce_win32_Misc.cpp ***/
  209087. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209088. // compiled on its own).
  209089. #if JUCE_INCLUDED_FILE
  209090. void SystemClipboard::copyTextToClipboard (const String& text)
  209091. {
  209092. if (OpenClipboard (0) != 0)
  209093. {
  209094. if (EmptyClipboard() != 0)
  209095. {
  209096. const int len = text.length();
  209097. if (len > 0)
  209098. {
  209099. HGLOBAL bufH = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE,
  209100. (len + 1) * sizeof (wchar_t));
  209101. if (bufH != 0)
  209102. {
  209103. WCHAR* const data = static_cast <WCHAR*> (GlobalLock (bufH));
  209104. text.copyToUnicode (data, len);
  209105. GlobalUnlock (bufH);
  209106. SetClipboardData (CF_UNICODETEXT, bufH);
  209107. }
  209108. }
  209109. }
  209110. CloseClipboard();
  209111. }
  209112. }
  209113. const String SystemClipboard::getTextFromClipboard()
  209114. {
  209115. String result;
  209116. if (OpenClipboard (0) != 0)
  209117. {
  209118. HANDLE bufH = GetClipboardData (CF_UNICODETEXT);
  209119. if (bufH != 0)
  209120. {
  209121. const wchar_t* const data = (const wchar_t*) GlobalLock (bufH);
  209122. if (data != 0)
  209123. {
  209124. result = String (data, (int) (GlobalSize (bufH) / sizeof (wchar_t)));
  209125. GlobalUnlock (bufH);
  209126. }
  209127. }
  209128. CloseClipboard();
  209129. }
  209130. return result;
  209131. }
  209132. #endif
  209133. /*** End of inlined file: juce_win32_Misc.cpp ***/
  209134. /*** Start of inlined file: juce_win32_ActiveXComponent.cpp ***/
  209135. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209136. // compiled on its own).
  209137. #if JUCE_INCLUDED_FILE
  209138. namespace ActiveXHelpers
  209139. {
  209140. class JuceIStorage : public ComBaseClassHelper <IStorage>
  209141. {
  209142. public:
  209143. JuceIStorage() {}
  209144. ~JuceIStorage() {}
  209145. HRESULT __stdcall CreateStream (const WCHAR*, DWORD, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  209146. HRESULT __stdcall OpenStream (const WCHAR*, void*, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  209147. HRESULT __stdcall CreateStorage (const WCHAR*, DWORD, DWORD, DWORD, IStorage**) { return E_NOTIMPL; }
  209148. HRESULT __stdcall OpenStorage (const WCHAR*, IStorage*, DWORD, SNB, DWORD, IStorage**) { return E_NOTIMPL; }
  209149. HRESULT __stdcall CopyTo (DWORD, IID const*, SNB, IStorage*) { return E_NOTIMPL; }
  209150. HRESULT __stdcall MoveElementTo (const OLECHAR*,IStorage*, const OLECHAR*, DWORD) { return E_NOTIMPL; }
  209151. HRESULT __stdcall Commit (DWORD) { return E_NOTIMPL; }
  209152. HRESULT __stdcall Revert() { return E_NOTIMPL; }
  209153. HRESULT __stdcall EnumElements (DWORD, void*, DWORD, IEnumSTATSTG**) { return E_NOTIMPL; }
  209154. HRESULT __stdcall DestroyElement (const OLECHAR*) { return E_NOTIMPL; }
  209155. HRESULT __stdcall RenameElement (const WCHAR*, const WCHAR*) { return E_NOTIMPL; }
  209156. HRESULT __stdcall SetElementTimes (const WCHAR*, FILETIME const*, FILETIME const*, FILETIME const*) { return E_NOTIMPL; }
  209157. HRESULT __stdcall SetClass (REFCLSID) { return S_OK; }
  209158. HRESULT __stdcall SetStateBits (DWORD, DWORD) { return E_NOTIMPL; }
  209159. HRESULT __stdcall Stat (STATSTG*, DWORD) { return E_NOTIMPL; }
  209160. juce_UseDebuggingNewOperator
  209161. };
  209162. class JuceOleInPlaceFrame : public ComBaseClassHelper <IOleInPlaceFrame>
  209163. {
  209164. HWND window;
  209165. public:
  209166. JuceOleInPlaceFrame (HWND window_) : window (window_) {}
  209167. ~JuceOleInPlaceFrame() {}
  209168. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  209169. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  209170. HRESULT __stdcall GetBorder (LPRECT) { return E_NOTIMPL; }
  209171. HRESULT __stdcall RequestBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  209172. HRESULT __stdcall SetBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  209173. HRESULT __stdcall SetActiveObject (IOleInPlaceActiveObject*, LPCOLESTR) { return S_OK; }
  209174. HRESULT __stdcall InsertMenus (HMENU, LPOLEMENUGROUPWIDTHS) { return E_NOTIMPL; }
  209175. HRESULT __stdcall SetMenu (HMENU, HOLEMENU, HWND) { return S_OK; }
  209176. HRESULT __stdcall RemoveMenus (HMENU) { return E_NOTIMPL; }
  209177. HRESULT __stdcall SetStatusText (LPCOLESTR) { return S_OK; }
  209178. HRESULT __stdcall EnableModeless (BOOL) { return S_OK; }
  209179. HRESULT __stdcall TranslateAccelerator(LPMSG, WORD) { return E_NOTIMPL; }
  209180. juce_UseDebuggingNewOperator
  209181. };
  209182. class JuceIOleInPlaceSite : public ComBaseClassHelper <IOleInPlaceSite>
  209183. {
  209184. HWND window;
  209185. JuceOleInPlaceFrame* frame;
  209186. public:
  209187. JuceIOleInPlaceSite (HWND window_)
  209188. : window (window_),
  209189. frame (new JuceOleInPlaceFrame (window))
  209190. {}
  209191. ~JuceIOleInPlaceSite()
  209192. {
  209193. frame->Release();
  209194. }
  209195. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  209196. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  209197. HRESULT __stdcall CanInPlaceActivate() { return S_OK; }
  209198. HRESULT __stdcall OnInPlaceActivate() { return S_OK; }
  209199. HRESULT __stdcall OnUIActivate() { return S_OK; }
  209200. HRESULT __stdcall GetWindowContext (LPOLEINPLACEFRAME* lplpFrame, LPOLEINPLACEUIWINDOW* lplpDoc, LPRECT, LPRECT, LPOLEINPLACEFRAMEINFO lpFrameInfo)
  209201. {
  209202. /* Note: if you call AddRef on the frame here, then some types of object (e.g. web browser control) cause leaks..
  209203. If you don't call AddRef then others crash (e.g. QuickTime).. Bit of a catch-22, so letting it leak is probably preferable.
  209204. */
  209205. if (lplpFrame != 0) { frame->AddRef(); *lplpFrame = frame; }
  209206. if (lplpDoc != 0) *lplpDoc = 0;
  209207. lpFrameInfo->fMDIApp = FALSE;
  209208. lpFrameInfo->hwndFrame = window;
  209209. lpFrameInfo->haccel = 0;
  209210. lpFrameInfo->cAccelEntries = 0;
  209211. return S_OK;
  209212. }
  209213. HRESULT __stdcall Scroll (SIZE) { return E_NOTIMPL; }
  209214. HRESULT __stdcall OnUIDeactivate (BOOL) { return S_OK; }
  209215. HRESULT __stdcall OnInPlaceDeactivate() { return S_OK; }
  209216. HRESULT __stdcall DiscardUndoState() { return E_NOTIMPL; }
  209217. HRESULT __stdcall DeactivateAndUndo() { return E_NOTIMPL; }
  209218. HRESULT __stdcall OnPosRectChange (LPCRECT) { return S_OK; }
  209219. juce_UseDebuggingNewOperator
  209220. };
  209221. class JuceIOleClientSite : public ComBaseClassHelper <IOleClientSite>
  209222. {
  209223. JuceIOleInPlaceSite* inplaceSite;
  209224. public:
  209225. JuceIOleClientSite (HWND window)
  209226. : inplaceSite (new JuceIOleInPlaceSite (window))
  209227. {}
  209228. ~JuceIOleClientSite()
  209229. {
  209230. inplaceSite->Release();
  209231. }
  209232. HRESULT __stdcall QueryInterface (REFIID type, void** result)
  209233. {
  209234. if (type == IID_IOleInPlaceSite)
  209235. {
  209236. inplaceSite->AddRef();
  209237. *result = static_cast <IOleInPlaceSite*> (inplaceSite);
  209238. return S_OK;
  209239. }
  209240. return ComBaseClassHelper <IOleClientSite>::QueryInterface (type, result);
  209241. }
  209242. HRESULT __stdcall SaveObject() { return E_NOTIMPL; }
  209243. HRESULT __stdcall GetMoniker (DWORD, DWORD, IMoniker**) { return E_NOTIMPL; }
  209244. HRESULT __stdcall GetContainer (LPOLECONTAINER* ppContainer) { *ppContainer = 0; return E_NOINTERFACE; }
  209245. HRESULT __stdcall ShowObject() { return S_OK; }
  209246. HRESULT __stdcall OnShowWindow (BOOL) { return E_NOTIMPL; }
  209247. HRESULT __stdcall RequestNewObjectLayout() { return E_NOTIMPL; }
  209248. juce_UseDebuggingNewOperator
  209249. };
  209250. static Array<ActiveXControlComponent*> activeXComps;
  209251. static HWND getHWND (const ActiveXControlComponent* const component)
  209252. {
  209253. HWND hwnd = 0;
  209254. const IID iid = IID_IOleWindow;
  209255. IOleWindow* const window = (IOleWindow*) component->queryInterface (&iid);
  209256. if (window != 0)
  209257. {
  209258. window->GetWindow (&hwnd);
  209259. window->Release();
  209260. }
  209261. return hwnd;
  209262. }
  209263. static void offerActiveXMouseEventToPeer (ComponentPeer* const peer, HWND hwnd, UINT message, LPARAM lParam)
  209264. {
  209265. RECT activeXRect, peerRect;
  209266. GetWindowRect (hwnd, &activeXRect);
  209267. GetWindowRect ((HWND) peer->getNativeHandle(), &peerRect);
  209268. const Point<int> mousePos (GET_X_LPARAM (lParam) + activeXRect.left - peerRect.left,
  209269. GET_Y_LPARAM (lParam) + activeXRect.top - peerRect.top);
  209270. const int64 mouseEventTime = Win32ComponentPeer::getMouseEventTime();
  209271. ModifierKeys::getCurrentModifiersRealtime(); // to update the mouse button flags
  209272. switch (message)
  209273. {
  209274. case WM_MOUSEMOVE:
  209275. case WM_LBUTTONDOWN:
  209276. case WM_MBUTTONDOWN:
  209277. case WM_RBUTTONDOWN:
  209278. case WM_LBUTTONUP:
  209279. case WM_MBUTTONUP:
  209280. case WM_RBUTTONUP:
  209281. peer->handleMouseEvent (0, mousePos, Win32ComponentPeer::currentModifiers, mouseEventTime);
  209282. break;
  209283. default:
  209284. break;
  209285. }
  209286. }
  209287. }
  209288. class ActiveXControlComponent::Pimpl : public ComponentMovementWatcher
  209289. {
  209290. ActiveXControlComponent& owner;
  209291. bool wasShowing;
  209292. public:
  209293. HWND controlHWND;
  209294. IStorage* storage;
  209295. IOleClientSite* clientSite;
  209296. IOleObject* control;
  209297. Pimpl (HWND hwnd, ActiveXControlComponent& owner_)
  209298. : ComponentMovementWatcher (&owner_),
  209299. owner (owner_),
  209300. wasShowing (owner_.isShowing()),
  209301. controlHWND (0),
  209302. storage (new ActiveXHelpers::JuceIStorage()),
  209303. clientSite (new ActiveXHelpers::JuceIOleClientSite (hwnd)),
  209304. control (0)
  209305. {
  209306. }
  209307. ~Pimpl()
  209308. {
  209309. if (control != 0)
  209310. {
  209311. control->Close (OLECLOSE_NOSAVE);
  209312. control->Release();
  209313. }
  209314. clientSite->Release();
  209315. storage->Release();
  209316. }
  209317. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  209318. {
  209319. Component* const topComp = owner.getTopLevelComponent();
  209320. if (topComp->getPeer() != 0)
  209321. {
  209322. const Point<int> pos (owner.relativePositionToOtherComponent (topComp, Point<int>()));
  209323. owner.setControlBounds (Rectangle<int> (pos.getX(), pos.getY(), owner.getWidth(), owner.getHeight()));
  209324. }
  209325. }
  209326. void componentPeerChanged()
  209327. {
  209328. const bool isShowingNow = owner.isShowing();
  209329. if (wasShowing != isShowingNow)
  209330. {
  209331. wasShowing = isShowingNow;
  209332. owner.setControlVisible (isShowingNow);
  209333. }
  209334. componentMovedOrResized (true, true);
  209335. }
  209336. void componentVisibilityChanged (Component&)
  209337. {
  209338. componentPeerChanged();
  209339. }
  209340. // intercepts events going to an activeX control, so we can sneakily use the mouse events
  209341. static LRESULT CALLBACK activeXHookWndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
  209342. {
  209343. for (int i = ActiveXHelpers::activeXComps.size(); --i >= 0;)
  209344. {
  209345. const ActiveXControlComponent* const ax = ActiveXHelpers::activeXComps.getUnchecked(i);
  209346. if (ax->control != 0 && ax->control->controlHWND == hwnd)
  209347. {
  209348. switch (message)
  209349. {
  209350. case WM_MOUSEMOVE:
  209351. case WM_LBUTTONDOWN:
  209352. case WM_MBUTTONDOWN:
  209353. case WM_RBUTTONDOWN:
  209354. case WM_LBUTTONUP:
  209355. case WM_MBUTTONUP:
  209356. case WM_RBUTTONUP:
  209357. case WM_LBUTTONDBLCLK:
  209358. case WM_MBUTTONDBLCLK:
  209359. case WM_RBUTTONDBLCLK:
  209360. if (ax->isShowing())
  209361. {
  209362. ComponentPeer* const peer = ax->getPeer();
  209363. if (peer != 0)
  209364. {
  209365. ActiveXHelpers::offerActiveXMouseEventToPeer (peer, hwnd, message, lParam);
  209366. if (! ax->areMouseEventsAllowed())
  209367. return 0;
  209368. }
  209369. }
  209370. break;
  209371. default:
  209372. break;
  209373. }
  209374. return CallWindowProc ((WNDPROC) ax->originalWndProc, hwnd, message, wParam, lParam);
  209375. }
  209376. }
  209377. return DefWindowProc (hwnd, message, wParam, lParam);
  209378. }
  209379. };
  209380. ActiveXControlComponent::ActiveXControlComponent()
  209381. : originalWndProc (0),
  209382. mouseEventsAllowed (true)
  209383. {
  209384. ActiveXHelpers::activeXComps.add (this);
  209385. }
  209386. ActiveXControlComponent::~ActiveXControlComponent()
  209387. {
  209388. deleteControl();
  209389. ActiveXHelpers::activeXComps.removeValue (this);
  209390. }
  209391. void ActiveXControlComponent::paint (Graphics& g)
  209392. {
  209393. if (control == 0)
  209394. g.fillAll (Colours::lightgrey);
  209395. }
  209396. bool ActiveXControlComponent::createControl (const void* controlIID)
  209397. {
  209398. deleteControl();
  209399. ComponentPeer* const peer = getPeer();
  209400. // the component must have already been added to a real window when you call this!
  209401. jassert (dynamic_cast <Win32ComponentPeer*> (peer) != 0);
  209402. if (dynamic_cast <Win32ComponentPeer*> (peer) != 0)
  209403. {
  209404. const Point<int> pos (relativePositionToOtherComponent (getTopLevelComponent(), Point<int>()));
  209405. HWND hwnd = (HWND) peer->getNativeHandle();
  209406. ScopedPointer<Pimpl> newControl (new Pimpl (hwnd, *this));
  209407. HRESULT hr;
  209408. if ((hr = OleCreate (*(const IID*) controlIID, IID_IOleObject, 1 /*OLERENDER_DRAW*/, 0,
  209409. newControl->clientSite, newControl->storage,
  209410. (void**) &(newControl->control))) == S_OK)
  209411. {
  209412. newControl->control->SetHostNames (L"Juce", 0);
  209413. if (OleSetContainedObject (newControl->control, TRUE) == S_OK)
  209414. {
  209415. RECT rect;
  209416. rect.left = pos.getX();
  209417. rect.top = pos.getY();
  209418. rect.right = pos.getX() + getWidth();
  209419. rect.bottom = pos.getY() + getHeight();
  209420. if (newControl->control->DoVerb (OLEIVERB_SHOW, 0, newControl->clientSite, 0, hwnd, &rect) == S_OK)
  209421. {
  209422. control = newControl;
  209423. setControlBounds (Rectangle<int> (pos.getX(), pos.getY(), getWidth(), getHeight()));
  209424. control->controlHWND = ActiveXHelpers::getHWND (this);
  209425. if (control->controlHWND != 0)
  209426. {
  209427. originalWndProc = (void*) (pointer_sized_int) GetWindowLongPtr ((HWND) control->controlHWND, GWLP_WNDPROC);
  209428. SetWindowLongPtr ((HWND) control->controlHWND, GWLP_WNDPROC, (LONG_PTR) Pimpl::activeXHookWndProc);
  209429. }
  209430. return true;
  209431. }
  209432. }
  209433. }
  209434. }
  209435. return false;
  209436. }
  209437. void ActiveXControlComponent::deleteControl()
  209438. {
  209439. control = 0;
  209440. originalWndProc = 0;
  209441. }
  209442. void* ActiveXControlComponent::queryInterface (const void* iid) const
  209443. {
  209444. void* result = 0;
  209445. if (control != 0 && control->control != 0
  209446. && SUCCEEDED (control->control->QueryInterface (*(const IID*) iid, &result)))
  209447. return result;
  209448. return 0;
  209449. }
  209450. void ActiveXControlComponent::setControlBounds (const Rectangle<int>& newBounds) const
  209451. {
  209452. if (control->controlHWND != 0)
  209453. MoveWindow (control->controlHWND, newBounds.getX(), newBounds.getY(), newBounds.getWidth(), newBounds.getHeight(), TRUE);
  209454. }
  209455. void ActiveXControlComponent::setControlVisible (const bool shouldBeVisible) const
  209456. {
  209457. if (control->controlHWND != 0)
  209458. ShowWindow (control->controlHWND, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  209459. }
  209460. void ActiveXControlComponent::setMouseEventsAllowed (const bool eventsCanReachControl)
  209461. {
  209462. mouseEventsAllowed = eventsCanReachControl;
  209463. }
  209464. #endif
  209465. /*** End of inlined file: juce_win32_ActiveXComponent.cpp ***/
  209466. /*** Start of inlined file: juce_win32_QuickTimeMovieComponent.cpp ***/
  209467. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209468. // compiled on its own).
  209469. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  209470. using namespace QTOLibrary;
  209471. using namespace QTOControlLib;
  209472. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  209473. static bool isQTAvailable = false;
  209474. class QuickTimeMovieComponent::Pimpl
  209475. {
  209476. public:
  209477. Pimpl() : dataHandle (0)
  209478. {
  209479. }
  209480. ~Pimpl()
  209481. {
  209482. clearHandle();
  209483. }
  209484. void clearHandle()
  209485. {
  209486. if (dataHandle != 0)
  209487. {
  209488. DisposeHandle (dataHandle);
  209489. dataHandle = 0;
  209490. }
  209491. }
  209492. IQTControlPtr qtControl;
  209493. IQTMoviePtr qtMovie;
  209494. Handle dataHandle;
  209495. };
  209496. QuickTimeMovieComponent::QuickTimeMovieComponent()
  209497. : movieLoaded (false),
  209498. controllerVisible (true)
  209499. {
  209500. pimpl = new Pimpl();
  209501. setMouseEventsAllowed (false);
  209502. }
  209503. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  209504. {
  209505. closeMovie();
  209506. pimpl->qtControl = 0;
  209507. deleteControl();
  209508. pimpl = 0;
  209509. }
  209510. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  209511. {
  209512. if (! isQTAvailable)
  209513. isQTAvailable = (InitializeQTML (0) == noErr) && (EnterMovies() == noErr);
  209514. return isQTAvailable;
  209515. }
  209516. void QuickTimeMovieComponent::createControlIfNeeded()
  209517. {
  209518. if (isShowing() && ! isControlCreated())
  209519. {
  209520. const IID qtIID = __uuidof (QTControl);
  209521. if (createControl (&qtIID))
  209522. {
  209523. const IID qtInterfaceIID = __uuidof (IQTControl);
  209524. pimpl->qtControl = (IQTControl*) queryInterface (&qtInterfaceIID);
  209525. if (pimpl->qtControl != 0)
  209526. {
  209527. pimpl->qtControl->Release(); // it has one ref too many at this point
  209528. pimpl->qtControl->QuickTimeInitialize();
  209529. pimpl->qtControl->PutSizing (qtMovieFitsControl);
  209530. if (movieFile != File::nonexistent)
  209531. loadMovie (movieFile, controllerVisible);
  209532. }
  209533. }
  209534. }
  209535. }
  209536. bool QuickTimeMovieComponent::isControlCreated() const
  209537. {
  209538. return isControlOpen();
  209539. }
  209540. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  209541. const bool isControllerVisible)
  209542. {
  209543. const ScopedPointer<InputStream> movieStreamDeleter (movieStream);
  209544. movieFile = File::nonexistent;
  209545. movieLoaded = false;
  209546. pimpl->qtMovie = 0;
  209547. controllerVisible = isControllerVisible;
  209548. createControlIfNeeded();
  209549. if (isControlCreated())
  209550. {
  209551. if (pimpl->qtControl != 0)
  209552. {
  209553. pimpl->qtControl->Put_MovieHandle (0);
  209554. pimpl->clearHandle();
  209555. Movie movie;
  209556. if (juce_OpenQuickTimeMovieFromStream (movieStream, movie, pimpl->dataHandle))
  209557. {
  209558. pimpl->qtControl->Put_MovieHandle ((long) (pointer_sized_int) movie);
  209559. pimpl->qtMovie = pimpl->qtControl->GetMovie();
  209560. if (pimpl->qtMovie != 0)
  209561. pimpl->qtMovie->PutMovieControllerType (isControllerVisible ? qtMovieControllerTypeStandard
  209562. : qtMovieControllerTypeNone);
  209563. }
  209564. if (movie == 0)
  209565. pimpl->clearHandle();
  209566. }
  209567. movieLoaded = (pimpl->qtMovie != 0);
  209568. }
  209569. else
  209570. {
  209571. // You're trying to open a movie when the control hasn't yet been created, probably because
  209572. // you've not yet added this component to a Window and made the whole component hierarchy visible.
  209573. jassertfalse;
  209574. }
  209575. return movieLoaded;
  209576. }
  209577. void QuickTimeMovieComponent::closeMovie()
  209578. {
  209579. stop();
  209580. movieFile = File::nonexistent;
  209581. movieLoaded = false;
  209582. pimpl->qtMovie = 0;
  209583. if (pimpl->qtControl != 0)
  209584. pimpl->qtControl->Put_MovieHandle (0);
  209585. pimpl->clearHandle();
  209586. }
  209587. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  209588. {
  209589. return movieFile;
  209590. }
  209591. bool QuickTimeMovieComponent::isMovieOpen() const
  209592. {
  209593. return movieLoaded;
  209594. }
  209595. double QuickTimeMovieComponent::getMovieDuration() const
  209596. {
  209597. if (pimpl->qtMovie != 0)
  209598. return pimpl->qtMovie->GetDuration() / (double) pimpl->qtMovie->GetTimeScale();
  209599. return 0.0;
  209600. }
  209601. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  209602. {
  209603. if (pimpl->qtMovie != 0)
  209604. {
  209605. struct QTRECT r = pimpl->qtMovie->GetNaturalRect();
  209606. width = r.right - r.left;
  209607. height = r.bottom - r.top;
  209608. }
  209609. else
  209610. {
  209611. width = height = 0;
  209612. }
  209613. }
  209614. void QuickTimeMovieComponent::play()
  209615. {
  209616. if (pimpl->qtMovie != 0)
  209617. pimpl->qtMovie->Play();
  209618. }
  209619. void QuickTimeMovieComponent::stop()
  209620. {
  209621. if (pimpl->qtMovie != 0)
  209622. pimpl->qtMovie->Stop();
  209623. }
  209624. bool QuickTimeMovieComponent::isPlaying() const
  209625. {
  209626. return pimpl->qtMovie != 0 && pimpl->qtMovie->GetRate() != 0.0f;
  209627. }
  209628. void QuickTimeMovieComponent::setPosition (const double seconds)
  209629. {
  209630. if (pimpl->qtMovie != 0)
  209631. pimpl->qtMovie->PutTime ((long) (seconds * pimpl->qtMovie->GetTimeScale()));
  209632. }
  209633. double QuickTimeMovieComponent::getPosition() const
  209634. {
  209635. if (pimpl->qtMovie != 0)
  209636. return pimpl->qtMovie->GetTime() / (double) pimpl->qtMovie->GetTimeScale();
  209637. return 0.0;
  209638. }
  209639. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  209640. {
  209641. if (pimpl->qtMovie != 0)
  209642. pimpl->qtMovie->PutRate (newSpeed);
  209643. }
  209644. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  209645. {
  209646. if (pimpl->qtMovie != 0)
  209647. {
  209648. pimpl->qtMovie->PutAudioVolume (newVolume);
  209649. pimpl->qtMovie->PutAudioMute (newVolume <= 0);
  209650. }
  209651. }
  209652. float QuickTimeMovieComponent::getMovieVolume() const
  209653. {
  209654. if (pimpl->qtMovie != 0)
  209655. return pimpl->qtMovie->GetAudioVolume();
  209656. return 0.0f;
  209657. }
  209658. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  209659. {
  209660. if (pimpl->qtMovie != 0)
  209661. pimpl->qtMovie->PutLoop (shouldLoop);
  209662. }
  209663. bool QuickTimeMovieComponent::isLooping() const
  209664. {
  209665. return pimpl->qtMovie != 0 && pimpl->qtMovie->GetLoop();
  209666. }
  209667. bool QuickTimeMovieComponent::isControllerVisible() const
  209668. {
  209669. return controllerVisible;
  209670. }
  209671. void QuickTimeMovieComponent::parentHierarchyChanged()
  209672. {
  209673. createControlIfNeeded();
  209674. QTCompBaseClass::parentHierarchyChanged();
  209675. }
  209676. void QuickTimeMovieComponent::visibilityChanged()
  209677. {
  209678. createControlIfNeeded();
  209679. QTCompBaseClass::visibilityChanged();
  209680. }
  209681. void QuickTimeMovieComponent::paint (Graphics& g)
  209682. {
  209683. if (! isControlCreated())
  209684. g.fillAll (Colours::black);
  209685. }
  209686. static Handle createHandleDataRef (Handle dataHandle, const char* fileName)
  209687. {
  209688. Handle dataRef = 0;
  209689. OSStatus err = PtrToHand (&dataHandle, &dataRef, sizeof (Handle));
  209690. if (err == noErr)
  209691. {
  209692. Str255 suffix;
  209693. CharacterFunctions::copy ((char*) suffix, fileName, 128);
  209694. StringPtr name = suffix;
  209695. err = PtrAndHand (name, dataRef, name[0] + 1);
  209696. if (err == noErr)
  209697. {
  209698. long atoms[3];
  209699. atoms[0] = EndianU32_NtoB (3 * sizeof (long));
  209700. atoms[1] = EndianU32_NtoB (kDataRefExtensionMacOSFileType);
  209701. atoms[2] = EndianU32_NtoB (MovieFileType);
  209702. err = PtrAndHand (atoms, dataRef, 3 * sizeof (long));
  209703. if (err == noErr)
  209704. return dataRef;
  209705. }
  209706. DisposeHandle (dataRef);
  209707. }
  209708. return 0;
  209709. }
  209710. static CFStringRef juceStringToCFString (const String& s)
  209711. {
  209712. const int len = s.length();
  209713. const juce_wchar* const t = s;
  209714. HeapBlock <UniChar> temp (len + 2);
  209715. for (int i = 0; i <= len; ++i)
  209716. temp[i] = t[i];
  209717. return CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  209718. }
  209719. static bool openMovie (QTNewMoviePropertyElement* props, int prop, Movie& movie)
  209720. {
  209721. Boolean trueBool = true;
  209722. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  209723. props[prop].propID = kQTMovieInstantiationPropertyID_DontResolveDataRefs;
  209724. props[prop].propValueSize = sizeof (trueBool);
  209725. props[prop].propValueAddress = &trueBool;
  209726. ++prop;
  209727. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  209728. props[prop].propID = kQTMovieInstantiationPropertyID_AsyncOK;
  209729. props[prop].propValueSize = sizeof (trueBool);
  209730. props[prop].propValueAddress = &trueBool;
  209731. ++prop;
  209732. Boolean isActive = true;
  209733. props[prop].propClass = kQTPropertyClass_NewMovieProperty;
  209734. props[prop].propID = kQTNewMoviePropertyID_Active;
  209735. props[prop].propValueSize = sizeof (isActive);
  209736. props[prop].propValueAddress = &isActive;
  209737. ++prop;
  209738. MacSetPort (0);
  209739. jassert (prop <= 5);
  209740. OSStatus err = NewMovieFromProperties (prop, props, 0, 0, &movie);
  209741. return err == noErr;
  209742. }
  209743. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle)
  209744. {
  209745. if (input == 0)
  209746. return false;
  209747. dataHandle = 0;
  209748. bool ok = false;
  209749. QTNewMoviePropertyElement props[5];
  209750. zeromem (props, sizeof (props));
  209751. int prop = 0;
  209752. DataReferenceRecord dr;
  209753. props[prop].propClass = kQTPropertyClass_DataLocation;
  209754. props[prop].propID = kQTDataLocationPropertyID_DataReference;
  209755. props[prop].propValueSize = sizeof (dr);
  209756. props[prop].propValueAddress = &dr;
  209757. ++prop;
  209758. FileInputStream* const fin = dynamic_cast <FileInputStream*> (input);
  209759. if (fin != 0)
  209760. {
  209761. CFStringRef filePath = juceStringToCFString (fin->getFile().getFullPathName());
  209762. QTNewDataReferenceFromFullPathCFString (filePath, (QTPathStyle) kQTNativeDefaultPathStyle, 0,
  209763. &dr.dataRef, &dr.dataRefType);
  209764. ok = openMovie (props, prop, movie);
  209765. DisposeHandle (dr.dataRef);
  209766. CFRelease (filePath);
  209767. }
  209768. else
  209769. {
  209770. // sanity-check because this currently needs to load the whole stream into memory..
  209771. jassert (input->getTotalLength() < 50 * 1024 * 1024);
  209772. dataHandle = NewHandle ((Size) input->getTotalLength());
  209773. HLock (dataHandle);
  209774. // read the entire stream into memory - this is a pain, but can't get it to work
  209775. // properly using a custom callback to supply the data.
  209776. input->read (*dataHandle, (int) input->getTotalLength());
  209777. HUnlock (dataHandle);
  209778. // different types to get QT to try. (We should really be a bit smarter here by
  209779. // working out in advance which one the stream contains, rather than just trying
  209780. // each one)
  209781. const char* const suffixesToTry[] = { "\04.mov", "\04.mp3",
  209782. "\04.avi", "\04.m4a" };
  209783. for (int i = 0; i < numElementsInArray (suffixesToTry) && ! ok; ++i)
  209784. {
  209785. /* // this fails for some bizarre reason - it can be bodged to work with
  209786. // movies, but can't seem to do it for other file types..
  209787. QTNewMovieUserProcRecord procInfo;
  209788. procInfo.getMovieUserProc = NewGetMovieUPP (readMovieStreamProc);
  209789. procInfo.getMovieUserProcRefcon = this;
  209790. procInfo.defaultDataRef.dataRef = dataRef;
  209791. procInfo.defaultDataRef.dataRefType = HandleDataHandlerSubType;
  209792. props[prop].propClass = kQTPropertyClass_DataLocation;
  209793. props[prop].propID = kQTDataLocationPropertyID_MovieUserProc;
  209794. props[prop].propValueSize = sizeof (procInfo);
  209795. props[prop].propValueAddress = (void*) &procInfo;
  209796. ++prop; */
  209797. dr.dataRef = createHandleDataRef (dataHandle, suffixesToTry [i]);
  209798. dr.dataRefType = HandleDataHandlerSubType;
  209799. ok = openMovie (props, prop, movie);
  209800. DisposeHandle (dr.dataRef);
  209801. }
  209802. }
  209803. return ok;
  209804. }
  209805. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  209806. const bool isControllerVisible)
  209807. {
  209808. const bool ok = loadMovie (static_cast <InputStream*> (movieFile_.createInputStream()), isControllerVisible);
  209809. movieFile = movieFile_;
  209810. return ok;
  209811. }
  209812. bool QuickTimeMovieComponent::loadMovie (const URL& movieURL,
  209813. const bool isControllerVisible)
  209814. {
  209815. return loadMovie (static_cast <InputStream*> (movieURL.createInputStream (false)), isControllerVisible);
  209816. }
  209817. void QuickTimeMovieComponent::goToStart()
  209818. {
  209819. setPosition (0.0);
  209820. }
  209821. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  209822. const RectanglePlacement& placement)
  209823. {
  209824. int normalWidth, normalHeight;
  209825. getMovieNormalSize (normalWidth, normalHeight);
  209826. if (normalWidth > 0 && normalHeight > 0 && ! spaceToFitWithin.isEmpty())
  209827. {
  209828. double x = 0.0, y = 0.0, w = normalWidth, h = normalHeight;
  209829. placement.applyTo (x, y, w, h,
  209830. spaceToFitWithin.getX(), spaceToFitWithin.getY(),
  209831. spaceToFitWithin.getWidth(), spaceToFitWithin.getHeight());
  209832. if (w > 0 && h > 0)
  209833. {
  209834. setBounds (roundToInt (x), roundToInt (y),
  209835. roundToInt (w), roundToInt (h));
  209836. }
  209837. }
  209838. else
  209839. {
  209840. setBounds (spaceToFitWithin);
  209841. }
  209842. }
  209843. #endif
  209844. /*** End of inlined file: juce_win32_QuickTimeMovieComponent.cpp ***/
  209845. /*** Start of inlined file: juce_win32_WebBrowserComponent.cpp ***/
  209846. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209847. // compiled on its own).
  209848. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  209849. class WebBrowserComponentInternal : public ActiveXControlComponent
  209850. {
  209851. public:
  209852. WebBrowserComponentInternal()
  209853. : browser (0),
  209854. connectionPoint (0),
  209855. adviseCookie (0)
  209856. {
  209857. }
  209858. ~WebBrowserComponentInternal()
  209859. {
  209860. if (connectionPoint != 0)
  209861. connectionPoint->Unadvise (adviseCookie);
  209862. if (browser != 0)
  209863. browser->Release();
  209864. }
  209865. void createBrowser()
  209866. {
  209867. createControl (&CLSID_WebBrowser);
  209868. browser = (IWebBrowser2*) queryInterface (&IID_IWebBrowser2);
  209869. IConnectionPointContainer* connectionPointContainer = (IConnectionPointContainer*) queryInterface (&IID_IConnectionPointContainer);
  209870. if (connectionPointContainer != 0)
  209871. {
  209872. connectionPointContainer->FindConnectionPoint (DIID_DWebBrowserEvents2,
  209873. &connectionPoint);
  209874. if (connectionPoint != 0)
  209875. {
  209876. WebBrowserComponent* const owner = dynamic_cast <WebBrowserComponent*> (getParentComponent());
  209877. jassert (owner != 0);
  209878. EventHandler* handler = new EventHandler (owner);
  209879. connectionPoint->Advise (handler, &adviseCookie);
  209880. handler->Release();
  209881. }
  209882. }
  209883. }
  209884. void goToURL (const String& url,
  209885. const StringArray* headers,
  209886. const MemoryBlock* postData)
  209887. {
  209888. if (browser != 0)
  209889. {
  209890. LPSAFEARRAY sa = 0;
  209891. VARIANT flags, frame, postDataVar, headersVar; // (_variant_t isn't available in all compilers)
  209892. VariantInit (&flags);
  209893. VariantInit (&frame);
  209894. VariantInit (&postDataVar);
  209895. VariantInit (&headersVar);
  209896. if (headers != 0)
  209897. {
  209898. V_VT (&headersVar) = VT_BSTR;
  209899. V_BSTR (&headersVar) = SysAllocString ((const OLECHAR*) headers->joinIntoString ("\r\n"));
  209900. }
  209901. if (postData != 0 && postData->getSize() > 0)
  209902. {
  209903. LPSAFEARRAY sa = SafeArrayCreateVector (VT_UI1, 0, postData->getSize());
  209904. if (sa != 0)
  209905. {
  209906. void* data = 0;
  209907. SafeArrayAccessData (sa, &data);
  209908. jassert (data != 0);
  209909. if (data != 0)
  209910. {
  209911. postData->copyTo (data, 0, postData->getSize());
  209912. SafeArrayUnaccessData (sa);
  209913. VARIANT postDataVar2;
  209914. VariantInit (&postDataVar2);
  209915. V_VT (&postDataVar2) = VT_ARRAY | VT_UI1;
  209916. V_ARRAY (&postDataVar2) = sa;
  209917. postDataVar = postDataVar2;
  209918. }
  209919. }
  209920. }
  209921. browser->Navigate ((BSTR) (const OLECHAR*) url,
  209922. &flags, &frame,
  209923. &postDataVar, &headersVar);
  209924. if (sa != 0)
  209925. SafeArrayDestroy (sa);
  209926. VariantClear (&flags);
  209927. VariantClear (&frame);
  209928. VariantClear (&postDataVar);
  209929. VariantClear (&headersVar);
  209930. }
  209931. }
  209932. IWebBrowser2* browser;
  209933. juce_UseDebuggingNewOperator
  209934. private:
  209935. IConnectionPoint* connectionPoint;
  209936. DWORD adviseCookie;
  209937. class EventHandler : public ComBaseClassHelper <IDispatch>,
  209938. public ComponentMovementWatcher
  209939. {
  209940. public:
  209941. EventHandler (WebBrowserComponent* owner_)
  209942. : ComponentMovementWatcher (owner_),
  209943. owner (owner_)
  209944. {
  209945. }
  209946. ~EventHandler()
  209947. {
  209948. }
  209949. HRESULT __stdcall GetTypeInfoCount (UINT*) { return E_NOTIMPL; }
  209950. HRESULT __stdcall GetTypeInfo (UINT, LCID, ITypeInfo**) { return E_NOTIMPL; }
  209951. HRESULT __stdcall GetIDsOfNames (REFIID, LPOLESTR*, UINT, LCID, DISPID*) { return E_NOTIMPL; }
  209952. HRESULT __stdcall Invoke (DISPID dispIdMember, REFIID /*riid*/, LCID /*lcid*/,
  209953. WORD /*wFlags*/, DISPPARAMS* pDispParams,
  209954. VARIANT* /*pVarResult*/, EXCEPINFO* /*pExcepInfo*/,
  209955. UINT* /*puArgErr*/)
  209956. {
  209957. switch (dispIdMember)
  209958. {
  209959. case DISPID_BEFORENAVIGATE2:
  209960. {
  209961. VARIANT* const vurl = pDispParams->rgvarg[5].pvarVal;
  209962. String url;
  209963. if ((vurl->vt & VT_BYREF) != 0)
  209964. url = *vurl->pbstrVal;
  209965. else
  209966. url = vurl->bstrVal;
  209967. *pDispParams->rgvarg->pboolVal
  209968. = owner->pageAboutToLoad (url) ? VARIANT_FALSE
  209969. : VARIANT_TRUE;
  209970. return S_OK;
  209971. }
  209972. default:
  209973. break;
  209974. }
  209975. return E_NOTIMPL;
  209976. }
  209977. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/) {}
  209978. void componentPeerChanged() {}
  209979. void componentVisibilityChanged (Component&)
  209980. {
  209981. owner->visibilityChanged();
  209982. }
  209983. juce_UseDebuggingNewOperator
  209984. private:
  209985. WebBrowserComponent* const owner;
  209986. EventHandler (const EventHandler&);
  209987. EventHandler& operator= (const EventHandler&);
  209988. };
  209989. };
  209990. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  209991. : browser (0),
  209992. blankPageShown (false),
  209993. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  209994. {
  209995. setOpaque (true);
  209996. addAndMakeVisible (browser = new WebBrowserComponentInternal());
  209997. }
  209998. WebBrowserComponent::~WebBrowserComponent()
  209999. {
  210000. delete browser;
  210001. }
  210002. void WebBrowserComponent::goToURL (const String& url,
  210003. const StringArray* headers,
  210004. const MemoryBlock* postData)
  210005. {
  210006. lastURL = url;
  210007. lastHeaders.clear();
  210008. if (headers != 0)
  210009. lastHeaders = *headers;
  210010. lastPostData.setSize (0);
  210011. if (postData != 0)
  210012. lastPostData = *postData;
  210013. blankPageShown = false;
  210014. browser->goToURL (url, headers, postData);
  210015. }
  210016. void WebBrowserComponent::stop()
  210017. {
  210018. if (browser->browser != 0)
  210019. browser->browser->Stop();
  210020. }
  210021. void WebBrowserComponent::goBack()
  210022. {
  210023. lastURL = String::empty;
  210024. blankPageShown = false;
  210025. if (browser->browser != 0)
  210026. browser->browser->GoBack();
  210027. }
  210028. void WebBrowserComponent::goForward()
  210029. {
  210030. lastURL = String::empty;
  210031. if (browser->browser != 0)
  210032. browser->browser->GoForward();
  210033. }
  210034. void WebBrowserComponent::refresh()
  210035. {
  210036. if (browser->browser != 0)
  210037. browser->browser->Refresh();
  210038. }
  210039. void WebBrowserComponent::paint (Graphics& g)
  210040. {
  210041. if (browser->browser == 0)
  210042. g.fillAll (Colours::white);
  210043. }
  210044. void WebBrowserComponent::checkWindowAssociation()
  210045. {
  210046. if (isShowing())
  210047. {
  210048. if (browser->browser == 0 && getPeer() != 0)
  210049. {
  210050. browser->createBrowser();
  210051. reloadLastURL();
  210052. }
  210053. else
  210054. {
  210055. if (blankPageShown)
  210056. goBack();
  210057. }
  210058. }
  210059. else
  210060. {
  210061. if (browser != 0 && unloadPageWhenBrowserIsHidden && ! blankPageShown)
  210062. {
  210063. // when the component becomes invisible, some stuff like flash
  210064. // carries on playing audio, so we need to force it onto a blank
  210065. // page to avoid this..
  210066. blankPageShown = true;
  210067. browser->goToURL ("about:blank", 0, 0);
  210068. }
  210069. }
  210070. }
  210071. void WebBrowserComponent::reloadLastURL()
  210072. {
  210073. if (lastURL.isNotEmpty())
  210074. {
  210075. goToURL (lastURL, &lastHeaders, &lastPostData);
  210076. lastURL = String::empty;
  210077. }
  210078. }
  210079. void WebBrowserComponent::parentHierarchyChanged()
  210080. {
  210081. checkWindowAssociation();
  210082. }
  210083. void WebBrowserComponent::resized()
  210084. {
  210085. browser->setSize (getWidth(), getHeight());
  210086. }
  210087. void WebBrowserComponent::visibilityChanged()
  210088. {
  210089. checkWindowAssociation();
  210090. }
  210091. bool WebBrowserComponent::pageAboutToLoad (const String&)
  210092. {
  210093. return true;
  210094. }
  210095. #endif
  210096. /*** End of inlined file: juce_win32_WebBrowserComponent.cpp ***/
  210097. /*** Start of inlined file: juce_win32_OpenGLComponent.cpp ***/
  210098. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  210099. // compiled on its own).
  210100. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  210101. #define WGL_EXT_FUNCTION_INIT(extType, extFunc) \
  210102. ((extFunc = (extType) wglGetProcAddress (#extFunc)) != 0)
  210103. typedef const char* (WINAPI* PFNWGLGETEXTENSIONSSTRINGARBPROC) (HDC hdc);
  210104. typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBIVARBPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
  210105. typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATARBPROC) (HDC hdc, const int* piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
  210106. typedef BOOL (WINAPI * PFNWGLSWAPINTERVALEXTPROC) (int interval);
  210107. typedef int (WINAPI * PFNWGLGETSWAPINTERVALEXTPROC) (void);
  210108. #define WGL_NUMBER_PIXEL_FORMATS_ARB 0x2000
  210109. #define WGL_DRAW_TO_WINDOW_ARB 0x2001
  210110. #define WGL_ACCELERATION_ARB 0x2003
  210111. #define WGL_SWAP_METHOD_ARB 0x2007
  210112. #define WGL_SUPPORT_OPENGL_ARB 0x2010
  210113. #define WGL_PIXEL_TYPE_ARB 0x2013
  210114. #define WGL_DOUBLE_BUFFER_ARB 0x2011
  210115. #define WGL_COLOR_BITS_ARB 0x2014
  210116. #define WGL_RED_BITS_ARB 0x2015
  210117. #define WGL_GREEN_BITS_ARB 0x2017
  210118. #define WGL_BLUE_BITS_ARB 0x2019
  210119. #define WGL_ALPHA_BITS_ARB 0x201B
  210120. #define WGL_DEPTH_BITS_ARB 0x2022
  210121. #define WGL_STENCIL_BITS_ARB 0x2023
  210122. #define WGL_FULL_ACCELERATION_ARB 0x2027
  210123. #define WGL_ACCUM_RED_BITS_ARB 0x201E
  210124. #define WGL_ACCUM_GREEN_BITS_ARB 0x201F
  210125. #define WGL_ACCUM_BLUE_BITS_ARB 0x2020
  210126. #define WGL_ACCUM_ALPHA_BITS_ARB 0x2021
  210127. #define WGL_STEREO_ARB 0x2012
  210128. #define WGL_SAMPLE_BUFFERS_ARB 0x2041
  210129. #define WGL_SAMPLES_ARB 0x2042
  210130. #define WGL_TYPE_RGBA_ARB 0x202B
  210131. static void getWglExtensions (HDC dc, StringArray& result) throw()
  210132. {
  210133. PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB = 0;
  210134. if (WGL_EXT_FUNCTION_INIT (PFNWGLGETEXTENSIONSSTRINGARBPROC, wglGetExtensionsStringARB))
  210135. result.addTokens (String (wglGetExtensionsStringARB (dc)), false);
  210136. else
  210137. jassertfalse; // If this fails, it may be because you didn't activate the openGL context
  210138. }
  210139. class WindowedGLContext : public OpenGLContext
  210140. {
  210141. public:
  210142. WindowedGLContext (Component* const component_,
  210143. HGLRC contextToShareWith,
  210144. const OpenGLPixelFormat& pixelFormat)
  210145. : renderContext (0),
  210146. dc (0),
  210147. component (component_)
  210148. {
  210149. jassert (component != 0);
  210150. createNativeWindow();
  210151. // Use a default pixel format that should be supported everywhere
  210152. PIXELFORMATDESCRIPTOR pfd;
  210153. zerostruct (pfd);
  210154. pfd.nSize = sizeof (pfd);
  210155. pfd.nVersion = 1;
  210156. pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
  210157. pfd.iPixelType = PFD_TYPE_RGBA;
  210158. pfd.cColorBits = 24;
  210159. pfd.cDepthBits = 16;
  210160. const int format = ChoosePixelFormat (dc, &pfd);
  210161. if (format != 0)
  210162. SetPixelFormat (dc, format, &pfd);
  210163. renderContext = wglCreateContext (dc);
  210164. makeActive();
  210165. setPixelFormat (pixelFormat);
  210166. if (contextToShareWith != 0 && renderContext != 0)
  210167. wglShareLists (contextToShareWith, renderContext);
  210168. }
  210169. ~WindowedGLContext()
  210170. {
  210171. deleteContext();
  210172. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  210173. nativeWindow = 0;
  210174. }
  210175. void deleteContext()
  210176. {
  210177. makeInactive();
  210178. if (renderContext != 0)
  210179. {
  210180. wglDeleteContext (renderContext);
  210181. renderContext = 0;
  210182. }
  210183. }
  210184. bool makeActive() const throw()
  210185. {
  210186. jassert (renderContext != 0);
  210187. return wglMakeCurrent (dc, renderContext) != 0;
  210188. }
  210189. bool makeInactive() const throw()
  210190. {
  210191. return (! isActive()) || (wglMakeCurrent (0, 0) != 0);
  210192. }
  210193. bool isActive() const throw()
  210194. {
  210195. return wglGetCurrentContext() == renderContext;
  210196. }
  210197. const OpenGLPixelFormat getPixelFormat() const
  210198. {
  210199. OpenGLPixelFormat pf;
  210200. makeActive();
  210201. StringArray availableExtensions;
  210202. getWglExtensions (dc, availableExtensions);
  210203. fillInPixelFormatDetails (GetPixelFormat (dc), pf, availableExtensions);
  210204. return pf;
  210205. }
  210206. void* getRawContext() const throw()
  210207. {
  210208. return renderContext;
  210209. }
  210210. bool setPixelFormat (const OpenGLPixelFormat& pixelFormat)
  210211. {
  210212. makeActive();
  210213. PIXELFORMATDESCRIPTOR pfd;
  210214. zerostruct (pfd);
  210215. pfd.nSize = sizeof (pfd);
  210216. pfd.nVersion = 1;
  210217. pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER;
  210218. pfd.iPixelType = PFD_TYPE_RGBA;
  210219. pfd.iLayerType = PFD_MAIN_PLANE;
  210220. pfd.cColorBits = (BYTE) (pixelFormat.redBits + pixelFormat.greenBits + pixelFormat.blueBits);
  210221. pfd.cRedBits = (BYTE) pixelFormat.redBits;
  210222. pfd.cGreenBits = (BYTE) pixelFormat.greenBits;
  210223. pfd.cBlueBits = (BYTE) pixelFormat.blueBits;
  210224. pfd.cAlphaBits = (BYTE) pixelFormat.alphaBits;
  210225. pfd.cDepthBits = (BYTE) pixelFormat.depthBufferBits;
  210226. pfd.cStencilBits = (BYTE) pixelFormat.stencilBufferBits;
  210227. pfd.cAccumBits = (BYTE) (pixelFormat.accumulationBufferRedBits + pixelFormat.accumulationBufferGreenBits
  210228. + pixelFormat.accumulationBufferBlueBits + pixelFormat.accumulationBufferAlphaBits);
  210229. pfd.cAccumRedBits = (BYTE) pixelFormat.accumulationBufferRedBits;
  210230. pfd.cAccumGreenBits = (BYTE) pixelFormat.accumulationBufferGreenBits;
  210231. pfd.cAccumBlueBits = (BYTE) pixelFormat.accumulationBufferBlueBits;
  210232. pfd.cAccumAlphaBits = (BYTE) pixelFormat.accumulationBufferAlphaBits;
  210233. int format = 0;
  210234. PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = 0;
  210235. StringArray availableExtensions;
  210236. getWglExtensions (dc, availableExtensions);
  210237. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  210238. && WGL_EXT_FUNCTION_INIT (PFNWGLCHOOSEPIXELFORMATARBPROC, wglChoosePixelFormatARB))
  210239. {
  210240. int attributes[64];
  210241. int n = 0;
  210242. attributes[n++] = WGL_DRAW_TO_WINDOW_ARB;
  210243. attributes[n++] = GL_TRUE;
  210244. attributes[n++] = WGL_SUPPORT_OPENGL_ARB;
  210245. attributes[n++] = GL_TRUE;
  210246. attributes[n++] = WGL_ACCELERATION_ARB;
  210247. attributes[n++] = WGL_FULL_ACCELERATION_ARB;
  210248. attributes[n++] = WGL_DOUBLE_BUFFER_ARB;
  210249. attributes[n++] = GL_TRUE;
  210250. attributes[n++] = WGL_PIXEL_TYPE_ARB;
  210251. attributes[n++] = WGL_TYPE_RGBA_ARB;
  210252. attributes[n++] = WGL_COLOR_BITS_ARB;
  210253. attributes[n++] = pfd.cColorBits;
  210254. attributes[n++] = WGL_RED_BITS_ARB;
  210255. attributes[n++] = pixelFormat.redBits;
  210256. attributes[n++] = WGL_GREEN_BITS_ARB;
  210257. attributes[n++] = pixelFormat.greenBits;
  210258. attributes[n++] = WGL_BLUE_BITS_ARB;
  210259. attributes[n++] = pixelFormat.blueBits;
  210260. attributes[n++] = WGL_ALPHA_BITS_ARB;
  210261. attributes[n++] = pixelFormat.alphaBits;
  210262. attributes[n++] = WGL_DEPTH_BITS_ARB;
  210263. attributes[n++] = pixelFormat.depthBufferBits;
  210264. if (pixelFormat.stencilBufferBits > 0)
  210265. {
  210266. attributes[n++] = WGL_STENCIL_BITS_ARB;
  210267. attributes[n++] = pixelFormat.stencilBufferBits;
  210268. }
  210269. attributes[n++] = WGL_ACCUM_RED_BITS_ARB;
  210270. attributes[n++] = pixelFormat.accumulationBufferRedBits;
  210271. attributes[n++] = WGL_ACCUM_GREEN_BITS_ARB;
  210272. attributes[n++] = pixelFormat.accumulationBufferGreenBits;
  210273. attributes[n++] = WGL_ACCUM_BLUE_BITS_ARB;
  210274. attributes[n++] = pixelFormat.accumulationBufferBlueBits;
  210275. attributes[n++] = WGL_ACCUM_ALPHA_BITS_ARB;
  210276. attributes[n++] = pixelFormat.accumulationBufferAlphaBits;
  210277. if (availableExtensions.contains ("WGL_ARB_multisample")
  210278. && pixelFormat.fullSceneAntiAliasingNumSamples > 0)
  210279. {
  210280. attributes[n++] = WGL_SAMPLE_BUFFERS_ARB;
  210281. attributes[n++] = 1;
  210282. attributes[n++] = WGL_SAMPLES_ARB;
  210283. attributes[n++] = pixelFormat.fullSceneAntiAliasingNumSamples;
  210284. }
  210285. attributes[n++] = 0;
  210286. UINT formatsCount;
  210287. const BOOL ok = wglChoosePixelFormatARB (dc, attributes, 0, 1, &format, &formatsCount);
  210288. (void) ok;
  210289. jassert (ok);
  210290. }
  210291. else
  210292. {
  210293. format = ChoosePixelFormat (dc, &pfd);
  210294. }
  210295. if (format != 0)
  210296. {
  210297. makeInactive();
  210298. // win32 can't change the pixel format of a window, so need to delete the
  210299. // old one and create a new one..
  210300. jassert (nativeWindow != 0);
  210301. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  210302. nativeWindow = 0;
  210303. createNativeWindow();
  210304. if (SetPixelFormat (dc, format, &pfd))
  210305. {
  210306. wglDeleteContext (renderContext);
  210307. renderContext = wglCreateContext (dc);
  210308. jassert (renderContext != 0);
  210309. return renderContext != 0;
  210310. }
  210311. }
  210312. return false;
  210313. }
  210314. void updateWindowPosition (int x, int y, int w, int h, int)
  210315. {
  210316. SetWindowPos ((HWND) nativeWindow->getNativeHandle(), 0,
  210317. x, y, w, h,
  210318. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  210319. }
  210320. void repaint()
  210321. {
  210322. nativeWindow->repaint (nativeWindow->getBounds().withPosition (Point<int>()));
  210323. }
  210324. void swapBuffers()
  210325. {
  210326. SwapBuffers (dc);
  210327. }
  210328. bool setSwapInterval (int numFramesPerSwap)
  210329. {
  210330. makeActive();
  210331. StringArray availableExtensions;
  210332. getWglExtensions (dc, availableExtensions);
  210333. PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = 0;
  210334. return availableExtensions.contains ("WGL_EXT_swap_control")
  210335. && WGL_EXT_FUNCTION_INIT (PFNWGLSWAPINTERVALEXTPROC, wglSwapIntervalEXT)
  210336. && wglSwapIntervalEXT (numFramesPerSwap) != FALSE;
  210337. }
  210338. int getSwapInterval() const
  210339. {
  210340. makeActive();
  210341. StringArray availableExtensions;
  210342. getWglExtensions (dc, availableExtensions);
  210343. PFNWGLGETSWAPINTERVALEXTPROC wglGetSwapIntervalEXT = 0;
  210344. if (availableExtensions.contains ("WGL_EXT_swap_control")
  210345. && WGL_EXT_FUNCTION_INIT (PFNWGLGETSWAPINTERVALEXTPROC, wglGetSwapIntervalEXT))
  210346. return wglGetSwapIntervalEXT();
  210347. return 0;
  210348. }
  210349. void findAlternativeOpenGLPixelFormats (OwnedArray <OpenGLPixelFormat>& results)
  210350. {
  210351. jassert (isActive());
  210352. StringArray availableExtensions;
  210353. getWglExtensions (dc, availableExtensions);
  210354. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  210355. int numTypes = 0;
  210356. if (availableExtensions.contains("WGL_ARB_pixel_format")
  210357. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  210358. {
  210359. int attributes = WGL_NUMBER_PIXEL_FORMATS_ARB;
  210360. if (! wglGetPixelFormatAttribivARB (dc, 1, 0, 1, &attributes, &numTypes))
  210361. jassertfalse;
  210362. }
  210363. else
  210364. {
  210365. numTypes = DescribePixelFormat (dc, 0, 0, 0);
  210366. }
  210367. OpenGLPixelFormat pf;
  210368. for (int i = 0; i < numTypes; ++i)
  210369. {
  210370. if (fillInPixelFormatDetails (i + 1, pf, availableExtensions))
  210371. {
  210372. bool alreadyListed = false;
  210373. for (int j = results.size(); --j >= 0;)
  210374. if (pf == *results.getUnchecked(j))
  210375. alreadyListed = true;
  210376. if (! alreadyListed)
  210377. results.add (new OpenGLPixelFormat (pf));
  210378. }
  210379. }
  210380. }
  210381. void* getNativeWindowHandle() const
  210382. {
  210383. return nativeWindow != 0 ? nativeWindow->getNativeHandle() : 0;
  210384. }
  210385. juce_UseDebuggingNewOperator
  210386. HGLRC renderContext;
  210387. private:
  210388. ScopedPointer<Win32ComponentPeer> nativeWindow;
  210389. Component* const component;
  210390. HDC dc;
  210391. void createNativeWindow()
  210392. {
  210393. Win32ComponentPeer* topLevelPeer = dynamic_cast <Win32ComponentPeer*> (component->getTopLevelComponent()->getPeer());
  210394. nativeWindow = new Win32ComponentPeer (component, ComponentPeer::windowIgnoresMouseClicks,
  210395. topLevelPeer == 0 ? 0 : (HWND) topLevelPeer->getNativeHandle());
  210396. nativeWindow->dontRepaint = true;
  210397. nativeWindow->setVisible (true);
  210398. dc = GetDC ((HWND) nativeWindow->getNativeHandle());
  210399. }
  210400. bool fillInPixelFormatDetails (const int pixelFormatIndex,
  210401. OpenGLPixelFormat& result,
  210402. const StringArray& availableExtensions) const throw()
  210403. {
  210404. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  210405. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  210406. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  210407. {
  210408. int attributes[32];
  210409. int numAttributes = 0;
  210410. attributes[numAttributes++] = WGL_DRAW_TO_WINDOW_ARB;
  210411. attributes[numAttributes++] = WGL_SUPPORT_OPENGL_ARB;
  210412. attributes[numAttributes++] = WGL_ACCELERATION_ARB;
  210413. attributes[numAttributes++] = WGL_DOUBLE_BUFFER_ARB;
  210414. attributes[numAttributes++] = WGL_PIXEL_TYPE_ARB;
  210415. attributes[numAttributes++] = WGL_RED_BITS_ARB;
  210416. attributes[numAttributes++] = WGL_GREEN_BITS_ARB;
  210417. attributes[numAttributes++] = WGL_BLUE_BITS_ARB;
  210418. attributes[numAttributes++] = WGL_ALPHA_BITS_ARB;
  210419. attributes[numAttributes++] = WGL_DEPTH_BITS_ARB;
  210420. attributes[numAttributes++] = WGL_STENCIL_BITS_ARB;
  210421. attributes[numAttributes++] = WGL_ACCUM_RED_BITS_ARB;
  210422. attributes[numAttributes++] = WGL_ACCUM_GREEN_BITS_ARB;
  210423. attributes[numAttributes++] = WGL_ACCUM_BLUE_BITS_ARB;
  210424. attributes[numAttributes++] = WGL_ACCUM_ALPHA_BITS_ARB;
  210425. if (availableExtensions.contains ("WGL_ARB_multisample"))
  210426. attributes[numAttributes++] = WGL_SAMPLES_ARB;
  210427. int values[32];
  210428. zeromem (values, sizeof (values));
  210429. if (wglGetPixelFormatAttribivARB (dc, pixelFormatIndex, 0, numAttributes, attributes, values))
  210430. {
  210431. int n = 0;
  210432. bool isValidFormat = (values[n++] == GL_TRUE); // WGL_DRAW_TO_WINDOW_ARB
  210433. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_SUPPORT_OPENGL_ARB
  210434. isValidFormat = (values[n++] == WGL_FULL_ACCELERATION_ARB) && isValidFormat; // WGL_ACCELERATION_ARB
  210435. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_DOUBLE_BUFFER_ARB:
  210436. isValidFormat = (values[n++] == WGL_TYPE_RGBA_ARB) && isValidFormat; // WGL_PIXEL_TYPE_ARB
  210437. result.redBits = values[n++]; // WGL_RED_BITS_ARB
  210438. result.greenBits = values[n++]; // WGL_GREEN_BITS_ARB
  210439. result.blueBits = values[n++]; // WGL_BLUE_BITS_ARB
  210440. result.alphaBits = values[n++]; // WGL_ALPHA_BITS_ARB
  210441. result.depthBufferBits = values[n++]; // WGL_DEPTH_BITS_ARB
  210442. result.stencilBufferBits = values[n++]; // WGL_STENCIL_BITS_ARB
  210443. result.accumulationBufferRedBits = values[n++]; // WGL_ACCUM_RED_BITS_ARB
  210444. result.accumulationBufferGreenBits = values[n++]; // WGL_ACCUM_GREEN_BITS_ARB
  210445. result.accumulationBufferBlueBits = values[n++]; // WGL_ACCUM_BLUE_BITS_ARB
  210446. result.accumulationBufferAlphaBits = values[n++]; // WGL_ACCUM_ALPHA_BITS_ARB
  210447. result.fullSceneAntiAliasingNumSamples = (uint8) values[n++]; // WGL_SAMPLES_ARB
  210448. return isValidFormat;
  210449. }
  210450. else
  210451. {
  210452. jassertfalse;
  210453. }
  210454. }
  210455. else
  210456. {
  210457. PIXELFORMATDESCRIPTOR pfd;
  210458. if (DescribePixelFormat (dc, pixelFormatIndex, sizeof (pfd), &pfd))
  210459. {
  210460. result.redBits = pfd.cRedBits;
  210461. result.greenBits = pfd.cGreenBits;
  210462. result.blueBits = pfd.cBlueBits;
  210463. result.alphaBits = pfd.cAlphaBits;
  210464. result.depthBufferBits = pfd.cDepthBits;
  210465. result.stencilBufferBits = pfd.cStencilBits;
  210466. result.accumulationBufferRedBits = pfd.cAccumRedBits;
  210467. result.accumulationBufferGreenBits = pfd.cAccumGreenBits;
  210468. result.accumulationBufferBlueBits = pfd.cAccumBlueBits;
  210469. result.accumulationBufferAlphaBits = pfd.cAccumAlphaBits;
  210470. result.fullSceneAntiAliasingNumSamples = 0;
  210471. return true;
  210472. }
  210473. else
  210474. {
  210475. jassertfalse;
  210476. }
  210477. }
  210478. return false;
  210479. }
  210480. WindowedGLContext (const WindowedGLContext&);
  210481. WindowedGLContext& operator= (const WindowedGLContext&);
  210482. };
  210483. OpenGLContext* OpenGLComponent::createContext()
  210484. {
  210485. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this,
  210486. contextToShareListsWith != 0 ? (HGLRC) contextToShareListsWith->getRawContext() : 0,
  210487. preferredPixelFormat));
  210488. return (c->renderContext != 0) ? c.release() : 0;
  210489. }
  210490. void* OpenGLComponent::getNativeWindowHandle() const
  210491. {
  210492. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle() : 0;
  210493. }
  210494. void juce_glViewport (const int w, const int h)
  210495. {
  210496. glViewport (0, 0, w, h);
  210497. }
  210498. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  210499. OwnedArray <OpenGLPixelFormat>& results)
  210500. {
  210501. Component tempComp;
  210502. {
  210503. WindowedGLContext wc (component, 0, OpenGLPixelFormat (8, 8, 16, 0));
  210504. wc.makeActive();
  210505. wc.findAlternativeOpenGLPixelFormats (results);
  210506. }
  210507. }
  210508. #endif
  210509. /*** End of inlined file: juce_win32_OpenGLComponent.cpp ***/
  210510. /*** Start of inlined file: juce_win32_AudioCDReader.cpp ***/
  210511. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  210512. // compiled on its own).
  210513. #if JUCE_INCLUDED_FILE
  210514. #if JUCE_USE_CDREADER
  210515. namespace CDReaderHelpers
  210516. {
  210517. //***************************************************************************
  210518. // %%% TARGET STATUS VALUES %%%
  210519. //***************************************************************************
  210520. #define STATUS_GOOD 0x00 // Status Good
  210521. #define STATUS_CHKCOND 0x02 // Check Condition
  210522. #define STATUS_CONDMET 0x04 // Condition Met
  210523. #define STATUS_BUSY 0x08 // Busy
  210524. #define STATUS_INTERM 0x10 // Intermediate
  210525. #define STATUS_INTCDMET 0x14 // Intermediate-condition met
  210526. #define STATUS_RESCONF 0x18 // Reservation conflict
  210527. #define STATUS_COMTERM 0x22 // Command Terminated
  210528. #define STATUS_QFULL 0x28 // Queue full
  210529. //***************************************************************************
  210530. // %%% SCSI MISCELLANEOUS EQUATES %%%
  210531. //***************************************************************************
  210532. #define MAXLUN 7 // Maximum Logical Unit Id
  210533. #define MAXTARG 7 // Maximum Target Id
  210534. #define MAX_SCSI_LUNS 64 // Maximum Number of SCSI LUNs
  210535. #define MAX_NUM_HA 8 // Maximum Number of SCSI HA's
  210536. //***************************************************************************
  210537. // %%% Commands for all Device Types %%%
  210538. //***************************************************************************
  210539. #define SCSI_CHANGE_DEF 0x40 // Change Definition (Optional)
  210540. #define SCSI_COMPARE 0x39 // Compare (O)
  210541. #define SCSI_COPY 0x18 // Copy (O)
  210542. #define SCSI_COP_VERIFY 0x3A // Copy and Verify (O)
  210543. #define SCSI_INQUIRY 0x12 // Inquiry (MANDATORY)
  210544. #define SCSI_LOG_SELECT 0x4C // Log Select (O)
  210545. #define SCSI_LOG_SENSE 0x4D // Log Sense (O)
  210546. #define SCSI_MODE_SEL6 0x15 // Mode Select 6-byte (Device Specific)
  210547. #define SCSI_MODE_SEL10 0x55 // Mode Select 10-byte (Device Specific)
  210548. #define SCSI_MODE_SEN6 0x1A // Mode Sense 6-byte (Device Specific)
  210549. #define SCSI_MODE_SEN10 0x5A // Mode Sense 10-byte (Device Specific)
  210550. #define SCSI_READ_BUFF 0x3C // Read Buffer (O)
  210551. #define SCSI_REQ_SENSE 0x03 // Request Sense (MANDATORY)
  210552. #define SCSI_SEND_DIAG 0x1D // Send Diagnostic (O)
  210553. #define SCSI_TST_U_RDY 0x00 // Test Unit Ready (MANDATORY)
  210554. #define SCSI_WRITE_BUFF 0x3B // Write Buffer (O)
  210555. //***************************************************************************
  210556. // %%% Commands Unique to Direct Access Devices %%%
  210557. //***************************************************************************
  210558. #define SCSI_COMPARE 0x39 // Compare (O)
  210559. #define SCSI_FORMAT 0x04 // Format Unit (MANDATORY)
  210560. #define SCSI_LCK_UN_CAC 0x36 // Lock Unlock Cache (O)
  210561. #define SCSI_PREFETCH 0x34 // Prefetch (O)
  210562. #define SCSI_MED_REMOVL 0x1E // Prevent/Allow medium Removal (O)
  210563. #define SCSI_READ6 0x08 // Read 6-byte (MANDATORY)
  210564. #define SCSI_READ10 0x28 // Read 10-byte (MANDATORY)
  210565. #define SCSI_RD_CAPAC 0x25 // Read Capacity (MANDATORY)
  210566. #define SCSI_RD_DEFECT 0x37 // Read Defect Data (O)
  210567. #define SCSI_READ_LONG 0x3E // Read Long (O)
  210568. #define SCSI_REASS_BLK 0x07 // Reassign Blocks (O)
  210569. #define SCSI_RCV_DIAG 0x1C // Receive Diagnostic Results (O)
  210570. #define SCSI_RELEASE 0x17 // Release Unit (MANDATORY)
  210571. #define SCSI_REZERO 0x01 // Rezero Unit (O)
  210572. #define SCSI_SRCH_DAT_E 0x31 // Search Data Equal (O)
  210573. #define SCSI_SRCH_DAT_H 0x30 // Search Data High (O)
  210574. #define SCSI_SRCH_DAT_L 0x32 // Search Data Low (O)
  210575. #define SCSI_SEEK6 0x0B // Seek 6-Byte (O)
  210576. #define SCSI_SEEK10 0x2B // Seek 10-Byte (O)
  210577. #define SCSI_SEND_DIAG 0x1D // Send Diagnostics (MANDATORY)
  210578. #define SCSI_SET_LIMIT 0x33 // Set Limits (O)
  210579. #define SCSI_START_STP 0x1B // Start/Stop Unit (O)
  210580. #define SCSI_SYNC_CACHE 0x35 // Synchronize Cache (O)
  210581. #define SCSI_VERIFY 0x2F // Verify (O)
  210582. #define SCSI_WRITE6 0x0A // Write 6-Byte (MANDATORY)
  210583. #define SCSI_WRITE10 0x2A // Write 10-Byte (MANDATORY)
  210584. #define SCSI_WRT_VERIFY 0x2E // Write and Verify (O)
  210585. #define SCSI_WRITE_LONG 0x3F // Write Long (O)
  210586. #define SCSI_WRITE_SAME 0x41 // Write Same (O)
  210587. //***************************************************************************
  210588. // %%% Commands Unique to Sequential Access Devices %%%
  210589. //***************************************************************************
  210590. #define SCSI_ERASE 0x19 // Erase (MANDATORY)
  210591. #define SCSI_LOAD_UN 0x1b // Load/Unload (O)
  210592. #define SCSI_LOCATE 0x2B // Locate (O)
  210593. #define SCSI_RD_BLK_LIM 0x05 // Read Block Limits (MANDATORY)
  210594. #define SCSI_READ_POS 0x34 // Read Position (O)
  210595. #define SCSI_READ_REV 0x0F // Read Reverse (O)
  210596. #define SCSI_REC_BF_DAT 0x14 // Recover Buffer Data (O)
  210597. #define SCSI_RESERVE 0x16 // Reserve Unit (MANDATORY)
  210598. #define SCSI_REWIND 0x01 // Rewind (MANDATORY)
  210599. #define SCSI_SPACE 0x11 // Space (MANDATORY)
  210600. #define SCSI_VERIFY_T 0x13 // Verify (Tape) (O)
  210601. #define SCSI_WRT_FILE 0x10 // Write Filemarks (MANDATORY)
  210602. //***************************************************************************
  210603. // %%% Commands Unique to Printer Devices %%%
  210604. //***************************************************************************
  210605. #define SCSI_PRINT 0x0A // Print (MANDATORY)
  210606. #define SCSI_SLEW_PNT 0x0B // Slew and Print (O)
  210607. #define SCSI_STOP_PNT 0x1B // Stop Print (O)
  210608. #define SCSI_SYNC_BUFF 0x10 // Synchronize Buffer (O)
  210609. //***************************************************************************
  210610. // %%% Commands Unique to Processor Devices %%%
  210611. //***************************************************************************
  210612. #define SCSI_RECEIVE 0x08 // Receive (O)
  210613. #define SCSI_SEND 0x0A // Send (O)
  210614. //***************************************************************************
  210615. // %%% Commands Unique to Write-Once Devices %%%
  210616. //***************************************************************************
  210617. #define SCSI_MEDIUM_SCN 0x38 // Medium Scan (O)
  210618. #define SCSI_SRCHDATE10 0x31 // Search Data Equal 10-Byte (O)
  210619. #define SCSI_SRCHDATE12 0xB1 // Search Data Equal 12-Byte (O)
  210620. #define SCSI_SRCHDATH10 0x30 // Search Data High 10-Byte (O)
  210621. #define SCSI_SRCHDATH12 0xB0 // Search Data High 12-Byte (O)
  210622. #define SCSI_SRCHDATL10 0x32 // Search Data Low 10-Byte (O)
  210623. #define SCSI_SRCHDATL12 0xB2 // Search Data Low 12-Byte (O)
  210624. #define SCSI_SET_LIM_10 0x33 // Set Limits 10-Byte (O)
  210625. #define SCSI_SET_LIM_12 0xB3 // Set Limits 10-Byte (O)
  210626. #define SCSI_VERIFY10 0x2F // Verify 10-Byte (O)
  210627. #define SCSI_VERIFY12 0xAF // Verify 12-Byte (O)
  210628. #define SCSI_WRITE12 0xAA // Write 12-Byte (O)
  210629. #define SCSI_WRT_VER10 0x2E // Write and Verify 10-Byte (O)
  210630. #define SCSI_WRT_VER12 0xAE // Write and Verify 12-Byte (O)
  210631. //***************************************************************************
  210632. // %%% Commands Unique to CD-ROM Devices %%%
  210633. //***************************************************************************
  210634. #define SCSI_PLAYAUD_10 0x45 // Play Audio 10-Byte (O)
  210635. #define SCSI_PLAYAUD_12 0xA5 // Play Audio 12-Byte 12-Byte (O)
  210636. #define SCSI_PLAYAUDMSF 0x47 // Play Audio MSF (O)
  210637. #define SCSI_PLAYA_TKIN 0x48 // Play Audio Track/Index (O)
  210638. #define SCSI_PLYTKREL10 0x49 // Play Track Relative 10-Byte (O)
  210639. #define SCSI_PLYTKREL12 0xA9 // Play Track Relative 12-Byte (O)
  210640. #define SCSI_READCDCAP 0x25 // Read CD-ROM Capacity (MANDATORY)
  210641. #define SCSI_READHEADER 0x44 // Read Header (O)
  210642. #define SCSI_SUBCHANNEL 0x42 // Read Subchannel (O)
  210643. #define SCSI_READ_TOC 0x43 // Read TOC (O)
  210644. //***************************************************************************
  210645. // %%% Commands Unique to Scanner Devices %%%
  210646. //***************************************************************************
  210647. #define SCSI_GETDBSTAT 0x34 // Get Data Buffer Status (O)
  210648. #define SCSI_GETWINDOW 0x25 // Get Window (O)
  210649. #define SCSI_OBJECTPOS 0x31 // Object Postion (O)
  210650. #define SCSI_SCAN 0x1B // Scan (O)
  210651. #define SCSI_SETWINDOW 0x24 // Set Window (MANDATORY)
  210652. //***************************************************************************
  210653. // %%% Commands Unique to Optical Memory Devices %%%
  210654. //***************************************************************************
  210655. #define SCSI_UpdateBlk 0x3D // Update Block (O)
  210656. //***************************************************************************
  210657. // %%% Commands Unique to Medium Changer Devices %%%
  210658. //***************************************************************************
  210659. #define SCSI_EXCHMEDIUM 0xA6 // Exchange Medium (O)
  210660. #define SCSI_INITELSTAT 0x07 // Initialize Element Status (O)
  210661. #define SCSI_POSTOELEM 0x2B // Position to Element (O)
  210662. #define SCSI_REQ_VE_ADD 0xB5 // Request Volume Element Address (O)
  210663. #define SCSI_SENDVOLTAG 0xB6 // Send Volume Tag (O)
  210664. //***************************************************************************
  210665. // %%% Commands Unique to Communication Devices %%%
  210666. //***************************************************************************
  210667. #define SCSI_GET_MSG_6 0x08 // Get Message 6-Byte (MANDATORY)
  210668. #define SCSI_GET_MSG_10 0x28 // Get Message 10-Byte (O)
  210669. #define SCSI_GET_MSG_12 0xA8 // Get Message 12-Byte (O)
  210670. #define SCSI_SND_MSG_6 0x0A // Send Message 6-Byte (MANDATORY)
  210671. #define SCSI_SND_MSG_10 0x2A // Send Message 10-Byte (O)
  210672. #define SCSI_SND_MSG_12 0xAA // Send Message 12-Byte (O)
  210673. //***************************************************************************
  210674. // %%% Request Sense Data Format %%%
  210675. //***************************************************************************
  210676. typedef struct {
  210677. BYTE ErrorCode; // Error Code (70H or 71H)
  210678. BYTE SegmentNum; // Number of current segment descriptor
  210679. BYTE SenseKey; // Sense Key(See bit definitions too)
  210680. BYTE InfoByte0; // Information MSB
  210681. BYTE InfoByte1; // Information MID
  210682. BYTE InfoByte2; // Information MID
  210683. BYTE InfoByte3; // Information LSB
  210684. BYTE AddSenLen; // Additional Sense Length
  210685. BYTE ComSpecInf0; // Command Specific Information MSB
  210686. BYTE ComSpecInf1; // Command Specific Information MID
  210687. BYTE ComSpecInf2; // Command Specific Information MID
  210688. BYTE ComSpecInf3; // Command Specific Information LSB
  210689. BYTE AddSenseCode; // Additional Sense Code
  210690. BYTE AddSenQual; // Additional Sense Code Qualifier
  210691. BYTE FieldRepUCode; // Field Replaceable Unit Code
  210692. BYTE SenKeySpec15; // Sense Key Specific 15th byte
  210693. BYTE SenKeySpec16; // Sense Key Specific 16th byte
  210694. BYTE SenKeySpec17; // Sense Key Specific 17th byte
  210695. BYTE AddSenseBytes; // Additional Sense Bytes
  210696. } SENSE_DATA_FMT;
  210697. //***************************************************************************
  210698. // %%% REQUEST SENSE ERROR CODE %%%
  210699. //***************************************************************************
  210700. #define SERROR_CURRENT 0x70 // Current Errors
  210701. #define SERROR_DEFERED 0x71 // Deferred Errors
  210702. //***************************************************************************
  210703. // %%% REQUEST SENSE BIT DEFINITIONS %%%
  210704. //***************************************************************************
  210705. #define SENSE_VALID 0x80 // Byte 0 Bit 7
  210706. #define SENSE_FILEMRK 0x80 // Byte 2 Bit 7
  210707. #define SENSE_EOM 0x40 // Byte 2 Bit 6
  210708. #define SENSE_ILI 0x20 // Byte 2 Bit 5
  210709. //***************************************************************************
  210710. // %%% REQUEST SENSE SENSE KEY DEFINITIONS %%%
  210711. //***************************************************************************
  210712. #define KEY_NOSENSE 0x00 // No Sense
  210713. #define KEY_RECERROR 0x01 // Recovered Error
  210714. #define KEY_NOTREADY 0x02 // Not Ready
  210715. #define KEY_MEDIUMERR 0x03 // Medium Error
  210716. #define KEY_HARDERROR 0x04 // Hardware Error
  210717. #define KEY_ILLGLREQ 0x05 // Illegal Request
  210718. #define KEY_UNITATT 0x06 // Unit Attention
  210719. #define KEY_DATAPROT 0x07 // Data Protect
  210720. #define KEY_BLANKCHK 0x08 // Blank Check
  210721. #define KEY_VENDSPEC 0x09 // Vendor Specific
  210722. #define KEY_COPYABORT 0x0A // Copy Abort
  210723. #define KEY_EQUAL 0x0C // Equal (Search)
  210724. #define KEY_VOLOVRFLW 0x0D // Volume Overflow
  210725. #define KEY_MISCOMP 0x0E // Miscompare (Search)
  210726. #define KEY_RESERVED 0x0F // Reserved
  210727. //***************************************************************************
  210728. // %%% PERIPHERAL DEVICE TYPE DEFINITIONS %%%
  210729. //***************************************************************************
  210730. #define DTYPE_DASD 0x00 // Disk Device
  210731. #define DTYPE_SEQD 0x01 // Tape Device
  210732. #define DTYPE_PRNT 0x02 // Printer
  210733. #define DTYPE_PROC 0x03 // Processor
  210734. #define DTYPE_WORM 0x04 // Write-once read-multiple
  210735. #define DTYPE_CROM 0x05 // CD-ROM device
  210736. #define DTYPE_SCAN 0x06 // Scanner device
  210737. #define DTYPE_OPTI 0x07 // Optical memory device
  210738. #define DTYPE_JUKE 0x08 // Medium Changer device
  210739. #define DTYPE_COMM 0x09 // Communications device
  210740. #define DTYPE_RESL 0x0A // Reserved (low)
  210741. #define DTYPE_RESH 0x1E // Reserved (high)
  210742. #define DTYPE_UNKNOWN 0x1F // Unknown or no device type
  210743. //***************************************************************************
  210744. // %%% ANSI APPROVED VERSION DEFINITIONS %%%
  210745. //***************************************************************************
  210746. #define ANSI_MAYBE 0x0 // Device may or may not be ANSI approved stand
  210747. #define ANSI_SCSI1 0x1 // Device complies to ANSI X3.131-1986 (SCSI-1)
  210748. #define ANSI_SCSI2 0x2 // Device complies to SCSI-2
  210749. #define ANSI_RESLO 0x3 // Reserved (low)
  210750. #define ANSI_RESHI 0x7 // Reserved (high)
  210751. typedef struct
  210752. {
  210753. USHORT Length;
  210754. UCHAR ScsiStatus;
  210755. UCHAR PathId;
  210756. UCHAR TargetId;
  210757. UCHAR Lun;
  210758. UCHAR CdbLength;
  210759. UCHAR SenseInfoLength;
  210760. UCHAR DataIn;
  210761. ULONG DataTransferLength;
  210762. ULONG TimeOutValue;
  210763. ULONG DataBufferOffset;
  210764. ULONG SenseInfoOffset;
  210765. UCHAR Cdb[16];
  210766. } SCSI_PASS_THROUGH, *PSCSI_PASS_THROUGH;
  210767. typedef struct
  210768. {
  210769. USHORT Length;
  210770. UCHAR ScsiStatus;
  210771. UCHAR PathId;
  210772. UCHAR TargetId;
  210773. UCHAR Lun;
  210774. UCHAR CdbLength;
  210775. UCHAR SenseInfoLength;
  210776. UCHAR DataIn;
  210777. ULONG DataTransferLength;
  210778. ULONG TimeOutValue;
  210779. PVOID DataBuffer;
  210780. ULONG SenseInfoOffset;
  210781. UCHAR Cdb[16];
  210782. } SCSI_PASS_THROUGH_DIRECT, *PSCSI_PASS_THROUGH_DIRECT;
  210783. typedef struct
  210784. {
  210785. SCSI_PASS_THROUGH_DIRECT spt;
  210786. ULONG Filler;
  210787. UCHAR ucSenseBuf[32];
  210788. } SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, *PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER;
  210789. typedef struct
  210790. {
  210791. ULONG Length;
  210792. UCHAR PortNumber;
  210793. UCHAR PathId;
  210794. UCHAR TargetId;
  210795. UCHAR Lun;
  210796. } SCSI_ADDRESS, *PSCSI_ADDRESS;
  210797. #define METHOD_BUFFERED 0
  210798. #define METHOD_IN_DIRECT 1
  210799. #define METHOD_OUT_DIRECT 2
  210800. #define METHOD_NEITHER 3
  210801. #define FILE_ANY_ACCESS 0
  210802. #ifndef FILE_READ_ACCESS
  210803. #define FILE_READ_ACCESS (0x0001)
  210804. #endif
  210805. #ifndef FILE_WRITE_ACCESS
  210806. #define FILE_WRITE_ACCESS (0x0002)
  210807. #endif
  210808. #define IOCTL_SCSI_BASE 0x00000004
  210809. #define SCSI_IOCTL_DATA_OUT 0
  210810. #define SCSI_IOCTL_DATA_IN 1
  210811. #define SCSI_IOCTL_DATA_UNSPECIFIED 2
  210812. #define CTL_CODE2( DevType, Function, Method, Access ) ( \
  210813. ((DevType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method) \
  210814. )
  210815. #define IOCTL_SCSI_PASS_THROUGH CTL_CODE2( IOCTL_SCSI_BASE, 0x0401, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  210816. #define IOCTL_SCSI_GET_CAPABILITIES CTL_CODE2( IOCTL_SCSI_BASE, 0x0404, METHOD_BUFFERED, FILE_ANY_ACCESS)
  210817. #define IOCTL_SCSI_PASS_THROUGH_DIRECT CTL_CODE2( IOCTL_SCSI_BASE, 0x0405, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  210818. #define IOCTL_SCSI_GET_ADDRESS CTL_CODE2( IOCTL_SCSI_BASE, 0x0406, METHOD_BUFFERED, FILE_ANY_ACCESS )
  210819. #define SENSE_LEN 14
  210820. #define SRB_DIR_SCSI 0x00
  210821. #define SRB_POSTING 0x01
  210822. #define SRB_ENABLE_RESIDUAL_COUNT 0x04
  210823. #define SRB_DIR_IN 0x08
  210824. #define SRB_DIR_OUT 0x10
  210825. #define SRB_EVENT_NOTIFY 0x40
  210826. #define RESIDUAL_COUNT_SUPPORTED 0x02
  210827. #define MAX_SRB_TIMEOUT 1080001u
  210828. #define DEFAULT_SRB_TIMEOUT 1080001u
  210829. #define SC_HA_INQUIRY 0x00
  210830. #define SC_GET_DEV_TYPE 0x01
  210831. #define SC_EXEC_SCSI_CMD 0x02
  210832. #define SC_ABORT_SRB 0x03
  210833. #define SC_RESET_DEV 0x04
  210834. #define SC_SET_HA_PARMS 0x05
  210835. #define SC_GET_DISK_INFO 0x06
  210836. #define SC_RESCAN_SCSI_BUS 0x07
  210837. #define SC_GETSET_TIMEOUTS 0x08
  210838. #define SS_PENDING 0x00
  210839. #define SS_COMP 0x01
  210840. #define SS_ABORTED 0x02
  210841. #define SS_ABORT_FAIL 0x03
  210842. #define SS_ERR 0x04
  210843. #define SS_INVALID_CMD 0x80
  210844. #define SS_INVALID_HA 0x81
  210845. #define SS_NO_DEVICE 0x82
  210846. #define SS_INVALID_SRB 0xE0
  210847. #define SS_OLD_MANAGER 0xE1
  210848. #define SS_BUFFER_ALIGN 0xE1
  210849. #define SS_ILLEGAL_MODE 0xE2
  210850. #define SS_NO_ASPI 0xE3
  210851. #define SS_FAILED_INIT 0xE4
  210852. #define SS_ASPI_IS_BUSY 0xE5
  210853. #define SS_BUFFER_TO_BIG 0xE6
  210854. #define SS_BUFFER_TOO_BIG 0xE6
  210855. #define SS_MISMATCHED_COMPONENTS 0xE7
  210856. #define SS_NO_ADAPTERS 0xE8
  210857. #define SS_INSUFFICIENT_RESOURCES 0xE9
  210858. #define SS_ASPI_IS_SHUTDOWN 0xEA
  210859. #define SS_BAD_INSTALL 0xEB
  210860. #define HASTAT_OK 0x00
  210861. #define HASTAT_SEL_TO 0x11
  210862. #define HASTAT_DO_DU 0x12
  210863. #define HASTAT_BUS_FREE 0x13
  210864. #define HASTAT_PHASE_ERR 0x14
  210865. #define HASTAT_TIMEOUT 0x09
  210866. #define HASTAT_COMMAND_TIMEOUT 0x0B
  210867. #define HASTAT_MESSAGE_REJECT 0x0D
  210868. #define HASTAT_BUS_RESET 0x0E
  210869. #define HASTAT_PARITY_ERROR 0x0F
  210870. #define HASTAT_REQUEST_SENSE_FAILED 0x10
  210871. #define PACKED
  210872. #pragma pack(1)
  210873. typedef struct
  210874. {
  210875. BYTE SRB_Cmd;
  210876. BYTE SRB_Status;
  210877. BYTE SRB_HaID;
  210878. BYTE SRB_Flags;
  210879. DWORD SRB_Hdr_Rsvd;
  210880. BYTE HA_Count;
  210881. BYTE HA_SCSI_ID;
  210882. BYTE HA_ManagerId[16];
  210883. BYTE HA_Identifier[16];
  210884. BYTE HA_Unique[16];
  210885. WORD HA_Rsvd1;
  210886. BYTE pad[20];
  210887. } PACKED SRB_HAInquiry, *PSRB_HAInquiry, FAR *LPSRB_HAInquiry;
  210888. typedef struct
  210889. {
  210890. BYTE SRB_Cmd;
  210891. BYTE SRB_Status;
  210892. BYTE SRB_HaID;
  210893. BYTE SRB_Flags;
  210894. DWORD SRB_Hdr_Rsvd;
  210895. BYTE SRB_Target;
  210896. BYTE SRB_Lun;
  210897. BYTE SRB_DeviceType;
  210898. BYTE SRB_Rsvd1;
  210899. BYTE pad[68];
  210900. } PACKED SRB_GDEVBlock, *PSRB_GDEVBlock, FAR *LPSRB_GDEVBlock;
  210901. typedef struct
  210902. {
  210903. BYTE SRB_Cmd;
  210904. BYTE SRB_Status;
  210905. BYTE SRB_HaID;
  210906. BYTE SRB_Flags;
  210907. DWORD SRB_Hdr_Rsvd;
  210908. BYTE SRB_Target;
  210909. BYTE SRB_Lun;
  210910. WORD SRB_Rsvd1;
  210911. DWORD SRB_BufLen;
  210912. BYTE FAR *SRB_BufPointer;
  210913. BYTE SRB_SenseLen;
  210914. BYTE SRB_CDBLen;
  210915. BYTE SRB_HaStat;
  210916. BYTE SRB_TargStat;
  210917. VOID FAR *SRB_PostProc;
  210918. BYTE SRB_Rsvd2[20];
  210919. BYTE CDBByte[16];
  210920. BYTE SenseArea[SENSE_LEN+2];
  210921. } PACKED SRB_ExecSCSICmd, *PSRB_ExecSCSICmd, FAR *LPSRB_ExecSCSICmd;
  210922. typedef struct
  210923. {
  210924. BYTE SRB_Cmd;
  210925. BYTE SRB_Status;
  210926. BYTE SRB_HaId;
  210927. BYTE SRB_Flags;
  210928. DWORD SRB_Hdr_Rsvd;
  210929. } PACKED SRB, *PSRB, FAR *LPSRB;
  210930. #pragma pack()
  210931. struct CDDeviceInfo
  210932. {
  210933. char vendor[9];
  210934. char productId[17];
  210935. char rev[5];
  210936. char vendorSpec[21];
  210937. BYTE ha;
  210938. BYTE tgt;
  210939. BYTE lun;
  210940. char scsiDriveLetter; // will be 0 if not using scsi
  210941. };
  210942. class CDReadBuffer
  210943. {
  210944. public:
  210945. int startFrame;
  210946. int numFrames;
  210947. int dataStartOffset;
  210948. int dataLength;
  210949. int bufferSize;
  210950. HeapBlock<BYTE> buffer;
  210951. int index;
  210952. bool wantsIndex;
  210953. CDReadBuffer (const int numberOfFrames)
  210954. : startFrame (0),
  210955. numFrames (0),
  210956. dataStartOffset (0),
  210957. dataLength (0),
  210958. bufferSize (2352 * numberOfFrames),
  210959. buffer (bufferSize),
  210960. index (0),
  210961. wantsIndex (false)
  210962. {
  210963. }
  210964. bool isZero() const throw()
  210965. {
  210966. BYTE* p = buffer + dataStartOffset;
  210967. for (int i = dataLength; --i >= 0;)
  210968. if (*p++ != 0)
  210969. return false;
  210970. return true;
  210971. }
  210972. };
  210973. class CDDeviceHandle;
  210974. class CDController
  210975. {
  210976. public:
  210977. CDController();
  210978. virtual ~CDController();
  210979. virtual bool read (CDReadBuffer* t) = 0;
  210980. virtual void shutDown();
  210981. bool readAudio (CDReadBuffer* t, CDReadBuffer* overlapBuffer = 0);
  210982. int getLastIndex();
  210983. public:
  210984. bool initialised;
  210985. CDDeviceHandle* deviceInfo;
  210986. int framesToCheck, framesOverlap;
  210987. void prepare (SRB_ExecSCSICmd& s);
  210988. void perform (SRB_ExecSCSICmd& s);
  210989. void setPaused (bool paused);
  210990. };
  210991. #pragma pack(1)
  210992. struct TOCTRACK
  210993. {
  210994. BYTE rsvd;
  210995. BYTE ADR;
  210996. BYTE trackNumber;
  210997. BYTE rsvd2;
  210998. BYTE addr[4];
  210999. };
  211000. struct TOC
  211001. {
  211002. WORD tocLen;
  211003. BYTE firstTrack;
  211004. BYTE lastTrack;
  211005. TOCTRACK tracks[100];
  211006. };
  211007. #pragma pack()
  211008. enum
  211009. {
  211010. READTYPE_ANY = 0,
  211011. READTYPE_ATAPI1 = 1,
  211012. READTYPE_ATAPI2 = 2,
  211013. READTYPE_READ6 = 3,
  211014. READTYPE_READ10 = 4,
  211015. READTYPE_READ_D8 = 5,
  211016. READTYPE_READ_D4 = 6,
  211017. READTYPE_READ_D4_1 = 7,
  211018. READTYPE_READ10_2 = 8
  211019. };
  211020. class CDDeviceHandle
  211021. {
  211022. public:
  211023. CDDeviceHandle (const CDDeviceInfo* const device)
  211024. : scsiHandle (0),
  211025. readType (READTYPE_ANY),
  211026. controller (0)
  211027. {
  211028. memcpy (&info, device, sizeof (info));
  211029. }
  211030. ~CDDeviceHandle()
  211031. {
  211032. if (controller != 0)
  211033. {
  211034. controller->shutDown();
  211035. controller = 0;
  211036. }
  211037. if (scsiHandle != 0)
  211038. CloseHandle (scsiHandle);
  211039. }
  211040. bool readTOC (TOC* lpToc);
  211041. bool readAudio (CDReadBuffer* buffer, CDReadBuffer* overlapBuffer = 0);
  211042. void openDrawer (bool shouldBeOpen);
  211043. CDDeviceInfo info;
  211044. HANDLE scsiHandle;
  211045. BYTE readType;
  211046. private:
  211047. ScopedPointer<CDController> controller;
  211048. bool testController (const int readType,
  211049. CDController* const newController,
  211050. CDReadBuffer* const bufferToUse);
  211051. };
  211052. DWORD (*fGetASPI32SupportInfo)(void);
  211053. DWORD (*fSendASPI32Command)(LPSRB);
  211054. static HINSTANCE winAspiLib = 0;
  211055. static bool usingScsi = false;
  211056. static bool initialised = false;
  211057. bool InitialiseCDRipper()
  211058. {
  211059. if (! initialised)
  211060. {
  211061. initialised = true;
  211062. OSVERSIONINFO info;
  211063. info.dwOSVersionInfoSize = sizeof (info);
  211064. GetVersionEx (&info);
  211065. usingScsi = (info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4);
  211066. if (! usingScsi)
  211067. {
  211068. fGetASPI32SupportInfo = 0;
  211069. fSendASPI32Command = 0;
  211070. winAspiLib = LoadLibrary (_T("WNASPI32.DLL"));
  211071. if (winAspiLib != 0)
  211072. {
  211073. fGetASPI32SupportInfo = (DWORD(*)(void)) GetProcAddress (winAspiLib, "GetASPI32SupportInfo");
  211074. fSendASPI32Command = (DWORD(*)(LPSRB)) GetProcAddress (winAspiLib, "SendASPI32Command");
  211075. if (fGetASPI32SupportInfo == 0 || fSendASPI32Command == 0)
  211076. return false;
  211077. }
  211078. else
  211079. {
  211080. usingScsi = true;
  211081. }
  211082. }
  211083. }
  211084. return true;
  211085. }
  211086. void DeinitialiseCDRipper()
  211087. {
  211088. if (winAspiLib != 0)
  211089. {
  211090. fGetASPI32SupportInfo = 0;
  211091. fSendASPI32Command = 0;
  211092. FreeLibrary (winAspiLib);
  211093. winAspiLib = 0;
  211094. }
  211095. initialised = false;
  211096. }
  211097. HANDLE CreateSCSIDeviceHandle (char driveLetter)
  211098. {
  211099. TCHAR devicePath[] = { '\\', '\\', '.', '\\', driveLetter, ':', 0, 0 };
  211100. OSVERSIONINFO info;
  211101. info.dwOSVersionInfoSize = sizeof (info);
  211102. GetVersionEx (&info);
  211103. DWORD flags = GENERIC_READ;
  211104. if ((info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4))
  211105. flags = GENERIC_READ | GENERIC_WRITE;
  211106. HANDLE h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  211107. if (h == INVALID_HANDLE_VALUE)
  211108. {
  211109. flags ^= GENERIC_WRITE;
  211110. h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  211111. }
  211112. return h;
  211113. }
  211114. DWORD performScsiPassThroughCommand (const LPSRB_ExecSCSICmd srb, const char driveLetter,
  211115. HANDLE& deviceHandle, const bool retryOnFailure = true)
  211116. {
  211117. SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER s;
  211118. zerostruct (s);
  211119. s.spt.Length = sizeof (SCSI_PASS_THROUGH);
  211120. s.spt.CdbLength = srb->SRB_CDBLen;
  211121. s.spt.DataIn = (BYTE) ((srb->SRB_Flags & SRB_DIR_IN)
  211122. ? SCSI_IOCTL_DATA_IN
  211123. : ((srb->SRB_Flags & SRB_DIR_OUT)
  211124. ? SCSI_IOCTL_DATA_OUT
  211125. : SCSI_IOCTL_DATA_UNSPECIFIED));
  211126. s.spt.DataTransferLength = srb->SRB_BufLen;
  211127. s.spt.TimeOutValue = 5;
  211128. s.spt.DataBuffer = srb->SRB_BufPointer;
  211129. s.spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  211130. memcpy (s.spt.Cdb, srb->CDBByte, srb->SRB_CDBLen);
  211131. srb->SRB_Status = SS_ERR;
  211132. srb->SRB_TargStat = 0x0004;
  211133. DWORD bytesReturned = 0;
  211134. if (DeviceIoControl (deviceHandle, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  211135. &s, sizeof (s),
  211136. &s, sizeof (s),
  211137. &bytesReturned, 0) != 0)
  211138. {
  211139. srb->SRB_Status = SS_COMP;
  211140. }
  211141. else if (retryOnFailure)
  211142. {
  211143. const DWORD error = GetLastError();
  211144. if ((error == ERROR_MEDIA_CHANGED) || (error == ERROR_INVALID_HANDLE))
  211145. {
  211146. if (error != ERROR_INVALID_HANDLE)
  211147. CloseHandle (deviceHandle);
  211148. deviceHandle = CreateSCSIDeviceHandle (driveLetter);
  211149. return performScsiPassThroughCommand (srb, driveLetter, deviceHandle, false);
  211150. }
  211151. }
  211152. return srb->SRB_Status;
  211153. }
  211154. // Controller types..
  211155. class ControllerType1 : public CDController
  211156. {
  211157. public:
  211158. ControllerType1() {}
  211159. ~ControllerType1() {}
  211160. bool read (CDReadBuffer* rb)
  211161. {
  211162. if (rb->numFrames * 2352 > rb->bufferSize)
  211163. return false;
  211164. SRB_ExecSCSICmd s;
  211165. prepare (s);
  211166. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211167. s.SRB_BufLen = rb->bufferSize;
  211168. s.SRB_BufPointer = rb->buffer;
  211169. s.SRB_CDBLen = 12;
  211170. s.CDBByte[0] = 0xBE;
  211171. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  211172. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  211173. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  211174. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  211175. s.CDBByte[9] = (BYTE)((deviceInfo->readType == READTYPE_ATAPI1) ? 0x10 : 0xF0);
  211176. perform (s);
  211177. if (s.SRB_Status != SS_COMP)
  211178. return false;
  211179. rb->dataLength = rb->numFrames * 2352;
  211180. rb->dataStartOffset = 0;
  211181. return true;
  211182. }
  211183. };
  211184. class ControllerType2 : public CDController
  211185. {
  211186. public:
  211187. ControllerType2() {}
  211188. ~ControllerType2() {}
  211189. void shutDown()
  211190. {
  211191. if (initialised)
  211192. {
  211193. BYTE bufPointer[] = { 0, 0, 0, 8, 83, 0, 0, 0, 0, 0, 8, 0 };
  211194. SRB_ExecSCSICmd s;
  211195. prepare (s);
  211196. s.SRB_Flags = SRB_EVENT_NOTIFY | SRB_ENABLE_RESIDUAL_COUNT;
  211197. s.SRB_BufLen = 0x0C;
  211198. s.SRB_BufPointer = bufPointer;
  211199. s.SRB_CDBLen = 6;
  211200. s.CDBByte[0] = 0x15;
  211201. s.CDBByte[4] = 0x0C;
  211202. perform (s);
  211203. }
  211204. }
  211205. bool init()
  211206. {
  211207. SRB_ExecSCSICmd s;
  211208. s.SRB_Status = SS_ERR;
  211209. if (deviceInfo->readType == READTYPE_READ10_2)
  211210. {
  211211. BYTE bufPointer1[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 35, 6, 0, 0, 0, 0, 0, 128 };
  211212. BYTE bufPointer2[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 1, 6, 32, 7, 0, 0, 0, 0 };
  211213. for (int i = 0; i < 2; ++i)
  211214. {
  211215. prepare (s);
  211216. s.SRB_Flags = SRB_EVENT_NOTIFY;
  211217. s.SRB_BufLen = 0x14;
  211218. s.SRB_BufPointer = (i == 0) ? bufPointer1 : bufPointer2;
  211219. s.SRB_CDBLen = 6;
  211220. s.CDBByte[0] = 0x15;
  211221. s.CDBByte[1] = 0x10;
  211222. s.CDBByte[4] = 0x14;
  211223. perform (s);
  211224. if (s.SRB_Status != SS_COMP)
  211225. return false;
  211226. }
  211227. }
  211228. else
  211229. {
  211230. BYTE bufPointer[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48 };
  211231. prepare (s);
  211232. s.SRB_Flags = SRB_EVENT_NOTIFY;
  211233. s.SRB_BufLen = 0x0C;
  211234. s.SRB_BufPointer = bufPointer;
  211235. s.SRB_CDBLen = 6;
  211236. s.CDBByte[0] = 0x15;
  211237. s.CDBByte[4] = 0x0C;
  211238. perform (s);
  211239. }
  211240. return s.SRB_Status == SS_COMP;
  211241. }
  211242. bool read (CDReadBuffer* rb)
  211243. {
  211244. if (rb->numFrames * 2352 > rb->bufferSize)
  211245. return false;
  211246. if (!initialised)
  211247. {
  211248. initialised = init();
  211249. if (!initialised)
  211250. return false;
  211251. }
  211252. SRB_ExecSCSICmd s;
  211253. prepare (s);
  211254. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211255. s.SRB_BufLen = rb->bufferSize;
  211256. s.SRB_BufPointer = rb->buffer;
  211257. s.SRB_CDBLen = 10;
  211258. s.CDBByte[0] = 0x28;
  211259. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  211260. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  211261. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  211262. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  211263. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  211264. perform (s);
  211265. if (s.SRB_Status != SS_COMP)
  211266. return false;
  211267. rb->dataLength = rb->numFrames * 2352;
  211268. rb->dataStartOffset = 0;
  211269. return true;
  211270. }
  211271. };
  211272. class ControllerType3 : public CDController
  211273. {
  211274. public:
  211275. ControllerType3() {}
  211276. ~ControllerType3() {}
  211277. bool read (CDReadBuffer* rb)
  211278. {
  211279. if (rb->numFrames * 2352 > rb->bufferSize)
  211280. return false;
  211281. if (!initialised)
  211282. {
  211283. setPaused (false);
  211284. initialised = true;
  211285. }
  211286. SRB_ExecSCSICmd s;
  211287. prepare (s);
  211288. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211289. s.SRB_BufLen = rb->numFrames * 2352;
  211290. s.SRB_BufPointer = rb->buffer;
  211291. s.SRB_CDBLen = 12;
  211292. s.CDBByte[0] = 0xD8;
  211293. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  211294. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  211295. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  211296. s.CDBByte[9] = (BYTE)(rb->numFrames & 0xFF);
  211297. perform (s);
  211298. if (s.SRB_Status != SS_COMP)
  211299. return false;
  211300. rb->dataLength = rb->numFrames * 2352;
  211301. rb->dataStartOffset = 0;
  211302. return true;
  211303. }
  211304. };
  211305. class ControllerType4 : public CDController
  211306. {
  211307. public:
  211308. ControllerType4() {}
  211309. ~ControllerType4() {}
  211310. bool selectD4Mode()
  211311. {
  211312. BYTE bufPointer[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 48 };
  211313. SRB_ExecSCSICmd s;
  211314. prepare (s);
  211315. s.SRB_Flags = SRB_EVENT_NOTIFY;
  211316. s.SRB_CDBLen = 6;
  211317. s.SRB_BufLen = 12;
  211318. s.SRB_BufPointer = bufPointer;
  211319. s.CDBByte[0] = 0x15;
  211320. s.CDBByte[1] = 0x10;
  211321. s.CDBByte[4] = 0x08;
  211322. perform (s);
  211323. return s.SRB_Status == SS_COMP;
  211324. }
  211325. bool read (CDReadBuffer* rb)
  211326. {
  211327. if (rb->numFrames * 2352 > rb->bufferSize)
  211328. return false;
  211329. if (!initialised)
  211330. {
  211331. setPaused (true);
  211332. if (deviceInfo->readType == READTYPE_READ_D4_1)
  211333. selectD4Mode();
  211334. initialised = true;
  211335. }
  211336. SRB_ExecSCSICmd s;
  211337. prepare (s);
  211338. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211339. s.SRB_BufLen = rb->bufferSize;
  211340. s.SRB_BufPointer = rb->buffer;
  211341. s.SRB_CDBLen = 10;
  211342. s.CDBByte[0] = 0xD4;
  211343. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  211344. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  211345. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  211346. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  211347. perform (s);
  211348. if (s.SRB_Status != SS_COMP)
  211349. return false;
  211350. rb->dataLength = rb->numFrames * 2352;
  211351. rb->dataStartOffset = 0;
  211352. return true;
  211353. }
  211354. };
  211355. CDController::CDController() : initialised (false)
  211356. {
  211357. }
  211358. CDController::~CDController()
  211359. {
  211360. }
  211361. void CDController::prepare (SRB_ExecSCSICmd& s)
  211362. {
  211363. zerostruct (s);
  211364. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  211365. s.SRB_HaID = deviceInfo->info.ha;
  211366. s.SRB_Target = deviceInfo->info.tgt;
  211367. s.SRB_Lun = deviceInfo->info.lun;
  211368. s.SRB_SenseLen = SENSE_LEN;
  211369. }
  211370. void CDController::perform (SRB_ExecSCSICmd& s)
  211371. {
  211372. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  211373. s.SRB_PostProc = event;
  211374. ResetEvent (event);
  211375. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s,
  211376. deviceInfo->info.scsiDriveLetter,
  211377. deviceInfo->scsiHandle)
  211378. : fSendASPI32Command ((LPSRB)&s);
  211379. if (status == SS_PENDING)
  211380. WaitForSingleObject (event, 4000);
  211381. CloseHandle (event);
  211382. }
  211383. void CDController::setPaused (bool paused)
  211384. {
  211385. SRB_ExecSCSICmd s;
  211386. prepare (s);
  211387. s.SRB_Flags = SRB_EVENT_NOTIFY;
  211388. s.SRB_CDBLen = 10;
  211389. s.CDBByte[0] = 0x4B;
  211390. s.CDBByte[8] = (BYTE) (paused ? 0 : 1);
  211391. perform (s);
  211392. }
  211393. void CDController::shutDown()
  211394. {
  211395. }
  211396. bool CDController::readAudio (CDReadBuffer* rb, CDReadBuffer* overlapBuffer)
  211397. {
  211398. if (overlapBuffer != 0)
  211399. {
  211400. const bool canDoJitter = (overlapBuffer->bufferSize >= 2352 * framesToCheck);
  211401. const bool doJitter = canDoJitter && ! overlapBuffer->isZero();
  211402. if (doJitter
  211403. && overlapBuffer->startFrame > 0
  211404. && overlapBuffer->numFrames > 0
  211405. && overlapBuffer->dataLength > 0)
  211406. {
  211407. const int numFrames = rb->numFrames;
  211408. if (overlapBuffer->startFrame == (rb->startFrame - framesToCheck))
  211409. {
  211410. rb->startFrame -= framesOverlap;
  211411. if (framesToCheck < framesOverlap
  211412. && numFrames + framesOverlap <= rb->bufferSize / 2352)
  211413. rb->numFrames += framesOverlap;
  211414. }
  211415. else
  211416. {
  211417. overlapBuffer->dataLength = 0;
  211418. overlapBuffer->startFrame = 0;
  211419. overlapBuffer->numFrames = 0;
  211420. }
  211421. }
  211422. if (! read (rb))
  211423. return false;
  211424. if (doJitter)
  211425. {
  211426. const int checkLen = framesToCheck * 2352;
  211427. const int maxToCheck = rb->dataLength - checkLen;
  211428. if (overlapBuffer->dataLength == 0 || overlapBuffer->isZero())
  211429. return true;
  211430. BYTE* const p = overlapBuffer->buffer + overlapBuffer->dataStartOffset;
  211431. bool found = false;
  211432. for (int i = 0; i < maxToCheck; ++i)
  211433. {
  211434. if (memcmp (p, rb->buffer + i, checkLen) == 0)
  211435. {
  211436. i += checkLen;
  211437. rb->dataStartOffset = i;
  211438. rb->dataLength -= i;
  211439. rb->startFrame = overlapBuffer->startFrame + framesToCheck;
  211440. found = true;
  211441. break;
  211442. }
  211443. }
  211444. rb->numFrames = rb->dataLength / 2352;
  211445. rb->dataLength = 2352 * rb->numFrames;
  211446. if (!found)
  211447. return false;
  211448. }
  211449. if (canDoJitter)
  211450. {
  211451. memcpy (overlapBuffer->buffer,
  211452. rb->buffer + rb->dataStartOffset + 2352 * (rb->numFrames - framesToCheck),
  211453. 2352 * framesToCheck);
  211454. overlapBuffer->startFrame = rb->startFrame + rb->numFrames - framesToCheck;
  211455. overlapBuffer->numFrames = framesToCheck;
  211456. overlapBuffer->dataLength = 2352 * framesToCheck;
  211457. overlapBuffer->dataStartOffset = 0;
  211458. }
  211459. else
  211460. {
  211461. overlapBuffer->startFrame = 0;
  211462. overlapBuffer->numFrames = 0;
  211463. overlapBuffer->dataLength = 0;
  211464. }
  211465. return true;
  211466. }
  211467. else
  211468. {
  211469. return read (rb);
  211470. }
  211471. }
  211472. int CDController::getLastIndex()
  211473. {
  211474. char qdata[100];
  211475. SRB_ExecSCSICmd s;
  211476. prepare (s);
  211477. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211478. s.SRB_BufLen = sizeof (qdata);
  211479. s.SRB_BufPointer = (BYTE*)qdata;
  211480. s.SRB_CDBLen = 12;
  211481. s.CDBByte[0] = 0x42;
  211482. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  211483. s.CDBByte[2] = 64;
  211484. s.CDBByte[3] = 1; // get current position
  211485. s.CDBByte[7] = 0;
  211486. s.CDBByte[8] = (BYTE)sizeof (qdata);
  211487. perform (s);
  211488. if (s.SRB_Status == SS_COMP)
  211489. return qdata[7];
  211490. return 0;
  211491. }
  211492. bool CDDeviceHandle::readTOC (TOC* lpToc)
  211493. {
  211494. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  211495. SRB_ExecSCSICmd s;
  211496. zerostruct (s);
  211497. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  211498. s.SRB_HaID = info.ha;
  211499. s.SRB_Target = info.tgt;
  211500. s.SRB_Lun = info.lun;
  211501. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211502. s.SRB_BufLen = 0x324;
  211503. s.SRB_BufPointer = (BYTE*)lpToc;
  211504. s.SRB_SenseLen = 0x0E;
  211505. s.SRB_CDBLen = 0x0A;
  211506. s.SRB_PostProc = event;
  211507. s.CDBByte[0] = 0x43;
  211508. s.CDBByte[1] = 0x00;
  211509. s.CDBByte[7] = 0x03;
  211510. s.CDBByte[8] = 0x24;
  211511. ResetEvent (event);
  211512. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  211513. : fSendASPI32Command ((LPSRB)&s);
  211514. if (status == SS_PENDING)
  211515. WaitForSingleObject (event, 4000);
  211516. CloseHandle (event);
  211517. return (s.SRB_Status == SS_COMP);
  211518. }
  211519. bool CDDeviceHandle::readAudio (CDReadBuffer* const buffer,
  211520. CDReadBuffer* const overlapBuffer)
  211521. {
  211522. if (controller == 0)
  211523. {
  211524. testController (READTYPE_ATAPI2, new ControllerType1(), buffer)
  211525. || testController (READTYPE_ATAPI1, new ControllerType1(), buffer)
  211526. || testController (READTYPE_READ10_2, new ControllerType2(), buffer)
  211527. || testController (READTYPE_READ10, new ControllerType2(), buffer)
  211528. || testController (READTYPE_READ_D8, new ControllerType3(), buffer)
  211529. || testController (READTYPE_READ_D4, new ControllerType4(), buffer)
  211530. || testController (READTYPE_READ_D4_1, new ControllerType4(), buffer);
  211531. }
  211532. buffer->index = 0;
  211533. if ((controller != 0)
  211534. && controller->readAudio (buffer, overlapBuffer))
  211535. {
  211536. if (buffer->wantsIndex)
  211537. buffer->index = controller->getLastIndex();
  211538. return true;
  211539. }
  211540. return false;
  211541. }
  211542. void CDDeviceHandle::openDrawer (bool shouldBeOpen)
  211543. {
  211544. if (shouldBeOpen)
  211545. {
  211546. if (controller != 0)
  211547. {
  211548. controller->shutDown();
  211549. controller = 0;
  211550. }
  211551. if (scsiHandle != 0)
  211552. {
  211553. CloseHandle (scsiHandle);
  211554. scsiHandle = 0;
  211555. }
  211556. }
  211557. SRB_ExecSCSICmd s;
  211558. zerostruct (s);
  211559. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  211560. s.SRB_HaID = info.ha;
  211561. s.SRB_Target = info.tgt;
  211562. s.SRB_Lun = info.lun;
  211563. s.SRB_SenseLen = SENSE_LEN;
  211564. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211565. s.SRB_BufLen = 0;
  211566. s.SRB_BufPointer = 0;
  211567. s.SRB_CDBLen = 12;
  211568. s.CDBByte[0] = 0x1b;
  211569. s.CDBByte[1] = (BYTE)(info.lun << 5);
  211570. s.CDBByte[4] = (BYTE)((shouldBeOpen) ? 2 : 3);
  211571. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  211572. s.SRB_PostProc = event;
  211573. ResetEvent (event);
  211574. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  211575. : fSendASPI32Command ((LPSRB)&s);
  211576. if (status == SS_PENDING)
  211577. WaitForSingleObject (event, 4000);
  211578. CloseHandle (event);
  211579. }
  211580. bool CDDeviceHandle::testController (const int type,
  211581. CDController* const newController,
  211582. CDReadBuffer* const rb)
  211583. {
  211584. controller = newController;
  211585. readType = (BYTE)type;
  211586. controller->deviceInfo = this;
  211587. controller->framesToCheck = 1;
  211588. controller->framesOverlap = 3;
  211589. bool passed = false;
  211590. memset (rb->buffer, 0xcd, rb->bufferSize);
  211591. if (controller->read (rb))
  211592. {
  211593. passed = true;
  211594. int* p = (int*) (rb->buffer + rb->dataStartOffset);
  211595. int wrong = 0;
  211596. for (int i = rb->dataLength / 4; --i >= 0;)
  211597. {
  211598. if (*p++ == (int) 0xcdcdcdcd)
  211599. {
  211600. if (++wrong == 4)
  211601. {
  211602. passed = false;
  211603. break;
  211604. }
  211605. }
  211606. else
  211607. {
  211608. wrong = 0;
  211609. }
  211610. }
  211611. }
  211612. if (! passed)
  211613. {
  211614. controller->shutDown();
  211615. controller = 0;
  211616. }
  211617. return passed;
  211618. }
  211619. void GetAspiDeviceInfo (CDDeviceInfo* dev, BYTE ha, BYTE tgt, BYTE lun)
  211620. {
  211621. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  211622. const int bufSize = 128;
  211623. BYTE buffer[bufSize];
  211624. zeromem (buffer, bufSize);
  211625. SRB_ExecSCSICmd s;
  211626. zerostruct (s);
  211627. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  211628. s.SRB_HaID = ha;
  211629. s.SRB_Target = tgt;
  211630. s.SRB_Lun = lun;
  211631. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211632. s.SRB_BufLen = bufSize;
  211633. s.SRB_BufPointer = buffer;
  211634. s.SRB_SenseLen = SENSE_LEN;
  211635. s.SRB_CDBLen = 6;
  211636. s.SRB_PostProc = event;
  211637. s.CDBByte[0] = SCSI_INQUIRY;
  211638. s.CDBByte[4] = 100;
  211639. ResetEvent (event);
  211640. if (fSendASPI32Command ((LPSRB)&s) == SS_PENDING)
  211641. WaitForSingleObject (event, 4000);
  211642. CloseHandle (event);
  211643. if (s.SRB_Status == SS_COMP)
  211644. {
  211645. memcpy (dev->vendor, &buffer[8], 8);
  211646. memcpy (dev->productId, &buffer[16], 16);
  211647. memcpy (dev->rev, &buffer[32], 4);
  211648. memcpy (dev->vendorSpec, &buffer[36], 20);
  211649. }
  211650. }
  211651. int FindCDDevices (CDDeviceInfo* const list, int maxItems)
  211652. {
  211653. int count = 0;
  211654. if (usingScsi)
  211655. {
  211656. for (char driveLetter = 'b'; driveLetter <= 'z'; ++driveLetter)
  211657. {
  211658. TCHAR drivePath[8];
  211659. drivePath[0] = driveLetter;
  211660. drivePath[1] = ':';
  211661. drivePath[2] = '\\';
  211662. drivePath[3] = 0;
  211663. if (GetDriveType (drivePath) == DRIVE_CDROM)
  211664. {
  211665. HANDLE h = CreateSCSIDeviceHandle (driveLetter);
  211666. if (h != INVALID_HANDLE_VALUE)
  211667. {
  211668. BYTE buffer[100], passThroughStruct[1024];
  211669. zeromem (buffer, sizeof (buffer));
  211670. zeromem (passThroughStruct, sizeof (passThroughStruct));
  211671. PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER p = (PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER)passThroughStruct;
  211672. p->spt.Length = sizeof (SCSI_PASS_THROUGH);
  211673. p->spt.CdbLength = 6;
  211674. p->spt.SenseInfoLength = 24;
  211675. p->spt.DataIn = SCSI_IOCTL_DATA_IN;
  211676. p->spt.DataTransferLength = 100;
  211677. p->spt.TimeOutValue = 2;
  211678. p->spt.DataBuffer = buffer;
  211679. p->spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  211680. p->spt.Cdb[0] = 0x12;
  211681. p->spt.Cdb[4] = 100;
  211682. DWORD bytesReturned = 0;
  211683. if (DeviceIoControl (h, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  211684. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  211685. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  211686. &bytesReturned, 0) != 0)
  211687. {
  211688. zeromem (&list[count], sizeof (CDDeviceInfo));
  211689. list[count].scsiDriveLetter = driveLetter;
  211690. memcpy (list[count].vendor, &buffer[8], 8);
  211691. memcpy (list[count].productId, &buffer[16], 16);
  211692. memcpy (list[count].rev, &buffer[32], 4);
  211693. memcpy (list[count].vendorSpec, &buffer[36], 20);
  211694. zeromem (passThroughStruct, sizeof (passThroughStruct));
  211695. PSCSI_ADDRESS scsiAddr = (PSCSI_ADDRESS)passThroughStruct;
  211696. scsiAddr->Length = sizeof (SCSI_ADDRESS);
  211697. if (DeviceIoControl (h, IOCTL_SCSI_GET_ADDRESS,
  211698. 0, 0, scsiAddr, sizeof (SCSI_ADDRESS),
  211699. &bytesReturned, 0) != 0)
  211700. {
  211701. list[count].ha = scsiAddr->PortNumber;
  211702. list[count].tgt = scsiAddr->TargetId;
  211703. list[count].lun = scsiAddr->Lun;
  211704. ++count;
  211705. }
  211706. }
  211707. CloseHandle (h);
  211708. }
  211709. }
  211710. }
  211711. }
  211712. else
  211713. {
  211714. const DWORD d = fGetASPI32SupportInfo();
  211715. BYTE status = HIBYTE (LOWORD (d));
  211716. if (status != SS_COMP || status == SS_NO_ADAPTERS)
  211717. return 0;
  211718. const int numAdapters = LOBYTE (LOWORD (d));
  211719. for (BYTE ha = 0; ha < numAdapters; ++ha)
  211720. {
  211721. SRB_HAInquiry s;
  211722. zerostruct (s);
  211723. s.SRB_Cmd = SC_HA_INQUIRY;
  211724. s.SRB_HaID = ha;
  211725. fSendASPI32Command ((LPSRB)&s);
  211726. if (s.SRB_Status == SS_COMP)
  211727. {
  211728. maxItems = (int)s.HA_Unique[3];
  211729. if (maxItems == 0)
  211730. maxItems = 8;
  211731. for (BYTE tgt = 0; tgt < maxItems; ++tgt)
  211732. {
  211733. for (BYTE lun = 0; lun < 8; ++lun)
  211734. {
  211735. SRB_GDEVBlock sb;
  211736. zerostruct (sb);
  211737. sb.SRB_Cmd = SC_GET_DEV_TYPE;
  211738. sb.SRB_HaID = ha;
  211739. sb.SRB_Target = tgt;
  211740. sb.SRB_Lun = lun;
  211741. fSendASPI32Command ((LPSRB) &sb);
  211742. if (sb.SRB_Status == SS_COMP
  211743. && sb.SRB_DeviceType == DTYPE_CROM)
  211744. {
  211745. zeromem (&list[count], sizeof (CDDeviceInfo));
  211746. list[count].ha = ha;
  211747. list[count].tgt = tgt;
  211748. list[count].lun = lun;
  211749. GetAspiDeviceInfo (&(list[count]), ha, tgt, lun);
  211750. ++count;
  211751. }
  211752. }
  211753. }
  211754. }
  211755. }
  211756. }
  211757. return count;
  211758. }
  211759. static int ripperUsers = 0;
  211760. static bool initialisedOk = false;
  211761. class DeinitialiseTimer : private Timer,
  211762. private DeletedAtShutdown
  211763. {
  211764. DeinitialiseTimer (const DeinitialiseTimer&);
  211765. DeinitialiseTimer& operator= (const DeinitialiseTimer&);
  211766. public:
  211767. DeinitialiseTimer()
  211768. {
  211769. startTimer (4000);
  211770. }
  211771. ~DeinitialiseTimer()
  211772. {
  211773. if (--ripperUsers == 0)
  211774. DeinitialiseCDRipper();
  211775. }
  211776. void timerCallback()
  211777. {
  211778. delete this;
  211779. }
  211780. juce_UseDebuggingNewOperator
  211781. };
  211782. static void incUserCount()
  211783. {
  211784. if (ripperUsers++ == 0)
  211785. initialisedOk = InitialiseCDRipper();
  211786. }
  211787. static void decUserCount()
  211788. {
  211789. new DeinitialiseTimer();
  211790. }
  211791. struct CDDeviceWrapper
  211792. {
  211793. ScopedPointer<CDDeviceHandle> cdH;
  211794. ScopedPointer<CDReadBuffer> overlapBuffer;
  211795. bool jitter;
  211796. };
  211797. int getAddressOf (const TOCTRACK* const t)
  211798. {
  211799. return (((DWORD)t->addr[0]) << 24) + (((DWORD)t->addr[1]) << 16) +
  211800. (((DWORD)t->addr[2]) << 8) + ((DWORD)t->addr[3]);
  211801. }
  211802. static const int samplesPerFrame = 44100 / 75;
  211803. static const int bytesPerFrame = samplesPerFrame * 4;
  211804. CDDeviceHandle* openHandle (const CDDeviceInfo* const device)
  211805. {
  211806. SRB_GDEVBlock s;
  211807. zerostruct (s);
  211808. s.SRB_Cmd = SC_GET_DEV_TYPE;
  211809. s.SRB_HaID = device->ha;
  211810. s.SRB_Target = device->tgt;
  211811. s.SRB_Lun = device->lun;
  211812. if (usingScsi)
  211813. {
  211814. HANDLE h = CreateSCSIDeviceHandle (device->scsiDriveLetter);
  211815. if (h != INVALID_HANDLE_VALUE)
  211816. {
  211817. CDDeviceHandle* cdh = new CDDeviceHandle (device);
  211818. cdh->scsiHandle = h;
  211819. return cdh;
  211820. }
  211821. }
  211822. else
  211823. {
  211824. if (fSendASPI32Command ((LPSRB)&s) == SS_COMP
  211825. && s.SRB_DeviceType == DTYPE_CROM)
  211826. {
  211827. return new CDDeviceHandle (device);
  211828. }
  211829. }
  211830. return 0;
  211831. }
  211832. }
  211833. const StringArray AudioCDReader::getAvailableCDNames()
  211834. {
  211835. using namespace CDReaderHelpers;
  211836. StringArray results;
  211837. incUserCount();
  211838. if (initialisedOk)
  211839. {
  211840. CDDeviceInfo list[8];
  211841. const int num = FindCDDevices (list, 8);
  211842. decUserCount();
  211843. for (int i = 0; i < num; ++i)
  211844. {
  211845. String s;
  211846. if (list[i].scsiDriveLetter > 0)
  211847. s << String::charToString (list[i].scsiDriveLetter).toUpperCase() << ": ";
  211848. s << String (list[i].vendor).trim()
  211849. << ' ' << String (list[i].productId).trim()
  211850. << ' ' << String (list[i].rev).trim();
  211851. results.add (s);
  211852. }
  211853. }
  211854. return results;
  211855. }
  211856. AudioCDReader* AudioCDReader::createReaderForCD (const int deviceIndex)
  211857. {
  211858. using namespace CDReaderHelpers;
  211859. incUserCount();
  211860. if (initialisedOk)
  211861. {
  211862. CDDeviceInfo list[8];
  211863. const int num = FindCDDevices (list, 8);
  211864. if (((unsigned int) deviceIndex) < (unsigned int) num)
  211865. {
  211866. CDDeviceHandle* const handle = openHandle (&(list[deviceIndex]));
  211867. if (handle != 0)
  211868. {
  211869. CDDeviceWrapper* const d = new CDDeviceWrapper();
  211870. d->cdH = handle;
  211871. d->overlapBuffer = new CDReadBuffer(3);
  211872. return new AudioCDReader (d);
  211873. }
  211874. }
  211875. }
  211876. decUserCount();
  211877. return 0;
  211878. }
  211879. AudioCDReader::AudioCDReader (void* handle_)
  211880. : AudioFormatReader (0, "CD Audio"),
  211881. handle (handle_),
  211882. indexingEnabled (false),
  211883. lastIndex (0),
  211884. firstFrameInBuffer (0),
  211885. samplesInBuffer (0)
  211886. {
  211887. using namespace CDReaderHelpers;
  211888. jassert (handle_ != 0);
  211889. refreshTrackLengths();
  211890. sampleRate = 44100.0;
  211891. bitsPerSample = 16;
  211892. numChannels = 2;
  211893. usesFloatingPointData = false;
  211894. buffer.setSize (4 * bytesPerFrame, true);
  211895. }
  211896. AudioCDReader::~AudioCDReader()
  211897. {
  211898. using namespace CDReaderHelpers;
  211899. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  211900. delete device;
  211901. decUserCount();
  211902. }
  211903. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  211904. int64 startSampleInFile, int numSamples)
  211905. {
  211906. using namespace CDReaderHelpers;
  211907. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  211908. bool ok = true;
  211909. while (numSamples > 0)
  211910. {
  211911. const int bufferStartSample = firstFrameInBuffer * samplesPerFrame;
  211912. const int bufferEndSample = bufferStartSample + samplesInBuffer;
  211913. if (startSampleInFile >= bufferStartSample
  211914. && startSampleInFile < bufferEndSample)
  211915. {
  211916. const int toDo = (int) jmin ((int64) numSamples, bufferEndSample - startSampleInFile);
  211917. int* const l = destSamples[0] + startOffsetInDestBuffer;
  211918. int* const r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  211919. const short* src = (const short*) buffer.getData();
  211920. src += 2 * (startSampleInFile - bufferStartSample);
  211921. for (int i = 0; i < toDo; ++i)
  211922. {
  211923. l[i] = src [i << 1] << 16;
  211924. if (r != 0)
  211925. r[i] = src [(i << 1) + 1] << 16;
  211926. }
  211927. startOffsetInDestBuffer += toDo;
  211928. startSampleInFile += toDo;
  211929. numSamples -= toDo;
  211930. }
  211931. else
  211932. {
  211933. const int framesInBuffer = buffer.getSize() / bytesPerFrame;
  211934. const int frameNeeded = (int) (startSampleInFile / samplesPerFrame);
  211935. if (firstFrameInBuffer + framesInBuffer != frameNeeded)
  211936. {
  211937. device->overlapBuffer->dataLength = 0;
  211938. device->overlapBuffer->startFrame = 0;
  211939. device->overlapBuffer->numFrames = 0;
  211940. device->jitter = false;
  211941. }
  211942. firstFrameInBuffer = frameNeeded;
  211943. lastIndex = 0;
  211944. CDReadBuffer readBuffer (framesInBuffer + 4);
  211945. readBuffer.wantsIndex = indexingEnabled;
  211946. int i;
  211947. for (i = 5; --i >= 0;)
  211948. {
  211949. readBuffer.startFrame = frameNeeded;
  211950. readBuffer.numFrames = framesInBuffer;
  211951. if (device->cdH->readAudio (&readBuffer, (device->jitter) ? device->overlapBuffer : 0))
  211952. break;
  211953. else
  211954. device->overlapBuffer->dataLength = 0;
  211955. }
  211956. if (i >= 0)
  211957. {
  211958. memcpy ((char*) buffer.getData(),
  211959. readBuffer.buffer + readBuffer.dataStartOffset,
  211960. readBuffer.dataLength);
  211961. samplesInBuffer = readBuffer.dataLength >> 2;
  211962. lastIndex = readBuffer.index;
  211963. }
  211964. else
  211965. {
  211966. int* l = destSamples[0] + startOffsetInDestBuffer;
  211967. int* r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  211968. while (--numSamples >= 0)
  211969. {
  211970. *l++ = 0;
  211971. if (r != 0)
  211972. *r++ = 0;
  211973. }
  211974. // sometimes the read fails for just the very last couple of blocks, so
  211975. // we'll ignore and errors in the last half-second of the disk..
  211976. ok = startSampleInFile > (trackStartSamples [getNumTracks()] - 20000);
  211977. break;
  211978. }
  211979. }
  211980. }
  211981. return ok;
  211982. }
  211983. bool AudioCDReader::isCDStillPresent() const
  211984. {
  211985. using namespace CDReaderHelpers;
  211986. TOC toc;
  211987. zerostruct (toc);
  211988. return ((CDDeviceWrapper*) handle)->cdH->readTOC (&toc);
  211989. }
  211990. void AudioCDReader::refreshTrackLengths()
  211991. {
  211992. using namespace CDReaderHelpers;
  211993. trackStartSamples.clear();
  211994. zeromem (audioTracks, sizeof (audioTracks));
  211995. TOC toc;
  211996. zerostruct (toc);
  211997. if (((CDDeviceWrapper*)handle)->cdH->readTOC (&toc))
  211998. {
  211999. int numTracks = 1 + toc.lastTrack - toc.firstTrack;
  212000. for (int i = 0; i <= numTracks; ++i)
  212001. {
  212002. trackStartSamples.add (samplesPerFrame * getAddressOf (&toc.tracks [i]));
  212003. audioTracks [i] = ((toc.tracks[i].ADR & 4) == 0);
  212004. }
  212005. }
  212006. lengthInSamples = getPositionOfTrackStart (getNumTracks());
  212007. }
  212008. bool AudioCDReader::isTrackAudio (int trackNum) const
  212009. {
  212010. return trackNum >= 0 && trackNum < getNumTracks() && audioTracks [trackNum];
  212011. }
  212012. void AudioCDReader::enableIndexScanning (bool b)
  212013. {
  212014. indexingEnabled = b;
  212015. }
  212016. int AudioCDReader::getLastIndex() const
  212017. {
  212018. return lastIndex;
  212019. }
  212020. const int framesPerIndexRead = 4;
  212021. int AudioCDReader::getIndexAt (int samplePos)
  212022. {
  212023. using namespace CDReaderHelpers;
  212024. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  212025. const int frameNeeded = samplePos / samplesPerFrame;
  212026. device->overlapBuffer->dataLength = 0;
  212027. device->overlapBuffer->startFrame = 0;
  212028. device->overlapBuffer->numFrames = 0;
  212029. device->jitter = false;
  212030. firstFrameInBuffer = 0;
  212031. lastIndex = 0;
  212032. CDReadBuffer readBuffer (4 + framesPerIndexRead);
  212033. readBuffer.wantsIndex = true;
  212034. int i;
  212035. for (i = 5; --i >= 0;)
  212036. {
  212037. readBuffer.startFrame = frameNeeded;
  212038. readBuffer.numFrames = framesPerIndexRead;
  212039. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  212040. break;
  212041. }
  212042. if (i >= 0)
  212043. return readBuffer.index;
  212044. return -1;
  212045. }
  212046. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  212047. {
  212048. using namespace CDReaderHelpers;
  212049. Array <int> indexes;
  212050. const int trackStart = getPositionOfTrackStart (trackNumber);
  212051. const int trackEnd = getPositionOfTrackStart (trackNumber + 1);
  212052. bool needToScan = true;
  212053. if (trackEnd - trackStart > 20 * 44100)
  212054. {
  212055. // check the end of the track for indexes before scanning the whole thing
  212056. needToScan = false;
  212057. int pos = jmax (trackStart, trackEnd - 44100 * 5);
  212058. bool seenAnIndex = false;
  212059. while (pos <= trackEnd - samplesPerFrame)
  212060. {
  212061. const int index = getIndexAt (pos);
  212062. if (index == 0)
  212063. {
  212064. // lead-out, so skip back a bit if we've not found any indexes yet..
  212065. if (seenAnIndex)
  212066. break;
  212067. pos -= 44100 * 5;
  212068. if (pos < trackStart)
  212069. break;
  212070. }
  212071. else
  212072. {
  212073. if (index > 0)
  212074. seenAnIndex = true;
  212075. if (index > 1)
  212076. {
  212077. needToScan = true;
  212078. break;
  212079. }
  212080. pos += samplesPerFrame * framesPerIndexRead;
  212081. }
  212082. }
  212083. }
  212084. if (needToScan)
  212085. {
  212086. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  212087. int pos = trackStart;
  212088. int last = -1;
  212089. while (pos < trackEnd - samplesPerFrame * 10)
  212090. {
  212091. const int frameNeeded = pos / samplesPerFrame;
  212092. device->overlapBuffer->dataLength = 0;
  212093. device->overlapBuffer->startFrame = 0;
  212094. device->overlapBuffer->numFrames = 0;
  212095. device->jitter = false;
  212096. firstFrameInBuffer = 0;
  212097. CDReadBuffer readBuffer (4);
  212098. readBuffer.wantsIndex = true;
  212099. int i;
  212100. for (i = 5; --i >= 0;)
  212101. {
  212102. readBuffer.startFrame = frameNeeded;
  212103. readBuffer.numFrames = framesPerIndexRead;
  212104. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  212105. break;
  212106. }
  212107. if (i < 0)
  212108. break;
  212109. if (readBuffer.index > last && readBuffer.index > 1)
  212110. {
  212111. last = readBuffer.index;
  212112. indexes.add (pos);
  212113. }
  212114. pos += samplesPerFrame * framesPerIndexRead;
  212115. }
  212116. indexes.removeValue (trackStart);
  212117. }
  212118. return indexes;
  212119. }
  212120. void AudioCDReader::ejectDisk()
  212121. {
  212122. using namespace CDReaderHelpers;
  212123. ((CDDeviceWrapper*) handle)->cdH->openDrawer (true);
  212124. }
  212125. #endif
  212126. #if JUCE_USE_CDBURNER
  212127. namespace CDBurnerHelpers
  212128. {
  212129. IDiscRecorder* enumCDBurners (StringArray* list, int indexToOpen, IDiscMaster** master)
  212130. {
  212131. CoInitialize (0);
  212132. IDiscMaster* dm;
  212133. IDiscRecorder* result = 0;
  212134. if (SUCCEEDED (CoCreateInstance (CLSID_MSDiscMasterObj, 0,
  212135. CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER,
  212136. IID_IDiscMaster,
  212137. (void**) &dm)))
  212138. {
  212139. if (SUCCEEDED (dm->Open()))
  212140. {
  212141. IEnumDiscRecorders* drEnum = 0;
  212142. if (SUCCEEDED (dm->EnumDiscRecorders (&drEnum)))
  212143. {
  212144. IDiscRecorder* dr = 0;
  212145. DWORD dummy;
  212146. int index = 0;
  212147. while (drEnum->Next (1, &dr, &dummy) == S_OK)
  212148. {
  212149. if (indexToOpen == index)
  212150. {
  212151. result = dr;
  212152. break;
  212153. }
  212154. else if (list != 0)
  212155. {
  212156. BSTR path;
  212157. if (SUCCEEDED (dr->GetPath (&path)))
  212158. list->add ((const WCHAR*) path);
  212159. }
  212160. ++index;
  212161. dr->Release();
  212162. }
  212163. drEnum->Release();
  212164. }
  212165. if (master == 0)
  212166. dm->Close();
  212167. }
  212168. if (master != 0)
  212169. *master = dm;
  212170. else
  212171. dm->Release();
  212172. }
  212173. return result;
  212174. }
  212175. }
  212176. class AudioCDBurner::Pimpl : public ComBaseClassHelper <IDiscMasterProgressEvents>,
  212177. public Timer
  212178. {
  212179. public:
  212180. Pimpl (AudioCDBurner& owner_, IDiscMaster* discMaster_, IDiscRecorder* discRecorder_)
  212181. : owner (owner_), discMaster (discMaster_), discRecorder (discRecorder_), redbook (0),
  212182. listener (0), progress (0), shouldCancel (false)
  212183. {
  212184. HRESULT hr = discMaster->SetActiveDiscMasterFormat (IID_IRedbookDiscMaster, (void**) &redbook);
  212185. jassert (SUCCEEDED (hr));
  212186. hr = discMaster->SetActiveDiscRecorder (discRecorder);
  212187. //jassert (SUCCEEDED (hr));
  212188. lastState = getDiskState();
  212189. startTimer (2000);
  212190. }
  212191. ~Pimpl() {}
  212192. void releaseObjects()
  212193. {
  212194. discRecorder->Close();
  212195. if (redbook != 0)
  212196. redbook->Release();
  212197. discRecorder->Release();
  212198. discMaster->Release();
  212199. Release();
  212200. }
  212201. HRESULT __stdcall QueryCancel (boolean* pbCancel)
  212202. {
  212203. if (listener != 0 && ! shouldCancel)
  212204. shouldCancel = listener->audioCDBurnProgress (progress);
  212205. *pbCancel = shouldCancel;
  212206. return S_OK;
  212207. }
  212208. HRESULT __stdcall NotifyBlockProgress (long nCompleted, long nTotal)
  212209. {
  212210. progress = nCompleted / (float) nTotal;
  212211. shouldCancel = listener != 0 && listener->audioCDBurnProgress (progress);
  212212. return E_NOTIMPL;
  212213. }
  212214. HRESULT __stdcall NotifyPnPActivity (void) { return E_NOTIMPL; }
  212215. HRESULT __stdcall NotifyAddProgress (long /*nCompletedSteps*/, long /*nTotalSteps*/) { return E_NOTIMPL; }
  212216. HRESULT __stdcall NotifyTrackProgress (long /*nCurrentTrack*/, long /*nTotalTracks*/) { return E_NOTIMPL; }
  212217. HRESULT __stdcall NotifyPreparingBurn (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  212218. HRESULT __stdcall NotifyClosingDisc (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  212219. HRESULT __stdcall NotifyBurnComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  212220. HRESULT __stdcall NotifyEraseComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  212221. class ScopedDiscOpener
  212222. {
  212223. public:
  212224. ScopedDiscOpener (Pimpl& p) : pimpl (p) { pimpl.discRecorder->OpenExclusive(); }
  212225. ~ScopedDiscOpener() { pimpl.discRecorder->Close(); }
  212226. private:
  212227. Pimpl& pimpl;
  212228. ScopedDiscOpener (const ScopedDiscOpener&);
  212229. ScopedDiscOpener& operator= (const ScopedDiscOpener&);
  212230. };
  212231. DiskState getDiskState()
  212232. {
  212233. const ScopedDiscOpener opener (*this);
  212234. long type, flags;
  212235. HRESULT hr = discRecorder->QueryMediaType (&type, &flags);
  212236. if (FAILED (hr))
  212237. return unknown;
  212238. if (type != 0 && (flags & MEDIA_WRITABLE) != 0)
  212239. return writableDiskPresent;
  212240. if (type == 0)
  212241. return noDisc;
  212242. else
  212243. return readOnlyDiskPresent;
  212244. }
  212245. int getIntProperty (const LPOLESTR name, const int defaultReturn) const
  212246. {
  212247. ComSmartPtr<IPropertyStorage> prop;
  212248. if (FAILED (discRecorder->GetRecorderProperties (prop.resetAndGetPointerAddress())))
  212249. return defaultReturn;
  212250. PROPSPEC iPropSpec;
  212251. iPropSpec.ulKind = PRSPEC_LPWSTR;
  212252. iPropSpec.lpwstr = name;
  212253. PROPVARIANT iPropVariant;
  212254. return FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant))
  212255. ? defaultReturn : (int) iPropVariant.lVal;
  212256. }
  212257. bool setIntProperty (const LPOLESTR name, const int value) const
  212258. {
  212259. ComSmartPtr<IPropertyStorage> prop;
  212260. if (FAILED (discRecorder->GetRecorderProperties (prop.resetAndGetPointerAddress())))
  212261. return false;
  212262. PROPSPEC iPropSpec;
  212263. iPropSpec.ulKind = PRSPEC_LPWSTR;
  212264. iPropSpec.lpwstr = name;
  212265. PROPVARIANT iPropVariant;
  212266. if (FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant)))
  212267. return false;
  212268. iPropVariant.lVal = (long) value;
  212269. return SUCCEEDED (prop->WriteMultiple (1, &iPropSpec, &iPropVariant, iPropVariant.vt))
  212270. && SUCCEEDED (discRecorder->SetRecorderProperties (prop));
  212271. }
  212272. void timerCallback()
  212273. {
  212274. const DiskState state = getDiskState();
  212275. if (state != lastState)
  212276. {
  212277. lastState = state;
  212278. owner.sendChangeMessage (&owner);
  212279. }
  212280. }
  212281. AudioCDBurner& owner;
  212282. DiskState lastState;
  212283. IDiscMaster* discMaster;
  212284. IDiscRecorder* discRecorder;
  212285. IRedbookDiscMaster* redbook;
  212286. AudioCDBurner::BurnProgressListener* listener;
  212287. float progress;
  212288. bool shouldCancel;
  212289. };
  212290. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  212291. {
  212292. IDiscMaster* discMaster = 0;
  212293. IDiscRecorder* discRecorder = CDBurnerHelpers::enumCDBurners (0, deviceIndex, &discMaster);
  212294. if (discRecorder != 0)
  212295. pimpl = new Pimpl (*this, discMaster, discRecorder);
  212296. }
  212297. AudioCDBurner::~AudioCDBurner()
  212298. {
  212299. if (pimpl != 0)
  212300. pimpl.release()->releaseObjects();
  212301. }
  212302. const StringArray AudioCDBurner::findAvailableDevices()
  212303. {
  212304. StringArray devs;
  212305. CDBurnerHelpers::enumCDBurners (&devs, -1, 0);
  212306. return devs;
  212307. }
  212308. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  212309. {
  212310. ScopedPointer<AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  212311. if (b->pimpl == 0)
  212312. b = 0;
  212313. return b.release();
  212314. }
  212315. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  212316. {
  212317. return pimpl->getDiskState();
  212318. }
  212319. bool AudioCDBurner::isDiskPresent() const
  212320. {
  212321. return getDiskState() == writableDiskPresent;
  212322. }
  212323. bool AudioCDBurner::openTray()
  212324. {
  212325. const Pimpl::ScopedDiscOpener opener (*pimpl);
  212326. return SUCCEEDED (pimpl->discRecorder->Eject());
  212327. }
  212328. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  212329. {
  212330. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  212331. DiskState oldState = getDiskState();
  212332. DiskState newState = oldState;
  212333. while (newState == oldState && Time::currentTimeMillis() < timeout)
  212334. {
  212335. newState = getDiskState();
  212336. Thread::sleep (jmin (250, (int) (timeout - Time::currentTimeMillis())));
  212337. }
  212338. return newState;
  212339. }
  212340. const Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  212341. {
  212342. Array<int> results;
  212343. const int maxSpeed = pimpl->getIntProperty (L"MaxWriteSpeed", 1);
  212344. const int speeds[] = { 1, 2, 4, 8, 12, 16, 20, 24, 32, 40, 64, 80 };
  212345. for (int i = 0; i < numElementsInArray (speeds); ++i)
  212346. if (speeds[i] <= maxSpeed)
  212347. results.add (speeds[i]);
  212348. results.addIfNotAlreadyThere (maxSpeed);
  212349. return results;
  212350. }
  212351. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  212352. {
  212353. if (pimpl->getIntProperty (L"BufferUnderrunFreeCapable", 0) == 0)
  212354. return false;
  212355. pimpl->setIntProperty (L"EnableBufferUnderrunFree", shouldBeEnabled ? -1 : 0);
  212356. return pimpl->getIntProperty (L"EnableBufferUnderrunFree", 0) != 0;
  212357. }
  212358. int AudioCDBurner::getNumAvailableAudioBlocks() const
  212359. {
  212360. long blocksFree = 0;
  212361. pimpl->redbook->GetAvailableAudioTrackBlocks (&blocksFree);
  212362. return blocksFree;
  212363. }
  212364. const String AudioCDBurner::burn (AudioCDBurner::BurnProgressListener* listener, bool ejectDiscAfterwards,
  212365. bool performFakeBurnForTesting, int writeSpeed)
  212366. {
  212367. pimpl->setIntProperty (L"WriteSpeed", writeSpeed > 0 ? writeSpeed : -1);
  212368. pimpl->listener = listener;
  212369. pimpl->progress = 0;
  212370. pimpl->shouldCancel = false;
  212371. UINT_PTR cookie;
  212372. HRESULT hr = pimpl->discMaster->ProgressAdvise ((AudioCDBurner::Pimpl*) pimpl, &cookie);
  212373. hr = pimpl->discMaster->RecordDisc (performFakeBurnForTesting,
  212374. ejectDiscAfterwards);
  212375. String error;
  212376. if (hr != S_OK)
  212377. {
  212378. const char* e = "Couldn't open or write to the CD device";
  212379. if (hr == IMAPI_E_USERABORT)
  212380. e = "User cancelled the write operation";
  212381. else if (hr == IMAPI_E_MEDIUM_NOTPRESENT || hr == IMAPI_E_TRACKOPEN)
  212382. e = "No Disk present";
  212383. error = e;
  212384. }
  212385. pimpl->discMaster->ProgressUnadvise (cookie);
  212386. pimpl->listener = 0;
  212387. return error;
  212388. }
  212389. bool AudioCDBurner::addAudioTrack (AudioSource* audioSource, int numSamples)
  212390. {
  212391. if (audioSource == 0)
  212392. return false;
  212393. ScopedPointer<AudioSource> source (audioSource);
  212394. long bytesPerBlock;
  212395. HRESULT hr = pimpl->redbook->GetAudioBlockSize (&bytesPerBlock);
  212396. const int samplesPerBlock = bytesPerBlock / 4;
  212397. bool ok = true;
  212398. hr = pimpl->redbook->CreateAudioTrack ((long) numSamples / (bytesPerBlock * 4));
  212399. HeapBlock <byte> buffer (bytesPerBlock);
  212400. AudioSampleBuffer sourceBuffer (2, samplesPerBlock);
  212401. int samplesDone = 0;
  212402. source->prepareToPlay (samplesPerBlock, 44100.0);
  212403. while (ok)
  212404. {
  212405. {
  212406. AudioSourceChannelInfo info;
  212407. info.buffer = &sourceBuffer;
  212408. info.numSamples = samplesPerBlock;
  212409. info.startSample = 0;
  212410. sourceBuffer.clear();
  212411. source->getNextAudioBlock (info);
  212412. }
  212413. zeromem (buffer, bytesPerBlock);
  212414. typedef AudioData::Pointer <AudioData::Int16, AudioData::LittleEndian,
  212415. AudioData::Interleaved, AudioData::NonConst> CDSampleFormat;
  212416. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian,
  212417. AudioData::NonInterleaved, AudioData::Const> SourceSampleFormat;
  212418. CDSampleFormat left (buffer, 2);
  212419. left.convertSamples (SourceSampleFormat (sourceBuffer.getSampleData (0)), samplesPerBlock);
  212420. CDSampleFormat right (buffer + 2, 2);
  212421. right.convertSamples (SourceSampleFormat (sourceBuffer.getSampleData (1)), samplesPerBlock);
  212422. hr = pimpl->redbook->AddAudioTrackBlocks (buffer, bytesPerBlock);
  212423. if (FAILED (hr))
  212424. ok = false;
  212425. samplesDone += samplesPerBlock;
  212426. if (samplesDone >= numSamples)
  212427. break;
  212428. }
  212429. hr = pimpl->redbook->CloseAudioTrack();
  212430. return ok && hr == S_OK;
  212431. }
  212432. #endif
  212433. #endif
  212434. /*** End of inlined file: juce_win32_AudioCDReader.cpp ***/
  212435. /*** Start of inlined file: juce_win32_Midi.cpp ***/
  212436. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  212437. // compiled on its own).
  212438. #if JUCE_INCLUDED_FILE
  212439. class MidiInCollector
  212440. {
  212441. public:
  212442. MidiInCollector (MidiInput* const input_,
  212443. MidiInputCallback& callback_)
  212444. : deviceHandle (0),
  212445. input (input_),
  212446. callback (callback_),
  212447. concatenator (4096),
  212448. isStarted (false),
  212449. startTime (0)
  212450. {
  212451. }
  212452. ~MidiInCollector()
  212453. {
  212454. stop();
  212455. if (deviceHandle != 0)
  212456. {
  212457. int count = 5;
  212458. while (--count >= 0)
  212459. {
  212460. if (midiInClose (deviceHandle) == MMSYSERR_NOERROR)
  212461. break;
  212462. Sleep (20);
  212463. }
  212464. }
  212465. }
  212466. void handleMessage (const uint32 message, const uint32 timeStamp)
  212467. {
  212468. if ((message & 0xff) >= 0x80 && isStarted)
  212469. {
  212470. concatenator.pushMidiData (&message, 3, convertTimeStamp (timeStamp), input, callback);
  212471. writeFinishedBlocks();
  212472. }
  212473. }
  212474. void handleSysEx (MIDIHDR* const hdr, const uint32 timeStamp)
  212475. {
  212476. if (isStarted)
  212477. {
  212478. concatenator.pushMidiData (hdr->lpData, hdr->dwBytesRecorded, convertTimeStamp (timeStamp), input, callback);
  212479. writeFinishedBlocks();
  212480. }
  212481. }
  212482. void start()
  212483. {
  212484. jassert (deviceHandle != 0);
  212485. if (deviceHandle != 0 && ! isStarted)
  212486. {
  212487. activeMidiCollectors.addIfNotAlreadyThere (this);
  212488. for (int i = 0; i < (int) numHeaders; ++i)
  212489. headers[i].write (deviceHandle);
  212490. startTime = Time::getMillisecondCounter();
  212491. MMRESULT res = midiInStart (deviceHandle);
  212492. if (res == MMSYSERR_NOERROR)
  212493. {
  212494. concatenator.reset();
  212495. isStarted = true;
  212496. }
  212497. else
  212498. {
  212499. unprepareAllHeaders();
  212500. }
  212501. }
  212502. }
  212503. void stop()
  212504. {
  212505. if (isStarted)
  212506. {
  212507. isStarted = false;
  212508. midiInReset (deviceHandle);
  212509. midiInStop (deviceHandle);
  212510. activeMidiCollectors.removeValue (this);
  212511. unprepareAllHeaders();
  212512. concatenator.reset();
  212513. }
  212514. }
  212515. static void CALLBACK midiInCallback (HMIDIIN, UINT uMsg, DWORD_PTR dwInstance, DWORD_PTR midiMessage, DWORD_PTR timeStamp)
  212516. {
  212517. MidiInCollector* const collector = reinterpret_cast <MidiInCollector*> (dwInstance);
  212518. if (activeMidiCollectors.contains (collector))
  212519. {
  212520. if (uMsg == MIM_DATA)
  212521. collector->handleMessage ((uint32) midiMessage, (uint32) timeStamp);
  212522. else if (uMsg == MIM_LONGDATA)
  212523. collector->handleSysEx ((MIDIHDR*) midiMessage, (uint32) timeStamp);
  212524. }
  212525. }
  212526. juce_UseDebuggingNewOperator
  212527. HMIDIIN deviceHandle;
  212528. private:
  212529. static Array <MidiInCollector*, CriticalSection> activeMidiCollectors;
  212530. MidiInput* input;
  212531. MidiInputCallback& callback;
  212532. MidiDataConcatenator concatenator;
  212533. bool volatile isStarted;
  212534. uint32 startTime;
  212535. class MidiHeader
  212536. {
  212537. public:
  212538. MidiHeader()
  212539. {
  212540. zerostruct (hdr);
  212541. hdr.lpData = data;
  212542. hdr.dwBufferLength = numElementsInArray (data);
  212543. }
  212544. void write (HMIDIIN deviceHandle)
  212545. {
  212546. hdr.dwBytesRecorded = 0;
  212547. MMRESULT res = midiInPrepareHeader (deviceHandle, &hdr, sizeof (hdr));
  212548. res = midiInAddBuffer (deviceHandle, &hdr, sizeof (hdr));
  212549. }
  212550. void writeIfFinished (HMIDIIN deviceHandle)
  212551. {
  212552. if ((hdr.dwFlags & WHDR_DONE) != 0)
  212553. {
  212554. MMRESULT res = midiInUnprepareHeader (deviceHandle, &hdr, sizeof (hdr));
  212555. (void) res;
  212556. write (deviceHandle);
  212557. }
  212558. }
  212559. void unprepare (HMIDIIN deviceHandle)
  212560. {
  212561. if ((hdr.dwFlags & WHDR_DONE) != 0)
  212562. {
  212563. int c = 10;
  212564. while (--c >= 0 && midiInUnprepareHeader (deviceHandle, &hdr, sizeof (hdr)) == MIDIERR_STILLPLAYING)
  212565. Thread::sleep (20);
  212566. jassert (c >= 0);
  212567. }
  212568. }
  212569. private:
  212570. MIDIHDR hdr;
  212571. char data [256];
  212572. MidiHeader (const MidiHeader&);
  212573. MidiHeader& operator= (const MidiHeader&);
  212574. };
  212575. enum { numHeaders = 32 };
  212576. MidiHeader headers [numHeaders];
  212577. void writeFinishedBlocks()
  212578. {
  212579. for (int i = 0; i < (int) numHeaders; ++i)
  212580. headers[i].writeIfFinished (deviceHandle);
  212581. }
  212582. void unprepareAllHeaders()
  212583. {
  212584. for (int i = 0; i < (int) numHeaders; ++i)
  212585. headers[i].unprepare (deviceHandle);
  212586. }
  212587. double convertTimeStamp (uint32 timeStamp)
  212588. {
  212589. timeStamp += startTime;
  212590. const uint32 now = Time::getMillisecondCounter();
  212591. if (timeStamp > now)
  212592. {
  212593. if (timeStamp > now + 2)
  212594. --startTime;
  212595. timeStamp = now;
  212596. }
  212597. return timeStamp * 0.001;
  212598. }
  212599. MidiInCollector (const MidiInCollector&);
  212600. MidiInCollector& operator= (const MidiInCollector&);
  212601. };
  212602. Array <MidiInCollector*, CriticalSection> MidiInCollector::activeMidiCollectors;
  212603. const StringArray MidiInput::getDevices()
  212604. {
  212605. StringArray s;
  212606. const int num = midiInGetNumDevs();
  212607. for (int i = 0; i < num; ++i)
  212608. {
  212609. MIDIINCAPS mc;
  212610. zerostruct (mc);
  212611. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212612. s.add (String (mc.szPname, sizeof (mc.szPname)));
  212613. }
  212614. return s;
  212615. }
  212616. int MidiInput::getDefaultDeviceIndex()
  212617. {
  212618. return 0;
  212619. }
  212620. MidiInput* MidiInput::openDevice (const int index, MidiInputCallback* const callback)
  212621. {
  212622. if (callback == 0)
  212623. return 0;
  212624. UINT deviceId = MIDI_MAPPER;
  212625. int n = 0;
  212626. String name;
  212627. const int num = midiInGetNumDevs();
  212628. for (int i = 0; i < num; ++i)
  212629. {
  212630. MIDIINCAPS mc;
  212631. zerostruct (mc);
  212632. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212633. {
  212634. if (index == n)
  212635. {
  212636. deviceId = i;
  212637. name = String (mc.szPname, numElementsInArray (mc.szPname));
  212638. break;
  212639. }
  212640. ++n;
  212641. }
  212642. }
  212643. ScopedPointer <MidiInput> in (new MidiInput (name));
  212644. ScopedPointer <MidiInCollector> collector (new MidiInCollector (in, *callback));
  212645. HMIDIIN h;
  212646. HRESULT err = midiInOpen (&h, deviceId,
  212647. (DWORD_PTR) &MidiInCollector::midiInCallback,
  212648. (DWORD_PTR) (MidiInCollector*) collector,
  212649. CALLBACK_FUNCTION);
  212650. if (err == MMSYSERR_NOERROR)
  212651. {
  212652. collector->deviceHandle = h;
  212653. in->internal = collector.release();
  212654. return in.release();
  212655. }
  212656. return 0;
  212657. }
  212658. MidiInput::MidiInput (const String& name_)
  212659. : name (name_),
  212660. internal (0)
  212661. {
  212662. }
  212663. MidiInput::~MidiInput()
  212664. {
  212665. delete static_cast <MidiInCollector*> (internal);
  212666. }
  212667. void MidiInput::start()
  212668. {
  212669. static_cast <MidiInCollector*> (internal)->start();
  212670. }
  212671. void MidiInput::stop()
  212672. {
  212673. static_cast <MidiInCollector*> (internal)->stop();
  212674. }
  212675. struct MidiOutHandle
  212676. {
  212677. int refCount;
  212678. UINT deviceId;
  212679. HMIDIOUT handle;
  212680. static Array<MidiOutHandle*> activeHandles;
  212681. juce_UseDebuggingNewOperator
  212682. };
  212683. Array<MidiOutHandle*> MidiOutHandle::activeHandles;
  212684. const StringArray MidiOutput::getDevices()
  212685. {
  212686. StringArray s;
  212687. const int num = midiOutGetNumDevs();
  212688. for (int i = 0; i < num; ++i)
  212689. {
  212690. MIDIOUTCAPS mc;
  212691. zerostruct (mc);
  212692. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212693. s.add (String (mc.szPname, sizeof (mc.szPname)));
  212694. }
  212695. return s;
  212696. }
  212697. int MidiOutput::getDefaultDeviceIndex()
  212698. {
  212699. const int num = midiOutGetNumDevs();
  212700. int n = 0;
  212701. for (int i = 0; i < num; ++i)
  212702. {
  212703. MIDIOUTCAPS mc;
  212704. zerostruct (mc);
  212705. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212706. {
  212707. if ((mc.wTechnology & MOD_MAPPER) != 0)
  212708. return n;
  212709. ++n;
  212710. }
  212711. }
  212712. return 0;
  212713. }
  212714. MidiOutput* MidiOutput::openDevice (int index)
  212715. {
  212716. UINT deviceId = MIDI_MAPPER;
  212717. const int num = midiOutGetNumDevs();
  212718. int i, n = 0;
  212719. for (i = 0; i < num; ++i)
  212720. {
  212721. MIDIOUTCAPS mc;
  212722. zerostruct (mc);
  212723. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212724. {
  212725. // use the microsoft sw synth as a default - best not to allow deviceId
  212726. // to be MIDI_MAPPER, or else device sharing breaks
  212727. if (String (mc.szPname, sizeof (mc.szPname)).containsIgnoreCase ("microsoft"))
  212728. deviceId = i;
  212729. if (index == n)
  212730. {
  212731. deviceId = i;
  212732. break;
  212733. }
  212734. ++n;
  212735. }
  212736. }
  212737. for (i = MidiOutHandle::activeHandles.size(); --i >= 0;)
  212738. {
  212739. MidiOutHandle* const han = MidiOutHandle::activeHandles.getUnchecked(i);
  212740. if (han != 0 && han->deviceId == deviceId)
  212741. {
  212742. han->refCount++;
  212743. MidiOutput* const out = new MidiOutput();
  212744. out->internal = han;
  212745. return out;
  212746. }
  212747. }
  212748. for (i = 4; --i >= 0;)
  212749. {
  212750. HMIDIOUT h = 0;
  212751. MMRESULT res = midiOutOpen (&h, deviceId, 0, 0, CALLBACK_NULL);
  212752. if (res == MMSYSERR_NOERROR)
  212753. {
  212754. MidiOutHandle* const han = new MidiOutHandle();
  212755. han->deviceId = deviceId;
  212756. han->refCount = 1;
  212757. han->handle = h;
  212758. MidiOutHandle::activeHandles.add (han);
  212759. MidiOutput* const out = new MidiOutput();
  212760. out->internal = han;
  212761. return out;
  212762. }
  212763. else if (res == MMSYSERR_ALLOCATED)
  212764. {
  212765. Sleep (100);
  212766. }
  212767. else
  212768. {
  212769. break;
  212770. }
  212771. }
  212772. return 0;
  212773. }
  212774. MidiOutput::~MidiOutput()
  212775. {
  212776. MidiOutHandle* const h = static_cast <MidiOutHandle*> (internal);
  212777. if (MidiOutHandle::activeHandles.contains (h) && --(h->refCount) == 0)
  212778. {
  212779. midiOutClose (h->handle);
  212780. MidiOutHandle::activeHandles.removeValue (h);
  212781. delete h;
  212782. }
  212783. }
  212784. void MidiOutput::reset()
  212785. {
  212786. const MidiOutHandle* const h = static_cast <const MidiOutHandle*> (internal);
  212787. midiOutReset (h->handle);
  212788. }
  212789. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  212790. {
  212791. const MidiOutHandle* const handle = static_cast <const MidiOutHandle*> (internal);
  212792. DWORD n;
  212793. if (midiOutGetVolume (handle->handle, &n) == MMSYSERR_NOERROR)
  212794. {
  212795. const unsigned short* const nn = reinterpret_cast<const unsigned short*> (&n);
  212796. rightVol = nn[0] / (float) 0xffff;
  212797. leftVol = nn[1] / (float) 0xffff;
  212798. return true;
  212799. }
  212800. else
  212801. {
  212802. rightVol = leftVol = 1.0f;
  212803. return false;
  212804. }
  212805. }
  212806. void MidiOutput::setVolume (float leftVol, float rightVol)
  212807. {
  212808. const MidiOutHandle* const handle = static_cast <MidiOutHandle*> (internal);
  212809. DWORD n;
  212810. unsigned short* const nn = reinterpret_cast<unsigned short*> (&n);
  212811. nn[0] = (unsigned short) jlimit (0, 0xffff, (int) (rightVol * 0xffff));
  212812. nn[1] = (unsigned short) jlimit (0, 0xffff, (int) (leftVol * 0xffff));
  212813. midiOutSetVolume (handle->handle, n);
  212814. }
  212815. void MidiOutput::sendMessageNow (const MidiMessage& message)
  212816. {
  212817. const MidiOutHandle* const handle = static_cast <const MidiOutHandle*> (internal);
  212818. if (message.getRawDataSize() > 3
  212819. || message.isSysEx())
  212820. {
  212821. MIDIHDR h;
  212822. zerostruct (h);
  212823. h.lpData = (char*) message.getRawData();
  212824. h.dwBufferLength = message.getRawDataSize();
  212825. h.dwBytesRecorded = message.getRawDataSize();
  212826. if (midiOutPrepareHeader (handle->handle, &h, sizeof (MIDIHDR)) == MMSYSERR_NOERROR)
  212827. {
  212828. MMRESULT res = midiOutLongMsg (handle->handle, &h, sizeof (MIDIHDR));
  212829. if (res == MMSYSERR_NOERROR)
  212830. {
  212831. while ((h.dwFlags & MHDR_DONE) == 0)
  212832. Sleep (1);
  212833. int count = 500; // 1 sec timeout
  212834. while (--count >= 0)
  212835. {
  212836. res = midiOutUnprepareHeader (handle->handle, &h, sizeof (MIDIHDR));
  212837. if (res == MIDIERR_STILLPLAYING)
  212838. Sleep (2);
  212839. else
  212840. break;
  212841. }
  212842. }
  212843. }
  212844. }
  212845. else
  212846. {
  212847. midiOutShortMsg (handle->handle,
  212848. *(unsigned int*) message.getRawData());
  212849. }
  212850. }
  212851. #endif
  212852. /*** End of inlined file: juce_win32_Midi.cpp ***/
  212853. /*** Start of inlined file: juce_win32_ASIO.cpp ***/
  212854. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  212855. // compiled on its own).
  212856. #if JUCE_INCLUDED_FILE && JUCE_ASIO
  212857. #undef WINDOWS
  212858. // #define ASIO_DEBUGGING 1
  212859. #undef log
  212860. #if ASIO_DEBUGGING
  212861. #define log(a) { Logger::writeToLog (a); DBG (a) }
  212862. #else
  212863. #define log(a) {}
  212864. #endif
  212865. /* The ASIO SDK *should* declare its callback functions as being __cdecl, but different versions seem
  212866. to be pretty random about whether or not they do this. If you hit an error using these functions
  212867. it'll be because you're trying to build using __stdcall, in which case you'd need to either get hold of
  212868. an ASIO SDK which correctly specifies __cdecl, or add the __cdecl keyword to its functions yourself.
  212869. */
  212870. #define JUCE_ASIOCALLBACK __cdecl
  212871. namespace ASIODebugging
  212872. {
  212873. #if ASIO_DEBUGGING
  212874. static void log (const String& context, long error)
  212875. {
  212876. String err ("unknown error");
  212877. if (error == ASE_NotPresent) err = "Not Present";
  212878. else if (error == ASE_HWMalfunction) err = "Hardware Malfunction";
  212879. else if (error == ASE_InvalidParameter) err = "Invalid Parameter";
  212880. else if (error == ASE_InvalidMode) err = "Invalid Mode";
  212881. else if (error == ASE_SPNotAdvancing) err = "Sample position not advancing";
  212882. else if (error == ASE_NoClock) err = "No Clock";
  212883. else if (error == ASE_NoMemory) err = "Out of memory";
  212884. log ("!!error: " + context + " - " + err);
  212885. }
  212886. #define logError(a, b) ASIODebugging::log ((a), (b))
  212887. #else
  212888. #define logError(a, b) {}
  212889. #endif
  212890. }
  212891. class ASIOAudioIODevice;
  212892. static ASIOAudioIODevice* volatile currentASIODev[3] = { 0, 0, 0 };
  212893. static const int maxASIOChannels = 160;
  212894. class JUCE_API ASIOAudioIODevice : public AudioIODevice,
  212895. private Timer
  212896. {
  212897. public:
  212898. Component ourWindow;
  212899. ASIOAudioIODevice (const String& name_, const CLSID classId_, const int slotNumber,
  212900. const String& optionalDllForDirectLoading_)
  212901. : AudioIODevice (name_, "ASIO"),
  212902. asioObject (0),
  212903. classId (classId_),
  212904. optionalDllForDirectLoading (optionalDllForDirectLoading_),
  212905. currentBitDepth (16),
  212906. currentSampleRate (0),
  212907. isOpen_ (false),
  212908. isStarted (false),
  212909. postOutput (true),
  212910. insideControlPanelModalLoop (false),
  212911. shouldUsePreferredSize (false)
  212912. {
  212913. name = name_;
  212914. ourWindow.addToDesktop (0);
  212915. windowHandle = ourWindow.getWindowHandle();
  212916. jassert (currentASIODev [slotNumber] == 0);
  212917. currentASIODev [slotNumber] = this;
  212918. openDevice();
  212919. }
  212920. ~ASIOAudioIODevice()
  212921. {
  212922. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  212923. if (currentASIODev[i] == this)
  212924. currentASIODev[i] = 0;
  212925. close();
  212926. log ("ASIO - exiting");
  212927. removeCurrentDriver();
  212928. }
  212929. void updateSampleRates()
  212930. {
  212931. // find a list of sample rates..
  212932. const double possibleSampleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  212933. sampleRates.clear();
  212934. if (asioObject != 0)
  212935. {
  212936. for (int index = 0; index < numElementsInArray (possibleSampleRates); ++index)
  212937. {
  212938. const long err = asioObject->canSampleRate (possibleSampleRates[index]);
  212939. if (err == 0)
  212940. {
  212941. sampleRates.add ((int) possibleSampleRates[index]);
  212942. log ("rate: " + String ((int) possibleSampleRates[index]));
  212943. }
  212944. else if (err != ASE_NoClock)
  212945. {
  212946. logError ("CanSampleRate", err);
  212947. }
  212948. }
  212949. if (sampleRates.size() == 0)
  212950. {
  212951. double cr = 0;
  212952. const long err = asioObject->getSampleRate (&cr);
  212953. log ("No sample rates supported - current rate: " + String ((int) cr));
  212954. if (err == 0)
  212955. sampleRates.add ((int) cr);
  212956. }
  212957. }
  212958. }
  212959. const StringArray getOutputChannelNames() { return outputChannelNames; }
  212960. const StringArray getInputChannelNames() { return inputChannelNames; }
  212961. int getNumSampleRates() { return sampleRates.size(); }
  212962. double getSampleRate (int index) { return sampleRates [index]; }
  212963. int getNumBufferSizesAvailable() { return bufferSizes.size(); }
  212964. int getBufferSizeSamples (int index) { return bufferSizes [index]; }
  212965. int getDefaultBufferSize() { return preferredSize; }
  212966. const String open (const BigInteger& inputChannels,
  212967. const BigInteger& outputChannels,
  212968. double sr,
  212969. int bufferSizeSamples)
  212970. {
  212971. close();
  212972. currentCallback = 0;
  212973. if (bufferSizeSamples <= 0)
  212974. shouldUsePreferredSize = true;
  212975. if (asioObject == 0 || ! isASIOOpen)
  212976. {
  212977. log ("Warning: device not open");
  212978. const String err (openDevice());
  212979. if (asioObject == 0 || ! isASIOOpen)
  212980. return err;
  212981. }
  212982. isStarted = false;
  212983. bufferIndex = -1;
  212984. long err = 0;
  212985. long newPreferredSize = 0;
  212986. // if the preferred size has just changed, assume it's a control panel thing and use it as the new value.
  212987. minSize = 0;
  212988. maxSize = 0;
  212989. newPreferredSize = 0;
  212990. granularity = 0;
  212991. if (asioObject->getBufferSize (&minSize, &maxSize, &newPreferredSize, &granularity) == 0)
  212992. {
  212993. if (preferredSize != 0 && newPreferredSize != 0 && newPreferredSize != preferredSize)
  212994. shouldUsePreferredSize = true;
  212995. preferredSize = newPreferredSize;
  212996. }
  212997. // unfortunate workaround for certain manufacturers whose drivers crash horribly if you make
  212998. // dynamic changes to the buffer size...
  212999. shouldUsePreferredSize = shouldUsePreferredSize
  213000. || getName().containsIgnoreCase ("Digidesign");
  213001. if (shouldUsePreferredSize)
  213002. {
  213003. log ("Using preferred size for buffer..");
  213004. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  213005. {
  213006. bufferSizeSamples = preferredSize;
  213007. }
  213008. else
  213009. {
  213010. bufferSizeSamples = 1024;
  213011. logError ("GetBufferSize1", err);
  213012. }
  213013. shouldUsePreferredSize = false;
  213014. }
  213015. int sampleRate = roundDoubleToInt (sr);
  213016. currentSampleRate = sampleRate;
  213017. currentBlockSizeSamples = bufferSizeSamples;
  213018. currentChansOut.clear();
  213019. currentChansIn.clear();
  213020. zeromem (inBuffers, sizeof (inBuffers));
  213021. zeromem (outBuffers, sizeof (outBuffers));
  213022. updateSampleRates();
  213023. if (sampleRate == 0 || (sampleRates.size() > 0 && ! sampleRates.contains (sampleRate)))
  213024. sampleRate = sampleRates[0];
  213025. jassert (sampleRate != 0);
  213026. if (sampleRate == 0)
  213027. sampleRate = 44100;
  213028. long numSources = 32;
  213029. ASIOClockSource clocks[32];
  213030. zeromem (clocks, sizeof (clocks));
  213031. asioObject->getClockSources (clocks, &numSources);
  213032. bool isSourceSet = false;
  213033. // careful not to remove this loop because it does more than just logging!
  213034. int i;
  213035. for (i = 0; i < numSources; ++i)
  213036. {
  213037. String s ("clock: ");
  213038. s += clocks[i].name;
  213039. if (clocks[i].isCurrentSource)
  213040. {
  213041. isSourceSet = true;
  213042. s << " (cur)";
  213043. }
  213044. log (s);
  213045. }
  213046. if (numSources > 1 && ! isSourceSet)
  213047. {
  213048. log ("setting clock source");
  213049. asioObject->setClockSource (clocks[0].index);
  213050. Thread::sleep (20);
  213051. }
  213052. else
  213053. {
  213054. if (numSources == 0)
  213055. {
  213056. log ("ASIO - no clock sources!");
  213057. }
  213058. }
  213059. double cr = 0;
  213060. err = asioObject->getSampleRate (&cr);
  213061. if (err == 0)
  213062. {
  213063. currentSampleRate = cr;
  213064. }
  213065. else
  213066. {
  213067. logError ("GetSampleRate", err);
  213068. currentSampleRate = 0;
  213069. }
  213070. error = String::empty;
  213071. needToReset = false;
  213072. isReSync = false;
  213073. err = 0;
  213074. bool buffersCreated = false;
  213075. if (currentSampleRate != sampleRate)
  213076. {
  213077. log ("ASIO samplerate: " + String (currentSampleRate) + " to " + String (sampleRate));
  213078. err = asioObject->setSampleRate (sampleRate);
  213079. if (err == ASE_NoClock && numSources > 0)
  213080. {
  213081. log ("trying to set a clock source..");
  213082. Thread::sleep (10);
  213083. err = asioObject->setClockSource (clocks[0].index);
  213084. if (err != 0)
  213085. {
  213086. logError ("SetClock", err);
  213087. }
  213088. Thread::sleep (10);
  213089. err = asioObject->setSampleRate (sampleRate);
  213090. }
  213091. }
  213092. if (err == 0)
  213093. {
  213094. currentSampleRate = sampleRate;
  213095. if (needToReset)
  213096. {
  213097. if (isReSync)
  213098. {
  213099. log ("Resync request");
  213100. }
  213101. log ("! Resetting ASIO after sample rate change");
  213102. removeCurrentDriver();
  213103. loadDriver();
  213104. const String error (initDriver());
  213105. if (error.isNotEmpty())
  213106. {
  213107. log ("ASIOInit: " + error);
  213108. }
  213109. needToReset = false;
  213110. isReSync = false;
  213111. }
  213112. numActiveInputChans = 0;
  213113. numActiveOutputChans = 0;
  213114. ASIOBufferInfo* info = bufferInfos;
  213115. int i;
  213116. for (i = 0; i < totalNumInputChans; ++i)
  213117. {
  213118. if (inputChannels[i])
  213119. {
  213120. currentChansIn.setBit (i);
  213121. info->isInput = 1;
  213122. info->channelNum = i;
  213123. info->buffers[0] = info->buffers[1] = 0;
  213124. ++info;
  213125. ++numActiveInputChans;
  213126. }
  213127. }
  213128. for (i = 0; i < totalNumOutputChans; ++i)
  213129. {
  213130. if (outputChannels[i])
  213131. {
  213132. currentChansOut.setBit (i);
  213133. info->isInput = 0;
  213134. info->channelNum = i;
  213135. info->buffers[0] = info->buffers[1] = 0;
  213136. ++info;
  213137. ++numActiveOutputChans;
  213138. }
  213139. }
  213140. const int totalBuffers = numActiveInputChans + numActiveOutputChans;
  213141. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  213142. if (currentASIODev[0] == this)
  213143. {
  213144. callbacks.bufferSwitch = &bufferSwitchCallback0;
  213145. callbacks.asioMessage = &asioMessagesCallback0;
  213146. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  213147. }
  213148. else if (currentASIODev[1] == this)
  213149. {
  213150. callbacks.bufferSwitch = &bufferSwitchCallback1;
  213151. callbacks.asioMessage = &asioMessagesCallback1;
  213152. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  213153. }
  213154. else if (currentASIODev[2] == this)
  213155. {
  213156. callbacks.bufferSwitch = &bufferSwitchCallback2;
  213157. callbacks.asioMessage = &asioMessagesCallback2;
  213158. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  213159. }
  213160. else
  213161. {
  213162. jassertfalse;
  213163. }
  213164. log ("disposing buffers");
  213165. err = asioObject->disposeBuffers();
  213166. log ("creating buffers: " + String (totalBuffers) + ", " + String (currentBlockSizeSamples));
  213167. err = asioObject->createBuffers (bufferInfos,
  213168. totalBuffers,
  213169. currentBlockSizeSamples,
  213170. &callbacks);
  213171. if (err != 0)
  213172. {
  213173. currentBlockSizeSamples = preferredSize;
  213174. logError ("create buffers 2", err);
  213175. asioObject->disposeBuffers();
  213176. err = asioObject->createBuffers (bufferInfos,
  213177. totalBuffers,
  213178. currentBlockSizeSamples,
  213179. &callbacks);
  213180. }
  213181. if (err == 0)
  213182. {
  213183. buffersCreated = true;
  213184. tempBuffer.calloc (totalBuffers * currentBlockSizeSamples + 32);
  213185. int n = 0;
  213186. Array <int> types;
  213187. currentBitDepth = 16;
  213188. for (i = 0; i < jmin ((int) totalNumInputChans, maxASIOChannels); ++i)
  213189. {
  213190. if (inputChannels[i])
  213191. {
  213192. inBuffers[n] = tempBuffer + (currentBlockSizeSamples * n);
  213193. ASIOChannelInfo channelInfo;
  213194. zerostruct (channelInfo);
  213195. channelInfo.channel = i;
  213196. channelInfo.isInput = 1;
  213197. asioObject->getChannelInfo (&channelInfo);
  213198. types.addIfNotAlreadyThere (channelInfo.type);
  213199. typeToFormatParameters (channelInfo.type,
  213200. inputChannelBitDepths[n],
  213201. inputChannelBytesPerSample[n],
  213202. inputChannelIsFloat[n],
  213203. inputChannelLittleEndian[n]);
  213204. currentBitDepth = jmax (currentBitDepth, inputChannelBitDepths[n]);
  213205. ++n;
  213206. }
  213207. }
  213208. jassert (numActiveInputChans == n);
  213209. n = 0;
  213210. for (i = 0; i < jmin ((int) totalNumOutputChans, maxASIOChannels); ++i)
  213211. {
  213212. if (outputChannels[i])
  213213. {
  213214. outBuffers[n] = tempBuffer + (currentBlockSizeSamples * (numActiveInputChans + n));
  213215. ASIOChannelInfo channelInfo;
  213216. zerostruct (channelInfo);
  213217. channelInfo.channel = i;
  213218. channelInfo.isInput = 0;
  213219. asioObject->getChannelInfo (&channelInfo);
  213220. types.addIfNotAlreadyThere (channelInfo.type);
  213221. typeToFormatParameters (channelInfo.type,
  213222. outputChannelBitDepths[n],
  213223. outputChannelBytesPerSample[n],
  213224. outputChannelIsFloat[n],
  213225. outputChannelLittleEndian[n]);
  213226. currentBitDepth = jmax (currentBitDepth, outputChannelBitDepths[n]);
  213227. ++n;
  213228. }
  213229. }
  213230. jassert (numActiveOutputChans == n);
  213231. for (i = types.size(); --i >= 0;)
  213232. {
  213233. log ("channel format: " + String (types[i]));
  213234. }
  213235. jassert (n <= totalBuffers);
  213236. for (i = 0; i < numActiveOutputChans; ++i)
  213237. {
  213238. const int size = currentBlockSizeSamples * (outputChannelBitDepths[i] >> 3);
  213239. if (bufferInfos [numActiveInputChans + i].buffers[0] == 0
  213240. || bufferInfos [numActiveInputChans + i].buffers[1] == 0)
  213241. {
  213242. log ("!! Null buffers");
  213243. }
  213244. else
  213245. {
  213246. zeromem (bufferInfos[numActiveInputChans + i].buffers[0], size);
  213247. zeromem (bufferInfos[numActiveInputChans + i].buffers[1], size);
  213248. }
  213249. }
  213250. inputLatency = outputLatency = 0;
  213251. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  213252. {
  213253. log ("ASIO - no latencies");
  213254. }
  213255. else
  213256. {
  213257. log ("ASIO latencies: " + String ((int) outputLatency) + ", " + String ((int) inputLatency));
  213258. }
  213259. isOpen_ = true;
  213260. log ("starting ASIO");
  213261. calledback = false;
  213262. err = asioObject->start();
  213263. if (err != 0)
  213264. {
  213265. isOpen_ = false;
  213266. log ("ASIO - stop on failure");
  213267. Thread::sleep (10);
  213268. asioObject->stop();
  213269. error = "Can't start device";
  213270. Thread::sleep (10);
  213271. }
  213272. else
  213273. {
  213274. int count = 300;
  213275. while (--count > 0 && ! calledback)
  213276. Thread::sleep (10);
  213277. isStarted = true;
  213278. if (! calledback)
  213279. {
  213280. error = "Device didn't start correctly";
  213281. log ("ASIO didn't callback - stopping..");
  213282. asioObject->stop();
  213283. }
  213284. }
  213285. }
  213286. else
  213287. {
  213288. error = "Can't create i/o buffers";
  213289. }
  213290. }
  213291. else
  213292. {
  213293. error = "Can't set sample rate: ";
  213294. error << sampleRate;
  213295. }
  213296. if (error.isNotEmpty())
  213297. {
  213298. logError (error, err);
  213299. if (asioObject != 0 && buffersCreated)
  213300. asioObject->disposeBuffers();
  213301. Thread::sleep (20);
  213302. isStarted = false;
  213303. isOpen_ = false;
  213304. const String errorCopy (error);
  213305. close(); // (this resets the error string)
  213306. error = errorCopy;
  213307. }
  213308. needToReset = false;
  213309. isReSync = false;
  213310. return error;
  213311. }
  213312. void close()
  213313. {
  213314. error = String::empty;
  213315. stopTimer();
  213316. stop();
  213317. if (isASIOOpen && isOpen_)
  213318. {
  213319. const ScopedLock sl (callbackLock);
  213320. isOpen_ = false;
  213321. isStarted = false;
  213322. needToReset = false;
  213323. isReSync = false;
  213324. log ("ASIO - stopping");
  213325. if (asioObject != 0)
  213326. {
  213327. Thread::sleep (20);
  213328. asioObject->stop();
  213329. Thread::sleep (10);
  213330. asioObject->disposeBuffers();
  213331. }
  213332. Thread::sleep (10);
  213333. }
  213334. }
  213335. bool isOpen() { return isOpen_ || insideControlPanelModalLoop; }
  213336. bool isPlaying() { return isASIOOpen && (currentCallback != 0); }
  213337. int getCurrentBufferSizeSamples() { return currentBlockSizeSamples; }
  213338. double getCurrentSampleRate() { return currentSampleRate; }
  213339. int getCurrentBitDepth() { return currentBitDepth; }
  213340. const BigInteger getActiveOutputChannels() const { return currentChansOut; }
  213341. const BigInteger getActiveInputChannels() const { return currentChansIn; }
  213342. int getOutputLatencyInSamples() { return outputLatency + currentBlockSizeSamples / 4; }
  213343. int getInputLatencyInSamples() { return inputLatency + currentBlockSizeSamples / 4; }
  213344. void start (AudioIODeviceCallback* callback)
  213345. {
  213346. if (callback != 0)
  213347. {
  213348. callback->audioDeviceAboutToStart (this);
  213349. const ScopedLock sl (callbackLock);
  213350. currentCallback = callback;
  213351. }
  213352. }
  213353. void stop()
  213354. {
  213355. AudioIODeviceCallback* const lastCallback = currentCallback;
  213356. {
  213357. const ScopedLock sl (callbackLock);
  213358. currentCallback = 0;
  213359. }
  213360. if (lastCallback != 0)
  213361. lastCallback->audioDeviceStopped();
  213362. }
  213363. const String getLastError() { return error; }
  213364. bool hasControlPanel() const { return true; }
  213365. bool showControlPanel()
  213366. {
  213367. log ("ASIO - showing control panel");
  213368. Component modalWindow (String::empty);
  213369. modalWindow.setOpaque (true);
  213370. modalWindow.addToDesktop (0);
  213371. modalWindow.enterModalState();
  213372. bool done = false;
  213373. JUCE_TRY
  213374. {
  213375. // are there are devices that need to be closed before showing their control panel?
  213376. // close();
  213377. insideControlPanelModalLoop = true;
  213378. const uint32 started = Time::getMillisecondCounter();
  213379. if (asioObject != 0)
  213380. {
  213381. asioObject->controlPanel();
  213382. const int spent = (int) Time::getMillisecondCounter() - (int) started;
  213383. log ("spent: " + String (spent));
  213384. if (spent > 300)
  213385. {
  213386. shouldUsePreferredSize = true;
  213387. done = true;
  213388. }
  213389. }
  213390. }
  213391. JUCE_CATCH_ALL
  213392. insideControlPanelModalLoop = false;
  213393. return done;
  213394. }
  213395. void resetRequest() throw()
  213396. {
  213397. needToReset = true;
  213398. }
  213399. void resyncRequest() throw()
  213400. {
  213401. needToReset = true;
  213402. isReSync = true;
  213403. }
  213404. void timerCallback()
  213405. {
  213406. if (! insideControlPanelModalLoop)
  213407. {
  213408. stopTimer();
  213409. // used to cause a reset
  213410. log ("! ASIO restart request!");
  213411. if (isOpen_)
  213412. {
  213413. AudioIODeviceCallback* const oldCallback = currentCallback;
  213414. close();
  213415. open (BigInteger (currentChansIn), BigInteger (currentChansOut),
  213416. currentSampleRate, currentBlockSizeSamples);
  213417. if (oldCallback != 0)
  213418. start (oldCallback);
  213419. }
  213420. }
  213421. else
  213422. {
  213423. startTimer (100);
  213424. }
  213425. }
  213426. juce_UseDebuggingNewOperator
  213427. private:
  213428. IASIO* volatile asioObject;
  213429. ASIOCallbacks callbacks;
  213430. void* windowHandle;
  213431. CLSID classId;
  213432. const String optionalDllForDirectLoading;
  213433. String error;
  213434. long totalNumInputChans, totalNumOutputChans;
  213435. StringArray inputChannelNames, outputChannelNames;
  213436. Array<int> sampleRates, bufferSizes;
  213437. long inputLatency, outputLatency;
  213438. long minSize, maxSize, preferredSize, granularity;
  213439. int volatile currentBlockSizeSamples;
  213440. int volatile currentBitDepth;
  213441. double volatile currentSampleRate;
  213442. BigInteger currentChansOut, currentChansIn;
  213443. AudioIODeviceCallback* volatile currentCallback;
  213444. CriticalSection callbackLock;
  213445. ASIOBufferInfo bufferInfos [maxASIOChannels];
  213446. float* inBuffers [maxASIOChannels];
  213447. float* outBuffers [maxASIOChannels];
  213448. int inputChannelBitDepths [maxASIOChannels];
  213449. int outputChannelBitDepths [maxASIOChannels];
  213450. int inputChannelBytesPerSample [maxASIOChannels];
  213451. int outputChannelBytesPerSample [maxASIOChannels];
  213452. bool inputChannelIsFloat [maxASIOChannels];
  213453. bool outputChannelIsFloat [maxASIOChannels];
  213454. bool inputChannelLittleEndian [maxASIOChannels];
  213455. bool outputChannelLittleEndian [maxASIOChannels];
  213456. WaitableEvent event1;
  213457. HeapBlock <float> tempBuffer;
  213458. int volatile bufferIndex, numActiveInputChans, numActiveOutputChans;
  213459. bool isOpen_, isStarted;
  213460. bool volatile isASIOOpen;
  213461. bool volatile calledback;
  213462. bool volatile littleEndian, postOutput, needToReset, isReSync;
  213463. bool volatile insideControlPanelModalLoop;
  213464. bool volatile shouldUsePreferredSize;
  213465. void removeCurrentDriver()
  213466. {
  213467. if (asioObject != 0)
  213468. {
  213469. asioObject->Release();
  213470. asioObject = 0;
  213471. }
  213472. }
  213473. bool loadDriver()
  213474. {
  213475. removeCurrentDriver();
  213476. JUCE_TRY
  213477. {
  213478. if (CoCreateInstance (classId, 0, CLSCTX_INPROC_SERVER,
  213479. classId, (void**) &asioObject) == S_OK)
  213480. {
  213481. return true;
  213482. }
  213483. // If a class isn't registered but we have a path for it, we can fallback to
  213484. // doing a direct load of the COM object (only available via the juce_createASIOAudioIODeviceForGUID function).
  213485. if (optionalDllForDirectLoading.isNotEmpty())
  213486. {
  213487. HMODULE h = LoadLibrary (optionalDllForDirectLoading);
  213488. if (h != 0)
  213489. {
  213490. typedef HRESULT (CALLBACK* DllGetClassObjectFunc) (REFCLSID clsid, REFIID iid, LPVOID* ppv);
  213491. DllGetClassObjectFunc dllGetClassObject = (DllGetClassObjectFunc) GetProcAddress (h, "DllGetClassObject");
  213492. if (dllGetClassObject != 0)
  213493. {
  213494. IClassFactory* classFactory = 0;
  213495. HRESULT hr = dllGetClassObject (classId, IID_IClassFactory, (void**) &classFactory);
  213496. if (classFactory != 0)
  213497. {
  213498. hr = classFactory->CreateInstance (0, classId, (void**) &asioObject);
  213499. classFactory->Release();
  213500. }
  213501. return asioObject != 0;
  213502. }
  213503. }
  213504. }
  213505. }
  213506. JUCE_CATCH_ALL
  213507. asioObject = 0;
  213508. return false;
  213509. }
  213510. const String initDriver()
  213511. {
  213512. if (asioObject != 0)
  213513. {
  213514. char buffer [256];
  213515. zeromem (buffer, sizeof (buffer));
  213516. if (! asioObject->init (windowHandle))
  213517. {
  213518. asioObject->getErrorMessage (buffer);
  213519. return String (buffer, sizeof (buffer) - 1);
  213520. }
  213521. // just in case any daft drivers expect this to be called..
  213522. asioObject->getDriverName (buffer);
  213523. return String::empty;
  213524. }
  213525. return "No Driver";
  213526. }
  213527. const String openDevice()
  213528. {
  213529. // use this in case the driver starts opening dialog boxes..
  213530. Component modalWindow (String::empty);
  213531. modalWindow.setOpaque (true);
  213532. modalWindow.addToDesktop (0);
  213533. modalWindow.enterModalState();
  213534. // open the device and get its info..
  213535. log ("opening ASIO device: " + getName());
  213536. needToReset = false;
  213537. isReSync = false;
  213538. outputChannelNames.clear();
  213539. inputChannelNames.clear();
  213540. bufferSizes.clear();
  213541. sampleRates.clear();
  213542. isASIOOpen = false;
  213543. isOpen_ = false;
  213544. totalNumInputChans = 0;
  213545. totalNumOutputChans = 0;
  213546. numActiveInputChans = 0;
  213547. numActiveOutputChans = 0;
  213548. currentCallback = 0;
  213549. error = String::empty;
  213550. if (getName().isEmpty())
  213551. return error;
  213552. long err = 0;
  213553. if (loadDriver())
  213554. {
  213555. if ((error = initDriver()).isEmpty())
  213556. {
  213557. numActiveInputChans = 0;
  213558. numActiveOutputChans = 0;
  213559. totalNumInputChans = 0;
  213560. totalNumOutputChans = 0;
  213561. if (asioObject != 0
  213562. && (err = asioObject->getChannels (&totalNumInputChans, &totalNumOutputChans)) == 0)
  213563. {
  213564. log (String ((int) totalNumInputChans) + " in, " + String ((int) totalNumOutputChans) + " out");
  213565. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  213566. {
  213567. // find a list of buffer sizes..
  213568. log (String ((int) minSize) + " " + String ((int) maxSize) + " " + String ((int) preferredSize) + " " + String ((int) granularity));
  213569. if (granularity >= 0)
  213570. {
  213571. granularity = jmax (1, (int) granularity);
  213572. for (int i = jmax ((int) minSize, (int) granularity); i < jmin (6400, (int) maxSize); i += granularity)
  213573. bufferSizes.addIfNotAlreadyThere (granularity * (i / granularity));
  213574. }
  213575. else if (granularity < 0)
  213576. {
  213577. for (int i = 0; i < 18; ++i)
  213578. {
  213579. const int s = (1 << i);
  213580. if (s >= minSize && s <= maxSize)
  213581. bufferSizes.add (s);
  213582. }
  213583. }
  213584. if (! bufferSizes.contains (preferredSize))
  213585. bufferSizes.insert (0, preferredSize);
  213586. double currentRate = 0;
  213587. asioObject->getSampleRate (&currentRate);
  213588. if (currentRate <= 0.0 || currentRate > 192001.0)
  213589. {
  213590. log ("setting sample rate");
  213591. err = asioObject->setSampleRate (44100.0);
  213592. if (err != 0)
  213593. {
  213594. logError ("setting sample rate", err);
  213595. }
  213596. asioObject->getSampleRate (&currentRate);
  213597. }
  213598. currentSampleRate = currentRate;
  213599. postOutput = (asioObject->outputReady() == 0);
  213600. if (postOutput)
  213601. {
  213602. log ("ASIO outputReady = ok");
  213603. }
  213604. updateSampleRates();
  213605. // ..because cubase does it at this point
  213606. inputLatency = outputLatency = 0;
  213607. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  213608. {
  213609. log ("ASIO - no latencies");
  213610. }
  213611. log ("latencies: " + String ((int) inputLatency) + ", " + String ((int) outputLatency));
  213612. // create some dummy buffers now.. because cubase does..
  213613. numActiveInputChans = 0;
  213614. numActiveOutputChans = 0;
  213615. ASIOBufferInfo* info = bufferInfos;
  213616. int i, numChans = 0;
  213617. for (i = 0; i < jmin (2, (int) totalNumInputChans); ++i)
  213618. {
  213619. info->isInput = 1;
  213620. info->channelNum = i;
  213621. info->buffers[0] = info->buffers[1] = 0;
  213622. ++info;
  213623. ++numChans;
  213624. }
  213625. const int outputBufferIndex = numChans;
  213626. for (i = 0; i < jmin (2, (int) totalNumOutputChans); ++i)
  213627. {
  213628. info->isInput = 0;
  213629. info->channelNum = i;
  213630. info->buffers[0] = info->buffers[1] = 0;
  213631. ++info;
  213632. ++numChans;
  213633. }
  213634. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  213635. if (currentASIODev[0] == this)
  213636. {
  213637. callbacks.bufferSwitch = &bufferSwitchCallback0;
  213638. callbacks.asioMessage = &asioMessagesCallback0;
  213639. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  213640. }
  213641. else if (currentASIODev[1] == this)
  213642. {
  213643. callbacks.bufferSwitch = &bufferSwitchCallback1;
  213644. callbacks.asioMessage = &asioMessagesCallback1;
  213645. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  213646. }
  213647. else if (currentASIODev[2] == this)
  213648. {
  213649. callbacks.bufferSwitch = &bufferSwitchCallback2;
  213650. callbacks.asioMessage = &asioMessagesCallback2;
  213651. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  213652. }
  213653. else
  213654. {
  213655. jassertfalse;
  213656. }
  213657. log ("creating buffers (dummy): " + String (numChans) + ", " + String ((int) preferredSize));
  213658. if (preferredSize > 0)
  213659. {
  213660. err = asioObject->createBuffers (bufferInfos, numChans, preferredSize, &callbacks);
  213661. if (err != 0)
  213662. {
  213663. logError ("dummy buffers", err);
  213664. }
  213665. }
  213666. long newInps = 0, newOuts = 0;
  213667. asioObject->getChannels (&newInps, &newOuts);
  213668. if (totalNumInputChans != newInps || totalNumOutputChans != newOuts)
  213669. {
  213670. totalNumInputChans = newInps;
  213671. totalNumOutputChans = newOuts;
  213672. log (String ((int) totalNumInputChans) + " in; " + String ((int) totalNumOutputChans) + " out");
  213673. }
  213674. updateSampleRates();
  213675. ASIOChannelInfo channelInfo;
  213676. channelInfo.type = 0;
  213677. for (i = 0; i < totalNumInputChans; ++i)
  213678. {
  213679. zerostruct (channelInfo);
  213680. channelInfo.channel = i;
  213681. channelInfo.isInput = 1;
  213682. asioObject->getChannelInfo (&channelInfo);
  213683. inputChannelNames.add (String (channelInfo.name));
  213684. }
  213685. for (i = 0; i < totalNumOutputChans; ++i)
  213686. {
  213687. zerostruct (channelInfo);
  213688. channelInfo.channel = i;
  213689. channelInfo.isInput = 0;
  213690. asioObject->getChannelInfo (&channelInfo);
  213691. outputChannelNames.add (String (channelInfo.name));
  213692. typeToFormatParameters (channelInfo.type,
  213693. outputChannelBitDepths[i],
  213694. outputChannelBytesPerSample[i],
  213695. outputChannelIsFloat[i],
  213696. outputChannelLittleEndian[i]);
  213697. if (i < 2)
  213698. {
  213699. // clear the channels that are used with the dummy stuff
  213700. const int bytesPerBuffer = preferredSize * (outputChannelBitDepths[i] >> 3);
  213701. zeromem (bufferInfos [outputBufferIndex + i].buffers[0], bytesPerBuffer);
  213702. zeromem (bufferInfos [outputBufferIndex + i].buffers[1], bytesPerBuffer);
  213703. }
  213704. }
  213705. outputChannelNames.trim();
  213706. inputChannelNames.trim();
  213707. outputChannelNames.appendNumbersToDuplicates (false, true);
  213708. inputChannelNames.appendNumbersToDuplicates (false, true);
  213709. // start and stop because cubase does it..
  213710. asioObject->getLatencies (&inputLatency, &outputLatency);
  213711. if ((err = asioObject->start()) != 0)
  213712. {
  213713. // ignore an error here, as it might start later after setting other stuff up
  213714. logError ("ASIO start", err);
  213715. }
  213716. Thread::sleep (100);
  213717. asioObject->stop();
  213718. }
  213719. else
  213720. {
  213721. error = "Can't detect buffer sizes";
  213722. }
  213723. }
  213724. else
  213725. {
  213726. error = "Can't detect asio channels";
  213727. }
  213728. }
  213729. }
  213730. else
  213731. {
  213732. error = "No such device";
  213733. }
  213734. if (error.isNotEmpty())
  213735. {
  213736. logError (error, err);
  213737. if (asioObject != 0)
  213738. asioObject->disposeBuffers();
  213739. removeCurrentDriver();
  213740. isASIOOpen = false;
  213741. }
  213742. else
  213743. {
  213744. isASIOOpen = true;
  213745. log ("ASIO device open");
  213746. }
  213747. isOpen_ = false;
  213748. needToReset = false;
  213749. isReSync = false;
  213750. return error;
  213751. }
  213752. void JUCE_ASIOCALLBACK callback (const long index)
  213753. {
  213754. if (isStarted)
  213755. {
  213756. bufferIndex = index;
  213757. processBuffer();
  213758. }
  213759. else
  213760. {
  213761. if (postOutput && (asioObject != 0))
  213762. asioObject->outputReady();
  213763. }
  213764. calledback = true;
  213765. }
  213766. void processBuffer()
  213767. {
  213768. const ASIOBufferInfo* const infos = bufferInfos;
  213769. const int bi = bufferIndex;
  213770. const ScopedLock sl (callbackLock);
  213771. if (needToReset)
  213772. {
  213773. needToReset = false;
  213774. if (isReSync)
  213775. {
  213776. log ("! ASIO resync");
  213777. isReSync = false;
  213778. }
  213779. else
  213780. {
  213781. startTimer (20);
  213782. }
  213783. }
  213784. if (bi >= 0)
  213785. {
  213786. const int samps = currentBlockSizeSamples;
  213787. if (currentCallback != 0)
  213788. {
  213789. int i;
  213790. for (i = 0; i < numActiveInputChans; ++i)
  213791. {
  213792. float* const dst = inBuffers[i];
  213793. jassert (dst != 0);
  213794. const char* const src = (const char*) (infos[i].buffers[bi]);
  213795. if (inputChannelIsFloat[i])
  213796. {
  213797. memcpy (dst, src, samps * sizeof (float));
  213798. }
  213799. else
  213800. {
  213801. jassert (dst == tempBuffer + (samps * i));
  213802. switch (inputChannelBitDepths[i])
  213803. {
  213804. case 16:
  213805. convertInt16ToFloat (src, dst, inputChannelBytesPerSample[i],
  213806. samps, inputChannelLittleEndian[i]);
  213807. break;
  213808. case 24:
  213809. convertInt24ToFloat (src, dst, inputChannelBytesPerSample[i],
  213810. samps, inputChannelLittleEndian[i]);
  213811. break;
  213812. case 32:
  213813. convertInt32ToFloat (src, dst, inputChannelBytesPerSample[i],
  213814. samps, inputChannelLittleEndian[i]);
  213815. break;
  213816. case 64:
  213817. jassertfalse;
  213818. break;
  213819. }
  213820. }
  213821. }
  213822. currentCallback->audioDeviceIOCallback ((const float**) inBuffers, numActiveInputChans,
  213823. outBuffers, numActiveOutputChans, samps);
  213824. for (i = 0; i < numActiveOutputChans; ++i)
  213825. {
  213826. float* const src = outBuffers[i];
  213827. jassert (src != 0);
  213828. char* const dst = (char*) (infos [numActiveInputChans + i].buffers[bi]);
  213829. if (outputChannelIsFloat[i])
  213830. {
  213831. memcpy (dst, src, samps * sizeof (float));
  213832. }
  213833. else
  213834. {
  213835. jassert (src == tempBuffer + (samps * (numActiveInputChans + i)));
  213836. switch (outputChannelBitDepths[i])
  213837. {
  213838. case 16:
  213839. convertFloatToInt16 (src, dst, outputChannelBytesPerSample[i],
  213840. samps, outputChannelLittleEndian[i]);
  213841. break;
  213842. case 24:
  213843. convertFloatToInt24 (src, dst, outputChannelBytesPerSample[i],
  213844. samps, outputChannelLittleEndian[i]);
  213845. break;
  213846. case 32:
  213847. convertFloatToInt32 (src, dst, outputChannelBytesPerSample[i],
  213848. samps, outputChannelLittleEndian[i]);
  213849. break;
  213850. case 64:
  213851. jassertfalse;
  213852. break;
  213853. }
  213854. }
  213855. }
  213856. }
  213857. else
  213858. {
  213859. for (int i = 0; i < numActiveOutputChans; ++i)
  213860. {
  213861. const int bytesPerBuffer = samps * (outputChannelBitDepths[i] >> 3);
  213862. zeromem (infos[numActiveInputChans + i].buffers[bi], bytesPerBuffer);
  213863. }
  213864. }
  213865. }
  213866. if (postOutput)
  213867. asioObject->outputReady();
  213868. }
  213869. static ASIOTime* JUCE_ASIOCALLBACK bufferSwitchTimeInfoCallback0 (ASIOTime*, long index, long)
  213870. {
  213871. if (currentASIODev[0] != 0)
  213872. currentASIODev[0]->callback (index);
  213873. return 0;
  213874. }
  213875. static ASIOTime* JUCE_ASIOCALLBACK bufferSwitchTimeInfoCallback1 (ASIOTime*, long index, long)
  213876. {
  213877. if (currentASIODev[1] != 0)
  213878. currentASIODev[1]->callback (index);
  213879. return 0;
  213880. }
  213881. static ASIOTime* JUCE_ASIOCALLBACK bufferSwitchTimeInfoCallback2 (ASIOTime*, long index, long)
  213882. {
  213883. if (currentASIODev[2] != 0)
  213884. currentASIODev[2]->callback (index);
  213885. return 0;
  213886. }
  213887. static void JUCE_ASIOCALLBACK bufferSwitchCallback0 (long index, long)
  213888. {
  213889. if (currentASIODev[0] != 0)
  213890. currentASIODev[0]->callback (index);
  213891. }
  213892. static void JUCE_ASIOCALLBACK bufferSwitchCallback1 (long index, long)
  213893. {
  213894. if (currentASIODev[1] != 0)
  213895. currentASIODev[1]->callback (index);
  213896. }
  213897. static void JUCE_ASIOCALLBACK bufferSwitchCallback2 (long index, long)
  213898. {
  213899. if (currentASIODev[2] != 0)
  213900. currentASIODev[2]->callback (index);
  213901. }
  213902. static long JUCE_ASIOCALLBACK asioMessagesCallback0 (long selector, long value, void*, double*)
  213903. {
  213904. return asioMessagesCallback (selector, value, 0);
  213905. }
  213906. static long JUCE_ASIOCALLBACK asioMessagesCallback1 (long selector, long value, void*, double*)
  213907. {
  213908. return asioMessagesCallback (selector, value, 1);
  213909. }
  213910. static long JUCE_ASIOCALLBACK asioMessagesCallback2 (long selector, long value, void*, double*)
  213911. {
  213912. return asioMessagesCallback (selector, value, 2);
  213913. }
  213914. static long JUCE_ASIOCALLBACK asioMessagesCallback (long selector, long value, const int deviceIndex)
  213915. {
  213916. switch (selector)
  213917. {
  213918. case kAsioSelectorSupported:
  213919. if (value == kAsioResetRequest
  213920. || value == kAsioEngineVersion
  213921. || value == kAsioResyncRequest
  213922. || value == kAsioLatenciesChanged
  213923. || value == kAsioSupportsInputMonitor)
  213924. return 1;
  213925. break;
  213926. case kAsioBufferSizeChange:
  213927. break;
  213928. case kAsioResetRequest:
  213929. if (currentASIODev[deviceIndex] != 0)
  213930. currentASIODev[deviceIndex]->resetRequest();
  213931. return 1;
  213932. case kAsioResyncRequest:
  213933. if (currentASIODev[deviceIndex] != 0)
  213934. currentASIODev[deviceIndex]->resyncRequest();
  213935. return 1;
  213936. case kAsioLatenciesChanged:
  213937. return 1;
  213938. case kAsioEngineVersion:
  213939. return 2;
  213940. case kAsioSupportsTimeInfo:
  213941. case kAsioSupportsTimeCode:
  213942. return 0;
  213943. }
  213944. return 0;
  213945. }
  213946. static void JUCE_ASIOCALLBACK sampleRateChangedCallback (ASIOSampleRate)
  213947. {
  213948. }
  213949. static void convertInt16ToFloat (const char* src,
  213950. float* dest,
  213951. const int srcStrideBytes,
  213952. int numSamples,
  213953. const bool littleEndian) throw()
  213954. {
  213955. const double g = 1.0 / 32768.0;
  213956. if (littleEndian)
  213957. {
  213958. while (--numSamples >= 0)
  213959. {
  213960. *dest++ = (float) (g * (short) ByteOrder::littleEndianShort (src));
  213961. src += srcStrideBytes;
  213962. }
  213963. }
  213964. else
  213965. {
  213966. while (--numSamples >= 0)
  213967. {
  213968. *dest++ = (float) (g * (short) ByteOrder::bigEndianShort (src));
  213969. src += srcStrideBytes;
  213970. }
  213971. }
  213972. }
  213973. static void convertFloatToInt16 (const float* src,
  213974. char* dest,
  213975. const int dstStrideBytes,
  213976. int numSamples,
  213977. const bool littleEndian) throw()
  213978. {
  213979. const double maxVal = (double) 0x7fff;
  213980. if (littleEndian)
  213981. {
  213982. while (--numSamples >= 0)
  213983. {
  213984. *(uint16*) dest = ByteOrder::swapIfBigEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  213985. dest += dstStrideBytes;
  213986. }
  213987. }
  213988. else
  213989. {
  213990. while (--numSamples >= 0)
  213991. {
  213992. *(uint16*) dest = ByteOrder::swapIfLittleEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  213993. dest += dstStrideBytes;
  213994. }
  213995. }
  213996. }
  213997. static void convertInt24ToFloat (const char* src,
  213998. float* dest,
  213999. const int srcStrideBytes,
  214000. int numSamples,
  214001. const bool littleEndian) throw()
  214002. {
  214003. const double g = 1.0 / 0x7fffff;
  214004. if (littleEndian)
  214005. {
  214006. while (--numSamples >= 0)
  214007. {
  214008. *dest++ = (float) (g * ByteOrder::littleEndian24Bit (src));
  214009. src += srcStrideBytes;
  214010. }
  214011. }
  214012. else
  214013. {
  214014. while (--numSamples >= 0)
  214015. {
  214016. *dest++ = (float) (g * ByteOrder::bigEndian24Bit (src));
  214017. src += srcStrideBytes;
  214018. }
  214019. }
  214020. }
  214021. static void convertFloatToInt24 (const float* src,
  214022. char* dest,
  214023. const int dstStrideBytes,
  214024. int numSamples,
  214025. const bool littleEndian) throw()
  214026. {
  214027. const double maxVal = (double) 0x7fffff;
  214028. if (littleEndian)
  214029. {
  214030. while (--numSamples >= 0)
  214031. {
  214032. ByteOrder::littleEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  214033. dest += dstStrideBytes;
  214034. }
  214035. }
  214036. else
  214037. {
  214038. while (--numSamples >= 0)
  214039. {
  214040. ByteOrder::bigEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  214041. dest += dstStrideBytes;
  214042. }
  214043. }
  214044. }
  214045. static void convertInt32ToFloat (const char* src,
  214046. float* dest,
  214047. const int srcStrideBytes,
  214048. int numSamples,
  214049. const bool littleEndian) throw()
  214050. {
  214051. const double g = 1.0 / 0x7fffffff;
  214052. if (littleEndian)
  214053. {
  214054. while (--numSamples >= 0)
  214055. {
  214056. *dest++ = (float) (g * (int) ByteOrder::littleEndianInt (src));
  214057. src += srcStrideBytes;
  214058. }
  214059. }
  214060. else
  214061. {
  214062. while (--numSamples >= 0)
  214063. {
  214064. *dest++ = (float) (g * (int) ByteOrder::bigEndianInt (src));
  214065. src += srcStrideBytes;
  214066. }
  214067. }
  214068. }
  214069. static void convertFloatToInt32 (const float* src,
  214070. char* dest,
  214071. const int dstStrideBytes,
  214072. int numSamples,
  214073. const bool littleEndian) throw()
  214074. {
  214075. const double maxVal = (double) 0x7fffffff;
  214076. if (littleEndian)
  214077. {
  214078. while (--numSamples >= 0)
  214079. {
  214080. *(uint32*) dest = ByteOrder::swapIfBigEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  214081. dest += dstStrideBytes;
  214082. }
  214083. }
  214084. else
  214085. {
  214086. while (--numSamples >= 0)
  214087. {
  214088. *(uint32*) dest = ByteOrder::swapIfLittleEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  214089. dest += dstStrideBytes;
  214090. }
  214091. }
  214092. }
  214093. static void typeToFormatParameters (const long type,
  214094. int& bitDepth,
  214095. int& byteStride,
  214096. bool& formatIsFloat,
  214097. bool& littleEndian) throw()
  214098. {
  214099. bitDepth = 0;
  214100. littleEndian = false;
  214101. formatIsFloat = false;
  214102. switch (type)
  214103. {
  214104. case ASIOSTInt16MSB:
  214105. case ASIOSTInt16LSB:
  214106. case ASIOSTInt32MSB16:
  214107. case ASIOSTInt32LSB16:
  214108. bitDepth = 16; break;
  214109. case ASIOSTFloat32MSB:
  214110. case ASIOSTFloat32LSB:
  214111. formatIsFloat = true;
  214112. bitDepth = 32; break;
  214113. case ASIOSTInt32MSB:
  214114. case ASIOSTInt32LSB:
  214115. bitDepth = 32; break;
  214116. case ASIOSTInt24MSB:
  214117. case ASIOSTInt24LSB:
  214118. case ASIOSTInt32MSB24:
  214119. case ASIOSTInt32LSB24:
  214120. case ASIOSTInt32MSB18:
  214121. case ASIOSTInt32MSB20:
  214122. case ASIOSTInt32LSB18:
  214123. case ASIOSTInt32LSB20:
  214124. bitDepth = 24; break;
  214125. case ASIOSTFloat64MSB:
  214126. case ASIOSTFloat64LSB:
  214127. default:
  214128. bitDepth = 64;
  214129. break;
  214130. }
  214131. switch (type)
  214132. {
  214133. case ASIOSTInt16MSB:
  214134. case ASIOSTInt32MSB16:
  214135. case ASIOSTFloat32MSB:
  214136. case ASIOSTFloat64MSB:
  214137. case ASIOSTInt32MSB:
  214138. case ASIOSTInt32MSB18:
  214139. case ASIOSTInt32MSB20:
  214140. case ASIOSTInt32MSB24:
  214141. case ASIOSTInt24MSB:
  214142. littleEndian = false; break;
  214143. case ASIOSTInt16LSB:
  214144. case ASIOSTInt32LSB16:
  214145. case ASIOSTFloat32LSB:
  214146. case ASIOSTFloat64LSB:
  214147. case ASIOSTInt32LSB:
  214148. case ASIOSTInt32LSB18:
  214149. case ASIOSTInt32LSB20:
  214150. case ASIOSTInt32LSB24:
  214151. case ASIOSTInt24LSB:
  214152. littleEndian = true; break;
  214153. default:
  214154. break;
  214155. }
  214156. switch (type)
  214157. {
  214158. case ASIOSTInt16LSB:
  214159. case ASIOSTInt16MSB:
  214160. byteStride = 2; break;
  214161. case ASIOSTInt24LSB:
  214162. case ASIOSTInt24MSB:
  214163. byteStride = 3; break;
  214164. case ASIOSTInt32MSB16:
  214165. case ASIOSTInt32LSB16:
  214166. case ASIOSTInt32MSB:
  214167. case ASIOSTInt32MSB18:
  214168. case ASIOSTInt32MSB20:
  214169. case ASIOSTInt32MSB24:
  214170. case ASIOSTInt32LSB:
  214171. case ASIOSTInt32LSB18:
  214172. case ASIOSTInt32LSB20:
  214173. case ASIOSTInt32LSB24:
  214174. case ASIOSTFloat32LSB:
  214175. case ASIOSTFloat32MSB:
  214176. byteStride = 4; break;
  214177. case ASIOSTFloat64MSB:
  214178. case ASIOSTFloat64LSB:
  214179. byteStride = 8; break;
  214180. default:
  214181. break;
  214182. }
  214183. }
  214184. };
  214185. class ASIOAudioIODeviceType : public AudioIODeviceType
  214186. {
  214187. public:
  214188. ASIOAudioIODeviceType()
  214189. : AudioIODeviceType ("ASIO"),
  214190. hasScanned (false)
  214191. {
  214192. CoInitialize (0);
  214193. }
  214194. ~ASIOAudioIODeviceType()
  214195. {
  214196. }
  214197. void scanForDevices()
  214198. {
  214199. hasScanned = true;
  214200. deviceNames.clear();
  214201. classIds.clear();
  214202. HKEY hk = 0;
  214203. int index = 0;
  214204. if (RegOpenKeyA (HKEY_LOCAL_MACHINE, "software\\asio", &hk) == ERROR_SUCCESS)
  214205. {
  214206. for (;;)
  214207. {
  214208. char name [256];
  214209. if (RegEnumKeyA (hk, index++, name, 256) == ERROR_SUCCESS)
  214210. {
  214211. addDriverInfo (name, hk);
  214212. }
  214213. else
  214214. {
  214215. break;
  214216. }
  214217. }
  214218. RegCloseKey (hk);
  214219. }
  214220. }
  214221. const StringArray getDeviceNames (bool /*wantInputNames*/) const
  214222. {
  214223. jassert (hasScanned); // need to call scanForDevices() before doing this
  214224. return deviceNames;
  214225. }
  214226. int getDefaultDeviceIndex (bool) const
  214227. {
  214228. jassert (hasScanned); // need to call scanForDevices() before doing this
  214229. for (int i = deviceNames.size(); --i >= 0;)
  214230. if (deviceNames[i].containsIgnoreCase ("asio4all"))
  214231. return i; // asio4all is a safe choice for a default..
  214232. #if JUCE_DEBUG
  214233. if (deviceNames.size() > 1 && deviceNames[0].containsIgnoreCase ("digidesign"))
  214234. return 1; // (the digi m-box driver crashes the app when you run
  214235. // it in the debugger, which can be a bit annoying)
  214236. #endif
  214237. return 0;
  214238. }
  214239. static int findFreeSlot()
  214240. {
  214241. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  214242. if (currentASIODev[i] == 0)
  214243. return i;
  214244. jassertfalse; // unfortunately you can only have a finite number
  214245. // of ASIO devices open at the same time..
  214246. return -1;
  214247. }
  214248. int getIndexOfDevice (AudioIODevice* d, bool /*asInput*/) const
  214249. {
  214250. jassert (hasScanned); // need to call scanForDevices() before doing this
  214251. return d == 0 ? -1 : deviceNames.indexOf (d->getName());
  214252. }
  214253. bool hasSeparateInputsAndOutputs() const { return false; }
  214254. AudioIODevice* createDevice (const String& outputDeviceName,
  214255. const String& inputDeviceName)
  214256. {
  214257. // ASIO can't open two different devices for input and output - they must be the same one.
  214258. jassert (inputDeviceName == outputDeviceName || outputDeviceName.isEmpty() || inputDeviceName.isEmpty());
  214259. jassert (hasScanned); // need to call scanForDevices() before doing this
  214260. const int index = deviceNames.indexOf (outputDeviceName.isNotEmpty() ? outputDeviceName
  214261. : inputDeviceName);
  214262. if (index >= 0)
  214263. {
  214264. const int freeSlot = findFreeSlot();
  214265. if (freeSlot >= 0)
  214266. return new ASIOAudioIODevice (outputDeviceName, *(classIds [index]), freeSlot, String::empty);
  214267. }
  214268. return 0;
  214269. }
  214270. juce_UseDebuggingNewOperator
  214271. private:
  214272. StringArray deviceNames;
  214273. OwnedArray <CLSID> classIds;
  214274. bool hasScanned;
  214275. static bool checkClassIsOk (const String& classId)
  214276. {
  214277. HKEY hk = 0;
  214278. bool ok = false;
  214279. if (RegOpenKey (HKEY_CLASSES_ROOT, _T("clsid"), &hk) == ERROR_SUCCESS)
  214280. {
  214281. int index = 0;
  214282. for (;;)
  214283. {
  214284. WCHAR buf [512];
  214285. if (RegEnumKey (hk, index++, buf, 512) == ERROR_SUCCESS)
  214286. {
  214287. if (classId.equalsIgnoreCase (buf))
  214288. {
  214289. HKEY subKey, pathKey;
  214290. if (RegOpenKeyEx (hk, buf, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  214291. {
  214292. if (RegOpenKeyEx (subKey, _T("InprocServer32"), 0, KEY_READ, &pathKey) == ERROR_SUCCESS)
  214293. {
  214294. WCHAR pathName [1024];
  214295. DWORD dtype = REG_SZ;
  214296. DWORD dsize = sizeof (pathName);
  214297. if (RegQueryValueEx (pathKey, 0, 0, &dtype, (LPBYTE) pathName, &dsize) == ERROR_SUCCESS)
  214298. ok = File (pathName).exists();
  214299. RegCloseKey (pathKey);
  214300. }
  214301. RegCloseKey (subKey);
  214302. }
  214303. break;
  214304. }
  214305. }
  214306. else
  214307. {
  214308. break;
  214309. }
  214310. }
  214311. RegCloseKey (hk);
  214312. }
  214313. return ok;
  214314. }
  214315. void addDriverInfo (const String& keyName, HKEY hk)
  214316. {
  214317. HKEY subKey;
  214318. if (RegOpenKeyEx (hk, keyName, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  214319. {
  214320. WCHAR buf [256];
  214321. zerostruct (buf);
  214322. DWORD dtype = REG_SZ;
  214323. DWORD dsize = sizeof (buf);
  214324. if (RegQueryValueEx (subKey, _T("clsid"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  214325. {
  214326. if (dsize > 0 && checkClassIsOk (buf))
  214327. {
  214328. CLSID classId;
  214329. if (CLSIDFromString ((LPOLESTR) buf, &classId) == S_OK)
  214330. {
  214331. dtype = REG_SZ;
  214332. dsize = sizeof (buf);
  214333. String deviceName;
  214334. if (RegQueryValueEx (subKey, _T("description"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  214335. deviceName = buf;
  214336. else
  214337. deviceName = keyName;
  214338. log ("found " + deviceName);
  214339. deviceNames.add (deviceName);
  214340. classIds.add (new CLSID (classId));
  214341. }
  214342. }
  214343. RegCloseKey (subKey);
  214344. }
  214345. }
  214346. }
  214347. ASIOAudioIODeviceType (const ASIOAudioIODeviceType&);
  214348. ASIOAudioIODeviceType& operator= (const ASIOAudioIODeviceType&);
  214349. };
  214350. AudioIODeviceType* juce_createAudioIODeviceType_ASIO()
  214351. {
  214352. return new ASIOAudioIODeviceType();
  214353. }
  214354. AudioIODevice* juce_createASIOAudioIODeviceForGUID (const String& name,
  214355. void* guid,
  214356. const String& optionalDllForDirectLoading)
  214357. {
  214358. const int freeSlot = ASIOAudioIODeviceType::findFreeSlot();
  214359. if (freeSlot < 0)
  214360. return 0;
  214361. return new ASIOAudioIODevice (name, *(CLSID*) guid, freeSlot, optionalDllForDirectLoading);
  214362. }
  214363. #undef logError
  214364. #undef log
  214365. #endif
  214366. /*** End of inlined file: juce_win32_ASIO.cpp ***/
  214367. /*** Start of inlined file: juce_win32_DirectSound.cpp ***/
  214368. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  214369. // compiled on its own).
  214370. #if JUCE_INCLUDED_FILE && JUCE_DIRECTSOUND
  214371. END_JUCE_NAMESPACE
  214372. extern "C"
  214373. {
  214374. // Declare just the minimum number of interfaces for the DSound objects that we need..
  214375. typedef struct typeDSBUFFERDESC
  214376. {
  214377. DWORD dwSize;
  214378. DWORD dwFlags;
  214379. DWORD dwBufferBytes;
  214380. DWORD dwReserved;
  214381. LPWAVEFORMATEX lpwfxFormat;
  214382. GUID guid3DAlgorithm;
  214383. } DSBUFFERDESC;
  214384. struct IDirectSoundBuffer;
  214385. #undef INTERFACE
  214386. #define INTERFACE IDirectSound
  214387. DECLARE_INTERFACE_(IDirectSound, IUnknown)
  214388. {
  214389. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  214390. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  214391. STDMETHOD_(ULONG,Release) (THIS) PURE;
  214392. STDMETHOD(CreateSoundBuffer) (THIS_ DSBUFFERDESC*, IDirectSoundBuffer**, LPUNKNOWN) PURE;
  214393. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  214394. STDMETHOD(DuplicateSoundBuffer) (THIS_ IDirectSoundBuffer*, IDirectSoundBuffer**) PURE;
  214395. STDMETHOD(SetCooperativeLevel) (THIS_ HWND, DWORD) PURE;
  214396. STDMETHOD(Compact) (THIS) PURE;
  214397. STDMETHOD(GetSpeakerConfig) (THIS_ LPDWORD) PURE;
  214398. STDMETHOD(SetSpeakerConfig) (THIS_ DWORD) PURE;
  214399. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  214400. };
  214401. #undef INTERFACE
  214402. #define INTERFACE IDirectSoundBuffer
  214403. DECLARE_INTERFACE_(IDirectSoundBuffer, IUnknown)
  214404. {
  214405. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  214406. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  214407. STDMETHOD_(ULONG,Release) (THIS) PURE;
  214408. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  214409. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  214410. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  214411. STDMETHOD(GetVolume) (THIS_ LPLONG) PURE;
  214412. STDMETHOD(GetPan) (THIS_ LPLONG) PURE;
  214413. STDMETHOD(GetFrequency) (THIS_ LPDWORD) PURE;
  214414. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  214415. STDMETHOD(Initialize) (THIS_ IDirectSound*, DSBUFFERDESC*) PURE;
  214416. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  214417. STDMETHOD(Play) (THIS_ DWORD, DWORD, DWORD) PURE;
  214418. STDMETHOD(SetCurrentPosition) (THIS_ DWORD) PURE;
  214419. STDMETHOD(SetFormat) (THIS_ const WAVEFORMATEX*) PURE;
  214420. STDMETHOD(SetVolume) (THIS_ LONG) PURE;
  214421. STDMETHOD(SetPan) (THIS_ LONG) PURE;
  214422. STDMETHOD(SetFrequency) (THIS_ DWORD) PURE;
  214423. STDMETHOD(Stop) (THIS) PURE;
  214424. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  214425. STDMETHOD(Restore) (THIS) PURE;
  214426. };
  214427. typedef struct typeDSCBUFFERDESC
  214428. {
  214429. DWORD dwSize;
  214430. DWORD dwFlags;
  214431. DWORD dwBufferBytes;
  214432. DWORD dwReserved;
  214433. LPWAVEFORMATEX lpwfxFormat;
  214434. } DSCBUFFERDESC;
  214435. struct IDirectSoundCaptureBuffer;
  214436. #undef INTERFACE
  214437. #define INTERFACE IDirectSoundCapture
  214438. DECLARE_INTERFACE_(IDirectSoundCapture, IUnknown)
  214439. {
  214440. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  214441. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  214442. STDMETHOD_(ULONG,Release) (THIS) PURE;
  214443. STDMETHOD(CreateCaptureBuffer) (THIS_ DSCBUFFERDESC*, IDirectSoundCaptureBuffer**, LPUNKNOWN) PURE;
  214444. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  214445. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  214446. };
  214447. #undef INTERFACE
  214448. #define INTERFACE IDirectSoundCaptureBuffer
  214449. DECLARE_INTERFACE_(IDirectSoundCaptureBuffer, IUnknown)
  214450. {
  214451. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  214452. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  214453. STDMETHOD_(ULONG,Release) (THIS) PURE;
  214454. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  214455. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  214456. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  214457. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  214458. STDMETHOD(Initialize) (THIS_ IDirectSoundCapture*, DSCBUFFERDESC*) PURE;
  214459. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  214460. STDMETHOD(Start) (THIS_ DWORD) PURE;
  214461. STDMETHOD(Stop) (THIS) PURE;
  214462. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  214463. };
  214464. };
  214465. BEGIN_JUCE_NAMESPACE
  214466. namespace
  214467. {
  214468. const String getDSErrorMessage (HRESULT hr)
  214469. {
  214470. const char* result = 0;
  214471. switch (hr)
  214472. {
  214473. case MAKE_HRESULT(1, 0x878, 10): result = "Device already allocated"; break;
  214474. case MAKE_HRESULT(1, 0x878, 30): result = "Control unavailable"; break;
  214475. case E_INVALIDARG: result = "Invalid parameter"; break;
  214476. case MAKE_HRESULT(1, 0x878, 50): result = "Invalid call"; break;
  214477. case E_FAIL: result = "Generic error"; break;
  214478. case MAKE_HRESULT(1, 0x878, 70): result = "Priority level error"; break;
  214479. case E_OUTOFMEMORY: result = "Out of memory"; break;
  214480. case MAKE_HRESULT(1, 0x878, 100): result = "Bad format"; break;
  214481. case E_NOTIMPL: result = "Unsupported function"; break;
  214482. case MAKE_HRESULT(1, 0x878, 120): result = "No driver"; break;
  214483. case MAKE_HRESULT(1, 0x878, 130): result = "Already initialised"; break;
  214484. case CLASS_E_NOAGGREGATION: result = "No aggregation"; break;
  214485. case MAKE_HRESULT(1, 0x878, 150): result = "Buffer lost"; break;
  214486. case MAKE_HRESULT(1, 0x878, 160): result = "Another app has priority"; break;
  214487. case MAKE_HRESULT(1, 0x878, 170): result = "Uninitialised"; break;
  214488. case E_NOINTERFACE: result = "No interface"; break;
  214489. case S_OK: result = "No error"; break;
  214490. default: return "Unknown error: " + String ((int) hr);
  214491. }
  214492. return result;
  214493. }
  214494. #define DS_DEBUGGING 1
  214495. #ifdef DS_DEBUGGING
  214496. #define CATCH JUCE_CATCH_EXCEPTION
  214497. #undef log
  214498. #define log(a) Logger::writeToLog(a);
  214499. #undef logError
  214500. #define logError(a) logDSError(a, __LINE__);
  214501. static void logDSError (HRESULT hr, int lineNum)
  214502. {
  214503. if (hr != S_OK)
  214504. {
  214505. String error ("DS error at line ");
  214506. error << lineNum << " - " << getDSErrorMessage (hr);
  214507. log (error);
  214508. }
  214509. }
  214510. #else
  214511. #define CATCH JUCE_CATCH_ALL
  214512. #define log(a)
  214513. #define logError(a)
  214514. #endif
  214515. #define DSOUND_FUNCTION(functionName, params) \
  214516. typedef HRESULT (WINAPI *type##functionName) params; \
  214517. static type##functionName ds##functionName = 0;
  214518. #define DSOUND_FUNCTION_LOAD(functionName) \
  214519. ds##functionName = (type##functionName) GetProcAddress (h, #functionName); \
  214520. jassert (ds##functionName != 0);
  214521. typedef BOOL (CALLBACK *LPDSENUMCALLBACKW) (LPGUID, LPCWSTR, LPCWSTR, LPVOID);
  214522. typedef BOOL (CALLBACK *LPDSENUMCALLBACKA) (LPGUID, LPCSTR, LPCSTR, LPVOID);
  214523. DSOUND_FUNCTION (DirectSoundCreate, (const GUID*, IDirectSound**, LPUNKNOWN))
  214524. DSOUND_FUNCTION (DirectSoundCaptureCreate, (const GUID*, IDirectSoundCapture**, LPUNKNOWN))
  214525. DSOUND_FUNCTION (DirectSoundEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  214526. DSOUND_FUNCTION (DirectSoundCaptureEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  214527. void initialiseDSoundFunctions()
  214528. {
  214529. if (dsDirectSoundCreate == 0)
  214530. {
  214531. HMODULE h = LoadLibraryA ("dsound.dll");
  214532. DSOUND_FUNCTION_LOAD (DirectSoundCreate)
  214533. DSOUND_FUNCTION_LOAD (DirectSoundCaptureCreate)
  214534. DSOUND_FUNCTION_LOAD (DirectSoundEnumerateW)
  214535. DSOUND_FUNCTION_LOAD (DirectSoundCaptureEnumerateW)
  214536. }
  214537. }
  214538. }
  214539. class DSoundInternalOutChannel
  214540. {
  214541. String name;
  214542. LPGUID guid;
  214543. int sampleRate, bufferSizeSamples;
  214544. float* leftBuffer;
  214545. float* rightBuffer;
  214546. IDirectSound* pDirectSound;
  214547. IDirectSoundBuffer* pOutputBuffer;
  214548. DWORD writeOffset;
  214549. int totalBytesPerBuffer;
  214550. int bytesPerBuffer;
  214551. unsigned int lastPlayCursor;
  214552. public:
  214553. int bitDepth;
  214554. bool doneFlag;
  214555. DSoundInternalOutChannel (const String& name_,
  214556. LPGUID guid_,
  214557. int rate,
  214558. int bufferSize,
  214559. float* left,
  214560. float* right)
  214561. : name (name_),
  214562. guid (guid_),
  214563. sampleRate (rate),
  214564. bufferSizeSamples (bufferSize),
  214565. leftBuffer (left),
  214566. rightBuffer (right),
  214567. pDirectSound (0),
  214568. pOutputBuffer (0),
  214569. bitDepth (16)
  214570. {
  214571. }
  214572. ~DSoundInternalOutChannel()
  214573. {
  214574. close();
  214575. }
  214576. void close()
  214577. {
  214578. HRESULT hr;
  214579. if (pOutputBuffer != 0)
  214580. {
  214581. JUCE_TRY
  214582. {
  214583. log ("closing dsound out: " + name);
  214584. hr = pOutputBuffer->Stop();
  214585. logError (hr);
  214586. }
  214587. CATCH
  214588. JUCE_TRY
  214589. {
  214590. hr = pOutputBuffer->Release();
  214591. logError (hr);
  214592. }
  214593. CATCH
  214594. pOutputBuffer = 0;
  214595. }
  214596. if (pDirectSound != 0)
  214597. {
  214598. JUCE_TRY
  214599. {
  214600. hr = pDirectSound->Release();
  214601. logError (hr);
  214602. }
  214603. CATCH
  214604. pDirectSound = 0;
  214605. }
  214606. }
  214607. const String open()
  214608. {
  214609. log ("opening dsound out device: " + name + " rate=" + String (sampleRate)
  214610. + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  214611. pDirectSound = 0;
  214612. pOutputBuffer = 0;
  214613. writeOffset = 0;
  214614. String error;
  214615. HRESULT hr = E_NOINTERFACE;
  214616. if (dsDirectSoundCreate != 0)
  214617. hr = dsDirectSoundCreate (guid, &pDirectSound, 0);
  214618. if (hr == S_OK)
  214619. {
  214620. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  214621. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  214622. const int numChannels = 2;
  214623. hr = pDirectSound->SetCooperativeLevel (GetDesktopWindow(), 2 /* DSSCL_PRIORITY */);
  214624. logError (hr);
  214625. if (hr == S_OK)
  214626. {
  214627. IDirectSoundBuffer* pPrimaryBuffer;
  214628. DSBUFFERDESC primaryDesc;
  214629. zerostruct (primaryDesc);
  214630. primaryDesc.dwSize = sizeof (DSBUFFERDESC);
  214631. primaryDesc.dwFlags = 1 /* DSBCAPS_PRIMARYBUFFER */;
  214632. primaryDesc.dwBufferBytes = 0;
  214633. primaryDesc.lpwfxFormat = 0;
  214634. log ("opening dsound out step 2");
  214635. hr = pDirectSound->CreateSoundBuffer (&primaryDesc, &pPrimaryBuffer, 0);
  214636. logError (hr);
  214637. if (hr == S_OK)
  214638. {
  214639. WAVEFORMATEX wfFormat;
  214640. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  214641. wfFormat.nChannels = (unsigned short) numChannels;
  214642. wfFormat.nSamplesPerSec = sampleRate;
  214643. wfFormat.wBitsPerSample = (unsigned short) bitDepth;
  214644. wfFormat.nBlockAlign = (unsigned short) (wfFormat.nChannels * wfFormat.wBitsPerSample / 8);
  214645. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  214646. wfFormat.cbSize = 0;
  214647. hr = pPrimaryBuffer->SetFormat (&wfFormat);
  214648. logError (hr);
  214649. if (hr == S_OK)
  214650. {
  214651. DSBUFFERDESC secondaryDesc;
  214652. zerostruct (secondaryDesc);
  214653. secondaryDesc.dwSize = sizeof (DSBUFFERDESC);
  214654. secondaryDesc.dwFlags = 0x8000 /* DSBCAPS_GLOBALFOCUS */
  214655. | 0x10000 /* DSBCAPS_GETCURRENTPOSITION2 */;
  214656. secondaryDesc.dwBufferBytes = totalBytesPerBuffer;
  214657. secondaryDesc.lpwfxFormat = &wfFormat;
  214658. hr = pDirectSound->CreateSoundBuffer (&secondaryDesc, &pOutputBuffer, 0);
  214659. logError (hr);
  214660. if (hr == S_OK)
  214661. {
  214662. log ("opening dsound out step 3");
  214663. DWORD dwDataLen;
  214664. unsigned char* pDSBuffData;
  214665. hr = pOutputBuffer->Lock (0, totalBytesPerBuffer,
  214666. (LPVOID*) &pDSBuffData, &dwDataLen, 0, 0, 0);
  214667. logError (hr);
  214668. if (hr == S_OK)
  214669. {
  214670. zeromem (pDSBuffData, dwDataLen);
  214671. hr = pOutputBuffer->Unlock (pDSBuffData, dwDataLen, 0, 0);
  214672. if (hr == S_OK)
  214673. {
  214674. hr = pOutputBuffer->SetCurrentPosition (0);
  214675. if (hr == S_OK)
  214676. {
  214677. hr = pOutputBuffer->Play (0, 0, 1 /* DSBPLAY_LOOPING */);
  214678. if (hr == S_OK)
  214679. return String::empty;
  214680. }
  214681. }
  214682. }
  214683. }
  214684. }
  214685. }
  214686. }
  214687. }
  214688. error = getDSErrorMessage (hr);
  214689. close();
  214690. return error;
  214691. }
  214692. void synchronisePosition()
  214693. {
  214694. if (pOutputBuffer != 0)
  214695. {
  214696. DWORD playCursor;
  214697. pOutputBuffer->GetCurrentPosition (&playCursor, &writeOffset);
  214698. }
  214699. }
  214700. bool service()
  214701. {
  214702. if (pOutputBuffer == 0)
  214703. return true;
  214704. DWORD playCursor, writeCursor;
  214705. for (;;)
  214706. {
  214707. HRESULT hr = pOutputBuffer->GetCurrentPosition (&playCursor, &writeCursor);
  214708. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  214709. {
  214710. pOutputBuffer->Restore();
  214711. continue;
  214712. }
  214713. if (hr == S_OK)
  214714. break;
  214715. logError (hr);
  214716. jassertfalse;
  214717. return true;
  214718. }
  214719. int playWriteGap = writeCursor - playCursor;
  214720. if (playWriteGap < 0)
  214721. playWriteGap += totalBytesPerBuffer;
  214722. int bytesEmpty = playCursor - writeOffset;
  214723. if (bytesEmpty < 0)
  214724. bytesEmpty += totalBytesPerBuffer;
  214725. if (bytesEmpty > (totalBytesPerBuffer - playWriteGap))
  214726. {
  214727. writeOffset = writeCursor;
  214728. bytesEmpty = totalBytesPerBuffer - playWriteGap;
  214729. }
  214730. if (bytesEmpty >= bytesPerBuffer)
  214731. {
  214732. void* lpbuf1 = 0;
  214733. void* lpbuf2 = 0;
  214734. DWORD dwSize1 = 0;
  214735. DWORD dwSize2 = 0;
  214736. HRESULT hr = pOutputBuffer->Lock (writeOffset,
  214737. bytesPerBuffer,
  214738. &lpbuf1, &dwSize1,
  214739. &lpbuf2, &dwSize2, 0);
  214740. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  214741. {
  214742. pOutputBuffer->Restore();
  214743. hr = pOutputBuffer->Lock (writeOffset,
  214744. bytesPerBuffer,
  214745. &lpbuf1, &dwSize1,
  214746. &lpbuf2, &dwSize2, 0);
  214747. }
  214748. if (hr == S_OK)
  214749. {
  214750. if (bitDepth == 16)
  214751. {
  214752. const float gainL = 32767.0f;
  214753. const float gainR = 32767.0f;
  214754. int* dest = static_cast<int*> (lpbuf1);
  214755. const float* left = leftBuffer;
  214756. const float* right = rightBuffer;
  214757. int samples1 = dwSize1 >> 2;
  214758. int samples2 = dwSize2 >> 2;
  214759. if (left == 0)
  214760. {
  214761. while (--samples1 >= 0)
  214762. {
  214763. int r = roundToInt (gainR * *right++);
  214764. if (r < -32768)
  214765. r = -32768;
  214766. else if (r > 32767)
  214767. r = 32767;
  214768. *dest++ = (r << 16);
  214769. }
  214770. dest = static_cast<int*> (lpbuf2);
  214771. while (--samples2 >= 0)
  214772. {
  214773. int r = roundToInt (gainR * *right++);
  214774. if (r < -32768)
  214775. r = -32768;
  214776. else if (r > 32767)
  214777. r = 32767;
  214778. *dest++ = (r << 16);
  214779. }
  214780. }
  214781. else if (right == 0)
  214782. {
  214783. while (--samples1 >= 0)
  214784. {
  214785. int l = roundToInt (gainL * *left++);
  214786. if (l < -32768)
  214787. l = -32768;
  214788. else if (l > 32767)
  214789. l = 32767;
  214790. l &= 0xffff;
  214791. *dest++ = l;
  214792. }
  214793. dest = static_cast<int*> (lpbuf2);
  214794. while (--samples2 >= 0)
  214795. {
  214796. int l = roundToInt (gainL * *left++);
  214797. if (l < -32768)
  214798. l = -32768;
  214799. else if (l > 32767)
  214800. l = 32767;
  214801. l &= 0xffff;
  214802. *dest++ = l;
  214803. }
  214804. }
  214805. else
  214806. {
  214807. while (--samples1 >= 0)
  214808. {
  214809. int l = roundToInt (gainL * *left++);
  214810. if (l < -32768)
  214811. l = -32768;
  214812. else if (l > 32767)
  214813. l = 32767;
  214814. l &= 0xffff;
  214815. int r = roundToInt (gainR * *right++);
  214816. if (r < -32768)
  214817. r = -32768;
  214818. else if (r > 32767)
  214819. r = 32767;
  214820. *dest++ = (r << 16) | l;
  214821. }
  214822. dest = static_cast<int*> (lpbuf2);
  214823. while (--samples2 >= 0)
  214824. {
  214825. int l = roundToInt (gainL * *left++);
  214826. if (l < -32768)
  214827. l = -32768;
  214828. else if (l > 32767)
  214829. l = 32767;
  214830. l &= 0xffff;
  214831. int r = roundToInt (gainR * *right++);
  214832. if (r < -32768)
  214833. r = -32768;
  214834. else if (r > 32767)
  214835. r = 32767;
  214836. *dest++ = (r << 16) | l;
  214837. }
  214838. }
  214839. }
  214840. else
  214841. {
  214842. jassertfalse;
  214843. }
  214844. writeOffset = (writeOffset + dwSize1 + dwSize2) % totalBytesPerBuffer;
  214845. pOutputBuffer->Unlock (lpbuf1, dwSize1, lpbuf2, dwSize2);
  214846. }
  214847. else
  214848. {
  214849. jassertfalse;
  214850. logError (hr);
  214851. }
  214852. bytesEmpty -= bytesPerBuffer;
  214853. return true;
  214854. }
  214855. else
  214856. {
  214857. return false;
  214858. }
  214859. }
  214860. };
  214861. struct DSoundInternalInChannel
  214862. {
  214863. String name;
  214864. LPGUID guid;
  214865. int sampleRate, bufferSizeSamples;
  214866. float* leftBuffer;
  214867. float* rightBuffer;
  214868. IDirectSound* pDirectSound;
  214869. IDirectSoundCapture* pDirectSoundCapture;
  214870. IDirectSoundCaptureBuffer* pInputBuffer;
  214871. public:
  214872. unsigned int readOffset;
  214873. int bytesPerBuffer, totalBytesPerBuffer;
  214874. int bitDepth;
  214875. bool doneFlag;
  214876. DSoundInternalInChannel (const String& name_,
  214877. LPGUID guid_,
  214878. int rate,
  214879. int bufferSize,
  214880. float* left,
  214881. float* right)
  214882. : name (name_),
  214883. guid (guid_),
  214884. sampleRate (rate),
  214885. bufferSizeSamples (bufferSize),
  214886. leftBuffer (left),
  214887. rightBuffer (right),
  214888. pDirectSound (0),
  214889. pDirectSoundCapture (0),
  214890. pInputBuffer (0),
  214891. bitDepth (16)
  214892. {
  214893. }
  214894. ~DSoundInternalInChannel()
  214895. {
  214896. close();
  214897. }
  214898. void close()
  214899. {
  214900. HRESULT hr;
  214901. if (pInputBuffer != 0)
  214902. {
  214903. JUCE_TRY
  214904. {
  214905. log ("closing dsound in: " + name);
  214906. hr = pInputBuffer->Stop();
  214907. logError (hr);
  214908. }
  214909. CATCH
  214910. JUCE_TRY
  214911. {
  214912. hr = pInputBuffer->Release();
  214913. logError (hr);
  214914. }
  214915. CATCH
  214916. pInputBuffer = 0;
  214917. }
  214918. if (pDirectSoundCapture != 0)
  214919. {
  214920. JUCE_TRY
  214921. {
  214922. hr = pDirectSoundCapture->Release();
  214923. logError (hr);
  214924. }
  214925. CATCH
  214926. pDirectSoundCapture = 0;
  214927. }
  214928. if (pDirectSound != 0)
  214929. {
  214930. JUCE_TRY
  214931. {
  214932. hr = pDirectSound->Release();
  214933. logError (hr);
  214934. }
  214935. CATCH
  214936. pDirectSound = 0;
  214937. }
  214938. }
  214939. const String open()
  214940. {
  214941. log ("opening dsound in device: " + name
  214942. + " rate=" + String (sampleRate) + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  214943. pDirectSound = 0;
  214944. pDirectSoundCapture = 0;
  214945. pInputBuffer = 0;
  214946. readOffset = 0;
  214947. totalBytesPerBuffer = 0;
  214948. String error;
  214949. HRESULT hr = E_NOINTERFACE;
  214950. if (dsDirectSoundCaptureCreate != 0)
  214951. hr = dsDirectSoundCaptureCreate (guid, &pDirectSoundCapture, 0);
  214952. logError (hr);
  214953. if (hr == S_OK)
  214954. {
  214955. const int numChannels = 2;
  214956. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  214957. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  214958. WAVEFORMATEX wfFormat;
  214959. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  214960. wfFormat.nChannels = (unsigned short)numChannels;
  214961. wfFormat.nSamplesPerSec = sampleRate;
  214962. wfFormat.wBitsPerSample = (unsigned short)bitDepth;
  214963. wfFormat.nBlockAlign = (unsigned short)(wfFormat.nChannels * (wfFormat.wBitsPerSample / 8));
  214964. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  214965. wfFormat.cbSize = 0;
  214966. DSCBUFFERDESC captureDesc;
  214967. zerostruct (captureDesc);
  214968. captureDesc.dwSize = sizeof (DSCBUFFERDESC);
  214969. captureDesc.dwFlags = 0;
  214970. captureDesc.dwBufferBytes = totalBytesPerBuffer;
  214971. captureDesc.lpwfxFormat = &wfFormat;
  214972. log ("opening dsound in step 2");
  214973. hr = pDirectSoundCapture->CreateCaptureBuffer (&captureDesc, &pInputBuffer, 0);
  214974. logError (hr);
  214975. if (hr == S_OK)
  214976. {
  214977. hr = pInputBuffer->Start (1 /* DSCBSTART_LOOPING */);
  214978. logError (hr);
  214979. if (hr == S_OK)
  214980. return String::empty;
  214981. }
  214982. }
  214983. error = getDSErrorMessage (hr);
  214984. close();
  214985. return error;
  214986. }
  214987. void synchronisePosition()
  214988. {
  214989. if (pInputBuffer != 0)
  214990. {
  214991. DWORD capturePos;
  214992. pInputBuffer->GetCurrentPosition (&capturePos, (DWORD*)&readOffset);
  214993. }
  214994. }
  214995. bool service()
  214996. {
  214997. if (pInputBuffer == 0)
  214998. return true;
  214999. DWORD capturePos, readPos;
  215000. HRESULT hr = pInputBuffer->GetCurrentPosition (&capturePos, &readPos);
  215001. logError (hr);
  215002. if (hr != S_OK)
  215003. return true;
  215004. int bytesFilled = readPos - readOffset;
  215005. if (bytesFilled < 0)
  215006. bytesFilled += totalBytesPerBuffer;
  215007. if (bytesFilled >= bytesPerBuffer)
  215008. {
  215009. LPBYTE lpbuf1 = 0;
  215010. LPBYTE lpbuf2 = 0;
  215011. DWORD dwsize1 = 0;
  215012. DWORD dwsize2 = 0;
  215013. HRESULT hr = pInputBuffer->Lock (readOffset,
  215014. bytesPerBuffer,
  215015. (void**) &lpbuf1, &dwsize1,
  215016. (void**) &lpbuf2, &dwsize2, 0);
  215017. if (hr == S_OK)
  215018. {
  215019. if (bitDepth == 16)
  215020. {
  215021. const float g = 1.0f / 32768.0f;
  215022. float* destL = leftBuffer;
  215023. float* destR = rightBuffer;
  215024. int samples1 = dwsize1 >> 2;
  215025. int samples2 = dwsize2 >> 2;
  215026. const short* src = (const short*)lpbuf1;
  215027. if (destL == 0)
  215028. {
  215029. while (--samples1 >= 0)
  215030. {
  215031. ++src;
  215032. *destR++ = *src++ * g;
  215033. }
  215034. src = (const short*)lpbuf2;
  215035. while (--samples2 >= 0)
  215036. {
  215037. ++src;
  215038. *destR++ = *src++ * g;
  215039. }
  215040. }
  215041. else if (destR == 0)
  215042. {
  215043. while (--samples1 >= 0)
  215044. {
  215045. *destL++ = *src++ * g;
  215046. ++src;
  215047. }
  215048. src = (const short*)lpbuf2;
  215049. while (--samples2 >= 0)
  215050. {
  215051. *destL++ = *src++ * g;
  215052. ++src;
  215053. }
  215054. }
  215055. else
  215056. {
  215057. while (--samples1 >= 0)
  215058. {
  215059. *destL++ = *src++ * g;
  215060. *destR++ = *src++ * g;
  215061. }
  215062. src = (const short*)lpbuf2;
  215063. while (--samples2 >= 0)
  215064. {
  215065. *destL++ = *src++ * g;
  215066. *destR++ = *src++ * g;
  215067. }
  215068. }
  215069. }
  215070. else
  215071. {
  215072. jassertfalse;
  215073. }
  215074. readOffset = (readOffset + dwsize1 + dwsize2) % totalBytesPerBuffer;
  215075. pInputBuffer->Unlock (lpbuf1, dwsize1, lpbuf2, dwsize2);
  215076. }
  215077. else
  215078. {
  215079. logError (hr);
  215080. jassertfalse;
  215081. }
  215082. bytesFilled -= bytesPerBuffer;
  215083. return true;
  215084. }
  215085. else
  215086. {
  215087. return false;
  215088. }
  215089. }
  215090. };
  215091. class DSoundAudioIODevice : public AudioIODevice,
  215092. public Thread
  215093. {
  215094. public:
  215095. DSoundAudioIODevice (const String& deviceName,
  215096. const int outputDeviceIndex_,
  215097. const int inputDeviceIndex_)
  215098. : AudioIODevice (deviceName, "DirectSound"),
  215099. Thread ("Juce DSound"),
  215100. isOpen_ (false),
  215101. isStarted (false),
  215102. outputDeviceIndex (outputDeviceIndex_),
  215103. inputDeviceIndex (inputDeviceIndex_),
  215104. totalSamplesOut (0),
  215105. sampleRate (0.0),
  215106. inputBuffers (1, 1),
  215107. outputBuffers (1, 1),
  215108. callback (0),
  215109. bufferSizeSamples (0)
  215110. {
  215111. if (outputDeviceIndex_ >= 0)
  215112. {
  215113. outChannels.add (TRANS("Left"));
  215114. outChannels.add (TRANS("Right"));
  215115. }
  215116. if (inputDeviceIndex_ >= 0)
  215117. {
  215118. inChannels.add (TRANS("Left"));
  215119. inChannels.add (TRANS("Right"));
  215120. }
  215121. }
  215122. ~DSoundAudioIODevice()
  215123. {
  215124. close();
  215125. }
  215126. const StringArray getOutputChannelNames()
  215127. {
  215128. return outChannels;
  215129. }
  215130. const StringArray getInputChannelNames()
  215131. {
  215132. return inChannels;
  215133. }
  215134. int getNumSampleRates()
  215135. {
  215136. return 4;
  215137. }
  215138. double getSampleRate (int index)
  215139. {
  215140. const double samps[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  215141. return samps [jlimit (0, 3, index)];
  215142. }
  215143. int getNumBufferSizesAvailable()
  215144. {
  215145. return 50;
  215146. }
  215147. int getBufferSizeSamples (int index)
  215148. {
  215149. int n = 64;
  215150. for (int i = 0; i < index; ++i)
  215151. n += (n < 512) ? 32
  215152. : ((n < 1024) ? 64
  215153. : ((n < 2048) ? 128 : 256));
  215154. return n;
  215155. }
  215156. int getDefaultBufferSize()
  215157. {
  215158. return 2560;
  215159. }
  215160. const String open (const BigInteger& inputChannels,
  215161. const BigInteger& outputChannels,
  215162. double sampleRate,
  215163. int bufferSizeSamples)
  215164. {
  215165. lastError = openDevice (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  215166. isOpen_ = lastError.isEmpty();
  215167. return lastError;
  215168. }
  215169. void close()
  215170. {
  215171. stop();
  215172. if (isOpen_)
  215173. {
  215174. closeDevice();
  215175. isOpen_ = false;
  215176. }
  215177. }
  215178. bool isOpen()
  215179. {
  215180. return isOpen_ && isThreadRunning();
  215181. }
  215182. int getCurrentBufferSizeSamples()
  215183. {
  215184. return bufferSizeSamples;
  215185. }
  215186. double getCurrentSampleRate()
  215187. {
  215188. return sampleRate;
  215189. }
  215190. int getCurrentBitDepth()
  215191. {
  215192. int i, bits = 256;
  215193. for (i = inChans.size(); --i >= 0;)
  215194. bits = jmin (bits, inChans[i]->bitDepth);
  215195. for (i = outChans.size(); --i >= 0;)
  215196. bits = jmin (bits, outChans[i]->bitDepth);
  215197. if (bits > 32)
  215198. bits = 16;
  215199. return bits;
  215200. }
  215201. const BigInteger getActiveOutputChannels() const
  215202. {
  215203. return enabledOutputs;
  215204. }
  215205. const BigInteger getActiveInputChannels() const
  215206. {
  215207. return enabledInputs;
  215208. }
  215209. int getOutputLatencyInSamples()
  215210. {
  215211. return (int) (getCurrentBufferSizeSamples() * 1.5);
  215212. }
  215213. int getInputLatencyInSamples()
  215214. {
  215215. return getOutputLatencyInSamples();
  215216. }
  215217. void start (AudioIODeviceCallback* call)
  215218. {
  215219. if (isOpen_ && call != 0 && ! isStarted)
  215220. {
  215221. if (! isThreadRunning())
  215222. {
  215223. // something gone wrong and the thread's stopped..
  215224. isOpen_ = false;
  215225. return;
  215226. }
  215227. call->audioDeviceAboutToStart (this);
  215228. const ScopedLock sl (startStopLock);
  215229. callback = call;
  215230. isStarted = true;
  215231. }
  215232. }
  215233. void stop()
  215234. {
  215235. if (isStarted)
  215236. {
  215237. AudioIODeviceCallback* const callbackLocal = callback;
  215238. {
  215239. const ScopedLock sl (startStopLock);
  215240. isStarted = false;
  215241. }
  215242. if (callbackLocal != 0)
  215243. callbackLocal->audioDeviceStopped();
  215244. }
  215245. }
  215246. bool isPlaying()
  215247. {
  215248. return isStarted && isOpen_ && isThreadRunning();
  215249. }
  215250. const String getLastError()
  215251. {
  215252. return lastError;
  215253. }
  215254. juce_UseDebuggingNewOperator
  215255. StringArray inChannels, outChannels;
  215256. int outputDeviceIndex, inputDeviceIndex;
  215257. private:
  215258. bool isOpen_;
  215259. bool isStarted;
  215260. String lastError;
  215261. OwnedArray <DSoundInternalInChannel> inChans;
  215262. OwnedArray <DSoundInternalOutChannel> outChans;
  215263. WaitableEvent startEvent;
  215264. int bufferSizeSamples;
  215265. int volatile totalSamplesOut;
  215266. int64 volatile lastBlockTime;
  215267. double sampleRate;
  215268. BigInteger enabledInputs, enabledOutputs;
  215269. AudioSampleBuffer inputBuffers, outputBuffers;
  215270. AudioIODeviceCallback* callback;
  215271. CriticalSection startStopLock;
  215272. DSoundAudioIODevice (const DSoundAudioIODevice&);
  215273. DSoundAudioIODevice& operator= (const DSoundAudioIODevice&);
  215274. const String openDevice (const BigInteger& inputChannels,
  215275. const BigInteger& outputChannels,
  215276. double sampleRate_,
  215277. int bufferSizeSamples_);
  215278. void closeDevice()
  215279. {
  215280. isStarted = false;
  215281. stopThread (5000);
  215282. inChans.clear();
  215283. outChans.clear();
  215284. inputBuffers.setSize (1, 1);
  215285. outputBuffers.setSize (1, 1);
  215286. }
  215287. void resync()
  215288. {
  215289. if (! threadShouldExit())
  215290. {
  215291. sleep (5);
  215292. int i;
  215293. for (i = 0; i < outChans.size(); ++i)
  215294. outChans.getUnchecked(i)->synchronisePosition();
  215295. for (i = 0; i < inChans.size(); ++i)
  215296. inChans.getUnchecked(i)->synchronisePosition();
  215297. }
  215298. }
  215299. public:
  215300. void run()
  215301. {
  215302. while (! threadShouldExit())
  215303. {
  215304. if (wait (100))
  215305. break;
  215306. }
  215307. const int latencyMs = (int) (bufferSizeSamples * 1000.0 / sampleRate);
  215308. const int maxTimeMS = jmax (5, 3 * latencyMs);
  215309. while (! threadShouldExit())
  215310. {
  215311. int numToDo = 0;
  215312. uint32 startTime = Time::getMillisecondCounter();
  215313. int i;
  215314. for (i = inChans.size(); --i >= 0;)
  215315. {
  215316. inChans.getUnchecked(i)->doneFlag = false;
  215317. ++numToDo;
  215318. }
  215319. for (i = outChans.size(); --i >= 0;)
  215320. {
  215321. outChans.getUnchecked(i)->doneFlag = false;
  215322. ++numToDo;
  215323. }
  215324. if (numToDo > 0)
  215325. {
  215326. const int maxCount = 3;
  215327. int count = maxCount;
  215328. for (;;)
  215329. {
  215330. for (i = inChans.size(); --i >= 0;)
  215331. {
  215332. DSoundInternalInChannel* const in = inChans.getUnchecked(i);
  215333. if ((! in->doneFlag) && in->service())
  215334. {
  215335. in->doneFlag = true;
  215336. --numToDo;
  215337. }
  215338. }
  215339. for (i = outChans.size(); --i >= 0;)
  215340. {
  215341. DSoundInternalOutChannel* const out = outChans.getUnchecked(i);
  215342. if ((! out->doneFlag) && out->service())
  215343. {
  215344. out->doneFlag = true;
  215345. --numToDo;
  215346. }
  215347. }
  215348. if (numToDo <= 0)
  215349. break;
  215350. if (Time::getMillisecondCounter() > startTime + maxTimeMS)
  215351. {
  215352. resync();
  215353. break;
  215354. }
  215355. if (--count <= 0)
  215356. {
  215357. Sleep (1);
  215358. count = maxCount;
  215359. }
  215360. if (threadShouldExit())
  215361. return;
  215362. }
  215363. }
  215364. else
  215365. {
  215366. sleep (1);
  215367. }
  215368. const ScopedLock sl (startStopLock);
  215369. if (isStarted)
  215370. {
  215371. JUCE_TRY
  215372. {
  215373. callback->audioDeviceIOCallback (const_cast <const float**> (inputBuffers.getArrayOfChannels()),
  215374. inputBuffers.getNumChannels(),
  215375. outputBuffers.getArrayOfChannels(),
  215376. outputBuffers.getNumChannels(),
  215377. bufferSizeSamples);
  215378. }
  215379. JUCE_CATCH_EXCEPTION
  215380. totalSamplesOut += bufferSizeSamples;
  215381. }
  215382. else
  215383. {
  215384. outputBuffers.clear();
  215385. totalSamplesOut = 0;
  215386. sleep (1);
  215387. }
  215388. }
  215389. }
  215390. };
  215391. class DSoundAudioIODeviceType : public AudioIODeviceType
  215392. {
  215393. public:
  215394. DSoundAudioIODeviceType()
  215395. : AudioIODeviceType ("DirectSound"),
  215396. hasScanned (false)
  215397. {
  215398. initialiseDSoundFunctions();
  215399. }
  215400. ~DSoundAudioIODeviceType()
  215401. {
  215402. }
  215403. void scanForDevices()
  215404. {
  215405. hasScanned = true;
  215406. outputDeviceNames.clear();
  215407. outputGuids.clear();
  215408. inputDeviceNames.clear();
  215409. inputGuids.clear();
  215410. if (dsDirectSoundEnumerateW != 0)
  215411. {
  215412. dsDirectSoundEnumerateW (outputEnumProcW, this);
  215413. dsDirectSoundCaptureEnumerateW (inputEnumProcW, this);
  215414. }
  215415. }
  215416. const StringArray getDeviceNames (bool wantInputNames) const
  215417. {
  215418. jassert (hasScanned); // need to call scanForDevices() before doing this
  215419. return wantInputNames ? inputDeviceNames
  215420. : outputDeviceNames;
  215421. }
  215422. int getDefaultDeviceIndex (bool /*forInput*/) const
  215423. {
  215424. jassert (hasScanned); // need to call scanForDevices() before doing this
  215425. return 0;
  215426. }
  215427. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  215428. {
  215429. jassert (hasScanned); // need to call scanForDevices() before doing this
  215430. DSoundAudioIODevice* const d = dynamic_cast <DSoundAudioIODevice*> (device);
  215431. if (d == 0)
  215432. return -1;
  215433. return asInput ? d->inputDeviceIndex
  215434. : d->outputDeviceIndex;
  215435. }
  215436. bool hasSeparateInputsAndOutputs() const { return true; }
  215437. AudioIODevice* createDevice (const String& outputDeviceName,
  215438. const String& inputDeviceName)
  215439. {
  215440. jassert (hasScanned); // need to call scanForDevices() before doing this
  215441. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  215442. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  215443. if (outputIndex >= 0 || inputIndex >= 0)
  215444. return new DSoundAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  215445. : inputDeviceName,
  215446. outputIndex, inputIndex);
  215447. return 0;
  215448. }
  215449. juce_UseDebuggingNewOperator
  215450. StringArray outputDeviceNames;
  215451. OwnedArray <GUID> outputGuids;
  215452. StringArray inputDeviceNames;
  215453. OwnedArray <GUID> inputGuids;
  215454. private:
  215455. bool hasScanned;
  215456. BOOL outputEnumProc (LPGUID lpGUID, String desc)
  215457. {
  215458. desc = desc.trim();
  215459. if (desc.isNotEmpty())
  215460. {
  215461. const String origDesc (desc);
  215462. int n = 2;
  215463. while (outputDeviceNames.contains (desc))
  215464. desc = origDesc + " (" + String (n++) + ")";
  215465. outputDeviceNames.add (desc);
  215466. if (lpGUID != 0)
  215467. outputGuids.add (new GUID (*lpGUID));
  215468. else
  215469. outputGuids.add (0);
  215470. }
  215471. return TRUE;
  215472. }
  215473. static BOOL CALLBACK outputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  215474. {
  215475. return ((DSoundAudioIODeviceType*) object)
  215476. ->outputEnumProc (lpGUID, String (description));
  215477. }
  215478. static BOOL CALLBACK outputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  215479. {
  215480. return ((DSoundAudioIODeviceType*) object)
  215481. ->outputEnumProc (lpGUID, String (description));
  215482. }
  215483. BOOL CALLBACK inputEnumProc (LPGUID lpGUID, String desc)
  215484. {
  215485. desc = desc.trim();
  215486. if (desc.isNotEmpty())
  215487. {
  215488. const String origDesc (desc);
  215489. int n = 2;
  215490. while (inputDeviceNames.contains (desc))
  215491. desc = origDesc + " (" + String (n++) + ")";
  215492. inputDeviceNames.add (desc);
  215493. if (lpGUID != 0)
  215494. inputGuids.add (new GUID (*lpGUID));
  215495. else
  215496. inputGuids.add (0);
  215497. }
  215498. return TRUE;
  215499. }
  215500. static BOOL CALLBACK inputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  215501. {
  215502. return ((DSoundAudioIODeviceType*) object)
  215503. ->inputEnumProc (lpGUID, String (description));
  215504. }
  215505. static BOOL CALLBACK inputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  215506. {
  215507. return ((DSoundAudioIODeviceType*) object)
  215508. ->inputEnumProc (lpGUID, String (description));
  215509. }
  215510. DSoundAudioIODeviceType (const DSoundAudioIODeviceType&);
  215511. DSoundAudioIODeviceType& operator= (const DSoundAudioIODeviceType&);
  215512. };
  215513. const String DSoundAudioIODevice::openDevice (const BigInteger& inputChannels,
  215514. const BigInteger& outputChannels,
  215515. double sampleRate_,
  215516. int bufferSizeSamples_)
  215517. {
  215518. closeDevice();
  215519. totalSamplesOut = 0;
  215520. sampleRate = sampleRate_;
  215521. if (bufferSizeSamples_ <= 0)
  215522. bufferSizeSamples_ = 960; // use as a default size if none is set.
  215523. bufferSizeSamples = bufferSizeSamples_ & ~7;
  215524. DSoundAudioIODeviceType dlh;
  215525. dlh.scanForDevices();
  215526. enabledInputs = inputChannels;
  215527. enabledInputs.setRange (inChannels.size(),
  215528. enabledInputs.getHighestBit() + 1 - inChannels.size(),
  215529. false);
  215530. inputBuffers.setSize (jmax (1, enabledInputs.countNumberOfSetBits()), bufferSizeSamples);
  215531. inputBuffers.clear();
  215532. int i, numIns = 0;
  215533. for (i = 0; i <= enabledInputs.getHighestBit(); i += 2)
  215534. {
  215535. float* left = 0;
  215536. if (enabledInputs[i])
  215537. left = inputBuffers.getSampleData (numIns++);
  215538. float* right = 0;
  215539. if (enabledInputs[i + 1])
  215540. right = inputBuffers.getSampleData (numIns++);
  215541. if (left != 0 || right != 0)
  215542. inChans.add (new DSoundInternalInChannel (dlh.inputDeviceNames [inputDeviceIndex],
  215543. dlh.inputGuids [inputDeviceIndex],
  215544. (int) sampleRate, bufferSizeSamples,
  215545. left, right));
  215546. }
  215547. enabledOutputs = outputChannels;
  215548. enabledOutputs.setRange (outChannels.size(),
  215549. enabledOutputs.getHighestBit() + 1 - outChannels.size(),
  215550. false);
  215551. outputBuffers.setSize (jmax (1, enabledOutputs.countNumberOfSetBits()), bufferSizeSamples);
  215552. outputBuffers.clear();
  215553. int numOuts = 0;
  215554. for (i = 0; i <= enabledOutputs.getHighestBit(); i += 2)
  215555. {
  215556. float* left = 0;
  215557. if (enabledOutputs[i])
  215558. left = outputBuffers.getSampleData (numOuts++);
  215559. float* right = 0;
  215560. if (enabledOutputs[i + 1])
  215561. right = outputBuffers.getSampleData (numOuts++);
  215562. if (left != 0 || right != 0)
  215563. outChans.add (new DSoundInternalOutChannel (dlh.outputDeviceNames[outputDeviceIndex],
  215564. dlh.outputGuids [outputDeviceIndex],
  215565. (int) sampleRate, bufferSizeSamples,
  215566. left, right));
  215567. }
  215568. String error;
  215569. // boost our priority while opening the devices to try to get better sync between them
  215570. const int oldThreadPri = GetThreadPriority (GetCurrentThread());
  215571. const int oldProcPri = GetPriorityClass (GetCurrentProcess());
  215572. SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  215573. SetPriorityClass (GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
  215574. for (i = 0; i < outChans.size(); ++i)
  215575. {
  215576. error = outChans[i]->open();
  215577. if (error.isNotEmpty())
  215578. {
  215579. error = "Error opening " + dlh.outputDeviceNames[i] + ": \"" + error + "\"";
  215580. break;
  215581. }
  215582. }
  215583. if (error.isEmpty())
  215584. {
  215585. for (i = 0; i < inChans.size(); ++i)
  215586. {
  215587. error = inChans[i]->open();
  215588. if (error.isNotEmpty())
  215589. {
  215590. error = "Error opening " + dlh.inputDeviceNames[i] + ": \"" + error + "\"";
  215591. break;
  215592. }
  215593. }
  215594. }
  215595. if (error.isEmpty())
  215596. {
  215597. totalSamplesOut = 0;
  215598. for (i = 0; i < outChans.size(); ++i)
  215599. outChans.getUnchecked(i)->synchronisePosition();
  215600. for (i = 0; i < inChans.size(); ++i)
  215601. inChans.getUnchecked(i)->synchronisePosition();
  215602. startThread (9);
  215603. sleep (10);
  215604. notify();
  215605. }
  215606. else
  215607. {
  215608. log (error);
  215609. }
  215610. SetThreadPriority (GetCurrentThread(), oldThreadPri);
  215611. SetPriorityClass (GetCurrentProcess(), oldProcPri);
  215612. return error;
  215613. }
  215614. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound()
  215615. {
  215616. return new DSoundAudioIODeviceType();
  215617. }
  215618. #undef log
  215619. #endif
  215620. /*** End of inlined file: juce_win32_DirectSound.cpp ***/
  215621. /*** Start of inlined file: juce_win32_WASAPI.cpp ***/
  215622. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  215623. // compiled on its own).
  215624. #if JUCE_INCLUDED_FILE && JUCE_WASAPI
  215625. #ifndef WASAPI_ENABLE_LOGGING
  215626. #define WASAPI_ENABLE_LOGGING 1
  215627. #endif
  215628. namespace WasapiClasses
  215629. {
  215630. void logFailure (HRESULT hr)
  215631. {
  215632. (void) hr;
  215633. #if WASAPI_ENABLE_LOGGING
  215634. if (FAILED (hr))
  215635. {
  215636. String e;
  215637. e << Time::getCurrentTime().toString (true, true, true, true)
  215638. << " -- WASAPI error: ";
  215639. switch (hr)
  215640. {
  215641. case E_POINTER: e << "E_POINTER"; break;
  215642. case E_INVALIDARG: e << "E_INVALIDARG"; break;
  215643. case AUDCLNT_E_NOT_INITIALIZED: e << "AUDCLNT_E_NOT_INITIALIZED"; break;
  215644. case AUDCLNT_E_ALREADY_INITIALIZED: e << "AUDCLNT_E_ALREADY_INITIALIZED"; break;
  215645. case AUDCLNT_E_WRONG_ENDPOINT_TYPE: e << "AUDCLNT_E_WRONG_ENDPOINT_TYPE"; break;
  215646. case AUDCLNT_E_DEVICE_INVALIDATED: e << "AUDCLNT_E_DEVICE_INVALIDATED"; break;
  215647. case AUDCLNT_E_NOT_STOPPED: e << "AUDCLNT_E_NOT_STOPPED"; break;
  215648. case AUDCLNT_E_BUFFER_TOO_LARGE: e << "AUDCLNT_E_BUFFER_TOO_LARGE"; break;
  215649. case AUDCLNT_E_OUT_OF_ORDER: e << "AUDCLNT_E_OUT_OF_ORDER"; break;
  215650. case AUDCLNT_E_UNSUPPORTED_FORMAT: e << "AUDCLNT_E_UNSUPPORTED_FORMAT"; break;
  215651. case AUDCLNT_E_INVALID_SIZE: e << "AUDCLNT_E_INVALID_SIZE"; break;
  215652. case AUDCLNT_E_DEVICE_IN_USE: e << "AUDCLNT_E_DEVICE_IN_USE"; break;
  215653. case AUDCLNT_E_BUFFER_OPERATION_PENDING: e << "AUDCLNT_E_BUFFER_OPERATION_PENDING"; break;
  215654. case AUDCLNT_E_THREAD_NOT_REGISTERED: e << "AUDCLNT_E_THREAD_NOT_REGISTERED"; break;
  215655. case AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED: e << "AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED"; break;
  215656. case AUDCLNT_E_ENDPOINT_CREATE_FAILED: e << "AUDCLNT_E_ENDPOINT_CREATE_FAILED"; break;
  215657. case AUDCLNT_E_SERVICE_NOT_RUNNING: e << "AUDCLNT_E_SERVICE_NOT_RUNNING"; break;
  215658. case AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED: e << "AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED"; break;
  215659. case AUDCLNT_E_EXCLUSIVE_MODE_ONLY: e << "AUDCLNT_E_EXCLUSIVE_MODE_ONLY"; break;
  215660. case AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL: e << "AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL"; break;
  215661. case AUDCLNT_E_EVENTHANDLE_NOT_SET: e << "AUDCLNT_E_EVENTHANDLE_NOT_SET"; break;
  215662. case AUDCLNT_E_INCORRECT_BUFFER_SIZE: e << "AUDCLNT_E_INCORRECT_BUFFER_SIZE"; break;
  215663. case AUDCLNT_E_BUFFER_SIZE_ERROR: e << "AUDCLNT_E_BUFFER_SIZE_ERROR"; break;
  215664. case AUDCLNT_S_BUFFER_EMPTY: e << "AUDCLNT_S_BUFFER_EMPTY"; break;
  215665. case AUDCLNT_S_THREAD_ALREADY_REGISTERED: e << "AUDCLNT_S_THREAD_ALREADY_REGISTERED"; break;
  215666. default: e << String::toHexString ((int) hr); break;
  215667. }
  215668. DBG (e);
  215669. jassertfalse;
  215670. }
  215671. #endif
  215672. }
  215673. #undef check
  215674. bool check (HRESULT hr)
  215675. {
  215676. logFailure (hr);
  215677. return SUCCEEDED (hr);
  215678. }
  215679. const String getDeviceID (IMMDevice* const device)
  215680. {
  215681. String s;
  215682. WCHAR* deviceId = 0;
  215683. if (check (device->GetId (&deviceId)))
  215684. {
  215685. s = String (deviceId);
  215686. CoTaskMemFree (deviceId);
  215687. }
  215688. return s;
  215689. }
  215690. EDataFlow getDataFlow (const ComSmartPtr<IMMDevice>& device)
  215691. {
  215692. EDataFlow flow = eRender;
  215693. ComSmartPtr <IMMEndpoint> endPoint;
  215694. if (check (device.QueryInterface (__uuidof (IMMEndpoint), endPoint)))
  215695. (void) check (endPoint->GetDataFlow (&flow));
  215696. return flow;
  215697. }
  215698. int refTimeToSamples (const REFERENCE_TIME& t, const double sampleRate) throw()
  215699. {
  215700. return roundDoubleToInt (sampleRate * ((double) t) * 0.0000001);
  215701. }
  215702. void copyWavFormat (WAVEFORMATEXTENSIBLE& dest, const WAVEFORMATEX* const src) throw()
  215703. {
  215704. memcpy (&dest, src, src->wFormatTag == WAVE_FORMAT_EXTENSIBLE ? sizeof (WAVEFORMATEXTENSIBLE)
  215705. : sizeof (WAVEFORMATEX));
  215706. }
  215707. class WASAPIDeviceBase
  215708. {
  215709. public:
  215710. WASAPIDeviceBase (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  215711. : device (device_),
  215712. sampleRate (0),
  215713. numChannels (0),
  215714. actualNumChannels (0),
  215715. defaultSampleRate (0),
  215716. minBufferSize (0),
  215717. defaultBufferSize (0),
  215718. latencySamples (0),
  215719. useExclusiveMode (useExclusiveMode_)
  215720. {
  215721. clientEvent = CreateEvent (0, false, false, _T("JuceWASAPI"));
  215722. ComSmartPtr <IAudioClient> tempClient (createClient());
  215723. if (tempClient == 0)
  215724. return;
  215725. REFERENCE_TIME defaultPeriod, minPeriod;
  215726. if (! check (tempClient->GetDevicePeriod (&defaultPeriod, &minPeriod)))
  215727. return;
  215728. WAVEFORMATEX* mixFormat = 0;
  215729. if (! check (tempClient->GetMixFormat (&mixFormat)))
  215730. return;
  215731. WAVEFORMATEXTENSIBLE format;
  215732. copyWavFormat (format, mixFormat);
  215733. CoTaskMemFree (mixFormat);
  215734. actualNumChannels = numChannels = format.Format.nChannels;
  215735. defaultSampleRate = format.Format.nSamplesPerSec;
  215736. minBufferSize = refTimeToSamples (minPeriod, defaultSampleRate);
  215737. defaultBufferSize = refTimeToSamples (defaultPeriod, defaultSampleRate);
  215738. rates.addUsingDefaultSort (defaultSampleRate);
  215739. static const double ratesToTest[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  215740. for (int i = 0; i < numElementsInArray (ratesToTest); ++i)
  215741. {
  215742. if (ratesToTest[i] == defaultSampleRate)
  215743. continue;
  215744. format.Format.nSamplesPerSec = roundDoubleToInt (ratesToTest[i]);
  215745. if (SUCCEEDED (tempClient->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  215746. (WAVEFORMATEX*) &format, 0)))
  215747. if (! rates.contains (ratesToTest[i]))
  215748. rates.addUsingDefaultSort (ratesToTest[i]);
  215749. }
  215750. }
  215751. ~WASAPIDeviceBase()
  215752. {
  215753. device = 0;
  215754. CloseHandle (clientEvent);
  215755. }
  215756. bool isOk() const throw() { return defaultBufferSize > 0 && defaultSampleRate > 0; }
  215757. bool openClient (const double newSampleRate, const BigInteger& newChannels)
  215758. {
  215759. sampleRate = newSampleRate;
  215760. channels = newChannels;
  215761. channels.setRange (actualNumChannels, channels.getHighestBit() + 1 - actualNumChannels, false);
  215762. numChannels = channels.getHighestBit() + 1;
  215763. if (numChannels == 0)
  215764. return true;
  215765. client = createClient();
  215766. if (client != 0
  215767. && (tryInitialisingWithFormat (true, 4) || tryInitialisingWithFormat (false, 4)
  215768. || tryInitialisingWithFormat (false, 3) || tryInitialisingWithFormat (false, 2)))
  215769. {
  215770. channelMaps.clear();
  215771. for (int i = 0; i <= channels.getHighestBit(); ++i)
  215772. if (channels[i])
  215773. channelMaps.add (i);
  215774. REFERENCE_TIME latency;
  215775. if (check (client->GetStreamLatency (&latency)))
  215776. latencySamples = refTimeToSamples (latency, sampleRate);
  215777. (void) check (client->GetBufferSize (&actualBufferSize));
  215778. return check (client->SetEventHandle (clientEvent));
  215779. }
  215780. return false;
  215781. }
  215782. void closeClient()
  215783. {
  215784. if (client != 0)
  215785. client->Stop();
  215786. client = 0;
  215787. ResetEvent (clientEvent);
  215788. }
  215789. ComSmartPtr <IMMDevice> device;
  215790. ComSmartPtr <IAudioClient> client;
  215791. double sampleRate, defaultSampleRate;
  215792. int numChannels, actualNumChannels;
  215793. int minBufferSize, defaultBufferSize, latencySamples;
  215794. const bool useExclusiveMode;
  215795. Array <double> rates;
  215796. HANDLE clientEvent;
  215797. BigInteger channels;
  215798. Array <int> channelMaps;
  215799. UINT32 actualBufferSize;
  215800. int bytesPerSample;
  215801. virtual void updateFormat (bool isFloat) = 0;
  215802. private:
  215803. const ComSmartPtr <IAudioClient> createClient()
  215804. {
  215805. ComSmartPtr <IAudioClient> client;
  215806. if (device != 0)
  215807. {
  215808. HRESULT hr = device->Activate (__uuidof (IAudioClient), CLSCTX_INPROC_SERVER, 0, (void**) client.resetAndGetPointerAddress());
  215809. logFailure (hr);
  215810. }
  215811. return client;
  215812. }
  215813. bool tryInitialisingWithFormat (const bool useFloat, const int bytesPerSampleToTry)
  215814. {
  215815. WAVEFORMATEXTENSIBLE format;
  215816. zerostruct (format);
  215817. if (numChannels <= 2 && bytesPerSampleToTry <= 2)
  215818. {
  215819. format.Format.wFormatTag = WAVE_FORMAT_PCM;
  215820. }
  215821. else
  215822. {
  215823. format.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
  215824. format.Format.cbSize = sizeof (WAVEFORMATEXTENSIBLE) - sizeof (WAVEFORMATEX);
  215825. }
  215826. format.Format.nSamplesPerSec = roundDoubleToInt (sampleRate);
  215827. format.Format.nChannels = (WORD) numChannels;
  215828. format.Format.wBitsPerSample = (WORD) (8 * bytesPerSampleToTry);
  215829. format.Format.nAvgBytesPerSec = (DWORD) (format.Format.nSamplesPerSec * numChannels * bytesPerSampleToTry);
  215830. format.Format.nBlockAlign = (WORD) (numChannels * bytesPerSampleToTry);
  215831. format.SubFormat = useFloat ? KSDATAFORMAT_SUBTYPE_IEEE_FLOAT : KSDATAFORMAT_SUBTYPE_PCM;
  215832. format.Samples.wValidBitsPerSample = format.Format.wBitsPerSample;
  215833. switch (numChannels)
  215834. {
  215835. case 1: format.dwChannelMask = SPEAKER_FRONT_CENTER; break;
  215836. case 2: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT; break;
  215837. case 4: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  215838. case 6: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  215839. 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;
  215840. default: break;
  215841. }
  215842. WAVEFORMATEXTENSIBLE* nearestFormat = 0;
  215843. HRESULT hr = client->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  215844. (WAVEFORMATEX*) &format, useExclusiveMode ? 0 : (WAVEFORMATEX**) &nearestFormat);
  215845. logFailure (hr);
  215846. if (hr == S_FALSE && format.Format.nSamplesPerSec == nearestFormat->Format.nSamplesPerSec)
  215847. {
  215848. copyWavFormat (format, (WAVEFORMATEX*) nearestFormat);
  215849. hr = S_OK;
  215850. }
  215851. CoTaskMemFree (nearestFormat);
  215852. REFERENCE_TIME defaultPeriod = 0, minPeriod = 0;
  215853. if (useExclusiveMode)
  215854. check (client->GetDevicePeriod (&defaultPeriod, &minPeriod));
  215855. GUID session;
  215856. if (hr == S_OK
  215857. && check (client->Initialize (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  215858. AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
  215859. defaultPeriod, defaultPeriod, (WAVEFORMATEX*) &format, &session)))
  215860. {
  215861. actualNumChannels = format.Format.nChannels;
  215862. const bool isFloat = format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE && format.SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
  215863. bytesPerSample = format.Format.wBitsPerSample / 8;
  215864. updateFormat (isFloat);
  215865. return true;
  215866. }
  215867. return false;
  215868. }
  215869. WASAPIDeviceBase (const WASAPIDeviceBase&);
  215870. WASAPIDeviceBase& operator= (const WASAPIDeviceBase&);
  215871. };
  215872. class WASAPIInputDevice : public WASAPIDeviceBase
  215873. {
  215874. public:
  215875. WASAPIInputDevice (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  215876. : WASAPIDeviceBase (device_, useExclusiveMode_),
  215877. reservoir (1, 1)
  215878. {
  215879. }
  215880. ~WASAPIInputDevice()
  215881. {
  215882. close();
  215883. }
  215884. bool open (const double newSampleRate, const BigInteger& newChannels)
  215885. {
  215886. reservoirSize = 0;
  215887. reservoirCapacity = 16384;
  215888. reservoir.setSize (actualNumChannels * reservoirCapacity * sizeof (float));
  215889. return openClient (newSampleRate, newChannels)
  215890. && (numChannels == 0 || check (client->GetService (__uuidof (IAudioCaptureClient), (void**) captureClient.resetAndGetPointerAddress())));
  215891. }
  215892. void close()
  215893. {
  215894. closeClient();
  215895. captureClient = 0;
  215896. reservoir.setSize (0);
  215897. }
  215898. void updateFormat (bool isFloat)
  215899. {
  215900. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> NativeType;
  215901. if (isFloat)
  215902. converter = new AudioData::ConverterInstance <AudioData::Pointer <AudioData::Float32, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>, NativeType> (actualNumChannels, 1);
  215903. else if (bytesPerSample == 4)
  215904. converter = new AudioData::ConverterInstance <AudioData::Pointer <AudioData::Int32, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>, NativeType> (actualNumChannels, 1);
  215905. else if (bytesPerSample == 3)
  215906. converter = new AudioData::ConverterInstance <AudioData::Pointer <AudioData::Int24, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>, NativeType> (actualNumChannels, 1);
  215907. else
  215908. converter = new AudioData::ConverterInstance <AudioData::Pointer <AudioData::Int16, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>, NativeType> (actualNumChannels, 1);
  215909. }
  215910. void copyBuffers (float** destBuffers, int numDestBuffers, int bufferSize, Thread& thread)
  215911. {
  215912. if (numChannels <= 0)
  215913. return;
  215914. int offset = 0;
  215915. while (bufferSize > 0)
  215916. {
  215917. if (reservoirSize > 0) // There's stuff in the reservoir, so use that...
  215918. {
  215919. const int samplesToDo = jmin (bufferSize, (int) reservoirSize);
  215920. for (int i = 0; i < numDestBuffers; ++i)
  215921. converter->convertSamples (destBuffers[i] + offset, 0, reservoir.getData(), channelMaps.getUnchecked(i), samplesToDo);
  215922. bufferSize -= samplesToDo;
  215923. offset += samplesToDo;
  215924. reservoirSize -= samplesToDo;
  215925. }
  215926. else
  215927. {
  215928. UINT32 packetLength = 0;
  215929. if (! check (captureClient->GetNextPacketSize (&packetLength)))
  215930. break;
  215931. if (packetLength == 0)
  215932. {
  215933. if (thread.threadShouldExit())
  215934. break;
  215935. Thread::sleep (1);
  215936. continue;
  215937. }
  215938. uint8* inputData = 0;
  215939. UINT32 numSamplesAvailable;
  215940. DWORD flags;
  215941. if (check (captureClient->GetBuffer (&inputData, &numSamplesAvailable, &flags, 0, 0)))
  215942. {
  215943. const int samplesToDo = jmin (bufferSize, (int) numSamplesAvailable);
  215944. for (int i = 0; i < numDestBuffers; ++i)
  215945. converter->convertSamples (destBuffers[i] + offset, 0, inputData, channelMaps.getUnchecked(i), samplesToDo);
  215946. bufferSize -= samplesToDo;
  215947. offset += samplesToDo;
  215948. if (samplesToDo < (int) numSamplesAvailable)
  215949. {
  215950. reservoirSize = jmin ((int) (numSamplesAvailable - samplesToDo), reservoirCapacity);
  215951. memcpy ((uint8*) reservoir.getData(), inputData + bytesPerSample * actualNumChannels * samplesToDo,
  215952. bytesPerSample * actualNumChannels * reservoirSize);
  215953. }
  215954. captureClient->ReleaseBuffer (numSamplesAvailable);
  215955. }
  215956. }
  215957. }
  215958. }
  215959. ComSmartPtr <IAudioCaptureClient> captureClient;
  215960. MemoryBlock reservoir;
  215961. int reservoirSize, reservoirCapacity;
  215962. ScopedPointer <AudioData::Converter> converter;
  215963. private:
  215964. WASAPIInputDevice (const WASAPIInputDevice&);
  215965. WASAPIInputDevice& operator= (const WASAPIInputDevice&);
  215966. };
  215967. class WASAPIOutputDevice : public WASAPIDeviceBase
  215968. {
  215969. public:
  215970. WASAPIOutputDevice (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  215971. : WASAPIDeviceBase (device_, useExclusiveMode_)
  215972. {
  215973. }
  215974. ~WASAPIOutputDevice()
  215975. {
  215976. close();
  215977. }
  215978. bool open (const double newSampleRate, const BigInteger& newChannels)
  215979. {
  215980. return openClient (newSampleRate, newChannels)
  215981. && (numChannels == 0 || check (client->GetService (__uuidof (IAudioRenderClient), (void**) renderClient.resetAndGetPointerAddress())));
  215982. }
  215983. void close()
  215984. {
  215985. closeClient();
  215986. renderClient = 0;
  215987. }
  215988. void updateFormat (bool isFloat)
  215989. {
  215990. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> NativeType;
  215991. if (isFloat)
  215992. converter = new AudioData::ConverterInstance <NativeType, AudioData::Pointer <AudioData::Float32, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> > (1, actualNumChannels);
  215993. else if (bytesPerSample == 4)
  215994. converter = new AudioData::ConverterInstance <NativeType, AudioData::Pointer <AudioData::Int32, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> > (1, actualNumChannels);
  215995. else if (bytesPerSample == 3)
  215996. converter = new AudioData::ConverterInstance <NativeType, AudioData::Pointer <AudioData::Int24, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> > (1, actualNumChannels);
  215997. else
  215998. converter = new AudioData::ConverterInstance <NativeType, AudioData::Pointer <AudioData::Int16, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> > (1, actualNumChannels);
  215999. }
  216000. void copyBuffers (const float** const srcBuffers, const int numSrcBuffers, int bufferSize, Thread& thread)
  216001. {
  216002. if (numChannels <= 0)
  216003. return;
  216004. int offset = 0;
  216005. while (bufferSize > 0)
  216006. {
  216007. UINT32 padding = 0;
  216008. if (! check (client->GetCurrentPadding (&padding)))
  216009. return;
  216010. int samplesToDo = useExclusiveMode ? bufferSize
  216011. : jmin ((int) (actualBufferSize - padding), bufferSize);
  216012. if (samplesToDo <= 0)
  216013. {
  216014. if (thread.threadShouldExit())
  216015. break;
  216016. Thread::sleep (0);
  216017. continue;
  216018. }
  216019. uint8* outputData = 0;
  216020. if (check (renderClient->GetBuffer (samplesToDo, &outputData)))
  216021. {
  216022. for (int i = 0; i < numSrcBuffers; ++i)
  216023. converter->convertSamples (outputData, channelMaps.getUnchecked(i), srcBuffers[i] + offset, 0, samplesToDo);
  216024. renderClient->ReleaseBuffer (samplesToDo, 0);
  216025. offset += samplesToDo;
  216026. bufferSize -= samplesToDo;
  216027. }
  216028. }
  216029. }
  216030. ComSmartPtr <IAudioRenderClient> renderClient;
  216031. ScopedPointer <AudioData::Converter> converter;
  216032. private:
  216033. WASAPIOutputDevice (const WASAPIOutputDevice&);
  216034. WASAPIOutputDevice& operator= (const WASAPIOutputDevice&);
  216035. };
  216036. class WASAPIAudioIODevice : public AudioIODevice,
  216037. public Thread
  216038. {
  216039. public:
  216040. WASAPIAudioIODevice (const String& deviceName,
  216041. const String& outputDeviceId_,
  216042. const String& inputDeviceId_,
  216043. const bool useExclusiveMode_)
  216044. : AudioIODevice (deviceName, "Windows Audio"),
  216045. Thread ("Juce WASAPI"),
  216046. isOpen_ (false),
  216047. isStarted (false),
  216048. outputDeviceId (outputDeviceId_),
  216049. inputDeviceId (inputDeviceId_),
  216050. useExclusiveMode (useExclusiveMode_),
  216051. currentBufferSizeSamples (0),
  216052. currentSampleRate (0),
  216053. callback (0)
  216054. {
  216055. }
  216056. ~WASAPIAudioIODevice()
  216057. {
  216058. close();
  216059. }
  216060. bool initialise()
  216061. {
  216062. double defaultSampleRateIn = 0, defaultSampleRateOut = 0;
  216063. int minBufferSizeIn = 0, defaultBufferSizeIn = 0, minBufferSizeOut = 0, defaultBufferSizeOut = 0;
  216064. latencyIn = latencyOut = 0;
  216065. Array <double> ratesIn, ratesOut;
  216066. if (createDevices())
  216067. {
  216068. jassert (inputDevice != 0 || outputDevice != 0);
  216069. if (inputDevice != 0 && outputDevice != 0)
  216070. {
  216071. defaultSampleRate = jmin (inputDevice->defaultSampleRate, outputDevice->defaultSampleRate);
  216072. minBufferSize = jmin (inputDevice->minBufferSize, outputDevice->minBufferSize);
  216073. defaultBufferSize = jmax (inputDevice->defaultBufferSize, outputDevice->defaultBufferSize);
  216074. sampleRates = inputDevice->rates;
  216075. sampleRates.removeValuesNotIn (outputDevice->rates);
  216076. }
  216077. else
  216078. {
  216079. WASAPIDeviceBase* d = inputDevice != 0 ? static_cast<WASAPIDeviceBase*> (inputDevice)
  216080. : static_cast<WASAPIDeviceBase*> (outputDevice);
  216081. defaultSampleRate = d->defaultSampleRate;
  216082. minBufferSize = d->minBufferSize;
  216083. defaultBufferSize = d->defaultBufferSize;
  216084. sampleRates = d->rates;
  216085. }
  216086. bufferSizes.addUsingDefaultSort (defaultBufferSize);
  216087. if (minBufferSize != defaultBufferSize)
  216088. bufferSizes.addUsingDefaultSort (minBufferSize);
  216089. int n = 64;
  216090. for (int i = 0; i < 40; ++i)
  216091. {
  216092. if (n >= minBufferSize && n <= 2048 && ! bufferSizes.contains (n))
  216093. bufferSizes.addUsingDefaultSort (n);
  216094. n += (n < 512) ? 32 : (n < 1024 ? 64 : 128);
  216095. }
  216096. return true;
  216097. }
  216098. return false;
  216099. }
  216100. const StringArray getOutputChannelNames()
  216101. {
  216102. StringArray outChannels;
  216103. if (outputDevice != 0)
  216104. for (int i = 1; i <= outputDevice->actualNumChannels; ++i)
  216105. outChannels.add ("Output channel " + String (i));
  216106. return outChannels;
  216107. }
  216108. const StringArray getInputChannelNames()
  216109. {
  216110. StringArray inChannels;
  216111. if (inputDevice != 0)
  216112. for (int i = 1; i <= inputDevice->actualNumChannels; ++i)
  216113. inChannels.add ("Input channel " + String (i));
  216114. return inChannels;
  216115. }
  216116. int getNumSampleRates() { return sampleRates.size(); }
  216117. double getSampleRate (int index) { return sampleRates [index]; }
  216118. int getNumBufferSizesAvailable() { return bufferSizes.size(); }
  216119. int getBufferSizeSamples (int index) { return bufferSizes [index]; }
  216120. int getDefaultBufferSize() { return defaultBufferSize; }
  216121. int getCurrentBufferSizeSamples() { return currentBufferSizeSamples; }
  216122. double getCurrentSampleRate() { return currentSampleRate; }
  216123. int getCurrentBitDepth() { return 32; }
  216124. int getOutputLatencyInSamples() { return latencyOut; }
  216125. int getInputLatencyInSamples() { return latencyIn; }
  216126. const BigInteger getActiveOutputChannels() const { return outputDevice != 0 ? outputDevice->channels : BigInteger(); }
  216127. const BigInteger getActiveInputChannels() const { return inputDevice != 0 ? inputDevice->channels : BigInteger(); }
  216128. const String getLastError() { return lastError; }
  216129. const String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  216130. double sampleRate, int bufferSizeSamples)
  216131. {
  216132. close();
  216133. lastError = String::empty;
  216134. if (sampleRates.size() == 0 && inputDevice != 0 && outputDevice != 0)
  216135. {
  216136. lastError = "The input and output devices don't share a common sample rate!";
  216137. return lastError;
  216138. }
  216139. currentBufferSizeSamples = bufferSizeSamples <= 0 ? defaultBufferSize : jmax (bufferSizeSamples, minBufferSize);
  216140. currentSampleRate = sampleRate > 0 ? sampleRate : defaultSampleRate;
  216141. if (inputDevice != 0 && ! inputDevice->open (currentSampleRate, inputChannels))
  216142. {
  216143. lastError = "Couldn't open the input device!";
  216144. return lastError;
  216145. }
  216146. if (outputDevice != 0 && ! outputDevice->open (currentSampleRate, outputChannels))
  216147. {
  216148. close();
  216149. lastError = "Couldn't open the output device!";
  216150. return lastError;
  216151. }
  216152. if (inputDevice != 0)
  216153. ResetEvent (inputDevice->clientEvent);
  216154. if (outputDevice != 0)
  216155. ResetEvent (outputDevice->clientEvent);
  216156. startThread (8);
  216157. Thread::sleep (5);
  216158. if (inputDevice != 0 && inputDevice->client != 0)
  216159. {
  216160. latencyIn = inputDevice->latencySamples + inputDevice->actualBufferSize + inputDevice->minBufferSize;
  216161. HRESULT hr = inputDevice->client->Start();
  216162. logFailure (hr); //xxx handle this
  216163. }
  216164. if (outputDevice != 0 && outputDevice->client != 0)
  216165. {
  216166. latencyOut = outputDevice->latencySamples + outputDevice->actualBufferSize + outputDevice->minBufferSize;
  216167. HRESULT hr = outputDevice->client->Start();
  216168. logFailure (hr); //xxx handle this
  216169. }
  216170. isOpen_ = true;
  216171. return lastError;
  216172. }
  216173. void close()
  216174. {
  216175. stop();
  216176. if (inputDevice != 0)
  216177. SetEvent (inputDevice->clientEvent);
  216178. if (outputDevice != 0)
  216179. SetEvent (outputDevice->clientEvent);
  216180. stopThread (5000);
  216181. if (inputDevice != 0)
  216182. inputDevice->close();
  216183. if (outputDevice != 0)
  216184. outputDevice->close();
  216185. isOpen_ = false;
  216186. }
  216187. bool isOpen() { return isOpen_ && isThreadRunning(); }
  216188. bool isPlaying() { return isStarted && isOpen_ && isThreadRunning(); }
  216189. void start (AudioIODeviceCallback* call)
  216190. {
  216191. if (isOpen_ && call != 0 && ! isStarted)
  216192. {
  216193. if (! isThreadRunning())
  216194. {
  216195. // something's gone wrong and the thread's stopped..
  216196. isOpen_ = false;
  216197. return;
  216198. }
  216199. call->audioDeviceAboutToStart (this);
  216200. const ScopedLock sl (startStopLock);
  216201. callback = call;
  216202. isStarted = true;
  216203. }
  216204. }
  216205. void stop()
  216206. {
  216207. if (isStarted)
  216208. {
  216209. AudioIODeviceCallback* const callbackLocal = callback;
  216210. {
  216211. const ScopedLock sl (startStopLock);
  216212. isStarted = false;
  216213. }
  216214. if (callbackLocal != 0)
  216215. callbackLocal->audioDeviceStopped();
  216216. }
  216217. }
  216218. void setMMThreadPriority()
  216219. {
  216220. DynamicLibraryLoader dll ("avrt.dll");
  216221. DynamicLibraryImport (AvSetMmThreadCharacteristics, avSetMmThreadCharacteristics, HANDLE, dll, (LPCTSTR, LPDWORD))
  216222. DynamicLibraryImport (AvSetMmThreadPriority, avSetMmThreadPriority, HANDLE, dll, (HANDLE, AVRT_PRIORITY))
  216223. if (avSetMmThreadCharacteristics != 0 && avSetMmThreadPriority != 0)
  216224. {
  216225. DWORD dummy = 0;
  216226. HANDLE h = avSetMmThreadCharacteristics (_T("Pro Audio"), &dummy);
  216227. if (h != 0)
  216228. avSetMmThreadPriority (h, AVRT_PRIORITY_NORMAL);
  216229. }
  216230. }
  216231. void run()
  216232. {
  216233. setMMThreadPriority();
  216234. const int bufferSize = currentBufferSizeSamples;
  216235. HANDLE events[2];
  216236. int numEvents = 0;
  216237. if (inputDevice != 0)
  216238. events [numEvents++] = inputDevice->clientEvent;
  216239. if (outputDevice != 0)
  216240. events [numEvents++] = outputDevice->clientEvent;
  216241. const int numInputBuffers = getActiveInputChannels().countNumberOfSetBits();
  216242. const int numOutputBuffers = getActiveOutputChannels().countNumberOfSetBits();
  216243. AudioSampleBuffer ins (jmax (1, numInputBuffers), bufferSize + 32);
  216244. AudioSampleBuffer outs (jmax (1, numOutputBuffers), bufferSize + 32);
  216245. float** const inputBuffers = ins.getArrayOfChannels();
  216246. float** const outputBuffers = outs.getArrayOfChannels();
  216247. ins.clear();
  216248. while (! threadShouldExit())
  216249. {
  216250. const DWORD result = useExclusiveMode ? (inputDevice != 0 ? WaitForSingleObject (inputDevice->clientEvent, 1000) : S_OK)
  216251. : WaitForMultipleObjects (numEvents, events, true, 1000);
  216252. if (result == WAIT_TIMEOUT)
  216253. continue;
  216254. if (threadShouldExit())
  216255. break;
  216256. if (inputDevice != 0)
  216257. inputDevice->copyBuffers (inputBuffers, numInputBuffers, bufferSize, *this);
  216258. // Make the callback..
  216259. {
  216260. const ScopedLock sl (startStopLock);
  216261. if (isStarted)
  216262. {
  216263. JUCE_TRY
  216264. {
  216265. callback->audioDeviceIOCallback ((const float**) inputBuffers,
  216266. numInputBuffers,
  216267. outputBuffers,
  216268. numOutputBuffers,
  216269. bufferSize);
  216270. }
  216271. JUCE_CATCH_EXCEPTION
  216272. }
  216273. else
  216274. {
  216275. outs.clear();
  216276. }
  216277. }
  216278. if (useExclusiveMode && WaitForSingleObject (outputDevice->clientEvent, 1000) == WAIT_TIMEOUT)
  216279. continue;
  216280. if (outputDevice != 0)
  216281. outputDevice->copyBuffers ((const float**) outputBuffers, numOutputBuffers, bufferSize, *this);
  216282. }
  216283. }
  216284. juce_UseDebuggingNewOperator
  216285. String outputDeviceId, inputDeviceId;
  216286. String lastError;
  216287. private:
  216288. // Device stats...
  216289. ScopedPointer<WASAPIInputDevice> inputDevice;
  216290. ScopedPointer<WASAPIOutputDevice> outputDevice;
  216291. const bool useExclusiveMode;
  216292. double defaultSampleRate;
  216293. int minBufferSize, defaultBufferSize;
  216294. int latencyIn, latencyOut;
  216295. Array <double> sampleRates;
  216296. Array <int> bufferSizes;
  216297. // Active state...
  216298. bool isOpen_, isStarted;
  216299. int currentBufferSizeSamples;
  216300. double currentSampleRate;
  216301. AudioIODeviceCallback* callback;
  216302. CriticalSection startStopLock;
  216303. bool createDevices()
  216304. {
  216305. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  216306. if (! check (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  216307. return false;
  216308. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  216309. if (! check (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, deviceCollection.resetAndGetPointerAddress())))
  216310. return false;
  216311. UINT32 numDevices = 0;
  216312. if (! check (deviceCollection->GetCount (&numDevices)))
  216313. return false;
  216314. for (UINT32 i = 0; i < numDevices; ++i)
  216315. {
  216316. ComSmartPtr <IMMDevice> device;
  216317. if (! check (deviceCollection->Item (i, device.resetAndGetPointerAddress())))
  216318. continue;
  216319. const String deviceId (getDeviceID (device));
  216320. if (deviceId.isEmpty())
  216321. continue;
  216322. const EDataFlow flow = getDataFlow (device);
  216323. if (deviceId == inputDeviceId && flow == eCapture)
  216324. inputDevice = new WASAPIInputDevice (device, useExclusiveMode);
  216325. else if (deviceId == outputDeviceId && flow == eRender)
  216326. outputDevice = new WASAPIOutputDevice (device, useExclusiveMode);
  216327. }
  216328. return (outputDeviceId.isEmpty() || (outputDevice != 0 && outputDevice->isOk()))
  216329. && (inputDeviceId.isEmpty() || (inputDevice != 0 && inputDevice->isOk()));
  216330. }
  216331. WASAPIAudioIODevice (const WASAPIAudioIODevice&);
  216332. WASAPIAudioIODevice& operator= (const WASAPIAudioIODevice&);
  216333. };
  216334. class WASAPIAudioIODeviceType : public AudioIODeviceType
  216335. {
  216336. public:
  216337. WASAPIAudioIODeviceType()
  216338. : AudioIODeviceType ("Windows Audio"),
  216339. hasScanned (false)
  216340. {
  216341. }
  216342. ~WASAPIAudioIODeviceType()
  216343. {
  216344. }
  216345. void scanForDevices()
  216346. {
  216347. hasScanned = true;
  216348. outputDeviceNames.clear();
  216349. inputDeviceNames.clear();
  216350. outputDeviceIds.clear();
  216351. inputDeviceIds.clear();
  216352. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  216353. if (! check (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  216354. return;
  216355. const String defaultRenderer = getDefaultEndpoint (enumerator, false);
  216356. const String defaultCapture = getDefaultEndpoint (enumerator, true);
  216357. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  216358. UINT32 numDevices = 0;
  216359. if (! (check (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, deviceCollection.resetAndGetPointerAddress()))
  216360. && check (deviceCollection->GetCount (&numDevices))))
  216361. return;
  216362. for (UINT32 i = 0; i < numDevices; ++i)
  216363. {
  216364. ComSmartPtr <IMMDevice> device;
  216365. if (! check (deviceCollection->Item (i, device.resetAndGetPointerAddress())))
  216366. continue;
  216367. const String deviceId (getDeviceID (device));
  216368. DWORD state = 0;
  216369. if (! check (device->GetState (&state)))
  216370. continue;
  216371. if (state != DEVICE_STATE_ACTIVE)
  216372. continue;
  216373. String name;
  216374. {
  216375. ComSmartPtr <IPropertyStore> properties;
  216376. if (! check (device->OpenPropertyStore (STGM_READ, properties.resetAndGetPointerAddress())))
  216377. continue;
  216378. PROPVARIANT value;
  216379. PropVariantInit (&value);
  216380. if (check (properties->GetValue (PKEY_Device_FriendlyName, &value)))
  216381. name = value.pwszVal;
  216382. PropVariantClear (&value);
  216383. }
  216384. const EDataFlow flow = getDataFlow (device);
  216385. if (flow == eRender)
  216386. {
  216387. const int index = (deviceId == defaultRenderer) ? 0 : -1;
  216388. outputDeviceIds.insert (index, deviceId);
  216389. outputDeviceNames.insert (index, name);
  216390. }
  216391. else if (flow == eCapture)
  216392. {
  216393. const int index = (deviceId == defaultCapture) ? 0 : -1;
  216394. inputDeviceIds.insert (index, deviceId);
  216395. inputDeviceNames.insert (index, name);
  216396. }
  216397. }
  216398. inputDeviceNames.appendNumbersToDuplicates (false, false);
  216399. outputDeviceNames.appendNumbersToDuplicates (false, false);
  216400. }
  216401. const StringArray getDeviceNames (bool wantInputNames) const
  216402. {
  216403. jassert (hasScanned); // need to call scanForDevices() before doing this
  216404. return wantInputNames ? inputDeviceNames
  216405. : outputDeviceNames;
  216406. }
  216407. int getDefaultDeviceIndex (bool /*forInput*/) const
  216408. {
  216409. jassert (hasScanned); // need to call scanForDevices() before doing this
  216410. return 0;
  216411. }
  216412. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  216413. {
  216414. jassert (hasScanned); // need to call scanForDevices() before doing this
  216415. WASAPIAudioIODevice* const d = dynamic_cast <WASAPIAudioIODevice*> (device);
  216416. return d == 0 ? -1 : (asInput ? inputDeviceIds.indexOf (d->inputDeviceId)
  216417. : outputDeviceIds.indexOf (d->outputDeviceId));
  216418. }
  216419. bool hasSeparateInputsAndOutputs() const { return true; }
  216420. AudioIODevice* createDevice (const String& outputDeviceName,
  216421. const String& inputDeviceName)
  216422. {
  216423. jassert (hasScanned); // need to call scanForDevices() before doing this
  216424. const bool useExclusiveMode = false;
  216425. ScopedPointer<WASAPIAudioIODevice> device;
  216426. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  216427. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  216428. if (outputIndex >= 0 || inputIndex >= 0)
  216429. {
  216430. device = new WASAPIAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  216431. : inputDeviceName,
  216432. outputDeviceIds [outputIndex],
  216433. inputDeviceIds [inputIndex],
  216434. useExclusiveMode);
  216435. if (! device->initialise())
  216436. device = 0;
  216437. }
  216438. return device.release();
  216439. }
  216440. juce_UseDebuggingNewOperator
  216441. StringArray outputDeviceNames, outputDeviceIds;
  216442. StringArray inputDeviceNames, inputDeviceIds;
  216443. private:
  216444. bool hasScanned;
  216445. static const String getDefaultEndpoint (IMMDeviceEnumerator* const enumerator, const bool forCapture)
  216446. {
  216447. String s;
  216448. IMMDevice* dev = 0;
  216449. if (check (enumerator->GetDefaultAudioEndpoint (forCapture ? eCapture : eRender,
  216450. eMultimedia, &dev)))
  216451. {
  216452. WCHAR* deviceId = 0;
  216453. if (check (dev->GetId (&deviceId)))
  216454. {
  216455. s = String (deviceId);
  216456. CoTaskMemFree (deviceId);
  216457. }
  216458. dev->Release();
  216459. }
  216460. return s;
  216461. }
  216462. WASAPIAudioIODeviceType (const WASAPIAudioIODeviceType&);
  216463. WASAPIAudioIODeviceType& operator= (const WASAPIAudioIODeviceType&);
  216464. };
  216465. }
  216466. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI()
  216467. {
  216468. return new WasapiClasses::WASAPIAudioIODeviceType();
  216469. }
  216470. #endif
  216471. /*** End of inlined file: juce_win32_WASAPI.cpp ***/
  216472. /*** Start of inlined file: juce_win32_CameraDevice.cpp ***/
  216473. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  216474. // compiled on its own).
  216475. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  216476. class DShowCameraDeviceInteral : public ChangeBroadcaster
  216477. {
  216478. public:
  216479. DShowCameraDeviceInteral (CameraDevice* const owner_,
  216480. const ComSmartPtr <ICaptureGraphBuilder2>& captureGraphBuilder_,
  216481. const ComSmartPtr <IBaseFilter>& filter_,
  216482. int minWidth, int minHeight,
  216483. int maxWidth, int maxHeight)
  216484. : owner (owner_),
  216485. captureGraphBuilder (captureGraphBuilder_),
  216486. filter (filter_),
  216487. ok (false),
  216488. imageNeedsFlipping (false),
  216489. width (0),
  216490. height (0),
  216491. activeUsers (0),
  216492. recordNextFrameTime (false),
  216493. previewMaxFPS (60)
  216494. {
  216495. HRESULT hr = graphBuilder.CoCreateInstance (CLSID_FilterGraph);
  216496. if (FAILED (hr))
  216497. return;
  216498. hr = captureGraphBuilder->SetFiltergraph (graphBuilder);
  216499. if (FAILED (hr))
  216500. return;
  216501. hr = graphBuilder.QueryInterface (IID_IMediaControl, mediaControl);
  216502. if (FAILED (hr))
  216503. return;
  216504. {
  216505. ComSmartPtr <IAMStreamConfig> streamConfig;
  216506. hr = captureGraphBuilder->FindInterface (&PIN_CATEGORY_CAPTURE, 0, filter,
  216507. IID_IAMStreamConfig, (void**) streamConfig.resetAndGetPointerAddress());
  216508. if (streamConfig != 0)
  216509. {
  216510. getVideoSizes (streamConfig);
  216511. if (! selectVideoSize (streamConfig, minWidth, minHeight, maxWidth, maxHeight))
  216512. return;
  216513. }
  216514. }
  216515. hr = graphBuilder->AddFilter (filter, _T("Video Capture"));
  216516. if (FAILED (hr))
  216517. return;
  216518. hr = smartTee.CoCreateInstance (CLSID_SmartTee);
  216519. if (FAILED (hr))
  216520. return;
  216521. hr = graphBuilder->AddFilter (smartTee, _T("Smart Tee"));
  216522. if (FAILED (hr))
  216523. return;
  216524. if (! connectFilters (filter, smartTee))
  216525. return;
  216526. ComSmartPtr <IBaseFilter> sampleGrabberBase;
  216527. hr = sampleGrabberBase.CoCreateInstance (CLSID_SampleGrabber);
  216528. if (FAILED (hr))
  216529. return;
  216530. hr = sampleGrabberBase.QueryInterface (IID_ISampleGrabber, sampleGrabber);
  216531. if (FAILED (hr))
  216532. return;
  216533. AM_MEDIA_TYPE mt;
  216534. zerostruct (mt);
  216535. mt.majortype = MEDIATYPE_Video;
  216536. mt.subtype = MEDIASUBTYPE_RGB24;
  216537. mt.formattype = FORMAT_VideoInfo;
  216538. sampleGrabber->SetMediaType (&mt);
  216539. callback = new GrabberCallback (*this);
  216540. hr = sampleGrabber->SetCallback (callback, 1);
  216541. hr = graphBuilder->AddFilter (sampleGrabberBase, _T("Sample Grabber"));
  216542. if (FAILED (hr))
  216543. return;
  216544. ComSmartPtr <IPin> grabberInputPin;
  216545. if (! (getPin (smartTee, PINDIR_OUTPUT, smartTeeCaptureOutputPin, "capture")
  216546. && getPin (smartTee, PINDIR_OUTPUT, smartTeePreviewOutputPin, "preview")
  216547. && getPin (sampleGrabberBase, PINDIR_INPUT, grabberInputPin)))
  216548. return;
  216549. hr = graphBuilder->Connect (smartTeePreviewOutputPin, grabberInputPin);
  216550. if (FAILED (hr))
  216551. return;
  216552. zerostruct (mt);
  216553. hr = sampleGrabber->GetConnectedMediaType (&mt);
  216554. VIDEOINFOHEADER* pVih = (VIDEOINFOHEADER*) (mt.pbFormat);
  216555. width = pVih->bmiHeader.biWidth;
  216556. height = pVih->bmiHeader.biHeight;
  216557. ComSmartPtr <IBaseFilter> nullFilter;
  216558. hr = nullFilter.CoCreateInstance (CLSID_NullRenderer);
  216559. hr = graphBuilder->AddFilter (nullFilter, _T("Null Renderer"));
  216560. if (connectFilters (sampleGrabberBase, nullFilter)
  216561. && addGraphToRot())
  216562. {
  216563. activeImage = Image (Image::RGB, width, height, true);
  216564. loadingImage = Image (Image::RGB, width, height, true);
  216565. ok = true;
  216566. }
  216567. }
  216568. ~DShowCameraDeviceInteral()
  216569. {
  216570. if (mediaControl != 0)
  216571. mediaControl->Stop();
  216572. removeGraphFromRot();
  216573. for (int i = viewerComps.size(); --i >= 0;)
  216574. viewerComps.getUnchecked(i)->ownerDeleted();
  216575. callback = 0;
  216576. graphBuilder = 0;
  216577. sampleGrabber = 0;
  216578. mediaControl = 0;
  216579. filter = 0;
  216580. captureGraphBuilder = 0;
  216581. smartTee = 0;
  216582. smartTeePreviewOutputPin = 0;
  216583. smartTeeCaptureOutputPin = 0;
  216584. asfWriter = 0;
  216585. }
  216586. void addUser()
  216587. {
  216588. if (ok && activeUsers++ == 0)
  216589. mediaControl->Run();
  216590. }
  216591. void removeUser()
  216592. {
  216593. if (ok && --activeUsers == 0)
  216594. mediaControl->Stop();
  216595. }
  216596. int getPreviewMaxFPS() const
  216597. {
  216598. return previewMaxFPS;
  216599. }
  216600. void handleFrame (double /*time*/, BYTE* buffer, long /*bufferSize*/)
  216601. {
  216602. if (recordNextFrameTime)
  216603. {
  216604. const double defaultCameraLatency = 0.1;
  216605. firstRecordedTime = Time::getCurrentTime() - RelativeTime (defaultCameraLatency);
  216606. recordNextFrameTime = false;
  216607. ComSmartPtr <IPin> pin;
  216608. if (getPin (filter, PINDIR_OUTPUT, pin))
  216609. {
  216610. ComSmartPtr <IAMPushSource> pushSource;
  216611. HRESULT hr = pin.QueryInterface (IID_IAMPushSource, pushSource);
  216612. if (pushSource != 0)
  216613. {
  216614. REFERENCE_TIME latency = 0;
  216615. hr = pushSource->GetLatency (&latency);
  216616. firstRecordedTime = firstRecordedTime - RelativeTime ((double) latency);
  216617. }
  216618. }
  216619. }
  216620. {
  216621. const int lineStride = width * 3;
  216622. const ScopedLock sl (imageSwapLock);
  216623. {
  216624. const Image::BitmapData destData (loadingImage, 0, 0, width, height, true);
  216625. for (int i = 0; i < height; ++i)
  216626. memcpy (destData.getLinePointer ((height - 1) - i),
  216627. buffer + lineStride * i,
  216628. lineStride);
  216629. }
  216630. imageNeedsFlipping = true;
  216631. }
  216632. if (listeners.size() > 0)
  216633. callListeners (loadingImage);
  216634. sendChangeMessage (this);
  216635. }
  216636. void drawCurrentImage (Graphics& g, int x, int y, int w, int h)
  216637. {
  216638. if (imageNeedsFlipping)
  216639. {
  216640. const ScopedLock sl (imageSwapLock);
  216641. swapVariables (loadingImage, activeImage);
  216642. imageNeedsFlipping = false;
  216643. }
  216644. RectanglePlacement rp (RectanglePlacement::centred);
  216645. double dx = 0, dy = 0, dw = width, dh = height;
  216646. rp.applyTo (dx, dy, dw, dh, x, y, w, h);
  216647. const int rx = roundToInt (dx), ry = roundToInt (dy);
  216648. const int rw = roundToInt (dw), rh = roundToInt (dh);
  216649. g.saveState();
  216650. g.excludeClipRegion (Rectangle<int> (rx, ry, rw, rh));
  216651. g.fillAll (Colours::black);
  216652. g.restoreState();
  216653. g.drawImage (activeImage, rx, ry, rw, rh, 0, 0, width, height);
  216654. }
  216655. bool createFileCaptureFilter (const File& file, int quality)
  216656. {
  216657. removeFileCaptureFilter();
  216658. file.deleteFile();
  216659. mediaControl->Stop();
  216660. firstRecordedTime = Time();
  216661. recordNextFrameTime = true;
  216662. previewMaxFPS = 60;
  216663. HRESULT hr = asfWriter.CoCreateInstance (CLSID_WMAsfWriter);
  216664. if (SUCCEEDED (hr))
  216665. {
  216666. ComSmartPtr <IFileSinkFilter> fileSink;
  216667. hr = asfWriter.QueryInterface (IID_IFileSinkFilter, fileSink);
  216668. if (SUCCEEDED (hr))
  216669. {
  216670. hr = fileSink->SetFileName (file.getFullPathName(), 0);
  216671. if (SUCCEEDED (hr))
  216672. {
  216673. hr = graphBuilder->AddFilter (asfWriter, _T("AsfWriter"));
  216674. if (SUCCEEDED (hr))
  216675. {
  216676. ComSmartPtr <IConfigAsfWriter> asfConfig;
  216677. hr = asfWriter.QueryInterface (IID_IConfigAsfWriter, asfConfig);
  216678. asfConfig->SetIndexMode (true);
  216679. ComSmartPtr <IWMProfileManager> profileManager;
  216680. hr = WMCreateProfileManager (profileManager.resetAndGetPointerAddress());
  216681. // This gibberish is the DirectShow profile for a video-only wmv file.
  216682. String prof ("<profile version=\"589824\" storageformat=\"1\" name=\"Quality\" description=\"Quality type for output.\">"
  216683. "<streamconfig majortype=\"{73646976-0000-0010-8000-00AA00389B71}\" streamnumber=\"1\" "
  216684. "streamname=\"Video Stream\" inputname=\"Video409\" bitrate=\"894960\" "
  216685. "bufferwindow=\"0\" reliabletransport=\"1\" decodercomplexity=\"AU\" rfc1766langid=\"en-us\">"
  216686. "<videomediaprops maxkeyframespacing=\"50000000\" quality=\"90\"/>"
  216687. "<wmmediatype subtype=\"{33564D57-0000-0010-8000-00AA00389B71}\" bfixedsizesamples=\"0\" "
  216688. "btemporalcompression=\"1\" lsamplesize=\"0\">"
  216689. "<videoinfoheader dwbitrate=\"894960\" dwbiterrorrate=\"0\" avgtimeperframe=\"$AVGTIMEPERFRAME\">"
  216690. "<rcsource left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/>"
  216691. "<rctarget left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/>"
  216692. "<bitmapinfoheader biwidth=\"$WIDTH\" biheight=\"$HEIGHT\" biplanes=\"1\" bibitcount=\"24\" "
  216693. "bicompression=\"WMV3\" bisizeimage=\"0\" bixpelspermeter=\"0\" biypelspermeter=\"0\" "
  216694. "biclrused=\"0\" biclrimportant=\"0\"/>"
  216695. "</videoinfoheader>"
  216696. "</wmmediatype>"
  216697. "</streamconfig>"
  216698. "</profile>");
  216699. const int fps[] = { 10, 15, 30 };
  216700. int maxFramesPerSecond = fps [jlimit (0, numElementsInArray (fps) - 1, quality & 0xff)];
  216701. if ((quality & 0xff000000) != 0) // (internal hacky way to pass explicit frame rates for testing)
  216702. maxFramesPerSecond = (quality >> 24) & 0xff;
  216703. prof = prof.replace ("$WIDTH", String (width))
  216704. .replace ("$HEIGHT", String (height))
  216705. .replace ("$AVGTIMEPERFRAME", String (10000000 / maxFramesPerSecond));
  216706. ComSmartPtr <IWMProfile> currentProfile;
  216707. hr = profileManager->LoadProfileByData ((const WCHAR*) prof, currentProfile.resetAndGetPointerAddress());
  216708. hr = asfConfig->ConfigureFilterUsingProfile (currentProfile);
  216709. if (SUCCEEDED (hr))
  216710. {
  216711. ComSmartPtr <IPin> asfWriterInputPin;
  216712. if (getPin (asfWriter, PINDIR_INPUT, asfWriterInputPin, "Video Input 01"))
  216713. {
  216714. hr = graphBuilder->Connect (smartTeeCaptureOutputPin, asfWriterInputPin);
  216715. if (SUCCEEDED (hr) && ok && activeUsers > 0
  216716. && SUCCEEDED (mediaControl->Run()))
  216717. {
  216718. previewMaxFPS = (quality < 2) ? 15 : 25; // throttle back the preview comps to try to leave the cpu free for encoding
  216719. if ((quality & 0x00ff0000) != 0) // (internal hacky way to pass explicit frame rates for testing)
  216720. previewMaxFPS = (quality >> 16) & 0xff;
  216721. return true;
  216722. }
  216723. }
  216724. }
  216725. }
  216726. }
  216727. }
  216728. }
  216729. removeFileCaptureFilter();
  216730. if (ok && activeUsers > 0)
  216731. mediaControl->Run();
  216732. return false;
  216733. }
  216734. void removeFileCaptureFilter()
  216735. {
  216736. mediaControl->Stop();
  216737. if (asfWriter != 0)
  216738. {
  216739. graphBuilder->RemoveFilter (asfWriter);
  216740. asfWriter = 0;
  216741. }
  216742. if (ok && activeUsers > 0)
  216743. mediaControl->Run();
  216744. previewMaxFPS = 60;
  216745. }
  216746. void addListener (CameraDevice::Listener* listenerToAdd)
  216747. {
  216748. const ScopedLock sl (listenerLock);
  216749. if (listeners.size() == 0)
  216750. addUser();
  216751. listeners.addIfNotAlreadyThere (listenerToAdd);
  216752. }
  216753. void removeListener (CameraDevice::Listener* listenerToRemove)
  216754. {
  216755. const ScopedLock sl (listenerLock);
  216756. listeners.removeValue (listenerToRemove);
  216757. if (listeners.size() == 0)
  216758. removeUser();
  216759. }
  216760. void callListeners (const Image& image)
  216761. {
  216762. const ScopedLock sl (listenerLock);
  216763. for (int i = listeners.size(); --i >= 0;)
  216764. {
  216765. CameraDevice::Listener* const l = listeners[i];
  216766. if (l != 0)
  216767. l->imageReceived (image);
  216768. }
  216769. }
  216770. class DShowCaptureViewerComp : public Component,
  216771. public ChangeListener
  216772. {
  216773. public:
  216774. DShowCaptureViewerComp (DShowCameraDeviceInteral* const owner_)
  216775. : owner (owner_), maxFPS (15), lastRepaintTime (0)
  216776. {
  216777. setOpaque (true);
  216778. owner->addChangeListener (this);
  216779. owner->addUser();
  216780. owner->viewerComps.add (this);
  216781. setSize (owner->width, owner->height);
  216782. }
  216783. ~DShowCaptureViewerComp()
  216784. {
  216785. if (owner != 0)
  216786. {
  216787. owner->viewerComps.removeValue (this);
  216788. owner->removeUser();
  216789. owner->removeChangeListener (this);
  216790. }
  216791. }
  216792. void ownerDeleted()
  216793. {
  216794. owner = 0;
  216795. }
  216796. void paint (Graphics& g)
  216797. {
  216798. g.setColour (Colours::black);
  216799. g.setImageResamplingQuality (Graphics::lowResamplingQuality);
  216800. if (owner != 0)
  216801. owner->drawCurrentImage (g, 0, 0, getWidth(), getHeight());
  216802. else
  216803. g.fillAll (Colours::black);
  216804. }
  216805. void changeListenerCallback (void*)
  216806. {
  216807. const int64 now = Time::currentTimeMillis();
  216808. if (now >= lastRepaintTime + (1000 / maxFPS))
  216809. {
  216810. lastRepaintTime = now;
  216811. repaint();
  216812. if (owner != 0)
  216813. maxFPS = owner->getPreviewMaxFPS();
  216814. }
  216815. }
  216816. private:
  216817. DShowCameraDeviceInteral* owner;
  216818. int maxFPS;
  216819. int64 lastRepaintTime;
  216820. };
  216821. bool ok;
  216822. int width, height;
  216823. Time firstRecordedTime;
  216824. Array <DShowCaptureViewerComp*> viewerComps;
  216825. private:
  216826. CameraDevice* const owner;
  216827. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  216828. ComSmartPtr <IBaseFilter> filter;
  216829. ComSmartPtr <IBaseFilter> smartTee;
  216830. ComSmartPtr <IGraphBuilder> graphBuilder;
  216831. ComSmartPtr <ISampleGrabber> sampleGrabber;
  216832. ComSmartPtr <IMediaControl> mediaControl;
  216833. ComSmartPtr <IPin> smartTeePreviewOutputPin;
  216834. ComSmartPtr <IPin> smartTeeCaptureOutputPin;
  216835. ComSmartPtr <IBaseFilter> asfWriter;
  216836. int activeUsers;
  216837. Array <int> widths, heights;
  216838. DWORD graphRegistrationID;
  216839. CriticalSection imageSwapLock;
  216840. bool imageNeedsFlipping;
  216841. Image loadingImage;
  216842. Image activeImage;
  216843. bool recordNextFrameTime;
  216844. int previewMaxFPS;
  216845. void getVideoSizes (IAMStreamConfig* const streamConfig)
  216846. {
  216847. widths.clear();
  216848. heights.clear();
  216849. int count = 0, size = 0;
  216850. streamConfig->GetNumberOfCapabilities (&count, &size);
  216851. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  216852. {
  216853. for (int i = 0; i < count; ++i)
  216854. {
  216855. VIDEO_STREAM_CONFIG_CAPS scc;
  216856. AM_MEDIA_TYPE* config;
  216857. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  216858. if (SUCCEEDED (hr))
  216859. {
  216860. const int w = scc.InputSize.cx;
  216861. const int h = scc.InputSize.cy;
  216862. bool duplicate = false;
  216863. for (int j = widths.size(); --j >= 0;)
  216864. {
  216865. if (w == widths.getUnchecked (j) && h == heights.getUnchecked (j))
  216866. {
  216867. duplicate = true;
  216868. break;
  216869. }
  216870. }
  216871. if (! duplicate)
  216872. {
  216873. DBG ("Camera capture size: " + String (w) + ", " + String (h));
  216874. widths.add (w);
  216875. heights.add (h);
  216876. }
  216877. deleteMediaType (config);
  216878. }
  216879. }
  216880. }
  216881. }
  216882. bool selectVideoSize (IAMStreamConfig* const streamConfig,
  216883. const int minWidth, const int minHeight,
  216884. const int maxWidth, const int maxHeight)
  216885. {
  216886. int count = 0, size = 0, bestArea = 0, bestIndex = -1;
  216887. streamConfig->GetNumberOfCapabilities (&count, &size);
  216888. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  216889. {
  216890. AM_MEDIA_TYPE* config;
  216891. VIDEO_STREAM_CONFIG_CAPS scc;
  216892. for (int i = 0; i < count; ++i)
  216893. {
  216894. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  216895. if (SUCCEEDED (hr))
  216896. {
  216897. if (scc.InputSize.cx >= minWidth
  216898. && scc.InputSize.cy >= minHeight
  216899. && scc.InputSize.cx <= maxWidth
  216900. && scc.InputSize.cy <= maxHeight)
  216901. {
  216902. int area = scc.InputSize.cx * scc.InputSize.cy;
  216903. if (area > bestArea)
  216904. {
  216905. bestIndex = i;
  216906. bestArea = area;
  216907. }
  216908. }
  216909. deleteMediaType (config);
  216910. }
  216911. }
  216912. if (bestIndex >= 0)
  216913. {
  216914. HRESULT hr = streamConfig->GetStreamCaps (bestIndex, &config, (BYTE*) &scc);
  216915. hr = streamConfig->SetFormat (config);
  216916. deleteMediaType (config);
  216917. return SUCCEEDED (hr);
  216918. }
  216919. }
  216920. return false;
  216921. }
  216922. static bool getPin (IBaseFilter* filter, const PIN_DIRECTION wantedDirection, ComSmartPtr<IPin>& result, const char* pinName = 0)
  216923. {
  216924. ComSmartPtr <IEnumPins> enumerator;
  216925. ComSmartPtr <IPin> pin;
  216926. filter->EnumPins (enumerator.resetAndGetPointerAddress());
  216927. while (enumerator->Next (1, pin.resetAndGetPointerAddress(), 0) == S_OK)
  216928. {
  216929. PIN_DIRECTION dir;
  216930. pin->QueryDirection (&dir);
  216931. if (wantedDirection == dir)
  216932. {
  216933. PIN_INFO info;
  216934. zerostruct (info);
  216935. pin->QueryPinInfo (&info);
  216936. if (pinName == 0 || String (pinName).equalsIgnoreCase (String (info.achName)))
  216937. {
  216938. result = pin;
  216939. return true;
  216940. }
  216941. }
  216942. }
  216943. return false;
  216944. }
  216945. bool connectFilters (IBaseFilter* const first, IBaseFilter* const second) const
  216946. {
  216947. ComSmartPtr <IPin> in, out;
  216948. return getPin (first, PINDIR_OUTPUT, out)
  216949. && getPin (second, PINDIR_INPUT, in)
  216950. && SUCCEEDED (graphBuilder->Connect (out, in));
  216951. }
  216952. bool addGraphToRot()
  216953. {
  216954. ComSmartPtr <IRunningObjectTable> rot;
  216955. if (FAILED (GetRunningObjectTable (0, rot.resetAndGetPointerAddress())))
  216956. return false;
  216957. ComSmartPtr <IMoniker> moniker;
  216958. WCHAR buffer[128];
  216959. HRESULT hr = CreateItemMoniker (_T("!"), buffer, moniker.resetAndGetPointerAddress());
  216960. if (FAILED (hr))
  216961. return false;
  216962. graphRegistrationID = 0;
  216963. return SUCCEEDED (rot->Register (0, graphBuilder, moniker, &graphRegistrationID));
  216964. }
  216965. void removeGraphFromRot()
  216966. {
  216967. ComSmartPtr <IRunningObjectTable> rot;
  216968. if (SUCCEEDED (GetRunningObjectTable (0, rot.resetAndGetPointerAddress())))
  216969. rot->Revoke (graphRegistrationID);
  216970. }
  216971. static void deleteMediaType (AM_MEDIA_TYPE* const pmt)
  216972. {
  216973. if (pmt->cbFormat != 0)
  216974. CoTaskMemFree ((PVOID) pmt->pbFormat);
  216975. if (pmt->pUnk != 0)
  216976. pmt->pUnk->Release();
  216977. CoTaskMemFree (pmt);
  216978. }
  216979. class GrabberCallback : public ComBaseClassHelper <ISampleGrabberCB>
  216980. {
  216981. public:
  216982. GrabberCallback (DShowCameraDeviceInteral& owner_)
  216983. : owner (owner_)
  216984. {
  216985. }
  216986. STDMETHODIMP SampleCB (double /*SampleTime*/, IMediaSample* /*pSample*/)
  216987. {
  216988. return E_FAIL;
  216989. }
  216990. STDMETHODIMP BufferCB (double time, BYTE* buffer, long bufferSize)
  216991. {
  216992. owner.handleFrame (time, buffer, bufferSize);
  216993. return S_OK;
  216994. }
  216995. private:
  216996. DShowCameraDeviceInteral& owner;
  216997. GrabberCallback (const GrabberCallback&);
  216998. GrabberCallback& operator= (const GrabberCallback&);
  216999. };
  217000. ComSmartPtr <GrabberCallback> callback;
  217001. Array <CameraDevice::Listener*> listeners;
  217002. CriticalSection listenerLock;
  217003. DShowCameraDeviceInteral (const DShowCameraDeviceInteral&);
  217004. DShowCameraDeviceInteral& operator= (const DShowCameraDeviceInteral&);
  217005. };
  217006. CameraDevice::CameraDevice (const String& name_, int /*index*/)
  217007. : name (name_)
  217008. {
  217009. isRecording = false;
  217010. }
  217011. CameraDevice::~CameraDevice()
  217012. {
  217013. stopRecording();
  217014. delete static_cast <DShowCameraDeviceInteral*> (internal);
  217015. internal = 0;
  217016. }
  217017. Component* CameraDevice::createViewerComponent()
  217018. {
  217019. return new DShowCameraDeviceInteral::DShowCaptureViewerComp (static_cast <DShowCameraDeviceInteral*> (internal));
  217020. }
  217021. const String CameraDevice::getFileExtension()
  217022. {
  217023. return ".wmv";
  217024. }
  217025. void CameraDevice::startRecordingToFile (const File& file, int quality)
  217026. {
  217027. stopRecording();
  217028. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  217029. d->addUser();
  217030. isRecording = d->createFileCaptureFilter (file, quality);
  217031. }
  217032. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  217033. {
  217034. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  217035. return d->firstRecordedTime;
  217036. }
  217037. void CameraDevice::stopRecording()
  217038. {
  217039. if (isRecording)
  217040. {
  217041. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  217042. d->removeFileCaptureFilter();
  217043. d->removeUser();
  217044. isRecording = false;
  217045. }
  217046. }
  217047. void CameraDevice::addListener (Listener* listenerToAdd)
  217048. {
  217049. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  217050. if (listenerToAdd != 0)
  217051. d->addListener (listenerToAdd);
  217052. }
  217053. void CameraDevice::removeListener (Listener* listenerToRemove)
  217054. {
  217055. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  217056. if (listenerToRemove != 0)
  217057. d->removeListener (listenerToRemove);
  217058. }
  217059. namespace
  217060. {
  217061. ComSmartPtr <IBaseFilter> enumerateCameras (StringArray* const names,
  217062. const int deviceIndexToOpen,
  217063. String& name)
  217064. {
  217065. int index = 0;
  217066. ComSmartPtr <IBaseFilter> result;
  217067. ComSmartPtr <ICreateDevEnum> pDevEnum;
  217068. HRESULT hr = pDevEnum.CoCreateInstance (CLSID_SystemDeviceEnum);
  217069. if (SUCCEEDED (hr))
  217070. {
  217071. ComSmartPtr <IEnumMoniker> enumerator;
  217072. hr = pDevEnum->CreateClassEnumerator (CLSID_VideoInputDeviceCategory, enumerator.resetAndGetPointerAddress(), 0);
  217073. if (SUCCEEDED (hr) && enumerator != 0)
  217074. {
  217075. ComSmartPtr <IMoniker> moniker;
  217076. ULONG fetched;
  217077. while (enumerator->Next (1, moniker.resetAndGetPointerAddress(), &fetched) == S_OK)
  217078. {
  217079. ComSmartPtr <IBaseFilter> captureFilter;
  217080. hr = moniker->BindToObject (0, 0, IID_IBaseFilter, (void**) captureFilter.resetAndGetPointerAddress());
  217081. if (SUCCEEDED (hr))
  217082. {
  217083. ComSmartPtr <IPropertyBag> propertyBag;
  217084. hr = moniker->BindToStorage (0, 0, IID_IPropertyBag, (void**) propertyBag.resetAndGetPointerAddress());
  217085. if (SUCCEEDED (hr))
  217086. {
  217087. VARIANT var;
  217088. var.vt = VT_BSTR;
  217089. hr = propertyBag->Read (_T("FriendlyName"), &var, 0);
  217090. propertyBag = 0;
  217091. if (SUCCEEDED (hr))
  217092. {
  217093. if (names != 0)
  217094. names->add (var.bstrVal);
  217095. if (index == deviceIndexToOpen)
  217096. {
  217097. name = var.bstrVal;
  217098. result = captureFilter;
  217099. break;
  217100. }
  217101. ++index;
  217102. }
  217103. }
  217104. }
  217105. }
  217106. }
  217107. }
  217108. return result;
  217109. }
  217110. }
  217111. const StringArray CameraDevice::getAvailableDevices()
  217112. {
  217113. StringArray devs;
  217114. String dummy;
  217115. enumerateCameras (&devs, -1, dummy);
  217116. return devs;
  217117. }
  217118. CameraDevice* CameraDevice::openDevice (int index,
  217119. int minWidth, int minHeight,
  217120. int maxWidth, int maxHeight)
  217121. {
  217122. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  217123. HRESULT hr = captureGraphBuilder.CoCreateInstance (CLSID_CaptureGraphBuilder2);
  217124. if (SUCCEEDED (hr))
  217125. {
  217126. String name;
  217127. const ComSmartPtr <IBaseFilter> filter (enumerateCameras (0, index, name));
  217128. if (filter != 0)
  217129. {
  217130. ScopedPointer <CameraDevice> cam (new CameraDevice (name, index));
  217131. DShowCameraDeviceInteral* const intern
  217132. = new DShowCameraDeviceInteral (cam, captureGraphBuilder, filter,
  217133. minWidth, minHeight, maxWidth, maxHeight);
  217134. cam->internal = intern;
  217135. if (intern->ok)
  217136. return cam.release();
  217137. }
  217138. }
  217139. return 0;
  217140. }
  217141. #endif
  217142. /*** End of inlined file: juce_win32_CameraDevice.cpp ***/
  217143. #endif
  217144. // Auto-link the other win32 libs that are needed by library calls..
  217145. #if (JUCE_AMALGAMATED_TEMPLATE || defined (JUCE_DLL_BUILD)) && JUCE_MSVC && ! DONT_AUTOLINK_TO_WIN32_LIBRARIES
  217146. /*** Start of inlined file: juce_win32_AutoLinkLibraries.h ***/
  217147. // Auto-links to various win32 libs that are needed by library calls..
  217148. #pragma comment(lib, "kernel32.lib")
  217149. #pragma comment(lib, "user32.lib")
  217150. #pragma comment(lib, "shell32.lib")
  217151. #pragma comment(lib, "gdi32.lib")
  217152. #pragma comment(lib, "vfw32.lib")
  217153. #pragma comment(lib, "comdlg32.lib")
  217154. #pragma comment(lib, "winmm.lib")
  217155. #pragma comment(lib, "wininet.lib")
  217156. #pragma comment(lib, "ole32.lib")
  217157. #pragma comment(lib, "oleaut32.lib")
  217158. #pragma comment(lib, "advapi32.lib")
  217159. #pragma comment(lib, "ws2_32.lib")
  217160. #pragma comment(lib, "version.lib")
  217161. #ifdef _NATIVE_WCHAR_T_DEFINED
  217162. #ifdef _DEBUG
  217163. #pragma comment(lib, "comsuppwd.lib")
  217164. #else
  217165. #pragma comment(lib, "comsuppw.lib")
  217166. #endif
  217167. #else
  217168. #ifdef _DEBUG
  217169. #pragma comment(lib, "comsuppd.lib")
  217170. #else
  217171. #pragma comment(lib, "comsupp.lib")
  217172. #endif
  217173. #endif
  217174. #if JUCE_OPENGL
  217175. #pragma comment(lib, "OpenGL32.Lib")
  217176. #pragma comment(lib, "GlU32.Lib")
  217177. #endif
  217178. #if JUCE_QUICKTIME
  217179. #pragma comment (lib, "QTMLClient.lib")
  217180. #endif
  217181. #if JUCE_USE_CAMERA
  217182. #pragma comment (lib, "Strmiids.lib")
  217183. #pragma comment (lib, "wmvcore.lib")
  217184. #endif
  217185. #if JUCE_DIRECT2D
  217186. #pragma comment (lib, "Dwrite.lib")
  217187. #pragma comment (lib, "D2d1.lib")
  217188. #endif
  217189. /*** End of inlined file: juce_win32_AutoLinkLibraries.h ***/
  217190. #endif
  217191. END_JUCE_NAMESPACE
  217192. #endif
  217193. /*** End of inlined file: juce_win32_NativeCode.cpp ***/
  217194. #endif
  217195. #if JUCE_LINUX
  217196. /*** Start of inlined file: juce_linux_NativeCode.cpp ***/
  217197. /*
  217198. This file wraps together all the mac-specific code, so that
  217199. we can include all the native headers just once, and compile all our
  217200. platform-specific stuff in one big lump, keeping it out of the way of
  217201. the rest of the codebase.
  217202. */
  217203. #if JUCE_LINUX
  217204. BEGIN_JUCE_NAMESPACE
  217205. #define JUCE_INCLUDED_FILE 1
  217206. // Now include the actual code files..
  217207. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  217208. /*
  217209. This file contains posix routines that are common to both the Linux and Mac builds.
  217210. It gets included directly in the cpp files for these platforms.
  217211. */
  217212. CriticalSection::CriticalSection() throw()
  217213. {
  217214. pthread_mutexattr_t atts;
  217215. pthread_mutexattr_init (&atts);
  217216. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  217217. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  217218. pthread_mutex_init (&internal, &atts);
  217219. }
  217220. CriticalSection::~CriticalSection() throw()
  217221. {
  217222. pthread_mutex_destroy (&internal);
  217223. }
  217224. void CriticalSection::enter() const throw()
  217225. {
  217226. pthread_mutex_lock (&internal);
  217227. }
  217228. bool CriticalSection::tryEnter() const throw()
  217229. {
  217230. return pthread_mutex_trylock (&internal) == 0;
  217231. }
  217232. void CriticalSection::exit() const throw()
  217233. {
  217234. pthread_mutex_unlock (&internal);
  217235. }
  217236. class WaitableEventImpl
  217237. {
  217238. public:
  217239. WaitableEventImpl (const bool manualReset_)
  217240. : triggered (false),
  217241. manualReset (manualReset_)
  217242. {
  217243. pthread_cond_init (&condition, 0);
  217244. pthread_mutexattr_t atts;
  217245. pthread_mutexattr_init (&atts);
  217246. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  217247. pthread_mutex_init (&mutex, &atts);
  217248. }
  217249. ~WaitableEventImpl()
  217250. {
  217251. pthread_cond_destroy (&condition);
  217252. pthread_mutex_destroy (&mutex);
  217253. }
  217254. bool wait (const int timeOutMillisecs) throw()
  217255. {
  217256. pthread_mutex_lock (&mutex);
  217257. if (! triggered)
  217258. {
  217259. if (timeOutMillisecs < 0)
  217260. {
  217261. do
  217262. {
  217263. pthread_cond_wait (&condition, &mutex);
  217264. }
  217265. while (! triggered);
  217266. }
  217267. else
  217268. {
  217269. struct timeval now;
  217270. gettimeofday (&now, 0);
  217271. struct timespec time;
  217272. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  217273. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  217274. if (time.tv_nsec >= 1000000000)
  217275. {
  217276. time.tv_nsec -= 1000000000;
  217277. time.tv_sec++;
  217278. }
  217279. do
  217280. {
  217281. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  217282. {
  217283. pthread_mutex_unlock (&mutex);
  217284. return false;
  217285. }
  217286. }
  217287. while (! triggered);
  217288. }
  217289. }
  217290. if (! manualReset)
  217291. triggered = false;
  217292. pthread_mutex_unlock (&mutex);
  217293. return true;
  217294. }
  217295. void signal() throw()
  217296. {
  217297. pthread_mutex_lock (&mutex);
  217298. triggered = true;
  217299. pthread_cond_broadcast (&condition);
  217300. pthread_mutex_unlock (&mutex);
  217301. }
  217302. void reset() throw()
  217303. {
  217304. pthread_mutex_lock (&mutex);
  217305. triggered = false;
  217306. pthread_mutex_unlock (&mutex);
  217307. }
  217308. private:
  217309. pthread_cond_t condition;
  217310. pthread_mutex_t mutex;
  217311. bool triggered;
  217312. const bool manualReset;
  217313. WaitableEventImpl (const WaitableEventImpl&);
  217314. WaitableEventImpl& operator= (const WaitableEventImpl&);
  217315. };
  217316. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  217317. : internal (new WaitableEventImpl (manualReset))
  217318. {
  217319. }
  217320. WaitableEvent::~WaitableEvent() throw()
  217321. {
  217322. delete static_cast <WaitableEventImpl*> (internal);
  217323. }
  217324. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  217325. {
  217326. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  217327. }
  217328. void WaitableEvent::signal() const throw()
  217329. {
  217330. static_cast <WaitableEventImpl*> (internal)->signal();
  217331. }
  217332. void WaitableEvent::reset() const throw()
  217333. {
  217334. static_cast <WaitableEventImpl*> (internal)->reset();
  217335. }
  217336. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  217337. {
  217338. struct timespec time;
  217339. time.tv_sec = millisecs / 1000;
  217340. time.tv_nsec = (millisecs % 1000) * 1000000;
  217341. nanosleep (&time, 0);
  217342. }
  217343. const juce_wchar File::separator = '/';
  217344. const String File::separatorString ("/");
  217345. const File File::getCurrentWorkingDirectory()
  217346. {
  217347. HeapBlock<char> heapBuffer;
  217348. char localBuffer [1024];
  217349. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  217350. int bufferSize = 4096;
  217351. while (cwd == 0 && errno == ERANGE)
  217352. {
  217353. heapBuffer.malloc (bufferSize);
  217354. cwd = getcwd (heapBuffer, bufferSize - 1);
  217355. bufferSize += 1024;
  217356. }
  217357. return File (String::fromUTF8 (cwd));
  217358. }
  217359. bool File::setAsCurrentWorkingDirectory() const
  217360. {
  217361. return chdir (getFullPathName().toUTF8()) == 0;
  217362. }
  217363. namespace
  217364. {
  217365. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  217366. typedef struct stat64 juce_statStruct; // (need to use the 64-bit version to work around a simulator bug)
  217367. #else
  217368. typedef struct stat juce_statStruct;
  217369. #endif
  217370. bool juce_stat (const String& fileName, juce_statStruct& info)
  217371. {
  217372. return fileName.isNotEmpty()
  217373. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  217374. && (stat64 (fileName.toUTF8(), &info) == 0);
  217375. #else
  217376. && (stat (fileName.toUTF8(), &info) == 0);
  217377. #endif
  217378. }
  217379. // if this file doesn't exist, find a parent of it that does..
  217380. bool juce_doStatFS (File f, struct statfs& result)
  217381. {
  217382. for (int i = 5; --i >= 0;)
  217383. {
  217384. if (f.exists())
  217385. break;
  217386. f = f.getParentDirectory();
  217387. }
  217388. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  217389. }
  217390. }
  217391. bool File::isDirectory() const
  217392. {
  217393. juce_statStruct info;
  217394. return fullPath.isEmpty()
  217395. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  217396. }
  217397. bool File::exists() const
  217398. {
  217399. juce_statStruct info;
  217400. return fullPath.isNotEmpty()
  217401. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  217402. && (lstat64 (fullPath.toUTF8(), &info) == 0);
  217403. #else
  217404. && (lstat (fullPath.toUTF8(), &info) == 0);
  217405. #endif
  217406. }
  217407. bool File::existsAsFile() const
  217408. {
  217409. return exists() && ! isDirectory();
  217410. }
  217411. int64 File::getSize() const
  217412. {
  217413. juce_statStruct info;
  217414. return juce_stat (fullPath, info) ? info.st_size : 0;
  217415. }
  217416. bool File::hasWriteAccess() const
  217417. {
  217418. if (exists())
  217419. return access (fullPath.toUTF8(), W_OK) == 0;
  217420. if ((! isDirectory()) && fullPath.containsChar (separator))
  217421. return getParentDirectory().hasWriteAccess();
  217422. return false;
  217423. }
  217424. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  217425. {
  217426. juce_statStruct info;
  217427. if (! juce_stat (fullPath, info))
  217428. return false;
  217429. info.st_mode &= 0777; // Just permissions
  217430. if (shouldBeReadOnly)
  217431. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  217432. else
  217433. // Give everybody write permission?
  217434. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  217435. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  217436. }
  217437. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  217438. {
  217439. modificationTime = 0;
  217440. accessTime = 0;
  217441. creationTime = 0;
  217442. juce_statStruct info;
  217443. if (juce_stat (fullPath, info))
  217444. {
  217445. modificationTime = (int64) info.st_mtime * 1000;
  217446. accessTime = (int64) info.st_atime * 1000;
  217447. creationTime = (int64) info.st_ctime * 1000;
  217448. }
  217449. }
  217450. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  217451. {
  217452. struct utimbuf times;
  217453. times.actime = (time_t) (accessTime / 1000);
  217454. times.modtime = (time_t) (modificationTime / 1000);
  217455. return utime (fullPath.toUTF8(), &times) == 0;
  217456. }
  217457. bool File::deleteFile() const
  217458. {
  217459. if (! exists())
  217460. return true;
  217461. else if (isDirectory())
  217462. return rmdir (fullPath.toUTF8()) == 0;
  217463. else
  217464. return remove (fullPath.toUTF8()) == 0;
  217465. }
  217466. bool File::moveInternal (const File& dest) const
  217467. {
  217468. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  217469. return true;
  217470. if (hasWriteAccess() && copyInternal (dest))
  217471. {
  217472. if (deleteFile())
  217473. return true;
  217474. dest.deleteFile();
  217475. }
  217476. return false;
  217477. }
  217478. void File::createDirectoryInternal (const String& fileName) const
  217479. {
  217480. mkdir (fileName.toUTF8(), 0777);
  217481. }
  217482. int64 juce_fileSetPosition (void* handle, int64 pos)
  217483. {
  217484. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  217485. return pos;
  217486. return -1;
  217487. }
  217488. void FileInputStream::openHandle()
  217489. {
  217490. totalSize = file.getSize();
  217491. const int f = open (file.getFullPathName().toUTF8(), O_RDONLY, 00644);
  217492. if (f != -1)
  217493. fileHandle = (void*) f;
  217494. }
  217495. void FileInputStream::closeHandle()
  217496. {
  217497. if (fileHandle != 0)
  217498. {
  217499. close ((int) (pointer_sized_int) fileHandle);
  217500. fileHandle = 0;
  217501. }
  217502. }
  217503. size_t FileInputStream::readInternal (void* const buffer, const size_t numBytes)
  217504. {
  217505. if (fileHandle != 0)
  217506. return jmax ((ssize_t) 0, ::read ((int) (pointer_sized_int) fileHandle, buffer, numBytes));
  217507. return 0;
  217508. }
  217509. void FileOutputStream::openHandle()
  217510. {
  217511. if (file.exists())
  217512. {
  217513. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  217514. if (f != -1)
  217515. {
  217516. currentPosition = lseek (f, 0, SEEK_END);
  217517. if (currentPosition >= 0)
  217518. fileHandle = (void*) f;
  217519. else
  217520. close (f);
  217521. }
  217522. }
  217523. else
  217524. {
  217525. const int f = open (file.getFullPathName().toUTF8(), O_RDWR + O_CREAT, 00644);
  217526. if (f != -1)
  217527. fileHandle = (void*) f;
  217528. }
  217529. }
  217530. void FileOutputStream::closeHandle()
  217531. {
  217532. if (fileHandle != 0)
  217533. {
  217534. close ((int) (pointer_sized_int) fileHandle);
  217535. fileHandle = 0;
  217536. }
  217537. }
  217538. int FileOutputStream::writeInternal (const void* const data, const int numBytes)
  217539. {
  217540. if (fileHandle != 0)
  217541. return (int) ::write ((int) (pointer_sized_int) fileHandle, data, numBytes);
  217542. return 0;
  217543. }
  217544. void FileOutputStream::flushInternal()
  217545. {
  217546. if (fileHandle != 0)
  217547. fsync ((int) (pointer_sized_int) fileHandle);
  217548. }
  217549. const File juce_getExecutableFile()
  217550. {
  217551. Dl_info exeInfo;
  217552. dladdr ((const void*) juce_getExecutableFile, &exeInfo);
  217553. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  217554. }
  217555. int64 File::getBytesFreeOnVolume() const
  217556. {
  217557. struct statfs buf;
  217558. if (juce_doStatFS (*this, buf))
  217559. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  217560. return 0;
  217561. }
  217562. int64 File::getVolumeTotalSize() const
  217563. {
  217564. struct statfs buf;
  217565. if (juce_doStatFS (*this, buf))
  217566. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  217567. return 0;
  217568. }
  217569. const String File::getVolumeLabel() const
  217570. {
  217571. #if JUCE_MAC
  217572. struct VolAttrBuf
  217573. {
  217574. u_int32_t length;
  217575. attrreference_t mountPointRef;
  217576. char mountPointSpace [MAXPATHLEN];
  217577. } attrBuf;
  217578. struct attrlist attrList;
  217579. zerostruct (attrList);
  217580. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  217581. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  217582. File f (*this);
  217583. for (;;)
  217584. {
  217585. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  217586. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  217587. (int) attrBuf.mountPointRef.attr_length);
  217588. const File parent (f.getParentDirectory());
  217589. if (f == parent)
  217590. break;
  217591. f = parent;
  217592. }
  217593. #endif
  217594. return String::empty;
  217595. }
  217596. int File::getVolumeSerialNumber() const
  217597. {
  217598. return 0; // xxx
  217599. }
  217600. void juce_runSystemCommand (const String& command)
  217601. {
  217602. int result = system (command.toUTF8());
  217603. (void) result;
  217604. }
  217605. const String juce_getOutputFromCommand (const String& command)
  217606. {
  217607. // slight bodge here, as we just pipe the output into a temp file and read it...
  217608. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  217609. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  217610. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  217611. String result (tempFile.loadFileAsString());
  217612. tempFile.deleteFile();
  217613. return result;
  217614. }
  217615. class InterProcessLock::Pimpl
  217616. {
  217617. public:
  217618. Pimpl (const String& name, const int timeOutMillisecs)
  217619. : handle (0), refCount (1)
  217620. {
  217621. #if JUCE_MAC
  217622. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  217623. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  217624. #else
  217625. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  217626. #endif
  217627. temp.create();
  217628. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  217629. if (handle != 0)
  217630. {
  217631. struct flock fl;
  217632. zerostruct (fl);
  217633. fl.l_whence = SEEK_SET;
  217634. fl.l_type = F_WRLCK;
  217635. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  217636. for (;;)
  217637. {
  217638. const int result = fcntl (handle, F_SETLK, &fl);
  217639. if (result >= 0)
  217640. return;
  217641. if (errno != EINTR)
  217642. {
  217643. if (timeOutMillisecs == 0
  217644. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  217645. break;
  217646. Thread::sleep (10);
  217647. }
  217648. }
  217649. }
  217650. closeFile();
  217651. }
  217652. ~Pimpl()
  217653. {
  217654. closeFile();
  217655. }
  217656. void closeFile()
  217657. {
  217658. if (handle != 0)
  217659. {
  217660. struct flock fl;
  217661. zerostruct (fl);
  217662. fl.l_whence = SEEK_SET;
  217663. fl.l_type = F_UNLCK;
  217664. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  217665. {}
  217666. close (handle);
  217667. handle = 0;
  217668. }
  217669. }
  217670. int handle, refCount;
  217671. };
  217672. InterProcessLock::InterProcessLock (const String& name_)
  217673. : name (name_)
  217674. {
  217675. }
  217676. InterProcessLock::~InterProcessLock()
  217677. {
  217678. }
  217679. bool InterProcessLock::enter (const int timeOutMillisecs)
  217680. {
  217681. const ScopedLock sl (lock);
  217682. if (pimpl == 0)
  217683. {
  217684. pimpl = new Pimpl (name, timeOutMillisecs);
  217685. if (pimpl->handle == 0)
  217686. pimpl = 0;
  217687. }
  217688. else
  217689. {
  217690. pimpl->refCount++;
  217691. }
  217692. return pimpl != 0;
  217693. }
  217694. void InterProcessLock::exit()
  217695. {
  217696. const ScopedLock sl (lock);
  217697. // Trying to release the lock too many times!
  217698. jassert (pimpl != 0);
  217699. if (pimpl != 0 && --(pimpl->refCount) == 0)
  217700. pimpl = 0;
  217701. }
  217702. void JUCE_API juce_threadEntryPoint (void*);
  217703. void* threadEntryProc (void* userData)
  217704. {
  217705. JUCE_AUTORELEASEPOOL
  217706. juce_threadEntryPoint (userData);
  217707. return 0;
  217708. }
  217709. void* juce_createThread (void* userData)
  217710. {
  217711. pthread_t handle = 0;
  217712. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  217713. {
  217714. pthread_detach (handle);
  217715. return (void*) handle;
  217716. }
  217717. return 0;
  217718. }
  217719. void juce_killThread (void* handle)
  217720. {
  217721. if (handle != 0)
  217722. pthread_cancel ((pthread_t) handle);
  217723. }
  217724. void juce_setCurrentThreadName (const String& /*name*/)
  217725. {
  217726. }
  217727. bool juce_setThreadPriority (void* handle, int priority)
  217728. {
  217729. struct sched_param param;
  217730. int policy;
  217731. priority = jlimit (0, 10, priority);
  217732. if (handle == 0)
  217733. handle = (void*) pthread_self();
  217734. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) != 0)
  217735. return false;
  217736. policy = priority == 0 ? SCHED_OTHER : SCHED_RR;
  217737. const int minPriority = sched_get_priority_min (policy);
  217738. const int maxPriority = sched_get_priority_max (policy);
  217739. param.sched_priority = ((maxPriority - minPriority) * priority) / 10 + minPriority;
  217740. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  217741. }
  217742. Thread::ThreadID Thread::getCurrentThreadId()
  217743. {
  217744. return (ThreadID) pthread_self();
  217745. }
  217746. void Thread::yield()
  217747. {
  217748. sched_yield();
  217749. }
  217750. /* Remove this macro if you're having problems compiling the cpu affinity
  217751. calls (the API for these has changed about quite a bit in various Linux
  217752. versions, and a lot of distros seem to ship with obsolete versions)
  217753. */
  217754. #if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
  217755. #define SUPPORT_AFFINITIES 1
  217756. #endif
  217757. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  217758. {
  217759. #if SUPPORT_AFFINITIES
  217760. cpu_set_t affinity;
  217761. CPU_ZERO (&affinity);
  217762. for (int i = 0; i < 32; ++i)
  217763. if ((affinityMask & (1 << i)) != 0)
  217764. CPU_SET (i, &affinity);
  217765. /*
  217766. N.B. If this line causes a compile error, then you've probably not got the latest
  217767. version of glibc installed.
  217768. If you don't want to update your copy of glibc and don't care about cpu affinities,
  217769. then you can just disable all this stuff by setting the SUPPORT_AFFINITIES macro to 0.
  217770. */
  217771. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  217772. sched_yield();
  217773. #else
  217774. /* affinities aren't supported because either the appropriate header files weren't found,
  217775. or the SUPPORT_AFFINITIES macro was turned off
  217776. */
  217777. jassertfalse;
  217778. #endif
  217779. }
  217780. /*** End of inlined file: juce_posix_SharedCode.h ***/
  217781. /*** Start of inlined file: juce_linux_Files.cpp ***/
  217782. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217783. // compiled on its own).
  217784. #if JUCE_INCLUDED_FILE
  217785. enum
  217786. {
  217787. U_ISOFS_SUPER_MAGIC = 0x9660, // linux/iso_fs.h
  217788. U_MSDOS_SUPER_MAGIC = 0x4d44, // linux/msdos_fs.h
  217789. U_NFS_SUPER_MAGIC = 0x6969, // linux/nfs_fs.h
  217790. U_SMB_SUPER_MAGIC = 0x517B // linux/smb_fs.h
  217791. };
  217792. bool File::copyInternal (const File& dest) const
  217793. {
  217794. FileInputStream in (*this);
  217795. if (dest.deleteFile())
  217796. {
  217797. {
  217798. FileOutputStream out (dest);
  217799. if (out.failedToOpen())
  217800. return false;
  217801. if (out.writeFromInputStream (in, -1) == getSize())
  217802. return true;
  217803. }
  217804. dest.deleteFile();
  217805. }
  217806. return false;
  217807. }
  217808. void File::findFileSystemRoots (Array<File>& destArray)
  217809. {
  217810. destArray.add (File ("/"));
  217811. }
  217812. bool File::isOnCDRomDrive() const
  217813. {
  217814. struct statfs buf;
  217815. return statfs (getFullPathName().toUTF8(), &buf) == 0
  217816. && buf.f_type == (short) U_ISOFS_SUPER_MAGIC;
  217817. }
  217818. bool File::isOnHardDisk() const
  217819. {
  217820. struct statfs buf;
  217821. if (statfs (getFullPathName().toUTF8(), &buf) == 0)
  217822. {
  217823. switch (buf.f_type)
  217824. {
  217825. case U_ISOFS_SUPER_MAGIC: // CD-ROM
  217826. case U_MSDOS_SUPER_MAGIC: // Probably floppy (but could be mounted FAT filesystem)
  217827. case U_NFS_SUPER_MAGIC: // Network NFS
  217828. case U_SMB_SUPER_MAGIC: // Network Samba
  217829. return false;
  217830. default:
  217831. // Assume anything else is a hard-disk (but note it could
  217832. // be a RAM disk. There isn't a good way of determining
  217833. // this for sure)
  217834. return true;
  217835. }
  217836. }
  217837. // Assume so if this fails for some reason
  217838. return true;
  217839. }
  217840. bool File::isOnRemovableDrive() const
  217841. {
  217842. jassertfalse; // xxx not implemented for linux!
  217843. return false;
  217844. }
  217845. bool File::isHidden() const
  217846. {
  217847. return getFileName().startsWithChar ('.');
  217848. }
  217849. namespace
  217850. {
  217851. const File juce_readlink (const String& file, const File& defaultFile)
  217852. {
  217853. const int size = 8192;
  217854. HeapBlock<char> buffer;
  217855. buffer.malloc (size + 4);
  217856. const size_t numBytes = readlink (file.toUTF8(), buffer, size);
  217857. if (numBytes > 0 && numBytes <= size)
  217858. return File (file).getSiblingFile (String::fromUTF8 (buffer, (int) numBytes));
  217859. return defaultFile;
  217860. }
  217861. }
  217862. const File File::getLinkedTarget() const
  217863. {
  217864. return juce_readlink (getFullPathName().toUTF8(), *this);
  217865. }
  217866. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  217867. const File File::getSpecialLocation (const SpecialLocationType type)
  217868. {
  217869. switch (type)
  217870. {
  217871. case userHomeDirectory:
  217872. {
  217873. const char* homeDir = getenv ("HOME");
  217874. if (homeDir == 0)
  217875. {
  217876. struct passwd* const pw = getpwuid (getuid());
  217877. if (pw != 0)
  217878. homeDir = pw->pw_dir;
  217879. }
  217880. return File (String::fromUTF8 (homeDir));
  217881. }
  217882. case userDocumentsDirectory:
  217883. case userMusicDirectory:
  217884. case userMoviesDirectory:
  217885. case userApplicationDataDirectory:
  217886. return File ("~");
  217887. case userDesktopDirectory:
  217888. return File ("~/Desktop");
  217889. case commonApplicationDataDirectory:
  217890. return File ("/var");
  217891. case globalApplicationsDirectory:
  217892. return File ("/usr");
  217893. case tempDirectory:
  217894. {
  217895. File tmp ("/var/tmp");
  217896. if (! tmp.isDirectory())
  217897. {
  217898. tmp = "/tmp";
  217899. if (! tmp.isDirectory())
  217900. tmp = File::getCurrentWorkingDirectory();
  217901. }
  217902. return tmp;
  217903. }
  217904. case invokedExecutableFile:
  217905. if (juce_Argv0 != 0)
  217906. return File (String::fromUTF8 (juce_Argv0));
  217907. // deliberate fall-through...
  217908. case currentExecutableFile:
  217909. case currentApplicationFile:
  217910. return juce_getExecutableFile();
  217911. case hostApplicationPath:
  217912. return juce_readlink ("/proc/self/exe", juce_getExecutableFile());
  217913. default:
  217914. jassertfalse; // unknown type?
  217915. break;
  217916. }
  217917. return File::nonexistent;
  217918. }
  217919. const String File::getVersion() const
  217920. {
  217921. return String::empty; // xxx not yet implemented
  217922. }
  217923. bool File::moveToTrash() const
  217924. {
  217925. if (! exists())
  217926. return true;
  217927. File trashCan ("~/.Trash");
  217928. if (! trashCan.isDirectory())
  217929. trashCan = "~/.local/share/Trash/files";
  217930. if (! trashCan.isDirectory())
  217931. return false;
  217932. return moveFileTo (trashCan.getNonexistentChildFile (getFileNameWithoutExtension(),
  217933. getFileExtension()));
  217934. }
  217935. class DirectoryIterator::NativeIterator::Pimpl
  217936. {
  217937. public:
  217938. Pimpl (const File& directory, const String& wildCard_)
  217939. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  217940. wildCard (wildCard_),
  217941. dir (opendir (directory.getFullPathName().toUTF8()))
  217942. {
  217943. if (wildCard == "*.*")
  217944. wildCard = "*";
  217945. wildcardUTF8 = wildCard.toUTF8();
  217946. }
  217947. ~Pimpl()
  217948. {
  217949. if (dir != 0)
  217950. closedir (dir);
  217951. }
  217952. bool next (String& filenameFound,
  217953. bool* const isDir, bool* const isHidden, int64* const fileSize,
  217954. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  217955. {
  217956. if (dir == 0)
  217957. return false;
  217958. for (;;)
  217959. {
  217960. struct dirent* const de = readdir (dir);
  217961. if (de == 0)
  217962. return false;
  217963. if (fnmatch (wildcardUTF8, de->d_name, FNM_CASEFOLD) == 0)
  217964. {
  217965. filenameFound = String::fromUTF8 (de->d_name);
  217966. const String path (parentDir + filenameFound);
  217967. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  217968. {
  217969. struct stat info;
  217970. const bool statOk = juce_stat (path, info);
  217971. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  217972. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  217973. if (modTime != 0) *modTime = statOk ? (int64) info.st_mtime * 1000 : 0;
  217974. if (creationTime != 0) *creationTime = statOk ? (int64) info.st_ctime * 1000 : 0;
  217975. }
  217976. if (isHidden != 0)
  217977. *isHidden = filenameFound.startsWithChar ('.');
  217978. if (isReadOnly != 0)
  217979. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  217980. return true;
  217981. }
  217982. }
  217983. }
  217984. private:
  217985. String parentDir, wildCard;
  217986. const char* wildcardUTF8;
  217987. DIR* dir;
  217988. Pimpl (const Pimpl&);
  217989. Pimpl& operator= (const Pimpl&);
  217990. };
  217991. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  217992. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  217993. {
  217994. }
  217995. DirectoryIterator::NativeIterator::~NativeIterator()
  217996. {
  217997. }
  217998. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  217999. bool* const isDir, bool* const isHidden, int64* const fileSize,
  218000. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  218001. {
  218002. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  218003. }
  218004. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  218005. {
  218006. String cmdString (fileName.replace (" ", "\\ ",false));
  218007. cmdString << " " << parameters;
  218008. if (URL::isProbablyAWebsiteURL (fileName)
  218009. || cmdString.startsWithIgnoreCase ("file:")
  218010. || URL::isProbablyAnEmailAddress (fileName))
  218011. {
  218012. // create a command that tries to launch a bunch of likely browsers
  218013. const char* const browserNames[] = { "xdg-open", "/etc/alternatives/x-www-browser", "firefox", "mozilla", "konqueror", "opera" };
  218014. StringArray cmdLines;
  218015. for (int i = 0; i < numElementsInArray (browserNames); ++i)
  218016. cmdLines.add (String (browserNames[i]) + " " + cmdString.trim().quoted());
  218017. cmdString = cmdLines.joinIntoString (" || ");
  218018. }
  218019. const char* const argv[4] = { "/bin/sh", "-c", cmdString.toUTF8(), 0 };
  218020. const int cpid = fork();
  218021. if (cpid == 0)
  218022. {
  218023. setsid();
  218024. // Child process
  218025. execve (argv[0], (char**) argv, environ);
  218026. exit (0);
  218027. }
  218028. return cpid >= 0;
  218029. }
  218030. void File::revealToUser() const
  218031. {
  218032. if (isDirectory())
  218033. startAsProcess();
  218034. else if (getParentDirectory().exists())
  218035. getParentDirectory().startAsProcess();
  218036. }
  218037. #endif
  218038. /*** End of inlined file: juce_linux_Files.cpp ***/
  218039. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  218040. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  218041. // compiled on its own).
  218042. #if JUCE_INCLUDED_FILE
  218043. struct NamedPipeInternal
  218044. {
  218045. String pipeInName, pipeOutName;
  218046. int pipeIn, pipeOut;
  218047. bool volatile createdPipe, blocked, stopReadOperation;
  218048. static void signalHandler (int) {}
  218049. };
  218050. void NamedPipe::cancelPendingReads()
  218051. {
  218052. while (internal != 0 && static_cast <NamedPipeInternal*> (internal)->blocked)
  218053. {
  218054. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  218055. intern->stopReadOperation = true;
  218056. char buffer [1] = { 0 };
  218057. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  218058. (void) bytesWritten;
  218059. int timeout = 2000;
  218060. while (intern->blocked && --timeout >= 0)
  218061. Thread::sleep (2);
  218062. intern->stopReadOperation = false;
  218063. }
  218064. }
  218065. void NamedPipe::close()
  218066. {
  218067. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  218068. if (intern != 0)
  218069. {
  218070. internal = 0;
  218071. if (intern->pipeIn != -1)
  218072. ::close (intern->pipeIn);
  218073. if (intern->pipeOut != -1)
  218074. ::close (intern->pipeOut);
  218075. if (intern->createdPipe)
  218076. {
  218077. unlink (intern->pipeInName.toUTF8());
  218078. unlink (intern->pipeOutName.toUTF8());
  218079. }
  218080. delete intern;
  218081. }
  218082. }
  218083. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  218084. {
  218085. close();
  218086. NamedPipeInternal* const intern = new NamedPipeInternal();
  218087. internal = intern;
  218088. intern->createdPipe = createPipe;
  218089. intern->blocked = false;
  218090. intern->stopReadOperation = false;
  218091. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  218092. siginterrupt (SIGPIPE, 1);
  218093. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  218094. intern->pipeInName = pipePath + "_in";
  218095. intern->pipeOutName = pipePath + "_out";
  218096. intern->pipeIn = -1;
  218097. intern->pipeOut = -1;
  218098. if (createPipe)
  218099. {
  218100. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  218101. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  218102. {
  218103. delete intern;
  218104. internal = 0;
  218105. return false;
  218106. }
  218107. }
  218108. return true;
  218109. }
  218110. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  218111. {
  218112. int bytesRead = -1;
  218113. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  218114. if (intern != 0)
  218115. {
  218116. intern->blocked = true;
  218117. if (intern->pipeIn == -1)
  218118. {
  218119. if (intern->createdPipe)
  218120. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  218121. else
  218122. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  218123. if (intern->pipeIn == -1)
  218124. {
  218125. intern->blocked = false;
  218126. return -1;
  218127. }
  218128. }
  218129. bytesRead = 0;
  218130. char* p = static_cast<char*> (destBuffer);
  218131. while (bytesRead < maxBytesToRead)
  218132. {
  218133. const int bytesThisTime = maxBytesToRead - bytesRead;
  218134. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  218135. if (numRead <= 0 || intern->stopReadOperation)
  218136. {
  218137. bytesRead = -1;
  218138. break;
  218139. }
  218140. bytesRead += numRead;
  218141. p += bytesRead;
  218142. }
  218143. intern->blocked = false;
  218144. }
  218145. return bytesRead;
  218146. }
  218147. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  218148. {
  218149. int bytesWritten = -1;
  218150. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  218151. if (intern != 0)
  218152. {
  218153. if (intern->pipeOut == -1)
  218154. {
  218155. if (intern->createdPipe)
  218156. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  218157. else
  218158. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  218159. if (intern->pipeOut == -1)
  218160. {
  218161. return -1;
  218162. }
  218163. }
  218164. const char* p = static_cast<const char*> (sourceBuffer);
  218165. bytesWritten = 0;
  218166. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  218167. while (bytesWritten < numBytesToWrite
  218168. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  218169. {
  218170. const int bytesThisTime = numBytesToWrite - bytesWritten;
  218171. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  218172. if (numWritten <= 0)
  218173. {
  218174. bytesWritten = -1;
  218175. break;
  218176. }
  218177. bytesWritten += numWritten;
  218178. p += bytesWritten;
  218179. }
  218180. }
  218181. return bytesWritten;
  218182. }
  218183. #endif
  218184. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  218185. /*** Start of inlined file: juce_linux_Network.cpp ***/
  218186. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218187. // compiled on its own).
  218188. #if JUCE_INCLUDED_FILE
  218189. void MACAddress::findAllAddresses (Array<MACAddress>& result)
  218190. {
  218191. const int s = socket (AF_INET, SOCK_DGRAM, 0);
  218192. if (s != -1)
  218193. {
  218194. char buf [1024];
  218195. struct ifconf ifc;
  218196. ifc.ifc_len = sizeof (buf);
  218197. ifc.ifc_buf = buf;
  218198. ioctl (s, SIOCGIFCONF, &ifc);
  218199. for (unsigned int i = 0; i < ifc.ifc_len / sizeof (struct ifreq); ++i)
  218200. {
  218201. struct ifreq ifr;
  218202. strcpy (ifr.ifr_name, ifc.ifc_req[i].ifr_name);
  218203. if (ioctl (s, SIOCGIFFLAGS, &ifr) == 0
  218204. && (ifr.ifr_flags & IFF_LOOPBACK) == 0
  218205. && ioctl (s, SIOCGIFHWADDR, &ifr) == 0)
  218206. {
  218207. result.addIfNotAlreadyThere (MACAddress ((const uint8*) ifr.ifr_hwaddr.sa_data));
  218208. }
  218209. }
  218210. close (s);
  218211. }
  218212. }
  218213. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  218214. const String& emailSubject,
  218215. const String& bodyText,
  218216. const StringArray& filesToAttach)
  218217. {
  218218. jassertfalse; // xxx todo
  218219. return false;
  218220. }
  218221. /** A HTTP input stream that uses sockets.
  218222. */
  218223. class JUCE_HTTPSocketStream
  218224. {
  218225. public:
  218226. JUCE_HTTPSocketStream()
  218227. : readPosition (0),
  218228. socketHandle (-1),
  218229. levelsOfRedirection (0),
  218230. timeoutSeconds (15)
  218231. {
  218232. }
  218233. ~JUCE_HTTPSocketStream()
  218234. {
  218235. closeSocket();
  218236. }
  218237. bool open (const String& url,
  218238. const String& headers,
  218239. const MemoryBlock& postData,
  218240. const bool isPost,
  218241. URL::OpenStreamProgressCallback* callback,
  218242. void* callbackContext,
  218243. int timeOutMs)
  218244. {
  218245. closeSocket();
  218246. uint32 timeOutTime = Time::getMillisecondCounter();
  218247. if (timeOutMs == 0)
  218248. timeOutTime += 60000;
  218249. else if (timeOutMs < 0)
  218250. timeOutTime = 0xffffffff;
  218251. else
  218252. timeOutTime += timeOutMs;
  218253. String hostName, hostPath;
  218254. int hostPort;
  218255. if (! decomposeURL (url, hostName, hostPath, hostPort))
  218256. return false;
  218257. const struct hostent* host = 0;
  218258. int port = 0;
  218259. String proxyName, proxyPath;
  218260. int proxyPort = 0;
  218261. String proxyURL (getenv ("http_proxy"));
  218262. if (proxyURL.startsWithIgnoreCase ("http://"))
  218263. {
  218264. if (! decomposeURL (proxyURL, proxyName, proxyPath, proxyPort))
  218265. return false;
  218266. host = gethostbyname (proxyName.toUTF8());
  218267. port = proxyPort;
  218268. }
  218269. else
  218270. {
  218271. host = gethostbyname (hostName.toUTF8());
  218272. port = hostPort;
  218273. }
  218274. if (host == 0)
  218275. return false;
  218276. struct sockaddr_in address;
  218277. zerostruct (address);
  218278. memcpy (&address.sin_addr, host->h_addr, host->h_length);
  218279. address.sin_family = host->h_addrtype;
  218280. address.sin_port = htons (port);
  218281. socketHandle = socket (host->h_addrtype, SOCK_STREAM, 0);
  218282. if (socketHandle == -1)
  218283. return false;
  218284. int receiveBufferSize = 16384;
  218285. setsockopt (socketHandle, SOL_SOCKET, SO_RCVBUF, (char*) &receiveBufferSize, sizeof (receiveBufferSize));
  218286. setsockopt (socketHandle, SOL_SOCKET, SO_KEEPALIVE, 0, 0);
  218287. #if JUCE_MAC
  218288. setsockopt (socketHandle, SOL_SOCKET, SO_NOSIGPIPE, 0, 0);
  218289. #endif
  218290. if (connect (socketHandle, (struct sockaddr*) &address, sizeof (address)) == -1)
  218291. {
  218292. closeSocket();
  218293. return false;
  218294. }
  218295. const MemoryBlock requestHeader (createRequestHeader (hostName, hostPort, proxyName, proxyPort,
  218296. hostPath, url, headers, postData, isPost));
  218297. size_t totalHeaderSent = 0;
  218298. while (totalHeaderSent < requestHeader.getSize())
  218299. {
  218300. if (Time::getMillisecondCounter() > timeOutTime)
  218301. {
  218302. closeSocket();
  218303. return false;
  218304. }
  218305. const int numToSend = jmin (1024, (int) (requestHeader.getSize() - totalHeaderSent));
  218306. if (send (socketHandle, ((const char*) requestHeader.getData()) + totalHeaderSent, numToSend, 0)
  218307. != numToSend)
  218308. {
  218309. closeSocket();
  218310. return false;
  218311. }
  218312. totalHeaderSent += numToSend;
  218313. if (callback != 0 && ! callback (callbackContext, totalHeaderSent, requestHeader.getSize()))
  218314. {
  218315. closeSocket();
  218316. return false;
  218317. }
  218318. }
  218319. const String responseHeader (readResponse (timeOutTime));
  218320. if (responseHeader.isNotEmpty())
  218321. {
  218322. headerLines.clear();
  218323. headerLines.addLines (responseHeader);
  218324. const int statusCode = responseHeader.fromFirstOccurrenceOf (" ", false, false)
  218325. .substring (0, 3).getIntValue();
  218326. //int contentLength = findHeaderItem (lines, "Content-Length:").getIntValue();
  218327. //bool isChunked = findHeaderItem (lines, "Transfer-Encoding:").equalsIgnoreCase ("chunked");
  218328. String location (findHeaderItem (headerLines, "Location:"));
  218329. if (statusCode >= 300 && statusCode < 400
  218330. && location.isNotEmpty())
  218331. {
  218332. if (! location.startsWithIgnoreCase ("http://"))
  218333. location = "http://" + location;
  218334. if (levelsOfRedirection++ < 3)
  218335. return open (location, headers, postData, isPost, callback, callbackContext, timeOutMs);
  218336. }
  218337. else
  218338. {
  218339. levelsOfRedirection = 0;
  218340. return true;
  218341. }
  218342. }
  218343. closeSocket();
  218344. return false;
  218345. }
  218346. int read (void* buffer, int bytesToRead)
  218347. {
  218348. fd_set readbits;
  218349. FD_ZERO (&readbits);
  218350. FD_SET (socketHandle, &readbits);
  218351. struct timeval tv;
  218352. tv.tv_sec = timeoutSeconds;
  218353. tv.tv_usec = 0;
  218354. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  218355. return 0; // (timeout)
  218356. const int bytesRead = jmax (0, (int) recv (socketHandle, buffer, bytesToRead, MSG_WAITALL));
  218357. readPosition += bytesRead;
  218358. return bytesRead;
  218359. }
  218360. int readPosition;
  218361. StringArray headerLines;
  218362. juce_UseDebuggingNewOperator
  218363. private:
  218364. int socketHandle, levelsOfRedirection;
  218365. const int timeoutSeconds;
  218366. void closeSocket()
  218367. {
  218368. if (socketHandle >= 0)
  218369. close (socketHandle);
  218370. socketHandle = -1;
  218371. }
  218372. const MemoryBlock createRequestHeader (const String& hostName,
  218373. const int hostPort,
  218374. const String& proxyName,
  218375. const int proxyPort,
  218376. const String& hostPath,
  218377. const String& originalURL,
  218378. const String& headers,
  218379. const MemoryBlock& postData,
  218380. const bool isPost)
  218381. {
  218382. String header (isPost ? "POST " : "GET ");
  218383. if (proxyName.isEmpty())
  218384. {
  218385. header << hostPath << " HTTP/1.0\r\nHost: "
  218386. << hostName << ':' << hostPort;
  218387. }
  218388. else
  218389. {
  218390. header << originalURL << " HTTP/1.0\r\nHost: "
  218391. << proxyName << ':' << proxyPort;
  218392. }
  218393. header << "\r\nUser-Agent: JUCE/"
  218394. << JUCE_MAJOR_VERSION << '.' << JUCE_MINOR_VERSION
  218395. << "\r\nConnection: Close\r\nContent-Length: "
  218396. << postData.getSize() << "\r\n"
  218397. << headers << "\r\n";
  218398. MemoryBlock mb;
  218399. mb.append (header.toUTF8(), (int) strlen (header.toUTF8()));
  218400. mb.append (postData.getData(), postData.getSize());
  218401. return mb;
  218402. }
  218403. const String readResponse (const uint32 timeOutTime)
  218404. {
  218405. int bytesRead = 0, numConsecutiveLFs = 0;
  218406. MemoryBlock buffer (1024, true);
  218407. while (numConsecutiveLFs < 2 && bytesRead < 32768
  218408. && Time::getMillisecondCounter() <= timeOutTime)
  218409. {
  218410. fd_set readbits;
  218411. FD_ZERO (&readbits);
  218412. FD_SET (socketHandle, &readbits);
  218413. struct timeval tv;
  218414. tv.tv_sec = timeoutSeconds;
  218415. tv.tv_usec = 0;
  218416. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  218417. return String::empty; // (timeout)
  218418. buffer.ensureSize (bytesRead + 8, true);
  218419. char* const dest = (char*) buffer.getData() + bytesRead;
  218420. if (recv (socketHandle, dest, 1, 0) == -1)
  218421. return String::empty;
  218422. const char lastByte = *dest;
  218423. ++bytesRead;
  218424. if (lastByte == '\n')
  218425. ++numConsecutiveLFs;
  218426. else if (lastByte != '\r')
  218427. numConsecutiveLFs = 0;
  218428. }
  218429. const String header (String::fromUTF8 ((const char*) buffer.getData()));
  218430. if (header.startsWithIgnoreCase ("HTTP/"))
  218431. return header.trimEnd();
  218432. return String::empty;
  218433. }
  218434. static bool decomposeURL (const String& url,
  218435. String& host, String& path, int& port)
  218436. {
  218437. if (! url.startsWithIgnoreCase ("http://"))
  218438. return false;
  218439. const int nextSlash = url.indexOfChar (7, '/');
  218440. int nextColon = url.indexOfChar (7, ':');
  218441. if (nextColon > nextSlash && nextSlash > 0)
  218442. nextColon = -1;
  218443. if (nextColon >= 0)
  218444. {
  218445. host = url.substring (7, nextColon);
  218446. if (nextSlash >= 0)
  218447. port = url.substring (nextColon + 1, nextSlash).getIntValue();
  218448. else
  218449. port = url.substring (nextColon + 1).getIntValue();
  218450. }
  218451. else
  218452. {
  218453. port = 80;
  218454. if (nextSlash >= 0)
  218455. host = url.substring (7, nextSlash);
  218456. else
  218457. host = url.substring (7);
  218458. }
  218459. if (nextSlash >= 0)
  218460. path = url.substring (nextSlash);
  218461. else
  218462. path = "/";
  218463. return true;
  218464. }
  218465. static const String findHeaderItem (const StringArray& lines, const String& itemName)
  218466. {
  218467. for (int i = 0; i < lines.size(); ++i)
  218468. if (lines[i].startsWithIgnoreCase (itemName))
  218469. return lines[i].substring (itemName.length()).trim();
  218470. return String::empty;
  218471. }
  218472. };
  218473. void* juce_openInternetFile (const String& url,
  218474. const String& headers,
  218475. const MemoryBlock& postData,
  218476. const bool isPost,
  218477. URL::OpenStreamProgressCallback* callback,
  218478. void* callbackContext,
  218479. int timeOutMs)
  218480. {
  218481. ScopedPointer<JUCE_HTTPSocketStream> s (new JUCE_HTTPSocketStream());
  218482. if (s->open (url, headers, postData, isPost, callback, callbackContext, timeOutMs))
  218483. return s.release();
  218484. return 0;
  218485. }
  218486. void juce_closeInternetFile (void* handle)
  218487. {
  218488. delete static_cast <JUCE_HTTPSocketStream*> (handle);
  218489. }
  218490. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  218491. {
  218492. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  218493. return s != 0 ? s->read (buffer, bytesToRead) : 0;
  218494. }
  218495. int64 juce_getInternetFileContentLength (void* handle)
  218496. {
  218497. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  218498. if (s != 0)
  218499. {
  218500. //xxx todo
  218501. jassertfalse
  218502. }
  218503. return -1;
  218504. }
  218505. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers)
  218506. {
  218507. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  218508. if (s != 0)
  218509. {
  218510. for (int i = 0; i < s->headerLines.size(); ++i)
  218511. {
  218512. const String& headersEntry = s->headerLines[i];
  218513. const String key (headersEntry.upToFirstOccurrenceOf (": ", false, false));
  218514. const String value (headersEntry.fromFirstOccurrenceOf (": ", false, false));
  218515. const String previousValue (headers [key]);
  218516. headers.set (key, previousValue.isEmpty() ? value : (previousValue + "," + value));
  218517. }
  218518. }
  218519. }
  218520. int juce_seekInInternetFile (void* handle, int newPosition)
  218521. {
  218522. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  218523. return s != 0 ? s->readPosition : 0;
  218524. }
  218525. #endif
  218526. /*** End of inlined file: juce_linux_Network.cpp ***/
  218527. /*** Start of inlined file: juce_linux_SystemStats.cpp ***/
  218528. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218529. // compiled on its own).
  218530. #if JUCE_INCLUDED_FILE
  218531. void Logger::outputDebugString (const String& text)
  218532. {
  218533. std::cerr << text << std::endl;
  218534. }
  218535. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  218536. {
  218537. return Linux;
  218538. }
  218539. const String SystemStats::getOperatingSystemName()
  218540. {
  218541. return "Linux";
  218542. }
  218543. bool SystemStats::isOperatingSystem64Bit()
  218544. {
  218545. #if JUCE_64BIT
  218546. return true;
  218547. #else
  218548. //xxx not sure how to find this out?..
  218549. return false;
  218550. #endif
  218551. }
  218552. namespace LinuxStatsHelpers
  218553. {
  218554. const String getCpuInfo (const char* const key)
  218555. {
  218556. StringArray lines;
  218557. lines.addLines (File ("/proc/cpuinfo").loadFileAsString());
  218558. for (int i = lines.size(); --i >= 0;) // (NB - it's important that this runs in reverse order)
  218559. if (lines[i].startsWithIgnoreCase (key))
  218560. return lines[i].fromFirstOccurrenceOf (":", false, false).trim();
  218561. return String::empty;
  218562. }
  218563. bool getTimeSinceStartup (timeval* const t) throw()
  218564. {
  218565. if (gettimeofday (t, 0) != 0)
  218566. return false;
  218567. static unsigned int calibrate = 0;
  218568. static bool calibrated = false;
  218569. if (! calibrated)
  218570. {
  218571. calibrated = true;
  218572. struct sysinfo sysi;
  218573. if (sysinfo (&sysi) == 0)
  218574. calibrate = t->tv_sec - sysi.uptime; // Safe to assume system was not brought up earlier than 1970!
  218575. }
  218576. t->tv_sec -= calibrate;
  218577. return true;
  218578. }
  218579. }
  218580. const String SystemStats::getCpuVendor()
  218581. {
  218582. return LinuxStatsHelpers::getCpuInfo ("vendor_id");
  218583. }
  218584. int SystemStats::getCpuSpeedInMegaherz()
  218585. {
  218586. return roundToInt (LinuxStatsHelpers::getCpuInfo ("cpu MHz").getFloatValue());
  218587. }
  218588. int SystemStats::getMemorySizeInMegabytes()
  218589. {
  218590. struct sysinfo sysi;
  218591. if (sysinfo (&sysi) == 0)
  218592. return (sysi.totalram * sysi.mem_unit / (1024 * 1024));
  218593. return 0;
  218594. }
  218595. int SystemStats::getPageSize()
  218596. {
  218597. return sysconf (_SC_PAGESIZE);
  218598. }
  218599. const String SystemStats::getLogonName()
  218600. {
  218601. const char* user = getenv ("USER");
  218602. if (user == 0)
  218603. {
  218604. struct passwd* const pw = getpwuid (getuid());
  218605. if (pw != 0)
  218606. user = pw->pw_name;
  218607. }
  218608. return String::fromUTF8 (user);
  218609. }
  218610. const String SystemStats::getFullUserName()
  218611. {
  218612. return getLogonName();
  218613. }
  218614. void SystemStats::initialiseStats()
  218615. {
  218616. const String flags (LinuxStatsHelpers::getCpuInfo ("flags"));
  218617. cpuFlags.hasMMX = flags.contains ("mmx");
  218618. cpuFlags.hasSSE = flags.contains ("sse");
  218619. cpuFlags.hasSSE2 = flags.contains ("sse2");
  218620. cpuFlags.has3DNow = flags.contains ("3dnow");
  218621. cpuFlags.numCpus = LinuxStatsHelpers::getCpuInfo ("processor").getIntValue() + 1;
  218622. }
  218623. void PlatformUtilities::fpuReset()
  218624. {
  218625. }
  218626. uint32 juce_millisecondsSinceStartup() throw()
  218627. {
  218628. timeval t;
  218629. if (LinuxStatsHelpers::getTimeSinceStartup (&t))
  218630. return (uint32) (t.tv_sec * 1000 + (t.tv_usec / 1000));
  218631. return 0;
  218632. }
  218633. int64 Time::getHighResolutionTicks() throw()
  218634. {
  218635. timeval t;
  218636. if (LinuxStatsHelpers::getTimeSinceStartup (&t))
  218637. return ((int64) t.tv_sec * (int64) 1000000) + (int64) t.tv_usec;
  218638. return 0;
  218639. }
  218640. int64 Time::getHighResolutionTicksPerSecond() throw()
  218641. {
  218642. return 1000000; // (microseconds)
  218643. }
  218644. double Time::getMillisecondCounterHiRes() throw()
  218645. {
  218646. return getHighResolutionTicks() * 0.001;
  218647. }
  218648. bool Time::setSystemTimeToThisTime() const
  218649. {
  218650. timeval t;
  218651. t.tv_sec = millisSinceEpoch % 1000000;
  218652. t.tv_usec = millisSinceEpoch - t.tv_sec;
  218653. return settimeofday (&t, 0) ? false : true;
  218654. }
  218655. #endif
  218656. /*** End of inlined file: juce_linux_SystemStats.cpp ***/
  218657. /*** Start of inlined file: juce_linux_Threads.cpp ***/
  218658. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218659. // compiled on its own).
  218660. #if JUCE_INCLUDED_FILE
  218661. /*
  218662. Note that a lot of methods that you'd expect to find in this file actually
  218663. live in juce_posix_SharedCode.h!
  218664. */
  218665. // sets the process to 0=low priority, 1=normal, 2=high, 3=realtime
  218666. void Process::setPriority (ProcessPriority prior)
  218667. {
  218668. struct sched_param param;
  218669. int policy, maxp, minp;
  218670. const int p = (int) prior;
  218671. if (p <= 1)
  218672. policy = SCHED_OTHER;
  218673. else
  218674. policy = SCHED_RR;
  218675. minp = sched_get_priority_min (policy);
  218676. maxp = sched_get_priority_max (policy);
  218677. if (p < 2)
  218678. param.sched_priority = 0;
  218679. else if (p == 2 )
  218680. // Set to middle of lower realtime priority range
  218681. param.sched_priority = minp + (maxp - minp) / 4;
  218682. else
  218683. // Set to middle of higher realtime priority range
  218684. param.sched_priority = minp + (3 * (maxp - minp) / 4);
  218685. pthread_setschedparam (pthread_self(), policy, &param);
  218686. }
  218687. void Process::terminate()
  218688. {
  218689. exit (0);
  218690. }
  218691. JUCE_API bool JUCE_CALLTYPE juce_isRunningUnderDebugger()
  218692. {
  218693. static char testResult = 0;
  218694. if (testResult == 0)
  218695. {
  218696. testResult = (char) ptrace (PT_TRACE_ME, 0, 0, 0);
  218697. if (testResult >= 0)
  218698. {
  218699. ptrace (PT_DETACH, 0, (caddr_t) 1, 0);
  218700. testResult = 1;
  218701. }
  218702. }
  218703. return testResult < 0;
  218704. }
  218705. JUCE_API bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  218706. {
  218707. return juce_isRunningUnderDebugger();
  218708. }
  218709. void Process::raisePrivilege()
  218710. {
  218711. // If running suid root, change effective user
  218712. // to root
  218713. if (geteuid() != 0 && getuid() == 0)
  218714. {
  218715. setreuid (geteuid(), getuid());
  218716. setregid (getegid(), getgid());
  218717. }
  218718. }
  218719. void Process::lowerPrivilege()
  218720. {
  218721. // If runing suid root, change effective user
  218722. // back to real user
  218723. if (geteuid() == 0 && getuid() != 0)
  218724. {
  218725. setreuid (geteuid(), getuid());
  218726. setregid (getegid(), getgid());
  218727. }
  218728. }
  218729. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  218730. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  218731. {
  218732. return dlopen (name.toUTF8(), RTLD_LOCAL | RTLD_NOW);
  218733. }
  218734. void PlatformUtilities::freeDynamicLibrary (void* handle)
  218735. {
  218736. dlclose(handle);
  218737. }
  218738. void* PlatformUtilities::getProcedureEntryPoint (void* libraryHandle, const String& procedureName)
  218739. {
  218740. return dlsym (libraryHandle, procedureName.toCString());
  218741. }
  218742. #endif
  218743. #endif
  218744. /*** End of inlined file: juce_linux_Threads.cpp ***/
  218745. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  218746. /*** Start of inlined file: juce_linux_Clipboard.cpp ***/
  218747. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218748. // compiled on its own).
  218749. #if JUCE_INCLUDED_FILE
  218750. extern Display* display;
  218751. extern Window juce_messageWindowHandle;
  218752. namespace ClipboardHelpers
  218753. {
  218754. static String localClipboardContent;
  218755. static Atom atom_UTF8_STRING;
  218756. static Atom atom_CLIPBOARD;
  218757. static Atom atom_TARGETS;
  218758. static void initSelectionAtoms()
  218759. {
  218760. static bool isInitialised = false;
  218761. if (! isInitialised)
  218762. {
  218763. atom_UTF8_STRING = XInternAtom (display, "UTF8_STRING", False);
  218764. atom_CLIPBOARD = XInternAtom (display, "CLIPBOARD", False);
  218765. atom_TARGETS = XInternAtom (display, "TARGETS", False);
  218766. }
  218767. }
  218768. // Read the content of a window property as either a locale-dependent string or an utf8 string
  218769. // works only for strings shorter than 1000000 bytes
  218770. static String readWindowProperty (Window window, Atom prop, Atom fmt)
  218771. {
  218772. String returnData;
  218773. char* clipData;
  218774. Atom actualType;
  218775. int actualFormat;
  218776. unsigned long numItems, bytesLeft;
  218777. if (XGetWindowProperty (display, window, prop,
  218778. 0L /* offset */, 1000000 /* length (max) */, False,
  218779. AnyPropertyType /* format */,
  218780. &actualType, &actualFormat, &numItems, &bytesLeft,
  218781. (unsigned char**) &clipData) == Success)
  218782. {
  218783. if (actualType == atom_UTF8_STRING && actualFormat == 8)
  218784. returnData = String::fromUTF8 (clipData, numItems);
  218785. else if (actualType == XA_STRING && actualFormat == 8)
  218786. returnData = String (clipData, numItems);
  218787. if (clipData != 0)
  218788. XFree (clipData);
  218789. jassert (bytesLeft == 0 || numItems == 1000000);
  218790. }
  218791. XDeleteProperty (display, window, prop);
  218792. return returnData;
  218793. }
  218794. // Send a SelectionRequest to the window owning the selection and waits for its answer (with a timeout) */
  218795. static bool requestSelectionContent (String& selectionContent, Atom selection, Atom requestedFormat)
  218796. {
  218797. Atom property_name = XInternAtom (display, "JUCE_SEL", false);
  218798. // The selection owner will be asked to set the JUCE_SEL property on the
  218799. // juce_messageWindowHandle with the selection content
  218800. XConvertSelection (display, selection, requestedFormat, property_name,
  218801. juce_messageWindowHandle, CurrentTime);
  218802. int count = 50; // will wait at most for 200 ms
  218803. while (--count >= 0)
  218804. {
  218805. XEvent event;
  218806. if (XCheckTypedWindowEvent (display, juce_messageWindowHandle, SelectionNotify, &event))
  218807. {
  218808. if (event.xselection.property == property_name)
  218809. {
  218810. jassert (event.xselection.requestor == juce_messageWindowHandle);
  218811. selectionContent = readWindowProperty (event.xselection.requestor,
  218812. event.xselection.property,
  218813. requestedFormat);
  218814. return true;
  218815. }
  218816. else
  218817. {
  218818. return false; // the format we asked for was denied.. (event.xselection.property == None)
  218819. }
  218820. }
  218821. // not very elegant.. we could do a select() or something like that...
  218822. // however clipboard content requesting is inherently slow on x11, it
  218823. // often takes 50ms or more so...
  218824. Thread::sleep (4);
  218825. }
  218826. return false;
  218827. }
  218828. }
  218829. // Called from the event loop in juce_linux_Messaging in response to SelectionRequest events
  218830. void juce_handleSelectionRequest (XSelectionRequestEvent &evt)
  218831. {
  218832. ClipboardHelpers::initSelectionAtoms();
  218833. // the selection content is sent to the target window as a window property
  218834. XSelectionEvent reply;
  218835. reply.type = SelectionNotify;
  218836. reply.display = evt.display;
  218837. reply.requestor = evt.requestor;
  218838. reply.selection = evt.selection;
  218839. reply.target = evt.target;
  218840. reply.property = None; // == "fail"
  218841. reply.time = evt.time;
  218842. HeapBlock <char> data;
  218843. int propertyFormat = 0, numDataItems = 0;
  218844. if (evt.selection == XA_PRIMARY || evt.selection == ClipboardHelpers::atom_CLIPBOARD)
  218845. {
  218846. if (evt.target == XA_STRING)
  218847. {
  218848. // format data according to system locale
  218849. numDataItems = ClipboardHelpers::localClipboardContent.getNumBytesAsCString() + 1;
  218850. data.calloc (numDataItems + 1);
  218851. ClipboardHelpers::localClipboardContent.copyToCString (data, numDataItems);
  218852. propertyFormat = 8; // bits/item
  218853. }
  218854. else if (evt.target == ClipboardHelpers::atom_UTF8_STRING)
  218855. {
  218856. // translate to utf8
  218857. numDataItems = ClipboardHelpers::localClipboardContent.getNumBytesAsUTF8() + 1;
  218858. data.calloc (numDataItems + 1);
  218859. ClipboardHelpers::localClipboardContent.copyToUTF8 (data, numDataItems);
  218860. propertyFormat = 8; // bits/item
  218861. }
  218862. else if (evt.target == ClipboardHelpers::atom_TARGETS)
  218863. {
  218864. // another application wants to know what we are able to send
  218865. numDataItems = 2;
  218866. propertyFormat = 32; // atoms are 32-bit
  218867. data.calloc (numDataItems * 4);
  218868. Atom* atoms = reinterpret_cast<Atom*> (data.getData());
  218869. atoms[0] = ClipboardHelpers::atom_UTF8_STRING;
  218870. atoms[1] = XA_STRING;
  218871. }
  218872. }
  218873. else
  218874. {
  218875. DBG ("requested unsupported clipboard");
  218876. }
  218877. if (data != 0)
  218878. {
  218879. const int maxReasonableSelectionSize = 1000000;
  218880. // for very big chunks of data, we should use the "INCR" protocol , which is a pain in the *ss
  218881. if (evt.property != None && numDataItems < maxReasonableSelectionSize)
  218882. {
  218883. XChangeProperty (evt.display, evt.requestor,
  218884. evt.property, evt.target,
  218885. propertyFormat /* 8 or 32 */, PropModeReplace,
  218886. reinterpret_cast<const unsigned char*> (data.getData()), numDataItems);
  218887. reply.property = evt.property; // " == success"
  218888. }
  218889. }
  218890. XSendEvent (evt.display, evt.requestor, 0, NoEventMask, (XEvent*) &reply);
  218891. }
  218892. void SystemClipboard::copyTextToClipboard (const String& clipText)
  218893. {
  218894. ClipboardHelpers::initSelectionAtoms();
  218895. ClipboardHelpers::localClipboardContent = clipText;
  218896. XSetSelectionOwner (display, XA_PRIMARY, juce_messageWindowHandle, CurrentTime);
  218897. XSetSelectionOwner (display, ClipboardHelpers::atom_CLIPBOARD, juce_messageWindowHandle, CurrentTime);
  218898. }
  218899. const String SystemClipboard::getTextFromClipboard()
  218900. {
  218901. ClipboardHelpers::initSelectionAtoms();
  218902. /* 1) try to read from the "CLIPBOARD" selection first (the "high
  218903. level" clipboard that is supposed to be filled by ctrl-C
  218904. etc). When a clipboard manager is running, the content of this
  218905. selection is preserved even when the original selection owner
  218906. exits.
  218907. 2) and then try to read from "PRIMARY" selection (the "legacy" selection
  218908. filled by good old x11 apps such as xterm)
  218909. */
  218910. String content;
  218911. Atom selection = XA_PRIMARY;
  218912. Window selectionOwner = None;
  218913. if ((selectionOwner = XGetSelectionOwner (display, selection)) == None)
  218914. {
  218915. selection = ClipboardHelpers::atom_CLIPBOARD;
  218916. selectionOwner = XGetSelectionOwner (display, selection);
  218917. }
  218918. if (selectionOwner != None)
  218919. {
  218920. if (selectionOwner == juce_messageWindowHandle)
  218921. {
  218922. content = ClipboardHelpers::localClipboardContent;
  218923. }
  218924. else
  218925. {
  218926. // first try: we want an utf8 string
  218927. bool ok = ClipboardHelpers::requestSelectionContent (content, selection, ClipboardHelpers::atom_UTF8_STRING);
  218928. if (! ok)
  218929. {
  218930. // second chance, ask for a good old locale-dependent string ..
  218931. ok = ClipboardHelpers::requestSelectionContent (content, selection, XA_STRING);
  218932. }
  218933. }
  218934. }
  218935. return content;
  218936. }
  218937. #endif
  218938. /*** End of inlined file: juce_linux_Clipboard.cpp ***/
  218939. /*** Start of inlined file: juce_linux_Messaging.cpp ***/
  218940. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218941. // compiled on its own).
  218942. #if JUCE_INCLUDED_FILE
  218943. #if JUCE_DEBUG && ! defined (JUCE_DEBUG_XERRORS)
  218944. #define JUCE_DEBUG_XERRORS 1
  218945. #endif
  218946. Display* display = 0;
  218947. Window juce_messageWindowHandle = None;
  218948. XContext windowHandleXContext; // This is referenced from Windowing.cpp
  218949. extern void juce_windowMessageReceive (XEvent* event); // Defined in Windowing.cpp
  218950. extern void juce_handleSelectionRequest (XSelectionRequestEvent &evt); // Defined in Clipboard.cpp
  218951. ScopedXLock::ScopedXLock() { XLockDisplay (display); }
  218952. ScopedXLock::~ScopedXLock() { XUnlockDisplay (display); }
  218953. class InternalMessageQueue
  218954. {
  218955. public:
  218956. InternalMessageQueue()
  218957. : bytesInSocket (0),
  218958. totalEventCount (0)
  218959. {
  218960. int ret = ::socketpair (AF_LOCAL, SOCK_STREAM, 0, fd);
  218961. (void) ret; jassert (ret == 0);
  218962. //setNonBlocking (fd[0]);
  218963. //setNonBlocking (fd[1]);
  218964. }
  218965. ~InternalMessageQueue()
  218966. {
  218967. close (fd[0]);
  218968. close (fd[1]);
  218969. clearSingletonInstance();
  218970. }
  218971. void postMessage (Message* msg)
  218972. {
  218973. const int maxBytesInSocketQueue = 128;
  218974. ScopedLock sl (lock);
  218975. queue.add (msg);
  218976. if (bytesInSocket < maxBytesInSocketQueue)
  218977. {
  218978. ++bytesInSocket;
  218979. ScopedUnlock ul (lock);
  218980. const unsigned char x = 0xff;
  218981. size_t bytesWritten = write (fd[0], &x, 1);
  218982. (void) bytesWritten;
  218983. }
  218984. }
  218985. bool isEmpty() const
  218986. {
  218987. ScopedLock sl (lock);
  218988. return queue.size() == 0;
  218989. }
  218990. bool dispatchNextEvent()
  218991. {
  218992. // This alternates between giving priority to XEvents or internal messages,
  218993. // to keep everything running smoothly..
  218994. if ((++totalEventCount & 1) != 0)
  218995. return dispatchNextXEvent() || dispatchNextInternalMessage();
  218996. else
  218997. return dispatchNextInternalMessage() || dispatchNextXEvent();
  218998. }
  218999. // Wait for an event (either XEvent, or an internal Message)
  219000. bool sleepUntilEvent (const int timeoutMs)
  219001. {
  219002. if (! isEmpty())
  219003. return true;
  219004. if (display != 0)
  219005. {
  219006. ScopedXLock xlock;
  219007. if (XPending (display))
  219008. return true;
  219009. }
  219010. struct timeval tv;
  219011. tv.tv_sec = 0;
  219012. tv.tv_usec = timeoutMs * 1000;
  219013. int fd0 = getWaitHandle();
  219014. int fdmax = fd0;
  219015. fd_set readset;
  219016. FD_ZERO (&readset);
  219017. FD_SET (fd0, &readset);
  219018. if (display != 0)
  219019. {
  219020. ScopedXLock xlock;
  219021. int fd1 = XConnectionNumber (display);
  219022. FD_SET (fd1, &readset);
  219023. fdmax = jmax (fd0, fd1);
  219024. }
  219025. const int ret = select (fdmax + 1, &readset, 0, 0, &tv);
  219026. return (ret > 0); // ret <= 0 if error or timeout
  219027. }
  219028. struct MessageThreadFuncCall
  219029. {
  219030. enum { uniqueID = 0x73774623 };
  219031. MessageCallbackFunction* func;
  219032. void* parameter;
  219033. void* result;
  219034. CriticalSection lock;
  219035. WaitableEvent event;
  219036. };
  219037. juce_DeclareSingleton_SingleThreaded_Minimal (InternalMessageQueue);
  219038. private:
  219039. CriticalSection lock;
  219040. OwnedArray <Message> queue;
  219041. int fd[2];
  219042. int bytesInSocket;
  219043. int totalEventCount;
  219044. int getWaitHandle() const throw() { return fd[1]; }
  219045. static bool setNonBlocking (int handle)
  219046. {
  219047. int socketFlags = fcntl (handle, F_GETFL, 0);
  219048. if (socketFlags == -1)
  219049. return false;
  219050. socketFlags |= O_NONBLOCK;
  219051. return fcntl (handle, F_SETFL, socketFlags) == 0;
  219052. }
  219053. static bool dispatchNextXEvent()
  219054. {
  219055. if (display == 0)
  219056. return false;
  219057. XEvent evt;
  219058. {
  219059. ScopedXLock xlock;
  219060. if (! XPending (display))
  219061. return false;
  219062. XNextEvent (display, &evt);
  219063. }
  219064. if (evt.type == SelectionRequest && evt.xany.window == juce_messageWindowHandle)
  219065. juce_handleSelectionRequest (evt.xselectionrequest);
  219066. else if (evt.xany.window != juce_messageWindowHandle)
  219067. juce_windowMessageReceive (&evt);
  219068. return true;
  219069. }
  219070. Message* popNextMessage()
  219071. {
  219072. ScopedLock sl (lock);
  219073. if (bytesInSocket > 0)
  219074. {
  219075. --bytesInSocket;
  219076. ScopedUnlock ul (lock);
  219077. unsigned char x;
  219078. size_t numBytes = read (fd[1], &x, 1);
  219079. (void) numBytes;
  219080. }
  219081. return queue.removeAndReturn (0);
  219082. }
  219083. bool dispatchNextInternalMessage()
  219084. {
  219085. ScopedPointer <Message> msg (popNextMessage());
  219086. if (msg == 0)
  219087. return false;
  219088. if (msg->intParameter1 == MessageThreadFuncCall::uniqueID)
  219089. {
  219090. // Handle callback message
  219091. MessageThreadFuncCall* const call = (MessageThreadFuncCall*) msg->pointerParameter;
  219092. call->result = (*(call->func)) (call->parameter);
  219093. call->event.signal();
  219094. }
  219095. else
  219096. {
  219097. // Handle "normal" messages
  219098. MessageManager::getInstance()->deliverMessage (msg.release());
  219099. }
  219100. return true;
  219101. }
  219102. };
  219103. juce_ImplementSingleton_SingleThreaded (InternalMessageQueue);
  219104. namespace LinuxErrorHandling
  219105. {
  219106. static bool errorOccurred = false;
  219107. static bool keyboardBreakOccurred = false;
  219108. static XErrorHandler oldErrorHandler = (XErrorHandler) 0;
  219109. static XIOErrorHandler oldIOErrorHandler = (XIOErrorHandler) 0;
  219110. // Usually happens when client-server connection is broken
  219111. static int ioErrorHandler (Display* display)
  219112. {
  219113. DBG ("ERROR: connection to X server broken.. terminating.");
  219114. if (JUCEApplication::isStandaloneApp())
  219115. MessageManager::getInstance()->stopDispatchLoop();
  219116. errorOccurred = true;
  219117. return 0;
  219118. }
  219119. // A protocol error has occurred
  219120. static int juce_XErrorHandler (Display* display, XErrorEvent* event)
  219121. {
  219122. #if JUCE_DEBUG_XERRORS
  219123. char errorStr[64] = { 0 };
  219124. char requestStr[64] = { 0 };
  219125. XGetErrorText (display, event->error_code, errorStr, 64);
  219126. XGetErrorDatabaseText (display, "XRequest", String (event->request_code).toCString(), "Unknown", requestStr, 64);
  219127. DBG ("ERROR: X returned " + String (errorStr) + " for operation " + String (requestStr));
  219128. #endif
  219129. return 0;
  219130. }
  219131. static void installXErrorHandlers()
  219132. {
  219133. oldIOErrorHandler = XSetIOErrorHandler (ioErrorHandler);
  219134. oldErrorHandler = XSetErrorHandler (juce_XErrorHandler);
  219135. }
  219136. static void removeXErrorHandlers()
  219137. {
  219138. if (JUCEApplication::isStandaloneApp())
  219139. {
  219140. XSetIOErrorHandler (oldIOErrorHandler);
  219141. oldIOErrorHandler = 0;
  219142. XSetErrorHandler (oldErrorHandler);
  219143. oldErrorHandler = 0;
  219144. }
  219145. }
  219146. static void keyboardBreakSignalHandler (int sig)
  219147. {
  219148. if (sig == SIGINT)
  219149. keyboardBreakOccurred = true;
  219150. }
  219151. static void installKeyboardBreakHandler()
  219152. {
  219153. struct sigaction saction;
  219154. sigset_t maskSet;
  219155. sigemptyset (&maskSet);
  219156. saction.sa_handler = keyboardBreakSignalHandler;
  219157. saction.sa_mask = maskSet;
  219158. saction.sa_flags = 0;
  219159. sigaction (SIGINT, &saction, 0);
  219160. }
  219161. }
  219162. void MessageManager::doPlatformSpecificInitialisation()
  219163. {
  219164. if (JUCEApplication::isStandaloneApp())
  219165. {
  219166. // Initialise xlib for multiple thread support
  219167. static bool initThreadCalled = false;
  219168. if (! initThreadCalled)
  219169. {
  219170. if (! XInitThreads())
  219171. {
  219172. // This is fatal! Print error and closedown
  219173. Logger::outputDebugString ("Failed to initialise xlib thread support.");
  219174. Process::terminate();
  219175. return;
  219176. }
  219177. initThreadCalled = true;
  219178. }
  219179. LinuxErrorHandling::installXErrorHandlers();
  219180. LinuxErrorHandling::installKeyboardBreakHandler();
  219181. }
  219182. // Create the internal message queue
  219183. InternalMessageQueue::getInstance();
  219184. // Try to connect to a display
  219185. String displayName (getenv ("DISPLAY"));
  219186. if (displayName.isEmpty())
  219187. displayName = ":0.0";
  219188. display = XOpenDisplay (displayName.toCString());
  219189. if (display != 0) // This is not fatal! we can run headless.
  219190. {
  219191. // Create a context to store user data associated with Windows we create in WindowDriver
  219192. windowHandleXContext = XUniqueContext();
  219193. // We're only interested in client messages for this window, which are always sent
  219194. XSetWindowAttributes swa;
  219195. swa.event_mask = NoEventMask;
  219196. // Create our message window (this will never be mapped)
  219197. const int screen = DefaultScreen (display);
  219198. juce_messageWindowHandle = XCreateWindow (display, RootWindow (display, screen),
  219199. 0, 0, 1, 1, 0, 0, InputOnly,
  219200. DefaultVisual (display, screen),
  219201. CWEventMask, &swa);
  219202. }
  219203. }
  219204. void MessageManager::doPlatformSpecificShutdown()
  219205. {
  219206. InternalMessageQueue::deleteInstance();
  219207. if (display != 0 && ! LinuxErrorHandling::errorOccurred)
  219208. {
  219209. XDestroyWindow (display, juce_messageWindowHandle);
  219210. XCloseDisplay (display);
  219211. juce_messageWindowHandle = 0;
  219212. display = 0;
  219213. LinuxErrorHandling::removeXErrorHandlers();
  219214. }
  219215. }
  219216. bool juce_postMessageToSystemQueue (Message* message)
  219217. {
  219218. if (LinuxErrorHandling::errorOccurred)
  219219. return false;
  219220. InternalMessageQueue::getInstanceWithoutCreating()->postMessage (message);
  219221. return true;
  219222. }
  219223. void MessageManager::broadcastMessage (const String& value)
  219224. {
  219225. /* TODO */
  219226. }
  219227. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* func, void* parameter)
  219228. {
  219229. if (LinuxErrorHandling::errorOccurred)
  219230. return 0;
  219231. if (isThisTheMessageThread())
  219232. return func (parameter);
  219233. InternalMessageQueue::MessageThreadFuncCall messageCallContext;
  219234. messageCallContext.func = func;
  219235. messageCallContext.parameter = parameter;
  219236. InternalMessageQueue::getInstanceWithoutCreating()
  219237. ->postMessage (new Message (InternalMessageQueue::MessageThreadFuncCall::uniqueID,
  219238. 0, 0, &messageCallContext));
  219239. // Wait for it to complete before continuing
  219240. messageCallContext.event.wait();
  219241. return messageCallContext.result;
  219242. }
  219243. // this function expects that it will NEVER be called simultaneously for two concurrent threads
  219244. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages)
  219245. {
  219246. while (! LinuxErrorHandling::errorOccurred)
  219247. {
  219248. if (LinuxErrorHandling::keyboardBreakOccurred)
  219249. {
  219250. LinuxErrorHandling::errorOccurred = true;
  219251. if (JUCEApplication::isStandaloneApp())
  219252. Process::terminate();
  219253. break;
  219254. }
  219255. if (InternalMessageQueue::getInstanceWithoutCreating()->dispatchNextEvent())
  219256. return true;
  219257. if (returnIfNoPendingMessages)
  219258. break;
  219259. InternalMessageQueue::getInstanceWithoutCreating()->sleepUntilEvent (2000);
  219260. }
  219261. return false;
  219262. }
  219263. #endif
  219264. /*** End of inlined file: juce_linux_Messaging.cpp ***/
  219265. /*** Start of inlined file: juce_linux_Fonts.cpp ***/
  219266. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  219267. // compiled on its own).
  219268. #if JUCE_INCLUDED_FILE
  219269. class FreeTypeFontFace
  219270. {
  219271. public:
  219272. enum FontStyle
  219273. {
  219274. Plain = 0,
  219275. Bold = 1,
  219276. Italic = 2
  219277. };
  219278. FreeTypeFontFace (const String& familyName)
  219279. : hasSerif (false),
  219280. monospaced (false)
  219281. {
  219282. family = familyName;
  219283. }
  219284. void setFileName (const String& name, const int faceIndex, FontStyle style)
  219285. {
  219286. if (names [(int) style].fileName.isEmpty())
  219287. {
  219288. names [(int) style].fileName = name;
  219289. names [(int) style].faceIndex = faceIndex;
  219290. }
  219291. }
  219292. const String& getFamilyName() const throw() { return family; }
  219293. const String& getFileName (const int style, int& faceIndex) const throw()
  219294. {
  219295. faceIndex = names[style].faceIndex;
  219296. return names[style].fileName;
  219297. }
  219298. void setMonospaced (bool mono) throw() { monospaced = mono; }
  219299. bool getMonospaced() const throw() { return monospaced; }
  219300. void setSerif (const bool serif) throw() { hasSerif = serif; }
  219301. bool getSerif() const throw() { return hasSerif; }
  219302. private:
  219303. String family;
  219304. struct FontNameIndex
  219305. {
  219306. String fileName;
  219307. int faceIndex;
  219308. };
  219309. FontNameIndex names[4];
  219310. bool hasSerif, monospaced;
  219311. };
  219312. class FreeTypeInterface : public DeletedAtShutdown
  219313. {
  219314. public:
  219315. FreeTypeInterface()
  219316. : ftLib (0),
  219317. lastFace (0),
  219318. lastBold (false),
  219319. lastItalic (false)
  219320. {
  219321. if (FT_Init_FreeType (&ftLib) != 0)
  219322. {
  219323. ftLib = 0;
  219324. DBG ("Failed to initialize FreeType");
  219325. }
  219326. StringArray fontDirs;
  219327. fontDirs.addTokens (String::fromUTF8 (getenv ("JUCE_FONT_PATH")), ";,", String::empty);
  219328. fontDirs.removeEmptyStrings (true);
  219329. if (fontDirs.size() == 0)
  219330. {
  219331. XmlDocument fontsConfig (File ("/etc/fonts/fonts.conf"));
  219332. const ScopedPointer<XmlElement> fontsInfo (fontsConfig.getDocumentElement());
  219333. if (fontsInfo != 0)
  219334. {
  219335. forEachXmlChildElementWithTagName (*fontsInfo, e, "dir")
  219336. {
  219337. fontDirs.add (e->getAllSubText().trim());
  219338. }
  219339. }
  219340. }
  219341. if (fontDirs.size() == 0)
  219342. fontDirs.add ("/usr/X11R6/lib/X11/fonts");
  219343. for (int i = 0; i < fontDirs.size(); ++i)
  219344. enumerateFaces (fontDirs[i]);
  219345. }
  219346. ~FreeTypeInterface()
  219347. {
  219348. if (lastFace != 0)
  219349. FT_Done_Face (lastFace);
  219350. if (ftLib != 0)
  219351. FT_Done_FreeType (ftLib);
  219352. clearSingletonInstance();
  219353. }
  219354. FreeTypeFontFace* findOrCreate (const String& familyName, const bool create = false)
  219355. {
  219356. for (int i = 0; i < faces.size(); i++)
  219357. if (faces[i]->getFamilyName() == familyName)
  219358. return faces[i];
  219359. if (! create)
  219360. return 0;
  219361. FreeTypeFontFace* newFace = new FreeTypeFontFace (familyName);
  219362. faces.add (newFace);
  219363. return newFace;
  219364. }
  219365. // Enumerate all font faces available in a given directory
  219366. void enumerateFaces (const String& path)
  219367. {
  219368. File dirPath (path);
  219369. if (path.isEmpty() || ! dirPath.isDirectory())
  219370. return;
  219371. DirectoryIterator di (dirPath, true);
  219372. while (di.next())
  219373. {
  219374. File possible (di.getFile());
  219375. if (possible.hasFileExtension ("ttf")
  219376. || possible.hasFileExtension ("pfb")
  219377. || possible.hasFileExtension ("pcf"))
  219378. {
  219379. FT_Face face;
  219380. int faceIndex = 0;
  219381. int numFaces = 0;
  219382. do
  219383. {
  219384. if (FT_New_Face (ftLib, possible.getFullPathName().toUTF8(),
  219385. faceIndex, &face) == 0)
  219386. {
  219387. if (faceIndex == 0)
  219388. numFaces = face->num_faces;
  219389. if ((face->face_flags & FT_FACE_FLAG_SCALABLE) != 0)
  219390. {
  219391. FreeTypeFontFace* const newFace = findOrCreate (face->family_name, true);
  219392. int style = (int) FreeTypeFontFace::Plain;
  219393. if ((face->style_flags & FT_STYLE_FLAG_BOLD) != 0)
  219394. style |= (int) FreeTypeFontFace::Bold;
  219395. if ((face->style_flags & FT_STYLE_FLAG_ITALIC) != 0)
  219396. style |= (int) FreeTypeFontFace::Italic;
  219397. newFace->setFileName (possible.getFullPathName(), faceIndex, (FreeTypeFontFace::FontStyle) style);
  219398. newFace->setMonospaced ((face->face_flags & FT_FACE_FLAG_FIXED_WIDTH) != 0);
  219399. // Surely there must be a better way to do this?
  219400. const String name (face->family_name);
  219401. newFace->setSerif (! (name.containsIgnoreCase ("Sans")
  219402. || name.containsIgnoreCase ("Verdana")
  219403. || name.containsIgnoreCase ("Arial")));
  219404. }
  219405. FT_Done_Face (face);
  219406. }
  219407. ++faceIndex;
  219408. }
  219409. while (faceIndex < numFaces);
  219410. }
  219411. }
  219412. }
  219413. // Create a FreeType face object for a given font
  219414. FT_Face createFT_Face (const String& fontName, const bool bold, const bool italic)
  219415. {
  219416. FT_Face face = 0;
  219417. if (fontName == lastFontName && bold == lastBold && italic == lastItalic)
  219418. {
  219419. face = lastFace;
  219420. }
  219421. else
  219422. {
  219423. if (lastFace != 0)
  219424. {
  219425. FT_Done_Face (lastFace);
  219426. lastFace = 0;
  219427. }
  219428. lastFontName = fontName;
  219429. lastBold = bold;
  219430. lastItalic = italic;
  219431. FreeTypeFontFace* const ftFace = findOrCreate (fontName);
  219432. if (ftFace != 0)
  219433. {
  219434. int style = (int) FreeTypeFontFace::Plain;
  219435. if (bold)
  219436. style |= (int) FreeTypeFontFace::Bold;
  219437. if (italic)
  219438. style |= (int) FreeTypeFontFace::Italic;
  219439. int faceIndex;
  219440. String fileName (ftFace->getFileName (style, faceIndex));
  219441. if (fileName.isEmpty())
  219442. {
  219443. style ^= (int) FreeTypeFontFace::Bold;
  219444. fileName = ftFace->getFileName (style, faceIndex);
  219445. if (fileName.isEmpty())
  219446. {
  219447. style ^= (int) FreeTypeFontFace::Bold;
  219448. style ^= (int) FreeTypeFontFace::Italic;
  219449. fileName = ftFace->getFileName (style, faceIndex);
  219450. if (! fileName.length())
  219451. {
  219452. style ^= (int) FreeTypeFontFace::Bold;
  219453. fileName = ftFace->getFileName (style, faceIndex);
  219454. }
  219455. }
  219456. }
  219457. if (! FT_New_Face (ftLib, fileName.toUTF8(), faceIndex, &lastFace))
  219458. {
  219459. face = lastFace;
  219460. // If there isn't a unicode charmap then select the first one.
  219461. if (FT_Select_Charmap (face, ft_encoding_unicode))
  219462. FT_Set_Charmap (face, face->charmaps[0]);
  219463. }
  219464. }
  219465. }
  219466. return face;
  219467. }
  219468. bool addGlyph (FT_Face face, CustomTypeface& dest, uint32 character)
  219469. {
  219470. const unsigned int glyphIndex = FT_Get_Char_Index (face, character);
  219471. const float height = (float) (face->ascender - face->descender);
  219472. const float scaleX = 1.0f / height;
  219473. const float scaleY = -1.0f / height;
  219474. Path destShape;
  219475. if (FT_Load_Glyph (face, glyphIndex, FT_LOAD_NO_SCALE | FT_LOAD_NO_BITMAP | FT_LOAD_IGNORE_TRANSFORM) != 0
  219476. || face->glyph->format != ft_glyph_format_outline)
  219477. {
  219478. return false;
  219479. }
  219480. const FT_Outline* const outline = &face->glyph->outline;
  219481. const short* const contours = outline->contours;
  219482. const char* const tags = outline->tags;
  219483. FT_Vector* const points = outline->points;
  219484. for (int c = 0; c < outline->n_contours; c++)
  219485. {
  219486. const int startPoint = (c == 0) ? 0 : contours [c - 1] + 1;
  219487. const int endPoint = contours[c];
  219488. for (int p = startPoint; p <= endPoint; p++)
  219489. {
  219490. const float x = scaleX * points[p].x;
  219491. const float y = scaleY * points[p].y;
  219492. if (p == startPoint)
  219493. {
  219494. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  219495. {
  219496. float x2 = scaleX * points [endPoint].x;
  219497. float y2 = scaleY * points [endPoint].y;
  219498. if (FT_CURVE_TAG (tags[endPoint]) != FT_Curve_Tag_On)
  219499. {
  219500. x2 = (x + x2) * 0.5f;
  219501. y2 = (y + y2) * 0.5f;
  219502. }
  219503. destShape.startNewSubPath (x2, y2);
  219504. }
  219505. else
  219506. {
  219507. destShape.startNewSubPath (x, y);
  219508. }
  219509. }
  219510. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_On)
  219511. {
  219512. if (p != startPoint)
  219513. destShape.lineTo (x, y);
  219514. }
  219515. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  219516. {
  219517. const int nextIndex = (p == endPoint) ? startPoint : p + 1;
  219518. float x2 = scaleX * points [nextIndex].x;
  219519. float y2 = scaleY * points [nextIndex].y;
  219520. if (FT_CURVE_TAG (tags [nextIndex]) == FT_Curve_Tag_Conic)
  219521. {
  219522. x2 = (x + x2) * 0.5f;
  219523. y2 = (y + y2) * 0.5f;
  219524. }
  219525. else
  219526. {
  219527. ++p;
  219528. }
  219529. destShape.quadraticTo (x, y, x2, y2);
  219530. }
  219531. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Cubic)
  219532. {
  219533. if (p >= endPoint)
  219534. return false;
  219535. const int next1 = p + 1;
  219536. const int next2 = (p == (endPoint - 1)) ? startPoint : p + 2;
  219537. const float x2 = scaleX * points [next1].x;
  219538. const float y2 = scaleY * points [next1].y;
  219539. const float x3 = scaleX * points [next2].x;
  219540. const float y3 = scaleY * points [next2].y;
  219541. if (FT_CURVE_TAG (tags[next1]) != FT_Curve_Tag_Cubic
  219542. || FT_CURVE_TAG (tags[next2]) != FT_Curve_Tag_On)
  219543. return false;
  219544. destShape.cubicTo (x, y, x2, y2, x3, y3);
  219545. p += 2;
  219546. }
  219547. }
  219548. destShape.closeSubPath();
  219549. }
  219550. dest.addGlyph (character, destShape, face->glyph->metrics.horiAdvance / height);
  219551. if ((face->face_flags & FT_FACE_FLAG_KERNING) != 0)
  219552. addKerning (face, dest, character, glyphIndex);
  219553. return true;
  219554. }
  219555. void addKerning (FT_Face face, CustomTypeface& dest, const uint32 character, const uint32 glyphIndex)
  219556. {
  219557. const float height = (float) (face->ascender - face->descender);
  219558. uint32 rightGlyphIndex;
  219559. uint32 rightCharCode = FT_Get_First_Char (face, &rightGlyphIndex);
  219560. while (rightGlyphIndex != 0)
  219561. {
  219562. FT_Vector kerning;
  219563. if (FT_Get_Kerning (face, glyphIndex, rightGlyphIndex, ft_kerning_unscaled, &kerning) == 0)
  219564. {
  219565. if (kerning.x != 0)
  219566. dest.addKerningPair (character, rightCharCode, kerning.x / height);
  219567. }
  219568. rightCharCode = FT_Get_Next_Char (face, rightCharCode, &rightGlyphIndex);
  219569. }
  219570. }
  219571. // Add a glyph to a font
  219572. bool addGlyphToFont (const uint32 character, const String& fontName,
  219573. bool bold, bool italic, CustomTypeface& dest)
  219574. {
  219575. FT_Face face = createFT_Face (fontName, bold, italic);
  219576. return face != 0 && addGlyph (face, dest, character);
  219577. }
  219578. void getFamilyNames (StringArray& familyNames) const
  219579. {
  219580. for (int i = 0; i < faces.size(); i++)
  219581. familyNames.add (faces[i]->getFamilyName());
  219582. }
  219583. void getMonospacedNames (StringArray& monoSpaced) const
  219584. {
  219585. for (int i = 0; i < faces.size(); i++)
  219586. if (faces[i]->getMonospaced())
  219587. monoSpaced.add (faces[i]->getFamilyName());
  219588. }
  219589. void getSerifNames (StringArray& serif) const
  219590. {
  219591. for (int i = 0; i < faces.size(); i++)
  219592. if (faces[i]->getSerif())
  219593. serif.add (faces[i]->getFamilyName());
  219594. }
  219595. void getSansSerifNames (StringArray& sansSerif) const
  219596. {
  219597. for (int i = 0; i < faces.size(); i++)
  219598. if (! faces[i]->getSerif())
  219599. sansSerif.add (faces[i]->getFamilyName());
  219600. }
  219601. juce_DeclareSingleton_SingleThreaded_Minimal (FreeTypeInterface)
  219602. private:
  219603. FT_Library ftLib;
  219604. FT_Face lastFace;
  219605. String lastFontName;
  219606. bool lastBold, lastItalic;
  219607. OwnedArray<FreeTypeFontFace> faces;
  219608. };
  219609. juce_ImplementSingleton_SingleThreaded (FreeTypeInterface)
  219610. class FreetypeTypeface : public CustomTypeface
  219611. {
  219612. public:
  219613. FreetypeTypeface (const Font& font)
  219614. {
  219615. FT_Face face = FreeTypeInterface::getInstance()
  219616. ->createFT_Face (font.getTypefaceName(), font.isBold(), font.isItalic());
  219617. if (face == 0)
  219618. {
  219619. #if JUCE_DEBUG
  219620. String msg ("Failed to create typeface: ");
  219621. msg << font.getTypefaceName() << " " << (font.isBold() ? 'B' : ' ') << (font.isItalic() ? 'I' : ' ');
  219622. DBG (msg);
  219623. #endif
  219624. }
  219625. else
  219626. {
  219627. setCharacteristics (font.getTypefaceName(),
  219628. face->ascender / (float) (face->ascender - face->descender),
  219629. font.isBold(), font.isItalic(),
  219630. L' ');
  219631. }
  219632. }
  219633. bool loadGlyphIfPossible (juce_wchar character)
  219634. {
  219635. return FreeTypeInterface::getInstance()
  219636. ->addGlyphToFont (character, name, isBold, isItalic, *this);
  219637. }
  219638. };
  219639. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  219640. {
  219641. return new FreetypeTypeface (font);
  219642. }
  219643. const StringArray Font::findAllTypefaceNames()
  219644. {
  219645. StringArray s;
  219646. FreeTypeInterface::getInstance()->getFamilyNames (s);
  219647. s.sort (true);
  219648. return s;
  219649. }
  219650. namespace
  219651. {
  219652. const String pickBestFont (const StringArray& names,
  219653. const char* const choicesString)
  219654. {
  219655. StringArray choices;
  219656. choices.addTokens (String (choicesString), ",", String::empty);
  219657. choices.trim();
  219658. choices.removeEmptyStrings();
  219659. int i, j;
  219660. for (j = 0; j < choices.size(); ++j)
  219661. if (names.contains (choices[j], true))
  219662. return choices[j];
  219663. for (j = 0; j < choices.size(); ++j)
  219664. for (i = 0; i < names.size(); i++)
  219665. if (names[i].startsWithIgnoreCase (choices[j]))
  219666. return names[i];
  219667. for (j = 0; j < choices.size(); ++j)
  219668. for (i = 0; i < names.size(); i++)
  219669. if (names[i].containsIgnoreCase (choices[j]))
  219670. return names[i];
  219671. return names[0];
  219672. }
  219673. const String linux_getDefaultSansSerifFontName()
  219674. {
  219675. StringArray allFonts;
  219676. FreeTypeInterface::getInstance()->getSansSerifNames (allFonts);
  219677. return pickBestFont (allFonts, "Verdana, Bitstream Vera Sans, Luxi Sans, Sans");
  219678. }
  219679. const String linux_getDefaultSerifFontName()
  219680. {
  219681. StringArray allFonts;
  219682. FreeTypeInterface::getInstance()->getSerifNames (allFonts);
  219683. return pickBestFont (allFonts, "Bitstream Vera Serif, Times, Nimbus Roman, Serif");
  219684. }
  219685. const String linux_getDefaultMonospacedFontName()
  219686. {
  219687. StringArray allFonts;
  219688. FreeTypeInterface::getInstance()->getMonospacedNames (allFonts);
  219689. return pickBestFont (allFonts, "Bitstream Vera Sans Mono, Courier, Sans Mono, Mono");
  219690. }
  219691. }
  219692. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  219693. {
  219694. defaultSans = linux_getDefaultSansSerifFontName();
  219695. defaultSerif = linux_getDefaultSerifFontName();
  219696. defaultFixed = linux_getDefaultMonospacedFontName();
  219697. }
  219698. #endif
  219699. /*** End of inlined file: juce_linux_Fonts.cpp ***/
  219700. /*** Start of inlined file: juce_linux_Windowing.cpp ***/
  219701. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  219702. // compiled on its own).
  219703. #if JUCE_INCLUDED_FILE
  219704. // These are defined in juce_linux_Messaging.cpp
  219705. extern Display* display;
  219706. extern XContext windowHandleXContext;
  219707. namespace Atoms
  219708. {
  219709. enum ProtocolItems
  219710. {
  219711. TAKE_FOCUS = 0,
  219712. DELETE_WINDOW = 1,
  219713. PING = 2
  219714. };
  219715. static Atom Protocols, ProtocolList[3], ChangeState, State,
  219716. ActiveWin, Pid, WindowType, WindowState,
  219717. XdndAware, XdndEnter, XdndLeave, XdndPosition, XdndStatus,
  219718. XdndDrop, XdndFinished, XdndSelection, XdndTypeList, XdndActionList,
  219719. XdndActionDescription, XdndActionCopy,
  219720. allowedActions[5],
  219721. allowedMimeTypes[2];
  219722. const unsigned long DndVersion = 3;
  219723. static void initialiseAtoms()
  219724. {
  219725. static bool atomsInitialised = false;
  219726. if (! atomsInitialised)
  219727. {
  219728. atomsInitialised = true;
  219729. Protocols = XInternAtom (display, "WM_PROTOCOLS", True);
  219730. ProtocolList [TAKE_FOCUS] = XInternAtom (display, "WM_TAKE_FOCUS", True);
  219731. ProtocolList [DELETE_WINDOW] = XInternAtom (display, "WM_DELETE_WINDOW", True);
  219732. ProtocolList [PING] = XInternAtom (display, "_NET_WM_PING", True);
  219733. ChangeState = XInternAtom (display, "WM_CHANGE_STATE", True);
  219734. State = XInternAtom (display, "WM_STATE", True);
  219735. ActiveWin = XInternAtom (display, "_NET_ACTIVE_WINDOW", False);
  219736. Pid = XInternAtom (display, "_NET_WM_PID", False);
  219737. WindowType = XInternAtom (display, "_NET_WM_WINDOW_TYPE", True);
  219738. WindowState = XInternAtom (display, "_NET_WM_STATE", True);
  219739. XdndAware = XInternAtom (display, "XdndAware", False);
  219740. XdndEnter = XInternAtom (display, "XdndEnter", False);
  219741. XdndLeave = XInternAtom (display, "XdndLeave", False);
  219742. XdndPosition = XInternAtom (display, "XdndPosition", False);
  219743. XdndStatus = XInternAtom (display, "XdndStatus", False);
  219744. XdndDrop = XInternAtom (display, "XdndDrop", False);
  219745. XdndFinished = XInternAtom (display, "XdndFinished", False);
  219746. XdndSelection = XInternAtom (display, "XdndSelection", False);
  219747. XdndTypeList = XInternAtom (display, "XdndTypeList", False);
  219748. XdndActionList = XInternAtom (display, "XdndActionList", False);
  219749. XdndActionCopy = XInternAtom (display, "XdndActionCopy", False);
  219750. XdndActionDescription = XInternAtom (display, "XdndActionDescription", False);
  219751. allowedMimeTypes[0] = XInternAtom (display, "text/plain", False);
  219752. allowedMimeTypes[1] = XInternAtom (display, "text/uri-list", False);
  219753. allowedActions[0] = XInternAtom (display, "XdndActionMove", False);
  219754. allowedActions[1] = XdndActionCopy;
  219755. allowedActions[2] = XInternAtom (display, "XdndActionLink", False);
  219756. allowedActions[3] = XInternAtom (display, "XdndActionAsk", False);
  219757. allowedActions[4] = XInternAtom (display, "XdndActionPrivate", False);
  219758. }
  219759. }
  219760. }
  219761. namespace Keys
  219762. {
  219763. enum MouseButtons
  219764. {
  219765. NoButton = 0,
  219766. LeftButton = 1,
  219767. MiddleButton = 2,
  219768. RightButton = 3,
  219769. WheelUp = 4,
  219770. WheelDown = 5
  219771. };
  219772. static int AltMask = 0;
  219773. static int NumLockMask = 0;
  219774. static bool numLock = false;
  219775. static bool capsLock = false;
  219776. static char keyStates [32];
  219777. static const int extendedKeyModifier = 0x10000000;
  219778. }
  219779. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  219780. {
  219781. int keysym;
  219782. if (keyCode & Keys::extendedKeyModifier)
  219783. {
  219784. keysym = 0xff00 | (keyCode & 0xff);
  219785. }
  219786. else
  219787. {
  219788. keysym = keyCode;
  219789. if (keysym == (XK_Tab & 0xff)
  219790. || keysym == (XK_Return & 0xff)
  219791. || keysym == (XK_Escape & 0xff)
  219792. || keysym == (XK_BackSpace & 0xff))
  219793. {
  219794. keysym |= 0xff00;
  219795. }
  219796. }
  219797. ScopedXLock xlock;
  219798. const int keycode = XKeysymToKeycode (display, keysym);
  219799. const int keybyte = keycode >> 3;
  219800. const int keybit = (1 << (keycode & 7));
  219801. return (Keys::keyStates [keybyte] & keybit) != 0;
  219802. }
  219803. #if JUCE_USE_XSHM
  219804. namespace XSHMHelpers
  219805. {
  219806. static int trappedErrorCode = 0;
  219807. extern "C" int errorTrapHandler (Display*, XErrorEvent* err)
  219808. {
  219809. trappedErrorCode = err->error_code;
  219810. return 0;
  219811. }
  219812. static bool isShmAvailable() throw()
  219813. {
  219814. static bool isChecked = false;
  219815. static bool isAvailable = false;
  219816. if (! isChecked)
  219817. {
  219818. isChecked = true;
  219819. int major, minor;
  219820. Bool pixmaps;
  219821. ScopedXLock xlock;
  219822. if (XShmQueryVersion (display, &major, &minor, &pixmaps))
  219823. {
  219824. trappedErrorCode = 0;
  219825. XErrorHandler oldHandler = XSetErrorHandler (errorTrapHandler);
  219826. XShmSegmentInfo segmentInfo;
  219827. zerostruct (segmentInfo);
  219828. XImage* xImage = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  219829. 24, ZPixmap, 0, &segmentInfo, 50, 50);
  219830. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  219831. xImage->bytes_per_line * xImage->height,
  219832. IPC_CREAT | 0777)) >= 0)
  219833. {
  219834. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  219835. if (segmentInfo.shmaddr != (void*) -1)
  219836. {
  219837. segmentInfo.readOnly = False;
  219838. xImage->data = segmentInfo.shmaddr;
  219839. XSync (display, False);
  219840. if (XShmAttach (display, &segmentInfo) != 0)
  219841. {
  219842. XSync (display, False);
  219843. XShmDetach (display, &segmentInfo);
  219844. isAvailable = true;
  219845. }
  219846. }
  219847. XFlush (display);
  219848. XDestroyImage (xImage);
  219849. shmdt (segmentInfo.shmaddr);
  219850. }
  219851. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  219852. XSetErrorHandler (oldHandler);
  219853. if (trappedErrorCode != 0)
  219854. isAvailable = false;
  219855. }
  219856. }
  219857. return isAvailable;
  219858. }
  219859. }
  219860. #endif
  219861. #if JUCE_USE_XRENDER
  219862. namespace XRender
  219863. {
  219864. typedef Status (*tXRenderQueryVersion) (Display*, int*, int*);
  219865. typedef XRenderPictFormat* (*tXrenderFindStandardFormat) (Display*, int);
  219866. typedef XRenderPictFormat* (*tXRenderFindFormat) (Display*, unsigned long, XRenderPictFormat*, int);
  219867. typedef XRenderPictFormat* (*tXRenderFindVisualFormat) (Display*, Visual*);
  219868. static tXRenderQueryVersion xRenderQueryVersion = 0;
  219869. static tXrenderFindStandardFormat xRenderFindStandardFormat = 0;
  219870. static tXRenderFindFormat xRenderFindFormat = 0;
  219871. static tXRenderFindVisualFormat xRenderFindVisualFormat = 0;
  219872. static bool isAvailable()
  219873. {
  219874. static bool hasLoaded = false;
  219875. if (! hasLoaded)
  219876. {
  219877. ScopedXLock xlock;
  219878. hasLoaded = true;
  219879. void* h = dlopen ("libXrender.so", RTLD_GLOBAL | RTLD_NOW);
  219880. if (h != 0)
  219881. {
  219882. xRenderQueryVersion = (tXRenderQueryVersion) dlsym (h, "XRenderQueryVersion");
  219883. xRenderFindStandardFormat = (tXrenderFindStandardFormat) dlsym (h, "XrenderFindStandardFormat");
  219884. xRenderFindFormat = (tXRenderFindFormat) dlsym (h, "XRenderFindFormat");
  219885. xRenderFindVisualFormat = (tXRenderFindVisualFormat) dlsym (h, "XRenderFindVisualFormat");
  219886. }
  219887. if (xRenderQueryVersion != 0
  219888. && xRenderFindStandardFormat != 0
  219889. && xRenderFindFormat != 0
  219890. && xRenderFindVisualFormat != 0)
  219891. {
  219892. int major, minor;
  219893. if (xRenderQueryVersion (display, &major, &minor))
  219894. return true;
  219895. }
  219896. xRenderQueryVersion = 0;
  219897. }
  219898. return xRenderQueryVersion != 0;
  219899. }
  219900. static XRenderPictFormat* findPictureFormat()
  219901. {
  219902. ScopedXLock xlock;
  219903. XRenderPictFormat* pictFormat = 0;
  219904. if (isAvailable())
  219905. {
  219906. pictFormat = xRenderFindStandardFormat (display, PictStandardARGB32);
  219907. if (pictFormat == 0)
  219908. {
  219909. XRenderPictFormat desiredFormat;
  219910. desiredFormat.type = PictTypeDirect;
  219911. desiredFormat.depth = 32;
  219912. desiredFormat.direct.alphaMask = 0xff;
  219913. desiredFormat.direct.redMask = 0xff;
  219914. desiredFormat.direct.greenMask = 0xff;
  219915. desiredFormat.direct.blueMask = 0xff;
  219916. desiredFormat.direct.alpha = 24;
  219917. desiredFormat.direct.red = 16;
  219918. desiredFormat.direct.green = 8;
  219919. desiredFormat.direct.blue = 0;
  219920. pictFormat = xRenderFindFormat (display,
  219921. PictFormatType | PictFormatDepth
  219922. | PictFormatRedMask | PictFormatRed
  219923. | PictFormatGreenMask | PictFormatGreen
  219924. | PictFormatBlueMask | PictFormatBlue
  219925. | PictFormatAlphaMask | PictFormatAlpha,
  219926. &desiredFormat,
  219927. 0);
  219928. }
  219929. }
  219930. return pictFormat;
  219931. }
  219932. }
  219933. #endif
  219934. namespace Visuals
  219935. {
  219936. static Visual* findVisualWithDepth (const int desiredDepth) throw()
  219937. {
  219938. ScopedXLock xlock;
  219939. Visual* visual = 0;
  219940. int numVisuals = 0;
  219941. long desiredMask = VisualNoMask;
  219942. XVisualInfo desiredVisual;
  219943. desiredVisual.screen = DefaultScreen (display);
  219944. desiredVisual.depth = desiredDepth;
  219945. desiredMask = VisualScreenMask | VisualDepthMask;
  219946. if (desiredDepth == 32)
  219947. {
  219948. desiredVisual.c_class = TrueColor;
  219949. desiredVisual.red_mask = 0x00FF0000;
  219950. desiredVisual.green_mask = 0x0000FF00;
  219951. desiredVisual.blue_mask = 0x000000FF;
  219952. desiredVisual.bits_per_rgb = 8;
  219953. desiredMask |= VisualClassMask;
  219954. desiredMask |= VisualRedMaskMask;
  219955. desiredMask |= VisualGreenMaskMask;
  219956. desiredMask |= VisualBlueMaskMask;
  219957. desiredMask |= VisualBitsPerRGBMask;
  219958. }
  219959. XVisualInfo* xvinfos = XGetVisualInfo (display,
  219960. desiredMask,
  219961. &desiredVisual,
  219962. &numVisuals);
  219963. if (xvinfos != 0)
  219964. {
  219965. for (int i = 0; i < numVisuals; i++)
  219966. {
  219967. if (xvinfos[i].depth == desiredDepth)
  219968. {
  219969. visual = xvinfos[i].visual;
  219970. break;
  219971. }
  219972. }
  219973. XFree (xvinfos);
  219974. }
  219975. return visual;
  219976. }
  219977. static Visual* findVisualFormat (const int desiredDepth, int& matchedDepth) throw()
  219978. {
  219979. Visual* visual = 0;
  219980. if (desiredDepth == 32)
  219981. {
  219982. #if JUCE_USE_XSHM
  219983. if (XSHMHelpers::isShmAvailable())
  219984. {
  219985. #if JUCE_USE_XRENDER
  219986. if (XRender::isAvailable())
  219987. {
  219988. XRenderPictFormat* pictFormat = XRender::findPictureFormat();
  219989. if (pictFormat != 0)
  219990. {
  219991. int numVisuals = 0;
  219992. XVisualInfo desiredVisual;
  219993. desiredVisual.screen = DefaultScreen (display);
  219994. desiredVisual.depth = 32;
  219995. desiredVisual.bits_per_rgb = 8;
  219996. XVisualInfo* xvinfos = XGetVisualInfo (display,
  219997. VisualScreenMask | VisualDepthMask | VisualBitsPerRGBMask,
  219998. &desiredVisual, &numVisuals);
  219999. if (xvinfos != 0)
  220000. {
  220001. for (int i = 0; i < numVisuals; ++i)
  220002. {
  220003. XRenderPictFormat* pictVisualFormat = XRender::xRenderFindVisualFormat (display, xvinfos[i].visual);
  220004. if (pictVisualFormat != 0
  220005. && pictVisualFormat->type == PictTypeDirect
  220006. && pictVisualFormat->direct.alphaMask)
  220007. {
  220008. visual = xvinfos[i].visual;
  220009. matchedDepth = 32;
  220010. break;
  220011. }
  220012. }
  220013. XFree (xvinfos);
  220014. }
  220015. }
  220016. }
  220017. #endif
  220018. if (visual == 0)
  220019. {
  220020. visual = findVisualWithDepth (32);
  220021. if (visual != 0)
  220022. matchedDepth = 32;
  220023. }
  220024. }
  220025. #endif
  220026. }
  220027. if (visual == 0 && desiredDepth >= 24)
  220028. {
  220029. visual = findVisualWithDepth (24);
  220030. if (visual != 0)
  220031. matchedDepth = 24;
  220032. }
  220033. if (visual == 0 && desiredDepth >= 16)
  220034. {
  220035. visual = findVisualWithDepth (16);
  220036. if (visual != 0)
  220037. matchedDepth = 16;
  220038. }
  220039. return visual;
  220040. }
  220041. }
  220042. class XBitmapImage : public Image::SharedImage
  220043. {
  220044. public:
  220045. XBitmapImage (const Image::PixelFormat format_, const int w, const int h,
  220046. const bool clearImage, const int imageDepth_, Visual* visual)
  220047. : Image::SharedImage (format_, w, h),
  220048. imageDepth (imageDepth_),
  220049. gc (None)
  220050. {
  220051. jassert (format_ == Image::RGB || format_ == Image::ARGB);
  220052. pixelStride = (format_ == Image::RGB) ? 3 : 4;
  220053. lineStride = ((w * pixelStride + 3) & ~3);
  220054. ScopedXLock xlock;
  220055. #if JUCE_USE_XSHM
  220056. usingXShm = false;
  220057. if ((imageDepth > 16) && XSHMHelpers::isShmAvailable())
  220058. {
  220059. zerostruct (segmentInfo);
  220060. segmentInfo.shmid = -1;
  220061. segmentInfo.shmaddr = (char *) -1;
  220062. segmentInfo.readOnly = False;
  220063. xImage = XShmCreateImage (display, visual, imageDepth, ZPixmap, 0, &segmentInfo, w, h);
  220064. if (xImage != 0)
  220065. {
  220066. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  220067. xImage->bytes_per_line * xImage->height,
  220068. IPC_CREAT | 0777)) >= 0)
  220069. {
  220070. if (segmentInfo.shmid != -1)
  220071. {
  220072. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  220073. if (segmentInfo.shmaddr != (void*) -1)
  220074. {
  220075. segmentInfo.readOnly = False;
  220076. xImage->data = segmentInfo.shmaddr;
  220077. imageData = (uint8*) segmentInfo.shmaddr;
  220078. if (XShmAttach (display, &segmentInfo) != 0)
  220079. usingXShm = true;
  220080. else
  220081. jassertfalse;
  220082. }
  220083. else
  220084. {
  220085. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  220086. }
  220087. }
  220088. }
  220089. }
  220090. }
  220091. if (! usingXShm)
  220092. #endif
  220093. {
  220094. imageDataAllocated.malloc (lineStride * h);
  220095. imageData = imageDataAllocated;
  220096. if (format_ == Image::ARGB && clearImage)
  220097. zeromem (imageData, h * lineStride);
  220098. xImage = (XImage*) juce_calloc (sizeof (XImage));
  220099. xImage->width = w;
  220100. xImage->height = h;
  220101. xImage->xoffset = 0;
  220102. xImage->format = ZPixmap;
  220103. xImage->data = (char*) imageData;
  220104. xImage->byte_order = ImageByteOrder (display);
  220105. xImage->bitmap_unit = BitmapUnit (display);
  220106. xImage->bitmap_bit_order = BitmapBitOrder (display);
  220107. xImage->bitmap_pad = 32;
  220108. xImage->depth = pixelStride * 8;
  220109. xImage->bytes_per_line = lineStride;
  220110. xImage->bits_per_pixel = pixelStride * 8;
  220111. xImage->red_mask = 0x00FF0000;
  220112. xImage->green_mask = 0x0000FF00;
  220113. xImage->blue_mask = 0x000000FF;
  220114. if (imageDepth == 16)
  220115. {
  220116. const int pixelStride = 2;
  220117. const int lineStride = ((w * pixelStride + 3) & ~3);
  220118. imageData16Bit.malloc (lineStride * h);
  220119. xImage->data = imageData16Bit;
  220120. xImage->bitmap_pad = 16;
  220121. xImage->depth = pixelStride * 8;
  220122. xImage->bytes_per_line = lineStride;
  220123. xImage->bits_per_pixel = pixelStride * 8;
  220124. xImage->red_mask = visual->red_mask;
  220125. xImage->green_mask = visual->green_mask;
  220126. xImage->blue_mask = visual->blue_mask;
  220127. }
  220128. if (! XInitImage (xImage))
  220129. jassertfalse;
  220130. }
  220131. zeromem (imageData, h * lineStride);
  220132. }
  220133. ~XBitmapImage()
  220134. {
  220135. ScopedXLock xlock;
  220136. if (gc != None)
  220137. XFreeGC (display, gc);
  220138. #if JUCE_USE_XSHM
  220139. if (usingXShm)
  220140. {
  220141. XShmDetach (display, &segmentInfo);
  220142. XFlush (display);
  220143. XDestroyImage (xImage);
  220144. shmdt (segmentInfo.shmaddr);
  220145. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  220146. }
  220147. else
  220148. #endif
  220149. {
  220150. xImage->data = 0;
  220151. XDestroyImage (xImage);
  220152. }
  220153. }
  220154. Image::ImageType getType() const { return Image::NativeImage; }
  220155. LowLevelGraphicsContext* createLowLevelContext()
  220156. {
  220157. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  220158. }
  220159. SharedImage* clone()
  220160. {
  220161. jassertfalse;
  220162. return 0;
  220163. }
  220164. void blitToWindow (Window window, int dx, int dy, int dw, int dh, int sx, int sy)
  220165. {
  220166. ScopedXLock xlock;
  220167. if (gc == None)
  220168. {
  220169. XGCValues gcvalues;
  220170. gcvalues.foreground = None;
  220171. gcvalues.background = None;
  220172. gcvalues.function = GXcopy;
  220173. gcvalues.plane_mask = AllPlanes;
  220174. gcvalues.clip_mask = None;
  220175. gcvalues.graphics_exposures = False;
  220176. gc = XCreateGC (display, window,
  220177. GCBackground | GCForeground | GCFunction | GCPlaneMask | GCClipMask | GCGraphicsExposures,
  220178. &gcvalues);
  220179. }
  220180. if (imageDepth == 16)
  220181. {
  220182. const uint32 rMask = xImage->red_mask;
  220183. const uint32 rShiftL = jmax (0, getShiftNeeded (rMask));
  220184. const uint32 rShiftR = jmax (0, -getShiftNeeded (rMask));
  220185. const uint32 gMask = xImage->green_mask;
  220186. const uint32 gShiftL = jmax (0, getShiftNeeded (gMask));
  220187. const uint32 gShiftR = jmax (0, -getShiftNeeded (gMask));
  220188. const uint32 bMask = xImage->blue_mask;
  220189. const uint32 bShiftL = jmax (0, getShiftNeeded (bMask));
  220190. const uint32 bShiftR = jmax (0, -getShiftNeeded (bMask));
  220191. const Image::BitmapData srcData (Image (this), false);
  220192. for (int y = sy; y < sy + dh; ++y)
  220193. {
  220194. const uint8* p = srcData.getPixelPointer (sx, y);
  220195. for (int x = sx; x < sx + dw; ++x)
  220196. {
  220197. const PixelRGB* const pixel = (const PixelRGB*) p;
  220198. p += srcData.pixelStride;
  220199. XPutPixel (xImage, x, y,
  220200. (((((uint32) pixel->getRed()) << rShiftL) >> rShiftR) & rMask)
  220201. | (((((uint32) pixel->getGreen()) << gShiftL) >> gShiftR) & gMask)
  220202. | (((((uint32) pixel->getBlue()) << bShiftL) >> bShiftR) & bMask));
  220203. }
  220204. }
  220205. }
  220206. // blit results to screen.
  220207. #if JUCE_USE_XSHM
  220208. if (usingXShm)
  220209. XShmPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh, True);
  220210. else
  220211. #endif
  220212. XPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh);
  220213. }
  220214. juce_UseDebuggingNewOperator
  220215. private:
  220216. XImage* xImage;
  220217. const int imageDepth;
  220218. HeapBlock <uint8> imageDataAllocated;
  220219. HeapBlock <char> imageData16Bit;
  220220. GC gc;
  220221. #if JUCE_USE_XSHM
  220222. XShmSegmentInfo segmentInfo;
  220223. bool usingXShm;
  220224. #endif
  220225. static int getShiftNeeded (const uint32 mask) throw()
  220226. {
  220227. for (int i = 32; --i >= 0;)
  220228. if (((mask >> i) & 1) != 0)
  220229. return i - 7;
  220230. jassertfalse;
  220231. return 0;
  220232. }
  220233. };
  220234. class LinuxComponentPeer : public ComponentPeer
  220235. {
  220236. public:
  220237. LinuxComponentPeer (Component* const component, const int windowStyleFlags)
  220238. : ComponentPeer (component, windowStyleFlags),
  220239. windowH (0),
  220240. parentWindow (0),
  220241. wx (0),
  220242. wy (0),
  220243. ww (0),
  220244. wh (0),
  220245. fullScreen (false),
  220246. mapped (false),
  220247. visual (0),
  220248. depth (0)
  220249. {
  220250. // it's dangerous to create a window on a thread other than the message thread..
  220251. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  220252. repainter = new LinuxRepaintManager (this);
  220253. createWindow();
  220254. setTitle (component->getName());
  220255. }
  220256. ~LinuxComponentPeer()
  220257. {
  220258. // it's dangerous to delete a window on a thread other than the message thread..
  220259. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  220260. deleteIconPixmaps();
  220261. destroyWindow();
  220262. windowH = 0;
  220263. }
  220264. void* getNativeHandle() const
  220265. {
  220266. return (void*) windowH;
  220267. }
  220268. static LinuxComponentPeer* getPeerFor (Window windowHandle) throw()
  220269. {
  220270. XPointer peer = 0;
  220271. ScopedXLock xlock;
  220272. if (! XFindContext (display, (XID) windowHandle, windowHandleXContext, &peer))
  220273. {
  220274. if (peer != 0 && ! ComponentPeer::isValidPeer ((LinuxComponentPeer*) peer))
  220275. peer = 0;
  220276. }
  220277. return (LinuxComponentPeer*) peer;
  220278. }
  220279. void setVisible (bool shouldBeVisible)
  220280. {
  220281. ScopedXLock xlock;
  220282. if (shouldBeVisible)
  220283. XMapWindow (display, windowH);
  220284. else
  220285. XUnmapWindow (display, windowH);
  220286. }
  220287. void setTitle (const String& title)
  220288. {
  220289. setWindowTitle (windowH, title);
  220290. }
  220291. void setPosition (int x, int y)
  220292. {
  220293. setBounds (x, y, ww, wh, false);
  220294. }
  220295. void setSize (int w, int h)
  220296. {
  220297. setBounds (wx, wy, w, h, false);
  220298. }
  220299. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  220300. {
  220301. fullScreen = isNowFullScreen;
  220302. if (windowH != 0)
  220303. {
  220304. Component::SafePointer<Component> deletionChecker (component);
  220305. wx = x;
  220306. wy = y;
  220307. ww = jmax (1, w);
  220308. wh = jmax (1, h);
  220309. ScopedXLock xlock;
  220310. // Make sure the Window manager does what we want
  220311. XSizeHints* hints = XAllocSizeHints();
  220312. hints->flags = USSize | USPosition;
  220313. hints->width = ww;
  220314. hints->height = wh;
  220315. hints->x = wx;
  220316. hints->y = wy;
  220317. if ((getStyleFlags() & (windowHasTitleBar | windowIsResizable)) == windowHasTitleBar)
  220318. {
  220319. hints->min_width = hints->max_width = hints->width;
  220320. hints->min_height = hints->max_height = hints->height;
  220321. hints->flags |= PMinSize | PMaxSize;
  220322. }
  220323. XSetWMNormalHints (display, windowH, hints);
  220324. XFree (hints);
  220325. XMoveResizeWindow (display, windowH,
  220326. wx - windowBorder.getLeft(),
  220327. wy - windowBorder.getTop(), ww, wh);
  220328. if (deletionChecker != 0)
  220329. {
  220330. updateBorderSize();
  220331. handleMovedOrResized();
  220332. }
  220333. }
  220334. }
  220335. const Rectangle<int> getBounds() const { return Rectangle<int> (wx, wy, ww, wh); }
  220336. const Point<int> getScreenPosition() const { return Point<int> (wx, wy); }
  220337. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition)
  220338. {
  220339. return relativePosition + getScreenPosition();
  220340. }
  220341. const Point<int> globalPositionToRelative (const Point<int>& screenPosition)
  220342. {
  220343. return screenPosition - getScreenPosition();
  220344. }
  220345. void setAlpha (float newAlpha)
  220346. {
  220347. //xxx todo!
  220348. }
  220349. void setMinimised (bool shouldBeMinimised)
  220350. {
  220351. if (shouldBeMinimised)
  220352. {
  220353. Window root = RootWindow (display, DefaultScreen (display));
  220354. XClientMessageEvent clientMsg;
  220355. clientMsg.display = display;
  220356. clientMsg.window = windowH;
  220357. clientMsg.type = ClientMessage;
  220358. clientMsg.format = 32;
  220359. clientMsg.message_type = Atoms::ChangeState;
  220360. clientMsg.data.l[0] = IconicState;
  220361. ScopedXLock xlock;
  220362. XSendEvent (display, root, false, SubstructureRedirectMask | SubstructureNotifyMask, (XEvent*) &clientMsg);
  220363. }
  220364. else
  220365. {
  220366. setVisible (true);
  220367. }
  220368. }
  220369. bool isMinimised() const
  220370. {
  220371. bool minimised = false;
  220372. unsigned char* stateProp;
  220373. unsigned long nitems, bytesLeft;
  220374. Atom actualType;
  220375. int actualFormat;
  220376. ScopedXLock xlock;
  220377. if (XGetWindowProperty (display, windowH, Atoms::State, 0, 64, False,
  220378. Atoms::State, &actualType, &actualFormat, &nitems, &bytesLeft,
  220379. &stateProp) == Success
  220380. && actualType == Atoms::State
  220381. && actualFormat == 32
  220382. && nitems > 0)
  220383. {
  220384. if (((unsigned long*) stateProp)[0] == IconicState)
  220385. minimised = true;
  220386. XFree (stateProp);
  220387. }
  220388. return minimised;
  220389. }
  220390. void setFullScreen (const bool shouldBeFullScreen)
  220391. {
  220392. Rectangle<int> r (lastNonFullscreenBounds); // (get a copy of this before de-minimising)
  220393. setMinimised (false);
  220394. if (fullScreen != shouldBeFullScreen)
  220395. {
  220396. if (shouldBeFullScreen)
  220397. r = Desktop::getInstance().getMainMonitorArea();
  220398. if (! r.isEmpty())
  220399. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  220400. getComponent()->repaint();
  220401. }
  220402. }
  220403. bool isFullScreen() const
  220404. {
  220405. return fullScreen;
  220406. }
  220407. bool isChildWindowOf (Window possibleParent) const
  220408. {
  220409. Window* windowList = 0;
  220410. uint32 windowListSize = 0;
  220411. Window parent, root;
  220412. ScopedXLock xlock;
  220413. if (XQueryTree (display, windowH, &root, &parent, &windowList, &windowListSize) != 0)
  220414. {
  220415. if (windowList != 0)
  220416. XFree (windowList);
  220417. return parent == possibleParent;
  220418. }
  220419. return false;
  220420. }
  220421. bool isFrontWindow() const
  220422. {
  220423. Window* windowList = 0;
  220424. uint32 windowListSize = 0;
  220425. bool result = false;
  220426. ScopedXLock xlock;
  220427. Window parent, root = RootWindow (display, DefaultScreen (display));
  220428. if (XQueryTree (display, root, &root, &parent, &windowList, &windowListSize) != 0)
  220429. {
  220430. for (int i = windowListSize; --i >= 0;)
  220431. {
  220432. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (windowList[i]);
  220433. if (peer != 0)
  220434. {
  220435. result = (peer == this);
  220436. break;
  220437. }
  220438. }
  220439. }
  220440. if (windowList != 0)
  220441. XFree (windowList);
  220442. return result;
  220443. }
  220444. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  220445. {
  220446. int x = position.getX();
  220447. int y = position.getY();
  220448. if (((unsigned int) x) >= (unsigned int) ww
  220449. || ((unsigned int) y) >= (unsigned int) wh)
  220450. return false;
  220451. bool inFront = false;
  220452. for (int i = 0; i < Desktop::getInstance().getNumComponents(); ++i)
  220453. {
  220454. Component* const c = Desktop::getInstance().getComponent (i);
  220455. if (inFront)
  220456. {
  220457. if (c->contains (x + wx - c->getScreenX(),
  220458. y + wy - c->getScreenY()))
  220459. {
  220460. return false;
  220461. }
  220462. }
  220463. else if (c == getComponent())
  220464. {
  220465. inFront = true;
  220466. }
  220467. }
  220468. if (trueIfInAChildWindow)
  220469. return true;
  220470. ::Window root, child;
  220471. unsigned int bw, depth;
  220472. int wx, wy, w, h;
  220473. ScopedXLock xlock;
  220474. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  220475. &wx, &wy, (unsigned int*) &w, (unsigned int*) &h,
  220476. &bw, &depth))
  220477. {
  220478. return false;
  220479. }
  220480. if (! XTranslateCoordinates (display, windowH, windowH, x, y, &wx, &wy, &child))
  220481. return false;
  220482. return child == None;
  220483. }
  220484. const BorderSize getFrameSize() const
  220485. {
  220486. return BorderSize();
  220487. }
  220488. bool setAlwaysOnTop (bool alwaysOnTop)
  220489. {
  220490. return false;
  220491. }
  220492. void toFront (bool makeActive)
  220493. {
  220494. if (makeActive)
  220495. {
  220496. setVisible (true);
  220497. grabFocus();
  220498. }
  220499. XEvent ev;
  220500. ev.xclient.type = ClientMessage;
  220501. ev.xclient.serial = 0;
  220502. ev.xclient.send_event = True;
  220503. ev.xclient.message_type = Atoms::ActiveWin;
  220504. ev.xclient.window = windowH;
  220505. ev.xclient.format = 32;
  220506. ev.xclient.data.l[0] = 2;
  220507. ev.xclient.data.l[1] = CurrentTime;
  220508. ev.xclient.data.l[2] = 0;
  220509. ev.xclient.data.l[3] = 0;
  220510. ev.xclient.data.l[4] = 0;
  220511. {
  220512. ScopedXLock xlock;
  220513. XSendEvent (display, RootWindow (display, DefaultScreen (display)),
  220514. False, SubstructureRedirectMask | SubstructureNotifyMask, &ev);
  220515. XWindowAttributes attr;
  220516. XGetWindowAttributes (display, windowH, &attr);
  220517. if (component->isAlwaysOnTop())
  220518. XRaiseWindow (display, windowH);
  220519. XSync (display, False);
  220520. }
  220521. handleBroughtToFront();
  220522. }
  220523. void toBehind (ComponentPeer* other)
  220524. {
  220525. LinuxComponentPeer* const otherPeer = dynamic_cast <LinuxComponentPeer*> (other);
  220526. jassert (otherPeer != 0); // wrong type of window?
  220527. if (otherPeer != 0)
  220528. {
  220529. setMinimised (false);
  220530. Window newStack[] = { otherPeer->windowH, windowH };
  220531. ScopedXLock xlock;
  220532. XRestackWindows (display, newStack, 2);
  220533. }
  220534. }
  220535. bool isFocused() const
  220536. {
  220537. int revert = 0;
  220538. Window focusedWindow = 0;
  220539. ScopedXLock xlock;
  220540. XGetInputFocus (display, &focusedWindow, &revert);
  220541. return focusedWindow == windowH;
  220542. }
  220543. void grabFocus()
  220544. {
  220545. XWindowAttributes atts;
  220546. ScopedXLock xlock;
  220547. if (windowH != 0
  220548. && XGetWindowAttributes (display, windowH, &atts)
  220549. && atts.map_state == IsViewable
  220550. && ! isFocused())
  220551. {
  220552. XSetInputFocus (display, windowH, RevertToParent, CurrentTime);
  220553. isActiveApplication = true;
  220554. }
  220555. }
  220556. void textInputRequired (const Point<int>&)
  220557. {
  220558. }
  220559. void repaint (const Rectangle<int>& area)
  220560. {
  220561. repainter->repaint (area.getIntersection (getComponent()->getLocalBounds()));
  220562. }
  220563. void performAnyPendingRepaintsNow()
  220564. {
  220565. repainter->performAnyPendingRepaintsNow();
  220566. }
  220567. static Pixmap juce_createColourPixmapFromImage (Display* display, const Image& image)
  220568. {
  220569. ScopedXLock xlock;
  220570. const int width = image.getWidth();
  220571. const int height = image.getHeight();
  220572. HeapBlock <uint32> colour (width * height);
  220573. int index = 0;
  220574. for (int y = 0; y < height; ++y)
  220575. for (int x = 0; x < width; ++x)
  220576. colour[index++] = image.getPixelAt (x, y).getARGB();
  220577. XImage* ximage = XCreateImage (display, CopyFromParent, 24, ZPixmap,
  220578. 0, reinterpret_cast<char*> (colour.getData()),
  220579. width, height, 32, 0);
  220580. Pixmap pixmap = XCreatePixmap (display, DefaultRootWindow (display),
  220581. width, height, 24);
  220582. GC gc = XCreateGC (display, pixmap, 0, 0);
  220583. XPutImage (display, pixmap, gc, ximage, 0, 0, 0, 0, width, height);
  220584. XFreeGC (display, gc);
  220585. return pixmap;
  220586. }
  220587. static Pixmap juce_createMaskPixmapFromImage (Display* display, const Image& image)
  220588. {
  220589. ScopedXLock xlock;
  220590. const int width = image.getWidth();
  220591. const int height = image.getHeight();
  220592. const int stride = (width + 7) >> 3;
  220593. HeapBlock <char> mask;
  220594. mask.calloc (stride * height);
  220595. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  220596. for (int y = 0; y < height; ++y)
  220597. {
  220598. for (int x = 0; x < width; ++x)
  220599. {
  220600. const char bit = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  220601. const int offset = y * stride + (x >> 3);
  220602. if (image.getPixelAt (x, y).getAlpha() >= 128)
  220603. mask[offset] |= bit;
  220604. }
  220605. }
  220606. return XCreatePixmapFromBitmapData (display, DefaultRootWindow (display),
  220607. mask.getData(), width, height, 1, 0, 1);
  220608. }
  220609. void setIcon (const Image& newIcon)
  220610. {
  220611. const int dataSize = newIcon.getWidth() * newIcon.getHeight() + 2;
  220612. HeapBlock <unsigned long> data (dataSize);
  220613. int index = 0;
  220614. data[index++] = newIcon.getWidth();
  220615. data[index++] = newIcon.getHeight();
  220616. for (int y = 0; y < newIcon.getHeight(); ++y)
  220617. for (int x = 0; x < newIcon.getWidth(); ++x)
  220618. data[index++] = newIcon.getPixelAt (x, y).getARGB();
  220619. ScopedXLock xlock;
  220620. XChangeProperty (display, windowH,
  220621. XInternAtom (display, "_NET_WM_ICON", False),
  220622. XA_CARDINAL, 32, PropModeReplace,
  220623. reinterpret_cast<unsigned char*> (data.getData()), dataSize);
  220624. deleteIconPixmaps();
  220625. XWMHints* wmHints = XGetWMHints (display, windowH);
  220626. if (wmHints == 0)
  220627. wmHints = XAllocWMHints();
  220628. wmHints->flags |= IconPixmapHint | IconMaskHint;
  220629. wmHints->icon_pixmap = juce_createColourPixmapFromImage (display, newIcon);
  220630. wmHints->icon_mask = juce_createMaskPixmapFromImage (display, newIcon);
  220631. XSetWMHints (display, windowH, wmHints);
  220632. XFree (wmHints);
  220633. XSync (display, False);
  220634. }
  220635. void deleteIconPixmaps()
  220636. {
  220637. ScopedXLock xlock;
  220638. XWMHints* wmHints = XGetWMHints (display, windowH);
  220639. if (wmHints != 0)
  220640. {
  220641. if ((wmHints->flags & IconPixmapHint) != 0)
  220642. {
  220643. wmHints->flags &= ~IconPixmapHint;
  220644. XFreePixmap (display, wmHints->icon_pixmap);
  220645. }
  220646. if ((wmHints->flags & IconMaskHint) != 0)
  220647. {
  220648. wmHints->flags &= ~IconMaskHint;
  220649. XFreePixmap (display, wmHints->icon_mask);
  220650. }
  220651. XSetWMHints (display, windowH, wmHints);
  220652. XFree (wmHints);
  220653. }
  220654. }
  220655. void handleWindowMessage (XEvent* event)
  220656. {
  220657. switch (event->xany.type)
  220658. {
  220659. case 2: // 'KeyPress'
  220660. {
  220661. ScopedXLock xlock;
  220662. XKeyEvent* const keyEvent = (XKeyEvent*) &event->xkey;
  220663. updateKeyStates (keyEvent->keycode, true);
  220664. char utf8 [64];
  220665. zeromem (utf8, sizeof (utf8));
  220666. KeySym sym;
  220667. {
  220668. const char* oldLocale = ::setlocale (LC_ALL, 0);
  220669. ::setlocale (LC_ALL, "");
  220670. XLookupString (keyEvent, utf8, sizeof (utf8), &sym, 0);
  220671. ::setlocale (LC_ALL, oldLocale);
  220672. }
  220673. const juce_wchar unicodeChar = String::fromUTF8 (utf8, sizeof (utf8) - 1) [0];
  220674. int keyCode = (int) unicodeChar;
  220675. if (keyCode < 0x20)
  220676. keyCode = XKeycodeToKeysym (display, keyEvent->keycode, currentModifiers.isShiftDown() ? 1 : 0);
  220677. const ModifierKeys oldMods (currentModifiers);
  220678. bool keyPressed = false;
  220679. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, true);
  220680. if ((sym & 0xff00) == 0xff00)
  220681. {
  220682. // Translate keypad
  220683. if (sym == XK_KP_Divide)
  220684. keyCode = XK_slash;
  220685. else if (sym == XK_KP_Multiply)
  220686. keyCode = XK_asterisk;
  220687. else if (sym == XK_KP_Subtract)
  220688. keyCode = XK_hyphen;
  220689. else if (sym == XK_KP_Add)
  220690. keyCode = XK_plus;
  220691. else if (sym == XK_KP_Enter)
  220692. keyCode = XK_Return;
  220693. else if (sym == XK_KP_Decimal)
  220694. keyCode = Keys::numLock ? XK_period : XK_Delete;
  220695. else if (sym == XK_KP_0)
  220696. keyCode = Keys::numLock ? XK_0 : XK_Insert;
  220697. else if (sym == XK_KP_1)
  220698. keyCode = Keys::numLock ? XK_1 : XK_End;
  220699. else if (sym == XK_KP_2)
  220700. keyCode = Keys::numLock ? XK_2 : XK_Down;
  220701. else if (sym == XK_KP_3)
  220702. keyCode = Keys::numLock ? XK_3 : XK_Page_Down;
  220703. else if (sym == XK_KP_4)
  220704. keyCode = Keys::numLock ? XK_4 : XK_Left;
  220705. else if (sym == XK_KP_5)
  220706. keyCode = XK_5;
  220707. else if (sym == XK_KP_6)
  220708. keyCode = Keys::numLock ? XK_6 : XK_Right;
  220709. else if (sym == XK_KP_7)
  220710. keyCode = Keys::numLock ? XK_7 : XK_Home;
  220711. else if (sym == XK_KP_8)
  220712. keyCode = Keys::numLock ? XK_8 : XK_Up;
  220713. else if (sym == XK_KP_9)
  220714. keyCode = Keys::numLock ? XK_9 : XK_Page_Up;
  220715. switch (sym)
  220716. {
  220717. case XK_Left:
  220718. case XK_Right:
  220719. case XK_Up:
  220720. case XK_Down:
  220721. case XK_Page_Up:
  220722. case XK_Page_Down:
  220723. case XK_End:
  220724. case XK_Home:
  220725. case XK_Delete:
  220726. case XK_Insert:
  220727. keyPressed = true;
  220728. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  220729. break;
  220730. case XK_Tab:
  220731. case XK_Return:
  220732. case XK_Escape:
  220733. case XK_BackSpace:
  220734. keyPressed = true;
  220735. keyCode &= 0xff;
  220736. break;
  220737. default:
  220738. {
  220739. if (sym >= XK_F1 && sym <= XK_F16)
  220740. {
  220741. keyPressed = true;
  220742. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  220743. }
  220744. break;
  220745. }
  220746. }
  220747. }
  220748. if (utf8[0] != 0 || ((sym & 0xff00) == 0 && sym >= 8))
  220749. keyPressed = true;
  220750. if (oldMods != currentModifiers)
  220751. handleModifierKeysChange();
  220752. if (keyDownChange)
  220753. handleKeyUpOrDown (true);
  220754. if (keyPressed)
  220755. handleKeyPress (keyCode, unicodeChar);
  220756. break;
  220757. }
  220758. case KeyRelease:
  220759. {
  220760. const XKeyEvent* const keyEvent = (const XKeyEvent*) &event->xkey;
  220761. updateKeyStates (keyEvent->keycode, false);
  220762. KeySym sym;
  220763. {
  220764. ScopedXLock xlock;
  220765. sym = XKeycodeToKeysym (display, keyEvent->keycode, 0);
  220766. }
  220767. const ModifierKeys oldMods (currentModifiers);
  220768. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, false);
  220769. if (oldMods != currentModifiers)
  220770. handleModifierKeysChange();
  220771. if (keyDownChange)
  220772. handleKeyUpOrDown (false);
  220773. break;
  220774. }
  220775. case ButtonPress:
  220776. {
  220777. const XButtonPressedEvent* const buttonPressEvent = (const XButtonPressedEvent*) &event->xbutton;
  220778. updateKeyModifiers (buttonPressEvent->state);
  220779. bool buttonMsg = false;
  220780. const int map = pointerMap [buttonPressEvent->button - Button1];
  220781. if (map == Keys::WheelUp || map == Keys::WheelDown)
  220782. {
  220783. handleMouseWheel (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y),
  220784. getEventTime (buttonPressEvent->time), 0, map == Keys::WheelDown ? -84.0f : 84.0f);
  220785. }
  220786. if (map == Keys::LeftButton)
  220787. {
  220788. currentModifiers = currentModifiers.withFlags (ModifierKeys::leftButtonModifier);
  220789. buttonMsg = true;
  220790. }
  220791. else if (map == Keys::RightButton)
  220792. {
  220793. currentModifiers = currentModifiers.withFlags (ModifierKeys::rightButtonModifier);
  220794. buttonMsg = true;
  220795. }
  220796. else if (map == Keys::MiddleButton)
  220797. {
  220798. currentModifiers = currentModifiers.withFlags (ModifierKeys::middleButtonModifier);
  220799. buttonMsg = true;
  220800. }
  220801. if (buttonMsg)
  220802. {
  220803. toFront (true);
  220804. handleMouseEvent (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y), currentModifiers,
  220805. getEventTime (buttonPressEvent->time));
  220806. }
  220807. clearLastMousePos();
  220808. break;
  220809. }
  220810. case ButtonRelease:
  220811. {
  220812. const XButtonReleasedEvent* const buttonRelEvent = (const XButtonReleasedEvent*) &event->xbutton;
  220813. updateKeyModifiers (buttonRelEvent->state);
  220814. const int map = pointerMap [buttonRelEvent->button - Button1];
  220815. if (map == Keys::LeftButton)
  220816. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::leftButtonModifier);
  220817. else if (map == Keys::RightButton)
  220818. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::rightButtonModifier);
  220819. else if (map == Keys::MiddleButton)
  220820. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::middleButtonModifier);
  220821. handleMouseEvent (0, Point<int> (buttonRelEvent->x, buttonRelEvent->y), currentModifiers,
  220822. getEventTime (buttonRelEvent->time));
  220823. clearLastMousePos();
  220824. break;
  220825. }
  220826. case MotionNotify:
  220827. {
  220828. const XPointerMovedEvent* const movedEvent = (const XPointerMovedEvent*) &event->xmotion;
  220829. updateKeyModifiers (movedEvent->state);
  220830. const Point<int> mousePos (Desktop::getMousePosition());
  220831. if (lastMousePos != mousePos)
  220832. {
  220833. lastMousePos = mousePos;
  220834. if (parentWindow != 0 && (styleFlags & windowHasTitleBar) == 0)
  220835. {
  220836. Window wRoot = 0, wParent = 0;
  220837. {
  220838. ScopedXLock xlock;
  220839. unsigned int numChildren;
  220840. Window* wChild = 0;
  220841. XQueryTree (display, windowH, &wRoot, &wParent, &wChild, &numChildren);
  220842. }
  220843. if (wParent != 0
  220844. && wParent != windowH
  220845. && wParent != wRoot)
  220846. {
  220847. parentWindow = wParent;
  220848. updateBounds();
  220849. }
  220850. else
  220851. {
  220852. parentWindow = 0;
  220853. }
  220854. }
  220855. handleMouseEvent (0, mousePos - getScreenPosition(), currentModifiers, getEventTime (movedEvent->time));
  220856. }
  220857. break;
  220858. }
  220859. case EnterNotify:
  220860. {
  220861. clearLastMousePos();
  220862. const XEnterWindowEvent* const enterEvent = (const XEnterWindowEvent*) &event->xcrossing;
  220863. if (! currentModifiers.isAnyMouseButtonDown())
  220864. {
  220865. updateKeyModifiers (enterEvent->state);
  220866. handleMouseEvent (0, Point<int> (enterEvent->x, enterEvent->y), currentModifiers, getEventTime (enterEvent->time));
  220867. }
  220868. break;
  220869. }
  220870. case LeaveNotify:
  220871. {
  220872. const XLeaveWindowEvent* const leaveEvent = (const XLeaveWindowEvent*) &event->xcrossing;
  220873. // Suppress the normal leave if we've got a pointer grab, or if
  220874. // it's a bogus one caused by clicking a mouse button when running
  220875. // in a Window manager
  220876. if (((! currentModifiers.isAnyMouseButtonDown()) && leaveEvent->mode == NotifyNormal)
  220877. || leaveEvent->mode == NotifyUngrab)
  220878. {
  220879. updateKeyModifiers (leaveEvent->state);
  220880. handleMouseEvent (0, Point<int> (leaveEvent->x, leaveEvent->y), currentModifiers, getEventTime (leaveEvent->time));
  220881. }
  220882. break;
  220883. }
  220884. case FocusIn:
  220885. {
  220886. isActiveApplication = true;
  220887. if (isFocused())
  220888. handleFocusGain();
  220889. break;
  220890. }
  220891. case FocusOut:
  220892. {
  220893. isActiveApplication = false;
  220894. if (! isFocused())
  220895. handleFocusLoss();
  220896. break;
  220897. }
  220898. case Expose:
  220899. {
  220900. // Batch together all pending expose events
  220901. XExposeEvent* exposeEvent = (XExposeEvent*) &event->xexpose;
  220902. XEvent nextEvent;
  220903. ScopedXLock xlock;
  220904. if (exposeEvent->window != windowH)
  220905. {
  220906. Window child;
  220907. XTranslateCoordinates (display, exposeEvent->window, windowH,
  220908. exposeEvent->x, exposeEvent->y, &exposeEvent->x, &exposeEvent->y,
  220909. &child);
  220910. }
  220911. repaint (Rectangle<int> (exposeEvent->x, exposeEvent->y,
  220912. exposeEvent->width, exposeEvent->height));
  220913. while (XEventsQueued (display, QueuedAfterFlush) > 0)
  220914. {
  220915. XPeekEvent (display, (XEvent*) &nextEvent);
  220916. if (nextEvent.type != Expose || nextEvent.xany.window != event->xany.window)
  220917. break;
  220918. XNextEvent (display, (XEvent*) &nextEvent);
  220919. XExposeEvent* nextExposeEvent = (XExposeEvent*) &nextEvent.xexpose;
  220920. repaint (Rectangle<int> (nextExposeEvent->x, nextExposeEvent->y,
  220921. nextExposeEvent->width, nextExposeEvent->height));
  220922. }
  220923. break;
  220924. }
  220925. case CirculateNotify:
  220926. case CreateNotify:
  220927. case DestroyNotify:
  220928. // Think we can ignore these
  220929. break;
  220930. case ConfigureNotify:
  220931. {
  220932. updateBounds();
  220933. updateBorderSize();
  220934. handleMovedOrResized();
  220935. // if the native title bar is dragged, need to tell any active menus, etc.
  220936. if ((styleFlags & windowHasTitleBar) != 0
  220937. && component->isCurrentlyBlockedByAnotherModalComponent())
  220938. {
  220939. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  220940. if (currentModalComp != 0)
  220941. currentModalComp->inputAttemptWhenModal();
  220942. }
  220943. XConfigureEvent* const confEvent = (XConfigureEvent*) &event->xconfigure;
  220944. if (confEvent->window == windowH
  220945. && confEvent->above != 0
  220946. && isFrontWindow())
  220947. {
  220948. handleBroughtToFront();
  220949. }
  220950. break;
  220951. }
  220952. case ReparentNotify:
  220953. {
  220954. parentWindow = 0;
  220955. Window wRoot = 0;
  220956. Window* wChild = 0;
  220957. unsigned int numChildren;
  220958. {
  220959. ScopedXLock xlock;
  220960. XQueryTree (display, windowH, &wRoot, &parentWindow, &wChild, &numChildren);
  220961. }
  220962. if (parentWindow == windowH || parentWindow == wRoot)
  220963. parentWindow = 0;
  220964. updateBounds();
  220965. updateBorderSize();
  220966. handleMovedOrResized();
  220967. break;
  220968. }
  220969. case GravityNotify:
  220970. {
  220971. updateBounds();
  220972. updateBorderSize();
  220973. handleMovedOrResized();
  220974. break;
  220975. }
  220976. case MapNotify:
  220977. mapped = true;
  220978. handleBroughtToFront();
  220979. break;
  220980. case UnmapNotify:
  220981. mapped = false;
  220982. break;
  220983. case MappingNotify:
  220984. {
  220985. XMappingEvent* mappingEvent = (XMappingEvent*) &event->xmapping;
  220986. if (mappingEvent->request != MappingPointer)
  220987. {
  220988. // Deal with modifier/keyboard mapping
  220989. ScopedXLock xlock;
  220990. XRefreshKeyboardMapping (mappingEvent);
  220991. updateModifierMappings();
  220992. }
  220993. break;
  220994. }
  220995. case ClientMessage:
  220996. {
  220997. const XClientMessageEvent* const clientMsg = (const XClientMessageEvent*) &event->xclient;
  220998. if (clientMsg->message_type == Atoms::Protocols && clientMsg->format == 32)
  220999. {
  221000. const Atom atom = (Atom) clientMsg->data.l[0];
  221001. if (atom == Atoms::ProtocolList [Atoms::PING])
  221002. {
  221003. Window root = RootWindow (display, DefaultScreen (display));
  221004. event->xclient.window = root;
  221005. XSendEvent (display, root, False, NoEventMask, event);
  221006. XFlush (display);
  221007. }
  221008. else if (atom == Atoms::ProtocolList [Atoms::TAKE_FOCUS])
  221009. {
  221010. XWindowAttributes atts;
  221011. ScopedXLock xlock;
  221012. if (clientMsg->window != 0
  221013. && XGetWindowAttributes (display, clientMsg->window, &atts))
  221014. {
  221015. if (atts.map_state == IsViewable)
  221016. XSetInputFocus (display, clientMsg->window, RevertToParent, clientMsg->data.l[1]);
  221017. }
  221018. }
  221019. else if (atom == Atoms::ProtocolList [Atoms::DELETE_WINDOW])
  221020. {
  221021. handleUserClosingWindow();
  221022. }
  221023. }
  221024. else if (clientMsg->message_type == Atoms::XdndEnter)
  221025. {
  221026. handleDragAndDropEnter (clientMsg);
  221027. }
  221028. else if (clientMsg->message_type == Atoms::XdndLeave)
  221029. {
  221030. resetDragAndDrop();
  221031. }
  221032. else if (clientMsg->message_type == Atoms::XdndPosition)
  221033. {
  221034. handleDragAndDropPosition (clientMsg);
  221035. }
  221036. else if (clientMsg->message_type == Atoms::XdndDrop)
  221037. {
  221038. handleDragAndDropDrop (clientMsg);
  221039. }
  221040. else if (clientMsg->message_type == Atoms::XdndStatus)
  221041. {
  221042. handleDragAndDropStatus (clientMsg);
  221043. }
  221044. else if (clientMsg->message_type == Atoms::XdndFinished)
  221045. {
  221046. resetDragAndDrop();
  221047. }
  221048. break;
  221049. }
  221050. case SelectionNotify:
  221051. handleDragAndDropSelection (event);
  221052. break;
  221053. case SelectionClear:
  221054. case SelectionRequest:
  221055. break;
  221056. default:
  221057. #if JUCE_USE_XSHM
  221058. {
  221059. ScopedXLock xlock;
  221060. if (event->xany.type == XShmGetEventBase (display))
  221061. repainter->notifyPaintCompleted();
  221062. }
  221063. #endif
  221064. break;
  221065. }
  221066. }
  221067. void showMouseCursor (Cursor cursor) throw()
  221068. {
  221069. ScopedXLock xlock;
  221070. XDefineCursor (display, windowH, cursor);
  221071. }
  221072. void setTaskBarIcon (const Image& image)
  221073. {
  221074. ScopedXLock xlock;
  221075. taskbarImage = image;
  221076. Screen* const screen = XDefaultScreenOfDisplay (display);
  221077. const int screenNumber = XScreenNumberOfScreen (screen);
  221078. String screenAtom ("_NET_SYSTEM_TRAY_S");
  221079. screenAtom << screenNumber;
  221080. Atom selectionAtom = XInternAtom (display, screenAtom.toUTF8(), false);
  221081. XGrabServer (display);
  221082. Window managerWin = XGetSelectionOwner (display, selectionAtom);
  221083. if (managerWin != None)
  221084. XSelectInput (display, managerWin, StructureNotifyMask);
  221085. XUngrabServer (display);
  221086. XFlush (display);
  221087. if (managerWin != None)
  221088. {
  221089. XEvent ev;
  221090. zerostruct (ev);
  221091. ev.xclient.type = ClientMessage;
  221092. ev.xclient.window = managerWin;
  221093. ev.xclient.message_type = XInternAtom (display, "_NET_SYSTEM_TRAY_OPCODE", False);
  221094. ev.xclient.format = 32;
  221095. ev.xclient.data.l[0] = CurrentTime;
  221096. ev.xclient.data.l[1] = 0 /*SYSTEM_TRAY_REQUEST_DOCK*/;
  221097. ev.xclient.data.l[2] = windowH;
  221098. ev.xclient.data.l[3] = 0;
  221099. ev.xclient.data.l[4] = 0;
  221100. XSendEvent (display, managerWin, False, NoEventMask, &ev);
  221101. XSync (display, False);
  221102. }
  221103. // For older KDE's ...
  221104. long atomData = 1;
  221105. Atom trayAtom = XInternAtom (display, "KWM_DOCKWINDOW", false);
  221106. XChangeProperty (display, windowH, trayAtom, trayAtom, 32, PropModeReplace, (unsigned char*) &atomData, 1);
  221107. // For more recent KDE's...
  221108. trayAtom = XInternAtom (display, "_KDE_NET_WM_SYSTEM_TRAY_WINDOW_FOR", false);
  221109. XChangeProperty (display, windowH, trayAtom, XA_WINDOW, 32, PropModeReplace, (unsigned char*) &windowH, 1);
  221110. // a minimum size must be specified for GNOME and Xfce, otherwise the icon is displayed with a width of 1
  221111. XSizeHints* hints = XAllocSizeHints();
  221112. hints->flags = PMinSize;
  221113. hints->min_width = 22;
  221114. hints->min_height = 22;
  221115. XSetWMNormalHints (display, windowH, hints);
  221116. XFree (hints);
  221117. }
  221118. const Image& getTaskbarIcon() const throw() { return taskbarImage; }
  221119. juce_UseDebuggingNewOperator
  221120. bool dontRepaint;
  221121. static ModifierKeys currentModifiers;
  221122. static bool isActiveApplication;
  221123. private:
  221124. class LinuxRepaintManager : public Timer
  221125. {
  221126. public:
  221127. LinuxRepaintManager (LinuxComponentPeer* const peer_)
  221128. : peer (peer_),
  221129. lastTimeImageUsed (0)
  221130. {
  221131. #if JUCE_USE_XSHM
  221132. shmCompletedDrawing = true;
  221133. useARGBImagesForRendering = XSHMHelpers::isShmAvailable();
  221134. if (useARGBImagesForRendering)
  221135. {
  221136. ScopedXLock xlock;
  221137. XShmSegmentInfo segmentinfo;
  221138. XImage* const testImage
  221139. = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  221140. 24, ZPixmap, 0, &segmentinfo, 64, 64);
  221141. useARGBImagesForRendering = (testImage->bits_per_pixel == 32);
  221142. XDestroyImage (testImage);
  221143. }
  221144. #endif
  221145. }
  221146. ~LinuxRepaintManager()
  221147. {
  221148. }
  221149. void timerCallback()
  221150. {
  221151. #if JUCE_USE_XSHM
  221152. if (! shmCompletedDrawing)
  221153. return;
  221154. #endif
  221155. if (! regionsNeedingRepaint.isEmpty())
  221156. {
  221157. stopTimer();
  221158. performAnyPendingRepaintsNow();
  221159. }
  221160. else if (Time::getApproximateMillisecondCounter() > lastTimeImageUsed + 3000)
  221161. {
  221162. stopTimer();
  221163. image = Image::null;
  221164. }
  221165. }
  221166. void repaint (const Rectangle<int>& area)
  221167. {
  221168. if (! isTimerRunning())
  221169. startTimer (repaintTimerPeriod);
  221170. regionsNeedingRepaint.add (area);
  221171. }
  221172. void performAnyPendingRepaintsNow()
  221173. {
  221174. #if JUCE_USE_XSHM
  221175. if (! shmCompletedDrawing)
  221176. {
  221177. startTimer (repaintTimerPeriod);
  221178. return;
  221179. }
  221180. #endif
  221181. peer->clearMaskedRegion();
  221182. RectangleList originalRepaintRegion (regionsNeedingRepaint);
  221183. regionsNeedingRepaint.clear();
  221184. const Rectangle<int> totalArea (originalRepaintRegion.getBounds());
  221185. if (! totalArea.isEmpty())
  221186. {
  221187. if (image.isNull() || image.getWidth() < totalArea.getWidth()
  221188. || image.getHeight() < totalArea.getHeight())
  221189. {
  221190. #if JUCE_USE_XSHM
  221191. image = Image (new XBitmapImage (useARGBImagesForRendering ? Image::ARGB
  221192. : Image::RGB,
  221193. #else
  221194. image = Image (new XBitmapImage (Image::RGB,
  221195. #endif
  221196. (totalArea.getWidth() + 31) & ~31,
  221197. (totalArea.getHeight() + 31) & ~31,
  221198. false, peer->depth, peer->visual));
  221199. }
  221200. startTimer (repaintTimerPeriod);
  221201. RectangleList adjustedList (originalRepaintRegion);
  221202. adjustedList.offsetAll (-totalArea.getX(), -totalArea.getY());
  221203. LowLevelGraphicsSoftwareRenderer context (image, -totalArea.getX(), -totalArea.getY(), adjustedList);
  221204. if (peer->depth == 32)
  221205. {
  221206. RectangleList::Iterator i (originalRepaintRegion);
  221207. while (i.next())
  221208. image.clear (*i.getRectangle() - totalArea.getPosition());
  221209. }
  221210. peer->handlePaint (context);
  221211. if (! peer->maskedRegion.isEmpty())
  221212. originalRepaintRegion.subtract (peer->maskedRegion);
  221213. for (RectangleList::Iterator i (originalRepaintRegion); i.next();)
  221214. {
  221215. #if JUCE_USE_XSHM
  221216. shmCompletedDrawing = false;
  221217. #endif
  221218. const Rectangle<int>& r = *i.getRectangle();
  221219. static_cast<XBitmapImage*> (image.getSharedImage())
  221220. ->blitToWindow (peer->windowH,
  221221. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  221222. r.getX() - totalArea.getX(), r.getY() - totalArea.getY());
  221223. }
  221224. }
  221225. lastTimeImageUsed = Time::getApproximateMillisecondCounter();
  221226. startTimer (repaintTimerPeriod);
  221227. }
  221228. #if JUCE_USE_XSHM
  221229. void notifyPaintCompleted() { shmCompletedDrawing = true; }
  221230. #endif
  221231. private:
  221232. enum { repaintTimerPeriod = 1000 / 100 };
  221233. LinuxComponentPeer* const peer;
  221234. Image image;
  221235. uint32 lastTimeImageUsed;
  221236. RectangleList regionsNeedingRepaint;
  221237. #if JUCE_USE_XSHM
  221238. bool useARGBImagesForRendering, shmCompletedDrawing;
  221239. #endif
  221240. LinuxRepaintManager (const LinuxRepaintManager&);
  221241. LinuxRepaintManager& operator= (const LinuxRepaintManager&);
  221242. };
  221243. ScopedPointer <LinuxRepaintManager> repainter;
  221244. friend class LinuxRepaintManager;
  221245. Window windowH, parentWindow;
  221246. int wx, wy, ww, wh;
  221247. Image taskbarImage;
  221248. bool fullScreen, mapped;
  221249. Visual* visual;
  221250. int depth;
  221251. BorderSize windowBorder;
  221252. struct MotifWmHints
  221253. {
  221254. unsigned long flags;
  221255. unsigned long functions;
  221256. unsigned long decorations;
  221257. long input_mode;
  221258. unsigned long status;
  221259. };
  221260. static void updateKeyStates (const int keycode, const bool press) throw()
  221261. {
  221262. const int keybyte = keycode >> 3;
  221263. const int keybit = (1 << (keycode & 7));
  221264. if (press)
  221265. Keys::keyStates [keybyte] |= keybit;
  221266. else
  221267. Keys::keyStates [keybyte] &= ~keybit;
  221268. }
  221269. static void updateKeyModifiers (const int status) throw()
  221270. {
  221271. int keyMods = 0;
  221272. if (status & ShiftMask) keyMods |= ModifierKeys::shiftModifier;
  221273. if (status & ControlMask) keyMods |= ModifierKeys::ctrlModifier;
  221274. if (status & Keys::AltMask) keyMods |= ModifierKeys::altModifier;
  221275. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  221276. Keys::numLock = ((status & Keys::NumLockMask) != 0);
  221277. Keys::capsLock = ((status & LockMask) != 0);
  221278. }
  221279. static bool updateKeyModifiersFromSym (KeySym sym, const bool press) throw()
  221280. {
  221281. int modifier = 0;
  221282. bool isModifier = true;
  221283. switch (sym)
  221284. {
  221285. case XK_Shift_L:
  221286. case XK_Shift_R:
  221287. modifier = ModifierKeys::shiftModifier;
  221288. break;
  221289. case XK_Control_L:
  221290. case XK_Control_R:
  221291. modifier = ModifierKeys::ctrlModifier;
  221292. break;
  221293. case XK_Alt_L:
  221294. case XK_Alt_R:
  221295. modifier = ModifierKeys::altModifier;
  221296. break;
  221297. case XK_Num_Lock:
  221298. if (press)
  221299. Keys::numLock = ! Keys::numLock;
  221300. break;
  221301. case XK_Caps_Lock:
  221302. if (press)
  221303. Keys::capsLock = ! Keys::capsLock;
  221304. break;
  221305. case XK_Scroll_Lock:
  221306. break;
  221307. default:
  221308. isModifier = false;
  221309. break;
  221310. }
  221311. if (modifier != 0)
  221312. {
  221313. if (press)
  221314. currentModifiers = currentModifiers.withFlags (modifier);
  221315. else
  221316. currentModifiers = currentModifiers.withoutFlags (modifier);
  221317. }
  221318. return isModifier;
  221319. }
  221320. // Alt and Num lock are not defined by standard X
  221321. // modifier constants: check what they're mapped to
  221322. static void updateModifierMappings() throw()
  221323. {
  221324. ScopedXLock xlock;
  221325. const int altLeftCode = XKeysymToKeycode (display, XK_Alt_L);
  221326. const int numLockCode = XKeysymToKeycode (display, XK_Num_Lock);
  221327. Keys::AltMask = 0;
  221328. Keys::NumLockMask = 0;
  221329. XModifierKeymap* mapping = XGetModifierMapping (display);
  221330. if (mapping)
  221331. {
  221332. for (int i = 0; i < 8; i++)
  221333. {
  221334. if (mapping->modifiermap [i << 1] == altLeftCode)
  221335. Keys::AltMask = 1 << i;
  221336. else if (mapping->modifiermap [i << 1] == numLockCode)
  221337. Keys::NumLockMask = 1 << i;
  221338. }
  221339. XFreeModifiermap (mapping);
  221340. }
  221341. }
  221342. void removeWindowDecorations (Window wndH)
  221343. {
  221344. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  221345. if (hints != None)
  221346. {
  221347. MotifWmHints motifHints;
  221348. zerostruct (motifHints);
  221349. motifHints.flags = 2; /* MWM_HINTS_DECORATIONS */
  221350. motifHints.decorations = 0;
  221351. ScopedXLock xlock;
  221352. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  221353. (unsigned char*) &motifHints, 4);
  221354. }
  221355. hints = XInternAtom (display, "_WIN_HINTS", True);
  221356. if (hints != None)
  221357. {
  221358. long gnomeHints = 0;
  221359. ScopedXLock xlock;
  221360. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  221361. (unsigned char*) &gnomeHints, 1);
  221362. }
  221363. hints = XInternAtom (display, "KWM_WIN_DECORATION", True);
  221364. if (hints != None)
  221365. {
  221366. long kwmHints = 2; /*KDE_tinyDecoration*/
  221367. ScopedXLock xlock;
  221368. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  221369. (unsigned char*) &kwmHints, 1);
  221370. }
  221371. }
  221372. void addWindowButtons (Window wndH)
  221373. {
  221374. ScopedXLock xlock;
  221375. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  221376. if (hints != None)
  221377. {
  221378. MotifWmHints motifHints;
  221379. zerostruct (motifHints);
  221380. motifHints.flags = 1 | 2; /* MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS */
  221381. motifHints.decorations = 2 /* MWM_DECOR_BORDER */ | 8 /* MWM_DECOR_TITLE */ | 16; /* MWM_DECOR_MENU */
  221382. motifHints.functions = 4 /* MWM_FUNC_MOVE */;
  221383. if ((styleFlags & windowHasCloseButton) != 0)
  221384. motifHints.functions |= 32; /* MWM_FUNC_CLOSE */
  221385. if ((styleFlags & windowHasMinimiseButton) != 0)
  221386. {
  221387. motifHints.functions |= 8; /* MWM_FUNC_MINIMIZE */
  221388. motifHints.decorations |= 0x20; /* MWM_DECOR_MINIMIZE */
  221389. }
  221390. if ((styleFlags & windowHasMaximiseButton) != 0)
  221391. {
  221392. motifHints.functions |= 0x10; /* MWM_FUNC_MAXIMIZE */
  221393. motifHints.decorations |= 0x40; /* MWM_DECOR_MAXIMIZE */
  221394. }
  221395. if ((styleFlags & windowIsResizable) != 0)
  221396. {
  221397. motifHints.functions |= 2; /* MWM_FUNC_RESIZE */
  221398. motifHints.decorations |= 0x4; /* MWM_DECOR_RESIZEH */
  221399. }
  221400. XChangeProperty (display, wndH, hints, hints, 32, 0, (unsigned char*) &motifHints, 5);
  221401. }
  221402. hints = XInternAtom (display, "_NET_WM_ALLOWED_ACTIONS", True);
  221403. if (hints != None)
  221404. {
  221405. int netHints [6];
  221406. int num = 0;
  221407. if ((styleFlags & windowIsResizable) != 0)
  221408. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_RESIZE", True);
  221409. if ((styleFlags & windowHasMaximiseButton) != 0)
  221410. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_FULLSCREEN", True);
  221411. if ((styleFlags & windowHasMinimiseButton) != 0)
  221412. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_MINIMIZE", True);
  221413. if ((styleFlags & windowHasCloseButton) != 0)
  221414. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_CLOSE", True);
  221415. XChangeProperty (display, wndH, hints, XA_ATOM, 32, PropModeReplace, (unsigned char*) &netHints, num);
  221416. }
  221417. }
  221418. void setWindowType()
  221419. {
  221420. int netHints [2];
  221421. int numHints = 0;
  221422. if ((styleFlags & windowIsTemporary) != 0
  221423. || ((styleFlags & windowHasDropShadow) == 0 && Desktop::canUseSemiTransparentWindows()))
  221424. netHints [numHints++] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_COMBO", True);
  221425. else
  221426. netHints [numHints++] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_NORMAL", True);
  221427. netHints[numHints++] = XInternAtom (display, "_KDE_NET_WM_WINDOW_TYPE_OVERRIDE", True);
  221428. XChangeProperty (display, windowH, Atoms::WindowType, XA_ATOM, 32, PropModeReplace,
  221429. (unsigned char*) &netHints, numHints);
  221430. numHints = 0;
  221431. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  221432. netHints [numHints++] = XInternAtom (display, "_NET_WM_STATE_SKIP_TASKBAR", True);
  221433. if (component->isAlwaysOnTop())
  221434. netHints [numHints++] = XInternAtom (display, "_NET_WM_STATE_ABOVE", True);
  221435. if (numHints > 0)
  221436. XChangeProperty (display, windowH, Atoms::WindowState, XA_ATOM, 32, PropModeReplace,
  221437. (unsigned char*) &netHints, numHints);
  221438. }
  221439. void createWindow()
  221440. {
  221441. ScopedXLock xlock;
  221442. Atoms::initialiseAtoms();
  221443. resetDragAndDrop();
  221444. // Get defaults for various properties
  221445. const int screen = DefaultScreen (display);
  221446. Window root = RootWindow (display, screen);
  221447. // Try to obtain a 32-bit visual or fallback to 24 or 16
  221448. visual = Visuals::findVisualFormat ((styleFlags & windowIsSemiTransparent) ? 32 : 24, depth);
  221449. if (visual == 0)
  221450. {
  221451. Logger::outputDebugString ("ERROR: System doesn't support 32, 24 or 16 bit RGB display.\n");
  221452. Process::terminate();
  221453. }
  221454. // Create and install a colormap suitable fr our visual
  221455. Colormap colormap = XCreateColormap (display, root, visual, AllocNone);
  221456. XInstallColormap (display, colormap);
  221457. // Set up the window attributes
  221458. XSetWindowAttributes swa;
  221459. swa.border_pixel = 0;
  221460. swa.background_pixmap = None;
  221461. swa.colormap = colormap;
  221462. swa.event_mask = getAllEventsMask();
  221463. windowH = XCreateWindow (display, root,
  221464. 0, 0, 1, 1,
  221465. 0, depth, InputOutput, visual,
  221466. CWBorderPixel | CWColormap | CWBackPixmap | CWEventMask,
  221467. &swa);
  221468. XGrabButton (display, AnyButton, AnyModifier, windowH, False,
  221469. ButtonPressMask | ButtonReleaseMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask,
  221470. GrabModeAsync, GrabModeAsync, None, None);
  221471. // Set the window context to identify the window handle object
  221472. if (XSaveContext (display, (XID) windowH, windowHandleXContext, (XPointer) this))
  221473. {
  221474. // Failed
  221475. jassertfalse;
  221476. Logger::outputDebugString ("Failed to create context information for window.\n");
  221477. XDestroyWindow (display, windowH);
  221478. windowH = 0;
  221479. return;
  221480. }
  221481. // Set window manager hints
  221482. XWMHints* wmHints = XAllocWMHints();
  221483. wmHints->flags = InputHint | StateHint;
  221484. wmHints->input = True; // Locally active input model
  221485. wmHints->initial_state = NormalState;
  221486. XSetWMHints (display, windowH, wmHints);
  221487. XFree (wmHints);
  221488. // Set the window type
  221489. setWindowType();
  221490. // Define decoration
  221491. if ((styleFlags & windowHasTitleBar) == 0)
  221492. removeWindowDecorations (windowH);
  221493. else
  221494. addWindowButtons (windowH);
  221495. // Set window name
  221496. setWindowTitle (windowH, getComponent()->getName());
  221497. // Associate the PID, allowing to be shut down when something goes wrong
  221498. unsigned long pid = getpid();
  221499. XChangeProperty (display, windowH, Atoms::Pid, XA_CARDINAL, 32, PropModeReplace,
  221500. (unsigned char*) &pid, 1);
  221501. // Set window manager protocols
  221502. XChangeProperty (display, windowH, Atoms::Protocols, XA_ATOM, 32, PropModeReplace,
  221503. (unsigned char*) Atoms::ProtocolList, 2);
  221504. // Set drag and drop flags
  221505. XChangeProperty (display, windowH, Atoms::XdndTypeList, XA_ATOM, 32, PropModeReplace,
  221506. (const unsigned char*) Atoms::allowedMimeTypes, numElementsInArray (Atoms::allowedMimeTypes));
  221507. XChangeProperty (display, windowH, Atoms::XdndActionList, XA_ATOM, 32, PropModeReplace,
  221508. (const unsigned char*) Atoms::allowedActions, numElementsInArray (Atoms::allowedActions));
  221509. XChangeProperty (display, windowH, Atoms::XdndActionDescription, XA_STRING, 8, PropModeReplace,
  221510. (const unsigned char*) "", 0);
  221511. unsigned long dndVersion = Atoms::DndVersion;
  221512. XChangeProperty (display, windowH, Atoms::XdndAware, XA_ATOM, 32, PropModeReplace,
  221513. (const unsigned char*) &dndVersion, 1);
  221514. // Initialise the pointer and keyboard mapping
  221515. // This is not the same as the logical pointer mapping the X server uses:
  221516. // we don't mess with this.
  221517. static bool mappingInitialised = false;
  221518. if (! mappingInitialised)
  221519. {
  221520. mappingInitialised = true;
  221521. const int numButtons = XGetPointerMapping (display, 0, 0);
  221522. if (numButtons == 2)
  221523. {
  221524. pointerMap[0] = Keys::LeftButton;
  221525. pointerMap[1] = Keys::RightButton;
  221526. pointerMap[2] = pointerMap[3] = pointerMap[4] = Keys::NoButton;
  221527. }
  221528. else if (numButtons >= 3)
  221529. {
  221530. pointerMap[0] = Keys::LeftButton;
  221531. pointerMap[1] = Keys::MiddleButton;
  221532. pointerMap[2] = Keys::RightButton;
  221533. if (numButtons >= 5)
  221534. {
  221535. pointerMap[3] = Keys::WheelUp;
  221536. pointerMap[4] = Keys::WheelDown;
  221537. }
  221538. }
  221539. updateModifierMappings();
  221540. }
  221541. }
  221542. void destroyWindow()
  221543. {
  221544. ScopedXLock xlock;
  221545. XPointer handlePointer;
  221546. if (! XFindContext (display, (XID) windowH, windowHandleXContext, &handlePointer))
  221547. XDeleteContext (display, (XID) windowH, windowHandleXContext);
  221548. XDestroyWindow (display, windowH);
  221549. // Wait for it to complete and then remove any events for this
  221550. // window from the event queue.
  221551. XSync (display, false);
  221552. XEvent event;
  221553. while (XCheckWindowEvent (display, windowH, getAllEventsMask(), &event) == True)
  221554. {}
  221555. }
  221556. static int getAllEventsMask() throw()
  221557. {
  221558. return NoEventMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask
  221559. | EnterWindowMask | LeaveWindowMask | PointerMotionMask | KeymapStateMask
  221560. | ExposureMask | StructureNotifyMask | FocusChangeMask;
  221561. }
  221562. static int64 getEventTime (::Time t)
  221563. {
  221564. static int64 eventTimeOffset = 0x12345678;
  221565. const int64 thisMessageTime = t;
  221566. if (eventTimeOffset == 0x12345678)
  221567. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  221568. return eventTimeOffset + thisMessageTime;
  221569. }
  221570. static void setWindowTitle (Window xwin, const String& title)
  221571. {
  221572. XTextProperty nameProperty;
  221573. char* strings[] = { const_cast <char*> (title.toUTF8()) };
  221574. ScopedXLock xlock;
  221575. if (XStringListToTextProperty (strings, 1, &nameProperty))
  221576. {
  221577. XSetWMName (display, xwin, &nameProperty);
  221578. XSetWMIconName (display, xwin, &nameProperty);
  221579. XFree (nameProperty.value);
  221580. }
  221581. }
  221582. void updateBorderSize()
  221583. {
  221584. if ((styleFlags & windowHasTitleBar) == 0)
  221585. {
  221586. windowBorder = BorderSize (0);
  221587. }
  221588. else if (windowBorder.getTopAndBottom() == 0 && windowBorder.getLeftAndRight() == 0)
  221589. {
  221590. ScopedXLock xlock;
  221591. Atom hints = XInternAtom (display, "_NET_FRAME_EXTENTS", True);
  221592. if (hints != None)
  221593. {
  221594. unsigned char* data = 0;
  221595. unsigned long nitems, bytesLeft;
  221596. Atom actualType;
  221597. int actualFormat;
  221598. if (XGetWindowProperty (display, windowH, hints, 0, 4, False,
  221599. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  221600. &data) == Success)
  221601. {
  221602. const unsigned long* const sizes = (const unsigned long*) data;
  221603. if (actualFormat == 32)
  221604. windowBorder = BorderSize ((int) sizes[2], (int) sizes[0],
  221605. (int) sizes[3], (int) sizes[1]);
  221606. XFree (data);
  221607. }
  221608. }
  221609. }
  221610. }
  221611. void updateBounds()
  221612. {
  221613. jassert (windowH != 0);
  221614. if (windowH != 0)
  221615. {
  221616. Window root, child;
  221617. unsigned int bw, depth;
  221618. ScopedXLock xlock;
  221619. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  221620. &wx, &wy, (unsigned int*) &ww, (unsigned int*) &wh,
  221621. &bw, &depth))
  221622. {
  221623. wx = wy = ww = wh = 0;
  221624. }
  221625. else if (! XTranslateCoordinates (display, windowH, root, 0, 0, &wx, &wy, &child))
  221626. {
  221627. wx = wy = 0;
  221628. }
  221629. }
  221630. }
  221631. void resetDragAndDrop()
  221632. {
  221633. dragAndDropFiles.clear();
  221634. lastDropPos = Point<int> (-1, -1);
  221635. dragAndDropCurrentMimeType = 0;
  221636. dragAndDropSourceWindow = 0;
  221637. srcMimeTypeAtomList.clear();
  221638. }
  221639. void sendDragAndDropMessage (XClientMessageEvent& msg)
  221640. {
  221641. msg.type = ClientMessage;
  221642. msg.display = display;
  221643. msg.window = dragAndDropSourceWindow;
  221644. msg.format = 32;
  221645. msg.data.l[0] = windowH;
  221646. ScopedXLock xlock;
  221647. XSendEvent (display, dragAndDropSourceWindow, False, 0, (XEvent*) &msg);
  221648. }
  221649. void sendDragAndDropStatus (const bool acceptDrop, Atom dropAction)
  221650. {
  221651. XClientMessageEvent msg;
  221652. zerostruct (msg);
  221653. msg.message_type = Atoms::XdndStatus;
  221654. msg.data.l[1] = (acceptDrop ? 1 : 0) | 2; // 2 indicates that we want to receive position messages
  221655. msg.data.l[4] = dropAction;
  221656. sendDragAndDropMessage (msg);
  221657. }
  221658. void sendDragAndDropLeave()
  221659. {
  221660. XClientMessageEvent msg;
  221661. zerostruct (msg);
  221662. msg.message_type = Atoms::XdndLeave;
  221663. sendDragAndDropMessage (msg);
  221664. }
  221665. void sendDragAndDropFinish()
  221666. {
  221667. XClientMessageEvent msg;
  221668. zerostruct (msg);
  221669. msg.message_type = Atoms::XdndFinished;
  221670. sendDragAndDropMessage (msg);
  221671. }
  221672. void handleDragAndDropStatus (const XClientMessageEvent* const clientMsg)
  221673. {
  221674. if ((clientMsg->data.l[1] & 1) == 0)
  221675. {
  221676. sendDragAndDropLeave();
  221677. if (dragAndDropFiles.size() > 0)
  221678. handleFileDragExit (dragAndDropFiles);
  221679. dragAndDropFiles.clear();
  221680. }
  221681. }
  221682. void handleDragAndDropPosition (const XClientMessageEvent* const clientMsg)
  221683. {
  221684. if (dragAndDropSourceWindow == 0)
  221685. return;
  221686. dragAndDropSourceWindow = clientMsg->data.l[0];
  221687. Point<int> dropPos ((int) clientMsg->data.l[2] >> 16,
  221688. (int) clientMsg->data.l[2] & 0xffff);
  221689. dropPos -= getScreenPosition();
  221690. if (lastDropPos != dropPos)
  221691. {
  221692. lastDropPos = dropPos;
  221693. dragAndDropTimestamp = clientMsg->data.l[3];
  221694. Atom targetAction = Atoms::XdndActionCopy;
  221695. for (int i = numElementsInArray (Atoms::allowedActions); --i >= 0;)
  221696. {
  221697. if ((Atom) clientMsg->data.l[4] == Atoms::allowedActions[i])
  221698. {
  221699. targetAction = Atoms::allowedActions[i];
  221700. break;
  221701. }
  221702. }
  221703. sendDragAndDropStatus (true, targetAction);
  221704. if (dragAndDropFiles.size() == 0)
  221705. updateDraggedFileList (clientMsg);
  221706. if (dragAndDropFiles.size() > 0)
  221707. handleFileDragMove (dragAndDropFiles, dropPos);
  221708. }
  221709. }
  221710. void handleDragAndDropDrop (const XClientMessageEvent* const clientMsg)
  221711. {
  221712. if (dragAndDropFiles.size() == 0)
  221713. updateDraggedFileList (clientMsg);
  221714. const StringArray files (dragAndDropFiles);
  221715. const Point<int> lastPos (lastDropPos);
  221716. sendDragAndDropFinish();
  221717. resetDragAndDrop();
  221718. if (files.size() > 0)
  221719. handleFileDragDrop (files, lastPos);
  221720. }
  221721. void handleDragAndDropEnter (const XClientMessageEvent* const clientMsg)
  221722. {
  221723. dragAndDropFiles.clear();
  221724. srcMimeTypeAtomList.clear();
  221725. dragAndDropCurrentMimeType = 0;
  221726. const unsigned long dndCurrentVersion = static_cast <unsigned long> (clientMsg->data.l[1] & 0xff000000) >> 24;
  221727. if (dndCurrentVersion < 3 || dndCurrentVersion > Atoms::DndVersion)
  221728. {
  221729. dragAndDropSourceWindow = 0;
  221730. return;
  221731. }
  221732. dragAndDropSourceWindow = clientMsg->data.l[0];
  221733. if ((clientMsg->data.l[1] & 1) != 0)
  221734. {
  221735. Atom actual;
  221736. int format;
  221737. unsigned long count = 0, remaining = 0;
  221738. unsigned char* data = 0;
  221739. ScopedXLock xlock;
  221740. XGetWindowProperty (display, dragAndDropSourceWindow, Atoms::XdndTypeList,
  221741. 0, 0x8000000L, False, XA_ATOM, &actual, &format,
  221742. &count, &remaining, &data);
  221743. if (data != 0)
  221744. {
  221745. if (actual == XA_ATOM && format == 32 && count != 0)
  221746. {
  221747. const unsigned long* const types = (const unsigned long*) data;
  221748. for (unsigned int i = 0; i < count; ++i)
  221749. if (types[i] != None)
  221750. srcMimeTypeAtomList.add (types[i]);
  221751. }
  221752. XFree (data);
  221753. }
  221754. }
  221755. if (srcMimeTypeAtomList.size() == 0)
  221756. {
  221757. for (int i = 2; i < 5; ++i)
  221758. if (clientMsg->data.l[i] != None)
  221759. srcMimeTypeAtomList.add (clientMsg->data.l[i]);
  221760. if (srcMimeTypeAtomList.size() == 0)
  221761. {
  221762. dragAndDropSourceWindow = 0;
  221763. return;
  221764. }
  221765. }
  221766. for (int i = 0; i < srcMimeTypeAtomList.size() && dragAndDropCurrentMimeType == 0; ++i)
  221767. for (int j = 0; j < numElementsInArray (Atoms::allowedMimeTypes); ++j)
  221768. if (srcMimeTypeAtomList[i] == Atoms::allowedMimeTypes[j])
  221769. dragAndDropCurrentMimeType = Atoms::allowedMimeTypes[j];
  221770. handleDragAndDropPosition (clientMsg);
  221771. }
  221772. void handleDragAndDropSelection (const XEvent* const evt)
  221773. {
  221774. dragAndDropFiles.clear();
  221775. if (evt->xselection.property != 0)
  221776. {
  221777. StringArray lines;
  221778. {
  221779. MemoryBlock dropData;
  221780. for (;;)
  221781. {
  221782. Atom actual;
  221783. uint8* data = 0;
  221784. unsigned long count = 0, remaining = 0;
  221785. int format = 0;
  221786. ScopedXLock xlock;
  221787. if (XGetWindowProperty (display, evt->xany.window, evt->xselection.property,
  221788. dropData.getSize() / 4, 65536, 1, AnyPropertyType, &actual,
  221789. &format, &count, &remaining, &data) == Success)
  221790. {
  221791. dropData.append (data, count * format / 8);
  221792. XFree (data);
  221793. if (remaining == 0)
  221794. break;
  221795. }
  221796. else
  221797. {
  221798. XFree (data);
  221799. break;
  221800. }
  221801. }
  221802. lines.addLines (dropData.toString());
  221803. }
  221804. for (int i = 0; i < lines.size(); ++i)
  221805. dragAndDropFiles.add (URL::removeEscapeChars (lines[i].fromFirstOccurrenceOf ("file://", false, true)));
  221806. dragAndDropFiles.trim();
  221807. dragAndDropFiles.removeEmptyStrings();
  221808. }
  221809. }
  221810. void updateDraggedFileList (const XClientMessageEvent* const clientMsg)
  221811. {
  221812. dragAndDropFiles.clear();
  221813. if (dragAndDropSourceWindow != None
  221814. && dragAndDropCurrentMimeType != 0)
  221815. {
  221816. dragAndDropTimestamp = clientMsg->data.l[2];
  221817. ScopedXLock xlock;
  221818. XConvertSelection (display,
  221819. Atoms::XdndSelection,
  221820. dragAndDropCurrentMimeType,
  221821. XInternAtom (display, "JXSelectionWindowProperty", 0),
  221822. windowH,
  221823. dragAndDropTimestamp);
  221824. }
  221825. }
  221826. StringArray dragAndDropFiles;
  221827. int dragAndDropTimestamp;
  221828. Point<int> lastDropPos;
  221829. Atom dragAndDropCurrentMimeType;
  221830. Window dragAndDropSourceWindow;
  221831. Array <Atom> srcMimeTypeAtomList;
  221832. static int pointerMap[5];
  221833. static Point<int> lastMousePos;
  221834. static void clearLastMousePos() throw()
  221835. {
  221836. lastMousePos = Point<int> (0x100000, 0x100000);
  221837. }
  221838. };
  221839. ModifierKeys LinuxComponentPeer::currentModifiers;
  221840. bool LinuxComponentPeer::isActiveApplication = false;
  221841. int LinuxComponentPeer::pointerMap[5];
  221842. Point<int> LinuxComponentPeer::lastMousePos;
  221843. bool Process::isForegroundProcess()
  221844. {
  221845. return LinuxComponentPeer::isActiveApplication;
  221846. }
  221847. void ModifierKeys::updateCurrentModifiers() throw()
  221848. {
  221849. currentModifiers = LinuxComponentPeer::currentModifiers;
  221850. }
  221851. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  221852. {
  221853. Window root, child;
  221854. int x, y, winx, winy;
  221855. unsigned int mask;
  221856. int mouseMods = 0;
  221857. ScopedXLock xlock;
  221858. if (XQueryPointer (display, RootWindow (display, DefaultScreen (display)),
  221859. &root, &child, &x, &y, &winx, &winy, &mask) != False)
  221860. {
  221861. if ((mask & Button1Mask) != 0) mouseMods |= ModifierKeys::leftButtonModifier;
  221862. if ((mask & Button2Mask) != 0) mouseMods |= ModifierKeys::middleButtonModifier;
  221863. if ((mask & Button3Mask) != 0) mouseMods |= ModifierKeys::rightButtonModifier;
  221864. }
  221865. LinuxComponentPeer::currentModifiers = LinuxComponentPeer::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  221866. return LinuxComponentPeer::currentModifiers;
  221867. }
  221868. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  221869. {
  221870. if (enableOrDisable)
  221871. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  221872. }
  221873. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  221874. {
  221875. return new LinuxComponentPeer (this, styleFlags);
  221876. }
  221877. // (this callback is hooked up in the messaging code)
  221878. void juce_windowMessageReceive (XEvent* event)
  221879. {
  221880. if (event->xany.window != None)
  221881. {
  221882. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (event->xany.window);
  221883. if (ComponentPeer::isValidPeer (peer))
  221884. peer->handleWindowMessage (event);
  221885. }
  221886. else
  221887. {
  221888. switch (event->xany.type)
  221889. {
  221890. case KeymapNotify:
  221891. {
  221892. const XKeymapEvent* const keymapEvent = (const XKeymapEvent*) &event->xkeymap;
  221893. memcpy (Keys::keyStates, keymapEvent->key_vector, 32);
  221894. break;
  221895. }
  221896. default:
  221897. break;
  221898. }
  221899. }
  221900. }
  221901. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool /*clipToWorkArea*/)
  221902. {
  221903. if (display == 0)
  221904. return;
  221905. #if JUCE_USE_XINERAMA
  221906. int major_opcode, first_event, first_error;
  221907. ScopedXLock xlock;
  221908. if (XQueryExtension (display, "XINERAMA", &major_opcode, &first_event, &first_error))
  221909. {
  221910. typedef Bool (*tXineramaIsActive) (Display*);
  221911. typedef XineramaScreenInfo* (*tXineramaQueryScreens) (Display*, int*);
  221912. static tXineramaIsActive xXineramaIsActive = 0;
  221913. static tXineramaQueryScreens xXineramaQueryScreens = 0;
  221914. if (xXineramaIsActive == 0 || xXineramaQueryScreens == 0)
  221915. {
  221916. void* h = dlopen ("libXinerama.so", RTLD_GLOBAL | RTLD_NOW);
  221917. if (h == 0)
  221918. h = dlopen ("libXinerama.so.1", RTLD_GLOBAL | RTLD_NOW);
  221919. if (h != 0)
  221920. {
  221921. xXineramaIsActive = (tXineramaIsActive) dlsym (h, "XineramaIsActive");
  221922. xXineramaQueryScreens = (tXineramaQueryScreens) dlsym (h, "XineramaQueryScreens");
  221923. }
  221924. }
  221925. if (xXineramaIsActive != 0
  221926. && xXineramaQueryScreens != 0
  221927. && xXineramaIsActive (display))
  221928. {
  221929. int numMonitors = 0;
  221930. XineramaScreenInfo* const screens = xXineramaQueryScreens (display, &numMonitors);
  221931. if (screens != 0)
  221932. {
  221933. for (int i = numMonitors; --i >= 0;)
  221934. {
  221935. int index = screens[i].screen_number;
  221936. if (index >= 0)
  221937. {
  221938. while (monitorCoords.size() < index)
  221939. monitorCoords.add (Rectangle<int>());
  221940. monitorCoords.set (index, Rectangle<int> (screens[i].x_org,
  221941. screens[i].y_org,
  221942. screens[i].width,
  221943. screens[i].height));
  221944. }
  221945. }
  221946. XFree (screens);
  221947. }
  221948. }
  221949. }
  221950. if (monitorCoords.size() == 0)
  221951. #endif
  221952. {
  221953. Atom hints = XInternAtom (display, "_NET_WORKAREA", True);
  221954. if (hints != None)
  221955. {
  221956. const int numMonitors = ScreenCount (display);
  221957. for (int i = 0; i < numMonitors; ++i)
  221958. {
  221959. Window root = RootWindow (display, i);
  221960. unsigned long nitems, bytesLeft;
  221961. Atom actualType;
  221962. int actualFormat;
  221963. unsigned char* data = 0;
  221964. if (XGetWindowProperty (display, root, hints, 0, 4, False,
  221965. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  221966. &data) == Success)
  221967. {
  221968. const long* const position = (const long*) data;
  221969. if (actualType == XA_CARDINAL && actualFormat == 32 && nitems == 4)
  221970. monitorCoords.add (Rectangle<int> (position[0], position[1],
  221971. position[2], position[3]));
  221972. XFree (data);
  221973. }
  221974. }
  221975. }
  221976. if (monitorCoords.size() == 0)
  221977. {
  221978. monitorCoords.add (Rectangle<int> (DisplayWidth (display, DefaultScreen (display)),
  221979. DisplayHeight (display, DefaultScreen (display))));
  221980. }
  221981. }
  221982. }
  221983. void Desktop::createMouseInputSources()
  221984. {
  221985. mouseSources.add (new MouseInputSource (0, true));
  221986. }
  221987. bool Desktop::canUseSemiTransparentWindows() throw()
  221988. {
  221989. int matchedDepth = 0;
  221990. const int desiredDepth = 32;
  221991. return Visuals::findVisualFormat (desiredDepth, matchedDepth) != 0
  221992. && (matchedDepth == desiredDepth);
  221993. }
  221994. const Point<int> Desktop::getMousePosition()
  221995. {
  221996. Window root, child;
  221997. int x, y, winx, winy;
  221998. unsigned int mask;
  221999. ScopedXLock xlock;
  222000. if (XQueryPointer (display,
  222001. RootWindow (display, DefaultScreen (display)),
  222002. &root, &child,
  222003. &x, &y, &winx, &winy, &mask) == False)
  222004. {
  222005. // Pointer not on the default screen
  222006. x = y = -1;
  222007. }
  222008. return Point<int> (x, y);
  222009. }
  222010. void Desktop::setMousePosition (const Point<int>& newPosition)
  222011. {
  222012. ScopedXLock xlock;
  222013. Window root = RootWindow (display, DefaultScreen (display));
  222014. XWarpPointer (display, None, root, 0, 0, 0, 0, newPosition.getX(), newPosition.getY());
  222015. }
  222016. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  222017. {
  222018. return upright;
  222019. }
  222020. static bool screenSaverAllowed = true;
  222021. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  222022. {
  222023. if (screenSaverAllowed != isEnabled)
  222024. {
  222025. screenSaverAllowed = isEnabled;
  222026. typedef void (*tXScreenSaverSuspend) (Display*, Bool);
  222027. static tXScreenSaverSuspend xScreenSaverSuspend = 0;
  222028. if (xScreenSaverSuspend == 0)
  222029. {
  222030. void* h = dlopen ("libXss.so", RTLD_GLOBAL | RTLD_NOW);
  222031. if (h != 0)
  222032. xScreenSaverSuspend = (tXScreenSaverSuspend) dlsym (h, "XScreenSaverSuspend");
  222033. }
  222034. ScopedXLock xlock;
  222035. if (xScreenSaverSuspend != 0)
  222036. xScreenSaverSuspend (display, ! isEnabled);
  222037. }
  222038. }
  222039. bool Desktop::isScreenSaverEnabled()
  222040. {
  222041. return screenSaverAllowed;
  222042. }
  222043. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  222044. {
  222045. ScopedXLock xlock;
  222046. const unsigned int imageW = image.getWidth();
  222047. const unsigned int imageH = image.getHeight();
  222048. #if JUCE_USE_XCURSOR
  222049. {
  222050. typedef XcursorBool (*tXcursorSupportsARGB) (Display*);
  222051. typedef XcursorImage* (*tXcursorImageCreate) (int, int);
  222052. typedef void (*tXcursorImageDestroy) (XcursorImage*);
  222053. typedef Cursor (*tXcursorImageLoadCursor) (Display*, const XcursorImage*);
  222054. static tXcursorSupportsARGB xXcursorSupportsARGB = 0;
  222055. static tXcursorImageCreate xXcursorImageCreate = 0;
  222056. static tXcursorImageDestroy xXcursorImageDestroy = 0;
  222057. static tXcursorImageLoadCursor xXcursorImageLoadCursor = 0;
  222058. static bool hasBeenLoaded = false;
  222059. if (! hasBeenLoaded)
  222060. {
  222061. hasBeenLoaded = true;
  222062. void* h = dlopen ("libXcursor.so", RTLD_GLOBAL | RTLD_NOW);
  222063. if (h != 0)
  222064. {
  222065. xXcursorSupportsARGB = (tXcursorSupportsARGB) dlsym (h, "XcursorSupportsARGB");
  222066. xXcursorImageCreate = (tXcursorImageCreate) dlsym (h, "XcursorImageCreate");
  222067. xXcursorImageLoadCursor = (tXcursorImageLoadCursor) dlsym (h, "XcursorImageLoadCursor");
  222068. xXcursorImageDestroy = (tXcursorImageDestroy) dlsym (h, "XcursorImageDestroy");
  222069. if (xXcursorSupportsARGB == 0 || xXcursorImageCreate == 0
  222070. || xXcursorImageLoadCursor == 0 || xXcursorImageDestroy == 0
  222071. || ! xXcursorSupportsARGB (display))
  222072. xXcursorSupportsARGB = 0;
  222073. }
  222074. }
  222075. if (xXcursorSupportsARGB != 0)
  222076. {
  222077. XcursorImage* xcImage = xXcursorImageCreate (imageW, imageH);
  222078. if (xcImage != 0)
  222079. {
  222080. xcImage->xhot = hotspotX;
  222081. xcImage->yhot = hotspotY;
  222082. XcursorPixel* dest = xcImage->pixels;
  222083. for (int y = 0; y < (int) imageH; ++y)
  222084. for (int x = 0; x < (int) imageW; ++x)
  222085. *dest++ = image.getPixelAt (x, y).getARGB();
  222086. void* result = (void*) xXcursorImageLoadCursor (display, xcImage);
  222087. xXcursorImageDestroy (xcImage);
  222088. if (result != 0)
  222089. return result;
  222090. }
  222091. }
  222092. }
  222093. #endif
  222094. Window root = RootWindow (display, DefaultScreen (display));
  222095. unsigned int cursorW, cursorH;
  222096. if (! XQueryBestCursor (display, root, imageW, imageH, &cursorW, &cursorH))
  222097. return 0;
  222098. Image im (Image::ARGB, cursorW, cursorH, true);
  222099. {
  222100. Graphics g (im);
  222101. if (imageW > cursorW || imageH > cursorH)
  222102. {
  222103. hotspotX = (hotspotX * cursorW) / imageW;
  222104. hotspotY = (hotspotY * cursorH) / imageH;
  222105. g.drawImageWithin (image, 0, 0, imageW, imageH,
  222106. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  222107. false);
  222108. }
  222109. else
  222110. {
  222111. g.drawImageAt (image, 0, 0);
  222112. }
  222113. }
  222114. const int stride = (cursorW + 7) >> 3;
  222115. HeapBlock <char> maskPlane, sourcePlane;
  222116. maskPlane.calloc (stride * cursorH);
  222117. sourcePlane.calloc (stride * cursorH);
  222118. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  222119. for (int y = cursorH; --y >= 0;)
  222120. {
  222121. for (int x = cursorW; --x >= 0;)
  222122. {
  222123. const char mask = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  222124. const int offset = y * stride + (x >> 3);
  222125. const Colour c (im.getPixelAt (x, y));
  222126. if (c.getAlpha() >= 128)
  222127. maskPlane[offset] |= mask;
  222128. if (c.getBrightness() >= 0.5f)
  222129. sourcePlane[offset] |= mask;
  222130. }
  222131. }
  222132. Pixmap sourcePixmap = XCreatePixmapFromBitmapData (display, root, sourcePlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  222133. Pixmap maskPixmap = XCreatePixmapFromBitmapData (display, root, maskPlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  222134. XColor white, black;
  222135. black.red = black.green = black.blue = 0;
  222136. white.red = white.green = white.blue = 0xffff;
  222137. void* result = (void*) XCreatePixmapCursor (display, sourcePixmap, maskPixmap, &white, &black, hotspotX, hotspotY);
  222138. XFreePixmap (display, sourcePixmap);
  222139. XFreePixmap (display, maskPixmap);
  222140. return result;
  222141. }
  222142. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool)
  222143. {
  222144. ScopedXLock xlock;
  222145. if (cursorHandle != 0)
  222146. XFreeCursor (display, (Cursor) cursorHandle);
  222147. }
  222148. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  222149. {
  222150. unsigned int shape;
  222151. switch (type)
  222152. {
  222153. case NormalCursor: return None; // Use parent cursor
  222154. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 16, 16, true), 0, 0);
  222155. case WaitCursor: shape = XC_watch; break;
  222156. case IBeamCursor: shape = XC_xterm; break;
  222157. case PointingHandCursor: shape = XC_hand2; break;
  222158. case LeftRightResizeCursor: shape = XC_sb_h_double_arrow; break;
  222159. case UpDownResizeCursor: shape = XC_sb_v_double_arrow; break;
  222160. case UpDownLeftRightResizeCursor: shape = XC_fleur; break;
  222161. case TopEdgeResizeCursor: shape = XC_top_side; break;
  222162. case BottomEdgeResizeCursor: shape = XC_bottom_side; break;
  222163. case LeftEdgeResizeCursor: shape = XC_left_side; break;
  222164. case RightEdgeResizeCursor: shape = XC_right_side; break;
  222165. case TopLeftCornerResizeCursor: shape = XC_top_left_corner; break;
  222166. case TopRightCornerResizeCursor: shape = XC_top_right_corner; break;
  222167. case BottomLeftCornerResizeCursor: shape = XC_bottom_left_corner; break;
  222168. case BottomRightCornerResizeCursor: shape = XC_bottom_right_corner; break;
  222169. case CrosshairCursor: shape = XC_crosshair; break;
  222170. case DraggingHandCursor:
  222171. {
  222172. static unsigned char dragHandData[] = { 71,73,70,56,57,97,16,0,16,0,145,2,0,0,0,0,255,255,255,0,
  222173. 0,0,0,0,0,33,249,4,1,0,0,2,0,44,0,0,0,0,16,0, 16,0,0,2,52,148,47,0,200,185,16,130,90,12,74,139,107,84,123,39,
  222174. 132,117,151,116,132,146,248,60,209,138,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 };
  222175. const int dragHandDataSize = 99;
  222176. return createMouseCursorFromImage (ImageFileFormat::loadFrom (dragHandData, dragHandDataSize), 8, 7);
  222177. }
  222178. case CopyingCursor:
  222179. {
  222180. static unsigned char copyCursorData[] = { 71,73,70,56,57,97,21,0,21,0,145,0,0,0,0,0,255,255,255,0,
  222181. 128,128,255,255,255,33,249,4,1,0,0,3,0,44,0,0,0,0,21,0, 21,0,0,2,72,4,134,169,171,16,199,98,11,79,90,71,161,93,56,111,
  222182. 78,133,218,215,137,31,82,154,100,200,86,91,202,142,12,108,212,87,235,174, 15,54,214,126,237,226,37,96,59,141,16,37,18,201,142,157,230,204,51,112,
  222183. 252,114,147,74,83,5,50,68,147,208,217,16,71,149,252,124,5,0,59,0,0 };
  222184. const int copyCursorSize = 119;
  222185. return createMouseCursorFromImage (ImageFileFormat::loadFrom (copyCursorData, copyCursorSize), 1, 3);
  222186. }
  222187. default:
  222188. jassertfalse;
  222189. return None;
  222190. }
  222191. ScopedXLock xlock;
  222192. return (void*) XCreateFontCursor (display, shape);
  222193. }
  222194. void MouseCursor::showInWindow (ComponentPeer* peer) const
  222195. {
  222196. LinuxComponentPeer* const lp = dynamic_cast <LinuxComponentPeer*> (peer);
  222197. if (lp != 0)
  222198. lp->showMouseCursor ((Cursor) getHandle());
  222199. }
  222200. void MouseCursor::showInAllWindows() const
  222201. {
  222202. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  222203. showInWindow (ComponentPeer::getPeer (i));
  222204. }
  222205. const Image juce_createIconForFile (const File& file)
  222206. {
  222207. return Image::null;
  222208. }
  222209. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  222210. {
  222211. return createSoftwareImage (format, width, height, clearImage);
  222212. }
  222213. #if JUCE_OPENGL
  222214. class WindowedGLContext : public OpenGLContext
  222215. {
  222216. public:
  222217. WindowedGLContext (Component* const component,
  222218. const OpenGLPixelFormat& pixelFormat_,
  222219. GLXContext sharedContext)
  222220. : renderContext (0),
  222221. embeddedWindow (0),
  222222. pixelFormat (pixelFormat_),
  222223. swapInterval (0)
  222224. {
  222225. jassert (component != 0);
  222226. LinuxComponentPeer* const peer = dynamic_cast <LinuxComponentPeer*> (component->getTopLevelComponent()->getPeer());
  222227. if (peer == 0)
  222228. return;
  222229. ScopedXLock xlock;
  222230. XSync (display, False);
  222231. GLint attribs [64];
  222232. int n = 0;
  222233. attribs[n++] = GLX_RGBA;
  222234. attribs[n++] = GLX_DOUBLEBUFFER;
  222235. attribs[n++] = GLX_RED_SIZE;
  222236. attribs[n++] = pixelFormat.redBits;
  222237. attribs[n++] = GLX_GREEN_SIZE;
  222238. attribs[n++] = pixelFormat.greenBits;
  222239. attribs[n++] = GLX_BLUE_SIZE;
  222240. attribs[n++] = pixelFormat.blueBits;
  222241. attribs[n++] = GLX_ALPHA_SIZE;
  222242. attribs[n++] = pixelFormat.alphaBits;
  222243. attribs[n++] = GLX_DEPTH_SIZE;
  222244. attribs[n++] = pixelFormat.depthBufferBits;
  222245. attribs[n++] = GLX_STENCIL_SIZE;
  222246. attribs[n++] = pixelFormat.stencilBufferBits;
  222247. attribs[n++] = GLX_ACCUM_RED_SIZE;
  222248. attribs[n++] = pixelFormat.accumulationBufferRedBits;
  222249. attribs[n++] = GLX_ACCUM_GREEN_SIZE;
  222250. attribs[n++] = pixelFormat.accumulationBufferGreenBits;
  222251. attribs[n++] = GLX_ACCUM_BLUE_SIZE;
  222252. attribs[n++] = pixelFormat.accumulationBufferBlueBits;
  222253. attribs[n++] = GLX_ACCUM_ALPHA_SIZE;
  222254. attribs[n++] = pixelFormat.accumulationBufferAlphaBits;
  222255. // xxx not sure how to do fullSceneAntiAliasingNumSamples on linux..
  222256. attribs[n++] = None;
  222257. XVisualInfo* const bestVisual = glXChooseVisual (display, DefaultScreen (display), attribs);
  222258. if (bestVisual == 0)
  222259. return;
  222260. renderContext = glXCreateContext (display, bestVisual, sharedContext, GL_TRUE);
  222261. Window windowH = (Window) peer->getNativeHandle();
  222262. Colormap colourMap = XCreateColormap (display, windowH, bestVisual->visual, AllocNone);
  222263. XSetWindowAttributes swa;
  222264. swa.colormap = colourMap;
  222265. swa.border_pixel = 0;
  222266. swa.event_mask = ExposureMask | StructureNotifyMask;
  222267. embeddedWindow = XCreateWindow (display, windowH,
  222268. 0, 0, 1, 1, 0,
  222269. bestVisual->depth,
  222270. InputOutput,
  222271. bestVisual->visual,
  222272. CWBorderPixel | CWColormap | CWEventMask,
  222273. &swa);
  222274. XSaveContext (display, (XID) embeddedWindow, windowHandleXContext, (XPointer) peer);
  222275. XMapWindow (display, embeddedWindow);
  222276. XFreeColormap (display, colourMap);
  222277. XFree (bestVisual);
  222278. XSync (display, False);
  222279. }
  222280. ~WindowedGLContext()
  222281. {
  222282. ScopedXLock xlock;
  222283. deleteContext();
  222284. XUnmapWindow (display, embeddedWindow);
  222285. XDestroyWindow (display, embeddedWindow);
  222286. }
  222287. void deleteContext()
  222288. {
  222289. makeInactive();
  222290. if (renderContext != 0)
  222291. {
  222292. ScopedXLock xlock;
  222293. glXDestroyContext (display, renderContext);
  222294. renderContext = 0;
  222295. }
  222296. }
  222297. bool makeActive() const throw()
  222298. {
  222299. jassert (renderContext != 0);
  222300. ScopedXLock xlock;
  222301. return glXMakeCurrent (display, embeddedWindow, renderContext)
  222302. && XSync (display, False);
  222303. }
  222304. bool makeInactive() const throw()
  222305. {
  222306. ScopedXLock xlock;
  222307. return (! isActive()) || glXMakeCurrent (display, None, 0);
  222308. }
  222309. bool isActive() const throw()
  222310. {
  222311. ScopedXLock xlock;
  222312. return glXGetCurrentContext() == renderContext;
  222313. }
  222314. const OpenGLPixelFormat getPixelFormat() const
  222315. {
  222316. return pixelFormat;
  222317. }
  222318. void* getRawContext() const throw()
  222319. {
  222320. return renderContext;
  222321. }
  222322. void updateWindowPosition (int x, int y, int w, int h, int)
  222323. {
  222324. ScopedXLock xlock;
  222325. XMoveResizeWindow (display, embeddedWindow,
  222326. x, y, jmax (1, w), jmax (1, h));
  222327. }
  222328. void swapBuffers()
  222329. {
  222330. ScopedXLock xlock;
  222331. glXSwapBuffers (display, embeddedWindow);
  222332. }
  222333. bool setSwapInterval (const int numFramesPerSwap)
  222334. {
  222335. static PFNGLXSWAPINTERVALSGIPROC GLXSwapIntervalSGI = (PFNGLXSWAPINTERVALSGIPROC) glXGetProcAddress ((const GLubyte*) "glXSwapIntervalSGI");
  222336. if (GLXSwapIntervalSGI != 0)
  222337. {
  222338. swapInterval = numFramesPerSwap;
  222339. GLXSwapIntervalSGI (numFramesPerSwap);
  222340. return true;
  222341. }
  222342. return false;
  222343. }
  222344. int getSwapInterval() const
  222345. {
  222346. return swapInterval;
  222347. }
  222348. void repaint()
  222349. {
  222350. }
  222351. juce_UseDebuggingNewOperator
  222352. GLXContext renderContext;
  222353. private:
  222354. Window embeddedWindow;
  222355. OpenGLPixelFormat pixelFormat;
  222356. int swapInterval;
  222357. WindowedGLContext (const WindowedGLContext&);
  222358. WindowedGLContext& operator= (const WindowedGLContext&);
  222359. };
  222360. OpenGLContext* OpenGLComponent::createContext()
  222361. {
  222362. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  222363. contextToShareListsWith != 0 ? (GLXContext) contextToShareListsWith->getRawContext() : 0));
  222364. return (c->renderContext != 0) ? c.release() : 0;
  222365. }
  222366. void juce_glViewport (const int w, const int h)
  222367. {
  222368. glViewport (0, 0, w, h);
  222369. }
  222370. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  222371. OwnedArray <OpenGLPixelFormat>& results)
  222372. {
  222373. results.add (new OpenGLPixelFormat()); // xxx
  222374. }
  222375. #endif
  222376. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  222377. {
  222378. jassertfalse; // not implemented!
  222379. return false;
  222380. }
  222381. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  222382. {
  222383. jassertfalse; // not implemented!
  222384. return false;
  222385. }
  222386. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  222387. {
  222388. if (! isOnDesktop ())
  222389. addToDesktop (0);
  222390. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  222391. if (wp != 0)
  222392. {
  222393. wp->setTaskBarIcon (newImage);
  222394. setVisible (true);
  222395. toFront (false);
  222396. repaint();
  222397. }
  222398. }
  222399. void SystemTrayIconComponent::paint (Graphics& g)
  222400. {
  222401. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  222402. if (wp != 0)
  222403. {
  222404. g.drawImageWithin (wp->getTaskbarIcon(), 0, 0, getWidth(), getHeight(),
  222405. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  222406. false);
  222407. }
  222408. }
  222409. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  222410. {
  222411. // xxx not yet implemented!
  222412. }
  222413. void PlatformUtilities::beep()
  222414. {
  222415. std::cout << "\a" << std::flush;
  222416. }
  222417. bool AlertWindow::showNativeDialogBox (const String& title,
  222418. const String& bodyText,
  222419. bool isOkCancel)
  222420. {
  222421. // use a non-native one for the time being..
  222422. if (isOkCancel)
  222423. return AlertWindow::showOkCancelBox (AlertWindow::NoIcon, title, bodyText);
  222424. else
  222425. AlertWindow::showMessageBox (AlertWindow::NoIcon, title, bodyText);
  222426. return true;
  222427. }
  222428. const int KeyPress::spaceKey = XK_space & 0xff;
  222429. const int KeyPress::returnKey = XK_Return & 0xff;
  222430. const int KeyPress::escapeKey = XK_Escape & 0xff;
  222431. const int KeyPress::backspaceKey = XK_BackSpace & 0xff;
  222432. const int KeyPress::leftKey = (XK_Left & 0xff) | Keys::extendedKeyModifier;
  222433. const int KeyPress::rightKey = (XK_Right & 0xff) | Keys::extendedKeyModifier;
  222434. const int KeyPress::upKey = (XK_Up & 0xff) | Keys::extendedKeyModifier;
  222435. const int KeyPress::downKey = (XK_Down & 0xff) | Keys::extendedKeyModifier;
  222436. const int KeyPress::pageUpKey = (XK_Page_Up & 0xff) | Keys::extendedKeyModifier;
  222437. const int KeyPress::pageDownKey = (XK_Page_Down & 0xff) | Keys::extendedKeyModifier;
  222438. const int KeyPress::endKey = (XK_End & 0xff) | Keys::extendedKeyModifier;
  222439. const int KeyPress::homeKey = (XK_Home & 0xff) | Keys::extendedKeyModifier;
  222440. const int KeyPress::insertKey = (XK_Insert & 0xff) | Keys::extendedKeyModifier;
  222441. const int KeyPress::deleteKey = (XK_Delete & 0xff) | Keys::extendedKeyModifier;
  222442. const int KeyPress::tabKey = XK_Tab & 0xff;
  222443. const int KeyPress::F1Key = (XK_F1 & 0xff) | Keys::extendedKeyModifier;
  222444. const int KeyPress::F2Key = (XK_F2 & 0xff) | Keys::extendedKeyModifier;
  222445. const int KeyPress::F3Key = (XK_F3 & 0xff) | Keys::extendedKeyModifier;
  222446. const int KeyPress::F4Key = (XK_F4 & 0xff) | Keys::extendedKeyModifier;
  222447. const int KeyPress::F5Key = (XK_F5 & 0xff) | Keys::extendedKeyModifier;
  222448. const int KeyPress::F6Key = (XK_F6 & 0xff) | Keys::extendedKeyModifier;
  222449. const int KeyPress::F7Key = (XK_F7 & 0xff) | Keys::extendedKeyModifier;
  222450. const int KeyPress::F8Key = (XK_F8 & 0xff) | Keys::extendedKeyModifier;
  222451. const int KeyPress::F9Key = (XK_F9 & 0xff) | Keys::extendedKeyModifier;
  222452. const int KeyPress::F10Key = (XK_F10 & 0xff) | Keys::extendedKeyModifier;
  222453. const int KeyPress::F11Key = (XK_F11 & 0xff) | Keys::extendedKeyModifier;
  222454. const int KeyPress::F12Key = (XK_F12 & 0xff) | Keys::extendedKeyModifier;
  222455. const int KeyPress::F13Key = (XK_F13 & 0xff) | Keys::extendedKeyModifier;
  222456. const int KeyPress::F14Key = (XK_F14 & 0xff) | Keys::extendedKeyModifier;
  222457. const int KeyPress::F15Key = (XK_F15 & 0xff) | Keys::extendedKeyModifier;
  222458. const int KeyPress::F16Key = (XK_F16 & 0xff) | Keys::extendedKeyModifier;
  222459. const int KeyPress::numberPad0 = (XK_KP_0 & 0xff) | Keys::extendedKeyModifier;
  222460. const int KeyPress::numberPad1 = (XK_KP_1 & 0xff) | Keys::extendedKeyModifier;
  222461. const int KeyPress::numberPad2 = (XK_KP_2 & 0xff) | Keys::extendedKeyModifier;
  222462. const int KeyPress::numberPad3 = (XK_KP_3 & 0xff) | Keys::extendedKeyModifier;
  222463. const int KeyPress::numberPad4 = (XK_KP_4 & 0xff) | Keys::extendedKeyModifier;
  222464. const int KeyPress::numberPad5 = (XK_KP_5 & 0xff) | Keys::extendedKeyModifier;
  222465. const int KeyPress::numberPad6 = (XK_KP_6 & 0xff) | Keys::extendedKeyModifier;
  222466. const int KeyPress::numberPad7 = (XK_KP_7 & 0xff)| Keys::extendedKeyModifier;
  222467. const int KeyPress::numberPad8 = (XK_KP_8 & 0xff)| Keys::extendedKeyModifier;
  222468. const int KeyPress::numberPad9 = (XK_KP_9 & 0xff)| Keys::extendedKeyModifier;
  222469. const int KeyPress::numberPadAdd = (XK_KP_Add & 0xff)| Keys::extendedKeyModifier;
  222470. const int KeyPress::numberPadSubtract = (XK_KP_Subtract & 0xff)| Keys::extendedKeyModifier;
  222471. const int KeyPress::numberPadMultiply = (XK_KP_Multiply & 0xff)| Keys::extendedKeyModifier;
  222472. const int KeyPress::numberPadDivide = (XK_KP_Divide & 0xff)| Keys::extendedKeyModifier;
  222473. const int KeyPress::numberPadSeparator = (XK_KP_Separator & 0xff)| Keys::extendedKeyModifier;
  222474. const int KeyPress::numberPadDecimalPoint = (XK_KP_Decimal & 0xff)| Keys::extendedKeyModifier;
  222475. const int KeyPress::numberPadEquals = (XK_KP_Equal & 0xff)| Keys::extendedKeyModifier;
  222476. const int KeyPress::numberPadDelete = (XK_KP_Delete & 0xff)| Keys::extendedKeyModifier;
  222477. const int KeyPress::playKey = (0xffeeff00) | Keys::extendedKeyModifier;
  222478. const int KeyPress::stopKey = (0xffeeff01) | Keys::extendedKeyModifier;
  222479. const int KeyPress::fastForwardKey = (0xffeeff02) | Keys::extendedKeyModifier;
  222480. const int KeyPress::rewindKey = (0xffeeff03) | Keys::extendedKeyModifier;
  222481. #endif
  222482. /*** End of inlined file: juce_linux_Windowing.cpp ***/
  222483. /*** Start of inlined file: juce_linux_Audio.cpp ***/
  222484. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  222485. // compiled on its own).
  222486. #if JUCE_INCLUDED_FILE && JUCE_ALSA
  222487. namespace
  222488. {
  222489. void getDeviceSampleRates (snd_pcm_t* handle, Array <int>& rates)
  222490. {
  222491. const int ratesToTry[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  222492. snd_pcm_hw_params_t* hwParams;
  222493. snd_pcm_hw_params_alloca (&hwParams);
  222494. for (int i = 0; ratesToTry[i] != 0; ++i)
  222495. {
  222496. if (snd_pcm_hw_params_any (handle, hwParams) >= 0
  222497. && snd_pcm_hw_params_test_rate (handle, hwParams, ratesToTry[i], 0) == 0)
  222498. {
  222499. rates.addIfNotAlreadyThere (ratesToTry[i]);
  222500. }
  222501. }
  222502. }
  222503. void getDeviceNumChannels (snd_pcm_t* handle, unsigned int* minChans, unsigned int* maxChans)
  222504. {
  222505. snd_pcm_hw_params_t *params;
  222506. snd_pcm_hw_params_alloca (&params);
  222507. if (snd_pcm_hw_params_any (handle, params) >= 0)
  222508. {
  222509. snd_pcm_hw_params_get_channels_min (params, minChans);
  222510. snd_pcm_hw_params_get_channels_max (params, maxChans);
  222511. }
  222512. }
  222513. void getDeviceProperties (const String& deviceID,
  222514. unsigned int& minChansOut,
  222515. unsigned int& maxChansOut,
  222516. unsigned int& minChansIn,
  222517. unsigned int& maxChansIn,
  222518. Array <int>& rates)
  222519. {
  222520. if (deviceID.isEmpty())
  222521. return;
  222522. snd_ctl_t* handle;
  222523. if (snd_ctl_open (&handle, deviceID.upToLastOccurrenceOf (",", false, false).toUTF8(), SND_CTL_NONBLOCK) >= 0)
  222524. {
  222525. snd_pcm_info_t* info;
  222526. snd_pcm_info_alloca (&info);
  222527. snd_pcm_info_set_stream (info, SND_PCM_STREAM_PLAYBACK);
  222528. snd_pcm_info_set_device (info, deviceID.fromLastOccurrenceOf (",", false, false).getIntValue());
  222529. snd_pcm_info_set_subdevice (info, 0);
  222530. if (snd_ctl_pcm_info (handle, info) >= 0)
  222531. {
  222532. snd_pcm_t* pcmHandle;
  222533. if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_PLAYBACK, SND_PCM_ASYNC | SND_PCM_NONBLOCK) >= 0)
  222534. {
  222535. getDeviceNumChannels (pcmHandle, &minChansOut, &maxChansOut);
  222536. getDeviceSampleRates (pcmHandle, rates);
  222537. snd_pcm_close (pcmHandle);
  222538. }
  222539. }
  222540. snd_pcm_info_set_stream (info, SND_PCM_STREAM_CAPTURE);
  222541. if (snd_ctl_pcm_info (handle, info) >= 0)
  222542. {
  222543. snd_pcm_t* pcmHandle;
  222544. if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_CAPTURE, SND_PCM_ASYNC | SND_PCM_NONBLOCK) >= 0)
  222545. {
  222546. getDeviceNumChannels (pcmHandle, &minChansIn, &maxChansIn);
  222547. if (rates.size() == 0)
  222548. getDeviceSampleRates (pcmHandle, rates);
  222549. snd_pcm_close (pcmHandle);
  222550. }
  222551. }
  222552. snd_ctl_close (handle);
  222553. }
  222554. }
  222555. }
  222556. class ALSADevice
  222557. {
  222558. public:
  222559. ALSADevice (const String& deviceID, bool forInput)
  222560. : handle (0),
  222561. bitDepth (16),
  222562. numChannelsRunning (0),
  222563. latency (0),
  222564. isInput (forInput),
  222565. isInterleaved (true)
  222566. {
  222567. failed (snd_pcm_open (&handle, deviceID.toUTF8(),
  222568. forInput ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK,
  222569. SND_PCM_ASYNC));
  222570. }
  222571. ~ALSADevice()
  222572. {
  222573. if (handle != 0)
  222574. snd_pcm_close (handle);
  222575. }
  222576. bool setParameters (unsigned int sampleRate, int numChannels, int bufferSize)
  222577. {
  222578. if (handle == 0)
  222579. return false;
  222580. snd_pcm_hw_params_t* hwParams;
  222581. snd_pcm_hw_params_alloca (&hwParams);
  222582. if (failed (snd_pcm_hw_params_any (handle, hwParams)))
  222583. return false;
  222584. if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_NONINTERLEAVED) >= 0)
  222585. isInterleaved = false;
  222586. else if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_INTERLEAVED) >= 0)
  222587. isInterleaved = true;
  222588. else
  222589. {
  222590. jassertfalse;
  222591. return false;
  222592. }
  222593. enum { isFloatBit = 1 << 16, isLittleEndianBit = 1 << 17 };
  222594. const int formatsToTry[] = { SND_PCM_FORMAT_FLOAT_LE, 32 | isFloatBit | isLittleEndianBit,
  222595. SND_PCM_FORMAT_FLOAT_BE, 32 | isFloatBit,
  222596. SND_PCM_FORMAT_S32_LE, 32 | isLittleEndianBit,
  222597. SND_PCM_FORMAT_S32_BE, 32,
  222598. SND_PCM_FORMAT_S24_3LE, 24 | isLittleEndianBit,
  222599. SND_PCM_FORMAT_S24_3BE, 24,
  222600. SND_PCM_FORMAT_S16_LE, 16 | isLittleEndianBit,
  222601. SND_PCM_FORMAT_S16_BE, 16 };
  222602. bitDepth = 0;
  222603. for (int i = 0; i < numElementsInArray (formatsToTry); i += 2)
  222604. {
  222605. if (snd_pcm_hw_params_set_format (handle, hwParams, (_snd_pcm_format) formatsToTry [i]) >= 0)
  222606. {
  222607. bitDepth = formatsToTry [i + 1] & 255;
  222608. const bool isFloat = (formatsToTry [i + 1] & isFloatBit) != 0;
  222609. const bool isLittleEndian = (formatsToTry [i + 1] & isLittleEndianBit) != 0;
  222610. converter = createConverter (isInput, bitDepth, isFloat, isLittleEndian, numChannels);
  222611. break;
  222612. }
  222613. }
  222614. if (bitDepth == 0)
  222615. {
  222616. error = "device doesn't support a compatible PCM format";
  222617. DBG ("ALSA error: " + error + "\n");
  222618. return false;
  222619. }
  222620. int dir = 0;
  222621. unsigned int periods = 4;
  222622. snd_pcm_uframes_t samplesPerPeriod = bufferSize;
  222623. if (failed (snd_pcm_hw_params_set_rate_near (handle, hwParams, &sampleRate, 0))
  222624. || failed (snd_pcm_hw_params_set_channels (handle, hwParams, numChannels))
  222625. || failed (snd_pcm_hw_params_set_periods_near (handle, hwParams, &periods, &dir))
  222626. || failed (snd_pcm_hw_params_set_period_size_near (handle, hwParams, &samplesPerPeriod, &dir))
  222627. || failed (snd_pcm_hw_params (handle, hwParams)))
  222628. {
  222629. return false;
  222630. }
  222631. snd_pcm_uframes_t frames = 0;
  222632. if (failed (snd_pcm_hw_params_get_period_size (hwParams, &frames, &dir))
  222633. || failed (snd_pcm_hw_params_get_periods (hwParams, &periods, &dir)))
  222634. latency = 0;
  222635. else
  222636. latency = frames * (periods - 1); // (this is the method JACK uses to guess the latency..)
  222637. snd_pcm_sw_params_t* swParams;
  222638. snd_pcm_sw_params_alloca (&swParams);
  222639. snd_pcm_uframes_t boundary;
  222640. if (failed (snd_pcm_sw_params_current (handle, swParams))
  222641. || failed (snd_pcm_sw_params_get_boundary (swParams, &boundary))
  222642. || failed (snd_pcm_sw_params_set_silence_threshold (handle, swParams, 0))
  222643. || failed (snd_pcm_sw_params_set_silence_size (handle, swParams, boundary))
  222644. || failed (snd_pcm_sw_params_set_start_threshold (handle, swParams, samplesPerPeriod))
  222645. || failed (snd_pcm_sw_params_set_stop_threshold (handle, swParams, boundary))
  222646. || failed (snd_pcm_sw_params (handle, swParams)))
  222647. {
  222648. return false;
  222649. }
  222650. /*
  222651. #if JUCE_DEBUG
  222652. // enable this to dump the config of the devices that get opened
  222653. snd_output_t* out;
  222654. snd_output_stdio_attach (&out, stderr, 0);
  222655. snd_pcm_hw_params_dump (hwParams, out);
  222656. snd_pcm_sw_params_dump (swParams, out);
  222657. #endif
  222658. */
  222659. numChannelsRunning = numChannels;
  222660. return true;
  222661. }
  222662. bool writeToOutputDevice (AudioSampleBuffer& outputChannelBuffer, const int numSamples)
  222663. {
  222664. jassert (numChannelsRunning <= outputChannelBuffer.getNumChannels());
  222665. float** const data = outputChannelBuffer.getArrayOfChannels();
  222666. snd_pcm_sframes_t numDone = 0;
  222667. if (isInterleaved)
  222668. {
  222669. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  222670. for (int i = 0; i < numChannelsRunning; ++i)
  222671. converter->convertSamples (scratch.getData(), i, data[i], 0, numSamples);
  222672. numDone = snd_pcm_writei (handle, scratch.getData(), numSamples);
  222673. }
  222674. else
  222675. {
  222676. for (int i = 0; i < numChannelsRunning; ++i)
  222677. converter->convertSamples (data[i], data[i], numSamples);
  222678. numDone = snd_pcm_writen (handle, (void**) data, numSamples);
  222679. }
  222680. if (failed (numDone))
  222681. {
  222682. if (numDone == -EPIPE)
  222683. {
  222684. if (failed (snd_pcm_prepare (handle)))
  222685. return false;
  222686. }
  222687. else if (numDone != -ESTRPIPE)
  222688. return false;
  222689. }
  222690. return true;
  222691. }
  222692. bool readFromInputDevice (AudioSampleBuffer& inputChannelBuffer, const int numSamples)
  222693. {
  222694. jassert (numChannelsRunning <= inputChannelBuffer.getNumChannels());
  222695. float** const data = inputChannelBuffer.getArrayOfChannels();
  222696. if (isInterleaved)
  222697. {
  222698. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  222699. scratch.fillWith (0); // (not clearing this data causes warnings in valgrind)
  222700. snd_pcm_sframes_t num = snd_pcm_readi (handle, scratch.getData(), numSamples);
  222701. if (failed (num))
  222702. {
  222703. if (num == -EPIPE)
  222704. {
  222705. if (failed (snd_pcm_prepare (handle)))
  222706. return false;
  222707. }
  222708. else if (num != -ESTRPIPE)
  222709. return false;
  222710. }
  222711. for (int i = 0; i < numChannelsRunning; ++i)
  222712. converter->convertSamples (data[i], 0, scratch.getData(), i, numSamples);
  222713. }
  222714. else
  222715. {
  222716. snd_pcm_sframes_t num = snd_pcm_readn (handle, (void**) data, numSamples);
  222717. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  222718. return false;
  222719. for (int i = 0; i < numChannelsRunning; ++i)
  222720. converter->convertSamples (data[i], data[i], numSamples);
  222721. }
  222722. return true;
  222723. }
  222724. juce_UseDebuggingNewOperator
  222725. snd_pcm_t* handle;
  222726. String error;
  222727. int bitDepth, numChannelsRunning, latency;
  222728. private:
  222729. const bool isInput;
  222730. bool isInterleaved;
  222731. MemoryBlock scratch;
  222732. ScopedPointer<AudioData::Converter> converter;
  222733. template <class SampleType>
  222734. struct ConverterHelper
  222735. {
  222736. static AudioData::Converter* createConverter (const bool forInput, const bool isLittleEndian, const int numInterleavedChannels)
  222737. {
  222738. if (forInput)
  222739. {
  222740. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> DestType;
  222741. if (isLittleEndian)
  222742. return new AudioData::ConverterInstance <AudioData::Pointer <SampleType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>, DestType> (numInterleavedChannels, 1);
  222743. else
  222744. return new AudioData::ConverterInstance <AudioData::Pointer <SampleType, AudioData::BigEndian, AudioData::Interleaved, AudioData::Const>, DestType> (numInterleavedChannels, 1);
  222745. }
  222746. else
  222747. {
  222748. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> SourceType;
  222749. if (isLittleEndian)
  222750. return new AudioData::ConverterInstance <SourceType, AudioData::Pointer <SampleType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> > (1, numInterleavedChannels);
  222751. else
  222752. return new AudioData::ConverterInstance <SourceType, AudioData::Pointer <SampleType, AudioData::BigEndian, AudioData::Interleaved, AudioData::NonConst> > (1, numInterleavedChannels);
  222753. }
  222754. }
  222755. };
  222756. static AudioData::Converter* createConverter (const bool forInput, const int bitDepth, const bool isFloat, const bool isLittleEndian, const int numInterleavedChannels)
  222757. {
  222758. switch (bitDepth)
  222759. {
  222760. case 16: return ConverterHelper <AudioData::Int16>::createConverter (forInput, isLittleEndian, numInterleavedChannels);
  222761. case 24: return ConverterHelper <AudioData::Int24>::createConverter (forInput, isLittleEndian, numInterleavedChannels);
  222762. case 32: return isFloat ? ConverterHelper <AudioData::Float32>::createConverter (forInput, isLittleEndian, numInterleavedChannels)
  222763. : ConverterHelper <AudioData::Int32>::createConverter (forInput, isLittleEndian, numInterleavedChannels);
  222764. default: jassertfalse; break; // unsupported format!
  222765. }
  222766. return 0;
  222767. }
  222768. bool failed (const int errorNum)
  222769. {
  222770. if (errorNum >= 0)
  222771. return false;
  222772. error = snd_strerror (errorNum);
  222773. DBG ("ALSA error: " + error + "\n");
  222774. return true;
  222775. }
  222776. };
  222777. class ALSAThread : public Thread
  222778. {
  222779. public:
  222780. ALSAThread (const String& inputId_,
  222781. const String& outputId_)
  222782. : Thread ("Juce ALSA"),
  222783. sampleRate (0),
  222784. bufferSize (0),
  222785. outputLatency (0),
  222786. inputLatency (0),
  222787. callback (0),
  222788. inputId (inputId_),
  222789. outputId (outputId_),
  222790. numCallbacks (0),
  222791. inputChannelBuffer (1, 1),
  222792. outputChannelBuffer (1, 1)
  222793. {
  222794. initialiseRatesAndChannels();
  222795. }
  222796. ~ALSAThread()
  222797. {
  222798. close();
  222799. }
  222800. void open (BigInteger inputChannels,
  222801. BigInteger outputChannels,
  222802. const double sampleRate_,
  222803. const int bufferSize_)
  222804. {
  222805. close();
  222806. error = String::empty;
  222807. sampleRate = sampleRate_;
  222808. bufferSize = bufferSize_;
  222809. inputChannelBuffer.setSize (jmax ((int) minChansIn, inputChannels.getHighestBit()) + 1, bufferSize);
  222810. inputChannelBuffer.clear();
  222811. inputChannelDataForCallback.clear();
  222812. currentInputChans.clear();
  222813. if (inputChannels.getHighestBit() >= 0)
  222814. {
  222815. for (int i = 0; i <= jmax (inputChannels.getHighestBit(), (int) minChansIn); ++i)
  222816. {
  222817. if (inputChannels[i])
  222818. {
  222819. inputChannelDataForCallback.add (inputChannelBuffer.getSampleData (i));
  222820. currentInputChans.setBit (i);
  222821. }
  222822. }
  222823. }
  222824. outputChannelBuffer.setSize (jmax ((int) minChansOut, outputChannels.getHighestBit()) + 1, bufferSize);
  222825. outputChannelBuffer.clear();
  222826. outputChannelDataForCallback.clear();
  222827. currentOutputChans.clear();
  222828. if (outputChannels.getHighestBit() >= 0)
  222829. {
  222830. for (int i = 0; i <= jmax (outputChannels.getHighestBit(), (int) minChansOut); ++i)
  222831. {
  222832. if (outputChannels[i])
  222833. {
  222834. outputChannelDataForCallback.add (outputChannelBuffer.getSampleData (i));
  222835. currentOutputChans.setBit (i);
  222836. }
  222837. }
  222838. }
  222839. if (outputChannelDataForCallback.size() > 0 && outputId.isNotEmpty())
  222840. {
  222841. outputDevice = new ALSADevice (outputId, false);
  222842. if (outputDevice->error.isNotEmpty())
  222843. {
  222844. error = outputDevice->error;
  222845. outputDevice = 0;
  222846. return;
  222847. }
  222848. currentOutputChans.setRange (0, minChansOut, true);
  222849. if (! outputDevice->setParameters ((unsigned int) sampleRate,
  222850. jlimit ((int) minChansOut, (int) maxChansOut, currentOutputChans.getHighestBit() + 1),
  222851. bufferSize))
  222852. {
  222853. error = outputDevice->error;
  222854. outputDevice = 0;
  222855. return;
  222856. }
  222857. outputLatency = outputDevice->latency;
  222858. }
  222859. if (inputChannelDataForCallback.size() > 0 && inputId.isNotEmpty())
  222860. {
  222861. inputDevice = new ALSADevice (inputId, true);
  222862. if (inputDevice->error.isNotEmpty())
  222863. {
  222864. error = inputDevice->error;
  222865. inputDevice = 0;
  222866. return;
  222867. }
  222868. currentInputChans.setRange (0, minChansIn, true);
  222869. if (! inputDevice->setParameters ((unsigned int) sampleRate,
  222870. jlimit ((int) minChansIn, (int) maxChansIn, currentInputChans.getHighestBit() + 1),
  222871. bufferSize))
  222872. {
  222873. error = inputDevice->error;
  222874. inputDevice = 0;
  222875. return;
  222876. }
  222877. inputLatency = inputDevice->latency;
  222878. }
  222879. if (outputDevice == 0 && inputDevice == 0)
  222880. {
  222881. error = "no channels";
  222882. return;
  222883. }
  222884. if (outputDevice != 0 && inputDevice != 0)
  222885. {
  222886. snd_pcm_link (outputDevice->handle, inputDevice->handle);
  222887. }
  222888. if (inputDevice != 0 && failed (snd_pcm_prepare (inputDevice->handle)))
  222889. return;
  222890. if (outputDevice != 0 && failed (snd_pcm_prepare (outputDevice->handle)))
  222891. return;
  222892. startThread (9);
  222893. int count = 1000;
  222894. while (numCallbacks == 0)
  222895. {
  222896. sleep (5);
  222897. if (--count < 0 || ! isThreadRunning())
  222898. {
  222899. error = "device didn't start";
  222900. break;
  222901. }
  222902. }
  222903. }
  222904. void close()
  222905. {
  222906. stopThread (6000);
  222907. inputDevice = 0;
  222908. outputDevice = 0;
  222909. inputChannelBuffer.setSize (1, 1);
  222910. outputChannelBuffer.setSize (1, 1);
  222911. numCallbacks = 0;
  222912. }
  222913. void setCallback (AudioIODeviceCallback* const newCallback) throw()
  222914. {
  222915. const ScopedLock sl (callbackLock);
  222916. callback = newCallback;
  222917. }
  222918. void run()
  222919. {
  222920. while (! threadShouldExit())
  222921. {
  222922. if (inputDevice != 0)
  222923. {
  222924. if (! inputDevice->readFromInputDevice (inputChannelBuffer, bufferSize))
  222925. {
  222926. DBG ("ALSA: read failure");
  222927. break;
  222928. }
  222929. }
  222930. if (threadShouldExit())
  222931. break;
  222932. {
  222933. const ScopedLock sl (callbackLock);
  222934. ++numCallbacks;
  222935. if (callback != 0)
  222936. {
  222937. callback->audioDeviceIOCallback ((const float**) inputChannelDataForCallback.getRawDataPointer(),
  222938. inputChannelDataForCallback.size(),
  222939. outputChannelDataForCallback.getRawDataPointer(),
  222940. outputChannelDataForCallback.size(),
  222941. bufferSize);
  222942. }
  222943. else
  222944. {
  222945. for (int i = 0; i < outputChannelDataForCallback.size(); ++i)
  222946. zeromem (outputChannelDataForCallback[i], sizeof (float) * bufferSize);
  222947. }
  222948. }
  222949. if (outputDevice != 0)
  222950. {
  222951. failed (snd_pcm_wait (outputDevice->handle, 2000));
  222952. if (threadShouldExit())
  222953. break;
  222954. failed (snd_pcm_avail_update (outputDevice->handle));
  222955. if (! outputDevice->writeToOutputDevice (outputChannelBuffer, bufferSize))
  222956. {
  222957. DBG ("ALSA: write failure");
  222958. break;
  222959. }
  222960. }
  222961. }
  222962. }
  222963. int getBitDepth() const throw()
  222964. {
  222965. if (outputDevice != 0)
  222966. return outputDevice->bitDepth;
  222967. if (inputDevice != 0)
  222968. return inputDevice->bitDepth;
  222969. return 16;
  222970. }
  222971. juce_UseDebuggingNewOperator
  222972. String error;
  222973. double sampleRate;
  222974. int bufferSize, outputLatency, inputLatency;
  222975. BigInteger currentInputChans, currentOutputChans;
  222976. Array <int> sampleRates;
  222977. StringArray channelNamesOut, channelNamesIn;
  222978. AudioIODeviceCallback* callback;
  222979. private:
  222980. const String inputId, outputId;
  222981. ScopedPointer<ALSADevice> outputDevice, inputDevice;
  222982. int numCallbacks;
  222983. CriticalSection callbackLock;
  222984. AudioSampleBuffer inputChannelBuffer, outputChannelBuffer;
  222985. Array<float*> inputChannelDataForCallback, outputChannelDataForCallback;
  222986. unsigned int minChansOut, maxChansOut;
  222987. unsigned int minChansIn, maxChansIn;
  222988. bool failed (const int errorNum)
  222989. {
  222990. if (errorNum >= 0)
  222991. return false;
  222992. error = snd_strerror (errorNum);
  222993. DBG ("ALSA error: " + error + "\n");
  222994. return true;
  222995. }
  222996. void initialiseRatesAndChannels()
  222997. {
  222998. sampleRates.clear();
  222999. channelNamesOut.clear();
  223000. channelNamesIn.clear();
  223001. minChansOut = 0;
  223002. maxChansOut = 0;
  223003. minChansIn = 0;
  223004. maxChansIn = 0;
  223005. unsigned int dummy = 0;
  223006. getDeviceProperties (inputId, dummy, dummy, minChansIn, maxChansIn, sampleRates);
  223007. getDeviceProperties (outputId, minChansOut, maxChansOut, dummy, dummy, sampleRates);
  223008. unsigned int i;
  223009. for (i = 0; i < maxChansOut; ++i)
  223010. channelNamesOut.add ("channel " + String ((int) i + 1));
  223011. for (i = 0; i < maxChansIn; ++i)
  223012. channelNamesIn.add ("channel " + String ((int) i + 1));
  223013. }
  223014. };
  223015. class ALSAAudioIODevice : public AudioIODevice
  223016. {
  223017. public:
  223018. ALSAAudioIODevice (const String& deviceName,
  223019. const String& inputId_,
  223020. const String& outputId_)
  223021. : AudioIODevice (deviceName, "ALSA"),
  223022. inputId (inputId_),
  223023. outputId (outputId_),
  223024. isOpen_ (false),
  223025. isStarted (false),
  223026. internal (inputId_, outputId_)
  223027. {
  223028. }
  223029. ~ALSAAudioIODevice()
  223030. {
  223031. }
  223032. const StringArray getOutputChannelNames() { return internal.channelNamesOut; }
  223033. const StringArray getInputChannelNames() { return internal.channelNamesIn; }
  223034. int getNumSampleRates() { return internal.sampleRates.size(); }
  223035. double getSampleRate (int index) { return internal.sampleRates [index]; }
  223036. int getDefaultBufferSize() { return 512; }
  223037. int getNumBufferSizesAvailable() { return 50; }
  223038. int getBufferSizeSamples (int index)
  223039. {
  223040. int n = 16;
  223041. for (int i = 0; i < index; ++i)
  223042. n += n < 64 ? 16
  223043. : (n < 512 ? 32
  223044. : (n < 1024 ? 64
  223045. : (n < 2048 ? 128 : 256)));
  223046. return n;
  223047. }
  223048. const String open (const BigInteger& inputChannels,
  223049. const BigInteger& outputChannels,
  223050. double sampleRate,
  223051. int bufferSizeSamples)
  223052. {
  223053. close();
  223054. if (bufferSizeSamples <= 0)
  223055. bufferSizeSamples = getDefaultBufferSize();
  223056. if (sampleRate <= 0)
  223057. {
  223058. for (int i = 0; i < getNumSampleRates(); ++i)
  223059. {
  223060. if (getSampleRate (i) >= 44100)
  223061. {
  223062. sampleRate = getSampleRate (i);
  223063. break;
  223064. }
  223065. }
  223066. }
  223067. internal.open (inputChannels, outputChannels,
  223068. sampleRate, bufferSizeSamples);
  223069. isOpen_ = internal.error.isEmpty();
  223070. return internal.error;
  223071. }
  223072. void close()
  223073. {
  223074. stop();
  223075. internal.close();
  223076. isOpen_ = false;
  223077. }
  223078. bool isOpen() { return isOpen_; }
  223079. bool isPlaying() { return isStarted && internal.error.isEmpty(); }
  223080. const String getLastError() { return internal.error; }
  223081. int getCurrentBufferSizeSamples() { return internal.bufferSize; }
  223082. double getCurrentSampleRate() { return internal.sampleRate; }
  223083. int getCurrentBitDepth() { return internal.getBitDepth(); }
  223084. const BigInteger getActiveOutputChannels() const { return internal.currentOutputChans; }
  223085. const BigInteger getActiveInputChannels() const { return internal.currentInputChans; }
  223086. int getOutputLatencyInSamples() { return internal.outputLatency; }
  223087. int getInputLatencyInSamples() { return internal.inputLatency; }
  223088. void start (AudioIODeviceCallback* callback)
  223089. {
  223090. if (! isOpen_)
  223091. callback = 0;
  223092. if (callback != 0)
  223093. callback->audioDeviceAboutToStart (this);
  223094. internal.setCallback (callback);
  223095. isStarted = (callback != 0);
  223096. }
  223097. void stop()
  223098. {
  223099. AudioIODeviceCallback* const oldCallback = internal.callback;
  223100. start (0);
  223101. if (oldCallback != 0)
  223102. oldCallback->audioDeviceStopped();
  223103. }
  223104. String inputId, outputId;
  223105. private:
  223106. bool isOpen_, isStarted;
  223107. ALSAThread internal;
  223108. };
  223109. class ALSAAudioIODeviceType : public AudioIODeviceType
  223110. {
  223111. public:
  223112. ALSAAudioIODeviceType()
  223113. : AudioIODeviceType ("ALSA"),
  223114. hasScanned (false)
  223115. {
  223116. }
  223117. ~ALSAAudioIODeviceType()
  223118. {
  223119. }
  223120. void scanForDevices()
  223121. {
  223122. if (hasScanned)
  223123. return;
  223124. hasScanned = true;
  223125. inputNames.clear();
  223126. inputIds.clear();
  223127. outputNames.clear();
  223128. outputIds.clear();
  223129. /* void** hints = 0;
  223130. if (snd_device_name_hint (-1, "pcm", &hints) >= 0)
  223131. {
  223132. for (void** hint = hints; *hint != 0; ++hint)
  223133. {
  223134. const String name (getHint (*hint, "NAME"));
  223135. if (name.isNotEmpty())
  223136. {
  223137. const String ioid (getHint (*hint, "IOID"));
  223138. String desc (getHint (*hint, "DESC"));
  223139. if (desc.isEmpty())
  223140. desc = name;
  223141. desc = desc.replaceCharacters ("\n\r", " ");
  223142. DBG ("name: " << name << "\ndesc: " << desc << "\nIO: " << ioid);
  223143. if (ioid.isEmpty() || ioid == "Input")
  223144. {
  223145. inputNames.add (desc);
  223146. inputIds.add (name);
  223147. }
  223148. if (ioid.isEmpty() || ioid == "Output")
  223149. {
  223150. outputNames.add (desc);
  223151. outputIds.add (name);
  223152. }
  223153. }
  223154. }
  223155. snd_device_name_free_hint (hints);
  223156. }
  223157. */
  223158. snd_ctl_t* handle = 0;
  223159. snd_ctl_card_info_t* info = 0;
  223160. snd_ctl_card_info_alloca (&info);
  223161. int cardNum = -1;
  223162. while (outputIds.size() + inputIds.size() <= 32)
  223163. {
  223164. snd_card_next (&cardNum);
  223165. if (cardNum < 0)
  223166. break;
  223167. if (snd_ctl_open (&handle, ("hw:" + String (cardNum)).toUTF8(), SND_CTL_NONBLOCK) >= 0)
  223168. {
  223169. if (snd_ctl_card_info (handle, info) >= 0)
  223170. {
  223171. String cardId (snd_ctl_card_info_get_id (info));
  223172. if (cardId.removeCharacters ("0123456789").isEmpty())
  223173. cardId = String (cardNum);
  223174. int device = -1;
  223175. for (;;)
  223176. {
  223177. if (snd_ctl_pcm_next_device (handle, &device) < 0 || device < 0)
  223178. break;
  223179. String id, name;
  223180. id << "hw:" << cardId << ',' << device;
  223181. bool isInput, isOutput;
  223182. if (testDevice (id, isInput, isOutput))
  223183. {
  223184. name << snd_ctl_card_info_get_name (info);
  223185. if (name.isEmpty())
  223186. name = id;
  223187. if (isInput)
  223188. {
  223189. inputNames.add (name);
  223190. inputIds.add (id);
  223191. }
  223192. if (isOutput)
  223193. {
  223194. outputNames.add (name);
  223195. outputIds.add (id);
  223196. }
  223197. }
  223198. }
  223199. }
  223200. snd_ctl_close (handle);
  223201. }
  223202. }
  223203. inputNames.appendNumbersToDuplicates (false, true);
  223204. outputNames.appendNumbersToDuplicates (false, true);
  223205. }
  223206. const StringArray getDeviceNames (bool wantInputNames) const
  223207. {
  223208. jassert (hasScanned); // need to call scanForDevices() before doing this
  223209. return wantInputNames ? inputNames : outputNames;
  223210. }
  223211. int getDefaultDeviceIndex (bool forInput) const
  223212. {
  223213. jassert (hasScanned); // need to call scanForDevices() before doing this
  223214. return 0;
  223215. }
  223216. bool hasSeparateInputsAndOutputs() const { return true; }
  223217. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  223218. {
  223219. jassert (hasScanned); // need to call scanForDevices() before doing this
  223220. ALSAAudioIODevice* d = dynamic_cast <ALSAAudioIODevice*> (device);
  223221. if (d == 0)
  223222. return -1;
  223223. return asInput ? inputIds.indexOf (d->inputId)
  223224. : outputIds.indexOf (d->outputId);
  223225. }
  223226. AudioIODevice* createDevice (const String& outputDeviceName,
  223227. const String& inputDeviceName)
  223228. {
  223229. jassert (hasScanned); // need to call scanForDevices() before doing this
  223230. const int inputIndex = inputNames.indexOf (inputDeviceName);
  223231. const int outputIndex = outputNames.indexOf (outputDeviceName);
  223232. String deviceName (outputIndex >= 0 ? outputDeviceName
  223233. : inputDeviceName);
  223234. if (inputIndex >= 0 || outputIndex >= 0)
  223235. return new ALSAAudioIODevice (deviceName,
  223236. inputIds [inputIndex],
  223237. outputIds [outputIndex]);
  223238. return 0;
  223239. }
  223240. juce_UseDebuggingNewOperator
  223241. private:
  223242. StringArray inputNames, outputNames, inputIds, outputIds;
  223243. bool hasScanned;
  223244. static bool testDevice (const String& id, bool& isInput, bool& isOutput)
  223245. {
  223246. unsigned int minChansOut = 0, maxChansOut = 0;
  223247. unsigned int minChansIn = 0, maxChansIn = 0;
  223248. Array <int> rates;
  223249. getDeviceProperties (id, minChansOut, maxChansOut, minChansIn, maxChansIn, rates);
  223250. DBG ("ALSA device: " + id
  223251. + " outs=" + String ((int) minChansOut) + "-" + String ((int) maxChansOut)
  223252. + " ins=" + String ((int) minChansIn) + "-" + String ((int) maxChansIn)
  223253. + " rates=" + String (rates.size()));
  223254. isInput = maxChansIn > 0;
  223255. isOutput = maxChansOut > 0;
  223256. return (isInput || isOutput) && rates.size() > 0;
  223257. }
  223258. /*static const String getHint (void* hint, const char* type)
  223259. {
  223260. char* const n = snd_device_name_get_hint (hint, type);
  223261. const String s ((const char*) n);
  223262. free (n);
  223263. return s;
  223264. }*/
  223265. ALSAAudioIODeviceType (const ALSAAudioIODeviceType&);
  223266. ALSAAudioIODeviceType& operator= (const ALSAAudioIODeviceType&);
  223267. };
  223268. AudioIODeviceType* juce_createAudioIODeviceType_ALSA()
  223269. {
  223270. return new ALSAAudioIODeviceType();
  223271. }
  223272. #endif
  223273. /*** End of inlined file: juce_linux_Audio.cpp ***/
  223274. /*** Start of inlined file: juce_linux_JackAudio.cpp ***/
  223275. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  223276. // compiled on its own).
  223277. #ifdef JUCE_INCLUDED_FILE
  223278. #if JUCE_JACK
  223279. static void* juce_libjack_handle = 0;
  223280. void* juce_load_jack_function (const char* const name)
  223281. {
  223282. if (juce_libjack_handle == 0)
  223283. return 0;
  223284. return dlsym (juce_libjack_handle, name);
  223285. }
  223286. #define JUCE_DECL_JACK_FUNCTION(return_type, fn_name, argument_types, arguments) \
  223287. typedef return_type (*fn_name##_ptr_t)argument_types; \
  223288. return_type fn_name argument_types { \
  223289. static fn_name##_ptr_t fn = 0; \
  223290. if (fn == 0) { fn = (fn_name##_ptr_t)juce_load_jack_function(#fn_name); } \
  223291. if (fn) return (*fn)arguments; \
  223292. else return 0; \
  223293. }
  223294. #define JUCE_DECL_VOID_JACK_FUNCTION(fn_name, argument_types, arguments) \
  223295. typedef void (*fn_name##_ptr_t)argument_types; \
  223296. void fn_name argument_types { \
  223297. static fn_name##_ptr_t fn = 0; \
  223298. if (fn == 0) { fn = (fn_name##_ptr_t)juce_load_jack_function(#fn_name); } \
  223299. if (fn) (*fn)arguments; \
  223300. }
  223301. JUCE_DECL_JACK_FUNCTION (jack_client_t*, jack_client_open, (const char* client_name, jack_options_t options, jack_status_t* status), (client_name, options, status));
  223302. JUCE_DECL_JACK_FUNCTION (int, jack_client_close, (jack_client_t *client), (client));
  223303. JUCE_DECL_JACK_FUNCTION (int, jack_activate, (jack_client_t* client), (client));
  223304. JUCE_DECL_JACK_FUNCTION (int, jack_deactivate, (jack_client_t* client), (client));
  223305. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_buffer_size, (jack_client_t* client), (client));
  223306. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_sample_rate, (jack_client_t* client), (client));
  223307. JUCE_DECL_VOID_JACK_FUNCTION (jack_on_shutdown, (jack_client_t* client, void (*function)(void* arg), void* arg), (client, function, arg));
  223308. JUCE_DECL_JACK_FUNCTION (void* , jack_port_get_buffer, (jack_port_t* port, jack_nframes_t nframes), (port, nframes));
  223309. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_port_get_total_latency, (jack_client_t* client, jack_port_t* port), (client, port));
  223310. JUCE_DECL_JACK_FUNCTION (jack_port_t* , jack_port_register, (jack_client_t* client, const char* port_name, const char* port_type, unsigned long flags, unsigned long buffer_size), (client, port_name, port_type, flags, buffer_size));
  223311. JUCE_DECL_VOID_JACK_FUNCTION (jack_set_error_function, (void (*func)(const char*)), (func));
  223312. JUCE_DECL_JACK_FUNCTION (int, jack_set_process_callback, (jack_client_t* client, JackProcessCallback process_callback, void* arg), (client, process_callback, arg));
  223313. JUCE_DECL_JACK_FUNCTION (const char**, jack_get_ports, (jack_client_t* client, const char* port_name_pattern, const char* type_name_pattern, unsigned long flags), (client, port_name_pattern, type_name_pattern, flags));
  223314. JUCE_DECL_JACK_FUNCTION (int, jack_connect, (jack_client_t* client, const char* source_port, const char* destination_port), (client, source_port, destination_port));
  223315. JUCE_DECL_JACK_FUNCTION (const char*, jack_port_name, (const jack_port_t* port), (port));
  223316. JUCE_DECL_JACK_FUNCTION (int, jack_set_port_connect_callback, (jack_client_t* client, JackPortConnectCallback connect_callback, void* arg), (client, connect_callback, arg));
  223317. JUCE_DECL_JACK_FUNCTION (jack_port_t* , jack_port_by_id, (jack_client_t* client, jack_port_id_t port_id), (client, port_id));
  223318. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected, (const jack_port_t* port), (port));
  223319. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected_to, (const jack_port_t* port, const char* port_name), (port, port_name));
  223320. #if JUCE_DEBUG
  223321. #define JACK_LOGGING_ENABLED 1
  223322. #endif
  223323. #if JACK_LOGGING_ENABLED
  223324. namespace
  223325. {
  223326. void jack_Log (const String& s)
  223327. {
  223328. std::cerr << s << std::endl;
  223329. }
  223330. void dumpJackErrorMessage (const jack_status_t status)
  223331. {
  223332. if (status & JackServerFailed || status & JackServerError) jack_Log ("Unable to connect to JACK server");
  223333. if (status & JackVersionError) jack_Log ("Client's protocol version does not match");
  223334. if (status & JackInvalidOption) jack_Log ("The operation contained an invalid or unsupported option");
  223335. if (status & JackNameNotUnique) jack_Log ("The desired client name was not unique");
  223336. if (status & JackNoSuchClient) jack_Log ("Requested client does not exist");
  223337. if (status & JackInitFailure) jack_Log ("Unable to initialize client");
  223338. }
  223339. }
  223340. #else
  223341. #define dumpJackErrorMessage(a) {}
  223342. #define jack_Log(...) {}
  223343. #endif
  223344. #ifndef JUCE_JACK_CLIENT_NAME
  223345. #define JUCE_JACK_CLIENT_NAME "JuceJack"
  223346. #endif
  223347. class JackAudioIODevice : public AudioIODevice
  223348. {
  223349. public:
  223350. JackAudioIODevice (const String& deviceName,
  223351. const String& inputId_,
  223352. const String& outputId_)
  223353. : AudioIODevice (deviceName, "JACK"),
  223354. inputId (inputId_),
  223355. outputId (outputId_),
  223356. isOpen_ (false),
  223357. callback (0),
  223358. totalNumberOfInputChannels (0),
  223359. totalNumberOfOutputChannels (0)
  223360. {
  223361. jassert (deviceName.isNotEmpty());
  223362. jack_status_t status;
  223363. client = JUCE_NAMESPACE::jack_client_open (JUCE_JACK_CLIENT_NAME, JackNoStartServer, &status);
  223364. if (client == 0)
  223365. {
  223366. dumpJackErrorMessage (status);
  223367. }
  223368. else
  223369. {
  223370. JUCE_NAMESPACE::jack_set_error_function (errorCallback);
  223371. // open input ports
  223372. const StringArray inputChannels (getInputChannelNames());
  223373. for (int i = 0; i < inputChannels.size(); i++)
  223374. {
  223375. String inputName;
  223376. inputName << "in_" << ++totalNumberOfInputChannels;
  223377. inputPorts.add (JUCE_NAMESPACE::jack_port_register (client, inputName.toUTF8(),
  223378. JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0));
  223379. }
  223380. // open output ports
  223381. const StringArray outputChannels (getOutputChannelNames());
  223382. for (int i = 0; i < outputChannels.size (); i++)
  223383. {
  223384. String outputName;
  223385. outputName << "out_" << ++totalNumberOfOutputChannels;
  223386. outputPorts.add (JUCE_NAMESPACE::jack_port_register (client, outputName.toUTF8(),
  223387. JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0));
  223388. }
  223389. inChans.calloc (totalNumberOfInputChannels + 2);
  223390. outChans.calloc (totalNumberOfOutputChannels + 2);
  223391. }
  223392. }
  223393. ~JackAudioIODevice()
  223394. {
  223395. close();
  223396. if (client != 0)
  223397. {
  223398. JUCE_NAMESPACE::jack_client_close (client);
  223399. client = 0;
  223400. }
  223401. }
  223402. const StringArray getChannelNames (bool forInput) const
  223403. {
  223404. StringArray names;
  223405. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */
  223406. forInput ? JackPortIsInput : JackPortIsOutput);
  223407. if (ports != 0)
  223408. {
  223409. int j = 0;
  223410. while (ports[j] != 0)
  223411. {
  223412. const String portName (ports [j++]);
  223413. if (portName.upToFirstOccurrenceOf (":", false, false) == getName())
  223414. names.add (portName.fromFirstOccurrenceOf (":", false, false));
  223415. }
  223416. free (ports);
  223417. }
  223418. return names;
  223419. }
  223420. const StringArray getOutputChannelNames() { return getChannelNames (false); }
  223421. const StringArray getInputChannelNames() { return getChannelNames (true); }
  223422. int getNumSampleRates() { return client != 0 ? 1 : 0; }
  223423. double getSampleRate (int index) { return client != 0 ? JUCE_NAMESPACE::jack_get_sample_rate (client) : 0; }
  223424. int getNumBufferSizesAvailable() { return client != 0 ? 1 : 0; }
  223425. int getBufferSizeSamples (int index) { return getDefaultBufferSize(); }
  223426. int getDefaultBufferSize() { return client != 0 ? JUCE_NAMESPACE::jack_get_buffer_size (client) : 0; }
  223427. const String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  223428. double sampleRate, int bufferSizeSamples)
  223429. {
  223430. if (client == 0)
  223431. {
  223432. lastError = "No JACK client running";
  223433. return lastError;
  223434. }
  223435. lastError = String::empty;
  223436. close();
  223437. JUCE_NAMESPACE::jack_set_process_callback (client, processCallback, this);
  223438. JUCE_NAMESPACE::jack_on_shutdown (client, shutdownCallback, this);
  223439. JUCE_NAMESPACE::jack_activate (client);
  223440. isOpen_ = true;
  223441. if (! inputChannels.isZero())
  223442. {
  223443. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsOutput);
  223444. if (ports != 0)
  223445. {
  223446. const int numInputChannels = inputChannels.getHighestBit() + 1;
  223447. for (int i = 0; i < numInputChannels; ++i)
  223448. {
  223449. const String portName (ports[i]);
  223450. if (inputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  223451. {
  223452. int error = JUCE_NAMESPACE::jack_connect (client, ports[i], JUCE_NAMESPACE::jack_port_name ((jack_port_t*) inputPorts[i]));
  223453. if (error != 0)
  223454. jack_Log ("Cannot connect input port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  223455. }
  223456. }
  223457. free (ports);
  223458. }
  223459. }
  223460. if (! outputChannels.isZero())
  223461. {
  223462. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsInput);
  223463. if (ports != 0)
  223464. {
  223465. const int numOutputChannels = outputChannels.getHighestBit() + 1;
  223466. for (int i = 0; i < numOutputChannels; ++i)
  223467. {
  223468. const String portName (ports[i]);
  223469. if (outputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  223470. {
  223471. int error = JUCE_NAMESPACE::jack_connect (client, JUCE_NAMESPACE::jack_port_name ((jack_port_t*) outputPorts[i]), ports[i]);
  223472. if (error != 0)
  223473. jack_Log ("Cannot connect output port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  223474. }
  223475. }
  223476. free (ports);
  223477. }
  223478. }
  223479. return lastError;
  223480. }
  223481. void close()
  223482. {
  223483. stop();
  223484. if (client != 0)
  223485. {
  223486. JUCE_NAMESPACE::jack_deactivate (client);
  223487. JUCE_NAMESPACE::jack_set_process_callback (client, processCallback, 0);
  223488. JUCE_NAMESPACE::jack_on_shutdown (client, shutdownCallback, 0);
  223489. }
  223490. isOpen_ = false;
  223491. }
  223492. void start (AudioIODeviceCallback* newCallback)
  223493. {
  223494. if (isOpen_ && newCallback != callback)
  223495. {
  223496. if (newCallback != 0)
  223497. newCallback->audioDeviceAboutToStart (this);
  223498. AudioIODeviceCallback* const oldCallback = callback;
  223499. {
  223500. const ScopedLock sl (callbackLock);
  223501. callback = newCallback;
  223502. }
  223503. if (oldCallback != 0)
  223504. oldCallback->audioDeviceStopped();
  223505. }
  223506. }
  223507. void stop()
  223508. {
  223509. start (0);
  223510. }
  223511. bool isOpen() { return isOpen_; }
  223512. bool isPlaying() { return callback != 0; }
  223513. int getCurrentBufferSizeSamples() { return getBufferSizeSamples (0); }
  223514. double getCurrentSampleRate() { return getSampleRate (0); }
  223515. int getCurrentBitDepth() { return 32; }
  223516. const String getLastError() { return lastError; }
  223517. const BigInteger getActiveOutputChannels() const
  223518. {
  223519. BigInteger outputBits;
  223520. for (int i = 0; i < outputPorts.size(); i++)
  223521. if (JUCE_NAMESPACE::jack_port_connected ((jack_port_t*) outputPorts [i]))
  223522. outputBits.setBit (i);
  223523. return outputBits;
  223524. }
  223525. const BigInteger getActiveInputChannels() const
  223526. {
  223527. BigInteger inputBits;
  223528. for (int i = 0; i < inputPorts.size(); i++)
  223529. if (JUCE_NAMESPACE::jack_port_connected ((jack_port_t*) inputPorts [i]))
  223530. inputBits.setBit (i);
  223531. return inputBits;
  223532. }
  223533. int getOutputLatencyInSamples()
  223534. {
  223535. int latency = 0;
  223536. for (int i = 0; i < outputPorts.size(); i++)
  223537. latency = jmax (latency, (int) JUCE_NAMESPACE::jack_port_get_total_latency (client, (jack_port_t*) outputPorts [i]));
  223538. return latency;
  223539. }
  223540. int getInputLatencyInSamples()
  223541. {
  223542. int latency = 0;
  223543. for (int i = 0; i < inputPorts.size(); i++)
  223544. latency = jmax (latency, (int) JUCE_NAMESPACE::jack_port_get_total_latency (client, (jack_port_t*) inputPorts [i]));
  223545. return latency;
  223546. }
  223547. String inputId, outputId;
  223548. private:
  223549. void process (const int numSamples)
  223550. {
  223551. int i, numActiveInChans = 0, numActiveOutChans = 0;
  223552. for (i = 0; i < totalNumberOfInputChannels; ++i)
  223553. {
  223554. jack_default_audio_sample_t* in
  223555. = (jack_default_audio_sample_t*) JUCE_NAMESPACE::jack_port_get_buffer ((jack_port_t*) inputPorts.getUnchecked(i), numSamples);
  223556. if (in != 0)
  223557. inChans [numActiveInChans++] = (float*) in;
  223558. }
  223559. for (i = 0; i < totalNumberOfOutputChannels; ++i)
  223560. {
  223561. jack_default_audio_sample_t* out
  223562. = (jack_default_audio_sample_t*) JUCE_NAMESPACE::jack_port_get_buffer ((jack_port_t*) outputPorts.getUnchecked(i), numSamples);
  223563. if (out != 0)
  223564. outChans [numActiveOutChans++] = (float*) out;
  223565. }
  223566. const ScopedLock sl (callbackLock);
  223567. if (callback != 0)
  223568. {
  223569. callback->audioDeviceIOCallback (const_cast<const float**> (inChans.getData()), numActiveInChans,
  223570. outChans, numActiveOutChans, numSamples);
  223571. }
  223572. else
  223573. {
  223574. for (i = 0; i < numActiveOutChans; ++i)
  223575. zeromem (outChans[i], sizeof (float) * numSamples);
  223576. }
  223577. }
  223578. static int processCallback (jack_nframes_t nframes, void* callbackArgument)
  223579. {
  223580. if (callbackArgument != 0)
  223581. ((JackAudioIODevice*) callbackArgument)->process (nframes);
  223582. return 0;
  223583. }
  223584. static void threadInitCallback (void* callbackArgument)
  223585. {
  223586. jack_Log ("JackAudioIODevice::initialise");
  223587. }
  223588. static void shutdownCallback (void* callbackArgument)
  223589. {
  223590. jack_Log ("JackAudioIODevice::shutdown");
  223591. JackAudioIODevice* device = (JackAudioIODevice*) callbackArgument;
  223592. if (device != 0)
  223593. {
  223594. device->client = 0;
  223595. device->close();
  223596. }
  223597. }
  223598. static void errorCallback (const char* msg)
  223599. {
  223600. jack_Log ("JackAudioIODevice::errorCallback " + String (msg));
  223601. }
  223602. bool isOpen_;
  223603. jack_client_t* client;
  223604. String lastError;
  223605. AudioIODeviceCallback* callback;
  223606. CriticalSection callbackLock;
  223607. HeapBlock <float*> inChans, outChans;
  223608. int totalNumberOfInputChannels;
  223609. int totalNumberOfOutputChannels;
  223610. Array<void*> inputPorts, outputPorts;
  223611. };
  223612. class JackAudioIODeviceType : public AudioIODeviceType
  223613. {
  223614. public:
  223615. JackAudioIODeviceType()
  223616. : AudioIODeviceType ("JACK"),
  223617. hasScanned (false)
  223618. {
  223619. }
  223620. ~JackAudioIODeviceType()
  223621. {
  223622. }
  223623. void scanForDevices()
  223624. {
  223625. hasScanned = true;
  223626. inputNames.clear();
  223627. inputIds.clear();
  223628. outputNames.clear();
  223629. outputIds.clear();
  223630. if (juce_libjack_handle == 0)
  223631. {
  223632. juce_libjack_handle = dlopen ("libjack.so", RTLD_LAZY);
  223633. if (juce_libjack_handle == 0)
  223634. return;
  223635. }
  223636. // open a dummy client
  223637. jack_status_t status;
  223638. jack_client_t* client = JUCE_NAMESPACE::jack_client_open ("JuceJackDummy", JackNoStartServer, &status);
  223639. if (client == 0)
  223640. {
  223641. dumpJackErrorMessage (status);
  223642. }
  223643. else
  223644. {
  223645. // scan for output devices
  223646. const char** ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsOutput);
  223647. if (ports != 0)
  223648. {
  223649. int j = 0;
  223650. while (ports[j] != 0)
  223651. {
  223652. String clientName (ports[j]);
  223653. clientName = clientName.upToFirstOccurrenceOf (":", false, false);
  223654. if (clientName != String (JUCE_JACK_CLIENT_NAME)
  223655. && ! inputNames.contains (clientName))
  223656. {
  223657. inputNames.add (clientName);
  223658. inputIds.add (ports [j]);
  223659. }
  223660. ++j;
  223661. }
  223662. free (ports);
  223663. }
  223664. // scan for input devices
  223665. ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsInput);
  223666. if (ports != 0)
  223667. {
  223668. int j = 0;
  223669. while (ports[j] != 0)
  223670. {
  223671. String clientName (ports[j]);
  223672. clientName = clientName.upToFirstOccurrenceOf (":", false, false);
  223673. if (clientName != String (JUCE_JACK_CLIENT_NAME)
  223674. && ! outputNames.contains (clientName))
  223675. {
  223676. outputNames.add (clientName);
  223677. outputIds.add (ports [j]);
  223678. }
  223679. ++j;
  223680. }
  223681. free (ports);
  223682. }
  223683. JUCE_NAMESPACE::jack_client_close (client);
  223684. }
  223685. }
  223686. const StringArray getDeviceNames (bool wantInputNames) const
  223687. {
  223688. jassert (hasScanned); // need to call scanForDevices() before doing this
  223689. return wantInputNames ? inputNames : outputNames;
  223690. }
  223691. int getDefaultDeviceIndex (bool forInput) const
  223692. {
  223693. jassert (hasScanned); // need to call scanForDevices() before doing this
  223694. return 0;
  223695. }
  223696. bool hasSeparateInputsAndOutputs() const { return true; }
  223697. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  223698. {
  223699. jassert (hasScanned); // need to call scanForDevices() before doing this
  223700. JackAudioIODevice* d = dynamic_cast <JackAudioIODevice*> (device);
  223701. if (d == 0)
  223702. return -1;
  223703. return asInput ? inputIds.indexOf (d->inputId)
  223704. : outputIds.indexOf (d->outputId);
  223705. }
  223706. AudioIODevice* createDevice (const String& outputDeviceName,
  223707. const String& inputDeviceName)
  223708. {
  223709. jassert (hasScanned); // need to call scanForDevices() before doing this
  223710. const int inputIndex = inputNames.indexOf (inputDeviceName);
  223711. const int outputIndex = outputNames.indexOf (outputDeviceName);
  223712. if (inputIndex >= 0 || outputIndex >= 0)
  223713. return new JackAudioIODevice (outputIndex >= 0 ? outputDeviceName
  223714. : inputDeviceName,
  223715. inputIds [inputIndex],
  223716. outputIds [outputIndex]);
  223717. return 0;
  223718. }
  223719. juce_UseDebuggingNewOperator
  223720. private:
  223721. StringArray inputNames, outputNames, inputIds, outputIds;
  223722. bool hasScanned;
  223723. JackAudioIODeviceType (const JackAudioIODeviceType&);
  223724. JackAudioIODeviceType& operator= (const JackAudioIODeviceType&);
  223725. };
  223726. AudioIODeviceType* juce_createAudioIODeviceType_JACK()
  223727. {
  223728. return new JackAudioIODeviceType();
  223729. }
  223730. #else // if JACK is turned off..
  223731. AudioIODeviceType* juce_createAudioIODeviceType_JACK() { return 0; }
  223732. #endif
  223733. #endif
  223734. /*** End of inlined file: juce_linux_JackAudio.cpp ***/
  223735. /*** Start of inlined file: juce_linux_Midi.cpp ***/
  223736. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  223737. // compiled on its own).
  223738. #if JUCE_INCLUDED_FILE
  223739. #if JUCE_ALSA
  223740. namespace
  223741. {
  223742. snd_seq_t* iterateMidiDevices (const bool forInput,
  223743. StringArray& deviceNamesFound,
  223744. const int deviceIndexToOpen)
  223745. {
  223746. snd_seq_t* returnedHandle = 0;
  223747. snd_seq_t* seqHandle;
  223748. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  223749. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  223750. {
  223751. snd_seq_system_info_t* systemInfo;
  223752. snd_seq_client_info_t* clientInfo;
  223753. if (snd_seq_system_info_malloc (&systemInfo) == 0)
  223754. {
  223755. if (snd_seq_system_info (seqHandle, systemInfo) == 0
  223756. && snd_seq_client_info_malloc (&clientInfo) == 0)
  223757. {
  223758. int numClients = snd_seq_system_info_get_cur_clients (systemInfo);
  223759. while (--numClients >= 0 && returnedHandle == 0)
  223760. {
  223761. if (snd_seq_query_next_client (seqHandle, clientInfo) == 0)
  223762. {
  223763. snd_seq_port_info_t* portInfo;
  223764. if (snd_seq_port_info_malloc (&portInfo) == 0)
  223765. {
  223766. int numPorts = snd_seq_client_info_get_num_ports (clientInfo);
  223767. const int client = snd_seq_client_info_get_client (clientInfo);
  223768. snd_seq_port_info_set_client (portInfo, client);
  223769. snd_seq_port_info_set_port (portInfo, -1);
  223770. while (--numPorts >= 0)
  223771. {
  223772. if (snd_seq_query_next_port (seqHandle, portInfo) == 0
  223773. && (snd_seq_port_info_get_capability (portInfo)
  223774. & (forInput ? SND_SEQ_PORT_CAP_READ
  223775. : SND_SEQ_PORT_CAP_WRITE)) != 0)
  223776. {
  223777. deviceNamesFound.add (snd_seq_client_info_get_name (clientInfo));
  223778. if (deviceNamesFound.size() == deviceIndexToOpen + 1)
  223779. {
  223780. const int sourcePort = snd_seq_port_info_get_port (portInfo);
  223781. const int sourceClient = snd_seq_client_info_get_client (clientInfo);
  223782. if (sourcePort != -1)
  223783. {
  223784. snd_seq_set_client_name (seqHandle,
  223785. forInput ? "Juce Midi Input"
  223786. : "Juce Midi Output");
  223787. const int portId
  223788. = snd_seq_create_simple_port (seqHandle,
  223789. forInput ? "Juce Midi In Port"
  223790. : "Juce Midi Out Port",
  223791. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  223792. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  223793. SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  223794. snd_seq_connect_from (seqHandle, portId, sourceClient, sourcePort);
  223795. returnedHandle = seqHandle;
  223796. }
  223797. }
  223798. }
  223799. }
  223800. snd_seq_port_info_free (portInfo);
  223801. }
  223802. }
  223803. }
  223804. snd_seq_client_info_free (clientInfo);
  223805. }
  223806. snd_seq_system_info_free (systemInfo);
  223807. }
  223808. if (returnedHandle == 0)
  223809. snd_seq_close (seqHandle);
  223810. }
  223811. deviceNamesFound.appendNumbersToDuplicates (true, true);
  223812. return returnedHandle;
  223813. }
  223814. snd_seq_t* createMidiDevice (const bool forInput, const String& deviceNameToOpen)
  223815. {
  223816. snd_seq_t* seqHandle = 0;
  223817. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  223818. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  223819. {
  223820. snd_seq_set_client_name (seqHandle,
  223821. (deviceNameToOpen + (forInput ? " Input" : " Output")).toCString());
  223822. const int portId
  223823. = snd_seq_create_simple_port (seqHandle,
  223824. forInput ? "in"
  223825. : "out",
  223826. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  223827. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  223828. forInput ? SND_SEQ_PORT_TYPE_APPLICATION
  223829. : SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  223830. if (portId < 0)
  223831. {
  223832. snd_seq_close (seqHandle);
  223833. seqHandle = 0;
  223834. }
  223835. }
  223836. return seqHandle;
  223837. }
  223838. }
  223839. class MidiOutputDevice
  223840. {
  223841. public:
  223842. MidiOutputDevice (MidiOutput* const midiOutput_,
  223843. snd_seq_t* const seqHandle_)
  223844. :
  223845. midiOutput (midiOutput_),
  223846. seqHandle (seqHandle_),
  223847. maxEventSize (16 * 1024)
  223848. {
  223849. jassert (seqHandle != 0 && midiOutput != 0);
  223850. snd_midi_event_new (maxEventSize, &midiParser);
  223851. }
  223852. ~MidiOutputDevice()
  223853. {
  223854. snd_midi_event_free (midiParser);
  223855. snd_seq_close (seqHandle);
  223856. }
  223857. void sendMessageNow (const MidiMessage& message)
  223858. {
  223859. if (message.getRawDataSize() > maxEventSize)
  223860. {
  223861. maxEventSize = message.getRawDataSize();
  223862. snd_midi_event_free (midiParser);
  223863. snd_midi_event_new (maxEventSize, &midiParser);
  223864. }
  223865. snd_seq_event_t event;
  223866. snd_seq_ev_clear (&event);
  223867. snd_midi_event_encode (midiParser,
  223868. message.getRawData(),
  223869. message.getRawDataSize(),
  223870. &event);
  223871. snd_midi_event_reset_encode (midiParser);
  223872. snd_seq_ev_set_source (&event, 0);
  223873. snd_seq_ev_set_subs (&event);
  223874. snd_seq_ev_set_direct (&event);
  223875. snd_seq_event_output (seqHandle, &event);
  223876. snd_seq_drain_output (seqHandle);
  223877. }
  223878. juce_UseDebuggingNewOperator
  223879. private:
  223880. MidiOutput* const midiOutput;
  223881. snd_seq_t* const seqHandle;
  223882. snd_midi_event_t* midiParser;
  223883. int maxEventSize;
  223884. };
  223885. const StringArray MidiOutput::getDevices()
  223886. {
  223887. StringArray devices;
  223888. iterateMidiDevices (false, devices, -1);
  223889. return devices;
  223890. }
  223891. int MidiOutput::getDefaultDeviceIndex()
  223892. {
  223893. return 0;
  223894. }
  223895. MidiOutput* MidiOutput::openDevice (int deviceIndex)
  223896. {
  223897. MidiOutput* newDevice = 0;
  223898. StringArray devices;
  223899. snd_seq_t* const handle = iterateMidiDevices (false, devices, deviceIndex);
  223900. if (handle != 0)
  223901. {
  223902. newDevice = new MidiOutput();
  223903. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  223904. }
  223905. return newDevice;
  223906. }
  223907. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  223908. {
  223909. MidiOutput* newDevice = 0;
  223910. snd_seq_t* const handle = createMidiDevice (false, deviceName);
  223911. if (handle != 0)
  223912. {
  223913. newDevice = new MidiOutput();
  223914. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  223915. }
  223916. return newDevice;
  223917. }
  223918. MidiOutput::~MidiOutput()
  223919. {
  223920. delete static_cast <MidiOutputDevice*> (internal);
  223921. }
  223922. void MidiOutput::reset()
  223923. {
  223924. }
  223925. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  223926. {
  223927. return false;
  223928. }
  223929. void MidiOutput::setVolume (float leftVol, float rightVol)
  223930. {
  223931. }
  223932. void MidiOutput::sendMessageNow (const MidiMessage& message)
  223933. {
  223934. static_cast <MidiOutputDevice*> (internal)->sendMessageNow (message);
  223935. }
  223936. class MidiInputThread : public Thread
  223937. {
  223938. public:
  223939. MidiInputThread (MidiInput* const midiInput_,
  223940. snd_seq_t* const seqHandle_,
  223941. MidiInputCallback* const callback_)
  223942. : Thread ("Juce MIDI Input"),
  223943. midiInput (midiInput_),
  223944. seqHandle (seqHandle_),
  223945. callback (callback_)
  223946. {
  223947. jassert (seqHandle != 0 && callback != 0 && midiInput != 0);
  223948. }
  223949. ~MidiInputThread()
  223950. {
  223951. snd_seq_close (seqHandle);
  223952. }
  223953. void run()
  223954. {
  223955. const int maxEventSize = 16 * 1024;
  223956. snd_midi_event_t* midiParser;
  223957. if (snd_midi_event_new (maxEventSize, &midiParser) >= 0)
  223958. {
  223959. HeapBlock <uint8> buffer (maxEventSize);
  223960. const int numPfds = snd_seq_poll_descriptors_count (seqHandle, POLLIN);
  223961. struct pollfd* const pfd = (struct pollfd*) alloca (numPfds * sizeof (struct pollfd));
  223962. snd_seq_poll_descriptors (seqHandle, pfd, numPfds, POLLIN);
  223963. while (! threadShouldExit())
  223964. {
  223965. if (poll (pfd, numPfds, 500) > 0)
  223966. {
  223967. snd_seq_event_t* inputEvent = 0;
  223968. snd_seq_nonblock (seqHandle, 1);
  223969. do
  223970. {
  223971. if (snd_seq_event_input (seqHandle, &inputEvent) >= 0)
  223972. {
  223973. // xxx what about SYSEXes that are too big for the buffer?
  223974. const int numBytes = snd_midi_event_decode (midiParser, buffer, maxEventSize, inputEvent);
  223975. snd_midi_event_reset_decode (midiParser);
  223976. if (numBytes > 0)
  223977. {
  223978. const MidiMessage message ((const uint8*) buffer,
  223979. numBytes,
  223980. Time::getMillisecondCounter() * 0.001);
  223981. callback->handleIncomingMidiMessage (midiInput, message);
  223982. }
  223983. snd_seq_free_event (inputEvent);
  223984. }
  223985. }
  223986. while (snd_seq_event_input_pending (seqHandle, 0) > 0);
  223987. snd_seq_free_event (inputEvent);
  223988. }
  223989. }
  223990. snd_midi_event_free (midiParser);
  223991. }
  223992. };
  223993. juce_UseDebuggingNewOperator
  223994. private:
  223995. MidiInput* const midiInput;
  223996. snd_seq_t* const seqHandle;
  223997. MidiInputCallback* const callback;
  223998. };
  223999. MidiInput::MidiInput (const String& name_)
  224000. : name (name_),
  224001. internal (0)
  224002. {
  224003. }
  224004. MidiInput::~MidiInput()
  224005. {
  224006. stop();
  224007. delete static_cast <MidiInputThread*> (internal);
  224008. }
  224009. void MidiInput::start()
  224010. {
  224011. static_cast <MidiInputThread*> (internal)->startThread();
  224012. }
  224013. void MidiInput::stop()
  224014. {
  224015. static_cast <MidiInputThread*> (internal)->stopThread (3000);
  224016. }
  224017. int MidiInput::getDefaultDeviceIndex()
  224018. {
  224019. return 0;
  224020. }
  224021. const StringArray MidiInput::getDevices()
  224022. {
  224023. StringArray devices;
  224024. iterateMidiDevices (true, devices, -1);
  224025. return devices;
  224026. }
  224027. MidiInput* MidiInput::openDevice (int deviceIndex, MidiInputCallback* callback)
  224028. {
  224029. MidiInput* newDevice = 0;
  224030. StringArray devices;
  224031. snd_seq_t* const handle = iterateMidiDevices (true, devices, deviceIndex);
  224032. if (handle != 0)
  224033. {
  224034. newDevice = new MidiInput (devices [deviceIndex]);
  224035. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  224036. }
  224037. return newDevice;
  224038. }
  224039. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  224040. {
  224041. MidiInput* newDevice = 0;
  224042. snd_seq_t* const handle = createMidiDevice (true, deviceName);
  224043. if (handle != 0)
  224044. {
  224045. newDevice = new MidiInput (deviceName);
  224046. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  224047. }
  224048. return newDevice;
  224049. }
  224050. #else
  224051. // (These are just stub functions if ALSA is unavailable...)
  224052. const StringArray MidiOutput::getDevices() { return StringArray(); }
  224053. int MidiOutput::getDefaultDeviceIndex() { return 0; }
  224054. MidiOutput* MidiOutput::openDevice (int) { return 0; }
  224055. MidiOutput* MidiOutput::createNewDevice (const String&) { return 0; }
  224056. MidiOutput::~MidiOutput() {}
  224057. void MidiOutput::reset() {}
  224058. bool MidiOutput::getVolume (float&, float&) { return false; }
  224059. void MidiOutput::setVolume (float, float) {}
  224060. void MidiOutput::sendMessageNow (const MidiMessage&) {}
  224061. MidiInput::MidiInput (const String& name_) : name (name_), internal (0) {}
  224062. MidiInput::~MidiInput() {}
  224063. void MidiInput::start() {}
  224064. void MidiInput::stop() {}
  224065. int MidiInput::getDefaultDeviceIndex() { return 0; }
  224066. const StringArray MidiInput::getDevices() { return StringArray(); }
  224067. MidiInput* MidiInput::openDevice (int, MidiInputCallback*) { return 0; }
  224068. MidiInput* MidiInput::createNewDevice (const String&, MidiInputCallback*) { return 0; }
  224069. #endif
  224070. #endif
  224071. /*** End of inlined file: juce_linux_Midi.cpp ***/
  224072. /*** Start of inlined file: juce_linux_AudioCDReader.cpp ***/
  224073. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  224074. // compiled on its own).
  224075. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  224076. AudioCDReader::AudioCDReader()
  224077. : AudioFormatReader (0, "CD Audio")
  224078. {
  224079. }
  224080. const StringArray AudioCDReader::getAvailableCDNames()
  224081. {
  224082. StringArray names;
  224083. return names;
  224084. }
  224085. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  224086. {
  224087. return 0;
  224088. }
  224089. AudioCDReader::~AudioCDReader()
  224090. {
  224091. }
  224092. void AudioCDReader::refreshTrackLengths()
  224093. {
  224094. }
  224095. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  224096. int64 startSampleInFile, int numSamples)
  224097. {
  224098. return false;
  224099. }
  224100. bool AudioCDReader::isCDStillPresent() const
  224101. {
  224102. return false;
  224103. }
  224104. bool AudioCDReader::isTrackAudio (int trackNum) const
  224105. {
  224106. return false;
  224107. }
  224108. void AudioCDReader::enableIndexScanning (bool b)
  224109. {
  224110. }
  224111. int AudioCDReader::getLastIndex() const
  224112. {
  224113. return 0;
  224114. }
  224115. const Array<int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  224116. {
  224117. return Array<int>();
  224118. }
  224119. #endif
  224120. /*** End of inlined file: juce_linux_AudioCDReader.cpp ***/
  224121. /*** Start of inlined file: juce_linux_FileChooser.cpp ***/
  224122. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  224123. // compiled on its own).
  224124. #if JUCE_INCLUDED_FILE
  224125. void FileChooser::showPlatformDialog (Array<File>& results,
  224126. const String& title,
  224127. const File& file,
  224128. const String& filters,
  224129. bool isDirectory,
  224130. bool selectsFiles,
  224131. bool isSave,
  224132. bool warnAboutOverwritingExistingFiles,
  224133. bool selectMultipleFiles,
  224134. FilePreviewComponent* previewComponent)
  224135. {
  224136. const String separator (":");
  224137. String command ("zenity --file-selection");
  224138. if (title.isNotEmpty())
  224139. command << " --title=\"" << title << "\"";
  224140. if (file != File::nonexistent)
  224141. command << " --filename=\"" << file.getFullPathName () << "\"";
  224142. if (isDirectory)
  224143. command << " --directory";
  224144. if (isSave)
  224145. command << " --save";
  224146. if (selectMultipleFiles)
  224147. command << " --multiple --separator=\"" << separator << "\"";
  224148. command << " 2>&1";
  224149. MemoryOutputStream result;
  224150. int status = -1;
  224151. FILE* stream = popen (command.toUTF8(), "r");
  224152. if (stream != 0)
  224153. {
  224154. for (;;)
  224155. {
  224156. char buffer [1024];
  224157. const int bytesRead = fread (buffer, 1, sizeof (buffer), stream);
  224158. if (bytesRead <= 0)
  224159. break;
  224160. result.write (buffer, bytesRead);
  224161. }
  224162. status = pclose (stream);
  224163. }
  224164. if (status == 0)
  224165. {
  224166. StringArray tokens;
  224167. if (selectMultipleFiles)
  224168. tokens.addTokens (result.toUTF8(), separator, String::empty);
  224169. else
  224170. tokens.add (result.toUTF8());
  224171. for (int i = 0; i < tokens.size(); i++)
  224172. results.add (File (tokens[i]));
  224173. return;
  224174. }
  224175. //xxx ain't got one!
  224176. jassertfalse;
  224177. }
  224178. #endif
  224179. /*** End of inlined file: juce_linux_FileChooser.cpp ***/
  224180. /*** Start of inlined file: juce_linux_WebBrowserComponent.cpp ***/
  224181. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  224182. // compiled on its own).
  224183. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  224184. /*
  224185. Sorry.. This class isn't implemented on Linux!
  224186. */
  224187. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  224188. : browser (0),
  224189. blankPageShown (false),
  224190. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  224191. {
  224192. setOpaque (true);
  224193. }
  224194. WebBrowserComponent::~WebBrowserComponent()
  224195. {
  224196. }
  224197. void WebBrowserComponent::goToURL (const String& url,
  224198. const StringArray* headers,
  224199. const MemoryBlock* postData)
  224200. {
  224201. lastURL = url;
  224202. lastHeaders.clear();
  224203. if (headers != 0)
  224204. lastHeaders = *headers;
  224205. lastPostData.setSize (0);
  224206. if (postData != 0)
  224207. lastPostData = *postData;
  224208. blankPageShown = false;
  224209. }
  224210. void WebBrowserComponent::stop()
  224211. {
  224212. }
  224213. void WebBrowserComponent::goBack()
  224214. {
  224215. lastURL = String::empty;
  224216. blankPageShown = false;
  224217. }
  224218. void WebBrowserComponent::goForward()
  224219. {
  224220. lastURL = String::empty;
  224221. }
  224222. void WebBrowserComponent::refresh()
  224223. {
  224224. }
  224225. void WebBrowserComponent::paint (Graphics& g)
  224226. {
  224227. g.fillAll (Colours::white);
  224228. }
  224229. void WebBrowserComponent::checkWindowAssociation()
  224230. {
  224231. }
  224232. void WebBrowserComponent::reloadLastURL()
  224233. {
  224234. if (lastURL.isNotEmpty())
  224235. {
  224236. goToURL (lastURL, &lastHeaders, &lastPostData);
  224237. lastURL = String::empty;
  224238. }
  224239. }
  224240. void WebBrowserComponent::parentHierarchyChanged()
  224241. {
  224242. checkWindowAssociation();
  224243. }
  224244. void WebBrowserComponent::resized()
  224245. {
  224246. }
  224247. void WebBrowserComponent::visibilityChanged()
  224248. {
  224249. checkWindowAssociation();
  224250. }
  224251. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  224252. {
  224253. return true;
  224254. }
  224255. #endif
  224256. /*** End of inlined file: juce_linux_WebBrowserComponent.cpp ***/
  224257. #endif
  224258. END_JUCE_NAMESPACE
  224259. #endif
  224260. /*** End of inlined file: juce_linux_NativeCode.cpp ***/
  224261. #endif
  224262. #if JUCE_MAC || JUCE_IPHONE
  224263. /*** Start of inlined file: juce_mac_NativeCode.mm ***/
  224264. /*
  224265. This file wraps together all the mac-specific code, so that
  224266. we can include all the native headers just once, and compile all our
  224267. platform-specific stuff in one big lump, keeping it out of the way of
  224268. the rest of the codebase.
  224269. */
  224270. #if JUCE_MAC || JUCE_IOS
  224271. BEGIN_JUCE_NAMESPACE
  224272. #undef Point
  224273. namespace
  224274. {
  224275. template <class RectType>
  224276. const Rectangle<int> convertToRectInt (const RectType& r)
  224277. {
  224278. return Rectangle<int> ((int) r.origin.x, (int) r.origin.y, (int) r.size.width, (int) r.size.height);
  224279. }
  224280. template <class RectType>
  224281. const Rectangle<float> convertToRectFloat (const RectType& r)
  224282. {
  224283. return Rectangle<float> (r.origin.x, r.origin.y, r.size.width, r.size.height);
  224284. }
  224285. template <class RectType>
  224286. CGRect convertToCGRect (const RectType& r)
  224287. {
  224288. return CGRectMake ((CGFloat) r.getX(), (CGFloat) r.getY(), (CGFloat) r.getWidth(), (CGFloat) r.getHeight());
  224289. }
  224290. }
  224291. #define JUCE_INCLUDED_FILE 1
  224292. // Now include the actual code files..
  224293. /*** Start of inlined file: juce_mac_ObjCSuffix.h ***/
  224294. /** This suffix is used for naming all Obj-C classes that are used inside juce.
  224295. Because of the flat naming structure used by Obj-C, you can get horrible situations where
  224296. two DLLs are loaded into a host, each of which uses classes with the same names, and these get
  224297. cross-linked so that when you make a call to a class that you thought was private, it ends up
  224298. actually calling into a similarly named class in the other module's address space.
  224299. By changing this macro to a unique value, you ensure that all the obj-C classes in your app
  224300. have unique names, and should avoid this problem.
  224301. If you're using the amalgamated version, you can just set this macro to something unique before
  224302. you include juce_amalgamated.cpp.
  224303. */
  224304. #ifndef JUCE_ObjCExtraSuffix
  224305. #define JUCE_ObjCExtraSuffix 3
  224306. #endif
  224307. #define appendMacro1(a, b, c, d, e) a ## _ ## b ## _ ## c ## _ ## d ## _ ## e
  224308. #define appendMacro2(a, b, c, d, e) appendMacro1(a, b, c, d, e)
  224309. #define MakeObjCClassName(rootName) appendMacro2 (rootName, JUCE_MAJOR_VERSION, JUCE_MINOR_VERSION, JUCE_BUILDNUMBER, JUCE_ObjCExtraSuffix)
  224310. /*** End of inlined file: juce_mac_ObjCSuffix.h ***/
  224311. /*** Start of inlined file: juce_mac_Strings.mm ***/
  224312. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224313. // compiled on its own).
  224314. #if JUCE_INCLUDED_FILE
  224315. namespace
  224316. {
  224317. const String nsStringToJuce (NSString* s)
  224318. {
  224319. return String::fromUTF8 ([s UTF8String]);
  224320. }
  224321. NSString* juceStringToNS (const String& s)
  224322. {
  224323. return [NSString stringWithUTF8String: s.toUTF8()];
  224324. }
  224325. const String convertUTF16ToString (const UniChar* utf16)
  224326. {
  224327. String s;
  224328. while (*utf16 != 0)
  224329. s += (juce_wchar) *utf16++;
  224330. return s;
  224331. }
  224332. }
  224333. const String PlatformUtilities::cfStringToJuceString (CFStringRef cfString)
  224334. {
  224335. String result;
  224336. if (cfString != 0)
  224337. {
  224338. CFRange range = { 0, CFStringGetLength (cfString) };
  224339. HeapBlock <UniChar> u (range.length + 1);
  224340. CFStringGetCharacters (cfString, range, u);
  224341. u[range.length] = 0;
  224342. result = convertUTF16ToString (u);
  224343. }
  224344. return result;
  224345. }
  224346. CFStringRef PlatformUtilities::juceStringToCFString (const String& s)
  224347. {
  224348. const int len = s.length();
  224349. HeapBlock <UniChar> temp (len + 2);
  224350. for (int i = 0; i <= len; ++i)
  224351. temp[i] = s[i];
  224352. return CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  224353. }
  224354. const String PlatformUtilities::convertToPrecomposedUnicode (const String& s)
  224355. {
  224356. #if JUCE_IOS
  224357. const ScopedAutoReleasePool pool;
  224358. return nsStringToJuce ([juceStringToNS (s) precomposedStringWithCanonicalMapping]);
  224359. #else
  224360. UnicodeMapping map;
  224361. map.unicodeEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  224362. kUnicodeNoSubset,
  224363. kTextEncodingDefaultFormat);
  224364. map.otherEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  224365. kUnicodeCanonicalCompVariant,
  224366. kTextEncodingDefaultFormat);
  224367. map.mappingVersion = kUnicodeUseLatestMapping;
  224368. UnicodeToTextInfo conversionInfo = 0;
  224369. String result;
  224370. if (CreateUnicodeToTextInfo (&map, &conversionInfo) == noErr)
  224371. {
  224372. const int len = s.length();
  224373. HeapBlock <UniChar> tempIn, tempOut;
  224374. tempIn.calloc (len + 2);
  224375. tempOut.calloc (len + 2);
  224376. for (int i = 0; i <= len; ++i)
  224377. tempIn[i] = s[i];
  224378. ByteCount bytesRead = 0;
  224379. ByteCount outputBufferSize = 0;
  224380. if (ConvertFromUnicodeToText (conversionInfo,
  224381. len * sizeof (UniChar), tempIn,
  224382. kUnicodeDefaultDirectionMask,
  224383. 0, 0, 0, 0,
  224384. len * sizeof (UniChar), &bytesRead,
  224385. &outputBufferSize, tempOut) == noErr)
  224386. {
  224387. result.preallocateStorage (bytesRead / sizeof (UniChar) + 2);
  224388. juce_wchar* t = result;
  224389. unsigned int i;
  224390. for (i = 0; i < bytesRead / sizeof (UniChar); ++i)
  224391. t[i] = (juce_wchar) tempOut[i];
  224392. t[i] = 0;
  224393. }
  224394. DisposeUnicodeToTextInfo (&conversionInfo);
  224395. }
  224396. return result;
  224397. #endif
  224398. }
  224399. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  224400. void SystemClipboard::copyTextToClipboard (const String& text)
  224401. {
  224402. #if JUCE_IOS
  224403. [[UIPasteboard generalPasteboard] setValue: juceStringToNS (text)
  224404. forPasteboardType: @"public.text"];
  224405. #else
  224406. [[NSPasteboard generalPasteboard] declareTypes: [NSArray arrayWithObject: NSStringPboardType]
  224407. owner: nil];
  224408. [[NSPasteboard generalPasteboard] setString: juceStringToNS (text)
  224409. forType: NSStringPboardType];
  224410. #endif
  224411. }
  224412. const String SystemClipboard::getTextFromClipboard()
  224413. {
  224414. #if JUCE_IOS
  224415. NSString* text = [[UIPasteboard generalPasteboard] valueForPasteboardType: @"public.text"];
  224416. #else
  224417. NSString* text = [[NSPasteboard generalPasteboard] stringForType: NSStringPboardType];
  224418. #endif
  224419. return text == 0 ? String::empty
  224420. : nsStringToJuce (text);
  224421. }
  224422. #endif
  224423. #endif
  224424. /*** End of inlined file: juce_mac_Strings.mm ***/
  224425. /*** Start of inlined file: juce_mac_SystemStats.mm ***/
  224426. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224427. // compiled on its own).
  224428. #if JUCE_INCLUDED_FILE
  224429. namespace SystemStatsHelpers
  224430. {
  224431. static int64 highResTimerFrequency = 0;
  224432. static double highResTimerToMillisecRatio = 0;
  224433. #if JUCE_INTEL
  224434. static void juce_getCpuVendor (char* const v) throw()
  224435. {
  224436. int vendor[4];
  224437. zerostruct (vendor);
  224438. int dummy = 0;
  224439. asm ("mov %%ebx, %%esi \n\t"
  224440. "cpuid \n\t"
  224441. "xchg %%esi, %%ebx"
  224442. : "=a" (dummy), "=S" (vendor[0]), "=c" (vendor[2]), "=d" (vendor[1]) : "a" (0));
  224443. memcpy (v, vendor, 16);
  224444. }
  224445. static unsigned int getCPUIDWord (unsigned int& familyModel, unsigned int& extFeatures)
  224446. {
  224447. unsigned int cpu = 0;
  224448. unsigned int ext = 0;
  224449. unsigned int family = 0;
  224450. unsigned int dummy = 0;
  224451. asm ("mov %%ebx, %%esi \n\t"
  224452. "cpuid \n\t"
  224453. "xchg %%esi, %%ebx"
  224454. : "=a" (family), "=S" (ext), "=c" (dummy), "=d" (cpu) : "a" (1));
  224455. familyModel = family;
  224456. extFeatures = ext;
  224457. return cpu;
  224458. }
  224459. #endif
  224460. }
  224461. void SystemStats::initialiseStats()
  224462. {
  224463. using namespace SystemStatsHelpers;
  224464. static bool initialised = false;
  224465. if (! initialised)
  224466. {
  224467. initialised = true;
  224468. #if JUCE_MAC
  224469. [NSApplication sharedApplication];
  224470. #endif
  224471. #if JUCE_INTEL
  224472. unsigned int familyModel, extFeatures;
  224473. const unsigned int features = getCPUIDWord (familyModel, extFeatures);
  224474. cpuFlags.hasMMX = ((features & (1 << 23)) != 0);
  224475. cpuFlags.hasSSE = ((features & (1 << 25)) != 0);
  224476. cpuFlags.hasSSE2 = ((features & (1 << 26)) != 0);
  224477. cpuFlags.has3DNow = ((extFeatures & (1 << 31)) != 0);
  224478. #else
  224479. cpuFlags.hasMMX = false;
  224480. cpuFlags.hasSSE = false;
  224481. cpuFlags.hasSSE2 = false;
  224482. cpuFlags.has3DNow = false;
  224483. #endif
  224484. #if JUCE_IOS || (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5)
  224485. cpuFlags.numCpus = (int) [[NSProcessInfo processInfo] activeProcessorCount];
  224486. #else
  224487. cpuFlags.numCpus = (int) MPProcessors();
  224488. #endif
  224489. mach_timebase_info_data_t timebase;
  224490. (void) mach_timebase_info (&timebase);
  224491. highResTimerFrequency = (int64) (1.0e9 * timebase.denom / timebase.numer);
  224492. highResTimerToMillisecRatio = timebase.numer / (1.0e6 * timebase.denom);
  224493. String s (SystemStats::getJUCEVersion());
  224494. rlimit lim;
  224495. getrlimit (RLIMIT_NOFILE, &lim);
  224496. lim.rlim_cur = lim.rlim_max = RLIM_INFINITY;
  224497. setrlimit (RLIMIT_NOFILE, &lim);
  224498. }
  224499. }
  224500. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  224501. {
  224502. return MacOSX;
  224503. }
  224504. const String SystemStats::getOperatingSystemName()
  224505. {
  224506. return "Mac OS X";
  224507. }
  224508. #if ! JUCE_IOS
  224509. int PlatformUtilities::getOSXMinorVersionNumber()
  224510. {
  224511. SInt32 versionMinor = 0;
  224512. OSErr err = Gestalt (gestaltSystemVersionMinor, &versionMinor);
  224513. (void) err;
  224514. jassert (err == noErr);
  224515. return (int) versionMinor;
  224516. }
  224517. #endif
  224518. bool SystemStats::isOperatingSystem64Bit()
  224519. {
  224520. #if JUCE_IOS
  224521. return false;
  224522. #elif JUCE_64BIT
  224523. return true;
  224524. #else
  224525. return PlatformUtilities::getOSXMinorVersionNumber() >= 6;
  224526. #endif
  224527. }
  224528. int SystemStats::getMemorySizeInMegabytes()
  224529. {
  224530. uint64 mem = 0;
  224531. size_t memSize = sizeof (mem);
  224532. int mib[] = { CTL_HW, HW_MEMSIZE };
  224533. sysctl (mib, 2, &mem, &memSize, 0, 0);
  224534. return (int) (mem / (1024 * 1024));
  224535. }
  224536. const String SystemStats::getCpuVendor()
  224537. {
  224538. #if JUCE_INTEL
  224539. char v [16];
  224540. SystemStatsHelpers::juce_getCpuVendor (v);
  224541. return String (v, 16);
  224542. #else
  224543. return String::empty;
  224544. #endif
  224545. }
  224546. int SystemStats::getCpuSpeedInMegaherz()
  224547. {
  224548. uint64 speedHz = 0;
  224549. size_t speedSize = sizeof (speedHz);
  224550. int mib[] = { CTL_HW, HW_CPU_FREQ };
  224551. sysctl (mib, 2, &speedHz, &speedSize, 0, 0);
  224552. #if JUCE_BIG_ENDIAN
  224553. if (speedSize == 4)
  224554. speedHz >>= 32;
  224555. #endif
  224556. return (int) (speedHz / 1000000);
  224557. }
  224558. const String SystemStats::getLogonName()
  224559. {
  224560. return nsStringToJuce (NSUserName());
  224561. }
  224562. const String SystemStats::getFullUserName()
  224563. {
  224564. return nsStringToJuce (NSFullUserName());
  224565. }
  224566. uint32 juce_millisecondsSinceStartup() throw()
  224567. {
  224568. return (uint32) (mach_absolute_time() * SystemStatsHelpers::highResTimerToMillisecRatio);
  224569. }
  224570. double Time::getMillisecondCounterHiRes() throw()
  224571. {
  224572. return mach_absolute_time() * SystemStatsHelpers::highResTimerToMillisecRatio;
  224573. }
  224574. int64 Time::getHighResolutionTicks() throw()
  224575. {
  224576. return (int64) mach_absolute_time();
  224577. }
  224578. int64 Time::getHighResolutionTicksPerSecond() throw()
  224579. {
  224580. return SystemStatsHelpers::highResTimerFrequency;
  224581. }
  224582. bool Time::setSystemTimeToThisTime() const
  224583. {
  224584. jassertfalse;
  224585. return false;
  224586. }
  224587. int SystemStats::getPageSize()
  224588. {
  224589. return (int) NSPageSize();
  224590. }
  224591. void PlatformUtilities::fpuReset()
  224592. {
  224593. }
  224594. #endif
  224595. /*** End of inlined file: juce_mac_SystemStats.mm ***/
  224596. /*** Start of inlined file: juce_mac_Network.mm ***/
  224597. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224598. // compiled on its own).
  224599. #if JUCE_INCLUDED_FILE
  224600. void MACAddress::findAllAddresses (Array<MACAddress>& result)
  224601. {
  224602. ifaddrs* addrs = 0;
  224603. if (getifaddrs (&addrs) == 0)
  224604. {
  224605. for (const ifaddrs* cursor = addrs; cursor != 0; cursor = cursor->ifa_next)
  224606. {
  224607. sockaddr_storage* sto = (sockaddr_storage*) cursor->ifa_addr;
  224608. if (sto->ss_family == AF_LINK)
  224609. {
  224610. const sockaddr_dl* const sadd = (const sockaddr_dl*) cursor->ifa_addr;
  224611. #ifndef IFT_ETHER
  224612. #define IFT_ETHER 6
  224613. #endif
  224614. if (sadd->sdl_type == IFT_ETHER)
  224615. result.addIfNotAlreadyThere (MACAddress (((const uint8*) sadd->sdl_data) + sadd->sdl_nlen));
  224616. }
  224617. }
  224618. freeifaddrs (addrs);
  224619. }
  224620. }
  224621. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  224622. const String& emailSubject,
  224623. const String& bodyText,
  224624. const StringArray& filesToAttach)
  224625. {
  224626. #if JUCE_IOS
  224627. //xxx probably need to use MFMailComposeViewController
  224628. jassertfalse;
  224629. return false;
  224630. #else
  224631. const ScopedAutoReleasePool pool;
  224632. String script;
  224633. script << "tell application \"Mail\"\r\n"
  224634. "set newMessage to make new outgoing message with properties {subject:\""
  224635. << emailSubject.replace ("\"", "\\\"")
  224636. << "\", content:\""
  224637. << bodyText.replace ("\"", "\\\"")
  224638. << "\" & return & return}\r\n"
  224639. "tell newMessage\r\n"
  224640. "set visible to true\r\n"
  224641. "set sender to \"sdfsdfsdfewf\"\r\n"
  224642. "make new to recipient at end of to recipients with properties {address:\""
  224643. << targetEmailAddress
  224644. << "\"}\r\n";
  224645. for (int i = 0; i < filesToAttach.size(); ++i)
  224646. {
  224647. script << "tell content\r\n"
  224648. "make new attachment with properties {file name:\""
  224649. << filesToAttach[i].replace ("\"", "\\\"")
  224650. << "\"} at after the last paragraph\r\n"
  224651. "end tell\r\n";
  224652. }
  224653. script << "end tell\r\n"
  224654. "end tell\r\n";
  224655. NSAppleScript* s = [[NSAppleScript alloc]
  224656. initWithSource: juceStringToNS (script)];
  224657. NSDictionary* error = 0;
  224658. const bool ok = [s executeAndReturnError: &error] != nil;
  224659. [s release];
  224660. return ok;
  224661. #endif
  224662. }
  224663. END_JUCE_NAMESPACE
  224664. using namespace JUCE_NAMESPACE;
  224665. #define JuceURLConnection MakeObjCClassName(JuceURLConnection)
  224666. @interface JuceURLConnection : NSObject
  224667. {
  224668. @public
  224669. NSURLRequest* request;
  224670. NSURLConnection* connection;
  224671. NSMutableData* data;
  224672. Thread* runLoopThread;
  224673. bool initialised, hasFailed, hasFinished;
  224674. int position;
  224675. int64 contentLength;
  224676. NSDictionary* headers;
  224677. NSLock* dataLock;
  224678. }
  224679. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req withCallback: (URL::OpenStreamProgressCallback*) callback withContext: (void*) context;
  224680. - (void) dealloc;
  224681. - (void) connection: (NSURLConnection*) connection didReceiveResponse: (NSURLResponse*) response;
  224682. - (void) connection: (NSURLConnection*) connection didFailWithError: (NSError*) error;
  224683. - (void) connection: (NSURLConnection*) connection didReceiveData: (NSData*) data;
  224684. - (void) connectionDidFinishLoading: (NSURLConnection*) connection;
  224685. - (BOOL) isOpen;
  224686. - (int) read: (char*) dest numBytes: (int) num;
  224687. - (int) readPosition;
  224688. - (void) stop;
  224689. - (void) createConnection;
  224690. @end
  224691. class JuceURLConnectionMessageThread : public Thread
  224692. {
  224693. JuceURLConnection* owner;
  224694. public:
  224695. JuceURLConnectionMessageThread (JuceURLConnection* owner_)
  224696. : Thread ("http connection"),
  224697. owner (owner_)
  224698. {
  224699. }
  224700. ~JuceURLConnectionMessageThread()
  224701. {
  224702. stopThread (10000);
  224703. }
  224704. void run()
  224705. {
  224706. [owner createConnection];
  224707. while (! threadShouldExit())
  224708. {
  224709. const ScopedAutoReleasePool pool;
  224710. [[NSRunLoop currentRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  224711. }
  224712. }
  224713. };
  224714. @implementation JuceURLConnection
  224715. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req
  224716. withCallback: (URL::OpenStreamProgressCallback*) callback
  224717. withContext: (void*) context;
  224718. {
  224719. [super init];
  224720. request = req;
  224721. [request retain];
  224722. data = [[NSMutableData data] retain];
  224723. dataLock = [[NSLock alloc] init];
  224724. connection = 0;
  224725. initialised = false;
  224726. hasFailed = false;
  224727. hasFinished = false;
  224728. contentLength = -1;
  224729. headers = 0;
  224730. runLoopThread = new JuceURLConnectionMessageThread (self);
  224731. runLoopThread->startThread();
  224732. while (runLoopThread->isThreadRunning() && ! initialised)
  224733. {
  224734. if (callback != 0)
  224735. callback (context, -1, (int) [[request HTTPBody] length]);
  224736. Thread::sleep (1);
  224737. }
  224738. return self;
  224739. }
  224740. - (void) dealloc
  224741. {
  224742. [self stop];
  224743. deleteAndZero (runLoopThread);
  224744. [connection release];
  224745. [data release];
  224746. [dataLock release];
  224747. [request release];
  224748. [headers release];
  224749. [super dealloc];
  224750. }
  224751. - (void) createConnection
  224752. {
  224753. NSUInteger oldRetainCount = [self retainCount];
  224754. connection = [[NSURLConnection alloc] initWithRequest: request
  224755. delegate: self];
  224756. if (oldRetainCount == [self retainCount])
  224757. [self retain]; // newer SDK should already retain this, but there were problems in older versions..
  224758. if (connection == nil)
  224759. runLoopThread->signalThreadShouldExit();
  224760. }
  224761. - (void) connection: (NSURLConnection*) conn didReceiveResponse: (NSURLResponse*) response
  224762. {
  224763. (void) conn;
  224764. [dataLock lock];
  224765. [data setLength: 0];
  224766. [dataLock unlock];
  224767. initialised = true;
  224768. contentLength = [response expectedContentLength];
  224769. [headers release];
  224770. headers = 0;
  224771. if ([response isKindOfClass: [NSHTTPURLResponse class]])
  224772. headers = [[((NSHTTPURLResponse*) response) allHeaderFields] retain];
  224773. }
  224774. - (void) connection: (NSURLConnection*) conn didFailWithError: (NSError*) error
  224775. {
  224776. (void) conn;
  224777. DBG (nsStringToJuce ([error description]));
  224778. hasFailed = true;
  224779. initialised = true;
  224780. if (runLoopThread != 0)
  224781. runLoopThread->signalThreadShouldExit();
  224782. }
  224783. - (void) connection: (NSURLConnection*) conn didReceiveData: (NSData*) newData
  224784. {
  224785. (void) conn;
  224786. [dataLock lock];
  224787. [data appendData: newData];
  224788. [dataLock unlock];
  224789. initialised = true;
  224790. }
  224791. - (void) connectionDidFinishLoading: (NSURLConnection*) conn
  224792. {
  224793. (void) conn;
  224794. hasFinished = true;
  224795. initialised = true;
  224796. if (runLoopThread != 0)
  224797. runLoopThread->signalThreadShouldExit();
  224798. }
  224799. - (BOOL) isOpen
  224800. {
  224801. return connection != 0 && ! hasFailed;
  224802. }
  224803. - (int) readPosition
  224804. {
  224805. return position;
  224806. }
  224807. - (int) read: (char*) dest numBytes: (int) numNeeded
  224808. {
  224809. int numDone = 0;
  224810. while (numNeeded > 0)
  224811. {
  224812. int available = jmin (numNeeded, (int) [data length]);
  224813. if (available > 0)
  224814. {
  224815. [dataLock lock];
  224816. [data getBytes: dest length: available];
  224817. [data replaceBytesInRange: NSMakeRange (0, available) withBytes: nil length: 0];
  224818. [dataLock unlock];
  224819. numDone += available;
  224820. numNeeded -= available;
  224821. dest += available;
  224822. }
  224823. else
  224824. {
  224825. if (hasFailed || hasFinished)
  224826. break;
  224827. Thread::sleep (1);
  224828. }
  224829. }
  224830. position += numDone;
  224831. return numDone;
  224832. }
  224833. - (void) stop
  224834. {
  224835. [connection cancel];
  224836. if (runLoopThread != 0)
  224837. runLoopThread->stopThread (10000);
  224838. }
  224839. @end
  224840. BEGIN_JUCE_NAMESPACE
  224841. void* juce_openInternetFile (const String& url,
  224842. const String& headers,
  224843. const MemoryBlock& postData,
  224844. const bool isPost,
  224845. URL::OpenStreamProgressCallback* callback,
  224846. void* callbackContext,
  224847. int timeOutMs)
  224848. {
  224849. const ScopedAutoReleasePool pool;
  224850. NSMutableURLRequest* req = [NSMutableURLRequest
  224851. requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  224852. cachePolicy: NSURLRequestUseProtocolCachePolicy
  224853. timeoutInterval: timeOutMs <= 0 ? 60.0 : (timeOutMs / 1000.0)];
  224854. if (req == nil)
  224855. return 0;
  224856. [req setHTTPMethod: isPost ? @"POST" : @"GET"];
  224857. //[req setCachePolicy: NSURLRequestReloadIgnoringLocalAndRemoteCacheData];
  224858. StringArray headerLines;
  224859. headerLines.addLines (headers);
  224860. headerLines.removeEmptyStrings (true);
  224861. for (int i = 0; i < headerLines.size(); ++i)
  224862. {
  224863. const String key (headerLines[i].upToFirstOccurrenceOf (":", false, false).trim());
  224864. const String value (headerLines[i].fromFirstOccurrenceOf (":", false, false).trim());
  224865. if (key.isNotEmpty() && value.isNotEmpty())
  224866. [req addValue: juceStringToNS (value) forHTTPHeaderField: juceStringToNS (key)];
  224867. }
  224868. if (isPost && postData.getSize() > 0)
  224869. {
  224870. [req setHTTPBody: [NSData dataWithBytes: postData.getData()
  224871. length: postData.getSize()]];
  224872. }
  224873. JuceURLConnection* const s = [[JuceURLConnection alloc] initWithRequest: req
  224874. withCallback: callback
  224875. withContext: callbackContext];
  224876. if ([s isOpen])
  224877. return s;
  224878. [s release];
  224879. return 0;
  224880. }
  224881. void juce_closeInternetFile (void* handle)
  224882. {
  224883. JuceURLConnection* const s = (JuceURLConnection*) handle;
  224884. if (s != 0)
  224885. {
  224886. const ScopedAutoReleasePool pool;
  224887. [s stop];
  224888. [s release];
  224889. }
  224890. }
  224891. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  224892. {
  224893. JuceURLConnection* const s = (JuceURLConnection*) handle;
  224894. if (s != 0)
  224895. {
  224896. const ScopedAutoReleasePool pool;
  224897. return [s read: (char*) buffer numBytes: bytesToRead];
  224898. }
  224899. return 0;
  224900. }
  224901. int64 juce_getInternetFileContentLength (void* handle)
  224902. {
  224903. JuceURLConnection* const s = (JuceURLConnection*) handle;
  224904. if (s != 0)
  224905. return s->contentLength;
  224906. return -1;
  224907. }
  224908. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers)
  224909. {
  224910. JuceURLConnection* const s = (JuceURLConnection*) handle;
  224911. if (s != 0 && s->headers != 0)
  224912. {
  224913. NSEnumerator* enumerator = [s->headers keyEnumerator];
  224914. NSString* key;
  224915. while ((key = [enumerator nextObject]) != nil)
  224916. headers.set (nsStringToJuce (key),
  224917. nsStringToJuce ((NSString*) [s->headers objectForKey: key]));
  224918. }
  224919. }
  224920. int juce_seekInInternetFile (void* handle, int /*newPosition*/)
  224921. {
  224922. JuceURLConnection* const s = (JuceURLConnection*) handle;
  224923. if (s != 0)
  224924. return [s readPosition];
  224925. return 0;
  224926. }
  224927. #endif
  224928. /*** End of inlined file: juce_mac_Network.mm ***/
  224929. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  224930. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224931. // compiled on its own).
  224932. #if JUCE_INCLUDED_FILE
  224933. struct NamedPipeInternal
  224934. {
  224935. String pipeInName, pipeOutName;
  224936. int pipeIn, pipeOut;
  224937. bool volatile createdPipe, blocked, stopReadOperation;
  224938. static void signalHandler (int) {}
  224939. };
  224940. void NamedPipe::cancelPendingReads()
  224941. {
  224942. while (internal != 0 && static_cast <NamedPipeInternal*> (internal)->blocked)
  224943. {
  224944. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  224945. intern->stopReadOperation = true;
  224946. char buffer [1] = { 0 };
  224947. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  224948. (void) bytesWritten;
  224949. int timeout = 2000;
  224950. while (intern->blocked && --timeout >= 0)
  224951. Thread::sleep (2);
  224952. intern->stopReadOperation = false;
  224953. }
  224954. }
  224955. void NamedPipe::close()
  224956. {
  224957. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  224958. if (intern != 0)
  224959. {
  224960. internal = 0;
  224961. if (intern->pipeIn != -1)
  224962. ::close (intern->pipeIn);
  224963. if (intern->pipeOut != -1)
  224964. ::close (intern->pipeOut);
  224965. if (intern->createdPipe)
  224966. {
  224967. unlink (intern->pipeInName.toUTF8());
  224968. unlink (intern->pipeOutName.toUTF8());
  224969. }
  224970. delete intern;
  224971. }
  224972. }
  224973. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  224974. {
  224975. close();
  224976. NamedPipeInternal* const intern = new NamedPipeInternal();
  224977. internal = intern;
  224978. intern->createdPipe = createPipe;
  224979. intern->blocked = false;
  224980. intern->stopReadOperation = false;
  224981. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  224982. siginterrupt (SIGPIPE, 1);
  224983. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  224984. intern->pipeInName = pipePath + "_in";
  224985. intern->pipeOutName = pipePath + "_out";
  224986. intern->pipeIn = -1;
  224987. intern->pipeOut = -1;
  224988. if (createPipe)
  224989. {
  224990. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  224991. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  224992. {
  224993. delete intern;
  224994. internal = 0;
  224995. return false;
  224996. }
  224997. }
  224998. return true;
  224999. }
  225000. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  225001. {
  225002. int bytesRead = -1;
  225003. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  225004. if (intern != 0)
  225005. {
  225006. intern->blocked = true;
  225007. if (intern->pipeIn == -1)
  225008. {
  225009. if (intern->createdPipe)
  225010. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  225011. else
  225012. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  225013. if (intern->pipeIn == -1)
  225014. {
  225015. intern->blocked = false;
  225016. return -1;
  225017. }
  225018. }
  225019. bytesRead = 0;
  225020. char* p = static_cast<char*> (destBuffer);
  225021. while (bytesRead < maxBytesToRead)
  225022. {
  225023. const int bytesThisTime = maxBytesToRead - bytesRead;
  225024. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  225025. if (numRead <= 0 || intern->stopReadOperation)
  225026. {
  225027. bytesRead = -1;
  225028. break;
  225029. }
  225030. bytesRead += numRead;
  225031. p += bytesRead;
  225032. }
  225033. intern->blocked = false;
  225034. }
  225035. return bytesRead;
  225036. }
  225037. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  225038. {
  225039. int bytesWritten = -1;
  225040. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  225041. if (intern != 0)
  225042. {
  225043. if (intern->pipeOut == -1)
  225044. {
  225045. if (intern->createdPipe)
  225046. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  225047. else
  225048. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  225049. if (intern->pipeOut == -1)
  225050. {
  225051. return -1;
  225052. }
  225053. }
  225054. const char* p = static_cast<const char*> (sourceBuffer);
  225055. bytesWritten = 0;
  225056. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  225057. while (bytesWritten < numBytesToWrite
  225058. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  225059. {
  225060. const int bytesThisTime = numBytesToWrite - bytesWritten;
  225061. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  225062. if (numWritten <= 0)
  225063. {
  225064. bytesWritten = -1;
  225065. break;
  225066. }
  225067. bytesWritten += numWritten;
  225068. p += bytesWritten;
  225069. }
  225070. }
  225071. return bytesWritten;
  225072. }
  225073. #endif
  225074. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  225075. /*** Start of inlined file: juce_mac_Threads.mm ***/
  225076. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225077. // compiled on its own).
  225078. #if JUCE_INCLUDED_FILE
  225079. /*
  225080. Note that a lot of methods that you'd expect to find in this file actually
  225081. live in juce_posix_SharedCode.h!
  225082. */
  225083. bool Process::isForegroundProcess()
  225084. {
  225085. #if JUCE_MAC
  225086. return [NSApp isActive];
  225087. #else
  225088. return true; // xxx change this if more than one app is ever possible on the iPhone!
  225089. #endif
  225090. }
  225091. void Process::raisePrivilege()
  225092. {
  225093. jassertfalse;
  225094. }
  225095. void Process::lowerPrivilege()
  225096. {
  225097. jassertfalse;
  225098. }
  225099. void Process::terminate()
  225100. {
  225101. exit (0);
  225102. }
  225103. void Process::setPriority (ProcessPriority)
  225104. {
  225105. // xxx
  225106. }
  225107. #endif
  225108. /*** End of inlined file: juce_mac_Threads.mm ***/
  225109. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  225110. /*
  225111. This file contains posix routines that are common to both the Linux and Mac builds.
  225112. It gets included directly in the cpp files for these platforms.
  225113. */
  225114. CriticalSection::CriticalSection() throw()
  225115. {
  225116. pthread_mutexattr_t atts;
  225117. pthread_mutexattr_init (&atts);
  225118. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  225119. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  225120. pthread_mutex_init (&internal, &atts);
  225121. }
  225122. CriticalSection::~CriticalSection() throw()
  225123. {
  225124. pthread_mutex_destroy (&internal);
  225125. }
  225126. void CriticalSection::enter() const throw()
  225127. {
  225128. pthread_mutex_lock (&internal);
  225129. }
  225130. bool CriticalSection::tryEnter() const throw()
  225131. {
  225132. return pthread_mutex_trylock (&internal) == 0;
  225133. }
  225134. void CriticalSection::exit() const throw()
  225135. {
  225136. pthread_mutex_unlock (&internal);
  225137. }
  225138. class WaitableEventImpl
  225139. {
  225140. public:
  225141. WaitableEventImpl (const bool manualReset_)
  225142. : triggered (false),
  225143. manualReset (manualReset_)
  225144. {
  225145. pthread_cond_init (&condition, 0);
  225146. pthread_mutexattr_t atts;
  225147. pthread_mutexattr_init (&atts);
  225148. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  225149. pthread_mutex_init (&mutex, &atts);
  225150. }
  225151. ~WaitableEventImpl()
  225152. {
  225153. pthread_cond_destroy (&condition);
  225154. pthread_mutex_destroy (&mutex);
  225155. }
  225156. bool wait (const int timeOutMillisecs) throw()
  225157. {
  225158. pthread_mutex_lock (&mutex);
  225159. if (! triggered)
  225160. {
  225161. if (timeOutMillisecs < 0)
  225162. {
  225163. do
  225164. {
  225165. pthread_cond_wait (&condition, &mutex);
  225166. }
  225167. while (! triggered);
  225168. }
  225169. else
  225170. {
  225171. struct timeval now;
  225172. gettimeofday (&now, 0);
  225173. struct timespec time;
  225174. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  225175. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  225176. if (time.tv_nsec >= 1000000000)
  225177. {
  225178. time.tv_nsec -= 1000000000;
  225179. time.tv_sec++;
  225180. }
  225181. do
  225182. {
  225183. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  225184. {
  225185. pthread_mutex_unlock (&mutex);
  225186. return false;
  225187. }
  225188. }
  225189. while (! triggered);
  225190. }
  225191. }
  225192. if (! manualReset)
  225193. triggered = false;
  225194. pthread_mutex_unlock (&mutex);
  225195. return true;
  225196. }
  225197. void signal() throw()
  225198. {
  225199. pthread_mutex_lock (&mutex);
  225200. triggered = true;
  225201. pthread_cond_broadcast (&condition);
  225202. pthread_mutex_unlock (&mutex);
  225203. }
  225204. void reset() throw()
  225205. {
  225206. pthread_mutex_lock (&mutex);
  225207. triggered = false;
  225208. pthread_mutex_unlock (&mutex);
  225209. }
  225210. private:
  225211. pthread_cond_t condition;
  225212. pthread_mutex_t mutex;
  225213. bool triggered;
  225214. const bool manualReset;
  225215. WaitableEventImpl (const WaitableEventImpl&);
  225216. WaitableEventImpl& operator= (const WaitableEventImpl&);
  225217. };
  225218. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  225219. : internal (new WaitableEventImpl (manualReset))
  225220. {
  225221. }
  225222. WaitableEvent::~WaitableEvent() throw()
  225223. {
  225224. delete static_cast <WaitableEventImpl*> (internal);
  225225. }
  225226. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  225227. {
  225228. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  225229. }
  225230. void WaitableEvent::signal() const throw()
  225231. {
  225232. static_cast <WaitableEventImpl*> (internal)->signal();
  225233. }
  225234. void WaitableEvent::reset() const throw()
  225235. {
  225236. static_cast <WaitableEventImpl*> (internal)->reset();
  225237. }
  225238. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  225239. {
  225240. struct timespec time;
  225241. time.tv_sec = millisecs / 1000;
  225242. time.tv_nsec = (millisecs % 1000) * 1000000;
  225243. nanosleep (&time, 0);
  225244. }
  225245. const juce_wchar File::separator = '/';
  225246. const String File::separatorString ("/");
  225247. const File File::getCurrentWorkingDirectory()
  225248. {
  225249. HeapBlock<char> heapBuffer;
  225250. char localBuffer [1024];
  225251. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  225252. int bufferSize = 4096;
  225253. while (cwd == 0 && errno == ERANGE)
  225254. {
  225255. heapBuffer.malloc (bufferSize);
  225256. cwd = getcwd (heapBuffer, bufferSize - 1);
  225257. bufferSize += 1024;
  225258. }
  225259. return File (String::fromUTF8 (cwd));
  225260. }
  225261. bool File::setAsCurrentWorkingDirectory() const
  225262. {
  225263. return chdir (getFullPathName().toUTF8()) == 0;
  225264. }
  225265. namespace
  225266. {
  225267. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  225268. typedef struct stat64 juce_statStruct; // (need to use the 64-bit version to work around a simulator bug)
  225269. #else
  225270. typedef struct stat juce_statStruct;
  225271. #endif
  225272. bool juce_stat (const String& fileName, juce_statStruct& info)
  225273. {
  225274. return fileName.isNotEmpty()
  225275. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  225276. && (stat64 (fileName.toUTF8(), &info) == 0);
  225277. #else
  225278. && (stat (fileName.toUTF8(), &info) == 0);
  225279. #endif
  225280. }
  225281. // if this file doesn't exist, find a parent of it that does..
  225282. bool juce_doStatFS (File f, struct statfs& result)
  225283. {
  225284. for (int i = 5; --i >= 0;)
  225285. {
  225286. if (f.exists())
  225287. break;
  225288. f = f.getParentDirectory();
  225289. }
  225290. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  225291. }
  225292. }
  225293. bool File::isDirectory() const
  225294. {
  225295. juce_statStruct info;
  225296. return fullPath.isEmpty()
  225297. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  225298. }
  225299. bool File::exists() const
  225300. {
  225301. juce_statStruct info;
  225302. return fullPath.isNotEmpty()
  225303. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  225304. && (lstat64 (fullPath.toUTF8(), &info) == 0);
  225305. #else
  225306. && (lstat (fullPath.toUTF8(), &info) == 0);
  225307. #endif
  225308. }
  225309. bool File::existsAsFile() const
  225310. {
  225311. return exists() && ! isDirectory();
  225312. }
  225313. int64 File::getSize() const
  225314. {
  225315. juce_statStruct info;
  225316. return juce_stat (fullPath, info) ? info.st_size : 0;
  225317. }
  225318. bool File::hasWriteAccess() const
  225319. {
  225320. if (exists())
  225321. return access (fullPath.toUTF8(), W_OK) == 0;
  225322. if ((! isDirectory()) && fullPath.containsChar (separator))
  225323. return getParentDirectory().hasWriteAccess();
  225324. return false;
  225325. }
  225326. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  225327. {
  225328. juce_statStruct info;
  225329. if (! juce_stat (fullPath, info))
  225330. return false;
  225331. info.st_mode &= 0777; // Just permissions
  225332. if (shouldBeReadOnly)
  225333. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  225334. else
  225335. // Give everybody write permission?
  225336. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  225337. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  225338. }
  225339. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  225340. {
  225341. modificationTime = 0;
  225342. accessTime = 0;
  225343. creationTime = 0;
  225344. juce_statStruct info;
  225345. if (juce_stat (fullPath, info))
  225346. {
  225347. modificationTime = (int64) info.st_mtime * 1000;
  225348. accessTime = (int64) info.st_atime * 1000;
  225349. creationTime = (int64) info.st_ctime * 1000;
  225350. }
  225351. }
  225352. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  225353. {
  225354. struct utimbuf times;
  225355. times.actime = (time_t) (accessTime / 1000);
  225356. times.modtime = (time_t) (modificationTime / 1000);
  225357. return utime (fullPath.toUTF8(), &times) == 0;
  225358. }
  225359. bool File::deleteFile() const
  225360. {
  225361. if (! exists())
  225362. return true;
  225363. else if (isDirectory())
  225364. return rmdir (fullPath.toUTF8()) == 0;
  225365. else
  225366. return remove (fullPath.toUTF8()) == 0;
  225367. }
  225368. bool File::moveInternal (const File& dest) const
  225369. {
  225370. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  225371. return true;
  225372. if (hasWriteAccess() && copyInternal (dest))
  225373. {
  225374. if (deleteFile())
  225375. return true;
  225376. dest.deleteFile();
  225377. }
  225378. return false;
  225379. }
  225380. void File::createDirectoryInternal (const String& fileName) const
  225381. {
  225382. mkdir (fileName.toUTF8(), 0777);
  225383. }
  225384. int64 juce_fileSetPosition (void* handle, int64 pos)
  225385. {
  225386. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  225387. return pos;
  225388. return -1;
  225389. }
  225390. void FileInputStream::openHandle()
  225391. {
  225392. totalSize = file.getSize();
  225393. const int f = open (file.getFullPathName().toUTF8(), O_RDONLY, 00644);
  225394. if (f != -1)
  225395. fileHandle = (void*) f;
  225396. }
  225397. void FileInputStream::closeHandle()
  225398. {
  225399. if (fileHandle != 0)
  225400. {
  225401. close ((int) (pointer_sized_int) fileHandle);
  225402. fileHandle = 0;
  225403. }
  225404. }
  225405. size_t FileInputStream::readInternal (void* const buffer, const size_t numBytes)
  225406. {
  225407. if (fileHandle != 0)
  225408. return jmax ((ssize_t) 0, ::read ((int) (pointer_sized_int) fileHandle, buffer, numBytes));
  225409. return 0;
  225410. }
  225411. void FileOutputStream::openHandle()
  225412. {
  225413. if (file.exists())
  225414. {
  225415. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  225416. if (f != -1)
  225417. {
  225418. currentPosition = lseek (f, 0, SEEK_END);
  225419. if (currentPosition >= 0)
  225420. fileHandle = (void*) f;
  225421. else
  225422. close (f);
  225423. }
  225424. }
  225425. else
  225426. {
  225427. const int f = open (file.getFullPathName().toUTF8(), O_RDWR + O_CREAT, 00644);
  225428. if (f != -1)
  225429. fileHandle = (void*) f;
  225430. }
  225431. }
  225432. void FileOutputStream::closeHandle()
  225433. {
  225434. if (fileHandle != 0)
  225435. {
  225436. close ((int) (pointer_sized_int) fileHandle);
  225437. fileHandle = 0;
  225438. }
  225439. }
  225440. int FileOutputStream::writeInternal (const void* const data, const int numBytes)
  225441. {
  225442. if (fileHandle != 0)
  225443. return (int) ::write ((int) (pointer_sized_int) fileHandle, data, numBytes);
  225444. return 0;
  225445. }
  225446. void FileOutputStream::flushInternal()
  225447. {
  225448. if (fileHandle != 0)
  225449. fsync ((int) (pointer_sized_int) fileHandle);
  225450. }
  225451. const File juce_getExecutableFile()
  225452. {
  225453. Dl_info exeInfo;
  225454. dladdr ((const void*) juce_getExecutableFile, &exeInfo);
  225455. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  225456. }
  225457. int64 File::getBytesFreeOnVolume() const
  225458. {
  225459. struct statfs buf;
  225460. if (juce_doStatFS (*this, buf))
  225461. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  225462. return 0;
  225463. }
  225464. int64 File::getVolumeTotalSize() const
  225465. {
  225466. struct statfs buf;
  225467. if (juce_doStatFS (*this, buf))
  225468. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  225469. return 0;
  225470. }
  225471. const String File::getVolumeLabel() const
  225472. {
  225473. #if JUCE_MAC
  225474. struct VolAttrBuf
  225475. {
  225476. u_int32_t length;
  225477. attrreference_t mountPointRef;
  225478. char mountPointSpace [MAXPATHLEN];
  225479. } attrBuf;
  225480. struct attrlist attrList;
  225481. zerostruct (attrList);
  225482. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  225483. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  225484. File f (*this);
  225485. for (;;)
  225486. {
  225487. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  225488. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  225489. (int) attrBuf.mountPointRef.attr_length);
  225490. const File parent (f.getParentDirectory());
  225491. if (f == parent)
  225492. break;
  225493. f = parent;
  225494. }
  225495. #endif
  225496. return String::empty;
  225497. }
  225498. int File::getVolumeSerialNumber() const
  225499. {
  225500. return 0; // xxx
  225501. }
  225502. void juce_runSystemCommand (const String& command)
  225503. {
  225504. int result = system (command.toUTF8());
  225505. (void) result;
  225506. }
  225507. const String juce_getOutputFromCommand (const String& command)
  225508. {
  225509. // slight bodge here, as we just pipe the output into a temp file and read it...
  225510. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  225511. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  225512. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  225513. String result (tempFile.loadFileAsString());
  225514. tempFile.deleteFile();
  225515. return result;
  225516. }
  225517. class InterProcessLock::Pimpl
  225518. {
  225519. public:
  225520. Pimpl (const String& name, const int timeOutMillisecs)
  225521. : handle (0), refCount (1)
  225522. {
  225523. #if JUCE_MAC
  225524. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  225525. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  225526. #else
  225527. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  225528. #endif
  225529. temp.create();
  225530. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  225531. if (handle != 0)
  225532. {
  225533. struct flock fl;
  225534. zerostruct (fl);
  225535. fl.l_whence = SEEK_SET;
  225536. fl.l_type = F_WRLCK;
  225537. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  225538. for (;;)
  225539. {
  225540. const int result = fcntl (handle, F_SETLK, &fl);
  225541. if (result >= 0)
  225542. return;
  225543. if (errno != EINTR)
  225544. {
  225545. if (timeOutMillisecs == 0
  225546. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  225547. break;
  225548. Thread::sleep (10);
  225549. }
  225550. }
  225551. }
  225552. closeFile();
  225553. }
  225554. ~Pimpl()
  225555. {
  225556. closeFile();
  225557. }
  225558. void closeFile()
  225559. {
  225560. if (handle != 0)
  225561. {
  225562. struct flock fl;
  225563. zerostruct (fl);
  225564. fl.l_whence = SEEK_SET;
  225565. fl.l_type = F_UNLCK;
  225566. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  225567. {}
  225568. close (handle);
  225569. handle = 0;
  225570. }
  225571. }
  225572. int handle, refCount;
  225573. };
  225574. InterProcessLock::InterProcessLock (const String& name_)
  225575. : name (name_)
  225576. {
  225577. }
  225578. InterProcessLock::~InterProcessLock()
  225579. {
  225580. }
  225581. bool InterProcessLock::enter (const int timeOutMillisecs)
  225582. {
  225583. const ScopedLock sl (lock);
  225584. if (pimpl == 0)
  225585. {
  225586. pimpl = new Pimpl (name, timeOutMillisecs);
  225587. if (pimpl->handle == 0)
  225588. pimpl = 0;
  225589. }
  225590. else
  225591. {
  225592. pimpl->refCount++;
  225593. }
  225594. return pimpl != 0;
  225595. }
  225596. void InterProcessLock::exit()
  225597. {
  225598. const ScopedLock sl (lock);
  225599. // Trying to release the lock too many times!
  225600. jassert (pimpl != 0);
  225601. if (pimpl != 0 && --(pimpl->refCount) == 0)
  225602. pimpl = 0;
  225603. }
  225604. void JUCE_API juce_threadEntryPoint (void*);
  225605. void* threadEntryProc (void* userData)
  225606. {
  225607. JUCE_AUTORELEASEPOOL
  225608. juce_threadEntryPoint (userData);
  225609. return 0;
  225610. }
  225611. void* juce_createThread (void* userData)
  225612. {
  225613. pthread_t handle = 0;
  225614. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  225615. {
  225616. pthread_detach (handle);
  225617. return (void*) handle;
  225618. }
  225619. return 0;
  225620. }
  225621. void juce_killThread (void* handle)
  225622. {
  225623. if (handle != 0)
  225624. pthread_cancel ((pthread_t) handle);
  225625. }
  225626. void juce_setCurrentThreadName (const String& /*name*/)
  225627. {
  225628. }
  225629. bool juce_setThreadPriority (void* handle, int priority)
  225630. {
  225631. struct sched_param param;
  225632. int policy;
  225633. priority = jlimit (0, 10, priority);
  225634. if (handle == 0)
  225635. handle = (void*) pthread_self();
  225636. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) != 0)
  225637. return false;
  225638. policy = priority == 0 ? SCHED_OTHER : SCHED_RR;
  225639. const int minPriority = sched_get_priority_min (policy);
  225640. const int maxPriority = sched_get_priority_max (policy);
  225641. param.sched_priority = ((maxPriority - minPriority) * priority) / 10 + minPriority;
  225642. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  225643. }
  225644. Thread::ThreadID Thread::getCurrentThreadId()
  225645. {
  225646. return (ThreadID) pthread_self();
  225647. }
  225648. void Thread::yield()
  225649. {
  225650. sched_yield();
  225651. }
  225652. /* Remove this macro if you're having problems compiling the cpu affinity
  225653. calls (the API for these has changed about quite a bit in various Linux
  225654. versions, and a lot of distros seem to ship with obsolete versions)
  225655. */
  225656. #if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
  225657. #define SUPPORT_AFFINITIES 1
  225658. #endif
  225659. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  225660. {
  225661. #if SUPPORT_AFFINITIES
  225662. cpu_set_t affinity;
  225663. CPU_ZERO (&affinity);
  225664. for (int i = 0; i < 32; ++i)
  225665. if ((affinityMask & (1 << i)) != 0)
  225666. CPU_SET (i, &affinity);
  225667. /*
  225668. N.B. If this line causes a compile error, then you've probably not got the latest
  225669. version of glibc installed.
  225670. If you don't want to update your copy of glibc and don't care about cpu affinities,
  225671. then you can just disable all this stuff by setting the SUPPORT_AFFINITIES macro to 0.
  225672. */
  225673. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  225674. sched_yield();
  225675. #else
  225676. /* affinities aren't supported because either the appropriate header files weren't found,
  225677. or the SUPPORT_AFFINITIES macro was turned off
  225678. */
  225679. jassertfalse;
  225680. #endif
  225681. }
  225682. /*** End of inlined file: juce_posix_SharedCode.h ***/
  225683. /*** Start of inlined file: juce_mac_Files.mm ***/
  225684. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225685. // compiled on its own).
  225686. #if JUCE_INCLUDED_FILE
  225687. /*
  225688. Note that a lot of methods that you'd expect to find in this file actually
  225689. live in juce_posix_SharedCode.h!
  225690. */
  225691. bool File::copyInternal (const File& dest) const
  225692. {
  225693. const ScopedAutoReleasePool pool;
  225694. NSFileManager* fm = [NSFileManager defaultManager];
  225695. return [fm fileExistsAtPath: juceStringToNS (fullPath)]
  225696. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  225697. && [fm copyItemAtPath: juceStringToNS (fullPath)
  225698. toPath: juceStringToNS (dest.getFullPathName())
  225699. error: nil];
  225700. #else
  225701. && [fm copyPath: juceStringToNS (fullPath)
  225702. toPath: juceStringToNS (dest.getFullPathName())
  225703. handler: nil];
  225704. #endif
  225705. }
  225706. void File::findFileSystemRoots (Array<File>& destArray)
  225707. {
  225708. destArray.add (File ("/"));
  225709. }
  225710. namespace
  225711. {
  225712. bool isFileOnDriveType (const File& f, const char* const* types)
  225713. {
  225714. struct statfs buf;
  225715. if (juce_doStatFS (f, buf))
  225716. {
  225717. const String type (buf.f_fstypename);
  225718. while (*types != 0)
  225719. if (type.equalsIgnoreCase (*types++))
  225720. return true;
  225721. }
  225722. return false;
  225723. }
  225724. bool juce_isHiddenFile (const String& path)
  225725. {
  225726. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6
  225727. const ScopedAutoReleasePool pool;
  225728. NSNumber* hidden = nil;
  225729. NSError* err = nil;
  225730. return [[NSURL fileURLWithPath: juceStringToNS (path)]
  225731. getResourceValue: &hidden forKey: NSURLIsHiddenKey error: &err]
  225732. && [hidden boolValue];
  225733. #else
  225734. #if JUCE_IOS
  225735. return File (path).getFileName().startsWithChar ('.');
  225736. #else
  225737. FSRef ref;
  225738. LSItemInfoRecord info;
  225739. return FSPathMakeRefWithOptions ((const UInt8*) path.toUTF8(), kFSPathMakeRefDoNotFollowLeafSymlink, &ref, 0) == noErr
  225740. && LSCopyItemInfoForRef (&ref, kLSRequestBasicFlagsOnly, &info) == noErr
  225741. && (info.flags & kLSItemInfoIsInvisible) != 0;
  225742. #endif
  225743. #endif
  225744. }
  225745. #if JUCE_IOS
  225746. const String getIOSSystemLocation (NSSearchPathDirectory type)
  225747. {
  225748. return nsStringToJuce ([NSSearchPathForDirectoriesInDomains (type, NSUserDomainMask, YES)
  225749. objectAtIndex: 0]);
  225750. }
  225751. #endif
  225752. }
  225753. bool File::isOnCDRomDrive() const
  225754. {
  225755. const char* const cdTypes[] = { "cd9660", "cdfs", "cddafs", "udf", 0 };
  225756. return isFileOnDriveType (*this, cdTypes);
  225757. }
  225758. bool File::isOnHardDisk() const
  225759. {
  225760. const char* const nonHDTypes[] = { "nfs", "smbfs", "ramfs", 0 };
  225761. return ! (isOnCDRomDrive() || isFileOnDriveType (*this, nonHDTypes));
  225762. }
  225763. bool File::isOnRemovableDrive() const
  225764. {
  225765. #if JUCE_IOS
  225766. return false; // xxx is this possible?
  225767. #else
  225768. const ScopedAutoReleasePool pool;
  225769. BOOL removable = false;
  225770. [[NSWorkspace sharedWorkspace]
  225771. getFileSystemInfoForPath: juceStringToNS (getFullPathName())
  225772. isRemovable: &removable
  225773. isWritable: nil
  225774. isUnmountable: nil
  225775. description: nil
  225776. type: nil];
  225777. return removable;
  225778. #endif
  225779. }
  225780. bool File::isHidden() const
  225781. {
  225782. return juce_isHiddenFile (getFullPathName());
  225783. }
  225784. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  225785. const File File::getSpecialLocation (const SpecialLocationType type)
  225786. {
  225787. const ScopedAutoReleasePool pool;
  225788. String resultPath;
  225789. switch (type)
  225790. {
  225791. case userHomeDirectory: resultPath = nsStringToJuce (NSHomeDirectory()); break;
  225792. #if JUCE_IOS
  225793. case userDocumentsDirectory: resultPath = getIOSSystemLocation (NSDocumentDirectory); break;
  225794. case userDesktopDirectory: resultPath = getIOSSystemLocation (NSDesktopDirectory); break;
  225795. case tempDirectory:
  225796. {
  225797. File tmp (getIOSSystemLocation (NSCachesDirectory));
  225798. tmp = tmp.getChildFile (juce_getExecutableFile().getFileNameWithoutExtension());
  225799. tmp.createDirectory();
  225800. return tmp.getFullPathName();
  225801. }
  225802. #else
  225803. case userDocumentsDirectory: resultPath = "~/Documents"; break;
  225804. case userDesktopDirectory: resultPath = "~/Desktop"; break;
  225805. case tempDirectory:
  225806. {
  225807. File tmp ("~/Library/Caches/" + juce_getExecutableFile().getFileNameWithoutExtension());
  225808. tmp.createDirectory();
  225809. return tmp.getFullPathName();
  225810. }
  225811. #endif
  225812. case userMusicDirectory: resultPath = "~/Music"; break;
  225813. case userMoviesDirectory: resultPath = "~/Movies"; break;
  225814. case userApplicationDataDirectory: resultPath = "~/Library"; break;
  225815. case commonApplicationDataDirectory: resultPath = "/Library"; break;
  225816. case globalApplicationsDirectory: resultPath = "/Applications"; break;
  225817. case invokedExecutableFile:
  225818. if (juce_Argv0 != 0)
  225819. return File (String::fromUTF8 (juce_Argv0));
  225820. // deliberate fall-through...
  225821. case currentExecutableFile:
  225822. return juce_getExecutableFile();
  225823. case currentApplicationFile:
  225824. {
  225825. const File exe (juce_getExecutableFile());
  225826. const File parent (exe.getParentDirectory());
  225827. #if JUCE_IOS
  225828. return parent;
  225829. #else
  225830. return parent.getFullPathName().endsWithIgnoreCase ("Contents/MacOS")
  225831. ? parent.getParentDirectory().getParentDirectory()
  225832. : exe;
  225833. #endif
  225834. }
  225835. case hostApplicationPath:
  225836. {
  225837. unsigned int size = 8192;
  225838. HeapBlock<char> buffer;
  225839. buffer.calloc (size + 8);
  225840. _NSGetExecutablePath (buffer.getData(), &size);
  225841. return String::fromUTF8 (buffer, size);
  225842. }
  225843. default:
  225844. jassertfalse; // unknown type?
  225845. break;
  225846. }
  225847. if (resultPath.isNotEmpty())
  225848. return File (PlatformUtilities::convertToPrecomposedUnicode (resultPath));
  225849. return File::nonexistent;
  225850. }
  225851. const String File::getVersion() const
  225852. {
  225853. const ScopedAutoReleasePool pool;
  225854. String result;
  225855. NSBundle* bundle = [NSBundle bundleWithPath: juceStringToNS (getFullPathName())];
  225856. if (bundle != 0)
  225857. {
  225858. NSDictionary* info = [bundle infoDictionary];
  225859. if (info != 0)
  225860. {
  225861. NSString* name = [info valueForKey: @"CFBundleShortVersionString"];
  225862. if (name != nil)
  225863. result = nsStringToJuce (name);
  225864. }
  225865. }
  225866. return result;
  225867. }
  225868. const File File::getLinkedTarget() const
  225869. {
  225870. #if JUCE_IOS || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MIN_ALLOWED >= MAC_OS_X_VERSION_10_5)
  225871. NSString* dest = [[NSFileManager defaultManager] destinationOfSymbolicLinkAtPath: juceStringToNS (getFullPathName()) error: nil];
  225872. #else
  225873. // (the cast here avoids a deprecation warning)
  225874. NSString* dest = [((id) [NSFileManager defaultManager]) pathContentOfSymbolicLinkAtPath: juceStringToNS (getFullPathName())];
  225875. #endif
  225876. if (dest != nil)
  225877. return File (nsStringToJuce (dest));
  225878. return *this;
  225879. }
  225880. bool File::moveToTrash() const
  225881. {
  225882. if (! exists())
  225883. return true;
  225884. #if JUCE_IOS
  225885. return deleteFile(); //xxx is there a trashcan on the iPhone?
  225886. #else
  225887. const ScopedAutoReleasePool pool;
  225888. NSString* p = juceStringToNS (getFullPathName());
  225889. return [[NSWorkspace sharedWorkspace]
  225890. performFileOperation: NSWorkspaceRecycleOperation
  225891. source: [p stringByDeletingLastPathComponent]
  225892. destination: @""
  225893. files: [NSArray arrayWithObject: [p lastPathComponent]]
  225894. tag: nil ];
  225895. #endif
  225896. }
  225897. class DirectoryIterator::NativeIterator::Pimpl
  225898. {
  225899. public:
  225900. Pimpl (const File& directory, const String& wildCard_)
  225901. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  225902. wildCard (wildCard_),
  225903. enumerator (0)
  225904. {
  225905. const ScopedAutoReleasePool pool;
  225906. enumerator = [[[NSFileManager defaultManager] enumeratorAtPath: juceStringToNS (directory.getFullPathName())] retain];
  225907. wildcardUTF8 = wildCard.toUTF8();
  225908. }
  225909. ~Pimpl()
  225910. {
  225911. [enumerator release];
  225912. }
  225913. bool next (String& filenameFound,
  225914. bool* const isDir, bool* const isHidden, int64* const fileSize,
  225915. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  225916. {
  225917. const ScopedAutoReleasePool pool;
  225918. for (;;)
  225919. {
  225920. NSString* file;
  225921. if (enumerator == 0 || (file = [enumerator nextObject]) == 0)
  225922. return false;
  225923. [enumerator skipDescendents];
  225924. filenameFound = nsStringToJuce (file);
  225925. if (fnmatch (wildcardUTF8, filenameFound.toUTF8(), FNM_CASEFOLD) != 0)
  225926. continue;
  225927. const String path (parentDir + filenameFound);
  225928. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  225929. {
  225930. juce_statStruct info;
  225931. const bool statOk = juce_stat (path, info);
  225932. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  225933. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  225934. if (modTime != 0) *modTime = statOk ? (int64) info.st_mtime * 1000 : 0;
  225935. if (creationTime != 0) *creationTime = statOk ? (int64) info.st_ctime * 1000 : 0;
  225936. }
  225937. if (isHidden != 0)
  225938. *isHidden = juce_isHiddenFile (path);
  225939. if (isReadOnly != 0)
  225940. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  225941. return true;
  225942. }
  225943. }
  225944. private:
  225945. String parentDir, wildCard;
  225946. const char* wildcardUTF8;
  225947. NSDirectoryEnumerator* enumerator;
  225948. Pimpl (const Pimpl&);
  225949. Pimpl& operator= (const Pimpl&);
  225950. };
  225951. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  225952. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  225953. {
  225954. }
  225955. DirectoryIterator::NativeIterator::~NativeIterator()
  225956. {
  225957. }
  225958. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  225959. bool* const isDir, bool* const isHidden, int64* const fileSize,
  225960. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  225961. {
  225962. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  225963. }
  225964. bool juce_launchExecutable (const String& pathAndArguments)
  225965. {
  225966. const char* const argv[4] = { "/bin/sh", "-c", pathAndArguments.toUTF8(), 0 };
  225967. const int cpid = fork();
  225968. if (cpid == 0)
  225969. {
  225970. // Child process
  225971. if (execve (argv[0], (char**) argv, 0) < 0)
  225972. exit (0);
  225973. }
  225974. else
  225975. {
  225976. if (cpid < 0)
  225977. return false;
  225978. }
  225979. return true;
  225980. }
  225981. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  225982. {
  225983. #if JUCE_IOS
  225984. return [[UIApplication sharedApplication] openURL: [NSURL fileURLWithPath: juceStringToNS (fileName)]];
  225985. #else
  225986. const ScopedAutoReleasePool pool;
  225987. if (parameters.isEmpty())
  225988. {
  225989. return [[NSWorkspace sharedWorkspace] openFile: juceStringToNS (fileName)]
  225990. || [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: juceStringToNS (fileName)]];
  225991. }
  225992. bool ok = false;
  225993. if (PlatformUtilities::isBundle (fileName))
  225994. {
  225995. NSMutableArray* urls = [NSMutableArray array];
  225996. StringArray docs;
  225997. docs.addTokens (parameters, true);
  225998. for (int i = 0; i < docs.size(); ++i)
  225999. [urls addObject: juceStringToNS (docs[i])];
  226000. ok = [[NSWorkspace sharedWorkspace] openURLs: urls
  226001. withAppBundleIdentifier: [[NSBundle bundleWithPath: juceStringToNS (fileName)] bundleIdentifier]
  226002. options: 0
  226003. additionalEventParamDescriptor: nil
  226004. launchIdentifiers: nil];
  226005. }
  226006. else if (File (fileName).exists())
  226007. {
  226008. ok = juce_launchExecutable ("\"" + fileName + "\" " + parameters);
  226009. }
  226010. return ok;
  226011. #endif
  226012. }
  226013. void File::revealToUser() const
  226014. {
  226015. #if ! JUCE_IOS
  226016. if (exists())
  226017. [[NSWorkspace sharedWorkspace] selectFile: juceStringToNS (getFullPathName()) inFileViewerRootedAtPath: @""];
  226018. else if (getParentDirectory().exists())
  226019. getParentDirectory().revealToUser();
  226020. #endif
  226021. }
  226022. #if ! JUCE_IOS
  226023. bool PlatformUtilities::makeFSRefFromPath (FSRef* destFSRef, const String& path)
  226024. {
  226025. return FSPathMakeRef ((const UInt8*) path.toUTF8(), destFSRef, 0) == noErr;
  226026. }
  226027. const String PlatformUtilities::makePathFromFSRef (FSRef* file)
  226028. {
  226029. char path [2048];
  226030. zerostruct (path);
  226031. if (FSRefMakePath (file, (UInt8*) path, sizeof (path) - 1) == noErr)
  226032. return PlatformUtilities::convertToPrecomposedUnicode (String::fromUTF8 (path));
  226033. return String::empty;
  226034. }
  226035. #endif
  226036. OSType PlatformUtilities::getTypeOfFile (const String& filename)
  226037. {
  226038. const ScopedAutoReleasePool pool;
  226039. #if JUCE_IOS || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MIN_ALLOWED >= MAC_OS_X_VERSION_10_5)
  226040. NSDictionary* fileDict = [[NSFileManager defaultManager] attributesOfItemAtPath: juceStringToNS (filename) error: nil];
  226041. #else
  226042. // (the cast here avoids a deprecation warning)
  226043. NSDictionary* fileDict = [((id) [NSFileManager defaultManager]) fileAttributesAtPath: juceStringToNS (filename) traverseLink: NO];
  226044. #endif
  226045. return [fileDict fileHFSTypeCode];
  226046. }
  226047. bool PlatformUtilities::isBundle (const String& filename)
  226048. {
  226049. #if JUCE_IOS
  226050. return false; // xxx can't find a sensible way to do this without trying to open the bundle..
  226051. #else
  226052. const ScopedAutoReleasePool pool;
  226053. return [[NSWorkspace sharedWorkspace] isFilePackageAtPath: juceStringToNS (filename)];
  226054. #endif
  226055. }
  226056. #endif
  226057. /*** End of inlined file: juce_mac_Files.mm ***/
  226058. #if JUCE_IOS
  226059. /*** Start of inlined file: juce_iphone_MiscUtilities.mm ***/
  226060. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226061. // compiled on its own).
  226062. #if JUCE_INCLUDED_FILE
  226063. END_JUCE_NAMESPACE
  226064. @interface JuceAppStartupDelegate : NSObject <UIApplicationDelegate>
  226065. {
  226066. }
  226067. - (void) applicationDidFinishLaunching: (UIApplication*) application;
  226068. - (void) applicationWillTerminate: (UIApplication*) application;
  226069. @end
  226070. @implementation JuceAppStartupDelegate
  226071. - (void) applicationDidFinishLaunching: (UIApplication*) application
  226072. {
  226073. initialiseJuce_GUI();
  226074. if (! JUCEApplication::createInstance()->initialiseApp (String::empty))
  226075. exit (0);
  226076. }
  226077. - (void) applicationWillTerminate: (UIApplication*) application
  226078. {
  226079. JUCEApplication::appWillTerminateByForce();
  226080. }
  226081. @end
  226082. BEGIN_JUCE_NAMESPACE
  226083. int juce_iOSMain (int argc, const char* argv[])
  226084. {
  226085. return UIApplicationMain (argc, const_cast<char**> (argv), nil, @"JuceAppStartupDelegate");
  226086. }
  226087. ScopedAutoReleasePool::ScopedAutoReleasePool()
  226088. {
  226089. pool = [[NSAutoreleasePool alloc] init];
  226090. }
  226091. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  226092. {
  226093. [((NSAutoreleasePool*) pool) release];
  226094. }
  226095. void PlatformUtilities::beep()
  226096. {
  226097. //xxx
  226098. //AudioServicesPlaySystemSound ();
  226099. }
  226100. void PlatformUtilities::addItemToDock (const File& file)
  226101. {
  226102. }
  226103. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  226104. END_JUCE_NAMESPACE
  226105. @interface JuceAlertBoxDelegate : NSObject
  226106. {
  226107. @public
  226108. bool clickedOk;
  226109. }
  226110. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex;
  226111. @end
  226112. @implementation JuceAlertBoxDelegate
  226113. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex
  226114. {
  226115. clickedOk = (buttonIndex == 0);
  226116. alertView.hidden = true;
  226117. }
  226118. @end
  226119. BEGIN_JUCE_NAMESPACE
  226120. // (This function is used directly by other bits of code)
  226121. bool juce_iPhoneShowModalAlert (const String& title,
  226122. const String& bodyText,
  226123. NSString* okButtonText,
  226124. NSString* cancelButtonText)
  226125. {
  226126. const ScopedAutoReleasePool pool;
  226127. JuceAlertBoxDelegate* callback = [[JuceAlertBoxDelegate alloc] init];
  226128. UIAlertView* alert = [[UIAlertView alloc] initWithTitle: juceStringToNS (title)
  226129. message: juceStringToNS (bodyText)
  226130. delegate: callback
  226131. cancelButtonTitle: okButtonText
  226132. otherButtonTitles: cancelButtonText, nil];
  226133. [alert retain];
  226134. [alert show];
  226135. while (! alert.hidden && alert.superview != nil)
  226136. [[NSRunLoop mainRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  226137. const bool result = callback->clickedOk;
  226138. [alert release];
  226139. [callback release];
  226140. return result;
  226141. }
  226142. bool AlertWindow::showNativeDialogBox (const String& title,
  226143. const String& bodyText,
  226144. bool isOkCancel)
  226145. {
  226146. return juce_iPhoneShowModalAlert (title, bodyText,
  226147. @"OK",
  226148. isOkCancel ? @"Cancel" : nil);
  226149. }
  226150. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  226151. {
  226152. jassertfalse; // no such thing on the iphone!
  226153. return false;
  226154. }
  226155. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  226156. {
  226157. jassertfalse; // no such thing on the iphone!
  226158. return false;
  226159. }
  226160. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  226161. {
  226162. [[UIApplication sharedApplication] setIdleTimerDisabled: ! isEnabled];
  226163. }
  226164. bool Desktop::isScreenSaverEnabled()
  226165. {
  226166. return ! [[UIApplication sharedApplication] isIdleTimerDisabled];
  226167. }
  226168. #endif
  226169. #endif
  226170. /*** End of inlined file: juce_iphone_MiscUtilities.mm ***/
  226171. #else
  226172. /*** Start of inlined file: juce_mac_MiscUtilities.mm ***/
  226173. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226174. // compiled on its own).
  226175. #if JUCE_INCLUDED_FILE
  226176. ScopedAutoReleasePool::ScopedAutoReleasePool()
  226177. {
  226178. pool = [[NSAutoreleasePool alloc] init];
  226179. }
  226180. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  226181. {
  226182. [((NSAutoreleasePool*) pool) release];
  226183. }
  226184. void PlatformUtilities::beep()
  226185. {
  226186. NSBeep();
  226187. }
  226188. void PlatformUtilities::addItemToDock (const File& file)
  226189. {
  226190. // check that it's not already there...
  226191. if (! juce_getOutputFromCommand ("defaults read com.apple.dock persistent-apps")
  226192. .containsIgnoreCase (file.getFullPathName()))
  226193. {
  226194. 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>"
  226195. + file.getFullPathName() + "</string><key>_CFURLStringType</key><integer>0</integer></dict></dict></dict>\"");
  226196. juce_runSystemCommand ("osascript -e \"tell application \\\"Dock\\\" to quit\"");
  226197. }
  226198. }
  226199. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  226200. bool AlertWindow::showNativeDialogBox (const String& title,
  226201. const String& bodyText,
  226202. bool isOkCancel)
  226203. {
  226204. const ScopedAutoReleasePool pool;
  226205. return NSRunAlertPanel (juceStringToNS (title),
  226206. juceStringToNS (bodyText),
  226207. @"Ok",
  226208. isOkCancel ? @"Cancel" : nil,
  226209. nil) == NSAlertDefaultReturn;
  226210. }
  226211. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool /*canMoveFiles*/)
  226212. {
  226213. if (files.size() == 0)
  226214. return false;
  226215. MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource(0);
  226216. if (draggingSource == 0)
  226217. {
  226218. jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
  226219. return false;
  226220. }
  226221. Component* sourceComp = draggingSource->getComponentUnderMouse();
  226222. if (sourceComp == 0)
  226223. {
  226224. jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
  226225. return false;
  226226. }
  226227. const ScopedAutoReleasePool pool;
  226228. NSView* view = (NSView*) sourceComp->getWindowHandle();
  226229. if (view == 0)
  226230. return false;
  226231. NSPasteboard* pboard = [NSPasteboard pasteboardWithName: NSDragPboard];
  226232. [pboard declareTypes: [NSArray arrayWithObject: NSFilenamesPboardType]
  226233. owner: nil];
  226234. NSMutableArray* filesArray = [NSMutableArray arrayWithCapacity: 4];
  226235. for (int i = 0; i < files.size(); ++i)
  226236. [filesArray addObject: juceStringToNS (files[i])];
  226237. [pboard setPropertyList: filesArray
  226238. forType: NSFilenamesPboardType];
  226239. NSPoint dragPosition = [view convertPoint: [[[view window] currentEvent] locationInWindow]
  226240. fromView: nil];
  226241. dragPosition.x -= 16;
  226242. dragPosition.y -= 16;
  226243. [view dragImage: [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (files[0])]
  226244. at: dragPosition
  226245. offset: NSMakeSize (0, 0)
  226246. event: [[view window] currentEvent]
  226247. pasteboard: pboard
  226248. source: view
  226249. slideBack: YES];
  226250. return true;
  226251. }
  226252. bool DragAndDropContainer::performExternalDragDropOfText (const String& /*text*/)
  226253. {
  226254. jassertfalse; // not implemented!
  226255. return false;
  226256. }
  226257. bool Desktop::canUseSemiTransparentWindows() throw()
  226258. {
  226259. return true;
  226260. }
  226261. const Point<int> Desktop::getMousePosition()
  226262. {
  226263. const ScopedAutoReleasePool pool;
  226264. const NSPoint p ([NSEvent mouseLocation]);
  226265. return Point<int> (roundToInt (p.x), roundToInt ([[[NSScreen screens] objectAtIndex: 0] frame].size.height - p.y));
  226266. }
  226267. void Desktop::setMousePosition (const Point<int>& newPosition)
  226268. {
  226269. // this rubbish needs to be done around the warp call, to avoid causing a
  226270. // bizarre glitch..
  226271. CGAssociateMouseAndMouseCursorPosition (false);
  226272. CGWarpMouseCursorPosition (CGPointMake (newPosition.getX(), newPosition.getY()));
  226273. CGAssociateMouseAndMouseCursorPosition (true);
  226274. }
  226275. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  226276. {
  226277. return upright;
  226278. }
  226279. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  226280. class ScreenSaverDefeater : public Timer,
  226281. public DeletedAtShutdown
  226282. {
  226283. public:
  226284. ScreenSaverDefeater()
  226285. {
  226286. startTimer (10000);
  226287. timerCallback();
  226288. }
  226289. ~ScreenSaverDefeater() {}
  226290. void timerCallback()
  226291. {
  226292. if (Process::isForegroundProcess())
  226293. UpdateSystemActivity (UsrActivity);
  226294. }
  226295. };
  226296. static ScreenSaverDefeater* screenSaverDefeater = 0;
  226297. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  226298. {
  226299. if (isEnabled)
  226300. deleteAndZero (screenSaverDefeater);
  226301. else if (screenSaverDefeater == 0)
  226302. screenSaverDefeater = new ScreenSaverDefeater();
  226303. }
  226304. bool Desktop::isScreenSaverEnabled()
  226305. {
  226306. return screenSaverDefeater == 0;
  226307. }
  226308. #else
  226309. static IOPMAssertionID screenSaverDisablerID = 0;
  226310. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  226311. {
  226312. if (isEnabled)
  226313. {
  226314. if (screenSaverDisablerID != 0)
  226315. {
  226316. IOPMAssertionRelease (screenSaverDisablerID);
  226317. screenSaverDisablerID = 0;
  226318. }
  226319. }
  226320. else
  226321. {
  226322. if (screenSaverDisablerID == 0)
  226323. {
  226324. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  226325. IOPMAssertionCreateWithName (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  226326. CFSTR ("Juce"), &screenSaverDisablerID);
  226327. #else
  226328. IOPMAssertionCreate (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  226329. &screenSaverDisablerID);
  226330. #endif
  226331. }
  226332. }
  226333. }
  226334. bool Desktop::isScreenSaverEnabled()
  226335. {
  226336. return screenSaverDisablerID == 0;
  226337. }
  226338. #endif
  226339. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  226340. {
  226341. const ScopedAutoReleasePool pool;
  226342. monitorCoords.clear();
  226343. NSArray* screens = [NSScreen screens];
  226344. const CGFloat mainScreenBottom = [[[NSScreen screens] objectAtIndex: 0] frame].size.height;
  226345. for (unsigned int i = 0; i < [screens count]; ++i)
  226346. {
  226347. NSScreen* s = (NSScreen*) [screens objectAtIndex: i];
  226348. NSRect r = clipToWorkArea ? [s visibleFrame]
  226349. : [s frame];
  226350. r.origin.y = mainScreenBottom - (r.origin.y + r.size.height);
  226351. monitorCoords.add (convertToRectInt (r));
  226352. }
  226353. jassert (monitorCoords.size() > 0);
  226354. }
  226355. #endif
  226356. #endif
  226357. /*** End of inlined file: juce_mac_MiscUtilities.mm ***/
  226358. #endif
  226359. /*** Start of inlined file: juce_mac_Debugging.mm ***/
  226360. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226361. // compiled on its own).
  226362. #if JUCE_INCLUDED_FILE
  226363. void Logger::outputDebugString (const String& text)
  226364. {
  226365. std::cerr << text << std::endl;
  226366. }
  226367. JUCE_API bool JUCE_CALLTYPE juce_isRunningUnderDebugger()
  226368. {
  226369. static char testResult = 0;
  226370. if (testResult == 0)
  226371. {
  226372. struct kinfo_proc info;
  226373. int m[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid() };
  226374. size_t sz = sizeof (info);
  226375. sysctl (m, 4, &info, &sz, 0, 0);
  226376. testResult = ((info.kp_proc.p_flag & P_TRACED) != 0) ? 1 : -1;
  226377. }
  226378. return testResult > 0;
  226379. }
  226380. JUCE_API bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  226381. {
  226382. return juce_isRunningUnderDebugger();
  226383. }
  226384. #endif
  226385. /*** End of inlined file: juce_mac_Debugging.mm ***/
  226386. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  226387. #if JUCE_IOS
  226388. /*** Start of inlined file: juce_mac_Fonts.mm ***/
  226389. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226390. // compiled on its own).
  226391. #if JUCE_INCLUDED_FILE
  226392. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  226393. #define SUPPORT_10_4_FONTS 1
  226394. #define NEW_CGFONT_FUNCTIONS_UNAVAILABLE (CGFontCreateWithFontName == 0)
  226395. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  226396. #define SUPPORT_ONLY_10_4_FONTS 1
  226397. #endif
  226398. END_JUCE_NAMESPACE
  226399. @interface NSFont (PrivateHack)
  226400. - (NSGlyph) _defaultGlyphForChar: (unichar) theChar;
  226401. @end
  226402. BEGIN_JUCE_NAMESPACE
  226403. #endif
  226404. class MacTypeface : public Typeface
  226405. {
  226406. public:
  226407. MacTypeface (const Font& font)
  226408. : Typeface (font.getTypefaceName())
  226409. {
  226410. const ScopedAutoReleasePool pool;
  226411. renderingTransform = CGAffineTransformIdentity;
  226412. bool needsItalicTransform = false;
  226413. #if JUCE_IOS
  226414. NSString* fontName = juceStringToNS (font.getTypefaceName());
  226415. if (font.isItalic() || font.isBold())
  226416. {
  226417. NSArray* familyFonts = [UIFont fontNamesForFamilyName: juceStringToNS (font.getTypefaceName())];
  226418. for (NSString* i in familyFonts)
  226419. {
  226420. const String fn (nsStringToJuce (i));
  226421. const String afterDash (fn.fromFirstOccurrenceOf ("-", false, false));
  226422. const bool probablyBold = afterDash.containsIgnoreCase ("bold") || fn.endsWithIgnoreCase ("bold");
  226423. const bool probablyItalic = afterDash.containsIgnoreCase ("oblique")
  226424. || afterDash.containsIgnoreCase ("italic")
  226425. || fn.endsWithIgnoreCase ("oblique")
  226426. || fn.endsWithIgnoreCase ("italic");
  226427. if (probablyBold == font.isBold()
  226428. && probablyItalic == font.isItalic())
  226429. {
  226430. fontName = i;
  226431. needsItalicTransform = false;
  226432. break;
  226433. }
  226434. else if (probablyBold && (! probablyItalic) && probablyBold == font.isBold())
  226435. {
  226436. fontName = i;
  226437. needsItalicTransform = true; // not ideal, so carry on in case we find a better one
  226438. }
  226439. }
  226440. if (needsItalicTransform)
  226441. renderingTransform.c = 0.15f;
  226442. }
  226443. fontRef = CGFontCreateWithFontName ((CFStringRef) fontName);
  226444. const int ascender = abs (CGFontGetAscent (fontRef));
  226445. const float totalHeight = ascender + abs (CGFontGetDescent (fontRef));
  226446. ascent = ascender / totalHeight;
  226447. unitsToHeightScaleFactor = 1.0f / totalHeight;
  226448. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / totalHeight;
  226449. #else
  226450. nsFont = [NSFont fontWithName: juceStringToNS (font.getTypefaceName()) size: 1024];
  226451. if (font.isItalic())
  226452. {
  226453. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: nsFont
  226454. toHaveTrait: NSItalicFontMask];
  226455. if (newFont == nsFont)
  226456. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  226457. nsFont = newFont;
  226458. }
  226459. if (font.isBold())
  226460. nsFont = [[NSFontManager sharedFontManager] convertFont: nsFont toHaveTrait: NSBoldFontMask];
  226461. [nsFont retain];
  226462. ascent = std::abs ((float) [nsFont ascender]);
  226463. float totalSize = ascent + std::abs ((float) [nsFont descender]);
  226464. ascent /= totalSize;
  226465. pathTransform = AffineTransform::identity.scale (1.0f / totalSize, 1.0f / totalSize);
  226466. if (needsItalicTransform)
  226467. {
  226468. pathTransform = pathTransform.sheared (-0.15f, 0.0f);
  226469. renderingTransform.c = 0.15f;
  226470. }
  226471. #if SUPPORT_ONLY_10_4_FONTS
  226472. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  226473. if (atsFont == 0)
  226474. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  226475. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  226476. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  226477. unitsToHeightScaleFactor = 1.0f / totalHeight;
  226478. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  226479. #else
  226480. #if SUPPORT_10_4_FONTS
  226481. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  226482. {
  226483. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  226484. if (atsFont == 0)
  226485. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  226486. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  226487. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  226488. unitsToHeightScaleFactor = 1.0f / totalHeight;
  226489. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  226490. }
  226491. else
  226492. #endif
  226493. {
  226494. fontRef = CGFontCreateWithFontName ((CFStringRef) [nsFont fontName]);
  226495. const int totalHeight = abs (CGFontGetAscent (fontRef)) + abs (CGFontGetDescent (fontRef));
  226496. unitsToHeightScaleFactor = 1.0f / totalHeight;
  226497. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / (float) totalHeight;
  226498. }
  226499. #endif
  226500. #endif
  226501. }
  226502. ~MacTypeface()
  226503. {
  226504. #if ! JUCE_IOS
  226505. [nsFont release];
  226506. #endif
  226507. if (fontRef != 0)
  226508. CGFontRelease (fontRef);
  226509. }
  226510. float getAscent() const
  226511. {
  226512. return ascent;
  226513. }
  226514. float getDescent() const
  226515. {
  226516. return 1.0f - ascent;
  226517. }
  226518. float getStringWidth (const String& text)
  226519. {
  226520. if (fontRef == 0 || text.isEmpty())
  226521. return 0;
  226522. const int length = text.length();
  226523. HeapBlock <CGGlyph> glyphs;
  226524. createGlyphsForString (text, length, glyphs);
  226525. float x = 0;
  226526. #if SUPPORT_ONLY_10_4_FONTS
  226527. HeapBlock <NSSize> advances (length);
  226528. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  226529. for (int i = 0; i < length; ++i)
  226530. x += advances[i].width;
  226531. #else
  226532. #if SUPPORT_10_4_FONTS
  226533. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  226534. {
  226535. HeapBlock <NSSize> advances (length);
  226536. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast<NSGlyph*> (glyphs.getData()) count: length];
  226537. for (int i = 0; i < length; ++i)
  226538. x += advances[i].width;
  226539. }
  226540. else
  226541. #endif
  226542. {
  226543. HeapBlock <int> advances (length);
  226544. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  226545. for (int i = 0; i < length; ++i)
  226546. x += advances[i];
  226547. }
  226548. #endif
  226549. return x * unitsToHeightScaleFactor;
  226550. }
  226551. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  226552. {
  226553. xOffsets.add (0);
  226554. if (fontRef == 0 || text.isEmpty())
  226555. return;
  226556. const int length = text.length();
  226557. HeapBlock <CGGlyph> glyphs;
  226558. createGlyphsForString (text, length, glyphs);
  226559. #if SUPPORT_ONLY_10_4_FONTS
  226560. HeapBlock <NSSize> advances (length);
  226561. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  226562. int x = 0;
  226563. for (int i = 0; i < length; ++i)
  226564. {
  226565. x += advances[i].width;
  226566. xOffsets.add (x * unitsToHeightScaleFactor);
  226567. resultGlyphs.add (reinterpret_cast <NSGlyph*> (glyphs.getData())[i]);
  226568. }
  226569. #else
  226570. #if SUPPORT_10_4_FONTS
  226571. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  226572. {
  226573. HeapBlock <NSSize> advances (length);
  226574. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  226575. [nsFont getAdvancements: advances forGlyphs: nsGlyphs count: length];
  226576. float x = 0;
  226577. for (int i = 0; i < length; ++i)
  226578. {
  226579. x += advances[i].width;
  226580. xOffsets.add (x * unitsToHeightScaleFactor);
  226581. resultGlyphs.add (nsGlyphs[i]);
  226582. }
  226583. }
  226584. else
  226585. #endif
  226586. {
  226587. HeapBlock <int> advances (length);
  226588. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  226589. {
  226590. int x = 0;
  226591. for (int i = 0; i < length; ++i)
  226592. {
  226593. x += advances [i];
  226594. xOffsets.add (x * unitsToHeightScaleFactor);
  226595. resultGlyphs.add (glyphs[i]);
  226596. }
  226597. }
  226598. }
  226599. #endif
  226600. }
  226601. bool getOutlineForGlyph (int glyphNumber, Path& path)
  226602. {
  226603. #if JUCE_IOS
  226604. return false;
  226605. #else
  226606. if (nsFont == 0)
  226607. return false;
  226608. // we might need to apply a transform to the path, so it mustn't have anything else in it
  226609. jassert (path.isEmpty());
  226610. const ScopedAutoReleasePool pool;
  226611. NSBezierPath* bez = [NSBezierPath bezierPath];
  226612. [bez moveToPoint: NSMakePoint (0, 0)];
  226613. [bez appendBezierPathWithGlyph: (NSGlyph) glyphNumber
  226614. inFont: nsFont];
  226615. for (int i = 0; i < [bez elementCount]; ++i)
  226616. {
  226617. NSPoint p[3];
  226618. switch ([bez elementAtIndex: i associatedPoints: p])
  226619. {
  226620. case NSMoveToBezierPathElement:
  226621. path.startNewSubPath ((float) p[0].x, (float) -p[0].y);
  226622. break;
  226623. case NSLineToBezierPathElement:
  226624. path.lineTo ((float) p[0].x, (float) -p[0].y);
  226625. break;
  226626. case NSCurveToBezierPathElement:
  226627. path.cubicTo ((float) p[0].x, (float) -p[0].y, (float) p[1].x, (float) -p[1].y, (float) p[2].x, (float) -p[2].y);
  226628. break;
  226629. case NSClosePathBezierPathElement:
  226630. path.closeSubPath();
  226631. break;
  226632. default:
  226633. jassertfalse;
  226634. break;
  226635. }
  226636. }
  226637. path.applyTransform (pathTransform);
  226638. return true;
  226639. #endif
  226640. }
  226641. juce_UseDebuggingNewOperator
  226642. CGFontRef fontRef;
  226643. float fontHeightToCGSizeFactor;
  226644. CGAffineTransform renderingTransform;
  226645. private:
  226646. float ascent, unitsToHeightScaleFactor;
  226647. #if JUCE_IOS
  226648. #else
  226649. NSFont* nsFont;
  226650. AffineTransform pathTransform;
  226651. #endif
  226652. void createGlyphsForString (const juce_wchar* const text, const int length, HeapBlock <CGGlyph>& glyphs)
  226653. {
  226654. #if SUPPORT_10_4_FONTS
  226655. #if ! SUPPORT_ONLY_10_4_FONTS
  226656. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  226657. #endif
  226658. {
  226659. glyphs.malloc (sizeof (NSGlyph) * length, 1);
  226660. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  226661. for (int i = 0; i < length; ++i)
  226662. nsGlyphs[i] = (NSGlyph) [nsFont _defaultGlyphForChar: text[i]];
  226663. return;
  226664. }
  226665. #endif
  226666. #if ! SUPPORT_ONLY_10_4_FONTS
  226667. if (charToGlyphMapper == 0)
  226668. charToGlyphMapper = new CharToGlyphMapper (fontRef);
  226669. glyphs.malloc (length);
  226670. for (int i = 0; i < length; ++i)
  226671. glyphs[i] = (CGGlyph) charToGlyphMapper->getGlyphForCharacter (text[i]);
  226672. #endif
  226673. }
  226674. #if ! SUPPORT_ONLY_10_4_FONTS
  226675. // Reads a CGFontRef's character map table to convert unicode into glyph numbers
  226676. class CharToGlyphMapper
  226677. {
  226678. public:
  226679. CharToGlyphMapper (CGFontRef fontRef)
  226680. : segCount (0), endCode (0), startCode (0), idDelta (0),
  226681. idRangeOffset (0), glyphIndexes (0)
  226682. {
  226683. CFDataRef cmapTable = CGFontCopyTableForTag (fontRef, 'cmap');
  226684. if (cmapTable != 0)
  226685. {
  226686. const int numSubtables = getValue16 (cmapTable, 2);
  226687. for (int i = 0; i < numSubtables; ++i)
  226688. {
  226689. if (getValue16 (cmapTable, i * 8 + 4) == 0) // check for platform ID of 0
  226690. {
  226691. const int offset = getValue32 (cmapTable, i * 8 + 8);
  226692. if (getValue16 (cmapTable, offset) == 4) // check that it's format 4..
  226693. {
  226694. const int length = getValue16 (cmapTable, offset + 2);
  226695. const int segCountX2 = getValue16 (cmapTable, offset + 6);
  226696. segCount = segCountX2 / 2;
  226697. const int endCodeOffset = offset + 14;
  226698. const int startCodeOffset = endCodeOffset + 2 + segCountX2;
  226699. const int idDeltaOffset = startCodeOffset + segCountX2;
  226700. const int idRangeOffsetOffset = idDeltaOffset + segCountX2;
  226701. const int glyphIndexesOffset = idRangeOffsetOffset + segCountX2;
  226702. endCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + endCodeOffset, segCountX2);
  226703. startCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + startCodeOffset, segCountX2);
  226704. idDelta = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idDeltaOffset, segCountX2);
  226705. idRangeOffset = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idRangeOffsetOffset, segCountX2);
  226706. glyphIndexes = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + glyphIndexesOffset, offset + length - glyphIndexesOffset);
  226707. }
  226708. break;
  226709. }
  226710. }
  226711. CFRelease (cmapTable);
  226712. }
  226713. }
  226714. ~CharToGlyphMapper()
  226715. {
  226716. if (endCode != 0)
  226717. {
  226718. CFRelease (endCode);
  226719. CFRelease (startCode);
  226720. CFRelease (idDelta);
  226721. CFRelease (idRangeOffset);
  226722. CFRelease (glyphIndexes);
  226723. }
  226724. }
  226725. int getGlyphForCharacter (const juce_wchar c) const
  226726. {
  226727. for (int i = 0; i < segCount; ++i)
  226728. {
  226729. if (getValue16 (endCode, i * 2) >= c)
  226730. {
  226731. const int start = getValue16 (startCode, i * 2);
  226732. if (start > c)
  226733. break;
  226734. const int delta = getValue16 (idDelta, i * 2);
  226735. const int rangeOffset = getValue16 (idRangeOffset, i * 2);
  226736. if (rangeOffset == 0)
  226737. return delta + c;
  226738. else
  226739. return getValue16 (glyphIndexes, 2 * ((rangeOffset / 2) + (c - start) - (segCount - i)));
  226740. }
  226741. }
  226742. // If we failed to find it "properly", this dodgy fall-back seems to do the trick for most fonts!
  226743. return jmax (-1, (int) c - 29);
  226744. }
  226745. private:
  226746. int segCount;
  226747. CFDataRef endCode, startCode, idDelta, idRangeOffset, glyphIndexes;
  226748. static uint16 getValue16 (CFDataRef data, const int index)
  226749. {
  226750. return CFSwapInt16BigToHost (*(UInt16*) (CFDataGetBytePtr (data) + index));
  226751. }
  226752. static uint32 getValue32 (CFDataRef data, const int index)
  226753. {
  226754. return CFSwapInt32BigToHost (*(UInt32*) (CFDataGetBytePtr (data) + index));
  226755. }
  226756. };
  226757. ScopedPointer <CharToGlyphMapper> charToGlyphMapper;
  226758. #endif
  226759. MacTypeface (const MacTypeface&);
  226760. MacTypeface& operator= (const MacTypeface&);
  226761. };
  226762. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  226763. {
  226764. return new MacTypeface (font);
  226765. }
  226766. const StringArray Font::findAllTypefaceNames()
  226767. {
  226768. StringArray names;
  226769. const ScopedAutoReleasePool pool;
  226770. #if JUCE_IOS
  226771. NSArray* fonts = [UIFont familyNames];
  226772. #else
  226773. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  226774. #endif
  226775. for (unsigned int i = 0; i < [fonts count]; ++i)
  226776. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  226777. names.sort (true);
  226778. return names;
  226779. }
  226780. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  226781. {
  226782. #if JUCE_IOS
  226783. defaultSans = "Helvetica";
  226784. defaultSerif = "Times New Roman";
  226785. defaultFixed = "Courier New";
  226786. #else
  226787. defaultSans = "Lucida Grande";
  226788. defaultSerif = "Times New Roman";
  226789. defaultFixed = "Monaco";
  226790. #endif
  226791. }
  226792. #endif
  226793. /*** End of inlined file: juce_mac_Fonts.mm ***/
  226794. /*** Start of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  226795. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226796. // compiled on its own).
  226797. #if JUCE_INCLUDED_FILE
  226798. class CoreGraphicsImage : public Image::SharedImage
  226799. {
  226800. public:
  226801. CoreGraphicsImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  226802. : Image::SharedImage (format_, width_, height_)
  226803. {
  226804. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  226805. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  226806. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  226807. imageData = imageDataAllocated;
  226808. CGColorSpaceRef colourSpace = (format == Image::SingleChannel) ? CGColorSpaceCreateDeviceGray()
  226809. : CGColorSpaceCreateDeviceRGB();
  226810. context = CGBitmapContextCreate (imageData, width, height, 8, lineStride,
  226811. colourSpace, getCGImageFlags (format_));
  226812. CGColorSpaceRelease (colourSpace);
  226813. }
  226814. ~CoreGraphicsImage()
  226815. {
  226816. CGContextRelease (context);
  226817. }
  226818. Image::ImageType getType() const { return Image::NativeImage; }
  226819. LowLevelGraphicsContext* createLowLevelContext();
  226820. SharedImage* clone()
  226821. {
  226822. CoreGraphicsImage* im = new CoreGraphicsImage (format, width, height, false);
  226823. memcpy (im->imageData, imageData, lineStride * height);
  226824. return im;
  226825. }
  226826. static CGImageRef createImage (const Image& juceImage, const bool forAlpha, CGColorSpaceRef colourSpace)
  226827. {
  226828. const CoreGraphicsImage* nativeImage = dynamic_cast <const CoreGraphicsImage*> (juceImage.getSharedImage());
  226829. if (nativeImage != 0 && (juceImage.getFormat() == Image::SingleChannel || ! forAlpha))
  226830. {
  226831. return CGBitmapContextCreateImage (nativeImage->context);
  226832. }
  226833. else
  226834. {
  226835. const Image::BitmapData srcData (juceImage, false);
  226836. CGDataProviderRef provider = CGDataProviderCreateWithData (0, srcData.data, srcData.lineStride * srcData.height, 0);
  226837. CGImageRef imageRef = CGImageCreate (srcData.width, srcData.height,
  226838. 8, srcData.pixelStride * 8, srcData.lineStride,
  226839. colourSpace, getCGImageFlags (juceImage.getFormat()), provider,
  226840. 0, true, kCGRenderingIntentDefault);
  226841. CGDataProviderRelease (provider);
  226842. return imageRef;
  226843. }
  226844. }
  226845. #if JUCE_MAC
  226846. static NSImage* createNSImage (const Image& image)
  226847. {
  226848. const ScopedAutoReleasePool pool;
  226849. NSImage* im = [[NSImage alloc] init];
  226850. [im setSize: NSMakeSize (image.getWidth(), image.getHeight())];
  226851. [im lockFocus];
  226852. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  226853. CGImageRef imageRef = createImage (image, false, colourSpace);
  226854. CGColorSpaceRelease (colourSpace);
  226855. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  226856. CGContextDrawImage (cg, CGRectMake (0, 0, image.getWidth(), image.getHeight()), imageRef);
  226857. CGImageRelease (imageRef);
  226858. [im unlockFocus];
  226859. return im;
  226860. }
  226861. #endif
  226862. CGContextRef context;
  226863. HeapBlock<uint8> imageDataAllocated;
  226864. private:
  226865. static CGBitmapInfo getCGImageFlags (const Image::PixelFormat& format)
  226866. {
  226867. #if JUCE_BIG_ENDIAN
  226868. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big) : kCGBitmapByteOrderDefault;
  226869. #else
  226870. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault;
  226871. #endif
  226872. }
  226873. };
  226874. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  226875. {
  226876. #if USE_COREGRAPHICS_RENDERING
  226877. return new CoreGraphicsImage (format == RGB ? ARGB : format, width, height, clearImage);
  226878. #else
  226879. return createSoftwareImage (format, width, height, clearImage);
  226880. #endif
  226881. }
  226882. class CoreGraphicsContext : public LowLevelGraphicsContext
  226883. {
  226884. public:
  226885. CoreGraphicsContext (CGContextRef context_, const float flipHeight_)
  226886. : context (context_),
  226887. flipHeight (flipHeight_),
  226888. lastClipRectIsValid (false),
  226889. state (new SavedState()),
  226890. numGradientLookupEntries (0)
  226891. {
  226892. CGContextRetain (context);
  226893. CGContextSaveGState(context);
  226894. CGContextSetShouldSmoothFonts (context, true);
  226895. CGContextSetShouldAntialias (context, true);
  226896. CGContextSetBlendMode (context, kCGBlendModeNormal);
  226897. rgbColourSpace = CGColorSpaceCreateDeviceRGB();
  226898. greyColourSpace = CGColorSpaceCreateDeviceGray();
  226899. gradientCallbacks.version = 0;
  226900. gradientCallbacks.evaluate = gradientCallback;
  226901. gradientCallbacks.releaseInfo = 0;
  226902. setFont (Font());
  226903. }
  226904. ~CoreGraphicsContext()
  226905. {
  226906. CGContextRestoreGState (context);
  226907. CGContextRelease (context);
  226908. CGColorSpaceRelease (rgbColourSpace);
  226909. CGColorSpaceRelease (greyColourSpace);
  226910. }
  226911. bool isVectorDevice() const { return false; }
  226912. void setOrigin (int x, int y)
  226913. {
  226914. CGContextTranslateCTM (context, x, -y);
  226915. if (lastClipRectIsValid)
  226916. lastClipRect.translate (-x, -y);
  226917. }
  226918. bool clipToRectangle (const Rectangle<int>& r)
  226919. {
  226920. CGContextClipToRect (context, CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()));
  226921. if (lastClipRectIsValid)
  226922. {
  226923. // This is actually incorrect, because the actual clip region may be complex, and
  226924. // clipping its bounds to a rect may not be right... But, removing this shortcut
  226925. // doesn't actually fix anything because CoreGraphics also ignores complex regions
  226926. // when calculating the resultant clip bounds, and makes the same mistake!
  226927. lastClipRect = lastClipRect.getIntersection (r);
  226928. return ! lastClipRect.isEmpty();
  226929. }
  226930. return ! isClipEmpty();
  226931. }
  226932. bool clipToRectangleList (const RectangleList& clipRegion)
  226933. {
  226934. if (clipRegion.isEmpty())
  226935. {
  226936. CGContextClipToRect (context, CGRectMake (0, 0, 0, 0));
  226937. lastClipRectIsValid = true;
  226938. lastClipRect = Rectangle<int>();
  226939. return false;
  226940. }
  226941. else
  226942. {
  226943. const int numRects = clipRegion.getNumRectangles();
  226944. HeapBlock <CGRect> rects (numRects);
  226945. for (int i = 0; i < numRects; ++i)
  226946. {
  226947. const Rectangle<int>& r = clipRegion.getRectangle(i);
  226948. rects[i] = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  226949. }
  226950. CGContextClipToRects (context, rects, numRects);
  226951. lastClipRectIsValid = false;
  226952. return ! isClipEmpty();
  226953. }
  226954. }
  226955. void excludeClipRectangle (const Rectangle<int>& r)
  226956. {
  226957. RectangleList remaining (getClipBounds());
  226958. remaining.subtract (r);
  226959. clipToRectangleList (remaining);
  226960. lastClipRectIsValid = false;
  226961. }
  226962. void clipToPath (const Path& path, const AffineTransform& transform)
  226963. {
  226964. createPath (path, transform);
  226965. CGContextClip (context);
  226966. lastClipRectIsValid = false;
  226967. }
  226968. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  226969. {
  226970. if (! transform.isSingularity())
  226971. {
  226972. Image singleChannelImage (sourceImage);
  226973. if (sourceImage.getFormat() != Image::SingleChannel)
  226974. singleChannelImage = sourceImage.convertedToFormat (Image::SingleChannel);
  226975. CGImageRef image = CoreGraphicsImage::createImage (singleChannelImage, true, greyColourSpace);
  226976. flip();
  226977. AffineTransform t (AffineTransform::scale (1.0f, -1.0f).translated (0, sourceImage.getHeight()).followedBy (transform));
  226978. applyTransform (t);
  226979. CGRect r = CGRectMake (0, 0, sourceImage.getWidth(), sourceImage.getHeight());
  226980. CGContextClipToMask (context, r, image);
  226981. applyTransform (t.inverted());
  226982. flip();
  226983. CGImageRelease (image);
  226984. lastClipRectIsValid = false;
  226985. }
  226986. }
  226987. bool clipRegionIntersects (const Rectangle<int>& r)
  226988. {
  226989. return getClipBounds().intersects (r);
  226990. }
  226991. const Rectangle<int> getClipBounds() const
  226992. {
  226993. if (! lastClipRectIsValid)
  226994. {
  226995. CGRect bounds = CGRectIntegral (CGContextGetClipBoundingBox (context));
  226996. lastClipRectIsValid = true;
  226997. lastClipRect.setBounds (roundToInt (bounds.origin.x),
  226998. roundToInt (flipHeight - (bounds.origin.y + bounds.size.height)),
  226999. roundToInt (bounds.size.width),
  227000. roundToInt (bounds.size.height));
  227001. }
  227002. return lastClipRect;
  227003. }
  227004. bool isClipEmpty() const
  227005. {
  227006. return getClipBounds().isEmpty();
  227007. }
  227008. void saveState()
  227009. {
  227010. CGContextSaveGState (context);
  227011. stateStack.add (new SavedState (*state));
  227012. }
  227013. void restoreState()
  227014. {
  227015. CGContextRestoreGState (context);
  227016. SavedState* const top = stateStack.getLast();
  227017. if (top != 0)
  227018. {
  227019. state = top;
  227020. stateStack.removeLast (1, false);
  227021. lastClipRectIsValid = false;
  227022. }
  227023. else
  227024. {
  227025. jassertfalse; // trying to pop with an empty stack!
  227026. }
  227027. }
  227028. void setFill (const FillType& fillType)
  227029. {
  227030. state->fillType = fillType;
  227031. if (fillType.isColour())
  227032. {
  227033. CGContextSetRGBFillColor (context, fillType.colour.getFloatRed(), fillType.colour.getFloatGreen(),
  227034. fillType.colour.getFloatBlue(), fillType.colour.getFloatAlpha());
  227035. CGContextSetAlpha (context, 1.0f);
  227036. }
  227037. }
  227038. void setOpacity (float newOpacity)
  227039. {
  227040. state->fillType.setOpacity (newOpacity);
  227041. setFill (state->fillType);
  227042. }
  227043. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  227044. {
  227045. CGContextSetInterpolationQuality (context, quality == Graphics::lowResamplingQuality
  227046. ? kCGInterpolationLow
  227047. : kCGInterpolationHigh);
  227048. }
  227049. void fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  227050. {
  227051. fillCGRect (CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()), replaceExistingContents);
  227052. }
  227053. void fillCGRect (const CGRect& cgRect, const bool replaceExistingContents)
  227054. {
  227055. if (replaceExistingContents)
  227056. {
  227057. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  227058. CGContextClearRect (context, cgRect);
  227059. #else
  227060. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  227061. if (CGContextDrawLinearGradient == 0) // (just a way of checking whether we're running in 10.5 or later)
  227062. CGContextClearRect (context, cgRect);
  227063. else
  227064. #endif
  227065. CGContextSetBlendMode (context, kCGBlendModeCopy);
  227066. #endif
  227067. fillCGRect (cgRect, false);
  227068. CGContextSetBlendMode (context, kCGBlendModeNormal);
  227069. }
  227070. else
  227071. {
  227072. if (state->fillType.isColour())
  227073. {
  227074. CGContextFillRect (context, cgRect);
  227075. }
  227076. else if (state->fillType.isGradient())
  227077. {
  227078. CGContextSaveGState (context);
  227079. CGContextClipToRect (context, cgRect);
  227080. drawGradient();
  227081. CGContextRestoreGState (context);
  227082. }
  227083. else
  227084. {
  227085. CGContextSaveGState (context);
  227086. CGContextClipToRect (context, cgRect);
  227087. drawImage (state->fillType.image, state->fillType.transform, true);
  227088. CGContextRestoreGState (context);
  227089. }
  227090. }
  227091. }
  227092. void fillPath (const Path& path, const AffineTransform& transform)
  227093. {
  227094. CGContextSaveGState (context);
  227095. if (state->fillType.isColour())
  227096. {
  227097. flip();
  227098. applyTransform (transform);
  227099. createPath (path);
  227100. if (path.isUsingNonZeroWinding())
  227101. CGContextFillPath (context);
  227102. else
  227103. CGContextEOFillPath (context);
  227104. }
  227105. else
  227106. {
  227107. createPath (path, transform);
  227108. if (path.isUsingNonZeroWinding())
  227109. CGContextClip (context);
  227110. else
  227111. CGContextEOClip (context);
  227112. if (state->fillType.isGradient())
  227113. drawGradient();
  227114. else
  227115. drawImage (state->fillType.image, state->fillType.transform, true);
  227116. }
  227117. CGContextRestoreGState (context);
  227118. }
  227119. void drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  227120. {
  227121. const int iw = sourceImage.getWidth();
  227122. const int ih = sourceImage.getHeight();
  227123. CGImageRef image = CoreGraphicsImage::createImage (sourceImage, false, rgbColourSpace);
  227124. CGContextSaveGState (context);
  227125. CGContextSetAlpha (context, state->fillType.getOpacity());
  227126. flip();
  227127. applyTransform (AffineTransform::scale (1.0f, -1.0f).translated (0, ih).followedBy (transform));
  227128. CGRect imageRect = CGRectMake (0, 0, iw, ih);
  227129. if (fillEntireClipAsTiles)
  227130. {
  227131. #if JUCE_IOS
  227132. CGContextDrawTiledImage (context, imageRect, image);
  227133. #else
  227134. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  227135. // There's a bug in CGContextDrawTiledImage that makes it incredibly slow
  227136. // if it's doing a transformation - it's quicker to just draw lots of images manually
  227137. if (CGContextDrawTiledImage != 0 && transform.isOnlyTranslation())
  227138. CGContextDrawTiledImage (context, imageRect, image);
  227139. else
  227140. #endif
  227141. {
  227142. // Fallback to manually doing a tiled fill on 10.4
  227143. CGRect clip = CGRectIntegral (CGContextGetClipBoundingBox (context));
  227144. int x = 0, y = 0;
  227145. while (x > clip.origin.x) x -= iw;
  227146. while (y > clip.origin.y) y -= ih;
  227147. const int right = (int) (clip.origin.x + clip.size.width);
  227148. const int bottom = (int) (clip.origin.y + clip.size.height);
  227149. while (y < bottom)
  227150. {
  227151. for (int x2 = x; x2 < right; x2 += iw)
  227152. CGContextDrawImage (context, CGRectMake (x2, y, iw, ih), image);
  227153. y += ih;
  227154. }
  227155. }
  227156. #endif
  227157. }
  227158. else
  227159. {
  227160. CGContextDrawImage (context, imageRect, image);
  227161. }
  227162. CGImageRelease (image); // (This causes a memory bug in iPhone sim 3.0 - try upgrading to a later version if you hit this)
  227163. CGContextRestoreGState (context);
  227164. }
  227165. void drawLine (const Line<float>& line)
  227166. {
  227167. if (state->fillType.isColour())
  227168. {
  227169. CGContextSetLineCap (context, kCGLineCapSquare);
  227170. CGContextSetLineWidth (context, 1.0f);
  227171. CGContextSetRGBStrokeColor (context,
  227172. state->fillType.colour.getFloatRed(), state->fillType.colour.getFloatGreen(),
  227173. state->fillType.colour.getFloatBlue(), state->fillType.colour.getFloatAlpha());
  227174. CGPoint cgLine[] = { { (CGFloat) line.getStartX(), flipHeight - (CGFloat) line.getStartY() },
  227175. { (CGFloat) line.getEndX(), flipHeight - (CGFloat) line.getEndY() } };
  227176. CGContextStrokeLineSegments (context, cgLine, 1);
  227177. }
  227178. else
  227179. {
  227180. Path p;
  227181. p.addLineSegment (line, 1.0f);
  227182. fillPath (p, AffineTransform::identity);
  227183. }
  227184. }
  227185. void drawVerticalLine (const int x, float top, float bottom)
  227186. {
  227187. if (state->fillType.isColour())
  227188. {
  227189. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  227190. CGContextFillRect (context, CGRectMake (x, flipHeight - bottom, 1.0f, bottom - top));
  227191. #else
  227192. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  227193. // the x co-ord slightly to trick it..
  227194. CGContextFillRect (context, CGRectMake (x + 1.0f / 256.0f, flipHeight - bottom, 1.0f + 1.0f / 256.0f, bottom - top));
  227195. #endif
  227196. }
  227197. else
  227198. {
  227199. fillCGRect (CGRectMake ((float) x, flipHeight - bottom, 1.0f, bottom - top), false);
  227200. }
  227201. }
  227202. void drawHorizontalLine (const int y, float left, float right)
  227203. {
  227204. if (state->fillType.isColour())
  227205. {
  227206. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  227207. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + 1.0f), right - left, 1.0f));
  227208. #else
  227209. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  227210. // the x co-ord slightly to trick it..
  227211. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + (1.0f + 1.0f / 256.0f)), right - left, 1.0f + 1.0f / 256.0f));
  227212. #endif
  227213. }
  227214. else
  227215. {
  227216. fillCGRect (CGRectMake (left, flipHeight - (y + 1), right - left, 1.0f), false);
  227217. }
  227218. }
  227219. void setFont (const Font& newFont)
  227220. {
  227221. if (state->font != newFont)
  227222. {
  227223. state->fontRef = 0;
  227224. state->font = newFont;
  227225. MacTypeface* mf = dynamic_cast <MacTypeface*> (state->font.getTypeface());
  227226. if (mf != 0)
  227227. {
  227228. state->fontRef = mf->fontRef;
  227229. CGContextSetFont (context, state->fontRef);
  227230. CGContextSetFontSize (context, state->font.getHeight() * mf->fontHeightToCGSizeFactor);
  227231. state->fontTransform = mf->renderingTransform;
  227232. state->fontTransform.a *= state->font.getHorizontalScale();
  227233. CGContextSetTextMatrix (context, state->fontTransform);
  227234. }
  227235. }
  227236. }
  227237. const Font getFont()
  227238. {
  227239. return state->font;
  227240. }
  227241. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  227242. {
  227243. if (state->fontRef != 0 && state->fillType.isColour())
  227244. {
  227245. if (transform.isOnlyTranslation())
  227246. {
  227247. CGContextSetTextMatrix (context, state->fontTransform); // have to set this each time, as it's not saved as part of the state
  227248. CGGlyph g = glyphNumber;
  227249. CGContextShowGlyphsAtPoint (context, transform.getTranslationX(),
  227250. flipHeight - roundToInt (transform.getTranslationY()), &g, 1);
  227251. }
  227252. else
  227253. {
  227254. CGContextSaveGState (context);
  227255. flip();
  227256. applyTransform (transform);
  227257. CGAffineTransform t = state->fontTransform;
  227258. t.d = -t.d;
  227259. CGContextSetTextMatrix (context, t);
  227260. CGGlyph g = glyphNumber;
  227261. CGContextShowGlyphsAtPoint (context, 0, 0, &g, 1);
  227262. CGContextRestoreGState (context);
  227263. }
  227264. }
  227265. else
  227266. {
  227267. Path p;
  227268. Font& f = state->font;
  227269. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  227270. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight())
  227271. .followedBy (transform));
  227272. }
  227273. }
  227274. private:
  227275. CGContextRef context;
  227276. const CGFloat flipHeight;
  227277. CGColorSpaceRef rgbColourSpace, greyColourSpace;
  227278. CGFunctionCallbacks gradientCallbacks;
  227279. mutable Rectangle<int> lastClipRect;
  227280. mutable bool lastClipRectIsValid;
  227281. struct SavedState
  227282. {
  227283. SavedState()
  227284. : font (1.0f), fontRef (0), fontTransform (CGAffineTransformIdentity)
  227285. {
  227286. }
  227287. SavedState (const SavedState& other)
  227288. : fillType (other.fillType), font (other.font), fontRef (other.fontRef),
  227289. fontTransform (other.fontTransform)
  227290. {
  227291. }
  227292. ~SavedState()
  227293. {
  227294. }
  227295. FillType fillType;
  227296. Font font;
  227297. CGFontRef fontRef;
  227298. CGAffineTransform fontTransform;
  227299. };
  227300. ScopedPointer <SavedState> state;
  227301. OwnedArray <SavedState> stateStack;
  227302. HeapBlock <PixelARGB> gradientLookupTable;
  227303. int numGradientLookupEntries;
  227304. static void gradientCallback (void* info, const CGFloat* inData, CGFloat* outData)
  227305. {
  227306. const CoreGraphicsContext* const g = static_cast <const CoreGraphicsContext*> (info);
  227307. const int index = roundToInt (g->numGradientLookupEntries * inData[0]);
  227308. PixelARGB colour (g->gradientLookupTable [jlimit (0, g->numGradientLookupEntries, index)]);
  227309. colour.unpremultiply();
  227310. outData[0] = colour.getRed() / 255.0f;
  227311. outData[1] = colour.getGreen() / 255.0f;
  227312. outData[2] = colour.getBlue() / 255.0f;
  227313. outData[3] = colour.getAlpha() / 255.0f;
  227314. }
  227315. CGShadingRef createGradient (const AffineTransform& transform, ColourGradient gradient)
  227316. {
  227317. numGradientLookupEntries = gradient.createLookupTable (transform, gradientLookupTable);
  227318. --numGradientLookupEntries;
  227319. CGShadingRef result = 0;
  227320. CGFunctionRef function = CGFunctionCreate (this, 1, 0, 4, 0, &gradientCallbacks);
  227321. CGPoint p1 (CGPointMake (gradient.point1.getX(), gradient.point1.getY()));
  227322. if (gradient.isRadial)
  227323. {
  227324. result = CGShadingCreateRadial (rgbColourSpace, p1, 0,
  227325. p1, gradient.point1.getDistanceFrom (gradient.point2),
  227326. function, true, true);
  227327. }
  227328. else
  227329. {
  227330. result = CGShadingCreateAxial (rgbColourSpace, p1,
  227331. CGPointMake (gradient.point2.getX(), gradient.point2.getY()),
  227332. function, true, true);
  227333. }
  227334. CGFunctionRelease (function);
  227335. return result;
  227336. }
  227337. void drawGradient()
  227338. {
  227339. flip();
  227340. applyTransform (state->fillType.transform);
  227341. CGContextSetInterpolationQuality (context, kCGInterpolationDefault); // (This is required for 10.4, where there's a crash if
  227342. // you draw a gradient with high quality interp enabled).
  227343. CGShadingRef shading = createGradient (state->fillType.transform, *(state->fillType.gradient));
  227344. CGContextSetAlpha (context, state->fillType.getOpacity());
  227345. CGContextDrawShading (context, shading);
  227346. CGShadingRelease (shading);
  227347. }
  227348. void createPath (const Path& path) const
  227349. {
  227350. CGContextBeginPath (context);
  227351. Path::Iterator i (path);
  227352. while (i.next())
  227353. {
  227354. switch (i.elementType)
  227355. {
  227356. case Path::Iterator::startNewSubPath: CGContextMoveToPoint (context, i.x1, i.y1); break;
  227357. case Path::Iterator::lineTo: CGContextAddLineToPoint (context, i.x1, i.y1); break;
  227358. case Path::Iterator::quadraticTo: CGContextAddQuadCurveToPoint (context, i.x1, i.y1, i.x2, i.y2); break;
  227359. case Path::Iterator::cubicTo: CGContextAddCurveToPoint (context, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3); break;
  227360. case Path::Iterator::closePath: CGContextClosePath (context); break;
  227361. default: jassertfalse; break;
  227362. }
  227363. }
  227364. }
  227365. void createPath (const Path& path, const AffineTransform& transform) const
  227366. {
  227367. CGContextBeginPath (context);
  227368. Path::Iterator i (path);
  227369. while (i.next())
  227370. {
  227371. switch (i.elementType)
  227372. {
  227373. case Path::Iterator::startNewSubPath:
  227374. transform.transformPoint (i.x1, i.y1);
  227375. CGContextMoveToPoint (context, i.x1, flipHeight - i.y1);
  227376. break;
  227377. case Path::Iterator::lineTo:
  227378. transform.transformPoint (i.x1, i.y1);
  227379. CGContextAddLineToPoint (context, i.x1, flipHeight - i.y1);
  227380. break;
  227381. case Path::Iterator::quadraticTo:
  227382. transform.transformPoints (i.x1, i.y1, i.x2, i.y2);
  227383. CGContextAddQuadCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2);
  227384. break;
  227385. case Path::Iterator::cubicTo:
  227386. transform.transformPoints (i.x1, i.y1, i.x2, i.y2, i.x3, i.y3);
  227387. CGContextAddCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2, i.x3, flipHeight - i.y3);
  227388. break;
  227389. case Path::Iterator::closePath:
  227390. CGContextClosePath (context); break;
  227391. default:
  227392. jassertfalse;
  227393. break;
  227394. }
  227395. }
  227396. }
  227397. void flip() const
  227398. {
  227399. CGContextConcatCTM (context, CGAffineTransformMake (1, 0, 0, -1, 0, flipHeight));
  227400. }
  227401. void applyTransform (const AffineTransform& transform) const
  227402. {
  227403. CGAffineTransform t;
  227404. t.a = transform.mat00;
  227405. t.b = transform.mat10;
  227406. t.c = transform.mat01;
  227407. t.d = transform.mat11;
  227408. t.tx = transform.mat02;
  227409. t.ty = transform.mat12;
  227410. CGContextConcatCTM (context, t);
  227411. }
  227412. CoreGraphicsContext (const CoreGraphicsContext&);
  227413. CoreGraphicsContext& operator= (const CoreGraphicsContext&);
  227414. };
  227415. LowLevelGraphicsContext* CoreGraphicsImage::createLowLevelContext()
  227416. {
  227417. return new CoreGraphicsContext (context, height);
  227418. }
  227419. #if USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  227420. const Image juce_loadWithCoreImage (InputStream& input)
  227421. {
  227422. MemoryBlock data;
  227423. input.readIntoMemoryBlock (data, -1);
  227424. #if JUCE_IOS
  227425. JUCE_AUTORELEASEPOOL
  227426. UIImage* image = [UIImage imageWithData: [NSData dataWithBytesNoCopy: data.getData()
  227427. length: data.getSize()
  227428. freeWhenDone: NO]];
  227429. if (image != nil)
  227430. {
  227431. CGImageRef loadedImage = image.CGImage;
  227432. #else
  227433. CGDataProviderRef provider = CGDataProviderCreateWithData (0, data.getData(), data.getSize(), 0);
  227434. CGImageSourceRef imageSource = CGImageSourceCreateWithDataProvider (provider, 0);
  227435. CGDataProviderRelease (provider);
  227436. if (imageSource != 0)
  227437. {
  227438. CGImageRef loadedImage = CGImageSourceCreateImageAtIndex (imageSource, 0, 0);
  227439. CFRelease (imageSource);
  227440. #endif
  227441. if (loadedImage != 0)
  227442. {
  227443. CGImageAlphaInfo alphaInfo = CGImageGetAlphaInfo (loadedImage);
  227444. const bool hasAlphaChan = (alphaInfo != kCGImageAlphaNone
  227445. && alphaInfo != kCGImageAlphaNoneSkipLast
  227446. && alphaInfo != kCGImageAlphaNoneSkipFirst);
  227447. Image image (Image::ARGB, // (CoreImage doesn't work with 24-bit images)
  227448. (int) CGImageGetWidth (loadedImage), (int) CGImageGetHeight (loadedImage),
  227449. hasAlphaChan, Image::NativeImage);
  227450. CoreGraphicsImage* const cgImage = dynamic_cast<CoreGraphicsImage*> (image.getSharedImage());
  227451. jassert (cgImage != 0); // if USE_COREGRAPHICS_RENDERING is set, the CoreGraphicsImage class should have been used.
  227452. CGContextDrawImage (cgImage->context, CGRectMake (0, 0, image.getWidth(), image.getHeight()), loadedImage);
  227453. CGContextFlush (cgImage->context);
  227454. #if ! JUCE_IOS
  227455. CFRelease (loadedImage);
  227456. #endif
  227457. // Because it's impossible to create a truly 24-bit CG image, this flag allows a user
  227458. // to find out whether the file they just loaded the image from had an alpha channel or not.
  227459. image.getProperties()->set ("originalImageHadAlpha", hasAlphaChan);
  227460. return image;
  227461. }
  227462. }
  227463. return Image::null;
  227464. }
  227465. #endif
  227466. #endif
  227467. /*** End of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  227468. /*** Start of inlined file: juce_iphone_UIViewComponentPeer.mm ***/
  227469. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227470. // compiled on its own).
  227471. #if JUCE_INCLUDED_FILE
  227472. class UIViewComponentPeer;
  227473. END_JUCE_NAMESPACE
  227474. #define JuceUIView MakeObjCClassName(JuceUIView)
  227475. @interface JuceUIView : UIView <UITextViewDelegate>
  227476. {
  227477. @public
  227478. UIViewComponentPeer* owner;
  227479. UITextView* hiddenTextView;
  227480. }
  227481. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner withFrame: (CGRect) frame;
  227482. - (void) dealloc;
  227483. - (void) drawRect: (CGRect) r;
  227484. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event;
  227485. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event;
  227486. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event;
  227487. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event;
  227488. - (BOOL) becomeFirstResponder;
  227489. - (BOOL) resignFirstResponder;
  227490. - (BOOL) canBecomeFirstResponder;
  227491. - (void) asyncRepaint: (id) rect;
  227492. - (BOOL) textView: (UITextView*) textView shouldChangeTextInRange: (NSRange) range replacementText: (NSString*) text;
  227493. @end
  227494. #define JuceUIViewController MakeObjCClassName(JuceUIViewController)
  227495. @interface JuceUIViewController : UIViewController
  227496. {
  227497. }
  227498. - (BOOL) shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation) interfaceOrientation;
  227499. - (void) didRotateFromInterfaceOrientation: (UIInterfaceOrientation) fromInterfaceOrientation;
  227500. @end
  227501. #define JuceUIWindow MakeObjCClassName(JuceUIWindow)
  227502. @interface JuceUIWindow : UIWindow
  227503. {
  227504. @private
  227505. UIViewComponentPeer* owner;
  227506. bool isZooming;
  227507. }
  227508. - (void) setOwner: (UIViewComponentPeer*) owner;
  227509. - (void) becomeKeyWindow;
  227510. @end
  227511. BEGIN_JUCE_NAMESPACE
  227512. class UIViewComponentPeer : public ComponentPeer,
  227513. public FocusChangeListener
  227514. {
  227515. public:
  227516. UIViewComponentPeer (Component* const component,
  227517. const int windowStyleFlags,
  227518. UIView* viewToAttachTo);
  227519. ~UIViewComponentPeer();
  227520. void* getNativeHandle() const;
  227521. void setVisible (bool shouldBeVisible);
  227522. void setTitle (const String& title);
  227523. void setPosition (int x, int y);
  227524. void setSize (int w, int h);
  227525. void setBounds (int x, int y, int w, int h, bool isNowFullScreen);
  227526. const Rectangle<int> getBounds() const;
  227527. const Rectangle<int> getBounds (const bool global) const;
  227528. const Point<int> getScreenPosition() const;
  227529. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition);
  227530. const Point<int> globalPositionToRelative (const Point<int>& screenPosition);
  227531. void setAlpha (float newAlpha);
  227532. void setMinimised (bool shouldBeMinimised);
  227533. bool isMinimised() const;
  227534. void setFullScreen (bool shouldBeFullScreen);
  227535. bool isFullScreen() const;
  227536. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const;
  227537. const BorderSize getFrameSize() const;
  227538. bool setAlwaysOnTop (bool alwaysOnTop);
  227539. void toFront (bool makeActiveWindow);
  227540. void toBehind (ComponentPeer* other);
  227541. void setIcon (const Image& newIcon);
  227542. virtual void drawRect (CGRect r);
  227543. virtual bool canBecomeKeyWindow();
  227544. virtual bool windowShouldClose();
  227545. virtual void redirectMovedOrResized();
  227546. virtual CGRect constrainRect (CGRect r);
  227547. virtual void viewFocusGain();
  227548. virtual void viewFocusLoss();
  227549. bool isFocused() const;
  227550. void grabFocus();
  227551. void textInputRequired (const Point<int>& position);
  227552. virtual BOOL textViewReplaceCharacters (const Range<int>& range, const String& text);
  227553. void updateHiddenTextContent (TextInputTarget* target);
  227554. void globalFocusChanged (Component*);
  227555. virtual BOOL shouldRotate (UIInterfaceOrientation interfaceOrientation);
  227556. virtual void displayRotated();
  227557. void handleTouches (UIEvent* e, bool isDown, bool isUp, bool isCancel);
  227558. void repaint (const Rectangle<int>& area);
  227559. void performAnyPendingRepaintsNow();
  227560. juce_UseDebuggingNewOperator
  227561. UIWindow* window;
  227562. JuceUIView* view;
  227563. JuceUIViewController* controller;
  227564. bool isSharedWindow, fullScreen, insideDrawRect;
  227565. static ModifierKeys currentModifiers;
  227566. static int64 getMouseTime (UIEvent* e)
  227567. {
  227568. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  227569. + (int64) ([e timestamp] * 1000.0);
  227570. }
  227571. static const Rectangle<int> rotatedScreenPosToReal (const Rectangle<int>& r)
  227572. {
  227573. const Rectangle<int> screen (convertToRectInt ([[UIScreen mainScreen] bounds]));
  227574. switch ([[UIApplication sharedApplication] statusBarOrientation])
  227575. {
  227576. case UIInterfaceOrientationPortrait:
  227577. return r;
  227578. case UIInterfaceOrientationPortraitUpsideDown:
  227579. return Rectangle<int> (screen.getWidth() - r.getRight(), screen.getHeight() - r.getBottom(),
  227580. r.getWidth(), r.getHeight());
  227581. case UIInterfaceOrientationLandscapeLeft:
  227582. return Rectangle<int> (r.getY(), screen.getHeight() - r.getRight(),
  227583. r.getHeight(), r.getWidth());
  227584. case UIInterfaceOrientationLandscapeRight:
  227585. return Rectangle<int> (screen.getWidth() - r.getBottom(), r.getX(),
  227586. r.getHeight(), r.getWidth());
  227587. default: jassertfalse; // unknown orientation!
  227588. }
  227589. return r;
  227590. }
  227591. static const Rectangle<int> realScreenPosToRotated (const Rectangle<int>& r)
  227592. {
  227593. const Rectangle<int> screen (convertToRectInt ([[UIScreen mainScreen] bounds]));
  227594. switch ([[UIApplication sharedApplication] statusBarOrientation])
  227595. {
  227596. case UIInterfaceOrientationPortrait:
  227597. return r;
  227598. case UIInterfaceOrientationPortraitUpsideDown:
  227599. return Rectangle<int> (screen.getWidth() - r.getRight(), screen.getHeight() - r.getBottom(),
  227600. r.getWidth(), r.getHeight());
  227601. case UIInterfaceOrientationLandscapeLeft:
  227602. return Rectangle<int> (screen.getHeight() - r.getBottom(), r.getX(),
  227603. r.getHeight(), r.getWidth());
  227604. case UIInterfaceOrientationLandscapeRight:
  227605. return Rectangle<int> (r.getY(), screen.getWidth() - r.getRight(),
  227606. r.getHeight(), r.getWidth());
  227607. default: jassertfalse; // unknown orientation!
  227608. }
  227609. return r;
  227610. }
  227611. Array <UITouch*> currentTouches;
  227612. };
  227613. END_JUCE_NAMESPACE
  227614. @implementation JuceUIViewController
  227615. - (BOOL) shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation) interfaceOrientation
  227616. {
  227617. JuceUIView* juceView = (JuceUIView*) [self view];
  227618. jassert (juceView != 0 && juceView->owner != 0);
  227619. return juceView->owner->shouldRotate (interfaceOrientation);
  227620. }
  227621. - (void) didRotateFromInterfaceOrientation: (UIInterfaceOrientation) fromInterfaceOrientation
  227622. {
  227623. JuceUIView* juceView = (JuceUIView*) [self view];
  227624. jassert (juceView != 0 && juceView->owner != 0);
  227625. juceView->owner->displayRotated();
  227626. }
  227627. @end
  227628. @implementation JuceUIView
  227629. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner_
  227630. withFrame: (CGRect) frame
  227631. {
  227632. [super initWithFrame: frame];
  227633. owner = owner_;
  227634. hiddenTextView = [[UITextView alloc] initWithFrame: CGRectMake (0, 0, 0, 0)];
  227635. [self addSubview: hiddenTextView];
  227636. hiddenTextView.delegate = self;
  227637. hiddenTextView.autocapitalizationType = UITextAutocapitalizationTypeNone;
  227638. hiddenTextView.autocorrectionType = UITextAutocorrectionTypeNo;
  227639. return self;
  227640. }
  227641. - (void) dealloc
  227642. {
  227643. [hiddenTextView removeFromSuperview];
  227644. [hiddenTextView release];
  227645. [super dealloc];
  227646. }
  227647. - (void) drawRect: (CGRect) r
  227648. {
  227649. if (owner != 0)
  227650. owner->drawRect (r);
  227651. }
  227652. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  227653. {
  227654. return false;
  227655. }
  227656. ModifierKeys UIViewComponentPeer::currentModifiers;
  227657. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  227658. {
  227659. return UIViewComponentPeer::currentModifiers;
  227660. }
  227661. void ModifierKeys::updateCurrentModifiers() throw()
  227662. {
  227663. currentModifiers = UIViewComponentPeer::currentModifiers;
  227664. }
  227665. JUCE_NAMESPACE::Point<int> juce_lastMousePos;
  227666. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event
  227667. {
  227668. if (owner != 0)
  227669. owner->handleTouches (event, true, false, false);
  227670. }
  227671. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event
  227672. {
  227673. if (owner != 0)
  227674. owner->handleTouches (event, false, false, false);
  227675. }
  227676. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event
  227677. {
  227678. if (owner != 0)
  227679. owner->handleTouches (event, false, true, false);
  227680. }
  227681. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event
  227682. {
  227683. if (owner != 0)
  227684. owner->handleTouches (event, false, true, true);
  227685. [self touchesEnded: touches withEvent: event];
  227686. }
  227687. - (BOOL) becomeFirstResponder
  227688. {
  227689. if (owner != 0)
  227690. owner->viewFocusGain();
  227691. return true;
  227692. }
  227693. - (BOOL) resignFirstResponder
  227694. {
  227695. if (owner != 0)
  227696. owner->viewFocusLoss();
  227697. return true;
  227698. }
  227699. - (BOOL) canBecomeFirstResponder
  227700. {
  227701. return owner != 0 && owner->canBecomeKeyWindow();
  227702. }
  227703. - (void) asyncRepaint: (id) rect
  227704. {
  227705. CGRect* r = (CGRect*) [((NSData*) rect) bytes];
  227706. [self setNeedsDisplayInRect: *r];
  227707. }
  227708. - (BOOL) textView: (UITextView*) textView shouldChangeTextInRange: (NSRange) range replacementText: (NSString*) text
  227709. {
  227710. return owner->textViewReplaceCharacters (Range<int> (range.location, range.location + range.length),
  227711. nsStringToJuce (text));
  227712. }
  227713. @end
  227714. @implementation JuceUIWindow
  227715. - (void) setOwner: (UIViewComponentPeer*) owner_
  227716. {
  227717. owner = owner_;
  227718. isZooming = false;
  227719. }
  227720. - (void) becomeKeyWindow
  227721. {
  227722. [super becomeKeyWindow];
  227723. if (owner != 0)
  227724. owner->grabFocus();
  227725. }
  227726. @end
  227727. BEGIN_JUCE_NAMESPACE
  227728. UIViewComponentPeer::UIViewComponentPeer (Component* const component,
  227729. const int windowStyleFlags,
  227730. UIView* viewToAttachTo)
  227731. : ComponentPeer (component, windowStyleFlags),
  227732. window (0),
  227733. view (0), controller (0),
  227734. isSharedWindow (viewToAttachTo != 0),
  227735. fullScreen (false),
  227736. insideDrawRect (false)
  227737. {
  227738. CGRect r = convertToCGRect (component->getLocalBounds());
  227739. view = [[JuceUIView alloc] initWithOwner: this withFrame: r];
  227740. if (isSharedWindow)
  227741. {
  227742. window = [viewToAttachTo window];
  227743. [viewToAttachTo addSubview: view];
  227744. setVisible (component->isVisible());
  227745. }
  227746. else
  227747. {
  227748. controller = [[JuceUIViewController alloc] init];
  227749. controller.view = view;
  227750. r = convertToCGRect (rotatedScreenPosToReal (component->getBounds()));
  227751. r.origin.y = [[UIScreen mainScreen] bounds].size.height - (r.origin.y + r.size.height);
  227752. window = [[JuceUIWindow alloc] init];
  227753. window.frame = r;
  227754. window.opaque = component->isOpaque();
  227755. view.opaque = component->isOpaque();
  227756. window.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  227757. view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  227758. [((JuceUIWindow*) window) setOwner: this];
  227759. if (component->isAlwaysOnTop())
  227760. window.windowLevel = UIWindowLevelAlert;
  227761. [window addSubview: view];
  227762. view.frame = CGRectMake (0, 0, r.size.width, r.size.height);
  227763. view.hidden = ! component->isVisible();
  227764. window.hidden = ! component->isVisible();
  227765. view.multipleTouchEnabled = YES;
  227766. }
  227767. setTitle (component->getName());
  227768. Desktop::getInstance().addFocusChangeListener (this);
  227769. }
  227770. UIViewComponentPeer::~UIViewComponentPeer()
  227771. {
  227772. Desktop::getInstance().removeFocusChangeListener (this);
  227773. view->owner = 0;
  227774. [view removeFromSuperview];
  227775. [view release];
  227776. [controller release];
  227777. if (! isSharedWindow)
  227778. {
  227779. [((JuceUIWindow*) window) setOwner: 0];
  227780. [window release];
  227781. }
  227782. }
  227783. void* UIViewComponentPeer::getNativeHandle() const
  227784. {
  227785. return view;
  227786. }
  227787. void UIViewComponentPeer::setVisible (bool shouldBeVisible)
  227788. {
  227789. view.hidden = ! shouldBeVisible;
  227790. if (! isSharedWindow)
  227791. window.hidden = ! shouldBeVisible;
  227792. }
  227793. void UIViewComponentPeer::setTitle (const String& title)
  227794. {
  227795. // xxx is this possible?
  227796. }
  227797. void UIViewComponentPeer::setPosition (int x, int y)
  227798. {
  227799. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  227800. }
  227801. void UIViewComponentPeer::setSize (int w, int h)
  227802. {
  227803. setBounds (component->getX(), component->getY(), w, h, false);
  227804. }
  227805. void UIViewComponentPeer::setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  227806. {
  227807. fullScreen = isNowFullScreen;
  227808. w = jmax (0, w);
  227809. h = jmax (0, h);
  227810. if (isSharedWindow)
  227811. {
  227812. CGRect r = CGRectMake ((float) x, (float) y, (float) w, (float) h);
  227813. if ([view frame].size.width != r.size.width
  227814. || [view frame].size.height != r.size.height)
  227815. [view setNeedsDisplay];
  227816. view.frame = r;
  227817. }
  227818. else
  227819. {
  227820. const Rectangle<int> bounds (rotatedScreenPosToReal (Rectangle<int> (x, y, w, h)));
  227821. window.frame = convertToCGRect (bounds);
  227822. view.frame = CGRectMake (0, 0, (float) bounds.getWidth(), (float) bounds.getHeight());
  227823. handleMovedOrResized();
  227824. }
  227825. }
  227826. const Rectangle<int> UIViewComponentPeer::getBounds (const bool global) const
  227827. {
  227828. CGRect r = [view frame];
  227829. if (global && [view window] != 0)
  227830. {
  227831. r = [view convertRect: r toView: nil];
  227832. CGRect wr = [[view window] frame];
  227833. const Rectangle<int> windowBounds (realScreenPosToRotated (convertToRectInt (wr)));
  227834. r.origin.x = windowBounds.getX();
  227835. r.origin.y = windowBounds.getY();
  227836. }
  227837. return convertToRectInt (r);
  227838. }
  227839. const Rectangle<int> UIViewComponentPeer::getBounds() const
  227840. {
  227841. return getBounds (! isSharedWindow);
  227842. }
  227843. const Point<int> UIViewComponentPeer::getScreenPosition() const
  227844. {
  227845. return getBounds (true).getPosition();
  227846. }
  227847. const Point<int> UIViewComponentPeer::relativePositionToGlobal (const Point<int>& relativePosition)
  227848. {
  227849. return relativePosition + getScreenPosition();
  227850. }
  227851. const Point<int> UIViewComponentPeer::globalPositionToRelative (const Point<int>& screenPosition)
  227852. {
  227853. return screenPosition - getScreenPosition();
  227854. }
  227855. CGRect UIViewComponentPeer::constrainRect (CGRect r)
  227856. {
  227857. if (constrainer != 0)
  227858. {
  227859. CGRect current = [window frame];
  227860. current.origin.y = [[UIScreen mainScreen] bounds].size.height - current.origin.y - current.size.height;
  227861. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.origin.y - r.size.height;
  227862. Rectangle<int> pos (convertToRectInt (r));
  227863. Rectangle<int> original (convertToRectInt (current));
  227864. constrainer->checkBounds (pos, original,
  227865. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  227866. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  227867. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  227868. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  227869. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  227870. r.origin.x = pos.getX();
  227871. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.size.height - pos.getY();
  227872. r.size.width = pos.getWidth();
  227873. r.size.height = pos.getHeight();
  227874. }
  227875. return r;
  227876. }
  227877. void UIViewComponentPeer::setAlpha (float newAlpha)
  227878. {
  227879. [[view window] setAlpha: (CGFloat) newAlpha];
  227880. }
  227881. void UIViewComponentPeer::setMinimised (bool shouldBeMinimised)
  227882. {
  227883. }
  227884. bool UIViewComponentPeer::isMinimised() const
  227885. {
  227886. return false;
  227887. }
  227888. void UIViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  227889. {
  227890. if (! isSharedWindow)
  227891. {
  227892. Rectangle<int> r (shouldBeFullScreen ? Desktop::getInstance().getMainMonitorArea()
  227893. : lastNonFullscreenBounds);
  227894. if ((! shouldBeFullScreen) && r.isEmpty())
  227895. r = getBounds();
  227896. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  227897. if (! r.isEmpty())
  227898. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  227899. component->repaint();
  227900. }
  227901. }
  227902. bool UIViewComponentPeer::isFullScreen() const
  227903. {
  227904. return fullScreen;
  227905. }
  227906. namespace
  227907. {
  227908. Desktop::DisplayOrientation convertToJuceOrientation (UIInterfaceOrientation interfaceOrientation)
  227909. {
  227910. switch (interfaceOrientation)
  227911. {
  227912. case UIInterfaceOrientationPortrait: return Desktop::upright;
  227913. case UIInterfaceOrientationPortraitUpsideDown: return Desktop::upsideDown;
  227914. case UIInterfaceOrientationLandscapeLeft: return Desktop::rotatedClockwise;
  227915. case UIInterfaceOrientationLandscapeRight: return Desktop::rotatedAntiClockwise;
  227916. default: jassertfalse; // unknown orientation!
  227917. }
  227918. return Desktop::upright;
  227919. }
  227920. }
  227921. BOOL UIViewComponentPeer::shouldRotate (UIInterfaceOrientation interfaceOrientation)
  227922. {
  227923. return Desktop::getInstance().isOrientationEnabled (convertToJuceOrientation (interfaceOrientation));
  227924. }
  227925. void UIViewComponentPeer::displayRotated()
  227926. {
  227927. const Rectangle<int> oldArea (component->getBounds());
  227928. const Rectangle<int> oldDesktop (Desktop::getInstance().getMainMonitorArea());
  227929. Desktop::getInstance().refreshMonitorSizes();
  227930. if (fullScreen)
  227931. {
  227932. fullScreen = false;
  227933. setFullScreen (true);
  227934. }
  227935. else
  227936. {
  227937. const float l = oldArea.getX() / (float) oldDesktop.getWidth();
  227938. const float r = oldArea.getRight() / (float) oldDesktop.getWidth();
  227939. const float t = oldArea.getY() / (float) oldDesktop.getHeight();
  227940. const float b = oldArea.getBottom() / (float) oldDesktop.getHeight();
  227941. const Rectangle<int> newDesktop (Desktop::getInstance().getMainMonitorArea());
  227942. setBounds ((int) (l * newDesktop.getWidth()),
  227943. (int) (t * newDesktop.getHeight()),
  227944. (int) ((r - l) * newDesktop.getWidth()),
  227945. (int) ((b - t) * newDesktop.getHeight()),
  227946. false);
  227947. }
  227948. }
  227949. bool UIViewComponentPeer::contains (const Point<int>& position, bool trueIfInAChildWindow) const
  227950. {
  227951. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  227952. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  227953. return false;
  227954. UIView* v = [view hitTest: CGPointMake ((float) position.getX(), (float) position.getY())
  227955. withEvent: nil];
  227956. if (trueIfInAChildWindow)
  227957. return v != nil;
  227958. return v == view;
  227959. }
  227960. const BorderSize UIViewComponentPeer::getFrameSize() const
  227961. {
  227962. return BorderSize();
  227963. }
  227964. bool UIViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  227965. {
  227966. if (! isSharedWindow)
  227967. window.windowLevel = alwaysOnTop ? UIWindowLevelAlert : UIWindowLevelNormal;
  227968. return true;
  227969. }
  227970. void UIViewComponentPeer::toFront (bool makeActiveWindow)
  227971. {
  227972. if (isSharedWindow)
  227973. [[view superview] bringSubviewToFront: view];
  227974. if (window != 0 && component->isVisible())
  227975. [window makeKeyAndVisible];
  227976. }
  227977. void UIViewComponentPeer::toBehind (ComponentPeer* other)
  227978. {
  227979. UIViewComponentPeer* const otherPeer = dynamic_cast <UIViewComponentPeer*> (other);
  227980. jassert (otherPeer != 0); // wrong type of window?
  227981. if (otherPeer != 0)
  227982. {
  227983. if (isSharedWindow)
  227984. {
  227985. [[view superview] insertSubview: view belowSubview: otherPeer->view];
  227986. }
  227987. else
  227988. {
  227989. jassertfalse; // don't know how to do this
  227990. }
  227991. }
  227992. }
  227993. void UIViewComponentPeer::setIcon (const Image& /*newIcon*/)
  227994. {
  227995. // to do..
  227996. }
  227997. void UIViewComponentPeer::handleTouches (UIEvent* event, const bool isDown, const bool isUp, bool isCancel)
  227998. {
  227999. NSArray* touches = [[event touchesForView: view] allObjects];
  228000. for (unsigned int i = 0; i < [touches count]; ++i)
  228001. {
  228002. UITouch* touch = [touches objectAtIndex: i];
  228003. CGPoint p = [touch locationInView: view];
  228004. const Point<int> pos ((int) p.x, (int) p.y);
  228005. juce_lastMousePos = pos + getScreenPosition();
  228006. const int64 time = getMouseTime (event);
  228007. int touchIndex = currentTouches.indexOf (touch);
  228008. if (touchIndex < 0)
  228009. {
  228010. touchIndex = currentTouches.size();
  228011. currentTouches.add (touch);
  228012. }
  228013. if (isDown)
  228014. {
  228015. currentModifiers = currentModifiers.withoutMouseButtons();
  228016. handleMouseEvent (touchIndex, pos, currentModifiers, time);
  228017. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  228018. }
  228019. else if (isUp)
  228020. {
  228021. currentModifiers = currentModifiers.withoutMouseButtons();
  228022. currentTouches.remove (touchIndex);
  228023. }
  228024. if (isCancel)
  228025. currentTouches.clear();
  228026. handleMouseEvent (touchIndex, pos, currentModifiers, time);
  228027. }
  228028. }
  228029. static UIViewComponentPeer* currentlyFocusedPeer = 0;
  228030. void UIViewComponentPeer::viewFocusGain()
  228031. {
  228032. if (currentlyFocusedPeer != this)
  228033. {
  228034. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  228035. currentlyFocusedPeer->handleFocusLoss();
  228036. currentlyFocusedPeer = this;
  228037. handleFocusGain();
  228038. }
  228039. }
  228040. void UIViewComponentPeer::viewFocusLoss()
  228041. {
  228042. if (currentlyFocusedPeer == this)
  228043. {
  228044. currentlyFocusedPeer = 0;
  228045. handleFocusLoss();
  228046. }
  228047. }
  228048. void juce_HandleProcessFocusChange()
  228049. {
  228050. if (UIViewComponentPeer::isValidPeer (currentlyFocusedPeer))
  228051. {
  228052. if (Process::isForegroundProcess())
  228053. {
  228054. currentlyFocusedPeer->handleFocusGain();
  228055. ComponentPeer::bringModalComponentToFront();
  228056. }
  228057. else
  228058. {
  228059. currentlyFocusedPeer->handleFocusLoss();
  228060. // turn kiosk mode off if we lose focus..
  228061. Desktop::getInstance().setKioskModeComponent (0);
  228062. }
  228063. }
  228064. }
  228065. bool UIViewComponentPeer::isFocused() const
  228066. {
  228067. return isSharedWindow ? this == currentlyFocusedPeer
  228068. : (window != 0 && [window isKeyWindow]);
  228069. }
  228070. void UIViewComponentPeer::grabFocus()
  228071. {
  228072. if (window != 0)
  228073. {
  228074. [window makeKeyWindow];
  228075. viewFocusGain();
  228076. }
  228077. }
  228078. void UIViewComponentPeer::textInputRequired (const Point<int>&)
  228079. {
  228080. }
  228081. void UIViewComponentPeer::updateHiddenTextContent (TextInputTarget* target)
  228082. {
  228083. view->hiddenTextView.text = juceStringToNS (target->getTextInRange (Range<int> (0, target->getHighlightedRegion().getStart())));
  228084. view->hiddenTextView.selectedRange = NSMakeRange (target->getHighlightedRegion().getStart(), 0);
  228085. }
  228086. BOOL UIViewComponentPeer::textViewReplaceCharacters (const Range<int>& range, const String& text)
  228087. {
  228088. TextInputTarget* const target = findCurrentTextInputTarget();
  228089. if (target != 0)
  228090. {
  228091. const Range<int> currentSelection (target->getHighlightedRegion());
  228092. if (range.getLength() == 1 && text.isEmpty()) // (detect backspace)
  228093. if (currentSelection.isEmpty())
  228094. target->setHighlightedRegion (currentSelection.withStart (currentSelection.getStart() - 1));
  228095. target->insertTextAtCaret (text);
  228096. updateHiddenTextContent (target);
  228097. }
  228098. return NO;
  228099. }
  228100. void UIViewComponentPeer::globalFocusChanged (Component*)
  228101. {
  228102. TextInputTarget* const target = findCurrentTextInputTarget();
  228103. if (target != 0)
  228104. {
  228105. Component* comp = dynamic_cast<Component*> (target);
  228106. Point<int> pos (comp->relativePositionToOtherComponent (component, Point<int>()));
  228107. view->hiddenTextView.frame = CGRectMake (pos.getX(), pos.getY(), 0, 0);
  228108. updateHiddenTextContent (target);
  228109. [view->hiddenTextView becomeFirstResponder];
  228110. }
  228111. else
  228112. {
  228113. [view->hiddenTextView resignFirstResponder];
  228114. }
  228115. }
  228116. void UIViewComponentPeer::drawRect (CGRect r)
  228117. {
  228118. if (r.size.width < 1.0f || r.size.height < 1.0f)
  228119. return;
  228120. CGContextRef cg = UIGraphicsGetCurrentContext();
  228121. if (! component->isOpaque())
  228122. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  228123. CGContextConcatCTM (cg, CGAffineTransformMake (1, 0, 0, -1, 0, view.bounds.size.height));
  228124. CoreGraphicsContext g (cg, view.bounds.size.height);
  228125. insideDrawRect = true;
  228126. handlePaint (g);
  228127. insideDrawRect = false;
  228128. }
  228129. bool UIViewComponentPeer::canBecomeKeyWindow()
  228130. {
  228131. return (getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowIgnoresKeyPresses) == 0;
  228132. }
  228133. bool UIViewComponentPeer::windowShouldClose()
  228134. {
  228135. if (! isValidPeer (this))
  228136. return YES;
  228137. handleUserClosingWindow();
  228138. return NO;
  228139. }
  228140. void UIViewComponentPeer::redirectMovedOrResized()
  228141. {
  228142. handleMovedOrResized();
  228143. }
  228144. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  228145. {
  228146. }
  228147. class AsyncRepaintMessage : public CallbackMessage
  228148. {
  228149. public:
  228150. UIViewComponentPeer* const peer;
  228151. const Rectangle<int> rect;
  228152. AsyncRepaintMessage (UIViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  228153. : peer (peer_), rect (rect_)
  228154. {
  228155. }
  228156. void messageCallback()
  228157. {
  228158. if (ComponentPeer::isValidPeer (peer))
  228159. peer->repaint (rect);
  228160. }
  228161. };
  228162. void UIViewComponentPeer::repaint (const Rectangle<int>& area)
  228163. {
  228164. if (insideDrawRect || ! MessageManager::getInstance()->isThisTheMessageThread())
  228165. {
  228166. (new AsyncRepaintMessage (this, area))->post();
  228167. }
  228168. else
  228169. {
  228170. [view setNeedsDisplayInRect: convertToCGRect (area)];
  228171. }
  228172. }
  228173. void UIViewComponentPeer::performAnyPendingRepaintsNow()
  228174. {
  228175. }
  228176. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  228177. {
  228178. return new UIViewComponentPeer (this, styleFlags, (UIView*) windowToAttachTo);
  228179. }
  228180. const Image juce_createIconForFile (const File& file)
  228181. {
  228182. return Image::null;
  228183. }
  228184. void Desktop::createMouseInputSources()
  228185. {
  228186. for (int i = 0; i < 10; ++i)
  228187. mouseSources.add (new MouseInputSource (i, false));
  228188. }
  228189. bool Desktop::canUseSemiTransparentWindows() throw()
  228190. {
  228191. return true;
  228192. }
  228193. const Point<int> Desktop::getMousePosition()
  228194. {
  228195. return juce_lastMousePos;
  228196. }
  228197. void Desktop::setMousePosition (const Point<int>&)
  228198. {
  228199. }
  228200. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  228201. {
  228202. return convertToJuceOrientation ([[UIApplication sharedApplication] statusBarOrientation]);
  228203. }
  228204. void juce_updateMultiMonitorInfo (Array <Rectangle <int> >& monitorCoords, const bool clipToWorkArea)
  228205. {
  228206. const ScopedAutoReleasePool pool;
  228207. monitorCoords.clear();
  228208. CGRect r = clipToWorkArea ? [[UIScreen mainScreen] applicationFrame]
  228209. : [[UIScreen mainScreen] bounds];
  228210. monitorCoords.add (UIViewComponentPeer::realScreenPosToRotated (convertToRectInt (r)));
  228211. }
  228212. const int KeyPress::spaceKey = ' ';
  228213. const int KeyPress::returnKey = 0x0d;
  228214. const int KeyPress::escapeKey = 0x1b;
  228215. const int KeyPress::backspaceKey = 0x7f;
  228216. const int KeyPress::leftKey = 0x1000;
  228217. const int KeyPress::rightKey = 0x1001;
  228218. const int KeyPress::upKey = 0x1002;
  228219. const int KeyPress::downKey = 0x1003;
  228220. const int KeyPress::pageUpKey = 0x1004;
  228221. const int KeyPress::pageDownKey = 0x1005;
  228222. const int KeyPress::endKey = 0x1006;
  228223. const int KeyPress::homeKey = 0x1007;
  228224. const int KeyPress::deleteKey = 0x1008;
  228225. const int KeyPress::insertKey = -1;
  228226. const int KeyPress::tabKey = 9;
  228227. const int KeyPress::F1Key = 0x2001;
  228228. const int KeyPress::F2Key = 0x2002;
  228229. const int KeyPress::F3Key = 0x2003;
  228230. const int KeyPress::F4Key = 0x2004;
  228231. const int KeyPress::F5Key = 0x2005;
  228232. const int KeyPress::F6Key = 0x2006;
  228233. const int KeyPress::F7Key = 0x2007;
  228234. const int KeyPress::F8Key = 0x2008;
  228235. const int KeyPress::F9Key = 0x2009;
  228236. const int KeyPress::F10Key = 0x200a;
  228237. const int KeyPress::F11Key = 0x200b;
  228238. const int KeyPress::F12Key = 0x200c;
  228239. const int KeyPress::F13Key = 0x200d;
  228240. const int KeyPress::F14Key = 0x200e;
  228241. const int KeyPress::F15Key = 0x200f;
  228242. const int KeyPress::F16Key = 0x2010;
  228243. const int KeyPress::numberPad0 = 0x30020;
  228244. const int KeyPress::numberPad1 = 0x30021;
  228245. const int KeyPress::numberPad2 = 0x30022;
  228246. const int KeyPress::numberPad3 = 0x30023;
  228247. const int KeyPress::numberPad4 = 0x30024;
  228248. const int KeyPress::numberPad5 = 0x30025;
  228249. const int KeyPress::numberPad6 = 0x30026;
  228250. const int KeyPress::numberPad7 = 0x30027;
  228251. const int KeyPress::numberPad8 = 0x30028;
  228252. const int KeyPress::numberPad9 = 0x30029;
  228253. const int KeyPress::numberPadAdd = 0x3002a;
  228254. const int KeyPress::numberPadSubtract = 0x3002b;
  228255. const int KeyPress::numberPadMultiply = 0x3002c;
  228256. const int KeyPress::numberPadDivide = 0x3002d;
  228257. const int KeyPress::numberPadSeparator = 0x3002e;
  228258. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  228259. const int KeyPress::numberPadEquals = 0x30030;
  228260. const int KeyPress::numberPadDelete = 0x30031;
  228261. const int KeyPress::playKey = 0x30000;
  228262. const int KeyPress::stopKey = 0x30001;
  228263. const int KeyPress::fastForwardKey = 0x30002;
  228264. const int KeyPress::rewindKey = 0x30003;
  228265. #endif
  228266. /*** End of inlined file: juce_iphone_UIViewComponentPeer.mm ***/
  228267. /*** Start of inlined file: juce_iphone_MessageManager.mm ***/
  228268. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228269. // compiled on its own).
  228270. #if JUCE_INCLUDED_FILE
  228271. struct CallbackMessagePayload
  228272. {
  228273. MessageCallbackFunction* function;
  228274. void* parameter;
  228275. void* volatile result;
  228276. bool volatile hasBeenExecuted;
  228277. };
  228278. END_JUCE_NAMESPACE
  228279. @interface JuceCustomMessageHandler : NSObject
  228280. {
  228281. }
  228282. - (void) performCallback: (id) info;
  228283. @end
  228284. @implementation JuceCustomMessageHandler
  228285. - (void) performCallback: (id) info
  228286. {
  228287. if ([info isKindOfClass: [NSData class]])
  228288. {
  228289. JUCE_NAMESPACE::CallbackMessagePayload* pl = (JUCE_NAMESPACE::CallbackMessagePayload*) [((NSData*) info) bytes];
  228290. if (pl != 0)
  228291. {
  228292. pl->result = (*pl->function) (pl->parameter);
  228293. pl->hasBeenExecuted = true;
  228294. }
  228295. }
  228296. else
  228297. {
  228298. jassertfalse; // should never get here!
  228299. }
  228300. }
  228301. @end
  228302. BEGIN_JUCE_NAMESPACE
  228303. void MessageManager::runDispatchLoop()
  228304. {
  228305. jassert (isThisTheMessageThread()); // must only be called by the message thread
  228306. runDispatchLoopUntil (-1);
  228307. }
  228308. void MessageManager::stopDispatchLoop()
  228309. {
  228310. [[[UIApplication sharedApplication] delegate] applicationWillTerminate: [UIApplication sharedApplication]];
  228311. exit (0); // iPhone apps get no mercy..
  228312. }
  228313. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  228314. {
  228315. const ScopedAutoReleasePool pool;
  228316. jassert (isThisTheMessageThread()); // must only be called by the message thread
  228317. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  228318. NSDate* endDate = [NSDate dateWithTimeIntervalSinceNow: millisecondsToRunFor * 0.001];
  228319. while (! quitMessagePosted)
  228320. {
  228321. const ScopedAutoReleasePool pool;
  228322. [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode
  228323. beforeDate: endDate];
  228324. if (millisecondsToRunFor >= 0 && Time::getMillisecondCounter() >= endTime)
  228325. break;
  228326. }
  228327. return ! quitMessagePosted;
  228328. }
  228329. namespace iOSMessageLoopHelpers
  228330. {
  228331. static CFRunLoopRef runLoop = 0;
  228332. static CFRunLoopSourceRef runLoopSource = 0;
  228333. static OwnedArray <Message, CriticalSection>* pendingMessages = 0;
  228334. static JuceCustomMessageHandler* juceCustomMessageHandler = 0;
  228335. void runLoopSourceCallback (void*)
  228336. {
  228337. if (pendingMessages != 0)
  228338. {
  228339. int numDispatched = 0;
  228340. do
  228341. {
  228342. Message* const nextMessage = pendingMessages->removeAndReturn (0);
  228343. if (nextMessage == 0)
  228344. return;
  228345. const ScopedAutoReleasePool pool;
  228346. MessageManager::getInstance()->deliverMessage (nextMessage);
  228347. } while (++numDispatched <= 4);
  228348. CFRunLoopSourceSignal (runLoopSource);
  228349. CFRunLoopWakeUp (runLoop);
  228350. }
  228351. }
  228352. }
  228353. void MessageManager::doPlatformSpecificInitialisation()
  228354. {
  228355. using namespace iOSMessageLoopHelpers;
  228356. pendingMessages = new OwnedArray <Message, CriticalSection>();
  228357. runLoop = CFRunLoopGetCurrent();
  228358. CFRunLoopSourceContext sourceContext;
  228359. zerostruct (sourceContext);
  228360. sourceContext.perform = runLoopSourceCallback;
  228361. runLoopSource = CFRunLoopSourceCreate (kCFAllocatorDefault, 1, &sourceContext);
  228362. CFRunLoopAddSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  228363. if (juceCustomMessageHandler == 0)
  228364. juceCustomMessageHandler = [[JuceCustomMessageHandler alloc] init];
  228365. }
  228366. void MessageManager::doPlatformSpecificShutdown()
  228367. {
  228368. using namespace iOSMessageLoopHelpers;
  228369. CFRunLoopSourceInvalidate (runLoopSource);
  228370. CFRelease (runLoopSource);
  228371. runLoopSource = 0;
  228372. deleteAndZero (pendingMessages);
  228373. if (juceCustomMessageHandler != 0)
  228374. {
  228375. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceCustomMessageHandler];
  228376. [juceCustomMessageHandler release];
  228377. juceCustomMessageHandler = 0;
  228378. }
  228379. }
  228380. bool juce_postMessageToSystemQueue (Message* message)
  228381. {
  228382. using namespace iOSMessageLoopHelpers;
  228383. if (pendingMessages != 0)
  228384. {
  228385. pendingMessages->add (message);
  228386. CFRunLoopSourceSignal (runLoopSource);
  228387. CFRunLoopWakeUp (runLoop);
  228388. }
  228389. return true;
  228390. }
  228391. void MessageManager::broadcastMessage (const String& value)
  228392. {
  228393. }
  228394. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback, void* data)
  228395. {
  228396. using namespace iOSMessageLoopHelpers;
  228397. if (isThisTheMessageThread())
  228398. {
  228399. return (*callback) (data);
  228400. }
  228401. else
  228402. {
  228403. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  228404. // deadlock because the message manager is blocked from running, so can never
  228405. // call your function..
  228406. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  228407. const ScopedAutoReleasePool pool;
  228408. CallbackMessagePayload cmp;
  228409. cmp.function = callback;
  228410. cmp.parameter = data;
  228411. cmp.result = 0;
  228412. cmp.hasBeenExecuted = false;
  228413. [juceCustomMessageHandler performSelectorOnMainThread: @selector (performCallback:)
  228414. withObject: [NSData dataWithBytesNoCopy: &cmp
  228415. length: sizeof (cmp)
  228416. freeWhenDone: NO]
  228417. waitUntilDone: YES];
  228418. return cmp.result;
  228419. }
  228420. }
  228421. #endif
  228422. /*** End of inlined file: juce_iphone_MessageManager.mm ***/
  228423. /*** Start of inlined file: juce_mac_FileChooser.mm ***/
  228424. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228425. // compiled on its own).
  228426. #if JUCE_INCLUDED_FILE
  228427. #if JUCE_MAC
  228428. END_JUCE_NAMESPACE
  228429. using namespace JUCE_NAMESPACE;
  228430. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  228431. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  228432. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  228433. #else
  228434. @interface JuceFileChooserDelegate : NSObject
  228435. #endif
  228436. {
  228437. StringArray* filters;
  228438. }
  228439. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  228440. - (void) dealloc;
  228441. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  228442. @end
  228443. @implementation JuceFileChooserDelegate
  228444. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  228445. {
  228446. [super init];
  228447. filters = filters_;
  228448. return self;
  228449. }
  228450. - (void) dealloc
  228451. {
  228452. delete filters;
  228453. [super dealloc];
  228454. }
  228455. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  228456. {
  228457. (void) sender;
  228458. const File f (nsStringToJuce (filename));
  228459. for (int i = filters->size(); --i >= 0;)
  228460. if (f.getFileName().matchesWildcard ((*filters)[i], true))
  228461. return true;
  228462. return f.isDirectory();
  228463. }
  228464. @end
  228465. BEGIN_JUCE_NAMESPACE
  228466. void FileChooser::showPlatformDialog (Array<File>& results,
  228467. const String& title,
  228468. const File& currentFileOrDirectory,
  228469. const String& filter,
  228470. bool selectsDirectory,
  228471. bool selectsFiles,
  228472. bool isSaveDialogue,
  228473. bool warnAboutOverwritingExistingFiles,
  228474. bool selectMultipleFiles,
  228475. FilePreviewComponent* extraInfoComponent)
  228476. {
  228477. const ScopedAutoReleasePool pool;
  228478. StringArray* filters = new StringArray();
  228479. filters->addTokens (filter.replaceCharacters (",:", ";;"), ";", String::empty);
  228480. filters->trim();
  228481. filters->removeEmptyStrings();
  228482. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  228483. [delegate autorelease];
  228484. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  228485. : [NSOpenPanel openPanel];
  228486. [panel setTitle: juceStringToNS (title)];
  228487. if (! isSaveDialogue)
  228488. {
  228489. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  228490. [openPanel setCanChooseDirectories: selectsDirectory];
  228491. [openPanel setCanChooseFiles: selectsFiles];
  228492. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  228493. }
  228494. [panel setDelegate: delegate];
  228495. if (isSaveDialogue || selectsDirectory)
  228496. [panel setCanCreateDirectories: YES];
  228497. String directory, filename;
  228498. if (currentFileOrDirectory.isDirectory())
  228499. {
  228500. directory = currentFileOrDirectory.getFullPathName();
  228501. }
  228502. else
  228503. {
  228504. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  228505. filename = currentFileOrDirectory.getFileName();
  228506. }
  228507. if ([panel runModalForDirectory: juceStringToNS (directory)
  228508. file: juceStringToNS (filename)]
  228509. == NSOKButton)
  228510. {
  228511. if (isSaveDialogue)
  228512. {
  228513. results.add (File (nsStringToJuce ([panel filename])));
  228514. }
  228515. else
  228516. {
  228517. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  228518. NSArray* urls = [openPanel filenames];
  228519. for (unsigned int i = 0; i < [urls count]; ++i)
  228520. {
  228521. NSString* f = [urls objectAtIndex: i];
  228522. results.add (File (nsStringToJuce (f)));
  228523. }
  228524. }
  228525. }
  228526. [panel setDelegate: nil];
  228527. }
  228528. #else
  228529. void FileChooser::showPlatformDialog (Array<File>& results,
  228530. const String& title,
  228531. const File& currentFileOrDirectory,
  228532. const String& filter,
  228533. bool selectsDirectory,
  228534. bool selectsFiles,
  228535. bool isSaveDialogue,
  228536. bool warnAboutOverwritingExistingFiles,
  228537. bool selectMultipleFiles,
  228538. FilePreviewComponent* extraInfoComponent)
  228539. {
  228540. const ScopedAutoReleasePool pool;
  228541. jassertfalse; //xxx to do
  228542. }
  228543. #endif
  228544. #endif
  228545. /*** End of inlined file: juce_mac_FileChooser.mm ***/
  228546. /*** Start of inlined file: juce_mac_OpenGLComponent.mm ***/
  228547. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228548. // compiled on its own).
  228549. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  228550. #if JUCE_MAC
  228551. END_JUCE_NAMESPACE
  228552. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  228553. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  228554. {
  228555. CriticalSection* contextLock;
  228556. bool needsUpdate;
  228557. }
  228558. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  228559. - (bool) makeActive;
  228560. - (void) makeInactive;
  228561. - (void) reshape;
  228562. @end
  228563. @implementation ThreadSafeNSOpenGLView
  228564. - (id) initWithFrame: (NSRect) frameRect
  228565. pixelFormat: (NSOpenGLPixelFormat*) format
  228566. {
  228567. contextLock = new CriticalSection();
  228568. self = [super initWithFrame: frameRect pixelFormat: format];
  228569. if (self != nil)
  228570. [[NSNotificationCenter defaultCenter] addObserver: self
  228571. selector: @selector (_surfaceNeedsUpdate:)
  228572. name: NSViewGlobalFrameDidChangeNotification
  228573. object: self];
  228574. return self;
  228575. }
  228576. - (void) dealloc
  228577. {
  228578. [[NSNotificationCenter defaultCenter] removeObserver: self];
  228579. delete contextLock;
  228580. [super dealloc];
  228581. }
  228582. - (bool) makeActive
  228583. {
  228584. const ScopedLock sl (*contextLock);
  228585. if ([self openGLContext] == 0)
  228586. return false;
  228587. [[self openGLContext] makeCurrentContext];
  228588. if (needsUpdate)
  228589. {
  228590. [super update];
  228591. needsUpdate = false;
  228592. }
  228593. return true;
  228594. }
  228595. - (void) makeInactive
  228596. {
  228597. const ScopedLock sl (*contextLock);
  228598. [NSOpenGLContext clearCurrentContext];
  228599. }
  228600. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  228601. {
  228602. const ScopedLock sl (*contextLock);
  228603. needsUpdate = true;
  228604. }
  228605. - (void) update
  228606. {
  228607. const ScopedLock sl (*contextLock);
  228608. needsUpdate = true;
  228609. }
  228610. - (void) reshape
  228611. {
  228612. const ScopedLock sl (*contextLock);
  228613. needsUpdate = true;
  228614. }
  228615. @end
  228616. BEGIN_JUCE_NAMESPACE
  228617. class WindowedGLContext : public OpenGLContext
  228618. {
  228619. public:
  228620. WindowedGLContext (Component* const component,
  228621. const OpenGLPixelFormat& pixelFormat_,
  228622. NSOpenGLContext* sharedContext)
  228623. : renderContext (0),
  228624. pixelFormat (pixelFormat_)
  228625. {
  228626. jassert (component != 0);
  228627. NSOpenGLPixelFormatAttribute attribs [64];
  228628. int n = 0;
  228629. attribs[n++] = NSOpenGLPFADoubleBuffer;
  228630. attribs[n++] = NSOpenGLPFAAccelerated;
  228631. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  228632. attribs[n++] = NSOpenGLPFAColorSize;
  228633. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  228634. pixelFormat.greenBits,
  228635. pixelFormat.blueBits);
  228636. attribs[n++] = NSOpenGLPFAAlphaSize;
  228637. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  228638. attribs[n++] = NSOpenGLPFADepthSize;
  228639. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  228640. attribs[n++] = NSOpenGLPFAStencilSize;
  228641. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  228642. attribs[n++] = NSOpenGLPFAAccumSize;
  228643. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  228644. pixelFormat.accumulationBufferGreenBits,
  228645. pixelFormat.accumulationBufferBlueBits,
  228646. pixelFormat.accumulationBufferAlphaBits);
  228647. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  228648. attribs[n++] = NSOpenGLPFASampleBuffers;
  228649. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  228650. attribs[n++] = NSOpenGLPFAClosestPolicy;
  228651. attribs[n++] = NSOpenGLPFANoRecovery;
  228652. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  228653. NSOpenGLPixelFormat* format
  228654. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  228655. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  228656. pixelFormat: format];
  228657. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  228658. shareContext: sharedContext] autorelease];
  228659. const GLint swapInterval = 1;
  228660. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  228661. [view setOpenGLContext: renderContext];
  228662. [format release];
  228663. viewHolder = new NSViewComponentInternal (view, component);
  228664. }
  228665. ~WindowedGLContext()
  228666. {
  228667. deleteContext();
  228668. viewHolder = 0;
  228669. }
  228670. void deleteContext()
  228671. {
  228672. makeInactive();
  228673. [renderContext clearDrawable];
  228674. [renderContext setView: nil];
  228675. [view setOpenGLContext: nil];
  228676. renderContext = nil;
  228677. }
  228678. bool makeActive() const throw()
  228679. {
  228680. jassert (renderContext != 0);
  228681. if ([renderContext view] != view)
  228682. [renderContext setView: view];
  228683. [view makeActive];
  228684. return isActive();
  228685. }
  228686. bool makeInactive() const throw()
  228687. {
  228688. [view makeInactive];
  228689. return true;
  228690. }
  228691. bool isActive() const throw()
  228692. {
  228693. return [NSOpenGLContext currentContext] == renderContext;
  228694. }
  228695. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  228696. void* getRawContext() const throw() { return renderContext; }
  228697. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  228698. {
  228699. }
  228700. void swapBuffers()
  228701. {
  228702. [renderContext flushBuffer];
  228703. }
  228704. bool setSwapInterval (const int numFramesPerSwap)
  228705. {
  228706. [renderContext setValues: (const GLint*) &numFramesPerSwap
  228707. forParameter: NSOpenGLCPSwapInterval];
  228708. return true;
  228709. }
  228710. int getSwapInterval() const
  228711. {
  228712. GLint numFrames = 0;
  228713. [renderContext getValues: &numFrames
  228714. forParameter: NSOpenGLCPSwapInterval];
  228715. return numFrames;
  228716. }
  228717. void repaint()
  228718. {
  228719. // we need to invalidate the juce view that holds this gl view, to make it
  228720. // cause a repaint callback
  228721. NSView* v = (NSView*) viewHolder->view;
  228722. NSRect r = [v frame];
  228723. // bit of a bodge here.. if we only invalidate the area of the gl component,
  228724. // it's completely covered by the NSOpenGLView, so the OS throws away the
  228725. // repaint message, thus never causing our paint() callback, and never repainting
  228726. // the comp. So invalidating just a little bit around the edge helps..
  228727. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  228728. }
  228729. void* getNativeWindowHandle() const { return viewHolder->view; }
  228730. juce_UseDebuggingNewOperator
  228731. NSOpenGLContext* renderContext;
  228732. ThreadSafeNSOpenGLView* view;
  228733. private:
  228734. OpenGLPixelFormat pixelFormat;
  228735. ScopedPointer <NSViewComponentInternal> viewHolder;
  228736. WindowedGLContext (const WindowedGLContext&);
  228737. WindowedGLContext& operator= (const WindowedGLContext&);
  228738. };
  228739. OpenGLContext* OpenGLComponent::createContext()
  228740. {
  228741. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  228742. contextToShareListsWith != 0 ? (NSOpenGLContext*) contextToShareListsWith->getRawContext() : 0));
  228743. return (c->renderContext != 0) ? c.release() : 0;
  228744. }
  228745. void* OpenGLComponent::getNativeWindowHandle() const
  228746. {
  228747. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle()
  228748. : 0;
  228749. }
  228750. void juce_glViewport (const int w, const int h)
  228751. {
  228752. glViewport (0, 0, w, h);
  228753. }
  228754. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  228755. OwnedArray <OpenGLPixelFormat>& results)
  228756. {
  228757. /* GLint attribs [64];
  228758. int n = 0;
  228759. attribs[n++] = AGL_RGBA;
  228760. attribs[n++] = AGL_DOUBLEBUFFER;
  228761. attribs[n++] = AGL_ACCELERATED;
  228762. attribs[n++] = AGL_NO_RECOVERY;
  228763. attribs[n++] = AGL_NONE;
  228764. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  228765. while (p != 0)
  228766. {
  228767. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  228768. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  228769. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  228770. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  228771. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  228772. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  228773. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  228774. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  228775. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  228776. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  228777. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  228778. results.add (pf);
  228779. p = aglNextPixelFormat (p);
  228780. }*/
  228781. //jassertfalse // can't see how you do this in cocoa!
  228782. }
  228783. #else
  228784. END_JUCE_NAMESPACE
  228785. @interface JuceGLView : UIView
  228786. {
  228787. }
  228788. + (Class) layerClass;
  228789. @end
  228790. @implementation JuceGLView
  228791. + (Class) layerClass
  228792. {
  228793. return [CAEAGLLayer class];
  228794. }
  228795. @end
  228796. BEGIN_JUCE_NAMESPACE
  228797. class GLESContext : public OpenGLContext
  228798. {
  228799. public:
  228800. GLESContext (UIViewComponentPeer* peer,
  228801. Component* const component_,
  228802. const OpenGLPixelFormat& pixelFormat_,
  228803. const GLESContext* const sharedContext,
  228804. NSUInteger apiType)
  228805. : component (component_), pixelFormat (pixelFormat_), glLayer (0), context (0),
  228806. useDepthBuffer (pixelFormat_.depthBufferBits > 0), frameBufferHandle (0), colorBufferHandle (0),
  228807. depthBufferHandle (0), lastWidth (0), lastHeight (0)
  228808. {
  228809. view = [[JuceGLView alloc] initWithFrame: CGRectMake (0, 0, 64, 64)];
  228810. view.opaque = YES;
  228811. view.hidden = NO;
  228812. view.backgroundColor = [UIColor blackColor];
  228813. view.userInteractionEnabled = NO;
  228814. glLayer = (CAEAGLLayer*) [view layer];
  228815. [peer->view addSubview: view];
  228816. if (sharedContext != 0)
  228817. context = [[EAGLContext alloc] initWithAPI: apiType
  228818. sharegroup: [sharedContext->context sharegroup]];
  228819. else
  228820. context = [[EAGLContext alloc] initWithAPI: apiType];
  228821. createGLBuffers();
  228822. }
  228823. ~GLESContext()
  228824. {
  228825. deleteContext();
  228826. [view removeFromSuperview];
  228827. [view release];
  228828. freeGLBuffers();
  228829. }
  228830. void deleteContext()
  228831. {
  228832. makeInactive();
  228833. [context release];
  228834. context = nil;
  228835. }
  228836. bool makeActive() const throw()
  228837. {
  228838. jassert (context != 0);
  228839. [EAGLContext setCurrentContext: context];
  228840. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  228841. return true;
  228842. }
  228843. void swapBuffers()
  228844. {
  228845. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  228846. [context presentRenderbuffer: GL_RENDERBUFFER_OES];
  228847. }
  228848. bool makeInactive() const throw()
  228849. {
  228850. return [EAGLContext setCurrentContext: nil];
  228851. }
  228852. bool isActive() const throw()
  228853. {
  228854. return [EAGLContext currentContext] == context;
  228855. }
  228856. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  228857. void* getRawContext() const throw() { return glLayer; }
  228858. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  228859. {
  228860. view.frame = CGRectMake ((CGFloat) x, (CGFloat) y, (CGFloat) w, (CGFloat) h);
  228861. if (lastWidth != w || lastHeight != h)
  228862. {
  228863. lastWidth = w;
  228864. lastHeight = h;
  228865. freeGLBuffers();
  228866. createGLBuffers();
  228867. }
  228868. }
  228869. bool setSwapInterval (const int numFramesPerSwap)
  228870. {
  228871. numFrames = numFramesPerSwap;
  228872. return true;
  228873. }
  228874. int getSwapInterval() const
  228875. {
  228876. return numFrames;
  228877. }
  228878. void repaint()
  228879. {
  228880. }
  228881. void createGLBuffers()
  228882. {
  228883. makeActive();
  228884. glGenFramebuffersOES (1, &frameBufferHandle);
  228885. glGenRenderbuffersOES (1, &colorBufferHandle);
  228886. glGenRenderbuffersOES (1, &depthBufferHandle);
  228887. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  228888. [context renderbufferStorage: GL_RENDERBUFFER_OES fromDrawable: glLayer];
  228889. GLint width, height;
  228890. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &width);
  228891. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &height);
  228892. if (useDepthBuffer)
  228893. {
  228894. glBindRenderbufferOES (GL_RENDERBUFFER_OES, depthBufferHandle);
  228895. glRenderbufferStorageOES (GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height);
  228896. }
  228897. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  228898. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  228899. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorBufferHandle);
  228900. if (useDepthBuffer)
  228901. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBufferHandle);
  228902. jassert (glCheckFramebufferStatusOES (GL_FRAMEBUFFER_OES) == GL_FRAMEBUFFER_COMPLETE_OES);
  228903. }
  228904. void freeGLBuffers()
  228905. {
  228906. if (frameBufferHandle != 0)
  228907. {
  228908. glDeleteFramebuffersOES (1, &frameBufferHandle);
  228909. frameBufferHandle = 0;
  228910. }
  228911. if (colorBufferHandle != 0)
  228912. {
  228913. glDeleteRenderbuffersOES (1, &colorBufferHandle);
  228914. colorBufferHandle = 0;
  228915. }
  228916. if (depthBufferHandle != 0)
  228917. {
  228918. glDeleteRenderbuffersOES (1, &depthBufferHandle);
  228919. depthBufferHandle = 0;
  228920. }
  228921. }
  228922. juce_UseDebuggingNewOperator
  228923. private:
  228924. Component::SafePointer<Component> component;
  228925. OpenGLPixelFormat pixelFormat;
  228926. JuceGLView* view;
  228927. CAEAGLLayer* glLayer;
  228928. EAGLContext* context;
  228929. bool useDepthBuffer;
  228930. GLuint frameBufferHandle, colorBufferHandle, depthBufferHandle;
  228931. int numFrames;
  228932. int lastWidth, lastHeight;
  228933. GLESContext (const GLESContext&);
  228934. GLESContext& operator= (const GLESContext&);
  228935. };
  228936. OpenGLContext* OpenGLComponent::createContext()
  228937. {
  228938. ScopedAutoReleasePool pool;
  228939. UIViewComponentPeer* peer = dynamic_cast <UIViewComponentPeer*> (getPeer());
  228940. if (peer != 0)
  228941. return new GLESContext (peer, this, preferredPixelFormat,
  228942. dynamic_cast <const GLESContext*> (contextToShareListsWith),
  228943. type == openGLES2 ? kEAGLRenderingAPIOpenGLES2 : kEAGLRenderingAPIOpenGLES1);
  228944. return 0;
  228945. }
  228946. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  228947. OwnedArray <OpenGLPixelFormat>& /*results*/)
  228948. {
  228949. }
  228950. void juce_glViewport (const int w, const int h)
  228951. {
  228952. glViewport (0, 0, w, h);
  228953. }
  228954. #endif
  228955. #endif
  228956. /*** End of inlined file: juce_mac_OpenGLComponent.mm ***/
  228957. /*** Start of inlined file: juce_mac_MouseCursor.mm ***/
  228958. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228959. // compiled on its own).
  228960. #if JUCE_INCLUDED_FILE
  228961. #if JUCE_MAC
  228962. namespace MouseCursorHelpers
  228963. {
  228964. static void* createFromImage (const Image& image, float hotspotX, float hotspotY)
  228965. {
  228966. NSImage* im = CoreGraphicsImage::createNSImage (image);
  228967. NSCursor* c = [[NSCursor alloc] initWithImage: im
  228968. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  228969. [im release];
  228970. return c;
  228971. }
  228972. static void* fromWebKitFile (const char* filename, float hx, float hy)
  228973. {
  228974. FileInputStream fileStream (String ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources/") + filename);
  228975. BufferedInputStream buf (fileStream, 4096);
  228976. PNGImageFormat pngFormat;
  228977. Image im (pngFormat.decodeImage (buf));
  228978. if (im.isValid())
  228979. return createFromImage (im, hx * im.getWidth(), hy * im.getHeight());
  228980. jassertfalse;
  228981. return 0;
  228982. }
  228983. }
  228984. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  228985. {
  228986. return MouseCursorHelpers::createFromImage (image, (float) hotspotX, (float) hotspotY);
  228987. }
  228988. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  228989. {
  228990. const ScopedAutoReleasePool pool;
  228991. NSCursor* c = 0;
  228992. switch (type)
  228993. {
  228994. case NormalCursor: c = [NSCursor arrowCursor]; break;
  228995. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 8, 8, true), 0, 0);
  228996. case DraggingHandCursor: c = [NSCursor openHandCursor]; break;
  228997. case WaitCursor: c = [NSCursor arrowCursor]; break; // avoid this on the mac, let the OS provide the beachball
  228998. case IBeamCursor: c = [NSCursor IBeamCursor]; break;
  228999. case PointingHandCursor: c = [NSCursor pointingHandCursor]; break;
  229000. case LeftRightResizeCursor: c = [NSCursor resizeLeftRightCursor]; break;
  229001. case LeftEdgeResizeCursor: c = [NSCursor resizeLeftCursor]; break;
  229002. case RightEdgeResizeCursor: c = [NSCursor resizeRightCursor]; break;
  229003. case CrosshairCursor: c = [NSCursor crosshairCursor]; break;
  229004. case CopyingCursor: return MouseCursorHelpers::fromWebKitFile ("copyCursor.png", 0, 0);
  229005. case UpDownResizeCursor:
  229006. case TopEdgeResizeCursor:
  229007. case BottomEdgeResizeCursor:
  229008. return MouseCursorHelpers::fromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  229009. case TopLeftCornerResizeCursor:
  229010. case BottomRightCornerResizeCursor:
  229011. return MouseCursorHelpers::fromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  229012. case TopRightCornerResizeCursor:
  229013. case BottomLeftCornerResizeCursor:
  229014. return MouseCursorHelpers::fromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  229015. case UpDownLeftRightResizeCursor:
  229016. return MouseCursorHelpers::fromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  229017. default:
  229018. jassertfalse;
  229019. break;
  229020. }
  229021. [c retain];
  229022. return c;
  229023. }
  229024. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool /*isStandard*/)
  229025. {
  229026. [((NSCursor*) cursorHandle) release];
  229027. }
  229028. void MouseCursor::showInAllWindows() const
  229029. {
  229030. showInWindow (0);
  229031. }
  229032. void MouseCursor::showInWindow (ComponentPeer*) const
  229033. {
  229034. NSCursor* c = (NSCursor*) getHandle();
  229035. if (c == 0)
  229036. c = [NSCursor arrowCursor];
  229037. [c set];
  229038. }
  229039. #else
  229040. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) { return 0; }
  229041. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type) { return 0; }
  229042. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard) {}
  229043. void MouseCursor::showInAllWindows() const {}
  229044. void MouseCursor::showInWindow (ComponentPeer*) const {}
  229045. #endif
  229046. #endif
  229047. /*** End of inlined file: juce_mac_MouseCursor.mm ***/
  229048. /*** Start of inlined file: juce_mac_WebBrowserComponent.mm ***/
  229049. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229050. // compiled on its own).
  229051. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  229052. #if JUCE_MAC
  229053. END_JUCE_NAMESPACE
  229054. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  229055. @interface DownloadClickDetector : NSObject
  229056. {
  229057. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  229058. }
  229059. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  229060. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  229061. request: (NSURLRequest*) request
  229062. frame: (WebFrame*) frame
  229063. decisionListener: (id<WebPolicyDecisionListener>) listener;
  229064. @end
  229065. @implementation DownloadClickDetector
  229066. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  229067. {
  229068. [super init];
  229069. ownerComponent = ownerComponent_;
  229070. return self;
  229071. }
  229072. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  229073. request: (NSURLRequest*) request
  229074. frame: (WebFrame*) frame
  229075. decisionListener: (id <WebPolicyDecisionListener>) listener
  229076. {
  229077. (void) sender;
  229078. (void) request;
  229079. (void) frame;
  229080. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  229081. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  229082. [listener use];
  229083. else
  229084. [listener ignore];
  229085. }
  229086. @end
  229087. BEGIN_JUCE_NAMESPACE
  229088. class WebBrowserComponentInternal : public NSViewComponent
  229089. {
  229090. public:
  229091. WebBrowserComponentInternal (WebBrowserComponent* owner)
  229092. {
  229093. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  229094. frameName: @""
  229095. groupName: @""];
  229096. setView (webView);
  229097. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  229098. [webView setPolicyDelegate: clickListener];
  229099. }
  229100. ~WebBrowserComponentInternal()
  229101. {
  229102. [webView setPolicyDelegate: nil];
  229103. [clickListener release];
  229104. setView (0);
  229105. }
  229106. void goToURL (const String& url,
  229107. const StringArray* headers,
  229108. const MemoryBlock* postData)
  229109. {
  229110. NSMutableURLRequest* r
  229111. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  229112. cachePolicy: NSURLRequestUseProtocolCachePolicy
  229113. timeoutInterval: 30.0];
  229114. if (postData != 0 && postData->getSize() > 0)
  229115. {
  229116. [r setHTTPMethod: @"POST"];
  229117. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  229118. length: postData->getSize()]];
  229119. }
  229120. if (headers != 0)
  229121. {
  229122. for (int i = 0; i < headers->size(); ++i)
  229123. {
  229124. const String headerName ((*headers)[i].upToFirstOccurrenceOf (":", false, false).trim());
  229125. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (":", false, false).trim());
  229126. [r setValue: juceStringToNS (headerValue)
  229127. forHTTPHeaderField: juceStringToNS (headerName)];
  229128. }
  229129. }
  229130. stop();
  229131. [[webView mainFrame] loadRequest: r];
  229132. }
  229133. void goBack()
  229134. {
  229135. [webView goBack];
  229136. }
  229137. void goForward()
  229138. {
  229139. [webView goForward];
  229140. }
  229141. void stop()
  229142. {
  229143. [webView stopLoading: nil];
  229144. }
  229145. void refresh()
  229146. {
  229147. [webView reload: nil];
  229148. }
  229149. private:
  229150. WebView* webView;
  229151. DownloadClickDetector* clickListener;
  229152. };
  229153. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  229154. : browser (0),
  229155. blankPageShown (false),
  229156. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  229157. {
  229158. setOpaque (true);
  229159. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  229160. }
  229161. WebBrowserComponent::~WebBrowserComponent()
  229162. {
  229163. deleteAndZero (browser);
  229164. }
  229165. void WebBrowserComponent::goToURL (const String& url,
  229166. const StringArray* headers,
  229167. const MemoryBlock* postData)
  229168. {
  229169. lastURL = url;
  229170. lastHeaders.clear();
  229171. if (headers != 0)
  229172. lastHeaders = *headers;
  229173. lastPostData.setSize (0);
  229174. if (postData != 0)
  229175. lastPostData = *postData;
  229176. blankPageShown = false;
  229177. browser->goToURL (url, headers, postData);
  229178. }
  229179. void WebBrowserComponent::stop()
  229180. {
  229181. browser->stop();
  229182. }
  229183. void WebBrowserComponent::goBack()
  229184. {
  229185. lastURL = String::empty;
  229186. blankPageShown = false;
  229187. browser->goBack();
  229188. }
  229189. void WebBrowserComponent::goForward()
  229190. {
  229191. lastURL = String::empty;
  229192. browser->goForward();
  229193. }
  229194. void WebBrowserComponent::refresh()
  229195. {
  229196. browser->refresh();
  229197. }
  229198. void WebBrowserComponent::paint (Graphics&)
  229199. {
  229200. }
  229201. void WebBrowserComponent::checkWindowAssociation()
  229202. {
  229203. if (isShowing())
  229204. {
  229205. if (blankPageShown)
  229206. goBack();
  229207. }
  229208. else
  229209. {
  229210. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  229211. {
  229212. // when the component becomes invisible, some stuff like flash
  229213. // carries on playing audio, so we need to force it onto a blank
  229214. // page to avoid this, (and send it back when it's made visible again).
  229215. blankPageShown = true;
  229216. browser->goToURL ("about:blank", 0, 0);
  229217. }
  229218. }
  229219. }
  229220. void WebBrowserComponent::reloadLastURL()
  229221. {
  229222. if (lastURL.isNotEmpty())
  229223. {
  229224. goToURL (lastURL, &lastHeaders, &lastPostData);
  229225. lastURL = String::empty;
  229226. }
  229227. }
  229228. void WebBrowserComponent::parentHierarchyChanged()
  229229. {
  229230. checkWindowAssociation();
  229231. }
  229232. void WebBrowserComponent::resized()
  229233. {
  229234. browser->setSize (getWidth(), getHeight());
  229235. }
  229236. void WebBrowserComponent::visibilityChanged()
  229237. {
  229238. checkWindowAssociation();
  229239. }
  229240. bool WebBrowserComponent::pageAboutToLoad (const String&)
  229241. {
  229242. return true;
  229243. }
  229244. #else
  229245. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  229246. {
  229247. }
  229248. WebBrowserComponent::~WebBrowserComponent()
  229249. {
  229250. }
  229251. void WebBrowserComponent::goToURL (const String& url,
  229252. const StringArray* headers,
  229253. const MemoryBlock* postData)
  229254. {
  229255. }
  229256. void WebBrowserComponent::stop()
  229257. {
  229258. }
  229259. void WebBrowserComponent::goBack()
  229260. {
  229261. }
  229262. void WebBrowserComponent::goForward()
  229263. {
  229264. }
  229265. void WebBrowserComponent::refresh()
  229266. {
  229267. }
  229268. void WebBrowserComponent::paint (Graphics& g)
  229269. {
  229270. }
  229271. void WebBrowserComponent::checkWindowAssociation()
  229272. {
  229273. }
  229274. void WebBrowserComponent::reloadLastURL()
  229275. {
  229276. }
  229277. void WebBrowserComponent::parentHierarchyChanged()
  229278. {
  229279. }
  229280. void WebBrowserComponent::resized()
  229281. {
  229282. }
  229283. void WebBrowserComponent::visibilityChanged()
  229284. {
  229285. }
  229286. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  229287. {
  229288. return true;
  229289. }
  229290. #endif
  229291. #endif
  229292. /*** End of inlined file: juce_mac_WebBrowserComponent.mm ***/
  229293. /*** Start of inlined file: juce_iphone_Audio.cpp ***/
  229294. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229295. // compiled on its own).
  229296. #if JUCE_INCLUDED_FILE
  229297. class IPhoneAudioIODevice : public AudioIODevice
  229298. {
  229299. public:
  229300. IPhoneAudioIODevice (const String& deviceName)
  229301. : AudioIODevice (deviceName, "Audio"),
  229302. actualBufferSize (0),
  229303. isRunning (false),
  229304. audioUnit (0),
  229305. callback (0),
  229306. floatData (1, 2)
  229307. {
  229308. numInputChannels = 2;
  229309. numOutputChannels = 2;
  229310. preferredBufferSize = 0;
  229311. AudioSessionInitialize (0, 0, interruptionListenerStatic, this);
  229312. updateDeviceInfo();
  229313. }
  229314. ~IPhoneAudioIODevice()
  229315. {
  229316. close();
  229317. }
  229318. const StringArray getOutputChannelNames()
  229319. {
  229320. StringArray s;
  229321. s.add ("Left");
  229322. s.add ("Right");
  229323. return s;
  229324. }
  229325. const StringArray getInputChannelNames()
  229326. {
  229327. StringArray s;
  229328. if (audioInputIsAvailable)
  229329. {
  229330. s.add ("Left");
  229331. s.add ("Right");
  229332. }
  229333. return s;
  229334. }
  229335. int getNumSampleRates()
  229336. {
  229337. return 1;
  229338. }
  229339. double getSampleRate (int index)
  229340. {
  229341. return sampleRate;
  229342. }
  229343. int getNumBufferSizesAvailable()
  229344. {
  229345. return 1;
  229346. }
  229347. int getBufferSizeSamples (int index)
  229348. {
  229349. return getDefaultBufferSize();
  229350. }
  229351. int getDefaultBufferSize()
  229352. {
  229353. return 1024;
  229354. }
  229355. const String open (const BigInteger& inputChannels,
  229356. const BigInteger& outputChannels,
  229357. double sampleRate,
  229358. int bufferSize)
  229359. {
  229360. close();
  229361. lastError = String::empty;
  229362. preferredBufferSize = (bufferSize <= 0) ? getDefaultBufferSize() : bufferSize;
  229363. // xxx set up channel mapping
  229364. activeOutputChans = outputChannels;
  229365. activeOutputChans.setRange (2, activeOutputChans.getHighestBit(), false);
  229366. numOutputChannels = activeOutputChans.countNumberOfSetBits();
  229367. monoOutputChannelNumber = activeOutputChans.findNextSetBit (0);
  229368. activeInputChans = inputChannels;
  229369. activeInputChans.setRange (2, activeInputChans.getHighestBit(), false);
  229370. numInputChannels = activeInputChans.countNumberOfSetBits();
  229371. monoInputChannelNumber = activeInputChans.findNextSetBit (0);
  229372. AudioSessionSetActive (true);
  229373. UInt32 audioCategory = audioInputIsAvailable ? kAudioSessionCategory_PlayAndRecord
  229374. : kAudioSessionCategory_MediaPlayback;
  229375. AudioSessionSetProperty (kAudioSessionProperty_AudioCategory, sizeof (audioCategory), &audioCategory);
  229376. AudioSessionAddPropertyListener (kAudioSessionProperty_AudioRouteChange, propertyChangedStatic, this);
  229377. fixAudioRouteIfSetToReceiver();
  229378. updateDeviceInfo();
  229379. Float32 bufferDuration = preferredBufferSize / sampleRate;
  229380. AudioSessionSetProperty (kAudioSessionProperty_PreferredHardwareIOBufferDuration, sizeof (bufferDuration), &bufferDuration);
  229381. actualBufferSize = preferredBufferSize;
  229382. prepareFloatBuffers();
  229383. isRunning = true;
  229384. propertyChanged (0, 0, 0); // creates and starts the AU
  229385. lastError = audioUnit != 0 ? "" : "Couldn't open the device";
  229386. return lastError;
  229387. }
  229388. void close()
  229389. {
  229390. if (isRunning)
  229391. {
  229392. isRunning = false;
  229393. AudioSessionSetActive (false);
  229394. if (audioUnit != 0)
  229395. {
  229396. AudioComponentInstanceDispose (audioUnit);
  229397. audioUnit = 0;
  229398. }
  229399. }
  229400. }
  229401. bool isOpen()
  229402. {
  229403. return isRunning;
  229404. }
  229405. int getCurrentBufferSizeSamples()
  229406. {
  229407. return actualBufferSize;
  229408. }
  229409. double getCurrentSampleRate()
  229410. {
  229411. return sampleRate;
  229412. }
  229413. int getCurrentBitDepth()
  229414. {
  229415. return 16;
  229416. }
  229417. const BigInteger getActiveOutputChannels() const
  229418. {
  229419. return activeOutputChans;
  229420. }
  229421. const BigInteger getActiveInputChannels() const
  229422. {
  229423. return activeInputChans;
  229424. }
  229425. int getOutputLatencyInSamples()
  229426. {
  229427. return 0; //xxx
  229428. }
  229429. int getInputLatencyInSamples()
  229430. {
  229431. return 0; //xxx
  229432. }
  229433. void start (AudioIODeviceCallback* callback_)
  229434. {
  229435. if (isRunning && callback != callback_)
  229436. {
  229437. if (callback_ != 0)
  229438. callback_->audioDeviceAboutToStart (this);
  229439. const ScopedLock sl (callbackLock);
  229440. callback = callback_;
  229441. }
  229442. }
  229443. void stop()
  229444. {
  229445. if (isRunning)
  229446. {
  229447. AudioIODeviceCallback* lastCallback;
  229448. {
  229449. const ScopedLock sl (callbackLock);
  229450. lastCallback = callback;
  229451. callback = 0;
  229452. }
  229453. if (lastCallback != 0)
  229454. lastCallback->audioDeviceStopped();
  229455. }
  229456. }
  229457. bool isPlaying()
  229458. {
  229459. return isRunning && callback != 0;
  229460. }
  229461. const String getLastError()
  229462. {
  229463. return lastError;
  229464. }
  229465. private:
  229466. CriticalSection callbackLock;
  229467. Float64 sampleRate;
  229468. int numInputChannels, numOutputChannels;
  229469. int preferredBufferSize;
  229470. int actualBufferSize;
  229471. bool isRunning;
  229472. String lastError;
  229473. AudioStreamBasicDescription format;
  229474. AudioUnit audioUnit;
  229475. UInt32 audioInputIsAvailable;
  229476. AudioIODeviceCallback* callback;
  229477. BigInteger activeOutputChans, activeInputChans;
  229478. AudioSampleBuffer floatData;
  229479. float* inputChannels[3];
  229480. float* outputChannels[3];
  229481. bool monoInputChannelNumber, monoOutputChannelNumber;
  229482. void prepareFloatBuffers()
  229483. {
  229484. floatData.setSize (numInputChannels + numOutputChannels, actualBufferSize);
  229485. zerostruct (inputChannels);
  229486. zerostruct (outputChannels);
  229487. for (int i = 0; i < numInputChannels; ++i)
  229488. inputChannels[i] = floatData.getSampleData (i);
  229489. for (int i = 0; i < numOutputChannels; ++i)
  229490. outputChannels[i] = floatData.getSampleData (i + numInputChannels);
  229491. }
  229492. OSStatus process (AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  229493. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData)
  229494. {
  229495. OSStatus err = noErr;
  229496. if (audioInputIsAvailable)
  229497. err = AudioUnitRender (audioUnit, ioActionFlags, inTimeStamp, 1, inNumberFrames, ioData);
  229498. const ScopedLock sl (callbackLock);
  229499. if (callback != 0)
  229500. {
  229501. if (audioInputIsAvailable && numInputChannels > 0)
  229502. {
  229503. short* shortData = (short*) ioData->mBuffers[0].mData;
  229504. if (numInputChannels >= 2)
  229505. {
  229506. for (UInt32 i = 0; i < inNumberFrames; ++i)
  229507. {
  229508. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  229509. inputChannels[1][i] = *shortData++ * (1.0f / 32768.0f);
  229510. }
  229511. }
  229512. else
  229513. {
  229514. if (monoInputChannelNumber > 0)
  229515. ++shortData;
  229516. for (UInt32 i = 0; i < inNumberFrames; ++i)
  229517. {
  229518. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  229519. ++shortData;
  229520. }
  229521. }
  229522. }
  229523. else
  229524. {
  229525. for (int i = numInputChannels; --i >= 0;)
  229526. zeromem (inputChannels[i], sizeof (float) * inNumberFrames);
  229527. }
  229528. callback->audioDeviceIOCallback ((const float**) inputChannels, numInputChannels,
  229529. outputChannels, numOutputChannels,
  229530. (int) inNumberFrames);
  229531. short* shortData = (short*) ioData->mBuffers[0].mData;
  229532. int n = 0;
  229533. if (numOutputChannels >= 2)
  229534. {
  229535. for (UInt32 i = 0; i < inNumberFrames; ++i)
  229536. {
  229537. shortData [n++] = (short) (outputChannels[0][i] * 32767.0f);
  229538. shortData [n++] = (short) (outputChannels[1][i] * 32767.0f);
  229539. }
  229540. }
  229541. else if (numOutputChannels == 1)
  229542. {
  229543. for (UInt32 i = 0; i < inNumberFrames; ++i)
  229544. {
  229545. const short s = (short) (outputChannels[monoOutputChannelNumber][i] * 32767.0f);
  229546. shortData [n++] = s;
  229547. shortData [n++] = s;
  229548. }
  229549. }
  229550. else
  229551. {
  229552. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  229553. }
  229554. }
  229555. else
  229556. {
  229557. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  229558. }
  229559. return err;
  229560. }
  229561. void updateDeviceInfo()
  229562. {
  229563. UInt32 size = sizeof (sampleRate);
  229564. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareSampleRate, &size, &sampleRate);
  229565. size = sizeof (audioInputIsAvailable);
  229566. AudioSessionGetProperty (kAudioSessionProperty_AudioInputAvailable, &size, &audioInputIsAvailable);
  229567. }
  229568. void propertyChanged (AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  229569. {
  229570. if (! isRunning)
  229571. return;
  229572. if (inPropertyValue != 0)
  229573. {
  229574. CFDictionaryRef routeChangeDictionary = (CFDictionaryRef) inPropertyValue;
  229575. CFNumberRef routeChangeReasonRef = (CFNumberRef) CFDictionaryGetValue (routeChangeDictionary,
  229576. CFSTR (kAudioSession_AudioRouteChangeKey_Reason));
  229577. SInt32 routeChangeReason;
  229578. CFNumberGetValue (routeChangeReasonRef, kCFNumberSInt32Type, &routeChangeReason);
  229579. if (routeChangeReason == kAudioSessionRouteChangeReason_OldDeviceUnavailable)
  229580. fixAudioRouteIfSetToReceiver();
  229581. }
  229582. updateDeviceInfo();
  229583. createAudioUnit();
  229584. AudioSessionSetActive (true);
  229585. if (audioUnit != 0)
  229586. {
  229587. UInt32 formatSize = sizeof (format);
  229588. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, &formatSize);
  229589. Float32 bufferDuration = preferredBufferSize / sampleRate;
  229590. UInt32 bufferDurationSize = sizeof (bufferDuration);
  229591. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareIOBufferDuration, &bufferDurationSize, &bufferDurationSize);
  229592. actualBufferSize = (int) (sampleRate * bufferDuration + 0.5);
  229593. AudioOutputUnitStart (audioUnit);
  229594. }
  229595. }
  229596. void interruptionListener (UInt32 inInterruption)
  229597. {
  229598. /*if (inInterruption == kAudioSessionBeginInterruption)
  229599. {
  229600. isRunning = false;
  229601. AudioOutputUnitStop (audioUnit);
  229602. if (juce_iPhoneShowModalAlert ("Audio Interrupted",
  229603. "This could have been interrupted by another application or by unplugging a headset",
  229604. @"Resume",
  229605. @"Cancel"))
  229606. {
  229607. isRunning = true;
  229608. propertyChanged (0, 0, 0);
  229609. }
  229610. }*/
  229611. if (inInterruption == kAudioSessionEndInterruption)
  229612. {
  229613. isRunning = true;
  229614. AudioSessionSetActive (true);
  229615. AudioOutputUnitStart (audioUnit);
  229616. }
  229617. }
  229618. static OSStatus processStatic (void* inRefCon, AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  229619. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData)
  229620. {
  229621. return ((IPhoneAudioIODevice*) inRefCon)->process (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  229622. }
  229623. static void propertyChangedStatic (void* inClientData, AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  229624. {
  229625. ((IPhoneAudioIODevice*) inClientData)->propertyChanged (inID, inDataSize, inPropertyValue);
  229626. }
  229627. static void interruptionListenerStatic (void* inClientData, UInt32 inInterruption)
  229628. {
  229629. ((IPhoneAudioIODevice*) inClientData)->interruptionListener (inInterruption);
  229630. }
  229631. void resetFormat (const int numChannels)
  229632. {
  229633. memset (&format, 0, sizeof (format));
  229634. format.mFormatID = kAudioFormatLinearPCM;
  229635. format.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked;
  229636. format.mBitsPerChannel = 8 * sizeof (short);
  229637. format.mChannelsPerFrame = 2;
  229638. format.mFramesPerPacket = 1;
  229639. format.mBytesPerFrame = format.mBytesPerPacket = 2 * sizeof (short);
  229640. }
  229641. bool createAudioUnit()
  229642. {
  229643. if (audioUnit != 0)
  229644. {
  229645. AudioComponentInstanceDispose (audioUnit);
  229646. audioUnit = 0;
  229647. }
  229648. resetFormat (2);
  229649. AudioComponentDescription desc;
  229650. desc.componentType = kAudioUnitType_Output;
  229651. desc.componentSubType = kAudioUnitSubType_RemoteIO;
  229652. desc.componentManufacturer = kAudioUnitManufacturer_Apple;
  229653. desc.componentFlags = 0;
  229654. desc.componentFlagsMask = 0;
  229655. AudioComponent comp = AudioComponentFindNext (0, &desc);
  229656. AudioComponentInstanceNew (comp, &audioUnit);
  229657. if (audioUnit == 0)
  229658. return false;
  229659. const UInt32 one = 1;
  229660. AudioUnitSetProperty (audioUnit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, 1, &one, sizeof (one));
  229661. AudioChannelLayout layout;
  229662. layout.mChannelBitmap = 0;
  229663. layout.mNumberChannelDescriptions = 0;
  229664. layout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  229665. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Input, 0, &layout, sizeof (layout));
  229666. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Output, 0, &layout, sizeof (layout));
  229667. AURenderCallbackStruct inputProc;
  229668. inputProc.inputProc = processStatic;
  229669. inputProc.inputProcRefCon = this;
  229670. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &inputProc, sizeof (inputProc));
  229671. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &format, sizeof (format));
  229672. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, sizeof (format));
  229673. AudioUnitInitialize (audioUnit);
  229674. return true;
  229675. }
  229676. // If the routing is set to go through the receiver (i.e. the speaker, but quiet), this re-routes it
  229677. // to make it loud. Needed because by default when using an input + output, the output is kept quiet.
  229678. static void fixAudioRouteIfSetToReceiver()
  229679. {
  229680. CFStringRef audioRoute = 0;
  229681. UInt32 propertySize = sizeof (audioRoute);
  229682. if (AudioSessionGetProperty (kAudioSessionProperty_AudioRoute, &propertySize, &audioRoute) == noErr)
  229683. {
  229684. NSString* route = (NSString*) audioRoute;
  229685. //DBG ("audio route: " + nsStringToJuce (route));
  229686. if ([route hasPrefix: @"Receiver"])
  229687. {
  229688. UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
  229689. AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute, sizeof (audioRouteOverride), &audioRouteOverride);
  229690. }
  229691. CFRelease (audioRoute);
  229692. }
  229693. }
  229694. IPhoneAudioIODevice (const IPhoneAudioIODevice&);
  229695. IPhoneAudioIODevice& operator= (const IPhoneAudioIODevice&);
  229696. };
  229697. class IPhoneAudioIODeviceType : public AudioIODeviceType
  229698. {
  229699. public:
  229700. IPhoneAudioIODeviceType()
  229701. : AudioIODeviceType ("iPhone Audio")
  229702. {
  229703. }
  229704. ~IPhoneAudioIODeviceType()
  229705. {
  229706. }
  229707. void scanForDevices()
  229708. {
  229709. }
  229710. const StringArray getDeviceNames (bool wantInputNames) const
  229711. {
  229712. StringArray s;
  229713. s.add ("iPhone Audio");
  229714. return s;
  229715. }
  229716. int getDefaultDeviceIndex (bool forInput) const
  229717. {
  229718. return 0;
  229719. }
  229720. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  229721. {
  229722. return device != 0 ? 0 : -1;
  229723. }
  229724. bool hasSeparateInputsAndOutputs() const { return false; }
  229725. AudioIODevice* createDevice (const String& outputDeviceName,
  229726. const String& inputDeviceName)
  229727. {
  229728. if (outputDeviceName.isNotEmpty() || inputDeviceName.isNotEmpty())
  229729. {
  229730. return new IPhoneAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  229731. : inputDeviceName);
  229732. }
  229733. return 0;
  229734. }
  229735. juce_UseDebuggingNewOperator
  229736. private:
  229737. IPhoneAudioIODeviceType (const IPhoneAudioIODeviceType&);
  229738. IPhoneAudioIODeviceType& operator= (const IPhoneAudioIODeviceType&);
  229739. };
  229740. AudioIODeviceType* juce_createAudioIODeviceType_iPhoneAudio()
  229741. {
  229742. return new IPhoneAudioIODeviceType();
  229743. }
  229744. #endif
  229745. /*** End of inlined file: juce_iphone_Audio.cpp ***/
  229746. /*** Start of inlined file: juce_mac_CoreMidi.cpp ***/
  229747. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229748. // compiled on its own).
  229749. #if JUCE_INCLUDED_FILE
  229750. #if JUCE_MAC
  229751. namespace CoreMidiHelpers
  229752. {
  229753. static bool logError (const OSStatus err, const int lineNum)
  229754. {
  229755. if (err == noErr)
  229756. return true;
  229757. Logger::writeToLog ("CoreMidi error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  229758. jassertfalse;
  229759. return false;
  229760. }
  229761. #undef CHECK_ERROR
  229762. #define CHECK_ERROR(a) CoreMidiHelpers::logError (a, __LINE__)
  229763. static const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  229764. {
  229765. String result;
  229766. CFStringRef str = 0;
  229767. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  229768. if (str != 0)
  229769. {
  229770. result = PlatformUtilities::cfStringToJuceString (str);
  229771. CFRelease (str);
  229772. str = 0;
  229773. }
  229774. MIDIEntityRef entity = 0;
  229775. MIDIEndpointGetEntity (endpoint, &entity);
  229776. if (entity == 0)
  229777. return result; // probably virtual
  229778. if (result.isEmpty())
  229779. {
  229780. // endpoint name has zero length - try the entity
  229781. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  229782. if (str != 0)
  229783. {
  229784. result += PlatformUtilities::cfStringToJuceString (str);
  229785. CFRelease (str);
  229786. str = 0;
  229787. }
  229788. }
  229789. // now consider the device's name
  229790. MIDIDeviceRef device = 0;
  229791. MIDIEntityGetDevice (entity, &device);
  229792. if (device == 0)
  229793. return result;
  229794. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  229795. if (str != 0)
  229796. {
  229797. const String s (PlatformUtilities::cfStringToJuceString (str));
  229798. CFRelease (str);
  229799. // if an external device has only one entity, throw away
  229800. // the endpoint name and just use the device name
  229801. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  229802. {
  229803. result = s;
  229804. }
  229805. else if (! result.startsWithIgnoreCase (s))
  229806. {
  229807. // prepend the device name to the entity name
  229808. result = (s + " " + result).trimEnd();
  229809. }
  229810. }
  229811. return result;
  229812. }
  229813. static const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  229814. {
  229815. String result;
  229816. // Does the endpoint have connections?
  229817. CFDataRef connections = 0;
  229818. int numConnections = 0;
  229819. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  229820. if (connections != 0)
  229821. {
  229822. numConnections = (int) (CFDataGetLength (connections) / sizeof (MIDIUniqueID));
  229823. if (numConnections > 0)
  229824. {
  229825. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  229826. for (int i = 0; i < numConnections; ++i, ++pid)
  229827. {
  229828. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  229829. MIDIObjectRef connObject;
  229830. MIDIObjectType connObjectType;
  229831. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  229832. if (err == noErr)
  229833. {
  229834. String s;
  229835. if (connObjectType == kMIDIObjectType_ExternalSource
  229836. || connObjectType == kMIDIObjectType_ExternalDestination)
  229837. {
  229838. // Connected to an external device's endpoint (10.3 and later).
  229839. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  229840. }
  229841. else
  229842. {
  229843. // Connected to an external device (10.2) (or something else, catch-all)
  229844. CFStringRef str = 0;
  229845. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  229846. if (str != 0)
  229847. {
  229848. s = PlatformUtilities::cfStringToJuceString (str);
  229849. CFRelease (str);
  229850. }
  229851. }
  229852. if (s.isNotEmpty())
  229853. {
  229854. if (result.isNotEmpty())
  229855. result += ", ";
  229856. result += s;
  229857. }
  229858. }
  229859. }
  229860. }
  229861. CFRelease (connections);
  229862. }
  229863. if (result.isNotEmpty())
  229864. return result;
  229865. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  229866. return getEndpointName (endpoint, false);
  229867. }
  229868. static MIDIClientRef getGlobalMidiClient()
  229869. {
  229870. static MIDIClientRef globalMidiClient = 0;
  229871. if (globalMidiClient == 0)
  229872. {
  229873. String name ("JUCE");
  229874. if (JUCEApplication::getInstance() != 0)
  229875. name = JUCEApplication::getInstance()->getApplicationName();
  229876. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  229877. CHECK_ERROR (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  229878. CFRelease (appName);
  229879. }
  229880. return globalMidiClient;
  229881. }
  229882. class MidiPortAndEndpoint
  229883. {
  229884. public:
  229885. MidiPortAndEndpoint (MIDIPortRef port_, MIDIEndpointRef endPoint_)
  229886. : port (port_), endPoint (endPoint_)
  229887. {
  229888. }
  229889. ~MidiPortAndEndpoint()
  229890. {
  229891. if (port != 0)
  229892. MIDIPortDispose (port);
  229893. if (port == 0 && endPoint != 0) // if port == 0, it means we created the endpoint, so it's safe to delete it
  229894. MIDIEndpointDispose (endPoint);
  229895. }
  229896. void send (const MIDIPacketList* const packets)
  229897. {
  229898. if (port != 0)
  229899. MIDISend (port, endPoint, packets);
  229900. else
  229901. MIDIReceived (endPoint, packets);
  229902. }
  229903. MIDIPortRef port;
  229904. MIDIEndpointRef endPoint;
  229905. };
  229906. class MidiPortAndCallback;
  229907. static CriticalSection callbackLock;
  229908. static Array<MidiPortAndCallback*> activeCallbacks;
  229909. class MidiPortAndCallback
  229910. {
  229911. public:
  229912. MidiPortAndCallback (MidiInputCallback& callback_)
  229913. : input (0), active (false), callback (callback_), concatenator (2048)
  229914. {
  229915. }
  229916. ~MidiPortAndCallback()
  229917. {
  229918. active = false;
  229919. {
  229920. const ScopedLock sl (callbackLock);
  229921. activeCallbacks.removeValue (this);
  229922. }
  229923. if (portAndEndpoint != 0 && portAndEndpoint->port != 0)
  229924. CHECK_ERROR (MIDIPortDisconnectSource (portAndEndpoint->port, portAndEndpoint->endPoint));
  229925. }
  229926. void handlePackets (const MIDIPacketList* const pktlist)
  229927. {
  229928. const double time = Time::getMillisecondCounterHiRes() * 0.001;
  229929. const ScopedLock sl (callbackLock);
  229930. if (activeCallbacks.contains (this) && active)
  229931. {
  229932. const MIDIPacket* packet = &pktlist->packet[0];
  229933. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  229934. {
  229935. concatenator.pushMidiData (packet->data, (int) packet->length, time,
  229936. input, callback);
  229937. packet = MIDIPacketNext (packet);
  229938. }
  229939. }
  229940. }
  229941. MidiInput* input;
  229942. ScopedPointer<MidiPortAndEndpoint> portAndEndpoint;
  229943. volatile bool active;
  229944. private:
  229945. MidiInputCallback& callback;
  229946. MidiDataConcatenator concatenator;
  229947. };
  229948. static void midiInputProc (const MIDIPacketList* pktlist, void* readProcRefCon, void* /*srcConnRefCon*/)
  229949. {
  229950. static_cast <MidiPortAndCallback*> (readProcRefCon)->handlePackets (pktlist);
  229951. }
  229952. }
  229953. const StringArray MidiOutput::getDevices()
  229954. {
  229955. StringArray s;
  229956. const ItemCount num = MIDIGetNumberOfDestinations();
  229957. for (ItemCount i = 0; i < num; ++i)
  229958. {
  229959. MIDIEndpointRef dest = MIDIGetDestination (i);
  229960. if (dest != 0)
  229961. {
  229962. String name (CoreMidiHelpers::getConnectedEndpointName (dest));
  229963. if (name.isEmpty())
  229964. name = "<error>";
  229965. s.add (name);
  229966. }
  229967. else
  229968. {
  229969. s.add ("<error>");
  229970. }
  229971. }
  229972. return s;
  229973. }
  229974. int MidiOutput::getDefaultDeviceIndex()
  229975. {
  229976. return 0;
  229977. }
  229978. MidiOutput* MidiOutput::openDevice (int index)
  229979. {
  229980. MidiOutput* mo = 0;
  229981. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfDestinations())
  229982. {
  229983. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  229984. CFStringRef pname;
  229985. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  229986. {
  229987. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  229988. MIDIPortRef port;
  229989. if (client != 0 && CHECK_ERROR (MIDIOutputPortCreate (client, pname, &port)))
  229990. {
  229991. mo = new MidiOutput();
  229992. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (port, endPoint);
  229993. }
  229994. CFRelease (pname);
  229995. }
  229996. }
  229997. return mo;
  229998. }
  229999. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  230000. {
  230001. MidiOutput* mo = 0;
  230002. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  230003. MIDIEndpointRef endPoint;
  230004. CFStringRef name = PlatformUtilities::juceStringToCFString (deviceName);
  230005. if (client != 0 && CHECK_ERROR (MIDISourceCreate (client, name, &endPoint)))
  230006. {
  230007. mo = new MidiOutput();
  230008. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (0, endPoint);
  230009. }
  230010. CFRelease (name);
  230011. return mo;
  230012. }
  230013. MidiOutput::~MidiOutput()
  230014. {
  230015. delete static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  230016. }
  230017. void MidiOutput::reset()
  230018. {
  230019. }
  230020. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  230021. {
  230022. return false;
  230023. }
  230024. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  230025. {
  230026. }
  230027. void MidiOutput::sendMessageNow (const MidiMessage& message)
  230028. {
  230029. CoreMidiHelpers::MidiPortAndEndpoint* const mpe = static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  230030. if (message.isSysEx())
  230031. {
  230032. const int maxPacketSize = 256;
  230033. int pos = 0, bytesLeft = message.getRawDataSize();
  230034. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  230035. HeapBlock <MIDIPacketList> packets;
  230036. packets.malloc (32 * numPackets + message.getRawDataSize(), 1);
  230037. packets->numPackets = numPackets;
  230038. MIDIPacket* p = packets->packet;
  230039. for (int i = 0; i < numPackets; ++i)
  230040. {
  230041. p->timeStamp = 0;
  230042. p->length = jmin (maxPacketSize, bytesLeft);
  230043. memcpy (p->data, message.getRawData() + pos, p->length);
  230044. pos += p->length;
  230045. bytesLeft -= p->length;
  230046. p = MIDIPacketNext (p);
  230047. }
  230048. mpe->send (packets);
  230049. }
  230050. else
  230051. {
  230052. MIDIPacketList packets;
  230053. packets.numPackets = 1;
  230054. packets.packet[0].timeStamp = 0;
  230055. packets.packet[0].length = message.getRawDataSize();
  230056. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  230057. mpe->send (&packets);
  230058. }
  230059. }
  230060. const StringArray MidiInput::getDevices()
  230061. {
  230062. StringArray s;
  230063. const ItemCount num = MIDIGetNumberOfSources();
  230064. for (ItemCount i = 0; i < num; ++i)
  230065. {
  230066. MIDIEndpointRef source = MIDIGetSource (i);
  230067. if (source != 0)
  230068. {
  230069. String name (CoreMidiHelpers::getConnectedEndpointName (source));
  230070. if (name.isEmpty())
  230071. name = "<error>";
  230072. s.add (name);
  230073. }
  230074. else
  230075. {
  230076. s.add ("<error>");
  230077. }
  230078. }
  230079. return s;
  230080. }
  230081. int MidiInput::getDefaultDeviceIndex()
  230082. {
  230083. return 0;
  230084. }
  230085. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  230086. {
  230087. jassert (callback != 0);
  230088. using namespace CoreMidiHelpers;
  230089. MidiInput* newInput = 0;
  230090. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfSources())
  230091. {
  230092. MIDIEndpointRef endPoint = MIDIGetSource (index);
  230093. if (endPoint != 0)
  230094. {
  230095. CFStringRef name;
  230096. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &name)))
  230097. {
  230098. MIDIClientRef client = getGlobalMidiClient();
  230099. if (client != 0)
  230100. {
  230101. MIDIPortRef port;
  230102. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  230103. if (CHECK_ERROR (MIDIInputPortCreate (client, name, midiInputProc, mpc, &port)))
  230104. {
  230105. if (CHECK_ERROR (MIDIPortConnectSource (port, endPoint, 0)))
  230106. {
  230107. mpc->portAndEndpoint = new MidiPortAndEndpoint (port, endPoint);
  230108. newInput = new MidiInput (getDevices() [index]);
  230109. mpc->input = newInput;
  230110. newInput->internal = mpc;
  230111. const ScopedLock sl (callbackLock);
  230112. activeCallbacks.add (mpc.release());
  230113. }
  230114. else
  230115. {
  230116. CHECK_ERROR (MIDIPortDispose (port));
  230117. }
  230118. }
  230119. }
  230120. }
  230121. CFRelease (name);
  230122. }
  230123. }
  230124. return newInput;
  230125. }
  230126. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  230127. {
  230128. jassert (callback != 0);
  230129. using namespace CoreMidiHelpers;
  230130. MidiInput* mi = 0;
  230131. MIDIClientRef client = getGlobalMidiClient();
  230132. if (client != 0)
  230133. {
  230134. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  230135. mpc->active = false;
  230136. MIDIEndpointRef endPoint;
  230137. CFStringRef name = PlatformUtilities::juceStringToCFString(deviceName);
  230138. if (CHECK_ERROR (MIDIDestinationCreate (client, name, midiInputProc, mpc, &endPoint)))
  230139. {
  230140. mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);
  230141. mi = new MidiInput (deviceName);
  230142. mpc->input = mi;
  230143. mi->internal = mpc;
  230144. const ScopedLock sl (callbackLock);
  230145. activeCallbacks.add (mpc.release());
  230146. }
  230147. CFRelease (name);
  230148. }
  230149. return mi;
  230150. }
  230151. MidiInput::MidiInput (const String& name_)
  230152. : name (name_)
  230153. {
  230154. }
  230155. MidiInput::~MidiInput()
  230156. {
  230157. delete static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal);
  230158. }
  230159. void MidiInput::start()
  230160. {
  230161. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  230162. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = true;
  230163. }
  230164. void MidiInput::stop()
  230165. {
  230166. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  230167. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = false;
  230168. }
  230169. #undef CHECK_ERROR
  230170. #else // Stubs for iOS...
  230171. MidiOutput::~MidiOutput() {}
  230172. void MidiOutput::reset() {}
  230173. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/) { return false; }
  230174. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/) {}
  230175. void MidiOutput::sendMessageNow (const MidiMessage& message) {}
  230176. const StringArray MidiOutput::getDevices() { return StringArray(); }
  230177. MidiOutput* MidiOutput::openDevice (int index) { return 0; }
  230178. const StringArray MidiInput::getDevices() { return StringArray(); }
  230179. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback) { return 0; }
  230180. #endif
  230181. #endif
  230182. /*** End of inlined file: juce_mac_CoreMidi.cpp ***/
  230183. #else
  230184. /*** Start of inlined file: juce_mac_Fonts.mm ***/
  230185. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  230186. // compiled on its own).
  230187. #if JUCE_INCLUDED_FILE
  230188. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  230189. #define SUPPORT_10_4_FONTS 1
  230190. #define NEW_CGFONT_FUNCTIONS_UNAVAILABLE (CGFontCreateWithFontName == 0)
  230191. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  230192. #define SUPPORT_ONLY_10_4_FONTS 1
  230193. #endif
  230194. END_JUCE_NAMESPACE
  230195. @interface NSFont (PrivateHack)
  230196. - (NSGlyph) _defaultGlyphForChar: (unichar) theChar;
  230197. @end
  230198. BEGIN_JUCE_NAMESPACE
  230199. #endif
  230200. class MacTypeface : public Typeface
  230201. {
  230202. public:
  230203. MacTypeface (const Font& font)
  230204. : Typeface (font.getTypefaceName())
  230205. {
  230206. const ScopedAutoReleasePool pool;
  230207. renderingTransform = CGAffineTransformIdentity;
  230208. bool needsItalicTransform = false;
  230209. #if JUCE_IOS
  230210. NSString* fontName = juceStringToNS (font.getTypefaceName());
  230211. if (font.isItalic() || font.isBold())
  230212. {
  230213. NSArray* familyFonts = [UIFont fontNamesForFamilyName: juceStringToNS (font.getTypefaceName())];
  230214. for (NSString* i in familyFonts)
  230215. {
  230216. const String fn (nsStringToJuce (i));
  230217. const String afterDash (fn.fromFirstOccurrenceOf ("-", false, false));
  230218. const bool probablyBold = afterDash.containsIgnoreCase ("bold") || fn.endsWithIgnoreCase ("bold");
  230219. const bool probablyItalic = afterDash.containsIgnoreCase ("oblique")
  230220. || afterDash.containsIgnoreCase ("italic")
  230221. || fn.endsWithIgnoreCase ("oblique")
  230222. || fn.endsWithIgnoreCase ("italic");
  230223. if (probablyBold == font.isBold()
  230224. && probablyItalic == font.isItalic())
  230225. {
  230226. fontName = i;
  230227. needsItalicTransform = false;
  230228. break;
  230229. }
  230230. else if (probablyBold && (! probablyItalic) && probablyBold == font.isBold())
  230231. {
  230232. fontName = i;
  230233. needsItalicTransform = true; // not ideal, so carry on in case we find a better one
  230234. }
  230235. }
  230236. if (needsItalicTransform)
  230237. renderingTransform.c = 0.15f;
  230238. }
  230239. fontRef = CGFontCreateWithFontName ((CFStringRef) fontName);
  230240. const int ascender = abs (CGFontGetAscent (fontRef));
  230241. const float totalHeight = ascender + abs (CGFontGetDescent (fontRef));
  230242. ascent = ascender / totalHeight;
  230243. unitsToHeightScaleFactor = 1.0f / totalHeight;
  230244. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / totalHeight;
  230245. #else
  230246. nsFont = [NSFont fontWithName: juceStringToNS (font.getTypefaceName()) size: 1024];
  230247. if (font.isItalic())
  230248. {
  230249. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: nsFont
  230250. toHaveTrait: NSItalicFontMask];
  230251. if (newFont == nsFont)
  230252. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  230253. nsFont = newFont;
  230254. }
  230255. if (font.isBold())
  230256. nsFont = [[NSFontManager sharedFontManager] convertFont: nsFont toHaveTrait: NSBoldFontMask];
  230257. [nsFont retain];
  230258. ascent = std::abs ((float) [nsFont ascender]);
  230259. float totalSize = ascent + std::abs ((float) [nsFont descender]);
  230260. ascent /= totalSize;
  230261. pathTransform = AffineTransform::identity.scale (1.0f / totalSize, 1.0f / totalSize);
  230262. if (needsItalicTransform)
  230263. {
  230264. pathTransform = pathTransform.sheared (-0.15f, 0.0f);
  230265. renderingTransform.c = 0.15f;
  230266. }
  230267. #if SUPPORT_ONLY_10_4_FONTS
  230268. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  230269. if (atsFont == 0)
  230270. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  230271. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  230272. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  230273. unitsToHeightScaleFactor = 1.0f / totalHeight;
  230274. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  230275. #else
  230276. #if SUPPORT_10_4_FONTS
  230277. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  230278. {
  230279. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  230280. if (atsFont == 0)
  230281. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  230282. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  230283. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  230284. unitsToHeightScaleFactor = 1.0f / totalHeight;
  230285. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  230286. }
  230287. else
  230288. #endif
  230289. {
  230290. fontRef = CGFontCreateWithFontName ((CFStringRef) [nsFont fontName]);
  230291. const int totalHeight = abs (CGFontGetAscent (fontRef)) + abs (CGFontGetDescent (fontRef));
  230292. unitsToHeightScaleFactor = 1.0f / totalHeight;
  230293. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / (float) totalHeight;
  230294. }
  230295. #endif
  230296. #endif
  230297. }
  230298. ~MacTypeface()
  230299. {
  230300. #if ! JUCE_IOS
  230301. [nsFont release];
  230302. #endif
  230303. if (fontRef != 0)
  230304. CGFontRelease (fontRef);
  230305. }
  230306. float getAscent() const
  230307. {
  230308. return ascent;
  230309. }
  230310. float getDescent() const
  230311. {
  230312. return 1.0f - ascent;
  230313. }
  230314. float getStringWidth (const String& text)
  230315. {
  230316. if (fontRef == 0 || text.isEmpty())
  230317. return 0;
  230318. const int length = text.length();
  230319. HeapBlock <CGGlyph> glyphs;
  230320. createGlyphsForString (text, length, glyphs);
  230321. float x = 0;
  230322. #if SUPPORT_ONLY_10_4_FONTS
  230323. HeapBlock <NSSize> advances (length);
  230324. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  230325. for (int i = 0; i < length; ++i)
  230326. x += advances[i].width;
  230327. #else
  230328. #if SUPPORT_10_4_FONTS
  230329. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  230330. {
  230331. HeapBlock <NSSize> advances (length);
  230332. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast<NSGlyph*> (glyphs.getData()) count: length];
  230333. for (int i = 0; i < length; ++i)
  230334. x += advances[i].width;
  230335. }
  230336. else
  230337. #endif
  230338. {
  230339. HeapBlock <int> advances (length);
  230340. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  230341. for (int i = 0; i < length; ++i)
  230342. x += advances[i];
  230343. }
  230344. #endif
  230345. return x * unitsToHeightScaleFactor;
  230346. }
  230347. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  230348. {
  230349. xOffsets.add (0);
  230350. if (fontRef == 0 || text.isEmpty())
  230351. return;
  230352. const int length = text.length();
  230353. HeapBlock <CGGlyph> glyphs;
  230354. createGlyphsForString (text, length, glyphs);
  230355. #if SUPPORT_ONLY_10_4_FONTS
  230356. HeapBlock <NSSize> advances (length);
  230357. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  230358. int x = 0;
  230359. for (int i = 0; i < length; ++i)
  230360. {
  230361. x += advances[i].width;
  230362. xOffsets.add (x * unitsToHeightScaleFactor);
  230363. resultGlyphs.add (reinterpret_cast <NSGlyph*> (glyphs.getData())[i]);
  230364. }
  230365. #else
  230366. #if SUPPORT_10_4_FONTS
  230367. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  230368. {
  230369. HeapBlock <NSSize> advances (length);
  230370. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  230371. [nsFont getAdvancements: advances forGlyphs: nsGlyphs count: length];
  230372. float x = 0;
  230373. for (int i = 0; i < length; ++i)
  230374. {
  230375. x += advances[i].width;
  230376. xOffsets.add (x * unitsToHeightScaleFactor);
  230377. resultGlyphs.add (nsGlyphs[i]);
  230378. }
  230379. }
  230380. else
  230381. #endif
  230382. {
  230383. HeapBlock <int> advances (length);
  230384. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  230385. {
  230386. int x = 0;
  230387. for (int i = 0; i < length; ++i)
  230388. {
  230389. x += advances [i];
  230390. xOffsets.add (x * unitsToHeightScaleFactor);
  230391. resultGlyphs.add (glyphs[i]);
  230392. }
  230393. }
  230394. }
  230395. #endif
  230396. }
  230397. bool getOutlineForGlyph (int glyphNumber, Path& path)
  230398. {
  230399. #if JUCE_IOS
  230400. return false;
  230401. #else
  230402. if (nsFont == 0)
  230403. return false;
  230404. // we might need to apply a transform to the path, so it mustn't have anything else in it
  230405. jassert (path.isEmpty());
  230406. const ScopedAutoReleasePool pool;
  230407. NSBezierPath* bez = [NSBezierPath bezierPath];
  230408. [bez moveToPoint: NSMakePoint (0, 0)];
  230409. [bez appendBezierPathWithGlyph: (NSGlyph) glyphNumber
  230410. inFont: nsFont];
  230411. for (int i = 0; i < [bez elementCount]; ++i)
  230412. {
  230413. NSPoint p[3];
  230414. switch ([bez elementAtIndex: i associatedPoints: p])
  230415. {
  230416. case NSMoveToBezierPathElement:
  230417. path.startNewSubPath ((float) p[0].x, (float) -p[0].y);
  230418. break;
  230419. case NSLineToBezierPathElement:
  230420. path.lineTo ((float) p[0].x, (float) -p[0].y);
  230421. break;
  230422. case NSCurveToBezierPathElement:
  230423. path.cubicTo ((float) p[0].x, (float) -p[0].y, (float) p[1].x, (float) -p[1].y, (float) p[2].x, (float) -p[2].y);
  230424. break;
  230425. case NSClosePathBezierPathElement:
  230426. path.closeSubPath();
  230427. break;
  230428. default:
  230429. jassertfalse;
  230430. break;
  230431. }
  230432. }
  230433. path.applyTransform (pathTransform);
  230434. return true;
  230435. #endif
  230436. }
  230437. juce_UseDebuggingNewOperator
  230438. CGFontRef fontRef;
  230439. float fontHeightToCGSizeFactor;
  230440. CGAffineTransform renderingTransform;
  230441. private:
  230442. float ascent, unitsToHeightScaleFactor;
  230443. #if JUCE_IOS
  230444. #else
  230445. NSFont* nsFont;
  230446. AffineTransform pathTransform;
  230447. #endif
  230448. void createGlyphsForString (const juce_wchar* const text, const int length, HeapBlock <CGGlyph>& glyphs)
  230449. {
  230450. #if SUPPORT_10_4_FONTS
  230451. #if ! SUPPORT_ONLY_10_4_FONTS
  230452. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  230453. #endif
  230454. {
  230455. glyphs.malloc (sizeof (NSGlyph) * length, 1);
  230456. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  230457. for (int i = 0; i < length; ++i)
  230458. nsGlyphs[i] = (NSGlyph) [nsFont _defaultGlyphForChar: text[i]];
  230459. return;
  230460. }
  230461. #endif
  230462. #if ! SUPPORT_ONLY_10_4_FONTS
  230463. if (charToGlyphMapper == 0)
  230464. charToGlyphMapper = new CharToGlyphMapper (fontRef);
  230465. glyphs.malloc (length);
  230466. for (int i = 0; i < length; ++i)
  230467. glyphs[i] = (CGGlyph) charToGlyphMapper->getGlyphForCharacter (text[i]);
  230468. #endif
  230469. }
  230470. #if ! SUPPORT_ONLY_10_4_FONTS
  230471. // Reads a CGFontRef's character map table to convert unicode into glyph numbers
  230472. class CharToGlyphMapper
  230473. {
  230474. public:
  230475. CharToGlyphMapper (CGFontRef fontRef)
  230476. : segCount (0), endCode (0), startCode (0), idDelta (0),
  230477. idRangeOffset (0), glyphIndexes (0)
  230478. {
  230479. CFDataRef cmapTable = CGFontCopyTableForTag (fontRef, 'cmap');
  230480. if (cmapTable != 0)
  230481. {
  230482. const int numSubtables = getValue16 (cmapTable, 2);
  230483. for (int i = 0; i < numSubtables; ++i)
  230484. {
  230485. if (getValue16 (cmapTable, i * 8 + 4) == 0) // check for platform ID of 0
  230486. {
  230487. const int offset = getValue32 (cmapTable, i * 8 + 8);
  230488. if (getValue16 (cmapTable, offset) == 4) // check that it's format 4..
  230489. {
  230490. const int length = getValue16 (cmapTable, offset + 2);
  230491. const int segCountX2 = getValue16 (cmapTable, offset + 6);
  230492. segCount = segCountX2 / 2;
  230493. const int endCodeOffset = offset + 14;
  230494. const int startCodeOffset = endCodeOffset + 2 + segCountX2;
  230495. const int idDeltaOffset = startCodeOffset + segCountX2;
  230496. const int idRangeOffsetOffset = idDeltaOffset + segCountX2;
  230497. const int glyphIndexesOffset = idRangeOffsetOffset + segCountX2;
  230498. endCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + endCodeOffset, segCountX2);
  230499. startCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + startCodeOffset, segCountX2);
  230500. idDelta = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idDeltaOffset, segCountX2);
  230501. idRangeOffset = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idRangeOffsetOffset, segCountX2);
  230502. glyphIndexes = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + glyphIndexesOffset, offset + length - glyphIndexesOffset);
  230503. }
  230504. break;
  230505. }
  230506. }
  230507. CFRelease (cmapTable);
  230508. }
  230509. }
  230510. ~CharToGlyphMapper()
  230511. {
  230512. if (endCode != 0)
  230513. {
  230514. CFRelease (endCode);
  230515. CFRelease (startCode);
  230516. CFRelease (idDelta);
  230517. CFRelease (idRangeOffset);
  230518. CFRelease (glyphIndexes);
  230519. }
  230520. }
  230521. int getGlyphForCharacter (const juce_wchar c) const
  230522. {
  230523. for (int i = 0; i < segCount; ++i)
  230524. {
  230525. if (getValue16 (endCode, i * 2) >= c)
  230526. {
  230527. const int start = getValue16 (startCode, i * 2);
  230528. if (start > c)
  230529. break;
  230530. const int delta = getValue16 (idDelta, i * 2);
  230531. const int rangeOffset = getValue16 (idRangeOffset, i * 2);
  230532. if (rangeOffset == 0)
  230533. return delta + c;
  230534. else
  230535. return getValue16 (glyphIndexes, 2 * ((rangeOffset / 2) + (c - start) - (segCount - i)));
  230536. }
  230537. }
  230538. // If we failed to find it "properly", this dodgy fall-back seems to do the trick for most fonts!
  230539. return jmax (-1, (int) c - 29);
  230540. }
  230541. private:
  230542. int segCount;
  230543. CFDataRef endCode, startCode, idDelta, idRangeOffset, glyphIndexes;
  230544. static uint16 getValue16 (CFDataRef data, const int index)
  230545. {
  230546. return CFSwapInt16BigToHost (*(UInt16*) (CFDataGetBytePtr (data) + index));
  230547. }
  230548. static uint32 getValue32 (CFDataRef data, const int index)
  230549. {
  230550. return CFSwapInt32BigToHost (*(UInt32*) (CFDataGetBytePtr (data) + index));
  230551. }
  230552. };
  230553. ScopedPointer <CharToGlyphMapper> charToGlyphMapper;
  230554. #endif
  230555. MacTypeface (const MacTypeface&);
  230556. MacTypeface& operator= (const MacTypeface&);
  230557. };
  230558. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  230559. {
  230560. return new MacTypeface (font);
  230561. }
  230562. const StringArray Font::findAllTypefaceNames()
  230563. {
  230564. StringArray names;
  230565. const ScopedAutoReleasePool pool;
  230566. #if JUCE_IOS
  230567. NSArray* fonts = [UIFont familyNames];
  230568. #else
  230569. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  230570. #endif
  230571. for (unsigned int i = 0; i < [fonts count]; ++i)
  230572. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  230573. names.sort (true);
  230574. return names;
  230575. }
  230576. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  230577. {
  230578. #if JUCE_IOS
  230579. defaultSans = "Helvetica";
  230580. defaultSerif = "Times New Roman";
  230581. defaultFixed = "Courier New";
  230582. #else
  230583. defaultSans = "Lucida Grande";
  230584. defaultSerif = "Times New Roman";
  230585. defaultFixed = "Monaco";
  230586. #endif
  230587. }
  230588. #endif
  230589. /*** End of inlined file: juce_mac_Fonts.mm ***/
  230590. // (must go before juce_mac_CoreGraphicsContext.mm)
  230591. /*** Start of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  230592. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  230593. // compiled on its own).
  230594. #if JUCE_INCLUDED_FILE
  230595. class CoreGraphicsImage : public Image::SharedImage
  230596. {
  230597. public:
  230598. CoreGraphicsImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  230599. : Image::SharedImage (format_, width_, height_)
  230600. {
  230601. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  230602. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  230603. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  230604. imageData = imageDataAllocated;
  230605. CGColorSpaceRef colourSpace = (format == Image::SingleChannel) ? CGColorSpaceCreateDeviceGray()
  230606. : CGColorSpaceCreateDeviceRGB();
  230607. context = CGBitmapContextCreate (imageData, width, height, 8, lineStride,
  230608. colourSpace, getCGImageFlags (format_));
  230609. CGColorSpaceRelease (colourSpace);
  230610. }
  230611. ~CoreGraphicsImage()
  230612. {
  230613. CGContextRelease (context);
  230614. }
  230615. Image::ImageType getType() const { return Image::NativeImage; }
  230616. LowLevelGraphicsContext* createLowLevelContext();
  230617. SharedImage* clone()
  230618. {
  230619. CoreGraphicsImage* im = new CoreGraphicsImage (format, width, height, false);
  230620. memcpy (im->imageData, imageData, lineStride * height);
  230621. return im;
  230622. }
  230623. static CGImageRef createImage (const Image& juceImage, const bool forAlpha, CGColorSpaceRef colourSpace)
  230624. {
  230625. const CoreGraphicsImage* nativeImage = dynamic_cast <const CoreGraphicsImage*> (juceImage.getSharedImage());
  230626. if (nativeImage != 0 && (juceImage.getFormat() == Image::SingleChannel || ! forAlpha))
  230627. {
  230628. return CGBitmapContextCreateImage (nativeImage->context);
  230629. }
  230630. else
  230631. {
  230632. const Image::BitmapData srcData (juceImage, false);
  230633. CGDataProviderRef provider = CGDataProviderCreateWithData (0, srcData.data, srcData.lineStride * srcData.height, 0);
  230634. CGImageRef imageRef = CGImageCreate (srcData.width, srcData.height,
  230635. 8, srcData.pixelStride * 8, srcData.lineStride,
  230636. colourSpace, getCGImageFlags (juceImage.getFormat()), provider,
  230637. 0, true, kCGRenderingIntentDefault);
  230638. CGDataProviderRelease (provider);
  230639. return imageRef;
  230640. }
  230641. }
  230642. #if JUCE_MAC
  230643. static NSImage* createNSImage (const Image& image)
  230644. {
  230645. const ScopedAutoReleasePool pool;
  230646. NSImage* im = [[NSImage alloc] init];
  230647. [im setSize: NSMakeSize (image.getWidth(), image.getHeight())];
  230648. [im lockFocus];
  230649. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  230650. CGImageRef imageRef = createImage (image, false, colourSpace);
  230651. CGColorSpaceRelease (colourSpace);
  230652. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  230653. CGContextDrawImage (cg, CGRectMake (0, 0, image.getWidth(), image.getHeight()), imageRef);
  230654. CGImageRelease (imageRef);
  230655. [im unlockFocus];
  230656. return im;
  230657. }
  230658. #endif
  230659. CGContextRef context;
  230660. HeapBlock<uint8> imageDataAllocated;
  230661. private:
  230662. static CGBitmapInfo getCGImageFlags (const Image::PixelFormat& format)
  230663. {
  230664. #if JUCE_BIG_ENDIAN
  230665. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big) : kCGBitmapByteOrderDefault;
  230666. #else
  230667. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault;
  230668. #endif
  230669. }
  230670. };
  230671. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  230672. {
  230673. #if USE_COREGRAPHICS_RENDERING
  230674. return new CoreGraphicsImage (format == RGB ? ARGB : format, width, height, clearImage);
  230675. #else
  230676. return createSoftwareImage (format, width, height, clearImage);
  230677. #endif
  230678. }
  230679. class CoreGraphicsContext : public LowLevelGraphicsContext
  230680. {
  230681. public:
  230682. CoreGraphicsContext (CGContextRef context_, const float flipHeight_)
  230683. : context (context_),
  230684. flipHeight (flipHeight_),
  230685. lastClipRectIsValid (false),
  230686. state (new SavedState()),
  230687. numGradientLookupEntries (0)
  230688. {
  230689. CGContextRetain (context);
  230690. CGContextSaveGState(context);
  230691. CGContextSetShouldSmoothFonts (context, true);
  230692. CGContextSetShouldAntialias (context, true);
  230693. CGContextSetBlendMode (context, kCGBlendModeNormal);
  230694. rgbColourSpace = CGColorSpaceCreateDeviceRGB();
  230695. greyColourSpace = CGColorSpaceCreateDeviceGray();
  230696. gradientCallbacks.version = 0;
  230697. gradientCallbacks.evaluate = gradientCallback;
  230698. gradientCallbacks.releaseInfo = 0;
  230699. setFont (Font());
  230700. }
  230701. ~CoreGraphicsContext()
  230702. {
  230703. CGContextRestoreGState (context);
  230704. CGContextRelease (context);
  230705. CGColorSpaceRelease (rgbColourSpace);
  230706. CGColorSpaceRelease (greyColourSpace);
  230707. }
  230708. bool isVectorDevice() const { return false; }
  230709. void setOrigin (int x, int y)
  230710. {
  230711. CGContextTranslateCTM (context, x, -y);
  230712. if (lastClipRectIsValid)
  230713. lastClipRect.translate (-x, -y);
  230714. }
  230715. bool clipToRectangle (const Rectangle<int>& r)
  230716. {
  230717. CGContextClipToRect (context, CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()));
  230718. if (lastClipRectIsValid)
  230719. {
  230720. // This is actually incorrect, because the actual clip region may be complex, and
  230721. // clipping its bounds to a rect may not be right... But, removing this shortcut
  230722. // doesn't actually fix anything because CoreGraphics also ignores complex regions
  230723. // when calculating the resultant clip bounds, and makes the same mistake!
  230724. lastClipRect = lastClipRect.getIntersection (r);
  230725. return ! lastClipRect.isEmpty();
  230726. }
  230727. return ! isClipEmpty();
  230728. }
  230729. bool clipToRectangleList (const RectangleList& clipRegion)
  230730. {
  230731. if (clipRegion.isEmpty())
  230732. {
  230733. CGContextClipToRect (context, CGRectMake (0, 0, 0, 0));
  230734. lastClipRectIsValid = true;
  230735. lastClipRect = Rectangle<int>();
  230736. return false;
  230737. }
  230738. else
  230739. {
  230740. const int numRects = clipRegion.getNumRectangles();
  230741. HeapBlock <CGRect> rects (numRects);
  230742. for (int i = 0; i < numRects; ++i)
  230743. {
  230744. const Rectangle<int>& r = clipRegion.getRectangle(i);
  230745. rects[i] = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  230746. }
  230747. CGContextClipToRects (context, rects, numRects);
  230748. lastClipRectIsValid = false;
  230749. return ! isClipEmpty();
  230750. }
  230751. }
  230752. void excludeClipRectangle (const Rectangle<int>& r)
  230753. {
  230754. RectangleList remaining (getClipBounds());
  230755. remaining.subtract (r);
  230756. clipToRectangleList (remaining);
  230757. lastClipRectIsValid = false;
  230758. }
  230759. void clipToPath (const Path& path, const AffineTransform& transform)
  230760. {
  230761. createPath (path, transform);
  230762. CGContextClip (context);
  230763. lastClipRectIsValid = false;
  230764. }
  230765. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  230766. {
  230767. if (! transform.isSingularity())
  230768. {
  230769. Image singleChannelImage (sourceImage);
  230770. if (sourceImage.getFormat() != Image::SingleChannel)
  230771. singleChannelImage = sourceImage.convertedToFormat (Image::SingleChannel);
  230772. CGImageRef image = CoreGraphicsImage::createImage (singleChannelImage, true, greyColourSpace);
  230773. flip();
  230774. AffineTransform t (AffineTransform::scale (1.0f, -1.0f).translated (0, sourceImage.getHeight()).followedBy (transform));
  230775. applyTransform (t);
  230776. CGRect r = CGRectMake (0, 0, sourceImage.getWidth(), sourceImage.getHeight());
  230777. CGContextClipToMask (context, r, image);
  230778. applyTransform (t.inverted());
  230779. flip();
  230780. CGImageRelease (image);
  230781. lastClipRectIsValid = false;
  230782. }
  230783. }
  230784. bool clipRegionIntersects (const Rectangle<int>& r)
  230785. {
  230786. return getClipBounds().intersects (r);
  230787. }
  230788. const Rectangle<int> getClipBounds() const
  230789. {
  230790. if (! lastClipRectIsValid)
  230791. {
  230792. CGRect bounds = CGRectIntegral (CGContextGetClipBoundingBox (context));
  230793. lastClipRectIsValid = true;
  230794. lastClipRect.setBounds (roundToInt (bounds.origin.x),
  230795. roundToInt (flipHeight - (bounds.origin.y + bounds.size.height)),
  230796. roundToInt (bounds.size.width),
  230797. roundToInt (bounds.size.height));
  230798. }
  230799. return lastClipRect;
  230800. }
  230801. bool isClipEmpty() const
  230802. {
  230803. return getClipBounds().isEmpty();
  230804. }
  230805. void saveState()
  230806. {
  230807. CGContextSaveGState (context);
  230808. stateStack.add (new SavedState (*state));
  230809. }
  230810. void restoreState()
  230811. {
  230812. CGContextRestoreGState (context);
  230813. SavedState* const top = stateStack.getLast();
  230814. if (top != 0)
  230815. {
  230816. state = top;
  230817. stateStack.removeLast (1, false);
  230818. lastClipRectIsValid = false;
  230819. }
  230820. else
  230821. {
  230822. jassertfalse; // trying to pop with an empty stack!
  230823. }
  230824. }
  230825. void setFill (const FillType& fillType)
  230826. {
  230827. state->fillType = fillType;
  230828. if (fillType.isColour())
  230829. {
  230830. CGContextSetRGBFillColor (context, fillType.colour.getFloatRed(), fillType.colour.getFloatGreen(),
  230831. fillType.colour.getFloatBlue(), fillType.colour.getFloatAlpha());
  230832. CGContextSetAlpha (context, 1.0f);
  230833. }
  230834. }
  230835. void setOpacity (float newOpacity)
  230836. {
  230837. state->fillType.setOpacity (newOpacity);
  230838. setFill (state->fillType);
  230839. }
  230840. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  230841. {
  230842. CGContextSetInterpolationQuality (context, quality == Graphics::lowResamplingQuality
  230843. ? kCGInterpolationLow
  230844. : kCGInterpolationHigh);
  230845. }
  230846. void fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  230847. {
  230848. fillCGRect (CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()), replaceExistingContents);
  230849. }
  230850. void fillCGRect (const CGRect& cgRect, const bool replaceExistingContents)
  230851. {
  230852. if (replaceExistingContents)
  230853. {
  230854. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  230855. CGContextClearRect (context, cgRect);
  230856. #else
  230857. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  230858. if (CGContextDrawLinearGradient == 0) // (just a way of checking whether we're running in 10.5 or later)
  230859. CGContextClearRect (context, cgRect);
  230860. else
  230861. #endif
  230862. CGContextSetBlendMode (context, kCGBlendModeCopy);
  230863. #endif
  230864. fillCGRect (cgRect, false);
  230865. CGContextSetBlendMode (context, kCGBlendModeNormal);
  230866. }
  230867. else
  230868. {
  230869. if (state->fillType.isColour())
  230870. {
  230871. CGContextFillRect (context, cgRect);
  230872. }
  230873. else if (state->fillType.isGradient())
  230874. {
  230875. CGContextSaveGState (context);
  230876. CGContextClipToRect (context, cgRect);
  230877. drawGradient();
  230878. CGContextRestoreGState (context);
  230879. }
  230880. else
  230881. {
  230882. CGContextSaveGState (context);
  230883. CGContextClipToRect (context, cgRect);
  230884. drawImage (state->fillType.image, state->fillType.transform, true);
  230885. CGContextRestoreGState (context);
  230886. }
  230887. }
  230888. }
  230889. void fillPath (const Path& path, const AffineTransform& transform)
  230890. {
  230891. CGContextSaveGState (context);
  230892. if (state->fillType.isColour())
  230893. {
  230894. flip();
  230895. applyTransform (transform);
  230896. createPath (path);
  230897. if (path.isUsingNonZeroWinding())
  230898. CGContextFillPath (context);
  230899. else
  230900. CGContextEOFillPath (context);
  230901. }
  230902. else
  230903. {
  230904. createPath (path, transform);
  230905. if (path.isUsingNonZeroWinding())
  230906. CGContextClip (context);
  230907. else
  230908. CGContextEOClip (context);
  230909. if (state->fillType.isGradient())
  230910. drawGradient();
  230911. else
  230912. drawImage (state->fillType.image, state->fillType.transform, true);
  230913. }
  230914. CGContextRestoreGState (context);
  230915. }
  230916. void drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  230917. {
  230918. const int iw = sourceImage.getWidth();
  230919. const int ih = sourceImage.getHeight();
  230920. CGImageRef image = CoreGraphicsImage::createImage (sourceImage, false, rgbColourSpace);
  230921. CGContextSaveGState (context);
  230922. CGContextSetAlpha (context, state->fillType.getOpacity());
  230923. flip();
  230924. applyTransform (AffineTransform::scale (1.0f, -1.0f).translated (0, ih).followedBy (transform));
  230925. CGRect imageRect = CGRectMake (0, 0, iw, ih);
  230926. if (fillEntireClipAsTiles)
  230927. {
  230928. #if JUCE_IOS
  230929. CGContextDrawTiledImage (context, imageRect, image);
  230930. #else
  230931. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  230932. // There's a bug in CGContextDrawTiledImage that makes it incredibly slow
  230933. // if it's doing a transformation - it's quicker to just draw lots of images manually
  230934. if (CGContextDrawTiledImage != 0 && transform.isOnlyTranslation())
  230935. CGContextDrawTiledImage (context, imageRect, image);
  230936. else
  230937. #endif
  230938. {
  230939. // Fallback to manually doing a tiled fill on 10.4
  230940. CGRect clip = CGRectIntegral (CGContextGetClipBoundingBox (context));
  230941. int x = 0, y = 0;
  230942. while (x > clip.origin.x) x -= iw;
  230943. while (y > clip.origin.y) y -= ih;
  230944. const int right = (int) (clip.origin.x + clip.size.width);
  230945. const int bottom = (int) (clip.origin.y + clip.size.height);
  230946. while (y < bottom)
  230947. {
  230948. for (int x2 = x; x2 < right; x2 += iw)
  230949. CGContextDrawImage (context, CGRectMake (x2, y, iw, ih), image);
  230950. y += ih;
  230951. }
  230952. }
  230953. #endif
  230954. }
  230955. else
  230956. {
  230957. CGContextDrawImage (context, imageRect, image);
  230958. }
  230959. CGImageRelease (image); // (This causes a memory bug in iPhone sim 3.0 - try upgrading to a later version if you hit this)
  230960. CGContextRestoreGState (context);
  230961. }
  230962. void drawLine (const Line<float>& line)
  230963. {
  230964. if (state->fillType.isColour())
  230965. {
  230966. CGContextSetLineCap (context, kCGLineCapSquare);
  230967. CGContextSetLineWidth (context, 1.0f);
  230968. CGContextSetRGBStrokeColor (context,
  230969. state->fillType.colour.getFloatRed(), state->fillType.colour.getFloatGreen(),
  230970. state->fillType.colour.getFloatBlue(), state->fillType.colour.getFloatAlpha());
  230971. CGPoint cgLine[] = { { (CGFloat) line.getStartX(), flipHeight - (CGFloat) line.getStartY() },
  230972. { (CGFloat) line.getEndX(), flipHeight - (CGFloat) line.getEndY() } };
  230973. CGContextStrokeLineSegments (context, cgLine, 1);
  230974. }
  230975. else
  230976. {
  230977. Path p;
  230978. p.addLineSegment (line, 1.0f);
  230979. fillPath (p, AffineTransform::identity);
  230980. }
  230981. }
  230982. void drawVerticalLine (const int x, float top, float bottom)
  230983. {
  230984. if (state->fillType.isColour())
  230985. {
  230986. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  230987. CGContextFillRect (context, CGRectMake (x, flipHeight - bottom, 1.0f, bottom - top));
  230988. #else
  230989. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  230990. // the x co-ord slightly to trick it..
  230991. CGContextFillRect (context, CGRectMake (x + 1.0f / 256.0f, flipHeight - bottom, 1.0f + 1.0f / 256.0f, bottom - top));
  230992. #endif
  230993. }
  230994. else
  230995. {
  230996. fillCGRect (CGRectMake ((float) x, flipHeight - bottom, 1.0f, bottom - top), false);
  230997. }
  230998. }
  230999. void drawHorizontalLine (const int y, float left, float right)
  231000. {
  231001. if (state->fillType.isColour())
  231002. {
  231003. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  231004. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + 1.0f), right - left, 1.0f));
  231005. #else
  231006. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  231007. // the x co-ord slightly to trick it..
  231008. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + (1.0f + 1.0f / 256.0f)), right - left, 1.0f + 1.0f / 256.0f));
  231009. #endif
  231010. }
  231011. else
  231012. {
  231013. fillCGRect (CGRectMake (left, flipHeight - (y + 1), right - left, 1.0f), false);
  231014. }
  231015. }
  231016. void setFont (const Font& newFont)
  231017. {
  231018. if (state->font != newFont)
  231019. {
  231020. state->fontRef = 0;
  231021. state->font = newFont;
  231022. MacTypeface* mf = dynamic_cast <MacTypeface*> (state->font.getTypeface());
  231023. if (mf != 0)
  231024. {
  231025. state->fontRef = mf->fontRef;
  231026. CGContextSetFont (context, state->fontRef);
  231027. CGContextSetFontSize (context, state->font.getHeight() * mf->fontHeightToCGSizeFactor);
  231028. state->fontTransform = mf->renderingTransform;
  231029. state->fontTransform.a *= state->font.getHorizontalScale();
  231030. CGContextSetTextMatrix (context, state->fontTransform);
  231031. }
  231032. }
  231033. }
  231034. const Font getFont()
  231035. {
  231036. return state->font;
  231037. }
  231038. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  231039. {
  231040. if (state->fontRef != 0 && state->fillType.isColour())
  231041. {
  231042. if (transform.isOnlyTranslation())
  231043. {
  231044. CGContextSetTextMatrix (context, state->fontTransform); // have to set this each time, as it's not saved as part of the state
  231045. CGGlyph g = glyphNumber;
  231046. CGContextShowGlyphsAtPoint (context, transform.getTranslationX(),
  231047. flipHeight - roundToInt (transform.getTranslationY()), &g, 1);
  231048. }
  231049. else
  231050. {
  231051. CGContextSaveGState (context);
  231052. flip();
  231053. applyTransform (transform);
  231054. CGAffineTransform t = state->fontTransform;
  231055. t.d = -t.d;
  231056. CGContextSetTextMatrix (context, t);
  231057. CGGlyph g = glyphNumber;
  231058. CGContextShowGlyphsAtPoint (context, 0, 0, &g, 1);
  231059. CGContextRestoreGState (context);
  231060. }
  231061. }
  231062. else
  231063. {
  231064. Path p;
  231065. Font& f = state->font;
  231066. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  231067. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight())
  231068. .followedBy (transform));
  231069. }
  231070. }
  231071. private:
  231072. CGContextRef context;
  231073. const CGFloat flipHeight;
  231074. CGColorSpaceRef rgbColourSpace, greyColourSpace;
  231075. CGFunctionCallbacks gradientCallbacks;
  231076. mutable Rectangle<int> lastClipRect;
  231077. mutable bool lastClipRectIsValid;
  231078. struct SavedState
  231079. {
  231080. SavedState()
  231081. : font (1.0f), fontRef (0), fontTransform (CGAffineTransformIdentity)
  231082. {
  231083. }
  231084. SavedState (const SavedState& other)
  231085. : fillType (other.fillType), font (other.font), fontRef (other.fontRef),
  231086. fontTransform (other.fontTransform)
  231087. {
  231088. }
  231089. ~SavedState()
  231090. {
  231091. }
  231092. FillType fillType;
  231093. Font font;
  231094. CGFontRef fontRef;
  231095. CGAffineTransform fontTransform;
  231096. };
  231097. ScopedPointer <SavedState> state;
  231098. OwnedArray <SavedState> stateStack;
  231099. HeapBlock <PixelARGB> gradientLookupTable;
  231100. int numGradientLookupEntries;
  231101. static void gradientCallback (void* info, const CGFloat* inData, CGFloat* outData)
  231102. {
  231103. const CoreGraphicsContext* const g = static_cast <const CoreGraphicsContext*> (info);
  231104. const int index = roundToInt (g->numGradientLookupEntries * inData[0]);
  231105. PixelARGB colour (g->gradientLookupTable [jlimit (0, g->numGradientLookupEntries, index)]);
  231106. colour.unpremultiply();
  231107. outData[0] = colour.getRed() / 255.0f;
  231108. outData[1] = colour.getGreen() / 255.0f;
  231109. outData[2] = colour.getBlue() / 255.0f;
  231110. outData[3] = colour.getAlpha() / 255.0f;
  231111. }
  231112. CGShadingRef createGradient (const AffineTransform& transform, ColourGradient gradient)
  231113. {
  231114. numGradientLookupEntries = gradient.createLookupTable (transform, gradientLookupTable);
  231115. --numGradientLookupEntries;
  231116. CGShadingRef result = 0;
  231117. CGFunctionRef function = CGFunctionCreate (this, 1, 0, 4, 0, &gradientCallbacks);
  231118. CGPoint p1 (CGPointMake (gradient.point1.getX(), gradient.point1.getY()));
  231119. if (gradient.isRadial)
  231120. {
  231121. result = CGShadingCreateRadial (rgbColourSpace, p1, 0,
  231122. p1, gradient.point1.getDistanceFrom (gradient.point2),
  231123. function, true, true);
  231124. }
  231125. else
  231126. {
  231127. result = CGShadingCreateAxial (rgbColourSpace, p1,
  231128. CGPointMake (gradient.point2.getX(), gradient.point2.getY()),
  231129. function, true, true);
  231130. }
  231131. CGFunctionRelease (function);
  231132. return result;
  231133. }
  231134. void drawGradient()
  231135. {
  231136. flip();
  231137. applyTransform (state->fillType.transform);
  231138. CGContextSetInterpolationQuality (context, kCGInterpolationDefault); // (This is required for 10.4, where there's a crash if
  231139. // you draw a gradient with high quality interp enabled).
  231140. CGShadingRef shading = createGradient (state->fillType.transform, *(state->fillType.gradient));
  231141. CGContextSetAlpha (context, state->fillType.getOpacity());
  231142. CGContextDrawShading (context, shading);
  231143. CGShadingRelease (shading);
  231144. }
  231145. void createPath (const Path& path) const
  231146. {
  231147. CGContextBeginPath (context);
  231148. Path::Iterator i (path);
  231149. while (i.next())
  231150. {
  231151. switch (i.elementType)
  231152. {
  231153. case Path::Iterator::startNewSubPath: CGContextMoveToPoint (context, i.x1, i.y1); break;
  231154. case Path::Iterator::lineTo: CGContextAddLineToPoint (context, i.x1, i.y1); break;
  231155. case Path::Iterator::quadraticTo: CGContextAddQuadCurveToPoint (context, i.x1, i.y1, i.x2, i.y2); break;
  231156. case Path::Iterator::cubicTo: CGContextAddCurveToPoint (context, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3); break;
  231157. case Path::Iterator::closePath: CGContextClosePath (context); break;
  231158. default: jassertfalse; break;
  231159. }
  231160. }
  231161. }
  231162. void createPath (const Path& path, const AffineTransform& transform) const
  231163. {
  231164. CGContextBeginPath (context);
  231165. Path::Iterator i (path);
  231166. while (i.next())
  231167. {
  231168. switch (i.elementType)
  231169. {
  231170. case Path::Iterator::startNewSubPath:
  231171. transform.transformPoint (i.x1, i.y1);
  231172. CGContextMoveToPoint (context, i.x1, flipHeight - i.y1);
  231173. break;
  231174. case Path::Iterator::lineTo:
  231175. transform.transformPoint (i.x1, i.y1);
  231176. CGContextAddLineToPoint (context, i.x1, flipHeight - i.y1);
  231177. break;
  231178. case Path::Iterator::quadraticTo:
  231179. transform.transformPoints (i.x1, i.y1, i.x2, i.y2);
  231180. CGContextAddQuadCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2);
  231181. break;
  231182. case Path::Iterator::cubicTo:
  231183. transform.transformPoints (i.x1, i.y1, i.x2, i.y2, i.x3, i.y3);
  231184. CGContextAddCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2, i.x3, flipHeight - i.y3);
  231185. break;
  231186. case Path::Iterator::closePath:
  231187. CGContextClosePath (context); break;
  231188. default:
  231189. jassertfalse;
  231190. break;
  231191. }
  231192. }
  231193. }
  231194. void flip() const
  231195. {
  231196. CGContextConcatCTM (context, CGAffineTransformMake (1, 0, 0, -1, 0, flipHeight));
  231197. }
  231198. void applyTransform (const AffineTransform& transform) const
  231199. {
  231200. CGAffineTransform t;
  231201. t.a = transform.mat00;
  231202. t.b = transform.mat10;
  231203. t.c = transform.mat01;
  231204. t.d = transform.mat11;
  231205. t.tx = transform.mat02;
  231206. t.ty = transform.mat12;
  231207. CGContextConcatCTM (context, t);
  231208. }
  231209. CoreGraphicsContext (const CoreGraphicsContext&);
  231210. CoreGraphicsContext& operator= (const CoreGraphicsContext&);
  231211. };
  231212. LowLevelGraphicsContext* CoreGraphicsImage::createLowLevelContext()
  231213. {
  231214. return new CoreGraphicsContext (context, height);
  231215. }
  231216. #if USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  231217. const Image juce_loadWithCoreImage (InputStream& input)
  231218. {
  231219. MemoryBlock data;
  231220. input.readIntoMemoryBlock (data, -1);
  231221. #if JUCE_IOS
  231222. JUCE_AUTORELEASEPOOL
  231223. UIImage* image = [UIImage imageWithData: [NSData dataWithBytesNoCopy: data.getData()
  231224. length: data.getSize()
  231225. freeWhenDone: NO]];
  231226. if (image != nil)
  231227. {
  231228. CGImageRef loadedImage = image.CGImage;
  231229. #else
  231230. CGDataProviderRef provider = CGDataProviderCreateWithData (0, data.getData(), data.getSize(), 0);
  231231. CGImageSourceRef imageSource = CGImageSourceCreateWithDataProvider (provider, 0);
  231232. CGDataProviderRelease (provider);
  231233. if (imageSource != 0)
  231234. {
  231235. CGImageRef loadedImage = CGImageSourceCreateImageAtIndex (imageSource, 0, 0);
  231236. CFRelease (imageSource);
  231237. #endif
  231238. if (loadedImage != 0)
  231239. {
  231240. CGImageAlphaInfo alphaInfo = CGImageGetAlphaInfo (loadedImage);
  231241. const bool hasAlphaChan = (alphaInfo != kCGImageAlphaNone
  231242. && alphaInfo != kCGImageAlphaNoneSkipLast
  231243. && alphaInfo != kCGImageAlphaNoneSkipFirst);
  231244. Image image (Image::ARGB, // (CoreImage doesn't work with 24-bit images)
  231245. (int) CGImageGetWidth (loadedImage), (int) CGImageGetHeight (loadedImage),
  231246. hasAlphaChan, Image::NativeImage);
  231247. CoreGraphicsImage* const cgImage = dynamic_cast<CoreGraphicsImage*> (image.getSharedImage());
  231248. jassert (cgImage != 0); // if USE_COREGRAPHICS_RENDERING is set, the CoreGraphicsImage class should have been used.
  231249. CGContextDrawImage (cgImage->context, CGRectMake (0, 0, image.getWidth(), image.getHeight()), loadedImage);
  231250. CGContextFlush (cgImage->context);
  231251. #if ! JUCE_IOS
  231252. CFRelease (loadedImage);
  231253. #endif
  231254. // Because it's impossible to create a truly 24-bit CG image, this flag allows a user
  231255. // to find out whether the file they just loaded the image from had an alpha channel or not.
  231256. image.getProperties()->set ("originalImageHadAlpha", hasAlphaChan);
  231257. return image;
  231258. }
  231259. }
  231260. return Image::null;
  231261. }
  231262. #endif
  231263. #endif
  231264. /*** End of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  231265. /*** Start of inlined file: juce_mac_NSViewComponentPeer.mm ***/
  231266. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  231267. // compiled on its own).
  231268. #if JUCE_INCLUDED_FILE
  231269. class NSViewComponentPeer;
  231270. END_JUCE_NAMESPACE
  231271. @interface NSEvent (JuceDeviceDelta)
  231272. - (float) deviceDeltaX;
  231273. - (float) deviceDeltaY;
  231274. @end
  231275. #define JuceNSView MakeObjCClassName(JuceNSView)
  231276. @interface JuceNSView : NSView<NSTextInput>
  231277. {
  231278. @public
  231279. NSViewComponentPeer* owner;
  231280. NSNotificationCenter* notificationCenter;
  231281. String* stringBeingComposed;
  231282. bool textWasInserted;
  231283. }
  231284. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner withFrame: (NSRect) frame;
  231285. - (void) dealloc;
  231286. - (BOOL) isOpaque;
  231287. - (void) drawRect: (NSRect) r;
  231288. - (void) mouseDown: (NSEvent*) ev;
  231289. - (void) asyncMouseDown: (NSEvent*) ev;
  231290. - (void) mouseUp: (NSEvent*) ev;
  231291. - (void) asyncMouseUp: (NSEvent*) ev;
  231292. - (void) mouseDragged: (NSEvent*) ev;
  231293. - (void) mouseMoved: (NSEvent*) ev;
  231294. - (void) mouseEntered: (NSEvent*) ev;
  231295. - (void) mouseExited: (NSEvent*) ev;
  231296. - (void) rightMouseDown: (NSEvent*) ev;
  231297. - (void) rightMouseDragged: (NSEvent*) ev;
  231298. - (void) rightMouseUp: (NSEvent*) ev;
  231299. - (void) otherMouseDown: (NSEvent*) ev;
  231300. - (void) otherMouseDragged: (NSEvent*) ev;
  231301. - (void) otherMouseUp: (NSEvent*) ev;
  231302. - (void) scrollWheel: (NSEvent*) ev;
  231303. - (BOOL) acceptsFirstMouse: (NSEvent*) ev;
  231304. - (void) frameChanged: (NSNotification*) n;
  231305. - (void) viewDidMoveToWindow;
  231306. - (void) keyDown: (NSEvent*) ev;
  231307. - (void) keyUp: (NSEvent*) ev;
  231308. // NSTextInput Methods
  231309. - (void) insertText: (id) aString;
  231310. - (void) doCommandBySelector: (SEL) aSelector;
  231311. - (void) setMarkedText: (id) aString selectedRange: (NSRange) selRange;
  231312. - (void) unmarkText;
  231313. - (BOOL) hasMarkedText;
  231314. - (long) conversationIdentifier;
  231315. - (NSAttributedString*) attributedSubstringFromRange: (NSRange) theRange;
  231316. - (NSRange) markedRange;
  231317. - (NSRange) selectedRange;
  231318. - (NSRect) firstRectForCharacterRange: (NSRange) theRange;
  231319. - (NSUInteger) characterIndexForPoint: (NSPoint) thePoint;
  231320. - (NSArray*) validAttributesForMarkedText;
  231321. - (void) flagsChanged: (NSEvent*) ev;
  231322. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  231323. - (BOOL) performKeyEquivalent: (NSEvent*) ev;
  231324. #endif
  231325. - (BOOL) becomeFirstResponder;
  231326. - (BOOL) resignFirstResponder;
  231327. - (BOOL) acceptsFirstResponder;
  231328. - (void) asyncRepaint: (id) rect;
  231329. - (NSArray*) getSupportedDragTypes;
  231330. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender;
  231331. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender;
  231332. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender;
  231333. - (void) draggingEnded: (id <NSDraggingInfo>) sender;
  231334. - (void) draggingExited: (id <NSDraggingInfo>) sender;
  231335. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender;
  231336. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender;
  231337. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender;
  231338. @end
  231339. #define JuceNSWindow MakeObjCClassName(JuceNSWindow)
  231340. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  231341. @interface JuceNSWindow : NSWindow <NSWindowDelegate>
  231342. #else
  231343. @interface JuceNSWindow : NSWindow
  231344. #endif
  231345. {
  231346. @private
  231347. NSViewComponentPeer* owner;
  231348. bool isZooming;
  231349. }
  231350. - (void) setOwner: (NSViewComponentPeer*) owner;
  231351. - (BOOL) canBecomeKeyWindow;
  231352. - (void) becomeKeyWindow;
  231353. - (BOOL) windowShouldClose: (id) window;
  231354. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen;
  231355. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize;
  231356. - (void) zoom: (id) sender;
  231357. @end
  231358. BEGIN_JUCE_NAMESPACE
  231359. class NSViewComponentPeer : public ComponentPeer
  231360. {
  231361. public:
  231362. NSViewComponentPeer (Component* const component,
  231363. const int windowStyleFlags,
  231364. NSView* viewToAttachTo);
  231365. ~NSViewComponentPeer();
  231366. void* getNativeHandle() const;
  231367. void setVisible (bool shouldBeVisible);
  231368. void setTitle (const String& title);
  231369. void setPosition (int x, int y);
  231370. void setSize (int w, int h);
  231371. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen);
  231372. const Rectangle<int> getBounds (const bool global) const;
  231373. const Rectangle<int> getBounds() const;
  231374. const Point<int> getScreenPosition() const;
  231375. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition);
  231376. const Point<int> globalPositionToRelative (const Point<int>& screenPosition);
  231377. void setAlpha (float newAlpha);
  231378. void setMinimised (bool shouldBeMinimised);
  231379. bool isMinimised() const;
  231380. void setFullScreen (bool shouldBeFullScreen);
  231381. bool isFullScreen() const;
  231382. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const;
  231383. const BorderSize getFrameSize() const;
  231384. bool setAlwaysOnTop (bool alwaysOnTop);
  231385. void toFront (bool makeActiveWindow);
  231386. void toBehind (ComponentPeer* other);
  231387. void setIcon (const Image& newIcon);
  231388. const StringArray getAvailableRenderingEngines();
  231389. int getCurrentRenderingEngine() throw();
  231390. void setCurrentRenderingEngine (int index);
  231391. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  231392. for example having more than one juce plugin loaded into a host, then when a
  231393. method is called, the actual code that runs might actually be in a different module
  231394. than the one you expect... So any calls to library functions or statics that are
  231395. made inside obj-c methods will probably end up getting executed in a different DLL's
  231396. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  231397. To work around this insanity, I'm only allowing obj-c methods to make calls to
  231398. virtual methods of an object that's known to live inside the right module's space.
  231399. */
  231400. virtual void redirectMouseDown (NSEvent* ev);
  231401. virtual void redirectMouseUp (NSEvent* ev);
  231402. virtual void redirectMouseDrag (NSEvent* ev);
  231403. virtual void redirectMouseMove (NSEvent* ev);
  231404. virtual void redirectMouseEnter (NSEvent* ev);
  231405. virtual void redirectMouseExit (NSEvent* ev);
  231406. virtual void redirectMouseWheel (NSEvent* ev);
  231407. void sendMouseEvent (NSEvent* ev);
  231408. bool handleKeyEvent (NSEvent* ev, bool isKeyDown);
  231409. virtual bool redirectKeyDown (NSEvent* ev);
  231410. virtual bool redirectKeyUp (NSEvent* ev);
  231411. virtual void redirectModKeyChange (NSEvent* ev);
  231412. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  231413. virtual bool redirectPerformKeyEquivalent (NSEvent* ev);
  231414. #endif
  231415. virtual BOOL sendDragCallback (int type, id <NSDraggingInfo> sender);
  231416. virtual bool isOpaque();
  231417. virtual void drawRect (NSRect r);
  231418. virtual bool canBecomeKeyWindow();
  231419. virtual bool windowShouldClose();
  231420. virtual void redirectMovedOrResized();
  231421. virtual void viewMovedToWindow();
  231422. virtual NSRect constrainRect (NSRect r);
  231423. static void showArrowCursorIfNeeded();
  231424. static void updateModifiers (NSEvent* e);
  231425. static void updateKeysDown (NSEvent* ev, bool isKeyDown);
  231426. static int getKeyCodeFromEvent (NSEvent* ev)
  231427. {
  231428. const String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  231429. int keyCode = unmodified[0];
  231430. if (keyCode == 0x19) // (backwards-tab)
  231431. keyCode = '\t';
  231432. else if (keyCode == 0x03) // (enter)
  231433. keyCode = '\r';
  231434. else
  231435. keyCode = (int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode);
  231436. if (([ev modifierFlags] & NSNumericPadKeyMask) != 0)
  231437. {
  231438. const int numPadConversions[] = { '0', KeyPress::numberPad0, '1', KeyPress::numberPad1,
  231439. '2', KeyPress::numberPad2, '3', KeyPress::numberPad3,
  231440. '4', KeyPress::numberPad4, '5', KeyPress::numberPad5,
  231441. '6', KeyPress::numberPad6, '7', KeyPress::numberPad7,
  231442. '8', KeyPress::numberPad8, '9', KeyPress::numberPad9,
  231443. '+', KeyPress::numberPadAdd, '-', KeyPress::numberPadSubtract,
  231444. '*', KeyPress::numberPadMultiply, '/', KeyPress::numberPadDivide,
  231445. '.', KeyPress::numberPadDecimalPoint, '=', KeyPress::numberPadEquals };
  231446. for (int i = 0; i < numElementsInArray (numPadConversions); i += 2)
  231447. if (keyCode == numPadConversions [i])
  231448. keyCode = numPadConversions [i + 1];
  231449. }
  231450. return keyCode;
  231451. }
  231452. static int64 getMouseTime (NSEvent* e)
  231453. {
  231454. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  231455. + (int64) ([e timestamp] * 1000.0);
  231456. }
  231457. static const Point<int> getMousePos (NSEvent* e, NSView* view)
  231458. {
  231459. NSPoint p = [view convertPoint: [e locationInWindow] fromView: nil];
  231460. return Point<int> (roundToInt (p.x), roundToInt ([view frame].size.height - p.y));
  231461. }
  231462. static int getModifierForButtonNumber (const NSInteger num)
  231463. {
  231464. return num == 0 ? ModifierKeys::leftButtonModifier
  231465. : (num == 1 ? ModifierKeys::rightButtonModifier
  231466. : (num == 2 ? ModifierKeys::middleButtonModifier : 0));
  231467. }
  231468. virtual void viewFocusGain();
  231469. virtual void viewFocusLoss();
  231470. bool isFocused() const;
  231471. void grabFocus();
  231472. void textInputRequired (const Point<int>& position);
  231473. void repaint (const Rectangle<int>& area);
  231474. void performAnyPendingRepaintsNow();
  231475. juce_UseDebuggingNewOperator
  231476. NSWindow* window;
  231477. JuceNSView* view;
  231478. bool isSharedWindow, fullScreen, insideDrawRect, usingCoreGraphics, recursiveToFrontCall;
  231479. static ModifierKeys currentModifiers;
  231480. static ComponentPeer* currentlyFocusedPeer;
  231481. static Array<int> keysCurrentlyDown;
  231482. };
  231483. END_JUCE_NAMESPACE
  231484. @implementation JuceNSView
  231485. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner_
  231486. withFrame: (NSRect) frame
  231487. {
  231488. [super initWithFrame: frame];
  231489. owner = owner_;
  231490. stringBeingComposed = 0;
  231491. textWasInserted = false;
  231492. notificationCenter = [NSNotificationCenter defaultCenter];
  231493. [notificationCenter addObserver: self
  231494. selector: @selector (frameChanged:)
  231495. name: NSViewFrameDidChangeNotification
  231496. object: self];
  231497. if (! owner_->isSharedWindow)
  231498. {
  231499. [notificationCenter addObserver: self
  231500. selector: @selector (frameChanged:)
  231501. name: NSWindowDidMoveNotification
  231502. object: owner_->window];
  231503. }
  231504. [self registerForDraggedTypes: [self getSupportedDragTypes]];
  231505. return self;
  231506. }
  231507. - (void) dealloc
  231508. {
  231509. [notificationCenter removeObserver: self];
  231510. delete stringBeingComposed;
  231511. [super dealloc];
  231512. }
  231513. - (void) drawRect: (NSRect) r
  231514. {
  231515. if (owner != 0)
  231516. owner->drawRect (r);
  231517. }
  231518. - (BOOL) isOpaque
  231519. {
  231520. return owner == 0 || owner->isOpaque();
  231521. }
  231522. - (void) mouseDown: (NSEvent*) ev
  231523. {
  231524. if (JUCEApplication::isStandaloneApp())
  231525. [self asyncMouseDown: ev];
  231526. else
  231527. // In some host situations, the host will stop modal loops from working
  231528. // correctly if they're called from a mouse event, so we'll trigger
  231529. // the event asynchronously..
  231530. [self performSelectorOnMainThread: @selector (asyncMouseDown:)
  231531. withObject: ev
  231532. waitUntilDone: NO];
  231533. }
  231534. - (void) asyncMouseDown: (NSEvent*) ev
  231535. {
  231536. if (owner != 0)
  231537. owner->redirectMouseDown (ev);
  231538. }
  231539. - (void) mouseUp: (NSEvent*) ev
  231540. {
  231541. if (! JUCEApplication::isStandaloneApp())
  231542. [self asyncMouseUp: ev];
  231543. else
  231544. // In some host situations, the host will stop modal loops from working
  231545. // correctly if they're called from a mouse event, so we'll trigger
  231546. // the event asynchronously..
  231547. [self performSelectorOnMainThread: @selector (asyncMouseUp:)
  231548. withObject: ev
  231549. waitUntilDone: NO];
  231550. }
  231551. - (void) asyncMouseUp: (NSEvent*) ev
  231552. {
  231553. if (owner != 0)
  231554. owner->redirectMouseUp (ev);
  231555. }
  231556. - (void) mouseDragged: (NSEvent*) ev
  231557. {
  231558. if (owner != 0)
  231559. owner->redirectMouseDrag (ev);
  231560. }
  231561. - (void) mouseMoved: (NSEvent*) ev
  231562. {
  231563. if (owner != 0)
  231564. owner->redirectMouseMove (ev);
  231565. }
  231566. - (void) mouseEntered: (NSEvent*) ev
  231567. {
  231568. if (owner != 0)
  231569. owner->redirectMouseEnter (ev);
  231570. }
  231571. - (void) mouseExited: (NSEvent*) ev
  231572. {
  231573. if (owner != 0)
  231574. owner->redirectMouseExit (ev);
  231575. }
  231576. - (void) rightMouseDown: (NSEvent*) ev
  231577. {
  231578. [self mouseDown: ev];
  231579. }
  231580. - (void) rightMouseDragged: (NSEvent*) ev
  231581. {
  231582. [self mouseDragged: ev];
  231583. }
  231584. - (void) rightMouseUp: (NSEvent*) ev
  231585. {
  231586. [self mouseUp: ev];
  231587. }
  231588. - (void) otherMouseDown: (NSEvent*) ev
  231589. {
  231590. [self mouseDown: ev];
  231591. }
  231592. - (void) otherMouseDragged: (NSEvent*) ev
  231593. {
  231594. [self mouseDragged: ev];
  231595. }
  231596. - (void) otherMouseUp: (NSEvent*) ev
  231597. {
  231598. [self mouseUp: ev];
  231599. }
  231600. - (void) scrollWheel: (NSEvent*) ev
  231601. {
  231602. if (owner != 0)
  231603. owner->redirectMouseWheel (ev);
  231604. }
  231605. - (BOOL) acceptsFirstMouse: (NSEvent*) ev
  231606. {
  231607. (void) ev;
  231608. return YES;
  231609. }
  231610. - (void) frameChanged: (NSNotification*) n
  231611. {
  231612. (void) n;
  231613. if (owner != 0)
  231614. owner->redirectMovedOrResized();
  231615. }
  231616. - (void) viewDidMoveToWindow
  231617. {
  231618. if (owner != 0)
  231619. owner->viewMovedToWindow();
  231620. }
  231621. - (void) asyncRepaint: (id) rect
  231622. {
  231623. NSRect* r = (NSRect*) [((NSData*) rect) bytes];
  231624. [self setNeedsDisplayInRect: *r];
  231625. }
  231626. - (void) keyDown: (NSEvent*) ev
  231627. {
  231628. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231629. textWasInserted = false;
  231630. if (target != 0)
  231631. [self interpretKeyEvents: [NSArray arrayWithObject: ev]];
  231632. else
  231633. deleteAndZero (stringBeingComposed);
  231634. if ((! textWasInserted) && (owner == 0 || ! owner->redirectKeyDown (ev)))
  231635. [super keyDown: ev];
  231636. }
  231637. - (void) keyUp: (NSEvent*) ev
  231638. {
  231639. if (owner == 0 || ! owner->redirectKeyUp (ev))
  231640. [super keyUp: ev];
  231641. }
  231642. - (void) insertText: (id) aString
  231643. {
  231644. // This commits multi-byte text when return is pressed, or after every keypress for western keyboards
  231645. NSString* newText = [aString isKindOfClass: [NSAttributedString class]] ? [aString string] : aString;
  231646. if ([newText length] > 0)
  231647. {
  231648. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231649. if (target != 0)
  231650. {
  231651. target->insertTextAtCaret (nsStringToJuce (newText));
  231652. textWasInserted = true;
  231653. }
  231654. }
  231655. deleteAndZero (stringBeingComposed);
  231656. }
  231657. - (void) doCommandBySelector: (SEL) aSelector
  231658. {
  231659. (void) aSelector;
  231660. }
  231661. - (void) setMarkedText: (id) aString selectedRange: (NSRange) selectionRange
  231662. {
  231663. (void) selectionRange;
  231664. if (stringBeingComposed == 0)
  231665. stringBeingComposed = new String();
  231666. *stringBeingComposed = nsStringToJuce ([aString isKindOfClass:[NSAttributedString class]] ? [aString string] : aString);
  231667. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231668. if (target != 0)
  231669. {
  231670. const Range<int> currentHighlight (target->getHighlightedRegion());
  231671. target->insertTextAtCaret (*stringBeingComposed);
  231672. target->setHighlightedRegion (currentHighlight.withLength (stringBeingComposed->length()));
  231673. textWasInserted = true;
  231674. }
  231675. }
  231676. - (void) unmarkText
  231677. {
  231678. if (stringBeingComposed != 0)
  231679. {
  231680. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231681. if (target != 0)
  231682. {
  231683. target->insertTextAtCaret (*stringBeingComposed);
  231684. textWasInserted = true;
  231685. }
  231686. }
  231687. deleteAndZero (stringBeingComposed);
  231688. }
  231689. - (BOOL) hasMarkedText
  231690. {
  231691. return stringBeingComposed != 0;
  231692. }
  231693. - (long) conversationIdentifier
  231694. {
  231695. return (long) (pointer_sized_int) self;
  231696. }
  231697. - (NSAttributedString*) attributedSubstringFromRange: (NSRange) theRange
  231698. {
  231699. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231700. if (target != 0)
  231701. {
  231702. const Range<int> r ((int) theRange.location,
  231703. (int) (theRange.location + theRange.length));
  231704. return [[[NSAttributedString alloc] initWithString: juceStringToNS (target->getTextInRange (r))] autorelease];
  231705. }
  231706. return nil;
  231707. }
  231708. - (NSRange) markedRange
  231709. {
  231710. return stringBeingComposed != 0 ? NSMakeRange (0, stringBeingComposed->length())
  231711. : NSMakeRange (NSNotFound, 0);
  231712. }
  231713. - (NSRange) selectedRange
  231714. {
  231715. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231716. if (target != 0)
  231717. {
  231718. const Range<int> highlight (target->getHighlightedRegion());
  231719. if (! highlight.isEmpty())
  231720. return NSMakeRange (highlight.getStart(), highlight.getLength());
  231721. }
  231722. return NSMakeRange (NSNotFound, 0);
  231723. }
  231724. - (NSRect) firstRectForCharacterRange: (NSRange) theRange
  231725. {
  231726. (void) theRange;
  231727. JUCE_NAMESPACE::Component* const comp = dynamic_cast <JUCE_NAMESPACE::Component*> (owner->findCurrentTextInputTarget());
  231728. if (comp == 0)
  231729. return NSMakeRect (0, 0, 0, 0);
  231730. const Rectangle<int> bounds (comp->getScreenBounds());
  231731. return NSMakeRect (bounds.getX(),
  231732. [[[NSScreen screens] objectAtIndex: 0] frame].size.height - bounds.getY(),
  231733. bounds.getWidth(),
  231734. bounds.getHeight());
  231735. }
  231736. - (NSUInteger) characterIndexForPoint: (NSPoint) thePoint
  231737. {
  231738. (void) thePoint;
  231739. return NSNotFound;
  231740. }
  231741. - (NSArray*) validAttributesForMarkedText
  231742. {
  231743. return [NSArray array];
  231744. }
  231745. - (void) flagsChanged: (NSEvent*) ev
  231746. {
  231747. if (owner != 0)
  231748. owner->redirectModKeyChange (ev);
  231749. }
  231750. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  231751. - (BOOL) performKeyEquivalent: (NSEvent*) ev
  231752. {
  231753. if (owner != 0 && owner->redirectPerformKeyEquivalent (ev))
  231754. return true;
  231755. return [super performKeyEquivalent: ev];
  231756. }
  231757. #endif
  231758. - (BOOL) becomeFirstResponder
  231759. {
  231760. if (owner != 0)
  231761. owner->viewFocusGain();
  231762. return true;
  231763. }
  231764. - (BOOL) resignFirstResponder
  231765. {
  231766. if (owner != 0)
  231767. owner->viewFocusLoss();
  231768. return true;
  231769. }
  231770. - (BOOL) acceptsFirstResponder
  231771. {
  231772. return owner != 0 && owner->canBecomeKeyWindow();
  231773. }
  231774. - (NSArray*) getSupportedDragTypes
  231775. {
  231776. return [NSArray arrayWithObjects: NSFilenamesPboardType, /*NSFilesPromisePboardType, NSStringPboardType,*/ nil];
  231777. }
  231778. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender
  231779. {
  231780. return owner != 0 && owner->sendDragCallback (type, sender);
  231781. }
  231782. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender
  231783. {
  231784. if ([self sendDragCallback: 0 sender: sender])
  231785. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  231786. else
  231787. return NSDragOperationNone;
  231788. }
  231789. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender
  231790. {
  231791. if ([self sendDragCallback: 0 sender: sender])
  231792. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  231793. else
  231794. return NSDragOperationNone;
  231795. }
  231796. - (void) draggingEnded: (id <NSDraggingInfo>) sender
  231797. {
  231798. [self sendDragCallback: 1 sender: sender];
  231799. }
  231800. - (void) draggingExited: (id <NSDraggingInfo>) sender
  231801. {
  231802. [self sendDragCallback: 1 sender: sender];
  231803. }
  231804. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender
  231805. {
  231806. (void) sender;
  231807. return YES;
  231808. }
  231809. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender
  231810. {
  231811. return [self sendDragCallback: 2 sender: sender];
  231812. }
  231813. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender
  231814. {
  231815. (void) sender;
  231816. }
  231817. @end
  231818. @implementation JuceNSWindow
  231819. - (void) setOwner: (NSViewComponentPeer*) owner_
  231820. {
  231821. owner = owner_;
  231822. isZooming = false;
  231823. }
  231824. - (BOOL) canBecomeKeyWindow
  231825. {
  231826. return owner != 0 && owner->canBecomeKeyWindow();
  231827. }
  231828. - (void) becomeKeyWindow
  231829. {
  231830. [super becomeKeyWindow];
  231831. if (owner != 0)
  231832. owner->grabFocus();
  231833. }
  231834. - (BOOL) windowShouldClose: (id) window
  231835. {
  231836. (void) window;
  231837. return owner == 0 || owner->windowShouldClose();
  231838. }
  231839. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen
  231840. {
  231841. (void) screen;
  231842. if (owner != 0)
  231843. frameRect = owner->constrainRect (frameRect);
  231844. return frameRect;
  231845. }
  231846. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize
  231847. {
  231848. (void) window;
  231849. if (isZooming)
  231850. return proposedFrameSize;
  231851. NSRect frameRect = [self frame];
  231852. frameRect.origin.y -= proposedFrameSize.height - frameRect.size.height;
  231853. frameRect.size = proposedFrameSize;
  231854. if (owner != 0)
  231855. frameRect = owner->constrainRect (frameRect);
  231856. if (JUCE_NAMESPACE::Component::getCurrentlyModalComponent() != 0
  231857. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  231858. && (owner->getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowHasTitleBar) != 0)
  231859. JUCE_NAMESPACE::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  231860. return frameRect.size;
  231861. }
  231862. - (void) zoom: (id) sender
  231863. {
  231864. isZooming = true;
  231865. [super zoom: sender];
  231866. isZooming = false;
  231867. }
  231868. - (void) windowWillMove: (NSNotification*) notification
  231869. {
  231870. (void) notification;
  231871. if (JUCE_NAMESPACE::Component::getCurrentlyModalComponent() != 0
  231872. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  231873. && (owner->getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowHasTitleBar) != 0)
  231874. JUCE_NAMESPACE::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  231875. }
  231876. @end
  231877. BEGIN_JUCE_NAMESPACE
  231878. ModifierKeys NSViewComponentPeer::currentModifiers;
  231879. ComponentPeer* NSViewComponentPeer::currentlyFocusedPeer = 0;
  231880. Array<int> NSViewComponentPeer::keysCurrentlyDown;
  231881. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  231882. {
  231883. if (NSViewComponentPeer::keysCurrentlyDown.contains (keyCode))
  231884. return true;
  231885. if (keyCode >= 'A' && keyCode <= 'Z'
  231886. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toLowerCase ((juce_wchar) keyCode)))
  231887. return true;
  231888. if (keyCode >= 'a' && keyCode <= 'z'
  231889. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode)))
  231890. return true;
  231891. return false;
  231892. }
  231893. void NSViewComponentPeer::updateModifiers (NSEvent* e)
  231894. {
  231895. int m = 0;
  231896. if (([e modifierFlags] & NSShiftKeyMask) != 0) m |= ModifierKeys::shiftModifier;
  231897. if (([e modifierFlags] & NSControlKeyMask) != 0) m |= ModifierKeys::ctrlModifier;
  231898. if (([e modifierFlags] & NSAlternateKeyMask) != 0) m |= ModifierKeys::altModifier;
  231899. if (([e modifierFlags] & NSCommandKeyMask) != 0) m |= ModifierKeys::commandModifier;
  231900. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (m);
  231901. }
  231902. void NSViewComponentPeer::updateKeysDown (NSEvent* ev, bool isKeyDown)
  231903. {
  231904. updateModifiers (ev);
  231905. int keyCode = getKeyCodeFromEvent (ev);
  231906. if (keyCode != 0)
  231907. {
  231908. if (isKeyDown)
  231909. keysCurrentlyDown.addIfNotAlreadyThere (keyCode);
  231910. else
  231911. keysCurrentlyDown.removeValue (keyCode);
  231912. }
  231913. }
  231914. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  231915. {
  231916. return NSViewComponentPeer::currentModifiers;
  231917. }
  231918. void ModifierKeys::updateCurrentModifiers() throw()
  231919. {
  231920. currentModifiers = NSViewComponentPeer::currentModifiers;
  231921. }
  231922. NSViewComponentPeer::NSViewComponentPeer (Component* const component_,
  231923. const int windowStyleFlags,
  231924. NSView* viewToAttachTo)
  231925. : ComponentPeer (component_, windowStyleFlags),
  231926. window (0),
  231927. view (0),
  231928. isSharedWindow (viewToAttachTo != 0),
  231929. fullScreen (false),
  231930. insideDrawRect (false),
  231931. #if USE_COREGRAPHICS_RENDERING
  231932. usingCoreGraphics (true),
  231933. #else
  231934. usingCoreGraphics (false),
  231935. #endif
  231936. recursiveToFrontCall (false)
  231937. {
  231938. NSRect r = NSMakeRect (0, 0, (float) component->getWidth(),(float) component->getHeight());
  231939. view = [[JuceNSView alloc] initWithOwner: this withFrame: r];
  231940. [view setPostsFrameChangedNotifications: YES];
  231941. if (isSharedWindow)
  231942. {
  231943. window = [viewToAttachTo window];
  231944. [viewToAttachTo addSubview: view];
  231945. }
  231946. else
  231947. {
  231948. r.origin.x = (float) component->getX();
  231949. r.origin.y = (float) component->getY();
  231950. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  231951. unsigned int style = 0;
  231952. if ((windowStyleFlags & windowHasTitleBar) == 0)
  231953. style = NSBorderlessWindowMask;
  231954. else
  231955. style = NSTitledWindowMask;
  231956. if ((windowStyleFlags & windowHasMinimiseButton) != 0)
  231957. style |= NSMiniaturizableWindowMask;
  231958. if ((windowStyleFlags & windowHasCloseButton) != 0)
  231959. style |= NSClosableWindowMask;
  231960. if ((windowStyleFlags & windowIsResizable) != 0)
  231961. style |= NSResizableWindowMask;
  231962. window = [[JuceNSWindow alloc] initWithContentRect: r
  231963. styleMask: style
  231964. backing: NSBackingStoreBuffered
  231965. defer: YES];
  231966. [((JuceNSWindow*) window) setOwner: this];
  231967. [window orderOut: nil];
  231968. [window setDelegate: (JuceNSWindow*) window];
  231969. [window setOpaque: component->isOpaque()];
  231970. [window setHasShadow: ((windowStyleFlags & windowHasDropShadow) != 0)];
  231971. if (component->isAlwaysOnTop())
  231972. [window setLevel: NSFloatingWindowLevel];
  231973. [window setContentView: view];
  231974. [window setAutodisplay: YES];
  231975. [window setAcceptsMouseMovedEvents: YES];
  231976. // We'll both retain and also release this on closing because plugin hosts can unexpectedly
  231977. // close the window for us, and also tend to get cause trouble if setReleasedWhenClosed is NO.
  231978. [window setReleasedWhenClosed: YES];
  231979. [window retain];
  231980. [window setExcludedFromWindowsMenu: (windowStyleFlags & windowIsTemporary) != 0];
  231981. [window setIgnoresMouseEvents: (windowStyleFlags & windowIgnoresMouseClicks) != 0];
  231982. }
  231983. const float alpha = component->getAlpha();
  231984. if (alpha < 1.0f)
  231985. setAlpha (alpha);
  231986. setTitle (component->getName());
  231987. }
  231988. NSViewComponentPeer::~NSViewComponentPeer()
  231989. {
  231990. view->owner = 0;
  231991. [view removeFromSuperview];
  231992. [view release];
  231993. if (! isSharedWindow)
  231994. {
  231995. [((JuceNSWindow*) window) setOwner: 0];
  231996. [window close];
  231997. [window release];
  231998. }
  231999. }
  232000. void* NSViewComponentPeer::getNativeHandle() const
  232001. {
  232002. return view;
  232003. }
  232004. void NSViewComponentPeer::setVisible (bool shouldBeVisible)
  232005. {
  232006. if (isSharedWindow)
  232007. {
  232008. [view setHidden: ! shouldBeVisible];
  232009. }
  232010. else
  232011. {
  232012. if (shouldBeVisible)
  232013. {
  232014. [window orderFront: nil];
  232015. handleBroughtToFront();
  232016. }
  232017. else
  232018. {
  232019. [window orderOut: nil];
  232020. }
  232021. }
  232022. }
  232023. void NSViewComponentPeer::setTitle (const String& title)
  232024. {
  232025. const ScopedAutoReleasePool pool;
  232026. if (! isSharedWindow)
  232027. [window setTitle: juceStringToNS (title)];
  232028. }
  232029. void NSViewComponentPeer::setPosition (int x, int y)
  232030. {
  232031. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  232032. }
  232033. void NSViewComponentPeer::setSize (int w, int h)
  232034. {
  232035. setBounds (component->getX(), component->getY(), w, h, false);
  232036. }
  232037. void NSViewComponentPeer::setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  232038. {
  232039. fullScreen = isNowFullScreen;
  232040. NSRect r = NSMakeRect ((float) x, (float) y, (float) jmax (0, w), (float) jmax (0, h));
  232041. if (isSharedWindow)
  232042. {
  232043. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  232044. if ([view frame].size.width != r.size.width
  232045. || [view frame].size.height != r.size.height)
  232046. [view setNeedsDisplay: true];
  232047. [view setFrame: r];
  232048. }
  232049. else
  232050. {
  232051. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  232052. [window setFrame: [window frameRectForContentRect: r]
  232053. display: true];
  232054. }
  232055. }
  232056. const Rectangle<int> NSViewComponentPeer::getBounds (const bool global) const
  232057. {
  232058. NSRect r = [view frame];
  232059. if (global && [view window] != 0)
  232060. {
  232061. r = [view convertRect: r toView: nil];
  232062. NSRect wr = [[view window] frame];
  232063. r.origin.x += wr.origin.x;
  232064. r.origin.y += wr.origin.y;
  232065. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  232066. }
  232067. else
  232068. {
  232069. r.origin.y = [[view superview] frame].size.height - r.origin.y - r.size.height;
  232070. }
  232071. return Rectangle<int> (convertToRectInt (r));
  232072. }
  232073. const Rectangle<int> NSViewComponentPeer::getBounds() const
  232074. {
  232075. return getBounds (! isSharedWindow);
  232076. }
  232077. const Point<int> NSViewComponentPeer::getScreenPosition() const
  232078. {
  232079. return getBounds (true).getPosition();
  232080. }
  232081. const Point<int> NSViewComponentPeer::relativePositionToGlobal (const Point<int>& relativePosition)
  232082. {
  232083. return relativePosition + getScreenPosition();
  232084. }
  232085. const Point<int> NSViewComponentPeer::globalPositionToRelative (const Point<int>& screenPosition)
  232086. {
  232087. return screenPosition - getScreenPosition();
  232088. }
  232089. NSRect NSViewComponentPeer::constrainRect (NSRect r)
  232090. {
  232091. if (constrainer != 0)
  232092. {
  232093. NSRect current = [window frame];
  232094. current.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - current.origin.y - current.size.height;
  232095. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  232096. Rectangle<int> pos (convertToRectInt (r));
  232097. Rectangle<int> original (convertToRectInt (current));
  232098. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_ALLOWED >= MAC_OS_X_VERSION_10_6
  232099. if ([window inLiveResize])
  232100. #else
  232101. if ([window respondsToSelector: @selector (inLiveResize)]
  232102. && [window performSelector: @selector (inLiveResize)])
  232103. #endif
  232104. {
  232105. constrainer->checkBounds (pos, original,
  232106. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  232107. false, false, true, true);
  232108. }
  232109. else
  232110. {
  232111. constrainer->checkBounds (pos, original,
  232112. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  232113. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  232114. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  232115. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  232116. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  232117. }
  232118. r.origin.x = pos.getX();
  232119. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.size.height - pos.getY();
  232120. r.size.width = pos.getWidth();
  232121. r.size.height = pos.getHeight();
  232122. }
  232123. return r;
  232124. }
  232125. void NSViewComponentPeer::setAlpha (float newAlpha)
  232126. {
  232127. if (! isSharedWindow)
  232128. [window setAlphaValue: (CGFloat) newAlpha];
  232129. else
  232130. [view setAlphaValue: (CGFloat) newAlpha];
  232131. }
  232132. void NSViewComponentPeer::setMinimised (bool shouldBeMinimised)
  232133. {
  232134. if (! isSharedWindow)
  232135. {
  232136. if (shouldBeMinimised)
  232137. [window miniaturize: nil];
  232138. else
  232139. [window deminiaturize: nil];
  232140. }
  232141. }
  232142. bool NSViewComponentPeer::isMinimised() const
  232143. {
  232144. return window != 0 && [window isMiniaturized];
  232145. }
  232146. void NSViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  232147. {
  232148. if (! isSharedWindow)
  232149. {
  232150. Rectangle<int> r (lastNonFullscreenBounds);
  232151. setMinimised (false);
  232152. if (fullScreen != shouldBeFullScreen)
  232153. {
  232154. if (shouldBeFullScreen && (getStyleFlags() & windowHasTitleBar) != 0)
  232155. {
  232156. fullScreen = true;
  232157. [window performZoom: nil];
  232158. }
  232159. else
  232160. {
  232161. if (shouldBeFullScreen)
  232162. r = Desktop::getInstance().getMainMonitorArea();
  232163. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  232164. if (r != getComponent()->getBounds() && ! r.isEmpty())
  232165. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  232166. }
  232167. }
  232168. }
  232169. }
  232170. bool NSViewComponentPeer::isFullScreen() const
  232171. {
  232172. return fullScreen;
  232173. }
  232174. bool NSViewComponentPeer::contains (const Point<int>& position, bool trueIfInAChildWindow) const
  232175. {
  232176. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  232177. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  232178. return false;
  232179. NSPoint p;
  232180. p.x = (float) position.getX();
  232181. p.y = (float) position.getY();
  232182. NSView* v = [view hitTest: p];
  232183. if (trueIfInAChildWindow)
  232184. return v != nil;
  232185. return v == view;
  232186. }
  232187. const BorderSize NSViewComponentPeer::getFrameSize() const
  232188. {
  232189. BorderSize b;
  232190. if (! isSharedWindow)
  232191. {
  232192. NSRect v = [view convertRect: [view frame] toView: nil];
  232193. NSRect w = [window frame];
  232194. b.setTop ((int) (w.size.height - (v.origin.y + v.size.height)));
  232195. b.setBottom ((int) v.origin.y);
  232196. b.setLeft ((int) v.origin.x);
  232197. b.setRight ((int) (w.size.width - (v.origin.x + v.size.width)));
  232198. }
  232199. return b;
  232200. }
  232201. bool NSViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  232202. {
  232203. if (! isSharedWindow)
  232204. {
  232205. [window setLevel: alwaysOnTop ? NSFloatingWindowLevel
  232206. : NSNormalWindowLevel];
  232207. }
  232208. return true;
  232209. }
  232210. void NSViewComponentPeer::toFront (bool makeActiveWindow)
  232211. {
  232212. if (isSharedWindow)
  232213. {
  232214. [[view superview] addSubview: view
  232215. positioned: NSWindowAbove
  232216. relativeTo: nil];
  232217. }
  232218. if (window != 0 && component->isVisible())
  232219. {
  232220. if (makeActiveWindow)
  232221. [window makeKeyAndOrderFront: nil];
  232222. else
  232223. [window orderFront: nil];
  232224. if (! recursiveToFrontCall)
  232225. {
  232226. recursiveToFrontCall = true;
  232227. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  232228. handleBroughtToFront();
  232229. recursiveToFrontCall = false;
  232230. }
  232231. }
  232232. }
  232233. void NSViewComponentPeer::toBehind (ComponentPeer* other)
  232234. {
  232235. NSViewComponentPeer* const otherPeer = dynamic_cast <NSViewComponentPeer*> (other);
  232236. jassert (otherPeer != 0); // wrong type of window?
  232237. if (otherPeer != 0)
  232238. {
  232239. if (isSharedWindow)
  232240. {
  232241. [[view superview] addSubview: view
  232242. positioned: NSWindowBelow
  232243. relativeTo: otherPeer->view];
  232244. }
  232245. else
  232246. {
  232247. [window orderWindow: NSWindowBelow
  232248. relativeTo: otherPeer->window != 0 ? [otherPeer->window windowNumber]
  232249. : nil ];
  232250. }
  232251. }
  232252. }
  232253. void NSViewComponentPeer::setIcon (const Image& /*newIcon*/)
  232254. {
  232255. // to do..
  232256. }
  232257. void NSViewComponentPeer::viewFocusGain()
  232258. {
  232259. if (currentlyFocusedPeer != this)
  232260. {
  232261. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  232262. currentlyFocusedPeer->handleFocusLoss();
  232263. currentlyFocusedPeer = this;
  232264. handleFocusGain();
  232265. }
  232266. }
  232267. void NSViewComponentPeer::viewFocusLoss()
  232268. {
  232269. if (currentlyFocusedPeer == this)
  232270. {
  232271. currentlyFocusedPeer = 0;
  232272. handleFocusLoss();
  232273. }
  232274. }
  232275. void juce_HandleProcessFocusChange()
  232276. {
  232277. NSViewComponentPeer::keysCurrentlyDown.clear();
  232278. if (NSViewComponentPeer::isValidPeer (NSViewComponentPeer::currentlyFocusedPeer))
  232279. {
  232280. if (Process::isForegroundProcess())
  232281. {
  232282. NSViewComponentPeer::currentlyFocusedPeer->handleFocusGain();
  232283. ComponentPeer::bringModalComponentToFront();
  232284. }
  232285. else
  232286. {
  232287. NSViewComponentPeer::currentlyFocusedPeer->handleFocusLoss();
  232288. // turn kiosk mode off if we lose focus..
  232289. Desktop::getInstance().setKioskModeComponent (0);
  232290. }
  232291. }
  232292. }
  232293. bool NSViewComponentPeer::isFocused() const
  232294. {
  232295. return isSharedWindow ? this == currentlyFocusedPeer
  232296. : (window != 0 && [window isKeyWindow]);
  232297. }
  232298. void NSViewComponentPeer::grabFocus()
  232299. {
  232300. if (window != 0)
  232301. {
  232302. [window makeKeyWindow];
  232303. [window makeFirstResponder: view];
  232304. viewFocusGain();
  232305. }
  232306. }
  232307. void NSViewComponentPeer::textInputRequired (const Point<int>&)
  232308. {
  232309. }
  232310. bool NSViewComponentPeer::handleKeyEvent (NSEvent* ev, bool isKeyDown)
  232311. {
  232312. String unicode (nsStringToJuce ([ev characters]));
  232313. String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  232314. int keyCode = getKeyCodeFromEvent (ev);
  232315. //DBG ("unicode: " + unicode + " " + String::toHexString ((int) unicode[0]));
  232316. //DBG ("unmodified: " + unmodified + " " + String::toHexString ((int) unmodified[0]));
  232317. if (unicode.isNotEmpty() || keyCode != 0)
  232318. {
  232319. if (isKeyDown)
  232320. {
  232321. bool used = false;
  232322. while (unicode.length() > 0)
  232323. {
  232324. juce_wchar textCharacter = unicode[0];
  232325. unicode = unicode.substring (1);
  232326. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  232327. textCharacter = 0;
  232328. used = handleKeyUpOrDown (true) || used;
  232329. used = handleKeyPress (keyCode, textCharacter) || used;
  232330. }
  232331. return used;
  232332. }
  232333. else
  232334. {
  232335. if (handleKeyUpOrDown (false))
  232336. return true;
  232337. }
  232338. }
  232339. return false;
  232340. }
  232341. bool NSViewComponentPeer::redirectKeyDown (NSEvent* ev)
  232342. {
  232343. updateKeysDown (ev, true);
  232344. bool used = handleKeyEvent (ev, true);
  232345. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  232346. {
  232347. // for command keys, the key-up event is thrown away, so simulate one..
  232348. updateKeysDown (ev, false);
  232349. used = (isValidPeer (this) && handleKeyEvent (ev, false)) || used;
  232350. }
  232351. // (If we're running modally, don't allow unused keystrokes to be passed
  232352. // along to other blocked views..)
  232353. if (Component::getCurrentlyModalComponent() != 0)
  232354. used = true;
  232355. return used;
  232356. }
  232357. bool NSViewComponentPeer::redirectKeyUp (NSEvent* ev)
  232358. {
  232359. updateKeysDown (ev, false);
  232360. return handleKeyEvent (ev, false)
  232361. || Component::getCurrentlyModalComponent() != 0;
  232362. }
  232363. void NSViewComponentPeer::redirectModKeyChange (NSEvent* ev)
  232364. {
  232365. keysCurrentlyDown.clear();
  232366. handleKeyUpOrDown (true);
  232367. updateModifiers (ev);
  232368. handleModifierKeysChange();
  232369. }
  232370. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  232371. bool NSViewComponentPeer::redirectPerformKeyEquivalent (NSEvent* ev)
  232372. {
  232373. if ([ev type] == NSKeyDown)
  232374. return redirectKeyDown (ev);
  232375. else if ([ev type] == NSKeyUp)
  232376. return redirectKeyUp (ev);
  232377. return false;
  232378. }
  232379. #endif
  232380. void NSViewComponentPeer::sendMouseEvent (NSEvent* ev)
  232381. {
  232382. updateModifiers (ev);
  232383. handleMouseEvent (0, getMousePos (ev, view), currentModifiers, getMouseTime (ev));
  232384. }
  232385. void NSViewComponentPeer::redirectMouseDown (NSEvent* ev)
  232386. {
  232387. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  232388. sendMouseEvent (ev);
  232389. }
  232390. void NSViewComponentPeer::redirectMouseUp (NSEvent* ev)
  232391. {
  232392. currentModifiers = currentModifiers.withoutFlags (getModifierForButtonNumber ([ev buttonNumber]));
  232393. sendMouseEvent (ev);
  232394. showArrowCursorIfNeeded();
  232395. }
  232396. void NSViewComponentPeer::redirectMouseDrag (NSEvent* ev)
  232397. {
  232398. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  232399. sendMouseEvent (ev);
  232400. }
  232401. void NSViewComponentPeer::redirectMouseMove (NSEvent* ev)
  232402. {
  232403. currentModifiers = currentModifiers.withoutMouseButtons();
  232404. sendMouseEvent (ev);
  232405. showArrowCursorIfNeeded();
  232406. }
  232407. void NSViewComponentPeer::redirectMouseEnter (NSEvent* ev)
  232408. {
  232409. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  232410. currentModifiers = currentModifiers.withoutMouseButtons();
  232411. sendMouseEvent (ev);
  232412. }
  232413. void NSViewComponentPeer::redirectMouseExit (NSEvent* ev)
  232414. {
  232415. currentModifiers = currentModifiers.withoutMouseButtons();
  232416. sendMouseEvent (ev);
  232417. }
  232418. void NSViewComponentPeer::redirectMouseWheel (NSEvent* ev)
  232419. {
  232420. updateModifiers (ev);
  232421. float x = 0, y = 0;
  232422. @try
  232423. {
  232424. x = [ev deviceDeltaX] * 0.5f;
  232425. y = [ev deviceDeltaY] * 0.5f;
  232426. }
  232427. @catch (...)
  232428. {}
  232429. if (x == 0 && y == 0)
  232430. {
  232431. x = [ev deltaX] * 10.0f;
  232432. y = [ev deltaY] * 10.0f;
  232433. }
  232434. handleMouseWheel (0, getMousePos (ev, view), getMouseTime (ev), x, y);
  232435. }
  232436. void NSViewComponentPeer::showArrowCursorIfNeeded()
  232437. {
  232438. MouseInputSource& mouse = Desktop::getInstance().getMainMouseSource();
  232439. if (mouse.getComponentUnderMouse() == 0
  232440. && Desktop::getInstance().findComponentAt (mouse.getScreenPosition()) == 0)
  232441. {
  232442. [[NSCursor arrowCursor] set];
  232443. }
  232444. }
  232445. BOOL NSViewComponentPeer::sendDragCallback (int type, id <NSDraggingInfo> sender)
  232446. {
  232447. NSString* bestType
  232448. = [[sender draggingPasteboard] availableTypeFromArray: [view getSupportedDragTypes]];
  232449. if (bestType == nil)
  232450. return false;
  232451. NSPoint p = [view convertPoint: [sender draggingLocation] fromView: nil];
  232452. const Point<int> pos ((int) p.x, (int) ([view frame].size.height - p.y));
  232453. StringArray files;
  232454. id list = [[sender draggingPasteboard] propertyListForType: bestType];
  232455. if (list == nil)
  232456. return false;
  232457. if ([list isKindOfClass: [NSArray class]])
  232458. {
  232459. NSArray* items = (NSArray*) list;
  232460. for (unsigned int i = 0; i < [items count]; ++i)
  232461. files.add (nsStringToJuce ((NSString*) [items objectAtIndex: i]));
  232462. }
  232463. if (files.size() == 0)
  232464. return false;
  232465. if (type == 0)
  232466. handleFileDragMove (files, pos);
  232467. else if (type == 1)
  232468. handleFileDragExit (files);
  232469. else if (type == 2)
  232470. handleFileDragDrop (files, pos);
  232471. return true;
  232472. }
  232473. bool NSViewComponentPeer::isOpaque()
  232474. {
  232475. return component == 0 || component->isOpaque();
  232476. }
  232477. void NSViewComponentPeer::drawRect (NSRect r)
  232478. {
  232479. if (r.size.width < 1.0f || r.size.height < 1.0f)
  232480. return;
  232481. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  232482. if (! component->isOpaque())
  232483. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  232484. #if USE_COREGRAPHICS_RENDERING
  232485. if (usingCoreGraphics)
  232486. {
  232487. CoreGraphicsContext context (cg, (float) [view frame].size.height);
  232488. insideDrawRect = true;
  232489. handlePaint (context);
  232490. insideDrawRect = false;
  232491. }
  232492. else
  232493. #endif
  232494. {
  232495. Image temp (getComponent()->isOpaque() ? Image::RGB : Image::ARGB,
  232496. (int) (r.size.width + 0.5f),
  232497. (int) (r.size.height + 0.5f),
  232498. ! getComponent()->isOpaque());
  232499. const int xOffset = -roundToInt (r.origin.x);
  232500. const int yOffset = -roundToInt ([view frame].size.height - (r.origin.y + r.size.height));
  232501. const NSRect* rects = 0;
  232502. NSInteger numRects = 0;
  232503. [view getRectsBeingDrawn: &rects count: &numRects];
  232504. const Rectangle<int> clipBounds (temp.getBounds());
  232505. RectangleList clip;
  232506. for (int i = 0; i < numRects; ++i)
  232507. {
  232508. clip.addWithoutMerging (clipBounds.getIntersection (Rectangle<int> (roundToInt (rects[i].origin.x) + xOffset,
  232509. roundToInt ([view frame].size.height - (rects[i].origin.y + rects[i].size.height)) + yOffset,
  232510. roundToInt (rects[i].size.width),
  232511. roundToInt (rects[i].size.height))));
  232512. }
  232513. if (! clip.isEmpty())
  232514. {
  232515. LowLevelGraphicsSoftwareRenderer context (temp, xOffset, yOffset, clip);
  232516. insideDrawRect = true;
  232517. handlePaint (context);
  232518. insideDrawRect = false;
  232519. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  232520. CGImageRef image = CoreGraphicsImage::createImage (temp, false, colourSpace);
  232521. CGColorSpaceRelease (colourSpace);
  232522. CGContextDrawImage (cg, CGRectMake (r.origin.x, r.origin.y, temp.getWidth(), temp.getHeight()), image);
  232523. CGImageRelease (image);
  232524. }
  232525. }
  232526. }
  232527. const StringArray NSViewComponentPeer::getAvailableRenderingEngines()
  232528. {
  232529. StringArray s (ComponentPeer::getAvailableRenderingEngines());
  232530. #if USE_COREGRAPHICS_RENDERING
  232531. s.add ("CoreGraphics Renderer");
  232532. #endif
  232533. return s;
  232534. }
  232535. int NSViewComponentPeer::getCurrentRenderingEngine() throw()
  232536. {
  232537. return usingCoreGraphics ? 1 : 0;
  232538. }
  232539. void NSViewComponentPeer::setCurrentRenderingEngine (int index)
  232540. {
  232541. #if USE_COREGRAPHICS_RENDERING
  232542. if (usingCoreGraphics != (index > 0))
  232543. {
  232544. usingCoreGraphics = index > 0;
  232545. [view setNeedsDisplay: true];
  232546. }
  232547. #endif
  232548. }
  232549. bool NSViewComponentPeer::canBecomeKeyWindow()
  232550. {
  232551. return (getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowIgnoresKeyPresses) == 0;
  232552. }
  232553. bool NSViewComponentPeer::windowShouldClose()
  232554. {
  232555. if (! isValidPeer (this))
  232556. return YES;
  232557. handleUserClosingWindow();
  232558. return NO;
  232559. }
  232560. void NSViewComponentPeer::redirectMovedOrResized()
  232561. {
  232562. handleMovedOrResized();
  232563. }
  232564. void NSViewComponentPeer::viewMovedToWindow()
  232565. {
  232566. if (isSharedWindow)
  232567. window = [view window];
  232568. }
  232569. void Desktop::createMouseInputSources()
  232570. {
  232571. mouseSources.add (new MouseInputSource (0, true));
  232572. }
  232573. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  232574. {
  232575. // Very annoyingly, this function has to use the old SetSystemUIMode function,
  232576. // which is in Carbon.framework. But, because there's no Cocoa equivalent, it
  232577. // is apparently still available in 64-bit apps..
  232578. if (enableOrDisable)
  232579. {
  232580. SetSystemUIMode (kUIModeAllSuppressed, allowMenusAndBars ? kUIOptionAutoShowMenuBar : 0);
  232581. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  232582. }
  232583. else
  232584. {
  232585. SetSystemUIMode (kUIModeNormal, 0);
  232586. }
  232587. }
  232588. class AsyncRepaintMessage : public CallbackMessage
  232589. {
  232590. public:
  232591. NSViewComponentPeer* const peer;
  232592. const Rectangle<int> rect;
  232593. AsyncRepaintMessage (NSViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  232594. : peer (peer_), rect (rect_)
  232595. {
  232596. }
  232597. void messageCallback()
  232598. {
  232599. if (ComponentPeer::isValidPeer (peer))
  232600. peer->repaint (rect);
  232601. }
  232602. };
  232603. void NSViewComponentPeer::repaint (const Rectangle<int>& area)
  232604. {
  232605. if (insideDrawRect)
  232606. {
  232607. (new AsyncRepaintMessage (this, area))->post();
  232608. }
  232609. else
  232610. {
  232611. [view setNeedsDisplayInRect: NSMakeRect ((float) area.getX(), [view frame].size.height - (float) area.getBottom(),
  232612. (float) area.getWidth(), (float) area.getHeight())];
  232613. }
  232614. }
  232615. void NSViewComponentPeer::performAnyPendingRepaintsNow()
  232616. {
  232617. [view displayIfNeeded];
  232618. }
  232619. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  232620. {
  232621. return new NSViewComponentPeer (this, styleFlags, (NSView*) windowToAttachTo);
  232622. }
  232623. const Image juce_createIconForFile (const File& file)
  232624. {
  232625. const ScopedAutoReleasePool pool;
  232626. NSImage* image = [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (file.getFullPathName())];
  232627. CoreGraphicsImage* result = new CoreGraphicsImage (Image::ARGB, (int) [image size].width, (int) [image size].height, true);
  232628. [NSGraphicsContext saveGraphicsState];
  232629. [NSGraphicsContext setCurrentContext: [NSGraphicsContext graphicsContextWithGraphicsPort: result->context flipped: false]];
  232630. [image drawAtPoint: NSMakePoint (0, 0)
  232631. fromRect: NSMakeRect (0, 0, [image size].width, [image size].height)
  232632. operation: NSCompositeSourceOver fraction: 1.0f];
  232633. [[NSGraphicsContext currentContext] flushGraphics];
  232634. [NSGraphicsContext restoreGraphicsState];
  232635. return Image (result);
  232636. }
  232637. const int KeyPress::spaceKey = ' ';
  232638. const int KeyPress::returnKey = 0x0d;
  232639. const int KeyPress::escapeKey = 0x1b;
  232640. const int KeyPress::backspaceKey = 0x7f;
  232641. const int KeyPress::leftKey = NSLeftArrowFunctionKey;
  232642. const int KeyPress::rightKey = NSRightArrowFunctionKey;
  232643. const int KeyPress::upKey = NSUpArrowFunctionKey;
  232644. const int KeyPress::downKey = NSDownArrowFunctionKey;
  232645. const int KeyPress::pageUpKey = NSPageUpFunctionKey;
  232646. const int KeyPress::pageDownKey = NSPageDownFunctionKey;
  232647. const int KeyPress::endKey = NSEndFunctionKey;
  232648. const int KeyPress::homeKey = NSHomeFunctionKey;
  232649. const int KeyPress::deleteKey = NSDeleteFunctionKey;
  232650. const int KeyPress::insertKey = -1;
  232651. const int KeyPress::tabKey = 9;
  232652. const int KeyPress::F1Key = NSF1FunctionKey;
  232653. const int KeyPress::F2Key = NSF2FunctionKey;
  232654. const int KeyPress::F3Key = NSF3FunctionKey;
  232655. const int KeyPress::F4Key = NSF4FunctionKey;
  232656. const int KeyPress::F5Key = NSF5FunctionKey;
  232657. const int KeyPress::F6Key = NSF6FunctionKey;
  232658. const int KeyPress::F7Key = NSF7FunctionKey;
  232659. const int KeyPress::F8Key = NSF8FunctionKey;
  232660. const int KeyPress::F9Key = NSF9FunctionKey;
  232661. const int KeyPress::F10Key = NSF10FunctionKey;
  232662. const int KeyPress::F11Key = NSF1FunctionKey;
  232663. const int KeyPress::F12Key = NSF12FunctionKey;
  232664. const int KeyPress::F13Key = NSF13FunctionKey;
  232665. const int KeyPress::F14Key = NSF14FunctionKey;
  232666. const int KeyPress::F15Key = NSF15FunctionKey;
  232667. const int KeyPress::F16Key = NSF16FunctionKey;
  232668. const int KeyPress::numberPad0 = 0x30020;
  232669. const int KeyPress::numberPad1 = 0x30021;
  232670. const int KeyPress::numberPad2 = 0x30022;
  232671. const int KeyPress::numberPad3 = 0x30023;
  232672. const int KeyPress::numberPad4 = 0x30024;
  232673. const int KeyPress::numberPad5 = 0x30025;
  232674. const int KeyPress::numberPad6 = 0x30026;
  232675. const int KeyPress::numberPad7 = 0x30027;
  232676. const int KeyPress::numberPad8 = 0x30028;
  232677. const int KeyPress::numberPad9 = 0x30029;
  232678. const int KeyPress::numberPadAdd = 0x3002a;
  232679. const int KeyPress::numberPadSubtract = 0x3002b;
  232680. const int KeyPress::numberPadMultiply = 0x3002c;
  232681. const int KeyPress::numberPadDivide = 0x3002d;
  232682. const int KeyPress::numberPadSeparator = 0x3002e;
  232683. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  232684. const int KeyPress::numberPadEquals = 0x30030;
  232685. const int KeyPress::numberPadDelete = 0x30031;
  232686. const int KeyPress::playKey = 0x30000;
  232687. const int KeyPress::stopKey = 0x30001;
  232688. const int KeyPress::fastForwardKey = 0x30002;
  232689. const int KeyPress::rewindKey = 0x30003;
  232690. #endif
  232691. /*** End of inlined file: juce_mac_NSViewComponentPeer.mm ***/
  232692. /*** Start of inlined file: juce_mac_MouseCursor.mm ***/
  232693. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232694. // compiled on its own).
  232695. #if JUCE_INCLUDED_FILE
  232696. #if JUCE_MAC
  232697. namespace MouseCursorHelpers
  232698. {
  232699. static void* createFromImage (const Image& image, float hotspotX, float hotspotY)
  232700. {
  232701. NSImage* im = CoreGraphicsImage::createNSImage (image);
  232702. NSCursor* c = [[NSCursor alloc] initWithImage: im
  232703. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  232704. [im release];
  232705. return c;
  232706. }
  232707. static void* fromWebKitFile (const char* filename, float hx, float hy)
  232708. {
  232709. FileInputStream fileStream (String ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources/") + filename);
  232710. BufferedInputStream buf (fileStream, 4096);
  232711. PNGImageFormat pngFormat;
  232712. Image im (pngFormat.decodeImage (buf));
  232713. if (im.isValid())
  232714. return createFromImage (im, hx * im.getWidth(), hy * im.getHeight());
  232715. jassertfalse;
  232716. return 0;
  232717. }
  232718. }
  232719. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  232720. {
  232721. return MouseCursorHelpers::createFromImage (image, (float) hotspotX, (float) hotspotY);
  232722. }
  232723. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  232724. {
  232725. const ScopedAutoReleasePool pool;
  232726. NSCursor* c = 0;
  232727. switch (type)
  232728. {
  232729. case NormalCursor: c = [NSCursor arrowCursor]; break;
  232730. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 8, 8, true), 0, 0);
  232731. case DraggingHandCursor: c = [NSCursor openHandCursor]; break;
  232732. case WaitCursor: c = [NSCursor arrowCursor]; break; // avoid this on the mac, let the OS provide the beachball
  232733. case IBeamCursor: c = [NSCursor IBeamCursor]; break;
  232734. case PointingHandCursor: c = [NSCursor pointingHandCursor]; break;
  232735. case LeftRightResizeCursor: c = [NSCursor resizeLeftRightCursor]; break;
  232736. case LeftEdgeResizeCursor: c = [NSCursor resizeLeftCursor]; break;
  232737. case RightEdgeResizeCursor: c = [NSCursor resizeRightCursor]; break;
  232738. case CrosshairCursor: c = [NSCursor crosshairCursor]; break;
  232739. case CopyingCursor: return MouseCursorHelpers::fromWebKitFile ("copyCursor.png", 0, 0);
  232740. case UpDownResizeCursor:
  232741. case TopEdgeResizeCursor:
  232742. case BottomEdgeResizeCursor:
  232743. return MouseCursorHelpers::fromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  232744. case TopLeftCornerResizeCursor:
  232745. case BottomRightCornerResizeCursor:
  232746. return MouseCursorHelpers::fromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  232747. case TopRightCornerResizeCursor:
  232748. case BottomLeftCornerResizeCursor:
  232749. return MouseCursorHelpers::fromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  232750. case UpDownLeftRightResizeCursor:
  232751. return MouseCursorHelpers::fromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  232752. default:
  232753. jassertfalse;
  232754. break;
  232755. }
  232756. [c retain];
  232757. return c;
  232758. }
  232759. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool /*isStandard*/)
  232760. {
  232761. [((NSCursor*) cursorHandle) release];
  232762. }
  232763. void MouseCursor::showInAllWindows() const
  232764. {
  232765. showInWindow (0);
  232766. }
  232767. void MouseCursor::showInWindow (ComponentPeer*) const
  232768. {
  232769. NSCursor* c = (NSCursor*) getHandle();
  232770. if (c == 0)
  232771. c = [NSCursor arrowCursor];
  232772. [c set];
  232773. }
  232774. #else
  232775. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) { return 0; }
  232776. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type) { return 0; }
  232777. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard) {}
  232778. void MouseCursor::showInAllWindows() const {}
  232779. void MouseCursor::showInWindow (ComponentPeer*) const {}
  232780. #endif
  232781. #endif
  232782. /*** End of inlined file: juce_mac_MouseCursor.mm ***/
  232783. /*** Start of inlined file: juce_mac_NSViewComponent.mm ***/
  232784. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232785. // compiled on its own).
  232786. #if JUCE_INCLUDED_FILE
  232787. class NSViewComponentInternal : public ComponentMovementWatcher
  232788. {
  232789. Component* const owner;
  232790. NSViewComponentPeer* currentPeer;
  232791. bool wasShowing;
  232792. public:
  232793. NSView* const view;
  232794. NSViewComponentInternal (NSView* const view_, Component* const owner_)
  232795. : ComponentMovementWatcher (owner_),
  232796. owner (owner_),
  232797. currentPeer (0),
  232798. wasShowing (false),
  232799. view (view_)
  232800. {
  232801. [view_ retain];
  232802. if (owner_->isShowing())
  232803. componentPeerChanged();
  232804. }
  232805. ~NSViewComponentInternal()
  232806. {
  232807. [view removeFromSuperview];
  232808. [view release];
  232809. }
  232810. void componentMovedOrResized (Component& comp, bool wasMoved, bool wasResized)
  232811. {
  232812. ComponentMovementWatcher::componentMovedOrResized (comp, wasMoved, wasResized);
  232813. // The ComponentMovementWatcher version of this method avoids calling
  232814. // us when the top-level comp is resized, but for an NSView we need to know this
  232815. // because with inverted co-ords, we need to update the position even if the
  232816. // top-left pos hasn't changed
  232817. if (comp.isOnDesktop() && wasResized)
  232818. componentMovedOrResized (wasMoved, wasResized);
  232819. }
  232820. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  232821. {
  232822. Component* const topComp = owner->getTopLevelComponent();
  232823. if (topComp->getPeer() != 0)
  232824. {
  232825. const Point<int> pos (owner->relativePositionToOtherComponent (topComp, Point<int>()));
  232826. NSRect r = NSMakeRect ((float) pos.getX(), (float) pos.getY(), (float) owner->getWidth(), (float) owner->getHeight());
  232827. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  232828. [view setFrame: r];
  232829. }
  232830. }
  232831. void componentPeerChanged()
  232832. {
  232833. NSViewComponentPeer* const peer = dynamic_cast <NSViewComponentPeer*> (owner->getPeer());
  232834. if (currentPeer != peer)
  232835. {
  232836. if ([view superview] != nil)
  232837. [view removeFromSuperview]; // Must be careful not to call this unless it's required - e.g. some Apple AU views
  232838. // override the call and use it as a sign that they're being deleted, which breaks everything..
  232839. currentPeer = peer;
  232840. if (peer != 0)
  232841. {
  232842. [peer->view addSubview: view];
  232843. componentMovedOrResized (false, false);
  232844. }
  232845. }
  232846. [view setHidden: ! owner->isShowing()];
  232847. }
  232848. void componentVisibilityChanged (Component&)
  232849. {
  232850. componentPeerChanged();
  232851. }
  232852. const Rectangle<int> getViewBounds() const
  232853. {
  232854. NSRect r = [view frame];
  232855. return Rectangle<int> (0, 0, (int) r.size.width, (int) r.size.height);
  232856. }
  232857. juce_UseDebuggingNewOperator
  232858. private:
  232859. NSViewComponentInternal (const NSViewComponentInternal&);
  232860. NSViewComponentInternal& operator= (const NSViewComponentInternal&);
  232861. };
  232862. NSViewComponent::NSViewComponent()
  232863. {
  232864. }
  232865. NSViewComponent::~NSViewComponent()
  232866. {
  232867. }
  232868. void NSViewComponent::setView (void* view)
  232869. {
  232870. if (view != getView())
  232871. {
  232872. if (view != 0)
  232873. info = new NSViewComponentInternal ((NSView*) view, this);
  232874. else
  232875. info = 0;
  232876. }
  232877. }
  232878. void* NSViewComponent::getView() const
  232879. {
  232880. return info == 0 ? 0 : info->view;
  232881. }
  232882. void NSViewComponent::resizeToFitView()
  232883. {
  232884. if (info != 0)
  232885. setBounds (info->getViewBounds());
  232886. }
  232887. void NSViewComponent::paint (Graphics&)
  232888. {
  232889. }
  232890. #endif
  232891. /*** End of inlined file: juce_mac_NSViewComponent.mm ***/
  232892. /*** Start of inlined file: juce_mac_AppleRemote.mm ***/
  232893. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232894. // compiled on its own).
  232895. #if JUCE_INCLUDED_FILE
  232896. AppleRemoteDevice::AppleRemoteDevice()
  232897. : device (0),
  232898. queue (0),
  232899. remoteId (0)
  232900. {
  232901. }
  232902. AppleRemoteDevice::~AppleRemoteDevice()
  232903. {
  232904. stop();
  232905. }
  232906. namespace
  232907. {
  232908. io_object_t getAppleRemoteDevice()
  232909. {
  232910. CFMutableDictionaryRef dict = IOServiceMatching ("AppleIRController");
  232911. io_iterator_t iter = 0;
  232912. io_object_t iod = 0;
  232913. if (IOServiceGetMatchingServices (kIOMasterPortDefault, dict, &iter) == kIOReturnSuccess
  232914. && iter != 0)
  232915. {
  232916. iod = IOIteratorNext (iter);
  232917. }
  232918. IOObjectRelease (iter);
  232919. return iod;
  232920. }
  232921. bool createAppleRemoteInterface (io_object_t iod, void** device)
  232922. {
  232923. jassert (*device == 0);
  232924. io_name_t classname;
  232925. if (IOObjectGetClass (iod, classname) == kIOReturnSuccess)
  232926. {
  232927. IOCFPlugInInterface** cfPlugInInterface = 0;
  232928. SInt32 score = 0;
  232929. if (IOCreatePlugInInterfaceForService (iod,
  232930. kIOHIDDeviceUserClientTypeID,
  232931. kIOCFPlugInInterfaceID,
  232932. &cfPlugInInterface,
  232933. &score) == kIOReturnSuccess)
  232934. {
  232935. HRESULT hr = (*cfPlugInInterface)->QueryInterface (cfPlugInInterface,
  232936. CFUUIDGetUUIDBytes (kIOHIDDeviceInterfaceID),
  232937. device);
  232938. (void) hr;
  232939. (*cfPlugInInterface)->Release (cfPlugInInterface);
  232940. }
  232941. }
  232942. return *device != 0;
  232943. }
  232944. void appleRemoteQueueCallback (void* const target, const IOReturn result, void*, void*)
  232945. {
  232946. if (result == kIOReturnSuccess)
  232947. ((AppleRemoteDevice*) target)->handleCallbackInternal();
  232948. }
  232949. }
  232950. bool AppleRemoteDevice::start (const bool inExclusiveMode)
  232951. {
  232952. if (queue != 0)
  232953. return true;
  232954. stop();
  232955. bool result = false;
  232956. io_object_t iod = getAppleRemoteDevice();
  232957. if (iod != 0)
  232958. {
  232959. if (createAppleRemoteInterface (iod, &device) && open (inExclusiveMode))
  232960. result = true;
  232961. else
  232962. stop();
  232963. IOObjectRelease (iod);
  232964. }
  232965. return result;
  232966. }
  232967. void AppleRemoteDevice::stop()
  232968. {
  232969. if (queue != 0)
  232970. {
  232971. (*(IOHIDQueueInterface**) queue)->stop ((IOHIDQueueInterface**) queue);
  232972. (*(IOHIDQueueInterface**) queue)->dispose ((IOHIDQueueInterface**) queue);
  232973. (*(IOHIDQueueInterface**) queue)->Release ((IOHIDQueueInterface**) queue);
  232974. queue = 0;
  232975. }
  232976. if (device != 0)
  232977. {
  232978. (*(IOHIDDeviceInterface**) device)->close ((IOHIDDeviceInterface**) device);
  232979. (*(IOHIDDeviceInterface**) device)->Release ((IOHIDDeviceInterface**) device);
  232980. device = 0;
  232981. }
  232982. }
  232983. bool AppleRemoteDevice::isActive() const
  232984. {
  232985. return queue != 0;
  232986. }
  232987. bool AppleRemoteDevice::open (const bool openInExclusiveMode)
  232988. {
  232989. Array <int> cookies;
  232990. CFArrayRef elements;
  232991. IOHIDDeviceInterface122** const device122 = (IOHIDDeviceInterface122**) device;
  232992. if ((*device122)->copyMatchingElements (device122, 0, &elements) != kIOReturnSuccess)
  232993. return false;
  232994. for (int i = 0; i < CFArrayGetCount (elements); ++i)
  232995. {
  232996. CFDictionaryRef element = (CFDictionaryRef) CFArrayGetValueAtIndex (elements, i);
  232997. // get the cookie
  232998. CFTypeRef object = CFDictionaryGetValue (element, CFSTR (kIOHIDElementCookieKey));
  232999. if (object == 0 || CFGetTypeID (object) != CFNumberGetTypeID())
  233000. continue;
  233001. long number;
  233002. if (! CFNumberGetValue ((CFNumberRef) object, kCFNumberLongType, &number))
  233003. continue;
  233004. cookies.add ((int) number);
  233005. }
  233006. CFRelease (elements);
  233007. if ((*(IOHIDDeviceInterface**) device)
  233008. ->open ((IOHIDDeviceInterface**) device,
  233009. openInExclusiveMode ? kIOHIDOptionsTypeSeizeDevice
  233010. : kIOHIDOptionsTypeNone) == KERN_SUCCESS)
  233011. {
  233012. queue = (*(IOHIDDeviceInterface**) device)->allocQueue ((IOHIDDeviceInterface**) device);
  233013. if (queue != 0)
  233014. {
  233015. (*(IOHIDQueueInterface**) queue)->create ((IOHIDQueueInterface**) queue, 0, 12);
  233016. for (int i = 0; i < cookies.size(); ++i)
  233017. {
  233018. IOHIDElementCookie cookie = (IOHIDElementCookie) cookies.getUnchecked(i);
  233019. (*(IOHIDQueueInterface**) queue)->addElement ((IOHIDQueueInterface**) queue, cookie, 0);
  233020. }
  233021. CFRunLoopSourceRef eventSource;
  233022. if ((*(IOHIDQueueInterface**) queue)
  233023. ->createAsyncEventSource ((IOHIDQueueInterface**) queue, &eventSource) == KERN_SUCCESS)
  233024. {
  233025. if ((*(IOHIDQueueInterface**) queue)->setEventCallout ((IOHIDQueueInterface**) queue,
  233026. appleRemoteQueueCallback, this, 0) == KERN_SUCCESS)
  233027. {
  233028. CFRunLoopAddSource (CFRunLoopGetCurrent(), eventSource, kCFRunLoopDefaultMode);
  233029. (*(IOHIDQueueInterface**) queue)->start ((IOHIDQueueInterface**) queue);
  233030. return true;
  233031. }
  233032. }
  233033. }
  233034. }
  233035. return false;
  233036. }
  233037. void AppleRemoteDevice::handleCallbackInternal()
  233038. {
  233039. int totalValues = 0;
  233040. AbsoluteTime nullTime = { 0, 0 };
  233041. char cookies [12];
  233042. int numCookies = 0;
  233043. while (numCookies < numElementsInArray (cookies))
  233044. {
  233045. IOHIDEventStruct e;
  233046. if ((*(IOHIDQueueInterface**) queue)->getNextEvent ((IOHIDQueueInterface**) queue, &e, nullTime, 0) != kIOReturnSuccess)
  233047. break;
  233048. if ((int) e.elementCookie == 19)
  233049. {
  233050. remoteId = e.value;
  233051. buttonPressed (switched, false);
  233052. }
  233053. else
  233054. {
  233055. totalValues += e.value;
  233056. cookies [numCookies++] = (char) (pointer_sized_int) e.elementCookie;
  233057. }
  233058. }
  233059. cookies [numCookies++] = 0;
  233060. //DBG (String::toHexString ((uint8*) cookies, numCookies, 1) + " " + String (totalValues));
  233061. static const char buttonPatterns[] =
  233062. {
  233063. 0x1f, 0x14, 0x12, 0x1f, 0x14, 0x12, 0,
  233064. 0x1f, 0x15, 0x12, 0x1f, 0x15, 0x12, 0,
  233065. 0x1f, 0x1d, 0x1c, 0x12, 0,
  233066. 0x1f, 0x1e, 0x1c, 0x12, 0,
  233067. 0x1f, 0x16, 0x12, 0x1f, 0x16, 0x12, 0,
  233068. 0x1f, 0x17, 0x12, 0x1f, 0x17, 0x12, 0,
  233069. 0x1f, 0x12, 0x04, 0x02, 0,
  233070. 0x1f, 0x12, 0x03, 0x02, 0,
  233071. 0x1f, 0x12, 0x1f, 0x12, 0,
  233072. 0x23, 0x1f, 0x12, 0x23, 0x1f, 0x12, 0,
  233073. 19, 0
  233074. };
  233075. int buttonNum = (int) menuButton;
  233076. int i = 0;
  233077. while (i < numElementsInArray (buttonPatterns))
  233078. {
  233079. if (strcmp (cookies, buttonPatterns + i) == 0)
  233080. {
  233081. buttonPressed ((ButtonType) buttonNum, totalValues > 0);
  233082. break;
  233083. }
  233084. i += (int) strlen (buttonPatterns + i) + 1;
  233085. ++buttonNum;
  233086. }
  233087. }
  233088. #endif
  233089. /*** End of inlined file: juce_mac_AppleRemote.mm ***/
  233090. /*** Start of inlined file: juce_mac_OpenGLComponent.mm ***/
  233091. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233092. // compiled on its own).
  233093. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  233094. #if JUCE_MAC
  233095. END_JUCE_NAMESPACE
  233096. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  233097. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  233098. {
  233099. CriticalSection* contextLock;
  233100. bool needsUpdate;
  233101. }
  233102. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  233103. - (bool) makeActive;
  233104. - (void) makeInactive;
  233105. - (void) reshape;
  233106. @end
  233107. @implementation ThreadSafeNSOpenGLView
  233108. - (id) initWithFrame: (NSRect) frameRect
  233109. pixelFormat: (NSOpenGLPixelFormat*) format
  233110. {
  233111. contextLock = new CriticalSection();
  233112. self = [super initWithFrame: frameRect pixelFormat: format];
  233113. if (self != nil)
  233114. [[NSNotificationCenter defaultCenter] addObserver: self
  233115. selector: @selector (_surfaceNeedsUpdate:)
  233116. name: NSViewGlobalFrameDidChangeNotification
  233117. object: self];
  233118. return self;
  233119. }
  233120. - (void) dealloc
  233121. {
  233122. [[NSNotificationCenter defaultCenter] removeObserver: self];
  233123. delete contextLock;
  233124. [super dealloc];
  233125. }
  233126. - (bool) makeActive
  233127. {
  233128. const ScopedLock sl (*contextLock);
  233129. if ([self openGLContext] == 0)
  233130. return false;
  233131. [[self openGLContext] makeCurrentContext];
  233132. if (needsUpdate)
  233133. {
  233134. [super update];
  233135. needsUpdate = false;
  233136. }
  233137. return true;
  233138. }
  233139. - (void) makeInactive
  233140. {
  233141. const ScopedLock sl (*contextLock);
  233142. [NSOpenGLContext clearCurrentContext];
  233143. }
  233144. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  233145. {
  233146. const ScopedLock sl (*contextLock);
  233147. needsUpdate = true;
  233148. }
  233149. - (void) update
  233150. {
  233151. const ScopedLock sl (*contextLock);
  233152. needsUpdate = true;
  233153. }
  233154. - (void) reshape
  233155. {
  233156. const ScopedLock sl (*contextLock);
  233157. needsUpdate = true;
  233158. }
  233159. @end
  233160. BEGIN_JUCE_NAMESPACE
  233161. class WindowedGLContext : public OpenGLContext
  233162. {
  233163. public:
  233164. WindowedGLContext (Component* const component,
  233165. const OpenGLPixelFormat& pixelFormat_,
  233166. NSOpenGLContext* sharedContext)
  233167. : renderContext (0),
  233168. pixelFormat (pixelFormat_)
  233169. {
  233170. jassert (component != 0);
  233171. NSOpenGLPixelFormatAttribute attribs [64];
  233172. int n = 0;
  233173. attribs[n++] = NSOpenGLPFADoubleBuffer;
  233174. attribs[n++] = NSOpenGLPFAAccelerated;
  233175. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  233176. attribs[n++] = NSOpenGLPFAColorSize;
  233177. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  233178. pixelFormat.greenBits,
  233179. pixelFormat.blueBits);
  233180. attribs[n++] = NSOpenGLPFAAlphaSize;
  233181. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  233182. attribs[n++] = NSOpenGLPFADepthSize;
  233183. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  233184. attribs[n++] = NSOpenGLPFAStencilSize;
  233185. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  233186. attribs[n++] = NSOpenGLPFAAccumSize;
  233187. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  233188. pixelFormat.accumulationBufferGreenBits,
  233189. pixelFormat.accumulationBufferBlueBits,
  233190. pixelFormat.accumulationBufferAlphaBits);
  233191. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  233192. attribs[n++] = NSOpenGLPFASampleBuffers;
  233193. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  233194. attribs[n++] = NSOpenGLPFAClosestPolicy;
  233195. attribs[n++] = NSOpenGLPFANoRecovery;
  233196. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  233197. NSOpenGLPixelFormat* format
  233198. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  233199. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  233200. pixelFormat: format];
  233201. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  233202. shareContext: sharedContext] autorelease];
  233203. const GLint swapInterval = 1;
  233204. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  233205. [view setOpenGLContext: renderContext];
  233206. [format release];
  233207. viewHolder = new NSViewComponentInternal (view, component);
  233208. }
  233209. ~WindowedGLContext()
  233210. {
  233211. deleteContext();
  233212. viewHolder = 0;
  233213. }
  233214. void deleteContext()
  233215. {
  233216. makeInactive();
  233217. [renderContext clearDrawable];
  233218. [renderContext setView: nil];
  233219. [view setOpenGLContext: nil];
  233220. renderContext = nil;
  233221. }
  233222. bool makeActive() const throw()
  233223. {
  233224. jassert (renderContext != 0);
  233225. if ([renderContext view] != view)
  233226. [renderContext setView: view];
  233227. [view makeActive];
  233228. return isActive();
  233229. }
  233230. bool makeInactive() const throw()
  233231. {
  233232. [view makeInactive];
  233233. return true;
  233234. }
  233235. bool isActive() const throw()
  233236. {
  233237. return [NSOpenGLContext currentContext] == renderContext;
  233238. }
  233239. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  233240. void* getRawContext() const throw() { return renderContext; }
  233241. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  233242. {
  233243. }
  233244. void swapBuffers()
  233245. {
  233246. [renderContext flushBuffer];
  233247. }
  233248. bool setSwapInterval (const int numFramesPerSwap)
  233249. {
  233250. [renderContext setValues: (const GLint*) &numFramesPerSwap
  233251. forParameter: NSOpenGLCPSwapInterval];
  233252. return true;
  233253. }
  233254. int getSwapInterval() const
  233255. {
  233256. GLint numFrames = 0;
  233257. [renderContext getValues: &numFrames
  233258. forParameter: NSOpenGLCPSwapInterval];
  233259. return numFrames;
  233260. }
  233261. void repaint()
  233262. {
  233263. // we need to invalidate the juce view that holds this gl view, to make it
  233264. // cause a repaint callback
  233265. NSView* v = (NSView*) viewHolder->view;
  233266. NSRect r = [v frame];
  233267. // bit of a bodge here.. if we only invalidate the area of the gl component,
  233268. // it's completely covered by the NSOpenGLView, so the OS throws away the
  233269. // repaint message, thus never causing our paint() callback, and never repainting
  233270. // the comp. So invalidating just a little bit around the edge helps..
  233271. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  233272. }
  233273. void* getNativeWindowHandle() const { return viewHolder->view; }
  233274. juce_UseDebuggingNewOperator
  233275. NSOpenGLContext* renderContext;
  233276. ThreadSafeNSOpenGLView* view;
  233277. private:
  233278. OpenGLPixelFormat pixelFormat;
  233279. ScopedPointer <NSViewComponentInternal> viewHolder;
  233280. WindowedGLContext (const WindowedGLContext&);
  233281. WindowedGLContext& operator= (const WindowedGLContext&);
  233282. };
  233283. OpenGLContext* OpenGLComponent::createContext()
  233284. {
  233285. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  233286. contextToShareListsWith != 0 ? (NSOpenGLContext*) contextToShareListsWith->getRawContext() : 0));
  233287. return (c->renderContext != 0) ? c.release() : 0;
  233288. }
  233289. void* OpenGLComponent::getNativeWindowHandle() const
  233290. {
  233291. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle()
  233292. : 0;
  233293. }
  233294. void juce_glViewport (const int w, const int h)
  233295. {
  233296. glViewport (0, 0, w, h);
  233297. }
  233298. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  233299. OwnedArray <OpenGLPixelFormat>& results)
  233300. {
  233301. /* GLint attribs [64];
  233302. int n = 0;
  233303. attribs[n++] = AGL_RGBA;
  233304. attribs[n++] = AGL_DOUBLEBUFFER;
  233305. attribs[n++] = AGL_ACCELERATED;
  233306. attribs[n++] = AGL_NO_RECOVERY;
  233307. attribs[n++] = AGL_NONE;
  233308. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  233309. while (p != 0)
  233310. {
  233311. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  233312. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  233313. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  233314. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  233315. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  233316. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  233317. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  233318. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  233319. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  233320. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  233321. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  233322. results.add (pf);
  233323. p = aglNextPixelFormat (p);
  233324. }*/
  233325. //jassertfalse // can't see how you do this in cocoa!
  233326. }
  233327. #else
  233328. END_JUCE_NAMESPACE
  233329. @interface JuceGLView : UIView
  233330. {
  233331. }
  233332. + (Class) layerClass;
  233333. @end
  233334. @implementation JuceGLView
  233335. + (Class) layerClass
  233336. {
  233337. return [CAEAGLLayer class];
  233338. }
  233339. @end
  233340. BEGIN_JUCE_NAMESPACE
  233341. class GLESContext : public OpenGLContext
  233342. {
  233343. public:
  233344. GLESContext (UIViewComponentPeer* peer,
  233345. Component* const component_,
  233346. const OpenGLPixelFormat& pixelFormat_,
  233347. const GLESContext* const sharedContext,
  233348. NSUInteger apiType)
  233349. : component (component_), pixelFormat (pixelFormat_), glLayer (0), context (0),
  233350. useDepthBuffer (pixelFormat_.depthBufferBits > 0), frameBufferHandle (0), colorBufferHandle (0),
  233351. depthBufferHandle (0), lastWidth (0), lastHeight (0)
  233352. {
  233353. view = [[JuceGLView alloc] initWithFrame: CGRectMake (0, 0, 64, 64)];
  233354. view.opaque = YES;
  233355. view.hidden = NO;
  233356. view.backgroundColor = [UIColor blackColor];
  233357. view.userInteractionEnabled = NO;
  233358. glLayer = (CAEAGLLayer*) [view layer];
  233359. [peer->view addSubview: view];
  233360. if (sharedContext != 0)
  233361. context = [[EAGLContext alloc] initWithAPI: apiType
  233362. sharegroup: [sharedContext->context sharegroup]];
  233363. else
  233364. context = [[EAGLContext alloc] initWithAPI: apiType];
  233365. createGLBuffers();
  233366. }
  233367. ~GLESContext()
  233368. {
  233369. deleteContext();
  233370. [view removeFromSuperview];
  233371. [view release];
  233372. freeGLBuffers();
  233373. }
  233374. void deleteContext()
  233375. {
  233376. makeInactive();
  233377. [context release];
  233378. context = nil;
  233379. }
  233380. bool makeActive() const throw()
  233381. {
  233382. jassert (context != 0);
  233383. [EAGLContext setCurrentContext: context];
  233384. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  233385. return true;
  233386. }
  233387. void swapBuffers()
  233388. {
  233389. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  233390. [context presentRenderbuffer: GL_RENDERBUFFER_OES];
  233391. }
  233392. bool makeInactive() const throw()
  233393. {
  233394. return [EAGLContext setCurrentContext: nil];
  233395. }
  233396. bool isActive() const throw()
  233397. {
  233398. return [EAGLContext currentContext] == context;
  233399. }
  233400. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  233401. void* getRawContext() const throw() { return glLayer; }
  233402. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  233403. {
  233404. view.frame = CGRectMake ((CGFloat) x, (CGFloat) y, (CGFloat) w, (CGFloat) h);
  233405. if (lastWidth != w || lastHeight != h)
  233406. {
  233407. lastWidth = w;
  233408. lastHeight = h;
  233409. freeGLBuffers();
  233410. createGLBuffers();
  233411. }
  233412. }
  233413. bool setSwapInterval (const int numFramesPerSwap)
  233414. {
  233415. numFrames = numFramesPerSwap;
  233416. return true;
  233417. }
  233418. int getSwapInterval() const
  233419. {
  233420. return numFrames;
  233421. }
  233422. void repaint()
  233423. {
  233424. }
  233425. void createGLBuffers()
  233426. {
  233427. makeActive();
  233428. glGenFramebuffersOES (1, &frameBufferHandle);
  233429. glGenRenderbuffersOES (1, &colorBufferHandle);
  233430. glGenRenderbuffersOES (1, &depthBufferHandle);
  233431. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  233432. [context renderbufferStorage: GL_RENDERBUFFER_OES fromDrawable: glLayer];
  233433. GLint width, height;
  233434. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &width);
  233435. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &height);
  233436. if (useDepthBuffer)
  233437. {
  233438. glBindRenderbufferOES (GL_RENDERBUFFER_OES, depthBufferHandle);
  233439. glRenderbufferStorageOES (GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height);
  233440. }
  233441. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  233442. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  233443. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorBufferHandle);
  233444. if (useDepthBuffer)
  233445. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBufferHandle);
  233446. jassert (glCheckFramebufferStatusOES (GL_FRAMEBUFFER_OES) == GL_FRAMEBUFFER_COMPLETE_OES);
  233447. }
  233448. void freeGLBuffers()
  233449. {
  233450. if (frameBufferHandle != 0)
  233451. {
  233452. glDeleteFramebuffersOES (1, &frameBufferHandle);
  233453. frameBufferHandle = 0;
  233454. }
  233455. if (colorBufferHandle != 0)
  233456. {
  233457. glDeleteRenderbuffersOES (1, &colorBufferHandle);
  233458. colorBufferHandle = 0;
  233459. }
  233460. if (depthBufferHandle != 0)
  233461. {
  233462. glDeleteRenderbuffersOES (1, &depthBufferHandle);
  233463. depthBufferHandle = 0;
  233464. }
  233465. }
  233466. juce_UseDebuggingNewOperator
  233467. private:
  233468. Component::SafePointer<Component> component;
  233469. OpenGLPixelFormat pixelFormat;
  233470. JuceGLView* view;
  233471. CAEAGLLayer* glLayer;
  233472. EAGLContext* context;
  233473. bool useDepthBuffer;
  233474. GLuint frameBufferHandle, colorBufferHandle, depthBufferHandle;
  233475. int numFrames;
  233476. int lastWidth, lastHeight;
  233477. GLESContext (const GLESContext&);
  233478. GLESContext& operator= (const GLESContext&);
  233479. };
  233480. OpenGLContext* OpenGLComponent::createContext()
  233481. {
  233482. ScopedAutoReleasePool pool;
  233483. UIViewComponentPeer* peer = dynamic_cast <UIViewComponentPeer*> (getPeer());
  233484. if (peer != 0)
  233485. return new GLESContext (peer, this, preferredPixelFormat,
  233486. dynamic_cast <const GLESContext*> (contextToShareListsWith),
  233487. type == openGLES2 ? kEAGLRenderingAPIOpenGLES2 : kEAGLRenderingAPIOpenGLES1);
  233488. return 0;
  233489. }
  233490. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  233491. OwnedArray <OpenGLPixelFormat>& /*results*/)
  233492. {
  233493. }
  233494. void juce_glViewport (const int w, const int h)
  233495. {
  233496. glViewport (0, 0, w, h);
  233497. }
  233498. #endif
  233499. #endif
  233500. /*** End of inlined file: juce_mac_OpenGLComponent.mm ***/
  233501. /*** Start of inlined file: juce_mac_MainMenu.mm ***/
  233502. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233503. // compiled on its own).
  233504. #if JUCE_INCLUDED_FILE
  233505. class JuceMainMenuHandler;
  233506. END_JUCE_NAMESPACE
  233507. using namespace JUCE_NAMESPACE;
  233508. #define JuceMenuCallback MakeObjCClassName(JuceMenuCallback)
  233509. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  233510. @interface JuceMenuCallback : NSObject <NSMenuDelegate>
  233511. #else
  233512. @interface JuceMenuCallback : NSObject
  233513. #endif
  233514. {
  233515. JuceMainMenuHandler* owner;
  233516. }
  233517. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_;
  233518. - (void) dealloc;
  233519. - (void) menuItemInvoked: (id) menu;
  233520. - (void) menuNeedsUpdate: (NSMenu*) menu;
  233521. @end
  233522. BEGIN_JUCE_NAMESPACE
  233523. class JuceMainMenuHandler : private MenuBarModel::Listener,
  233524. private DeletedAtShutdown
  233525. {
  233526. public:
  233527. static JuceMainMenuHandler* instance;
  233528. JuceMainMenuHandler()
  233529. : currentModel (0),
  233530. lastUpdateTime (0)
  233531. {
  233532. callback = [[JuceMenuCallback alloc] initWithOwner: this];
  233533. }
  233534. ~JuceMainMenuHandler()
  233535. {
  233536. setMenu (0);
  233537. jassert (instance == this);
  233538. instance = 0;
  233539. [callback release];
  233540. }
  233541. void setMenu (MenuBarModel* const newMenuBarModel)
  233542. {
  233543. if (currentModel != newMenuBarModel)
  233544. {
  233545. if (currentModel != 0)
  233546. currentModel->removeListener (this);
  233547. currentModel = newMenuBarModel;
  233548. if (currentModel != 0)
  233549. currentModel->addListener (this);
  233550. menuBarItemsChanged (0);
  233551. }
  233552. }
  233553. void addSubMenu (NSMenu* parent, const PopupMenu& child,
  233554. const String& name, const int menuId, const int tag)
  233555. {
  233556. NSMenuItem* item = [parent addItemWithTitle: juceStringToNS (name)
  233557. action: nil
  233558. keyEquivalent: @""];
  233559. [item setTag: tag];
  233560. NSMenu* sub = createMenu (child, name, menuId, tag);
  233561. [parent setSubmenu: sub forItem: item];
  233562. [sub setAutoenablesItems: false];
  233563. [sub release];
  233564. }
  233565. void updateSubMenu (NSMenuItem* parentItem, const PopupMenu& menuToCopy,
  233566. const String& name, const int menuId, const int tag)
  233567. {
  233568. [parentItem setTag: tag];
  233569. NSMenu* menu = [parentItem submenu];
  233570. [menu setTitle: juceStringToNS (name)];
  233571. while ([menu numberOfItems] > 0)
  233572. [menu removeItemAtIndex: 0];
  233573. PopupMenu::MenuItemIterator iter (menuToCopy);
  233574. while (iter.next())
  233575. addMenuItem (iter, menu, menuId, tag);
  233576. [menu setAutoenablesItems: false];
  233577. [menu update];
  233578. }
  233579. void menuBarItemsChanged (MenuBarModel*)
  233580. {
  233581. lastUpdateTime = Time::getMillisecondCounter();
  233582. StringArray menuNames;
  233583. if (currentModel != 0)
  233584. menuNames = currentModel->getMenuBarNames();
  233585. NSMenu* menuBar = [NSApp mainMenu];
  233586. while ([menuBar numberOfItems] > 1 + menuNames.size())
  233587. [menuBar removeItemAtIndex: [menuBar numberOfItems] - 1];
  233588. int menuId = 1;
  233589. for (int i = 0; i < menuNames.size(); ++i)
  233590. {
  233591. const PopupMenu menu (currentModel->getMenuForIndex (i, menuNames [i]));
  233592. if (i >= [menuBar numberOfItems] - 1)
  233593. addSubMenu (menuBar, menu, menuNames[i], menuId, i);
  233594. else
  233595. updateSubMenu ([menuBar itemAtIndex: 1 + i], menu, menuNames[i], menuId, i);
  233596. }
  233597. }
  233598. static void flashMenuBar (NSMenu* menu)
  233599. {
  233600. if ([[menu title] isEqualToString: @"Apple"])
  233601. return;
  233602. [menu retain];
  233603. const unichar f35Key = NSF35FunctionKey;
  233604. NSString* f35String = [NSString stringWithCharacters: &f35Key length: 1];
  233605. NSMenuItem* item = [[NSMenuItem alloc] initWithTitle: @"x"
  233606. action: nil
  233607. keyEquivalent: f35String];
  233608. [item setTarget: nil];
  233609. [menu insertItem: item atIndex: [menu numberOfItems]];
  233610. [item release];
  233611. if ([menu indexOfItem: item] >= 0)
  233612. {
  233613. NSEvent* f35Event = [NSEvent keyEventWithType: NSKeyDown
  233614. location: NSZeroPoint
  233615. modifierFlags: NSCommandKeyMask
  233616. timestamp: 0
  233617. windowNumber: 0
  233618. context: [NSGraphicsContext currentContext]
  233619. characters: f35String
  233620. charactersIgnoringModifiers: f35String
  233621. isARepeat: NO
  233622. keyCode: 0];
  233623. [menu performKeyEquivalent: f35Event];
  233624. if ([menu indexOfItem: item] >= 0)
  233625. [menu removeItem: item]; // (this throws if the item isn't actually in the menu)
  233626. }
  233627. [menu release];
  233628. }
  233629. static NSMenuItem* findMenuItem (NSMenu* const menu, const ApplicationCommandTarget::InvocationInfo& info)
  233630. {
  233631. for (NSInteger i = [menu numberOfItems]; --i >= 0;)
  233632. {
  233633. NSMenuItem* m = [menu itemAtIndex: i];
  233634. if ([m tag] == info.commandID)
  233635. return m;
  233636. if ([m submenu] != 0)
  233637. {
  233638. NSMenuItem* found = findMenuItem ([m submenu], info);
  233639. if (found != 0)
  233640. return found;
  233641. }
  233642. }
  233643. return 0;
  233644. }
  233645. void menuCommandInvoked (MenuBarModel*, const ApplicationCommandTarget::InvocationInfo& info)
  233646. {
  233647. NSMenuItem* item = findMenuItem ([NSApp mainMenu], info);
  233648. if (item != 0)
  233649. flashMenuBar ([item menu]);
  233650. }
  233651. void updateMenus()
  233652. {
  233653. if (Time::getMillisecondCounter() > lastUpdateTime + 500)
  233654. menuBarItemsChanged (0);
  233655. }
  233656. void invoke (const int commandId, ApplicationCommandManager* const commandManager, const int topLevelIndex) const
  233657. {
  233658. if (currentModel != 0)
  233659. {
  233660. if (commandManager != 0)
  233661. {
  233662. ApplicationCommandTarget::InvocationInfo info (commandId);
  233663. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  233664. commandManager->invoke (info, true);
  233665. }
  233666. currentModel->menuItemSelected (commandId, topLevelIndex);
  233667. }
  233668. }
  233669. MenuBarModel* currentModel;
  233670. uint32 lastUpdateTime;
  233671. void addMenuItem (PopupMenu::MenuItemIterator& iter, NSMenu* menuToAddTo,
  233672. const int topLevelMenuId, const int topLevelIndex)
  233673. {
  233674. NSString* text = juceStringToNS (iter.itemName.upToFirstOccurrenceOf ("<end>", false, true));
  233675. if (text == 0)
  233676. text = @"";
  233677. if (iter.isSeparator)
  233678. {
  233679. [menuToAddTo addItem: [NSMenuItem separatorItem]];
  233680. }
  233681. else if (iter.isSectionHeader)
  233682. {
  233683. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  233684. action: nil
  233685. keyEquivalent: @""];
  233686. [item setEnabled: false];
  233687. }
  233688. else if (iter.subMenu != 0)
  233689. {
  233690. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  233691. action: nil
  233692. keyEquivalent: @""];
  233693. [item setTag: iter.itemId];
  233694. [item setEnabled: iter.isEnabled];
  233695. NSMenu* sub = createMenu (*iter.subMenu, iter.itemName, topLevelMenuId, topLevelIndex);
  233696. [sub setDelegate: nil];
  233697. [menuToAddTo setSubmenu: sub forItem: item];
  233698. [sub release];
  233699. }
  233700. else
  233701. {
  233702. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  233703. action: @selector (menuItemInvoked:)
  233704. keyEquivalent: @""];
  233705. [item setTag: iter.itemId];
  233706. [item setEnabled: iter.isEnabled];
  233707. [item setState: iter.isTicked ? NSOnState : NSOffState];
  233708. [item setTarget: (id) callback];
  233709. NSMutableArray* info = [NSMutableArray arrayWithObject: [NSNumber numberWithUnsignedLongLong: (pointer_sized_int) (void*) iter.commandManager]];
  233710. [info addObject: [NSNumber numberWithInt: topLevelIndex]];
  233711. [item setRepresentedObject: info];
  233712. if (iter.commandManager != 0)
  233713. {
  233714. const Array <KeyPress> keyPresses (iter.commandManager->getKeyMappings()
  233715. ->getKeyPressesAssignedToCommand (iter.itemId));
  233716. if (keyPresses.size() > 0)
  233717. {
  233718. const KeyPress& kp = keyPresses.getReference(0);
  233719. if (kp.getKeyCode() != KeyPress::backspaceKey
  233720. && kp.getKeyCode() != KeyPress::deleteKey) // (adding these is annoying because it flashes the menu bar
  233721. // every time you press the key while editing text)
  233722. {
  233723. juce_wchar key = kp.getTextCharacter();
  233724. if (kp.getKeyCode() == KeyPress::backspaceKey)
  233725. key = NSBackspaceCharacter;
  233726. else if (kp.getKeyCode() == KeyPress::deleteKey)
  233727. key = NSDeleteCharacter;
  233728. else if (key == 0)
  233729. key = (juce_wchar) kp.getKeyCode();
  233730. unsigned int mods = 0;
  233731. if (kp.getModifiers().isShiftDown())
  233732. mods |= NSShiftKeyMask;
  233733. if (kp.getModifiers().isCtrlDown())
  233734. mods |= NSControlKeyMask;
  233735. if (kp.getModifiers().isAltDown())
  233736. mods |= NSAlternateKeyMask;
  233737. if (kp.getModifiers().isCommandDown())
  233738. mods |= NSCommandKeyMask;
  233739. [item setKeyEquivalent: juceStringToNS (String::charToString (key))];
  233740. [item setKeyEquivalentModifierMask: mods];
  233741. }
  233742. }
  233743. }
  233744. }
  233745. }
  233746. JuceMenuCallback* callback;
  233747. private:
  233748. NSMenu* createMenu (const PopupMenu menu,
  233749. const String& menuName,
  233750. const int topLevelMenuId,
  233751. const int topLevelIndex)
  233752. {
  233753. NSMenu* m = [[NSMenu alloc] initWithTitle: juceStringToNS (menuName)];
  233754. [m setAutoenablesItems: false];
  233755. [m setDelegate: callback];
  233756. PopupMenu::MenuItemIterator iter (menu);
  233757. while (iter.next())
  233758. addMenuItem (iter, m, topLevelMenuId, topLevelIndex);
  233759. [m update];
  233760. return m;
  233761. }
  233762. };
  233763. JuceMainMenuHandler* JuceMainMenuHandler::instance = 0;
  233764. END_JUCE_NAMESPACE
  233765. @implementation JuceMenuCallback
  233766. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_
  233767. {
  233768. [super init];
  233769. owner = owner_;
  233770. return self;
  233771. }
  233772. - (void) dealloc
  233773. {
  233774. [super dealloc];
  233775. }
  233776. - (void) menuItemInvoked: (id) menu
  233777. {
  233778. NSMenuItem* item = (NSMenuItem*) menu;
  233779. if ([[item representedObject] isKindOfClass: [NSArray class]])
  233780. {
  233781. // If the menu is being triggered by a keypress, the OS will have picked it up before we had a chance to offer it to
  233782. // our own components, which may have wanted to intercept it. So, rather than dispatching directly, we'll feed it back
  233783. // into the focused component and let it trigger the menu item indirectly.
  233784. NSEvent* e = [NSApp currentEvent];
  233785. if ([e type] == NSKeyDown || [e type] == NSKeyUp)
  233786. {
  233787. if (JUCE_NAMESPACE::Component::getCurrentlyFocusedComponent() != 0)
  233788. {
  233789. JUCE_NAMESPACE::NSViewComponentPeer* peer = dynamic_cast <JUCE_NAMESPACE::NSViewComponentPeer*> (JUCE_NAMESPACE::Component::getCurrentlyFocusedComponent()->getPeer());
  233790. if (peer != 0)
  233791. {
  233792. if ([e type] == NSKeyDown)
  233793. peer->redirectKeyDown (e);
  233794. else
  233795. peer->redirectKeyUp (e);
  233796. return;
  233797. }
  233798. }
  233799. }
  233800. NSArray* info = (NSArray*) [item representedObject];
  233801. owner->invoke ((int) [item tag],
  233802. (ApplicationCommandManager*) (pointer_sized_int)
  233803. [((NSNumber*) [info objectAtIndex: 0]) unsignedLongLongValue],
  233804. (int) [((NSNumber*) [info objectAtIndex: 1]) intValue]);
  233805. }
  233806. }
  233807. - (void) menuNeedsUpdate: (NSMenu*) menu;
  233808. {
  233809. (void) menu;
  233810. if (JuceMainMenuHandler::instance != 0)
  233811. JuceMainMenuHandler::instance->updateMenus();
  233812. }
  233813. @end
  233814. BEGIN_JUCE_NAMESPACE
  233815. namespace MainMenuHelpers
  233816. {
  233817. NSMenu* createStandardAppMenu (NSMenu* menu, const String& appName, const PopupMenu* extraItems)
  233818. {
  233819. if (extraItems != 0 && JuceMainMenuHandler::instance != 0 && extraItems->getNumItems() > 0)
  233820. {
  233821. PopupMenu::MenuItemIterator iter (*extraItems);
  233822. while (iter.next())
  233823. JuceMainMenuHandler::instance->addMenuItem (iter, menu, 0, -1);
  233824. [menu addItem: [NSMenuItem separatorItem]];
  233825. }
  233826. NSMenuItem* item;
  233827. // Services...
  233828. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Services", nil)
  233829. action: nil keyEquivalent: @""];
  233830. [menu addItem: item];
  233831. [item release];
  233832. NSMenu* servicesMenu = [[NSMenu alloc] initWithTitle: @"Services"];
  233833. [menu setSubmenu: servicesMenu forItem: item];
  233834. [NSApp setServicesMenu: servicesMenu];
  233835. [servicesMenu release];
  233836. [menu addItem: [NSMenuItem separatorItem]];
  233837. // Hide + Show stuff...
  233838. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Hide " + appName)
  233839. action: @selector (hide:) keyEquivalent: @"h"];
  233840. [item setTarget: NSApp];
  233841. [menu addItem: item];
  233842. [item release];
  233843. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Hide Others", nil)
  233844. action: @selector (hideOtherApplications:) keyEquivalent: @"h"];
  233845. [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
  233846. [item setTarget: NSApp];
  233847. [menu addItem: item];
  233848. [item release];
  233849. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Show All", nil)
  233850. action: @selector (unhideAllApplications:) keyEquivalent: @""];
  233851. [item setTarget: NSApp];
  233852. [menu addItem: item];
  233853. [item release];
  233854. [menu addItem: [NSMenuItem separatorItem]];
  233855. // Quit item....
  233856. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Quit " + appName)
  233857. action: @selector (terminate:) keyEquivalent: @"q"];
  233858. [item setTarget: NSApp];
  233859. [menu addItem: item];
  233860. [item release];
  233861. return menu;
  233862. }
  233863. // Since our app has no NIB, this initialises a standard app menu...
  233864. void rebuildMainMenu (const PopupMenu* extraItems)
  233865. {
  233866. // this can't be used in a plugin!
  233867. jassert (JUCEApplication::isStandaloneApp());
  233868. if (JUCEApplication::getInstance() != 0)
  233869. {
  233870. const ScopedAutoReleasePool pool;
  233871. NSMenu* mainMenu = [[NSMenu alloc] initWithTitle: @"MainMenu"];
  233872. NSMenuItem* item = [mainMenu addItemWithTitle: @"Apple" action: nil keyEquivalent: @""];
  233873. NSMenu* appMenu = [[NSMenu alloc] initWithTitle: @"Apple"];
  233874. [NSApp performSelector: @selector (setAppleMenu:) withObject: appMenu];
  233875. [mainMenu setSubmenu: appMenu forItem: item];
  233876. [NSApp setMainMenu: mainMenu];
  233877. MainMenuHelpers::createStandardAppMenu (appMenu, JUCEApplication::getInstance()->getApplicationName(), extraItems);
  233878. [appMenu release];
  233879. [mainMenu release];
  233880. }
  233881. }
  233882. }
  233883. void MenuBarModel::setMacMainMenu (MenuBarModel* newMenuBarModel,
  233884. const PopupMenu* extraAppleMenuItems)
  233885. {
  233886. if (getMacMainMenu() != newMenuBarModel)
  233887. {
  233888. const ScopedAutoReleasePool pool;
  233889. if (newMenuBarModel == 0)
  233890. {
  233891. delete JuceMainMenuHandler::instance;
  233892. jassert (JuceMainMenuHandler::instance == 0); // should be zeroed in the destructor
  233893. jassert (extraAppleMenuItems == 0); // you can't specify some extra items without also supplying a model
  233894. extraAppleMenuItems = 0;
  233895. }
  233896. else
  233897. {
  233898. if (JuceMainMenuHandler::instance == 0)
  233899. JuceMainMenuHandler::instance = new JuceMainMenuHandler();
  233900. JuceMainMenuHandler::instance->setMenu (newMenuBarModel);
  233901. }
  233902. }
  233903. MainMenuHelpers::rebuildMainMenu (extraAppleMenuItems);
  233904. if (newMenuBarModel != 0)
  233905. newMenuBarModel->menuItemsChanged();
  233906. }
  233907. MenuBarModel* MenuBarModel::getMacMainMenu()
  233908. {
  233909. return JuceMainMenuHandler::instance != 0
  233910. ? JuceMainMenuHandler::instance->currentModel : 0;
  233911. }
  233912. void juce_initialiseMacMainMenu()
  233913. {
  233914. if (JuceMainMenuHandler::instance == 0)
  233915. MainMenuHelpers::rebuildMainMenu (0);
  233916. }
  233917. #endif
  233918. /*** End of inlined file: juce_mac_MainMenu.mm ***/
  233919. /*** Start of inlined file: juce_mac_FileChooser.mm ***/
  233920. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233921. // compiled on its own).
  233922. #if JUCE_INCLUDED_FILE
  233923. #if JUCE_MAC
  233924. END_JUCE_NAMESPACE
  233925. using namespace JUCE_NAMESPACE;
  233926. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  233927. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  233928. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  233929. #else
  233930. @interface JuceFileChooserDelegate : NSObject
  233931. #endif
  233932. {
  233933. StringArray* filters;
  233934. }
  233935. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  233936. - (void) dealloc;
  233937. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  233938. @end
  233939. @implementation JuceFileChooserDelegate
  233940. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  233941. {
  233942. [super init];
  233943. filters = filters_;
  233944. return self;
  233945. }
  233946. - (void) dealloc
  233947. {
  233948. delete filters;
  233949. [super dealloc];
  233950. }
  233951. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  233952. {
  233953. (void) sender;
  233954. const File f (nsStringToJuce (filename));
  233955. for (int i = filters->size(); --i >= 0;)
  233956. if (f.getFileName().matchesWildcard ((*filters)[i], true))
  233957. return true;
  233958. return f.isDirectory();
  233959. }
  233960. @end
  233961. BEGIN_JUCE_NAMESPACE
  233962. void FileChooser::showPlatformDialog (Array<File>& results,
  233963. const String& title,
  233964. const File& currentFileOrDirectory,
  233965. const String& filter,
  233966. bool selectsDirectory,
  233967. bool selectsFiles,
  233968. bool isSaveDialogue,
  233969. bool warnAboutOverwritingExistingFiles,
  233970. bool selectMultipleFiles,
  233971. FilePreviewComponent* extraInfoComponent)
  233972. {
  233973. const ScopedAutoReleasePool pool;
  233974. StringArray* filters = new StringArray();
  233975. filters->addTokens (filter.replaceCharacters (",:", ";;"), ";", String::empty);
  233976. filters->trim();
  233977. filters->removeEmptyStrings();
  233978. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  233979. [delegate autorelease];
  233980. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  233981. : [NSOpenPanel openPanel];
  233982. [panel setTitle: juceStringToNS (title)];
  233983. if (! isSaveDialogue)
  233984. {
  233985. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  233986. [openPanel setCanChooseDirectories: selectsDirectory];
  233987. [openPanel setCanChooseFiles: selectsFiles];
  233988. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  233989. }
  233990. [panel setDelegate: delegate];
  233991. if (isSaveDialogue || selectsDirectory)
  233992. [panel setCanCreateDirectories: YES];
  233993. String directory, filename;
  233994. if (currentFileOrDirectory.isDirectory())
  233995. {
  233996. directory = currentFileOrDirectory.getFullPathName();
  233997. }
  233998. else
  233999. {
  234000. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  234001. filename = currentFileOrDirectory.getFileName();
  234002. }
  234003. if ([panel runModalForDirectory: juceStringToNS (directory)
  234004. file: juceStringToNS (filename)]
  234005. == NSOKButton)
  234006. {
  234007. if (isSaveDialogue)
  234008. {
  234009. results.add (File (nsStringToJuce ([panel filename])));
  234010. }
  234011. else
  234012. {
  234013. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  234014. NSArray* urls = [openPanel filenames];
  234015. for (unsigned int i = 0; i < [urls count]; ++i)
  234016. {
  234017. NSString* f = [urls objectAtIndex: i];
  234018. results.add (File (nsStringToJuce (f)));
  234019. }
  234020. }
  234021. }
  234022. [panel setDelegate: nil];
  234023. }
  234024. #else
  234025. void FileChooser::showPlatformDialog (Array<File>& results,
  234026. const String& title,
  234027. const File& currentFileOrDirectory,
  234028. const String& filter,
  234029. bool selectsDirectory,
  234030. bool selectsFiles,
  234031. bool isSaveDialogue,
  234032. bool warnAboutOverwritingExistingFiles,
  234033. bool selectMultipleFiles,
  234034. FilePreviewComponent* extraInfoComponent)
  234035. {
  234036. const ScopedAutoReleasePool pool;
  234037. jassertfalse; //xxx to do
  234038. }
  234039. #endif
  234040. #endif
  234041. /*** End of inlined file: juce_mac_FileChooser.mm ***/
  234042. /*** Start of inlined file: juce_mac_QuickTimeMovieComponent.mm ***/
  234043. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234044. // compiled on its own).
  234045. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  234046. END_JUCE_NAMESPACE
  234047. #define NonInterceptingQTMovieView MakeObjCClassName(NonInterceptingQTMovieView)
  234048. @interface NonInterceptingQTMovieView : QTMovieView
  234049. {
  234050. }
  234051. - (id) initWithFrame: (NSRect) frame;
  234052. - (BOOL) acceptsFirstMouse: (NSEvent*) theEvent;
  234053. - (NSView*) hitTest: (NSPoint) p;
  234054. @end
  234055. @implementation NonInterceptingQTMovieView
  234056. - (id) initWithFrame: (NSRect) frame
  234057. {
  234058. self = [super initWithFrame: frame];
  234059. [self setNextResponder: [self superview]];
  234060. return self;
  234061. }
  234062. - (void) dealloc
  234063. {
  234064. [super dealloc];
  234065. }
  234066. - (NSView*) hitTest: (NSPoint) point
  234067. {
  234068. return [self isControllerVisible] ? [super hitTest: point] : nil;
  234069. }
  234070. - (BOOL) acceptsFirstMouse: (NSEvent*) theEvent
  234071. {
  234072. return YES;
  234073. }
  234074. @end
  234075. BEGIN_JUCE_NAMESPACE
  234076. #define theMovie (static_cast <QTMovie*> (movie))
  234077. QuickTimeMovieComponent::QuickTimeMovieComponent()
  234078. : movie (0)
  234079. {
  234080. setOpaque (true);
  234081. setVisible (true);
  234082. QTMovieView* view = [[NonInterceptingQTMovieView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)];
  234083. setView (view);
  234084. [view release];
  234085. }
  234086. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  234087. {
  234088. closeMovie();
  234089. setView (0);
  234090. }
  234091. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  234092. {
  234093. return true;
  234094. }
  234095. static QTMovie* openMovieFromStream (InputStream* movieStream, File& movieFile)
  234096. {
  234097. // unfortunately, QTMovie objects can only be created on the main thread..
  234098. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  234099. QTMovie* movie = 0;
  234100. FileInputStream* const fin = dynamic_cast <FileInputStream*> (movieStream);
  234101. if (fin != 0)
  234102. {
  234103. movieFile = fin->getFile();
  234104. movie = [QTMovie movieWithFile: juceStringToNS (movieFile.getFullPathName())
  234105. error: nil];
  234106. }
  234107. else
  234108. {
  234109. MemoryBlock temp;
  234110. movieStream->readIntoMemoryBlock (temp);
  234111. const char* const suffixesToTry[] = { ".mov", ".mp3", ".avi", ".m4a" };
  234112. for (int i = 0; i < numElementsInArray (suffixesToTry); ++i)
  234113. {
  234114. movie = [QTMovie movieWithDataReference: [QTDataReference dataReferenceWithReferenceToData: [NSData dataWithBytes: temp.getData()
  234115. length: temp.getSize()]
  234116. name: [NSString stringWithUTF8String: suffixesToTry[i]]
  234117. MIMEType: @""]
  234118. error: nil];
  234119. if (movie != 0)
  234120. break;
  234121. }
  234122. }
  234123. return movie;
  234124. }
  234125. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  234126. const bool isControllerVisible_)
  234127. {
  234128. return loadMovie ((InputStream*) movieFile_.createInputStream(), isControllerVisible_);
  234129. }
  234130. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  234131. const bool controllerVisible_)
  234132. {
  234133. closeMovie();
  234134. if (getPeer() == 0)
  234135. {
  234136. // To open a movie, this component must be visible inside a functioning window, so that
  234137. // the QT control can be assigned to the window.
  234138. jassertfalse;
  234139. return false;
  234140. }
  234141. movie = openMovieFromStream (movieStream, movieFile);
  234142. [theMovie retain];
  234143. QTMovieView* view = (QTMovieView*) getView();
  234144. [view setMovie: theMovie];
  234145. [view setControllerVisible: controllerVisible_];
  234146. setLooping (looping);
  234147. return movie != nil;
  234148. }
  234149. bool QuickTimeMovieComponent::loadMovie (const URL& movieURL,
  234150. const bool isControllerVisible_)
  234151. {
  234152. // unfortunately, QTMovie objects can only be created on the main thread..
  234153. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  234154. closeMovie();
  234155. if (getPeer() == 0)
  234156. {
  234157. // To open a movie, this component must be visible inside a functioning window, so that
  234158. // the QT control can be assigned to the window.
  234159. jassertfalse;
  234160. return false;
  234161. }
  234162. NSURL* url = [NSURL URLWithString: juceStringToNS (movieURL.toString (true))];
  234163. NSError* err;
  234164. if ([QTMovie canInitWithURL: url])
  234165. movie = [QTMovie movieWithURL: url error: &err];
  234166. [theMovie retain];
  234167. QTMovieView* view = (QTMovieView*) getView();
  234168. [view setMovie: theMovie];
  234169. [view setControllerVisible: controllerVisible];
  234170. setLooping (looping);
  234171. return movie != nil;
  234172. }
  234173. void QuickTimeMovieComponent::closeMovie()
  234174. {
  234175. stop();
  234176. QTMovieView* view = (QTMovieView*) getView();
  234177. [view setMovie: nil];
  234178. [theMovie release];
  234179. movie = 0;
  234180. movieFile = File::nonexistent;
  234181. }
  234182. bool QuickTimeMovieComponent::isMovieOpen() const
  234183. {
  234184. return movie != nil;
  234185. }
  234186. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  234187. {
  234188. return movieFile;
  234189. }
  234190. void QuickTimeMovieComponent::play()
  234191. {
  234192. [theMovie play];
  234193. }
  234194. void QuickTimeMovieComponent::stop()
  234195. {
  234196. [theMovie stop];
  234197. }
  234198. bool QuickTimeMovieComponent::isPlaying() const
  234199. {
  234200. return movie != 0 && [theMovie rate] != 0;
  234201. }
  234202. void QuickTimeMovieComponent::setPosition (const double seconds)
  234203. {
  234204. if (movie != 0)
  234205. {
  234206. QTTime t;
  234207. t.timeValue = (uint64) (100000.0 * seconds);
  234208. t.timeScale = 100000;
  234209. t.flags = 0;
  234210. [theMovie setCurrentTime: t];
  234211. }
  234212. }
  234213. double QuickTimeMovieComponent::getPosition() const
  234214. {
  234215. if (movie == 0)
  234216. return 0.0;
  234217. QTTime t = [theMovie currentTime];
  234218. return t.timeValue / (double) t.timeScale;
  234219. }
  234220. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  234221. {
  234222. [theMovie setRate: newSpeed];
  234223. }
  234224. double QuickTimeMovieComponent::getMovieDuration() const
  234225. {
  234226. if (movie == 0)
  234227. return 0.0;
  234228. QTTime t = [theMovie duration];
  234229. return t.timeValue / (double) t.timeScale;
  234230. }
  234231. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  234232. {
  234233. looping = shouldLoop;
  234234. [theMovie setAttribute: [NSNumber numberWithBool: shouldLoop]
  234235. forKey: QTMovieLoopsAttribute];
  234236. }
  234237. bool QuickTimeMovieComponent::isLooping() const
  234238. {
  234239. return looping;
  234240. }
  234241. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  234242. {
  234243. [theMovie setVolume: newVolume];
  234244. }
  234245. float QuickTimeMovieComponent::getMovieVolume() const
  234246. {
  234247. return movie != 0 ? [theMovie volume] : 0.0f;
  234248. }
  234249. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  234250. {
  234251. width = 0;
  234252. height = 0;
  234253. if (movie != 0)
  234254. {
  234255. NSSize s = [[theMovie attributeForKey: QTMovieNaturalSizeAttribute] sizeValue];
  234256. width = (int) s.width;
  234257. height = (int) s.height;
  234258. }
  234259. }
  234260. void QuickTimeMovieComponent::paint (Graphics& g)
  234261. {
  234262. if (movie == 0)
  234263. g.fillAll (Colours::black);
  234264. }
  234265. bool QuickTimeMovieComponent::isControllerVisible() const
  234266. {
  234267. return controllerVisible;
  234268. }
  234269. void QuickTimeMovieComponent::goToStart()
  234270. {
  234271. setPosition (0.0);
  234272. }
  234273. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  234274. const RectanglePlacement& placement)
  234275. {
  234276. int normalWidth, normalHeight;
  234277. getMovieNormalSize (normalWidth, normalHeight);
  234278. if (normalWidth > 0 && normalHeight > 0 && ! spaceToFitWithin.isEmpty())
  234279. {
  234280. double x = 0.0, y = 0.0, w = normalWidth, h = normalHeight;
  234281. placement.applyTo (x, y, w, h,
  234282. spaceToFitWithin.getX(), spaceToFitWithin.getY(),
  234283. spaceToFitWithin.getWidth(), spaceToFitWithin.getHeight());
  234284. if (w > 0 && h > 0)
  234285. {
  234286. setBounds (roundToInt (x), roundToInt (y),
  234287. roundToInt (w), roundToInt (h));
  234288. }
  234289. }
  234290. else
  234291. {
  234292. setBounds (spaceToFitWithin);
  234293. }
  234294. }
  234295. #if ! (JUCE_MAC && JUCE_64BIT)
  234296. bool juce_OpenQuickTimeMovieFromStream (InputStream* movieStream, Movie& result, Handle& dataHandle)
  234297. {
  234298. if (movieStream == 0)
  234299. return false;
  234300. File file;
  234301. QTMovie* movie = openMovieFromStream (movieStream, file);
  234302. if (movie != nil)
  234303. result = [movie quickTimeMovie];
  234304. return movie != nil;
  234305. }
  234306. #endif
  234307. #endif
  234308. /*** End of inlined file: juce_mac_QuickTimeMovieComponent.mm ***/
  234309. /*** Start of inlined file: juce_mac_AudioCDBurner.mm ***/
  234310. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234311. // compiled on its own).
  234312. #if JUCE_INCLUDED_FILE && JUCE_USE_CDBURNER
  234313. const int kilobytesPerSecond1x = 176;
  234314. END_JUCE_NAMESPACE
  234315. #define OpenDiskDevice MakeObjCClassName(OpenDiskDevice)
  234316. @interface OpenDiskDevice : NSObject
  234317. {
  234318. @public
  234319. DRDevice* device;
  234320. NSMutableArray* tracks;
  234321. bool underrunProtection;
  234322. }
  234323. - (OpenDiskDevice*) initWithDRDevice: (DRDevice*) device;
  234324. - (void) dealloc;
  234325. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) numSamples_;
  234326. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  234327. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting speed: (int) burnSpeed;
  234328. @end
  234329. #define AudioTrackProducer MakeObjCClassName(AudioTrackProducer)
  234330. @interface AudioTrackProducer : NSObject
  234331. {
  234332. JUCE_NAMESPACE::AudioSource* source;
  234333. int readPosition, lengthInFrames;
  234334. }
  234335. - (AudioTrackProducer*) init: (int) lengthInFrames;
  234336. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) lengthInSamples;
  234337. - (void) dealloc;
  234338. - (void) setupTrackProperties: (DRTrack*) track;
  234339. - (void) cleanupTrackAfterBurn: (DRTrack*) track;
  234340. - (BOOL) cleanupTrackAfterVerification:(DRTrack*)track;
  234341. - (uint64_t) estimateLengthOfTrack:(DRTrack*)track;
  234342. - (BOOL) prepareTrack:(DRTrack*)track forBurn:(DRBurn*)burn
  234343. toMedia:(NSDictionary*)mediaInfo;
  234344. - (BOOL) prepareTrackForVerification:(DRTrack*)track;
  234345. - (uint32_t) produceDataForTrack:(DRTrack*)track intoBuffer:(char*)buffer
  234346. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  234347. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  234348. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  234349. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  234350. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  234351. ioFlags:(uint32_t*)flags;
  234352. - (BOOL) verifyDataForTrack:(DRTrack*)track inBuffer:(const char*)buffer
  234353. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  234354. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  234355. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  234356. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  234357. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  234358. ioFlags:(uint32_t*)flags;
  234359. @end
  234360. @implementation OpenDiskDevice
  234361. - (OpenDiskDevice*) initWithDRDevice: (DRDevice*) device_
  234362. {
  234363. [super init];
  234364. device = device_;
  234365. tracks = [[NSMutableArray alloc] init];
  234366. underrunProtection = true;
  234367. return self;
  234368. }
  234369. - (void) dealloc
  234370. {
  234371. [tracks release];
  234372. [super dealloc];
  234373. }
  234374. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) numSamples_
  234375. {
  234376. AudioTrackProducer* p = [[AudioTrackProducer alloc] initWithAudioSource: source_ numSamples: numSamples_];
  234377. DRTrack* t = [[DRTrack alloc] initWithProducer: p];
  234378. [p setupTrackProperties: t];
  234379. [tracks addObject: t];
  234380. [t release];
  234381. [p release];
  234382. }
  234383. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  234384. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting speed: (int) burnSpeed
  234385. {
  234386. DRBurn* burn = [DRBurn burnForDevice: device];
  234387. if (! [device acquireExclusiveAccess])
  234388. {
  234389. *error = "Couldn't open or write to the CD device";
  234390. return;
  234391. }
  234392. [device acquireMediaReservation];
  234393. NSMutableDictionary* d = [[burn properties] mutableCopy];
  234394. [d autorelease];
  234395. [d setObject: [NSNumber numberWithBool: peformFakeBurnForTesting] forKey: DRBurnTestingKey];
  234396. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnVerifyDiscKey];
  234397. [d setObject: (shouldEject ? DRBurnCompletionActionEject : DRBurnCompletionActionMount) forKey: DRBurnCompletionActionKey];
  234398. if (burnSpeed > 0)
  234399. [d setObject: [NSNumber numberWithFloat: burnSpeed * JUCE_NAMESPACE::kilobytesPerSecond1x] forKey: DRBurnRequestedSpeedKey];
  234400. if (! underrunProtection)
  234401. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnUnderrunProtectionKey];
  234402. [burn setProperties: d];
  234403. [burn writeLayout: tracks];
  234404. for (;;)
  234405. {
  234406. JUCE_NAMESPACE::Thread::sleep (300);
  234407. float progress = [[[burn status] objectForKey: DRStatusPercentCompleteKey] floatValue];
  234408. if (listener != 0 && listener->audioCDBurnProgress (progress))
  234409. {
  234410. [burn abort];
  234411. *error = "User cancelled the write operation";
  234412. break;
  234413. }
  234414. if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateFailed])
  234415. {
  234416. *error = "Write operation failed";
  234417. break;
  234418. }
  234419. else if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateDone])
  234420. {
  234421. break;
  234422. }
  234423. NSString* err = (NSString*) [[[burn status] objectForKey: DRErrorStatusKey]
  234424. objectForKey: DRErrorStatusErrorStringKey];
  234425. if ([err length] > 0)
  234426. {
  234427. *error = JUCE_NAMESPACE::String::fromUTF8 ([err UTF8String]);
  234428. break;
  234429. }
  234430. }
  234431. [device releaseMediaReservation];
  234432. [device releaseExclusiveAccess];
  234433. }
  234434. @end
  234435. @implementation AudioTrackProducer
  234436. - (AudioTrackProducer*) init: (int) lengthInFrames_
  234437. {
  234438. lengthInFrames = lengthInFrames_;
  234439. readPosition = 0;
  234440. return self;
  234441. }
  234442. - (void) setupTrackProperties: (DRTrack*) track
  234443. {
  234444. NSMutableDictionary* p = [[track properties] mutableCopy];
  234445. [p setObject:[DRMSF msfWithFrames: lengthInFrames] forKey: DRTrackLengthKey];
  234446. [p setObject:[NSNumber numberWithUnsignedShort:2352] forKey: DRBlockSizeKey];
  234447. [p setObject:[NSNumber numberWithInt:0] forKey: DRDataFormKey];
  234448. [p setObject:[NSNumber numberWithInt:0] forKey: DRBlockTypeKey];
  234449. [p setObject:[NSNumber numberWithInt:0] forKey: DRTrackModeKey];
  234450. [p setObject:[NSNumber numberWithInt:0] forKey: DRSessionFormatKey];
  234451. [track setProperties: p];
  234452. [p release];
  234453. }
  234454. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) lengthInSamples
  234455. {
  234456. AudioTrackProducer* s = [self init: (lengthInSamples + 587) / 588];
  234457. if (s != nil)
  234458. s->source = source_;
  234459. return s;
  234460. }
  234461. - (void) dealloc
  234462. {
  234463. if (source != 0)
  234464. {
  234465. source->releaseResources();
  234466. delete source;
  234467. }
  234468. [super dealloc];
  234469. }
  234470. - (void) cleanupTrackAfterBurn: (DRTrack*) track
  234471. {
  234472. }
  234473. - (BOOL) cleanupTrackAfterVerification: (DRTrack*) track
  234474. {
  234475. return true;
  234476. }
  234477. - (uint64_t) estimateLengthOfTrack: (DRTrack*) track
  234478. {
  234479. return lengthInFrames;
  234480. }
  234481. - (BOOL) prepareTrack: (DRTrack*) track forBurn: (DRBurn*) burn
  234482. toMedia: (NSDictionary*) mediaInfo
  234483. {
  234484. if (source != 0)
  234485. source->prepareToPlay (44100 / 75, 44100);
  234486. readPosition = 0;
  234487. return true;
  234488. }
  234489. - (BOOL) prepareTrackForVerification: (DRTrack*) track
  234490. {
  234491. if (source != 0)
  234492. source->prepareToPlay (44100 / 75, 44100);
  234493. return true;
  234494. }
  234495. - (uint32_t) produceDataForTrack: (DRTrack*) track intoBuffer: (char*) buffer
  234496. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  234497. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  234498. {
  234499. if (source != 0)
  234500. {
  234501. const int numSamples = JUCE_NAMESPACE::jmin ((int) bufferLength / 4, (lengthInFrames * (44100 / 75)) - readPosition);
  234502. if (numSamples > 0)
  234503. {
  234504. JUCE_NAMESPACE::AudioSampleBuffer tempBuffer (2, numSamples);
  234505. JUCE_NAMESPACE::AudioSourceChannelInfo info;
  234506. info.buffer = &tempBuffer;
  234507. info.startSample = 0;
  234508. info.numSamples = numSamples;
  234509. source->getNextAudioBlock (info);
  234510. typedef JUCE_NAMESPACE::AudioData::Pointer <JUCE_NAMESPACE::AudioData::Int16,
  234511. JUCE_NAMESPACE::AudioData::LittleEndian,
  234512. JUCE_NAMESPACE::AudioData::Interleaved,
  234513. JUCE_NAMESPACE::AudioData::NonConst> CDSampleFormat;
  234514. typedef JUCE_NAMESPACE::AudioData::Pointer <JUCE_NAMESPACE::AudioData::Float32,
  234515. JUCE_NAMESPACE::AudioData::NativeEndian,
  234516. JUCE_NAMESPACE::AudioData::NonInterleaved,
  234517. JUCE_NAMESPACE::AudioData::Const> SourceSampleFormat;
  234518. CDSampleFormat left (buffer, 2);
  234519. left.convertSamples (SourceSampleFormat (tempBuffer.getSampleData (0)), numSamples);
  234520. CDSampleFormat right (buffer + 2, 2);
  234521. right.convertSamples (SourceSampleFormat (tempBuffer.getSampleData (1)), numSamples);
  234522. readPosition += numSamples;
  234523. }
  234524. return numSamples * 4;
  234525. }
  234526. return 0;
  234527. }
  234528. - (uint32_t) producePreGapForTrack: (DRTrack*) track
  234529. intoBuffer: (char*) buffer length: (uint32_t) bufferLength
  234530. atAddress: (uint64_t) address blockSize: (uint32_t) blockSize
  234531. ioFlags: (uint32_t*) flags
  234532. {
  234533. zeromem (buffer, bufferLength);
  234534. return bufferLength;
  234535. }
  234536. - (BOOL) verifyDataForTrack: (DRTrack*) track inBuffer: (const char*) buffer
  234537. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  234538. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  234539. {
  234540. return true;
  234541. }
  234542. @end
  234543. BEGIN_JUCE_NAMESPACE
  234544. class AudioCDBurner::Pimpl : public Timer
  234545. {
  234546. public:
  234547. Pimpl (AudioCDBurner& owner_, const int deviceIndex)
  234548. : device (0), owner (owner_)
  234549. {
  234550. DRDevice* dev = [[DRDevice devices] objectAtIndex: deviceIndex];
  234551. if (dev != 0)
  234552. {
  234553. device = [[OpenDiskDevice alloc] initWithDRDevice: dev];
  234554. lastState = getDiskState();
  234555. startTimer (1000);
  234556. }
  234557. }
  234558. ~Pimpl()
  234559. {
  234560. stopTimer();
  234561. [device release];
  234562. }
  234563. void timerCallback()
  234564. {
  234565. const DiskState state = getDiskState();
  234566. if (state != lastState)
  234567. {
  234568. lastState = state;
  234569. owner.sendChangeMessage (&owner);
  234570. }
  234571. }
  234572. DiskState getDiskState() const
  234573. {
  234574. if ([device->device isValid])
  234575. {
  234576. NSDictionary* status = [device->device status];
  234577. NSString* state = [status objectForKey: DRDeviceMediaStateKey];
  234578. if ([state isEqualTo: DRDeviceMediaStateNone])
  234579. {
  234580. if ([[status objectForKey: DRDeviceIsTrayOpenKey] boolValue])
  234581. return trayOpen;
  234582. return noDisc;
  234583. }
  234584. if ([state isEqualTo: DRDeviceMediaStateMediaPresent])
  234585. {
  234586. if ([[[status objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceMediaBlocksFreeKey] intValue] > 0)
  234587. return writableDiskPresent;
  234588. else
  234589. return readOnlyDiskPresent;
  234590. }
  234591. }
  234592. return unknown;
  234593. }
  234594. bool openTray() { return [device->device isValid] && [device->device ejectMedia]; }
  234595. const Array<int> getAvailableWriteSpeeds() const
  234596. {
  234597. Array<int> results;
  234598. if ([device->device isValid])
  234599. {
  234600. NSArray* speeds = [[[device->device status] objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceBurnSpeedsKey];
  234601. for (unsigned int i = 0; i < [speeds count]; ++i)
  234602. {
  234603. const int kbPerSec = [[speeds objectAtIndex: i] intValue];
  234604. results.add (kbPerSec / kilobytesPerSecond1x);
  234605. }
  234606. }
  234607. return results;
  234608. }
  234609. bool setBufferUnderrunProtection (const bool shouldBeEnabled)
  234610. {
  234611. if ([device->device isValid])
  234612. {
  234613. device->underrunProtection = shouldBeEnabled;
  234614. return shouldBeEnabled && [[[device->device status] objectForKey: DRDeviceCanUnderrunProtectCDKey] boolValue];
  234615. }
  234616. return false;
  234617. }
  234618. int getNumAvailableAudioBlocks() const
  234619. {
  234620. return [[[[device->device status] objectForKey: DRDeviceMediaInfoKey]
  234621. objectForKey: DRDeviceMediaBlocksFreeKey] intValue];
  234622. }
  234623. OpenDiskDevice* device;
  234624. private:
  234625. DiskState lastState;
  234626. AudioCDBurner& owner;
  234627. };
  234628. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  234629. {
  234630. pimpl = new Pimpl (*this, deviceIndex);
  234631. }
  234632. AudioCDBurner::~AudioCDBurner()
  234633. {
  234634. }
  234635. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  234636. {
  234637. ScopedPointer <AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  234638. if (b->pimpl->device == 0)
  234639. b = 0;
  234640. return b.release();
  234641. }
  234642. namespace
  234643. {
  234644. NSArray* findDiskBurnerDevices()
  234645. {
  234646. NSMutableArray* results = [NSMutableArray array];
  234647. NSArray* devs = [DRDevice devices];
  234648. for (int i = 0; i < [devs count]; ++i)
  234649. {
  234650. NSDictionary* dic = [[devs objectAtIndex: i] info];
  234651. NSString* name = [dic valueForKey: DRDeviceProductNameKey];
  234652. if (name != nil)
  234653. [results addObject: name];
  234654. }
  234655. return results;
  234656. }
  234657. }
  234658. const StringArray AudioCDBurner::findAvailableDevices()
  234659. {
  234660. NSArray* names = findDiskBurnerDevices();
  234661. StringArray s;
  234662. for (unsigned int i = 0; i < [names count]; ++i)
  234663. s.add (String::fromUTF8 ([[names objectAtIndex: i] UTF8String]));
  234664. return s;
  234665. }
  234666. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  234667. {
  234668. return pimpl->getDiskState();
  234669. }
  234670. bool AudioCDBurner::isDiskPresent() const
  234671. {
  234672. return getDiskState() == writableDiskPresent;
  234673. }
  234674. bool AudioCDBurner::openTray()
  234675. {
  234676. return pimpl->openTray();
  234677. }
  234678. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  234679. {
  234680. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  234681. DiskState oldState = getDiskState();
  234682. DiskState newState = oldState;
  234683. while (newState == oldState && Time::currentTimeMillis() < timeout)
  234684. {
  234685. newState = getDiskState();
  234686. Thread::sleep (100);
  234687. }
  234688. return newState;
  234689. }
  234690. const Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  234691. {
  234692. return pimpl->getAvailableWriteSpeeds();
  234693. }
  234694. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  234695. {
  234696. return pimpl->setBufferUnderrunProtection (shouldBeEnabled);
  234697. }
  234698. int AudioCDBurner::getNumAvailableAudioBlocks() const
  234699. {
  234700. return pimpl->getNumAvailableAudioBlocks();
  234701. }
  234702. bool AudioCDBurner::addAudioTrack (AudioSource* source, int numSamps)
  234703. {
  234704. if ([pimpl->device->device isValid])
  234705. {
  234706. [pimpl->device addSourceTrack: source numSamples: numSamps];
  234707. return true;
  234708. }
  234709. return false;
  234710. }
  234711. const String AudioCDBurner::burn (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener* listener,
  234712. bool ejectDiscAfterwards,
  234713. bool performFakeBurnForTesting,
  234714. int writeSpeed)
  234715. {
  234716. String error ("Couldn't open or write to the CD device");
  234717. if ([pimpl->device->device isValid])
  234718. {
  234719. error = String::empty;
  234720. [pimpl->device burn: listener
  234721. errorString: &error
  234722. ejectAfterwards: ejectDiscAfterwards
  234723. isFake: performFakeBurnForTesting
  234724. speed: writeSpeed];
  234725. }
  234726. return error;
  234727. }
  234728. #endif
  234729. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  234730. void AudioCDReader::ejectDisk()
  234731. {
  234732. const ScopedAutoReleasePool p;
  234733. [[NSWorkspace sharedWorkspace] unmountAndEjectDeviceAtPath: juceStringToNS (volumeDir.getFullPathName())];
  234734. }
  234735. #endif
  234736. /*** End of inlined file: juce_mac_AudioCDBurner.mm ***/
  234737. /*** Start of inlined file: juce_mac_AudioCDReader.mm ***/
  234738. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234739. // compiled on its own).
  234740. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  234741. namespace CDReaderHelpers
  234742. {
  234743. inline const XmlElement* getElementForKey (const XmlElement& xml, const String& key)
  234744. {
  234745. forEachXmlChildElementWithTagName (xml, child, "key")
  234746. if (child->getAllSubText().trim() == key)
  234747. return child->getNextElement();
  234748. return 0;
  234749. }
  234750. static int getIntValueForKey (const XmlElement& xml, const String& key, int defaultValue = -1)
  234751. {
  234752. const XmlElement* const block = getElementForKey (xml, key);
  234753. return block != 0 ? block->getAllSubText().trim().getIntValue() : defaultValue;
  234754. }
  234755. // Get the track offsets for a CD given an XmlElement representing its TOC.Plist.
  234756. // Returns NULL on success, otherwise a const char* representing an error.
  234757. static const char* getTrackOffsets (XmlDocument& xmlDocument, Array<int>& offsets)
  234758. {
  234759. const ScopedPointer<XmlElement> xml (xmlDocument.getDocumentElement());
  234760. if (xml == 0)
  234761. return "Couldn't parse XML in file";
  234762. const XmlElement* const dict = xml->getChildByName ("dict");
  234763. if (dict == 0)
  234764. return "Couldn't get top level dictionary";
  234765. const XmlElement* const sessions = getElementForKey (*dict, "Sessions");
  234766. if (sessions == 0)
  234767. return "Couldn't find sessions key";
  234768. const XmlElement* const session = sessions->getFirstChildElement();
  234769. if (session == 0)
  234770. return "Couldn't find first session";
  234771. const int leadOut = getIntValueForKey (*session, "Leadout Block");
  234772. if (leadOut < 0)
  234773. return "Couldn't find Leadout Block";
  234774. const XmlElement* const trackArray = getElementForKey (*session, "Track Array");
  234775. if (trackArray == 0)
  234776. return "Couldn't find Track Array";
  234777. forEachXmlChildElement (*trackArray, track)
  234778. {
  234779. const int trackValue = getIntValueForKey (*track, "Start Block");
  234780. if (trackValue < 0)
  234781. return "Couldn't find Start Block in the track";
  234782. offsets.add (trackValue * AudioCDReader::samplesPerFrame - 88200);
  234783. }
  234784. offsets.add (leadOut * AudioCDReader::samplesPerFrame - 88200);
  234785. return 0;
  234786. }
  234787. static void findDevices (Array<File>& cds)
  234788. {
  234789. File volumes ("/Volumes");
  234790. volumes.findChildFiles (cds, File::findDirectories, false);
  234791. for (int i = cds.size(); --i >= 0;)
  234792. if (! cds.getReference(i).getChildFile (".TOC.plist").exists())
  234793. cds.remove (i);
  234794. }
  234795. struct TrackSorter
  234796. {
  234797. static int getCDTrackNumber (const File& file)
  234798. {
  234799. return file.getFileName().initialSectionContainingOnly ("0123456789").getIntValue();
  234800. }
  234801. static int compareElements (const File& first, const File& second)
  234802. {
  234803. const int firstTrack = getCDTrackNumber (first);
  234804. const int secondTrack = getCDTrackNumber (second);
  234805. jassert (firstTrack > 0 && secondTrack > 0);
  234806. return firstTrack - secondTrack;
  234807. }
  234808. };
  234809. }
  234810. const StringArray AudioCDReader::getAvailableCDNames()
  234811. {
  234812. Array<File> cds;
  234813. CDReaderHelpers::findDevices (cds);
  234814. StringArray names;
  234815. for (int i = 0; i < cds.size(); ++i)
  234816. names.add (cds.getReference(i).getFileName());
  234817. return names;
  234818. }
  234819. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  234820. {
  234821. Array<File> cds;
  234822. CDReaderHelpers::findDevices (cds);
  234823. if (cds[index].exists())
  234824. return new AudioCDReader (cds[index]);
  234825. return 0;
  234826. }
  234827. AudioCDReader::AudioCDReader (const File& volume)
  234828. : AudioFormatReader (0, "CD Audio"),
  234829. volumeDir (volume),
  234830. currentReaderTrack (-1),
  234831. reader (0)
  234832. {
  234833. sampleRate = 44100.0;
  234834. bitsPerSample = 16;
  234835. numChannels = 2;
  234836. usesFloatingPointData = false;
  234837. refreshTrackLengths();
  234838. }
  234839. AudioCDReader::~AudioCDReader()
  234840. {
  234841. }
  234842. void AudioCDReader::refreshTrackLengths()
  234843. {
  234844. tracks.clear();
  234845. trackStartSamples.clear();
  234846. lengthInSamples = 0;
  234847. volumeDir.findChildFiles (tracks, File::findFiles | File::ignoreHiddenFiles, false, "*.aiff");
  234848. CDReaderHelpers::TrackSorter sorter;
  234849. tracks.sort (sorter);
  234850. const File toc (volumeDir.getChildFile (".TOC.plist"));
  234851. if (toc.exists())
  234852. {
  234853. XmlDocument doc (toc);
  234854. const char* error = CDReaderHelpers::getTrackOffsets (doc, trackStartSamples);
  234855. (void) error; // could be logged..
  234856. lengthInSamples = trackStartSamples.getLast() - trackStartSamples.getFirst();
  234857. }
  234858. }
  234859. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  234860. int64 startSampleInFile, int numSamples)
  234861. {
  234862. while (numSamples > 0)
  234863. {
  234864. int track = -1;
  234865. for (int i = 0; i < trackStartSamples.size() - 1; ++i)
  234866. {
  234867. if (startSampleInFile < trackStartSamples.getUnchecked (i + 1))
  234868. {
  234869. track = i;
  234870. break;
  234871. }
  234872. }
  234873. if (track < 0)
  234874. return false;
  234875. if (track != currentReaderTrack)
  234876. {
  234877. reader = 0;
  234878. FileInputStream* const in = tracks [track].createInputStream();
  234879. if (in != 0)
  234880. {
  234881. BufferedInputStream* const bin = new BufferedInputStream (in, 65536, true);
  234882. AiffAudioFormat format;
  234883. reader = format.createReaderFor (bin, true);
  234884. if (reader == 0)
  234885. currentReaderTrack = -1;
  234886. else
  234887. currentReaderTrack = track;
  234888. }
  234889. }
  234890. if (reader == 0)
  234891. return false;
  234892. const int startPos = (int) (startSampleInFile - trackStartSamples.getUnchecked (track));
  234893. const int numAvailable = (int) jmin ((int64) numSamples, reader->lengthInSamples - startPos);
  234894. reader->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer, startPos, numAvailable);
  234895. numSamples -= numAvailable;
  234896. startSampleInFile += numAvailable;
  234897. }
  234898. return true;
  234899. }
  234900. bool AudioCDReader::isCDStillPresent() const
  234901. {
  234902. return volumeDir.exists();
  234903. }
  234904. bool AudioCDReader::isTrackAudio (int trackNum) const
  234905. {
  234906. return tracks [trackNum].hasFileExtension (".aiff");
  234907. }
  234908. void AudioCDReader::enableIndexScanning (bool b)
  234909. {
  234910. // any way to do this on a Mac??
  234911. }
  234912. int AudioCDReader::getLastIndex() const
  234913. {
  234914. return 0;
  234915. }
  234916. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  234917. {
  234918. return Array <int>();
  234919. }
  234920. #endif
  234921. /*** End of inlined file: juce_mac_AudioCDReader.mm ***/
  234922. /*** Start of inlined file: juce_mac_MessageManager.mm ***/
  234923. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234924. // compiled on its own).
  234925. #if JUCE_INCLUDED_FILE
  234926. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  234927. for example having more than one juce plugin loaded into a host, then when a
  234928. method is called, the actual code that runs might actually be in a different module
  234929. than the one you expect... So any calls to library functions or statics that are
  234930. made inside obj-c methods will probably end up getting executed in a different DLL's
  234931. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  234932. To work around this insanity, I'm only allowing obj-c methods to make calls to
  234933. virtual methods of an object that's known to live inside the right module's space.
  234934. */
  234935. class AppDelegateRedirector
  234936. {
  234937. public:
  234938. AppDelegateRedirector()
  234939. {
  234940. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_4
  234941. runLoop = CFRunLoopGetMain();
  234942. #else
  234943. runLoop = CFRunLoopGetCurrent();
  234944. #endif
  234945. CFRunLoopSourceContext sourceContext;
  234946. zerostruct (sourceContext);
  234947. sourceContext.info = this;
  234948. sourceContext.perform = runLoopSourceCallback;
  234949. runLoopSource = CFRunLoopSourceCreate (kCFAllocatorDefault, 1, &sourceContext);
  234950. CFRunLoopAddSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  234951. }
  234952. virtual ~AppDelegateRedirector()
  234953. {
  234954. CFRunLoopRemoveSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  234955. CFRunLoopSourceInvalidate (runLoopSource);
  234956. CFRelease (runLoopSource);
  234957. }
  234958. virtual NSApplicationTerminateReply shouldTerminate()
  234959. {
  234960. if (JUCEApplication::getInstance() != 0)
  234961. {
  234962. JUCEApplication::getInstance()->systemRequestedQuit();
  234963. if (! MessageManager::getInstance()->hasStopMessageBeenSent())
  234964. return NSTerminateCancel;
  234965. }
  234966. return NSTerminateNow;
  234967. }
  234968. virtual void willTerminate()
  234969. {
  234970. JUCEApplication::appWillTerminateByForce();
  234971. }
  234972. virtual BOOL openFile (NSString* filename)
  234973. {
  234974. if (JUCEApplication::getInstance() != 0)
  234975. {
  234976. JUCEApplication::getInstance()->anotherInstanceStarted (nsStringToJuce (filename));
  234977. return YES;
  234978. }
  234979. return NO;
  234980. }
  234981. virtual void openFiles (NSArray* filenames)
  234982. {
  234983. StringArray files;
  234984. for (unsigned int i = 0; i < [filenames count]; ++i)
  234985. {
  234986. String filename (nsStringToJuce ((NSString*) [filenames objectAtIndex: i]));
  234987. if (filename.containsChar (' '))
  234988. filename = filename.quoted('"');
  234989. files.add (filename);
  234990. }
  234991. if (files.size() > 0 && JUCEApplication::getInstance() != 0)
  234992. {
  234993. JUCEApplication::getInstance()->anotherInstanceStarted (files.joinIntoString (" "));
  234994. }
  234995. }
  234996. virtual void focusChanged()
  234997. {
  234998. juce_HandleProcessFocusChange();
  234999. }
  235000. struct CallbackMessagePayload
  235001. {
  235002. MessageCallbackFunction* function;
  235003. void* parameter;
  235004. void* volatile result;
  235005. bool volatile hasBeenExecuted;
  235006. };
  235007. virtual void performCallback (CallbackMessagePayload* pl)
  235008. {
  235009. pl->result = (*pl->function) (pl->parameter);
  235010. pl->hasBeenExecuted = true;
  235011. }
  235012. virtual void deleteSelf()
  235013. {
  235014. delete this;
  235015. }
  235016. void postMessage (Message* const m)
  235017. {
  235018. messages.add (m);
  235019. CFRunLoopSourceSignal (runLoopSource);
  235020. CFRunLoopWakeUp (runLoop);
  235021. }
  235022. private:
  235023. CFRunLoopRef runLoop;
  235024. CFRunLoopSourceRef runLoopSource;
  235025. OwnedArray <Message, CriticalSection> messages;
  235026. void runLoopCallback()
  235027. {
  235028. int numDispatched = 0;
  235029. do
  235030. {
  235031. Message* const nextMessage = messages.removeAndReturn (0);
  235032. if (nextMessage == 0)
  235033. return;
  235034. const ScopedAutoReleasePool pool;
  235035. MessageManager::getInstance()->deliverMessage (nextMessage);
  235036. } while (++numDispatched <= 4);
  235037. CFRunLoopSourceSignal (runLoopSource);
  235038. CFRunLoopWakeUp (runLoop);
  235039. }
  235040. static void runLoopSourceCallback (void* info)
  235041. {
  235042. static_cast <AppDelegateRedirector*> (info)->runLoopCallback();
  235043. }
  235044. };
  235045. END_JUCE_NAMESPACE
  235046. using namespace JUCE_NAMESPACE;
  235047. #define JuceAppDelegate MakeObjCClassName(JuceAppDelegate)
  235048. @interface JuceAppDelegate : NSObject
  235049. {
  235050. @private
  235051. id oldDelegate;
  235052. @public
  235053. AppDelegateRedirector* redirector;
  235054. }
  235055. - (JuceAppDelegate*) init;
  235056. - (void) dealloc;
  235057. - (BOOL) application: (NSApplication*) theApplication openFile: (NSString*) filename;
  235058. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames;
  235059. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app;
  235060. - (void) applicationWillTerminate: (NSNotification*) aNotification;
  235061. - (void) applicationDidBecomeActive: (NSNotification*) aNotification;
  235062. - (void) applicationDidResignActive: (NSNotification*) aNotification;
  235063. - (void) applicationWillUnhide: (NSNotification*) aNotification;
  235064. - (void) performCallback: (id) info;
  235065. - (void) dummyMethod;
  235066. @end
  235067. @implementation JuceAppDelegate
  235068. - (JuceAppDelegate*) init
  235069. {
  235070. [super init];
  235071. redirector = new AppDelegateRedirector();
  235072. NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
  235073. if (JUCEApplication::isStandaloneApp())
  235074. {
  235075. oldDelegate = [NSApp delegate];
  235076. [NSApp setDelegate: self];
  235077. }
  235078. else
  235079. {
  235080. oldDelegate = 0;
  235081. [center addObserver: self selector: @selector (applicationDidResignActive:)
  235082. name: NSApplicationDidResignActiveNotification object: NSApp];
  235083. [center addObserver: self selector: @selector (applicationDidBecomeActive:)
  235084. name: NSApplicationDidBecomeActiveNotification object: NSApp];
  235085. [center addObserver: self selector: @selector (applicationWillUnhide:)
  235086. name: NSApplicationWillUnhideNotification object: NSApp];
  235087. }
  235088. return self;
  235089. }
  235090. - (void) dealloc
  235091. {
  235092. if (oldDelegate != 0)
  235093. [NSApp setDelegate: oldDelegate];
  235094. redirector->deleteSelf();
  235095. [super dealloc];
  235096. }
  235097. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app
  235098. {
  235099. (void) app;
  235100. return redirector->shouldTerminate();
  235101. }
  235102. - (void) applicationWillTerminate: (NSNotification*) aNotification
  235103. {
  235104. (void) aNotification;
  235105. redirector->willTerminate();
  235106. }
  235107. - (BOOL) application: (NSApplication*) app openFile: (NSString*) filename
  235108. {
  235109. (void) app;
  235110. return redirector->openFile (filename);
  235111. }
  235112. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames
  235113. {
  235114. (void) sender;
  235115. return redirector->openFiles (filenames);
  235116. }
  235117. - (void) applicationDidBecomeActive: (NSNotification*) notification
  235118. {
  235119. (void) notification;
  235120. redirector->focusChanged();
  235121. }
  235122. - (void) applicationDidResignActive: (NSNotification*) notification
  235123. {
  235124. (void) notification;
  235125. redirector->focusChanged();
  235126. }
  235127. - (void) applicationWillUnhide: (NSNotification*) notification
  235128. {
  235129. (void) notification;
  235130. redirector->focusChanged();
  235131. }
  235132. - (void) performCallback: (id) info
  235133. {
  235134. if ([info isKindOfClass: [NSData class]])
  235135. {
  235136. AppDelegateRedirector::CallbackMessagePayload* pl
  235137. = (AppDelegateRedirector::CallbackMessagePayload*) [((NSData*) info) bytes];
  235138. if (pl != 0)
  235139. redirector->performCallback (pl);
  235140. }
  235141. else
  235142. {
  235143. jassertfalse; // should never get here!
  235144. }
  235145. }
  235146. - (void) dummyMethod {} // (used as a way of running a dummy thread)
  235147. @end
  235148. BEGIN_JUCE_NAMESPACE
  235149. static JuceAppDelegate* juceAppDelegate = 0;
  235150. void MessageManager::runDispatchLoop()
  235151. {
  235152. if (! quitMessagePosted) // check that the quit message wasn't already posted..
  235153. {
  235154. const ScopedAutoReleasePool pool;
  235155. // must only be called by the message thread!
  235156. jassert (isThisTheMessageThread());
  235157. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  235158. @try
  235159. {
  235160. [NSApp run];
  235161. }
  235162. @catch (NSException* e)
  235163. {
  235164. // An AppKit exception will kill the app, but at least this provides a chance to log it.,
  235165. std::runtime_error ex (std::string ("NSException: ") + [[e name] UTF8String] + ", Reason:" + [[e reason] UTF8String]);
  235166. JUCEApplication::sendUnhandledException (&ex, __FILE__, __LINE__);
  235167. }
  235168. @finally
  235169. {
  235170. }
  235171. #else
  235172. [NSApp run];
  235173. #endif
  235174. }
  235175. }
  235176. void MessageManager::stopDispatchLoop()
  235177. {
  235178. quitMessagePosted = true;
  235179. [NSApp stop: nil];
  235180. [NSApp activateIgnoringOtherApps: YES]; // (if the app is inactive, it sits there and ignores the quit request until the next time it gets activated)
  235181. [NSEvent startPeriodicEventsAfterDelay: 0 withPeriod: 0.1];
  235182. }
  235183. namespace
  235184. {
  235185. bool isEventBlockedByModalComps (NSEvent* e)
  235186. {
  235187. if (Component::getNumCurrentlyModalComponents() == 0)
  235188. return false;
  235189. NSWindow* const w = [e window];
  235190. if (w == 0 || [w worksWhenModal])
  235191. return false;
  235192. bool isKey = false, isInputAttempt = false;
  235193. switch ([e type])
  235194. {
  235195. case NSKeyDown:
  235196. case NSKeyUp:
  235197. isKey = isInputAttempt = true;
  235198. break;
  235199. case NSLeftMouseDown:
  235200. case NSRightMouseDown:
  235201. case NSOtherMouseDown:
  235202. isInputAttempt = true;
  235203. break;
  235204. case NSLeftMouseDragged:
  235205. case NSRightMouseDragged:
  235206. case NSLeftMouseUp:
  235207. case NSRightMouseUp:
  235208. case NSOtherMouseUp:
  235209. case NSOtherMouseDragged:
  235210. if (Desktop::getInstance().getDraggingMouseSource(0) != 0)
  235211. return false;
  235212. break;
  235213. case NSMouseMoved:
  235214. case NSMouseEntered:
  235215. case NSMouseExited:
  235216. case NSCursorUpdate:
  235217. case NSScrollWheel:
  235218. case NSTabletPoint:
  235219. case NSTabletProximity:
  235220. break;
  235221. default:
  235222. return false;
  235223. }
  235224. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  235225. {
  235226. ComponentPeer* const peer = ComponentPeer::getPeer (i);
  235227. NSView* const compView = (NSView*) peer->getNativeHandle();
  235228. if ([compView window] == w)
  235229. {
  235230. if (isKey)
  235231. {
  235232. if (compView == [w firstResponder])
  235233. return false;
  235234. }
  235235. else
  235236. {
  235237. NSViewComponentPeer* nsViewPeer = dynamic_cast<NSViewComponentPeer*> (peer);
  235238. if ((nsViewPeer == 0 || ! nsViewPeer->isSharedWindow)
  235239. ? NSPointInRect ([e locationInWindow], NSMakeRect (0, 0, [w frame].size.width, [w frame].size.height))
  235240. : NSPointInRect ([compView convertPoint: [e locationInWindow] fromView: nil], [compView bounds]))
  235241. return false;
  235242. }
  235243. }
  235244. }
  235245. if (isInputAttempt)
  235246. {
  235247. if (! [NSApp isActive])
  235248. [NSApp activateIgnoringOtherApps: YES];
  235249. Component* const modal = Component::getCurrentlyModalComponent (0);
  235250. if (modal != 0)
  235251. modal->inputAttemptWhenModal();
  235252. }
  235253. return true;
  235254. }
  235255. }
  235256. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  235257. {
  235258. jassert (isThisTheMessageThread()); // must only be called by the message thread
  235259. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  235260. while (! quitMessagePosted)
  235261. {
  235262. const ScopedAutoReleasePool pool;
  235263. CFRunLoopRunInMode (kCFRunLoopDefaultMode, 0.001, true);
  235264. NSEvent* e = [NSApp nextEventMatchingMask: NSAnyEventMask
  235265. untilDate: [NSDate dateWithTimeIntervalSinceNow: 0.001]
  235266. inMode: NSDefaultRunLoopMode
  235267. dequeue: YES];
  235268. if (e != 0 && ! isEventBlockedByModalComps (e))
  235269. [NSApp sendEvent: e];
  235270. if (Time::getMillisecondCounter() >= endTime)
  235271. break;
  235272. }
  235273. return ! quitMessagePosted;
  235274. }
  235275. void MessageManager::doPlatformSpecificInitialisation()
  235276. {
  235277. if (juceAppDelegate == 0)
  235278. juceAppDelegate = [[JuceAppDelegate alloc] init];
  235279. // This launches a dummy thread, which forces Cocoa to initialise NSThreads
  235280. // correctly (needed prior to 10.5)
  235281. if (! [NSThread isMultiThreaded])
  235282. [NSThread detachNewThreadSelector: @selector (dummyMethod)
  235283. toTarget: juceAppDelegate
  235284. withObject: nil];
  235285. }
  235286. void MessageManager::doPlatformSpecificShutdown()
  235287. {
  235288. if (juceAppDelegate != 0)
  235289. {
  235290. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceAppDelegate];
  235291. [[NSNotificationCenter defaultCenter] removeObserver: juceAppDelegate];
  235292. [juceAppDelegate release];
  235293. juceAppDelegate = 0;
  235294. }
  235295. }
  235296. bool juce_postMessageToSystemQueue (Message* message)
  235297. {
  235298. juceAppDelegate->redirector->postMessage (message);
  235299. return true;
  235300. }
  235301. void MessageManager::broadcastMessage (const String& value)
  235302. {
  235303. }
  235304. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback, void* data)
  235305. {
  235306. if (isThisTheMessageThread())
  235307. {
  235308. return (*callback) (data);
  235309. }
  235310. else
  235311. {
  235312. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  235313. // deadlock because the message manager is blocked from running, so can never
  235314. // call your function..
  235315. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  235316. const ScopedAutoReleasePool pool;
  235317. AppDelegateRedirector::CallbackMessagePayload cmp;
  235318. cmp.function = callback;
  235319. cmp.parameter = data;
  235320. cmp.result = 0;
  235321. cmp.hasBeenExecuted = false;
  235322. [juceAppDelegate performSelectorOnMainThread: @selector (performCallback:)
  235323. withObject: [NSData dataWithBytesNoCopy: &cmp
  235324. length: sizeof (cmp)
  235325. freeWhenDone: NO]
  235326. waitUntilDone: YES];
  235327. return cmp.result;
  235328. }
  235329. }
  235330. #endif
  235331. /*** End of inlined file: juce_mac_MessageManager.mm ***/
  235332. /*** Start of inlined file: juce_mac_WebBrowserComponent.mm ***/
  235333. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  235334. // compiled on its own).
  235335. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  235336. #if JUCE_MAC
  235337. END_JUCE_NAMESPACE
  235338. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  235339. @interface DownloadClickDetector : NSObject
  235340. {
  235341. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  235342. }
  235343. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  235344. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  235345. request: (NSURLRequest*) request
  235346. frame: (WebFrame*) frame
  235347. decisionListener: (id<WebPolicyDecisionListener>) listener;
  235348. @end
  235349. @implementation DownloadClickDetector
  235350. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  235351. {
  235352. [super init];
  235353. ownerComponent = ownerComponent_;
  235354. return self;
  235355. }
  235356. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  235357. request: (NSURLRequest*) request
  235358. frame: (WebFrame*) frame
  235359. decisionListener: (id <WebPolicyDecisionListener>) listener
  235360. {
  235361. (void) sender;
  235362. (void) request;
  235363. (void) frame;
  235364. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  235365. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  235366. [listener use];
  235367. else
  235368. [listener ignore];
  235369. }
  235370. @end
  235371. BEGIN_JUCE_NAMESPACE
  235372. class WebBrowserComponentInternal : public NSViewComponent
  235373. {
  235374. public:
  235375. WebBrowserComponentInternal (WebBrowserComponent* owner)
  235376. {
  235377. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  235378. frameName: @""
  235379. groupName: @""];
  235380. setView (webView);
  235381. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  235382. [webView setPolicyDelegate: clickListener];
  235383. }
  235384. ~WebBrowserComponentInternal()
  235385. {
  235386. [webView setPolicyDelegate: nil];
  235387. [clickListener release];
  235388. setView (0);
  235389. }
  235390. void goToURL (const String& url,
  235391. const StringArray* headers,
  235392. const MemoryBlock* postData)
  235393. {
  235394. NSMutableURLRequest* r
  235395. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  235396. cachePolicy: NSURLRequestUseProtocolCachePolicy
  235397. timeoutInterval: 30.0];
  235398. if (postData != 0 && postData->getSize() > 0)
  235399. {
  235400. [r setHTTPMethod: @"POST"];
  235401. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  235402. length: postData->getSize()]];
  235403. }
  235404. if (headers != 0)
  235405. {
  235406. for (int i = 0; i < headers->size(); ++i)
  235407. {
  235408. const String headerName ((*headers)[i].upToFirstOccurrenceOf (":", false, false).trim());
  235409. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (":", false, false).trim());
  235410. [r setValue: juceStringToNS (headerValue)
  235411. forHTTPHeaderField: juceStringToNS (headerName)];
  235412. }
  235413. }
  235414. stop();
  235415. [[webView mainFrame] loadRequest: r];
  235416. }
  235417. void goBack()
  235418. {
  235419. [webView goBack];
  235420. }
  235421. void goForward()
  235422. {
  235423. [webView goForward];
  235424. }
  235425. void stop()
  235426. {
  235427. [webView stopLoading: nil];
  235428. }
  235429. void refresh()
  235430. {
  235431. [webView reload: nil];
  235432. }
  235433. private:
  235434. WebView* webView;
  235435. DownloadClickDetector* clickListener;
  235436. };
  235437. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  235438. : browser (0),
  235439. blankPageShown (false),
  235440. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  235441. {
  235442. setOpaque (true);
  235443. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  235444. }
  235445. WebBrowserComponent::~WebBrowserComponent()
  235446. {
  235447. deleteAndZero (browser);
  235448. }
  235449. void WebBrowserComponent::goToURL (const String& url,
  235450. const StringArray* headers,
  235451. const MemoryBlock* postData)
  235452. {
  235453. lastURL = url;
  235454. lastHeaders.clear();
  235455. if (headers != 0)
  235456. lastHeaders = *headers;
  235457. lastPostData.setSize (0);
  235458. if (postData != 0)
  235459. lastPostData = *postData;
  235460. blankPageShown = false;
  235461. browser->goToURL (url, headers, postData);
  235462. }
  235463. void WebBrowserComponent::stop()
  235464. {
  235465. browser->stop();
  235466. }
  235467. void WebBrowserComponent::goBack()
  235468. {
  235469. lastURL = String::empty;
  235470. blankPageShown = false;
  235471. browser->goBack();
  235472. }
  235473. void WebBrowserComponent::goForward()
  235474. {
  235475. lastURL = String::empty;
  235476. browser->goForward();
  235477. }
  235478. void WebBrowserComponent::refresh()
  235479. {
  235480. browser->refresh();
  235481. }
  235482. void WebBrowserComponent::paint (Graphics&)
  235483. {
  235484. }
  235485. void WebBrowserComponent::checkWindowAssociation()
  235486. {
  235487. if (isShowing())
  235488. {
  235489. if (blankPageShown)
  235490. goBack();
  235491. }
  235492. else
  235493. {
  235494. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  235495. {
  235496. // when the component becomes invisible, some stuff like flash
  235497. // carries on playing audio, so we need to force it onto a blank
  235498. // page to avoid this, (and send it back when it's made visible again).
  235499. blankPageShown = true;
  235500. browser->goToURL ("about:blank", 0, 0);
  235501. }
  235502. }
  235503. }
  235504. void WebBrowserComponent::reloadLastURL()
  235505. {
  235506. if (lastURL.isNotEmpty())
  235507. {
  235508. goToURL (lastURL, &lastHeaders, &lastPostData);
  235509. lastURL = String::empty;
  235510. }
  235511. }
  235512. void WebBrowserComponent::parentHierarchyChanged()
  235513. {
  235514. checkWindowAssociation();
  235515. }
  235516. void WebBrowserComponent::resized()
  235517. {
  235518. browser->setSize (getWidth(), getHeight());
  235519. }
  235520. void WebBrowserComponent::visibilityChanged()
  235521. {
  235522. checkWindowAssociation();
  235523. }
  235524. bool WebBrowserComponent::pageAboutToLoad (const String&)
  235525. {
  235526. return true;
  235527. }
  235528. #else
  235529. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  235530. {
  235531. }
  235532. WebBrowserComponent::~WebBrowserComponent()
  235533. {
  235534. }
  235535. void WebBrowserComponent::goToURL (const String& url,
  235536. const StringArray* headers,
  235537. const MemoryBlock* postData)
  235538. {
  235539. }
  235540. void WebBrowserComponent::stop()
  235541. {
  235542. }
  235543. void WebBrowserComponent::goBack()
  235544. {
  235545. }
  235546. void WebBrowserComponent::goForward()
  235547. {
  235548. }
  235549. void WebBrowserComponent::refresh()
  235550. {
  235551. }
  235552. void WebBrowserComponent::paint (Graphics& g)
  235553. {
  235554. }
  235555. void WebBrowserComponent::checkWindowAssociation()
  235556. {
  235557. }
  235558. void WebBrowserComponent::reloadLastURL()
  235559. {
  235560. }
  235561. void WebBrowserComponent::parentHierarchyChanged()
  235562. {
  235563. }
  235564. void WebBrowserComponent::resized()
  235565. {
  235566. }
  235567. void WebBrowserComponent::visibilityChanged()
  235568. {
  235569. }
  235570. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  235571. {
  235572. return true;
  235573. }
  235574. #endif
  235575. #endif
  235576. /*** End of inlined file: juce_mac_WebBrowserComponent.mm ***/
  235577. /*** Start of inlined file: juce_mac_CoreAudio.cpp ***/
  235578. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  235579. // compiled on its own).
  235580. #if JUCE_INCLUDED_FILE
  235581. #ifndef JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  235582. #define JUCE_COREAUDIO_ERROR_LOGGING_ENABLED 1
  235583. #endif
  235584. #undef log
  235585. #if JUCE_COREAUDIO_LOGGING_ENABLED
  235586. #define log(a) Logger::writeToLog (a)
  235587. #else
  235588. #define log(a)
  235589. #endif
  235590. #undef OK
  235591. #if JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  235592. static bool logAnyErrors_CoreAudio (const OSStatus err, const int lineNum)
  235593. {
  235594. if (err == noErr)
  235595. return true;
  235596. Logger::writeToLog ("CoreAudio error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  235597. jassertfalse;
  235598. return false;
  235599. }
  235600. #define OK(a) logAnyErrors_CoreAudio (a, __LINE__)
  235601. #else
  235602. #define OK(a) (a == noErr)
  235603. #endif
  235604. class CoreAudioInternal : public Timer
  235605. {
  235606. public:
  235607. CoreAudioInternal (AudioDeviceID id)
  235608. : inputLatency (0),
  235609. outputLatency (0),
  235610. callback (0),
  235611. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  235612. audioProcID (0),
  235613. #endif
  235614. isSlaveDevice (false),
  235615. deviceID (id),
  235616. started (false),
  235617. sampleRate (0),
  235618. bufferSize (512),
  235619. numInputChans (0),
  235620. numOutputChans (0),
  235621. callbacksAllowed (true),
  235622. numInputChannelInfos (0),
  235623. numOutputChannelInfos (0)
  235624. {
  235625. jassert (deviceID != 0);
  235626. updateDetailsFromDevice();
  235627. AudioObjectPropertyAddress pa;
  235628. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  235629. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235630. pa.mElement = kAudioObjectPropertyElementWildcard;
  235631. AudioObjectAddPropertyListener (deviceID, &pa, deviceListenerProc, this);
  235632. }
  235633. ~CoreAudioInternal()
  235634. {
  235635. AudioObjectPropertyAddress pa;
  235636. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  235637. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235638. pa.mElement = kAudioObjectPropertyElementWildcard;
  235639. AudioObjectRemovePropertyListener (deviceID, &pa, deviceListenerProc, this);
  235640. stop (false);
  235641. }
  235642. void allocateTempBuffers()
  235643. {
  235644. const int tempBufSize = bufferSize + 4;
  235645. audioBuffer.calloc ((numInputChans + numOutputChans) * tempBufSize);
  235646. tempInputBuffers.calloc (numInputChans + 2);
  235647. tempOutputBuffers.calloc (numOutputChans + 2);
  235648. int i, count = 0;
  235649. for (i = 0; i < numInputChans; ++i)
  235650. tempInputBuffers[i] = audioBuffer + count++ * tempBufSize;
  235651. for (i = 0; i < numOutputChans; ++i)
  235652. tempOutputBuffers[i] = audioBuffer + count++ * tempBufSize;
  235653. }
  235654. // returns the number of actual available channels
  235655. void fillInChannelInfo (const bool input)
  235656. {
  235657. int chanNum = 0;
  235658. UInt32 size;
  235659. AudioObjectPropertyAddress pa;
  235660. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  235661. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235662. pa.mElement = kAudioObjectPropertyElementMaster;
  235663. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235664. {
  235665. HeapBlock <AudioBufferList> bufList;
  235666. bufList.calloc (size, 1);
  235667. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  235668. {
  235669. const int numStreams = bufList->mNumberBuffers;
  235670. for (int i = 0; i < numStreams; ++i)
  235671. {
  235672. const AudioBuffer& b = bufList->mBuffers[i];
  235673. for (unsigned int j = 0; j < b.mNumberChannels; ++j)
  235674. {
  235675. String name;
  235676. {
  235677. char channelName [256];
  235678. zerostruct (channelName);
  235679. UInt32 nameSize = sizeof (channelName);
  235680. UInt32 channelNum = chanNum + 1;
  235681. pa.mSelector = kAudioDevicePropertyChannelName;
  235682. if (AudioObjectGetPropertyData (deviceID, &pa, sizeof (channelNum), &channelNum, &nameSize, channelName) == noErr)
  235683. name = String::fromUTF8 (channelName, nameSize);
  235684. }
  235685. if (input)
  235686. {
  235687. if (activeInputChans[chanNum])
  235688. {
  235689. inputChannelInfo [numInputChannelInfos].streamNum = i;
  235690. inputChannelInfo [numInputChannelInfos].dataOffsetSamples = j;
  235691. inputChannelInfo [numInputChannelInfos].dataStrideSamples = b.mNumberChannels;
  235692. ++numInputChannelInfos;
  235693. }
  235694. if (name.isEmpty())
  235695. name << "Input " << (chanNum + 1);
  235696. inChanNames.add (name);
  235697. }
  235698. else
  235699. {
  235700. if (activeOutputChans[chanNum])
  235701. {
  235702. outputChannelInfo [numOutputChannelInfos].streamNum = i;
  235703. outputChannelInfo [numOutputChannelInfos].dataOffsetSamples = j;
  235704. outputChannelInfo [numOutputChannelInfos].dataStrideSamples = b.mNumberChannels;
  235705. ++numOutputChannelInfos;
  235706. }
  235707. if (name.isEmpty())
  235708. name << "Output " << (chanNum + 1);
  235709. outChanNames.add (name);
  235710. }
  235711. ++chanNum;
  235712. }
  235713. }
  235714. }
  235715. }
  235716. }
  235717. void updateDetailsFromDevice()
  235718. {
  235719. stopTimer();
  235720. if (deviceID == 0)
  235721. return;
  235722. const ScopedLock sl (callbackLock);
  235723. Float64 sr;
  235724. UInt32 size = sizeof (Float64);
  235725. AudioObjectPropertyAddress pa;
  235726. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  235727. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235728. pa.mElement = kAudioObjectPropertyElementMaster;
  235729. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &sr)))
  235730. sampleRate = sr;
  235731. UInt32 framesPerBuf;
  235732. size = sizeof (framesPerBuf);
  235733. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  235734. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &framesPerBuf)))
  235735. {
  235736. bufferSize = framesPerBuf;
  235737. allocateTempBuffers();
  235738. }
  235739. bufferSizes.clear();
  235740. pa.mSelector = kAudioDevicePropertyBufferFrameSizeRange;
  235741. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235742. {
  235743. HeapBlock <AudioValueRange> ranges;
  235744. ranges.calloc (size, 1);
  235745. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  235746. {
  235747. bufferSizes.add ((int) ranges[0].mMinimum);
  235748. for (int i = 32; i < 2048; i += 32)
  235749. {
  235750. for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
  235751. {
  235752. if (i >= ranges[j].mMinimum && i <= ranges[j].mMaximum)
  235753. {
  235754. bufferSizes.addIfNotAlreadyThere (i);
  235755. break;
  235756. }
  235757. }
  235758. }
  235759. if (bufferSize > 0)
  235760. bufferSizes.addIfNotAlreadyThere (bufferSize);
  235761. }
  235762. }
  235763. if (bufferSizes.size() == 0 && bufferSize > 0)
  235764. bufferSizes.add (bufferSize);
  235765. sampleRates.clear();
  235766. const double possibleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  235767. String rates;
  235768. pa.mSelector = kAudioDevicePropertyAvailableNominalSampleRates;
  235769. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235770. {
  235771. HeapBlock <AudioValueRange> ranges;
  235772. ranges.calloc (size, 1);
  235773. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  235774. {
  235775. for (int i = 0; i < numElementsInArray (possibleRates); ++i)
  235776. {
  235777. bool ok = false;
  235778. for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
  235779. if (possibleRates[i] >= ranges[j].mMinimum - 2 && possibleRates[i] <= ranges[j].mMaximum + 2)
  235780. ok = true;
  235781. if (ok)
  235782. {
  235783. sampleRates.add (possibleRates[i]);
  235784. rates << possibleRates[i] << ' ';
  235785. }
  235786. }
  235787. }
  235788. }
  235789. if (sampleRates.size() == 0 && sampleRate > 0)
  235790. {
  235791. sampleRates.add (sampleRate);
  235792. rates << sampleRate;
  235793. }
  235794. log ("sr: " + rates);
  235795. inputLatency = 0;
  235796. outputLatency = 0;
  235797. UInt32 lat;
  235798. size = sizeof (lat);
  235799. pa.mSelector = kAudioDevicePropertyLatency;
  235800. pa.mScope = kAudioDevicePropertyScopeInput;
  235801. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  235802. inputLatency = (int) lat;
  235803. pa.mScope = kAudioDevicePropertyScopeOutput;
  235804. size = sizeof (lat);
  235805. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  235806. outputLatency = (int) lat;
  235807. log ("lat: " + String (inputLatency) + " " + String (outputLatency));
  235808. inChanNames.clear();
  235809. outChanNames.clear();
  235810. inputChannelInfo.calloc (numInputChans + 2);
  235811. numInputChannelInfos = 0;
  235812. outputChannelInfo.calloc (numOutputChans + 2);
  235813. numOutputChannelInfos = 0;
  235814. fillInChannelInfo (true);
  235815. fillInChannelInfo (false);
  235816. }
  235817. const StringArray getSources (bool input)
  235818. {
  235819. StringArray s;
  235820. HeapBlock <OSType> types;
  235821. const int num = getAllDataSourcesForDevice (deviceID, types);
  235822. for (int i = 0; i < num; ++i)
  235823. {
  235824. AudioValueTranslation avt;
  235825. char buffer[256];
  235826. avt.mInputData = &(types[i]);
  235827. avt.mInputDataSize = sizeof (UInt32);
  235828. avt.mOutputData = buffer;
  235829. avt.mOutputDataSize = 256;
  235830. UInt32 transSize = sizeof (avt);
  235831. AudioObjectPropertyAddress pa;
  235832. pa.mSelector = kAudioDevicePropertyDataSourceNameForID;
  235833. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235834. pa.mElement = kAudioObjectPropertyElementMaster;
  235835. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &transSize, &avt)))
  235836. {
  235837. DBG (buffer);
  235838. s.add (buffer);
  235839. }
  235840. }
  235841. return s;
  235842. }
  235843. int getCurrentSourceIndex (bool input) const
  235844. {
  235845. OSType currentSourceID = 0;
  235846. UInt32 size = sizeof (currentSourceID);
  235847. int result = -1;
  235848. AudioObjectPropertyAddress pa;
  235849. pa.mSelector = kAudioDevicePropertyDataSource;
  235850. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235851. pa.mElement = kAudioObjectPropertyElementMaster;
  235852. if (deviceID != 0)
  235853. {
  235854. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &currentSourceID)))
  235855. {
  235856. HeapBlock <OSType> types;
  235857. const int num = getAllDataSourcesForDevice (deviceID, types);
  235858. for (int i = 0; i < num; ++i)
  235859. {
  235860. if (types[num] == currentSourceID)
  235861. {
  235862. result = i;
  235863. break;
  235864. }
  235865. }
  235866. }
  235867. }
  235868. return result;
  235869. }
  235870. void setCurrentSourceIndex (int index, bool input)
  235871. {
  235872. if (deviceID != 0)
  235873. {
  235874. HeapBlock <OSType> types;
  235875. const int num = getAllDataSourcesForDevice (deviceID, types);
  235876. if (((unsigned int) index) < (unsigned int) num)
  235877. {
  235878. AudioObjectPropertyAddress pa;
  235879. pa.mSelector = kAudioDevicePropertyDataSource;
  235880. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235881. pa.mElement = kAudioObjectPropertyElementMaster;
  235882. OSType typeId = types[index];
  235883. OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (typeId), &typeId));
  235884. }
  235885. }
  235886. }
  235887. const String reopen (const BigInteger& inputChannels,
  235888. const BigInteger& outputChannels,
  235889. double newSampleRate,
  235890. int bufferSizeSamples)
  235891. {
  235892. String error;
  235893. log ("CoreAudio reopen");
  235894. callbacksAllowed = false;
  235895. stopTimer();
  235896. stop (false);
  235897. activeInputChans = inputChannels;
  235898. activeInputChans.setRange (inChanNames.size(),
  235899. activeInputChans.getHighestBit() + 1 - inChanNames.size(),
  235900. false);
  235901. activeOutputChans = outputChannels;
  235902. activeOutputChans.setRange (outChanNames.size(),
  235903. activeOutputChans.getHighestBit() + 1 - outChanNames.size(),
  235904. false);
  235905. numInputChans = activeInputChans.countNumberOfSetBits();
  235906. numOutputChans = activeOutputChans.countNumberOfSetBits();
  235907. // set sample rate
  235908. AudioObjectPropertyAddress pa;
  235909. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  235910. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235911. pa.mElement = kAudioObjectPropertyElementMaster;
  235912. Float64 sr = newSampleRate;
  235913. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (sr), &sr)))
  235914. {
  235915. error = "Couldn't change sample rate";
  235916. }
  235917. else
  235918. {
  235919. // change buffer size
  235920. UInt32 framesPerBuf = bufferSizeSamples;
  235921. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  235922. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (framesPerBuf), &framesPerBuf)))
  235923. {
  235924. error = "Couldn't change buffer size";
  235925. }
  235926. else
  235927. {
  235928. // Annoyingly, after changing the rate and buffer size, some devices fail to
  235929. // correctly report their new settings until some random time in the future, so
  235930. // after calling updateDetailsFromDevice, we need to manually bodge these values
  235931. // to make sure we're using the correct numbers..
  235932. updateDetailsFromDevice();
  235933. sampleRate = newSampleRate;
  235934. bufferSize = bufferSizeSamples;
  235935. if (sampleRates.size() == 0)
  235936. error = "Device has no available sample-rates";
  235937. else if (bufferSizes.size() == 0)
  235938. error = "Device has no available buffer-sizes";
  235939. else if (inputDevice != 0)
  235940. error = inputDevice->reopen (inputChannels,
  235941. outputChannels,
  235942. newSampleRate,
  235943. bufferSizeSamples);
  235944. }
  235945. }
  235946. callbacksAllowed = true;
  235947. return error;
  235948. }
  235949. bool start (AudioIODeviceCallback* cb)
  235950. {
  235951. if (! started)
  235952. {
  235953. callback = 0;
  235954. if (deviceID != 0)
  235955. {
  235956. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  235957. if (OK (AudioDeviceAddIOProc (deviceID, audioIOProc, this)))
  235958. #else
  235959. if (OK (AudioDeviceCreateIOProcID (deviceID, audioIOProc, this, &audioProcID)))
  235960. #endif
  235961. {
  235962. if (OK (AudioDeviceStart (deviceID, audioIOProc)))
  235963. {
  235964. started = true;
  235965. }
  235966. else
  235967. {
  235968. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  235969. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  235970. #else
  235971. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  235972. audioProcID = 0;
  235973. #endif
  235974. }
  235975. }
  235976. }
  235977. }
  235978. if (started)
  235979. {
  235980. const ScopedLock sl (callbackLock);
  235981. callback = cb;
  235982. }
  235983. if (inputDevice != 0)
  235984. return started && inputDevice->start (cb);
  235985. else
  235986. return started;
  235987. }
  235988. void stop (bool leaveInterruptRunning)
  235989. {
  235990. {
  235991. const ScopedLock sl (callbackLock);
  235992. callback = 0;
  235993. }
  235994. if (started
  235995. && (deviceID != 0)
  235996. && ! leaveInterruptRunning)
  235997. {
  235998. OK (AudioDeviceStop (deviceID, audioIOProc));
  235999. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  236000. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  236001. #else
  236002. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  236003. audioProcID = 0;
  236004. #endif
  236005. started = false;
  236006. { const ScopedLock sl (callbackLock); }
  236007. // wait until it's definately stopped calling back..
  236008. for (int i = 40; --i >= 0;)
  236009. {
  236010. Thread::sleep (50);
  236011. UInt32 running = 0;
  236012. UInt32 size = sizeof (running);
  236013. AudioObjectPropertyAddress pa;
  236014. pa.mSelector = kAudioDevicePropertyDeviceIsRunning;
  236015. pa.mScope = kAudioObjectPropertyScopeWildcard;
  236016. pa.mElement = kAudioObjectPropertyElementMaster;
  236017. OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &running));
  236018. if (running == 0)
  236019. break;
  236020. }
  236021. const ScopedLock sl (callbackLock);
  236022. }
  236023. if (inputDevice != 0)
  236024. inputDevice->stop (leaveInterruptRunning);
  236025. }
  236026. double getSampleRate() const
  236027. {
  236028. return sampleRate;
  236029. }
  236030. int getBufferSize() const
  236031. {
  236032. return bufferSize;
  236033. }
  236034. void audioCallback (const AudioBufferList* inInputData,
  236035. AudioBufferList* outOutputData)
  236036. {
  236037. int i;
  236038. const ScopedLock sl (callbackLock);
  236039. if (callback != 0)
  236040. {
  236041. if (inputDevice == 0)
  236042. {
  236043. for (i = numInputChans; --i >= 0;)
  236044. {
  236045. const CallbackDetailsForChannel& info = inputChannelInfo[i];
  236046. float* dest = tempInputBuffers [i];
  236047. const float* src = ((const float*) inInputData->mBuffers[info.streamNum].mData)
  236048. + info.dataOffsetSamples;
  236049. const int stride = info.dataStrideSamples;
  236050. if (stride != 0) // if this is zero, info is invalid
  236051. {
  236052. for (int j = bufferSize; --j >= 0;)
  236053. {
  236054. *dest++ = *src;
  236055. src += stride;
  236056. }
  236057. }
  236058. }
  236059. }
  236060. if (! isSlaveDevice)
  236061. {
  236062. if (inputDevice == 0)
  236063. {
  236064. callback->audioDeviceIOCallback (const_cast<const float**> (tempInputBuffers.getData()),
  236065. numInputChans,
  236066. tempOutputBuffers,
  236067. numOutputChans,
  236068. bufferSize);
  236069. }
  236070. else
  236071. {
  236072. jassert (inputDevice->bufferSize == bufferSize);
  236073. // Sometimes the two linked devices seem to get their callbacks in
  236074. // parallel, so we need to lock both devices to stop the input data being
  236075. // changed while inside our callback..
  236076. const ScopedLock sl2 (inputDevice->callbackLock);
  236077. callback->audioDeviceIOCallback (const_cast<const float**> (inputDevice->tempInputBuffers.getData()),
  236078. inputDevice->numInputChans,
  236079. tempOutputBuffers,
  236080. numOutputChans,
  236081. bufferSize);
  236082. }
  236083. for (i = numOutputChans; --i >= 0;)
  236084. {
  236085. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  236086. const float* src = tempOutputBuffers [i];
  236087. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  236088. + info.dataOffsetSamples;
  236089. const int stride = info.dataStrideSamples;
  236090. if (stride != 0) // if this is zero, info is invalid
  236091. {
  236092. for (int j = bufferSize; --j >= 0;)
  236093. {
  236094. *dest = *src++;
  236095. dest += stride;
  236096. }
  236097. }
  236098. }
  236099. }
  236100. }
  236101. else
  236102. {
  236103. for (i = jmin (numOutputChans, numOutputChannelInfos); --i >= 0;)
  236104. {
  236105. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  236106. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  236107. + info.dataOffsetSamples;
  236108. const int stride = info.dataStrideSamples;
  236109. if (stride != 0) // if this is zero, info is invalid
  236110. {
  236111. for (int j = bufferSize; --j >= 0;)
  236112. {
  236113. *dest = 0.0f;
  236114. dest += stride;
  236115. }
  236116. }
  236117. }
  236118. }
  236119. }
  236120. // called by callbacks
  236121. void deviceDetailsChanged()
  236122. {
  236123. if (callbacksAllowed)
  236124. startTimer (100);
  236125. }
  236126. void timerCallback()
  236127. {
  236128. stopTimer();
  236129. log ("CoreAudio device changed callback");
  236130. const double oldSampleRate = sampleRate;
  236131. const int oldBufferSize = bufferSize;
  236132. updateDetailsFromDevice();
  236133. if (oldBufferSize != bufferSize || oldSampleRate != sampleRate)
  236134. {
  236135. callbacksAllowed = false;
  236136. stop (false);
  236137. updateDetailsFromDevice();
  236138. callbacksAllowed = true;
  236139. }
  236140. }
  236141. CoreAudioInternal* getRelatedDevice() const
  236142. {
  236143. UInt32 size = 0;
  236144. ScopedPointer <CoreAudioInternal> result;
  236145. AudioObjectPropertyAddress pa;
  236146. pa.mSelector = kAudioDevicePropertyRelatedDevices;
  236147. pa.mScope = kAudioObjectPropertyScopeWildcard;
  236148. pa.mElement = kAudioObjectPropertyElementMaster;
  236149. if (deviceID != 0
  236150. && AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size) == noErr
  236151. && size > 0)
  236152. {
  236153. HeapBlock <AudioDeviceID> devs;
  236154. devs.calloc (size, 1);
  236155. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, devs)))
  236156. {
  236157. for (unsigned int i = 0; i < size / sizeof (AudioDeviceID); ++i)
  236158. {
  236159. if (devs[i] != deviceID && devs[i] != 0)
  236160. {
  236161. result = new CoreAudioInternal (devs[i]);
  236162. const bool thisIsInput = inChanNames.size() > 0 && outChanNames.size() == 0;
  236163. const bool otherIsInput = result->inChanNames.size() > 0 && result->outChanNames.size() == 0;
  236164. if (thisIsInput != otherIsInput
  236165. || (inChanNames.size() + outChanNames.size() == 0)
  236166. || (result->inChanNames.size() + result->outChanNames.size()) == 0)
  236167. break;
  236168. result = 0;
  236169. }
  236170. }
  236171. }
  236172. }
  236173. return result.release();
  236174. }
  236175. juce_UseDebuggingNewOperator
  236176. int inputLatency, outputLatency;
  236177. BigInteger activeInputChans, activeOutputChans;
  236178. StringArray inChanNames, outChanNames;
  236179. Array <double> sampleRates;
  236180. Array <int> bufferSizes;
  236181. AudioIODeviceCallback* callback;
  236182. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  236183. AudioDeviceIOProcID audioProcID;
  236184. #endif
  236185. ScopedPointer<CoreAudioInternal> inputDevice;
  236186. bool isSlaveDevice;
  236187. private:
  236188. CriticalSection callbackLock;
  236189. AudioDeviceID deviceID;
  236190. bool started;
  236191. double sampleRate;
  236192. int bufferSize;
  236193. HeapBlock <float> audioBuffer;
  236194. int numInputChans, numOutputChans;
  236195. bool callbacksAllowed;
  236196. struct CallbackDetailsForChannel
  236197. {
  236198. int streamNum;
  236199. int dataOffsetSamples;
  236200. int dataStrideSamples;
  236201. };
  236202. int numInputChannelInfos, numOutputChannelInfos;
  236203. HeapBlock <CallbackDetailsForChannel> inputChannelInfo, outputChannelInfo;
  236204. HeapBlock <float*> tempInputBuffers, tempOutputBuffers;
  236205. CoreAudioInternal (const CoreAudioInternal&);
  236206. CoreAudioInternal& operator= (const CoreAudioInternal&);
  236207. static OSStatus audioIOProc (AudioDeviceID /*inDevice*/,
  236208. const AudioTimeStamp* /*inNow*/,
  236209. const AudioBufferList* inInputData,
  236210. const AudioTimeStamp* /*inInputTime*/,
  236211. AudioBufferList* outOutputData,
  236212. const AudioTimeStamp* /*inOutputTime*/,
  236213. void* device)
  236214. {
  236215. static_cast <CoreAudioInternal*> (device)->audioCallback (inInputData, outOutputData);
  236216. return noErr;
  236217. }
  236218. static OSStatus deviceListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  236219. {
  236220. CoreAudioInternal* const intern = static_cast <CoreAudioInternal*> (inClientData);
  236221. switch (pa->mSelector)
  236222. {
  236223. case kAudioDevicePropertyBufferSize:
  236224. case kAudioDevicePropertyBufferFrameSize:
  236225. case kAudioDevicePropertyNominalSampleRate:
  236226. case kAudioDevicePropertyStreamFormat:
  236227. case kAudioDevicePropertyDeviceIsAlive:
  236228. intern->deviceDetailsChanged();
  236229. break;
  236230. case kAudioDevicePropertyBufferSizeRange:
  236231. case kAudioDevicePropertyVolumeScalar:
  236232. case kAudioDevicePropertyMute:
  236233. case kAudioDevicePropertyPlayThru:
  236234. case kAudioDevicePropertyDataSource:
  236235. case kAudioDevicePropertyDeviceIsRunning:
  236236. break;
  236237. }
  236238. return noErr;
  236239. }
  236240. static int getAllDataSourcesForDevice (AudioDeviceID deviceID, HeapBlock <OSType>& types)
  236241. {
  236242. AudioObjectPropertyAddress pa;
  236243. pa.mSelector = kAudioDevicePropertyDataSources;
  236244. pa.mScope = kAudioObjectPropertyScopeWildcard;
  236245. pa.mElement = kAudioObjectPropertyElementMaster;
  236246. UInt32 size = 0;
  236247. if (deviceID != 0
  236248. && OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  236249. {
  236250. types.calloc (size, 1);
  236251. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, types)))
  236252. return size / (int) sizeof (OSType);
  236253. }
  236254. return 0;
  236255. }
  236256. };
  236257. class CoreAudioIODevice : public AudioIODevice
  236258. {
  236259. public:
  236260. CoreAudioIODevice (const String& deviceName,
  236261. AudioDeviceID inputDeviceId,
  236262. const int inputIndex_,
  236263. AudioDeviceID outputDeviceId,
  236264. const int outputIndex_)
  236265. : AudioIODevice (deviceName, "CoreAudio"),
  236266. inputIndex (inputIndex_),
  236267. outputIndex (outputIndex_),
  236268. isOpen_ (false),
  236269. isStarted (false)
  236270. {
  236271. CoreAudioInternal* device = 0;
  236272. if (outputDeviceId == 0 || outputDeviceId == inputDeviceId)
  236273. {
  236274. jassert (inputDeviceId != 0);
  236275. device = new CoreAudioInternal (inputDeviceId);
  236276. }
  236277. else
  236278. {
  236279. device = new CoreAudioInternal (outputDeviceId);
  236280. if (inputDeviceId != 0)
  236281. {
  236282. CoreAudioInternal* secondDevice = new CoreAudioInternal (inputDeviceId);
  236283. device->inputDevice = secondDevice;
  236284. secondDevice->isSlaveDevice = true;
  236285. }
  236286. }
  236287. internal = device;
  236288. AudioObjectPropertyAddress pa;
  236289. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  236290. pa.mScope = kAudioObjectPropertyScopeWildcard;
  236291. pa.mElement = kAudioObjectPropertyElementWildcard;
  236292. AudioObjectAddPropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  236293. }
  236294. ~CoreAudioIODevice()
  236295. {
  236296. AudioObjectPropertyAddress pa;
  236297. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  236298. pa.mScope = kAudioObjectPropertyScopeWildcard;
  236299. pa.mElement = kAudioObjectPropertyElementWildcard;
  236300. AudioObjectRemovePropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  236301. }
  236302. const StringArray getOutputChannelNames()
  236303. {
  236304. return internal->outChanNames;
  236305. }
  236306. const StringArray getInputChannelNames()
  236307. {
  236308. if (internal->inputDevice != 0)
  236309. return internal->inputDevice->inChanNames;
  236310. else
  236311. return internal->inChanNames;
  236312. }
  236313. int getNumSampleRates()
  236314. {
  236315. return internal->sampleRates.size();
  236316. }
  236317. double getSampleRate (int index)
  236318. {
  236319. return internal->sampleRates [index];
  236320. }
  236321. int getNumBufferSizesAvailable()
  236322. {
  236323. return internal->bufferSizes.size();
  236324. }
  236325. int getBufferSizeSamples (int index)
  236326. {
  236327. return internal->bufferSizes [index];
  236328. }
  236329. int getDefaultBufferSize()
  236330. {
  236331. for (int i = 0; i < getNumBufferSizesAvailable(); ++i)
  236332. if (getBufferSizeSamples(i) >= 512)
  236333. return getBufferSizeSamples(i);
  236334. return 512;
  236335. }
  236336. const String open (const BigInteger& inputChannels,
  236337. const BigInteger& outputChannels,
  236338. double sampleRate,
  236339. int bufferSizeSamples)
  236340. {
  236341. isOpen_ = true;
  236342. if (bufferSizeSamples <= 0)
  236343. bufferSizeSamples = getDefaultBufferSize();
  236344. lastError = internal->reopen (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  236345. isOpen_ = lastError.isEmpty();
  236346. return lastError;
  236347. }
  236348. void close()
  236349. {
  236350. isOpen_ = false;
  236351. internal->stop (false);
  236352. }
  236353. bool isOpen()
  236354. {
  236355. return isOpen_;
  236356. }
  236357. int getCurrentBufferSizeSamples()
  236358. {
  236359. return internal != 0 ? internal->getBufferSize() : 512;
  236360. }
  236361. double getCurrentSampleRate()
  236362. {
  236363. return internal != 0 ? internal->getSampleRate() : 0;
  236364. }
  236365. int getCurrentBitDepth()
  236366. {
  236367. return 32; // no way to find out, so just assume it's high..
  236368. }
  236369. const BigInteger getActiveOutputChannels() const
  236370. {
  236371. return internal != 0 ? internal->activeOutputChans : BigInteger();
  236372. }
  236373. const BigInteger getActiveInputChannels() const
  236374. {
  236375. BigInteger chans;
  236376. if (internal != 0)
  236377. {
  236378. chans = internal->activeInputChans;
  236379. if (internal->inputDevice != 0)
  236380. chans |= internal->inputDevice->activeInputChans;
  236381. }
  236382. return chans;
  236383. }
  236384. int getOutputLatencyInSamples()
  236385. {
  236386. if (internal == 0)
  236387. return 0;
  236388. // this seems like a good guess at getting the latency right - comparing
  236389. // this with a round-trip measurement, it gets it to within a few millisecs
  236390. // for the built-in mac soundcard
  236391. return internal->outputLatency + internal->getBufferSize() * 2;
  236392. }
  236393. int getInputLatencyInSamples()
  236394. {
  236395. if (internal == 0)
  236396. return 0;
  236397. return internal->inputLatency + internal->getBufferSize() * 2;
  236398. }
  236399. void start (AudioIODeviceCallback* callback)
  236400. {
  236401. if (internal != 0 && ! isStarted)
  236402. {
  236403. if (callback != 0)
  236404. callback->audioDeviceAboutToStart (this);
  236405. isStarted = true;
  236406. internal->start (callback);
  236407. }
  236408. }
  236409. void stop()
  236410. {
  236411. if (isStarted && internal != 0)
  236412. {
  236413. AudioIODeviceCallback* const lastCallback = internal->callback;
  236414. isStarted = false;
  236415. internal->stop (true);
  236416. if (lastCallback != 0)
  236417. lastCallback->audioDeviceStopped();
  236418. }
  236419. }
  236420. bool isPlaying()
  236421. {
  236422. if (internal->callback == 0)
  236423. isStarted = false;
  236424. return isStarted;
  236425. }
  236426. const String getLastError()
  236427. {
  236428. return lastError;
  236429. }
  236430. int inputIndex, outputIndex;
  236431. juce_UseDebuggingNewOperator
  236432. private:
  236433. ScopedPointer<CoreAudioInternal> internal;
  236434. bool isOpen_, isStarted;
  236435. String lastError;
  236436. static OSStatus hardwareListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  236437. {
  236438. CoreAudioInternal* const intern = static_cast <CoreAudioInternal*> (inClientData);
  236439. switch (pa->mSelector)
  236440. {
  236441. case kAudioHardwarePropertyDevices:
  236442. intern->deviceDetailsChanged();
  236443. break;
  236444. case kAudioHardwarePropertyDefaultOutputDevice:
  236445. case kAudioHardwarePropertyDefaultInputDevice:
  236446. case kAudioHardwarePropertyDefaultSystemOutputDevice:
  236447. break;
  236448. }
  236449. return noErr;
  236450. }
  236451. CoreAudioIODevice (const CoreAudioIODevice&);
  236452. CoreAudioIODevice& operator= (const CoreAudioIODevice&);
  236453. };
  236454. class CoreAudioIODeviceType : public AudioIODeviceType
  236455. {
  236456. public:
  236457. CoreAudioIODeviceType()
  236458. : AudioIODeviceType ("CoreAudio"),
  236459. hasScanned (false)
  236460. {
  236461. }
  236462. ~CoreAudioIODeviceType()
  236463. {
  236464. }
  236465. void scanForDevices()
  236466. {
  236467. hasScanned = true;
  236468. inputDeviceNames.clear();
  236469. outputDeviceNames.clear();
  236470. inputIds.clear();
  236471. outputIds.clear();
  236472. UInt32 size;
  236473. AudioObjectPropertyAddress pa;
  236474. pa.mSelector = kAudioHardwarePropertyDevices;
  236475. pa.mScope = kAudioObjectPropertyScopeWildcard;
  236476. pa.mElement = kAudioObjectPropertyElementMaster;
  236477. if (OK (AudioObjectGetPropertyDataSize (kAudioObjectSystemObject, &pa, 0, 0, &size)))
  236478. {
  236479. HeapBlock <AudioDeviceID> devs;
  236480. devs.calloc (size, 1);
  236481. if (OK (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, devs)))
  236482. {
  236483. const int num = size / (int) sizeof (AudioDeviceID);
  236484. for (int i = 0; i < num; ++i)
  236485. {
  236486. char name [1024];
  236487. size = sizeof (name);
  236488. pa.mSelector = kAudioDevicePropertyDeviceName;
  236489. if (OK (AudioObjectGetPropertyData (devs[i], &pa, 0, 0, &size, name)))
  236490. {
  236491. const String nameString (String::fromUTF8 (name, (int) strlen (name)));
  236492. const int numIns = getNumChannels (devs[i], true);
  236493. const int numOuts = getNumChannels (devs[i], false);
  236494. if (numIns > 0)
  236495. {
  236496. inputDeviceNames.add (nameString);
  236497. inputIds.add (devs[i]);
  236498. }
  236499. if (numOuts > 0)
  236500. {
  236501. outputDeviceNames.add (nameString);
  236502. outputIds.add (devs[i]);
  236503. }
  236504. }
  236505. }
  236506. }
  236507. }
  236508. inputDeviceNames.appendNumbersToDuplicates (false, true);
  236509. outputDeviceNames.appendNumbersToDuplicates (false, true);
  236510. }
  236511. const StringArray getDeviceNames (bool wantInputNames) const
  236512. {
  236513. jassert (hasScanned); // need to call scanForDevices() before doing this
  236514. if (wantInputNames)
  236515. return inputDeviceNames;
  236516. else
  236517. return outputDeviceNames;
  236518. }
  236519. int getDefaultDeviceIndex (bool forInput) const
  236520. {
  236521. jassert (hasScanned); // need to call scanForDevices() before doing this
  236522. AudioDeviceID deviceID;
  236523. UInt32 size = sizeof (deviceID);
  236524. // if they're asking for any input channels at all, use the default input, so we
  236525. // get the built-in mic rather than the built-in output with no inputs..
  236526. AudioObjectPropertyAddress pa;
  236527. pa.mSelector = forInput ? kAudioHardwarePropertyDefaultInputDevice : kAudioHardwarePropertyDefaultOutputDevice;
  236528. pa.mScope = kAudioObjectPropertyScopeWildcard;
  236529. pa.mElement = kAudioObjectPropertyElementMaster;
  236530. if (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, &deviceID) == noErr)
  236531. {
  236532. if (forInput)
  236533. {
  236534. for (int i = inputIds.size(); --i >= 0;)
  236535. if (inputIds[i] == deviceID)
  236536. return i;
  236537. }
  236538. else
  236539. {
  236540. for (int i = outputIds.size(); --i >= 0;)
  236541. if (outputIds[i] == deviceID)
  236542. return i;
  236543. }
  236544. }
  236545. return 0;
  236546. }
  236547. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  236548. {
  236549. jassert (hasScanned); // need to call scanForDevices() before doing this
  236550. CoreAudioIODevice* const d = dynamic_cast <CoreAudioIODevice*> (device);
  236551. if (d == 0)
  236552. return -1;
  236553. return asInput ? d->inputIndex
  236554. : d->outputIndex;
  236555. }
  236556. bool hasSeparateInputsAndOutputs() const { return true; }
  236557. AudioIODevice* createDevice (const String& outputDeviceName,
  236558. const String& inputDeviceName)
  236559. {
  236560. jassert (hasScanned); // need to call scanForDevices() before doing this
  236561. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  236562. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  236563. String deviceName (outputDeviceName);
  236564. if (deviceName.isEmpty())
  236565. deviceName = inputDeviceName;
  236566. if (index >= 0)
  236567. return new CoreAudioIODevice (deviceName,
  236568. inputIds [inputIndex],
  236569. inputIndex,
  236570. outputIds [outputIndex],
  236571. outputIndex);
  236572. return 0;
  236573. }
  236574. juce_UseDebuggingNewOperator
  236575. private:
  236576. StringArray inputDeviceNames, outputDeviceNames;
  236577. Array <AudioDeviceID> inputIds, outputIds;
  236578. bool hasScanned;
  236579. static int getNumChannels (AudioDeviceID deviceID, bool input)
  236580. {
  236581. int total = 0;
  236582. UInt32 size;
  236583. AudioObjectPropertyAddress pa;
  236584. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  236585. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  236586. pa.mElement = kAudioObjectPropertyElementMaster;
  236587. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  236588. {
  236589. HeapBlock <AudioBufferList> bufList;
  236590. bufList.calloc (size, 1);
  236591. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  236592. {
  236593. const int numStreams = bufList->mNumberBuffers;
  236594. for (int i = 0; i < numStreams; ++i)
  236595. {
  236596. const AudioBuffer& b = bufList->mBuffers[i];
  236597. total += b.mNumberChannels;
  236598. }
  236599. }
  236600. }
  236601. return total;
  236602. }
  236603. CoreAudioIODeviceType (const CoreAudioIODeviceType&);
  236604. CoreAudioIODeviceType& operator= (const CoreAudioIODeviceType&);
  236605. };
  236606. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio()
  236607. {
  236608. return new CoreAudioIODeviceType();
  236609. }
  236610. #undef log
  236611. #endif
  236612. /*** End of inlined file: juce_mac_CoreAudio.cpp ***/
  236613. /*** Start of inlined file: juce_mac_CoreMidi.cpp ***/
  236614. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  236615. // compiled on its own).
  236616. #if JUCE_INCLUDED_FILE
  236617. #if JUCE_MAC
  236618. namespace CoreMidiHelpers
  236619. {
  236620. static bool logError (const OSStatus err, const int lineNum)
  236621. {
  236622. if (err == noErr)
  236623. return true;
  236624. Logger::writeToLog ("CoreMidi error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  236625. jassertfalse;
  236626. return false;
  236627. }
  236628. #undef CHECK_ERROR
  236629. #define CHECK_ERROR(a) CoreMidiHelpers::logError (a, __LINE__)
  236630. static const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  236631. {
  236632. String result;
  236633. CFStringRef str = 0;
  236634. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  236635. if (str != 0)
  236636. {
  236637. result = PlatformUtilities::cfStringToJuceString (str);
  236638. CFRelease (str);
  236639. str = 0;
  236640. }
  236641. MIDIEntityRef entity = 0;
  236642. MIDIEndpointGetEntity (endpoint, &entity);
  236643. if (entity == 0)
  236644. return result; // probably virtual
  236645. if (result.isEmpty())
  236646. {
  236647. // endpoint name has zero length - try the entity
  236648. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  236649. if (str != 0)
  236650. {
  236651. result += PlatformUtilities::cfStringToJuceString (str);
  236652. CFRelease (str);
  236653. str = 0;
  236654. }
  236655. }
  236656. // now consider the device's name
  236657. MIDIDeviceRef device = 0;
  236658. MIDIEntityGetDevice (entity, &device);
  236659. if (device == 0)
  236660. return result;
  236661. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  236662. if (str != 0)
  236663. {
  236664. const String s (PlatformUtilities::cfStringToJuceString (str));
  236665. CFRelease (str);
  236666. // if an external device has only one entity, throw away
  236667. // the endpoint name and just use the device name
  236668. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  236669. {
  236670. result = s;
  236671. }
  236672. else if (! result.startsWithIgnoreCase (s))
  236673. {
  236674. // prepend the device name to the entity name
  236675. result = (s + " " + result).trimEnd();
  236676. }
  236677. }
  236678. return result;
  236679. }
  236680. static const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  236681. {
  236682. String result;
  236683. // Does the endpoint have connections?
  236684. CFDataRef connections = 0;
  236685. int numConnections = 0;
  236686. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  236687. if (connections != 0)
  236688. {
  236689. numConnections = (int) (CFDataGetLength (connections) / sizeof (MIDIUniqueID));
  236690. if (numConnections > 0)
  236691. {
  236692. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  236693. for (int i = 0; i < numConnections; ++i, ++pid)
  236694. {
  236695. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  236696. MIDIObjectRef connObject;
  236697. MIDIObjectType connObjectType;
  236698. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  236699. if (err == noErr)
  236700. {
  236701. String s;
  236702. if (connObjectType == kMIDIObjectType_ExternalSource
  236703. || connObjectType == kMIDIObjectType_ExternalDestination)
  236704. {
  236705. // Connected to an external device's endpoint (10.3 and later).
  236706. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  236707. }
  236708. else
  236709. {
  236710. // Connected to an external device (10.2) (or something else, catch-all)
  236711. CFStringRef str = 0;
  236712. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  236713. if (str != 0)
  236714. {
  236715. s = PlatformUtilities::cfStringToJuceString (str);
  236716. CFRelease (str);
  236717. }
  236718. }
  236719. if (s.isNotEmpty())
  236720. {
  236721. if (result.isNotEmpty())
  236722. result += ", ";
  236723. result += s;
  236724. }
  236725. }
  236726. }
  236727. }
  236728. CFRelease (connections);
  236729. }
  236730. if (result.isNotEmpty())
  236731. return result;
  236732. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  236733. return getEndpointName (endpoint, false);
  236734. }
  236735. static MIDIClientRef getGlobalMidiClient()
  236736. {
  236737. static MIDIClientRef globalMidiClient = 0;
  236738. if (globalMidiClient == 0)
  236739. {
  236740. String name ("JUCE");
  236741. if (JUCEApplication::getInstance() != 0)
  236742. name = JUCEApplication::getInstance()->getApplicationName();
  236743. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  236744. CHECK_ERROR (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  236745. CFRelease (appName);
  236746. }
  236747. return globalMidiClient;
  236748. }
  236749. class MidiPortAndEndpoint
  236750. {
  236751. public:
  236752. MidiPortAndEndpoint (MIDIPortRef port_, MIDIEndpointRef endPoint_)
  236753. : port (port_), endPoint (endPoint_)
  236754. {
  236755. }
  236756. ~MidiPortAndEndpoint()
  236757. {
  236758. if (port != 0)
  236759. MIDIPortDispose (port);
  236760. if (port == 0 && endPoint != 0) // if port == 0, it means we created the endpoint, so it's safe to delete it
  236761. MIDIEndpointDispose (endPoint);
  236762. }
  236763. void send (const MIDIPacketList* const packets)
  236764. {
  236765. if (port != 0)
  236766. MIDISend (port, endPoint, packets);
  236767. else
  236768. MIDIReceived (endPoint, packets);
  236769. }
  236770. MIDIPortRef port;
  236771. MIDIEndpointRef endPoint;
  236772. };
  236773. class MidiPortAndCallback;
  236774. static CriticalSection callbackLock;
  236775. static Array<MidiPortAndCallback*> activeCallbacks;
  236776. class MidiPortAndCallback
  236777. {
  236778. public:
  236779. MidiPortAndCallback (MidiInputCallback& callback_)
  236780. : input (0), active (false), callback (callback_), concatenator (2048)
  236781. {
  236782. }
  236783. ~MidiPortAndCallback()
  236784. {
  236785. active = false;
  236786. {
  236787. const ScopedLock sl (callbackLock);
  236788. activeCallbacks.removeValue (this);
  236789. }
  236790. if (portAndEndpoint != 0 && portAndEndpoint->port != 0)
  236791. CHECK_ERROR (MIDIPortDisconnectSource (portAndEndpoint->port, portAndEndpoint->endPoint));
  236792. }
  236793. void handlePackets (const MIDIPacketList* const pktlist)
  236794. {
  236795. const double time = Time::getMillisecondCounterHiRes() * 0.001;
  236796. const ScopedLock sl (callbackLock);
  236797. if (activeCallbacks.contains (this) && active)
  236798. {
  236799. const MIDIPacket* packet = &pktlist->packet[0];
  236800. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  236801. {
  236802. concatenator.pushMidiData (packet->data, (int) packet->length, time,
  236803. input, callback);
  236804. packet = MIDIPacketNext (packet);
  236805. }
  236806. }
  236807. }
  236808. MidiInput* input;
  236809. ScopedPointer<MidiPortAndEndpoint> portAndEndpoint;
  236810. volatile bool active;
  236811. private:
  236812. MidiInputCallback& callback;
  236813. MidiDataConcatenator concatenator;
  236814. };
  236815. static void midiInputProc (const MIDIPacketList* pktlist, void* readProcRefCon, void* /*srcConnRefCon*/)
  236816. {
  236817. static_cast <MidiPortAndCallback*> (readProcRefCon)->handlePackets (pktlist);
  236818. }
  236819. }
  236820. const StringArray MidiOutput::getDevices()
  236821. {
  236822. StringArray s;
  236823. const ItemCount num = MIDIGetNumberOfDestinations();
  236824. for (ItemCount i = 0; i < num; ++i)
  236825. {
  236826. MIDIEndpointRef dest = MIDIGetDestination (i);
  236827. if (dest != 0)
  236828. {
  236829. String name (CoreMidiHelpers::getConnectedEndpointName (dest));
  236830. if (name.isEmpty())
  236831. name = "<error>";
  236832. s.add (name);
  236833. }
  236834. else
  236835. {
  236836. s.add ("<error>");
  236837. }
  236838. }
  236839. return s;
  236840. }
  236841. int MidiOutput::getDefaultDeviceIndex()
  236842. {
  236843. return 0;
  236844. }
  236845. MidiOutput* MidiOutput::openDevice (int index)
  236846. {
  236847. MidiOutput* mo = 0;
  236848. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfDestinations())
  236849. {
  236850. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  236851. CFStringRef pname;
  236852. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  236853. {
  236854. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  236855. MIDIPortRef port;
  236856. if (client != 0 && CHECK_ERROR (MIDIOutputPortCreate (client, pname, &port)))
  236857. {
  236858. mo = new MidiOutput();
  236859. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (port, endPoint);
  236860. }
  236861. CFRelease (pname);
  236862. }
  236863. }
  236864. return mo;
  236865. }
  236866. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  236867. {
  236868. MidiOutput* mo = 0;
  236869. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  236870. MIDIEndpointRef endPoint;
  236871. CFStringRef name = PlatformUtilities::juceStringToCFString (deviceName);
  236872. if (client != 0 && CHECK_ERROR (MIDISourceCreate (client, name, &endPoint)))
  236873. {
  236874. mo = new MidiOutput();
  236875. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (0, endPoint);
  236876. }
  236877. CFRelease (name);
  236878. return mo;
  236879. }
  236880. MidiOutput::~MidiOutput()
  236881. {
  236882. delete static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  236883. }
  236884. void MidiOutput::reset()
  236885. {
  236886. }
  236887. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  236888. {
  236889. return false;
  236890. }
  236891. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  236892. {
  236893. }
  236894. void MidiOutput::sendMessageNow (const MidiMessage& message)
  236895. {
  236896. CoreMidiHelpers::MidiPortAndEndpoint* const mpe = static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  236897. if (message.isSysEx())
  236898. {
  236899. const int maxPacketSize = 256;
  236900. int pos = 0, bytesLeft = message.getRawDataSize();
  236901. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  236902. HeapBlock <MIDIPacketList> packets;
  236903. packets.malloc (32 * numPackets + message.getRawDataSize(), 1);
  236904. packets->numPackets = numPackets;
  236905. MIDIPacket* p = packets->packet;
  236906. for (int i = 0; i < numPackets; ++i)
  236907. {
  236908. p->timeStamp = 0;
  236909. p->length = jmin (maxPacketSize, bytesLeft);
  236910. memcpy (p->data, message.getRawData() + pos, p->length);
  236911. pos += p->length;
  236912. bytesLeft -= p->length;
  236913. p = MIDIPacketNext (p);
  236914. }
  236915. mpe->send (packets);
  236916. }
  236917. else
  236918. {
  236919. MIDIPacketList packets;
  236920. packets.numPackets = 1;
  236921. packets.packet[0].timeStamp = 0;
  236922. packets.packet[0].length = message.getRawDataSize();
  236923. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  236924. mpe->send (&packets);
  236925. }
  236926. }
  236927. const StringArray MidiInput::getDevices()
  236928. {
  236929. StringArray s;
  236930. const ItemCount num = MIDIGetNumberOfSources();
  236931. for (ItemCount i = 0; i < num; ++i)
  236932. {
  236933. MIDIEndpointRef source = MIDIGetSource (i);
  236934. if (source != 0)
  236935. {
  236936. String name (CoreMidiHelpers::getConnectedEndpointName (source));
  236937. if (name.isEmpty())
  236938. name = "<error>";
  236939. s.add (name);
  236940. }
  236941. else
  236942. {
  236943. s.add ("<error>");
  236944. }
  236945. }
  236946. return s;
  236947. }
  236948. int MidiInput::getDefaultDeviceIndex()
  236949. {
  236950. return 0;
  236951. }
  236952. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  236953. {
  236954. jassert (callback != 0);
  236955. using namespace CoreMidiHelpers;
  236956. MidiInput* newInput = 0;
  236957. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfSources())
  236958. {
  236959. MIDIEndpointRef endPoint = MIDIGetSource (index);
  236960. if (endPoint != 0)
  236961. {
  236962. CFStringRef name;
  236963. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &name)))
  236964. {
  236965. MIDIClientRef client = getGlobalMidiClient();
  236966. if (client != 0)
  236967. {
  236968. MIDIPortRef port;
  236969. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  236970. if (CHECK_ERROR (MIDIInputPortCreate (client, name, midiInputProc, mpc, &port)))
  236971. {
  236972. if (CHECK_ERROR (MIDIPortConnectSource (port, endPoint, 0)))
  236973. {
  236974. mpc->portAndEndpoint = new MidiPortAndEndpoint (port, endPoint);
  236975. newInput = new MidiInput (getDevices() [index]);
  236976. mpc->input = newInput;
  236977. newInput->internal = mpc;
  236978. const ScopedLock sl (callbackLock);
  236979. activeCallbacks.add (mpc.release());
  236980. }
  236981. else
  236982. {
  236983. CHECK_ERROR (MIDIPortDispose (port));
  236984. }
  236985. }
  236986. }
  236987. }
  236988. CFRelease (name);
  236989. }
  236990. }
  236991. return newInput;
  236992. }
  236993. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  236994. {
  236995. jassert (callback != 0);
  236996. using namespace CoreMidiHelpers;
  236997. MidiInput* mi = 0;
  236998. MIDIClientRef client = getGlobalMidiClient();
  236999. if (client != 0)
  237000. {
  237001. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  237002. mpc->active = false;
  237003. MIDIEndpointRef endPoint;
  237004. CFStringRef name = PlatformUtilities::juceStringToCFString(deviceName);
  237005. if (CHECK_ERROR (MIDIDestinationCreate (client, name, midiInputProc, mpc, &endPoint)))
  237006. {
  237007. mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);
  237008. mi = new MidiInput (deviceName);
  237009. mpc->input = mi;
  237010. mi->internal = mpc;
  237011. const ScopedLock sl (callbackLock);
  237012. activeCallbacks.add (mpc.release());
  237013. }
  237014. CFRelease (name);
  237015. }
  237016. return mi;
  237017. }
  237018. MidiInput::MidiInput (const String& name_)
  237019. : name (name_)
  237020. {
  237021. }
  237022. MidiInput::~MidiInput()
  237023. {
  237024. delete static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal);
  237025. }
  237026. void MidiInput::start()
  237027. {
  237028. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  237029. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = true;
  237030. }
  237031. void MidiInput::stop()
  237032. {
  237033. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  237034. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = false;
  237035. }
  237036. #undef CHECK_ERROR
  237037. #else // Stubs for iOS...
  237038. MidiOutput::~MidiOutput() {}
  237039. void MidiOutput::reset() {}
  237040. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/) { return false; }
  237041. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/) {}
  237042. void MidiOutput::sendMessageNow (const MidiMessage& message) {}
  237043. const StringArray MidiOutput::getDevices() { return StringArray(); }
  237044. MidiOutput* MidiOutput::openDevice (int index) { return 0; }
  237045. const StringArray MidiInput::getDevices() { return StringArray(); }
  237046. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback) { return 0; }
  237047. #endif
  237048. #endif
  237049. /*** End of inlined file: juce_mac_CoreMidi.cpp ***/
  237050. /*** Start of inlined file: juce_mac_CameraDevice.mm ***/
  237051. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  237052. // compiled on its own).
  237053. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  237054. #if ! JUCE_QUICKTIME
  237055. #error "On the Mac, cameras use Quicktime, so if you turn on JUCE_USE_CAMERA, you also need to enable JUCE_QUICKTIME"
  237056. #endif
  237057. #define QTCaptureCallbackDelegate MakeObjCClassName(QTCaptureCallbackDelegate)
  237058. class QTCameraDeviceInteral;
  237059. END_JUCE_NAMESPACE
  237060. @interface QTCaptureCallbackDelegate : NSObject
  237061. {
  237062. @public
  237063. CameraDevice* owner;
  237064. QTCameraDeviceInteral* internal;
  237065. int64 firstPresentationTime;
  237066. int64 averageTimeOffset;
  237067. }
  237068. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner internalDev: (QTCameraDeviceInteral*) d;
  237069. - (void) dealloc;
  237070. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  237071. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  237072. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  237073. fromConnection: (QTCaptureConnection*) connection;
  237074. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  237075. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  237076. fromConnection: (QTCaptureConnection*) connection;
  237077. @end
  237078. BEGIN_JUCE_NAMESPACE
  237079. class QTCameraDeviceInteral
  237080. {
  237081. public:
  237082. QTCameraDeviceInteral (CameraDevice* owner, int index)
  237083. {
  237084. const ScopedAutoReleasePool pool;
  237085. session = [[QTCaptureSession alloc] init];
  237086. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  237087. device = (QTCaptureDevice*) [devs objectAtIndex: index];
  237088. input = 0;
  237089. audioInput = 0;
  237090. audioDevice = 0;
  237091. fileOutput = 0;
  237092. imageOutput = 0;
  237093. callbackDelegate = [[QTCaptureCallbackDelegate alloc] initWithOwner: owner
  237094. internalDev: this];
  237095. NSError* err = 0;
  237096. [device retain];
  237097. [device open: &err];
  237098. if (err == 0)
  237099. {
  237100. input = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  237101. audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  237102. [session addInput: input error: &err];
  237103. if (err == 0)
  237104. {
  237105. resetFile();
  237106. imageOutput = [[QTCaptureDecompressedVideoOutput alloc] init];
  237107. [imageOutput setDelegate: callbackDelegate];
  237108. if (err == 0)
  237109. {
  237110. [session startRunning];
  237111. return;
  237112. }
  237113. }
  237114. }
  237115. openingError = nsStringToJuce ([err description]);
  237116. DBG (openingError);
  237117. }
  237118. ~QTCameraDeviceInteral()
  237119. {
  237120. [session stopRunning];
  237121. [session removeOutput: imageOutput];
  237122. [session release];
  237123. [input release];
  237124. [device release];
  237125. [audioDevice release];
  237126. [audioInput release];
  237127. [fileOutput release];
  237128. [imageOutput release];
  237129. [callbackDelegate release];
  237130. }
  237131. void resetFile()
  237132. {
  237133. [fileOutput recordToOutputFileURL: nil];
  237134. [session removeOutput: fileOutput];
  237135. [fileOutput release];
  237136. fileOutput = [[QTCaptureMovieFileOutput alloc] init];
  237137. [session removeInput: audioInput];
  237138. [audioInput release];
  237139. audioInput = 0;
  237140. [audioDevice release];
  237141. audioDevice = 0;
  237142. [fileOutput setDelegate: callbackDelegate];
  237143. }
  237144. void addDefaultAudioInput()
  237145. {
  237146. NSError* err = nil;
  237147. audioDevice = [QTCaptureDevice defaultInputDeviceWithMediaType: QTMediaTypeSound];
  237148. if ([audioDevice open: &err])
  237149. [audioDevice retain];
  237150. else
  237151. audioDevice = nil;
  237152. if (audioDevice != 0)
  237153. {
  237154. audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: audioDevice];
  237155. [session addInput: audioInput error: &err];
  237156. }
  237157. }
  237158. void addListener (CameraDevice::Listener* listenerToAdd)
  237159. {
  237160. const ScopedLock sl (listenerLock);
  237161. if (listeners.size() == 0)
  237162. [session addOutput: imageOutput error: nil];
  237163. listeners.addIfNotAlreadyThere (listenerToAdd);
  237164. }
  237165. void removeListener (CameraDevice::Listener* listenerToRemove)
  237166. {
  237167. const ScopedLock sl (listenerLock);
  237168. listeners.removeValue (listenerToRemove);
  237169. if (listeners.size() == 0)
  237170. [session removeOutput: imageOutput];
  237171. }
  237172. void callListeners (CIImage* frame, int w, int h)
  237173. {
  237174. CoreGraphicsImage* cgImage = new CoreGraphicsImage (Image::ARGB, w, h, false);
  237175. Image image (cgImage);
  237176. CIContext* cic = [CIContext contextWithCGContext: cgImage->context options: nil];
  237177. [cic drawImage: frame inRect: CGRectMake (0, 0, w, h) fromRect: CGRectMake (0, 0, w, h)];
  237178. CGContextFlush (cgImage->context);
  237179. const ScopedLock sl (listenerLock);
  237180. for (int i = listeners.size(); --i >= 0;)
  237181. {
  237182. CameraDevice::Listener* const l = listeners[i];
  237183. if (l != 0)
  237184. l->imageReceived (image);
  237185. }
  237186. }
  237187. QTCaptureDevice* device;
  237188. QTCaptureDeviceInput* input;
  237189. QTCaptureDevice* audioDevice;
  237190. QTCaptureDeviceInput* audioInput;
  237191. QTCaptureSession* session;
  237192. QTCaptureMovieFileOutput* fileOutput;
  237193. QTCaptureDecompressedVideoOutput* imageOutput;
  237194. QTCaptureCallbackDelegate* callbackDelegate;
  237195. String openingError;
  237196. Array<CameraDevice::Listener*> listeners;
  237197. CriticalSection listenerLock;
  237198. };
  237199. END_JUCE_NAMESPACE
  237200. @implementation QTCaptureCallbackDelegate
  237201. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner_
  237202. internalDev: (QTCameraDeviceInteral*) d
  237203. {
  237204. [super init];
  237205. owner = owner_;
  237206. internal = d;
  237207. firstPresentationTime = 0;
  237208. averageTimeOffset = 0;
  237209. return self;
  237210. }
  237211. - (void) dealloc
  237212. {
  237213. [super dealloc];
  237214. }
  237215. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  237216. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  237217. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  237218. fromConnection: (QTCaptureConnection*) connection
  237219. {
  237220. if (internal->listeners.size() > 0)
  237221. {
  237222. const ScopedAutoReleasePool pool;
  237223. internal->callListeners ([CIImage imageWithCVImageBuffer: videoFrame],
  237224. CVPixelBufferGetWidth (videoFrame),
  237225. CVPixelBufferGetHeight (videoFrame));
  237226. }
  237227. }
  237228. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  237229. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  237230. fromConnection: (QTCaptureConnection*) connection
  237231. {
  237232. const Time now (Time::getCurrentTime());
  237233. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  237234. NSNumber* hosttime = (NSNumber*) [sampleBuffer attributeForKey: QTSampleBufferHostTimeAttribute];
  237235. #else
  237236. NSNumber* hosttime = (NSNumber*) [sampleBuffer attributeForKey: @"hostTime"];
  237237. #endif
  237238. int64 presentationTime = (hosttime != nil)
  237239. ? ((int64) AudioConvertHostTimeToNanos ([hosttime unsignedLongLongValue]) / 1000000 + 40)
  237240. : (([sampleBuffer presentationTime].timeValue * 1000) / [sampleBuffer presentationTime].timeScale + 50);
  237241. const int64 timeDiff = now.toMilliseconds() - presentationTime;
  237242. if (firstPresentationTime == 0)
  237243. {
  237244. firstPresentationTime = presentationTime;
  237245. averageTimeOffset = timeDiff;
  237246. }
  237247. else
  237248. {
  237249. averageTimeOffset = (averageTimeOffset * 120 + timeDiff * 8) / 128;
  237250. }
  237251. }
  237252. @end
  237253. BEGIN_JUCE_NAMESPACE
  237254. class QTCaptureViewerComp : public NSViewComponent
  237255. {
  237256. public:
  237257. QTCaptureViewerComp (CameraDevice* const cameraDevice, QTCameraDeviceInteral* const internal)
  237258. {
  237259. const ScopedAutoReleasePool pool;
  237260. captureView = [[QTCaptureView alloc] init];
  237261. [captureView setCaptureSession: internal->session];
  237262. setSize (640, 480); // xxx need to somehow get the movie size - how?
  237263. setView (captureView);
  237264. }
  237265. ~QTCaptureViewerComp()
  237266. {
  237267. setView (0);
  237268. [captureView setCaptureSession: nil];
  237269. [captureView release];
  237270. }
  237271. QTCaptureView* captureView;
  237272. };
  237273. CameraDevice::CameraDevice (const String& name_, int index)
  237274. : name (name_)
  237275. {
  237276. isRecording = false;
  237277. internal = new QTCameraDeviceInteral (this, index);
  237278. }
  237279. CameraDevice::~CameraDevice()
  237280. {
  237281. stopRecording();
  237282. delete static_cast <QTCameraDeviceInteral*> (internal);
  237283. internal = 0;
  237284. }
  237285. Component* CameraDevice::createViewerComponent()
  237286. {
  237287. return new QTCaptureViewerComp (this, static_cast <QTCameraDeviceInteral*> (internal));
  237288. }
  237289. const String CameraDevice::getFileExtension()
  237290. {
  237291. return ".mov";
  237292. }
  237293. void CameraDevice::startRecordingToFile (const File& file, int quality)
  237294. {
  237295. stopRecording();
  237296. QTCameraDeviceInteral* const d = static_cast <QTCameraDeviceInteral*> (internal);
  237297. d->callbackDelegate->firstPresentationTime = 0;
  237298. file.deleteFile();
  237299. // In some versions of QT (e.g. on 10.5), if you record video without audio, the speed comes
  237300. // out wrong, so we'll put some audio in there too..,
  237301. d->addDefaultAudioInput();
  237302. [d->session addOutput: d->fileOutput error: nil];
  237303. NSEnumerator* connectionEnumerator = [[d->fileOutput connections] objectEnumerator];
  237304. for (;;)
  237305. {
  237306. QTCaptureConnection* connection = [connectionEnumerator nextObject];
  237307. if (connection == 0)
  237308. break;
  237309. QTCompressionOptions* options = 0;
  237310. NSString* mediaType = [connection mediaType];
  237311. if ([mediaType isEqualToString: QTMediaTypeVideo])
  237312. options = [QTCompressionOptions compressionOptionsWithIdentifier:
  237313. quality >= 1 ? @"QTCompressionOptionsSD480SizeH264Video"
  237314. : @"QTCompressionOptions240SizeH264Video"];
  237315. else if ([mediaType isEqualToString: QTMediaTypeSound])
  237316. options = [QTCompressionOptions compressionOptionsWithIdentifier: @"QTCompressionOptionsHighQualityAACAudio"];
  237317. [d->fileOutput setCompressionOptions: options forConnection: connection];
  237318. }
  237319. [d->fileOutput recordToOutputFileURL: [NSURL fileURLWithPath: juceStringToNS (file.getFullPathName())]];
  237320. isRecording = true;
  237321. }
  237322. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  237323. {
  237324. QTCameraDeviceInteral* const d = static_cast <QTCameraDeviceInteral*> (internal);
  237325. if (d->callbackDelegate->firstPresentationTime != 0)
  237326. return Time (d->callbackDelegate->firstPresentationTime + d->callbackDelegate->averageTimeOffset);
  237327. return Time();
  237328. }
  237329. void CameraDevice::stopRecording()
  237330. {
  237331. if (isRecording)
  237332. {
  237333. static_cast <QTCameraDeviceInteral*> (internal)->resetFile();
  237334. isRecording = false;
  237335. }
  237336. }
  237337. void CameraDevice::addListener (Listener* listenerToAdd)
  237338. {
  237339. if (listenerToAdd != 0)
  237340. static_cast <QTCameraDeviceInteral*> (internal)->addListener (listenerToAdd);
  237341. }
  237342. void CameraDevice::removeListener (Listener* listenerToRemove)
  237343. {
  237344. if (listenerToRemove != 0)
  237345. static_cast <QTCameraDeviceInteral*> (internal)->removeListener (listenerToRemove);
  237346. }
  237347. const StringArray CameraDevice::getAvailableDevices()
  237348. {
  237349. const ScopedAutoReleasePool pool;
  237350. StringArray results;
  237351. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  237352. for (int i = 0; i < (int) [devs count]; ++i)
  237353. {
  237354. QTCaptureDevice* dev = (QTCaptureDevice*) [devs objectAtIndex: i];
  237355. results.add (nsStringToJuce ([dev localizedDisplayName]));
  237356. }
  237357. return results;
  237358. }
  237359. CameraDevice* CameraDevice::openDevice (int index,
  237360. int minWidth, int minHeight,
  237361. int maxWidth, int maxHeight)
  237362. {
  237363. ScopedPointer <CameraDevice> d (new CameraDevice (getAvailableDevices() [index], index));
  237364. if (static_cast <QTCameraDeviceInteral*> (d->internal)->openingError.isEmpty())
  237365. return d.release();
  237366. return 0;
  237367. }
  237368. #endif
  237369. /*** End of inlined file: juce_mac_CameraDevice.mm ***/
  237370. #endif
  237371. #endif
  237372. END_JUCE_NAMESPACE
  237373. #endif
  237374. /*** End of inlined file: juce_mac_NativeCode.mm ***/
  237375. #endif
  237376. #endif